

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



GO
PRINT N'Altering Table [sAssessment].[tTempAllExam]...';


GO
ALTER TABLE [sAssessment].[tTempAllExam] ALTER COLUMN [ObtainedMaximum1] DECIMAL (10, 2) NULL;

ALTER TABLE [sAssessment].[tTempAllExam] ALTER COLUMN [ObtainedMaximum2] DECIMAL (10, 2) NULL;

ALTER TABLE [sAssessment].[tTempAllExam] ALTER COLUMN [ObtainedMaximum3] DECIMAL (10, 2) NULL;

ALTER TABLE [sAssessment].[tTempAllExam] ALTER COLUMN [ObtainedMaximum4] DECIMAL (10, 2) NULL;


GO
ALTER TABLE [sAssessment].[tTempAllExam]
    ADD [FeeCategory]       NVARCHAR (100)  NULL,
        [StudentContactNo]  NVARCHAR (50)   NULL,
        [ObtainedMaximum5]  DECIMAL (10, 2) NULL,
        [ObtainedMaximum6]  DECIMAL (10, 2) NULL,
        [ObtainedMaximum7]  DECIMAL (10, 2) NULL,
        [ObtainedMaximum8]  DECIMAL (10, 2) NULL,
        [ObtainedMaximum9]  DECIMAL (10, 2) NULL,
        [ObtainedMaximum10] DECIMAL (10, 2) NULL,
        [ObtainedMaximum11] DECIMAL (10, 2) NULL,
        [ObtainedMaximum12] DECIMAL (10, 2) NULL,
        [ObtainedMaximum13] DECIMAL (10, 2) NULL;


GO
PRINT N'Altering Table [sHrm].[tEmployeeStatutoryAndOther]...';


GO
ALTER TABLE [sHrm].[tEmployeeStatutoryAndOther]
    ADD [PayTypeId] TINYINT NULL;


GO
PRINT N'Altering Table [sPayroll].[tPayProcessEmployeeRemark]...';


GO
ALTER TABLE [sPayroll].[tPayProcessEmployeeRemark]
    ADD [PayTypeId] TINYINT       NULL,
        [ChequeNo]  NVARCHAR (40) NULL,
        [PayDate]   DATE          NULL;


GO
PRINT N'Altering Table [sSetup].[tOrgGroupEIS]...';


GO
ALTER TABLE [sSetup].[tOrgGroupEIS]
    ADD [Title] NVARCHAR (MAX) NULL;


GO

PRINT N'Altering View [sCertificate].[vPrintTemplateStudentBasicDetails]...';


GO
ALTER VIEW [sCertificate].[vPrintTemplateStudentBasicDetails]
AS
	SELECT 
	  [sStudent].[fStudentNameGet](SM.FirstName , SM.MiddleName, SM.LastName,OM.StudentNameFormatId ) AS StudentName,
	  SM.Code,	
	  DM.Code AS ClassDivision,
	  A.RollNo,
	  BM.Title AS BatchName,
	  SO.DateOfBirth AS DateOfBirth, 
	  GetDate() AS PrintDate, 	-- Change for Mantis id 29447 and also added in below row "[PrintDate]" 
	  '[BatchName],[ClassDivision],[Code],[DateOfBirth],[RollNo],[FirstName],[MiddleName],
	  [LastName],[PreviousSchool],[Gender],[Caste],[SubCaste],[BirthPlace],[DOBInWords],[PreviousSchoolYear],
	  [OldGRNo],[PreviousLCDate],[PreviousLCResult],[PreviousLCNumber],[PreviousStandard],
	  [BirthTaluka],[BirthState],[BirthCountry],[BirthDistrict],[Address],[ContactNo],[Email],[Religion],[FamilyCaste],[CasteCategory],[Nationality],[MotherTongue],[BloodGroup],[AadhaarNumber],[PhysicalCategory],
	  [FatherName],[FatherQualification],[FatherOccupation],[FatherContactNo],[FatherOfficeAddress],[FatherEmail],[FatherExStudent],[FatherPassingYear],[FatherIncome],
	  [MotherName],[MotherQualification],[MotherOccupation],[MotherContactNo],[MotherOfficeAddress],[MotherEmail],[MotherExStudent],[MotherPassingYear],[MotherIncome],
	  [AdmissionDate],[AdmissionStandard],[ClassName],[UIDNumber],[BankHolderName],[BankName],[BankBranch],[BankIFSCcode],[BankAccountNo],[StudentPhoto],[WhatsAppContactNo],[PrintDate],[SUIDNumber]' As ColumnList
	  --Manits: 31034, add SUIDNumber in ColumnList
  FROM 
	sStudent.tAcademic A
	INNER JOIN sStudent.tStudentMaster SM
		ON A.StudentId=SM.Id
	INNER JOIN sStudent.tStudentAdmission SA
		ON SA.StudentId=SM.Id	
	INNER JOIN sSetup.tClassMaster CM
		ON CM.Id=A.ClassId
	INNER JOIN sSetup.tDivisionMaster DM
		ON DM.Id=A.DivisionId
	INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId 
	INNER JOIN sStudent.tStatusMaster STM
		ON STM.Id=SM.StatusId
	INNER JOIN sSetup.tDepartmentMaster DeptM
		ON DeptM.Id=CM.DepartmentId
	INNER JOIN sSetup.tOrganizationMaster OM 
	    ON A.OrgId = OM.Id
	INNER JOIN [sStudent].[tStudentOther] SO
	    ON SO.StudentId=SM.Id
GO
PRINT N'Altering View [sCertificate].[vPrintTemplateStudentDetail]...';


GO
ALTER VIEW [sCertificate].[vPrintTemplateStudentDetail]
 
AS  
  
SELECT 
			A.Id AS AcademicId,
		    DivM.Id AS DivisionId,
		    DivM.DisplayTitle AS DivisionName,
		    CM.Id AS ClassId,
		    CM.DisplayTitle AS ClassName,
		    CM.DisplayTitle+'-'+DivM.DisplayTitle AS ClassDivision,
		    DM.Id AS DepartmentId,
		    DM.DisplayTitle AS DepartmentName,
		    SM.FirstName AS FirstName,
		    SM.MiddleName AS MiddleName,
		    SM.LastName AS LastName,
		    SM.Code,
		    A.RollNo,
		    A.BatchId,
		    BM.Title AS BatchName,
		    CONVERT(VARCHAR(10),SO.DateOfBirth,103) AS DateOfBirth,
		    SA.PreviousSchool,
			ISNULL(GM.Title,'') AS Gender,
			SO.FamilyCast AS Caste,  
			SO.FamilySubCast AS SubCaste,
			SO.BirthPlace,
			SO.BirthDateInWord AS DOBInWords,
			SA.PreviousLCDate AS PreviousLCDate,
			SA.PreviousLCResult AS PreviousLCResult,
			SA.PreviousLCNumber AS PreviousLCNumber,
			SA.AdmissionNumber AS OldGRNo,
			SA.PassingYear AS PreviousSchoolYear,			
			SA.PreviousStandard AS PreviousStandard,
			SO.BirthTaluka AS BirthTaluka,
			SO.BirthState AS BirthState,
			SO.BirthCountry AS BirthCountry,
			SO.BirthDistrict AS BirthDistrict,
			ISNULL(SC.PresentStreetOne,'')+' '+ISNULL(SC.PresentStreetTwo,'')+' '+ISNULL(SC.PresentStreetThree,'')+' '+ISNULL(SC.PresentCity,'')+' '+ISNULL(SC.PresentState,'')+' '+ISNULL(SC.PresentZipCode,'') AS Address,
			SC.ParentContactNo AS ContactNo,		
			SC.ParentEmail AS Email,
			ISNULL(RM.Title,'') AS Religion,
			SO.FamilyCast AS FamilyCaste,
			ISNULL(CCM.Title,'') AS CasteCategory,
			ISNULL(NM.Title,'') AS Nationality,
			ISNULL(SO.MotherTongue,'') AS MotherTongue,
			ISNULL(BGM.Title,'') As BloodGroup,
			ISNULL(SO.AdhaarNumber,'') AS AadhaarNumber,
			ISNULL(PDCM.Title,'') AS PhysicalCategory,
			SF.FatherName AS FatherName,
			SF.FatherQualification AS FatherQualification,
			SF.FatherOccupation AS FatherOccupation,
			SF.FatherContactNo AS FatherContactNo,
			SF.FatherOfficeAddress AS FatherOfficeAddress,
			SF.FatherMail AS FatherEmail,
			SF.IsFatherExStudent AS FatherExStudent,
			SF.FatherPassOutYear AS FatherPassingYear,
			SF.FatherIncome AS FatherIncome,
			SF.MotherName AS MotherName,
			SF.MotherQualification AS MotherQualification,
			SF.MotherOccupation AS MotherOccupation,
			SF.MotherContactNo AS MotherContactNo,
			SF.MotherOfficeAddress AS MotherOfficeAddress,
			SF.MotherMail AS MotherEmail,
			SF.IsMotherExStudent AS MotherExStudent,
			SF.MotherPassOutYear AS MotherPassingYear,
			SF.MotherIncome AS MotherIncome,
			SA.AdmissionDate AS AdmissionDate,
			CM1.Title AS AdmissionStandard,
			SO.UIDNumber AS UIDNumber,
			ISNULL(StuA.BankAccountHolderName,'') AS BankHolderName,
			ISNULL(StuA.BankName,'') AS BankName,
			ISNULL(StuA.BankBranch,'') AS BankBranch,
			ISNULL(StuA.BankIFSCcode,'') AS BankIFSCcode,
			ISNULL(StuA.BankAccountNumber,'') AS BankAccountNo,
			ISNULL(SI.StudentPhoto, CONVERT(VARBINARY(MAX), 0)) AS StudentPhoto,
			ISNULL(SC.WhatsAppContactNo,'') AS WhatsAppContactNo,
			GetDate() AS PrintDate, -- Change for Mantis id 29447 added "[PrintDate]"
			SM.SUId AS SUIDNumber	--Add for Manits: 31034

	FROM 
			sStudent.tAcademic A
			INNER JOIN sStudent.tStudentMaster SM ON SM.Id=A.StudentId
			INNER JOIN sStudent.tStudentOther SO ON SO.StudentId=SM.Id
			INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId
			INNER JOIN sSetup.tDivisionMaster DivM ON DivM.Id=A.DivisionId
			INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id = CM.DepartmentId
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId
			LEFT JOIN sStudent.tStudentAdmission SA ON SA.StudentId=A.StudentId
			LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId = A.StudentId
			LEFT JOIN sCommon.tBloodGroupMaster BGM ON BGM.Id=SO.BloodGroupId
			LEFT JOIN sCommon.tCastCategoryMaster CCM  ON CCM.Id=SO.CastCategoryId
			LEFT JoIN sCommon.tReligionMaster RM ON RM.Id=SO.ReligionId
			LEFT JOIN sCommon.tMotherTongueMaster MT ON MT.Id = SO.MotherTongueId
			LEFT JOIN sCommon.tCountryMaster NM ON NM.Id = SO.NationalityId
			LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId = A.StudentId
			LEFT JOIN sStudent.tStudentHealth SH ON SH.StudentId = A.StudentId
			LEFT JOIN sCommon.tPhysicalDisabilityCategoryMaster PDCM ON PDCM.Id = SH.PhysicalDisabilityCategoryId
			LEFT JOIN sCommon.tGenderMaster GM ON GM.Id = SO.GenderId
			LEFT JOIN sSetup.tClassMaster CM1 ON CM1.Id=SA.AdmissionStandardId
			LEFT JOIN sStudent.tStudentAdditional StuA ON StuA.StudentId = SM.Id
			LEFT JOIN sStudent.tStudentImages SI ON SM.Id = SI.StudentId
GO
PRINT N'Creating Function [sAttendance].[fAttendanceWithRemarkGet]...';


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


GO

 
ALTER PROCEDURE [sHrm].[pEmployeeDataModify]	 
	@rCategoryId int,
	@rXML nvarchar(max),
	@rSubCategoryField nvarchar(100),
	@rOrgGroupId int = 0
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
DECLARE @lInterrorCode INT
Declare @Sql nvarchar(max) 
DECLARE @loDoc INT

--BEGIN TRY
--BEGIN TRANSACTION

EXEC sp_xml_preparedocument @loDoc OUTPUT,@rXML
BEGIN
	
	IF(@rSubCategoryField = 'Gender' OR @rSubCategoryField = 'Religion' OR @rSubCategoryField = 'BloodGroup'
	OR @rSubCategoryField = 'MaritalStatus' OR @rSubCategoryField = 'OrganizationDepartment' OR @rSubCategoryField = 'EmployeeType' OR @rSubCategoryField = 'EmployeeBusinessHead'
			OR @rSubCategoryField = 'EmployeeGroup' OR @rSubCategoryField = 'EmployeeGrade' OR @rSubCategoryField = 'Relationship' OR  @rSubCategoryField = 'EmployeeDesignation'
			OR  @rSubCategoryField = 'Payroll' OR  @rSubCategoryField = 'PayrollGroup'  OR  @rSubCategoryField = 'OrgGroupDepartment' OR  @rSubCategoryField = 'EmployeeManager' 
			OR @rSubCategoryField = 'Tribe'
			)
	BEGIN
		SET @rSubCategoryField = @rSubCategoryField + 'Id'
	END
	ELSE IF (@rSubCategoryField = 'CasteCategory' )
		BEGIN
			SET @rSubCategoryField = Replace(@rSubCategoryField,'Caste','Cast')+'Id'
		END
	ELSE IF(@rSubCategoryField = 'NotEmployee')
		 BEGIN
		 SET @rSubCategoryField = Replace(@rSubCategoryField,'NotEmployee','IsOtherUser')
		 END
	ELSE IF(@rSubCategoryField = 'PaymentMode')
		 BEGIN
		 SET @rSubCategoryField = Replace(@rSubCategoryField,'PaymentMode','PayTypeId')
		 END

	IF OBJECT_ID('ListofData') IS NOT NULL	
	BEGIN 
		DROP TABLE ListofData
	END	
	
	CREATE TABLE ListofData(Id bigint,EmployeeId bigint,SubCategory nvarchar(150),UpdatedUserId bigint,IsExist bit);
	
	IF(@rCategoryId= 1)
		BEGIN
		insert into ListofData
		select 0,E.EmployeeId,sSetup.fPortalXMLTagsReplaceReverse(E.SubCategory),E.UpdatedUserId,0
		from
		(
				SELECT EmployeeId,SubCategory,UpdatedUserId FROM
				OPENXML (@loDoc, '/Employees/Employees', 2)
				WITH (
						EmployeeId BIGINT, 
						SubCategory nvarchar(150),
						UpdatedUserId bigint)	
						)E 	
		UPDATE ListofData SET IsExist=1 WHERE EmployeeId NOT IN(SELECT EmployeeId FROM sHrm.tEmployeeCommunications) 
		
		set @sql='INSERT INTO sHrm.tEmployeeCommunications 
					(EmployeeId,'+@rSubCategoryField+',CreatedUserId,CreatedDateTime)
					SELECT
						LD.EmployeeId,Ld.SubCategory,LD.UpdatedUserId,sCommon.fGetDate()
					FROM
						ListofData LD WHERE LD.IsExist=1'
		Exec sp_executesql @sql
		set @sql='UPDATE sHrm.tEmployeeCommunications set '+@rSubCategoryField+' = LD.SubCategory,
					UpdatedUserId=LD.UpdatedUserId,
					UpdatedDateTime=sCommon.fGetDate()  
					from sHrm.tEmployeeCommunications EC 
					INNER JOIN ListofData LD ON EC.EmployeeId=LD.EmployeeId AND IsExist=0'
		
		Exec sp_executesql @sql
		
		
		
		Drop Table ListofData
			 SELECT 1 AS StatusId
	    END
	    
	Else IF(@rCategoryId= 2)
		BEGIN
		insert into ListofData
		select 0,E.EmployeeId,sSetup.fPortalXMLTagsReplaceReverse(E.SubCategory),E.UpdatedUserId,0
		from
		(
				SELECT EmployeeId,SubCategory,UpdatedUserId FROM
				OPENXML (@loDoc, '/Employees/Employees', 2)
				WITH (
						EmployeeId BIGINT, 
						SubCategory nvarchar(100),
						UpdatedUserId bigint)	
						)E 	
		UPDATE ListofData SET IsExist=1 WHERE EmployeeId NOT IN(SELECT EmployeeId FROM sHrm.tEmployeePersonalDetail) 
		
		IF(@rSubCategoryField = 'DateOfBirth')
		BEGIN			
					
			 				
			set @sql='UPDATE sHrm.tEmployeePersonalDetail set '+@rSubCategoryField+' = LD.SubCategory,
						UpdatedUserId=LD.UpdatedUserId,
						UpdatedDateTime=sCommon.fGetDate()  
						from sHrm.tEmployeePersonalDetail EPD 
						INNER JOIN ListofData LD ON EPD.EmployeeId=LD.EmployeeId'			
			Exec sp_executesql @sql
			set @sql='UPDATE sHrm.tEmployeePersonalDetail SET '+@rSubCategoryField+' = null WHERE DateOfBirth=''1900-01-01'''
			Exec sp_executesql @sql
		END
		ELSE
		BEGIN
			
			 				
			set @sql='UPDATE sHrm.tEmployeePersonalDetail set '+@rSubCategoryField+' = LD.SubCategory,
						UpdatedUserId=LD.UpdatedUserId,
						UpdatedDateTime=sCommon.fGetDate()  
						from sHrm.tEmployeePersonalDetail EPD 
						INNER JOIN ListofData LD ON EPD.EmployeeId=LD.EmployeeId'
			
			Exec sp_executesql @sql
		END
		Drop Table ListofData
			 SELECT 1 AS StatusId
	    END	
	    
	Else IF(@rCategoryId= 3)
	
		BEGIN
	 
		insert into ListofData
		select 0,E.EmployeeId,sSetup.fPortalXMLTagsReplaceReverse(E.SubCategory),E.UpdatedUserId,0
		from
		(
				SELECT EmployeeId,SubCategory,UpdatedUserId FROM
				OPENXML (@loDoc, '/Employees/Employees', 2)
				WITH (
						EmployeeId BIGINT, 
						SubCategory nvarchar(100),
						UpdatedUserId bigint)	
						)E 	

		IF(@rSubCategoryField = 'EmployeeManagerId' )
			BEGIN

		set @sql='UPDATE sHrm.tEmployeeJobDetail set '+@rSubCategoryField+' = (SELECT EmployeeId FROM sHrm.vExtEmployeeMaster WHERE EmployeeId=LD.SubCategory AND ISNULL(IsOtherUser,0) = 0 ),
				  UpdatedUserId=LD.UpdatedUserId,
				  UpdatedDateTime=sCommon.fGetDate()  
				  from sHrm.tEmployeeJobDetail EJ	
				  INNER JOIN ListofData LD ON LD.EmployeeId=EJ.EmployeeId'
				  Exec sp_executesql @sql
		END

		ELSE
		BEGIN
	
		set @sql='UPDATE sHrm.tEmployeeJobDetail set '+@rSubCategoryField+' = LD.SubCategory,
					UpdatedUserId=LD.UpdatedUserId,
					UpdatedDateTime=sCommon.fGetDate()  
					from sHrm.tEmployeeJobDetail EJ 
					INNER JOIN ListofData LD ON EJ.EmployeeId=LD.EmployeeId'
		
		Exec sp_executesql @sql
		END
		IF(@rSubCategoryField = 'DateOfJoining' )
		BEGIN
		SET @sql='UPDATE sHrm.tEmployeeJobDetail SET '+@rSubCategoryField+' = null WHERE DateOfJoining=''1900-01-01'''
			Exec sp_executesql @sql
		END
		
		IF(@rSubCategoryField = 'DateOfleaving' )
		BEGIN
		SET @sql='UPDATE sHrm.tEmployeeJobDetail SET '+@rSubCategoryField+' = null WHERE DateOfleaving=''1900-01-01'''
			Exec sp_executesql @sql
		END		
		IF(@rSubCategoryField = 'PermanentDate' )
		BEGIN
		SET @sql='UPDATE sHrm.tEmployeeJobDetail SET '+@rSubCategoryField+' = null WHERE PermanentDate=''1900-01-01'''
			Exec sp_executesql @sql
		END	
		IF(@rSubCategoryField = 'ProbationUptoDate' )
		BEGIN

		SET @sql='UPDATE sHrm.tEmployeeJobDetail SET '+@rSubCategoryField+' = null WHERE ProbationUptoDate=''1900-01-01'''
			Exec sp_executesql @sql
		END	
		IF(@rSubCategoryField = 'AhdocUptoDate' )
		BEGIN
		SET @sql='UPDATE sHrm.tEmployeeJobDetail SET '+@rSubCategoryField+' = null WHERE AhdocUptoDate=''1900-01-01'''
			Exec sp_executesql @sql
		END
		IF(@rSubCategoryField = 'DateOfResignation' )
		BEGIN
		SET @sql='UPDATE sHrm.tEmployeeJobDetail SET '+@rSubCategoryField+' = null WHERE DateOfResignation=''1900-01-01'''
			Exec sp_executesql @sql
		END		
		Drop Table ListofData
			 SELECT 1 AS StatusId
	    END	
  Else IF(@rCategoryId= 4)
	BEGIN
		
		
		IF(@rSubCategoryField = 'CustomTag')
		BEGIN
		insert into ListofData
		select 0,E.EmployeeId,sSetup.fPortalXMLTagsReplaceReverse(E.SubCategory),E.UpdatedUserId,0
		from
		(
				SELECT EmployeeId, SubCategory, UpdatedUserId FROM
				OPENXML (@loDoc, '/Employees/Employees', 2)
				WITH (
						EmployeeId BIGINT, 
						SubCategory nvarchar(100),
						UpdatedUserId bigint)	
						)E 	

		UPDATE ListofData SET IsExist=1 WHERE EmployeeId NOT IN(SELECT EmployeeId FROM sHrm.tEmployeeMaster WHERE  ISNULL(IsOtherUser,0) = 0 ) 

			 
			DELETE FROM sHrm.tEmployeeCustomTag WHERE EmployeeId In (SELECT EmployeeId FROM ListofData WHERE IsExist=0)
			set @sql = '
				        INSERT INTO sHrm.tEmployeeCustomTag (EmployeeId,CustomTagId)
						SELECT
							LD.EmployeeId,
							CTM.Id
						FROM sHrm.tCustomTagMaster CTM INNER JOIN ListofData LD ON CTM.Title = LD.SubCategory 
						INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id = LD.EmployeeId 
						INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = EM.OrgID 
						INNER JOIN sSetup.tOrgGroupMaster OGM ON OGM.Id = OM.OrgGroupId  
						WHERE IsExist = 0 AND CTM.OrgGroupId = OGM.Id'
			 
		END
		ELSE
		BEGIN
		insert into ListofData
		select 0,E.EmployeeId,sSetup.fPortalXMLTagsReplaceReverse(E.SubCategory),E.UpdatedUserId,0
		from
		(
				SELECT EmployeeId,SubCategory,UpdatedUserId FROM
				OPENXML (@loDoc, '/Employees/Employees', 2)
				WITH (
						EmployeeId BIGINT, 
						SubCategory nvarchar(100),
						UpdatedUserId bigint)	
						)E 	

		UPDATE ListofData SET IsExist=1 WHERE EmployeeId NOT IN(SELECT EmployeeId FROM sHrm.tEmployeeMaster WHERE  ISNULL(IsOtherUser,0) = 0 ) 
		set @sql='UPDATE sHrm.tEmployeeMaster set '+@rSubCategoryField+' = LD.SubCategory,
					UpdatedUserId=LD.UpdatedUserId,
					UpdatedDateTime=sCommon.fGetDate()  
					from sHrm.tEmployeeMaster HEM 
					INNER JOIN ListofData LD ON HEM.Id=LD.EmployeeId AND IsExist=0 AND ISNULL(HEM.IsOtherUser,0) = 0 ' 
		END
		Print @sql
		Exec sp_executesql @sql
		Drop Table ListofData
			SELECT 1 AS StatusId
	    END
	    
	    Else IF(@rCategoryId= 5)
		BEGIN
		insert into ListofData
		select 0,E.EmployeeId,sSetup.fPortalXMLTagsReplaceReverse(E.SubCategory),E.UpdatedUserId,0
		from
		(
				SELECT EmployeeId,SubCategory,UpdatedUserId FROM
				OPENXML (@loDoc, '/Employees/Employees', 2)
				WITH (
						EmployeeId BIGINT, 
						SubCategory nvarchar(100),
						UpdatedUserId bigint)	
						)E 
						
		UPDATE ListofData SET IsExist=1 WHERE EmployeeId NOT IN(SELECT EmployeeId FROM sHrm.tEmployeeStatutoryAndOther) 
		
		set @sql='INSERT INTO sHrm.tEmployeeStatutoryAndOther 
					(EmployeeId,'+@rSubCategoryField+',IsVPFDeduction,UpdatedUserId,UpdatedDateTime)
					SELECT
						LD.EmployeeId,Ld.SubCategory,0,LD.UpdatedUserId,sCommon.fGetDate()
					FROM
						ListofData LD WHERE LD.IsExist=1'
		Exec sp_executesql @sql			
		
		
		IF(@rSubCategoryField = 'EPFJoinDate')
		BEGIN			
		    set @sql='UPDATE sHrm.tEmployeeStatutoryAndOther set '+@rSubCategoryField+' = LD.SubCategory,
					UpdatedUserId=LD.UpdatedUserId,
					UpdatedDateTime=sCommon.fGetDate()  
					from sHrm.tEmployeeStatutoryAndOther ESO 
					INNER JOIN ListofData LD ON ESO.EmployeeId=LD.EmployeeId'			
			Exec sp_executesql @sql
			set @sql='UPDATE sHrm.tEmployeeStatutoryAndOther SET '+@rSubCategoryField+' = NULL WHERE EPFJoinDate=''1900-01-01'''
			Exec sp_executesql @sql
		END
		ELSE IF(@rSubCategoryField = 'IncrementDate')
		BEGIN			
		    set @sql='UPDATE sHrm.tEmployeeStatutoryAndOther set '+@rSubCategoryField+' = LD.SubCategory,
					UpdatedUserId=LD.UpdatedUserId,
					UpdatedDateTime=sCommon.fGetDate()  
					from sHrm.tEmployeeStatutoryAndOther ESO 
					INNER JOIN ListofData LD ON ESO.EmployeeId=LD.EmployeeId'			
			Exec sp_executesql @sql
			set @sql='UPDATE sHrm.tEmployeeStatutoryAndOther SET '+@rSubCategoryField+' = NULL WHERE IncrementDate=''1900-01-01'''
			Exec sp_executesql @sql
		END
			ELSE IF(@rSubCategoryField = 'RetirementDate')
		BEGIN			
		    set @sql='UPDATE sHrm.tEmployeeStatutoryAndOther set '+@rSubCategoryField+' = LD.SubCategory,
					UpdatedUserId=LD.UpdatedUserId,
					UpdatedDateTime=sCommon.fGetDate()  
					from sHrm.tEmployeeStatutoryAndOther ESO 
					INNER JOIN ListofData LD ON ESO.EmployeeId=LD.EmployeeId'			
			Exec sp_executesql @sql
			set @sql='UPDATE sHrm.tEmployeeStatutoryAndOther SET '+@rSubCategoryField+' = NULL WHERE RetirementDate=''1900-01-01'''
			Exec sp_executesql @sql
		END
		ELSE
		BEGIN
			set @sql='UPDATE sHrm.tEmployeeStatutoryAndOther set '+@rSubCategoryField+' = LD.SubCategory,
					UpdatedUserId=LD.UpdatedUserId,
					UpdatedDateTime=sCommon.fGetDate()  
					from sHrm.tEmployeeStatutoryAndOther ESO 
					INNER JOIN ListofData LD ON ESO.EmployeeId=LD.EmployeeId'

			Exec sp_executesql @sql
		END
		
		
		Drop Table ListofData
			 SELECT 1 AS StatusId
	    END	
	    
	    
END 
	--   COMMIT TRANSACTION
		
	--END TRY
	
	--BEGIN CATCH 
	--	ROLLBACK TRANSACTION
	--	Drop Table ListofData
	--	SELECT -1 AS Result
	--END CATCH
GO
PRINT N'Altering Procedure [sHrm].[pEmployeeStatutoryDetailAdd]...';


GO
ALTER PROCEDURE [sHrm].[pEmployeeStatutoryDetailAdd]

	       @rEmployeeId bigint,
	       @rAccountNumber nvarchar(20),
	       @rBankName nvarchar(200),
           @rBranch nvarchar(50),          
           @rEPFNumber nvarchar(50),
           @rPanNumber nvarchar(20),
           @rIsVPFDeduction bit,
           @rVPFContributionId tinyint,
           @rVPFContributionEffectiveFrom date,
           @rVPFPercentage decimal(5,2),
           @rVPFAmount decimal(22,6),
           @rESINumber nvarchar(20),        
           @rIFSCNumber nvarchar(50),           
           @rIncomeTaxStatusId int,
           @rUpdatedUserId bigint,            
           @rIncrementDate date,
           @rBasicPay decimal(12,2),
           @rPayrollId int,
           @rPayrollGroupId int,
           @rPayscale nvarchar(150)='',
           @rEPFJoinDate date = NULL,
           @rUAN nvarchar(20)='',
           @rRetirementDate date,
		   @rAccountHolderName nvarchar(300)='',
		   @rPayTypeId int = 0
           
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
BEGIN TRY
BEGIN TRANSACTION
	DECLARE @lNextNumber BIGINT 
 	  
IF NOT EXISTS(Select 1 From sHrm.tEmployeeStatutoryAndOther Where EmployeeId = @rEmployeeId)
   BEGIN
	INSERT INTO sHrm.tEmployeeStatutoryAndOther
           (
            [EmployeeId]
           ,[EPFNumber]
           ,[IsVPFDeduction]
           ,[VPFContributionId]
           ,[VPFContributionEffectiveFrom]
           ,[VPFPercentage]
           ,[VPFAmount]
           ,[ESINumber]
           ,[BankName]
           ,[Branch]
           ,[AccountNumber]
           ,[IFSCNumber]
           ,[PanNumber]
           ,[IncomeTaxStatusId]
           ,[UpdatedUserId]
           ,[UpdatedDateTime]
           ,[IncrementDate]
           ,[BasicPay]
           ,[PayrollId]
           ,[PayrollGroupId]
           ,[Payscale]
           ,[EPFJoinDate]
           ,[UAN]
           ,[RetirementDate]
		   ,[AccountHolderName]
		   ,[PayTypeId]
           )
     VALUES
           (
           @rEmployeeId,
           @rEPFNumber,
           @rIsVPFDeduction,
           @rVPFContributionId,
           @rVPFContributionEffectiveFrom,
           @rVPFPercentage,
           @rVPFAmount,
           @rESINumber,
           @rBankName,
           @rBranch,
           @rAccountNumber,
           @rIFSCNumber,
           @rPanNumber,
           @rIncomeTaxStatusId,
           @rUpdatedUserId,
           sCommon.fGetDate(),
           @rIncrementDate,
           @rBasicPay,
           @rPayrollId,
           @rPayrollGroupId,
           @rPayscale,
           @rEPFJoinDate,
           @rUAN,
           @rRetirementDate,
		   @rAccountHolderName,
		   @rPayTypeId
           )
     END
     ELSE
     BEGIN
      UPDATE sHrm.tEmployeeStatutoryAndOther
      SET 
		  [EPFNumber] = @rEPFNumber,
		  [IsVPFDeduction] = @rIsVPFDeduction, 
		  [VPFContributionId] = @rVPFContributionId, 
		  [VPFContributionEffectiveFrom] = @rVPFContributionEffectiveFrom, 
		  [VPFPercentage] = @rVPFPercentage, 
		  [VPFAmount] = @rVPFAmount, 
		  [ESINumber] = @rESINumber, 
		  [BankName] = @rBankName, 
		  [Branch] = @rBranch, 
		  [AccountNumber] = @rAccountNumber, 
		  [IFSCNumber] = @rIFSCNumber, 
		  [PanNumber] = @rPanNumber, 
		  [IncomeTaxStatusId] = @rIncomeTaxStatusId, 
		  [UpdatedUserId] = @rUpdatedUserId, 
		  [UpdatedDateTime] = sCommon.fGetDate(), 
		  [IncrementDate] = @rIncrementDate, 
		  [BasicPay] = @rBasicPay,
		  [PayrollId]=@rPayrollId,
          [PayrollGroupId]=@rPayrollGroupId,
          [Payscale]=@rPayscale,
          [EPFJoinDate]=@rEPFJoinDate,
          [UAN]=@rUAN,
          [RetirementDate]=@rRetirementDate,
		  [AccountHolderName]=@rAccountHolderName,
		  [PayTypeId]=@rPayTypeId
	  WHERE 
			EmployeeId = @rEmployeeId
     END    
     
	SELECT 1 AS RESULT
	COMMIT TRANSACTION
	END TRY
	BEGIN CATCH
	ROLLBACK TRANSACTION
	SELECT -1 AS RESULT
	END CATCH				
END
GO
PRINT N'Altering Procedure [sHrm].[pEmployeeStatutoryDetailGet]...';


GO
ALTER PROCEDURE [sHrm].[pEmployeeStatutoryDetailGet]
	
	@rOrgId smallint,
	@rEmployeeId [bigint] = 0
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	 SELECT 
		    [EmployeeId]
		  , [EPFNumber]
		  , [IsVPFDeduction]
		  ,ISNULL([VPFContributionId],0) AS VPFContributionId
		  ,ISNULL([VPFContributionEffectiveFrom],'1/1/0001')  AS VPFContributionEffectiveFrom
		  ,ISNULL([VPFPercentage],0) AS VPFPercentage
		  ,ISNULL([VPFAmount],0) AS VPFAmount
		  ,[ESINumber]
		  ,[BankName]
		  ,[Branch]
		  ,[AccountNumber]
		  ,[IFSCNumber]
		  ,[PanNumber]
		  ,ISNULL([IncomeTaxStatusId],0) AS IncomeTaxStatusId       
		  ,ISNULL([IncrementDate],'1/1/0001') AS IncrementDate
		  ,ISNULL([BasicPay],0) AS BasicPay
		  ,ISNULL([PayrollId],0) AS PayrollId
		  ,ISNULL([PayrollGroupId],0) AS PayrollGroupId 
		  ,ISNULL([Payscale],'') AS Payscale
		  ,ISNULL([EPFJoinDate],'1/1/0001') AS EPFJoinDate
		  ,ISNULL(UAN,'') AS UAN
		  ,ISNULL(RetirementDate,'1/1/0001') AS RetirementDate
		  ,ISNULL([AccountHolderName],'')As AccountHolderName
		  ,ISNULL([PayTypeId],0) AS PayTypeId
		  
	FROM 
			[sHrm].[tEmployeeStatutoryAndOther] 
			 
	Where 
			 EmployeeId = @rEmployeeId	  
END
GO
PRINT N'Altering Procedure [sPayroll].[pPayProcessEmployeeRemarkList]...';


GO

ALTER PROCEDURE [sPayroll].[pPayProcessEmployeeRemarkList]
	
	 @rForMonth int,
	 @rForYear int,
	 @rPayrollYearId int
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN  
	SELECT  
		EM.EmployeeId,
		EM.EmployeeName,
		EM.Code AS EmployeeCode,
		OM.DisplayTitle AS OrgName,
		PER.Remark,
		PER.AutoId,
		ISNULL(PER.ChequeNo,'') ChequeNo,
		PER.PayDate,
		CASE WHEN ISNULL(PER.PayTypeId,0) = 0 THEN ISNULL(ESO.PayTypeId,0)
			ELSE ISNULL(PER.PayTypeId,0) END AS PayTypeId
	FROM 
		sHrm.vEmployeeCommonDetail EM
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = EM.OrgID	
		INNER JOIN sHrm.tEmployeeStatutoryAndOther ESO ON EM.EmployeeId = ESO.EmployeeId
		LEFT JOIN sPayroll.tPayProcessEmployeeRemark PER ON
		PER.SalaryMonth=@rForMonth AND PER.SalaryYear=@rForYear	AND PER.PayrollYearId=@rPayrollYearId AND EM.EmployeeId = PER.EmployeeId
		INNER JOIN sPayroll.tPayrollMaster PM ON PM.Id = ESO.PayrollId
		INNER JOIN sPayroll.tPayrollYearMaster PY ON PY.PayrollId = PM.Id
		--LEFT JOIN sFinanceCommon.tPayTypeMaster PTM ON PTM.Id = PER.PayTypeId
		--LEFT JOIN sFinanceCommon.tPayTypeMaster PTM2 ON PTM2.Id = ESO.PayTypeId
	WHERE 
		PY.Id = @rPayrollYearId AND ISNULL(EM.IsOtherUser,0) = 0
END
GO
PRINT N'Altering Procedure [sPayroll].[pRptEmployeeSalaryDetail]...';


GO

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

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

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


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

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


GO

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

BEGIN 
	
	DECLARE @lFirstDate Date
	DECLARE @lLasteDate Date
	IF(@rForMonth!=0 and @rForYear!=0)
	BEGIN
		SET @lFirstDate = CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'/'+CONVERT(NVARCHAR(2),@rForMonth)+'/01'))
		SET @lLasteDate=DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,@lFirstDate)+1,0))
	END

	SET @rEmployeeCode = sCommon.fSearchStringGet(@rEmployeeCode)
	SET @rEmployeeName = sCommon.fSearchStringGet(@rEmployeeName)

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

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

	SELECT 
		@rOrderByField AS OrderByField,
		@rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,	
		ISNULL(ESO.EPFNumber,'') AS PFNumber,
		EM.EmployeeId,
		tEM.FirstName +' '+tEM.MiddleName+' '+ tEM.LastName AS EmployeeName,
		EM.Code AS EmployeeCode,
		ISNULL(PPE.GrossBasic,0) AS GrossBasic,
		PFS.PfSalaryLimit,
		PFS.FpsSalaryLimit,
		PFS.EmployeePfPercent,
		PFS.EmployerPfPercent,
		PFS.EmployerFpsPercent,
		PFS.AdminChargesPercent,
		PFS.EdliPercent,
		PFS.InspectionChargesPercent,
		PFPro.PayProcessElementId,
		PFPro.EmployeePfAmount,
		PFPro.EmployerPfAmount,
		PFPro.EmployerFpsAmount,
		PFPro.AdminChargesAmount,
		PFPro.EdliChargesAmount,
		PFPro.InspectionChargesAmount,
		PY.Title AS PayrollYearName,
		PP.SalaryMonth,
		PP.SalaryYear,
	    MM.Title AS MonthName,
	    (ISNULL(AT.TotalWorkingDays,0) - ISNULL(AT.LWP,0)) AS WorkingDays,
	   (SELECT ISNULL(SUM(PPE.Amount),0) FROM sPayroll.tPayProcessElement PPE INNER JOIN sPayroll.tPayElement P  
	    ON PPE.PayElementId =  P.ID  WHERE PPE.PayProcessEmployeeId = PE.PayProcessEmployeeId AND PayElementId IN 
		(SELECT DependentPayElementId FROM sPayroll.tPaySetupDependent PD INNER JOIN sPayroll.tPaySetup PS ON  PD.PaySetupId = PS.ID
		INNER JOIN sPayroll.tPayElement PE ON PS.PayElementId = PE.ID WHERE PS.PayrollId = @rPayrollId AND PS.PayrollYearId = @rPayrollYearId 
		AND PE.PayElementDefaultId = 56 AND ((PS.SourceTypeId=2020 AND ESO.PayrollGroupId=PS.SourceId) OR (PS.SourceTypeId=95 AND tEM.Id=PS.SourceId)))
		) 
		AS Salary,
	    ISNULL(ESO.UAN,'') AS UAN,
	    PPE.TotalEarning,
	    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,
		(SELECT SUM(PE1.Amount) FROM sPayroll.tPayProcessElement PE1
		INNER JOIN sPayroll.tPayElement P1 ON PE1.PayElementId=P1.Id
		INNER JOIN sPayroll.tPayProcessEmployee PPE1 ON PPE1.Id = PE1.PayProcessEmployeeID
		INNER JOIN sPayroll.tPayProcess PP1 ON PP1.Id = PPE1.PayProcessId AND PP1.SalaryMonth = PP.SalaryMonth AND PP1.SalaryYear = PP.SalaryYear
		--INNER JOIN sPayroll.tPaySetup PS1 ON PE1.PayElementId = PS1.PayElementId AND PY.Id = PS1.PayrollYearId
		WHERE P1.PayElementDefaultId IN (1,2,16) AND PPE1.EmployeeId = PPE.EmployeeId 
		AND P1.PayrollId = P.PayrollId
		GROUP BY PPE1.EmployeeId) AS BasicDaOaAmount,
		EM.DateOfLeaving,
		tEM.CreatedDateTime


	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
		LEFT JOIN sHrm.tEmployeeStatutoryAndOther ESO ON ESO.EmployeeId=EM.EmployeeId
		INNER JOIN sPayroll.tPayProcessElement PE ON PE.PayProcessEmployeeId=PPE.ID
		INNER JOIN sPayroll.tPayElement P ON PE.PayElementId=P.ID 
		INNER JOIN sPayroll.tPfProcess PFPro ON PFPro.PayProcessElementId=PE.ID
		INNER JOIN sPayroll.tPayrollYearMaster PY ON PP.PayrollYearId = PY.Id
		INNER JOIN sPayroll.tPfSetup PFS ON PFS.PayrollYearId = PY.Id 
		INNER JOIN sCommon.tMonthMaster MM ON MM.Id=PP.SalaryMonth
		--INNER JOIN sHrm.tEmployeeAttendance AT ON AT.EmployeeId=EM.EmployeeId AND AT.ForMonth=@rForMonth AND AT.ForYear =@rForYear
		--INNER JOIN sHrm.tEmployeeAttendance AT ON AT.EmployeeId=EM.EmployeeId AND ((AT.ForMonth = 0) OR (0 = 0))  AND ((AT.ForYear = 0) OR (0 = 0)) 
		INNER JOIN sHrm.tEmployeeAttendance AT ON AT.EmployeeId=EM.EmployeeId AND ((AT.ForMonth = @rForMonth) OR (@rForMonth = 0))  AND ((AT.ForYear = @rForYear) OR (@rForYear = 0)) 
		LEFT JOIN 
		(
		SELECT PE.Amount,PPE.WorkingDays,PPE.PayProcessId,PPE.EmployeeId, PPE.PayrollGroupId
		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
		LEFT JOIN sHrm.tEmployeeStatutoryAndOther ESO ON ESO.EmployeeId=EM.EmployeeId
		INNER JOIN sPayroll.tPayProcessElement PE ON PE.PayProcessEmployeeId=PPE.ID
		INNER JOIN sPayroll.tPayElement P ON PE.PayElementId=P.ID AND P.PayElementDefaultId = 1
		INNER JOIN sPayroll.tPayrollYearMaster PY ON PP.PayrollYearId = PY.Id
		WHERE 
		(PPE.EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
		AND ((EM.Code Like @rEmployeeCode) OR (@rEmployeeCode = ''))
		AND ((EM.EmployeeName Like @rEmployeeName) OR (@rEmployeeName = ''))
		AND ((PP.SalaryMonth = @rForMonth) OR (@rForMonth = 0))
	    AND ((PP.SalaryYear = @rForYear) OR (@rForYear = 0))
		AND ((PY.PayrollId=@rPayrollId) OR (@rPayrollId=0))
		AND (PPE.PayrollGroupId = @rPayrollGroupId OR @rPayrollGroupId = 0) 
		AND (PP.PayrollYearId = @rPayrollYearId OR @rPayrollYearId = 0) 
		AND ((EM.DateOfleaving >= @lFirstDate) OR ISNULL(EM.DateOfleaving,'') = '')
        AND ((EM.DateOfJoining <= @lLasteDate) OR ISNULL(EM.DateOfJoining,'') = '')
		AND ((tEM.OrgID = @rOrgId) OR (@rOrgId = 0))
		AND (EM.DepartmentId = @rDepartmentId OR @rDepartmentId = 0)
		AND ((tEM.StatusId = @rStatusId) OR (@rStatusId = 0))
		) A ON A.PayProcessId = PPE.PayProcessId AND A.EmployeeId = PPE.EmployeeId  AND A.PayrollGroupId =  PPE.PayrollGroupId
		--LEFT JOIN sSetup.tOrgImages OI ON OI.OrgId = tEM.OrgID
		INNER JOIN sPayroll.tPayrollMaster PM ON PY.PayrollId = PM.Id
		
WHERE 
		(PPE.EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
		AND ((EM.Code Like @rEmployeeCode) OR (@rEmployeeCode = ''))
		AND ((EM.EmployeeName Like @rEmployeeName) OR (@rEmployeeName = ''))
		AND ((PP.SalaryMonth = @rForMonth) OR (@rForMonth = 0))
	    AND ((PP.SalaryYear = @rForYear) OR (@rForYear = 0))
		AND ((PY.PayrollId=@rPayrollId) OR (@rPayrollId=0))
		AND (PPE.PayrollGroupId = @rPayrollGroupId OR @rPayrollGroupId = 0) 
		AND (PP.PayrollYearId = @rPayrollYearId OR @rPayrollYearId = 0) 
		AND ((EM.DateOfleaving >= @lFirstDate) OR ISNULL(EM.DateOfleaving,'') = '' OR ISNULL(@lFirstDate,'')='')
        AND ((EM.DateOfJoining <= @lLasteDate) OR ISNULL(EM.DateOfJoining,'') = '' OR ISNULL(@lLasteDate,'')='')
		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 Procedure [sPayroll].[pPayProcessRemarkManage]...';


GO

ALTER PROCEDURE [sPayroll].[pPayProcessRemarkManage] 
 @rID int
,@rSalaryMonth tinyint
,@rSalaryYear smallint
,@rPayrollYearId int
,@rEmployeeId bigint=0
,@rRemark nvarchar(1000)=''
,@rPayTypeId tinyint = 0
,@rChequeNo nvarchar(40) = ''
,@rPayDate Date = Null
           
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN

BEGIN TRY	
	
  IF EXISTS(Select 1 FROM sPayroll.tPayProcessEmployeeRemark Where AutoId=@rID)
	BEGIN
	  UPDATE [sPayroll].[tPayProcessEmployeeRemark] 
	  SET Remark=@rRemark
			,PayTypeId = @rPayTypeId
			,ChequeNo = @rChequeNo
			,PayDate = @rPayDate
	  where AutoId=@rID    
	  
	  select @rID
	END
  ELSE
	BEGIN
	   INSERT INTO [sPayroll].[tPayProcessEmployeeRemark]
           (
            [SalaryMonth]
           ,[SalaryYear]   
           ,[PayrollYearId]        
           ,[EmployeeId]
           ,[Remark]
		   ,[PayTypeId]
		   ,[ChequeNo]
		   ,[PayDate]
           )
     VALUES
           (
            @rSalaryMonth
           ,@rSalaryYear
           ,@rPayrollYearId
           ,@rEmployeeId           
           ,@rRemark
		   ,@rPayTypeId
		   ,@rChequeNo
		   ,@rPayDate
           )
       SELECT SCOPE_IDENTITY()
	END
END TRY	

BEGIN CATCH 
		SELECT -1 AS Result
END CATCH		
	
END
GO
PRINT N'Altering Procedure [sSetup].[pOrgGroupEISAdd]...';


GO
ALTER PROCEDURE [sSetup].[pOrgGroupEISAdd]
	 
	@rOrgGroupId int,
	@rMapOrgGroupId int,
	@rMapApiUrl nvarchar(200),
	@rIsObsolete bit=0,
	@rTitle nvarchar(max)=''
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	 BEGIN TRY

	  BEGIN TRANSACTION	

	  IF EXISTS(SELECT 1 FROM sSetup.tOrgGroupEIS WHERE OrgGroupId = @rOrgGroupId AND MapOrgGroupId = @rMapOrgGroupId)
	  BEGIN
			 UPDATE sSetup.tOrgGroupEIS
			 SET
				MapApiUrl = @rMapApiUrl,
				IsObsolete = @rIsObsolete,
				Title = @rTitle
			 WHERE
			     OrgGroupId = @rOrgGroupId 
				 AND MapOrgGroupId = @rMapOrgGroupId
		     
			 SELECT 101 AS Result
	  END
	  ELSE
	  BEGIN
			 INSERT INTO sSetup.tOrgGroupEIS
			 VALUES
			 (
				@rOrgGroupId,
				@rMapOrgGroupId,
				@rMapApiUrl,
				@rIsObsolete,
				@rTitle
			 )
			 SELECT 1 AS Result
	  END
	
	 COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Altering Procedure [sAcademic].[pClassworkStudentWithStatusGet]...';


GO

 
ALTER PROCEDURE [sAcademic].[pClassworkStudentWithStatusGet]

	 @rStudentId bigint,
	 @rBatchId int,	 
	 @rFromDate date='',
     @rToDate date='',
     @rHomeWorkEndDate	date='' 
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
	DECLARE @lDivisionId int
	DECLARE @lAcademicId bigint
	SELECT @lDivisionId = DivisionId,@lAcademicId = Id FROM sStudent.tAcademic WHERE StudentId = @rStudentId AND BatchId = @rBatchId

	DECLARE @lOrgGroupBatchId int=0
	SELECT @lOrgGroupBatchId=OrgGroupBatchId FROM sSetup.tBatchMaster WHERE Id = @rBatchId

	DECLARE @lConfigValue nvarchar(50)
	DECLARE @lIsClassworkHomeworkBasedOnApproval bit=0
	SELECT @lConfigValue = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 323 AND SourceTypeId = 2010 AND SourceId = LEFT(@lOrgGroupBatchId,4)

	IF (@lConfigValue IS NULL) OR (@lConfigValue = 'False')
	SET @lIsClassworkHomeworkBasedOnApproval = 0
	ELSE
	SET @lIsClassworkHomeworkBasedOnApproval = 1
	
	SELECT 
			DISTINCT(AC.Id),
			AC.EmployeeId,
			AC.ClassId,
			AC.DivisionId,
			AC.SubjectId,
		    CASE WHEN AC.ClassworkStatusId != 2 THEN AC.Classwork ELSE 'NA' END AS Classwork,
		    CASE WHEN AC.HomeWorkStatusId != 2 THEN AC.Homework ELSE 'NA' END AS Homework,
		    AC.ClassWorkDate,
		    AC.HomeWorkEndDate,
		    ISNULL(SM.Title,'') as SubjectName,
		    ISNULL(EM.FirstName +' ' + EM.LastName,'') AS TeacherName,
		    ISNULL(CM.Title,'') AS ClassName,
		    ISNULL(DM.Title,'') AS DivisionName,
		    OM.OrgGroupId AS OrgId,
		    ISNULL(HCSM.Title,'Assigned') AS HomeworkStatus,
			AC.ClassWorkDate ,
			ISNULL(AC.IsSubmitHomework,0) AS IsSubmitHomework
	FROM 
			sAcademic.tClasswork AC			 
			INNER JOIN sSetup.tSubjectMaster SM On SM.Id=AC.SubjectId
			INNER JOIN sHrm.tEmployeeMaster EM On EM.Id = AC.EmployeeId
			INNER JOIN sSetup.tClassMaster CM On CM.Id = AC.ClassId
			INNER JOIN sSetup.tDivisionMaster DM On DM.Id = AC.DivisionId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = DM.OrgId
			INNER JOIN sStudent.tAcademic SA ON SA.ClassId = AC.ClassId AND SA.DivisionId = AC.DivisionId AND SA.BatchId = AC.BatchId
			LEFT JOIN sAcademic.tHomeworkCheck HWC ON HWC.AcademicId = SA.Id AND HWC.ClassworkId = AC.Id
			LEFT JOIN sAcademic.tHomeworkCheckStatusMaster HCSM ON HCSM.Id = HWC.HomeWorkCheckStatusId
	WHERE 
			AC.DivisionId = @lDivisionId		 
			AND (AC.ClassWorkDate>=@rFromDate OR ISNULL(@rFromDate,'')='')
			AND (AC.ClassWorkDate<=@rToDate OR ISNULL(@rToDate,'')='')
			AND (AC.HomeWorkEndDate>=@rHomeWorkEndDate OR ISNULL(@rHomeWorkEndDate,'')='')
			AND AC.BatchId = @rBatchId
			AND ((@lIsClassworkHomeworkBasedOnApproval=0) OR (@lIsClassworkHomeworkBasedOnApproval=1 AND AC.StatusId=550))
			AND ISNULL(EM.IsOtherUser,0) = 0 
			--AND AC.StatusId=550
			--AND SA.Id = @lAcademicId
			--uncomment above AND SA.Id = @lAcademicId because HomeworkStatus not display Studentwise
			AND SA.Id = @lAcademicId
	ORDER BY  AC.ID DESC
END
GO
PRINT N'Altering Procedure [sAdmission].[pAdmissionInquiryGet]...';


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

BEGIN 
	
	IF(@rIsGivenAdmissionForm=1)
		SET @rIsGivenAdmissionForm = 1
  	IF(@rIsGivenAdmissionForm=2)
		SET @rIsGivenAdmissionForm =0
	 
	 
	 SET @rToDate = DATEADD(d,1,@rToDate)
	 --IF @rIsSearch = 1
		BEGIN
			SET @rFirstName= sCommon.fSearchStringGet(@rFirstName)
			SET @rLastName= sCommon.fSearchStringGet(@rLastName)
			SET @rHandledBy= sCommon.fSearchStringGet(@rHandledBy)
			--SET @rContactNo= sCommon.fSearchStringGet(@rContactNo)
		END
	
	SELECT 
	
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			CASE WHEN @rAdmissionInquiryIdText = 0 THEN AI.Number ELSE @rAdmissionInquiryIdText END AS AdmissionInquiryIdText,
			 AI.Id
			,AI.ForBatchId
			,AI.ForClassId
			,AI.StatusId
			,ISNULL(SM.Id,0) AS InquiryStatusMasterId
			,ISNULL(AI.GenderId,0) AS GenderId
			,ISNULL(AI.InquiryModeId,0) AS InquiryModeId
			,ISNULL(IMM.Title,'') AS InquiryMode
			,ISNULL(AI.InquiryReferenceId,0) AS InquiryReferenceId		
		    ,ISNULL(AI.AdmissionCategoryId,0) AS AdmissionCategoryId
		    ,AI.OrgId
		    ,ISNULL(AI.Number,0) AS InquiryNumber
		    ,ISNULL(AI.InquiryDate,'') AS AdmissionInquiryDate 		    
		    ,OM.DisplayTitle AS OrgName
		    ,BM.Title AS ForBatch
			,ISNULL(CM.Title,'') AS ClassName	
			,AI.FirstName
			,AI.MiddleName
			,AI.LastName
			,[sStudent].[fStudentNameGet](AI.FirstName , ISNULL(AI.MiddleName,'') , AI.LastName,OM.StudentNameFormatId ) AS StudentName
			,AI.LastName +' ' +AI.FirstName+' '+AI.MiddleName as Name				
			,ISNULL(AI.DateOfBirth,'') As DateOfBirth
			,ISNULL(GM.Title,'') As Gender			
			,AI.ContactNo
			,AI.ContactEmail			
			,AI.StreetOne
			,AI.StreetTwo
			,AI.StreetThree
			,AI.Country
			,AI.State
			,AI.City
			,AI.ZipCode
			,ISNULL(AI.Remark,'') AS Remark						
		    ,ISNULL(AI.PreviousSchool,'') as PreviousSchool			
			,ISNULL(AI.MeritMarks,0) AS MeritMarks
			,ISNULL(AI.MeritGrade,'') AS MeritGrade
			,ISNULL(AI.MeritMarksBreakup,'') AS MeritMarksBreakup
			,SM.Title as StatusName	
			--,cast(replace(FollowupDate,'/','-') as date) As FollowupDate
			,ISNULL(AI.FollowupDate,'') As FollowupDate
			,ISNULL(AI.FollowupRemark,'') As FollowupRemark			
			,ISNULL(IRM.Title ,'') AS InquiryReference	
			,ISNULL(SCM.Title,'') AS AdmissionCategory		
			,ISNULL(AI.HandledBy,'') AS HandledBy
			,ISNULL(AI.CreatedDateTime,'') As CreatedDateTime
			,ISNULL(AI.StudentId,0) AS StudentId,
			ISNULL(AI.CastCategoryId,0) AS CastCategoryId,
			ISNULL(AI.IsTransportRequired,0) AS IsTransportRequired,
			ISNULL(AI.IsHostelRequired,0) AS IsHostelRequired,
			CONVERT(int,ISNULL(AI.IsGivenAdmissionForm,0)) AS IsGivenAdmissionForm,
			--ISNULL(AI.IsGivenAdmissionForm,0) AS IsGivenAdmissionForm,
			ISNULL(SM.HighlightColor,'') AS HighlightColor,
			ISNULL(SA.PreviousStandard,'') As PreviousStandard,
			AI.AlternateContactNo,
			AI.AlternateContactEmail
			,CASE WHEN AI.FollowupDate IS NULL THEN '' ELSE  CONVERT(VARCHAR(10), AI.FollowupDate, 103) END AS FollowupDateString,
			ISNULL(AIC.AgeCutOffDate,'') AS AgeCutOffDate,
			ISNULL(AI.MotherName,'') AS MotherName,
			CASE WHEN AI.DataEntryModeId = 561 THEN 'Online' ELSE 'Offline' END DataEntryMode 
			,ISNULL(AI.MinorityStatusId,0) As MinorityStatusId
		    ,ISNULL(AI.LiveWithId,0) AS LiveWithId
			,ISNULL(AI.AdhaarNumber,'') AS AdhaarNumber 
			,ISNULL(AI.BloodGroupId,0) AS BloodGroupId
			 ,ISNULL(AI.FatherName,'') AS FatherName
			,ISNULL(AI.FatherOccupation,'') AS FatherOccupation 
			,ISNULL(AI.FatherIncome,0) AS FatherIncome 
			,ISNULL(AI.FatherContactNo,'') AS FatherContactNo
			,ISNULL(AI.FatherMail,'') AS FatherMail
			,ISNULL(AI.FatherQualification,'') AS FatherQualification
			,ISNULL(AI.MotherOccupation,'') As MotherOccupation
			,ISNULL(AI.MotherIncome,0) AS MotherIncome
			,ISNULL(AI.MotherContactNo,'') AS MotherContactNo 
			,ISNULL(AI.MotherMail,'') AS MotherMail 
			,ISNULL(AI.MotherQualification,'') AS  MotherQualification
			,ISNULL(AI.Stream,'') AS Stream
			,ISNULL(AI.Board,'') AS Board
			,ISNULL(CCM.Title,'') AS CasteCategory
			,ISNULL(AI.InquiryReferenceRemark,'') AS InquiryReferenceRemark
			,ISNULL(AI.WhatsAppContactNo,'') AS WhatsAppContactNo
			--,(SELECT STUFF ((SELECT ',' +' ' + AIF.FieldRemark+' - '+AIF.FieldGroup+ ' - ' +AI1.AdmissionInquiryFieldResponse
			--	FROM sAdmission.tAdmissionInquiryForm AIF 
			--	LEFT JOIN sAdmission.tAdmissionInquiryField AI1 ON AI1.AdmissionInquiryFormId = AIF.Id AND AI1.AdmissionInquiryId =  AI.Number
			--	WHERE (ClassId = @rForClassId  OR @rForClassId=0)
			--	AND (AI1.AdmissionInquiryFormId = @rId  OR @rId = 0)
			--	AND (BatchId = @rForBatchId OR @rForBatchId=0) ORDER BY AIF.FieldOrder
			--	FOR XML PATH('')),1,1,'')) AS AdmissionCustomField
  FROM 
            sAdmission.tAdmissionInquiry AI
            LEFT JOIN sAdmission.tInquiryModeMaster IMM ON IMM.Id = AI.InquiryModeId
           --INNER JOIN sCommon.tStatusMaster SM ON SM.Id=AI.StatusId AND StatusTypeId=104
            INNER JOIN sAdmission.tInquiryStatusMaster SM ON SM.Id=AI.InquiryStatusId 
			INNER JOIN sSetup.tClassMaster CM ON CM.Id=AI.ForClassId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=AI.OrgId
			INNER JOIN sSetup.tBatchMaster BM ON AI.ForBatchId = BM.Id
			LEFT JOIN sAdmission.tInquiryReferenceMaster IRM ON IRM.Id=AI.InquiryReferenceId
			LEFT JOIN sStudent.tAdmissionCategoryMaster SCM ON SCM.Id=AI.AdmissionCategoryId
			LEFT JOIN sCommon.tGenderMaster GM ON GM.Id=AI.GenderId  
			LEFT JOIN sStudent.tStudentAdmission SA oN SA.StudentId=AI.StudentID
			LEFT JOIN sAdmission.tAdmissionInquiryCriteria AIC ON AIC.ClassId=AI.ForClassId AND AIC.BatchId=AI.ForBatchId 
			LEFT JOIN  scommon.tCastCategoryMaster CCM on CCM.Id = AI.CastCategoryId
			--LEFT JOIN sAdmission.tAdmissionInquiryField AIF ON AIF.AdmissionInquiryFormId = AI.Id 
			--LEFT JOIN sAdmission.tAdmissionInquiryForm AIF1 ON AIF.AdmissionInquiryFormId = AIF1.Id   
  WHERE  
      ((AI.Id = @rId) OR (@rId = 0))
      AND ((AI.FirstName like @rFirstName) OR (@rFirstName=''))
      AND ((AI.LastName like @rLastName) OR (@rLastName=''))
      AND ((AI.InquiryDate>= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
      AND ((AI.InquiryDate < @rToDate) OR (ISNULL(@rToDate,'')=''))
	  AND ((AI.ForClassId=@rForClassId) OR (@rForClassId=0)) 
	  --AND ((AI.StatusId=@rStatusId) OR (@rStatusId=0))
	  AND ((SM.Id=@rInquiryStatusMasterId) OR (@rInquiryStatusMasterId=0))
	  AND (AI.OrgId=@rOrgId OR @rOrgId=0)
	  AND ((AI.ForBatchId=@rForBatchId) OR (@rForBatchId=0))
	  AND ((CM.DepartmentId=@rDepartmentId) or (@rDepartmentId = 0))
	  AND ((AI.MeritMarks >= @rFromMeritMarks) OR (@rFromMeritMarks=0))
	  AND ((AI.MeritMarks <= @rToMeritMarks) OR (@rToMeritMarks=0))
	  AND ((AI.InquiryModeId=@rInquiryModeId) OR (@rInquiryModeId=0))
	  AND ((AI.InquiryReferenceId=@rInquiryReferenceId) OR (@rInquiryReferenceId=0))
	  AND ((AI.Number=@rNumber) OR (@rNumber=0))
	  AND (BM.OrgGroupBatchid=@rOrgGroupBatchId OR @rOrgGroupBatchId=0)
	  AND ((AI.FollowUpdate=@rFollowupdate) OR (ISNULL(@rFollowUpdate,'')=''))

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

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


GO
ALTER PROCEDURE [sAssessment].[pRptResultSheetStandardMultiExamGet]
	 
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 @rSubjectId int = 0,
	 @rBatchId int=0,
	 @rClassId int=0,
	 @rDivisionId int=0,
	 @rExamId int,
	 @rCode nvarchar(20)='',
	 @rFromRollNo int=0,
	 @rToRollNo int=0,
	 @rFromRank int=0,
	 @rToRank int=0,
	 @rGrade nvarchar(20)='',
	 @rResultId bigint=0,
	 @rStatusId int=0,
	 @rAcademicId bigint=0,
	 @rFromObtain decimal(5,2)=0,
	 @rToObtain decimal(5,2)=0,
	 @rFromPercentage decimal(5,2)=0,
	 @rToPercentage decimal(5,2)=0,
	 @rIsDetail bit=0,
	 @rIsShowWithDetail bit=0,
	 @rFilterId int=0,
	 @rOrgGroupBatchId int=0,
	 @rClassStatusId int=0,
	 @rMultiCode nvarchar(max)='' 
	
	 --,@rcolumn_visible bit
	

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
begin
 
  --select * from sAssessment.tTempAllExam
 IF(@rOrgGroupBatchId=0)
	SELECT @rOrgGroupBatchId=OrgGroupBatchId FROM sSetup.tBatchMaster WHERE Id=@rBatchId  
  
DECLARE @GradeString nvarchar(1000)
DECLARE @GradeStringRemark nvarchar(500),
@GradeSetId int , @IsIncludeSubExam bit,@GradeStringHtml nvarchar(500)
SELECT @GradeSetId = GradesetId,
	   @IsIncludeSubExam = ISNULL(IsIncludeSubExam,0)  FROM sAssessment.tExamMaster WHERE Id = @rExamId
SELECT @GradeString = [sAssessment].[fGradeStringGet](@GradeSetId)

Select @GradeStringHtml = GradeStringHtml from sAssessment.tGradeSetMaster where Id =@GradeSetId
Select @GradeStringRemark = GradeStringText from sAssessment.tGradeSetMaster Where Id =@GradeSetId

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

DECLARE @lAbsentRemarkConfig nvarchar(20) = ''
SELECT @lAbsentRemarkConfig =ItemValue From sConfig.tConfigurationSetup WHERE ConfigurationId = 515 AND SourceTypeId = 1016 AND SourceId = @lOrgId


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

--#TempAllExam
	CREATE TABLE #TempAllExam
	(
		AcademicIdText nvarchar(20),
		ExamIdText nvarchar(20),
		CoScholasticScopeIdText nvarchar(20),
		IsDisplayMonthlyAttendanceText nvarchar(20),
		ClassIdText nvarchar(50),
		AcademicId bigint,
		ExamName Nvarchar(100),
		StudCode NVarchar(20),
		StudentName Nvarchar(300),
		RollNo int,
		ResultStatus Nvarchar(50),	
		ClassName NVarchar(100),		
		Division NVarchar(100),
		TotalMark decimal(8,2),
		TotalObtain decimal(8,2),
		Percentage decimal(5,2),
		RankNumber int,
		ResultGrade NVarchar(10),
		
		MaximumMark1 decimal(10,2),		
		SubjectGrade1 NVarchar(10),
		--Obtain1 decimal(5,2) Default 0,	--remove this line and add below line for mantis: 31081
		Obtain1 decimal(5,2),
		ExamMaximum1 decimal(10,2),
		IsPresent1 bit,
						
		MaximumMark2 decimal(10,2),	
		SubjectGrade2 NVarchar(10),
		--Obtain2 decimal(5,2) Default 0,	--remove this line and add below line for mantis: 31081
		Obtain2 decimal(5,2),
		ExamMaximum2 decimal(10,2),
		IsPresent2 bit,
				
		MaximumMark3 decimal(10,2),
		SubjectGrade3 NVarchar(10),
		--Obtain3 decimal(5,2) Default 0,	--remove this line and add below line for mantis: 31081
		Obtain3 decimal(5,2),
		ExamMaximum3 decimal(10,2),
		IsPresent3 bit,		
		
		MaximumMark4 decimal(10,2),	
		SubjectGrade4 NVarchar(10),
		--Obtain4 decimal(5,2) Default 0,	--remove this line and add below line for mantis: 31081
		Obtain4 decimal(5,2),
		ExamMaximum4 decimal(10,2),
		IsPresent4 bit,	
				
		MaximumMark5 decimal(10,2),		
		SubjectGrade5 NVarchar(10),
		--Obtain5 decimal(5,2) Default 0,	--remove this line and add below line for mantis: 31081
		Obtain5 decimal(5,2),
		ExamMaximum5 decimal(10,2),
		IsPresent5 bit,	
				
		MaximumMark6 decimal(10,2),		
		SubjectGrade6 NVarchar(10),
		--Obtain6 decimal(5,2) Default 0,	--remove this line and add below line for mantis: 31081
		Obtain6 decimal(5,2),
		ExamMaximum6 decimal(10,2),
		IsPresent6 bit,	
		
		MaximumMark7 decimal(10,2),		
		SubjectGrade7 NVarchar(10),
		--Obtain7 decimal(5,2) Default 0,	--remove this line and add below line for mantis: 31081
		Obtain7 decimal(5,2),
		ExamMaximum7 decimal(10,2),
		IsPresent7 bit,	
		
		MaximumMark8 decimal(10,2),	
		SubjectGrade8 NVarchar(10),
		--Obtain8 decimal(5,2) Default 0,	--remove this line and add below line for mantis: 31081
		Obtain8 decimal(5,2),
		ExamMaximum8 decimal(10,2),
		IsPresent8 bit,	
		
		MaximumMark9 decimal(10,2),		
		SubjectGrade9 NVarchar(10),
		--Obtain9 decimal(5,2) Default 0,	----remove this line and add below line for mantis: 31081
		Obtain9 decimal(5,2),
		ExamMaximum9 decimal(10,2),
		IsPresent9 bit,	
		
		
		MaximumMark10 decimal(10,2),		
		SubjectGrade10 NVarchar(10),
		--Obtain10 decimal(5,2) Default 0,	--remove this line and add below line for mantis: 31081
		Obtain10 decimal(5,2),
		ExamMaximum10 decimal(10,2),
		IsPresent10 bit,	
		
		MaximumMark11 decimal(10,2),		
		SubjectGrade11 NVarchar(10),
		--Obtain11 decimal(5,2) Default 0,	--remove this line and add below line for mantis: 31081
		Obtain11 decimal(5,2),
		ExamMaximum11 decimal(10,2),
		IsPresent11 bit,
		
		MaximumMark12 decimal(10,2),		
		SubjectGrade12 NVarchar(10),
		--Obtain12 decimal(5,2) Default 0,	--remove this line and add below line for mantis: 31081
		Obtain12 decimal(5,2),
		ExamMaximum12 decimal(10,2),
		IsPresent12 bit,
		
		MaximumMark13 decimal(10,2),		
		SubjectGrade13 NVarchar(10),
		--Obtain13 decimal(5,2) Default 0,	--remove this line and add below line for mantis: 31081
		Obtain13 decimal(5,2),
		ExamMaximum13 decimal(10,2),
		IsPresent13 bit,		
		 
		 
		SubjectGradeTerm1 NVarchar(10),
		SubjectGradeTerm2 NVarchar(10),
		SubjectGradeTerm3 NVarchar(10),
		IsMarksInDecimal bit,
		column_visible bit,
		--Obtain decimal(5,2),
		Percentile decimal(5,2),
		--ClassSubject nvarchar(100),
		ResultDetailId bigint,
		ResultId bigint,	
		Remark1 nvarchar(1000),
		Remark2 nvarchar(300),
		Remark3 nvarchar(300),
		DisplayTitle nvarchar(150),		
		IsRankNo bit, 
		IsGrade bit,
		IsPercentile bit,
		IsPercentage bit,
		IsSubjectPercentile bit,
		IsProcessResult bit,
		IsNegativeMarks bit,
		IsIncludeCoScholastic bit,
		IsOnPrePrinted bit,
		IsDisplayPhoto bit,
		IsDisplayBirthDate bit,
		IsLockForEdit bit,
		IsDisplaySchoolName bit,			
		IsDisplayAttendance bit,
		IsDisplayHeightWeight bit,
		IsResultStatus bit,
		FooterAdjustmentText nvarchar(max),
		DetailAdjustmentText nvarchar(max),
		FooterAdjustment smallint,
		DetailAdjustment smallint,
		ResultRemark nvarchar(200),
		DateOfBirth date,
		HeightTerm1 decimal(5,2),
		WeightTerm1 decimal(5,2),
		HeightTerm2 decimal(5,2),
		WeightTerm2 decimal(5,2),
		HeightAnnual decimal(5,2),
		WeightAnnual decimal(5,2),
		PresentDaysTerm1 smallint,
		PresentDaysTerm2 smallint,
		PresentDaysAnnual smallint,
		TotalDaysTerm1 smallint,
		TotalDaysTerm2 smallint,
		TotalDaysAnnual smallint,
		TotalMarkTerm1 decimal(8,2),
		TotalObtainTerm1 decimal(8,2),
		PercentageTerm1 decimal(5,2),
		RankNumberTerm1 int,
		ResultGradeTerm1 NVarchar(10),
		PercentileTerm1 decimal(5,2),
		ResultStatusTerm1 Nvarchar(50),		   
		TotalMarkTerm2 decimal(8,2),
		TotalObtainTerm2 decimal(8,2),
		PercentageTerm2 decimal(5,2),
		RankNumberTerm2 int,
		ResultGradeTerm2 NVarchar(10),
		PercentileTerm2 decimal(5,2),
		ResultStatusTerm2 Nvarchar(50), 
		TotalMarkTerm3 	decimal(8,2),
		TotalObtainTerm3 decimal(8,2),
		PercentageTerm3 decimal(5,2),
		RankNumberTerm3 int,
		ResultGradeTerm3 NVarchar(10),
		PercentileTerm3 decimal(5,2),
		ResultStatusTerm3 Nvarchar(50), 
		
		TermScopeId tinyint,		 
		StudentPhoto varbinary(max),
		GradeString nvarchar(1000),
		IsDisplayGradeString bit,		 
		IsDisplayInMarksheet bit,
		IsShowSubjectGrade bit,
		IsIncludeInTotal bit,
		ClassSubjectID int,
		SubjectId int,
		--Maximum decimal(5,2),
		SubjectOrderIndex smallint,
		SubjectGrade NVarchar(10),
		SubjectName NVarchar(100),
		SubjectCode Nvarchar(20),	
		SubjectMinimum decimal(10,2),		
		SubjectMaximum decimal(10,2),
		SubjectObtain  decimal(5,2),
		
		Exam1Name Nvarchar(100),		
		TotalMarks1 decimal(8,2),		
		TotalObtain1 decimal(8,2),
		Percentage1 decimal(5,2),
		RankNumber1 int,
		ResultGrade1 NVarchar(10),
		Percentile1 decimal(5,2),
		ResultStatus1 Nvarchar(50),
		Exam1CombineExamName Nvarchar(100),
				
		Exam2Name nvarchar(100),	
		TotalMarks2 decimal(8,2),
		TotalObtain2 decimal(8,2),
		Percentage2 decimal(5,2),
		RankNumber2 int,
		ResultGrade2 NVarchar(10),
		Percentile2 decimal(5,2),
		ResultStatus2 Nvarchar(50),
		Exam2CombineExamName Nvarchar(100),
		
		Exam3Name nvarchar(100),	
		TotalMarks3 decimal(8,2),
		TotalObtain3 decimal(8,2),
		Percentage3 decimal(5,2),
		RankNumber3 int,
		ResultGrade3 NVarchar(10),
		Percentile3 decimal(5,2),		
		ResultStatus3 Nvarchar(50),
		Exam3CombineExamName Nvarchar(100),
		
		Exam4Name nvarchar(100),	
		TotalMarks4 decimal(8,2),
		TotalObtain4 decimal(8,2),
		Percentage4 decimal(5,2),
		RankNumber4 int,
		ResultGrade4 NVarchar(10),
		Percentile4 decimal(5,2),
		ResultStatus4 Nvarchar(50),
		Exam4CombineExamName Nvarchar(100),
		
		Exam5Name nvarchar(100),		
		TotalMarks5 decimal(8,2),
		TotalObtain5 decimal(8,2),
		Percentage5 decimal(5,2),
		RankNumber5 int,
		ResultGrade5 NVarchar(10),
		Percentile5 decimal(5,2),
		ResultStatus5 Nvarchar(50),
		Exam5CombineExamName Nvarchar(100),
		
		Exam6Name nvarchar(100),	
		TotalMarks6 decimal(8,2),
		TotalObtain6 decimal(8,2),
		Percentage6 decimal(5,2),
		RankNumber6 int,
		ResultGrade6 NVarchar(10),
		Percentile6 decimal(5,2),
		ResultStatus6 Nvarchar(50),
		Exam6CombineExamName Nvarchar(100),
		
		Exam7Name nvarchar(100),		
		TotalMarks7 decimal(8,2),
		TotalObtain7 decimal(8,2),
		Percentage7 decimal(5,2),
		RankNumber7 int,
		ResultGrade7 NVarchar(10),
		Percentile7 decimal(5,2),
		ResultStatus7 Nvarchar(50),
		Exam7CombineExamName Nvarchar(100),
		
		Exam8Name nvarchar(100),
		TotalMarks8 decimal(8,2),
		TotalObtain8 decimal(8,2),
		Percentage8 decimal(5,2),
		RankNumber8 int,
		ResultGrade8 NVarchar(10),
		Percentile8 decimal(5,2),
		ResultStatus8 Nvarchar(50),
		Exam8CombineExamName Nvarchar(100),
		
		
		Exam9Name nvarchar(100),	
		TotalMarks9 decimal(8,2),
		TotalObtain9 decimal(8,2),
		Percentage9 decimal(5,2),
		RankNumber9 int,
		ResultGrade9 NVarchar(10),
		Percentile9 decimal(5,2),
		ResultStatus9 Nvarchar(50),
		Exam9CombineExamName Nvarchar(100),
		
		Exam10Name nvarchar(100),	
		TotalMarks10 decimal(8,2),
		TotalObtain10 decimal(8,2),
		Percentage10 decimal(5,2),
		RankNumber10 int,
		ResultGrade10 NVarchar(10),
		Percentile10 decimal(5,2),
		ResultStatus10 Nvarchar(50),
		Exam10CombineExamName Nvarchar(100),
		
		Exam11Name nvarchar(100),	
		TotalMarks11 decimal(8,2),
		TotalObtain11 decimal(8,2),
		Percentage11 decimal(5,2),
		RankNumber11 int,
		ResultGrade11 NVarchar(10),
		Percentile11 decimal(5,2),
		ResultStatus11 Nvarchar(50),
		Exam11CombineExamName Nvarchar(100),
		
		Exam12Name nvarchar(100),	
		TotalMarks12 decimal(8,2),
		TotalObtain12 decimal(8,2),
		Percentage12 decimal(5,2),
		RankNumber12 int,
		ResultGrade12 NVarchar(10),
		Percentile12 decimal(5,2),
		ResultStatus12 Nvarchar(50),
		Exam12CombineExamName Nvarchar(100),

		Exam13Name nvarchar(100),	
		TotalMarks13 decimal(8,2),
		TotalObtain13 decimal(8,2),
		Percentage13 decimal(5,2),
		RankNumber13 int,
		ResultGrade13 NVarchar(10),
		Percentile13 decimal(5,2),
		ResultStatus13 Nvarchar(50),
		Exam13CombineExamName Nvarchar(100),
		
		ResultRemark1 nvarchar(200),
		ResultRemark2 nvarchar(200),
		
		TotalDays decimal(6,2),
		PresentDays decimal(6,2),
		StudentHeight decimal(6,2),
		StudentWeight decimal(6,2),
		ExamSeatNo nvarchar(20),
		ExamId int,
		
		ExamCode nvarchar(20),
		Exam1Code nvarchar(20),
		Exam2Code nvarchar(20),
		Exam3Code nvarchar(20),
		Exam4Code nvarchar(20),
		Exam5Code nvarchar(20),
		Exam6Code Nvarchar(20),
		Exam7Code Nvarchar(20),
		Exam8Code nvarchar(20),
		Exam9Code nvarchar(20),
		Exam10Code nvarchar(20),
		Exam11Code nvarchar(20),
		Exam12Code nvarchar(20),
		Exam13Code nvarchar(20),
		
		IsDisplayParentName bit,
		FatherName nvarchar(100),
		MotherName nvarchar(100),
		IsShowSubjectMark bit, 
		IsOptionalSubject bit,
		CoScholasticScopeId tinyint,
		IsDisplayPrincipalSign bit,
		IsDisplayTeacherSign bit,
		EmployeeSign varbinary(max),
		Batch nvarchar(100),
		ExamNameTerm1 NVarchar(100),
		ExamNameTerm2 NVarchar(100) ,
		ExamNameTerm3 NVarchar(100),
		ClassTeacherName Nvarchar(100),
		FirstName nvarchar(100),
		LastName nvarchar(100),
		IsDisplayMonthlyAttendance bit,
		MarksheetHeaderA4 varbinary(max),
		IsImageHeader bit,
		MyGoal nvarchar(200),
		AreaOfInterest nvarchar(200),
		Responsibility nvarchar(200),
		MyInterestHobby nvarchar(200),
		MyStrength nvarchar(200),
		Achievements nvarchar(1000),
		
		DentalHygiene nvarchar(50),
		VisionLeft nvarchar(50),
		VisionRight nvarchar(50), 
		IsDetail bit,
		SubjectGroupId int,
		SubjectGroupTitle nvarchar(100),
		SubjectGroupCode nvarchar(20),
		DecimalFormat nvarchar(10),
		SubjectRemark nvarchar(100),
		GraceMark decimal(5,2),
		KrupaMark decimal(5,2),
		GradeStringHtml nvarchar(500),
		ResultRemark3 nvarchar(200),
		IsDisplayTotalMark bit,
		SubjectObtainTerm1 decimal(5,2),	
		SubjectObtainTerm2 decimal(5,2),
		SubjectObtainTerm3  decimal(5,2),
		SubjectMaxTerm1 decimal(10,2),
		SubjectMaxTerm2 decimal(10,2),
		SubjectMaxTerm3 decimal(10,2),
		ContactNo nvarchar(50),
		PresentAddress nvarchar(max),
		TeacherSignCaption nvarchar(100),
		PrincipalSignCaption nvarchar(100),
		ParentSignCaption nvarchar(100),
		ImprovementArea nvarchar(200),
		ProgressArea nvarchar(200),
		GeneralRemark nvarchar(1000),
		MyActivity nvarchar(200),
		ClassTeacherRemark nvarchar(1000),
		 
		HouseRemark nvarchar(1000),
		BloodGroup Nvarchar(20),
		TotalDays1 decimal(6,2),
		PresentDays1 decimal(6,2),
		TotalDays2 decimal(6,2),
		PresentDays2 decimal(6,2),
		TotalDays3 decimal(6,2),
		PresentDays3 decimal(6,2),
		TotalDays4 decimal(6,2),
		PresentDays4 decimal(6,2),
		TotalDays5 decimal(6,2),
		PresentDays5 decimal(6,2),
		TotalDays6 decimal(6,2),
		PresentDays6 decimal(6,2),
		TotalDays7 decimal(6,2),
		PresentDays7 decimal(6,2), 
		TotalDays8 decimal(6,2),
		PresentDays8 decimal(6,2),
		TotalDays9 decimal(6,2),
		PresentDays9 decimal(6,2),
		TotalDays10 decimal(6,2),
		PresentDays10 decimal(6,2),
		TotalDays11 decimal(6,2),
		PresentDays11 decimal(6,2),
		TotalDays12 decimal(6,2),
		PresentDays12 decimal(6,2),
		TotalDays13 decimal(6,2),
		PresentDays13 decimal(6,2),
		BatchIdText nvarchar(20),
		IsShowWithDetail bit,
		IsPresent bit,
		GradeTitle nvarchar(50),
		SubjectHighestDivisionGrade nvarchar(50),
		SubjectHighestDivisionMark decimal(5, 2),
		
		AchievementsTerm1 nvarchar(1000),
		AchievementsTerm2 nvarchar(1000),
		GeneralRemarkTerm1 nvarchar(1000),
		GeneralRemarkTerm2 nvarchar(1000),
		ResultRemark1Term1 nvarchar(200),
		ResultRemark2Term1 nvarchar(200),
		ResultRemark1Term2 nvarchar(200),
		ResultRemark2Term2 nvarchar(200),
		SR_HeightTerm1 decimal(6,2),
		SR_WeightTerm1 decimal(6,2),
		SR_HeightTerm2 decimal(6,2),
		SR_WeightTerm2 decimal(6,2),
		SR_PresentDaysTerm1 decimal(6,2),
		SR_PresentDaysTerm2 decimal(6,2),
		SR_TotalDaysTerm1 decimal(6,2),
		SR_TotalDaysTerm2 decimal(6,2),
		HouseId int,
		HouseName nvarchar(100),
		AdhaarNumber nvarchar(20),
		UIdNumber nvarchar(50),
		FatherContactNo nvarchar(50),
		MotherContactNo nvarchar(50),
		FatherMail nvarchar(50),
		MotherMail nvarchar(50),
		Gender nvarchar(100),
		CoordinatorEmployeeSign varbinary(max),
		StudentAddress nvarchar(max),
		SUId nvarchar(50),
		HighestDivisionMark decimal(5, 2),
		HighestDivisionGrade nvarchar(10),
		StreamTitle nvarchar(50),
		AdmissionNo nvarchar(50),
		AdmissionDate Date,
		MiddleName nvarchar(100) ,
		FatherOccupation nvarchar(50),
		ResultSheetAdditionalTitle nvarchar(100),
		IsDecimal bit,
		IsAbsentRemark bit,
		FinalAbsentRemark nvarchar(100),
		AbsentRemark1 nvarchar(100),
		AbsentRemark2 nvarchar(100),
		AbsentRemark3 nvarchar(100),
		AbsentRemark4 nvarchar(100),
		AbsentRemark5 nvarchar(100),
		AbsentRemark6 nvarchar(100),
		AbsentRemark7 nvarchar(100),
		AbsentRemark8 nvarchar(100),
		AbsentRemark9 nvarchar(100),
		AbsentRemark10 nvarchar(100),
		AbsentRemark11 nvarchar(100),
		AbsentRemark12 nvarchar(100),
		AbsentRemark13 nvarchar(100),
		ExamMaximumTerm1 decimal(6,2),
		ExamMaximumTerm2 decimal(6,2),
		ExamMaximumTerm3 decimal(6,2),
		--add for 29923 mantis start
		PermanentStreetOne nvarchar(150),
		PermanentStreetTwo nvarchar(150),
		PermanentStreetThree nvarchar(150),
		--add for 29923 mantis end
		CasteCategory nvarchar(50),--Mantis 0030303
		--Mantis Start - 0031091
		FeeCategory nvarchar(100),
		StudentContactNo nvarchar(50),
		--Mantis End - 0031091
		ObtainedMaximum1 decimal(10,2),
		ObtainedMaximum2 decimal(10,2),
		ObtainedMaximum3 decimal(10,2),
		ObtainedMaximum4 decimal(10,2),
		ObtainedMaximum5 decimal(10,2),
		ObtainedMaximum6 decimal(10,2),
		ObtainedMaximum7 decimal(10,2),
		ObtainedMaximum8 decimal(10,2),
		ObtainedMaximum9 decimal(10,2),
		ObtainedMaximum10 decimal(10,2),
		ObtainedMaximum11 decimal(10,2),
		ObtainedMaximum12 decimal(10,2),
		ObtainedMaximum13 decimal(10,2)
		)
	 --print 'temp created'    	
	INSERT INTO  #TempAllExam 
	(
	AcademicIdText,
	ExamIdText,
	CoScholasticScopeIdText,
	IsDisplayMonthlyAttendanceText,
	ClassIdText,
	AcademicId,
	ExamName,
	StudCode,
	StudentName,
	RollNo,
	ResultStatus,
	ClassName,
	Division,
	TotalMark,
	TotalObtain,
	Percentage,
	RankNumber,
	ResultGrade,
	IsMarksInDecimal,
	column_visible,
	--Obtain,
	Percentile,
	--ClassSubject,
	ResultDetailId,
	ResultId,

	Remark1,
	Remark2,
    Remark3,
	DisplayTitle,
	IsRankNo, 
	IsGrade,
	IsPercentile,
	IsPercentage,
	IsSubjectPercentile,
	IsProcessResult,
	IsNegativeMarks,
	IsIncludeCoScholastic,
	IsOnPrePrinted,
	IsDisplayPhoto,
	IsDisplayBirthDate,
	IsLockForEdit,
	IsDisplaySchoolName,			
	IsDisplayAttendance,
	IsDisplayHeightWeight,
	IsResultStatus,
	FooterAdjustmentText,
	DetailAdjustmentText,
	FooterAdjustment,
	DetailAdjustment,
	ResultRemark,
	DateOfBirth,
	HeightTerm1,
	WeightTerm1,
	HeightTerm2,
	WeightTerm2,
	HeightAnnual,
	WeightAnnual,
	PresentDaysTerm1,
	PresentDaysTerm2,
	PresentDaysAnnual,
	TotalDaysTerm1,
	TotalDaysTerm2,
	TotalDaysAnnual,
	TermScopeId,
	StudentPhoto,
	GradeString,
	IsDisplayGradeString,	 
	IsDisplayInMarksheet,
	IsShowSubjectGrade,
	IsIncludeInTotal,
	ClassSubjectID,
	SubjectId,
	--Maximum,
	SubjectOrderIndex,
	SubjectGrade,
	SubjectName,
	SubjectCode,
	SubjectMinimum,
	SubjectMaximum,
	SubjectObtain,
	ResultRemark1,
	ResultRemark2,
	
	TotalDays,
	PresentDays,
	StudentHeight,
	StudentWeight,
	ExamSeatNo,
	ExamId,
	
	ExamCode,
	
	IsDisplayParentName,
	FatherName,
	MotherName,
	IsShowSubjectMark,
	IsOptionalSubject,
	CoScholasticScopeId,
	IsDisplayPrincipalSign,
	IsDisplayTeacherSign,
	EmployeeSign,
	Batch,
	ClassTeacherName,
	FirstName,
	LastName,
	IsDisplayMonthlyAttendance,
	MarksheetHeaderA4,
	IsImageHeader,
	MyGoal,
	AreaOfInterest,
	Responsibility,
	MyInterestHobby,
	MyStrength,
	Achievements, 
	
	DentalHygiene,
	VisionLeft,
	VisionRight,
	IsDetail,
	SubjectGroupId,
	SubjectGroupTitle,
	SubjectGroupCode,
	DecimalFormat,
	SubjectRemark,
	GraceMark,
	KrupaMark,
	GradeStringHtml,
	ResultRemark3,
	IsDisplayTotalMark,
	ContactNo,
	PresentAddress,
	TeacherSignCaption,
	PrincipalSignCaption,
	ParentSignCaption,
	ImprovementArea,
	ProgressArea,
	GeneralRemark,
	MyActivity,
	ClassTeacherRemark,
	
	HouseRemark,
	BloodGroup,
	BatchIdText,
    IsShowWithDetail,
    IsPresent,
    GradeTitle,
	
	SubjectHighestDivisionGrade,
	SubjectHighestDivisionMark,
	
	AchievementsTerm1,
	AchievementsTerm2,
	GeneralRemarkTerm1,
	GeneralRemarkTerm2,
	ResultRemark1Term1,
	ResultRemark2Term1,
	ResultRemark1Term2,
	ResultRemark2Term2,
	SR_HeightTerm1,
	SR_WeightTerm1,
	SR_HeightTerm2,
	SR_WeightTerm2,
	SR_PresentDaysTerm1,
	SR_PresentDaysTerm2,
	SR_TotalDaysTerm1,
	SR_TotalDaysTerm2,
	HouseName,
	HouseId,
	AdhaarNumber,
	UIdNumber,
	FatherContactNo ,
	MotherContactNo ,
	FatherMail ,
	MotherMail ,
	Gender,
	CoordinatorEmployeeSign,
	StudentAddress,
	SUId,
	HighestDivisionMark,
	HighestDivisionGrade,
	StreamTitle,
	AdmissionNo,
	AdmissionDate,
	MiddleName ,
	FatherOccupation,
	ResultSheetAdditionalTitle,
	IsDecimal,
	IsAbsentRemark,
	FinalAbsentRemark,
	--Mantis Start - 29923 mantis
	PermanentStreetOne,
	PermanentStreetTwo,
	PermanentStreetThree,
	--Mantis End - 29923 mantis
	CasteCategory,--Mantis 0030303
	
	--Mantis Start - 0031091
		FeeCategory,
		StudentContactNo
	--Mantis End - 0031091
	)
	SELECT 
		Convert(nvarchar(20),A.Id),
		Convert(nvarchar(20),@rExamId),
		Convert(nvarchar(20),EM.CoScholasticScopeId),
		Convert(nvarchar(20),ISNULL(EM.IsDisplayMonthlyAttendance,0)),
		Convert(nvarchar(50),@rClassId),
		A.Id,
		ISNULL(ESGM.Title,'') AS EXAMNAME,
		StuM.Code AS StudCode,
		[sStudent].[fStudentNameGet](stum.FirstName , StuM.MiddleName, StuM.LastName,OM.StudentNameFormatId ) AS Name,
		A.RollNo,
		ISNULL(R.ResultStatus,'') AS ResultStatus,
		CM.DisplayTitle AS ClassName,
		DM.DisplayTitle AS Division,
		R.TotalMarks AS TotalMark,
		R.TotalObtain,
		ISNULL(R.Percentage,0) As Percentage,
		R.RankNumber,
		ISNULL(R.ResultGrade,'') AS ResultGrade,


		EM.IsMarksInDecimal,
		
				
		1,
		--RD.Obtain,
		R.Percentile,
		--SM.Title AS ClassSubject,
		RD.Id AS ResultDetailId,
		R.Id AS ResultId,

		ISNULL(EM.Remark1,'') AS Remark1,
		ISNULL(EM.Remark2,'') AS Remark2,
		ISNULL(EM.Remark3,'') AS Remark3,
		EM.DisplayTitle,
		EM.IsRankNo, 
		EM.IsGrade,
		EM.IsPercentile,
		EM.IsPercentage,
		EM.IsSubjectPercentile,
		EM.IsProcessResult,
		EM.IsNegativeMarks,
		EM.IsIncludeCoScholastic,
		EM.IsOnPrePrinted,
		EM.IsDisplayPhoto,
		EM.IsDisplayBirthDate,
		EM.IsLockForEdit,
		EM.IsDisplaySchoolName,			
		EM.IsDisplayAttendance,
		EM.IsDisplayHeightWeight,
		EM.IsResultStatus,
		REPLICATE(',',EM.FooterAdjustment) AS FooterAdjustmentText,
		REPLICATE(',',EM.DetailAdjustment) AS DetailAdjustmentText,
		EM.FooterAdjustment,
		EM.DetailAdjustment,
		ISNULL(R.ResultRemark,'') AS ResultRemark,
		SO.DateOfBirth,
		AD.HeightTerm1,
		AD.WeightTerm1,
		AD.HeightTerm2,
		AD.WeightTerm2,
		AD.HeightAnnual,
		AD.WeightAnnual,
		AD.PresentDaysTerm1,
		AD.PresentDaysTerm2,
		AD.PresentDaysAnnual,
		AD.TotalDaysTerm1,
		AD.TotalDaysTerm2,
		AD.TotalDaysAnnual,
		EM.TermScopeId,
		(CASE EM.IsDisplayPhoto WHEN 1 THEN
		SI.StudentPhoto
		ELSE NULL END)AS StudentPhoto,
		CASE @GradeStringRemark WHEN '' THEN @GradeString ELSE @GradeStringRemark END AS GradeString,
		EM.IsDisplayGradeString,
		ED.IsDisplayInMarksheet,
		ED.IsShowSubjectGrade,
		ED.IsIncludeInTotal,
	    ED.ClassSubjectId,
		CS.SubjectId AS SubjectId,
		--ED.Maximum,
		(CASE ISNULL(ED.DisplayOrder,0)
		WHEN 0 THEN CS.OrderIndex
		ELSE ED.DisplayOrder END) AS SubjectOrderIndex,
		
		--SM.OrderIndex AS SubjectOrderIndex,
		RD.SubjectGrade,
		SM.Title AS SubjectName,
		ISNULL(SM.Code,'') AS SubjectCode,
		ED.Minimum,
		ED.Maximum,
		RD.Obtain,
		SR.ResultRemark1,
		SR.ResultRemark2,
		ISNULL(SR.TotalDays,0)AS TotalDays,
		ISNULL(SR.PresentDays,0)AS PresentDays,
		SR.StudentHeight,
		SR.StudentWeight,
		SR.ExamSeatNo,
		@rExamId,
		ISNULL(ESGM.Code,'') AS ExamCode,
		EM.IsDisplayParentName,
		SF.FatherName,
		SF.MotherName,
		ED.IsShowSubjectMark,
		--EMP.FirstName
		(CASE ISNULL(OS.AcademicId,0)
		WHEN 0 THEN 0
		ELSE 1 END) AS IsOptionalSubject,
		EM.CoScholasticScopeId,
		EM.IsDisplayPrincipalSign,
		Em.IsDisplayTeacherSign,
		(CASE Em.IsDisplayTeacherSign WHEN 1 THEN
			EI.EmployeeSign
			ELSE NULL END ) AS EmployeeSign,
		BM.Title AS Batch,
		EMP.FirstName + ' ' + EMP.LastName AS ClassTeacherName,
		Stum.FirstName,
		Stum.LastName,
		 
		ISNULL(EM.IsDisplayMonthlyAttendance,0) AS IsDisplayMonthlyAttendance,
		--(CASE EM.IsDisplayImageHeader WHEN 1 THEN
		--	OI.CertificateHeaderA4 
		--	ELSE NULL END)AS  MarksheetHeaderA4,
		(CASE EM.IsDisplayImageHeader WHEN 1 THEN 
		OI.MarksheetHeaderA4 
		ELSE 
			NULL END) AS MarksheetHeaderA4,
		ISNULL(EM.IsDisplayImageHeader,0) AS IsImageHeader,
		ISNULL(SR.MyGoal,'') AS MyGoal,
		ISNULL(SR.AreaOfInterest,'') AS AreaOfInterest,
		ISNULL(SR.Responsibility,'') AS Responsibility,
		ISNULL(SR.MyInterestHobby,'') AS MyInterestHobby,
		ISNULL(SR.MyStrength,'') AS MyStrength,
		ISNULL(SR.Achievements,'') AS Achievements,
		ISNULL(SR.DentalHygiene,'') AS DentalHygiene,
		ISNULL(SR.VisionLeft,'') AS VisionLeft,
		ISNULL(SR.VisionRight,'') AS VisionRight,
		@rIsDetail AS IsDetail,
		ISNULL(SM.SubjectGroupId,0) AS SubjectGroupId,
		ISNULL(SG.Title,'')AS SubjectGroupTitle,
		ISNULL(SG.Code,'') AS SubjectGroupCode,
		ISNULL(EM.DecimalFormat,0) AS DecimalFormat,
		ISNULL(RD.Remark,'') AS SubjectRemark,
		RD.GraceMark,
		RD.KrupaMark,
		@GradeStringHtml,
		SR.ResultRemark3,
		EM.IsDisplayTotalMark,
		ISNULL(SC.ParentContactNo,'') AS ContactNo,
		ISNULL(SC.PresentStreetOne,'')+' '+ISNULL(SC.PresentStreetTwo,'')+' '+ISNULL(SC.PresentStreetThree,'')+' '+ISNULL(SC.PresentCity,'')+' '+ISNULL(SC.PresentState,'') AS PresentAddress,
		ISNULL(EM.TeacherSignCaption,'') AS TeacherSignCaption,
		ISNULL(EM.PrincipalSignCaption,'') AS PrincipalSignCaption,
		ISNULL(Em.ParentSignCaption,'') As ParentSignCaption,
		ISNULL(SR.ImprovementArea,'') As ImprovementArea,
		ISNULL(SR.ProgressArea,'') AS ProgressArea,
		ISNULL(SR.GeneralRemark,'') As GeneralRemark,
		ISNULL(SR.MyActivity,'') AS MyActivity,
		ISNULL(SR.ClassTeacherRemark,'') As ClassTeacherRemark,
		ISNULL(Sr.HouseRemark,'') As HouseRemark,
		ISNULL(BGM.Title,'') AS BloodGroup,
		Convert(nvarchar(20),@rBatchId) AS BatchIdText,
		@rIsShowWithDetail AS IsShowWithDetail,
		IsPresent,
		GradeTitle ,
		RAD.SubjectHighestDivisionGrade,
		RAD.SubjectHighestDivisionMark,
		
		'' AS AchievementsTerm1,
		'' AS AchievementsTerm2,
		'' AS GeneralRemarkTerm1,
		'' AS GeneralRemarkTerm2,
		'' AS ResultRemark1Term1,
		'' AS ResultRemark2Term1, 
		'' AS ResultRemark1Term2,
		'' AS ResultRemark2Term2,
		SR.StudentHeight AS SR_HeightTerm1,
		SR.StudentWeight AS SR_WeightTerm1,
		SR.StudentHeight AS SR_HeightTerm2,
		SR.StudentWeight AS SR_WeightTerm2,
		ISNULL(SR.PresentDays,0) AS SR_PresentDaysTerm1,
	    ISNULL(SR.PresentDays,0) AS SR_PresentDaysTerm2,
	    ISNULL(SR.TotalDays,0) AS SR_TotalDaysTerm1,
	    ISNULL(SR.TotalDays,0) AS SR_TotalDaysTerm2,
	    HM.Title As HouseName,HM.Id as HouseId,
	    ISNULL(SO.AdhaarNumber,'') As AdhaarNumber,
	    ISNULL(SO.UIdNumber,'') As UIdNumber,
		SF.FatherContactNo,
		SF.MotherContactNo,
		SF.FatherMail,
		SF.MotherMail,
		(CASE WHEN SO.GenderId=1 THEN 'Male' ELSE 'Female' END)AS Gender,
		(CASE  When EM.CoordinatorEmployeeId IS NOT NULL AND EM.CoordinatorEmployeeId !=0 then EICoordinator.EmployeeSign ELSE NULL END) AS CoordinatorEmployeeSign,
		(SC.PresentStreetOne +' '+ SC.PresentStreetTwo +' '+ SC.PresentStreetThree +' '+ SC.PresentCity +' '+ SC.PermanentState) AS StudentAddress,
		ISNULL(Stum.SUId,'') AS SUId,
		(CASE EM.IsDisplayHighestDivisionMark
		WHEN 1 THEN [sAssessment].[fGetHighestDivisionMark](A.DivisionId ,RD.ExamDetailId)
		ELSE 0 END) AS HighestDivisionMark,
		(CASE EM.IsDisplayHighestDivisionGrade
		WHEN 1 THEN [sAssessment].[fGetHighestDivisionGrade] (A.DivisionId ,RD.ExamDetailId)
		ELSE '' END) AS HighestDivisionGrade,
		ISNULL(StM.Title,'') AS StreamTitle,
		ISNULL(StuA.AdmissionNumber,0) AS AdmissionNo,
		ISNULL(StuA.AdmissionDate,'') AS AdmissionDate,
		Stum.MiddleName ,
		ISNULL(SF.FatherOccupation,'') AS FatherOccupation,
		ISNULL(EM.ResultSheetAdditionalTitle, '') AS ResultSheetAdditionalTitle,
		CONVERT(bit,@lDecimalConfig) AS IsDecimal,
		CONVERT(bit,@lAbsentRemarkConfig) AS IsAbsentRemark,
		ISNULL(RD.AbsentRemark,'') AS FinalAbsentRemark,
		--add for 29923 mantis start
		SC.PermanentStreetOne,
		SC.PermanentStreetTwo,
		SC.PermanentStreetThree,
		--add for 29923 mantis End
		CSM.Title As CasteCategory,      --Mantis 0030303
		--Mantis Start - 0031091
		ACM.Title AS FeeCategory,
		SC.StudentContactNo AS StudentContactNo
		--Mantis End - 0031091
				
FROM 
	sAssessment.tResultDetail RD
	INNER JOIN sAssessment.tResult R ON R.Id = RD.ResultId
	INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId AND R.ExamId = ED.ExamId
	INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId		
	INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
	INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=CS.SubjectId	
	LEFT JOIN sSetup.tSubjectGroupMaster SG ON SG.Id = Sm.SubjectGroupId				 
	INNER JOIN sStudent.tAcademic A ON A.Id=R.AcademicId
	INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=A.OrgId
	LEFT JOIN sSetup.tOrgImages OI ON OI.Orgid = OM.Id
	INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId
	INNER JOIN sStudent.tStudentMaster StuM ON StuM.Id=A.StudentId
	INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId
	INNER JOIN sSetup.tStreamMaster StM ON CM.StreamId = Stm.Id
	INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId
	LEFT JOIN sHrm.tEmployeeImages EI ON EI.EmployeeId = Dm.InchargeEmployeeId
	LEFT JOIN sHrm.tEmployeeMaster EMP ON EMP.Id = DM.InchargeEmployeeId AND  ISNULL(EMP.IsOtherUser,0) = 0
	INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id = EM.EXAMSUBGROUPID
	LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId=StuM.Id
	Left JOIN sActivity.tHouseMaster HM ON SO.HouseId = HM.Id
	LEFT JOIN sStudent.tAcademicDetail AD ON AD.AcademicId=A.Id
	LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId=StuM.Id
	LEFT JOIN sAssessment.tStudentRemark SR ON R.AcademicId = SR.AcademicId AND R.ExamId = SR.ExamId
	LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId = StuM.Id
	LEFT JOIN sAssessment.tOptionalSubject OS ON OS.AcademicId = R.AcademicId AND OS.ClassSubjectId = ED.ClassSubjectId  AND ED.ExamId = R.ExamId
	LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId=A.StudentId
	LEFT JOIN 	sCommon.tBloodGroupMaster BGM ON BGM.Id=So.BloodGroupId
	LEFT JOIN sAssessment.tGradeSetDetail GS ON GS.GradeSetId=ED.GradeSetId AND ED.GradeSetId = @GradeSetId and RD.SubjectGrade = GS.GradeCode
	LEFT JOIN sAssessment.tResultAnalysisDivisionDetail RAD ON RAD.ClassSubjectId = CS.Id AND RAD.DivisionId = A.DivisionId AND RAD.ExamId = Em.Id
	
	LEFT JOIN sHostel.tAssignRoom AR ON  AR.SourceId=StuM.Id AND AR.SourceTypeId=2003 AND ((BM.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  AND ((AR.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0) AND (BM.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 = StuM.Id 
	LEFT JOIN sHrm.tEmployeeImages EICoordinator ON EICoordinator.EmployeeId = EM.CoordinatorEmployeeId		  
	--LEFT JOIN sAcademic.tTeacherSubjectDivision TSD ON TSD.SubjectId=SM.Id AND TSD.DivisionId = A.DivisionId
	--LEFT JOIN sHrm.tEmployeeMaster EMP ON TSD.EmployeeId = EMP.Id
	LEFT JOIN sStudent.tStudentAdmission StuA ON StuM.Id = StuA.StudentId
	LEFT JOIN sCommon.tCastCategoryMaster CSM ON CSM.Id=SO.CastCategoryId        --Mantis 0030303
	LEFT JOIN sStudent.tAdmissionCategoryMaster ACM ON ACM.Id=StuM.AdmissionCategoryId	--Mantis - 0031091
	 
	 WHERE
		R.ExamId = @rExamId 
		AND ((A.DivisionId =  @rDivisionId) OR (@rDivisionId=0))
		AND ((A.ClassId =  @rClassId) OR (@rClassId=0))		 
		AND ((A.BatchId =  @rBatchId) OR (@rBatchId=0))
		AND ((A.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
		AND ((A.RollNo <= @rToRollNo) OR (@rToRollNo=0))
		AND ((R.RankNumber >= @rFromRank) OR (@rFromRank=0))
		AND ((R.RankNumber <= @rToRank) OR (@rToRank=0))
		AND ((R.ResultGrade = @rGrade) OR (@rGrade=''))
		AND ((StuM.Code=@rCode) OR (@rCode=''))	
		AND ((R.Id = @rResultId) OR (@rResultId = 0))	
		AND ((StuM.StatusId=@rStatusId)OR(@rStatusId=0))
		AND((A.Id=@rAcademicId)OR (@rAcademicId=0))
		AND ((CS.SubjectId=@rSubjectId) OR(@rSubjectId=0) ) 
		AND ((R.TotalObtain>=@rFromObtain) OR (@rFromObtain=0))
		AND ((R.TotalObtain<=@rToObtain) OR (@rToObtain=0))
		AND ((R.Percentage>=@rFromPercentage) OR (@rFromPercentage=0))
		AND ((R.Percentage<=@rToPercentage) OR (@rToPercentage=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 ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0)) 
	AND (ISNULL(StuM.Code,0) IN( SELECT cast(item as nvarchar(20)) FROM  sCommon.fnsplit(@rMultiCode,',')) OR @rMultiCode='')
	    
	Order By ED.DisplayOrder

 --print 'temp insert'
  --SET @IsIncludeSubExam = 1
	create TABLE #tempcombineExam
	(	Id int IDENTITY,
		ExamID int )

	IF (@IsIncludeSubExam = 0)
	BEGIN	
	INSERT INTO #tempcombineExam (ExamID) 
	SELECT SUBEXAMID FROM sAssessment.tExamCombine WHERE ExamId  = @rExamId Order By ExamOrder ASC
 	END
 	ELSE
 	BEGIN
 	-- if we want to display result for both the term with all exam select this option
 	INSERT INTO #tempcombineExam (ExamID) 
	SELECT C.SUBEXAMID FROM sAssessment.tExamCombine C
	INNER JOIN (SELECT SUBEXAMID,ExamOrder FROM sAssessment.tExamCombine WHERE ExamId  = @rExamId) E
	ON C.ExamId = E.SubExamId
	ORDER BY E.ExamOrder,C.ExamOrder
	END
	--print ('tempcombine')
	--SELECT * FROM #tempcombineExam
	--ON 
	
	-- Order By ExamOrder ASC
	--WHERE ExamId in (SELECT SUBEXAMID FROM sAssessment.tExamCombine WHERE ExamId  = @rExamId Order By ExamOrder ASC)
	
	DECLARE @lCount int,@query  AS NVARCHAR(MAX),@lSubExamId int,@lCount1 int
  
	Select @lCount = MAX(Id) from #tempcombineExam
	--SET @lCount1 = @lCount+1
	DECLARE @ExamTitle nvarchar(150)
	while (@lCount > 0)
	begin
		select @lSubExamId = ExamID from #tempcombineExam Where Id = @lCount
		--select @ExamTitle = Title from sAssessment.tExamMaster Where Id = @lSubExamId	
		set @query ='update T SET
					 MaximumMark' + convert(nvarchar(15),@lCount)+ '=ED.Maximum,
					 --Obtain' + convert(nvarchar(15),@lCount)+'= ISNULL(RD.Obtain,0),	--remove this line and add below line for mantis: 31081
					 Obtain' + convert(nvarchar(15),@lCount)+'= RD.Obtain,
					 IsPresent' + convert(nvarchar(15),@lCount)+'=RD.IsPresent,	
					 AbsentRemark' + convert(nvarchar(15),@lCount)+'= ISNULL(RD.AbsentRemark,' + CHAR(39)+CHAR(39) + '),
					 		
					 SubjectGrade' + convert(nvarchar(15),@lCount)+ '=RD.SubjectGrade,
					 TotalDays'+convert(nvarchar(15),@lCount)+'=SR.TotalDays,
					 PresentDays'+convert(nvarchar(15),@lCount)+'=SR.PresentDays,

					 ObtainedMaximum' + convert(nvarchar(15),@lCount)+ '= CASE WHEN EM.IsDisplayHighestDivisionMark = 1
									THEN [sAssessment].[fGetHighestDivisionMark](A.DivisionId ,RD.ExamDetailId)
									ELSE 0  END							
					 From
						sAssessment.tResultDetail RD
						INNER JOIN sAssessment.tResult R ON R.Id = RD.ResultId
						INNER JOIN sStudent.tAcademic A ON A.Id=R.AcademicId
						INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId AND R.ExamId = ED.ExamId
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
						INNER JOIN sAssessment.tExamSubgroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId					
						INNER JOIN 	#TempAllExam  T ON T.ClassSubjectID = ED.ClassSubjectId And T.AcademicId = R.AcademicId	
						LEFT JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND T.AcademicId = SR.AcademicId 									
						WHERE EM.Id =' + convert(nvarchar(15), @lSubExamId)  
						
--print(@query)
	 execute(@query)
	
						
			set @query ='update T set 
				    TotalMarks' + convert(nvarchar(15),@lCount)+ '=R.TotalMarks,
					TotalObtain' + convert(nvarchar(15),@lCount)+ '=R.TotalObtain,
					Percentage' + convert(nvarchar(15),@lCount)+ '=R.Percentage,
					RankNumber' + convert(nvarchar(15),@lCount)+'=R.RankNumber,
					ResultGrade' + convert(nvarchar(15),@lCount)+'=R.ResultGrade,
					Percentile' + convert(nvarchar(15),@lCount)+'=R.Percentile,
					ResultStatus' + convert(nvarchar(15),@lCount)+'=R.ResultStatus,
					Exam' + convert(nvarchar(15),@lCount)+ 'Name=ESGM.ExamSubGroupDisplayTitle,
					Exam' + convert(nvarchar(15),@lCount)+ 'Code=ESGM.Code,
					ExamMaximum' + convert(nvarchar(15),@lCount)+'=ISNULL(EM.ExamMaximum,0)
					 From						
						sAssessment.tResult R						
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id=R.ExamId
						INNER JOIN sAssessment.tExamSubgroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId					
						INNER JOIN 	#TempAllExam  T ON  T.AcademicId = R.AcademicId						
						WHERE EM.Id =' + convert(nvarchar(15), @lSubExamId)  
						
		execute(@query)
		
		Declare @lCombineExamId int
			SELECT @lCombineExamId = EC.ExamId  FROM [sAssessment].[tExamMaster] EM 
										INNER JOIN SASSESSMENT.TEXAMSUBGROUPmASTER ESGM ON ESGM.ID = EM.ExamSubGroupId  
										INNER JOIN sAssessment.tExamCombine EC ON EC.SubExamId=EM.Id AND EC.ExamId in (SELECT SubExamId  FROM sAssessment.tExamCombine WHERE examid=@rExamId) 
										WHERE   (EM.ClassId=@rClassId) AND EM.BatchId =@rBatchId AND EM.Id = @lSubExamId
			--SELECT @lSubCombineExamName
		set @query ='update T set 
					 Exam' + convert(nvarchar(15),@lCount)+ 'CombineExamName =  EM.DisplayTitle
					  From						
						sAssessment.tResult R						
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id=R.ExamId
						INNER JOIN sAssessment.tExamSubgroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId					
						INNER JOIN 	#TempAllExam  T ON  T.AcademicId = R.AcademicId						
						WHERE EM.Id =' + convert(nvarchar(15), @lCombineExamId) 
				
				--Print @query		
		execute(@query)
		
	set @lCount = @lCount -1
	end
	

	IF (@IsIncludeSubExam = 1)
	BEGIN	
		select @lSubExamId = SubExamId from sAssessment.tExamCombine  Where ExamId  = @rExamId AND ExamOrder = 1
		--select @ExamTitle = Title from sAssessment.tExamMaster Where Id = @lSubExamId	
		
		
			set @query ='update T set					 
					SubjectGradeTerm1=RD.SubjectGrade,
					SubjectObtainTerm1 = RD.Obtain,
					 SubjectMaxTerm1 = ED.Maximum
							 
					 From
						 sAssessment.tResultDetail RD
						INNER JOIN  sAssessment.tResult R ON R.Id = RD.ResultId
						INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId AND R.ExamId = ED.ExamId
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
						INNER JOIN sAssessment.tExamSubgroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId					
						INNER JOIN 	#TempAllExam  T ON T.ClassSubjectID = ED.ClassSubjectId And T.AcademicId = R.AcademicId						
						WHERE EM.Id =' + convert(nvarchar(15), @lSubExamId)  
		
				execute(@query)
				
		set @query ='update T set					 
					 
					TotalMarkTerm1 = R.TotalMarks,
					TotalObtainTerm1=R.TotalObtain,
					PercentageTerm1=R.Percentage,
					RankNumberTerm1=R.RankNumber,
					ResultGradeTerm1=R.ResultGrade,
					PercentileTerm1 = R.Percentile,
					ResultStatusTerm1 = R.ResultStatus,
					ExamNameTerm1 = ESGM.Code,
					AchievementsTerm1 = SR.Achievements,
					GeneralRemarkTerm1 = SR.GeneralRemark,
					ResultRemark1Term1 = SR.ResultRemark1,
					ResultRemark2Term1 = SR.ResultRemark2,
					SR_HeightTerm1 = SR.StudentHeight,
					SR_WeightTerm1 = SR.StudentWeight,
					SR_PresentDaysTerm1 = SR.PresentDays,
					SR_TotalDaysTerm1 = SR.TotalDays,
					ExamMaximumTerm1 = EM.ExamMaximum
					
					From
					 
						sAssessment.tResult  R 				
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id = R.ExamId
						LEFT JOIN sAssessment.tStudentRemark SR ON SR.AcademicId = R.AcademicId AND SR.ExamId = EM.Id
						INNER JOIN sAssessment.tExamSubgroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId					
						INNER JOIN 	#TempAllExam  T ON  T.AcademicId = R.AcademicId						
						WHERE EM.Id =' + convert(nvarchar(15), @lSubExamId)  
						
		 	
						
		execute(@query)
		
					select @lSubExamId = SubExamId from sAssessment.tExamCombine  Where ExamId  = @rExamId AND ExamOrder = 2
		--select @ExamTitle = Title from sAssessment.tExamMaster Where Id = @lSubExamId	
		set @query ='update T set					 
					SubjectGradeTerm2=RD.SubjectGrade,
					SubjectObtainTerm2 = RD.Obtain,
					SubjectMaxTerm2= ED.Maximum,
					AchievementsTerm2 = SR.Achievements,
					GeneralRemarkTerm2 = SR.GeneralRemark,
					ResultRemark1Term2 = SR.ResultRemark1,
					ResultRemark2Term2 = SR.ResultRemark2,
					SR_HeightTerm2 = SR.StudentHeight,
					SR_WeightTerm2 = SR.StudentWeight,
					SR_PresentDaysTerm2 = SR.PresentDays,
					SR_TotalDaysTerm2 = SR.TotalDays
									 
					 From
						sAssessment.tResultDetail RD
						INNER JOIN sAssessment.tResult R ON R.Id = RD.ResultId
						INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId AND R.ExamId = ED.ExamId
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
						LEFT JOIN sAssessment.tStudentRemark SR ON SR.AcademicId = R.AcademicId AND SR.ExamId = EM.Id
						INNER JOIN sAssessment.tExamSubgroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId					
						INNER JOIN 	#TempAllExam  T ON T.ClassSubjectID = ED.ClassSubjectId And T.AcademicId = R.AcademicId						
						WHERE EM.Id =' + convert(nvarchar(15), @lSubExamId)  
		execute(@query)
		
		
				set @query ='update T set
 
					TotalMarkTerm2 = R.TotalMarks,
					TotalObtainTerm2=R.TotalObtain,
					PercentageTerm2=R.Percentage,
					RankNumberTerm2=R.RankNumber,
					ResultGradeTerm2=R.ResultGrade,
					PercentileTerm2 = R.Percentile,
					ResultStatusTerm2 = R.ResultStatus,
					ExamNameTerm2 = ESGM.Code,
					ExamMaximumTerm2 = EM.ExamMaximum			
					 From						 
					   sAssessment.tResult R  				 
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id=R.ExamId
						INNER JOIN sAssessment.tExamSubgroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId					
						INNER JOIN 	#TempAllExam  T ON  T.AcademicId = R.AcademicId						
						WHERE EM.Id =' + convert(nvarchar(15), @lSubExamId)  
		execute(@query)
		
		select @lSubExamId = SubExamId from sAssessment.tExamCombine  Where ExamId  = @rExamId AND ExamOrder = 3
		set @query ='update T set					 
					SubjectGradeTerm3=RD.SubjectGrade,
					SubjectObtainTerm3 = RD.Obtain,
					SubjectMaxTerm3= ED.Maximum				 
					 From
						sAssessment.tResultDetail RD
						INNER JOIN sAssessment.tResult R ON R.Id = RD.ResultId
						INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId AND R.ExamId = ED.ExamId
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
						INNER JOIN sAssessment.tExamSubgroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId					
						INNER JOIN 	#TempAllExam  T ON T.ClassSubjectID = ED.ClassSubjectId And T.AcademicId = R.AcademicId						
						WHERE EM.Id =' + convert(nvarchar(15), @lSubExamId)  
		execute(@query)
		set @query ='update T set
 
					TotalMarkTerm3 = R.TotalMarks,
					TotalObtainTerm3=R.TotalObtain,
					PercentageTerm3=R.Percentage,
					RankNumberTerm3=R.RankNumber,
					ResultGradeTerm3=R.ResultGrade,
					PercentileTerm3 = R.Percentile,
					ResultStatusTerm3 = R.ResultStatus,
					ExamNameTerm3 = ESGM.Code,
					ExamMaximumTerm3 = EM.ExamMaximum			
					 From						 
					   sAssessment.tResult R  				 
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id=R.ExamId
						INNER JOIN sAssessment.tExamSubgroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId					
						INNER JOIN 	#TempAllExam  T ON  T.AcademicId = R.AcademicId						
						WHERE EM.Id =' + convert(nvarchar(15), @lSubExamId)  
		execute(@query)
	END
	
	
	
	
	
	--WHILE (@lCount1 <= 6)
	--BEGIN
	--	set @query ='ALTER TABLE #TempAllExam DROP COLUMN MaximumMark' + convert(nvarchar(15),@lCount1)
	--	execute(@query)
	--	set @query ='ALTER TABLE #TempAllExam DROP COLUMN Exam' + convert(nvarchar(150),@lCount1)+ 'Name'
	--	execute(@query)
	--	set @query ='ALTER TABLE #TempAllExam DROP COLUMN SubjectGrade' + convert(nvarchar(150),@lCount1)
	--	execute(@query)		
	--	set @query ='ALTER TABLE #TempAllExam DROP COLUMN Obtain' + convert(nvarchar(15),@lCount1)
	--	execute(@query)
	--	set @query ='ALTER TABLE #TempAllExam DROP COLUMN ExamMaximum' + convert(nvarchar(15),@lCount1)
	--	execute(@query)
	--	SET @lCount1 = @lCount1 + 1
	--END
	
	SELECT @rBuilder1,@rBuilder2, T.*
	FROM #TempAllExam T
	
	--INNER JOIN SSETUP.TCLASSSUBJECT CS ON CS.ID = T.CLASSSUBJECTID
	--WHERE
	--	((T.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
	--	AND ((T.RollNo <= @rToRollNo) OR (@rToRollNo=0))
	--	AND ((T.RankNumber >= @rFromRank) OR (@rFromRank=0))
	--	AND ((T.RankNumber <= @rToRank) OR (@rToRank=0))
	--	AND ((T.ResultGrade = @rGrade) OR (@rGrade=''))
	--	AND ((T.StudCode=@rCode) OR (@rCode=''))		
		--order by T.RollNo,CS.ORDERINDEX
	--SELECT * FROM #TempAllExam	
	drop table #tempcombineExam
	Drop table #TempAllExam
	
	--Select
	--	'' As Builder1,
	--	'' As Builder2,
	--    '' As AcademicIdText,
	--	'' As ExamIdText,
	--	'' As CoScholasticScopeIdText ,
	--	'' As IsDisplayMonthlyAttendanceText,
	--    '' AS ClassIdText,
	--	0 As AcademicId,
	--	'' As ExamName,
	--	'' As StudCode,
	--	'' As StudentName ,
	--	0 As RollNo,
	--	'' As ResultStatus ,	
	--	'' As ClassName ,		
	--	'' As Division ,
	--	0 As TotalMark ,
	--	0 As TotalObtain,
	--	0 As Percentage ,
	--	0 As RankNumber ,
	--	'' As ResultGrade ,
 --       '' As IsMarksInDecimal,
 --             0 As column_visible,

 --             0 As Percentile ,

 --            0 As ResultDetailId, 
 --            0 As ResultId,

	--	'' As Remark1 ,
	--	'' As Remark2 ,
	--	'' As Remark3 ,
	--	'' As DisplayTitle ,		
	--	0 As IsRankNo , 
	--	0 As IsGrade ,
	--	0 As IsPercentile ,
	--	0 As IsPercentage ,
	--	0 As IsSubjectPercentile ,
	--	0 As IsProcessResult ,
	--	0 As IsNegativeMarks ,
	--	0 As IsIncludeCoScholastic ,
	--	0 As IsOnPrePrinted ,
	--	0 As IsDisplayPhoto ,
	--	0 As IsDisplayBirthDate ,
	--	0 As IsLockForEdit ,
	--	0 As IsDisplaySchoolName ,			
	--	0 As IsDisplayAttendance ,
	--	0 As IsDisplayHeightWeight ,
	--	0 As IsResultStatus ,
	--	'' As FooterAdjustmentText ,
	--	'' As DetailAdjustmentText ,
	--	0 As FooterAdjustment ,
	--	0 As DetailAdjustment ,
	--	'' As ResultRemark ,
	--	'' As DateOfBirth ,
	--	0 As HeightTerm1 ,
	--	0 As WeightTerm1 ,
	--	0 As HeightTerm2,
	--	0 As WeightTerm2 ,
	--	0 As HeightAnnual ,
	--	0 As WeightAnnual ,
	--	0 As PresentDaysTerm1,
	--	0 As PresentDaysTerm2 ,
	--	0 As PresentDaysAnnual ,
	--	0 As TotalDaysTerm1 ,
	--	0 As TotalDaysTerm2 ,
	--	0 As TotalDaysAnnual ,
	--	0 As TermScopeId ,		 
	--	0x As StudentPhoto ,
	--	'' As GradeString,
	--	0 As IsDisplayGradeString ,		 
	--	0 As IsDisplayInMarksheet ,
	--	0 As IsShowSubjectGrade ,
	--	0 As IsIncludeInTotal ,
	--	0 As ClassSubjectID ,
	--	0 As SubjectId ,
	--	--Maximum decimal(5,2),
	--	0 As SubjectOrderIndex ,
	--	'' As SubjectGrade ,
	--	'' As SubjectName ,
	--	'' As SubjectCode ,	
	--	0 As SubjectMinimum ,		
	--	0 As SubjectMaximum ,
	--	0 As SubjectObtain ,
	--	'' As ResultRemark1 ,
	--	'' As ResultRemark2,

	--	0 As TotalDays ,
	--	0 As PresentDays ,
	--	0 As StudentHeight,
	--	0 As StudentWeight ,
	--	'' As ExamSeatNo ,
	--    0 As ExamId ,

 --       '' AS ExamCode,

	--	0 As IsDisplayParentName ,
	--	'' As FatherName ,
	--	'' As MotherName ,
	--	0 As IsShowSubjectMark , 
	--	0 As IsOptionalSubject ,
	--	0 As CoScholasticScopeId ,
	--	0 As IsDisplayPrincipalSign ,
	--	0 As IsDisplayTeacherSign ,
	--	0x As EmployeeSign,
 --            '' As Batch,
 --            '' As ClassTeacherName,
 --      '' AS FirstName,
 --      '' AS LastName,
 --            0 As IsDisplayMonthlyAttendance,
	--	0x As MarksheetHeaderA4 ,
	--	0 As IsImageHeader ,
 --            '' As    MyGoal,
 --       '' As  AreaOfInterest,
 --       '' As Responsibility,
 --       '' As MyInterestHobby,
 --       '' As MyStrength,
 --       '' As Achievements,

	--	  '' As DentalHygiene ,
	--	'' As VisionLeft ,
	--	'' As VisionRight ,
 --             0 As IsDetail,
 --             0 AS   SubjectGroupId,
 --             ''   AS SubjectGroupTitle,
 --        '' AS SubjectGroupCode,
 --        '' AS DecimalFormat,
 --        '' AS SubjectRemark,
 --               0 As GraceMark,
 --               0 As KrupaMark,
 --                '' As GradeStringHtml,
 --          '' As ResultRemark3,
 --         0 As IsDisplayTotalMark,
 --         ''  As ContactNo,
	--	'' As PresentAddress ,
	--	'' As TeacherSignCaption ,
	--	'' As PrincipalSignCaption ,
	--	'' As ParentSignCaption ,
 --       '' As ImprovementArea,
 --       '' As ProgressArea,
 --       '' As GeneralRemark,
 --              '' As MyActivity,
 --        ''  As ClassTeacherRemark,

 --        '' As HouseRemark,
	--	  '' As BloodGroup ,
 --         '' As BatchIdText,
 --                0 As IsShowWithDetail,
 --                0 As IsPresent,
 --                ''  As GradeTitle,

 --         '' As SubjectHighestDivisionGrade,
 --                 0  As SubjectHighestDivisionMark,

 --         '' As  AchievementsTerm1,
 --         '' As  AchievementsTerm2,
 --         '' As GeneralRemarkTerm1,
 --         '' As GeneralRemarkTerm2,
 --         '' As ResultRemark1Term1,
 --          '' As ResultRemark2Term1,
 --          '' As ResultRemark1Term2,
 --         '' As ResultRemark2Term2,
 --         0 As SR_HeightTerm1,
 --         0 As SR_WeightTerm1,
 --         0 As SR_HeightTerm2,
 --         0 As SR_WeightTerm2,
 --         0 As SR_PresentDaysTerm1,
 --         0 As SR_PresentDaysTerm2,
 --         0 As SR_TotalDaysTerm1,
 --         0 As SR_TotalDaysTerm2,
 --         '' As HouseName,
 --         0 As HouseId,
 --         '' As AdhaarNumber,
 --         '' As UidNumber,
 --         '' As FatherContactNo,
 --         '' As MotherContactNo,
 --         '' As FatherMail,
 --         '' As MotherMail,
 --         '' AS Gender,
--			0x AS CoordinatorEmployeeSign ,	
 --			'' As FatherOccupation ,
 --			0 AS IsDecimal,
 --			CONVERT(decimal(6,2),0) AS ExamMaximumTerm1,
 --			CONVERT(decimal(6,2),0) AS ExamMaximumTerm2,
 --			CONVERT(decimal(6,2),0) AS ExamMaximumTerm3

-- SELECT @rBuilder1 AS Builder1,@rBuilder2 AS Builder2, T.* FROM sAssessment.tTempAllExam T
 
	END
--	SELECT @rBuilder1 AS Builder1,@rBuilder2 AS Builder2, T.* FROM sAssessment.tTempAllExam T
	
--end
GO
PRINT N'Altering Procedure [sAssessment].[pRptStudentOptionalSubjectListGet]...';


GO

ALTER PROCEDURE [sAssessment].[pRptStudentOptionalSubjectListGet]
         
	@rBatchId int,
	@rClassId bigint,         
    @rDivisionId bigint,
    @rSubjectId bigint ,
	@rClassStatusId int=0   ,
	@rStatusId int=1,
    @rBuilder1 nvarchar(max)='',
	@rBuilder2 nvarchar(max)=''
      
AS
SET NOCOUNT ON

BEGIN
	SELECT
		A.Id AS AcademicId,
		SM.FirstName +' '+SM.LastName AS  StudentName,
		SM.Code,
		A.RollNo,
		ISNULL((SELECT  (STUFF(( SELECT  ',' + ISNULL(SM.Title , ',') FROM sSetup.tSubjectMaster SM
		INNER JOIN sSetup.tClassSubject CS ON CS.SubjectId = SM.Id AND CS.IsOptional = 1
		INNER JOIN sAssessment.tOptionalSubject OS ON OS.AcademicId = A.Id AND OS.ClassSubjectId = CS.Id
		WHERE ((CS.SubjectId = @rSubjectId) OR @rSubjectId = 0)
		FOR XML PATH(''), TYPE).
		value('.','NVARCHAR(MAX)'),1,1,''))),'') As SubjectName,
		ISNULL(SC.StudentContactNo, '-') AS StudentContactNo

	FROM
		sStudent.tAcademic A
		INNER JOIN sStudent.tStudentMaster SM ON A.StudentId = SM.Id 
		INNER JOIN sAssessment.tOptionalSubject OS1 ON OS1.AcademicId = A.Id
		INNER JOIN sSetup.tClassSubject CS1 ON OS1.ClassSubjectId = CS1.Id AND CS1.IsOptional = 1
		INNER JOIN sSetup.tSubjectMaster SM1 ON CS1.SubjectId = SM1.Id
		LEFT OUTER JOIN sStudent.tStudentCommunication AS SC ON SC.StudentId = A.StudentId

		WHERE 
		A.BatchId =@rBatchId 
		AND (A.ClassId = @rClassId OR @rClassId=0)
		AND (DivisionId =@rDivisionId OR @rDivisionId=0)
		AND ((CS1.SubjectId = @rSubjectId) OR @rSubjectId = 0)
		AND (SM.StatusId = @rStatusId OR @rStatusId = 0)					--MantisId : 0031013
		AND (A.ClassStatusId = @rClassStatusId OR @rClassStatusId = 0)		--MantisId : 0031013
END
GO
PRINT N'Altering Procedure [sAttendance].[pRptStudentwiseAbsentDaysGet]...';


GO
ALTER PROCEDURE [sAttendance].[pRptStudentwiseAbsentDaysGet]
	 
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 @rOrgId smallint,
	 @rBatchId int,
	 @rClassId int,
	 @rDivisionId int,
	 @rAttendanceTypeId tinyint,
	 @rSubjectId int,
	 @rFromDate date,
	 @rToDate date,
	 @rStudentCode nvarchar(20),
	 @rDepartmentId int,
	 @rIsAbsentRemark bit = 0	--mantis: 30947
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
 
	SELECT 
			DISTINCT(SA.AcademicId),
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			SA.ClassId,
			SA.DivisionId,
			SA.ClassName,
			SA.DivisionName,
			SA.ClassName+' - '+SA.DivisionName AS ClassDivision,
			SA.Code,
			SA.RollNo,			
			SA.Name,
			(case when @rIsAbsentRemark =0 then sAttendance.fAttendanceGet(SA.AcademicId,@rAttendanceTypeId,@rSubjectId,@rFromDate,@rToDate)	-- remove for mantis: 30947
			else sAttendance.fAttendanceWithRemarkGet(SA.AcademicId,@rAttendanceTypeId,@rSubjectId,@rFromDate,@rToDate) end) AS AttendanceDate,	-- add for mantis: 30947
			AbsentCount=(SELECT COUNT(1) FROM sAttendance.tStudentRegister SR1 
				WHERE SR1.AcademicId=SA.AcademicId 
				AND ((SR1.AttendanceTypeId=@rAttendanceTypeId) OR (@rAttendanceTypeId=0))
				AND ((SR1.SubjectId=@rSubjectId) OR (@rSubjectId=0))
				AND ((SR1.AttendanceDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
				AND ((SR1.AttendanceDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
				AND SR1.IsPresent=0),
		    
		   SA.DivisionOrder,
		   SC.ParentContactNo
	FROM 
			sStudent.vStudentAcademic SA
		INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=SA.AcademicId
		INNER JOIN sStudent.tStudentCommunication SC ON SC.StudentId=SA.StudentId
	WHERE 
			(SA.OrgId=@rOrgId)
		AND	(SA.BatchId = @rBatchId) 
		AND ((SA.ClassId=@rClassId) OR (@rClassId=0))
		AND ((SA.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		AND ((SR.AttendanceTypeId=@rAttendanceTypeId) OR (@rAttendanceTypeId=0))
		AND ((SR.SubjectId=@rSubjectId) OR (@rSubjectId=0))
		AND ((SR.AttendanceDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
		AND ((SR.AttendanceDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
		AND (SR.IsPresent = 0)
		AND (SA.StatusId != 3)
		AND ((SA.Code=@rStudentCode) OR (@rStudentCode=''))
		AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
		GROUP BY SA.AcademicId,SA.ClassId,SA.DivisionId,SA.ClassName,SA.DivisionName,SA.Code,SA.RollNo,SA.Name,SA.DivisionOrder,SC.ParentContactNo,SR.AttendanceRemark;

END
GO
PRINT N'Altering Procedure [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,
		E.Number as EMPNumber            --Mantis - 30977
	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 Procedure [sFee].[pFeeReceiptImportValidate]...';


GO
ALTER PROCEDURE [sFee].[pFeeReceiptImportValidate]
	
		   @rReceiptNumber int,
		   @rBatchId int,
		   @rOrgGroupBatchId int,
		   @rReceiptBookId int,
		   @rSourceId bigint,
		   @rReceiptDetailXml [nvarchar](max),
		   @rChequeNoValidate nvarchar(40) = ''  --Mantis - 0030695

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

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

BEGIN

	DECLARE @lValidatioCode TABLE(Id int identity, Result nvarchar(10))

	SELECT @rOrgGroupBatchId = OrgGroupBatchId FROM sSetup.tBatchMaster where Id = @rBatchId
	
	IF(@rReceiptNumber <> 0)
	BEGIN
		IF EXISTS(SELECT 1 from sFee.tReceipt where ReceiptNumber=@rReceiptNumber AND ReceiptBookId=@rReceiptBookId AND OrgGroupBatchId = @rOrgGroupBatchId)
		BEGIN
			INSERT @lValidatioCode SELECT ('-101')
		END
	END
	--Mantis Start - 0030695
	 DECLARE @lConfigValue1 nvarchar(50)=''
	 SELECT @lConfigValue1 = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 543 AND SourceTypeId = 2010 AND SourceId = LEFT(@rOrgGroupBatchId,4)

	If(@rChequeNoValidate <> '' AND @lConfigValue1 = 'True')
	BEGIN
		IF EXISTS(SELECT 1 FROM SFee.tReceipt where ChequeNo = @rChequeNoValidate  AND ReceiptBookId=@rReceiptBookId AND OrgGroupBatchId = @rOrgGroupBatchId)
		BEGIN
			 INSERT @lValidatioCode SELECT ('-103')
		END
	END
	--Mantis End - 0030695
	EXECUTE [sFee].[pReceiptAddValidate] @rSourceId,'',@rReceiptDetailXml,@rIsCreated = @lIsCreated OUTPUT
 	IF(@lIsCreated = 1)
	BEGIN
		INSERT @lValidatioCode SELECT ('-102')
	END
	
	EXEC sp_xml_removedocument @loDoc
	
	SELECT * FROM @lValidatioCode 
END
GO
PRINT N'Altering Procedure [sFee].[pReceiptAdd]...';


GO

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

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

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

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

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

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

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

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

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

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

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

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

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

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

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

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


GO


ALTER PROCEDURE [sFee].[pRptFeeSummaryGet]
		
	@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 = 0,
	@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,
	@rFeeGroupId int=0,
	@rOrgGroupId 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
	
	IF(@rReportId=20624)
	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,
			FS.FeeCode,
			FS.FeeOrderIndex,
			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,
			@rFeeGroupId As FeeGroup,
			SA.OrgGroupBatchId AS BatchId,
			SA.BatchName AS BatchName,
			0.00 AS CancelAmount,
			0.00 AS Discount,
			SM.Title AS Status,
			SA.SUId AS SUId,
			CONVERT(Date,NULL) AS LeftDate, -- For DataSet Refresh
			'' AS ExemptedRemarkFeeWise,		-- For DataSet Refresh
			'' AS RemarkWithComma,
			'' AS AdditionalRemark,
			'' AS NotApplicableRemark
			
	  FROM 
			sStudent.vStudentAcademic SA
			INNER JOIN sStudent.tStudentAdmission tSA ON tSA.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.FeeHeadId,
					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 (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 
					((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 (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.FeeHeadId,
					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 FS1.BatchId = SA1.BatchId
			AND SA1.ClassId=FS1.ClassId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				AND ((SA1.ClassId=@rClassId) OR (@rClassId=0)) 
				AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				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='')  
			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(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='')
				AND (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR @rOrgGroupId=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 
					INNER JOIN sStudent.tStudentAdmission tSA ON tSA.StudentId = SA1.StudentId
					AND ((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
					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 (R.IsObsolete = 0) 
					AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=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 (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 (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR @rOrgGroupId=0)
					AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')  
					--AND ((tSA.LeftDate > @rUptoDate) OR (tSA.LeftDate Is null))
					AND (tSA.AdmissionDate <= @rUptoDate)
						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)) 
			INNER JOIN sStudent.tStatusMaster SM ON SA.StatusId = SM.Id
			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 (O.OrgGroupId = @rOrgGroupId OR @rOrgGroupId=0)
		AND (ISNULL(SA.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')  
		--AND ((tSA.LeftDate > @rUptoDate) OR (tSA.LeftDate Is null))
		AND (tSA.AdmissionDate <= @rUptoDate)
		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  FHM.OrderIndex,FS.FeeOrderIndex,SA.RollNo
	END
	ELSE IF (@rReportId=20842 OR @rReportId=10150 OR @rReportId=30714 OR @rReportId=30831)
	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,
			FS.FeeCode,
			FS.FeeOrderIndex,
			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,
			@rFeeGroupId As FeeGroup,
			SA.OrgGroupBatchId AS BatchId,
			SA.BatchName AS BatchName,
			0.00 AS CancelAmount,
			0.00 AS Discount,
			SM.Title AS Status,
			SA.SUId AS SUId,
			SAD.LeftDate,
			'' AS ExemptedRemarkFeeWise
			
	  FROM 
			sStudent.vStudentAcademic SA
			INNER JOIN sStudent.tStudentAdmission tSA ON tSA.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.FeeHeadId,
					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 (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 
					((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 (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.Code As FeeCode,
					FM.FeeHeadId,
					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 FS1.BatchId = SA1.BatchId
			AND SA1.ClassId=FS1.ClassId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				AND ((SA1.ClassId=@rClassId) OR (@rClassId=0)) 
				AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				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='')  
			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(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='')
				AND (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR @rOrgGroupId=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 
					INNER JOIN sStudent.tStudentAdmission tSA ON tSA.StudentId = SA1.StudentId
					AND ((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
					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 (R.IsObsolete = 0) 
					AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=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 (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 (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR @rOrgGroupId=0)
					AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')  
					--AND ((tSA.LeftDate > @rUptoDate) OR (tSA.LeftDate Is null))
					AND (tSA.AdmissionDate <= @rUptoDate)
						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)) 
			INNER JOIN sStudent.tStatusMaster SM ON SA.StatusId = SM.Id
			LEFT JOIN sStudent.tStudentAdmission SAD ON SAD.StudentId=SA.StudentId
			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 (O.OrgGroupId = @rOrgGroupId OR @rOrgGroupId=0)
		AND (ISNULL(SA.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')  
		--AND ((tSA.LeftDate > @rUptoDate) OR (tSA.LeftDate Is null))
		AND (tSA.AdmissionDate <= @rUptoDate)
		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  FHM.OrderIndex,FS.FeeOrderIndex,SA.RollNo
	END
	ELSE IF(@rReportId=30655)
	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,
			@rFeeGroupId As FeeGroup,
			SA.OrgGroupBatchId AS BatchId,
			SA.BatchName AS BatchName,
			0.00 AS CancelAmount,
			'' AS ExemptedRemarkFeeWise	
	  FROM 
			sStudent.vStudentAcademic SA
			INNER JOIN sStudent.tStudentAdmission tSA ON tSA.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.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))
				AND (ISNULL(SA1.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='')
				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 (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.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 FS1.BatchId = SA1.BatchId
			AND SA1.ClassId=FS1.ClassId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				AND ((SA1.ClassId=@rClassId) OR (@rClassId=0)) 
				AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				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='')  
			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(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='')
				AND (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR @rOrgGroupId=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.OrgId=@rOrgId) OR (@rOrgId=0))
					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 (R.IsObsolete = 0) 
					AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=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 (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 (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR @rOrgGroupId=0)
					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
			 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  ISNULL(FA.NotApplicableAmount,0) > 0) 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 (O.OrgGroupId = @rOrgGroupId OR @rOrgGroupId=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
	ELSE IF(@rReportId=30799)
	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(R1.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(R1.PaidAmount,0.00)AS PendingAmount,
			ISNULL(FA.Remark,'') AS Remark,
			FS.ReceiptBookId,
			FS.FeeName,
			FS.FeeCode,
			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,
			@rFeeGroupId As FeeGroup,
			SA.OrgGroupBatchId AS BatchId,
			SA.BatchName AS BatchName,
			ISNULL(R2.TotalReceiptAmount,0.00) AS CancelAmount,
			'' AS ExemptedRemarkFeeWise	
	  FROM 
			sStudent.vStudentAcademic SA
			INNER JOIN sStudent.tStudentAdmission tSA ON tSA.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.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 (ISNULL(SA1.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='')
				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 (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.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 FS1.BatchId = SA1.BatchId
			AND SA1.ClassId=FS1.ClassId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				AND ((SA1.ClassId=@rClassId) OR (@rClassId=0)) 
				AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				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='') 
			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 (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR @rOrgGroupId=0)
				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,ISNULL(R.TotalReceiptAmount,0)AS TotalReceiptAmount
				FROM
						sFee.tReceipt R 
					INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id 
					INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id
					INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id
					INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=R.SourceId 
					INNER JOIN sStudent.tStudentAdmission tSA ON tSA.StudentId = SA1.StudentId
					AND ((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
					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 (R.IsObsolete = 0) 
					AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=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 (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 (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR @rOrgGroupId=0)
					AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')  
					--AND ((tSA.LeftDate > @rUptoDate) OR (tSA.LeftDate Is null))
					AND (tSA.AdmissionDate <= @rUptoDate)
						GROUP BY FeeSetupId,R.SourceId,R.TotalReceiptAmount
			
			) R1 ON R1.FeeSetupId = FS.Id AND SA.AcademicId = R1.SourceId
			LEFT JOIN
			(
				SELECT 
						ISNULL(SUM(RD.Amount),0) AS PaidAmount,RD.FeeSetupId ,R.SourceId,ISNULL(R.TotalReceiptAmount,0)AS TotalReceiptAmount
				FROM
						sFee.tReceipt R 
					INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id 
					INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id
					INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id
					INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=R.SourceId 
					INNER JOIN sStudent.tStudentAdmission tSA ON tSA.StudentId = SA1.StudentId
					AND ((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
					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 (R.IsObsolete = 1) 
					AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=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 (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 (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR @rOrgGroupId=0)
					AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')  
					--AND ((tSA.LeftDate > @rUptoDate) OR (tSA.LeftDate Is null))
					AND (tSA.AdmissionDate <= @rUptoDate)
						GROUP BY FeeSetupId,R.SourceId,R.TotalReceiptAmount
			
			) R2 ON R2.FeeSetupId = FS.Id AND SA.AcademicId = R2.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 (O.OrgGroupId = @rOrgGroupId OR @rOrgGroupId=0)
		AND (ISNULL(SA.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')  
		--AND ((tSA.LeftDate > @rUptoDate) OR (tSA.LeftDate Is null))
		AND (tSA.AdmissionDate <= @rUptoDate)
		 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
	ELSE IF(@rReportId=30825)
	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,
			FS.FeeCode,
			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,
			@rFeeGroupId As FeeGroup,
			SA.OrgGroupBatchId AS BatchId,
			SA.BatchName AS BatchName,
			0.00 AS CancelAmount,
			0.00 AS Discount,
			ISNULL(SC.ParentContactNo,'') AS ParentContactNo,
			'' AS ExemptedRemarkFeeWise	
	  FROM 
			sStudent.vStudentAcademic SA
			INNER JOIN sStudent.tStudentAdmission tSA ON tSA.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.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
				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 
					((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 (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.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 FS1.BatchId = SA1.BatchId
			AND SA1.ClassId=FS1.ClassId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				AND ((SA1.ClassId=@rClassId) OR (@rClassId=0)) 
				AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				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='')  
			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 (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR @rOrgGroupId=0)
				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 
					INNER JOIN sStudent.tStudentAdmission tSA ON tSA.StudentId = SA1.StudentId
					AND ((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
					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 (R.IsObsolete = 0) 
					AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=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 (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 (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR @rOrgGroupId=0)
					AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')  
					--AND ((tSA.LeftDate > @rUptoDate) OR (tSA.LeftDate Is null))
					--AND (tSA.AdmissionDate <= @rUptoDate)
					AND ((tSA.LeftDate > @rUptoDate) OR (tSA.LeftDate Is null AND SA1.StatusId = 1))
						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)) 
			LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId = SA.StudentId
			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 (O.OrgGroupId = @rOrgGroupId OR @rOrgGroupId=0)
		AND (ISNULL(SA.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')  
		--AND ((tSA.LeftDate > @rUptoDate) OR (tSA.LeftDate Is null))
		--AND (tSA.AdmissionDate <= @rUptoDate)
		AND ((tSA.LeftDate > @rUptoDate) OR (tSA.LeftDate Is null AND SA.StatusId = 1))
		 --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
	--ELSE IF(@rReportId=30821)
	--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(R.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,
	--		FS.FeeCode,
	--		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,
	--		@rFeeGroupId As FeeGroup,
	--		SA.OrgGroupBatchId AS BatchId,
	--		SA.BatchName AS BatchName,
	--		0.00 AS CancelAmount,
	--		(Select ISNULL(SUM(R.DiscountAmount),0) FROM  sFee.tReceipt R Where R.SourceId=SA.AcademicId)AS Discount
	--  FROM 
	--		sStudent.vStudentAcademic SA
	--		INNER JOIN sStudent.tStudentAdmission tSA ON tSA.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.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='')  
	--				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.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 FS1.BatchId = SA1.BatchId
	--		AND SA1.ClassId=FS1.ClassId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
	--			AND ((SA1.ClassId=@rClassId) OR (@rClassId=0)) 
	--			AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
	--			AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')  
	--		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 (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR @rOrgGroupId=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,R.DiscountAmount
	--			FROM
	--					sFee.tReceipt R 
	--				INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id 
	--				INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id
	--				INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id
	--				INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=R.SourceId 
	--				INNER JOIN sStudent.tStudentAdmission tSA ON tSA.StudentId = SA1.StudentId
	--				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 OR @rOrgGroupBatchId=0)
	--				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 (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR @rOrgGroupId=0)
	--				AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')  
	--				--AND ((tSA.LeftDate > @rUptoDate) OR (tSA.LeftDate Is null))
	--				AND (tSA.AdmissionDate <= @rUptoDate)
	--					GROUP BY FeeSetupId,R.SourceId,R.DiscountAmount
			
	--		) 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 (O.OrgGroupId = @rOrgGroupId OR @rOrgGroupId=0)
	--	AND (ISNULL(SA.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')  
	--	--AND ((tSA.LeftDate > @rUptoDate) OR (tSA.LeftDate Is null))
	--	AND (tSA.AdmissionDate <= @rUptoDate)
	--	 AND ((SA.ClassStatusId=@rClassStatusId) OR (@rClassStatusId=0))  	
	--	Order by SA.RollNo 
	--END
	ELSE IF(@rReportId=30920)
	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.StatusId,
			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,
			--CASE WHEN ISNULL(FA.Remark,'') ='' THEN ''	ELSE [sFee].[fFeeAllocationRemarkGet](FA.SourceId,2) END as RemarkWithComma,
			'' RemarkWithComma,
			--CASE WHEN ISNULL(FA.DiscountRemark,'') ='' THEN ''	ELSE [sFee].[fFeeAllocationRemarkGet](FA.SourceId,1) END as ExampltedRemark,

			--CASE WHEN ISNULL(DiscountRemark,'') ='' THEN ''
			--ELSE
			(STUFF((SELECT  ','+DiscountRemark	FROM sFee.tFeeAllocation WHERE SourceId = FA.SourceId	
			ORDER BY DiscountRemark	FOR XML PATH('')), 1, 1,NULL)) as ExampltedRemark,

			''  AdditionalRemark,
			'' NotApplicableRemark,
			FS.ReceiptBookId,
			FS.FeeName,
			--FS.FeeCode,
			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,
			@rFeeGroupId As FeeGroup,
			SA.OrgGroupBatchId AS BatchId,
			SA.BatchName AS BatchName,
			0.00 AS CancelAmount,
			'' AS ExemptedRemarkFeeWise	
	  FROM 
			sStudent.vStudentAcademic SA
			INNER JOIN sStudent.tStudentAdmission tSA ON tSA.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.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 (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='')
				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 (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.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 FS1.BatchId = SA1.BatchId
			AND SA1.ClassId=FS1.ClassId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				AND ((SA1.ClassId=@rClassId) OR (@rClassId=0)) 
				AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				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='')  
			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(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='')
				AND (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR @rOrgGroupId=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.OrgId=@rOrgId) OR (@rOrgId=0))
					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 (R.IsObsolete = 0) 
					AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=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 (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 (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR @rOrgGroupId=0)
					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
			 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 (O.OrgGroupId = @rOrgGroupId OR @rOrgGroupId=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 (tSA.AdmissionDate <= @rUptoDate)
			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

	ELSE IF(@rReportId=30232) -- Mantis : 0028532  #Start 
	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.StatusId,
			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,
			--CASE WHEN ISNULL(FA.Remark,'') ='' THEN ''	ELSE [sFee].[fFeeAllocationRemarkGet](FA.SourceId,2) END as RemarkWithComma,
			'' RemarkWithComma,
			--CASE WHEN ISNULL(FA.DiscountRemark,'') ='' THEN ''	ELSE [sFee].[fFeeAllocationRemarkGet](FA.SourceId,1) END as ExampltedRemark,

			CASE WHEN ISNULL(DiscountRemark,'') ='' THEN ''
			ELSE
			(STUFF((SELECT  ','+DiscountRemark	FROM sFee.tFeeAllocation WHERE SourceId = FA.SourceId	
			ORDER BY DiscountRemark	FOR XML PATH('')), 1, 1,NULL)) END as ExampltedRemark,

			--CASE WHEN ISNULL(FA.DiscountRemark,'') ='' THEN ''	ELSE [sFee].[fFeeAllocationRemarkGet](FA.SourceId) END  as ExampltedRemark,

			--CASE WHEN ISNULL(FA.AdditionalRemark,'') ='' THEN ''	ELSE [sFee].[fFeeAllocationRemarkGet](FA.SourceId,3) END as AdditionalRemark,
			''  AdditionalRemark,
			--CASE WHEN ISNULL(FA.NotApplicableRemark,'') ='' THEN ''	ELSE [sFee].[fFeeAllocationRemarkGet](FA.SourceId,4) END as NotApplicableRemark,
			'' NotApplicableRemark,
			FS.ReceiptBookId,
			FS.FeeName,
			--FS.FeeCode,
			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,
			@rFeeGroupId As FeeGroup,
			SA.OrgGroupBatchId AS BatchId,
			SA.BatchName AS BatchName,
			0.00 AS CancelAmount,
			SAD.LeftDate,
			'' AS ExemptedRemarkFeeWise	
	  FROM 
			sStudent.vStudentAcademic SA
			INNER JOIN sStudent.tStudentAdmission tSA ON tSA.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.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))
				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 
					((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 (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.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 FS1.BatchId = SA1.BatchId
			AND SA1.ClassId=FS1.ClassId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				AND ((SA1.ClassId=@rClassId) OR (@rClassId=0)) 
				AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				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='') 
			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 (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR @rOrgGroupId=0)
				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.OrgId=@rOrgId) OR (@rOrgId=0))
					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 (R.IsObsolete = 0) 
					AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=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 (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 (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR @rOrgGroupId=0)
					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
			 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)) 
			LEFT JOIN sStudent.tStudentAdmission SAD ON SAD.StudentId=SA.StudentId
			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 (O.OrgGroupId = @rOrgGroupId OR @rOrgGroupId=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 -- #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.StatusId,
			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,
			--CASE WHEN ISNULL(FA.Remark,'') ='' THEN ''	ELSE [sFee].[fFeeAllocationRemarkGet](FA.SourceId,2) END as RemarkWithComma,
			'' RemarkWithComma,
			--CASE WHEN ISNULL(FA.DiscountRemark,'') ='' THEN ''	ELSE [sFee].[fFeeAllocationRemarkGet](FA.SourceId,1) END as ExampltedRemark,

			CASE WHEN ISNULL(DiscountRemark,'') ='' THEN ''
			ELSE
			(STUFF((SELECT  ','+DiscountRemark	FROM sFee.tFeeAllocation WHERE SourceId = FA.SourceId	
			ORDER BY DiscountRemark	FOR XML PATH('')), 1, 1,NULL)) END as ExampltedRemark,

			--CASE WHEN ISNULL(FA.DiscountRemark,'') ='' THEN ''	ELSE [sFee].[fFeeAllocationRemarkGet](FA.SourceId) END  as ExampltedRemark,

			--CASE WHEN ISNULL(FA.AdditionalRemark,'') ='' THEN ''	ELSE [sFee].[fFeeAllocationRemarkGet](FA.SourceId,3) END as AdditionalRemark,
			''  AdditionalRemark,
			--CASE WHEN ISNULL(FA.NotApplicableRemark,'') ='' THEN ''	ELSE [sFee].[fFeeAllocationRemarkGet](FA.SourceId,4) END as NotApplicableRemark,
			'' NotApplicableRemark,
			FS.ReceiptBookId,
			FS.FeeName,
			--FS.FeeCode,
			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,
			@rFeeGroupId As FeeGroup,
			SA.OrgGroupBatchId AS BatchId,
			SA.BatchName AS BatchName,
			0.00 AS CancelAmount,
			SAD.LeftDate,
			(STUFF((SELECT  ','+ tFA.DiscountRemark	FROM sFee.tFeeAllocation tFA INNER JOIN sFee.tFeeSetup tFS On tFS.Id = tFA.FeeSetupId
			WHERE tFA.SourceId = FA.SourceId AND (tFS.FeeId IN (SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,',')) OR @rFeeId='')
			ORDER BY tFA.DiscountRemark	FOR XML PATH('')), 1, 1,NULL)) AS ExemptedRemarkFeeWise		-- Mantis Id : 0030870
	  FROM 
			sStudent.vStudentAcademic SA
			INNER JOIN sStudent.tStudentAdmission tSA ON tSA.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.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))
				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 
					((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 (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.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 FS1.BatchId = SA1.BatchId
			AND SA1.ClassId=FS1.ClassId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				AND ((SA1.ClassId=@rClassId) OR (@rClassId=0)) 
				AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				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='') 
			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 (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR @rOrgGroupId=0)
				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.OrgId=@rOrgId) OR (@rOrgId=0))
					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 (R.IsObsolete = 0) 
					AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=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 (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 (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR @rOrgGroupId=0)
					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
			 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)) 
			LEFT JOIN sStudent.tStudentAdmission SAD ON SAD.StudentId=SA.StudentId
			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 (O.OrgGroupId = @rOrgGroupId OR @rOrgGroupId=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
	
	
	
END
GO
PRINT N'Altering Procedure [sHrm].[pEmployeeDataUpdateGet]...';


GO
 
ALTER PROCEDURE [sHrm].[pEmployeeDataUpdateGet]
	 @rCategoryId int,
	 @rSubCategory nvarchar(100),
	 @rOrgId int,
	 @rIsBlank bit,
	 @rStatusId int,
	 @rDepartmentId int,
	 @rGroupId int,
	 @rTypeId int,
	 @rGradeId int 
	  
	 --@rOrderBy int
	 
AS
SET NOCOUNT ON

BEGIN

		 DECLARE @lDataTypeId nvarchar(1)
		 IF(@rSubCategory = 'EmployeeBusinessHead')
		 BEGIN
			SELECT @lDataTypeId=DataTypeId FROM sCommon.tUpdateFieldMaster WHERE Field='OrganizationHeadManager'
		 END
		SELECT @lDataTypeId=DataTypeId FROM sCommon.tUpdateFieldMaster WHERE Field=@rSubCategory
		
		IF(@rSubCategory = 'MaritalStatus' OR @rSubCategory = 'Gender' OR @rSubCategory = 'Religion' OR @rSubCategory = 'BloodGroup'
		   OR @rSubCategory = 'OrganizationDepartment' OR @rSubCategory = 'EmployeeType' OR @rSubCategory = 'EmployeeBusinessHead'
			OR @rSubCategory = 'EmployeeGroup' OR @rSubCategory = 'EmployeeGrade' OR @rSubCategory = 'EmployeeDesignation'
			 OR @rSubCategory='Payroll' OR @rSubCategory='PayrollGroup'
			  OR @rSubCategory='OrgGroupDepartment'  OR @rSubCategory='EmployeeManager' OR @rSubCategory='CustomTag'
			  OR @rSubCategory='Tribe'
			 )
		BEGIN
			SET @rSubCategory = @rSubCategory + 'Id'
		END
		
		 ELSE IF ( @rSubCategory = 'CasteCategory')
			BEGIN 
		 		SET @rSubCategory = Replace(@rSubCategory,'Caste','Cast') + 'Id'
		 END
		 ELSE IF(@rSubCategory = 'NotEmployee')
		 BEGIN
		 SET @rSubCategory = Replace(@rSubCategory,'NotEmployee','IsOtherUser')
		 END
		 ELSE IF(@rSubCategory = 'PaymentMode')
		 BEGIN
		 SET @rSubCategory = Replace(@rSubCategory,'PaymentMode','PayTypeId')
		 END
		
		 Declare @Sql nvarchar(max)
		 print @lDataTypeId
		 SET @Sql =  CASE @rCategoryId					  
					 WHEN 1 THEN -- EmployeeCommunication
						'Select EM.Id,EM.EmployeeId,EM.Code,EM.EmployeeName,EM.LastName,EM.EmployeeGroup,EM.DepartmentName,
						CASE WHEN '+@lDataTypeId+'=1 THEN
						ISNULL(EC.'+@rSubCategory+','''')
						WHEN '+@lDataTypeId+'=2 THEN
						ISNULL(EC.'+@rSubCategory+',''0'')
						WHEN '+@lDataTypeId+'=3 THEN
						ISNULL(EC.'+@rSubCategory+',''False'')
						WHEN '+@lDataTypeId+'=4 THEN
						ISNULL(EC.'+@rSubCategory+',''0001/01/01'')
						WHEN '+@lDataTypeId+'=5 THEN
						ISNULL(EC.'+@rSubCategory+',''0'')
						END AS SubCategory
							FROM 
							sHrm.vExtEmployeeMaster EM
							LEFT JOIN sHrm.tEmployeeCommunications EC ON EC.EmployeeId=EM.EmployeeId 
							Where  ISNULL(EM.IsOtherUser,0) = 0 AND EM.OrgId='+CAST(@rOrgId AS nvarchar(15)) 
							
							+ 'AND (EM.StatusId='+ CAST(@rStatusId AS nvarchar(15)) +' OR '+CAST(@rStatusId AS nvarchar(15))+'=0)
							AND (EM.DepartmentId='+ CAST(@rDepartmentId AS nvarchar(15)) +' OR '+CAST(@rDepartmentId AS nvarchar(15))+'=0)
							AND (EM.EmployeeGroupId='+ CAST(@rGroupId AS nvarchar(15)) +' OR '+CAST(@rGroupId AS nvarchar(15))+'=0)
							AND (EM.EmployeeGradeId='+ CAST(@rGradeId AS nvarchar(15)) +' OR '+CAST(@rGradeId AS nvarchar(15))+'=0)
							AND (EM.EmployeeTypeId='+ CAST(@rTypeId AS nvarchar(15)) +' OR '+CAST(@rTypeId AS nvarchar(15))+'=0)
							AND 
							('+CAST(@rIsBlank AS nvarchar(1))+'=0 
								OR ('+@lDataTypeId+'=1 AND ISNULL(EC.'+@rSubCategory+','''')='''')
								OR ('+@lDataTypeId+'=2 AND ISNULL(EC.'+@rSubCategory+',''0'')=''0'')
								OR ('+@lDataTypeId+'=3 AND ISNULL(EC.'+@rSubCategory+',''False'')=''False'')
								OR ('+@lDataTypeId+'=4 AND ISNULL(EC.'+@rSubCategory+',''0001/01/01'')=''0001/01/01'') 
							) ORDER BY EM.Number'
					 WHEN 2 THEN -- Other
						'Select EM.Id,EM.EmployeeId,EM.Code,EM.EmployeeName,EM.LastName,EM.EmployeeGroup,EM.DepartmentName,
						CASE WHEN '+@lDataTypeId+'=1 THEN
						ISNULL(EP.'+@rSubCategory+','''')
						WHEN '+@lDataTypeId+'=2 THEN
						ISNULL(EP.'+@rSubCategory+',''0'')
						WHEN '+@lDataTypeId+'=3 THEN
						ISNULL(EP.'+@rSubCategory+',''False'')
						WHEN '+@lDataTypeId+'=4 THEN
						ISNULL(EP.'+@rSubCategory+',''0001/01/01'')
						WHEN '+@lDataTypeId+'=5 THEN
						ISNULL(EP.'+@rSubCategory+',''0'')
						END AS SubCategory
							FROM 
							sHrm.vExtEmployeeMaster EM
							LEFT JOIN sHrm.tEmployeePersonalDetail EP ON EP.EmployeeId=EM.EmployeeId  
							Where ISNULL(EM.IsOtherUser,0) = 0 AND EM.OrgId='+CAST(@rOrgId AS nvarchar(15))
							+'AND (EM.StatusId='+ CAST(@rStatusId AS nvarchar(15)) +' OR '+CAST(@rStatusId AS nvarchar(15))+'=0)
							AND (EM.DepartmentId='+ CAST(@rDepartmentId AS nvarchar(15)) +' OR '+CAST(@rDepartmentId AS nvarchar(15))+'=0)
							AND (EM.EmployeeGroupId='+ CAST(@rGroupId AS nvarchar(15)) +' OR '+CAST(@rGroupId AS nvarchar(15))+'=0)
							AND (EM.EmployeeGradeId='+ CAST(@rGradeId AS nvarchar(15)) +' OR '+CAST(@rGradeId AS nvarchar(15))+'=0)
							AND (EM.EmployeeTypeId='+ CAST(@rTypeId AS nvarchar(15)) +' OR '+CAST(@rTypeId AS nvarchar(15))+'=0)
							AND 
							('+CAST(@rIsBlank AS nvarchar(1))+'=0 
								OR ('+@lDataTypeId+'=1 AND ISNULL(EP.'+@rSubCategory+','''')='''')
								OR ('+@lDataTypeId+'=2 AND ISNULL(EP.'+@rSubCategory+',''0'')=''0'')
								OR ('+@lDataTypeId+'=3 AND ISNULL(EP.'+@rSubCategory+',''False'')=''False'')
								OR ('+@lDataTypeId+'=4 AND ISNULL(EP.'+@rSubCategory+',''0001/01/01'')=''0001/01/01'') 
							) ORDER BY EM.Number'
							
					WHEN 3 THEN -- JobDetail
					
					CASE WHEN  @rSubCategory ='EmployeeManagerId' then 
						
						'Select EM.Id,EM.EmployeeId,EM.Code,EM.EmployeeName,EM.LastName,EM.EmployeeGroup,EM.DepartmentName,
						CASE WHEN '+@lDataTypeId+'=1 THEN ISNULL((SELECT EmployeeId FROM sHrm.vExtEmployeeMaster WHERE EmployeeId=EJD.EmployeeManagerId AND ISNULL(IsOtherUser,0) = 0 ),'''')
						WHEN '+@lDataTypeId+'=2 THEN ISNULL((SELECT EmployeeId FROM sHrm.vExtEmployeeMaster WHERE EmployeeId=EJD.EmployeeManagerId AND ISNULL(IsOtherUser,0) = 0 ),''0'')
						WHEN '+@lDataTypeId+'=3 THEN ISNULL((SELECT EmployeeId FROM sHrm.vExtEmployeeMaster WHERE EmployeeId=EJD.EmployeeManagerId AND ISNULL(IsOtherUser,0) = 0 ),''False'')
						WHEN '+@lDataTypeId+'=4 THEN ISNULL((SELECT EmployeeId FROM sHrm.vExtEmployeeMaster WHERE EmployeeId=EJD.EmployeeManagerId AND ISNULL(IsOtherUser,0) = 0 ),''0001/01/01'')
						WHEN '+@lDataTypeId+'=5 THEN ISNULL((SELECT EmployeeId FROM sHrm.vExtEmployeeMaster WHERE EmployeeId=EJD.EmployeeManagerId AND ISNULL(IsOtherUser,0) = 0 ),''0'')
						END AS SubCategory 
							FROM 
							sHrm.vExtEmployeeMaster EM
							INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.EmployeeId  
							Where ISNULL(EM.IsOtherUser,0) = 0 AND EM.OrgId='+CAST(@rOrgId AS nvarchar(15))
							+'AND (EM.StatusId='+ CAST(@rStatusId AS nvarchar(15)) +' OR '+CAST(@rStatusId AS nvarchar(15))+'=0)
							AND (EM.DepartmentId='+ CAST(@rDepartmentId AS nvarchar(15)) +' OR '+CAST(@rDepartmentId AS nvarchar(15))+'=0)
							AND (EM.EmployeeGroupId='+ CAST(@rGroupId AS nvarchar(15)) +' OR '+CAST(@rGroupId AS nvarchar(15))+'=0)
							AND (EM.EmployeeGradeId='+ CAST(@rGradeId AS nvarchar(15)) +' OR '+CAST(@rGradeId AS nvarchar(15))+'=0)
							AND (EM.EmployeeTypeId='+ CAST(@rTypeId AS nvarchar(15)) +' OR '+CAST(@rTypeId AS nvarchar(15))+'=0)
							AND 
							('+CAST(@rIsBlank AS nvarchar(1))+'=0 
								OR ('+@lDataTypeId+'=1 AND ISNULL((SELECT CODE FROM sHrm.vExtEmployeeMaster WHERE EmployeeId=EJD.EmployeeManagerId AND ISNULL(IsOtherUser,0) = 0),'''')='''')
								OR ('+@lDataTypeId+'=2 AND ISNULL((SELECT CODE FROM sHrm.vExtEmployeeMaster WHERE EmployeeId=EJD.EmployeeManagerId AND ISNULL(IsOtherUser,0) = 0 ),''0'')=''0'')
								OR ('+@lDataTypeId+'=3 AND ISNULL((SELECT CODE FROM sHrm.vExtEmployeeMaster WHERE EmployeeId=EJD.EmployeeManagerId AND ISNULL(IsOtherUser,0) = 0 ),''False'')=''False'')
								OR ('+@lDataTypeId+'=4 AND ISNULL((SELECT CODE FROM sHrm.vExtEmployeeMaster WHERE EmployeeId=EJD.EmployeeManagerId AND ISNULL(IsOtherUser,0) = 0 ),''0001/01/01'')=''0001/01/01'') 
							) ORDER BY EM.Number'

							else

								'Select EM.Id,EM.EmployeeId,EM.Code,EM.EmployeeName,EM.LastName,EM.EmployeeGroup,EM.DepartmentName,
								CASE WHEN '+@lDataTypeId+'=1 THEN ISNULL(EJD.'+@rSubCategory+','''')
								WHEN '+@lDataTypeId+'=2 THEN ISNULL(EJD.'+@rSubCategory+',''0'')
								WHEN '+@lDataTypeId+'=3 THEN ISNULL(EJD.'+@rSubCategory+',''False'')
								WHEN '+@lDataTypeId+'=4 THEN ISNULL(EJD.'+@rSubCategory+',''0001/01/01'')
								WHEN '+@lDataTypeId+'=5 THEN ISNULL(EJD.'+@rSubCategory+',''0'')
								END AS SubCategory 
								FROM 
								sHrm.vExtEmployeeMaster EM
								INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.EmployeeId  
								Where ISNULL(EM.IsOtherUser,0) = 0 AND EM.OrgId='+CAST(@rOrgId AS nvarchar(15))
								+'AND (EM.StatusId='+ CAST(@rStatusId AS nvarchar(15)) +' OR '+CAST(@rStatusId AS nvarchar(15))+'=0)
								AND (EM.DepartmentId='+ CAST(@rDepartmentId AS nvarchar(15)) +' OR '+CAST(@rDepartmentId AS nvarchar(15))+'=0)
								AND (EM.EmployeeGroupId='+ CAST(@rGroupId AS nvarchar(15)) +' OR '+CAST(@rGroupId AS nvarchar(15))+'=0)
								AND (EM.EmployeeGradeId='+ CAST(@rGradeId AS nvarchar(15)) +' OR '+CAST(@rGradeId AS nvarchar(15))+'=0)
								AND (EM.EmployeeTypeId='+ CAST(@rTypeId AS nvarchar(15)) +' OR '+CAST(@rTypeId AS nvarchar(15))+'=0)
								AND 
									('+CAST(@rIsBlank AS nvarchar(1))+'=0 
									OR ('+@lDataTypeId+'=1 AND ISNULL(EJD.'+@rSubCategory+','''')='''')
									OR ('+@lDataTypeId+'=2 AND ISNULL(EJD.'+@rSubCategory+',''0'')=''0'')
									OR ('+@lDataTypeId+'=3 AND ISNULL(EJD.'+@rSubCategory+',''False'')=''False'')
									OR ('+@lDataTypeId+'=4 AND ISNULL(EJD.'+@rSubCategory+',''0001/01/01'')=''0001/01/01'') 
								) ORDER BY EM.Number'
							end
					 
					WHEN 4 THEN --General
						
						CASE WHEN  @rSubCategory ='CustomTagId' then 

							'Select  EM.Id,EM.EmployeeId,EM.Code,EM.EmployeeName,EM.LastName,EM.EmployeeGroup,EM.DepartmentName,STUFF( (SELECT DISTINCT '','' + CTM.Title FROM sHrm.tEmployeeCustomTag ECT INNER JOIN sHrm.tCustomTagMaster CTM ON ECT.CustomTagId=CTM.Id 
							WHERE ECT.EmployeeId = EM.EmployeeId FOR XML PATH ('''')), 1, 1, '''')  AS SubCategory
							
							FROM 
							sHrm.vExtEmployeeMaster EM
							LEFT JOIN sHrm.tEmployeeCustomTag ECT ON ECT.EmployeeId=EM.EmployeeId  
							LEFT JOIN sHrm.tCustomTagMaster CTM ON ECT.CustomTagId=CTM.Id

							Where ISNULL(EM.IsOtherUser,0) = 0 AND EM.OrgId='+CAST(@rOrgId AS nvarchar(15))
							+'AND (EM.StatusId='+ CAST(@rStatusId AS nvarchar(15)) +' OR '+CAST(@rStatusId AS nvarchar(15))+'=0)
							AND (EM.DepartmentId='+ CAST(@rDepartmentId AS nvarchar(15)) +' OR '+CAST(@rDepartmentId AS nvarchar(15))+'=0)
							AND (EM.EmployeeGroupId='+ CAST(@rGroupId AS nvarchar(15)) +' OR '+CAST(@rGroupId AS nvarchar(15))+'=0)
							AND (EM.EmployeeGradeId='+ CAST(@rGradeId AS nvarchar(15)) +' OR '+CAST(@rGradeId AS nvarchar(15))+'=0)
							AND (EM.EmployeeTypeId='+ CAST(@rTypeId AS nvarchar(15)) +' OR '+CAST(@rTypeId AS nvarchar(15))+'=0)
							AND 
							('+CAST(@rIsBlank AS nvarchar(1))+'=0 
								OR ('+@lDataTypeId+'=1 AND ISNULL(ECT.'+@rSubCategory+','''')='''')
								OR ('+@lDataTypeId+'=2 AND ISNULL(ECT.'+@rSubCategory+',''0'')=''0'')
								OR ('+@lDataTypeId+'=3 AND ISNULL(ECT.'+@rSubCategory+',''False'')=''False'')
								OR ('+@lDataTypeId+'=4 AND ISNULL(ECT.'+@rSubCategory+',''0001/01/01'')=''0001/01/01'') 
							)
							GROUP BY EM.Id,EM.EmployeeId,EM.Code,EM.EmployeeName,EM.LastName,EM.EmployeeGroup,EM.DepartmentName,EM.Number ORDER BY EM.Number'
						else

						'Select EM.Id,EM.EmployeeId,EM.Code,EM.EmployeeName,EM.LastName,EM.EmployeeGroup,EM.DepartmentName,
					    CASE WHEN '+@lDataTypeId+'=1 THEN
						ISNULL(HEM.'+@rSubCategory+','''')
						WHEN '+@lDataTypeId+'=2 THEN
						ISNULL(HEM.'+@rSubCategory+',''0'')
						WHEN '+@lDataTypeId+'=3 THEN
						ISNULL(HEM.'+@rSubCategory+',''False'')
						WHEN '+@lDataTypeId+'=4 THEN
						ISNULL(HEM.'+@rSubCategory+',''0001/01/01'')
						WHEN '+@lDataTypeId+'=5 THEN
						ISNULL(HEM.'+@rSubCategory+',''0'')
						END AS SubCategory
							FROM 
							sHrm.vExtEmployeeMaster EM
							INNER JOIN sHrm.tEmployeeMaster HEM ON HEM.Id=EM.EmployeeId  
							Where ISNULL(EM.IsOtherUser,0) = 0 AND EM.OrgId='+CAST(@rOrgId AS nvarchar(15))
							+'AND (EM.StatusId='+ CAST(@rStatusId AS nvarchar(15)) +' OR '+CAST(@rStatusId AS nvarchar(15))+'=0)
							AND (EM.DepartmentId='+ CAST(@rDepartmentId AS nvarchar(15)) +' OR '+CAST(@rDepartmentId AS nvarchar(15))+'=0)
							AND (EM.EmployeeGroupId='+ CAST(@rGroupId AS nvarchar(15)) +' OR '+CAST(@rGroupId AS nvarchar(15))+'=0)
							AND (EM.EmployeeGradeId='+ CAST(@rGradeId AS nvarchar(15)) +' OR '+CAST(@rGradeId AS nvarchar(15))+'=0)
							AND (EM.EmployeeTypeId='+ CAST(@rTypeId AS nvarchar(15)) +' OR '+CAST(@rTypeId AS nvarchar(15))+'=0)
							AND 
							('+CAST(@rIsBlank AS nvarchar(1))+'=0 
								OR ('+@lDataTypeId+'=1 AND ISNULL(HEM.'+@rSubCategory+','''')='''')
								OR ('+@lDataTypeId+'=2 AND ISNULL(HEM.'+@rSubCategory+',''0'')=''0'')
								OR ('+@lDataTypeId+'=3 AND ISNULL(HEM.'+@rSubCategory+',''False'')=''False'')
								OR ('+@lDataTypeId+'=4 AND ISNULL(HEM.'+@rSubCategory+',''0001/01/01'')=''0001/01/01'') 
							) ORDER BY EM.Number'
				   
					     end
					
					WHEN 5 THEN --Statutory
						'Select EM.Id,EM.EmployeeId,EM.Code,EM.EmployeeName,EM.LastName,EM.EmployeeGroup,EM.DepartmentName,
					    CASE WHEN '+@lDataTypeId+'=1 THEN
						ISNULL(ESO.'+@rSubCategory+','''')
						WHEN '+@lDataTypeId+'=2 THEN
						ISNULL(ESO.'+@rSubCategory+',''0'')
						WHEN '+@lDataTypeId+'=3 THEN
						ISNULL(ESO.'+@rSubCategory+',''False'')
						WHEN '+@lDataTypeId+'=4 THEN
						ISNULL(ESO.'+@rSubCategory+',''0001/01/01'')
						WHEN '+@lDataTypeId+'=5 THEN
						ISNULL(ESO.'+@rSubCategory+',''0'')
						END AS SubCategory
							FROM 
							sHrm.vExtEmployeeMaster EM
							LEFT JOIN sHrm.tEmployeeStatutoryAndOther ESO ON ESO.EmployeeId=EM.EmployeeId  
							Where ISNULL(EM.IsOtherUser,0) = 0 AND EM.OrgId='+CAST(@rOrgId AS nvarchar(15))
							+'AND (EM.StatusId='+ CAST(@rStatusId AS nvarchar(15)) +' OR '+CAST(@rStatusId AS nvarchar(15))+'=0)
							AND (EM.DepartmentId='+ CAST(@rDepartmentId AS nvarchar(15)) +' OR '+CAST(@rDepartmentId AS nvarchar(15))+'=0)
							AND (EM.EmployeeGroupId='+ CAST(@rGroupId AS nvarchar(15)) +' OR '+CAST(@rGroupId AS nvarchar(15))+'=0)
							AND (EM.EmployeeGradeId='+ CAST(@rGradeId AS nvarchar(15)) +' OR '+CAST(@rGradeId AS nvarchar(15))+'=0)
							AND (EM.EmployeeTypeId='+ CAST(@rTypeId AS nvarchar(15)) +' OR '+CAST(@rTypeId AS nvarchar(15))+'=0)
							AND 
							('+CAST(@rIsBlank AS nvarchar(1))+'=0 
								OR ('+@lDataTypeId+'=1 AND ISNULL(ESO.'+@rSubCategory+','''')='''')
								OR ('+@lDataTypeId+'=2 AND ISNULL(ESO.'+@rSubCategory+',''0'')=''0'')
								OR ('+@lDataTypeId+'=3 AND ISNULL(ESO.'+@rSubCategory+',''False'')=''False'')
								OR ('+@lDataTypeId+'=4 AND ISNULL(ESO.'+@rSubCategory+',''0001/01/01'')=''0001/01/01'') 
							) ORDER BY EM.Number'
				   
					END
		print @Sql    
	    
	   EXECUTE  sp_executesql @Sql
END
GO
PRINT N'Altering Procedure [sProcurement].[pRptStockIssueReturn]...';


GO
ALTER PROCEDURE [sProcurement].[pRptStockIssueReturn]
 
	@rId [bigint] = 0
WITH EXECUTE AS CALLER
AS
BEGIN
	
	SET NOCOUNT ON;
	SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED
	
	
 SELECT SIR.Id,
		SIR.Number,
		ISNULL(SIR.ReturnedByName,'') AS ReturnedByName,
		SIR.ToStoreLocationId,
		SIR.Remark,
		SIR.StockIssueId,
		SIRB.StockIssueBatchId,
		SIRB.ReturnQuantity,
		SIM.Code AS StockItemCode,
		SIM.Title AS StockItemName,
		SIM.Id AS StockItemId,
		SIB.StockBatchId AS BatchId,
		SIR.CreatedUserId,
		SI.Number AS InwardNumber,
		SIND.IssuedQuantity, 
		RM.Title AS ReasonName,
		case when SIR.TransactionDate is not null then SIR.TransactionDate else SIR.CreatedDateTime end as CreatedDateTime
		

FROM sProcurement.tStockIssueReturn SIR 
INNER JOIN sProcurement.tStockIssueReturnBatch SIRB ON SIRB.StockIssueReturnId=SIR.Id
INNER JOIN sProcurement.tStockIssueBatch SIB ON SIB.Id=SIRB.StockIssueBatchId
INNER JOIN sProcurement.tStockIssueDetail SIND ON SIND.Id=SIB.StockIssueDetailId
INNER JOIN sIp.tStockItemMaster SIM ON SIM.Id=SIND.StockItemId
INNER JOIN sProcurement.tStockIssue SI ON SI.Id=SIR.StockIssueId
INNER JOIN sCommon.tReasonMaster RM ON RM.Id=SIRB.ReasonId
		 
		WHERE SIR.Id = @rId 
			
END
GO

ALTER PROCEDURE [sStudent].[pRptSiblingLinkListGet]	
	
	@rClassId int,
	@rDivisionId int,
	@rStudentId bigint,
	@rBuilder1 nvarchar(max),
	@rBuilder2 nvarchar(max),
	@rOrgId int,
	@rBatchID int,
	@rDepartmentId int,
	@rOrgGroupBatchId int,
	@rClassStatusId int=0
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON			 
BEGIN 	 		
  SELECT 
		@rBuilder1 AS Builder1,
		DENSE_rank() OVER(ORDER BY LS.StudentId)AS RowNumber,
		SA.OrganizationName,
		SA.Name,
		SA.Code,		
		SA.ClassName+'-'+SA.DivisionName AS DivDept	,
		SA1.ClassName+'-'+SA1.DivisionName AS StudentClass,		
		LS.LinkedStudentId,
		LS.StudentId,
		SM.FirstName +' '+SM.MiddleName+' '+SM.LastName As StudentName,
		SA.BatchName,
		SM.Code AS StudentCode
			
  FROM	sStudent.tLinkSibling LS
		INNER JOIN	sStudent.vStudentLastAcademic SA ON SA.StudentId=LS.LinkedStudentId		
		INNER JOIN sStudent.tStudentMaster SM ON SM.Id=LS.StudentId	
		INNER JOIN	sStudent.vStudentLastAcademic SA1 ON SA1.StudentId=LS.StudentId	
  WHERE 
		((LS.StudentId like @rStudentId) OR (ISNULL(@rStudentId,0) = 0)) 
		AND((SA.ClassId=@rClassId) OR  (@rClassId=0))
		AND ((Sa.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		--Mantis Id:- 30932, comment OrgGroupBatchId and add OrgId
		--AND LEFT(SA.OrgGroupBatchId,4) = @rOrgId
		AND SA.OrgId = @rOrgId
		AND SA.IsActiveBatch = 1
		AND SA.BatchId =@rBatchID
		AND ((SA.DepartmentId = @rDepartmentId) OR (@rDepartmentId=0))
		AND ((SA.ClassStatusId=@rClassStatusId) OR (@rClassStatusId=0))
		ORDER BY RowNumber
END
GO
PRINT N'Altering Procedure [sStudent].[pStudentFullProfileGet]...';


GO
ALTER PROCEDURE [sStudent].[pStudentFullProfileGet]
	 
	 @rBatchId int,
	 @rStudentId bigint,
	 @rReportId int=0,
	 @rOrgId int,
	 @rStrCode nvarchar(max)='',
	 @rClassId int=0,
	 @rDivisionId int=0,
	 @rFromRollNo int=0,
	 @rToRollNo int=0,
	 @rStatusId int=0,
	 @rClassStatusId int=0,
	 @rDateOfBirth int=0,
	 @rDepartmentId int=0,
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='',
	 @rOrgGroupBatchId int,
	 @rFromAdmissionDate date = '',
	 @rToAdmissionDate date = ''	 
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
	
	DECLARE @lAcademicId bigint
	SELECT @lAcademicId = Id from sStudent.tAcademic Where StudentId = @rStudentId AND BatchId = @rBatchId
		
	SELECT 
			--Academic
			@rBuilder1 As Builder1,
			SA.StudentId AS Id,
			SA.Name AS StudentName,
			SA.FirstName as FirstName,
			SA.MiddleName as MiddleName,
			SA.LastName as LastName,
			SA.Batch AS AcademicYear,
			ISNULL(SA.Code,' - ') AS Code,
			SA.ClassDivision AS ClassDiv,			
			SA.RollNo,
			ISNULL(SM.Title,'-') AS House,
			--Other
			CASE WHEN @rReportId=0 THEN ISNULL(SA.DateOfBirth,'0001/01/01')  
			WHEN @rReportId=1 THEN  SA.DateOfBirth END  AS DateOfBirth,
			ISNULL(SA.BirthTaluka,'') AS BirthTaluka,
			ISNULL(SA.BirthPlace,'') AS BirthPlace,	
			ISNULL(SA.BirthDistrict,'') AS BirthDistrict,
			ISNULL(SA.BirthDateInWord,'') AS BirthDateInWord,                           
			ISNULL(SA.Gender,'') AS Gender,
			ISNULL(SA.Religion,'') AS Religion,
			--Admission			
			ISNULL(SA.AdmissionStandard,'') AS AdmissionStandard,
			--ISNULL(SA.AdmissionDate,'0001/01/01') AS AdmissionDate,
			CASE WHEN @rReportId=0 THEN ISNULL(SA.AdmissionDate,'0001/01/01')
			WHEN @rReportId=1 THEN  SA.AdmissionDate END AS AdmissionDate,	
			ISNULL(SA.PreviousSchool,'') AS PreviousSchool,
			ISNULL(SA.AdmissionCategory,'') AS StudentAdmissionCategory,
			CASE WHEN @rReportId=0 THEN ISNULL(SA.LeftDate,'0001/01/01')
			WHEN @rReportId=1 THEN  SA.LeftDate END AS LeftDate,						 
			ISNULL(SA.LeftStandard,'') AS LeftStandard,
			--ISNULL(SA.InactiveDate,'0001/01/01') AS InactiveDate,
			CASE WHEN @rReportId=0 THEN ISNULL(SA.InactiveDate,'0001/01/01')
			WHEN @rReportId=1 THEN  SA.InactiveDate END AS InactiveDate,		
			ISNULL(SA.LCNumber,'') AS LCNumber,
			--ISNULL(SA.LCDate,'0001/01/01') AS LCDate,
			 CASE WHEN @rReportId=0 THEN ISNULL(SA.LCDate,'0001/01/01')
			WHEN @rReportId=1 THEN  SA.LCDate END AS LCDate,
			--Communication
			ISNULL(SA.PresentStreetone,'') + ' ' + ISNULL(SA.PresentStreetTwo,'') + ' ' + ISNULL(SA.PresentStreetThree,'') AS PresentAddress,
			ISNULL(SA.PresentCity,'') AS PresentCity,
			ISNULL(SA.PresentState,'') AS PresentState,
			ISNULL(SA.PresentCountry,'') AS PresentCountry,
			ISNULL(SA.PresentZipCode,'') AS PresentZipCode,
			ISNULL(SA.PresentContactNo,'') AS PresentContactNo,			
			ISNULL(SA.EmergencyStreetOne,'') + ' ' + ISNULL(SA.EmergencyStreetTwo,'') + ' ' + ISNULL(SA.EmergencyStreetThree,'') AS EmergencyAddress,
			ISNULL(SA.EmergencyCity,'') AS EmergencyCity,
			ISNULL(SA.EmergencyState,'') AS EmergencyState,
			ISNULL(SA.EmergencyCountry,'') AS EmergencyCountry,
			ISNULL(SA.EmergencyZipCode,'') AS EmergencyZipCode,
			ISNULL(SA.EmergencyContactNo,'') AS EmergencyContactNo,			
			ISNULL(SA.PermanentStreetOne,'') + ' ' + ISNULL(SA.PermanentStreetTwo,'') + ' ' + ISNULL(SA.PermanentStreetThree,'') AS PermanentAddress,
			ISNULL(SA.PermanentCity,'') AS PermanentCity,
			ISNULL(SA.PermanentState,'') AS PermanentState,
			ISNULL(SA.PermanentCountry,'') AS PermanentCountry,
			ISNULL(SA.PermanentZipCode,'') AS PermanentZipCode,
			ISNULL(SA.PermanentContactNo,'') AS PermanentContactNo,			
			--Parent Information
			ISNULL(SF.FatherName,'') AS FatherName,
			ISNULL(SF.FatherOccupation,'') AS FatherOccupation,
			ISNULL(SF.FatherQualification,'') AS FatherQualification,
			ISNULL(SF.FatherContactNo,'') AS FatherContactNo,
			ISNULL(SF.FatherMail,'') AS FatherMail,
			ISNULL(SF.FatherOfficeAddress,'') AS FatherOfficeAddress,
			ISNULL(SF.FatherDesignation,'') AS FatherDesignation,
			ISNULL(SF.FatherOrganization,'') AS FatherOrganization,
			ISNULL(SF.FatherIncome,'') AS FatherIncome,
			ISNULL(SF.MotherName,'') AS MotherName,
			ISNULL(SF.MotherOccupation,'') AS MotherOccupation,
			ISNULL(SF.MotherQualification,'') AS MotherQualification,
			ISNULL(SF.MotherContactNo,'') AS MotherContactNo,
			ISNULL(SF.MotherMail,'') AS MotherMail,
			ISNULL(SF.MotherOfficeAddress,'') AS MotherOfficeAddress,
			ISNULL(SF.MotherDesignation,'') AS MotherDesignation,
			ISNULL(SF.MotherOrganization,'') AS MotherOrganization,
			ISNULL(SF.MotherIncome,'') AS MotherIncome,
			ISNULL(SF.RelationshipName,'') AS RelationShip,
			ISNULL(SF.RelativeName,'') AS RelativeName,
			ISNULL(SF.RelativeOccupation,'') AS RelativeOccupation,
			ISNULL(SF.RelativeQualification,'') AS RelativeQualification,
			ISNULL(SF.RelativeContactNo,'') AS RelativeContactNo,
			ISNULL(SF.RelativeMail,'') AS RelativeMail,
			ISNULL(SF.RelativeOfficeAddress,'') AS RelativeOfficeAddress,
			ISNULL(SF.RelativeDesignation,'') AS RelativeDesignation,
			ISNULL(SF.RelativeOrganization,'') AS RelativeOrganization,
			ISNULL(SF.RelativeIncome,'') AS RelativeIncome,			
			--Health Information
			ISNULL(SA.BloodGroup,'') AS BloodGroup,
			ISNULL(SH.IdentificationMark1,'')+' '+ISNULL(SH.IdentificationMark2,'') as IdentificationMark,			
			ISNULL(SH.FamilyDoctorName,'') AS FamilyDoctorName,
			ISNULL(SH.FamilyDoctorContactNo,'') AS FamilyDoctorContactNo,			
			ISNULL(SH.IsPysicalDeformity,0) AS IsPysicalDeformity,
			ISNULL(SH.PysicalDeformityRemark,'') AS PysicalDeformityRemark,
			ISNULL(SH.IsMajorIllness,0) AS IsMajorIllness,
			ISNULL(SH.MajorIllnessRemark,'') As MajorIllnessRemark,
			ISNULL(SH.IsAllergy,0) AS IsAllergy,
			ISNULL(SH.AllergyRemark,'') As AllergyRemark,
			ISNULL(SH.IsPastHistory,0) As IsPastHistory ,
			ISNULL(SH.PastHistoryRemark,'') As PastHistoryRemark,
			--Hostel
			ISNULL(RM.Title,'') AS RoomNo,			
			ISNULL(HM.Title,'') AS Hostel,
			ISNULL(EMW.FirstName,'')+' '+ISNULL(EMW.LastName,'') AS WardenName,
			ISNULL(ECW.PhoneNoCompany,'') As WardenPhoneNo,
			ISNULL(ECW.ExtensionNo,'') AS WardenExtNo,
			ISNULL(ECW.MobileNumber,'') AS WardenMobileNo,
			ISNULL(EMA.FirstName,'')+' '+ISNULL(EMA.LastName,'') AS AssignedRoomBy,	
			ISNULL(ECA.PhoneNoCompany,'') AS AssignedRoomByPhoneNo,
			ISNULL(ECA.ExtensionNo,'') AS AssignedRoomByExtNo,
			ISNULL(ECA.MobileNumber,'') AS AssignedRoomByMobileNo,
			--Notification Details
			ISNULL(SA.ParentEmail,'') AS ParentEmail,
			ISNULL(SA.ParentContactNo,'') As ParentContactNo,
			ISNULL(SA.StudentEmail,'') AS StudentEmail,
			ISNULL(SA.StudentContactNo,'') AS StudentContactNo,
	   	   CASE WHEN @rReportId=0
			THEN ISNULL(SA.StudentPhoto, CONVERT(VARBINARY(MAX), 0))
			WHEN @rReportId=1
			THEN ISNULL(SA.StudentPhoto, CONVERT(VARBINARY(MAX), ''))
			END AS StudentPhoto,			
			CASE WHEN @rReportId=0
			THEN ISNULL(SA.MotherPhoto, CONVERT(VARBINARY(MAX), 0))
			WHEN @rReportId=1
			THEN ISNULL(SA.MotherPhoto, CONVERT(VARBINARY(MAX), ''))
			END AS MotherPhoto,			
			CASE WHEN @rReportId=0
			THEN ISNULL(SA.FatherPhoto, CONVERT(VARBINARY(MAX), 0))
			WHEN @rReportId=1
			THEN ISNULL(SA.FatherPhoto, CONVERT(VARBINARY(MAX), ''))
			END AS FatherPhoto,			
			CASE WHEN @rReportId=0
			THEN ISNULL(SA.RelativePhoto, CONVERT(VARBINARY(MAX), 0))
			WHEN @rReportId=1
			THEN ISNULL(SA.RelativePhoto, CONVERT(VARBINARY(MAX), ''))
			END AS RelativePhoto,
		   -- Transport Details
		    A.VehicleName AS VehicleName,
		    A.VehicleRegistrationNumber AS VehicleRegistrationNumber,
		    A.TypeOfVehicle AS TypeOfVehicle,
		    ISNULL(A.BusRoute,'') AS BusRoute,
		    A.DriverName,
		    A.DriverMobileNo,
		    A.ConductorName,
		    A.ConductorMobileNo,
		    ISNULL(A.BusRouteDestination,'') AS BusRouteDestination,		  
		    A.DropVehicleName AS DropVehicleName,
		    A.DropVehicleRegistrationNumber AS DropVehicleRegistrationNumber,
		    A.DropTypeOfVehicle AS DropTypeOfVehicle,
		    ISNULL(A.DropRoute,'') AS DropRoute,
		    A.DropRouteDriverName AS DropRouteDriverName,
		    A.DropRouteDriverMobileNo AS DropRouteDriverMobileNo,
		    A.DropRouteConductorName AS DropRouteConductorName,
		    A.DropRouteConductorMobileNo AS DropRouteConductorMobileNo,
		    ISNULL(A.DropDestination,'') AS DropDestination,		    
		    --ClassTeacher Details
		    ISNULL(EMT.Id,0) AS TeacherId,
		    EMT.FirstName+' '+EMT.MiddleName+' '+EMT.LastName AS TeacherFullName,
		    EDM.Title AS TeacherDesignation,
		    EPD.Qualification AS TeacherQualification,
		    ISNULL(EI.EmployeePhoto, CONVERT(VARBINARY(MAX), 0)) AS TeacherPhoto,
		    ISNULL(DF.IsDisplayFamilyDetail,0) AS IsDisplayFamilyDetail,
		    ISNULL(DF.IsDisplaySiblingDetail,0) AS IsDisplaySiblingDetail,
		    ISNULL(DF.IsDisplayPassportDetail,0) AS IsDisplayPassportDetail,
		    ISNULL(DF.IsDisplayBankDetail,0) AS IsDisplayBankDetail,
		    ISNULL(DF.IsDisplayCBSEREGDetail,0) AS IsDisplayCBSEREGDetail,
		    ISNULL(DF.IsDisplayCollegeDetail,0) AS IsDisplayCollegeDetail,
		    ISNULL(DF.IsDisplayGOVREGNoDetail,0) AS IsDisplayGOVREGNoDetail,
		    ISNULL(DF.IsDisplayHealthDetail,0) AS IsDisplayHealthDetail,
		    ISNULL(DF.IsDisplayTransportDetail,0) AS IsDisplayTransportDetail,
		    ISNULL(DF.IsDisplayHostelDetail,0) AS IsDisplayHostelDetail,
		    ISNULL(DF.IsDisplayClubDetail,0) AS IsDisplayClubDetail,		    
		    ISNULL(DF.IsDisplaySSCResultDDetail,0) AS IsDisplaySSCResultDDetail,
		    ISNULL(DF.IsDisplayHSCResultDetail,0) AS IsDisplayHSCResultDetail,
		    ISNULL(DF.IsDisplayJeeDetail,0) AS IsDisplayJeeDetail,
		    ISNULL(DF.IsDisplayDiplomaDetail,0) AS IsDisplayDiplomaDetail,
			ISNULL(DF.IsDisplayClassTeacherDetail,0) AS IsDisplayClassTeacherDetail,
			ISNULL(DF.IsDisplayAdmissionDetail, 0) AS IsDisplayAdmissionDetail,
		    --Sibling Detail
		    isnull(SS.SiblingName1,'') AS SiblingName1,
	        ISNULL (SS.SiblingInstitue1,'') AS SiblingInstitue1,
	        ISNULL(SS.SiblingClass1,'')AS SiblingClass1,
	        ISNULL(SS.SiblingAge1,'')AS SiblingAge1,
	        ISNULL(SS.SiblingRelation1,'')AS SiblingRelation1,
	        isnull(SS.SiblingName2,'') AS SiblingName2,
	        ISNULL(SS.SiblingInstitue2,'')AS SiblingInstitue2,
	        ISNULL(SS.SiblingClass2,'')AS SiblingClass2,
	        ISNULL(SS.SiblingAge2,'') AS SiblingAge2,
	        ISNULL(SS.SiblingRelation2,'')AS SiblingRelation2,
	        isnull(SS.SiblingName3,'') AS SiblingName3,
	        ISNULL( SS.SiblingInstitue3,'')AS SiblingInstitue3,
	        ISNULL(SS.SiblingClass3,'')AS SiblingClass3,
	        ISNULL(SS.SiblingAge3,'')AS SiblingAge3,
	        ISNULL(SS.SiblingRelation3,'')AS SiblingRelation3,
	        ISNULL(SAD.BankAccountNumber,'')AS BankAccountNumber,
	        ISNULL(SAD.BankName,'')AS BankName,
	        ISNULL(SAD.BankBranch,'') AS BankBranch,
	        ISNULL(SAD.BankIFSCCode,'')AS BankIFSCCode,
	        ISNULL(SAD.Class9BoardRegistrationNumber,'') AS Class9BoardRegistrationNumber,
	        ISNULL(SAD.Class11BoardRegistrationNumber,'')AS Class11BoardRegistrationNumber,
	        ISNULL(SAD.PassportNumber,'')AS PassportNumber, 
	        ISNULL(SAD.PassportType,'') AS PassportType,
	       ISNULL( SAD.PassportCountryCode,'') AS PassportCountryCode,
	        CASE WHEN @rReportId=0 THEN ISNULL(SAD.PassportIssueDate,'0001/01/01')
			WHEN @rReportId=1 THEN  SAD.PassportIssueDate END AS PassportIssueDate,
			CASE WHEN @rReportId=0 THEN ISNULL(SAD.PassportExpiryDate,'0001/01/01')
			WHEN @rReportId=1 THEN  SAD.PassportExpiryDate END AS PassportExpiryDate,
	        ISNULL(SA.UIDNumber,'')AS UIDNumber,
	        ISNULL(SA.AdhaarNumber,'') AS AdhaarNumber,
	       ISNull(SA.StatusId,0) AS StatusId,
	       ISNUll(SA.IsTransfer,0)AS IsTransfer,
	       ISNULL(SA.TransferFrom,'') AS TransferFrom,
	       ISNULL(SA.CertificateName,'') AS CertificateName,
	       ISNUll(SA.IsTFWS,0)AS IsTFWS,
	       ISNUll(SA.IsCertificateHolder,0)AS IsCertificateHolder,
	       ISNULL(CD.SSCBoard,'') AS SSCBoard,
	       ISNULL(CD.SSCSchool,'') AS SSCSchool,
	       ISNULL(CD.SSCPassingYear,'') AS SSCPassingYear,
	       ISNULL(CD.SSCObtainMarks,0) AS SSCObtainMarks,
	       ISNULL(CD.SSCOutOfMarks,0) AS SSCOutOfMarks,
	       ISNULL(CD.SSCPercentage,0) AS SSCPercentage,
	       ISNULL(CD.SSCMathMarks,0) AS SSCMathMarks,
	       ISNULL(CD.SSCMathOutOfMarks,0) AS SSCMathOutOfMarks,
	       ISNULL(CD.SSCPercentile,0) AS SSCPercentile,
	       ISNULL(CD.SSCGrade,0) AS SSCGrade,
	       ISNULL(CD.HSCBoard,'') AS HSCBoard,
	       ISNULL(CD.HSCSchool,'') AS HSCSchool,
	       ISNULL(CD.HSCPassingYear,0) AS HSCPassingYear,
	       ISNULL(CD.HSCObtainMarks,0) AS HSCObtainMarks,
	       ISNULL(CD.HSCOutOfMarks,0) AS HSCOutOfMarks,
	       ISNULL(CD.HSCPercentage,0) AS HSCPercentage,
	       ISNULL(CD.HSCPhysicsMarks,0) AS HSCPhysicsMarks,
	       ISNULL(CD.HSCPhysicsOutOfMarks,0) AS HSCPhysicsOutOfMarks,
	       ISNULL(CD.HSCChemistryMarks,0) AS HSCChemistryMarks,
	       ISNULL(CD.HSCChemistryOutOfMarks,0) AS HSCChemistryOutOfMarks,
	       ISNULL(CD.HSCMathMarks,0) AS HSCMathMarks,
	       ISNULL(CD.HSCMathOutOfMarks,0) AS HSCMathOutOfMarks,
	       ISNULL(CD.HSCBiologyMarks,0) AS HSCBiologyMarks,
	       ISNULL(CD.HSCBiologyOutOfMarks,0) AS HSCBiologyOutOfMarks,
	       ISNULL(CD.PCMMarks,0) AS PCMMarks,
	       ISNULL(CD.PCBMarks,0) AS PCBMarks,
	       ISNULL(CD.JEERollNo,'') AS JEERollNo,
	       ISNULL(CD.JEEMeritNo,'') AS JEEMeritNo,
	       ISNULL(CD.JEEMeritMarks,0) AS JEEMeritMarks,
	       ISNULL(CD.JEEOutOfMarks,0) AS JEEOutOfMarks,
	       ISNULL(CD.DiplomaBoard,'') AS DiplomaBoard,
	       ISNULL(CD.DiplomaCollege,'') AS DiplomaCollege,
	       ISNULL(CD.DiplomaPassingYear,'') AS DiplomaPassingYear,
	       ISNULL(CD.DiplomaObtainMarks,0) AS DiplomaObtainMarks,
	       ISNULL(CD.DiplomaOutOfMarks,0) AS DiplomaOutOfMarks,
	       ISNULL(CD.DiplomaPercentage,0) AS DiplomaPercentage,
	       ISNULL(CD.ApplicationNo,'') AS ApplicationNo,
	       ISNULL(CD.AdmissionRound,0) AS AdmissionRound,
	       ISNULL(CD.MaritalStatusId,0) AS MaritalStatusId,
	       ISNULL(MS.Title,'') AS MaritalStatus,
	       ISNULL(ACD.RepeatCount,1)AS RepeatCount,
	       ISNULL(SA.MotherTongue,'') As MotherTongue,
	       ISNULL(SA.FamilyCast,'') AS FamilyCast,
	       ISNULL(CM.Nationality,'') AS Nationality,
	       ISNULL(CT.Title,'') AS CasteCategory,
	       ISnull(SA.ClassName,'') AS ClassName ,
	       ISnull( SA.DivisionName,'') AS DivisionName,
	       ISNULL( SF.IsFatherExStudent,0) AS IsFatherExStudent,
	       ISnull(SF.FatherPassOutYear,'') AS FatherPassOutYear,
	       Isnull(SF.IsMotherExStudent,0) AS IsMotherExStudent,
	       Isnull(SF.MotherPassOutYear,'') AS MotherPassOutYear,
	       ISNULL(SF.IsRelativeExStudent,0) AS IsRelativeExStudent,
	       ISNULL(SF.RelativePassOutYear,'') AS RelativePassOutYear,
	       ISNULL(Sa.PresentDistanceFromSchool,0) AS PresentDistanceFromSchool,
	        SA.StudentId,
	        SA.ClassId,
	        SA.DivisionId,
	        SA.BirthState,
	        SA.BirthCountry,
	         ISNULL(SA.PreviousStandard,'')AS PreviousStandard
	        ,ISNULL(CGG.Title,'') AS CustomGroup
			,ISNULL(SGM.Title,'') As StudentGroup
			,ISNULL(SOGM.Title,'') As StudentOtherGroup
			,ISNULL([sStudent].[fAssignedClubGet](@lAcademicId),'') AS ClubName
			,ISNULL([sStudent].[fAssignedCustomTagGet](@lAcademicId),'') AS CustomTag 
	        ,SA.ClassStatusId
	        ,SA.ClassStatusName
	        ,PDCM.Title As PhysicalDisabilityCategory
			,ISNULL(SAM.PreviousLCNumber,'') AS PreviousLCNumber
			,ISNULL(SAM.PreviousLCDate,'') AS PreviousLCDate,
			ISNULL(SAM.AdmissionNumber,'') AS  AdmissionNumber,
			ISNULL(SAM.AdmissionFormNumber,'') AS  AdmissionFormNumber,
			SA.SUId,
		    MS.Title AS MaritalStatus,
		    SA.FamilySubCast,
		    SA.ReferenceRemark,
			ISNULL(SA.WhatsAppContactNo,'') AS WhatsAppContactNo
  FROM 
           sStudent.vStudentAllDetail SA
          -- LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId = SA.StudentId
           LEFT JOIN sStudent.tStudentHealth SH ON SA.StudentId=SH.StudentId
           LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId = SA.StudentId 
          -- LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId = SA.StudentId
           LEFT JOIN sActivity.tHouseMaster SM ON SM.ID = SA.HouseId
           LEFT JOIN sHostel.tAssignRoom AR ON AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003  AND ((AR.OrgGroupBatchId=@rOrgGroupBatchId) OR(@rOrgGroupBatchId=0))
           LEFT JOIN sHostel.tRoomMaster RM ON RM.Id=AR.RoomId
           LEFT JOIN sCommon.tPhysicalDisabilityCategoryMaster PDCM ON PDCM.Id = SH.PhysicalDisabilityCategoryId
           LEFT JOIN sHostel.tHostelMaster HM ON HM.Id=RM.HostelId   
            LEFT JOIN
            (
		   SELECT 
		   employeeId, 
		   HostelId,   
		   ROW_NUMBER() OVER (PARTITION BY HostelId ORDER By HostelId ) as ROWNo 		   
		 
		   FROM sHostel.tHostelwarden 
            )  HW ON HW.HostelId=HM.Id AND RowNo = 1       
           --LEFT JOIN sHostel.tHostelWarden HW ON HW.HostelId=HM.Id
           LEFT JOIN sHrm.tEmployeeMaster EMW ON HW.EmployeeId=EMW.Id AND  ISNULL(EMW.IsOtherUser,0) = 0
           LEFT JOIN sHrm.tEmployeeMaster EMA ON RM.AssignedEmployeeId=EMA.Id AND  ISNULL(EMA.IsOtherUser,0) = 0
           LEFT JOIN sHrm.tEmployeeCommunications ECW ON EMW.Id=ECW.EmployeeId 
           LEFT JOIN sHrm.tEmployeeCommunications ECA ON  EMA.Id=ECA.EmployeeId
           LEFT JOIN 
           ( SElect AR1.SourceId,
           VM.Title AS VehicleName,
		    VM.RegistrationNumber AS VehicleRegistrationNumber,
		    TV.Title AS TypeOfVehicle,
		    ISNULL(BRM.Title,'') AS BusRoute,
		    BRM.DriverName,
		    BRM.DriverMobileNo,
		    BRM.ConductorName,
		    BRM.ConductorMobileNo,
		    ISNULL(BRDM.Title,'') AS BusRouteDestination,
		    VM.Title AS DropVehicleName,
		    VM.RegistrationNumber AS DropVehicleRegistrationNumber,
		    TV1.Title AS DropTypeOfVehicle,
		    ISNULL(BRM1.Title,'') AS DropRoute,
		    BRM1.DriverName AS DropRouteDriverName,
		    BRM1.DriverMobileNo AS DropRouteDriverMobileNo,
		    BRM1.ConductorName AS DropRouteConductorName,
		    BRM1.ConductorMobileNo AS DropRouteConductorMobileNo,
		    ISNULL(BRDM1.Title,'') AS DropDestination
		      FROM
             sTransport.tAssignRoute AR1   
           INNER JOIN sTransport.tBusRouteDestinationMaster BRDM ON BRDM.Id=AR1.PickupDestinationId AND AR1.SourceTypeId=2003
           INNER JOIN sTransport.tBusRouteMaster BRM ON BRM.Id=BRDM.BusRouteId AND ((BRM.OrgGroupBatchId=@rOrgGroupBatchId) OR(@rOrgGroupBatchId=0))
           LEFT JOIN sTransport.tVehicleMaster VM ON VM.Id=BRM.VehicleId
           LEFT JOIN sTransport.tVehicleTypeMaster TV ON TV.Id = VM.VehicleTypeId
           LEFT JOIN sTransport.tBusRouteDestinationMaster BRDM1 ON BRDM1.Id=AR1.DropDestinationId
           LEFT JOIN sTransport.tBusRouteMaster BRM1 ON BRM1.Id=BRDM1.BusRouteId AND ((BRM1.OrgGroupBatchId=@rOrgGroupBatchId) OR(@rOrgGroupBatchId=0))
           LEFT JOIN sTransport.tVehicleMaster VM1 ON VM1.Id=BRM1.VehicleId
           LEFT JOIN sTransport.tVehicleTypeMaster TV1 ON TV1.Id = VM1.VehicleTypeId) A ON A.SourceId=SA.StudentId
           LEFT JOIN sSetup.tDivisionMaster DM ON  DM.Id=SA.DivisionId
           LEFT JOIN sHrm.tEmployeeMaster EMT ON EMT.Id=DM.InchargeEmployeeId AND  ISNULL(EMT.IsOtherUser,0) = 0
           LEFT JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EMT.Id
           LEFT JOIN sHrm.tEmployeeDesignationMaster EDM ON EDM.Id=EJD.EmployeeDesignationId
           LEFT JOIN sHrm.tEmployeePersonalDetail EPD ON EPD.EmployeeId=EMT.Id
           LEFT JOIN sHrm.tEmployeeImages EI ON EI.EmployeeId=EMT.Id
		   LEFT JOIN sStudent.tStudentSibling  SS ON SS.StudentId=SA.StudentId 
           LEFT JOIN sStudent.tStudentAdditional  SAD ON SAD.StudentId=SA.StudentId 
           LEFT JOIN sStudent.tCollegeDetail  CD ON CD.StudentId=SA.StudentId 
           LEFT JOIN sStudent.tAcademicDetail  ACD ON ACD.AcademicId=SA.AcademicId 
           LEFT JOIN sCommon.tMaritalStatusMaster  MS ON MS.Id=CD.MaritalStatusId
           LEFT JOIN sConfig.fDisplayFieldGet(@rOrgId) AS DF ON DF.OrgId=SA.OrgId
           LEFT JOIN sCommon.tCastCategoryMaster CT ON CT.Id = SA.CastCategoryId
           LEFT JOIN sCommon.tCountryMaster CM ON CM.Id=SA.NationalityId
           INNER JOIN sSetup.tBatchClass BC ON BC.ClassID =  SA.ClassID and BC.BatchId= @rBatchId
           LEFT JOIN sCommunication.tCustomGroupMember CGM ON CGM.SourceId = SA.StudentId AND CGM.SourceTypeId = 2003
           LEFT JOIN sCommunication.tCustomGroup CGG ON CGG.Id = CGM.CustomGroupId
           LEFT JOIN sStudent.tStudentMaster SMM ON SMM.Id = SA.StudentId
           LEFT JOIN sStudent.tStudentGroupMaster SGM ON SGM.Id = SMM.StudentGroupId
           LEFT JOIN sStudent.tStudentOtherGroupMaster SOGM ON SOGM.Id = SMM.StudentOtherGroupId
		   LEFT JOIN sStudent.tStudentAdmission SAM ON SAM.StudentId = SA.StudentId
  WHERE 
			((SA.StudentId=@rStudentId)OR(@rStudentId=0))
			AND((SA.BatchId=@rBatchId) OR(@rBatchId=0))
			AND (ISNULL(SA.Code,0) IN( SELECT cast(item as nvarchar(20)) FROM  sCommon.fnsplit(@rStrCode,',')) OR @rStrCode='') 
			AND ((SA.ClassId=@rClassId) OR (@rClassId=0))
			AND ((SA.DivisionId=@rDivisionId) OR (@rDivisionId=0))
			AND ((SA.StudentId=@rStudentId) OR (@rStudentId=0))
			AND ((SA.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
			AND ((SA.RollNo <= @rToRollNo) OR (@rToRollNo=0))
			AND ((SA.StatusId=@rStatusId)OR(@rStatusId=0))
			AND ((SA.ClassStatusId=@rClassStatusId)OR(@rClassStatusId=0))
			AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
			AND ((SA.OrgGroupBatchId=@rOrgGroupBatchId) OR(@rOrgGroupBatchId=0))
			AND ((SA.AdmissionDate >= @rFromAdmissionDate) OR (ISNULL(@rFromAdmissionDate,'') = ''))
			AND ((SA.AdmissionDate <= @rToAdmissionDate) OR (ISNULL(@rToAdmissionDate,'') = ''))
			--AND(SA.OrgId=@rOrgId)
			
END
GO

PRINT N'Creating Procedure [sAdmission].[pExportAdmissionInquiryGet]...';


GO
CREATE PROCEDURE [sAdmission].[pExportAdmissionInquiryGet]
	
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='',
	 @rId bigint = 0,	 
	 @rForClassId int = 0,
	 @rClassId int = 0,
	 @rBatchId int = 0,
	 @rStatusId int =0,
	 @rInquiryStatusMasterId int = 0,
	 @rOrgId int,
	 @rFirstName nvarchar(100) = '',
	 @rLastName nvarchar(100) = '',
	 @rFromDate datetime=Null,
	 @rToDate datetime=Null,
	 @rForBatchId int = 0,
	 @rDepartmentId int = 0,
	 @rFromMeritMarks decimal(10,2) = 0,
	 @rToMeritMarks decimal(10,2)=0,
	 @rInquiryModeId smallint=0,
	 @rInquiryReferenceId int=0,
	 @rNumber bigint=0,
	 @rOrgGroupBatchId int = 0,
	 @rFollowUpdate datetime='',
	 @rIsTransportRequired int=0,
	 @rIsHostelRequired int=0,
	 @rOrderBy int =0,
	 @rIsGivenAdmissionForm int =0,
	 @rContactNo nvarchar(100)='',
	 @rAdmissionInquiryIdText int =0,
	 @rHandledBy nvarchar(100) = '',
	 @rGenderId int=0
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
	
	IF(@rIsGivenAdmissionForm=1)
		SET @rIsGivenAdmissionForm = 1
  	IF(@rIsGivenAdmissionForm=2)
		SET @rIsGivenAdmissionForm =0
	 
	SET @rToDate = DATEADD(d,1,@rToDate)
	BEGIN
		SET @rFirstName= sCommon.fSearchStringGet(@rFirstName)
		SET @rLastName= sCommon.fSearchStringGet(@rLastName)
		SET @rHandledBy= sCommon.fSearchStringGet(@rHandledBy)
	END

DECLARE @cols AS NVARCHAR(MAX),@query  AS NVARCHAR(MAX)

-- CTE for Admission Form custom Field
;WITH AdmissionInquiryCriteriaFormCTE AS (SELECT DISTINCT (AIF.FieldGroup+' - '+AIF.FieldRemark) AS FieldRemark FROM sAdmission.tAdmissionInquiryForm AIF 
	LEFT JOIN sAdmission.tAdmissionInquiryField AI ON AI.AdmissionInquiryFormId = AIF.Id 
	WHERE (ClassId = @rForClassId  OR @rForClassId=0)
	AND (AI.AdmissionInquiryFormId = @rId  OR @rId = 0)
	AND (BatchId = @rForBatchId OR @rForBatchId=0) 
)

SELECT @cols = STUFF((SELECT  ',' + QUOTENAME(FieldRemark) FROM AdmissionInquiryCriteriaFormCTE GROUP BY FieldRemark
ORDER BY FieldRemark FOR XML PATH(''), TYPE ).value('.', 'NVARCHAR(MAX)'),1,1,'')

IF object_id('tempdb..##tempAdmissionInquiryCustomField') IS NOT NULL 
BEGIN
   DROP TABLE ##tempAdmissionInquiryCustomField 
END

IF(@cols IS NOT NULL)
BEGIN 
	SET @query = N'SELECT DISTINCT AdmissionInquiryId,' + @cols + N' INTO ##tempAdmissionInquiryCustomField FROM 
	(
		SELECT DISTINCT  AI.AdmissionInquiryId,AI.AdmissionInquiryFieldResponse, (AIF.FieldGroup+'' - ''+AIF.FieldRemark) AS FieldRemark
		FROM sAdmission.tAdmissionInquiryForm AIF
		LEFT JOIN sAdmission.tAdmissionInquiryField AI ON AI.AdmissionInquiryFormId = AIF.Id
		WHERE (AIF.ClassId = '+CONVERT(nvarchar(10),@rForClassId)+'  OR '+CONVERT(nvarchar(10),@rForClassId)+'=0)
		AND (AIF.BatchId = '+CONVERT(nvarchar(10),@rForBatchId)+' OR '+CONVERT(nvarchar(10),@rForBatchId)+'=0)
	) x
	PIVOT
	(
		MAX(AdmissionInquiryFieldResponse)
		FOR FieldRemark IN (' + @cols + N')
	) p'

	exec sp_executesql @query
	
	SELECT 
		@rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,
		CASE WHEN @rAdmissionInquiryIdText = 0 THEN AI.Number ELSE @rAdmissionInquiryIdText END AS AdmissionInquiryIdText
		,AI.Id
		,AI.ForBatchId
		,AI.ForClassId
		,AI.StatusId
		,ISNULL(SM.Id,0) AS InquiryStatusMasterId
		,ISNULL(AI.GenderId,0) AS GenderId
		,ISNULL(AI.InquiryModeId,0) AS InquiryModeId
		,ISNULL(IMM.Title,'') AS InquiryMode
		,ISNULL(AI.InquiryReferenceId,0) AS InquiryReferenceId		
		,ISNULL(AI.AdmissionCategoryId,0) AS AdmissionCategoryId
		,AI.OrgId
		,ISNULL(AI.Number,0) AS InquiryNumber
		,ISNULL(AI.InquiryDate,'') AS AdmissionInquiryDate 		    
		,OM.DisplayTitle AS OrgName
		,BM.Title AS ForBatch
		,ISNULL(CM.Title,'') AS ClassName	
		,AI.FirstName
		,AI.MiddleName
		,AI.LastName
		,[sStudent].[fStudentNameGet](AI.FirstName , ISNULL(AI.MiddleName,'') , AI.LastName,OM.StudentNameFormatId ) AS StudentName
		,AI.LastName +' ' +AI.FirstName+' '+AI.MiddleName as Name				
		,ISNULL(AI.DateOfBirth,'') As DateOfBirth
		,ISNULL(GM.Title,'') As Gender			
		,AI.ContactNo
		,AI.ContactEmail			
		,AI.StreetOne
		,AI.StreetTwo
		,AI.StreetThree
		,AI.Country
		,AI.State
		,AI.City
		,AI.ZipCode
		,ISNULL(AI.Remark,'') AS Remark						
		,ISNULL(AI.PreviousSchool,'') as PreviousSchool			
		,ISNULL(AI.MeritMarks,0) AS MeritMarks
		,ISNULL(AI.MeritGrade,'') AS MeritGrade
		,ISNULL(AI.MeritMarksBreakup,'') AS MeritMarksBreakup
		,SM.Title as StatusName	
		,ISNULL(AI.FollowupDate,'') As FollowupDate
		,ISNULL(AI.FollowupRemark,'') As FollowupRemark			
		,ISNULL(IRM.Title ,'') AS InquiryReference	
		,ISNULL(SCM.Title,'') AS AdmissionCategory		
		,ISNULL(AI.HandledBy,'') AS HandledBy
		,ISNULL(AI.CreatedDateTime,'') As CreatedDateTime
		,ISNULL(AI.StudentId,0) AS StudentId,
		ISNULL(AI.CastCategoryId,0) AS CastCategoryId,
		ISNULL(AI.IsTransportRequired,0) AS IsTransportRequired,
		ISNULL(AI.IsHostelRequired,0) AS IsHostelRequired,
		CONVERT(int,ISNULL(AI.IsGivenAdmissionForm,0)) AS IsGivenAdmissionForm,
		ISNULL(SM.HighlightColor,'') AS HighlightColor,
		ISNULL(SA.PreviousStandard,'') As PreviousStandard,
		AI.AlternateContactNo,
		AI.AlternateContactEmail
		,CASE WHEN AI.FollowupDate IS NULL THEN '' ELSE  CONVERT(VARCHAR(10), AI.FollowupDate, 103) END AS FollowupDateString,
		ISNULL(AIC.AgeCutOffDate,'') AS AgeCutOffDate,
		ISNULL(AI.MotherName,'') AS MotherName,
		CASE WHEN AI.DataEntryModeId = 561 THEN 'Online' ELSE 'Offline' END DataEntryMode 
		,ISNULL(AI.MinorityStatusId,0) As MinorityStatusId
		,ISNULL(AI.LiveWithId,0) AS LiveWithId
		,ISNULL(AI.AdhaarNumber,'') AS AdhaarNumber 
		,ISNULL(AI.BloodGroupId,0) AS BloodGroupId
		,ISNULL(AI.FatherName,'') AS FatherName
		,ISNULL(AI.FatherOccupation,'') AS FatherOccupation 
		,ISNULL(AI.FatherIncome,0) AS FatherIncome 
		,ISNULL(AI.FatherContactNo,'') AS FatherContactNo
		,ISNULL(AI.FatherMail,'') AS FatherMail
		,ISNULL(AI.FatherQualification,'') AS FatherQualification
		,ISNULL(AI.MotherOccupation,'') As MotherOccupation
		,ISNULL(AI.MotherIncome,0) AS MotherIncome
		,ISNULL(AI.MotherContactNo,'') AS MotherContactNo 
		,ISNULL(AI.MotherMail,'') AS MotherMail 
		,ISNULL(AI.MotherQualification,'') AS  MotherQualification
		,ISNULL(AI.Stream,'') AS Stream
		,ISNULL(AI.Board,'') AS Board
		,ISNULL(CCM.Title,'') AS CasteCategory
		,ISNULL(AI.InquiryReferenceRemark,'') AS InquiryReferenceRemark
		,ISNULL(AI.WhatsAppContactNo,'') AS WhatsAppContactNo
		,tempACF.*
  FROM 
            sAdmission.tAdmissionInquiry AI
            LEFT JOIN sAdmission.tInquiryModeMaster IMM ON IMM.Id = AI.InquiryModeId
            INNER JOIN sAdmission.tInquiryStatusMaster SM ON SM.Id=AI.InquiryStatusId 
			INNER JOIN sSetup.tClassMaster CM ON CM.Id=AI.ForClassId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=AI.OrgId
			INNER JOIN sSetup.tBatchMaster BM ON AI.ForBatchId = BM.Id
			LEFT JOIN sAdmission.tInquiryReferenceMaster IRM ON IRM.Id=AI.InquiryReferenceId
			LEFT JOIN sStudent.tAdmissionCategoryMaster SCM ON SCM.Id=AI.AdmissionCategoryId
			LEFT JOIN sCommon.tGenderMaster GM ON GM.Id=AI.GenderId  
			LEFT JOIN sStudent.tStudentAdmission SA oN SA.StudentId=AI.StudentID
			LEFT JOIN sAdmission.tAdmissionInquiryCriteria AIC ON AIC.ClassId=AI.ForClassId AND AIC.BatchId=AI.ForBatchId 
			LEFT JOIN  scommon.tCastCategoryMaster CCM on CCM.Id = AI.CastCategoryId
			LEFT JOIN sAdmission.tAdmissionInquiryField AIF ON AIF.AdmissionInquiryFormId = AI.Id 
			LEFT JOIN sAdmission.tAdmissionInquiryForm AIF1 ON AIF.AdmissionInquiryFormId = AIF1.Id   
			LEFT JOIN ##tempAdmissionInquiryCustomField tempACF ON tempACF.AdmissionInquiryId = AI.Number
  WHERE  
      ((AI.Id = @rId) OR (@rId = 0))
      AND ((AI.FirstName like @rFirstName) OR (@rFirstName=''))
      AND ((AI.LastName like @rLastName) OR (@rLastName=''))
      AND ((AI.InquiryDate>= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
      AND ((AI.InquiryDate < @rToDate) OR (ISNULL(@rToDate,'')=''))
	  AND ((AI.ForClassId=@rForClassId) OR (@rForClassId=0)) 
	  AND ((SM.Id=@rInquiryStatusMasterId) OR (@rInquiryStatusMasterId=0))
	  AND (AI.OrgId=@rOrgId OR @rOrgId=0)
	  AND ((AI.ForBatchId=@rForBatchId) OR (@rForBatchId=0))
	  AND ((CM.DepartmentId=@rDepartmentId) or (@rDepartmentId = 0))
	  AND ((AI.MeritMarks >= @rFromMeritMarks) OR (@rFromMeritMarks=0))
	  AND ((AI.MeritMarks <= @rToMeritMarks) OR (@rToMeritMarks=0))
	  AND ((AI.InquiryModeId=@rInquiryModeId) OR (@rInquiryModeId=0))
	  AND ((AI.InquiryReferenceId=@rInquiryReferenceId) OR (@rInquiryReferenceId=0))
	  AND ((AI.Number=@rNumber) OR (@rNumber=0))
	  AND (BM.OrgGroupBatchid=@rOrgGroupBatchId OR @rOrgGroupBatchId=0)
	  AND ((AI.FollowUpdate=@rFollowupdate) OR (ISNULL(@rFollowUpdate,'')=''))
	  AND ((ISNULL(AI.IsGivenAdmissionForm,0)=@rIsGivenAdmissionForm) OR (@rIsGivenAdmissionForm=-1))
	  AND (AI.IsTransportRequired = CASE @rIsTransportRequired
                              WHEN 0 THEN ISNULL(AI.IsTransportRequired,0)
                              WHEN 2 THEN 0
                              WHEN 1 THEN 1 END)
	  AND (AI.IsHostelRequired = CASE @rIsHostelRequired
                              WHEN 0 THEN ISNULL(AI.IsHostelRequired,0)
                              WHEN 2 THEN 0
                              WHEN 1 THEN 1 END)
	 AND ((AI.ContactNo = @rContactNo) OR (ISNULL(@rContactNo, '')=''))
	 AND ((AI.HandledBy like @rHandledBy) OR (ISNULL(@rHandledBy, '')=''))
	 AND ((GM.Id = @rGenderId) OR (@rGenderId = 0))
	 Order by Case @rOrderBy When 1 then AI.MeritMarks END desc, Case @rOrderBy when 0 then AI.Number Else AI.Number END desc  
END	
ELSE 
BEGIN
	SELECT 
		@rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,
		CASE WHEN @rAdmissionInquiryIdText = 0 THEN AI.Number ELSE @rAdmissionInquiryIdText END AS AdmissionInquiryIdText,
		 AI.Id
		,AI.ForBatchId
		,AI.ForClassId
		,AI.StatusId
		,ISNULL(SM.Id,0) AS InquiryStatusMasterId
		,ISNULL(AI.GenderId,0) AS GenderId
		,ISNULL(AI.InquiryModeId,0) AS InquiryModeId
		,ISNULL(IMM.Title,'') AS InquiryMode
		,ISNULL(AI.InquiryReferenceId,0) AS InquiryReferenceId		
		,ISNULL(AI.AdmissionCategoryId,0) AS AdmissionCategoryId
		,AI.OrgId
		,ISNULL(AI.Number,0) AS InquiryNumber
		,ISNULL(AI.InquiryDate,'') AS AdmissionInquiryDate 		    
		,OM.DisplayTitle AS OrgName
		,BM.Title AS ForBatch
		,ISNULL(CM.Title,'') AS ClassName	
		,AI.FirstName
		,AI.MiddleName
		,AI.LastName
		,[sStudent].[fStudentNameGet](AI.FirstName , ISNULL(AI.MiddleName,'') , AI.LastName,OM.StudentNameFormatId ) AS StudentName
		,AI.LastName +' ' +AI.FirstName+' '+AI.MiddleName as Name				
		,ISNULL(AI.DateOfBirth,'') As DateOfBirth
		,ISNULL(GM.Title,'') As Gender			
		,AI.ContactNo
		,AI.ContactEmail			
		,AI.StreetOne
		,AI.StreetTwo
		,AI.StreetThree
		,AI.Country
		,AI.State
		,AI.City
		,AI.ZipCode
		,ISNULL(AI.Remark,'') AS Remark						
		,ISNULL(AI.PreviousSchool,'') as PreviousSchool			
		,ISNULL(AI.MeritMarks,0) AS MeritMarks
		,ISNULL(AI.MeritGrade,'') AS MeritGrade
		,ISNULL(AI.MeritMarksBreakup,'') AS MeritMarksBreakup
		,SM.Title as StatusName
		,ISNULL(AI.FollowupDate,'') As FollowupDate
		,ISNULL(AI.FollowupRemark,'') As FollowupRemark			
		,ISNULL(IRM.Title ,'') AS InquiryReference	
		,ISNULL(SCM.Title,'') AS AdmissionCategory		
		,ISNULL(AI.HandledBy,'') AS HandledBy
		,ISNULL(AI.CreatedDateTime,'') As CreatedDateTime
		,ISNULL(AI.StudentId,0) AS StudentId,
		ISNULL(AI.CastCategoryId,0) AS CastCategoryId,
		ISNULL(AI.IsTransportRequired,0) AS IsTransportRequired,
		ISNULL(AI.IsHostelRequired,0) AS IsHostelRequired,
		CONVERT(int,ISNULL(AI.IsGivenAdmissionForm,0)) AS IsGivenAdmissionForm,
		ISNULL(SM.HighlightColor,'') AS HighlightColor,
		ISNULL(SA.PreviousStandard,'') As PreviousStandard,
		AI.AlternateContactNo,
		AI.AlternateContactEmail
		,CASE WHEN AI.FollowupDate IS NULL THEN '' ELSE  CONVERT(VARCHAR(10), AI.FollowupDate, 103) END AS FollowupDateString,
		ISNULL(AIC.AgeCutOffDate,'') AS AgeCutOffDate,
		ISNULL(AI.MotherName,'') AS MotherName,
		CASE WHEN AI.DataEntryModeId = 561 THEN 'Online' ELSE 'Offline' END DataEntryMode 
		,ISNULL(AI.MinorityStatusId,0) As MinorityStatusId
		,ISNULL(AI.LiveWithId,0) AS LiveWithId
		,ISNULL(AI.AdhaarNumber,'') AS AdhaarNumber 
		,ISNULL(AI.BloodGroupId,0) AS BloodGroupId
		,ISNULL(AI.FatherName,'') AS FatherName
		,ISNULL(AI.FatherOccupation,'') AS FatherOccupation 
		,ISNULL(AI.FatherIncome,0) AS FatherIncome 
		,ISNULL(AI.FatherContactNo,'') AS FatherContactNo
		,ISNULL(AI.FatherMail,'') AS FatherMail
		,ISNULL(AI.FatherQualification,'') AS FatherQualification
		,ISNULL(AI.MotherOccupation,'') As MotherOccupation
		,ISNULL(AI.MotherIncome,0) AS MotherIncome
		,ISNULL(AI.MotherContactNo,'') AS MotherContactNo 
		,ISNULL(AI.MotherMail,'') AS MotherMail 
		,ISNULL(AI.MotherQualification,'') AS  MotherQualification
		,ISNULL(AI.Stream,'') AS Stream
		,ISNULL(AI.Board,'') AS Board
		,ISNULL(CCM.Title,'') AS CasteCategory
		,ISNULL(AI.InquiryReferenceRemark,'') AS InquiryReferenceRemark
		,ISNULL(AI.WhatsAppContactNo,'') AS WhatsAppContactNo
  FROM 
            sAdmission.tAdmissionInquiry AI
            LEFT JOIN sAdmission.tInquiryModeMaster IMM ON IMM.Id = AI.InquiryModeId
            INNER JOIN sAdmission.tInquiryStatusMaster SM ON SM.Id=AI.InquiryStatusId 
			INNER JOIN sSetup.tClassMaster CM ON CM.Id=AI.ForClassId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=AI.OrgId
			INNER JOIN sSetup.tBatchMaster BM ON AI.ForBatchId = BM.Id
			LEFT JOIN sAdmission.tInquiryReferenceMaster IRM ON IRM.Id=AI.InquiryReferenceId
			LEFT JOIN sStudent.tAdmissionCategoryMaster SCM ON SCM.Id=AI.AdmissionCategoryId
			LEFT JOIN sCommon.tGenderMaster GM ON GM.Id=AI.GenderId  
			LEFT JOIN sStudent.tStudentAdmission SA oN SA.StudentId=AI.StudentID
			LEFT JOIN sAdmission.tAdmissionInquiryCriteria AIC ON AIC.ClassId=AI.ForClassId AND AIC.BatchId=AI.ForBatchId 
			LEFT JOIN  scommon.tCastCategoryMaster CCM on CCM.Id = AI.CastCategoryId 
  WHERE  
      ((AI.Id = @rId) OR (@rId = 0))
      AND ((AI.FirstName like @rFirstName) OR (@rFirstName=''))
      AND ((AI.LastName like @rLastName) OR (@rLastName=''))
      AND ((AI.InquiryDate>= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
      AND ((AI.InquiryDate < @rToDate) OR (ISNULL(@rToDate,'')=''))
	  AND ((AI.ForClassId=@rForClassId) OR (@rForClassId=0)) 
	  AND ((SM.Id=@rInquiryStatusMasterId) OR (@rInquiryStatusMasterId=0))
	  AND (AI.OrgId=@rOrgId OR @rOrgId=0)
	  AND ((AI.ForBatchId=@rForBatchId) OR (@rForBatchId=0))
	  AND ((CM.DepartmentId=@rDepartmentId) or (@rDepartmentId = 0))
	  AND ((AI.MeritMarks >= @rFromMeritMarks) OR (@rFromMeritMarks=0))
	  AND ((AI.MeritMarks <= @rToMeritMarks) OR (@rToMeritMarks=0))
	  AND ((AI.InquiryModeId=@rInquiryModeId) OR (@rInquiryModeId=0))
	  AND ((AI.InquiryReferenceId=@rInquiryReferenceId) OR (@rInquiryReferenceId=0))
	  AND ((AI.Number=@rNumber) OR (@rNumber=0))
	  AND (BM.OrgGroupBatchid=@rOrgGroupBatchId OR @rOrgGroupBatchId=0)
	  AND ((AI.FollowUpdate=@rFollowupdate) OR (ISNULL(@rFollowUpdate,'')=''))
	  AND ((ISNULL(AI.IsGivenAdmissionForm,0)=@rIsGivenAdmissionForm) OR (@rIsGivenAdmissionForm=-1))
	  AND (AI.IsTransportRequired = CASE @rIsTransportRequired
                              WHEN 0 THEN ISNULL(AI.IsTransportRequired,0)
                              WHEN 2 THEN 0
                              WHEN 1 THEN 1  END)
	  AND (AI.IsHostelRequired = CASE @rIsHostelRequired
                              WHEN 0 THEN ISNULL(AI.IsHostelRequired,0)
                              WHEN 2 THEN 0
                              WHEN 1 THEN 1 END)
	 AND ((AI.ContactNo = @rContactNo) OR (ISNULL(@rContactNo, '')=''))
	 AND ((AI.HandledBy like @rHandledBy) OR (ISNULL(@rHandledBy, '')=''))
	 AND ((GM.Id = @rGenderId) OR (@rGenderId = 0))
	 Order by Case @rOrderBy When 1 then AI.MeritMarks END desc, Case @rOrderBy when 0 then AI.Number Else  AI.Number END desc  
END		    
END
GO
PRINT N'Creating Procedure [sAssessment].[pRptResultSheetStandardMultiExamHTMLGet]...';


GO

CREATE PROCEDURE [sAssessment].[pRptResultSheetStandardMultiExamHTMLGet]
	 
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 @rSubjectId int = 0,
	 @rBatchId int=0,
	 @rClassId int=0,
	 @rDivisionId int=0,
	 @rExamId int,
	 @rCode nvarchar(20)='',
	 @rFromRollNo int=0,
	 @rToRollNo int=0,
	 @rFromRank int=0,
	 @rToRank int=0,
	 @rGrade nvarchar(20)='',
	 @rResultId bigint=0,
	 @rStatusId int=0,
	 @rAcademicId bigint=0,
	 @rFromObtain decimal(5,2)=0,
	 @rToObtain decimal(5,2)=0,
	 @rFromPercentage decimal(5,2)=0,
	 @rToPercentage decimal(5,2)=0,
	 @rIsDetail bit=0,
	 @rIsShowWithDetail bit=0,
	 @rFilterId int=0,
	 @rOrgGroupBatchId int=0,
	 @rClassStatusId int=0,
	 @rMultiCode nvarchar(max)='' 
	
	 --,@rcolumn_visible bit
	

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
begin
 
  --select * from sAssessment.tTempAllExam
 IF(@rOrgGroupBatchId=0)
	SELECT @rOrgGroupBatchId=OrgGroupBatchId FROM sSetup.tBatchMaster WHERE Id=@rBatchId  
  
DECLARE @GradeString nvarchar(1000)
DECLARE @GradeStringRemark nvarchar(500),
@GradeSetId int , @IsIncludeSubExam bit,@GradeStringHtml nvarchar(500)
SELECT @GradeSetId = GradesetId,
	   @IsIncludeSubExam = ISNULL(IsIncludeSubExam,0)  FROM sAssessment.tExamMaster WHERE Id = @rExamId
SELECT @GradeString = [sAssessment].[fGradeStringGet](@GradeSetId)

Select @GradeStringHtml = GradeStringHtml from sAssessment.tGradeSetMaster where Id =@GradeSetId
Select @GradeStringRemark = GradeStringText from sAssessment.tGradeSetMaster Where Id =@GradeSetId

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

DECLARE @lAbsentRemarkConfig nvarchar(20) = ''
SELECT @lAbsentRemarkConfig =ItemValue From sConfig.tConfigurationSetup WHERE ConfigurationId = 515 AND SourceTypeId = 1016 AND SourceId = @lOrgId


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

--#TempAllExam
	CREATE TABLE #TempAllExam
	(
		AcademicIdText nvarchar(20),
		ExamIdText nvarchar(20),
		CoScholasticScopeIdText nvarchar(20),
		IsDisplayMonthlyAttendanceText nvarchar(20),
		ClassIdText nvarchar(50),
		AcademicId bigint,
		ExamName Nvarchar(100),
		StudCode NVarchar(20),
		StudentName Nvarchar(300),
		RollNo int,
		ResultStatus Nvarchar(50),	
		ClassName NVarchar(100),		
		Division NVarchar(100),
		TotalMark decimal(8,2),
		TotalObtain decimal(8,2),
		Percentage decimal(5,2),
		RankNumber int,
		ResultGrade NVarchar(10),
		
		MaximumMark1 decimal(10,2),		
		SubjectGrade1 NVarchar(10),
		Obtain1 decimal(5,2) Default 0,
		ExamMaximum1 decimal(10,2),
		IsPresent1 bit,
						
		MaximumMark2 decimal(10,2),	
		SubjectGrade2 NVarchar(10),
		Obtain2 decimal(5,2) Default 0,
		ExamMaximum2 decimal(10,2),
		IsPresent2 bit,
				
		MaximumMark3 decimal(10,2),
		SubjectGrade3 NVarchar(10),
		Obtain3 decimal(5,2) Default 0,
		ExamMaximum3 decimal(10,2),
		IsPresent3 bit,		
		
		MaximumMark4 decimal(10,2),	
		SubjectGrade4 NVarchar(10),
		Obtain4 decimal(5,2) Default 0,
		ExamMaximum4 decimal(10,2),
		IsPresent4 bit,	
				
		MaximumMark5 decimal(10,2),		
		SubjectGrade5 NVarchar(10),
		Obtain5 decimal(5,2) Default 0,
		ExamMaximum5 decimal(10,2),
		IsPresent5 bit,	
				
		MaximumMark6 decimal(10,2),		
		SubjectGrade6 NVarchar(10),
		Obtain6 decimal(5,2) Default 0,
		ExamMaximum6 decimal(10,2),
		IsPresent6 bit,	
		
		MaximumMark7 decimal(10,2),		
		SubjectGrade7 NVarchar(10),
		Obtain7 decimal(5,2) Default 0,
		ExamMaximum7 decimal(10,2),
		IsPresent7 bit,	
		
		MaximumMark8 decimal(10,2),	
		SubjectGrade8 NVarchar(10),
		Obtain8 decimal(5,2) Default 0,
		ExamMaximum8 decimal(10,2),
		IsPresent8 bit,	
		
		MaximumMark9 decimal(10,2),		
		SubjectGrade9 NVarchar(10),
		Obtain9 decimal(5,2) Default 0,
		ExamMaximum9 decimal(10,2),
		IsPresent9 bit,	
		
		
		MaximumMark10 decimal(10,2),		
		SubjectGrade10 NVarchar(10),
		Obtain10 decimal(5,2) Default 0,
		ExamMaximum10 decimal(10,2),
		IsPresent10 bit,	
		
		MaximumMark11 decimal(10,2),		
		SubjectGrade11 NVarchar(10),
		Obtain11 decimal(5,2) Default 0,
		ExamMaximum11 decimal(10,2),
		IsPresent11 bit,
		
		MaximumMark12 decimal(10,2),		
		SubjectGrade12 NVarchar(10),
		Obtain12 decimal(5,2) Default 0,
		ExamMaximum12 decimal(10,2),
		IsPresent12 bit,
		
		MaximumMark13 decimal(10,2),		
		SubjectGrade13 NVarchar(10),
		Obtain13 decimal(5,2) Default 0,
		ExamMaximum13 decimal(10,2),
		IsPresent13 bit,		
		 
		 
		SubjectGradeTerm1 NVarchar(10),
		SubjectGradeTerm2 NVarchar(10),
		SubjectGradeTerm3 NVarchar(10),
		IsMarksInDecimal bit,
		column_visible bit,
		--Obtain decimal(5,2),
		Percentile decimal(5,2),
		--ClassSubject nvarchar(100),
		ResultDetailId bigint,
		ResultId bigint,	
		Remark1 nvarchar(1000),
		Remark2 nvarchar(300),
		Remark3 nvarchar(300),
		DisplayTitle nvarchar(150),		
		IsRankNo bit, 
		IsGrade bit,
		IsPercentile bit,
		IsPercentage bit,
		IsSubjectPercentile bit,
		IsProcessResult bit,
		IsNegativeMarks bit,
		IsIncludeCoScholastic bit,
		IsOnPrePrinted bit,
		IsDisplayPhoto bit,
		IsDisplayBirthDate bit,
		IsLockForEdit bit,
		IsDisplaySchoolName bit,			
		IsDisplayAttendance bit,
		IsDisplayHeightWeight bit,
		IsResultStatus bit,
		FooterAdjustmentText nvarchar(max),
		DetailAdjustmentText nvarchar(max),
		FooterAdjustment smallint,
		DetailAdjustment smallint,
		ResultRemark nvarchar(200),
		DateOfBirth date,
		HeightTerm1 decimal(5,2),
		WeightTerm1 decimal(5,2),
		HeightTerm2 decimal(5,2),
		WeightTerm2 decimal(5,2),
		HeightAnnual decimal(5,2),
		WeightAnnual decimal(5,2),
		PresentDaysTerm1 smallint,
		PresentDaysTerm2 smallint,
		PresentDaysAnnual smallint,
		TotalDaysTerm1 smallint,
		TotalDaysTerm2 smallint,
		TotalDaysAnnual smallint,
		TotalMarkTerm1 decimal(8,2),
		TotalObtainTerm1 decimal(8,2),
		PercentageTerm1 decimal(5,2),
		RankNumberTerm1 int,
		ResultGradeTerm1 NVarchar(10),
		PercentileTerm1 decimal(5,2),
		ResultStatusTerm1 Nvarchar(50),		   
		TotalMarkTerm2 decimal(8,2),
		TotalObtainTerm2 decimal(8,2),
		PercentageTerm2 decimal(5,2),
		RankNumberTerm2 int,
		ResultGradeTerm2 NVarchar(10),
		PercentileTerm2 decimal(5,2),
		ResultStatusTerm2 Nvarchar(50), 
		TotalMarkTerm3 	decimal(8,2),
		TotalObtainTerm3 decimal(8,2),
		PercentageTerm3 decimal(5,2),
		RankNumberTerm3 int,
		ResultGradeTerm3 NVarchar(10),
		PercentileTerm3 decimal(5,2),
		ResultStatusTerm3 Nvarchar(50), 
		
		TermScopeId tinyint,		 
		StudentPhoto varbinary(max),
		GradeString nvarchar(1000),
		IsDisplayGradeString bit,		 
		IsDisplayInMarksheet bit,
		IsShowSubjectGrade bit,
		IsIncludeInTotal bit,
		ClassSubjectID int,
		SubjectId int,
		--Maximum decimal(5,2),
		SubjectOrderIndex smallint,
		SubjectGrade NVarchar(10),
		SubjectName NVarchar(100),
		SubjectCode Nvarchar(20),	
		SubjectMinimum decimal(10,2),		
		SubjectMaximum decimal(10,2),
		SubjectObtain  decimal(5,2),
		
		Exam1Name Nvarchar(100),		
		TotalMarks1 decimal(8,2),		
		TotalObtain1 decimal(8,2),
		Percentage1 decimal(5,2),
		RankNumber1 int,
		ResultGrade1 NVarchar(10),
		Percentile1 decimal(5,2),
		ResultStatus1 Nvarchar(50),
		Exam1CombineExamName Nvarchar(100),
				
		Exam2Name nvarchar(100),	
		TotalMarks2 decimal(8,2),
		TotalObtain2 decimal(8,2),
		Percentage2 decimal(5,2),
		RankNumber2 int,
		ResultGrade2 NVarchar(10),
		Percentile2 decimal(5,2),
		ResultStatus2 Nvarchar(50),
		Exam2CombineExamName Nvarchar(100),
		
		Exam3Name nvarchar(100),	
		TotalMarks3 decimal(8,2),
		TotalObtain3 decimal(8,2),
		Percentage3 decimal(5,2),
		RankNumber3 int,
		ResultGrade3 NVarchar(10),
		Percentile3 decimal(5,2),		
		ResultStatus3 Nvarchar(50),
		Exam3CombineExamName Nvarchar(100),
		
		Exam4Name nvarchar(100),	
		TotalMarks4 decimal(8,2),
		TotalObtain4 decimal(8,2),
		Percentage4 decimal(5,2),
		RankNumber4 int,
		ResultGrade4 NVarchar(10),
		Percentile4 decimal(5,2),
		ResultStatus4 Nvarchar(50),
		Exam4CombineExamName Nvarchar(100),
		
		Exam5Name nvarchar(100),		
		TotalMarks5 decimal(8,2),
		TotalObtain5 decimal(8,2),
		Percentage5 decimal(5,2),
		RankNumber5 int,
		ResultGrade5 NVarchar(10),
		Percentile5 decimal(5,2),
		ResultStatus5 Nvarchar(50),
		Exam5CombineExamName Nvarchar(100),
		
		Exam6Name nvarchar(100),	
		TotalMarks6 decimal(8,2),
		TotalObtain6 decimal(8,2),
		Percentage6 decimal(5,2),
		RankNumber6 int,
		ResultGrade6 NVarchar(10),
		Percentile6 decimal(5,2),
		ResultStatus6 Nvarchar(50),
		Exam6CombineExamName Nvarchar(100),
		
		Exam7Name nvarchar(100),		
		TotalMarks7 decimal(8,2),
		TotalObtain7 decimal(8,2),
		Percentage7 decimal(5,2),
		RankNumber7 int,
		ResultGrade7 NVarchar(10),
		Percentile7 decimal(5,2),
		ResultStatus7 Nvarchar(50),
		Exam7CombineExamName Nvarchar(100),
		
		Exam8Name nvarchar(100),
		TotalMarks8 decimal(8,2),
		TotalObtain8 decimal(8,2),
		Percentage8 decimal(5,2),
		RankNumber8 int,
		ResultGrade8 NVarchar(10),
		Percentile8 decimal(5,2),
		ResultStatus8 Nvarchar(50),
		Exam8CombineExamName Nvarchar(100),
		
		
		Exam9Name nvarchar(100),	
		TotalMarks9 decimal(8,2),
		TotalObtain9 decimal(8,2),
		Percentage9 decimal(5,2),
		RankNumber9 int,
		ResultGrade9 NVarchar(10),
		Percentile9 decimal(5,2),
		ResultStatus9 Nvarchar(50),
		Exam9CombineExamName Nvarchar(100),
		
		Exam10Name nvarchar(100),	
		TotalMarks10 decimal(8,2),
		TotalObtain10 decimal(8,2),
		Percentage10 decimal(5,2),
		RankNumber10 int,
		ResultGrade10 NVarchar(10),
		Percentile10 decimal(5,2),
		ResultStatus10 Nvarchar(50),
		Exam10CombineExamName Nvarchar(100),
		
		Exam11Name nvarchar(100),	
		TotalMarks11 decimal(8,2),
		TotalObtain11 decimal(8,2),
		Percentage11 decimal(5,2),
		RankNumber11 int,
		ResultGrade11 NVarchar(10),
		Percentile11 decimal(5,2),
		ResultStatus11 Nvarchar(50),
		Exam11CombineExamName Nvarchar(100),
		
		Exam12Name nvarchar(100),	
		TotalMarks12 decimal(8,2),
		TotalObtain12 decimal(8,2),
		Percentage12 decimal(5,2),
		RankNumber12 int,
		ResultGrade12 NVarchar(10),
		Percentile12 decimal(5,2),
		ResultStatus12 Nvarchar(50),
		Exam12CombineExamName Nvarchar(100),

		Exam13Name nvarchar(100),	
		TotalMarks13 decimal(8,2),
		TotalObtain13 decimal(8,2),
		Percentage13 decimal(5,2),
		RankNumber13 int,
		ResultGrade13 NVarchar(10),
		Percentile13 decimal(5,2),
		ResultStatus13 Nvarchar(50),
		Exam13CombineExamName Nvarchar(100),
		
		ResultRemark1 nvarchar(200),
		ResultRemark2 nvarchar(200),
		
		TotalDays decimal(6,2),
		PresentDays decimal(6,2),
		StudentHeight decimal(6,2),
		StudentWeight decimal(6,2),
		ExamSeatNo nvarchar(20),
		ExamId int,
		
		ExamCode nvarchar(20),
		Exam1Code nvarchar(20),
		Exam2Code nvarchar(20),
		Exam3Code nvarchar(20),
		Exam4Code nvarchar(20),
		Exam5Code nvarchar(20),
		Exam6Code Nvarchar(20),
		Exam7Code Nvarchar(20),
		Exam8Code nvarchar(20),
		Exam9Code nvarchar(20),
		Exam10Code nvarchar(20),
		Exam11Code nvarchar(20),
		Exam12Code nvarchar(20),
		Exam13Code nvarchar(20),
		
		IsDisplayParentName bit,
		FatherName nvarchar(100),
		MotherName nvarchar(100),
		IsShowSubjectMark bit, 
		IsOptionalSubject bit,
		CoScholasticScopeId tinyint,
		IsDisplayPrincipalSign bit,
		IsDisplayTeacherSign bit,
		EmployeeSign varbinary(max),
		Batch nvarchar(100),
		ExamNameTerm1 NVarchar(100),
		ExamNameTerm2 NVarchar(100) ,
		ExamNameTerm3 NVarchar(100),
		ClassTeacherName Nvarchar(100),
		FirstName nvarchar(100),
		LastName nvarchar(100),
		IsDisplayMonthlyAttendance bit,
		MarksheetHeaderA4 varbinary(max),
		IsImageHeader bit,
		MyGoal nvarchar(200),
		AreaOfInterest nvarchar(200),
		Responsibility nvarchar(200),
		MyInterestHobby nvarchar(200),
		MyStrength nvarchar(200),
		Achievements nvarchar(1000),
		
		DentalHygiene nvarchar(50),
		VisionLeft nvarchar(50),
		VisionRight nvarchar(50), 
		IsDetail bit,
		SubjectGroupId int,
		SubjectGroupTitle nvarchar(100),
		SubjectGroupCode nvarchar(20),
		DecimalFormat nvarchar(10),
		SubjectRemark nvarchar(100),
		GraceMark decimal(5,2),
		KrupaMark decimal(5,2),
		GradeStringHtml nvarchar(500),
		ResultRemark3 nvarchar(200),
		IsDisplayTotalMark bit,
		SubjectObtainTerm1 decimal(5,2),	
		SubjectObtainTerm2 decimal(5,2),
		SubjectObtainTerm3  decimal(5,2),
		SubjectMaxTerm1 decimal(10,2),
		SubjectMaxTerm2 decimal(10,2),
		SubjectMaxTerm3 decimal(10,2),
		ContactNo nvarchar(50),
		PresentAddress nvarchar(max),
		TeacherSignCaption nvarchar(100),
		PrincipalSignCaption nvarchar(100),
		ParentSignCaption nvarchar(100),
		ImprovementArea nvarchar(200),
		ProgressArea nvarchar(200),
		GeneralRemark nvarchar(1000),
		MyActivity nvarchar(200),
		ClassTeacherRemark nvarchar(1000),
		 
		HouseRemark nvarchar(1000),
		BloodGroup Nvarchar(20),
		TotalDays1 decimal(6,2),
		PresentDays1 decimal(6,2),
		TotalDays2 decimal(6,2),
		PresentDays2 decimal(6,2),
		TotalDays3 decimal(6,2),
		PresentDays3 decimal(6,2),
		TotalDays4 decimal(6,2),
		PresentDays4 decimal(6,2),
		TotalDays5 decimal(6,2),
		PresentDays5 decimal(6,2),
		TotalDays6 decimal(6,2),
		PresentDays6 decimal(6,2),
		TotalDays7 decimal(6,2),
		PresentDays7 decimal(6,2), 
		TotalDays8 decimal(6,2),
		PresentDays8 decimal(6,2),
		TotalDays9 decimal(6,2),
		PresentDays9 decimal(6,2),
		TotalDays10 decimal(6,2),
		PresentDays10 decimal(6,2),
		TotalDays11 decimal(6,2),
		PresentDays11 decimal(6,2),
		TotalDays12 decimal(6,2),
		PresentDays12 decimal(6,2),
		TotalDays13 decimal(6,2),
		PresentDays13 decimal(6,2),
		BatchIdText nvarchar(20),
		IsShowWithDetail bit,
		IsPresent bit,
		GradeTitle nvarchar(50),
		SubjectHighestDivisionGrade nvarchar(50),
		SubjectHighestDivisionMark decimal(5, 2),
		
		AchievementsTerm1 nvarchar(1000),
		AchievementsTerm2 nvarchar(1000),
		GeneralRemarkTerm1 nvarchar(1000),
		GeneralRemarkTerm2 nvarchar(1000),
		ResultRemark1Term1 nvarchar(200),
		ResultRemark2Term1 nvarchar(200),
		ResultRemark1Term2 nvarchar(200),
		ResultRemark2Term2 nvarchar(200),
		SR_HeightTerm1 decimal(6,2),
		SR_WeightTerm1 decimal(6,2),
		SR_HeightTerm2 decimal(6,2),
		SR_WeightTerm2 decimal(6,2),
		SR_PresentDaysTerm1 decimal(6,2),
		SR_PresentDaysTerm2 decimal(6,2),
		SR_TotalDaysTerm1 decimal(6,2),
		SR_TotalDaysTerm2 decimal(6,2),
		HouseId int,
		HouseName nvarchar(100),
		AdhaarNumber nvarchar(20),
		UIdNumber nvarchar(50),
		FatherContactNo nvarchar(50),
		MotherContactNo nvarchar(50),
		FatherMail nvarchar(50),
		MotherMail nvarchar(50),
		Gender nvarchar(100),
		CoordinatorEmployeeSign varbinary(max),
		StudentAddress nvarchar(max),
		SUId nvarchar(50),
		HighestDivisionMark decimal(5, 2),
		HighestDivisionGrade nvarchar(10),
		StreamTitle nvarchar(50),
		AdmissionNo nvarchar(50),
		AdmissionDate Date,
		MiddleName nvarchar(100) ,
		FatherOccupation nvarchar(50),
		ResultSheetAdditionalTitle nvarchar(100),
		IsDecimal bit,
		IsAbsentRemark bit,
		FinalAbsentRemark nvarchar(100),
		AbsentRemark1 nvarchar(100),
		AbsentRemark2 nvarchar(100),
		AbsentRemark3 nvarchar(100),
		AbsentRemark4 nvarchar(100),
		AbsentRemark5 nvarchar(100),
		AbsentRemark6 nvarchar(100),
		AbsentRemark7 nvarchar(100),
		AbsentRemark8 nvarchar(100),
		AbsentRemark9 nvarchar(100),
		AbsentRemark10 nvarchar(100),
		AbsentRemark11 nvarchar(100),
		AbsentRemark12 nvarchar(100),
		AbsentRemark13 nvarchar(100),
		ExamMaximumTerm1 decimal(6,2),
		ExamMaximumTerm2 decimal(6,2),
		ExamMaximumTerm3 decimal(6,2),
		--add for 29923 mantis start
		PermanentStreetOne nvarchar(150),
		PermanentStreetTwo nvarchar(150),
		PermanentStreetThree nvarchar(150),
		--add for 29923 mantis end
		CasteCategory nvarchar(50),--Mantis 0030303
		--Mantis Start - 0031091
		FeeCategory nvarchar(100),
		StudentContactNo nvarchar(50),
		--Mantis End - 0031091
		ObtainedMaximum1 decimal(10,2),
		ObtainedMaximum2 decimal(10,2),
		ObtainedMaximum3 decimal(10,2),
		ObtainedMaximum4 decimal(10,2),
		ObtainedMaximum5 decimal(10,2),
		ObtainedMaximum6 decimal(10,2),
		ObtainedMaximum7 decimal(10,2),
		ObtainedMaximum8 decimal(10,2),
		ObtainedMaximum9 decimal(10,2),
		ObtainedMaximum10 decimal(10,2),
		ObtainedMaximum11 decimal(10,2),
		ObtainedMaximum12 decimal(10,2),
		ObtainedMaximum13 decimal(10,2)
		)
	 --print 'temp created'    	
	INSERT INTO  #TempAllExam 
	(
	AcademicIdText,
	ExamIdText,
	CoScholasticScopeIdText,
	IsDisplayMonthlyAttendanceText,
	ClassIdText,
	AcademicId,
	ExamName,
	StudCode,
	StudentName,
	RollNo,
	ResultStatus,
	ClassName,
	Division,
	TotalMark,
	TotalObtain,
	Percentage,
	RankNumber,
	ResultGrade,
	IsMarksInDecimal,
	column_visible,
	--Obtain,
	Percentile,
	--ClassSubject,
	ResultDetailId,
	ResultId,

	Remark1,
	Remark2,
    Remark3,
	DisplayTitle,
	IsRankNo, 
	IsGrade,
	IsPercentile,
	IsPercentage,
	IsSubjectPercentile,
	IsProcessResult,
	IsNegativeMarks,
	IsIncludeCoScholastic,
	IsOnPrePrinted,
	IsDisplayPhoto,
	IsDisplayBirthDate,
	IsLockForEdit,
	IsDisplaySchoolName,			
	IsDisplayAttendance,
	IsDisplayHeightWeight,
	IsResultStatus,
	FooterAdjustmentText,
	DetailAdjustmentText,
	FooterAdjustment,
	DetailAdjustment,
	ResultRemark,
	DateOfBirth,
	HeightTerm1,
	WeightTerm1,
	HeightTerm2,
	WeightTerm2,
	HeightAnnual,
	WeightAnnual,
	PresentDaysTerm1,
	PresentDaysTerm2,
	PresentDaysAnnual,
	TotalDaysTerm1,
	TotalDaysTerm2,
	TotalDaysAnnual,
	TermScopeId,
	StudentPhoto,
	GradeString,
	IsDisplayGradeString,	 
	IsDisplayInMarksheet,
	IsShowSubjectGrade,
	IsIncludeInTotal,
	ClassSubjectID,
	SubjectId,
	--Maximum,
	SubjectOrderIndex,
	SubjectGrade,
	SubjectName,
	SubjectCode,
	SubjectMinimum,
	SubjectMaximum,
	SubjectObtain,
	ResultRemark1,
	ResultRemark2,
	
	TotalDays,
	PresentDays,
	StudentHeight,
	StudentWeight,
	ExamSeatNo,
	ExamId,
	
	ExamCode,
	
	IsDisplayParentName,
	FatherName,
	MotherName,
	IsShowSubjectMark,
	IsOptionalSubject,
	CoScholasticScopeId,
	IsDisplayPrincipalSign,
	IsDisplayTeacherSign,
	EmployeeSign,
	Batch,
	ClassTeacherName,
	FirstName,
	LastName,
	IsDisplayMonthlyAttendance,
	MarksheetHeaderA4,
	IsImageHeader,
	MyGoal,
	AreaOfInterest,
	Responsibility,
	MyInterestHobby,
	MyStrength,
	Achievements, 
	
	DentalHygiene,
	VisionLeft,
	VisionRight,
	IsDetail,
	SubjectGroupId,
	SubjectGroupTitle,
	SubjectGroupCode,
	DecimalFormat,
	SubjectRemark,
	GraceMark,
	KrupaMark,
	GradeStringHtml,
	ResultRemark3,
	IsDisplayTotalMark,
	ContactNo,
	PresentAddress,
	TeacherSignCaption,
	PrincipalSignCaption,
	ParentSignCaption,
	ImprovementArea,
	ProgressArea,
	GeneralRemark,
	MyActivity,
	ClassTeacherRemark,
	
	HouseRemark,
	BloodGroup,
	BatchIdText,
    IsShowWithDetail,
    IsPresent,
    GradeTitle,
	
	SubjectHighestDivisionGrade,
	SubjectHighestDivisionMark,
	
	AchievementsTerm1,
	AchievementsTerm2,
	GeneralRemarkTerm1,
	GeneralRemarkTerm2,
	ResultRemark1Term1,
	ResultRemark2Term1,
	ResultRemark1Term2,
	ResultRemark2Term2,
	SR_HeightTerm1,
	SR_WeightTerm1,
	SR_HeightTerm2,
	SR_WeightTerm2,
	SR_PresentDaysTerm1,
	SR_PresentDaysTerm2,
	SR_TotalDaysTerm1,
	SR_TotalDaysTerm2,
	HouseName,
	HouseId,
	AdhaarNumber,
	UIdNumber,
	FatherContactNo ,
	MotherContactNo ,
	FatherMail ,
	MotherMail ,
	Gender,
	CoordinatorEmployeeSign,
	StudentAddress,
	SUId,
	HighestDivisionMark,
	HighestDivisionGrade,
	StreamTitle,
	AdmissionNo,
	AdmissionDate,
	MiddleName ,
	FatherOccupation,
	ResultSheetAdditionalTitle,
	IsDecimal,
	IsAbsentRemark,
	FinalAbsentRemark,
	--Mantis Start - 29923 mantis
	PermanentStreetOne,
	PermanentStreetTwo,
	PermanentStreetThree,
	--Mantis End - 29923 mantis
	CasteCategory,--Mantis 0030303
	
	--Mantis Start - 0031091
		FeeCategory,
		StudentContactNo
	--Mantis End - 0031091
	)
	SELECT 
		Convert(nvarchar(20),A.Id),
		Convert(nvarchar(20),@rExamId),
		Convert(nvarchar(20),EM.CoScholasticScopeId),
		Convert(nvarchar(20),ISNULL(EM.IsDisplayMonthlyAttendance,0)),
		Convert(nvarchar(50),@rClassId),
		A.Id,
		ISNULL(ESGM.Title,'') AS EXAMNAME,
		StuM.Code AS StudCode,
		[sStudent].[fStudentNameGet](stum.FirstName , StuM.MiddleName, StuM.LastName,OM.StudentNameFormatId ) AS Name,
		A.RollNo,
		ISNULL(R.ResultStatus,'') AS ResultStatus,
		CM.DisplayTitle AS ClassName,
		DM.DisplayTitle AS Division,
		R.TotalMarks AS TotalMark,
		R.TotalObtain,
		ISNULL(R.Percentage,0) As Percentage,
		R.RankNumber,
		ISNULL(R.ResultGrade,'') AS ResultGrade,


		EM.IsMarksInDecimal,
		
				
		1,
		--RD.Obtain,
		R.Percentile,
		--SM.Title AS ClassSubject,
		RD.Id AS ResultDetailId,
		R.Id AS ResultId,

		ISNULL(EM.Remark1,'') AS Remark1,
		ISNULL(EM.Remark2,'') AS Remark2,
		ISNULL(EM.Remark3,'') AS Remark3,
		EM.DisplayTitle,
		EM.IsRankNo, 
		EM.IsGrade,
		EM.IsPercentile,
		EM.IsPercentage,
		EM.IsSubjectPercentile,
		EM.IsProcessResult,
		EM.IsNegativeMarks,
		EM.IsIncludeCoScholastic,
		EM.IsOnPrePrinted,
		EM.IsDisplayPhoto,
		EM.IsDisplayBirthDate,
		EM.IsLockForEdit,
		EM.IsDisplaySchoolName,			
		EM.IsDisplayAttendance,
		EM.IsDisplayHeightWeight,
		EM.IsResultStatus,
		REPLICATE(',',EM.FooterAdjustment) AS FooterAdjustmentText,
		REPLICATE(',',EM.DetailAdjustment) AS DetailAdjustmentText,
		EM.FooterAdjustment,
		EM.DetailAdjustment,
		ISNULL(R.ResultRemark,'') AS ResultRemark,
		SO.DateOfBirth,
		AD.HeightTerm1,
		AD.WeightTerm1,
		AD.HeightTerm2,
		AD.WeightTerm2,
		AD.HeightAnnual,
		AD.WeightAnnual,
		AD.PresentDaysTerm1,
		AD.PresentDaysTerm2,
		AD.PresentDaysAnnual,
		AD.TotalDaysTerm1,
		AD.TotalDaysTerm2,
		AD.TotalDaysAnnual,
		EM.TermScopeId,
		(CASE EM.IsDisplayPhoto WHEN 1 THEN
		SI.StudentPhoto
		ELSE NULL END)AS StudentPhoto,
		CASE @GradeStringRemark WHEN '' THEN @GradeString ELSE @GradeStringRemark END AS GradeString,
		EM.IsDisplayGradeString,
		ED.IsDisplayInMarksheet,
		ED.IsShowSubjectGrade,
		ED.IsIncludeInTotal,
	    ED.ClassSubjectId,
		CS.SubjectId AS SubjectId,
		--ED.Maximum,
		(CASE ISNULL(ED.DisplayOrder,0)
		WHEN 0 THEN CS.OrderIndex
		ELSE ED.DisplayOrder END) AS SubjectOrderIndex,
		
		--SM.OrderIndex AS SubjectOrderIndex,
		RD.SubjectGrade,
		SM.Title AS SubjectName,
		ISNULL(SM.Code,'') AS SubjectCode,
		ED.Minimum,
		ED.Maximum,
		RD.Obtain,
		SR.ResultRemark1,
		SR.ResultRemark2,
		ISNULL(SR.TotalDays,0)AS TotalDays,
		ISNULL(SR.PresentDays,0)AS PresentDays,
		SR.StudentHeight,
		SR.StudentWeight,
		SR.ExamSeatNo,
		@rExamId,
		ISNULL(ESGM.Code,'') AS ExamCode,
		EM.IsDisplayParentName,
		SF.FatherName,
		SF.MotherName,
		ED.IsShowSubjectMark,
		--EMP.FirstName
		(CASE ISNULL(OS.AcademicId,0)
		WHEN 0 THEN 0
		ELSE 1 END) AS IsOptionalSubject,
		EM.CoScholasticScopeId,
		EM.IsDisplayPrincipalSign,
		Em.IsDisplayTeacherSign,
		(CASE Em.IsDisplayTeacherSign WHEN 1 THEN
			EI.EmployeeSign
			ELSE NULL END ) AS EmployeeSign,
		BM.Title AS Batch,
		EMP.FirstName + ' ' + EMP.LastName AS ClassTeacherName,
		Stum.FirstName,
		Stum.LastName,
		 
		ISNULL(EM.IsDisplayMonthlyAttendance,0) AS IsDisplayMonthlyAttendance,
		--(CASE EM.IsDisplayImageHeader WHEN 1 THEN
		--	OI.CertificateHeaderA4 
		--	ELSE NULL END)AS  MarksheetHeaderA4,
		(CASE EM.IsDisplayImageHeader WHEN 1 THEN 
		OI.MarksheetHeaderA4 
		ELSE 
			NULL END) AS MarksheetHeaderA4,
		ISNULL(EM.IsDisplayImageHeader,0) AS IsImageHeader,
		ISNULL(SR.MyGoal,'') AS MyGoal,
		ISNULL(SR.AreaOfInterest,'') AS AreaOfInterest,
		ISNULL(SR.Responsibility,'') AS Responsibility,
		ISNULL(SR.MyInterestHobby,'') AS MyInterestHobby,
		ISNULL(SR.MyStrength,'') AS MyStrength,
		ISNULL(SR.Achievements,'') AS Achievements,
		ISNULL(SR.DentalHygiene,'') AS DentalHygiene,
		ISNULL(SR.VisionLeft,'') AS VisionLeft,
		ISNULL(SR.VisionRight,'') AS VisionRight,
		@rIsDetail AS IsDetail,
		ISNULL(SM.SubjectGroupId,0) AS SubjectGroupId,
		ISNULL(SG.Title,'')AS SubjectGroupTitle,
		ISNULL(SG.Code,'') AS SubjectGroupCode,
		ISNULL(EM.DecimalFormat,0) AS DecimalFormat,
		ISNULL(RD.Remark,'') AS SubjectRemark,
		RD.GraceMark,
		RD.KrupaMark,
		@GradeStringHtml,
		SR.ResultRemark3,
		EM.IsDisplayTotalMark,
		ISNULL(SC.ParentContactNo,'') AS ContactNo,
		ISNULL(SC.PresentStreetOne,'')+' '+ISNULL(SC.PresentStreetTwo,'')+' '+ISNULL(SC.PresentStreetThree,'')+' '+ISNULL(SC.PresentCity,'')+' '+ISNULL(SC.PresentState,'') AS PresentAddress,
		ISNULL(EM.TeacherSignCaption,'') AS TeacherSignCaption,
		ISNULL(EM.PrincipalSignCaption,'') AS PrincipalSignCaption,
		ISNULL(Em.ParentSignCaption,'') As ParentSignCaption,
		ISNULL(SR.ImprovementArea,'') As ImprovementArea,
		ISNULL(SR.ProgressArea,'') AS ProgressArea,
		ISNULL(SR.GeneralRemark,'') As GeneralRemark,
		ISNULL(SR.MyActivity,'') AS MyActivity,
		ISNULL(SR.ClassTeacherRemark,'') As ClassTeacherRemark,
		ISNULL(Sr.HouseRemark,'') As HouseRemark,
		ISNULL(BGM.Title,'') AS BloodGroup,
		Convert(nvarchar(20),@rBatchId) AS BatchIdText,
		@rIsShowWithDetail AS IsShowWithDetail,
		IsPresent,
		GradeTitle ,
		RAD.SubjectHighestDivisionGrade,
		RAD.SubjectHighestDivisionMark,
		
		'' AS AchievementsTerm1,
		'' AS AchievementsTerm2,
		'' AS GeneralRemarkTerm1,
		'' AS GeneralRemarkTerm2,
		'' AS ResultRemark1Term1,
		'' AS ResultRemark2Term1, 
		'' AS ResultRemark1Term2,
		'' AS ResultRemark2Term2,
		SR.StudentHeight AS SR_HeightTerm1,
		SR.StudentWeight AS SR_WeightTerm1,
		SR.StudentHeight AS SR_HeightTerm2,
		SR.StudentWeight AS SR_WeightTerm2,
		ISNULL(SR.PresentDays,0) AS SR_PresentDaysTerm1,
	    ISNULL(SR.PresentDays,0) AS SR_PresentDaysTerm2,
	    ISNULL(SR.TotalDays,0) AS SR_TotalDaysTerm1,
	    ISNULL(SR.TotalDays,0) AS SR_TotalDaysTerm2,
	    HM.Title As HouseName,HM.Id as HouseId,
	    ISNULL(SO.AdhaarNumber,'') As AdhaarNumber,
	    ISNULL(SO.UIdNumber,'') As UIdNumber,
		SF.FatherContactNo,
		SF.MotherContactNo,
		SF.FatherMail,
		SF.MotherMail,
		(CASE WHEN SO.GenderId=1 THEN 'Male' ELSE 'Female' END)AS Gender,
		(CASE  When EM.CoordinatorEmployeeId IS NOT NULL AND EM.CoordinatorEmployeeId !=0 then EICoordinator.EmployeeSign ELSE NULL END) AS CoordinatorEmployeeSign,
		(SC.PresentStreetOne +' '+ SC.PresentStreetTwo +' '+ SC.PresentStreetThree +' '+ SC.PresentCity +' '+ SC.PermanentState) AS StudentAddress,
		ISNULL(Stum.SUId,'') AS SUId,
		(CASE EM.IsDisplayHighestDivisionMark
		WHEN 1 THEN [sAssessment].[fGetHighestDivisionMark](A.DivisionId ,RD.ExamDetailId)
		ELSE 0 END) AS HighestDivisionMark,
		(CASE EM.IsDisplayHighestDivisionGrade
		WHEN 1 THEN [sAssessment].[fGetHighestDivisionGrade] (A.DivisionId ,RD.ExamDetailId)
		ELSE '' END) AS HighestDivisionGrade,
		ISNULL(StM.Title,'') AS StreamTitle,
		ISNULL(StuA.AdmissionNumber,0) AS AdmissionNo,
		ISNULL(StuA.AdmissionDate,'') AS AdmissionDate,
		Stum.MiddleName ,
		ISNULL(SF.FatherOccupation,'') AS FatherOccupation,
		ISNULL(EM.ResultSheetAdditionalTitle, '') AS ResultSheetAdditionalTitle,
		CONVERT(bit,@lDecimalConfig) AS IsDecimal,
		CONVERT(bit,@lAbsentRemarkConfig) AS IsAbsentRemark,
		ISNULL(RD.AbsentRemark,'') AS FinalAbsentRemark,
		--add for 29923 mantis start
		SC.PermanentStreetOne,
		SC.PermanentStreetTwo,
		SC.PermanentStreetThree,
		--add for 29923 mantis End
		CSM.Title As CasteCategory,      --Mantis 0030303
		--Mantis Start - 0031091
		ACM.Title AS FeeCategory,
		SC.StudentContactNo AS StudentContactNo
		--Mantis End - 0031091
				
FROM 
	sAssessment.tResultDetail RD
	INNER JOIN sAssessment.tResult R ON R.Id = RD.ResultId
	INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId AND R.ExamId = ED.ExamId
	INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId		
	INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
	INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=CS.SubjectId	
	LEFT JOIN sSetup.tSubjectGroupMaster SG ON SG.Id = Sm.SubjectGroupId				 
	INNER JOIN sStudent.tAcademic A ON A.Id=R.AcademicId
	INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=A.OrgId
	LEFT JOIN sSetup.tOrgImages OI ON OI.Orgid = OM.Id
	INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId
	INNER JOIN sStudent.tStudentMaster StuM ON StuM.Id=A.StudentId
	INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId
	INNER JOIN sSetup.tStreamMaster StM ON CM.StreamId = Stm.Id
	INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId
	LEFT JOIN sHrm.tEmployeeImages EI ON EI.EmployeeId = Dm.InchargeEmployeeId
	LEFT JOIN sHrm.tEmployeeMaster EMP ON EMP.Id = DM.InchargeEmployeeId AND  ISNULL(EMP.IsOtherUser,0) = 0
	INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id = EM.EXAMSUBGROUPID
	LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId=StuM.Id
	Left JOIN sActivity.tHouseMaster HM ON SO.HouseId = HM.Id
	LEFT JOIN sStudent.tAcademicDetail AD ON AD.AcademicId=A.Id
	LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId=StuM.Id
	LEFT JOIN sAssessment.tStudentRemark SR ON R.AcademicId = SR.AcademicId AND R.ExamId = SR.ExamId
	LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId = StuM.Id
	LEFT JOIN sAssessment.tOptionalSubject OS ON OS.AcademicId = R.AcademicId AND OS.ClassSubjectId = ED.ClassSubjectId  AND ED.ExamId = R.ExamId
	LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId=A.StudentId
	LEFT JOIN 	sCommon.tBloodGroupMaster BGM ON BGM.Id=So.BloodGroupId
	LEFT JOIN sAssessment.tGradeSetDetail GS ON GS.GradeSetId=ED.GradeSetId AND ED.GradeSetId = @GradeSetId and RD.SubjectGrade = GS.GradeCode
	LEFT JOIN sAssessment.tResultAnalysisDivisionDetail RAD ON RAD.ClassSubjectId = CS.Id AND RAD.DivisionId = A.DivisionId AND RAD.ExamId = Em.Id
	
	LEFT JOIN sHostel.tAssignRoom AR ON  AR.SourceId=StuM.Id AND AR.SourceTypeId=2003 AND ((BM.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  AND ((AR.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0) AND (BM.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 = StuM.Id 
	LEFT JOIN sHrm.tEmployeeImages EICoordinator ON EICoordinator.EmployeeId = EM.CoordinatorEmployeeId		  
	--LEFT JOIN sAcademic.tTeacherSubjectDivision TSD ON TSD.SubjectId=SM.Id AND TSD.DivisionId = A.DivisionId
	--LEFT JOIN sHrm.tEmployeeMaster EMP ON TSD.EmployeeId = EMP.Id
	LEFT JOIN sStudent.tStudentAdmission StuA ON StuM.Id = StuA.StudentId
	LEFT JOIN sCommon.tCastCategoryMaster CSM ON CSM.Id=SO.CastCategoryId        --Mantis 0030303
	LEFT JOIN sStudent.tAdmissionCategoryMaster ACM ON ACM.Id=StuM.AdmissionCategoryId	--Mantis - 0031091
	 
	 WHERE
		R.ExamId = @rExamId 
		AND ((A.DivisionId =  @rDivisionId) OR (@rDivisionId=0))
		AND ((A.ClassId =  @rClassId) OR (@rClassId=0))		 
		AND ((A.BatchId =  @rBatchId) OR (@rBatchId=0))
		AND ((A.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
		AND ((A.RollNo <= @rToRollNo) OR (@rToRollNo=0))
		AND ((R.RankNumber >= @rFromRank) OR (@rFromRank=0))
		AND ((R.RankNumber <= @rToRank) OR (@rToRank=0))
		AND ((R.ResultGrade = @rGrade) OR (@rGrade=''))
		AND ((StuM.Code=@rCode) OR (@rCode=''))	
		AND ((R.Id = @rResultId) OR (@rResultId = 0))	
		AND ((StuM.StatusId=@rStatusId)OR(@rStatusId=0))
		AND((A.Id=@rAcademicId)OR (@rAcademicId=0))
		AND ((CS.SubjectId=@rSubjectId) OR(@rSubjectId=0) ) 
		AND ((R.TotalObtain>=@rFromObtain) OR (@rFromObtain=0))
		AND ((R.TotalObtain<=@rToObtain) OR (@rToObtain=0))
		AND ((R.Percentage>=@rFromPercentage) OR (@rFromPercentage=0))
		AND ((R.Percentage<=@rToPercentage) OR (@rToPercentage=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 ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0)) 
	AND (ISNULL(StuM.Code,0) IN( SELECT cast(item as nvarchar(20)) FROM  sCommon.fnsplit(@rMultiCode,',')) OR @rMultiCode='')
	    
	Order By ED.DisplayOrder

 --print 'temp insert'
  --SET @IsIncludeSubExam = 1
	create TABLE #tempcombineExam
	(	Id int IDENTITY,
		ExamID int )

	IF (@IsIncludeSubExam = 0)
	BEGIN	
	INSERT INTO #tempcombineExam (ExamID) 
	SELECT SUBEXAMID FROM sAssessment.tExamCombine WHERE ExamId  = @rExamId Order By ExamOrder ASC
 	END
 	ELSE
 	BEGIN
 	-- if we want to display result for both the term with all exam select this option
 	INSERT INTO #tempcombineExam (ExamID) 
	SELECT C.SUBEXAMID FROM sAssessment.tExamCombine C
	INNER JOIN (SELECT SUBEXAMID,ExamOrder FROM sAssessment.tExamCombine WHERE ExamId  = @rExamId) E
	ON C.ExamId = E.SubExamId
	ORDER BY E.ExamOrder,C.ExamOrder
	END
	--print ('tempcombine')
	--SELECT * FROM #tempcombineExam
	--ON 
	
	-- Order By ExamOrder ASC
	--WHERE ExamId in (SELECT SUBEXAMID FROM sAssessment.tExamCombine WHERE ExamId  = @rExamId Order By ExamOrder ASC)
	
	DECLARE @lCount int,@query  AS NVARCHAR(MAX),@lSubExamId int,@lCount1 int
  
	Select @lCount = MAX(Id) from #tempcombineExam
	--SET @lCount1 = @lCount+1
	DECLARE @ExamTitle nvarchar(150)
	while (@lCount > 0)
	begin
		select @lSubExamId = ExamID from #tempcombineExam Where Id = @lCount
		--select @ExamTitle = Title from sAssessment.tExamMaster Where Id = @lSubExamId	
		set @query ='update T SET
					 MaximumMark' + convert(nvarchar(15),@lCount)+ '=ED.Maximum,
					 Obtain' + convert(nvarchar(15),@lCount)+'= ISNULL(RD.Obtain,0),
					 IsPresent' + convert(nvarchar(15),@lCount)+'=RD.IsPresent,	
					 AbsentRemark' + convert(nvarchar(15),@lCount)+'= ISNULL(RD.AbsentRemark,' + CHAR(39)+CHAR(39) + '),
					 		
					 SubjectGrade' + convert(nvarchar(15),@lCount)+ '=RD.SubjectGrade,
					 TotalDays'+convert(nvarchar(15),@lCount)+'=SR.TotalDays,
					 PresentDays'+convert(nvarchar(15),@lCount)+'=SR.PresentDays,

					 ObtainedMaximum' + convert(nvarchar(15),@lCount)+ '= CASE WHEN EM.IsDisplayHighestDivisionMark = 1
									THEN [sAssessment].[fGetHighestDivisionMark](A.DivisionId ,RD.ExamDetailId)
									ELSE 0  END							
					 From
						sAssessment.tResultDetail RD
						INNER JOIN sAssessment.tResult R ON R.Id = RD.ResultId
						INNER JOIN sStudent.tAcademic A ON A.Id=R.AcademicId
						INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId AND R.ExamId = ED.ExamId
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
						INNER JOIN sAssessment.tExamSubgroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId					
						INNER JOIN 	#TempAllExam  T ON T.ClassSubjectID = ED.ClassSubjectId And T.AcademicId = R.AcademicId	
						LEFT JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND T.AcademicId = SR.AcademicId 									
						WHERE EM.Id =' + convert(nvarchar(15), @lSubExamId)  
						
--print(@query)
	 execute(@query)
	
						
			set @query ='update T set 
				    TotalMarks' + convert(nvarchar(15),@lCount)+ '=R.TotalMarks,
					TotalObtain' + convert(nvarchar(15),@lCount)+ '=R.TotalObtain,
					Percentage' + convert(nvarchar(15),@lCount)+ '=R.Percentage,
					RankNumber' + convert(nvarchar(15),@lCount)+'=R.RankNumber,
					ResultGrade' + convert(nvarchar(15),@lCount)+'=R.ResultGrade,
					Percentile' + convert(nvarchar(15),@lCount)+'=R.Percentile,
					ResultStatus' + convert(nvarchar(15),@lCount)+'=R.ResultStatus,
					Exam' + convert(nvarchar(15),@lCount)+ 'Name=ESGM.ExamSubGroupDisplayTitle,
					Exam' + convert(nvarchar(15),@lCount)+ 'Code=ESGM.Code,
					ExamMaximum' + convert(nvarchar(15),@lCount)+'=ISNULL(EM.ExamMaximum,0)
					 From						
						sAssessment.tResult R						
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id=R.ExamId
						INNER JOIN sAssessment.tExamSubgroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId					
						INNER JOIN 	#TempAllExam  T ON  T.AcademicId = R.AcademicId						
						WHERE EM.Id =' + convert(nvarchar(15), @lSubExamId)  
						
		execute(@query)
		
		Declare @lCombineExamId int
			SELECT @lCombineExamId = EC.ExamId  FROM [sAssessment].[tExamMaster] EM 
										INNER JOIN SASSESSMENT.TEXAMSUBGROUPmASTER ESGM ON ESGM.ID = EM.ExamSubGroupId  
										INNER JOIN sAssessment.tExamCombine EC ON EC.SubExamId=EM.Id AND EC.ExamId in (SELECT SubExamId  FROM sAssessment.tExamCombine WHERE examid=@rExamId) 
										WHERE   (EM.ClassId=@rClassId) AND EM.BatchId =@rBatchId AND EM.Id = @lSubExamId
			--SELECT @lSubCombineExamName
		set @query ='update T set 
					 Exam' + convert(nvarchar(15),@lCount)+ 'CombineExamName =  EM.DisplayTitle
					  From						
						sAssessment.tResult R						
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id=R.ExamId
						INNER JOIN sAssessment.tExamSubgroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId					
						INNER JOIN 	#TempAllExam  T ON  T.AcademicId = R.AcademicId						
						WHERE EM.Id =' + convert(nvarchar(15), @lCombineExamId) 
				
				--Print @query		
		execute(@query)
		
	set @lCount = @lCount -1
	end
	

	IF (@IsIncludeSubExam = 1)
	BEGIN	
		select @lSubExamId = SubExamId from sAssessment.tExamCombine  Where ExamId  = @rExamId AND ExamOrder = 1
		--select @ExamTitle = Title from sAssessment.tExamMaster Where Id = @lSubExamId	
		
		
			set @query ='update T set					 
					SubjectGradeTerm1=RD.SubjectGrade,
					SubjectObtainTerm1 = RD.Obtain,
					 SubjectMaxTerm1 = ED.Maximum
							 
					 From
						 sAssessment.tResultDetail RD
						INNER JOIN  sAssessment.tResult R ON R.Id = RD.ResultId
						INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId AND R.ExamId = ED.ExamId
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
						INNER JOIN sAssessment.tExamSubgroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId					
						INNER JOIN 	#TempAllExam  T ON T.ClassSubjectID = ED.ClassSubjectId And T.AcademicId = R.AcademicId						
						WHERE EM.Id =' + convert(nvarchar(15), @lSubExamId)  
		
				execute(@query)
				
		set @query ='update T set					 
					 
					TotalMarkTerm1 = R.TotalMarks,
					TotalObtainTerm1=R.TotalObtain,
					PercentageTerm1=R.Percentage,
					RankNumberTerm1=R.RankNumber,
					ResultGradeTerm1=R.ResultGrade,
					PercentileTerm1 = R.Percentile,
					ResultStatusTerm1 = R.ResultStatus,
					ExamNameTerm1 = ESGM.Code,
					AchievementsTerm1 = SR.Achievements,
					GeneralRemarkTerm1 = SR.GeneralRemark,
					ResultRemark1Term1 = SR.ResultRemark1,
					ResultRemark2Term1 = SR.ResultRemark2,
					SR_HeightTerm1 = SR.StudentHeight,
					SR_WeightTerm1 = SR.StudentWeight,
					SR_PresentDaysTerm1 = SR.PresentDays,
					SR_TotalDaysTerm1 = SR.TotalDays,
					ExamMaximumTerm1 = EM.ExamMaximum
					
					From
					 
						sAssessment.tResult  R 				
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id = R.ExamId
						LEFT JOIN sAssessment.tStudentRemark SR ON SR.AcademicId = R.AcademicId AND SR.ExamId = EM.Id
						INNER JOIN sAssessment.tExamSubgroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId					
						INNER JOIN 	#TempAllExam  T ON  T.AcademicId = R.AcademicId						
						WHERE EM.Id =' + convert(nvarchar(15), @lSubExamId)  
						
		 	
						
		execute(@query)
		
					select @lSubExamId = SubExamId from sAssessment.tExamCombine  Where ExamId  = @rExamId AND ExamOrder = 2
		--select @ExamTitle = Title from sAssessment.tExamMaster Where Id = @lSubExamId	
		set @query ='update T set					 
					SubjectGradeTerm2=RD.SubjectGrade,
					SubjectObtainTerm2 = RD.Obtain,
					SubjectMaxTerm2= ED.Maximum,
					AchievementsTerm2 = SR.Achievements,
					GeneralRemarkTerm2 = SR.GeneralRemark,
					ResultRemark1Term2 = SR.ResultRemark1,
					ResultRemark2Term2 = SR.ResultRemark2,
					SR_HeightTerm2 = SR.StudentHeight,
					SR_WeightTerm2 = SR.StudentWeight,
					SR_PresentDaysTerm2 = SR.PresentDays,
					SR_TotalDaysTerm2 = SR.TotalDays
									 
					 From
						sAssessment.tResultDetail RD
						INNER JOIN sAssessment.tResult R ON R.Id = RD.ResultId
						INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId AND R.ExamId = ED.ExamId
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
						LEFT JOIN sAssessment.tStudentRemark SR ON SR.AcademicId = R.AcademicId AND SR.ExamId = EM.Id
						INNER JOIN sAssessment.tExamSubgroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId					
						INNER JOIN 	#TempAllExam  T ON T.ClassSubjectID = ED.ClassSubjectId And T.AcademicId = R.AcademicId						
						WHERE EM.Id =' + convert(nvarchar(15), @lSubExamId)  
		execute(@query)
		
		
				set @query ='update T set
 
					TotalMarkTerm2 = R.TotalMarks,
					TotalObtainTerm2=R.TotalObtain,
					PercentageTerm2=R.Percentage,
					RankNumberTerm2=R.RankNumber,
					ResultGradeTerm2=R.ResultGrade,
					PercentileTerm2 = R.Percentile,
					ResultStatusTerm2 = R.ResultStatus,
					ExamNameTerm2 = ESGM.Code,
					ExamMaximumTerm2 = EM.ExamMaximum			
					 From						 
					   sAssessment.tResult R  				 
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id=R.ExamId
						INNER JOIN sAssessment.tExamSubgroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId					
						INNER JOIN 	#TempAllExam  T ON  T.AcademicId = R.AcademicId						
						WHERE EM.Id =' + convert(nvarchar(15), @lSubExamId)  
		execute(@query)
		
		select @lSubExamId = SubExamId from sAssessment.tExamCombine  Where ExamId  = @rExamId AND ExamOrder = 3
		set @query ='update T set					 
					SubjectGradeTerm3=RD.SubjectGrade,
					SubjectObtainTerm3 = RD.Obtain,
					SubjectMaxTerm3= ED.Maximum				 
					 From
						sAssessment.tResultDetail RD
						INNER JOIN sAssessment.tResult R ON R.Id = RD.ResultId
						INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId AND R.ExamId = ED.ExamId
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
						INNER JOIN sAssessment.tExamSubgroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId					
						INNER JOIN 	#TempAllExam  T ON T.ClassSubjectID = ED.ClassSubjectId And T.AcademicId = R.AcademicId						
						WHERE EM.Id =' + convert(nvarchar(15), @lSubExamId)  
		execute(@query)
		set @query ='update T set
 
					TotalMarkTerm3 = R.TotalMarks,
					TotalObtainTerm3=R.TotalObtain,
					PercentageTerm3=R.Percentage,
					RankNumberTerm3=R.RankNumber,
					ResultGradeTerm3=R.ResultGrade,
					PercentileTerm3 = R.Percentile,
					ResultStatusTerm3 = R.ResultStatus,
					ExamNameTerm3 = ESGM.Code,
					ExamMaximumTerm3 = EM.ExamMaximum			
					 From						 
					   sAssessment.tResult R  				 
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id=R.ExamId
						INNER JOIN sAssessment.tExamSubgroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId					
						INNER JOIN 	#TempAllExam  T ON  T.AcademicId = R.AcademicId						
						WHERE EM.Id =' + convert(nvarchar(15), @lSubExamId)  
		execute(@query)
	END
	
	
	
	
	
	--WHILE (@lCount1 <= 6)
	--BEGIN
	--	set @query ='ALTER TABLE #TempAllExam DROP COLUMN MaximumMark' + convert(nvarchar(15),@lCount1)
	--	execute(@query)
	--	set @query ='ALTER TABLE #TempAllExam DROP COLUMN Exam' + convert(nvarchar(150),@lCount1)+ 'Name'
	--	execute(@query)
	--	set @query ='ALTER TABLE #TempAllExam DROP COLUMN SubjectGrade' + convert(nvarchar(150),@lCount1)
	--	execute(@query)		
	--	set @query ='ALTER TABLE #TempAllExam DROP COLUMN Obtain' + convert(nvarchar(15),@lCount1)
	--	execute(@query)
	--	set @query ='ALTER TABLE #TempAllExam DROP COLUMN ExamMaximum' + convert(nvarchar(15),@lCount1)
	--	execute(@query)
	--	SET @lCount1 = @lCount1 + 1
	--END
	
	SELECT @rBuilder1,@rBuilder2, T.*
	FROM #TempAllExam T
	
	--INNER JOIN SSETUP.TCLASSSUBJECT CS ON CS.ID = T.CLASSSUBJECTID
	--WHERE
	--	((T.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
	--	AND ((T.RollNo <= @rToRollNo) OR (@rToRollNo=0))
	--	AND ((T.RankNumber >= @rFromRank) OR (@rFromRank=0))
	--	AND ((T.RankNumber <= @rToRank) OR (@rToRank=0))
	--	AND ((T.ResultGrade = @rGrade) OR (@rGrade=''))
	--	AND ((T.StudCode=@rCode) OR (@rCode=''))		
		--order by T.RollNo,CS.ORDERINDEX
	--SELECT * FROM #TempAllExam	
	drop table #tempcombineExam
	Drop table #TempAllExam
	
	--Select
	--	'' As Builder1,
	--	'' As Builder2,
	--    '' As AcademicIdText,
	--	'' As ExamIdText,
	--	'' As CoScholasticScopeIdText ,
	--	'' As IsDisplayMonthlyAttendanceText,
	--    '' AS ClassIdText,
	--	0 As AcademicId,
	--	'' As ExamName,
	--	'' As StudCode,
	--	'' As StudentName ,
	--	0 As RollNo,
	--	'' As ResultStatus ,	
	--	'' As ClassName ,		
	--	'' As Division ,
	--	0 As TotalMark ,
	--	0 As TotalObtain,
	--	0 As Percentage ,
	--	0 As RankNumber ,
	--	'' As ResultGrade ,
 --       '' As IsMarksInDecimal,
 --             0 As column_visible,

 --             0 As Percentile ,

 --            0 As ResultDetailId, 
 --            0 As ResultId,

	--	'' As Remark1 ,
	--	'' As Remark2 ,
	--	'' As Remark3 ,
	--	'' As DisplayTitle ,		
	--	0 As IsRankNo , 
	--	0 As IsGrade ,
	--	0 As IsPercentile ,
	--	0 As IsPercentage ,
	--	0 As IsSubjectPercentile ,
	--	0 As IsProcessResult ,
	--	0 As IsNegativeMarks ,
	--	0 As IsIncludeCoScholastic ,
	--	0 As IsOnPrePrinted ,
	--	0 As IsDisplayPhoto ,
	--	0 As IsDisplayBirthDate ,
	--	0 As IsLockForEdit ,
	--	0 As IsDisplaySchoolName ,			
	--	0 As IsDisplayAttendance ,
	--	0 As IsDisplayHeightWeight ,
	--	0 As IsResultStatus ,
	--	'' As FooterAdjustmentText ,
	--	'' As DetailAdjustmentText ,
	--	0 As FooterAdjustment ,
	--	0 As DetailAdjustment ,
	--	'' As ResultRemark ,
	--	'' As DateOfBirth ,
	--	0 As HeightTerm1 ,
	--	0 As WeightTerm1 ,
	--	0 As HeightTerm2,
	--	0 As WeightTerm2 ,
	--	0 As HeightAnnual ,
	--	0 As WeightAnnual ,
	--	0 As PresentDaysTerm1,
	--	0 As PresentDaysTerm2 ,
	--	0 As PresentDaysAnnual ,
	--	0 As TotalDaysTerm1 ,
	--	0 As TotalDaysTerm2 ,
	--	0 As TotalDaysAnnual ,
	--	0 As TermScopeId ,		 
	--	0x As StudentPhoto ,
	--	'' As GradeString,
	--	0 As IsDisplayGradeString ,		 
	--	0 As IsDisplayInMarksheet ,
	--	0 As IsShowSubjectGrade ,
	--	0 As IsIncludeInTotal ,
	--	0 As ClassSubjectID ,
	--	0 As SubjectId ,
	--	--Maximum decimal(5,2),
	--	0 As SubjectOrderIndex ,
	--	'' As SubjectGrade ,
	--	'' As SubjectName ,
	--	'' As SubjectCode ,	
	--	0 As SubjectMinimum ,		
	--	0 As SubjectMaximum ,
	--	0 As SubjectObtain ,
	--	'' As ResultRemark1 ,
	--	'' As ResultRemark2,

	--	0 As TotalDays ,
	--	0 As PresentDays ,
	--	0 As StudentHeight,
	--	0 As StudentWeight ,
	--	'' As ExamSeatNo ,
	--    0 As ExamId ,

 --       '' AS ExamCode,

	--	0 As IsDisplayParentName ,
	--	'' As FatherName ,
	--	'' As MotherName ,
	--	0 As IsShowSubjectMark , 
	--	0 As IsOptionalSubject ,
	--	0 As CoScholasticScopeId ,
	--	0 As IsDisplayPrincipalSign ,
	--	0 As IsDisplayTeacherSign ,
	--	0x As EmployeeSign,
 --            '' As Batch,
 --            '' As ClassTeacherName,
 --      '' AS FirstName,
 --      '' AS LastName,
 --            0 As IsDisplayMonthlyAttendance,
	--	0x As MarksheetHeaderA4 ,
	--	0 As IsImageHeader ,
 --            '' As    MyGoal,
 --       '' As  AreaOfInterest,
 --       '' As Responsibility,
 --       '' As MyInterestHobby,
 --       '' As MyStrength,
 --       '' As Achievements,

	--	  '' As DentalHygiene ,
	--	'' As VisionLeft ,
	--	'' As VisionRight ,
 --             0 As IsDetail,
 --             0 AS   SubjectGroupId,
 --             ''   AS SubjectGroupTitle,
 --        '' AS SubjectGroupCode,
 --        '' AS DecimalFormat,
 --        '' AS SubjectRemark,
 --               0 As GraceMark,
 --               0 As KrupaMark,
 --                '' As GradeStringHtml,
 --          '' As ResultRemark3,
 --         0 As IsDisplayTotalMark,
 --         ''  As ContactNo,
	--	'' As PresentAddress ,
	--	'' As TeacherSignCaption ,
	--	'' As PrincipalSignCaption ,
	--	'' As ParentSignCaption ,
 --       '' As ImprovementArea,
 --       '' As ProgressArea,
 --       '' As GeneralRemark,
 --              '' As MyActivity,
 --        ''  As ClassTeacherRemark,

 --        '' As HouseRemark,
	--	  '' As BloodGroup ,
 --         '' As BatchIdText,
 --                0 As IsShowWithDetail,
 --                0 As IsPresent,
 --                ''  As GradeTitle,

 --         '' As SubjectHighestDivisionGrade,
 --                 0  As SubjectHighestDivisionMark,

 --         '' As  AchievementsTerm1,
 --         '' As  AchievementsTerm2,
 --         '' As GeneralRemarkTerm1,
 --         '' As GeneralRemarkTerm2,
 --         '' As ResultRemark1Term1,
 --          '' As ResultRemark2Term1,
 --          '' As ResultRemark1Term2,
 --         '' As ResultRemark2Term2,
 --         0 As SR_HeightTerm1,
 --         0 As SR_WeightTerm1,
 --         0 As SR_HeightTerm2,
 --         0 As SR_WeightTerm2,
 --         0 As SR_PresentDaysTerm1,
 --         0 As SR_PresentDaysTerm2,
 --         0 As SR_TotalDaysTerm1,
 --         0 As SR_TotalDaysTerm2,
 --         '' As HouseName,
 --         0 As HouseId,
 --         '' As AdhaarNumber,
 --         '' As UidNumber,
 --         '' As FatherContactNo,
 --         '' As MotherContactNo,
 --         '' As FatherMail,
 --         '' As MotherMail,
 --         '' AS Gender,
--			0x AS CoordinatorEmployeeSign ,	
 --			'' As FatherOccupation ,
 --			0 AS IsDecimal,
 --			CONVERT(decimal(6,2),0) AS ExamMaximumTerm1,
 --			CONVERT(decimal(6,2),0) AS ExamMaximumTerm2,
 --			CONVERT(decimal(6,2),0) AS ExamMaximumTerm3

-- SELECT @rBuilder1 AS Builder1,@rBuilder2 AS Builder2, T.* FROM sAssessment.tTempAllExam T
 
	END
--	SELECT @rBuilder1 AS Builder1,@rBuilder2 AS Builder2, T.* FROM sAssessment.tTempAllExam T
	
--end
GO
PRINT N'Creating Procedure [sErp].[pVersionUpdateDetailsGet]...';


GO

CREATE PROCEDURE [sErp].[pVersionUpdateDetailsGet]
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
 
DECLARE @lCurrentVersionId int , @lReleaseDate Date
SELECT @lCurrentVersionId = VersionId FROM sSystem.tDatabaseInfo

--concat 20 for fullYear (like replace 23 to 2023)
DECLARE @lVersionId int = CONVERT(nvarchar,20)+CONVERT(nvarchar,@lCurrentVersionId)

SELECT @lReleaseDate = ReleaseDate FROM SapphireERP.sErp.tReleaseNote WHERE VersionId = @lVersionId
SELECT 
	Id,
	ReleaseDate,
	VersionNumber,
	VersionId

FROM SapphireERP.sErp.tReleaseNote WHERE ReleaseDate > @lReleaseDate AND IsObsolete = 0  Order By ReleaseDate


--Select * from [sSystem].[tVersionUpdate]
	 
END
GO
PRINT N'Creating Procedure [sFee].[pFeePendingAllOldBatchGet]...';


GO
CREATE PROCEDURE [sFee].[pFeePendingAllOldBatchGet] 
	@rOrgGroupBatchId INT = 0
	,@rBatchId INT = ''
	,@rOrgId INT = 0
	,@rCode NVARCHAR(20) = ''
	,@rUserId BIGINT = 0

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	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 AS DivisionOrderIndex
		,FS.OrderIndex AS FeeOrderIndex
	INTO #TempAllPendingFeeBatch
	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
		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.Code = @rCode) OR (@rCode = ''))
		
		
		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
		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.Code = @rCode) OR (@rCode = ''))
			
		) 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 ((R.CreatedUserId = @rUserId) OR (@rUserId = 0))
			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 (
			(SA.OrgGroupBatchId = @rOrgGroupBatchId)
			OR (@rOrgGroupBatchId = 0)
			)
		--AND (
		--	(SA.BatchId = @rBatchId)
		--	OR (@rBatchId = 0)
		--	)
		AND (
			(SA.Code = @rCode)
			OR (@rCode = '')
			)
		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)
	ORDER BY SA.RollNo

	DECLARE @lBatchOrderIdex smallint = 0
	SET @lBatchOrderIdex = (SELECT OrderIndex FROM sSetup.tBatchMaster WHERE Id = @rBatchId) 

	SELECT T.OrgId
		,T.ReceiptBookId
		,T.AcademicId
		,T.DivisionId
		,T.ClassDivision
		,T.RollNo
		,T.Name
		,T.Code
		,T.ReceiptBookTitle
		,T.OrgName
		,SUM(T.PendingAmount) AS PendingAmount
		,(SELECT STUFF((
				SELECT ', ' + FeeCode
				FROM 
				(SELECT FeeCode, FeeOrderIndex FROM 
				#TempAllPendingFeeBatch
				WHERE T.AcademicId = AcademicId 
				AND T.ReceiptBookId = ReceiptBookId
				AND T.BatchId = BatchId
				GROUP BY FeeCode, FeeOrderIndex)
				AS A
				ORDER BY FeeOrderIndex
				FOR XML PATH('')
				), 1, 1, '')) AS PendingFeeName 
		--'[sFee].[fPendingFeeNamesGet]'(AcademicId,ReceiptBookId,	@p) AS PendingFeeName,
		,T.ReceiptOrderIndex
		,T.BatchId
		,T.BatchName
		,T.Pickup
		,T.DRoppoint
		,T.PresentContactNo
		,T.SUID
		,T.ClassOrderIndex
		,T.DivisionOrderIndex
		,BM.OrderIndex AS BatchOrderIndex
	FROM #TempAllPendingFeeBatch T
	INNER JOIN sSetup.tBatchMaster BM ON BM.Id = T.BatchId 
	WHERE BM.OrderIndex < @lBatchOrderIdex
	GROUP BY T.OrgId
			,T.AcademicId
			,T.ReceiptBookId
			,T.DivisionId
			,T.BatchId
			,T.ClassDivision
			,T.RollNo
			,T.Name
			,T.Code
			,T.ReceiptBookTitle
			,T.OrgName
			,T.ReceiptOrderIndex
			,T.BatchName
			,T.Pickup
			,T.DRoppoint
			,T.PresentContactNo
			,T.SUID
			,T.ClassOrderIndex
			,T.DivisionOrderIndex
			,BM.OrderIndex
	
	ORDER BY AcademicId DESC 
END
GO
PRINT N'Creating Procedure [sPayroll].[pRptBankStatement]...';


GO

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

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

	SET @rEmployeeCode = sCommon.fSearchStringGet(@rEmployeeCode)
    SET @rEmployeeName = sCommon.fSearchStringGet(@rEmployeeName)
	

	SELECT 
		@rOrderByField AS OrderByField,
		@rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,
		EM.EmployeeId, 
		PP.ID As PayProcessId,
		PPE.ID AS PayProcessEmployeeId,
		PP.SalaryMonth,
		PP.SalaryYear,
		tEM.FirstName +' '+tEM.MiddleName+' '+tEm.LastName AS EmployeeName,
		[sHrm].[fEmployeeNameGet](tEM.FirstName, tEM.MiddleName, tEm.LastName, OM.EmployeeNameFormatId) AS EmployeeNameFormatWise,
		EM.Code AS EmployeeCode,
		PPE.TotalEarning,
		PPE.TotalDeduction,
		PPE.NetAmount,
		(CASE WHEN PayElementId = @lBasicPayElementId then PPE.TotalEarning else 0 END) AS TotalEarningTotal,
		(CASE WHEN PayElementId = @lBasicPayElementId then PPE.TotalDeduction else 0 END) AS TotalDeductionTotal,
		(CASE WHEN PayElementId = @lBasicPayElementId then PPE.NetAmount else 0 END) AS NetAmountTotal,
		ISNULL(ESO.BankName,'') AS BankName,
		ISNULL(ESO.AccountNumber,'') AS AccountNumber,
		MM.Title AS MonthName,
		ISNULL(PPE.WorkingDays,0) AS WorkingDays,
		(ISNULL(PPE.WorkingDays,0) - ISNULL(PPE.Lwp,0)) AS PresentDays,
		ISNULL(PPE.GrossBasic,0) AS GrossBasic,
		PY.Title AS PayrollYearName,
		PGM.Id AS PayrollGroupId,
		PGM.Title AS PayrollGroupName,
		ISNULL(ESO.IFSCNumber,'') AS IFSCNumber,
		tEM.FirstName,
		tEm.LastName,
		ISNULL(ESO.AccountHolderName,'')AS AccountHolderName,
		tEM.Number,
		EM.EmployeeDesignation,
		(CASE WHEN ISNULL(PM.HeaderDisplayId,1) = 3 THEN ISNULL(PM.PayrollHeader,0x) ELSE NULL END) AS PayrollHeader,
		ISNULL(PM.HeaderDisplayId,1)AS HeaderDisplayId,
		ISNULL(PER.ChequeNo,'') ChequeNo,
		PER.PayDate,
		ISNULL(PER.PayTypeId,0) AS PayTypeId,
		tEM.CreatedDateTime

		
	FROM sPayroll.tPayProcess PP 
	INNER JOIN sPayroll.tPayProcessEmployee PPE ON PPE.PayProcessId=PP.ID
	INNER JOIN sHrm.vEmployeeCommonDetail EM ON EM.EmployeeId = PPE.EmployeeId 
	INNER JOIN sHrm.tEmployeeMaster tEM ON tEM.Id = PPE.EmployeeId 
	INNER JOIN sPayroll.tPayProcessElement PE ON PE.PayProcessEmployeeId=PPE.ID
	INNER JOIN sPayroll.tPayElement P ON PE.PayElementId=P.ID 
	LEFT JOIN sHrm.tEmployeeStatutoryAndOther ESO ON ESO.EmployeeId=PPE.EmployeeId	
	INNER JOIN sCommon.tMonthMaster MM ON MM.Id=PP.SalaryMonth	
	INNER JOIN sPayroll.tPayrollYearMaster PY ON PP.PayrollYearId = PY.Id 
	INNER JOIN sPayroll.tPayrollGroupMaster PGM ON PGM.Id = PPE.PayrollGroupId
	INNER JOIN sPayroll.tPayrollMaster PM ON PY.PayrollId = PM.Id
	INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = tEM.OrgId
	LEFT JOIN sPayroll.tPayProcessEmployeeRemark PER ON
		PER.SalaryMonth=@rForMonth AND PER.SalaryYear=@rForYear	AND PER.PayrollYearId=@rPayrollYearId AND EM.EmployeeId = PER.EmployeeId
where 
      (PPE.EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
      AND ((EM.Code Like '%' +  @rEmployeeCode + '%' ) OR (@rEmployeeCode = ''))
	  AND ((EM.EmployeeName Like '%' + @rEmployeeName  + '%') OR (@rEmployeeName = ''))
	  AND (EM.DepartmentId = @rDepartmentId OR @rDepartmentId = 0)
	  AND (PP.SalaryMonth = @rForMonth OR @rForMonth = 0)
	  AND (PP.SalaryYear = @rForYear OR @rForYear = 0) 
	  AND ((PY.PayrollId=@rPayrollId) OR (@rPayrollId=0))
	  AND (PPE.PayrollGroupId = @rPayrollGroupId OR @rPayrollGroupId = 0) 
	  AND (PP.PayrollYearId = @rPayrollYearId OR @rPayrollYearId = 0) 
	  AND ((tEM.OrgID = @rOrgId) OR (@rOrgId = 0))
	  AND ((tEM.StatusId = @rStatusId) OR (@rStatusId = 0))
	  AND ((EM.EmployeeGroupId = @rEmployeeGroupId) OR (@rEmployeeGroupId = 0))
	 
END
GO
PRINT N'Creating Procedure [sPayroll].[pRptMonthlyPayElementwiseListGet]...';


GO

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

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


	SELECT 
	@rOrderByField AS OrderByField,
	@rBuilder1 AS Builder1,
	@rBuilder2 AS Builder2,	
	PE.Amount,
	P.Id AS PayElementId, 
	P.Title AS PayElementName,
	P.Code AS PayElementCode,
	EM.EmployeeId,
	tEM.FirstName +' '+tEM.MiddleName+' '+ tEM.LastName AS EmployeeName,
	EM.Code,
	EM.EmployeeDesignation,
	PP.SalaryMonth,
	PP.SalaryYear,
	MM.Title AS MonthName,
	PY.Title AS PayrollYearName,
	P.SortOrder,
	P.PayElementTypeId,
	@rPayElementTypeId AS IsPayElementTypeIdZero,
	@rPayElementId AS IsPayElementIdZero, 
	PPE.TotalEarning,		
	PPE.TotalDeduction,
	PPE.NetAmount,
	PGM.Id AS PayrollGroupId,
	PGM.Title AS PayrollGroupName,
	PPE.GrossBasic ,
	P.PayElementDefaultId,
	ISNULL(PPE.WorkingDays,0) AS WorkingDays,
	ISNULL(PPE.Lwp,0) AS Lwp,
	EM.FirstName,
	EM.LastName,
	tEM.Number,
	OM.Id AS OrganizationId,
	OM.Title AS OrganizationTitle,
	OM.Code AS OrganizationCode,
	OM.OrderIndex AS OrganizationOrderIndex,
	@rIsDetail AS IsDetail,
	EM.DateOfBirth,
	EM.DateOfJoining,
	(CASE WHEN ISNULL(PM.HeaderDisplayId,1) = 3 THEN ISNULL(PM.PayrollHeader,0x) ELSE NULL END) AS PayrollHeader,
	ISNULL(PM.HeaderDisplayId,1)AS HeaderDisplayId,
	tEM.CreatedDateTime as CreatedDateTime,
			CASE 
			WHEN ISNULL(P.IsEmployeeSpecific,0) = 1
			THEN
				(SELECT PS.Percentage 
					FROM sPayroll.tPaySetup PS 
					WHERE PS.PayElementId = P.Id 
					AND (PS.SourceId = tEM.Id AND PS.SourceTypeId = 95) 
					AND PS.PayrollYearId = PP.PayrollYearId)
			ELSE
				(SELECT PS.Percentage
					FROM sPayroll.tPaySetup PS 
					WHERE PS.PayElementId = P.Id 
					AND (PS.SourceId = PPE.PayrollGroupId AND PS.SourceTypeId = 2020) 
					AND PS.PayrollYearId = PP.PayrollYearId) 
			END AS PaySetupPercentage,
			ESO.AccountNumber,
		[sHrm].[fEmployeeNameGet](tEM.FirstName, tEM.MiddleName, tEm.LastName, OM.EmployeeNameFormatId) AS EmployeeNameFormatWise
		
	FROM sPayroll.tPayProcessEmployee PPE
		INNER JOIN sPayroll.tPayProcess PP ON PPE.PayProcessId=PP.ID
		INNER JOIN sPayroll.tPayProcessElement PE ON PE.PayProcessEmployeeId=PPE.ID
		INNER JOIN sPayroll.tPayElement P ON P.ID=PE.PayElementId AND P.IsObsolete = 0
		INNER JOIN sHrm.vEmployeeCommonDetail EM ON EM.EmployeeId=PPE.EmployeeId
		INNER JOIN sHrm.tEmployeeMaster tEM ON tEM.Id=PPE.EmployeeId
		LEFT JOIN sHrm.tEmployeeStatutoryAndOther ESO ON ESO.EmployeeId=PPE.EmployeeId	
		INNER JOIN sCommon.tMonthMaster MM ON MM.Id=PP.SalaryMonth
		INNER JOIN sPayroll.tPayrollYearMaster PY ON PP.PayrollYearId = PY.Id 
		INNER JOIN sPayroll.tPayrollGroupMaster PGM ON PGM.Id = PPE.PayrollGroupId
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = tEM.OrgId
		INNER JOIN sPayroll.tPayrollMaster PM ON PY.PayrollId = PM.Id
WHERE 
      (PPE.EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
      AND ((P.ID=@rPayElementId) OR (@rPayElementId=0))
      AND ((EM.Code Like  @rEmployeeCode) OR (@rEmployeeCode = ''))
	  AND ((EM.EmployeeName Like @rEmployeeName ) OR (@rEmployeeName = ''))
	  AND (EM.DepartmentId = @rDepartmentId OR @rDepartmentId = 0)
	  AND (PP.SalaryMonth = @rForMonth OR @rForMonth = 0)
	  AND (PP.SalaryYear = @rForYear OR @rForYear = 0)
	  AND ((PY.PayrollId=@rPayrollId) OR (@rPayrollId=0))
	  AND (PPE.PayrollGroupId = @rPayrollGroupId OR @rPayrollGroupId = 0) 
	  AND (PP.PayrollYearId = @rPayrollYearId OR @rPayrollYearId = 0) 
	  AND (P.PayElementTypeId = @rPayElementTypeId OR @rPayElementTypeId = 0) 
	  AND (PP.SalaryMonth IN(SELECT cast(item as int) FROM  sCommon.fnsplit(@rMonths,',')) OR @rMonths='')
	  AND ((tEM.OrgID = @rOrgId) OR (@rOrgId = 0))
	  AND ((tEM.StatusId = @rStatusId) OR (@rStatusId = 0))
	  AND ((EM.EmployeeGroupId = @rEmployeeGroupId) OR (@rEmployeeGroupId = 0))
END
GO
PRINT N'Creating Procedure [sPayroll].[pRptPayStatementGet]...';


GO

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

BEGIN 
	DECLARE @lMonthDay int=0
	SELECT @lMonthDay=[sCommon].[fGetDaysInMonth] (@rForMonth,@rForYear)

	DECLARE @lFirstDate Date
	DECLARE @lLasteDate Date
	IF(@rForMonth!=0 and @rForYear!=0)
	BEGIN
		SET @lFirstDate = CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'/'+CONVERT(NVARCHAR(2),@rForMonth)+'/01'))
		SET @lLasteDate=DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,@lFirstDate)+1,0))
	END

	SET @rEmployeeCode = sCommon.fSearchStringGet(@rEmployeeCode)
	SET @rEmployeeName = sCommon.fSearchStringGet(@rEmployeeName)


	SELECT 
		@rOrderByField AS OrderByField,
		@rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,	
		ISNULL(ESO.EPFNumber,'') AS PFNumber,
		EM.EmployeeId,
		tEM.FirstName +' '+tEM.MiddleName+' '+ tEM.LastName AS EmployeeName,
		[sHrm].[fEmployeeNameGet](tEM.FirstName, tEM.MiddleName, tEm.LastName, OM.EmployeeNameFormatId) AS EmployeeNameFormatWise,
		EM.Code AS EmployeeCode,
		ISNULL(PPE.GrossBasic,0) AS GrossBasic,
		PY.Title AS PayrollYearName,
		PP.SalaryMonth,
		PP.SalaryYear,
	    MM.Title AS MonthName,
	    ISNULL(ESO.UAN,'') AS UAN,
	    PPE.TotalEarning,
	    EM.FirstName,
		EM.LastName,
		tEM.Number,
		(CASE WHEN ISNULL(PM.HeaderDisplayId,1) = 3 THEN ISNULL(PM.PayrollHeader,0x) ELSE NULL END) AS PayrollHeader,
		ISNULL(PM.HeaderDisplayId,1)AS HeaderDisplayId,
		EM.DateOfLeaving,
		tEM.CreatedDateTime,
		ISNULL(PPE.WorkingDays,@lMonthDay) WorkingDays,
		PPE.Lwp,
		ISNULL(PPE.PaidLeave,0) PaidLeave,
		ISNULL(PER.ChequeNo,'') ChequeNo,
		PER.PayDate,
		CASE WHEN ISNULL(PER.PayTypeId,0) = 0 THEN ISNULL(ESO.PayTypeId,0)
			ELSE ISNULL(PER.PayTypeId,0) END AS PayTypeId,
		CASE WHEN ISNULL(PER.PayTypeId,0) = 0 THEN ISNULL(PTM2.Title,'')
			ELSE ISNULL(PTM.Title,'') END AS PayTypeName


	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
		LEFT JOIN sHrm.tEmployeeStatutoryAndOther ESO ON ESO.EmployeeId=EM.EmployeeId
		INNER JOIN sPayroll.tPayProcessElement PE ON PE.PayProcessEmployeeId=PPE.ID
		INNER JOIN sPayroll.tPayElement P ON PE.PayElementId=P.ID 
		INNER JOIN sPayroll.tPayrollYearMaster PY ON PP.PayrollYearId = PY.Id
		INNER JOIN sCommon.tMonthMaster MM ON MM.Id=PP.SalaryMonth
		INNER JOIN sHrm.tEmployeeAttendance AT ON AT.EmployeeId=EM.EmployeeId AND ((AT.ForMonth = @rForMonth) OR (@rForMonth = 0))  AND ((AT.ForYear = @rForYear) OR (@rForYear = 0)) 
		INNER JOIN sPayroll.tPayrollMaster PM ON PY.PayrollId = PM.Id
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=tEM.OrgId
		LEFT JOIN sPayroll.tPayProcessEmployeeRemark PER ON
			PER.SalaryMonth=@rForMonth AND PER.SalaryYear=@rForYear	AND PER.PayrollYearId=@rPayrollYearId AND EM.EmployeeId = PER.EmployeeId
		LEFT JOIN sFinanceCommon.tPayTypeMaster PTM ON PTM.Id = PER.PayTypeId
		LEFT JOIN sFinanceCommon.tPayTypeMaster PTM2 ON PTM2.Id = ESO.PayTypeId
WHERE 
		(PPE.EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
		AND ((EM.Code Like @rEmployeeCode) OR (@rEmployeeCode = ''))
		AND ((EM.EmployeeName Like @rEmployeeName) OR (@rEmployeeName = ''))
		AND ((PP.SalaryMonth = @rForMonth) OR (@rForMonth = 0))
	    AND ((PP.SalaryYear = @rForYear) OR (@rForYear = 0))
		AND ((PY.PayrollId=@rPayrollId) OR (@rPayrollId=0))
		AND (PPE.PayrollGroupId = @rPayrollGroupId OR @rPayrollGroupId = 0) 
		AND (PP.PayrollYearId = @rPayrollYearId OR @rPayrollYearId = 0) 
		AND ((EM.DateOfleaving >= @lFirstDate) OR ISNULL(EM.DateOfleaving,'') = '' OR ISNULL(@lFirstDate,'')='')
        AND ((EM.DateOfJoining <= @lLasteDate) OR ISNULL(EM.DateOfJoining,'') = '' OR ISNULL(@lLasteDate,'')='')
		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


GO
PRINT N'Update complete.';


GO

--change Config type from true/false to dropdown value for fee receipt
GO
UPDATE sConfig.tConfigurationSetup SET ItemValue = CASE WHEN ISNULL(ItemValue, '') = 'Force' THEN 'Force'  WHEN ISNULL(ItemValue, '') = 'General' THEN 'General' WHEN ISNULL(ItemValue, '') = 'No Need' THEN 'No Need' WHEN ISNULL(ItemValue, '') = 'True' THEN 'General' ELSE 'No Need' END WHERE ConfigurationId = 330
GO
GO
UPDATE sConfig.tConfigurationSetup SET ItemValue = CASE WHEN ISNULL(ItemValue, '') = 'True' THEN 'General' ELSE 'No Need' END WHERE ConfigurationId = 287
GO

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

