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

 
GO
PRINT N'Dropping [sFee].[fPendingFeeNamesGet]...';


GO
DROP FUNCTION [sFee].[fPendingFeeNamesGet];


GO
PRINT N'Dropping [dbo].[TempPendingFee]...';


GO
DROP TYPE [dbo].[TempPendingFee];


GO
PRINT N'Altering [sAssessment].[tAllBatchResult]...';


GO
ALTER TABLE [sAssessment].[tAllBatchResult]
    ADD [PGPercentage]        DECIMAL (12, 2) NULL,
        [PGPercentage1]       DECIMAL (12, 2) NULL,
        [PGPercentage2]       DECIMAL (12, 2) NULL,
        [NursaryPercentage]   DECIMAL (12, 2) NULL,
        [NursaryPercentage1]  DECIMAL (12, 2) NULL,
        [NursaryPercentage2]  DECIMAL (12, 2) NULL,
        [SrKgPercentage]      DECIMAL (12, 2) NULL,
        [SrKgPercentage1]     DECIMAL (12, 2) NULL,
        [SrKgPercentage2]     DECIMAL (12, 2) NULL,
        [JrKgPercentage]      DECIMAL (12, 2) NULL,
        [JrKgPercentage1]     DECIMAL (12, 2) NULL,
        [JrKgPercentage2]     DECIMAL (12, 2) NULL,
        [FirstPercentage]     DECIMAL (12, 2) NULL,
        [FirstPercentage1]    DECIMAL (12, 2) NULL,
        [FirstPercentage2]    DECIMAL (12, 2) NULL,
        [SecondPercentage]    DECIMAL (12, 2) NULL,
        [SecondPercentage1]   DECIMAL (12, 2) NULL,
        [SecondPercentage2]   DECIMAL (12, 2) NULL,
        [ThirdPercentage]     DECIMAL (12, 2) NULL,
        [ThirdPercentage1]    DECIMAL (12, 2) NULL,
        [ThirdPercentage2]    DECIMAL (12, 2) NULL,
        [FourthPercentage]    DECIMAL (12, 2) NULL,
        [FourthPercentage1]   DECIMAL (12, 2) NULL,
        [FourthPercentage2]   DECIMAL (12, 2) NULL,
        [FifthPercentage]     DECIMAL (12, 2) NULL,
        [FifthPercentage1]    DECIMAL (12, 2) NULL,
        [FifthPercentage2]    DECIMAL (12, 2) NULL,
        [SixthPercentage]     DECIMAL (12, 2) NULL,
        [SixthPercentage1]    DECIMAL (12, 2) NULL,
        [SixthPercentage2]    DECIMAL (12, 2) NULL,
        [SeventhPercentage]   DECIMAL (12, 2) NULL,
        [SeventhPercentage1]  DECIMAL (12, 2) NULL,
        [SeventhPercentage2]  DECIMAL (12, 2) NULL,
        [EighthPercentage]    DECIMAL (12, 2) NULL,
        [EighthPercentage1]   DECIMAL (12, 2) NULL,
        [EighthPercentage2]   DECIMAL (12, 2) NULL,
        [NinthPercentage]     DECIMAL (12, 2) NULL,
        [NinthPercentage1]    DECIMAL (12, 2) NULL,
        [NinthPercentage2]    DECIMAL (12, 2) NULL,
        [TenthPercentage]     DECIMAL (12, 2) NULL,
        [TenthPercentage1]    DECIMAL (12, 2) NULL,
        [TenthPercentage2]    DECIMAL (12, 2) NULL,
        [EleventhPercentage]  DECIMAL (12, 2) NULL,
        [EleventhPercentage1] DECIMAL (12, 2) NULL,
        [EleventhPercentage2] DECIMAL (12, 2) NULL,
        [TwelfthPercentage]   DECIMAL (12, 2) NULL,
        [TwelfthPercentage1]  DECIMAL (12, 2) NULL,
        [TwelfthPercentage2]  DECIMAL (12, 2) NULL;


GO
PRINT N'Altering [sAudit].[tChargeDeleted]...';


GO
ALTER TABLE [sAudit].[tChargeDeleted]
    ADD [DeleteRemark] NVARCHAR (500) NULL;


GO
PRINT N'Altering [sFee].[tChargeReceipt]...';


GO
ALTER TABLE [sFee].[tChargeReceipt] ALTER COLUMN [Remark] NVARCHAR (500) NULL;


GO
ALTER TABLE [sFee].[tChargeReceipt]
    ADD [DeleteRemark] NVARCHAR (500) NULL;


GO
PRINT N'Altering [sLibrary].[tBookMaster]...';


GO
ALTER TABLE [sLibrary].[tBookMaster]
    ADD [OrderIndex] INT NULL;


GO
PRINT N'Creating [dbo].[TempPendingFee]...';


GO
CREATE TYPE [dbo].[TempPendingFee] AS  TABLE (
    [AcademicId]         BIGINT          NULL,
    [RollNo]             INT             NULL,
    [Name]               NVARCHAR (200)  NULL,
    [Code]               NVARCHAR (20)   NULL,
    [ClassId]            INT             NULL,
    [DivisionId]         INT             NULL,
    [ClassName]          NVARCHAR (100)  NULL,
    [DivisionName]       NVARCHAR (100)  NULL,
    [ClassDivision]      NVARCHAR (100)  NULL,
    [FeeSetupId]         INT             NULL,
    [IsVariable]         INT             NULL,
    [Amount]             DECIMAL (12, 2) NULL,
    [StartDate]          DATE            NULL,
    [EndDate]            DATE            NULL,
    [FAAmount]           DECIMAL (12, 2) NULL,
    [DiscountAmount]     DECIMAL (12, 2) NULL,
    [AdditionalAmount]   DECIMAL (12, 2) NULL,
    [PaidAmount]         DECIMAL (12, 2) NULL,
    [PendingAmount]      DECIMAL (12, 2) NULL,
    [Remark]             NVARCHAR (200)  NULL,
    [ReceiptBookId]      INT             NULL,
    [FeeName]            NVARCHAR (100)  NULL,
    [FeeCode]            NVARCHAR (100)  NULL,
    [OrgId]              INT             NULL,
    [OrgName]            NVARCHAR (200)  NULL,
    [OrgOrderIndex]      INT             NULL,
    [ReceiptBookTitle]   NVARCHAR (200)  NULL,
    [ReceiptOrderIndex]  INT             NULL,
    [BatchId]            INT             NULL,
    [BatchName]          NVARCHAR (100)  NULL,
    [Pickup]             NVARCHAR (100)  NULL,
    [DRoppoint]          NVARCHAR (100)  NULL,
    [PresentContactNo]   NVARCHAR (20)   NULL,
    [SUID]               NVARCHAR (20)   NULL,
    [ClassOrderIndex]    INT             NULL,
    [DivisionOrderIndex] INT             NULL,
    [FeeOrderIndex]      INT             NULL);


GO
PRINT N'Creating [sFee].[fPendingFeeNamesGet]...';


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

DECLARE @rFeeDetail nvarchar(2000)
SELECT 
			@rFeeDetail=COALESCE(@rFeeDetail+',','') +  F.FeeCode
			 FROM
			 @Fee F			  
			 WHERE AcademicId = @rAcademicId  
			 AND ReceiptBookId = @rReceiptBookId
			 Order By F.FeeOrderIndex
		
    RETURN ISNULL(@rFeeDetail,'') 
 
END
 
GO

 
GO
PRINT N'Altering [sFee].[fPendingFeeNamesGet]...';


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

DECLARE @rFeeDetail nvarchar(2000)
SELECT 
			@rFeeDetail=COALESCE(@rFeeDetail+',','') +  F.FeeCode
			 FROM
			 @Fee F			  
			 WHERE AcademicId = @rAcademicId  
			 AND ReceiptBookId = @rReceiptBookId
			 Order By F.FeeOrderIndex
		
    RETURN ISNULL(@rFeeDetail,'') 
 
END
GO
PRINT N'Altering [sHrm].[fAttendanceWithApproveLeaveGet]...';


GO

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

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



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

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



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


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

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

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

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



 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

 
GO
PRINT N'Altering [sAdmission].[pAdmissionAndInquiryConsolidateDashBoardGet]...';


GO
ALTER PROCEDURE [sAdmission].[pAdmissionAndInquiryConsolidateDashBoardGet]
                              
    @rTypeId int, -- 1-Admission, 2-Inquiry 
    @rType nvarchar(200), -- OrgGroup, Organization
    @rOrgGroupId int=0,
    @rOrgId int=0,
    @rCommonOrgGroupBatchId int=0,
	@rInquiryStatusId int=0,
	@rClassId int =0,
	@rSyncDate int =0,
	@rInquiryMainStatus int =0
	 
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

	DECLARE @lTempOrgBatchOrder TABLE( OrgId int, BatchOrderIndex int)
	INSERT INTO @lTempOrgBatchOrder ( OrgId,BatchOrderIndex )
	SELECT 
		OM.Id AS OrgId, MAX(BM.OrderIndex) AS BatchOrderIndex
	FROM
		sSetup.tOrganizationMaster OM
		INNER JOIN sSetup.tBatchMaster BM ON BM.OrgId = OM.Id
		INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
	WHERE 
		((OM.OrgGroupId = @rOrgGroupId) OR (@rOrgGroupId = 0))
		AND BM.IsObsolete = 0 AND COGBM.Id=@rCommonOrgGroupBatchId
	GROUP BY
		OM.Id
		
	DECLARE @lTempBatchId TABLE(OrgId int, BatchId int)
	INSERT INTO @lTempBatchId (OrgId , BatchId)
	SELECT 
		BM.OrgId AS OrgId,
		BM.Id AS BatchId
	FROM 
		sSetup.tBatchMaster BM
		INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
		--INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		INNER JOIN @lTempOrgBatchOrder BO ON BO.OrgId = BM.OrgId
	WHERE
		BO.BatchOrderIndex = BM.OrderIndex  AND COGBM.Id=@rCommonOrgGroupBatchId
	
	DECLARE @lConfigValue nvarchar(50)=''
	IF(@rOrgGroupId = 0)
	BEGIN
		DECLARE @lOrgGroupId int
		SELECT @lOrgGroupId = OrgGroupId FROM sSetup.tOrganizationMaster WHERE Id = @rOrgId
		
		SELECT @lConfigValue = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 397 AND SourceTypeId = 2010 AND SourceId = @lOrgGroupId
	END
	ELSE
	BEGIN
		SELECT @lConfigValue = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 397 AND SourceTypeId = 2010 AND SourceId = @rOrgGroupId
	END
	IF @lConfigValue = ''
		SET @lConfigValue = 'False' 

-- For Admission TypeId=1
	IF(@rTypeId=1) 
	BEGIN
		IF(@rType='OrgGroup')
		BEGIN

		IF(@rSyncDate =1)
				BEGIN
				DELETE  sAdmission.tTempAdmissionFormCount WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))  
				IF EXISTS (SELECT 1 FROM sAdmission.tTempAdmissionFormCount WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND (OrgGroupId = @rOrgGroupId))  
				BEGIN  
					IF(@rOrgGroupId !=0)  
					INSERT INTO sAdmission.tTempAdmissionFormCount  
					SELECT ISNULL(OGM.Id,0) AS OrgGroupId,OGM.Title AS OrgGroupTitle,ISNULL(COUNT(AF.Id),0) AS AdmissionCount,@rCommonOrgGroupBatchId,GetDate(),

					(SELECT ISNULL(COUNT(AF1.Id),0) FROM sSetup.tOrgGroupMaster OGM1     
					INNER JOIN sSetup.tOrganizationMaster OM1 ON OGM1.Id = OM1.OrgGroupId   
					INNER JOIN @lTempBatchId TB1 ON TB1.OrgId = OM1.Id  
					LEFT JOIN sSetup.tBatchMaster BM1 ON BM1.Id = TB1.BatchId  
					INNER JOIN sSetup.tOrgGroupBatchMaster OGBM1 ON OGBM1.ID=BM1.OrgGroupBatchId AND OGM1.Id = OGBM1.OrgGroupId   
					INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM1 ON COGBM1.Id=OGBM1.CommonOrgGroupBatchId   
					LEFT JOIN sAdmission.tAdmissionForm AF1 ON BM1.Id = AF1.BatchId
					LEFT JOIN sAdmission.tAdmissionFormSelected AFS ON AF1.Id = AFS.AdmissionFormId
				    LEFT JOIN sAdmission.tAdmissionStatusMaster ASM ON ASM.Id = AFS.AdmissionStatusId WHERE OGM1.Id<>1 AND COGBM1.Id = COGBM.Id AND OGM1.Id = OGM.Id AND ASM.Id = null) as PendingCount,

					(SELECT ISNULL(COUNT(AF1.Id),0) FROM sSetup.tOrgGroupMaster OGM1     
					INNER JOIN sSetup.tOrganizationMaster OM1 ON OGM1.Id = OM1.OrgGroupId   
					INNER JOIN @lTempBatchId TB1 ON TB1.OrgId = OM1.Id  
					LEFT JOIN sSetup.tBatchMaster BM1 ON BM1.Id = TB1.BatchId  
					INNER JOIN sSetup.tOrgGroupBatchMaster OGBM1 ON OGBM1.ID=BM1.OrgGroupBatchId AND OGM1.Id = OGBM1.OrgGroupId   
					INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM1 ON COGBM1.Id=OGBM1.CommonOrgGroupBatchId   
					LEFT JOIN sAdmission.tAdmissionForm AF1 ON BM1.Id = AF1.BatchId
					LEFT JOIN sAdmission.tAdmissionFormSelected AFS ON AF1.Id = AFS.AdmissionFormId
				    LEFT JOIN sAdmission.tAdmissionStatusMaster ASM ON ASM.Id = AFS.AdmissionStatusId WHERE OGM1.Id<>1 AND COGBM1.Id = COGBM.Id AND OGM1.Id = OGM.Id AND ASM.Id = 3) as ConfirmCount
					
					FROM sSetup.tOrgGroupMaster OGM     
					INNER JOIN sSetup.tOrganizationMaster OM ON OGM.Id = OM.OrgGroupId   
					INNER JOIN @lTempBatchId TB ON TB.OrgId = OM.Id  
					LEFT JOIN sSetup.tBatchMaster BM ON BM.Id = TB.BatchId  
					INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId AND OGM.Id = OGBM.OrgGroupId   
					--INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId        
					INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId   
					LEFT JOIN sAdmission.tAdmissionForm AF ON BM.Id = AF.BatchId  
					WHERE   
					OGM.Id<>1 AND  
					COGBM.Id=@rCommonOrgGroupBatchId AND  
					--BM.IsActive = 1  
					BM.Id = TB.BatchId  
					GROUP BY OGM.Id,OGM.Title,COGBM.Id  
					SELECT * FROM sAdmission.tTempAdmissionFormCount WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))  
				END  
				ELSE  
				BEGIN  
					INSERT INTO sAdmission.tTempAdmissionFormCount  
					SELECT ISNULL(OGM.Id,0) AS OrgGroupId,OGM.Title AS OrgGroupTitle,ISNULL(COUNT(AF.Id),0) AS AdmissionCount,@rCommonOrgGroupBatchId,GetDate(),

					(SELECT ISNULL(COUNT(AF1.Id),0) FROM sSetup.tOrgGroupMaster OGM1     
					INNER JOIN sSetup.tOrganizationMaster OM1 ON OGM1.Id = OM1.OrgGroupId   
					INNER JOIN @lTempBatchId TB1 ON TB1.OrgId = OM1.Id  
					LEFT JOIN sSetup.tBatchMaster BM1 ON BM1.Id = TB1.BatchId  
					INNER JOIN sSetup.tOrgGroupBatchMaster OGBM1 ON OGBM1.ID=BM1.OrgGroupBatchId AND OGM1.Id = OGBM1.OrgGroupId   
					INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM1 ON COGBM1.Id=OGBM1.CommonOrgGroupBatchId   
					LEFT JOIN sAdmission.tAdmissionForm AF1 ON BM1.Id = AF1.BatchId
					LEFT JOIN sAdmission.tAdmissionFormSelected AFS ON AF1.Id = AFS.AdmissionFormId
				    LEFT JOIN sAdmission.tAdmissionStatusMaster ASM ON ASM.Id = AFS.AdmissionStatusId WHERE OGM1.Id<>1 AND COGBM1.Id = COGBM.Id AND OGM1.Id = OGM.Id AND ASM.Id IS NULL) as PendingCount,

					(SELECT ISNULL(COUNT(AF1.Id),0) FROM sSetup.tOrgGroupMaster OGM1     
					INNER JOIN sSetup.tOrganizationMaster OM1 ON OGM1.Id = OM1.OrgGroupId   
					INNER JOIN @lTempBatchId TB1 ON TB1.OrgId = OM1.Id  
					LEFT JOIN sSetup.tBatchMaster BM1 ON BM1.Id = TB1.BatchId  
					INNER JOIN sSetup.tOrgGroupBatchMaster OGBM1 ON OGBM1.ID=BM1.OrgGroupBatchId AND OGM1.Id = OGBM1.OrgGroupId   
					INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM1 ON COGBM1.Id=OGBM1.CommonOrgGroupBatchId   
					LEFT JOIN sAdmission.tAdmissionForm AF1 ON BM1.Id = AF1.BatchId
					LEFT JOIN sAdmission.tAdmissionFormSelected AFS ON AF1.Id = AFS.AdmissionFormId
				    LEFT JOIN sAdmission.tAdmissionStatusMaster ASM ON ASM.Id = AFS.AdmissionStatusId WHERE OGM1.Id<>1 AND COGBM1.Id = COGBM.Id AND OGM1.Id = OGM.Id AND ASM.Id = 3) as ConfirmCount

					FROM sSetup.tOrgGroupMaster OGM     
					INNER JOIN sSetup.tOrganizationMaster OM ON OGM.Id = OM.OrgGroupId   
					INNER JOIN @lTempBatchId TB ON TB.OrgId = OM.Id  
					LEFT JOIN sSetup.tBatchMaster BM ON BM.Id = TB.BatchId  
					INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId AND OGM.Id = OGBM.OrgGroupId   
					--INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId        
					INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId   
					LEFT JOIN sAdmission.tAdmissionForm AF ON BM.Id = AF.BatchId  
					WHERE   
					OGM.Id<>1 AND  
					COGBM.Id=@rCommonOrgGroupBatchId AND  
					--BM.IsActive = 1  
					BM.Id = TB.BatchId  
					GROUP BY OGM.Id,OGM.Title,COGBM.Id  
					SELECT * FROM sAdmission.tTempAdmissionFormCount WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))  
				END  
		END
		ELSE
			BEGIN
			 IF  Exists(select 1 from sAdmission.tTempAdmissionFormCount   where CONVERT(date,UpdateDate) =  CONVERT(date,getdate(),102) AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0)) AND CommonOrgGroupBatchId=@rCommonOrgGroupBatchId)   
			 BEGIN  
				 SELECT * FROM sAdmission.tTempAdmissionFormCount   WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))  
				 return  
			 END  
			 ELSE  
			 BEGIN  
				DELETE  sAdmission.tTempAdmissionFormCount WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))  
				IF EXISTS (SELECT 1 FROM sAdmission.tTempAdmissionFormCount WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0)))  
				BEGIN  
					IF(@rOrgGroupId !=0)  
        
					INSERT INTO sAdmission.tTempAdmissionFormCount  
					SELECT ISNULL(OGM.Id,0) AS OrgGroupId,OGM.Title AS OrgGroupTitle,ISNULL(COUNT(AF.Id),0) AS AdmissionCount,@rCommonOrgGroupBatchId,GetDate(),
				
					(SELECT ISNULL(COUNT(AF1.Id),0) FROM sSetup.tOrgGroupMaster OGM1     
					INNER JOIN sSetup.tOrganizationMaster OM1 ON OGM1.Id = OM1.OrgGroupId   
					INNER JOIN @lTempBatchId TB1 ON TB1.OrgId = OM1.Id  
					LEFT JOIN sSetup.tBatchMaster BM1 ON BM1.Id = TB1.BatchId  
					INNER JOIN sSetup.tOrgGroupBatchMaster OGBM1 ON OGBM1.ID=BM1.OrgGroupBatchId AND OGM1.Id = OGBM1.OrgGroupId   
					INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM1 ON COGBM1.Id=OGBM1.CommonOrgGroupBatchId   
					LEFT JOIN sAdmission.tAdmissionForm AF1 ON BM1.Id = AF1.BatchId
					LEFT JOIN sAdmission.tAdmissionFormSelected AFS ON AF1.Id = AFS.AdmissionFormId
					LEFT JOIN sAdmission.tAdmissionStatusMaster ASM ON ASM.Id = AFS.AdmissionStatusId WHERE OGM1.Id<>1 AND COGBM1.Id = COGBM.Id AND OGM1.Id = OGM.Id AND ASM.Id IS NULL) as PendingCount,

					(SELECT ISNULL(COUNT(AF1.Id),0) FROM sSetup.tOrgGroupMaster OGM1     
					INNER JOIN sSetup.tOrganizationMaster OM1 ON OGM1.Id = OM1.OrgGroupId   
					INNER JOIN @lTempBatchId TB1 ON TB1.OrgId = OM1.Id  
					LEFT JOIN sSetup.tBatchMaster BM1 ON BM1.Id = TB1.BatchId  
					INNER JOIN sSetup.tOrgGroupBatchMaster OGBM1 ON OGBM1.ID=BM1.OrgGroupBatchId AND OGM1.Id = OGBM1.OrgGroupId   
					INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM1 ON COGBM1.Id=OGBM1.CommonOrgGroupBatchId   
					LEFT JOIN sAdmission.tAdmissionForm AF1 ON BM1.Id = AF1.BatchId
					LEFT JOIN sAdmission.tAdmissionFormSelected AFS ON AF1.Id = AFS.AdmissionFormId
					LEFT JOIN sAdmission.tAdmissionStatusMaster ASM ON ASM.Id = AFS.AdmissionStatusId WHERE OGM1.Id<>1 AND COGBM1.Id = COGBM.Id AND OGM1.Id = OGM.Id AND ASM.Id = 3) as ConfirmCount
					  
					FROM sSetup.tOrgGroupMaster OGM     
					INNER JOIN sSetup.tOrganizationMaster OM ON OGM.Id = OM.OrgGroupId   
					INNER JOIN @lTempBatchId TB ON TB.OrgId = OM.Id  
					LEFT JOIN sSetup.tBatchMaster BM ON BM.Id = TB.BatchId  
					INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId AND OGM.Id = OGBM.OrgGroupId   
					--INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId        
					INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId   
					LEFT JOIN sAdmission.tAdmissionForm AF ON BM.Id = AF.BatchId  
					WHERE   
					OGM.Id<>1 AND  
					COGBM.Id=@rCommonOrgGroupBatchId AND  
					--BM.IsActive = 1  
					BM.Id = TB.BatchId  
					GROUP BY OGM.Id,OGM.Title,COGBM.Id
					SELECT * FROM sAdmission.tTempAdmissionFormCount WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))  
				END  
				ELSE  
				BEGIN  
					INSERT INTO sAdmission.tTempAdmissionFormCount  
					SELECT ISNULL(OGM.Id,0) AS OrgGroupId,OGM.Title AS OrgGroupTitle,ISNULL(COUNT(AF.Id),0) AS AdmissionCount,@rCommonOrgGroupBatchId,GetDate(),
			
					(SELECT ISNULL(COUNT(AF1.Id),0) FROM sSetup.tOrgGroupMaster OGM1     
					INNER JOIN sSetup.tOrganizationMaster OM1 ON OGM1.Id = OM1.OrgGroupId   
					INNER JOIN @lTempBatchId TB1 ON TB1.OrgId = OM1.Id  
					LEFT JOIN sSetup.tBatchMaster BM1 ON BM1.Id = TB1.BatchId  
					INNER JOIN sSetup.tOrgGroupBatchMaster OGBM1 ON OGBM1.ID=BM1.OrgGroupBatchId AND OGM1.Id = OGBM1.OrgGroupId   
					INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM1 ON COGBM1.Id=OGBM1.CommonOrgGroupBatchId   
					LEFT JOIN sAdmission.tAdmissionForm AF1 ON BM1.Id = AF1.BatchId
					LEFT JOIN sAdmission.tAdmissionFormSelected AFS ON AF1.Id = AFS.AdmissionFormId
					LEFT JOIN sAdmission.tAdmissionStatusMaster ASM ON ASM.Id = AFS.AdmissionStatusId WHERE OGM1.Id<>1 AND COGBM1.Id = COGBM.Id AND OGM1.Id = OGM.Id AND ASM.Id IS NULL) as PendingCount,

					(SELECT ISNULL(COUNT(AF1.Id),0) FROM sSetup.tOrgGroupMaster OGM1     
					INNER JOIN sSetup.tOrganizationMaster OM1 ON OGM1.Id = OM1.OrgGroupId   
					INNER JOIN @lTempBatchId TB1 ON TB1.OrgId = OM1.Id  
					LEFT JOIN sSetup.tBatchMaster BM1 ON BM1.Id = TB1.BatchId  
					INNER JOIN sSetup.tOrgGroupBatchMaster OGBM1 ON OGBM1.ID=BM1.OrgGroupBatchId AND OGM1.Id = OGBM1.OrgGroupId   
					INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM1 ON COGBM1.Id=OGBM1.CommonOrgGroupBatchId   
					LEFT JOIN sAdmission.tAdmissionForm AF1 ON BM1.Id = AF1.BatchId
					LEFT JOIN sAdmission.tAdmissionFormSelected AFS ON AF1.Id = AFS.AdmissionFormId
					LEFT JOIN sAdmission.tAdmissionStatusMaster ASM ON ASM.Id = AFS.AdmissionStatusId WHERE OGM1.Id<>1 AND COGBM1.Id = COGBM.Id AND OGM1.Id = OGM.Id AND ASM.Id = 3) as ConfirmCount
				     
					FROM sSetup.tOrgGroupMaster OGM     
					INNER JOIN sSetup.tOrganizationMaster OM ON OGM.Id = OM.OrgGroupId   
					INNER JOIN @lTempBatchId TB ON TB.OrgId = OM.Id  
					LEFT JOIN sSetup.tBatchMaster BM ON BM.Id = TB.BatchId  
					INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId AND OGM.Id = OGBM.OrgGroupId   
					--INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId        
					INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId   
					LEFT JOIN sAdmission.tAdmissionForm AF ON BM.Id = AF.BatchId  
					WHERE   
					OGM.Id<>1 AND  
					COGBM.Id=@rCommonOrgGroupBatchId AND  
					--BM.IsActive = 1  
					BM.Id = TB.BatchId  
					GROUP BY OGM.Id,OGM.Title,COGBM.Id  
					SELECT * FROM sAdmission.tTempAdmissionFormCount WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))  
				END  
			END  
		END
	END
-- For Admission TypeId=1
IF(@rType='Organization')
		BEGIN
			SELECT ISNULL(OM.Id,0) AS OrgId,OM.Title AS Organization,ISNULL(COUNT(AF.Id),0) AS AdmissionCount,OM.OrderIndex
			FROM sAdmission.tAdmissionForm AF 
			LEFT JOIN  sSetup.tOrganizationMaster OM ON AF.OrgId = OM.Id 
			LEFT JOIN sSetup.tBatchMaster BM ON BM.Id = AF.BatchId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
			
			
			LEFT JOIN @lTempBatchId TB ON TB.OrgId = OM.Id and BM.Id = TB.BatchId
			WHERE --BM.IsActive = 1 
			OM.OrgGroupId = @rOrgGroupId 	
			AND BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId 
			And ISNULL(O.IsObsolete,0) = 0
			GROUP BY OM.Id,OM.Title,OM.OrderIndex
			Order BY OM.OrderIndex
		END
-- For Admission TypeId=1
IF(@rType='Status')
		BEGIN
			SELECT ISNULL(ASM.Id,0) AS InquiryStatusId,ISNULL(OM.Id,0) AS OrgId,OM.Title AS Organization, ISNULL(ASM.Title,'Pending') AS StatusName ,ISNULL(COUNT(AF.Id),0) AS StatusCount ,0 AS InquiryMainStatusId
			,OM.OrderIndex
			FROM sAdmission.tAdmissionForm AF 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AF.BatchId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
			
			INNER JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AF.OrgId = OM.Id
			LEFT JOIN sAdmission.tAdmissionFormSelected AFS ON AF.Id = AFS.AdmissionFormId
			LEFT JOIN sAdmission.tAdmissionStatusMaster ASM ON ASM.Id = AFS.AdmissionStatusId
			WHERE --BM.IsActive = 1 
			BM.Id = TB.BatchId AND OM.Id = @rOrgId AND COGBM.Id=@rCommonOrgGroupBatchId 
			And ISNULL(O.IsObsolete,0) = 0
			GROUP BY OM.Id,OM.Title,ASM.Id,ASM.Title,OM.OrderIndex
			Order By OM.OrderIndex
		END
-- For Admission TypeId=1
IF(@rType='StatusOrgGroupWise')
		BEGIN
		    CREATE Table #MyTempTable(
						  OrgId Int,
						  Organization nvarchar(100),
                          StatusName nvarchar(100),
                          StatusCount BigInt)
            INSERT INTO #MyTempTable(OrgId,Organization,StatusName,StatusCount)
			SELECT OM.Id,OM.Title AS Organization, ISNULL(ASM.Title,'Pending') AS StatusName ,AF.Id AS StatusCount 			
			FROM sAdmission.tAdmissionForm AF 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AF.BatchId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
			
			INNER JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AF.OrgId = OM.Id
			
			LEFT JOIN sAdmission.tAdmissionFormSelected AFS ON AF.Id = AFS.AdmissionFormId
			LEFT JOIN sAdmission.tAdmissionStatusMaster ASM ON ASM.Id = AFS.AdmissionStatusId
			WHERE --BM.IsActive = 1 
			BM.Id = TB.BatchId
			AND OM.OrgGroupId = @rOrgGroupId AND COGBM.Id=@rCommonOrgGroupBatchId
			And ISNULL(O.IsObsolete,0) = 0;


	DECLARE 
    @columns NVARCHAR(MAX) = '', 
    @sql     NVARCHAR(MAX) = '';

	SELECT 
    @columns+=QUOTENAME(ASM.Title) + ','
  FROM 
    sAdmission.tAdmissionStatusMaster ASM
  ORDER BY 
    ASM.Title;
  -- Add Pending Column
  SET @columns = LEFT(@columns, LEN(@columns) - 1)+',Pending';


  -- construct dynamic SQL
  SET @sql ='
  SELECT * FROM #MyTempTable MT  
  PIVOT(
    Count(MT.StatusCount)
    FOR MT.StatusName IN ('+ @columns +')
  ) AS pivot_table;';

  -- execute the dynamic SQL
  EXECUTE sp_executesql @sql;
  DROP Table #MyTempTable
		END
-- For Admission TypeId=1
ELSE IF(@rType='StatusClassWise')
		BEGIN
		
			SELECT CM.Id AS ClassId,CM.DisplayTitle AS ClassName,ISNULL(COUNT(AF.Id),0) AS StatusCount ,CM.OrderIndex 
			FROM sAdmission.tAdmissionForm AF 
			INNER JOIN sSetup.tClassMaster CM ON CM.Id = AF.ForClassId
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AF.BatchId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
			INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
			INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
			INNER JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AF.OrgId = OM.Id

			LEFT JOIN sAdmission.tAdmissionFormSelected AFS ON AF.Id = AFS.AdmissionFormId
			LEFT JOIN sAdmission.tAdmissionStatusMaster ASM ON ASM.Id = AFS.AdmissionStatusId
			WHERE --BM.IsActive = 1 
			BM.Id = TB.BatchId
			AND OM.OrgGroupId = @rOrgGroupId AND COGBM.Id=@rCommonOrgGroupBatchId
			AND ISNULL(ASM.Id,0)=@rInquiryStatusId
			And ISNULL(O.IsObsolete,0) = 0
			AND((CM.OrgId = @rOrgId)OR(@rOrgId=0))
			GROUP BY CM.Id,CM.DisplayTitle,CM.OrderIndex
		END
-- For Admission TypeId=1
ELSE IF(@rType='StatusClassWise')
		BEGIN
		
			SELECT CM.Id AS ClassId,CM.DisplayTitle AS ClassName,ISNULL(COUNT(AF.Id),0) AS StatusCount ,CM.OrderIndex 
			FROM sAdmission.tAdmissionForm AF 
			INNER JOIN sSetup.tClassMaster CM ON CM.Id = AF.ForClassId
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AF.BatchId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
			INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
			INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
			INNER JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AF.OrgId = OM.Id

			LEFT JOIN sAdmission.tAdmissionFormSelected AFS ON AF.Id = AFS.AdmissionFormId
			LEFT JOIN sAdmission.tAdmissionStatusMaster ASM ON ASM.Id = AFS.AdmissionStatusId
			WHERE --BM.IsActive = 1 
			BM.Id = TB.BatchId
			AND OM.OrgGroupId = @rOrgGroupId AND COGBM.Id=@rCommonOrgGroupBatchId
			AND ISNULL(ASM.Id,0)=@rInquiryStatusId
			And ISNULL(O.IsObsolete,0) = 0
			AND((CM.OrgId = @rOrgId)OR(@rOrgId=0))
			GROUP BY CM.Id,CM.DisplayTitle,CM.OrderIndex
		END
-- For Admission TypeId=1
ELSE IF(@rType='StatusStudentList')
			BEGIN
			SELECT AF.FormNo As InquiryId, AF.FirstName+' '+AF.MiddleName +' '+ AF.LastName AS StudentName,AF.ContactNo AS ContactNo 
			FROM sAdmission.tAdmissionForm AF 
			INNER JOIN sSetup.tClassMaster CM ON CM.Id = AF.ForClassId
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AF.BatchId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
			INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
			INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
			INNER JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AF.OrgId = OM.Id
			LEFT JOIN sAdmission.tAdmissionFormSelected AFS ON AF.Id = AFS.AdmissionFormId
			LEFT JOIN sAdmission.tAdmissionStatusMaster ASM ON ASM.Id = AFS.AdmissionStatusId
			WHERE --BM.IsActive = 1 
			BM.Id = TB.BatchId
			AND OM.OrgGroupId = @rOrgGroupId 
			AND COGBM.Id=@rCommonOrgGroupBatchId
			AND ISNULL(ASM.Id,0)=@rInquiryStatusId
			AND((CM.OrgId = @rOrgId)OR(@rOrgId=0))
			AND((CM.Id = @rClassId)OR(@rClassId=0))
			And ISNULL(O.IsObsolete,0) = 0
			GROUP BY AF.FirstName,AF.MiddleName,AF.LastName,AF.ContactNo,AF.FormNo
			END
			END
	
-- For Inquiry
	IF(@rTypeId=2)
	BEGIN
	IF(@rType='OrgGroup')
		BEGIN
			IF(@rSyncDate =1)
				BEGIN
			DELETE  sAdmission.tTempAdmissionInquiryCount WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))  
			IF EXISTS (SELECT 1 FROM sAdmission.tTempAdmissionInquiryCount WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND (OrgGroupId = @rOrgGroupId))  
				   BEGIN  
				   IF(@rOrgGroupId !=0)  
				   INSERT INTO sAdmission.tTempAdmissionInquiryCount  
					SELECT ISNULL(OGM.Id,0) AS OrgGroupId,OGM.Title AS OrgGroupTitle,ISNULL(COUNT(AI.Id),0) AS AdmissionCount,@rCommonOrgGroupBatchId,GetDate()  
					FROM   
					sSetup.tOrgGroupMaster OGM  
					INNER JOIN sSetup.tOrganizationMaster OM ON OGM.Id = OM.OrgGroupId   
			        
					INNER JOIN @lTempBatchId TB ON TB.OrgId = OM.Id  
					LEFT JOIN sSetup.tBatchMaster BM ON BM.Id = TB.BatchId  
					INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId  
					INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId        
					INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId   
			        
					LEFT JOIN sAdmission.tAdmissionInquiry AI ON BM.Id = AI.ForBatchId    
					WHERE OGM.Id<>1 and BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId   
					--BM.IsActive = 1  
					GROUP BY OGM.Id,OGM.Title  
					SELECT OrgGroupTitle AS OrgGroup,0 AS PendingCount,0 AS ConfirmCount,* FROM sAdmission.tTempAdmissionInquiryCount WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))  
				   END  
      ELSE   
       BEGIN  
		    INSERT INTO sAdmission.tTempAdmissionInquiryCount  
        SELECT ISNULL(OGM.Id,0) AS OrgGroupId,OGM.Title AS OrgGroupTitle,ISNULL(COUNT(AI.Id),0) AS AdmissionCount,@rCommonOrgGroupBatchId,GetDate()  
       FROM   
       sSetup.tOrgGroupMaster OGM  
       INNER JOIN sSetup.tOrganizationMaster OM ON OGM.Id = OM.OrgGroupId   
       
       INNER JOIN @lTempBatchId TB ON TB.OrgId = OM.Id  
       LEFT JOIN sSetup.tBatchMaster BM ON BM.Id = TB.BatchId  
       INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId  
       INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId        
       INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId   
       LEFT JOIN sAdmission.tAdmissionInquiry AI ON BM.Id = AI.ForBatchId  
       WHERE OGM.Id<>1 and BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId   
       --BM.IsActive = 1  
       GROUP BY OGM.Id,OGM.Title  
		  SELECT OrgGroupTitle AS OrgGroup,0 AS PendingCount,0 AS ConfirmCount,* FROM sAdmission.tTempAdmissionInquiryCount WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))  
       END  
				END
			ELSE
				BEGIN
						IF  Exists(select 1 from sAdmission.tTempAdmissionInquiryCount   where CONVERT(date,UpdateDate) =  CONVERT(date,getdate(),102)   AND CommonOrgGroupBatchId=@rCommonOrgGroupBatchId  AND (OrgGroupId = @rOrgGroupId))  
			  BEGIN  
			   SELECT  OrgGroupTitle AS OrgGroup,0 AS PendingCount,0 AS ConfirmCount,* FROM sAdmission.tTempAdmissionInquiryCount   WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))  
			   return  
			  END  
			 ELSE  
			  BEGIN  
			  DELETE  sAdmission.tTempAdmissionInquiryCount WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))  
			  IF EXISTS (SELECT 1 FROM sAdmission.tTempAdmissionInquiryCount WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0)))  
			   BEGIN  
				IF(@rOrgGroupId !=0)  
				INSERT INTO sAdmission.tTempAdmissionInquiryCount  
				 SELECT ISNULL(OGM.Id,0) AS OrgGroupId,OGM.Title AS OrgGroupTitle,ISNULL(COUNT(AI.Id),0) AS AdmissionCount,@rCommonOrgGroupBatchId,GetDate()  
				FROM   
				sSetup.tOrgGroupMaster OGM  
				INNER JOIN sSetup.tOrganizationMaster OM ON OGM.Id = OM.OrgGroupId   
		        
				INNER JOIN @lTempBatchId TB ON TB.OrgId = OM.Id  
				LEFT JOIN sSetup.tBatchMaster BM ON BM.Id = TB.BatchId  
				INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId  
				INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId        
				INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId   
		        
				LEFT JOIN sAdmission.tAdmissionInquiry AI ON BM.Id = AI.ForBatchId  
				WHERE OGM.Id<>1 and BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId   
				--BM.IsActive = 1  
				GROUP BY OGM.Id,OGM.Title  
				SELECT OrgGroupTitle AS OrgGroup,0 AS PendingCount,0 AS ConfirmCount,* FROM sAdmission.tTempAdmissionInquiryCount WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))  
			   END  
			  ELSE  
			   BEGIN  
				DELETE  sAdmission.tTempAdmissionInquiryCount WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))  
				INSERT INTO sAdmission.tTempAdmissionInquiryCount  
				 SELECT ISNULL(OGM.Id,0) AS OrgGroupId,OGM.Title AS OrgGroupTitle,ISNULL(COUNT(AI.Id),0) AS AdmissionCount,@rCommonOrgGroupBatchId,GetDate()  
				FROM   
				sSetup.tOrgGroupMaster OGM  
				INNER JOIN sSetup.tOrganizationMaster OM ON OGM.Id = OM.OrgGroupId   
				INNER JOIN @lTempBatchId TB ON TB.OrgId = OM.Id  
				LEFT JOIN sSetup.tBatchMaster BM ON BM.Id = TB.BatchId  
				INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId  
				INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId        
				INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId   
				LEFT JOIN sAdmission.tAdmissionInquiry AI ON BM.Id = AI.ForBatchId  
				WHERE OGM.Id<>1 and BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId   
				--BM.IsActive = 1  
				GROUP BY OGM.Id,OGM.Title  
				SELECT OrgGroupTitle AS OrgGroup,0 AS PendingCount,0 AS ConfirmCount,* FROM sAdmission.tTempAdmissionInquiryCount WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))  
       END  
		END  
		 END		
		END
-- For Inquiry
	IF(@rType='Organization')
		BEGIN
			SELECT ISNULL(OM.Id,0) AS OrgId,OM.Title AS Organization,ISNULL(COUNT(AI.Id),0) AS AdmissionCount,OM.OrderIndex
			FROM sAdmission.tAdmissionInquiry AI 
			LEFT JOIN sSetup.tOrganizationMaster OM ON AI.OrgId = OM.Id
			LEFT JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForBatchId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
			
			LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			
			--sAdmission.tAdmissionForm AF 
			--LEFT JOIN  sSetup.tOrganizationMaster OM ON AF.OrgId = OM.Id 	
			--LEFT JOIN sSetup.tBatchMaster BM ON BM.Id = AF.BatchId
			--LEFT JOIN @lTempBatchId TB ON TB.OrgId = OM.Id and BM.Id = TB.BatchId
			WHERE BM.Id = TB.BatchId
			And ISNULL(O.IsObsolete,0) = 0
			--BM.IsActive = 1 
			AND OM.OrgGroupId = @rOrgGroupId AND COGBM.Id=@rCommonOrgGroupBatchId
			GROUP BY OM.Id,OM.Title,OM.OrderIndex
			ORDER BY OM.OrderIndex
		END
-- For Inquiry
	IF(@rType='Status')
		BEGIN
		IF(@lConfigValue = 'True')
		BEGIN
-- 11
-- Inquiry Form 
			SELECT 
			ISM.Id AS InquiryStatusId,
			ISNULL(OM.Id,0) AS OrgId,
			OM.Title AS Organization,
			ISNULL(ISM.Title,'') AS StatusName,
			(
			SELECT 
			ISNULL(COUNT(ISM.Id),0) AS StatusCount 
			FROM sAdmission.tAdmissionInquiry AI1 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI1.ForBatchId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
			LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AI1.OrgId = OM.Id
			LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI1.InquiryStatusId
			WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
			AND ISM.InquiryMainStatusId >= 11
			AND((OM.Id = @rOrgId)OR(@rOrgId=0)) AND OM.Id = AI.OrgId
			) AS StatusCount,
			ISM.InquiryMainStatusId AS InquiryMainStatusId
			FROM sAdmission.tAdmissionInquiry AI 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForBatchId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
			
			LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AI.OrgId = OM.Id
			LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI.InquiryStatusId
			WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
			AND ISM.InquiryMainStatusId = 11
			--BM.IsActive = 1 
			AND((OM.Id = @rOrgId)OR(@rOrgId=0))
			And ISNULL(O.IsObsolete,0) = 0
			
			GROUP BY OM.Id,OM.Title,ISM.Id,ISM.Title,ISM.InquiryMainStatusId,AI.OrgId
			
			UNION ALL
-- 21
-- Admission Form Given
			SELECT 
			ISM.Id AS InquiryStatusId,
			ISNULL(OM.Id,0) AS OrgId,
			OM.Title AS Organization,
			ISNULL(ISM.Title,'') AS StatusName,
			(
			SELECT 
			ISNULL(COUNT(ISM.Id),0) AS StatusCount 
			FROM sAdmission.tAdmissionInquiry AI1
			INNER JOIN sSetup.tClassMaster CM ON CM.Id = AI1.ForClassId
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI1.ForBatchId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
			LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AI1.OrgId = OM.Id
			LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI1.InquiryStatusId
			WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
			AND ISM.InquiryMainStatusId > 11
			--BM.IsActive = 1 
			AND((OM.Id = @rOrgId)OR(@rOrgId=0)) AND OM.Id = AI.OrgId
			) AS StatusCount,
			ISM.InquiryMainStatusId AS InquiryMainStatusId
			FROM sAdmission.tAdmissionInquiry AI 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForBatchId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
			
			LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AI.OrgId = OM.Id
			LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI.InquiryStatusId
			WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
			AND ISM.InquiryMainStatusId = 21
			--BM.IsActive = 1 
			AND((OM.Id = @rOrgId)OR(@rOrgId=0))
			And ISNULL(O.IsObsolete,0) = 0
			GROUP BY OM.Id,OM.Title,ISM.Id,ISM.Title,ISM.InquiryMainStatusId,AI.OrgId
			
			UNION ALL
-- 31
-- Admission Form Submitted
			SELECT 
			ISM.Id AS InquiryStatusId,
			ISNULL(OM.Id,0) AS OrgId,
			OM.Title AS Organization,
			ISNULL(ISM.Title,'') AS StatusName,
			(
			SELECT 
			ISNULL(COUNT(ISM.Id),0) AS StatusCount 
			FROM sAdmission.tAdmissionInquiry AI1 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI1.ForBatchId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
			LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AI1.OrgId = OM.Id
			LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI1.InquiryStatusId
			WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
			AND ISM.InquiryMainStatusId > 21
			--BM.IsActive = 1 
			AND((OM.Id = @rOrgId)OR(@rOrgId=0))  AND OM.Id = AI.OrgId
			) AS StatusCount ,
			ISM.InquiryMainStatusId AS InquiryMainStatusId
			FROM sAdmission.tAdmissionInquiry AI 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForBatchId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
			
			LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AI.OrgId = OM.Id
			LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI.InquiryStatusId
			WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
			AND ISM.InquiryMainStatusId =31
			--BM.IsActive = 1 
			AND((OM.Id = @rOrgId)OR(@rOrgId=0))
			And ISNULL(O.IsObsolete,0) = 0
			GROUP BY OM.Id,OM.Title,ISM.Id,ISM.Title,ISM.InquiryMainStatusId,AI.OrgId
			
			UNION ALL
-- 41
-- Appeared For Entrance Exam
			SELECT 
			ISM.Id AS InquiryStatusId,
			ISNULL(OM.Id,0) AS OrgId,
			OM.Title AS Organization,
			ISNULL(ISM.Title,'') AS StatusName,
			(
			SELECT 
			ISNULL(COUNT(ISM.Id),0) AS StatusCount 
			FROM sAdmission.tAdmissionInquiry AI1 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI1.ForBatchId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
			LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AI1.OrgId = OM.Id
			LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI1.InquiryStatusId
			WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
			AND ISM.InquiryMainStatusId > 31
			--BM.IsActive = 1 
			AND((OM.Id = @rOrgId)OR(@rOrgId=0))  AND OM.Id = AI.OrgId
			) AS StatusCount  ,
			ISM.InquiryMainStatusId AS InquiryMainStatusId
			FROM sAdmission.tAdmissionInquiry AI 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForBatchId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
			
			LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AI.OrgId = OM.Id
			LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI.InquiryStatusId
			WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
			AND ISM.InquiryMainStatusId =41
			--BM.IsActive = 1 
			AND((OM.Id = @rOrgId)OR(@rOrgId=0))
			And ISNULL(O.IsObsolete,0) = 0
			GROUP BY OM.Id,OM.Title,ISM.Id,ISM.Title,ISM.InquiryMainStatusId,AI.OrgId
			
			UNION ALL
-- 51
-- Came for Interaction
			SELECT 
			ISM.Id AS InquiryStatusId,
			ISNULL(OM.Id,0) AS OrgId,
			OM.Title AS Organization,
			ISNULL(ISM.Title,'') AS StatusName,
			(
			SELECT 
			ISNULL(COUNT(ISM.Id),0) AS StatusCount 
			FROM sAdmission.tAdmissionInquiry AI1
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI1.ForBatchId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
			LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AI1.OrgId = OM.Id
			LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI1.InquiryStatusId
			WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
			AND ISM.InquiryMainStatusId > 41 and ISM.InquiryMainStatusId <> 61

			--BM.IsActive = 1 
			AND((OM.Id = @rOrgId)OR(@rOrgId=0)) AND OM.Id = AI.OrgId
			) AS StatusCount  ,
			ISM.InquiryMainStatusId AS InquiryMainStatusId
			FROM sAdmission.tAdmissionInquiry AI 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForBatchId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
			
			LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AI.OrgId = OM.Id
			LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI.InquiryStatusId
			WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
			AND ISM.InquiryMainStatusId =51 
			--BM.IsActive = 1 
			AND((OM.Id = @rOrgId)OR(@rOrgId=0))
			And ISNULL(O.IsObsolete,0) = 0
			GROUP BY OM.Id,OM.Title,ISM.Id,ISM.Title,ISM.InquiryMainStatusId,AI.OrgId
			
			UNION ALL
-- 61
-- Not Came for interaction
			SELECT 
			ISM.Id AS InquiryStatusId,
			ISNULL(OM.Id,0) AS OrgId,
			OM.Title AS Organization,
			ISNULL(ISM.Title,'') AS StatusName,
			(
			SELECT 
			ISNULL(COUNT(ISM.Id),0) AS StatusCount 
			FROM sAdmission.tAdmissionInquiry AI1
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI1.ForBatchId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
			LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AI1.OrgId = OM.Id
			LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI1.InquiryStatusId
			WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
			--AND ISM.InquiryMainStatusId > 51  AND ISM.InquiryMainStatusId !=71
			AND ISM.InquiryMainStatusId = 61

			--BM.IsActive = 1 
			AND((OM.Id = @rOrgId)OR(@rOrgId=0))  AND OM.Id = AI.OrgId
			) AS StatusCount  ,
			ISM.InquiryMainStatusId AS InquiryMainStatusId
			FROM sAdmission.tAdmissionInquiry AI 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForBatchId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
			
			LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AI.OrgId = OM.Id
			LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI.InquiryStatusId
			WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
			AND ISM.InquiryMainStatusId = 61 

			--BM.IsActive = 1 
			AND((OM.Id = @rOrgId)OR(@rOrgId=0))
			And ISNULL(O.IsObsolete,0) = 0
			GROUP BY OM.Id,OM.Title,ISM.Id,ISM.Title,ISM.InquiryMainStatusId,AI.OrgId
		
		    UNION ALL
			
-- 71
--Confirmed Admission

			SELECT
			ISM.Id AS InquiryStatusId, 
			ISNULL(OM.Id,0) AS OrgId,
			OM.Title AS Organization,
			ISNULL(ISM.Title,'') AS StatusName,
			(
			SELECT 
			ISNULL(COUNT(ISM.Id),0) AS StatusCount 
			FROM sAdmission.tAdmissionInquiry AI1
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI1.ForBatchId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
			LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AI1.OrgId = OM.Id
			LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI1.InquiryStatusId
			WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
			AND ISM.InquiryMainStatusId > 61 

			--BM.IsActive = 1 
			AND((OM.Id = @rOrgId)OR(@rOrgId=0))  AND OM.Id = AI.OrgId
			) AS StatusCount  ,
			ISM.InquiryMainStatusId AS InquiryMainStatusId
			FROM sAdmission.tAdmissionInquiry AI 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForBatchId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
			
			LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AI.OrgId = OM.Id
			LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI.InquiryStatusId
			WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
			AND ISM.InquiryMainStatusId =71
			--BM.IsActive = 1 
			AND((OM.Id = @rOrgId)OR(@rOrgId=0))
			And ISNULL(O.IsObsolete,0) = 0
			GROUP BY OM.Id,OM.Title,ISM.Id,ISM.Title,ISM.InquiryMainStatusId,AI.OrgId
			UNION ALL
-- 81
-- Rejected Form
			SELECT 
			ISM.Id AS InquiryStatusId,
			ISNULL(OM.Id,0) AS OrgId,
			OM.Title AS Organization,
			ISNULL(ISM.Title,'') AS StatusName,
			(
			SELECT 
			ISNULL(COUNT(ISM.Id),0) AS StatusCount 
			FROM sAdmission.tAdmissionInquiry AI1 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI1.ForBatchId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
			LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AI1.OrgId = OM.Id
			LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI1.InquiryStatusId
			WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
			AND ISM.InquiryMainStatusId =81
			--BM.IsActive = 1 
			AND((OM.Id = @rOrgId)OR(@rOrgId=0)) AND OM.Id = AI.OrgId
			) AS StatusCount  ,
			ISM.InquiryMainStatusId AS InquiryMainStatusId
			FROM sAdmission.tAdmissionInquiry AI 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForBatchId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
			LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AI.OrgId = OM.Id
			LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI.InquiryStatusId
			WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
			AND ISM.InquiryMainStatusId =81
			--BM.IsActive = 1 
			AND((OM.Id = @rOrgId)OR(@rOrgId=0))
			And ISNULL(O.IsObsolete,0) = 0
			GROUP BY OM.Id,OM.Title,ISM.Id,ISM.Title,ISM.InquiryMainStatusId,AI.OrgId
			UNION ALL
-- 91
-- Fees Paid

			SELECT 
			ISM.Id AS InquiryStatusId,
			ISNULL(OM.Id,0) AS OrgId,
			OM.Title AS Organization,
			ISNULL(ISM.Title,'') AS StatusName,
			(
			SELECT 
			ISNULL(COUNT(ISM.Id),0) AS StatusCount 
			FROM sAdmission.tAdmissionInquiry AI1 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI1.ForBatchId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
			LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AI1.OrgId = OM.Id
			LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI1.InquiryStatusId
			WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
			AND ISM.InquiryMainStatusId > 81 AND ISM.InquiryMainStatusId !=101

			--BM.IsActive = 1 
			AND((OM.Id = @rOrgId)OR(@rOrgId=0))  AND OM.Id = AI.OrgId
			) AS StatusCount ,
			ISM.InquiryMainStatusId AS InquiryMainStatusId 
			FROM sAdmission.tAdmissionInquiry AI 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForBatchId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
			
			LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AI.OrgId = OM.Id
			LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI.InquiryStatusId
			WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
			AND ISM.InquiryMainStatusId =91

 
			--BM.IsActive = 1 
			AND((OM.Id = @rOrgId)OR(@rOrgId=0))
			And ISNULL(O.IsObsolete,0) = 0
			GROUP BY OM.Id,OM.Title,ISM.Id,ISM.Title,ISM.InquiryMainStatusId,AI.OrgId
			UNION ALL
-- 101		
-- Fees not paid
			SELECT 
			ISM.Id AS InquiryStatusId,
			ISNULL(OM.Id,0) AS OrgId,
			OM.Title AS Organization,
			ISNULL(ISM.Title,'') AS StatusName,
			(
			SELECT 
			ISNULL(COUNT(ISM.Id),0) AS StatusCount 
			FROM sAdmission.tAdmissionInquiry AI1 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI1.ForBatchId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
			LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AI1.OrgId = OM.Id
			LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI1.InquiryStatusId
			WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
			AND ISM.InquiryMainStatusId =101
			--BM.IsActive = 1 
			AND((OM.Id = @rOrgId)OR(@rOrgId=0))AND OM.Id = AI.OrgId
			) AS StatusCount ,
			ISM.InquiryMainStatusId AS InquiryMainStatusId 
			FROM sAdmission.tAdmissionInquiry AI 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForBatchId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
			LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AI.OrgId = OM.Id
			LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI.InquiryStatusId
			WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
			AND ISM.InquiryMainStatusId =101
			--BM.IsActive = 1 
			AND((OM.Id = @rOrgId)OR(@rOrgId=0))
			And ISNULL(O.IsObsolete,0) = 0
			GROUP BY OM.Id,OM.Title,ISM.Id,ISM.Title,ISM.InquiryMainStatusId,AI.OrgId
			UNION ALL
-- 111			
-- Refunded Fees
			SELECT 
			ISM.Id AS InquiryStatusId,
			ISNULL(OM.Id,0) AS OrgId,
			OM.Title AS Organization,
			ISNULL(ISM.Title,'') AS StatusName,
			(
			SELECT 
			ISNULL(COUNT(ISM.Id),0) AS StatusCount 
			FROM sAdmission.tAdmissionInquiry AI1 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI1.ForBatchId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
			LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AI1.OrgId = OM.Id
			LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI1.InquiryStatusId
			WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
			AND ISM.InquiryMainStatusId > 101

			--BM.IsActive = 1 
			AND OM.OrgGroupId = @rOrgGroupId  AND OM.Id = AI.OrgId
			) AS StatusCount  ,
			ISM.InquiryMainStatusId AS InquiryMainStatusId
			FROM sAdmission.tAdmissionInquiry AI 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForBatchId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
			
			LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AI.OrgId = OM.Id
			LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI.InquiryStatusId
			WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
			AND ISM.InquiryMainStatusId =111
 
			--BM.IsActive = 1 
			AND((OM.Id = @rOrgId)OR(@rOrgId=0))
			And ISNULL(O.IsObsolete,0) = 0
			GROUP BY OM.Id,OM.Title,ISM.Id,ISM.Title,ISM.InquiryMainStatusId,AI.OrgId
		END
		ELSE 
		BEGIN
			SELECT 
			ISM1.Id AS InquiryStatusId,
			ISNULL(OM.Id,0) AS OrgId,
			OM.Title AS Organization,
			ISNULL(ISM1.Title,'') AS StatusName,
			ISNULL(COUNT(ISM1.Id),0) AS StatusCount, 
			ISM1.InquiryMainStatusId AS InquiryMainStatusId
			,OM.OrderIndex
			FROM sAdmission.tAdmissionInquiry AI 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForBatchId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
			LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AI.OrgId = OM.Id
			LEFT JOIN sAdmission.tInquiryStatusMaster ISM1 ON ISM1.Id = AI.InquiryStatusId
			WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
			--AND ISM.InquiryMainStatusId = 11
			--BM.IsActive = 1 
			AND((OM.Id = @rOrgId)OR(@rOrgId=0))
			And ISNULL(O.IsObsolete,0) = 0
			
			GROUP BY OM.Id,OM.Title,ISM1.Id,ISM1.Title,ISM1.InquiryMainStatusId,AI.OrgId,OM.OrderIndex
			ORDER BY OM.OrderIndex
		END
		END
		
	IF(@rType='StatusOrgGroupWise')
		BEGIN
		IF(@lConfigValue = 'True')
		BEGIN

-- 11
-- Inquiry Form 
			SELECT 
			ISM.Id AS InquiryStatusId,
			ISNULL(OM.Id,0) AS OrgId,
			OM.Title AS Organization,
			ISNULL(ISM.Title,'') AS StatusName,
			(
			SELECT 
			ISNULL(COUNT(ISM.Id),0) AS StatusCount 
			FROM sAdmission.tAdmissionInquiry AI1 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI1.ForBatchId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
			LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AI1.OrgId = OM.Id
			LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI1.InquiryStatusId
			WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
			AND ISM.InquiryMainStatusId >= 11
			AND OM.OrgGroupId = @rOrgGroupId AND OM.Id = AI.OrgId
			) AS StatusCount,
			ISNULL(ISM.InquiryMainStatusId,0) AS InquiryMainStatusId
			FROM sAdmission.tAdmissionInquiry AI 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForBatchId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
			
			LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AI.OrgId = OM.Id
			LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI.InquiryStatusId
			WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
			AND ISM.InquiryMainStatusId = 11
			--BM.IsActive = 1 
			AND OM.OrgGroupId = @rOrgGroupId
			And ISNULL(O.IsObsolete,0) = 0
			
			GROUP BY OM.Id,OM.Title,ISM.Id,ISM.Title,ISM.InquiryMainStatusId,AI.OrgId
			
			UNION ALL
-- 21
-- Admission Form Given
			SELECT 
			ISM.Id AS InquiryStatusId,
			ISNULL(OM.Id,0) AS OrgId,
			OM.Title AS Organization,
			ISNULL(ISM.Title,'') AS StatusName,
			(
			SELECT 
			ISNULL(COUNT(ISM.Id),0) AS StatusCount 
			FROM sAdmission.tAdmissionInquiry AI1
			INNER JOIN sSetup.tClassMaster CM ON CM.Id = AI1.ForClassId
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI1.ForBatchId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
			LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AI1.OrgId = OM.Id
			LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI1.InquiryStatusId
			WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
			AND ISM.InquiryMainStatusId > 11
			--BM.IsActive = 1 
			AND OM.OrgGroupId = @rOrgGroupId AND OM.Id = AI.OrgId
			) AS StatusCount,
			ISM.InquiryMainStatusId AS InquiryMainStatusId
			FROM sAdmission.tAdmissionInquiry AI 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForBatchId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
			
			LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AI.OrgId = OM.Id
			LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI.InquiryStatusId
			WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
			AND ISM.InquiryMainStatusId = 21
			--BM.IsActive = 1 
			AND OM.OrgGroupId = @rOrgGroupId
			And ISNULL(O.IsObsolete,0) = 0
			GROUP BY OM.Id,OM.Title,ISM.Id,ISM.Title,ISM.InquiryMainStatusId,AI.OrgId
			
			UNION ALL
-- 31
-- Admission Form Submitted
			SELECT 
			ISM.Id AS InquiryStatusId,
			ISNULL(OM.Id,0) AS OrgId,
			OM.Title AS Organization,
			ISNULL(ISM.Title,'') AS StatusName,
			(
			SELECT 
			ISNULL(COUNT(ISM.Id),0) AS StatusCount 
			FROM sAdmission.tAdmissionInquiry AI1 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI1.ForBatchId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
			LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AI1.OrgId = OM.Id
			LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI1.InquiryStatusId
			WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
			AND ISM.InquiryMainStatusId > 21
			--BM.IsActive = 1 
			AND OM.OrgGroupId = @rOrgGroupId  AND OM.Id = AI.OrgId
			) AS StatusCount ,
			ISM.InquiryMainStatusId AS InquiryMainStatusId
			FROM sAdmission.tAdmissionInquiry AI 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForBatchId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
			
			LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AI.OrgId = OM.Id
			LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI.InquiryStatusId
			WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
			AND ISM.InquiryMainStatusId =31
			--BM.IsActive = 1 
			AND OM.OrgGroupId = @rOrgGroupId
			And ISNULL(O.IsObsolete,0) = 0
			GROUP BY OM.Id,OM.Title,ISM.Id,ISM.Title,ISM.InquiryMainStatusId,AI.OrgId
			
			UNION ALL
-- 41
-- Appeared For Entrance Exam
			SELECT 
			ISM.Id AS InquiryStatusId,
			ISNULL(OM.Id,0) AS OrgId,
			OM.Title AS Organization,
			ISNULL(ISM.Title,'') AS StatusName,
			(
			SELECT 
			ISNULL(COUNT(ISM.Id),0) AS StatusCount 
			FROM sAdmission.tAdmissionInquiry AI1 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI1.ForBatchId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
			LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AI1.OrgId = OM.Id
			LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI1.InquiryStatusId
			WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
			AND ISM.InquiryMainStatusId > 31
			--BM.IsActive = 1 
			AND OM.OrgGroupId = @rOrgGroupId  AND OM.Id = AI.OrgId
			) AS StatusCount  ,
			ISM.InquiryMainStatusId AS InquiryMainStatusId
			FROM sAdmission.tAdmissionInquiry AI 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForBatchId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
			
			LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AI.OrgId = OM.Id
			LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI.InquiryStatusId
			WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
			AND ISM.InquiryMainStatusId =41
			--BM.IsActive = 1 
			AND OM.OrgGroupId = @rOrgGroupId
			And ISNULL(O.IsObsolete,0) = 0
			GROUP BY OM.Id,OM.Title,ISM.Id,ISM.Title,ISM.InquiryMainStatusId,AI.OrgId
			
			
			
			UNION ALL
-- 51
-- Came for Interaction
			SELECT 
			ISM.Id AS InquiryStatusId,
			ISNULL(OM.Id,0) AS OrgId,
			OM.Title AS Organization,
			ISNULL(ISM.Title,'') AS StatusName,
			(
			SELECT 
			ISNULL(COUNT(ISM.Id),0) AS StatusCount 
			FROM sAdmission.tAdmissionInquiry AI1
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI1.ForBatchId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
			LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AI1.OrgId = OM.Id
			LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI1.InquiryStatusId
			WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
			AND ISM.InquiryMainStatusId > 41 and ISM.InquiryMainStatusId <> 61

			--BM.IsActive = 1 
			AND OM.OrgGroupId = @rOrgGroupId AND OM.Id = AI.OrgId
			) AS StatusCount  ,
			ISM.InquiryMainStatusId AS InquiryMainStatusId
			FROM sAdmission.tAdmissionInquiry AI 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForBatchId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
			
			LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AI.OrgId = OM.Id
			LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI.InquiryStatusId
			WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
			AND ISM.InquiryMainStatusId =51 
			--BM.IsActive = 1 
			AND OM.OrgGroupId = @rOrgGroupId
			And ISNULL(O.IsObsolete,0) = 0
			GROUP BY OM.Id,OM.Title,ISM.Id,ISM.Title,ISM.InquiryMainStatusId,AI.OrgId
			
			UNION ALL
-- 61
-- Not Came for interaction
			SELECT 
			ISM.Id AS InquiryStatusId,
			ISNULL(OM.Id,0) AS OrgId,
			OM.Title AS Organization,
			ISNULL(ISM.Title,'') AS StatusName,
			(
			SELECT 
			ISNULL(COUNT(ISM.Id),0) AS StatusCount 
			FROM sAdmission.tAdmissionInquiry AI1
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI1.ForBatchId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
			LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AI1.OrgId = OM.Id
			LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI1.InquiryStatusId
			WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
			--AND ISM.InquiryMainStatusId > 51  AND ISM.InquiryMainStatusId !=71
			AND ISM.InquiryMainStatusId = 61

			--BM.IsActive = 1 
			AND OM.OrgGroupId = @rOrgGroupId  AND OM.Id = AI.OrgId
			) AS StatusCount  ,
			ISM.InquiryMainStatusId AS InquiryMainStatusId
			FROM sAdmission.tAdmissionInquiry AI 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForBatchId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
			
			LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AI.OrgId = OM.Id
			LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI.InquiryStatusId
			WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
			AND ISM.InquiryMainStatusId = 61 

			--BM.IsActive = 1 
			AND OM.OrgGroupId = @rOrgGroupId
			And ISNULL(O.IsObsolete,0) = 0
			GROUP BY OM.Id,OM.Title,ISM.Id,ISM.Title,ISM.InquiryMainStatusId,AI.OrgId
		
		UNION ALL
			
-- 71
--Confirmed Admission

			SELECT
			ISM.Id AS InquiryStatusId, 
			ISNULL(OM.Id,0) AS OrgId,
			OM.Title AS Organization,
			ISNULL(ISM.Title,'') AS StatusName,
			(
			SELECT 
			ISNULL(COUNT(ISM.Id),0) AS StatusCount 
			FROM sAdmission.tAdmissionInquiry AI1
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI1.ForBatchId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
			LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AI1.OrgId = OM.Id
			LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI1.InquiryStatusId
			WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
			AND ISM.InquiryMainStatusId > 61 

			--BM.IsActive = 1 
			AND OM.OrgGroupId = @rOrgGroupId  AND OM.Id = AI.OrgId
			) AS StatusCount  ,
			ISM.InquiryMainStatusId AS InquiryMainStatusId
			FROM sAdmission.tAdmissionInquiry AI 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForBatchId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
			
			LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AI.OrgId = OM.Id
			LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI.InquiryStatusId
			WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
			AND ISM.InquiryMainStatusId =71
			--BM.IsActive = 1 
			AND OM.OrgGroupId = @rOrgGroupId
			And ISNULL(O.IsObsolete,0) = 0
			GROUP BY OM.Id,OM.Title,ISM.Id,ISM.Title,ISM.InquiryMainStatusId,AI.OrgId
			UNION ALL
-- 81
-- Rejected Form
			SELECT 
			ISM.Id AS InquiryStatusId,
			ISNULL(OM.Id,0) AS OrgId,
			OM.Title AS Organization,
			ISNULL(ISM.Title,'') AS StatusName,
			(
			SELECT 
			ISNULL(COUNT(ISM.Id),0) AS StatusCount 
			FROM sAdmission.tAdmissionInquiry AI1 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI1.ForBatchId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
			LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AI1.OrgId = OM.Id
			LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI1.InquiryStatusId
			WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
			AND ISM.InquiryMainStatusId =81
			--BM.IsActive = 1 
			AND OM.OrgGroupId = @rOrgGroupId  AND OM.Id = AI.OrgId
			) AS StatusCount  ,
			ISM.InquiryMainStatusId AS InquiryMainStatusId
			FROM sAdmission.tAdmissionInquiry AI 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForBatchId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
			LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AI.OrgId = OM.Id
			LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI.InquiryStatusId
			WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
			AND ISM.InquiryMainStatusId =81
			--BM.IsActive = 1 
			AND OM.OrgGroupId = @rOrgGroupId
			And ISNULL(O.IsObsolete,0) = 0
			GROUP BY OM.Id,OM.Title,ISM.Id,ISM.Title,ISM.InquiryMainStatusId,AI.OrgId
			UNION ALL
-- 91
-- Fees Paid

			SELECT 
			ISM.Id AS InquiryStatusId,
			ISNULL(OM.Id,0) AS OrgId,
			OM.Title AS Organization,
			ISNULL(ISM.Title,'') AS StatusName,
			(
			SELECT 
			ISNULL(COUNT(ISM.Id),0) AS StatusCount 
			FROM sAdmission.tAdmissionInquiry AI1 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI1.ForBatchId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
			LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AI1.OrgId = OM.Id
			LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI1.InquiryStatusId
			WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
			AND ISM.InquiryMainStatusId > 81 AND ISM.InquiryMainStatusId !=101

			--BM.IsActive = 1 
			AND OM.OrgGroupId = @rOrgGroupId  AND OM.Id = AI.OrgId
			) AS StatusCount ,
			ISM.InquiryMainStatusId AS InquiryMainStatusId 
			FROM sAdmission.tAdmissionInquiry AI 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForBatchId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
			
			LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AI.OrgId = OM.Id
			LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI.InquiryStatusId
			WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
			AND ISM.InquiryMainStatusId =91

 
			--BM.IsActive = 1 
			AND OM.OrgGroupId = @rOrgGroupId
			And ISNULL(O.IsObsolete,0) = 0
			GROUP BY OM.Id,OM.Title,ISM.Id,ISM.Title,ISM.InquiryMainStatusId,AI.OrgId
			UNION ALL
-- 101		
-- Fees not paid
			SELECT 
			ISM.Id AS InquiryStatusId,
			ISNULL(OM.Id,0) AS OrgId,
			OM.Title AS Organization,
			ISNULL(ISM.Title,'') AS StatusName,
			(
			SELECT 
			ISNULL(COUNT(ISM.Id),0) AS StatusCount 
			FROM sAdmission.tAdmissionInquiry AI1 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI1.ForBatchId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
			LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AI1.OrgId = OM.Id
			LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI1.InquiryStatusId
			WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
			AND ISM.InquiryMainStatusId =101
			--BM.IsActive = 1 
			AND OM.OrgGroupId = @rOrgGroupId AND OM.Id = AI.OrgId
			) AS StatusCount ,
			ISM.InquiryMainStatusId AS InquiryMainStatusId 
			FROM sAdmission.tAdmissionInquiry AI 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForBatchId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
			LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AI.OrgId = OM.Id
			LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI.InquiryStatusId
			WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
			AND ISM.InquiryMainStatusId =101
			--BM.IsActive = 1 
			AND OM.OrgGroupId = @rOrgGroupId
			And ISNULL(O.IsObsolete,0) = 0
			GROUP BY OM.Id,OM.Title,ISM.Id,ISM.Title,ISM.InquiryMainStatusId,AI.OrgId
			UNION ALL
-- 111			
-- Refunded Fees
			SELECT 
			ISM.Id AS InquiryStatusId,
			ISNULL(OM.Id,0) AS OrgId,
			OM.Title AS Organization,
			ISNULL(ISM.Title,'') AS StatusName,
			(
			SELECT 
			ISNULL(COUNT(ISM.Id),0) AS StatusCount 
			FROM sAdmission.tAdmissionInquiry AI1 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI1.ForBatchId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
			LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AI1.OrgId = OM.Id
			LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI1.InquiryStatusId
			WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
			AND ISM.InquiryMainStatusId > 101

			--BM.IsActive = 1 
			AND OM.OrgGroupId = @rOrgGroupId  AND OM.Id = AI.OrgId
			) AS StatusCount  ,
			ISM.InquiryMainStatusId AS InquiryMainStatusId
			FROM sAdmission.tAdmissionInquiry AI 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForBatchId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
			
			LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AI.OrgId = OM.Id
			LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI.InquiryStatusId
			WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
			AND ISM.InquiryMainStatusId =111
 
			--BM.IsActive = 1 
			AND OM.OrgGroupId = @rOrgGroupId
			And ISNULL(O.IsObsolete,0) = 0
			GROUP BY OM.Id,OM.Title,ISM.Id,ISM.Title,ISM.InquiryMainStatusId,AI.OrgId
		 END
		 ELSE
		 BEGIN
			SELECT 
			ISM1.Id AS InquiryStatusId,
			ISNULL(OM.Id,0) AS OrgId,
			OM.Title AS Organization,
			ISNULL(ISM1.Title,'') AS StatusName,
			ISNULL(COUNT(ISM1.Id),0) AS StatusCount,
			ISNULL(ISM1.InquiryMainStatusId,0) AS InquiryMainStatusId
			,OM.OrderIndex
			FROM sAdmission.tAdmissionInquiry AI 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForBatchId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
			
			LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AI.OrgId = OM.Id
			LEFT JOIN sAdmission.tInquiryStatusMaster ISM1 ON ISM1.Id = AI.InquiryStatusId
			WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
			--AND ISM.InquiryMainStatusId = 11
			--BM.IsActive = 1 
			AND OM.OrgGroupId = @rOrgGroupId
			And ISNULL(O.IsObsolete,0) = 0
			
			GROUP BY OM.Id,OM.Title,ISM1.Id,ISM1.Title,ISM1.InquiryMainStatusId,AI.OrgId,OM.OrderIndex
			ORDER BY OM.OrderIndex
		 END
		END

	IF(@rType='StatusClassWise')
		BEGIN
				IF(@lConfigValue = 'True')
				BEGIN

				DECLARE @lInquiryMainStatus nvarchar(500)='' 
				IF(@rInquiryMainStatus=11)
				SET  @lInquiryMainStatus = 'AND ISM.InquiryMainStatusId >= 11'
				ELSE IF(@rInquiryMainStatus=21)
				SET  @lInquiryMainStatus = 'AND ISM.InquiryMainStatusId > 11'
				ELSE IF(@rInquiryMainStatus=31)
				SET  @lInquiryMainStatus ='AND ISM.InquiryMainStatusId > 21'
				ELSE IF(@rInquiryMainStatus=41)
				SET  @lInquiryMainStatus ='AND ISM.InquiryMainStatusId > 31'
				ELSE IF(@rInquiryMainStatus=51)
				SET  @lInquiryMainStatus ='AND ISM.InquiryMainStatusId > 41 and ISM.InquiryMainStatusId <> 61'
				ELSE IF(@rInquiryMainStatus=61)
				SET  @lInquiryMainStatus ='AND ISM.InquiryMainStatusId = 61 '
				ELSE IF(@rInquiryMainStatus=71)
				SET  @lInquiryMainStatus ='AND ISM.InquiryMainStatusId > 61'
				ELSE IF(@rInquiryMainStatus=81)
				SET  @lInquiryMainStatus ='AND ISM.InquiryMainStatusId = 81'
				ELSE IF(@rInquiryMainStatus=91)
				SET  @lInquiryMainStatus ='AND ISM.InquiryMainStatusId > 81 AND ISM.InquiryMainStatusId !=101'
				ELSE IF(@rInquiryMainStatus=101)
				SET  @lInquiryMainStatus ='AND ISM.InquiryMainStatusId = 101'
				ELSE IF(@rInquiryMainStatus=111)
				SET  @lInquiryMainStatus ='AND ISM.InquiryMainStatusId > 101'


				DECLARE @lSQLString nvarchar(max)=''

				SET @lSQLString = 'DECLARE @lTempOrgBatchOrder TABLE( OrgId int, BatchOrderIndex int)
						INSERT INTO @lTempOrgBatchOrder ( OrgId,BatchOrderIndex )
						SELECT OM.Id AS OrgId, MAX(BM.OrderIndex) AS BatchOrderIndex
						FROM
							sSetup.tOrganizationMaster OM
							INNER JOIN sSetup.tBatchMaster BM ON BM.OrgId = OM.Id
							INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
							INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
						WHERE 
							((OM.OrgGroupId='+CONVERT(nvarchar(20),@rOrgGroupId)+') OR ('+CONVERT(nvarchar(20),@rOrgGroupId)+' = 0))
							AND BM.IsObsolete = 0  AND COGBM.Id='+CONVERT(nvarchar(20),@rCommonOrgGroupBatchId)+'
						GROUP BY
							OM.Id
		
						DECLARE @lTempBatchId TABLE(OrgId int, BatchId int)
						INSERT INTO @lTempBatchId (OrgId , BatchId)
						SELECT 
							BM.OrgId AS OrgId,
							BM.Id AS BatchId
						FROM 
							sSetup.tBatchMaster BM
							INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
							INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
		 
							INNER JOIN @lTempOrgBatchOrder BO ON BO.OrgId = BM.OrgId
						WHERE
							BO.BatchOrderIndex = BM.OrderIndex  AND COGBM.Id='+CONVERT(nvarchar(20),@rCommonOrgGroupBatchId)+'

						SELECT 
							AI2.ForClassId AS ClassId,CM.Title AS ClassName,CM.OrderIndex,
							(SELECT ISNULL(COUNT(ISM.Id),0) AS StatusCount 
							FROM sAdmission.tAdmissionInquiry AI 
							INNER JOIN sSetup.tClassMaster CM ON CM.Id = AI.ForClassId
							INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForBatchId
							INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
							INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
							INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
							LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
							INNER JOIN sSetup.tOrganizationMaster OM ON AI.OrgId = OM.Id
							LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI.InquiryStatusId
							WHERE BM.Id = TB.BatchId AND COGBM.Id='+CONVERT(nvarchar(20),@rCommonOrgGroupBatchId)+'
								'+CONVERT(nvarchar(500),@lInquiryMainStatus)+' and AI2.ForClassId = CM.Id
							--BM.IsActive = 1 And ISNULL(O.IsObsolete,0) = 0
							AND ((OM.OrgGroupId = '+CONVERT(nvarchar(20),@rOrgGroupId)+' )OR('+CONVERT(nvarchar(20),@rOrgGroupId)+'=0)))
							AS StatusCount
						FROM 
							sAdmission.tAdmissionInquiry AI2
							INNER JOIN sSetup.tClassMaster CM ON CM.Id = AI2.ForClassId
							INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI2.ForBatchId
							LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
							LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI2.InquiryStatusId
						WHERE BM.Id = TB.BatchId 
						--and OM.OrgId = @rOrgId
							--and Ai2.ForClassId = CM.Id
							--AND COGBM.Id=1
							AND ((CM.OrgId = '+CONVERT(nvarchar(20),@rOrgId)+' )OR('+CONVERT(nvarchar(20),@rOrgId)+'=0))
							'+CONVERT(nvarchar(500),@lInquiryMainStatus)+'
						Group BY 
							AI2.ForClassId,CM.Title,CM.OrderIndex '

						print @lSQLString

						execute(@lSQLString)
				END
				ELSE 
				BEGIN
						DECLARE @lSQLString1 nvarchar(max)=''

						SET @lSQLString1 = 'DECLARE @lTempOrgBatchOrder TABLE( OrgId int, BatchOrderIndex int)
						INSERT INTO @lTempOrgBatchOrder ( OrgId,BatchOrderIndex )
						SELECT OM.Id AS OrgId, MAX(BM.OrderIndex) AS BatchOrderIndex
						FROM
							sSetup.tOrganizationMaster OM
							INNER JOIN sSetup.tBatchMaster BM ON BM.OrgId = OM.Id
							INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
							INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
						WHERE 
							((OM.OrgGroupId='+CONVERT(nvarchar(20),@rOrgGroupId)+') OR ('+CONVERT(nvarchar(20),@rOrgGroupId)+' = 0))
							AND BM.IsObsolete = 0  AND COGBM.Id='+CONVERT(nvarchar(20),@rCommonOrgGroupBatchId)+'
						GROUP BY
							OM.Id
		
						DECLARE @lTempBatchId TABLE(OrgId int, BatchId int)
						INSERT INTO @lTempBatchId (OrgId , BatchId)
						SELECT 
							BM.OrgId AS OrgId,
							BM.Id AS BatchId
						FROM 
							sSetup.tBatchMaster BM
							INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
							INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
		 
							INNER JOIN @lTempOrgBatchOrder BO ON BO.OrgId = BM.OrgId
						WHERE
							BO.BatchOrderIndex = BM.OrderIndex  AND COGBM.Id='+CONVERT(nvarchar(20),@rCommonOrgGroupBatchId)+'

						SELECT 
							AI2.ForClassId AS ClassId,CM.Title AS ClassName,CM.OrderIndex,
							(SELECT ISNULL(COUNT(ISM.Id),0) AS StatusCount 
							FROM sAdmission.tAdmissionInquiry AI 
							INNER JOIN sSetup.tClassMaster CM ON CM.Id = AI.ForClassId
							INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForBatchId
							INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
							INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
							INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
							LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
							INNER JOIN sSetup.tOrganizationMaster OM ON AI.OrgId = OM.Id
							LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI.InquiryStatusId
							WHERE BM.Id = TB.BatchId AND COGBM.Id='+CONVERT(nvarchar(20),@rCommonOrgGroupBatchId)+'
								and ISM.InquiryMainStatusId = ISM1.InquiryMainStatusId and AI2.ForClassId = CM.Id
							--BM.IsActive = 1 And ISNULL(O.IsObsolete,0) = 0
							AND ((OM.OrgGroupId = '+CONVERT(nvarchar(20),@rOrgGroupId)+' )OR('+CONVERT(nvarchar(20),@rOrgGroupId)+'=0)))
							AS StatusCount
						FROM 
							sAdmission.tAdmissionInquiry AI2
							INNER JOIN sSetup.tClassMaster CM ON CM.Id = AI2.ForClassId
							INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI2.ForBatchId
							LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
							LEFT JOIN sAdmission.tInquiryStatusMaster ISM1 ON ISM1.Id = AI2.InquiryStatusId
						WHERE BM.Id = TB.BatchId 
						--and OM.OrgId = @rOrgId
							--and Ai2.ForClassId = CM.Id
							--AND COGBM.Id=1
							AND ISM1.InquiryMainStatusId  = '+CONVERT(nvarchar(20),@rInquiryMainStatus)+'
							AND ((CM.OrgId = '+CONVERT(nvarchar(20),@rOrgId)+' )OR('+CONVERT(nvarchar(20),@rOrgId)+'=0))
						Group BY 
							AI2.ForClassId,CM.Title,CM.OrderIndex,ISM1.InquiryMainStatusId'

						print @lSQLString1

						execute(@lSQLString1)
				END
			END

	ELSE IF(@rType='StatusStudentList')
		BEGIN
				IF(@lConfigValue = 'True')
				BEGIN

				DECLARE @lInquiryMainStatusStudent nvarchar(500)='' 
				IF(@rInquiryMainStatus=11)
				SET  @lInquiryMainStatusStudent = 'AND ISM.InquiryMainStatusId >=11'
				ELSE IF(@rInquiryMainStatus=21)
				SET  @lInquiryMainStatusStudent = 'AND ISM.InquiryMainStatusId > 11'
				ELSE IF(@rInquiryMainStatus=31)
				SET  @lInquiryMainStatusStudent ='AND ISM.InquiryMainStatusId > 21'
				ELSE IF(@rInquiryMainStatus=41)
				SET  @lInquiryMainStatusStudent ='AND ISM.InquiryMainStatusId > 31'
				ELSE IF(@rInquiryMainStatus=51)
				SET  @lInquiryMainStatusStudent ='AND ISM.InquiryMainStatusId > 41 and ISM.InquiryMainStatusId <> 61'
				ELSE IF(@rInquiryMainStatus=61)
				SET  @lInquiryMainStatusStudent ='AND ISM.InquiryMainStatusId > 51 AND ISM.InquiryMainStatusId !=71'
				ELSE IF(@rInquiryMainStatus=71)
				SET  @lInquiryMainStatusStudent ='AND ISM.InquiryMainStatusId > 61'
				ELSE IF(@rInquiryMainStatus=81)
				SET  @lInquiryMainStatusStudent ='AND ISM.InquiryMainStatusId > 71 AND ISM.InquiryMainStatusId !=91'
				ELSE IF(@rInquiryMainStatus=91)
				SET  @lInquiryMainStatusStudent ='AND ISM.InquiryMainStatusId > 81 AND ISM.InquiryMainStatusId !=101'
				ELSE IF(@rInquiryMainStatus=101)
				SET  @lInquiryMainStatusStudent ='AND ISM.InquiryMainStatusId > 91 AND ISM.InquiryMainStatusId !=111'
				ELSE IF(@rInquiryMainStatus=111)
				SET  @lInquiryMainStatusStudent ='AND ISM.InquiryMainStatusId > 101'


				DECLARE @lSQLStduentList nvarchar(max)=''

				SET @lSQLStduentList = 'DECLARE @lTempOrgBatchOrder TABLE( OrgId int, BatchOrderIndex int)
						INSERT INTO @lTempOrgBatchOrder ( OrgId,BatchOrderIndex )
						SELECT OM.Id AS OrgId, MAX(BM.OrderIndex) AS BatchOrderIndex
						FROM
							sSetup.tOrganizationMaster OM
							INNER JOIN sSetup.tBatchMaster BM ON BM.OrgId = OM.Id
							INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
							INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
						WHERE 
							((OM.OrgGroupId='+CONVERT(nvarchar(20),@rOrgGroupId)+') OR ('+CONVERT(nvarchar(20),@rOrgGroupId)+' = 0))
							AND BM.IsObsolete = 0 AND COGBM.Id='+CONVERT(nvarchar(20),@rCommonOrgGroupBatchId)+'
						GROUP BY
							OM.Id
		
						DECLARE @lTempBatchId TABLE(OrgId int, BatchId int)
						INSERT INTO @lTempBatchId (OrgId , BatchId)
						SELECT 
							BM.OrgId AS OrgId,
							BM.Id AS BatchId
						FROM 
							sSetup.tBatchMaster BM
							INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
							INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
							--INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
							INNER JOIN @lTempOrgBatchOrder BO ON BO.OrgId = BM.OrgId
						WHERE
							BO.BatchOrderIndex = BM.OrderIndex  AND COGBM.Id='+CONVERT(nvarchar(20),@rCommonOrgGroupBatchId)+'
		
		
							SELECT AI.Number As InquiryId, AI.FirstName+ SPACE(1) +AI.MiddleName +SPACE(1) +AI.LastName AS StudentName,AI.ContactNo AS ContactNo FROM 
								sAdmission.tAdmissionInquiry AI 
								INNER JOIN sSetup.tClassMaster CM ON CM.Id = AI.ForClassId
								INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForBatchId
								INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
								INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
								INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
			
				
								LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
								INNER JOIN sSetup.tOrganizationMaster OM ON AI.OrgId = OM.Id
								LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI.InquiryStatusId --AND((ISM.Id = '+CONVERT(nvarchar(20),@rInquiryStatusId)+')OR('+CONVERT(nvarchar(20),@rInquiryStatusId)+'=0))
								WHERE BM.Id = TB.BatchId AND COGBM.Id='+CONVERT(nvarchar(20),@rCommonOrgGroupBatchId)+'
								'+CONVERT(nvarchar(500),@lInquiryMainStatusStudent)+'
								AND ((OM.OrgGroupId = '+CONVERT(nvarchar(20),@rOrgGroupId)+' )OR('+CONVERT(nvarchar(20),@rOrgGroupId)+'=0)) 
			
								AND((CM.OrgId = '+CONVERT(nvarchar(20),@rOrgId)+')OR('+CONVERT(nvarchar(20),@rOrgId)+'=0))
								AND((CM.Id ='+CONVERT(nvarchar(20),@rClassId)+' )OR('+CONVERT(nvarchar(20),@rClassId)+'=0))
								GROUP BY AI.FirstName,AI.MiddleName,AI.LastName,AI.ContactNo,AI.Number'

					--print @lSQLStduentList

					execute(@lSQLStduentList)

					END
					ELSE
					BEGIN	
						DECLARE @lSQLStduentList1 nvarchar(max)=''

						SET @lSQLStduentList1 = 'DECLARE @lTempOrgBatchOrder TABLE( OrgId int, BatchOrderIndex int)
								INSERT INTO @lTempOrgBatchOrder ( OrgId,BatchOrderIndex )
								SELECT OM.Id AS OrgId, MAX(BM.OrderIndex) AS BatchOrderIndex
								FROM
									sSetup.tOrganizationMaster OM
									INNER JOIN sSetup.tBatchMaster BM ON BM.OrgId = OM.Id
									INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
									INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
								WHERE 
									((OM.OrgGroupId='+CONVERT(nvarchar(20),@rOrgGroupId)+') OR ('+CONVERT(nvarchar(20),@rOrgGroupId)+' = 0))
									AND BM.IsObsolete = 0 AND COGBM.Id='+CONVERT(nvarchar(20),@rCommonOrgGroupBatchId)+'
								GROUP BY
									OM.Id
		
								DECLARE @lTempBatchId TABLE(OrgId int, BatchId int)
								INSERT INTO @lTempBatchId (OrgId , BatchId)
								SELECT 
									BM.OrgId AS OrgId,
									BM.Id AS BatchId
								FROM 
									sSetup.tBatchMaster BM
									INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
									INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
									--INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
									INNER JOIN @lTempOrgBatchOrder BO ON BO.OrgId = BM.OrgId
								WHERE
									BO.BatchOrderIndex = BM.OrderIndex  AND COGBM.Id='+CONVERT(nvarchar(20),@rCommonOrgGroupBatchId)+'
		
		
									SELECT AI.Number As InquiryId, AI.FirstName+ SPACE(1) +AI.MiddleName +SPACE(1) +AI.LastName AS StudentName,AI.ContactNo AS ContactNo FROM 
										sAdmission.tAdmissionInquiry AI 
										INNER JOIN sSetup.tClassMaster CM ON CM.Id = AI.ForClassId
										INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForBatchId
										INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
										INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
										INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
			
				
										LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
										INNER JOIN sSetup.tOrganizationMaster OM ON AI.OrgId = OM.Id
										LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI.InquiryStatusId --AND((ISM.Id = '+CONVERT(nvarchar(20),@rInquiryStatusId)+')OR('+CONVERT(nvarchar(20),@rInquiryStatusId)+'=0))
										WHERE BM.Id = TB.BatchId AND COGBM.Id='+CONVERT(nvarchar(20),@rCommonOrgGroupBatchId)+'
										 AND ISM.InquiryMainStatusId = '+CONVERT(nvarchar(20),@rInquiryMainStatus)+'
										AND ((OM.OrgGroupId = '+CONVERT(nvarchar(20),@rOrgGroupId)+' )OR('+CONVERT(nvarchar(20),@rOrgGroupId)+'=0)) 
			
										AND((CM.OrgId = '+CONVERT(nvarchar(20),@rOrgId)+')OR('+CONVERT(nvarchar(20),@rOrgId)+'=0))
										AND((CM.Id ='+CONVERT(nvarchar(20),@rClassId)+' )OR('+CONVERT(nvarchar(20),@rClassId)+'=0))
										GROUP BY AI.FirstName,AI.MiddleName,AI.LastName,AI.ContactNo,AI.Number'

					print @lSQLStduentList1

						execute(@lSQLStduentList1)
			END
		END

    ELSE IF(@rType='NotDoneStatusClassWise')
		BEGIN
				IF(@lConfigValue = 'True')
				BEGIN

				DECLARE @lInqMainStatus nvarchar(500)='' 
				SET  @lInqMainStatus = 'AND ISM.Id =' + CONVERT(nvarchar,@rInquiryStatusId)
				--IF(@rInquiryMainStatus=11)
				--SET  @lInquiryMainStatus = 'AND ISM.InquiryMainStatusId >= 11'
				--ELSE IF(@rInquiryMainStatus=21)
				--SET  @lInquiryMainStatus = 'AND ISM.InquiryMainStatusId > 11'
				--ELSE IF(@rInquiryMainStatus=31)
				--SET  @lInquiryMainStatus ='AND ISM.InquiryMainStatusId > 21'
				--ELSE IF(@rInquiryMainStatus=41)
				--SET  @lInquiryMainStatus ='AND ISM.InquiryMainStatusId > 31'
				--ELSE IF(@rInquiryMainStatus=51)
				--SET  @lInquiryMainStatus ='AND ISM.InquiryMainStatusId > 41 and ISM.InquiryMainStatusId <> 61'
				--ELSE IF(@rInquiryMainStatus=61)
				--SET  @lInquiryMainStatus ='AND ISM.InquiryMainStatusId = 61 '
				--ELSE IF(@rInquiryMainStatus=71)
				--SET  @lInquiryMainStatus ='AND ISM.InquiryMainStatusId > 61'
				--ELSE IF(@rInquiryMainStatus=81)
				--SET  @lInquiryMainStatus ='AND ISM.InquiryMainStatusId = 81'
				--ELSE IF(@rInquiryMainStatus=91)
				--SET  @lInquiryMainStatus ='AND ISM.InquiryMainStatusId > 81 AND ISM.InquiryMainStatusId !=101'
				--ELSE IF(@rInquiryMainStatus=101)
				--SET  @lInquiryMainStatus ='AND ISM.InquiryMainStatusId = 101'
				--ELSE IF(@rInquiryMainStatus=111)
				--SET  @lInquiryMainStatus ='AND ISM.InquiryMainStatusId > 101'


				DECLARE @lSQLString3 nvarchar(max)=''

				SET @lSQLString3 = 'DECLARE @lTempOrgBatchOrder TABLE( OrgId int, BatchOrderIndex int)
						INSERT INTO @lTempOrgBatchOrder ( OrgId,BatchOrderIndex )
						SELECT OM.Id AS OrgId, MAX(BM.OrderIndex) AS BatchOrderIndex
						FROM
							sSetup.tOrganizationMaster OM
							INNER JOIN sSetup.tBatchMaster BM ON BM.OrgId = OM.Id
							INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
							INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
						WHERE 
							((OM.OrgGroupId='+CONVERT(nvarchar(20),@rOrgGroupId)+') OR ('+CONVERT(nvarchar(20),@rOrgGroupId)+' = 0))
							AND BM.IsObsolete = 0  AND COGBM.Id='+CONVERT(nvarchar(20),@rCommonOrgGroupBatchId)+'
						GROUP BY
							OM.Id
		
						DECLARE @lTempBatchId TABLE(OrgId int, BatchId int)
						INSERT INTO @lTempBatchId (OrgId , BatchId)
						SELECT 
							BM.OrgId AS OrgId,
							BM.Id AS BatchId
						FROM 
							sSetup.tBatchMaster BM
							INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
							INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
		 
							INNER JOIN @lTempOrgBatchOrder BO ON BO.OrgId = BM.OrgId
						WHERE
							BO.BatchOrderIndex = BM.OrderIndex  AND COGBM.Id='+CONVERT(nvarchar(20),@rCommonOrgGroupBatchId)+'

						SELECT 
							AI2.ForClassId AS ClassId,CM.Title AS ClassName,CM.OrderIndex,
							(SELECT ISNULL(COUNT(ISM.Id),0) AS StatusCount 
							FROM sAdmission.tAdmissionInquiry AI 
							INNER JOIN sSetup.tClassMaster CM ON CM.Id = AI.ForClassId
							INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForBatchId
							INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
							INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
							INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
							LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
							INNER JOIN sSetup.tOrganizationMaster OM ON AI.OrgId = OM.Id
							LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI.InquiryStatusId
							WHERE BM.Id = TB.BatchId AND COGBM.Id='+CONVERT(nvarchar(20),@rCommonOrgGroupBatchId)+'
								'+CONVERT(nvarchar(500),@lInqMainStatus)+' and AI2.ForClassId = CM.Id
							--BM.IsActive = 1 And ISNULL(O.IsObsolete,0) = 0
							AND ((OM.OrgGroupId = '+CONVERT(nvarchar(20),@rOrgGroupId)+' )OR('+CONVERT(nvarchar(20),@rOrgGroupId)+'=0)))
							AS StatusCount
						FROM 
							sAdmission.tAdmissionInquiry AI2
							INNER JOIN sSetup.tClassMaster CM ON CM.Id = AI2.ForClassId
							INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI2.ForBatchId
							LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
							LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI2.InquiryStatusId
						WHERE BM.Id = TB.BatchId 
						--and OM.OrgId = @rOrgId
							--and Ai2.ForClassId = CM.Id
							--AND COGBM.Id=1
							AND ((CM.OrgId = '+CONVERT(nvarchar(20),@rOrgId)+' )OR('+CONVERT(nvarchar(20),@rOrgId)+'=0))
							'+CONVERT(nvarchar(500),@lInqMainStatus)+'
						Group BY 
							AI2.ForClassId,CM.Title,CM.OrderIndex '

						print @lSQLString3

						execute(@lSQLString3)
				END
				ELSE 
				BEGIN
						DECLARE @lSQLString4 nvarchar(max)=''

						SET @lSQLString4 = 'DECLARE @lTempOrgBatchOrder TABLE( OrgId int, BatchOrderIndex int)
						INSERT INTO @lTempOrgBatchOrder ( OrgId,BatchOrderIndex )
						SELECT OM.Id AS OrgId, MAX(BM.OrderIndex) AS BatchOrderIndex
						FROM
							sSetup.tOrganizationMaster OM
							INNER JOIN sSetup.tBatchMaster BM ON BM.OrgId = OM.Id
							INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
							INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
						WHERE 
							((OM.OrgGroupId='+CONVERT(nvarchar(20),@rOrgGroupId)+') OR ('+CONVERT(nvarchar(20),@rOrgGroupId)+' = 0))
							AND BM.IsObsolete = 0  AND COGBM.Id='+CONVERT(nvarchar(20),@rCommonOrgGroupBatchId)+'
						GROUP BY
							OM.Id
		
						DECLARE @lTempBatchId TABLE(OrgId int, BatchId int)
						INSERT INTO @lTempBatchId (OrgId , BatchId)
						SELECT 
							BM.OrgId AS OrgId,
							BM.Id AS BatchId
						FROM 
							sSetup.tBatchMaster BM
							INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
							INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
		 
							INNER JOIN @lTempOrgBatchOrder BO ON BO.OrgId = BM.OrgId
						WHERE
							BO.BatchOrderIndex = BM.OrderIndex  AND COGBM.Id='+CONVERT(nvarchar(20),@rCommonOrgGroupBatchId)+'

						SELECT 
							AI2.ForClassId AS ClassId,CM.Title AS ClassName,CM.OrderIndex,
							(SELECT ISNULL(COUNT(ISM.Id),0) AS StatusCount 
							FROM sAdmission.tAdmissionInquiry AI 
							INNER JOIN sSetup.tClassMaster CM ON CM.Id = AI.ForClassId
							INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForBatchId
							INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
							INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
							INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
							LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
							INNER JOIN sSetup.tOrganizationMaster OM ON AI.OrgId = OM.Id
							LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI.InquiryStatusId
							WHERE BM.Id = TB.BatchId AND COGBM.Id='+CONVERT(nvarchar(20),@rCommonOrgGroupBatchId)+'
								and ISM.InquiryMainStatusId = ISM1.InquiryMainStatusId and AI2.ForClassId = CM.Id
							--BM.IsActive = 1 And ISNULL(O.IsObsolete,0) = 0
							AND ((OM.OrgGroupId = '+CONVERT(nvarchar(20),@rOrgGroupId)+' )OR('+CONVERT(nvarchar(20),@rOrgGroupId)+'=0)))
							AS StatusCount
						FROM 
							sAdmission.tAdmissionInquiry AI2
							INNER JOIN sSetup.tClassMaster CM ON CM.Id = AI2.ForClassId
							INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI2.ForBatchId
							LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
							LEFT JOIN sAdmission.tInquiryStatusMaster ISM1 ON ISM1.Id = AI2.InquiryStatusId
						WHERE BM.Id = TB.BatchId 
						--and OM.OrgId = @rOrgId
							--and Ai2.ForClassId = CM.Id
							--AND COGBM.Id=1
							AND ISM1.InquiryMainStatusId  = '+CONVERT(nvarchar(20),@rInquiryMainStatus)+'
							AND ((CM.OrgId = '+CONVERT(nvarchar(20),@rOrgId)+' )OR('+CONVERT(nvarchar(20),@rOrgId)+'=0))
						Group BY 
							AI2.ForClassId,CM.Title,CM.OrderIndex,ISM1.InquiryMainStatusId'

						print @lSQLString4

						execute(@lSQLString4)
				END
			END

	ELSE IF(@rType='NotDoneStatusStudentList')
		BEGIN
				IF(@lConfigValue = 'True')
				BEGIN

				DECLARE @lInqMainStatusStudent nvarchar(500)='' 
				 
				SET  @lInqMainStatusStudent = 'AND ISM.Id =' + CONVERT(nvarchar,@rInquiryStatusId)
				--IF(@rInquiryMainStatus=11)
				--SET  @lInquiryMainStatusStudent = 'AND ISM.InquiryMainStatusId >=11'
				--ELSE IF(@rInquiryMainStatus=21)
				--SET  @lInquiryMainStatusStudent = 'AND ISM.InquiryMainStatusId > 11'
				--ELSE IF(@rInquiryMainStatus=31)
				--SET  @lInquiryMainStatusStudent ='AND ISM.InquiryMainStatusId > 21'
				--ELSE IF(@rInquiryMainStatus=41)
				--SET  @lInquiryMainStatusStudent ='AND ISM.InquiryMainStatusId > 31'
				--ELSE IF(@rInquiryMainStatus=51)
				--SET  @lInquiryMainStatusStudent ='AND ISM.InquiryMainStatusId > 41 and ISM.InquiryMainStatusId <> 61'
				--ELSE IF(@rInquiryMainStatus=61)
				--SET  @lInquiryMainStatusStudent ='AND ISM.InquiryMainStatusId > 51 AND ISM.InquiryMainStatusId !=71'
				--ELSE IF(@rInquiryMainStatus=71)
				--SET  @lInquiryMainStatusStudent ='AND ISM.InquiryMainStatusId > 61'
				--ELSE IF(@rInquiryMainStatus=81)
				--SET  @lInquiryMainStatusStudent ='AND ISM.InquiryMainStatusId > 71 AND ISM.InquiryMainStatusId !=91'
				--ELSE IF(@rInquiryMainStatus=91)
				--SET  @lInquiryMainStatusStudent ='AND ISM.InquiryMainStatusId > 81 AND ISM.InquiryMainStatusId !=101'
				--ELSE IF(@rInquiryMainStatus=101)
				--SET  @lInquiryMainStatusStudent ='AND ISM.InquiryMainStatusId > 91 AND ISM.InquiryMainStatusId !=111'
				--ELSE IF(@rInquiryMainStatus=111)
				--SET  @lInquiryMainStatusStudent ='AND ISM.InquiryMainStatusId > 101'


				DECLARE @lSQLStduentList3 nvarchar(max)=''

				SET @lSQLStduentList3 = 'DECLARE @lTempOrgBatchOrder TABLE( OrgId int, BatchOrderIndex int)
						INSERT INTO @lTempOrgBatchOrder ( OrgId,BatchOrderIndex )
						SELECT OM.Id AS OrgId, MAX(BM.OrderIndex) AS BatchOrderIndex
						FROM
							sSetup.tOrganizationMaster OM
							INNER JOIN sSetup.tBatchMaster BM ON BM.OrgId = OM.Id
							INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
							INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
						WHERE 
							((OM.OrgGroupId='+CONVERT(nvarchar(20),@rOrgGroupId)+') OR ('+CONVERT(nvarchar(20),@rOrgGroupId)+' = 0))
							AND BM.IsObsolete = 0 AND COGBM.Id='+CONVERT(nvarchar(20),@rCommonOrgGroupBatchId)+'
						GROUP BY
							OM.Id
		
						DECLARE @lTempBatchId TABLE(OrgId int, BatchId int)
						INSERT INTO @lTempBatchId (OrgId , BatchId)
						SELECT 
							BM.OrgId AS OrgId,
							BM.Id AS BatchId
						FROM 
							sSetup.tBatchMaster BM
							INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
							INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
							--INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
							INNER JOIN @lTempOrgBatchOrder BO ON BO.OrgId = BM.OrgId
						WHERE
							BO.BatchOrderIndex = BM.OrderIndex  AND COGBM.Id='+CONVERT(nvarchar(20),@rCommonOrgGroupBatchId)+'
		
		
							SELECT AI.Number As InquiryId, AI.FirstName+ SPACE(1) +AI.MiddleName +SPACE(1) +AI.LastName AS StudentName,AI.ContactNo AS ContactNo FROM 
								sAdmission.tAdmissionInquiry AI 
								INNER JOIN sSetup.tClassMaster CM ON CM.Id = AI.ForClassId
								INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForBatchId
								INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
								INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
								INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
			
				
								LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
								INNER JOIN sSetup.tOrganizationMaster OM ON AI.OrgId = OM.Id
								LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI.InquiryStatusId --AND((ISM.Id = '+CONVERT(nvarchar(20),@rInquiryStatusId)+')OR('+CONVERT(nvarchar(20),@rInquiryStatusId)+'=0))
								WHERE BM.Id = TB.BatchId AND COGBM.Id='+CONVERT(nvarchar(20),@rCommonOrgGroupBatchId)+'
								'+CONVERT(nvarchar(500),@lInqMainStatusStudent)+'
								AND ((OM.OrgGroupId = '+CONVERT(nvarchar(20),@rOrgGroupId)+' )OR('+CONVERT(nvarchar(20),@rOrgGroupId)+'=0)) 
			
								AND((CM.OrgId = '+CONVERT(nvarchar(20),@rOrgId)+')OR('+CONVERT(nvarchar(20),@rOrgId)+'=0))
								AND((CM.Id ='+CONVERT(nvarchar(20),@rClassId)+' )OR('+CONVERT(nvarchar(20),@rClassId)+'=0))
								GROUP BY AI.FirstName,AI.MiddleName,AI.LastName,AI.ContactNo,AI.Number'

					--print @lSQLStduentList

					execute(@lSQLStduentList3)

					END
					ELSE
					BEGIN	
						DECLARE @lSQLStduentList4 nvarchar(max)=''

						SET @lSQLStduentList4 = 'DECLARE @lTempOrgBatchOrder TABLE( OrgId int, BatchOrderIndex int)
								INSERT INTO @lTempOrgBatchOrder ( OrgId,BatchOrderIndex )
								SELECT OM.Id AS OrgId, MAX(BM.OrderIndex) AS BatchOrderIndex
								FROM
									sSetup.tOrganizationMaster OM
									INNER JOIN sSetup.tBatchMaster BM ON BM.OrgId = OM.Id
									INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
									INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
								WHERE 
									((OM.OrgGroupId='+CONVERT(nvarchar(20),@rOrgGroupId)+') OR ('+CONVERT(nvarchar(20),@rOrgGroupId)+' = 0))
									AND BM.IsObsolete = 0 AND COGBM.Id='+CONVERT(nvarchar(20),@rCommonOrgGroupBatchId)+'
								GROUP BY
									OM.Id
		
								DECLARE @lTempBatchId TABLE(OrgId int, BatchId int)
								INSERT INTO @lTempBatchId (OrgId , BatchId)
								SELECT 
									BM.OrgId AS OrgId,
									BM.Id AS BatchId
								FROM 
									sSetup.tBatchMaster BM
									INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
									INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
									--INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
									INNER JOIN @lTempOrgBatchOrder BO ON BO.OrgId = BM.OrgId
								WHERE
									BO.BatchOrderIndex = BM.OrderIndex  AND COGBM.Id='+CONVERT(nvarchar(20),@rCommonOrgGroupBatchId)+'
		
		
									SELECT AI.Number As InquiryId, AI.FirstName+ SPACE(1) +AI.MiddleName +SPACE(1) +AI.LastName AS StudentName,AI.ContactNo AS ContactNo FROM 
										sAdmission.tAdmissionInquiry AI 
										INNER JOIN sSetup.tClassMaster CM ON CM.Id = AI.ForClassId
										INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForBatchId
										INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
										INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
										INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
			
				
										LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
										INNER JOIN sSetup.tOrganizationMaster OM ON AI.OrgId = OM.Id
										LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI.InquiryStatusId --AND((ISM.Id = '+CONVERT(nvarchar(20),@rInquiryStatusId)+')OR('+CONVERT(nvarchar(20),@rInquiryStatusId)+'=0))
										WHERE BM.Id = TB.BatchId AND COGBM.Id='+CONVERT(nvarchar(20),@rCommonOrgGroupBatchId)+'
										 AND ISM.InquiryMainStatusId = '+CONVERT(nvarchar(20),@rInquiryMainStatus)+'
										AND ((OM.OrgGroupId = '+CONVERT(nvarchar(20),@rOrgGroupId)+' )OR('+CONVERT(nvarchar(20),@rOrgGroupId)+'=0)) 
			
										AND((CM.OrgId = '+CONVERT(nvarchar(20),@rOrgId)+')OR('+CONVERT(nvarchar(20),@rOrgId)+'=0))
										AND((CM.Id ='+CONVERT(nvarchar(20),@rClassId)+' )OR('+CONVERT(nvarchar(20),@rClassId)+'=0))
										GROUP BY AI.FirstName,AI.MiddleName,AI.LastName,AI.ContactNo,AI.Number'

					print @lSQLStduentList4

						execute(@lSQLStduentList4)
			END
		END
	END


	-- For AdmissionConverted Tab
	IF(@rTypeId = 3)
	BEGIN
		IF(@rType='OrgGroupWise')
		BEGIN
			-- Organization wise Count
			SELECT OrgId, Organization, ISNULL(Inquiry, 0) AS InquiryCount, ISNULL(Form, 0) AS FormCount, (ISNULL([Converted Inquiry], 0) + ISNULL([Converted Form], 0)) AS ConvertedCount
			FROM  
			(
				SELECT 
					ISNULL(OM.Id,0) AS OrgId,
					OM.Title AS Organization,
					'Inquiry' AS Type,
					ISNULL(COUNT(AI.Id),0) AS Total
				FROM sAdmission.tAdmissionInquiry AI 
					INNER JOIN sAdmission.tInquiryStatusMaster SM ON SM.Id=AI.InquiryStatusId
					INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForBatchId
					INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
					INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
					INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
					LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
					INNER JOIN sSetup.tOrganizationMaster OM ON AI.OrgId = OM.Id
				WHERE 
					BM.Id = TB.BatchId 
					AND COGBM.Id=@rCommonOrgGroupBatchId
					--AND OM.OrgGroupId = @rOrgGroupId
					And ISNULL(O.IsObsolete,0) = 0
				GROUP BY OM.Id,OM.Title

				UNION ALL

				SELECT 
					OM.Id, 
					OM.Title AS Organization,
					'Form' AS Type,
					COUNT(AF.Id) AS Total
				FROM sAdmission.tAdmissionForm AF 
					INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AF.BatchId
					INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
					INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
					INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
					INNER JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
					INNER JOIN sSetup.tOrganizationMaster OM ON AF.OrgId = OM.Id
				WHERE
					BM.Id = TB.BatchId
					AND OM.OrgGroupId = @rOrgGroupId 
					AND COGBM.Id = @rCommonOrgGroupBatchId
					And ISNULL(O.IsObsolete,0) = 0
				GROUP BY OM.Id, OM.Title

				UNION ALL

				SELECT
					ISNULL(OM.Id,0) AS OrgId,
					OM.Title AS Organization,
					'Converted Inquiry' AS Type,
					COUNT(AI.Id) AS Total
				FROM sAdmission.tAdmissionInquiry AI
					INNER JOIN sAdmission.tInquiryStatusMaster SM ON SM.Id=AI.InquiryStatusId
					LEFT JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForBatchId
					LEFT JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
					LEFT JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
					LEFT JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
					LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
					LEFT JOIN sSetup.tOrganizationMaster OM ON AI.OrgId = OM.Id
					LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI.InquiryStatusId
				WHERE 
					BM.Id = TB.BatchId 
					AND COGBM.Id=@rCommonOrgGroupBatchId
					AND ISM.InquiryMainStatusId = 71
					--AND OM.OrgGroupId = @rOrgGroupId
					And ISNULL(O.IsObsolete,0) = 0
				GROUP BY OM.Id, OM.Title

				UNION ALL

				SELECT 
					OM.Id, 
					OM.Title AS Organization,
					'Converted Form' AS Type,
					COUNT(AF.Id) AS Total
				FROM sAdmission.tAdmissionForm AF 
					INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AF.BatchId
					INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
					INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
					INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
					INNER JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
					INNER JOIN sSetup.tOrganizationMaster OM ON AF.OrgId = OM.Id
				WHERE
					BM.Id = TB.BatchId
					AND OM.OrgGroupId = @rOrgGroupId 
					AND COGBM.Id = @rCommonOrgGroupBatchId
					And ISNULL(O.IsObsolete,0) = 0
					AND AF.StatusId = 208 --Closed
				GROUP BY OM.Id, OM.Title
			   ) AS A
				PIVOT  
				(SUM(Total) FOR [Type] IN ([Inquiry],[Form],[Converted Inquiry],[Converted Form])) AS A1
		END

		IF(@rType='ClassWise')
		BEGIN
			-- Class wise Count
			SELECT ClassId, ClassName, OrderIndex, ISNULL(Inquiry, 0) AS InquiryCount, ISNULL(Form, 0) AS FormCount,(ISNULL([Converted Inquiry], 0) + ISNULL([Converted Form], 0)) AS ConvertedCount
			FROM  
			(
				--Inquiry
				SELECT 
					AI.ForClassId AS ClassId, CM.Title AS ClassName, 'Inquiry' AS Type, ISNULL(COUNT(AI.Id),0) AS Total, CM.OrderIndex
				FROM sAdmission.tAdmissionInquiry AI
					INNER JOIN sAdmission.tInquiryStatusMaster SM ON SM.Id=AI.InquiryStatusId
					INNER JOIN sSetup.tClassMaster CM ON CM.Id = AI.ForClassId
					INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForBatchId
					LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
				WHERE 
					BM.Id = TB.BatchId 
					AND ((CM.OrgId = @rOrgId) OR (@rOrgId=0))				
				Group BY AI.ForClassId,CM.Title,CM.OrderIndex 

				UNION ALL 

				-- Form
				SELECT 
					CM.Id AS ClassId, CM.DisplayTitle AS ClassName, 'Form' AS Type, ISNULL(COUNT(AF.Id),0) AS Total, CM.OrderIndex 
				FROM sAdmission.tAdmissionForm AF 
					INNER JOIN sSetup.tClassMaster CM ON CM.Id = AF.ForClassId
					INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AF.BatchId
					INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
					INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
					INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
					INNER JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
					INNER JOIN sSetup.tOrganizationMaster OM ON AF.OrgId = OM.Id
				WHERE 
					BM.Id = TB.BatchId
					AND OM.OrgGroupId = 9911 AND COGBM.Id=@rCommonOrgGroupBatchId
					And ISNULL(O.IsObsolete,0) = 0
					AND ((CM.OrgId = @rOrgId) OR (@rOrgId=0))
				GROUP BY CM.Id,CM.DisplayTitle,CM.OrderIndex

				UNION ALL
				
				SELECT 
					AI.ForClassId AS ClassId, CM.Title AS ClassName, 'Converted Inquiry' AS Type, ISNULL(COUNT(AI.Id),0) AS Total, CM.OrderIndex
				FROM sAdmission.tAdmissionInquiry AI
					INNER JOIN sAdmission.tInquiryStatusMaster SM ON SM.Id=AI.InquiryStatusId
					INNER JOIN sSetup.tClassMaster CM ON CM.Id = AI.ForClassId
					INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForBatchId
					LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
					LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI.InquiryStatusId
				WHERE 
					BM.Id = TB.BatchId 
					AND ((CM.OrgId = @rOrgId )OR(@rOrgId=0))
					AND ISM.InquiryMainStatusId = 71			
				Group BY AI.ForClassId,CM.Title,CM.OrderIndex 

				UNION ALL

				SELECT 
					CM.Id AS ClassId, CM.DisplayTitle AS ClassName, 'Converted Form' AS Type, ISNULL(COUNT(AF.Id),0) AS Total, CM.OrderIndex 
				FROM sAdmission.tAdmissionForm AF 
					INNER JOIN sSetup.tClassMaster CM ON CM.Id = AF.ForClassId
					INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AF.BatchId
					INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
					INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
					INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
					INNER JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
					INNER JOIN sSetup.tOrganizationMaster OM ON AF.OrgId = OM.Id
				WHERE 
					BM.Id = TB.BatchId
					AND OM.OrgGroupId = @rOrgGroupId 
					AND COGBM.Id=@rCommonOrgGroupBatchId
					And ISNULL(O.IsObsolete,0) = 0
					AND AF.StatusId = 208 --Closed
					AND((CM.OrgId = @rOrgId)OR(@rOrgId=0))
				GROUP BY CM.Id,CM.DisplayTitle,CM.OrderIndex
			)  
			AS A
			PIVOT  
			(SUM(Total) FOR [Type] IN ([Inquiry],[Form],[Converted Inquiry],[Converted Form])) AS A2
		END
	END

END
GO
PRINT N'Altering [sAdmission].[pAdmissionInquiryAdd]...';


GO

ALTER PROCEDURE [sAdmission].[pAdmissionInquiryAdd]
		 @rId bigint
		,@rFirstName nvarchar(100)
		,@rMiddleName nvarchar(100)
		,@rLastName nvarchar(100)
		,@rForClassId int
		,@rForBatchId	int =0
		--,@rForBatch	nvarchar(20)
		,@rDateOfBirth date
		,@rOrgId smallint
		--,@rStatusId	smallint
		,@rInquiryStatusMasterId int
		,@rStreetOne nvarchar(50)
		,@rStreetTwo nvarchar(50)
		,@rStreetThree nvarchar(50)
		,@rCountry nvarchar(50)
		,@rState nvarchar(50)
		,@rCity	nvarchar(50)
		,@rZipCode nvarchar(20)
		,@rContactNo nvarchar(20)
		,@rContactEmail	nvarchar(50)
		,@rRemark nvarchar(200)
		,@rInquiryModeId tinyint
		,@rInquiryReferenceId int
		,@rAdmissionCategoryId int
		,@rPreviousSchool nvarchar(200)
		,@rMeritMarks decimal(10,2) 
		,@rMeritGrade nvarchar(20)
		,@rMeritMarksBreakup nvarchar(100)
		,@rGenderId tinyint
		,@rFollowupDate date
		,@rFollowupRemark nvarchar(150)
		,@rCreatedUserId bigint
		,@rInquiryDate date
		,@rNumber bigint 
		,@rHandledBy nvarchar(100) 
		,@rOrgGroupId int,
		@rCastCategoryId int=0,
		@rIsHostelRequired bit=0,
		@rIsTransportRequired bit=0,
		@rIsValidateInquiryAsPerAdmission bit=0,
		@rIsGivenAdmissionForm bit=0,
		@rAlternateContactNo nvarchar(100)='',
		@rAlternateContactEmail	nvarchar(200) = '',
		@rMotherName nvarchar(100)='',
		@rDataEntryModeId smallint = 562 ,
		@rMinorityStatusId smallint = 0,
		@rLiveWithId smallint = 0,
		@rAdhaarNumber nvarchar(20)='',
		@rBloodGroupId smallint = 0,
		@rFatherName nvarchar(100)='',
		@rFatherOccupation nvarchar(50)='',
		@rFatherIncome int = 0,
		@rFatherContactNo nvarchar(50)='',
		@rFatherMail nvarchar(50)='',
		@rFatherQualification nvarchar(50)='',
	    @rMotherOccupation nvarchar(50)='',
		@rMotherIncome int=0,
		@rMotherContactNo nvarchar(50)='',
		@rMotherMail nvarchar(50)='',
		@rMotherQualification nvarchar(50)='',
		@rStream nvarchar(20)='',
		@rBoard nvarchar(50)='' ,
		@rInquiryReferenceRemark nvarchar(200) = ''
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	DECLARE @lOrgGroupBatchId int=0
	
	SELECT @lOrgGroupBatchId=OrgGroupBatchId FROM sSetup.tBatchMaster BM WHERE BM.Id = @rForBatchId
	
	DECLARE @lConfigValue nvarchar(50)=''
	SELECT @lConfigValue = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 341 AND SourceTypeId = 2010 AND SourceId = @rOrgGroupId
	 
	DECLARE @lConfigValueForAdmissionNumber nvarchar(50)=''
	SELECT @lConfigValueForAdmissionNumber = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 462 AND SourceTypeId = 2010 AND SourceId = @rOrgGroupId 

	PRINT @lConfigValueForAdmissionNumber
	IF(@lConfigValueForAdmissionNumber = 'True')
	BEGIN
		PRINT 1
		IF(@lConfigValue='OrgGroupBatch')
		BEGIN
		PRINT 2
			SELECT @rNumber = (ISNULL(MAX(Number),0) + 1) FROM sAdmission.tAdmissionInquiry AI
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForbatchId 
			WHERE BM.OrgGroupBatchId = @lOrgGroupBatchId
		END
		ELSE IF(@lConfigValue='Batch')
		BEGIN
		PRINT 3
			SELECT @rNumber = (ISNULL(MAX(Number),0) + 1) FROM sAdmission.tAdmissionInquiry AI
			WHERE AI.ForBatchId = @rForBatchId
		END
		ELSE IF (@lConfigValue = 'Continuous')
		BEGIN
		PRINT 4
			SELECT @rNumber =(ISNULL(MAX(Number),0) + 1) FROM sAdmission.tAdmissionInquiry  
			WHERE OrgGroupId = @rOrgGroupId
		END
	END
	
	PRINT(@rNumber)

	Declare @lStatusId smallint,@lIsValidateBirthdate bit,@lFromDateOfBirth date,@lToDateOfBirth date
	SET @lStatusId= 0
	
	if(@rIsValidateInquiryAsPerAdmission=1)
	Begin
		Select @lIsValidateBirthdate=IsValidateBirthdate,@lFromDateOfBirth=FromDateOfBirth,@lToDateOfBirth=ToDateOfBirth from  sAdmission.tAdmissionCriteria where ClassId=@rForClassId AND BatchID=@rForBatchId
		
		if(@lIsValidateBirthdate=1 AND @rDateOfBirth NOT between @lFromDateOfBirth And @lToDateOfBirth)
		BEGIN
			Select  -101 AS Result
			return
		End
	End
	 
 BEGIN TRANSACTION	
IF(@rId = 0)	
	BEGIN	

 DECLARE @lNextNumber BIGINT 
 EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sAdmission.tAdmissionInquiry', 0, 1, 1,@outNextNumber = @lNextNumber output
			
	INSERT INTO sAdmission.tAdmissionInquiry
		(
			 Id
			,FirstName
			,MiddleName
			,LastName
			,ForClassId			 
			,ForBatchId
			,DateOfBirth
			,OrgId
			,StatusId
			,StreetOne
			,StreetTwo
			,StreetThree
			,Country
			,State
			,City
			,ZipCode
			,ContactNo
			,ContactEmail
			,Remark
			,InquiryModeId
			,InquiryReferenceId
			,AdmissionCategoryId
			,PreviousSchool
			,MeritMarks
			,MeritGrade
			,MeritMarksBreakup
			,GenderId
			,FollowupDate
			,FollowupRemark
			,CreatedUserId
			,CreatedDateTime
			,InquiryDate
			,Number
			,HandledBy
			,OrgGroupId
			,InquiryStatusId,
			CastCategoryId,
			IsHostelRequired,
			IsTransportRequired,
			IsGivenAdmissionForm,
			AlternateContactNo,
			AlternateContactEmail,
			MotherName,
			DataEntryModeId
			,MinorityStatusId 
		    ,LiveWithId
			,AdhaarNumber
			,BloodGroupId
			,FatherName
			,FatherOccupation
			,FatherIncome
			,FatherContactNo
			,FatherMail
			,FatherQualification
			,MotherOccupation
			,MotherIncome
			,MotherContactNo
			,MotherMail
			,MotherQualification
			,Stream
			,Board
			,InquiryReferenceRemark
		)
	VALUES
		(
			 @lNextNumber
			,@rFirstName
			,@rMiddleName
			,@rLastName
			,@rForClassId
			,@rForBatchId			 
			,@rDateOfBirth
			,@rOrgId
			,@lStatusId
			,@rStreetOne
			,@rStreetTwo
			,@rStreetThree
			,@rCountry
			,@rState
			,@rCity
			,@rZipCode
			,@rContactNo
			,@rContactEmail
			,@rRemark
			,@rInquiryModeId
			,@rInquiryReferenceId
			,@rAdmissionCategoryId
			,@rPreviousSchool
			,@rMeritMarks
			,@rMeritGrade
			,@rMeritMarksBreakup
			,@rGenderId
			,@rFollowupDate
			,@rFollowupRemark
			,@rCreatedUserId
			,sCommon.fGetDate()
			,@rInquiryDate
			,@rNumber
			,@rHandledBy
			,@rOrgGroupId
			,@rInquiryStatusMasterId,
			@rCastCategoryId,
			@rIsHostelRequired,
			@rIsTransportRequired,
			@rIsGivenAdmissionForm,
			@rAlternateContactNo,
			@rAlternateContactEmail,
			@rMotherName,
			@rDataEntryModeId,
			@rMinorityStatusId,
			@rLiveWithId,
			@rAdhaarNumber,
			@rBloodGroupId,
			@rFatherName,
			@rFatherOccupation,
			@rFatherIncome,
			@rFatherContactNo,
			@rFatherMail,
			@rFatherQualification,
			@rMotherOccupation,
			@rMotherIncome,
			@rMotherContactNo,
			@rMotherMail,
			@rMotherQualification,
			@rStream,
			@rBoard,
			@rInquiryReferenceRemark
		)
		    SELECT @lNextNumber AS Result         
	END	 
	 ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE  sAdmission.tAdmissionInquiry
	    SET
			 FirstName=@rFirstName
			,MiddleName=@rMiddleName
			,LastName=@rLastName
			,ForClassId=@rForClassId
			,ForBatchId = @rForBatchId		 
			,DateOfBirth=@rDateOfBirth
			,OrgId=@rOrgId
			,StatusId=@lStatusId
			,StreetOne=@rStreetOne
			,StreetTwo=@rStreetTwo
			,StreetThree=@rStreetThree
			,Country=@rCountry
			,State=@rState
			,City=@rCity
			,ZipCode=@rZipCode
			,ContactNo=@rContactNo
			,ContactEmail=@rContactEmail
			,Remark=@rRemark
			,InquiryModeId=@rInquiryModeId
			,InquiryReferenceId=@rInquiryReferenceId 
			,AdmissionCategoryId=@rAdmissionCategoryId
			,PreviousSchool=@rPreviousSchool
			,MeritMarks=@rMeritMarks
			,MeritGrade=@rMeritGrade
			,MeritMarksBreakup=@rMeritMarksBreakup
			,GenderId=@rGenderId
			,FollowupDate=@rFollowupDate
			,FollowupRemark=@rFollowupRemark
			,UpdatedUserId=@rCreatedUserId
			,UpdatedDateTime=sCommon.fGetDate()
			,InquiryDate=@rInquiryDate
			,HandledBy=@rHandledBy
			,InquiryStatusId = @rInquiryStatusMasterId,
			CastCategoryId = @rCastCategoryId,
			IsHostelRequired=@rIsHostelRequired,
			IsTransportRequired=@rIsTransportRequired,
			IsGivenAdmissionForm =@rIsGivenAdmissionForm,
			AlternateContactNo = @rAlternateContactNo,
			AlternateContactEmail = @rAlternateContactEmail,
			MotherName = @rMotherName,
			DataEntryModeId = @rDataEntryModeId ,
			MinorityStatusId  = @rMinorityStatusId , 
			LiveWithId = @rLiveWithId ,
			AdhaarNumber = @rAdhaarNumber ,
			BloodGroupId = @rBloodGroupId ,
			FatherName = @rFatherName,
			FatherOccupation =  @rFatherOccupation ,
			FatherIncome = @rFatherIncome ,
			FatherContactNo = @rFatherContactNo ,
			FatherMail = @rFatherMail ,
			FatherQualification =@rFatherQualification ,
			MotherOccupation = @rMotherOccupation ,
			MotherIncome = @rMotherIncome ,
			MotherContactNo =  @rMotherContactNo ,
			MotherMail = @rMotherMail ,
			MotherQualification = @rMotherQualification ,
			Stream = @rStream ,
			Board  =  @rBoard ,
			InquiryReferenceRemark =@rInquiryReferenceRemark
		
		
	      WHERE Id = @rId 	   
	      SELECT @lNextNumber AS Result      
	      
	 END  
	
		COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
		SELECT ERROR_MESSAGE() AS ERROR
	END CATCH	
		
END
GO
PRINT N'Altering [sAlert].[pPublishExamScheduleGet]...';


GO

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


GO
ALTER PROCEDURE [sAssessment].[pRptBatchWiseResultGet]
	  @rCode nvarchar(20)='',
	  @rOrgId int=0,
	  @rClassId int=0,
	  @rDivisionId int=0,
	  @rBatchId int=0
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 

	declare @quer varchar(max)=''
	DEClare @lOrgId int,@lCode nvarchar(20),@lClassId int,@lDivisionId int,@lBatchId int
	DEClare @lClassGroupId int
	
  		SET @lOrgId=ISNULL(@rOrgId,0)
  		SET @lBatchId=ISNULL(@rBatchId,0)
  		SET @lClassId=ISNULL(@rClassId,0)
  		SET @lDivisionId=ISNULL(@rDivisionId,0)
  	    SET @lCode=ISNULL(@rCode,'')
     DELETE FROM sAssessment.tAllBatchResult 
 select @quer = 'INSERT INTO sAssessment.tAllBatchResult 
  	(
	SubjectId,StudentId
	)
	 SELECT 
			 DISTINCT SM.Id AS Subject,STM.Id AS StudentID FROM
              sStudent.tStudentMaster STM
			  INNER JOIN sStudent.tAcademic AD ON STM.Id = AD.StudentId 
			  INNER JOIN sSetup.tClassMaster CM ON CM.Id=AD.ClassId
			  INNER JOIn sSetup.tClassSubject CS ON CS.ClassId=CM.Id
			  INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=CS.SubjectId 
			  AND SM.OrgId=' + convert(varchar,@lOrgId) + '
			  INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=SM.Id 
  	          WHERE STM.OrgId=' + convert(varchar,@lOrgId) + '
  			  AND AB.OrgId =' + convert(varchar,@lOrgId) + '
  			  AND ((STM.Code = ''' + @lCode + ''') OR (''' + @lCode + ''' = ''''))
  			  AND ((AD.ClassId = ''' + convert(varchar,@lClassId) + ''') OR (' + convert(varchar,@lClassId) + ' = 0))
  			  AND ((AD.DivisionId = ''' + convert(varchar,@lDivisionId) + ''') OR (' + convert(varchar,@lDivisionId) + ' = 0))
  			  AND  AD.BatchId='+Convert(varchar,@lBatchId)+''
  			--SELECT  @quer
  	     EXEC (@quer)
  	     
	    DEClare @query varchar(max)

  		select @query=  ' UPDATE  AR  SET PG = RD.Obtain, PGPercentage = R.Percentage FROM 
			sAssessment.tAllBatchResult  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=101 AND  ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
			
		
		 	exec (@query)
		 	
		 	select @query=  ' UPDATE  AR  SET Nursary = RD.Obtain, NursaryPercentage = R.Percentage FROM 
			sAssessment.tAllBatchResult  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=102 AND  ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
			
		
		 	exec (@query)
		 	
		 	select @query=  ' UPDATE  AR  SET SrKg = RD.Obtain, SrKgPercentage = R.Percentage FROM 
			sAssessment.tAllBatchResult  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=104 AND  ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
		
		 	exec (@query)
		 	select @query=  ' UPDATE  AR  SET JrKg = RD.Obtain, JrKgPercentage = R.Percentage FROM 
			sAssessment.tAllBatchResult  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=103 AND  ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
			
		
		 	exec (@query)
		 	
   select @query=  ' UPDATE  AR  SET First = RD.Obtain, FirstPercentage = R.Percentage FROM 
			sAssessment.tAllBatchResult  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId 
			WHERE CGM.ClassGroupId=1 AND  ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
			
		 	exec (@query)
		 
select @query=  ' UPDATE  AR  SET Second = RD.Obtain, SecondPercentage = R.Percentage FROM 
			sAssessment.tAllBatchResult  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=2 AND ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
			
		 	exec (@query)
		 	
		 
	select @query=  ' UPDATE  AR  SET Third = RD.Obtain, ThirdPercentage = R.Percentage FROM 
			sAssessment.tAllBatchResult  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=3 AND ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
			
		   exec (@query)
		  
	select @query=  ' UPDATE  AR  SET Fourth = RD.Obtain, FourthPercentage = R.Percentage FROM 
			sAssessment.tAllBatchResult  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=4 AND  ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) +''
			
		 	exec (@query)
		 
select @query=  ' UPDATE  AR  SET Fifth = RD.Obtain, FifthPercentage = R.Percentage FROM 
			sAssessment.tAllBatchResult  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=5 AND  ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
			
		 	exec (@query)
		 	
select @query=  ' UPDATE  AR  SET Sixth = RD.Obtain, SixthPercentage = R.Percentage FROM 
			sAssessment.tAllBatchResult  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=6 AND  ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
			
		 	exec (@query)
		 	
select @query=  ' UPDATE  AR  SET Seventh = RD.Obtain, SeventhPercentage = R.Percentage FROM 
			sAssessment.tAllBatchResult  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=7 AND ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
		 	exec (@query)
		 
	select @query=  ' UPDATE  AR  SET Eighth = RD.Obtain, EighthPercentage = R.Percentage FROM 
			sAssessment.tAllBatchResult  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=8 AND  ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
			
		 	exec (@query)
		 	
	select @query=  ' UPDATE  AR  SET Ninth = RD.Obtain, NinthPercentage = R.Percentage FROM 
			sAssessment.tAllBatchResult  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=9 AND ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
		
		 	exec (@query)
		 	
select @query=  ' UPDATE  AR  SET Tenth = RD.Obtain, TenthPercentage = R.Percentage FROM 
			sAssessment.tAllBatchResult  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=10 AND ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
		
		 	exec (@query)
		 	
	select @query=  ' UPDATE  AR  SET Eleventh = RD.Obtain, EleventhPercentage = R.Percentage FROM 
			sAssessment.tAllBatchResult  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=11 AND  ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
			
		 	exec (@query)
		 
	select @query=  ' UPDATE  AR  SET Twelfth = RD.Obtain , TwelfthPercentage = R.Percentage FROM 
			sAssessment.tAllBatchResult  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=12 AND ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
			exec (@query)
			
		 	select @query=  ' UPDATE  AR  SET PG1 = RD.Obtain, PGPercentage1 = R.Percentage FROM 
			sAssessment.tAllBatchResult  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=101 AND  ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
			
		 	exec (@query)
		 	
		 	select @query=  ' UPDATE  AR  SET Nursary1 = RD.Obtain, NursaryPercentage1 = R.Percentage FROM 
			sAssessment.tAllBatchResult  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=102 AND  ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
		
		 	exec (@query)
		 	select @query=  ' UPDATE  AR  SET SrKg1 = RD.Obtain, SrKgPercentage1 = R.Percentage FROM 
			sAssessment.tAllBatchResult  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=104 AND  ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
			
		 	exec (@query)
		 	select @query=  ' UPDATE  AR  SET JrKg1 = RD.Obtain, JrKgPercentage1 = R.Percentage FROM 
			sAssessment.tAllBatchResult  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=103 AND  ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
			
		 	exec (@query)
		 
   select @query=  ' UPDATE  AR  SET First1 = RD.Obtain, FirstPercentage1 = R.Percentage FROM 
			sAssessment.tAllBatchResult  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId 
			WHERE CGM.ClassGroupId=1 AND  ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
			
		 	exec (@query)
		 
		
select @query=  ' UPDATE  AR  SET Second1 = RD.Obtain, SecondPercentage1 = R.Percentage FROM 
			sAssessment.tAllBatchResult  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=2 AND ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
			
		 	exec (@query)
		 	
	select @query=  ' UPDATE  AR  SET Third1 = RD.Obtain, ThirdPercentage1 = R.Percentage FROM 
			sAssessment.tAllBatchResult  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=3 AND ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
		
		   exec (@query)
		  
	select @query=  ' UPDATE  AR  SET Fourth1 = RD.Obtain, FourthPercentage1 = R.Percentage FROM 
			sAssessment.tAllBatchResult  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=4 AND  ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
		
		 	exec (@query)
		 	
select @query=  ' UPDATE  AR  SET Fifth1 = RD.Obtain, FifthPercentage1 = R.Percentage FROM 
			sAssessment.tAllBatchResult  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=5 AND  ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
			
		 	exec (@query)
		 
select @query=  ' UPDATE  AR  SET Sixth1 = RD.Obtain, SixthPercentage1 = R.Percentage FROM 
			sAssessment.tAllBatchResult  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=6 AND  ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
			
		 	exec (@query)
		 	
select @query=  ' UPDATE  AR  SET Seventh1 = RD.Obtain, SeventhPercentage1 = R.Percentage FROM 
			sAssessment.tAllBatchResult  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=7 AND ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
			
		 	exec (@query)
		 	
	select @query=  ' UPDATE  AR  SET Eighth1 = RD.Obtain, EighthPercentage1 = R.Percentage FROM 
			sAssessment.tAllBatchResult  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=8 AND  ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
			
		 	exec (@query)
		 
	select @query=  ' UPDATE  AR  SET Ninth1 = RD.Obtain, NinthPercentage1 = R.Percentage FROM 
			sAssessment.tAllBatchResult  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=9 AND ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
			
		 	exec (@query)
		 
select @query=  ' UPDATE  AR  SET Tenth1 = RD.Obtain, TenthPercentage1 = R.Percentage FROM 
			sAssessment.tAllBatchResult  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=10 AND ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
			
		 	exec (@query)
		 	
		 	
	select @query=  ' UPDATE  AR  SET Eleventh1 = RD.Obtain, EleventhPercentage1 = R.Percentage FROM 
			sAssessment.tAllBatchResult  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=11 AND  ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
			
		 	exec (@query)
		 	
	select @query=  ' UPDATE  AR  SET Twelfth1 = RD.Obtain , TwelfthPercentage1 = R.Percentage FROM 
			sAssessment.tAllBatchResult  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=12 AND ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
				exec (@query)
		 
		 	select @query=  ' UPDATE  AR  SET PG2 = RD.Obtain, PGPercentage2 = R.Percentage FROM 
			sAssessment.tAllBatchResult  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=101 AND  ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
			
		 	exec (@query)
		 	select @query=  ' UPDATE  AR  SET Nursary2 = RD.Obtain, NursaryPercentage2 = R.Percentage FROM 
			sAssessment.tAllBatchResult  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=102 AND  ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
			
		 	exec (@query)
		 	select @query=  ' UPDATE  AR  SET SrKg2 = RD.Obtain, SrKgPercentage2 = R.Percentage FROM 
			sAssessment.tAllBatchResult  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=104 AND  ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
			
		 	exec (@query)
		 	select @query=  ' UPDATE  AR  SET JrKg2 = RD.Obtain, JrKgPercentage2 = R.Percentage FROM 
			sAssessment.tAllBatchResult  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=103 AND  ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) +''
			
		 	exec (@query)
		 
   select @query=  ' UPDATE  AR  SET First2 = RD.Obtain, FirstPercentage2 = R.Percentage FROM 
			sAssessment.tAllBatchResult  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId 
			WHERE CGM.ClassGroupId=1 AND  ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
			
		 	exec (@query)
		 
		
select @query=  ' UPDATE  AR  SET Second2 = RD.Obtain, SecondPercentage2 = R.Percentage FROM 
			sAssessment.tAllBatchResult  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=2 AND ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
			
		 	exec (@query)
		 	
	select @query=  ' UPDATE  AR  SET Third2 = RD.Obtain, ThirdPercentage2 = R.Percentage FROM 
			sAssessment.tAllBatchResult  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=3 AND ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
			
		   exec (@query)
		   	
	select @query=  ' UPDATE  AR  SET Fourth2 = RD.Obtain , FourthPercentage2 = R.Percentage FROM 
			sAssessment.tAllBatchResult  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=4 AND  ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
		
		 	exec (@query)
		 	
select @query=  ' UPDATE  AR  SET Fifth2 = RD.Obtain, FifthPercentage2 = R.Percentage FROM 
			sAssessment.tAllBatchResult  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=5 AND  ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
		
		 	exec (@query)
		 	
select @query=  ' UPDATE  AR  SET Sixth2 = RD.Obtain, SixthPercentage2 = R.Percentage FROM 
			sAssessment.tAllBatchResult  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=6 AND  ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
			exec (@query)
			
select @query=  ' UPDATE  AR  SET Seventh2 = RD.Obtain, SeventhPercentage2 = R.Percentage FROM 
			sAssessment.tAllBatchResult  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=7 AND ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
			
		 	exec (@query)
		 		
	select @query=  ' UPDATE  AR  SET Eighth2 = RD.Obtain, EighthPercentage2 = R.Percentage FROM 
			sAssessment.tAllBatchResult  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=8 AND  ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
			
		 	exec (@query)
		 	
	select @query=  ' UPDATE  AR  SET Ninth2 = RD.Obtain, NinthPercentage2 = R.Percentage FROM 
			sAssessment.tAllBatchResult  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=9 AND ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
			
		 	exec (@query)
		 		
select @query=  ' UPDATE  AR  SET Tenth2 = RD.Obtain, TenthPercentage2 = R.Percentage FROM 
			sAssessment.tAllBatchResult  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=10 AND ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
			
		 	exec (@query)
		 	
	select @query=  ' UPDATE  AR  SET Eleventh2 = RD.Obtain, EleventhPercentage2 = R.Percentage FROM 
			sAssessment.tAllBatchResult  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=11 AND  ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
		
		 	exec (@query)
		 	
	select @query=  ' UPDATE  AR  SET Twelfth2 = RD.Obtain , TwelfthPercentage2 = R.Percentage FROM 
			sAssessment.tAllBatchResult  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=12 AND ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
	   	exec (@query)
	   
		 	select @query='SELECT AR.StudentId,SM.Id AS SubjectId,Isnull(PG,0) AS PG,Isnull(Nursary,0) AS Nursary,Isnull(SrKg,0) AS SrKg , Isnull(JrKg,0) AS JrKg,Isnull(First,0) AS FirstAnnual,
		 	Isnull(Second,0) AS Second, Isnull(Third,0) As  Third, Isnull(Fourth,0) AS Fourth,Isnull(Fifth,0) AS Fifth, Isnull(Sixth,0) AS Sixth, Isnull(Seventh,0) AS Seventh, Isnull(Eighth,0) AS Eighth, Isnull(Ninth,0) AS Ninth, 
		 	Isnull(Tenth,0) As Tenth, Isnull(Eleventh,0) As Eleventh, Isnull(Twelfth,0) As Twelfth ,
		 	Isnull(PG1,0) AS PG1,Isnull(Nursary1,0) AS Nursary1,Isnull(SrKg1,0) AS SrKg1 , Isnull(JrKg1,0) AS JrKg1,Isnull(First1,0) AS First1,
		 	Isnull(Second1,0) AS Second1, Isnull(Third1,0) As  Third1, Isnull(Fourth1,0) AS Fourth1,Isnull(Fifth1,0) AS Fifth1, Isnull(Sixth1,0) AS Sixth1, Isnull(Seventh1,0) AS Seventh1, Isnull(Eighth1,0) AS Eighth1, Isnull(Ninth1,0) AS Ninth1, 
		 	Isnull(Tenth1,0) As Tenth1, Isnull(Eleventh1,0) As Eleventh1, Isnull(Twelfth1,0) As Twelfth1,
		 	Isnull(PG2,0) AS PG2,Isnull(Nursary2,0) AS Nursary2,Isnull(SrKg2,0) AS SrKg2 , Isnull(JrKg2,0) AS JrKg2,Isnull(First2,0) AS First2,
		 	Isnull(Second2,0) AS Second2, Isnull(Third2,0) As  Third2, Isnull(Fourth2,0) AS Fourth2,Isnull(Fifth2,0) AS Fifth2, Isnull(Sixth2,0) AS Sixth2, Isnull(Seventh2,0) AS Seventh2, Isnull(Eighth2,0) AS Eighth2, Isnull(Ninth2,0) AS Ninth2, 
		 	Isnull(Tenth2,0) As Tenth2, Isnull(Eleventh2,0) As Eleventh2, Isnull(Twelfth2,0) As Twelfth2,
		 	SM.Code As SubjectCode,A.Code,A.Name,A.BatchName,A.BatchId,SM.OrderIndex,A.RollNo,
			Isnull(PGPercentage,0) AS PGPercentage,Isnull(PGPercentage1,0) AS PGPercentage1, Isnull(PGPercentage2,0) AS PGPercentage2,
			Isnull(NursaryPercentage,0) AS NursaryPercentage,Isnull(NursaryPercentage1,0) AS NursaryPercentage1, Isnull(NursaryPercentage2,0) AS NursaryPercentage2,
			Isnull(SrKgPercentage,0) AS SrKgPercentage,Isnull(SrKgPercentage1,0) AS SrKgPercentage1, Isnull(SrKgPercentage2,0) AS SrKgPercentage2,
			Isnull(JrKgPercentage,0) AS JrKgPercentage,Isnull(JrKgPercentage1,0) AS JrKgPercentage1, Isnull(JrKgPercentage2,0) AS JrKgPercentage2,
			Isnull(FirstPercentage,0) AS FirstPercentage,Isnull(FirstPercentage1,0) AS FirstPercentage1, Isnull(FirstPercentage2,0) AS FirstPercentage2,
			Isnull(SecondPercentage,0) AS SecondPercentage,Isnull(SecondPercentage1,0) AS SecondPercentage1, Isnull(SecondPercentage2,0) AS SecondPercentage2,
			Isnull(ThirdPercentage,0) AS ThirdPercentage,Isnull(ThirdPercentage1,0) AS ThirdPercentage1, Isnull(ThirdPercentage2,0) AS ThirdPercentage2,
			Isnull(FourthPercentage,0) AS FourthPercentage,Isnull(FourthPercentage1,0) AS FourthPercentage1, Isnull(FourthPercentage2,0) AS FourthPercentage2,
			Isnull(FifthPercentage,0) AS FifthPercentage,Isnull(FifthPercentage1,0) AS FifthPercentage1, Isnull(FifthPercentage2,0) AS FifthPercentage2,
			Isnull(SixthPercentage,0) AS SixthPercentage,Isnull(SixthPercentage1,0) AS SixthPercentage1, Isnull(SixthPercentage2,0) AS SixthPercentage2,
			Isnull(SeventhPercentage,0) AS SeventhPercentage,Isnull(SeventhPercentage1,0) AS SeventhPercentage1, Isnull(SeventhPercentage2,0) AS SeventhPercentage2,
			Isnull(EighthPercentage,0) AS EighthPercentage,Isnull(EighthPercentage1,0) AS EighthPercentage1, Isnull(EighthPercentage2,0) AS EighthPercentage2,
			Isnull(NinthPercentage,0) AS NinthPercentage,Isnull(NinthPercentage1,0) AS NinthPercentage1, Isnull(NinthPercentage2,0) AS NinthPercentage2,
			Isnull(TenthPercentage,0) AS TenthPercentage,Isnull(TenthPercentage1,0) AS TenthPercentage1, Isnull(TenthPercentage2,0) AS TenthPercentage2,
			Isnull(EleventhPercentage,0) AS EleventhPercentage,Isnull(EleventhPercentage1,0) AS EleventhPercentage1, Isnull(EleventhPercentage2,0) AS EleventhPercentage2,
			Isnull(TwelfthPercentage,0) AS TwelfthPercentage,Isnull(TwelfthPercentage1,0) AS TwelfthPercentage1, Isnull(TwelfthPercentage2,0) AS TwelfthPercentage2
		     FROM sStudent.vStudentLastAcademic A  INNER JOIN  sAssessment.tAllBatchResult AR ON  AR.StudentId=A.StudentId 
	       INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=AR.SubjectId 
		    WHERE A.OrgId=' + convert(varchar,@lOrgId) + ' '
		   
		 exec (@query)
END
GO
PRINT N'Altering [sAssessment].[pRptStudentAllExamResultGet]...';


GO


ALTER PROCEDURE [sAssessment].[pRptStudentAllExamResultGet]
	 
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 @rSubjectId int=0,
	 @rBatchId int,
	 @rClassId int=0,
	 @rDivisionId int=0,
	  @rExamId int=0,
	 @rExamSubGroupId int=0,
	 @rCode nvarchar(20)='',
	 @rFromRollNo int=0,
	 @rToRollNo int=0,
	 @rFromRank int=0,
	 @rToRank int=0,
	 @rGrade nvarchar(20)='',
	 @rFromPercentage decimal(5,2)=0,
	 @rToPercentage decimal(5,2)=0,
	 @rExamSubGroup nvarchar(MAX)='',
	 @rStatusId int = 0,
	 @rClassStatusId int=0
	 
	
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
SELECT
		@rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,
		R.AcademicId,
		ESGM.Title AS Exam,
		  [sStudent].[fStudentNameGet](StuM.FirstName , StuM.MiddleName, StuM.LastName,OM.StudentNameFormatId ) AS Name,
		A.RollNo,
		CM.DisplayTitle AS Class,
		DM.DisplayTitle AS Division,
		R.Percentage,
		StuM.Code,
		CM.Title,
		DM.Title,
		R.ResultStatus
	
FROM 
			sAssessment.tResult R 
			INNER JOIN sStudent.vStudentAcademic A ON A.AcademicId=R.AcademicId
			INNER JOIN sStudent.tStudentMaster StuM ON StuM.Id=A.StudentId
			INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId
			INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId
			INNER JOIN sAssessment.tExamMaster E ON R.ExamId = E.Id
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id = E.ExamSubGroupId
			INNER JOIN sSetup.tOrganizationMaster OM ON StuM.OrgId = OM.Id
			
	WHERE 
			
		E.BatchId = @rBatchId 
		AND (A.ClassId=@rClassId OR @rClassId=0) 
		--AND ((SM.Id=@rSubjectId) OR (@rSubjectId=0))
		AND (A.DivisionId=@rDivisionId OR @rDivisionId=0)
		AND ((A.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
		AND ((A.RollNo <= @rToRollNo) OR (@rToRollNo=0))
		AND ((R.RankNumber >= @rFromRank) OR (@rFromRank=0))
		AND ((R.RankNumber <= @rToRank) OR (@rToRank=0))
		AND E.IsProcessResult = 1
		
		AND ((R.Percentage >= @rFromPercentage) OR (@rFromPercentage=0))
		AND ((R.Percentage<=@rToPercentage) OR (@rToPercentage=0))
		--AND ((R.ResultGrade = @rGrade) OR (@rGrade=''))
		
		--AND ((R.ExamId = @rExamId) OR (@rExamId =0))
		AND ((ESGM.Id=@rExamSubGroupId) OR (@rExamSubGroupId=0))
		AND ((E.Id=@rExamId )	OR (@rExamId = 0))
		
		 AND (ISNULL(ESGM.Id,0) IN( SELECT item FROM  sCommon.fnsplit(@rExamSubGroup,','))OR @rExamSubGroup='')
		  AND ((A.StatusId=@rStatusId) OR (@rStatusId=0))
		  AND ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0))
		order by ESGM.OrderIndex
		--AND ((StuM.Code=@rCode) OR (@rCode=''))
		
		--order by A.RollNo,CS.OrderIndex 
		--AND A.id = 1005000000007
		
END
GO
PRINT N'Altering [sAttendance].[pMonthlyRegisterStudentviewGet]...';


GO

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

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

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

		SET @YearNumber =Year(GETDATE())



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

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


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

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

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

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


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


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

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


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

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

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


GO
 
 
ALTER PROCEDURE [sBiometric].[pBiometricReportData]

	@rBuilder1 nvarchar(max)='',
	@rBuilder2 nvarchar(max)='',
	@rOrgId int,
	@rDeptId int,
	@rForYear int=0,
	@rForMonth int=0,
	@rIsFirstIn bit=0,
	@rIsLastOut bit=0,
	@rIsOT bit=0,
	@rIsLateBy	bit=0,
	@rIsEarlyBy bit=0,
	@rIsDuration  bit=0,
	@rEmployeeStatusId int=0,
	@rEmployeeId bigint = 0,
	@rOrgGroupId int = 0,
	@OrgGroupDepartmentId int = 0

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 

	DECLARE @lATTN_DATE nvarchar(20)
	DECLARE @lBatchID int
	DECLARE @Days int 
	SELECT @Days=sCommon.fGetDaysInMonth(@rForMonth,@rForYear)
	SELECT @lBatchID = Id FROM sSetup.tBatchMaster WHERE OrgId = @rOrgId AND IsActive = 1

	SET @lATTN_DATE = CONVERT(nvarchar(10),@rForYear) + '-' + Right('000000' + CONVERT(nvarchar, @rForMonth), 2) + '-01'
	
	DECLARE @lDN1 nvarchar(10),@lDN2 nvarchar(10),@lDN3 nvarchar(10),@lDN4 nvarchar(10),@lDN5 nvarchar(10),
	@lDN6 nvarchar(10),@lDN7 nvarchar(10),@lDN8 nvarchar(10),@lDN9 nvarchar(10),@lDN10 nvarchar(10),
	@lDN11 nvarchar(10),@lDN12 nvarchar(10),@lDN13 nvarchar(10),@lDN14 nvarchar(10),@lDN15 nvarchar(10),
	@lDN16 nvarchar(10),@lDN17 nvarchar(10),@lDN18 nvarchar(10),@lDN19 nvarchar(10),@lDN20 nvarchar(10),
	@lDN21 nvarchar(10),@lDN22 nvarchar(10),@lDN23 nvarchar(10),@lDN24 nvarchar(10),@lDN25 nvarchar(10),
	@lDN26 nvarchar(10),@lDN27 nvarchar(10),@lDN28 nvarchar(10),@lDN29 nvarchar(10),@lDN30 nvarchar(10),
	@lDN31 nvarchar(10)
	
	SET @lDN1 = '01 ' + substring(DATENAME( dw, convert( date, ( '01' + '/' + CONVERT(nvarchar(2),@rforMonth) + '/' + CONVERT(nvarchar(4),@rforYear) ), 103 ) ),1,2)
	SET @lDN2 = '02 ' + substring(DATENAME( dw, convert( date, ( '02' + '/' + CONVERT(nvarchar(2),@rforMonth) + '/' + CONVERT(nvarchar(4),@rforYear) ), 103 ) ),1,2)
	SET @lDN3 = '03 ' + substring(DATENAME( dw, convert( date, ( '03' + '/' + CONVERT(nvarchar(2),@rforMonth) + '/' + CONVERT(nvarchar(4),@rforYear) ), 103 ) ),1,2)
	SET @lDN4 = '04 ' + substring(DATENAME( dw, convert( date, ( '04' + '/' + CONVERT(nvarchar(2),@rforMonth) + '/' + CONVERT(nvarchar(4),@rforYear) ), 103 ) ),1,2)
	SET @lDN5 = '05 ' + substring(DATENAME( dw, convert( date, ( '05' + '/' + CONVERT(nvarchar(2),@rforMonth) + '/' + CONVERT(nvarchar(4),@rforYear) ), 103 ) ),1,2)
	SET @lDN6 = '06 ' + substring(DATENAME( dw, convert( date, ( '06' + '/' + CONVERT(nvarchar(2),@rforMonth) + '/' + CONVERT(nvarchar(4),@rforYear) ), 103 ) ),1,2)
	SET @lDN7 = '07 ' + substring(DATENAME( dw, convert( date, ( '07' + '/' + CONVERT(nvarchar(2),@rforMonth) + '/' + CONVERT(nvarchar(4),@rforYear) ), 103 ) ),1,2)
	SET @lDN8 = '08 ' + substring(DATENAME( dw, convert( date, ( '08' + '/' + CONVERT(nvarchar(2),@rforMonth) + '/' + CONVERT(nvarchar(4),@rforYear) ), 103 ) ),1,2)
	SET @lDN9 = '09 ' + substring(DATENAME( dw, convert( date, ( '09' + '/' + CONVERT(nvarchar(2),@rforMonth) + '/' + CONVERT(nvarchar(4),@rforYear) ), 103 ) ),1,2)
	SET @lDN10 = '10 ' + substring(DATENAME( dw, convert( date, ( '10' + '/' + CONVERT(nvarchar(2),@rforMonth) + '/' + CONVERT(nvarchar(4),@rforYear) ), 103 ) ),1,2)
	SET @lDN11 = '11 ' + substring(DATENAME( dw, convert( date, ( '11' + '/' + CONVERT(nvarchar(2),@rforMonth) + '/' + CONVERT(nvarchar(4),@rforYear) ), 103 ) ),1,2)
	SET @lDN12 = '12 ' + substring(DATENAME( dw, convert( date, ( '12' + '/' + CONVERT(nvarchar(2),@rforMonth) + '/' + CONVERT(nvarchar(4),@rforYear) ), 103 ) ),1,2)
	SET @lDN13 = '13 ' + substring(DATENAME( dw, convert( date, ( '13' + '/' + CONVERT(nvarchar(2),@rforMonth) + '/' + CONVERT(nvarchar(4),@rforYear) ), 103 ) ),1,2)
	SET @lDN14 = '14 ' + substring(DATENAME( dw, convert( date, ( '14' + '/' + CONVERT(nvarchar(2),@rforMonth) + '/' + CONVERT(nvarchar(4),@rforYear) ), 103 ) ),1,2)
	SET @lDN15 = '15 ' + substring(DATENAME( dw, convert( date, ( '15' + '/' + CONVERT(nvarchar(2),@rforMonth) + '/' + CONVERT(nvarchar(4),@rforYear) ), 103 ) ),1,2)
	SET @lDN16 = '16 ' + substring(DATENAME( dw, convert( date, ( '16' + '/' + CONVERT(nvarchar(2),@rforMonth) + '/' + CONVERT(nvarchar(4),@rforYear) ), 103 ) ),1,2)
	SET @lDN17 = '17 ' + substring(DATENAME( dw, convert( date, ( '17' + '/' + CONVERT(nvarchar(2),@rforMonth) + '/' + CONVERT(nvarchar(4),@rforYear) ), 103 ) ),1,2)
	SET @lDN18 = '18 ' + substring(DATENAME( dw, convert( date, ( '18' + '/' + CONVERT(nvarchar(2),@rforMonth) + '/' + CONVERT(nvarchar(4),@rforYear) ), 103 ) ),1,2)
	SET @lDN19 = '19 ' + substring(DATENAME( dw, convert( date, ( '19' + '/' + CONVERT(nvarchar(2),@rforMonth) + '/' + CONVERT(nvarchar(4),@rforYear) ), 103 ) ),1,2)
	SET @lDN20 = '20 ' + substring(DATENAME( dw, convert( date, ( '20' + '/' + CONVERT(nvarchar(2),@rforMonth) + '/' + CONVERT(nvarchar(4),@rforYear) ), 103 ) ),1,2)
	SET @lDN21 = '21 ' + substring(DATENAME( dw, convert( date, ( '21' + '/' + CONVERT(nvarchar(2),@rforMonth) + '/' + CONVERT(nvarchar(4),@rforYear) ), 103 ) ),1,2)
	SET @lDN22 = '22 ' + substring(DATENAME( dw, convert( date, ( '22' + '/' + CONVERT(nvarchar(2),@rforMonth) + '/' + CONVERT(nvarchar(4),@rforYear) ), 103 ) ),1,2)
	SET @lDN23 = '23 ' + substring(DATENAME( dw, convert( date, ( '23' + '/' + CONVERT(nvarchar(2),@rforMonth) + '/' + CONVERT(nvarchar(4),@rforYear) ), 103 ) ),1,2)
	SET @lDN24 = '24 ' + substring(DATENAME( dw, convert( date, ( '24' + '/' + CONVERT(nvarchar(2),@rforMonth) + '/' + CONVERT(nvarchar(4),@rforYear) ), 103 ) ),1,2)
	SET @lDN25 = '25 ' + substring(DATENAME( dw, convert( date, ( '25' + '/' + CONVERT(nvarchar(2),@rforMonth) + '/' + CONVERT(nvarchar(4),@rforYear) ), 103 ) ),1,2)
	SET @lDN26 = '26 ' + substring(DATENAME( dw, convert( date, ( '26' + '/' + CONVERT(nvarchar(2),@rforMonth) + '/' + CONVERT(nvarchar(4),@rforYear) ), 103 ) ),1,2)
	SET @lDN27 = '27 ' + substring(DATENAME( dw, convert( date, ( '27' + '/' + CONVERT(nvarchar(2),@rforMonth) + '/' + CONVERT(nvarchar(4),@rforYear) ), 103 ) ),1,2)
	SET @lDN28 = '28 ' + substring(DATENAME( dw, convert( date, ( '28' + '/' + CONVERT(nvarchar(2),@rforMonth) + '/' + CONVERT(nvarchar(4),@rforYear) ), 103 ) ),1,2)
	SET @lDN29 = case when @Days >= 29 then '29 ' + substring(DATENAME( dw, convert( date, ( '29' + '/' + CONVERT(nvarchar(2),@rforMonth) + '/' + CONVERT(nvarchar(4),@rforYear) ), 103 ) ),1,2) end
	SET @lDN30 = case when @Days >= 30 then '30 ' + substring(DATENAME( dw, convert( date, ( '30' + '/' + CONVERT(nvarchar(2),@rforMonth) + '/' + CONVERT(nvarchar(4),@rforYear) ), 103 ) ),1,2) end
	SET @lDN31 = case when @Days < 31 Then '' else '31 ' + substring(DATENAME( dw, convert( date, ( '31' + '/' + CONVERT(nvarchar(2),@rforMonth) + '/' + CONVERT(nvarchar(4),@rforYear) ), 103 ) ),1,2) end

	SELECT 
		datediff(day, dateadd(day, 1-day(@lATTN_DATE), @lATTN_DATE),
		dateadd(month, 1, dateadd(day, 1-day(@lATTN_DATE), @lATTN_DATE))) AS DayCount,
		@rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2, 
		
		@lDN1 as DN1,@lDN2 as DN2,@lDN3 as DN3,@lDN4 as DN4,@lDN5 as DN5,@lDN6 as DN6,@lDN7 as DN7,@lDN8 as DN8,@lDN9 as DN9,@lDN10 as DN10,
		@lDN11 as DN11,@lDN12 as DN12,@lDN13 as DN13,@lDN14 as DN14,@lDN15 as DN15,@lDN16 as DN16,@lDN17 as DN17,@lDN18 as DN18,@lDN19 as DN19,
		@lDN20 as DN20,@lDN21 as DN21,@lDN22 as DN22,@lDN23 as DN23,@lDN24 as DN24,@lDN25 as DN25,@lDN26 as DN26,@lDN27 as DN27,@lDN28 as DN28,	@lDN29 as DN29,@lDN30 as DN30,@lDN31 AS DN31,
		
		E.Code,	
		E.ShortName,
		DM.Displaytitle DeptName,
		DM.Code AS DeptCode,
		E.OrgID,
		DM.Id AS DepartmentId,
		EDM.Title AS Designation,
		EDM.Code AS DesignationCode,
		@rIsFirstIn AS IsFirstIn,
		@rIsLastOut AS IsLastOut,
		@rIsOT AS IsOT,
		@rIsLateBy	AS IsLateBy,
		@rIsEarlyBy AS IsEarlyBy,
		@rIsDuration  AS IsDuration,
		E.FirstName +' ' + E.MiddleName +' '+ E.LastName AS Name,
		sBiometric.fEmployeeLeaveTypeGet(Attn_Dt,T.EmployeeId) AS LeaveStatus,
		ISNULL(sBiometric.fEmployeeCLTypeGet(@rForMonth,@rForYear,T.EmployeeId),'') AS CLeaveStatus,
		[sHrm].[fWeekHOffGetBio](T.EmployeeId, @rForYear,@rForMonth,1,@lBatchID,ED.OrganizationDepartmentId,@rOrgId) AS D01,
		[sHrm].[fWeekHOffGetBio](T.EmployeeId, @rForYear,@rForMonth,2,@lBatchID,ED.OrganizationDepartmentId,@rOrgId) AS D02,
		[sHrm].[fWeekHOffGetBio](T.EmployeeId, @rForYear,@rForMonth,3,@lBatchID,ED.OrganizationDepartmentId,@rOrgId) AS D03,
		[sHrm].[fWeekHOffGetBio](T.EmployeeId, @rForYear,@rForMonth,4,@lBatchID,ED.OrganizationDepartmentId,@rOrgId) AS D04,
		[sHrm].[fWeekHOffGetBio](T.EmployeeId, @rForYear,@rForMonth,5,@lBatchID,ED.OrganizationDepartmentId,@rOrgId) AS D05,
		[sHrm].[fWeekHOffGetBio](T.EmployeeId, @rForYear,@rForMonth,6,@lBatchID,ED.OrganizationDepartmentId,@rOrgId) AS D06,
		[sHrm].[fWeekHOffGetBio](T.EmployeeId, @rForYear,@rForMonth,7,@lBatchID,ED.OrganizationDepartmentId,@rOrgId) AS D07,
		[sHrm].[fWeekHOffGetBio](T.EmployeeId, @rForYear,@rForMonth,8,@lBatchID,ED.OrganizationDepartmentId,@rOrgId) AS D08,
		[sHrm].[fWeekHOffGetBio](T.EmployeeId, @rForYear,@rForMonth,9,@lBatchID,ED.OrganizationDepartmentId,@rOrgId) AS D09,
		[sHrm].[fWeekHOffGetBio](T.EmployeeId, @rForYear,@rForMonth,10,@lBatchID,ED.OrganizationDepartmentId,@rOrgId) AS D10,
		[sHrm].[fWeekHOffGetBio](T.EmployeeId, @rForYear,@rForMonth,11,@lBatchID,ED.OrganizationDepartmentId,@rOrgId) AS D11,
		[sHrm].[fWeekHOffGetBio](T.EmployeeId, @rForYear,@rForMonth,12,@lBatchID,ED.OrganizationDepartmentId,@rOrgId) AS D12,
		[sHrm].[fWeekHOffGetBio](T.EmployeeId, @rForYear,@rForMonth,13,@lBatchID,ED.OrganizationDepartmentId,@rOrgId) AS D13,
		[sHrm].[fWeekHOffGetBio](T.EmployeeId, @rForYear,@rForMonth,14,@lBatchID,ED.OrganizationDepartmentId,@rOrgId) AS D14,
		[sHrm].[fWeekHOffGetBio](T.EmployeeId, @rForYear,@rForMonth,15,@lBatchID,ED.OrganizationDepartmentId,@rOrgId) AS D15,
		[sHrm].[fWeekHOffGetBio](T.EmployeeId, @rForYear,@rForMonth,16,@lBatchID,ED.OrganizationDepartmentId,@rOrgId) AS D16,
		[sHrm].[fWeekHOffGetBio](T.EmployeeId, @rForYear,@rForMonth,17,@lBatchID,ED.OrganizationDepartmentId,@rOrgId) AS D17,
		[sHrm].[fWeekHOffGetBio](T.EmployeeId, @rForYear,@rForMonth,18,@lBatchID,ED.OrganizationDepartmentId,@rOrgId) AS D18,
		[sHrm].[fWeekHOffGetBio](T.EmployeeId, @rForYear,@rForMonth,19,@lBatchID,ED.OrganizationDepartmentId,@rOrgId) AS D19,
		[sHrm].[fWeekHOffGetBio](T.EmployeeId, @rForYear,@rForMonth,20,@lBatchID,ED.OrganizationDepartmentId,@rOrgId) AS D20,
		[sHrm].[fWeekHOffGetBio](T.EmployeeId, @rForYear,@rForMonth,21,@lBatchID,ED.OrganizationDepartmentId,@rOrgId) AS D21,
		[sHrm].[fWeekHOffGetBio](T.EmployeeId, @rForYear,@rForMonth,22,@lBatchID,ED.OrganizationDepartmentId,@rOrgId) AS D22,
		[sHrm].[fWeekHOffGetBio](T.EmployeeId, @rForYear,@rForMonth,23,@lBatchID,ED.OrganizationDepartmentId,@rOrgId) AS D23,
		[sHrm].[fWeekHOffGetBio](T.EmployeeId, @rForYear,@rForMonth,24,@lBatchID,ED.OrganizationDepartmentId,@rOrgId) AS D24,
		[sHrm].[fWeekHOffGetBio](T.EmployeeId, @rForYear,@rForMonth,25,@lBatchID,ED.OrganizationDepartmentId,@rOrgId) AS D25,
		[sHrm].[fWeekHOffGetBio](T.EmployeeId, @rForYear,@rForMonth,26,@lBatchID,ED.OrganizationDepartmentId,@rOrgId) AS D26,
		[sHrm].[fWeekHOffGetBio](T.EmployeeId, @rForYear,@rForMonth,27,@lBatchID,ED.OrganizationDepartmentId,@rOrgId) AS D27,
		[sHrm].[fWeekHOffGetBio](T.EmployeeId, @rForYear,@rForMonth,28,@lBatchID,ED.OrganizationDepartmentId,@rOrgId) AS D28,
		--[sHrm].[fWeekHOffGetBio](T.EmployeeId, @rForYear,@rForMonth,29,@lBatchID,ED.OrganizationDepartmentId,@rOrgId) AS D29,
		--[sHrm].[fWeekHOffGetBio](T.EmployeeId, @rForYear,@rForMonth,30,@lBatchID,ED.OrganizationDepartmentId,@rOrgId) AS D30,
		--[sHrm].[fWeekHOffGetBio](T.EmployeeId, @rForYear,@rForMonth,31,@lBatchID,ED.OrganizationDepartmentId,@rOrgId) AS D31,

		case when @Days >= 29 then [sHrm].[fWeekHOffGetBio](T.EmployeeId, @rForYear,@rForMonth,29,@lBatchID,ED.OrganizationDepartmentId,@rOrgId) end AS D29,
		case when @Days >= 30 then [sHrm].[fWeekHOffGetBio](T.EmployeeId, @rForYear,@rForMonth,30,@lBatchID,ED.OrganizationDepartmentId,@rOrgId) end AS D30,
		case when @Days >= 31 then [sHrm].[fWeekHOffGetBio](T.EmployeeId, @rForYear,@rForMonth,31,@lBatchID,ED.OrganizationDepartmentId,@rOrgId) end AS D31,


		
		E.Code AS  EmpCode, Attn_Dt, D01_IN, D02_IN, D03_IN, D04_IN, D05_IN, D06_IN, D07_IN, D08_IN, D09_IN, D10_IN, D11_IN, D12_IN, D13_IN, D14_IN, D15_IN, D16_IN, 
		D17_IN, D18_IN, D19_IN, D20_IN, D21_IN, D22_IN, D23_IN, D24_IN, D25_IN, D26_IN, D27_IN, D28_IN, D29_IN, D30_IN, D31_IN, D01_OUT, D02_OUT, D03_OUT, 
		D04_OUT, D05_OUT, D06_OUT, D07_OUT, D08_OUT, D09_OUT, D10_OUT, D11_OUT, D12_OUT, D13_OUT, D14_OUT, D15_OUT, D16_OUT, D17_OUT, D18_OUT, 
		D19_OUT, D20_OUT, D21_OUT, D22_OUT, D23_OUT, D24_OUT, D25_OUT, D26_OUT, D27_OUT, D28_OUT, D29_OUT, D30_OUT, D31_OUT, D01_O, D02_O, D03_O, 
		D04_O, D05_O, D06_O, D07_O, D08_O, D09_O, D10_O, D11_O, D12_O, D13_O, D14_O, D15_O, D16_O, D17_O, D18_O, D19_O, D20_O, D21_O, D22_O, D23_O, 
		D24_O, D25_O, D26_O, D27_O, D28_O, D29_O, D30_O, D31_O, D01_L, D02_L, D03_L, D04_L, D05_L, D06_L, D07_L, D08_L, D09_L, D10_L, D11_L, D12_L, D13_L, 
		D14_L, D15_L, D16_L, D17_L, D18_L, D19_L, D20_L, D21_L, D22_L, D23_L, D24_L, D25_L, D26_L, D27_L, D28_L, D29_L, D30_L, D31_L, D01_T, D02_T, D03_T, 
		D04_T, D05_T, D06_T, D07_T, D08_T, D09_T, D10_T, D11_T, D12_T, D13_T, D14_T, D15_T, D16_T, D17_T, D18_T, D19_T, D20_T, D21_T, D22_T, D23_T, D24_T, 
		D25_T, D26_T, D27_T, D28_T, D29_T, D30_T, D31_T, D01_E, D02_E, D03_E, D04_E, D05_E, D06_E, D07_E, D08_E, D09_E, D10_E, D11_E, D12_E, D13_E, D14_E, 
		D15_E, D16_E, D17_E, D18_E, D19_E, D20_E, D21_E, D22_E, D23_E, D24_E, D25_E, D26_E, D27_E, D28_E, D29_E, D30_E, D31_E, D01_S, D02_S, D03_S, D04_S, 
		D05_S, D06_S, D07_S, D08_S, D09_S, D10_S, D11_S, D12_S, D13_S, D14_S, D15_S, D16_S, D17_S, D18_S, D19_S, D20_S, D21_S, D22_S, D23_S, D24_S, D25_S, 
		D26_S, D27_S, D28_S, D29_S, D30_S, D31_S, Tot_Attn, Tot_Abs, Tot_WeekOFF, Tot_Holiday, TotalHour, Tot_HD, Tot_Early, Tot_Late, Tot_OT, Tot_OD, Tot_Leave, 
		Count_Late, Count_Early, Count_OT, Tot_CL, Tot_SL, Tot_EL, Tot_SP, Tot_C, Tot_PL, Tot_ML, T.EmployeeId,OM.Title AS OrganizationTitle,
		ISNULL(E.PunchId,'') AS PunchId
	FROM 
		sBiometric.tMonthTrans T
		INNER JOIN sHRM.tEmployeeMaster E on E.Id = T.EmployeeId
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = E.OrgID
		LEFT JOIN sHRM.tEmployeeJobDetail ED ON ED.EmployeeId = E.Id
		LEFT JOIN sSetup.tDepartmentMaster DM ON DM.Id = ED.OrganizationDepartmentId
		LEFT JOIN sHRM.tEmployeeDesignationMaster EDM ON EDM.Id = ED.EmployeeDesignationId
	WHERE 
		(E.OrgId=@rOrgId OR @rOrgId = 0) 		
		AND (DM.Id = @rDeptId OR @rDeptId = 0)		 
		AND(T.Attn_dt = @lATTN_DATE) --AND E.StatusID = 7
		AND (MONTH(ED.DateofLeaving) >= @rForMonth AND YEAR(ED.DateofLeaving) >= @rForYear OR ED.DateofLeaving Is null )
		AND (E.STatusId = @rEmployeeStatusId OR ISNULL(@rEmployeeStatusId,0)=0)
		AND ISNULL(E.IsOtherUser,0) = 0 
		AND (ISNULL(T.SourceTypeId,95) = 95 OR T.SourceTypeId = 0)
		AND (T.EmployeeId = @rEmployeeId OR @rEmployeeId = 0)
		AND OM.OrgGroupId = @rOrgGroupId
		AND ((ED.OrgGroupDepartmentId = @OrgGroupDepartmentId) OR (@OrgGroupDepartmentId=0)) 
	ORDER BY 
	E.Code,T.Attn_dt
END
GO
PRINT N'Altering [sBiometric].[pRptDateWiseTimeSheetSummary]...';


GO
 
ALTER PROCEDURE [sBiometric].[pRptDateWiseTimeSheetSummary]
     @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='',
	 @rFromDate Date,
	 @rToDate Date,
	 @rOrgId int,
	 @rOrganizationDepartmentId int=0,
	 @rEmployeeTypeId int =0,
	 @rEmployeeId bigint = 0,
	 @rForYear int=0,
	 @rForMonth int=0,
	 @rIsFirstIn bit=0,
	 @rIsLastOut bit=0,
	 @rIsOT bit=0,
	 @rIsLateBy	bit=0,
	 @rIsEarlyBy bit=0,
	 @rIsDuration  bit=0,
	 @rGradeId nvarchar(200) = '0',
	 @rEmployeeStatusId int=0,
	 @rOrgGroupId int = 0,
	 @OrgGroupDepartmentId int = 0
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 

DECLARE @TableEmployee TABLE (Id int Identity,EmployeeID BigINT, OrganizationDepartmentId int, EmployeeTypeId Int)
INSERT INTO @TableEmployee
SELECT EM.Id AS EmployeeId,ED.OrganizationDepartmentId,ED.EmployeeTypeId from shrm.tEmployeeMaster EM 
INNER JOIN sHRM.tEmployeeJobDetail ED ON ED.EmployeeId = EM.Id 
Where (ED.OrganizationDepartmentId =@rOrganizationDepartmentId Or @rOrganizationDepartmentId= 0 )
AND (ED.EmployeeTypeId = @rEmployeeTypeId OR @rEmployeeTypeId = 0 )
AND  EM.ORgId = @rOrgId 
AND (EM.StatusId = @rEmployeeStatusId) OR (ISNULL(@rEmployeeStatusId,0)=0)
AND ISNULL(EM.IsOtherUser,0) = 0 
AND ((ED.OrgGroupDepartmentId = @OrgGroupDepartmentId) OR (@OrgGroupDepartmentId=0)) 



DECLARE @lCount int
DECLARE @lCount1 int
Declare @lQuery nvarchar(Max)
DECLARE @strQuery nvarchar(Max)
DECLARE @lDate date
DECLARE @lDay as nvarchar(3)
DECLARE @lBatchID int
DECLARE @lEmployeeId bigint
DECLARE @lEmpCount int
DECLARE @lEmpDepartmentID int

DECLARE @TempDate TABLE(Id int identity,Idate date)
insert into @TempDate
SELECT  TOP (DATEDIFF(DAY, @rFromDate, @rToDate) + 1)
        Date = DATEADD(DAY, ROW_NUMBER() OVER(ORDER BY a.object_id) - 1, @rFromDate)
FROM    sys.all_objects a CROSS JOIN sys.all_objects b;

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

truncate table #TempMonthTrans

SELECT @lBatchID = Id from sSetup.tBatchMaster Where OrgId = @rOrgId AND IsActive = 1

Select @lCount = Max(Id) from @TempDate
Select @lEmpCount = Max(Id) from @TableEmployee
While (@lEmpCount > 0)
	BEGIN
		SELECT @lEmployeeId = EmployeeId,@lEmpDepartmentID = OrganizationDepartmentId  From @TableEmployee Where Id = @lEmpCount	
	set @lCount1 = 1
	while (@lCount1 <= @lCount)
	begin			
		Select @lDate = Idate from @TempDate Where Id = @lCount1
		Select @lDay  = RIGHT('00' + CAST(DATEPART(dd,@lDate) AS varchar(2)), 2)

		DECLARE @weekoffstatus nvarchar(20)

		--SET @weekoffstatus = [sHrm].[fWeekHOffGetBio](@rEmployeeId , @rForYear ,@rForMonth ,@rDay ,@rBatchId ,@rDepartmentId ,@rOrgId , @rBiometricStatus )
		SET @weekoffstatus = [sHrm].[fWeekHOffGetBio](@lEmployeeId,Year(@lDate)  ,Month(@lDate), @lDay, @lBatchId,@lEmpDepartmentID,@rOrgId)		
		--SET @weekoffstatus = [sHrm].[fWeekHOffGetBio](@lEmployeeId,Year(''' + convert(nvarchar(15),@lDate) + convert(nvarchar(15),@lEmployeeId) + ', Year(''' + convert(nvarchar(15),@lDate) + '''),Month(''' + convert(nvarchar(15),@lDate) + '''),' + @lDay + ',' + convert(nvarchar(15),@lBatchId) + ',ED.OrganizationDepartmentId,' + convert(nvarchar(15),@rOrgId) + ')

		set @lQuery =  ' INSERT INTO #TempMonthTrans
						SELECT  ' + convert(nvarchar(15),@lEmployeeId) + ',''' + convert(nvarchar(15),@lDate) + ''',
						'''+''+''',
						substring(DATENAME( dw, ''' + convert(nvarchar(15),@lDate) + '''),1,3) AS DN1,
						CAse 
						When ''' +@weekoffstatus +''' in (''H'') AND D'+ convert(nvarchar(15),@lDay) +' <> ''A'' then D'+convert(nvarchar(15),@lDay) +'
						When ''' +@weekoffstatus +''' in (''H'') AND D'+convert(nvarchar(15),@lDay)+'_IN != ''00:00'' then ''PH''
						When ''' +@weekoffstatus +''' in (''W'')  AND D'+convert(nvarchar(15),@lDay)+'_IN != ''00:00'' then ''PW''
						When ''' +@weekoffstatus +''' in (''W'') AND D'+ convert(nvarchar(15),@lDay) +' = ''PW'' AND D'+convert(nvarchar(15),@lDay)+'_IN = ''00:00'' then ''W''
						When ''' +@weekoffstatus +''' not in (''W'') AND D'+ convert(nvarchar(15),@lDay) +' = ''PW'' then ''P''
						When ''' +@weekoffstatus +''' not in (''W'') AND D'+ convert(nvarchar(15),@lDay) +' = ''W'' AND D'+convert(nvarchar(15),@lDay)+'_IN != ''00:00'' then ''P''
						When ''' +@weekoffstatus +''' not in (''W'') AND D'+ convert(nvarchar(15),@lDay) +' =''W'' AND D'+convert(nvarchar(15),@lDay)+'_IN = ''00:00'' then ''A''
						When ''' +@weekoffstatus +''' Not in (''-'',''XX'') 
						Then ''' +@weekoffstatus +''' 
						Else D'+convert(nvarchar(15),@lDay)+' End D'+convert(nvarchar(15),@lDay)+',D'+convert(nvarchar(15),@lDay)+'_IN,D'+convert(nvarchar(15),@lDay)+'_OUT,D'+convert(nvarchar(15),@lDay)+'_O,D'+convert(nvarchar(15),@lDay)+'_L,D'+convert(nvarchar(15),@lDay)+'_T,D'+convert(nvarchar(15),@lDay)+'_E 
						FROM sBiometric.tMonthTrans T1 
						INNER JOIN sHRM.tEmployeeJobDetail ED ON ED.EmployeeId = T1.EmployeeId AND (ED.OrganizationDepartmentId ='''+CONVERT(nvarchar(15),@rOrganizationDepartmentId)+''' Or '''+CONVERT(nvarchar(15),@rOrganizationDepartmentId)+'''= 0 )AND (ED.OrgGroupDepartmentId ='''+CONVERT(nvarchar(15),@OrgGroupDepartmentId)+''' Or '''+CONVERT(nvarchar(15),@OrgGroupDepartmentId)+'''= 0 )
						WHERE T1.EmployeeId =' + convert(nvarchar(15),@lEmployeeId) + ' AND ATTN_DT = cast(rtrim(YEAR(''' + convert(nvarchar(15),@lDate) + ''') *10000+ Month(''' + convert(nvarchar(15),@lDate) + ''') *100+ 01) as datetime) AND (ISNULL(T1.SourceTypeId,95) = 95 OR T1.SourceTypeId = 0)'				
		--print @lQuery				
		Execute(@lQuery )
		set @lCount1 = @lCount1 + 1
	end
		SET @lEmpCount = @lEmpCount - 1			
	END
	--Select * from #TempMonthTrans
	
	UPDATE tmp 
	SET PresentStatus='A'
	FROM  #TempMonthTrans tmp
	INNER JOIN sHrm.tLeave L ON tmp.EmployeeId=L.EmployeeId
	INNER JOIN sHrm.tLeaveTypeMaster LTM ON LTM.Id = L.LeaveTypeId
	WHERE L.StatusId = 550 AND L.EmployeeId = tmp.EmployeeId AND CAST(Attn_Date AS DATE) BETWEEN L.FromDate AND L.ToDate

	UPDATE tmp 
	SET Leave=LTM.Code + '/' + CASE WHEN L.LeavePeriodId = 1 THEN '1' WHEN L.LeavePeriodId = 2  THEN  '0.5' ELSE '0.25' END
	FROM  #TempMonthTrans tmp
	INNER JOIN sHrm.tLeave L ON tmp.EmployeeId=L.EmployeeId
	INNER JOIN sHrm.tLeaveTypeMaster LTM ON LTM.Id = L.LeaveTypeId
	WHERE L.StatusId = 550 AND L.EmployeeId = tmp.EmployeeId AND CAST(Attn_Date AS DATE) BETWEEN L.FromDate AND L.ToDate


	--Select * from #TempMonthTrans

	SET @strQuery = 'select  Day(T.Attn_Date), T.*,isnull(A.TotAbsent,0) AS TotAbsent,isnull(TotPresent,0) AS TotPresent,A1.TotWeekOff,isnull(A6.TotEarly,0) as TotEarly,
	isnull(TotHalfDay,0) AS TotHalfDay,Isnull(TotHoliday,0) AS TotHoliday,isnull(CLLeave,0) AS CLLeave,Isnull(LV.LeaveCode,'''') as LeaveCode1,isnull(LV1.LeaveCode1,'''') AS LeaveCode,
	Emp.Code AS EmpCode,Emp.FirstName +'' '' + Emp.MiddleName +'' ''+ Emp.LastName  AS EmpName,isnull(TotEarly,0) AS TotEarly,
	DM.Displaytitle DeptName,
	' + convert(nvarchar(10),@rIsFirstIn) + ' AS IsFirstIn,
	' + convert(nvarchar(10),@rIsLastOut) + ' AS IsLastOut,
	' +  convert(nvarchar(10),@rIsOT) + ' AS IsOT,
	' +  convert(nvarchar(10),@rIsLateBy) + '	AS IsLateBy,
	' +  convert(nvarchar(10),@rIsEarlyBy) + ' AS IsEarlyBy,
	' +  convert(nvarchar(10),@rIsDuration) + '  AS IsDuration,
	OM.Id AS OrgId,
	OM.Title AS OrganizationTitle
	from #TempMonthTrans T
	INNER JOIN sHRM.tEmployeeMaster Emp on Emp.Id = T.EmployeeId AND ISNULL(EMP.IsOtherUser,0) = 0 
	INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = Emp.OrgID
	LEFT JOIN sHRM.tEmployeeJobDetail ED ON ED.EmployeeId = Emp.Id 
	LEFT JOIN sSetup.tDepartmentMaster DM ON DM.Id = ED.OrganizationDepartmentId
	LEFT JOIN sHRM.tEmployeeDesignationMaster EDM ON EDM.Id = ED.EmployeeDesignationId 
	LEFT Join (Select COUNT(*) AS TotPresent,EmployeeId from #TempMonthTrans Where PresentStatus IN (''P'',''PW'',''PH'') group by EmployeeId,PresentStatus) A4 ON A4.EmployeeId = T.employeeID
	LEFT Join (Select COUNT(*) AS TotEarly,EmployeeId from #TempMonthTrans Where PresentStatus IN (''E'') group by EmployeeId,PresentStatus) A6 ON A6.EmployeeId = T.employeeID
	LEFT Join (Select COUNT(*) AS TotAbsent,EmployeeId from #TempMonthTrans Where PresentStatus Like ''A'' group by EmployeeId,PresentStatus) A ON A.EmployeeId = T.employeeID
	LEFT Join (Select COUNT(*) AS TotWeekOff,EmployeeId from #TempMonthTrans Where PresentStatus IN (''W'',''PW'',''PHW'') group by EmployeeId) A1 ON A1.EmployeeId = T.employeeID
	LEFT Join (Select COUNT(*) AS TotHalfDay,EmployeeId from #TempMonthTrans Where PresentStatus Like ''HD'' group by EmployeeId,PresentStatus) A3 ON A3.EmployeeId = T.employeeID
    LEFT Join (Select COUNT(*) AS TotHoliday,EmployeeId from #TempMonthTrans Where PresentStatus Like ''H'' group by EmployeeId,PresentStatus) A5 ON A5.EmployeeId = T.employeeID		
	
	LEFT Join (Select sum(NoOfLeave) AS CLLeave,EmployeeId,LT.Code as LeaveCode from shrm.tLeave L inner join shrm.tLeaveTypeMaster LT ON LT.Id=L.LeaveTypeId 
	Where FromDate>=''' + Convert(nvarchar(12),@rFromDate) + ''' AND FromDate<=''' + Convert(nvarchar(12),@rToDate) + ''' GRoup By EmployeeId,LT.Code ) AS LV ON LV.EmployeeId = T.EmployeeId

	LEFT Join (select   distinct  EmployeeId,
    ISNULL( stuff((
        select Distinct '','' + LT.Code + '':'' + Convert(nvarchar(10),Sum(NoOfLeave)) 
        from shrm.tLeave L inner join shrm.tLeaveTypeMaster LT ON LT.Id=L.LeaveTypeId
        where  (FromDate >= ''' + Convert(nvarchar(12),@rFromDate) + ''' OR (ISNULL(''' + Convert(nvarchar(12),@rFromDate) + ''','''')='''')) 
        AND (ToDate <= ''' + Convert(nvarchar(12),@rToDate) + ''' OR (ISNULL(''' + Convert(nvarchar(12),@rToDate) + ''','''')='''') )
        AND L.EmployeeId = L1.EmployeeId AND L.StatusId= 550
        group by LT.Code
        for xml path('''')
    ),1,1,''''),'''') as LeaveCode1
	from shrm.tLeave L1 
	inner join shrm.tLeaveTypeMaster LT ON LT.Id=L1.LeaveTypeId AND L1.StatusId=550
	group by EmployeeId,LT.Code) AS LV1 ON LV1.EmployeeId = T.EmployeeId 
	WHERE (T.EmployeeId = ' + convert(nvarchar(15),@rEmployeeId) + ' OR ' + convert(nvarchar(15),@rEmployeeId) + ' = 0) AND (len((''' + @rGRadeId + '''))= 1 AND EmployeeGradeId > 0 ) Or
   (len((''' + @rGRadeId + ''')) > 1 AND EmployeeGradeId in(' + convert(nvarchar(100),@rGRadeId) + ')) AND (OM.OrgGroupId = ' + convert(nvarchar(15),@rOrgGroupId) + ') Order By T.EmployeeId,T.Attn_Date' 
	--WHERE 1=1 and (ED.EmployeeGradeId in (' + convert(nvarchar(100),@rGRadeId) + ') OR (' + convert(nvarchar(100),@rGRadeId) + ') = 0) )' 
	--print @strQuery
	execute (@strQuery)
	
	DROP TABLE #TempMonthTrans
	--select  
	--@rBuilder1 as Builder1,
	--@rBuilder2 as Builder2,
	--'' as Attn_Date,
	--'' as Leave,
	--'' as EmployeeId,	
	--'' as DayNumber ,
	--'' as PresentStatus ,
	--'' as FirstIn,
	--'' as LastOut,
	--'' as OverTime,
	--'' as LateBy,
	--'' as Duration,
	--'' as EarlyBy,
	--'' as TotPresent,
	--'' as TotWeekOff,
	--'' as TotHalfDay,
	--'' as TotHoliday,
	--'' AS TotEarly,
	--'' as CLLeave,
	--'' as LeaveCode,
	--'' as EmpCode,
	--'' as EmpName,
	--'' as DeptName,
	--'' as TotAbsent,
	--'' as IsFirstIn,
	--'' as IsLastOut,
	--'' as IsOT,
	--'' as IsLateBy,
	--'' as IsEarlyBy,
	--'' as IsDuration,
	--'' as OrgId,
	--'' as OrganizationTitle
END
GO
PRINT N'Altering [sCommunication].[pQueryQueueGet]...';


GO
 
ALTER PROCEDURE [sCommunication].[pQueryQueueGet]
	 
	 @rQueryCategoryId int = 0,
	 --@rCreatedUserId bigint,
	 @rOrgGroupBatchId int,
	 @rOrgGroupId smallint,
	 @rQueryId bigint,
	 @rUserSourceId bigint,
	 @rMyList bit,
	 @rStatusId int = 0,
	 @rSourceId bigint = 0,
	 @rSubjectId int = 0,
	 @rFromDate date ='',
	 @rToDate date =''
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
		
BEGIN 
IF(@rMyList=0)
BEGIN
	SELECT 
			QCM.Id AS QueryCategoryId,
			ISNULL(QCM.Title,'') AS QueryCategoryMaster,
			QM.Title,
			QM.Remark,
			QM.CreatedDateTime,
			QM.StatusId,
			ISNULL(sm.Title,'') AS StatusMaster,
			QM.Id AS QueryId,
			QM.IsUserView,
			QM.IsAssigneeView,
			ODM.Title AS Department,
			U.DisplayTitle AS SourceName, 
			U.SourceTypeId, 
			'Employee' AS SourceType,
			QM.CreatedUserId AS QueryCreatedUserId,
			OM.DisplayTitle AS OrgName,
			EM.Code AS Code,
			(SELECT TOP 1 U.DisplayTitle AS SourceName FROM sCommunication.tQueryComment QC INNER JOIN sSecurity.tUser U ON U.Id=QC.CreatedUserId WHERE QC.QueryId=QM.Id AND  QM.CreatedUserId != QC.CreatedUserId ORDER BY QC.CreatedDateTime DESC) AS AnswerUserName,
			(SELECT TOP 1 CONVERT(NVARCHAR,QC.CreatedDateTime,103) AS SourceName FROM sCommunication.tQueryComment QC INNER JOIN sSecurity.tUser U ON U.Id=QC.CreatedUserId WHERE QC.QueryId=QM.Id AND QM.CreatedUserId != QC.CreatedUserId ORDER BY QC.CreatedDateTime DESC) AS AnswerUserDate,
			(CASE WHEN QM.StatusId=210 then  U.DisplayTitle ELSE '' END) AS UserName
	FROM 
			sCommunication.tQuery QM
		INNER JOIN sCommunication.tQueryCategoryMaster QCM ON QM.QueryCategoryId=QCM.Id
        INNER JOIN sCommon.tStatusMaster SM ON SM.Id=QM.StatusId
        INNER JOIN sSecurity.tUser U ON U.Id=QM.CreatedUserId
        INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id = U.SourceId AND U.SourceTypeId = 95
        INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = U.SourceId AND U.SourceTypeId = 95
        INNER JOIN sSetup.tDepartmentMaster ODM ON EJD.OrganizationDepartmentId=ODM.Id  
        INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = ODM.OrgId
        
	WHERE 
  
			((QCM.Id = @rQueryCategoryId) OR (@rQueryCategoryId = 0))
		AND ((QM.Id = @rQueryId) OR (@rQueryId = 0)) 
		AND (QCM.OrgGroupId = @rOrgGroupId) 
		AND (QM.OrgGroupBatchId = @rOrgGroupBatchId)
	    AND ((QM.StatusId=@rStatusId) OR (@rStatusId=0))
	    AND ((EJD.EmployeeId=@rSourceId) OR (@rSourceId=0))
		AND ((QM.CreatedDateTime >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
		AND ((QM.CreatedDateTime <= @rToDate) OR (ISNULL(@rToDate,'')=''))
		AND ISNULL(EM.IsOtherUser,0) = 0
	UNION 

	SELECT 
			QCM.Id AS QueryCategoryId,
			ISNULL(QCM.Title,'') AS QueryCategoryMaster,
			QM.Title,
			QM.Remark,
			QM.CreatedDateTime,
			QM.StatusId,
			ISNULL(sm.Title,'') AS StatusMaster,
			QM.Id AS QueryId,
			QM.IsUserView,
			QM.IsAssigneeView,
			SA.ClassName + ' ' + SA.DivisionName  AS Department,
			U.DisplayTitle AS SourceName,
			U.SourceTypeId,
			'Student' AS SourceType,
			QM.CreatedUserId AS QueryCreatedUserId,
			OM.DisplayTitle AS OrgName,
			SA.Code,
			(SELECT TOP 1 U.DisplayTitle AS SourceName FROM sCommunication.tQueryComment QC INNER JOIN sSecurity.tUser U ON U.Id=QC.CreatedUserId WHERE QC.QueryId=QM.Id AND  QM.CreatedUserId != QC.CreatedUserId ORDER BY QC.CreatedDateTime DESC) AS AnswerUserName,
			(SELECT TOP 1 CONVERT(NVARCHAR,QC.CreatedDateTime,103) AS SourceName FROM sCommunication.tQueryComment QC INNER JOIN sSecurity.tUser U ON U.Id=QC.CreatedUserId WHERE QC.QueryId=QM.Id AND QM.CreatedUserId != QC.CreatedUserId ORDER BY QC.CreatedDateTime DESC) AS AnswerUserDate,
			(CASE WHEN QM.StatusId=210 then  U.DisplayTitle ELSE '' END) AS UserName
			
	FROM 
			sCommunication.tQuery QM
        INNER JOIN sCommunication.tQueryCategoryMaster QCM ON QM.QueryCategoryId=QCM.Id
        INNER JOIN sCommon.tStatusMaster SM ON SM.Id=QM.StatusId
        INNER JOIN sSecurity.tUser U ON U.Id=QM.CreatedUserId
        INNER JOIN sStudent.vStudentAcademic SA ON SA.StudentId = U.SourceId AND U.SourceTypeId = 2003 AND SA.OrgGroupBatchId = @rOrgGroupBatchId AND SA.IsActiveBatch = 1
        INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SA.OrgId
	WHERE 
			((QCM.Id = @rQueryCategoryId) OR (@rQueryCategoryId = 0))
		AND ((QM.Id = @rQueryId) OR (@rQueryId = 0)) 
		AND (QCM.OrgGroupId=@rOrgGroupId)  
		AND (QM.OrgGroupBatchId=@rOrgGroupBatchId)
		AND ((QM.StatusId=@rStatusId) OR (@rStatusId=0))
		AND ((SA.StudentId=@rSourceId) OR (@rSourceId=0))
		AND ((QM.CreatedDateTime >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
		AND ((QM.CreatedDateTime <= @rToDate) OR (ISNULL(@rToDate,'')=''))
		
		
	
		UNION
		SELECT 
			QCM.Id AS QueryCategoryId,
			ISNULL(QCM.Title,'') AS QueryCategoryMaster,
			QM.Title,
			QM.Remark,
			QM.CreatedDateTime,
			QM.StatusId,
			ISNULL(sm.Title,'') AS StatusMaster,
			QM.Id AS QueryId,
			QM.IsUserView,
			QM.IsAssigneeView,
			SA.ClassName + ' ' + SA.DivisionName  AS Department,
			U.DisplayTitle AS SourceName,
			U.SourceTypeId,
			'Student' AS SourceType,
			QM.CreatedUserId AS QueryCreatedUserId,
			OM.DisplayTitle AS OrgName,
			SA.Code,
			(SELECT TOP 1 U.DisplayTitle AS SourceName FROM sCommunication.tQueryComment QC INNER JOIN sSecurity.tUser U ON U.Id=QC.CreatedUserId WHERE QC.QueryId=QM.Id AND  QM.CreatedUserId != QC.CreatedUserId ORDER BY QC.CreatedDateTime DESC) AS AnswerUserName,
			(SELECT TOP 1 CONVERT(NVARCHAR,QC.CreatedDateTime,103) AS SourceName FROM sCommunication.tQueryComment QC INNER JOIN sSecurity.tUser U ON U.Id=QC.CreatedUserId WHERE QC.QueryId=QM.Id AND QM.CreatedUserId != QC.CreatedUserId ORDER BY QC.CreatedDateTime DESC) AS AnswerUserDate,
			(CASE WHEN QM.StatusId=210 then  U.DisplayTitle ELSE '' END) AS UserName
	FROM 
		sCommunication.tQuery QM
        INNER JOIN sCommunication.tQueryCategoryMaster QCM ON QM.QueryCategoryId=QCM.Id
        INNER JOIN sCommon.tStatusMaster SM ON SM.Id=QM.StatusId
        INNER JOIN sSecurity.tUser U ON U.Id=QM.CreatedUserId
        INNER JOIN sStudent.vStudentAcademic SA ON SA.StudentId = U.SourceId AND SA.IsActiveBatch = 1 --AND U.SourceTypeId = 2003 AND SA.OrgGroupBatchId = 120100101 
        INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SA.OrgId
	WHERE 
	       ((QCM.Id = @rQueryCategoryId) OR (@rQueryCategoryId = 0))
			AND ((QM.Id = @rQueryId) OR (@rQueryId = 0)) 
			AND (QCM.OrgGroupId=@rOrgGroupId)  
			AND (QM.OrgGroupBatchId=@rOrgGroupBatchId)
			--AND QueryCategoryId IN (select QueryCategoryId FROM sCommunication.tQueryCategoryAssignedTo where  RIGHT(SourceId,2) = 25 AND SourceTypeId = 2015)
			AND ((QM.StatusId=@rStatusId) OR (@rStatusId=0))
			AND ((SA.StudentId=@rSourceId) OR (@rSourceId=0))
			AND ((QM.FromSourceId=@rUserSourceId) OR (@rUserSourceId=0)) and QM.FromSourceTypeId=2003 and QM.OrgGroupBatchId=@rOrgGroupBatchId
			AND ((QM.CreatedDateTime >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
			AND ((QM.CreatedDateTime <= @rToDate) OR (ISNULL(@rToDate,'')=''))
		
		UNION
		
		
		SELECT 
			QCM.Id AS QueryCategoryId,
			ISNULL(QCM.Title,'') AS QueryCategoryMaster,
			QM.Title,
			QM.Remark,
			QM.CreatedDateTime,
			QM.StatusId,
			ISNULL(sm.Title,'') AS StatusMaster,
			QM.Id AS QueryId,
			QM.IsUserView,
			QM.IsAssigneeView,
			ODM.Title AS Department,
			U.DisplayTitle AS SourceName, 
			U.SourceTypeId, 
			'Employee' AS SourceType,
			QM.CreatedUserId AS QueryCreatedUserId,
			OM.DisplayTitle AS OrgName,
			EM.Code,
			(SELECT TOP 1 U.DisplayTitle AS SourceName FROM sCommunication.tQueryComment QC INNER JOIN sSecurity.tUser U ON U.Id=QC.CreatedUserId WHERE QC.QueryId=QM.Id AND  QM.CreatedUserId != QC.CreatedUserId ORDER BY QC.CreatedDateTime DESC) AS AnswerUserName,
			(SELECT TOP 1 CONVERT(NVARCHAR,QC.CreatedDateTime,103) AS SourceName FROM sCommunication.tQueryComment QC INNER JOIN sSecurity.tUser U ON U.Id=QC.CreatedUserId WHERE QC.QueryId=QM.Id AND QM.CreatedUserId != QC.CreatedUserId ORDER BY QC.CreatedDateTime DESC) AS AnswerUserDate,
			(CASE WHEN QM.StatusId=210 then  U.DisplayTitle ELSE '' END) AS UserName
	FROM 
			sCommunication.tQuery QM
		INNER JOIN sCommunication.tQueryCategoryMaster QCM ON QM.QueryCategoryId=QCM.Id
        INNER JOIN sCommon.tStatusMaster SM ON SM.Id=QM.StatusId
        INNER JOIN sSecurity.tUser U ON U.Id=QM.CreatedUserId  
        INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id = QM.AssignedToEmployeeId 
        INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id
        INNER JOIN sSetup.tDepartmentMaster ODM ON EJD.OrganizationDepartmentId=ODM.Id 
        INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = EM.OrgId
	
	 WHERE 
	 
	 ((QCM.Id = @rQueryCategoryId) OR (@rQueryCategoryId = 0))
	 AND ((QM.Id = @rQueryId) OR (@rQueryId = 0)) 
	 AND (QCM.OrgGroupId=@rOrgGroupId)  
	 AND (QM.OrgGroupBatchId=@rOrgGroupBatchId)
	 AND ((QM.StatusId=@rStatusId) OR (@rStatusId=0))
	 
	 AND ((QM.AssignedToEmployeeId=@rUserSourceId) OR (@rUserSourceId=0))
	 AND ISNULL(EM.IsOtherUser,0) = 0
	 AND ((QM.CreatedDateTime >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
	 AND ((QM.CreatedDateTime <= @rToDate) OR (ISNULL(@rToDate,'')=''))
	 ORDER BY QM.CreatedDateTime DESC
	 --and QM.FromSourceTypeId=95
		
		
END
ELSE IF(@rMyList=1)
BEGIN

	SELECT 
			QCM.Id AS QueryCategoryId,
			ISNULL(QCM.Title,'') AS QueryCategoryMaster,
			QM.Title,
			QM.Remark,
			QM.CreatedDateTime,
			QM.StatusId,
			ISNULL(sm.Title,'') AS StatusMaster,
			QM.Id AS QueryId,
			QM.IsUserView,
			QM.IsAssigneeView,
			ODM.Title AS Department,
			U.DisplayTitle AS SourceName, 
			U.SourceTypeId, 
			'Employee' AS SourceType,
			QM.CreatedUserId AS QueryCreatedUserId,
			OM.DisplayTitle AS OrgName,
			EM.Code,
			(SELECT TOP 1 U.DisplayTitle AS SourceName FROM sCommunication.tQueryComment QC INNER JOIN sSecurity.tUser U ON U.Id=QC.CreatedUserId WHERE QC.QueryId=QM.Id AND  QM.CreatedUserId != QC.CreatedUserId ORDER BY QC.CreatedDateTime DESC) AS AnswerUserName,
			(SELECT TOP 1 CONVERT(NVARCHAR,QC.CreatedDateTime,103) AS SourceName FROM sCommunication.tQueryComment QC INNER JOIN sSecurity.tUser U ON U.Id=QC.CreatedUserId WHERE QC.QueryId=QM.Id AND QM.CreatedUserId != QC.CreatedUserId ORDER BY QC.CreatedDateTime DESC) AS AnswerUserDate,
			(CASE WHEN QM.StatusId=210 then  U.DisplayTitle ELSE '' END) AS UserName
	FROM 
			sCommunication.tQuery QM
		INNER JOIN sCommunication.tQueryCategoryMaster QCM ON QM.QueryCategoryId=QCM.Id
        INNER JOIN sCommon.tStatusMaster SM ON SM.Id=QM.StatusId
        INNER JOIN sSecurity.tUser U ON U.Id=QM.CreatedUserId
        INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id = U.SourceId AND U.SourceTypeId = 95
        INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = U.SourceId AND U.SourceTypeId = 95
        INNER JOIN sSetup.tDepartmentMaster ODM ON EJD.OrganizationDepartmentId=ODM.Id 
        INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = ODM.OrgId
	WHERE 
			((QCM.Id = @rQueryCategoryId) OR (@rQueryCategoryId = 0))
		AND ((QM.Id = @rQueryId) OR (@rQueryId = 0)) 
		AND (QCM.OrgGroupId = @rOrgGroupId)
		AND (QM.OrgGroupBatchId = @rOrgGroupBatchId)
	    --AND QueryCategoryId IN (select QueryCategoryId FROM sCommunication.tQueryCategoryAssignedTo where  SourceId = @rUserSourceId)
	    AND ((QM.StatusId=@rStatusId) OR (@rStatusId=0))
	    AND (( EJD.EmployeeId=@rUserSourceId) OR (@rUserSourceId=0))
		AND ((QM.CreatedDateTime >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
		AND ((QM.CreatedDateTime <= @rToDate) OR (ISNULL(@rToDate,'')=''))
		AND ISNULL(EM.IsOtherUser,0) = 0
	UNION 

	SELECT 
			QCM.Id AS QueryCategoryId,
			ISNULL(QCM.Title,'') AS QueryCategoryMaster,
			QM.Title,
			QM.Remark,
			QM.CreatedDateTime,
			QM.StatusId,
			ISNULL(sm.Title,'') AS StatusMaster,
			QM.Id AS QueryId,
			QM.IsUserView,
			QM.IsAssigneeView,
			SA.ClassName + ' ' + SA.DivisionName  AS Department,
			U.DisplayTitle AS SourceName,
			U.SourceTypeId,
			'Student' AS SourceType,
			QM.CreatedUserId AS QueryCreatedUserId,
			OM.DisplayTitle AS OrgName,
			SA.Code,
			(SELECT TOP 1 U.DisplayTitle AS SourceName FROM sCommunication.tQueryComment QC INNER JOIN sSecurity.tUser U ON U.Id=QC.CreatedUserId WHERE QC.QueryId=QM.Id AND  QM.CreatedUserId != QC.CreatedUserId ORDER BY QC.CreatedDateTime DESC) AS AnswerUserName,
			(SELECT TOP 1 CONVERT(NVARCHAR,QC.CreatedDateTime,103) AS SourceName FROM sCommunication.tQueryComment QC INNER JOIN sSecurity.tUser U ON U.Id=QC.CreatedUserId WHERE QC.QueryId=QM.Id AND QM.CreatedUserId != QC.CreatedUserId ORDER BY QC.CreatedDateTime DESC) AS AnswerUserDate,
			(CASE WHEN QM.StatusId=210 then  U.DisplayTitle ELSE '' END) AS UserName
	FROM 
		sCommunication.tQuery QM
        INNER JOIN sCommunication.tQueryCategoryMaster QCM ON QM.QueryCategoryId=QCM.Id
        INNER JOIN sCommon.tStatusMaster SM ON SM.Id=QM.StatusId
        INNER JOIN sSecurity.tUser U ON U.Id=QM.CreatedUserId
        INNER JOIN sStudent.vStudentAcademic SA ON SA.StudentId = U.SourceId AND U.SourceTypeId = 2003 AND SA.OrgGroupBatchId = @rOrgGroupBatchId AND SA.IsActiveBatch = 1
        INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SA.OrgId
	WHERE 
			((QCM.Id = @rQueryCategoryId) OR (@rQueryCategoryId = 0))
		AND ((QM.Id = @rQueryId) OR (@rQueryId = 0)) 
		AND (QCM.OrgGroupId=@rOrgGroupId)  
		AND (QM.OrgGroupBatchId=@rOrgGroupBatchId)
		AND QueryCategoryId IN (select QueryCategoryId FROM sCommunication.tQueryCategoryAssignedTo where  SourceId = @rUserSourceId AND SourceTypeId <> 2015)
		AND ((QM.StatusId=@rStatusId) OR (@rStatusId=0))
		AND ((SA.StudentId=@rSourceId) OR (@rSourceId=0))
		AND ((QM.CreatedDateTime >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
		AND ((QM.CreatedDateTime <= @rToDate) OR (ISNULL(@rToDate,'')=''))
	UNION 

	SELECT 
			QCM.Id AS QueryCategoryId,
			ISNULL(QCM.Title,'') AS QueryCategoryMaster,
			QM.Title,
			QM.Remark,
			QM.CreatedDateTime,
			QM.StatusId,
			ISNULL(sm.Title,'') AS StatusMaster,
			QM.Id AS QueryId,
			QM.IsUserView,
			QM.IsAssigneeView,
			SA.ClassName + ' ' + SA.DivisionName  AS Department,
			U.DisplayTitle AS SourceName,
			U.SourceTypeId,
			'Student' AS SourceType,
			QM.CreatedUserId AS QueryCreatedUserId,
			OM.DisplayTitle AS OrgName,
			SA.Code,
			(SELECT TOP 1 U.DisplayTitle AS SourceName FROM sCommunication.tQueryComment QC INNER JOIN sSecurity.tUser U ON U.Id=QC.CreatedUserId WHERE QC.QueryId=QM.Id AND  QM.CreatedUserId != QC.CreatedUserId ORDER BY QC.CreatedDateTime DESC) AS AnswerUserName,
			(SELECT TOP 1 CONVERT(NVARCHAR,QC.CreatedDateTime,103) AS SourceName FROM sCommunication.tQueryComment QC INNER JOIN sSecurity.tUser U ON U.Id=QC.CreatedUserId WHERE QC.QueryId=QM.Id AND QM.CreatedUserId != QC.CreatedUserId ORDER BY QC.CreatedDateTime DESC) AS AnswerUserDate,
			(CASE WHEN QM.StatusId=210 then  U.DisplayTitle ELSE '' END) AS UserName
	FROM 
		sCommunication.tQuery QM
        INNER JOIN sCommunication.tQueryCategoryMaster QCM ON QM.QueryCategoryId=QCM.Id
        INNER JOIN sCommon.tStatusMaster SM ON SM.Id=QM.StatusId
        INNER JOIN sSecurity.tUser U ON U.Id=QM.CreatedUserId
        INNER JOIN sStudent.vStudentAcademic SA ON SA.StudentId = U.SourceId AND U.SourceTypeId = 2003 AND SA.OrgGroupBatchId = @rOrgGroupBatchId AND SA.IsActiveBatch = 1
					AND SA.DivisionId IN (SELECT Id FROM sSetup.tDivisionMaster WHERE InchargeEmployeeId=@rUserSourceId)
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SA.OrgId			
	WHERE 
			((QCM.Id = @rQueryCategoryId) OR (@rQueryCategoryId = 0))
		AND ((QM.Id = @rQueryId) OR (@rQueryId = 0)) 
		AND (QCM.OrgGroupId=@rOrgGroupId)  
		AND (QM.OrgGroupBatchId=@rOrgGroupBatchId)
		AND QueryCategoryId IN (select QueryCategoryId FROM sCommunication.tQueryCategoryAssignedTo where  RIGHT(SourceId,2) = 24 AND SourceTypeId = 2015)
		AND ((QM.StatusId=@rStatusId) OR (@rStatusId=0))
		AND ((SA.StudentId=@rSourceId) OR (@rSourceId=0))
		AND ((QM.CreatedDateTime >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
		AND ((QM.CreatedDateTime <= @rToDate) OR (ISNULL(@rToDate,'')=''))
	UNION 

	SELECT 
			QCM.Id AS QueryCategoryId,
			ISNULL(QCM.Title,'') AS QueryCategoryMaster,
			QM.Title,
			QM.Remark,
			QM.CreatedDateTime,
			QM.StatusId,
			ISNULL(sm.Title,'') AS StatusMaster,
			QM.Id AS QueryId,
			QM.IsUserView,
			QM.IsAssigneeView,
			SA.ClassName + ' ' + SA.DivisionName  AS Department,
			U.DisplayTitle AS SourceName,
			U.SourceTypeId,
			'Student' AS SourceType,
			QM.CreatedUserId AS QueryCreatedUserId,
			OM.DisplayTitle AS OrgName,
			SA.Code,
			(SELECT TOP 1 U.DisplayTitle AS SourceName FROM sCommunication.tQueryComment QC INNER JOIN sSecurity.tUser U ON U.Id=QC.CreatedUserId WHERE QC.QueryId=QM.Id AND  QM.CreatedUserId != QC.CreatedUserId ORDER BY QC.CreatedDateTime DESC) AS AnswerUserName,
			(SELECT TOP 1 CONVERT(NVARCHAR,QC.CreatedDateTime,103) AS SourceName FROM sCommunication.tQueryComment QC INNER JOIN sSecurity.tUser U ON U.Id=QC.CreatedUserId WHERE QC.QueryId=QM.Id AND QM.CreatedUserId != QC.CreatedUserId ORDER BY QC.CreatedDateTime DESC) AS AnswerUserDate,
			(CASE WHEN QM.StatusId=210 then  U.DisplayTitle ELSE '' END) AS UserName
	FROM 
		sCommunication.tQuery QM
        INNER JOIN sCommunication.tQueryCategoryMaster QCM ON QM.QueryCategoryId=QCM.Id
        INNER JOIN sCommon.tStatusMaster SM ON SM.Id=QM.StatusId
        INNER JOIN sSecurity.tUser U ON U.Id=QM.CreatedUserId
        INNER JOIN sStudent.vStudentAcademic SA ON SA.StudentId = U.SourceId AND U.SourceTypeId = 2003 AND SA.OrgGroupBatchId = @rOrgGroupBatchId AND SA.IsActiveBatch = 1
        INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SA.OrgId
	WHERE 
			((QCM.Id = @rQueryCategoryId) OR (@rQueryCategoryId = 0))
		AND ((QM.Id = @rQueryId) OR (@rQueryId = 0)) 
		AND (QCM.OrgGroupId=@rOrgGroupId)  
		AND (QM.OrgGroupBatchId=@rOrgGroupBatchId)
		AND QueryCategoryId IN (select QueryCategoryId FROM sCommunication.tQueryCategoryAssignedTo where  RIGHT(SourceId,2) = 25 AND SourceTypeId = 2015)
		AND ((QM.StatusId=@rStatusId) OR (@rStatusId=0))
		AND ((SA.StudentId=@rSourceId) OR (@rSourceId=0))
		AND ((QM.CreatedDateTime >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
		AND ((QM.CreatedDateTime <= @rToDate) OR (ISNULL(@rToDate,'')=''))
		
		
		UNION 

	SELECT 
			QCM.Id AS QueryCategoryId,
			ISNULL(QCM.Title,'') AS QueryCategoryMaster,
			QM.Title,
			QM.Remark,
			QM.CreatedDateTime,
			QM.StatusId,
			ISNULL(sm.Title,'') AS StatusMaster,
			QM.Id AS QueryId,
			QM.IsUserView,
			QM.IsAssigneeView,
			SA.ClassName + ' ' + SA.DivisionName  AS Department,
			U.DisplayTitle AS SourceName,
			U.SourceTypeId,
			'Student' AS SourceType,
			QM.CreatedUserId AS QueryCreatedUserId,
			OM.DisplayTitle AS OrgName,
			SA.Code,
			(SELECT TOP 1 U.DisplayTitle AS SourceName FROM sCommunication.tQueryComment QC INNER JOIN sSecurity.tUser U ON U.Id=QC.CreatedUserId WHERE QC.QueryId=QM.Id AND  QM.CreatedUserId != QC.CreatedUserId ORDER BY QC.CreatedDateTime DESC) AS AnswerUserName,
			(SELECT TOP 1 CONVERT(NVARCHAR,QC.CreatedDateTime,103) AS SourceName FROM sCommunication.tQueryComment QC INNER JOIN sSecurity.tUser U ON U.Id=QC.CreatedUserId WHERE QC.QueryId=QM.Id AND QM.CreatedUserId != QC.CreatedUserId ORDER BY QC.CreatedDateTime DESC) AS AnswerUserDate,
			(CASE WHEN QM.StatusId=210 then  U.DisplayTitle ELSE '' END) AS UserName
	FROM 
		sCommunication.tQuery QM
        INNER JOIN sCommunication.tQueryCategoryMaster QCM ON QM.QueryCategoryId=QCM.Id
        INNER JOIN sCommon.tStatusMaster SM ON SM.Id=QM.StatusId
        INNER JOIN sSecurity.tUser U ON U.Id=QM.CreatedUserId
        INNER JOIN sStudent.vStudentAcademic SA ON SA.StudentId = U.SourceId AND SA.IsActiveBatch = 1 --AND U.SourceTypeId = 2003 AND SA.OrgGroupBatchId = 120100101 
        INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SA.OrgId
	WHERE 
	       ((QCM.Id = @rQueryCategoryId) OR (@rQueryCategoryId = 0))
			AND ((QM.Id = @rQueryId) OR (@rQueryId = 0)) 
			AND (QCM.OrgGroupId=@rOrgGroupId)  
			AND (QM.OrgGroupBatchId=@rOrgGroupBatchId)
			--AND QueryCategoryId IN (select QueryCategoryId FROM sCommunication.tQueryCategoryAssignedTo where  RIGHT(SourceId,2) = 25 AND SourceTypeId = 2015)
			AND ((QM.StatusId=@rStatusId) OR (@rStatusId=0))
			AND ((SA.StudentId=@rSourceId) OR (@rSourceId=0))
			AND ((QM.FromSourceId=@rUserSourceId) OR (@rUserSourceId=0)) and QM.FromSourceTypeId=2003 and QM.OrgGroupBatchId=@rOrgGroupBatchId
			AND ((QM.CreatedDateTime >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
			AND ((QM.CreatedDateTime <= @rToDate) OR (ISNULL(@rToDate,'')=''))
		
   UNION
    
    
    
    
    
    SELECT 
			QCM.Id AS QueryCategoryId,
			ISNULL(QCM.Title,'') AS QueryCategoryMaster,
			QM.Title,
			QM.Remark,
			QM.CreatedDateTime,
			QM.StatusId,
			ISNULL(sm.Title,'') AS StatusMaster,
			QM.Id AS QueryId,
			QM.IsUserView,
			QM.IsAssigneeView,
			SA.ClassName + ' ' + SA.DivisionName  AS Department,
			U.DisplayTitle AS SourceName, 
			U.SourceTypeId, 
			'Employee' AS SourceType,
			QM.CreatedUserId AS QueryCreatedUserId,
			OM.DisplayTitle AS OrgName,
			SA.Code,
			(SELECT TOP 1 U.DisplayTitle AS SourceName FROM sCommunication.tQueryComment QC INNER JOIN sSecurity.tUser U ON U.Id=QC.CreatedUserId WHERE QC.QueryId=QM.Id AND  QM.CreatedUserId != QC.CreatedUserId ORDER BY QC.CreatedDateTime DESC) AS AnswerUserName,
			(SELECT TOP 1 CONVERT(NVARCHAR,QC.CreatedDateTime,103) AS SourceName FROM sCommunication.tQueryComment QC INNER JOIN sSecurity.tUser U ON U.Id=QC.CreatedUserId WHERE QC.QueryId=QM.Id AND QM.CreatedUserId != QC.CreatedUserId ORDER BY QC.CreatedDateTime DESC) AS AnswerUserDate,
			(CASE WHEN QM.StatusId=210 then  U.DisplayTitle ELSE '' END) AS UserName
			
	FROM 
		sCommunication.tQuery QM
        INNER JOIN sCommunication.tQueryCategoryMaster QCM ON QM.QueryCategoryId=QCM.Id
        INNER JOIN sCommon.tStatusMaster SM ON SM.Id=QM.StatusId
        INNER JOIN sSecurity.tUser U ON U.Id=QM.CreatedUserId AND U.SourceTypeId = 95
        INNER JOIN sStudent.vStudentAcademic SA ON SA.StudentId = U.SourceId AND U.SourceTypeId = 2003 AND SA.OrgGroupBatchId = @rOrgGroupBatchId AND SA.IsActiveBatch = 1
        INNER JOIN sAcademic.tTeacherSubjectDivision TSD ON TSD.DivisionId = SA.DivisionId AND (( TSD.EmployeeId = @rUserSourceId) OR (@rUserSourceId=0)) AND QM.SubjectId= TSD.SubjectId                  
        INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SA.OrgId
        
  WHERE 
	       ((QCM.Id = @rQueryCategoryId) OR (@rQueryCategoryId = 0))
			AND ((QM.Id = @rQueryId) OR (@rQueryId = 0)) 
			AND (QM.OrgGroupId=@rOrgGroupId)  
			AND (QM.OrgGroupBatchId=@rOrgGroupBatchId)
			--AND QueryCategoryId IN (select QueryCategoryId FROM sCommunication.tQueryCategoryAssignedTo where  RIGHT(SourceId,2) = 25 AND SourceTypeId = 2015)
			AND ((QM.StatusId=@rStatusId) OR (@rStatusId=0))
			AND ((SA.StudentId=@rSourceId) OR (@rSourceId=0))
			AND ((TSD.SubjectId=@rSubjectId) OR (@rSubjectId=0))
			--AND ((QM.FromSourceId=@rUserSourceId) OR (@rUserSourceId=0)) and QM.FromSourceTypeId=2003 and QM.OrgGroupBatchId=@rOrgGroupBatchId      
			AND ((QM.CreatedDateTime >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
			AND ((QM.CreatedDateTime <= @rToDate) OR (ISNULL(@rToDate,'')=''))
	 
	 UNION
    
    SELECT 
			QCM.Id AS QueryCategoryId,
			ISNULL(QCM.Title,'') AS QueryCategoryMaster,
			QM.Title,
			QM.Remark,
			QM.CreatedDateTime,
			QM.StatusId,
			ISNULL(sm.Title,'') AS StatusMaster,
			QM.Id AS QueryId,
			QM.IsUserView,
			QM.IsAssigneeView,
			ODM.Title AS Department,
			U.DisplayTitle AS SourceName, 
			U.SourceTypeId, 
			'Employee' AS SourceType,
			QM.CreatedUserId AS QueryCreatedUserId,
			OM.DisplayTitle AS OrgName,
			EM.Code,
			(SELECT TOP 1 U.DisplayTitle AS SourceName FROM sCommunication.tQueryComment QC INNER JOIN sSecurity.tUser U ON U.Id=QC.CreatedUserId WHERE QC.QueryId=QM.Id AND  QM.CreatedUserId != QC.CreatedUserId ORDER BY QC.CreatedDateTime DESC) AS AnswerUserName,
			(SELECT TOP 1 CONVERT(NVARCHAR,QC.CreatedDateTime,103) AS SourceName FROM sCommunication.tQueryComment QC INNER JOIN sSecurity.tUser U ON U.Id=QC.CreatedUserId WHERE QC.QueryId=QM.Id AND QM.CreatedUserId != QC.CreatedUserId ORDER BY QC.CreatedDateTime DESC) AS AnswerUserDate,
			(CASE WHEN QM.StatusId=210 then  U.DisplayTitle ELSE '' END) AS UserName
	FROM 	
		
		sCommunication.tQuery QM
		INNER JOIN sCommunication.tQueryCategoryMaster QCM ON QM.QueryCategoryId=QCM.Id
        INNER JOIN sCommon.tStatusMaster SM ON SM.Id=QM.StatusId
        INNER JOIN sSecurity.tUser U ON U.Id=QM.CreatedUserId  
        INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id = QM.AssignedToEmployeeId 
        INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id
        INNER JOIN sSetup.tDepartmentMaster ODM ON EJD.OrganizationDepartmentId=ODM.Id 
        INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = EM.OrgId
	
	 WHERE 
	 
	 ((QCM.Id = @rQueryCategoryId) OR (@rQueryCategoryId = 0))
	 AND ((QM.Id = @rQueryId) OR (@rQueryId = 0)) 
	 AND (QCM.OrgGroupId=@rOrgGroupId)  
	 AND (QM.OrgGroupBatchId=@rOrgGroupBatchId)
	 AND ((QM.StatusId=@rStatusId) OR (@rStatusId=0))
	 AND ((QM.AssignedToEmployeeId=@rUserSourceId) OR (@rUserSourceId=0))
	 AND ISNULL(EM.IsOtherUser,0) = 0
	 AND ((QM.CreatedDateTime >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
	 AND ((QM.CreatedDateTime <= @rToDate) OR (ISNULL(@rToDate,'')=''))
	 ORDER BY QM.CreatedDateTime DESC	
	 
	 
	 
	 
	 
	 
	 
		
END
END


--SELECT Q.CreatedUserId FROM sCommunication.tQueryCategoryMaster QCM INNER JOIN sCommunication.tQuery Q ON Q.QueryCategoryId = QCM.Id
GO
PRINT N'Altering [sFee].[pChargeReceiptDeletedLog]...';


GO
ALTER PROCEDURE [sFee].[pChargeReceiptDeletedLog]

	 @rChargeReceiptId bigint,
	 @rUserId bigint=0
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
	BEGIN TRY
	BEGIN TRANSACTION	
		--Charge Receipt Delete
		INSERT INTO 
			sAudit.tChargeDeleted 
		SELECT 
			CR.OrgId,
			Id,
			SA.Code,
			SourceTypeId,
			SourceId,
			SA.FirstName + ' ' + SA.MiddleName + ' ' + SA.LastName AS SourceName,
			Remark,
			ReceiptNumber,
			ReceiptDate,
			PayTypeId,
			ChequeNo,
			BankName,
			IsObsolete,
			CR.BatchId,
			(select Title from sFee.tChargeReceiptBookMaster CB where CB.Id=CR.ChargeReceiptBookId) AS ChargeReceiptBookName,			
			CR.OrgGroupBatchId,
			(SELECT DisplayTitle FROM sSecurity.tUser WHERE Id=CR.CreatedUserId),
			CreatedDateTime,
			(SELECT DisplayTitle FROM sSecurity.tUser WHERE Id=CR.CreatedUserId),
			UpdatedDateTime,		
			ReceiptAmount,
			ChequeDate,
			(SELECT DisplayTitle FROM sSecurity.tUser WHERE Id=@rUserId),
			sCommon.fGetDate(),
			CR.DeleteRemark
		FROM 
			sFee.tChargeReceipt CR
			INNER join sStudent.vStudentAcademic SA ON CR.SourceId=SA.AcademicId
		WHERE 
			Id=@rChargeReceiptId 
		
		-- Charge Receipt Detail Delete
		INSERT INTO 
			sAudit.tChargeDetailDelete 
		SELECT
			ChargeReceiptId,
			CM.Title,
			Amount
		FROM
			sFee.tChargeReceipt CR 
			INNER JOIN sFee.tChargeReceiptDetail CRD ON CRD.ChargeReceiptId=CR.Id 
			INNER JOIN sFee.tChargeMaster CM ON CM.Id=CRD.ChargeId 
			INNER JOIN sFee.tChargeCategoryMaster CCM ON CCM.Id=CM.ChargeCategoryId
		WHERE 
			ChargeReceiptId=@rChargeReceiptId
		
		SELECT 1 AS Result
		
	COMMIT TRANSACTION
	END TRY
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result, Error_message(),Error_line()
	END CATCH	
END
GO
PRINT N'Altering [sFee].[pChargeReceiptListGet]...';


GO

 
ALTER PROCEDURE [sFee].[pChargeReceiptListGet]
	 
	 --@rReceiptNumber int,
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 @rSourceTypeId smallint,
	 @rSourceCode nvarchar(20),
	 @rGuestName nvarchar(200),
	 @rFromDate date,
	 @rToDate date,
	 @rFromNo int,
	 @rToNo int,
	 @rReceiptBookId int,
	 @rChargeCategoryId int,
	 @rOrgId int,
	 @rBatchId int,
	 @rOrgGroupBatchId int,
	 @rDepartmentId int = 0,
	 @rStudentCode nvarchar(20) = '',
	 @rOrgGroupId int=0,
	 @rStatusId int=0,
	 @rFromReceiptNumber int=0,    
	 @rToReceiptNumber int=0
	 
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON		 
BEGIN 
		--select 
		--		'' AS Builder1,
		--		'' AS Builder2,
		--		'' AS Id,
		--		'' AS SourceType,
		--		'' AS SourceTypeId
		--		,'' AS GuestName
		--		,'' AS ReceiptNumber
		--		,'' AS ReceiptDate
		--		,'' AS Amount
		--		,'' AS ChargeCategory
		--		,'' AS ReceiptBook
		--		,'' AS ChargeCategoryId
		--		,'' As ReceiptBookId
		--		,'' AS OrgId
		--		,'' AS School
		--		,'' AS OrgGroupId
		--		,'' AS ChargeId

	    ----IF(@rIsSearch=1)
		----BEGIN
			SET @rSourceCode = sCommon.fSearchStringGet(@rSourceCode)
			SET @rGuestName = sCommon.fSearchStringGet(@rGuestName)

			print @rSourceCode
		--Declare @rSourceTypeId smallint
		--select @rSourceTypeId=SourceTypeId from sFee.tChargeReceipt where ReceiptNumber=@rReceiptNumber and OrgId=@rOrgId
		--END
IF @rSourceTypeId=95
BEGIN
		SELECT 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			--CRD.Id as DetailId,
			CR.Id,
			'Employee' as SourceType,
			ISNULL(EM.Code,'') AS Code,
			CR.SourceTypeId,
			--EM.Code as SourceCode,
			EM.FirstName+' '+EM.LastName as GuestName,
			--CR.Remark,
			CR.ReceiptNumber,
			CR.ReceiptDate,
			PTM.Title AS PayType,  
			--CR.PayTypeId,
			CR.ChequeNo,
			CR.BankName,
			--CR.IsObsolete,
			--CRD.Id as DetailId,
			--CRD.ChargeId,
			--CRD.Remark as DetailRemark,
			sum(CRD.Amount) as Amount,
			--Amount=(select sum(Amount) from sFee.tChargeReceiptDetail group by ChargeReceiptId),
			--CM.Code,
			--CM.Title,
			CCM.Title as ChargeCategory,
			CM.ChargeCategoryId,
			CR.OrgId,
			CR.BatchId,
			RBM.Title AS ReceiptBook,
			CR.ChargeReceiptBookId,
			OM.DisplayTitle AS OrganizationName,
			DM.DisplayTitle AS Class,
			CR.Remark
			--OM.DisplayTitle AS School,
			--OM.OrgGroupId,
			--CM.Id AS ChargeId
  FROM 
           sFee.tChargeReceipt CR
		   INNER JOIN sFee.tChargeReceiptDetail CRD ON CRD.ChargeReceiptId=CR.Id
		   INNER JOIN sHRM.tEmployeeMaster EM ON EM.Id=CR.SourceId AND (CR.SourceTypeId = @rSourceTypeId)
		   INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id 
		   INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id = EJD.OrganizationDepartmentId
		   --AND EM.StatusId=7
		    INNER JOIN sFinanceCommon.tPayTypeMaster PTM  ON PTM.Id=CR.PayTypeId 
		   INNER JOIN sFee.tChargeMaster CM ON CM.Id=CRD.ChargeId
		   INNER JOIN sFee.tChargeCategoryMaster CCM ON CCM.Id=CM.ChargeCategoryId
		   INNER JOIN sFee.tChargeReceiptBookMaster RBM ON RBM.Id=CR.ChargeReceiptBookId
		   INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=CR.OrgId
		   --INNER JOIN sSetup.tOrgGroupBatchMaster OBM ON OBM.Id=CR.OrgGroupBatchId
		   --INNER JOIN sSetup.tOrganizationMaster OM ON OM.OrgGroupId=OBM.OrgGroupId
  WHERE 
			--(CR.ReceiptNumber=@rReceiptNumber OR ISNULL(@rReceiptNumber,'')='')
			--AND 
			((EM.FirstName+' '+EM.LastName Like @rGuestName) OR (ISNULL(@rGuestName,'') = ''))
			AND ((EM.Code Like @rSourceCode) OR (ISNULL(@rSourceCode,'') = ''))
			AND ((CR.ReceiptDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
			AND ((CR.ReceiptDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
			AND ((CR.ReceiptNumber>=@rFromNo) OR (ISNULL(@rFromNo,'')=''))
			AND ((CR.ReceiptNumber<=@rToNo) OR (ISNULL(@rToNo,'')=''))
			AND ((CR.ChargeReceiptBookId = @rReceiptBookId) OR (ISNULL(@rReceiptBookId,0) = 0))
			AND ((CM.ChargeCategoryId = @rChargeCategoryId) OR (ISNULL(@rChargeCategoryId,0) = 0))
			AND (CR.IsObsolete=0)
			AND ((CR.OrgId=@rOrgId) OR (@rOrgId=0))
			And ((CR.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
			AND ((CR.BatchId=@rBatchId) OR (@rBatchId=0))
			AND (CRD.IsObsolete=0) 
			AND (OM.OrgGroupId = @rOrgGroupId or @rOrgGroupId=0)
			AND ((EM.StatusId=@rStatusId) OR (@rStatusId=0))
			AND ISNULL(EM.IsOtherUser,0) = 0 
			AND ((CR.ReceiptNumber>=@rFromReceiptNumber)OR(@rFromReceiptNumber=0))    
			AND ((CR.ReceiptNumber<=@rToReceiptNumber)OR(@rToReceiptNumber=0))    
GROUP BY 
			CR.Id,EM.FirstName,EM.LastName,CR.ReceiptNumber,CR.ReceiptDate,CCM.Title,CR.OrgId,CR.BatchId,RBM.Title,
			CR.ChargeReceiptBookId,CM.ChargeCategoryId,CR.SourceTypeId,OM.DisplayTitle, DM.DisplayTitle
			,PTM.Title,CR.ChequeNo,CR.BankName,EM.Code,CR.Remark

END
ELSE IF @rSourceTypeId=2001
BEGIN
		SELECT 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			CR.Id,
			'Student' as SourceType,
			CR.SourceTypeId,
			ISNULL(SA.Code,'') as Code,
			SA.FirstName+' '+SA.LastName as GuestName,
			--CR.Remark,
			CR.ReceiptNumber,
			CR.ReceiptDate,
			PTM.Title AS PayType,  
			--CR.PayTypeId,
			CR.ChequeNo,
			CR.BankName,
			--CR.IsObsolete,
			--CRD.Id as DetailId,
			--CRD.ChargeId,
			--CRD.Remark as DetailRemark,
			sum(CRD.Amount) as Amount,
			--CM.Code,
			--CM.Title,
			CCM.Title as ChargeCategory,
			CM.ChargeCategoryId,
			CR.OrgId,
			CR.BatchId,
			RBM.Title AS ReceiptBook,
			CR.ChargeReceiptBookId,
			OM.DisplayTitle AS OrganizationName,
			CMM.DisplayTitle + '-' + DM.DisplayTitle AS Class ,
			CR.Remark
			--CLM.Id AS ClassId,
			--CLM.DisplayTitle AS ClassName,
			--DM.Id AS DivisionId,
			--DM.DisplayTitle AS DivisionName
			--OM.DisplayTitle AS School,
			--OM.OrgGroupId,
			--CM.Id AS ChargeId
  FROM 
           sFee.tChargeReceipt CR
		   INNER JOIN sFee.tChargeReceiptDetail CRD ON CRD.ChargeReceiptId=CR.Id
		   INNER JOIN sFee.tChargeMaster CM ON CM.Id=CRD.ChargeId
		   INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=CR.SourceId AND CR.SourceTypeId=2001 --AND SA.StatusId=1
		   INNER JOIN sFinanceCommon.tPayTypeMaster PTM  ON PTM.Id=CR.PayTypeId 
		   INNER JOIN sSetup.tClassMaster CMM ON CMM.Id = SA.ClassId
		   INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = SA.DivisionId
		   INNER JOIN sFee.tChargeCategoryMaster CCM ON CCM.Id=CM.ChargeCategoryId
		   INNER JOIN sFee.tChargeReceiptBookMaster RBM ON RBM.Id=CR.ChargeReceiptBookId
		   INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=CR.OrgId
		   --INNER JOIN sSetup.tClassMaster CLM ON CLM.Id = SA.ClassId
		   --INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = SA.DivisionId
		   --INNER JOIN sSetup.tOrgGroupBatchMaster OBM ON OBM.Id=CR.OrgGroupBatchId
		   --INNER JOIN sSetup.tOrganizationMaster OM ON OM.OrgGroupId=OBM.OrgGroupId
  WHERE 
			--(CR.ReceiptNumber=@rReceiptNumber OR ISNULL(@rReceiptNumber,'')='')
			--AND 
			((SA.FirstName+' '+SA.LastName Like @rGuestName) OR (ISNULL(@rGuestName,'') = ''))
			AND ((SA.Code Like @rSourceCode) OR (ISNULL(@rSourceCode,'') = ''))
			AND ((CR.ReceiptDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
			AND ((CR.ReceiptDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
			AND ((CR.ChargeReceiptBookId = @rReceiptBookId) OR (ISNULL(@rReceiptBookId,0) = 0))
			AND ((CM.ChargeCategoryId = @rChargeCategoryId) OR (ISNULL(@rChargeCategoryId,0) = 0))
			AND (CR.IsObsolete=0)
			AND ((CR.OrgId=@rOrgId) OR (@rOrgId=0))
			AND ((CR.BatchId=@rBatchId) OR (@rBatchId=0))
			AND (CRD.IsObsolete=0)
			AND ((SA.Code=@rStudentCode) OR (@rStudentCode=''))
			AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0)) 
			AND (OM.OrgGroupId = @rOrgGroupId or @rOrgGroupId=0)
			AND ((SA.StatusId=@rStatusId) OR (@rStatusId=0))
			And ((CR.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
			AND ((CR.ReceiptNumber>=@rFromReceiptNumber)OR(@rFromReceiptNumber=0))    
			AND ((CR.ReceiptNumber<=@rToReceiptNumber)OR(@rToReceiptNumber=0)) 
 GROUP BY   CR.Id,SA.FirstName,SA.LastName,CR.ReceiptNumber,CR.ReceiptDate,CCM.Title,CR.OrgId,CR.BatchId,RBM.Title,CM.ChargeCategoryId,
            CR.ChargeReceiptBookId,CR.SourceTypeId,OM.DisplayTitle, CMM.DisplayTitle, DM.DisplayTitle
			,PTM.Title,CR.ChequeNo,CR.BankName,SA.Code ,CR.Remark
            --CLM.Id,CLM.DisplayTitle, DM.Id, DM.DisplayTitle
END
ELSE IF @rSourceTypeId=3
BEGIN
		SELECT 
		@rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,
		CR.Id,
		'Other' as SourceType,
		'' AS Code,
		CR.SourceTypeId,
		--EM.Code as SourceCode,
		CR.GuestName as GuestName,
		--CR.Remark,
		CR.ReceiptNumber,
		CR.ReceiptDate,
		  PTM.Title AS PayType,  
		--CR.PayTypeId,
		CR.ChequeNo,
		CR.BankName,
		--CR.IsObsolete,
		--CRD.Id as DetailId,
		--CRD.ChargeId,
		--CRD.Remark as DetailRemark,
		sum(CRD.Amount) as Amount,
		--CM.Code,
		--CM.Title,
		CCM.Title as ChargeCategory,
		CM.ChargeCategoryId,
		CR.OrgId,
		CR.BatchId,
		RBM.Title AS ReceiptBook,
		CR.ChargeReceiptBookId,
		OM.DisplayTitle AS OrganizationName,
		'' AS Class ,
		CR.Remark
		--OM.DisplayTitle AS School,
		--OM.OrgGroupId,
		--CM.Id AS ChargeId
		--CRD.IsObsolete
  FROM 
       sFee.tChargeReceipt CR
	   INNER JOIN sFee.tChargeReceiptDetail CRD ON CRD.ChargeReceiptId=CR.Id
	   INNER JOIN sFee.tChargeMaster CM ON CM.Id=CRD.ChargeId
	   INNER JOIN sFee.tChargeCategoryMaster CCM ON CCM.Id=CM.ChargeCategoryId
	   INNER JOIN sFee.tChargeReceiptBookMaster RBM ON RBM.Id=CR.ChargeReceiptBookId
	   INNER JOIN sFinanceCommon.tPayTypeMaster PTM  ON PTM.Id=CR.PayTypeId 
	   INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=CR.OrgId
	   --INNER JOIN sSetup.tOrgGroupBatchMaster OBM ON OBM.Id=CR.OrgGroupBatchId
	   --INNER JOIN sSetup.tOrganizationMaster OM ON OM.OrgGroupId=OBM.OrgGroupId
  WHERE 
		--(CR.ReceiptNumber=@rReceiptNumber OR ISNULL(@rReceiptNumber,'')='')
		--AND 
		(ISNULL(CR.SourceTypeId,0)=3)
		AND	((CR.GuestName Like @rGuestName) OR (ISNULL(@rGuestName,'') = ''))
		--AND (ISNULL(@rSourceCode,'') = '')
		AND ((CR.ReceiptDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
		AND ((CR.ReceiptDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
		AND ((CR.ChargeReceiptBookId = @rReceiptBookId) OR (ISNULL(@rReceiptBookId,0) = 0))
		AND ((CM.ChargeCategoryId = @rChargeCategoryId) OR (ISNULL(@rChargeCategoryId,0) = 0))
		AND (CR.IsObsolete=0)
		AND ((CR.OrgId=@rOrgId) OR (@rOrgId=0))
		AND ((CR.BatchId=@rBatchId) OR (@rBatchId=0))
		AND (CRD.IsObsolete=0) 
		AND (OM.OrgGroupId = @rOrgGroupId or @rOrgGroupId=0)
		And ((CR.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
		AND ((CR.ReceiptNumber>=@rFromReceiptNumber)OR(@rFromReceiptNumber=0))    
		AND ((CR.ReceiptNumber<=@rToReceiptNumber)OR(@rToReceiptNumber=0)) 
		group by CR.Id,CR.GuestName,CR.ReceiptNumber,CR.ReceiptDate,CCM.Title,CR.OrgId,CR.BatchId,RBM.Title,CR.ChargeReceiptBookId,CM.ChargeCategoryId,CR.SourceTypeId,OM.DisplayTitle
		,PTM.Title,CR.ChequeNo,CR.BankName ,CR.Remark

END	
ELSE
BEGIN
	SELECT 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			--CRD.Id as DetailId,
			CR.Id,
			'Employee' as SourceType,
			CR.SourceTypeId,
			ISNULL(EM.Code,'') as Code,
			EM.FirstName+' '+EM.LastName as GuestName,
			--CR.Remark,
			CR.ReceiptNumber,
			CR.ReceiptDate,
			  PTM.Title AS PayType,  
			--CR.PayTypeId,
			CR.ChequeNo,
			CR.BankName,
			--CR.IsObsolete,
			--CRD.Id as DetailId,
			--CRD.ChargeId,
			--CRD.Remark as DetailRemark,
			sum(CRD.Amount) as Amount,
			--Amount=(select sum(Amount) from sFee.tChargeReceiptDetail group by ChargeReceiptId),
			--CM.Code,
			--CM.Title,
			CCM.Title as ChargeCategory,
			CM.ChargeCategoryId,
			CR.OrgId,
			CR.BatchId,
			RBM.Title AS ReceiptBook,
			CR.ChargeReceiptBookId,
			OM.DisplayTitle AS OrganizationName,
			DM.DisplayTitle AS Class,
			CR.Remark
			--OM.DisplayTitle AS School,
			--OM.OrgGroupId,
			--CM.Id AS ChargeId
			--CRD.IsObsolete
  FROM 
           sFee.tChargeReceipt CR
		   INNER JOIN sFee.tChargeReceiptDetail CRD ON CRD.ChargeReceiptId=CR.Id
		   INNER JOIN sHRM.tEmployeeMaster EM ON EM.Id=CR.SourceId AND (CR.SourceTypeId = 95) 
		   INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id 
		   INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id = EJD.OrganizationDepartmentId
		   --AND EM.StatusId=7
		   INNER JOIN sFee.tChargeMaster CM ON CM.Id=CRD.ChargeId
		   INNER JOIN sFee.tChargeCategoryMaster CCM ON CCM.Id=CM.ChargeCategoryId
		   INNER JOIN sFee.tChargeReceiptBookMaster RBM ON RBM.Id=CR.ChargeReceiptBookId
		   INNER JOIN sFinanceCommon.tPayTypeMaster PTM  ON PTM.Id=CR.PayTypeId 
		   INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=CR.OrgId
		   
		   --INNER JOIN sSetup.tOrgGroupBatchMaster OBM ON OBM.Id=CR.OrgGroupBatchId
		   --INNER JOIN sSetup.tOrganizationMaster OM ON OM.OrgGroupId=OBM.OrgGroupId
       
  WHERE 
			--(CR.ReceiptNumber=@rReceiptNumber OR ISNULL(@rReceiptNumber,'')='')
			--AND 
			((EM.FirstName+' '+EM.LastName Like @rGuestName) OR (ISNULL(@rGuestName,'') = ''))
			AND ((EM.Code Like @rSourceCode) OR (ISNULL(@rSourceCode,'') = ''))
			AND ((CR.ReceiptDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
			AND ((CR.ReceiptDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
			AND ((CR.ChargeReceiptBookId = @rReceiptBookId) OR (ISNULL(@rReceiptBookId,0) = 0))
			AND ((CM.ChargeCategoryId = @rChargeCategoryId) OR (ISNULL(@rChargeCategoryId,0) = 0))
			AND (CR.IsObsolete=0)
			AND ((CR.OrgId=@rOrgId) OR (@rOrgId=0))
			AND ((CR.BatchId=@rBatchId) OR (@rBatchId=0))
			AND (CRD.IsObsolete=0)
			AND (OM.OrgGroupId = @rOrgGroupId or @rOrgGroupId=0)
			And ((CR.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
			AND ISNULL(EM.IsOtherUser,0) = 0 
			AND ((CR.ReceiptNumber>=@rFromReceiptNumber)OR(@rFromReceiptNumber=0))    
			AND ((CR.ReceiptNumber<=@rToReceiptNumber)OR(@rToReceiptNumber=0)) 
			AND ((CR.ReceiptNumber>=@rFromNo) OR (ISNULL(@rFromNo,'')=''))
			AND ((CR.ReceiptNumber<=@rToNo) OR (ISNULL(@rToNo,'')=''))
			group by CR.Id,EM.FirstName,EM.LastName,CR.ReceiptNumber,CR.ReceiptDate,CCM.Title,CR.OrgId,
			CR.BatchId,RBM.Title,CM.ChargeCategoryId,CR.ChargeReceiptBookId,CR.SourceTypeId,OM.DisplayTitle, DM.DisplayTitle
			,PTM.Title,CR.ChequeNo,CR.BankName,EM.Code ,CR.Remark

			UNION ALL
			
			SELECT 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			CR.Id,
			'Student' as SourceType,
			CR.SourceTypeId,
			ISNULL(SA.Code,'') as Code,
			SA.FirstName+' '+SA.LastName as GuestName,
			--CR.Remark,
			CR.ReceiptNumber,
			CR.ReceiptDate,
			  PTM.Title AS PayType,  
			--CR.PayTypeId,
			CR.ChequeNo,
			CR.BankName,
			--CR.IsObsolete,
			--CRD.Id as DetailId,
			--CRD.ChargeId,
			--CRD.Remark as DetailRemark,
			sum(CRD.Amount) as Amount,
			--CM.Code,
			--CM.Title,
			CCM.Title as ChargeCategory,
			CM.ChargeCategoryId,
			CR.OrgId,
			CR.BatchId,
			RBM.Title AS ReceiptBook,
			CR.ChargeReceiptBookId,
			OM.DisplayTitle AS OrganizationName,
			CMM.DisplayTitle + '-' + DM.DisplayTitle AS Class ,
			CR.Remark
			--OM.DisplayTitle AS School,
			--OM.OrgGroupId,
			--CM.Id AS ChargeId
			--CRD.IsObsolete
  FROM 
           sFee.tChargeReceipt CR
		   INNER JOIN sFee.tChargeReceiptDetail CRD ON CRD.ChargeReceiptId=CR.Id
		   INNER JOIN sFee.tChargeMaster CM ON CM.Id=CRD.ChargeId
		   INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=CR.SourceId AND CR.SourceTypeId=2001
		   INNER JOIN sSetup.tClassMaster CMM ON CMM.Id = SA.ClassId
		   INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = SA.DivisionId 
		   --AND SA.StatusId=1
		   INNER JOIN sFee.tChargeCategoryMaster CCM ON CCM.Id=CM.ChargeCategoryId
		   INNER JOIN sFee.tChargeReceiptBookMaster RBM ON RBM.Id=CR.ChargeReceiptBookId
		   INNER JOIN sFinanceCommon.tPayTypeMaster PTM  ON PTM.Id=CR.PayTypeId 
		   INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=CR.OrgId
		   --INNER JOIN sSetup.tOrgGroupBatchMaster OBM ON OBM.Id=CR.OrgGroupBatchId
		   --INNER JOIN sSetup.tOrganizationMaster OM ON OM.OrgGroupId=OBM.OrgGroupId
       
  WHERE 
			--(CR.ReceiptNumber=@rReceiptNumber OR ISNULL(@rReceiptNumber,'')='')
			--AND 
			((SA.FirstName+' '+SA.LastName Like @rGuestName) OR (ISNULL(@rGuestName,'') = ''))
			AND ((SA.Code Like @rSourceCode) OR (ISNULL(@rSourceCode,'') = ''))
			AND ((CR.ReceiptDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
			AND ((CR.ReceiptDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
			AND ((CR.ChargeReceiptBookId = @rReceiptBookId) OR (ISNULL(@rReceiptBookId,0) = 0))
			AND ((CM.ChargeCategoryId = @rChargeCategoryId) OR (ISNULL(@rChargeCategoryId,0) = 0))
			AND (CR.IsObsolete=0)
			AND ((CR.OrgId=@rOrgId) OR (@rOrgId=0))
			AND ((CR.BatchId=@rBatchId) OR (@rBatchId=0))
			AND (CRD.IsObsolete=0)
			AND ((SA.Code=@rStudentCode) OR (@rStudentCode=''))
			AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))  
			AND (OM.OrgGroupId = @rOrgGroupId or @rOrgGroupId=0)
			And ((CR.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
			AND ((CR.ReceiptNumber>=@rFromReceiptNumber)OR(@rFromReceiptNumber=0))    
			AND ((CR.ReceiptNumber<=@rToReceiptNumber)OR(@rToReceiptNumber=0)) 
			AND ((CR.ReceiptNumber>=@rFromNo) OR (ISNULL(@rFromNo,'')=''))
			AND ((CR.ReceiptNumber<=@rToNo) OR (ISNULL(@rToNo,'')=''))
			group by CR.Id,SA.FirstName,SA.LastName,CR.ReceiptNumber,CR.ReceiptDate,CCM.Title,CR.OrgId,CR.BatchId,
			RBM.Title,CR.ChargeReceiptBookId,CM.ChargeCategoryId,CR.SourceTypeId,OM.DisplayTitle, CMM.DisplayTitle, DM.DisplayTitle
			,PTM.Title,CR.ChequeNo,CR.BankName,SA.Code,CR.Remark

			UNION ALL
			
			SELECT 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			CR.Id,
			'Other' as SourceType,
			CR.SourceTypeId,
			'' AS Code,
			CR.GuestName as GuestName,
			--CR.Remark,
			CR.ReceiptNumber,
			CR.ReceiptDate,
			  PTM.Title AS PayType,  
			--CR.PayTypeId,
			CR.ChequeNo,
			CR.BankName,
			--CR.IsObsolete,
			--CRD.Id as DetailId,
			--CRD.ChargeId,
			--CRD.Remark as DetailRemark,
			sum(CRD.Amount) as Amount,
			--CM.Code,
			--CM.Title,
			CCM.Title as ChargeCategory,
			CM.ChargeCategoryId,
			CR.OrgId,
			CR.BatchId,
			RBM.Title AS ReceiptBook,
			CR.ChargeReceiptBookId,
			OM.DisplayTitle AS OrganizationName,
			'' AS Class ,
			CR.Remark
			--OM.DisplayTitle AS School,
			--OM.OrgGroupId,
			--CM.Id AS ChargeId
			--CRD.IsObsolete
  FROM 
           sFee.tChargeReceipt CR
		   INNER JOIN sFee.tChargeReceiptDetail CRD ON CRD.ChargeReceiptId=CR.Id
		   INNER JOIN sFee.tChargeMaster CM ON CM.Id=CRD.ChargeId
		   INNER JOIN sFee.tChargeCategoryMaster CCM ON CCM.Id=CM.ChargeCategoryId
		   INNER JOIN sFee.tChargeReceiptBookMaster RBM ON RBM.Id=CR.ChargeReceiptBookId
		   INNER JOIN sFinanceCommon.tPayTypeMaster PTM  ON PTM.Id=CR.PayTypeId 
		   INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=CR.OrgId
		   --INNER JOIN sSetup.tOrgGroupBatchMaster OBM ON OBM.Id=CR.OrgGroupBatchId
		   --INNER JOIN sSetup.tOrganizationMaster OM ON OM.OrgGroupId=OBM.OrgGroupId
  WHERE 
			--(CR.ReceiptNumber=@rReceiptNumber OR ISNULL(@rReceiptNumber,'')='')
			--AND 
			(ISNULL(CR.SourceTypeId,0)=3)
			AND	((CR.GuestName Like @rGuestName) OR (ISNULL(@rGuestName,'') = ''))
			AND ((CR.ReceiptDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
			AND ((CR.ReceiptDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
			AND ((CR.ChargeReceiptBookId = @rReceiptBookId) OR (ISNULL(@rReceiptBookId,0) = 0))
			AND ((CM.ChargeCategoryId = @rChargeCategoryId) OR (ISNULL(@rChargeCategoryId,0) = 0))
			AND (CR.IsObsolete=0)
			AND ((CR.OrgId=@rOrgId) OR (@rOrgId=0))
			AND ((CR.BatchId=@rBatchId) OR (@rBatchId=0))
			AND (CRD.IsObsolete=0) 
			AND (OM.OrgGroupId = @rOrgGroupId or @rOrgGroupId=0)
			And ((CR.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
			AND ((CR.ReceiptNumber>=@rFromReceiptNumber)OR(@rFromReceiptNumber=0))    
			AND ((CR.ReceiptNumber<=@rToReceiptNumber)OR(@rToReceiptNumber=0)) 
			AND ((CR.ReceiptNumber>=@rFromNo) OR (ISNULL(@rFromNo,'')=''))
			AND ((CR.ReceiptNumber<=@rToNo) OR (ISNULL(@rToNo,'')=''))
			--AND ((ISNULL(@rSourceCode,'%') = '%'))
			group by CR.Id,CR.GuestName,CR.ReceiptNumber,CR.ReceiptDate,CCM.Title,CR.OrgId,CR.BatchId,RBM.Title,CR.ChargeReceiptBookId,CM.ChargeCategoryId,CR.SourceTypeId,OM.DisplayTitle
			,PTM.Title,CR.ChequeNo,CR.BankName ,CR.Remark
END
END
GO
PRINT N'Altering [sFee].[pExportChargeReceiptDeletedLog]...';


GO
ALTER PROCEDURE [sFee].[pExportChargeReceiptDeletedLog]

	 @rOrgGroupBatchId bigint,
	 @rOrgId bigint=0,
	 @rFromDate date=NULL,
	 @rToDate date=NULL
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
	SELECT 
		CD.Code,
		GuestName As SourceName,
		ReceiptNumber,			
		convert(varchar(10), ReceiptDate, 103) As ReceiptDate,
		ReceiptAmount,
		PayTypeId As PayType,
		ChequeNo,
		BankName,
		ChargeReceiptBookName,
		Remark,
		CreatedUser,				
           convert(varchar(10),CreatedDateTime, 103) + right(convert(varchar(32),CreatedDateTime,100),8) As CreatedDateTime,	 		
		DeletededUser,			
		convert(varchar(10),DeletedDateTime, 103) + right(convert(varchar(32),DeletedDateTime,100),8) As DeletedDateTime,	 
		(SELECT DISTINCT
		 STUFF((SELECT ',' + U.ChargeName + '-' + CONVERT(varchar(10), U.Amount) 
				FROM sAudit.tChargeDetailDelete U
				WHERE U.ChargeName = ChargeName And  ChargeReceiptId=CD.Id
				ORDER BY U.ChargeName FOR XML PATH('')),1,1,''
				) AS ChargeReceiptDetailDeletelist
	     FROM sAudit.tChargeDetailDelete GROUP BY ChargeReceiptId
	     ) AS DeletedChargeReceiptDetail,
		 ISNULL(DeleteRemark,'') AS DeleteRemark
	FROM 
	   sAudit.tChargeDeleted  CD
	   INNER JOIN sStudent.vStudentAcademic SA ON CD.SourceId=SA.AcademicId
	WHERE 
	   SA.OrgGroupBatchId =@rOrgGroupBatchId
	   AND ((SA.OrgId=@rOrgId) OR (@rOrgId = 0))
	   AND ((CD.ReceiptDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
	   AND ((CD.ReceiptDate <= @rToDate) OR (ISNULL(@rToDate,'') = ''))
	ORDER BY CD.ReceiptDate DESC    
END
GO
PRINT N'Altering [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	
					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
					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
					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
					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
					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''))
					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
					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''))
					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
					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''))
					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
						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''))
						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
					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
				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
					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
				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
					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=''))
				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
					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=''))
				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
					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=''))
				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
					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=''))
				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
					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
				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
					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
					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=''))
					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
					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=''))
					GROUP BY  R.ReceiptNumber,R.ReceiptDate,SA.Code, SA.Name
				END
				END
		
	
END
GO
PRINT N'Altering [sFee].[pFeeCustomSearchGet]...';


GO
 
ALTER PROCEDURE [sFee].[pFeeCustomSearchGet]
(
	@rOrgGroupBatchId int,
	@rOrgId smallint,
	@rBatchId int,
	@rOrderBy nvarchar(max) = 'ReceiptNumber',
	@rCode [nvarchar](20) = '',
	@rFirstName [nvarchar](50) = '',	
	@rLastName [nvarchar](50) = '',	
	@rDivisionId nvarchar(max) = '',
	@rReceiptBookId nvarchar(max) = '',
	@rFromReceiptDate Date = '0001-01-01',
	@rToReceiptDate Date = '9999-12-31',
	@rFromReceiptNo int,
	@rToReceiptNo int,
	@rCreatedUserId bigint,
	@rIsObsolete bit,
	@rDropDownStatusId int,
	@rDropDownClassId int,
	@rDropDownDivisionId int,
	@rDropDownReceiptBookId int,
	@rDepartmentId int=0,
	@rPageIndex int = null,
	@rAdmissionCategoryId int = 0
 )
AS
SET NOCOUNT ON
BEGIN
	create table #TEMPFee
	(
		tid int identity(1,1),t_AcedemicId bigint,t_ReceiptId bigint
	)
	
	DECLARE @Sql nvarchar(MAX)
	IF(@rFromReceiptDate IS NULL)
		SET @rFromReceiptDate='0001-01-01'
	IF(@rToReceiptDate IS NULL)
		SET @rToReceiptDate='9999-12-31'

		
	SET @rCode = sCommon.fSearchStringGet(@rCode)
	SET @rFirstName = sCommon.fSearchStringGet(@rFirstName)
	SET @rLastName = sCommon.fSearchStringGet(@rLastName)
	select @rPageIndex = case when isnull(@rPageIndex,0) = 0 then 1 else @rPageIndex end
	
	SELECT FCS.AcademicId,FCS.ClassId,FCS.DivisionId,FCS.RollNo,FCS.OrgGroupBatchId,
	FCS.OrgId,FCS.BatchId,FCS.OrgGroupBatch,FCS.Organization,FCS.Batch,FCS.StudentId,
	FCS.Code,FCS.Number,FCS.FirstName,FCS.LastName,FCS.Name,FCS.StatusId,FCS.ClassName,
	FCS.DivisionName,FCS.StatusName,FCS.ReceiptId,FCS.ReceiptNumber,FCS.ReceiptDate,
	FCS.ReceiptAmount,FCS.ChequeNo,FCS.BankName,FCS.Remark,FCS.IsObsolete,FCS.FeeReceiptBookId,
	FCS.ReceiptBookCode,FCS.ReceiptBookName,FCS.Address1,FCS.Address2,FCS.BankAccountNumber,
	FCS.PayTypeId,FCS.PayType,FCS.CreatedUserId,FCS.CreatedUserName, FCS.ParentContactNo
	into sFee.tTempFee1
	FROM sFee.vFeeCustomSearch FCS
	INNER JOIN sSetup.tClassMaster CM ON CM.Id = FCS.ClassId
	WHERE (FCS.OrgGroupBatchId = @rOrgGroupBatchId)
	AND	((FCS.OrgId = @rOrgId) OR (@rOrgId=0))
	AND ((FCS.BatchId = @rBatchId) OR (@rBatchId=0))
	AND ((FCS.Code Like @rCode + '%') OR (@rCode = ''))
	AND ((FCS.FirstName Like @rFirstName  + '%') OR (@rFirstName = ''))
	AND ((FCS.LastName Like @rLastName + '%')OR(@rLastName = ''))
	AND ((FCS.ReceiptNumber >= @rFromReceiptNo) OR (@rFromReceiptNo =0))
	AND ((FCS.ReceiptNumber <= @rToReceiptNo) OR (@rToReceiptNo=0))
	AND ((ISNULL(FCS.ReceiptDate,'0001-01-01') >= @rFromReceiptDate) OR (ISNULL(@rFromReceiptDate,'') = ''))
	AND ((ISNULL(FCS.ReceiptDate,'9999-12-31') <= @rToReceiptDate) OR (ISNULL(@rToReceiptDate,'') = ''))
	AND (FCS.DivisionId In( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionId,','))OR @rDivisionId='')
	AND (FCS.FeeReceiptBookId In( SELECT cast(item as int) FROM  sCommon.fnsplit(@rReceiptBookId,','))OR @rReceiptBookId='')
	AND ((FCS.CreatedUserId=@rCreatedUserId) OR (@rCreatedUserId=0))
	AND (FCS.IsObsolete=@rIsObsolete)
	AND ((FCS.StatusId = @rDropDownStatusId) OR (@rDropDownStatusId=0))
	AND ((FCS.ClassId = @rDropDownClassId) OR (@rDropDownClassId=0))
	AND ((FCS.DivisionId = @rDropDownDivisionId) OR (@rDropDownDivisionId=0))
	AND ((FCS.FeeReceiptBookId = @rDropDownReceiptBookId) OR (@rDropDownReceiptBookId=0))
	AND ((Cm.DepartmentId =@rDepartmentId ) OR (@rDepartmentId=0))
	AND ((FCS.AdmissionCategoryId = @rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
	
	SET @rOrderBy=Replace(@rOrderBy,'ID No','Code')
	SET @rOrderBy=Replace(@rOrderBy,'GR No','Code')
	
	SET @sql='SELECT Code AS Code,Name,ReceiptNumber,ReceiptDate,ReceiptAmount,
	PayType,ChequeNo,BankName,ReceiptBookName,Remark,OrgId,BatchId
	FROM sFee.tTempFee1 ORDER BY '+@rOrderBy
	
	exec(@Sql)
	
	SET @sql='INSERT INTO #TEMPFee SELECT AcademicId, ReceiptId
	FROM sFee.tTempFee1 ORDER BY '+@rOrderBy
	
	exec(@Sql)
	
	declare @lTotalRecords int,@lPageSize int = 10,@lPaging varchar(max)='',@lResult varchar(max)=''
	select @lTotalRecords = count(*) from #TEMPFee
	
	select @lPaging = @lPaging + dbo.fnc_SearchPagingFormat(@rPageIndex,@lTotalRecords,@lPageSize)
	
	select @lResult = @lResult + '<tr attrId="' + convert(varchar,isnull(t_AcedemicId,0)) + '"
	attrCode="' + isnull(Code,'') + '"
	attrReceiptNo="' + isnull(convert(varchar,ReceiptNumber),'') + '"
	attrBatchId="' + convert(varchar,@rBatchId) + '"
	attrOrgId="' + convert(varchar,@rOrgId) + '"
	attrOrgGroupBatchId="' + convert(varchar,@rOrgGroupBatchId) + '">
	<td><a style="cursor:pointer;" onclick="SecectThisRecord(this);">Select</a></td><td>' + isnull(Code,'') + '</td>
	<td>' + isnull(Name,'') + '</td><td>' + isnull(convert(varchar,ReceiptNumber),'') + '</td>
	<td>' + isnull(convert(varchar,ReceiptDate,103),'') + '</td>
	<td>' + isnull(convert(varchar,ReceiptAmount),'') + '</td><td>' + isnull(PayType,'') + '</td>
	<td>' + isnull(ChequeNo,'') + '</td><td>' + isnull(BankName,'') + '</td>
	<td>' + isnull(ReceiptBookName,'') + '</td><td>' + isnull(Remark,'') + '</td></tr>'
	from sFee.tTempFee1,#TEMPFee where t_AcedemicId = AcademicId AND t_ReceiptId = ReceiptId
	and tid between ((@lPageSize * (@rPageIndex - 1)) + 1) AND (@lPageSize * @rPageIndex)
	
	select @lPaging as UserPaging,@lResult as UserResult,@lTotalRecords as UserTotal
			
	DROP Table sFee.tTempFee1
	drop Table #TEMPFee
END
GO
PRINT N'Altering [sFee].[pFeePendingListGet]...';


GO
 
ALTER PROCEDURE [sFee].[pFeePendingListGet]
		
		@rOrgGroupBatchId int=0,
		@rAdmissionCategoryId int=0,
		@rClassId int=0,
		@rDivisionId int=0,
		@rCode nvarchar(20)='',
		@rFirstName nvarchar(100)='',
		@rLastName nvarchar(100) = '',
		@rReceiptBookId int=0,
		@rOrgId int=0,
		@rBatchId int=0,
		@rDepartmentId int=0,
		@rSUId nvarchar(20) = '',
		@rUptoDate date='',
		@rFromNextFollowupDate date='',
		@rToNextFollowupDate date=''
		
		
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
		BEGIN
			SET @rFirstName = sCommon.fSearchStringGet(@rFirstName)
			SET @rLastName = sCommon.fSearchStringGet(@rLastName)
		END		 
BEGIN 	
	
	DECLARE @p AS TempPendingFee
	
	INSERT INTO @p 
	SELECT 
		SA.AcademicId,
		SA.RollNo,
		SA.Name,
		SA.Code,
		SA.ClassId,
		SA.DivisionId,
		SA.ClassName,
		SA.DivisionName,
		SA.ClassName+' - '+SA.DivisionName AS ClassDivision,
		FS.Id AS FeeSetupId,		
		ISNULL(FS.IsVariable,0)AS IsVariable,
		ISNULL(FS.Amount,0)AS Amount,
		ISNULL(FS.StartDate,'1900-01-01')AS StartDate,
		ISNULL(FS.EndDate,'1900-01-01')AS EndDate,
		ISNULL(FA.VariableAmount,0.00)AS FAAmount,
		ISNULL(FA.DiscountAmount,0.00)AS DiscountAmount,
		ISNULL(FA.AdditionalAmount,0.00)AS AdditionalAmount,
		ISNULL(R.PaidAmount,0) AS PaidAmount,
		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 PendingAmount,
		ISNULL(FA.Remark,'') AS Remark,
		FS.ReceiptBookId,
		FS.FeeName,
		FS.FeeCode,
		SA.OrgId,
		O.Title AS OrgName,
		O.OrderIndex AS OrgOrderIndex,
		ISNULL(RBM.Title,'') AS ReceiptBookTitle,
		ISNULL(RBM.OrderIndex,0) AS ReceiptOrderIndex,
		SA.BatchId,
		BM.Title AS BatchName,
		'',
		'',
		'',
		ISNULL(SA.SUID,'') AS SUID,
		SA.ClassOrderIndex,
		SA.DivisionOrder,
		FS.OrderIndex
  FROM 
		sStudent.vStudentAcademic SA
		INNER JOIN 
		(
			SELECT 
				FS1.FeeId,
				FS1.Id,
				ISNULL(FS1.IsOptional,0)AS IsOptional,
				ISNULL(FS1.IsVariable,0)AS IsVariable,
				ISNULL(FS1.Amount,0)AS Amount,
				ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
				ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
				FS1.BatchId,
				ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
				SA1.AcademicId,
				FM.Title AS FeeName,
				FM.Code AS FeeCode,
				FM.OrderIndex
			FROM 
				sFee.tFeeSetup FS1
				INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId 
				AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId				
				AND ((SA1.ClassId=@rClassId) OR (@rClassId=0)) AND ((SA1.DivisionId=@rDivisionId) OR (@rDivisionId=0))
				AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
			WHERE 
			    ((SA1.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
				AND	((FS1.ClassId=@rClassId) OR (@rClassId=0))
				AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
				AND (FS1.IsOptional=0)
				AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
				
			UNION ALL
				
			SELECT 
				FS1.FeeId,
				FS1.Id,
				ISNULL(FS1.IsOptional,0)AS IsOptional,
				ISNULL(FS1.IsVariable,0)AS IsVariable,
				ISNULL(FS1.Amount,0)AS Amount,
				ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
				ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
				FS1.BatchId,
				ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
				SA1.AcademicId,
				FM.Title AS FeeName,
				FM.Code AS FeeCode,
				FM.OrderIndex
			FROM 
				sFee.tFeeSetup FS1
				INNER JOIN sFee.tFeeOptional FO ON FO.FeeSetupId=FS1.Id
				INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
				INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=FO.SourceId AND SA1.BatchId = FS1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				AND ((SA1.ClassId=@rClassId) OR (@rClassId=0)) AND ((SA1.DivisionId=@rDivisionId) OR (@rDivisionId=0))
				AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
			WHERE
		        ((SA1.OrgGroupBatchId = @rOrgGroupBatchId)  OR (@rOrgGroupBatchId=0))
				AND ((FS1.ClassId=@rClassId) OR (@rClassId=0))
				AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
				AND (FS1.IsOptional=1)
				AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
		) FS ON FS.AcademicId=SA.AcademicId
		LEFT JOIN sFee.tFeeAllocation FA ON FA.FeeSetupId=FS.Id AND FA.SourceId=SA.AcademicId
		LEFT JOIN
		(
		    SELECT 
					ISNULL(SUM(RD.Amount),0) AS PaidAmount,RD.FeeSetupId ,R.SourceId
		    FROM
				sFee.tReceipt R 
				INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id 
				INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id
				INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id
				INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=R.SourceId				
				AND (SA1.ClassId=@rClassId OR @rClassId=0) AND ((SA1.DivisionId=@rDivisionId) OR (@rDivisionId=0))
				AND (SA1.DivisionId=@rDivisionId OR @rDivisionId=0)
				
			WHERE		
				(R.SourceTypeId = 2001)
				AND ((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND (R.IsObsolete = 0) 
				AND ((SA1.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
				AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
				GROUP BY FeeSetupId,R.SourceId
		) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
		 INNER JOIN sSetup.tOrganizationMaster O ON SA.OrgId = O.Id
		 INNER JOIN sFee.tReceiptBookMaster RBM ON FS.ReceiptBookId=RBM.Id
		 INNER JOIN sSetup.tBatchMaster BM ON BM.Id=SA.BatchId	
		 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 
		AND ((SA.OrgGroupBatchId = RT.OrgGroupBatchId))
		AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) 
	WHERE	
			((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
			AND ((SA.BatchId=@rBatchId) OR (@rBatchId=0)) 
			AND ((SA.Code=@rCode) OR (@rCode=''))
			AND ((SA.Code=@rSUId) OR (@rSUId=''))
			AND ((SA.FirstName like @rFirstName) OR(ISNULL(@rFirstName,'')=''))
			AND ((SA.LastName like @rLastName) OR (ISNULL(@rLastName,'')=''))
			AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=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 SA.	StatusId = 1
			AND ((FS.StartDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
			
			ORDER BY SA.RollNo
 
			SELECT
				Temp.OrgId,			 
				Temp.ReceiptBookId,
				Temp.AcademicId,
				Temp.DivisionId,
				Temp.ClassDivision,
				Temp.RollNo, 
				Temp.Name,
				Temp.Code,
				Temp.ReceiptBookTitle,
				Temp.OrgName,
				SUM(Temp.PendingAmount) AS PendingAmount, 
				[sFee].[fPendingFeeNamesGet](Temp.AcademicId,Temp.ReceiptBookId,	@p) AS PendingFeeName,
				Temp.ReceiptOrderIndex,
				Temp.BatchId,
				Temp.BatchName,
				SA.SUId AS SUId,
				FF.NextFollowupDate,
				ISNULL(SC.IsStopApplicationAccess,0) as IsStopApplicationAccess,
				ISNULL(SC.StudentCustomAlert,'') as StudentCustomAlert,
				ISNULL(SC.ParentContactNo,'')AS ParentContactNo,
				ISNULL(SC.StudentContactNo,'')AS StudentContactNo,
				ISNULL(SC.WhatsAppContactNo,'')AS WhatsAppContactNo,
				Temp.ClassOrderIndex,
				Temp.DivisionOrderIndex
			FROM @p Temp
			LEFT JOIN 
			(
				SELECT AcademicId,ReceiptBookId,NextFollowupDate 
				FROM 
				(
				SELECT AcademicId,ReceiptBookId,NextFollowupDate, 
				ROW_NUMBER() OVER(PARTITION BY AcademicId,ReceiptBookId ORDER BY NextFollowupDate DESC) AS RowNumber
				FROM sFee.tFeeFollowup FF 
				) AS T
				WHERE RowNumber = 1 
			) FF ON FF.AcademicId = Temp.AcademicId AND FF.ReceiptBookId = Temp.ReceiptBookId
			INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId = Temp.AcademicId AND SA.OrgId = Temp.OrgId
			LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId = SA.StudentId 
		WHERE 
			((FF.NextFollowupDate >= @rFromNextFollowupDate) OR (ISNULL(@rFromNextFollowupDate,'') = ''))
			AND ((FF.NextFollowupDate <= @rToNextFollowupDate) OR (ISNULL(@rToNextFollowupDate,'') = ''))
		GROUP BY 
			Temp.OrgId,Temp.AcademicId,Temp.ReceiptBookId,Temp.DivisionId,Temp.BatchId,
			Temp.ClassDivision,Temp.RollNo, Temp.Name,Temp.Code,Temp.ReceiptBookTitle,
			Temp.OrgName,Temp.ReceiptOrderIndex,Temp.BatchName,FF.NextFollowupDate,
			SC.IsStopApplicationAccess,SC.StudentCustomAlert,SC.ParentContactNo,SC.StudentContactNo,SC.WhatsAppContactNo,SA.SUId,Temp.ClassOrderIndex,
			Temp.DivisionOrderIndex
			ORDER BY Temp.AcademicId
END
GO
PRINT N'Altering [sFee].[pFeeSummaryDashboard]...';


GO
ALTER PROCEDURE [sFee].[pFeeSummaryDashboard]
	@rType nvarchar(20)='',
	@rOrgId int =0,
	@rBatchId int=0,
	@rDepartmentId int =0
	--@rLibraryId int =0
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON			 
BEGIN 

	--DECLARE @lAdmissionCategoryId int =  0
	--SET @lAdmissionCategoryId = [sCommon].[fGetIntIdForOrg](1,@rOrgId)
	
	if object_id('tempdb..#tTable') is not null
			BEGIN
				DROP TABLE #tTable
			END
		Create table #tTable(
			AcademicId bigint not null
		)
		Insert into #tTable
			select SA.AcademicId 
			FROM sFee.tFeeSetup FS
			INNER JOIN sStudent.vStudentAcademic SA ON SA.ClassId=FS.ClassId AND FS.BatchId = SA.BatchId AND SA.AdmissionCategoryId = FS.AdmissionCategoryId
			where ((SA.OrgId=@rOrgId)OR(@rOrgId=0)) AND ((SA.BatchId=@rBatchId) OR (@rBatchId=0))AND SA.StatusId =1
			-- AND SA.AdmissionCategoryId=@lAdmissionCategoryId
			group by FS.ClassId,SA.AcademicId 

		--Create Table #ttemptable1
		--	(
		--		AcademicId bigint,
		--		PaidAmount int,
		--		PendingAmount int
		--	)
		--	Insert into #ttemptable1
		--	(
		--		AcademicId,
		--		PaidAmount,
		--		PendingAmount
		--	)
		--	Select SA.AcademicId , SUM(SF.PaidAmount) AS PaidAmount , SUM(SF.PendingAmount) AS PendingAmount
		--	From sStudent.vStudentAcademic SA 
		--	Inner Join sFee.tStudentFee SF ON SA.AcademicId=SF.AcademicId
		--	where SA.OrgId=9911 AND SA.BatchId=991100104
		--	Group by SA.AcademicId


	IF(@rType = 'FeeList')
		BEGIN

		CREATE TABLE #tmp
		(
			AcademicId bigint,
			Amount decimal(12,2),
			VariableAmount decimal(12,2),
			AdditionalAmount decimal(12,2),
			DiscountAmount decimal(12,2),
			NotApplicableAmount decimal(12,2)
		)
		INSERT INTO #tmp
			Select SA.AcademicId  AS AcademicId 
			, SUM(FS1.Amount) AS Amount , Sum(FA1.VariableAmount) AS VariableAmount, SUM(FA1.AdditionalAmount)AS AdditionalAmount,SUM(FA1.DiscountAmount)AS DiscountAmount,
			SUM(FA1.NotApplicableAmount)AS NotApplicableAmount
			From sStudent.vStudentAcademic SA
			LEFT JOIN sFee.tFeeAllocation FA1 ON FA1.SourceId = SA.AcademicId
			LEFT JOIN sFee.tFeeSetup FS1 ON FA1.FeeSetupId = FS1.Id AND FS1.BatchId = SA.BatchId AND FS1.ClassId = SA.ClassId AND FS1.AdmissionCategoryId = SA.AdmissionCategoryId
			INNER JOIN #tTable tmp1 ON tmp1.AcademicId = SA.AcademicId
		
			Where
			((SA.OrgId=@rOrgId)OR(@rOrgId=0)) AND ((SA.BatchId=@rBatchId) OR (@rBatchId=0))AND SA.StatusId =1
			group by FS1.ClassId,SA.AcademicId 

			SELECT COUNT(SA.AcademicId)AS TotalCount,COUNT(T.PaidCount) AS PaidCount,(COUNT(tmp.AcademicId)-COUNT(T.PaidCount))AS UnPaidCount
			, COUNT(PS.AcademicId) AS PartialCount
			FROM sStudent.vStudentAcademic SA 
			LEFT JOIN #tmp tmp ON SA.AcademicId = tmp.AcademicId 
			AND ISNULL(((ISNULL(Amount,0) + ISNULL(VariableAmount,0)+ ISNULL(0,AdditionalAmount)) - (DiscountAmount + NotApplicableAmount)),1) <> 0 
			INNER JOIN sStudent.tAdmissionCategoryMaster ACM ON SA.AdmissionCategoryId = ACM.Id
			Inner Join #tTable FS  on  FS.AcademicId=SA.AcademicId
			LEFT JOIN(
			SELECT COUNT(R.Id)as PaidCount,SA.AcademicId AS AcademicId FROM sFee.tReceipt R
			INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.SourceId 
			WHERE R.SourceTypeId = 2001 AND((SA.OrgId=@rOrgId) OR (@rOrgId=0))
			AND ((R.BatchId=@rBatchId) OR (@rBatchId=0)) AND (R.IsObsolete = 0) 
			GROUP BY SA.AcademicId
			)T ON T.AcademicId = SA.AcademicId 

			LEFT JOIN 
			(
				SELECT 
					SA1.AcademicId 
				FROM sFee.tFeeSetup FS1
				INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				LEFT JOIN sFee.tFeeAllocation FA ON FA.FeeSetupId=FS1.Id AND FA.SourceId=SA1.AcademicId
				LEFT JOIN 
				(
				SELECT SUM(RD.Amount) as Amount,R.SourceId,FS.Id AS FeeSetupId
				FROM sFee.tReceiptDetail RD
				INNER JOIN sFee.tReceipt R ON RD.ReceiptId = R.Id
				INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id
				WHERE R.SourceTypeId = 2001
				AND (R.IsObsolete = 0) 
				AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
				Group By R.SourceId,FS.Id
				) R ON R.SourceId = SA1.AcademicId AND R.FeeSetupId = FS1.Id
				INNER JOIN 
				(
				SELECT Distinct SourceId 
				FROM sFee.tReceipt 
				) RE ON RE.SourceId = SA1.AcademicId
				WHERE 
					((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
					AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
					AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
					AND SA1.StatusId =1
					AND FS1.IsOptional = 0
					AND ISNULL(FS1.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.Amount,0.00) > 0
					
				UNION 

				SELECT 
					SA1.AcademicId 
				FROM sFee.tFeeSetup FS1
				INNER JOIN sFee.tFeeOptional FO ON FO.FeeSetupId=FS1.Id 
				INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId AND SA1.AcademicId=FO.SourceId
				LEFT JOIN sFee.tFeeAllocation FA ON FA.FeeSetupId=FS1.Id AND FA.SourceId=SA1.AcademicId
				LEFT JOIN 
				(
				SELECT SUM(RD.Amount) as Amount,R.SourceId,FS.Id AS FeeSetupId
				FROM sFee.tReceiptDetail RD
				INNER JOIN sFee.tReceipt R ON RD.ReceiptId = R.Id
				INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id
				WHERE R.SourceTypeId = 2001
				AND (R.IsObsolete = 0) 
				AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
				Group By R.SourceId,FS.Id
				) R ON R.SourceId = SA1.AcademicId AND R.FeeSetupId = FS1.Id
				INNER JOIN 
				(
				SELECT Distinct SourceId 
				FROM sFee.tReceipt 
				) RE ON RE.SourceId = SA1.AcademicId
				WHERE 
					((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
					AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
					AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
					AND SA1.StatusId =1
					AND FS1.IsOptional = 1
					AND ISNULL(FS1.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.Amount,0.00) > 0
					
			) PS ON PS.AcademicId=SA.AcademicId

			WHERE ((SA.OrgId=@rOrgId) OR (@rOrgId=0))
			AND SA.StatusId =1
			AND ((SA.BatchId=@rBatchId) OR (@rBatchId=0))
			--AND ACM.Code Like '%General%' 
			--AND ACM.ID = @lAdmissionCategoryId 
			AND ACM.IsObsolete = 0	
			DROP TABLE  #tmp
		END
	ELSE IF(@rType = 'FeeGraph')
		BEGIN
		
		CREATE TABLE #tmpData
		(
			AcademicId bigint,
			Amount decimal(12,2),
			VariableAmount decimal(12,2),
			AdditionalAmount decimal(12,2),
			DiscountAmount decimal(12,2),
			NotApplicableAmount decimal(12,2)
		)
		INSERT INTO #tmpData
			Select SA.AcademicId  AS AcademicId 
			, SUM(FS1.Amount) AS Amount , Sum(FA1.VariableAmount) AS VariableAmount, SUM(FA1.AdditionalAmount)AS AdditionalAmount,SUM(FA1.DiscountAmount)AS DiscountAmount,
			SUM(FA1.NotApplicableAmount)AS NotApplicableAmount
			From sStudent.vStudentAcademic SA
			LEFT JOIN sFee.tFeeAllocation FA1 ON FA1.SourceId = SA.AcademicId
			LEFT JOIN sFee.tFeeSetup FS1 ON FA1.FeeSetupId = FS1.Id AND FS1.BatchId = SA.BatchId AND FS1.ClassId = SA.ClassId AND FS1.AdmissionCategoryId = SA.AdmissionCategoryId
			INNER JOIN #tTable tmp1 ON tmp1.AcademicId = SA.AcademicId
		
			Where
			((SA.OrgId=@rOrgId)OR(@rOrgId=0)) AND ((SA.BatchId=@rBatchId) OR (@rBatchId=0))AND SA.StatusId =1
			group by FS1.ClassId,SA.AcademicId 


		SELECT CM.Id,CM.Title,ISNULL(T.TotalCount,0)AS TotalCount,COUNT(T1.PaidCount) AS PaidCount,(COUNT(tmpData.AcademicId)-COUNT(T1.PaidCount))AS UnPaidCount,CM.OrderIndex
			FROM sStudent.vStudentAcademic SA
			LEFT JOIN #tmpData tmpData ON SA.AcademicId = tmpData.AcademicId 
			AND ISNULL(((ISNULL(Amount,0) + ISNULL(VariableAmount,0)+ ISNULL(0,AdditionalAmount)) - (DiscountAmount + NotApplicableAmount)),1) <> 0 
			INNER JOIN sStudent.tAdmissionCategoryMaster ACM ON SA.AdmissionCategoryId = ACM.Id
			LEFT JOIN sSetup.tClassMaster CM ON  CM.Id = SA.ClassId
			LEFT JOIN 
			(SELECT COUNT(SA1.AcademicId) AS TotalCount,SA1.ClassId AS ClassId FROM sStudent.vStudentAcademic SA1
			INNER JOIN sStudent.tAdmissionCategoryMaster ACM1 ON SA1.AdmissionCategoryId = ACM1.Id
			Inner Join #tTable temp on SA1.AcademicId=temp.AcademicId
			WHERE ((SA1.OrgId=@rOrgId)OR(@rOrgId=0)) AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))AND SA1.StatusId =1
			--AND ACM1.Code Like '%General%' AND ACM1.IsObsolete = 0	
			--AND ACM1.ID = @lAdmissionCategoryId 
			AND ACM1.IsObsolete = 0
			GROUP BY ClassId
			)T ON T.ClassId = CM.Id	
			LEFT JOIN(
			SELECT COUNT(SA.AcademicId)as PaidCount,SA.AcademicId AS AcademicId,SA.ClassId AS ClassId FROM sFee.tReceipt R
			INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.SourceId 
			INNER JOIN sStudent.tAdmissionCategoryMaster ACM ON SA.AdmissionCategoryId = ACM.Id
			LEFT JOIN sSetup.tClassMaster CM ON  CM.Id = SA.ClassId
			WHERE R.SourceTypeId = 2001 AND((SA.OrgId=@rOrgId) OR (@rOrgId=0))AND SA.StatusId =1
			--AND ACM.Code Like '%General%' AND ACM.IsObsolete = 0
			--AND ACM.ID = @lAdmissionCategoryId 
			AND ACM.IsObsolete = 0		
			AND ((R.BatchId=@rBatchId) OR (@rBatchId=0)) AND (R.IsObsolete = 0) 
			GROUP BY SA.AcademicId,SA.ClassId
			)T1 ON T1.AcademicId = SA.AcademicId  AND CM.Id = SA.ClassId
			WHERE ((CM.OrgId =@rOrgId)OR(@rOrgId=0))
			AND SA.StatusId =1
			--AND ACM.ID = @lAdmissionCategoryId 
			AND ACM.IsObsolete = 0
			--AND ACM.Code Like '%General%' AND ACM.IsObsolete = 0	
			GROUP BY CM.Title, CM.Id,T.TotalCount,CM.OrderIndex
			ORDER BY CM.OrderIndex

			DROP TABLE #tmpData
		
		END
	ELSE IF (@rType = 'FeeListDetails')
		BEGIN
		SELECT F.RollNo,F.Name,F.Code,F.Pending,F.[Partial],F.[Status],F.ClassDivision
		FROM
		(

		SELECT SA.RollNo,SA.Name,SA.Code, ISNULL(T.AcademicId,0) AS Pending, ISNULL(PS.AcademicId,0) AS [Partial],'' AS [Status]
			,SA.ClassName+'/'+SA.DivisionName AS ClassDivision,
			(
				Select (SUM(FS1.Amount)+Sum(FA1.VariableAmount)+ SUM(FA1.AdditionalAmount)) - (SUM(FA1.DiscountAmount)+ SUM(FA1.NotApplicableAmount)) 
				From sFee.tFeeAllocation FA1
				INNER JOIN sFee.tFeeSetup FS1 ON FS1.BatchId = SA.BatchId AND FS1.ClassId = SA.ClassId AND FS1.AdmissionCategoryId = SA.AdmissionCategoryId AND FA1.FeeSetupId = FS1.Id
				Where FA1.SourceId = SA.AcademicId 
			) AS IsFeePayAmount
			--,ISNULL(FS1.PaidAmount,0) AS PaidAmount ,ISNULL(FS1.PendingAmount,0)AS PendingAmount
			FROM sStudent.vStudentAcademic SA 
			Inner Join #tTable FS  on  FS.AcademicId=SA.AcademicId
			--LEFT Join #ttemptable1 FS1 ON FS1.AcademicId=SA.AcademicId
			LEFT JOIN(
			SELECT COUNT(R.Id)as PaidCount,SA.AcademicId AS AcademicId, SA.Code,SA.Name FROM sFee.tReceipt R
			INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.SourceId 
			WHERE R.SourceTypeId = 2001 AND((SA.OrgId=@rOrgId) OR (@rOrgId=0))
			AND ((R.BatchId=@rBatchId) OR (@rBatchId=0)) AND (R.IsObsolete = 0) 
			GROUP BY SA.AcademicId, SA.Code,SA.Name
			)T ON T.AcademicId = SA.AcademicId
			LEFT JOIN 
			(
				SELECT 
					SA1.AcademicId 
				FROM sFee.tFeeSetup FS1
				INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				LEFT JOIN sFee.tFeeAllocation FA ON FA.FeeSetupId=FS1.Id AND FA.SourceId=SA1.AcademicId
				LEFT JOIN 
				(
				SELECT SUM(RD.Amount) as Amount,R.SourceId,FS.Id AS FeeSetupId
				FROM sFee.tReceiptDetail RD
				INNER JOIN sFee.tReceipt R ON RD.ReceiptId = R.Id
				INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id
				WHERE R.SourceTypeId = 2001
				AND (R.IsObsolete = 0) 
				AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
				Group By R.SourceId,FS.Id
				) R ON R.SourceId = SA1.AcademicId AND R.FeeSetupId = FS1.Id
				INNER JOIN 
				(
				SELECT Distinct SourceId 
				FROM sFee.tReceipt 
				) RE ON RE.SourceId = SA1.AcademicId
				WHERE 
					((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
					AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
					AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
					AND SA1.StatusId =1
					AND FS1.IsOptional = 0
					AND ISNULL(FS1.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.Amount,0.00) > 0
					
				UNION 

				SELECT 
					SA1.AcademicId 
				FROM sFee.tFeeSetup FS1
				INNER JOIN sFee.tFeeOptional FO ON FO.FeeSetupId=FS1.Id 
				INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId AND SA1.AcademicId=FO.SourceId
				LEFT JOIN sFee.tFeeAllocation FA ON FA.FeeSetupId=FS1.Id AND FA.SourceId=SA1.AcademicId
				LEFT JOIN 
				(
				SELECT SUM(RD.Amount) as Amount,R.SourceId,FS.Id AS FeeSetupId
				FROM sFee.tReceiptDetail RD
				INNER JOIN sFee.tReceipt R ON RD.ReceiptId = R.Id
				INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id
				WHERE R.SourceTypeId = 2001
				AND (R.IsObsolete = 0) 
				AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
				Group By R.SourceId,FS.Id
				) R ON R.SourceId = SA1.AcademicId AND R.FeeSetupId = FS1.Id
				INNER JOIN 
				(
				SELECT Distinct SourceId 
				FROM sFee.tReceipt 
				) RE ON RE.SourceId = SA1.AcademicId
				WHERE 
					((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
					AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
					AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
					AND SA1.StatusId =1
					AND FS1.IsOptional = 1
					AND ISNULL(FS1.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.Amount,0.00) > 0
					
			) PS ON PS.AcademicId=SA.AcademicId


			WHERE ((SA.OrgId=@rOrgId) OR (@rOrgId=0))
			AND SA.StatusId =1
			AND ((SA.BatchId=@rBatchId) OR (@rBatchId=0))	 			
			) AS F 
			WHERE ISNULL(F.IsFeePayAmount,1) <> 0
		END

	ELSE IF(@rType='FeeCollection')
		BEGIN
			SELECT Isnull(Sum(R.ReceiptAmount),0.00) as TodayCollection 
			FROM sFee.tReceipt R
				INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.SourceId 
			WHERE R.SourceTypeId = 2001 AND((SA.OrgId=@rOrgId) OR (@rOrgId=0))
				AND ((R.BatchId=@rBatchId) OR (@rBatchId=0)) AND (R.IsObsolete = 0) 
				AND ((SA.OrgId=@rOrgId) OR (@rOrgId=0))
				AND SA.StatusId =1
				AND ((SA.BatchId=@rBatchId) OR (@rBatchId=0))
				AND (R.ReceiptDate=CAST(GETDATE() as DATE))

			SELECT ISNULL(Sum(R.ReceiptAmount),0.00) as MonthlyCollection 
			FROM sFee.tReceipt R
				INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.SourceId 
			WHERE R.SourceTypeId = 2001 AND((SA.OrgId=@rOrgId) OR (@rOrgId=0))
				AND ((R.BatchId=@rBatchId) OR (@rBatchId=0)) AND (R.IsObsolete = 0) 
				AND ((SA.OrgId=@rOrgId) OR (@rOrgId=0))
				AND SA.StatusId =1
				AND ((SA.BatchId=@rBatchId) OR (@rBatchId=0))
				AND (R.ReceiptDate>=CAST(DATEADD(DD,-(DAY(GETDATE() -1)), GETDATE()) as DATE) AND R.ReceiptDate<=CAST(DATEADD(DD,-(DAY(GETDATE())), DATEADD(MM, 1, GETDATE())) as DATE))

			SELECT Isnull(Sum(R.ReceiptAmount),0.00) as UptodateCollection 
			FROM sFee.tReceipt R
				INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.SourceId 
			WHERE R.SourceTypeId = 2001 AND((SA.OrgId=@rOrgId) OR (@rOrgId=0))
				AND ((R.BatchId=@rBatchId) OR (@rBatchId=0)) AND (R.IsObsolete = 0) 
				AND ((SA.OrgId=@rOrgId) OR (@rOrgId=0))
				AND SA.StatusId =1
				AND ((SA.BatchId=@rBatchId) OR (@rBatchId=0))
				AND (R.ReceiptDate<=CAST(GETDATE() as DATE))
		END
		--Drop Table #ttemptable1
		Drop Table #tTable
END
GO
PRINT N'Altering [sFee].[pRptCustomFeePendingDetailListGet]...';


GO
ALTER PROCEDURE [sFee].[pRptCustomFeePendingDetailListGet]  

	@rReportId int=0,  
	@rReceiptBookId int=0,  
	@rAdmissionCategoryId int=0,  
	@rClassId int=0,  
	@rDivisionId int=0,  
	@rUptoDate date='',  
	@rBatchId int=0,  
	@rUserId bigint=0,  
	@rBuilder1 nvarchar(max) = '',  
	@rBuilder2 nvarchar(max) = '',  
	@rIsDetail bit=0,  
	@rOrgId int=0,  
	@rOrgGroupBatchId int=0,  
	@rStatusId int=0,  
	@rCommonBatch nvarchar(100) = '',  
	@rDepartmentId int=0,  
	@rFromRollNo int=0,  
	@rToRollNo int=0,  
	@rCode nvarchar(20)='',  
	@rIsFilter bit=0,  
	@rIsHeader bit=0,    
	@rCreatedUserName nvarchar(20) = '',  
	@rIsReceiptBookGroup bit=0,  
	@rFeeHeadId nvarchar(max) = '',  
	@rIsDisplayOrgGroup bit=0,  
	@rFeeId nvarchar(max) = '',  
	@rFilterId int=0,  
	@rOrgIds  nvarchar(max) = '',  
	@rPayDate date='',  
	@rCollectionGroupId int =0,  
	@rCastCategoryId int = 0,
	@rReportType int=0,
	@rClassStatusId int=0 ,
	@rCollectionGrupId nvarchar(max) ='',
	@rClassIds nvarchar(max) = '',
	@rDivisionIds nvarchar(max) = ''
	 
WITH EXECUTE AS CALLER  
AS  
SET NOCOUNT ON  
BEGIN 
	
	CREATE TABLE #TempIsOptional
	(
		FeeId int,  
		Id int,  
		IsOptional bit,  
		IsVariable bit,  
		Amount decimal(12,2),  
		StartDate date,  
		EndDate date,  
		BatchId int,  
		ReceiptBookId int,  
		AcademicId bigint,  
		FeeName nvarchar(100),  
		FeeHeadId int,
		CollectionGroupId int,
		CollectionGroup nvarchar(max)
	)
	
	INSERT INTO #TempIsOptional
		SELECT   
			FS1.FeeId,  
			FS1.Id,  
			ISNULL(FS1.IsOptional,0)AS IsOptional,  
			ISNULL(FS1.IsVariable,0)AS IsVariable,  
			ISNULL(FS1.Amount,0)AS Amount,  
			ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,  
			ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,  
			FS1.BatchId,  
			ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,  
			SA1.Id AS AcademicId,  
			FM.Title AS FeeName,  
			FM.FeeHeadId,
			ISNULL(CGM.Id,0) AS CollectionGroupId,
		    ISNULL(CGM.Title,'') AS CollectionGroup      
		FROM 
			sFee.tFeeSetup FS1  
			INNER JOIN sStudent.tAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId    
			INNER JOIN sStudent.tStudentMaster SM ON SA1.StudentId = SM.Id      
			AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId  
			AND ((SA1.ClassId=@rClassId) OR (@rClassId=0))
			AND (ISNULL(SA1.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='') 
			AND ((SA1.DivisionId=@rDivisionId) OR (@rDivisionId=0)) 
			AND (ISNULL(SA1.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='')  
			AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))  
			INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId  
			INNER JOIN sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId  
			LEFT JOIN sFee.tCollectionGroupMaster CGM ON FS1.CollectionGroupId=CGM.Id 
			--AND RBM.Id = CGM.ReceiptBookId 
			AND CGM.OrgGroupBatchId = @rOrgGroupBatchId
		WHERE   
			BM.OrgGroupBatchId = @rOrgGroupBatchId  
			AND ((FS1.ClassId=@rClassId) OR (@rClassId=0))      
			AND ((SA1.OrgId=@rOrgId) OR (@rOrgId=0))  
			AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))  
			AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))  
			AND ((FS1.CollectionGroupId=@rCollectionGroupId) OR (@rCollectionGroupId=0))  
			AND (FS1.IsOptional=0)  
			AND ((BM.Title = @rCommonBatch) OR (@rCommonBatch = ''))  
			AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))  
			AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=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(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')
			AND (ISNULL(CGM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rCollectionGrupId,','))OR @rCollectionGrupId='')
			AND (ISNULL(FS1.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='') 
			AND (ISNULL(SA1.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='')  

	UNION ALL  

		SELECT   
			FS1.FeeId,  
			FS1.Id,  
			ISNULL(FS1.IsOptional,0)AS IsOptional,  
			ISNULL(FS1.IsVariable,0)AS IsVariable,  
			ISNULL(FS1.Amount,0)AS Amount,  
			ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,  
			ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,  
			FS1.BatchId,  
			ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,  
			SA1.Id AS AcademicId,  
			FM.Title AS FeeName,  
			FM.FeeHeadId,
			ISNULL(CGM.Id,0) AS CollectionGroupId,
		    ISNULL(CGM.Title,'') AS CollectionGroup       
		FROM 
			sFee.tFeeSetup FS1  
			INNER JOIN sFee.tFeeOptional FO  
			ON FO.FeeSetupId=FS1.Id  
			INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId  
			INNER JOIN sStudent.tAcademic SA1 ON SA1.Id=FO.SourceId   
			AND SA1.BatchId = FS1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId AND SA1.ClassId = FS1.ClassId  
			AND ((SA1.ClassId=@rClassId) OR (@rClassId=0)) 
			AND (ISNULL(SA1.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='')
			AND ((SA1.DivisionId=@rDivisionId) OR (@rDivisionId=0))  
			AND (ISNULL(SA1.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='') 
			AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))  
			INNER JOIN sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId 
			LEFT JOIN sFee.tCollectionGroupMaster CGM ON FS1.CollectionGroupId=CGM.Id 
			--AND RBM.Id = CGM.ReceiptBookId 
			AND CGM.OrgGroupBatchId = @rOrgGroupBatchId 
		WHERE  
			BM.OrgGroupBatchId = @rOrgGroupBatchId  
			AND ((FS1.ClassId=@rClassId) OR (@rClassId=0))  
			AND ((SA1.OrgId=@rOrgId) OR (@rOrgId=0))  
			AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))  
			AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))  
			AND ((FS1.CollectionGroupId=@rCollectionGroupId) OR (@rCollectionGroupId=0))  
			AND (FS1.IsOptional=1)  
			AND ((BM.Title = @rCommonBatch) OR (@rCommonBatch = ''))  
			AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))  
			AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=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(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')  
			AND (ISNULL(CGM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rCollectionGrupId,','))OR @rCollectionGrupId='')
			AND (ISNULL(FS1.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='') 
			AND (ISNULL(SA1.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='')  
	 
	--select * from #TempIsOptional
	CREATE TABLE #TempReceipt
	(
		PaidAmount decimal(12,2),
		FeeSetupId int,
		SourceId bigint
	)
	
	INSERT INTO #TempReceipt
	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.tAcademic SA1 ON SA1.Id=R.SourceId  
		INNER JOIN sSetup.tBatchMaster BM ON BM.Id=SA1.BatchId     
		AND (SA1.ClassId=@rClassId OR @rClassId=0)
		AND (ISNULL(SA1.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='')   
		AND ((SA1.DivisionId=@rDivisionId) OR (@rDivisionId=0))  
		AND (ISNULL(SA1.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='') 
		AND (SA1.DivisionId=@rDivisionId OR @rDivisionId=0)  
	WHERE    
		(R.SourceTypeId = 2001)  
		AND ((SA1.OrgId=@rOrgId) OR (@rOrgId=0))  
		AND (R.IsObsolete = 0)   
		AND ((BM.OrgGroupBatchId = @rOrgGroupBatchId))  
		AND (R.OrgGroupBatchId = @rOrgGroupBatchId)  
		AND (R.ReceiptDate <= @rUptoDate) -- added condition after nes issue on 09/08/2016  
		-- OR (@rOrgGroupBatchId = @rOrgGroupBatchId))  
		AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))  
		AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))  
		AND ((BM.Title = @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 (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')
	GROUP BY FeeSetupId,R.SourceId
	
	--select * from #TempReceipt
	
	CREATE TABLE #TempAssignRoute
	(
		SourceId bigint  
	)
	

	INSERT INTO #TempAssignRoute
	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))
	
	IF(@rReportType=1)
	BEGIN	   
		SELECT   		  
		SA.AcademicId,  
		SA.RollNo,  
		SA.Name,  
		SA.Code,  
		SA.ClassId,  
		SA.DivisionId,  
		SA.ClassName,  
		SA.DivisionName,  		
		SA.ClassName+' - '+SA.DivisionName AS ClassDivision,  		  
		SUM(ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00))AS PendingAmount,  		
		SA.OrgId,  
		O.Title AS OrgName,  				
		ISNULL(SC.ParentContactNo,'') AS ParentContactNo,  		  
		ISNULL(CCM.Title,'') AS CastCategoryName,  		
		ISNULL((SELECT ISNULL(Template,'') FROM sCommon.tReportTemplate WHERE ReportId = @rReportId AND OrgId=SA.OrgId),0) AS ReportTemplate,
		SA.DepartmentName,
		(Select SUM(PaidAmount)
				FROM #TempReceipt R1
				Where R1.SourceId = SA.AcademicId) AS PaidAmount,
		--(SELECT  STUFF((SELECT ',' + Convert(varchar,ReceiptDate)
		--		FROM sFee.tReceipt
		--		where SourceId = SA.AcademicId
		--       FOR XML PATH('')
		--       ), 1, 1, '')) AS ReceiptDate
		sCommon.fGetDate() AS PrintDate
	
	FROM   
		sStudent.vStudentAcademic SA  
		INNER JOIN #TempIsOptional FS ON FS.AcademicId=SA.AcademicId  
		LEFT JOIN sFee.tFeeAllocation FA  
		ON FA.FeeSetupId=FS.Id AND FA.SourceId=SA.AcademicId  
		LEFT JOIN #TempReceipt R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId  
		INNER JOIN sSetup.tOrganizationMaster O ON   
		SA.OrgId = O.Id  
		INNER JOIN sFee.tReceiptBookMaster RBM   
		ON FS.ReceiptBookId=RBM.Id  
		LEFT JOIN sStudent.tStudentCommunication SC   
		ON SC.StudentId = SA.StudentId  
		LEFT JOIN sStudent.tStudentOther SO   
		ON SO.StudentId = SA.StudentId  
		LEFT JOIN sCommon.tCastCategoryMaster CCM   
		ON CCM.Id = SO.CastCategoryId    
		INNER JOIN sFee.tFeeHeadMaster FHM  
		ON FHM.Id = FS.FeeHeadId
		
		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))   
		LEFT JOIN #TempAssignRoute RT ON RT.SourceId = SA.StudentId AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))
		LEFT JOIN sStudent.tStudentFamily SSF ON SSF.StudentId = SA .StudentId
	WHERE   
		SA.OrgGroupBatchId = @rOrgGroupBatchId  
		AND ((SA.BatchId=@rBatchId) OR (@rBatchId=0))   
		AND (SA.StatusId = @rStatusId OR @rStatusId=0)  
		AND ((FS.StartDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))  
		AND ((SA.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))  
		AND ((SA.RollNo <= @rToRollNo) OR (@rToRollNo=0))  
		AND ((SA.Code=@rCode) OR (@rCode=''))  
		AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=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)))  
			)  
		AND (ISNULL(SA.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')      
		AND ((CCM.Id=@rCastCategoryId) OR (@rCastCategoryId=0)) 
		AND ((SA.ClassStatusId=@rClassStatusId) OR (@rClassStatusId=0))  
	GROUP BY
	SA.AcademicId,  
	SA.RollNo,  
	SA.Name,  
	SA.Code,  
	SA.ClassId,  
	SA.DivisionId,  
	SA.ClassName,  
	SA.DivisionName,
	SA.OrgId,  
	O.Title,  				
	SC.ParentContactNo,
	CCM.Title,
	SA.DepartmentName
	--R.PaidAmount,
	--R.SourceId
	Order by SA.RollNo  
	END	
	
	DROP TABLE #TempIsOptional
	DROP TABLE #TempReceipt
	DROP TABLE #TempAssignRoute
	
	--SELECT   
	--	'' AS Builder1,  
	--	'' AS Builder2,  
	--	0 AS IsDetail,  
	--	0 As IsFilter,  
	--	0 As IsHeader,  
	--	0 AS IsDisplayOrgGroup,  
	--	1104000002505 AS AcademicId,  
	--	0 AS RollNo,  
	--	'' AS Name,  
	--	'' AS Code,  
	--	0 AS ClassId,  
	--	0 AS DivisionId,  
	--	'' AS ClassName,  
	--	'' AS DivisionName,  
	--	0 AS DivisionOrder,  
	--	'' AS ClassDivision,  
	--	0 AS FeeSetupId,  
	--	0 AS IsVariable,  
	--	0.00 AS Amount,  
	--	'2001-01-30' AS StartDate,  
	--	'2001-01-30' AS EndDate,  
	--	0.00 AS FAAmount,  
	--	0.00 AS DiscountAmount,  
	--	0.00 AS AdditionalAmount,  
	--	0.00 AS PaidAmount,
	--	0.00 PendingAmount,
	--	'' AS Remark,  
	--	'' AS FeeName,  
	--	0 AS FeeHeadId,  
	--	'' AS FeeHeadName,  
	--	0 AS FeeHeadOrderIndex,  
	--	0 AS OrgId,  
	--	'' AS OrgName,  
	--	0 AS OrgOrderIndex,  
	--	0 AS ReceiptBookId,   
	--	'' AS ReceiptBookTitle,  
	--	0 AS ReceiptOrderIndex,    
	--	0 As ReceiptBookId,  
	--	'' AS ReceiptBookFullTitle,
	--	'' AS RecieptBookAddress1,
	--	'' As RecieptBookAddress2,
	--	'' As Remark1,
	--	0 AS ReceiptOrderIndex,  
	--	0 AS OrgGoupBatchId,  
	--	0 AS DepartmentId,  
	--	'' AS DepartmentName,  
	--	'' AS ParentContactNo,  
	--	'' AS ReferenceRemark,  
	--	'2001-01-30' AS PayDate ,  
	--	0 AS CastCategoryId,  
	--	'' AS CastCategoryName,  
	--	0 AS CastCategoryOrderIndex,
	--	'' AS ReportTemplate,
	--0 As CollectionGroupId,
	--'' AS CollectionGroup,
	--'' AS BatchName,
	--'' AS FatherName,
	--'' AS FatherContactNo,
	--'' AS MotherName,
	--'' AS MotherContactNo

	
END
GO
PRINT N'Altering [sFee].[pRptFeePendingAllBatchGet]...';


GO
 
ALTER PROCEDURE [sFee].[pRptFeePendingAllBatchGet]
		@rReportId int=0,
		@rReceiptBookId int=0,
		@rAdmissionCategoryId int=0,
		@rClassId int=0,
		@rDivisionId int=0,
		@rUptoDate date='',
		@rBatchId int='',
		@rUserId bigint=0,
		@rBuilder1 nvarchar(max)='',	
		@rBuilder2 nvarchar(max)='',
		@rIsDetail bit=0,
		@rOrgId int=0,
		@rOrgGroupBatchId int=0,
		@rStatusId int=0,
		@rCommonBatch nvarchar(100)='',
		@rDepartmentId int=0,
		@rFromRollNo int=0,
	    @rToRollNo int=0,
	    @rCode nvarchar(20)='',
	    @rIsFilter bit=0,
		@rIsHeader bit=0,		
		@rCreatedUserName nvarchar(20) = '',
		@rFeeHeadId nvarchar(max) = '',
		@rIsDisplayOrgGroup bit=0,
		@rFeeId nvarchar(max) = '',
		@rFilterId  int=0,
		@rOrgGroupId int = 0,
		@rOrgIds nvarchar(max) = '',
		@rReportType int=1,    
	    @rClassStatusId int=0,
		@rClassIds nvarchar(max) = '',
		@rDivisionIds nvarchar(max) = ''

	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
BEGIN 	
	
	DECLARE @p as TempPendingFee

	IF(@rReportType=1)
	BEGIN
	
		INSERT INTO  @p 
	 
	SELECT 
	
		SA.AcademicId,
		SA.RollNo,
		SA.Name,
		SA.Code,
		SA.ClassId,
		SA.DivisionId,
		SA.ClassName,
		SA.DivisionName,
		SA.ClassName+' - '+SA.DivisionName AS ClassDivision,
		FS.Id AS FeeSetupId,		
		ISNULL(FS.IsVariable,0)AS IsVariable,
		ISNULL(FS.Amount,0)AS Amount,
		ISNULL(FS.StartDate,'1900-01-01')AS StartDate,
		ISNULL(FS.EndDate,'1900-01-01')AS EndDate,
		ISNULL(FA.VariableAmount,0.00)AS FAAmount,
		ISNULL(FA.DiscountAmount,0.00)AS DiscountAmount,
		ISNULL(FA.AdditionalAmount,0.00)AS AdditionalAmount,
		ISNULL(R.PaidAmount,0) AS PaidAmount,
		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 PendingAmount,
		ISNULL(FA.Remark,'') AS Remark,
		FS.ReceiptBookId,
		FS.FeeName,
		FS.FeeCode,
		SA.OrgId,
		O.Title AS OrgName,
		O.OrderIndex AS OrgOrderIndex,
		ISNULL(RBM.Title,'') AS ReceiptBookTitle,
		ISNULL(RBM.OrderIndex,0) AS ReceiptOrderIndex,
		SA.BatchId,
		BM.Title AS BatchName,
	    RT.Pickup  AS Pickup,
		RT.DRoppoint As DRoppoint,
		SC.PresentContactNo,
		ISNULL(SA.SUID,'') AS SUID,
		SA.ClassOrderIndex,
		SA.DivisionOrder,
		FS.OrderIndex
  FROM 
  
			 sStudent.vStudentAcademic SA
			 Left join [sStudent].[tStudentCommunication] SC ON SC.studentId=SA.studentId
		INNER JOIN 
		(
			SELECT 
				FS1.FeeId,
				FS1.Id,
				ISNULL(FS1.IsOptional,0)AS IsOptional,
				ISNULL(FS1.IsVariable,0)AS IsVariable,
				ISNULL(FS1.Amount,0)AS Amount,
				ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
				ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
				FS1.BatchId,
				ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
				SA1.AcademicId,
				FM.Title AS FeeName,
				FM.Code AS FeeCode,
				FM.OrderIndex
			FROM sFee.tFeeSetup FS1
			INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId 
				AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId				
				AND ((SA1.ClassId=@rClassId) OR (@rClassId=0)) 
				AND (ISNULL(SA1.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='')
				AND ((SA1.DivisionId=@rDivisionId) OR (@rDivisionId=0))
				AND (ISNULL(SA1.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='')
				AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
			INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
			WHERE 
				(CAST(LEFT(SA1.OrgGroupBatchId, 4) AS int) = @rOrgGroupId OR @rOrgGroupId=0)
			    AND ((SA1.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
				AND	((FS1.ClassId=@rClassId) OR (@rClassId=0))
				AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
				AND (FS1.IsOptional=0)
				AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
				AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=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(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')
				AND ((SA1.Code=@rCode) OR (@rCode=''))
				AND (ISNULL(FS1.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='')
				AND (ISNULL(SA1.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='')
				UNION ALL
				
			SELECT 
				FS1.FeeId,
				FS1.Id,
				ISNULL(FS1.IsOptional,0)AS IsOptional,
				ISNULL(FS1.IsVariable,0)AS IsVariable,
				ISNULL(FS1.Amount,0)AS Amount,
				ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
				ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
				FS1.BatchId,
				ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
				SA1.AcademicId,
				FM.Title AS FeeName,
				FM.Code AS FeeCode,
				FM.OrderIndex
			FROM sFee.tFeeSetup FS1
		INNER JOIN sFee.tFeeOptional FO
			ON FO.FeeSetupId=FS1.Id
	    INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
		INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=FO.SourceId AND SA1.BatchId = FS1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
		AND SA1.ClassId = FS1.ClassId
			AND ((SA1.ClassId=@rClassId) OR (@rClassId=0)) 
			AND (ISNULL(SA1.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='')
			AND ((SA1.DivisionId=@rDivisionId) OR (@rDivisionId=0))
			AND (ISNULL(SA1.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='')
			AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
		WHERE
				(CAST(LEFT(SA1.OrgGroupBatchId, 4) AS int) = @rOrgGroupId OR @rOrgGroupId=0)
		        AND ((SA1.OrgGroupBatchId = @rOrgGroupBatchId)  OR (@rOrgGroupBatchId=0))
				AND ((FS1.ClassId=@rClassId) OR (@rClassId=0))
				AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
				AND (FS1.IsOptional=1)
				AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
				AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=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(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')
				AND ((SA1.Code=@rCode) OR (@rCode=''))
				AND (ISNULL(FS1.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='')
				AND (ISNULL(SA1.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='')
		) FS ON FS.AcademicId=SA.AcademicId
		LEFT JOIN sFee.tFeeAllocation FA
			ON FA.FeeSetupId=FS.Id AND FA.SourceId=SA.AcademicId
		LEFT JOIN
		(
		    SELECT 
					ISNULL(SUM(RD.Amount),0) AS PaidAmount,RD.FeeSetupId ,R.SourceId
		    FROM
				sFee.tReceipt R 
				INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id 
				INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id
				INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id
				INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=R.SourceId
				AND (SA1.ClassId=@rClassId OR @rClassId=0) 
				AND (ISNULL(SA1.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='')
				AND (SA1.DivisionId=@rDivisionId OR @rDivisionId=0)
				AND (ISNULL(SA1.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='')
			WHERE	
				(CAST(LEFT(SA1.OrgGroupBatchId, 4) AS int) = @rOrgGroupId OR @rOrgGroupId=0)
				AND (R.SourceTypeId = 2001)
				AND ((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND (R.IsObsolete = 0) 
				AND ((SA1.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
				AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((R.CreatedUserId=@rUserId) OR (@rUserId=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 (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')
				AND ((SA1.Code=@rCode) OR (@rCode=''))
		
				GROUP BY FeeSetupId,R.SourceId
		) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
		 INNER JOIN sSetup.tOrganizationMaster O ON
		 SA.OrgId = O.Id
		 INNER JOIN sFee.tReceiptBookMaster RBM 
			ON FS.ReceiptBookId=RBM.Id
		 INNER JOIN sSetup.tBatchMaster BM 
			ON BM.Id=SA.BatchId	
      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,B.Title As Pickup,B1.Title As DRoppoint 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))
	Left JOIN sTransport.tBusRouteDestinationMaster BM1 ON BM1.Id=AT.DropDestinationId
    LEFT JOIN sTransport.tBusRouteMaster B1 ON B1.Id=BM1.BusRouteId AND  AT.SourceTypeId=2003 AND ((B1.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))
 ) RT
    ON RT.SourceId = SA.StudentId 
    AND ((SA.OrgGroupBatchId = RT.OrgGroupBatchId))
    AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) 
	WHERE	
			(CAST(LEFT(SA.OrgGroupBatchId, 4) AS int) = @rOrgGroupId OR @rOrgGroupId=0)
			AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
			AND ((SA.BatchId=@rBatchId) OR (@rBatchId=0)) 
			AND (SA.StatusId = @rStatusId OR @rStatusId=0)
			AND ((FS.StartDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
			AND ((SA.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
			AND ((SA.RollNo <= @rToRollNo) OR (@rToRollNo=0))
			AND ((SA.Code=@rCode) OR (@rCode=''))
			AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=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)))
			    )
		   AND (ISNULL(SA.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')
		   AND ((SA.ClassStatusId=@rClassStatusId) OR (@rClassStatusId=0))	   
			Order by SA.RollNo
 
		SELECT
			@rBuilder1 AS Builder1,
			@rIsDisplayOrgGroup AS IsDisplayOrgGroup,
			OrgId,			 
			ReceiptBookId,
			AcademicId,
			DivisionId,
			ClassDivision,
			RollNo, 
			Name,
			Code,
			ReceiptBookTitle,
			OrgName,
			SUM(PendingAmount) AS PendingAmount, 
			[sFee].[fPendingFeeNamesGet](AcademicId,ReceiptBookId,	@p) AS PendingFeeName,
			ReceiptOrderIndex,
			BatchId,
			BatchName,
		    Pickup,
			DRoppoint,
			PresentContactNo,
			SUID,
			ClassOrderIndex,
			DivisionOrderIndex
			FROM @p 
			
			GROUP By 
			OrgId,AcademicId,ReceiptBookId,DivisionId,BatchId,
			ClassDivision,RollNo, Name,Code,ReceiptBookTitle,OrgName,ReceiptOrderIndex,BatchName,Pickup,DRoppoint,PresentContactNo,SUID,ClassOrderIndex,DivisionOrderIndex
			ORDER BY AcademicId Desc
	END
	ELSE
	BEGIN
	
	INSERT INTO  @p 
	SELECT 
	
		SA.AcademicId,
		SA.RollNo,
		SA.Name,
		SA.Code,
		SA.ClassId,
		SA.DivisionId,
		SA.ClassName,
		SA.DivisionName,
		SA.ClassName+' - '+SA.DivisionName AS ClassDivision,
		FS.Id AS FeeSetupId,		
		ISNULL(FS.IsVariable,0)AS IsVariable,
		ISNULL(FAS.FeeAmount,0)AS Amount,
		ISNULL(FS.StartDate,'1900-01-01')AS StartDate,
		ISNULL(FS.EndDate,'1900-01-01')AS EndDate,
		ISNULL(FAS.VariableAmount,0.00)AS FAAmount,
		ISNULL(FAS.DiscountAmount,0.00)AS DiscountAmount,
		ISNULL(FAS.AdditionalAmount,0.00)AS AdditionalAmount,
		ISNULL(FAS.PaidAmount,0) AS PaidAmount,
		ISNULL(FAS.ToPayAmount,0) AS PendingAmount,
		--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 PendingAmount,
		ISNULL(FAS.Remark,'') AS Remark,
		FS.ReceiptBookId,
		--FS.FeeName,
		FM.Title AS FeeName, 
		FM.Code AS FeeCode,
		--FS.FeeCode,
		SA.OrgId,
		O.Title AS OrgName,
		O.OrderIndex AS OrgOrderIndex,
		ISNULL(RBM.Title,'') AS ReceiptBookTitle,
		ISNULL(RBM.OrderIndex,0) AS ReceiptOrderIndex,
		SA.BatchId,
		BM.Title AS BatchName,
	    RT.Pickup  AS Pickup,
		RT.DRoppoint As DRoppoint,
		SC.PresentContactNo,
		ISNULL(SA.SUID,'') AS SUID,
		SA.ClassOrderIndex,
		SA.DivisionOrder,
		FM.OrderIndex
  FROM	 sStudent.vStudentAcademic SA
        INNER JOIN sFee.tFeeAllocationStudent FAS ON FAS.AcademicId = SA.AcademicId
		INNER JOIN sFee.tFeeSetup FS ON FS.ID=FAS.FeeSetupId	
		INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS.FeeId
		INNER JOIN sSetup.tOrganizationMaster O ON SA.OrgId = O.Id
		INNER JOIN sFee.tReceiptBookMaster RBM ON FS.ReceiptBookId=RBM.Id		
		INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FM.FeeHeadId
		LEFT JOIN sStudent.tStudentCommunication SC	ON SC.StudentId = SA.StudentId 
		INNER JOIN sSetup.tBatchMaster BM ON BM.Id=SA.BatchId	
        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,B.Title As Pickup,B1.Title As DRoppoint 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))
	    Left JOIN sTransport.tBusRouteDestinationMaster BM1 ON BM1.Id=AT.DropDestinationId
        LEFT JOIN sTransport.tBusRouteMaster B1 ON B1.Id=BM1.BusRouteId AND  AT.SourceTypeId=2003 AND ((B1.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))
        ) RT
        ON RT.SourceId = SA.StudentId 
        AND ((SA.OrgGroupBatchId = RT.OrgGroupBatchId))
        AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) 
	    WHERE	
			(CAST(LEFT(SA.OrgGroupBatchId, 4) AS int) = @rOrgGroupId OR @rOrgGroupId=0)
			AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
			AND ((SA.BatchId=@rBatchId) OR (@rBatchId=0)) 
			AND (SA.StatusId = @rStatusId OR @rStatusId=0)
			AND ((FS.StartDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
			AND ((SA.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
			AND ((SA.RollNo <= @rToRollNo) OR (@rToRollNo=0))
			AND ((SA.Code=@rCode) OR (@rCode=''))
			AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=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(FAS.ToPayAmount,0) !=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(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(SA.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')  
		   AND ((SA.ClassStatusId=@rClassStatusId) OR (@rClassStatusId=0))  
			Order by SA.RollNo

			
				SELECT
			@rBuilder1 AS Builder1,
			@rIsDisplayOrgGroup AS IsDisplayOrgGroup,
			OrgId,			 
			ReceiptBookId,
			AcademicId,
			DivisionId,
			ClassDivision,
			RollNo, 
			Name,
			Code,
			ReceiptBookTitle,
			OrgName,
			SUM(PendingAmount) AS PendingAmount, 
			[sFee].[fPendingFeeNamesGet](AcademicId,ReceiptBookId,	@p) AS PendingFeeName,
			ReceiptOrderIndex,
			BatchId,
			BatchName,
		    Pickup,
			DRoppoint,
			PresentContactNo,
			SUID,
			ClassOrderIndex,
			DivisionOrderIndex
			
			FROM @p 
			
			GROUP By 
			OrgId,AcademicId,ReceiptBookId,DivisionId,BatchId,
			ClassDivision,RollNo, Name,Code,ReceiptBookTitle,OrgName,ReceiptOrderIndex,BatchName,Pickup,DRoppoint,PresentContactNo,SUID,ClassOrderIndex,
			DivisionOrderIndex,
			DivisionOrderIndex
			ORDER BY AcademicId
	END
END
GO
PRINT N'Altering [sFee].[pRptFeePendingDetailListGet]...';


GO
ALTER PROCEDURE [sFee].[pRptFeePendingDetailListGet]  

	@rReportId int=0,  
	@rReceiptBookId int=0,
	@rReceiptBookIds nvarchar(max) = '',
	@rAdmissionCategoryId int=0,  
	@rClassId int=0,  
	@rDivisionId int=0,  
	@rUptoDate date='',  
	@rBatchId int=0,  
	@rUserId bigint=0,  
	@rBuilder1 nvarchar(max) = '',  
	@rBuilder2 nvarchar(max) = '',  
	@rIsDetail bit=0,  
	@rOrgId int=0,  
	@rOrgGroupBatchId int=0,  
	@rStatusId int=0,  
	@rCommonBatch nvarchar(100) = '',  
	@rDepartmentId int=0,  
	@rFromRollNo int=0,  
	@rToRollNo int=0,  
	@rCode nvarchar(20)='',  
	@rIsFilter bit=0,  
	@rIsHeader bit=0,    
	@rCreatedUserName nvarchar(20) = '',  
	@rIsReceiptBookGroup bit=0,  
	@rFeeHeadId nvarchar(max) = '',  
	@rIsDisplayOrgGroup bit=0,  
	@rFeeId nvarchar(max) = '',  
	@rFilterId int=0,  
	@rOrgIds  nvarchar(max) = '',  
	@rPayDate date='',  
	@rCollectionGroupId int =0,  
	@rCastCategoryId int = 0,
	@rReportType int=0,
	@rClassStatusId int=0 ,
	@rCollectionGrupId nvarchar(max) ='',
	@rClassIds nvarchar(max) = '',
	@rDivisionIds nvarchar(max) = ''
	 
WITH EXECUTE AS CALLER  
AS  
SET NOCOUNT ON  
BEGIN 
	
	CREATE TABLE #TempIsOptional
	(
		FeeId int,  
		Id int,  
		IsOptional bit,  
		IsVariable bit,  
		Amount decimal(12,2),  
		StartDate date,  
		EndDate date,  
		BatchId int,  
		ReceiptBookId int,  
		AcademicId bigint,  
		FeeName nvarchar(100),  
		FeeHeadId int,
		CollectionGroupId int,
		CollectionGroup nvarchar(max),
		FeeOrderIndex int,
		CollectionGroupOrderIndex int
	)
	
	INSERT INTO #TempIsOptional
		SELECT   
			FS1.FeeId,  
			FS1.Id,  
			ISNULL(FS1.IsOptional,0)AS IsOptional,  
			ISNULL(FS1.IsVariable,0)AS IsVariable,  
			ISNULL(FS1.Amount,0)AS Amount,  
			ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,  
			ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,  
			FS1.BatchId,  
			ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,  
			SA1.Id AS AcademicId,  
			FM.Title AS FeeName,  
			FM.FeeHeadId,
			ISNULL(CGM.Id,0) AS CollectionGroupId,
		    ISNULL(CGM.Title,'') AS CollectionGroup,
			FM.OrderIndex,
			CGM.OrderIndex  AS CollectionGroupOrderIndex     
		FROM 
			sFee.tFeeSetup FS1  
			INNER JOIN sStudent.tAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId   
			INNER JOIN sStudent.tStudentMaster SM ON SA1.StudentId = SM.Id      
			AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId  
			AND ((SA1.ClassId=@rClassId) OR (@rClassId=0)) 
			AND (ISNULL(SA1.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='')
			AND ((SA1.DivisionId=@rDivisionId) OR (@rDivisionId=0))
			AND (ISNULL(SA1.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='')  
			AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))  
			INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId  
			INNER JOIN sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId  
			LEFT JOIN sFee.tCollectionGroupMaster CGM ON FS1.CollectionGroupId=CGM.Id 
			--AND RBM.Id = CGM.ReceiptBookId 
			AND CGM.OrgGroupBatchId = @rOrgGroupBatchId
		WHERE   
			BM.OrgGroupBatchId = @rOrgGroupBatchId  
			AND ((FS1.ClassId=@rClassId) OR (@rClassId=0))      
			AND ((SA1.OrgId=@rOrgId) OR (@rOrgId=0))  
			AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))  
			AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))  
			AND (FS1.ReceiptBookId IN(SELECT cast(item as int) FROM  sCommon.fnsplit(@rReceiptBookIds,',')) OR @rReceiptBookIds='')
			AND ((FS1.CollectionGroupId=@rCollectionGroupId) OR (@rCollectionGroupId=0))  
			AND (FS1.IsOptional=0)  
			AND ((BM.Title = @rCommonBatch) OR (@rCommonBatch = ''))  
			AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))  
			AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=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(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')
			AND (ISNULL(CGM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rCollectionGrupId,','))OR @rCollectionGrupId='')
			AND (ISNULL(FS1.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='') 
			AND (ISNULL(SA1.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='')  

	UNION ALL  

		SELECT   
			FS1.FeeId,  
			FS1.Id,  
			ISNULL(FS1.IsOptional,0)AS IsOptional,  
			ISNULL(FS1.IsVariable,0)AS IsVariable,  
			ISNULL(FS1.Amount,0)AS Amount,  
			ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,  
			ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,  
			FS1.BatchId,  
			ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,  
			SA1.Id AS AcademicId,  
			FM.Title AS FeeName,  
			FM.FeeHeadId,
			ISNULL(CGM.Id,0) AS CollectionGroupId,
		    ISNULL(CGM.Title,'') AS CollectionGroup,
			FM.OrderIndex,
			CGM.OrderIndex  AS CollectionGroupOrderIndex       
		FROM 
			sFee.tFeeSetup FS1  
			INNER JOIN sFee.tFeeOptional FO  
			ON FO.FeeSetupId=FS1.Id  
			INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId  
			INNER JOIN sStudent.tAcademic SA1 ON SA1.Id=FO.SourceId   
			AND SA1.BatchId = FS1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId AND SA1.ClassId = FS1.ClassId  
			
			AND ((SA1.ClassId=@rClassId) OR (@rClassId=0)) 
			AND (ISNULL(SA1.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='')
			AND ((SA1.DivisionId=@rDivisionId) OR (@rDivisionId=0)) 
			AND (ISNULL(SA1.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='')  
			AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))  
			INNER JOIN sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId 
			LEFT JOIN sFee.tCollectionGroupMaster CGM ON FS1.CollectionGroupId=CGM.Id 
			--AND RBM.Id = CGM.ReceiptBookId 
			AND CGM.OrgGroupBatchId = @rOrgGroupBatchId
		WHERE  
			BM.OrgGroupBatchId = @rOrgGroupBatchId  
			AND ((FS1.ClassId=@rClassId) OR (@rClassId=0))  
			AND ((SA1.OrgId=@rOrgId) OR (@rOrgId=0))  
			AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))  
			AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))  
			AND (FS1.ReceiptBookId IN(SELECT cast(item as int) FROM  sCommon.fnsplit(@rReceiptBookIds,',')) OR @rReceiptBookIds='')
			AND ((FS1.CollectionGroupId=@rCollectionGroupId) OR (@rCollectionGroupId=0))  
			AND (FS1.IsOptional=1)  
			AND ((BM.Title = @rCommonBatch) OR (@rCommonBatch = ''))  
			AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))  
			AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=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(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')  
			AND (ISNULL(CGM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rCollectionGrupId,','))OR @rCollectionGrupId='')
			AND (ISNULL(FS1.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='')
			AND (ISNULL(SA1.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='')   
	 
	CREATE TABLE #TempReceipt
	(
		PaidAmount decimal(12,2),
		FeeSetupId int,
		SourceId bigint  
	)
	
	INSERT INTO #TempReceipt
	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.tAcademic SA1 ON SA1.Id=R.SourceId  
		INNER JOIN sSetup.tBatchMaster BM ON BM.Id=SA1.BatchId     
		AND (SA1.ClassId=@rClassId OR @rClassId=0)   
		AND (ISNULL(SA1.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='')
		AND ((SA1.DivisionId=@rDivisionId) OR (@rDivisionId=0))  
		AND (ISNULL(SA1.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='') 
		AND (SA1.DivisionId=@rDivisionId OR @rDivisionId=0)  
	WHERE    
		(R.SourceTypeId = 2001)  
		AND ((SA1.OrgId=@rOrgId) OR (@rOrgId=0))  
		AND (R.IsObsolete = 0)   
		AND ((BM.OrgGroupBatchId = @rOrgGroupBatchId))  
		AND (R.OrgGroupBatchId = @rOrgGroupBatchId)  
		AND (R.ReceiptDate <= @rUptoDate) -- added condition after nes issue on 09/08/2016  
		-- OR (@rOrgGroupBatchId = @rOrgGroupBatchId))  
		AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))  
		AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))  
		AND ((BM.Title = @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 (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')
	GROUP BY FeeSetupId,R.SourceId  
	
	CREATE TABLE #TempAssignRoute
	(
		SourceId bigint  
	)
	
	INSERT INTO #TempAssignRoute
	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))
	
	IF(@rReportType=1)
	BEGIN	   
		SELECT   
		@rBuilder1 AS Builder1,  
		@rBuilder2 AS Builder2,  
		@rIsDetail AS IsDetail,  
		@rIsFilter As IsFilter,  
		@rIsHeader As IsHeader,  
		@rIsDisplayOrgGroup AS IsDisplayOrgGroup,  
		SA.AcademicId,  
		SA.RollNo,  
		SA.Name,  
		SA.Code,  
		SA.ClassId,  
		SA.DivisionId,  
		SA.ClassName,  
		SA.DivisionName,  
		SA.DivisionOrder,  
		SA.ClassName+' - '+SA.DivisionName AS ClassDivision,  
		FS.Id AS FeeSetupId,  
		ISNULL(FS.IsVariable,0)AS IsVariable,  
		ISNULL(FS.Amount,0)AS Amount,  
		ISNULL(FS.StartDate,'1900-01-01')AS StartDate,  
		ISNULL(FS.EndDate,'1900-01-01')AS EndDate,  
		ISNULL(FA.VariableAmount,0.00)AS FAAmount,  
		ISNULL(FA.DiscountAmount,0.00)AS DiscountAmount,  
		ISNULL(FA.AdditionalAmount,0.00)AS AdditionalAmount,  
		ISNULL(R.PaidAmount,0) AS PaidAmount,  
		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 PendingAmount,  
		ISNULL(FA.Remark,'') AS Remark,  
		FS.FeeName,  
		FHM.Id AS FeeHeadId,  
		FHM.Title AS FeeHeadName,  
		FHM.OrderIndex AS FeeHeadOrderIndex,  
		SA.OrgId,  
		O.Title AS OrgName,  
		O.OrderIndex AS OrgOrderIndex,  
		(CASE WHEN @rIsReceiptBookGroup = 0 THEN 0  
		WHEN @rIsReceiptBookGroup = 1 THEN FS.ReceiptBookId  
		END) AS ReceiptBookId,   
		(CASE WHEN @rIsReceiptBookGroup = 0 THEN 'ALL'  
		WHEN @rIsReceiptBookGroup = 1 THEN ISNULL(RBM.Title,'')  
		END) AS ReceiptBookTitle,  
		(CASE WHEN @rIsReceiptBookGroup = 0 THEN 0  
		WHEN @rIsReceiptBookGroup = 1 THEN ISNULL(RBM.OrderIndex,0)  
		END) AS ReceiptOrderIndex,    
		--FS.ReceiptBookId,  
		ISNULL(RBM.FullTitle,'') AS ReceiptBookFullTitle,
		ISNULL(RBM.Address1,'') AS RecieptBookAddress1,
		IsNULL(RBM.Address2,'') As RecieptBookAddress2,
		IsNULL(RBM.Remark1,'') As Remark1,
		--ISNULL(RBM.OrderIndex,0) AS ReceiptOrderIndex,  
		SA.OrgGroupBatchId,  
		SA.DepartmentId,  
		SA.DepartmentName,  
		ISNULL(SC.ParentContactNo,'') AS ParentContactNo,  
		ISNULL(SO.ReferenceRemark,'') AS ReferenceRemark,  
		@rPayDate AS PayDate ,  
		ISNULL(CCM.MainCastCategoryId,0) AS CastCategoryId,  
		ISNULL(CCM.Title,'') AS CastCategoryName,  
		ISNULL(CCM.OrderIndex,'') AS CastCategoryOrderIndex,
		ISNULL((SELECT ISNULL(Template,'') FROM sCommon.tReportTemplate WHERE ReportId = @rReportId AND OrgId=SA.OrgId),0) AS ReportTemplate  ,
		FS.CollectionGroupId,
		FS.CollectionGroup,
		SA.BatchName,
		ISNULL(SSF.FatherName, '') AS FatherName,
		ISNULL(SSF.FatherContactNo, '') AS FatherContactNo,
		ISNULL(SSF.MotherName, '') AS MotherName,
		ISNULL(SSF.MotherContactNo, '') AS MotherContactNo,
		FS.FeeOrderIndex AS FeeOrderIndex,
		ISNULL(SC.PresentStreetOne,'')+' '+ISNULL(SC.PresentStreetTwo,'')+' '+ISNULL(SC.PresentStreetThree,'')+' '+ISNULL(SC.PresentCity,'')+' '+ISNULL(SC.PresentState,'') AS [Address],
		ISNULL(SC.StudentContactNo,'') AS StudentContactNo,
	 SA.GenderId,
	 SA.FirstName as StudentName,
	 FS.CollectionGroupOrderIndex,
	 SA.SUId AS SUId

	FROM   
		sStudent.vStudentAcademic SA  
		INNER JOIN #TempIsOptional FS ON FS.AcademicId=SA.AcademicId  
		LEFT JOIN sFee.tFeeAllocation FA  
		ON FA.FeeSetupId=FS.Id AND FA.SourceId=SA.AcademicId  
		LEFT JOIN #TempReceipt R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId  
		INNER JOIN sSetup.tOrganizationMaster O ON   
		SA.OrgId = O.Id  
		INNER JOIN sFee.tReceiptBookMaster RBM   
		ON FS.ReceiptBookId=RBM.Id  
		LEFT JOIN sStudent.tStudentCommunication SC   
		ON SC.StudentId = SA.StudentId  
		LEFT JOIN sStudent.tStudentOther SO   
		ON SO.StudentId = SA.StudentId  
		LEFT JOIN sCommon.tCastCategoryMaster CCM   
		ON CCM.Id = SO.CastCategoryId    
		INNER JOIN sFee.tFeeHeadMaster FHM  
		ON FHM.Id = FS.FeeHeadId
		
		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))   
		LEFT JOIN #TempAssignRoute RT ON RT.SourceId = SA.StudentId AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))
		LEFT JOIN sStudent.tStudentFamily SSF ON SSF.StudentId = SA .StudentId
	WHERE   
		SA.OrgGroupBatchId = @rOrgGroupBatchId  
		AND ((SA.BatchId=@rBatchId) OR (@rBatchId=0))   
		AND (SA.StatusId = @rStatusId OR @rStatusId=0)  
		AND ((FS.StartDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))  
		AND ((SA.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))  
		AND ((SA.RollNo <= @rToRollNo) OR (@rToRollNo=0))  
		AND ((SA.Code=@rCode) OR (@rCode=''))  
		AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=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)))  
			)  
		AND (ISNULL(SA.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')       
		AND ((CCM.Id=@rCastCategoryId) OR (@rCastCategoryId=0)) 
		AND ((SA.ClassStatusId=@rClassStatusId) OR (@rClassStatusId=0))
	Order by SA.RollNo  
	END
	ELSE
	BEGIN
	SELECT   
		@rBuilder1 AS Builder1,  
		@rBuilder2 AS Builder2,  
		@rIsDetail AS IsDetail,  
		@rIsFilter As IsFilter,  
		@rIsHeader As IsHeader,  
		@rIsDisplayOrgGroup AS IsDisplayOrgGroup,  
		SA.AcademicId,  
		SA.RollNo,  
		SA.Name,  
		SA.Code,  
		SA.ClassId,  
		SA.DivisionId,  
		SA.ClassName,  
		SA.DivisionName,  
		SA.DivisionOrder,  
		SA.ClassName+' - '+SA.DivisionName AS ClassDivision,  
		FS.Id AS FeeSetupId,  
		ISNULL(FS.IsVariable,0)AS IsVariable,  
		ISNULL(FS.Amount,0)AS Amount,  
		ISNULL(FS.StartDate,'1900-01-01')AS StartDate,  
		ISNULL(FS.EndDate,'1900-01-01')AS EndDate,  
		ISNULL(FA.VariableAmount,0.00)AS FAAmount,  
		ISNULL(FA.DiscountAmount,0.00)AS DiscountAmount,  
		ISNULL(FA.AdditionalAmount,0.00)AS AdditionalAmount,  
		ISNULL(FAS.PaidAmount,0) AS PaidAmount,
		ISNULL(FAS.ToPayAmount,0.00) PendingAmount,
		ISNULL(FA.Remark,'') AS Remark,  
		--FS.FeeName,  
		FM.Title AS FeeName,  
		FHM.Id AS FeeHeadId,  
		FHM.Title AS FeeHeadName,  
		FHM.OrderIndex AS FeeHeadOrderIndex,  
		SA.OrgId,  
		O.Title AS OrgName,  
		O.OrderIndex AS OrgOrderIndex,  
		(CASE WHEN @rIsReceiptBookGroup = 0 THEN 0  
		WHEN @rIsReceiptBookGroup = 1 THEN FS.ReceiptBookId  
		END) AS ReceiptBookId,   
		(CASE WHEN @rIsReceiptBookGroup = 0 THEN 'ALL'  
		WHEN @rIsReceiptBookGroup = 1 THEN ISNULL(RBM.Title,'')  
		END) AS ReceiptBookTitle,  
		(CASE WHEN @rIsReceiptBookGroup = 0 THEN 0  
		WHEN @rIsReceiptBookGroup = 1 THEN ISNULL(RBM.OrderIndex,0)  
		END) AS ReceiptOrderIndex,    
		ISNULL(FS.ReceiptBookId,'0') As ReceiptBookId,  
		ISNULL(RBM.FullTitle,'') AS ReceiptBookFullTitle,
		ISNULL(RBM.Address1,'') AS RecieptBookAddress1,
		IsNULL(RBM.Address2,'') As RecieptBookAddress2,
		IsNULL(RBM.Remark1,'') As Remark1,
		ISNULL(RBM.OrderIndex,0) AS ReceiptOrderIndex,  
		SA.OrgGroupBatchId,  
		SA.DepartmentId,  
		SA.DepartmentName,  
		ISNULL(SC.ParentContactNo,'') AS ParentContactNo,  
		ISNULL(SO.ReferenceRemark,'') AS ReferenceRemark,  
		@rPayDate AS PayDate ,  
		ISNULL(CCM.MainCastCategoryId,0) AS CastCategoryId,  
		ISNULL(CCM.Title,'') AS CastCategoryName,  
		ISNULL(CCM.OrderIndex,'') AS CastCategoryOrderIndex,
		ISNULL((SELECT ISNULL(Template,'') FROM sCommon.tReportTemplate WHERE ReportId = @rReportId AND OrgId=SA.OrgId),0) AS ReportTemplate,
		ISNULL(CGM.Id,0) AS CollectionGroupId,
		ISNULL(CGM.Title,'') AS CollectionGroup,
		SA.BatchName,
		ISNULL(SSF.FatherName, '') AS FatherName,
		ISNULL(SSF.FatherContactNo, '') AS FatherContactNo,
		ISNULL(SSF.MotherName, '') AS MotherName,
		ISNULL(SSF.MotherContactNo, '') AS MotherContactNo,
		FM.OrderIndex AS FeeOrderIndex,
		ISNULL(SC.PresentStreetOne,'')+' '+ISNULL(SC.PresentStreetTwo,'')+' '+ISNULL(SC.PresentStreetThree,'')+' '+ISNULL(SC.PresentCity,'')+' '+ISNULL(SC.PresentState,'') AS [Address],
		ISNULL(SC.StudentContactNo,'') AS StudentContactNo,
		CGM.OrderIndex  AS CollectionGroupOrderIndex,
		SA.SUId AS SUId
	FROM   
		sStudent.vStudentAcademic SA		
		INNER JOIN sFee.tFeeAllocationStudent FAS ON FAS.AcademicId=  SA.AcademicId	
		INNER JOIN sFee.tFeeSetup FS ON FS.ID=FAS.FeeSetupId	
		INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS.FeeId
		INNER JOIN sSetup.tOrganizationMaster O ON SA.OrgId = O.Id
		INNER JOIN sFee.tReceiptBookMaster RBM ON FS.ReceiptBookId=RBM.Id		
		INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FM.FeeHeadId
		LEFT JOIN sFee.tFeeAllocation FA ON FA.FeeSetupId=FAS.FeeSetupId AND FA.SourceId=SA.AcademicId  
		LEFT JOIN sStudent.tStudentCommunication SC	ON SC.StudentId = SA.StudentId  
		LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId = SA.StudentId  
		LEFT JOIN sCommon.tCastCategoryMaster CCM ON CCM.Id = SO.CastCategoryId
		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)) 
        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 = SA.StudentId AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))
		LEFT JOIN sFee.tCollectionGroupMaster CGM ON FS.CollectionGroupId=CGM.Id 
		AND CGM.OrgGroupBatchId = @rOrgGroupBatchId
		LEFT JOIN sStudent.tStudentFamily SSF ON SSF.StudentId = SA .StudentId
	WHERE   
		SA.OrgGroupBatchId = @rOrgGroupBatchId  
		AND ((SA.BatchId=@rBatchId) OR (@rBatchId=0))   
		AND (SA.StatusId = @rStatusId OR @rStatusId=0)  
		AND ((FS.StartDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))  
		AND ((SA.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))  
		AND ((SA.RollNo <= @rToRollNo) OR (@rToRollNo=0))  
		AND ((SA.Code=@rCode) OR (@rCode=''))  
		AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=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(FAS.ToPayAmount,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)))  
			)  
		AND (ISNULL(SA.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')       
		AND ((CCM.Id=@rCastCategoryId) OR (@rCastCategoryId=0))   
		AND ((SA.ClassStatusId=@rClassStatusId) OR (@rClassStatusId=0))
		AND (ISNULL(CGM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rCollectionGrupId,','))OR @rCollectionGrupId='')
	Order by SA.RollNo  
	END
	
	DROP TABLE #TempIsOptional
	DROP TABLE #TempReceipt
	DROP TABLE #TempAssignRoute


	
	--SELECT 
	--    '' as Builder1,  
	--	'' as Builder2,  
	--	Convert(bit,0) as IsDetail,  
	--	Convert(bit,0) as IsFilter,  
	--	Convert(bit,0) as IsHeader,  
	--	Convert(bit,0) as IsDisplayOrgGroup,  
	--	0 as AcademicId,  
	--	0 As RollNo,  
	--	'' as Name,  
	--	'' As Code,  
	--	0 as ClassId,  
	--	0 as DivisionId,  
	--	'' as ClassName,  
	--	'' as DivisionName,  
	--	0 as DivisionOrder,  
	--	 '' as ClassDivision,  
	--	0 as FeeSetupId,  
	--	Convert(bit,0) as IsVariable,  
	--	 0.00 As Amount,  
	--	'2001-01-30' AS StartDate,  
	--	'2001-01-30' As EndDate,  
	--	0.00 As FAAmount,  
	--	0.00 As DiscountAmount,  
	--	0.00 As AdditionalAmount,  
	--	0.00 As PaidAmount,
	--	0.00 As  PendingAmount,
	--	'' AS Remark,  
	--	--FS.FeeName,  
	--	'' AS FeeName,  
	--	0 AS FeeHeadId,  
	--	'' AS FeeHeadName,  
	--	0 As FeeHeadOrderIndex,  
	--	0 As OrgId,  
	--	'' AS OrgName,  
	--	0 AS OrgOrderIndex,  
	--	0 AS ReceiptBookId,   
	--	'' AS ReceiptBookTitle,  
	--	0 AS ReceiptOrderIndex,    
	--	'' AS ReceiptBookFullTitle,
	--	'' AS RecieptBookAddress1,
	--	'' AS RecieptBookAddress2,
	--	'' As Remark1,
	--	0 As OrgGroupBatchId,  
	--	0 As DepartmentId,  
	--	'' AS DepartmentName,  
	--	'' AS ParentContactNo,  
	--	'' AS ReferenceRemark,  
	--	'2001-01-30' AS PayDate ,  
	--	0 AS CastCategoryId,  
	--	'' AS CastCategoryName,  
	--	0 AS CastCategoryOrderIndex,
	--	'' AS ReportTemplate,
	--	0 AS CollectionGroupId,
	--	'' AS CollectionGroup,
	--	'' AS BatchName,
	--	'' AS FatherName,
	--	 '' AS FatherContactNo,
	--	 '' AS MotherName,
	--	 '' AS MotherContactNo,
	--	0 AS FeeOrderIndex,
	--	'' AS Address,
	--	'' AS StudentContactNo,
	--    '' as StudentName,
	--	0 As GenderId,
	-- 0 AS CollectionGroupOrderIndex,
	-- 0 AS SUId


END
GO
PRINT N'Altering [sFee].[pRptFeePendingDetailWithScholarshipListGet]...';


GO
ALTER PROCEDURE [sFee].[pRptFeePendingDetailWithScholarshipListGet]
		@rReportId int,
		@rReceiptBookId int,
		@rAdmissionCategoryId int,
		@rClassId int,
		@rDivisionId int,
		@rUptoDate date,
		@rBatchId int,
		@rUserId bigint,
		@rBuilder1 nvarchar(max),
		@rBuilder2 nvarchar(max),
		@rOrgId int,
		@rOrgGroupBatchId int,
		@rStatusId int,
		@rCommonBatch nvarchar(100),
		@rDepartmentId int,
		@rFromRollNo int,
	    @rToRollNo int,
	    @rCode nvarchar(20),
	    @rIsFilter bit,
		@rIsHeader bit,
		@rCreatedUserName nvarchar(100)='',
		@rFeeHeadId nvarchar(max) = '',
		@rIsDisplayOrgGroup bit=0,
		@rFeeId nvarchar(max) = '',
		@rFilterId  int=0,
		@rOrgIds nvarchar(max) = '',
		@rClassStatusId int=0,
		@rClassIds nvarchar(max) = '',
		@rDivisionIds nvarchar(max) = ''  
	    
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
BEGIN 	

	DECLARE @p as TempPendingFee
	
	INSERT INTO  @p 
	 
	SELECT 
		SA.AcademicId,
		SA.RollNo,
		SA.Name,
		SA.Code,
		SA.ClassId,
		SA.DivisionId,
		SA.ClassName,
		SA.DivisionName,
		SA.ClassName+' - '+SA.DivisionName AS ClassDivision,
		0 AS FeeSetupId,		
		0 AS IsVariable,
		0 AS Amount,
		'1900-01-01' AS StartDate,
		'1900-01-01' AS EndDate,
	    0.00 AS FAAmount,
		0.00 AS DiscountAmount,
		0.00 AS AdditionalAmount,
		0 AS PaidAmount,
		SUM(ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00)) AS PendingAmount,
		'' AS Remark,
		0 ReceiptBookId,
		'' AS FeeName,
		'' AS FeeCode,
		SA.OrgId,
		O.Title AS OrgName,
		O.OrderIndex AS OrgOrderIndex,
		'' AS ReceiptBookTitle,
		0 AS ReceiptOrderIndex,
		0 AS BatchId,
		'' AS BatchName,
		'',
		'',
		'',
		ISNULL(SA.SUID,'') AS SUID,
		SA.ClassOrderIndex,
		SA.DivisionOrder,
		FS.FeeOrderIndex
  FROM 
  
			 sStudent.vStudentAcademic SA
		INNER JOIN 
		(
			SELECT 
				FS1.FeeId,
				FS1.Id,
				ISNULL(FS1.IsOptional,0)AS IsOptional,
				ISNULL(FS1.IsVariable,0)AS IsVariable,
				ISNULL(FS1.Amount,0)AS Amount,
				ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
				ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
				FS1.BatchId,
				ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
				SA1.AcademicId,
				FM.Title AS FeeName,
				FM.Code AS FeeCode,
				FM.OrderIndex AS FeeOrderIndex
			FROM sFee.tFeeSetup FS1
			INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId 
				AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				AND ((SA1.ClassId=@rClassId) OR (@rClassId=0))  AND ((SA1.DivisionId=@rDivisionId) OR (@rDivisionId=0))
				AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				AND (ISNULL(SA1.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='')
				AND (ISNULL(SA1.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='')
			INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
			WHERE 
			     (SA1.OrgGroupBatchId = @rOrgGroupBatchId)
				AND	((FS1.ClassId=@rClassId) OR (@rClassId=0))
				AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
				AND (FS1.IsOptional=0)
				AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
				AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=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(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')  
				AND (ISNULL(FS1.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='')
				AND (ISNULL(SA1.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='') 
				UNION ALL
				
			SELECT 
				FS1.FeeId,
				FS1.Id,
				ISNULL(FS1.IsOptional,0)AS IsOptional,
				ISNULL(FS1.IsVariable,0)AS IsVariable,
				ISNULL(FS1.Amount,0)AS Amount,
				ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
				ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
				FS1.BatchId,
				ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
				SA1.AcademicId,
				FM.Title AS FeeName,
				FM.Code AS FeeCode,
				FM.OrderIndex AS FeeOrderIndex
			FROM sFee.tFeeSetup FS1
		INNER JOIN sFee.tFeeOptional FO
			ON FO.FeeSetupId=FS1.Id
	    INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
		INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=FO.SourceId
			AND SA1.BatchId = FS1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId AND SA1.ClassId = FS1.ClassId 
			AND ((SA1.ClassId=@rClassId) OR (@rClassId=0))   AND ((SA1.DivisionId=@rDivisionId) OR (@rDivisionId=0))
			AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
			AND (ISNULL(SA1.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='')
			AND (ISNULL(SA1.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='')
		WHERE
		       (SA1.OrgGroupBatchId = @rOrgGroupBatchId)
				AND ((FS1.ClassId=@rClassId) OR (@rClassId=0))
				AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
				AND (FS1.IsOptional=1)
				AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
				AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=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(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')
				AND (ISNULL(FS1.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='')
				AND (ISNULL(SA1.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='')  
				
		) FS ON FS.AcademicId=SA.AcademicId
		LEFT JOIN sFee.tFeeAllocation FA
			ON FA.FeeSetupId=FS.Id AND FA.SourceId=SA.AcademicId
		LEFT JOIN
		(
		    SELECT 
					ISNULL(SUM(RD.Amount),0) AS PaidAmount,RD.FeeSetupId ,R.SourceId
		    FROM
				sFee.tReceipt R 
				INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id 
				INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id
				INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id
				INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=R.SourceId				
				AND (SA1.ClassId=@rClassId OR @rClassId=0) 
				AND (SA1.DivisionId=@rDivisionId OR @rDivisionId=0)
				AND (ISNULL(SA1.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='')
				AND (ISNULL(SA1.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='')
				
			WHERE		
				(R.SourceTypeId = 2001)
				AND ((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND (R.IsObsolete = 0) 
				AND ((SA1.OrgGroupBatchId = @rOrgGroupBatchId)  )
				AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((R.CreatedUserId=@rUserId) OR (@rUserId=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 (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='') 
				GROUP BY FeeSetupId,R.SourceId
				
				
		
		) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
		 INNER JOIN sSetup.tOrganizationMaster O ON
		 SA.OrgId = O.Id
		 INNER JOIN sFee.tReceiptBookMaster RBM 
			ON FS.ReceiptBookId=RBM.Id
	    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)) 
       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 = SA.StudentId AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) 
		
	WHERE	
			(SA.OrgGroupBatchId = @rOrgGroupBatchId)
			AND ((SA.BatchId=@rBatchId) OR (@rBatchId=0)) 
			AND (SA.StatusId = @rStatusId OR @rStatusId=0)
			AND ((FS.StartDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
			AND ((SA.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
			AND ((SA.RollNo <= @rToRollNo) OR (@rToRollNo=0))
			AND ((SA.Code=@rCode) OR (@rCode=''))
			AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=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)))
			     )
            AND (ISNULL(SA.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')
			AND ((SA.ClassStatusId=@rClassStatusId) OR (@rClassStatusId=0))		     
			GROUP BY 
			SA.AcademicId,
			SA.RollNo,
			SA.Name,
			SA.Code,
			SA.ClassId,
			SA.DivisionId,
			SA.ClassName,
			SA.DivisionName,
			SA.ClassName,
			SA.DivisionName,
			OrgId,
			O.Title,
			O.OrderIndex,
			BatchName,
			SA.SUID,
			SA.ClassOrderIndex,
			SA.DivisionOrder,
			FeeOrderIndex
				
			Order by SA.RollNo

			SELECT
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			@rIsFilter AS IsFilter, 
			@rIsDisplayOrgGroup AS IsDisplayOrgGroup,
			OrgId,			 
			p.AcademicId,
			DivisionId,
			ClassDivision,
			RollNo, 
			Name,
			Code,
			OrgName,
			ISNULL(SUM(PendingAmount),0) AS PendingAmount, 
			ISNULL(SUM(SS.ScholarshipPaid),0) AS ScholarshipPaid,
			ISNULL(SUM(SSE.EligibleAmount),0) AS EligibleAmount,
			ISNULL(SS.ReferenceRemark,'')   AS ReferenceRemark,
			SUID,
			ClassOrderIndex,
			DivisionOrderIndex
			--,
			--CASE ISNULL(SS.AcademicId,0) WHEN 0 THEN 0 ELSE 1 END AS IsScholarshipEligible		
			FROM @p p 
			
		LEFT JOIN				
		(SELECT  SE.AcademicId,Sum(PaidAmount) AS ScholarshipPaid,SO.ReferenceRemark FROM 
		sScholarship.tScholarshipEligibleStudent SE
		INNER JOIN sStudent.vStudentAcademic SA1  ON SE.AcademicId = SA1.AcademicId 
		INNER JOIN sScholarship.tScholarshipReceive RE ON SE.ScholarshipId = RE.ScholarshipId 
		INNER JOIN sScholarship.tScholarshipStudentPaid SP on SE.AcademicId = SP.AcademicId	AND SP.ScholarshipReceiveId = RE.Id	
		INNER JOIN sStudent.tStudentOther SO ON SA1.StudentId = SO.StudentId
		WHERE
		    (SA1.OrgGroupBatchId = @rOrgGroupBatchId)
		 	AND ((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
		 	AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
		 	AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
		 	AND ((SA1.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = @rOrgGroupBatchId))
		 	AND ((SA1.ClassId=@rClassId) OR (@rClassId=0))
		 	 AND ((SA1.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		 	 AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')  
			 AND ((SA1.ClassStatusId=@rClassStatusId) OR (@rClassStatusId=0))
			 AND (ISNULL(SA1.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='')
			 AND (ISNULL(SA1.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='') 	
		 	GROUP BY SE.AcademicId,ReferenceRemark
		 ) SS ON p.AcademicId=SS.AcademicId
		LEFT JOIN				
		(SELECT  SE.AcademicId,SUM(SE.EligibleAmount) AS EligibleAmount FROM 
		sScholarship.tScholarshipEligibleStudent SE
		INNER JOIN sStudent.vStudentAcademic SA1  ON SE.AcademicId = SA1.AcademicId		 
		WHERE
		    (SA1.OrgGroupBatchId = @rOrgGroupBatchId)
		 	AND ((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
		 	AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
		 	AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
		 	AND ((SA1.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = @rOrgGroupBatchId))
		 	AND ((SA1.ClassId=@rClassId) OR (@rClassId=0))
		 	 AND ((SA1.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		 	 AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')
			 AND ((SA1.ClassStatusId=@rClassStatusId) OR (@rClassStatusId=0))
			 AND (ISNULL(SA1.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='')
			 AND (ISNULL(SA1.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='') 	  
		 	GROUP BY SE.AcademicId 
		 ) SSE ON p.AcademicId=SSE.AcademicId		 
		 
			GROUP By 
			OrgId,			
			p.AcademicId,
			--SS.AcademicId,
			DivisionId,
			ClassDivision,
			RollNo, 
			Name,
			Code,
			OrgName,
			ReferenceRemark,
			SUID,
			ClassOrderIndex,
			DivisionOrderIndex
			ORDER BY AcademicId
END
GO
PRINT N'Altering [sFee].[pRptFeePendingWithFeeNameGet]...';


GO

 
ALTER PROCEDURE [sFee].[pRptFeePendingWithFeeNameGet]
		@rReportId int=0,
		@rReceiptBookId int,
		@rAdmissionCategoryId int,
		@rClassId int,
		@rDivisionId int,
		@rUptoDate date,
		@rBatchId int,
		@rUserId bigint,
		@rBuilder1 nvarchar(max),
		@rBuilder2 nvarchar(max),
		@rIsDetail bit,
		@rOrgId int,
		@rOrgGroupBatchId int,
		@rStatusId int,
		@rCommonBatch nvarchar(100),
		@rDepartmentId int=0,
		@rFromRollNo int=0,
	    @rToRollNo int=0,
	    @rCode nvarchar(20)='',
	    @rIsFilter bit=0,
		@rIsHeader bit=0,		
		@rCreatedUserName nvarchar(20) = '',
		@rIsReceiptBookGroup bit=0	,
		@rFeeHeadId nvarchar(max) = '',
		@rIsDisplayOrgGroup bit=0,
		@rFeeId nvarchar(max) = '',
		@rFilterId int=0,
		@rOrgIds nvarchar(max) = '' ,
		@rReportType int=1,
		@rClassStatusId int=0,
		@rClassIds nvarchar(max) = '',
		@rDivisionIds nvarchar(max) = '',
		@rFromAmount decimal = 0.00,
		@rToAmount decimal = 0.00
	    
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
BEGIN 	

	IF(@rReportType=1)

		BEGIN

--CREATE TABLE #TempStudent
--	(
--	AcademicId bigint,
--	ClassId int,
--	BatchId int,
--	a
--	)
--	SELECT AcademicId

 
	--CREATE TYPE  TempPendingFee AS TABLE
	--(
	--AcademicId bigint
	--,
	--RollNo int,
	--Name nvarchar(200),
	--Code nvarchar(20),
	--ClassId int,
	--DivisionId int,
	--ClassName nvarchar(100),
	--DivisionName nvarchar(100),
	--ClassDivision nvarchar(100),
	--FeeSetupId int,
	--IsVariable int,
	--Amount Decimal(12,2),
	--StartDate date,
	--EndDate date,
	--FAAmount Decimal(12,2),
	--DiscountAmount Decimal(12,2),
	--AdditionalAmount Decimal(12,2),
	--PaidAmount Decimal(12,2),
	--PendingAmount Decimal(12,2),
	--Remark nvarchar(200),
	--ReceiptBookId int,
	--FeeName nvarchar(100),
	--FeeCode nvarchar(100),
	--OrgId int,
	--OrgName nvarchar(200),
	--OrgOrderIndex int,
	--ReceiptBookTitle nvarchar(200),
	--ReceiptOrderIndex int	
	--)
	
	DECLARE @p as TempPendingFee
	INSERT INTO  @p 
	 
	SELECT 
		--@rBuilder1 AS Builder1,
		--@rBuilder2 AS Builder2,
		--@rIsDetail AS IsDetail,
		--@rIsFilter As IsFilter,
		--@rIsHeader As IsHeader,
		SA.AcademicId		,
		SA.RollNo,
		SA.Name,
		SA.Code,
		SA.ClassId,
		SA.DivisionId,
		SA.ClassName,
		SA.DivisionName,
		SA.ClassName+' - '+SA.DivisionName AS ClassDivision,
		FS.Id AS FeeSetupId,		
		ISNULL(FS.IsVariable,0)AS IsVariable,
		ISNULL(FS.Amount,0)AS Amount,
		ISNULL(FS.StartDate,'1900-01-01')AS StartDate,
		ISNULL(FS.EndDate,'1900-01-01')AS EndDate,
		ISNULL(FA.VariableAmount,0.00)AS FAAmount,
		ISNULL(FA.DiscountAmount,0.00)AS DiscountAmount,
		ISNULL(FA.AdditionalAmount,0.00)AS AdditionalAmount,
		ISNULL(R.PaidAmount,0) AS PaidAmount,
		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 PendingAmount,
		ISNULL(FA.Remark,'') AS Remark,
		FS.ReceiptBookId,
		FS.FeeName,
		FS.FeeCode,
		SA.OrgId,
		O.Title AS OrgName,
		O.OrderIndex AS OrgOrderIndex,
		ISNULL(RBM.Title,'') AS ReceiptBookTitle,
		ISNULL(RBM.OrderIndex,0) AS ReceiptOrderIndex,
		0 AS BatchId,
		'' AS BatchName,
		ISNULL(SC.ParentContactNo,'') AS ParentContactNo,
		ISNULL(SC.StudentContactNo,'') AS StudentContactNo,
		'',
		ISNULL(SA.SUID,'') AS SUID,
		SA.ClassOrderIndex,
		SA.DivisionOrder,
		FS.FeeOrderIndex
			
  FROM 
  
			 sStudent.vStudentAcademic SA
		INNER JOIN 
		(
			SELECT 
				FS1.FeeId,
				FS1.Id,
				ISNULL(FS1.IsOptional,0)AS IsOptional,
				ISNULL(FS1.IsVariable,0)AS IsVariable,
				ISNULL(FS1.Amount,0)AS Amount,
				ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
				ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
				FS1.BatchId,
				ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
				SA1.AcademicId,
				FM.Title AS FeeName,
				FM.Code AS FeeCode,
				FM.OrderIndex AS FeeOrderIndex
			FROM sFee.tFeeSetup FS1
			INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId 
				AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				AND ((SA1.ClassId=@rClassId) OR (@rClassId=0)) 
				AND (ISNULL(SA1.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='')
				AND ((SA1.DivisionId=@rDivisionId) OR (@rDivisionId=0))
				AND (ISNULL(SA1.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='')
				AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
			INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
			WHERE 
			     (SA1.OrgGroupBatchId = @rOrgGroupBatchId)
				AND	((FS1.ClassId=@rClassId) OR (@rClassId=0))
				AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
				AND (FS1.IsOptional=0)
				AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
				AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=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(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')
				AND (ISNULL(FS1.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='')
				AND (ISNULL(SA1.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='')
				UNION ALL
				
			SELECT 
				FS1.FeeId,
				FS1.Id,
				ISNULL(FS1.IsOptional,0)AS IsOptional,
				ISNULL(FS1.IsVariable,0)AS IsVariable,
				ISNULL(FS1.Amount,0)AS Amount,
				ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
				ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
				FS1.BatchId,
				ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
				SA1.AcademicId,
				FM.Title AS FeeName,
				FM.Code AS FeeCode,
				FM.OrderIndex AS FeeOrderIndex
			FROM sFee.tFeeSetup FS1
		INNER JOIN sFee.tFeeOptional FO
			ON FO.FeeSetupId=FS1.Id
	    INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
		INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=FO.SourceId 
			AND SA1.BatchId = FS1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId AND SA1.ClassId = FS1.ClassId 
			AND ((SA1.ClassId=@rClassId) OR (@rClassId=0)) AND ((SA1.DivisionId=@rDivisionId) OR (@rDivisionId=0)) 
			AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
			AND (ISNULL(SA1.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='')
			AND (ISNULL(SA1.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='')
		WHERE
		       (SA1.OrgGroupBatchId = @rOrgGroupBatchId)
				AND ((FS1.ClassId=@rClassId) OR (@rClassId=0))
				AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
				AND (FS1.IsOptional=1)
				AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
				AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=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(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')
				AND (ISNULL(FS1.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='')
				AND (ISNULL(SA1.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='')
		) FS ON FS.AcademicId=SA.AcademicId
		LEFT JOIN sFee.tFeeAllocation FA
			ON FA.FeeSetupId=FS.Id AND FA.SourceId=SA.AcademicId
		LEFT JOIN
		(
		    SELECT 
					ISNULL(SUM(RD.Amount),0) AS PaidAmount,RD.FeeSetupId ,R.SourceId
		    FROM
				sFee.tReceipt R 
				INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id 
				INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id
				INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id
				INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=R.SourceId				
				AND (SA1.ClassId=@rClassId OR @rClassId=0) 
				AND (ISNULL(SA1.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='')
				AND ((SA1.DivisionId=@rDivisionId) OR (@rDivisionId=0))  
				AND (SA1.DivisionId=@rDivisionId OR @rDivisionId=0)
				AND (ISNULL(SA1.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='')
			WHERE		
				(R.SourceTypeId = 2001)
				AND ((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND (R.IsObsolete = 0) 
				AND ((SA1.OrgGroupBatchId = @rOrgGroupBatchId)  )
				AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((R.CreatedUserId=@rUserId) OR (@rUserId=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 (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')
				GROUP BY FeeSetupId,R.SourceId) R ON R.FeeSetupId = FS.Id 
				AND SA.AcademicId = R.SourceId
		       INNER JOIN sSetup.tOrganizationMaster O ON SA.OrgId = O.Id
		       INNER JOIN sFee.tReceiptBookMaster RBM 
			ON FS.ReceiptBookId=RBM.Id
			LEFT JOIN sStudent.tStudentCommunication SC 
			ON SC.StudentId = SA.StudentId
		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)) 
         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 = SA.StudentId AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) 
		
	WHERE	
			(SA.OrgGroupBatchId = @rOrgGroupBatchId)
			AND ((SA.BatchId=@rBatchId) OR (@rBatchId=0)) 
			AND (SA.StatusId = @rStatusId OR @rStatusId=0)
			AND ((FS.StartDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
			AND ((SA.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
			AND ((SA.RollNo <= @rToRollNo) OR (@rToRollNo=0))
			AND ((SA.Code=@rCode) OR (@rCode=''))
			AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=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)))
			     )
			AND (ISNULL(SA.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')  
			AND ((SA.ClassStatusId=@rClassStatusId) OR (@rClassStatusId=0))  
			Order by SA.RollNo

	SELECT
			@rBuilder1 as Builder1,
			@rIsDisplayOrgGroup AS IsDisplayOrgGroup,
			(CASE WHEN @rIsReceiptBookGroup = 0 THEN 0
			 WHEN @rIsReceiptBookGroup = 1 THEN	ReceiptBookId
			 END) AS ReceiptBookId,	
			(CASE WHEN @rIsReceiptBookGroup = 0 THEN 'ALL'
			 WHEN @rIsReceiptBookGroup = 1 THEN	ReceiptBookTitle
			 END) AS ReceiptBookTitle,
			(CASE WHEN @rIsReceiptBookGroup = 0 THEN 0
			 WHEN @rIsReceiptBookGroup = 1 THEN	ReceiptOrderIndex
			 END) AS ReceiptOrderIndex,	 
			
			OrgId,			 
			--ReceiptBookId,
			AcademicId,
			DivisionId,
			ClassDivision,RollNo, Name,Code,
			--ReceiptBookTitle,
			OrgName,
			SUM(PendingAmount) AS PendingAmount, 
			[sFee].[fPendingFeeNamesGet](AcademicId,ReceiptBookId,	@p) AS PendingFeeName,
			Pickup AS ParentContactNo,
			DRoppoint AS StudentContactNo,
			SUID,
			ClassOrderIndex,
			DivisionOrderIndex,
			FeeOrderIndex
			--ReceiptOrderIndex
			FROM @p 
			GROUP By ReceiptBookId,OrgId,AcademicId,DivisionId,
			ClassDivision,RollNo, Name,Code,
			ReceiptBookTitle,OrgName,ReceiptOrderIndex,Pickup,DRoppoint,SUID,ClassOrderIndex,
			DivisionOrderIndex,
			FeeOrderIndex
			HAVING
			((SUM(PendingAmount) >= @rFromAmount) OR (@rFromAmount=0.00))
			AND (( SUM(PendingAmount)<= @rToAmount) OR (@rToAmount=0.00))
			ORDER BY AcademicId

END

	ELSE
		BEGIN

	INSERT INTO  @p
SELECT 

		SA.AcademicId,
		SA.RollNo,
		SA.Name,
		SA.Code,
		SA.ClassId,
		SA.DivisionId,
		SA.ClassName,
		SA.DivisionName,
		SA.ClassName+' - '+SA.DivisionName AS ClassDivision,
		FS.Id AS FeeSetupId,		
		ISNULL(FS.IsVariable,0)AS IsVariable,
		ISNULL(FS.Amount,0)AS Amount,
		ISNULL(FS.StartDate,'1900-01-01')AS StartDate,
		ISNULL(FS.EndDate,'1900-01-01')AS EndDate,
		ISNULL(FAS.VariableAmount,0.00)AS FAAmount,
		ISNULL(FAS.DiscountAmount,0.00)AS DiscountAmount,
		ISNULL(FAS.AdditionalAmount,0.00)AS AdditionalAmount,
		ISNULL(FAS.PaidAmount,0) AS PaidAmount,
		ISNULL(FAS.ToPayAmount,0) AS PendingAmount,
		--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 PendingAmount,
		ISNULL(FAS.Remark,'') AS Remark,
		FS.ReceiptBookId,
		--FS.FeeName,
		--FS.FeeCode,
		FM.Title AS FeeName, 
		FM.Code AS FeeCode,
		SA.OrgId,
		O.Title AS OrgName,
		O.OrderIndex AS OrgOrderIndex,
		ISNULL(RBM.Title,'') AS ReceiptBookTitle,
		ISNULL(RBM.OrderIndex,0) AS ReceiptOrderIndex,
		0 AS BatchId,
		'' AS BatchName,
		ISNULL(SC.ParentContactNo,'') AS ParentContactNo,
		ISNULL(SC.StudentContactNo,'') AS StudentContactNo,
		'',
		ISNULL(SA.SUID,'') AS SUID,
		SA.ClassOrderIndex,
		SA.DivisionOrder,
		FM.OrderIndex AS FeeOrderIndex
  FROM  sStudent.vStudentAcademic SA
		INNER JOIN sFee.tFeeAllocationStudent FAS ON FAS.AcademicId = SA.AcademicId
		INNER JOIN sFee.tFeeSetup FS ON FS.ID=FAS.FeeSetupId	
		INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS.FeeId
		INNER JOIN sSetup.tOrganizationMaster O ON SA.OrgId = O.Id
		INNER JOIN sFee.tReceiptBookMaster RBM ON FS.ReceiptBookId=RBM.Id		
		INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FM.FeeHeadId
		--LEFT JOIN sFee.tFeeAllocation FA ON FA.FeeSetupId=SF.FeeSetupId AND FA.SourceId=SA.AcademicId
		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)) 
        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 = SA.StudentId AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))
		LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId = SA.StudentId 
		
	WHERE	
			(SA.OrgGroupBatchId = @rOrgGroupBatchId)
			AND ((SA.BatchId=@rBatchId) OR (@rBatchId=0)) 
			AND (SA.StatusId = @rStatusId OR @rStatusId=0)
			AND ((FS.StartDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
			AND ((SA.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
			AND ((SA.RollNo <= @rToRollNo) OR (@rToRollNo=0))
			AND ((SA.Code=@rCode) OR (@rCode=''))
			AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=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(FAS.ToPayAmount,0) !=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(SA.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')
			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 ((SA.ClassStatusId=@rClassStatusId) OR (@rClassStatusId=0))
			Order by   SA.RollNo
			--FM.OrderIndex 
			

	SELECT
			@rBuilder1 as Builder1,
			@rIsDisplayOrgGroup AS IsDisplayOrgGroup,
			(CASE WHEN @rIsReceiptBookGroup = 0 THEN 0
			 WHEN @rIsReceiptBookGroup = 1 THEN	ReceiptBookId
			 END) AS ReceiptBookId,	
			(CASE WHEN @rIsReceiptBookGroup = 0 THEN 'ALL'
			 WHEN @rIsReceiptBookGroup = 1 THEN	ReceiptBookTitle
			 END) AS ReceiptBookTitle,
			(CASE WHEN @rIsReceiptBookGroup = 0 THEN 0
			 WHEN @rIsReceiptBookGroup = 1 THEN	ReceiptOrderIndex
			 END) AS ReceiptOrderIndex,	 
			
			OrgId,			 
			--ReceiptBookId,
			AcademicId,
			DivisionId,
			ClassDivision,RollNo, Name,Code,
			--ReceiptBookTitle,
			OrgName,
			SUM(PendingAmount) AS PendingAmount, 
			[sFee].[fPendingFeeNamesGet](AcademicId,ReceiptBookId,	@p) AS PendingFeeName,
			Pickup AS ParentContactNo,
			DRoppoint AS StudentContactNo,
			SUID,
			ClassOrderIndex,
			DivisionOrderIndex,
			--ReceiptOrderIndex,
			FeeOrderIndex
			FROM @p 
			GROUP By ReceiptBookId,OrgId,AcademicId,DivisionId,
			ClassDivision,RollNo, Name,Code,
			ReceiptBookTitle,OrgName,ReceiptOrderIndex,Pickup,DRoppoint,SUID,ClassOrderIndex,
			DivisionOrderIndex,FeeOrderIndex
			HAVING
			((SUM(PendingAmount) >= @rFromAmount) OR (@rFromAmount=0.00))
			AND (( SUM(PendingAmount)<= @rToAmount) OR (@rToAmount=0.00))
			ORDER BY AcademicId

END 
END
GO
PRINT N'Altering [sFee].[pRptFeeReceiptListGet]...';


GO

ALTER PROCEDURE [sFee].[pRptFeeReceiptListGet]  
  @rReportId int=0,  
  @rReceiptBookId int=0,  
  @rAdmissionCategoryId int=0,  
  @rClassId int=0,  
  @rDivisionId int=0,  
  @rFromDate date='',  
  @rToDate date='',  
  @rFromReceiptNo int=0,  
  @rToReceiptNo int=0,  
  @rBatchId int,  
  @rUserId bigint=0,  
  @rBuilder1 nvarchar(max)=0,  
  @rBuilder2 nvarchar(max)=0,  
  @rIsDetail bit=0,  
  @rIsCancel bit=0,  
  @rOrgId int,  
  @rOrgGroupBatchId int,  
  @rStatusId int=0,  
  @rPaytypeId int=0,  
  @rCommonBatch nvarchar(100)='',  
  @rDepartmentId int=0,  
  @rFromRollNo int=0,  
     @rToRollNo int=0,  
     @rCode nvarchar(20),  
     @rIsFilter bit=0,  
     @rIsHeader bit=0,  
     @rCreatedUserName nvarchar(100)='',  
     @rFeeHeadId nvarchar(max) = '',  
     @rIsDisplayOrgGroup bit=0,  
     @rIsDiscount bit = 0,  
     @rFeeId nvarchar(max) = '',  
     @rFilterId int=0,  
     @rCustomGroupId smallint = 0,  
     @rOrgGroupId int=0,  
     @rFeeStatusId int=0,  
     @rFromChequeDate date='',      
  @rToChequeDate date='',      
     @rBankName nvarchar(100)='',  
     @rOrgIds nvarchar(max) = '',  
     @rBankNames nvarchar(max) = '',  
  
  @rFromChequeClearDate Date = '',  
  @rToChequeClearDate Date = '' ,
  @rClassStatusId int=0 ,
  @rPayTypeIds nvarchar(max) = '',
  @rUserAcessUserId bigint = 0,
  @rReceiptBookIds nvarchar(max) = ''
 WITH EXECUTE AS CALLER  
AS  
SET NOCOUNT ON  
      
BEGIN   
   
  BEGIN      
  SET @rBankName = sCommon.fSearchStringGet(@rBankName)      
    END   
	--OR @rReportId=20547
  IF(@rReportId=10138 OR @rReportId=20456)
	BEGIN
		SELECT   
		  @rBuilder1 AS Builder1,  
		  @rBuilder2 AS Builder2,  
		  @rIsDetail AS IsDetail,  
		  (CASE WHEN @rReportId IN (20456,30804) THEN  R.IsObsolete ELSE @rIsCancel END) AS IsCancel,  
		  --@rIsCancel AS IsCancel,  
		  @rIsFilter As IsFilter,  
		  @rIsHeader As IsHeader,  
		  @rIsDisplayOrgGroup AS IsDisplayOrgGroup,  
		  R.Id AS ReceiptId,  
		  R.ReceiptNumber,  
		  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,  
		  --ISNULL(R.ChequeNo,'') AS ChequeNo,  
		  CASE WHEN ISNULL(R.ChequeNo,'') != '' THEN R.ChequeNo ELSE CONVERT(nvarchar(20),R.PaymentTransactionId) END AS ChequeNo,
		  ISNULL(R.BankName,'') AS BankName,  
		  R.ReceiptAmount,  
		  --R.ReceiptDate,  
		  CASE  WHEN @rReportId = 30611 AND R.ChequeClearDate IS NOT NULL THEN R.ChequeClearDate ELSE R.ReceiptDate END AS ReceiptDate,  
		  R.CreatedUserId,  
		  ISNULL(U.LoginTitle,'') AS UserName,  
		  ISNULL(RBM.Title,'') AS ReceiptBookTitle,  
		  ISNULL(RBM.BankName,'') AS ReceiptBookBank,  
		  ISNULL(RBM.BankAccountNumber,'') AS BankAccountNumber,  
		  ISNULL(R.ReceiptBookId,'0') As ReceiptBookId,  
		  ISNULL((CASE @rReportId WHEN 20461 THEN [sFee].[fReceiptFeeDetailGet](R.Id)  
		   ELSE '' END),'') AS FeeDetail,  
		   R.Remark,  
		   R.DiscountAmount,  
		   ISNULL(RBM.OrderIndex,0) AS ReceiptBookOrderIndex,  
		   SA.OrgId,  
		   SA.OrganizationName,  
		   ISNULL(R.AmountAfterDiscount,0) AS AmountAfterDiscount,  
		   ISNULL(R.CGSTPercentage,0) AS CGSTPercentage,  
		   ISNULL(R.SGSTPercentage,0) AS SGSTPercentage,  
		   ISNULL(R.CGSTAmount,0) AS CGSTAmount,  
		   ISNULL(R.SGSTAmount,0) AS SGSTAmount,  
		   @rCustomGroupId AS CustomGroupId,  
		   SA.OrgGroupBatchId AS BatchId,  
		   SA.BatchName,  
		   R.ChequeDate,  
		   R.ChequeClearDate ,
		   SA.GenderId
		  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 SA  
		   ON SA.AcademicId=R.SourceId AND ((SA.OrgId=@rOrgId) OR (@rOrgId=0)) 

		  --According UserAccess
		  INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id =SA.OrgId
		  INNER JOIN sSecurity.tUserOrganization UO ON UO.OrgId=SA.OrgId AND OM.IsObsolete=0 AND UO.UserId=@rUserAcessUserId  

		  INNER JOIN sFinanceCommon.tPayTypeMaster PTM  
		   ON PTM.Id=R.PayTypeId  
		  INNER JOIN sFee.tReceiptBookMaster RBM   
		   ON RBM.Id=R.ReceiptBookId  
		  
		  --According UserAccess
		  INNER JOIN sSecurity.tUserAccess UA ON UA.SourceId=RBM.Id AND UA.SourceTypeId=2013 AND RBM.IsObsolete=0 AND UA.UserId =@rUserAcessUserId 


		  LEFT JOIN sSecurity.tUser U  
		   ON U.Id=R.CreatedUserId  
		 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   
			AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))    
			AND (SA.OrgGroupBatchId = RT.OrgGroupBatchId)  
		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.ReceiptNumber >= @rFromReceiptNo) OR (@rFromReceiptNo = 0))  
		 AND ((R.ReceiptNumber <= @rToReceiptNo) OR (@rToReceiptNo = 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 ((R.CreatedUserId=@rUserId) OR (@rUserId=0))  
		 AND ((R.IsObsolete =@rIsCancel  AND (@rReportId != 20456 OR @rReportId != 30804))  OR   
		  ((@rReportId = 20456 OR @rReportId = 30804) AND ((@rFeeStatusId = 0) -- All  
		  OR (@rFeeStatusId = 1 AND R.IsObsolete = 0) -- Valid  
		  OR (@rFeeStatusId = 2 AND R.IsObsolete = 1) -- Cancel  
		  )))  
		 AND (SA.StatusId=@rStatusId OR @rStatusId=0)  
		 AND (SA.ClassStatusId=@rClassStatusId OR @rClassStatusId=0)  
		 AND (R.PayTypeId = @rPaytypeId OR @rPaytypeId=0)  
		 AND ((SA.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))  
		 AND ((SA.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))  
		 AND ((SA.RollNo <= @rToRollNo) OR (@rToRollNo=0))  
		 AND ((SA.Code=@rCode) OR (@rCode=''))  
		 AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))  
		 AND ((ISNULL(U.LoginTitle,'') like @rCreatedUserName) OR (ISNULL(@rCreatedUserName,'')=''))  
		 AND ((@rIsDiscount =1 AND R.DiscountAmount!=0) OR (@rIsDiscount=0))  
		 --AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')  
		  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 ((RBM.OrgGroupId=@rOrgGroupId) OR (@rOrgGroupId=0))  
		 AND ((UPPER(R.BankName) like UPPER(@rBankName)) OR(ISNULL(@rBankName,'')=''))  
		 AND (ISNULL(SA.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')    
		 AND (ISNULL(R.BankName,'') IN( SELECT cast(item as nvarchar(100)) FROM  sCommon.fnsplit(@rBankNames,',')) OR @rBankNames='')   
		 AND ((R.ChequeClearDate>=@rFromChequeClearDate)OR(ISNULL(@rFromChequeClearDate,'')=''))      
		 AND ((R.ChequeClearDate<=@rToChequeClearDate)OR(ISNULL(@rToChequeClearDate,'')=''))
		 AND (ISNULL(R.PayTypeId,0) IN (SELECT cast(item as tinyint) FROM sCommon.fnsplit(@rPayTypeIds,',')) OR @rPayTypeIds='')
		 AND (ISNULL(R.ReceiptBookId,0) IN (SELECT cast(item as int) FROM sCommon.fnsplit(@rReceiptBookIds,',')) OR @rReceiptBookIds='')
  
		 ORDER BY R.ReceiptNumber
	END

	ELSE IF(@rReportId=30866)
	BEGIN
		SELECT   
		  @rBuilder1 AS Builder1,  
		  @rBuilder2 AS Builder2,  
		  @rIsDetail AS IsDetail,  
		  (CASE WHEN @rReportId IN (20456,30804) THEN  R.IsObsolete ELSE @rIsCancel END) AS IsCancel,  
		  --@rIsCancel AS IsCancel,  
		  @rIsFilter As IsFilter,  
		  @rIsHeader As IsHeader,  
		  @rIsDisplayOrgGroup AS IsDisplayOrgGroup,  
		  R.Id AS ReceiptId,  
		  R.ReceiptNumber,  
		  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,  
		  --ISNULL(R.ChequeNo,'') AS ChequeNo,  
		  CASE WHEN ISNULL(R.ChequeNo,'') != '' THEN R.ChequeNo ELSE CONVERT(nvarchar(20),R.PaymentTransactionId) END AS ChequeNo,
		  ISNULL(R.BankName,'') AS BankName,
		  --R.ReceiptAmount,  
		  RD.Amount AS ReceiptAmount,
		  --R.ReceiptDate,  
		  CASE  WHEN @rReportId = 30611 AND R.ChequeClearDate IS NOT NULL THEN R.ChequeClearDate ELSE R.ReceiptDate END AS ReceiptDate,  
		  R.CreatedUserId,  
		  ISNULL(U.LoginTitle,'') AS UserName,  
		  ISNULL(RBM.Title,'') AS ReceiptBookTitle,  
		  ISNULL(RBM.BankName,'') AS ReceiptBookBank,  
		  ISNULL(RBM.BankAccountNumber,'') AS BankAccountNumber,  
		  ISNULL(R.ReceiptBookId,'0') As ReceiptBookId,  
		  ISNULL((CASE @rReportId WHEN 20461 THEN [sFee].[fReceiptFeeDetailGet](R.Id)  
		   WHEN 30940 THEN [sFee].[fReceiptFeeDetailGet](R.Id) ELSE '' END),'') AS FeeDetail,  
		   R.Remark,  
		   R.DiscountAmount,  
		   ISNULL(RBM.OrderIndex,0) AS ReceiptBookOrderIndex,  
		   SA.OrgId,  
		   SA.OrganizationName,  
		   ISNULL(R.AmountAfterDiscount,0) AS AmountAfterDiscount,  
		   ISNULL(R.CGSTPercentage,0) AS CGSTPercentage,  
		   ISNULL(R.SGSTPercentage,0) AS SGSTPercentage,  
		   ISNULL(R.CGSTAmount,0) AS CGSTAmount,  
		   ISNULL(R.SGSTAmount,0) AS SGSTAmount,  
		   @rCustomGroupId AS CustomGroupId,  
		   SA.OrgGroupBatchId AS BatchId,  
		   SA.BatchName,  
		   R.ChequeDate,  
		   R.ChequeClearDate,
		   FM.Id AS FeeId,
		  FM.Code AS FeeCode,
		  FM.Title AS FeeTitle,
		   FM.OrderIndex AS FeeOrderIndex
		      
		  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 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 sSecurity.tUser U  
		   ON U.Id=R.CreatedUserId  
		 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   
			AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))    
			AND (SA.OrgGroupBatchId = RT.OrgGroupBatchId)  
		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.ReceiptNumber >= @rFromReceiptNo) OR (@rFromReceiptNo = 0))  
		 AND ((R.ReceiptNumber <= @rToReceiptNo) OR (@rToReceiptNo = 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 ((R.CreatedUserId=@rUserId) OR (@rUserId=0))  
		 AND ((R.IsObsolete =@rIsCancel  AND (@rReportId != 20456 OR @rReportId != 30804))  OR   
		  ((@rReportId = 20456 OR @rReportId = 30804) AND ((@rFeeStatusId = 0) -- All  
		  OR (@rFeeStatusId = 1 AND R.IsObsolete = 0) -- Valid  
		  OR (@rFeeStatusId = 2 AND R.IsObsolete = 1) -- Cancel  
		  )))  
		 AND (SA.StatusId=@rStatusId OR @rStatusId=0)  
		 AND (SA.ClassStatusId=@rClassStatusId OR @rClassStatusId=0)  
		 AND (R.PayTypeId = @rPaytypeId OR @rPaytypeId=0)  
		 AND ((SA.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))  
		 AND ((SA.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))  
		 AND ((SA.RollNo <= @rToRollNo) OR (@rToRollNo=0))  
		 AND ((SA.Code=@rCode) OR (@rCode=''))  
		 AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))  
		 AND ((ISNULL(U.LoginTitle,'') like @rCreatedUserName) OR (ISNULL(@rCreatedUserName,'')=''))  
		 AND ((@rIsDiscount =1 AND R.DiscountAmount!=0) OR (@rIsDiscount=0))  
		 --AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')  
		  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 ((RBM.OrgGroupId=@rOrgGroupId) OR (@rOrgGroupId=0))  
		 AND ((UPPER(R.BankName) like UPPER(@rBankName)) OR(ISNULL(@rBankName,'')=''))  
		 AND (ISNULL(SA.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')    
		 AND (ISNULL(R.BankName,'') IN( SELECT cast(item as nvarchar(100)) FROM  sCommon.fnsplit(@rBankNames,',')) OR @rBankNames='')   
		 AND ((R.ChequeClearDate>=@rFromChequeClearDate)OR(ISNULL(@rFromChequeClearDate,'')=''))      
		 AND ((R.ChequeClearDate<=@rToChequeClearDate)OR(ISNULL(@rToChequeClearDate,'')=''))
		 AND (ISNULL(R.PayTypeId,0) IN (SELECT cast(item as tinyint) FROM sCommon.fnsplit(@rPayTypeIds,',')) OR @rPayTypeIds='')  		 
  
		 ORDER BY R.ReceiptNumber  
	END

	ELSE IF(@rReportId=20547)
	BEGIN
		SELECT   
		  @rBuilder1 AS Builder1,  
		  @rBuilder2 AS Builder2,  
		  @rIsDetail AS IsDetail,  
		  (CASE WHEN @rReportId IN (20456,30804) THEN  R.IsObsolete ELSE @rIsCancel END) AS IsCancel,  
		  --@rIsCancel AS IsCancel,  
		  @rIsFilter As IsFilter,  
		  @rIsHeader As IsHeader,  
		  @rIsDisplayOrgGroup AS IsDisplayOrgGroup,  
		  R.Id AS ReceiptId,  
		  R.ReceiptNumber,  
		  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,  
		  --ISNULL(R.ChequeNo,'') AS ChequeNo,  
		  CASE WHEN ISNULL(R.ChequeNo,'') != '' THEN R.ChequeNo ELSE CONVERT(nvarchar(20),R.PaymentTransactionId) END AS ChequeNo,
		  ISNULL(R.BankName,'') AS BankName,  
		  RD.Amount AS ReceiptAmount,  
		  --R.ReceiptDate,  
		  CASE  WHEN @rReportId = 30611 AND R.ChequeClearDate IS NOT NULL THEN R.ChequeClearDate ELSE R.ReceiptDate END AS ReceiptDate,  
		  R.CreatedUserId,  
		  ISNULL(U.LoginTitle,'') AS UserName,  
		  ISNULL(RBM.Title,'') AS ReceiptBookTitle,  
		  ISNULL(RBM.BankName,'') AS ReceiptBookBank,  
		  ISNULL(RBM.BankAccountNumber,'') AS BankAccountNumber,  
		  ISNULL(R.ReceiptBookId,'0') As ReceiptBookId,  
		  ISNULL((CASE @rReportId WHEN 20461 THEN [sFee].[fReceiptFeeDetailGet](R.Id)  
		   ELSE '' END),'') AS FeeDetail,  
		   R.Remark,  
		   R.DiscountAmount,  
		   ISNULL(RBM.OrderIndex,0) AS ReceiptBookOrderIndex,  
		   SA.OrgId,  
		   SA.OrganizationName,  
		   ISNULL(R.AmountAfterDiscount,0) AS AmountAfterDiscount,  
		   ISNULL(R.CGSTPercentage,0) AS CGSTPercentage,  
		   ISNULL(R.SGSTPercentage,0) AS SGSTPercentage,  
		   ISNULL(R.CGSTAmount,0) AS CGSTAmount,  
		   ISNULL(R.SGSTAmount,0) AS SGSTAmount,  
		   @rCustomGroupId AS CustomGroupId,  
		   SA.OrgGroupBatchId AS BatchId,  
		   SA.BatchName,  
		   R.ChequeDate,  
		   R.ChequeClearDate ,
		   SA.GenderId
		  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 SA  
		   ON SA.AcademicId=R.SourceId AND ((SA.OrgId=@rOrgId) OR (@rOrgId=0)) 

		  --According UserAccess
		  INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id =SA.OrgId
		  INNER JOIN sSecurity.tUserOrganization UO ON UO.OrgId=SA.OrgId AND OM.IsObsolete=0 AND UO.UserId=@rUserAcessUserId  

		  INNER JOIN sFinanceCommon.tPayTypeMaster PTM  
		   ON PTM.Id=R.PayTypeId  
		  INNER JOIN sFee.tReceiptBookMaster RBM   
		   ON RBM.Id=R.ReceiptBookId  
		  
		  --According UserAccess
		  INNER JOIN sSecurity.tUserAccess UA ON UA.SourceId=RBM.Id AND UA.SourceTypeId=2013 AND RBM.IsObsolete=0 AND UA.UserId =@rUserAcessUserId 


		  LEFT JOIN sSecurity.tUser U  
		   ON U.Id=R.CreatedUserId  
		 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   
			AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))    
			AND (SA.OrgGroupBatchId = RT.OrgGroupBatchId)  
		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.ReceiptNumber >= @rFromReceiptNo) OR (@rFromReceiptNo = 0))  
		 AND ((R.ReceiptNumber <= @rToReceiptNo) OR (@rToReceiptNo = 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 ((R.CreatedUserId=@rUserId) OR (@rUserId=0))  
		 AND ((R.IsObsolete =@rIsCancel  AND (@rReportId != 20456 OR @rReportId != 30804))  OR   
		  ((@rReportId = 20456 OR @rReportId = 30804) AND ((@rFeeStatusId = 0) -- All  
		  OR (@rFeeStatusId = 1 AND R.IsObsolete = 0) -- Valid  
		  OR (@rFeeStatusId = 2 AND R.IsObsolete = 1) -- Cancel  
		  )))  
		 AND (SA.StatusId=@rStatusId OR @rStatusId=0)  
		 AND (SA.ClassStatusId=@rClassStatusId OR @rClassStatusId=0)  
		 AND (R.PayTypeId = @rPaytypeId OR @rPaytypeId=0)  
		 AND ((SA.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))  
		 AND ((SA.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))  
		 AND ((SA.RollNo <= @rToRollNo) OR (@rToRollNo=0))  
		 AND ((SA.Code=@rCode) OR (@rCode=''))  
		 AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))  
		 AND ((ISNULL(U.LoginTitle,'') like @rCreatedUserName) OR (ISNULL(@rCreatedUserName,'')=''))  
		 AND ((@rIsDiscount =1 AND R.DiscountAmount!=0) OR (@rIsDiscount=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 (  
		  (@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 ((RBM.OrgGroupId=@rOrgGroupId) OR (@rOrgGroupId=0))  
		 AND ((UPPER(R.BankName) like UPPER(@rBankName)) OR(ISNULL(@rBankName,'')=''))  
		 AND (ISNULL(SA.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')    
		 AND (ISNULL(R.BankName,'') IN( SELECT cast(item as nvarchar(100)) FROM  sCommon.fnsplit(@rBankNames,',')) OR @rBankNames='')   
		 AND ((R.ChequeClearDate>=@rFromChequeClearDate)OR(ISNULL(@rFromChequeClearDate,'')=''))      
		 AND ((R.ChequeClearDate<=@rToChequeClearDate)OR(ISNULL(@rToChequeClearDate,'')=''))
		 AND (ISNULL(R.PayTypeId,0) IN (SELECT cast(item as tinyint) FROM sCommon.fnsplit(@rPayTypeIds,',')) OR @rPayTypeIds='')
		 AND (ISNULL(R.ReceiptBookId,0) IN (SELECT cast(item as int) FROM sCommon.fnsplit(@rReceiptBookIds,',')) OR @rReceiptBookIds='')
  
		--GROUP BY R.Id,R.IsObsolete,R.ReceiptNumber,SA.ClassId,SA.DivisionId,SA.ClassName,SA.DivisionName,SA.RollNo, SA.Code,SA.Name,PTM.Title,R.ChequeNo,R.PaymentTransactionId
		--  ,R.BankName,R.ReceiptAmount,R.ChequeClearDate,R.ReceiptDate,R.CreatedUserId,U.LoginTitle,RBM.Title,RBM.BankName,RBM.BankAccountNumber,
		--  R.ReceiptBookId,R.Remark,R.DiscountAmount,RBM.OrderIndex,SA.OrgId,SA.OrganizationName,  
		--  R.AmountAfterDiscount,R.CGSTPercentage,R.SGSTPercentage,R.CGSTAmount,R.SGSTAmount,SA.OrgGroupBatchId,
		--  SA.BatchName,R.ChequeDate,R.ChequeClearDate,SA.GenderId

		 ORDER BY R.ReceiptNumber
	END

	ELSE
	BEGIN
		SELECT   
		  @rBuilder1 AS Builder1,  
		  @rBuilder2 AS Builder2,  
		  @rIsDetail AS IsDetail,  
		  (CASE WHEN @rReportId IN (20456,30804) THEN  R.IsObsolete ELSE @rIsCancel END) AS IsCancel,  
		  --@rIsCancel AS IsCancel,  
		  @rIsFilter As IsFilter,  
		  @rIsHeader As IsHeader,  
		  @rIsDisplayOrgGroup AS IsDisplayOrgGroup,  
		  R.Id AS ReceiptId,  
		  R.ReceiptNumber,  
		  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,  
		  --ISNULL(R.ChequeNo,'') AS ChequeNo,  
		  CASE WHEN ISNULL(R.ChequeNo,'') != '' THEN R.ChequeNo ELSE CONVERT(nvarchar(20),R.PaymentTransactionId) END AS ChequeNo,
		  ISNULL(R.BankName,'') AS BankName,  
		  R.ReceiptAmount,  
		  --R.ReceiptDate,  
		  CASE  WHEN @rReportId = 30611 AND R.ChequeClearDate IS NOT NULL THEN R.ChequeClearDate ELSE R.ReceiptDate END AS ReceiptDate,  
		  R.CreatedUserId,  
		  ISNULL(U.LoginTitle,'') AS UserName,  
		  ISNULL(RBM.Title,'') AS ReceiptBookTitle,  
		  ISNULL(RBM.BankName,'') AS ReceiptBookBank,  
		  ISNULL(RBM.BankAccountNumber,'') AS BankAccountNumber,  
		  ISNULL(R.ReceiptBookId,'0') As ReceiptBookId,  
		  ISNULL((CASE @rReportId WHEN 20461 THEN [sFee].[fReceiptFeeDetailGet](R.Id)  
		   WHEN 30940 THEN [sFee].[fReceiptFeeDetailGet](R.Id) ELSE '' END),'') AS FeeDetail,  
		   R.Remark,  
		   R.DiscountAmount,  
		   ISNULL(RBM.OrderIndex,0) AS ReceiptBookOrderIndex,  
		   SA.OrgId,  
		   SA.OrganizationName,  
		   ISNULL(R.AmountAfterDiscount,0) AS AmountAfterDiscount,  
		   ISNULL(R.CGSTPercentage,0) AS CGSTPercentage,  
		   ISNULL(R.SGSTPercentage,0) AS SGSTPercentage,  
		   ISNULL(R.CGSTAmount,0) AS CGSTAmount,  
		   ISNULL(R.SGSTAmount,0) AS SGSTAmount,  
		   @rCustomGroupId AS CustomGroupId,  
		   SA.OrgGroupBatchId AS BatchId,  
		   SA.BatchName,  
		   R.ChequeDate,  
		   R.ChequeClearDate   
		  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 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 sSecurity.tUser U  
		   ON U.Id=R.CreatedUserId  
		 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   
			AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))    
			AND (SA.OrgGroupBatchId = RT.OrgGroupBatchId)  
		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.ReceiptNumber >= @rFromReceiptNo) OR (@rFromReceiptNo = 0))  
		 AND ((R.ReceiptNumber <= @rToReceiptNo) OR (@rToReceiptNo = 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 ((R.CreatedUserId=@rUserId) OR (@rUserId=0))  
		 AND ((R.IsObsolete =@rIsCancel  AND (@rReportId != 20456 OR @rReportId != 30804))  OR   
		  ((@rReportId = 20456 OR @rReportId = 30804) AND ((@rFeeStatusId = 0) -- All  
		  OR (@rFeeStatusId = 1 AND R.IsObsolete = 0) -- Valid  
		  OR (@rFeeStatusId = 2 AND R.IsObsolete = 1) -- Cancel  
		  )))  
		 AND (SA.StatusId=@rStatusId OR @rStatusId=0)  
		 AND (SA.ClassStatusId=@rClassStatusId OR @rClassStatusId=0)  
		 AND (R.PayTypeId = @rPaytypeId OR @rPaytypeId=0)  
		 AND ((SA.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))  
		 AND ((SA.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))  
		 AND ((SA.RollNo <= @rToRollNo) OR (@rToRollNo=0))  
		 AND ((SA.Code=@rCode) OR (@rCode=''))  
		 AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))  
		 AND ((ISNULL(U.LoginTitle,'') like @rCreatedUserName) OR (ISNULL(@rCreatedUserName,'')=''))  
		 AND ((@rIsDiscount =1 AND R.DiscountAmount!=0) OR (@rIsDiscount=0))  
		 --AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')  
		  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 ((RBM.OrgGroupId=@rOrgGroupId) OR (@rOrgGroupId=0))  
		 AND ((UPPER(R.BankName) like UPPER(@rBankName)) OR(ISNULL(@rBankName,'')=''))  
		 AND (ISNULL(SA.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')    
		 AND (ISNULL(R.BankName,'') IN( SELECT cast(item as nvarchar(100)) FROM  sCommon.fnsplit(@rBankNames,',')) OR @rBankNames='')   
		 AND ((R.ChequeClearDate>=@rFromChequeClearDate)OR(ISNULL(@rFromChequeClearDate,'')=''))      
		 AND ((R.ChequeClearDate<=@rToChequeClearDate)OR(ISNULL(@rToChequeClearDate,'')=''))
		 AND (ISNULL(R.PayTypeId,0) IN (SELECT cast(item as tinyint) FROM sCommon.fnsplit(@rPayTypeIds,',')) OR @rPayTypeIds='')  		 
  
		 ORDER BY R.ReceiptNumber  
	END
 
-- UNION ALL  
   
-- SELECT   
--  R.Id AS ReceiptId,  
--  0 AS ClassId,  
--  --SA.ClassName,  
--  0 AS DivisionId,  
--  --SA.DivisionName,  
--  EM.DepartmentId,  
--  EM.DepartmentName AS ClassDept,  
--  0 AS RollNo,  
--  EM.Code,  
--  EM.EmployeeName,  
--  PTM.Title AS PayType,  
--  R.ReceiptAmount  
     
--  FROM   
--   sFee.tReceipt R  
--  INNER JOIN sCommon.tSourceTypeMaster STM  
--   ON STM.Id=R.SourceTypeId AND R.SourceTypeId = 95  
--  INNER JOIN sHrm.vExtEmployeeMaster EM  
--   ON EM.EmployeeId=R.SourceId  
--  INNER JOIN sFinanceCommon.tPayTypeMaster PTM  
--   ON PTM.Id=R.PayTypeId  
     
--WHERE   
--  ((EM.DepartmentId = @rDepartmentId) OR (@rDepartmentId = 0))  
-- AND ((R.ReceiptNumber >= @rFromReceiptNo) OR (@rFromReceiptNo = 0))  
-- AND ((R.ReceiptNumber <= @rToReceiptNo) OR (@rToReceiptNo = 0))  
-- AND ((R.ReceiptDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))  
-- AND ((R.ReceiptDate <= @rToDate) OR (ISNULL(@rToDate,'') = ''))  
-- AND (R.BatchId = @rBatchId)  
END
GO
PRINT N'Altering [sFee].[pRptFeeSummaryOtherGet]...';


GO
ALTER PROCEDURE [sFee].[pRptFeeSummaryOtherGet]
		@rReportId int,
		@rReceiptBookId int,
		@rAdmissionCategoryId int,
		@rClassId int,
		@rDivisionId int,
		@rUptoDate date,
		@rBatchId int,
		@rUserId bigint,
		@rBuilder1 nvarchar(max),
		@rBuilder2 nvarchar(max),
		@rIsDetail bit,
		@rOrgId int,
		@rOrgGroupBatchId int,
		@rIsExemption bit =0,
		@rStatusId int,
		@rCommonBatch nvarchar(100),
		@rDepartmentId int,
		@rFromRollNo int,
	    @rToRollNo int,
	    @rCode nvarchar(20),
	    @rIsFilter bit,
		@rIsHeader bit,
		@rCreatedUserName nvarchar(100)='',
		@rFeeHeadId nvarchar(max) = '',
		@rIsDisplayOrgGroup bit=0,
		@rExemptionTypeId int=0,
		@rFeeId nvarchar(max) = '',
		@rFilterId int=0,
		@rOrgIds nvarchar(max) = '',
		@rIsReceiptBookGroup bit=0,
		@rClassStatusId int=0,
		@rClassIds nvarchar(max) = '',
		@rDivisionIds nvarchar(max) = ''
		
		
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
BEGIN 	
	SELECT 
		@rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,
		@rIsDetail AS IsDetail,
		@rIsFilter As IsFilter,
		@rIsHeader As IsHeader, 
		@rIsDisplayOrgGroup AS IsDisplayOrgGroup,
		SA.AcademicId,
		SA.RollNo,
		SA.Name,
		SA.Code,
		SA.ClassId,
		SA.DivisionId,
		SA.ClassName,
		SA.DivisionName,
		SA.DivisionOrder AS DivisionOrderIndex,
		SA.ClassOrderIndex AS ClassOrderIndex,
		SA.ClassName+' - '+SA.DivisionName AS ClassDivision,
		FS.Id AS FeeSetupId,
		
		ISNULL(FS.IsVariable,0)AS IsVariable,
		ISNULL(FS.Amount,0)AS Amount,
		ISNULL(FS.StartDate,'1900-01-01')AS StartDate,
		ISNULL(FS.EndDate,'1900-01-01')AS EndDate,
		ISNULL(FA.VariableAmount,0.00)AS FAAmount,
		ISNULL(FA.DiscountAmount,0.00)AS DiscountAmount,
		ISNULL(FA.AdditionalAmount,0.00)AS AdditionalAmount,
		ISNULL(FA.NotApplicableAmount,0.00)AS NotApplicableAmount,
		ISNULL(R.PaidAmount,0) AS PaidAmount,
		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 PendingAmount,
		ISNULL(FA.Remark,'') AS Remark,
		FS.ReceiptBookId,
		FS.FeeName,
		SA.OrgId,
		O.DisplayTitle AS OrgName,
		O.OrderIndex AS OrgOrderIndex,
		ISNULL(RBM.Title,'') AS ReceiptBookTitle,
		ISNULL(RBM.OrderIndex,0) AS ReceiptOrderIndex,
		SA.DepartmentId,
		SA.DepartmentName,
		SA.ExemptionTypeId,
		ISNULL(ETM.Title,'') AS ExemptionType,
		FHM.Id AS FeeHeadId,
		FHM.Title AS FeeHeadName,
		FHM.OrderIndex AS FeeHeadOrderIndex
  FROM 
  
			 sStudent.vStudentAcademic SA
		INNER JOIN 
		(
			SELECT 
				FS1.FeeId,
				FS1.Id,
				ISNULL(FS1.IsOptional,0)AS IsOptional,
				ISNULL(FS1.IsVariable,0)AS IsVariable,
				ISNULL(FS1.Amount,0)AS Amount,
				ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
				ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
				FS1.BatchId,
				ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
				SA1.AcademicId,
				FM.Title AS FeeName,
				FM.FeeHeadId
			FROM sFee.tFeeSetup FS1
			INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
			AND ((SA1.ClassId=@rClassId) OR (@rClassId=0))
			AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
			INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
			WHERE 
				((FS1.ClassId=@rClassId) OR (@rClassId=0))
				AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
				AND (FS1.IsOptional=0)
				AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
				AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=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(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')
				AND ((FS1.StartDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
				AND (ISNULL(SA1.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='')
				AND (ISNULL(SA1.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='')  
				UNION ALL
				
			SELECT 
				FS1.FeeId,
				FS1.Id,
				ISNULL(FS1.IsOptional,0)AS IsOptional,
				ISNULL(FS1.IsVariable,0)AS IsVariable,
				ISNULL(FS1.Amount,0)AS Amount,
				ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
				ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
				FS1.BatchId,
				ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
				SA1.AcademicId,
				FM.Title AS FeeName,
				FM.FeeHeadId
			FROM sFee.tFeeSetup FS1
		INNER JOIN sFee.tFeeOptional FO
			ON FO.FeeSetupId=FS1.Id 
	    INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
		INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=FO.SourceId AND SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
			AND ((SA1.ClassId=@rClassId) OR (@rClassId=0)) 
			AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
		WHERE
					((FS1.ClassId=@rClassId) OR (@rClassId=0))
					AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
				AND (FS1.IsOptional=1)
				AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
				AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=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(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')
				AND ((FS1.StartDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
				AND (ISNULL(SA1.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='')
				AND (ISNULL(SA1.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='')  
		) FS ON FS.AcademicId=SA.AcademicId
		LEFT JOIN sFee.tFeeAllocation FA
			ON FA.FeeSetupId=FS.Id AND FA.SourceId=SA.AcademicId
		LEFT JOIN
		(
		    SELECT 
					ISNULL(SUM(RD.Amount),0) AS PaidAmount,RD.FeeSetupId ,R.SourceId
		    FROM
					sFee.tReceipt R 
				INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id 
				INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id
				INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id
				INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=R.SourceId 
				AND ((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND (SA1.ClassId=@rClassId OR @rClassId=0) 
				AND (SA1.DivisionId=@rDivisionId OR @rDivisionId=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 ((R.CreatedUserId=@rUserId) OR (@rUserId=0))
				AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
				AND (R.ReceiptDate <= @rUptoDate)
				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(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')
				AND (ISNULL(SA1.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='')
				AND (ISNULL(SA1.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='')  
					GROUP BY FeeSetupId,R.SourceId
		
		) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
		 INNER JOIN sSetup.tOrganizationMaster O ON
		 SA.OrgId = O.Id
		 INNER JOIN sFee.tReceiptBookMaster RBM 
			ON FS.ReceiptBookId=RBM.Id
		 INNER JOIN sFee.tFeeHeadMaster FHM 
			ON FHM.Id=FS.FeeHeadId	
		 LEFT JOIN sFee.tExemptionTypeMaster ETM
			ON ETM.Id = SA.ExemptionTypeId
		  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)) 
       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 = SA.StudentId AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) 
	WHERE	
	((@rIsExemption = 0 AND  1 = 1) OR (@rIsExemption = 1  AND  ISNULL(FA.DiscountAmount,0) > 0))
    AND	((SA.BatchId=@rBatchId) OR (@rBatchId=0))   
    AND	((SA.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))   
    AND (SA.StatusId=@rStatusId OR @rStatusId=0)
	AND ((FS.StartDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
	AND ((SA.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
	AND ((SA.RollNo <= @rToRollNo) OR (@rToRollNo=0))
	AND ((SA.Code=@rCode) OR (@rCode=''))
	AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))		
	AND ((SA.ExemptionTypeId=@rExemptionTypeId) OR (@rExemptionTypeId=0))		
	AND ((SA.ClassId=@rClassId) OR (@rClassId=0))
	AND ((SA.DivisionId=@rDivisionId) OR (@rDivisionId=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(SA.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')
	AND ((SA.ClassStatusId=@rClassStatusId) OR (@rClassStatusId=0))
	AND (ISNULL(SA.ClassId,0) IN (SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='')	
	AND (ISNULL(SA.DivisionId,0) IN (SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='')  		     
			Order by SA.RollNo
END
GO
PRINT N'Altering [sFee].[pRptReceiptListCollectionGroupwiseListGet]...';


GO
ALTER PROCEDURE [sFee].[pRptReceiptListCollectionGroupwiseListGet]  
  @rReportId int,  
  @rReceiptBookId int,  
  @rAdmissionCategoryId int,  
  @rClassId int,  
  @rDivisionId int,  
  @rFromDate date,  
  @rToDate date,  
  @rFromReceiptNo int,  
  @rToReceiptNo int,  
  @rBatchId int,  
  @rUserId bigint,  
  @rBuilder1 nvarchar(max),  
  @rBuilder2 nvarchar(max),  
  @rIsCancel bit,  
  @rOrgId int,  
  @rOrgGroupBatchId int,  
  @rStatusId int,  
  @rCommonBatch nvarchar(100),  
  @rDepartmentId int,  
  @rFromRollNo int,  
  @rToRollNo int,  
  @rCode nvarchar(20),  
  @rIsDetail bit=0,  
  @rIsFilter bit,  
  @rIsHeader bit,  
  @rCreatedUserName nvarchar(100)='',  
  @rFeeHeadId nvarchar(max) = '',  
  @rIsDisplayOrgGroup bit=0,  
  @rPayTypeId int=0,  
  @rFeeId nvarchar(max) = '',  
  @rFilterId int=0,
  @rOrgIds nvarchar(max) = '',
  @rClassStatusId int=0,
  @rPayTypeIds nvarchar(max) = '',
  @rCollectionGroupId int =0  
  
 WITH EXECUTE AS CALLER  
AS  
SET NOCOUNT ON  
      
BEGIN    
 SELECT   
  @rBuilder1 AS Builder1,  
  @rBuilder2 AS Builder2,  
  @rIsCancel AS IsCancel,  
  @rIsDetail AS IsDetail,  
  @rIsFilter As IsFilter,  
  @rIsHeader As IsHeader,  
  @rIsDisplayOrgGroup AS IsDisplayOrgGroup,  
  R.Id AS ReceiptId,  
  R.ReceiptNumber,  
  SA.ClassId,  
  SA.ClassName,  
  SA.DivisionId,  
  SA.DivisionName,  
  SA.ClassName+' - '+SA.DivisionName AS ClassDivision,  
  SA.RollNo,  
  SA.AcademicId,  
  SA.FirstName,  
  SA.MiddleName,  
  SA.LastName,  
  SA.Code,  
  SA.Name,  
  PTM.Title AS PayType,  
  --R.ChequeNo,  
  CASE WHEN ISNULL(R.ChequeNo,'') != '' THEN R.ChequeNo ELSE CONVERT(nvarchar(20),R.PaymentTransactionId) END AS ChequeNo,
  R.BankName,  
  --R.ReceiptAmount,  ,
  CASE WHEN ROW_NUMBER() OVER (PARTITION BY R.Id  ORDER BY R.Id ) =1 THEN R.ReceiptAmount ELSE 0 END AS ReceiptAmount,
  R.ReceiptDate,  
  FM.Title AS FeeDetail,  
  FM.Code AS FeeCode,  
  FM.OrderIndex AS FeeOrderIndex,  
  RD.Amount AS DetailAmount,  
  ISNULL(R.ReceiptBookId,'0') As ReceiptBookId,  
  ISNULL(RBM.Title,'') AS ReceiptBookTitle,  
  ISNULL(RBM.OrderIndex,0) AS ReceiptOrderIndex,  
  ISNULL(FHM.Title,'') AS FeeHead,  
  ISNULL(FHM.Code,'') AS FeeHeadCode,  
  ISNULL(FHM.OrderIndex,0) AS FeeHeadOrderIndex,  
  SA.OrgId,  
  O.DisplayTitle AS OrgName,  
  O.OrderIndex AS OrgOrderIndex,  
  ISNULL(R.Remark,'') AS Remark,  
  DM.Id AS DepartmentId,  
  DM.Title AS DepartmentName,  
  SA.ClassOrderIndex,  
  ISNULL(SO.GenderId,0) AS GenderId,  
  ISNULL(SA.BatchName,'') BatchName,  
  ISNULL(FM.FeeHeadId,0) AS FeeHeadId,  
  sFinanceCommon.fNumberToWordsWithDecimal(ISNULL(R.ReceiptAmount,0.00),1,2,O.OrgGroupId) AS ReceiptAmountInWords,  
  R.ChequeDate,  
  ISNULL(FM.Id,0) AS FeeId,  
  ISNULL(FM.Title,'') AS Fee,  
  ISNULL(SF.FatherName,'' ) AS FatherName,  
  ISNULL(SF.MotherName,'' ) AS MotherNameDiscount,
  CASE WHEN ROW_NUMBER() OVER (PARTITION BY R.Id  ORDER BY R.Id ) =1 THEN R.DiscountAmount ELSE 0 END AS Discount,
  RD.Amount AS PaidAmount,
  ISNULL(CGM.Id,0) AS CollectionGroupId,
  ISNULL(CGM.Title,'') AS CollectionGroup  ,
  ISNULL(U.LoginTitle,'') AS UserName,
  SA.SUId AS SUId
  
  FROM   
   sFee.tReceipt R  
  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.tReceiptDetail RD  
   ON RD.ReceiptId=R.Id  
  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 sFee.tReceiptBookMaster RBM   
   ON RBM.Id=R.ReceiptBookId  
  INNER JOIN sSetup.tDepartmentMaster DM  
   ON SA.DepartmentId=DM.Id  
  INNER JOIN sSetup.tOrganizationMaster O  
   ON O.Id=sa.OrgId  
   LEFT JOIN sSecurity.tUser U  
   ON U.Id=R.CreatedUserId 
  LEFT JOIN sStudent.tStudentOther SO  
   ON SO.StudentId = SA.StudentId  
  LEFT JOIN sStudent.tStudentFamily SF  
   ON SF.StudentId = SA.StudentId  
    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))   
     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 = SA.StudentId AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) 
	LEFT JOIN sFee.tCollectionGroupMaster CGM ON FS.CollectionGroupId=CGM.Id  
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.ReceiptNumber >= @rFromReceiptNo) OR (@rFromReceiptNo = 0))  
 AND ((R.ReceiptNumber <= @rToReceiptNo) OR (@rToReceiptNo = 0))  
 AND ((R.ReceiptDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))  
 AND ((R.ReceiptDate <= @rToDate) OR (ISNULL(@rToDate,'') = ''))  
 AND (SA.OrgGroupBatchId = @rOrgGroupBatchId)  
 AND ((SA.OrgId=@rOrgId) OR (@rOrgId=0))  
 AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))  
 AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))  
 AND (R.IsObsolete = @rIsCancel)   
 AND (SA.StatusId = @rStatusId OR @rStatusId=0)  
 AND ((SA.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))  
 AND ((SA.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))  
 AND ((SA.RollNo <= @rToRollNo) OR (@rToRollNo=0))  
 AND ((SA.Code=@rCode) OR (@rCode=''))  
 AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))  
 --AND ((ISNULL(U.LoginTitle,'') like @rCreatedUserName) OR (ISNULL(@rCreatedUserName,'')=''))  
 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 ((R.PayTypeId=@rPayTypeId) OR (@rPayTypeId=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(SA.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')
  	 AND ((SA.ClassStatusId=@rClassStatusId) OR (@rClassStatusId=0))
	AND (ISNULL(R.PayTypeId,0) IN (SELECT cast(item as tinyint) FROM sCommon.fnsplit(@rPayTypeIds,',')) OR @rPayTypeIds='')  
	AND ((FS.CollectionGroupId=@rCollectionGroupId) OR (@rCollectionGroupId=0))     
 ORDER BY R.ReceiptNumber  
 --ORDER BY R.Id 
-- UNION ALL  
   
-- SELECT   
--  R.Id AS ReceiptId,  
--  0 AS ClassId,  
--  --SA.ClassName,  
--  0 AS DivisionId,  
--  --SA.DivisionName,  
--  EM.DepartmentId,  
--  EM.DepartmentName AS ClassDept,  
--  0 AS RollNo,  
--  EM.Code,  
--  EM.EmployeeName,  
--  PTM.Title AS PayType,  
--  R.ReceiptAmount  
     
--  FROM   
--   sFee.tReceipt R  
--  INNER JOIN sCommon.tSourceTypeMaster STM  
--   ON STM.Id=R.SourceTypeId AND R.SourceTypeId = 95  
--  INNER JOIN sHrm.vExtEmployeeMaster EM  
--   ON EM.EmployeeId=R.SourceId  
--  INNER JOIN sFinanceCommon.tPayTypeMaster PTM  
--   ON PTM.Id=R.PayTypeId  
     
--WHERE   
--  ((EM.DepartmentId = @rDepartmentId) OR (@rDepartmentId = 0))  
-- AND ((R.ReceiptNumber >= @rFromReceiptNo) OR (@rFromReceiptNo = 0))  
-- AND ((R.ReceiptNumber <= @rToReceiptNo) OR (@rToReceiptNo = 0))  
-- AND ((R.ReceiptDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))  
-- AND ((R.ReceiptDate <= @rToDate) OR (ISNULL(@rToDate,'') = ''))  
-- AND (R.BatchId = @rBatchId)  
END
GO
PRINT N'Altering [sFee].[pRptTransportFeePendingWithFeeNameGet]...';


GO
 
ALTER PROCEDURE [sFee].[pRptTransportFeePendingWithFeeNameGet]
		@rReportId int=0,
		@rReceiptBookId int=0,
		@rAdmissionCategoryId int=0,
		@rClassId int=0,
		@rDivisionId int=0,
		@rUptoDate date='',
		@rBatchId int=0,
		@rUserId bigint=0,
		@rBuilder1 nvarchar(max)='',
		@rBuilder2 nvarchar(max)='',
		@rOrgId int=0,
		@rOrgGroupBatchId int=0,
		@rStatusId int=0,
		@rCommonBatch nvarchar(100)='',
		@rDepartmentId int=0,
		@rFromRollNo int=0,
	    @rToRollNo int=0,
	    @rCode nvarchar(20)='',
	    @rIsFilter bit=0,
		@rIsHeader bit=0,		
		@rCreatedUserName nvarchar(20) = '',
		@rRouteId int=0,
		@rDestinationId int = 0,
		@rTransportId int =0
	    
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
BEGIN 	


--CREATE TABLE #TempStudent
--	(
--	AcademicId bigint,
--	ClassId int,
--	BatchId int,
--	a
--	)
--	SELECT AcademicId

 
	--CREATE TYPE  TempPendingFee AS TABLE
	--(
	--AcademicId bigint
	--,
	--RollNo int,
	--Name nvarchar(200),
	--Code nvarchar(20),
	--ClassId int,
	--DivisionId int,
	--ClassName nvarchar(100),
	--DivisionName nvarchar(100),
	--ClassDivision nvarchar(100),
	--FeeSetupId int,
	--IsVariable int,
	--Amount Decimal(12,2),
	--StartDate date,
	--EndDate date,
	--FAAmount Decimal(12,2),
	--DiscountAmount Decimal(12,2),
	--AdditionalAmount Decimal(12,2),
	--PaidAmount Decimal(12,2),
	--PendingAmount Decimal(12,2),
	--Remark nvarchar(200),
	--ReceiptBookId int,
	--FeeName nvarchar(100),
	--FeeCode nvarchar(100),
	--OrgId int,
	--OrgName nvarchar(200),
	--OrgOrderIndex int,
	--ReceiptBookTitle nvarchar(200),
	--ReceiptOrderIndex int 
	--)
	 
	DECLARE @p as TempPendingFee
	
	INSERT INTO  @p 
	 
	SELECT 
		--@rBuilder1 AS Builder1,
		--@rBuilder2 AS Builder2,
		--@rIsDetail AS IsDetail,
		--@rIsFilter As IsFilter,
		--@rIsHeader As IsHeader,
		SA.AcademicId
		,
		SA.RollNo,
		SA.Name,
		SA.Code,
		SA.ClassId,
		SA.DivisionId,
		SA.ClassName,
		SA.DivisionName,
		SA.ClassName+' - '+SA.DivisionName AS ClassDivision,
		FS.Id AS FeeSetupId,		
		ISNULL(FS.IsVariable,0)AS IsVariable,
		ISNULL(FS.Amount,0)AS Amount,
		ISNULL(FS.StartDate,'1900-01-01')AS StartDate,
		ISNULL(FS.EndDate,'1900-01-01')AS EndDate,
		ISNULL(FA.VariableAmount,0.00)AS FAAmount,
		ISNULL(FA.DiscountAmount,0.00)AS DiscountAmount,
		ISNULL(FA.AdditionalAmount,0.00)AS AdditionalAmount,
		ISNULL(R.PaidAmount,0) AS PaidAmount,
		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 PendingAmount,
		ISNULL(FA.Remark,'') AS Remark,
		FS.ReceiptBookId,
		FS.FeeName,
		FS.FeeCode,
		SA.OrgId,
		O.Title AS OrgName,
		O.OrderIndex AS OrgOrderIndex,
		ISNULL(RBM.Title,'') AS ReceiptBookTitle,
		ISNULL(RBM.OrderIndex,0) AS ReceiptOrderIndex,
		0 AS BatchId,
		'' AS BatchName, 
		'' AS Pickup,
		'' AS DRoppoint,
		'' AS PresentContactNo,
		ISNULL(SA.SUID,'') AS SUID,
		SA.ClassOrderIndex,
		SA.DivisionOrder,
		FS.OrderIndex
  FROM 
  
			 sStudent.vStudentAcademic SA
		INNER JOIN 
		(
			SELECT 
				FS1.FeeId,
				FS1.Id,
				ISNULL(FS1.IsOptional,0)AS IsOptional,
				ISNULL(FS1.IsVariable,0)AS IsVariable,
				ISNULL(FS1.Amount,0)AS Amount,
				ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
				ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
				FS1.BatchId,
				ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
				SA1.AcademicId,
				FM.Title AS FeeName,
				FM.Code AS FeeCode,
				SA1.StudentId AS StudentId,
				FM.OrderIndex
			FROM sFee.tFeeSetup FS1
			INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId 
				AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				AND ((SA1.ClassId=@rClassId) OR (@rClassId=0)) AND ((SA1.DivisionId=@rDivisionId) OR (@rDivisionId=0))
				AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
			INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
			INNER JOIN sFee.tFeeHeadMaster FH ON FH.Id = FM.FeeHeadId AND FH.Number = 1001
			--INNER JOIN sTransport.tAssignRoute AR oN SA1.AcademicId = AR.SourceId AND AR.SourceTypeId = 2003
			INNER JOIN sTransport.tAssignRoute AR oN SA1.StudentId = AR.SourceId AND AR.SourceTypeId = 2003
			INNER JOIN sTransport.tBusRouteDestinationMaster BRDM ON BRDM.Id = AR.PickupDestinationId
			INNER JOIN sTransport.tBusRouteMaster BRM ON BRDM.BusRouteId = BRM.Id
			WHERE 
			     (SA1.OrgGroupBatchId = @rOrgGroupBatchId)
				AND	((FS1.ClassId=@rClassId) OR (@rClassId=0))
				AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
				AND (FS1.IsOptional=0)
				AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
				AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((BRDM.BusRouteId=@rRouteId) OR (@rRouteId=0))
				AND ((BRDM.Id=@rDestinationId) OR (@rDestinationId=0))
				AND ((BRM.TransportId=@rTransportId) OR (@rTransportId=0))
				AND (BRM.OrgGroupBatchId = @rOrgGroupBatchId)
				
				UNION ALL
				
			SELECT 
				FS1.FeeId,
				FS1.Id,
				ISNULL(FS1.IsOptional,0)AS IsOptional,
				ISNULL(FS1.IsVariable,0)AS IsVariable,
				ISNULL(FS1.Amount,0)AS Amount,
				ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
				ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
				FS1.BatchId,
				ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
				SA1.AcademicId,
				FM.Title AS FeeName,
				FM.Code AS FeeCode,
				SA1.StudentId AS StudentId,
				FM.OrderIndex
			FROM sFee.tFeeSetup FS1
		INNER JOIN sFee.tFeeOptional FO
			ON FO.FeeSetupId=FS1.Id
	    INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
		INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=FO.SourceId AND SA1.BatchId = FS1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
			AND ((SA1.ClassId=@rClassId) OR (@rClassId=0)) AND ((SA1.DivisionId=@rDivisionId) OR (@rDivisionId=0))
			AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
		INNER JOIN sFee.tFeeHeadMaster FH ON FH.Id = FM.FeeHeadId AND FH.Number = 1001
		--INNER JOIN sTransport.tAssignRoute AR oN SA1.AcademicId = AR.SourceId AND AR.SourceTypeId = 2003
		INNER JOIN sTransport.tAssignRoute AR oN SA1.StudentId = AR.SourceId AND AR.SourceTypeId = 2003
		INNER JOIN sTransport.tBusRouteDestinationMaster BRDM ON BRDM.Id = AR.PickupDestinationId
		INNER JOIN sTransport.tBusRouteMaster BRM ON BRDM.BusRouteId = BRM.Id
		WHERE
		       (SA1.OrgGroupBatchId = @rOrgGroupBatchId)
				AND ((FS1.ClassId=@rClassId) OR (@rClassId=0))
				AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
				AND (FS1.IsOptional=1)
				AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
				AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((BRDM.BusRouteId=@rRouteId) OR (@rRouteId=0))
				AND ((BRDM.Id=@rDestinationId) OR (@rDestinationId=0))
				AND ((BRM.TransportId=@rTransportId) OR (@rTransportId=0))
				AND (BRM.OrgGroupBatchId = @rOrgGroupBatchId)
				
		) FS ON FS.AcademicId=SA.AcademicId
		LEFT JOIN sFee.tFeeAllocation FA
			ON FA.FeeSetupId=FS.Id AND FA.SourceId=SA.AcademicId
		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 FS.Id = RD.FeeSetupId 
				INNER JOIN sfEe.tFeeMaster FM ON FM.Id = FS.FeeId 
				INNER JOIN sFee.tFeeHeadMaster FH ON FM.FeeHeadId = FH.Id AND FH.Number = 1001
				INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=R.SourceId				
				AND (SA1.ClassId=@rClassId OR @rClassId=0) AND ((SA1.DivisionId=@rDivisionId) OR (@rDivisionId=0))
				AND (SA1.DivisionId=@rDivisionId OR @rDivisionId=0)
				--INNER JOIN sTransport.tAssignRoute AR oN SA1.AcademicId = AR.SourceId AND AR.SourceTypeId = 2003
				INNER JOIN sTransport.tAssignRoute AR oN SA1.StudentId = AR.SourceId AND AR.SourceTypeId = 2003
				INNER JOIN sTransport.tBusRouteDestinationMaster BRDM ON BRDM.Id = AR.PickupDestinationId
				INNER JOIN sTransport.tBusRouteMaster BRM ON BRDM.BusRouteId = BRM.Id
				
			WHERE		
				(R.SourceTypeId = 2001)
				AND ((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND (R.IsObsolete = 0) 
				AND ((SA1.OrgGroupBatchId = @rOrgGroupBatchId)  )
				AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))
				AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
				AND ((BRDM.BusRouteId=@rRouteId) OR (@rRouteId=0))
				AND ((BRDM.Id=@rDestinationId) OR (@rDestinationId=0))
				AND ((BRM.TransportId=@rTransportId) OR (@rTransportId=0))
				AND (BRM.OrgGroupBatchId = @rOrgGroupBatchId)
				GROUP BY FeeSetupId,R.SourceId
				
				
		
		) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
		 INNER JOIN sSetup.tOrganizationMaster O ON
		 SA.OrgId = O.Id
		 INNER JOIN sFee.tReceiptBookMaster RBM 
			ON FS.ReceiptBookId=RBM.Id
		INNER JOIN sTransport.tAssignRoute AR 
			ON  SA.StudentId = AR.SourceId AND AR.SourceTypeId = 2003	
		INNER JOIN sTransport.tBusRouteDestinationMaster BRDM 
			ON BRDM.Id = AR.PickupDestinationId
	 INNER JOIN sTransport.tBusRouteMaster BRM ON BRDM.BusRouteId = BRM.Id
		
	WHERE	
			(SA.OrgGroupBatchId = @rOrgGroupBatchId)
			AND ((SA.BatchId=@rBatchId) OR (@rBatchId=0)) 
			AND (SA.StatusId = @rStatusId OR @rStatusId=0)
			AND ((FS.StartDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
			AND ((SA.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
			AND ((SA.RollNo <= @rToRollNo) OR (@rToRollNo=0))
			AND ((SA.Code=@rCode) OR (@rCode=''))
			AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=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 ((BRDM.BusRouteId=@rRouteId) OR (@rRouteId=0))
			AND ((BRDM.Id=@rDestinationId) OR (@rDestinationId=0))
			AND (BRM.OrgGroupBatchId = @rOrgGroupBatchId)
			Order by SA.RollNo

			SELECT
			P.OrgId,			 
			P.ReceiptBookId,
			P.AcademicId,
			P.DivisionId,
			P.ClassDivision,P.RollNo, P.Name,P.Code,ReceiptBookTitle,OrgName,
			SUM(P.PendingAmount) AS PendingAmount, 
			[sFee].[fPendingFeeNamesGet](P.AcademicId,ReceiptBookId,	@p) AS PendingFeeName,
			P.ReceiptOrderIndex,
			BR.Id AS BusRouteId,
			BR.Title AS BusRoute,
			BD.Title AS BusDestination,
			isnull(SC.ParentContactNo,'') AS ParentContactNo,
			P.SUID,
			P.ClassOrderIndex,
			P.DivisionOrderIndex
			
			FROM @p P INNER JOIN sStudent.vStudentAcademic VA ON p.AcademicId=VA.AcademicId
			INNER JOIN sTransport.tAssignRoute AR oN VA.StudentId = AR.SourceId AND SourceTypeId = 2003
			INNER JOIN sTransport.tBusRouteDestinationMaster BD ON BD.Id = AR.PickupDestinationId 
			INNER JOIN sTransport.tBusRouteMaster BR ON BR.Id = BD.BusRouteId 
			AND BR.OrgGroupBatchId = @rOrgGroupBatchId
			LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId =  VA.StudentId
			GROUP By P.ReceiptBookId,P.OrgId,P.AcademicId,P.DivisionId,
			P.ClassDivision,P.RollNo, P.Name,P.Code,
			P.ReceiptBookTitle,P.OrgName,P.ReceiptOrderIndex,BR.Title,BD.Title,BR.Id,SC.ParentContactNo	,P.SUID,P.ClassOrderIndex,P.DivisionOrderIndex
			ORDER BY P.AcademicId
 
END
GO
PRINT N'Altering [sFee].[pStudentFeeDetailGet]...';


GO
 
ALTER PROCEDURE [sFee].[pStudentFeeDetailGet]
	 
	   @rBusRouteId int,
	   @rOrgGroupId smallint, 
	   @rOrgGroupBatchId int
		
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
		
BEGIN 

DECLARE @p as TempPendingFee
	
	INSERT INTO  @p 
	 
	SELECT 
		SA.AcademicId,
		SA.RollNo,
		SA.Name,
		SA.Code,
		SA.ClassId,
		SA.DivisionId,
		SA.ClassName,
		SA.DivisionName,
		SA.ClassName+' - '+SA.DivisionName AS ClassDivision,
		FS.Id AS FeeSetupId,		
		ISNULL(FS.IsVariable,0)AS IsVariable,
		ISNULL(FS.Amount,0)AS Amount,
		ISNULL(FS.StartDate,'1900-01-01')AS StartDate,
		ISNULL(FS.EndDate,'1900-01-01')AS EndDate,
		ISNULL(FA.VariableAmount,0.00)AS FAAmount,
		ISNULL(FA.DiscountAmount,0.00)AS DiscountAmount,
		ISNULL(FA.AdditionalAmount,0.00)AS AdditionalAmount,
		ISNULL(R.PaidAmount,0) AS PaidAmount,
		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 PendingAmount,
		ISNULL(FA.Remark,'') AS Remark,
		FS.ReceiptBookId,
		FS.FeeName,
		FS.FeeCode,
		SA.OrgId,
		O.Title AS OrgName,
		O.OrderIndex AS OrgOrderIndex,
		ISNULL(RBM.Title,'') AS ReceiptBookTitle,
		ISNULL(RBM.OrderIndex,0) AS ReceiptOrderIndex,
		0 AS BatchId,
		'' AS BatchName, 
		'' AS Pickup,
		'' AS DRoppoint,
		'' AS PresentContactNo,
		ISNULL(SA.SUID,'') AS SUID,
		SA.ClassOrderIndex,
		SA.DivisionOrder,
		FS.FeeOrderIndex	
  FROM 
        sStudent.vStudentAcademic SA
		INNER JOIN 
		(
			SELECT 
				FS1.FeeId,
				FS1.Id,
				ISNULL(FS1.IsOptional,0)AS IsOptional,
				ISNULL(FS1.IsVariable,0)AS IsVariable,
				ISNULL(FS1.Amount,0)AS Amount,
				ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
				ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
				FS1.BatchId,
				ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
				SA1.AcademicId,
				FM.Title AS FeeName,
				FM.Code AS FeeCode,
				SA1.StudentId AS StudentId,
				FM.OrderIndex AS FeeOrderIndex
			FROM sFee.tFeeSetup FS1
				INNER JOIN sFee.tFeeOptional FO ON FO.FeeSetupId=FS1.Id
				INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
				INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=FO.SourceId AND SA1.BatchId = FS1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId AND SA1.ClassId = FS1.ClassId
				INNER JOIN sFee.tFeeHeadMaster FH ON FH.Id = FM.FeeHeadId AND FH.Number = 1001
				INNER JOIN sTransport.tAssignRoute AR oN SA1.StudentId = AR.SourceId AND AR.SourceTypeId = 2003
				INNER JOIN sTransport.tBusRouteDestinationMaster BRDM ON BRDM.Id = AR.PickupDestinationId
				INNER JOIN sTransport.tBusRouteMaster BRM ON BRDM.BusRouteId = BRM.Id
		WHERE
		       (SA1.OrgGroupBatchId = @rOrgGroupBatchId)
				AND (FS1.IsOptional=1)
				AND ((BRDM.BusRouteId=@rBusRouteId) OR (@rBusRouteId=0))
				AND (BRM.OrgGroupBatchId = @rOrgGroupBatchId)
				
		) FS ON FS.AcademicId=SA.AcademicId
		LEFT JOIN sFee.tFeeAllocation FA
			ON FA.FeeSetupId=FS.Id AND FA.SourceId=SA.AcademicId
		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 FS.Id = RD.FeeSetupId 
				INNER JOIN sfEe.tFeeMaster FM ON FM.Id = FS.FeeId 
				INNER JOIN sFee.tFeeHeadMaster FH ON FM.FeeHeadId = FH.Id AND FH.Number = 1001
				INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=R.SourceId				
				INNER JOIN sTransport.tAssignRoute AR oN SA1.StudentId = AR.SourceId AND AR.SourceTypeId = 2003
				INNER JOIN sTransport.tBusRouteDestinationMaster BRDM ON BRDM.Id = AR.PickupDestinationId
				INNER JOIN sTransport.tBusRouteMaster BRM ON BRDM.BusRouteId = BRM.Id
				
			WHERE		
				(R.SourceTypeId = 2001)
				AND (R.IsObsolete = 0) 
				AND ((SA1.OrgGroupBatchId = @rOrgGroupBatchId)  )
				AND ((BRDM.BusRouteId=@rBusRouteId) OR (@rBusRouteId=0))
				AND (BRM.OrgGroupBatchId = @rOrgGroupBatchId)
			GROUP BY FeeSetupId,R.SourceId
		) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
		 INNER JOIN sSetup.tOrganizationMaster O ON SA.OrgId = O.Id
		 INNER JOIN sFee.tReceiptBookMaster RBM ON FS.ReceiptBookId=RBM.Id
		 INNER JOIN sTransport.tAssignRoute AR ON  SA.StudentId = AR.SourceId AND AR.SourceTypeId = 2003	
		 INNER JOIN sTransport.tBusRouteDestinationMaster BRDM ON BRDM.Id = AR.PickupDestinationId
	     INNER JOIN sTransport.tBusRouteMaster BRM ON BRDM.BusRouteId = BRM.Id
		
	WHERE	
			(SA.OrgGroupBatchId = @rOrgGroupBatchId)
			AND (SA.StatusId = 1)
			AND ((BRDM.BusRouteId=@rBusRouteId) OR (@rBusRouteId=0))
			AND (BRM.OrgGroupBatchId = @rOrgGroupBatchId)
    Order by SA.DivisionOrder

			SELECT 
				 CM.DisplayTitle + '-' + DM.DisplayTitle AS ClassDivision,
			 	 SA.StudentId AS StudentId, 
			 	 SA.Code AS StudentCode,
				 0x AS StudentPhoto, 
				 SA.FirstName + ' ' + SA.LastName AS StudentName, 
				 BRDM.Title AS Destination,
				 ISNULL(P.PendingAmount,0.00) AS PendingAmount ,
				 ISNULL(P.FeeName,'')AS FeeName
			FROM 
				 sTransport.tAssignRoute AR 
				 INNER JOIN sStudent.vStudentAcademic SA ON SA.StudentId = AR.SourceId
		         INNER JOIN sTransport.tBusRouteDestinationMaster BRDM ON BRDM.Id = AR.PickupDestinationId 
		         INNER JOIN sTransport.tBusRouteMaster BRM ON BRM.Id = BRDM.BusRouteId 
		         INNER JOIN sSetup.tClassMaster CM ON CM.Id = SA.ClassId 
		         INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = SA.DivisionId 
                 LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId = SA.StudentId 
				 LEFT JOIN @p P ON P.AcademicId = SA.AcademicId
            WHERE 
                 BRM.Id = @rBusRouteId 
                 AND BRM.OrgGroupId = @rOrgGroupId 
                 AND BRM.OrgGroupBatchId = @rOrgGroupBatchId
                 AND SA.IsActiveBatch = 1
                 AND SA.StatusId = 1
            ORDER BY 
				 BRDM.OrderIndex,DM.OrderIndex
END
GO
PRINT N'Altering [sFee].[pUpdatePendingAsNAGet]...';


GO
 
ALTER PROCEDURE [sFee].[pUpdatePendingAsNAGet]
	 
		@rOrgGroupBatchId int=0,
		@rOrgId int=0,
		@rBatchId int=0,	 
		@rFromLeftDate Date=NULL,
		@rToLeftDate Date=NULL,
	    @rStatusId int=3

	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 	
	
	DECLARE @p AS TempPendingFee
	
	INSERT INTO @p 
	SELECT 
		SA.AcademicId,
		SA.RollNo,
		SA.Name,
		SA.Code,
		SA.ClassId,
		SA.DivisionId,
		SA.ClassName,
		SA.DivisionName,
		SA.ClassName+' - '+SA.DivisionName AS ClassDivision,
		FS.Id AS FeeSetupId,		
		ISNULL(FS.IsVariable,0)AS IsVariable,
		ISNULL(FS.Amount,0)AS Amount,
		ISNULL(FS.StartDate,'1900-01-01')AS StartDate,
		ISNULL(FS.EndDate,'1900-01-01')AS EndDate,
		ISNULL(FA.VariableAmount,0.00)AS FAAmount,
		ISNULL(FA.DiscountAmount,0.00)AS DiscountAmount,
		ISNULL(FA.AdditionalAmount,0.00)AS AdditionalAmount,
		ISNULL(R.PaidAmount,0) AS PaidAmount,
		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 PendingAmount,
		ISNULL(FA.Remark,'') AS Remark,
		FS.ReceiptBookId,
		FS.FeeName,
		FS.FeeCode,
		SA.OrgId,
		O.Title AS OrgName,
		O.OrderIndex AS OrgOrderIndex,
		ISNULL(RBM.Title,'') AS ReceiptBookTitle,
		ISNULL(RBM.OrderIndex,0) AS ReceiptOrderIndex,
		SA.BatchId,
		BM.Title AS BatchName,
		'',
		'',
		'',
		ISNULL(SA.SUID,'') AS SUID,
		SA.ClassOrderIndex,
		SA.DivisionOrder,
		FS.OrderIndex
  FROM 
		sStudent.vStudentAcademic SA
		INNER JOIN 
		(
			SELECT 
				FS1.FeeId,
				FS1.Id,
				ISNULL(FS1.IsOptional,0)AS IsOptional,
				ISNULL(FS1.IsVariable,0)AS IsVariable,
				ISNULL(FS1.Amount,0)AS Amount,
				ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
				ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
				FS1.BatchId,
				ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
				SA1.AcademicId,
				FM.Title AS FeeName,
				FM.Code AS FeeCode,
				FM.OrderIndex
			FROM 
				sFee.tFeeSetup FS1
				INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId 
				AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId				
				INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
			WHERE 
			    ((SA1.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
				AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND (FS1.IsOptional=0)
				AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND SA1.StatusId = @rStatusId
				
			UNION ALL
				
			SELECT 
				FS1.FeeId,
				FS1.Id,
				ISNULL(FS1.IsOptional,0)AS IsOptional,
				ISNULL(FS1.IsVariable,0)AS IsVariable,
				ISNULL(FS1.Amount,0)AS Amount,
				ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
				ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
				FS1.BatchId,
				ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
				SA1.AcademicId,
				FM.Title AS FeeName,
				FM.Code AS FeeCode,
				FM.OrderIndex
			FROM 
				sFee.tFeeSetup FS1
				INNER JOIN sFee.tFeeOptional FO ON FO.FeeSetupId=FS1.Id
				INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
				INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=FO.SourceId AND SA1.BatchId = FS1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
			WHERE
		        ((SA1.OrgGroupBatchId = @rOrgGroupBatchId)  OR (@rOrgGroupBatchId=0))
				AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND (FS1.IsOptional=1)
				AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND SA1.StatusId = @rStatusId
				
		) FS ON FS.AcademicId=SA.AcademicId
		LEFT JOIN sFee.tFeeAllocation FA ON FA.FeeSetupId=FS.Id AND FA.SourceId=SA.AcademicId
		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				
			WHERE		
				(R.SourceTypeId = 2001)
				AND ((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND (R.IsObsolete = 0) 
				AND ((SA1.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
				AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
				AND SA1.StatusId = @rStatusId
				GROUP BY FeeSetupId,R.SourceId
		) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
		 INNER JOIN sSetup.tOrganizationMaster O ON SA.OrgId = O.Id
		 INNER JOIN sFee.tReceiptBookMaster RBM ON FS.ReceiptBookId=RBM.Id
		 INNER JOIN sSetup.tBatchMaster BM ON BM.Id=SA.BatchId	
		 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 
		AND ((SA.OrgGroupBatchId = RT.OrgGroupBatchId))
		AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) 
	WHERE	
			((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
			AND ((SA.BatchId=@rBatchId) OR (@rBatchId=0)) 
			AND (ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00) -ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00) != 0)			
			AND SA.	StatusId = @rStatusId
			
			ORDER BY SA.RollNo
	 
			SELECT
				Temp.OrgId,			 
				Temp.ReceiptBookId,
				Temp.AcademicId,
				Temp.DivisionId,
				ClassDivision,
				Temp.RollNo, 
				Name,
				Temp.Code,
				ReceiptBookTitle,
				OrgName,
				SUM(PendingAmount) AS PendingAmount, 
				[sFee].[fPendingFeeNamesGet](Temp.AcademicId,Temp.ReceiptBookId,	@p) AS PendingFeeName,
				ReceiptOrderIndex,
				Temp.BatchId,
				BatchName,
				'' AS SUId,
				SA.LeftDate,
				Temp.ClassOrderIndex,
				Temp.DivisionOrderIndex
			FROM @p Temp
				INNER JOIN sStudent.tAcademic A ON A.Id =  Temp.AcademicId
				INNER JOIN sStudent.tStudentMaster SM ON SM.Id = A.StudentId AND SM.StatusId = @rStatusId
				INNER JOIN sStudent.tStudentAdmission SA ON SA.StudentId = A.StudentId
			WHERE 
			    ( (@rStatusId = 3 AND ((SA.LeftDate >= @rFromLeftDate) OR (ISNULL(@rFromLeftDate,'') = ''))
				  AND ((SA.LeftDate <= @rToLeftDate) OR (ISNULL(@rToLeftDate,'') = '')) )
				OR (@rStatusId = 2 AND ((SA.InActiveDate >= @rFromLeftDate) OR (ISNULL(@rFromLeftDate,'') = ''))
				  AND ((SA.InActiveDate <= @rToLeftDate) OR (ISNULL(@rToLeftDate,'') = '')) )
				)
				AND SM.StatusId = @rStatusId
				GROUP BY 
				Temp.OrgId,Temp.AcademicId,Temp.ReceiptBookId,Temp.DivisionId,Temp.BatchId,
				ClassDivision,Temp.RollNo, Name,Temp.Code,ReceiptBookTitle,
				OrgName,ReceiptOrderIndex,BatchName,SA.LeftDate,Temp.ClassOrderIndex,
				Temp.DivisionOrderIndex
				ORDER BY Temp.AcademicId
END
GO
PRINT N'Altering [sFrontOffice].[pVisitorLogGet]...';


GO
ALTER PROCEDURE [sFrontOffice].[pVisitorLogGet]
          
           @rVisitorId int=0,
           --@rOutTimeFrom datetime,
           --@rOutTimeTo datetime,
           @rFromVisitDate datetime,
           @rToVisitDate datetime,
           @rOrgId int=0,
           @rWhomToMeetName nvarchar(100)='',
           @rIsPrintView bit=0,
           @rOrgGroupId int=0,
           @rTypeId int=0 ,
		   @rStatusId int=0 
           --@rIsWildCardSearch bit
          
AS
SET NOCOUNT ON

		--IF @rIsWildCardSearch = 1
		--BEGIN
			SET @rWhomToMeetName = sCommon.fSearchStringGet(@rWhomToMeetName)
		--END
		Declare @GatePassConfig nvarchar(20)=''
		SELECT @GatePassConfig =ItemValue From sConfig.tConfigurationSetup WHERE ConfigurationId = 241 AND SourceId = @rOrgGroupId


BEGIN
SELECT  
	   VL.Id As VisitorId,
       VL.VisitorName,
       VL.NoOfVisitor,
       VL.PurposeOfVisit,
       VL.WhomToMeet AS WhomToMeetId,
	   (isnull(case when isnull(VL.WhomToMeet,0)!=0 then isnull(EM.EmployeeName,'') else ISNULL(VL.WhomToMeetName,'') end,'' )
	   --+ (case when isnull(VL.StudentId,0)!=0 AND isnull(VL.WhomToMeet,0)!=0 then ',' else '' end)
	   --+isnull(case when  isnull(VL.StudentId,0)!=0 Then sStudent.fStudentNameGet(STM.FirstName, STM.MiddleName,STM.LastName, OM1.StudentNameFormatId) end,'')
	   ) AS WhomToMeetName,
	   ISNULL(VL.InTime,'00:00') AS InTime,
       ISNULL(VL.OutTime,'00:00') AS OutTime,
       ISNULL(VL.VisitDate,'1900-01-01 00:00:00') AS VisitDate,
       --VL.CreatedDateTime ,
       (CASE  WHEN @rIsPrintView=1 THEN 
				VL.VisitorPhoto		
			ELSE ISNULL(VL.VisitorPhoto, CONVERT(VARBINARY(MAX), 0)) END) AS VisitorPhoto,
       --ISNULL(VL.VisitorPhoto, CONVERT(VARBINARY(MAX), 0)) AS VisitorPhoto,
       VL.OrgId,
       ISNULL(OM.DisplayTitle,'') AS Organization,
       ISNULL(Remark,'') AS Remark,
       @GatePassConfig AS ConfigValue,
	   ISNUll(VisitorContactNumber,'') AS VisitorContactNumber,
	   ISNULL(STM.Id,0) AS StudentId,
	   (CASE WHEN ISNULL(VL.TypeId,'')!='' then case when VL.TypeId=1 then 'Visitor' else 'Parents' end
			 when ISNULL(VL.StudentId,0)=0 THEN 'Visitor'
			 ELSE 'Parents' END) AS VisitorType,
	   (CASE WHEN ISNULL(VL.OutTime,'00:00:00')='00:00:00' THEN 0
			 ELSE 1 END) AS InOutStatus,
		OM.OrgGroupId AS OrgGroupId,
		SM.Title as Status,
		ISNULL(VL.StatusId,0) as StatusId,
		(CASE WHEN ISNULL(VL.TypeId,'')!='' then case when VL.TypeId=1 then 1 else 2 end
			 when ISNULL(VL.StudentId,0)=0 THEN 1
			 ELSE 2 END) AS VisitorTypeId,
		ISNULL(STM.Code,'') AS StudentCode,
		ISNULL(STM.FirstName,'') +' '+ ISNULL(STM.LastName,'') AS  StudentName,
		 (select ISNULL(CM.Title,'') from sSetup.tClassMaster CM Inner join sStudent.tAcademic A ON A.ClassId=CM.Id AND A.StudentId=STM.Id INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId AND BM.IsActive=1 GROUP BY CM.Title) AS StudentClass
		,(select ISNULL(DM.Title,'') from sSetup.tDivisionMaster DM Inner join sStudent.tAcademic A ON A.DivisionId=DM.Id AND A.StudentId=STM.Id INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId AND BM.IsActive=1 GROUP BY DM.Title) AS StudentDivision
		--ISNULL(CM.Title,'') AS StudentClass,
		--ISNULL(DM.Title,'') AS StudentDivision
		 		
  FROM  sFrontOffice.tVisitorLog VL 
  INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=VL.OrgId
  LEFT JOIN sCommon.tStatusMaster SM ON SM.Id = VL.StatusId
  LEFT JOIN sHrm.vExtEmployeeMaster EM ON EM.EmployeeId=VL.WhomToMeet
  LEFT JOIN sStudent.tStudentMaster STM On STM.Id=VL.StudentId  
  --LEFT JOIN sStudent.tAcademic A ON A.StudentId = STM.Id
  --LEFT JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId AND BM.IsActive=1
  --LEFT JOIN sSetup.tClassMaster CM ON CM.Id = A.ClassId
  --LEFT JOIN sSetup.tDivisionMaster DM ON DM.Id = A.DivisionId
  LEFT JOIN sSetup.tOrganizationMaster AS OM1 ON STM.OrgId = OM1.Id 
 
  WHERE 
	(VL.OrgId=@rOrgId OR @rOrgId=0) AND OM.OrgGroupId=@rOrgGroupId
	AND (VL.Id=@rVisitorId OR @rVisitorId=0)
	AND (((VL.WhomToMeetName LIKE @rWhomToMeetName) OR  (isnull(EM.EmployeeId,0)>0 AND EM.EmployeeName Like  @rWhomToMeetName) OR (isnull(STM.Id,0)>0 AND sStudent.fStudentNameGet(STM.FirstName, STM.MiddleName,STM.LastName, OM1.StudentNameFormatId) like  @rWhomToMeetName)) OR (ISNULL(@rWhomToMeetName,'')=''))
	AND (VL.VisitDate>=@rFromVisitDate OR ISNULL(@rFromVisitDate,'')='')
	AND (VL.VisitDate<=@rToVisitDate OR ISNULL(@rToVisitDate,'')='')
	AND ((ISNULL(VL.TypeId,0)=0 AND (ISNULL(VL.StudentId,1) = @rTypeId) OR  (@rTypeId=0) OR (((VL.StudentId > 0 AND @rTypeId=2) OR  @rTypeId=0)))  OR (ISNULL(VL.TypeId,0)!=0 AND ((VL.TypeId=@rTypeId) or (@rTypeId=0)))) -- Visitor 
	AND ((VL.StatusId = @rStatusId) OR (ISNULL(@rStatusId,0) = 0)) 
	--AND BM.IsActive=1
	 -- Parents
  ORDER BY VL.VisitDate DESC,VL.InTime DESC
END
GO
PRINT N'Altering [sHostel].[pAttendanceRegisterAdd]...';


GO
ALTER PROCEDURE [sHostel].[pAttendanceRegisterAdd]
	
	@rStrXml nvarchar(MAX),
    @rAttendanceDate date='',
    @rCreatedUserId bigint,
    @rRoomId int=0 ,
    @rHostelId int,
    @rHostelAttendanceTypeId int,
    @rOrgGroupBatchId int,
	@rBuildingId int = 0
		
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
--SET @rStrXml=REPLACE(@rStrXml,'&','AND')
DECLARE @loDoc INT
EXEC sp_xml_preparedocument @loDoc OUTPUT, @rStrXml
BEGIN
	BEGIN TRY
	
	 BEGIN TRANSACTION 
	 BEGIN
	 
	 DELETE AR FROM sHostel.tAttendanceRegister AR 
	 INNER JOIN sHostel.tAssignRoom ASR ON ASR.SourceId = AR.StudentId AND ASR.SourceTypeId=2003   
	 INNER JOIN sHostel.tRoomMaster RM ON RM.Id = ASR.RoomId
	    WHERE 
	    AR.AttendanceDate = @rAttendanceDate
	    AND  (ASR.RoomId=@rRoomId OR @rRoomId=0)
	    AND AR.HostelId = @rHostelId
	    AND AR.HostelAttendanceTypeId=@rHostelAttendanceTypeId
	    AND AR.OrgGroupBatchId=@rOrgGroupBatchId
		AND (RM.BuildingId = @rBuildingId OR @rBuildingId=0)
	 INSERT INTO sHostel.tAttendanceRegister
		(
			HostelId,
			StudentId,
			AttendanceDate,
			IsPresent,
			AbsentReasonId,
			CreatedUserId,
			CreatedDateTime,
			HostelAttendanceTypeId,
			OrgGroupBatchId
			)
		SELECT	
			@rHostelId,
			StudentId,
			@rAttendanceDate,
			IsPresent,
			ISNULL(AbsentReasonId,0),
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rHostelAttendanceTypeId,
			@rOrgGroupBatchId
						
		FROM OPENXML (@loDoc, '/Table/AttendanceRegister', 1)
		WITH ( 
				StudentId bigint,
				IsPresent bit,
				AbsentReasonId int,
				HostelAttendanceTypeId int
			  )  
        SELECT 1 AS Result
	 END	
	
		COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Altering [sHostel].[pAttendanceRegisterDelete]...';


GO

ALTER PROCEDURE [sHostel].[pAttendanceRegisterDelete]
	 
	@rAttendanceDate date,
	@rRoomId int=0 ,
    @rHostelId int,
    @rHostelAttendanceTypeId int,
    @rOrgGroupBatchId int,
	@rBuildingId int = 0
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
BEGIN TRY
	 BEGIN TRANSACTION	
DELETE AR
FROM sHostel.tAttendanceRegister AR
 INNER JOIN sHostel.tAssignRoom ASR ON ASR.SourceId = AR.StudentId AND ASR.SourceTypeId=2003  
  INNER JOIN sHostel.tRoomMaster RM ON RM.Id = ASR.RoomId
 WHERE 
	    AR.AttendanceDate = @rAttendanceDate
	    AND  (ASR.RoomId=@rRoomId OR @rRoomId=0)
	    AND AR.HostelId = @rHostelId
	    AND AR.HostelAttendanceTypeId=@rHostelAttendanceTypeId
	    AND AR.OrgGroupBatchId=@rOrgGroupBatchId
	    AND (RM.BuildingId = @rBuildingId OR @rBuildingId = 0)
 SELECT 1 AS Result
	COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH			
END
GO
PRINT N'Altering [sHostel].[pAttendanceRegisterGet]...';


GO

 
 
ALTER PROCEDURE [sHostel].[pAttendanceRegisterGet]
	 	 
	 	 @rRoomId int,
		 @rAttendanceDate date,
		 @rHostelId int,
		 @rHostelAttendanceTypeId int,
		 @rOrgGroupBatchId int,
		 @rBuildingId int = 0

	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	IF EXISTS(SELECT 1 FROM sHostel.tAttendanceRegister ATR INNER JOIN sHostel.tAssignRoom AR ON AR.SourceId = ATR.StudentId AND AR.SourceTypeId=2003
	            INNER JOIN sHostel.tRoomMaster RM ON RM.Id = AR.RoomId
				WHERE ATR.AttendanceDate=@rAttendanceDate AND ATR.OrgGroupBatchId=@rOrgGroupBatchId AND ATR.HostelAttendanceTypeId=@rHostelAttendanceTypeId
				 AND AR.RoomId = @rRoomId AND RM.BuildingId = @rBuildingId )
	BEGIN
		SELECT 
			AR.SourceId AS StudentId,
			VA.Code,
			VA.Name,
			VA.SUId,
			ISNULL(ATR.IsPresent,'true') as IsPresent,
			ISNULL(ATR.AbsentReasonId,0) as AbsentReasonId,
			CASE WHEN ATR.CreatedUserId IS NULL THEN 'false' ELSE 'true' END AS IsDeleted,
			(SI.StudentPhoto) AS StudentPhoto,
			ISNULL(ATR.HostelAttendanceTypeId,0) AS HostelAttendanceTypeId
			
  FROM 
           sStudent.vStudentAcademic VA 
            INNER JOIN sHostel.tAssignRoom AR ON VA.StudentId = AR.SourceId AND AR.SourceTypeId=2003
            LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId=VA.StudentId
            INNER JOIN sHostel.tRoomMaster RM ON RM.Id = AR.RoomId
            INNER JOIN sHostel.tAttendanceRegister ATR ON ATR.StudentId=VA.StudentId 			
			AND (ATR.AttendanceDate=@rAttendanceDate) AND (ATR.OrgGroupBatchId=@rOrgGroupBatchId)
			AND isnull(ATR.HostelAttendanceTypeId,0)=@rHostelAttendanceTypeId
								  
  WHERE 
      RM.HostelId = @rHostelId
	  AND ((AR.RoomId=@rRoomId) OR (@rRoomId=0))
	   AND VA.OrgGroupBatchId=@rOrgGroupBatchId
	   AND AR.OrgGroupBatchId=@rOrgGroupBatchId
	   AND ((RM.BuildingId = @rBuildingId) OR (@rBuildingId=0))
  ORDER BY VA.Code
	END
	ELSE
		BEGIN
		SELECT 
				AR.SourceId AS StudentId,
				VA.Code,
				VA.Name,
				VA.SUId,
				ISNULL(ATR.IsPresent,'true') as IsPresent,
				ISNULL(ATR.AbsentReasonId,0) as AbsentReasonId,
				CASE WHEN ATR.CreatedUserId IS NULL THEN 'false' ELSE 'true' END AS IsDeleted,
				(SI.StudentPhoto) AS StudentPhoto,
				ISNULL(ATR.HostelAttendanceTypeId,0) AS HostelAttendanceTypeId
			
	  FROM 
			   sStudent.vStudentAcademic VA 
				INNER JOIN sHostel.tAssignRoom AR ON VA.StudentId = AR.SourceId AND AR.SourceTypeId=2003
				LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId=VA.StudentId
				INNER JOIN sHostel.tRoomMaster RM ON RM.Id = AR.RoomId
				LEFT JOIN sHostel.tAttendanceRegister ATR ON ATR.StudentId=VA.StudentId 			
				AND (ATR.AttendanceDate=@rAttendanceDate) AND (ATR.OrgGroupBatchId=@rOrgGroupBatchId)
				AND isnull(ATR.HostelAttendanceTypeId,0)=@rHostelAttendanceTypeId			
			
		  
	  WHERE 
		  RM.HostelId = @rHostelId
		  AND ((AR.RoomId=@rRoomId) OR (@rRoomId=0))
		   AND VA.OrgGroupBatchId=@rOrgGroupBatchId
		   AND AR.OrgGroupBatchId=@rOrgGroupBatchId
		   AND ((RM.BuildingId = @rBuildingId) OR (@rBuildingId=0))
	  ORDER BY VA.Code
	  END

	 --Select * from sHostel.tAttendanceRegister where Hostelattendancetypeid = 991100003 AND Attendancedate = '2022-12-28 00:00:00'
GO
PRINT N'Altering [sHostel].[pHostelGetPassReasonMasterAdd]...';


GO
ALTER PROCEDURE [sHostel].[pHostelGetPassReasonMasterAdd]
	 @rHostelId int,	
	 @rId int, 
	 @rCode nvarchar(20), 
	 @rTitle nvarchar(100), 
	 @rIsObsolete bit, 
	 @rCreatedUserId bigint, 
	 @rUpdatedUserId bigint ,
	  @rOrgGroupId int      	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	IF(@rId = 0)	
	BEGIN
		If Exists(select Id from sHostel.tHostelGatePassReasonMaster where Code=@rCode AND OrgGroupId=@rOrgGroupId AND HostelId = @rHostelId)
			BEGIN
			select -102 as Result
			RETURN
		END 
	
		If Exists(select Id from sHostel.tHostelGatePassReasonMaster where Title=@rTitle AND OrgGroupId=@rOrgGroupId AND HostelId = @rHostelId)
			BEGIN
			select -103 as Result
			RETURN
		END 
	END
	ELSE
	BEGIN
		If Exists(select Id from sHostel.tHostelGatePassReasonMaster where Code=@rCode AND OrgGroupId=@rOrgGroupId AND HostelId = @rHostelId AND Id<>@rId)
		Begin
			select -102 as Result
			RETURN
		End
		If  Exists(select Id from sHostel.tHostelGatePassReasonMaster where Title=@rTitle  AND OrgGroupId=@rOrgGroupId AND HostelId = @rHostelId AND Id<>@rId)
		Begin
			select -103 as Result
			RETURN
		End

	END
	
	 BEGIN TRANSACTION	
	 DECLARE @lNextNumber BIGINT 

	IF(@rId = 0)	
	BEGIN
		
	EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sHostel.tHostelGatePassReasonMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	INSERT INTO sHostel.tHostelGatePassReasonMaster
		(
			HostelId,
			 OrgGroupId,
			 Id,
			 Code,
			 Title,
			 IsObsolete,
			 CreatedUserId,
			 CreatedDateTime,
			 UpdatedUserId, 
			 UpdatedDateTime

		)
	VALUES
		(
			@rHostelId,
			 @rOrgGroupId ,
			 @lNextNumber, 
			 @rCode , 
			 @rTitle , 
			 @rIsObsolete , 
			 @rCreatedUserId , 
			 sCommon.fGetDate(),
			 @rUpdatedUserId  ,			  
			 sCommon.fGetDate()
		)
		    SELECT 1 AS Result
	END	 

ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE  sHostel.tHostelGatePassReasonMaster
	    SET
			Title=@rTitle,
			Code=@rCode,
			IsObsolete=@rIsObsolete,			
			UpdatedUserId=@rCreatedUserId,
			UpdatedDateTime=sCommon.fGetDate()
	      
	      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 [sHrm].[pEmployeeDocumentSubmitGet]...';


GO
ALTER PROCEDURE [sHrm].[pEmployeeDocumentSubmitGet]
	 
        @rEmployeeId bigint,
		@rOrgId int
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
 
	BEGIN
			SELECT Isnull(D.Id,0) AS DocumentId,ISNULL(D.DocumentName,'') AS DocumentName,
			CASE WHEN  S.SubmitDocumentMasterId Is null THEN 'False' ELSE 'True'END AS IsCheck
			,ISNULL(S.DocumentName,'') As FileName
		 	FROM sCommon.tSubmitDocumentMaster D
			LEFT Join [sHrm].[tEmployeeDocument]  S ON S.SubmitDocumentMasterId=D.id AND S.EmployeeId=@rEmployeeId
			WHERE OrgId=@rOrgId AND SubmitDocumentFunctionalityId='2'
END
GO
PRINT N'Altering [sHrm].[pRptEmpLeavePresence]...';


GO
 
ALTER PROCEDURE [sHrm].[pRptEmpLeavePresence]
	 
		@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,
		@rIsDetail bit=0,
		@rEmployeeStatusId int=0,
		@rFromDate date = null,
	    @rToDate date=null
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
       SELECT 	
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2, 
			@rIsDetail AS IsDetail,
			EM.Code AS EmployeeCode,
			EM.EmployeeName,   
			EM.EmployeeId,
			EM.DepartmentName,
			EM.EmployeeGrade,      
			ISNULL(LB.BalanceLeave,0) AS BalanceLeave,
			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,
			LTM.Id AS LeaveTypeId,	
			LTM.Title AS LeaveType,
			(
				SELECT ISNULL(SUM(L.NoOfLeave),0)				 
				FROM 
					sHrm.tLeave L
					INNER JOIN sHrm.tLeaveTypeMaster LTM1 ON L.LeaveTypeId = LTM1.Id 
					AND IsLWP = 0 AND StatusId=550
				WHERE 
					L.BatchId=@rBatchId AND L.OrgId = @rOrgId 
					AND EM.EmployeeId = L.EmployeeId AND LTM.Id = L.LeaveTypeId
					AND (YEAR(L.FromDate) = @rForYear OR @rForYear=0) 
					AND (MONTH(L.FromDate) = @rForMonth OR @rForMonth=0) 
					AND ((L.FromDate>=@rFromDate) OR (ISNULL(@rFromDate,'')=''))
    				AND ((L.ToDate<=@rToDate) OR (ISNULL(@rToDate,'')=''))
		   	) AS NoOfLeave,
	   		(
			SELECT ISNULL(SUM(L.NoOfLeave),0)				 
			FROM 
				sHrm.tLeave L
				INNER JOIN sHrm.tLeaveTypeMaster LTM1 ON L.LeaveTypeId = LTM1.Id 
				AND IsLWP = 1 AND StatusId=550
			WHERE 
				L.BatchId=@rBatchId AND L.OrgId = @rOrgId 
				AND EM.EmployeeId = L.EmployeeId AND LTM.Id = L.LeaveTypeId
				AND (YEAR(L.FromDate) = @rForYear OR @rForYear=0) 
				AND (MONTH(L.FromDate) = @rForMonth OR @rForMonth=0) 
				AND ((L.FromDate>=@rFromDate) OR (ISNULL(@rFromDate,'')=''))
    	        AND ((L.ToDate<=@rToDate) OR (ISNULL(@rToDate,'')=''))
	   	    ) AS LWPNoOfLeave,
		   	ISNULL(LTM.IsLWP,0) AS IsLWP,
		   	(
				SELECT ISNULL(SUM(L.NoOfLeave),0)				 
				FROM 
					sHrm.tLeave L
					INNER JOIN sHrm.tLeaveTypeMaster LTM1 ON L.LeaveTypeId = LTM1.Id 
					AND IsLWP = 0 AND StatusId=550
				WHERE 
					L.BatchId=@rBatchId AND L.OrgId = @rOrgId 
					AND EM.EmployeeId = L.EmployeeId AND LTM.Id = L.LeaveTypeId
					AND (YEAR(L.FromDate) = @rForYear OR @rForYear=0) 
					AND (MONTH(L.FromDate) < @rForMonth OR @rForMonth=0) 
					AND ((L.FromDate>=@rFromDate) OR (ISNULL(@rFromDate,'')=''))
    				AND ((L.ToDate<=@rToDate) OR (ISNULL(@rToDate,'')=''))
		   	) AS UptoNoOfLeave,
		   	(
				SELECT ISNULL(SUM(L.NoOfLeave),0)				 
				FROM 
					sHrm.tLeave L
					INNER JOIN sHrm.tLeaveTypeMaster LTM1 ON L.LeaveTypeId = LTM1.Id 
					AND IsLWP = 1 AND StatusId=550
				WHERE 
					L.BatchId=@rBatchId AND L.OrgId = @rOrgId 
					AND EM.EmployeeId = L.EmployeeId AND LTM.Id = L.LeaveTypeId
					AND (YEAR(L.FromDate) = @rForYear OR @rForYear=0) 
					AND (MONTH(L.FromDate) < @rForMonth OR @rForMonth=0) 
					AND ((L.FromDate>=@rFromDate) OR (ISNULL(@rFromDate,'')=''))
    				AND ((L.ToDate<=@rToDate) OR (ISNULL(@rToDate,'')=''))
		   	) AS LWPUptoNoOfLeave,
		   	(
				SELECT ISNULL(SUM(L.NoOfLeave),0)				 
				FROM 
					sHrm.tLeave L
					INNER JOIN sHrm.tLeaveTypeMaster LTM1 ON L.LeaveTypeId = LTM1.Id 
					AND IsLWP = 0 AND StatusId=550
				WHERE 
					L.BatchId=@rBatchId AND L.OrgId = @rOrgId 
					AND EM.EmployeeId = L.EmployeeId AND LTM.Id = L.LeaveTypeId
					AND (YEAR(L.FromDate) = @rForYear OR @rForYear=0) 
					AND (MONTH(L.FromDate) = @rForMonth OR @rForMonth=0) 
					AND ((L.FromDate>=@rFromDate) OR (ISNULL(@rFromDate,'')=''))
    				AND ((L.ToDate<=@rToDate) OR (ISNULL(@rToDate,'')=''))
		   	) AS CurrentNoOfLeave,
		   	(
				SELECT ISNULL(SUM(L.NoOfLeave),0)				 
				FROM 
					sHrm.tLeave L
					INNER JOIN sHrm.tLeaveTypeMaster LTM1 ON L.LeaveTypeId = LTM1.Id 
					AND IsLWP = 1 AND StatusId=550
				WHERE 
					L.BatchId=@rBatchId AND L.OrgId = @rOrgId 
					AND EM.EmployeeId = L.EmployeeId AND LTM.Id = L.LeaveTypeId
					AND (YEAR(L.FromDate) = @rForYear OR @rForYear=0) 
					AND (MONTH(L.FromDate) = @rForMonth OR @rForMonth=0)
					AND ((L.FromDate>=@rFromDate) OR (ISNULL(@rFromDate,'')=''))
    				AND ((L.ToDate<=@rToDate) OR (ISNULL(@rToDate,'')='')) 
		   	) AS LWPCurrentNoOfLeave,
			EM.Number
        FROM
			sHrm.vEmployeeCommonDetail EM
			INNER JOIN sHrm.tLeaveTypeMaster LTM ON LTM.OrgId=EM.OrgId AND LTM.IsObsolete = 0
			LEFT JOIN sHrm.tLeaveBalance LB ON LB.EmployeeId=EM.EmployeeId AND LTM.Id = LB.LeaveTypeId AND LB.BatchId=@rBatchId
			inner JOIN sHrm.tEmployeeGradeMaster EGM ON EGM.OrgId=EM.OrgID AND EM.EmployeeGradeId = EGM.Id 
			LEFT JOIN sHrm.tWorkingDays WD ON WD.EmployeeGradeId = EGM.Id AND
			WD.ForYear = @rForYear AND WD.forMonth = @rForMonth
			LEFT JOIN sHrm.tEmployeeAttendance AT ON AT.EmployeeId=EM.EmployeeId
			AND AT.ForYear = @rForYear AND AT.forMonth = @rForMonth
			
			
    	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=@rEmployeeStatusId) OR (@rEmployeeStatusId=0))
			AND EM.IsOtherUser = 0
    		ORDER BY EM.Code
    		
END
GO
PRINT N'Altering [sHrm].[pRptEmployeeProfileGet]...';


GO
ALTER PROCEDURE [sHrm].[pRptEmployeeProfileGet]
(

		@rBuilder1 nvarchar(max)='',
		@rBuilder2 nvarchar(max)='',
		@rPayrollId int,
		@rPayrollGroupId int,
		@rPayrollYearId int,
    	@rEmployeeId bigint,
		@rEmployeeCode nvarchar(200),
		@rEmployeeName nvarchar(200),
	    @rOrderByField nvarchar(20)='',
		@rOrgId int = 0,
		@rDepartmentId int = 0,
		@rStatusId int = 0,
	 @rEmployeeGroupId int = 0
)
AS
SET NOCOUNT ON

BEGIN

	--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,
				EM.EmployeeId AS EmployeeId,
				tEM.FirstName +' '+tEM.MiddleName+' '+ tEM.LastName AS Name,
				DM.Id AS DepartmentId,
				DM.Title AS DepartmentName,
				CONVERT(date,EJD.DateOfJoining) AS DateOfJoining,
				EM.Code AS Code,
				CONVERT(date,EJD.DateOfleaving) AS DateOfleaving,
				EDM.Title AS Designation,
				EPD.Qualification,
				EM.GenderTitle,
				CONVERT(date,EPD.DateOfBirth) AS DateOfBirth,
				EPD.UIDNumber,
				EC.PersonalEmail AS Email,
				ESO.BankName,
				ESO.AccountNumber,
				ESO.EPFNumber,
				ESO.PanNumber,
				EC.MobileNumber,
				ISNULL(DATEDIFF(YY,EJD.DateOfJoining,EJD.DateOfleaving),'')AS EXPYEAR,
				ISNULL(DATEDIFF(MM,EJD.DateOfJoining,EJD.DateOfleaving),'') AS EXPMONTH,
				EM.FirstName,
				EM.LastName,
				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.BasicPay,0)AS BasicPay
				--,PP.SalaryMonth
		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.tPayrollYearMaster PY ON PP.PayrollYearId = PY.Id
			INNER JOIN  sHrm.tEmployeeCommunications EC ON EC.EmployeeId=EM.EmployeeId
			INNER JOIN sHrm.tEmployeePersonalDetail EPD ON EPD.EmployeeId=EM.EmployeeId
			INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.EmployeeId
			INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id=EJD.OrganizationDepartmentId
			INNER JOIN sHrm.tEmployeeDesignationMaster EDM ON EDM.Id=EJD.EmployeeDesignationId
			INNER JOIN sHrm.tEmployeeStatutoryAndOther ESO ON ESO.EmployeeId=PPE.EmployeeId	
			--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((PY.PayrollId=@rPayrollId) OR (@rPayrollId=0))
			 AND (PPE.PayrollGroupId = @rPayrollGroupId OR @rPayrollGroupId = 0) 
			 AND ((EM.Code Like '%' +  @rEmployeeCode + '%' ) OR (@rEmployeeCode = ''))
			 AND ((EM.EmployeeName Like '%' + @rEmployeeName  + '%') OR (@rEmployeeName = ''))
			 AND (PP.PayrollYearId = @rPayrollYearId OR @rPayrollYearId = 0) 
			 AND ((tEM.OrgID = @rOrgId) OR (@rOrgId = 0))
			 AND (EM.DepartmentId = @rDepartmentId OR @rDepartmentId = 0)
			 AND ((tEM.StatusId = @rStatusId) OR (@rStatusId = 0))
			 AND ((EM.EmployeeGroupId = @rEmployeeGroupId) OR (@rEmployeeGroupId = 0))
		END
GO
PRINT N'Altering [sSecurity].[pAppPermissionGet]...';


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

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


GO
ALTER PROCEDURE [sSecurity].[pNewTaskAdd]
 
	@rOrgGroupId smallint
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	BEGIN TRANSACTION
	
	DECLARE @lItemValue nvarchar(20) = ''
	SELECT 
		@lItemValue = CASE WHEN CS.Id IS NOT NULL THEN ISNULL(CS.ItemValue,'') ELSE ISNULL(CM.ItemValue,'') END 
	FROM 
		sConfig.tConfigurationMaster CM
		LEFT JOIN sConfig.tConfigurationSetup CS ON CM.Id = CS.ConfigurationId
		AND SourceTypeId = 2010 AND SourceId = @rOrgGroupId WHERE CM.Id = 494
    
 
	 
	IF EXISTS (SELECT 1 FROM sSystem.tDatabaseInfo WHERE ISNULL(HostedAS,'') <> 'Portal' AND Id = 1)
	 
	BEGIN
	DELETE OT FROM 
	sSecurity.tOrganizationTask OT
	INNER JOIN sSecurity.tTask T ON OT.TaskId = T.Id
	 WHERE OT.OrgGroupId=@rOrgGroupId AND T.IsClientSpecific = 0
			
	INSERT INTO sSecurity.tOrganizationTask 
	(
		OrgGroupId, TaskId, AvailablePermission
	)
	SELECT  @rOrgGroupId, 
			T.Id,
			T.AvailablePermission
	FROM
			sSecurity.tTask T INNER JOIN sSecurity.tModulePermission P
			ON T.ModuleId = P.ModuleId
	WHERE 
			P.OrgGroupId = @rOrgGroupId
			--AND T.AvailablePermission != 0
			AND T.IsObsolete = 0
			AND T.IsClientSpecific = 0
			
	END
	
	DELETE FROM sSecurity.tPermission WHERE OrgGroupId=@rOrgGroupId AND RoleId =sCommon.fGetIntIdForOrg(2,@rOrgGroupId) 
	
	IF(@lItemValue='True')
	BEGIN
		INSERT INTO 
		sSecurity.tPermission
		(
		TaskId, 
		RoleId, 
		Permission, 
		IsObsolete, 
		CreatedUserId, 
		CreatedDateTime, 
		UpdatedUserId, 
		UpdatedDateTime,
		OrgGroupId
		)
		SELECT  
		TaskId,
		sCommon.fGetIntIdForOrg(2,@rOrgGroupId),
		AvailablePermission,
		0,
		1,
		sCommon.fGetDate(),
		1,
		sCommon.fGetDate(),
		@rOrgGroupId
		FROM 
		sSecurity.tOrganizationTask 
		WHERE 
		OrgGroupId = @rOrgGroupId
	END
	ELSE
	BEGIN
		INSERT INTO 
		sSecurity.tPermission
		(
		TaskId, 
		RoleId, 
		Permission, 
		IsObsolete, 
		CreatedUserId, 
		CreatedDateTime, 
		UpdatedUserId, 
		UpdatedDateTime,
		OrgGroupId
		)
		SELECT  
		TaskId,
		sCommon.fGetIntIdForOrg(2,@rOrgGroupId),
		AvailablePermission,
		0,
		1,
		sCommon.fGetDate(),
		1,
		sCommon.fGetDate(),
		@rOrgGroupId
		FROM 
		sSecurity.tOrganizationTask OT
		INNER JOIN tSecurity.tTask T ON T.Id = OT.TaskId
		WHERE 
		OrgGroupId = @rOrgGroupId
		AND T.IsClientSpecific = 0
	END

	
		 
	
	
	--DELETE FROM sSecurity.tPermission WHERE OrgGroupId = @rOrgGroupId

	SELECT 1 AS RESULT
	COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	

END
GO
PRINT N'Altering [sSecurity].[pScreenGroupDataListGet]...';


GO

 
ALTER PROCEDURE [sSecurity].[pScreenGroupDataListGet]

	@rUserId [bigint]

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

DECLARE @lOrgGroupId bigint , @lConfigValue nvarchar(10) = ''

IF EXISTS (SELECT OM.OrgGroupId FROM sSecurity.tUser U INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = U.OrgId WHERE U.Id = @rUserId)
BEGIN
	SELECT @lOrgGroupId = OM.OrgGroupId FROM sSecurity.tUser U INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = U.OrgId WHERE U.Id = @rUserId
		
	SELECT @lConfigValue = ISNULL(CS.ItemValue,'False') FROM sConfig.tConfigurationMaster CM LEFT JOIN sConfig.tConfigurationSetup CS ON CM.Id=CS.Configurationid AND CS.SourceId= @lOrgGroupId AND CS.SourceTypeId=2010 WHERE CM.Id = 327

		IF(@lConfigValue = 'True')
		BEGIN
		     IF EXISTS (SELECT 1 FROM sSecurity.tPermissionUser WHERE UserId=@rUserId AND OrgGroupId=@lOrgGroupId)
				BEGIN
					SELECT S.Id AS Id,LEFT(S.Title,32) AS Title 
					From sSecurity.tScreen S 
					INNER JOIN sSecurity.tPermissionUser P ON P.TaskId=S.TaskId 
					INNER JOIN sSecurity.tTask T ON T.ID = p.TaskId 
					INNER JOIN sSecurity.tOrganizationTask OT ON T.Id = OT.TaskId AND OT.OrgGroupId = P.OrgGroupId 
					INNER JOIN sSecurity.tModulePermission MP ON MP.ModuleId=T.ModuleId AND MP.OrgGroupId=@lOrgGroupId
					WHERE (P.Permission & 2) =2 AND P.OrgGroupId = @lOrgGroupId AND T.IsObsolete = 0 AND P.UserId=@rUserId
					AND T.Id IN (20085,20086,30401,30222,20762,20091,20184,20183,20054,20621,20056,20199,
					30228,20693,20692,20241,20563,20561,30249,20622,143,9072,144,20249,20223,20270,20246,20001,20002,20003,20004,20007,20285,20323,20616,20055,
					139,20175,20176,141,142,20158, 30499,20309,20021,20312,20269,30299,10187,20716,20268,20968,20216,20215,20962,20080,31002,31005,31015,30580,31023,31033,31038,31043,31048,31175,31188)
				END
			ELSE
				BEGIN
					SELECT S.Id AS Id,LEFT(S.Title,32) AS Title 
					From sSecurity.tScreen S 
					INNER JOIN sSecurity.tPermission P ON P.TaskId=S.TaskId 
					INNER JOIN sSecurity.tUserRole U ON U.RoleId=P.RoleId 
					INNER JOIN sSecurity.tTask T ON T.ID = p.TaskId 
					INNER JOIN sSecurity.tOrganizationTask OT ON T.Id = OT.TaskId AND OT.OrgGroupId = P.OrgGroupId 
					WHERE (P.Permission & 2) =2 AND U.IsObsolete=0 AND T.IsObsolete = 0 AND U.UserId=@rUserId
					AND T.Id IN (20085,20086,30401,30222,20762,20091,20184,20183,20054,20621,20056,20199,
					30228,20693,20692,20241,20563,20561,30249,20622,143,9072,144,20249,20223,20270,20246,20001,20002,20003,20004,20007,20285,20323,20616,20055,
					139,20175,20176,141,142,20158, 30499,20309,20021,20312,20269,30299,10187,20716,20268,20968,20216,20215,20962,20080,31002,31005,31015,30580,310235,31033,31038,31043,31048,31175,31179,30331,31182,31188)
				END
		END
		ELSE
		BEGIN
			  IF EXISTS (SELECT 1 FROM sSecurity.tPermissionUser WHERE UserId=@rUserId AND OrgGroupId=@lOrgGroupId)
				BEGIN
					SELECT S.Id AS Id,LEFT(S.Title,32) AS Title 
					From sSecurity.tScreen S 
					INNER JOIN sSecurity.tPermissionUser P ON P.TaskId=S.TaskId 
					INNER JOIN sSecurity.tTask T ON T.ID = p.TaskId 
					INNER JOIN sSecurity.tOrganizationTask OT ON T.Id = OT.TaskId AND OT.OrgGroupId = P.OrgGroupId 
					INNER JOIN sSecurity.tModulePermission MP ON MP.ModuleId=T.ModuleId AND MP.OrgGroupId=@lOrgGroupId
					WHERE (P.Permission & 2) =2 AND P.OrgGroupId = @lOrgGroupId AND T.IsObsolete = 0 AND P.UserId=@rUserId
				END
			  ELSE
				BEGIN
					SELECT S.Id AS Id,LEFT(S.Title,32) AS Title 
					From sSecurity.tScreen S 
					INNER JOIN sSecurity.tPermission P ON P.TaskId=S.TaskId 
					INNER JOIN sSecurity.tUserRole U ON U.RoleId=P.RoleId 
					INNER JOIN sSecurity.tTask T ON T.ID = p.TaskId 
					INNER JOIN sSecurity.tOrganizationTask OT ON T.Id = OT.TaskId AND OT.OrgGroupId = P.OrgGroupId 
					WHERE (P.Permission & 2) =2 AND U.IsObsolete=0 AND T.IsObsolete = 0 AND U.UserId=@rUserId
				END
		END
END

END
GO
PRINT N'Altering [sStudent].[pRptStudentAttendanceSummaryGet]...';


GO

ALTER PROCEDURE [sStudent].[pRptStudentAttendanceSummaryGet]
	 
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 @rOrgId smallint,
	 @rBatchId int,
	 @rClassId int,
	 @rDivisionId int,
	 @rFromDate date='',
	 @rToDate date='',
	 @rDepartmentId int,
	 @rAttendanceTypeId int,
	 @rIsDetail bit= 0
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
CREATE TABLE #tmp
(
Builder1 nvarchar(max),
Builder2 nvarchar(max),
AcademicId bigint,
ClassId int,
DivisionId int,
DepartmentId int,
ClassName nvarchar(500),
DivisionName nvarchar(500),
IsPresent bit,
ClassOrderIndex int,
DivisionOrder int,
AttendanceDate Date,
RowNo int,
AttendanceType nvarchar(100),
AttendanceTypeId int,
GenderId int,
MonthTitle nvarchar(50),
MonthNumber int,
YearNumber int
)
INSERT INTO #tmp
SELECT 	@rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,
		SA.AcademicId,
		SA.ClassId,
		SA.DivisionId,
		SA.DepartmentId,
		SA.ClassName,
		SA.DivisionName,
		ISNULL(SR.IsPresent,0)AS IsPresent,
		SA.ClassOrderIndex,
		SA.DivisionOrder,
		SR.AttendanceDate,		
		--1 AS AttendanceDay,
		Row_Number() OVER(PARTITION BY SA.ClassId,SA.DivisionId,SR.AttendanceDate ORDER BY SR.AttendanceDate ASC) AS RowNo,
		ATM.Title AS AttendanceType,
		SR.AttendanceTypeId,
		SA.GenderId,
		DATENAME(MONTH,SR.AttendanceDate) AS MonthTitle,
		DATEPART(MONTH,SR.AttendanceDate) AS MonthNumber,
		DATENAME(YEAR,SR.AttendanceDate) AS YearNumber
	FROM 
            sStudent.vStudentAcademic SA 
            INNER JOIN sStudent.tStudentAdmission AD ON SA.StudentId = AD.StudentId
			LEFT JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=SA.AcademicId
			INNER JOIN sAttendance.tAttendanceTypeMaster ATM ON SR.AttendanceTypeId = ATM.Id
			AND (SR.AttendanceTypeId=@rAttendanceTypeId OR @rAttendanceTypeId = 0)
			AND ((SR.AttendanceDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
    		AND ((SR.AttendanceDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
			--INNER JOIN #tmpDates tmp ON tmp.AllDates = SR.AttendanceDate
		Where SA.OrgId = @rOrgId
			  AND SA.BatchId = @rBatchId
			  AND ((SA.ClassId = @rClassId) OR (@rClassId = 0))
			  AND ((SA.DivisionId = @rDivisionId) OR (@rDivisionId = 0))
			  AND ((SA.DepartmentId = @rDepartmentId) OR (@rDepartmentId = 0))
			
			  AND SA.StatusId = 1
			  AND (AD.LeftDate > SR.AttendanceDate OR ISNULL(AD.LeftDate,'')= '')
			  AND (AD.AdmissionDate <= SR.AttendanceDate)
			  Order By SA.ClassOrderIndex,SA.DivisionOrder,SR.AttendanceDate
			   
SELECT
Builder1,
Builder2,
@rIsDetail AS IsDetail,
AcademicId,
ClassId,
DivisionId,
DepartmentId,
ClassName,
DivisionName,
IsPresent,
ClassOrderIndex,
DivisionOrder,
AttendanceDate,
(CASE WHEN RowNo = 1 THEN 1 ELSE 0 END)AS AttendanceDay,
AttendanceType,
AttendanceTypeId,
GenderId,
MonthTitle,
MonthNumber,
YearNumber
FROM
#tmp

DROP TABLE #tmp

--Select
--'' AS Builder1,
--'' AS Builder2,
--0 AS IsDetail,
--0 AS AcademicId,
--0 AS ClassId,
--0 AS DivisionId,
--0 AS DepartmentId,
--'' AS ClassName,
--'' AS DivisionName,
--0 AS IsPresent,
--0 AS ClassOrderIndex,
--0 AS DivisionOrder,
--''AS AttendanceDate,
--0 AS AttendanceDay,
--'' AS AttendanceType,
--0 AS AttendanceTypeId,
--0 AS GenderId,
--'' AS MonthTitle,
--0 AS MonthNumber,
--0 AS YearNumber
END
GO
PRINT N'Altering [sTimetable].[pEmployeeTimeTableGet]...';


GO
 
ALTER PROCEDURE [sTimetable].[pEmployeeTimeTableGet]
	
	@rEmployeeId bigint,
	 @rBatchId int=0,
	 @rTimeTableSchemaId int
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 

	DECLARE @lTableList TABLE
(
   
    LectureNumber int,   
	Sunday varchar(Max) NULL,
    Monday varchar(Max) NULL,
    Tuesday varchar(Max) NULL,
    Wednesday varchar(Max) NULL,
    Thursday varchar(Max) NULL,
    Friday varchar(Max) NULL,
    Saturday varchar(Max) NULL,	
	SundayClassSubjectId varchar(Max) NULL,
    MondayClassSubjectId varchar(Max) NULL,
    TuesdayClassSubjectId varchar(Max) NULL,
    WednesdayClassSubjectId varchar(Max) NULL,
    ThursdayClassSubjectId varchar(Max) NULL,
    FridayClassSubjectId varchar(Max) NULL,
    SaturdayClassSubjectId varchar(Max) NULL    
)


DECLARE @HeaderCounterStart INT=1
DECLARE @HeaderMaxCounter INT=0

SET @HeaderMaxCounter  = (select max(NoOfPeriod) as MaxLectures  From [sTimetable].[tTimeSetup] where TimeTableSchemaId=@rTimeTableSchemaId and BatchId=@rBatchId)

  WHILE (@HeaderCounterStart <= @HeaderMaxCounter)
    BEGIN
        --DECLARE @HeaderTitle varchar(100)='';
        --SET @HeaderTitle=(SELECT FieldName from @lFieldList where Id=@HeaderCounterStart)  
        --IF(SUBSTRING(@HeaderTitle, len(@HeaderTitle) - 1, 2)='Id')
        --BEGIN
        --  SET @HeaderTitle=REPLACE(@HeaderTitle, SUBSTRING(@HeaderTitle, len(@HeaderTitle) - 1, 2), '') 
        --END     
        --SET @HeaderHtml=@HeaderHtml + ('<th>'+@HeaderTitle+'</th>') 
      
			--Declare @AssignSundayClassDivisionName varchar(100)
   --         SET @AssignSundayClassDivisionName=(SELECT VBCD.ClassDivisionName From  sTimetable.tTimeTable T INNER JOIN sSetup.vClassDivision VBCD ON VBCD.DivisionId=T.DivisionId  where EmployeeId=@rEmployeeId and TimeTableSchemaId=@rTimeTableSchemaId and DayId=1 and LectureNumber=@HeaderCounterStart)
            
   --         IF(@AssignSundayClassDivisionName is NULL)
   --          BEGIN
   --           SET @AssignSundayClassDivisionName='-1'
   --          END 
             
            
            --Declare @AssignSundaySubjectName varchar(100)
   --         SET @AssignSundaySubjectName=(SELECT SM.Code From  sTimetable.tTimeTable T INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=T.SubjectId  where EmployeeId=@rEmployeeId and TimeTableSchemaId=@rTimeTableSchemaId and DayId=1 and LectureNumber=@HeaderCounterStart)
            
   --          IF(@AssignSundaySubjectName is NULL)
   --          BEGIN
   --           SET @AssignSundaySubjectName='-1'
   --          END

			Declare @AssignSundayDivisionSubjectName varchar(Max)=null
			Declare @AssignSundayDivisionSubject varchar(Max)=null
			SELECT @AssignSundayDivisionSubjectName=COALESCE(@AssignSundayDivisionSubjectName+','+VBCD.ClassDivisionName+'/'+SM.Code ,VBCD.ClassDivisionName+'/'+SM.Code),
					@AssignSundayDivisionSubject=COALESCE(@AssignSundayDivisionSubject+','+Cast(VBCD.DivisionId AS Nvarchar)+'/'+cast(SM.Id AS Nvarchar)+'/'+cast(T.Id AS Nvarchar),Cast(VBCD.DivisionId AS Nvarchar)+'/'+cast(SM.Id AS Nvarchar)+'/'+cast(T.Id AS Nvarchar))
			From  sTimetable.tTimeTable T 
			INNER JOIN sSetup.vClassDivision VBCD ON VBCD.DivisionId=T.DivisionId 
			INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=T.SubjectId 
				where EmployeeId=@rEmployeeId and TimeTableSchemaId=@rTimeTableSchemaId and DayId=1 and LectureNumber=@HeaderCounterStart
			IF(@AssignSundayDivisionSubjectName is NULL)
				BEGIN
					SET @AssignSundayDivisionSubjectName='-1/-1'
				END 
			IF(@AssignSundayDivisionSubject is NULL)
				BEGIN
					SET @AssignSundayDivisionSubject='-1/-1'
				END 


            --Declare @AssignMondayClassDivisionName varchar(100)
            --SET @AssignMondayClassDivisionName=(SELECT VBCD.ClassDivisionName From  sTimetable.tTimeTable T INNER JOIN sSetup.vClassDivision VBCD ON VBCD.DivisionId=T.DivisionId  where EmployeeId=@rEmployeeId and TimeTableSchemaId=@rTimeTableSchemaId and DayId=2 and LectureNumber=@HeaderCounterStart)
            
            --IF(@AssignMondayClassDivisionName is NULL)
            -- BEGIN
            --  SET @AssignMondayClassDivisionName='-1'
            -- END 
             
            
            --Declare @AssignMondaySubjectName varchar(100)
            --SET @AssignMondaySubjectName=(SELECT SM.Code From  sTimetable.tTimeTable T INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=T.SubjectId  where EmployeeId=@rEmployeeId and TimeTableSchemaId=@rTimeTableSchemaId and DayId=2 and LectureNumber=@HeaderCounterStart)
            
            -- IF(@AssignMondaySubjectName is NULL)
            -- BEGIN
            --  SET @AssignMondaySubjectName='-1'
            -- END 

            Declare @AssignMondayDivisionSubjectName varchar(Max)=null
			Declare @AssignMondayDivisionSubject varchar(Max)=null
			SELECT @AssignMondayDivisionSubjectName=COALESCE(@AssignMondayDivisionSubjectName+','+VBCD.ClassDivisionName+'/'+SM.Code,VBCD.ClassDivisionName+'/'+SM.Code),
					@AssignMondayDivisionSubject=COALESCE(@AssignMondayDivisionSubject+','+Cast(VBCD.DivisionId AS Nvarchar)+'/'+cast(SM.Id AS Nvarchar)+'/'+cast(T.Id AS Nvarchar),Cast(VBCD.DivisionId AS Nvarchar)+'/'+cast(SM.Id AS Nvarchar)+'/'+cast(T.Id AS Nvarchar))
				From  sTimetable.tTimeTable T 
				INNER JOIN sSetup.vClassDivision VBCD ON VBCD.DivisionId=T.DivisionId 
				INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=T.SubjectId 
				where EmployeeId=@rEmployeeId and TimeTableSchemaId=@rTimeTableSchemaId and DayId=2 and LectureNumber=@HeaderCounterStart
			IF(@AssignMondayDivisionSubjectName is NULL)
				BEGIN
					SET @AssignMondayDivisionSubjectName='-1/-1'
				END 
			IF(@AssignMondayDivisionSubject is NULL)
				BEGIN
					SET @AssignMondayDivisionSubject='-1/-1'
				END 

            --Declare @AssignTuesdayClassDivisionName varchar(100)
            --SET @AssignTuesdayClassDivisionName=(SELECT VBCD.ClassDivisionName From  sTimetable.tTimeTable T INNER JOIN sSetup.vClassDivision VBCD ON VBCD.DivisionId=T.DivisionId  where EmployeeId=@rEmployeeId and TimeTableSchemaId=@rTimeTableSchemaId and DayId=3 and LectureNumber=@HeaderCounterStart)
            
            -- IF(@AssignTuesdayClassDivisionName is NULL)
            -- BEGIN
            --  SET @AssignTuesdayClassDivisionName='-1'
            -- END 
            
            --Declare @AssignTuesdaySubjectName varchar(100)
            --SET @AssignTuesdaySubjectName=(SELECT SM.Code From  sTimetable.tTimeTable T INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=T.SubjectId  where EmployeeId=@rEmployeeId and TimeTableSchemaId=@rTimeTableSchemaId and DayId=3 and LectureNumber=@HeaderCounterStart)
           
            -- IF(@AssignTuesdaySubjectName is NULL)
            -- BEGIN
            --  SET @AssignTuesdaySubjectName='-1'
            -- END 

            Declare @AssignTuesdayDivisionSubjectName varchar(Max)=null
			Declare @AssignTuesdayDivisionSubject varchar(Max)=null
			SELECT @AssignTuesdayDivisionSubjectName=COALESCE(@AssignTuesdayDivisionSubjectName+','+VBCD.ClassDivisionName+'/'+SM.Code,VBCD.ClassDivisionName+'/'+SM.Code),
					@AssignTuesdayDivisionSubject=COALESCE(@AssignTuesdayDivisionSubject+','+Cast(VBCD.DivisionId AS Nvarchar)+'/'+cast(SM.Id AS Nvarchar) +'/'+cast(T.Id AS Nvarchar),Cast(VBCD.DivisionId AS Nvarchar)+'/'+cast(SM.Id AS Nvarchar)+'/'+cast(T.Id AS Nvarchar))
				From  sTimetable.tTimeTable T 
				INNER JOIN sSetup.vClassDivision VBCD ON VBCD.DivisionId=T.DivisionId 
				INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=T.SubjectId 
				where EmployeeId=@rEmployeeId and TimeTableSchemaId=@rTimeTableSchemaId and DayId=3 and LectureNumber=@HeaderCounterStart
			IF(@AssignTuesdayDivisionSubjectName is NULL)
				BEGIN
					SET @AssignTuesdayDivisionSubjectName='-1/-1'
				END 
			IF(@AssignTuesdayDivisionSubject is NULL)
				BEGIN
					SET @AssignTuesdayDivisionSubject='-1/-1'
				END 
            
            --Declare @AssignWedenadayClassDivisionName varchar(100)
            --SET @AssignWedenadayClassDivisionName=(SELECT VBCD.ClassDivisionName From  sTimetable.tTimeTable T INNER JOIN sSetup.vClassDivision VBCD ON VBCD.DivisionId=T.DivisionId  where EmployeeId=@rEmployeeId and TimeTableSchemaId=@rTimeTableSchemaId and DayId=4 and LectureNumber=@HeaderCounterStart)
            
            -- IF(@AssignWedenadayClassDivisionName is NULL)
            -- BEGIN
            --  SET @AssignWedenadayClassDivisionName='-1'
            -- END 
            
            --   Declare @AssignWedenadaySubjectName varchar(100)
            --SET @AssignWedenadaySubjectName=(SELECT SM.Code From  sTimetable.tTimeTable T INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=T.SubjectId  where EmployeeId=@rEmployeeId and TimeTableSchemaId=@rTimeTableSchemaId and DayId=4 and LectureNumber=@HeaderCounterStart)
           
            
            -- IF(@AssignWedenadaySubjectName is NULL)
            -- BEGIN
            --  SET @AssignWedenadaySubjectName='-1'
            -- END 

            Declare @AssignWednesdayDivisionSubjectName varchar(Max)=null
			Declare @AssignWednesdayDivisionSubject varchar(Max)=null
			SELECT @AssignWednesdayDivisionSubjectName=COALESCE(@AssignWednesdayDivisionSubjectName+','+VBCD.ClassDivisionName+'/'+SM.Code,VBCD.ClassDivisionName+'/'+SM.Code),
					@AssignWednesdayDivisionSubject=COALESCE(@AssignWednesdayDivisionSubject+','+Cast(VBCD.DivisionId AS Nvarchar)+'/'+cast(SM.Id AS Nvarchar)+'/'+cast(T.Id AS Nvarchar),Cast(VBCD.DivisionId AS Nvarchar)+'/'+cast(SM.Id AS Nvarchar)+'/'+cast(T.Id AS Nvarchar))
				From  sTimetable.tTimeTable T 
				INNER JOIN sSetup.vClassDivision VBCD ON VBCD.DivisionId=T.DivisionId 
				INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=T.SubjectId 
				where EmployeeId=@rEmployeeId and TimeTableSchemaId=@rTimeTableSchemaId and DayId=4 and LectureNumber=@HeaderCounterStart
			IF(@AssignWednesdayDivisionSubjectName is NULL)
				BEGIN
					SET @AssignWednesdayDivisionSubjectName='-1/-1'
				END 
			IF(@AssignWednesdayDivisionSubject is NULL)
				BEGIN
					SET @AssignWednesdayDivisionSubject='-1/-1'
				END 
            
            --Declare @AssignThrusdayClassDivisionName nvarchar(100)
            --SET @AssignThrusdayClassDivisionName=(SELECT VBCD.ClassDivisionName From  sTimetable.tTimeTable T INNER JOIN sSetup.vClassDivision VBCD ON VBCD.DivisionId=T.DivisionId  where EmployeeId=@rEmployeeId and TimeTableSchemaId=@rTimeTableSchemaId and DayId=5 and LectureNumber=@HeaderCounterStart)
            
            
            -- IF(@AssignThrusdayClassDivisionName is NULL)
            -- BEGIN
            --  SET @AssignThrusdayClassDivisionName='-1'
            -- END 
            
            
            --Declare @AssignThrusdaySubjectName nvarchar(100)
            --SET @AssignThrusdaySubjectName=(SELECT SM.Code From  sTimetable.tTimeTable T INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=T.SubjectId  where EmployeeId=@rEmployeeId and TimeTableSchemaId=@rTimeTableSchemaId and DayId=5 and LectureNumber=@HeaderCounterStart)
           
            --IF(@AssignThrusdaySubjectName is NULL)
            -- BEGIN
            --  SET @AssignThrusdaySubjectName='-1'
            -- END 

            Declare @AssignThrusdayDivisionSubjectName varchar(Max)=null
			Declare @AssignThursdayDivisionSubject varchar(Max)=null
			SELECT @AssignThrusdayDivisionSubjectName=COALESCE(@AssignThrusdayDivisionSubjectName+','+VBCD.ClassDivisionName+'/'+SM.Code,VBCD.ClassDivisionName+'/'+SM.Code),
				@AssignThursdayDivisionSubject=COALESCE(@AssignThursdayDivisionSubject+','+Cast(VBCD.DivisionId AS Nvarchar)+'/'+cast(SM.Id AS Nvarchar)+'/'+cast(T.Id AS Nvarchar),Cast(VBCD.DivisionId AS Nvarchar)+'/'+cast(SM.Id AS Nvarchar)+'/'+cast(T.Id AS Nvarchar))
				From  sTimetable.tTimeTable T 
				INNER JOIN sSetup.vClassDivision VBCD ON VBCD.DivisionId=T.DivisionId 
				INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=T.SubjectId 
				where EmployeeId=@rEmployeeId and TimeTableSchemaId=@rTimeTableSchemaId and DayId=5 and LectureNumber=@HeaderCounterStart
			IF(@AssignThrusdayDivisionSubjectName is NULL)
				BEGIN
					SET @AssignThrusdayDivisionSubjectName='-1/-1'
				END 
			IF(@AssignThursdayDivisionSubject is NULL)
				BEGIN
					SET @AssignThursdayDivisionSubject='-1/-1'
				END 
            
            --Declare @AssignFridayClassDivisionName varchar(100)
            --SET @AssignFridayClassDivisionName=(SELECT VBCD.ClassDivisionName From  sTimetable.tTimeTable T INNER JOIN sSetup.vClassDivision VBCD ON VBCD.DivisionId=T.DivisionId  where EmployeeId=@rEmployeeId and TimeTableSchemaId=@rTimeTableSchemaId and DayId=6 and LectureNumber=@HeaderCounterStart)
       
            -- IF(@AssignFridayClassDivisionName is NULL)
            -- BEGIN
            --  SET @AssignFridayClassDivisionName='-1'
            -- END 
            
       
            --Declare @AssignFridaySubjectName varchar(100)
            --SET @AssignFridaySubjectName=(SELECT SM.Code From  sTimetable.tTimeTable T INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=T.SubjectId  where EmployeeId=@rEmployeeId and TimeTableSchemaId=@rTimeTableSchemaId and DayId=6 and LectureNumber=@HeaderCounterStart)
           
            -- IF(@AssignFridaySubjectName is NULL)
            -- BEGIN
            --  SET @AssignFridaySubjectName='-1'
            -- END 
             
            Declare @AssignFridayDivisionSubjectName varchar(Max)=null
			Declare @AssignFridayDivisionSubject varchar(Max)=null
			SELECT @AssignFridayDivisionSubjectName=COALESCE(@AssignFridayDivisionSubjectName+','+VBCD.ClassDivisionName+'/'+SM.Code,VBCD.ClassDivisionName+'/'+SM.Code),
					@AssignFridayDivisionSubject=COALESCE(@AssignFridayDivisionSubject+','+Cast(VBCD.DivisionId AS Nvarchar)+'/'+cast(SM.Id AS Nvarchar)+'/'+cast(T.Id AS Nvarchar),Cast(VBCD.DivisionId AS Nvarchar)+'/'+cast(SM.Id AS Nvarchar)+'/'+cast(T.Id AS Nvarchar))
				From  sTimetable.tTimeTable T 
				INNER JOIN sSetup.vClassDivision VBCD ON VBCD.DivisionId=T.DivisionId 
				INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=T.SubjectId 
				where EmployeeId=@rEmployeeId and TimeTableSchemaId=@rTimeTableSchemaId and DayId=6 and LectureNumber=@HeaderCounterStart
			IF(@AssignFridayDivisionSubjectName is NULL)
				BEGIN
					SET @AssignFridayDivisionSubjectName='-1/-1'
				END 
			IF(@AssignFridayDivisionSubject is NULL)
				BEGIN
					SET @AssignFridayDivisionSubject='-1/-1'
				END 
      
           -- Declare @AssignSaturdayClassDivisionName varchar(100)
           -- SET @AssignSaturdayClassDivisionName=(SELECT VBCD.ClassDivisionName From  sTimetable.tTimeTable T INNER JOIN sSetup.vClassDivision VBCD ON VBCD.DivisionId=T.DivisionId  where EmployeeId=@rEmployeeId and TimeTableSchemaId=@rTimeTableSchemaId and DayId=7 and LectureNumber=@HeaderCounterStart)
      
           -- IF(@AssignSaturdayClassDivisionName is NULL)
           --  BEGIN
           --   SET @AssignSaturdayClassDivisionName='-1'
           --  END 
          
           -- Declare @AssignSaturdaySubjectName varchar(100)
           -- SET @AssignSaturdaySubjectName=(SELECT SM.Code From  sTimetable.tTimeTable T INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=T.SubjectId  where EmployeeId=@rEmployeeId and TimeTableSchemaId=@rTimeTableSchemaId and DayId=7 and LectureNumber=@HeaderCounterStart)
           
           --IF(@AssignSaturdaySubjectName is NULL)
           --  BEGIN
           --   SET @AssignSaturdaySubjectName='-1'
           --  END 
           
		   Declare @AssignSaturdayDivisionSubjectName varchar(Max)=null
		   Declare @AssignSaturdayDivisionSubject varchar(Max)=null
			SELECT @AssignSaturdayDivisionSubjectName=COALESCE(@AssignSaturdayDivisionSubjectName+','+VBCD.ClassDivisionName+'/'+SM.Code,VBCD.ClassDivisionName+'/'+SM.Code),
					@AssignSaturdayDivisionSubject=COALESCE(@AssignSaturdayDivisionSubject+','+Cast(VBCD.DivisionId AS Nvarchar)+'/'+cast(SM.Id AS Nvarchar)+'/'+cast(T.Id AS Nvarchar),Cast(VBCD.DivisionId AS Nvarchar)+'/'+cast(SM.Id AS Nvarchar)+'/'+cast(T.Id AS Nvarchar))
				From  sTimetable.tTimeTable T 
				INNER JOIN sSetup.vClassDivision VBCD ON VBCD.DivisionId=T.DivisionId 
				INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=T.SubjectId 
				where EmployeeId=@rEmployeeId and TimeTableSchemaId=@rTimeTableSchemaId and DayId=7 and LectureNumber=@HeaderCounterStart
			IF(@AssignSaturdayDivisionSubjectName is NULL)
				BEGIN
					SET @AssignSaturdayDivisionSubjectName='-1/-1'
				END 
			IF(@AssignSaturdayDivisionSubject is NULL)
				BEGIN
					SET @AssignSaturdayDivisionSubject='-1/-1'
				END 


			--Declare @AssignSundayDivisionSubject varchar(100)
   --          Declare @AssignSundayClassDivisionId varchar(100)
   --          Declare @AssignSundaySubjectId varchar(100)
             
   --          SET @AssignSundayClassDivisionId=(SELECT VBCD.DivisionId From  sTimetable.tTimeTable T INNER JOIN sSetup.vClassDivision VBCD ON VBCD.DivisionId=T.DivisionId  where EmployeeId=@rEmployeeId and TimeTableSchemaId=@rTimeTableSchemaId and DayId=1 and LectureNumber=@HeaderCounterStart)
   --          SET @AssignSundaySubjectId=(SELECT SM.Id From  sTimetable.tTimeTable T INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=T.SubjectId  where EmployeeId=@rEmployeeId and TimeTableSchemaId=@rTimeTableSchemaId and DayId=1 and LectureNumber=@HeaderCounterStart)
             
   --          IF(@AssignSundayClassDivisionId is NULL)
   --          BEGIN
   --           SET @AssignSundayClassDivisionId='-1'
   --          END 
   --           IF(@AssignSundaySubjectId is NULL)
   --          BEGIN
   --           SET @AssignSundaySubjectId='-1'
   --          END 
           
             
             --SET @AssignSundayDivisionSubject=@AssignSundayClassDivisionId +'/' + @AssignSundaySubjectId

           
            -- Declare @AssignMondayDivisionSubject varchar(100)
            -- Declare @AssignMondayClassDivisionId varchar(100)
            -- Declare @AssignMondaySubjectId varchar(100)
             
            -- SET @AssignMondayClassDivisionId=(SELECT VBCD.DivisionId From  sTimetable.tTimeTable T INNER JOIN sSetup.vClassDivision VBCD ON VBCD.DivisionId=T.DivisionId  where EmployeeId=@rEmployeeId and TimeTableSchemaId=@rTimeTableSchemaId and DayId=2 and LectureNumber=@HeaderCounterStart)
            -- SET @AssignMondaySubjectId=(SELECT SM.Id From  sTimetable.tTimeTable T INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=T.SubjectId  where EmployeeId=@rEmployeeId and TimeTableSchemaId=@rTimeTableSchemaId and DayId=2 and LectureNumber=@HeaderCounterStart)
             
            -- IF(@AssignMondayClassDivisionId is NULL)
            -- BEGIN
            --  SET @AssignMondayClassDivisionId='-1'
            -- END 
            --  IF(@AssignMondaySubjectId is NULL)
            -- BEGIN
            --  SET @AssignMondaySubjectId='-1'
            -- END 
           
             
            -- SET @AssignMondayDivisionSubject=@AssignMondayClassDivisionId +'/' + @AssignMondaySubjectId
             
            -- Declare @AssignTuesdayDivisionSubject varchar(100)
            -- Declare @AssignTuesdayClassDivisionId varchar(100)
            -- Declare @AssignTuesdaySubjectId varchar(100)
             
            -- SET @AssignTuesdayClassDivisionId=(SELECT VBCD.DivisionId From  sTimetable.tTimeTable T INNER JOIN sSetup.vClassDivision VBCD ON VBCD.DivisionId=T.DivisionId  where EmployeeId=@rEmployeeId and TimeTableSchemaId=@rTimeTableSchemaId and DayId=3 and LectureNumber=@HeaderCounterStart)
            -- SET @AssignTuesdaySubjectId=(SELECT SM.Id From  sTimetable.tTimeTable T INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=T.SubjectId  where EmployeeId=@rEmployeeId and TimeTableSchemaId=@rTimeTableSchemaId and DayId=3 and LectureNumber=@HeaderCounterStart)
             
            --IF(@AssignTuesdayClassDivisionId is NULL)
            -- BEGIN
            --  SET @AssignTuesdayClassDivisionId='-1'
            -- END 
            --  IF(@AssignTuesdaySubjectId is NULL)
            -- BEGIN
            --  SET @AssignTuesdaySubjectId='-1'
            -- END 
             
            -- SET @AssignTuesdayDivisionSubject=@AssignTuesdayClassDivisionId +'/' + @AssignTuesdaySubjectId
             
             
            -- Declare @AssignWednesdayDivisionSubject varchar(100)
            -- Declare @AssignWednesdayClassDivisionId varchar(100)
            -- Declare @AssignWednesdaySubjectId varchar(100)
             
            -- SET @AssignWednesdayClassDivisionId=(SELECT VBCD.DivisionId From  sTimetable.tTimeTable T INNER JOIN sSetup.vClassDivision VBCD ON VBCD.DivisionId=T.DivisionId  where EmployeeId=@rEmployeeId and TimeTableSchemaId=@rTimeTableSchemaId and DayId=4 and LectureNumber=@HeaderCounterStart)
            -- SET @AssignWednesdaySubjectId=(SELECT SM.Id From  sTimetable.tTimeTable T INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=T.SubjectId  where EmployeeId=@rEmployeeId and TimeTableSchemaId=@rTimeTableSchemaId and DayId=4 and LectureNumber=@HeaderCounterStart)
             
            --  IF(@AssignWednesdayClassDivisionId is NULL)
            -- BEGIN
            --  SET @AssignWednesdayClassDivisionId='-1'
            -- END 
            --  IF(@AssignWednesdaySubjectId is NULL)
            -- BEGIN
            --  SET @AssignWednesdaySubjectId='-1'
            -- END 
             
             
            -- SET @AssignWednesdayDivisionSubject=@AssignWednesdayClassDivisionId +'/' + @AssignWednesdaySubjectId
             
            -- Declare @AssignThursdayDivisionSubject varchar(100)
            -- Declare @AssignThursdayClassDivisionId varchar(100)
            -- Declare @AssignThursdaySubjectId varchar(100)
             
            -- SET @AssignThursdayClassDivisionId=(SELECT VBCD.DivisionId From  sTimetable.tTimeTable T INNER JOIN sSetup.vClassDivision VBCD ON VBCD.DivisionId=T.DivisionId  where EmployeeId=@rEmployeeId and TimeTableSchemaId=@rTimeTableSchemaId and DayId=5 and LectureNumber=@HeaderCounterStart)
            -- SET @AssignThursdaySubjectId=(SELECT SM.Id From  sTimetable.tTimeTable T INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=T.SubjectId  where EmployeeId=@rEmployeeId and TimeTableSchemaId=@rTimeTableSchemaId and DayId=5 and LectureNumber=@HeaderCounterStart)
             
            -- IF(@AssignThursdayClassDivisionId is NULL)
            -- BEGIN
            --  SET @AssignThursdayClassDivisionId='-1'
            -- END 
            --  IF(@AssignThursdaySubjectId is NULL)
            -- BEGIN
            --  SET @AssignThursdaySubjectId='-1'
            -- END 
             
             
            -- SET @AssignThursdayDivisionSubject=@AssignThursdayClassDivisionId +'/' + @AssignThursdaySubjectId
             
             
            -- Declare @AssignFridayDivisionSubject varchar(100)
            -- Declare @AssignFridayClassDivisionId varchar(100)
            -- Declare @AssignFridaySubjectId varchar(100)
             
            -- SET @AssignFridayClassDivisionId=(SELECT VBCD.DivisionId From  sTimetable.tTimeTable T INNER JOIN sSetup.vClassDivision VBCD ON VBCD.DivisionId=T.DivisionId  where EmployeeId=@rEmployeeId and TimeTableSchemaId=@rTimeTableSchemaId and DayId=6 and LectureNumber=@HeaderCounterStart)
            -- SET @AssignFridaySubjectId=(SELECT SM.Id From  sTimetable.tTimeTable T INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=T.SubjectId  where EmployeeId=@rEmployeeId and TimeTableSchemaId=@rTimeTableSchemaId and DayId=6 and LectureNumber=@HeaderCounterStart)
             
            -- IF(@AssignFridayClassDivisionId is NULL)
            -- BEGIN
            --  SET @AssignFridayClassDivisionId='-1'
            -- END 
            --  IF(@AssignFridaySubjectId is NULL)
            -- BEGIN
            --  SET @AssignFridaySubjectId='-1'
            -- END 
             
             
            -- SET @AssignFridayDivisionSubject=@AssignFridayClassDivisionId +'/' + @AssignFridaySubjectId
             
            -- Declare @AssignSaturdayDivisionSubject varchar(100)
            -- Declare @AssignSaturdayClassDivisionId varchar(100)
            -- Declare @AssignSaturdaySubjectId varchar(100)
             
            -- SET @AssignSaturdayClassDivisionId=(SELECT VBCD.DivisionId From  sTimetable.tTimeTable T INNER JOIN sSetup.vClassDivision VBCD ON VBCD.DivisionId=T.DivisionId  where EmployeeId=@rEmployeeId and TimeTableSchemaId=@rTimeTableSchemaId and DayId=7 and LectureNumber=@HeaderCounterStart)
            -- SET @AssignSaturdaySubjectId=(SELECT SM.Id From  sTimetable.tTimeTable T INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=T.SubjectId  where EmployeeId=@rEmployeeId and TimeTableSchemaId=@rTimeTableSchemaId and DayId=7 and LectureNumber=@HeaderCounterStart)
             
            -- IF(@AssignSaturdayClassDivisionId is NULL)
            -- BEGIN
            --  SET @AssignSaturdayClassDivisionId='-1'
            -- END 
            --  IF(@AssignSaturdaySubjectId is NULL)
            -- BEGIN
            --  SET @AssignSaturdaySubjectId='-1'
            -- END 
             
             
            -- SET @AssignSaturdayDivisionSubject=@AssignSaturdayClassDivisionId +'/' + @AssignSaturdaySubjectId
             
           print @HeaderCounterStart
      -- print @AssignThrusdayClassDivisionName
       --print @AssignThrusdaySubjectName
			--INSERT INTO @lTableList(LectureNumber,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday,MondayClassSubjectId,TuesdayClassSubjectId,WednesdayClassSubjectId,ThursdayClassSubjectId,FridayClassSubjectId,SaturdayClassSubjectId)
			--values(@HeaderCounterStart,@AssignMondayClassDivisionName +'/' + @AssignMondaySubjectName,@AssignTuesdayClassDivisionName+'/' + @AssignTuesdaySubjectName,@AssignWedenadayClassDivisionName+'/' + @AssignWedenadaySubjectName,@AssignThrusdayClassDivisionName+'/' + @AssignThrusdaySubjectName,@AssignFridayClassDivisionName+'/' + @AssignFridaySubjectName,@AssignSaturdayClassDivisionName+'/' + @AssignSaturdaySubjectName,@AssignMondayDivisionSubject,@AssignTuesdayDivisionSubject,@AssignWednesdayDivisionSubject,@AssignThursdayDivisionSubject,@AssignFridayDivisionSubject,@AssignSaturdayDivisionSubject)
        
   --    INSERT INTO @lTableList(LectureNumber,Sunday,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday,SundayClassSubjectId,MondayClassSubjectId,TuesdayClassSubjectId,WednesdayClassSubjectId,ThursdayClassSubjectId,FridayClassSubjectId,SaturdayClassSubjectId)
			--values(@HeaderCounterStart,@AssignSundayClassDivisionName +'/' + @AssignSundaySubjectName,@AssignMondayClassDivisionName +'/' + @AssignMondaySubjectName,@AssignTuesdayClassDivisionName+'/' + @AssignTuesdaySubjectName,@AssignWedenadayClassDivisionName+'/' + @AssignWedenadaySubjectName,@AssignThrusdayClassDivisionName +'/' + @AssignThrusdaySubjectName,@AssignFridayClassDivisionName+'/' + @AssignFridaySubjectName,@AssignSaturdayClassDivisionName+'/' + @AssignSaturdaySubjectName,@AssignSundayDivisionSubject,@AssignMondayDivisionSubject,@AssignTuesdayDivisionSubject,@AssignWednesdayDivisionSubject,@AssignThursdayDivisionSubject,@AssignFridayDivisionSubject,@AssignSaturdayDivisionSubject)
        
        INSERT INTO @lTableList(LectureNumber,Sunday,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday,SundayClassSubjectId,MondayClassSubjectId,TuesdayClassSubjectId,WednesdayClassSubjectId,ThursdayClassSubjectId,FridayClassSubjectId,SaturdayClassSubjectId)
			values(@HeaderCounterStart,@AssignSundayDivisionSubjectName,@AssignMondayDivisionSubjectName,@AssignTuesdayDivisionSubjectName,@AssignWednesdayDivisionSubjectName,@AssignThrusdayDivisionSubjectName,@AssignFridayDivisionSubjectName,@AssignSaturdayDivisionSubjectName,@AssignSundayDivisionSubject,@AssignMondayDivisionSubject,@AssignTuesdayDivisionSubject,@AssignWednesdayDivisionSubject,@AssignThursdayDivisionSubject,@AssignFridayDivisionSubject,@AssignSaturdayDivisionSubject)
        
            
        SET @HeaderCounterStart=@HeaderCounterStart+1;
    END



     select *From @lTableList
END
GO
PRINT N'Altering [sTimetable].[pTimeTableAdd]...';


GO

ALTER PROCEDURE [sTimetable].[pTimeTableAdd]
		
		@rOrgId int,
		@rId int,
		@rTimeTableSchemaID int,
		@rEmployeeId bigint,
		@rDivisionId int,
		@rSubjectId int,
		@rDayId smallint,
		@rLectureNumber smallint,
		@rLockNo bigint,
		@rLockColour varchar(50)
		
		
           	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

	 
 
BEGIN 

	 BEGIN TRY	
	 BEGIN TRANSACTION 
	   --print 'a'
	DECLARE @lIsAssignSameSubjectDivison bit=0,
	@lAssignSameSubjectDivison nvarchar(50),
	@lOrgGroupId int
	
	select @lOrgGroupId = OrgGroupId from [sSetup].[tOrganizationMaster] where Id=@rOrgId
	SELECT @lAssignSameSubjectDivison = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 493 AND SourceTypeId = 2010 AND SourceId = @lOrgGroupId
	
	IF (@lAssignSameSubjectDivison IS NULL) OR (@lAssignSameSubjectDivison = 'False')
		SET @lIsAssignSameSubjectDivison = 0
		
	ELSE
		SET @lIsAssignSameSubjectDivison = 1
	print @lIsAssignSameSubjectDivison

	IF NOT EXISTS(Select 1 FROM sTimetable.tTimeTable Where EmployeeId = @rEmployeeId AND SubjectId=@rSubjectId  AND  LectureNumber = @rLectureNumber AND DayId = @rDayId and TimeTableSchemaId=@rTimeTableSchemaId AND DivisionId=@rDivisionId )
	 
	BEGIN
	IF NOT EXISTS(Select 1 FROM sTimetable.tTimeTable Where  SubjectId=@rSubjectId  AND LectureNumber = @rLectureNumber AND DayId = @rDayId and TimeTableSchemaId=@rTimeTableSchemaId AND DivisionId=@rDivisionId AND @lIsAssignSameSubjectDivison=0)
	BEGIN
	DECLARE @lNextNumber BIGINT
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sTimetable.tTimeTable', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	 
	  BEGIN
		   INSERT INTO sTimetable.tTimeTable		 
		   (
				[Id]
			   ,[TimeTableSchemaId]
			   ,[EmployeeId]
			   ,[DivisionId]
			   ,[SubjectId]
			   ,[DayId]
			   ,[LectureNumber]
			   ,[LockNo]
			   ,[LockColour]
            )		 
			VALUES
			(	
				@lNextNumber,
				@rTimeTableSchemaID,
				@rEmployeeId,
				@rDivisionId,
				@rSubjectId,
				@rDayId,
				@rLectureNumber,
				@rLockNo,
				@rLockColour
			)		
			SELECT @lNextNumber AS Result
    	END
      END
	  ELSE
	  BEGIN       
		  SELECT -102 AS Result
		END
	  END
    ELSE
    BEGIN       
      SELECT -101 AS Result
    END
	
	COMMIT TRANSACTION
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
	
	
END 	             
	
		
END
GO
PRINT N'Altering [sTransport].[pRptRoutewiseStudentListGet]...';


GO
ALTER PROCEDURE [sTransport].[pRptRoutewiseStudentListGet]	 
	 @rOrgGroupBatchId int=0,
	 @rOrgId int=0,
	 @rDepartmentId int=0,
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 @rClassId int=0,
	 @rDivisionId int=0,
	 @rRouteId int=0,
	 @rDestinationId int=0,
	 @rTransportId int =0,
	 @rDropDestinationId int=0,
	 @rDropBusRouteId int=0,
	 @rStatusId int=0,
	 @rStrRouteId nvarchar(500)=null,
	 @rDestinationTitle nvarchar(50)=null,
	 @rIsWithDetail bit
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
BEGIN 
	SELECT DISTINCT * FROM 
	(
		SELECT 
	        @rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			AR.SourceId,
			SM.Code,
			SM.FirstName+' '+SM.LastName AS Name,
			DM.Id AS DivisionId,
			CM.DisplayTitle AS Class,
			DM.DisplayTitle AS Division,
			CM.DisplayTitle+' - '+DM.DisplayTitle AS ClassDivision,
			BRDM.Title AS DestinationPoint,
			BRM.Id AS BusRouteId,
			BRM.Title AS BusRoute,
			A.RollNo,
			VM.Title AS Vehicle,
			VM.NoOfSeats,
			BRM.OrderIndex AS RouteOrder,
			BRDM.OrderIndex AS PickupOrder,
			DM.OrderIndex AS DivisionOrderIndex,
			OM.Id AS OrgId,
			OM.DisplayTitle AS OrganizationName,
			DMast.Id AS DepartmentId,
			DMast.Title AS DepartmentName,
			SC.ParentContactNo AS ParentContactNo,
			ISNULL(SC.PresentStreetone,'')+' '+ISNULL(SC.PresentStreetTwo,'')+' '+ISNULL(SC.PresentStreetThree,'')+' '+ISNULL(SC.PresentCity,'')+' '+ISNULL(SC.PresentState,'')+' '+ISNULL(SC.PresentZipCode,'') AS PresentAddress,
			ISNULL(VM.RegistrationNumber,'') AS RegistrationNumber,
			ISNULL(BRM.DriverName,'') AS DriverName,
			ISNULL(BRM.DriverMobileNo,'') AS DriverMobileNo,
			ISNULL(BRM.ConductorName,'') AS ConductorName,
			ISNULL(BRM.ConductorMobileNo,'') AS ConductorMobileNo,
			BRDM.Amount,
			ISNULL(BRM1.DriverName,'') AS DropRoutDriverName,
			ISNULL(BRM1.DriverMobileNo,'') AS DropRoutDriverMobileNo,
			ISNULL(BRM1.ConductorName,'') AS DropRoutConductorName,
			ISNULL(BRM1.ConductorMobileNo,'') AS DropRoutConductorMobileNo,
			BRM1.Id AS DropRoutBusRouteId,
			BRM1.Title AS DropRoutBusRoute,
			ISNULL(VM1.RegistrationNumber,'') AS DropRoutRegistrationNumber,
			VM1.Title AS DropRoutVehicle,
			VM1.NoOfSeats AS DropRoutVehicleNoOfSeats,
			BRM1.OrderIndex AS DropRoutRouteOrder,
			BRDM1.OrderIndex AS DropRoutOrder,
			BRDM1.Title AS DropDestinationPoint ,
			BRDM1.DropTime,
			BRDM.PickUpTime,
			@rIsWithDetail As WithDetails
			
		FROM 
			sTransport.tAssignRoute AR
			INNER JOIN sStudent.tAcademic A ON A.StudentId=AR.SourceId
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId 
			INNER JOIN sStudent.tStudentMaster SM ON A.StudentId=SM.Id 
			LEFT JOIN sStudent.tStudentCommunication SC ON A.StudentId=SC.StudentId AND SM.StatusId=1
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id
			INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=A.OrgId
			INNER JOIN sSetup.tDepartmentMaster DMast ON DMast.Id=CM.DepartmentId
			INNER JOIN sTransport.tBusRouteDestinationMaster BRDM ON BRDM.Id=AR.PickupDestinationId
			INNER JOIN sTransport.tBusRouteMaster BRM ON BRM.Id=BRDM.BusRouteId
			LEFT JOIN sTransport.tVehicleMaster VM ON VM.Id=BRM.VehicleId
			LEFT JOIN sTransport.tBusRouteDestinationMaster BRDM1 ON BRDM1.Id=AR.DropDestinationId 
			LEFT JOIN sTransport.tBusRouteMaster BRM1 ON BRM1.Id=BRDM1.BusRouteId AND (BRM1.OrgGroupBatchId=@rOrgGroupBatchId)
			INNER JOIN sSetup.tBatchMaster BMM ON BMM.OrgGroupBatchId = BRM.OrgGroupBatchId AND BMM.Id = A.BatchId 
			LEFT JOIN sTransport.tVehicleMaster VM1 ON VM1.Id=BRM1.VehicleId
		WHERE 
			--((AR.SourceId=@rAcademicId) OR (@rAcademicId=0))
			(BRM.OrgGroupBatchId=@rOrgGroupBatchId)
			AND BM.OrgGroupBatchId = @rOrgGroupBatchId
			AND ((OM.Id=@rOrgId) OR (@rOrgId=0))
			AND ((DMast.Id=@rDepartmentId) OR (@rDepartmentId=0))
			AND ((CM.Id=@rClassId) OR (@rClassId=0))
			AND ((DM.Id=@rDivisionId) OR (@rDivisionId=0))
			AND ((BRM.Id=@rRouteId) OR (@rRouteId=0))
			AND ((BRM.TransportId=@rTransportId) OR (@rTransportId=0))
			AND ((BRDM.Id=@rDestinationId) OR (@rDestinationId=0))
			AND ((BRDM1.BusRouteId=@rDropBusRouteId) OR (@rDropBusRouteId=0))
			AND ((BRDM1.Id=@rDropDestinationId) OR (@rDropDestinationId=0))
			AND ((SM.StatusId = @rStatusId) OR (@rStatusId=0))
			AND BMM.IsInContext = 1
			AND (BRM.Id IN (SELECT item from sCommon.fnSplit(@rStrRouteId,',')) OR ISNULL(@rStrRouteId,'') = '')
			AND (BRDM.Title Like @rDestinationTitle OR ISNULL(@rDestinationTitle,'') = '')

		UNION ALL 

		SELECT 
	        @rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			AR.SourceId,
			SM.Code,
			SM.FirstName+' '+SM.LastName AS Name,
			DM.Id AS DivisionId,
			CM.DisplayTitle AS Class,
			DM.DisplayTitle AS Division,
			CM.DisplayTitle+' - '+DM.DisplayTitle AS ClassDivision,
			BRDM.Title AS DestinationPoint,
			BRM.Id AS BusRouteId,
			BRM.Title AS BusRoute,
			A.RollNo,
			VM.Title AS Vehicle,
			VM.NoOfSeats,
			BRM.OrderIndex AS RouteOrder,
			BRDM.OrderIndex AS PickupOrder,
			DM.OrderIndex AS DivisionOrderIndex,
			OM.Id AS OrgId,
			OM.DisplayTitle AS OrganizationName,
			DMast.Id AS DepartmentId,
			DMast.Title AS DepartmentName,
			SC.ParentContactNo AS ParentContactNo,
			ISNULL(SC.PresentStreetone,'')+' '+ISNULL(SC.PresentStreetTwo,'')+' '+ISNULL(SC.PresentStreetThree,'')+' '+ISNULL(SC.PresentCity,'')+' '+ISNULL(SC.PresentState,'')+' '+ISNULL(SC.PresentZipCode,'') AS PresentAddress,
			ISNULL(VM.RegistrationNumber,'') AS RegistrationNumber,
			ISNULL(BRM.DriverName,'') AS DriverName,
			ISNULL(BRM.DriverMobileNo,'') AS DriverMobileNo,
			ISNULL(BRM.ConductorName,'') AS ConductorName,
			ISNULL(BRM.ConductorMobileNo,'') AS ConductorMobileNo,
			BRDM.Amount,
			ISNULL(BRM1.DriverName,'') AS DropRoutDriverName,
			ISNULL(BRM1.DriverMobileNo,'') AS DropRoutDriverMobileNo,
			ISNULL(BRM1.ConductorName,'') AS DropRoutConductorName,
			ISNULL(BRM1.ConductorMobileNo,'') AS DropRoutConductorMobileNo,
			BRM1.Id AS DropRoutBusRouteId,
			BRM1.Title AS DropRoutBusRoute,
			ISNULL(VM1.RegistrationNumber,'') AS DropRoutRegistrationNumber,
			VM1.Title AS DropRoutVehicle,
			VM1.NoOfSeats AS DropRoutVehicleNoOfSeats,
			BRM1.OrderIndex AS DropRoutRouteOrder,
			BRDM1.OrderIndex AS DropRoutOrder,
			BRDM1.Title AS DropDestinationPoint ,
			BRDM1.DropTime,
			BRDM.PickUpTime,
			@rIsWithDetail As WithDetails
			
		FROM 
			sTransport.tAssignRoute AR
			INNER JOIN sStudent.tAcademic A ON A.StudentId=AR.SourceId
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId 
			INNER JOIN sStudent.tStudentMaster SM ON A.StudentId=SM.Id 
			LEFT JOIN sStudent.tStudentCommunication SC ON A.StudentId=SC.StudentId AND SM.StatusId=1
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id
			INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=A.OrgId
			INNER JOIN sSetup.tDepartmentMaster DMast ON DMast.Id=CM.DepartmentId
			INNER JOIN sTransport.tBusRouteDestinationMaster BRDM ON BRDM.Id=AR.DropDestinationId
			INNER JOIN sTransport.tBusRouteMaster BRM ON BRM.Id=BRDM.BusRouteId
			LEFT JOIN sTransport.tVehicleMaster VM ON VM.Id=BRM.VehicleId
			LEFT JOIN sTransport.tBusRouteDestinationMaster BRDM1 ON BRDM1.Id=AR.PickupDestinationId
			LEFT JOIN sTransport.tBusRouteMaster BRM1 ON BRM1.Id=BRDM1.BusRouteId AND (BRM1.OrgGroupBatchId=@rOrgGroupBatchId)
			INNER JOIN sSetup.tBatchMaster BMM ON BMM.OrgGroupBatchId = BRM.OrgGroupBatchId AND BMM.Id = A.BatchId 
			LEFT JOIN sTransport.tVehicleMaster VM1 ON VM1.Id=BRM1.VehicleId
		WHERE 
			--((AR.SourceId=@rAcademicId) OR (@rAcademicId=0))
			(BRM.OrgGroupBatchId=@rOrgGroupBatchId)
			AND BM.OrgGroupBatchId = @rOrgGroupBatchId
			AND ((OM.Id=@rOrgId) OR (@rOrgId=0))
			AND ((DMast.Id=@rDepartmentId) OR (@rDepartmentId=0))
			AND ((CM.Id=@rClassId) OR (@rClassId=0))
			AND ((DM.Id=@rDivisionId) OR (@rDivisionId=0))
			AND ((BRM.Id=@rRouteId) OR (@rRouteId=0))
			AND ((BRM.TransportId=@rTransportId) OR (@rTransportId=0))
			AND ((BRDM.Id=@rDestinationId) OR (@rDestinationId=0))
			AND ((BRDM1.BusRouteId=@rDropBusRouteId) OR (@rDropBusRouteId=0))
			AND ((BRDM1.Id=@rDropDestinationId) OR (@rDropDestinationId=0))
			AND ((SM.StatusId = @rStatusId) OR (@rStatusId=0))
			AND BMM.IsInContext = 1
			AND (BRM.Id IN (SELECT item from sCommon.fnSplit(@rStrRouteId,',')) OR ISNULL(@rStrRouteId,'') = '')
			AND (BRDM.Title Like @rDestinationTitle OR ISNULL(@rDestinationTitle,'') = '')
	) A
END
GO
PRINT N'Creating [sAlert].[pGetWebNotificationList]...';


GO


CREATE proc [sAlert].[pGetWebNotificationList]
@rSourceId bigint,
@rSourceTypeId int

AS
BEGIN
	DECLARE @lnotifictiongrid NVARCHAR(max)=''

	--SELECT  @lnotifictiongrid = @lnotifictiongrid + '<tr>
	--<td align="left" scope="col">' + ISNULL(NL.MessageTitle,'')+' '+'<a  class="fa fa-plus-square"  
 --   onclick="window.open(' + '''' + Replace(S.Page,'~','') + '''' +');"></a>'+ '</td>
	--</tr>'

 --From
	--[sAlert].[tNotificationLog]  NL
	--INNER JOIN [sSecurity].[tScreen] S ON NL.StatusCode = S.Id
	--WHERE OSTypeId  = 3 
	--AND SourceId = @rSourceId
	--AND SourceTypeId = @rSourceTypeId
	
	
	--select '<table class="table table-striped table-bordered"><thead><tr><th scope ="col">Notifications</th></tr></thead><tbody style="text-align: center;">' + 
	--isnull(@lnotifictiongrid,'')  +'</tbody></table>'  as NotificationGrid

	SELECT  @lnotifictiongrid = @lnotifictiongrid + '<a class="text-light-blue" onclick="window.open(' + '''' + Replace(S.Page,'~','') + '''' +');">
		<div class="notification-item"><p style="margin-bottom: 0.1rem" class="item-info">' + ISNULL(NL.MessageTitle,'')+'
		</p></div></a>'

 From
	[sAlert].[tNotificationLog]  NL
	INNER JOIN [sSecurity].[tScreen] S ON NL.StatusCode = S.Id
	WHERE OSTypeId  = 3 
	AND SourceId = @rSourceId
	AND SourceTypeId = @rSourceTypeId
	
	
	select '<ul aria-labelledby="dLabel"><div class="notifications-wrapper">' + 
	isnull(@lnotifictiongrid,'')  +'</div></ul>'  as NotificationGrid

END
GO
PRINT N'Creating [sAttendance].[pStudentSubjectwiseAttendanceGet]...';


GO

CREATE PROCEDURE [sAttendance].[pStudentSubjectwiseAttendanceGet]
	 	  @rForMonth smallint,
	      @rForYear smallint,
	      @rAcademicId bigint,
	      @rBatchId int
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	Select 
	
	        DAY(SR.AttendanceDate) AS DayNo,
			
			CASE  WHEN SR.IsPresent = 1 AND SR.AttendanceTagId = 1 THEN 'LA' 
				  WHEN SR.IsPresent = 1 AND SR.AttendanceTagId = 2 THEN 'ED' 
			      WHEN SR.IsPresent = 1  THEN 'P' 
				  WHEN SR.IsPresent = 0 THEN 'A'
				  ELSE  '' END AS  Presence,
			OM.WeekOffs,
			sAttendance.fHolidayForMonthGet(@rForMonth,@rForYear,@rBatchId,SA.DivisionId)  As Holidays,
			ISNULL(SM.Id,0) AS SubjectId,  
			ISNULL(SM.Code,'') AS SubjectCode,  
			ISNULL(SM.Title,'') AS SubjectName,  
			ISNULL(SR.PeriodNo,0) As PeriodNo,
			SR.AcademicId
			
			
		
	From  
			sStudent.vStudentAcademic SA
            INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=SA.AcademicId
			 INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=SR.SubjectId 
            INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SA.OrgId
	
	WHERE
			SR.AttendanceTypeId=5
		AND SR.AcademicId=@rAcademicId
		AND YEAR(SR.AttendanceDate)=@rForYear
		AND MONTH(SR.AttendanceDate)=@rForMonth
		AND SA.BatchId=@rBatchId
		
		ORDER BY DayNo ,SubjectName,PeriodNo
END
GO
PRINT N'Creating [sHrm].[pStaffCountDashboardGet]...';


GO
CREATE PROCEDURE [sHrm].[pStaffCountDashboardGet]
	 
	 @rTypeId smallint,
	 @rOrgGroupId int = 0,
	 @rOrgId int = 0,
	 @rDepartmentId int = 0,
	 @rCommonOrgGroupBatchId int = 0	 
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	IF (@rTypeId=1)
	BEGIN
		--DECLARE @lEmployeeDesignationList nvarchar(max) = ''
		--DECLARE @lEmployeeDesignationListSum nvarchar(max) = ''
	
		--SET @lEmployeeDesignationList = (SELECT STUFF((SELECT ', [' + ISNULL(EDM.Title,',') + ']'
		--													FROM sHrm.tEmployeeDesignationMaster EDM
		--													INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = EDM.OrgId
		--													INNER JOIN sSetup.tOrgGroupMaster OGM ON OM.OrgGroupId = OGM.Id
		--													INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.OrgGroupId=OGM.Id
		--													INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId  
		--													WHERE EDM.IsObsolete = 0 
		--													AND COGBM.Id = @rCommonOrgGroupBatchId
		--													And ISNULL(OGM.IsObsolete,0) = 0
		--													AND (OGM.Id=@rOrgGroupId OR @rOrgGroupId=0) 
		--													FOR XML PATH(''), TYPE).value('.','NVARCHAR(MAX)'),1,2,''))

		--SET @lEmployeeDesignationListSum = REPLACE(@lEmployeeDesignationList,', ', '+')
	
		--DECLARE @lQuery nvarchar(max) = ''

		--IF(@lEmployeeDesignationList IS NOT NULL)
		--BEGIN
			--SET @lQuery = 'SELECT OrgGroupId,OrgGroupTitle,'+ @lEmployeeDesignationList +', '+ (@lEmployeeDesignationListSum) +' AS Total
			--FROM 
			--(
				SELECT     
					OGM.Id AS OrgGroupId,
					OGM.Title AS OrgGroupTitle,
					EDM.Title AS Designation,
					COUNT(ISNULL(EM.Id, 0)) AS StaffCount
				FROM sHrm.tEmployeeMaster EM 
					INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID
					INNER JOIN sHrm.tEmployeeDesignationMaster EDM  ON EDM.Id = EJD.EmployeeDesignationId
					INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = EM.OrgID
					INNER JOIN sSetup.tOrgGroupMaster OGM ON OM.OrgGroupId = OGM.Id
					INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.OrgGroupId=OGM.Id
					INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId  
				WHERE 
					--(OGM.Id=' + CAST(@rOrgGroupId AS nvarchar(20)) + ' OR ' + CAST(@rOrgGroupId AS nvarchar(20)) + '=0) 
					--AND COGBM.Id = ' + CAST(@rCommonOrgGroupBatchId AS nvarchar(20)) + '
					(OGM.Id=@rOrgGroupId OR @rOrgGroupId=0) 
					AND COGBM.Id = @rCommonOrgGroupBatchId
					AND EDM.IsObsolete = 0
					AND EM.StatusId = 7
					And ISNULL(OGM.IsObsolete,0) = 0
				GROUP BY OGM.Id, OGM.Title, EDM.Title
			--) AS A 
			--PIVOT
			--(
			--	MAX(EmployeeCount) FOR [Designation] IN (' + @lEmployeeDesignationList + ')
			--) AS A1'

			--execute(@lQuery) 
		--END
	END
END
GO
PRINT N'Creating [sLibrary].[pBookLogListViewGetEmployee]...';


GO

CREATE PROCEDURE [sLibrary].[pBookLogListViewGetEmployee]
	 @rReaderSourceTypeId smallint=95,
	 @rOrgId smallint,
	 @rEmployeeId Bigint	
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
DECLARE @lBookgrid VARCHAR(max)=''

SELECT  @lBookgrid = @lBookgrid + '<tr>
  <td align="left" scope="col">' +  Isnull(LM.Title,'') + '</td>
	<td align="left" scope="col">' + ISNULL(BM.Code,'')+ '</td>	
	<td align="left" scope="col">' + isnull(BM.Title,'') + '</td>
	<td align="left" scope="col">' +  convert(varchar,isnull(BL.LogDate,''),103) + '</td>
	<td align="left" scope="col">' +  convert(varchar,isnull(BL.DueDate,''),103) + '</td>
	<td align="left" scope="col">' + CASE WHEN SM.Title = 'Available' THEN  'Returned' ELSE ISNULL(SM.Title,'') END + '</td>
</tr>'	
	FROM 
			sLibrary.tBookLog BL
			INNER JOIN sLibrary.tBookMaster BM ON BM.Id=BL.ResourceSourceId
			INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id=BL.ReaderSourceId
			INNER JOIN sCommon.tStatusMaster SM ON SM.Id=BL.StatusId AND SM.IsObsolete = 0 AND SM.StatusTypeId=106
			INNER JOIN sLibrary.tLibraryMaster LM ON LM.Id=BL.LibraryId
	WHERE ((BL.ReaderSourceTypeId=@rReaderSourceTypeId) OR (@rReaderSourceTypeId=0))
		 AND BL.IsCurrentStatus=1
		AND ((BL.StatusId=521) OR (BL.StatusId=523))
		AND (BL.OrgId=@rOrgId)
		AND (BL.ReaderSourceId = @rEmployeeId)
	select isnull(@lBookgrid,'') as Bookgrid
END
GO
PRINT N'Creating [sMis].[pRptStudentBirthdayList]...';


GO

CREATE PROCEDURE [sMis].[pRptStudentBirthdayList]
	 
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 @rOrgMainGroupId int,
	 @rOrgSubGroupId int,
	 @rOrgGroupId int,
	 @rOrgId smallint,
	 @rOrgGroupBatchId int, 
	 @rDepartmentId int,
	 @rClassId int,
	 @rDivisionId int,
     @rStudentStatusId int=0,
	 @rMonth tinyint =0
		
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 

	SELECT  
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			SD.AcademicId,
			SD.StudentId, 
			SD.ClassId,
			SD.DivisionId,
			SD.ClassDivision,
			SD.Code,
			SD.RollNo,			
			SD.FirstName,
			SD.MiddleName,			
			SD.LastName,
			SD.Name,		
			SD.ClassName,
			SD.DivisionName,
			SD.StatusName,
			SD.StatusId,
			SD.LCProgress,
			SD.Religion,
			SD.FamilyCast,
			SD.FamilySubCast,
			SD.LCConduct,
			SD.BirthPlace,
			SD.BirthTaluka,
			SD.BirthDistrict,
			SD.LeftDate,
			SD.PreviousSchool,
			SD.DateOfBirth,
			SD.BirthDateInWord,
			SD.LeftReason,
			SD.AdmissionDate,
			SD.AdmissionStandard,
			SD.LeftStandard,
			SD.LCNumber,
			SD.LCDate,
			SD.StudentPhoto,
			SD.BloodGroup,
			SD.PresentAddress,
			SD.ContactNo,
			SD.Batch,
			SD.InactiveDate,
			OM.Title AS OrgName,
			SF.MotherName,
			SD.DivisionOrder,
			SD.Number AS StudentNumber,
			SF.FatherName,
			SD.Nationality,
			SD.MotherTongue,
			SD.BirthState,
			SD.BirthCountry,
			SD.SUId,
            SD.AdhaarNumber,
            SD.ClassStatusId,
            SD.ClassStatusName,
			SD.UIDNumber,
			SD.Gender,
			SF.FatherOfficeContactNo,
			SF.MotherOfficeContactNo,
			SD.OrgId
	FROM 
			sStudent.vStudentAllDetail SD
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=SD.OrgId
			LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId=SD.StudentId
			INNER JOIN sSetup.tBatchClass BC ON BC.ClassID =  SD.ClassID AND BC.BatchId = SD.BatchId 
			LEFT JOIN sStudent.tStudentAdmission SAM ON SD.StudentId=SAM.StudentId
			--AND ((SAM.AdmissionDate>=@rFromAdmissionDate)OR(ISNULL(@rFromAdmissionDate,'')=''))    
			--AND ((SAM.AdmissionDate<=@rToAdmissionDate)OR(ISNULL(@rToAdmissionDate,'')=''))  
			--AND	SAM.BatchId = @rBatchId   
	WHERE 
		((SD.OrgId=@rOrgId) OR (@rOrgId=0))
		--AND (ISNULL(SD.Code,0) IN( SELECT cast(item as nvarchar(20)) FROM  sCommon.fnsplit(@rStrCode,',')) OR @rStrCode='') 
		And ((SD.ClassId=@rClassId) OR (@rClassId=0))
		AND ((SD.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		--AND ((SD.StudentId=@rStudentId) OR (@rStudentId=0))
		--AND ((SD.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
		--AND ((SD.RollNo <= @rToRollNo) OR (@rToRollNo=0))
		--AND ((SD.StatusId=@rStatusId)OR(@rStatusId=0))
		--AND ((SD.ClassStatusId=@rClassStatusId) OR (@rClassStatusId=0))
		--AND ((MONTH(SD.DateOfBirth)=@rDateOfBirth OR @rDateOfBirth=0))
	    AND ((SD.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
	 --   AND((SD.Code>=@rFromStudentCode) OR (ISNULL(@rFromStudentCode,'')=''))
	 --   AND((SD.Code<=@rToStudentCode) OR (ISNULL(@rToStudentCode,'')=''))
		--AND((SD.Number>=@rFromNumber) OR (ISNULL(@rFromNumber,0)=0))
	 --   AND((SD.Number<=@rToNumber) OR (ISNULL(@rToNumber,0)=0))
	   And (Month(SD.DateOfBirth)=@rMonth OR @rMonth = 0)
	 Order by
	 SD.RollNo
END
GO
PRINT N'Creating [sTimetable].[pExportTimeTableGet]...';


GO
 
 CREATE PROCEDURE [sTimetable].[pExportTimeTableGet]
 
	@rOrgGroupBatchId int=0,
	@rTimeTableSchemaId int=0,
	@rOrgId int=0,
	@rDivisionId int = 0

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON 

BEGIN    
SELECT 	 
	ISNULL(DV.Code,'') AS Division,
	ISNULL(DayId,0) AS Day,
	ISNULL(SM.Title,'') AS Subject,
	ISNULL(LectureNumber,'') AS Period,
	 ISNULL(EM.Code,'') as EmployeeCode
	FROM 
	sTimetable.tTimeTable TT  
	INNER JOIN sSetup.tSubjectMaster SM ON SM.Id = TT.SubjectId 
	INNER JOIN sHrm.tEmployeeMaster EM ON Em.Id = TT.EmployeeId
	--INNER JOIN sCommon.tDayMaster DM ON DM.Id = TT.DayId
	INNER JOIN sSetup.tDivisionMaster DV ON DV.Id = TT.DivisionId
	Inner Join sTimetable.tTimeTableSchema TS On TS.Id=TT.TimeTableSchemaId
	--INNER JOIN sSetup.tClassMaster CL ON CL.Id = DV.ClassId
	
	WHERE
	 TT.TimeTableSchemaId=@rTimeTableSchemaId 
	   AND (Ts.OrgGroupBatchId=@rOrgGroupBatchId)
	   AND ((DV.OrgId=@rOrgId) OR (@rOrgId=0))
	   AND  ISNULL(EM.IsOtherUser,0) = 0
	   AND (TT.DivisionId=@rDivisionId or @rDivisionId=0)
	

END
GO
PRINT N'Creating [sTransport].[pRptTransportDivisionwiseStudentListAmountWiseGet]...';


GO
CREATE PROCEDURE [sTransport].[pRptTransportDivisionwiseStudentListAmountWiseGet]	 
	 @rOrgGroupBatchId int=0,
	 @rOrgId int=0,
	 @rDepartmentId int=0,
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 @rClassId int=0,
	 @rDivisionId int=0,
	 @rRouteId int=0,
	 @rDestinationId int=0,
	 @rTransportId int =0,
	 @rDropDestinationId int=0,
	 @rDropBusRouteId int=0,
	 @rStatusId int=0,
	 @rStrRouteId nvarchar(500)=null,
	 @rDestinationTitle nvarchar(50)=null,
	 @rIsWithDetail bit
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
BEGIN 
	SELECT DISTINCT * FROM 
	(
		SELECT 
	        @rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			AR.SourceId,
			SM.Code,
			SM.FirstName+' '+SM.LastName AS Name,
			DM.Id AS DivisionId,
			CM.DisplayTitle AS Class,
			DM.DisplayTitle AS Division,
			CM.DisplayTitle+' - '+DM.DisplayTitle AS ClassDivision,
			BRDM.Title AS DestinationPoint,
			BRM.Id AS BusRouteId,
			BRM.Title AS BusRoute,
			A.RollNo,
			VM.Title AS Vehicle,
			VM.NoOfSeats,
			BRM.OrderIndex AS RouteOrder,
			BRDM.OrderIndex AS PickupOrder,
			DM.OrderIndex AS DivisionOrderIndex,
			OM.Id AS OrgId,
			OM.DisplayTitle AS OrganizationName,
			DMast.Id AS DepartmentId,
			DMast.Title AS DepartmentName,
			SC.ParentContactNo AS ParentContactNo,
			ISNULL(SC.PresentStreetone,'')+' '+ISNULL(SC.PresentStreetTwo,'')+' '+ISNULL(SC.PresentStreetThree,'')+' '+ISNULL(SC.PresentCity,'')+' '+ISNULL(SC.PresentState,'')+' '+ISNULL(SC.PresentZipCode,'') AS PresentAddress,
			ISNULL(VM.RegistrationNumber,'') AS RegistrationNumber,
			ISNULL(BRM.DriverName,'') AS DriverName,
			ISNULL(BRM.DriverMobileNo,'') AS DriverMobileNo,
			ISNULL(BRM.ConductorName,'') AS ConductorName,
			ISNULL(BRM.ConductorMobileNo,'') AS ConductorMobileNo,
			BRDM.Amount,
			ISNULL(BRM1.DriverName,'') AS DropRoutDriverName,
			ISNULL(BRM1.DriverMobileNo,'') AS DropRoutDriverMobileNo,
			ISNULL(BRM1.ConductorName,'') AS DropRoutConductorName,
			ISNULL(BRM1.ConductorMobileNo,'') AS DropRoutConductorMobileNo,
			BRM1.Id AS DropRoutBusRouteId,
			BRM1.Title AS DropRoutBusRoute,
			ISNULL(VM1.RegistrationNumber,'') AS DropRoutRegistrationNumber,
			VM1.Title AS DropRoutVehicle,
			VM1.NoOfSeats AS DropRoutVehicleNoOfSeats,
			BRM1.OrderIndex AS DropRoutRouteOrder,
			BRDM1.OrderIndex AS DropRoutOrder,
			BRDM1.Title AS DropDestinationPoint ,
			BRDM1.DropTime,
			BRDM.PickUpTime,
			@rIsWithDetail As WithDetails,
			BRDM1.Amount AS DropRoutAmount
			
		FROM 
			sTransport.tAssignRoute AR
			INNER JOIN sStudent.tAcademic A ON A.StudentId=AR.SourceId
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId 
			INNER JOIN sStudent.tStudentMaster SM ON A.StudentId=SM.Id 
			LEFT JOIN sStudent.tStudentCommunication SC ON A.StudentId=SC.StudentId AND SM.StatusId=1
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id
			INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=A.OrgId
			INNER JOIN sSetup.tDepartmentMaster DMast ON DMast.Id=CM.DepartmentId
			INNER JOIN sTransport.tBusRouteDestinationMaster BRDM ON BRDM.Id=AR.PickupDestinationId
			INNER JOIN sTransport.tBusRouteMaster BRM ON BRM.Id=BRDM.BusRouteId
			LEFT JOIN sTransport.tVehicleMaster VM ON VM.Id=BRM.VehicleId
			LEFT JOIN sTransport.tBusRouteDestinationMaster BRDM1 ON BRDM1.Id=AR.DropDestinationId 
			LEFT JOIN sTransport.tBusRouteMaster BRM1 ON BRM1.Id=BRDM1.BusRouteId AND (BRM1.OrgGroupBatchId=@rOrgGroupBatchId)
			INNER JOIN sSetup.tBatchMaster BMM ON BMM.OrgGroupBatchId = BRM.OrgGroupBatchId AND BMM.Id = A.BatchId 
			LEFT JOIN sTransport.tVehicleMaster VM1 ON VM1.Id=BRM1.VehicleId
		WHERE 
			--((AR.SourceId=@rAcademicId) OR (@rAcademicId=0))
			(BRM.OrgGroupBatchId=@rOrgGroupBatchId)
			AND BM.OrgGroupBatchId = @rOrgGroupBatchId
			AND ((OM.Id=@rOrgId) OR (@rOrgId=0))
			AND ((DMast.Id=@rDepartmentId) OR (@rDepartmentId=0))
			AND ((CM.Id=@rClassId) OR (@rClassId=0))
			AND ((DM.Id=@rDivisionId) OR (@rDivisionId=0))
			AND ((BRM.Id=@rRouteId) OR (@rRouteId=0))
			AND ((BRM.TransportId=@rTransportId) OR (@rTransportId=0))
			AND ((BRDM.Id=@rDestinationId) OR (@rDestinationId=0))
			AND ((BRDM1.BusRouteId=@rDropBusRouteId) OR (@rDropBusRouteId=0))
			AND ((BRDM1.Id=@rDropDestinationId) OR (@rDropDestinationId=0))
			AND ((SM.StatusId = @rStatusId) OR (@rStatusId=0))
			AND BMM.IsInContext = 1
			AND (BRM.Id IN (SELECT item from sCommon.fnSplit(@rStrRouteId,',')) OR ISNULL(@rStrRouteId,'') = '')
			AND (BRDM.Title Like @rDestinationTitle OR ISNULL(@rDestinationTitle,'') = '')

		--UNION ALL 

		--SELECT 
	 --       @rBuilder1 AS Builder1,
		--	@rBuilder2 AS Builder2,
		--	AR.SourceId,
		--	SM.Code,
		--	SM.FirstName+' '+SM.LastName AS Name,
		--	DM.Id AS DivisionId,
		--	CM.DisplayTitle AS Class,
		--	DM.DisplayTitle AS Division,
		--	CM.DisplayTitle+' - '+DM.DisplayTitle AS ClassDivision,
		--	BRDM.Title AS DestinationPoint,
		--	BRM.Id AS BusRouteId,
		--	BRM.Title AS BusRoute,
		--	A.RollNo,
		--	VM.Title AS Vehicle,
		--	VM.NoOfSeats,
		--	BRM.OrderIndex AS RouteOrder,
		--	BRDM.OrderIndex AS PickupOrder,
		--	DM.OrderIndex AS DivisionOrderIndex,
		--	OM.Id AS OrgId,
		--	OM.DisplayTitle AS OrganizationName,
		--	DMast.Id AS DepartmentId,
		--	DMast.Title AS DepartmentName,
		--	SC.ParentContactNo AS ParentContactNo,
		--	ISNULL(SC.PresentStreetone,'')+' '+ISNULL(SC.PresentStreetTwo,'')+' '+ISNULL(SC.PresentStreetThree,'')+' '+ISNULL(SC.PresentCity,'')+' '+ISNULL(SC.PresentState,'')+' '+ISNULL(SC.PresentZipCode,'') AS PresentAddress,
		--	ISNULL(VM.RegistrationNumber,'') AS RegistrationNumber,
		--	ISNULL(BRM.DriverName,'') AS DriverName,
		--	ISNULL(BRM.DriverMobileNo,'') AS DriverMobileNo,
		--	ISNULL(BRM.ConductorName,'') AS ConductorName,
		--	ISNULL(BRM.ConductorMobileNo,'') AS ConductorMobileNo,
		--	BRDM.Amount,
		--	ISNULL(BRM1.DriverName,'') AS DropRoutDriverName,
		--	ISNULL(BRM1.DriverMobileNo,'') AS DropRoutDriverMobileNo,
		--	ISNULL(BRM1.ConductorName,'') AS DropRoutConductorName,
		--	ISNULL(BRM1.ConductorMobileNo,'') AS DropRoutConductorMobileNo,
		--	BRM1.Id AS DropRoutBusRouteId,
		--	BRM1.Title AS DropRoutBusRoute,
		--	ISNULL(VM1.RegistrationNumber,'') AS DropRoutRegistrationNumber,
		--	VM1.Title AS DropRoutVehicle,
		--	VM1.NoOfSeats AS DropRoutVehicleNoOfSeats,
		--	BRM1.OrderIndex AS DropRoutRouteOrder,
		--	BRDM1.OrderIndex AS DropRoutOrder,
		--	BRDM1.Title AS DropDestinationPoint ,
		--	BRDM1.DropTime,
		--	BRDM.PickUpTime,
		--	@rIsWithDetail As WithDetails,
		--	BRDM1.Amount AS DropRoutAmount
			
		--FROM 
		--	sTransport.tAssignRoute AR
		--	INNER JOIN sStudent.tAcademic A ON A.StudentId=AR.SourceId
		--	INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId 
		--	INNER JOIN sStudent.tStudentMaster SM ON A.StudentId=SM.Id 
		--	LEFT JOIN sStudent.tStudentCommunication SC ON A.StudentId=SC.StudentId AND SM.StatusId=1
		--	INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id
		--	INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId
		--	INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=A.OrgId
		--	INNER JOIN sSetup.tDepartmentMaster DMast ON DMast.Id=CM.DepartmentId
		--	INNER JOIN sTransport.tBusRouteDestinationMaster BRDM ON BRDM.Id=AR.DropDestinationId
		--	INNER JOIN sTransport.tBusRouteMaster BRM ON BRM.Id=BRDM.BusRouteId
		--	LEFT JOIN sTransport.tVehicleMaster VM ON VM.Id=BRM.VehicleId
		--	LEFT JOIN sTransport.tBusRouteDestinationMaster BRDM1 ON BRDM1.Id=AR.PickupDestinationId
		--	LEFT JOIN sTransport.tBusRouteMaster BRM1 ON BRM1.Id=BRDM1.BusRouteId AND (BRM1.OrgGroupBatchId=@rOrgGroupBatchId)
		--	INNER JOIN sSetup.tBatchMaster BMM ON BMM.OrgGroupBatchId = BRM.OrgGroupBatchId AND BMM.Id = A.BatchId 
		--	LEFT JOIN sTransport.tVehicleMaster VM1 ON VM1.Id=BRM1.VehicleId
		--WHERE 
		--	--((AR.SourceId=@rAcademicId) OR (@rAcademicId=0))
		--	(BRM.OrgGroupBatchId=@rOrgGroupBatchId)
		--	AND BM.OrgGroupBatchId = @rOrgGroupBatchId
		--	AND ((OM.Id=@rOrgId) OR (@rOrgId=0))
		--	AND ((DMast.Id=@rDepartmentId) OR (@rDepartmentId=0))
		--	AND ((CM.Id=@rClassId) OR (@rClassId=0))
		--	AND ((DM.Id=@rDivisionId) OR (@rDivisionId=0))
		--	AND ((BRM.Id=@rRouteId) OR (@rRouteId=0))
		--	AND ((BRM.TransportId=@rTransportId) OR (@rTransportId=0))
		--	AND ((BRDM.Id=@rDestinationId) OR (@rDestinationId=0))
		--	AND ((BRDM1.BusRouteId=@rDropBusRouteId) OR (@rDropBusRouteId=0))
		--	AND ((BRDM1.Id=@rDropDestinationId) OR (@rDropDestinationId=0))
		--	AND ((SM.StatusId = @rStatusId) OR (@rStatusId=0))
		--	AND BMM.IsInContext = 1
		--	AND (BRM.Id IN (SELECT item from sCommon.fnSplit(@rStrRouteId,',')) OR ISNULL(@rStrRouteId,'') = '')
		--	AND (BRDM.Title Like @rDestinationTitle OR ISNULL(@rDestinationTitle,'') = '')
	) A
END
GO
 
  

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