

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


GO

PRINT N'Creating Function [sHrm].[fAttendanceWithEMPLeaveGet]...';


GO

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

--this function is created for mantisid -- 29177 
-- if Holiday is weekoff then display weekoff instead of Holiday in old function it is not working

--SELECT @rDepartmentId = ODM.Id FROM sHrm.tEmployeeMaster EM
--				   INNER JOIN sHrm.tEmployeeJobDetail EJD ON EM.Id = EJD.EmployeeId
--				   INNER JOIN sSetup.tDepartmentMaster ODM ON EJD.OrganizationDepartmentId = ODM.Id 
--				   WHERE EM.Id = @rEmployeeId

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



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

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



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

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

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

if @EmpFirstWeekOffRule = 1 
	BEGIN		
		if(@lWeekOff = @lWeekDay1)
			BEGIN	
				if(@rDateOfJoining  > @rAttendanceDate)
				BEGIN 
					 Set @rStatus = 'NA'
				END
				ELSE
				BEGIN
					 Set @rStatus = 'W'
				END
				RETURN @rStatus	
			 END 					
					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 Procedure [sActivity].[pEnrollmentGet]...';


GO
ALTER PROCEDURE [sActivity].[pEnrollmentGet]
	 
	 @rEventScheduleId int,
	 @rTitle nvarchar(100),
	 @rFromDate date,
	 @rToDate date,
	 @rBatchId int,
	 @rIsSearch bit
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	
BEGIN 
	 IF @rIsSearch = 1
		BEGIN
			SET @rTitle = sCommon.fSearchStringGet(@rTitle)
		END
	
	SELECT 
			ISNULL(EE.Id,0) AS Id,
			ES.Id as EventScheduleId,
			ES.Title,
			ES.FromDate,
			ES.ToDate,
		    ES.Remark EventRemark,
		    ES.IsCommonForAll,
		    ES.IsHoliday,
		    ES.IsEnrollment,
		    EE.Remark,
		    'Student' AS SourceType,
		    SA.Code as SourceCode,
			SA.Name as SourceName,
			SA.ClassName+'-'+SA.DivisionName AS ClassDept
  FROM 
            sStudent.vStudentAcademic SA
        INNER JOIN sActivity.tEventAssign EA ON EA.SourceId=SA.DivisionId AND EA.SourceTypeId=2005
        INNER JOIN sActivity.tEventSchedule ES ON ES.Id=EA.EventScheduleId
        INNER JOIN sActivity.tEventEnrollment EE ON EE.EventScheduleId=ES.Id AND EE.SourceId=SA.StudentId AND EE.SourceTypeId=2003
  WHERE 
  
		((ES.Id = @rEventScheduleId) OR (@rEventScheduleId = 0))
	AND	((ES.Title like @rTitle) OR (ISNULL(@rTitle,'') = ''))
	AND ((ES.FromDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
	AND ((ES.ToDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
	AND (ES.BatchId=@rBatchId)
	
	UNION ALL
	
	SELECT 
			ISNULL(EE.Id,0) AS Id,
			ES.Id as EventScheduleId,
			ES.Title,
			ES.FromDate,
			ES.ToDate,
		    ES.Remark AS EventRemark,
		    ES.IsCommonForAll,
		    ES.IsHoliday,
		    ES.IsEnrollment,
		    EE.Remark,
		    'Employee' AS SourceType,
		    EJD.EmployeeCode AS SourceCode,
			EJD.EmployeeName AS SourceName,
			EJD.DepartmentName AS ClassDept 
  FROM 
            sHrm.vExtEmployeeJobDetail EJD
		--mantis id 30734, comment the below line and add another inner join of tEventAssign table
        --INNER JOIN sActivity.tEventAssign EA ON EA.SourceId=EJD.OrganizationDepartmentId AND EA.SourceTypeId=2004
		INNER JOIN sActivity.tEventAssign EA ON ((EA.SourceId=EJD.OrganizationDepartmentId AND EA.SourceTypeId=2004) OR (EA.SourceId=EJD.EmployeeId AND EA.SourceTypeId=95))
        INNER JOIN sActivity.tEventSchedule ES ON ES.Id=EA.EventScheduleId
        INNER JOIN sActivity.tEventEnrollment EE ON EE.EventScheduleId=ES.Id AND EE.SourceId=EJD.EmployeeId AND EE.SourceTypeId=95
  WHERE 
  
		((ES.Id = @rEventScheduleId) OR (@rEventScheduleId = 0))
	AND	((ES.Title like @rTitle) OR (ISNULL(@rTitle,'') = ''))
	AND ((ES.FromDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
	AND ((ES.ToDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
	AND (ES.BatchId=@rBatchId)
	
END
GO
PRINT N'Altering Procedure [sAdmission].[pAdmissionInquiryGet]...';


GO

ALTER PROCEDURE [sAdmission].[pAdmissionInquiryGet]
	
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='',
	 @rId bigint = 0,
	 
	 @rForClassId int = 0,
	 @rClassId int = 0,
	 @rBatchId int = 0,
	 @rStatusId int =0,
	-- @rStatusId smallint,
	 @rInquiryStatusMasterId int = 0,
	 @rOrgId int,
	 @rFirstName nvarchar(100) = '',
	 @rLastName nvarchar(100) = '',
	 @rFromDate datetime=Null, -- MantisId : 0030699 changed '' to null
	 @rToDate datetime=Null, -- MantisId : 0030699 changed '' to null
	 @rForBatchId int = 0,
	 @rDepartmentId int = 0,
	 @rFromMeritMarks decimal(10,2) = 0,
	 @rToMeritMarks decimal(10,2)=0,
	 @rInquiryModeId smallint=0,
	 @rInquiryReferenceId int=0,
	 @rNumber bigint=0,
	 @rOrgGroupBatchId int = 0,
	 @rFollowUpdate datetime='',
	 @rIsTransportRequired int=0,
	 @rIsHostelRequired int=0,
	 @rOrderBy int =0,
	 @rIsGivenAdmissionForm int =0,
	 @rContactNo nvarchar(100)='',
	 @rAdmissionInquiryIdText int =0,
	 @rHandledBy nvarchar(100) = '',
	 @rGenderId int=0
	  --@rIsGivenAdmissionFormNew int =0
	 --@rIsSearch bit = 1
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	
	IF(@rIsGivenAdmissionForm=1)
		SET @rIsGivenAdmissionForm = 1
  	IF(@rIsGivenAdmissionForm=2)
		SET @rIsGivenAdmissionForm =0
	 
	 
	 SET @rToDate = DATEADD(d,1,@rToDate)
	 --IF @rIsSearch = 1
		BEGIN
			SET @rFirstName= sCommon.fSearchStringGet(@rFirstName)
			SET @rLastName= sCommon.fSearchStringGet(@rLastName)
			SET @rHandledBy= sCommon.fSearchStringGet(@rHandledBy)
			--SET @rContactNo= sCommon.fSearchStringGet(@rContactNo)
		END
	
	SELECT 
	
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			CASE WHEN @rAdmissionInquiryIdText = 0 THEN AI.Number ELSE @rAdmissionInquiryIdText END AS AdmissionInquiryIdText,
			 AI.Id
			,AI.ForBatchId
			,AI.ForClassId
			,AI.StatusId
			,ISNULL(SM.Id,0) AS InquiryStatusMasterId
			,ISNULL(AI.GenderId,0) AS GenderId
			,ISNULL(AI.InquiryModeId,0) AS InquiryModeId
			,ISNULL(IMM.Title,'') AS InquiryMode
			,ISNULL(AI.InquiryReferenceId,0) AS InquiryReferenceId		
		    ,ISNULL(AI.AdmissionCategoryId,0) AS AdmissionCategoryId
		    ,AI.OrgId
		    ,ISNULL(AI.Number,0) AS InquiryNumber
		    ,ISNULL(AI.InquiryDate,'') AS AdmissionInquiryDate 		    
		    ,OM.DisplayTitle AS OrgName
		    ,BM.Title AS ForBatch
			,ISNULL(CM.Title,'') AS ClassName	
			,AI.FirstName
			,AI.MiddleName
			,AI.LastName
			,[sStudent].[fStudentNameGet](AI.FirstName , ISNULL(AI.MiddleName,'') , AI.LastName,OM.StudentNameFormatId ) AS StudentName
			,AI.LastName +' ' +AI.FirstName+' '+AI.MiddleName as Name				
			,ISNULL(AI.DateOfBirth,'') As DateOfBirth
			,ISNULL(GM.Title,'') As Gender			
			,AI.ContactNo
			,AI.ContactEmail			
			,AI.StreetOne
			,AI.StreetTwo
			,AI.StreetThree
			,AI.Country
			,AI.State
			,AI.City
			,AI.ZipCode
			,ISNULL(AI.Remark,'') AS Remark						
		    ,ISNULL(AI.PreviousSchool,'') as PreviousSchool			
			,ISNULL(AI.MeritMarks,0) AS MeritMarks
			,ISNULL(AI.MeritGrade,'') AS MeritGrade
			,ISNULL(AI.MeritMarksBreakup,'') AS MeritMarksBreakup
			,SM.Title as StatusName	
			--,cast(replace(FollowupDate,'/','-') as date) As FollowupDate
			,ISNULL(AI.FollowupDate,'') As FollowupDate
			,ISNULL(AI.FollowupRemark,'') As FollowupRemark			
			,ISNULL(IRM.Title ,'') AS InquiryReference	
			,ISNULL(SCM.Title,'') AS AdmissionCategory		
			,ISNULL(AI.HandledBy,'') AS HandledBy
			,ISNULL(AI.CreatedDateTime,'') As CreatedDateTime
			,ISNULL(AI.StudentId,0) AS StudentId,
			ISNULL(AI.CastCategoryId,0) AS CastCategoryId,
			ISNULL(AI.IsTransportRequired,0) AS IsTransportRequired,
			ISNULL(AI.IsHostelRequired,0) AS IsHostelRequired,
			CONVERT(int,ISNULL(AI.IsGivenAdmissionForm,0)) AS IsGivenAdmissionForm,
			--ISNULL(AI.IsGivenAdmissionForm,0) AS IsGivenAdmissionForm,
			ISNULL(SM.HighlightColor,'') AS HighlightColor,
			ISNULL(SA.PreviousStandard,'') As PreviousStandard,
			AI.AlternateContactNo,
			AI.AlternateContactEmail
			,CASE WHEN AI.FollowupDate IS NULL THEN '' ELSE  CONVERT(VARCHAR(10), AI.FollowupDate, 103) END AS FollowupDateString,
			ISNULL(AIC.AgeCutOffDate,'') AS AgeCutOffDate,
			ISNULL(AI.MotherName,'') AS MotherName,
			CASE WHEN AI.DataEntryModeId = 561 THEN 'Online' ELSE 'Offline' END DataEntryMode 
			,ISNULL(AI.MinorityStatusId,0) As MinorityStatusId
		    ,ISNULL(AI.LiveWithId,0) AS LiveWithId
			,ISNULL(AI.AdhaarNumber,'') AS AdhaarNumber 
			,ISNULL(AI.BloodGroupId,0) AS BloodGroupId
			 ,ISNULL(AI.FatherName,'') AS FatherName
			,ISNULL(AI.FatherOccupation,'') AS FatherOccupation 
			,ISNULL(AI.FatherIncome,0) AS FatherIncome 
			,ISNULL(AI.FatherContactNo,'') AS FatherContactNo
			,ISNULL(AI.FatherMail,'') AS FatherMail
			,ISNULL(AI.FatherQualification,'') AS FatherQualification
			,ISNULL(AI.MotherOccupation,'') As MotherOccupation
			,ISNULL(AI.MotherIncome,0) AS MotherIncome
			,ISNULL(AI.MotherContactNo,'') AS MotherContactNo 
			,ISNULL(AI.MotherMail,'') AS MotherMail 
			,ISNULL(AI.MotherQualification,'') AS  MotherQualification
			,ISNULL(AI.Stream,'') AS Stream
			,ISNULL(AI.Board,'') AS Board
			,ISNULL(CCM.Title,'') AS CasteCategory
			,ISNULL(AI.InquiryReferenceRemark,'') AS InquiryReferenceRemark,
			ISNULL(AI.WhatsAppContactNo,'') AS WhatsAppContactNo

  FROM 
            sAdmission.tAdmissionInquiry AI
            LEFT JOIN sAdmission.tInquiryModeMaster IMM ON IMM.Id = AI.InquiryModeId
           --INNER JOIN sCommon.tStatusMaster SM ON SM.Id=AI.StatusId AND StatusTypeId=104
            INNER JOIN sAdmission.tInquiryStatusMaster SM ON SM.Id=AI.InquiryStatusId 
			INNER JOIN sSetup.tClassMaster CM ON CM.Id=AI.ForClassId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=AI.OrgId
			INNER JOIN sSetup.tBatchMaster BM ON AI.ForBatchId = BM.Id
			LEFT JOIN sAdmission.tInquiryReferenceMaster IRM ON IRM.Id=AI.InquiryReferenceId
			LEFT JOIN sStudent.tAdmissionCategoryMaster SCM ON SCM.Id=AI.AdmissionCategoryId
			LEFT JOIN sCommon.tGenderMaster GM ON GM.Id=AI.GenderId  
			LEFT JOIN sStudent.tStudentAdmission SA oN SA.StudentId=AI.StudentID
			LEFT JOIN sAdmission.tAdmissionInquiryCriteria AIC ON AIC.ClassId=AI.ForClassId AND AIC.BatchId=AI.ForBatchId 
			LEFT JOIN  scommon.tCastCategoryMaster CCM on CCM.Id = AI.CastCategoryId
  WHERE  
      ((AI.Id = @rId) OR (@rId = 0))
      AND ((AI.FirstName like @rFirstName) OR (@rFirstName=''))
      AND ((AI.LastName like @rLastName) OR (@rLastName=''))
      AND ((AI.InquiryDate>= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
      AND ((AI.InquiryDate < @rToDate) OR (ISNULL(@rToDate,'')=''))
	  AND ((AI.ForClassId=@rForClassId) OR (@rForClassId=0)) 
	  --AND ((AI.StatusId=@rStatusId) OR (@rStatusId=0))
	  AND ((SM.Id=@rInquiryStatusMasterId) OR (@rInquiryStatusMasterId=0))
	  AND (AI.OrgId=@rOrgId OR @rOrgId=0)
	  AND ((AI.ForBatchId=@rForBatchId) OR (@rForBatchId=0))
	  AND ((CM.DepartmentId=@rDepartmentId) or (@rDepartmentId = 0))
	  AND ((AI.MeritMarks >= @rFromMeritMarks) OR (@rFromMeritMarks=0))
	  AND ((AI.MeritMarks <= @rToMeritMarks) OR (@rToMeritMarks=0))
	  AND ((AI.InquiryModeId=@rInquiryModeId) OR (@rInquiryModeId=0))
	  AND ((AI.InquiryReferenceId=@rInquiryReferenceId) OR (@rInquiryReferenceId=0))
	  AND ((AI.Number=@rNumber) OR (@rNumber=0))
	  AND (BM.OrgGroupBatchid=@rOrgGroupBatchId OR @rOrgGroupBatchId=0)
	  AND ((AI.FollowUpdate=@rFollowupdate) OR (ISNULL(@rFollowUpdate,'')=''))

	AND ((ISNULL(AI.IsGivenAdmissionForm,0)=@rIsGivenAdmissionForm) OR (@rIsGivenAdmissionForm=-1))
	  --AND ((ISNULL(AI.IsGivenAdmissionForm,0)=@rIsGivenAdmissionForm) OR (@rIsGivenAdmissionForm=0)OR (@rIsGivenAdmissionForm=-1))

	  AND (AI.IsTransportRequired = CASE @rIsTransportRequired
                              WHEN 0 THEN ISNULL(AI.IsTransportRequired,0)
                              WHEN 2 THEN 0
                              WHEN 1 THEN 1
                         END)
	  
	  AND (AI.IsHostelRequired = CASE @rIsHostelRequired
                              WHEN 0 THEN ISNULL(AI.IsHostelRequired,0)
                              WHEN 2 THEN 0
                              WHEN 1 THEN 1
                         END)
	 --AND ((ISNULL(AI.IsGivenAdmissionForm,0)=@rIsGivenAdmissionForm) OR (@rIsGivenAdmissionForm=-1))
      --AND (AI.IsGivenAdmissionForm = CASE @rIsGivenAdmissionForm WHEN 0 THEN ISNULL(AI.IsGivenAdmissionForm,0) WHEN 2 THEN 1 WHEN 1 THEN 0 END)
	  AND ((AI.ContactNo = @rContactNo) OR (ISNULL(@rContactNo, '')=''))
	 AND ((AI.HandledBy like @rHandledBy) OR (ISNULL(@rHandledBy, '')=''))
	 AND ((GM.Id = @rGenderId) OR (@rGenderId = 0))
	  --AND ((AI.IsTransportRequired=@rIsTransportRequired) OR (@rIsTransportRequired=0))	   
	    --AND ((AI.IsHostelRequired =@rIsHostelRequired) OR (@rIsHostelRequired=0))
	  Order by Case @rOrderBy When 1 then AI.MeritMarks END desc ,
			    Case @rOrderBy when 0 then AI.Number Else 
			    AI.Number END desc  
			    
END
GO
PRINT N'Altering Procedure [sAlert].[pAbsentStudentContinueGet]...';


GO

ALTER PROCEDURE [sAlert].[pAbsentStudentContinueGet]
	 	 
	 	 @rBatchId int,
	 	 @rClassId int,
	 	 @rDivisionId int,
	 	 @rOrgId int,
	 	 @rTemplate nvarchar(max),
	 	 @rAttendanceTypeId tinyint,
	 	 @rSubjectId int,
	 	 @rFromDate date,
	 	 @rToDate date,
	 	 @rIsPresent bit,
	 	 @rMailSubject nvarchar(500)='',
		 @rDays int
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

CREATE TABLE #tmpData
(
AcademicId bigint,
Code nvarchar(20),
Name nvarchar(300),
MobileNo nvarchar(50),
EmailId nvarchar(50),
StudentContactNo nvarchar(50),
StudentEmail nvarchar(50),
FatherContactNo nvarchar(50),
FatherMail nvarchar(50),
MotherContactNo nvarchar(50),
MotherMail nvarchar(50),
MsgText nvarchar(max),
Subject nvarchar(max),
SourceId bigint,
SourceTypeId int,
OrgId int,
OrgGroupId int,
ReceiverSourceId bigint,
ReceiverSourceTypeId int,
Class nvarchar(100),
Division nvarchar(100),
AbsentDates date,
AbsentReason nvarchar(100),
PresentDates date,
WhatsAppContactNo nvarchar(20),
ConsecDates date
)

INSERT INTO #tmpData
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,
			--CASE WHEN 0=0 THEN
			--replace (replace (
			--replace(replace(replace(@rTemplate,'[Name]',SC.Name),
			--'[Class]',SC.ClassName),
			--'[Division]',SC.DivisionName),
			--'[AbsentDates]',SR.AttendanceDate),
			--'[AbsentReason]',ISNULL(AR.Title,''))
			--ELSE
			--replace (
			--replace(replace(replace(@rTemplate,'[Name]',SC.Name),
			--'[Class]',SC.ClassName),
			--'[Division]',SC.DivisionName),
			--'[PresentDates]',SR.AttendanceDate)
			--END
			-- AS MsgText,
			'' AS MsgText,
			@rMailSubject AS Subject,
			SC.AcademicId AS SourceId,
			2001 AS SourceTypeId,
			SC.OrgId,
			SC.OrgGroupId,
			SC.AcademicId AS ReceiverSourceId,
			2001 AS ReceiverSourceTypeId,
			SC.ClassName AS Class,
			SC.DivisionName AS Division,
			SR.AttendanceDate AS AbsentDates,
			ISNULL(AR.Title,'') AS AbsentReason,
			SR.AttendanceDate AS PresentDates,
			SC.WhatsAppContactNo,
			 (
            select min(b.AttendanceDate) from sAttendance.tStudentRegister b where SR.AcademicId = b.AcademicId 
            and b.AttendanceDate >= SR.AttendanceDate
            and not exists ( 
                select 1 from sAttendance.tStudentRegister c where c.AcademicId = b.AcademicId and dateadd( dd, 1, b.AttendanceDate) = c.AttendanceDate  
            )
            ) ConsecDates

	From 
		sStudent.vStudentCommunication SC
	INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=SC.AcademicId
	LEFT JOIN sAttendance.tAbsentReasonMaster AR ON SR.AbsentReasonId = AR.Id
			
	WHERE
			((SC.ClassId=@rClassId) OR (@rClassId=0))
		AND ((SC.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		AND (SC.OrgId=@rOrgId)
		AND (SC.BatchId=@rBatchId)
		AND (SC.StatusId=1)
		AND ((SR.AttendanceTypeId=@rAttendanceTypeId) OR (@rAttendanceTypeId=0))
			AND ((SR.SubjectId=@rSubjectId) OR (@rSubjectId=0))
			AND ((SR.AttendanceDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
			AND ((SR.AttendanceDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
			AND (SR.IsPresent = @rIsPresent)
		AND	SC.AcademicId NOT IN (SELECT AcademicId FROM sAttendance.tStudentLeaveRequest WHERE LeaveFromDate = @rFromDate AND LeaveToDate=@rToDate)
		AND SC.IsBlockAttendanceAlert=0 AND SC.IsBlockAllAlert=0
   ORDER BY SR.AcademicId,SR.AttendanceDate asc
   --Select * from #tmpData ORDER BY AcademicId

--Select * from #tmpData

CREATE TABLE #tmp
(
AcademicId bigint ,
ConsecDates date ,
AbsentDays nvarchar(max),
FullAbsentDate nvarchar(max)
)
INSERT INTO #tmp
SELECT AcademicId,ConsecDates,
isnull(STUFF((SELECT ',' + CONVERT(nvarchar,DATEPART(day,d.AbsentDates)) from #tmpData d  
WHERE d.AcademicId=a.AcademicId AND d.ConsecDates = a.ConsecDates FOR XML PATH('')), 1, 1, ''),''),
/**Added new field  for mantis : 29178**/
isnull(STUFF((SELECT ', ' + CONVERT(nvarchar, d.AbsentDates,103) from #tmpData d  
WHERE d.AcademicId=a.AcademicId AND d.ConsecDates = a.ConsecDates FOR XML PATH('')), 1, 1, ''),'')
FROM #tmpData a

CREATE TABLE #Finaltmp
(
AcademicId bigint ,
ConsecDates date ,
AbsentDays nvarchar(max),
FullAbsentDate nvarchar(max)
)
INSERT INTO #Finaltmp
Select * from #tmp GROUP BY AcademicId,ConsecDates,AbsentDays,FullAbsentDate having COUNT(ConsecDates) >= @rDays
ORDER BY AcademicId,ConsecDates asc



ALTER TABLE #tmpData
DROP COLUMN AbsentDates,
 AbsentReason,
PresentDates;

--Select * from #Finaltmp
--Select * from #tmpData
Select Distinct
			tmp.AcademicId,
			tmp.Code,
			tmp.Name,
			tmp.MobileNo,	
			tmp.EmailId,
			tmp.StudentContactNo,
			tmp.StudentEmail,
			tmp.FatherContactNo,
			tmp.FatherMail,
			tmp.MotherContactNo,
			tmp.MotherMail,
			CASE WHEN 0=0 THEN
			
			replace(replace(replace(replace(replace(@rTemplate,'[Name]',tmp.Name),
			'[Class]',tmp.Class),
			'[Division]',tmp.Division),
			'[AbsentDates]',isnull(STUFF((SELECT ',' + f.AbsentDays from #Finaltmp f  
			WHERE f.AcademicId=tmp.AcademicId FOR XML PATH('')), 1, 1, ''),'')),
			'[FullAbsentDate]',isnull(STUFF((SELECT ',' + f.FullAbsentDate from #Finaltmp f  
			WHERE f.AcademicId=tmp.AcademicId FOR XML PATH('')), 1, 1, ''),'')) --Added new field  for mantis : 29178
			
			--'[AbsentDates]',SR.AttendanceDate),
			--'[AbsentReason]',ISNULL(AR.Title,''))
			ELSE
			replace(replace (replace(
			replace(replace(@rTemplate,'[Name]',tmp.Name),
			'[Class]',tmp.Class),
			'[Division]',tmp.Division),
			'[AbsentDates]',isnull(STUFF((SELECT ',' + f.AbsentDays from #Finaltmp f  
			WHERE f.AcademicId=tmp.AcademicId FOR XML PATH('')), 1, 1, ''),'')),
			'[FullAbsentDate]',isnull(STUFF((SELECT ',' + f.FullAbsentDate from #Finaltmp f  
			WHERE f.AcademicId=tmp.AcademicId FOR XML PATH('')), 1, 1, ''),'') --Added new field  for mantis : 29178
			)
			--'[PresentDates]',SR.AttendanceDate)
			END
			 AS MsgText,
			tmp.Subject,
			tmp.SourceId,
			tmp.SourceTypeId,
			tmp.OrgId,
			tmp.OrgGroupId,
			tmp.ReceiverSourceId,
			tmp.ReceiverSourceTypeId,
			tmp.Class,
			tmp.Division,
			--tmp.AbsentDates,
			--tmp.AbsentReason,
			--tmp.PresentDates,
			tmp.WhatsAppContactNo,
			--finaltmp.ConsecDates,
			--finaltmp.AbsentDays
			isnull(STUFF((SELECT ',' + f.AbsentDays from #Finaltmp f  
			WHERE f.AcademicId=tmp.AcademicId FOR XML PATH('')), 1, 1, ''),'')AS AbsentDays,
			isnull(STUFF((SELECT ',' + f.FullAbsentDate from #Finaltmp f  
			WHERE f.AcademicId=tmp.AcademicId FOR XML PATH('')), 1, 1, ''),'')AS FullAbsentDate --Added new field  for mantis : 29178


	From 
		#tmpData tmp
	INNER JOIN #Finaltmp finaltmp ON tmp.AcademicId = finaltmp.AcademicId AND tmp.ConsecDates =finaltmp.ConsecDates
	
DROP TABLE #tmpData
DROP TABLE #tmp
DROP TABLE #Finaltmp
END
GO
PRINT N'Altering Procedure [sAlert].[pEmployeeBirthdayWishSchedulerGet]...';


GO
 
ALTER PROCEDURE [sAlert].[pEmployeeBirthdayWishSchedulerGet]
	 	 
	 	 @rOrgId smallint,
	 	 @rTemplate nvarchar(max),
	 	 @rMailSubject nvarchar(100)
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	
	Select 
			EC.MobileNumber AS MobileNo,	
			--EC.PersonalEmail AS EmailId,			
			(CASE WHEN ISNULL(EC.PersonalEmail,'')='' THEN EC.CompanyEmail
			ELSE EC.PersonalEmail END) AS EmailId,
			replace(replace(@rTemplate,'[Name]',EC.EmployeeName),'[SchoolName]',OM.Title)
			AS MsgText,
			@rMailSubject AS Subject,
			OM.OrgGroupId AS OrgGroupId,
			OM.Id AS OrgId,
			EC.EmployeeId AS SourceId,
			95 AS SourceTypeId,
			EC.EmployeeId AS ReceiverSourceId,
			95 AS ReceiverSourceTypeId,
			EC.EmployeeName AS [Name],
			OM.Title AS SchoolName,
			EC.WhatsAppContactNo AS WhatsAppContactNo,
			'' AS AttachMent
		
	From 
		sHrm.vEmployeeCommunication EC
		INNER JOIN sSetup.tOrganizationMaster OM ON EC.OrgId = OM.Id
	WHERE
			(DAY(EC.DateOfBirth) = DAY(sCommon.fGetDate()))
		AND (MONTH(EC.DateOfBirth) = MONTH(sCommon.fGetDate()))
		AND (EC.StatusId=7)
		AND (EC.OrgId=@rOrgId)
END
GO
PRINT N'Altering Procedure [sAlert].[pStudentBirthdayWishSchedulerGet]...';


GO
 
ALTER PROCEDURE [sAlert].[pStudentBirthdayWishSchedulerGet]
	 	 
	 	 @rOrgId smallint,
	 	 @rTemplate nvarchar(max),
	 	 @rMailSubject nvarchar(100)
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	
	Select 
 
			SC.ParentContactNo AS MobileNo,	
			SC.ParentEmail AS EmailId,
			replace(replace(@rTemplate,'[Name]',SC.Name),'[SchoolName]',OM.Title)
			 AS MsgText,
			@rMailSubject AS Subject,
			OM.OrgGroupId AS OrgGroupId,
			OM.Id AS OrgId,
			SC.StudentId AS SourceId,
			2003 AS SourceTypeId,
			SC.StudentId AS ReceiverSourceId,
			2003 AS ReceiverSourceTypeId,
			SC.Name AS [Name],
			OM.Title AS SchoolName,
			SC.WhatsAppContactNo AS WhatsAppContactNo,
			'' AS AttachMent
			
	From 
		sStudent.vStudentCommunication SC
		INNER JOIN sSetup.tOrganizationMaster OM ON SC.OrgId = OM.Id
	WHERE
			(DAY(SC.DateOfBirth) = DAY(sCommon.fGetDate()))
		AND (MONTH(SC.DateOfBirth) = MONTH(sCommon.fGetDate()))
		AND (SC.StatusId=1)
		AND (SC.OrgId=@rOrgId)
		AND SC.IsActiveBatch = 1 AND SC.IsBlockAllAlert=0
END
GO
PRINT N'Altering Procedure [sAppraisal].[pConductAdd]...';


GO

/******************************
** Name:  [sAppraisal].[pConductTypeMasterAdd]
** Desc:  Create and Update Data in Loan ConductTypeMaster
** Auth:  Savan Vaghela
** Date:  08-March-2017
** Page:  /Pages/Hrm/Appraisal/ConductTypeMaster.aspx
************************************************************
** Change History
************************************************************
** PR      Date                Author            Description 
**
** 1    08-March-2017      Savan Vaghela       
************************************************************/
--[sAppraisal].[pConductAdd]
ALTER PROCEDURE [sAppraisal].[pConductAdd]
	    @rId BIGINT,
		@rConductDate DATETIME,
		@rEmployeeId BIGINT,
		@rConductTypeId INT,
		@rBatchId int,
		@rTitle nvarchar(100),
		@rRemark nvarchar(400),
		@rOrgId SmallINT,
		@rOrgGroupId SmallINT,
		@rCreatedUserId BIGINT		       
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
		--IF(@rId = 0)	
		--	BEGIN
		--		IF Exists(SELECT Id FROM [sAppraisal].[tConductTypeMaster]  WHERE Title=@rTitle AND OrgGroupId=@rOrgGroupId )
		--			BEGIN
		--				SELECT -102 as Result
		--				RETURN
		--			END 
		--	END
		
		--ELSE
		--	BEGIN
		--		IF  Exists(SELECT Id FROM [sAppraisal].[tConductTypeMaster]  WHERE Title=@rTitle AND OrgGroupId=@rOrgGroupId AND Id<>@rId )
		--			BEGIN
		--				SELECT -102 as Result
		--				RETURN
		--			END
		--	END
	
		BEGIN TRANSACTION	
		DECLARE @lNextNumber BIGINT 
	
		IF(@rId = 0)	
			BEGIN
				EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sAppraisal.tConduct', 0, 1, 1,@outNextNumber = @lNextNumber output
				INSERT INTO [sAppraisal].[tConduct]
				(
					Id,
					ConductDate,
					EmployeeId,
					ConductTypeId,
					Title,
					Remark,
					BatchId,
					CreatedUserId,
					CreatedDateTime
					
				)
				VALUES
				(
					@lNextNumber,
					@rConductDate,
					@rEmployeeId,
					@rConductTypeId,
					@rTitle,
					@rRemark,
					@rBatchId,
					@rCreatedUserId,
					sCommon.fGetDate()
					
				)
				SELECT 1 AS Result
			END	 
		ELSE
			BEGIN
			SET @lNextNumber = @rId
				UPDATE  [sAppraisal].[tConduct]
				SET
					Title=@rTitle,
					Remark=@rRemark,
					ConductDate=@rConductDate, 
					ConductTypeId = @rConductTypeId -- Added field ConductTypeId for mantis 30032 
					
				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 [sAssessment].[pRptExamAdmitcard]...';


GO
ALTER PROCEDURE [sAssessment].[pRptExamAdmitcard]
	  
	  @rBatchId int,
	  @rClassId int,
	  @rDivisionId int,
	 -- @rExamId int=0,
	  @rExamSubGroupId int=0,
	  @rCode nvarchar(20),
	  @rFromRollNo int,
	  @rToRollNo int,
	  @rDepartmentId int,
	  @rSubjectId int=0,
	  @rStatusId int=0,
	  @rClassStatusId int=0
	  
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON 
BEGIN 	
	SELECT 		
	       	ESGM.Title AS ExamName,
	       	ISNULL(ED.DisplayOrder,0) as DisplayOrder,
	        ISNULL(ED.ExamDate,sCommon.fGetDate()) as ExamDate,
	        ISNULL(ED.ExamTime,'') as ExamTime,
	        V.SubjectName AS SubjectName,
	        CM.DisplayTitle+' / '+DM.DisplayTitle AS ClassDivision,
	         CM.DisplayTitle AS ClassName,
	         CM.Id As ClassId,
	         DM.Id AS DiVisionId,
	        V.ClassSubjectId AS ClassSubjectId,
	        SA.Name,
	        SA.RollNo,
	        SA.Code,
	        SF.FatherName,
	        So.DateOfBirth,
	        GM.Title AS Gender,
	        EM.Remark1,
	        EM.Remark2,
	        EM.Remark3,
	        SA.AcademicId,
	        SI.StudentPhoto,
	        SF.MotherName,
	        SR. ExamCenter,
	        SR.ExamSeatNo,
	        V.SubjectCode AS SubjectCode,
		
	         
		(CASE EM.IsDisplayImageHeader WHEN 1 THEN
			OI.CertificateHeaderA4 
			ELSE NULL END)AS  MarksheetHeaderA4 ,
			ISNULL(EM.IsDisplayImageHeader,0) AS IsImageHeader,
			EM.IsOnPrePrinted ,
	        --EM.Id As ExamId,
			EM.IsDisplayPhoto,
			SR.ExamBlock,
			EI.EmployeeSign,
			EM.TeacherSignCaption,
			EM.PrincipalSignCaption,
			EM.ParentSignCaption,
			ISNULL(EM.DisplayTitle,'') AS DisplayTitle ,
			ISNULL(ED.ExamTopic,'') AS ExamTopic,
			ISNULL(ED.ExamLanguage,'') AS ExamLanguage,
			ISNULL(SA.OrganizationName,'') AS OrganizationName,
			ISNULL(SA.SUId,'') AS SUId ,
			EM.IsDisplayPrincipalSign AS IsDisplayPrincipalSign,
			ISNULL(SO.UIDNumber,'') AS UId ,
			CSM.Title As CasteCategory ,
		    ISNULL(SO.AdhaarNumber,'') AS AdhaarNumber,
			ISNULL(SO.FamilySubCast,'') AS FamilySubCast,
			DM.DisplayTitle AS DivisionName   -- 30455

			FROM
			sStudent.vStudentAcademic SA 
			INNER JOIN sSetup.tClassMaster CM ON SA.ClassId=CM.Id 
			INNER JOIN sSetup.tDivisionMaster DM ON DM.ClassId=CM.Id AND SA.DivisionId=DM.Id
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id  ANd Em.BatchId=SA.BatchId 
			INNER JOIN sAssessment.tExamSubGroupMaster	ESGM ON ESGM.Id = EM.ExamSubGroupId
			INNER JOIN sAssessment.tExamGroupMaster EGM ON EGM.Id=ESGM.ExamGroupId
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			LEFT JOIN sSetup.vClassSubject V ON V.ClassSubjectId = Ed.ClassSubjectId  
			LEFT JOIN sAssessment.tOptionalSubject OS on OS.AcademicId=SA.AcademicId and OS.ClassSubjectId=V.ClassSubjectId
			LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId=SA.StudentId  
			LEFT JOIN sStudent.tStudentOther SO ON So.StudentId=SA.StudentId  
			LEFT JOIN sCommon.tGenderMaster GM ON GM.Id=So.GenderId   
			LEFT JOIN  sStudent.tStudentImages SI ON SI.StudentId=SA.StudentId 
			LEFT JOIN sAssessment.tStudentRemark SR ON SR.ExamId=EM.Id AND SR.AcademicId=SA.AcademicId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=SA.OrgId
			LEFT JOIN sSetup.tOrgImages OI ON OI.Orgid = OM.Id
			LEFT JOIN sHrm.tEmployeeImages EI ON EI.EmployeeId = DM.InchargeEmployeeId
			LEFT JOIN sCommon.tCastCategoryMaster CSM ON CSM.Id=SO.CastCategoryId
	WHERE 
			SA.BatchId = @rBatchId 
		 AND (SA.ClassId=@rClassId OR @rClassId=0) 
		 AND (SA.DivisionId=@rDivisionId OR @rDivisionId=0)
		 AND ((SA.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
		 AND ((SA.RollNo <= @rToRollNo) OR (@rToRollNo=0))
		 AND ((ESGM.Id = @rExamSubGroupId) OR (@rExamSubGroupId = 0))	
	     AND ((SA.Code=@rCode) OR (@rCode=''))
	     AND (SA.DepartmentId=@rDepartmentId OR @rDepartmentId=0) 
	     AND (V.SubjectId=@rSubjectId OR @rSubjectId=0) 
	    AND ((V.IsOptional = 1 AND  isnull(OS.AcademicId,0) <> 0) OR (V.IsOptional = 0))
		AND ((SA.StatusId=@rStatusId) OR (@rStatusId = 0))
		AND (SA.ClassStatusId=@rClassStatusId OR @rClassStatusId=0)
	
	Order by ED.ExamDate
END
GO
PRINT N'Altering Procedure [sCertificate].[pRptBonafiedCertificateGet]...';


GO
ALTER PROCEDURE [sCertificate].[pRptBonafiedCertificateGet]
	 
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 @rOrgId smallint,
	 @rBatchId int,
	 @rFromNo nvarchar(20)='',
	 @rToNo nvarchar(20)='',
	 @rNumber nvarchar(20)='',
	 @rClassId int=0,
	 @rDivisionId int=0,
	 @rFromDate date='',
     @rToDate date='',
     @rCode nvarchar(20)='',
     @rName nvarchar(20)='',
     @rOrgGroupBatchId int
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 

DECLARE @lIsShowPhoto bit = 0
DECLARE @lIsOnPrePrinted bit = 0
DECLARE @lIsDisplayReligion bit=0
DECLARE @lIsDisplayImageHeader bit=0

DECLARE @lConfigValue nvarchar(50)
Declare @lIDConfigValue nvarchar(50)='',@lOrgGroupId int=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
	
	SELECT @lConfigValue = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 177 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 @lOrgGroupId = OrgGroupId From  sSetup.tOrganizationMaster Where Id = @rOrgId
	SELECT @lIDConfigValue =ItemValue From sConfig.tConfigurationSetup
	WHERE ConfigurationId = 236 AND SourceId = @lOrgGroupId
	--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	
	
	
	
	SELECT 	
			@rBuilder1 AS Builder1,
		    @rBuilder2 AS Builder2,
			B.Id,
			B.Number,
			B.AcademicId,
			SM.Code,
			--SM.FirstName+' '+SM.MiddleName+' '+SM.LastName AS Name,
			   [sStudent].[fStudentNameGet](SM.FirstName , SM.MiddleName, SM.LastName,OM.StudentNameFormatId ) AS Name,
			CM.DisplayTitle+' - '+DM.DisplayTitle AS Class,
			BM.Title AS Batch,
			SM.FirstName,
			SM.MiddleName,
			SM.LastName,
			SO.DateOfBirth,
			ISNULL(SO.BirthDateInWord,'') AS DOBInWords,
			ISNULL(SO.BirthPlace,'') AS BirthPlace,
			ISNULL(SO.BirthTaluka,'') AS Taluka,
			ISNULL(SO.BirthDistrict,'')	AS District,		
			B.BonafideDate,
			ISNULL(SO.FamilyCast,'') AS Caste,
			ISNULL(SO.FamilySubCast,'') AS SubCaste,
			ISNULL(OM.CityName,'') AS City,
			ISNULL(OM.StateName,'') AS CityState,
			SO.GenderId,
			SI.StudentPhoto,
			OM.OrgLogo,
			OM.Title AS OrgTitle,
			--OM.StreetOne+' '+OM.StreetTwo+' '+OM.StreetThree AS OrgAddress,
			--OM.PhoneNo,
			SM.StatusId,
			A.RollNo,
			DM.OrderIndex AS DivisionOrder,
			ATM.Title AS AffiliationType,
			OM.ReportOrgTitle,
			OM.SmallAddress1,
			OM.SmallAddress2,
			OM.RegistrationDetail,
			ISNULL(RM.Title,'') AS ReligionName,
			@lIsShowPhoto AS IsShowPhoto,
			@lIsOnPrePrinted AS IsOnPrePrinted,
			@lIsDisplayReligion AS IsDisplayReligion,
			B.Remark AS ReceiptNo,
			SF.FatherName,
			SA.AdmissionDate,
			DP.Title AS DepartmentName,
			ISNULL(OM.DegreeAwarded,'') AS DegreeAwarded,
			@lIsDisplayImageHeader AS IsDisplayImageHeader,
			--OI.CertificateHeaderA4,
			REPLICATE(',',OM.LetterHeadMargin)    AS LetterHeadMargin,
			ISNULL(B.BonafiedReason,'') AS BonafiedReason,
			CT.Title AS Category,
			SF.MotherName,
			C.PermanentStreetOne,
			C.PermanentStreetTwo,
			C.PermanentStreetThree,
			C.PermanentCountry,
			C.PermanentState,
			C.PermanentCity,
			C.PermanentZipCode,
			C.PermanentContactNo,
			C.PresentStreetOne,
			C.PresentStreetTwo,
			C.PresentStreetThree,
			C.PresentCountry,
			C.PresentState,
			C.PresentCity,
			C.PresentContactNo,
			C.PresentZipCode,
			SM.SUId,
			SO.AdhaarNumber,
			CM.DisplayTitle AS ClassName,
			ISNULL(CTM.Nationality,'') AS Nationality,
			OM.PrincipalSignature,
			ISnull(AR.SourceId,0) AS StudentidForhostel,
			DM.DisplayTitle AS Divisionname,
			@lIDConfigValue AS ItemValue ,
			SM.RecordStatusId,
			SO.BirthState AS BirthState,
			CM1.Title AS AdmissionStandard,
			RRG.SchoolRemark1,
			RRG.SchoolRemark2,
			RRG.SchoolRemark3,
			SF.FatherAdhaarNumber AS FatherAadharNo,
			SF.MotherAdhaarNumber AS MotherAadharNo,
			ISNULL(OM.ReportOrgGroupTitle,'') AS ReportOrgGroupTitle,
			OM.ReportOrgTitle,
			--OI.CertificateHeaderA4,
			OI.CertificateHeaderA4Portrait AS CertificateHeaderA4,
			SM.Id AS StudentId,
			(CASE WHEN RRG.SchoolRequiredSignature IS NULL THEN NULL ELSE RRG.SchoolRequiredSignature END) AS SchoolRequiredSignature ,
			SO.UIDNumber,
			ISNULL(EI.EmployeeSign,0x) AS EmployeeSign,
			ISNULL(SA.AdmissionNumber,'') AS AdmissionNumber,
			BM.FromDate AS BatchFromDate,
			BM.ToDate AS BatchToDate ,

			ISNULL(U.DisplayTitle,'') AS UserName ,
		
		    ISNULL(EM.FirstName,'') +' '+ISNULL(EM.LastName,'') AS PrincipalName,
			ISNULL(CM.ClassNameInWord,'') AS ClassNameInWord,
			CM2.Title AS LeftStandard,
			CAST((CASE WHEN SI.QRCode IS NULL THEN 0 ELSE 1 END) AS bit) AS IsDisplayQRCode,			--add for 27638 mantis
			ISNULL(SI.QRCode,'') AS QRCode,							--add for 27638 mantis
			SA.LeftDate AS LeftDate
	FROM 
			sCertificate.tBonafide B
			
			INNER JOIN sStudent.tAcademic A ON B.AcademicId=A.Id
			LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId=A.StudentId
			INNER JOIN sStudent.tStudentMaster SM ON SM.Id=A.StudentId
			LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId=A.StudentId
			INNER JOIN sSetup.tDivisionMaster DM ON A.DivisionId = DM.Id  
			INNER JOIN sSetup.tClassMaster CM ON CM.Id= DM.ClassId
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id=A.BatchId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=A.OrgId
			left JOIN sSetup.tOrgImages OI ON OI.OrgId = OM.Id
			INNER JOIN sSetup.tAffiliationMaster AM ON OM.AffiliationId = AM.Id
			INNER JOIN sSetup.tAffiliationTypeMaster ATM ON AM.AffiliationTypeId = ATM.Id
			LEFT JOIN sCommon.tReligionMaster RM ON SO.ReligionId=RM.Id
			LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId = SM.Id
			INNER JOIN sStudent.tStudentAdmission SA ON SA.StudentId = SM.Id
			LEFT JOIN sSetup.tClassMaster CM1 ON CM1.Id = SA.AdmissionStandardId
			INNER JOIN sSetup.tDepartmentMaster DP ON CM.DepartmentId = DP.Id
			LEFT JOIN sCommon.tCastCategoryMaster CT ON CT.Id = SO.CastCategoryId
			LEFT JOIN sStudent.tStudentCommunication C ON C.StudentId = A.StudentId
			LEFT JOIN sCommon.tCountryMaster CTM ON CTM.Id=SO.NationalityId
			LEFT JOIN SHostel.tAssignRoom Ar On Ar.SourceId=A.StudentId AND Ar.OrgGroupBatchId=@rOrgGroupBatchId 
			LEFT JOIN sCommon.tReportRemarkGroupOrg RRG ON RRG.OrgId = OM.Id AND ReportRemarkGroupId=6
			LEFT JOIN sHrm.tEmployeeImages EI ON EI.EmployeeId = DM.InchargeEmployeeId 
			LEFT JOIN sSecurity.tUser U	ON U.Id=B.CreatedUserId

			Left join sHrm.tEmployeeMaster EM on EM.Id = OM.EmployeeId
			LEFT JOIN sSetup.tClassMaster CM2 ON CM2.Id = SA.LeftStandardId
			--INNER JOIN sSetup.tTermMaster TM ON  TM.ID=
	WHERE 
			A.OrgId=@rOrgId
			AND	A.BatchId = @rBatchId 
			AND ((A.ClassId=@rClassId) OR (@rClassId=0))
			AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId=0))
			AND ((SM.Code = @rCode) OR (ISNULL(@rCode,'') = ''))
			AND ((SM.FirstName = @rName) OR (ISNULL(@rName,'') = ''))
			--AND ((B.BonafideDate=@rBonafiedDate) OR (ISNULL(@rBonafiedDate,'')=''))
			AND ((B.Number=@rNumber) OR (@rNumber=''))
			AND ((B.Number >= @rFromNo) OR (@rFromNo=''))
			AND ((B.Number <= @rToNo) OR (@rToNo=''))
			AND ((B.BonafideDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
			AND ((B.BonafideDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
			--Group By B.AcademicId,SM.Code,SM.FirstName,SM.LastName,SM.MiddleName,CM.DisplayTitle,BM.Title,SO.DateOfBirth,SO.BirthDateInWord,
			--SO.BirthPlace,SO.BirthTaluka,SO.BirthDistrict,B.BonafideDate,OM.CityName,OM.StateName,SO.FamilyCast,SO.FamilySubCast,SO.GenderId,SI.StudentPhoto,SM.StatusId,
			--OM.OrgLogo,OM.PhoneNo,OM.Title,OM.StreetOne,OM.StreetTwo,OM.StreetThree
	END
GO
PRINT N'Altering Procedure [sCommon].[pUploadDocumentAdd]...';


GO

 
 
ALTER PROCEDURE [sCommon].[pUploadDocumentAdd]
	 
	@rUploadFunctionalityId smallint,
	@rUserSourceTypeId smallint,
	@rUserSourceId bigint,
	@rDocumentId bigint,
	@rDocumentName nvarchar(200),
	@rCreatedUserId bigint,
	@rDocumentSize decimal (12,2) = 0.00,
	@rOrgGroupBatchId int = 0   
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	BEGIN TRANSACTION
	--if not not exists then record add
	IF ((@rUserSourceTypeId = 95 OR @rUserSourceTypeId = 2003) AND @rUserSourceId <> 0)
	BEGIN 
	IF NOT EXISTS (SELECT 1 FROM sCommon.tUploadDocument WHERE UploadFunctionalityId = @rUploadFunctionalityId AND DocumentId = @rDocumentId AND DocumentName = @rDocumentName AND OrgGroupBatchId = @rOrgGroupBatchId AND UserSourceId = @rUserSourceId AND UserSourceTypeId = @rUserSourceTypeId)
	BEGIN		
	INSERT INTO sCommon.tUploadDocument
		(
		UploadFunctionalityId,
		UserSourceTypeId,
		UserSourceId,
		DocumentId,
		DocumentName,
		CreatedUserId,
		CreatedDateTime,
		DocumentSize,
		OrgGroupBatchId
		)
	VALUES
		(
		@rUploadFunctionalityId,
		@rUserSourceTypeId,
		@rUserSourceId,
		@rDocumentId,
		@rDocumentName,
		@rCreatedUserId,
		sCommon.fGetDate(),
		@rDocumentSize,
		@rOrgGroupBatchId
		)
	 END
	END
	ELSE
	BEGIN
	IF NOT EXISTS (SELECT 1 FROM sCommon.tUploadDocument WHERE UploadFunctionalityId = @rUploadFunctionalityId AND DocumentId = @rDocumentId AND DocumentName = @rDocumentName AND OrgGroupBatchId = @rOrgGroupBatchId)
	BEGIN
	INSERT INTO sCommon.tUploadDocument
		(
		UploadFunctionalityId,
		UserSourceTypeId,
		UserSourceId,
		DocumentId,
		DocumentName,
		CreatedUserId,
		CreatedDateTime,
		DocumentSize,
		OrgGroupBatchId
		)
	VALUES
		(
		@rUploadFunctionalityId,
		@rUserSourceTypeId,
		@rUserSourceId,
		@rDocumentId,
		@rDocumentName,
		@rCreatedUserId,
		sCommon.fGetDate(),
		@rDocumentSize,
		@rOrgGroupBatchId
		)
	 END
	 END
	COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Altering Procedure [sCommunication].[pAssignmentQueueGet]...';


GO
ALTER PROCEDURE [sCommunication].[pAssignmentQueueGet]
	 @rId bigint = 0,
	 @rSubjectId int,
	 @rTitle nvarchar(100),
	 @rFromDate date,
	 @rToDate date,
	 @rBatchId int,
	 @rIsSearch bit = 1,
	 @rCreatedUserId bigint=0,
	 @rStatusId int=0,
	 @rUserId bigint = 0,
	 @rClassId int = 0,
	 @rDivisionId int = 0
	 	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
		
		
DECLARE @rSourceId bigint
DECLARE @rSourceTypeId int
DECLARE @rAssignmentCount int

set @rSourceId = ( SELECT SourceId FROM sSecurity.tUser where Id=@rCreatedUserId)
set @rSourceTypeId = ( SELECT SourceTypeId FROM sSecurity.tUser where Id=@rCreatedUserId)

IF(@rSourceTypeId = 95)

BEGIN 
	IF @rIsSearch = 1
	BEGIN
		SET @rTitle = sCommon.fSearchStringGet(@rTitle)
	END

	SET @rAssignmentCount=	(select ISNULL(COUNT(1),0) FROM sCommunication.tAssignment WHERE CreatedUserId=@rCreatedUserId)

	IF(@rAssignmentCount=0)
	BEGIN
		SET @rCreatedUserId=0
	END
	ELSE
	BEGIN
		SET @rCreatedUserId = @rCreatedUserId
	END
	
	SELECT DISTINCT
		A.Id as AssignmentId,
		A.SubjectId,
		SM.Title as SubjectName,
		A.Title,
		A.Remark,
		A.StartDate,
		A.EndDate,
		U.DisplayTitle as CreatedUserName,
		ISNULL(A.StatusId,549) as StatusId,
		CASE WHEN ISNULL(A.StatusId,549)=549 THEN 'Pending' WHEN A.StatusId=550 THEN 'Approve' ELSE 'Reject' END AS Status		    
	FROM 
		sCommunication.tAssignment A
        LEFT JOIN sSecurity.tUser U ON U.Id=A.CreatedUserId
        INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=A.SubjectId
		INNER JOIN sCommunication.tAssignmentScope ASS ON ASS.AssignmentId=A.ID
		INNER JOIN sAcademic.vTeacherSubjectDivision vTSD ON vTSD.SubjectId = SM.Id 
		--AND vTSD.ClassId=ASS.SourceId --comment for mantis Id :0030424
		AND vTSD.DivisionId=ASS.SourceId
			
	WHERE ((A.Id = @rId) OR (@rId = 0))
		AND ((A.SubjectId = @rSubjectId) OR (@rSubjectId = 0))
		AND ((A.Title like @rTitle) OR (ISNULL(@rTitle,'') = ''))
		AND ((A.StartDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
		AND ((A.EndDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
		--AND ((A.CreatedUserId = @rCreatedUserId) OR (@rCreatedUserId = 0)) --comment for mantis Id :0030424
		AND ((A.CreatedUserId != @rCreatedUserId) OR (@rCreatedUserId = 0))
		AND A.BatchId=@rBatchId
		AND ((ISNULL(A.StatusId,549) = @rStatusId) OR (@rStatusId = 0))	 
		AND((ISNULL(vTSD.SubjectCordinatorEmployeeId,0) = @rUserId)OR(@rUserId=0))
	 
	 --Add union for mantis Id :0030424

	UNION 

	SELECT DISTINCT
		A.Id as AssignmentId,
		A.SubjectId,
		SM.Title as SubjectName,
		A.Title,
		A.Remark,
		A.StartDate,
		A.EndDate,
		U.DisplayTitle as CreatedUserName,
		ISNULL(A.StatusId,549) as StatusId,
		CASE WHEN ISNULL(A.StatusId,549)=549 THEN 'Pending' WHEN A.StatusId=550 THEN 'Approve' ELSE 'Reject' END AS Status
	FROM 
		sCommunication.tAssignment A
		LEFT JOIN sSecurity.tUser U ON U.Id=A.CreatedUserId
		INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=A.SubjectId
		INNER JOIN sCommunication.tAssignmentScope ASS ON ASS.AssignmentId=A.ID AND ASS.SourceTypeId = 2017
			
	WHERE ((A.Id = @rId) OR (@rId = 0))
		AND ((A.SubjectId = @rSubjectId) OR (@rSubjectId = 0))
		AND ((A.Title like @rTitle) OR (ISNULL(@rTitle,'') = ''))
		AND ((A.StartDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
		AND ((A.EndDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
		AND ((A.CreatedUserId != @rCreatedUserId) OR (@rCreatedUserId = 0))
		AND A.BatchId=@rBatchId
		AND ((ISNULL(A.StatusId,549) = @rStatusId) OR (@rStatusId = 0))	 

END

ELSE
BEGIN
 IF @rIsSearch = 1
		BEGIN
			SET @rTitle = sCommon.fSearchStringGet(@rTitle)
		END
	
	SELECT 
	DISTINCT
			A.Id as AssignmentId,
			A.SubjectId,
			SM.Title as SubjectName,
			A.Title,
			A.Remark,
			A.StartDate,
			A.EndDate,
			U.DisplayTitle as CreatedUserName,
			ISNULL(A.StatusId,549) as StatusId,
			CASE WHEN ISNULL(A.StatusId,549)=549 THEN 'Pending' WHEN A.StatusId=550 THEN 'Approve' ELSE 'Reject' END AS Status
		    
  FROM 
            sCommunication.tAssignment A
			INNER JOIN [sCommunication].[tAssignmentScope] CAS on A.Id = CAS.AssignmentId and CAS.SourceTypeId = 2005 
            LEFT JOIN sSecurity.tUser U ON U.Id=A.CreatedUserId
            INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=A.SubjectId
			--INNER JOIN sAcademic.vTeacherSubjectDivision vTSD ON vTSD.SubjectId = SM.Id
			INNER JOIN [sSetup].[tClassSubject] CS on CS.SubjectId = SM.Id
			INNER JOIN [sSetup].[tClassMaster] CM on Cs.ClassId = CM.Id									
			INNER JOIN [sSetup].[tDivisionMaster] DM on DM.Id = CAS.SourceId and CM.Id = Dm.classId 
			
  WHERE 
  
      ((A.Id = @rId) OR (@rId = 0))
    AND ((A.SubjectId = @rSubjectId) OR (@rSubjectId = 0))
	AND ((A.Title like @rTitle) OR (ISNULL(@rTitle,'') = ''))
	AND ((A.StartDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
	AND ((A.EndDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
	AND ((A.CreatedUserId = @rCreatedUserId) OR (@rCreatedUserId = 0))
	AND A.BatchId=@rBatchId
	AND ((ISNULL(A.StatusId,549) = @rStatusId) OR (@rStatusId = 0))	
	AND ((CM.Id = @rClassId) OR (@rClassId = 0))
	AND ((DM.Id = @rDivisionId) OR (@rDivisionId = 0)) 
	--AND((ISNULL(vTSD.SubjectCordinatorEmployeeId,0) = @rSubjectCordinatorId)OR(@rSubjectCordinatorId=0))
END
GO
PRINT N'Altering Procedure [sCommunication].[pMultiPhotoCategoryMaster_Get]...';


GO
ALTER PROCEDURE [sCommunication].[pMultiPhotoCategoryMaster_Get]
	 
	 @rScopeSourceId bigint=0,
	 @rId int = 0,
	 @rSyncedPhotoCategoryId int = 0,
	 @rSourcetypeId smallint,
	 @rBatchId int
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 

	DECLARE @lOrgGroupId smallint,@lOrgGroupBatchID int,@lOrgId smallint
  
	IF @rSourcetypeId=2003
	BEGIN
		SELECT @lOrgGroupId=Om.OrgGroupId,@lOrgId=OM.Id ,@lOrgGroupBatchID=BM.OrgGroupBatchId  
		FROM sSetup.tOrganizationMaster OM INNER JOIN sStudent.tAcademic A ON A.OrgId=OM.Id
		INNER JOIN sSetup.tBatchMaster BM ON  BM.Id=A.BatchId 
		WHERE A.BatchId= @rBatchId AND A.Id=@rScopeSourceId 
	END
	ELSE IF @rSourcetypeId=95
	BEGIN
		SELECT @lOrgGroupId=Om.OrgGroupId, @lOrgId=OrgId 
		FROM sSetup.tOrganizationMaster OM INNER JOIN sHrm.tEmployeeMaster EM ON EM.OrgID=OM.Id 
		WHERE Em.Id=@rScopeSourceId AND ISNULL(EM.IsOtherUser,0) = 0
	END
	ELSE
	BEGIN
		SELECT @lOrgGroupId=OM.OrgGRoupId 
		FROM sSetup.tOrganizationMaster OM INNER JOIN sSetup.tBatchMaster BM ON BM.OrgId=OM.Id 
		WHERE Bm.Id=@rBatchId
	END
 
	IF @rSourcetypeId=2003
	BEGIN
	SELECT DISTINCT
		PCM.[Id],
  		PCM.[Title],
		PCM.[IsObsolete],
		ISNULL(PCS.ScopeSourceTypeId,0) AS ScopeSourceTypeId,
		ISNULL(Remark,'') AS Remark,
		ISNULL(PCM.OrgGroupBatchId,0) AS OrgGroupBatchId,
		PCM.ScopeSourceTypeId AS AssigneeId
		--PCS.AssigneeToId AS AssigneeId
	FROM 
		[sCommunication].[tMultiPhotoCategoryMaster] PCM 
		LEFT JOIN sCommunication.tMultiPhotoCategoryScope PCS  ON PCM.Id = PCS.MultiPhotoCategoryId 
		--comment for mantis Id:0030339
		--AND (PCS.ScopeSourceId = CASE WHEN PCS.ScopeSourceTypeId = 2005 THEN
		--(SELECT DivisionId FROM sStudent.tAcademic WHERE DivisionId = PCS.ScopeSourceId And Id = @rScopeSourceId)
		--WHEN PCS.ScopeSourceTypeId = 2016 THEN
		--(SELECT ClassId FROM sStudent.tAcademic WHERE DivisionId = PCS.ScopeSourceId And Id = @rScopeSourceId)
		--WHEN PCS.ScopeSourceTypeId = 2017 THEN
		--(SELECT D.Id FROM sSetup.tDepartmentMaster D INNER JOIN sSetup.tClassMaster CA ON CA.DepartmentId=D.Id 
		--INNER JOIN sStudent.tAcademic A ON A.ClassID=CA.Id WHERE A.Id =@rScopeSourceId)
		--WHEN PCS.ScopeSourceTypeId =2021 THEN
		--(SELECT OM.Id FROM sSetup.tOrganizationMaster OM INNER JOIN sStudent.tAcademic A ON A.OrgId =OM.Id WHERE A.Id=@rScopeSourceId)
		--WHEN PCS.ScopeSourceTypeId =2014 THEN
		--(SELECT Hm.Id FROM sHostel.tHostelMaster Hm INNER JOIN  sHostel.tRoomMaster RA ON RA.HostelId=HM.Id 
		--INNER JOIN sHostel.tAssignRoom AR ON AR.RoomId=RA.Id
		--INNER JOIN sStudent.tAcademic A ON A.StudentId=AR.SourceId 
		--WHERE AR.OrgGroupBatchId = @lOrgGroupBatchID AND HM.OrgGroupId=@lOrgGroupId AND A.Id=@rScopeSourceId)
		--WHEN PCS.ScopeSourceTypeId =2029 THEN
		--(SELECT HO.Id FROM sActivity.tHouseMaster HO
		--INNER JOIN sStudent.tStudentOther SO ON SO.HouseId=HO.Id 
		--INNER JOIN sStudent.tAcademic A ON A.StudentId=SO.StudentId
		--WHERE HO.OrgId=@lOrgId AND A.Id=@rScopeSourceId)
		--When PCS.ScopeSourceTypeId =2003 Then
		--(select StudentId from sStudent.tAcademic  Where StudentId = PCS.ScopeSourceId AND Id = @rScopeSourceId)
		--ENd)
		--LEFT JOIN sCommon.tAssigneeMaster AM ON AM.Id = PCM.ScopeSourceTypeId	
		
	WHERE 
		--PCM.IsObsolete=0	
		(PCM.Id=@rId OR @rId=0) 
		AND PCM.OrgGroupId = @lOrgGroupId
	--ORDER BY PCM.CreatedDateTime DESC
	END
	ELSE IF @rSourcetypeId=95
	BEGIN 
	SELECT DISTINCT
		PCM.[Id],
		PCM.[Title],
		PCM.[IsObsolete],
		ISNULL(PCS.ScopeSourceTypeId,0) AS ScopeSourceTypeId,
		ISNULL(Remark,'') AS Remark,
		ISNULL(PCM.OrgGroupBatchId,0) AS OrgGroupBatchId,
		PCM.ScopeSourceTypeId AS AssigneeId
		--PCS.AssigneeToId AS AssigneeId
	FROM 
		[sCommunication].[tMultiPhotoCategoryMaster] PCM 
		LEFT join sCommunication.tMultiPhotoCategoryScope PCS  ON PCM.Id = PCS.MultiPhotoCategoryId 
		--comment for mantis Id:0030339
		--AND
		--(PCS.ScopeSourceId = Case WHEN PCS.ScopeSourceTypeId = 2017 THEN
		--(SELECT D.Id FROM sSetup.tDepartmentMaster D 
		--INNER JOIN sHrm.tEmployeeJobDetail EJ ON EJ.OrganizationDepartmentId=D.Id
		--WHERE EJ.EmployeeId=@rScopeSourceId AND EJ.OrgId=@lOrgId)
		--WHEN PCS.ScopeSourceTypeId=2021 THEN
		--(SELECT OM.Id FROM sSetup.tOrganizationMaster OM 
		--INNER JOIN sHrm.tEmployeeMaster EM ON EM.OrgId=OM.Id
		--WHERE EM.OrgId=@lOrgId and Em.Id=@rScopeSourceId AND ISNULL(EM.IsOtherUser,0) = 0)
		--When PCS.ScopeSourceTypeId = 95 Then
		--(select Id from sHrm.tEmployeeMaster  Where Id = @rScopeSourceId)
		--END)
		--LEFT JOIN sCommon.tAssigneeMaster AM ON AM.Id = PCM.ScopeSourceTypeId	

	WHERE 
		--PCM.IsObsolete=0 
		((PCM.Id = @rId) OR (@rId=0)) 
		AND PCM.OrgGroupId = @lOrgGroupId
		--ORDER BY PCM.CreatedDateTime DESC
	END
	ELSE
	BEGIN
	SELECT  DISTINCT
		PCM.[Id],
  		PCM.[Title],
		PCM.[IsObsolete],
		ISNULL(PCS.ScopeSourceTypeId,0) AS ScopeSourceTypeId,
		ISNULL(Remark,'') AS Remark,
		ISNULL(PCM.OrgGroupBatchId,0) AS OrgGroupBatchId,
		PCM.ScopeSourceTypeId AS AssigneeId
		--PCS.AssigneeToId AS AssigneeId
	FROM    
		[sCommunication].[tMultiPhotoCategoryMaster]  PCM 
		INNER JOIN sCommunication.tMultiPhotoCategoryScope PCS  ON PCM.Id = PCS.MultiPhotoCategoryId 
		--LEFT JOIN sCommon.tAssigneeMaster AM ON AM.Id = PCM.ScopeSourceTypeId
	WHERE   
		--PCM.IsObsolete = 0
		((PCM.Id = @rId) OR (@rId = 0))
		AND ((PCM.Id > @rSyncedPhotoCategoryId) OR (@rSyncedPhotoCategoryId = 0))
		AND OrgGroupId=@lOrgGroupId
		--ORDER BY PCM.CreatedDateTime DESC
	END   
      
END
GO
PRINT N'Altering Procedure [sCommunication].[pQueryListGet]...';


GO

ALTER PROCEDURE [sCommunication].[pQueryListGet]
	 
	 
	  @rQueryCategoryId int = 0,
	 --@rTitle nvarchar(100),
	 @rOrgGroupBatchId int,
	 --@rOrgId int,
	 @rOrgGroupId int=0,
	 @rId bigint,
	 @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= 0 
	 
	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,
			--VQCM.OrgId As OrgId,
			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(U.SourceTypeId,0) AS FromSourceTypeId,
			--ISNULL(QM.FromSourceId,0) AS FromSourceId,
			CASE 
			   WHEN ISNULL(U.SourceTypeId,0) = 2003 THEN (SELECT Code from sStudent.tStudentMaster SM where SM.Id=U.SourceId)
			   WHEN ISNULL(U.SourceTypeId,0) = 95 THEN (SELECT Code from sHrm.tEmployeeMaster EM where EM.Id=U.SourceId AND ISNULL(EM.IsOtherUser,0) = 0)
			   ELSE ''
			END AS FromSourceId,
			CASE 
			   WHEN ISNULL(U.SourceTypeId,0) = 2003 THEN (SELECT Code from sStudent.tStudentMaster SM where SM.Id=U.SourceId)
			   WHEN ISNULL(U.SourceTypeId,0) = 95 THEN (SELECT Code from sHrm.tEmployeeMaster EM where EM.Id=U.SourceId AND ISNULL(EM.IsOtherUser,0) = 0)
			   ELSE ''
			END AS FromSourceId,
			CASE 
			   WHEN ISNULL(U.SourceTypeId,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=U.SourceId and BM.OrgGroupBatchId=@rOrgGroupBatchId
			                                                   )
               WHEN ISNULL(U.SourceTypeId,0) = 95 THEN (SELECT 
			                                                        DM.Title
			                                                   FROM 
			                                                        sHrm.tEmployeeJobDetail EJD
			                                                         INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id=EJD.OrganizationDepartmentId
			                                                   WHERE EmployeeId=U.SourceId
			                                                   )			                                                   
			  
			   ELSE ''
			END AS Code,
			CASE 
			   WHEN ISNULL(U.SourceTypeId,0) = 2003 THEN (SELECT 
			                                                        U.DisplayTitle
			                                                   )
               WHEN ISNULL(U.SourceTypeId,0) = 95 THEN (SELECT 
			                                                        U.DisplayTitle
			                                                   )			                                                   
			  
			   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 sCommunication.vOrgwiseQueryCategory VQCM ON QM.QueryCategoryId=VQCM.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
		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 ((QCM.OrgGroupId = @rOrgGroupId) OR (@rOrgGroupId=0))
		AND ISNULL(EM.IsOtherUser,0) = 0
		--AND ((ISNULL(VQCM.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,
			--VQCM.OrgId As OrgId,
			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(U.SourceTypeId,0) AS FromSourceTypeId,
			--ISNULL(QM.FromSourceId,0) AS FromSourceId,
			CASE 
			   WHEN ISNULL(U.SourceTypeId,0) = 2003 THEN (SELECT Code from sStudent.tStudentMaster SM where SM.Id=U.SourceId)
			   WHEN ISNULL(U.SourceTypeId,0) = 95 THEN (SELECT Code from sHrm.tEmployeeMaster EM where EM.Id=U.SourceId AND ISNULL(EM.IsOtherUser,0) = 0)
			   ELSE ''
			END AS FromSourceId,
			CASE 
			   WHEN ISNULL(U.SourceTypeId,0) = 2003 THEN (SELECT Code from sStudent.tStudentMaster SM where SM.Id=U.SourceId)
			   WHEN ISNULL(U.SourceTypeId,0) = 95 THEN (SELECT Code from sHrm.tEmployeeMaster EM where EM.Id=U.SourceId AND ISNULL(EM.IsOtherUser,0) = 0)
			   ELSE ''
			END AS FromSourceId,
			CASE 
			   WHEN ISNULL(U.SourceTypeId,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=U.SourceId and BM.OrgGroupBatchId=@rOrgGroupBatchId
			                                                   )
               WHEN ISNULL(U.SourceTypeId,0) = 95 THEN (SELECT 
			                                                        DM.Title
			                                                   FROM 
			                                                        sHrm.tEmployeeJobDetail EJD
			                                                         INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id=EJD.OrganizationDepartmentId
			                                                   WHERE EmployeeId=U.SourceId
			                                                   )			                                                   
			  
			   ELSE ''
			END AS Code,
			CASE 
			   WHEN ISNULL(U.SourceTypeId,0) = 2003 THEN (SELECT 
			                                                        U.DisplayTitle
			                                                   )
               WHEN ISNULL(U.SourceTypeId,0) = 95 THEN (SELECT 
			                                                        U.DisplayTitle
			                                                   )			                                                   
			  
			   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 sCommunication.vOrgwiseQueryCategory VQCM ON QM.QueryCategoryId=VQCM.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
		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 ((QCM.OrgGroupId = @rOrgGroupId) OR (@rOrgGroupId=0))
		AND ISNULL(EM.IsOtherUser,0) = 0
		--AND ((ISNULL(VQCM.AssignedToId,1) <> @rAssignedToId) OR (@rAssignedToId = 0))
		AND QCM.AssignedToId IN (1,2) 
        ORDER BY QM.CreatedDateTime DESC

	  END
	  ELSE --For Other Login
	  BEGIN
			SELECT 
			QM.Id AS QueryId,
			QCM.Id AS QueryCategoryId,
			--VQCM.OrgId As OrgId,
			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(U.SourceTypeId,0) AS FromSourceTypeId,
			--comment above FromSourceTypeId because in admin login we get 0 FromSourceTypeId - mantisid -- 0030521
			ISNULL(QM.FromSourceTypeId,0) AS FromSourceTypeId,
			--ISNULL(QM.FromSourceId,0) AS FromSourceId,
			CASE 
			   WHEN ISNULL(U.SourceTypeId,0) = 2003 THEN (SELECT Code from sStudent.tStudentMaster SM where SM.Id=U.SourceId)
			   WHEN ISNULL(U.SourceTypeId,0) = 95 THEN (SELECT Code from sHrm.tEmployeeMaster EM where EM.Id=U.SourceId AND ISNULL(EM.IsOtherUser,0) = 0)
			   ELSE ''
			END AS FromSourceId,
			CASE 
			   WHEN ISNULL(U.SourceTypeId,0) = 2003 THEN (SELECT Code from sStudent.tStudentMaster SM where SM.Id=U.SourceId)
			   WHEN ISNULL(U.SourceTypeId,0) = 95 THEN (SELECT Code from sHrm.tEmployeeMaster EM where EM.Id=U.SourceId AND ISNULL(EM.IsOtherUser,0) = 0)
			   ELSE ''
			END AS FromSourceId,
			CASE 
			   WHEN ISNULL(U.SourceTypeId,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=U.SourceId and BM.OrgGroupBatchId=@rOrgGroupBatchId
			                                                   )
               WHEN ISNULL(U.SourceTypeId,0) = 95 THEN (SELECT 
			                                                        DM.Title
			                                                   FROM 
			                                                        sHrm.tEmployeeJobDetail EJD
			                                                         INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id=EJD.OrganizationDepartmentId
			                                                   WHERE EmployeeId=U.SourceId
			                                                   )			                                                   
			  
			   ELSE ''
			END AS Code,
			CASE 
			   WHEN ISNULL(U.SourceTypeId,0) = 2003 THEN (SELECT 
			                                                        U.DisplayTitle
			                                                   )
               WHEN ISNULL(U.SourceTypeId,0) = 95 THEN (SELECT 
			                                                        U.DisplayTitle
			                                                   )			                                                   
			  
			   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 sCommunication.vOrgwiseQueryCategory VQCM ON QM.QueryCategoryId=VQCM.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 ((QCM.OrgGroupId = @rOrgGroupId) OR (@rOrgGroupId=0))
		AND ISNULL(EM.IsOtherUser,0) = 0
		--AND ((ISNULL(QCM.AssignedToId,1) <> @rAssignedToId) OR (@rAssignedToId = 0))
        ORDER BY QM.CreatedDateTime DESC
	  END

        
END
GO


PRINT N'Altering Procedure [sFee].[pDepositAdjustmentGet]...';


GO

ALTER PROCEDURE [sFee].[pDepositAdjustmentGet]
          
		   @rOrgId int=0,          
           @rDepositHeadId int=0,
           @rFromAmount decimal(12,2)=0,
           @rToAmount decimal(12,2)=0,
           @rFromAdjustmentDate date='',
           @rToAdjustmentDate date='',
           @rBatchId int=0,
           @rCode nvarchar(20)='',
           @rOrgGroupBatchId int=0,
           @rFeeDepositExpenseTypeId int=0,
           @rClassId int=0,
           @rDivisionId int=0
AS
SET NOCOUNT ON

BEGIN
SELECT  
		DHM.Title AS DepositHeadName,
		vSA.OrgId,
		DA.Id,
		DA.DepositHeadId,
	--	DA.StudentId AS StudentId,
		vSA.AcademicId AS AcademicId,
		DA.Amount,
		DA.AdjustmentDate,
		DA.Remark,
		DA.CreatedDateTime,
		vSA.Code,
        vSA.Name AS StudentName,        
        vSA.ClassName+' - '+vSA.DivisionName AS ClassDivisionName,
        ISNULL(VSA.SUID,'') AS SUID,
        VSA.BatchId,
        Isnull(DA.FeeDepositExpenseTypeId,0) AS FeeDepositExpenseTypeId,
        ISNULL(EM.Title,'') As FeeDepositExpenseType,
        vSA.StudentId,
		ISNULL(AdjustmentNumber,0) AS AdjustmentNumber,
		vSA.BatchName,				-- MantisId : 0030328
		vSA.OrganizationName
  FROM 		
		sStudent.vStudentAcademic vSA
		INNER JOIN sFee.tDepositAdjustment DA ON DA.AcademicId = vSA.AcademicId
		INNER JOIN sFee.tDepositHeadMaster DHM ON DHM.Id = DA.DepositHeadId
		LEFT JOIN  sFee.tFeeDepositExpenseTypeMaster EM ON EM.Id=DA.FeeDepositExpenseTypeId
  WHERE  
		--vSA.BatchId = @rBatchId 
		 (vSA.OrgId=@rOrgId OR @rOrgId=0)
		AND (DA.DepositHeadId=@rDepositHeadId OR @rDepositHeadId=0)
		AND ((DA.Amount >= @rFromAmount) OR (@rFromAmount = 0))
		AND ((DA.Amount <= @rToAmount) OR (@rToAmount = 0))
		AND ((DA.AdjustmentDate >= @rFromAdjustmentDate) OR (ISNULL(@rFromAdjustmentDate,'') = ''))
		AND ((DA.AdjustmentDate <= @rToAdjustmentDate) OR (ISNULL(@rToAdjustmentDate,'') = ''))
		AND ((vSA.Code=@rCode) OR (ISNULL(@rCode,'')=''))
	    AND VSA.OrgGroupBatchId=@rOrgGroupBatchId
	    AND (DA.FeeDepositExpenseTypeId=@rFeeDepositExpenseTypeId OR @rFeeDepositExpenseTypeId=0)
	    AND((vSA.ClassId = @rClassId)OR(@rClassId=0))
		AND((vSA.DivisionId = @rDivisionId)OR(@rDivisionId=0))
		Order By DA.AdjustmentDate
END
GO
PRINT N'Altering Procedure [sFee].[pFeeCollectionConsolidatedDashboardGet]...';


GO
ALTER PROCEDURE [sFee].[pFeeCollectionConsolidatedDashboardGet]

     @rOrgGroupId smallint=0,
     @rTypeId int=0,
     @rType nvarchar(20)='',
     @rCommonOrgGroupBatchId int=0,
	 @rFromDate date =null,
	 @rToDate date = null,
	 @rReceiptBookId int =0,
	 @rUserId bigint=0,
	 @rOrgId int =0,
	 @rCommonFeeId int =0
	 
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
--If @rFromDate= NULL Set @rFromDate = ''
--  If @rToDate =NULL Set @rToDate = ''
 DECLARE @cols NVARCHAR(MAX),@query  NVARCHAR(MAX),@cols1 NVARCHAR(MAX), @cols2 NVARCHAR(MAX); 
	---Fee Collection Wise  
			IF(@rTypeId=1)
				BEGIN
					SET @cols = STUFF((SELECT ',' +  QUOTENAME(PTM.Title )
					FROM sFinanceCommon.tPayTypeMaster PTM
					--INNER JOIN  sFee.tReceipt R  ON PTM.Id=R.PayTypeId
					--INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.SourceId 
					GROUP BY PTM.Title
					FOR XML PATH(''), TYPE
					).value('.', 'NVARCHAR(MAX)') 
					,1,1,'')

					SET @cols1 = STUFF((SELECT ', SUM(ISNULL(' + QUOTENAME(PTM.Title) + ', ''0'')) ' + QUOTENAME(PTM.Title) 
					FROM sFinanceCommon.tPayTypeMaster PTM
					--INNER JOIN  sFee.tReceipt R  ON PTM.Id=R.PayTypeId
					--INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.SourceId 
					GROUP BY PTM.Title
					FOR XML PATH(''), TYPE
					).value('.', 'NVARCHAR(MAX)') 
					,1,1,'')					

					SET @cols2 = STUFF((SELECT '+ SUM(ISNULL(' + QUOTENAME(PTM.Title) + ', ''0'')) ' 
					FROM sFinanceCommon.tPayTypeMaster PTM
					GROUP BY PTM.Title
					FOR XML PATH(''), TYPE
					).value('.', 'NVARCHAR(MAX)') 
					,1,1,'')	

					set @query = 'SELECT OrgGroupId,OrgGroupName,' + @cols2 + ' AS Total, ' + @cols1 + ' from 
					(
					SELECT  OMM.Id AS OrgGroupId ,OMM.Title AS OrgGroupName,SUM(R.ReceiptAmount) AS Total,PTM.Title AS PayTypeName, COALESCE(SUM(R.ReceiptAmount),0) AS ReceiptAmount FROM sFee.tReceipt R
					INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.SourceId 
					INNER JOIN  sFinanceCommon.tPayTypeMaster PTM  ON PTM.Id=R.PayTypeId
					INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SA.OrgId
					INNER JOIN sSetup.tOrgGroupMaster OMM ON OMM.Id = OM.OrgGroupId 
					INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=SA.OrgGroupBatchId
					INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
					INNER JOIN sSetup.tBatchMaster BM ON SA.BatchId = BM.Id
					WHERE  COGBM.Id='+CONVERT(nvarchar(20),@rCommonOrgGroupBatchId)+' AND R.SourceTypeId = 2001 
					AND((OMM.Id='+CONVERT(nvarchar(20),@rOrgGroupId)+') OR ('+CONVERT(nvarchar(20),@rOrgGroupId)+'=0))
					AND (( convert(DATE, R.ReceiptDate,102) >= '''+CONVERT(nvarchar(20),@rFromDate)+''') OR ('''+CONVERT(nvarchar(20),@rFromDate)+'''=''1900-01-01''))
					AND (( convert(DATE, R.ReceiptDate,102) <= '''+CONVERT(nvarchar(20),@rToDate)+''') OR ('''+CONVERT(nvarchar(20),@rToDate)+'''=''1900-01-01''))
					AND R.IsObsolete = 0
					And ISNULL(OMM.IsObsolete,0) = 0
					AND BM.IsInContext = 1 
					GROUP BY OMM.Title,OMM.Id,PTM.Title
					) x
					pivot 
					(
					Sum(ReceiptAmount) 
					for PayTypeName in (' + @cols + ')
					) p GROUP BY OrgGroupId,OrgGroupName  ORDER BY OrgGroupId'
					--print(@query)
					execute(@query)
				END
			ELSE IF( @rTypeId=11)
				BEGIN
					SET @cols = STUFF((SELECT ',' +  QUOTENAME(PTM.Title )
					FROM sFinanceCommon.tPayTypeMaster PTM
					--INNER JOIN  sFee.tReceipt R  ON PTM.Id=R.PayTypeId
					--INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.SourceId 
					GROUP BY PTM.Title
					FOR XML PATH(''), TYPE
					).value('.', 'NVARCHAR(MAX)') 
					,1,1,'')

					SET @cols1 = STUFF((SELECT ', SUM(ISNULL(' + QUOTENAME(PTM.Title) + ', ''0'')) ' + QUOTENAME(PTM.Title) 
					FROM sFinanceCommon.tPayTypeMaster PTM
					--INNER JOIN  sFee.tReceipt R  ON PTM.Id=R.PayTypeId
					--INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.SourceId 
					GROUP BY PTM.Title
					FOR XML PATH(''), TYPE
					).value('.', 'NVARCHAR(MAX)') 
					,1,1,'')

					SET @cols2 = STUFF((SELECT '+ SUM(ISNULL(' + QUOTENAME(PTM.Title) + ', ''0'')) ' 
					FROM sFinanceCommon.tPayTypeMaster PTM
					GROUP BY PTM.Title
					FOR XML PATH(''), TYPE
					).value('.', 'NVARCHAR(MAX)') 
					,1,1,'')

					set @query = 'SELECT ReceiptBookId,ReceiptBook,'+@cols2+' AS Total, ' + @cols1 + ' from 
					(
					SELECT RBM.Id AS ReceiptBookId,RBM.Title AS ReceiptBook,SUM(R.ReceiptAmount) AS Total,PTM.Title AS PayTypeName, COALESCE(SUM(R.ReceiptAmount),0) AS ReceiptAmount FROM sFee.tReceipt R
					INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.SourceId 
					INNER JOIN sFinanceCommon.tPayTypeMaster PTM ON PTM.Id=R.PayTypeId
					INNER JOIN sFee.tReceiptBookMaster RBM ON RBM.Id=R.ReceiptBookId
					INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SA.OrgId
					INNER JOIN sSetup.tOrgGroupMaster OMM ON OMM.Id = OM.OrgGroupId 
					INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=SA.OrgGroupBatchId
					INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
					INNER JOIN sSetup.tBatchMaster BM ON SA.BatchId = BM.Id
					WHERE  COGBM.Id='+CONVERT(nvarchar(20),@rCommonOrgGroupBatchId)+' AND R.SourceTypeId = 2001 
					AND((OMM.Id='+CONVERT(nvarchar(20),@rOrgGroupId)+') OR ('+CONVERT(nvarchar(20),@rOrgGroupId)+'=0))
					AND (( convert(DATE, R.ReceiptDate,102) >= '''+CONVERT(nvarchar(20),@rFromDate)+''') OR ('''+CONVERT(nvarchar(20),@rFromDate)+'''=''1900-01-01''))
					AND (( convert(DATE, R.ReceiptDate,102) <= '''+CONVERT(nvarchar(20),@rToDate)+''') OR ('''+CONVERT(nvarchar(20),@rToDate)+'''=''1900-01-01''))
					AND R.IsObsolete = 0
					And ISNULL(OMM.IsObsolete,0) = 0
					AND BM.IsInContext = 1
					GROUP BY RBM.Title,RBM.Id,PTM.Title
					) x
					pivot 
					(
					Sum(ReceiptAmount) 
					for PayTypeName in (' + @cols + ')
					) p GROUP BY ReceiptBookId,ReceiptBook ORDER BY ReceiptBookId'					
					print(@query)
					execute(@query)
				 END
			ELSE IF( @rTypeId=12)
				BEGIN
						SET @cols = STUFF((SELECT ',' +  QUOTENAME(PTM.Title )
					FROM sFinanceCommon.tPayTypeMaster PTM
					--INNER JOIN  sFee.tReceipt R  ON PTM.Id=R.PayTypeId
					--INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.SourceId 
					GROUP BY PTM.Title
					FOR XML PATH(''), TYPE
					).value('.', 'NVARCHAR(MAX)') 
					,1,1,'')

					SET @cols1 = STUFF((SELECT ', SUM(ISNULL(' + QUOTENAME(PTM.Title) + ', ''0'')) ' + QUOTENAME(PTM.Title) 
					FROM sFinanceCommon.tPayTypeMaster PTM
					--INNER JOIN  sFee.tReceipt R  ON PTM.Id=R.PayTypeId
					--INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.SourceId 
					GROUP BY PTM.Title
					FOR XML PATH(''), TYPE
					).value('.', 'NVARCHAR(MAX)') 
					,1,1,'')

					SET @cols2 = STUFF((SELECT '+ SUM(ISNULL(' + QUOTENAME(PTM.Title) + ', ''0'')) '
					FROM sFinanceCommon.tPayTypeMaster PTM
					GROUP BY PTM.Title
					FOR XML PATH(''), TYPE
					).value('.', 'NVARCHAR(MAX)') 
					,1,1,'')

					set @query = 'SELECT UserId,UserName,SourceTypeId,' + @cols2 + ' AS Total, ' + @cols1 + ' from 
					(
					SELECT  U.Id As UserId,U.DisplayTitle AS UserName,ISNULL(U.SourceTypeId,0) AS SourceTypeId,SUM(R.ReceiptAmount) AS Total,PTM.Title AS PayTypeName, COALESCE(SUM(R.ReceiptAmount),0) AS ReceiptAmount FROM sFee.tReceipt R
					INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.SourceId 
					INNER JOIN sFinanceCommon.tPayTypeMaster PTM ON PTM.Id=R.PayTypeId
					INNER JOIN sFee.tReceiptBookMaster RBM ON RBM.Id=R.ReceiptBookId
					INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SA.OrgId
					INNER JOIN sSetup.tOrgGroupMaster OMM ON OMM.Id = OM.OrgGroupId 
					INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=SA.OrgGroupBatchId
					INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
					INNER JOIN sSetup.tBatchMaster BM ON SA.BatchId = BM.Id
					LEFT JOIN sSecurity.tUser U ON U.Id=R.CreatedUserId
					WHERE  COGBM.Id='+CONVERT(nvarchar(20),@rCommonOrgGroupBatchId)+' AND R.SourceTypeId = 2001 
					AND((OMM.Id='+CONVERT(nvarchar(20),@rOrgGroupId)+') OR ('+CONVERT(nvarchar(20),@rOrgGroupId)+'=0))
					AND (( convert(DATE, R.ReceiptDate,102) >= '''+CONVERT(nvarchar(20),@rFromDate)+''') OR ('''+CONVERT(nvarchar(20),@rFromDate)+'''=''1900-01-01''))
					AND (( convert(DATE, R.ReceiptDate,102) <= '''+CONVERT(nvarchar(20),@rToDate)+''') OR ('''+CONVERT(nvarchar(20),@rToDate)+'''=''1900-01-01''))
					AND BM.IsInContext = 1
					GROUP BY U.id,U.DisplayTitle,PTM.Title,U.SourceTypeId
					) x
					pivot 
					(
					Sum(ReceiptAmount) 
					for PayTypeName in (' + @cols + ')
					) p GROUP BY UserId,UserName,SourceTypeId ORDER BY UserId'
					print(@query)
					execute(@query)
				END
			ELSE IF (@rTypeId=13)
				BEGIN
					SET @cols = STUFF((SELECT ',' +  QUOTENAME(PTM.Title )
					FROM sFinanceCommon.tPayTypeMaster PTM
					--INNER JOIN  sFee.tReceipt R  ON PTM.Id=R.PayTypeId
					--INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.SourceId 
					GROUP BY PTM.Title
					FOR XML PATH(''), TYPE
					).value('.', 'NVARCHAR(MAX)') 
					,1,1,'')

					SET @cols1 = STUFF((SELECT ', SUM(ISNULL(' + QUOTENAME(PTM.Title) + ', ''0'')) ' + QUOTENAME(PTM.Title) 
					FROM sFinanceCommon.tPayTypeMaster PTM
					--INNER JOIN  sFee.tReceipt R  ON PTM.Id=R.PayTypeId
					--INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.SourceId 
					GROUP BY PTM.Title
					FOR XML PATH(''), TYPE
					).value('.', 'NVARCHAR(MAX)') 
					,1,1,'')

					SET @cols2 = STUFF((SELECT '+ SUM(ISNULL(' + QUOTENAME(PTM.Title) + ', ''0'')) '
					FROM sFinanceCommon.tPayTypeMaster PTM
					GROUP BY PTM.Title
					FOR XML PATH(''), TYPE
					).value('.', 'NVARCHAR(MAX)') 
					,1,1,'')

					set @query = 'SELECT OrgGroupId,OrgGroupName,' + @cols2 + ' AS Total, ' + @cols1 + ' from 
					(
					SELECT  OM.Id AS OrgGroupId ,OM.DisplayTitle AS OrgGroupName,SUM(R.ReceiptAmount) AS Total,PTM.Title AS PayTypeName, COALESCE(SUM(R.ReceiptAmount),0) AS ReceiptAmount FROM sFee.tReceipt R
					INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.SourceId 
					INNER JOIN sFinanceCommon.tPayTypeMaster PTM ON PTM.Id=R.PayTypeId
					INNER JOIN sFee.tReceiptBookMaster RBM ON RBM.Id=R.ReceiptBookId
					INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SA.OrgId
					INNER JOIN sSetup.tOrgGroupMaster OMM ON OMM.Id = OM.OrgGroupId 
					INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=SA.OrgGroupBatchId
					INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
					INNER JOIN sSetup.tBatchMaster BM ON SA.BatchId = BM.Id
					WHERE  COGBM.Id='+CONVERT(nvarchar(20),@rCommonOrgGroupBatchId)+' AND R.SourceTypeId = 2001 
					AND((OMM.Id='+CONVERT(nvarchar(20),@rOrgGroupId)+') OR ('+CONVERT(nvarchar(20),@rOrgGroupId)+'=0))
					AND (( convert(DATE, R.ReceiptDate,102) >= '''+CONVERT(nvarchar(20),@rFromDate)+''') OR ('''+CONVERT(nvarchar(20),@rFromDate)+'''=''1900-01-01''))
					AND (( convert(DATE, R.ReceiptDate,102) <= '''+CONVERT(nvarchar(20),@rToDate)+''') OR ('''+CONVERT(nvarchar(20),@rToDate)+'''=''1900-01-01''))
					AND BM.IsInContext = 1
					GROUP BY OM.DisplayTitle,OM.Id,PTM.Title
					) x
					pivot 
					(
					Sum(ReceiptAmount) 
					for PayTypeName in (' + @cols + ')
					) p GROUP BY OrgGroupId,OrgGroupName ORDER BY OrgGroupId '
					print(@query)
					execute(@query)
				END
			ELSE IF (@rTypeId=14)
				BEGIN
					SET @cols = STUFF((SELECT ',' +  QUOTENAME(PTM.Title )
					FROM sFinanceCommon.tPayTypeMaster PTM
					--INNER JOIN  sFee.tReceipt R  ON PTM.Id=R.PayTypeId
					--INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.SourceId 
					GROUP BY PTM.Title
					FOR XML PATH(''), TYPE
					).value('.', 'NVARCHAR(MAX)') 
					,1,1,'')

					SET @cols1 = STUFF((SELECT ', SUM(ISNULL(' + QUOTENAME(PTM.Title) + ', ''0'')) ' + QUOTENAME(PTM.Title) 
					FROM sFinanceCommon.tPayTypeMaster PTM
					--INNER JOIN  sFee.tReceipt R  ON PTM.Id=R.PayTypeId
					--INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.SourceId 
					GROUP BY PTM.Title
					FOR XML PATH(''), TYPE
					).value('.', 'NVARCHAR(MAX)') 
					,1,1,'')

					SET @cols2 = STUFF((SELECT '+ SUM(ISNULL(' + QUOTENAME(PTM.Title) + ', ''0'')) '
					FROM sFinanceCommon.tPayTypeMaster PTM
					GROUP BY PTM.Title
					FOR XML PATH(''), TYPE
					).value('.', 'NVARCHAR(MAX)') 
					,1,1,'')

					set @query = 'SELECT FeeHeadId,FeeHead,' + @cols2 + ' AS Total, ' + @cols1 + ' from 
					(
					SELECT  FHM.Id AS FeeHeadId,FHM.Title AS FeeHead,SUM(RD.Amount) AS total,PTM.Title AS PayTypeName,ISNULL(SUM(RD.Amount),0) AS ReceiptAmount FROM sFee.tReceipt R
					INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.SourceId 
					INNER JOIN sFee.tReceiptDetail RD ON R.Id = RD.ReceiptId
					INNER JOIN sFinanceCommon.tPayTypeMaster PTM ON PTM.Id=R.PayTypeId
					INNER JOIN sFee.tReceiptBookMaster RBM ON RBM.Id=R.ReceiptBookId
					INNER JOIN sFee.tFeeSetup FS ON FS.Id = RD.FeeSetupId
					INNER JOIN sFee.tFeeMaster FM ON FM.Id = FS.FeeId
					INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FM.FeeHeadId
					INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SA.OrgId
					INNER JOIN sSetup.tOrgGroupMaster OMM ON OMM.Id = OM.OrgGroupId 
					INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=SA.OrgGroupBatchId
					INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
					INNER JOIN sSetup.tBatchMaster BM ON SA.BatchId = BM.Id
					WHERE  COGBM.Id='+CONVERT(nvarchar(20),@rCommonOrgGroupBatchId)+' AND R.SourceTypeId = 2001 
					AND((OMM.Id='+CONVERT(nvarchar(20),@rOrgGroupId)+') OR ('+CONVERT(nvarchar(20),@rOrgGroupId)+'=0))
					AND (( convert(DATE, R.ReceiptDate,102) >= '''+CONVERT(nvarchar(20),@rFromDate)+''') OR ('''+CONVERT(nvarchar(20),@rFromDate)+'''=''1900-01-01''))
					AND (( convert(DATE, R.ReceiptDate,102) <= '''+CONVERT(nvarchar(20),@rToDate)+''') OR ('''+CONVERT(nvarchar(20),@rToDate)+'''=''1900-01-01''))
					AND BM.IsInContext = 1
					GROUP BY FHM.Id,FHM.Title,PTM.Id,PTM.Title
					) x
					pivot 
					(
					Sum(ReceiptAmount) 
					for PayTypeName in (' + @cols + ')
					) p GROUP BY FeeHeadId,FeeHead ORDER BY FeeHeadId'
					
					execute(@query)
				END
			ELSE IF (@rTypeId=15)
				BEGIN
					SET @cols = STUFF((SELECT ',' +  QUOTENAME(PTM.Title )
					FROM sFinanceCommon.tPayTypeMaster PTM
					--INNER JOIN  sFee.tReceipt R  ON PTM.Id=R.PayTypeId
					--INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.SourceId 
					GROUP BY PTM.Title
					FOR XML PATH(''), TYPE
					).value('.', 'NVARCHAR(MAX)') 
					,1,1,'')

					SET @cols1 = STUFF((SELECT ', SUM(ISNULL(' + QUOTENAME(PTM.Title) + ', ''0'')) ' + QUOTENAME(PTM.Title) 
					FROM sFinanceCommon.tPayTypeMaster PTM
					--INNER JOIN  sFee.tReceipt R  ON PTM.Id=R.PayTypeId
					--INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.SourceId 
					GROUP BY PTM.Title
					FOR XML PATH(''), TYPE
					).value('.', 'NVARCHAR(MAX)') 
					,1,1,'')

					SET @cols2 = STUFF((SELECT '+ SUM(ISNULL(' + QUOTENAME(PTM.Title) + ', ''0'')) '
					FROM sFinanceCommon.tPayTypeMaster PTM
					GROUP BY PTM.Title
					FOR XML PATH(''), TYPE
					).value('.', 'NVARCHAR(MAX)') 
					,1,1,'')

					set @query = 'SELECT FeeHeadId,FeeMaster,' + @cols2 + ' AS Total, ' + @cols1 + ' from 
					(
					SELECT FM.Id AS FeeHeadId,FM.Title AS FeeMaster,SUM(RD.Amount) AS total,PTM.Title AS PayTypeName,ISNULL(SUM(RD.Amount),0) AS ReceiptAmount FROM sFee.tReceipt R
						INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.SourceId 
						INNER JOIN sFee.tReceiptDetail RD ON R.Id = RD.ReceiptId
						INNER JOIN sFinanceCommon.tPayTypeMaster PTM ON PTM.Id=R.PayTypeId
						INNER JOIN sFee.tReceiptBookMaster RBM ON RBM.Id=R.ReceiptBookId
						INNER JOIN sFee.tFeeSetup FS ON FS.Id = RD.FeeSetupId
						INNER JOIN sFee.tFeeMaster FM ON FM.Id = FS.FeeId
						INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FM.FeeHeadId
						INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SA.OrgId
						INNER JOIN sSetup.tOrgGroupMaster OMM ON OMM.Id = OM.OrgGroupId 
						INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=SA.OrgGroupBatchId
						INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
						INNER JOIN sSetup.tBatchMaster BM ON SA.BatchId = BM.Id
						WHERE  COGBM.Id='+CONVERT(nvarchar(20),@rCommonOrgGroupBatchId)+' AND R.SourceTypeId = 2001 
						AND((OMM.Id='+CONVERT(nvarchar(20),@rOrgGroupId)+') OR ('+CONVERT(nvarchar(20),@rOrgGroupId)+'=0))
						AND (( convert(DATE, R.ReceiptDate,102) >= '''+CONVERT(nvarchar(20),@rFromDate)+''') OR ('''+CONVERT(nvarchar(20),@rFromDate)+'''=''1900-01-01''))
						AND (( convert(DATE, R.ReceiptDate,102) <= '''+CONVERT(nvarchar(20),@rToDate)+''') OR ('''+CONVERT(nvarchar(20),@rToDate)+'''=''1900-01-01''))
						AND BM.IsInContext = 1
						GROUP BY FM.Id,FM.Title,PTM.Id,PTM.Title
					) x
					pivot 
					(
					Sum(ReceiptAmount) 
					for PayTypeName in (' + @cols + ')
					) p GROUP BY FeeHeadId,FeeMaster  ORDER BY FeeHeadId'
					execute(@query)
				END

			ELSE IF(@rTypeId =21)
				BEGIN
				IF NOT EXISTS(SELECT 1 FROM sFee.tApplicablePayType WHERE OrgGroupId = @rOrgGroupId)
				BEGIN
					SELECT  R.ReceiptNumber AS ReceiptNumber,R.ReceiptDate AS ReceiptDate,SA.Code AS Code, SA.Name AS Name,R.ReceiptAmount AS Amount
					FROM sFee.tReceipt R
					INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.SourceId 
					INNER JOIN sFinanceCommon.tPayTypeMaster PTM ON PTM.Id=R.PayTypeId
					INNER JOIN sFee.tReceiptBookMaster RBM ON RBM.Id=R.ReceiptBookId
					INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SA.OrgId
					INNER JOIN sSetup.tOrgGroupMaster OMM ON OMM.Id = OM.OrgGroupId 
					INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=SA.OrgGroupBatchId
					INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
					INNER JOIN sSetup.tBatchMaster BM ON SA.BatchId = BM.Id
					WHERE  COGBM.Id= @rCommonOrgGroupBatchId  AND R.SourceTypeId = 2001 					 
					AND((OMM.Id=@rOrgGroupId) OR (@rOrgGroupId=0))
					AND ((R.ReceiptBookId =@rReceiptBookId )OR(@rReceiptBookId=0))
					AND (( convert(DATE, R.ReceiptDate,102) >= @rFromDate) OR (@rFromDate=''))
					AND (( convert(DATE, R.ReceiptDate,102) <= @rToDate) OR (@rToDate=''))
					AND R.IsObsolete = 0
					And ISNULL(OMM.IsObsolete,0) = 0
					AND BM.IsInContext = 1
					ORDER BY R.ReceiptNumber -- Added By Foram - 02/08/2023 - Mantis Issue: 0026499
				END
				ELSE
				BEGIN
				SELECT  R.ReceiptNumber AS ReceiptNumber,R.ReceiptDate AS ReceiptDate,SA.Code AS Code, SA.Name AS Name,R.ReceiptAmount AS Amount
					FROM sFee.tReceipt R
					INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.SourceId 
					INNER JOIN sFee.tApplicablePayType PTM ON PTM.PayTypeId=R.PayTypeId
					INNER JOIN sFee.tReceiptBookMaster RBM ON RBM.Id=R.ReceiptBookId
					INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SA.OrgId
					INNER JOIN sSetup.tOrgGroupMaster OMM ON OMM.Id = OM.OrgGroupId 
					INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=SA.OrgGroupBatchId
					INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
					INNER JOIN sSetup.tBatchMaster BM ON SA.BatchId = BM.Id
					WHERE  COGBM.Id= @rCommonOrgGroupBatchId  AND R.SourceTypeId = 2001 					 
					AND((OMM.Id=@rOrgGroupId) OR (@rOrgGroupId=0))
					AND ((R.ReceiptBookId =@rReceiptBookId )OR(@rReceiptBookId=0))
					AND (( convert(DATE, R.ReceiptDate,102) >= @rFromDate) OR (@rFromDate=''))
					AND (( convert(DATE, R.ReceiptDate,102) <= @rToDate) OR (@rToDate=''))
					AND R.IsObsolete = 0
					And ISNULL(OMM.IsObsolete,0) = 0
					AND BM.IsInContext = 1
					ORDER BY R.ReceiptNumber -- Added By Foram - 02/08/2023 - Mantis Issue: 0026499
				END
				END
			ELSE IF(@rTypeId =22)
				BEGIN
				IF NOT EXISTS(SELECT 1 FROM sFee.tApplicablePayType WHERE OrgGroupId = @rOrgGroupId)
				BEGIN
					SELECT  R.ReceiptNumber AS ReceiptNumber,R.ReceiptDate AS ReceiptDate,SA.Code AS Code, SA.Name AS Name,R.ReceiptAmount AS Amount
					FROM sFee.tReceipt R
					INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.SourceId 
					INNER JOIN sFinanceCommon.tPayTypeMaster PTM ON PTM.Id=R.PayTypeId
					INNER JOIN sFee.tReceiptBookMaster RBM ON RBM.Id=R.ReceiptBookId
					INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SA.OrgId
					INNER JOIN sSetup.tOrgGroupMaster OMM ON OMM.Id = OM.OrgGroupId 
					INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=SA.OrgGroupBatchId
					INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
					LEFT JOIN sSecurity.tUser U ON U.Id=R.CreatedUserId
					INNER JOIN sSetup.tBatchMaster BM ON SA.BatchId = BM.Id
					WHERE  COGBM.Id= @rCommonOrgGroupBatchId  AND R.SourceTypeId = 2001 					 
					AND((OMM.Id=@rOrgGroupId) OR (@rOrgGroupId=0))
					--AND ((U.Id =@rUserId )OR(@rUserId=0))
					AND ((U.Id = CASE WHEN @rUserId = 2003 THEN 0 ELSE @rUserId END)OR(CASE WHEN @rUserId = 2003 THEN 0 ELSE @rUserId END=0))
					AND ((U.SourceTypeId = CASE WHEN @rUserId = 2003 THEN 2003 ELSE 0 END)OR(CASE WHEN @rUserId = 2003 THEN 2003 ELSE 0 END=0))
					AND (( convert(DATE, R.ReceiptDate,102) >= @rFromDate) OR (@rFromDate=''))
					AND (( convert(DATE, R.ReceiptDate,102) <= @rToDate) OR (@rToDate=''))
					AND BM.IsInContext = 1
				END
				ELSE
				BEGIN
					SELECT  R.ReceiptNumber AS ReceiptNumber,R.ReceiptDate AS ReceiptDate,SA.Code AS Code, SA.Name AS Name,R.ReceiptAmount AS Amount
					FROM sFee.tReceipt R
					INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.SourceId 
					INNER JOIN sFee.tApplicablePayType PTM ON PTM.PayTypeId=R.PayTypeId
					INNER JOIN sFee.tReceiptBookMaster RBM ON RBM.Id=R.ReceiptBookId
					INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SA.OrgId
					INNER JOIN sSetup.tOrgGroupMaster OMM ON OMM.Id = OM.OrgGroupId 
					INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=SA.OrgGroupBatchId
					INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
					LEFT JOIN sSecurity.tUser U ON U.Id=R.CreatedUserId
					INNER JOIN sSetup.tBatchMaster BM ON SA.BatchId = BM.Id
					WHERE  COGBM.Id= @rCommonOrgGroupBatchId  AND R.SourceTypeId = 2001 					 
					AND((OMM.Id=@rOrgGroupId) OR (@rOrgGroupId=0))
					--AND ((U.Id =@rUserId )OR(@rUserId=0))
					AND ((U.Id = CASE WHEN @rUserId = 2003 THEN 0 ELSE @rUserId END)OR(CASE WHEN @rUserId = 2003 THEN 0 ELSE @rUserId END=0))
					AND ((U.SourceTypeId = CASE WHEN @rUserId = 2003 THEN 2003 ELSE 0 END)OR(CASE WHEN @rUserId = 2003 THEN 2003 ELSE 0 END=0))
					AND (( convert(DATE, R.ReceiptDate,102) >= @rFromDate) OR (@rFromDate=''))
					AND (( convert(DATE, R.ReceiptDate,102) <= @rToDate) OR (@rToDate=''))
					AND BM.IsInContext = 1
				END
				END
			ELSE IF(@rTypeId =23)
				BEGIN
				IF NOT EXISTS(SELECT 1 FROM sFee.tApplicablePayType WHERE OrgGroupId = @rOrgGroupId)
				BEGIN
					SELECT  R.ReceiptNumber AS ReceiptNumber,R.ReceiptDate AS ReceiptDate,SA.Code AS Code, SA.Name AS Name,R.ReceiptAmount AS Amount
					FROM sFee.tReceipt R
					INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.SourceId 
					INNER JOIN sFinanceCommon.tPayTypeMaster PTM ON PTM.Id=R.PayTypeId
					INNER JOIN sFee.tReceiptBookMaster RBM ON RBM.Id=R.ReceiptBookId
					INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SA.OrgId
					INNER JOIN sSetup.tOrgGroupMaster OMM ON OMM.Id = OM.OrgGroupId 
					INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=SA.OrgGroupBatchId
					INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
					INNER JOIN sSetup.tBatchMaster BM ON SA.BatchId = BM.Id
					WHERE  COGBM.Id= @rCommonOrgGroupBatchId  AND R.SourceTypeId = 2001 					 
					AND((OMM.Id=@rOrgGroupId) OR (@rOrgGroupId=0))
					AND ((OM.Id =@rOrgId )OR(@rOrgId=0))
					AND (( convert(DATE, R.ReceiptDate,102) >= @rFromDate) OR (@rFromDate=''))
					AND (( convert(DATE, R.ReceiptDate,102) <= @rToDate) OR (@rToDate=''))
					AND BM.IsInContext = 1
				END
				ELSE
				BEGIN
					SELECT  R.ReceiptNumber AS ReceiptNumber,R.ReceiptDate AS ReceiptDate,SA.Code AS Code, SA.Name AS Name,R.ReceiptAmount AS Amount
					FROM sFee.tReceipt R
					INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.SourceId 
					INNER JOIN sFee.tApplicablePayType PTM ON PTM.PayTypeId=R.PayTypeId
					INNER JOIN sFee.tReceiptBookMaster RBM ON RBM.Id=R.ReceiptBookId
					INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SA.OrgId
					INNER JOIN sSetup.tOrgGroupMaster OMM ON OMM.Id = OM.OrgGroupId 
					INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=SA.OrgGroupBatchId
					INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
					INNER JOIN sSetup.tBatchMaster BM ON SA.BatchId = BM.Id
					WHERE  COGBM.Id= @rCommonOrgGroupBatchId  AND R.SourceTypeId = 2001 					 
					AND((OMM.Id=@rOrgGroupId) OR (@rOrgGroupId=0))
					AND ((OM.Id =@rOrgId )OR(@rOrgId=0))
					AND (( convert(DATE, R.ReceiptDate,102) >= @rFromDate) OR (@rFromDate=''))
					AND (( convert(DATE, R.ReceiptDate,102) <= @rToDate) OR (@rToDate=''))
					AND BM.IsInContext = 1
				END
				END
			ELSE IF(@rTypeId =24)
				BEGIN
				IF NOT EXISTS(SELECT 1 FROM sFee.tApplicablePayType WHERE OrgGroupId = @rOrgGroupId)
				BEGIN
					SELECT  R.ReceiptNumber AS ReceiptNumber,R.ReceiptDate AS ReceiptDate,SA.Code AS Code, SA.Name AS Name,SUM(RD.Amount) AS Amount
					FROM sFee.tReceipt R
					INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.SourceId 
					INNER JOIN sFee.tReceiptDetail RD ON R.Id = RD.ReceiptId
					INNER JOIN sFinanceCommon.tPayTypeMaster PTM ON PTM.Id=R.PayTypeId
					INNER JOIN sFee.tReceiptBookMaster RBM ON RBM.Id=R.ReceiptBookId
					INNER JOIN sFee.tFeeSetup FS ON FS.Id = RD.FeeSetupId
					INNER JOIN sFee.tFeeMaster FM ON FM.Id = FS.FeeId
					INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FM.FeeHeadId
					INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SA.OrgId
					INNER JOIN sSetup.tOrgGroupMaster OMM ON OMM.Id = OM.OrgGroupId 
					INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=SA.OrgGroupBatchId
					INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
					INNER JOIN sSetup.tBatchMaster BM ON SA.BatchId = BM.Id
					WHERE  COGBM.Id= @rCommonOrgGroupBatchId  AND R.SourceTypeId = 2001 					 
					AND((OMM.Id=@rOrgGroupId) OR (@rOrgGroupId=0))
					AND ((FHM.Id =@rCommonFeeId)OR(@rCommonFeeId=0))
					AND (( convert(DATE, R.ReceiptDate,102) >= @rFromDate) OR (@rFromDate=''))
					AND (( convert(DATE, R.ReceiptDate,102) <= @rToDate) OR (@rToDate=''))
					AND BM.IsInContext = 1
					GROUP BY  R.ReceiptNumber,R.ReceiptDate,SA.Code, SA.Name 
				END
				ELSE
				BEGIN
					SELECT  R.ReceiptNumber AS ReceiptNumber,R.ReceiptDate AS ReceiptDate,SA.Code AS Code, SA.Name AS Name,SUM(RD.Amount) AS Amount
					FROM sFee.tReceipt R
					INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.SourceId 
					INNER JOIN sFee.tReceiptDetail RD ON R.Id = RD.ReceiptId
					INNER JOIN sFee.tApplicablePayType PTM ON PTM.PayTypeId=R.PayTypeId
					INNER JOIN sFee.tReceiptBookMaster RBM ON RBM.Id=R.ReceiptBookId
					INNER JOIN sFee.tFeeSetup FS ON FS.Id = RD.FeeSetupId
					INNER JOIN sFee.tFeeMaster FM ON FM.Id = FS.FeeId
					INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FM.FeeHeadId
					INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SA.OrgId
					INNER JOIN sSetup.tOrgGroupMaster OMM ON OMM.Id = OM.OrgGroupId 
					INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=SA.OrgGroupBatchId
					INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
					INNER JOIN sSetup.tBatchMaster BM ON SA.BatchId = BM.Id
					WHERE  COGBM.Id= @rCommonOrgGroupBatchId  AND R.SourceTypeId = 2001 					 
					AND((OMM.Id=@rOrgGroupId) OR (@rOrgGroupId=0))
					AND ((FHM.Id =@rCommonFeeId)OR(@rCommonFeeId=0))
					AND (( convert(DATE, R.ReceiptDate,102) >= @rFromDate) OR (@rFromDate=''))
					AND (( convert(DATE, R.ReceiptDate,102) <= @rToDate) OR (@rToDate=''))
					GROUP BY  R.ReceiptNumber,R.ReceiptDate,SA.Code, SA.Name
				END
				END
			ELSE IF(@rTypeId =25)
				BEGIN
				IF NOT EXISTS(SELECT 1 FROM sFee.tApplicablePayType WHERE OrgGroupId = @rOrgGroupId)
				BEGIN
					SELECT  R.ReceiptNumber AS ReceiptNumber,R.ReceiptDate AS ReceiptDate,SA.Code AS Code, SA.Name AS Name,SUM(RD.Amount) AS Amount
					FROM sFee.tReceipt R
					INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.SourceId 
					INNER JOIN sFee.tReceiptDetail RD ON R.Id = RD.ReceiptId
					INNER JOIN sFinanceCommon.tPayTypeMaster PTM ON PTM.Id=R.PayTypeId
					INNER JOIN sFee.tReceiptBookMaster RBM ON RBM.Id=R.ReceiptBookId
					INNER JOIN sFee.tFeeSetup FS ON FS.Id = RD.FeeSetupId
					INNER JOIN sFee.tFeeMaster FM ON FM.Id = FS.FeeId
					INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FM.FeeHeadId
					INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SA.OrgId
					INNER JOIN sSetup.tOrgGroupMaster OMM ON OMM.Id = OM.OrgGroupId 
					INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=SA.OrgGroupBatchId
					INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
					INNER JOIN sSetup.tBatchMaster BM ON SA.BatchId = BM.Id
					WHERE  
					COGBM.Id=@rCommonOrgGroupBatchId
					AND R.SourceTypeId = 2001 					 
					AND((OMM.Id=@rOrgGroupId) OR (@rOrgGroupId=0))
					AND ((FM.Id =@rCommonFeeId)OR(@rCommonFeeId=0))
					AND (( convert(DATE, R.ReceiptDate,102) >= @rFromDate) OR (@rFromDate=''))
					AND (( convert(DATE, R.ReceiptDate,102) <= @rToDate) OR (@rToDate=''))
					AND BM.IsInContext = 1
					GROUP BY  R.ReceiptNumber,R.ReceiptDate,SA.Code, SA.Name 
				END
				ELSE
				BEGIN
					SELECT  R.ReceiptNumber AS ReceiptNumber,R.ReceiptDate AS ReceiptDate,SA.Code AS Code, SA.Name AS Name,SUM(RD.Amount) AS Amount
					FROM sFee.tReceipt R
					INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.SourceId 
					INNER JOIN sFee.tReceiptDetail RD ON R.Id = RD.ReceiptId
					INNER JOIN sFee.tApplicablePayType PTM ON PTM.PayTypeId=R.PayTypeId
					INNER JOIN sFee.tReceiptBookMaster RBM ON RBM.Id=R.ReceiptBookId
					INNER JOIN sFee.tFeeSetup FS ON FS.Id = RD.FeeSetupId
					INNER JOIN sFee.tFeeMaster FM ON FM.Id = FS.FeeId
					INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FM.FeeHeadId
					INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SA.OrgId
					INNER JOIN sSetup.tOrgGroupMaster OMM ON OMM.Id = OM.OrgGroupId 
					INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=SA.OrgGroupBatchId
					INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
					INNER JOIN sSetup.tBatchMaster BM ON SA.BatchId = BM.Id
					WHERE  
					COGBM.Id=@rCommonOrgGroupBatchId
					AND R.SourceTypeId = 2001 					 
					AND((OMM.Id=@rOrgGroupId) OR (@rOrgGroupId=0))
					AND ((FM.Id =@rCommonFeeId)OR(@rCommonFeeId=0))
					AND (( convert(DATE, R.ReceiptDate,102) >= @rFromDate) OR (@rFromDate=''))
					AND (( convert(DATE, R.ReceiptDate,102) <= @rToDate) OR (@rToDate=''))
					AND BM.IsInContext = 1
					GROUP BY  R.ReceiptNumber,R.ReceiptDate,SA.Code, SA.Name
				END
				END
		
	
END
GO
PRINT N'Altering Procedure [sFee].[pReceiptAdd]...';


GO

ALTER PROCEDURE [sFee].[pReceiptAdd]
	
		   @rId bigint,
		   @rSourceTypeId smallint,
		   @rSourceId bigint,
		   @rReceiptNumber int,
		   @rReceiptDate date,
		   @rReceiptAmount decimal(12,2),
		   @rTotalReceiptAmount decimal(12,2),
		   @rDiscountAmount decimal(12,2),
		   @rPayTypeId tinyint,
		   @rChequeNo nvarchar(40),
		   @rBankName nvarchar(200),
		   @rReceiptBookId int,
		   @rIsObsolete bit,
		   @rCreatedUserId bigint,
		   @rOrgId int,
		   @rBatchId int,
		   @rOrgGroupBatchId int,
		   @rRemark nvarchar(200),
		   @rReceiptDetailXml [nvarchar](max),
		   @rChequeDate date,
		   @rCharge decimal(12,2)=0,
		   @rFeeInvoiceId bigint = NULL,
		   @rCollectionGroupId int = 0,
		   @rDepositedLedgerId int = 0,
		   @rPaymentTransactionId bigint = 0,
		   @rReceiptPrintGroupId nvarchar(100),
		   @rIsDiscountCoupon bit = 0

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

DECLARE @loDoc INT
DECLARE @lIsCreated INT
EXEC sp_xml_preparedocument @loDoc OUTPUT, @rReceiptDetailXml

BEGIN
	BEGIN TRY
	
	 SELECT @rOrgGroupBatchId = OrgGroupBatchId FROM sSetup.tBatchMaster where Id = @rBatchId

	 DECLARE @lConfigValue nvarchar(50)=''
	 SELECT @lConfigValue = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 339 AND SourceTypeId = 2010 AND SourceId = LEFT(@rOrgGroupBatchId,4)

	 IF @lConfigValue = ''
		SET @lConfigValue = 'ReceiptBookWise'

	IF @rChequeDate = '1900-01-01'
		SET @rChequeDate = NULL

-- Mantis - 0030695
	 DECLARE @lConfigValue1 nvarchar(50)=''
	 SELECT @lConfigValue1 = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 543 AND SourceTypeId = 1016 AND SourceId = LEFT(@rOrgGroupBatchId,4)
-- Mantis - 0030695	 

	IF(@rReceiptNumber <> 0)
	BEGIN
		IF(@rId = 0)--ID Condition Added by dhruv for issue no.0013266	
		BEGIN
			IF(@lConfigValue='ReceiptBookWise')
			BEGIN
				IF EXISTS(SELECT 1 from sFee.tReceipt where ReceiptNumber=@rReceiptNumber AND ReceiptBookId=@rReceiptBookId AND OrgGroupBatchId = @rOrgGroupBatchId)
				BEGIN
					SELECT -102 AS Result
					RETURN	
				END
			END
			ELSE IF(@lConfigValue='PayTypeWise')
			BEGIN
				IF EXISTS(SELECT 1 from sFee.tReceipt where ReceiptNumber=@rReceiptNumber AND ReceiptBookId=@rReceiptBookId AND  PayTypeId=@rPayTypeId AND OrgGroupBatchId = @rOrgGroupBatchId)
				BEGIN
					SELECT -102 AS Result
					RETURN	
				END
			END
			-- Mantis - 0030695
			IF(@rChequeNo <> '' AND @lConfigValue1 = 'True')
			BEGIN
				IF EXISTS(SELECT 1 from sFee.tReceipt where ChequeNo=@rChequeNo)
				BEGIN
					SELECT -103 AS Result
					RETURN	
				END
			END
			-- Mantis - 0030695
		END
		ELSE
		BEGIN
			IF(@lConfigValue='ReceiptBookWise')
			BEGIN
				IF EXISTS(SELECT 1 from sFee.tReceipt where ReceiptNumber=@rReceiptNumber AND ReceiptBookId=@rReceiptBookId AND OrgGroupBatchId = @rOrgGroupBatchId AND Id != @rId)
				BEGIN
					SELECT -102 AS Result
					RETURN	
				END
			END
			ELSE IF(@lConfigValue='PayTypeWise')
			BEGIN
				IF EXISTS(SELECT 1 from sFee.tReceipt where ReceiptNumber=@rReceiptNumber AND ReceiptBookId=@rReceiptBookId AND  PayTypeId=@rPayTypeId AND OrgGroupBatchId = @rOrgGroupBatchId AND Id != @rId)
				BEGIN
					SELECT -102 AS Result
					RETURN	
				END
			END
			-- Mantis - 0030695
			IF(@rChequeNo <> '' AND @lConfigValue1 = 'True')
			BEGIN
				IF EXISTS(SELECT 1 from sFee.tReceipt where ChequeNo=@rChequeNo AND Id != @rId)
				BEGIN
					SELECT -103 AS Result
					RETURN	
				END
			END
			-- Mantis - 0030695
		END 
	END
	ELSE
	BEGIN
		SET @rReceiptNumber = sFee.fReceiptNumberGet(@rReceiptBookId,@rOrgGroupBatchId,@rPayTypeId,@lConfigValue)
	END	
	EXECUTE [sFee].[pReceiptAddValidate] @rSourceId,'',@rReceiptDetailXml,@rIsCreated = @lIsCreated OUTPUT
 	IF(@lIsCreated = 1)
 		BEGIN
			SELECT -501 AS Result
			RETURN
		END
 
	 BEGIN TRANSACTION	
 IF(@rId = 0)	
BEGIN

	DECLARE @lNextNumber BIGINT     
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sFee.tReceipt', 0, 1, 1,@outNextNumber = @lNextNumber output
	Print @lNextNumber
--IF EXISTS(SELECT 1 from sFee.tReceipt where ReceiptNumber=@rReceiptNumber AND ReceiptBookId=@rReceiptBookId AND OrgGroupBatchId = @rOrgGroupBatchId)
--			BEGIN
--				SELECT -102 AS Result
--				RETURN	
--			END

		--Added By Dhruv
			IF(@lConfigValue='ReceiptBookWise')
		BEGIN
			IF EXISTS(SELECT 1 from sFee.tReceipt where ReceiptNumber=@rReceiptNumber AND ReceiptBookId=@rReceiptBookId AND OrgGroupBatchId = @rOrgGroupBatchId)
			BEGIN
				SELECT -102 AS Result
				RETURN	
			END
		END
		ELSE IF(@lConfigValue='PayTypeWise')
		BEGIN
			IF EXISTS(SELECT 1 from sFee.tReceipt where ReceiptNumber=@rReceiptNumber AND ReceiptBookId=@rReceiptBookId AND  PayTypeId=@rPayTypeId AND OrgGroupBatchId = @rOrgGroupBatchId)
			BEGIN
				SELECT -102 AS Result
				RETURN	
			END
		END
		--Added By Dhruv
		-- Mantis - 0030695
		IF(@rChequeNo <> '' AND @lConfigValue1 = 'True')
		BEGIN
			IF EXISTS(SELECT 1 from sFee.tReceipt where ChequeNo=@rChequeNo)
			BEGIN
				SELECT -103 AS Result
				RETURN	
			END
		END
		-- Mantis - 0030695

	Declare @lSourceTypeId int 
	SET @lSourceTypeId =(select ISNULL(SourceTypeId,0) from sSecurity.tUser where Id = @rCreatedUserId)

	DECLARE @lCreatedUserId bigint
	IF(@lSourceTypeId = 2001 OR @lSourceTypeId = 2003 OR @rCreatedUserId = 3)
		SET @lCreatedUserId=(Select [sCommon].[fGetBigIntIdForOrg](4,LEFT(@rOrgGroupBatchId,4)))
	ELSE
		SET @lCreatedUserId = @rCreatedUserId 

	INSERT INTO sFee.tReceipt
		(
		   Id,
		   SourceTypeId,
		   SourceId,
		   ReceiptNumber,
		   ReceiptDate,
		   ReceiptAmount,
		   TotalReceiptAmount,
		   DiscountAmount,
		   PayTypeId,
		   ChequeNo,
		   BankName,
		   ReceiptBookId,
		   Remark,
		   IsObsolete,
		   BatchId,
		   CreatedUserId,
		   CreatedDateTime,
		   OrgGroupBatchId,
		   ChequeDate,
		   FeeInvoiceId,
		   CollectionGroupId,
		   DepositedLedgerId,
		   PaymentTransactionId,
		   ReceiptPrintGroupId,
		   IsDiscountCoupon  ---Added By Dhruv for Issue . 0011150
        )
	VALUES
		(
			@lNextNumber,
			@rSourceTypeId,
			@rSourceId,
		    @rReceiptNumber,
		    @rReceiptDate,
		    @rReceiptAmount,
		    @rTotalReceiptAmount,
		    @rDiscountAmount,
		    @rPayTypeId,
		    @rChequeNo,
		    @rBankName,
		    @rReceiptBookId,
		    @rRemark,
		    @rIsObsolete,
		    @rBatchId,
		    @lCreatedUserId,
		    sCommon.fGetDate(),
		    @rOrgGroupBatchId,
		    @rChequeDate,
		    @rFeeInvoiceId,
		    @rCollectionGroupId,
		    @rDepositedLedgerId,
		    @rPaymentTransactionId,
			@rReceiptPrintGroupId,
			@rIsDiscountCoupon
		)
		
		INSERT INTO sFee.tReceiptDetail
		(
		   ReceiptId,
		   FeeSetupId,
		   Amount
        )
        SELECT  	
		  @lNextNumber,
		  FeeSetupId,
		  Amount
		
	FROM OPENXML (@loDoc, '/Table/ReceiptDetail', 1)
		WITH ( 
				FeeSetupId int,
				Amount decimal(12,2)
			  ) 
		
		
		SELECT @lNextNumber AS Result
		EXEC sp_xml_removedocument @loDoc
		
		IF (@rCharge > 0)
		BEGIN
		EXEC [sFee].[pReceiptChargeAdd] @rSourceTypeId,@rSourceId,@lNextNumber,@lCreatedUserId,@rOrgId,@rBatchId,@rCharge,@rReceiptBookId
	
		END
	
		
		DECLARE @lIsServiceTaxApplicable bit
	    DECLARE @lServiceTaxPercentage decimal(6,2)
	
	    SELECT @lIsServiceTaxApplicable = ISNULL(IsServiceTaxApplicable,0),@lServiceTaxPercentage = ISNULL(ServiceTaxPercentage,0) FROM sFee.tReceiptBookMaster where Id = @rReceiptBookId
		
		IF (@lIsServiceTaxApplicable > 0 AND @lServiceTaxPercentage > 0)
		BEGIN
		EXEC [sFee].[pReceiptServiceTaxAdd] @rSourceTypeId,@rSourceId,@lNextNumber,@lCreatedUserId,@rOrgId,@rBatchId,@lServiceTaxPercentage
		END

		EXEC [sFee].[pFeeProcessGeneratePaidFeeAdd] @rOrgId,@rBatchId,@rSourceId,@lNextNumber,@lCreatedUserId
		
 END 
	ELSE
	
	IF EXISTS(SELECT 1 FROM sFee.tReceipt where ReceiptNumber=@rReceiptNumber AND Id = @rId)
	BEGIN
		UPDATE sFee.tReceipt SET
			ReceiptDate=@rReceiptDate,
			PayTypeId=@rPayTypeId,
			ChequeDate=@rChequeDate,
		    ChequeNo=@rChequeNo,
		    BankName=@rBankName,
		    Remark=@rRemark
		WHERE Id=@rId
		
	SELECT @rId AS RESULT
	END 
	ELSE
	IF(@rReceiptNumber <> 0)
	BEGIN
		IF(@lConfigValue='ReceiptBookWise')
		BEGIN
			IF EXISTS(SELECT 1 from sFee.tReceipt where ReceiptNumber=@rReceiptNumber AND ReceiptBookId=@rReceiptBookId AND OrgGroupBatchId = @rOrgGroupBatchId)
			BEGIN
				SELECT -102 AS Result
				RETURN	
			END
		END
		ELSE IF(@lConfigValue='PayTypeWise')
		BEGIN
			IF EXISTS(SELECT 1 from sFee.tReceipt where ReceiptNumber=@rReceiptNumber AND ReceiptBookId=@rReceiptBookId AND  PayTypeId=@rPayTypeId AND OrgGroupBatchId = @rOrgGroupBatchId)
			BEGIN
				SELECT -102 AS Result
				RETURN	
			END
		END
		-- Mantis - 0030695
			IF(@rChequeNo <> '' AND @lConfigValue1 = 'True')
			BEGIN
				IF EXISTS(SELECT 1 from sFee.tReceipt where ChequeNo=@rChequeNo AND Id != @rId)
				BEGIN
					SELECT -103 AS Result
					RETURN	
				END
			END
			-- Mantis - 0030695

		BEGIN
		UPDATE sFee.tReceipt SET
			ReceiptNumber = @rReceiptNumber,
			ReceiptDate=@rReceiptDate,
			PayTypeId=@rPayTypeId,
			ChequeDate=@rChequeDate,
		    ChequeNo=@rChequeNo,
		    BankName=@rBankName,
		    Remark=@rRemark
		WHERE Id=@rId
		
	SELECT @rId AS RESULT
	END 
	END
	
		COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Altering Procedure [sFee].[pRptFeeInvoiceGet]...';


GO
ALTER PROCEDURE [sFee].[pRptFeeInvoiceGet]
		
		@rBuilder1 nvarchar(max),
		@rBuilder2 nvarchar(max),
		@rReportId int,
		@rIsFilter bit,
	    @rIsDisplayOrgGroup bit,
	    @rIsFeeInvoiceHeadwise bit,
		@rOrgGroupBatchId int,
		@rCommonBatch nvarchar(100),
		@rReceiptBookId int,
		@rOrgId int,
		@rBatchId int,
		@rDepartmentId int,
		@rAdmissionCategoryId int,
		@rClassId int,
		@rDivisionId int,
		@rStatusId int,
		@rFromRollNo int,
	    @rToRollNo int,
	    @rCode nvarchar(20),
	    @rCollectionGroupId int=0,
	    @rFeeHeadId nvarchar(max) = '',
	    @rFeeId nvarchar(max) = '',
	    @rFilterId int=0,
	    @rOrgIds nvarchar(max) = '',
		@rClassStatusId int=0    
	    
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
BEGIN
   if(@rReportId =20886)
   begin
	SELECT 
		@rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,
		@rIsFilter AS IsFilter,
		@rIsDisplayOrgGroup AS IsDisplayOrgGroup,
		@rIsFeeInvoiceHeadwise AS IsFeeInvoiceHeadwise,
		FS.AcademicId,
		FS.Name,
		FS.ClassId,
		FS.ClassName,
		FS.DivisionId,
		FS.DivisionName,
		FS.DivisionOrder,
		FS.RollNo,
		FS.Code,
		FS.DepartmentId,
		FS.DepartmentName,
		FM.Id AS FeeId,
		FM.Title AS FeeName,
		FM.OrderIndex AS FeeOrderIndex,
		FHM.Id AS FeeHeadId,
		FHM.Title AS FeeHeadName,
		FHM.OrderIndex AS FeeHeadOrderIndex,
		RBM.Id AS ReceiptBookId,
		RBM.Title AS ReceiptBookName,
		RBM.BankName,
		RBM.BankAccountNumber,
		RBM.OrderIndex AS ReceiptBookOrderIndex,
		ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00) AS FeeAmount,
		ISNULL(R.PaidAmount,0.00) AS PaidAmount,
		CGM.Id AS CollectionGroupId,
		CGM.Title AS CollectionGroupName,
		CGM.OrderIndex AS CollectionGroupOrderIndex,
		CGM.FooterRemark1 AS FooterRemark1,
		CGM.FooterRemark2 AS FooterRemark2,
		CGM.FeePeriod AS FeePeriod,
		FS.BatchName,
		CGM.StartDate,
		CGM.EndDate,
		CGM.Remark,
		RBM.FullTitle,
		RBM.Address1,
		RBM.Address2,
		OM.OrgLogo,
		ISNULL(RBM.IsOnPrePrinted,0) AS IsOnPrePrinted,
		ISNULL(RBM.IsSupressLogo,0) AS IsSupressLogo,
		RBM.GroupTitle AS OrgGroupName,
		sFinanceCommon.fDefaultCurrencyTitleGet(OM.OrgGroupId) AS CurrencyTitle,
		ISNULL(SO.GenderId,0) AS GenderId,
		sFinanceCommon.fDefaultCurrencyCodeGet(OM.OrgGroupId) AS CurrencyCode,
		ISNULL(CGM.IsDisplayCashDetailInFolio,0) AS IsDisplayCashDetailInFolio,
		ISnull(CGM.IsOnPrePrinted,0) AS IsOnPrePrintedHeader,
			        
	         CASE
				 WHEN RBM.IsOnPrePrinted=1       
				 THEN 2
				 ELSE  ISNULL(RBM.FeeInvoiceHeaderDisplayId,1)
				END AS FeeInvoiceHeaderDisplayId,
       RBM.FeeInvoiceHeader
	  ,SC.PermanentStreetOne as PermanentStreetOne         -- #Start Mentis 29588
	  ,SC.PermanentStreetTwo as PermanentStreetTwo
	  ,SC.PermanentStreetThree as PermanentStreetThree 
	  ,SC.PermanentCountry as PermanentCountry
	  ,SC.PermanentState as PermanentState
	  ,SC.PermanentCity as PermanentCity
	  ,SC.PermanentZipCode as PermanentZipCode
	  ,SC.PermanentContactNo as PermanentContactNo 
	  ,SF.FatherName as FatherName
	  ,SF.MotherName as MotherName     
	  ,ISNULL(SAD.AdmissionNumber,'') AS AdmissionNumber 
	  ,SO.DateOfBirth as DateOfBirth                     
	  ,sFee.fFeeAmountSumGet (FS.AcademicId)  as TotalAmount	 -- #End Mantis 29588  
	  ,SI.StudentPhoto as StudentPhoto            -- Mentis 29588
	  ,SC.PresentStreetOne    --#Start Mantis - 0030332
	  ,SC.PresentStreetTwo
	  ,SC.PresentCity        
	  ,OI.CertificateHeaderA4Portrait AS CertificateHeaderA4  
	  ,TBM.FromDate AS BatchStartDate
	  ,TBM.ToDate AS BatchEndDate		--#End Mantis - 0030332
	    
  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,
				SA.AcademicId,
				SA.StudentId,
				SA.Name,
				SA.ClassId,
				SA.ClassName,
				SA.DivisionId,
				SA.DivisionName,
				SA.DivisionOrder,
				SA.RollNo,
				SA.Code,
				SA.DepartmentId,
				SA.DepartmentName,
				SA.BatchName,
				SA.OrgId,
				SA.OrgGroupBatchId,
				SA.AdmissionCategoryId,
				SA.StatusId				
			    FROM sFee.tFeeSetup FS1
				INNER JOIN sStudent.vStudentAcademic SA ON SA.AdmissionCategoryId = FS1.AdmissionCategoryId AND SA.ClassId = FS1.ClassId				
				WHERE FS1.ClassId=SA.ClassId AND FS1.AdmissionCategoryId=SA.AdmissionCategoryId AND IsOptional=0
				AND FS1.BatchId = SA.BatchId AND ((FS1.ReceiptBookId = @rReceiptBookId) OR (@rReceiptBookId=0))
				AND (ISNULL(SA.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')
				AND ((SA.ClassStatusId=@rClassStatusId) OR (@rClassStatusId=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,
				SA.AcademicId,
				SA.StudentId,
				SA.Name,
				SA.ClassId,
				SA.ClassName,
				SA.DivisionId,
				SA.DivisionName,
				SA.DivisionOrder,
				SA.RollNo,
				SA.Code,
				SA.DepartmentId,
				SA.DepartmentName,
				SA.BatchName,
				SA.OrgId,
				SA.OrgGroupBatchId,
				SA.AdmissionCategoryId,
				SA.StatusId				
			FROM sFee.tFeeSetup FS1
			INNER JOIN sStudent.vStudentAcademic SA ON SA.AdmissionCategoryId = FS1.AdmissionCategoryId AND SA.ClassId = FS1.ClassId			
			INNER JOIN sFee.tFeeOptional FO
				ON FO.FeeSetupId=FS1.Id AND (FO.SourceId=SA.AcademicId) AND(FO.SourceTypeId=2001)
			WHERE FS1.BatchId = SA.BatchId AND FS1.ClassId=SA.ClassId AND FS1.AdmissionCategoryId=SA.AdmissionCategoryId AND IsOptional=1 
			AND ((FS1.ReceiptBookId = @rReceiptBookId) OR (@rReceiptBookId=0))
			AND (ISNULL(SA.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')
			AND ((SA.ClassStatusId=@rClassStatusId) OR (@rClassStatusId=0))
		) FS ON FS.FeeId=FM.Id
		INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id = FM.FeeHeadId
		INNER JOIN sFee.tReceiptBookMaster RBM ON RBM.Id = FS.ReceiptBookId
		INNER JOIN sSetup.tOrgGroupMaster OGM ON OGM.Id = RBM.OrgGroupId
		LEFT JOIN sSetup.tOrgImages OI ON OI.OrgId = FS.OrgId		--	Mantis - 0030332 changed OGM.Id to FS.OrgId
		LEFT JOIN sFee.tCollectionGroupMaster CGM ON CGM.Id = FS.CollectionGroupId 
		AND FS.OrgGroupBatchId = CGM.OrgGroupBatchId
		LEFT JOIN sSetup.tOrganizationMaster OM ON OM.Id=FS.OrgId
		LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId = FS.StudentId
		LEFT JOIN sFee.tFeeAllocation FA
			ON FA.FeeSetupId=FS.Id AND (FA.SourceId=FS.AcademicId) AND(FA.SourceTypeId=2001)
		
         LEFT JOIN sHostel.tAssignRoom AR ON  AR.SourceId=FS.StudentId AND AR.SourceTypeId=2003 AND ((FS.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  AND ((AR.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) 
         LEFT JOIN
	(SELECT AT.SourceId FROM sTransport.tAssignRoute AT 
    INNER JOIN sTransport.tBusRouteDestinationMaster BM ON BM.Id=AT.PickupDestinationId
    INNER JOIN sTransport.tBusRouteMaster B ON B.Id=BM.BusRouteId AND  AT.SourceTypeId=2003 AND ((B.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))) RT
    ON RT.SourceId = FS.StudentId AND ((FS.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) 
    
    LEFT  JOIN
	(
	    SELECT 
				ISNULL(SUM(RD.Amount),0) AS PaidAmount,
				RD.FeeSetupId,
				R.SourceId
	    FROM
				sFee.tReceipt R 
			INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id 
			INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id
			INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id
			INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=R.SourceId 
			INNER JOIN sFinanceCommon.tPayTypeMaster PTM ON PTM.Id = R.PayTypeId
			AND ((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
			AND (SA1.ClassId=@rClassId OR @rClassId=0) 
			AND (SA1.DivisionId=@rDivisionId OR @rDivisionId=0)
			
			--AND (R.ReceiptBookId=@rReceiptBookId OR @rReceiptBookId=0)
			--AND (R.CollectionGroupId=@rCollectionGroupId OR @rCollectionGroupId=0)
		WHERE		
			(R.SourceTypeId = 2001)
			AND (R.IsObsolete = 0) 
			AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
			AND (SA1.OrgGroupBatchId = @rOrgGroupBatchId)
			AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
			AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
			AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
			AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
			AND ((SA1.ClassStatusId=@rClassStatusId) OR (@rClassStatusId=0))
				GROUP BY FeeSetupId,R.SourceId--,R.ReceiptNumber,R.ReceiptDate,PTM.Title,R.ChequeNo,R.BankName,R.ChequeDate
	) R ON R.FeeSetupId = FS.Id AND FS.AcademicId = R.SourceId

	LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentID = FS.StudentID    -- Mentis 29588
	LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentID = FS.StudentID           -- Mentis 29588
	LEFT JOIN sStudent.tStudentAdmission SAD ON SAD.StudentId = FS.StudentID 
	LEFT JOIN sStudent.tStudentImages SI ON SI.StudentID = FS.StudentID      -- Mentis 29588
    INNER JOIN sSetup.tBatchMaster TBM ON TBM.Id = FS.BatchId				-- Mantis 0030332
WHERE 
		(FS.OrgGroupBatchId = @rOrgGroupBatchId)
		AND ((FS.OrgId=@rOrgId) OR (@rOrgId=0))	
		AND ((FS.BatchId=@rBatchId) OR (@rBatchId=0))	
		AND	((FS.AdmissionCategoryId = @rAdmissionCategoryId) OR (@rAdmissionCategoryId = 0))
		AND ((FS.ClassId = @rClassId) OR (@rClassId = 0))
		AND ((FS.DivisionId = @rDivisionId) OR (@rDivisionId = 0))	
		AND ((FS.StatusId=@rStatusId) OR (@rStatusId=0))
		AND ((FS.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
		AND ((FS.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
		AND ((FS.RollNo <= @rToRollNo) OR (@rToRollNo=0))
		AND ((FS.Code=@rCode) OR (@rCode=''))
		AND ((FS.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
		AND	((FS.ReceiptBookId = @rReceiptBookId) OR (@rReceiptBookId = 0))
		AND	((FS.CollectionGroupId = @rCollectionGroupId) OR (@rCollectionGroupId = 0))
		 AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
		AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
		AND ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00) > 0  
		--AND ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00) > 0  
        --AND ISNULL(FS.Amount,0.00) > 0
		 AND (
			 (@rFilterId = 0) -- All
			 OR (@rFilterId = 2 AND isnull(AR.SourceId,0)!=0) -- Hostel
			 OR (@rFilterId = 3 AND isnull(RT.SourceId,0)!=0) -- Transport
			 OR ((@rFilterId =1) AND ((isnull(AR.SourceId,0)=0) AND (isnull(RT.SourceId,0)=0)))
			 ) 
       end

	   else
	     begin

		             SELECT 
		@rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,
		@rIsFilter AS IsFilter,
		@rIsDisplayOrgGroup AS IsDisplayOrgGroup,
		@rIsFeeInvoiceHeadwise AS IsFeeInvoiceHeadwise,
		FS.AcademicId,
		FS.Name,
		FS.ClassId,
		FS.ClassName,
		FS.DivisionId,
		FS.DivisionName,
		FS.DivisionOrder,
		FS.RollNo,
		FS.Code,
		FS.DepartmentId,
		FS.DepartmentName,
		FM.Id AS FeeId,
		FM.Title AS FeeName,
		FM.OrderIndex AS FeeOrderIndex,
		FHM.Id AS FeeHeadId,
		FHM.Title AS FeeHeadName,
		FHM.OrderIndex AS FeeHeadOrderIndex,
		RBM.Id AS ReceiptBookId,
		RBM.Title AS ReceiptBookName,
		RBM.BankName,
		RBM.BankAccountNumber,
		RBM.OrderIndex AS ReceiptBookOrderIndex,
		--ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00) AS FeeAmount,
		ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00) AS FeeAmount,
		CGM.Id AS CollectionGroupId,
		CGM.Title AS CollectionGroupName,
		CGM.OrderIndex AS CollectionGroupOrderIndex,
		CGM.FooterRemark1 AS FooterRemark1,
		CGM.FooterRemark2 AS FooterRemark2,
		CGM.FeePeriod AS FeePeriod,
		FS.BatchName,
		CGM.StartDate,
		CGM.EndDate,
		CGM.Remark,
		RBM.FullTitle,
		RBM.Address1,
		RBM.Address2,
		OM.OrgLogo,
		ISNULL(RBM.IsOnPrePrinted,0) AS IsOnPrePrinted,
		ISNULL(RBM.IsSupressLogo,0) AS IsSupressLogo,
		RBM.GroupTitle AS OrgGroupName,
		sFinanceCommon.fDefaultCurrencyTitleGet(OM.OrgGroupId) AS CurrencyTitle,
		ISNULL(SO.GenderId,0) AS GenderId,
		sFinanceCommon.fDefaultCurrencyCodeGet(OM.OrgGroupId) AS CurrencyCode,
		ISNULL(CGM.IsDisplayCashDetailInFolio,0) AS IsDisplayCashDetailInFolio,
		ISnull(CGM.IsOnPrePrinted,0) AS IsOnPrePrintedHeader,
			        
	         CASE
				 WHEN RBM.IsOnPrePrinted=1       
				 THEN 2
				 ELSE  ISNULL(RBM.FeeInvoiceHeaderDisplayId,1)
				END AS FeeInvoiceHeaderDisplayId,
       RBM.FeeInvoiceHeader
	  ,'' as PermanentStreetOne         -- #Start Mentis 29588
	  ,'' as PermanentStreetTwo
	  ,'' as PermanentStreetThree 
	  ,'' as PermanentCountry
	  ,'' as PermanentState
	  ,'' as PermanentCity
	  ,'' as PermanentZipCode
	  ,'' as PermanentContactNo 
	  ,'' as FatherName
	  ,'' as MotherName     
	  ,0 as AdmissionNumber 
	  ,SO.DateOfBirth  
	  , Convert(Decimal,0) as TotalAmount      
	  ,convert(varbinary(max),'') as StudentPhoto -- #End Mentis 29588
	  ,'' as PresentStreetOne    --#Start mentis - 0030332
	  ,'' as PresentStreetTwo
	  ,'' as PresentCity        
	  ,Convert(varbinary(max),'') as CertificateHeaderA4  --#End mentis - 0030332
	  ,Convert(date,'') AS BatchStartDate
	  ,Convert(date,'') AS BatchEndDate
  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,
				SA.AcademicId,
				SA.StudentId,
				SA.Name,
				SA.ClassId,
				SA.ClassName,
				SA.DivisionId,
				SA.DivisionName,
				SA.DivisionOrder,
				SA.RollNo,
				SA.Code,
				SA.DepartmentId,
				SA.DepartmentName,
				SA.BatchName,
				SA.OrgId,
				SA.OrgGroupBatchId,
				SA.AdmissionCategoryId,
				SA.StatusId
			    FROM sFee.tFeeSetup FS1
				INNER JOIN sStudent.vStudentAcademic SA ON SA.AdmissionCategoryId = FS1.AdmissionCategoryId AND SA.ClassId = FS1.ClassId
				WHERE FS1.ClassId=SA.ClassId AND FS1.AdmissionCategoryId=SA.AdmissionCategoryId AND IsOptional=0
				AND FS1.BatchId = SA.BatchId AND ((FS1.ReceiptBookId = @rReceiptBookId) OR (@rReceiptBookId=0))
				AND (ISNULL(SA.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')
				AND ((SA.ClassStatusId=@rClassStatusId) OR (@rClassStatusId=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,
				SA.AcademicId,
				SA.StudentId,
				SA.Name,
				SA.ClassId,
				SA.ClassName,
				SA.DivisionId,
				SA.DivisionName,
				SA.DivisionOrder,
				SA.RollNo,
				SA.Code,
				SA.DepartmentId,
				SA.DepartmentName,
				SA.BatchName,
				SA.OrgId,
				SA.OrgGroupBatchId,
				SA.AdmissionCategoryId,
				SA.StatusId
			FROM sFee.tFeeSetup FS1
			INNER JOIN sStudent.vStudentAcademic SA ON SA.AdmissionCategoryId = FS1.AdmissionCategoryId AND SA.ClassId = FS1.ClassId
			INNER JOIN sFee.tFeeOptional FO
				ON FO.FeeSetupId=FS1.Id AND (FO.SourceId=SA.AcademicId) AND(FO.SourceTypeId=2001)
			WHERE FS1.BatchId = SA.BatchId AND FS1.ClassId=SA.ClassId AND FS1.AdmissionCategoryId=SA.AdmissionCategoryId AND IsOptional=1 
			AND ((FS1.ReceiptBookId = @rReceiptBookId) OR (@rReceiptBookId=0))
			AND (ISNULL(SA.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')
			AND ((SA.ClassStatusId=@rClassStatusId) OR (@rClassStatusId=0))
		) FS ON FS.FeeId=FM.Id
		INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id = FM.FeeHeadId
		INNER JOIN sFee.tReceiptBookMaster RBM ON RBM.Id = FS.ReceiptBookId
		INNER JOIN sSetup.tOrgGroupMaster OGM ON OGM.Id = RBM.OrgGroupId
		LEFT JOIN sFee.tCollectionGroupMaster CGM ON CGM.Id = FS.CollectionGroupId 
		AND FS.OrgGroupBatchId = CGM.OrgGroupBatchId
		LEFT JOIN sSetup.tOrganizationMaster OM ON OM.Id=FS.OrgId
		LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId = FS.StudentId
		LEFT JOIN sFee.tFeeAllocation FA
			ON FA.FeeSetupId=FS.Id AND (FA.SourceId=FS.AcademicId) AND(FA.SourceTypeId=2001)
		
         LEFT JOIN sHostel.tAssignRoom AR ON  AR.SourceId=FS.StudentId AND AR.SourceTypeId=2003 AND ((FS.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  AND ((AR.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) 
         LEFT JOIN
	(SELECT AT.SourceId FROM sTransport.tAssignRoute AT 
    INNER JOIN sTransport.tBusRouteDestinationMaster BM ON BM.Id=AT.PickupDestinationId
    INNER JOIN sTransport.tBusRouteMaster B ON B.Id=BM.BusRouteId AND  AT.SourceTypeId=2003 AND ((B.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))) RT
    ON RT.SourceId = FS.StudentId AND ((FS.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) 
    
    LEFT  JOIN
	(
	    SELECT 
				ISNULL(SUM(RD.Amount),0) AS PaidAmount,
				RD.FeeSetupId,
				R.SourceId
	    FROM
				sFee.tReceipt R 
			INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id 
			INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id
			INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id
			INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=R.SourceId 
			INNER JOIN sFinanceCommon.tPayTypeMaster PTM ON PTM.Id = R.PayTypeId
			AND ((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
			AND (SA1.ClassId=@rClassId OR @rClassId=0) 
			AND (SA1.DivisionId=@rDivisionId OR @rDivisionId=0)
			
			--AND (R.ReceiptBookId=@rReceiptBookId OR @rReceiptBookId=0)
			--AND (R.CollectionGroupId=@rCollectionGroupId OR @rCollectionGroupId=0)
		WHERE		
			(R.SourceTypeId = 2001)
			AND (R.IsObsolete = 0) 
			AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
			AND (SA1.OrgGroupBatchId = @rOrgGroupBatchId)
			AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
			AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
			AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
			AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
			AND ((SA1.ClassStatusId=@rClassStatusId) OR (@rClassStatusId=0))
				GROUP BY FeeSetupId,R.SourceId--,R.ReceiptNumber,R.ReceiptDate,PTM.Title,R.ChequeNo,R.BankName,R.ChequeDate
	) R ON R.FeeSetupId = FS.Id AND FS.AcademicId = R.SourceId
    
WHERE 
		(FS.OrgGroupBatchId = @rOrgGroupBatchId)
		AND ((FS.OrgId=@rOrgId) OR (@rOrgId=0))	
		AND ((FS.BatchId=@rBatchId) OR (@rBatchId=0))	
		AND	((FS.AdmissionCategoryId = @rAdmissionCategoryId) OR (@rAdmissionCategoryId = 0))
		AND ((FS.ClassId = @rClassId) OR (@rClassId = 0))
		AND ((FS.DivisionId = @rDivisionId) OR (@rDivisionId = 0))	
		AND ((FS.StatusId=@rStatusId) OR (@rStatusId=0))
		AND ((FS.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
		AND ((FS.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
		AND ((FS.RollNo <= @rToRollNo) OR (@rToRollNo=0))
		AND ((FS.Code=@rCode) OR (@rCode=''))
		AND ((FS.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
		AND	((FS.ReceiptBookId = @rReceiptBookId) OR (@rReceiptBookId = 0))
		AND	((FS.CollectionGroupId = @rCollectionGroupId) OR (@rCollectionGroupId = 0))
		AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
		AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
		--AND ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00) > 0  
		AND ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00) > 0  
         AND (
			 (@rFilterId = 0) -- All
			 OR (@rFilterId = 2 AND isnull(AR.SourceId,0)!=0) -- Hostel
			 OR (@rFilterId = 3 AND isnull(RT.SourceId,0)!=0) -- Transport
			 OR ((@rFilterId =1) AND ((isnull(AR.SourceId,0)=0) AND (isnull(RT.SourceId,0)=0)))
			 ) 

		 end


END
GO
PRINT N'Altering Procedure [sFee].[pRptFeeSummaryPaytypewiseReportGet]...';


GO

ALTER PROCEDURE [sFee].[pRptFeeSummaryPaytypewiseReportGet]  
	@rReportId int=0,  
	@rIsFilter bit=0,  
	@rIsDisplayOrgGroup bit=0,
	@rOrgGroupBatchId int,  
	@rCommonBatch nvarchar(100)='',
	@rReceiptBookId int=0,  
	@rOrgId int,  
	@rBatchId int,
	@rDepartmentId int=0,  
	@rAdmissionCategoryId int=0,  
	@rClassId int=0,  
	@rDivisionId int=0, 
	@rFromDate date='',  
	@rToDate date='',  
	@rPaytypeId int=0, 
	@rCode nvarchar(20),
	@rFilterId int=0,  
	@rClassStatusId int=0 ,
	@rPayTypeIds nvarchar(max) = '',
	@rBuilder1 nvarchar(max)=0,  
    @rBuilder2 nvarchar(max)=0
	

 WITH EXECUTE AS CALLER  
AS  
SET NOCOUNT ON  
      
BEGIN   
   
 SELECT   
  @rBuilder1 AS Builder1,  
  @rBuilder2 AS Builder2,  
  @rIsFilter As IsFilter,  
  @rIsDisplayOrgGroup AS IsDisplayOrgGroup,
  RBM.Id AS ReceiptBookId,
  RBM.Title AS ReceiptBookTitle,
  RBM.FullTitle AS ReceiptBookFullTitle,
  SA.ClassId,  
  SA.ClassName,  
  SA.DivisionId,  
  SA.DivisionName,  
  SA.ClassName+' - '+SA.DivisionName AS ClassDivision,  
  SA.RollNo,  
  SA.Code,  
  SA.Name,  
  ISNULL(PTM.Title,'') AS PayType,  
  RD.Amount AS ReceiptDetailAmount,  
  R.ReceiptAmount  
  FROM   
   sFee.tReceipt R  
   INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id   
   INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.SourceId AND ((SA.OrgId=@rOrgId) OR (@rOrgId=0))  
   INNER JOIN sFinanceCommon.tPayTypeMaster PTM  ON PTM.Id=R.PayTypeId  
  INNER JOIN sFee.tReceiptBookMaster RBM   
   ON RBM.Id=R.ReceiptBookId
 LEFT JOIN sHostel.tAssignRoom AR ON  AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003 AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  AND ((AR.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0) AND (SA.OrgGroupBatchId = AR.OrgGroupBatchId))   
    LEFT JOIN  
 (SELECT AT.SourceId,B.OrgGroupBatchId FROM sTransport.tAssignRoute AT   
    INNER JOIN sTransport.tBusRouteDestinationMaster BM ON BM.Id=AT.PickupDestinationId   
    INNER JOIN sTransport.tBusRouteMaster B ON B.Id=BM.BusRouteId AND  AT.SourceTypeId=2003 AND ((B.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))) RT  
   ON RT.SourceId = SA.StudentId 
WHERE   
 R.SourceTypeId = 2001  
 AND ((SA.AdmissionCategoryId = @rAdmissionCategoryId) OR (@rAdmissionCategoryId = 0))  
 AND ((SA.ClassId = @rClassId) OR (@rClassId = 0))  
 AND ((SA.DivisionId = @rDivisionId) OR (@rDivisionId = 0))  
 AND ((R.ReceiptBookId = @rReceiptBookId) OR (@rReceiptBookId = 0))  
 AND ((R.ReceiptDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))  
 AND ((R.ReceiptDate <= @rToDate) OR (ISNULL(@rToDate,'') = ''))  
 AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  
 AND ((SA.OrgId=@rOrgId) OR (@rOrgId=0))  
 AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))  
 AND (SA.ClassStatusId=@rClassStatusId OR @rClassStatusId=0)  
 AND (R.PayTypeId = @rPaytypeId OR @rPaytypeId=0)  
 AND ((SA.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))  
 AND ((SA.Code=@rCode) OR (@rCode=''))  
 AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0)) 
  AND (  
  (@rFilterId = 0) -- All  
     OR (@rFilterId = 2 AND isnull(AR.SourceId,0)!=0) -- Hostel  
     OR (@rFilterId = 3 AND isnull(RT.SourceId,0)!=0) -- Transport  
     OR ((@rFilterId =1) AND ((isnull(AR.SourceId,0)=0) AND (isnull(RT.SourceId,0)=0)))  
    )  
 AND (ISNULL(R.PayTypeId,0) IN (SELECT cast(item as tinyint) FROM sCommon.fnsplit(@rPayTypeIds,',')) OR @rPayTypeIds='')
 AND R.IsObsolete = 0
  
 ORDER BY R.ReceiptNumber  

END
GO
PRINT N'Altering Procedure [sHrm].[pHoliDayCountGet]...';


GO

ALTER PROCEDURE [sHrm].[pHoliDayCountGet]
	
	@rForMonth int=0,
	@rForYear int=0,
	@rBatchId int=0,
	@rOrgId int=0,
	--@rClassId int=0,
	@rEmployeeId bigint=0,
	@rDepartmentId int=0
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
	CREATE table #Table1 (Id bigint identity,FromDate Date,ToDate Date,SourceId bigint,IsExists bit)
	
	CREATE table #Table2 (Id bigint identity,FromDate Date,ToDate Date,SourceId bigint)
	
	INSERT INTO #Table2 
						SELECT ES.FromDate,ES.ToDate,EA.SourceId FROM sActivity.tEventSchedule ES 
						INNER JOIN  sActivity.tEventAssign EA ON EA.EventScheduleId=ES.Id 
						INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id=EA.SourceId 
						INNER JOIN sHrm.vEmployeeCommunication EC ON EC.DepartmentId=DM.Id 				   
						WHERE ((ES.BatchId=@rBatchId)) 
						AND ((MONTH(ES.FromDate)<=@rForMonth) 
						AND (YEAR(ES.FromDate)=@rForYear))
						AND ((MONTH(ES.ToDate)>=@rForMonth) 
						AND (YEAR(ES.ToDate)=@rForYear)) 
						AND ES.IsHoliday=1 
						AND EA.SourceTypeId  = 2004
						AND ((EC.EmployeeId = @rEmployeeId) OR (@rEmployeeId = 0))
						GROUP BY ES.FromDate,ES.ToDate,EA.SourceId
					   
						UNION ALL
					   
						SELECT ES.FromDate,ES.ToDate,EA.SourceId FROM sActivity.tEventSchedule ES 
						INNER JOIN  sActivity.tEventAssign EA ON EA.EventScheduleId=ES.Id 			    
						INNER JOIN sHrm.vEmployeeCommunication EC ON EC.EmployeeId=EA.SourceId 
						WHERE ((ES.BatchId=@rBatchId)) 
						AND ((MONTH(ES.FromDate)<=@rForMonth) 
						AND (YEAR(ES.FromDate)=@rForYear))
						AND ((MONTH(ES.ToDate)>=@rForMonth) 
						AND (YEAR(ES.ToDate)=@rForYear)) 
						AND ES.IsHoliday=1 
						AND EA.SourceTypeId =95
						AND (EC.EmployeeId=@rEmployeeId OR (@rEmployeeId=0))
						GROUP BY ES.FromDate,ES.ToDate,EA.SourceId 
	  
	INSERT INTO #Table1 
	select FromDate,ToDate,Max(SourceId),0
	from
	( 
	SELECT case when MONTH(FromDate)=@rForMonth then FromDate
				when MONTH(FromDate)<>@rForMonth and MONTH(ToDate)=@rForMonth then DATEADD(DD,-Day(ToDate)+1,ToDate)
				when MONTH(FromDate)<@rForMonth and MONTH(ToDate)>@rForMonth then cast(rtrim(@rForYear *10000+ @rForMonth *100+ 01) as date) --mantis:28433
				else FromDate end as FromDate,
				ToDate,
				SourceId	
	From #Table2
	GROUP BY  FromDate,ToDate,SourceId
	)As Tmp
	GROUP BY  Tmp.FromDate,Tmp.ToDate,Tmp.SourceId
	--select * from #Table2 
	--select * from #Table1
	DECLARE @lTempCount int=0
	SELECT @lTempCount = count(Id) from #Table1
	WHILE @lTempCount > 0 
	BEGIN
		DECLARE @lFromDate Date,@lToDate Date

		SELECT @lFromDate = FromDate, @lToDate = ToDate FROM #Table1 WHERE Id=@lTempCount
		IF EXISTS(SELECT 1 FROM #Table1 WHERE Id <> @lTempCount AND ((@lFromDate between FromDate and ToDate) AND (@lToDate between FromDate and ToDate)))
		BEGIN
			UPDATE #Table1 SET IsExists = 1 WHERE Id = @lTempCount	
		END
		SET @lTempCount = @lTempCount - 1
	END
	 
	DECLARE @lCount int
	SELECT @lCount = count(Id) from #Table1
	DECLARE @lStatus nvarchar(5),@lFromYear int,@lFromMonth int,@lFromDay int,@lSourceId bigint,@lToYear int,@lToMonth int,@lToDay int
	DECLARE @lHoliDayCount int,@lBeginCount int ,@lEndCount int , @lTotalMonth int 
	SET @lHoliDayCount =0
	
		WHILE @lCount > 0 
					BEGIN
						SELECT
							@lFromYear = YEAR(FromDate),
							@lFromMonth = MONTH(FromDate),
							@lFromDay = DAY(FromDate),
							@lToYear = YEAR(ToDate),
							@lToMonth = MONTH(ToDate),
							@lToDay = DAY(ToDate),
							@lSourceId = SourceId,
							@lBeginCount = DAY(FromDate),
							@lEndCount = DAY(ToDate)
						FROM #Table1 T WHERE Id = @lCount AND IsExists = 0
					
						IF(@lFromDay = @lToDay  AND @lFromMonth = @lToMonth)
						BEGIN
							
							--SELECT @lStatus = [sAttendance].[fWeekHOffGet]
							--(@lFromYear,@lFromMonth,@lFromDay,@rBatchId,0,@lSourceId,'',@rOrgId)
							--SELECT @lStatus = [sHrm].[fAttendanceWithLeaveGet](@lSourceId,@lFromYear,@lFromMonth,@lFromDay,@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-'+CONVERT(NVARCHAR(2),@lFromDay))),'','',0)
							--this function is created for mantisid -- 29177 
							-- if Holiday is weekoff then display Holiday instead of weekoff for that comment above function and create new function
							SELECT @lStatus = [sHrm].[fAttendanceWithEMPLeaveGet](@lSourceId,@lFromYear,@lFromMonth,@lFromDay,@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-'+CONVERT(NVARCHAR(2),@lFromDay))),'','',0)
							IF(@lStatus = 'H')SET @lHoliDayCount=@lHoliDayCount+1
							
							
						END
						ELSE IF(@lFromDay != @lToDay)
						BEGIN
							IF(@lFromMonth = @lToMonth)
							BEGIN
								WHILE (@lBeginCount <= @lEndCount)
								BEGIN
								  
									--SELECT @lStatus = [sAttendance].[fWeekHOffGet] 	(@lFromYear,@lFromMonth,@lFromDay,@rBatchId,0,@lSourceId,'',@rOrgId)
									--SELECT @lStatus = [sHrm].[fAttendanceWithLeaveGet](@lSourceId,@lFromYear,@lFromMonth,@lBeginCount,@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-'+CONVERT(NVARCHAR(2),@lFromDay))),'','',0)
									--this function is created for mantisid -- 29177 
									-- if Holiday is weekoff then display Holiday instead of weekoff for that comment above function and create new function
									SELECT @lStatus = [sHrm].[fAttendanceWithEMPLeaveGet](@lSourceId,@lFromYear,@lFromMonth,@lBeginCount,@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-'+CONVERT(NVARCHAR(2),@lFromDay))),'','',0)
									IF(@lStatus = 'H')
										SET @lHoliDayCount=@lHoliDayCount+1
									
									SET @lBeginCount = @lBeginCount +1	
							   END
							END
							ELSE
							BEGIN
								SET @lTotalMonth = @lToMonth - @lFromMonth
								 WHILE (@lTotalMonth > 0 AND @rForMonth=@lFromMonth)
								 BEGIN
									 DECLARE @lDays int = 0
									 SELECT @lDays = sCommon.fGetDaysInMonth(@lFromMonth,@lFromYear)
									 WHILE (@lBeginCount  <= @lDays)
									 BEGIN
										
										--SELECT @lStatus = [sHrm].[fAttendanceWithLeaveGet](@lSourceId,@lFromYear,@lFromMonth,@lBeginCount,@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-'+CONVERT(NVARCHAR(2),@lFromDay))),'','',0)
										--this function is created for mantisid -- 29177 
										-- if Holiday is weekoff then display Holiday instead of weekoff for that comment above function and create new function
										SELECT @lStatus = [sHrm].[fAttendanceWithEMPLeaveGet](@lSourceId,@lFromYear,@lFromMonth,@lBeginCount,@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-'+CONVERT(NVARCHAR(2),@lFromDay))),'','',0)
										IF(@lStatus = 'H')
											SET @lHoliDayCount=@lHoliDayCount+1
											
										SET @lBeginCount = @lBeginCount +1
									END
									SET @lTotalMonth = @lTotalMonth-1
								 END
							END
						END
						SET @lCount = @lCount - 1
					END
	SELECT @lHoliDayCount
	DROP TABLE #Table1
	DROP TABLE #Table2
END
GO
PRINT N'Altering Procedure [sHrm].[pRptEmployeeAttendanceGet]...';


GO
 
ALTER PROCEDURE [sHrm].[pRptEmployeeAttendanceGet]
	 
	@rBuilder1 nvarchar(max)='',
	@rBuilder2 nvarchar(max)='',
	@rEmployeeName nvarchar(200),
	@rEmployeeCode nvarchar (200),
	@rEmployeeId bigint,
	@rDepartmentId int,
	@rEmployeeGradeId int,
	@rForYear  smallint,
	@rForMonth tinyint,
	@rBatchId int,
	@rOrgId int,
	@rEmployeeStatusId int = 0
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
       SELECT 
			 @rBuilder1 AS Builder1,
			 @rBuilder2 AS Builder2, 
			 EM.Code AS EmployeeCode,
			 EM.EmployeeName,   
			 EM.EmployeeId,
			 EM.DepartmentName,
			 EM.EmployeeGrade,      
			 ISNULL(WD.TotalDays,ISNULL(AT.TotalWorkingDays,0)) As TotalDays,
			 ISNULL(AT.TotalWorkingDays,ISNULL(WD.WorkingDays,0)) AS WorkingDays, 
			 ISNULL(AT.LWP,0) AS LWP,
			-- CONVERT(INT,(ISNULL(AT.TotalWorkingDays,0) - ISNULL(AT.LWP,0))) AS PresentDays,
			 (ISNULL(AT.TotalWorkingDays,0) - (ISNULL(AT.LWP,0) + ISNULL(AT.PaidLeave,0))) AS PresentDays,
			 MM.Title AS MonthName,
			 AT.ForYear As YearName,			
			 --L.LeaveReason,
			 --L.NoOfLeave,
			 --L.ReportDate,
			 --L.FromDate,
			 --L.ToDate,
			 --LPM.Title As LeavePeriod,
			 --LTM.Title As LeaveType,
			 --LTM.IsCarryForward,
			 --LTM.IsLWP
			  EM.EmployeeDesignation As Designation -- Mantis 0030721
			 
        FROM 
			sHrm.vEmployeeCommonDetail EM 
			LEFT JOIN sHrm.tEmployeeAttendance AT ON AT.EmployeeId=EM.EmployeeId
			LEFT JOIN sCommon.tMonthMaster MM ON MM.Id=AT.ForMonth
			LEFT JOIN sHrm.tWorkingDays WD ON  EM.EmployeeGradeId = WD.EmployeeGradeId
			AND WD.ForMonth=@rForMonth AND WD.ForYear=@rForYear AND WD.BatchId = @rBatchId			
			
			--INNER JOIN sHrm.tLeave L ON L.EmployeeId = EM.EmployeeId
			--INNER JOIN sHrm.tLeavePeriodMaster LPM ON LPM.Id=L.LeavePeriodId
			--INNER JOIN sHrm.tLeaveTypeMaster LTM ON LTM.Id=L.LeaveTypeId
    	WHERE 
    			EM.OrgID = @rOrgId 
    		AND (AT.BatchId=@rBatchId)
    		AND ((AT.ForMonth=@rForMonth) OR (@rForMonth=0))
    		AND ((AT.ForYear=@rForYear) OR (@rForYear=0))
    		AND ((EM.EmployeeGradeId=@rEmployeeGradeId) OR (@rEmployeeGradeId=0))
    		AND ((EM.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
    		AND ((EM.Code like @rEmployeeCode) OR (@rEmployeeCode=''))
    		AND ((EM.EmployeeName like @rEmployeeName) OR (@rEmployeeName=''))
    		AND ((EM.EmployeeId=@rEmployeeId) OR (@rEmployeeId=0))
    		AND ((EM.EmployeeStatusId=@rEmployeeStatusId) OR (@rEmployeeStatusId=0))
    		--AND ((L.FromDate>=@rFromDate) OR (ISNULL(@rFromDate,'')=''))
    		--AND ((L.ToDate>=@rToDate) OR (ISNULL(@rToDate,'')=''))
    		AND EM.IsOtherUser = 0
    		ORDER BY EM.Number
    		
END
GO
PRINT N'Altering Procedure [sHrm].[pRptEmployeeAttendanceRegisterGet]...';


GO

ALTER PROCEDURE [sHrm].[pRptEmployeeAttendanceRegisterGet]
	 
		@rBuilder1 nvarchar(max)='',
		@rBuilder2 nvarchar(max)='',
		@rEmployeeName nvarchar(200),
		@rEmployeeCode nvarchar (200),
		@rEmployeeId bigint,
		@rDepartmentId int,
		@rEmployeeGradeId int,
		@rForYear  smallint,
		@rForMonth tinyint,
		@rBatchId int,
		@rOrgId int,
		@rStatusId smallint=0,
		@rEmployeeStatusId int = 0,
		@rFromNumber int = NULL,
		@rToNumber int = NULL
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 

DECLARE @li int 
SET @li=1
Declare @ldate datetime,@lDays int
declare @Days int
Declare @Firstdate datetime
Declare @Lastdate datetime

		
Set @ldate= CONVERT(nvarchar(10), @rForYear)+ '-' +  CONVERT(nvarchar(10), @rForMonth) + '-' + CONVERT(nvarchar(10), 01)
Select @lDays=day(dateadd(mm,DateDiff(mm, -1, @ldate),0) -1) 
select @Days=sCommon.fGetDaysInMonth(@rForMonth,@rForYear)
		
set @Firstdate=CONVERT(nvarchar(10), @rForYear)+ '-' +  CONVERT(nvarchar(10), @rForMonth) + '-' + CONVERT(nvarchar(10), 01)
set @Lastdate=CONVERT(nvarchar(10), @rForYear)+ '-' +  CONVERT(nvarchar(10), @rForMonth) + '-' + CONVERT(nvarchar(10), @Days)
		
CREATE Table #EmployeeAttendanceRegistertempTable
(
	 
	EmployeeCode nvarchar(50),
	EmployeeId bigint,
	EmployeeName nvarchar(100),
	ForYear int,
	ForMonth int,
	ForMonthInWord nvarchar(100),
	DepartmentId int,
	DepartmentName nvarchar(50),
	IsPresent bit,
	DayPart int,
	AttendanceDate date,
	DateOfJoining date,
	DateOfLeaving  date,
	AttendanceTagId int ,
	Number int ,
	IsOtherUser smallint,
	EmployeeGrade nvarchar(500),
	Code nvarchar(200),
	LeaveCount decimal(12,2),
	LeaveType nvarchar(100), 
	WorkingDays tinyint,
	HoliDays tinyint 
 
)
Insert INTO #EmployeeAttendanceRegistertempTable
(	
	EmployeeCode ,
	EmployeeId ,
	EmployeeName,
	ForYear ,
	ForMonth,
	ForMonthInWord,
	DepartmentId ,
	DepartmentName ,
	IsPresent ,
	DayPart ,
	AttendanceDate ,
	DateOfJoining ,
	DateOfLeaving ,
	AttendanceTagId,
	Number,
	IsOtherUser,
	EmployeeGrade,
	Code,
	LeaveCount,
	LeaveType , 
	WorkingDays ,
	HoliDays  
)
SELECT  
		EM.Code AS EmployeeCode,
		EM.EmployeeId AS EmployeeId,
		EM.EmployeeName,
		YEAR(EAR.AttendanceDate) AS ForYear,
		MONTH(EAR.AttendanceDate) AS ForMonth,
		DATENAME(month, EAR.AttendanceDate) AS ForMonthInWord,
		EM.DepartmentId,
		EM.DepartmentName,
		EAR.IsPresent,
		day(EAR.AttendanceDate) AS DayPart,
		EAR.AttendanceDate,
		EJD.DateOfJoining,
		EJD.DateOfLeaving,
			EAR.AttendancetagId,
		EM.Number,
		EM.IsOtherUser,
		EM.EmployeeGrade,
		LTM.Code,
		(SELECT ISNULL(SUM(CONVERT(decimal(12,2),  '.'+PARSENAME(NoOfLeave,1))),0) FROM sHrm.tLeave WHERE LeaveTypeId = LTM.Id AND FromDate BETWEEN @FirstDate AND @LastDate AND StatusId!=551 AND OrgId = @rOrgId AND BatchId = @rBatchId AND EmployeeId = EM.EmployeeId) AS LeaveCount,
		LTM.Title AS LeaveType , 
		WD.WorkingDays ,
		WD.HoliDays  

	FROM 

		sHrm.vEmployeeCommonDetail EM 
		INNER JOIN sHrm.tEmployeeMaster E ON E.Id = EM.EmployeeId
		INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.EmployeeId
		INNER JOIN sHrm.tWorkingDays WD ON  EM.EmployeeGradeId = WD.EmployeeGradeId
		AND WD.ForMonth=@rForMonth AND WD.ForYear=@rForYear AND WD.BatchId = @rBatchId
		LEFT JOIN sHrm.tEmployeeAttendanceRegister EAR ON EAR.EmployeeId = EM.EmployeeId AND (EAR.BatchId = @rBatchId)
		AND MONTH(EAR.AttendanceDate)=@rForMonth AND YEAR(EAR.AttendanceDate)=@rForYear
		INNER JOIN sHrm.tLeaveTypeMaster LTM ON E.OrgID=LTM.OrgId AND LTM.IsObsolete=0	
	WHERE 
			EM.OrgID = @rOrgId 
    		AND ((EM.EmployeeGradeId=@rEmployeeGradeId) OR (@rEmployeeGradeId=0))
    		AND ((EM.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
    		AND ((EM.Code like @rEmployeeCode) OR (@rEmployeeCode=''))
    		AND ((EM.EmployeeName like @rEmployeeName) OR (@rEmployeeName=''))
    		AND ((EM.EmployeeId=@rEmployeeId) OR (@rEmployeeId=0))
    		AND ((EM.EmployeeStatusId=@rStatusId) OR (@rStatusId=0))
    		AND ((EM.EmployeeStatusId=@rEmployeeStatusId) OR (@rEmployeeStatusId=0))
    		AND (EM.DateOfJoining<= @Lastdate OR ISNULL(EM.DateOfJoining,'')='')
    		AND (EM.DateOfleaving>= @Firstdate OR ISNULL(EM.DateOfleaving,'')='')
			AND EM.IsOtherUser = 0
			AND (EM.Number >= @rFromNumber OR @rFromNumber IS NULL) AND (EM.Number <= @rToNumber OR @rToNumber IS NULL)
			ORDER BY EM.Number

CREATE TABLE #TempDaysTempTable
(
 DayPart int
 )
WHILE @li<=@Days

BEGIN

INSERT INTO #TempDaysTempTable
(
	DayPart 
)

SELECT 
@li AS DayPart
SET @li = @li + 1

END

		
			SELECT 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2, 
			Number,
			isnull(EmployeeCode,'') as EmployeeCode,
			PivotTable.EmployeeId,
			isnull(EmployeeName,'') as EmployeeName,   
			DepartmentName,
			EmployeeGrade,      
		   	sCommon.fGetDaysInMonth (@rForMonth,@rForYear) AS TotalDays,
			[sHrm].[fAttendanceWithApproveLeaveGet](PivotTable.EmployeeId,@rForYear,@rForMonth,'01',@rBatchId,DepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-01')),DateOfJoining,DateOfLeaving,[1]) AS P1,
			[sHrm].[fAttendanceWithApproveLeaveGet](PivotTable.EmployeeId,@rForYear,@rForMonth,'02',@rBatchId,DepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-02')),DateOfJoining,DateOfLeaving,[2]) AS P2,
			[sHrm].[fAttendanceWithApproveLeaveGet](PivotTable.EmployeeId,@rForYear,@rForMonth,'03',@rBatchId,DepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-03')),DateOfJoining,DateOfLeaving,[3]) AS P3,
			[sHrm].[fAttendanceWithApproveLeaveGet](PivotTable.EmployeeId,@rForYear,@rForMonth,'04',@rBatchId,DepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-04')),DateOfJoining,DateOfLeaving,[4])  AS P4,
			[sHrm].[fAttendanceWithApproveLeaveGet](PivotTable.EmployeeId,@rForYear,@rForMonth,'05',@rBatchId,DepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-05')),DateOfJoining,DateOfLeaving,[5]) AS P5,
			[sHrm].[fAttendanceWithApproveLeaveGet](PivotTable.EmployeeId,@rForYear,@rForMonth,'06',@rBatchId,DepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-06')),DateOfJoining,DateOfLeaving,[6]) AS P6,
			[sHrm].[fAttendanceWithApproveLeaveGet](PivotTable.EmployeeId,@rForYear,@rForMonth,'07',@rBatchId,DepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-07')),DateOfJoining,DateOfLeaving,[7])  AS P7,
			[sHrm].[fAttendanceWithApproveLeaveGet](PivotTable.EmployeeId,@rForYear,@rForMonth,'08',@rBatchId,DepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-08')),DateOfJoining,DateOfLeaving,[8]) As P8,
			[sHrm].[fAttendanceWithApproveLeaveGet](PivotTable.EmployeeId,@rForYear,@rForMonth,'09',@rBatchId,DepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-09')),DateOfJoining,DateOfLeaving,[9]) AS P9,
			[sHrm].[fAttendanceWithApproveLeaveGet](PivotTable.EmployeeId,@rForYear,@rForMonth,'10',@rBatchId,DepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-10')),DateOfJoining,DateOfLeaving,[10]) AS P10,
			[sHrm].[fAttendanceWithApproveLeaveGet](PivotTable.EmployeeId,@rForYear,@rForMonth,'11',@rBatchId,DepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-11')),DateOfJoining,DateOfLeaving,[11]) AS P11,
			[sHrm].[fAttendanceWithApproveLeaveGet](PivotTable.EmployeeId,@rForYear,@rForMonth,'12',@rBatchId,DepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-12')),DateOfJoining,DateOfLeaving,[12]) AS P12,
			[sHrm].[fAttendanceWithApproveLeaveGet](PivotTable.EmployeeId,@rForYear,@rForMonth,'13',@rBatchId,DepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-13')),DateOfJoining,DateOfLeaving,[13]) AS P13,
			[sHrm].[fAttendanceWithApproveLeaveGet](PivotTable.EmployeeId,@rForYear,@rForMonth,'14',@rBatchId,DepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-14')),DateOfJoining,DateOfLeaving,[14]) AS P14,
			[sHrm].[fAttendanceWithApproveLeaveGet](PivotTable.EmployeeId,@rForYear,@rForMonth,'15',@rBatchId,DepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-15')),DateOfJoining,DateOfLeaving,[15]) AS P15,
			[sHrm].[fAttendanceWithApproveLeaveGet](PivotTable.EmployeeId,@rForYear,@rForMonth,'16',@rBatchId,DepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-16')),DateOfJoining,DateOfLeaving,[16])  AS P16,
			[sHrm].[fAttendanceWithApproveLeaveGet](PivotTable.EmployeeId,@rForYear,@rForMonth,'17',@rBatchId,DepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-17')),DateOfJoining,DateOfLeaving,[17]) AS P17,
			[sHrm].[fAttendanceWithApproveLeaveGet](PivotTable.EmployeeId,@rForYear,@rForMonth,'18',@rBatchId,DepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-18')),DateOfJoining,DateOfLeaving,[18])  AS P18,
			[sHrm].[fAttendanceWithApproveLeaveGet](PivotTable.EmployeeId,@rForYear,@rForMonth,'19',@rBatchId,DepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-19')),DateOfJoining,DateOfLeaving,[19])  AS P19,
			[sHrm].[fAttendanceWithApproveLeaveGet](PivotTable.EmployeeId,@rForYear,@rForMonth,'20',@rBatchId,DepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-20')),DateOfJoining,DateOfLeaving,[20])  AS P20,
			[sHrm].[fAttendanceWithApproveLeaveGet](PivotTable.EmployeeId,@rForYear,@rForMonth,'21',@rBatchId,DepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-21')),DateOfJoining,DateOfLeaving,[21]) AS P21,
			[sHrm].[fAttendanceWithApproveLeaveGet](PivotTable.EmployeeId,@rForYear,@rForMonth,'22',@rBatchId,DepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-22')),DateOfJoining,DateOfLeaving,[22]) AS P22,
			[sHrm].[fAttendanceWithApproveLeaveGet](PivotTable.EmployeeId,@rForYear,@rForMonth,'23',@rBatchId,DepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-23')),DateOfJoining,DateOfLeaving,[23]) AS P23,
			[sHrm].[fAttendanceWithApproveLeaveGet](PivotTable.EmployeeId,@rForYear,@rForMonth,'24',@rBatchId,DepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-24')),DateOfJoining,DateOfLeaving,[24]) AS P24,
			[sHrm].[fAttendanceWithApproveLeaveGet](PivotTable.EmployeeId,@rForYear,@rForMonth,'25',@rBatchId,DepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-25')),DateOfJoining,DateOfLeaving,[25]) AS P25,
			[sHrm].[fAttendanceWithApproveLeaveGet](PivotTable.EmployeeId,@rForYear,@rForMonth,'26',@rBatchId,DepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-26')),DateOfJoining,DateOfLeaving,[26]) AS P26,
			[sHrm].[fAttendanceWithApproveLeaveGet](PivotTable.EmployeeId,@rForYear,@rForMonth,'27',@rBatchId,DepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-27')),DateOfJoining,DateOfLeaving,[27]) AS P27,
			[sHrm].[fAttendanceWithApproveLeaveGet](PivotTable.EmployeeId,@rForYear,@rForMonth,'28',@rBatchId,DepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-28')),DateOfJoining,DateOfLeaving,[28]) AS P28,
			CASE WHEN @Days>=29 THEN[sHrm].[fAttendanceWithApproveLeaveGet](PivotTable.EmployeeId,@rForYear,@rForMonth,'29',@rBatchId,DepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-29')),DateOfJoining,DateOfLeaving,[29]) end AS P29,
			CASE WHEN @Days>=30 THEN[sHrm].[fAttendanceWithApproveLeaveGet](PivotTable.EmployeeId,@rForYear,@rForMonth,'30',@rBatchId,DepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-30')),DateOfJoining,DateOfLeaving,[30])end AS P30,
			CASE WHEN @Days>=31 THEN[sHrm].[fAttendanceWithApproveLeaveGet](PivotTable.EmployeeId,@rForYear,@rForMonth,'31',@rBatchId,DepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-31')),DateOfJoining,DateOfLeaving,[31])end AS P31,
			Code,
			LeaveCount,
			LeaveType , 
			WorkingDays ,
			HoliDays  
			FROM
(
	Select  
		EmployeeCode,
		EmployeeId,
		EmployeeName,
		YEAR(ST.AttendanceDate) AS ForYear,
		MONTH(ST.AttendanceDate) AS ForMonth,
		DATENAME(month, ST.AttendanceDate) AS ForMonthInWord,
		DepartmentId,
		DepartmentName,
		(
			CASE 
				  WHEN IsPresent = 1 AND ST.AttendanceTagId = 1 THEN 'LA' 
				  WHEN IsPresent = 1 AND ST.AttendanceTagId = 2 THEN 'ED' 
			      WHEN IsPresent = 1  THEN 'P' 
				  WHEN IsPresent = 0 THEN 'A'
				END 
		)AS  IsPresent,		
		day(ST.AttendanceDate) AS DayPart,
		DateOfLeaving,		 
		DateOfJoining,
		Number,
		EmployeeGrade,
		Code,
		LeaveCount	,
		LeaveType , 
		WorkingDays ,
		HoliDays 
	 FROM 
		#EmployeeAttendanceRegistertempTable ST 
		LEFT JOIN #TempDaysTempTable DT ON DT.DayPart = ST.DayPart
	 WHERE 
		  ((DateOfLeaving >= @FirstDate) OR ISNULL(DateOfLeaving,'') = '')
		  AND IsOtherUser = 0
	   -- WHERE 
	   -- ForYear=@rForYear AND ForMonth=@rForMonth
) AS SourceTable 
	           
	        
PIVOT
(	
MIN(IsPresent)
FOR DayPart IN ([0], [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])
) AS PivotTable
	LEFT JOIN
	(
		Select  EmployeeId AS EmployeeId, COUNT(1) AS TCount 
		   FROM  
				#EmployeeAttendanceRegistertempTable
				WHERE AttendanceDate < (convert(date,CONVERT(nvarchar(10), @rForYear)+ '/' +  CONVERT(nvarchar(10), @rForMonth) + '/' + '01' ))
		     GROUP BY  EmployeeId 
    ) TC ON TC.EmployeeId = PivotTable.EmployeeId 
	LEFT JOIN
	(
		Select EmployeeId AS EmployeeId, COUNT(1) AS ACount 
		   FROM  #EmployeeAttendanceRegistertempTable
		    WHERE   IsPresent = 0	 	 
		      AND AttendanceDate < (convert(date,CONVERT(nvarchar(10), @rForYear)+ '/' +  CONVERT(nvarchar(10), @rForMonth) + '/' + '01' ))
			GROUP BY  EmployeeId
    ) AC ON AC.EmployeeId = PivotTable.EmployeeId
	LEFT JOIN
	(
		SELECT EJD.EmployeeId, COUNT(1) AS PCount  FROM 
		
		sHrm.vEmployeeCommonDetail EM 
		INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.EmployeeId
		INNER JOIN sHrm.tWorkingDays WD ON  EM.EmployeeGradeId = WD.EmployeeGradeId
		AND WD.ForMonth=@rForMonth AND WD.ForYear=@rForYear AND WD.BatchId = @rBatchId
		LEFT JOIN sHrm.tEmployeeAttendanceRegister EAR ON EAR.EmployeeId = EM.EmployeeId AND (EAR.BatchId = @rBatchId)
		AND MONTH(EAR.AttendanceDate)=@rForMonth AND YEAR(EAR.AttendanceDate)=@rForYear
	   
			WHERE   
	
	    ((EM.OrgId=@rOrgId) OR (@rOrgId= 0))
	       AND ((EM.DepartmentId = @rDepartmentId)OR (@rDepartmentId=0))
	       AND ((EAR.BatchId=@rBatchId) OR (@rBatchId= 0))
	       AND EAR.AttendanceDate < (convert(date,CONVERT(nvarchar(10), @rForYear)+ '/' +  CONVERT(nvarchar(10), @rForMonth) + '/' + '01' ))
		   AND EM.IsOtherUser = 0
	 GROUP BY EJD.EmployeeId 
    ) PC ON PC.EmployeeId = PivotTable.EmployeeId
		
	Order By PivotTable.Number	
			--FROM
			--sHrm.vEmployeeCommonDetail EM
			--INNER JOIN sHrm.tEmployeeMaster E ON E.Id = EM.EmployeeId				
			--INNER JOIN sHrm.tLeaveTypeMaster LTM ON E.OrgID=LTM.OrgId						
			
   -- 		WHERE 
   -- 		EM.OrgID = @rOrgId 
   -- 		AND ((EM.EmployeeGradeId=@rEmployeeGradeId) OR (@rEmployeeGradeId=0))
   -- 		AND ((EM.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
   -- 		AND ((EM.Code like @rEmployeeCode) OR (@rEmployeeCode=''))
   -- 		AND ((EM.EmployeeName like @rEmployeeName) OR (@rEmployeeName=''))
   -- 		AND ((EM.EmployeeId=@rEmployeeId) OR (@rEmployeeId=0))
   -- 		AND ((EM.EmployeeStatusId=@rStatusId) OR (@rStatusId=0))
   -- 		AND ((EM.EmployeeStatusId=@rEmployeeStatusId) OR (@rEmployeeStatusId=0))
   -- 		AND (EM.DateOfJoining<= @Lastdate OR ISNULL(EM.DateOfJoining,'')='')
   -- 		AND (EM.DateOfleaving>= @Firstdate OR ISNULL(EM.DateOfleaving,'')='')
   -- 		--AND ((ISNULL(EM.DateOfJoining,''))<=CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-'+CONVERT(NVARCHAR(2),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)))))			
			--AND EM.IsOtherUser = 0
			--AND E.Number>=@rFromNumber AND E.Number<=@rToNumber

			--SELECT 
			--	'' as [Builder1]
			--	,'' as [Builder2]
			--	,convert(bigint,0) as [Number]
   --   ,'' as [EmployeeCode]
   --   ,convert(bigint,0)  as [EmployeeId]
   --   ,'' as [EmployeeName]
   --   ,'' as [DepartmentName]
   --   ,'' as [EmployeeGrade]
   --   ,0 as [TotalDays]
   --   ,'' as [P1]
   --   ,'' as [P2]
   --   ,'' as [P3]
   --   ,'' as [P4]
   --   ,'' as [P5]
   --   ,'' as [P6]
   --   ,'' as [P7]
   --   ,'' as [P8]
   --   ,'' as [P9]
   --   ,'' as [P10]
   --   ,'' as [P11]
   --   ,'' as [P12]
   --   ,'' as [P13]
   --   ,'' as [P14]
   --   ,'' as [P15]
   --   ,'' as [P16]
   --   ,'' as [P17]
   --   ,'' as [P18]
   --   ,'' as [P19]
   --   ,'' as [P20]
   --   ,'' as [P21]
   --   ,'' as [P22]
   --   ,'' as [P23]
   --   ,'' as [P24]
   --   ,'' as [P25]
   --   ,'' as [P26]
   --   ,'' as [P27]
   --   ,'' as [P28]
   --   ,'' as [P29]
   --   ,'' as [P30]
   --   ,'' as [P31]
   --   ,'' as [Code]
   --   ,0 as [LeaveCount]
   --   ,'' as [LeaveType] 
	  --,convert(tinyint,0) as [WorkingDays] 
	  --,convert(tinyint,0) as [HoliDays]  
 
drop table #EmployeeAttendanceRegistertempTable	  
drop table #TempDaysTempTable
END
GO
PRINT N'Altering Procedure [sMis].[pRptResultAnalysisExamWiseGet]...';


GO
ALTER PROCEDURE [sMis].[pRptResultAnalysisExamWiseGet]
	 
		@rBuilder1 nvarchar(max)='',
		@rBuilder2 nvarchar(max)='', 
		
		@rOrgGroupBatchId int,
		@rExamId int,
		@rStrOrgMainGroupId nvarchar(max),
		@rStrOrgSubGroupId nvarchar(max),
		@rStrOrgId nvarchar(max),
		@rStrDepartmentId nvarchar(max),
		@rStrClassId nvarchar(max)
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
--Select 
--		0 AS OrgMainGroupId,
--	    '' AS OrgMainGroupName,
--		0 AS OrgSubGroupId,
--		'' AS SubGroupName,
--		'' AS OrgName,
--		0 AS DepartmentId,
--		0 AS OrgId,
--		'' AS Code,
--		'' AS Name,
--		0 AS RollNo,
--		0 AS AcademicId,			
--		'' AS Class,
--		0 As ClassId,
--		'' AS Division,
--		0 AS DivisionId,
--		'' AS Exam,
--		0 AS SubjectId,	
--		'' AS SubjectCode,
--		'' AS SubjectName,
--		--RD.SubjectGrade,
--		--R.ResultGrade,
--		--BM.OrgGroupBatchId,
--		--RD.Obtain,
--		'' AS SubjectGrade,
--		--R.Percentage,
--		'' AS ResultGrade,
--		@rExamId AS ExamId


			
 
 
 
		Select 
		OMGM.Id AS OrgMainGroupId,
		OMGM.Code AS OrgMainGroupName,
		OSGM.Id AS OrgSubGroupId,
		OSGM.Code AS SubGroupName,
		OM.Title AS OrgName,
		DM.Id AS DepartmentId,
		--CM.Id,
		stum.OrgId,
		Stum.Code,
		[sStudent].[fStudentNameGet](stum.FirstName , StuM.MiddleName, StuM.LastName,OM.StudentNameFormatId ) AS Name,
		A.RollNo,
		A.Id AS AcademicId,			
		CM.DisplayTitle AS Class,
		CM.Id As ClassId,
		DM.DisplayTitle AS Division,
		DM.Id AS DivisionId,
		ETM.Code AS Exam,
		CS.Id AS SubjectId,	
		SM.Code AS SubjectCode,
		SM.Title AS SubjectName,
		--RD.SubjectGrade,
		--R.ResultGrade,
		--BM.OrgGroupBatchId,
		--RD.Obtain,
		[sAssessment].[fGetConfigGrade](stum.OrgId,RD.Obtain) AS SubjectGrade,
		--R.Percentage,
		[sAssessment].[fGetResuultGradeCount](stum.OrgId,RD.Obtain,@rExamId,@rStrOrgMainGroupId,@rStrOrgSubGroupId,@rStrOrgId,@rStrDepartmentId,@rStrClassId,@rOrgGroupBatchId,CM.Id,DM.Id)AS ResultGrade,
		@rExamId AS ExamId,
		--R.ResultGrade,
		 --OMGM.Id
		 ISNULL(RD.IsPresent, 0) AS IsPresent      --Mantis 30006

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

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


END
GO
PRINT N'Altering Procedure [sPayroll].[pRptEmployeeSalaryDetail]...';


GO

ALTER PROCEDURE [sPayroll].[pRptEmployeeSalaryDetail]
	
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 @rEmployeeId bigint,
	 @rEmployeeCode nvarchar(200),
	 @rEmployeeName nvarchar(200),
	 @rDepartmentId int,
	 @rForMonth int,
	 @rForYear int,
	 @rPayrollId int,
	 @rPayrollGroupId int,
	 @rPayrollYearId int,
	 @rReportId smallint=0,
	 @rOrderByField nvarchar(20)='',
	 @rMonths nvarchar(50)='',
	 @rOrgId int = 0,
	 @rStatusId int = 0,
	 @rEmployeeGroupId int = 0
	 
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN  
	
	DECLARE @lMonthDay int=0
	SELECT @lMonthDay=[sCommon].[fGetDaysInMonth] (@rForMonth,@rForYear)
	
	--DECLARE @lConfigValue nvarchar(50) = ''
	--DECLARE @lIsOnPrePrinted bit = 0
	--DECLARE @lIsDisplayImageHeader bit=0

	
	--SELECT @lConfigValue = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 469 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


	DECLARE @lFirstDate Date
	DECLARE @lLasteDate Date
	IF(@rForMonth!=0 and @rForYear!=0)
	BEGIN
		SET @lFirstDate = CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'/'+CONVERT(NVARCHAR(2),@rForMonth)+'/01'))
		SET @lLasteDate=DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,@lFirstDate)+1,0))
	END
	
	DECLARE @lBasicPayElementId int
	SELECT @lBasicPayElementId = Id FROM sPayroll.tPayElement WHERE PayrollId = @rPayrollId AND PayElementDefaultId = 1
	
	SET @rEmployeeCode = sCommon.fSearchStringGet(@rEmployeeCode)
    SET @rEmployeeName = sCommon.fSearchStringGet(@rEmployeeName)

	SELECT
		@rOrderByField AS OrderByField,
		@rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2, 
		EM.EmployeeId, 
		PP.ID As PayProcessId,
		PPE.ID AS PayProcessEmployeeId,
		PP.SalaryMonth,
		PP.SalaryYear,
		tEM.FirstName +' '+tEM.MiddleName+' '+tEm.LastName AS EmployeeName,
		EM.Code AS EmployeeCode,
		EM.EmployeeDesignation,
		EM.EmployeeGrade,
		ESO.EPFNumber,
		ESO.PanNumber,
		PPE.TotalEarning,		
		PPE.TotalDeduction,
		PPE.NetAmount,
		(CASE WHEN PayElementId = @lBasicPayElementId then PPE.TotalEarning else 0 END) AS TotalEarningTotal,
		(CASE WHEN PayElementId = @lBasicPayElementId then PPE.TotalDeduction else 0 END) AS TotalDeductionTotal,
		(CASE WHEN PayElementId = @lBasicPayElementId then PPE.NetAmount else 0 END) AS NetAmountTotal,
		PE.Amount As PPEAmount,
		P.Title AS PayElementTitle,
		P.ID AS PayElementId,
		P.PayElementTypeId,
		ISNULL(ESO.BankName,'') AS BankName,
		ISNULL(ESO.AccountNumber,'') AS AccountNumber, 
		MM.Title AS MonthName,
		P.Title AS PayElementName,
		P.Code AS PayElementCode,
		(CASE WHEN PayElementId = @lBasicPayElementId then ISNULL(PPE.WorkingDays,@lMonthDay) else 0 END) AS WorkingDays,
		--ISNULL(EWD.WorkingDays,@lMonthDay) AS WorkingDays,
		(CASE WHEN PayElementId = @lBasicPayElementId then PPE.Lwp else 0 END) AS Lwp,
		(CASE WHEN PayElementId = @lBasicPayElementId then ISNULL(PPE.PaidLeave,0) else 0 END) AS PaidLeave,
		P.SortOrder,
		PY.Title AS PayrollYearName,
		PGM.Id AS PayrollGroupId,
		PGM.Title AS PayrollGroupName,
		PPE.GrossBasic,
		P.PayElementDefaultId,
		ISNULL(EPD.Qualification,'') AS Qualification,
		EJD.DateOfJoining AS DateOfAppointment,
		ISNULL(ESO.PayScale,'') AS PayScale,
		EPD.DateOfBirth,
		ISNULL(ROG.SelectableField,'') AS SelectableField,
		RGO.SchoolRequiredSignature ,
		RGO.SchoolRemark1,
		ISNULL(ESO.BasicPay,0) AS BasicPay,
		DAY(DATEADD(DD,-1,DATEADD(mm, DATEDIFF(mm, 0, CONVERT(DATE,CONVERT(nvarchar,PP.SalaryMonth) +'/01/'+CONVERT(nvarchar,PP.SalaryYear)) ) + 1, 0))) AS MonthDay,
		ESO.UAN,
		EPD.GenderId,
		ISNULL(PPR.Remark,'') AS PayProcessEmployeeRemark,
		tEM.FirstName,
		tEm.LastName,
		EM.DateOfJoining,
		OI.CertificateHeaderA4Portrait AS CertificateHeaderA4,
		ISNULL(REPLACE(REPLACE(
		(SELECT STUFF(
		(
		  SELECT  ' ' + Leave FROM -- create comma separated values
			(
					Select '<br>'+('<b>'+ LTM.Code +'</b>' +' - '+ CAST(SUM(CAST(L.NoOfLeave AS FLOAT)) AS varchar(50)) ) + '</br>'AS Leave 
					from 
					sHrm.tLeaveTypeMaster LTM  
					INNER JOIN sHrm.tLeave L ON  EM.EmployeeId = L.EmployeeId 
					INNER JOIN sCommon.tStatusMaster SM ON SM.Id=L.StatusId
					Where EM.EmployeeId=EM.EmployeeId AND LTM.OrgId=EM.OrgId AND LTM.IsObsolete = 0 
					AND LTM.Id = L.LeaveTypeId AND SM.Id=550
					AND (YEAR(L.FromDate) = @rForYear OR @rForYear=0) 
					AND (MONTH(L.FromDate) = @rForMonth OR @rForMonth=0) 
					GROUP BY LTM.Code
					)AS T FOR XML PATH('')
		)
		,1,1,'')),'&lt;','<'),'&gt;','>')
		,'') AS LeaveCount,
		tEM.Number,
		--@lIsOnPrePrinted AS IsOnPrePrinted,
		--@lIsDisplayImageHeader AS IsDisplayImageHeader,
		--ISNULL(OI.PayrollHeaderA4,0x) AS PayrollHeader
		(CASE WHEN ISNULL(PM.HeaderDisplayId,1) = 3 THEN ISNULL(PM.PayrollHeader,0x) ELSE NULL END) AS PayrollHeader,
		--ISNULL(PM.PayrollHeader,0x) AS PayrollHeader,
		ISNULL(PM.HeaderDisplayId,1)AS HeaderDisplayId,
		ISNULL(ESO.IFSCNumber,'') AS IFSCNumber,
		ISNULL(EPD.AdhaarNumber,'') AS AdhaarNumber,
		EM.DepartmentName, --Mantis : 0029371
		ESO.ESINumber,
		(SELECT PS.Amount FROM sPayroll.tPaySetup PS WHERE PS.PayElementId = P.Id 
			AND PS.SourceId = tEM.Id AND PS.PayrollYearId = PP.PayrollYearId) AS PaySetupAmount,
			tEM.CreatedDateTime AS CreatedDateTime --mantis - 0030732
	FROM 
	sPayroll.tPayProcess PP 
	INNER JOIN sPayroll.tPayProcessEmployee PPE ON PPE.PayProcessId = PP.ID 
	INNER JOIN sHrm.vEmployeeCommonDetail EM ON EM.EmployeeId = PPE.EmployeeId 
	INNER JOIN sHrm.tEmployeeMaster tEM ON tEM.Id = PPE.EmployeeId 
	INNER JOIN sPayroll.tPayProcessElement PE ON PE.PayProcessEmployeeId=PPE.ID
	INNER JOIN sPayroll.tPayElement P ON PE.PayElementId=P.ID AND P.IsIncludeInPaySlip = 1
	LEFT JOIN sHrm.tEmployeeStatutoryAndOther ESO ON ESO.EmployeeId=PPE.EmployeeId	
	LEFT JOIN sHrm.tEmployeePersonalDetail EPD ON EPD.EmployeeId=PPE.EmployeeId	
	LEFT JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=PPE.EmployeeId	
	INNER JOIN sCommon.tMonthMaster MM ON MM.Id=PP.SalaryMonth
	INNER JOIN sPayroll.tPayrollYearMaster PY ON PP.PayrollYearId = PY.Id 
	INNER JOIN sPayroll.tPayrollGroupMaster PGM ON PGM.Id = PPE.PayrollGroupId
	LEFT JOIN sCommon.tReportOrgGroup ROG ON ROG.OrgGroupId=PY.OrgGroupId AND (ROG.ReportId = @rReportId OR @rReportId = 0) 
	LEFT JOIN sCommon.tReportRemarkGroupOrg RGO ON RGO.OrgId = tEM.OrgID AND RGO.ReportRemarkGroupId =  4
	LEFT JOIN sPayroll.tPayProcessEmployeeRemark PPR ON PPR.SalaryMonth = PP.SalaryMonth
	AND PPR.SalaryYear = PP.SalaryYear AND PPR.PayrollYearId = PP.PayrollYearId AND  PPR.EmployeeId = PPE.EmployeeId
	INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=tEM.OrgId
	LEFT JOIN sSetup.tOrgImages OI ON OI.OrgId = OM.Id
	INNER JOIN sPayroll.tPayrollMaster PM ON PY.PayrollId = PM.Id
	
	--LEFT JOIN sHrm.tEmployeeWorkingDays EWD ON tEM.Id = EWD.EmployeeId AND PP.SalaryMonth=EWD.ForMonth AND PP.SalaryYear=EWD.ForYear
where 
      (EM.EmployeeId = @rEmployeeId OR @rEmployeeId = 0)
      AND (P.IsObsolete=0)
      AND ((EM.Code Like '%' +  @rEmployeeCode + '%' ) OR (@rEmployeeCode = ''))
	  AND ((EM.EmployeeName Like '%' + @rEmployeeName  + '%') OR (@rEmployeeName = ''))
	  AND (EM.DepartmentId = @rDepartmentId OR @rDepartmentId = 0)
	  AND (PP.SalaryMonth = @rForMonth OR @rForMonth = 0)
	  AND (PP.SalaryYear = @rForYear OR @rForYear = 0)
	  AND ((PY.PayrollId=@rPayrollId) OR (@rPayrollId=0))
	  AND (PPE.PayrollGroupId = @rPayrollGroupId OR @rPayrollGroupId = 0) 
	  AND (PP.PayrollYearId = @rPayrollYearId OR @rPayrollYearId = 0) 
	  AND (PP.SalaryMonth IN(SELECT cast(item as int) FROM  sCommon.fnsplit(@rMonths,',')) OR @rMonths='')
	  --AND ((EM.DateOfleaving >= @lFirstDate) OR ISNULL(EM.DateOfleaving,'') = '')
   --   AND ((EM.DateOfJoining <= @lLasteDate) OR ISNULL(EM.DateOfJoining,'') = '')
	  AND ((tEM.OrgID = @rOrgId) OR (@rOrgId = 0))
	  AND ((tEM.StatusId = @rStatusId) OR (@rStatusId = 0))
	  AND ((EJD.EmployeeGroupId = @rEmployeeGroupId) OR (@rEmployeeGroupId = 0))
END
GO
PRINT N'Altering Procedure [sPayroll].[pRptMonthlyProfessoionTaxSummary]...';


GO
ALTER PROCEDURE [sPayroll].[pRptMonthlyProfessoionTaxSummary]
	
		@rBuilder1 nvarchar(max)='',
		@rBuilder2 nvarchar(max)='', 
		@rEmployeeId bigint,
		@rEmployeeCode nvarchar(200),
		@rEmployeeName nvarchar(200),
		@rDepartmentId int,
		@rForMonth int,
		@rForYear int,
		@rPayrollId int,
		@rPayrollGroupId int,
		@rPayrollYearId int,
		@rOrgId int = 0,
		@rStatusId int = 0,
		@rEmployeeGroupId int = 0
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN   
		
		DECLARE @lFirstDate Date
		DECLARE @lLasteDate Date
	
	
		SET @lFirstDate = CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'/'+CONVERT(NVARCHAR(2),@rForMonth)+'/01'))
		SET @lLasteDate=DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,@lFirstDate)+1,0))
		
 
		SET @rEmployeeCode = sCommon.fSearchStringGet(@rEmployeeCode)
		SET @rEmployeeName = sCommon.fSearchStringGet(@rEmployeeName)

	--DECLARE @lConfigValue nvarchar(50) = ''
	--DECLARE @lIsOnPrePrinted bit = 0
	--DECLARE @lIsDisplayImageHeader bit=0

	--SELECT @lConfigValue = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 469 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
			@rBuilder1 AS Builder1,
		    @rBuilder2 AS Builder2, 
			PTR.Id,
			PTR.Tax,
			ISNULL(A.NomberOfEmployee,0) AS NumberOfEmployee,
			--@lIsOnPrePrinted AS IsOnPrePrinted,
			--@lIsDisplayImageHeader AS IsDisplayImageHeader,
			PayrollHeader,
			HeaderDisplayId
		FROM 
			sPayroll.tProfessionalTaxRange PTR
		LEFT JOIN 
		(	
		SELECT 
			PTR.Id, COUNT(EM.EmployeeId) AS NomberOfEmployee ,PE.Amount,
			(CASE WHEN ISNULL(PM.HeaderDisplayId,1) = 3 THEN ISNULL(PM.PayrollHeader,0x) ELSE NULL END) AS PayrollHeader,ISNULL(PM.HeaderDisplayId,1)AS HeaderDisplayId
		FROM 
			sPayroll.tProfessionalTaxRange PTR
			INNER JOIN sPayroll.tPayProcess PP ON PP.PayrollYearId = PTR.PayrollYearId
			INNER JOIN sPayroll.tPayProcessEmployee PPE ON PPE.PayProcessId = PP.ID 
			INNER JOIN sHrm.vEmployeeCommonDetail EM ON EM.EmployeeId = PPE.EmployeeId 
			INNER JOIN sHrm.tEmployeeMaster tEM ON tEM.Id = PPE.EmployeeId 
			INNER JOIN sPayroll.tPayProcessElement PE ON PE.PayProcessEmployeeId=PPE.ID
			INNER JOIN sPayroll.tPayElement P ON PE.PayElementId=P.ID  AND PayElementDefaultId = 57 
			LEFT JOIN sHrm.tEmployeeStatutoryAndOther ESO ON ESO.EmployeeId=PPE.EmployeeId	
			LEFT JOIN sHrm.tEmployeePersonalDetail EPD ON EPD.EmployeeId=PPE.EmployeeId	
			LEFT JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=PPE.EmployeeId	
			INNER JOIN sCommon.tMonthMaster MM ON MM.Id=PP.SalaryMonth
			INNER JOIN sPayroll.tPayrollYearMaster PY ON PP.PayrollYearId = PY.Id 
			INNER JOIN sPayroll.tPayrollGroupMaster PGM ON PGM.Id = PPE.PayrollGroupId	
			--LEFT JOIN sSetup.tOrgImages OI ON OI.OrgId = tEM.OrgID
			INNER JOIN sPayroll.tPayrollMaster PM ON PY.PayrollId = PM.Id
		WHERE 
			(EM.EmployeeId = @rEmployeeId OR @rEmployeeId = 0)
			AND (P.IsObsolete=0)
			AND ((EM.Code Like '%' +  @rEmployeeCode + '%' ) OR (@rEmployeeCode = ''))
			AND ((EM.EmployeeName Like '%' + @rEmployeeName  + '%') OR (@rEmployeeName = ''))
			AND (EM.DepartmentId = @rDepartmentId OR @rDepartmentId = 0)
			AND (PP.SalaryMonth = @rForMonth OR @rForMonth = 0)
			AND (PP.SalaryYear = @rForYear OR @rForYear = 0)
			AND ((PY.PayrollId=@rPayrollId) OR (@rPayrollId=0))
			AND (PPE.PayrollGroupId = @rPayrollGroupId OR @rPayrollGroupId = 0) 
			AND (PP.PayrollYearId = @rPayrollYearId OR @rPayrollYearId = 0) 
			AND ((EM.DateOfleaving >= @lFirstDate) OR ISNULL(EM.DateOfleaving,'') = '')
			AND ((EM.DateOfJoining <= @lLasteDate) OR ISNULL(EM.DateOfJoining,'') = '')
			AND ((tEM.OrgID = @rOrgId) OR (@rOrgId = 0))
			AND ((tEM.StatusId = @rStatusId) OR (@rStatusId = 0))
			AND ((EM.EmployeeGroupId = @rEmployeeGroupId) OR (@rEmployeeGroupId = 0))
		GROUP BY 
			PTR.Id,PE.Amount,PM.PayrollHeader,PM.HeaderDisplayId -- Removed EM.Employee from Groupby for mantis 0030813 by Foram
		) A ON A.Id = PTR.Id AND PTR.Tax = A.Amount
		WHERE PTR.PayrollYearId = @rPayrollYearId
		GROUP BY PTR.Id,PTR.Tax,A.NomberOfEmployee,PayrollHeader,HeaderDisplayId
		ORDER BY PTR.Tax
END
GO
PRINT N'Altering Procedure [sPayroll].[pRptPayElementwiseSummaryDetail]...';


GO
ALTER PROCEDURE [sPayroll].[pRptPayElementwiseSummaryDetail]
	
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 @rPayElementId int,
	 @rEmployeeId bigint,
	 @rEmployeeCode nvarchar(200),
	 @rEmployeeName nvarchar(200),
	 @rDepartmentId int,
	 @rForMonth int,
	 @rForYear int,
	 @rPayrollId int,
	 @rPayrollGroupId int,
	 @rPayrollYearId int,	
	 @rPayElementTypeId int=0,
	 @rMonths nvarchar(50)='',
	 @rOrderByField nvarchar(20)='',
	 @rOrgId int = 0,
	 @rIsDetail bit = 0,
	 @rStatusId int = 0,
	 @rEmployeeGroupId int = 0
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN  
	
	DECLARE @lFirstDate Date
	DECLARE @lLasteDate Date
	IF(@rForMonth!=0 and @rForYear!=0)
	BEGIN
		SET @lFirstDate = CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'/'+CONVERT(NVARCHAR(2),@rForMonth)+'/01'))
		SET @lLasteDate=DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,@lFirstDate)+1,0))
	END
	
	DECLARE @lBasicPayElementId int
	DECLARE @lProfessionalTaxPayElementId int
	
	SELECT @lBasicPayElementId = Id FROM sPayroll.tPayElement WHERE PayrollId = @rPayrollId AND PayElementDefaultId = 1
	SELECT @lProfessionalTaxPayElementId = Id FROM sPayroll.tPayElement WHERE PayrollId = @rPayrollId AND PayElementDefaultId = 57
	
	SET @rEmployeeCode = sCommon.fSearchStringGet(@rEmployeeCode)
    SET @rEmployeeName = sCommon.fSearchStringGet(@rEmployeeName)

	--DECLARE @lConfigValue nvarchar(50) = ''
	--DECLARE @lIsOnPrePrinted bit = 0
	--DECLARE @lIsDisplayImageHeader bit=0

	--SELECT @lConfigValue = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 469 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 
	@rOrderByField AS OrderByField,
	@rBuilder1 AS Builder1,
	@rBuilder2 AS Builder2,	
	PE.Amount,
	P.Id AS PayElementId, 
	P.Title AS PayElementName,
	P.Code AS PayElementCode,
	EM.EmployeeId,
	tEM.FirstName +' '+tEM.MiddleName+' '+ tEM.LastName AS EmployeeName,
	EM.Code,
	EM.EmployeeDesignation,
	PP.SalaryMonth,
	PP.SalaryYear,
	MM.Title AS MonthName,
	PY.Title AS PayrollYearName,
	P.SortOrder,
	P.PayElementTypeId,
	@rPayElementTypeId AS IsPayElementTypeIdZero,
	@rPayElementId AS IsPayElementIdZero, 
	PPE.TotalEarning,		
	PPE.TotalDeduction,
	PPE.NetAmount,
	(CASE WHEN PayElementId = @lBasicPayElementId then PPE.TotalEarning else 0 END) AS TotalEarningTotal,
	(CASE WHEN (PayElementId = @lBasicPayElementId And @rPayElementTypeId <> 2) 
	 THEN PPE.TotalDeduction WHEN PayElementId = @lProfessionalTaxPayElementId And @rPayElementTypeId = 2 
	 THEN PPE.TotalDeduction ELSE 0 END) AS TotalDeductionTotal,	 
	(CASE WHEN PayElementId = @lBasicPayElementId then PPE.NetAmount else 0 END) AS NetAmountTotal,
	PGM.Id AS PayrollGroupId,
	PGM.Title AS PayrollGroupName,
	PPE.GrossBasic ,
	P.PayElementDefaultId,
	ISNULL(PPE.WorkingDays,0) AS WorkingDays,
	ISNULL(PPE.Lwp,0) AS Lwp,
	EM.FirstName,
	EM.LastName,
	tEM.Number,
	OM.Id AS OrganizationId,
	OM.Title AS OrganizationTitle,
	OM.Code AS OrganizationCode,
	OM.OrderIndex AS OrganizationOrderIndex,
	@rIsDetail AS IsDetail,
	EM.DateOfBirth,
	EM.DateOfJoining,
	--@lIsOnPrePrinted AS IsOnPrePrinted,
	--@lIsDisplayImageHeader AS IsDisplayImageHeader,
	--ISNULL(OI.PayrollHeaderA4,0x) AS PayrollHeader
	(CASE WHEN ISNULL(PM.HeaderDisplayId,1) = 3 THEN ISNULL(PM.PayrollHeader,0x) ELSE NULL END) AS PayrollHeader,
	--ISNULL(PM.PayrollHeader,0x) AS PayrollHeader,
	ISNULL(PM.HeaderDisplayId,1)AS HeaderDisplayId,
	tEM.CreatedDateTime as CreatedDateTime    ---30737
		
	FROM sPayroll.tPayProcessEmployee PPE
		INNER JOIN sPayroll.tPayProcess PP ON PPE.PayProcessId=PP.ID
		INNER JOIN sPayroll.tPayProcessElement PE ON PE.PayProcessEmployeeId=PPE.ID
		INNER JOIN sPayroll.tPayElement P ON P.ID=PE.PayElementId AND P.IsObsolete = 0
		INNER JOIN sHrm.vEmployeeCommonDetail EM ON EM.EmployeeId=PPE.EmployeeId
		INNER JOIN sHrm.tEmployeeMaster tEM ON tEM.Id=PPE.EmployeeId
		LEFT JOIN sHrm.tEmployeeStatutoryAndOther ESO ON ESO.EmployeeId=PPE.EmployeeId	
		INNER JOIN sCommon.tMonthMaster MM ON MM.Id=PP.SalaryMonth
		INNER JOIN sPayroll.tPayrollYearMaster PY ON PP.PayrollYearId = PY.Id 
		INNER JOIN sPayroll.tPayrollGroupMaster PGM ON PGM.Id = PPE.PayrollGroupId
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = tEM.OrgId
		--LEFT JOIN sSetup.tOrgImages OI ON OI.OrgId = tEM.OrgID
		INNER JOIN sPayroll.tPayrollMaster PM ON PY.PayrollId = PM.Id
WHERE 
      (PPE.EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
      AND ((P.ID=@rPayElementId) OR (@rPayElementId=0))
      AND ((EM.Code Like  @rEmployeeCode) OR (@rEmployeeCode = ''))
	  AND ((EM.EmployeeName Like @rEmployeeName ) OR (@rEmployeeName = ''))
	  AND (EM.DepartmentId = @rDepartmentId OR @rDepartmentId = 0)
	  AND (PP.SalaryMonth = @rForMonth OR @rForMonth = 0)
	  AND (PP.SalaryYear = @rForYear OR @rForYear = 0)
	  AND ((PY.PayrollId=@rPayrollId) OR (@rPayrollId=0))
	  AND (PPE.PayrollGroupId = @rPayrollGroupId OR @rPayrollGroupId = 0) 
	  AND (PP.PayrollYearId = @rPayrollYearId OR @rPayrollYearId = 0) 
	  AND (P.PayElementTypeId = @rPayElementTypeId OR @rPayElementTypeId = 0) 
	  AND (PP.SalaryMonth IN(SELECT cast(item as int) FROM  sCommon.fnsplit(@rMonths,',')) OR @rMonths='')
	  AND ((tEM.OrgID = @rOrgId) OR (@rOrgId = 0))
	  AND ((tEM.StatusId = @rStatusId) OR (@rStatusId = 0))
	  --AND ((EM.DateOfleaving >= @lFirstDate) OR ISNULL(EM.DateOfleaving,'') = '')
   --   AND ((EM.DateOfJoining <= @lLasteDate) OR ISNULL(EM.DateOfJoining,'') = '')
	  AND ((EM.EmployeeGroupId = @rEmployeeGroupId) OR (@rEmployeeGroupId = 0))
END
GO

PRINT N'Altering Procedure [sSecurity].[pDashletGet]...';


GO
ALTER PROCEDURE [sSecurity].[pDashletGet]
	@rOrgGroupId int=0,
	@rDate date='',
	@rDashletId int=0,
	@rOrgGroupBatchId int=0,
	@rUserId bigint=0,
	@rUserSourceId bigint=0,
	@rUserSourceTypeId int=0,
	@rOrgId Int=0,
	@rSourceTypeId smallint=0,
	@rSourceId bigint=0,
	@rBatchId int=0,
	@rExamId int=0,
	@rStatusId int =0
	
									
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED
BEGIN
DECLARE @TimeZoneDate datetime
SET  @TimeZoneDate=sCommon.fGetDate()
if(@rDashletId='1')
       BEGIN
        exec sCommunication.pCircularListGet @rUserSourceId=@rUserSourceId,@rOrgGroupBatchId=@rOrgGroupBatchId,@rUserSourceTypeId=@rUserSourceTypeId,@rUserId=@rUserId,@rStartDate=@rDate
        END
 if(@rDashletId='2')
        BEGIN
        SELECT  N.Id,N.Title FROM sCommunication.tNews N WHERE N.OrgGroupBatchId=@rOrgGroupBatchId AND Convert(date,N.CreatedDateTime)=convert(date,@TimeZoneDate)
        END
 if(@rDashletId='3')
          BEGIN
        exec sActivity.pMyEventGet @rSourceTypeId=@rSourceTypeId,@rSourceId=@rSourceId,@rOrgId=@rOrgId,@rBatchId=@rBatchId,@rFromDate=@rDate,@rToDate=@rDate
          END
if(@rDashletId='4')
        BEGIN
        exec sCommunication.pAssignTaskGet @rId=0,@rOrgId=@rOrgId,@rCreatedUserId=@rUserId,@rIsAssignTaskToMe=1,@rStatus=0,@rIsSearch=1
        END
 if(@rDashletId='5')
        BEGIN
        exec sCommunication.pAssignTaskGet @rId=0,@rOrgId=@rOrgId,@rCreatedUserId=@rUserId,@rIsAssignTaskToMe=0,@rStatus=0,@rIsSearch=1
        END
 if(@rDashletId='6')
        BEGIN
		DECLARE @BirthdayDays int=0
		IF EXISTS (SELECT 1 FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 355 AND SourceTypeId = 1016 AND SourceId = @rOrgId)
			BEGIN
			SET @BirthdayDays = (SELECT ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 355 AND SourceTypeId = 1016 AND SourceId = @rOrgId)
			END
		ELSE 
			BEGIN
			SET @BirthdayDays = 7
			END
        SELECT 	EM.FirstName + ' ' + EM.MiddleName + ' ' + EM.LastName AS Name,	EM.DepartmentName, EM.DateOfBirth AS DateOfBirth  FROM [sHrm].[vExtEmployeeMaster] EM	
        WHERE  	EM.OrgId = @rOrgId  
     --    AND (MONTH(EM.DateOfBirth) = CAST(MONTH(@TimeZoneDate) AS varchar(2))) AND EM.DateOfBirth!='' AND EM.StatusId=7
	    --AND (DAY(EM.DateOfBirth) = CAST(DAY(@TimeZoneDate) AS varchar(2)))
		--AND(MONTH(EM.DateOfBirth) <= CAST(MONTH(@TimeZoneDate) AS varchar(2)) AND MONTH(EM.DateOfBirth) >= CAST(MONTH(@TimeZoneDate) AS varchar(2)))
		--AND(DAY(EM.DateOfBirth) <= CAST(DAY(@TimeZoneDate+@BirthdayDay) AS varchar(2)) AND DAY(EM.DateOfBirth) >= CAST(DAY(@TimeZoneDate) AS varchar(2)))

		AND CONVERT(VARCHAR(5),EM.DateOfBirth,110) <= CONVERT(VARCHAR(5),@TimeZoneDate+@BirthdayDays,110) 
		AND CONVERT(VARCHAR(5),EM.DateOfBirth,110) >= CONVERT(VARCHAR(5),@TimeZoneDate,110)
		AND EM.DateOfBirth!='' AND EM.StatusId=7
		ORDER BY CONVERT(VARCHAR(5),EM.DateOfBirth,110)
		
        END
 if(@rDashletId='7')
        BEGIN
        SELECT SC.FirstName + ' ' + SC.MiddleName + ' ' + SC.LastName AS Name, SC.ClassName+' '+SC.DivisionName AS ClassName FROM sStudent.vStudentAllDetail SC WHERE SC.OrgId=@rOrgId AND SC.BatchId=@rBatchId
         AND (MONTH(SC.DateOfBirth) = CAST(MONTH(@TimeZoneDate) AS varchar(2))) AND SC.DateOfBirth!='' AND SC.StatusId=1
	    AND (DAY(SC.DateOfBirth) = CAST(DAY(@TimeZoneDate) AS varchar(2)))   
        END
         if(@rDashletId='10')
        BEGIN
       exec sAttendance.pDashletAttendanceStatusGet @rAcademicId=@rSourceId
        END
   
   if(@rDashletId='11')
        BEGIN
       SELECT EM.EmployeeName,L.FromDate,L.ToDate FROM  sHrm.tLeave L 
        INNER JOIN sSetup.tBatchMaster BM ON BM.Id = L.BatchId	
        INNER JOIN sHrm.vEmployeeCommonDetail EM ON EM.EmployeeId = L.EmployeeId
        INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = L.EmployeeId
         WHERE  
			BM.OrgGroupBatchId = @rOrgGroupBatchId
			AND L.OrgId = @rOrgId
			AND (EJD.EmployeeManagerId = @rUserSourceId OR @rUserSourceId = 0)
			--AND ((L.FromDate >= @rDate) OR (ISNULL(@rDate,'') = '')) --comment for Mantis Id: 0030464
			AND EM.EmployeeStatusId=7
			AND L.StatusId = 549
       -- exec [sHrm].[pLeaveListingGet] @rOrgId=@rOrgId,@rEmployeeId=@rUserSourceId,@rLeaveTypeId=0,@rOrgGroupBatchId=@rOrgGroupBatchId,@rFromDate=@rDate,@rTodate=''
        END
   if(@rDashletId='12')
        BEGIN
     exec sCommunication.pPollGet @rOrgGroupBatchId=@rOrgGroupBatchId,@rSourceTypeId=@rUserSourceTypeId,@rCreatedUserId=@rUserId,@rCreatedDateTime=@rDate
        END
  if(@rDashletId='14')
       BEGIN
        exec sCommunication.pMyBookGet @rReaderSourceTypeId=@rUserSourceTypeId,@rReaderSourceId=@rUserSourceId,@rBatchId=@rBatchId,@rStatusId=@rStatusId

        END
  if(@rDashletId='16')
        BEGIN
      exec [sFee].[pRptFeeReceiptTotalGet] @rFromDate=@rDate,@rToDate=@rDate,@rOrgGroupBatchId=@rOrgGroupBatchId
        END
      
  if(@rDashletId='17')
        BEGIN
      exec [sFee].[pFeeDueAlertGet] @rSourceId=@rSourceId,@rSourceTypeId=@rSourceTypeId,@rBatchId=@rBatchId

        END
  if(@rDashletId='18')
        BEGIN
     exec sCommunication.pBlogGet @rId=0,@rOrgGroupBatchId=@rOrgGroupBatchId,@rTitle=NULL,@rCreatedUserId=0,@rOrgId=@rOrgId,@rCreatedDateTime=@rDate
        END
 if(@rDashletId='19')
        BEGIN
     exec sAssessment.pStudentResultGet @rAcademicId=@rSourceId,@rStudentId=@rUserSourceId,@rBatchId=@rBatchId,@rExamId=@rExamId
     END
  if(@rDashletId='21')
       BEGIN
       SELECT vCD.ClassDivisionName,ISNULL(EM.FirstName+' '+ EM.LastName,'') AS ClassTeacherName,
	   CASE WHEN COUNT(SR.AcademicId)=0 THEN CASE WHEN (Select [sCommon].[fCountAbsentStudent](A.DivisionId,  @rBatchId,@rDate,1,0)) =0 THEN 'Pending' ELSE 'Complete' END ELSE 'Complete' END AS PresentStatus
        FROM sStudent.tAcademic A 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 
       LEFT JOIN sAttendance.tStudentRegister SR ON A.Id = SR.AcademicId AND SR.AttendanceTypeId = 1 
       AND SR.IsPresent=1 AND SR.AttendanceDate=@rDate GROUP BY A.DivisionId,A.BatchId,vCD.ClassDivisionName,vCD.OrderIndex,EM.FirstName,EM.LastName ORDER BY vCD.OrderIndex
         END
  if(@rDashletId='22')
       BEGIN
        SELECT VL.Id,VL.VisitorName, VL.NoOfVisitor,  (isnull(case when isnull(VL.WhomToMeet,0)!=0 then isnull(EM.EmployeeName,'') else ISNULL(VL.WhomToMeetName,'') end,'' )) AS WhomToMeetName
		FROM sFrontOffice.tVisitorLog VL  
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=VL.OrgId 
		 LEFT JOIN sHrm.vExtEmployeeMaster EM ON EM.EmployeeId=VL.WhomToMeet
        WHERE VL.OrgId=@rOrgId AND VL.VisitDate=@rDate ORDER BY VL.VisitDate DESC,VL.InTime DESC
        END
  if(@rDashletId='23')
       BEGIN
        SELECT DispatchedTo, DispatchedCity  FROM sFrontOffice.tCourierDispatch  WHERE OrgGroupId=@rOrgGroupId AND DispatchDate=@rDate  AND @rDashletId='23' ORDER BY DispatchDate
        END
    if(@rDashletId='24')
       BEGIN
        SELECT ReceiveFrom, ReceiveFor  FROM  sFrontOffice.tCourierReceive  WHERE OrgGroupId=@rOrgGroupId  AND ReceiveDate=@rDate  AND @rDashletId='24' ORDER BY ReceiveDate
    END
     if(@rDashletId='25')
        BEGIN
     SELECT ISNULL(Ps.LectureNumber,'') AS LactureNumber,PS.EmployeeId,ISNULL(SMT.Title,'') AS Subject,ISNULL(EM1.FirstName,'') + ' '+ISNULL(EM1.LastName,'') AS EmployeeName,ISNULL(Em.FirstName,'') + ' '+ISNULL(Em.LastName,'') AS ProxyEmployeeName, ISNULL


(DV.Code,'') AS ClassDivisionName,ISNULL(SM.Title,'') AS ProxySubject from sTimetable.tProxySetting PS 
     INNER JOIN sSetup.tSubjectMaster SM ON SM.Id = PS.SubjectId INNER JOIN sCommon.tDayMaster DM ON DM.Id = PS.DayId INNER JOIN sSetup.tDivisionMaster DV ON DV.Id = PS.DivisionId
     INNER JOIN sTimetable.tTimeTable TT ON TT.Id=PS.TimeTableId 
     INNER JOIN sSetup.tSubjectMaster SMT ON SMT.Id = TT.SubjectId 
     INNER JOIN sHrm.tEmployeeMaster EM1  ON TT.EmployeeId=EM1.Id 
     INNER JOIN sHrm.tEmployeeMaster Em ON Em.Id = PS.EmployeeId  WHERE PS.ProxyDate=@rDate AND PS.BatchId=@rBatchId AND ((PS.EmployeeId=@rSourceId) OR (@rSourceId=0))  ORDER BY PS.ProxyDate
        END
        
        if(@rDashletId='27')
        BEGIN
     --Asset Check
		SELECT LM.Title AS LocationName, AM.Code AS AssetCode, AM.Title AS AssetName, CONVERT(nvarchar(12),AM.CheckedLastDate,103) AS CheckedLastDate
        FROM sAssetManagement.tAssetMaster AM INNER JOIN sAssetManagement.tAssetInchargeUser AU ON AM.Id = AU.AssetId 
        INNER JOIN sFixedAsset.tLocationMaster LM ON LM.Id = AM.LocationId 
        WHERE ISNULL(AM.IsCheckRequired,0) = 1 AND (AM.CheckFrequencyId=1 AND AM.CheckedLastDate <=  DATEADD(dd,1,@TimeZoneDate) OR AM.CheckFrequencyId=2 AND AM.CheckedLastDate <=  DATEADD(dd,7,@TimeZoneDate) OR AM.CheckFrequencyId=3 AND AM.CheckedLastDate <= DATEADD(dd,30,@TimeZoneDate))
        AND AU.InchargeUserId =   @rUserId AND AM.OrgGroupId = @rOrgGroupId
     
     
     
  --      SELECT LM.Title AS LocationName, AM.Code AS AssetCode, AM.Title AS AssetName,CONVERT(nvarchar(12),
		--AM.LastMaintenanceDate,103) AS LastMaintenanceDate,CONVERT(nvarchar(12),AM.NextMaintenanceDate,103) AS NextMaintenanceDate
		--FROM sAssetManagement.tAssetMaster AM 
		--INNER JOIN sAssetManagement.tAssetInchargeUser AU ON AM.Id = AU.AssetId 
		--INNER JOIN sFixedAsset.tLocationMaster LM ON LM.Id = AM.LocationId
		-- WHERE AU.InchargeUserId = @rUserId AND AM.OrgGroupId = @rOrgGroupId
		 END
		if(@rDashletId='28')
        BEGIN
     --Asset maintenance
			 SELECT LM.Title AS LocationName, AM.Code AS AssetCode, AM.Title AS AssetName,CONVERT(nvarchar(12),
			 AM.LastMaintenanceDate,103) AS LastMaintenanceDate,CONVERT(nvarchar(12),AM.NextMaintenanceDate,103) AS NextMaintenanceDate 
             FROM sAssetManagement.tAssetMaster AM 
             INNER JOIN sAssetManagement.tAssetInchargeUser AU ON AM.Id = AU.AssetId 
             INNER JOIN sFixedAsset.tLocationMaster LM ON LM.Id = AM.LocationId 
                                WHERE AU.InchargeUserId =@rUserId  AND AM.OrgGroupId = @rOrgGroupId
		 END
		if(@rDashletId='29')
        BEGIN
     --Asset Renew
        SELECT LM.Title AS LocationName, AM.Code AS AssetCode, AM.Title AS AssetName, CONVERT(nvarchar(12),
         AM.RenewLastDate,103) AS RenewLastDate, CONVERT(nvarchar(12), AM.RenewNextDate,103) AS RenewNextDate
           FROM sAssetManagement.tAssetMaster AM INNER JOIN sAssetManagement.tAssetInchargeUser AU ON AM.Id = AU.AssetId 
           INNER JOIN sFixedAsset.tLocationMaster LM ON LM.Id = AM.LocationId 
            WHERE ISNULL(AM.IsRenewRequired,0) = 1
            -- AND AM.RenewNextDate >= DATEADD(dd,ISNULL(AM.RenewAlertBeforeDays,0),AM.RenewLastDate) 
             AND convert(Date,@TimeZoneDate) >=  DATEADD(dd,-ISNULL(AM.RenewAlertBeforeDays,0), AM.RenewNextDate)
                           AND AU.InchargeUserId =  @rUserId  AND AM.OrgGroupId = @rOrgGroupId
        END
        --Inward
       IF(@rDashletId='30')
        BEGIN
        DECLARE @InwardRegisterGrid VARCHAR(max)=''
        SELECT  @InwardRegisterGrid = @InwardRegisterGrid + '<tr>
	       <td align="left" scope="col">' + ISNULL(LetterNumber,'') + '</td>
	       <td align="left" scope="col">' + ISNULL(LetterSubject,'') + '</td>
	       <td align="left" scope="col">' + ISNULL(LetterFrom,'') + '</td>
	       <td align="left" scope="col">' + convert(varchar,isnull(ReceivedDate,'01/01/0001'),103) + '</td>
	 	</tr>'		
	 	FROM
	 	 sFrontOffice.tInwardRegister
	 	 WHERE IsReplyRequired=1 AND IsReplied=0 AND OrgId=@rOrgId
	 	 AND ReceivedDate<=convert(Date,@TimeZoneDate)
		 Order by ReceivedDate Desc

	   SELECT Isnull(@InwardRegisterGrid,'') As	InwardRegisterGrid
        END
            --Outward
         IF(@rDashletId='31')
        BEGIN
        DECLARE @OutwardRegisterGrid VARCHAR(max)=''
        SELECT  @OutwardRegisterGrid = @OutwardRegisterGrid + '<tr>
	    <td align="left" scope="col">' + ISNULL(LetterNumber,'') + '</td>
	       <td align="left" scope="col">' + ISNULL(LetterSubject,'') + '</td>
	       <td align="left" scope="col">' + ISNULL(LetterTo,'') + '</td>
	       <td align="left" scope="col">' + convert(varchar,isnull(OutWardDate,'01/01/0001'),103) + '</td>
	 	</tr>'	
	 	FROM
	 	 sFrontOffice.tOutwardRegister
	 	 WHERE IsReplyRequired=1 AND IsReplied=0 AND OrgId=@rOrgId
	 	 AND OutwardDate<=convert(Date,@TimeZoneDate)
		 Order by OutwardDate Desc

	   SELECT Isnull(@OutwardRegisterGrid,'') As	OutwardRegisterGrid
	   END
	   
	   IF(@rDashletId='32')
        BEGIN
        DECLARE @ReorderQuantityGrid VARCHAR(max)=''
        SELECT   @ReorderQuantityGrid=@ReorderQuantityGrid+'<tr>
		     <td align="left" scope="col">' + ISNULL(SE.Title,'')  + '</td>
	        <td align="left" scope="col">' +ISNULL(SM.Title,'')  + '</td>
	      <td align="left" scope="col">' +convert(varchar,ISNULL(SUM(SB.AvailableQuantity),0))+ '</td>
	       <td align="left" scope="col">' + convert(varchar,isnull(SP.ReOrderQuantity,0)) + '</td>
	 	 </tr>'	
	 	FROM
	 	 sProcurement.tStockBatch SB
	 	  INNER JOIN sIp.tStockItemMaster SM ON SM.Id=SB.STockItemID
	 	 INNER JOIN sIp.tStoreLocationMaster SE ON SE.Id=SB.StoreLocationId
	 	 INNER JOIN sIp.tStockItemPlanning SP ON SP.STockItemID=SM.Id AND SP.StoreLocationId =SE.Id
	 	 --INNER JOIN  sSecurity.tUserLocation UL ON UL.StoreLocationId = SB.StoreLocationId
	 	 WHERE  SM.OrgGroupId=@rOrgGroupId AND SM.IsObsolete=0 
	 	 group by SE.Title,SM.Title,SP.ReOrderQuantity,SP.ReOrderPoint
	 	 HAVING SUM(SB.AvailableQuantity) < SP.ReOrderPoint
	   
		SELECT Isnull(@ReorderQuantityGrid,'') As	ReorderQuantityGrid
		END
		
		 IF(@rDashletId='33')
        BEGIN
        DECLARE @SafetyStockGrid VARCHAR(max)=''
        SELECT   @SafetyStockGrid=@SafetyStockGrid+'<tr>
		     <td align="left" scope="col">' + ISNULL(SE.Title,'')  + '</td>
	        <td align="left" scope="col">' +ISNULL(SM.Title,'')  + '</td>
	      <td align="left" scope="col">' +convert(varchar,ISNULL(SUM(SB.AvailableQuantity),0))+ '</td>
	       <td align="left" scope="col">' + convert(varchar,isnull(SP.SafetyStock,0)) + '</td>
	 	 </tr>'	
	 	FROM
	 	 sProcurement.tStockBatch SB
	 	  INNER JOIN sIp.tStockItemMaster SM ON SM.Id=SB.STockItemID
	 	 INNER JOIN sIp.tStoreLocationMaster SE ON SE.Id=SB.StoreLocationId
	 	 INNER JOIN sIp.tStockItemPlanning SP ON SP.STockItemID=SM.Id AND SP.StoreLocationId =SE.Id
	 	 --INNER JOIN  sSecurity.tUserLocation UL ON UL.StoreLocationId = SB.StoreLocationId
	 	 WHERE  SM.OrgGroupId=@rOrgGroupId AND SM.IsObsolete=0 
	 	 group by SE.Title,SM.Title,SP.SafetyStock,SP.ReOrderPoint
	 	 HAVING SUM(SB.AvailableQuantity) < SP.SafetyStock
	   
		SELECT Isnull(@SafetyStockGrid,'') As	SafetyStockGrid
        END
		 IF(@rDashletId='34')
		 BEGIN 
		 DECLARE @Increment varchar(max)=''
		 SELECT @Increment=@Increment+'<tr>
		  <td align="left" scope="col">' + ISNULL(EM.FirstName,'') + ' '+ISNULL(EM.LastName,'') + '</td>
	        <td align="left" scope="col">' +convert(varchar,isnull(IncrementDate,'01/01/0001'),103)  + '</td></tr>'
		FROM sHrm.tEmployeeStatutoryAndOther SA
		INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id=SA.EmployeeId
		WHERE IncrementDate BETWEEN GETDATE()-1 AND GETDATE()+7
		AND EM.OrgID=@rOrgId And EM.StatusId=7
		SELECT Isnull(@Increment, '') As	IncrementGrid
		END
		
			 IF(@rDashletId='78')
		 BEGIN 
		 DECLARE @Retirement varchar(max)=''
		 SELECT @Retirement=@Retirement+'<tr>
		  <td align="left" scope="col">' + ISNULL(EM.FirstName,'') + ' '+ISNULL(EM.LastName,'') + '</td>
	        <td align="left" scope="col">' +convert(varchar,isnull(RetirementDate,'01/01/0001'),103)  + '</td></tr>'
		FROM sHrm.tEmployeeStatutoryAndOther SA
		INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id=SA.EmployeeId
		WHERE RetirementDate BETWEEN GETDATE()-1 AND GETDATE()+30
		AND EM.OrgID=@rOrgId And EM.StatusId=7
		SELECT Isnull(@Retirement, '') As RetirementGrid
		END

	if(@rDashletId='83')
        BEGIN
			SELECT SA.Name,L.LeaveFromDate,L.LeaveToDate 
			FROM  sAttendance.tStudentLeaveRequest L   
			INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId = L.AcademicId  
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId    
			WHERE  
				 SA.BatchId = @rBatchId
				AND SA.OrgId = @rOrgId
				--Comment for Mantis Id:0029925
				--AND ((L.LeaveFromDate <= @rDate) OR (ISNULL(@rDate,'') = ''))
				--AND ((L.LeaveToDate >= @rDate) OR (ISNULL(@rDate,'') = ''))
				AND SA.StatusId=1
				AND L.StatusId IS NULL
		END
  END
GO
PRINT N'Altering Procedure [sStudent].[pDigitalFormMasterScopeDetailGet]...';


GO
ALTER PROCEDURE [sStudent].[pDigitalFormMasterScopeDetailGet]
	@rSourceId bigint = 0,
	@rSourceTypeId int = 0,
	@rDigitalFormId bigint = 0
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 	
	  IF(@rDigitalFormId != 0)
	  BEGIN
		SELECT
			 DS.DigitalFormId,
			 DS.SourceTypeId as SourceTypeId,
			 DS.SourceId as SourceId,
			 OM.DisplayTitle AS Source,
			 'Organization' AS SourceType,
			 '' AS RollNo,
             '' AS Code,
             '' AS ClassDepartment,
             OM.DisplayTitle AS OrgName
			 
			FROM sStudent.tDigitalFormScope DS
			INNER JOIN sSetup.tOrganizationMaster OM
				ON DS.SourceId=OM.Id
			WHERE DS.DigitalFormId=@rDigitalFormId AND DS.SourceTypeId=2021

			UNION ALL

			SELECT
			 DS.DigitalFormId,
			 DS.SourceTypeId  as SourceTypeId,
			 DS.SourceId as SourceId,
			 DM.DisplayTitle AS Source,
			 'Department' AS SourceType,
			 '' AS RollNo,
             '' AS Code,
             DM.Title AS ClassDepartment,
             OM.DisplayTitle AS OrgName 
			 
			FROM sStudent.tDigitalFormScope DS
			INNER JOIN sSetup.tDepartmentMaster DM
				ON DS.SourceId=DM.Id
			INNER JOIN sSetup.tOrganizationMaster OM
				ON DM.OrgId=OM.Id  
			WHERE DS.DigitalFormId=@rDigitalFormId AND DS.SourceTypeId=2017

			UNION ALL

			SELECT
			 DS.DigitalFormId,
			 DS.SourceTypeId as SourceTypeId,
			 DS.SourceId as SourceId,
			 CM.DisplayTitle AS Source,
			 'Class' AS SourceType,
			 '' AS RollNo,
             '' AS Code,
             DMast.Title AS ClassDepartment,
             OM.DisplayTitle AS OrgName 
			 
			FROM sStudent.tDigitalFormScope DS
			INNER JOIN  sSetup.tClassMaster CM
				ON DS.SourceId=CM.Id
			INNER JOIN sSetup.tDepartmentMaster DMast
				ON CM.DepartmentId =DMast.Id		
			INNER JOIN sSetup.tOrganizationMaster OM
				ON DMast.OrgId=OM.Id 
			WHERE DS.DigitalFormId=@rDigitalFormId AND DS.SourceTypeId=2016

			UNION ALL

			SELECT
			 DS.DigitalFormId,
			 DS.SourceTypeId as SourceTypeId,
			 DS.SourceId as SourceId,
			 (CM.DisplayTitle + '-' + DM.DisplayTitle) AS Source,
			 'Division' AS SourceType,
			 '' AS RollNo,
             '' AS Code,
             DMast.Title AS ClassDepartment,
             OM.DisplayTitle AS OrgName 
			 
			FROM sStudent.tDigitalFormScope DS
			INNER JOIN   sSetup.tDivisionMaster DM
				ON DS.SourceId=DM.Id
			INNER JOIN 	sSetup.tClassMaster CM
				ON DM.ClassId=CM.Id	
			INNER JOIN sSetup.tDepartmentMaster DMast
				ON CM.DepartmentId =DMast.Id
			INNER JOIN sSetup.tOrganizationMaster OM
				ON DMast.OrgId=OM.Id 
			WHERE DS.DigitalFormId=@rDigitalFormId AND DS.SourceTypeId=2005


			UNION ALL
			
			SELECT
			 DS.DigitalFormId,
			 DS.SourceTypeId as SourceTypeId,
			 DS.SourceId as SourceId,
			 [sStudent].[fStudentNameGet](SM.FirstName , SM.MiddleName, SM.LastName,OM.StudentNameFormatId ) AS Source,
			 'Student' AS SourceType,
			 SA.RollNo,
             SA.Code,
             SA.ClassName+' - '+SA.DivisionName AS ClassDepartment,
             OM.DisplayTitle AS OrgName 
			 
			FROM sStudent.tDigitalFormScope DS
		    INNER JOIN sStudent.tStudentMaster SM
				ON DS.SourceId=SM.Id
			INNER JOIN  sStudent.vStudentAcademic SA
				ON DS.SourceId=SA.StudentId AND SA.IsActiveBatch=1 AND SA.StatusId=1		
			INNER JOIN sSetup.tOrganizationMaster OM
				ON SM.OrgId = OM.Id 
			WHERE DS.DigitalFormId=@rDigitalFormId AND DS.SourceTypeId=2003
			
			UNION ALL
			
			SELECT
			 DS.DigitalFormId,
			 DS.SourceTypeId as SourceTypeId,
			 DS.SourceId as SourceId,
			 SA.Name AS Source,
			 'Student' AS SourceType,
			 SA.RollNo,
             SA.Code,
             SA.ClassName+' - '+SA.DivisionName AS ClassDepartment,
             OM.DisplayTitle AS OrgName 
			 
			FROM sStudent.tDigitalFormScope DS
		   	INNER JOIN  sStudent.vStudentAcademic SA
				ON DS.SourceId=SA.AcademicId AND SA.IsActiveBatch=1 AND SA.StatusId=1
			INNER JOIN sSetup.tOrganizationMaster OM
				ON SA.OrgId = OM.Id	 
			WHERE DS.DigitalFormId=@rDigitalFormId AND DS.SourceTypeId=2001
			 
	  END
	  ELSE IF(@rSourceId != 0 AND @rSourceTypeId != 0)
	  BEGIN
		SELECT
			  
			 [sStudent].[fStudentNameGet](SM.FirstName , SM.MiddleName, SM.LastName,OM.StudentNameFormatId ) AS Source,
			 'Student' AS SourceType,
			 SA.RollNo,
             SA.Code,
             SA.ClassName+' - '+SA.DivisionName AS ClassDepartment,
             OM.DisplayTitle AS OrgName 
			 
			FROM 
			sStudent.tStudentMaster SM
			INNER JOIN  sStudent.vStudentAcademic SA
				ON SM.Id=SA.StudentId AND SA.IsActiveBatch=1 AND SA.StatusId=1		
			INNER JOIN sSetup.tOrganizationMaster OM
				ON SM.OrgId = OM.Id
			 
			WHERE SM.Id=@rSourceId AND @rSourceTypeId=2003
		UNION ALL
		SELECT
			 DM.DisplayTitle AS Source,
			 'Department' AS SourceType,
			 '' AS RollNo,
             '' AS Code,
             DM.Title AS ClassDepartment,
             OM.DisplayTitle AS OrgName 
			FROM  
			 sSetup.tDepartmentMaster DM
			INNER JOIN sSetup.tOrganizationMaster OM
				ON DM.OrgId=OM.Id 
			WHERE DM.Id=@rSourceId AND @rSourceTypeId=2017

		UNION ALL
		SELECT
			 CM.DisplayTitle AS Source,
			 'Class' AS SourceType,
			 '' AS RollNo,
             '' AS Code,
             DMast.Title AS ClassDepartment,
             OM.DisplayTitle AS OrgName 
			 
			FROM  
			 sSetup.tClassMaster CM
			INNER JOIN sSetup.tDepartmentMaster DMast
				ON CM.DepartmentId =DMast.Id		
			INNER JOIN sSetup.tOrganizationMaster OM
				ON DMast.OrgId=OM.Id
			WHERE CM.Id=@rSourceId AND @rSourceTypeId=2016

		UNION ALL
		SELECT
			  
			 DM.Code AS Source,
			 'Division' AS SourceType,
			 '' AS RollNo,
             '' AS Code,
             DMast.Title AS ClassDepartment,
             OM.DisplayTitle AS OrgName 
			 
			FROM  
			  sSetup.tDivisionMaster DM
			INNER JOIN 	sSetup.tClassMaster CM
				ON DM.ClassId=CM.Id	
			INNER JOIN sSetup.tDepartmentMaster DMast
				ON CM.DepartmentId =DMast.Id
			INNER JOIN sSetup.tOrganizationMaster OM
				ON DMast.OrgId=OM.Id		
			 
			WHERE DM.Id=@rSourceId AND @rSourceTypeId=2005
		UNION ALL
		SELECT  OM.DisplayTitle AS Source,
			 'Organization' AS SourceType,
			 '' AS RollNo,
             '' AS Code,
             '' AS ClassDepartment,
             OM.DisplayTitle AS OrgName  FROM sSetup.tOrganizationMaster OM  WHERE   OM.Id = @rSourceId AND @rSourceTypeId = 2021
		
	  END
END
GO
PRINT N'Altering Procedure [sStudent].[pImportStudentLakshya]...';


GO
ALTER PROCEDURE sStudent.pImportStudentLakshya
	@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
			,@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
			,@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)
			,@lEmergencyContactNo NVARCHAR(20)
			,@lBirthPlace NVARCHAR(150)
			,@lBirthTaluka NVARCHAR(150)
			,@lBirthDistrict NVARCHAR(150)
			,@lBirthDateInWord NVARCHAR(150)
			,@lHouseId INT
			,@lHouse NVARCHAR(100)
			,@lMotherTongue NVARCHAR(100)
			,@lAdhaarNumber NVARCHAR(20)
			,@lUIDNumber NVARCHAR(50)
			,@lQuotaId INT
			,@lQuota NVARCHAR(100)
			,@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
			,@lFeesRemark NVARCHAR(500)

			,@lPayType nvarchar(500)
			,@lCheque_ReferenceNo nvarchar(500)

		DECLARE @EmployeeId BIGINT
		DECLARE @OutStudentId BIGINT
		
		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)
			,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)
			,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
			,FeesRemark NVARCHAR(500)
			,PayType NVARCHAR(500)
			,Cheque_ReferenceNo NVARCHAR(500)
			)

		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
			,FamilyCast
			,FamilySubCast
			,CastCategoryId
			,CastCategory
			,ParentContactNo
			,ParentEmail
			,StudentContactNo
			,StudentEmail
			,PresentStreetOne
			,PresentStreetTwo
			,PresentStreetThree
			,PresentCity
			,PresentZipCode
			,PresentState
			,PresentCountry
			,PresentContactNo
			,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
			,FeesRemark
			,PayType
			,Cheque_ReferenceNo
			)
		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
			,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
			,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
			,sSetup.fPortalXMLTagsReplaceReverse(FeesRemark) AS FeesRemark
			,sSetup.fPortalXMLTagsReplaceReverse(PayType) AS PayType
			,sSetup.fPortalXMLTagsReplaceReverse(Cheque_ReferenceNo) AS Cheque_ReferenceNo
		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'
				,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'
				,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'
				,FeesRemark NVARCHAR(200) '@FeesRemark'
				,PayType NVARCHAR(500) '@CustomField_PayType'
				,Cheque_ReferenceNo NVARCHAR(500) '@CustomField_Cheque_ReferenceNo'
				)

		EXEC sp_xml_removedocument @intDoc
		
		SELECT * FROM #tTable
		
		SELECT @lCount = COUNT(Id) FROM #tTable

		WHILE @lCount > 0
BEGIN
BEGIN TRANSACTION
			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 @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 @lEmergencyContactNo = ''
			SET @lBirthPlace = ''
			SET @lBirthTaluka = ''
			SET @lBirthDistrict = ''
			SET @lBirthDateInWord = ''
			SET @OutStudentId = NULL
			SET @lHouseId = NULL
			SET @lHouse = ''
			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 = ''
			SET @lFeesRemark = ''
			SET @lPayType = ''
			SET	@lCheque_ReferenceNo = ''

			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
				,@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
				,@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
				,@lFeesRemark = FeesRemark
				,@lPayType = PayType
				,@lCheque_ReferenceNo = Cheque_ReferenceNo
			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 @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 @lTribeId = ID FROM sCommon.tTribeMaster WHERE Title = @lTribe

			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

			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
					,@lFeesRemark

				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

				SET @1StudentId = @OutStudentId
			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()
						,FeesRemark = @lFeesRemark
					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

			SELECT Id FROM sStudent.tStudentCustomFieldMaster WHERE FieldTitle = 'PayType'

			DECLARE @lStudentCustomFieldPayTypeId int = (SELECT Id FROM sStudent.tStudentCustomFieldMaster WHERE FieldTitle = 'PayType')
			IF EXISTS(SELECT 1 FROM sStudent.tStudentCustomFieldData WHERE StudentCustomFieldId = @lStudentCustomFieldPayTypeId AND StudentId = @1StudentId)
			BEGIN
				UPDATE sStudent.tStudentCustomFieldData SET FieldData = @lPayType WHERE StudentCustomFieldId = @lStudentCustomFieldPayTypeId AND StudentId = @1StudentId
			END
			ELSE
			BEGIN
				INSERT INTO sStudent.tStudentCustomFieldData 
				(StudentId, StudentCustomFieldId, FieldData, CreatedUserId, CreatedDateTime, UpdatedUserId, UpdatedDateTime)
				VALUES
				(@1StudentId, @lStudentCustomFieldPayTypeId, @lPayType, @rUserId, GETDATE(), @rUserId, GETDATE())
			END


			DECLARE @lStudentCustomFieldChequeId int = (SELECT Id FROM sStudent.tStudentCustomFieldMaster WHERE FieldTitle = 'Cheque_ReferenceNo')
			IF EXISTS(SELECT 1 FROM sStudent.tStudentCustomFieldData WHERE StudentCustomFieldId = @lStudentCustomFieldChequeId AND StudentId = @1StudentId)
			BEGIN
				UPDATE sStudent.tStudentCustomFieldData SET FieldData = @lCheque_ReferenceNo WHERE StudentCustomFieldId = @lStudentCustomFieldChequeId AND StudentId = @1StudentId
			END
			ELSE
			BEGIN
				INSERT INTO sStudent.tStudentCustomFieldData 
				(StudentId, StudentCustomFieldId, FieldData, CreatedUserId, CreatedDateTime, UpdatedUserId, UpdatedDateTime)
				VALUES
				(@1StudentId, @lStudentCustomFieldChequeId, @lCheque_ReferenceNo, @rUserId, GETDATE(), @rUserId, GETDATE())
			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 [sStudent].[pRptClassDivisionCapacityGet]...';


GO

ALTER PROCEDURE [sStudent].[pRptClassDivisionCapacityGet]
	
		@rBuilder1 nvarchar(max)='',
		@rBuilder2 nvarchar(max)='', 
		@rOrgMainGroupId int,
		@rOrgSubGroupId int,
		@rOrgId int,
		@rDepartmentId int,
		@rClassId int,
		@rDivisionId int,
		@rOrgGroupId int,
		@rOrgGroupBatchId int 
	
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
	SELECT 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			CM.Id AS ClassId,
			CM.DisplayTitle AS ClassName,
			CM.OrderIndex,
			CM.DepartmentId,
			DeptM.DisplayTitle AS DepartmentName,
			OMGM.Id AS OrgMainGroupId,
			OMGM.Title AS OrgMainGroupTitle,
			OSGM.Id AS OrgSubGroupId,
			OSGM.Title AS OrgSubGroupTitle,
			OM.Id AS OrgId,
			OM.DisplayTitle AS OrgDisplayTitle,
			ISNULL(CM.Capacity,0) AS ClassCapacity,
			ISNULL(DM.Capacity,0) AS DivisionCapacity,

			(SELECT ISNULL(count(1),0) FROM sStudent.tAcademic A 
			--INNER JOIN sStudent.tStudentMaster SM ON A.StudentId = SM.Id 
			INNER JOIN sSetup.tBatchMaster BM ON A.BatchId = BM.Id
			--INNER JOIN sSetup.tBatchGroupMaster BGM ON BGM.ID=BM.BatchgroupId
			WHERE A.DivisionId = DM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId			
			) AS DivisionCurrentStrength,

			(SELECT ISNULL(count(1),0) FROM sStudent.tAcademic A 
			INNER JOIN sStudent.tStudentMaster SM ON A.StudentId = SM.Id 
			INNER JOIN sSetup.tBatchMaster BM ON A.BatchId = BM.Id
			--INNER JOIN sSetup.tBatchGroupMaster BGM ON BGM.ID=BM.BatchgroupId
			WHERE A.DivisionId = DM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
			AND SM.StatusId = 3 			
			) AS LeftStudentDivisionWise,

			(SELECT ISNULL(count(1),0) FROM sStudent.tAcademic A 
			INNER JOIN sStudent.tStudentMaster SM ON A.StudentId = SM.Id 
			INNER JOIN sSetup.tBatchMaster BM ON A.BatchId = BM.Id
			--INNER JOIN sSetup.tBatchGroupMaster BGM ON BGM.ID=BM.BatchgroupId
			WHERE A.DivisionId = DM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
			AND SM.StatusId = 2			
			) AS InActiveStudentDivisionWise,
			DM.Title AS  DivisionName
					
	FROM 
			sSetup.tDivisionMaster DM
			INNER JOIN sSetup.tClassMaster CM ON CM.Id=DM.ClassId
			INNER JOIN sSetup.tBatchClass BC ON CM.Id=BC.ClassId
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = BC.BatchId
			INNER JOIN sSetup.tDepartmentMaster DeptM ON DeptM.Id=CM.DepartmentId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = DM.OrgId
			INNER JOIN sSetup.tOrgSubGroupMaster OSGM ON OSGM.Id = OM.OrgSubGroupId
			INNER JOIN sSetup.tOrgMainGroupMaster OMGM ON OMGM.Id = OSGM.OrgMainGroupId
			--LEFT JOIN 
  WHERE 
			BM.OrgGroupBatchId = @rOrgGroupBatchId
			AND ((CM.DepartmentId = @rDepartmentId) OR (@rDepartmentId = 0))
			AND ((DM.Id=@rDivisionId) OR (@rDivisionId=0)) 
			AND ((CM.Id=@rClassId) OR (@rClassId=0))
			AND ((OMGM.Id=@rOrgMainGroupId) OR (@rOrgMainGroupId=0))
			AND ((OSGM.Id=@rOrgSubGroupId) OR (@rOrgSubGroupId=0))
			AND ((OM.Id=@rOrgId) OR (@rOrgId=0))
			AND ((OM.OrgGroupId = @rOrgGroupId))
			
			ORDER BY CM.OrderIndex ASC
END
GO
PRINT N'Altering Procedure [sStudent].[pStudentViewProfileGet]...';


GO


ALTER PROCEDURE [sStudent].[pStudentViewProfileGet]
	 
	 @rBatchId int,
	 @rAcademicId bigint,
	 @rReportId int=0,
	 @rOrgId int,
	 @rOrgGroupBatchId int
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
	
	SELECT 
			SA.StudentId AS Id,
			SA.SUId,
			SA.FirstName + ' ' + ISNULL(SA.MiddleName,'') + ' ' + 	SA.LastName AS StudentName,
			ISnull(SA.Batch,'') AS AcademicYear,
			ISNULL(SA.Code,' ') AS Code,
			SA.ClassDivision AS ClassDiv,			
			Isnull(SA.RollNo,'') AS RollNo,
			convert(varchar,ISNULL(SA.DateOfBirth,'0001/01/01'),103) AS DateOfBirth,
			ISNULL(SM.Title,'-') AS House,
			ISNULL(SA.BirthTaluka,'') AS BirthTaluka,
			ISNULL(SA.BirthPlace,'') AS BirthPlace,	
			ISNULL(SA.BirthDistrict,'') AS BirthDistrict,
			ISNULL(SA.BirthDateInWord,'') AS BirthDateInWord,                           
			ISNULL(SA.Gender,'') AS Gender,
			ISNULL(SA.Religion,'') AS Religion,
			ISNULL(SA.AdmissionStandard,'') AS AdmissionStandard,
			convert(varchar,ISNULL(SA.AdmissionDate,'0001/01/01'),103) AS AdmissionDate,
			ISNULL(SA.PreviousSchool,'') AS PreviousSchool,
			ISNULL(SA.AdmissionCategory,'') AS StudentAdmissionCategory,
            convert(varchar,ISNULL(SA.LeftDate,'0001/01/01'),103) AS LeftDate,
			ISNULL(SA.LeftStandard,'') AS LeftStandard,
			convert(varchar,ISNULL(SA.InactiveDate,'01/01/0001'),103) AS InactiveDate,
			ISNULL(SA.LCNumber,'') AS LCNumber,
			convert(varchar,ISNULL(SA.LCDate,'01/01/0001'),103) AS LCDate,
			ISNULL(SA.PresentStreetone,'') + ' ' + ISNULL(SA.PresentStreetTwo,'') + ' ' + ISNULL(SA.PresentStreetThree,'') AS PresentAddress,
			ISNULL(SA.PresentCity,'') AS PresentCity,
			ISNULL(SA.PresentState,'') AS PresentState,
			ISNULL(SA.PresentCountry,'') AS PresentCountry,
			ISNULL(SA.PresentZipCode,'') AS PresentZipCode,
			ISNULL(SA.PresentContactNo,'') AS PresentContactNo,
			ISNULL(SA.EmergencyStreetOne,'') + ' ' + ISNULL(SA.EmergencyStreetTwo,'') + ' ' + ISNULL(SA.EmergencyStreetThree,'') AS EmergencyAddress,
			ISNULL(SA.EmergencyCity,'') AS EmergencyCity,
			ISNULL(SA.EmergencyState,'') AS EmergencyState,
			ISNULL(SA.EmergencyCountry,'') AS EmergencyCountry,
			ISNULL(SA.EmergencyZipCode,'') AS EmergencyZipCode,
			ISNULL(SA.EmergencyContactNo,'') AS EmergencyContactNo,
			ISNULL(SA.PermanentStreetOne,'') + ' ' + ISNULL(SA.PermanentStreetTwo,'') + ' ' + ISNULL(SA.PermanentStreetThree,'') AS PermanentAddress,
			ISNULL(SA.PermanentCity,'') AS PermanentCity,
			ISNULL(SA.PermanentState,'') AS PermanentState,
			ISNULL(SA.PermanentCountry,'') AS PermanentCountry,
			ISNULL(SA.PermanentZipCode,'') AS PermanentZipCode,
			ISNULL(SA.PermanentContactNo,'') AS PermanentContactNo,
			ISNULL(SF.FatherName,'') AS FatherName,
			ISNULL(SF.FatherOccupation,'') AS FatherOccupation,
			ISNULL(SF.FatherQualification,'') AS FatherQualification,
			ISNULL(SF.FatherContactNo,'') AS FatherContactNo,
			ISNULL(SF.FatherMail,'') AS FatherMail,
			ISNULL(SF.FatherOfficeAddress,'') AS FatherOfficeAddress,
			ISNULL(SF.FatherDesignation,'') AS FatherDesignation,
			ISNULL(SF.FatherOrganization,'') AS FatherOrganization,
			ISNULL(SF.MotherName,'') AS MotherName,
			ISNULL(SF.MotherOccupation,'') AS MotherOccupation,
			ISNULL(SF.MotherQualification,'') AS MotherQualification,
			ISNULL(SF.MotherContactNo,'') AS MotherContactNo,
			ISNULL(SF.MotherMail,'') AS MotherMail,
			ISNULL(SF.MotherOfficeAddress,'') AS MotherOfficeAddress,
			ISNULL(SF.MotherDesignation,'') AS MotherDesignation,
			ISNULL(SF.MotherOrganization,'') AS MotherOrganization,
			ISNULL(SF.RelationshipName,'') AS RelationShip,
			ISNULL(SF.RelativeName,'') AS RelativeName,
			ISNULL(SF.RelativeOccupation,'') AS RelativeOccupation,
			ISNULL(SF.RelativeQualification,'') AS RelativeQualification,
			ISNULL(SF.RelativeContactNo,'') AS RelativeContactNo,
			ISNULL(SF.RelativeMail,'') AS RelativeMail,
			ISNULL(SF.RelativeOfficeAddress,'') AS RelativeOfficeAddress,
			ISNULL(SF.RelativeDesignation,'') AS RelativeDesignation,
			ISNULL(SF.RelativeOrganization,'') AS RelativeOrganization,
			ISNULL(SA.BloodGroup,'') AS BloodGroup,
			ISNULL(SH.IdentificationMark1,'')+' '+ISNULL(SH.IdentificationMark2,'') as IdentificationMark,
			ISNULL(SH.FamilyDoctorName,'') AS FamilyDoctorName,
			ISNULL(SH.FamilyDoctorContactNo,'') AS FamilyDoctorContactNo,
			case When isnull(SH.IsPysicalDeformity,0)=0 then 'NO' Else 'Yes' End As IsPysicalDeformity,
			SH.PysicalDeformityRemark ,
			case When isnull(SH.IsMajorIllness,0)=0 then 'NO' Else 'Yes' End As IsMajorIllness,
			ISNULL(SH.MajorIllnessRemark,'') As MajorIllnessRemark,
			 case When isnull(SH.IsAllergy,0)=0 then 'NO' Else 'Yes' End As IsAllergy,
			ISNULL(SH.AllergyRemark,'') As AllergyRemark,
			 case When isnull(SH.IsPastHistory,0)=0 then 'NO' Else 'Yes' End As IsPastHistory,
			ISNULL(SH.PastHistoryRemark,'') As PastHistoryRemark,
			ISNULL(RM.Title,'') AS RoomNo,			
			ISNULL(HM.Title,'') AS Hostel,
			ISNULL(EMW.FirstName,'')+' '+ISNULL(EMW.LastName,'') AS WardenName,
			ISNULL(ECW.PhoneNoCompany,'') As WardenPhoneNo,
			ISNULL(ECW.ExtensionNo,'') AS WardenExtNo,
			ISNULL(ECW.MobileNumber,'') AS WardenMobileNo,
			ISNULL(EMA.FirstName,'')+' '+ISNULL(EMA.LastName,'') AS AssignedRoomBy,	
			ISNULL(ECA.PhoneNoCompany,'') AS AssignedRoomByPhoneNo,
			ISNULL(ECA.ExtensionNo,'') AS AssignedRoomByExtNo,
			ISNULL(ECA.MobileNumber,'') AS AssignedRoomByMobileNo,
			--Notification Details
			ISNULL(SA.ParentEmail,'') AS ParentEmail,
			ISNULL(SA.ParentContactNo,'') As ParentContactNo,
			ISNULL(SA.WhatsAppContactNo,'') As WhatsAppContactNo,
			ISNULL(SA.StudentEmail,'') AS StudentEmail,
			ISNULL(SA.StudentContactNo,'') AS StudentContactNo,
		    ISnull( A.VehicleName,'') AS VehicleName,
		    ISNULL( A.VehicleRegistrationNumber,'') AS VehicleRegistrationNumber,
		    ISNULL(A.TypeOfVehicle ,'') AS TypeOfVehicle ,
		    ISNULL(A.BusRoute,'') AS BusRoute,
		    ISNULL( A.DriverName,'') AS DriverName,
		    ISNULL(A.DriverMobileNo,'') AS DriverMobileNo,
		    ISNULL( A.ConductorName,'') AS ConductorName,
		    ISNULL( A.ConductorMobileNo,'') AS ConductorMobileNo ,
		    ISNULL(A.BusRouteDestination,'') AS BusRouteDestination,
		    isnull(A.DropVehicleName,'') AS DropVehicleName,
		    isnull(A.DropVehicleRegistrationNumber,'') AS DropVehicleRegistrationNumber,
		    isnull(A.DropTypeOfVehicle,'') AS DropTypeOfVehicle,
		    ISNULL(A.DropRoute,'') AS DropRoute,
		    isnull( A.DriverName,'') AS DropRouteDriverName,
		    isnull(A.DriverMobileNo,'') AS DropRouteDriverMobileNo,
		    isnull(A.ConductorName,'') AS DropRouteConductorName,
		    isnull(A.ConductorMobileNo,'') AS DropRouteConductorMobileNo,
		    ISNULL(A.DropDestination,'') AS DropDestination,
		    --ISNULL( EMT.FirstName+' '+EMT.MiddleName+' '+EMT.LastName,'') AS TeacherFullName,
		    --isnull( EDM.Title,'') AS TeacherDesignation,
		    --ISNULL( EPD.Qualification,'') AS TeacherQualification,
		    ISNULL(DF.IsDisplayFamilyDetail,0) AS IsDisplayFamilyDetail,
		    ISNULL(DF.IsDisplaySiblingDetail,0) AS IsDisplaySiblingDetail,
		    ISNULL(DF.IsDisplayPassportDetail,0) AS IsDisplayPassportDetail,
		    ISNULL(DF.IsDisplayBankDetail,0) AS IsDisplayBankDetail,
		    ISNULL(DF.IsDisplayCBSEREGDetail,0) AS IsDisplayCBSEREGDetail,
		    ISNULL(DF.IsDisplayCollegeDetail,0) AS IsDisplayCollegeDetail,
		    ISNULL(DF.IsDisplayGOVREGNoDetail,0) AS IsDisplayGOVREGNoDetail,
		    ISNULL(DF.IsDisplayHealthDetail,0) AS IsDisplayHealthDetail,
		    ISNULL(DF.IsDisplayTransportDetail,0) AS IsDisplayTransportDetail,
		    ISNULL(DF.IsDisplayHostelDetail,0) AS IsDisplayHostelDetail,
		    ISNULL(DF.IsDisplayClubDetail,0) AS IsDisplayClubDetail,
		    
		    ISNULL(DF.IsDisplaySSCResultDDetail,0) AS IsDisplaySSCResultDDetail,
		    ISNULL(DF.IsDisplayHSCResultDetail,0) AS IsDisplayHSCResultDetail,
		    ISNULL(DF.IsDisplayJeeDetail,0) AS IsDisplayJeeDetail,
		    ISNULL(DF.IsDisplayDiplomaDetail,0) AS IsDisplayDiplomaDetail,
		
		    isnull(SS.SiblingName1,'') AS SiblingName1,
	        ISNULL (SS.SiblingInstitue1,'') AS SiblingInstitue1,
	        ISNULL(SS.SiblingClass1,'')AS SiblingClass1,
	        ISNULL(SS.SiblingAge1,'')AS SiblingAge1,
	        ISNULL(SS.SiblingRelation1,'')AS SiblingRelation1,
	        isnull(SS.SiblingName2,'') AS SiblingName2,
	        ISNULL(SS.SiblingInstitue2,'')AS SiblingInstitue2,
	        ISNULL(SS.SiblingClass2,'')AS SiblingClass2,
	        ISNULL(SS.SiblingAge2,'') AS SiblingAge2,
	        ISNULL(SS.SiblingRelation2,'')AS SiblingRelation2,
	        isnull(SS.SiblingName3,'') AS SiblingName3,
	        ISNULL( SS.SiblingInstitue3,'')AS SiblingInstitue3,
	        ISNULL(SS.SiblingClass3,'')AS SiblingClass3,
	        ISNULL(SS.SiblingAge3,'')AS SiblingAge3,
	        ISNULL(SS.SiblingRelation3,'')AS SiblingRelation3,
	        ISNULL(SAD.BankAccountNumber,'')AS BankAccountNumber,
	        ISNULL(SAD.BankName,'')AS BankName,
	        ISNULL(SAD.BankBranch,'') AS BankBranch,
	        ISNULL(SAD.BankIFSCCode,'')AS BankIFSCCode,
	        ISNULL(SAD.Class9BoardRegistrationNumber,'') AS Class9BoardRegistrationNumber,
	        ISNULL(SAD.Class11BoardRegistrationNumber,'')AS Class11BoardRegistrationNumber,
	        ISNULL(SAD.PassportNumber,'')AS PassportNumber, 
	        ISNULL(SAD.PassportType,'') AS PassportType,
	        ISNULL( SAD.PassportCountryCode,'') AS PassportCountryCode,
	       	convert(varchar,ISNULL(SAD.PassportExpiryDate,'01/01/0001'),103) AS PassportExpiryDate,
	       	convert(varchar,ISNULL(SAD.PassportIssueDate,'01/01/0001'),103) AS PassportIssueDate,
	        ISNULL(SA.UIDNumber,'')AS UIDNumber,
	        ISNULL(SA.AdhaarNumber,'') AS AdhaarNumber,
	        case When isnull(SA.IsTransfer,0)=0 then 'No' Else 'Yes' End As IsTransfer,
	        ISNULL(SA.TransferFrom,'') AS TransferFrom,
	        ISNULL(SA.CertificateName,'') AS CertificateName,
	        case When isnull(SA.IsTFWS,0)=0 then 'No' Else 'Yes 'End As IsTFWS,
	        case When isnull(SA.IsCertificateHolder,0)=0 then 'No' Else 'Yes' End As IsCertificateHolder,
	        ISNULL(CD.SSCBoard,'') AS SSCBoard,
	        ISNULL(CD.SSCSchool,'') AS SSCSchool,
	        ISNULL(CD.SSCPassingYear,'') AS SSCPassingYear,
	        ISNULL(CD.SSCObtainMarks,0) AS SSCObtainMarks,
	        ISNULL(CD.SSCOutOfMarks,0) AS SSCOutOfMarks,
	        ISNULL(CD.SSCMathMarks,0) AS SSCMathMarks,
	        ISNULL(CD.SSCMathOutOfMarks,0) AS SSCMathOutOfMarks,
	        ISNULL(CD.SSCPercentage,0) AS SSCPercentage,
	        ISNULL(CD.HSCBoard,'') AS HSCBoard,
	        ISNULL(CD.HSCSchool,'') AS HSCSchool,
	        ISNULL(CD.HSCPassingYear,0) AS HSCPassingYear,
	        ISNULL(CD.HSCObtainMarks,0) AS HSCObtainMarks,
	        ISNULL(CD.HSCOutOfMarks,0) AS HSCOutOfMarks,
	        ISNULL(CD.HSCPercentage,0) AS HSCPercentage,
	        ISNULL(CD.HSCPhysicsMarks,0) AS HSCPhysicsMarks,
	        ISNULL(CD.HSCPhysicsOutOfMarks,0) AS HSCPhysicsOutOfMarks,
	        ISNULL(CD.HSCChemistryMarks,0) AS HSCChemistryMarks,
	        ISNULL(CD.HSCChemistryOutOfMarks,0) AS HSCChemistryOutOfMarks,
	        ISNULL(CD.HSCMathMarks,0) AS HSCMathMarks,
	        ISNULL(CD.HSCMathOutOfMarks,0) AS HSCMathOutOfMarks,
	        ISNULL(CD.HSCBiologyMarks,0) AS HSCBiologyMarks,
	        ISNULL(CD.HSCBiologyOutOfMarks,0) AS HSCBiologyOutOfMarks,
	        ISNULL(CD.PCMMarks,0) AS PCMMarks,
	        ISNULL(CD.PCBMarks,0) AS PCBMarks,
	        ISNULL(CD.JEERollNo,'') AS JEERollNo,
	        ISNULL(CD.JEEMeritNo,'') AS JEEMeritNo,
	        ISNULL(CD.JEEMeritMarks,0) AS JEEMeritMarks,
	        ISNULL(CD.JEEOutOfMarks,0) AS JEEOutOfMarks,
	        ISNULL(CD.DiplomaBoard,'') AS DiplomaBoard,
	        ISNULL(CD.DiplomaCollege,'') AS DiplomaCollege,
	        ISNULL(CD.DiplomaPassingYear,'') AS DiplomaPassingYear,
	        ISNULL(CD.DiplomaObtainMarks,0) AS DiplomaObtainMarks,
	        ISNULL(CD.DiplomaOutOfMarks,0) AS DiplomaOutOfMarks,
	        ISNULL(CD.DiplomaPercentage,0) AS DiplomaPercentage,
	        ISNULL(CD.ApplicationNo,'') AS ApplicationNo,
	        ISNULL(CD.AdmissionRound,0) AS AdmissionRound,
            ISNULL(MS.Title,'') AS MaritalStatus,
	        ISNULL(ACD.RepeatCount,1)AS RepeatCount,
	        ISNULL(SA.MotherTongue,'') As MotherTongue,
	        ISNULL(SA.FamilyCast,'') AS FamilyCast,
			ISNULL(SA.FamilySubCast,'') AS FamilySubCast,
	        ISNULL(CM.Nationality,'') AS Nationality,
            ISNULL(CT.Title,'') AS CasteCategory,
            --StudentPhoto = case when SA.StudentPhoto is null then '' else SA.StudentPhoto end,
	        StudentPhoto=(SELECT CAST(SA.StudentPhoto as varbinary(max)) FOR XML PATH(''), BINARY BASE64) ,
			--TeacherPhoto=(SELECT CAST(EI.EmployeePhoto as varbinary(max)) FOR XML PATH(''), BINARY BASE64) ,
			--FatherPhoto=(SELECT CAST(SA.FatherPhoto as varbinary(max)) FOR XML PATH(''), BINARY BASE64) ,
			MotherPhoto=(SELECT CAST(SA.MotherPhoto as varbinary(max)) FOR XML PATH(''), BINARY BASE64) ,
			RelativePhoto=(SELECT CAST(SA.RelativePhoto as varbinary(max)) FOR XML PATH(''), BINARY BASE64) ,
			ISNULL(SA.PreviousStandard,'')AS PreviousStandard
			,CGG.Title AS CustomGroup
			,SGM.Title As StudentGroup
			,SOGM.Title As StudentOtherGroup
			,ISNULL([sStudent].[fAssignedClubGet](@rAcademicId),'') AS ClubName
			,ISNULL([sStudent].[fAssignedCustomTagGet](@rAcademicId),'') AS CustomTag,
			ISNULL(SA.StudentPhoto, CONVERT(VARBINARY(MAX), 0))AS StudentImage,
		   DID.TeacherFullName,
		   DID.TeacherDesignation,
		   DID.TeacherQualification,
		   TeacherPhoto=(SELECT CAST(DID.TeacherPhoto as varbinary(max)) FOR XML PATH(''), BINARY BASE64),
		   ISNULL(SA.PresentDistanceFromSchool,'') AS PresentDistanceFromSchool, -- Added columns for mantis : 0030712
		   case When isnull(SF.IsFatherExStudent,0)=0 then 'NO' Else 'Yes' End As IsFatherExStudent, -- Added columns for mantis : 0030712
		   ISNULL(SF.FatherPassOutYear,'') AS FatherPassOutYear, -- Added columns for mantis : 0030712
		   case When isnull(SF.IsMotherExStudent,0)=0 then 'NO' Else 'Yes' End As IsMotherExStudent, -- Added columns for mantis : 0030712
		   ISNULL(SF.MotherPassOutYear,'') AS MotherPassOutYear, -- Added columns for mantis : 0030712
		   case When isnull(SF.IsRelativeExStudent,0)=0 then 'NO' Else 'Yes' End As IsRelativeExStudent, -- Added columns for mantis : 0030712
		   ISNULL(SF.RelativePassOutYear,'') AS RelativePassOutYear -- Added columns for mantis : 0030712
		   

  FROM 
           sStudent.vStudentAllDetail SA
           --LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId = SA.StudentId
           LEFT JOIN sStudent.tStudentHealth SH ON SA.StudentId=SH.StudentId
           LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId = SA.StudentId 
           --LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId = SA.StudentId
           LEFT JOIN sActivity.tHouseMaster SM ON SM.ID = SA.HouseId
           LEFT JOIN sHostel.tAssignRoom AR ON AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003  AND ((AR.OrgGroupBatchId=@rOrgGroupBatchId) OR(@rOrgGroupBatchId=0))
           LEFT JOIN sHostel.tRoomMaster RM ON RM.Id=AR.RoomId
           LEFT JOIN sHostel.tHostelMaster HM ON HM.Id=RM.HostelId 
           LEFT JOIN
           (
		   SELECT 
		   employeeId, 
		   HostelId,   
		   ROW_NUMBER() OVER (PARTITION BY HostelId ORDER By HostelId ) as ROWNo 
		   FROM sHostel.tHostelwarden 
            )  HW ON HW.HostelId=HM.Id AND RowNo = 1       
           --LEFT JOIN sHostel.tHostelWarden HW ON HW.HostelId=HM.Id
           LEFT JOIN sHrm.tEmployeeMaster EMW ON HW.EmployeeId=EMW.Id AND  ISNULL(EMW.IsOtherUser,0) = 0
           LEFT JOIN sHrm.tEmployeeMaster EMA ON RM.AssignedEmployeeId=EMA.Id AND  ISNULL(EMA.IsOtherUser,0) = 0
           LEFT JOIN sHrm.tEmployeeCommunications ECW ON EMW.Id=ECW.EmployeeId 
           LEFT JOIN sHrm.tEmployeeCommunications ECA ON  EMA.Id=ECA.EmployeeId
           LEFT JOIN 
           (SELECT AR1.SourceId ,
           ISnull( VM.Title,'') AS VehicleName,
		   ISNULL( VM.RegistrationNumber,'') AS VehicleRegistrationNumber,
		   ISNULL(TV.Title ,'') AS TypeOfVehicle ,
		   ISNULL(BRM.Title,'') AS BusRoute,
		   ISNULL( BRM.DriverName,'') AS DriverName,
		   ISNULL(BRM.DriverMobileNo,'') AS DriverMobileNo,
		   ISNULL( BRM.ConductorName,'') AS ConductorName,
		   ISNULL( BRM.ConductorMobileNo,'') AS ConductorMobileNo ,
		   ISNULL(BRDM.Title,'') AS BusRouteDestination,
		   isnull(VM.Title,'') AS DropVehicleName,
		   isnull(VM.RegistrationNumber,'') AS DropVehicleRegistrationNumber,
		   isnull(TV1.Title,'') AS DropTypeOfVehicle,
		   ISNULL(BRM1.Title,'') AS DropRoute,
		   isnull( BRM1.DriverName,'') AS DropRouteDriverName,
		   isnull(BRM1.DriverMobileNo,'') AS DropRouteDriverMobileNo,
		   isnull(BRM1.ConductorName,'') AS DropRouteConductorName,
		   isnull(BRM1.ConductorMobileNo,'') AS DropRouteConductorMobileNo,
		   ISNULL(BRDM1.Title,'') AS DropDestination

		   FROM sTransport.tAssignRoute AR1 
           INNER JOIN sTransport.tBusRouteDestinationMaster BRDM ON BRDM.Id=AR1.PickupDestinationId AND AR1.SourceTypeId=2003
           INNER JOIN sTransport.tBusRouteMaster BRM ON BRM.Id=BRDM.BusRouteId  AND ((BRM.OrgGroupBatchId=@rOrgGroupBatchId) OR(@rOrgGroupBatchId=0))
           LEFT JOIN sTransport.tVehicleMaster VM ON VM.Id=BRM.VehicleId
           LEFT JOIN sTransport.tVehicleTypeMaster TV ON TV.Id = VM.VehicleTypeId
           LEFT JOIN sTransport.tBusRouteDestinationMaster BRDM1 ON BRDM1.Id=AR1.DropDestinationId
           LEFT JOIN sTransport.tBusRouteMaster BRM1 ON BRM1.Id=BRDM1.BusRouteId AND ((BRM1.OrgGroupBatchId=@rOrgGroupBatchId) OR(@rOrgGroupBatchId=0))
           LEFT JOIN sTransport.tVehicleMaster VM1 ON VM1.Id=BRM1.VehicleId
           LEFT JOIN sTransport.tVehicleTypeMaster TV1 ON TV1.Id = VM1.VehicleTypeId)A ON A.SourceId=SA.StudentId
           --LEFT JOIN sSetup.tDivisionMaster DM ON  DM.Id=SA.DivisionId
           --LEFT JOIN sHrm.tEmployeeMaster EMT ON EMT.Id=DM.InchargeEmployeeId AND  ISNULL(EMT.IsOtherUser,0) = 0
           --LEFT JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EMT.Id
           --LEFT JOIN sHrm.tEmployeeDesignationMaster EDM ON EDM.Id=EJD.EmployeeDesignationId
           --LEFT JOIN sHrm.tEmployeePersonalDetail EPD ON EPD.EmployeeId=EMT.Id
           --LEFT JOIN sHrm.tEmployeeImages EI ON EI.EmployeeId=EMT.Id
		   LEFT JOIN (SELECT * FROM [sStudent].[fDivisionInchargeDetailsGet](@rAcademicId, @rBatchId)) DID ON SA.DivisionId = DID.DivisionId
           LEFT JOIN sStudent.tStudentSibling  SS ON SS.StudentId=SA.StudentId 
           LEFT JOIN sStudent.tStudentAdditional  SAD ON SAD.StudentId=SA.StudentId 
           LEFT JOIN sStudent.tCollegeDetail  CD ON CD.StudentId=SA.StudentId 
           LEFT JOIN sStudent.tAcademicDetail  ACD ON ACD.AcademicId=SA.AcademicId 
           LEFT JOIN sCommon.tMaritalStatusMaster  MS ON MS.Id=CD.MaritalStatusId
           LEFT JOIN sConfig.fDisplayFieldGet(@rOrgId) AS DF ON DF.OrgId=SA.OrgId
           LEFT JOIN sCommon.tCastCategoryMaster CT ON CT.Id = SA.CastCategoryId
           LEFT JOIN sCommon.tCountryMaster CM ON CM.Id=SA.NationalityId
           LEFT JOIN sCommunication.tCustomGroupMember CGM ON CGM.SourceId = SA.AcademicId AND CGM.SourceTypeId = 2001
           LEFT JOIN sCommunication.tCustomGroup CGG ON CGG.Id = CGM.CustomGroupId
           LEFT JOIN sStudent.tStudentMaster SMM ON SMM.Id = SA.StudentId
           LEFT JOIN sStudent.tStudentGroupMaster SGM ON SGM.Id = SMM.StudentGroupId
           LEFT JOIN sStudent.tStudentOtherGroupMaster SOGM ON SOGM.Id = SMM.StudentOtherGroupId
  WHERE 
		   ((SA.AcademicId=@rAcademicId)OR(@rAcademicId=0))
		   AND(SA.BatchId=@rBatchId)
		
END
GO
PRINT N'Altering Procedure [sTool].[pUpgradeVersion]...';


GO

ALTER PROCEDURE [sTool].[pUpgradeVersion]
	 
	@rVersionId int,
	@rVersion nvarchar(20),
	@rOrgGroupId int

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

if 	@rVersionId = 0
BEGIN
SELECT 'Enter Version Id'
return	
END


if 	@rVersion = ''
BEGIN
SELECT 'Enter Version Detail'
return	
END

if 	@rOrgGroupId = 0
BEGIN
SELECT 'Enter Org Group Id'
return	
END



--if 	@rOrgGroupId = 1
--BEGIN
--SELECT '1 OrgGroup Not Valid'
--return	
--END

IF NOT EXISTS (SELECT 1 FROM sSetup.tOrgGroupMaster WHERE Id = @rOrgGroupId)
BEGIN
SELECT 'Org Group Not Exists'
return	
END

-- For Upgrade Vesion Start
INSERT INTO [sSystem].[tVersionUpdate] ([VersionNumber],[VersionId],[Status],[UpdateScript],[StartDateTime],[EndDateTime],[OrgGroupId])
VALUES(@rVersion,@rVersionId,'BEGIN','Upgrade Vesion',sCommon.fGetDate(),sCommon.fGetDate(),@rOrgGroupId)

--exec [sTool].[pInsertStaticData]
		
-- add newly added task for admin role
exec [sSecurity].[pNewTaskAdd] @rOrgGroupId

-- update tablerowid master data from excel to table

--pass orgGroupId
-- add new table row ids added
exec [sTool].[pTableRowIdAdd] @rOrgGroupId

-- Pass OrgGroupId
-- Remove tablrowid for organization
--exec sTool.pTableRowChangeOrgToOrgGroupRemove @rOrgGroupId

update sstudent.tAcademic   set rollno = 0 where RollNo is null



delete from sSecurity.tPermission where TaskId in (select ID from sSecurity.tTask where IsObsolete = 1)
delete from sSecurity.tPermission where TaskId not in (select ID from sSecurity.tTask)




exec [sTool].[pTableRowIdCurrentNumberSet] @rOrgGroupId

IF NOT EXISTS(SELECT 1 FROM sCommunication.teContentTypeMaster WHERE Id = sCommon.fGetIntIdForOrg(1,@rOrgGroupId))
 BEGIN
				INSERT INTO sCommunication.teContentTypeMaster
					   ([Id]
					   ,[Code]
					   ,[Title]
					   ,[IsObsolete]
					   ,[CreatedUserId]
					   ,[CreatedDateTime]
					   ,[UpdatedUserId]
					   ,[UpdatedDateTime]
					   ,[OrgGroupId])
				 SELECT
						 sCommon.fGetIntIdForOrg(1,@rOrgGroupId)
						,'Subject'
						,'Subject'
						,0
						,1
						,getdate()
						,1
						,getdate()
						,@rOrgGroupId
						
 END


IF NOT EXISTS(SELECT 1 FROM sCommunication.tCircularTypeMaster WHERE Id = sCommon.fGetIntIdForOrg(1,@rOrgGroupId))
 BEGIN
				INSERT INTO sCommunication.tCircularTypeMaster
					   ([Id]
					   ,[Code]
					   ,[Title]
					   ,[IsObsolete]
					   ,[CreatedUserId]
					   ,[CreatedDateTime]
					   ,[UpdatedUserId]
					   ,[UpdatedDateTime]
					   ,[OrgGroupId]
					   ,HighlightColor)
				 SELECT
						 sCommon.fGetIntIdForOrg(1,@rOrgGroupId)
						,'Circular'
						,'Circular'
						,0
						,1
						,getdate()
						,1
						,getdate()
						,@rOrgGroupId
						,NULL
 END

IF NOT EXISTS(SELECT 1 FROM sCommon.tPublishDocumentMaster WHERE Id = sCommon.fGetIntIdForOrg(1,@rOrgGroupId))
BEGIN				
				INSERT INTO sCommon.tPublishDocumentMaster
					   ([Id]
					   ,[Code]
					   ,[Title]
					   ,[IsObsolete]
					   ,[CreatedUserId]
					   ,[CreatedDateTime]
					   ,[UpdatedUserId]
					   ,[UpdatedDateTime]
					   ,[OrgGroupId])
				 VALUES
						(sCommon.fGetIntIdForOrg(1,@rOrgGroupId),'Fee Receipt','Fee Receipt',0,1,Getdate(),1,Getdate(),@rOrgGroupId),
						(sCommon.fGetIntIdForOrg(2,@rOrgGroupId),'Bonafide','Bonafide',0,1,Getdate(),1,Getdate(),@rOrgGroupId),
						(sCommon.fGetIntIdForOrg(3,@rOrgGroupId),'Trial','Trial',0,1,Getdate(),1,Getdate(),@rOrgGroupId),
						(sCommon.fGetIntIdForOrg(4,@rOrgGroupId),'Charactor','Charactor',0,1,Getdate(),1,Getdate(),@rOrgGroupId),
						(sCommon.fGetIntIdForOrg(5,@rOrgGroupId),'Id Card','Id Card',0,1,Getdate(),1,Getdate(),@rOrgGroupId)
						
END


IF NOT EXISTS(SELECT 1 FROM sAdmission.tInquiryStatusMaster WHERE OrgGroupId = @rOrgGroupId)
BEGIN				
				INSERT INTO sAdmission.tInquiryStatusMaster
					   ([Id]
					   ,[Code]
					   ,[Title]
					   ,[IsObsolete]
					   ,[CreatedUserId]
					   ,[CreatedDateTime]
					   ,[UpdatedUserId]
					   ,[UpdatedDateTime]
					   ,[OrgGroupId]
					   ,StatusId
					   --,HighlightColor
					   --,InquiryMainStatusId
					   )
				 SELECT
						 sCommon.fGetIntIdForOrg(Id,@rOrgGroupId)
						,Title
						,Title
						,0
						,1
						,getdate()
						,NULL
						,NULL
						,@rOrgGroupId
						,Id	
						--,ISM.HighlightColor
						--,ISM.InquiryMainStatusId					
						FROM sCommon.tStatusMaster
						--INNER JOIN sAdmission.tInquiryStatusMaster ISM ON SM.Id = ISM.StatusId AND ISM.OrgGroupId = 1
						where statustypeId = 104


						UPDATE ISM  
							SET ISM.HighlightColor = ISM1.HighlightColor ,
								ISM.InquiryMainStatusId = ISM1.InquiryMainStatusId
							FROM sAdmission.tInquiryStatusMaster ISM  
							INNER JOIN sAdmission.tInquiryStatusMaster ISM1 ON ISM.StatusId = ISM1.StatusId AND ISM1.OrgGroupId = 1
							INNER JOIN sCommon.tStatusMaster SM ON SM.Id = ISM1.StatusId 
							where SM.statustypeId = 104 AND ISM.OrgGroupId = @rOrgGroupId

						
	DECLARE @lMaxId int
	SET @lMaxId = sCommon.fGetIntIdForOrg(213,@rOrgGroupId)					
	EXECUTE sCommon.pTableRowIdModify @rOrgGroupId, @rTableTitle = 'sAdmission.tInquiryStatusMaster', @rCurrentNumber = @lMaxId
						
END

--static entry in tVisitorTypeMaster

IF NOT EXISTS(SELECT 1 FROM sFrontOffice.tVisitorTypeMaster WHERE Id = 1)
BEGIN	
	INSERT INTO [sFrontOffice].[tVisitorTypeMaster]
           ([Id]
           ,[Code]
           ,[Title]
           ,[IsObsolete]
           ,[CreatedUserId]
           ,[CreatedDateTime]
           ,[UpdatedUserId]
           ,[UpdatedDateTime]
           ,[OrgGroupId])
     VALUES
           (1,
		   'Visitor',
		   'Visitor',
		   0,
		   1,
		   GetDate(),
		   NULL,
		   NULL,
		   1)
END

IF NOT EXISTS(SELECT 1 FROM sFrontOffice.tVisitorTypeMaster WHERE Id = 2)
BEGIN	
	INSERT INTO [sFrontOffice].[tVisitorTypeMaster]
           ([Id]
           ,[Code]
           ,[Title]
           ,[IsObsolete]
           ,[CreatedUserId]
           ,[CreatedDateTime]
           ,[UpdatedUserId]
           ,[UpdatedDateTime]
           ,[OrgGroupId])
     VALUES
           (2,
		   'Parents',
		   'Parents',
		   0,
		   1,
		   GetDate(),
		   NULL,
		   NULL,
		   1)
END

--OrgGoup wise VisitorTypeMaster entry
IF NOT EXISTS(SELECT 1 FROM sFrontOffice.tVisitorTypeMaster WHERE OrgGroupId = @rOrgGroupId AND Id = sCommon.fGetIntIdForOrg(1,@rOrgGroupId))
BEGIN
	INSERT INTO [sFrontOffice].[tVisitorTypeMaster]
			   (
			    [Id]
			   ,[Code]
			   ,[Title]
			   ,[IsObsolete]
			   ,[CreatedUserId]
			   ,[CreatedDateTime]
			   ,[UpdatedUserId]
			   ,[UpdatedDateTime]
			   ,[OrgGroupId])
		 VALUES
			   (
			   sCommon.fGetIntIdForOrg(1,@rOrgGroupId),
			   'Visitor',
			   'Visitor',
			   0,
			   --1,
			   [sCommon].[fGetBigIntIdForOrg](3,@rOrgGroupId),
			   GetDate(),
			   NULL,
			   NULL,
			   @rOrgGroupId)
END

IF NOT EXISTS(SELECT 1 FROM sFrontOffice.tVisitorTypeMaster WHERE OrgGroupId = @rOrgGroupId AND Id = sCommon.fGetIntIdForOrg(2,@rOrgGroupId))
BEGIN
	INSERT INTO [sFrontOffice].[tVisitorTypeMaster]
			   (
			    [Id]
			   ,[Code]
			   ,[Title]
			   ,[IsObsolete]
			   ,[CreatedUserId]
			   ,[CreatedDateTime]
			   ,[UpdatedUserId]
			   ,[UpdatedDateTime]
			   ,[OrgGroupId])
		 VALUES
			   (
			   sCommon.fGetIntIdForOrg(2,@rOrgGroupId),
			   'Parents',
			   'Parents',
			   0,
			   --1,
			   [sCommon].[fGetBigIntIdForOrg](3,@rOrgGroupId),
			   GetDate(),
			   NULL,
			   NULL,
			   @rOrgGroupId)
END

--PeriodNoMaster Entry

IF NOT EXISTS(SELECT 1 FROM [sAttendance].[tPeriodNoMaster])
BEGIN	

INSERT INTO [sAttendance].[tPeriodNoMaster]
           ([Id]
           ,[Title]
           ,[IsObsolete])
     VALUES
          (1, '1', 0),
		  (2, '2', 0),
		  (3, '3', 0),
		  (4, '4', 0),
		  (5, '5', 0),
		  (6, '6', 0),
		  (7, '7', 0),
		  (8, '8', 0),
		  (9, '9', 0),
		  (10,'10', 0),
		  (11,'11', 0),
		  (12,'12', 0)

END

IF NOT EXISTS(SELECT 1 FROM sCommon.tCastCategoryMaster WHERE OrgGroupId = @rOrgGroupId)
BEGIN				
				INSERT INTO sCommon.tCastCategoryMaster
					   ([Id]
					   ,[Number]
					   ,[Code]
					   ,[Title]
					   ,[IsObsolete]
					   ,[CreatedUserId]
					   ,[CreatedDateTime]
					   ,[UpdatedUserId]
					   ,[UpdatedDateTime]
					   ,[OrgGroupId]
					   , MainCastCategoryId 
					   ,OrderIndex)
				 SELECT
						 sCommon.fGetIntIdForOrg(Id,@rOrgGroupId)
						,Id	
						,Code
						,Title
						,0
						,1
						,getdate()
						,1
						,getdate()
						,@rOrgGroupId
						,Id
						,Id						
						FROM sCommon.tMainCastCategoryMaster
						 
						
	DECLARE @lMaxCatId int
	SET @lMaxCatId = sCommon.fGetIntIdForOrg(100,@rOrgGroupId)					
	EXECUTE sCommon.pTableRowIdModify @rOrgGroupId, @rTableTitle = 'sCommon.tCastCategoryMaster', @rCurrentNumber = @lMaxCatId

UPDATE
    o
SET
    o.CastCategoryId	=  sCommon.fGetIntIdForOrg(o.CastCategoryId,@rOrgGroupId)
FROM
    sStudent.tStudentOther o
    INNER JOIN
    sStudent.tStudentMaster S ON S.Id = o.StudentId
WHERE
o.CastCategoryId < 100 
AND CastCategoryId IS NOT NULL
AND S.OrgId IN (SELECT Id From sSetup.tOrganizationMaster WHERE OrgGroupId = @rOrgGroupId)		
			
UPDATE sAdmission.tAdmissionForm SET CastCategoryId	= sCommon.fGetIntIdForOrg(CastCategoryId,@rOrgGroupId)	
WHERE CastCategoryId IS NOT NULL AND CastCategoryId < 100 
AND OrgId IN (SELECT Id From sSetup.tOrganizationMaster WHERE OrgGroupId = @rOrgGroupId)

UPDATE sCommon.tFamiliyCastMaster SET 	CastCategoryId	=  sCommon.fGetIntIdForOrg(CastCategoryId,@rOrgGroupId)	
WHERE CastCategoryId IS NOT NULL AND CastCategoryId < 100   AND OrgGroupId = @rOrgGroupId

UPDATE sCommon.tSurnameMaster SET 	CastCategoryId	=  sCommon.fGetIntIdForOrg(CastCategoryId,@rOrgGroupId)	
WHERE CastCategoryId IS NOT NULL AND CastCategoryId < 100 AND OrgGroupId = @rOrgGroupId
			
			
END


IF NOT EXISTS(SELECT 1 FROM sTransport.tTransportMaster WHERE OrgGroupId = @rOrgGroupId)
BEGIN				
				INSERT INTO sTransport.tTransportMaster
					   ([Id]
					   ,[Number]
					   ,[Code]
					   ,[Title]
					   ,[IsObsolete]
					   ,[CreatedUserId]
					   ,[CreatedDateTime]
					   ,[UpdatedUserId]
					   ,[UpdatedDateTime]
					   ,[OrgGroupId]					    
					   )
				 SELECT
						 sCommon.fGetIntIdForOrg(1,@rOrgGroupId)
						,1
						,'Common'
						,'Common'
						,0
						,1
						,getdate()
						,1
						,getdate()
						,@rOrgGroupId
						 
		DECLARE @lMaxTranId int
	SET @lMaxTranId = sCommon.fGetIntIdForOrg(1,@rOrgGroupId)					
	EXECUTE sCommon.pTableRowIdModify @rOrgGroupId, @rTableTitle = 'sTransport.tTransportMaster', @rCurrentNumber = @lMaxTranId
						 
					 				
	INSERT INTO sTransport.tAssignTransportOrg
					   (TransportId
					   ,OrgId					    				    
					   )
	SELECT 		
	@lMaxTranId
	,Id
	FROM
	sSetup.tOrganizationMaster
	WHERE OrgGroupId = 		@rOrgGroupId	 
						 
						

UPDATE sTransport.tBusRouteMaster
SET TransportId = @lMaxTranId WHERE OrgGroupId = @rOrgGroupId

UPDATE sTransport.tVehicleMaster
SET TransportId = @lMaxTranId WHERE OrgGroupId = @rOrgGroupId


			
			
END


IF NOT EXISTS(SELECT 1 FROM sSetup.tBatchGroupMaster WHERE OrgGroupId = @rOrgGroupId AND Id =  sCommon.fGetIntIdForOrg(1,@rOrgGroupId))
BEGIN				
				INSERT INTO sSetup.tBatchGroupMaster
					   ([Id]
					   ,[Number]
					   ,[Code]
					   ,[Title]
					   ,[OrgGroupId]					    
					   ,[OrderIndex]
					   ,[CreatedUserId]
					   ,[CreatedDateTime]
					   ,[UpdatedUserId]
					   ,[UpdatedDateTime]
					   )
				 SELECT
						 sCommon.fGetIntIdForOrg(1,@rOrgGroupId)
						,1
						,'Common'
						,'Common'
						,@rOrgGroupId
						,1
						
						,1
						,getdate()
						,1
						,getdate()
						
						 
	--DECLARE @lBatchGroupId int
	--SET @lMaxTranId = sCommon.fGetIntIdForOrg(1,@rOrgGroupId)					
	--EXECUTE sCommon.pTableRowIdModify @rOrgGroupId, @rTableTitle = 'sSetup.tBatchGroupMaster', @rCurrentNumber = @lBatchGroupId
	
	UPDATE B    
	SET BatchGroupId = sCommon.fGetIntIdForOrg(1,@rOrgGroupId)
	FROM sSetup.tBatchMaster B INNER JOIN sSetup.tOrganizationMaster O ON B.OrgId = O.ID
	WHERE O.OrgGroupId = @rOrgGroupId AND B.BatchGroupId IS NULL

END


UPDATE sSetup.tClassMaster SET DepartmentId = sCommon.fGetIntIdForOrg(OrgId,1) where DepartmentId is null

if (@rOrgGroupId <> 1154)
BEGIN
UPDATE sCommon.tReport SET IsObsolete = 1
 Where Id in (20642,20643,20644,20645,20646,20647,20648,20649,20650,20665,20718,20779,20692,20693,20694)

END

UPDATE sSystem.tDatabaseInfo SET ApplicationId = 1

UPDATE sSystem.tDatabaseInfo SET 
VersionNumber = @rVersion,
VersionId = @rVersionId,
LastVersionUpdateDateTime = getdate() ,
IsNewVersion = 1
WHERE ApplicationId = 1 
 
-- for student - remove permission for employee center
DECLARE @lRoleId int = 0
DECLARE @lDefaultRoleId int = 10
SET @lRoleId = (@rOrgGroupId * 100000) + @lDefaultRoleId
 
--DELETE P FROM sSecurity.tPermission P INNER JOIN sSecurity.tTask T ON P.TaskId = T.Id 
--WHERE P.RoleId = @lRoleId AND P.OrgGroupId=@rOrgGroupId AND T.ModuleId =  234

---- for employee - remove permisiion for student center
--SET @lDefaultRoleId = 22
--SET @lRoleId = (@rOrgGroupId * 100000) + @lDefaultRoleId
--DELETE P FROM sSecurity.tPermission P INNER JOIN sSecurity.tTask T ON P.TaskId = T.Id 
--WHERE P.RoleId = @lRoleId AND P.OrgGroupId=@rOrgGroupId AND T.ModuleId =  233

-- for SysSuperAdmin
SET @lDefaultRoleId = 1
SET @lRoleId = (@rOrgGroupId * 100000) + @lDefaultRoleId
DELETE P FROM sSecurity.tPermission P INNER JOIN sSecurity.tTask T ON P.TaskId = T.Id 
WHERE P.RoleId = @lRoleId AND P.OrgGroupId=@rOrgGroupId
AND T.Id IN (30258,30262,30266,30257,30160,30243,30244)

IF NOT EXISTS (SELECT 1 FROM sSecurity.tOrganizationTask  T   WHERE TaskId = 20596  AND OrgGroupId = @rOrgGroupId)
BEGIN
	INSERT INTO sSecurity.tOrganizationTask 
	(OrgGroupId, TaskId, AvailablePermission)
	SELECT  @rOrgGroupId,20596,2
END

--default permission for Lesson Plan Complete Task for Admin only (for execute permission)
IF NOT EXISTS (SELECT 1 FROM sSecurity.tOrganizationTask  T   WHERE TaskId = 31244  AND OrgGroupId = @rOrgGroupId)
BEGIN
	INSERT INTO sSecurity.tOrganizationTask 
	(OrgGroupId, TaskId, AvailablePermission)
	SELECT  @rOrgGroupId,31244,64
END

IF NOT EXISTS (SELECT * FROM sSecurity.tPermission   WHERE RoleId =sCommon.fGetIntIdForOrg(2,@rOrgGroupId) AND TaskId = 20596  AND OrgGroupId = @rOrgGroupId)
BEGIN
	INSERT INTO sSecurity.tPermission(TaskId, RoleId, Permission, IsObsolete, CreatedUserId, CreatedDateTime, UpdatedUserId, UpdatedDateTime,OrgGroupId)
	SELECT  20596,sCommon.fGetIntIdForOrg(2,@rOrgGroupId),2,0,1,sCommon.fGetDate(),1,sCommon.fGetDate(),@rOrgGroupId
	FROM sSecurity.tOrganizationTask WHERE OrgGroupId = @rOrgGroupId
END

---- for SysSuperAdmin update password
--UPDATE sSecurity.tUser SET LoginPassword='XAqFcL/nd0bnDNhkyF/PxobplNJ+ggbN9370AHxj7oU=' WHERE Id = sCommon.fGetBigIntIdForOrg(1,@rOrgGroupId)
--UPDATE sSecurity.tUser SET LoginPassword='XAqFcL/nd0bnDNhkyF/PxobplNJ+ggbN9370AHxj7oU=' WHERE Id = 1

-- for SysSuperAdmin update password
--UPDATE sSecurity.tUser SET LoginPassword='FxYuAuSiWcl4MZWDctl++A==' WHERE Id = sCommon.fGetBigIntIdForOrg(1,@rOrgGroupId)
--UPDATE sSecurity.tUser SET LoginPassword='FxYuAuSiWcl4MZWDctl++A==' WHERE Id = 1

 -- For Upgrade Vesion END
INSERT INTO [sSystem].[tVersionUpdate] ([VersionNumber],[VersionId],[Status],[UpdateScript],[StartDateTime],[EndDateTime],[OrgGroupId])
VALUES(@rVersion,@rVersionId,'END','Upgrade Vesion',sCommon.fGetDate(),sCommon.fGetDate(),@rOrgGroupId)

END
GO

PRINT N'Creating Procedure [sAlert].[pAlumniStudentBirthdayWishGet]...';


GO
CREATE PROCEDURE [sAlert].[pAlumniStudentBirthdayWishGet]
	 	 
	 	 @rOrgId smallint,
	 	 @rTemplate nvarchar(max),
	 	 @rMailSubject nvarchar(100)
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN	
	SELECT
		R.Id As RegistrationId,
		R.FirstName,
		R.LastName,
		R.MappedStudentId As AcademicId,
		SC.StudentId,
		SC.Name As StudentName,
		replace(
		replace(
		replace (					
		replace (
		@rTemplate,'[Name]',SC.Name)
		,'[Class]',SC.ClassName)
		,'[Division]',SC.DivisionName)
		,'[SchoolName]',OM.Title)
		AS MsgText,
		@rMailSubject AS Subject,
		OM.OrgGroupId AS OrgGroupId,
		OM.Id As OrgId,
		OM.Title As SchoolName,
		BM.Id AS BatchId,
		SC.StudentId AS SourceId,
		2003 AS SourceTypeId,
		SC.StudentId AS ReceiverSourceId,
		2003 AS ReceiverSourceTypeId,
		ISNULL(CM.DisplayTitle,'') AS Class,
		ISNULL(SC.Code,'') as Code,
		ISNULL(SC.ClassName +'-'+ SC.DivisionName,'') as ClassDivision,
		ISNULL(Sc.ParentContactNo,'') AS MobileNo,
		ISNULL(SC.ParentEmail,'') As EmailId,
		ISNULL(SC.WhatsAppContactNo,'') AS WhatsAppContactNo
		FROM  [sStudent].[vStudentCommunication]  SC
		INNER JOIN sAlumni.tRegistration R ON SC.AcademicId = R.MappedStudentId
		INNER JOIN sSetup.tClassMaster CM ON CM.Id=R.PassingClassId
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=R.OrgId
		INNER JOIN sSetup.tBatchMaster BM ON BM.Id = R.PassingBatchId
		
	WHERE R.MappedStudentId <> 0
		AND (DAY(SC.DateOfBirth) = DAY(sCommon.fGetDate()))
		AND (MONTH(SC.DateOfBirth) = MONTH(sCommon.fGetDate()))
		AND (SC.StatusId=1)
		AND (SC.OrgId=@rOrgId)
		AND SC.IsActiveBatch = 1 AND SC.IsBlockAllAlert=0
END
GO

PRINT N'Creating Procedure [sFee].[pRptStudentFeeHistoryGet]...';


GO

 
CREATE PROCEDURE [sFee].[pRptStudentFeeHistoryGet]

	@rBuilder1 nvarchar(max),  
	@rBuilder2 nvarchar(max),
	@rOrgId int = 0,
	@rBatchId bigint = 0,
	@rFromDate date=NULL,
	@rToDate date=NULL,
	@rHistoryTypeId tinyint=null,
	@rOrgGroupBatchId int = 0,
	@rCommonBatch nvarchar(50) = '',
	@rDepartmentId int = 0,
	@rClassId int = 0,
	@rDivisionId int = 0,
	@rAdmissionCategoryId int = 0,
	@rFromRollNo int = 0,
	@rToRollNo int = 0,
	@rCode nvarchar(50) = '',
	@rFeeId nvarchar(Max) = '',
	@rReportId int = 0,
	@rOrgGroupId int = 0

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	SELECT 
		@rBuilder1 AS Builder1
		,@rBuilder2 AS Builder2
		,SA.AcademicId
		,(SA.FirstName + ' '+ SA.MiddleName + ' '+ SA.LastName) AS StudentName
		,ISNULL(SA.Code, '') AS StudentCode
		,FM.Code AS FeeName
		,FS.Amount AS FeeAmount
		,FAH.VariableAmount
		,FAH.DiscountAmount
		,FAH.AdditionalAmount
		,FAH.NotApplicableAmount
		,(FS.Amount + FAH.VariableAmount + FAH.AdditionalAmount - FAH.DiscountAmount - FAH.NotApplicableAmount) AS AmountAfterApply
		,FAH.Remark
		,FAH.ReferenceTypeId
		,FAH.ReferenceSourceId
		,FAH.UserId
		,U.DisplayTitle AS UserName
		,FAH.LogDateTime
		,FAH.DiscountRemark
		,FAH.AdditionalRemark
		,FAH.NotApplicableRemark
		,SA.DivisionOrder
		,SA.RollNo
	FROM sFee.tFeeAllocationHistory FAH
		INNER JOIN sStudent.vStudentAcademic SA ON FAH.SourceId=SA.AcademicId
		LEFT JOIN sFee.tFeeSetup FS ON FS.Id=FAH.FeeSetupId
		INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS.FeeId
		INNER JOIN sSecurity.tUser U ON U.Id=FAH.UserId
	WHERE 
		(SA.OrgId = @rOrgId OR @rOrgId = 0)
		AND (SA.BatchId = @rBatchId OR @rBatchId = 0)
		AND ((CAST(FAH.LogDateTime AS DATE) >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
		AND ((CAST(FAH.LogDateTime AS DATE) <= @rToDate) OR (ISNULL(@rToDate,'') = ''))
		AND ((ISNULL(FAH.HistoryTypeId,1) = @rHistoryTypeId) OR (ISNULL(@rHistoryTypeId, 0) = 0))
		AND (SA.OrgGroupBatchId = @rOrgGroupBatchId)
		AND ((SA.BatchName = @rCommonBatch) OR (@rCommonBatch = '')) 
		AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
		AND ((SA.ClassId = @rClassId) OR (@rClassId = 0))  
		AND ((SA.DivisionId = @rDivisionId) OR (@rDivisionId = 0))
		AND ((SA.AdmissionCategoryId = @rAdmissionCategoryId) OR (@rAdmissionCategoryId = 0))
		AND ((SA.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))  
		AND ((SA.RollNo <= @rToRollNo) OR (@rToRollNo=0))
		AND ((SA.Code=@rCode) OR (@rCode=''))
		AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
	ORDER BY FAH.LogDateTime DESC
END
GO

PRINT N'Creating Procedure [sStudent].[pAdminDeletedStudentMasterDetailsGet]...';


GO
CREATE PROCEDURE [sStudent].[pAdminDeletedStudentMasterDetailsGet] 
	 @rCode VARCHAR(20) = ''
	,@rFirstName VARCHAR(100) = ''
	,@rLastName VARCHAR(100) = ''
	,@rDeletedUserName VARCHAR(100) = ''
	,@rOrgGroupId INT
	,@rFromDate DATE = ''
	,@rToDate DATE = ''
	,@Status BIT = 0
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	IF (@Status = 0)
	BEGIN
		SELECT [sStudent].[fStudentNameGet](SM.FirstName, SM.MiddleName, SM.LastName, OM.StudentNameFormatId) AS Name
			,SM.Code
			,DeletededUser
			,DeletedDateTime
		FROM sStudent.tStudentMasterDelete SM
		INNER JOIN sSetup.tOrganizationMaster OM ON SM.OrgId = OM.Id
		WHERE ((SM.Code = @rCode) OR (@rCode = 0))
			AND ((SM.FirstName LIKE @rFirstName) OR (ISNULL(@rFirstName, '') = ''))
			AND ((SM.LastName LIKE @rLastName) OR (ISNULL(@rLastName, '') = ''))
			AND ((SM.DeletededUser LIKE @rDeletedUserName) OR (ISNULL(@rDeletedUserName, '') = ''))
			AND OM.OrgGroupId = @rOrgGroupId
			AND ((CONVERT(DATE, SM.DeletedDateTime) >= @rFromDate) OR (ISNULL(@rFromDate, '') = ''))
			AND ((CONVERT(DATE, SM.DeletedDateTime) <= @rToDate) OR (ISNULL(@rToDate, '') = ''))
		ORDER BY DeletedDateTime DESC
	END
	ELSE
	BEGIN
		SELECT *
		FROM sStudent.tStudentMasterDelete SM
		INNER JOIN sSetup.tOrganizationMaster OM ON SM.OrgId = OM.Id
		WHERE ((SM.Code = @rCode) OR (@rCode = 0))
			AND ((SM.FirstName LIKE @rFirstName) OR (ISNULL(@rFirstName, '') = ''))
			AND ((SM.LastName LIKE @rLastName) OR (ISNULL(@rLastName, '') = ''))
			AND ((SM.DeletededUser LIKE @rDeletedUserName) OR (ISNULL(@rDeletedUserName, '') = ''))
			AND OM.OrgGroupId = @rOrgGroupId
			AND ((CONVERT(DATE, SM.DeletedDateTime) >= @rFromDate) OR (ISNULL(@rFromDate, '') = ''))
			AND ((CONVERT(DATE, SM.DeletedDateTime) <= @rToDate) OR (ISNULL(@rToDate, '') = ''))
		ORDER BY DeletedDateTime DESC
	END
END
GO

PRINT N'Update complete.';

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

