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

GO
PRINT N'Altering Table [sCanteen].[tCanteenIssue]...';


GO
ALTER TABLE [sCanteen].[tCanteenIssue]
    ADD [Remarks] NVARCHAR (1000) NULL;


GO
PRINT N'Creating Index [sCommunication].[tAssignmentView].[AssignmentId_UserId]...';


GO
CREATE NONCLUSTERED INDEX [AssignmentId_UserId]
    ON [sCommunication].[tAssignmentView]([AssignmentId] ASC, [UserId] ASC);


GO
PRINT N'Altering View [sCertificate].[vPrintTemplateBonafideCertificate]...';


GO
ALTER VIEW [sCertificate].[vPrintTemplateBonafideCertificate]
AS
	SELECT
		B.Id,
		B.Number,
		B.AcademicId,
		SM.Code,
		[sStudent].[fStudentNameGet](SM.FirstName , SM.MiddleName, SM.LastName,OM.StudentNameFormatId ) AS Name,
		CM.DisplayTitle+' - '+DM.DisplayTitle AS Class,
		BM.Title AS Batch,
		SM.FirstName,
		SM.MiddleName,
		SM.LastName,
		SO.DateOfBirth,
		ISNULL(SO.BirthDateInWord,'') AS DOBInWords,
		ISNULL(SO.BirthPlace,'') AS BirthPlace,
		ISNULL(SO.BirthTaluka,'') AS Taluka,
		ISNULL(SO.BirthDistrict,'')	AS District,
		B.BonafideDate,
		ISNULL(SO.FamilyCast,'') AS Caste,
		ISNULL(SO.FamilySubCast,'') AS SubCaste,
		ISNULL(OM.CityName,'') AS City,
		ISNULL(OM.StateName,'') AS CityState,
		SO.GenderId,
		SI.StudentPhoto,
		OM.OrgLogo,
		OM.Title AS OrgTitle,
		SM.StatusId,
		A.RollNo,
		DM.OrderIndex AS DivisionOrder,
		ATM.Title AS AffiliationType,
		OM.ReportOrgTitle,
		OM.SmallAddress1,
		OM.SmallAddress2,
		OM.RegistrationDetail,
		ISNULL(RM.Title,'') AS ReligionName,
		B.Remark AS ReceiptNo,
		SF.FatherName,
		SA.AdmissionDate,
		DP.Title AS DepartmentName,
		ISNULL(OM.DegreeAwarded,'') AS DegreeAwarded,
		OI.CertificateHeaderA4,
		REPLICATE(',',OM.LetterHeadMargin)    AS LetterHeadMargin,
		ISNULL(B.BonafiedReason,'') AS BonafiedReason,
		CT.Title AS Category,
		SF.MotherName,
		C.PermanentStreetOne,
		C.PermanentStreetTwo,
		C.PermanentStreetThree,
		C.PermanentCountry,
		C.PermanentState,
		C.PermanentCity,
		C.PermanentZipCode,
		C.PermanentContactNo,
		C.PresentStreetOne,
		C.PresentStreetTwo,
		C.PresentStreetThree,
		C.PresentCountry,
		C.PresentState,
		C.PresentCity,
		C.PresentContactNo,
		C.PresentZipCode,
		SM.SUId,
		SO.AdhaarNumber,
		CM.DisplayTitle AS ClassName,
		ISNULL(CTM.Nationality,'') AS Nationality,
		OM.PrincipalSignature,
		ISnull(AR.SourceId,0) AS StudentidForhostel,
		DM.DisplayTitle AS Divisionname,
		SM.RecordStatusId,
		SO.BirthState AS BirthState,
		CM1.Title AS AdmissionStandard,
		A.BatchId,
		GM.Title AS Gender,
		ISNULL(SM.LocalName,'') AS LocalName,	--Add for Mantis: 32199
		ISNULL(SM.PENNumber,'') AS PENNo,	--Add for Mantis: 33853
        '[AdhaarNumber],[AdmissionDate],[AdmissionStandard],[AffiliationType],[Batch],[BirthPlace],[BirthState],[BonafideDate],[BonafiedReason],[Caste],[Category],[CertificateHeaderA4],[City],[CityState],[Class],[ClassName],[Code],[ColumnList],[DateOfBirth],[DegreeAwarded],[DepartmentName],[District],[Divisionname],[DivisionOrder],[DOBInWords],[FatherName],[FirstName],[Gender],[LastName],[LetterHeadMargin],[MiddleName],[MotherName],[Name],[Nationality],[Number],[OrgLogo],[OrgTitle],[PermanentCity],[PermanentContactNo],[PermanentCountry],[PermanentState],[PermanentStreetOne],[PermanentStreetThree],[PermanentStreetTwo],[PermanentZipCode],[PresentCity],[PresentContactNo],[PresentCountry],[PresentState],[PresentStreetOne],[PresentStreetThree],[PresentStreetTwo],[PresentZipCode],[PrincipalSignature],[ReceiptNo],[RecordStatusId],[RegistrationDetail],[ReligionName],[ReportOrgTitle],[RollNo],[SmallAddress1],[SmallAddress2],[StudentPhoto],[SubCaste],[Taluka],[LocalName],[PENNo],[SUID],[Remark],[UIDNumber],[Kumar-Kumari],[He-She],[His-Her],[is-was],[Mr-Miss],[Son-Daughter],[LeftDate]' As ColumnList,  --added[Remark] by dhananjay for mantis - 38238
		ISNULL(B.Remark,'') AS Remark, --added by dhananjay for mantis - 38238
		--Mantis: 32199, add LocalName in ColumnList
		--Manits: 33853, add PENNo and SUID in ColumnList
		ISNULL(SO.UIDNumber ,'') AS UIDNumber,  --Mantis - 38768
		CASE WHEN SO.GenderId = 1 Then 'Kumar'
			WHEN SO.GenderId = 2 Then 'Kumari' END AS [Kumar-Kumari],
		CASE WHEN SO.GenderId = 1 Then 'He'
			WHEN SO.GenderId = 2 Then 'She' END AS [He-She],
		CASE WHEN SO.GenderId = 1 Then 'His'
			WHEN SO.GenderId = 2 Then 'Her' END AS [His-Her],
		CASE WHEN SM.StatusId = 1 Then 'is'
			ELSE 'was' END AS [is-was],
		CASE WHEN SO.GenderId = 1 Then 'Mr.'
			WHEN SO.GenderId = 2 Then 'Miss' END AS [Mr-Miss],
		CASE WHEN SO.GenderId = 1 Then 'Son'
			WHEN SO.GenderId = 2 Then 'Daughter' END AS [Son-Daughter],
		SA.LeftDate

	FROM
		sCertificate.tBonafide B
		INNER JOIN sStudent.tAcademic A ON B.AcademicId=A.Id
		LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId=A.StudentId
		INNER JOIN sStudent.tStudentMaster SM ON SM.Id=A.StudentId
		LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId=A.StudentId
		INNER JOIN sSetup.tDivisionMaster DM ON A.DivisionId = DM.Id
		INNER JOIN sSetup.tClassMaster CM ON CM.Id= DM.ClassId
		INNER JOIN sSetup.tBatchMaster BM ON BM.Id=A.BatchId
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=A.OrgId
		left JOIN sSetup.tOrgImages OI ON OI.OrgId = OM.Id
		INNER JOIN sSetup.tAffiliationMaster AM ON OM.AffiliationId = AM.Id
		INNER JOIN sSetup.tAffiliationTypeMaster ATM ON AM.AffiliationTypeId = ATM.Id
		LEFT JOIN sCommon.tReligionMaster RM ON SO.ReligionId=RM.Id
		LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId = SM.Id
		INNER JOIN sStudent.tStudentAdmission SA ON SA.StudentId = SM.Id
		LEFT JOIN sSetup.tClassMaster CM1 ON CM1.Id = SA.AdmissionStandardId
		INNER JOIN sSetup.tDepartmentMaster DP ON CM.DepartmentId = DP.Id
		LEFT JOIN sCommon.tCastCategoryMaster CT ON CT.Id = SO.CastCategoryId
		LEFT JOIN sStudent.tStudentCommunication C ON C.StudentId = A.StudentId
		LEFT JOIN sCommon.tCountryMaster CTM ON CTM.Id=SO.NationalityId
		LEFT JOIN SHostel.tAssignRoom Ar On Ar.SourceId=A.StudentId
		INNER JOIN sCommon.tGenderMaster GM ON GM.Id = SO.GenderId
GO
PRINT N'Altering View [sCertificate].[vPrintTemplateCharacterCertificate]...';


GO

ALTER VIEW [sCertificate].[vPrintTemplateCharacterCertificate]
AS
	SELECT
		C.Id AS Id,
		C.AcademicId AS AcademicId,
		SM.Code AS Code,
		[sStudent].[fStudentNameGet](SM.FirstName , SM.MiddleName, SM.LastName,OM.StudentNameFormatId ) AS Name,
		CM.DisplayTitle+' - '+DM.DisplayTitle AS Class,
		CM.DisplayTitle AS ClassOnly,
		BM.Title AS Batch,
		SO.DateOfBirth,
		ISNULL(SO.BirthDateInWord,'') AS DOBInWords,
		ISNULL(SO.BirthPlace,'') AS BirthPlace,
		ISNULL(SO.BirthTaluka,'') AS Taluka,
		ISNULL(SO.BirthDistrict,'')	AS District,
		C.characterDate AS characterDate,
		C.Number AS Number,
		ISNULL(SO.FamilyCast,'') AS Caste,
		ISNULL(SO.FamilySubCast,'') AS SubCaste,
		ISNULL(OM.CityName,'') AS City,
		ISNULL(OM.StateName,'') AS CityState,
		SO.GenderId AS GenderId,
		SI.StudentPhoto AS StudentPhoto,
		OM.OrgLogo AS OrgLogo,
		OM.Title AS OrgName,
		OM.StateName+' '+OM.StreetTwo+' '+OM.StreetThree AS OrgAddress,
		OM.PhoneNo AS PhoneNo,
		SM.StatusId AS StatusId,
		A.RollNo AS RollNo,
		DM.OrderIndex AS DivisionOrder,
		OM.ReportOrgTitle AS ReportOrgTitle,
		OM.SmallAddress1 AS SmallAddress1,
		OM.SmallAddress2 AS SmallAddress2,
		OM.RegistrationDetail AS RegistrationDetail,
		OI.CertificateHeaderA4 AS CertificateHeaderA4,
		SA.AdmissionDate AS AdmissionDate,
		SF.FatherName AS FatherName,
		A.BatchId AS BatchId,
		ISNULL(SM.LocalName,'') AS LocalName,	--Add for Mantis: 32199
		CASE WHEN SO.GenderId = 1 Then 'Kumar'
			WHEN SO.GenderId = 2 Then 'Kumari' END AS [Kumar-Kumari],
		CASE WHEN SO.GenderId = 1 Then 'He'
			WHEN SO.GenderId = 2 Then 'She' END AS [He-She],
		CASE WHEN SO.GenderId = 1 Then 'His'
			WHEN SO.GenderId = 2 Then 'Her' END AS [His-Her],
		CASE WHEN SM.StatusId = 1 Then 'is'
			ELSE 'was' END AS [is-was],
		'[AdmissionDate],[Batch],[BirthPlace],[Caste],[CertificateHeaderA4],[characterDate],[City],[CityState],[Class],[ClassOnly],[Code],[DateOfBirth],[District],[DivisionOrder],[DOBInWords],[FatherName],[Name],[Number],[OrgAddress],[OrgLogo],[OrgName],[PhoneNo],[RegistrationDetail],[ReportOrgTitle],[RollNo],[SmallAddress1],[SmallAddress2],[StudentPhoto],[SubCaste],[Taluka],[LocalName],[Kumar-Kumari],[He-She],[His-Her],[is-was]' As ColumnList
		--Mantis: 32199, add LocalName in ColumnList
	FROM
		sCertificate.tCharacter C
		INNER JOIN sStudent.tAcademic A ON C.AcademicId=A.Id
		LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId=A.StudentId
		INNER JOIN sStudent.tStudentMaster SM ON SM.Id=A.StudentId
		INNER JOIN sStudent.tStudentOther SO ON SO.StudentId=A.StudentId
		INNER JOIN sSetup.tDivisionMaster DM ON A.DivisionId = DM.Id
		INNER JOIN sSetup.tClassMaster CM ON CM.Id= DM.ClassId
		INNER JOIN sSetup.tBatchMaster BM ON BM.Id=A.BatchId
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=A.OrgId
		LEFT JOIN sSetup.tOrgImages OI ON OI.OrgId = OM.Id
		LEFT JOIN sStudent.tStudentAdmission SA ON SA.StudentId=A.StudentId
		LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId=A.StudentId
GO
PRINT N'Altering View [sCertificate].[vPrintTemplateFirstTrialCertificate]...';


GO


ALTER VIEW [sCertificate].[vPrintTemplateFirstTrialCertificate]
AS
	SELECT
		FT.Id,
		FT.Number,
		FT.AcademicId,
		FT.FirstTrialDate,
		FT.ExamCentre,
		FT.ExamYear,
		FT.SeatNo,
		FT.Trial,
		SM.Code,
		[sStudent].[fStudentNameGet](SM.FirstName , SM.MiddleName, SM.LastName,OM.StudentNameFormatId ) AS Name,
		SM.LastName as Surname,
		SO.GenderId,
		ISNULL(OM.CityName,'') AS City,
		ISNULL(OM.StateName,'') AS CityState,
		SM.StatusId,
		OM.OrgLogo,
		OM.Title AS OrgTitle,
		OM.StreetOne+' '+OM.StreetTwo+' '+OM.StreetThree AS OrgAddress,
		OM.PhoneNo,
		A.RollNo,
		DM.OrderIndex AS DivisionOrder,
		OM.ReportOrgTitle,
		OM.SmallAddress1,
		OM.SmallAddress2,
		OM.RegistrationDetail,
		CM.DisplayTitle+' - '+DM.DisplayTitle AS Class,
		CM.DisplayTitle  AS ClassName,
		OI.CertificateHeaderA4,
		(CASE WHEN CGM.Title='10' THEN  'SSC'
		WHEN  CGM.Title='12'  THEN 'HSC'  ElSE CGM.Title + ' '+'std'
		END) AS Exam,
		FT.Remark AS Remark,
		ISNULL(SF.FatherName,'') As FatherName,
		SA.AdmissionDate,
		SO.BirthDateInWord,
		SO.DateOfBirth,
		SI.StudentPhoto,
		SM.SUID,
		A.BatchId,
		ISNULL(SM.LocalName,'') AS LocalName,	--Add for Mantis: 32199
		ISNULL(DeptM.DisplayTitle,'') AS DepartmentName, --add for mantis : 0040988
		ISNULL(FT.LastExamName,'') AS LastExamName, --add for mantis : 0041177
		ISNULL(FT.ObtainedMark,'') AS ObtainedMarkInLastExam, --add for mantis : 0041177
		CASE WHEN SO.GenderId = 1 Then 'Kumar'
			WHEN SO.GenderId = 2 Then 'Kumari' END AS [Kumar-Kumari],
		CASE WHEN SO.GenderId = 1 Then 'He'
			WHEN SO.GenderId = 2 Then 'She' END AS [He-She],
		CASE WHEN SO.GenderId = 1 Then 'His'
			WHEN SO.GenderId = 2 Then 'Her' END AS [His-Her],
		CASE WHEN SM.StatusId = 1 Then 'is'
			ELSE 'was' END AS [is-was],
		CASE WHEN SO.GenderId = 1 Then 'Mr.'
			WHEN SO.GenderId = 2 Then 'Miss' END AS [Mr.-Miss],
		CASE WHEN SO.GenderId = 1 Then 'Son'
			WHEN SO.GenderId = 2 Then 'Daughter' END AS [Son-Daughter],
		CASE WHEN SO.GenderId = 1 Then 'Him'
			WHEN SO.GenderId = 2 Then 'Her' END AS [Him-Her],
		'[AdmissionDate],[BirthDateInWord],[CertificateHeaderA4],[City],[CityState],[Class],[ClassName],[Code],[DateOfBirth],[DivisionOrder],[Exam],[ExamCentre],[ExamYear],[FatherName],[FirstTrialDate],[Name],[Number],[OrgAddress],[OrgLogo],[OrgTitle],[PhoneNo]
,[RegistrationDetail],[Remark],[ReportOrgTitle],[RollNo],[SeatNo],[SmallAddress1],[SmallAddress2],[StudentPhoto],[SUID],[Surname],[Trial],[LocalName],[DepartmentName],[LastExamName],[ObtainedMarkInLastExam],[Kumar-Kumari],[He-She],[His-Her],[is-was],[Mr.-Miss],[Son-Daughter],[Him-Her]' As ColumnList
		--Mantis: 32199, add LocalName in ColumnList  
		--Mantis: 0041177, add [LastExamName],[ObtainedMarkInLastExam] in ColumnList  
	FROM
		sCertificate.tFirstTrial FT
		INNER JOIN sStudent.tAcademic A ON FT.AcademicId=A.Id
		INNER JOIN sStudent.tStudentMaster SM ON SM.Id=A.StudentId
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=A.OrgId
		INNER JOIN sStudent.tStudentOther SO ON SO.StudentId=A.StudentId
		INNER JOIN sSetup.tDivisionMaster DM ON A.DivisionId = DM.Id
		INNER JOIN sSetup.tClassMaster CM ON CM.Id= DM.ClassId
		Left JOIN sSetup.tOrgImages OI ON OI.OrgId = OM.Id
		LEFT JOIN sSetup.tClassGroupMaster CGM ON CGM.Id = CM.ClassGroupId
		LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId=A.StudentId
		LEFT JOIN sStudent.tStudentAdmission SA ON SA.StudentId=A.StudentId
		LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId=A.StudentId
		INNER JOIN sSetup.tDepartmentMaster DeptM ON DeptM.Id = CM.DepartmentId --add for mantis : 0040988
GO
PRINT N'Altering View [sCertificate].[vPrintTemplateLeavingCertificate]...';


GO

ALTER VIEW [sCertificate].[vPrintTemplateLeavingCertificate]
AS
	SELECT
		L.Id,
		SM.Code,
		L.AcademicId,
		SM.FirstName,SM.MiddleName,SM.LastName,
		[sStudent].[fStudentNameGet](SM.FirstName , SM.MiddleName, SM.LastName,OM.StudentNameFormatId ) AS Name,
		ISNULL(SF.FatherName,'') As FatherName,
		ISNULL(SF.MotherName,'') As MotherName,
		ISNULL(CTM.Nationality,'') AS Nationality,
		ISNULL(RM.Title,'') AS Religion,
		ISNULL(so.BirthPlace,'') AS BirthPlace,
		ISNULL(SO.BirthTaluka,'') AS BirthTaluka,
		ISNULL(SO.BirthDistrict,'') AS BirthDistrict,
		SO.DateOfBirth,
		ISNULL(SO.BirthDateInWord,'') AS DOBInWord,
		SA.PreviousSchool,
		SA.AdmissionDate,
		L.LCNumber,
		L.LeftDate,
		L.LCReason,
		L.LCProgress,
		L.LCConduct,
		L.LCRemark,
		L.LCDate,
		L.LCBookNumber,
		SO.GenderId,
		ISNULL(SO.FamilySubCast,'') AS SubCaste,
		ISNULL(SO.FamilyCast,'') AS Caste,
		ISNULL(OM.CityName,'') AS City,
		ISNULL(OM.StateName,'') AS CityState,
		CM.DisplayTitle AS AdmissionStandard,
		CMS.DisplayTitle AS CurrentStandard,
		CMS.Title AS CurrentStandardTitle,
		SM.StatusId,
		L.LastExamName AS Result,
		L.LastExamResult AS FailOrPass,
		L.SubjectStudied AS SubjectNAme,
		L.RepeatDetail as PromotedorNot,
		L.PromoteToClass  AS PromotedToClass,
		L.FeeDetail AS LastFeesPaid,
		L.FeeConcessionDetail AS AnyConcession,
		L.NCCScoutDetail  AS NCCScoutDetail,
		L.ExtraCurricularActivities AS GamesPlayed,
		OM.OrgLogo,
		OM.Title AS OrgTitle,
		OM.StreetOne+' '+OM.StreetTwo+' '+OM.StreetThree AS OrgAddress,
		OM.PhoneNo,
		vSA.RollNo,
		DM.OrderIndex AS DivisionOrder,
		OM.SmallAddress1,
		OM.SmallAddress2,
		OM.RegistrationDetail,
		AD.PresentDaysAnnual AS PresentDaysSum,
		AD.TotalDaysAnnual AS TotalDaysSum,
		vSA.ClassName AS ClassName,
		vSA.DivisionName AS DivisionName,
		OI.CertificateHeaderA4,
		isnull(MainCastCategoryId,0) AS CastCategoryId,
		ISNULL(L.ToCollege,'') AS ToCollege,
		ISNULL(L.ToCollegeAddress,'')AS ToCollegeAddress,
		ISNULL(OM.University,'')AS University,
		ISNULL(CSG.Inword,'')AS CurrentStandardInWords,
		SO.MotherTongue,
		SO.AdhaarNumber,
		vSA.SUId,
		CASE WHEN isnull(BM.FromDate,'')>Isnull(SA.AdmissionDate,'') THEN BM.FromDate ELSE SA.AdmissionDate END AS BatchDate,
		SO.BirthState,
		SO.BirthCountry,
		SD.BankAccountNumber,
		SO.UIDNumber,
		SD.BankName,
		SD.BankIFSCCode,
		SA.PreviousStandard,
		L.TermsInInstitute,
		L.LCCopy,
		(EM.FirstName + ' ' + EM.LastName) AS ClassTeacher,
		vSA.BatchName AS BatchName,
		CSM.Title As CasteCategory,
		vSA.BatchId,
		GetDate() AS PrintDate, --Change for Mantis id 29447 and also added in below row "[PrintDate]"
		ISNULL(SM.LocalName,'') As LocalName,	--Add for Mantis: 32199
		ISNULL(L.DisplayName,NULL) As DisplayName,	--Add for mantis : 0041217
		CASE WHEN SO.GenderId = 1 Then 'Kumar'
			WHEN SO.GenderId = 2 Then 'Kumari' END AS [Kumar-Kumari],
		CASE WHEN SO.GenderId = 1 Then 'He'
			WHEN SO.GenderId = 2 Then 'She' END AS [He-She],
		CASE WHEN SO.GenderId = 1 Then 'His'
			WHEN SO.GenderId = 2 Then 'Her' END AS [His-Her],
		CASE WHEN SM.StatusId = 1 Then 'is'
			ELSE 'was' END AS [is-was],
		'[AdhaarNumber],[AdmissionDate],[AdmissionStandard],[AnyConcession],[BankAccountNumber],[BankIFSCCode],[BankName],[BatchDate],[BatchName],[BirthCountry],[DOBInWord],[BirthDistrict],[BirthPlace],[BirthState],[BirthTaluka],[Caste],[CasteCategory],[CertificateHeaderA4],[City],[CityState],[ClassName],[ClassTeacher],[Code],[CurrentStandard],[CurrentStandardInWords],[CurrentStandardTitle],[DateOfBirth],[DivisionName],[DivisionOrder],[FailOrPass],[FatherName],[FirstName],[GamesPlayed],[LastFeesPaid],[LastName],[LCBookNumber],[LCConduct],[LCCopy],[LCDate],[LCNumber],[LCProgress],[LCReason],[LCRemark],[LeftDate],[MiddleName],[MotherName],[MotherTongue],[Name],[Nationality],[NCCScoutDetail],[OrgAddress],[OrgLogo],[OrgTitle],[PhoneNo],[PresentDaysSum],[PreviousSchool],[PreviousStandard],[PromotedorNot],[PromotedToClass],[RegistrationDetail],[Religion],[Result],[RollNo],[SUId],[SmallAddress1],[SmallAddress2],[SubCaste],[SubjectNAme],[TermsInInstitute],[ToCollege],[ToCollegeAddress],[TotalDaysSum],[UIDNumber],[University],[PrintDate],[LocalName],[Kumar-Kumari],[He-She],[His-Her],[is-was]' As ColumnList
		--Mantis: 32199, add LocalName in ColumnList
	FROM
		sCertificate.tLeaving L
		INNER JOIN sStudent.vStudentAcademic vSA ON vSA.AcademicId=L.AcademicId
		LEFT JOIN sStudent.tStudentAdmission SA ON SA.StudentId=vSA.StudentId
		INNER JOIN sStudent.tStudentMaster SM ON SM.Id=vSA.StudentId
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=vSA.OrgId
		LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId=vSA.StudentId
		LEFT JOIN sCommon.tReligionMaster RM ON SO.ReligionId=RM.Id
		LEFT JOIN sSetup.tClassMaster CM ON CM.Id=SA.AdmissionStandardId
		INNER JOIN sSetup.tDivisionMaster DM ON vSA.DivisionId = DM.Id
		INNER JOIN sSetup.tClassMaster CMS ON CMS.Id= DM.ClassId
		LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId=vSA.StudentId
		LEFT JOIN sCommon.tCountryMaster CTM ON CTM.Id=SO.NationalityId
		LEFT JOIN sStudent.tAcademicDetail AD ON AD.AcademicId=vSA.AcademicId
		LEFT JOIN sSetup.tOrgImages OI ON OI.OrgId = OM.Id
		LEFT JOIN sCommon.tCastCategoryMaster CSM ON CSM.Id=SO.CastCategoryId
		LEFT JOIN sSetup.tClassGroupMaster CSG ON CSG.Id=CMS.ClassGroupId
		INNER JOIN sSetup.tBatchMaster BM ON BM.Id=vSA.BatchId
		LEFT JOIN sStudent.tStudentAdditional SD ON SD.StudentId=vSA.StudentId
		LEFT JOIN sHrm.tEmployeeMaster EM ON DM.InchargeEmployeeId = EM.Id			-- MantisId : 0033805
GO
PRINT N'Altering View [sCertificate].[vPrintTemplateTransferCertificateReport]...';


GO

ALTER VIEW [sCertificate].[vPrintTemplateTransferCertificateReport]
AS
	SELECT
		T.Id,
		SM.Code,
		T.AcademicId,
		SM.FirstName,SM.MiddleName,SM.LastName,
		[sStudent].[fStudentNameGet](SM.FirstName , SM.MiddleName, SM.LastName,OM.StudentNameFormatId ) AS Name,
		ISNULL(SF.FatherName,'') As FatherName,
		ISNULL(SF.MotherName,'') As MotherName,
		ISNULL(CTM.Nationality,'') AS Nationality,
		ISNULL(RM.Title,'') AS Religion,
		ISNULL(so.BirthPlace,'') AS BirthPlace,
		ISNULL(SO.BirthTaluka,'') AS BirthTaluka,
		ISNULL(SO.BirthDistrict,'') AS BirthDistrict,
		SO.DateOfBirth,
		ISNULL(SO.BirthDateInWord,'') AS DOBInWord,
		SA.PreviousSchool,
		SA.AdmissionDate,
		--L.LCNumber,
		T.Number,
		T.TCDate,
		T.LeftDate,
		T.LeftDate as [TransferDate],
		T.SemesterDuration,
		T.ExamName,
		T.ExamSeatNo,
		T.ExamYear,
		T.ExamResult,
		T.PromotedClass,
		T.TransferConduct,
		T.OptionalSubject,
		T.Reason,
		T.Remark,
		SO.GenderId,
		ISNULL(SO.FamilySubCast,'') AS SubCaste,
		ISNULL(SO.FamilyCast,'') AS Caste,
		ISNULL(OM.CityName,'') AS City,
		ISNULL(OM.StateName,'') AS CityState,
		CM.DisplayTitle AS AdmissionStandard,
		CMS.DisplayTitle AS CurrentStandard,
		CMS.Title AS CurrentStandardTitle,
		SM.StatusId,
		OM.OrgLogo,
		OM.Title AS OrgTitle,
		OM.StreetOne+' '+OM.StreetTwo+' '+OM.StreetThree AS OrgAddress,
		OM.PhoneNo,
		vSA.RollNo,
		DM.OrderIndex AS DivisionOrder,
		OM.SmallAddress1,
		OM.SmallAddress2,
		OM.RegistrationDetail,
		AD.PresentDaysAnnual AS PresentDaysSum,
		AD.TotalDaysAnnual AS TotalDaysSum,
		vSA.ClassName AS ClassName,
		vSA.DivisionName AS DivisionName,
		OI.CertificateHeaderA4,
		isnull(MainCastCategoryId,0) AS CastCategoryId,
		ISNULL(OM.University,'')AS University,
		ISNULL(CSG.Inword,'')AS CurrentStandardInWords,
		SO.MotherTongue,
		SO.AdhaarNumber,
		vSA.SUId,
		CASE WHEN isnull(BM.FromDate,'')>Isnull(SA.AdmissionDate,'') THEN BM.FromDate ELSE SA.AdmissionDate END AS BatchDate,
		SO.BirthState,
		SO.BirthCountry,
		SD.BankAccountNumber,
		SO.UIDNumber,
		SD.BankName,
		SD.BankIFSCCode,
		SA.PreviousStandard,		
		DM.InchargeEmployeeId AS ClassTeacher,
		vSA.BatchName AS BatchName,
		CSM.Title As CasteCategory,
		vSA.BatchId,
		ISNULL(SM.LocalName,'') AS LocalName,	
		CASE WHEN SO.GenderId = 1 Then 'Kumar'
			WHEN SO.GenderId = 2 Then 'Kumari' END AS [Kumar-Kumari],
		CASE WHEN SO.GenderId = 1 Then 'He'
			WHEN SO.GenderId = 2 Then 'She' END AS [He-She],
		CASE WHEN SO.GenderId = 1 Then 'His'
			WHEN SO.GenderId = 2 Then 'Her' END AS [His-Her],
		CASE WHEN SM.StatusId = 1 Then 'is'
			ELSE 'was' END AS [is-was],
		'[Number],[TCDate],[TransferDate],[SemesterDuration],[ExamName],[ExamSeatNo],[ExamYear],[ExamResult],
		[PromotedClass],[TransferConduct],[OptionalSubject],[Reason],[Remark],
		[FirstName],[MiddleName],[LastName],[FatherName],[MotherName],[Name],[Code],[ClassName],[Divisionname],[DateOfBirth],[DOBInWord],[Kumar-Kumari],[He-She],[His-Her],[is-was]' As ColumnList

	FROM		
		sCertificate.tTransfer T
		INNER JOIN sStudent.vStudentAcademic vSA ON vSA.AcademicId=T.AcademicId
		LEFT JOIN sStudent.tStudentAdmission SA ON SA.StudentId=vSA.StudentId
		INNER JOIN sStudent.tStudentMaster SM ON SM.Id=vSA.StudentId
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=vSA.OrgId
		LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId=vSA.StudentId
		LEFT JOIN sCommon.tReligionMaster RM ON SO.ReligionId=RM.Id
		LEFT JOIN sSetup.tClassMaster CM ON CM.Id=SA.AdmissionStandardId
		INNER JOIN sSetup.tDivisionMaster DM ON vSA.DivisionId = DM.Id
		INNER JOIN sSetup.tClassMaster CMS ON CMS.Id= DM.ClassId
		LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId=vSA.StudentId
		LEFT JOIN sCommon.tCountryMaster CTM ON CTM.Id=SO.NationalityId
		LEFT JOIN sStudent.tAcademicDetail AD ON AD.AcademicId=vSA.AcademicId
		LEFT JOIN sSetup.tOrgImages OI ON OI.OrgId = OM.Id
		LEFT JOIN sCommon.tCastCategoryMaster CSM ON CSM.Id=SO.CastCategoryId
		LEFT JOIN sSetup.tClassGroupMaster CSG ON CSG.Id=CMS.ClassGroupId
		INNER JOIN sSetup.tBatchMaster BM ON BM.Id=vSA.BatchId
		LEFT JOIN sStudent.tStudentAdditional SD ON SD.StudentId=vSA.StudentId
GO
PRINT N'Altering Function [sCertificate].[fBonafideCertificateTemplate]...';


GO

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

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

    RETURN @Template;
END;
GO
PRINT N'Altering Function [sCertificate].[fCharacterCertificateTemplate]...';


GO


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

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

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

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

    RETURN @Template;
END;
GO
PRINT N'Altering Function [sCertificate].[fFirstTrialCertificateTemplate]...';


GO


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

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

    -- Replace placeholders in the template with actual values

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


    RETURN @Template;
END;
GO
PRINT N'Altering Function [sCertificate].[fLeavingCertificateTemplate]...';


GO

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

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

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

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

    RETURN @Template;
END;
GO
PRINT N'Altering Function [sCertificate].[fTransferCertificateTemplate]...';


GO


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

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

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


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

		SET @rId=0 -- Commented above if else block - as Table scope is OrgGroup and here data was accessed by OrgId
	END
	return  @rId 
END
GO
PRINT N'Altering Function [sCommon].[fGetOrgwiseNationalityId]...';


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


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

		--SET @rSql = 'SELECT @rTitle=Title FROM '+@rTableName+' WHERE Id=@rId'
		--EXECUTE sp_executesql @rSql, N'@rId int,@rTitle nvarchar(100) OUTPUT',
		--							@rId=@rId,@rTitle=@rTitle OUTPUT
		
		--SET @rSql = 'SELECT @rId=Id FROM '+@rTableName+' WHERE Title=@rTitle AND OrgId=@rOrgId'
		--EXECUTE sp_executesql @rSql, N'@rTitle nvarchar(100),@rOrgId smallint,@rId int OUTPUT',
		--							@rTitle=@rTitle,@rOrgId=@rOrgId,@rId=@rId OUTPUT
	END
	return  @rId 
      
END
GO
PRINT N'Altering Procedure [sAcademic].[pRptLessonPlanAddGet]...';


GO
ALTER PROCEDURE [sAcademic].[pRptLessonPlanAddGet]

	 
	 @rClassId int,
	 @rSubjectId int,
	 @rDivisionId int,
	 @rIsCompleted bit=0 ,
	 @rBatchId int,
	 @rEmployeeId bigint,
	 @rOrgId smallint ,
	 @rId  bigint,
	 @rStatus int = 0
	
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
	IF(@rStatus = 0)
	BEGIN
	SELECT 
			LP.Id,
			TM.ClassId,
			LP.DivisionId,
			TM.SubjectId,
			LP.TopicId,
			LP.NoOfPeriodRequired,
			LP.Objective,
			LP.IndicativeHomework,
			LP.Summary,
			LP.StartDate,
			LP.EndDate,
			LP.IsCompleted,
			LP.EmployeeId,
			LP.BatchId,
			LP.CreatedUserId,
			LP.CreatedDateTime,
			TM.Title AS TopicName,
			--Mantis - 44459
			--vTSD.ClassTitle+' - '+ vTSD.DivisionTitle AS ClassDivisionName,
			CM.Title + '' + DM.Title AS ClassDivisionName,
			--vTSD.SubjectName,
			SM.Title AS SubjectName,		    
			--Mantis - 44459
			ISNULL(EM.FirstName,'') + ' ' + ISNULL(EM.LastName,'') AS  EmployeeName,
			LP.LearningExperience,
			LP.ToolsAndTechniques,
			LP.EssentialMaterial ,
			LP.AssessmentQuestion ,
			LP.TeacherExample,
			LP.GuidedPractice,
			LP.IndependentPractice,
			
			----lesson plan
			
			
			--- lesson plan fuction
			
		   ISNULL(DFl.IsObjective,0)AS IsObjective,
		   ISNULL(DFl.IsSummary,0)AS IsSummary,
		   ISNULL(DFl.IsLearningExperience,0)AS IsLearningExperience,
		   ISNULL(DFl.IsEssentialMaterial,0)AS IsEssentialMaterial,
		   ISNULL(DFl.IsToolsTechniques,0)AS IsToolsTechniques,
		   ISNULL(DFl.IsIndicativeHomework,0)AS IsIndicativeHomework,
		   ISNULL(DFl.IsAssessmentQuestion,0)AS IsAssessmentQuestion,
		   ISNULL(DFl.IsTeacherExample,0)AS IsTeacherExample,
		   ISNULL(DFl.IsGuidedPractice,0)AS IsGuidedPractice,
		   ISNULL(DFl.IsIndependentPractice,0)AS IsIndependentPractice
		   	
	FROM 
			sAcademic.tLessonPlan LP
			INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id=LP.EmployeeId
			INNER JOIN sAcademic.tTopicMaster TM ON TM.Id=LP.TopicId
			--Mantis - 44459
			--INNER JOIN sAcademic.vTeacherSubjectDivision vTSD ON vTSD.DivisionId = LP.DivisionId  -- Mantis 
			INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = LP.DivisionId
			INNER JOIN sSetup.tClassMaster CM ON CM.Id = DM.ClassId
			INNER JOIN sSetup.tSubjectMaster SM ON SM.Id = TM.SubjectId
			--Mantis - 44459
			LEFT JOIN sConfig.fDisplayFieldLessionGet(@rOrgId) AS DFl ON DFl.OrgId=SM.OrgId
			--AND vTSD.ClassId = TM.ClassId 
			--AND vTSD.SubjectId = TM.SubjectId 
			--AND vTSD.EmployeeId = LP.EmployeeId
	WHERE 
		(LP.BatchId = @rBatchId) 
		AND ((LP.EmployeeId = @rEmployeeId) OR (@rEmployeeId = 0))
		AND ((LP.Id = @rId) OR (@rId = 0))
		AND ((TM.ClassId = @rClassId) OR (@rClassId = 0))
		--AND ((vTSD.DivisionId = @rDivisionId) OR (@rDivisionId = 0))	--Mantis - 44459
		AND((LP.DivisionId = @rDivisionId) OR (@rDivisionId = 0)) --Mantis - 44459(vTSD.DivisionId to LP.DivisionId)	
		AND ((TM.SubjectId = @rSubjectId) OR (@rSubjectId = 0))
		AND ((LP.IsCompleted='False') OR (LP.IsCompleted=@rIsCompleted))
		AND((DFl.OrgId=@rOrgId) OR (@rOrgId = 0))
		AND  ISNULL(EM.IsOtherUser,0) = 0
	END
	ELSE
	BEGIN
	SELECT 
			LP.Id,
			TM.ClassId,
			LP.DivisionId,
			TM.SubjectId,
			LP.TopicId,
			LP.NoOfPeriodRequired,
			LP.Objective,
			LP.IndicativeHomework,
			LP.Summary,
			LP.StartDate,
			LP.EndDate,
			LP.IsCompleted,
			LP.EmployeeId,
			LP.BatchId,
			LP.CreatedUserId,
			LP.CreatedDateTime,
			TM.Title AS TopicName,
			--Mantis - 44459
			--vTSD.ClassTitle+' - '+ vTSD.DivisionTitle AS ClassDivisionName,
			CM.Title + '' + DM.Title AS ClassDivisionName,
			--vTSD.SubjectName,
			SM.Title AS SubjectName,		    
			--Mantis - 44459
			ISNULL(EM.FirstName,'') + ' ' + ISNULL(EM.LastName,'') AS  EmployeeName,
			LP.LearningExperience,
			LP.ToolsAndTechniques,
			LP.EssentialMaterial ,
			LP.AssessmentQuestion ,
			LP.TeacherExample,
			LP.GuidedPractice,
			LP.IndependentPractice,
			
			----lesson plan
			
			
			--- lesson plan fuction
			
		   ISNULL(DFl.IsObjective,0)AS IsObjective,
		   ISNULL(DFl.IsSummary,0)AS IsSummary,
		   ISNULL(DFl.IsLearningExperience,0)AS IsLearningExperience,
		   ISNULL(DFl.IsEssentialMaterial,0)AS IsEssentialMaterial,
		   ISNULL(DFl.IsToolsTechniques,0)AS IsToolsTechniques,
		   ISNULL(DFl.IsIndicativeHomework,0)AS IsIndicativeHomework,
		   ISNULL(DFl.IsAssessmentQuestion,0)AS IsAssessmentQuestion,
		   ISNULL(DFl.IsTeacherExample,0)AS IsTeacherExample,
		   ISNULL(DFl.IsGuidedPractice,0)AS IsGuidedPractice,
		   ISNULL(DFl.IsIndependentPractice,0)AS IsIndependentPractice,
		   SM.Title AS SubjectName,
		   CM.Title + '' + DM.Title AS ClassDivisionName
		 
	
	FROM 
			sAcademic.tLessonPlan LP
			INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id=LP.EmployeeId
			INNER JOIN sAcademic.tTopicMaster TM ON TM.Id=LP.TopicId
			--Mantis - 44459
			--INNER JOIN sAcademic.vTeacherSubjectDivision vTSD ON vTSD.DivisionId = LP.DivisionId  -- Mantis 
			INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = LP.DivisionId
			INNER JOIN sSetup.tClassMaster CM ON CM.Id = DM.ClassId
			INNER JOIN sSetup.tSubjectMaster SM ON SM.Id = TM.SubjectId
			--Mantis - 44459
			LEFT JOIN sConfig.fDisplayFieldLessionGet(@rOrgId) AS DFl ON DFl.OrgId=SM.OrgId  
			--AND vTSD.ClassId = TM.ClassId 
			--AND vTSD.SubjectId = TM.SubjectId 
			--AND vTSD.EmployeeId = LP.EmployeeId
			

	WHERE 
		(LP.BatchId = @rBatchId) 
		AND ((LP.EmployeeId = @rEmployeeId) OR (@rEmployeeId = 0))
		AND ((LP.Id = @rId) OR (@rId = 0))
		AND ((TM.ClassId = @rClassId) OR (@rClassId = 0))
		--AND ((vTSD.DivisionId = @rDivisionId) OR (@rDivisionId = 0))	--Mantis - 44459
		AND((LP.DivisionId = @rDivisionId) OR (@rDivisionId = 0))	--Mantis - 44459(vTSD.DivisionId to LP.DivisionId)
		AND ((TM.SubjectId = @rSubjectId) OR (@rSubjectId = 0))
		AND ((@rStatus = 2) OR (LP.IsCompleted=@rIsCompleted))
		AND((DFl.OrgId=@rOrgId) OR (@rOrgId = 0))
		AND  ISNULL(EM.IsOtherUser,0) = 0
	END
		
		
END
GO
PRINT N'Altering Procedure [sAdmission].[pRptAdmissionBlankFormGet]...';


GO

ALTER PROCEDURE [sAdmission].[pRptAdmissionBlankFormGet]
	@rClassId int = 0,
	@rBatchId int = 0

AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;

   select 
	 ISNULL(AC.ClassId,0) AS ClassId,
	 ISNULL(AC.IsFixParentAcademic,0) AS IsParentAcademicRequired ,
	 ISNULL (AC.IsStudentAcademicRequired,0) AS IsStudentAcademicRequired ,
	 ISNULL(AC.IsSiblingDetailRequired,0) AS IsSiblingDetailRequired,
	 ISNULL(AC.IsReferenceDetailRequired,0) AS IsReferenceDetailRequired ,
	 ISNULL(AC.IsFamilyDetailRequired,0) AS IsFamilyDetailRequired ,
	 ISNULL(AC.IsFixStudentAcademic,0) AS IsFixStudentAcademic,
	 ISNULL(AC.ConfirmationRemark,'') AS ConfirmationRemark,
	 ISNULL(AC.IsHostelDetailRequired,0) AS IsHostelDetailRequired ,
	 ISNULL (AC.IsTransportDetailRequired,0) AS IsTransportDetailRequired ,
	 ISNULL(AC.IsHealthDetailRequired,0) AS IsHealthDetailRequired,
	 ISNULL(AC.IsBirthPlaceDetailRequired,0) AS IsBirthPlaceDetailRequired ,
	 ISNULL(AC.IsAadhaarDetailRequired,0) AS IsAadhaarDetailRequired ,
	 ISNULL(AC.IsBloodGroupDetailRequired,0) AS IsBloodGroupDetailRequired,
	 ISNULL(AC.CustomField1Remark,'') AS CustomField1Remark,
	 ISNULL(AC.CustomField2Remark,'') AS CustomField2Remark,
	 ISNULL(AC.CustomField3Remark,'') AS CustomField3Remark,
	 ISNULL(AC.AgeCutOffDate,'') AS AgeCutOffDate,
	 ISNULL(AC.Remark1,'') AS ExtraRemark1,
	 ISNULL(AC.Remark2,'') AS ExtraRemark2,
	 ISNULL(AC.Remark3,'') AS ExtraRemark3,
	 ISNULL(AC.IsFatherDetail,0) AS IsFatherDetail,
	 ISNULL(AC.IsFatherFullDetail,0) AS IsFatherFullDetail,
	 ISNULL (AC.IsFatherAcademic,0) As IsFatherAcademic,
	 ISNULL (AC.IsMotherDetail,0) As IsMotherDetail,
	 ISNULL (AC.IsMotherFullDetail,0)As IsMotherFullDetail,
	 ISNULL (AC.IsMotherAcademic,0)As IsMotherAcademic,
	 ISNULL (AC.IsGuardianDetail,0)As IsGuardianDetail,
	 ISNULL (AC.IsGuardianFullDetail,0)As IsGuardianFullDetail,
	 ISNULL (AC.IsGuardianAcademic,0)As IsGuardianAcademic,
	 ISNULL (AC.IsOtherInformationRequired,0)As IsOtherInformationRequired,
	 ISNULL (AC.IsHealthDetailRequired,0) As IsHealthDetailRequired,
	 ISNULL (AC.IsCustomField1Required,0) As IsCustomField1Required,
	 ISNULL (AC.IsCustomField2Required,0) As IsCustomField2Required,
	 ISNULL (AC.IsCustomField3Required,0) As IsCustomField3Required,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](302,OM.Id) AS IsBirthPlace,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](303,OM.Id) AS IsBirthTaluka,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](304,OM.Id) AS IsBirthDistrict,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](305,OM.Id) AS IsBirthState,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](306,OM.Id) AS IsBirthCountry,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](307,OM.Id) AS IsPreviousSchool,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](308,OM.Id) AS IsStudentPhoto,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](316,OM.Id) AS IsContactEmail,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](317,OM.Id) AS IsReligion,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](318,OM.Id) AS IsFamilyCaste,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](319,OM.Id) AS IsNationality,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](320,OM.Id) AS IsCasteCategory,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](388,OM.Id) AS IsFamilySubCaste,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](321,OM.Id) AS IsMotherTongue,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](322,OM.Id) AS IsAadhaarNo,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](323,OM.Id) AS IsOtherInformation,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](324,OM.Id) AS IsLiveWith,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](325,OM.Id) AS IsHotelRequired,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](326,OM.Id) AS IsTransportRequired,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](327,OM.Id) AS IsMotherFullName,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](328,OM.Id) AS IsMotherMobilNo,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](329,OM.Id) AS IsMotherQualification,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](330,OM.Id) AS IsMotherOccupation,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](331,OM.Id) AS IsMotherEmail,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](332,OM.Id) AS IsMotherIncome,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](333,OM.Id) AS IsMotherOrganization,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](334,OM.Id) AS IsMotherDesignation,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](337,OM.Id) AS IsMotherOfficeAddress,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](338,OM.Id) AS IsMotherPhoto,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](410,OM.Id) AS IsMotherAadhaarNo,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](349,OM.Id) AS IsFatherFullName,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](350,OM.Id) AS IsFatherMobileNo,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](351,OM.Id) AS IsFatherQualification,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](352,OM.Id) AS IsFatherOccupation,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](353,OM.Id) AS IsFatherEmail,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](354,OM.Id) AS IsFatherIncome,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](355,OM.Id) AS IsFatherOrganization,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](356,OM.Id) AS IsFatherDesignation,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](359,OM.Id) AS IsFatherOfficeAddress,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](360,OM.Id) AS IsFatherPhoto,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](409,OM.Id) AS IsFatherAadhaarNo,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](361,OM.Id) AS IsGuardianFullName,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](362,OM.Id) AS IsGuardianMobileNo,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](363,OM.Id) AS IsGuardianPhoto,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](396,OM.Id) AS IsGuardianQualification,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](397,OM.Id) AS IsGuardianOccupation,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](398,OM.Id) AS IsGuardianEmail,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](399,OM.Id) AS IsGuardianIncome,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](400,OM.Id) AS IsGuardianOrganization,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](401,OM.Id) AS IsGuardianDesignation,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](403,OM.Id) AS IsGuardianRelationship,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](405,OM.Id) AS IsGuardianOfficeAddress,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](411,OM.Id) AS IsGuardianAadhaarNo,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](369,OM.Id) AS IsPhysicalDeformity,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](370,OM.Id) AS IsPhysicalDeformityRemark,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](371,OM.Id) AS IsMajorIllness,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](372,OM.Id) AS IsMajorIllnessRemark,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](373,OM.Id) AS IsAllergy,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](374,OM.Id) AS IsAllergyRemark,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](407,OM.Id) AS IsMeritMarks,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](408,OM.Id) AS IsMeritGrade,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](395,OM.Id) AS IsBloodGroup,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](309,OM.Id) AS IsStreetOneAddress
	 ,[sAdmission].[fAdmissionFormDisplayFieldGet](1233,OM.Id) AS IsPENNumber --mantis : 0043425
	 ,[sAdmission].[fAdmissionFormDisplayFieldGet](1234,OM.Id) AS IsApaarIdNumber--mantis : 0043425
	FROM  
		    sAdmission.tAdmissionCriteria AC 
		    INNER JOIN sSetup.tClassMaster CM ON CM.Id=AC.ClassId
			INNER JOIN sSetup.tBatchMaster BM  ON  BM.Id=AC.BatchId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=BM.OrgId
	WHERE 	
	((AC.ClassId = @rClassId) OR (@rClassId = 0))	
	AND ((AC.BatchId = @rBatchId) OR (@rBatchId = 0))
END
GO
PRINT N'Altering Procedure [sAlert].[pSMSViewGet]...';


GO
ALTER PROCEDURE [sAlert].[pSMSViewGet]
	@rMobileNumber nvarchar(50),
	@rEmail nvarchar(50),
	@rOrgId int,
	@rIsFlag bit = 0,
	@rAlertModeId tinyint = 0,
	@rReceiverSourceId bigint = 0 --Mantis: 0044870
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
declare  @lAlertgrid NVARCHAR(max)=''
BEGIN

IF(@rIsFlag = 0)
BEGIN
	select AL.SourceEvent,EM.Title,AL.AlertSubject,[sCommon].[fXMLTagsReplace](AL.AlertMessage) as AlertMessage,AL.CreatedDateTime
	Into #tempAlertLogStudent360
	FROM
			sAlert.tAlertLog AL
			INNER JOIN sAlert.tEventMaster EM ON EM.Id=AL.EventId
	WHERE  ((AL.ContactId = @rMobileNumber) OR (AL.ContactId = @rEmail))
		And AL.OrgId=@rOrgId	
		AND (AL.AlertModeId = @rAlertModeId OR @rAlertModeId = 0)
		AND AL.ReceiverSourceId = @rReceiverSourceId
	ORDER BY AL.CreatedDateTime DESC	
	SELECT  @lAlertgrid = @lAlertgrid + '<tr>
	<td align="left" scope="col">' + isnull(SourceEvent,'') + '</td>
	<td align="left" scope="col">' + isnull(Title,'') + '</td>
	<td align="left" scope="col">' +  isnull(AlertSubject,'') + '</td>
	<td align="left" scope="col">' +  isnull(AlertMessage,'') + '</td>
	<td align="left" scope="col">' + Convert(varchar,isnull(CreatedDateTime,''),120) + '</td>
	</tr>'	
	FROM #tempAlertLogStudent360

	DROP TABLE #tempAlertLogStudent360
END
ELSE
BEGIN
	select AL.SourceEvent,EM.Title,AL.AlertSubject,[sCommon].[fXMLTagsReplace](AL.AlertMessage) as AlertMessage,AL.CreatedDateTime
	Into #tempAlertLogStudentDetailForm
	FROM
			sAlert.tAlertLog AL
			INNER JOIN sAlert.tEventMaster EM ON EM.Id=AL.EventId
	WHERE  ((AL.ContactId = @rMobileNumber) OR (AL.ContactId = @rEmail))
		And AL.OrgId=@rOrgId	
		AND CAST(CreatedDateTime AS DATE) = CAST(sCommon.fGetDate() AS DATE)
		AND (AL.AlertModeId = @rAlertModeId OR @rAlertModeId = 0)
		AND AL.ReceiverSourceId = @rReceiverSourceId
	ORDER BY AL.CreatedDateTime DESC

	SELECT  @lAlertgrid = @lAlertgrid + '<tr>
	<td align="left" scope="col">' + isnull(SourceEvent,'') + '</td>
	<td align="left" scope="col">' + isnull(Title,'') + '</td>
	<td align="left" scope="col">' +  isnull(AlertSubject,'') + '</td>
	<td align="left" scope="col">' +  isnull(AlertMessage,'') + '</td>
	<td align="left" scope="col">' + Convert(varchar,isnull(CreatedDateTime,''),120) + '</td>
	</tr>'	
	FROM #tempAlertLogStudentDetailForm

	DROP TABLE #tempAlertLogStudentDetailForm
END
    	
END
 SELECT ISNULL(@lAlertgrid,'') AS Alertgrid
GO
PRINT N'Altering Procedure [sAssessment].[pRptResultSheetNCRTExamGet]...';


GO
 
ALTER PROCEDURE [sAssessment].[pRptResultSheetNCRTExamGet]
	 
	 @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,
	 @rFromPercentage decimal(5,2)=0,
	 @rToPercentage decimal(5,2)=0,
	 @rIsDetail bit=0,
	 @rIsShowWithDetail bit=0
	 --,@rcolumn_visible bit
	 
	

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
 begin
 

  --select * from sAssessment.tTempAllExam
-- --drop table sAssessment.tTempAllExam

 Declare @lLinkExamId int
 Select @lLinkExamId = LinkExamId From sAssessment.tExamMaster Where ClassId=@rClassID AND Id=@rExamId ANd BatchId=@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 = @lLinkExamId
SELECT @GradeString = [sAssessment].[fGradeStringGet](@GradeSetId)

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

 

--#TempAllExam
	CREATE TABLE #TempAllExam
	(
		AcademicIdText nvarchar(20),
		ExamIdText nvarchar(20),
		CoScholasticScopeIdText nvarchar(20),
		IsDisplayMonthlyAttendanceText nvarchar(20),
		ClassIdText nvarchar(50),
		
		AcademicId bigint,
		ExamName Nvarchar(150),
		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(8,2),
		RankNumber int,
		ResultGrade NVarchar(50),
		
		MaximumMark1 decimal(8,2),		
		SubjectGrade1 NVarchar(50),
		Obtain1 decimal(8,2),
		ExamMaximum1 decimal(8,2),
		IsPresent1 bit,
						
		MaximumMark2 decimal(8,2),	
		SubjectGrade2 NVarchar(50),
		Obtain2 decimal(8,2),
		ExamMaximum2 decimal(8,2),
		IsPresent2 bit,
				
		MaximumMark3 decimal(8,2),
		SubjectGrade3 NVarchar(50),
		Obtain3 decimal(8,2),
		ExamMaximum3 decimal(8,2),
		IsPresent3 bit,		
		
		MaximumMark4 decimal(8,2),	
		SubjectGrade4 NVarchar(50),
		Obtain4 decimal(8,2),
		ExamMaximum4 decimal(8,2),
		IsPresent4 bit,	
				
		MaximumMark5 decimal(8,2),		
		SubjectGrade5 NVarchar(50),
		Obtain5 decimal(8,2),
		ExamMaximum5 decimal(8,2),
		IsPresent5 bit,	
				
		MaximumMark6 decimal(8,2),		
		SubjectGrade6 NVarchar(50),
		Obtain6 decimal(8,2),
		ExamMaximum6 decimal(8,2),
		IsPresent6 bit,	
		
		MaximumMark7 decimal(8,2),		
		SubjectGrade7 NVarchar(50),
		Obtain7 decimal(8,2),
		ExamMaximum7 decimal(8,2),
		IsPresent7 bit,	
		
		MaximumMark8 decimal(8,2),	
		SubjectGrade8 NVarchar(50),
		Obtain8 decimal(8,2),
		ExamMaximum8 decimal(8,2),
		IsPresent8 bit,	
		
		MaximumMark9 decimal(8,2),		
		SubjectGrade9 NVarchar(50),
		Obtain9 decimal(8,2),
		ExamMaximum9 decimal(8,2),
		IsPresent9 bit,	
		
		
		MaximumMark10 decimal(8,2),		
		SubjectGrade10 NVarchar(50),
		Obtain10 decimal(8,2),
		ExamMaximum10 decimal(8,2),
		IsPresent10 bit,	
		
			MaximumMark11 decimal(8,2),		
		SubjectGrade11 NVarchar(50),
		Obtain11 decimal(8,2),
		ExamMaximum11 decimal(8,2),
		IsPresent11 bit,
		
		MaximumMark12 decimal(8,2),		
		SubjectGrade12 NVarchar(50),
		Obtain12 decimal(8,2),
		ExamMaximum12 decimal(8,2),
		IsPresent12 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(100),
		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(8,2),
		RankNumberTerm1 int,
		ResultGradeTerm1 NVarchar(50),
		PercentileTerm1 decimal(8,2),
		ResultStatusTerm1 Nvarchar(20),		   
		TotalMarkTerm2 decimal(8,2),
		TotalObtainTerm2 decimal(8,2),
		PercentageTerm2 decimal(8,2),
		RankNumberTerm2 int,
		ResultGradeTerm2 NVarchar(50),
		PercentileTerm2 decimal(8,2),
		ResultStatusTerm2 Nvarchar(20), 
		TotalMarkTerm3 		decimal(8,2),
		TotalObtainTerm3 decimal(8,2),
		PercentageTerm3 decimal(8,2),
		RankNumberTerm3 int,
		ResultGradeTerm3 NVarchar(50),
		PercentileTerm3 decimal(8,2),
		ResultStatusTerm3 Nvarchar(20), 
		
		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(50),
		SubjectName NVarchar(150),
		SubjectCode Nvarchar(50),	
		SubjectMinimum decimal(8,2),		
		SubjectMaximum decimal(8,2),
		SubjectObtain  decimal(8,2),
		
		Exam1Name Nvarchar(150),		
		TotalMarks1 decimal(8,2),		
		TotalObtain1 decimal(8,2),
		Percentage1 decimal(8,2),
		RankNumber1 int,
		ResultGrade1 NVarchar(50),
		Percentile1 decimal(8,2),
		ResultStatus1 Nvarchar(20),
		
		Exam2Name nvarchar(150),	
		TotalMarks2 decimal(8,2),
		TotalObtain2 decimal(8,2),
		Percentage2 decimal(8,2),
		RankNumber2 int,
		ResultGrade2 NVarchar(50),
		Percentile2 decimal(8,2),
		ResultStatus2 Nvarchar(20),
		
		Exam3Name nvarchar(150),	
		TotalMarks3 decimal(8,2),
		TotalObtain3 decimal(8,2),
		Percentage3 decimal(8,2),
		RankNumber3 int,
		ResultGrade3 NVarchar(50),
		Percentile3 decimal(8,2),		
		ResultStatus3 Nvarchar(20),
		
		Exam4Name nvarchar(150),	
		TotalMarks4 decimal(8,2),
		TotalObtain4 decimal(8,2),
		Percentage4 decimal(8,2),
		RankNumber4 int,
		ResultGrade4 NVarchar(50),
		Percentile4 decimal(8,2),
		ResultStatus4 Nvarchar(20),
		
		Exam5Name nvarchar(150),		
		TotalMarks5 decimal(8,2),
		TotalObtain5 decimal(8,2),
		Percentage5 decimal(8,2),
		RankNumber5 int,
		ResultGrade5 NVarchar(50),
		Percentile5 decimal(8,2),
		ResultStatus5 Nvarchar(20),
		
		Exam6Name nvarchar(150),	
		TotalMarks6 decimal(8,2),
		TotalObtain6 decimal(8,2),
		Percentage6 decimal(8,2),
		RankNumber6 int,
		ResultGrade6 NVarchar(50),
		Percentile6 decimal(8,2),
		ResultStatus6 Nvarchar(20),
		
		Exam7Name nvarchar(150),		
		TotalMarks7 decimal(8,2),
		TotalObtain7 decimal(8,2),
		Percentage7 decimal(8,2),
		RankNumber7 int,
		ResultGrade7 NVarchar(50),
		Percentile7 decimal(8,2),
		ResultStatus7 Nvarchar(20),
		
		Exam8Name nvarchar(150),
		TotalMarks8 decimal(8,2),
		TotalObtain8 decimal(8,2),
		Percentage8 decimal(8,2),
		RankNumber8 int,
		ResultGrade8 NVarchar(50),
		Percentile8 decimal(8,2),
		ResultStatus8 Nvarchar(20),
		
		
		Exam9Name nvarchar(150),	
		TotalMarks9 decimal(8,2),
		TotalObtain9 decimal(8,2),
		Percentage9 decimal(8,2),
		RankNumber9 int,
		ResultGrade9 NVarchar(50),
		Percentile9 decimal(8,2),
		ResultStatus9 Nvarchar(20),
		
		Exam10Name nvarchar(150),	
		TotalMarks10 decimal(8,2),
		TotalObtain10 decimal(8,2),
		Percentage10 decimal(8,2),
		RankNumber10 int,
		ResultGrade10 NVarchar(50),
		Percentile10 decimal(8,2),
		ResultStatus10 Nvarchar(20),
		
		Exam11Name nvarchar(150),	
		TotalMarks11 decimal(8,2),
		TotalObtain11 decimal(8,2),
		Percentage11 decimal(8,2),
		RankNumber11 int,
		ResultGrade11 NVarchar(50),
		Percentile11 decimal(8,2),
		ResultStatus11 Nvarchar(20),
		
		
		Exam12Name nvarchar(150),	
		TotalMarks12 decimal(8,2),
		TotalObtain12 decimal(8,2),
		Percentage12 decimal(8,2),
		RankNumber12 int,
		ResultGrade12 NVarchar(50),
		Percentile12 decimal(8,2),
		ResultStatus12 Nvarchar(20),
		
		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),
		
		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(200),
		VisionLeft nvarchar(50),
		VisionRight nvarchar(50), 
		IsDetail bit,
		SubjectGroupId int,
		SubjectGroupTitle nvarchar(100),
		SubjectGroupCode nvarchar(20),
		DecimalFormat nvarchar(10),
		SubjectRemark nvarchar(1000),
		GraceMark decimal(5,2),
		GradeStringHtml nvarchar(500),
		ResultRemark3 nvarchar(200),
		IsDisplayTotalMark bit,
		SubjectObtainTerm1 decimal(8,2),	
		SubjectObtainTerm2 decimal(8,2),
		SubjectObtainTerm3  decimal(8,2),
		SubjectMaxTerm1 decimal(8,2),
		SubjectMaxTerm2 decimal(8,2),
		SubjectMaxTerm3 decimal(8,2),
		ContactNo nvarchar(20),
		PresentAddress nvarchar(max),
		TeacherSignCaption nvarchar(100),
		PrincipalSignCaption nvarchar(100),
		 ParentSignCaption nvarchar(100),
		 ImprovementArea nvarchar(200),
		 ProgressArea nvarchar(200),
		 GeneralRemark nvarchar(1000),
		 MyActivity nvarchar(2000),
		 ClassTeacherRemark nvarchar(1000),
		 
		HouseRemark nvarchar(1000),
		BloodGroup Nvarchar(100),
		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),
		BatchIdText nvarchar(20),
		IsShowWithDetail bit,
		IsPresent bit,
		GradeTitle nvarchar(50),
		SubjectHighestDivisionGrade nvarchar(50),
		SubjectHighestDivisionMark decimal(5, 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,
	GradeStringHtml,
	ResultRemark3,
	IsDisplayTotalMark,
	ContactNo,
	PresentAddress,
	TeacherSignCaption,
	PrincipalSignCaption,
	ParentSignCaption,
	ImprovementArea,
	ProgressArea,
	GeneralRemark,
	MyActivity,
	ClassTeacherRemark,
	
	HouseRemark,
	BloodGroup,
	BatchIdText,
   IsShowWithDetail,
 IsPresent,
 GradeTitle,
	
	 SubjectHighestDivisionGrade,
	 SubjectHighestDivisionMark
	)
	SELECT 
		Convert(nvarchar(20),A.Id),
		Convert(nvarchar(20),@lLinkExamId),
		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,
		@lLinkExamId,
		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,
		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,
		@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),
		@rIsShowWithDetail AS IsShowWithDetail,
		IsPresent,
		GradeTitle ,
		RAD.SubjectHighestDivisionGrade,
		RAD.SubjectHighestDivisionMark 
FROM 
	sAssessment.tResultDetail RD
	INNER JOIN sAssessment.tResult R ON R.Id = RD.ResultId
	INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId
	INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId		
	INNER JOIN 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.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
	INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id = EM.EXAMSUBGROUPID
	LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId=StuM.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 sAcademic.tTeacherSubjectDivision TSD ON TSD.SubjectId=SM.Id AND TSD.DivisionId = A.DivisionId
	--LEFT JOIN sHrm.tEmployeeMaster EMP ON TSD.EmployeeId = EMP.Id
	
	 WHERE
		R.ExamId = @lLinkExamId 
		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.Percentage>=@rFromPercentage) OR (@rFromPercentage=0))
		AND ((R.Percentage<=@rToPercentage) OR (@rToPercentage=0))
		 AND  ISNULL(EMP.IsOtherUser,0) = 0
	 
	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  = @lLinkExamId 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  = @lLinkExamId) E
	ON C.ExamId = E.SubExamId
	ORDER BY E.ExamOrder,C.ExamOrder
	END
	--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)+'=RD.Obtain,
					 IsPresent' + convert(nvarchar(15),@lCount)+'=RD.IsPresent,	
					 				
					 SubjectGrade' + convert(nvarchar(15),@lCount)+ '=RD.SubjectGrade,
					  TotalDays'+convert(nvarchar(15),@lCount)+'=SR.TotalDays,
					 PresentDays'+convert(nvarchar(15),@lCount)+'=SR.PresentDays										
					 From
						sAssessment.tResultDetail RD
						INNER JOIN sAssessment.tResult R ON R.Id = RD.ResultId
						INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
						INNER JOIN sAssessment.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)  
						
	
	 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.Title,
					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)
		
		
	set @lCount = @lCount -1
	end
	

	IF (@IsIncludeSubExam = 1)
	BEGIN	
		select @lSubExamId = SubExamId from sAssessment.tExamCombine  Where ExamId  = @lLinkExamId 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
						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					 
					 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  = @lLinkExamId 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				 
					 From
						sAssessment.tResultDetail RD
						INNER JOIN sAssessment.tResult R ON R.Id = RD.ResultId
						INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
						INNER JOIN sAssessment.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			
					 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  = @lLinkExamId 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
						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			
					 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
		
	drop table #tempcombineExam
	Drop table #TempAllExam
	END

  --end
GO
PRINT N'Altering Procedure [sAttendance].[pRptMonthlyAttendanceStudentwise]...';


GO
ALTER PROCEDURE [sAttendance].[pRptMonthlyAttendanceStudentwise]

	@rBuilder1 nvarchar(max)='',
	@rBuilder2 nvarchar(max)='', 
	@rDepartmentId int,
	@rClassId int,
	@rDivisionId int,
	@rAttendanceTagId int,
	--@rFromDate date,
	@rUpToDate date,
	@rBatchId int,
	@rOrgId int	 ,
	@rAdmissionCategoryId int,
	@rAttendanceTypeId int = 0,
	@rStatus int = 0	--mantis: 44417
	 	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	--mantis: 44417, start
	DECLARE @lOrgGroupId int=0, @lIDNoLabel nvarchar(500)='Id No'
	SELECT @lOrgGroupId=OrgGroupId FROM sSetup.tOrganizationMaster WHERE Id=@rOrgId
	SELECT @lIDNoLabel=ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId=236 AND SourceTypeId=2010 AND SourceId=@lOrgGroupId
	--mantis: 44417, end

	DECLARE @lAttendanceDate nvarchar(MAX)
	SELECT 
		@rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,
		
		SA.AcademicId,
		ISNULL(SA.RollNo,0) as RollNo,
		SA.Name,
		SA.Code,
		CM.ID AS ClassId,
		CM.Title AS Class,
		CM.OrderIndex AS ClassOrderIndex,
		DM.Id AS DivisionId,
		DM.Title AS Division,
		DM.OrderIndex AS DivisionOrderIndex,

		DEM.Id As DepartmentId,
		DEM.Title AS DepartmentName ,
		DEM.OrderIndex As DepartmentOrderIndex ,

		SA.ClassName + '-'+ SA.DivisionName AS ClassDivision,
		ISNULL(AR.AttendanceTagCount,0) AS AttendanceTagCount,

		ISNULL((SELECT COUNT(SR.AcademicId)
						FROM sStudent.vStudentAcademic SA1 
							INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=SA1.AcademicId And SR.AcademicId=SA.AcademicId
							INNER JOIN sSetup.tClassMaster CM ON CM.Id = SA.ClassId	 
							 AND SR.AttendanceDate <= @rUpToDate WHERE SR.IsPresent=1 AND ((SA.OrgId=@rOrgId)OR(@rOrgId=0))
							 AND ((CM.Id =@rClassId)OR(@rClassId=0))
							 AND (SR.AttendanceTypeId =  @rAttendanceTypeId OR @rAttendanceTypeId = 0)
							AND((CM.DepartmentId = @rDepartmentId)OR(@rDepartmentId=0))),0) AS TotalPresentDays ,
		ISNULL((SELECT COUNT(SR.AcademicId)
						FROM sStudent.vStudentAcademic SA1 
							INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=SA1.AcademicId And SR.AcademicId=SA.AcademicId
							INNER JOIN sSetup.tClassMaster CM ON CM.Id = SA.ClassId	 
							 AND SR.AttendanceDate <= @rUpToDate WHERE ((SA.OrgId=@rOrgId)OR(@rOrgId=0))
							 AND ((CM.Id =@rClassId)OR(@rClassId=0))
							 AND (SR.AttendanceTypeId =  @rAttendanceTypeId OR @rAttendanceTypeId = 0)
							AND((CM.DepartmentId = @rDepartmentId)OR(@rDepartmentId=0))),0) AS TotalWorkingDays ,				
       -- ISNULL(MS.WorkingDays,0) As TotalWorkingDays ,

		STUFF(
         (SELECT DISTINCT  ', ' + CONVERT(NVARCHAR(MAX),SR.AttendanceDate,105)
           FROM
				sStudent.vStudentAcademic A INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.AcademicId  
			WHERE 
				 A.AcademicId = SA.AcademicId
				--AND (SR.AttendanceDate >= @rFromDate  AND SR.AttendanceDate <= @rToDate)
				AND (SR.AttendanceDate <= @rUpToDate)
				--AND SR.AttendanceTagId>0
				AND (SR.AttendanceTypeId =  @rAttendanceTypeId OR @rAttendanceTypeId = 0)
				AND ((SR.AttendanceTagId =@rAttendanceTagId) OR (@rAttendanceTagId=0))
				AND ((SA.AdmissionCategoryId =@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
			GROUP BY SR.AcademicId,AttendanceDate
          FOR XML PATH (''))
          , 1, 1, '')  AS UptoDate,

		  SA.Suid AS SUID,	--mantis: 44417
		  @lIDNoLabel AS IDLabel --mantis: 44417
		 
	FROM 
		sStudent.vStudentAcademic SA 
		INNER JOIN sStudent.tStudentAdmission AD ON SA.StudentId = AD.StudentId
		INNER JOIN sSetup.tClassMaster CM ON CM.Id = SA.ClassId
		INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = SA.DivisionId
		INNER JOIN sSetup.tDepartmentMaster DEM on DEM.Id = CM.DepartmentId
		
		--Inner JOIN sAttendance.tMonthlySetup MS on MS.ClassId = SA.ClassId And MS.BatchId = SA.BatchId
		--INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=SA.AcademicId
		       
		LEFT JOIN
		(
			SELECT 
				SR.AcademicId,COUNT(SR.AttendanceTagId) AS AttendanceTagCount 
			FROM 
				sStudent.vStudentAcademic A
				INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.AcademicId 
				INNER JOIN sStudent.tStudentAdmission SA  ON SA.StudentId = A.StudentId
			WHERE 
				((A.ClassId=@rClassId) OR (@rClassId=0))
				AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId=0))
				AND ((A.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
				AND (A.OrgId = @rOrgId)
				AND (A.BatchId = @rBatchID)
				--AND (SR.AttendanceDate >= @rFromDate  AND SR.AttendanceDate <= @rToDate)
				AND (SR.AttendanceDate <= @rUpToDate)
				AND A.StatusId=1
				--AND SR.AttendanceTagId>0
				AND ((SR.AttendanceTagId =@rAttendanceTagId) OR (@rAttendanceTagId=0))
				AND ((A.AdmissionCategoryId =@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
			GROUP BY SR.AcademicId
		) AR ON AR.AcademicId = SA.AcademicId
		
	WHERE 
		(SA.OrgId = @rOrgId)
		AND (SA.BatchId = @rBatchId)
		AND ((SA.ClassId=@rClassId) OR (@rClassId=0))
		AND ((SA.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		AND ((CM.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
		AND ((SA.AdmissionCategoryId =@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
		--AND (AD.LeftDate > @rFromDate OR ISNULL(AD.LeftDate,'')= '')
		--AND (AD.AdmissionDate <= @rFromDate)
		AND ((SA.StatusId = @rStatus) OR (@rStatus = 0))	--mantis: 44417
END
GO
PRINT N'Altering Procedure [sAttendance].[pStudentSetupGet]...';


GO
ALTER PROCEDURE [sAttendance].[pStudentSetupGet]
	 	 @rBatchId int,
	 	 @rAcademicId bigint
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	Select 
		MY.MonthTitle AS ForMonthInWord,
		MY.MonthNumber AS ForMonth, 
		MY.YearNumber AS ForYear,		
		CASE WHEN SS.WorkingDays IS NOT NULL THEN
		ISNULL(SS.WorkingDays,0)
		ELSE ISNULL(MS.WorkingDays,0) END AS WorkingDays
	From 
	
	sSetup.fMonthYearForBatchGET(@rBatchId) AS MY
	INNER JOIN sStudent.vStudentAcademic SA ON SA.BatchId=MY.BatchId AND SA.AcademicId=@rAcademicId
	LEFT JOIN sAttendance.tMonthlySetup MS ON MS.ClassId=SA.ClassId
	AND MS.ForMonth = MY.MonthNumber AND MS.ForYear = MY.YearNumber and MS.BatchId=@rBatchId --Add a BatchId condition to handle duplicate data by Sahjanand.
	--LEFT JOIN 
	--(
	--SELECT A.batchId, ss.*
	--FROM sAttendance.tStudentSetup SS INNER JOIN sStudent.tAcademic A ON SS.academicId = a.Id AND A.Id = @rAcademicId
	
	--) AS BI
	--ON MY.BatchId = BI.BatchId AND MY.MonthNumber = BI.ForMonth AND MY.YearNumber = BI.ForYear 
	
	LEFT JOIN sAttendance.tStudentSetup SS ON SS.AcademicId=SA.AcademicId AND (SS.AcademicId=@rAcademicId)
	AND SS.ForMonth = MY.MonthNumber AND SS.ForYear = MY.YearNumber
	
	WHERE
		(MY.BatchId=@rBatchId)
END
GO
PRINT N'Altering Procedure [sBiometric].[pCloudTransactionDataAdd]...';


GO
ALTER PROCEDURE [sBiometric].[pCloudTransactionDataAdd]
	@rXmlDoc nvarchar(max) = ''

	AS
	SET NOCOUNT ON

BEGIN
	SET @rXmlDoc=REPLACE(@rXmlDoc,'&','AND')
	DECLARE @lInterrorCode INT,
			@intDoc INT

	DECLARE @exceptiondetail NVARCHAR(MAX)

	BEGIN TRY
    BEGIN TRANSACTION;
		EXECUTE @lInterrorCode = sp_xml_preparedocument @intDoc OUTPUT, @rXmlDoc

		CREATE TABLE #tTable(
		TransactionId bigint NOT NULL,
		[PunchId] [nvarchar](50) NOT NULL,
		TransactionDateTime [datetime] NOT NULL,
		[DeviceIP] [nvarchar](20) NOT NULL,
		[Mode] [nvarchar](10) NOT NULL,
		[CreatedDateTime] [datetime] NOT NULL
		)
		INSERT INTO #tTable
		SELECT
			A.TransactionId,
			A.PunchId,
			A.TransactionDateTime,
			A.DeviceIP,
			A.Mode,
			sCommon.fGetDate()
		FROM OPENXML (@intDoc, '/Table/CloudTransactionData', 1)
		WITH
		(
			TransactionId bigint '@TransactionId',
			PunchId nvarchar(50) '@PunchId',
			TransactionDateTime datetime '@TransactionDateTime',
			DeviceIP nvarchar(20) '@DeviceIP',
			Mode nvarchar(10) '@Mode'
		) A

		INSERT INTO sBiometric.tCloudTransactionRawData WITH (rowlock)
		SELECT
			A.TransactionId,
			A.PunchId,
			A.TransactionDateTime,
			A.DeviceIP,
			A.Mode,
			A.CreatedDateTime
		From #tTable A
		Where NOT EXISTS
			(SELECT 1 FROM  sBiometric.tCloudTransactionRawData CRD WITH (NOLOCK) where  A.TransactionDateTime=CRD.TransactionDateTime AND A.PunchId=CRD.PunchId AND A.DeviceIP=CRD.DeviceIP)

		INSERT INTO [sBiometric].[tCloudTransactionData] with (rowlock)
	--Employee
		SELECT
			EM.Id,
			CRD.TransactionDateTime,
			CASE WHEN (SELECT 1 FROM sBiometric.tShiftAllocationCloud WITH (NOLOCK) WHERE (ShiftDay = DATEPART(WEEKDAY, CRD.TransactionDateTime - 1) OR cast(CRD.TransactionDateTime as Date) BETWEEN FromShiftDate AND ToShiftDate) AND SourceId = EM.Id AND SourceTypeId = 95) IS NOT NULL THEN 
			(SELECT top 1 ShiftCode FROM sBiometric.tShiftAllocationCloud WITH (NOLOCK) WHERE (ShiftDay = DATEPART(WEEKDAY, CRD.TransactionDateTime - 1) OR cast(CRD.TransactionDateTime as Date) BETWEEN FromShiftDate AND ToShiftDate) AND SourceId = EM.Id AND SourceTypeId = 95 order by fromShiftDate desc)
			ELSE EM.ShiftId END AS ShiftCode,
			CONVERT(DATE,CRD.TransactionDateTime) AS Attn_Dt,
			CASE WHEN (SELECT TOP 1 ISNULL(Mode,'IN') FROM [sBiometric].[tCloudTransactionData] WITH (NOLOCK) WHERE SourceId = EM.Id AND Attn_Dt = CONVERT(DATE,CRD.TransactionDateTime) ORDER BY In_Out_Time DESC) = 'IN' THEN 'OUT' ELSE 'IN' END AS Mode,
			sCommon.fGetDate(),
			CRD.DeviceIP,
			0,
			CRD.PunchId,
			CRD.TransactionId,
			95,
			0
		FROM
			sBiometric.tCloudTransactionRawData CRD WITH (NOLOCK)
			INNER JOIN sHrm.tEmployeeMaster EM WITH (NOLOCK) ON EM.PunchId = CRD.PunchId
		WHERE
			--mantis: 44582, comment the below condition and add new condition next to it
			--CRD.TransactionId NOT IN (SELECT TransactionId FROM sBiometric.tCloudTransactionData WITH (NOLOCK))
			CRD.TransactionId NOT IN (SELECT TransactionId FROM sBiometric.tCloudTransactionData WITH (NOLOCK) WHERE DeviceIP=CRD.DeviceIP)

		UNION ALL

		--Student
		SELECT
			AC.Id,		--Mantis: 34829, change SM.Id => AC.Id by dhruvik
			CRD.TransactionDateTime,
			CASE WHEN (SELECT 1 FROM sBiometric.tShiftAllocationCloud WITH (NOLOCK) WHERE (ShiftDay = DATEPART(WEEKDAY, CRD.TransactionDateTime - 1) OR cast(CRD.TransactionDateTime as Date) BETWEEN FromShiftDate AND ToShiftDate) AND SourceId = SM.Id AND SourceTypeId = 2003) IS NOT NULL THEN 
			(SELECT top 1 ShiftCode FROM sBiometric.tShiftAllocationCloud WITH (NOLOCK) WHERE (ShiftDay = DATEPART(WEEKDAY, CRD.TransactionDateTime - 1) OR cast(CRD.TransactionDateTime as Date) BETWEEN FromShiftDate AND ToShiftDate) AND SourceId = SM.Id AND SourceTypeId = 2003 order by fromShiftDate desc)
			ELSE SM.ShiftId END AS ShiftCode,
			CONVERT(DATE,CRD.TransactionDateTime) AS Attn_Dt,
			CASE WHEN (SELECT TOP 1 ISNULL(Mode,'IN') FROM [sBiometric].[tCloudTransactionData] WITH (NOLOCK) WHERE SourceId = AC.Id AND Attn_Dt = CONVERT(DATE,CRD.TransactionDateTime) ORDER BY In_Out_Time DESC) = 'IN' THEN 'OUT' ELSE 'IN' END AS Mode,		--Mantis: 34829, change SM.Id => AC.Id by dhruvik
			sCommon.fGetDate(),
			CRD.DeviceIP,
			0,
			CRD.PunchId,
			CRD.TransactionId,
			2001,		--Mantis: 34829, change 2003 => 2001 by dhruvik
			0
		FROM
			sBiometric.tCloudTransactionRawData CRD WITH (NOLOCK)
			INNER JOIN sStudent.tStudentMaster SM WITH (NOLOCK) ON SM.PunchId = CRD.PunchId
			INNER JOIN sStudent.tAcademic AC WITH (NOLOCK) ON AC.StudentId = SM.Id		--Mantis: 34829, add INNER JOIN by dhruvik
			INNER JOIN sSetup.tBatchMaster BM WITH (NOLOCK) ON BM.Id = AC.BatchId		--Mantis: 34829, add INNER JOIN by dhruvik
		WHERE
			--mantis: 44582, comment the below condition and add new condition next to it
			--CRD.TransactionId NOT IN (SELECT TransactionId FROM sBiometric.tCloudTransactionData WITH (NOLOCK))
			CRD.TransactionId NOT IN (SELECT TransactionId FROM sBiometric.tCloudTransactionData WITH (NOLOCK) WHERE DeviceIP=CRD.DeviceIP)
			AND BM.IsActive = 1		--Mantis: 34829, add condition by dhruvik

		--add for mantis: 10346, start
		INSERT INTO sAudit.tActivityLog
		SELECT TOP 1 * FROM
		(SELECT TOP 1
				OM.OrgGroupId as OrgGroupId,
				EM.OrgId as OrgId,
				3 as UserId,
				'' as SessionId,
				30027 as ScreenId,
				sCommon.fGetDate() as AuditDate,
				'Scheduler-CloudTransactionData' as Activity,
				0 as RecordSourceId,
				'' as RecordDetail,
				3 as OSTypeId
		FROM sBiometric.tCloudTransactionData CTD WITH (NOLOCK)
			INNER JOIN #tTable t ON t.TransactionId = CTD.TransactionId
			INNER JOIN sHrm.tEmployeeMaster EM WITH (NOLOCK) ON EM.PunchId = t.PunchId
			INNER JOIN sSetup.tOrganizationMaster OM WITH (NOLOCK) ON OM.Id = EM.OrgID
		WHERE CTD.SourceTypeId=95

		UNION ALL

		SELECT TOP 1
				OM.OrgGroupId as OrgGroupId,
				SM.OrgId as OrgId,
				3 as UserId,
				'' as SessionId,
				30027 as ScreenId,
				sCommon.fGetDate() as AuditDate,
				'Scheduler-CloudTransactionData' as Activity,
				0 as RecordSourceId,
				'' as RecordDetail,
				3 as OSTypeId
		FROM sBiometric.tCloudTransactionData CTD WITH (NOLOCK)
			INNER JOIN #tTable t ON t.TransactionId = CTD.TransactionId
			INNER JOIN sStudent.tStudentMaster SM WITH (NOLOCK) ON SM.PunchId = t.PunchId
			INNER JOIN sSetup.tOrganizationMaster OM WITH (NOLOCK) ON OM.Id = SM.OrgId
		WHERE CTD.SourceTypeId=2001
		) d

		--add for mantis: 10346, end

		DROP TABLE #tTable
	COMMIT TRANSACTION
	SELECT 1 AS Result
	END TRY

	BEGIN CATCH
        IF @@TRANCOUNT > 0
            ROLLBACK TRANSACTION;

		SELECT -1 AS Result

		SET @exceptiondetail='<Table style="border:2px solid #ddd;margin:10px" cellpadding="0" cellspacing="0" >
		<tr><td colspan="2" style="text-align: center;font-weight: bold;font-size:20px;padding:4px;background-color:#dadada"> :: Exception ::
		 </td> </tr>
		<tr><td style="width: 15%;padding:4px;font-weight: bold;border-bottom: 1px solid #ddd;border-right: 1px solid #dadada">Error Message : </td>
		<td style="width: 85%;padding:4px;border-bottom: 1px solid #ddd">'+ ERROR_MESSAGE() +','+ '[sBiometric].[tCloudTransactionData]' +'</td></tr>
		</Table>'

		INSERT INTO sSystem.tExceptionLog(OrgGroupId,ExceptionType,ExceptionMessage,ExceptionDetail,CreatedDateTime)
		SELECT 0,'tCloudTransactionData_DbError,'+ ' [sBiometric].[tCloudTransactionData]',ERROR_MESSAGE(),@exceptiondetail,sCommon.fGetDate()
		RETURN
    END CATCH
END
GO
PRINT N'Altering Procedure [sBiometric].[pMonthTransProcess]...';


GO
ALTER PROCEDURE [sBiometric].[pMonthTransProcess]
AS
SET NOCOUNT ON

BEGIN
	--Drop temp table for server issue(tempdb)
	IF object_id('tempdb..#tTable') IS NOT NULL
	BEGIN
		DROP TABLE #tTable
	END

	CREATE TABLE #tTable (
		Id BIGINT identity
		,[SourceId] [bigint] NOT NULL
		,[In_Out_Time] [datetime] NOT NULL
		,[ShiftCode] [int] NOT NULL
		,[Attn_Dt] [date] NOT NULL
		,[Mode] [nvarchar](10) NOT NULL
		,[CreatedDateTime] [datetime] NOT NULL
		,[DeviceIP] [nvarchar](20) NOT NULL
		,[EntryMode] [tinyint] NOT NULL
		,[PunchId] [nvarchar](50) NOT NULL
		,[TransactionId] [bigint] NOT NULL
		,[SourceTypeId] [smallint] NULL
		,[IsProcessed] [bit] NULL
		)

	DECLARE @lPrevAttn_Dt DATE = ''
	DECLARE @lPrevSourceId BIGINT = 0
	DECLARE @lPrevSourceTypeId SMALLINT = 0

	IF (DAY(sCommon.fGetDate()) > 10)
	BEGIN
		INSERT INTO #tTable
		SELECT [SourceId]
			,[In_Out_Time]
			,[ShiftCode]
			,[Attn_Dt]
			,[Mode]
			,[CreatedDateTime]
			,[DeviceIP]
			,[EntryMode]
			,[PunchId]
			,[TransactionId]
			,[SourceTypeId]
			,[IsProcessed]
		FROM [sBiometric].[tCloudTransactionData] WITH (NOLOCK)
		WHERE MONTH(Attn_Dt) = MONTH(sCommon.fGetDate())
			AND YEAR(Attn_Dt) = YEAR(sCommon.fGetDate())
			AND IsProcessed = 0
	END
	ELSE
	BEGIN
		INSERT INTO #tTable
		SELECT [SourceId]
			,[In_Out_Time]
			,[ShiftCode]
			,[Attn_Dt]
			,[Mode]
			,[CreatedDateTime]
			,[DeviceIP]
			,[EntryMode]
			,[PunchId]
			,[TransactionId]
			,[SourceTypeId]
			,[IsProcessed]
		FROM [sBiometric].[tCloudTransactionData] WITH (NOLOCK)
		WHERE YEAR(Attn_Dt) = YEAR(sCommon.fGetDate())
			AND MONTH(Attn_Dt) IN (
				MONTH(sCommon.fGetDate())
				,MONTH(sCommon.fGetDate()) - 1
				)
			AND IsProcessed = 0 --mantis: 34236, change (MONTH(sCommon.fGetDate()),MONTH(sCommon.fGetDate() - 1)) => (MONTH(sCommon.fGetDate()),MONTH(sCommon.fGetDate()) - 1)
	END

	SELECT *
	FROM #tTable

	DECLARE @lCount INT = 1
	DECLARE @lTotal INT = (
			SELECT COUNT(Id)
			FROM #tTable
			)

	WHILE @lCount <= @lTotal
	BEGIN
		DECLARE @lQuery NVARCHAR(max) = ''
		DECLARE @lAttn_Dt DATE = (
				SELECT Attn_Dt
				FROM #tTable
				WHERE Id = @lCount
				)
		DECLARE @lSourceId BIGINT = (
				SELECT SourceId
				FROM #tTable
				WHERE Id = @lCount
				)
		DECLARE @lSourceTypeId SMALLINT = (
				SELECT SourceTypeId
				FROM #tTable
				WHERE Id = @lCount
				)
		DECLARE @lTransactionId BIGINT = (
				SELECT TransactionId
				FROM #tTable
				WHERE Id = @lCount
				)

		IF (
				@lPrevAttn_Dt = @lAttn_Dt
				AND @lPrevSourceId = @lSourceId
				AND @lPrevSourceTypeId = @lSourceTypeId
				)
		BEGIN
			PRINT ('same employee')

			UPDATE sBiometric.tCloudTransactionData WITH (ROWLOCK)
			SET IsProcessed = 1
			WHERE TransactionId = @lTransactionId
		END
		ELSE
		BEGIN
			DECLARE @lCode INT = (
					SELECT ISNULL(MAX(EmpCode), 0) + 1
					FROM sBiometric.tMonthTrans WITH (NOLOCK)
					)

			IF EXISTS (
					SELECT 1
					FROM sBiometric.tMonthTrans WITH (NOLOCK)
					WHERE EmployeeId = @lSourceId
						AND SourceTypeId = @lSourceTypeId
					)
			BEGIN
				SET @lCode = (
						SELECT TOP 1 EmpCode
						FROM sBiometric.tMonthTrans WITH (NOLOCK)
						WHERE EmployeeId = @lSourceId
							AND SourceTypeId = @lSourceTypeId
						)
			END

			DECLARE @lShift VARCHAR(25) = (
					SELECT ShiftName
					FROM sBiometric.tShiftMasterCloud WITH (NOLOCK)
					WHERE ShiftCode IN (
							SELECT ShiftCode
							FROM #tTable
							WHERE Id = @lCount
							)
					)
			DECLARE @lShiftStartTime DATETIME = (
					SELECT StartTime
					FROM sBiometric.tShiftMasterCloud WITH (NOLOCK)
					WHERE ShiftCode IN (
							SELECT ShiftCode
							FROM #tTable
							WHERE Id = @lCount
							)
					)
			DECLARE @lShiftEndTime DATETIME = (
					SELECT EndTime
					FROM sBiometric.tShiftMasterCloud WITH (NOLOCK)
					WHERE ShiftCode IN (
							SELECT ShiftCode
							FROM #tTable
							WHERE Id = @lCount
							)
					)
			DECLARE @lMinHoursHalfDay TIME = CAST(CAST((
							SELECT MinHrsHalfDay
							FROM sBiometric.tShiftMasterCloud WITH (NOLOCK)
							WHERE ShiftCode IN (
									SELECT ShiftCode
									FROM #tTable
									WHERE Id = @lCount
									)
							) AS NVARCHAR) AS TIME)
			DECLARE @lMinHoursFullDay TIME = CAST(CAST((
							SELECT MinHrsFullDay
							FROM sBiometric.tShiftMasterCloud WITH (NOLOCK)
							WHERE ShiftCode IN (
									SELECT ShiftCode
									FROM #tTable
									WHERE Id = @lCount
									)
							) AS NVARCHAR) AS TIME)
			DECLARE @lIn TIME = CONVERT(TIME, (
						SELECT MIN(In_Out_Time)
						FROM sBiometric.tCloudTransactionData WITH (NOLOCK)
						WHERE Attn_Dt = @lAttn_Dt
							AND SourceId = @lSourceId
							AND SourceTypeId = @lSourceTypeId
						))
			DECLARE @lOut TIME = CASE 
					WHEN (
							SELECT COUNT(In_Out_Time)
							FROM sBiometric.tCloudTransactionData WITH (NOLOCK)
							WHERE Attn_Dt = @lAttn_Dt
								AND SourceId = @lSourceId
								AND SourceTypeId = @lSourceTypeId
							) > 1
						THEN CONVERT(TIME, (
									SELECT MAX(In_Out_Time)
									FROM #tTable
									WHERE Attn_Dt = @lAttn_Dt
										AND SourceId = @lSourceId
										AND SourceTypeId = @lSourceTypeId
									))
					ELSE '00:00'
					END
			DECLARE @lTotalTime VARCHAR(10) = CASE 
					WHEN @lOut <> '00:00'
						THEN (
								SELECT CONVERT(VARCHAR(10), DATEADD(minute, DATEDIFF(minute, @lIn, @lOut), 0), 114)
								)
					ELSE '00:00'
					END
			DECLARE @lEarlyBy VARCHAR(10) = '00:00'
			DECLARE @lLateBy VARCHAR(10) = '00:00'
			DECLARE @lOverTime VARCHAR(10) = ''
			DECLARE @lStatus VARCHAR(10) = ''

			--Add by Nimesh MantisId:0027752
			--Start
			IF (
					DATEDIFF(minute, @lShiftStartTime, @lIn) > 0
					AND @lIn <> '00:00'
					)
			BEGIN
				--SET @lLateBy = '00:00'
				SET @lLateBy = (
						SELECT CONVERT(VARCHAR(10), DATEADD(minute, DATEDIFF(minute, @lShiftStartTime, @lIn), 0), 114)
						)
			END

			IF (
					DATEDIFF(minute, @lShiftEndTime, @lOut) < 0
					AND @lOut <> '00:00'
					)
			BEGIN
				--SET @lEarlyBy = '00:00'
				SET @lEarlyBy = (
						SELECT CONVERT(VARCHAR(10), DATEADD(minute, DATEDIFF(minute, @lOut, @lShiftEndTime), 0), 114)
						)
			END

			--End
			IF (DATEDIFF(minute, @lShiftEndTime, @lOut) < 0)
			BEGIN
				SET @lOverTime = '00:00'
			END
			ELSE
			BEGIN
				SET @lOverTime = CASE 
						WHEN @lOut <> '00:00'
							THEN (
									SELECT CONVERT(VARCHAR(10), DATEADD(minute, DATEDIFF(minute, @lShiftEndTime, @lOut), 0), 114)
									)
						ELSE '00:00'
						END
			END

			IF (CAST(@lTotalTime AS TIME) >= @lMinHoursFullDay)
			BEGIN
				SET @lStatus = 'P'
			END

			IF (
					CAST(@lTotalTime AS TIME) >= @lMinHoursHalfDay
					AND CAST(@lTotalTime AS TIME) < @lMinHoursFullDay
					)
			BEGIN
				SET @lStatus = 'HD'
			END

			IF (CAST(@lTotalTime AS TIME) < @lMinHoursHalfDay)
			BEGIN
				SET @lStatus = 'LH'
			END

			IF (
					@lOut = '00:00'
					AND @lIn <> '00:00'
					)
			BEGIN
				SET @lStatus = 'E'
			END

			--Uncomment this for testing purposes
			--PRINT('In Time: ' + CONVERT(VARCHAR(5),@lIn,108))
			--PRINT('Out Time: ' + CONVERT(VARCHAR(5),@lOut,108))
			--PRINT('Total Time : ' + CONVERT(VARCHAR(5),@lTotalTime,108))
			--PRINT('Overtime : ' + CONVERT(VARCHAR(5),@lOverTime,108))
			--PRINT('Min Hours Half Day : ' + CONVERT(VARCHAR(5),@lMinHoursHalfDay,108))
			--PRINT('Min Hours Full Day : ' + CONVERT(VARCHAR(5),@lMinHoursFullDay,108))
			--PRINT('EarlyBy : ' + CONVERT(VARCHAR(5),@lEarlyBy,108))
			--PRINT('LateBy : ' + CONVERT(VARCHAR(5),@lLateBy,108))
			--PRINT('Status : ' + CONVERT(VARCHAR(5),@lStatus,108))
			--BREAK
			DECLARE @lDay NVARCHAR(10) = (
					SELECT DAY(IN_Out_Time)
					FROM #tTable
					WHERE Id = @lCount
					)

			SET @lDay = (
					SELECT CASE 
							WHEN @lDay BETWEEN 0
									AND 9
								THEN RIGHT('0' + CAST(@lDay AS VARCHAR(2)), 2)
							ELSE CAST(@lDay AS NVARCHAR(10))
							END
					)

			DECLARE @lMonthTransAttn_DtTemp DATETIME = (
					SELECT cast((cast(YEAR(@lAttn_Dt) AS VARCHAR(255)) + '-' + cast(MONTH(@lAttn_Dt) AS VARCHAR(255)) + '-' + '01') AS DATETIME)
					)
			DECLARE @lMonthTransAttn_Dt VARCHAR(20) = convert(VARCHAR(20), @lMonthTransAttn_DtTemp, 20)

			PRINT (@lMonthTransAttn_Dt)

			IF NOT EXISTS (
					SELECT 1
					FROM sBiometric.tMonthTrans WITH (NOLOCK)
					WHERE EmployeeId = @lSourceId
						AND SourceTypeId = @lSourceTypeId
						AND Attn_Dt = @lMonthTransAttn_Dt
					)
			BEGIN
				--Insert 
				INSERT INTO sBiometric.tMonthTrans
				WITH (ROWLOCK) (
					EmpCode
					,EmployeeId
					,Attn_Dt
					,D01
					,D02
					,D03
					,D04
					,D05
					,D06
					,D07
					,D08
					,D09
					,D10
					,D11
					,D12
					,D13
					,D14
					,D15
					,D16
					,D17
					,D18
					,D19
					,D20
					,D21
					,D22
					,D23
					,D24
					,D25
					,D26
					,D27
					,D28
					,D29
					,D30
					,D31
					,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_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
					,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
					,[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
					,SourceTypeId
					)
				VALUES (
					@lCode
					,@lSourceId
					,@lMonthTransAttn_Dt
					,'XX'
					,'XX'
					,'XX'
					,'XX'
					,'XX'
					,'XX'
					,'XX'
					,'XX'
					,'XX'
					,'XX'
					,'XX'
					,'XX'
					,'XX'
					,'XX'
					,'XX'
					,'XX'
					,'XX'
					,'XX'
					,'XX'
					,'XX'
					,'XX'
					,'XX'
					,'XX'
					,'XX'
					,'XX'
					,'XX'
					,'XX'
					,'XX'
					,'XX'
					,'XX'
					,'XX'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'XX'
					,'XX'
					,'XX'
					,'XX'
					,'XX'
					,'XX'
					,'XX'
					,'XX'
					,'XX'
					,'XX'
					,'XX'
					,'XX'
					,'XX'
					,'XX'
					,'XX'
					,'XX'
					,'XX'
					,'XX'
					,'XX'
					,'XX'
					,'XX'
					,'XX'
					,'XX'
					,'XX'
					,'XX'
					,'XX'
					,'XX'
					,'XX'
					,'XX'
					,'XX'
					,'XX'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,0
					,0
					,0
					,0
					,''
					,0
					,''
					,''
					,''
					,0
					,0
					,0
					,0
					,0
					,0
					,0
					,0
					,0
					,0
					,0
					,0
					,@lSourceTypeId
					)
			END

			--Update
			SET @lQuery = 'UPDATE sBiometric.tMonthTrans with (rowlock)
			SET D' + CAST(@lDay AS VARCHAR) + '_IN = ''' + CONVERT(VARCHAR(5), @lIn, 108) + ''',
			D' + CAST(@lDay AS VARCHAR) + '_OUT = ''' + CONVERT(VARCHAR(5), @lOut, 108) + ''',
			D' + CAST(@lDay AS VARCHAR) + '_E = ''' + CONVERT(VARCHAR(5), @lEarlyBy, 108) + ''',
			D' + CAST(@lDay AS VARCHAR) + '_L = ''' + CONVERT(VARCHAR(5), @lLateBy, 108) + ''',
			D' + CAST(@lDay AS VARCHAR) + '_O = ''' + CONVERT(VARCHAR(5), @lOverTime, 108) + ''',
			D' + CAST(@lDay AS VARCHAR) + '_T = ''' + CONVERT(VARCHAR(5), @lTotalTime, 108) + ''',
			D' + CAST(@lDay AS VARCHAR) + ' = ''' + CONVERT(VARCHAR(5), @lStatus, 108) + ''',
			D' + CAST(@lDay AS VARCHAR) + '_S = ''' + CAST(@lShift AS VARCHAR) + '''
			WHERE EmployeeId = ' + CAST(@lSourceId AS VARCHAR) + ' AND Attn_Dt = ''' + CAST(@lMonthTransAttn_Dt AS VARCHAR) + ''' AND SourceTypeId = ' + CAST(@lSourceTypeId AS VARCHAR)

			PRINT ('Query : ' + @lQuery)

			EXEC (@lQuery)

			CREATE TABLE #tSummary (
				PresentStatus VARCHAR(10)
				,PresentStatusCount INT
				)

			INSERT INTO #tSummary
			SELECT [Status]
				,COUNT(*) AS [Count]
			FROM (
				SELECT D01
					,D02
					,D03
					,D04
					,D05
					,D06
					,D07
					,D08
					,D09
					,D10
					,D11
					,D12
					,D13
					,D14
					,D15
					,D16
					,D17
					,D18
					,D19
					,D20
					,D21
					,D22
					,D23
					,D24
					,D25
					,D26
					,D27
					,D28
					,D29
					,D30
					,D31
				FROM sBiometric.tMonthTrans WITH (NOLOCK)
				WHERE EmployeeId = @lSourceId
					AND CAST(Attn_Dt AS DATE) = @lMonthTransAttn_Dt
					AND SourceTypeId = @lSourceTypeId
				) AS TEMP
			UNPIVOT([Status] FOR [Dd] IN (
						D01
						,D02
						,D03
						,D04
						,D05
						,D06
						,D07
						,D08
						,D09
						,D10
						,D11
						,D12
						,D13
						,D14
						,D15
						,D16
						,D17
						,D18
						,D19
						,D20
						,D21
						,D22
						,D23
						,D24
						,D25
						,D26
						,D27
						,D28
						,D29
						,D30
						,D31
						)) AS [unpivoted]
			GROUP BY [Status]
			HAVING COUNT(*) > 0

			--SELECT * FROM #tSummary
			--BREAK
			DECLARE @lTotal_HalfDay INT = (
					SELECT ISNULL(SUM(PresentStatusCount), 0)
					FROM #tSummary
					WHERE PresentStatus IN ('HD')
					)
			DECLARE @lTotal_Present FLOAT = (
					SELECT ISNULL(SUM(PresentStatusCount), 0)
					FROM #tSummary
					WHERE PresentStatus IN ('P')
					) + @lTotal_HalfDay * 0.5
			DECLARE @lTotal_Absent FLOAT = (
					SELECT ISNULL(SUM(PresentStatusCount), 0)
					FROM #tSummary
					WHERE PresentStatus IN (
							'A'
							,'XX'
							,'LH'
							)
					) + @lTotal_HalfDay * 0.5
			DECLARE @lTotal_WeekOff INT = (
					SELECT ISNULL(SUM(PresentStatusCount), 0)
					FROM #tSummary
					WHERE PresentStatus IN (
							'W'
							,'PW'
							)
					)
			DECLARE @lTotal_Holiday INT = (
					SELECT ISNULL(SUM(PresentStatusCount), 0)
					FROM #tSummary
					WHERE PresentStatus IN (
							'H'
							,'PH'
							)
					)
			DECLARE @lTotal_Hours VARCHAR(50) = (
					SELECT CAST(t.time_sum / 3600 AS VARCHAR(10)) + ':' + CAST(t.time_sum % 3600 / 60 AS VARCHAR(10))
					FROM (
						SELECT SUM(DATEDIFF(S, '00:00', [Status])) AS time_sum
						FROM (
							SELECT 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
							FROM sBiometric.tMonthTrans WITH (NOLOCK)
							WHERE EmployeeId = @lSourceId
								AND CAST(Attn_Dt AS DATE) = @lMonthTransAttn_Dt
								AND SourceTypeId = @lSourceTypeId
							) AS TEMP
						UNPIVOT([Status] FOR [Dd] IN (
									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
									)) AS [unpivoted]
						) t
					)
			DECLARE @lTotal_Early VARCHAR(50) = (
					SELECT CAST(t.time_sum / 3600 AS VARCHAR(10)) + ':' + CAST(t.time_sum % 3600 / 60 AS VARCHAR(10))
					FROM (
						SELECT SUM(DATEDIFF(S, '00:00', [Status])) AS time_sum
						FROM (
							SELECT 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
							FROM sBiometric.tMonthTrans WITH (NOLOCK)
							WHERE EmployeeId = @lSourceId
								AND CAST(Attn_Dt AS DATE) = @lMonthTransAttn_Dt
								AND SourceTypeId = @lSourceTypeId
							) AS TEMP
						UNPIVOT([Status] FOR [Dd] IN (
									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
									)) AS [unpivoted]
						) t
					)
			DECLARE @lTotal_Late VARCHAR(50) = (
					SELECT CAST(t.time_sum / 3600 AS VARCHAR(10)) + ':' + CAST(t.time_sum % 3600 / 60 AS VARCHAR(10))
					FROM (
						SELECT SUM(DATEDIFF(S, '00:00', [Status])) AS time_sum
						FROM (
							SELECT 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
							FROM sBiometric.tMonthTrans WITH (NOLOCK)
							WHERE EmployeeId = @lSourceId
								AND CAST(Attn_Dt AS DATE) = @lMonthTransAttn_Dt
								AND SourceTypeId = @lSourceTypeId
							) AS TEMP
						UNPIVOT([Status] FOR [Dd] IN (
									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
									)) AS [unpivoted]
						) t
					)
			DECLARE @lTotal_OverTime VARCHAR(50) = (
					SELECT CAST(t.time_sum / 3600 AS VARCHAR(10)) + ':' + CAST(t.time_sum % 3600 / 60 AS VARCHAR(10))
					FROM (
						SELECT SUM(DATEDIFF(S, '00:00', [Status])) AS time_sum
						FROM (
							SELECT 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
							FROM sBiometric.tMonthTrans WITH (NOLOCK)
							WHERE EmployeeId = @lSourceId
								AND CAST(Attn_Dt AS DATE) = @lMonthTransAttn_Dt
								AND SourceTypeId = @lSourceTypeId
							) AS TEMP
						UNPIVOT([Status] FOR [Dd] IN (
									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
									)) AS [unpivoted]
						) t
					)

			UPDATE sBiometric.tMonthTrans WITH (ROWLOCK)
			SET [Tot_Attn] = @lTotal_Present
				,[Tot_Abs] = @lTotal_Absent
				,[Tot_WeekOFF] = @lTotal_WeekOff
				,[Tot_Holiday] = @lTotal_Holiday
				,[TotalHour] = @lTotal_Hours
				,[Tot_HD] = @lTotal_HalfDay
				,[Tot_Early] = @lTotal_Early
				,[Tot_Late] = @lTotal_Late
				,[Tot_OT] = @lTotal_OverTime
			WHERE EmployeeId = @lSourceId
				AND CAST(Attn_Dt AS DATE) = @lMonthTransAttn_Dt
				AND SourceTypeId = @lSourceTypeId

			UPDATE sBiometric.tCloudTransactionData WITH (ROWLOCK)
			SET IsProcessed = 1
			WHERE TransactionId = @lTransactionId

			DROP TABLE #tSummary
		END

		SET @lPrevAttn_Dt = @lAttn_Dt
		SET @lPrevSourceId = @lSourceId
		SET @lPrevSourceTypeId = @lSourceTypeId
		SET @lCount = @lCount + 1
	END

	--add for mantis: 10346, start
	INSERT INTO sAudit.tActivityLog WITH (ROWLOCK)
	SELECT TOP 1 *
	FROM (
		SELECT TOP 1 OM.OrgGroupId AS OrgGroupId
			,EM.OrgId AS OrgId
			,3 AS UserId
			,'' AS SessionId
			,30027 AS ScreenId
			,sCommon.fGetDate() AS AuditDate
			,'Scheduler-MonthTrans' AS Activity
			,0 AS RecordSourceId
			,'' AS RecordDetail
			,3 AS OSTypeId
		FROM sBiometric.tMonthTrans MT WITH (NOLOCK)
		INNER JOIN #tTable t ON t.SourceId = MT.EmployeeId
		INNER JOIN sHrm.tEmployeeMaster EM WITH (NOLOCK) ON EM.PunchId = t.PunchId
		INNER JOIN sSetup.tOrganizationMaster OM WITH (NOLOCK) ON OM.Id = EM.OrgID
		WHERE MT.SourceTypeId = 95
		
		UNION ALL
		
		SELECT TOP 1 OM.OrgGroupId AS OrgGroupId
			,SM.OrgId AS OrgId
			,3 AS UserId
			,'' AS SessionId
			,30027 AS ScreenId
			,sCommon.fGetDate() AS AuditDate
			,'Scheduler-MonthTrans' AS Activity
			,0 AS RecordSourceId
			,'' AS RecordDetail
			,3 AS OSTypeId
		FROM sBiometric.tMonthTrans MT WITH (NOLOCK)
		INNER JOIN #tTable t ON t.SourceId = MT.EmployeeId
		INNER JOIN sStudent.tStudentMaster SM WITH (NOLOCK) ON SM.PunchId = t.PunchId
		INNER JOIN sSetup.tOrganizationMaster OM WITH (NOLOCK) ON OM.Id = SM.OrgId
		WHERE MT.SourceTypeId = 2001
		) d

	--add for mantis: 10346, end
	--Drop temp table for server issue(tempdb)
	DROP TABLE #tTable
END
GO
PRINT N'Altering Procedure [sCertificate].[pLeavingBulkGet]...';


GO
ALTER PROCEDURE [sCertificate].[pLeavingBulkGet]
	 
	 @rClassID int,
	 @rDivisionId int,
	 @rOrgId int,
	 @rBatchId int,
	 @rStatusId smallint=0
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	
	SELECT 
			SA.AcademicId,
			ISNULL(SA.RollNo,0) AS RollNo,
			SA.Code,
			SA.Name,
			SA.Number,
			ISNULL(L.Id,0) AS Id,
			ISNULL(L.LCNumber,0) AS LCNumber,
			ISNULL(L.LCDate,'') AS LCDate,
			ISNULL(L.LCRemark,'')AS LCRemark,
			ISNULL(L.LastExamName,'')AS LastExamName,
			ISNULL(L.LastExamResult,'')AS LastExamResult,
			ISNULL(L.RepeatDetail,'')AS RepeatDetail,
			--ISNULL(L.SubjectStudied,'')AS SubjectStudied,
			ISNULL(L.PromoteToClass,'')AS PromoteToClass,
			ISNULL(L.ExtraCurricularActivities,'')As ExtraCurricularActivities,
			ISNULL(L.NCCScoutDetail,'')AS NCCScoutDetail,
			ISNULL(L.TermsInInstitute,'')As TermsInInstitute,
			ISNULL(L.FeeDetail,'')AS FeeDetail,
			ISNULL(L.FeeConcessionDetail,'')AS FeeConcessionDetail,
			ISNULL(AD.TotalDaysAnnual,0)AS TotalDays,
			ISNULL(AD.PresentDaysAnnual,0)AS PresentDays,
			ISNULL(StuA.ProofOfDOB,'')AS ProofOfDOB,
			CASE WHEN EXISTS(SELECT 1 FROM sSetup.tSubjectMaster S  INNER JOIN sSetup.tClassSubject CS ON  S.Id = CS.SubjectId AND CS.ClassId=@rClassId	
								WHERE S.OrgId=@rOrgId AND CS.IsOptional=0) THEN
			reverse(STUFF(reverse(isnull([sCommon].[fXMLTagsReplaceReverse](STUFF((SELECT ',' + S.Title from sSetup.tSubjectMaster S  
						   INNER JOIN sSetup.tClassSubject CS ON  S.Id = CS.SubjectId AND CS.ClassId=@rClassId	
						   WHERE S.OrgId=@rOrgId AND CS.IsOptional=0 FOR XML PATH('')), 1, 1, '')),'') + -- +',' + removed for mantis - 0044229
			isnull([sCommon].[fXMLTagsReplaceReverse](STUFF((SELECT ',' + S.Title FROM sAssessment.tOptionalSubject OS 
						   INNER JOIN sSetup.tClassSubject CS ON CS.Id = OS.ClassSubjectId 
						   INNER JOIN sSetup.tSubjectMaster S ON  S.Id = CS.SubjectId 
						   WHERE OS.AcademicId = SA.AcademicId FOR XML PATH('')), 1, 0, '')),'') -- Changed 1,1 to 1,0 for prevent to remove last character  - 0044229
						   ), 1, 0, ''))  -- Changed 1,1 to 1,0 for prevent to remove last character  - 0044229
						   
			ELSE

			STUFF(reverse(reverse(isnull([sCommon].[fXMLTagsReplaceReverse](STUFF((SELECT ',' + S.Title from sSetup.tSubjectMaster S  
						   INNER JOIN sSetup.tClassSubject CS ON  S.Id = CS.SubjectId AND CS.ClassId=@rClassId	
						   WHERE S.OrgId=@rOrgId AND CS.IsOptional=0 FOR XML PATH('')), 1, 1, '')),'') + -- +',' + removed for mantis - 0044229
			isnull([sCommon].[fXMLTagsReplaceReverse](STUFF((SELECT ',' + S.Title FROM sAssessment.tOptionalSubject OS 
						   INNER JOIN sSetup.tClassSubject CS ON CS.Id = OS.ClassSubjectId 
						   INNER JOIN sSetup.tSubjectMaster S ON  S.Id = CS.SubjectId 
						   WHERE OS.AcademicId = SA.AcademicId FOR XML PATH('')), 1, 0, '')),'')  -- Changed 1,1 to 1,0 for prevent to remove last character  - 0044229
						   )), 1, 0, '') END AS SubjectStudied,
			(SA.ClassName +'-'+SA.DivisionName)AS ClassDivision

  FROM 
			[sStudent].[vStudentAcademic]  SA 
			LEFT OUTER JOIN sCertificate.tLeaving L ON L.AcademicId=SA.AcademicId
			LEFT JOIN sStudent.tAcademicDetail AD ON SA.AcademicId=AD.AcademicId
			LEFT JOIN sStudent.tStudentAdmission StuA ON StuA.StudentId = SA.StudentId
  WHERE 
			(SA.ClassId=@rClassId OR @rClassId=0)
			AND (SA.DivisionId=@rDivisionId OR @rDivisionId=0)
			AND SA.BatchId=@rBatchId
			AND SA.OrgID=@rOrgId 
			AND L.Id IS NULL
			AND((SA.StatusId=@rStatusId)OR(@rStatusId=0))
			--order by
			--CASE @rOrderBy WHEN 2 THEN (CASE ISNUMERIC(SA.Code) WHEN 1 THEN REPLICATE(0 , 100 - LEN(SA.Code)) + SA.Code ELSE SA.Code  END) END,
			--CASE @rOrderBy WHEN 1 THEN SA.RollNo END,
			--CASE @rOrderBy WHEN 0 THEN SA.RollNo END
END
GO
PRINT N'Altering Procedure [sCertificate].[pRptLeavingCertificateGet]...';


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

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

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


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

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


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

	--add for 27638 mantis start
	DECLARE @lIsShowPhoto bit = 0
	SELECT @lConfigValue = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 124 AND SourceTypeId = 1016 AND SourceId = @rOrgId
	
	IF (@lConfigValue IS NULL) OR (@lConfigValue = 'False')
	SET @lIsShowPhoto = 0
	ELSE
	SET @lIsShowPhoto = 1
	--add for 27638 mantis end
	
	--Added by Krunal Patel for : mantis- 0041217 
	SELECT @lConfigValue = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 598 AND SourceTypeId = 1016 AND SourceId = @rOrgId
	
	IF (@lConfigValue IS NULL) OR (@lConfigValue = 'False')
	SET @lIsDisplayName = 0
	ELSE
	SET @lIsDisplayName = 1	
	

	SELECT
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			--MR.PresentCount AS PresentDays ,
			--MR.TotalCount AS TotalDays ,
			L.Id,
			--(SELECT SUM(MR.PresentCount) FROM sAttendance.tMonthlyRegister MR WHERE MR.AcademicId=A.Id) AS PresentDaysSum ,
			--(SELECT SUM(MR.TotalCount) FROM sAttendance.tMonthlyRegister MR WHERE MR.AcademicId=A.Id) AS TotalDaysSum ,
			SM.Code,
			L.AcademicId,
			SM.FirstName,SM.MiddleName,SM.LastName,
			--Added by Krunal Patel for : mantis- 0041217 
			--[sStudent].[fStudentNameGet](SM.FirstName , SM.MiddleName, SM.LastName,OM.StudentNameFormatId ) AS Name,			
			CASE WHEN @lIsDisplayName=0
			THEN [sStudent].[fStudentNameGet](SM.FirstName , SM.MiddleName, SM.LastName,OM.StudentNameFormatId )			
			WHEN @lIsDisplayName=1
			THEN ISNULL(L.displayName,[sStudent].[fStudentNameGet](SM.FirstName , SM.MiddleName, SM.LastName,OM.StudentNameFormatId ))			
			END AS Name,

			ISNULL(SF.FatherName,'') As FatherName,
			ISNULL(SF.MotherName,'') As MotherName,
			ISNULL(CTM.Nationality,'') AS Nationality,
			--0 As CastCategoryId,
			--ISNULL(SO.CastCategoryId,0) As CastCategoryId,
			ISNULL(RM.Title,'') AS Religion,
			ISNULL(so.BirthPlace,'') AS BirthPlace,
			ISNULL(SO.BirthTaluka,'') AS BirthTaluka,
			ISNULL(SO.BirthDistrict,'') AS BirthDistrict,
			SO.DateOfBirth,
			ISNULL(SO.BirthDateInWord,'') AS BirthDateInWord,
			SA.PreviousSchool,
			SA.AdmissionDate,
			L.LCNumber,
			L.LeftDate,
			L.LCReason,
			L.LCProgress,
			L.LCConduct,
			L.LCRemark,
			L.LCDate,
			L.LCBookNumber,
			SO.GenderId,
			
			ISNULL(SO.FamilySubCast,'') AS SubCaste,
			ISNULL(SO.FamilyCast,'') AS Caste,
			ISNULL(OM.CityName,'') AS City,
			ISNULL(SC.PresentState,'') AS CityState,
			CM.DisplayTitle AS AdmissionStandard,
			CMS.DisplayTitle AS CurrentStandard,
			CMS.Title AS CurrentStandardTitle,
			--'' AS CurrentStandardInWords,
			SM.StatusId,
			L.LastExamName AS Result,
			L.LastExamResult AS FailOrPass,
			L.SubjectStudied AS SubjectNAme,
			L.RepeatDetail as PromotedorNot,
			--ISNULL(SubM.Title,'') AS SubjectNAme,
			--'' AS PromotedorNot,
			ISNULL(L.PromoteToClass,'')  AS PromotedToClass,
			L.FeeDetail AS LastFeesPaid,
			L.FeeConcessionDetail AS AnyConcession,
			L.NCCScoutDetail  AS NCCScoutDetail,
			L.ExtraCurricularActivities AS GamesPlayed,
			OM.OrgLogo,
			OM.Title AS OrgTitle,
			OM.StreetOne+' '+OM.StreetTwo+' '+OM.StreetThree AS OrgAddress,
			OM.PhoneNo,
			vSA.RollNo,
			DM.OrderIndex AS DivisionOrder,
			OM.SmallAddress1,
			OM.SmallAddress2,
			OM.RegistrationDetail,
			@lIsOnPrePrinted AS IsOnPrePrinted,
			@lIsDisplayReligion AS IsDisplayReligion,
			AD.PresentDaysAnnual AS PresentDaysSum,
			AD.TotalDaysAnnual AS TotalDaysSum,
			vSA.ClassName AS ClassName,
			vSA.DivisionName AS DivisionName,
			@lIsDisplayImageHeader AS IsDisplayImageHeader,
			--OI.CertificateHeaderA4  ,
			isnull(MainCastCategoryId,0) AS CastCategoryId,
			ISNULL(L.ToCollege,'') AS ToCollege ,
			ISNULL(L.ToCollegeAddress,'')AS ToCollegeAddress,
			ISNULL(OM.University,'')AS University,
			@lSchoolRemark1 AS SchoolRemark1 ,
			@lSchoolRemark2 AS SchoolRemark2 ,
			@lSchoolRemark3 AS SchoolRemark3 ,
			@lSchoolRequiredSignature AS SchoolRequiredSignature,
			ISNULL(CMS.ClassNameInWord,'')AS CurrentStandardInWords,
			SO.MotherTongue,
			SO.AdhaarNumber,
			vSA.SUId,
			CASE WHEN isnull(BM.FromDate,'')>Isnull(SA.AdmissionDate,'') THEN BM.FromDate ELSE SA.AdmissionDate END AS BatchDate,
			SO.BirthState,
			SO.BirthCountry,
			SD.BankAccountNumber,
			SO.UIDNumber,
			SD.BankName,
			SD.BankIFSCCode,
			SA.PreviousStandard 
			,L.TermsInInstitute,
			@lIDConfigValue AS ItemValue 
			,L.LCCopy
			,DM.InchargeEmployeeId AS ClassTeacher
			,vSA.BatchName AS BatchName,
			CSM.Title As CasteCategory,
			ISNULL(SA.AdmissionNumber,'') AS AdmissionNumber,
			SI.StudentPhoto,
			SA.AdmissionFormNumber,
			BM.FromDate as BatchStartDate,
			BM.ToDate as BatchEndDate,
			SO.UIDNumber,
			SC.PresentStreetOne AS Address1,
			SC.PresentStreetTwo AS Address2,
			SC.PresentStreetThree AS Address3,
			SC.PresentCity AS PresentCity,
			SC.PresentZipCode AS PresentZipCode,
			ISNULL(OM.ReportOrgGroupTitle,'') AS ReportOrgGroupTitle,
			OM.ReportOrgTitle,
			OI.CertificateHeaderA4Portrait AS CertificateHeaderA4,
			ISNULL(SA.PreviousSchool,'') AS PreviousSchool,
			L.TotalDays,
			L.PresentDays,
			ISNULL(CMS.ClassNameInWord,'') AS ClassNameInWord,
			vSA.ClassId AS ClassId,
		--sFinanceCommon.fNumberToWords(ISNULL(CM.ClassGroupId,0),'',OM.OrgGroupId) AS CurrentStandardInWords
		--CASE WHEN @rIsTransferCerti=1
		--THEN ISNULL(MR.PresentCount,0)
		--WHEN @rIsTransferCerti=0
		--THEN SUM(ISNULL(MR.PresentCount,0))
		--END AS Presentdays,
		--CASE WHEN @rIsTransferCerti=1
		--THEN ISNULL(MR.TotalCount,0)
		--WHEN @rIsTransferCerti=0
		--THEN SUM(ISNULL(MR.TotalCount,0))
		--END AS TotalCount
		@rUserName AS UserName,
		EI.EmployeeSign,
		EI1.EmployeeSign AS DivisionInchargeEmployeeSign,
		ISNULL(L.ProofOfDOB,'')AS ProofOfDOB,
		U.LoginTitle AS CreatedUserName,
		OM.PrincipalSignature,
		CM.ClassNameInWord AS AdmissionStandardInWord,
		LM.Title AS LanguageTitle,
		@lIsShowPhoto AS IsShowPhoto,		--add for 27638 mantis start
		CAST((CASE WHEN SI.QRCode IS NULL THEN 0 ELSE 1 END) AS bit) AS IsDisplayQRCode,
		ISNULL(SI.QRCode,'') AS QRCode		--add for 27638 mantis end 
		,ISNULL(L.LCCopyRemark,'') AS LCCopyRemark    --add for 28079 mantis end 
		,ISNULL(SH.IdentificationMark1,'') AS IdentificationMark1,
		ISNULL(L.LastExamName ,'') AS LastExamName,--Mantis - 0032104
		vSA.PENNumber,     --mantis - 0032285
		vSA.DepartmentName AS DepartmentName,  --add for mentis : 0033427
		IsNUll(BGM.Title,'') AS BloodGroup,--mantis - 0033572
		ISNULL(SM.LocalName,'') AS LocalName, -- added by dhananjay for mantis id - 0035713
        ISNULL(CMM.Title,'')	AS LeftStandard	  --added by dhananjay for mantis id - 35764 
		,ISNULL(SH.IdentificationMark2,'') AS IdentificationMark2  --added by dhananjay for mantis id - 36467                     
		,L.CreatedDateTime AS LCCreateDate --add for mantis : 0039190
		,ISNULL(CGM.Title,'') AS AdmissionClassGroup --add for mantis : 0039971
		,ISNULL(CGMS.Title,'') AS CurrentClassGroup --add for mantis : 0039971
		,ISNULL(SM.ApaarIdNumber,'') AS ApaarIdNumber--Added by dhananjay for mantis : 40247
		,ISNULL(ACM.Title ,'') AS FeeCategory		--Mantis - 40574			
		,L.DisplayName AS DisplayName    --Mantis -0041217 - Krunal
		,ISNULL(GM.Title,'')AS Gender	--Mantis - 42635
		,U.DisplayTitle AS CreatedUser		--Mantis - 44570
	
	FROM 
			sCertificate.tLeaving L
			INNER JOIN sStudent.vStudentAcademic vSA ON vSA.AcademicId=L.AcademicId
			--INNER JOIN sStudent.tAcademic A ON L.AcademicId=A.Id
			LEFT JOIN sStudent.tStudentAdmission SA ON SA.StudentId=vSA.StudentId
			INNER JOIN sStudent.tStudentMaster SM ON SM.Id=vSA.StudentId			
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=vSA.OrgId 
			INNER JOIN sSecurity.tUser U ON U.Id = L.CreatedUserId
			LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId=vSA.StudentId 
			LEFT JOIN sCommon.tReligionMaster RM ON SO.ReligionId=RM.Id
			--LEFT JOIN  sAttendance.tMonthlyRegister MR ON MR.AcademicId=A.Id 
			LEFT JOIN sSetup.tClassMaster CM ON CM.Id=SA.AdmissionStandardId
			INNER JOIN sSetup.tDivisionMaster DM ON vSA.DivisionId = DM.Id  
			INNER JOIN sSetup.tClassMaster CMS ON CMS.Id= DM.ClassId 
			LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId=vSA.StudentId
			LEFT JOIN sCommon.tCountryMaster CTM ON CTM.Id=SO.NationalityId
			LEFT JOIN sStudent.tAcademicDetail AD ON AD.AcademicId=vSA.AcademicId
			--LEFT JOIN sSetup.tClassSubject CS ON CS.ClassId=A.ClassId
			--LEFT JOIN sSetup.tSubjectMaster SubM ON SM.Id=CS.SubjectId
			LEFT JOIN sSetup.tOrgImages OI ON OI.OrgId = OM.Id
			LEFT JOIN sCommon.tCastCategoryMaster CSM ON CSM.Id=SO.CastCategoryId
			--LEFT JOIN sSetup.tClassGroupMaster CSG ON CSG.Id=CMS.ClassGroupId
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id=vSA.BatchId 
			--AND BM.OrgGroupBatchId=vSA.OrgGroupBatchId
			LEFT JOIN sStudent.tStudentAdditional SD ON SD.StudentId=vSA.StudentId
			LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId=SM.Id
			LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId=SM.Id
			LEFT JOIN sHrm.tEmployeeImages EI ON EI.EmployeeId = DM.InchargeEmployeeId
			LEFT JOIN sSetup.tDivisionInchargeEmployee DIE ON vSA.DivisionId = DIE.DivisionId AND DIE.BatchId = vSA.BatchId
			AND DIE.Number = (SELECT MIN(Number) FROM sSetup.tDivisionInchargeEmployee WHERE  DIE.DivisionId = vSA.DivisionId AND DIE.BatchId = vSA.BatchId)
			LEFT JOIN sHrm.tEmployeeImages EI1 ON EI1.EmployeeId = DIE.EmployeeId
			INNER JOIN sSetup.tLanguageMaster LM ON LM.Id = OM.LanguageId
			LEFT JOIN sStudent.tStudentHealth SH ON SH.StudentId=vSA.StudentId 
			LEFT JOIN sCommon.tBloodGroupMaster BGM ON BGM.Id =SO.BloodGroupId --mantis - 0033572
			LEFT JOIN  sSetup.tClassMaster CMM ON CMM.Id= SA.LeftStandardId   --added by dhananjay for mantis id - 35764
			LEFT JOIN sSetup.tClassGroupMaster CGM ON CGM.Id=CM.ClassGroupId --add for mantis : 0039971
			LEFT JOIN sSetup.tClassGroupMaster CGMS ON CGMS.Id=CMS.ClassGroupId --add for mantis : 0039971
			LEFT JOIN sStudent.tAdmissionCategoryMaster ACM on ACM.Id = vSA.AdmissionCategoryId --Mantis - 40574
			INNER JOIN sCommon.tGenderMaster GM ON GM.Id = vSA.GenderId		--Mantis - 42635

	WHERE 
				L.OrgId=@rOrgId
				AND	vSA.BatchId = @rBatchId 
				AND ((SM.Code = @rCode) OR (ISNULL(@rCode,'') = ''))
				AND ((SM.FirstName = @rName) OR (ISNULL(@rName,'') = ''))
				--AND ((L.LCNumber=@rNumber) OR (@rNumber=''))
				AND ((L.LCDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
				AND ((L.LCDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
				--AND ((L.LCDate=@rLCDate) OR (ISNULL(@rLCDate,'')=''))
				--AND ((L.LeftDate=@rLeftDate) OR (ISNULL(@rLeftDate,'')=''))
				--AND ((L.LCCopy=@rLCCopy) OR (@rLCCopy=0))
				--AND ((L.LCBookNumber=@rLCBookNumber) OR (@rLCBookNumber=''))
				AND ((vSA.ClassId=@rClassId) OR(@rClassId=0))
				AND ((vSA.DivisionId=@rDivisionId) OR (@rDivisionId=0))
				AND ((L.LCNumber=@rLCNumber) OR (@rLCNumber=''))
				AND ((L.LCNumber >= @rFromNo) OR (@rFromNo=''))
				AND ((L.LCNumber <= @rToNo) OR (@rToNo=''))
				AND ((DM.ClassId=@rClassId) OR(@rClassId=0))
				--group by MR.PresentCount,MR.TotalCount, SubM.Title, SM.Code,L.AcademicId,SM.FirstName,SM.LastName,SM.MiddleName,SF.FatherName,SF.MotherName,NM.Title,
				--SO.CastCategoryId,RM.Title,so.BirthPlace,SO.BirthTaluka,SO.BirthDistrict,SO.DateOfBirth,SO.BirthDateInWord,SA.PreviousSchool,
				--	SA.AdmissionDate,L.LeftDate,L.LCReason,L.LCProgress,L.LCConduct,L.LCRemark,L.LCDate,SO.GenderId,
				--	OM.CityName,OM.StateName,CM.DisplayTitle,CMS.DisplayTitle,SM.StatusId,OM.OrgLogo,OM.PhoneNo,OM.Title,OM.StreetOne,OM.StreetTwo,OM.StreetThree
END
GO
PRINT N'Altering Procedure [sCertificate].[pStudentCustomFiledDataGet]...';


GO

ALTER PROCEDURE [sCertificate].[pStudentCustomFiledDataGet]
	 
	 @rAcademicId bigint = 0,
	 @rOrgGroupId int = 0
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 

DECLARE @lStudentId BigInt = 0;
SELECT @lStudentId = StudentId FROM sStudent.tAcademic WHERE Id = @rAcademicId

DECLARE @columns NVARCHAR(MAX);
DECLARE @sql NVARCHAR(MAX);

	SET @columns = STUFF(
		(
			SELECT ',' + QUOTENAME(LTRIM(RTRIM(FieldTitle)))
			FROM sStudent.tStudentCustomFieldMaster SM
			LEFT JOIN sStudent.tStudentCustomFieldData CM ON SM.Id = CM.StudentCustomFieldId AND CM.StudentId = @lStudentId
			WHERE SM.OrgGroupId = @rOrgGroupId AND SM.IsObsolete = 0
			GROUP BY FieldTitle
			FOR XML PATH(''), TYPE
		).value('.', 'NVARCHAR(MAX)')
		,1,1,''); -- Remove the leading comma


-- Construct the dynamic SQL query
	SET @sql = '
	SELECT StudentId, ' + @columns + '
	FROM
	(
		SELECT 
			CM.StudentId,
			LTRIM(RTRIM(SM.FieldTitle)) AS FieldTitle,
			CASE WHEN ISNULL(CM.FieldData, '''') = ''- Select -'' THEN ''''
                ELSE ISNULL(CM.FieldData, '''') END AS FieldData
		FROM sStudent.tStudentCustomFieldMaster SM
		LEFT JOIN sStudent.tStudentCustomFieldData CM ON SM.Id = CM.StudentCustomFieldId AND CM.StudentId = ' + Convert(varchar(20),@lStudentId) + ' 
		WHERE SM.OrgGroupId = ' + Convert(varchar(10),@rOrgGroupId) + ' AND SM.IsObsolete = 0 AND CM.StudentId IS NOT NULL
	) AS SourceTable
	PIVOT
	(
		MAX(FieldData)
		FOR FieldTitle IN (' + @columns + ')
	) AS PivotTable
	';

-- Print the SQL for debugging
	--PRINT @sql;

-- Execute the dynamic SQL
	EXEC sp_executesql @sql;

END
GO
PRINT N'Altering Procedure [sCommon].[pTableRowIdModify]...';


GO

ALTER PROCEDURE [sCommon].[pTableRowIdModify]
@rOrgGroupId [int],
@rTableTitle [nvarchar](100),
@rCurrentNumber [bigint] = NULL,
@rSeed [bigint] = NULL,
@rIncrement [bigint] = NULL,
@rIsCurrentNumber [bit] = 0,
@rNextNumber [bigint] = NULL OUTPUT

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
BEGIN TRY
Begin tran
declare @exceptiondetail nvarchar(max)
	IF @rCurrentNumber > 0
	BEGIN
		UPDATE sCommon.tTableRowId WITH (rowlock) SET CurrentNumber = @rCurrentNumber
		--,UpdatedDateTime = sCommon.fGetDate() 
		WHERE TableTitle = @rTableTitle AND OrgId = @rOrgGroupId
	END
	ELSE
	BEGIN 
		UPDATE sCommon.tTableRowId WITH (rowlock) 
		SET @rNextNumber = CurrentNumber = (CASE @rIsCurrentNumber WHEN 1 THEN CurrentNumber ELSE 
		                                   (CASE WHEN CurrentNumber < Seed THEN Seed ELSE CurrentNumber + Increment END) END),
		Seed = ISNULL(@rSeed, Seed),
		Increment = ISNULL(@rIncrement, Increment),
		UpdatedDateTime = sCommon.fGetDate()
		WHERE TableTitle = @rTableTitle AND OrgId = @rOrgGroupId
	END
	commit tran
END TRY
BEGIN CATCH
 	
rollback tran
set @exceptiondetail='<Table style="border:2px solid #ddd;margin:10px" cellpadding="0" cellspacing="0" >
<tr><td colspan="2" style="text-align: center;font-weight: bold;font-size:20px;padding:4px;background-color:#dadada"> :: Exception ::
 </td> </tr>
<tr><td style="width: 15%;padding:4px;font-weight: bold;border-bottom: 1px solid #ddd;border-right: 1px solid #dadada">Error Message : </td>
<td style="width: 85%;padding:4px;border-bottom: 1px solid #ddd">'+ ERROR_MESSAGE() +','+ @rTableTitle +'</td></tr>
</Table>'
 
		insert into sSystem.tExceptionLog(OrgGroupId,ExceptionType,ExceptionMessage,ExceptionDetail,CreatedDateTime)
		Select @rOrgGroupId,'TableRowId_DBError,'+ @rTableTitle,ERROR_MESSAGE(),@exceptiondetail,sCommon.fGetDate()	
Return
END CATCH

END
GO
PRINT N'Altering Procedure [sLibrary].[pXMLNewspaperLogAdd]...';


GO
ALTER PROCEDURE [sLibrary].[pXMLNewspaperLogAdd]
(
	@rXml  nvarchar(MAX),
	@rOrgId int,
	@rCreatedUserId bigint,
	@rLibraryId int = 0	--mantis: 44411
)
AS
SET NOCOUNT ON
BEGIN

	DECLARE @lInterrorCode INT,@intDoc INT
	DECLARE @lNextNumber BIGINT			
 
	EXECUTE @lInterrorCode = sp_xml_preparedocument @intDoc OUTPUT, @rXml
	
	BEGIN TRY

		CREATE TABLE #tempTable  
		(
			Id bigint identity,
			NewspaperId smallint,
			NewspaperTitle nvarchar(300),
			NewspaperLanguage nvarchar(100),
			NewsType nvarchar(30),
			NewspaperDate datetime,
			NoOfCopy int,
			NewspaperAmount decimal(12,2)
		)

		INSERT INTO #tempTable
		(
			NewspaperTitle,
			NewspaperLanguage,
			NewsType,
			NewspaperDate,
			NoOfCopy,
			NewspaperAmount
		)
		SELECT	
			A.NewspaperTitle,
			A.NewspaperLanguage,
			A.NewsType,
			CONVERT(datetime, A.NewspaperDate, 103) AS NewspaperDate,
			A.NoOfCopy,
			A.NewspaperAmount
		FROM OPENXML (@intDoc, '/Table/NewspaperLog', 1)
		WITH
		( 
			NewspaperTitle NVARCHAR(300) '@NewspaperTitle',
			NewspaperLanguage NVARCHAR(100) '@NewspaperLanguage',
			NewsType NVARCHAR(30) '@NewsType',
			NewspaperDate datetime '@NewspaperDate',
			NoOfCopy int '@NoOfCopy',
			NewspaperAmount decimal(12,2) '@NewspaperAmount' 
		)A 

		--Select * from #tempTable return
		DECLARE @lCount int,@lId int
		SELECT @lCount = COUNT(Id) FROM #tempTable
		SELECT Top 1 @lId=Id FROM #tempTable
	
		WHILE @lId <= @lCount 
		BEGIN

			DECLARE @lNewspaperId BIGINT, @lNewspaperDate date, @lNoOfCopy Int, @lNewspaperAmount int
	
			SELECT @lNewspaperId = NM.Id 
			FROM sLibrary.tNewspaperMaster AS NM
				INNER JOIN #tempTable AS TT ON TT.NewspaperTitle = NM.Title 
			WHERE  TT.Id = @lId
				AND NM.LibraryId = @rLibraryId	--mantis: 44411

			SELECT @lNewspaperDate = NewspaperDate from #tempTable where  Id = @lId
			SELECT @lNoOfCopy = NoOfCopy from #tempTable where  Id = @lId
			SELECT @lNewspaperAmount = NewspaperAmount from #tempTable where  Id = @lId
		
			EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sLibrary.tNewspaperLog', 0, 1, 1,@outNextNumber = @lNextNumber output

			print @lNextNumber
										
			SET IDENTITY_INSERT sLibrary.tNewspaperLog ON

			INSERT INTO sLibrary.tNewspaperLog
			(
				AutoId,
				NewspaperId,
				NewspaperDate,
				NoOfCopy,
				NewspaperAmount,
				CreatedUserId,
				CreatedDateTime 	
			)
			Values
			(	
				@lNextNumber,
				@lNewspaperId,
				@lNewspaperDate,
				@lNoOfCopy,
				@lNewspaperAmount,
				@rCreatedUserId,
				sCommon.fGetDate()   
			)

			SET IDENTITY_INSERT sLibrary.tNewspaperLog OFF
	
			SELECT @lNextNumber = MAX(AutoId) FROM sLibrary.tNewspaperLog
			EXECUTE sCommon.pTableRowIdModify @rOrgId, @rTableTitle = 'sLibrary.tNewspaperLog', @rCurrentNumber = @lNextNumber 

			SET @lId=@lId+1
		
		END
		EXEC sp_xml_removedocument @intDoc
		SELECT 1 as Result
		DROP Table #tempTable
	END TRY	

	BEGIN CATCH 
		SELECT -1 AS Result,error_message() AS MSG
	END CATCH
END
GO
PRINT N'Altering Procedure [sStudent].[pStudentGenerateReport]...';


GO
ALTER PROCEDURE [sStudent].[pStudentGenerateReport]
	@rId bigint,
	@rTitle nvarchar(50),
	@rColumnName nvarchar(max) = '',
	@rOrderBy nvarchar(max) = 'RollNo',
	@rOrgId smallint,
	@rCode [nvarchar](20) = '',
	@rFirstName [nvarchar](50) = '',	
	@rLastName [nvarchar](50) = '',
	@rCountry [nvarchar](50) = '',
	@rState [nvarchar](50) = '',
	@rCity nvarchar(max) = '',
	@rArea nvarchar(max) = '',
	@rDivisionId nvarchar(max) = '',
	@rStatusId nvarchar(max) = '',
	@rTransportModeId nvarchar(max) = '',
	@rBusRouteDestinationId nvarchar(max) = '',
	@rBloodGroupId nvarchar(max) = '',
	@rGenderId nvarchar(max) = '',
	@rReligionId nvarchar(max) = '',
	@rCastCategoryId nvarchar(max) = '',
	@rHouseId nvarchar(max) = '',
	@rMotherTongueId nvarchar(max) = '',
	@rNationalityId nvarchar(max) = '',
	@rHobby nvarchar(50) = '',
	@rFatherQualification nvarchar(max) = '',
	@rMotherQualification nvarchar(max) = '',
	@rFatherOccupation nvarchar(max) = '',
	@rMotherOccupation nvarchar(max) = '',
	@rPreviousSchool nvarchar(max) = '',
	@rAdmissionCategoryId nvarchar(max) = '',
	@rDOBFromDate Date = '0001-01-01',
	@rDOBToDate Date = '9999-12-31',
	@rDOAFromDate Date = '0001-01-01',
	@rDOAToDate Date = '9999-12-31',
	@rDOLFromDate Date = '0001-01-01',
	@rDOLToDate Date = '9999-12-31',
	@rIsPysicalDeformity bit,
	@rIsMajorIllness bit,
	@rIsCommon bit,
	@rIsCommonForOrg bit,
	@rCreatedUserId bigint,
	@BatchId int,
	@rIsBlackList bit,
	@rFromCode nvarchar(20), 
	@rToCode nvarchar(20),
	@rSpecificCode nvarchar(max),
	@rDropDownStatusId int,
	@rDropDownClassId int,
	@rDropDownDivisionId int,
	@rCustomTagId nvarchar(max) = '',
	@rCustomGroupId nvarchar(max) = '',
	@rClubId nvarchar(max) = '',
	@rRepeatCount smallint=0,
	@rStudentStatusId smallint=0,
	@rHostelId nvarchar(max) = '',
	@rStudentGroupId nvarchar(max) = '',
	@rStudentOtherGroupId nvarchar(max) = '',
	@rOrgGroupBatchId int,
	@rBusRouteId nvarchar(max) = '',
	@rFeeExemption nvarchar(max)='',
	@rRecordTagId nvarchar(max) = '',
	@rContactNo nvarchar(50) = '',
	@rBirthDay int =0,
	@rDateOfMonth int =0,
	@rStopApplicationAccess int = 0,
	@rCurrentOrgId int = 0

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
		IF(@rHostelId IS NULL)
			SET @rHostelId = ''
		IF(@rStudentGroupId IS NULL)
			SET @rStudentGroupId = ''
		IF(@rStudentOtherGroupId IS NULL)
			SET @rStudentOtherGroupId = ''	
		IF(@rOrgGroupBatchId IS NULL)
			SET @rOrgGroupBatchId = 0
		IF(@rGenderId IS NULL)
			SET @rGenderId = ''
		IF(@rBusRouteId IS NULL)
			SET @rBusRouteId = ''	
		IF(@rDOBFromDate IS NULL)
			SET @rDOBFromDate='0001-01-01'
		IF(@rDOBToDate IS NULL)
			SET @rDOBToDate='9999-12-31'
		IF(@rDOAFromDate IS NULL)
			SET @rDOAFromDate='0001-01-01'
		IF(@rDOAToDate IS NULL)
			SET @rDOAToDate='9999-12-31'
		IF(@rDOLFromDate IS NULL)
			SET @rDOLFromDate='0001-01-01'
		IF(@rDOLToDate IS NULL)
			SET @rDOLToDate='9999-12-31'
		
		IF(@rTitle != '' AND @rId = 0)
		BEGIN
			DECLARE @lNextNumber BIGINT

			-- when OrgId 0 then issue in @lNextNumber thats why add new parameter @rCurrentOrgId and generate Id according current session -- mantisid - 0033556
			IF(@rOrgId = 0)
			BEGIN
				EXECUTE sCommon.pTableRowIdGet @rCurrentOrgId, 'sStudent.tStudentCustomSearch', 0, 1, 1,@outNextNumber = @lNextNumber output

				INSERT INTO sStudent.tStudentCustomSearch
				(
					Id,Title,ColumnName,OrderBy,OrgId,Code,FirstName,LastName,Country,State,City,Area,DivisionId,
					StatusId,TransportModeId,BusRouteDestinationId,BloodGroupId,GenderId,ReligionId,CastCategoryId,
					HouseId,MotherTongueId,NationalityId,Hobby,FatherQualification,MotherQualification,FatherOccupation,
					MotherOccupation,PreviousSchool,AdmissionCategoryId,DOBFromDate,DOBToDate,DOAFromDate,DOAToDate,
					DOLFromDate,DOLToDate,IsPysicalDeformity,IsMajorIllness,IsCommon,IsCommonForOrg, CreatedUserId,CreatedDateTime,
					IsBlackList,FromCode,ToCode,CustomTag,CustomGroup,Club,RepeatCount,StudentStatusId,Hostel,StudentGroup,
					StudentOtherGroup,FeeExemption,RecordTag,ContactNo,BirthDay,DateOfMonth,IsStopApplicationAccess
				)
				VALUES
				(
					@lNextNumber,@rTitle,@rColumnName,@rOrderBy,@rCurrentOrgId,@rSpecificCode,@rFirstName,@rLastName,@rCountry,@rState,
					@rCity,@rArea,@rDivisionId,@rStatusId,@rTransportModeId,@rBusRouteDestinationId,@rBloodGroupId,@rGenderId,
					@rReligionId,@rCastCategoryId,@rHouseId,@rMotherTongueId,@rNationalityId,@rHobby,@rFatherQualification,
					@rMotherQualification,@rFatherOccupation,@rMotherOccupation,@rPreviousSchool,@rAdmissionCategoryId,
					@rDOBFromDate,@rDOBToDate,@rDOAFromDate,@rDOAToDate,@rDOLFromDate,@rDOLToDate,@rIsPysicalDeformity,
					@rIsMajorIllness,@rIsCommon,@rIsCommonForOrg,@rCreatedUserId,sCommon.fGetDate(),@rIsBlackList,@rFromCode,@rToCode,
					@rCustomTagId,@rCustomGroupId,@rClubId,@rRepeatCount,@rStudentStatusId,@rHostelId,@rStudentGroupId,
					@rStudentOtherGroupId,@rFeeExemption,@rRecordTagId,@rContactNo,@rBirthDay,@rDateOfMonth,@rStopApplicationAccess
				)
			END
			ELSE
			BEGIN
				EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sStudent.tStudentCustomSearch', 0, 1, 1,@outNextNumber = @lNextNumber output

				INSERT INTO sStudent.tStudentCustomSearch
				(
					Id,Title,ColumnName,OrderBy,OrgId,Code,FirstName,LastName,Country,State,City,Area,DivisionId,
					StatusId,TransportModeId,BusRouteDestinationId,BloodGroupId,GenderId,ReligionId,CastCategoryId,
					HouseId,MotherTongueId,NationalityId,Hobby,FatherQualification,MotherQualification,FatherOccupation,
					MotherOccupation,PreviousSchool,AdmissionCategoryId,DOBFromDate,DOBToDate,DOAFromDate,DOAToDate,
					DOLFromDate,DOLToDate,IsPysicalDeformity,IsMajorIllness,IsCommon,IsCommonForOrg, CreatedUserId,CreatedDateTime,
					IsBlackList,FromCode,ToCode,CustomTag,CustomGroup,Club,RepeatCount,StudentStatusId,Hostel,StudentGroup,
					StudentOtherGroup,FeeExemption,RecordTag,ContactNo,BirthDay,DateOfMonth,IsStopApplicationAccess
				)
				VALUES
				(
					@lNextNumber,@rTitle,@rColumnName,@rOrderBy,@rOrgId,@rSpecificCode,@rFirstName,@rLastName,@rCountry,@rState,
					@rCity,@rArea,@rDivisionId,@rStatusId,@rTransportModeId,@rBusRouteDestinationId,@rBloodGroupId,@rGenderId,
					@rReligionId,@rCastCategoryId,@rHouseId,@rMotherTongueId,@rNationalityId,@rHobby,@rFatherQualification,
					@rMotherQualification,@rFatherOccupation,@rMotherOccupation,@rPreviousSchool,@rAdmissionCategoryId,
					@rDOBFromDate,@rDOBToDate,@rDOAFromDate,@rDOAToDate,@rDOLFromDate,@rDOLToDate,@rIsPysicalDeformity,
					@rIsMajorIllness,@rIsCommon,@rIsCommonForOrg,@rCreatedUserId,sCommon.fGetDate(),@rIsBlackList,@rFromCode,@rToCode,
					@rCustomTagId,@rCustomGroupId,@rClubId,@rRepeatCount,@rStudentStatusId,@rHostelId,@rStudentGroupId,
					@rStudentOtherGroupId,@rFeeExemption,@rRecordTagId,@rContactNo,@rBirthDay,@rDateOfMonth,@rStopApplicationAccess
				)
			END

		END
		
		
		IF(@rId > 0)
		BEGIN
			Select @rColumnName=ColumnName,@rOrderBy=OrderBy,@rOrgId=OrgId,@rSpecificCode=Code,@rFirstName=FirstName,
			@rLastName=LastName,@rCountry=Country,@rState=State,@rCity=City,@rArea=Area,@rDivisionId=DivisionId,
			@rStatusId=StatusId,@rTransportModeId=TransportModeId,@rBusRouteDestinationId=BusRouteDestinationId,
			@rBloodGroupId=BloodGroupId,@rGenderId=GenderId,@rReligionId=ReligionId,@rCastCategoryId=CastCategoryId,
			@rHouseId=HouseId,@rMotherTongueId=MotherTongueId,@rNationalityId=NationalityId,@rHobby=Hobby,
			@rFatherQualification=FatherQualification,@rMotherQualification=MotherQualification,
			@rFatherOccupation=FatherOccupation,@rMotherOccupation=MotherOccupation,
			@rPreviousSchool=PreviousSchool,@rAdmissionCategoryId=AdmissionCategoryId,
			@rDOBFromDate=DOBFromDate,@rDOBToDate=DOBToDate,@rDOAFromDate=DOAFromDate,
			@rDOAToDate=DOAToDate,@rDOLFromDate=DOLFromDate,@rDOLToDate=DOLToDate,
			@rIsPysicalDeformity=IsPysicalDeformity,@rIsMajorIllness=IsMajorIllness,
			@rIsBlackList=IsBlackList,@rFromCode=FromCode,@rToCode=ToCode,
			@rCustomTagId=CustomTag,@rCustomGroupId = CustomGroup,@rClubId = Club,
			@rRepeatCount = RepeatCount,@rStudentStatusId =StudentStatusId,
			@rHostelId = Hostel,@rStudentGroupId = StudentGroup,
			@rStudentOtherGroupId = StudentOtherGroup,@rFeeExemption =FeeExemption,
			@rRecordTagId=RecordTag,@rContactNo=ContactNo,@rStopApplicationAccess=IsStopApplicationAccess
			FROM sStudent.tStudentCustomSearch WHERE Id=@rId
		END
		
		DECLARE @ListofCodes TABLE(Code nvarchar(25), ID INT IDENTITY(1,1));
			INSERT INTO @ListofCodes
	     
		SELECT q2.value from
			(SELECT cast('<x>'+replace(@rSpecificCode,',','</x><x>')+'</x>' as xml) as thexml)q1 CROSS APPLY
			(SELECT x.value('.','nvarchar(max)') as value FROM thexml.nodes('x') as f(x))q2
		
		SET @rOrderBy=Replace(@rOrderBy,'GR No','Code')
		SET @rOrderBy=Replace(@rOrderBy,'ID No','Code')
		SET @rColumnName=Replace(@rColumnName,'GR No','Code')
		SET @rColumnName=Replace(@rColumnName,'ID No','Code')
		SET @rColumnName=Replace(@rColumnName,'PhysicalDeformityRemark','PysicalDeformityRemark')
		SET @rColumnName=Replace(@rColumnName,'IsPhysicalDeformity','IsPysicalDeformity')
		SET @rOrderBy=Replace(@rOrderBy,'PhysicalDeformityRemark','PysicalDeformityRemark')
		SET @rOrderBy=Replace(@rOrderBy,'IsPhysicalDeformity','IsPysicalDeformity')
		
		DECLARE @Sql nvarchar(MAX)= ''
		
		SET @rSpecificCode = sCommon.fSearchStringGet(@rSpecificCode)
		SET @rFirstName = sCommon.fSearchStringGet(@rFirstName)
		SET @rLastName = sCommon.fSearchStringGet(@rLastName)
		SET @rCountry = sCommon.fSearchStringGet(@rCountry)
		SET @rState = sCommon.fSearchStringGet(@rState)
		
		 IF  EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME ='tTempStudent1')
		 BEGIN
			DROP Table sStudent.tTempStudent1
		 END
		 IF  EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME ='tTempStudent2')
		 BEGIN		
			DROP Table sStudent.tTempStudent2
		 END
		 IF  EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME ='tTempStudent3')
		 BEGIN
			DROP Table sStudent.tTempStudent3
		 END
		 IF  EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME ='tTempStudent4')
		 BEGIN
			DROP Table sStudent.tTempStudent4
		 END
		 IF  EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME ='tTempStudent5')
		 BEGIN
			DROP Table sStudent.tTempStudent5  
		 END
		 IF  EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME ='tTempStudent6')
		 BEGIN
			DROP Table sStudent.tTempStudent6
		 END
		 
		 IF  EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME ='tTempStudent7')
		 BEGIN
			DROP Table sStudent.tTempStudent7
		 END
		 
		 IF  EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME ='tTempStudent8')
		 BEGIN
			DROP Table sStudent.tTempStudent8
		 END
		 IF  EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME ='tTempStudent9')
		 BEGIN
			DROP Table sStudent.tTempStudent9
		 END
		 IF  EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME ='tTempStudent10')
		 BEGIN
			DROP Table sStudent.tTempStudent10
		 END
		 IF  EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME ='tTempStudent11')
		 BEGIN
			DROP Table sStudent.tTempStudent11
		 END
		 IF  EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME ='tTempStudent12')
		 BEGIN
			DROP Table sStudent.tTempStudent12
		 END
		 IF  EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME ='tTempStudent13')
		 BEGIN
			DROP Table sStudent.tTempStudent13
		 END
		  IF  EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME ='tTempStudent14')
		 BEGIN
			DROP Table sStudent.tTempStudent14
		 END
		
		SELECT  DISTINCT SM.Id AS StudentId6,
		CASE WHEN SF.IsFatherExStudent = 0 THEN 'No' WHEN SF.IsFatherExStudent = 1 THEN 'Yes' ELSE '' END AS IsFatherExStudent,
		CASE WHEN SF.IsMotherExStudent = 0 THEN 'No' WHEN SF.IsMotherExStudent = 1 THEN 'Yes' ELSE '' END AS IsMotherExStudent,
		SF.FatherOrganization, SF.FatherDesignation, SF.MotherOrganization, SF.MotherDesignation, SF.RelativeOrganization, SF.RelativeDesignation
		INTO sStudent.tTempStudent11
		FROM sStudent.tStudentMaster SM
			 INNER JOIN sStudent.tAcademic A ON A.StudentId = SM.Id AND ((SM.OrgId = @rOrgId) OR (@rOrgId=0)) AND ((A.BatchId=@BatchId) OR (@BatchId = 0))
			 INNER JOIN sStudent.tStudentFamily SF ON SF.StudentId = SM.Id
	
		-- For Left Detail
		SELECT DISTINCT  SA.StudentId AS StudentId12,InactiveDate,InActiveReason,LCBook,--LeftStandardId,
		CM.Title AS LeftStandard,
		CONVERT(VARCHAR(10),LCDate,111) AS LCDate,LCCopy,LeftReason,LCProgress,
		LCConduct,LCRemark 
		INTO sStudent.tTempStudent12
		FROM sStudent.tStudentAdmission SA
		     INNER JOIN sStudent.tAcademic A ON A.StudentId = SA.StudentId AND ((A.OrgId = @rOrgId) OR (@rOrgId = 0)) AND ((A.BatchId=@BatchId) OR (@BatchId=0))
		     LEFT JOIN sSetup.tClassMaster CM ON CM.Id = SA.LeftStandardId
		
		-- For Custom Tag
		IF (@rCustomTagId <> '')
		BEGIN
			SELECT DISTINCT SM.Id AS StudentId1
			INTO sStudent.tTempStudent5
			FROM sStudent.tStudentMaster SM
			INNER JOIN sStudent.tStudentCustomTag SCT ON SCT.StudentId=SM.Id
			INNER JOIN sStudent.tAcademic A ON A.StudentId = SM.Id
			WHERE ((SM.OrgId = @rOrgId) OR (@rOrgId = 0))  AND ((A.BatchId = @BatchId) OR (@BatchId = 0))
			AND (ISNULL(SCT.CustomTagId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rCustomTagId,','))OR @rCustomTagId='')
		END
		ELSE
		BEGIN
			SELECT DISTINCT NULL AS StudentId1
			INTO sStudent.tTempStudent5
		END
		
		-- For Custom Group
		IF (@rCustomGroupId <> '')
		BEGIN
			SELECT DISTINCT SM.Id AS StudentId2
			INTO sStudent.tTempStudent6
			FROM sStudent.tStudentMaster SM
			INNER JOIN sStudent.tAcademic A ON A.StudentId = SM.Id
			INNER JOIN sCommunication.tCustomGroupMember CGM ON CGM.SourceId = A.Id AND CGM.SourceTypeId=2001
			WHERE ((SM.OrgId = @rOrgId) OR (@rOrgId = 0))  AND ((A.BatchId = @BatchId) OR (@BatchId = 0))
			AND (ISNULL(CGM.CustomGroupId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rCustomGroupId,','))OR @rCustomGroupId='')
		END
		ELSE
		BEGIN
			SELECT DISTINCT NULL AS StudentId2
			INTO sStudent.tTempStudent6
		END
		
		-- For Club Group
		IF (@rClubId <> '')
		BEGIN
			SELECT DISTINCT SM.Id AS StudentId3
			INTO sStudent.tTempStudent7
			FROM sStudent.tStudentMaster SM
			INNER JOIN sStudent.tAcademic A ON A.StudentId = SM.Id
			INNER JOIN sActivity.tAssignClub AC ON AC.AcademicId = A.Id
			WHERE ((SM.OrgId = @rOrgId) OR (@rOrgId = 0))  AND ((A.BatchId = @BatchId) OR (@BatchId = 0))
			AND (ISNULL(AC.ClubId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClubId,','))OR @rClubId='')
		END
		ELSE
		BEGIN
			SELECT DISTINCT NULL AS StudentId3
			INTO sStudent.tTempStudent7
		END
		
		-- For Hostel
		IF (@rHostelId <> '')
		BEGIN
			SELECT DISTINCT SM.Id AS StudentId4
			INTO sStudent.tTempStudent9
			FROM sStudent.tStudentMaster SM
			INNER JOIN sStudent.tAcademic A ON A.StudentId = SM.Id
			INNER JOIN sHostel.tAssignRoom AR ON AR.SourceId = A.StudentId
			AND ((AR.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
			INNER JOIN sHostel.tRoomMaster RM ON RM.Id = AR.RoomId
			WHERE((SM.OrgId = @rOrgId) OR (@rOrgId = 0))  
			AND (ISNULL(RM.HostelId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rHostelId,','))OR @rHostelId='')
		END
		ELSE
		BEGIN
			SELECT DISTINCT NULL AS StudentId4
			INTO sStudent.tTempStudent9
		END
		
		--Transport
		IF (@rBusRouteId <> '')
		BEGIN
			SELECT DISTINCT SM.Id AS StudentId5
			INTO sStudent.tTempStudent10
			FROM sStudent.tStudentMaster SM
			INNER JOIN sStudent.tAcademic A ON A.StudentId = SM.Id
			INNER JOIN sTransport.tAssignRoute AT ON AT.SourceId = A.StudentId
			INNER JOIN sTransport.tBusRouteDestinationMaster BM ON BM.Id = AT.PickupDestinationId
			INNER JOIN sTransport.tBusRouteMaster BRM ON BRM.Id = BM.BusRouteId
			AND ((BRM.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
			WHERE ((SM.OrgId = @rOrgId) OR (@rOrgId = 0)) 
			AND (ISNULL(BRM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rBusRouteId,','))OR @rBusRouteId='')
		END
		ELSE
		BEGIN
			SELECT DISTINCT NULL AS StudentId5
			INTO sStudent.tTempStudent10
			
			
		END
		-- For Record Tag
		IF (@rRecordTagId <> '')
		BEGIN
			SELECT DISTINCT SM.Id AS StudentId14		
			INTO sStudent.tTempStudent14	--mantis: 44697, uncomment this line
			FROM sStudent.tStudentMaster SM
			INNER JOIN sStudent.tAcademic A ON A.StudentId = SM.Id
			WHERE ((SM.OrgId = @rOrgId) OR (@rOrgId = 0))  AND ((A.BatchId = @BatchId) OR (@BatchId = 0))
			AND (ISNULL(SM.RecordStatusId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rRecordTagId,','))OR @rRecordTagId='')
		END
		ELSE
		BEGIN
		
			SELECT DISTINCT NULL AS StudentId14
			INTO sStudent.tTempStudent14
		END
		
		SET @rColumnName=Replace(@rColumnName,'GR No','Code')
		SET @rColumnName=Replace(@rColumnName,'ID No','Code')
		--if @rColumnName <> ''
		--begin
		--	select @rColumnName = left(@rColumnName,len(@rColumnName)-1)
		--end
		--print 'asdasda'
		    DECLARE @lAvailableStudentColumns nvarchar(max)=''
			DECLARE @lAvailableStudentCustomRes nvarchar(max)=''
			Declare @Title as nvarchar(max)
			DECLARE @cols AS NVARCHAR(MAX),@query  AS NVARCHAR(MAX)
		
		
          --BEGIN  
		   
		   --drop table sStudent.tTempStudent13

             
			--print @BatchId
			--print @rOrgId
            DECLARE @rOrgGroupId smallint

			--mantisid -- 0033556
			IF(@rOrgId = 0)
			BEGIN
				SET @rOrgGroupId = (Select orggroupid from sSetup.tOrganizationMaster where Id=@rCurrentOrgId)
			END
			ELSE
			BEGIN
				SET @rOrgGroupId = (Select orggroupid from sSetup.tOrganizationMaster where Id=@rOrgId)
			END

                        
             
			SET @lAvailableStudentColumns=   STUFF((SELECT ',' + QUOTENAME(PP.FieldTitle,'[]'), '' AS FieldTitle, '' AS SalaryMonth
								from sStudent.tStudentCustomFieldMaster PP  WHERE PP.OrgGroupId = @rOrgGroupId  
						FOR XML PATH(''), TYPE
						).value('.', 'NVARCHAR(MAX)') 
					,1,1,'')
					--Print @lAvailableStudentColumns
	        IF(@lAvailableStudentColumns IS NOT NULL)
	        BEGIN
				set @query = 'SELECT  StudentId AS StudentId13 ,' + @lAvailableStudentColumns + ' into sStudent.tTempStudent13 from 
					 (
						select PPE.FieldTitle,PP.StudentId,FieldData 
						FROM
						sStudent.tStudentCustomFieldData PP 
							INNER JOIN sStudent.tStudentCustomFieldMaster PPE ON PPE.Id = PP.StudentCustomFieldId AND PPE.IsObsolete=0
							INNER JOIN sStudent.tStudentMaster SM ON SM.Id = PP.StudentId						
							INNER JOIN sStudent.tAcademic A ON A.StudentId = SM.Id AND A.BatchId='+convert(varchar(20),@BatchId)+' 
							WHERE ((SM.OrgId='+convert(varchar(20),@rOrgId) +') OR ('+ convert(varchar(20),@rOrgId) +' = 0))
					) x 
					pivot 
					(
						Max(FieldData)
						for FieldTitle in (' +@lAvailableStudentColumns  + ')
					) p'
					
				 --print @query
                execute(@query)
		   
		   
		
		Select * into sStudent.tTempStudent
		FROM sStudent.vStudentCustomSearch SCS
		INNER JOIN sStudent.tTempStudent5 T5 ON SCS.StudentId = T5.StudentId1 OR @rCustomTagId = ''
		INNER JOIN sStudent.tTempStudent6 T6 ON SCS.StudentId = T6.StudentId2 OR @rCustomGroupId = ''
		INNER JOIN sStudent.tTempStudent7 T7 ON SCS.StudentId = T7.StudentId3 OR @rClubId = ''
		INNER JOIN sStudent.tTempStudent9 T9 ON SCS.StudentId = T9.StudentId4 OR @rHostelId = ''
		INNER JOIN sStudent.tTempStudent10 T10 ON SCS.StudentId = T10.StudentId5 OR @rBusRouteId = ''
		LEFT JOIN sStudent.tTempStudent11 T11 ON SCS.StudentId = T11.StudentId6
		LEFT JOIN  sStudent.tTempStudent12 T12 ON SCS.StudentId= T12.StudentId12 
		LEFT JOIN  sStudent.tTempStudent13 T13 ON SCS.StudentId= T13.StudentId13 
		INNER JOIN sStudent.tTempStudent14 T14 ON SCS.StudentId = T14.StudentId14 OR @rRecordTagId = ''
		WHERE ((SCS.OrgId = @rOrgId) OR (@rOrgId = 0)) 
		AND ((SCS.BatchId = @BatchId) OR (@BatchId = 0))
		--AND ((SCS.Code Like @rCode + '%') OR (@rCode = ''))
		AND ((SCS.FirstName Like @rFirstName  + '%') OR (@rFirstName = ''))
		AND ((SCS.LastName Like @rLastName + '%')OR(@rLastName = ''))
		AND ((SCS.Hobby Like '%' + @rHobby + '%') OR (@rHobby = ''))
		AND ((ISNULL(SCS.PermanentCountry,'') Like @rCountry + '%') OR(@rCountry = ''))
		AND ((ISNULL(SCS.PermanentState,'') Like @rState + '%')OR(@rState = ''))
		AND ((ISNULL(SCS.DateOfBirth,'0001-01-01') >= @rDOBFromDate) OR (ISNULL(@rDOBFromDate,'') = ''))
		AND ((ISNULL(SCS.DateOfBirth,'9999-12-31') <= @rDOBToDate) OR (ISNULL(@rDOBToDate,'') = ''))
		AND ((ISNULL(SCS.AdmissionDate,'0001-01-01') >= @rDOAFromDate) OR (ISNULL(@rDOAFromDate,'') = ''))
		AND ((ISNULL(SCS.AdmissionDate,'9999-12-31') <= @rDOAToDate) OR (ISNULL(@rDOAToDate,'') = ''))
		AND ((ISNULL(SCS.LeftDate,'0001-01-01') >= @rDOLFromDate) OR (ISNULL(@rDOLFromDate,'') = ''))
		AND ((ISNULL(SCS.LeftDate,'9999-12-31') <= @rDOLToDate) OR (ISNULL(@rDOLToDate,'') = ''))
		AND (ISNULL(SCS.PermanentCity,0) IN( SELECT item FROM  sCommon.fnsplit(@rCity,','))OR @rCity='')
		AND (ISNULL(SCS.PermanentStreetThree,0) IN( SELECT item FROM  sCommon.fnsplit(@rArea,','))OR @rArea='')
		AND (SCS.DivisionId In( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionId,','))OR @rDivisionId='')
		AND (SCS.StatusId In( SELECT cast(item as int) FROM  sCommon.fnsplit(@rStatusId,','))OR @rStatusId='')
		AND (SCS.TransportModeId In( SELECT cast(item as int) FROM  sCommon.fnsplit(@rTransportModeId,','))OR @rTransportModeId='')
		AND (ISNULL(SCS.BloodGroupId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rBloodGroupId,','))OR @rBloodGroupId='')
		AND (ISNULL(SCS.GenderId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rGenderId,','))OR (@rGenderId=''))
		AND (ISNULL(SCS.ReligionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rReligionId,','))OR @rReligionId='')
		AND (ISNULL(SCS.CastCategoryId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rCastCategoryId,','))OR @rCastCategoryId='')
		AND (ISNULL(SCS.HouseId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rHouseId,','))OR @rHouseId='')
		AND (ISNULL(SCS.MotherTongueId,0) IN ( SELECT cast(item as int) FROM  sCommon.fnsplit(@rMotherTongueId,','))OR @rMotherTongueId='')
		AND (ISNULL(SCS.NationalityId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rNationalityId,','))OR @rNationalityId='')
		AND (ISNULL(SCS.BusRouteDestinationId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rBusRouteDestinationId,','))OR @rBusRouteDestinationId='')
		AND (ISNULL(SCS.FatherQualification,'') IN( SELECT item FROM  sCommon.fnsplit(@rFatherQualification,','))OR @rFatherQualification='')
		AND (ISNULL(SCS.FatherOccupation,'') IN( SELECT item FROM  sCommon.fnsplit(@rFatherOccupation,','))OR @rFatherOccupation='')
		AND (ISNULL(SCS.MotherQualification,'') IN( SELECT item FROM  sCommon.fnsplit(@rMotherQualification,','))OR @rMotherQualification='')
		AND (ISNULL(SCS.MotherOccupation,'') IN( SELECT item FROM  sCommon.fnsplit(@rMotherOccupation,','))OR @rMotherOccupation='')
		AND (ISNULL(SCS.AdmissionCategoryId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rAdmissionCategoryId,','))OR @rAdmissionCategoryId='')
		AND (ISNULL(SCS.PreviousSchool,'') IN( SELECT item FROM  sCommon.fnsplit(@rPreviousSchool,','))OR @rPreviousSchool='')
		AND (ISNULL(SCS.RepeatCount,0) IN( SELECT item FROM  sCommon.fnsplit(@rRepeatCount,','))OR @rRepeatCount='')
		AND (ISNULL(SCS.StudentStatusId,0) IN( SELECT item FROM  sCommon.fnsplit(@rStudentStatusId,','))OR @rStudentStatusId='')
		AND (ISNULL(SCS.StudentGroupId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rStudentGroupId,','))OR @rStudentGroupId='')
		AND (ISNULL(SCS.StudentOtherGroupId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rStudentOtherGroupId,','))OR @rStudentOtherGroupId='')
		AND ((SCS.IsPysicalDeformity=@rIsPysicalDeformity) OR (@rIsPysicalDeformity=0))
		AND ((SCS.IsMajorIllness=@rIsMajorIllness) OR (@rIsMajorIllness=0))
		AND ((SCS.IsBlackList=@rIsBlackList) OR (@rIsBlackList=0))
		--AND ((REPLICATE(0, 50 - LEN(SCS.Code)) + SCS.Code) >= (REPLICATE(0, 50 - LEN(@rFromCode)) + @rFromCode) OR (@rFromCode='') OR (@rFromCode=0))	-- Add @rFromCode=0 for MantisId : 0029214
		--AND ((REPLICATE(0, 50 - LEN(SCS.Code)) + SCS.Code) <= (REPLICATE(0, 50 - LEN(@rToCode)) + @rToCode) OR (@rToCode='') OR (@rToCode=0))			-- Add @rToCode=0 for MantisId : 0029214
		AND ((REPLICATE(0, 50 - LEN(SCS.Code)) + SCS.Code) >= (REPLICATE(0, 50 - LEN(@rFromCode)) + @rFromCode) OR (@rFromCode=''))			-- MantisId : 0032524
		AND ((REPLICATE(0, 50 - LEN(SCS.Code)) + SCS.Code) <= (REPLICATE(0, 50 - LEN(@rToCode)) + @rToCode) OR (@rToCode=''))				-- MantisId : 0032524
		AND ((SCS.Code IN(SELECT Code FROM @ListofCodes)) OR (ISNULL(@rSpecificCode,'') = ''))
		AND ((SCS.StatusId = @rDropDownStatusId) OR (@rDropDownStatusId=0))
		AND ((SCS.ClassId = @rDropDownClassId) OR (@rDropDownClassId=0))
		AND ((SCS.DivisionId = @rDropDownDivisionId) OR (@rDropDownDivisionId=0))
		AND (ISNULL(SCS.BusRouteId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rBusRouteId,','))OR @rBusRouteId='')
		AND (ISNULL(SCS.ExemptionTypeId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeExemption,','))OR @rFeeExemption='')
		AND ((SCS.PresentContactNo=@rContactNo) OR (SCS.PermanentContactNo=@rContactNo) OR (SCS.EmergencyContactNo=@rContactNo) OR (SCS.ParentContactno=@rContactNo) OR (SCS.StudentContactNo=@rContactNo) OR (SCS.FatherContactNo=@rContactNo) OR (SCS.MotherContactNo=@rContactNo) OR (@rContactNo=''))
		AND (( DAY(CONVERT(date,SCS.DateOfBirth)) = @rBirthDay) OR (@rBirthDay = 0))
	    AND (( MONTH(CONVERT(date,SCS.DateOfBirth)) = @rDateOfMonth) OR (@rDateOfMonth = 0))
		--AND (ISNULL(SCS.CustomTagId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rCustomTagId,','))OR @rCustomTagId='')
		--Select * from sStudent.tTempStudent return	
		AND ((SCS.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))
		AND ((SCS.IsStopApplicationAccess = @rStopApplicationAccess) OR (@rStopApplicationAccess = -1))
				
		set @sql = 'SELECT '+ @rColumnName+' FROM sStudent.tTempStudent ORDER BY '+@rOrderBy
		
		if(@rColumnName='ID No')
		BEGIN
			SET @sql=Replace(@sql,'SELECT Code','SELECT Code AS [ID No]')
		END
		if(@rColumnName='GR No')
		BEGIN
			SET @sql=Replace(@sql,'SELECT Code','SELECT Code AS [GR No]')
		END
		
		exec(@Sql)
			
		DROP Table sStudent.tTempStudent
		DROP Table sStudent.tTempStudent5
		DROP Table sStudent.tTempStudent6
		DROP Table sStudent.tTempStudent7
		DROP Table sStudent.tTempStudent9
		DROP Table sStudent.tTempStudent10
		DROP Table sStudent.tTempStudent12
		DROP Table sStudent.tTempStudent13
		DROP Table sStudent.tTempStudent14
 
	END 
	 
	ELSE
	BEGIN
	    Select * into sStudent.tTempStudent
		FROM sStudent.vStudentCustomSearch SCS
		INNER JOIN sStudent.tTempStudent5 T5 ON SCS.StudentId = T5.StudentId1 OR @rCustomTagId = ''
		INNER JOIN sStudent.tTempStudent6 T6 ON SCS.StudentId = T6.StudentId2 OR @rCustomGroupId = ''
		INNER JOIN sStudent.tTempStudent7 T7 ON SCS.StudentId = T7.StudentId3 OR @rClubId = ''
		INNER JOIN sStudent.tTempStudent9 T9 ON SCS.StudentId = T9.StudentId4 OR @rHostelId = ''
		INNER JOIN sStudent.tTempStudent10 T10 ON SCS.StudentId = T10.StudentId5 OR @rBusRouteId = ''
		LEFT JOIN sStudent.tTempStudent11 T11 ON SCS.StudentId = T11.StudentId6
		LEFT JOIN  sStudent.tTempStudent12 T12 ON SCS.StudentId= T12.StudentId12 
		INNER JOIN sStudent.tTempStudent14 T14 ON SCS.StudentId = T14.StudentId14 OR @rRecordTagId = ''
		
		WHERE ((SCS.OrgId = @rOrgId) OR (@rOrgId = 0)) 
		AND ((SCS.BatchId = @BatchId) OR (@BatchId = 0)) 
		--AND ((SCS.Code Like @rCode + '%') OR (@rCode = ''))
		AND ((SCS.FirstName Like @rFirstName  + '%') OR (@rFirstName = ''))
		AND ((SCS.LastName Like @rLastName + '%')OR(@rLastName = ''))
		AND ((SCS.Hobby Like '%' + @rHobby + '%') OR (@rHobby = ''))
		AND ((ISNULL(SCS.PermanentCountry,'') Like @rCountry + '%') OR(@rCountry = ''))
		AND ((ISNULL(SCS.PermanentState,'') Like @rState + '%')OR(@rState = ''))
		AND ((ISNULL(SCS.DateOfBirth,'0001-01-01') >= @rDOBFromDate) OR (ISNULL(@rDOBFromDate,'') = ''))
		AND ((ISNULL(SCS.DateOfBirth,'9999-12-31') <= @rDOBToDate) OR (ISNULL(@rDOBToDate,'') = ''))
		AND ((ISNULL(SCS.AdmissionDate,'0001-01-01') >= @rDOAFromDate) OR (ISNULL(@rDOAFromDate,'') = ''))
		AND ((ISNULL(SCS.AdmissionDate,'9999-12-31') <= @rDOAToDate) OR (ISNULL(@rDOAToDate,'') = ''))
		AND ((ISNULL(SCS.LeftDate,'0001-01-01') >= @rDOLFromDate) OR (ISNULL(@rDOLFromDate,'') = ''))
		AND ((ISNULL(SCS.LeftDate,'9999-12-31') <= @rDOLToDate) OR (ISNULL(@rDOLToDate,'') = ''))
		AND (ISNULL(SCS.PermanentCity,0) IN( SELECT item FROM  sCommon.fnsplit(@rCity,','))OR @rCity='')
		AND (ISNULL(SCS.PermanentStreetThree,0) IN( SELECT item FROM  sCommon.fnsplit(@rArea,','))OR @rArea='')
		AND (SCS.DivisionId In( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionId,','))OR @rDivisionId='')
		AND (SCS.StatusId In( SELECT cast(item as int) FROM  sCommon.fnsplit(@rStatusId,','))OR @rStatusId='')
		AND (SCS.TransportModeId In( SELECT cast(item as int) FROM  sCommon.fnsplit(@rTransportModeId,','))OR @rTransportModeId='')
		AND (ISNULL(SCS.BloodGroupId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rBloodGroupId,','))OR @rBloodGroupId='')
		AND (ISNULL(SCS.GenderId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rGenderId,','))OR (@rGenderId=''))
		AND (ISNULL(SCS.ReligionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rReligionId,','))OR @rReligionId='')
		AND (ISNULL(SCS.CastCategoryId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rCastCategoryId,','))OR @rCastCategoryId='')
		AND (ISNULL(SCS.HouseId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rHouseId,','))OR @rHouseId='')
		AND (ISNULL(SCS.MotherTongueId,0) IN ( SELECT cast(item as int) FROM  sCommon.fnsplit(@rMotherTongueId,','))OR @rMotherTongueId='')
		AND (ISNULL(SCS.NationalityId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rNationalityId,','))OR @rNationalityId='')
		AND (ISNULL(SCS.BusRouteDestinationId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rBusRouteDestinationId,','))OR @rBusRouteDestinationId='')
		AND (ISNULL(SCS.FatherQualification,'') IN( SELECT item FROM  sCommon.fnsplit(@rFatherQualification,','))OR @rFatherQualification='')
		AND (ISNULL(SCS.FatherOccupation,'') IN( SELECT item FROM  sCommon.fnsplit(@rFatherOccupation,','))OR @rFatherOccupation='')
		AND (ISNULL(SCS.MotherQualification,'') IN( SELECT item FROM  sCommon.fnsplit(@rMotherQualification,','))OR @rMotherQualification='')
		AND (ISNULL(SCS.MotherOccupation,'') IN( SELECT item FROM  sCommon.fnsplit(@rMotherOccupation,','))OR @rMotherOccupation='')
		AND (ISNULL(SCS.AdmissionCategoryId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rAdmissionCategoryId,','))OR @rAdmissionCategoryId='')
		AND (ISNULL(SCS.PreviousSchool,'') IN( SELECT item FROM  sCommon.fnsplit(@rPreviousSchool,','))OR @rPreviousSchool='')
		AND (ISNULL(SCS.RepeatCount,0) IN( SELECT item FROM  sCommon.fnsplit(@rRepeatCount,','))OR @rRepeatCount='')
		AND (ISNULL(SCS.StudentStatusId,0) IN( SELECT item FROM  sCommon.fnsplit(@rStudentStatusId,','))OR @rStudentStatusId='')
		AND (ISNULL(SCS.StudentGroupId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rStudentGroupId,','))OR @rStudentGroupId='')
		AND (ISNULL(SCS.StudentOtherGroupId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rStudentOtherGroupId,','))OR @rStudentOtherGroupId='')
		AND ((SCS.IsPysicalDeformity=@rIsPysicalDeformity) OR (@rIsPysicalDeformity=0))
		AND ((SCS.IsMajorIllness=@rIsMajorIllness) OR (@rIsMajorIllness=0))
		AND ((SCS.IsBlackList=@rIsBlackList) OR (@rIsBlackList=0))
		--AND ((REPLICATE(0, 50 - LEN(SCS.Code)) + SCS.Code) >= (REPLICATE(0, 50 - LEN(@rFromCode)) + @rFromCode) OR (@rFromCode='') OR (@rFromCode=0))	-- Add @rFromCode=0 for MantisId : 0029214
		--AND ((REPLICATE(0, 50 - LEN(SCS.Code)) + SCS.Code) <= (REPLICATE(0, 50 - LEN(@rToCode)) + @rToCode) OR (@rToCode='') OR (@rToCode=0))			-- Add @rToCode=0 for MantisId : 0029214
		AND ((REPLICATE(0, 50 - LEN(SCS.Code)) + SCS.Code) >= (REPLICATE(0, 50 - LEN(@rFromCode)) + @rFromCode) OR (@rFromCode=''))			-- MantisId : 0032524
		AND ((REPLICATE(0, 50 - LEN(SCS.Code)) + SCS.Code) <= (REPLICATE(0, 50 - LEN(@rToCode)) + @rToCode) OR (@rToCode=''))				-- MantisId : 0032524
		AND ((SCS.Code IN(SELECT Code FROM @ListofCodes)) OR (ISNULL(@rSpecificCode,'') = ''))
		AND ((SCS.StatusId = @rDropDownStatusId) OR (@rDropDownStatusId=0))
		AND ((SCS.ClassId = @rDropDownClassId) OR (@rDropDownClassId=0))
		AND ((SCS.DivisionId = @rDropDownDivisionId) OR (@rDropDownDivisionId=0))
		AND (ISNULL(SCS.BusRouteId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rBusRouteId,','))OR @rBusRouteId='')
		AND (ISNULL(SCS.ExemptionTypeId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeExemption,','))OR @rFeeExemption='')
		AND ((SCS.PresentContactNo=@rContactNo) OR (SCS.PermanentContactNo=@rContactNo) OR (SCS.EmergencyContactNo=@rContactNo) OR (SCS.ParentContactno=@rContactNo) OR (SCS.StudentContactNo=@rContactNo) OR (SCS.FatherContactNo=@rContactNo) OR (SCS.MotherContactNo=@rContactNo) OR (@rContactNo=''))
		--AND (ISNULL(SCS.CustomTagId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rCustomTagId,','))OR @rCustomTagId='')
		--Select * from sStudent.tTempStudent return	
		AND ((SCS.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))
		AND (( DAY(CONVERT(date,SCS.DateOfBirth)) = @rBirthDay) OR (@rBirthDay = 0))
	    AND (( MONTH(CONVERT(date,SCS.DateOfBirth)) = @rDateOfMonth) OR (@rDateOfMonth = 0))
		AND ((SCS.IsStopApplicationAccess = @rStopApplicationAccess) OR (@rStopApplicationAccess = -1))		
				--Select * From sStudent.tTempStudent
		set @sql = 'SELECT '+ @rColumnName+' FROM sStudent.tTempStudent ORDER BY '+@rOrderBy
		
		
		if(@rColumnName='ID No')
		BEGIN
			SET @sql=Replace(@sql,'SELECT Code','SELECT Code AS [ID No]')
		END
		if(@rColumnName='GR No')
		BEGIN
			SET @sql=Replace(@sql,'SELECT Code','SELECT Code AS [GR No]')
		END
		
		exec(@Sql)
			
		DROP Table sStudent.tTempStudent
		DROP Table sStudent.tTempStudent5
		DROP Table sStudent.tTempStudent6
		DROP Table sStudent.tTempStudent7
		DROP Table sStudent.tTempStudent9
		DROP Table sStudent.tTempStudent10
		DROP Table sStudent.tTempStudent12
		
	    
	    
	END 
	 
	 
END
GO
PRINT N'Altering Procedure [sStudent].[pStudentMasterAdd]...';


GO
ALTER PROCEDURE [sStudent].[pStudentMasterAdd]
	 
	@rId bigint,
	@rCode nvarchar(20),
	@rRegistrationNumber nvarchar(20),
	@rNumber bigint,
	@rFirstName nvarchar(100),
	@rMiddleName nvarchar(100),
	@rLastName nvarchar(100),
	@rOrgId int,
	--@rDepartmentId int,
	@rAdmissionCategoryId int,
	@rStatusId smallint,
	@rRecordStatusId smallint,
	@rCreatedUserId bigint,
	@rUpdatedUserId bigint,
	@rOrgGroupBatchId int =0,
	@OutStudentId BIGINT = NULL OUTPUT,
	@rSUId nvarchar(50) = '',
	@rPENNumber bigint = 0, --Mantis - 0031338
	@rOrgGroupId int = 0,
	@rMobileNo nvarchar(50)='',
	@rStudentGroupId int=0,
	@rStudentOtherGroupId int=0,
	@rDateOfBirth Date=NULL,
    @rGenderId int=0,
    @rAcademicId bigint = 0,
	@rBirthDateInWord nvarchar(150)='',
	@rTransportModeId int = 0,
	@rLocalName nvarchar(100) = '',	--add for mantis: 32197
	@rApaarIdNumber nvarchar(50) = '' --Added by dhananjay for Mantis - 38255
	
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	--UPDATE sStudent.tAcademic SET ClassStatusId = 1 WHERE ClassStatusId is null WHERE Id = 
	
	--if(@rStatusId=3)
	--UPDATE A
	--	SET ClassStatusId = 3
	--	FROM sStudent.tAcademic A
	--	INNER JOIN sStudent.tStudentMaster SM ON A.StudentId = SM.Id
	--	--INNER JOIN sStudent.tStudentAdmission SA ON A.StudentId = SA.StudentId AND A.ClassId = SA.LeftStandardId
	--	WHERE SM.StatusId = 3 AND A.Id = @rAcademicId
	--else if(@rStatusId=1)
	--UPDATE A
	--SET ClassStatusId = 1
	--	FROM sStudent.tAcademic A
	--	INNER JOIN sStudent.tStudentMaster SM ON A.StudentId = SM.Id
	--	--INNER JOIN sStudent.tStudentAdmission SA ON A.StudentId = SA.StudentId AND A.ClassId = SA.LeftStandardId
	--	WHERE SM.StatusId = 3 AND A.Id = @rAcademicId
	
	Declare @lStudCap int,@lOrgStudentCap int
	--IF(@rNumber=0)
	--SET @rNumber=NULL
	IF(@rId=0)
	BEGIN		 
	 
		--IF((@rCode = Null) OR (@rCode = ''))	
		--BEGIN

		--	EXECUTE sCommon.pPrefixSetupNextNumberGet @rOrgId = @rOrgId, @rPrefixFunctionalityId = 2001,@rStoreLocationId = 0, @rNextNumber = @rCode OUTPUT

		--	SET @rCode = ISNULL(@rCode, '-300')

		--	IF @rCode = '-300'
		--	BEGIN
		--		 SELECT -300 AS Result, '' AS Code, 0 AS Id 
		--		 RETURN
		--	END
		--END
		--ELSE
		--BEGIN
			Select @lStudCap=ISNULL(NoOfStudent,0)+ISNULL(StudentExtraCap,0) from
			sSetup.tOrgGroupSetting Where OrgGroupId= @rOrgGroupId
			
			Select @lOrgStudentCap=[sSetup].[fStudentCapGet](@rOrgGroupBatchId)
			 
			IF(@lOrgStudentCap > @lStudCap )
			BEGIN
				Select -111 AS RESULT, '' AS Code, @lStudCap AS Id 
				Return
			END
			
			IF EXISTS (SELECT SM.Id FROM sStudent.tStudentMaster SM INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SM.OrgId
					   WHERE SM.SUId=@rSUId AND OM.OrgGroupId=@rOrgGroupId)
			BEGIN
				SELECT -101 AS RESULT, '' AS Code, 0 AS Id 
				RETURN
			END 
			ELSE IF EXISTS (SELECT Id from sStudent.tStudentMaster WHERE Code=@rCode AND OrgId=@rOrgId)
			BEGIN
				SELECT -100 AS RESULT, '' AS Code, 0 AS Id 
				RETURN
			END 
			ELSE IF EXISTS (SELECT Id from sStudent.tStudentMaster WHERE ISNULL(@rRegistrationNumber,'')!='' AND RegistrationNumber=@rRegistrationNumber AND OrgId=@rOrgId)
			BEGIN
				SELECT -200 AS RESULT, '' AS Code, 0 AS Id 
				RETURN
			END 
			--Mantis Start - 0031338
			ELSE IF(@rPENNumber > 0)
			BEGIN
				IF EXISTS (SELECT SM.Id FROM sStudent.tStudentMaster SM INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SM.OrgId
						   WHERE SM.PENNumber=@rPENNumber AND SM.OrgId = @rOrgId AND SM.StatusId = 1 AND SM.Id NOT IN (SELECT ReferenceSourceId FROM sStudent.tStudentMaster)) 
						   --Mantis - 44014(OrgGroupId to OrgId)
				BEGIN
					SELECT -400 AS RESULT, '' AS Code, 0 AS Id 
					RETURN
				END 
			END
			--Mantis End - 0031338

			--Added by dhananjay for Mantis - 38255
			IF(Len(@rApaarIdNumber) > 0)
			BEGIN
				IF EXISTS (SELECT SM.Id FROM sStudent.tStudentMaster SM INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SM.OrgId
						WHERE SM.ApaarIdNumber=@rApaarIdNumber AND SM.OrgId = @rOrgId AND SM.StatusId = 1 AND SM.Id NOT IN (SELECT ReferenceSourceId FROM sStudent.tStudentMaster))  
						--Mantis - 44014(OrgGroupId to OrgId)
				BEGIN
					SELECT -500 AS RESULT, '' AS Code, 0 AS Id 
					RETURN
				END 
			END
			--Added by dhananjay for Mantis - 38255
		--END
	END
	ELSE
	BEGIN
	
		Select @lStudCap=ISNULL(NoOfStudent,0)+ISNULL(StudentExtraCap,0) from
		sSetup.tOrgGroupSetting Where OrgGroupId= @rOrgGroupId
		
		Select @lOrgStudentCap=[sSetup].[fStudentCapGet](@rOrgGroupBatchId)
		 
		IF(@lOrgStudentCap > @lStudCap AND (@rStatusId = 1 OR @rStatusId = 2))
		BEGIN
			Select -111 AS RESULT, '' AS Code, @lStudCap AS Id 
			Return
		END
	
		DECLARE @lReferenceSourceId bigint=0
		SELECT @lReferenceSourceId = ISNULL(ReferenceSourceId,0)  FROM sStudent.tStudentMaster WHERE Id = @rId
		
		IF(@lReferenceSourceId=0)
			SELECT @lReferenceSourceId = Id FROM sStudent.tStudentMaster WHERE ReferenceSourceId = @rId
		IF(@lReferenceSourceId = 0)
		BEGIN 
			IF EXISTS (SELECT SM.Id FROM sStudent.tStudentMaster SM INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SM.OrgId
						   WHERE SM.SUId=@rSUId AND OM.OrgGroupId=@rOrgGroupId AND SM.Id!=@rId)
			BEGIN
				SELECT -101 AS RESULT, '' AS Code, 0 AS Id 
				RETURN
			END 
		END
		 
		IF EXISTS (SELECT Id from sStudent.tStudentMaster WHERE Code=@rCode AND OrgId=@rOrgId AND Id!=@rId)
		BEGIN
			SELECT -100 AS RESULT, '' AS Code, 0 AS Id 
			RETURN
		END 
		ELSE IF EXISTS (SELECT Id from sStudent.tStudentMaster WHERE RegistrationNumber=@rRegistrationNumber AND OrgId=@rOrgId AND Id!=@rId)
		BEGIN
			SELECT -200 AS RESULT, '' AS Code, 0 AS Id 
			RETURN
		END 
		--Mantis Start - 0031338
		ELSE IF(@rPENNumber > 0)
		BEGIN
		--IF(@lReferenceSourceId = 0)  --add this condition for mantis Id:0036628
		--BEGIN 
			IF EXISTS (SELECT SM.Id FROM sStudent.tStudentMaster SM INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SM.OrgId
					   WHERE SM.PENNumber=@rPENNumber  AND SM.OrgId = @rOrgId AND SM.StatusId = 1  AND SM.Id!=@rId AND ISNULL(SM.ReferenceSourceId,0) != @rId
					   AND SM.Id != (SELECT ISNULL(ReferenceSourceId,0)  FROM sStudent.tStudentMaster WHERE Id = @rId))			-- --Added by dhananjay for Mantis - 41797
			BEGIN
				SELECT -400 AS RESULT, '' AS Code, 0 AS Id 
				RETURN
			END 
		--END
		END
		--Mantis End - 0031338
		--Added by dhananjay for Mantis - 38255
		IF(Len(@rApaarIdNumber) > 0)
		BEGIN
		--IF(@lReferenceSourceId = 0) --add this condition for mantis Id:0036628
			--BEGIN
			IF EXISTS (SELECT SM.Id FROM sStudent.tStudentMaster SM INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SM.OrgId
					WHERE SM.ApaarIdNumber=@rApaarIdNumber AND SM.OrgId = @rOrgId AND SM.StatusId = 1 AND SM.Id!=@rId AND ISNULL(SM.ReferenceSourceId,0) != @rId
					AND SM.Id != (SELECT ISNULL(ReferenceSourceId,0)  FROM sStudent.tStudentMaster WHERE Id = @rId))		--Added by dhananjay for Mantis - 41797
				BEGIN
					SELECT -500 AS RESULT, '' AS Code, 0 AS Id 
					RETURN
				END 
			--END
		END
		--Added by dhananjay for Mantis - 38255
	END
	
	BEGIN TRY
	
	 BEGIN TRANSACTION	
	IF(@rId=0)
	BEGIN	
	DECLARE @lNextNumber BIGINT     
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sStudent.tStudentMaster', 0, 1, 1,@outNextNumber = @lNextNumber output

	IF(@rNumber=0)
	BEGIN
	SET @rNumber=@lNextNumber
	END
	INSERT INTO sStudent.tStudentMaster
		(
			Id,
			Code,
			Number,
			RegistrationNumber,
			FirstName,
			MiddleName,
			LastName,
			OrgId,
			--DepartmentId,
			AdmissionCategoryId,
			StatusId,
			RecordStatusId,
			CreatedUserId,
			CreatedDateTime,
		    SUId,
		    StudentGroupId,
		    StudentOtherGroupId,
			PENNumber, --Mantis - 0031338
			LocalName,	--add for mantis: 32197
			ApaarIdNumber  --Added by dhananjay for Mantis - 38255
		)
	VALUES
		(
			@lNextNumber,
			@rCode,
			@rNumber,
			@rRegistrationNumber,
			@rFirstName,
			@rMiddleName,
			@rLastName,
			@rOrgId,
			--@rDepartmentId,
			@rAdmissionCategoryId,
			@rStatusId,
			@rRecordStatusId,
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rSUId,
			@rStudentGroupId ,
			@rStudentOtherGroupId ,
			@rPENNumber, --Mantis - 0031338
			@rLocalName	,	--add for mantis: 32197
			@rApaarIdNumber  --Added by dhananjay for Mantis - 38255
		)
		
		INSERT INTO sStudent.tStudentOther
		(
			StudentId,
			DateOfBirth,
			GenderId,
			CreatedUserId,
			CreatedDateTime,
			BirthDateInWord,
			TransportModeId
		)
		VALUES
		(
			@lNextNumber,
			@rDateOfBirth,
			@rGenderId,
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rBirthDateInWord,
			@rTransportModeId
		)
		----IF(@rMobileNo!='')
		--BEGIN
			INSERT INTO sStudent.tStudentCommunication
			(
				StudentId,
				ParentContactNo,
				CreatedUserId,
				CreatedDateTime
			)
			VALUES
			(
				@lNextNumber,
				@rMobileNo,
				@rCreatedUserId,
				sCommon.fGetDate()
			)
		--END
		      
	END	 
	 ELSE
	 BEGIN
	 SET @lNextNumber = @rId
			IF(@rNumber=0)
			BEGIN
			SET  @rNumber=(SELECT ISnull(Number,0) FROM sStudent.tStudentMaster WHERE  Id=@rId)
			IF(@rNumber=0)
			SET @rNumber=@lNextNumber
			END
	    UPDATE  sStudent.tStudentMaster
	    SET
			--Code=@rCode,
			Number=@rNumber,
			RegistrationNumber=@rRegistrationNumber,
			FirstName=@rFirstName,
			MiddleName=@rMiddleName,
			LastName=@rLastName,
			--OrgId=@rOrgId,
			--DepartmentId=@rDepartmentId,
			AdmissionCategoryId=@rAdmissionCategoryId,
			StatusId=@rStatusId,
			RecordStatusId=@rRecordStatusId,
	        UpdatedUserId=@rUpdatedUserId,
	        UpdatedDateTime=sCommon.fGetDate(),
			SUId=@rSUId,
			StudentGroupId=@rStudentGroupId ,
		    StudentOtherGroupId=@rStudentOtherGroupId,
			PENNumber=@rPENNumber, --Mantis - 0031338
			LocalName=@rLocalName,	--add for mantis: 32197
			ApaarIdNumber =@rApaarIdNumber  --Added by dhananjay for Mantis - 38255
	      
	      WHERE Id = @rId 
	      
	    UPDATE  sStudent.tStudentOther
		SET
			DateOfBirth=@rDateOfBirth,
			GenderId=@rGenderId,
	        UpdatedUserId=@rUpdatedUserId,
	        UpdatedDateTime=sCommon.fGetDate(),
			BirthDateInWord = @rBirthDateInWord,
			TransportModeId = @rTransportModeId
	      WHERE StudentId = @rId 
	     
	     
	     IF(@rStatusId=3)
		BEGIN
		    UPDATE sSecurity.tUser
			   SET IsObsolete=1 
			WHERE SourceTypeId=2003 AND SourceId=@rId
		END
	 END  
	 
		SET @OutStudentId = @lNextNumber
	  SELECT 1 AS Result, @rCode AS Code, @lNextNumber AS Id 
		--SELECT @lNextNumber AS Result
	
	
	
		COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Altering Procedure [sCommunication].[pAssignmentListGet]...';


GO
ALTER PROCEDURE [sCommunication].[pAssignmentListGet] 
	@rBatchId INT
	,@rUserId BIGINT
	,@rUserSourceId BIGINT
	,@rUserSourceTypeId INT
	,@rSyncedAssignmentId BIGINT = 0
	,@rName NVARCHAR(100) = ''
	,@rFromDate DATE = ''
	,@rToDate DATE = ''
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	DECLARE @lOrgGroupBatchId INT = 0

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

	--DECLARE @lDivisionId int
	--SELECT @lDivisionId = DivisionId FROM sStudent.tAcademic WHERE StudentId = @rStudentId AND BatchId = @rBatchId
	DECLARE @lConfigValue NVARCHAR(50)
	DECLARE @lIsAssignmentBasedOnApproval BIT = 0

	SELECT @lConfigValue = ItemValue
	FROM sConfig.tConfigurationSetup
	WHERE ConfigurationId = 329
		AND SourceTypeId = 2010
		AND SourceId = LEFT(@lOrgGroupBatchId, 4)

	IF (@lConfigValue IS NULL)
		OR (@lConfigValue = 'False')
		SET @lIsAssignmentBasedOnApproval = 0
	ELSE
		SET @lIsAssignmentBasedOnApproval = 1

	BEGIN
		SET @rName = sCommon.fSearchStringGet(@rName)
	END

	IF @rUserSourceTypeId = 2003 -- For Student Login
	BEGIN
		IF OBJECT_ID(N'tempdb..#DivisionData') IS NOT NULL
		BEGIN
			DROP TABLE #DivisionData
		END

		SELECT A.DivisionId, DM.ClassId
		INTO #DivisionData
		FROM sStudent.tAcademic A
		INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = A.DivisionId --Added for mantis : 42198
		WHERE A.StudentId = @rUserSourceId AND A.BatchId = @rBatchId
		

		;WITH AssignmentBase AS (
			SELECT A1.Id AS AssignmentId,
				   A1.SubjectId,
				   SM.Title AS SubjectName,
				   A1.Title,
				   A1.Remark,
				   A1.StartDate,
				   A1.EndDate,
				   --0 AS UserId,
				   --(SELECT Userid FROM sCommunication.tAssignmentView  WHERE AssignmentId = A1.Id AND UserId = @rUserId) AS UserId,
				   ISNULL(AV.UserId, 0) AS UserId,
				   U.DisplayTitle AS CreatedUserName,
				   SM.OrgId,
				   ISNULL(A1.IsAssignmentDocumentUpload, 0) AS IsAssignmentDocumentUpload,
				   A1.CreatedDateTime,
				   CS.IsOptional,
				   CS.Id AS ClassSubjectId,
				   AS1.SourceId
			FROM sCommunication.tAssignment A1
			INNER JOIN sCommunication.tAssignmentScope AS1 ON AS1.AssignmentId = A1.Id
			INNER JOIN #DivisionData D ON D.DivisionId = AS1.SourceId AND AS1.SourceTypeId = 2005
			INNER JOIN sSetup.tSubjectMaster SM ON SM.Id = A1.SubjectId
			INNER JOIN sSetup.tClassSubject CS ON CS.SubjectId = A1.SubjectId AND D.ClassId = CS.ClassId
			INNER JOIN sSecurity.tUser U ON U.Id = A1.CreatedUserId
			LEFT JOIN sCommunication.tAssignmentView AV ON AV.AssignmentId = A1.Id AND UserId = @rUserId
			WHERE A1.BatchId = @rBatchId
			AND (
				A1.Id > @rSyncedAssignmentId
				OR @rSyncedAssignmentId = 0
				)
			AND (CAST(A1.CreatedDateTime AS DATE) >= CAST(@rFromDate AS DATE)
				--Convert(DATE, A1.CreatedDateTime) >= convert(DATE, @rFromDate)
				OR ISNULL(@rFromDate, '') = ''
				)
			AND (
				CAST(A1.CreatedDateTime AS DATE) <= CAST(@rToDate AS DATE)
				--Convert(DATE, A1.CreatedDateTime) <= convert(DATE, @rToDate)
				OR ISNULL(@rToDate, '') = ''
				)
			AND (
				A1.Title LIKE @rName
				OR ISNULL(@rName, '') = ''
				)
			AND (
				(@lIsAssignmentBasedOnApproval = 0)
				OR (
					@lIsAssignmentBasedOnApproval = 1
					AND A1.StatusId = 550
					)
				)
		)
		SELECT AB.AssignmentId, AB.SubjectId, AB.SubjectName, AB.Title, AB.Remark,
			   AB.StartDate, AB.EndDate, AB.UserId, AB.CreatedUserName, AB.OrgId, AB.IsAssignmentDocumentUpload
		FROM AssignmentBase AB
		WHERE AB.IsOptional = 0

		UNION

		SELECT AB.AssignmentId, AB.SubjectId, AB.SubjectName, AB.Title, AB.Remark,
			   AB.StartDate, AB.EndDate, AB.UserId, AB.CreatedUserName, AB.OrgId, AB.IsAssignmentDocumentUpload
		FROM AssignmentBase AB
		INNER JOIN sAssessment.tOptionalSubject OS ON OS.ClassSubjectId = AB.ClassSubjectId
		INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId = OS.AcademicId
										  AND SA.DivisionId = AB.SourceId
										  AND SA.ClassId = AB.ClassSubjectId
		WHERE AB.IsOptional = 1 AND SA.StudentId = @rUserSourceId

		--SELECT A1.Id AS AssignmentId
		--	,A1.SubjectId
		--	,SM.Title AS SubjectName
		--	,A1.Title
		--	,A1.Remark
		--	,A1.StartDate
		--	,A1.EndDate
		--	,ISNULL(AV.UserId, 0) AS UserId
		--	,U.DisplayTitle AS CreatedUserName
		--	,SM.OrgId
		--	,ISNULL(A1.IsAssignmentDocumentUpload, 0) AS IsAssignmentDocumentUpload
		--FROM sCommunication.tAssignment A1
		--INNER JOIN sCommunication.tAssignmentScope AS1 ON AS1.AssignmentId = A1.Id
		--INNER JOIN #DivisionData D ON D.DivisionId = AS1.SourceId AND AS1.SourceTypeId = 2005
		----INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = AS1.SourceId --Added for mantis : 42198
		--INNER JOIN sSetup.tSubjectMaster SM ON SM.Id = A1.SubjectId
		--INNER JOIN [sSetup].[tClassSubject] CS ON CS.SubjectId = A1.SubjectId AND D.ClassId = CS.ClassId --Added for mantis : 42198
		--INNER JOIN sSecurity.tUser U ON U.Id = A1.CreatedUserId
		--LEFT JOIN sCommunication.tAssignmentView AV ON AV.AssignmentId = A1.Id AND UserId = @rUserId
		--WHERE CS.IsOptional = 0 --Added for mantis : 42198
		--	AND A1.BatchId = @rBatchId
		--	AND (
		--		A1.Id > @rSyncedAssignmentId
		--		OR @rSyncedAssignmentId = 0
		--		)
		--	AND (
		--		Convert(DATE, A1.CreatedDateTime) >= convert(DATE, @rFromDate)
		--		OR ISNULL(@rFromDate, '') = ''
		--		)
		--	AND (
		--		Convert(DATE, A1.CreatedDateTime) <= convert(DATE, @rToDate)
		--		OR ISNULL(@rToDate, '') = ''
		--		)
		--	AND (
		--		A1.Title LIKE @rName
		--		OR ISNULL(@rName, '') = ''
		--		)
		--	AND (
		--		(@lIsAssignmentBasedOnApproval = 0)
		--		OR (
		--			@lIsAssignmentBasedOnApproval = 1
		--			AND A1.StatusId = 550
		--			)
		--		)
		----Order by A1.CreatedDateTime DESC 
		
		--UNION
		
		----Added this query for mantis : 42198
		--SELECT A1.Id AS AssignmentId
		--	,A1.SubjectId
		--	,SM.Title AS SubjectName
		--	,A1.Title
		--	,A1.Remark
		--	,A1.StartDate
		--	,A1.EndDate
		--	,ISNULL(AV.UserId, 0) AS UserId
		--	,U.DisplayTitle AS CreatedUserName
		--	,SM.OrgId
		--	,ISNULL(A1.IsAssignmentDocumentUpload, 0) AS IsAssignmentDocumentUpload
		--FROM sCommunication.tAssignment A1
		--INNER JOIN sCommunication.tAssignmentScope AS1 ON AS1.AssignmentId = A1.Id
		--INNER JOIN  #DivisionData D ON D.DivisionId = AS1.SourceId AND AS1.SourceTypeId = 2005
		----(
		----	SELECT A.DivisionId
		----	FROM sStudent.tAcademic A
		----	WHERE A.StudentId = @rUserSourceId
		----		AND A.BatchId = @rBatchId
		----	) D ON D.DivisionId = AS1.SourceId
		----INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = AS1.SourceId 
		--INNER JOIN sSetup.tSubjectMaster SM ON SM.Id = A1.SubjectId
		--INNER JOIN [sSetup].[tClassSubject] CS ON CS.SubjectId = A1.SubjectId AND D.ClassId = CS.ClassId
		--INNER JOIN [sAssessment].[tOptionalSubject] AS OS ON OS.ClassSubjectId = CS.Id
		--INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId = OS.AcademicId AND CS.ClassId = SA.ClassId AND SA.DivisionId = AS1.SourceId
		--INNER JOIN sSecurity.tUser U ON U.Id = A1.CreatedUserId
		--LEFT JOIN sCommunication.tAssignmentView AV ON AV.AssignmentId = A1.Id AND UserId = @rUserId
		--WHERE CS.IsOptional = 1
		--	AND SA.StudentId = @rUserSourceId
		--	AND A1.BatchId = @rBatchId
		--	AND (
		--		A1.Id > @rSyncedAssignmentId
		--		OR @rSyncedAssignmentId = 0
		--		)
		--	AND (
		--		Convert(DATE, A1.CreatedDateTime) >= convert(DATE, @rFromDate)
		--		OR ISNULL(@rFromDate, '') = ''
		--		)
		--	AND (
		--		Convert(DATE, A1.CreatedDateTime) <= convert(DATE, @rToDate)
		--		OR ISNULL(@rToDate, '') = ''
		--		)
		--	AND (
		--		A1.Title LIKE @rName
		--		OR ISNULL(@rName, '') = ''
		--		)
		--	AND (
		--		(@lIsAssignmentBasedOnApproval = 0)
		--		OR (
		--			@lIsAssignmentBasedOnApproval = 1
		--			AND A1.StatusId = 550
		--			)
		--		)
		--	--Order by A1.CreatedDateTime DESC 
	END
	ELSE
	BEGIN
		--IF @rUserSourceTypeId   = 2003 -- For Student Login
		SELECT A1.Id AS AssignmentId
			,A1.SubjectId
			,SM.Title AS SubjectName
			,A1.Title
			,A1.Remark
			,A1.StartDate
			,A1.EndDate
			,ISNULL(AV.UserId, 0) AS UserId
			,U.DisplayTitle AS CreatedUserName
			,SM.OrgId
			,ISNULL(A1.IsAssignmentDocumentUpload, 0) AS IsAssignmentDocumentUpload
		FROM sCommunication.tAssignment A1
		INNER JOIN sSetup.tSubjectMaster SM ON SM.Id = A1.SubjectId
		LEFT JOIN sCommunication.tAssignmentView AV ON AV.AssignmentId = A1.Id
			AND UserId = @rUserId
		INNER JOIN sCommunication.tAssignmentScope AS1 ON AS1.AssignmentId = A1.Id
		INNER JOIN (
			SELECT EJD.OrganizationDepartmentId
			FROM sHrm.tEmployeeMaster EM
			INNER JOIN sHrm.tEmployeeJobDetail EJD ON EM.Id = EJD.EmployeeId
			WHERE EM.Id = @rUserSourceId
				AND ISNULL(EM.IsOtherUser, 0) = 0
			) D ON D.OrganizationDepartmentId = AS1.SourceId
			AND AS1.SourceTypeId = 2017
		INNER JOIN sSecurity.tUser U ON U.Id = A1.CreatedUserId
		WHERE A1.BatchId = @rBatchId
			AND (
				A1.Id > @rSyncedAssignmentId
				OR @rSyncedAssignmentId = 0
				)
			AND (
				Convert(DATE, A1.CreatedDateTime) >= convert(DATE, @rFromDate)
				OR ISNULL(@rFromDate, '') = ''
				)
			AND (
				Convert(DATE, A1.CreatedDateTime) <= convert(DATE, @rToDate)
				OR ISNULL(@rToDate, '') = ''
				)
			AND (
				A1.Title LIKE @rName
				OR ISNULL(@rName, '') = ''
				)
		ORDER BY A1.CreatedDateTime DESC
	END
END
GO
PRINT N'Altering Procedure [sFee].[pConsolidateFeeStatusDashboardGet]...';


GO
ALTER PROCEDURE [sFee].[pConsolidateFeeStatusDashboardGet]
	@rType int =0,
	@rCommonOrgGroupBatchId int=0,
	@rOrgGroupId smallint=0,
	@rReceiptBookId int =0,
	@rOrgId int  =0,
	@rFeeHeadId int =0,
	@rFeeId int =0
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 

DECLARE @lIsLogEnable bit = 0

IF(@lIsLogEnable = 1)
BEGIN

	INSERT INTO [sSystem].[tTraceLog]
	(LogMessage, ExtraLogMessage, ExceptionLog, ExceptionDetailLog, CreatedDateTime, PagePath)
	VALUES
	('Type: ' + CAST(@rType AS nvarchar(100)), 
	+ '@rCommonOrgGroupBatchId = ' +  CAST(@rCommonOrgGroupBatchId AS nvarchar(100)) 
	+ ', @rOrgGroupId = ' +  CAST(@rOrgGroupId AS nvarchar(100))
	+ ', @rReceiptBookId = ' +  CAST(@rReceiptBookId AS nvarchar(100))
	+ ', @rOrgId = ' +  CAST(@rOrgId AS nvarchar(100))   
	+ ', @rFeeHeadId = ' +  CAST(@rFeeHeadId AS nvarchar(100))  
	+ ', @rFeeId = ' +  CAST(@rFeeId AS nvarchar(100)), 
	'',
	'', 
	GETDATE(), 
	'[sFee].[pConsolidateFeeStatusDashboardGet]')
END

--Changes for Mantis Id: 0039838
DECLARE @lConfigValue nvarchar(50)='', @lFromTime nvarchar(50)='', @lToTime nvarchar(50)='';

SELECT @lConfigValue = ItemValue FROM sConfig.tConfigurationSetup WITH (NOLOCK) WHERE ConfigurationId = 592   AND SourceTypeId = 2010   AND SourceId = @rOrgGroupId;

WITH SplitData AS (SELECT cast(item AS nvarchar(50)) AS item, ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) AS RowNum
    FROM sCommon.fnsplit(@lConfigValue, '-')
)
SELECT 
    @lFromTime = MAX(CASE WHEN RowNum = 1 THEN item END),
    @lToTime = MAX(CASE WHEN RowNum = 2 THEN item END)
FROM SplitData;


IF(@lConfigValue <> '' AND (CAST(CAST(GETDATE() AS DATE) AS DATETIME) + @lToTime) < (CAST(CAST(GETDATE() AS DATE) AS DATETIME) + @lFromTime))
BEGIN
	SET @lToTime = CAST(CAST((GETDATE()+1) AS DATE) AS DATETIME) + @lToTime
END
ELSE
BEGIN
	SET @lToTime = (CAST(CAST(GETDATE() AS DATE) AS DATETIME) + @lToTime)
END

IF(@lConfigValue <> '' AND (GETDATE() NOT BETWEEN (CAST(CAST(GETDATE() AS DATE) AS DATETIME) + @lFromTime) AND @lToTime))
BEGIN
	RETURN
END

	IF OBJECT_ID('tempdb..#TempFeeSetupData') IS NOT NULL DROP TABLE #TempFeeSetupData
	
	SELECT * 
	INTO #TempFeeSetupData
	FROM 
	(
		SELECT 
			FS1.FeeId,
			FS1.Id,
			ISNULL(FS1.Amount,0)AS Amount,
			ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
			FM.Title AS FeeName,
			FM.Id AS FeeMasterId,
			SA1.AcademicId,
			FM.FeeHeadId,
			FM.OrderIndex
		FROM sFee.tFeeSetup FS1 WITH (NOLOCK)
		INNER JOIN sStudent.vStudentAcademic SA1 WITH (NOLOCK) ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
		INNER JOIN sFee.tFeeMaster FM WITH (NOLOCK) ON FM.Id=FS1.FeeId
		WHERE FS1.IsOptional=0

		UNION ALL
				
		SELECT 
			FS1.FeeId,
			FS1.Id,
			ISNULL(FS1.Amount,0)AS Amount,
			ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
			FM.Title AS FeeName,
			FM.Id AS FeeMasterId,
			SA1.AcademicId,
			FM.FeeHeadId,
			FM.OrderIndex
		FROM sFee.tFeeSetup FS1 WITH (NOLOCK)
		INNER JOIN sFee.tFeeOptional FO WITH (NOLOCK) ON FO.FeeSetupId=FS1.Id 
		INNER JOIN sFee.tFeeMaster FM WITH (NOLOCK) ON FM.Id=FS1.FeeId
		INNER JOIN sStudent.vStudentAcademic SA1 WITH (NOLOCK) ON SA1.AcademicId=FO.SourceId AND FS1.BatchId = SA1.BatchId
		AND SA1.ClassId=FS1.ClassId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
		WHERE FS1.IsOptional=1
	) AS A

	IF (@rType = 1)
	BEGIN
		
		SELECT 
			RBM.Id AS ReceiptBookId,
			RBM.Title AS ReceiptBook,
			SUM(ISNULL(R.PaidAmount,0)) AS PaidAmount,
			SUM(ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00))AS PendingAmount,
			SUM(ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)) AS Total,
			RBM.OrderIndex
		FROM 
			sStudent.vStudentAcademic SA WITH (NOLOCK)
			INNER JOIN sStudent.tStudentAdmission tSA WITH (NOLOCK) ON tSA.StudentId = SA.StudentId
			INNER JOIN #TempFeeSetupData FS ON FS.AcademicId=SA.AcademicId
			LEFT JOIN sFee.tFeeAllocation FA WITH (NOLOCK) 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 WITH (NOLOCK)
					INNER JOIN sFee.tReceiptDetail RD WITH (NOLOCK) ON RD.ReceiptId = R.Id 
					INNER JOIN sFee.tFeeSetup FS WITH (NOLOCK) ON RD.FeeSetupId = FS.Id
					INNER JOIN sFee.tFeeMaster FM WITH (NOLOCK) ON FS.FeeId = FM.Id
					INNER JOIN sStudent.vStudentAcademic SA1 WITH (NOLOCK) ON SA1.AcademicId=R.SourceId 
					INNER JOIN sStudent.tStudentAdmission tSA WITH (NOLOCK) ON tSA.StudentId = SA1.StudentId
					INNER JOIN sSetup.tOrganizationMaster OM WITH (NOLOCK) ON OM.Id = SA1.OrgId
					INNER JOIN sSetup.tOrgGroupMaster OMM WITH (NOLOCK) ON OMM.Id = OM.OrgGroupId 
					INNER JOIN sSetup.tOrgGroupBatchMaster OGBM WITH (NOLOCK) ON OGBM.ID=SA1.OrgGroupBatchId
					INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM WITH (NOLOCK) ON COGBM.Id=OGBM.CommonOrgGroupBatchId
				WHERE		
					(R.SourceTypeId = 2001) AND (R.IsObsolete = 0) 
					AND COGBM.Id = @rCommonOrgGroupBatchId
					AND((OMM.Id = @rOrgGroupId) OR (@rOrgGroupId = 0))
				GROUP BY FeeSetupId,R.SourceId
			) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
			LEFT JOIN sHostel.tAssignRoom AR  WITH (NOLOCK) ON  AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003  
			LEFT JOIN (
				SELECT AT.SourceId FROM sTransport.tAssignRoute AT  WITH (NOLOCK)
				INNER JOIN sTransport.tBusRouteDestinationMaster BM WITH (NOLOCK) ON BM.Id=AT.PickupDestinationId
				INNER JOIN sTransport.tBusRouteMaster B WITH (NOLOCK) ON B.Id=BM.BusRouteId AND  AT.SourceTypeId=2003
				INNER JOIN sSetup.tOrgGroupBatchMaster OGBM WITH (NOLOCK) ON OGBM.ID=B.OrgGroupBatchId
				INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM WITH (NOLOCK) ON COGBM.Id=OGBM.CommonOrgGroupBatchId
				WHERE COGBM.Id = @rCommonOrgGroupBatchId
			) RT ON RT.SourceId = SA.StudentId 
			INNER JOIN sSetup.tOrganizationMaster O WITH (NOLOCK) ON SA.OrgId = O.Id
			INNER JOIN sFee.tReceiptBookMaster RBM WITH (NOLOCK) ON FS.ReceiptBookId=RBM.Id
			INNER JOIN sFee.tFeeHeadMaster FHM WITH (NOLOCK) ON FHM.Id=FS.FeeHeadId
			INNER JOIN sSetup.tOrganizationMaster OM WITH (NOLOCK) ON OM.Id = SA.OrgId
			INNER JOIN sSetup.tOrgGroupMaster OMM WITH (NOLOCK) ON OMM.Id = OM.OrgGroupId 
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM WITH (NOLOCK) ON OGBM.ID=SA.OrgGroupBatchId
			INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM WITH (NOLOCK) ON COGBM.Id=OGBM.CommonOrgGroupBatchId
		WHERE  
			COGBM.Id = @rCommonOrgGroupBatchId
			AND((OMM.Id = @rOrgGroupId) OR (@rOrgGroupId = 0))
		GROUP BY RBM.Title,RBM.Id,RBM.OrderIndex
		Order By RBM.OrderIndex, RBM.Id
	END
	ELSE IF (@rType = 11)
	BEGIN
		SELECT 
			ISNULL(SA.AcademicId,0) AS SourceId,
			ISNULL(SA.ClassName,'') AS ClassName,
			ISNULL(SA.DivisionId,0) AS DivisionId,
			ISNULL(SA.DivisionName,'') AS DivisionName,
			ISNULL(SA.ClassName+'-'+SA.DivisionName,'') AS ClassDivision,
			ISNULL(SA.Code,'') As Code,
			ISNULL(SA.Name,'') AS Name,
			ISNULL(SC.ParentContactNo,'') AS ParentContactNo,
			SUM(ISNULL(R.PaidAmount,0)) AS PaidAmount,
			SA.ClassOrderIndex,  
			SA.DivisionOrder,
			SA.RollNo 
		FROM 
			sStudent.vStudentAcademic SA WITH (NOLOCK)
			INNER JOIN sStudent.tStudentAdmission tSA WITH (NOLOCK) ON tSA.StudentId = SA.StudentId
			LEFT JOIN sStudent.tStudentCommunication SC WITH (NOLOCK) ON SC.StudentId = SA.StudentId
			INNER JOIN 
			(
				SELECT 
					FS1.FeeId,
					FS1.Id,
					ISNULL(FS1.Amount,0)AS Amount,
					ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
					FM.Title AS FeeName,
					SA1.AcademicId,
					FM.FeeHeadId
				FROM sFee.tFeeSetup FS1 WITH (NOLOCK)
				INNER JOIN sStudent.vStudentAcademic SA1 WITH (NOLOCK) ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				INNER JOIN sFee.tFeeMaster FM WITH (NOLOCK) ON FM.Id=FS1.FeeId
		
				WHERE 
					(FS1.IsOptional=0)

				UNION ALL
				
				SELECT 
					FS1.FeeId,
					FS1.Id,
					ISNULL(FS1.Amount,0)AS Amount,
					ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
					FM.Title AS FeeName,
					SA1.AcademicId,
					FM.FeeHeadId
				FROM sFee.tFeeSetup FS1 WITH (NOLOCK)
				INNER JOIN sFee.tFeeOptional FO WITH (NOLOCK) ON FO.FeeSetupId=FS1.Id 
				INNER JOIN sFee.tFeeMaster FM WITH (NOLOCK) ON FM.Id=FS1.FeeId
				INNER JOIN sStudent.vStudentAcademic SA1 WITH (NOLOCK) ON SA1.AcademicId=FO.SourceId AND FS1.BatchId = SA1.BatchId
				AND SA1.ClassId=FS1.ClassId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				WHERE
					 (FS1.IsOptional=1)
			
				) FS ON FS.AcademicId=SA.AcademicId
				LEFT JOIN sFee.tFeeAllocation FA WITH (NOLOCK) 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 WITH (NOLOCK)
						INNER JOIN sFee.tReceiptDetail RD WITH (NOLOCK) ON RD.ReceiptId = R.Id 
						INNER JOIN sFee.tFeeSetup FS WITH (NOLOCK) ON RD.FeeSetupId = FS.Id
						INNER JOIN sFee.tFeeMaster FM WITH (NOLOCK) ON FS.FeeId = FM.Id
						INNER JOIN sStudent.vStudentAcademic SA1 WITH (NOLOCK) ON SA1.AcademicId=R.SourceId 
						INNER JOIN sStudent.tStudentAdmission tSA WITH (NOLOCK) ON tSA.StudentId = SA1.StudentId
					WHERE		
						(R.SourceTypeId = 2001)
						AND (R.IsObsolete = 0) 
					GROUP BY FeeSetupId,R.SourceId
				) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
				LEFT JOIN sHostel.tAssignRoom AR WITH (NOLOCK) ON  AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003  
				LEFT JOIN
				(SELECT AT.SourceId FROM sTransport.tAssignRoute AT WITH (NOLOCK) 
					INNER JOIN sTransport.tBusRouteDestinationMaster BM WITH (NOLOCK) ON BM.Id=AT.PickupDestinationId
					INNER JOIN sTransport.tBusRouteMaster B WITH (NOLOCK) ON B.Id=BM.BusRouteId AND  AT.SourceTypeId=2003
					INNER JOIN sSetup.tOrgGroupBatchMaster OGBM WITH (NOLOCK) ON OGBM.ID=B.OrgGroupBatchId
					INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM WITH (NOLOCK) ON COGBM.Id=OGBM.CommonOrgGroupBatchId
					WHERE COGBM.Id = @rCommonOrgGroupBatchId) RT ON RT.SourceId = SA.StudentId 
				 INNER JOIN sSetup.tOrganizationMaster O WITH (NOLOCK) ON SA.OrgId = O.Id
				 INNER JOIN sFee.tReceiptBookMaster RBM WITH (NOLOCK) ON FS.ReceiptBookId=RBM.Id
				 INNER JOIN sFee.tFeeHeadMaster FHM WITH (NOLOCK) ON FHM.Id=FS.FeeHeadId
				 INNER JOIN sSetup.tOrganizationMaster OM WITH (NOLOCK) ON OM.Id = SA.OrgId
				 INNER JOIN sSetup.tOrgGroupMaster OMM WITH (NOLOCK) ON OMM.Id = OM.OrgGroupId 
				 INNER JOIN sSetup.tOrgGroupBatchMaster OGBM WITH (NOLOCK) ON OGBM.ID=SA.OrgGroupBatchId
				 INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM WITH (NOLOCK) ON COGBM.Id=OGBM.CommonOrgGroupBatchId
		WHERE  
			COGBM.Id = @rCommonOrgGroupBatchId
			AND((OMM.Id = @rOrgGroupId) OR (@rOrgGroupId = 0))
			AND ((RBM.Id = @rReceiptBookId) OR (@rReceiptBookId = 0))
		GROUP by SA.ClassName,SA.DivisionName,SA.Name,SC.ParentContactNo,SA.Code,SA.ClassOrderIndex,SA.DivisionOrder,SA.RollNo,SA.DivisionId,SA.AcademicId
		Having SUM(ISNULL(R.PaidAmount,0)) >0
		ORDER BY SA.ClassOrderIndex,SA.DivisionOrder,SA.RollNo
	END
	ELSE IF (@rType = 12)
	BEGIN
		SELECT 
			ISNULL(SA.AcademicId,0) AS SourceId,
			ISNULL(SA.ClassName,'') AS ClassName,
			ISNULL(SA.DivisionId,0) AS DivisionId,
			ISNULL(SA.DivisionName,'') AS DivisionName,
			ISNULL(SA.ClassName+'-'+SA.DivisionName,'') AS ClassDivision,
			ISNULL(SA.Code,'') As Code,
			ISNULL(SA.Name,'') AS Name,
			ISNULL(SC.ParentContactNo,'') AS ParentContactNo,
			SUM(ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00))AS PendingAmount,
			SA.ClassOrderIndex,  
			SA.DivisionOrder,
			SA.RollNo 
		FROM 
			sStudent.vStudentAcademic SA WITH (NOLOCK)
			INNER JOIN sStudent.tStudentAdmission tSA WITH (NOLOCK) ON tSA.StudentId = SA.StudentId
			LEFT JOIN sStudent.tStudentCommunication SC WITH (NOLOCK) ON SC.StudentId = SA.StudentId
			INNER JOIN 
			(
				SELECT 
					FS1.FeeId,
					FS1.Id,
					ISNULL(FS1.Amount,0)AS Amount,
					ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
					FM.Title AS FeeName,
					SA1.AcademicId,
					FM.FeeHeadId
				FROM sFee.tFeeSetup FS1 WITH (NOLOCK)
				INNER JOIN sStudent.vStudentAcademic SA1 WITH (NOLOCK) ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				INNER JOIN sFee.tFeeMaster FM WITH (NOLOCK) ON FM.Id=FS1.FeeId
		
				WHERE 
					(FS1.IsOptional=0)

				UNION ALL
				
				SELECT 
					FS1.FeeId,
					FS1.Id,
					ISNULL(FS1.Amount,0)AS Amount,
					ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
					FM.Title AS FeeName,
					SA1.AcademicId,
					FM.FeeHeadId
				FROM sFee.tFeeSetup FS1 WITH (NOLOCK)
				INNER JOIN sFee.tFeeOptional FO WITH (NOLOCK) ON FO.FeeSetupId=FS1.Id 
				INNER JOIN sFee.tFeeMaster FM WITH (NOLOCK) ON FM.Id=FS1.FeeId
				INNER JOIN sStudent.vStudentAcademic SA1 WITH (NOLOCK) ON SA1.AcademicId=FO.SourceId AND FS1.BatchId = SA1.BatchId
				AND SA1.ClassId=FS1.ClassId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				WHERE
					 (FS1.IsOptional=1)
			
				) FS ON FS.AcademicId=SA.AcademicId
				LEFT JOIN sFee.tFeeAllocation FA WITH (NOLOCK) 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 WITH (NOLOCK) 
						INNER JOIN sFee.tReceiptDetail RD WITH (NOLOCK) ON RD.ReceiptId = R.Id 
						INNER JOIN sFee.tFeeSetup FS WITH (NOLOCK) ON RD.FeeSetupId = FS.Id
						INNER JOIN sFee.tFeeMaster FM WITH (NOLOCK) ON FS.FeeId = FM.Id
						INNER JOIN sStudent.vStudentAcademic SA1 WITH (NOLOCK) ON SA1.AcademicId=R.SourceId 
						INNER JOIN sStudent.tStudentAdmission tSA WITH (NOLOCK) ON tSA.StudentId = SA1.StudentId
					WHERE		
						(R.SourceTypeId = 2001)
						AND (R.IsObsolete = 0) 
					GROUP BY FeeSetupId,R.SourceId
				) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
				LEFT JOIN sHostel.tAssignRoom AR WITH (NOLOCK) ON  AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003  
				LEFT JOIN
				(SELECT AT.SourceId FROM sTransport.tAssignRoute AT WITH (NOLOCK) 
					INNER JOIN sTransport.tBusRouteDestinationMaster BM WITH (NOLOCK) ON BM.Id=AT.PickupDestinationId
					INNER JOIN sTransport.tBusRouteMaster B WITH (NOLOCK) ON B.Id=BM.BusRouteId AND  AT.SourceTypeId=2003
					INNER JOIN sSetup.tOrgGroupBatchMaster OGBM WITH (NOLOCK) ON OGBM.ID=B.OrgGroupBatchId
					INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM WITH (NOLOCK) ON COGBM.Id=OGBM.CommonOrgGroupBatchId
					WHERE COGBM.Id = @rCommonOrgGroupBatchId) RT ON RT.SourceId = SA.StudentId 
				 INNER JOIN sSetup.tOrganizationMaster O WITH (NOLOCK) ON SA.OrgId = O.Id
				 INNER JOIN sFee.tReceiptBookMaster RBM WITH (NOLOCK) ON FS.ReceiptBookId=RBM.Id
				 INNER JOIN sFee.tFeeHeadMaster FHM WITH (NOLOCK) ON FHM.Id=FS.FeeHeadId
				 INNER JOIN sSetup.tOrganizationMaster OM WITH (NOLOCK) ON OM.Id = SA.OrgId
				 INNER JOIN sSetup.tOrgGroupMaster OMM WITH (NOLOCK) ON OMM.Id = OM.OrgGroupId 
				 INNER JOIN sSetup.tOrgGroupBatchMaster OGBM WITH (NOLOCK) ON OGBM.ID=SA.OrgGroupBatchId
				 INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM WITH (NOLOCK) ON COGBM.Id=OGBM.CommonOrgGroupBatchId
		WHERE  
			COGBM.Id = @rCommonOrgGroupBatchId
			AND((OMM.Id = @rOrgGroupId) OR (@rOrgGroupId = 0))
			AND ((RBM.Id = @rReceiptBookId) OR (@rReceiptBookId = 0))
		GROUP by SA.ClassName,SA.DivisionName,SA.Name,SC.ParentContactNo,SA.Code,SA.ClassOrderIndex,SA.DivisionOrder,SA.RollNo,SA.DivisionId,SA.AcademicId
		Having SUM(ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00)) >0
		ORDER BY SA.ClassOrderIndex,SA.DivisionOrder,SA.RollNo
	END
	ELSE IF (@rType = 13)
	BEGIN
		SELECT 
			ISNULL(SA.AcademicId,0) AS SourceId,
			ISNULL(SA.ClassName,'') AS ClassName,
			ISNULL(SA.DivisionId,0) AS DivisionId,
			ISNULL(SA.DivisionName,'') AS DivisionName,
			ISNULL(SA.ClassName+'-'+SA.DivisionName,'') AS ClassDivision,
			ISNULL(SA.Code,'') As Code,
			ISNULL(SA.Name,'') AS Name,
			ISNULL(SC.ParentContactNo,'') AS ParentContactNo,
			SUM(ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)) AS TotalAmount,
			SA.ClassOrderIndex,  
			SA.DivisionOrder,
			SA.RollNo 
		FROM 
			sStudent.vStudentAcademic SA WITH (NOLOCK)
			INNER JOIN sStudent.tStudentAdmission tSA WITH (NOLOCK) ON tSA.StudentId = SA.StudentId
			LEFT JOIN sStudent.tStudentCommunication SC WITH (NOLOCK) ON SC.StudentId = SA.StudentId
			INNER JOIN 
			(
				SELECT 
					FS1.FeeId,
					FS1.Id,
					ISNULL(FS1.Amount,0)AS Amount,
					ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
					FM.Title AS FeeName,
					SA1.AcademicId,
					FM.FeeHeadId
				FROM sFee.tFeeSetup FS1 WITH (NOLOCK)
				INNER JOIN sStudent.vStudentAcademic SA1 WITH (NOLOCK) ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				INNER JOIN sFee.tFeeMaster FM WITH (NOLOCK) ON FM.Id=FS1.FeeId
		
				WHERE 
					(FS1.IsOptional=0)

				UNION ALL
				
				SELECT 
					FS1.FeeId,
					FS1.Id,
					ISNULL(FS1.Amount,0)AS Amount,
					ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
					FM.Title AS FeeName,
					SA1.AcademicId,
					FM.FeeHeadId
				FROM sFee.tFeeSetup FS1 WITH (NOLOCK)
				INNER JOIN sFee.tFeeOptional FO WITH (NOLOCK) ON FO.FeeSetupId=FS1.Id 
				INNER JOIN sFee.tFeeMaster FM WITH (NOLOCK) ON FM.Id=FS1.FeeId
				INNER JOIN sStudent.vStudentAcademic SA1 WITH (NOLOCK) ON SA1.AcademicId=FO.SourceId AND FS1.BatchId = SA1.BatchId
				AND SA1.ClassId=FS1.ClassId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				WHERE
					 (FS1.IsOptional=1)
			
				) FS ON FS.AcademicId=SA.AcademicId
				LEFT JOIN sFee.tFeeAllocation FA WITH (NOLOCK) 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 WITH (NOLOCK)
						INNER JOIN sFee.tReceiptDetail RD WITH (NOLOCK) ON RD.ReceiptId = R.Id 
						INNER JOIN sFee.tFeeSetup FS WITH (NOLOCK) ON RD.FeeSetupId = FS.Id
						INNER JOIN sFee.tFeeMaster FM WITH (NOLOCK) ON FS.FeeId = FM.Id
						INNER JOIN sStudent.vStudentAcademic SA1 WITH (NOLOCK) ON SA1.AcademicId=R.SourceId 
						INNER JOIN sStudent.tStudentAdmission tSA WITH (NOLOCK) ON tSA.StudentId = SA1.StudentId
					WHERE		
						(R.SourceTypeId = 2001)
						AND (R.IsObsolete = 0) 
					GROUP BY FeeSetupId,R.SourceId
				) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
				LEFT JOIN sHostel.tAssignRoom AR WITH (NOLOCK) ON  AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003  
				LEFT JOIN
				(SELECT AT.SourceId FROM sTransport.tAssignRoute AT WITH (NOLOCK) 
					INNER JOIN sTransport.tBusRouteDestinationMaster BM WITH (NOLOCK) ON BM.Id=AT.PickupDestinationId
					INNER JOIN sTransport.tBusRouteMaster B WITH (NOLOCK) ON B.Id=BM.BusRouteId AND  AT.SourceTypeId=2003
					INNER JOIN sSetup.tOrgGroupBatchMaster OGBM WITH (NOLOCK) ON OGBM.ID=B.OrgGroupBatchId
					INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM WITH (NOLOCK) ON COGBM.Id=OGBM.CommonOrgGroupBatchId
					WHERE COGBM.Id = @rCommonOrgGroupBatchId) RT ON RT.SourceId = SA.StudentId 
				 INNER JOIN sSetup.tOrganizationMaster O WITH (NOLOCK) ON SA.OrgId = O.Id
				 INNER JOIN sFee.tReceiptBookMaster RBM WITH (NOLOCK) ON FS.ReceiptBookId=RBM.Id
				 INNER JOIN sFee.tFeeHeadMaster FHM WITH (NOLOCK) ON FHM.Id=FS.FeeHeadId
				 INNER JOIN sSetup.tOrganizationMaster OM WITH (NOLOCK) ON OM.Id = SA.OrgId
				 INNER JOIN sSetup.tOrgGroupMaster OMM WITH (NOLOCK) ON OMM.Id = OM.OrgGroupId 
				 INNER JOIN sSetup.tOrgGroupBatchMaster OGBM WITH (NOLOCK) ON OGBM.ID=SA.OrgGroupBatchId
				 INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM WITH (NOLOCK) ON COGBM.Id=OGBM.CommonOrgGroupBatchId
		WHERE  
			COGBM.Id = @rCommonOrgGroupBatchId
			AND((OMM.Id = @rOrgGroupId) OR (@rOrgGroupId = 0))
			AND ((RBM.Id = @rReceiptBookId) OR (@rReceiptBookId = 0))
		GROUP by SA.ClassName,SA.DivisionName,SA.Name,SC.ParentContactNo,SA.Code,SA.ClassOrderIndex,SA.DivisionOrder,SA.RollNo,SA.DivisionId,SA.AcademicId
		Having SUM(ISNULL(R.PaidAmount,0)+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.ClassOrderIndex,SA.DivisionOrder,SA.RollNo
	END
	ELSE IF(@rType = 2)
	BEGIN
		SELECT 
			OM.Id AS OrgId,
			OM.Title AS Organization,
			SUM(ISNULL(R.PaidAmount,0)) AS PaidAmount,
			SUM(ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00))AS PendingAmount,
			SUM(ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)) AS Total,
			OM.OrderIndex
		FROM 
			sStudent.vStudentAcademic SA WITH (NOLOCK)
			INNER JOIN sStudent.tStudentAdmission tSA WITH (NOLOCK) ON tSA.StudentId = SA.StudentId
			INNER JOIN #TempFeeSetupData FS ON FS.AcademicId=SA.AcademicId
			LEFT JOIN sFee.tFeeAllocation FA WITH (NOLOCK) 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 WITH (NOLOCK)
						INNER JOIN sFee.tReceiptDetail RD WITH (NOLOCK) ON RD.ReceiptId = R.Id 
						INNER JOIN sFee.tFeeSetup FS WITH (NOLOCK) ON RD.FeeSetupId = FS.Id
						INNER JOIN sFee.tFeeMaster FM WITH (NOLOCK) ON FS.FeeId = FM.Id
						INNER JOIN sStudent.vStudentAcademic SA1 WITH (NOLOCK) ON SA1.AcademicId=R.SourceId 
						INNER JOIN sStudent.tStudentAdmission tSA WITH (NOLOCK) ON tSA.StudentId = SA1.StudentId
					WHERE		
						(R.SourceTypeId = 2001)
						AND (R.IsObsolete = 0) 
					GROUP BY FeeSetupId,R.SourceId
				) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
				LEFT JOIN sHostel.tAssignRoom AR WITH (NOLOCK) ON  AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003  
				LEFT JOIN
				(SELECT AT.SourceId FROM sTransport.tAssignRoute AT WITH (NOLOCK) 
					INNER JOIN sTransport.tBusRouteDestinationMaster BM WITH (NOLOCK) ON BM.Id=AT.PickupDestinationId
					INNER JOIN sTransport.tBusRouteMaster B WITH (NOLOCK) ON B.Id=BM.BusRouteId AND  AT.SourceTypeId=2003
					INNER JOIN sSetup.tOrgGroupBatchMaster OGBM WITH (NOLOCK) ON OGBM.ID=B.OrgGroupBatchId
					INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM WITH (NOLOCK) ON COGBM.Id=OGBM.CommonOrgGroupBatchId
					WHERE COGBM.Id = @rCommonOrgGroupBatchId) RT ON RT.SourceId = SA.StudentId 
				 INNER JOIN sSetup.tOrganizationMaster O WITH (NOLOCK) ON SA.OrgId = O.Id
				 INNER JOIN sFee.tReceiptBookMaster RBM WITH (NOLOCK) ON FS.ReceiptBookId=RBM.Id
				 INNER JOIN sFee.tFeeHeadMaster FHM WITH (NOLOCK) ON FHM.Id=FS.FeeHeadId
				 INNER JOIN sSetup.tOrganizationMaster OM WITH (NOLOCK) ON OM.Id = SA.OrgId
				 INNER JOIN sSetup.tOrgGroupMaster OMM WITH (NOLOCK) ON OMM.Id = OM.OrgGroupId 
				 INNER JOIN sSetup.tOrgGroupBatchMaster OGBM WITH (NOLOCK) ON OGBM.ID=SA.OrgGroupBatchId
				 INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM WITH (NOLOCK) ON COGBM.Id=OGBM.CommonOrgGroupBatchId
		WHERE  
			COGBM.Id = @rCommonOrgGroupBatchId
			AND((OMM.Id = @rOrgGroupId) OR (@rOrgGroupId = 0))
		GROUP BY OM.Title,OM.Id,OM.OrderIndex
		Order BY OM.OrderIndex
	END
	ELSE IF (@rType = 21)
	BEGIN
		SELECT 
			ISNULL(SA.AcademicId,0) AS SourceId,
			ISNULL(SA.ClassName,'') AS ClassName,
			ISNULL(SA.DivisionId,0) AS DivisionId,
			ISNULL(SA.DivisionName,'') AS DivisionName,
			ISNULL(SA.ClassName+'-'+SA.DivisionName,'') AS ClassDivision,
			ISNULL(SA.Code,'') As Code,
			ISNULL(SA.Name,'') AS Name,
			ISNULL(SC.ParentContactNo,'') AS ParentContactNo,
			SUM(ISNULL(R.PaidAmount,0)) AS PaidAmount,
			SA.ClassOrderIndex,  
			SA.DivisionOrder,
			SA.RollNo 
		FROM 
			sStudent.vStudentAcademic SA WITH (NOLOCK)
			INNER JOIN sStudent.tStudentAdmission tSA WITH (NOLOCK) ON tSA.StudentId = SA.StudentId
			LEFT JOIN sStudent.tStudentCommunication SC WITH (NOLOCK) ON SC.StudentId = SA.StudentId
			INNER JOIN 
			(
				SELECT 
					FS1.FeeId,
					FS1.Id,
					ISNULL(FS1.Amount,0)AS Amount,
					ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
					FM.Title AS FeeName,
					SA1.AcademicId,
					FM.FeeHeadId
				FROM sFee.tFeeSetup FS1 WITH (NOLOCK)
				INNER JOIN sStudent.vStudentAcademic SA1 WITH (NOLOCK) ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				INNER JOIN sFee.tFeeMaster FM WITH (NOLOCK) ON FM.Id=FS1.FeeId
		
				WHERE 
					(FS1.IsOptional=0)

				UNION ALL
				
				SELECT 
					FS1.FeeId,
					FS1.Id,
					ISNULL(FS1.Amount,0)AS Amount,
					ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
					FM.Title AS FeeName,
					SA1.AcademicId,
					FM.FeeHeadId
				FROM sFee.tFeeSetup FS1 WITH (NOLOCK)
				INNER JOIN sFee.tFeeOptional FO WITH (NOLOCK) ON FO.FeeSetupId=FS1.Id 
				INNER JOIN sFee.tFeeMaster FM WITH (NOLOCK) ON FM.Id=FS1.FeeId
				INNER JOIN sStudent.vStudentAcademic SA1 WITH (NOLOCK) ON SA1.AcademicId=FO.SourceId AND FS1.BatchId = SA1.BatchId
				AND SA1.ClassId=FS1.ClassId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				WHERE
					 (FS1.IsOptional=1)
			
				) FS ON FS.AcademicId=SA.AcademicId
				LEFT JOIN sFee.tFeeAllocation FA WITH (NOLOCK) 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 WITH (NOLOCK)
						INNER JOIN sFee.tReceiptDetail RD WITH (NOLOCK) ON RD.ReceiptId = R.Id 
						INNER JOIN sFee.tFeeSetup FS WITH (NOLOCK) ON RD.FeeSetupId = FS.Id
						INNER JOIN sFee.tFeeMaster FM WITH (NOLOCK) ON FS.FeeId = FM.Id
						INNER JOIN sStudent.vStudentAcademic SA1 WITH (NOLOCK) ON SA1.AcademicId=R.SourceId 
						INNER JOIN sStudent.tStudentAdmission tSA WITH (NOLOCK) ON tSA.StudentId = SA1.StudentId
					WHERE		
						(R.SourceTypeId = 2001)
						AND (R.IsObsolete = 0) 
					GROUP BY FeeSetupId,R.SourceId
				) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
				LEFT JOIN sHostel.tAssignRoom AR WITH (NOLOCK) ON  AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003  
				LEFT JOIN
				(SELECT AT.SourceId FROM sTransport.tAssignRoute AT WITH (NOLOCK)
					INNER JOIN sTransport.tBusRouteDestinationMaster BM WITH (NOLOCK) ON BM.Id=AT.PickupDestinationId
					INNER JOIN sTransport.tBusRouteMaster B WITH (NOLOCK) ON B.Id=BM.BusRouteId AND  AT.SourceTypeId=2003
					INNER JOIN sSetup.tOrgGroupBatchMaster OGBM WITH (NOLOCK) ON OGBM.ID=B.OrgGroupBatchId
					INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM WITH (NOLOCK) ON COGBM.Id=OGBM.CommonOrgGroupBatchId
					WHERE COGBM.Id = @rCommonOrgGroupBatchId) RT ON RT.SourceId = SA.StudentId 
				 INNER JOIN sSetup.tOrganizationMaster O WITH (NOLOCK) ON SA.OrgId = O.Id
				 INNER JOIN sFee.tReceiptBookMaster RBM WITH (NOLOCK) ON FS.ReceiptBookId=RBM.Id
				 INNER JOIN sFee.tFeeHeadMaster FHM WITH (NOLOCK) ON FHM.Id=FS.FeeHeadId
				 INNER JOIN sSetup.tOrganizationMaster OM WITH (NOLOCK) ON OM.Id = SA.OrgId
				 INNER JOIN sSetup.tOrgGroupMaster OMM WITH (NOLOCK) ON OMM.Id = OM.OrgGroupId 
				 INNER JOIN sSetup.tOrgGroupBatchMaster OGBM WITH (NOLOCK) ON OGBM.ID=SA.OrgGroupBatchId
				 INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM WITH (NOLOCK) ON COGBM.Id=OGBM.CommonOrgGroupBatchId
		WHERE  
			COGBM.Id = @rCommonOrgGroupBatchId
			AND((OMM.Id = @rOrgGroupId) OR (@rOrgGroupId = 0))
			AND ((O.Id = @rOrgId) OR (@rOrgId = 0))
		GROUP by SA.ClassName,SA.DivisionName,SA.Name,SC.ParentContactNo,SA.Code,SA.ClassOrderIndex,SA.DivisionOrder,SA.RollNo,SA.DivisionId,SA.AcademicId
		Having SUM(ISNULL(R.PaidAmount,0)) >0
		ORDER BY SA.ClassOrderIndex,SA.DivisionOrder,SA.RollNo
	END
	ELSE IF (@rType = 22)
	BEGIN
		SELECT 
			ISNULL(SA.AcademicId,0) AS SourceId,
			ISNULL(SA.ClassName,'') AS ClassName,
			ISNULL(SA.DivisionId,0) AS DivisionId,
			ISNULL(SA.DivisionName,'') AS DivisionName,
			ISNULL(SA.ClassName+'-'+SA.DivisionName,'') AS ClassDivision,
			ISNULL(SA.Code,'') As Code,
			ISNULL(SA.Name,'') AS Name,
			ISNULL(SC.ParentContactNo,'') AS ParentContactNo,
			SUM(ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00))AS PendingAmount,
			SA.ClassOrderIndex,  
			SA.DivisionOrder,
			SA.RollNo 
		FROM 
			sStudent.vStudentAcademic SA WITH (NOLOCK)
			INNER JOIN sStudent.tStudentAdmission tSA WITH (NOLOCK) ON tSA.StudentId = SA.StudentId
			LEFT JOIN sStudent.tStudentCommunication SC WITH (NOLOCK) ON SC.StudentId = SA.StudentId
			INNER JOIN 
			(
				SELECT 
					FS1.FeeId,
					FS1.Id,
					ISNULL(FS1.Amount,0)AS Amount,
					ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
					FM.Title AS FeeName,
					SA1.AcademicId,
					FM.FeeHeadId
				FROM sFee.tFeeSetup FS1 WITH (NOLOCK)
				INNER JOIN sStudent.vStudentAcademic SA1 WITH (NOLOCK) ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				INNER JOIN sFee.tFeeMaster FM WITH (NOLOCK) ON FM.Id=FS1.FeeId
		
				WHERE 
					(FS1.IsOptional=0)

				UNION ALL
				
				SELECT 
					FS1.FeeId,
					FS1.Id,
					ISNULL(FS1.Amount,0)AS Amount,
					ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
					FM.Title AS FeeName,
					SA1.AcademicId,
					FM.FeeHeadId
				FROM sFee.tFeeSetup FS1 WITH (NOLOCK)
				INNER JOIN sFee.tFeeOptional FO WITH (NOLOCK) ON FO.FeeSetupId=FS1.Id 
				INNER JOIN sFee.tFeeMaster FM WITH (NOLOCK) ON FM.Id=FS1.FeeId
				INNER JOIN sStudent.vStudentAcademic SA1 WITH (NOLOCK) ON SA1.AcademicId=FO.SourceId AND FS1.BatchId = SA1.BatchId
				AND SA1.ClassId=FS1.ClassId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				WHERE
					 (FS1.IsOptional=1)
			
				) FS ON FS.AcademicId=SA.AcademicId
				LEFT JOIN sFee.tFeeAllocation FA WITH (NOLOCK) 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 WITH (NOLOCK)
						INNER JOIN sFee.tReceiptDetail RD WITH (NOLOCK) ON RD.ReceiptId = R.Id 
						INNER JOIN sFee.tFeeSetup FS WITH (NOLOCK) ON RD.FeeSetupId = FS.Id
						INNER JOIN sFee.tFeeMaster FM WITH (NOLOCK) ON FS.FeeId = FM.Id
						INNER JOIN sStudent.vStudentAcademic SA1 WITH (NOLOCK) ON SA1.AcademicId=R.SourceId 
						INNER JOIN sStudent.tStudentAdmission tSA WITH (NOLOCK) ON tSA.StudentId = SA1.StudentId
					WHERE		
						(R.SourceTypeId = 2001)
						AND (R.IsObsolete = 0) 
					GROUP BY FeeSetupId,R.SourceId
				) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
				LEFT JOIN sHostel.tAssignRoom AR WITH (NOLOCK) ON AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003  
				LEFT JOIN
				(SELECT AT.SourceId FROM sTransport.tAssignRoute AT WITH (NOLOCK) 
					INNER JOIN sTransport.tBusRouteDestinationMaster BM WITH (NOLOCK) ON BM.Id=AT.PickupDestinationId
					INNER JOIN sTransport.tBusRouteMaster B WITH (NOLOCK) ON B.Id=BM.BusRouteId AND  AT.SourceTypeId=2003
					INNER JOIN sSetup.tOrgGroupBatchMaster OGBM WITH (NOLOCK) ON OGBM.ID=B.OrgGroupBatchId
					INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM WITH (NOLOCK) ON COGBM.Id=OGBM.CommonOrgGroupBatchId
					WHERE COGBM.Id = @rCommonOrgGroupBatchId) RT ON RT.SourceId = SA.StudentId 
				 INNER JOIN sSetup.tOrganizationMaster O WITH (NOLOCK) ON SA.OrgId = O.Id
				 INNER JOIN sFee.tReceiptBookMaster RBM WITH (NOLOCK) ON FS.ReceiptBookId=RBM.Id
				 INNER JOIN sFee.tFeeHeadMaster FHM WITH (NOLOCK) ON FHM.Id=FS.FeeHeadId
				 INNER JOIN sSetup.tOrganizationMaster OM WITH (NOLOCK) ON OM.Id = SA.OrgId
				 INNER JOIN sSetup.tOrgGroupMaster OMM WITH (NOLOCK) ON OMM.Id = OM.OrgGroupId 
				 INNER JOIN sSetup.tOrgGroupBatchMaster OGBM WITH (NOLOCK) ON OGBM.ID=SA.OrgGroupBatchId
				 INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM WITH (NOLOCK) ON COGBM.Id=OGBM.CommonOrgGroupBatchId
		WHERE  
			COGBM.Id = @rCommonOrgGroupBatchId
			AND((OMM.Id = @rOrgGroupId) OR (@rOrgGroupId = 0))
			AND ((O.Id = @rOrgId) OR (@rOrgId = 0))
		GROUP by SA.ClassName,SA.DivisionName,SA.Name,SC.ParentContactNo,SA.Code,SA.ClassOrderIndex,SA.DivisionOrder,SA.RollNo,SA.DivisionId,SA.AcademicId
		Having SUM(ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00)) >0
		ORDER BY SA.ClassOrderIndex,SA.DivisionOrder,SA.RollNo
	END
	ELSE IF (@rType = 23)
	BEGIN
		SELECT 
			ISNULL(SA.AcademicId,0) AS SourceId,
			ISNULL(SA.ClassName,'') AS ClassName,
			ISNULL(SA.DivisionId,0) AS DivisionId,
			ISNULL(SA.DivisionName,'') AS DivisionName,
			ISNULL(SA.ClassName+'-'+SA.DivisionName,'') AS ClassDivision,
			ISNULL(SA.Code,'') As Code,
			ISNULL(SA.Name,'') AS Name,
			ISNULL(SC.ParentContactNo,'') AS ParentContactNo,
			SUM(ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)) AS TotalAmount,
			SA.ClassOrderIndex,  
			SA.DivisionOrder,
			SA.RollNo 
		FROM 
			sStudent.vStudentAcademic SA WITH (NOLOCK)
			INNER JOIN sStudent.tStudentAdmission tSA WITH (NOLOCK) ON tSA.StudentId = SA.StudentId
			LEFT JOIN sStudent.tStudentCommunication SC WITH (NOLOCK) ON SC.StudentId = SA.StudentId
			INNER JOIN 
			(
				SELECT 
					FS1.FeeId,
					FS1.Id,
					ISNULL(FS1.Amount,0)AS Amount,
					ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
					FM.Title AS FeeName,
					SA1.AcademicId,
					FM.FeeHeadId
				FROM sFee.tFeeSetup FS1 WITH (NOLOCK)
				INNER JOIN sStudent.vStudentAcademic SA1 WITH (NOLOCK) ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				INNER JOIN sFee.tFeeMaster FM WITH (NOLOCK) ON FM.Id=FS1.FeeId
		
				WHERE 
					(FS1.IsOptional=0)

				UNION ALL
				
				SELECT 
					FS1.FeeId,
					FS1.Id,
					ISNULL(FS1.Amount,0)AS Amount,
					ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
					FM.Title AS FeeName,
					SA1.AcademicId,
					FM.FeeHeadId
				FROM sFee.tFeeSetup FS1 WITH (NOLOCK)
				INNER JOIN sFee.tFeeOptional FO WITH (NOLOCK) ON FO.FeeSetupId=FS1.Id 
				INNER JOIN sFee.tFeeMaster FM WITH (NOLOCK) ON FM.Id=FS1.FeeId
				INNER JOIN sStudent.vStudentAcademic SA1 WITH (NOLOCK) ON SA1.AcademicId=FO.SourceId AND FS1.BatchId = SA1.BatchId
				AND SA1.ClassId=FS1.ClassId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				WHERE
					 (FS1.IsOptional=1)
			
				) FS ON FS.AcademicId=SA.AcademicId
				LEFT JOIN sFee.tFeeAllocation FA WITH (NOLOCK) 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  WITH (NOLOCK)
						INNER JOIN sFee.tReceiptDetail RD WITH (NOLOCK) ON RD.ReceiptId = R.Id 
						INNER JOIN sFee.tFeeSetup FS WITH (NOLOCK) ON RD.FeeSetupId = FS.Id
						INNER JOIN sFee.tFeeMaster FM WITH (NOLOCK) ON FS.FeeId = FM.Id
						INNER JOIN sStudent.vStudentAcademic SA1 WITH (NOLOCK) ON SA1.AcademicId=R.SourceId 
						INNER JOIN sStudent.tStudentAdmission tSA WITH (NOLOCK) ON tSA.StudentId = SA1.StudentId
					WHERE		
						(R.SourceTypeId = 2001)
						AND (R.IsObsolete = 0) 
					GROUP BY FeeSetupId,R.SourceId
				) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
				LEFT JOIN sHostel.tAssignRoom AR ON  AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003  
				LEFT JOIN
				(SELECT AT.SourceId FROM sTransport.tAssignRoute AT WITH (NOLOCK) 
					INNER JOIN sTransport.tBusRouteDestinationMaster BM WITH (NOLOCK) ON BM.Id=AT.PickupDestinationId
					INNER JOIN sTransport.tBusRouteMaster B WITH (NOLOCK) ON B.Id=BM.BusRouteId AND  AT.SourceTypeId=2003
					INNER JOIN sSetup.tOrgGroupBatchMaster OGBM WITH (NOLOCK) ON OGBM.ID=B.OrgGroupBatchId
					INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM WITH (NOLOCK) ON COGBM.Id=OGBM.CommonOrgGroupBatchId
					WHERE COGBM.Id = @rCommonOrgGroupBatchId) RT ON RT.SourceId = SA.StudentId 
				 INNER JOIN sSetup.tOrganizationMaster O WITH (NOLOCK) ON SA.OrgId = O.Id
				 INNER JOIN sFee.tReceiptBookMaster RBM WITH (NOLOCK) ON FS.ReceiptBookId=RBM.Id
				 INNER JOIN sFee.tFeeHeadMaster FHM WITH (NOLOCK) ON FHM.Id=FS.FeeHeadId
				 INNER JOIN sSetup.tOrganizationMaster OM WITH (NOLOCK) ON OM.Id = SA.OrgId
				 INNER JOIN sSetup.tOrgGroupMaster OMM WITH (NOLOCK) ON OMM.Id = OM.OrgGroupId 
				 INNER JOIN sSetup.tOrgGroupBatchMaster OGBM WITH (NOLOCK) ON OGBM.ID=SA.OrgGroupBatchId
				 INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM WITH (NOLOCK) ON COGBM.Id=OGBM.CommonOrgGroupBatchId
		WHERE  
			COGBM.Id = @rCommonOrgGroupBatchId
			AND((OMM.Id = @rOrgGroupId) OR (@rOrgGroupId = 0))
			AND ((O.Id = @rOrgId) OR (@rOrgId = 0))
		GROUP by SA.ClassName,SA.DivisionName,SA.Name,SC.ParentContactNo,SA.Code,SA.ClassOrderIndex,SA.DivisionOrder,SA.RollNo,SA.DivisionId,SA.AcademicId
		Having SUM(ISNULL(R.PaidAmount,0)+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.ClassOrderIndex,SA.DivisionOrder,SA.RollNo
	END
	ELSE IF (@rType = 24)
	BEGIN
		SELECT 
			ISNULL(SA.DivisionId,0) AS DivisionId,
			ISNULL(SA.ClassName,'') AS ClassName,
			ISNULL(SA.DivisionName,'') AS DivisionName,
			ISNULL(SA.ClassName+'-'+SA.DivisionName,'') AS ClassDivision,
			SUM(ISNULL(R.PaidAmount,0)) AS PaidAmount,
			SUM(ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00))AS PendingAmount,
			SUM(ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)) AS Total,
			SA.DivisionOrder
			,SA.ClassOrderIndex -- add for mantis : 0042058
		FROM 
			sStudent.vStudentAcademic SA WITH (NOLOCK)
			INNER JOIN sStudent.tStudentAdmission tSA WITH (NOLOCK) ON tSA.StudentId = SA.StudentId
			INNER JOIN 
			(
				SELECT 
					FS1.FeeId,
					FS1.Id,
					ISNULL(FS1.Amount,0)AS Amount,
					ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
					FM.Title AS FeeName,
					SA1.AcademicId,
					FM.FeeHeadId
				FROM sFee.tFeeSetup FS1 WITH (NOLOCK)
				INNER JOIN sStudent.vStudentAcademic SA1 WITH (NOLOCK) ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				INNER JOIN sFee.tFeeMaster FM WITH (NOLOCK) ON FM.Id=FS1.FeeId
		
				WHERE 
					(FS1.IsOptional=0)

				UNION ALL
				
				SELECT 
					FS1.FeeId,
					FS1.Id,
					ISNULL(FS1.Amount,0)AS Amount,
					ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
					FM.Title AS FeeName,
					SA1.AcademicId,
					FM.FeeHeadId
				FROM sFee.tFeeSetup FS1 WITH (NOLOCK)
				INNER JOIN sFee.tFeeOptional FO WITH (NOLOCK) ON FO.FeeSetupId=FS1.Id 
				INNER JOIN sFee.tFeeMaster FM WITH (NOLOCK) ON FM.Id=FS1.FeeId
				INNER JOIN sStudent.vStudentAcademic SA1 WITH (NOLOCK) ON SA1.AcademicId=FO.SourceId AND FS1.BatchId = SA1.BatchId
				AND SA1.ClassId=FS1.ClassId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				WHERE
					 (FS1.IsOptional=1)
			
				) FS ON FS.AcademicId=SA.AcademicId
				LEFT JOIN sFee.tFeeAllocation FA WITH (NOLOCK) 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 WITH (NOLOCK) 
						INNER JOIN sFee.tReceiptDetail RD WITH (NOLOCK) ON RD.ReceiptId = R.Id 
						INNER JOIN sFee.tFeeSetup FS WITH (NOLOCK) ON RD.FeeSetupId = FS.Id
						INNER JOIN sFee.tFeeMaster FM WITH (NOLOCK) ON FS.FeeId = FM.Id
						INNER JOIN sStudent.vStudentAcademic SA1 WITH (NOLOCK) ON SA1.AcademicId=R.SourceId 
						INNER JOIN sStudent.tStudentAdmission tSA WITH (NOLOCK) ON tSA.StudentId = SA1.StudentId
					WHERE		
						(R.SourceTypeId = 2001)
						AND (R.IsObsolete = 0) 
					GROUP BY FeeSetupId,R.SourceId
				) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
				LEFT JOIN sHostel.tAssignRoom AR WITH (NOLOCK) ON  AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003  
				LEFT JOIN
				(SELECT AT.SourceId FROM sTransport.tAssignRoute AT  WITH (NOLOCK)
					INNER JOIN sTransport.tBusRouteDestinationMaster BM WITH (NOLOCK) ON BM.Id=AT.PickupDestinationId
					INNER JOIN sTransport.tBusRouteMaster B WITH (NOLOCK) ON B.Id=BM.BusRouteId AND  AT.SourceTypeId=2003
					INNER JOIN sSetup.tOrgGroupBatchMaster OGBM WITH (NOLOCK) ON OGBM.ID=B.OrgGroupBatchId
					INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM WITH (NOLOCK) ON COGBM.Id=OGBM.CommonOrgGroupBatchId
					WHERE COGBM.Id = @rCommonOrgGroupBatchId) RT ON RT.SourceId = SA.StudentId 
				 INNER JOIN sSetup.tOrganizationMaster O WITH (NOLOCK) ON SA.OrgId = O.Id
				 INNER JOIN sFee.tReceiptBookMaster RBM WITH (NOLOCK) ON FS.ReceiptBookId=RBM.Id
				 INNER JOIN sFee.tFeeHeadMaster FHM WITH (NOLOCK) ON FHM.Id=FS.FeeHeadId
				 INNER JOIN sSetup.tOrganizationMaster OM WITH (NOLOCK) ON OM.Id = SA.OrgId
				 INNER JOIN sSetup.tOrgGroupMaster OMM WITH (NOLOCK) ON OMM.Id = OM.OrgGroupId 
				 INNER JOIN sSetup.tOrgGroupBatchMaster OGBM WITH (NOLOCK) ON OGBM.ID=SA.OrgGroupBatchId
				 INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM WITH (NOLOCK) ON COGBM.Id=OGBM.CommonOrgGroupBatchId
		WHERE  
			COGBM.Id = @rCommonOrgGroupBatchId
			AND((OMM.Id = @rOrgGroupId) OR (@rOrgGroupId = 0))
			AND ((O.Id = @rOrgId) OR (@rOrgId = 0))
		GROUP BY  SA.ClassName,SA.DivisionName,SA.DivisionId,SA.DivisionOrder,SA.ClassOrderIndex --add class division order index for mantis : 0042058
		Order BY SA.ClassOrderIndex,SA.DivisionOrder--add for mantis : 0042058
	END
	ELSE IF(@rType = 3)
	BEGIN
		SELECT 
			FHM.Id AS FeeHeadId,
			FHM.Title AS FeeHeadTitle,
			SUM(ISNULL(R.PaidAmount,0)) AS PaidAmount,
			SUM(ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00))AS PendingAmount,
			SUM(ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)) AS Total,
			FHM.OrderIndex
		FROM 
			sStudent.vStudentAcademic SA WITH (NOLOCK)
			INNER JOIN sStudent.tStudentAdmission tSA WITH (NOLOCK) ON tSA.StudentId = SA.StudentId
			INNER JOIN #TempFeeSetupData FS ON FS.AcademicId=SA.AcademicI
			LEFT JOIN sFee.tFeeAllocation FA WITH (NOLOCK) 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 WITH (NOLOCK) 
						INNER JOIN sFee.tReceiptDetail RD WITH (NOLOCK) ON RD.ReceiptId = R.Id 
						INNER JOIN sFee.tFeeSetup FS WITH (NOLOCK) ON RD.FeeSetupId = FS.Id
						INNER JOIN sFee.tFeeMaster FM WITH (NOLOCK) ON FS.FeeId = FM.Id
						INNER JOIN sStudent.vStudentAcademic SA1 WITH (NOLOCK) ON SA1.AcademicId=R.SourceId 
						INNER JOIN sStudent.tStudentAdmission tSA WITH (NOLOCK) ON tSA.StudentId = SA1.StudentId
					WHERE		
						(R.SourceTypeId = 2001)
						AND (R.IsObsolete = 0) 
					GROUP BY FeeSetupId,R.SourceId
				) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
				LEFT JOIN sHostel.tAssignRoom AR WITH (NOLOCK) ON AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003  
				LEFT JOIN
				(SELECT AT.SourceId FROM sTransport.tAssignRoute AT WITH (NOLOCK) 
					INNER JOIN sTransport.tBusRouteDestinationMaster BM WITH (NOLOCK) ON BM.Id=AT.PickupDestinationId
					INNER JOIN sTransport.tBusRouteMaster B WITH (NOLOCK) ON B.Id=BM.BusRouteId AND  AT.SourceTypeId=2003
					INNER JOIN sSetup.tOrgGroupBatchMaster OGBM WITH (NOLOCK) ON OGBM.ID=B.OrgGroupBatchId
					INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM WITH (NOLOCK) ON COGBM.Id=OGBM.CommonOrgGroupBatchId
					WHERE COGBM.Id = @rCommonOrgGroupBatchId) RT ON RT.SourceId = SA.StudentId 
				 INNER JOIN sSetup.tOrganizationMaster O WITH (NOLOCK) ON SA.OrgId = O.Id
				 INNER JOIN sFee.tReceiptBookMaster RBM WITH (NOLOCK) ON FS.ReceiptBookId=RBM.Id
				 INNER JOIN sFee.tFeeHeadMaster FHM WITH (NOLOCK) ON FHM.Id=FS.FeeHeadId
				 INNER JOIN sSetup.tOrganizationMaster OM WITH (NOLOCK) ON OM.Id = SA.OrgId
				 INNER JOIN sSetup.tOrgGroupMaster OMM WITH (NOLOCK) ON OMM.Id = OM.OrgGroupId 
				 INNER JOIN sSetup.tOrgGroupBatchMaster OGBM WITH (NOLOCK) ON OGBM.ID=SA.OrgGroupBatchId
				 INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM WITH (NOLOCK) ON COGBM.Id=OGBM.CommonOrgGroupBatchId
		WHERE  
			COGBM.Id = @rCommonOrgGroupBatchId
			AND((OMM.Id = @rOrgGroupId) OR (@rOrgGroupId = 0))
		GROUP BY FHM.Title,FHM.Id,FHM.OrderIndex
		Order By FHM.OrderIndex
	END
	ELSE IF (@rType = 31)
	BEGIN
		SELECT 
			ISNULL(SA.AcademicId,0) AS SourceId,
			ISNULL(SA.ClassName,'') AS ClassName,
			ISNULL(SA.DivisionId,0) AS DivisionId,
			ISNULL(SA.DivisionName,'') AS DivisionName,
			ISNULL(SA.ClassName+'-'+SA.DivisionName,'') AS ClassDivision,
			ISNULL(SA.Code,'') As Code,
			ISNULL(SA.Name,'') AS Name,
			ISNULL(SC.ParentContactNo,'') AS ParentContactNo,
			SUM(ISNULL(R.PaidAmount,0)) AS PaidAmount,
			SA.ClassOrderIndex,  
			SA.DivisionOrder,
			SA.RollNo 
		FROM 
			sStudent.vStudentAcademic SA WITH (NOLOCK)
			INNER JOIN sStudent.tStudentAdmission tSA WITH (NOLOCK) ON tSA.StudentId = SA.StudentId
			LEFT JOIN sStudent.tStudentCommunication SC WITH (NOLOCK) ON SC.StudentId = SA.StudentId
			INNER JOIN 
			(
				SELECT 
					FS1.FeeId,
					FS1.Id,
					ISNULL(FS1.Amount,0)AS Amount,
					ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
					FM.Title AS FeeName,
					SA1.AcademicId,
					FM.FeeHeadId
				FROM sFee.tFeeSetup FS1 WITH (NOLOCK)
				INNER JOIN sStudent.vStudentAcademic SA1 WITH (NOLOCK) ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				INNER JOIN sFee.tFeeMaster FM WITH (NOLOCK) ON FM.Id=FS1.FeeId
		
				WHERE 
					(FS1.IsOptional=0)

				UNION ALL
				
				SELECT 
					FS1.FeeId,
					FS1.Id,
					ISNULL(FS1.Amount,0)AS Amount,
					ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
					FM.Title AS FeeName,
					SA1.AcademicId,
					FM.FeeHeadId
				FROM sFee.tFeeSetup FS1 WITH (NOLOCK)
				INNER JOIN sFee.tFeeOptional FO WITH (NOLOCK) ON FO.FeeSetupId=FS1.Id 
				INNER JOIN sFee.tFeeMaster FM WITH (NOLOCK) ON FM.Id=FS1.FeeId
				INNER JOIN sStudent.vStudentAcademic SA1 WITH (NOLOCK) ON SA1.AcademicId=FO.SourceId AND FS1.BatchId = SA1.BatchId
				AND SA1.ClassId=FS1.ClassId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				WHERE
					 (FS1.IsOptional=1)
			
				) FS ON FS.AcademicId=SA.AcademicId
				LEFT JOIN sFee.tFeeAllocation FA WITH (NOLOCK) 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 WITH (NOLOCK)
						INNER JOIN sFee.tReceiptDetail RD WITH (NOLOCK) ON RD.ReceiptId = R.Id 
						INNER JOIN sFee.tFeeSetup FS WITH (NOLOCK) ON RD.FeeSetupId = FS.Id
						INNER JOIN sFee.tFeeMaster FM WITH (NOLOCK) ON FS.FeeId = FM.Id
						INNER JOIN sStudent.vStudentAcademic SA1 WITH (NOLOCK) ON SA1.AcademicId=R.SourceId 
						INNER JOIN sStudent.tStudentAdmission tSA WITH (NOLOCK) ON tSA.StudentId = SA1.StudentId
					WHERE		
						(R.SourceTypeId = 2001)
						AND (R.IsObsolete = 0) 
					GROUP BY FeeSetupId,R.SourceId
				) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
				LEFT JOIN sHostel.tAssignRoom AR WITH (NOLOCK) ON  AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003  
				LEFT JOIN
				(SELECT AT.SourceId FROM sTransport.tAssignRoute AT  WITH (NOLOCK)
					INNER JOIN sTransport.tBusRouteDestinationMaster BM WITH (NOLOCK) ON BM.Id=AT.PickupDestinationId
					INNER JOIN sTransport.tBusRouteMaster B WITH (NOLOCK) ON B.Id=BM.BusRouteId AND  AT.SourceTypeId=2003
					INNER JOIN sSetup.tOrgGroupBatchMaster OGBM WITH (NOLOCK) ON OGBM.ID=B.OrgGroupBatchId
					INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM WITH (NOLOCK) ON COGBM.Id=OGBM.CommonOrgGroupBatchId
					WHERE COGBM.Id = @rCommonOrgGroupBatchId) RT ON RT.SourceId = SA.StudentId 
				 INNER JOIN sSetup.tOrganizationMaster O WITH (NOLOCK) ON SA.OrgId = O.Id
				 INNER JOIN sFee.tReceiptBookMaster RBM WITH (NOLOCK) ON FS.ReceiptBookId=RBM.Id
				 INNER JOIN sFee.tFeeHeadMaster FHM WITH (NOLOCK) ON FHM.Id=FS.FeeHeadId
				 INNER JOIN sSetup.tOrganizationMaster OM WITH (NOLOCK) ON OM.Id = SA.OrgId
				 INNER JOIN sSetup.tOrgGroupMaster OMM WITH (NOLOCK) ON OMM.Id = OM.OrgGroupId 
				 INNER JOIN sSetup.tOrgGroupBatchMaster OGBM WITH (NOLOCK) ON OGBM.ID=SA.OrgGroupBatchId
				 INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM WITH (NOLOCK) ON COGBM.Id=OGBM.CommonOrgGroupBatchId
		WHERE  
			COGBM.Id = @rCommonOrgGroupBatchId
			AND((OMM.Id = @rOrgGroupId) OR (@rOrgGroupId = 0))
			AND ((FHM.Id = @rFeeHeadId) OR (@rFeeHeadId =0))
		GROUP by SA.ClassName,SA.DivisionName,SA.Name,SC.ParentContactNo,SA.Code,SA.ClassOrderIndex,SA.DivisionOrder,SA.RollNo,SA.DivisionId,SA.AcademicId
		Having SUM(ISNULL(R.PaidAmount,0)) >0
		ORDER BY SA.ClassOrderIndex,SA.DivisionOrder,SA.RollNo
	END
	ELSE IF (@rType = 32)
	BEGIN
		SELECT 
			ISNULL(SA.AcademicId,0) AS SourceId,
			ISNULL(SA.ClassName,'') AS ClassName,
			ISNULL(SA.DivisionId,0) AS DivisionId,
			ISNULL(SA.DivisionName,'') AS DivisionName,
			ISNULL(SA.ClassName+'-'+SA.DivisionName,'') AS ClassDivision,
			ISNULL(SA.Code,'') As Code,
			ISNULL(SA.Name,'') AS Name,
			ISNULL(SC.ParentContactNo,'') AS ParentContactNo,
			SUM(ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00))AS PendingAmount,
			SA.ClassOrderIndex,  
			SA.DivisionOrder,
			SA.RollNo 
		FROM 
			sStudent.vStudentAcademic SA WITH (NOLOCK)
			INNER JOIN sStudent.tStudentAdmission tSA WITH (NOLOCK) ON tSA.StudentId = SA.StudentId
			LEFT JOIN sStudent.tStudentCommunication SC WITH (NOLOCK) ON SC.StudentId = SA.StudentId
			INNER JOIN 
			(
				SELECT 
					FS1.FeeId,
					FS1.Id,
					ISNULL(FS1.Amount,0)AS Amount,
					ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
					FM.Title AS FeeName,
					SA1.AcademicId,
					FM.FeeHeadId
				FROM sFee.tFeeSetup FS1 WITH (NOLOCK)
				INNER JOIN sStudent.vStudentAcademic SA1 WITH (NOLOCK) ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				INNER JOIN sFee.tFeeMaster FM WITH (NOLOCK) ON FM.Id=FS1.FeeId
		
				WHERE 
					(FS1.IsOptional=0)

				UNION ALL
				
				SELECT 
					FS1.FeeId,
					FS1.Id,
					ISNULL(FS1.Amount,0)AS Amount,
					ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
					FM.Title AS FeeName,
					SA1.AcademicId,
					FM.FeeHeadId
				FROM sFee.tFeeSetup FS1 WITH (NOLOCK)
				INNER JOIN sFee.tFeeOptional FO WITH (NOLOCK) ON FO.FeeSetupId=FS1.Id 
				INNER JOIN sFee.tFeeMaster FM WITH (NOLOCK) ON FM.Id=FS1.FeeId
				INNER JOIN sStudent.vStudentAcademic SA1 WITH (NOLOCK) ON SA1.AcademicId=FO.SourceId AND FS1.BatchId = SA1.BatchId
				AND SA1.ClassId=FS1.ClassId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				WHERE
					 (FS1.IsOptional=1)
			
				) FS ON FS.AcademicId=SA.AcademicId
				LEFT JOIN sFee.tFeeAllocation FA WITH (NOLOCK) 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 WITH (NOLOCK) 
						INNER JOIN sFee.tReceiptDetail RD WITH (NOLOCK) ON RD.ReceiptId = R.Id 
						INNER JOIN sFee.tFeeSetup FS WITH (NOLOCK) ON RD.FeeSetupId = FS.Id
						INNER JOIN sFee.tFeeMaster FM WITH (NOLOCK) ON FS.FeeId = FM.Id
						INNER JOIN sStudent.vStudentAcademic SA1 WITH (NOLOCK) ON SA1.AcademicId=R.SourceId 
						INNER JOIN sStudent.tStudentAdmission tSA WITH (NOLOCK) ON tSA.StudentId = SA1.StudentId
					WHERE		
						(R.SourceTypeId = 2001)
						AND (R.IsObsolete = 0) 
					GROUP BY FeeSetupId,R.SourceId
				) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
				LEFT JOIN sHostel.tAssignRoom AR WITH (NOLOCK) ON  AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003  
				LEFT JOIN
				(SELECT AT.SourceId FROM sTransport.tAssignRoute AT WITH (NOLOCK)
					INNER JOIN sTransport.tBusRouteDestinationMaster BM WITH (NOLOCK) ON BM.Id=AT.PickupDestinationId
					INNER JOIN sTransport.tBusRouteMaster B WITH (NOLOCK) ON B.Id=BM.BusRouteId AND  AT.SourceTypeId=2003
					INNER JOIN sSetup.tOrgGroupBatchMaster OGBM WITH (NOLOCK) ON OGBM.ID=B.OrgGroupBatchId
					INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM WITH (NOLOCK) ON COGBM.Id=OGBM.CommonOrgGroupBatchId
					WHERE COGBM.Id = @rCommonOrgGroupBatchId) RT ON RT.SourceId = SA.StudentId 
				 INNER JOIN sSetup.tOrganizationMaster O WITH (NOLOCK) ON SA.OrgId = O.Id
				 INNER JOIN sFee.tReceiptBookMaster RBM WITH (NOLOCK) ON FS.ReceiptBookId=RBM.Id
				 INNER JOIN sFee.tFeeHeadMaster FHM WITH (NOLOCK) ON FHM.Id=FS.FeeHeadId
				 INNER JOIN sSetup.tOrganizationMaster OM WITH (NOLOCK) ON OM.Id = SA.OrgId
				 INNER JOIN sSetup.tOrgGroupMaster OMM WITH (NOLOCK) ON OMM.Id = OM.OrgGroupId 
				 INNER JOIN sSetup.tOrgGroupBatchMaster OGBM WITH (NOLOCK) ON OGBM.ID=SA.OrgGroupBatchId
				 INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM WITH (NOLOCK) ON COGBM.Id=OGBM.CommonOrgGroupBatchId
		WHERE  
			COGBM.Id = @rCommonOrgGroupBatchId
			AND((OMM.Id = @rOrgGroupId) OR (@rOrgGroupId = 0))
			AND ((FHM.Id = @rFeeHeadId) OR (@rFeeHeadId = 0))
		GROUP by SA.ClassName,SA.DivisionName,SA.Name,SC.ParentContactNo,SA.Code,SA.ClassOrderIndex,SA.DivisionOrder,SA.RollNo,SA.DivisionId,SA.AcademicId
		Having SUM(ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00)) >0
		ORDER BY SA.ClassOrderIndex,SA.DivisionOrder,SA.RollNo
	END
	ELSE IF (@rType = 33)
	BEGIN
		SELECT 
			ISNULL(SA.AcademicId,0) AS SourceId,
			ISNULL(SA.ClassName,'') AS ClassName,
			ISNULL(SA.DivisionId,0) AS DivisionId,
			ISNULL(SA.DivisionName,'') AS DivisionName,
			ISNULL(SA.ClassName+'-'+SA.DivisionName,'') AS ClassDivision,
			ISNULL(SA.Code,'') As Code,
			ISNULL(SA.Name,'') AS Name,
			ISNULL(SC.ParentContactNo,'') AS ParentContactNo,
			SUM(ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)) AS TotalAmount,
			SA.ClassOrderIndex,  
			SA.DivisionOrder,
			SA.RollNo 
		FROM 
			sStudent.vStudentAcademic SA WITH (NOLOCK)
			INNER JOIN sStudent.tStudentAdmission tSA WITH (NOLOCK) ON tSA.StudentId = SA.StudentId
			LEFT JOIN sStudent.tStudentCommunication SC WITH (NOLOCK) ON SC.StudentId = SA.StudentId
			INNER JOIN 
			(
				SELECT 
					FS1.FeeId,
					FS1.Id,
					ISNULL(FS1.Amount,0)AS Amount,
					ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
					FM.Title AS FeeName,
					SA1.AcademicId,
					FM.FeeHeadId
				FROM sFee.tFeeSetup FS1 WITH (NOLOCK)
				INNER JOIN sStudent.vStudentAcademic SA1 WITH (NOLOCK) ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				INNER JOIN sFee.tFeeMaster FM WITH (NOLOCK) ON FM.Id=FS1.FeeId
		
				WHERE 
					(FS1.IsOptional=0)

				UNION ALL
				
				SELECT 
					FS1.FeeId,
					FS1.Id,
					ISNULL(FS1.Amount,0)AS Amount,
					ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
					FM.Title AS FeeName,
					SA1.AcademicId,
					FM.FeeHeadId
				FROM sFee.tFeeSetup FS1 WITH (NOLOCK)
				INNER JOIN sFee.tFeeOptional FO WITH (NOLOCK) ON FO.FeeSetupId=FS1.Id 
				INNER JOIN sFee.tFeeMaster FM WITH (NOLOCK) ON FM.Id=FS1.FeeId
				INNER JOIN sStudent.vStudentAcademic SA1 WITH (NOLOCK) ON SA1.AcademicId=FO.SourceId AND FS1.BatchId = SA1.BatchId
				AND SA1.ClassId=FS1.ClassId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				WHERE
					 (FS1.IsOptional=1)
			
				) FS ON FS.AcademicId=SA.AcademicId
				LEFT JOIN sFee.tFeeAllocation FA WITH (NOLOCK) 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 WITH (NOLOCK) 
						INNER JOIN sFee.tReceiptDetail RD WITH (NOLOCK) ON RD.ReceiptId = R.Id 
						INNER JOIN sFee.tFeeSetup FS WITH (NOLOCK) ON RD.FeeSetupId = FS.Id
						INNER JOIN sFee.tFeeMaster FM WITH (NOLOCK) ON FS.FeeId = FM.Id
						INNER JOIN sStudent.vStudentAcademic SA1 WITH (NOLOCK) ON SA1.AcademicId=R.SourceId 
						INNER JOIN sStudent.tStudentAdmission tSA WITH (NOLOCK) ON tSA.StudentId = SA1.StudentId
					WHERE		
						(R.SourceTypeId = 2001)
						AND (R.IsObsolete = 0) 
					GROUP BY FeeSetupId,R.SourceId
				) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
				LEFT JOIN sHostel.tAssignRoom AR WITH (NOLOCK) ON  AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003  
				LEFT JOIN
				(SELECT AT.SourceId FROM sTransport.tAssignRoute AT WITH (NOLOCK)
					INNER JOIN sTransport.tBusRouteDestinationMaster BM WITH (NOLOCK) ON BM.Id=AT.PickupDestinationId
					INNER JOIN sTransport.tBusRouteMaster B WITH (NOLOCK) ON B.Id=BM.BusRouteId AND  AT.SourceTypeId=2003
					INNER JOIN sSetup.tOrgGroupBatchMaster OGBM WITH (NOLOCK) ON OGBM.ID=B.OrgGroupBatchId
					INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM WITH (NOLOCK) ON COGBM.Id=OGBM.CommonOrgGroupBatchId
					WHERE COGBM.Id = @rCommonOrgGroupBatchId) RT ON RT.SourceId = SA.StudentId 
				 INNER JOIN sSetup.tOrganizationMaster O WITH (NOLOCK) ON SA.OrgId = O.Id
				 INNER JOIN sFee.tReceiptBookMaster RBM WITH (NOLOCK) ON FS.ReceiptBookId=RBM.Id
				 INNER JOIN sFee.tFeeHeadMaster FHM WITH (NOLOCK) ON FHM.Id=FS.FeeHeadId
				 INNER JOIN sSetup.tOrganizationMaster OM WITH (NOLOCK) ON OM.Id = SA.OrgId
				 INNER JOIN sSetup.tOrgGroupMaster OMM WITH (NOLOCK) ON OMM.Id = OM.OrgGroupId 
				 INNER JOIN sSetup.tOrgGroupBatchMaster OGBM WITH (NOLOCK) ON OGBM.ID=SA.OrgGroupBatchId
				 INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM WITH (NOLOCK) ON COGBM.Id=OGBM.CommonOrgGroupBatchId
		WHERE  
			COGBM.Id = @rCommonOrgGroupBatchId
			AND((OMM.Id = @rOrgGroupId) OR (@rOrgGroupId = 0))
			AND ((FHM.Id = @rFeeHeadId) OR (@rFeeHeadId = 0))
		GROUP by SA.ClassName,SA.DivisionName,SA.Name,SC.ParentContactNo,SA.Code,SA.ClassOrderIndex,SA.DivisionOrder,SA.RollNo,SA.DivisionId,SA.AcademicId
		Having SUM(ISNULL(R.PaidAmount,0)+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.ClassOrderIndex,SA.DivisionOrder,SA.RollNo
	END
	ELSE IF(@rType = 4)
	BEGIN
		SELECT 
			FS.FeeMasterId AS FeeId,
			FS.FeeName AS FeeName,
			SUM(ISNULL(R.PaidAmount,0)) AS PaidAmount,
			SUM(ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(FA.DiscountAmount,0.00)-ISNULL(R.PaidAmount,0.00))AS PendingAmount,		-- Add -ISNULL(FA.DiscountAmount,0.00) for MantisId : 0036887
			SUM(ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(FA.DiscountAmount,0.00)) AS Total,										-- Add -ISNULL(FA.DiscountAmount,0.00) for MantisId : 0036887
			FS.OrderIndex
		FROM 
			sStudent.vStudentAcademic SA WITH (NOLOCK)
			INNER JOIN sStudent.tStudentAdmission tSA WITH (NOLOCK) ON tSA.StudentId = SA.StudentId
			INNER JOIN #TempFeeSetupData FS ON FS.AcademicId=SA.AcademicId
			LEFT JOIN sFee.tFeeAllocation FA WITH (NOLOCK) 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 WITH (NOLOCK)
						INNER JOIN sFee.tReceiptDetail RD WITH (NOLOCK) ON RD.ReceiptId = R.Id 
						INNER JOIN sFee.tFeeSetup FS WITH (NOLOCK) ON RD.FeeSetupId = FS.Id
						INNER JOIN sFee.tFeeMaster FM WITH (NOLOCK) ON FS.FeeId = FM.Id
						INNER JOIN sStudent.vStudentAcademic SA1 WITH (NOLOCK) ON SA1.AcademicId=R.SourceId 
						INNER JOIN sStudent.tStudentAdmission tSA WITH (NOLOCK) ON tSA.StudentId = SA1.StudentId
					WHERE		
						(R.SourceTypeId = 2001)
						AND (R.IsObsolete = 0) 
					GROUP BY FeeSetupId,R.SourceId
				) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
				LEFT JOIN sHostel.tAssignRoom AR WITH (NOLOCK) ON  AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003  
				LEFT JOIN
				(SELECT AT.SourceId FROM sTransport.tAssignRoute AT  WITH (NOLOCK)
					INNER JOIN sTransport.tBusRouteDestinationMaster BM WITH (NOLOCK) ON BM.Id=AT.PickupDestinationId
					INNER JOIN sTransport.tBusRouteMaster B WITH (NOLOCK) ON B.Id=BM.BusRouteId AND  AT.SourceTypeId=2003
					INNER JOIN sSetup.tOrgGroupBatchMaster OGBM  WITH (NOLOCK) ON OGBM.ID=B.OrgGroupBatchId
					INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM WITH (NOLOCK) ON COGBM.Id=OGBM.CommonOrgGroupBatchId
					WHERE COGBM.Id = @rCommonOrgGroupBatchId) RT ON RT.SourceId = SA.StudentId 
				 INNER JOIN sSetup.tOrganizationMaster O WITH (NOLOCK) ON SA.OrgId = O.Id
				 INNER JOIN sFee.tReceiptBookMaster RBM WITH (NOLOCK) ON FS.ReceiptBookId=RBM.Id
				 INNER JOIN sFee.tFeeHeadMaster FHM WITH (NOLOCK) ON FHM.Id=FS.FeeHeadId
				 INNER JOIN sSetup.tOrganizationMaster OM WITH (NOLOCK) ON OM.Id = SA.OrgId
				 INNER JOIN sSetup.tOrgGroupMaster OMM WITH (NOLOCK) ON OMM.Id = OM.OrgGroupId 
				 INNER JOIN sSetup.tOrgGroupBatchMaster OGBM WITH (NOLOCK) ON OGBM.ID=SA.OrgGroupBatchId
				 INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM WITH (NOLOCK) ON COGBM.Id=OGBM.CommonOrgGroupBatchId
		WHERE  
			COGBM.Id = @rCommonOrgGroupBatchId
			AND((OMM.Id = @rOrgGroupId) OR (@rOrgGroupId = 0))
		GROUP BY FS.FeeName,FS.FeeMasterId,FS.OrderIndex
		Order By FS.OrderIndex 
	END
	ELSE IF (@rType = 41)
	BEGIN
		SELECT 
			ISNULL(SA.AcademicId,0) AS SourceId,
			ISNULL(SA.ClassName,'') AS ClassName,
			ISNULL(SA.DivisionId,0) AS DivisionId,
			ISNULL(SA.DivisionName,'') AS DivisionName,
			ISNULL(SA.ClassName+'-'+SA.DivisionName,'') AS ClassDivision,
			ISNULL(SA.Code,'') As Code,
			ISNULL(SA.Name,'') AS Name,
			ISNULL(SC.ParentContactNo,'') AS ParentContactNo,
			SUM(ISNULL(R.PaidAmount,0)) AS PaidAmount,
			SA.ClassOrderIndex,  
			SA.DivisionOrder,
			SA.RollNo 
		FROM 
			sStudent.vStudentAcademic SA WITH (NOLOCK)
			INNER JOIN sStudent.tStudentAdmission tSA WITH (NOLOCK) ON tSA.StudentId = SA.StudentId
			LEFT JOIN sStudent.tStudentCommunication SC WITH (NOLOCK) ON SC.StudentId = SA.StudentId
			INNER JOIN 
			(
				SELECT 
					FS1.FeeId,
					FS1.Id,
					ISNULL(FS1.Amount,0)AS Amount,
					ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
					FM.Title AS FeeName,
					FM.Id AS FeeMasterId,
					SA1.AcademicId,
					FM.FeeHeadId
				FROM sFee.tFeeSetup FS1 WITH (NOLOCK)
				INNER JOIN sStudent.vStudentAcademic SA1 WITH (NOLOCK) ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				INNER JOIN sFee.tFeeMaster FM WITH (NOLOCK) ON FM.Id=FS1.FeeId
		
				WHERE 
					(FS1.IsOptional=0)

				UNION ALL
				
				SELECT 
					FS1.FeeId,
					FS1.Id,
					ISNULL(FS1.Amount,0)AS Amount,
					ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
					FM.Title AS FeeName,
					FM.Id AS FeeMasterId,
					SA1.AcademicId,
					FM.FeeHeadId
				FROM sFee.tFeeSetup FS1 WITH (NOLOCK)
				INNER JOIN sFee.tFeeOptional FO WITH (NOLOCK) ON FO.FeeSetupId=FS1.Id 
				INNER JOIN sFee.tFeeMaster FM WITH (NOLOCK) ON FM.Id=FS1.FeeId
				INNER JOIN sStudent.vStudentAcademic SA1 WITH (NOLOCK) ON SA1.AcademicId=FO.SourceId AND FS1.BatchId = SA1.BatchId
				AND SA1.ClassId=FS1.ClassId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				WHERE
					 (FS1.IsOptional=1)
			
				) FS ON FS.AcademicId=SA.AcademicId
				LEFT JOIN sFee.tFeeAllocation FA WITH (NOLOCK) 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 WITH (NOLOCK) 
						INNER JOIN sFee.tReceiptDetail RD WITH (NOLOCK) ON RD.ReceiptId = R.Id 
						INNER JOIN sFee.tFeeSetup FS WITH (NOLOCK) ON RD.FeeSetupId = FS.Id
						INNER JOIN sFee.tFeeMaster FM WITH (NOLOCK) ON FS.FeeId = FM.Id
						INNER JOIN sStudent.vStudentAcademic SA1 WITH (NOLOCK) ON SA1.AcademicId=R.SourceId 
						INNER JOIN sStudent.tStudentAdmission tSA WITH (NOLOCK) ON tSA.StudentId = SA1.StudentId
					WHERE		
						(R.SourceTypeId = 2001)
						AND (R.IsObsolete = 0) 
					GROUP BY FeeSetupId,R.SourceId
				) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
				LEFT JOIN sHostel.tAssignRoom AR WITH (NOLOCK) ON  AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003  
				LEFT JOIN
				(SELECT AT.SourceId FROM sTransport.tAssignRoute AT  WITH (NOLOCK)
					INNER JOIN sTransport.tBusRouteDestinationMaster BM WITH (NOLOCK) ON BM.Id=AT.PickupDestinationId
					INNER JOIN sTransport.tBusRouteMaster B WITH (NOLOCK) ON B.Id=BM.BusRouteId AND  AT.SourceTypeId=2003
					INNER JOIN sSetup.tOrgGroupBatchMaster OGBM WITH (NOLOCK) ON OGBM.ID=B.OrgGroupBatchId
					INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM WITH (NOLOCK) ON COGBM.Id=OGBM.CommonOrgGroupBatchId
					WHERE COGBM.Id = @rCommonOrgGroupBatchId) RT ON RT.SourceId = SA.StudentId 
				 INNER JOIN sSetup.tOrganizationMaster O WITH (NOLOCK) ON SA.OrgId = O.Id
				 INNER JOIN sFee.tReceiptBookMaster RBM WITH (NOLOCK) ON FS.ReceiptBookId=RBM.Id
				 INNER JOIN sFee.tFeeHeadMaster FHM WITH (NOLOCK) ON FHM.Id=FS.FeeHeadId
				 INNER JOIN sSetup.tOrganizationMaster OM WITH (NOLOCK) ON OM.Id = SA.OrgId
				 INNER JOIN sSetup.tOrgGroupMaster OMM WITH (NOLOCK) ON OMM.Id = OM.OrgGroupId 
				 INNER JOIN sSetup.tOrgGroupBatchMaster OGBM WITH (NOLOCK) ON OGBM.ID=SA.OrgGroupBatchId
				 INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM WITH (NOLOCK) ON COGBM.Id=OGBM.CommonOrgGroupBatchId
		WHERE  
			COGBM.Id = @rCommonOrgGroupBatchId
			AND((OMM.Id = @rOrgGroupId) OR (@rOrgGroupId = 0))
			AND ((FS.FeeMasterId = @rFeeId) OR (@rFeeId = 0))
		GROUP by SA.ClassName,SA.DivisionName,SA.Name,SC.ParentContactNo,SA.Code,SA.ClassOrderIndex,SA.DivisionOrder,SA.RollNo,SA.DivisionId,SA.AcademicId
		Having SUM(ISNULL(R.PaidAmount,0)) >0
		ORDER BY SA.ClassOrderIndex,SA.DivisionOrder,SA.RollNo
	END
	ELSE IF (@rType = 42)
	BEGIN
		SELECT 
			ISNULL(SA.AcademicId,0) AS SourceId,
			ISNULL(SA.ClassName,'') AS ClassName,
			ISNULL(SA.DivisionId,0) AS DivisionId,
			ISNULL(SA.DivisionName,'') AS DivisionName,
			ISNULL(SA.ClassName+'-'+SA.DivisionName,'') AS ClassDivision,
			ISNULL(SA.Code,'') As Code,
			ISNULL(SA.Name,'') AS Name,
			ISNULL(SC.ParentContactNo,'') AS ParentContactNo,
			SUM(ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00))AS PendingAmount,
			SA.ClassOrderIndex,  
			SA.DivisionOrder,
			SA.RollNo 
		FROM 
			sStudent.vStudentAcademic SA WITH (NOLOCK)
			INNER JOIN sStudent.tStudentAdmission tSA WITH (NOLOCK) ON tSA.StudentId = SA.StudentId
			LEFT JOIN sStudent.tStudentCommunication SC WITH (NOLOCK) ON SC.StudentId = SA.StudentId
			INNER JOIN 
			(
				SELECT 
					FS1.FeeId,
					FS1.Id,
					ISNULL(FS1.Amount,0)AS Amount,
					ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
					FM.Title AS FeeName,
					FM.Id AS FeeMasterId,
					SA1.AcademicId,
					FM.FeeHeadId
				FROM sFee.tFeeSetup FS1 WITH (NOLOCK)
				INNER JOIN sStudent.vStudentAcademic SA1 WITH (NOLOCK) ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				INNER JOIN sFee.tFeeMaster FM WITH (NOLOCK) ON FM.Id=FS1.FeeId
		
				WHERE 
					(FS1.IsOptional=0)

				UNION ALL
				
				SELECT 
					FS1.FeeId,
					FS1.Id,
					ISNULL(FS1.Amount,0)AS Amount,
					ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
					FM.Title AS FeeName,
					FM.Id AS FeeMasterId,
					SA1.AcademicId,
					FM.FeeHeadId
				FROM sFee.tFeeSetup FS1 WITH (NOLOCK)
				INNER JOIN sFee.tFeeOptional FO WITH (NOLOCK) ON FO.FeeSetupId=FS1.Id 
				INNER JOIN sFee.tFeeMaster FM WITH (NOLOCK) ON FM.Id=FS1.FeeId
				INNER JOIN sStudent.vStudentAcademic SA1 WITH (NOLOCK) ON SA1.AcademicId=FO.SourceId AND FS1.BatchId = SA1.BatchId
				AND SA1.ClassId=FS1.ClassId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				WHERE
					 (FS1.IsOptional=1)
			
				) FS ON FS.AcademicId=SA.AcademicId
				LEFT JOIN sFee.tFeeAllocation FA WITH (NOLOCK) 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 WITH (NOLOCK) 
						INNER JOIN sFee.tReceiptDetail RD WITH (NOLOCK) ON RD.ReceiptId = R.Id 
						INNER JOIN sFee.tFeeSetup FS WITH (NOLOCK) ON RD.FeeSetupId = FS.Id
						INNER JOIN sFee.tFeeMaster FM WITH (NOLOCK) ON FS.FeeId = FM.Id
						INNER JOIN sStudent.vStudentAcademic SA1 WITH (NOLOCK) ON SA1.AcademicId=R.SourceId 
						INNER JOIN sStudent.tStudentAdmission tSA WITH (NOLOCK) ON tSA.StudentId = SA1.StudentId
					WHERE		
						(R.SourceTypeId = 2001)
						AND (R.IsObsolete = 0) 
					GROUP BY FeeSetupId,R.SourceId
				) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
				LEFT JOIN sHostel.tAssignRoom AR WITH (NOLOCK) ON  AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003  
				LEFT JOIN
				(SELECT AT.SourceId FROM sTransport.tAssignRoute AT WITH (NOLOCK)
					INNER JOIN sTransport.tBusRouteDestinationMaster BM WITH (NOLOCK) ON BM.Id=AT.PickupDestinationId
					INNER JOIN sTransport.tBusRouteMaster B WITH (NOLOCK) ON B.Id=BM.BusRouteId AND  AT.SourceTypeId=2003
					INNER JOIN sSetup.tOrgGroupBatchMaster OGBM WITH (NOLOCK) ON OGBM.ID=B.OrgGroupBatchId
					INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM WITH (NOLOCK) ON COGBM.Id=OGBM.CommonOrgGroupBatchId
					WHERE COGBM.Id = @rCommonOrgGroupBatchId) RT ON RT.SourceId = SA.StudentId 
				 INNER JOIN sSetup.tOrganizationMaster O WITH (NOLOCK) ON SA.OrgId = O.Id
				 INNER JOIN sFee.tReceiptBookMaster RBM WITH (NOLOCK) ON FS.ReceiptBookId=RBM.Id
				 INNER JOIN sFee.tFeeHeadMaster FHM WITH (NOLOCK) ON FHM.Id=FS.FeeHeadId
				 INNER JOIN sSetup.tOrganizationMaster OM WITH (NOLOCK) ON OM.Id = SA.OrgId
				 INNER JOIN sSetup.tOrgGroupMaster OMM WITH (NOLOCK) ON OMM.Id = OM.OrgGroupId 
				 INNER JOIN sSetup.tOrgGroupBatchMaster OGBM WITH (NOLOCK) ON OGBM.ID=SA.OrgGroupBatchId
				 INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM WITH (NOLOCK) ON COGBM.Id=OGBM.CommonOrgGroupBatchId
		WHERE  
			COGBM.Id = @rCommonOrgGroupBatchId
			AND((OMM.Id = @rOrgGroupId) OR (@rOrgGroupId = 0))
			AND ((FS.FeeMasterId = @rFeeId) OR (@rFeeId = 0))
		GROUP by SA.ClassName,SA.DivisionName,SA.Name,SC.ParentContactNo,SA.Code,SA.ClassOrderIndex,SA.DivisionOrder,SA.RollNo,SA.DivisionId,SA.AcademicId
		Having SUM(ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00)) >0
		ORDER BY SA.ClassOrderIndex,SA.DivisionOrder,SA.RollNo
	END
	ELSE IF (@rType = 43)
	BEGIN
		SELECT 
			ISNULL(SA.AcademicId,0) AS SourceId,
			ISNULL(SA.ClassName,'') AS ClassName,
			ISNULL(SA.DivisionId,0) AS DivisionId,
			ISNULL(SA.DivisionName,'') AS DivisionName,
			ISNULL(SA.ClassName+'-'+SA.DivisionName,'') AS ClassDivision,
			ISNULL(SA.Code,'') As Code,
			ISNULL(SA.Name,'') AS Name,
			ISNULL(SC.ParentContactNo,'') AS ParentContactNo,
			SUM(ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)) AS TotalAmount,
			SA.ClassOrderIndex,  
			SA.DivisionOrder,
			SA.RollNo 
		FROM 
			sStudent.vStudentAcademic SA WITH (NOLOCK)
			INNER JOIN sStudent.tStudentAdmission tSA WITH (NOLOCK) ON tSA.StudentId = SA.StudentId
			LEFT JOIN sStudent.tStudentCommunication SC WITH (NOLOCK) ON SC.StudentId = SA.StudentId
			INNER JOIN 
			(
				SELECT 
					FS1.FeeId,
					FS1.Id,
					ISNULL(FS1.Amount,0)AS Amount,
					ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
					FM.Title AS FeeName,
					FM.Id AS FeeMasterId,
					SA1.AcademicId,
					FM.FeeHeadId
				FROM sFee.tFeeSetup FS1 WITH (NOLOCK)
				INNER JOIN sStudent.vStudentAcademic SA1 WITH (NOLOCK) ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				INNER JOIN sFee.tFeeMaster FM WITH (NOLOCK) ON FM.Id=FS1.FeeId
		
				WHERE 
					(FS1.IsOptional=0)

				UNION ALL
				
				SELECT 
					FS1.FeeId,
					FS1.Id,
					ISNULL(FS1.Amount,0)AS Amount,
					ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
					FM.Title AS FeeName,
					FM.Id AS FeeMasterId,
					SA1.AcademicId,
					FM.FeeHeadId
				FROM sFee.tFeeSetup FS1 WITH (NOLOCK)
				INNER JOIN sFee.tFeeOptional FO WITH (NOLOCK) ON FO.FeeSetupId=FS1.Id 
				INNER JOIN sFee.tFeeMaster FM WITH (NOLOCK) ON FM.Id=FS1.FeeId
				INNER JOIN sStudent.vStudentAcademic SA1 WITH (NOLOCK) ON SA1.AcademicId=FO.SourceId AND FS1.BatchId = SA1.BatchId
				AND SA1.ClassId=FS1.ClassId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				WHERE
					 (FS1.IsOptional=1)
			
				) FS ON FS.AcademicId=SA.AcademicId
				LEFT JOIN sFee.tFeeAllocation FA WITH (NOLOCK) 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 WITH (NOLOCK) 
						INNER JOIN sFee.tReceiptDetail RD WITH (NOLOCK) ON RD.ReceiptId = R.Id 
						INNER JOIN sFee.tFeeSetup FS WITH (NOLOCK) ON RD.FeeSetupId = FS.Id
						INNER JOIN sFee.tFeeMaster FM WITH (NOLOCK) ON FS.FeeId = FM.Id
						INNER JOIN sStudent.vStudentAcademic SA1 WITH (NOLOCK) ON SA1.AcademicId=R.SourceId 
						INNER JOIN sStudent.tStudentAdmission tSA WITH (NOLOCK) ON tSA.StudentId = SA1.StudentId
					WHERE		
						(R.SourceTypeId = 2001)
						AND (R.IsObsolete = 0) 
					GROUP BY FeeSetupId,R.SourceId
				) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
				LEFT JOIN sHostel.tAssignRoom AR WITH (NOLOCK) ON  AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003  
				LEFT JOIN
				(SELECT AT.SourceId FROM sTransport.tAssignRoute AT WITH (NOLOCK)
					INNER JOIN sTransport.tBusRouteDestinationMaster BM WITH (NOLOCK) ON BM.Id=AT.PickupDestinationId
					INNER JOIN sTransport.tBusRouteMaster B WITH (NOLOCK) ON B.Id=BM.BusRouteId AND  AT.SourceTypeId=2003
					INNER JOIN sSetup.tOrgGroupBatchMaster OGBM WITH (NOLOCK) ON OGBM.ID=B.OrgGroupBatchId
					INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM WITH (NOLOCK) ON COGBM.Id=OGBM.CommonOrgGroupBatchId
					WHERE COGBM.Id = @rCommonOrgGroupBatchId) RT ON RT.SourceId = SA.StudentId 
				 INNER JOIN sSetup.tOrganizationMaster O WITH (NOLOCK) ON SA.OrgId = O.Id
				 INNER JOIN sFee.tReceiptBookMaster RBM WITH (NOLOCK) ON FS.ReceiptBookId=RBM.Id
				 INNER JOIN sFee.tFeeHeadMaster FHM WITH (NOLOCK) ON FHM.Id=FS.FeeHeadId
				 INNER JOIN sSetup.tOrganizationMaster OM WITH (NOLOCK) ON OM.Id = SA.OrgId
				 INNER JOIN sSetup.tOrgGroupMaster OMM WITH (NOLOCK) ON OMM.Id = OM.OrgGroupId 
				 INNER JOIN sSetup.tOrgGroupBatchMaster OGBM  WITH (NOLOCK) ON OGBM.ID=SA.OrgGroupBatchId
				 INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM WITH (NOLOCK) ON COGBM.Id=OGBM.CommonOrgGroupBatchId
		WHERE  
			COGBM.Id = @rCommonOrgGroupBatchId
			AND((OMM.Id = @rOrgGroupId) OR (@rOrgGroupId = 0))
			AND ((FS.FeeMasterId = @rFeeId) OR (@rFeeId = 0))
		GROUP by SA.ClassName,SA.DivisionName,SA.Name,SC.ParentContactNo,SA.Code,SA.ClassOrderIndex,SA.DivisionOrder,SA.RollNo,SA.DivisionId,SA.AcademicId
		Having SUM(ISNULL(R.PaidAmount,0)+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.ClassOrderIndex,SA.DivisionOrder,SA.RollNo
	END

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


GO
ALTER PROCEDURE [sFee].[pFeeCollectionConsolidatedDashboardGet]

     @rOrgGroupId smallint=0,
     @rTypeId int=0,
     @rType nvarchar(20)='',
     @rCommonOrgGroupBatchId int=0,
	 @rFromDate date =null,
	 @rToDate date = null,
	 @rReceiptBookId int =0,
	 @rUserId bigint=0,
	 @rOrgId int =0,
	 @rCommonFeeId int =0
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 

DECLARE @lIsLogEnable bit = 0

IF(@lIsLogEnable = 1)
BEGIN

	INSERT INTO [sSystem].[tTraceLog]
	(LogMessage, ExtraLogMessage, ExceptionLog, ExceptionDetailLog, CreatedDateTime, PagePath)
	VALUES
	('TypeId: ' + CAST(@rTypeId AS nvarchar(100)), 
	'@rOrgGroupId = ' + CAST(@rOrgGroupId AS nvarchar(100)) + ', @rTypeId = ' + CAST(@rTypeId AS nvarchar(100)) 
	+ ', @rType = ' +  CAST(@rType AS nvarchar(100))  + ', @rCommonOrgGroupBatchId = ' +  CAST(@rCommonOrgGroupBatchId AS nvarchar(100))
	+ ', @rFromDate = ' +  CAST(@rFromDate AS nvarchar(100))  + ', @rToDate = ' +  CAST(@rToDate AS nvarchar(100))
	+ ', @rReceiptBookId = ' +  CAST(@rReceiptBookId AS nvarchar(100))  + ', @rUserId = ' +  CAST(@rUserId AS nvarchar(100))
	+ ', @rOrgId = ' +  CAST(@rOrgId AS nvarchar(100))  + ', @rCommonFeeId = ' +  CAST(@rCommonFeeId AS nvarchar(100)), 
	'@rType: ' + CAST(@rType AS nvarchar(100)), 
	'', 
	GETDATE(), 
	'[sFee].[pFeeCollectionConsolidatedDashboardGet]')
END

--Changes for Mantis Id: 0039838
DECLARE @lConfigValue nvarchar(50)='', @lFromTime nvarchar(50)='', @lToTime nvarchar(50)='';

SELECT @lConfigValue = ItemValue FROM sConfig.tConfigurationSetup WITH (NOLOCK) WHERE ConfigurationId = 592   AND SourceTypeId = 2010   AND SourceId = @rOrgGroupId;


WITH SplitData AS (SELECT cast(item AS nvarchar(50)) AS item, ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) AS RowNum
    FROM sCommon.fnsplit(@lConfigValue, '-')
)
SELECT 
    @lFromTime = MAX(CASE WHEN RowNum = 1 THEN item END),
    @lToTime = MAX(CASE WHEN RowNum = 2 THEN item END)
FROM SplitData;


IF(@lConfigValue <> '' AND (CAST(CAST(GETDATE() AS DATE) AS DATETIME) + @lToTime) < (CAST(CAST(GETDATE() AS DATE) AS DATETIME) + @lFromTime))
BEGIN
	SET @lToTime = CAST(CAST((GETDATE()+1) AS DATE) AS DATETIME) + @lToTime
END
ELSE
BEGIN
	SET @lToTime = (CAST(CAST(GETDATE() AS DATE) AS DATETIME) + @lToTime)
END

IF(@lConfigValue <> '' AND (GETDATE() NOT BETWEEN (CAST(CAST(GETDATE() AS DATE) AS DATETIME) + @lFromTime) AND @lToTime))
BEGIN
	RETURN
END

--If @rFromDate= NULL Set @rFromDate = ''
--  If @rToDate =NULL Set @rToDate = ''
 DECLARE @cols NVARCHAR(MAX),@query  NVARCHAR(MAX),@cols1 NVARCHAR(MAX), @cols2 NVARCHAR(MAX); 
	---Fee Collection Wise  
			IF(@rTypeId=1)
				BEGIN
					SET @cols = STUFF((SELECT ',' +  QUOTENAME(PTM.Title )
					FROM sFinanceCommon.tPayTypeMaster PTM WITH (NOLOCK)
					--INNER JOIN  sFee.tReceipt R  ON PTM.Id=R.PayTypeId
					--INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.SourceId 
					GROUP BY PTM.Title
					FOR XML PATH(''), TYPE
					).value('.', 'NVARCHAR(MAX)') 
					,1,1,'')

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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


GO
ALTER PROCEDURE [sFee].[pFeeConsolidateDashBoardGet]
		
	@rType nvarchar(100)='',
	@rCount int =0 ,
	@rDivisionId int  =0,
	@rClassId int  =0,
	@rOrgId int  =0,
	@rOrgGroupId int=0,
	@rOrgGroupBatchId int  =0,
	@rCollectionGroupId int =0,
	@rReceiptBookId int =0,
	@rDays int=0,
	@rCommonOrgGroupBatchId int=0,
	@rFromDate varchar(10)='',
	@rToDate varchar(10)='',
	@rMonth int =0,
	@rSyncDate int =0,
	@rUserId bigint = 0,
	@rOsTypeId int = 0,
	@rPagePath nvarchar(500) = ''
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 

DECLARE @lIsLogEnable bit = 0

IF(@lIsLogEnable = 1)
BEGIN

	INSERT INTO [sSystem].[tTraceLog]
	(LogMessage, ExtraLogMessage, ExceptionLog, ExceptionDetailLog, CreatedDateTime, PagePath)
	VALUES
	('Type: ' + CAST(@rType AS nvarchar(100)), 
	'@rCount = ' + CAST(@rCount AS nvarchar(100)) + ', @rDivisionId = ' + CAST(@rDivisionId AS nvarchar(100)) 
	+ ', @rClassId = ' +  CAST(@rClassId AS nvarchar(100))  + ', @rOrgId = ' +  CAST(@rOrgId AS nvarchar(100))
	+ ', @rOrgGroupId = ' +  CAST(@rOrgGroupId AS nvarchar(100))  + ', @rOrgGroupBatchId = ' +  CAST(@rOrgGroupBatchId AS nvarchar(100))
	+ ', @rCollectionGroupId = ' +  CAST(@rCollectionGroupId AS nvarchar(100))  + ', @rReceiptBookId = ' +  CAST(@rReceiptBookId AS nvarchar(100))
	+ ', @rDays = ' +  CAST(@rDays AS nvarchar(100))  + ', @rCommonOrgGroupBatchId = ' +  CAST(@rCommonOrgGroupBatchId AS nvarchar(100))
	+ ', @rFromDate = ' +  CAST(@rFromDate AS nvarchar(100))  + ', @rToDate = ' +  CAST(@rToDate AS nvarchar(100))
	+ ', @rMonth = ' +  CAST(@rMonth AS nvarchar(100))  + ', @rSyncDate = ' +  CAST(@rSyncDate AS nvarchar(100)), 
	'@rUserId = ' + CAST(@rUserId AS nvarchar(100)) + ', @rOsTypeId = ' +  CAST(@rOsTypeId AS nvarchar(100)),
	'@rPagePath = ' + CAST(@rPagePath AS nvarchar(500)), 
	GETDATE(), 
	'[sFee].[pFeeConsolidateDashBoardGet]')
END

--Update sSetup.tOrgGroupMaster Set IsObsolete=0 WHERE IsObsolete IS NULL 

--Changes for Mantis Id: 0039838
DECLARE @lConfigValue nvarchar(50)='', @lFromTime nvarchar(50)='', @lToTime nvarchar(50)='';

SELECT @lConfigValue = ItemValue FROM sConfig.tConfigurationSetup WITH (NOLOCK) WHERE ConfigurationId = 592   AND SourceTypeId = 2010   AND SourceId = @rOrgGroupId;

WITH SplitData AS (SELECT cast(item AS nvarchar(50)) AS item, ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) AS RowNum
    FROM sCommon.fnsplit(@lConfigValue, '-')
)
SELECT 
    @lFromTime = MAX(CASE WHEN RowNum = 1 THEN item END),
    @lToTime = MAX(CASE WHEN RowNum = 2 THEN item END)
FROM SplitData;

IF(@lConfigValue <> '' AND (CAST(CAST(GETDATE() AS DATE) AS DATETIME) + @lToTime) < (CAST(CAST(GETDATE() AS DATE) AS DATETIME) + @lFromTime))
BEGIN
	SET @lToTime = CAST(CAST((GETDATE()+1) AS DATE) AS DATETIME) + @lToTime
END
ELSE
BEGIN
	SET @lToTime = (CAST(CAST(GETDATE() AS DATE) AS DATETIME) + @lToTime)
END

IF(@lConfigValue <> '' AND (GETDATE() NOT BETWEEN (CAST(CAST(GETDATE() AS DATE) AS DATETIME) + @lFromTime) AND @lToTime))
BEGIN
	RETURN
END

IF(@rType ='FeeStatusOrganization')
	BEGIN 
	IF(@rSyncDate =1)
		BEGIN
			DELETE  sFee.tTempOrgGroupFeeStatus WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))
				
				CREATE TABLE #tempOrganizationSync(
				PaidAmount DECIMAL(12,0),
				PendingAmount DECIMAL(12,0),
				OrgGroupName nvarchar(200),
				OrgGroupId int
				)
				INSERT INTO #tempOrganizationSync
					SELECT 
						SUM(ISNULL(FAS.PaidAmount,0)) AS PaidAmount,
						SUM(ISNULL(FAS.ToPayAmount,0.00))AS PendingAmount,
						O.Title AS OrgGroupName,
						O.Id AS OrgGroupId
					FROM 
						sStudent.tAcademic SA  WITH (NOLOCK)
						INNER JOIN sStudent.tStudentMaster SM WITH (NOLOCK) ON SA.StudentId = SM.Id
						INNER JOIN sFee.tFeeAllocationStudent FAS WITH (NOLOCK) ON FAS.AcademicId = SA.Id
						INNER JOIN sFee.tFeeSetup FS WITH (NOLOCK) ON FS.Id = FAS.FeeSetupId AND FS.AdmissionCategoryId=SA.AdmissionCategoryId
						INNER JOIN sSetup.tBatchMaster BM WITH (NOLOCK) ON BM.Id = SA.BatchId
						INNER JOIN sSetup.tOrgGroupBatchMaster OGBM WITH (NOLOCK) ON OGBM.ID=BM.OrgGroupBatchId
						INNER JOIN sSetup.tOrgGroupMaster O WITH (NOLOCK) ON O.Id =  OGBM.OrgGroupId		    
						INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM WITH (NOLOCK) ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
						INNER JOIN sSetup.tOrganizationMaster OM WITH (NOLOCK) ON OM.ID = SA.OrgId
					WHERE	
						  COGBM.Id=@rCommonOrgGroupBatchId 
						  --And ISNULL(O.IsObsolete,0) = 0
						  And O.IsObsolete <> 1
						  AND ((O.Id = @rOrgGroupId )OR(@rOrgGroupId=0))
						  AND FAS.PaidAmount >= 0		-- Added for Mantis : 0039379 By Dhananjay
						  AND FAS.ToPayAmount >= 0.00	-- Added for Mantis : 0039379 By Dhananjay
						  --AND SM.StatusId=1
						  -- IsInContext
						  AND BM.IsInContext = 1
					GROUP BY  o.Id,o.Title

					IF EXISTS (SELECT 1 FROM sFee.tTempOrgGroupFeeStatus WITH (NOLOCK) WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND OrgGroupId = @rOrgGroupId)
						BEGIN							
						IF(@rOrgGroupId !=0)
							INSERT INTO sFee.tTempOrgGroupFeeStatus
							SELECT @rCommonOrgGroupBatchId,T.OrgGroupName,T.OrgGroupId,ISNULL(T.PaidAmount,0) AS PaidAmount,ISNULL(T.PendingAmount,0) AS  PendingAmount,
							ISNULL(ISNULL(T.PaidAmount,0) + ISNULL(T.PendingAmount,0),0) AS TotalAmount,GETDATE() from #tempOrganizationSync T
							SELECT * FROM sFee.tTempOrgGroupFeeStatus WITH (NOLOCK) WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))
						END
					ELSE
						BEGIN						
						INSERT INTO sFee.tTempOrgGroupFeeStatus
							SELECT @rCommonOrgGroupBatchId,T.OrgGroupName,T.OrgGroupId,ISNULL(T.PaidAmount,0) AS PaidAmount,ISNULL(T.PendingAmount,0) AS  PendingAmount,
							ISNULL(ISNULL(T.PaidAmount,0) + ISNULL(T.PendingAmount,0),0) AS TotalAmount,GETDATE() from #tempOrganizationSync T
							SELECT * FROM sFee.tTempOrgGroupFeeStatus WITH (NOLOCK) WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))
						END
				
				DROP TABLE #tempOrganizationSync			
		END
	ELSE
		BEGIN

			IF  Exists(select 1 from sFee.tTempOrgGroupFeeStatus WITH (NOLOCK) where CONVERT(date,UpdatedDateTime) =  CONVERT(date,getdate(),102)   AND CommonOrgGroupBatchId=@rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))) 
			BEGIN
	
				SELECT * FROM sFee.tTempOrgGroupFeeStatus WITH (NOLOCK) WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))
				return
			END
		ELSE
			BEGIN
			DELETE  sFee.tTempOrgGroupFeeStatus WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))

			CREATE TABLE #tempOrganization(
				PaidAmount DECIMAL(12,0),
				PendingAmount DECIMAL(12,0),
				OrgGroupName nvarchar(200),
				OrgGroupId int
				)
			INSERT INTO #tempOrganization
					SELECT 
						SUM(ISNULL(FAS.PaidAmount,0)) AS PaidAmount,
						SUM(ISNULL(FAS.ToPayAmount,0.00))AS PendingAmount,
						O.Title AS OrgGroupName,
						O.Id AS OrgGroupId
					FROM 
						sStudent.tAcademic SA WITH (NOLOCK)
						INNER JOIN sStudent.tStudentMaster SM WITH (NOLOCK) ON SA.StudentId = SM.Id
						INNER JOIN sFee.tFeeAllocationStudent FAS WITH (NOLOCK) ON FAS.AcademicId = SA.Id 
						INNER JOIN sFee.tFeeSetup FS WITH (NOLOCK) ON FS.Id = FAS.FeeSetupId AND FS.AdmissionCategoryId=SA.AdmissionCategoryId -- Added AdmissionCategoryId Condition on join for Mantis : 0039379 By Dhananjay
						INNER JOIN sSetup.tBatchMaster BM WITH (NOLOCK) ON BM.Id = SA.BatchId
						INNER JOIN sSetup.tOrgGroupBatchMaster OGBM WITH (NOLOCK) ON OGBM.ID=BM.OrgGroupBatchId
						INNER JOIN sSetup.tOrgGroupMaster O WITH (NOLOCK) ON O.Id =  OGBM.OrgGroupId		    
						INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM WITH (NOLOCK) ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
						INNER JOIN sSetup.tOrganizationMaster OM WITH (NOLOCK) ON OM.ID = SA.OrgId
						
					WHERE	
						  COGBM.Id=@rCommonOrgGroupBatchId 
						  --And ISNULL(O.IsObsolete,0) = 0
						  And O.IsObsolete <> 1
						  AND ((O.Id = @rOrgGroupId )OR(@rOrgGroupId=0))
						  AND FAS.PaidAmount >= 0		-- Added for Mantis : 0039379 By Dhananjay
						  AND FAS.ToPayAmount >= 0.00	-- Added for Mantis : 0039379 By Dhananjay
						  -- IsInContext
						  AND BM.IsInContext = 1
					GROUP BY  o.Id,o.Title

						
				IF EXISTS (SELECT 1 FROM sFee.tTempOrgGroupFeeStatus WITH (NOLOCK) WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND OrgGroupId = @rOrgGroupId)
					BEGIN
						
					IF(@rOrgGroupId !=0)
						INSERT INTO sFee.tTempOrgGroupFeeStatus
						SELECT @rCommonOrgGroupBatchId,T.OrgGroupName,T.OrgGroupId,ISNULL(T.PaidAmount,0) AS PaidAmount,ISNULL(T.PendingAmount,0) AS  PendingAmount,
						ISNULL(ISNULL(T.PaidAmount,0) + ISNULL(T.PendingAmount,0),0) AS TotalAmount,GETDATE() from #tempOrganization  T
						SELECT * FROM sFee.tTempOrgGroupFeeStatus WITH (NOLOCK) WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))
					END
				ELSE
					BEGIN
					
					INSERT INTO sFee.tTempOrgGroupFeeStatus
						SELECT @rCommonOrgGroupBatchId,T.OrgGroupName,T.OrgGroupId,ISNULL(T.PaidAmount,0) AS PaidAmount,ISNULL(T.PendingAmount,0) AS  PendingAmount,
						ISNULL(ISNULL(T.PaidAmount,0) + ISNULL(T.PendingAmount,0),0) AS TotalAmount,GETDATE() from #tempOrganization  T
						SELECT * FROM sFee.tTempOrgGroupFeeStatus WITH (NOLOCK) WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))
					END 
					
				DROP TABLE #tempOrganization
			END
		END
	END
ELSE IF(@rType = 'FeeStatusPaid&UnpaidDetilsClassWise')
	BEGIN 
	IF(@rCount = 1)
	BEGIN

	CREATE TABLE #tempPaidDetailsClassWise(
	OrgGroupId int,
	OrgGroupName nvarchar(100),
	ClassId int,
	ClassName nvarchar(50),
	PaidAmount DECIMAL(12,0),
	StudentCount int
	,ClassOrderIndex INT,--add for mantis : 0042058
	DivisionOrder INT --add for mantis : 0042058
	)
  
	INSERT INTO #tempPaidDetailsClassWise
	SELECT 
		 ISNULL(O.Id,0) AS OrgGroupId,
		 SA.OrganizationName AS OrgGroupName,
		 ISNULL(SA.ClassId,0)AS ClassId,
		 ISNULL(SA.ClassName,'') AS ClassName,
		 SUM(ISNULL(FAS.PaidAmount,0)) AS PaidAmount,
		 COUNT(Distinct(SA.AcademicId)) as StudentCount
		 ,SA.ClassOrderIndex,--add for mantis : 0042058
		SA.DivisionOrder --add for mantis : 0042058
	FROM 		
		sStudent.vStudentAcademic SA WITH (NOLOCK)
		INNER JOIN sFee.tFeeAllocationStudent FAS WITH (NOLOCK) ON FAS.AcademicId = SA.AcademicId
		INNER JOIN sFee.tFeeSetup FS WITH (NOLOCK) ON FS.Id = FAS.FeeSetupId AND FS.AdmissionCategoryId=SA.AdmissionCategoryId -- Added AdmissionCategoryId Condition on join for Mantis : 0039379 By Dhananjay
	    INNER JOIN sSetup.tBatchMaster BM WITH (NOLOCK) ON BM.Id = SA.BatchId
	    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM WITH (NOLOCK) ON OGBM.ID=BM.OrgGroupBatchId
	    INNER JOIN sSetup.tOrgGroupMaster O WITH (NOLOCK) ON O.Id =  OGBM.OrgGroupId		    
	    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM WITH (NOLOCK) ON COGBM.Id=OGBM.CommonOrgGroupBatchId			
	WHERE
		(O.Id = @rOrgGroupId OR (@rOrgGroupId=0))	
		AND
		((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0))
		--And ISNULL(O.IsObsolete,0) = 0 
		And O.IsObsolete <> 1
		AND FAS.PaidAmount >= 0		-- Added = for Mantis : 0039379 By Dhananjay
		AND FAS.ToPayAmount >= 0.00	-- Added for Mantis : 0039379 By Dhananjay
		-- IsInContext
		AND BM.IsInContext = 1
	GROUP by O.Id,SA.OrgId,SA.ClassName,SA.ClassId,SA.OrganizationName
	 ,SA.ClassOrderIndex,SA.DivisionOrder -- class division order index add for mantis : 0042058
	ORDER BY O.Id
		,SA.ClassOrderIndex
		,SA.DivisionOrder --add for mantis : 0042058

		SELECT T.OrgGroupId,T.OrgGroupName,T.ClassId,T.ClassName AS ClassDivision,T.PaidAmount AS PaidAmount,T.StudentCount
		,T.ClassOrderIndex
		,T.DivisionOrder
		FROM #tempPaidDetailsClassWise T
		WHERE T.PaidAmount > 0
		ORDER BY T.OrgGroupId
			,T.ClassOrderIndex
			,T.DivisionOrder --add for mantis : 0042058
			 
	DROP TABLE #tempPaidDetailsClassWise
 
	END
	ELSE IF(@rCount = 2)
	BEGIN

	CREATE TABLE #tempPendingDetailsClassWise(
	AcademicId bigint,
	OrgGroupId int,
	OrgGroupName nvarchar(100),
	ClassId int,
	ClassName nvarchar(50),
	PendingAmount DECIMAL(12,0) 
	,ClassOrderIndex INT,--add for mantis : 0042058
	DivisionOrder INT --add for mantis : 0042058
	)
 
	INSERT INTO #tempPendingDetailsClassWise
	SELECT 
		 ISNULL(SA.AcademicId,0) AS AcademicId,
		 ISNULL(O.Id,0) AS OrgGroupId,
		 SA.OrganizationName AS OrgGroupName,
		 ISNULL(SA.ClassId,0)AS ClassId,
		 ISNULL(SA.ClassName,'') AS ClassName,
		 SUM(ISNULL(FAS.ToPayAmount,0.00))AS PendingAmount
		 ,SA.ClassOrderIndex,--add for mantis : 0042058
		 SA.DivisionOrder --add for mantis : 0042058
	FROM 		
		sStudent.vStudentAcademic SA WITH (NOLOCK)
		INNER JOIN sFee.tFeeAllocationStudent FAS WITH (NOLOCK) ON FAS.AcademicId = SA.AcademicId
		INNER JOIN sFee.tFeeSetup FS WITH (NOLOCK) ON FS.Id = FAS.FeeSetupId AND FS.AdmissionCategoryId=SA.AdmissionCategoryId
	    INNER JOIN sSetup.tBatchMaster BM WITH (NOLOCK) ON BM.Id = SA.BatchId
	    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM WITH (NOLOCK) ON OGBM.ID=BM.OrgGroupBatchId
	    INNER JOIN sSetup.tOrgGroupMaster O WITH (NOLOCK) ON O.Id =  OGBM.OrgGroupId		    
	    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM WITH (NOLOCK) ON COGBM.Id=OGBM.CommonOrgGroupBatchId			
	WHERE
		(LEFT(SA.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))	
		AND((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0))
		--nd ISNULL(O.IsObsolete,0) = 0 
		And O.IsObsolete <> 1
		AND FAS.ToPayAmount >= 0.00 --AND SA.StatusId=1 -- Added = for Mantis : 0039379 By Dhananjay
		AND FAS.PaidAmount >= 0		-- Added for Mantis : 0039379 By Dhananjay
		-- IsInContext
		AND BM.IsInContext = 1
	GROUP by O.Id,SA.OrgId,SA.ClassName,SA.ClassId,SA.OrganizationName,SA.AcademicId,SA.ClassOrderIndex,SA.DivisionOrder --add for mantis : 0042058

		SELECT T.OrgGroupId,T.OrgGroupName,T.ClassId,T.ClassName AS ClassDivision,ISNULL(SUM(T.PendingAmount),0) AS UnPaidAmount,COUNT(T.PendingAmount)AS StudentCount
		,T.ClassOrderIndex,T.DivisionOrder --add for mantis : 0042058
		FROM #tempPendingDetailsClassWise T
		--WHERE T.PendingAmount > 0
		GROUP BY T.OrgGroupId,T.ClassName,T.ClassId,T.OrgGroupName,T.ClassOrderIndex,T.DivisionOrder
		HAVING ISNULL(SUM(T.PendingAmount),0) > 0
		ORDER BY T.ClassOrderIndex,T.DivisionOrder -- remove classid add for mantis : 0042058
	 
	DROP TABLE #tempPendingDetailsClassWise
 
	END
	END
ELSE IF(@rType ='FeeStatusPaid&UnpaidDetils')
BEGIN 

	IF(@rCount = 1)
	BEGIN
		CREATE TABLE #tempPaidDetails(
			SourceId bigint,
			OrgGroupId int,
			ClassName nvarchar(50),
			DivisionId int,
			DivisionName nvarchar(50),
			Code nvarchar(20),
			Name nvarchar(200),
			ParentContactNo nvarchar(50),
			PaidAmount DECIMAL(12,0),
			ClassOrderIndex int,
			DivisionOrder int,
			RollNo int
		)
		INSERT INTO #tempPaidDetails
		SELECT 
				ISNULL(SA.AcademicId,0) AS SourceId,
				ISNULL(O.Id,0) AS OrgGroupId,
				ISNULL(SA.ClassName,'') AS ClassName,
				ISNULL(SA.DivisionId,0) AS DivisionId,
				ISNULL(SA.DivisionName,'') AS DivisionName,
				ISNULL(SA.Code,'') As Code,
				ISNULL(SA.Name,'') AS Name,
				ISNULL(SC.ParentContactNo,'') AS ParentContactNo,
				SUM(ISNULL(FAS.PaidAmount,0)) AS PaidAmount,
				 SA.ClassOrderIndex,  
				 SA.DivisionOrder,
				 SA.RollNo 
			FROM 		
				sStudent.vStudentAcademic SA WITH (NOLOCK)
				LEFT JOIN sStudent.tStudentCommunication SC WITH (NOLOCK) ON SC.StudentId = SA.StudentId
				INNER JOIN sFee.tFeeAllocationStudent FAS WITH (NOLOCK) ON FAS.AcademicId = SA.AcademicId
			    INNER JOIN sSetup.tBatchMaster BM WITH (NOLOCK) ON BM.Id = SA.BatchId
			    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM WITH (NOLOCK) ON OGBM.ID=BM.OrgGroupBatchId
			    INNER JOIN sSetup.tOrgGroupMaster O WITH (NOLOCK) ON O.Id =  OGBM.OrgGroupId		    
			    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM WITH (NOLOCK) ON COGBM.Id=OGBM.CommonOrgGroupBatchId			
		
		 WHERE
				(LEFT(SA.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))	
				AND((SA.ClassId = @rClassId)OR(@rClassId=0))
				AND ((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0))
				--And ISNULL(O.IsObsolete,0) = 0
				And O.IsObsolete <> 1
				AND FAS.PaidAmount > 0
				-- IsInContext
				AND BM.IsInContext = 1
		GROUP by O.Id,SA.ClassName,SA.DivisionName,SA.Name,SC.ParentContactNo,SA.Code,SA.ClassOrderIndex,SA.DivisionOrder,SA.RollNo,SA.DivisionId,SA.AcademicId
		Having SUM(ISNULL(FAS.PaidAmount,0)) >0
		ORDER BY O.Id,SA.ClassOrderIndex,SA.DivisionOrder,SA.RollNo

		SELECT T.SourceId, T.OrgGroupId,T.ClassName+' - '+  T.DivisionName  AS ClassDivision,T.Code AS Code,T.Name AS Name,T.DivisionId,
			T.ParentContactNo AS ParentContactNo,T.PaidAmount AS PaidAmount,T.ClassOrderIndex,T.DivisionOrder,T.RollNo
		FROM #tempPaidDetails T
		WHERE T.PaidAmount > 0
		GROUP BY T.OrgGroupId,T.ClassName,T.DivisionName,T.Name,T.ParentContactNo,T.PaidAmount,T.Code,T.ClassOrderIndex,T.DivisionOrder,T.RollNo,T.DivisionId,T.SourceId
		HAVING T.PaidAmount > 0
		ORDER BY T.OrgGroupId,T.ClassOrderIndex,T.DivisionOrder,T.RollNo
	END
	ELSE IF(@rCount = 2)
	BEGIN
		CREATE TABLE #tempPendingDetails(
			SourceId bigint,
			OrgGroupId int,
			ClassName nvarchar(50),
			DivisionId int,
			DivisionName nvarchar(50),
			Code nvarchar(20),
			Name nvarchar(200),
			ParentContactNo nvarchar(50),
			PendingAmount DECIMAL(12,0),
			ClassOrderIndex int,
			DivisionOrder int,
			RollNo int
		)
		INSERT INTO #tempPendingDetails
		SELECT 
				ISNULL(SA.AcademicId,0) AS SourceId,
				ISNULL(O.Id,0) AS OrgGroupId,
				ISNULL(SA.ClassName,'') AS ClassName,
				ISNULL(SA.DivisionId,0) AS DivisionId,
				ISNULL(SA.DivisionName,'') AS DivisionName,
				ISNULL(SA.Code,'') As Code,
				ISNULL(SA.Name,'') AS Name,
				ISNULL(SC.ParentContactNo,'') AS ParentContactNo,
				SUM(ISNULL(FAS.ToPayAmount,0.00))AS PendingAmount,
				SA.ClassOrderIndex,  
				SA.DivisionOrder,
				SA.RollNo 
			FROM 		
				sStudent.vStudentAcademic SA WITH (NOLOCK)
				LEFT JOIN sStudent.tStudentCommunication SC WITH (NOLOCK) ON SC.StudentId = SA.StudentId
				INNER JOIN sFee.tFeeAllocationStudent FAS WITH (NOLOCK) ON FAS.AcademicId = SA.AcademicId
				INNER JOIN sFee.tFeeSetup FS WITH (NOLOCK) ON FS.Id = FAS.FeeSetupId AND FS.AdmissionCategoryId=SA.AdmissionCategoryId
			    INNER JOIN sSetup.tBatchMaster BM WITH (NOLOCK) ON BM.Id = SA.BatchId
			    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM WITH (NOLOCK) ON OGBM.ID=BM.OrgGroupBatchId
			    INNER JOIN sSetup.tOrgGroupMaster O WITH (NOLOCK) ON O.Id =  OGBM.OrgGroupId		    
			    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM WITH (NOLOCK) ON COGBM.Id=OGBM.CommonOrgGroupBatchId			
		
		 WHERE
				(LEFT(SA.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))	
				AND((SA.ClassId = @rClassId)OR(@rClassId=0))
				AND ((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0))
				--And ISNULL(O.IsObsolete,0) = 0 
				And O.IsObsolete <> 1
				AND FAS.ToPayAmount > 0.00 --AND SA.StatusId=1
				-- IsInContext
				AND BM.IsInContext = 1
				
		GROUP by O.Id,SA.ClassName,SA.DivisionName,SA.Name,SC.ParentContactNo,SA.Code,SA.ClassOrderIndex,SA.DivisionOrder,SA.RollNo,SA.DivisionId,SA.AcademicId
		ORDER BY O.Id,SA.ClassOrderIndex,SA.DivisionOrder,SA.RollNo

		SELECT T.SourceId, T.OrgGroupId,T.ClassName+' - '+  T.DivisionName  AS ClassDivision,T.Code AS Code,T.Name AS Name,T.DivisionId,
			T.ParentContactNo AS ParentContactNo,T.PendingAmount AS UnPaidAmount,T.ClassOrderIndex,T.DivisionOrder,T.RollNo
		FROM #tempPendingDetails T
		WHERE T.PendingAmount > 0
		GROUP BY T.OrgGroupId,T.ClassName,T.DivisionName,T.Name,T.ParentContactNo,T.PendingAmount,T.Code,T.ClassOrderIndex,T.DivisionOrder,T.RollNo,T.DivisionId,T.SourceId
		HAVING T.PendingAmount > 0
		ORDER BY T.OrgGroupId,T.ClassOrderIndex,T.DivisionOrder,T.RollNo
	END
END

ELSE IF(@rType ='FeeStatusTotalHeadwiseAmount')
BEGIN 
	IF(@rSyncDate =1)
		BEGIN
		DELETE  sFee.tTempTotalPaidDetails WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))
		DELETE  sFee.tTempTotalStudentCount WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))
		DELETE  sFee.tTempPendingCount WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))

			CREATE TABLE #tempTotalPaidDetailsSync (
				FeeHeadId bigint,
				FeeHeadName nvarchar(200),
				CollectionGroupId bigint,
				CollectionGroup nvarchar(200),
				ReceiptBookId bigint,
				RecepitTitle nvarchar(100),
				PaidAmount DECIMAL(12,0),
				PendingAmount DECIMAL(12,0),
				OrderIndex int
			)
			 
			INSERT INTO #tempTotalPaidDetailsSync
			SELECT 
				ISNULL(FHM.Id,0) AS FeeHeadId,
				ISNULL(FHM.code,'') AS FeeHeadName,
				ISNULL(CGM.Id,0) AS CollectionGroupId,
				ISNULL(CGM.Code,'') AS CollectionGroup,
				ISNULL(RBM.Id,'')  AS ReceiptBookId,
				ISNULL(RBM.Title,'')  AS ReceiptTitle,
				SUM(ISNULL(FAS.PaidAmount,0)) AS PaidAmount,
				SUM(ISNULL(FAS.ToPayAmount,0.00))AS PendingAmount,
				FHM.OrderIndex
			FROM 
				sStudent.tAcademic SA WITH (NOLOCK)
				INNER JOIN sStudent.tStudentMaster SM WITH (NOLOCK) ON SA.StudentId = SM.Id
				INNER JOIN sFee.tFeeAllocationStudent FAS WITH (NOLOCK) ON FAS.AcademicId = SA.Id 
				INNER JOIN sFee.tFeeSetup FS WITH (NOLOCK) ON FS.Id = FAS.FeeSetupId AND FS.AdmissionCategoryId=SA.AdmissionCategoryId -- Added for Mantis : 0039379 By Hemali
				INNER JOIN sSetup.tBatchMaster BM WITH (NOLOCK) ON BM.Id = SA.BatchId
				INNER JOIN sSetup.tOrgGroupBatchMaster OGBM WITH (NOLOCK) ON OGBM.ID=BM.OrgGroupBatchId
				INNER JOIN sSetup.tOrgGroupMaster O WITH (NOLOCK) ON O.Id =  OGBM.OrgGroupId		    
				INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM WITH (NOLOCK) ON COGBM.Id=OGBM.CommonOrgGroupBatchId			
				INNER JOIN sFee.tReceiptBookMaster RBM WITH (NOLOCK) ON FS.ReceiptBookId=RBM.Id
				LEFT JOIN sFee.tCollectionGroupMaster CGM WITH (NOLOCK) ON FS.CollectionGroupId=CGM.Id AND RBM.Id = CGM.ReceiptBookId 
				INNER JOIN sFee.tFeeMaster FM WITH (NOLOCK) ON FM.Id = FS.FeeId
				INNER JOIN sFee.tFeeHeadMaster FHM WITH (NOLOCK) ON FHM.Id=FM.FeeHeadId	
			WHERE
			 (O.Id = @rOrgGroupId OR (@rOrgGroupId=0))	
			 AND ((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0))
			 --And ISNULL(O.IsObsolete,0) = 0
			 And O.IsObsolete <> 1
			 -- IsInContext
			AND FAS.PaidAmount >= 0	-- Added for Mantis : 0039379 By Hemali
			AND FAS.ToPayAmount >= 0.00  -- Added for Mantis : 0039379 By Hemali
				AND BM.IsInContext = 1
			GROUP BY FHM.Id,FHM.code,CGM.Id,CGM.Code,RBM.Title,RBM.Id,FHM.OrderIndex

			INSERT INTO sFee.tTempTotalPaidDetails
			SELECT @rOrgGroupId,T.FeeHeadId,ISNULL(T.FeeHeadName,'') AS FeeHeadName,T.CollectionGroupId,
						ISNULL(T.CollectionGroup,'') As CollectionGroup,ISNULL(T.ReceiptBookId,0)AS ReceiptBookId,
						T.RecepitTitle +'-'+T.CollectionGroup AS ReceiptCollection,
						ISNULL(T.PaidAmount,0) AS PaidAmount,ISNULL(T.PendingAmount,0) AS  PendingAmount,
						ISNULL(ISNULL(T.PaidAmount,0)+ISNULL(T.PendingAmount,0),0) AS TotalAmount,
						T.OrderIndex,@rCommonOrgGroupBatchId,GETDATE() from #tempTotalPaidDetailsSync T
			GROUP BY T.PaidAmount,T.PendingAmount,T.CollectionGroup,T.FeeHeadName,T.FeeHeadId,T.RecepitTitle,T.ReceiptBookId,T.CollectionGroupId,T.OrderIndex
			ORDER BY T.OrderIndex

			SELECT * FROM sFee.tTempTotalPaidDetails WITH (NOLOCK) WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))		

		--New Temp Table Create-------------
			CREATE TABLE #tempTotalStudentCountSync (
			AcademicId bigint,
			CollectionGroupId bigint,
			CollectionGroup nvarchar(200),
			RecepitTitle nvarchar(100),
			ReceiptBookId bigint,
			EndDate date,
			PaidAmount DECIMAL(12,0),
			PendingAmount DECIMAL(12,0)
			)
	
			--Test
			--Added for query optimization - TRIS Loading issue - 10 Jan 2025
			DECLARE @lTopReceiptDate datetime = (SELECT TOP 1 ReceiptDate 
					FROM sFee.tReceipt R  WITH (NOLOCK)
					INNER JOIN sStudent.tAcademic SA WITH (NOLOCK) ON SA.Id=R.SourceId 
					INNER JOIN sStudent.tStudentMaster SM WITH (NOLOCK) ON SA.StudentId = SM.Id
					INNER JOIN sFee.tCollectionGroupMaster CGM WITH (NOLOCK) ON CGM.ReceiptBookId = R.ReceiptBookId
					WHERE (LEFT(CGM.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))
					ORDER BY ReceiptDate DESC)
			--Added for query optimization - TRIS Loading issue - 10 Jan 2025

			INSERT INTO #tempTotalStudentCountSync
			SELECT 
					ISNULL(SA.Id,0) AS AcademicId,
					ISNULL(CGM.Id,0) AS CollectionGroupId,
					ISNULL(CGM.Code,'') AS CollectionGroup,
					ISNULL(RBM.Title,'')  AS ReceiptTitle,
					ISNULL(RBM.Id,0) As ReceiptBookId,
					--Commented due to not useful as getting same receiptdate for every record - TRIS Loading issue - 10 Jan 2025
					--(SELECT TOP 1 ReceiptDate FROM sFee.tReceipt R 
					--INNER JOIN sStudent.tAcademic SA ON SA.Id=R.SourceId 
					--INNER JOIN sStudent.tStudentMaster SM ON SA.StudentId = SM.Id
					--INNER JOIN sFee.tCollectionGroupMaster CGM ON CGM.ReceiptBookId = R.ReceiptBookId
					--WHERE  (LEFT(CGM.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))
					-- ORDER BY ReceiptDate DESC) EndDate,
					--Commented due to not useful as getting same receiptdate for every record - TRIS Loading issue - 10 Jan 2025
					@lTopReceiptDate AS EndDate,
					SUM(ISNULL(FAS.PaidAmount,0)) AS PaidAmount,
					SUM(ISNULL(FAS.ToPayAmount,0.00))AS PendingAmount
			FROM 
				sStudent.tAcademic SA WITH (NOLOCK)
				INNER JOIN sStudent.tStudentMaster SM WITH (NOLOCK) ON SA.StudentId = SM.Id
		        INNER JOIN sFee.tFeeAllocationStudent FAS WITH (NOLOCK) ON FAS.AcademicId = SA.Id 
				INNER JOIN sFee.tFeeSetup FS WITH (NOLOCK) ON FAS.FeeSetupId = FS.Id AND FS.AdmissionCategoryId=SA.AdmissionCategoryId   -- Added for Mantis : 0039379 By Hemali
				INNER JOIN sSetup.tBatchMaster BM WITH (NOLOCK) ON BM.Id = SA.BatchId
				INNER JOIN sSetup.tOrgGroupBatchMaster OGBM WITH (NOLOCK) ON OGBM.ID=BM.OrgGroupBatchId
				INNER JOIN sSetup.tOrgGroupMaster O WITH (NOLOCK) ON O.Id =  OGBM.OrgGroupId		    
				INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM WITH (NOLOCK) ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
				INNER JOIN sFee.tReceiptBookMaster RBM WITH (NOLOCK) ON FS.ReceiptBookId=RBM.Id
				LEFT JOIN sFee.tCollectionGroupMaster CGM WITH (NOLOCK) ON FS.CollectionGroupId=CGM.Id AND RBM.Id = CGM.ReceiptBookId 
				INNER JOIN sFee.tFeeMaster FM WITH (NOLOCK) ON FS.FeeId = FM.Id
				INNER JOIN sFee.tFeeHeadMaster FHM WITH (NOLOCK) ON FHM.Id=FM.FeeHeadId	
			WHERE
			 (O.Id = @rOrgGroupId OR (@rOrgGroupId=0))	
			 --And ISNULL(O.IsObsolete,0) = 0
			 And O.IsObsolete <> 1
			 AND COGBM.Id=@rCommonOrgGroupBatchId 
			 -- IsInContext
				AND FAS.PaidAmount >= 0	  -- Added for Mantis : 0039379 By Hemali
				AND FAS.ToPayAmount >= 0.00  -- Added for Mantis : 0039379 By Hemali
				AND BM.IsInContext = 1
			GROUP BY SA.Id,CGM.Id,CGM.Code,RBM.Title,RBM.Id,CGM.EndDate
	
			INSERT INTO sFee.tTempTotalStudentCount
			SELECT @rOrgGroupId,E.CollectionGroupId,E.CollectionGroup AS CollectionGroup,E.ReceiptBookId AS ReceiptId,E.ReceiptCollection AS ReceiptCollection,
					ISNULL(E.EndDate,'1900-01-01')AS EndDate,
					--E.EndDate AS EndDate,
					SUM(E.TotalStudentCount) AS TotalStudentCount,SUM(E.PaidStudentCount) AS PaidStudentCount,SUM(E.PendingStudentCount) AS PendingStudentCount,
					@rCommonOrgGroupBatchId,GETDATE() 
			FROM (
				SELECT ISNULL(T.ReceiptBookId,0) AS ReceiptBookId,T.RecepitTitle +'-'+T.CollectionGroup AS ReceiptCollection,
						ISNULL(T.CollectionGroup,'') As CollectionGroup,
						ISNULL(COUNT(T.AcademicId),0) AS TotalStudentCount,T.CollectionGroupId AS CollectionGroupId,
						ISNULL(A.PaidCount,0) AS PaidStudentCount,ISNULL(B.PendingCount,0) AS PendingStudentCount,
						CASE CONVERT(varchar(20),T.EndDate,103) WHEN '01/01/1900' THEN '' ELSE T.EndDate END  AS EndDate 
						from #tempTotalStudentCountSync T
						LEFT JOIN 
						(
							SELECT CollectionGroupId,ReceiptBookId,ISNULL(COUNT(AcademicId),0) AS PaidCount  FROM #tempTotalStudentCountSync --CollectionGroupId,CollectionGroup,
							WHERE PendingAmount  = 0
							GROUP BY CollectionGroupId,ReceiptBookId
						) A ON A.CollectionGroupId = T.CollectionGroupId
						LEFT JOIN 
						(
							SELECT CollectionGroupId,ReceiptBookId,ISNULL(COUNT(AcademicId),0) AS PendingCount  FROM #tempTotalStudentCountSync
							WHERE PendingAmount !=0
							GROUP BY CollectionGroupId,ReceiptBookId
						)B ON B.CollectionGroupId = T.CollectionGroupId 
						GROUP BY T.CollectionGroupId,T.CollectionGroup,T.RecepitTitle,T.ReceiptBookId,T.CollectionGroup,A.PaidCount,B.PendingCount,T.EndDate
						)E
					GROUP BY E.ReceiptBookId,E.ReceiptCollection,E.CollectionGroup,E.EndDate,E.CollectionGroupId
		
		 SELECT * FROM sFee.tTempTotalStudentCount WITH (NOLOCK) WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))	


		-------------Create a New Temp Table For Pending date-----------------
			CREATE TABLE #tempPendingCountSync(
			AcademicId bigint,
			CollectionGroupId bigint,
			CollectionGroup nvarchar(200),
			RecepitTitle nvarchar(100),
			ReceiptBookId bigint,
			EndDate date,
			PaidAmount DECIMAL(12,0),
			PendingAmount DECIMAL(12,0)
			)
	 
			DECLARE @lLastReceiptDate datetime
			SET @lLastReceiptDate = (SELECT TOP 1 ReceiptDate FROM sFee.tReceipt R WITH (NOLOCK)
							INNER JOIN sStudent.tAcademic SA WITH (NOLOCK) ON SA.Id=R.SourceId
							INNER JOIN sStudent.tStudentMaster SM WITH (NOLOCK) ON SA.StudentId = SM.Id
							INNER JOIN sSetup.tBatchMaster BM WITH (NOLOCK) ON BM.Id = SA.BatchId
							INNER JOIN sSetup.tOrgGroupBatchMaster OGBM WITH (NOLOCK) ON OGBM.ID=R.OrgGroupBatchId
							INNER JOIN sSetup.tOrgGroupMaster O WITH (NOLOCK) ON O.Id =  OGBM.OrgGroupId		    
							INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM WITH (NOLOCK) ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
							INNER JOIN sSetup.tOrganizationMaster OM WITH (NOLOCK) ON SA.OrgId = OM.Id 
							INNER JOIN sFee.tCollectionGroupMaster CGM WITH (NOLOCK) ON CGM.ReceiptBookId = R.ReceiptBookId
					WHERE  
							(LEFT(R.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0)) --AND BM.IsActive=1 
							AND ((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0))
							--And ISNULL(O.IsObsolete,0) = 0
							And O.IsObsolete <> 1
							-- IsInContext
						AND BM.IsInContext = 1
					ORDER BY ReceiptDate DESC)

			INSERT INTO #tempPendingCountSync
			SELECT 
					ISNULL(SA.Id,0) AS AcademicId,
					ISNULL(CGM.Id,0) AS CollectionGroupId,
					ISNULL(CGM.Code,'') AS CollectionGroup,
					ISNULL(RBM.Title,'')  AS ReceiptTitle,
					ISNULL(RBM.Id,0) As ReceiptBookId,
					@lLastReceiptDate AS EndDate,
					SUM(ISNULL(FAS.PaidAmount,0)) AS PaidAmount,
					SUM(ISNULL(FAS.ToPayAmount,0.00))AS PendingAmount
			FROM 
				sStudent.tAcademic SA WITH (NOLOCK)
				INNER JOIN sStudent.tStudentMaster SM WITH (NOLOCK) ON SA.StudentId = SM.Id
				LEFT JOIN sStudent.tStudentCommunication SC WITH (NOLOCK) ON SC.StudentId = SA.StudentId
				INNER JOIN sFee.tFeeAllocationStudent FAS WITH (NOLOCK) ON FAS.AcademicId = SA.Id
				INNER JOIN sFee.tFeeSetup FS WITH (NOLOCK) ON FAS.FeeSetupId = FS.Id AND FS.AdmissionCategoryId=SA.AdmissionCategoryId  -- Added for Mantis : 0039379 By Hemali
				INNER JOIN sFee.tFeeMaster FM WITH (NOLOCK) ON FM.Id = FS.FeeId
				INNER JOIN sFee.tFeeHeadMaster FHM WITH (NOLOCK) ON FHM.Id=FM.FeeHeadId	
				INNER JOIN sSetup.tBatchMaster BM WITH (NOLOCK) ON BM.Id = SA.BatchId
				INNER JOIN sSetup.tOrgGroupBatchMaster OGBM WITH (NOLOCK) ON OGBM.ID=BM.OrgGroupBatchId
				INNER JOIN sSetup.tOrgGroupMaster O WITH (NOLOCK) ON O.Id =  OGBM.OrgGroupId		    
				INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM WITH (NOLOCK) ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
				INNER JOIN sFee.tReceiptBookMaster RBM WITH (NOLOCK) ON FS.ReceiptBookId=RBM.Id
				LEFT JOIN sFee.tCollectionGroupMaster CGM WITH (NOLOCK) ON FS.CollectionGroupId=CGM.Id AND RBM.Id = CGM.ReceiptBookId 
				
			WHERE
			 (O.Id = @rOrgGroupId OR (@rOrgGroupId=0))	
			 --And ISNULL(O.IsObsolete,0) = 0
			 And O.IsObsolete <> 1
			 AND ((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0))  
			 -- IsInContext
				AND FAS.PaidAmount >= 0	  -- Added for Mantis : 0039379 By Hemali
				AND FAS.ToPayAmount >= 0.00  -- Added for Mantis : 0039379 By Hemali
				AND BM.IsInContext = 1
			GROUP BY SA.Id,CGM.Id,CGM.Code,RBM.Title,RBM.Id,CGM.EndDate

			INSERT INTO sFee.tTempPendingCount
			SELECT @rOrgGroupId,ISNULL(T.CollectionGroupId,0) AS CollectionGroupId,ISNULL(T.CollectionGroup,'') As CollectionGroup,T.ReceiptBookId AS ReceiptId,
						T.RecepitTitle +'-'+T.CollectionGroup AS ReceiptCollection,ISNULL(COUNT(T.AcademicId),0) AS LastPendingCount,@rCommonOrgGroupBatchId,GETDATE()
			FROM   #tempPendingCountSync T
			WHERE PendingAmount !=0
			 AND  CONVERT(DATE,T.EndDate) BETWEEN CONVERT(DATE,GETDATE()- @rDays) AND CONVERT(DATE,GETDATE())
			GROUP BY T.CollectionGroupId,T.CollectionGroup,T.ReceiptBookId,T.RecepitTitle,T.CollectionGroup

			SELECT * FROM sFee.tTempPendingCount WITH (NOLOCK) WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))	
	 
			DROP TABLE #tempTotalPaidDetailsSync
			DROP TABLE #tempTotalStudentCountSync
			DROP TABLE #tempPendingCountSync

		END
	ELSE
		BEGIN
		IF  Exists(select 1 from sFee.tTempTotalPaidDetails WITH (NOLOCK) where CONVERT(date,UpdateDate) =  CONVERT(date,getdate(),102)   AND CommonOrgGroupBatchId=@rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0)) )
			BEGIN
	
				SELECT * FROM sFee.tTempTotalPaidDetails WITH (NOLOCK) WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))
				SELECT * FROM sFee.tTempTotalStudentCount WITH (NOLOCK) WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))
				SELECT * FROM sFee.tTempPendingCount WITH (NOLOCK) WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))
				return
			END
		ELSE
			BEGIN

			DELETE  sFee.tTempTotalPaidDetails WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))
			DELETE  sFee.tTempTotalStudentCount WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))
			DELETE  sFee.tTempPendingCount WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))

			CREATE TABLE #tempTotalPaidDetails (
				FeeHeadId bigint,
				FeeHeadName nvarchar(200),
				CollectionGroupId bigint,
				CollectionGroup nvarchar(200),
				ReceiptBookId bigint,
				RecepitTitle nvarchar(100),
				PaidAmount DECIMAL(12,0),
				PendingAmount DECIMAL(12,0),
				OrderIndex int
				)
			
				INSERT INTO #tempTotalPaidDetails
				SELECT 
					ISNULL(FHM.Id,0) AS FeeHeadId,
					ISNULL(FHM.code,'') AS FeeHeadName,
					ISNULL(CGM.Id,0) AS CollectionGroupId,
					ISNULL(CGM.Code,'') AS CollectionGroup,
					ISNULL(RBM.Id,'')  AS ReceiptBookId,
					ISNULL(RBM.Title,'')  AS ReceiptTitle,
					SUM(ISNULL(FAS.PaidAmount,0)) AS PaidAmount,
					SUM(ISNULL(FAS.ToPayAmount,0.00))AS PendingAmount,
					FHM.OrderIndex
				FROM 
					sStudent.tAcademic SA WITH (NOLOCK)
					INNER JOIN sStudent.tStudentMaster SM WITH (NOLOCK) ON SA.StudentId = SM.Id
					INNER JOIN sFee.tFeeAllocationStudent FAS WITH (NOLOCK) ON FAS.AcademicId = SA.Id
					INNER JOIN sFee.tFeeSetup FS WITH (NOLOCK) ON FS.Id = FAS.FeeSetupId AND FS.AdmissionCategoryId=SA.AdmissionCategoryId   -- Added for Mantis : 0039379 By Hemali
					INNER JOIN sSetup.tBatchMaster BM WITH (NOLOCK) ON BM.Id = SA.BatchId
					INNER JOIN sSetup.tOrgGroupBatchMaster OGBM WITH (NOLOCK) ON OGBM.ID=BM.OrgGroupBatchId
					INNER JOIN sSetup.tOrgGroupMaster O WITH (NOLOCK) ON O.Id =  OGBM.OrgGroupId		    
					INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM WITH (NOLOCK) ON COGBM.Id=OGBM.CommonOrgGroupBatchId			
					INNER JOIN sFee.tReceiptBookMaster RBM WITH (NOLOCK) ON FS.ReceiptBookId=RBM.Id
					LEFT JOIN sFee.tCollectionGroupMaster CGM WITH (NOLOCK) ON FS.CollectionGroupId=CGM.Id AND RBM.Id = CGM.ReceiptBookId 
					INNER JOIN sFee.tFeeMaster FM WITH (NOLOCK) ON FM.Id = FS.FeeId
					INNER JOIN sFee.tFeeHeadMaster FHM WITH (NOLOCK) ON FHM.Id=FM.FeeHeadId	
				WHERE
				 (O.Id = @rOrgGroupId OR (@rOrgGroupId=0))	
				 AND ((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0))
				 --And ISNULL(O.IsObsolete,0) = 0
				 And O.IsObsolete <> 1
				 -- IsInContext

				 -- Added for Mantis : 0039379 By Hemali
				AND FAS.PaidAmount >= 0	  
				AND FAS.ToPayAmount >= 0.00
				AND BM.IsInContext = 1
				GROUP BY FHM.Id,FHM.code,CGM.Id,CGM.Code,RBM.Title,RBM.Id,FHM.OrderIndex

			INSERT INTO sFee.tTempTotalPaidDetails
				SELECT @rOrgGroupId,T.FeeHeadId,ISNULL(T.FeeHeadName,'') AS FeeHeadName,T.CollectionGroupId,
				ISNULL(T.CollectionGroup,'') As CollectionGroup,ISNULL(T.ReceiptBookId,0)AS ReceiptBookId,
				T.RecepitTitle +'-'+T.CollectionGroup AS ReceiptCollection,
				ISNULL(T.PaidAmount,0) AS PaidAmount,ISNULL(T.PendingAmount,0) AS  PendingAmount,
				ISNULL(ISNULL(T.PaidAmount,0)+ISNULL(T.PendingAmount,0),0) AS TotalAmount,
				T.OrderIndex,@rCommonOrgGroupBatchId,GETDATE()from #tempTotalPaidDetails T
				GROUP BY T.PaidAmount,T.PendingAmount,T.CollectionGroup,T.FeeHeadName,T.FeeHeadId,T.RecepitTitle,T.ReceiptBookId,T.CollectionGroupId,T.OrderIndex
				ORDER BY T.OrderIndex

			SELECT * FROM sFee.tTempTotalPaidDetails WITH (NOLOCK) WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))	

					--New Temp Table Create-------------
				CREATE TABLE #tempTotalStudentCount (
				AcademicId bigint,
				CollectionGroupId bigint,
				CollectionGroup nvarchar(200),
				RecepitTitle nvarchar(100),
				ReceiptBookId bigint,
				EndDate date,
				PaidAmount DECIMAL(12,0),
				PendingAmount DECIMAL(12,0)
				)
	
				--Test
				--Added for query optimization - TRIS Loading issue - 10 Jan 2025
				DECLARE @lTopReceiptDate1 datetime = (SELECT TOP 1 ReceiptDate 
					FROM sFee.tReceipt R WITH (NOLOCK) 
					INNER JOIN sStudent.tAcademic SA WITH (NOLOCK) ON SA.Id=R.SourceId 
					INNER JOIN sStudent.tStudentMaster SM WITH (NOLOCK) ON SA.StudentId = SM.Id
					INNER JOIN sFee.tCollectionGroupMaster CGM WITH (NOLOCK) ON CGM.ReceiptBookId = R.ReceiptBookId
					WHERE  (LEFT(CGM.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))
					ORDER BY ReceiptDate DESC)
				--Added for query optimization - TRIS Loading issue - 10 Jan 2025
	
				INSERT INTO #tempTotalStudentCount
				SELECT 
					ISNULL(SA.Id,0) AS AcademicId,
					ISNULL(CGM.Id,0) AS CollectionGroupId,
					ISNULL(CGM.Code,'') AS CollectionGroup,
					ISNULL(RBM.Title,'')  AS ReceiptTitle,
					ISNULL(RBM.Id,0) As ReceiptBookId,
					--Commented due to not useful as getting same receiptdate for every record - TRIS Loading issue - 10 Jan 2025
					--(SELECT TOP 1 ReceiptDate FROM sFee.tReceipt R 
					--INNER JOIN sStudent.tAcademic SA ON SA.Id=R.SourceId 
					--INNER JOIN sStudent.tStudentMaster SM ON SA.StudentId = SM.Id
					--INNER JOIN sFee.tCollectionGroupMaster CGM ON CGM.ReceiptBookId = R.ReceiptBookId
					--WHERE  (LEFT(CGM.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))
					-- ORDER BY ReceiptDate DESC) EndDate,
					--Commented due to not useful as getting same receiptdate for every record - TRIS Loading issue - 10 Jan 2025
					@lTopReceiptDate1 AS EndDate,
					SUM(ISNULL(FAS.PaidAmount,0)) AS PaidAmount,
					SUM(ISNULL(FAS.ToPayAmount,0.00))AS PendingAmount
				FROM 
					sStudent.tAcademic SA WITH (NOLOCK)
					INNER JOIN sStudent.tStudentMaster SM WITH (NOLOCK) ON SA.StudentId = SM.Id
					INNER JOIN sFee.tFeeAllocationStudent FAS WITH (NOLOCK) ON FAS.AcademicId = SA.Id 
					INNER JOIN sFee.tFeeSetup FS WITH (NOLOCK) ON FAS.FeeSetupId = FS.Id AND FS.AdmissionCategoryId=SA.AdmissionCategoryId  -- Added for Mantis : 0039379 By Hemali
					INNER JOIN sSetup.tBatchMaster BM WITH (NOLOCK) ON BM.Id = SA.BatchId
					INNER JOIN sSetup.tOrgGroupBatchMaster OGBM WITH (NOLOCK) ON OGBM.ID=BM.OrgGroupBatchId
					INNER JOIN sSetup.tOrgGroupMaster O WITH (NOLOCK) ON O.Id =  OGBM.OrgGroupId		    
					INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM WITH (NOLOCK) ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
					INNER JOIN sFee.tReceiptBookMaster RBM WITH (NOLOCK) ON FS.ReceiptBookId=RBM.Id
					LEFT JOIN sFee.tCollectionGroupMaster CGM WITH (NOLOCK) ON FS.CollectionGroupId=CGM.Id AND RBM.Id = CGM.ReceiptBookId 
					INNER JOIN sFee.tFeeMaster FM WITH (NOLOCK) ON FS.FeeId = FM.Id
					INNER JOIN sFee.tFeeHeadMaster FHM WITH (NOLOCK) ON FHM.Id=FM.FeeHeadId	
				WHERE
				 (O.Id = @rOrgGroupId OR (@rOrgGroupId=0))	
				 --And ISNULL(O.IsObsolete,0) = 0
				 And O.IsObsolete <> 1
				 AND COGBM.Id=@rCommonOrgGroupBatchId 
				 -- IsInContext
				 -- Added for Mantis : 0039379 By Hemali
				AND FAS.PaidAmount >= 0	
				AND FAS.ToPayAmount >= 0.00
				AND BM.IsInContext = 1
				GROUP BY SA.Id,CGM.Id,CGM.Code,RBM.Title,RBM.Id,CGM.EndDate
	
			INSERT INTO sFee.tTempTotalStudentCount
			SELECT @rOrgGroupId,E.CollectionGroupId,E.CollectionGroup AS CollectionGroup,E.ReceiptBookId AS ReceiptId,
			E.ReceiptCollection AS ReceiptCollection,
					ISNULL(E.EndDate,'1900-01-01')AS EndDate,
					--E.EndDate AS EndDate,
					SUM(E.TotalStudentCount) AS TotalStudentCount,
					SUM(E.PaidStudentCount) AS PaidStudentCount,
					SUM(E.PendingStudentCount) AS PendingStudentCount,
					@rCommonOrgGroupBatchId,GETDATE() FROM (
			SELECT ISNULL(T.ReceiptBookId,0) AS ReceiptBookId,T.RecepitTitle +'-'+T.CollectionGroup AS ReceiptCollection,
			ISNULL(T.CollectionGroup,'') As CollectionGroup,
				ISNULL(COUNT(T.AcademicId),0) AS TotalStudentCount,T.CollectionGroupId AS CollectionGroupId,
				ISNULL(A.PaidCount,0) AS PaidStudentCount,ISNULL(B.PendingCount,0) AS PendingStudentCount,
				CASE CONVERT(varchar(20),T.EndDate,103) WHEN '01/01/1900' THEN '' ELSE T.EndDate END  AS EndDate from #tempTotalStudentCount T
					LEFT JOIN 
					(
						SELECT CollectionGroupId,ReceiptBookId,ISNULL(COUNT(AcademicId),0) AS PaidCount  FROM #tempTotalStudentCount --CollectionGroupId,CollectionGroup,
						WHERE PendingAmount  = 0
						GROUP BY CollectionGroupId,ReceiptBookId
					) A ON A.CollectionGroupId = T.CollectionGroupId
					LEFT JOIN 
					(
						SELECT CollectionGroupId,ReceiptBookId,ISNULL(COUNT(AcademicId),0) AS PendingCount  FROM #tempTotalStudentCount
						WHERE PendingAmount !=0
						GROUP BY CollectionGroupId,ReceiptBookId
					)B ON B.CollectionGroupId = T.CollectionGroupId 
					GROUP BY T.CollectionGroupId,T.CollectionGroup,T.RecepitTitle,T.ReceiptBookId,T.CollectionGroup,A.PaidCount,B.PendingCount,T.EndDate
					)E
					GROUP BY E.ReceiptBookId,E.ReceiptCollection,E.CollectionGroup,E.EndDate,E.CollectionGroupId
				 
				 SELECT * FROM sFee.tTempTotalStudentCount WITH (NOLOCK) WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))

					-------------Create a New Temp Table For Pending date-----------------
				CREATE TABLE #tempPendingCount(
				AcademicId bigint,
				CollectionGroupId bigint,
				CollectionGroup nvarchar(200),
				RecepitTitle nvarchar(100),
				ReceiptBookId bigint,
				EndDate date,
				PaidAmount DECIMAL(12,0),
				PendingAmount DECIMAL(12,0)
				)
				
				--Added for query optimization - TRIS Loading issue - 10 Jan 2025
				DECLARE @lTopReceiptDate2 datetime = (SELECT TOP 1 ReceiptDate FROM sFee.tReceipt R 
					INNER JOIN sStudent.tAcademic SA WITH (NOLOCK) ON SA.Id=R.SourceId
					INNER JOIN sStudent.tStudentMaster SM WITH (NOLOCK) ON SA.StudentId = SM.Id
					INNER JOIN sSetup.tBatchMaster BM WITH (NOLOCK) ON BM.Id = SA.BatchId
					INNER JOIN sSetup.tOrgGroupBatchMaster OGBM WITH (NOLOCK) ON OGBM.ID=BM.OrgGroupBatchId
					INNER JOIN sSetup.tOrgGroupMaster O WITH (NOLOCK) ON O.Id =  OGBM.OrgGroupId		    
					INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM WITH (NOLOCK) ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
					INNER JOIN sSetup.tOrganizationMaster OM WITH (NOLOCK) ON SA.OrgId = OM.Id 
					INNER JOIN sFee.tCollectionGroupMaster CGM WITH (NOLOCK) ON CGM.ReceiptBookId = R.ReceiptBookId
					  WHERE  
							(LEFT(BM.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))
							AND ((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0))
							And O.IsObsolete <> 1
						AND BM.IsInContext = 1
					  ORDER BY ReceiptDate DESC)
				--Added for query optimization - TRIS Loading issue - 10 Jan 2025

				INSERT INTO #tempPendingCount
				SELECT 
					ISNULL(SA.Id,0) AS AcademicId,
					ISNULL(CGM.Id,0) AS CollectionGroupId,
					ISNULL(CGM.Code,'') AS CollectionGroup,
					ISNULL(RBM.Title,'')  AS ReceiptTitle,
					ISNULL(RBM.Id,0) As ReceiptBookId,
					--Commented due to not useful as getting same receiptdate for every record - TRIS Loading issue - 10 Jan 2025
					--(SELECT TOP 1 ReceiptDate FROM sFee.tReceipt R 
					--INNER JOIN sStudent.tAcademic SA ON SA.Id=R.SourceId
					--INNER JOIN sStudent.tStudentMaster SM ON SA.StudentId = SM.Id
					--INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId
					--INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
					--INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
					--INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
					--INNER JOIN sSetup.tOrganizationMaster OM ON SA.OrgId = OM.Id 
					--INNER JOIN sFee.tCollectionGroupMaster CGM ON CGM.ReceiptBookId = R.ReceiptBookId
					--  WHERE  
					--		(LEFT(BM.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0)) --AND BM.IsActive=1 
					--		AND ((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0))
					--		--And ISNULL(O.IsObsolete,0) = 0
					--		And O.IsObsolete <> 1
					--		-- IsInContext
					--	AND BM.IsInContext = 1
					--  ORDER BY ReceiptDate DESC) EndDate,
					--Commented due to not useful as getting same receiptdate for every record - TRIS Loading issue - 10 Jan 2025
					@lTopReceiptDate2 AS EndDate,
					SUM(ISNULL(FAS.PaidAmount,0)) AS PaidAmount,
					SUM(ISNULL(FAS.ToPayAmount,0.00))AS PendingAmount
			FROM 
				sStudent.tAcademic SA WITH (NOLOCK)
				INNER JOIN sStudent.tStudentMaster SM WITH (NOLOCK) ON SA.StudentId = SM.Id
				LEFT JOIN sStudent.tStudentCommunication SC WITH (NOLOCK) ON SC.StudentId = SA.StudentId
				INNER JOIN sFee.tFeeAllocationStudent FAS WITH (NOLOCK) ON FAS.AcademicId = SA.Id
				INNER JOIN sFee.tFeeSetup FS WITH (NOLOCK) ON FAS.FeeSetupId = FS.Id AND FS.AdmissionCategoryId=SA.AdmissionCategoryId  -- Added for Mantis : 0039379 By Hemali
				INNER JOIN sSetup.tBatchMaster BM WITH (NOLOCK) ON BM.Id = SA.BatchId
				INNER JOIN sSetup.tOrgGroupBatchMaster OGBM WITH (NOLOCK) ON OGBM.ID=BM.OrgGroupBatchId
				INNER JOIN sSetup.tOrgGroupMaster O WITH (NOLOCK) ON O.Id =  OGBM.OrgGroupId		    
				INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM WITH (NOLOCK) ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
				INNER JOIN sFee.tReceiptBookMaster RBM WITH (NOLOCK) ON FS.ReceiptBookId=RBM.Id
				LEFT JOIN sFee.tCollectionGroupMaster CGM WITH (NOLOCK) ON FS.CollectionGroupId=CGM.Id AND RBM.Id = CGM.ReceiptBookId 
				INNER JOIN sFee.tFeeMaster FM WITH (NOLOCK) ON FM.Id = FS.FeeId
				INNER JOIN sFee.tFeeHeadMaster FHM WITH (NOLOCK) ON FHM.Id=FM.FeeHeadId	
			WHERE
			 (O.Id = @rOrgGroupId OR (@rOrgGroupId=0))	
			 --And ISNULL(O.IsObsolete,0) = 0
			 And O.IsObsolete <> 1
			 AND ((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0))  
			 -- IsInContext

			 -- Added for Mantis : 0039379 By Hemali
			AND FAS.PaidAmount >= 0	
			AND FAS.ToPayAmount >= 0.00
				AND BM.IsInContext = 1
			GROUP BY SA.Id,CGM.Id,CGM.Code,RBM.Title,RBM.Id,CGM.EndDate
		
		INSERT INTO sFee.tTempPendingCount
				SELECT @rOrgGroupId,ISNULL(T.CollectionGroupId,0) AS CollectionGroupId,ISNULL(T.CollectionGroup,'') As CollectionGroup,T.ReceiptBookId AS ReceiptId,
				T.RecepitTitle +'-'+T.CollectionGroup AS ReceiptCollection,ISNULL(COUNT(T.AcademicId),0) AS LastPendingCount,@rCommonOrgGroupBatchId,GETDATE()
				FROM   #tempPendingCount T
				WHERE PendingAmount !=0
				 AND  CONVERT(DATE,T.EndDate) BETWEEN CONVERT(DATE,GETDATE()- @rDays) AND CONVERT(DATE,GETDATE())
				 GROUP BY T.CollectionGroupId,T.CollectionGroup,T.ReceiptBookId,T.RecepitTitle,T.CollectionGroup
		SELECT * FROM sFee.tTempPendingCount WITH (NOLOCK) WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))	
	
				DROP TABLE #tempTotalPaidDetails
				DROP TABLE #tempTotalStudentCount
				DROP TABLE #tempPendingCount
			END
		END
END

ELSE IF(@rType ='FeeStatusPaidSubPartAmount')
BEGIN 
	CREATE TABLE #tempPaidSubPart (
	OrgGroupId int,
	OrgGroupName nvarchar(100),
	ClassId bigint,
	ClassName nvarchar(50),
	--DivisionId bigint,
	--DivisionName nvarchar(50),
	CollectionGroupId bigint,
	CollectionGroup nvarchar(200),
	RecepitTitle nvarchar(100),
	ReceiptBookId bigint,
	PaidAmount DECIMAL(12,0),
	PendingAmount DECIMAL(12,0),
	ClassOrderIndex int,
	StudentCount int
	,DivisionOrder int
	)
    
IF(@rCollectionGroupId = 0)
	BEGIN
	INSERT INTO #tempPaidSubPart
	SELECT 
		 SA.OrgId AS OrgGroupId,
		 SA.OrganizationName AS OrgGroupName,
		 SA.ClassId AS ClassId,
		 SA.ClassName AS ClassName,
		 ISNULL(CGM.Id,0) AS CollectionGroupId,
		 ISNULL(CGM.Code,'') AS CollectionGroup,
		 ISNULL(RBM.Title,'')  AS ReceiptTitle,
		 ISNULL(RBM.Id,0) As ReceiptBookId,
		 SUM(ISNULL(FAS.PaidAmount,0)) AS PaidAmount,
		 SUM(ISNULL(FAS.ToPayAmount,0.00))AS PendingAmount,
		 SA.ClassOrderIndex,
		 COUNT(Distinct(FAS.AcademicId)) as StudentCount
		 ,SA.DivisionOrder --add for mantis : 0042058
	FROM 
		sStudent.vStudentAcademic SA WITH (NOLOCK)
		INNER JOIN sFee.tFeeAllocationStudent FAS WITH (NOLOCK) ON FAS.AcademicId = SA.AcademicId
		INNER JOIN sFee.tFeeSetup FS WITH (NOLOCK) ON FS.Id = FAS.FeeSetupId
	    INNER JOIN sSetup.tBatchMaster BM WITH (NOLOCK) ON BM.Id = SA.BatchId
	    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM WITH (NOLOCK) ON OGBM.ID=BM.OrgGroupBatchId
	    INNER JOIN sSetup.tOrgGroupMaster O WITH (NOLOCK) ON O.Id =  OGBM.OrgGroupId		    
	    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM WITH (NOLOCK) ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
		INNER JOIN sFee.tReceiptBookMaster RBM WITH (NOLOCK) ON FS.ReceiptBookId=RBM.Id
		LEFT JOIN sFee.tCollectionGroupMaster CGM WITH (NOLOCK) ON FS.CollectionGroupId=CGM.Id AND RBM.Id = CGM.ReceiptBookId 
		INNER JOIN sFee.tFeeMaster FM WITH (NOLOCK) ON FS.FeeId = FM.Id
	    INNER JOIN sFee.tFeeHeadMaster FHM WITH (NOLOCK) ON FHM.Id=FM.FeeHeadId	    	
	WHERE
		(LEFT(SA.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))	
		AND ((RBM.Id = @rReceiptBookId) OR (@rReceiptBookId=0))
		AND ((CGM.Id = @rCollectionGroupId) OR (@rCollectionGroupId=0))
		AND ((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0))  
		--And ISNULL(O.IsObsolete,0) = 0
		And O.IsObsolete <> 1
		AND FAS.PaidAmount > 0
		-- IsInContext
		AND BM.IsInContext = 1
	GROUP by SA.OrgId,SA.OrganizationName,SA.ClassName,SA.ClassId,SA.AcademicId,CGM.Id,CGM.Code,RBM.Title,RBM.Id,SA.ClassOrderIndex,SA.DivisionOrder
	HAVING ISNULL(SUM(FAS.PaidAmount),0) > 0
	ORDER BY SA.ClassOrderIndex,SA.DivisionOrder --add for mantis : 0042058

		select T.OrgGroupId,T.OrgGroupName,T.ClassId,T.ClassName AS ClassDivision,T.PaidAmount AS PaidAmount, T.StudentCount AS StudentCount,
			ISNULL(T.CollectionGroupId,0) AS CollectionGroupId,T.ReceiptBookId AS ReceiptBookId,T.ClassOrderIndex,
			'' as MonthName ,T.ClassOrderIndex,T.DivisionOrder --add for mantis : 0042058
		from #tempPaidSubPart T
		 

	END 
	ELSE 
	BEGIN
	INSERT INTO #tempPaidSubPart
		
	SELECT 
		 SA.OrgId AS OrgGroupId,SA.OrganizationName As OrgGroupName,
		 SA.ClassId As ClassId,
		 SA.ClassName AS ClassName,
		 ISNULL(CGM.Id,0) AS CollectionGroupId,
		 ISNULL(CGM.Code,'') AS CollectionGroup,
		 ISNULL(RBM.Title,'')  AS ReceiptTitle,
		 ISNULL(RBM.Id,0) As ReceiptBookId,
		 SUM(ISNULL(FAS.PaidAmount,0)) AS PaidAmount,
		 SUM(ISNULL(FAS.ToPayAmount,0.00))AS PendingAmount,
		 SA.ClassOrderIndex,
		 COUNT(Distinct(FAS.AcademicId)) as StudentCount
		 ,SA.DivisionOrder --add for mantis : 0042058
	FROM 
		sStudent.vStudentAcademic SA WITH (NOLOCK)
		INNER JOIN sFee.tFeeAllocationStudent FAS WITH (NOLOCK) ON FAS.AcademicId = SA.AcademicId
		INNER JOIN sFee.tFeeSetup FS WITH (NOLOCK) ON FS.Id = FAS.FeeSetupId
	    INNER JOIN sSetup.tBatchMaster BM WITH (NOLOCK) ON BM.Id = SA.BatchId
	    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM WITH (NOLOCK) ON OGBM.ID=BM.OrgGroupBatchId
	    INNER JOIN sSetup.tOrgGroupMaster O WITH (NOLOCK) ON O.Id =  OGBM.OrgGroupId		    
	    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM WITH (NOLOCK) ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
		INNER JOIN sFee.tReceiptBookMaster RBM WITH (NOLOCK) ON FS.ReceiptBookId=RBM.Id
		LEFT JOIN sFee.tCollectionGroupMaster CGM WITH (NOLOCK) ON FS.CollectionGroupId=CGM.Id AND RBM.Id = CGM.ReceiptBookId 
		INNER JOIN sFee.tFeeMaster FM WITH (NOLOCK) ON FM.Id = FS.FeeId
		INNER JOIN sFee.tFeeHeadMaster FHM WITH (NOLOCK) ON FHM.Id=FM.FeeHeadId	
	WHERE
		 (LEFT(SA.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))	
		 AND ((RBM.Id = @rReceiptBookId) OR (@rReceiptBookId=0))
		 AND ((CGM.Id = @rCollectionGroupId) OR (@rCollectionGroupId=0))
		 AND ((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0)) 
		 --And ISNULL(O.IsObsolete,0) = 0
		 And O.IsObsolete <> 1
		 AND FAS.PaidAmount > 0
		 -- IsInContext
		AND BM.IsInContext = 1
    GROUP by SA.OrgId,SA.OrganizationName,SA.ClassName,SA.ClassId,CGM.Id,CGM.Code,RBM.Title,RBM.Id,SA.ClassOrderIndex,SA.DivisionOrder
	HAVING ISNULL(SUM(FAS.PaidAmount),0) > 0
	ORDER BY SA.ClassOrderIndex,SA.DivisionOrder

	select T.OrgGroupId,T.OrgGroupName,T.ClassId,T.ClassName AS ClassDivision,T.PaidAmount AS PaidAmount,T.StudentCount As StudentCount,
		ISNULL(T.CollectionGroupId,0) AS CollectionGroupId,T.ReceiptBookId AS ReceiptBookId,T.ClassOrderIndex,
		'' as MonthName ,T.DivisionOrder
		from #tempPaidSubPart T
	END
	
	DROP TABLE #tempPaidSubPart

END

ELSE IF(@rType ='FeeStatusPaidSubPartAmountMonthWise')
BEGIN 
	CREATE TABLE #tempPaidSubPartMonthWise (
	AcademicId bigint,
	OrgGroupId int,
	OrgGroupName nvarchar(100),
	CollectionGroupId bigint,
	CollectionGroup nvarchar(200),
	RecepitTitle nvarchar(100),
	ReceiptBookId bigint,
	PaidAmount DECIMAL(12,0),
	PendingAmount DECIMAL(12,0),
	MonthName nvarchar(15),
	)
   
    CREATE TABLE #tempPFSMonthWise (
Id INT,
       Amount DECIMAL(12,0),
       FeeHeadId INT,
       CollectionGroupId INT,
       ReceiptBookId INT,
       AcademicId BIGINT  
    )

    INSERT INTO #tempPFSMonthWise	
    SELECT 
		FS1.Id,
		ISNULL(FS1.Amount,0)AS Amount,
		FM.FeeHeadId,
		FS1.CollectionGroupId,
		ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
		SA1.Id AS AcademicId
	FROM sFee.tFeeSetup FS1 WITH (NOLOCK)
		INNER JOIN sStudent.tAcademic SA1 WITH (NOLOCK) ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
	    INNER JOIN sStudent.tStudentMaster SM WITH (NOLOCK) ON SA1.StudentId = SM.Id
		INNER JOIN sSetup.tBatchMaster BM WITH (NOLOCK) ON BM.Id = SA1.BatchId
	    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM WITH (NOLOCK) ON OGBM.ID=BM.OrgGroupBatchId
	    INNER JOIN sSetup.tOrgGroupMaster O WITH (NOLOCK) ON O.Id =  OGBM.OrgGroupId		    
	    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM WITH (NOLOCK) ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
		INNER JOIN  sSetup.tOrganizationMaster OM WITH (NOLOCK) ON SA1.OrgId = OM.Id
		INNER JOIN sFee.tFeeMaster FM WITH (NOLOCK) ON FM.Id=FS1.FeeId
	WHERE 
	   (FS1.IsOptional=0)
	   --AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
		AND (LEFT(BM.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0)) --AND BM.IsActive=1 
		AND ((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0))
		--And ISNULL(O.IsObsolete,0) = 0
		And O.IsObsolete <> 1
		-- IsInContext
		AND BM.IsInContext = 1
		--AND FS1.StartDate>=@rFromDate AND FS1.EndDate<=@rToDate   
		--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='')
	UNION ALL
				
	SELECT 
		FS1.Id,
		ISNULL(FS1.Amount,0)AS Amount,
		FM.FeeHeadId,
		FS1.CollectionGroupId,
		ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
		SA1.Id AS AcademicId
	FROM sFee.tFeeSetup FS1 WITH (NOLOCK)
		INNER JOIN sFee.tFeeOptional FO WITH (NOLOCK) ON FO.FeeSetupId=FS1.Id 
	    INNER JOIN sFee.tFeeMaster FM WITH (NOLOCK) ON FM.Id=FS1.FeeId
		INNER JOIN sStudent.tAcademic SA1 WITH (NOLOCK) ON SA1.Id=FO.SourceId
		INNER JOIN sStudent.tStudentMaster SM WITH (NOLOCK) ON SA1.StudentId = SM.Id
	    INNER JOIN sSetup.tBatchMaster BM WITH (NOLOCK) ON BM.Id = SA1.BatchId
	    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM WITH (NOLOCK) ON OGBM.ID=BM.OrgGroupBatchId
	    INNER JOIN sSetup.tOrgGroupMaster O WITH (NOLOCK) ON O.Id =  OGBM.OrgGroupId		    
	    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM WITH (NOLOCK) ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
		INNER JOIN  sSetup.tOrganizationMaster OM WITH (NOLOCK) ON SA1.OrgId = OM.Id 
		AND FS1.BatchId = SA1.BatchId AND SA1.ClassId=FS1.ClassId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId 
		--AND BM.IsActive=1 
		AND ((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0))
		--And ISNULL(O.IsObsolete,0) = 0
		And O.IsObsolete <> 1
		--AND FS1.StartDate>=@rFromDate AND FS1.EndDate<=@rToDate  
	WHERE
				
	    (FS1.IsOptional=1)
		AND (LEFT(BM.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))
		-- IsInContext
		AND BM.IsInContext = 1
		--AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))


     CREATE TABLE #tempPRMonthWise (
         PaidAmount DECIMAL(12,0),
	     FeeSetupId INT,
	     SourceId BIGINT,
		  ReceiptDate DATE
     )
     INSERT INTO #tempPRMonthWise	
     SELECT 
		  ISNULL(SUM(RD.Amount),0) AS PaidAmount,RD.FeeSetupId ,R.SourceId,R.ReceiptDate
	 FROM
		  sFee.tReceipt R WITH (NOLOCK) 
		  INNER JOIN sFee.tReceiptDetail RD WITH (NOLOCK) ON RD.ReceiptId = R.Id 
		  INNER JOIN sFee.tFeeSetup FS WITH (NOLOCK) ON RD.FeeSetupId = FS.Id
		  INNER JOIN sFee.tFeeMaster FM WITH (NOLOCK) ON FS.FeeId = FM.Id
		  INNER JOIN sStudent.tAcademic SA1 WITH (NOLOCK) ON SA1.Id=R.SourceId 
		  INNER JOIN sStudent.tStudentMaster SM WITH (NOLOCK) ON SA1.StudentId = SM.Id
		  INNER JOIN sSetup.tBatchMaster BM WITH (NOLOCK) ON BM.Id = SA1.BatchId
		  INNER JOIN sSetup.tOrgGroupBatchMaster OGBM WITH (NOLOCK) ON OGBM.ID=BM.OrgGroupBatchId
		  INNER JOIN sSetup.tOrgGroupMaster O WITH (NOLOCK) ON O.Id =  OGBM.OrgGroupId		    
		  INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM WITH (NOLOCK) ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
		  INNER JOIN  sSetup.tOrganizationMaster OM WITH (NOLOCK) ON SA1.OrgId = OM.Id 
		 
	WHERE		
		  (R.SourceTypeId = 2001)
		   AND (LEFT(BM.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))
		   AND (R.IsObsolete = 0) --AND BM.IsActive=1 
		   AND COGBM.Id=@rCommonOrgGroupBatchId 
		   --And ISNULL(O.IsObsolete,0) = 0
		   And O.IsObsolete <> 1
		   -- IsInContext
		AND BM.IsInContext = 1
		   --AND FS.StartDate>=@rFromDate AND FS.EndDate<=@rToDate    
		   --AND ((SA1.OrgGroupBatchId = @rOrgGroupBatchId) OR(@rOrgGroupBatchId=0))
	GROUP BY FeeSetupId,R.SourceId,R.ReceiptDate
 

IF(@rCollectionGroupId = 0)
	BEGIN
	INSERT INTO #tempPaidSubPartMonthWise
SELECT 
		ISNULL(SA.AcademicId,0) AS AcademicId,
		 O.Id AS OrgGroupId,
		 O.Title As OrgGroupName,
		ISNULL(CGM.Id,0) AS CollectionGroupId,
		ISNULL(CGM.Code,'') AS CollectionGroup,
		ISNULL(RBM.Title,'')  AS ReceiptTitle,
		ISNULL(RBM.Id,0) As ReceiptBookId,
		SUM(ISNULL(TPR.PaidAmount,0)) AS PaidAmount,
		SUM(ISNULL(TPFS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(TPR.PaidAmount,0.00))AS PendingAmount,
		TPR.ReceiptDate		 
	FROM 
		sStudent.vStudentAcademic SA WITH (NOLOCK)
		INNER JOIN #tempPFSMonthWise TPFS ON TPFS.AcademicId=SA.AcademicId
		LEFT JOIN sFee.tFeeAllocation FA WITH (NOLOCK) ON FA.FeeSetupId=TPFS.Id AND FA.SourceId=SA.AcademicId
		LEFT JOIN #tempPRMonthWise TPR ON TPR.FeeSetupId = TPFS.Id AND SA.AcademicId = TPR.SourceId
	    INNER JOIN sSetup.tBatchMaster BM WITH (NOLOCK) ON BM.Id = SA.BatchId
	    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM WITH (NOLOCK) ON OGBM.ID=BM.OrgGroupBatchId
	    INNER JOIN sSetup.tOrgGroupMaster O WITH (NOLOCK) ON O.Id =  OGBM.OrgGroupId		    
	    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM WITH (NOLOCK) ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
		
		INNER JOIN sFee.tReceiptBookMaster RBM WITH (NOLOCK) ON TPFS.ReceiptBookId=RBM.Id
		LEFT JOIN sFee.tCollectionGroupMaster CGM WITH (NOLOCK) ON TPFS.CollectionGroupId=CGM.Id AND RBM.Id = CGM.ReceiptBookId-- AND (CGM.OrgGroupBatchId = 0 OR(0=0))
	    INNER JOIN sFee.tFeeHeadMaster FHM WITH (NOLOCK) ON FHM.Id=TPFS.FeeHeadId	    	
	WHERE
	 (LEFT(SA.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))	
	 AND ((RBM.Id = @rReceiptBookId) OR (@rReceiptBookId=0))
	AND  ISNULL(CGM.Id,0)=0
	--And ISNULL(O.IsObsolete,0) = 0
	And O.IsObsolete <> 1
	-- IsInContext
	AND BM.IsInContext = 1  
	-- ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
	--AND(SA.IsActiveBatch =1) 
	AND ((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0))  
		GROUP by O.Id,O.Title,SA.AcademicId,CGM.Id,CGM.Code,RBM.Title,RBM.Id,TPR.ReceiptDate
	
	select T.OrgGroupId,T.OrgGroupName,ISNULL(SUM(T.PaidAmount),0) AS PaidAmount, COUNT(T.AcademicId) AS StudentCount,
		ISNULL(T.CollectionGroupId,0) AS CollectionGroupId,T.ReceiptBookId AS ReceiptBookId,DATENAME(month,T.MonthName)MonthName,DATEPART(M, T.MonthName) AS Month from #tempPaidSubPartMonthWise T
		group by T.OrgGroupId,T.PaidAmount,T.CollectionGroupId,T.ReceiptBookId,T.OrgGroupName,DATENAME(month,T.MonthName),DATEPART(M, T.MonthName)
		HAVING ISNULL(SUM(T.PaidAmount),0) > 0
		--ORDER BY DATEPART(MONTH, T.MonthName)
	END 
	ELSE 
	BEGIN
	
	CREATE TABLE #tempPFSMonthWise1 (
       Id INT,
       Amount DECIMAL(12,0),
       FeeHeadId INT,
      CollectionGroupId INT,
       ReceiptBookId INT,
       AcademicId BIGINT  
 )
    INSERT INTO #tempPFSMonthWise1
    SELECT 
		 FS1.Id,
		 ISNULL(FS1.Amount,0)AS Amount,
		 FM.FeeHeadId,
		 FS1.CollectionGroupId,
		 ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
		 SA1.Id AS AcademicId
	FROM sFee.tFeeSetup FS1 WITH (NOLOCK)
		 INNER JOIN sStudent.tAcademic SA1 WITH (NOLOCK) ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
	     INNER JOIN sStudent.tStudentMaster SM WITH (NOLOCK) ON SA1.StudentId = SM.Id
		 INNER JOIN sSetup.tBatchMaster BM WITH (NOLOCK) ON BM.Id = SA1.BatchId
	     INNER JOIN sSetup.tOrgGroupBatchMaster OGBM WITH (NOLOCK) ON OGBM.ID=BM.OrgGroupBatchId
	     INNER JOIN sSetup.tOrgGroupMaster O WITH (NOLOCK) ON O.Id =  OGBM.OrgGroupId		    
	     INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM WITH (NOLOCK) ON COGBM.Id=OGBM.CommonOrgGroupBatchId			 
		 INNER JOIN  sSetup.tOrganizationMaster OM WITH (NOLOCK) ON SA1.OrgId = OM.Id 
	   
		 INNER JOIN sFee.tFeeMaster FM WITH (NOLOCK) ON FM.Id=FS1.FeeId
	WHERE 
		(FS1.IsOptional=0) --AND BM.IsActive=1 
		AND COGBM.Id=@rCommonOrgGroupBatchId --AND FS1.StartDate>=@rFromDate AND FS1.EndDate<=@rToDate    
		 --AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
		 AND (LEFT(BM.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))
		 --And ISNULL(O.IsObsolete,0) = 0
		 And O.IsObsolete <> 1
		 -- IsInContext
	AND BM.IsInContext = 1  
		 --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='')
	UNION ALL
				
	SELECT 
		 FS1.Id,
		 ISNULL(FS1.Amount,0)AS Amount,
		 FM.FeeHeadId,
		 FS1.CollectionGroupId,
		 ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
		SA1.Id AS AcademicId
	FROM sFee.tFeeSetup FS1 WITH (NOLOCK)
		INNER JOIN sFee.tFeeOptional FO WITH (NOLOCK) ON FO.FeeSetupId=FS1.Id 
	    INNER JOIN sFee.tFeeMaster FM WITH (NOLOCK) ON FM.Id=FS1.FeeId
		INNER JOIN sStudent.tAcademic SA1 WITH (NOLOCK) ON SA1.Id=FO.SourceId AND FS1.BatchId = SA1.BatchId AND SA1.ClassId=FS1.ClassId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
	  INNER JOIN sStudent.tStudentMaster SM WITH (NOLOCK) ON SA1.StudentId = SM.Id
		INNER JOIN sSetup.tBatchMaster BM WITH (NOLOCK) ON BM.Id = SA1.BatchId
	    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM WITH (NOLOCK) ON OGBM.ID=BM.OrgGroupBatchId
	    INNER JOIN sSetup.tOrgGroupMaster O WITH (NOLOCK) ON O.Id =  OGBM.OrgGroupId		    
	    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM WITH (NOLOCK) ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
		INNER JOIN  sSetup.tOrganizationMaster OM WITH (NOLOCK) ON SA1.OrgId = OM.Id 
		
	WHERE
				
		(FS1.IsOptional=1) AND (LEFT(BM.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0)) --AND BM.IsActive=1 
		AND ((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0))
		--And ISNULL(O.IsObsolete,0) = 0
		And O.IsObsolete <> 1
		-- IsInContext
	AND BM.IsInContext = 1  
		--AND FS1.StartDate>=@rFromDate AND FS1.EndDate<=@rToDate  
			--AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
    
    CREATE TABLE #tempPRMonthWise1(
         PaidAmount DECIMAL(12,0),
	     FeeSetupId INT,
	     SourceId BIGINT,
		  ReceiptDate DATE
     )
     INSERT INTO #tempPRMonthWise1
     SELECT 
		ISNULL(SUM(RD.Amount),0) AS PaidAmount,
		RD.FeeSetupId ,R.SourceId,R.ReceiptDate
	 FROM
		sFee.tReceipt R WITH (NOLOCK) 
		INNER JOIN sFee.tReceiptDetail RD WITH (NOLOCK) ON RD.ReceiptId = R.Id 
		INNER JOIN sFee.tFeeSetup FS WITH (NOLOCK) ON RD.FeeSetupId = FS.Id
		INNER JOIN sFee.tFeeMaster FM WITH (NOLOCK) ON FS.FeeId = FM.Id
		INNER JOIN sStudent.tAcademic SA1 WITH (NOLOCK) ON SA1.Id=R.SourceId
		INNER JOIN sStudent.tStudentMaster SM WITH (NOLOCK) ON SA1.StudentId = SM.Id
	    INNER JOIN sSetup.tBatchMaster BM WITH (NOLOCK) ON BM.Id = SA1.BatchId
	    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM WITH (NOLOCK) ON OGBM.ID=BM.OrgGroupBatchId
	    INNER JOIN sSetup.tOrgGroupMaster O WITH (NOLOCK) ON O.Id =  OGBM.OrgGroupId		    
	    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM WITH (NOLOCK) ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
		INNER JOIN  sSetup.tOrganizationMaster OM WITH (NOLOCK) ON SA1.OrgId = OM.Id 
	WHERE		
		(R.SourceTypeId = 2001)
		AND (LEFT(BM.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0)) --AND BM.IsActive=1 
		AND ((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0))--AND FS.StartDate>=@rFromDate AND FS.EndDate<=@rToDate   
		AND (R.IsObsolete = 0) 
		-- IsInContext
	AND BM.IsInContext = 1  
		--AND ((SA1.OrgGroupBatchId = @rOrgGroupBatchId) OR(@rOrgGroupBatchId=0))
	GROUP BY FeeSetupId,R.SourceId,R.ReceiptDate  
   
	
	INSERT INTO #tempPaidSubPartMonthWise
		SELECT 
		ISNULL(SA.AcademicId,0) AS AcademicId,
		 O.Id AS OrgGroupId,
		 O.Title As OrgGroupName,		
		ISNULL(CGM.Id,0) AS CollectionGroupId,
		ISNULL(CGM.Code,'') AS CollectionGroup,
		ISNULL(RBM.Title,'')  AS ReceiptTitle,
		ISNULL(RBM.Id,0) As ReceiptBookId,
		SUM(ISNULL(TPR1.PaidAmount,0)) AS PaidAmount,
		SUM(ISNULL(TPFS1.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(TPR1.PaidAmount,0.00))AS PendingAmount,
		TPR1.ReceiptDate
	FROM 
		sStudent.vStudentAcademic SA WITH (NOLOCK)
		 LEFT JOIN sStudent.tStudentCommunication SC WITH (NOLOCK) ON SC.StudentId = SA.StudentId
		INNER JOIN #tempPFSMonthWise1 TPFS1 ON TPFS1.AcademicId=SA.AcademicId
		LEFT JOIN sFee.tFeeAllocation FA WITH (NOLOCK)
			ON FA.FeeSetupId=TPFS1.Id AND FA.SourceId=SA.AcademicId
		LEFT JOIN #tempPRMonthWise1 TPR1 ON TPR1.FeeSetupId = TPFS1.Id AND SA.AcademicId = TPR1.SourceId
	    INNER JOIN sSetup.tBatchMaster BM WITH (NOLOCK) ON BM.Id = SA.BatchId
	    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM WITH (NOLOCK) ON OGBM.ID=BM.OrgGroupBatchId
	    INNER JOIN sSetup.tOrgGroupMaster O WITH (NOLOCK) ON O.Id =  OGBM.OrgGroupId		    
	    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM WITH (NOLOCK) ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
		INNER JOIN sFee.tReceiptBookMaster RBM WITH (NOLOCK) ON TPFS1.ReceiptBookId=RBM.Id
		LEFT JOIN sFee.tCollectionGroupMaster CGM WITH (NOLOCK) ON TPFS1.CollectionGroupId=CGM.Id AND RBM.Id = CGM.ReceiptBookId --AND (CGM.OrgGroupBatchId = 0 OR(0=0))
		INNER JOIN sFee.tFeeHeadMaster FHM WITH (NOLOCK) ON FHM.Id=TPFS1.FeeHeadId
	WHERE
	 (LEFT(SA.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))	
	 AND ((RBM.Id = @rReceiptBookId) OR (@rReceiptBookId=0))
	AND ((CGM.Id = @rCollectionGroupId) OR (@rCollectionGroupId=0))
	-- ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
	--AND(SA.IsActiveBatch =1) 
	AND ((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0)) 
	--And ISNULL(O.IsObsolete,0) = 0
	And O.IsObsolete <> 1
	-- IsInContext
		AND BM.IsInContext = 1
		GROUP by O.Id,O.Title,SA.AcademicId,CGM.Id,CGM.Code,RBM.Title,RBM.Id,TPR1.ReceiptDate
	
	select T.OrgGroupId,T.OrgGroupName,ISNULL(SUM(T.PaidAmount),0) AS PaidAmount,COUNT(T.AcademicId) As StudentCount,
		ISNULL(T.CollectionGroupId,0) AS CollectionGroupId,T.ReceiptBookId AS ReceiptBookId,DATENAME(month,T.MonthName)MonthName,DATEPART(M, T.MonthName) AS Month from #tempPaidSubPartMonthWise T
		group by T.OrgGroupId,T.CollectionGroupId,T.ReceiptBookId,T.OrgGroupName,DATENAME(month,T.MonthName),DATEPART(M, T.MonthName)
		HAVING ISNULL(SUM(T.PaidAmount),0) > 0
		--ORDER BY DATEPART(MONTH, T.MonthName)
	END
	
	DROP TABLE #tempPaidSubPartMonthWise
	DROP TABLE #tempPFSMonthWise
	DROP TABLE #tempPRMonthWise
	DROP TABLE #tempPFSMonthWise1
	DROP TABLE #tempPRMonthWise1
	
END

ELSE IF(@rType ='FeeStatusPendingSubPartAmount')
BEGIN 
CREATE TABLE #tempPendingSubPart(
	AcademicId bigint,
	OrgGroupId int,
	OrgGroupName nvarchar(100),
	ClassId bigint ,
	ClassName nvarchar(50),
	--DivisionId bigint,
	--DivisionName nvarchar(50),
	CollectionGroupId bigint,
	CollectionGroup nvarchar(200),
	RecepitTitle nvarchar(100),
	ReceiptBookId bigint,
	PaidAmount DECIMAL(12,0),
	PendingAmount DECIMAL(12,0),
	ClassOrderIndex int
	,DivisionOrder int
	)

IF(@rCollectionGroupId = 0)
	BEGIN

	INSERT INTO #tempPendingSubPart
    SELECT 
		ISNULL(SA.AcademicId,0) AS AcademicId,
		 SA.OrgId AS OrgGroupId,
		 SA.OrganizationName AS OrgGroupName,
		 SA.ClassId  AS ClassId,
		 SA.ClassName AS ClassName,
		ISNULL(CGM.Id,0) AS CollectionGroupId,
		ISNULL(CGM.Code,'') AS CollectionGroup,
		ISNULL(RBM.Title,'')  AS ReceiptTitle,
		ISNULL(RBM.Id,0) As ReceiptBookId,
		SUM(ISNULL(FAS.PaidAmount,0)) AS PaidAmount,
		SUM(ISNULL(FAS.ToPayAmount,0.00))AS PendingAmount,
		SA.ClassOrderIndex
		,SA.DivisionOrder --add for mantis : 0042058
	FROM 
		sStudent.vStudentAcademic SA WITH (NOLOCK)
		INNER JOIN sFee.tFeeAllocationStudent FAS WITH (NOLOCK) ON FAS.AcademicId = SA.AcademicId
		INNER JOIN sFee.tFeeSetup FS WITH (NOLOCK) ON FAS.FeeSetupId = FS.Id
	    INNER JOIN sSetup.tBatchMaster BM WITH (NOLOCK) ON BM.Id = SA.BatchId
	    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM WITH (NOLOCK) ON OGBM.ID=BM.OrgGroupBatchId
	    INNER JOIN sSetup.tOrgGroupMaster O WITH (NOLOCK) ON O.Id =  OGBM.OrgGroupId		    
	    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM WITH (NOLOCK) ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
		INNER JOIN sFee.tReceiptBookMaster RBM WITH (NOLOCK) ON FS.ReceiptBookId=RBM.Id
		LEFT JOIN sFee.tCollectionGroupMaster CGM WITH (NOLOCK) ON FS.CollectionGroupId=CGM.Id AND RBM.Id = CGM.ReceiptBookId 
		INNER JOIN sFee.tFeeMaster FM WITH (NOLOCK) ON FM.Id = FS.FeeId
	    INNER JOIN sFee.tFeeHeadMaster FHM WITH (NOLOCK) ON FHM.Id=FM.FeeHeadId	
	WHERE
		(FS.IsOptional=0)
		AND (LEFT(BM.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0)) 
		--And ISNULL(O.IsObsolete,0) = 0
		And O.IsObsolete <> 1
		AND COGBM.Id=@rCommonOrgGroupBatchId 
		AND ((FS.ReceiptBookId = @rReceiptBookId) OR (@rReceiptBookId=0))
		AND ((FS.CollectionGroupId=@rCollectionGroupId) OR (@rCollectionGroupId = 0))
		-- IsInContext
		AND BM.IsInContext = 1
	GROUP by SA.OrgId,SA.OrganizationName,SA.ClassId,SA.ClassName,SA.AcademicId,CGM.Id,CGM.Code,RBM.Title,RBM.Id,SA.ClassOrderIndex,SA.DivisionOrder
	
	select T.OrgGroupId,T.OrgGroupName,T.ClassId,T.ClassName AS ClassDivision,ISNULL(SUM(T.PendingAmount),0) AS PendingAmount,COUNT(T.AcademicId)AS StudentCount,
		ISNULL(T.CollectionGroupId,0) AS CollectionGroupId,T.ReceiptBookId AS ReceiptBookId,T.ClassOrderIndex 
		,T.DivisionOrder ----add for mantis : 0042058
		from #tempPendingSubPart T
		WHERE T.PendingAmount >0
     group by T.OrgGroupId,T.OrgGroupName,T.ClassName,T.ClassId,T.CollectionGroupId,T.ReceiptBookId,T.ClassOrderIndex,T.DivisionOrder
		ORDER BY T.ClassOrderIndex,T.DivisionOrder
		
DROP TABLE #tempPendingSubPart
		
	END 
	ELSE 
	BEGIN
	
	INSERT INTO #tempPendingSubPart
	SELECT 
		ISNULL(SA.AcademicId,0) AS AcademicId,
		 SA.OrgId AS OrgGroupId,
		 SA.OrganizationName AS OrgGroupName,
		 SA.ClassId AS ClassId,
		 SA.ClassName AS ClassName,
		ISNULL(CGM.Id,0) AS CollectionGroupId,
		ISNULL(CGM.Code,'') AS CollectionGroup,
		ISNULL(RBM.Title,'')  AS ReceiptTitle,
		ISNULL(RBM.Id,0) As ReceiptBookId,
		SUM(ISNULL(FAS.PaidAmount,0)) AS PaidAmount,
		SUM(ISNULL(FAS.ToPayAmount,0.00))AS PendingAmount,
		SA.ClassOrderIndex  
		,SA.DivisionOrder --add for mantis : 0042058
	FROM 
		sStudent.vStudentAcademic SA WITH (NOLOCK)
		INNER JOIN sFee.tFeeAllocationStudent FAS WITH (NOLOCK) ON FAS.AcademicId = SA.AcademicId
		INNER JOIN sFee.tFeeSetup FS WITH (NOLOCK) ON FAS.FeeSetupId = FS.Id
	    INNER JOIN sSetup.tBatchMaster BM WITH (NOLOCK) ON BM.Id = SA.BatchId
	    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM WITH (NOLOCK) ON OGBM.ID=BM.OrgGroupBatchId
	    INNER JOIN sSetup.tOrgGroupMaster O WITH (NOLOCK) ON O.Id =  OGBM.OrgGroupId		    
	    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM WITH (NOLOCK) ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
		INNER JOIN sFee.tReceiptBookMaster RBM WITH (NOLOCK) ON FS.ReceiptBookId=RBM.Id
		LEFT JOIN sFee.tCollectionGroupMaster CGM WITH (NOLOCK) ON FS.CollectionGroupId=CGM.Id AND RBM.Id = CGM.ReceiptBookId 
		INNER JOIN sFee.tFeeMaster FM WITH (NOLOCK) ON FM.Id = FS.FeeId
	    INNER JOIN sFee.tFeeHeadMaster FHM WITH (NOLOCK) ON FHM.Id=FM.FeeHeadId	
	WHERE
		(FS.IsOptional=0)
		AND (LEFT(BM.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0)) 
		--And ISNULL(O.IsObsolete,0) = 0
		And O.IsObsolete <> 1
		AND COGBM.Id=@rCommonOrgGroupBatchId 
		AND ((FS.ReceiptBookId = @rReceiptBookId) OR (@rReceiptBookId=0))
		AND ((FS.CollectionGroupId=@rCollectionGroupId) OR (@rCollectionGroupId = 0))
		-- IsInContext
		AND BM.IsInContext = 1
	 GROUP by SA.OrgId,SA.OrganizationName,SA.ClassName,SA.AcademicId,SA.ClassId,CGM.Id,CGM.Code,RBM.Title,RBM.Id,SA.ClassOrderIndex
	 ,SA.DivisionOrder --add division for mantis :0042058
	
	SELECT T.OrgGroupId,T.OrgGroupName,T.ClassId,T.ClassName AS ClassDivision,ISNULL(SUM(T.PendingAmount),0) AS PendingAmount, COUNT(T.AcademicId) AS StudentCount,
		ISNULL(T.CollectionGroupId,0) AS CollectionGroupId,T.ReceiptBookId AS ReceiptBookId,T.ClassOrderIndex 
		,T.DivisionOrder
		from #tempPendingSubPart T
	WHERE T.PendingAmount >0
	GROUP BY T.OrgGroupId,T.ClassName,T.OrgGroupName,T.ClassId,T.CollectionGroupId,T.ReceiptBookId,T.ClassOrderIndex,T.DivisionOrder
	--HAVING ISNULL(SUM(T.PendingAmount),0) > 0
	ORDER BY T.ClassOrderIndex,T.DivisionOrder --DivisionOrder add for mantis : 0042058	
		
   
	   DROP TABLE #tempPendingSubPart
		
	END
	END

ELSE IF(@rType ='FeeStatusPendingSubPartDetails')
BEGIN 
CREATE TABLE #tempPendingSubPartDetails(
SourceId bigint,
OrgGroupId int,
Code nvarchar(20),
Name nvarchar(200),
ParentContactNo nvarchar(50),
ClassName nvarchar(50),
DivisionId bigint,
DivisionName nvarchar(50),
CollectionGroupId bigint,
CollectionGroup nvarchar(200),
RecepitTitle nvarchar(100),
ReceiptBookId bigint,
PaidAmount DECIMAL(12,0),
PendingAmount DECIMAL(12,0),
RollNo int
,DivisionOrder INT --mantis : 0042058
)

IF(@rCollectionGroupId = 0)
	BEGIN
	insert into #tempPendingSubPartDetails
SELECT 
		ISNULL(SA.AcademicId,0) AS SourceId,
		 O.Id AS OrgGroupId,
		 ISNULL(SA.Code,'') As Code,
		 ISNULL(SA.Name,'') AS Name,
		 ISNULL(SC.ParentContactNo,'') AS ParentContactNo,
		 SA.ClassName AS ClassName,
		 SA.DivisionId AS DivisionId,
		 SA.DivisionName AS DivisionName,
		ISNULL(CGM.Id,0) AS CollectionGroupId,
		ISNULL(CGM.Code,'') AS CollectionGroup,
		ISNULL(RBM.Title,'')  AS ReceiptTitle,
		ISNULL(RBM.Id,0) As ReceiptBookId,
		SUM(ISNULL(FAS.PaidAmount,0)) AS PaidAmount,
		SUM(ISNULL(FAS.ToPayAmount,0.00))AS PendingAmount,
		SA.RollNo
		,SA.DivisionOrder --mantis : 0042058
	FROM 
		sStudent.vStudentAcademic SA WITH (NOLOCK)
		LEFT JOIN sStudent.tStudentCommunication SC WITH (NOLOCK) ON SC.StudentId = SA.StudentId
		INNER JOIN sFee.tFeeAllocationStudent FAS WITH (NOLOCK) ON FAS.AcademicId = SA.AcademicId
		INNER JOIN sFee.tFeeSetup FS WITH (NOLOCK) ON FAS.FeeSetupId = FS.Id
	    INNER JOIN sSetup.tBatchMaster BM WITH (NOLOCK) ON BM.Id = SA.BatchId
	    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM WITH (NOLOCK) ON OGBM.ID=BM.OrgGroupBatchId
	    INNER JOIN sSetup.tOrgGroupMaster O WITH (NOLOCK) ON O.Id =  OGBM.OrgGroupId		    
	    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM WITH (NOLOCK) ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
		INNER JOIN sFee.tReceiptBookMaster RBM WITH (NOLOCK) ON FS.ReceiptBookId=RBM.Id
		LEFT JOIN sFee.tCollectionGroupMaster CGM WITH (NOLOCK) ON FS.CollectionGroupId=CGM.Id AND RBM.Id = CGM.ReceiptBookId 
		INNER JOIN sFee.tFeeMaster FM WITH (NOLOCK) ON FM.Id = FS.FeeId
	    INNER JOIN sFee.tFeeHeadMaster FHM WITH (NOLOCK) ON FHM.Id=FM.FeeHeadId	
	WHERE
	 (LEFT(SA.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))	
	 AND ((RBM.Id = @rReceiptBookId) OR (@rReceiptBookId=0))
	 AND ((CGM.Id = @rCollectionGroupId) OR (@rCollectionGroupId=0))
	 AND ((SA.ClassId = @rClassId) OR (@rClassId = 0))
	 AND ((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0)) 
	 --And ISNULL(O.IsObsolete,0) = 0
	 And O.IsObsolete <> 1
	 -- IsInContext
		AND BM.IsInContext = 1
		GROUP by O.Id,SA.ClassName,SA.DivisionName,SA.AcademicId,SA.DivisionId,CGM.Id,CGM.Code,RBM.Title,RBM.Id,SA.Name,SC.ParentContactNo,SA.Code,SA.RollNo
		,SA.DivisionOrder --mantis :0042058 	
		select T.SourceId,T.Name AS Name,T.DivisionId,T.ClassName+'-'+ T.DivisionName AS ClassDivision,ISNULL(SUM(T.PendingAmount),0) AS PendingAmount,T.ParentContactNo AS ParentContactNo,T.Code AS Code,
			ISNULL(T.CollectionGroupId,0) AS CollectionGroupId,T.ReceiptBookId AS ReceiptBookId,T.RollNo 
			,T.DivisionOrder --mantis : 0042058
			from #tempPendingSubPartDetails T
		WHERE T.PendingAmount >0
		group by T.DivisionId,T.CollectionGroupId,T.ReceiptBookId,T.ParentContactNo,T.Name,T.Code,T.RollNo,T.ClassName,T.DivisionName,T.SourceId
		HAVING SUM(ISNULL(PaidAmount,0)+ISNULL(PendingAmount,0)) > 0
		ORDER BY T.DivisionOrder,T.RollNo
	END 
	ELSE 
	BEGIN
	
	insert into #tempPendingSubPartDetails
		SELECT 
		ISNULL(SA.AcademicId,0) AS SourceId,
		 O.Id AS OrgGroupId,
		 ISNULL(SA.Code,'') As Code,
		 ISNULL(SA.Name,'') AS Name,
		 ISNULL(SC.ParentContactNo,'') AS ParentContactNo,
		 SA.ClassName AS ClassName,
		 SA.DivisionId AS DivisionId,
		 SA.DivisionName AS DivisionName,
		ISNULL(CGM.Id,0) AS CollectionGroupId,
		ISNULL(CGM.Code,'') AS CollectionGroup,
		ISNULL(RBM.Title,'')  AS ReceiptTitle,
		ISNULL(RBM.Id,0) As ReceiptBookId,
		SUM(ISNULL(FAS.PaidAmount,0)) AS PaidAmount,
		SUM(ISNULL(FAS.ToPayAmount,0.00))AS PendingAmount,
		SA.RollNo
		--SA.ClassOrderIndex
		,SA.DivisionOrder
	FROM 
		sStudent.vStudentAcademic SA WITH (NOLOCK)
		LEFT JOIN sStudent.tStudentCommunication SC WITH (NOLOCK) ON SC.StudentId = SA.StudentId
		INNER JOIN sFee.tFeeAllocationStudent FAS WITH (NOLOCK) ON FAS.AcademicId = SA.AcademicId
		INNER JOIN sFee.tFeeSetup FS WITH (NOLOCK) ON FAS.FeeSetupId = FS.Id
	    INNER JOIN sSetup.tBatchMaster BM WITH (NOLOCK) ON BM.Id = SA.BatchId
	    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM WITH (NOLOCK) ON OGBM.ID=BM.OrgGroupBatchId
	    INNER JOIN sSetup.tOrgGroupMaster O WITH (NOLOCK) ON O.Id =  OGBM.OrgGroupId		    
	    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM WITH (NOLOCK) ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
		INNER JOIN sFee.tReceiptBookMaster RBM WITH (NOLOCK) ON FS.ReceiptBookId=RBM.Id
		LEFT JOIN sFee.tCollectionGroupMaster CGM WITH (NOLOCK) ON FS.CollectionGroupId=CGM.Id AND RBM.Id = CGM.ReceiptBookId 
		INNER JOIN sFee.tFeeMaster FM WITH (NOLOCK) ON FM.Id = FS.FeeId
	    INNER JOIN sFee.tFeeHeadMaster FHM WITH (NOLOCK) ON FHM.Id=FM.FeeHeadId	
	WHERE
	 (LEFT(SA.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))	
	 AND ((RBM.Id = @rReceiptBookId) OR (@rReceiptBookId=0))
	 AND ((CGM.Id = @rCollectionGroupId) OR (@rCollectionGroupId=0))
	 AND ((SA.ClassId = @rClassId) OR (@rClassId = 0))
	 --And ISNULL(O.IsObsolete,0) = 0
	 And O.IsObsolete <> 1
	 AND ((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0)) 
	 -- IsInContext
		AND BM.IsInContext = 1
	GROUP by O.Id,SA.ClassName,SA.DivisionName,SA.AcademicId,SA.DivisionId,CGM.Id,CGM.Code,RBM.Title,RBM.Id,SA.Name,SC.ParentContactNo,SA.Code,SA.RollNo--,SA.ClassOrderIndex
	,SA.DivisionOrder	

		select T.SourceId,T.Name AS Name,T.DivisionId,T.ClassName+'-'+ T.DivisionName AS ClassDivision,ISNULL(SUM(T.PendingAmount),0) AS PendingAmount,T.ParentContactNo AS ParentContactNo,T.Code As Code,
		ISNULL(T.CollectionGroupId,0) AS CollectionGroupId,T.ReceiptBookId AS ReceiptBookId,T.RollNo 
		,T.DivisionOrder --mantis : 0042058
		from #tempPendingSubPartDetails T
		WHERE T.PendingAmount >0
		group by T.DivisionId,T.CollectionGroupId,T.ReceiptBookId,T.ParentContactNo,T.Name,T.Code,T.RollNo,T.ClassName,T.DivisionName,T.SourceId--,T.ClassOrderIndex
		,T.DivisionOrder 
		HAVING SUM(ISNULL(PaidAmount,0)+ISNULL(PendingAmount,0)) > 0
		ORDER BY T.DivisionOrder
				,T.RollNo --mantis : 0042058
		 
	END
	
	DROP TABLE #tempPendingSubPartDetails
	 
END	
	
ELSE IF(@rType ='FeeStatusTotalSubPartAmount')
BEGIN 
CREATE TABLE #tempTotalSubPart (
AcademicId bigint,
OrgGroupId int,
OrgGroupName nvarchar(100),
ClassId bigint,
ClassName nvarchar(50),
--DivisionId bigint,
--DivisionName nvarchar(50),
CollectionGroupId bigint,
CollectionGroup nvarchar(200),
RecepitTitle nvarchar(100),
ReceiptBookId bigint,
PaidAmount DECIMAL(12,0),
PendingAmount DECIMAL(12,0),
ClassOrderIndex int
,DivisionOrder int
)

IF(@rCollectionGroupId = 0)
	BEGIN

	INSERT INTO #tempTotalSubPart
	SELECT 
		ISNULL(SA.AcademicId,0) AS AcademicId,
		SA.OrgId AS OrgGroupId,
		SA.OrganizationName AS OrgGroupName,
		SA.ClassId AS ClassId,
		SA.ClassName AS ClassName,
		ISNULL(CGM.Id,0) AS CollectionGroupId,
		ISNULL(CGM.Code,'') AS CollectionGroup,
		ISNULL(RBM.Title,'')  AS ReceiptTitle,
		ISNULL(RBM.Id,0) As ReceiptBookId,
		SUM(ISNULL(FAS.PaidAmount,0)) AS PaidAmount,
		SUM(ISNULL(FAS.ToPayAmount,0.00))AS PendingAmount,
		SA.ClassOrderIndex
		,SA.DivisionOrder
	FROM 
		sStudent.vStudentAcademic SA WITH (NOLOCK)
		INNER JOIN sFee.tFeeAllocationStudent FAS WITH (NOLOCK) ON FAS.AcademicId = SA.AcademicId
		INNER JOIN sFee.tFeeSetup FS WITH (NOLOCK) ON FAS.FeeSetupId = FS.Id
	    INNER JOIN sSetup.tBatchMaster BM WITH (NOLOCK) ON BM.Id = SA.BatchId
	    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM WITH (NOLOCK) ON OGBM.ID=BM.OrgGroupBatchId
	    INNER JOIN sSetup.tOrgGroupMaster O WITH (NOLOCK) ON O.Id =  OGBM.OrgGroupId		    
	    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM WITH (NOLOCK) ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
		INNER JOIN sFee.tReceiptBookMaster RBM WITH (NOLOCK) ON FS.ReceiptBookId=RBM.Id
		LEFT JOIN sFee.tCollectionGroupMaster CGM WITH (NOLOCK) ON FS.CollectionGroupId=CGM.Id AND RBM.Id = CGM.ReceiptBookId 
		INNER JOIN sFee.tFeeMaster FM WITH (NOLOCK) ON FM.Id = FS.FeeId
	    INNER JOIN sFee.tFeeHeadMaster FHM WITH (NOLOCK) ON FHM.Id=FM.FeeHeadId	
	WHERE 
		   ((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0))
			--And ISNULL(O.IsObsolete,0) = 0
			And O.IsObsolete <> 1
			AND ((FS.ReceiptBookId = @rReceiptBookId) OR (@rReceiptBookId=0))
			AND ((FS.CollectionGroupId = @rCollectionGroupId) OR (@rCollectionGroupId=0))
			-- IsInContext
		AND BM.IsInContext = 1
	GROUP by SA.OrgId,SA.OrganizationName, SA.ClassId,SA.ClassName--,SA.DivisionName
		,SA.AcademicId,SA.DivisionId,CGM.Id,CGM.Code,RBM.Title,RBM.Id,SA.ClassOrderIndex,SA.DivisionOrder
	

	select T.OrgGroupId,T.OrgGroupName,T.ClassId,T.ClassName AS ClassDivision,SUM(ISNULL(PaidAmount,0)+ISNULL(PendingAmount,0)) AS TotalAmount,COUNT(T.AcademicId) AS StudentCount,
		ISNULL(T.CollectionGroupId,0) AS CollectionGroupId,T.ReceiptBookId AS ReceiptBookId 
		,T.ClassOrderIndex
		,T.DivisionOrder
		from #tempTotalSubPart T
	group by T.OrgGroupId,T.OrgGroupName,T.ClassId,T.ClassName,T.CollectionGroupId,T.ReceiptBookId,T.ClassOrderIndex,T.DivisionOrder
	HAVING SUM(ISNULL(PaidAmount,0)+ISNULL(PendingAmount,0)) > 0
	ORDER BY T.ClassOrderIndex
				,T.DivisionOrder --add for mantis : 0042058
		
	END 
	ELSE 
	BEGIN
	
	INSERT INTO #tempTotalSubPart
		SELECT 
		ISNULL(SA.AcademicId,0) AS AcademicId,
		 SA.OrgId AS OrgGroupId,
		  SA.OrganizationName AS OrgGroupName,
		 SA.ClassId AS ClassId,
		 SA.ClassName AS ClassName,
		ISNULL(CGM.Id,0) AS CollectionGroupId,
		ISNULL(CGM.Code,'') AS CollectionGroup,
		ISNULL(RBM.Title,'')  AS ReceiptTitle,
		ISNULL(RBM.Id,0) As ReceiptBookId,
		SUM(ISNULL(FAS.PaidAmount,0)) AS PaidAmount,
		SUM(ISNULL(FAS.ToPayAmount,0.00))AS PendingAmount,
		SA.ClassOrderIndex--,SA.DivisionOrder
		,SA.DivisionOrder
	FROM 
		sStudent.vStudentAcademic SA WITH (NOLOCK)
		INNER JOIN sFee.tFeeAllocationStudent FAS WITH (NOLOCK) ON FAS.AcademicId = SA.AcademicId
		INNER JOIN sFee.tFeeSetup FS WITH (NOLOCK) ON FAS.FeeSetupId = FS.Id
	    INNER JOIN sSetup.tBatchMaster BM WITH (NOLOCK) ON BM.Id = SA.BatchId
	    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM WITH (NOLOCK) ON OGBM.ID=BM.OrgGroupBatchId
	    INNER JOIN sSetup.tOrgGroupMaster O WITH (NOLOCK) ON O.Id =  OGBM.OrgGroupId		    
	    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM WITH (NOLOCK) ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
		INNER JOIN sFee.tReceiptBookMaster RBM WITH (NOLOCK) ON FS.ReceiptBookId=RBM.Id
		LEFT JOIN sFee.tCollectionGroupMaster CGM WITH (NOLOCK) ON FS.CollectionGroupId=CGM.Id AND RBM.Id = CGM.ReceiptBookId 
		INNER JOIN sFee.tFeeMaster FM WITH (NOLOCK) ON FM.Id = FS.FeeId
	    INNER JOIN sFee.tFeeHeadMaster FHM WITH (NOLOCK) ON FHM.Id=FM.FeeHeadId	
	WHERE 
		   ((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0))
			--And ISNULL(O.IsObsolete,0) = 0
			And O.IsObsolete <> 1
			AND ((FS.ReceiptBookId = @rReceiptBookId) OR (@rReceiptBookId=0))
			AND ((FS.CollectionGroupId = @rCollectionGroupId) OR (@rCollectionGroupId=0))
			-- IsInContext
		AND BM.IsInContext = 1

	GROUP by SA.OrgId,SA.OrganizationName,SA.ClassId,SA.ClassName--,SA.DivisionName
		,SA.AcademicId,SA.DivisionId,CGM.Id,CGM.Code,RBM.Title,RBM.Id,SA.ClassOrderIndex,SA.DivisionOrder

		 
	SELECT T.OrgGroupId,T.OrgGroupName,T.ClassId,T.ClassName AS ClassDivision,SUM(ISNULL(PaidAmount,0)+ISNULL(PendingAmount,0)) AS TotalAmount, COUNT(T.AcademicId) AS StudentCount,
		ISNULL(T.CollectionGroupId,0) AS CollectionGroupId,T.ReceiptBookId AS ReceiptBookId 
		,T.ClassOrderIndex
		,T.DivisionOrder
		from #tempTotalSubPart T
	GROUP BY T.OrgGroupId,T.OrgGroupName,T.ClassId,T.ClassName,T.CollectionGroupId,T.ReceiptBookId,T.OrgGroupName,T.ClassOrderIndex,T.DivisionOrder
	HAVING SUM(ISNULL(PaidAmount,0)+ISNULL(PendingAmount,0)) > 0
		ORDER BY T.ClassOrderIndex,T.DivisionOrder
		
	END
	
	DROP TABLE #tempTotalSubPart
	
  END	
ELSE IF(@rType ='FeeStatusTotalSubPartDetails')
BEGIN 
CREATE TABLE #tempTotalSubPartDetails(
SourceId bigint,
OrgGroupId int,
Code nvarchar(20),
Name nvarchar(200),
ParentContactNo nvarchar(50),
ClassName nvarchar(50),
DivisionId bigint,
DivisionName nvarchar(50),
CollectionGroupId bigint,
CollectionGroup nvarchar(200),
RecepitTitle nvarchar(100),
ReceiptBookId bigint,
PaidAmount DECIMAL(12,0),
PendingAmount DECIMAL(12,0),
RollNo int
,ClassOrderIndex INT --add for mantis : 0042058
,DivisionOrder INT --add for mantis : 0042058
)

 
IF(@rCollectionGroupId = 0)
	BEGIN
	insert into #tempTotalSubPartDetails
SELECT 
		ISNULL(SA.AcademicId,0) AS SourceId,
		 O.Id AS OrgGroupId,
		 ISNULL(SA.Code,'') As Code,
		 ISNULL(SA.Name,'') AS Name,
		 ISNULL(SC.ParentContactNo,'') AS ParentContactNo,
		 SA.ClassName AS ClassName,
		 SA.DivisionId AS DivisionId,
		 SA.DivisionName AS DivisionName,
		ISNULL(CGM.Id,0) AS CollectionGroupId,
		ISNULL(CGM.Code,'') AS CollectionGroup,
		ISNULL(RBM.Title,'')  AS ReceiptTitle,
		ISNULL(RBM.Id,0) As ReceiptBookId,
		SUM(ISNULL(FAS.PaidAmount,0)) AS PaidAmount,
		SUM(ISNULL(FAS.ToPayAmount,0.00))AS PendingAmount,
		SA.RollNo
		,SA.ClassOrderIndex --add for mantis : 0042058
		,SA.DivisionOrder --add for mantis : 0042058
	FROM 
		sStudent.vStudentAcademic SA WITH (NOLOCK)
		LEFT JOIN sStudent.tStudentCommunication SC WITH (NOLOCK) ON SC.StudentId = SA.StudentId
		INNER JOIN sFee.tFeeAllocationStudent FAS WITH (NOLOCK) ON FAS.AcademicId = SA.AcademicId
		INNER JOIN sFee.tFeeSetup FS WITH (NOLOCK) ON FAS.FeeSetupId = FS.Id
	    INNER JOIN sSetup.tBatchMaster BM WITH (NOLOCK) ON BM.Id = SA.BatchId
	    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM WITH (NOLOCK) ON OGBM.ID=BM.OrgGroupBatchId
	    INNER JOIN sSetup.tOrgGroupMaster O WITH (NOLOCK) ON O.Id =  OGBM.OrgGroupId		    
	    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM WITH (NOLOCK) ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
		INNER JOIN sFee.tReceiptBookMaster RBM WITH (NOLOCK) ON FS.ReceiptBookId=RBM.Id
		LEFT JOIN sFee.tCollectionGroupMaster CGM WITH (NOLOCK) ON FS.CollectionGroupId=CGM.Id AND RBM.Id = CGM.ReceiptBookId 
		INNER JOIN sFee.tFeeMaster FM WITH (NOLOCK) ON FM.Id = FS.FeeId
	    INNER JOIN sFee.tFeeHeadMaster FHM WITH (NOLOCK) ON FHM.Id=FM.FeeHeadId	
	WHERE
	 (LEFT(SA.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))	
	 AND ((RBM.Id = @rReceiptBookId) OR (@rReceiptBookId=0))
	 AND  ISNULL(CGM.Id,0)=0
	 AND ((SA.ClassId = @rClassId) OR (@rClassId = 0))
	 --And ISNULL(O.IsObsolete,0) = 0
	 And O.IsObsolete <> 1
	 AND ((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0)) 
	 -- IsInContext
		AND BM.IsInContext = 1
		GROUP by O.Id,SA.ClassName,SA.DivisionName,SA.AcademicId,SA.DivisionId,CGM.Id,CGM.Code,RBM.Title,RBM.Id,SA.Name,SC.ParentContactNo,SA.Code,SA.RollNo,SA.ClassOrderIndex
				,SA.DivisionOrder
	
	select T.SourceId,T.Name AS Name,T.DivisionId,T.ClassName+'-'+ T.DivisionName AS ClassDivision,SUM(ISNULL(PaidAmount,0)+ISNULL(PendingAmount,0)) AS TotalAmount,T.ParentContactNo AS ParentContactNo,T.Code AS Code,
		ISNULL(T.CollectionGroupId,0) AS CollectionGroupId,T.ReceiptBookId AS ReceiptBookId,T.RollNo 
		,T.ClassOrderIndex
		,T.DivisionOrder
		from #tempTotalSubPartDetails T
	group by T.DivisionId,T.CollectionGroupId,T.ReceiptBookId,T.ParentContactNo,T.Name,T.Code,T.RollNo,T.ClassName,T.DivisionName,T.SourceId,T.ClassOrderIndex
				,T.DivisionOrder
	HAVING SUM(ISNULL(PaidAmount,0)+ISNULL(PendingAmount,0)) > 0
	ORDER BY T.ClassOrderIndex,T.DivisionOrder,T.RollNo
	END 
	ELSE 
	BEGIN
	
	insert into #tempTotalSubPartDetails
		SELECT 
		ISNULL(SA.AcademicId,0) AS SourceId,
		 O.Id AS OrgGroupId,
		 ISNULL(SA.Code,'') As Code,
		 ISNULL(SA.Name,'') AS Name,
		 ISNULL(SC.ParentContactNo,'') AS ParentContactNo,
		 SA.ClassName AS ClassName,
		 SA.DivisionId AS DivisionId,
		 SA.DivisionName AS DivisionName,
		ISNULL(CGM.Id,0) AS CollectionGroupId,
		ISNULL(CGM.Code,'') AS CollectionGroup,
		ISNULL(RBM.Title,'')  AS ReceiptTitle,
		ISNULL(RBM.Id,0) As ReceiptBookId,
		SUM(ISNULL(FAS.PaidAmount,0)) AS PaidAmount,
		SUM(ISNULL(FAS.ToPayAmount,0.00))AS PendingAmount,
		SA.RollNo
		,SA.ClassOrderIndex --add for mantis : 0042058
		,SA.DivisionOrder --add for mantis : 0042058
	FROM 
		sStudent.vStudentAcademic SA WITH (NOLOCK)
		LEFT JOIN sStudent.tStudentCommunication SC WITH (NOLOCK) ON SC.StudentId = SA.StudentId
		INNER JOIN sFee.tFeeAllocationStudent FAS WITH (NOLOCK) ON FAS.AcademicId = SA.AcademicId
		INNER JOIN sFee.tFeeSetup FS WITH (NOLOCK) ON FAS.FeeSetupId = FS.Id
	    INNER JOIN sSetup.tBatchMaster BM WITH (NOLOCK) ON BM.Id = SA.BatchId
	   INNER JOIN sSetup.tOrgGroupBatchMaster OGBM WITH (NOLOCK) ON OGBM.ID=BM.OrgGroupBatchId
	    INNER JOIN sSetup.tOrgGroupMaster O WITH (NOLOCK) ON O.Id =  OGBM.OrgGroupId		    
	    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM WITH (NOLOCK) ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
		INNER JOIN sFee.tReceiptBookMaster RBM WITH (NOLOCK) ON FS.ReceiptBookId=RBM.Id
		LEFT JOIN sFee.tCollectionGroupMaster CGM WITH (NOLOCK) ON FS.CollectionGroupId=CGM.Id AND RBM.Id = CGM.ReceiptBookId 
		INNER JOIN sFee.tFeeMaster FM WITH (NOLOCK) ON FM.Id = FS.FeeId
	    INNER JOIN sFee.tFeeHeadMaster FHM WITH (NOLOCK) ON FHM.Id=FM.FeeHeadId	
	WHERE
	 (LEFT(SA.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))	
	 AND ((RBM.Id = @rReceiptBookId) OR (@rReceiptBookId=0))
	 AND ((CGM.Id = @rCollectionGroupId) OR (@rCollectionGroupId=0))
	 AND ((SA.ClassId = @rClassId) OR (@rClassId = 0))
	 AND ((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0)) 
	 --And ISNULL(O.IsObsolete,0) = 0
	 And O.IsObsolete <> 1
	 -- IsInContext
		AND BM.IsInContext = 1
	GROUP by O.Id,SA.ClassName,SA.DivisionName,SA.AcademicId,SA.DivisionId,CGM.Id,CGM.Code,RBM.Title,RBM.Id,SA.Name,SC.ParentContactNo,SA.Code,SA.RollNo,SA.ClassOrderIndex,SA.DivisionOrder
	

	select T.SourceId,T.Name AS Name,T.DivisionId,T.ClassName+'-'+ T.DivisionName AS ClassDivision,SUM(ISNULL(PaidAmount,0)+ISNULL(PendingAmount,0)) AS TotalAmount,T.ParentContactNo AS ParentContactNo,T.Code As Code,
		ISNULL(T.CollectionGroupId,0) AS CollectionGroupId,T.ReceiptBookId AS ReceiptBookId,T.RollNo 
		,T.ClassOrderIndex,T.DivisionOrder
		from #tempTotalSubPartDetails T
	group by T.DivisionId,T.CollectionGroupId,T.ReceiptBookId,T.ParentContactNo,T.Name,T.Code,T.RollNo,T.ClassName,T.DivisionName,T.SourceId,T.ClassOrderIndex,T.DivisionOrder 
	HAVING SUM(ISNULL(PaidAmount,0)+ISNULL(PendingAmount,0)) > 0
	ORDER BY T.ClassOrderIndex,T.DivisionOrder ,T.RollNo
		
	 
	END
	
	DROP TABLE #tempTotalSubPartDetails
	
END
  
ELSE IF(@rType ='FeeStatusPaidSubPartDetails')
BEGIN 
CREATE TABLE #tempPaidSubPartDetails(
SourceId bigint,
OrgGroupId int,
Code nvarchar(20),
Name nvarchar(200),
ParentContactNo nvarchar(50),
ClassName nvarchar(50),
DivisionId bigint,
DivisionName nvarchar(50),
CollectionGroupId bigint,
CollectionGroup nvarchar(200),
RecepitTitle nvarchar(100),
ReceiptBookId bigint,
PaidAmount DECIMAL(12,0),
PendingAmount DECIMAL(12,0),
RollNo int
,ClassOrderIndex INT --add for mantis : 0042058
,DivisionOrder INT --add for mantis : 0042058
)

 
IF(@rCollectionGroupId = 0)
	BEGIN
	insert into #tempPaidSubPartDetails
	SELECT 
		ISNULL(SA.AcademicId,0) AS SourceId,
		 O.Id AS OrgGroupId,
		 ISNULL(SA.Code,'') As Code,
		 ISNULL(SA.Name,'') AS Name,
		 ISNULL(SC.ParentContactNo,'') AS ParentContactNo,
		 SA.ClassName AS ClassName,
		 SA.DivisionId AS DivisionId,
		 SA.DivisionName AS DivisionName,
		ISNULL(CGM.Id,0) AS CollectionGroupId,
		ISNULL(CGM.Code,'') AS CollectionGroup,
		ISNULL(RBM.Title,'')  AS ReceiptTitle,
		ISNULL(RBM.Id,0) As ReceiptBookId,
		SUM(ISNULL(FAS.PaidAmount,0)) AS PaidAmount,
		SUM(ISNULL(FAS.ToPayAmount,0.00))AS PendingAmount,
		SA.RollNo
		,SA.ClassOrderIndex INT --add for mantis : 0042058
		,SA.DivisionOrder INT --add for mantis : 0042058
		
	FROM 
		sStudent.vStudentAcademic SA WITH (NOLOCK)
		LEFT JOIN sStudent.tStudentCommunication SC WITH (NOLOCK) ON SC.StudentId = SA.StudentId
		INNER JOIN sFee.tFeeAllocationStudent FAS WITH (NOLOCK) ON FAS.AcademicId = SA.AcademicId
		INNER JOIN sFee.tFeeSetup FS WITH (NOLOCK) ON FAS.FeeSetupId = FS.Id
	    INNER JOIN sSetup.tBatchMaster BM WITH (NOLOCK) ON BM.Id = SA.BatchId
	    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM WITH (NOLOCK) ON OGBM.ID=BM.OrgGroupBatchId
	    INNER JOIN sSetup.tOrgGroupMaster O WITH (NOLOCK) ON O.Id =  OGBM.OrgGroupId		    
	    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM WITH (NOLOCK) ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
		INNER JOIN sFee.tReceiptBookMaster RBM WITH (NOLOCK) ON FS.ReceiptBookId=RBM.Id
		LEFT JOIN sFee.tCollectionGroupMaster CGM WITH (NOLOCK) ON FS.CollectionGroupId=CGM.Id AND RBM.Id = CGM.ReceiptBookId 
		INNER JOIN sFee.tFeeMaster FM WITH (NOLOCK) ON FM.Id = FS.FeeId
	    INNER JOIN sFee.tFeeHeadMaster FHM WITH (NOLOCK) ON FHM.Id=FM.FeeHeadId	
	WHERE
	 (LEFT(SA.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))	
	 AND ((RBM.Id = @rReceiptBookId) OR (@rReceiptBookId=0))
	 AND  ISNULL(CGM.Id,0)=0
	 AND ((SA.ClassId = @rClassId) OR (@rClassId = 0))
	 AND ((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0)) 
	 --And ISNULL(O.IsObsolete,0) = 0
	 And O.IsObsolete <> 1
	 -- IsInContext
		AND BM.IsInContext = 1
	GROUP by O.Id,SA.ClassName,SA.DivisionName,SA.AcademicId,SA.DivisionId,CGM.Id,CGM.Code,RBM.Title,RBM.Id,SA.Name,SC.ParentContactNo,SA.Code,SA.RollNo,SA.ClassOrderIndex
				,SA.DivisionOrder --0042058
	
	select T.SourceId,T.Name AS Name,T.DivisionId,T.ClassName+'-'+ T.DivisionName AS ClassDivision,SUM(ISNULL(T.PaidAmount,0)) AS PaidAmount,T.ParentContactNo AS ParentContactNo,T.Code AS Code,
		ISNULL(T.CollectionGroupId,0) AS CollectionGroupId,T.ReceiptBookId AS ReceiptBookId,T.RollNo 
		,T.ClassOrderIndex --add for mantis : 0042058
				,T.DivisionOrder --add for mantis : 0042058
		from #tempPaidSubPartDetails T
	group by T.DivisionId,T.CollectionGroupId,T.ReceiptBookId,T.ParentContactNo,T.Name,T.Code,T.RollNo,T.ClassName,T.DivisionName,T.SourceId,T.ClassOrderIndex
				,T.DivisionOrder
	HAVING SUM(ISNULL(T.PaidAmount,0)) > 0
	ORDER BY T.ClassOrderIndex
				,T.DivisionOrder,T.RollNo
	END 
	ELSE 
	BEGIN
	
	insert into #tempPaidSubPartDetails
	SELECT 
		ISNULL(SA.AcademicId,0) AS SourceId,
		 O.Id AS OrgGroupId,
		 ISNULL(SA.Code,'') As Code,
		 ISNULL(SA.Name,'') AS Name,
		 ISNULL(SC.ParentContactNo,'') AS ParentContactNo,
		 SA.ClassName AS ClassName,
		 SA.DivisionId AS DivisionId,
		 SA.DivisionName AS DivisionName,
		ISNULL(CGM.Id,0) AS CollectionGroupId,
		ISNULL(CGM.Code,'') AS CollectionGroup,
		ISNULL(RBM.Title,'')  AS ReceiptTitle,
		ISNULL(RBM.Id,0) As ReceiptBookId,
		SUM(ISNULL(FAS.PaidAmount,0)) AS PaidAmount,
		SUM(ISNULL(FAS.ToPayAmount,0.00))AS PendingAmount,
		SA.RollNo
		,SA.ClassOrderIndex INT --add for mantis : 0042058
		,SA.DivisionOrder INT --add for mantis : 0042058
	FROM 
		sStudent.vStudentAcademic SA WITH (NOLOCK)
		LEFT JOIN sStudent.tStudentCommunication SC WITH (NOLOCK) ON SC.StudentId = SA.StudentId
		INNER JOIN sFee.tFeeAllocationStudent FAS WITH (NOLOCK) ON FAS.AcademicId = SA.AcademicId
		INNER JOIN sFee.tFeeSetup FS WITH (NOLOCK) ON FAS.FeeSetupId = FS.Id
	    INNER JOIN sSetup.tBatchMaster BM WITH (NOLOCK) ON BM.Id = SA.BatchId
	    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM WITH (NOLOCK) ON OGBM.ID=BM.OrgGroupBatchId
	    INNER JOIN sSetup.tOrgGroupMaster O WITH (NOLOCK) ON O.Id =  OGBM.OrgGroupId		    
	    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM WITH (NOLOCK) ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
		INNER JOIN sFee.tReceiptBookMaster RBM WITH (NOLOCK) ON FS.ReceiptBookId=RBM.Id
		LEFT JOIN sFee.tCollectionGroupMaster CGM WITH (NOLOCK) ON FS.CollectionGroupId=CGM.Id AND RBM.Id = CGM.ReceiptBookId 
		INNER JOIN sFee.tFeeMaster FM WITH (NOLOCK) ON FM.Id = FS.FeeId
	    INNER JOIN sFee.tFeeHeadMaster FHM WITH (NOLOCK) ON FHM.Id=FM.FeeHeadId
	WHERE
	 (LEFT(SA.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))	
	 AND ((RBM.Id = @rReceiptBookId) OR (@rReceiptBookId=0))
	 AND ((CGM.Id = @rCollectionGroupId) OR (@rCollectionGroupId=0))
	 AND ((SA.ClassId = @rClassId) OR (@rClassId = 0))
	 --And ISNULL(O.IsObsolete,0) = 0
	 And O.IsObsolete <> 1
	 AND ((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0)) 
	 -- IsInContext
		AND BM.IsInContext = 1
	GROUP by O.Id,SA.ClassName,SA.DivisionName,SA.AcademicId,SA.DivisionId,CGM.Id,CGM.Code,RBM.Title,RBM.Id,SA.Name,SC.ParentContactNo,SA.Code
	,SA.RollNo,SA.ClassOrderIndex,SA.DivisionOrder

	select T.SourceId,T.Name AS Name,T.DivisionId,T.ClassName+'-'+ T.DivisionName AS ClassDivision,SUM(ISNULL(T.PaidAmount,0)) AS PaidAmount,T.ParentContactNo AS ParentContactNo,T.Code As Code,
		ISNULL(T.CollectionGroupId,0) AS CollectionGroupId,T.ReceiptBookId AS ReceiptBookId,T.RollNo
		,T.ClassOrderIndex --add for mantis : 0042058
		,T.DivisionOrder --add for mantis : 0042058
		from #tempPaidSubPartDetails T
		
		group by T.DivisionId,T.CollectionGroupId,T.ReceiptBookId,T.ParentContactNo,T.Name,T.Code,T.RollNo,T.ClassName,T.DivisionName,T.SourceId
		,T.ClassOrderIndex,T.DivisionOrder 
		HAVING SUM(ISNULL(T.PaidAmount,0)) > 0
		ORDER BY T.ClassOrderIndex
				,T.DivisionOrder
				,T.RollNo --0042058
		
	END
	
	DROP TABLE #tempPaidSubPartDetails
END

ELSE IF(@rType ='FeeStatusPaidSubPartDetailsMonthWise')
BEGIN 
CREATE TABLE #tempPaidSubPartDetailsMonthWise(
AcademicId bigint,
OrgGroupId int,
Code nvarchar(20),
Name nvarchar(200),
ParentContactNo nvarchar(50),
ClassName nvarchar(50),
DivisionId bigint,
DivisionName nvarchar(50),
CollectionGroupId bigint,
CollectionGroup nvarchar(200),
RecepitTitle nvarchar(100),
ReceiptBookId bigint,
PaidAmount DECIMAL(12,0),
PendingAmount DECIMAL(12,0),
RollNo int
)

CREATE TABLE #tempDFSMonthWise(
     Id INT,
     Amount DECIMAL(12,0),
     FeeHeadId INT,
     CollectionGroupId INT,
     ReceiptBookId INT,
     AcademicId BIGINT

)

INSERT INTO #tempDFSMonthWise
	 SELECT 
		FS1.Id,
		ISNULL(FS1.Amount,0)AS Amount,
		FM.FeeHeadId,
		FS1.CollectionGroupId,
		ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
		SA1.Id As AcademicId 
	FROM sFee.tFeeSetup FS1 WITH (NOLOCK)
		INNER JOIN sStudent.tAcademic SA1 WITH (NOLOCK) ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
	    INNER JOIN sStudent.tStudentMaster SM WITH (NOLOCK) ON SA1.StudentId = SM.Id
		INNER JOIN sSetup.tBatchMaster BM WITH (NOLOCK) ON BM.Id = SA1.BatchId
	    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM WITH (NOLOCK) ON OGBM.ID=BM.OrgGroupBatchId
	    INNER JOIN sSetup.tOrgGroupMaster O WITH (NOLOCK) ON O.Id =  OGBM.OrgGroupId		    
	    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM WITH (NOLOCK) ON COGBM.Id=OGBM.CommonOrgGroupBatchId
		INNER JOIN  sSetup.tOrganizationMaster OM WITH (NOLOCK) ON SA1.OrgId = OM.Id 
		INNER JOIN sFee.tFeeMaster FM WITH (NOLOCK) ON FM.Id=FS1.FeeId
	WHERE 
		(FS1.IsOptional=0) --AND BM.IsActive=1 
		AND COGBM.Id=@rCommonOrgGroupBatchId 
		--And ISNULL(O.IsObsolete,0) = 0
		And O.IsObsolete <> 1
		-- IsInContext
		AND BM.IsInContext = 1
		--AND FS1.StartDate>=@rFromDate AND FS1.EndDate<=@rToDate    
		--AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
		--AND (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=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='')
	UNION ALL
				
	SELECT 
		FS1.Id,
		ISNULL(FS1.Amount,0)AS Amount,
		FM.FeeHeadId,
		FS1.CollectionGroupId,
		ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
		SA1.Id As AcademicId 
	FROM sFee.tFeeSetup FS1 WITH (NOLOCK)
		INNER JOIN sFee.tFeeOptional FO WITH (NOLOCK) ON FO.FeeSetupId=FS1.Id 
	    INNER JOIN sFee.tFeeMaster FM WITH (NOLOCK) ON FM.Id=FS1.FeeId
		INNER JOIN sStudent.tAcademic SA1 WITH (NOLOCK) ON SA1.Id=FO.SourceId
		INNER JOIN sStudent.tStudentMaster SM WITH (NOLOCK) ON SA1.StudentId = SM.Id
	    INNER JOIN sSetup.tBatchMaster BM WITH (NOLOCK) ON BM.Id = SA1.BatchId
	    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM WITH (NOLOCK) ON OGBM.ID=BM.OrgGroupBatchId
	    INNER JOIN sSetup.tOrgGroupMaster O WITH (NOLOCK) ON O.Id =  OGBM.OrgGroupId		    
	    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM WITH (NOLOCK) ON COGBM.Id=OGBM.CommonOrgGroupBatchId
		INNER JOIN  sSetup.tOrganizationMaster OM WITH (NOLOCK) ON SA1.OrgId = OM.Id 
		AND FS1.BatchId = SA1.BatchId AND SA1.ClassId=FS1.ClassId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
    WHERE
				
	   (FS1.IsOptional=1) --AND BM.IsActive=1 
	   AND COGBM.Id=@rCommonOrgGroupBatchId 
	   --And ISNULL(O.IsObsolete,0) = 0
	   And O.IsObsolete <> 1
	   -- IsInContext
		AND BM.IsInContext = 1
	   --AND FS1.StartDate>=@rFromDate AND FS1.EndDate<=@rToDate    
	    --AND (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))
	    --AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0)) 
		


CREATE TABLE #tempDRMonthWise(
       PaidAmount DECIMAL(12,0),
	   FeeSetupId INT,
	   SourceId BIGINT,
	   ReceiptDate DATE
)
INSERT INTO #tempDRMonthWise
	SELECT 
		ISNULL(SUM(RD.Amount),0) AS PaidAmount,
		RD.FeeSetupId,
		R.SourceId
		,R.ReceiptDate
	FROM
		sFee.tReceipt R WITH (NOLOCK)
		INNER JOIN sFee.tReceiptDetail RD WITH (NOLOCK) ON RD.ReceiptId = R.Id 
		INNER JOIN sFee.tFeeSetup FS WITH (NOLOCK) ON RD.FeeSetupId = FS.Id
		INNER JOIN sFee.tFeeMaster FM WITH (NOLOCK) ON FS.FeeId = FM.Id
		INNER JOIN sStudent.tAcademic SA1 WITH (NOLOCK) ON SA1.Id=R.SourceId 
		INNER JOIN sStudent.tStudentMaster SM WITH (NOLOCK) ON SA1.StudentId = SM.Id
	    INNER JOIN sSetup.tBatchMaster BM WITH (NOLOCK) ON BM.Id = SA1.BatchId
	    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM WITH (NOLOCK) ON OGBM.ID=BM.OrgGroupBatchId
	    INNER JOIN sSetup.tOrgGroupMaster O WITH (NOLOCK) ON O.Id =  OGBM.OrgGroupId		    
	    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM WITH (NOLOCK) ON COGBM.Id=OGBM.CommonOrgGroupBatchId
		INNER JOIN  sSetup.tOrganizationMaster OM WITH (NOLOCK) ON SA1.OrgId = OM.Id 
	    
	WHERE		
		(R.SourceTypeId = 2001) 
		--AND (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))
		AND (R.IsObsolete = 0) 
		--AND BM.IsActive=1 
		AND COGBM.Id=@rCommonOrgGroupBatchId 
		--And ISNULL(O.IsObsolete,0) = 0
		And O.IsObsolete <> 1
		-- IsInContext
		AND BM.IsInContext = 1
		--AND FS.StartDate>=@rFromDate AND FS.EndDate<=@rToDate     
		--AND ((SA1.OrgGroupBatchId = @rOrgGroupBatchId) OR(@rOrgGroupBatchId=0))
	GROUP BY FeeSetupId,R.SourceId,R.ReceiptDate



IF(@rCollectionGroupId = 0)
	BEGIN
	insert into #tempPaidSubPartDetailsMonthWise
SELECT 
		ISNULL(SA.AcademicId,0) AS AcademicId,
		 O.Id AS OrgGroupId,
		 ISNULL(SA.Code,'') As Code,
		 ISNULL(SA.Name,'') AS Name,
		 ISNULL(SC.ParentContactNo,'') AS ParentContactNo,
		 SA.ClassName AS ClassName,
		 SA.DivisionId AS DivisionId,
		 SA.DivisionName AS DivisionName,
		ISNULL(CGM.Id,0) AS CollectionGroupId,
		ISNULL(CGM.Code,'') AS CollectionGroup,
		ISNULL(RBM.Title,'')  AS ReceiptTitle,
		ISNULL(RBM.Id,0) As ReceiptBookId,
		SUM(ISNULL(TDR.PaidAmount,0)) AS PaidAmount,
		SUM(ISNULL(TDFS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(TDR.PaidAmount,0.00))AS PendingAmount,
		SA.RollNo
		
	FROM 
		sStudent.vStudentAcademic SA WITH (NOLOCK)
		LEFT JOIN sStudent.tStudentCommunication SC WITH (NOLOCK) ON SC.StudentId = SA.StudentId
		INNER JOIN #tempDFSMonthWise TDFS ON TDFS.AcademicId=SA.AcademicId
	    INNER JOIN sSetup.tBatchMaster BM WITH (NOLOCK) ON BM.Id = SA.BatchId
	    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM WITH (NOLOCK) ON OGBM.ID=BM.OrgGroupBatchId
	    INNER JOIN sSetup.tOrgGroupMaster O WITH (NOLOCK) ON O.Id =  OGBM.OrgGroupId		    
	    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM WITH (NOLOCK) ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
		LEFT JOIN sFee.tFeeAllocation FA WITH (NOLOCK) ON FA.FeeSetupId=TDFS.Id AND FA.SourceId=SA.AcademicId
		LEFT JOIN #tempDRMonthWise TDR ON TDR.FeeSetupId = TDFS.Id AND SA.AcademicId = TDR.SourceId
		INNER JOIN sFee.tReceiptBookMaster RBM WITH (NOLOCK) ON TDFS.ReceiptBookId=RBM.Id
		LEFT JOIN sFee.tCollectionGroupMaster CGM WITH (NOLOCK) ON TDFS.CollectionGroupId=CGM.Id AND RBM.Id = CGM.ReceiptBookId-- AND (CGM.OrgGroupBatchId = 0 OR(0=0))
		INNER JOIN sFee.tFeeHeadMaster FHM WITH (NOLOCK) ON FHM.Id=TDFS.FeeHeadId	
	WHERE
	 (LEFT(SA.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))	
	 AND ((RBM.Id = @rReceiptBookId) OR (@rReceiptBookId=0))
	AND  ISNULL(CGM.Id,0)=0
	AND((DATEPART(M, TDR.ReceiptDate)  =@rMonth)OR(@rMonth=0))
	--And ISNULL(O.IsObsolete,0) = 0
	And O.IsObsolete <> 1
	-- IsInContext
		AND BM.IsInContext = 1
	--AND ((SA.ClassId = @rClassId) OR (@rClassId = 0))
	-- ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
	--AND(SA.IsActiveBatch =1)
	 AND ((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0)) 
		GROUP by O.Id,SA.ClassName,SA.DivisionName,SA.AcademicId,SA.DivisionId,CGM.Id,CGM.Code,RBM.Title,RBM.Id,SA.Name,SC.ParentContactNo,SA.Code,SA.RollNo
	
	select T.Name AS Name,T.DivisionId,T.ClassName+'-'+ T.DivisionName AS ClassDivision,SUM(ISNULL(T.PaidAmount,0)) AS PaidAmount,T.ParentContactNo AS ParentContactNo,T.Code AS Code,
		ISNULL(T.CollectionGroupId,0) AS CollectionGroupId,T.ReceiptBookId AS ReceiptBookId,T.RollNo from #tempPaidSubPartDetailsMonthWise T
		--LEFT JOIN 
		--(
		--	select OrgGroupId,ClassId,CollectionGroupId,ReceiptBookId, SUM(PaidAmount) AS PaidCount  from @ltempPaidSubPartDetails 
		--	WHERE PendingAmount  = 0
		--	group by OrgGroupId,ClassId,CollectionGroupId,ReceiptBookId
		--) A ON A.OrgGroupId = T.OrgGroupId AND A.ClassId = T.ClassId AND A.CollectionGroupId = T.CollectionGroupId
		group by T.AcademicId,T.DivisionId,T.CollectionGroupId,T.ReceiptBookId,T.ParentContactNo,T.Name,T.Code,T.RollNo,T.ClassName,T.DivisionName
		HAVING SUM(ISNULL(T.PaidAmount,0)) > 0
		ORDER BY T.RollNo
	END 
	ELSE 
	BEGIN
	
	CREATE TABLE #tempDFSMonthWise1(
     Id INT,
     Amount DECIMAL(12,0),
     FeeHeadId INT,
     CollectionGroupId INT,
     ReceiptBookId INT,
     AcademicId BIGINT  

    )
    
    INSERT INTO #tempDFSMonthWise1
	SELECT 
		FS1.Id,
		ISNULL(FS1.Amount,0)AS Amount,
		FM.FeeHeadId,
		FS1.CollectionGroupId,
		ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
		SA1.Id As AcademicId
	FROM sFee.tFeeSetup FS1 WITH (NOLOCK)
		INNER JOIN sStudent.tAcademic SA1 WITH (NOLOCK) ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
	    INNER JOIN sStudent.tStudentMaster SM WITH (NOLOCK) ON SA1.StudentId = SM.Id
		INNER JOIN sSetup.tBatchMaster BM WITH (NOLOCK) ON BM.Id = SA1.BatchId
	    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM WITH (NOLOCK) ON OGBM.ID=BM.OrgGroupBatchId
	    INNER JOIN sSetup.tOrgGroupMaster O WITH (NOLOCK) ON O.Id =  OGBM.OrgGroupId		    
	    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM WITH (NOLOCK) ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
		INNER JOIN  sSetup.tOrganizationMaster OM WITH (NOLOCK) ON SA1.OrgId = OM.Id 
		INNER JOIN sFee.tFeeMaster FM WITH (NOLOCK) ON FM.Id=FS1.FeeId
	WHERE 
		(FS1.IsOptional=0) 
		--AND BM.IsActive=1 
		AND COGBM.Id=@rCommonOrgGroupBatchId 
		--And ISNULL(O.IsObsolete,0) = 0
		And O.IsObsolete <> 1
		-- IsInContext
		AND BM.IsInContext = 1
		--AND FS1.StartDate>=@rFromDate AND FS1.EndDate<=@rToDate    
		--AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
		--AND (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=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='')
	UNION ALL
				
	SELECT 
		FS1.Id,
		ISNULL(FS1.Amount,0)AS Amount,
		FM.FeeHeadId,
		FS1.CollectionGroupId,
		ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
		SA1.Id As AcademicId
	FROM sFee.tFeeSetup FS1 WITH (NOLOCK)
		INNER JOIN sFee.tFeeOptional FO WITH (NOLOCK) ON FO.FeeSetupId=FS1.Id 
	    INNER JOIN sFee.tFeeMaster FM WITH (NOLOCK) ON FM.Id=FS1.FeeId
		INNER JOIN sStudent.tAcademic SA1 WITH (NOLOCK) ON SA1.Id=FO.SourceId
		INNER JOIN sStudent.tStudentMaster SM WITH (NOLOCK) ON SA1.StudentId = SM.Id
	    INNER JOIN sSetup.tBatchMaster BM WITH (NOLOCK) ON BM.Id = SA1.BatchId
	    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM WITH (NOLOCK) ON OGBM.ID=BM.OrgGroupBatchId
	    INNER JOIN sSetup.tOrgGroupMaster O WITH (NOLOCK) ON O.Id =  OGBM.OrgGroupId		    
	    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM WITH (NOLOCK) ON COGBM.Id=OGBM.CommonOrgGroupBatchId
		INNER JOIN  sSetup.tOrganizationMaster OM WITH (NOLOCK) ON SA1.OrgId = OM.Id
		AND FS1.BatchId = SA1.BatchId AND SA1.ClassId=FS1.ClassId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId 
		--AND BM.IsActive=1
		--AND FS1.StartDate>=@rFromDate AND FS1.EndDate<=@rToDate  
	WHERE
				
	    (FS1.IsOptional=1) AND ((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0))
		--And ISNULL(O.IsObsolete,0) = 0
		And O.IsObsolete <> 1
		-- IsInContext
		AND BM.IsInContext = 1
		--AND (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))
		--AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
	
	
	
CREATE TABLE #tempDRMonthWise1(
       PaidAmount DECIMAL(12,0),
	   FeeSetupId INT,
	   SourceId BIGINT,
	   ReceiptDate DATE
)
INSERT INTO #tempDRMonthWise1
	SELECT 
		ISNULL(SUM(RD.Amount),0) AS PaidAmount,
		RD.FeeSetupId,
		R.SourceId,
		R.ReceiptDate
	FROM
		sFee.tReceipt R WITH (NOLOCK)
		INNER JOIN sFee.tReceiptDetail RD WITH (NOLOCK) ON RD.ReceiptId = R.Id 
		INNER JOIN sFee.tFeeSetup FS WITH (NOLOCK) ON RD.FeeSetupId = FS.Id
		INNER JOIN sFee.tFeeMaster FM WITH (NOLOCK) ON FS.FeeId = FM.Id
		INNER JOIN sStudent.tAcademic SA1 WITH (NOLOCK) ON SA1.Id=R.SourceId 
		INNER JOIN sStudent.tStudentMaster SM WITH (NOLOCK) ON SA1.StudentId = SM.Id
	    INNER JOIN sSetup.tBatchMaster BM WITH (NOLOCK) ON BM.Id = SA1.BatchId
	    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM WITH (NOLOCK) ON OGBM.ID=BM.OrgGroupBatchId
	    INNER JOIN sSetup.tOrgGroupMaster O WITH (NOLOCK) ON O.Id =  OGBM.OrgGroupId		    
	    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM WITH (NOLOCK) ON COGBM.Id=OGBM.CommonOrgGroupBatchId
		INNER JOIN  sSetup.tOrganizationMaster OM WITH (NOLOCK) ON SA1.OrgId = OM.Id
	WHERE		
		(R.SourceTypeId = 2001)
		--AND (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))
		AND (R.IsObsolete = 0) 
		--And ISNULL(O.IsObsolete,0) = 0
		And O.IsObsolete <> 1
		--AND BM.IsActive=1 
		AND COGBM.Id=@rCommonOrgGroupBatchId
		-- IsInContext
		AND BM.IsInContext = 1
		 --AND FS.StartDate>=@rFromDate AND FS.EndDate<=@rToDate   
		--AND ((SA1.OrgGroupBatchId = @rOrgGroupBatchId) OR(@rOrgGroupBatchId=0))
	GROUP BY FeeSetupId,R.SourceId,R.ReceiptDate
	
	
	
	insert into #tempPaidSubPartDetailsMonthWise
		SELECT 
		ISNULL(SA.AcademicId,0) AS AcademicId,
		 O.Id AS OrgGroupId,
		 ISNULL(SA.Code,'') As Code,
		 ISNULL(SA.Name,'') AS Name,
		 ISNULL(SC.ParentContactNo,'') AS ParentContactNo,
		 SA.ClassName AS ClassName,
		 SA.DivisionId AS DivisionId,
		 SA.DivisionName AS DivisionName,
		ISNULL(CGM.Id,0) AS CollectionGroupId,
		ISNULL(CGM.Code,'') AS CollectionGroup,
		ISNULL(RBM.Title,'')  AS ReceiptTitle,
		ISNULL(RBM.Id,0) As ReceiptBookId,
		SUM(ISNULL(TDR1.PaidAmount,0)) AS PaidAmount,
		SUM(ISNULL(TDFS1.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(TDR1.PaidAmount,0.00))AS PendingAmount,
		SA.RollNo
		--SA.ClassOrderIndex,SA.DivisionOrder
	FROM 
		sStudent.vStudentAcademic SA WITH (NOLOCK)
		 LEFT JOIN sStudent.tStudentCommunication SC WITH (NOLOCK) ON SC.StudentId = SA.StudentId
		INNER JOIN #tempDFSMonthWise1 TDFS1 WITH (NOLOCK) ON TDFS1.AcademicId=SA.AcademicId
		LEFT JOIN sFee.tFeeAllocation FA WITH (NOLOCK)
			ON FA.FeeSetupId=TDFS1.Id AND FA.SourceId=SA.AcademicId
		LEFT JOIN #tempDRMonthWise TDR1 ON TDR1.FeeSetupId = TDFS1.Id AND SA.AcademicId = TDR1.SourceId
	    INNER JOIN sSetup.tBatchMaster BM WITH (NOLOCK) ON BM.Id = SA.BatchId
	    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM WITH (NOLOCK) ON OGBM.ID=BM.OrgGroupBatchId
	    INNER JOIN sSetup.tOrgGroupMaster O WITH (NOLOCK) ON O.Id =  OGBM.OrgGroupId		    
	    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM WITH (NOLOCK) ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
		INNER JOIN sFee.tReceiptBookMaster RBM WITH (NOLOCK) ON TDFS1.ReceiptBookId=RBM.Id
		LEFT JOIN sFee.tCollectionGroupMaster CGM WITH (NOLOCK) ON TDFS1.CollectionGroupId=CGM.Id AND RBM.Id = CGM.ReceiptBookId --AND (CGM.OrgGroupBatchId = 0 OR(0=0))
		INNER JOIN sFee.tFeeHeadMaster FHM WITH (NOLOCK) ON FHM.Id=TDFS1.FeeHeadId	
	WHERE
	 (LEFT(SA.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))	
	 AND ((RBM.Id = @rReceiptBookId) OR (@rReceiptBookId=0))
	AND ((CGM.Id = @rCollectionGroupId) OR (@rCollectionGroupId=0))
	AND((DATEPART(M, TDR1.ReceiptDate)  =@rMonth)OR(@rMonth=0))
	--AND ((SA.ClassId = @rClassId) OR (@rClassId = 0))
	-- ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
	--AND(SA.IsActiveBatch =1)
	--And ISNULL(O.IsObsolete,0) = 0
	And O.IsObsolete <> 1
	 AND ((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0)) 
	 -- IsInContext
		AND BM.IsInContext = 1
		GROUP by O.Id,SA.ClassName,SA.DivisionName,SA.AcademicId,SA.DivisionId,CGM.Id,CGM.Code,RBM.Title,RBM.Id,SA.Name,SC.ParentContactNo,SA.Code,SA.RollNo--,SA.ClassOrderIndex,SA.DivisionOrder
	

	select T.Name AS Name,T.DivisionId,T.ClassName+'-'+ T.DivisionName AS ClassDivision,SUM(ISNULL(T.PaidAmount,0)) AS PaidAmount,T.ParentContactNo AS ParentContactNo,T.Code As Code,
		ISNULL(T.CollectionGroupId,0) AS CollectionGroupId,T.ReceiptBookId AS ReceiptBookId,T.RollNo from #tempPaidSubPartDetailsMonthWise T
		--LEFT JOIN 
		--(
		--	select OrgGroupId,ClassId,CollectionGroupId,ReceiptBookId, SUM(PaidAmount) AS PaidCount  from @ltempPaidSubPartDetails 
		--	WHERE PendingAmount  = 0
		--	group by OrgGroupId,ClassId,CollectionGroupId,ReceiptBookId
		--) A ON A.OrgGroupId = T.OrgGroupId AND A.ClassId = T.ClassId AND A.CollectionGroupId = T.CollectionGroupId
		group by T.AcademicId,T.DivisionId,T.CollectionGroupId,T.ReceiptBookId,T.ParentContactNo,T.Name,T.Code,T.RollNo,T.ClassName,T.DivisionName
		--,T.ClassOrderIndex,T.DivisionOrder 
		HAVING SUM(ISNULL(T.PaidAmount,0)) > 0
		ORDER BY T.RollNo
		
		DROP TABLE #tempDFSMonthWise1
	DROP TABLE #tempDRMonthWise1
	END
	
	DROP TABLE #tempPaidSubPartDetailsMonthWise
	DROP TABLE #tempDFSMonthWise
	DROP TABLE #tempDRMonthWise
	
	
	
END

ELSE IF(@rType='ReceiptOrganization')
  BEGIN
	IF(@rSyncDate =1)
		BEGIN
				DELETE  sFee.tTempReceiptOrganization WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))
				CREATE TABLE #tempReceiptOrganizationSync(
				OrgGroupId int,
				OrgGroupName nvarchar(500),
				ReceiptId bigint,
				TotalReceiptAmount DECIMAL(12,0),
				IsObsolete bit
				)
				INSERT INTO #tempReceiptOrganizationSync
				SELECT O.Id AS OrgGroupId ,O.Title AS OrgGroupName,R.Id AS ReceiptCount,R.ReceiptAmount,R.IsObsolete
				FROM  sFee.tReceipt R WITH (NOLOCK)
				INNER JOIN sStudent.tAcademic SA WITH (NOLOCK) ON SA.Id=R.SourceId 
				INNER JOIN sStudent.tStudentMaster SM WITH (NOLOCK) ON SA.StudentId = SM.Id
				INNER JOIN sSetup.tBatchMaster BM WITH (NOLOCK) ON BM.Id = SA.BatchId
				INNER JOIN sSetup.tOrgGroupBatchMaster OGBM WITH (NOLOCK) ON OGBM.ID=BM.OrgGroupBatchId
				INNER JOIN sSetup.tOrgGroupMaster O WITH (NOLOCK) ON O.Id =  OGBM.OrgGroupId		    
				INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM WITH (NOLOCK) ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
				--INNER JOIN sSetup.tOrgGroupMaster OGM ON OGM.Id = LEFT(SA.OrgGroupBatchId,4)
				--INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SA.OrgId
				--INNER JOIN sFee.tReceiptBookMaster RBM ON RBM.Id=R.ReceiptBookId
				WHERE R.SourceTypeId = 2001
				AND ( (O.Id= @rOrgGroupId) OR  (@rOrgGroupId=0) )
				AND ((BM.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
				--AND(BM.IsActive =1) 
				AND (COGBM.Id=@rCommonOrgGroupBatchId )
				--And ISNULL(O.IsObsolete,0) = 0 
				And O.IsObsolete <> 1
				AND (R.ReceiptDate between @rFromDate and @rToDate)   
				-- IsInContext
				AND BM.IsInContext = 1 
			
			INSERT INTO sFee.tTempReceiptOrganization
				SELECT  T.OrgGroupId,T.OrgGroupName,ISNULL(COUNT(ReceiptId),0) AS ReceiptCount,ISNULL(SUM(TotalReceiptAmount),0.00) AS ReceiptAmount ,
				ISNULL(a.CancelReceiptCount,0.00)AS CancelAmount,@rFromDate,@rCommonOrgGroupBatchId,GetDate() FROM #tempReceiptOrganizationSync T  
				LEFT JOIN (
				SELECT  OrgGroupId,OrgGroupName,SUM(TotalReceiptAmount) AS CancelReceiptCount  FROM #tempReceiptOrganizationSync WHERE IsObsolete = 1
				GROUP BY OrgGroupId,OrgGroupName
				) A ON A.OrgGroupId=t.OrgGroupId
				WHERE IsObsolete = 0
				GROUP BY T.OrgGroupId,T.OrgGroupName,A.CancelReceiptCount
				ORDER BY OrgGroupId
				SELECT * FROM sFee.tTempReceiptOrganization WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))
				
				DROP TABLE #tempReceiptOrganizationSync
		END 
	ELSE
		BEGIN
			IF  Exists(select 1 from sFee.tTempReceiptOrganization WITH (NOLOCK) 
			where CONVERT(date,UpdateDate) =  CONVERT(date,getdate(),102)   AND CommonOrgGroupBatchId=@rCommonOrgGroupBatchId AND CONVERT(date,ReceiptDate) =@rFromDate AND CONVERT(date,ReceiptDate) =@rToDate)
			BEGIN
				SELECT * FROM sFee.tTempReceiptOrganization WITH (NOLOCK) WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))
				return
			END
			ELSE
			BEGIN 
			DELETE  sFee.tTempReceiptOrganization WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))
				CREATE TABLE #tempReceiptOrganization(
					OrgGroupId int,
					OrgGroupName nvarchar(500),
					ReceiptId bigint,
					TotalReceiptAmount DECIMAL(12,0),
					IsObsolete bit
				)
				INSERT INTO #tempReceiptOrganization
				SELECT O.Id AS OrgGroupId ,O.Title AS OrgGroupName,R.Id AS ReceiptCount,R.TotalReceiptAmount,R.IsObsolete
				FROM  sFee.tReceipt R WITH (NOLOCK)
				INNER JOIN sStudent.tAcademic SA WITH (NOLOCK) ON SA.Id=R.SourceId 
				INNER JOIN sStudent.tStudentMaster SM WITH (NOLOCK) ON SA.StudentId = SM.Id
				INNER JOIN sSetup.tBatchMaster BM WITH (NOLOCK) ON BM.Id = SA.BatchId
				INNER JOIN sSetup.tOrgGroupBatchMaster OGBM WITH (NOLOCK) ON OGBM.ID=BM.OrgGroupBatchId
				INNER JOIN sSetup.tOrgGroupMaster O WITH (NOLOCK) ON O.Id =  OGBM.OrgGroupId		    
				INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM WITH (NOLOCK) ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
				--INNER JOIN sSetup.tOrgGroupMaster OGM ON OGM.Id = LEFT(SA.OrgGroupBatchId,4)
				--INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SA.OrgId
				--INNER JOIN sFee.tReceiptBookMaster RBM ON RBM.Id=R.ReceiptBookId
				WHERE R.SourceTypeId = 2001
				AND ( (O.Id= @rOrgGroupId) OR  (@rOrgGroupId=0) )
				AND ((BM.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
				--AND(BM.IsActive =1) 
				AND (COGBM.Id=@rCommonOrgGroupBatchId ) 
				AND (R.ReceiptDate between @rFromDate and @rToDate)    
				-- IsInContext
				AND BM.IsInContext = 1
			
				INSERT INTO sFee.tTempReceiptOrganization
				SELECT  T.OrgGroupId,T.OrgGroupName,ISNULL(COUNT(ReceiptId),0) AS ReceiptCount,ISNULL(SUM(TotalReceiptAmount),0.00) AS ReceiptAmount ,
				ISNULL(a.CancelReceiptCount,0.00)AS CancelAmount,@rFromDate,@rCommonOrgGroupBatchId,GetDate() FROM #tempReceiptOrganization T  
				LEFT JOIN (
				SELECT  OrgGroupId,OrgGroupName,SUM(TotalReceiptAmount) AS CancelReceiptCount  FROM #tempReceiptOrganization WHERE IsObsolete = 1
				GROUP BY OrgGroupId,OrgGroupName
				) A ON A.OrgGroupId=t.OrgGroupId
				WHERE IsObsolete = 0
				GROUP BY T.OrgGroupId,T.OrgGroupName,A.CancelReceiptCount
				ORDER BY OrgGroupId
				SELECT * FROM sFee.tTempReceiptOrganization WITH (NOLOCK) WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))
		DROP TABLE #tempReceiptOrganization
			END
		END
  END
ELSE IF(@rType='ReceiptBookCollectionGroup')
  BEGIN
	CREATE TABLE #tempReceiptBookCollection (
	RecepitTitle nvarchar(200),
	--CollectionTitle nvarchar(200),
	ReceiptCount int,
	ReceiptAmount DECIMAL(12,0),
	ReceiptId bigint,
	--CollectionGroupId bigint,
	IsObsolete bit
)

INSERT INTO #tempReceiptBookCollection
 SELECT ISNULL(RBM.Title,'')  AS RecepitTitle ,
			--ISNULL(CGM.Code,'') AS CollectionTitle,
			ISNULL(COUNT(DISTINCT R.Id),0) AS ReceiptCount,CASE WHEN ROW_NUMBER() OVER (PARTITION BY R.Id  ORDER BY R.Id ) =1 THEN R.ReceiptAmount ELSE 0 END AS ReceiptAmount,
			ISNULL(RBM.Id,0) AS ReceiptId,
			--ISNULL(CGM.Id,0) AS CollectionGroupId,
			R.IsObsolete
		FROM  sFee.tReceipt R WITH (NOLOCK)
			INNER JOIN sFee.tReceiptDetail RD WITH (NOLOCK) ON R.Id = RD.ReceiptId
			INNER JOIN sStudent.tAcademic SA WITH (NOLOCK) ON SA.Id=R.SourceId
			INNER JOIN sStudent.tStudentMaster SM WITH (NOLOCK) ON SA.StudentId = SM.Id
			INNER JOIN sSetup.tBatchMaster BM WITH (NOLOCK) ON BM.Id = SA.BatchId
		    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM WITH (NOLOCK) ON OGBM.ID=BM.OrgGroupBatchId
		    INNER JOIN sSetup.tOrgGroupMaster O WITH (NOLOCK) ON O.Id =  OGBM.OrgGroupId		    
		    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM WITH (NOLOCK) ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
			INNER JOIN  sSetup.tOrganizationMaster OM WITH (NOLOCK) ON SA.OrgId = OM.Id 			
			INNER JOIN sFee.tFeeSetup FS WITH (NOLOCK) ON FS.Id = RD.FeeSetupId AND FS.ClassId = SA.ClassId AND FS.AdmissionCategoryId=SA.AdmissionCategoryId AND FS.ClassId = SA.ClassId
			INNER JOIN sFee.tReceiptBookMaster RBM WITH (NOLOCK) ON RBM.Id=FS.ReceiptBookId
			--LEFT JOIN sFee.tCollectionGroupMaster CGM ON CGM.Id=FS.CollectionGroupId AND CGM.ReceiptBookId  = RBM.Id 
			--AND CGM.OrgGroupBatchId = BM.OrgGroupBatchId
		WHERE R.SourceTypeId = 2001
			AND (LEFT(BM.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))
			AND ((BM.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
			--AND (R.IsObsolete = 1) 
			--AND(BM.IsActive =1) 
			AND ((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0))AND R.ReceiptDate between @rFromDate and @rToDate 
			--And ISNULL(O.IsObsolete,0) = 0   
			And O.IsObsolete <> 1
			-- IsInContext
		AND BM.IsInContext = 1
			GROUP BY RBM.Title,RBM.Id,R.ReceiptBookId,R.IsObsolete,R.Id,R.ReceiptAmount
			
			--SELECT  TRC.RecepitTitle +'-'+ TRC.CollectionTitle AS ReceictCollection,TRC.ReceiptId AS ReceiptId,TRC.CollectionGroupId AS CollectionGroupId,ISNULL(COUNT(TRC.ReceiptCount),0) AS ReceiptCount,SUM(ReceiptAmount) AS ReceiptAmount ,
			--ISNULL(A.CancelReceiptCount,0)AS CancelAmount FROM #tempReceiptBookCollection TRC 
			--LEFT JOIN (
			--SELECT ReceiptId,CollectionGroupId,SUM(ReceiptAmount) AS CancelReceiptCount  FROM #tempReceiptBookCollection WHERE IsObsolete = 1
			--GROUP BY ReceiptId,CollectionGroupId
			--) A ON A.ReceiptId=TRC.ReceiptId AND A.CollectionGroupId=TRC.CollectionGroupId
			
			--WHERE IsObsolete = 0
			--GROUP BY TRC.RecepitTitle,TRC.CollectionTitle,A.ReceiptId,A.CancelReceiptCount,TRC.ReceiptId,TRC.CollectionGroupId,TRC.ReceiptCount 

			SELECT  TRC.RecepitTitle AS ReceictCollection,TRC.ReceiptId AS ReceiptId,0 AS CollectionGroupId,ISNULL(COUNT(TRC.ReceiptCount),0) AS ReceiptCount,SUM(ReceiptAmount) AS ReceiptAmount ,
			ISNULL(A.CancelReceiptCount,0)AS CancelAmount FROM #tempReceiptBookCollection TRC 
			LEFT JOIN (
			SELECT ReceiptId,SUM(ReceiptAmount) AS CancelReceiptCount  FROM #tempReceiptBookCollection WHERE IsObsolete = 1
			GROUP BY ReceiptId
			) A ON A.ReceiptId=TRC.ReceiptId
			WHERE IsObsolete = 0
			GROUP BY TRC.RecepitTitle,A.ReceiptId,A.CancelReceiptCount,TRC.ReceiptId,TRC.ReceiptCount 
		DROP TABLE #tempReceiptBookCollection
  END
ELSE IF(@rType='ReceiptBookCollectionGroupDetail')
  BEGIN
  CREATE TABLE #tempReceiptBookCollectionDetail(
  SourceId bigint,
Code nvarchar(200),
Name nvarchar(200),
ReceiptNumber bigint,
ReceiptAmount DECIMAL(12,0),
ReceiptId bigint,
IsObsolete bit
)
  
	INSERT INTO #tempReceiptBookCollectionDetail
		 SELECT ISNULL(SA.Id,0) AS SourceId,SM.Code AS Code,[sStudent].[fStudentNameGet](SM.FirstName , SM.MiddleName, SM.LastName,OM.StudentNameFormatId ) As Name, R.ReceiptNumber AS ReceiptNumber,
		 CASE WHEN ROW_NUMBER() OVER (PARTITION BY R.Id  ORDER BY R.Id ) = 1 THEN R.ReceiptAmount ELSE 0 END AS ReceiptAmount,
		 R.Id AS ReceiptId,R.IsObsolete
		FROM  sFee.tReceipt R WITH (NOLOCK)
			INNER JOIN sFee.tReceiptDetail RD WITH (NOLOCK) ON R.Id = RD.ReceiptId
			INNER JOIN sStudent.tAcademic SA WITH (NOLOCK) ON SA.Id=R.SourceId
			--INNER JOIN sStudent.tStudentMaster SM1 ON SA.StudentId = SM1.Id
			INNER JOIN sStudent.tStudentMaster SM WITH (NOLOCK) ON SA.StudentId = SM.Id
			INNER JOIN sSetup.tOrganizationMaster OM WITH (NOLOCK) ON SA.OrgId = OM.Id AND SM.OrgId = OM.Id
			INNER JOIN sSetup.tBatchMaster BM WITH (NOLOCK) ON BM.Id = SA.BatchId
		    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM WITH (NOLOCK) ON OGBM.ID=BM.OrgGroupBatchId
		    INNER JOIN sSetup.tOrgGroupMaster O WITH (NOLOCK) ON O.Id =  OGBM.OrgGroupId		    
		    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM WITH (NOLOCK) ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
			--INNER JOIN sSetup.tOrganizationMaster OM ON SA.OrgId = OM.Id
			--INNER JOIN sStudent.tStudentMaster SM ON SA.StudentId=SM.Id	
			INNER JOIN sFee.tFeeSetup FS WITH (NOLOCK) ON FS.Id = RD.FeeSetupId AND FS.ClassId = SA.ClassId AND FS.AdmissionCategoryId =  SA.AdmissionCategoryId --AND FS.ClassId = SA.ClassId
			INNER JOIN sFee.tReceiptBookMaster RBM WITH (NOLOCK) ON RBM.Id=FS.ReceiptBookId 
			LEFT JOIN sFee.tCollectionGroupMaster CGM WITH (NOLOCK) ON CGM.Id=FS.CollectionGroupId AND CGM.ReceiptBookId  = RBM.Id AND CGM.OrgGroupBatchId = BM.OrgGroupBatchId
		WHERE R.SourceTypeId = 2001
			AND (LEFT(BM.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))
			--AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
			AND ((R.ReceiptBookId = @rReceiptBookId) OR (@rReceiptBookId=0))
			--AND ((CGM.Id = @rCollectionGroupId) OR (@rCollectionGroupId=0))
			--AND ((CGM.Id = @rCollectionGroupId) OR (@rCollectionGroupId=0))
			--AND (R.IsObsolete = 0) 
			--AND(BM.IsActive =1) 
			--And ISNULL(O.IsObsolete,0) = 0 -- remove isnull because it will take more time to execute in all above conditions mantisid : 0038978
			--And O.IsObsolete = 0	
			And O.IsObsolete <> 1		
			AND COGBM.Id=@rCommonOrgGroupBatchId AND R.ReceiptDate between @rFromDate and @rToDate    
			-- IsInContext
			AND BM.IsInContext = 1
			GROUP BY SA.Id,SM.Code,R.ReceiptNumber,[sStudent].[fStudentNameGet](SM.FirstName , SM.MiddleName, SM.LastName,OM.StudentNameFormatId), R.ReceiptBookId,R.Id,R.IsObsolete,R.ReceiptAmount 
			--ORDER BY 
	 
  SELECT *  FROM #tempReceiptBookCollectionDetail ORDER BY ReceiptNumber
  
  DROP TABLE #tempReceiptBookCollectionDetail
  END
END
GO
PRINT N'Altering Procedure [sFee].[pPendingFeeDashboardGet]...';


GO
ALTER PROCEDURE [sFee].[pPendingFeeDashboardGet]

	@rOrgGroupBatchId int = 0,
	@rCommonOrgGroupBatchId int = 0,
	@rType int,
	@rFilterType nvarchar(Max),
	@rFeeType nvarchar(Max),
	@rStudentStatus int = 0,
	@rUptoDate date = '',
	@rDepartmentId int=0,
	@rOrgId int,
	@rReceiptBookId int,
	@rOrgGroupId int = 0

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

DECLARE @lIsLogEnable bit = 0

IF(@lIsLogEnable = 1)
BEGIN

	INSERT INTO [sSystem].[tTraceLog]
	(LogMessage, ExtraLogMessage, ExceptionLog, ExceptionDetailLog, CreatedDateTime, PagePath)
	VALUES
	('Type: ' + CAST(@rType AS nvarchar(100)), 
	'@rOrgGroupBatchId = ' +  CAST(@rOrgGroupBatchId AS nvarchar(100))
	+ ', @rCommonOrgGroupBatchId = ' +  CAST(@rCommonOrgGroupBatchId AS nvarchar(100))
	+ ', @rFilterType = ' +  CAST(@rFilterType AS nvarchar(100))
	+ ', @rFeeType = ' +  CAST(@rFeeType AS nvarchar(100))
	+ ', @rStudentStatus = ' +  CAST(@rStudentStatus AS nvarchar(100))
	+ ', @rUptoDate = ' +  CAST(@rUptoDate AS nvarchar(100))  
	+ ', @rDepartmentId = ' +  CAST(@rDepartmentId AS nvarchar(100))  
	+ ', @rOrgId = ' +  CAST(@rOrgId AS nvarchar(100))
	+ ', @rReceiptBookId = ' +  CAST(@rReceiptBookId AS nvarchar(100))
	+ ', @rOrgGroupId = ' +  CAST(@rOrgGroupId AS nvarchar(100)), 
	'',
	'', 
	GETDATE(), 
	'[sFee].[pPendingFeeDashboardGet]')
END

--Changes for Mantis Id: 0039838
DECLARE @lConfigValue nvarchar(50)='', @lFromTime nvarchar(50)='', @lToTime nvarchar(50)='';

SELECT @lConfigValue = ItemValue FROM sConfig.tConfigurationSetup WITH (NOLOCK) WHERE ConfigurationId = 592   AND SourceTypeId = 2010   AND SourceId = @rOrgGroupId;

WITH SplitData AS (SELECT cast(item AS nvarchar(50)) AS item, ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) AS RowNum
    FROM sCommon.fnsplit(@lConfigValue, '-')
)
SELECT 
    @lFromTime = MAX(CASE WHEN RowNum = 1 THEN item END),
    @lToTime = MAX(CASE WHEN RowNum = 2 THEN item END)
FROM SplitData;


IF(@lConfigValue <> '' AND (CAST(CAST(GETDATE() AS DATE) AS DATETIME) + @lToTime) < (CAST(CAST(GETDATE() AS DATE) AS DATETIME) + @lFromTime))
BEGIN
	SET @lToTime = CAST(CAST((GETDATE()+1) AS DATE) AS DATETIME) + @lToTime
END
ELSE
BEGIN
	SET @lToTime = (CAST(CAST(GETDATE() AS DATE) AS DATETIME) + @lToTime)
END

IF(@lConfigValue <> '' AND (GETDATE() NOT BETWEEN (CAST(CAST(GETDATE() AS DATE) AS DATETIME) + @lFromTime) AND @lToTime))
BEGIN
	RETURN
END

SELECT @rOrgGroupBatchId = Id FROM sSetup.tOrgGroupBatchMaster WITH (NOLOCK) WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND OrgGroupId = @rOrgGroupId

IF (@rType = 1)
 BEGIN
IF(@rFilterType = 'Organizationwise')		
BEGIN 
	IF OBJECT_ID('tempdb..#FeeReceiptTemp') IS NOT NULL DROP TABLE #FeeReceiptTemp
	CREATE TABLE #FeeReceiptTemp
		(
			PaidAmount decimal (12,2),
			FeesetupId int,
			SourceId bigint
		)

	INSERT INTO #FeeReceiptTemp
		SELECT ISNULL(SUM(RD.Amount),0) AS PaidAmount,RD.FeeSetupId ,R.SourceId
		FROM
			sFee.tReceipt R WITH (NOLOCK)
			INNER JOIN sFee.tReceiptDetail RD WITH (NOLOCK) ON RD.ReceiptId = R.Id 
			INNER JOIN sFee.tFeeSetup FS WITH (NOLOCK) ON RD.FeeSetupId = FS.Id
			INNER JOIN sFee.tFeeMaster FM WITH (NOLOCK) ON FS.FeeId = FM.Id
			INNER JOIN sStudent.tAcademic SA1 WITH (NOLOCK) ON SA1.Id=R.SourceId
			INNER JOIN sSetup.tBatchMaster BM WITH (NOLOCK) ON BM.Id=SA1.BatchId			
		WHERE		
			(R.SourceTypeId = 2001) 
			AND (R.IsObsolete = 0) 
			AND ((BM.OrgGroupBatchId = @rOrgGroupBatchId))
			AND (R.OrgGroupBatchId = @rOrgGroupBatchId)
			AND (R.ReceiptDate <= @rUptoDate) 
			AND BM.IsInContext = 1 
			GROUP BY FeeSetupId,R.SourceId

	 IF(@rFeeType = 'FeeHeadwise')
	 BEGIN
		
		CREATE TABLE #FeeHeadwisetmp
		(
		Amount decimal (12,2),
		FeeName nvarchar(100),
		FeeHeadId int,
		AcademicId bigint,
		Id int,
		StartDate date
		)

		INSERT INTO #FeeHeadwisetmp
		SELECT 
					ISNULL(FS1.Amount,0)AS Amount,
					FM.Title AS FeeName,
					FM.FeeHeadId,
					SA1.Id As AcademicId,
					FS1.Id,
					FS1.StartDate
 				FROM sFee.tFeeSetup FS1 WITH (NOLOCK)
				INNER JOIN sStudent.tAcademic SA1 WITH (NOLOCK) ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId 
				INNER JOIN sStudent.tStudentMaster SM WITH (NOLOCK) ON SA1.StudentId = SM.Id			 
				AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				INNER JOIN sFee.tFeeMaster FM WITH (NOLOCK) ON FM.Id=FS1.FeeId
				INNER JOIN sSetup.tBatchMaster BM WITH (NOLOCK) ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
				WHERE 
					BM.OrgGroupBatchId = @rOrgGroupBatchId
					AND (FS1.IsOptional=0)
					-- IsInContext
					AND BM.IsInContext = 1
				UNION ALL
				SELECT 
					ISNULL(FS1.Amount,0)AS Amount,
					FM.Title AS FeeName,
					FM.FeeHeadId,
					SA1.AcademicId As AcademicId,
					FS1.Id,
					FS1.StartDate
				FROM sFee.tFeeSetup FS1 WITH (NOLOCK)
				INNER JOIN sFee.tFeeOptional FO WITH (NOLOCK) ON FO.FeeSetupId=FS1.Id
				INNER JOIN sFee.tFeeMaster FM WITH (NOLOCK) ON FM.Id=FS1.FeeId
				INNER JOIN sStudent.vStudentAcademic SA1 WITH (NOLOCK) ON SA1.AcademicId=FO.SourceId 
				AND SA1.BatchId = FS1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId AND SA1.ClassId = FS1.ClassId
				INNER JOIN sSetup.tBatchMaster BM WITH (NOLOCK) ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
				WHERE
						SA1.OrgGroupBatchId = @rOrgGroupBatchId
						AND (FS1.IsOptional=1)
						-- IsInContext
						AND BM.IsInContext = 1

		SELECT
			SA.OrgId,
			O.Title AS OrgName,
			SUM(ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00))AS PendingAmount,
			FHM.Id AS FeeHeadId,
			FHM.Title AS FeeHeadName,
			FHM.OrderIndex,
			ISNULL(O.OrderIndex,0) AS TypeOrderIndex
		FROM
			sStudent.vStudentAcademic SA WITH (NOLOCK)
			INNER JOIN sSetup.tOrganizationMaster O WITH (NOLOCK) ON SA.OrgId = O.Id
			INNER JOIN #FeeHeadwisetmp FS ON FS.AcademicId=SA.AcademicId
			LEFT JOIN sFee.tFeeAllocation FA WITH (NOLOCK) ON FA.FeeSetupId=FS.Id AND FA.SourceId=SA.AcademicId
			LEFT JOIN #FeeReceiptTemp R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
			INNER JOIN sFee.tFeeHeadMaster FHM WITH (NOLOCK) ON FHM.Id = FS.FeeHeadId	
			INNER JOIN sSetup.tBatchMaster BM WITH (NOLOCK) ON BM.Id = SA.BatchId
			WHERE
			  SA.OrgGroupBatchId = @rOrgGroupBatchId
			  AND (SA.StatusId = @rStudentStatus OR @rStudentStatus=0)
			  AND ((FS.StartDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
			  -- IsInContext
			  AND BM.IsInContext = 1
			GROUP BY SA.OrgId,O.Title,FHM.Id,FHM.Title,FHM.OrderIndex,O.OrderIndex
			ORDER BY O.OrderIndex,OrgId,FHM.OrderIndex

		DROP TABLE #FeeHeadwisetmp
	 END
	 ELSE IF(@rFeeType = 'FeeMasterwise')
	 BEGIN
		CREATE TABLE #FeeMasterwisetmp
		(
			FeeId int,
			Amount decimal (12,2),
			FeeName nvarchar(100),
			FeeHeadId int,
			AcademicId bigint,
			Id int,
			StartDate date,
			OrderIndex int
		)
	 
	 INSERT INTO #FeeMasterwisetmp
		 SELECT 
			FS1.FeeId,
			ISNULL(FS1.Amount,0)AS Amount,
			FM.Title AS FeeName,
			FM.FeeHeadId,
			SA1.Id As AcademicId,
			FS1.Id,
			FS1.StartDate,
			FM.OrderIndex
 		FROM sFee.tFeeSetup FS1 WITH (NOLOCK)
		INNER JOIN sStudent.tAcademic SA1 WITH (NOLOCK) ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId 
		INNER JOIN sStudent.tStudentMaster SM WITH (NOLOCK) ON SA1.StudentId = SM.Id			 
		AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
		INNER JOIN sFee.tFeeMaster FM WITH (NOLOCK) ON FM.Id=FS1.FeeId
		INNER JOIN sSetup.tBatchMaster BM WITH (NOLOCK) ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
		WHERE 
			BM.OrgGroupBatchId = @rOrgGroupBatchId
			AND (FS1.IsOptional=0)
			-- IsInContext
			AND BM.IsInContext = 1
		UNION ALL
		SELECT 
			FS1.FeeId,
			ISNULL(FS1.Amount,0)AS Amount,
			FM.Title AS FeeName,
			FM.FeeHeadId,
			SA1.AcademicId As AcademicId,
			FS1.Id,
			FS1.StartDate,
			FM.OrderIndex
		FROM sFee.tFeeSetup FS1 WITH (NOLOCK)
		INNER JOIN sFee.tFeeOptional FO WITH (NOLOCK) ON FO.FeeSetupId=FS1.Id
		INNER JOIN sFee.tFeeMaster FM WITH (NOLOCK) ON FM.Id=FS1.FeeId
		INNER JOIN sStudent.vStudentAcademic SA1 WITH (NOLOCK) ON SA1.AcademicId=FO.SourceId 
		AND SA1.BatchId = FS1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId AND SA1.ClassId = FS1.ClassId
		INNER JOIN sSetup.tBatchMaster BM WITH (NOLOCK) ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
		WHERE
				SA1.OrgGroupBatchId = @rOrgGroupBatchId
				AND (FS1.IsOptional=1)
				-- IsInContext
				AND BM.IsInContext = 1

	 SELECT
			SA.OrgId,
			O.Title AS OrgName,
			SUM(ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00))AS PendingAmount,
			FS.FeeId,
			FS.FeeName,
			FS.OrderIndex,
			ISNULL(O.OrderIndex,0) AS TypeOrderIndex
		FROM
			sStudent.vStudentAcademic SA WITH (NOLOCK)
				INNER JOIN sSetup.tOrganizationMaster O WITH (NOLOCK) ON SA.OrgId = O.Id
				INNER JOIN #FeeMasterwisetmp FS ON FS.AcademicId=SA.AcademicId
				LEFT JOIN sFee.tFeeAllocation FA WITH (NOLOCK) ON FA.FeeSetupId=FS.Id AND FA.SourceId=SA.AcademicId
				LEFT JOIN #FeeReceiptTemp R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
				INNER JOIN sFee.tFeeHeadMaster FHM WITH (NOLOCK) ON FHM.Id = FS.FeeHeadId	
				INNER JOIN sSetup.tBatchMaster BM WITH (NOLOCK) ON BM.Id = SA.BatchId
			WHERE
				SA.OrgGroupBatchId = @rOrgGroupBatchId
				AND (SA.StatusId = @rStudentStatus OR @rStudentStatus=0)
				AND ((FS.StartDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
				-- IsInContext
				AND BM.IsInContext = 1
			GROUP BY SA.OrgId,O.Title,FS.FeeId,FS.FeeName,FS.OrderIndex,O.OrderIndex
			ORDER BY O.OrderIndex,OrgId,FS.FeeId
	 DROP TABLE #FeeMasterwisetmp
	 END
	 ELSE IF(@rFeeType = 'CollectionGroupwise')
	 BEGIN
		CREATE TABLE #CollectionGroupwisetmp
		(
			FeeId int,
			Amount decimal (12,2),
			FeeName nvarchar(100),
			FeeHeadId int,
			AcademicId bigint,
			Id int,
			StartDate date,
			CollectionGroupId int
		)
		
		INSERT INTO #CollectionGroupwisetmp
	 SELECT 
			FS1.FeeId,
			ISNULL(FS1.Amount,0)AS Amount,
			FM.Title AS FeeName,
			FM.FeeHeadId,
			SA1.Id As AcademicId,
			FS1.Id,
			FS1.StartDate,
			FS1.CollectionGroupId
 		FROM sFee.tFeeSetup FS1 WITH (NOLOCK)
		INNER JOIN sStudent.tAcademic SA1 WITH (NOLOCK) ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId 
		INNER JOIN sStudent.tStudentMaster SM WITH (NOLOCK) ON SA1.StudentId = SM.Id			 
		AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
		INNER JOIN sFee.tFeeMaster FM WITH (NOLOCK) ON FM.Id=FS1.FeeId
		INNER JOIN sSetup.tBatchMaster BM WITH (NOLOCK) ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
		WHERE 
			BM.OrgGroupBatchId = @rOrgGroupBatchId
			AND (FS1.IsOptional=0)
			-- IsInContext
			AND BM.IsInContext = 1
		UNION ALL
		SELECT 
			FS1.FeeId,
			ISNULL(FS1.Amount,0)AS Amount,
			FM.Title AS FeeName,
			FM.FeeHeadId,
			SA1.AcademicId As AcademicId,
			FS1.Id,
			FS1.StartDate,
			FS1.CollectionGroupId
		FROM sFee.tFeeSetup FS1 WITH (NOLOCK)
		INNER JOIN sFee.tFeeOptional FO WITH (NOLOCK) ON FO.FeeSetupId=FS1.Id
		INNER JOIN sFee.tFeeMaster FM WITH (NOLOCK) ON FM.Id=FS1.FeeId
		INNER JOIN sStudent.vStudentAcademic SA1 WITH (NOLOCK) ON SA1.AcademicId=FO.SourceId 
		AND SA1.BatchId = FS1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId AND SA1.ClassId = FS1.ClassId
		INNER JOIN sSetup.tBatchMaster BM WITH (NOLOCK) ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
		WHERE
				SA1.OrgGroupBatchId = @rOrgGroupBatchId
				AND (FS1.IsOptional=1)
				-- IsInContext
				AND BM.IsInContext = 1

	 SELECT
			SA.OrgId,
			O.Title AS OrgName,
			SUM(ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00))AS PendingAmount,
			ISNULL(CGM.Id,0) AS CollectionGroupId,
			ISNULL(CGM.Title,'') AS CollectionGroupName,
			ISNULL(CGM.OrderIndex,0) AS OrderIndex,
			ISNULL(O.OrderIndex,0) AS TypeOrderIndex
		FROM
			sStudent.vStudentAcademic SA WITH (NOLOCK)
			INNER JOIN sSetup.tOrganizationMaster O WITH (NOLOCK) ON SA.OrgId = O.Id
			INNER JOIN #CollectionGroupwisetmp FS ON FS.AcademicId=SA.AcademicId
			LEFT JOIN sFee.tFeeAllocation FA WITH (NOLOCK) ON FA.FeeSetupId=FS.Id AND FA.SourceId=SA.AcademicId
			LEFT JOIN #FeeReceiptTemp R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
			LEFT JOIN sFee.tCollectionGroupMaster CGM WITH (NOLOCK) ON FS.CollectionGroupId=CGM.Id
			INNER JOIN sSetup.tBatchMaster BM WITH (NOLOCK) ON BM.Id = SA.BatchId
		WHERE
			  SA.OrgGroupBatchId = @rOrgGroupBatchId
			  AND (SA.StatusId = @rStudentStatus OR @rStudentStatus=0)
			  AND ((FS.StartDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
			  -- IsInContext
			  AND BM.IsInContext = 1
			GROUP BY SA.OrgId,O.Title,CGM.Id,CGM.Title,CGM.OrderIndex,O.OrderIndex
			ORDER BY O.OrderIndex,OrgId,CGM.Id

	 DROP TABLE #CollectionGroupwisetmp
	 END
	
	DROP TABLE #FeeReceiptTemp

END

ELSE IF(@rFilterType = 'Departmentwise')
BEGIN
	
	IF OBJECT_ID('tempdb..#FeeReceiptdeptTemp') IS NOT NULL DROP TABLE #FeeReceiptdeptTemp
	CREATE TABLE #FeeReceiptdeptTemp
		(
			PaidAmount decimal (12,2),
			FeesetupId int,
			SourceId bigint
		)

	INSERT INTO #FeeReceiptdeptTemp
	SELECT ISNULL(SUM(RD.Amount),0) AS PaidAmount,RD.FeeSetupId ,R.SourceId
		FROM
			sFee.tReceipt R WITH (NOLOCK) 
			INNER JOIN sFee.tReceiptDetail RD WITH (NOLOCK) ON RD.ReceiptId = R.Id 
			INNER JOIN sFee.tFeeSetup FS WITH (NOLOCK) ON RD.FeeSetupId = FS.Id
			INNER JOIN sFee.tFeeMaster FM WITH (NOLOCK) ON FS.FeeId = FM.Id
			INNER JOIN sStudent.tAcademic SA1 WITH (NOLOCK) ON SA1.Id=R.SourceId
			INNER JOIN sSetup.tBatchMaster BM WITH (NOLOCK) ON BM.Id=SA1.BatchId			
		WHERE		
			(R.SourceTypeId = 2001) 
			AND (R.IsObsolete = 0) 
			AND ((BM.OrgGroupBatchId = @rOrgGroupBatchId))
			AND (R.OrgGroupBatchId = @rOrgGroupBatchId)
			AND (R.ReceiptDate <= @rUptoDate) 
			AND BM.IsInContext = 1 
			GROUP BY FeeSetupId,R.SourceId

	 IF(@rFeeType = 'FeeHeadwise')
	 BEGIN
		IF OBJECT_ID('tempdb..#tmpDepartFeeHeadWise') IS NOT NULL DROP TABLE #tmpDepartFeeHeadWise
		CREATE TABLE #tmpDepartFeeHeadWise
		(
		Amount decimal (12,2),
		FeeName nvarchar(100),
		FeeHeadId int,
		AcademicId bigint,
		Id int,
		StartDate date
		)

		Insert Into #tmpDepartFeeHeadWise
		SELECT 
					ISNULL(FS1.Amount,0)AS Amount,
					FM.Title AS FeeName,
					FM.FeeHeadId,
					SA1.Id As AcademicId,
					FS1.Id,
					FS1.StartDate
 				FROM sFee.tFeeSetup FS1 WITH (NOLOCK)
				INNER JOIN sStudent.tAcademic SA1 WITH (NOLOCK) ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId 
				INNER JOIN sStudent.tStudentMaster SM WITH (NOLOCK) ON SA1.StudentId = SM.Id			 
				AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				INNER JOIN sFee.tFeeMaster FM WITH (NOLOCK) ON FM.Id=FS1.FeeId
				INNER JOIN sSetup.tBatchMaster BM WITH (NOLOCK) ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
				WHERE 
					BM.OrgGroupBatchId = @rOrgGroupBatchId
					AND (FS1.IsOptional=0)
					-- IsInContext
					AND BM.IsInContext = 1
				UNION ALL
				SELECT 
					ISNULL(FS1.Amount,0)AS Amount,
					FM.Title AS FeeName,
					FM.FeeHeadId,
					SA1.AcademicId As AcademicId,
					FS1.Id,
					FS1.StartDate
				FROM sFee.tFeeSetup FS1 WITH (NOLOCK)
				INNER JOIN sFee.tFeeOptional FO WITH (NOLOCK) ON FO.FeeSetupId=FS1.Id
				INNER JOIN sFee.tFeeMaster FM WITH (NOLOCK) ON FM.Id=FS1.FeeId
				INNER JOIN sStudent.vStudentAcademic SA1 WITH (NOLOCK) ON SA1.AcademicId=FO.SourceId 
				AND SA1.BatchId = FS1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId AND SA1.ClassId = FS1.ClassId
				INNER JOIN sSetup.tBatchMaster BM WITH (NOLOCK) ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
				WHERE
						SA1.OrgGroupBatchId = @rOrgGroupBatchId
						AND (FS1.IsOptional=1)
						-- IsInContext
						AND BM.IsInContext = 1

		SELECT
			SA.DepartmentId,
		    SA.DepartmentName,
			SUM(ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00))AS PendingAmount,
			FHM.Id AS FeeHeadId,
			FHM.Title AS FeeHeadName,
			FHM.OrderIndex,
			ISNULL(DM.OrderIndex,0) AS TypeOrderIndex
		FROM
			sStudent.vStudentAcademic SA WITH (NOLOCK)
		INNER JOIN sSetup.tOrganizationMaster O WITH (NOLOCK) ON SA.OrgId = O.Id
		INNER JOIN sSetup.tDepartmentMaster DM WITH (NOLOCK) ON DM.Id = SA.DepartmentId
		INNER JOIN #tmpDepartFeeHeadWise FS ON FS.AcademicId=SA.AcademicId
		LEFT JOIN sFee.tFeeAllocation FA WITH (NOLOCK) ON FA.FeeSetupId=FS.Id AND FA.SourceId=SA.AcademicId
		LEFT JOIN #FeeReceiptdeptTemp R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
		INNER JOIN sFee.tFeeHeadMaster FHM WITH (NOLOCK) ON FHM.Id = FS.FeeHeadId	
		INNER JOIN sSetup.tBatchMaster BM WITH (NOLOCK) ON BM.Id = SA.BatchId
		WHERE
			  SA.OrgGroupBatchId = @rOrgGroupBatchId
			  AND (SA.StatusId = @rStudentStatus OR @rStudentStatus=0)
			  AND ((FS.StartDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
			  -- IsInContext
			  AND BM.IsInContext = 1 
		GROUP BY SA.DepartmentId,SA.DepartmentName,FHM.Id,FHM.Title,FHM.OrderIndex,DM.OrderIndex
		ORDER BY DM.OrderIndex,DepartmentId,FHM.Id
	 END
	 ELSE IF(@rFeeType = 'FeeMasterwise')
	 BEGIN

		IF OBJECT_ID('tempdb..#tmpDepartFeeMasterwise') IS NOT NULL DROP TABLE #tmpDepartFeeMasterwise
		CREATE TABLE #tmpDepartFeeMasterwise
		(
		FeeId int,
		Amount decimal (12,2),
		FeeName nvarchar(100),
		FeeHeadId int,
		AcademicId bigint,
		Id int,
		StartDate date,
		OrderIndex int
		)

		Insert Into #tmpDepartFeeMasterwise
		SELECT 
					FS1.FeeId,
					ISNULL(FS1.Amount,0)AS Amount,
					FM.Title AS FeeName,
					FM.FeeHeadId,
					SA1.Id As AcademicId,
					FS1.Id,
					FS1.StartDate,
					FM.OrderIndex
 				FROM sFee.tFeeSetup FS1 WITH (NOLOCK)
				INNER JOIN sStudent.tAcademic SA1 WITH (NOLOCK) ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId 
				INNER JOIN sStudent.tStudentMaster SM WITH (NOLOCK) ON SA1.StudentId = SM.Id			 
				AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				INNER JOIN sFee.tFeeMaster FM WITH (NOLOCK) ON FM.Id=FS1.FeeId
				INNER JOIN sSetup.tBatchMaster BM WITH (NOLOCK) ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
				WHERE 
					BM.OrgGroupBatchId = @rOrgGroupBatchId
					AND (FS1.IsOptional=0)
					-- IsInContext
					AND BM.IsInContext = 1
				UNION ALL
				SELECT 
					FS1.FeeId,
					ISNULL(FS1.Amount,0)AS Amount,
					FM.Title AS FeeName,
					FM.FeeHeadId,
					SA1.AcademicId As AcademicId,
					FS1.Id,
					FS1.StartDate,
					FM.OrderIndex
				FROM sFee.tFeeSetup FS1 WITH (NOLOCK)
				INNER JOIN sFee.tFeeOptional FO WITH (NOLOCK) ON FO.FeeSetupId=FS1.Id
				INNER JOIN sFee.tFeeMaster FM WITH (NOLOCK) ON FM.Id=FS1.FeeId
				INNER JOIN sStudent.vStudentAcademic SA1 WITH (NOLOCK) ON SA1.AcademicId=FO.SourceId 
				AND SA1.BatchId = FS1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId AND SA1.ClassId = FS1.ClassId
				INNER JOIN sSetup.tBatchMaster BM WITH (NOLOCK) ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
				WHERE
						SA1.OrgGroupBatchId = @rOrgGroupBatchId
						AND (FS1.IsOptional=1)
						-- IsInContext
						AND BM.IsInContext = 1

		SELECT
			SA.DepartmentId,
		    SA.DepartmentName,
			SUM(ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00))AS PendingAmount,
			FS.FeeId,
			FS.FeeName,
			FS.OrderIndex,
			ISNULL(DM.OrderIndex,0) AS TypeOrderIndex
		FROM
			sStudent.vStudentAcademic SA WITH (NOLOCK)
				INNER JOIN sSetup.tOrganizationMaster O WITH (NOLOCK) ON SA.OrgId = O.Id
				INNER JOIN sSetup.tDepartmentMaster DM WITH (NOLOCK) ON DM.Id = SA.DepartmentId
				INNER JOIN #tmpDepartFeeMasterwise FS ON FS.AcademicId=SA.AcademicId
				LEFT JOIN sFee.tFeeAllocation FA WITH (NOLOCK) ON FA.FeeSetupId=FS.Id AND FA.SourceId=SA.AcademicId
				LEFT JOIN #FeeReceiptdeptTemp R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
				INNER JOIN sFee.tFeeHeadMaster FHM WITH (NOLOCK) ON FHM.Id = FS.FeeHeadId	
				INNER JOIN sSetup.tBatchMaster BM WITH (NOLOCK) ON BM.Id = SA.BatchId
			WHERE
			  SA.OrgGroupBatchId = @rOrgGroupBatchId
			  AND (SA.StatusId = @rStudentStatus OR @rStudentStatus=0)
			  AND ((FS.StartDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
			  -- IsInContext
			  AND BM.IsInContext = 1
			GROUP BY SA.DepartmentId,SA.DepartmentName,FS.FeeId,FS.FeeName,FS.OrderIndex,DM.OrderIndex
			ORDER BY DM.OrderIndex,DepartmentId,FS.FeeId
	 END
	 ELSE IF(@rFeeType = 'CollectionGroupwise')
	 BEGIN
		IF OBJECT_ID('tempdb..#tmpDepartCollectionGroupwise') IS NOT NULL DROP TABLE #tmpDepartCollectionGroupwise
		CREATE TABLE #tmpDepartCollectionGroupwise
		(
		FeeId int,
		Amount decimal (12,2),
		FeeName nvarchar(100),
		FeeHeadId int,
		AcademicId bigint,
		Id int,
		StartDate date,
		CollectionGroupId int
		)

		INSERT INTO #tmpDepartCollectionGroupwise
		SELECT 
					FS1.FeeId,
					ISNULL(FS1.Amount,0)AS Amount,
					FM.Title AS FeeName,
					FM.FeeHeadId,
					SA1.Id As AcademicId,
					FS1.Id,
					FS1.StartDate,
					FS1.CollectionGroupId
 				FROM sFee.tFeeSetup FS1 WITH (NOLOCK)
				INNER JOIN sStudent.tAcademic SA1 WITH (NOLOCK) ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId 
				INNER JOIN sStudent.tStudentMaster SM WITH (NOLOCK) ON SA1.StudentId = SM.Id			 
				AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				INNER JOIN sFee.tFeeMaster FM WITH (NOLOCK) ON FM.Id=FS1.FeeId
				INNER JOIN sSetup.tBatchMaster BM WITH (NOLOCK) ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
				WHERE 
					BM.OrgGroupBatchId = @rOrgGroupBatchId
					AND (FS1.IsOptional=0)
					-- IsInContext
					AND BM.IsInContext = 1
				UNION ALL
				SELECT 
					FS1.FeeId,
					ISNULL(FS1.Amount,0)AS Amount,
					FM.Title AS FeeName,
					FM.FeeHeadId,
					SA1.AcademicId As AcademicId,
					FS1.Id,
					FS1.StartDate,
					FS1.CollectionGroupId
				FROM sFee.tFeeSetup FS1 WITH (NOLOCK)
				INNER JOIN sFee.tFeeOptional FO WITH (NOLOCK) ON FO.FeeSetupId=FS1.Id
				INNER JOIN sFee.tFeeMaster FM WITH (NOLOCK) ON FM.Id=FS1.FeeId
				INNER JOIN sStudent.vStudentAcademic SA1 WITH (NOLOCK) ON SA1.AcademicId=FO.SourceId 
				AND SA1.BatchId = FS1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId AND SA1.ClassId = FS1.ClassId
				INNER JOIN sSetup.tBatchMaster BM WITH (NOLOCK) ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
				WHERE
						SA1.OrgGroupBatchId = @rOrgGroupBatchId
						AND (FS1.IsOptional=1)
						-- IsInContext
						AND BM.IsInContext = 1


		SELECT
			SA.DepartmentId,
		    SA.DepartmentName,
			SUM(ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00))AS PendingAmount,
			ISNULL(CGM.Id,0) AS CollectionGroupId,
			ISNULL(CGM.Title,'') AS CollectionGroupName,
			ISNULL(CGM.OrderIndex,0) AS OrderIndex,
			ISNULL(DM.OrderIndex,0) AS TypeOrderIndex
		FROM
			sStudent.vStudentAcademic SA WITH (NOLOCK)
				INNER JOIN sSetup.tOrganizationMaster O WITH (NOLOCK) ON SA.OrgId = O.Id
				INNER JOIN sSetup.tDepartmentMaster DM WITH (NOLOCK) ON DM.Id = SA.DepartmentId
				INNER JOIN #tmpDepartCollectionGroupwise FS ON FS.AcademicId=SA.AcademicId
				LEFT JOIN sFee.tFeeAllocation FA WITH (NOLOCK) ON FA.FeeSetupId=FS.Id AND FA.SourceId=SA.AcademicId
				LEFT JOIN #FeeReceiptdeptTemp R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
				LEFT JOIN sFee.tCollectionGroupMaster CGM WITH (NOLOCK) ON FS.CollectionGroupId=CGM.Id
				INNER JOIN sSetup.tBatchMaster BM WITH (NOLOCK) ON BM.Id = SA.BatchId
			WHERE
			  SA.OrgGroupBatchId = @rOrgGroupBatchId
			  AND (SA.StatusId = @rStudentStatus OR @rStudentStatus=0)
			  AND ((FS.StartDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
			  -- IsInContext
			  AND BM.IsInContext = 1
			GROUP BY SA.DepartmentId,SA.DepartmentName,CGM.Id,CGM.Title,CGM.OrderIndex,DM.OrderIndex
			ORDER BY DM.OrderIndex,DepartmentId,CGM.Id
	 END

	 DROP TABLE #FeeReceiptdeptTemp
END
ELSE IF(@rFilterType = 'ReceiptBookwise')
BEGIN

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

	CREATE TABLE #FeeReceiptbookTemp
		(
			PaidAmount decimal (12,2),
			FeesetupId int,
			SourceId bigint
		)

	INSERT INTO #FeeReceiptbookTemp
		SELECT ISNULL(SUM(RD.Amount),0) AS PaidAmount,RD.FeeSetupId ,R.SourceId
		FROM
			sFee.tReceipt R WITH (NOLOCK) 
			INNER JOIN sFee.tReceiptDetail RD WITH (NOLOCK) ON RD.ReceiptId = R.Id 
			INNER JOIN sFee.tFeeSetup FS WITH (NOLOCK) ON RD.FeeSetupId = FS.Id
			INNER JOIN sFee.tFeeMaster FM WITH (NOLOCK) ON FS.FeeId = FM.Id
			INNER JOIN sStudent.tAcademic SA1 WITH (NOLOCK) ON SA1.Id=R.SourceId
			INNER JOIN sSetup.tBatchMaster BM WITH (NOLOCK) ON BM.Id=SA1.BatchId			
		WHERE		
			(R.SourceTypeId = 2001) 
			AND (R.IsObsolete = 0) 
			AND ((BM.OrgGroupBatchId = @rOrgGroupBatchId))
			AND (R.OrgGroupBatchId = @rOrgGroupBatchId)
			AND (R.ReceiptDate <= @rUptoDate) 
			AND BM.IsInContext = 1 
			GROUP BY FeeSetupId,R.SourceId
		
	IF(@rFeeType = 'FeeHeadwise')
	BEGIN
		-- For Timeout issue
		CREATE TABLE #tmp
		(
		Amount decimal (12,2),
		FeeName nvarchar(100),
		FeeHeadId int,
		AcademicId bigint,
		Id int,
		StartDate date,
		ReceiptBookId int 
		)

		INSERT INTO #tmp
		SELECT 
			ISNULL(FS1.Amount,0)AS Amount,
			FM.Title AS FeeName,
			FM.FeeHeadId,
			SA1.Id As AcademicId,
			FS1.Id,
			FS1.StartDate,
			FS1.ReceiptBookId
 		FROM sFee.tFeeSetup FS1 WITH (NOLOCK)
		INNER JOIN sStudent.tAcademic SA1 WITH (NOLOCK) ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId 
		INNER JOIN sStudent.tStudentMaster SM WITH (NOLOCK) ON SA1.StudentId = SM.Id			 
		AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
		INNER JOIN sFee.tFeeMaster FM WITH (NOLOCK) ON FM.Id=FS1.FeeId
		INNER JOIN sSetup.tBatchMaster BM WITH (NOLOCK) ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
		WHERE 
			BM.OrgGroupBatchId = @rOrgGroupBatchId
			AND (FS1.IsOptional=0)
			-- IsInContext
			AND BM.IsInContext = 1
		UNION ALL
		SELECT 
			ISNULL(FS1.Amount,0)AS Amount,
			FM.Title AS FeeName,
			FM.FeeHeadId,
			SA1.AcademicId As AcademicId,
			FS1.Id,
			FS1.StartDate,
			FS1.ReceiptBookId
		FROM sFee.tFeeSetup FS1 WITH (NOLOCK)
		INNER JOIN sFee.tFeeOptional FO WITH (NOLOCK) ON FO.FeeSetupId=FS1.Id
		INNER JOIN sFee.tFeeMaster FM WITH (NOLOCK) ON FM.Id=FS1.FeeId
		INNER JOIN sStudent.vStudentAcademic SA1 WITH (NOLOCK) ON SA1.AcademicId=FO.SourceId 
		AND SA1.BatchId = FS1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId AND SA1.ClassId = FS1.ClassId
		INNER JOIN sSetup.tBatchMaster BM WITH (NOLOCK) ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
		WHERE
				SA1.OrgGroupBatchId = @rOrgGroupBatchId
				AND (FS1.IsOptional=1)
				-- IsInContext
				AND BM.IsInContext = 1

		SELECT
			FS.ReceiptBookId,
		    ISNULL(RBM.Title,'') AS ReceiptBookTitle,
			SUM(ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00))AS PendingAmount,
			FHM.Id AS FeeHeadId,
			FHM.Title AS FeeHeadName,
			FHM.OrderIndex,
			ISNULL(RBM.OrderIndex,0) AS TypeOrderIndex
		FROM
			sStudent.tAcademic SA WITH (NOLOCK)
			INNER JOIN [sStudent].[tStudentMaster] SM WITH (NOLOCK) ON SA.StudentId = SM.Id 
			INNER JOIN [sSetup].[tBatchMaster] BM WITH (NOLOCK) ON SA.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster O WITH (NOLOCK) ON SA.OrgId = O.Id
			INNER JOIN #tmp FS ON FS.AcademicId=SA.Id
			LEFT JOIN sFee.tFeeAllocation FA WITH (NOLOCK) ON FA.FeeSetupId=FS.Id AND FA.SourceId=SA.Id
			LEFT JOIN #FeeReceiptbookTemp R ON R.FeeSetupId = FS.Id AND SA.Id = R.SourceId
			INNER JOIN sFee.tFeeHeadMaster FHM WITH (NOLOCK) ON FHM.Id = FS.FeeHeadId	
			INNER JOIN sFee.tReceiptBookMaster RBM WITH (NOLOCK) ON FS.ReceiptBookId=RBM.Id
			WHERE
			  BM.OrgGroupBatchId = @rOrgGroupBatchId
			  AND (SM.StatusId = @rStudentStatus OR @rStudentStatus=0)
			  AND ((FS.StartDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
			  -- IsInContext
			  AND BM.IsInContext = 1
			GROUP BY FS.ReceiptBookId,RBM.Title,FHM.Id,FHM.Title,FHM.OrderIndex,RBM.OrderIndex
			ORDER BY RBM.OrderIndex,ReceiptBookId,FHM.Id

		DROP TABLE #tmp
	 END
	ELSE IF(@rFeeType = 'FeeMasterwise')
	BEGIN

		IF OBJECT_ID('tempdb..#tmpReceiptFeeMasterwise') IS NOT NULL DROP TABLE #tmpReceiptFeeMasterwise
		CREATE TABLE #tmpReceiptFeeMasterwise
		(
		FeeId int,
		Amount decimal (12,2),
		FeeName nvarchar(100),
		FeeHeadId int,
		AcademicId bigint,
		Id int,
		StartDate date,
		ReceiptBookId int,
		OrderIndex int
		)

		INSERT INTO  #tmpReceiptFeeMasterwise
		SELECT 
					FS1.FeeId,
					ISNULL(FS1.Amount,0)AS Amount,
					FM.Title AS FeeName,
					FM.FeeHeadId,
					SA1.Id As AcademicId,
					FS1.Id,
					FS1.StartDate,
					FS1.ReceiptBookId,
					FM.OrderIndex
 				FROM sFee.tFeeSetup FS1 WITH (NOLOCK)
				INNER JOIN sStudent.tAcademic SA1 WITH (NOLOCK) ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId 
				INNER JOIN sStudent.tStudentMaster SM WITH (NOLOCK) ON SA1.StudentId = SM.Id			 
				AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				INNER JOIN sFee.tFeeMaster FM WITH (NOLOCK) ON FM.Id=FS1.FeeId
				INNER JOIN sSetup.tBatchMaster BM WITH (NOLOCK) ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
				WHERE 
					BM.OrgGroupBatchId = @rOrgGroupBatchId
					AND (FS1.IsOptional=0)
					-- IsInContext
					AND BM.IsInContext = 1
				UNION ALL
				SELECT 
					FS1.FeeId,
					ISNULL(FS1.Amount,0)AS Amount,
					FM.Title AS FeeName,
					FM.FeeHeadId,
					SA1.AcademicId As AcademicId,
					FS1.Id,
					FS1.StartDate,
					FS1.ReceiptBookId,
					FM.OrderIndex
				FROM sFee.tFeeSetup FS1 WITH (NOLOCK)
				INNER JOIN sFee.tFeeOptional FO WITH (NOLOCK) ON FO.FeeSetupId=FS1.Id
				INNER JOIN sFee.tFeeMaster FM WITH (NOLOCK) ON FM.Id=FS1.FeeId
				INNER JOIN sStudent.vStudentAcademic SA1 WITH (NOLOCK) ON SA1.AcademicId=FO.SourceId 
				AND SA1.BatchId = FS1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId AND SA1.ClassId = FS1.ClassId
				INNER JOIN sSetup.tBatchMaster BM WITH (NOLOCK) ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
				WHERE
						SA1.OrgGroupBatchId = @rOrgGroupBatchId
						AND (FS1.IsOptional=1)
						-- IsInContext
						AND BM.IsInContext = 1

		SELECT
			FS.ReceiptBookId,
		    ISNULL(RBM.Title,'') AS ReceiptBookTitle,
			SUM(ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00))AS PendingAmount,
			FS.FeeId,
			FS.FeeName,
			FS.OrderIndex,
			ISNULL(RBM.OrderIndex,0) AS TypeOrderIndex
		FROM
			sStudent.vStudentAcademic SA WITH (NOLOCK)
				INNER JOIN sSetup.tOrganizationMaster O WITH (NOLOCK) ON SA.OrgId = O.Id
				INNER JOIN #tmpReceiptFeeMasterwise FS ON FS.AcademicId=SA.AcademicId
				LEFT JOIN sFee.tFeeAllocation FA WITH (NOLOCK) ON FA.FeeSetupId=FS.Id AND FA.SourceId=SA.AcademicId
				LEFT JOIN #FeeReceiptbookTemp R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
				INNER JOIN sFee.tFeeHeadMaster FHM WITH (NOLOCK) ON FHM.Id = FS.FeeHeadId	
				INNER JOIN sFee.tReceiptBookMaster RBM WITH (NOLOCK) ON FS.ReceiptBookId=RBM.Id
				INNER JOIN sSetup.tBatchMaster BM WITH (NOLOCK) ON SA.BatchId = BM.Id
			WHERE
			  SA.OrgGroupBatchId = @rOrgGroupBatchId
			  AND (SA.StatusId = @rStudentStatus OR @rStudentStatus=0)
			  AND ((FS.StartDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
			  -- IsInContext
			  AND BM.IsInContext = 1
			GROUP BY FS.ReceiptBookId,RBM.Title,FS.FeeId,FS.FeeName,FS.OrderIndex,RBM.OrderIndex
			ORDER BY RBM.OrderIndex,ReceiptBookId,FS.FeeId
	END
	ELSE IF(@rFeeType = 'CollectionGroupwise')
	BEGIN

		IF OBJECT_ID('tempdb..#tmpReceiptCollectionGroupwise') IS NOT NULL DROP TABLE #tmpReceiptCollectionGroupwise
		CREATE TABLE #tmpReceiptCollectionGroupwise
		(
		FeeId int,
		Amount decimal (12,2),
		FeeName nvarchar(100),
		FeeHeadId int,
		AcademicId bigint,
		Id int,
		StartDate date,
		CollectionGroupId int,
		ReceiptBookId int
		)

		INSERT INTO #tmpReceiptCollectionGroupwise
		SELECT 
					FS1.FeeId,
					ISNULL(FS1.Amount,0)AS Amount,
					FM.Title AS FeeName,
					FM.FeeHeadId,
					SA1.Id As AcademicId,
					FS1.Id,
					FS1.StartDate,
					FS1.CollectionGroupId,
					FS1.ReceiptBookId
 				FROM sFee.tFeeSetup FS1 WITH (NOLOCK)
				INNER JOIN sStudent.tAcademic SA1 WITH (NOLOCK) ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId 
				INNER JOIN sStudent.tStudentMaster SM WITH (NOLOCK) ON SA1.StudentId = SM.Id			 
				AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				INNER JOIN sFee.tFeeMaster FM WITH (NOLOCK) ON FM.Id=FS1.FeeId
				INNER JOIN sSetup.tBatchMaster BM WITH (NOLOCK) ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
				WHERE 
					BM.OrgGroupBatchId = @rOrgGroupBatchId
					AND (FS1.IsOptional=0)
					-- IsInContext
					AND BM.IsInContext = 1
				UNION ALL
				SELECT 
					FS1.FeeId,
					ISNULL(FS1.Amount,0)AS Amount,
					FM.Title AS FeeName,
					FM.FeeHeadId,
					SA1.AcademicId As AcademicId,
					FS1.Id,
					FS1.StartDate,
					FS1.CollectionGroupId,
					FS1.ReceiptBookId
				FROM sFee.tFeeSetup FS1 WITH (NOLOCK)
				INNER JOIN sFee.tFeeOptional FO WITH (NOLOCK) ON FO.FeeSetupId=FS1.Id
				INNER JOIN sFee.tFeeMaster FM WITH (NOLOCK) ON FM.Id=FS1.FeeId
				INNER JOIN sStudent.vStudentAcademic SA1 WITH (NOLOCK) ON SA1.AcademicId=FO.SourceId 
				AND SA1.BatchId = FS1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId AND SA1.ClassId = FS1.ClassId
				INNER JOIN sSetup.tBatchMaster BM WITH (NOLOCK) ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
				WHERE
						SA1.OrgGroupBatchId = @rOrgGroupBatchId
						AND (FS1.IsOptional=1)
						-- IsInContext
						AND BM.IsInContext = 1

		SELECT
			FS.ReceiptBookId,
		    ISNULL(RBM.Title,'') AS ReceiptBookTitle,
			SUM(ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00))AS PendingAmount,
			ISNULL(CGM.Id,0) AS CollectionGroupId,
			ISNULL(CGM.Title,'') AS CollectionGroupName,
			ISNULL(CGM.OrderIndex,0) AS OrderIndex,
			ISNULL(RBM.OrderIndex,0) AS TypeOrderIndex
		FROM
			sStudent.vStudentAcademic SA WITH (NOLOCK)
				INNER JOIN sSetup.tOrganizationMaster O WITH (NOLOCK) ON SA.OrgId = O.Id
				INNER JOIN #tmpReceiptCollectionGroupwise FS ON FS.AcademicId=SA.AcademicId
				LEFT JOIN sFee.tFeeAllocation FA WITH (NOLOCK) ON FA.FeeSetupId=FS.Id AND FA.SourceId=SA.AcademicId
				LEFT JOIN #FeeReceiptbookTemp R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
				LEFT JOIN sFee.tCollectionGroupMaster CGM WITH (NOLOCK) ON FS.CollectionGroupId=CGM.Id
				INNER JOIN sFee.tReceiptBookMaster RBM WITH (NOLOCK) ON FS.ReceiptBookId=RBM.Id
				INNER JOIN sSetup.tBatchMaster BM WITH (NOLOCK) ON SA.BatchId = BM.Id
			WHERE
			  SA.OrgGroupBatchId = @rOrgGroupBatchId
			  AND (SA.StatusId = @rStudentStatus OR @rStudentStatus=0)
			  AND ((FS.StartDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
			  -- IsInContext
			  AND BM.IsInContext = 1
			GROUP BY FS.ReceiptBookId,RBM.Title,CGM.Id,CGM.Title,CGM.OrderIndex,RBM.OrderIndex
			--ORDER BY ReceiptBookId,CGM.Id
			ORDER BY RBM.OrderIndex,CGM.OrderIndex
	END

	DROP TABLE #FeeReceiptbookTemp
END
	
END
ELSE IF(@rType = 2)
BEGIN
	IF OBJECT_ID('tempdb..#ReceiptTemp') IS NOT NULL DROP TABLE #ReceiptTemp

	CREATE TABLE #ReceiptTemp
		(
			PaidAmount decimal (12,2),
			FeesetupId int,
			SourceId bigint
		)

	INSERT INTO #ReceiptTemp
	SELECT ISNULL(SUM(RD.Amount),0) AS PaidAmount,RD.FeeSetupId ,R.SourceId
	FROM
		sFee.tReceipt R WITH (NOLOCK) 
		INNER JOIN sFee.tReceiptDetail RD WITH (NOLOCK) ON RD.ReceiptId = R.Id 
		INNER JOIN sFee.tFeeSetup FS WITH (NOLOCK) ON RD.FeeSetupId = FS.Id
		INNER JOIN sFee.tFeeMaster FM WITH (NOLOCK) ON FS.FeeId = FM.Id
		INNER JOIN sStudent.tAcademic SA1 WITH (NOLOCK) ON SA1.Id=R.SourceId
		INNER JOIN sSetup.tBatchMaster BM WITH (NOLOCK) ON BM.Id=SA1.BatchId			
	WHERE		
		(R.SourceTypeId = 2001) 
		AND (R.IsObsolete = 0) 
		AND ((BM.OrgGroupBatchId = @rOrgGroupBatchId))
		AND (R.OrgGroupBatchId = @rOrgGroupBatchId)
		AND (R.ReceiptDate <= @rUptoDate) 
		AND BM.IsInContext = 1 
		GROUP BY FeeSetupId,R.SourceId

		IF OBJECT_ID('tempdb..#tmptbl') IS NOT NULL DROP TABLE #tmptbl
		CREATE TABLE #tmptbl
			(
				FeeId int,
				Id int,
				IsOptional bit,
				IsVariable bit,
				Amount decimal (12,2),
				StartDate date,
				EndDate date,
				BatchId int,
				ReceiptBookId int,
				AcademicId bigint,
				FeeName nvarchar(100),
				FeeHeadId int,
				CollectionGroupId int,
				FeeOrderIndex int
			)
		INSERT INTO #tmptbl 
			SELECT 
							FS1.FeeId,
							FS1.Id,
							ISNULL(FS1.IsOptional,0)AS IsOptional,
							ISNULL(FS1.IsVariable,0)AS IsVariable,
							ISNULL(FS1.Amount,0)AS Amount,
							ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
							ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
							FS1.BatchId,
							ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
							SA1.Id AS AcademicId,
							FM.Title AS FeeName,
							FM.FeeHeadId,
							FS1.CollectionGroupId,
							FM.OrderIndex AS FeeOrderIndex			 
						FROM sFee.tFeeSetup FS1 WITH (NOLOCK)
						INNER JOIN sStudent.tAcademic SA1 WITH (NOLOCK) ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId 
						INNER JOIN sStudent.tStudentMaster SM WITH (NOLOCK) ON SA1.StudentId = SM.Id			 
						AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
						INNER JOIN sFee.tFeeMaster FM WITH (NOLOCK) ON FM.Id=FS1.FeeId
						INNER JOIN sSetup.tBatchMaster BM WITH (NOLOCK) ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
						WHERE 
							BM.OrgGroupBatchId = @rOrgGroupBatchId
							AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
							AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
							AND (FS1.IsOptional=0)
							-- IsInContext
							AND BM.IsInContext = 1
						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,
							FS1.CollectionGroupId,
							FM.OrderIndex AS FeeOrderIndex			 			 
						FROM sFee.tFeeSetup FS1 WITH (NOLOCK)
						INNER JOIN sFee.tFeeOptional FO WITH (NOLOCK) ON FO.FeeSetupId=FS1.Id
						INNER JOIN sFee.tFeeMaster FM WITH (NOLOCK) ON FM.Id=FS1.FeeId
						INNER JOIN sStudent.vStudentAcademic SA1 WITH (NOLOCK) ON SA1.AcademicId=FO.SourceId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
						INNER JOIN sSetup.tBatchMaster BM WITH (NOLOCK) ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
						WHERE
							SA1.OrgGroupBatchId = @rOrgGroupBatchId
							AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
							AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
							AND (FS1.IsOptional=1)
							-- IsInContext
							AND BM.IsInContext = 1
	
		SELECT 
					SA.OrgId,
					SA.OrganizationName as OrgName,
					SA.ClassId,
					SA.ClassName,
					SUM(ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00))AS PendingAmount
				FROM 
					sStudent.vStudentAcademic SA WITH (NOLOCK)
					INNER JOIN #tmptbl  FS ON FS.AcademicId=SA.AcademicId
					LEFT JOIN sFee.tFeeAllocation FA WITH (NOLOCK) ON FA.FeeSetupId=FS.Id AND FA.SourceId=SA.AcademicId
					LEFT JOIN #ReceiptTemp R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
					 INNER JOIN sSetup.tOrganizationMaster O WITH (NOLOCK) ON	
					 SA.OrgId = O.Id
					 INNER JOIN sFee.tReceiptBookMaster RBM WITH (NOLOCK) 
						ON FS.ReceiptBookId=RBM.Id
					 LEFT JOIN sFee.tCollectionGroupMaster CGM WITH (NOLOCK)
						ON FS.CollectionGroupId=CGM.Id	
					 LEFT JOIN sStudent.tStudentCommunication SC WITH (NOLOCK) 
						ON SC.StudentId = SA.StudentId
					 LEFT JOIN sStudent.tStudentOther SO WITH (NOLOCK)
						ON SO.StudentId = SA.StudentId
					 INNER JOIN sFee.tFeeHeadMaster FHM WITH (NOLOCK)
						ON FHM.Id = FS.FeeHeadId
					INNER JOIN sSetup.tBatchMaster BM WITH (NOLOCK) ON SA.BatchId = BM.Id	
				  LEFT JOIN sHostel.tAssignRoom AR WITH (NOLOCK) 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 WITH (NOLOCK) 
					INNER JOIN sTransport.tBusRouteDestinationMaster BM WITH (NOLOCK) ON BM.Id=AT.PickupDestinationId
					INNER JOIN sTransport.tBusRouteMaster B WITH (NOLOCK) ON B.Id=BM.BusRouteId AND  AT.SourceTypeId=2003 AND ((B.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))) RT
					ON RT.SourceId = SA.StudentId AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  
				WHERE	
				 SA.OrgGroupBatchId = @rOrgGroupBatchId
                 AND (SA.StatusId = @rStudentStatus OR @rStudentStatus=0) AND ((FS.StartDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
				 AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
				 AND (ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00) -ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00) != 0)			
				 -- IsInContext
				 AND BM.IsInContext = 1
				GROUP BY SA.ClassId,SA.ClassName,SA.OrgId,SA.OrganizationName,SA.ClassOrderIndex,SA.DivisionOrder
				--Order By SA.ClassId
				Order By SA.ClassOrderIndex,SA.DivisionOrder --add for mantis : 0042058
	DROP TABLE #ReceiptTemp
END
END
GO
PRINT N'Altering Procedure [sFee].[pRptFeeReceiptDetailsGet]...';


GO

ALTER PROCEDURE [sFee].[pRptFeeReceiptDetailsGet] 
	@rReportId INT = 0
	,@rReceiptId BIGINT = 0
	,@rOrgGroupId INT = 0
	,@rReceiptBookId INT = 0
	,@rFromReceiptNo INT = 0
	,@rToReceiptNo INT = 0
	,@rOrgId INT = 0
	,@rBatchId INT = 0
	,@rReceiptDate DATE = ''
	,@rClassId INT = 0
	,@rOrgIds NVARCHAR(max) = ''
	,@rReceiptPrintGroupId NVARCHAR(100) = ''
	,@rDivisionId INT = 0
	,@rAdmissionCategoryId INT = 0

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	DECLARE @lOrgGroupId INT = 0
	DECLARE @lAmountInWord NVARCHAR(500) = ''
	DECLARE @lReceiptAmount DECIMAL(12, 2) = 0.0
	DECLARE @lCurrencyCode NVARCHAR(20) = ''
	DECLARE @lCurrencyTitle NVARCHAR(100) = ''
	DECLARE @lIDConfigValue NVARCHAR(50) = '',@lOrgGroup_Id INT = 0

	SELECT @lOrgGroup_Id = OrgGroupId
	FROM sSetup.tOrganizationMaster
	WHERE Id = @rOrgId

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

	IF (@rOrgGroupId = 0)
	BEGIN
		SELECT @lOrgGroupId = OrgGroupId
			,@lReceiptAmount = R.ReceiptAmount
		FROM sFee.tReceipt R
		INNER JOIN sSetup.tOrgGroupBatchMaster OB ON R.OrgGroupBatchId = OB.Id
		WHERE R.Id = @rReceiptId

		SELECT @lAmountInWord = sFinanceCommon.fNumberToWordsWithDecimal(ISNULL(@lReceiptAmount, 0.00), 1, 2, @lOrgGroupId)
		--SELECT @lCurrencyCode = [sFinanceCommon].[fDefaultCurrencyCodeGet](@lOrgGroupId) -- Created common function for both code and title by Foram
		--SELECT @lCurrencyTitle = [sFinanceCommon].[fDefaultCurrencyTitleGet](@lOrgGroupId) -- Created common function for both code and title by Foram
	END
	--ELSE
	--BEGIN
	--	--SELECT @lCurrencyCode = [sFinanceCommon].[fDefaultCurrencyCodeGet](@rOrgGroupId) -- Created common function for both code and title by Foram
	--END

	IF (@rOrgGroupId = 0)
		SET @rOrgGroupId = @lOrgGroupId

	SELECT @lCurrencyCode = CurrencyCode, @lCurrencyTitle = CurrencyTitle FROM [sFinanceCommon].[fDefaultCurrencyValueGet](@rOrgGroupId) -- For Optimization by Foram

	SELECT FRD.ReceiptId
		,FR.ReceiptNumber
		,FR.ReceiptDate
		,SA.AcademicId
		,SA.Name AS Name --SA.FirstName+' '+SA.MiddleName+' '+SA.LastName AS Name,
		,SA.Code
		,SA.RollNo
		,SA.ClassId
		,SA.DivisionId
		,SA.ClassName
		,SA.DivisionName
		,SA.ClassName + ' - ' + SA.DivisionName AS ClassDivision
		,FM.FeeHeadId
		,FHM.Title AS FeeHead
		,FM.Id AS FeeId
		,FM.Title AS FeeName
		,FRD.Amount AS PaidAmount
		,PTM.Id AS PayTypeId
		,PTM.Title AS PayType
		,
		--changes by Jash on 06/11/2020--%
		CASE 
			WHEN ISNULL(FR.ChequeNo, '') != ''
				THEN FR.ChequeNo
			ELSE CONVERT(NVARCHAR(20), ISNULL(FR.PaymentTransactionId, ''))
			END AS ChequeNo
		,
		--CASE WHEN ISNULL(FR.ChequeNo,'') != '' THEN FR.ChequeNo
		--	WHEN ISNULL(PT.BankTransactionId,'') = '' THEN  CONVERT(nvarchar(20),FR.PaymentTransactionId)
		--	ELSE CONVERT(nvarchar(20),FR.PaymentTransactionId) +' - '+ CONVERT(nvarchar(20),PT.BankTransactionId) END AS ChequeNo,
		--%ISNULL(FR.ChequeNo,'') AS ChequeNo,
		ISNULL(FR.BankName, '') AS BankName
		,ISNULL(RBM.Address1, '') AS Address1
		,ISNULL(RBM.Address2, '') AS Address2
		,ISNULL(RBM.FullTitle, '') AS FullTitle
		,ISNULL(FR.TotalReceiptAmount, 0.00) AS TotalReceiptAmount
		,ISNULL(FR.ReceiptAmount, 0.00) AS ReceiptAmount
		,sFinanceCommon.fNumberToWordsWithDecimal(ISNULL(FR.ReceiptAmount, 0.00), 1, 2, @rOrgGroupId) AS ReceiptAmountInWords
		--,(
		--	CASE 
		--		WHEN @rOrgGroupId = 0 -- For Single Receipt
		--			THEN ''
		--		WHEN @rOrgGroupId != 0 -- For Bulk Receipt
		--			THEN sFinanceCommon.fNumberToWordsWithDecimal(ISNULL(FR.ReceiptAmount, 0.00), 1, 2, @rOrgGroupId)
		--		END
		--	) AS ReceiptAmountInWords
		,ISNULL(FR.DiscountAmount, 0.00) AS DiscountAmount
		,FR.Remark
		,(
			CASE 
				WHEN ISNULL(FR.PaymentTransactionId, 0) > 0
					THEN -- Navrachana
						'Online Generated'
				ELSE ISNULL(U.DisplayTitle, '')
				END
			) AS UserName
		,OM.OrgLogo
		--ISNULL(U.DisplayTitle,'') AS UserName,
		,RBM.Remark1
		,RBM.Remark2
		,ISNULL(RBM.IsOnPrePrinted, 0) AS IsOnPrePrinted
		,ISNULL(RBM.IsSupressLogo, 0) AS IsSupressLogo
		,ISNULL(RBM.IsDisplaySchoolName, 0) AS IsDisplaySchoolName
		,RBM.ReportId
		,OM.Title AS OrganizationName
		,
		--(CASE  WHEN (RBM.ReportId = 20775 OR RBM.ReportId = 20777 OR RBM.ReportId = 20874 OR RBM.ReportId =20427 OR RBM.ReportId =20890 OR RBM.ReportId =20901 OR RBM.ReportId =20902) AND ISNULL(RBM.IsMonthDetailOnly,0) = 0 THEN 
		--	[sFee].[fFeeHeadMonthDetailGet](FR.ID,FHM.Id) -- Fee name in detail	 			  
		(
			CASE 
				WHEN RBM.ReportId = 20576
					THEN [sFee].[fReceiptMonthDetailGet](FR.ID, 0) -- HM patel report
				WHEN RBM.ReportId = 30457
					THEN [sFee].[fReceiptMonthDetailGet](FR.ID, 1)
				WHEN ISNULL(RBM.IsMonthDetailOnly, 0) = 1 AND ISNULL(RBM.IsFeeInvoiceHeadwise, 0) = 1
					THEN [sFee].[fFeeHeadMonthNameGet](FR.ID, FHM.Id) -- Head wise Month name in detail
				WHEN ISNULL(RBM.IsMonthDetailOnly, 0) = 1 AND ISNULL(RBM.IsFeeInvoiceHeadwise, 0) = 0
					THEN [sFee].[fFeeMonthNameGet](FR.ID, FM.Id) -- Fee wise Month name in detail
				ELSE ''
				END
			) AS MonthDetail
		,(
			CASE 
				WHEN ISNULL(RBM.IsFeeInvoiceHeadwise, 0) = 1 AND @rReceiptId > 0 -- Added @rReceiptId condition for optimization by Foram
					THEN Stuff((
								SELECT N', ' + FS1.FeeDuration
								FROM sFee.tReceipt FR1
								INNER JOIN sFee.tReceiptDetail FRD1 ON FR1.Id = FRD1.ReceiptId
									AND FR1.SourceTypeId = 2001
								INNER JOIN sFee.tFeeSetup FS1 ON FRD1.FeeSetupId = FS1.Id
								INNER JOIN sFee.tFeeMaster FM1 ON FS1.FeeId = FM1.Id
								INNER JOIN sFee.tFeeHeadMaster FHM1 ON FHM1.Id = FM1.FeeHeadId
								INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId = FR1.SourceId
								WHERE FM1.FeeHeadId = FM.FeeHeadId
									AND FS.ClassId = FS1.ClassId
									AND FR1.Id = @rReceiptId
									--Where FM1.Id = FM.Id AND FS.ClassId = FS1.ClassId AND FR1.Id = @rReceiptId
									AND (ISNULL(SA1.OrgId, 0) IN (SELECT cast(item AS INT) FROM sCommon.fnsplit(@rOrgIds, ',')) OR @rOrgIds = '')
								ORDER BY FS1.StartDate
								FOR XML PATH('')
									,TYPE
								).value('text()[1]', 'nvarchar(max)'), 1, 2, N'') -- Fee Head wise Fee Duration
				WHEN ISNULL(RBM.IsFeeInvoiceHeadwise, 0) = 0
					THEN FS.FeeDuration -- Fee wise Fee Duration
				ELSE ''
				END
			) AS FeeDuration
		,
		--Stuff((SELECT  N', ' +  FS1.FeeDuration FROM 
		--sFee.tReceipt FR1				
		--INNER JOIN sFee.tReceiptDetail FRD1	ON FR1.Id=FRD1.ReceiptId AND FR1.SourceTypeId=2001				
		--INNER JOIN sFee.tFeeSetup FS1 ON FRD1.FeeSetupId = FS1.Id
		--INNER JOIN sFee.tFeeMaster FM1 ON FS1.FeeId=FM1.Id						
		--INNER JOIN sFee.tFeeHeadMaster FHM1 ON FHM1.Id=FM1.FeeHeadId 
		--INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId = FR1.SourceId
		----Where FM1.FeeHeadId = FM.FeeHeadId AND FS.ClassId = FS1.ClassId AND FR1.Id = @rReceiptId
		--Where FM1.Id = FM.Id AND FS.ClassId = FS1.ClassId AND FR1.Id = @rReceiptId
		--AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')
		-- Order By FS.StartDate
		--FOR XML PATH(''),TYPE).value('text()[1]','nvarchar(max)'),1,2,N'' ) AS FeeDuration,			
		DM.Title AS DepartmentName
		,FM.OrderIndex AS FeeOrderIndex
		,FHM.OrderIndex AS FeeHeadOrderIndex
		,FR.IsObsolete AS IsCancelReceipt
		,@lCurrencyCode AS CurrencyCode
		,@lCurrencyTitle AS CurrencyTitle
		,BM.Title AS Batch
		,FR.ChequeDate AS ChequeDate
		,ISNULL(RBM.IsMonthDetailOnly, 0) AS IsMonthDetailOnly
		,ISNULL(RBM.IsFeeInvoiceHeadwise, 0) AS IsFeeInvoiceHeadwise
		,ISNULL(RBM.GroupTitle, '') AS GroupTitle
		,ISNULL(RBM.IsSuppressFeeDetail, 0) AS IsSuppressFeeDetail
		,ISNULL(CGM.Title, '') AS CollectionGroupName
		,ISNULL(FI.InvoiceNumber, 0) AS InvoiceNumber
		,SA.SUID
		,CASE WHEN RBM.IsOnPrePrinted = 1 THEN 2 ELSE ISNULL(RBM.HeaderDisplayId, 1) END AS HeaderDisplayId
		,RBM.ReceiptBookHeader
		,RBM.ServiceTaxPercentage
		,ISNULL(FR.AmountAfterDiscount, 0) AS AmountAfterDiscount
		--,(
		--	CASE 
		--		WHEN FR.CGSTPercentage IS NULL
		--			THEN RBM.CGSTPercentage
		--		ELSE FR.CGSTPercentage
		--		END
		--	) AS CGSTPercentage
		,ISNULL(FR.CGSTPercentage,RBM.CGSTPercentage) AS CGSTPercentage -- removed above case and added dircetly ISNULL for optmization By Foram
		--,(
		--	CASE 
		--		WHEN FR.SGSTPercentage IS NULL
		--			THEN RBM.SGSTPercentage
		--		ELSE FR.SGSTPercentage
		--		END
		--	) AS SGSTPercentage
		,ISNULL(FR.SGSTPercentage,RBM.SGSTPercentage) AS SGSTPercentage -- removed above case and added dircetly ISNULL for optmization By Foram
		,ISNULL(FR.CGSTAmount, 0) AS CGSTAmount
		,ISNULL(FR.SGSTAmount, 0) AS SGSTAmount
		,ISNULL(OOM.GSTINNo, '') AS GSTINNo
		,ISNULL(OOM.HSNSACCode, '') AS HSNSACCode
		,@lIDConfigValue AS ItemValue
		,SF.FatherName
		,SF.MotherName
		,ISNULL(FA.DiscountAmount, 0) AS ExemptionAmount
		,ISNULL(FA.Remark, '') AS ExemptionRemark
		,EI.EmployeeSign
		,ISNULL(SC.PresentCity, '') AS PresentCity
		--,(
		--			ISNULL((
		--			CASE 
		--				WHEN SC.PresentStreetOne IS NOT NULL
		--					AND SC.PresentStreetOne != ''
		--					THEN '' + SC.PresentStreetOne
		--				END
		--			), '') 
		--			+ ISNULL((
		--			CASE 
		--				WHEN SC.PresentStreetTwo IS NOT NULL
		--					AND SC.PresentStreetTwo != ''
		--					THEN ', ' + SC.PresentStreetTwo
		--				END
		--			), '') 
		--			+ ISNULL((
		--			CASE 
		--				WHEN SC.PresentStreetThree IS NOT NULL
		--					AND SC.PresentStreetThree != ''
		--					THEN ', ' + SC.PresentStreetThree
		--				END
		--			), '') 
		--			+ ISNULL((
		--			CASE 
		--				WHEN SC.PresentCity IS NOT NULL
		--					AND SC.PresentCity != ''
		--					THEN ', ' + SC.PresentCity
		--				END
		--			), '') 
		--			+ ISNULL((
		--			CASE 
		--				WHEN SC.PresentState IS NOT NULL
		--					AND SC.PresentState != ''
		--					THEN ', ' + SC.PresentState
		--				END
		--			), '') 
		--			+ ISNULL((
		--			CASE 
		--				WHEN SC.PresentZipCode IS NOT NULL
		--					AND SC.PresentZipCode != ''
		--					THEN ', ' + SC.PresentZipCode
		--				END
		--			), '')
		--	) AS PresentAdress
		,LTRIM(
			ISNULL(NULLIF(SC.PresentStreetOne, ''), '') +
			ISNULL(', ' + NULLIF(SC.PresentStreetTwo, ''), '') +
			ISNULL(', ' + NULLIF(SC.PresentStreetThree, ''), '') +
			ISNULL(', ' + NULLIF(SC.PresentCity, ''), '') +
			ISNULL(', ' + NULLIF(SC.PresentState, ''), '') +
			ISNULL(', ' + NULLIF(SC.PresentZipCode, ''), '')
		) AS PresentAddress -- removed above case and added dircetly ISNULL for optmization By Foram
		--ISNULL(SC.PresentStreetOne +','+ SC.PresentStreetTwo +','+ SC.PresentStreetThree +','+ SC.PresentCity +','+ SC.PresentState +'-'+ SC.PresentZipCode ,'') AS PresentAdress,
		,SC.ParentContactNo
		,ISNULL(RBM.IsDisplayPendingFeeAmount, 0) AS IsDisplayPendingFeeAmount
		,CASE 
			WHEN @rOrgGroupId = 1134 OR @rOrgGroupId = 1742
				THEN (
						CASE 
							WHEN ISNULL(RBM.IsDisplayPendingFeeAmount, 0) = 0
								THEN 0
							ELSE ISNULL([sFee].[fPendingFeeAmountReceiptBookwiseGet](FR.SourceId, RBM.Id), 0)
							END
						)
			ELSE (
					CASE 
						WHEN ISNULL(RBM.IsDisplayPendingFeeAmount, 0) = 0
							THEN 0
						ELSE ISNULL([sFee].[fPendingFeeAmountReceiptBookwiseGet](FR.SourceId, 0), 0)
						END
					)
			END AS PendingFeeAmount
		,SA.FirstName
		,SA.LastName
		,ISNULL([sFee].[fFeeAmountSumGet](FR.SourceId), 0) AS FeeAmount
		,ISNULL([sFee].[fFeeReceiptDiscountSumGet](FR.SourceId), 0) AS ExemptionAmountSum
		,[sFee].[fTransportBusRouteGet](SA.StudentId, FR.OrgGroupBatchId) AS TransportBusRoute
		,ISNULL(RBM.BankAccountNumber, '') AS BankAccountNumber
		,ISNULL(FHM.Number, 0) AS FeeHeadNumber
		,ISNULL(FM.Number, 0) AS FeeNumber
		,ISNULL(RBM.DigitalSignature, 0x) AS DigitalSignature
		,ISNULL(FR.CancelStatusRemark, '') AS CancelStatusRemark
		,FS.Amount AS FeeSetupAmount
		,FR.CreatedDateTime
		,ISNULL(FR.PaymentTransactionId, 0) AS PaymentTransactionId
		,SA.MiddleName
		,CONVERT(CHAR(5), FR.CreatedDateTime, 108) AS CreatedTime
		,
		--by megha - 0026430
		(
			CASE 
				WHEN ISNULL(FA.VariableAmount, 0) > 0
					THEN FA.VariableAmount
				WHEN ISNULL(FS.Amount, 0) > 0
					THEN FS.Amount
				END
			) + ISNULL(FA.AdditionalAmount, 0) - ISNULL(FA.DiscountAmount, 0) - ISNULL(FA.NotApplicableAmount, 0) AS TotalPayableAmount
		,OGM.Title AS OrgGroupTitle
		,NID.CollectionGroupName AS NextInstallmentName
		,--Mantis End- 0031305
		ISNULL(HM.Title, '') AS House
		,--add for mantis: 32658
		NID.StartDate AS NextInstallmentStartDate
		,--Mantis -  Start 32760
		NID.EndDate AS NextInstallmentEndDate
		,NID.PendingAmount AS NextInstallmentAmount
		,--Mantis -  End 32760			
		ISNULL([sFee].[fFeeActualAmountSumGet](FR.SourceId), 0) AS FeeActualAmount
		,-- MantisId : 0032658
		ISNULL(SC.StudentContactNo, '') AS StudentContactNo
		,-- MantisId : 0032895
		--mantis Start - 0033973
		ISNULL(SC.PermanentStreetOne, '') AS PermanentStreetOne
		,ISNULL(SC.PermanentStreetTwo, '') AS PermanentStreetTwo
		,ISNULL(SC.PermanentStreetThree, '') AS PermanentStreetThree
		,
		--mantis End - 0033973
		--mantis Start - 0034206
		ISNull(SC.PermanentCountry, '') AS PermanentCountry
		,ISNull(SC.PermanentState, '') AS PermanentState
		,ISNull(SC.PermanentCity, '') AS PermanentCity
		,ISNull(SC.PermanentZipCode, '') AS PermanentZipCode
		,
		--mantis End - 0034206
		FS.StartDate
		,--mantis : 0034274
		FS.EndDate
		,--mantis : 0034274
		ISNull(CSM.Title, '') AS CasteCategory
		,--mantis : 0034588
		LM.Title AS Medium
		,--mantis : 0034588
		CASE 
			WHEN @rOrgGroupId = 1134
				OR @rOrgGroupId = 1742
				THEN ISNULL([sFee].[fPaidFeeAmountReceiptBookwiseGet](FR.SourceId, RBM.Id), 0)
			ELSE ISNULL([sFee].[fPaidFeeAmountReceiptBookwiseGet](FR.SourceId, 0), 0)
			END AS TotalPaidAmount
		,--mantis : 0034862
		ISNULL(SO.UIDNumber, '') AS UID
		,--Mantis - 35268
		ISNULL((
				SELECT TOP 1 BusRoute
				FROM [sFee].[fStudentWiseBusRoute](SA.StudentId, FR.OrgGroupBatchId)
				), '') AS BusRoute		,--Mantis - 35545
		ISNULL((
				SELECT TOP 1 PickupPoint
				FROM [sFee].[fStudentWiseBusRoute](SA.StudentId, FR.OrgGroupBatchId)
				), '') AS PickupPoint		,--Mantis - 35545
		--RR.RefundAmount AS RefundAmount		--mantis : 35909
		ISNULL((
				SELECT SUM(RefundAmount)
				FROM sFee.tReceiptRefund
				WHERE ReceiptId = FR.Id
				), 0) AS RefundAmount		,--mantis : 35909
		ISNULL(SF.FatherMail, '') AS FatherMail
		,--add for mantis : 0036283
		ISNULL(SF.MotherMail, '') AS MotherMail
		,--add for mantis : 0036283
		ISNULL(SF.FatherContactNo, '') AS FatherContactNo
		,--add for mantis : 0036283
		ISNULL(SF.MotherContactNo, '') AS MotherContactNo
		,--add for mantis : 0036283
		--ISNULL(FSCGM.Title,'') AS FeeSetupWiseCollectionGroupName --add for mantis : 37204
		STUFF((
				SELECT DISTINCT ', ' + ISNULL(CGM.Title, '')
				FROM sFee.tReceipt FR1
				INNER JOIN sfee.tReceiptDetail RD ON FR1.Id = RD.ReceiptId
					AND FR1.SourceTypeId = 2001
				INNER JOIN sFee.tFeeSetup FS ON FS.Id = RD.FeeSetupId
					AND FS.ReceiptBookId = FR1.ReceiptBookId
				INNER JOIN sFee.tCollectionGroupMaster CGM ON FS.CollectionGroupId = CGM.Id
					AND FR1.ReceiptBookId = CGM.ReceiptBookId
				INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId = FR1.SourceId
					AND SA.BatchId = FS.BatchId
					AND SA.AdmissionCategoryId = FS.AdmissionCategoryId
				WHERE FR1.Id = FR.Id
				FOR XML PATH('')
					,TYPE
				).value('.', 'NVARCHAR(MAX)'), 1, 2, '') AS FeeSetupWiseCollectionGroupName		,--Add for mantis : 0037204
		--,PT.ID AS PaymentGatewayID
		SO.GenderId
		,-- Add for mantis : 0038284
		ISNULL(OI.SchoolStamp, 0x) AS SchoolStamp
		,--Added by dhananjay for mantis : 39933
		(
			CASE 
				WHEN ISNULL(FR.PaymentTransactionId, 0) > 0
					THEN -- Navrachana
						'Online Generated'
				ELSE ISNULL([sHrm].[fEmployeeNameGet](EM.FirstName, EM.MiddleName, EM.LastName, OM.EmployeeNameFormatId), '')
				END
			) AS UserNameFormat
		,--Mantis - 404385
		ISNULL(OM.HomePage, '') AS Board --Mantis - 42048
		,ISNULL(SC.PresentStreetOne,'') AS LocalPresentStreetOne--mantis : 0043901
		,ISNULL(SC.PresentStreetTwo,'') AS LocalPresentStreetTwo--mantis : 0043901
		,ISNULL(SC.PresentStreetThree,'') AS LocalPresentStreetThree--mantis : 0043901,
		,CONVERT(Nvarchar(10),SA.OrgId) AS OrgIdText  --Mantis - 44201
		,CONVERT(Nvarchar(20),SA.StudentId) AS StudentIdText	--Mantis - 44201
		,ISNULL([sFee].[fStudentFeeSetupReceiptAmountGet](SA.AcademicId,FS.id),0) AS TotalAmountFeeSetWise --mantis : 0043901
	FROM sFee.tReceipt FR
	INNER JOIN sFee.tReceiptDetail FRD ON FR.Id = FRD.ReceiptId AND FR.SourceTypeId = 2001
	INNER JOIN sFee.tFeeSetup FS ON FRD.FeeSetupId = FS.Id
	INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id
	INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id = FM.FeeHeadId
	INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId = FR.SourceId
	INNER JOIN sStudent.tStudentCommunication SC ON SC.StudentId = SA.StudentId
	INNER JOIN sFinanceCommon.tPayTypeMaster PTM ON PTM.Id = FR.PayTypeId
	INNER JOIN sSetup.tDepartmentMaster DM ON SA.DepartmentId = DM.Id
	INNER JOIN sFee.tReceiptBookMaster RBM ON RBM.Id = FR.ReceiptBookId
	INNER JOIN sSetup.tBatchMaster BM ON BM.Id = FR.BatchId
	INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = DM.OrgId -- Changed Left to Inner join for optimization by Foram
	INNER JOIN sSetup.tOrgGroupMaster OGM ON OGM.Id = OM.OrgGroupId -- Mantis : 0029314
	INNER JOIN sSetup.tLanguageMaster LM ON LM.Id = OM.LanguageId --mantis : 0034588	
	LEFT JOIN sFee.tFeeAllocation FA ON FA.FeeSetupId = FS.Id AND FA.SourceId = SA.AcademicId
	LEFT JOIN sSecurity.tUser U ON U.Id = FR.CreatedUserId
	LEFT JOIN sSetup.tOrgImages OI ON OI.OrgId = OM.Id --Added by dhananjay for mantis : 39933
	LEFT JOIN sSetup.tOrganizationOtherDetail OOM ON OM.Id = OOM.OrgId
	LEFT JOIN sFee.tCollectionGroupMaster CGM ON CGM.Id = FR.CollectionGroupId
	LEFT JOIN sFee.tFeeInvoice FI ON FI.Id = FR.FeeInvoiceId
	LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId = SA.StudentId
	LEFT JOIN sHrm.tEmployeeImages EI ON EI.EmployeeId = U.SourceId AND U.SourceTypeId = 95
	--LEFT JOIN sOp.tPaymentTransaction PT ON PT.Id = FR.PaymentTransactionId
	LEFT JOIN (SELECT CollectionGroupName,StartDate,EndDate,PendingAmount,SourceId,SourceTypeId 
	FROM [sFee].[fNextInstallmentDetailsGet](@rReceiptBookId, @rReceiptId)) NID -- Mantis Start - 0031305
			ON NID.SourceId = FR.SourceId AND NID.SourceTypeId = FR.SourcetypeId -- Mantis End - 0031305
	LEFT JOIN sStudent.tStudentOther AS SO ON SO.StudentId = SA.StudentId
	LEFT JOIN sActivity.tHouseMaster HM ON HM.Id = SO.HouseId --add for mantis: 32658
	LEFT JOIN sCommon.tCastCategoryMaster CSM ON CSM.Id = SO.CastCategoryId --mantis : 0034588
	--LEFT JOIN sFee.tReceiptRefund RR ON RR.ReceiptId = FR.Id		--mantis : 35909
	LEFT JOIN sHrm.tEmployeeMaster EM ON EM.Id = U.SourceId AND U.SourceTypeId = 95 --Mantis - 40438
	WHERE (
			(FR.Id = @rReceiptId)
			OR (@rReceiptId = 0)
			)
		AND (
			(RBM.OrgGroupId = @rOrgGroupId)
			OR (@rOrgGroupId = 0)
			)
		AND (
			(FR.ReceiptBookId = @rReceiptBookId)
			OR (@rReceiptBookId = 0)
			)
		AND (
			(FR.ReceiptNumber >= @rFromReceiptNo)
			OR (@rFromReceiptNo = 0)
			)
		AND (
			(FR.ReceiptNumber <= @rToReceiptNo)
			OR (@rToReceiptNo = 0)
			)
		AND (
			(FR.BatchId = @rBatchId)
			OR (@rBatchId = 0)
			)
		AND (
			(BM.OrgId = @rOrgId)
			OR (@rOrgId = 0)
			)
		AND (
			(FR.ReceiptDate = @rReceiptDate)
			OR (ISNULL(@rReceiptDate, '') = '')
			)
		AND (
			(SA.ClassId = @rClassId)
			OR (@rClassId = 0)
			)
		AND (
			(SA.DivisionId = @rDivisionId)
			OR (@rDivisionId = 0)
			)
		AND (
			ISNULL(SA.OrgId, 0) IN (
				SELECT cast(item AS INT)
				FROM sCommon.fnsplit(@rOrgIds, ',')
				)
			OR @rOrgIds = ''
			)
		AND (
			(ISNULL(FR.ReceiptPrintGroupId, '') = @rReceiptPrintGroupId)
			OR (ISNULL(@rReceiptPrintGroupId, '') = '')
			)
		AND (
			(FS.AdmissionCategoryId = @rAdmissionCategoryId)
			OR (@rAdmissionCategoryId = 0)
			)
	ORDER BY FS.StartDate
		,FHM.OrderIndex
		,FM.OrderIndex ASC
END
	--BEGIN
	--SELECT
	-- CAST(0 AS bigint) AS ReceiptId,
	-- 0	AS ReceiptNumber,
	-- CAST('' AS date) AS ReceiptDate,
	-- CAST(0 AS bigint) AS AcademicId,
	-- ''	AS Name,
	--''	AS Code,
	-- 0	AS RollNo,
	--0	AS ClassId,
	--0	AS DivisionId,
	--''	AS ClassName,
	--''	AS DivisionName,
	--''	AS ClassDivision,
	--0	AS FeeHeadId,
	--''	AS FeeHead,
	--0	AS FeeId,
	--''	AS FeeName,
	--CAST(0.0 AS decimal(12,2)) AS PaidAmount,
	--CAST(0 AS tinyint) AS PayTypeId,
	--''	AS PayType,
	--''	AS ChequeNo,	
	--''	AS BankName,
	--''	AS Address1,
	--''	AS Address2,
	--''	AS FullTitle,
	--CAST(0.0 AS decimal(12,2)) AS TotalReceiptAmount,
	--CAST(0.0 AS decimal(12,2)) AS ReceiptAmount,					
	--''	AS ReceiptAmountInWords,		
	--CAST(0.0 AS decimal(12,2)) AS DiscountAmount,
	--''	AS Remark,
	--''	AS UserName,		
	--0x  AS OrgLogo,
	--''	AS Remark1,
	--''	AS Remark2,			 
	--CAST(0 AS bit) AS IsOnPrePrinted,
	--CAST(0 AS bit) AS IsSupressLogo,
	--CAST(0 AS bit) AS IsDisplaySchoolName,
	--0	AS ReportId,
	--''	AS OrganizationName,		  
	--''	AS MonthDetail,    			
	--''	AS FeeDuration,		
	--''	AS DepartmentName,
	-- 0	AS FeeOrderIndex,
	--CAST(0 AS smallint)	AS FeeHeadOrderIndex,
	--CAST(0 AS bit) AS IsCancelReceipt,
	--''	AS CurrencyCode,
	--''	AS CurrencyTitle,
	--''	AS Batch,
	--CAST('' AS date) AS ChequeDate,
	--CAST(0 AS bit) AS IsMonthDetailOnly,
	--CAST(0 AS bit) AS IsFeeInvoiceHeadwise,
	--''	AS GroupTitle,
	--CAST(0 AS bit) AS IsSuppressFeeDetail,
	--''	AS CollectionGroupName,
	--0	AS InvoiceNumber,
	--''	AS SUID,
	--CAST(0 AS tinyint) AS HeaderDisplayId,
	--0x  AS ReceiptBookHeader,
	--CAST(0.0 AS decimal(6,2)) AS ServiceTaxPercentage,
	--CAST(0.0 AS decimal(12,2)) AS AmountAfterDiscount,
	--CAST(0.0 AS decimal(5,2)) AS CGSTPercentage,
	--CAST(0.0 AS decimal(5,2)) AS SGSTPercentage,
	--CAST(0.0 AS decimal(12,2)) AS CGSTAmount,
	--CAST(0.0 AS decimal(12,2))	AS SGSTAmount,
	--''	AS GSTINNo,
	--''	AS HSNSACCode,
	--''	AS ItemValue ,
	--''	AS FatherName,
	--''	AS MotherName,
	--CAST(0.0 AS decimal(12,2)) AS ExemptionAmount,
	--''	AS ExemptionRemark,
	--0x AS EmployeeSign,
	--''	AS PresentCity,
	--''	AS PresentAdress,
	--''	AS ParentContactNo,	
	--CAST(0 AS bit) AS IsDisplayPendingFeeAmount,
	--CAST(0.0 AS decimal(12,0)) AS PendingFeeAmount,
	--''	AS FirstName,
	--''	AS LastName,
	--CAST(0.0 AS decimal(12,0))	AS FeeAmount,
	--CAST(0.0 AS decimal(12,0)) AS ExemptionAmountSum,
	--''	AS TransportBusRoute,
	--''	AS BankAccountNumber,
	--0	AS FeeHeadNumber,
	--0	AS FeeNumber,
	--0x AS DigitalSignature,
	--''	AS CancelStatusRemark,
	--CAST(0.0 AS decimal(12,2))	AS FeeSetupAmount,
	--CAST('' AS date)	AS CreatedDateTime ,
	--CAST(0 AS bigint)	AS PaymentTransactionId,
	--''	AS MiddleName,
	--'' AS CreatedTime,
	-- 0 AS TotalPayableAmount,
	-- '' AS OrgGroupTitle,
	-- '' AS NextInstallmentName,
	-- '' AS House,
	-- CAST('' AS date) AS NextInstallmentStartDate,
	-- CAST('' AS date) NextInstallmentEndDate,
	-- CAST(0.0 AS decimal(12,2)) AS NextInstallmentAmount,
	-- CAST(0.0 AS decimal(12,2)) AS FeeActualAmount,
	-- '' AS StudentContactNo,
	-- '' AS PermanentStreetOne,
	-- '' AS PermanentStreetTwo,
	-- '' AS PermanentStreetThree,
	--'' AS PermanentCountry,
	-- '' AS PermanentState,
	-- '' AS PermanentCity,
	-- '' AS PermanentZipCode,
	-- CAST('' AS date) AS StartDate,
	-- CAST('' AS date) AS EndDate,  
	--   '' AS CasteCategory,  
	--	   '' AS Medium,
	--CAST(0.0 AS decimal(12,0)) AS TotalPaidAmount,
	--''	AS UID,
	--'' AS BusRoute,
	--'' AS PickupPoint,
	-- CAST(0.0 AS decimal(12,2)) AS RefundAmount,
	--'' AS FatherMail,
	--'' AS MotherMail,
	--'' AS FatherContactNo,
	--'' AS MotherContactNo,
	--'' AS FeeSetupWiseCollectionGroupName,
	--'' AS GenderId,
	--'' AS UserNameFormat,
	--'' AS Board		--Mantis - 42048
	--,'' AS LocalPresentStreetOne
	--,'' AS LocalPresentStreetTwo
	--,'' AS LocalPresentStreetThree
	--Mantis Start - 44201
	--,'' AS OrgIdText	
	--,'' AS StudentIdText
	--Mantis End - 44201
	--,CAST(0.0 AS decimal(12,0)) AS TotalAmountFeeSetWise 
	--END
GO
PRINT N'Altering Procedure [sFee].[pRptFeeReportAllFeeWiseDetailsGet]...';


GO

ALTER PROCEDURE [sFee].[pRptFeeReportAllFeeWiseDetailsGet]    
	
	@rBuilder1 nvarchar(max) = '',  
	@rBuilder2 nvarchar(max) = '', 
	@rOrgGroupBatchId int,
	@rIsDisplayOrgGroup bit = 0,   
	@rAdmissionCategoryId int,    
	@rClassId int,    
	@rDivisionId int,    
	@rCode nvarchar(50)='',        
	@rFromReceiptNo int=0,    
	@rToReceiptNo int=0,    
	@rReceiptBookId int=0,        
	@rPayTypeId int,        
	@rFromDate date,    
	@rToDate date,    
	@rIsCancel bit,    
	@rOrgId smallint,    
	@rBatchId int,            
	@rDepartmentId int=0,           
	@rIsFilter bit = 0,
	@rCommonBatch nvarchar(100) = '',
	@rReportId int = 0,
	@rFromRollNo int = null,  
	@rToRollNo int = null,
    @rFilterId int = 0,
	@rOrgIds nvarchar(max) = ''
	,@rIsDetail bit=0

 WITH EXECUTE AS CALLER    
AS    
SET NOCOUNT ON    

BEGIN       
	
	DECLARE @rOrgGroupId INT
	SELECT @rOrgGroupId = OrgGroupId FROM ssetup.tOrgGroupBatchMaster WHERE Id = @rOrgGroupBatchId
	DECLARE @OrgIds TABLE (Id INT);
	INSERT INTO @OrgIds
	SELECT CAST(item AS INT) FROM sCommon.fnsplit(@rOrgIds, ',');

	DECLARE @AssignRouteStudentIds TABLE (SourceId BIGINT);
	INSERT INTO @AssignRouteStudentIds
	SELECT AT.SourceId
	FROM sTransport.tAssignRoute AT WITH (NOLOCK)
	INNER JOIN sTransport.tBusRouteDestinationMaster BM WITH (NOLOCK) ON BM.Id = AT.PickupDestinationId
	INNER JOIN sTransport.tBusRouteMaster B WITH (NOLOCK) ON B.Id = BM.BusRouteId
		AND AT.SourceTypeId = 2003
		AND ((B.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))

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

	BEGIN
		CREATE TABLE #ReceiptAmount
		(
			ReceiptId BigInt,
			FeeId Int,
			Amount Decimal(12, 2),
			VariableAmount Decimal(12, 2),
			ExemptionAmount Decimal(12, 2),
			AdditionalAmount Decimal(12, 2),
			NotApplicableAmount Decimal(12, 2)
		)
	END
	INSERT INTO #ReceiptAmount (ReceiptId, FeeId, Amount, VariableAmount, ExemptionAmount, AdditionalAmount, NotApplicableAmount)
		SELECT 	 
		R.Id AS ReceiptId, 
		FS.FeeId,
		RD.Amount,
		FA.VariableAmount,
		FA.DiscountAmount AS ExemptionAmount,
		FA.AdditionalAmount,
		FA.NotApplicableAmount
	FROM 
		sFee.tReceiptDetail RD
		INNER JOIN sFee.tReceipt R ON R.Id = RD.ReceiptId
		INNER JOIN sFee.tFeeSetup FS ON FS.Id = RD.FeeSetupId
		LEFT JOIN sFee.tFeeAllocation FA ON FA.FeeSetupId=FS.Id AND FA.SourceId=R.SourceId AND FA.SourceTypeId = R.SourceTypeId
	WHERE 
		(R.SourceTypeId=2001)     
		AND ((R.ReceiptNumber>=@rFromReceiptNo)OR(@rFromReceiptNo=0))    
		AND ((R.ReceiptNumber<=@rToReceiptNo)OR(@rToReceiptNo=0))    
		AND ((R.ReceiptBookId=@rReceiptBookId)OR(@rReceiptBookId=0))    
		AND ((R.PayTypeId=@rPayTypeId)OR(@rPayTypeId=0))         
		AND ((R.ReceiptDate>=@rFromDate)OR(ISNULL(@rFromDate,'')=''))    
		AND ((R.ReceiptDate<=@rToDate)OR(ISNULL(@rToDate,'')=''))    
		AND (R.IsObsolete=@rIsCancel) 
		AND ((FS.BatchId=@rBatchId) OR (@rBatchId=0))
		AND ((FS.ClassId=@rClassId) OR (@rClassId=0)) 

 SELECT 
	@rBuilder1 AS Builder1,
	@rBuilder2 AS Builder2,
    A.StatusId,    
	R.Id AS ReceiptId,
	ISNULL(RA.Amount,0) AS Amount,
	OM.DisplayTitle AS Organization,  
	BM.Title AS Batch,
	BM.Id AS BatchId,
	A.Code, 
	CM.Title +' - '+ DM.Title AS ClassDiv,
	A.Name,    
	R.ReceiptNumber,     
	CONVERT(VARCHAR(10), R.ReceiptDate, 103) AS ReceiptDate, 
	ISNULL(R.ReceiptAmount,0)AS ReceiptAmount,
	PTM.Title AS PayType,    
	ISNULL(NULLIF(R.ChequeNo, ''), CONVERT(NVARCHAR(20), R.PaymentTransactionId)) AS ChequeNo,    
	R.Remark,
	CONVERT(VARCHAR(10), R.ChequeDate, 103)AS ChequeDate,  
	ISNULL(FI.InvoiceNumber,0) AS InvoiceNumber,    
	R.CreatedDateTime AS ReceiptCreatedDateTime,
	R.BankName,    
	RBM.Title AS ReceiptBook,    
    ISNULL(R.TotalReceiptAmount,0)AS TotalReceiptAmount,    
    ISNULL(R.DiscountAmount,0)AS DiscountAmount,
	RA.VariableAmount,
	RA.ExemptionAmount,
	RA.AdditionalAmount,
	RA.NotApplicableAmount,
	ISNULL(A.SUId,'') As SUId,
	ISNULL(R.CancelDateTime,'')AS CancelDateTime,
	ISNULL(R.CancelStatusRemark,'')AS CancelRemark,
	FM.Id AS FeeId,
	FM.Code AS FeeCode,
	FM.Title AS FeeName,
	FM.OrderIndex AS FeeOrderIndex
	--start mantis : 0044420
	,FHM.Id AS FeeHeadId
	,FHM.Code AS FeeHeadCode
	,FHM.Title AS FeeHeadTitle
	,FHM.OrderIndex AS FeeHeadOrderIndex
	,@rIsDetail AS IsDetail
	--end : mantis : 0044420
FROM  
	sFee.tReceipt R
	INNER JOIN sStudent.vStudentAcademic A    
	ON A.AcademicId=R.SourceId AND (A.AdmissionCategoryId=@rAdmissionCategoryId OR @rAdmissionCategoryId=0)  
	INNER JOIN sFee.tFeeMaster FM ON FM.IsObsolete = 0 AND FM.OrgGroupId = @rOrgGroupId
	INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id = FM.FeeHeadId-- mantis : 0044420
	INNER JOIN  sSetup.tClassMaster CM ON CM.Id = A.ClassId     
	INNER JOIN  sSetup.tDivisionMaster DM ON DM.Id = A.DivisionId
	INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=A.OrgId   
	INNER JOIN sFinanceCommon.tPayTypeMaster PTM ON PTM.Id=R.PayTypeId    
	INNER JOIN sFee.tReceiptBookMaster RBM ON RBM.Id=R.ReceiptBookId
	INNER JOIN sSetup.tBatchMaster BM ON BM.Id=R.BatchId   
	LEFT JOIN sFee.tFeeInvoice FI ON FI.Id = R.FeeInvoiceId     
	LEFT JOIN sHostel.tAssignRoom AR ON  AR.SourceId=A.StudentId AND AR.SourceTypeId=2003
    LEFT JOIN  @AssignRouteStudentIds RT ON RT.SourceId = A.StudentId
	LEFT JOIN #ReceiptAmount RA ON RA.ReceiptId = R.Id AND RA.FeeId = FM.Id 	
WHERE     
	((A.Code like @rCode) OR (ISNULL(@rCode,'')=''))    
	AND (R.SourceTypeId=2001)     
	AND ((R.ReceiptNumber>=@rFromReceiptNo)OR(@rFromReceiptNo=0))    
	AND ((R.ReceiptNumber<=@rToReceiptNo)OR(@rToReceiptNo=0))    
	AND ((R.ReceiptBookId=@rReceiptBookId)OR(@rReceiptBookId=0))    
	AND ((R.PayTypeId=@rPayTypeId)OR(@rPayTypeId=0))         
	AND ((R.ReceiptDate>=@rFromDate)OR(ISNULL(@rFromDate,'')=''))    
	AND ((R.ReceiptDate<=@rToDate)OR(ISNULL(@rToDate,'')=''))    
	AND (R.IsObsolete=@rIsCancel)    
	AND ((A.OrgId=@rOrgId) OR (@rOrgId=0))    
	AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))       
	AND ((CM.DepartmentId = @rDepartmentId) OR (@rDepartmentId=0))    
	AND ((A.ClassId=@rClassId) OR (@rClassId=0))     
	AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId=0))
	AND ((A.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 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 (@rOrgIds = '' OR ISNULL(A.OrgId,0) IN (SELECT Id FROM @OrgIds))
	AND (A.AdmissionCategoryId=@rAdmissionCategoryId OR @rAdmissionCategoryId=0)
	AND FM.IsObsolete = 0
	AND FHM.IsObsolete = 0 -- mantis : 0044420
	             
 ORDER BY R.ReceiptNumber DESC   
  
END
GO
PRINT N'Altering Procedure [sHrm].[pLeaveBulkGet]...';


GO
 

ALTER PROCEDURE [sHrm].[pLeaveBulkGet]  
(  
	@rOrgId int,  
    @rEmployeeId  bigint,     
    @rFromDate date,   
    @rTodate date,  
    @rOrgGroupBatchId int,   
    @rOrgGroupId int,  
    @rDepartmentId int,
	@rStatusId int = 0
	 
 )  
AS  
SET NOCOUNT ON  

BEGIN
		SELECT 
		EM.EmployeeId,
		EMP.FirstName +' '+EMP.MiddleName+' '+EMP.LastName As EmployeeName,
		EMP.Code As EmployeeCode,
		EAR.AttendanceDate As LeaveDate,
		EAR.IsPresent
		
		FROM 
		sHrm.tEmployeeAttendanceRegister EAR
		INNER JOIN sSetup.tBatchMaster BM ON BM.Id = EAR.BatchId    
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = BM.OrgId  
		LEFT JOIN sHrm.tEmployeeMaster EMP ON EMP.Id = EAR.EmployeeId 
		INNER JOIN sHrm.vEmployeeCommonDetail EM ON EM.EmployeeId = EAR.EmployeeId   
		WHERE EAR.EmployeeId 
		NOT IN (SELECT EmployeeId FROM sHrm.tLeave WHERE Fromdate >=AttendanceDate AND TODATE <=AttendanceDate)
		--AND  AttendanceDate >=@rFromDate AND AttendanceDate <=@rToDate
		AND  ((AttendanceDate >=@rFromDate)  OR (ISNULL(@rFromDate,'')=''))
		AND ((AttendanceDate <=@rToDate)  OR (ISNULL(@rToDate,'')=''))
		and IsPresent=0
		AND ((EM.DepartmentId = @rDepartmentId ) OR (@rDepartmentId = 0))
		AND BM.OrgGroupBatchId = @rOrgGroupBatchId  
		AND ((EMP.OrgId = @rOrgId) OR (@rOrgId = 0)) 
		AND ((EMP.StatusId = @rStatusId) OR (@rStatusId = 0))
		--ORDER BY EMP.Code

END
GO
PRINT N'Altering Procedure [sRecruitment].[pRecruitmentDocumentGet]...';


GO
ALTER PROCEDURE [sRecruitment].[pRecruitmentDocumentGet]
	 
	@rVacancyId bigint,
	@rDocumentId int,
	@rOrgId int
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	
BEGIN 
WITH CombinedResults AS ( -- Changed for mantis : 35443 by Nilesh
	SELECT 
		RCD.VacancyId,RCD.SubmitDocumentMasterId AS DocumentId,SDM.DocumentName,ISNULL(RCD.Remark,'') AS Remark,ISNULL(RCD.IsMandatory,0) IsMandatory 
	FROM 
		sRecruitment.tRecruitmentCriteriaDocument RCD
		INNER JOIN sCommon.tSubmitDocumentMaster SDM ON SDM.Id = RCD.SubmitDocumentMasterId and SDM.OrgId=@rOrgId --mantis: 44743, change LEFT JOIN to INNER JOIN
	WHERE 
		(RCD.VacancyId = @rVacancyId OR ISNULL(@rVacancyId,0)=0)
		AND (RCD.SubmitDocumentMasterId = @rDocumentId OR ISNULL(@rDocumentId,0)=0)

		UNION
		SELECT 
		0 VacancyId,Id AS DocumentId,DocumentName,'' AS Remark,CAST('FALSE' as bit) IsMandatory
	FROM 
		sCommon.tSubmitDocumentMaster SDM		
		WHERE  SubmitDocumentFunctionalityId=4 AND ID NOT IN(SELECT SubmitDocumentMasterId FROM sRecruitment.tRecruitmentCriteriaDocument WHERE VacancyId = @rVacancyId )
		AND OrgId=@rOrgId
			)

	/******Added for mantis : 35443 by Nilesh******/
	SELECT 
	    VacancyId,
	    DocumentId,
	    DocumentName,
	    Remark,
	    IsMandatory
	FROM 
	    CombinedResults
	ORDER BY 
	    DocumentId ASC;

END
GO
PRINT N'Altering Procedure [sScholarship].[pScholarshipEligibleStudentAdd]...';


GO
ALTER PROCEDURE [sScholarship].[pScholarshipEligibleStudentAdd] 
    @rScholarshipId INT
	,@rAcademicId BIGINT
	,@rEligibleAmount DECIMAL(10, 2)
	,@rIsDeleted BIT
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
		BEGIN TRANSACTION

		-- For Delete sScholarship.tScholarshipStudentPaid
		IF (@rIsDeleted = 1)
		BEGIN
			IF EXISTS (
					SELECT 1
					FROM sScholarship.tScholarshipStudentPaid SSP
					INNER JOIN sScholarship.tScholarshipReceive SR ON SR.Id = SSP.ScholarshipReceiveId
						AND SR.ScholarshipId = @rScholarshipId
						AND SSP.AcademicId = @rAcademicId
						AND SSP.PaidAmount > 0
					)
			BEGIN
				SELECT - 101 AS Result

				COMMIT TRANSACTION

				RETURN
			END
			ELSE
			BEGIN
				DELETE
				FROM sScholarship.tScholarshipEligibleStudent
				WHERE ScholarshipId = @rScholarshipId
					AND AcademicId = @rAcademicId

				SELECT @rAcademicId AS Result
			END
		END
		ELSE
		BEGIN
			IF EXISTS (
					SELECT AcademicId
					FROM sScholarship.tScholarshipEligibleStudent
					WHERE AcademicId = @rAcademicId
						AND ScholarshipId = @rScholarshipId
					)
			BEGIN
				SELECT - 103 AS Result

				COMMIT TRANSACTION

				RETURN
			END

			INSERT INTO sScholarship.tScholarshipEligibleStudent (
				ScholarshipId
				,AcademicId
				,EligibleAmount
				)
			VALUES (
				@rScholarshipId
				,@rAcademicId
				,@rEligibleAmount
				)
		END

		SELECT @rAcademicId AS Result

		COMMIT TRANSACTION
	END TRY

	BEGIN CATCH
		ROLLBACK TRANSACTION

		SELECT - 1 AS Result
	END CATCH
END
GO
PRINT N'Altering Procedure [sScholarship].[pScholarshipStudentPaidAdd]...';


GO
ALTER PROCEDURE [sScholarship].[pScholarshipStudentPaidAdd] @rScholarshipReceiveId BIGINT
	,@rAcademicId BIGINT
	,@rPaidDate DATE
	,@rPaidAmount DECIMAL(10, 2)
	,@rChequeNumber NVARCHAR(20)
	,@rBankName NVARCHAR(20)
	,@rRemark NVARCHAR(200)
	,@rIsDeleted BIT
	,@rPayTypeId TINYINT = 0
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	-- FOR DELETE 
	IF (@rIsDeleted = 1)
	BEGIN
		DELETE
		FROM sScholarship.tScholarshipStudentPaid
		WHERE ScholarshipReceiveId = @rScholarshipReceiveId
			AND AcademicId = @rAcademicId

		SELECT @rScholarshipReceiveId AS Result
	END

	BEGIN
		BEGIN TRY
			IF EXISTS (
					SELECT 1
					FROM sScholarship.tScholarshipReceive
					WHERE ReceiveDate > @rPaidDate
						AND Id = @rScholarshipReceiveId
					)
			BEGIN
				SELECT - 101 AS Result

				RETURN
			END

			BEGIN TRANSACTION

			-- DATE VALIDATION
			
			--IF NOT EXISTS (SELECT 1 FROM sScholarship.tScholarshipStudentPaid WHERE AcademicId=@rAcademicId AND ScholarshipReceiveId=@rScholarshipReceiveId)
			--BEGIN
			--	IF EXISTS (SELECT 1 FROM sScholarship.tScholarshipReceive WHERE ReceiveDate > @rPaidDate AND Id=@rScholarshipReceiveId  )
			--	BEGIN
			--		SELECT -101 AS Result
			--		RETURN
			--	END
			--END 
			--ELSE
			--BEGIN
			--	IF EXISTS	(SELECT 1 FROM sScholarship.tScholarshipStudentPaid SSP INNER JOIN sScholarship.tScholarshipReceive SR ON SR.Id = SSP.ScholarshipReceiveId
			--					AND ScholarshipReceiveId=@rScholarshipReceiveId  AND SR.ReceiveDate > @rPaidDate)
			--	BEGIN
			--		SELECT -101 as Result
			--		RETURN
			--	END 
			--END 
			-- AMOUNT VALIDATIEON
			IF EXISTS (
					SELECT 1
					FROM sScholarship.tScholarshipStudentPaid
					WHERE AcademicId = @rAcademicId
						AND ScholarshipReceiveId = @rScholarshipReceiveId
					)
			BEGIN
				IF EXISTS (
						SELECT 1
						FROM sScholarship.tScholarshipReceive SR
						WHERE SR.Id = @rScholarshipReceiveId
							AND SR.TotalAmount < (
								SELECT ISNULL(SUM(SSP.PaidAmount), 0) + @rPaidAmount - (
										SELECT ISNULL(PaidAmount, 0)
										FROM sScholarship.tScholarshipStudentPaid
										WHERE AcademicId = @rAcademicId
											AND ScholarshipReceiveId = @rScholarshipReceiveId
										) AS TotalPaidAmount
								FROM sScholarship.tScholarshipStudentPaid SSP
								WHERE ScholarshipReceiveId = @rScholarshipReceiveId
								)
						)
				BEGIN
					SELECT - 102 AS Result

					RETURN
				END
			END
			ELSE
			BEGIN
				IF EXISTS (
						SELECT SR.TotalAmount
						FROM sScholarship.tScholarshipReceive SR
						WHERE SR.Id = @rScholarshipReceiveId
							AND SR.TotalAmount < (
								SELECT ISNULL(SUM(SSP.PaidAmount), 0) + @rPaidAmount AS TotalPaidAmount
								FROM sScholarship.tScholarshipStudentPaid SSP
								WHERE ScholarshipReceiveId = @rScholarshipReceiveId
								)
						)
				BEGIN
					SELECT - 102 AS Result

					RETURN
				END
			END

			IF NOT EXISTS (
					SELECT 1
					FROM sScholarship.tScholarshipStudentPaid
					WHERE AcademicId = @rAcademicId
						AND ScholarshipReceiveId = @rScholarshipReceiveId
					)
			BEGIN
				INSERT INTO sScholarship.tScholarshipStudentPaid (
					ScholarshipReceiveId
					,AcademicId
					,PaidDate
					,PaidAmount
					,ChequeNumber
					,BankName
					,Remark
					,PayTypeId
					)
				VALUES (
					@rScholarshipReceiveId
					,@rAcademicId
					,@rPaidDate
					,@rPaidAmount
					,@rChequeNumber
					,@rBankName
					,@rRemark
					,@rPayTypeId
					)
			END
			ELSE
			BEGIN
				UPDATE sScholarship.tScholarshipStudentPaid
				SET PaidDate = @rPaidDate
					,PaidAmount = @rPaidAmount
					,ChequeNumber = @rChequeNumber
					,BankName = @rBankName
					,Remark = @rRemark
					,PayTypeId = @rPayTypeId
				WHERE ScholarshipReceiveId = @rScholarshipReceiveId
					AND AcademicId = @rAcademicId
			END

			SELECT @rAcademicId AS Result

			COMMIT TRANSACTION
		END TRY

		BEGIN CATCH
			ROLLBACK TRANSACTION

			SELECT - 1 AS Result
		END CATCH
	END
END
GO
PRINT N'Altering Procedure [sSecurity].[pDashletGet]...';


GO
ALTER PROCEDURE [sSecurity].[pDashletGet]
	@rOrgGroupId int=0,
	@rDate date='',
	@rDashletId int=0,
	@rOrgGroupBatchId int=0,
	@rUserId bigint=0,
	@rUserSourceId bigint=0,
	@rUserSourceTypeId int=0,
	@rOrgId Int=0,
	@rSourceTypeId smallint=0,
	@rSourceId bigint=0,
	@rBatchId int=0,
	@rExamId int=0,
	@rStatusId int =0


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

			AND CONVERT(VARCHAR(5),EM.DateOfBirth,110) <= CONVERT(VARCHAR(5),@TimeZoneDate+@BirthdayDays,110)
			AND CONVERT(VARCHAR(5),EM.DateOfBirth,110) >= CONVERT(VARCHAR(5),@TimeZoneDate,110)
			AND EM.DateOfBirth!='' AND EM.StatusId=7
		ORDER BY CONVERT(VARCHAR(5),EM.DateOfBirth,110)
	END
	if(@rDashletId='7')
	BEGIN
		SELECT SC.FirstName + ' ' + SC.MiddleName + ' ' + SC.LastName AS Name, SC.ClassName+' '+SC.DivisionName AS ClassName FROM sStudent.vStudentAllDetail SC
		WHERE SC.OrgId=@rOrgId AND SC.BatchId=@rBatchId
			AND (MONTH(SC.DateOfBirth) = CAST(MONTH(@TimeZoneDate) AS varchar(2))) AND SC.DateOfBirth!='' AND SC.StatusId=1
			AND (DAY(SC.DateOfBirth) = CAST(DAY(@TimeZoneDate) AS varchar(2)))
	END
	if(@rDashletId='10')
	BEGIN
		exec sAttendance.pDashletAttendanceStatusGet @rAcademicId=@rSourceId
	END

	if(@rDashletId='11')
	BEGIN
		SELECT EM.EmployeeName,L.FromDate,L.ToDate
		FROM  sHrm.tLeave L
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = L.BatchId
			INNER JOIN sHrm.vEmployeeCommonDetail EM ON EM.EmployeeId = L.EmployeeId
			INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = L.EmployeeId
		WHERE BM.OrgGroupBatchId = @rOrgGroupBatchId
			AND L.OrgId = @rOrgId
			AND (EJD.EmployeeManagerId = @rUserSourceId OR @rUserSourceId = 0)
			--AND ((L.FromDate >= @rDate) OR (ISNULL(@rDate,'') = '')) --comment for Mantis Id: 0030464
			AND EM.EmployeeStatusId=7
			AND L.StatusId = 549
		--exec [sHrm].[pLeaveListingGet] @rOrgId=@rOrgId,@rEmployeeId=@rUserSourceId,@rLeaveTypeId=0,@rOrgGroupBatchId=@rOrgGroupBatchId,@rFromDate=@rDate,@rTodate=''
	END
	if(@rDashletId='12')
	BEGIN
		exec sCommunication.pPollGet @rOrgGroupBatchId=@rOrgGroupBatchId,@rSourceTypeId=@rUserSourceTypeId,@rCreatedUserId=@rUserId,@rCreatedDateTime=@rDate
	END
	if(@rDashletId='14')
	BEGIN
		exec sCommunication.pMyBookGet @rReaderSourceTypeId=@rUserSourceTypeId,@rReaderSourceId=@rUserSourceId,@rBatchId=@rBatchId,@rStatusId=@rStatusId
	END
	if(@rDashletId='16')
	BEGIN
		exec [sFee].[pRptFeeReceiptTotalGet] @rFromDate=@rDate,@rToDate=@rDate,@rOrgGroupBatchId=@rOrgGroupBatchId
	END

	if(@rDashletId='17')
	BEGIN
		exec [sFee].[pFeeDueAlertGet] @rSourceId=@rSourceId,@rSourceTypeId=@rSourceTypeId,@rBatchId=@rBatchId
	END
	if(@rDashletId='18')
	BEGIN
		exec sCommunication.pBlogGet @rId=0,@rOrgGroupBatchId=@rOrgGroupBatchId,@rTitle=NULL,@rCreatedUserId=0,@rOrgId=@rOrgId,@rCreatedDateTime=@rDate
	END
	if(@rDashletId='19')
	BEGIN
		exec sAssessment.pStudentResultGet @rAcademicId=@rSourceId,@rStudentId=@rUserSourceId,@rBatchId=@rBatchId,@rExamId=@rExamId
	END
	if(@rDashletId='21')
	BEGIN
		SELECT vCD.ClassDivisionName,ISNULL(EM.FirstName+' '+ EM.LastName,'') AS ClassTeacherName, CASE WHEN COUNT(SR.AcademicId)=0 THEN CASE WHEN (Select [sCommon].[fCountAbsentStudent](A.DivisionId,  @rBatchId,@rDate,1,0)) =0 THEN 'Pending' ELSE 'Complete' END ELSE 'Complete' END AS PresentStatus
		FROM sStudent.tAcademic A
			INNER JOIN sSetup.vClassDivision vCD ON vCD.ClassId=A.ClassId AND vCD.DivisionId=A.DivisionId AND A.OrgId=vCD.OrgId AND A.OrgId=@rOrgId  AND A.BatchId=@rBatchId AND vCD.IsObsolete=0
			INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = vCD.DivisionId
			LEFT JOIN sHrm.tEmployeeMaster EM ON EM.Id = DM.InchargeEmployeeId
			LEFT JOIN sAttendance.tStudentRegister SR ON A.Id = SR.AcademicId AND SR.AttendanceTypeId = 1 AND SR.IsPresent=1 AND SR.AttendanceDate=@rDate
		GROUP BY A.DivisionId,A.BatchId,vCD.ClassDivisionName,vCD.OrderIndex,EM.FirstName,EM.LastName
		ORDER BY vCD.OrderIndex
	END
	if(@rDashletId='22')
	BEGIN
		SELECT VL.Id,VL.VisitorName, VL.NoOfVisitor,  (isnull(case when isnull(VL.WhomToMeet,0)!=0 then isnull(EM.EmployeeName,'') else ISNULL(VL.WhomToMeetName,'') end,'' )) AS WhomToMeetName
		FROM sFrontOffice.tVisitorLog VL
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=VL.OrgId
			LEFT JOIN sHrm.vExtEmployeeMaster EM ON EM.EmployeeId=VL.WhomToMeet
		WHERE VL.OrgId=@rOrgId AND VL.VisitDate=@rDate
		ORDER BY VL.VisitDate DESC,VL.InTime DESC
	END
	if(@rDashletId='23')
	BEGIN
		SELECT DispatchedTo, DispatchedCity  FROM sFrontOffice.tCourierDispatch  WHERE OrgGroupId=@rOrgGroupId AND DispatchDate=@rDate  AND @rDashletId='23' ORDER BY DispatchDate
	END
	if(@rDashletId='24')
	BEGIN
		SELECT ReceiveFrom, ReceiveFor  FROM  sFrontOffice.tCourierReceive  WHERE OrgGroupId=@rOrgGroupId  AND ReceiveDate=@rDate  AND @rDashletId='24' ORDER BY ReceiveDate
	END
	if(@rDashletId='25')
	BEGIN
		SELECT ISNULL(Ps.LectureNumber,'') AS LactureNumber,PS.EmployeeId,ISNULL(SMT.Title,'') AS Subject,ISNULL(EM1.FirstName,'') + ' '+ISNULL(EM1.LastName,'') AS EmployeeName,ISNULL(Em.FirstName,'') + ' '+ISNULL(Em.LastName,'') AS ProxyEmployeeName, ISNULL(DV
.Code,'') AS ClassDivisionName,ISNULL(SM.Title,'') AS ProxySubject
		from sTimetable.tProxySetting PS
			INNER JOIN sSetup.tSubjectMaster SM ON SM.Id = PS.SubjectId
			INNER JOIN sCommon.tDayMaster DM ON DM.Id = PS.DayId
			INNER JOIN sSetup.tDivisionMaster DV ON DV.Id = PS.DivisionId
			INNER JOIN sTimetable.tTimeTable TT ON TT.Id=PS.TimeTableId
			INNER JOIN sSetup.tSubjectMaster SMT ON SMT.Id = TT.SubjectId
			INNER JOIN sHrm.tEmployeeMaster EM1  ON TT.EmployeeId=EM1.Id
			INNER JOIN sHrm.tEmployeeMaster Em ON Em.Id = PS.EmployeeId
		WHERE PS.ProxyDate=@rDate AND PS.BatchId=@rBatchId AND ((PS.EmployeeId=@rSourceId) OR (@rSourceId=0))
		ORDER BY PS.ProxyDate
	END

	if(@rDashletId='27')
	BEGIN
		--Asset Check
		SELECT LM.Title AS LocationName, AM.Code AS AssetCode, AM.Title AS AssetName, CONVERT(nvarchar(12),AM.CheckedLastDate,103) AS CheckedLastDate
		FROM sAssetManagement.tAssetMaster AM
			INNER JOIN sAssetManagement.tAssetInchargeUser AU ON AM.Id = AU.AssetId
			INNER JOIN sFixedAsset.tLocationMaster LM ON LM.Id = AM.LocationId
		WHERE ISNULL(AM.IsCheckRequired,0) = 1 AND (AM.CheckFrequencyId=1 AND AM.CheckedLastDate <=  DATEADD(dd,1,@TimeZoneDate) OR AM.CheckFrequencyId=2 AND AM.CheckedLastDate <=  DATEADD(dd,7,@TimeZoneDate) OR AM.CheckFrequencyId=3 AND AM.CheckedLastDate <= DATEADD(dd,30,@TimeZoneDate)) AND AU.InchargeUserId =   @rUserId AND AM.OrgGroupId = @rOrgGroupId



		--SELECT LM.Title AS LocationName, AM.Code AS AssetCode, AM.Title AS AssetName,CONVERT(nvarchar(12),
		--AM.LastMaintenanceDate,103) AS LastMaintenanceDate,CONVERT(nvarchar(12),AM.NextMaintenanceDate,103) AS NextMaintenanceDate
		--FROM sAssetManagement.tAssetMaster AM
		--INNER JOIN sAssetManagement.tAssetInchargeUser AU ON AM.Id = AU.AssetId
		--INNER JOIN sFixedAsset.tLocationMaster LM ON LM.Id = AM.LocationId
		-- WHERE AU.InchargeUserId = @rUserId AND AM.OrgGroupId = @rOrgGroupId
	END
	if(@rDashletId='28')
	BEGIN
		--Asset maintenance
		SELECT LM.Title AS LocationName, AM.Code AS AssetCode, AM.Title AS AssetName,CONVERT(nvarchar(12),AM.LastMaintenanceDate,103) AS LastMaintenanceDate,CONVERT(nvarchar(12),AM.NextMaintenanceDate,103) AS NextMaintenanceDate
		FROM sAssetManagement.tAssetMaster AM
			INNER JOIN sAssetManagement.tAssetInchargeUser AU ON AM.Id = AU.AssetId
			INNER JOIN sFixedAsset.tLocationMaster LM ON LM.Id = AM.LocationId
		WHERE AU.InchargeUserId = @rUserId AND AM.OrgGroupId = @rOrgGroupId
	END
	if(@rDashletId='29')
	BEGIN
		--Asset Renew
		SELECT LM.Title AS LocationName, AM.Code AS AssetCode, AM.Title AS AssetName, CONVERT(nvarchar(12),AM.RenewLastDate,103) AS RenewLastDate, CONVERT(nvarchar(12),AM.RenewNextDate,103) AS RenewNextDate
		FROM sAssetManagement.tAssetMaster AM
			INNER JOIN sAssetManagement.tAssetInchargeUser AU ON AM.Id = AU.AssetId
			INNER JOIN sFixedAsset.tLocationMaster LM ON LM.Id = AM.LocationId
		WHERE ISNULL(AM.IsRenewRequired,0) = 1
			--AND AM.RenewNextDate >= DATEADD(dd,ISNULL(AM.RenewAlertBeforeDays,0),AM.RenewLastDate)
			AND convert(Date,@TimeZoneDate) >=  DATEADD(dd,-ISNULL(AM.RenewAlertBeforeDays,0), AM.RenewNextDate)
			AND AU.InchargeUserId =  @rUserId
			AND AM.OrgGroupId = @rOrgGroupId
	END
	--Inward
	IF(@rDashletId='30')
	BEGIN
		DECLARE @InwardRegisterGrid VARCHAR(max)=''
		SELECT  @InwardRegisterGrid = @InwardRegisterGrid + '<tr>
	       <td align="left" scope="col">' + ISNULL(LetterNumber,'') + '</td>
	       <td align="left" scope="col">' + ISNULL(LetterSubject,'') + '</td>
	       <td align="left" scope="col">' + ISNULL(LetterFrom,'') + '</td>
	       <td align="left" scope="col">' + convert(varchar,isnull(ReceivedDate,'01/01/0001'),103) + '</td>
	 	</tr>'
		FROM sFrontOffice.tInwardRegister
		WHERE IsReplyRequired=1 AND IsReplied=0 AND OrgId=@rOrgId AND ReceivedDate<=convert(Date,@TimeZoneDate)
		Order by ReceivedDate Desc

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

		SELECT Isnull(@OutwardRegisterGrid,'') As	OutwardRegisterGrid
	END

	IF(@rDashletId='32')
	BEGIN
		DECLARE @ReorderQuantityGrid VARCHAR(max)=''
		SELECT   @ReorderQuantityGrid=@ReorderQuantityGrid+'<tr>
			<td align="left" scope="col">' + ISNULL(SE.Title,'')  + '</td>
			<td align="left" scope="col">' +ISNULL(SM.Title,'')  + '</td>
			<td align="left" scope="col">' +convert(varchar,ISNULL(SUM(SB.AvailableQuantity),0))+ '</td>
			<td align="left" scope="col">' + convert(varchar,isnull(SP.ReOrderQuantity,0)) + '</td>
		</tr>'
		FROM sProcurement.tStockBatch SB
			INNER JOIN sIp.tStockItemMaster SM ON SM.Id=SB.STockItemID
			INNER JOIN sIp.tStoreLocationMaster SE ON SE.Id=SB.StoreLocationId
			INNER JOIN sIp.tStockItemPlanning SP ON SP.STockItemID=SM.Id AND SP.StoreLocationId =SE.Id
			--INNER JOIN  sSecurity.tUserLocation UL ON UL.StoreLocationId = SB.StoreLocationId
		WHERE SM.OrgGroupId=@rOrgGroupId AND SM.IsObsolete=0
		group by SE.Title,SM.Title,SP.ReOrderQuantity,SP.ReOrderPoint
		HAVING SUM(SB.AvailableQuantity) < SP.ReOrderPoint

		SELECT Isnull(@ReorderQuantityGrid,'') As	ReorderQuantityGrid
	END

	IF(@rDashletId='33')
	BEGIN
		DECLARE @SafetyStockGrid VARCHAR(max)=''
		SELECT   @SafetyStockGrid=@SafetyStockGrid+'<tr>
			<td align="left" scope="col">' + ISNULL(SE.Title,'')  + '</td>
			<td align="left" scope="col">' +ISNULL(SM.Title,'')  + '</td>
			<td align="left" scope="col">' +convert(varchar,ISNULL(SUM(SB.AvailableQuantity),0))+ '</td>
			<td align="left" scope="col">' + convert(varchar,isnull(SP.SafetyStock,0)) + '</td>
		</tr>'
		FROM sProcurement.tStockBatch SB
			INNER JOIN sIp.tStockItemMaster SM ON SM.Id=SB.STockItemID
			INNER JOIN sIp.tStoreLocationMaster SE ON SE.Id=SB.StoreLocationId
			INNER JOIN sIp.tStockItemPlanning SP ON SP.STockItemID=SM.Id AND SP.StoreLocationId =SE.Id
			--INNER JOIN  sSecurity.tUserLocation UL ON UL.StoreLocationId = SB.StoreLocationId
		WHERE  SM.OrgGroupId=@rOrgGroupId AND SM.IsObsolete=0
		group by SE.Title,SM.Title,SP.SafetyStock,SP.ReOrderPoint
		HAVING SUM(SB.AvailableQuantity) < SP.SafetyStock

		SELECT Isnull(@SafetyStockGrid,'') As	SafetyStockGrid
	END
	IF(@rDashletId='34')
	BEGIN
		DECLARE @Increment varchar(max)=''
		SELECT @Increment=@Increment+'<tr>
			<td align="left" scope="col">' + ISNULL(EM.FirstName,'') + ' '+ISNULL(EM.LastName,'') + '</td>
			<td align="left" scope="col">' +convert(varchar,isnull(IncrementDate,'01/01/0001'),103)  + '</td>
		</tr>'
		FROM sHrm.tEmployeeStatutoryAndOther SA INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id=SA.EmployeeId
		WHERE IncrementDate BETWEEN GETDATE()-1 AND GETDATE()+7 AND EM.OrgID=@rOrgId And EM.StatusId=7
		SELECT Isnull(@Increment, '') As IncrementGrid
	END

	IF(@rDashletId='78')
	BEGIN
		DECLARE @Retirement varchar(max)=''
		SELECT @Retirement=@Retirement+'<tr>
			<td align="left" scope="col">' + ISNULL(EM.FirstName,'') + ' '+ISNULL(EM.LastName,'') + '</td>
			<td align="left" scope="col">' +convert(varchar,isnull(RetirementDate,'01/01/0001'),103)  + '</td>
		</tr>'
		FROM sHrm.tEmployeeStatutoryAndOther SA INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id=SA.EmployeeId
		WHERE RetirementDate BETWEEN GETDATE()-1 AND GETDATE()+30 AND EM.OrgID=@rOrgId And EM.StatusId=7
		SELECT Isnull(@Retirement, '') As RetirementGrid
	END

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

	IF(@rDashletId='85')
	BEGIN
		SELECT
			AF.Id,
			AF.AdmissionInquiryId,
			ISNULL(AF.FollowupDate,'') AS  FollowupDate,
			AF.FollowupRemark,
			AI.LastName +' ' +AI.FirstName+' '+AI.MiddleName as Name,
			AI.Number AS InquiryNumber
		FROM
			sAdmission.tAdmissionInquiryFollowup AF
			INNER JOIN sAdmission.tAdmissionInquiry AI ON AI.Id=AF.AdmissionInquiryId
			INNER JOIN sSetup.tBatchMaster BM ON AI.ForBatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=AI.OrgId
		WHERE ((AF.FollowupDate < @rDate) OR (ISNULL(@rDate,'')=''))
			AND ((AI.OrgId=@rOrgId) OR (@rOrgId=0))
			AND ((BM.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
		Order by AF.FollowupDate DESC
	END

	IF(@rDashletId='86')
	BEGIN
		SELECT
			AF.Id,
			AF.AdmissionInquiryId,
			ISNULL(AF.FollowupDate,'') AS  FollowupDate,
			AF.FollowupRemark,
			AI.LastName +' ' +AI.FirstName+' '+AI.MiddleName as Name,
			AI.Number AS InquiryNumber
		FROM
			sAdmission.tAdmissionInquiryFollowup AF
			INNER JOIN sAdmission.tAdmissionInquiry AI ON AI.Id=AF.AdmissionInquiryId
			INNER JOIN sSetup.tBatchMaster BM ON AI.ForBatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=AI.OrgId
		WHERE ((AF.FollowupDate = @rDate) OR (ISNULL(@rDate,'')=''))
			AND ((AI.OrgId=@rOrgId) OR (@rOrgId=0))
			AND ((BM.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
		Order by AF.FollowupDate DESC
	END

	IF(@rDashletId='87')
	BEGIN
		Declare @lOrgGroupBatchId int=0
		select @lOrgGroupBatchId=OrgGroupBatchId from sSetup.tBatchMaster where Id=@rBatchId
		SELECT Distinct
			PDP.Id
			,ISNULL(SA.Code, '') AS IdNo
			,ISNULL(SA.Name, '') AS StudentName
			,PDP.Amount AS ReceiptAmount
			,PDP.ChequeNo
			,PDP.PaymentClearanceDate
		FROM
			sFee.tPostDatePayment PDP
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = PDP.OrgId
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = PDP.BatchId
			INNER JOIN [sStudent].[vStudentAcademic] SA ON SA.AcademicId = PDP.SourceId AND PDP.SourceTypeId = 2001
		--Mantis: 40861, comment the below where condition and add new where condition
		--WHERE  (PDP.OrgId = @rOrgId OR @rOrgId = 0)
		--	AND (PDP.BatchId = @rBatchId OR @rBatchId = 0)
		--	AND (PDP.PaymentClearanceDate <= @rDate OR ISNULL(@rDate, '') = '')
		--	AND PDP.StatusId = 751
		WHERE (PDP.OrgGroupBatchId = @lOrgGroupBatchId OR @lOrgGroupBatchId = 0)
			AND (PDP.PaymentClearanceDate <= @rDate OR ISNULL(@rDate, '') = '')
			AND PDP.StatusId = 751
		ORDER BY PDP.PaymentClearanceDate DESC
	END

--Added by dhananjay for mantis : 41224
	IF(@rDashletId='88')
	BEGIN
		DECLARE @lForDate nvarchar(20), @Query nvarchar(max)
 
		Set @lForDate = Right('0'+(convert(nvarchar(2),(Day(@rDate)))),2)
 
		SET @Query='SELECT EM.Id as EmployeeId,  ISNULL(EM.FirstName, '''') + '' '' + ISNULL(EM.LastName, '''') AS EmpName, 
			isnull(cast(rtrim(YEAR(MT.attn_dt) *10000+ Month(MT.attn_dt) *100+ '+@lForDate+') as datetime),
			cast(rtrim(YEAR('''+convert(nvarchar(max),@rDate)+''') *10000+ Month('''+convert(nvarchar(max),@rDate)+''') *100+ '+@lForDate+') as datetime)),
			D'+@lForDate+',ISNULL(D'+@lForDate+'_IN,''00:00'') as FirstIn,ISNULL(D'+@lForDate+'_OUT,''00:00'') as LastOut,
			D'+@lForDate+'_O,D'+@lForDate+'_L,D'+@lForDate+'_T,D'+@lForDate+'_E,D'+@lForDate+'_S 
			FROM sHRM.tEmployeeMaster EM
				INNER JOIN sHrm.tEmployeeJobDetail EJD ON EM.Id=EJD.EmployeeId
				LEFT JOIN sBiometric.tMonthTrans MT ON EM.Id=MT.EmployeeId 
						AND MT.ATTN_DT = cast(rtrim(YEAR('''+convert(nvarchar(max),@rDate)+''') *10000+ Month('''+convert(nvarchar(max),@rDate)+''') *100+ 01) as datetime)
			WHERE (EM.Id = '+convert(nvarchar(max),@rSourceId)+' OR '+convert(nvarchar(max),@rSourceId)+' = 0)
			AND EM.OrgId = '+convert(nvarchar(max),@rOrgId)+'
			AND (EJD.DateOfJoining<= '''+convert(nvarchar(max),@rDate)+''')
			AND (EJD.DateOfleaving>= '''+convert(nvarchar(max),@rDate)+''' OR ISNULL(EJD.DateOfleaving,'''')='''')
			AND (ISNULL(MT.SourceTypeId,95) = 95 OR MT.SourceTypeId = 0)
			AND EM.StatusId=7'
 
		EXEC(@Query)
	END
	--Added by dhananjay for mantis : 41224
END
GO
PRINT N'Altering Procedure [sSecurity].[pMenu_Migration]...';


GO



ALTER PROCEDURE [sSecurity].[pMenu_Migration]
 @rUserId [bigint],
 @rMenuId int = 0,
 @rResourceTypeId int= 0,
 @rIsCoreMenu bit = 0,
 @rEnvironmentName nvarchar(max) ,
 @rScreenGroupId int = 0

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
 IF(@rIsCoreMenu=0)
 BEGIN
 IF EXISTS(SELECT 1 FROM sSecurity.tPermissionUser WHERE UserId = @rUserId)
  BEGIN
   SELECT
    MenuID,
    ModuleId,
    ParentMenuID,
    MenuTitle,
    ScreenTitle,
    PageURL,
    ScreenId,
    Permission,
    OrderNumber,
    TaskId,
    PageURL  AS PagePath,
    IconPath

   FROM
     (SELECT Menu.Id AS MenuID,
    ISNULL(Menu.ParentMenuID, 0) AS ParentMenuID,
    Menu.Title AS MenuTitle,
    ISNULL(Screen.Title, '') AS ScreenTitle,
    ISNULL(Screen.Page, '') AS PageURL,
    ISNULL(Screen.ScreenGroupId,0) AS ScreenGroupId,
    ISNULL(Menu.ScreenId, 0) AS ScreenId,
    ISNULL(PermissionValue, 0) AS Permission,
    ISNULL(OrderNumber, 0) AS OrderNumber,
    ISNULL(Screen.TaskId,0) AS TaskId,
    ISNULL(Screen.IconPath,'') As IconPath,
    ISNULL(T.ResourceTypeId,0) AS ResourceTypeId,
    ISNULL(T.ModuleId,0) AS ModuleId


   FROM sSecurity.tMenu Menu
   LEFT OUTER JOIN sSecurity.tScreen Screen
    ON Menu.ScreenId = Screen.Id
   LEFT OUTER JOIN (
       SELECT
        TaskId,
        SUM(Permission & 2) PermissionValue
       FROM
        sSecurity.tPermissionUser P
        INNER JOIN sSecurity.tTask T ON T.Id = P.TaskId
        --INNER JOIN sSecuirty.tOrganizationTask OT ON OT.TaskId = T.Id AND OT.OrgGroupId = P.OrgGroupId
        INNER JOIN sSecurity.tModulePermission MP ON MP.ModuleId = T.ModuleId AND MP.OrgGroupId = P.OrgGroupId
       WHERE
        T.IsObsolete = 0 AND P.UserId = @rUserId
       GROUP BY
        TaskId) TBL2
       ON
        Screen.TaskId = TBL2.TaskId
         LEFT OUTER JOIN sSecurity.tTask  T ON T.Id =  Screen.TaskId AND ResourceTypeId = @rResourceTypeId

       WHERE
       (Menu.IsObsolete = 0)  --For ScreenGroupId Master Page
       AND ISNULL(Screen.IsObsolete, 0) = 0)
       MenuTable
       --INNER JOIN sSecurity.tTask  T ON T.Id =  MenuTable.TaskId
   WHERE
    MenuTable.ScreenId = 0 OR MenuTable.Permission >= 2
    AND
    ((MenuTable.ResourceTypeId = @rResourceTypeId) OR (@rResourceTypeId = 0))
    AND ((MenuTable.MenuID = @rMenuID)OR(@rMenuID = 0))

   ORDER BY
    ParentMenuID
  END
 ELSE
  BEGIN
   SELECT
    MenuID,
    ModuleId,
    ParentMenuID,
    MenuTitle,
    ScreenTitle,
    PageURL,
    ScreenId,
    Permission,
    OrderNumber,
    TaskId,
     PageURL  AS PagePath,
     IconPath

   FROM
     (SELECT Menu.Id AS MenuID,
    ISNULL(Menu.ParentMenuID, 0) AS ParentMenuID,
    Menu.Title AS MenuTitle,
    ISNULL(Screen.Title, '') AS ScreenTitle,
    ISNULL(Screen.Page, '') AS PageURL,
    ISNULL(Screen.ScreenGroupId,0) AS ScreenGroupId,
    ISNULL(Menu.ScreenId, 0) AS ScreenId,
    ISNULL(PermissionValue, 0) AS Permission,
    ISNULL(OrderNumber, 0) AS OrderNumber,
    ISNULL(Screen.TaskId,0) AS TaskId,
    ISNULL(Screen.IconPath,'') As IconPath,
    ISNULL(T.ResourceTypeId,0) AS ResourceTypeId,
    ISNULL(T.ModuleId,0) AS ModuleId


   FROM sSecurity.tMenu Menu
   LEFT OUTER JOIN sSecurity.tScreen Screen
    ON Menu.ScreenId = Screen.Id
   LEFT OUTER JOIN (
       SELECT
        TaskId,
        SUM(Permission & 2) PermissionValue
       FROM
        sSecurity.tPermission P
        INNER JOIN sSecurity.tTask T ON T.Id = P.TaskId
        --INNER JOIN sSecuirty.tOrganizationTask OT ON OT.TaskId = T.Id AND OT.OrgGroupId = P.OrgGroupId
        INNER JOIN sSecurity.tModulePermission MP ON MP.ModuleId = T.ModuleId AND MP.OrgGroupId = P.OrgGroupId
        INNER JOIN
        (
        SELECT RoleId FROM sSecurity.tUserRole UR WHERE  UserId = @rUserId AND IsObsolete = 0
        ) B ON B.RoleId = P.RoleId
       WHERE
        T.IsObsolete = 0
       GROUP BY
        TaskId) TBL2
       ON
        Screen.TaskId = TBL2.TaskId
         LEFT OUTER JOIN sSecurity.tTask  T ON T.Id =  Screen.TaskId AND ResourceTypeId = @rResourceTypeId

       WHERE
       (Menu.IsObsolete = 0)  --For ScreenGroupId Master Page
       AND ISNULL(Screen.IsObsolete, 0) = 0)
       MenuTable
       --INNER JOIN sSecurity.tTask  T ON T.Id =  MenuTable.TaskId
   WHERE
    MenuTable.ScreenId = 0 OR MenuTable.Permission >= 2
    AND
    ((MenuTable.ResourceTypeId = @rResourceTypeId) OR (@rResourceTypeId = 0))
    AND ((MenuTable.MenuID = @rMenuID)OR(@rMenuID = 0))

   ORDER BY
    ParentMenuID
  END
 END
 ELSE
 BEGIN
 if (@rScreenGroupId = 0)
 BEGIN
  SELECT
   MenuID,
   ModuleId,
   ParentMenuID,
   MenuTitle,
   ScreenTitle,
   PageURL,
   ScreenId,
   Permission,
   OrderNumber,
   TaskId,
   PageURL AS PagePath,
   MenuIsObsolete,
   Icon
  FROM
  (
	SELECT
   ISNULL(Menu.Id,0) AS MenuID,
   ISNULL(Menu.ParentMenuID, 0) AS ParentMenuID,
   ISNULL(Menu.Title,'') AS MenuTitle,
   ISNULL(Screen.Title, '') AS ScreenTitle,
   ISNULL(Screen.Page, '') AS PageURL,
   ISNULL(Screen.ScreenGroupId,0) AS ScreenGroupId,
   ISNULL(Menu.ScreenId, 0) AS ScreenId,
   ISNULL(PermissionValue, 0) AS Permission,
   ISNULL(OrderNumber, 0) AS OrderNumber,
   ISNULL(Screen.TaskId,0) AS TaskId,
   ISNULL(T.ResourceTypeId,0) AS ResourceTypeId,
   ISNULL(T.ModuleId,0) AS ModuleId,
   ISNULL(Menu.IsObsolete,1) AS MenuIsObsolete,
   ISNULL(Screen.IconPath,'') AS Icon
  FROM
  sSecurity.tMenu Menu
  LEFT OUTER JOIN sSecurity.tScreen Screen ON Menu.ScreenId = Screen.Id
  LEFT OUTER JOIN
  (
  SELECT
   P.TaskId,
   SUM(OT.AvailablePermission & 2) PermissionValue
  FROM
   sSecurity.tPermission P
   INNER JOIN sSecurity.tTask T ON T.Id = P.TaskId  AND T.IsObsolete = 0
   INNER JOIN sSecurity.tModulePermission MP ON MP.ModuleId = T.ModuleId
   INNER JOIN sCommon.tModuleMaster MM ON MP.ModuleId = MM.Id And  MM.IsObsolete = 0
   INNER JOIN sSecurity.tOrganizationTask OT ON OT.TaskId = T.Id
   INNER JOIN (SELECT RoleId FROM sSecurity.tUserRole WHERE  UserId = @rUserId AND IsObsolete = 0) UR ON UR.RoleId = P.RoleId
  GROUP BY P.TaskId
  ) TBL2 ON Screen.TaskId = TBL2.TaskId
  LEFT OUTER JOIN sSecurity.tTask  T ON T.Id =  Screen.TaskId AND ResourceTypeId = @rResourceTypeId
  WHERE (Menu.IsObsolete = 0)
  AND ISNULL(Screen.IsObsolete, 0) = 0
  AND (
		(@rEnvironmentName = 'Local' AND Menu.Id in(24,2711,2411,2714,55,2412,53,52,5515,19181022,19184006,2622,15,5524,552417,22,23,19181046,57,5535,5511,19181043,58,1813,2216,19181039,5510,18,1815,1810,1821,2215,1822,19181017,52,5210,5211,2212,5514,5516,2212,5533,54,5410,19181033,19181023,5414,19184004,19181038,5411,1811)) -- updated by parth/Darsh for showing more menu inside the communication 07-02-2023
	OR (@rEnvironmentName = 'QA' AND Menu.Id in(24,2711,2411,2714,55,2412,53,52,5515,19181022,19184006,2622,15,5524,552417,22,23,19181046,57,5535,5511,19181043,58,1813,2216,19181039,5510,18,1815,1810,1821,2215,1822,19181017,52,5210,5211,2212,5514,5516,2212,5533,54,5410,19181033,19181023,5414,19184004,19181038,5411,1811))
	OR (@rEnvironmentName = 'Production' AND Menu.Id in(24,55,2411,2412,2711,2714,19184006,19181022,2622,15,57,5535,19181039,5511,5510,5524))
	)

  --AND Menu.Id  in (24,2711,2411)  -- Issue: For Only Student Center, My Communication Menu , Developer: Foram, Date: 15-07-2022
  --AND (Menu.Id  in (24,2711)
  --Or ParentMenuID  in (24,2711))
  --AND (Menu.Id IN (15, 32, 55,24, 19181042, 36, 3606,2714)
  --OR ParentMenuID IN (15, 32, 55, 19181042, 36, 24, 18))
  UNION

  SELECT

   ISNULL(Menu.Id, 0) AS MenuID,
   ISNULL(Menu.Id, 0) AS ParentMenuID,
   ISNULL(Screen1.Title,'') AS MenuTitle,
   ISNULL(Screen1.Title, '') AS ScreenTitle,
   ISNULL(Screen1.Page, '')  AS PageURL,
   ISNULL(Screen1.ScreenGroupId,0) AS ScreenGroupId,
   ISNULL(Menu.ScreenId, 0) AS ScreenId,
   ISNULL(PermissionValue, 0) AS Permission,
   ISNULL(OrderNumber, 0) AS OrderNumber,
   ISNULL(Screen1.TaskId,0) AS TaskId,
   ISNULL(T.ResourceTypeId,0) AS ResourceTypeId,
   ISNULL(T.ModuleId,0) AS ModuleId,
   ISNULL(Menu.IsObsolete,1) AS MenuIsObsolete,
   ISNULL(Screen1.IconPath,'') AS Icon
  FROM
   sSecurity.tMenu Menu
   LEFT OUTER JOIN sSecurity.tScreen Screen ON Menu.ScreenId = Screen.Id
   LEFT OUTER JOIN sSecurity.tScreen Screen1 ON Screen1.ScreenGroupId = Screen.ScreenGroupId
   LEFT OUTER JOIN sSecurity.tTask  T ON T.Id =  Screen1.TaskId
   LEFT OUTER JOIN (
  SELECT
   P.TaskId,
   SUM(OT.AvailablePermission & 2) PermissionValue
  FROM
   sSecurity.tPermission P
   INNER JOIN sSecurity.tTask T ON T.Id = P.TaskId   AND T.IsObsolete = 0
   INNER JOIN sSecurity.tModulePermission MP ON MP.ModuleId = T.ModuleId
   INNER JOIN sCommon.tModuleMaster MM ON MP.ModuleId = MM.Id And  MM.IsObsolete = 0
   INNER JOIN sSecurity.tOrganizationTask OT ON OT.TaskId = T.Id
   INNER JOIN (SELECT RoleId FROM sSecurity.tUserRole WHERE  UserId = @rUserId AND IsObsolete = 0) UR ON UR.RoleId = P.RoleId

  GROUP BY P.TaskId
  ) TBL2 ON Screen1.TaskId = TBL2.TaskId
  WHERE (Menu.IsObsolete = 0)
  AND ISNULL(Screen1.IsObsolete, 0) = 0
  --AND (Menu.ParentMenuID  in (24,2711)
  --or Menu.Id  in (24,2711))
  AND Screen1.Id IN (10187,30363,30342,20241,30282,20565,20563,30377,20915,30331,20564,20180,20617,30364,20130,30818,30828,20191,30787,20996,20717  -- Issue: For Only Student Center Menu , Developer: Foram, Date: 15-07-2022
		,9137,20054,20085,20088,20093,20099,20104,20107,20172,20198,20204,20209,20222,20566,20577,20692,20723,20724,30228,30242,30254,30365,30556,30559,30585,30794,30858,30943,31175,30921,20103,20102,30561, -- Issue: For Only My Communication Menu , Developer: Foram, Date: 20-07-2022
		30857,30696,30739,30284,20171,20105,31048,9136,30678,20179,30793,20720,20115,20693,20086,20819,20126,20950,20094,30856,30855,30795,30789,20697,20758,20083,30245,30246,20125,30874,30274,30817,30251,30252,30253,30247,30395, -- this line for communication screen changes by parth
		20983,30071,30103,30859,30935,30602,30848,30362,20181,20246,20576,20916,20979,30020,30093,30106,30115,30124,30134,30139,30149,30257,30327,30788,30455,30344,31005, -- this line for employee center screen changes by parth
		20108,30298,30552,20025,20026,20068,20336,20551,20719,20866,20894,20899,20900,3009530203,30296,30701,30816,30962, -- this line for fees screen changes by parth
		20396,20630,30138,30548,31012,20075,20161,20163,20167,20654,20985,30974,30994,20388,20073,20074,20165,20224,20462, -- this line for atte screen changes by parth
		20766,20927,20555,30366,20622,30651,30515,20554,20561,20159, 30664, -- this line is use for academic module
		30236,30500,30600,30604,31188,31182,30797,30471,30456,30411,30412,30409,30410,30447,30449,20949,20197,20056,20750,20759,20952,20059,20150,20153, --17/05/2023
		20951,20679,20233,31016,20124,30007,20120,20123,20375,20676,20986,20376,20122,30544,20194,30777,30193,30041,20131,20132,20133,20134,20374,20135,20136,20137,30381,30382,20677,20199,30292,20121,20413,31013,10160,20676,30390,30391,
		30100,30102,30105,30110,30107,30108,30113,
		31224,20930,20932,30936,30951,20284,20696,20698,20700,20776,20918,30164,30579,20570,20567,20568,20173,20174,20260, -- Payroll
		20187,20188,20189,30059,30034,
		20325,20379,20380,20631,20235,20043,
		20997,20201,20215,20297,20848,30235,30687,30688,30689,31307,20170,20195,30546,30547,20216,20221,30582,20961,20960,20962,
		20243,20244,20247,20945,30599,30755,30932,31179,30680,30116,30176,30070,20538,20687,20743,20816,20817,20248,20245,30694,20280,20537,10201,10202,10203,20846,30080,30081,30137,30346,30375,30682
		,30685,30580,30178,30180,20948,20919,20920,31382,
		30661,20845,20844,20843,20653,20681,20663,20658,30966,
		8,9,10,11,19,21,9013,9029,20018,20037,20142,20143,20144,20145,20146,20157,20173,20174,20332,20419,20678,20689,20835,20860,20941,30267,30698,30950,30985,31036,20728,20730,20831,7,20931,20,9030,18,
		30499,121,122,124,125,20158,20175,20176,20309,20596,30120,30122,30577,30602,30778,20250, -- Security
		20001,20002,20003,20004,20006,20007,20008,20285,30021,30338,30509,20953,31173,31379,20967,30995,20323,20616,20913,20055,30801,20632,30030,
		441,459,460,476,500,30699,30716,30847,31003,31004,31020,31021,31022,30852,30991,31177,31187,31257,30388,30627,20908,20909,20910,30269,30517,30614,30617,20035,601,602,603,604,605,606,9084,20270,20339,20402,20230,20573,20586,20629,20836,31174,10117,524,30446,30451,30675,30676,30619,10217,30923,31025,31034,31035,10097,20904,20905,20638,20729,20834,20613,20432,20433,20435,31176,10118,31262,31303,30774,30849,30337,20249,20841,20965,30679,30691,
		20409,20727,20907,20919,20971,30564,30732,20998,31315,31027,31028,30019,30831,30850,30612,30626,30650,30535,20978,20882,20208,20416,20513,20514,20544,20553,20688,31348,31359,31364,20716,20268,20968,20828,30271,30343,31225,30931,30596,30597,20259,20623,30538,30545,30955,30957,30939,31383,
		20518,30908,30259,30208,30118,20878,20969,20975,20840,31432,

500,476,459,460,449,408,409,449,472, -- this line for HR master module
31410,
20021,20643,30204,30205,30618,30796,30798,30971,30972,30970,30605,30609,31335,30329,30531,20628,20269,20539,20227,20127,20147,30268,30299,30554,20207,20539,30539,30615,30970,20963,20539,30098,30539,30096,30068,
20010,20013,20014,20016,20019,20560,20875,20973,20987,30234,30335,30332,30726,30534,20009,31435,31434, -- this line for Student Management and Setting module
20061,20063,20064,20065,20066,20067,20069,20070,20071,20072,20389,20390,20552,20557,30227,30457,30578, -- this line for Certificate module
20079,20080,20226,20540,20694,20695,20715,20726,20728,20818,20947,30008,30336,30549,30870,30958,31228,20917,20633,20168,30032, -- this line for Admission module
20058,20151,20621,20748,20751,31420, -- this line for Event | Activity Master
30027,20262,30111,30161,30243,30262,30415,30581,30976,30977,30978,30999,31038,31172,31204,31313,30889, -- this line for Biometric module
20033,20057,20034,20060,20062,20237,20258,20271,20276,20286,20316,20385,20418,20427,20464,20490,20682,20684,20711,20714,20761,20962,30072,30113,30114,30130,30132,30408,30450,30996,30997,31046,  -- this line for Assesment General module
20729,20741,20730,20742,20744,20745,20746,20749,20752,20829, -- this line for activity based
20096,20098,20239, -- line for cce
20076,20078,20081,20082,20084,20087,20090,20092,20072,20082,20932,20923,20925,20934,20995,30006,20434,20436,20468,20478,20479,20480,20618,20710, --co scholastic
20317, -- GSEB
20912, -- MHBHSE
30215, -- CBSE
143,127 -- Configuration
		)
  --AND Screen1.Id IN (9147, 30300, 30301, 30330, 30341, 30782, 30783, 30784, 30785, 30786, 30787, 30788, 30790, 30791, 30792, 30499,20246,
  --30914,30913,30912,30911
  --)
  ) MenuTable
  WHERE
  --(MenuTable.ScreenId = 0 OR MenuTable.Permission >= 2)
  --AND
  ((MenuTable.ResourceTypeId = @rResourceTypeId) OR (@rResourceTypeId = 0))
  AND ((MenuTable.MenuID = @rMenuID)OR(@rMenuID = 0))
  AND MenuIsObsolete = 0
  --AND MenuTable.MenuId IN (15,32,36,55,24,1515,3606,19184009,19181042,2714,19184020)
  AND (
		(@rEnvironmentName = 'Local' AND MenuTable.MenuId in(24,2711,2411,2714,55,2412,53,52,5515,19181022,19184006,2622,15,5524,552417,22,23,19181046,57,5535,5511,19181043,58,1813,2216,19181039,5510,18,1815,1810,1821,2215,1822,19181017,52,5210,5211,2212,5514,5516,2212,5533,54,5410,19181033,19181023,5414,19184004,19181038,5411,1811)) -- updated by parth/Darsh for showing more menu inside the communication 07-02-2023
	OR (@rEnvironmentName = 'QA' AND MenuTable.MenuId in(24,2711,2411,2714,55,2412,53,52,5515,19181022,19184006,2622,15,5524,552417,22,23,19181046,57,5535,5511,19181043,58,1813,2216,19181039,5510,18,1815,1810,1821,2215,1822,19181017,52,5210,5211,2212,5514,5516,2212,5533,54,5410,19181033,19181023,5414,19184004,19181038,5411,1811))
	OR (@rEnvironmentName = 'Production' AND MenuTable.MenuId in(24,55,2411,2412,2711,2714,19184006,19181022,2622,15,57,5535,19181039,5511,5510,5524))
	)
  --AND MenuTable.MenuId  in (24,2711,2411,2714,55,2412,53,52,5515,19181022,19184006,2622)  -- updated by parth for showing more menu inside the communication 07-02-2023
  --AND MenuTable.MenuId  in (24,2711,2411)  -- Issue: For Only Student Center, My Communication Menu , Developer: Foram, Date: 15-07-2022
  ORDER BY ParentMenuID
  END
  ELSE
  BEGIN
	IF EXISTS(SELECT 1 FROM sSecurity.tPermissionUser WHERE UserId = @rUserId)
	BEGIN
		Select


				ISNULL(0, 0) AS MenuID,
				ISNULL(0, 0) AS ParentMenuID,
				ISNULL(S.Title,'') AS MenuTitle,
				ISNULL(S.Title, '') AS ScreenTitle,
				ISNULL(S.Page, '')  AS PageURL,
				ISNULL(S.ScreenGroupId,0) AS ScreenGroupId,
				ISNULL(S.Id, 0) AS ScreenId,
				ISNULL(0, 0) AS Permission,
				ISNULL(0, 0) AS OrderNumber,
				ISNULL(S.TaskId,0) AS TaskId,
				ISNULL(T.ResourceTypeId,0) AS ResourceTypeId,
				ISNULL(MP.ModuleId,0) AS ModuleId,
				ISNULL(1,1) AS MenuIsObsolete,
				ISNULL(S.IconPath,'') AS Icon

			   From sSecurity.tScreen S
		INNER JOIN sSecurity.tPermissionUser P ON P.TaskId=S.TaskId
		--INNER JOIN sSecurity.tUserRole U ON U.RoleId=P.RoleId
		INNER JOIN sSecurity.tTask T ON T.ID = p.TaskId
		INNER JOIN sSecurity.tResourceTypeMaster RTM ON RTM.ID = T.ResourceTypeId
		INNER JOIN sSecurity.tOrganizationTask OT ON T.Id = OT.TaskId AND OT.OrgGroupId = P.OrgGroupId
		INNER JOIN sSecurity.tModulePermission MP ON T.ModuleId = MP.ModuleId And OT.OrgGroupId = MP.OrgGroupId

		WHERE
		(P.Permission & 2) =2
		AND ( ScreenGroupId=@rScreenGroupId OR @rScreenGroupId = 0)
		AND P.UserId=@rUserId
		AND T.IsObsolete = 0
		AND S.IsObsolete = 0
		AND S.IsHideInScreenGroup = 0
		Order by RTM.OrderIndex,S.OrderIndex
	END
	ELSE
	BEGIN
		Select

				ISNULL(0, 0) AS MenuID,
				ISNULL(0, 0) AS ParentMenuID,
				ISNULL(S.Title,'') AS MenuTitle,
				ISNULL(S.Title, '') AS ScreenTitle,
				ISNULL(S.Page, '')  AS PageURL,
				ISNULL(S.ScreenGroupId,0) AS ScreenGroupId,
				ISNULL(S.Id, 0) AS ScreenId,
				ISNULL(0, 0) AS Permission,
				ISNULL(0, 0) AS OrderNumber,
				ISNULL(S.TaskId,0) AS TaskId,
				ISNULL(T.ResourceTypeId,0) AS ResourceTypeId,
				ISNULL(MP.ModuleId,0) AS ModuleId,
				ISNULL(1,1) AS MenuIsObsolete,
				ISNULL(S.IconPath,'') AS Icon


			   From sSecurity.tScreen S
		INNER JOIN sSecurity.tPermission P ON P.TaskId=S.TaskId
		INNER JOIN sSecurity.tUserRole U ON U.RoleId=P.RoleId
		INNER JOIN sSecurity.tTask T ON T.ID = p.TaskId
		INNER JOIN sSecurity.tResourceTypeMaster RTM ON RTM.ID = T.ResourceTypeId
		INNER JOIN sSecurity.tOrganizationTask OT ON T.Id = OT.TaskId AND OT.OrgGroupId = P.OrgGroupId
		INNER JOIN sSecurity.tModulePermission MP ON T.ModuleId = MP.ModuleId And OT.OrgGroupId = MP.OrgGroupId

		WHERE
		(P.Permission & 2) =2
		AND ( ScreenGroupId=@rScreenGroupId OR @rScreenGroupId = 0)
		 AND U.IsObsolete=0
		AND U.UserId=@rUserId
		AND T.IsObsolete = 0
		AND S.IsObsolete = 0
		AND S.IsHideInScreenGroup = 0
		Order by RTM.OrderIndex,S.OrderIndex
	END
  END
 END
END
GO
PRINT N'Altering Procedure [sStudent].[pValidateImportStudent]...';


GO

ALTER PROCEDURE [sStudent].[pValidateImportStudent]

	@rOrgGroupId int,
    @rOrgId int,
	@rXmldoc [nvarchar](max),
	@rOperation int=0,   --1 For Insert,2 For Update
	@rBatchId int=0
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
DECLARE @lSUIdActivate nvarchar(50)=''
DECLARE @lPENNumberActive nvarchar(50)='' --Mantis- 0031338		
DECLARE @lIsActivateUniquePENNumber bit = 0 --Mantis- 0031338
--Added by dhananjay for Mantis- 38255
DECLARE @lApaarIdNumberActive nvarchar(50)='' 
DECLARE @lIsActivateUniqueApaarIdNumber bit = 0
--Added by dhananjay for Mantis- 38255
DECLARE @lIsSurnameAndFatherNameMandatory nvarchar(50)=''
DECLARE @lIsActivateUniqueId bit = 0
DECLARE @lOrgGroupId int = 0
DECLARE @lIsStudentUIDNumberUnique nvarchar(50)=''		--add
SELECT @lOrgGroupId=OrgGroupId FROM sSetup.tOrganizationMaster WHERE Id = @rOrgId
SELECT @lSUIdActivate = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 167 AND SourceTypeId = 2010 AND SourceId = @lOrgGroupId
SELECT @lPENNumberActive = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 544 AND SourceTypeId = 2010 AND SourceId = @lOrgGroupId --Mantis- 0031338	
SELECT @lApaarIdNumberActive = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 587 AND SourceTypeId = 2010 AND SourceId = @lOrgGroupId --Added by dhananjay for Mantis- 38255
SELECT @lIsSurnameAndFatherNameMandatory =  ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 415 AND SourceTypeId = 2010 AND SourceId = @lOrgGroupId	
SELECT @lIsStudentUIDNumberUnique = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 534 AND SourceTypeId = 2010 AND SourceId = @lOrgGroupId		--add
IF (@lSUIdActivate = '') OR (@lSUIdActivate = 'False')
	SET @lIsActivateUniqueId = 0
ELSE
	SET @lIsActivateUniqueId = 1	

	
--Mantis Start- 0031338	
IF (ISNULL(@lPENNumberActive, '') = '') OR (@lPENNumberActive = 'False')
	SET @lIsActivateUniquePENNumber = 0
ELSE
	SET @lIsActivateUniquePENNumber = 1	
--Mantis End- 0031338	

--Added by dhananjay for Mantis Start - 38255
IF (ISNULL(@lApaarIdNumberActive,'') = '') OR (@lApaarIdNumberActive = 'False')
	SET @lIsActivateUniqueApaarIdNumber = 0
Else
	SET @lIsActivateUniqueApaarIdNumber = 1
--Added by dhananjay for Mantis End - 38255

DECLARE @lCount INT
DECLARE @lInterrorCode INT,
		@intDoc INT,
        @lCode nvarchar(50),
        @lClass nvarchar(100),
        @lDivision nvarchar(100),        
        @lRegistrationNumber nvarchar(20),  
        @lAdmissionDate nvarchar(15),        
        @lDOB nvarchar(15),             
        @1ReturnCode int = 1,
        @1ExistStudentCode nvarchar(max) = '',
        @1NotExistStudentCode nvarchar(max) = '',
        @1ExistStudentRegistrationNumber nvarchar(max) = '',
        @1ValidAdmissionDate nvarchar(max) = '',
        @1ValidDOB nvarchar(max) = '',
        @1DuplicateStudentCode nvarchar(max) = '',
        @1DuplicateStudentRegistrationNumber nvarchar(max) = '',
        @lSUId nvarchar(50),
        @1ExistStudentSUId nvarchar(max) = '',
        @1DuplicateStudentSUId nvarchar(max) = '',
        @lLeftDate nvarchar(15),
        @lLCDate nvarchar(15),
        @1ValidLeftDate nvarchar(max) = '',
        @1ValidLCDate nvarchar(max) = '',
        @lStatusId smallint,
        
        @lAdhaarNumber nvarchar(50),  
        @1DuplicateAdhaarNumber nvarchar(max) = '',
        
        @lUIDNumber nvarchar(50),  
        @1DuplicateUIDNumber nvarchar(max) = '',
        
        @1StudentId BIGINT = 0,
		@lPENNumber BIGINT = 0, --Mantis- 0031338	
		@1ExistPENNumber nvarchar(max) = '',--Mantis- 0031338	
		@1DuplicatePENNumber nvarchar(max) = '', --Mantis - 0031338	
		--Added by dhananjay for Mantis Start- 38255
		@lApaarIdNumber nvarchar(50) = '', 
		@1ExistApaarIdNumber nvarchar(max) = '',	
		@1DuplicateApaarIdNumber nvarchar(max) = '' 
		--Added by dhananjay for Mantis End- 38255

EXECUTE @lInterrorCode = sp_xml_preparedocument @intDoc OUTPUT, @rXmlDoc
 
CREATE TABLE #tTable1 
 (
		Id bigint identity,
        Code nvarchar(50),
        RegistrationNumber nvarchar(20),
        FirstName nvarchar(100),
		MiddleName nvarchar(100),
        LastName nvarchar(100),
		Class nvarchar(100),
		Division nvarchar(100),
		AdmissionStandard nvarchar(100),
		AdmissionDate nvarchar(15),
        DOB nvarchar(15),
        Gender nvarchar(10),
        --AdmissionCategory nvarchar(100),
		Religion nvarchar(100),
		CastCategory nvarchar(100),
        SUId nvarchar(50),
        LeftDate nvarchar(15),
        LCDate nvarchar(15),
        LeftStandard nvarchar(100),
        StatusId smallint,
        AdhaarNumber varchar(100),
        UIDNumber varchar(100),
        --Id1 bigint NULL,
        --departmentId int NULL
		PENNumber BIGINT, --Mantis- 0031338	
		ApaarIdNumber nvarchar(50)--Added by dhananjay for Mantis Start- 38255
 
  )
  INSERT INTO #tTable1
	(
	    Code,
	    RegistrationNumber, 
	    FirstName,
		MiddleName,
	    LastName,
	    Class,
	    Division,
	    AdmissionStandard,
	    AdmissionDate,
	    DOB,
	    Gender,
	    --AdmissionCategory,
	    Religion,
	    CastCategory,
	    SUId,
	    LeftDate,
        LCDate,
        LeftStandard,
        StatusId,
        AdhaarNumber,
        UIDNumber,
		PENNumber, --Mantis- 0031338	
		ApaarIdNumber --Added by dhananjay for Mantis Start- 38255
    ) 
   SELECT
        Code,
	    RegistrationNumber, 
	    sSetup.fPortalXMLTagsReplaceReverse(FirstName) AS FirstName,
		sSetup.fPortalXMLTagsReplaceReverse(MiddleName) AS MiddleName,
	    sSetup.fPortalXMLTagsReplaceReverse(LastName) AS LastName,
	    Class,
	    Division,
	    AdmissionStandard,
	    AdmissionDate,
	    DOB,
	    Gender,
	    --AdmissionCategory,
	    sSetup.fPortalXMLTagsReplaceReverse(Religion) AS Religion,
	    sSetup.fPortalXMLTagsReplaceReverse(CastCategory) AS CastCategory,
	    SUId,
	    LeftDate,
        LCDate,
        LeftStandard,
        StatusId,
        AdhaarNumber,
        UIDNumber,
		PENNumber, --Mantis- 0031338	
		ApaarIdNumber --Added by dhananjay for Mantis Start- 38255
   
   FROM OPENXML (@intDoc, '/Table/ImportStudent', 1)
   With
   (
        Code nvarchar(50) '@Code',
        RegistrationNumber nvarchar(20) '@RegistrationNumber',
        FirstName nvarchar(100) '@FirstName',
		MiddleName nvarchar(100) '@MiddleName',
        LastName nvarchar(100) '@LastName',
		Class nvarchar(100) '@Class',
		Division nvarchar(100) '@Division',
		AdmissionStandard nvarchar(100) '@AdmissionStandard',
		AdmissionDate nvarchar(15) '@AdmissionDate',
		DOB nvarchar(15) '@DOB',
		Gender nvarchar(10) '@Gender',
		--AdmissionCategory nvarchar(100) '@AdmissionCategory',
		Religion nvarchar(100) '@Religion',
		CastCategory nvarchar(100) '@CastCategory',
		SUId nvarchar(50) '@SUId',
		LeftDate nvarchar(15) '@LeftDate',
		LCDate nvarchar(15) '@LCDate',
		LeftStandard nvarchar(100) '@LeftStandard',
		StatusId smallint '@StatusId',
		AdhaarNumber varchar(100) '@AdhaarNumber',
		UIDNumber varchar(100) '@UIDNumber',
		PENNumber BIGINT '@PENNumber', --Mantis- 0031338	
		ApaarIdNumber nvarchar(50) '@ApaarIdNumber ' --Added by dhananjay for Mantis Start- 38255
   )   
EXEC sp_xml_removedocument @intDoc
		
SELECT @lCount =  COUNT(Id) FROM #tTable1

WHILE @lCount > 0 
  BEGIN
  
       SELECT         
         
         @lCode = Code, 
         @lRegistrationNumber = RegistrationNumber,
         @lAdmissionDate = AdmissionDate,
         @lDOB=DOB,
         @lSUId = SUId,
         @lLeftDate = LeftDate,
         @lLCDate = LCDate,
         @lStatusId = StatusId,
         @lAdhaarNumber = AdhaarNumber,
         @lUIDNumber = UIDNumber,
		 @lPENNumber = PENNumber, --Mantis- 0031338	
		 @lApaarIdNumber = ApaarIdNumber --Added by dhananjay for Mantis Start- 38255
        FROM #tTable1 WHERE Id = @lCount 

IF(@rOperation=2)
   BEGIN   
     IF Exists(SELECT Id FROM sStudent.tStudentMaster WHERE Code COLLATE DATABASE_DEFAULT = @lCode COLLATE DATABASE_DEFAULT AND OrgId = @rOrgId)    
      SET @1StudentId = (SELECT Id FROM sStudent.tStudentMaster WHERE Code COLLATE DATABASE_DEFAULT = @lCode COLLATE DATABASE_DEFAULT AND OrgId = @rOrgId)
     ELSE
       SET @1NotExistStudentCode = @1NotExistStudentCode + @lCode + ','    
   END     
       
        
IF(@rOperation=1 OR @rOperation=0)     
 BEGIN    
    IF Exists ((select 1 from sStudent.tStudentMaster where Code COLLATE DATABASE_DEFAULT = @lCode COLLATE DATABASE_DEFAULT AND OrgId = @rOrgId))         
          BEGIN
  			    SET @1ExistStudentCode = @1ExistStudentCode + @lCode + ','
	       END	  
	IF Exists ((select 1 from sStudent.tStudentMaster SM INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SM.OrgId where SM.SUId COLLATE DATABASE_DEFAULT = @lSUId COLLATE DATABASE_DEFAULT AND OM.OrgGroupId = @rOrgGroupId))         
          BEGIN
  			    SET @1ExistStudentSUId = @1ExistStudentSUId + @lSUId + ','
	       END	 
--Mantis Start- 0031338	 
	IF(@lPENNumber > 0 )
	BEGIN
		IF Exists ((select 1 from sStudent.tStudentMaster SM INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SM.OrgId where CAST(SM.PENNumber AS NVARCHAR(200)) COLLATE DATABASE_DEFAULT = CAST(@lPENNumber AS NVARCHAR(200)) COLLATE DATABASE_DEFAULT AND SM.OrgId = @rOrgId AND SM.StatusId = 1 AND SM.Id NOT IN (SELECT ReferenceSourceId FROM sStudent.tStudentMaster)))          --Mantis - 44014(OrgGroupId to OrgId, Add Status id )
        BEGIN
  		    SET @1ExistPENNumber = @1ExistPENNumber + CAST(@lPENNumber AS NVARCHAR(200)) + ','
	    END	       
	END
--Mantis Start- 0031338	     
	--Added by dhananjay for Mantis Start- 38255
	IF(ISNULL(@lApaarIdNumber,'')!='')
		BEGIN
			IF Exists ((select 1 from sStudent.tStudentMaster SM INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SM.OrgId where SM.ApaarIdNumber  COLLATE DATABASE_DEFAULT = @lApaarIdNumber COLLATE DATABASE_DEFAULT AND SM.OrgId = @rOrgId AND SM.StatusId = 1 AND SM.Id NOT IN (SELECT ReferenceSourceId FROM sStudent.tStudentMaster))) --Mantis - 44014(@rOrgGroupId to @rOrgId)				--Mantis - 44014(OrgGroupId to OrgId, Add Status id )
			BEGIN
  				SET @1ExistApaarIdNumber = @1ExistApaarIdNumber + @lApaarIdNumber + ','
			END	       
		END
	--Added by dhananjay for Mantis End- 38255   
	IF Exists ((select 1 from sStudent.tStudentMaster where RegistrationNumber COLLATE DATABASE_DEFAULT = @lRegistrationNumber COLLATE DATABASE_DEFAULT AND OrgId = @rOrgId))         
          BEGIN
				IF(ISNULL(@lRegistrationNumber,'')!='')
				BEGIN
  					SET @1ExistStudentRegistrationNumber = @1ExistStudentRegistrationNumber + CAST(@lRegistrationNumber as varchar(max)) + ','
				END
	       END
	IF Exists ((select * from sStudent.tStudentOther SO INNER JOIN sStudent.tStudentMaster SM ON SM.Id = SO.StudentId INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SM.OrgId where SO.AdhaarNumber COLLATE DATABASE_DEFAULT = @lAdhaarNumber COLLATE DATABASE_DEFAULT))         
          BEGIN
          
                IF(ISNULL(@lAdhaarNumber,'')!='')
                BEGIN
  			        SET @1DuplicateAdhaarNumber = @1DuplicateAdhaarNumber + @lAdhaarNumber + ','
  			    END
	       END	
	     
	IF Exists ((select * from sStudent.tStudentOther SO INNER JOIN sStudent.tStudentMaster SM ON SM.Id = SO.StudentId INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SM.OrgId where SO.UIDNumber COLLATE DATABASE_DEFAULT = @lUIDNumber COLLATE DATABASE_DEFAULT))         
	BEGIN
		IF(@lIsStudentUIDNumberUnique='True')	--add
		BEGIN
			IF(ISNULL(@lUIDNumber,'')!='')
			BEGIN
                
  				SET @1DuplicateUIDNumber = @1DuplicateUIDNumber + @lUIDNumber + ',' 
  			                 
			END 
		END
	END	
END


ELSE

BEGIN    

    IF Exists ((select 1 from sStudent.tStudentMaster where Code COLLATE DATABASE_DEFAULT = @lCode COLLATE DATABASE_DEFAULT AND OrgId = @rOrgId AND Id<>@1StudentId))         
          BEGIN
  			    SET @1ExistStudentCode = @1ExistStudentCode + @lCode + ','
	       END	  
	IF Exists ((select 1 from sStudent.tStudentMaster SM INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SM.OrgId where SM.SUId COLLATE DATABASE_DEFAULT = @lSUId COLLATE DATABASE_DEFAULT AND OM.OrgGroupId = @rOrgGroupId AND SM.Id<>@1StudentId))         



          BEGIN
  			    SET @1ExistStudentSUId = @1ExistStudentSUId + @lSUId + ','
	       END	
--Mantis Start- 0031338	
	IF(@lPENNumber > 0)
	BEGIN 
		--IF Exists ((select 1 from sStudent.tStudentMaster SM INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SM.OrgId 
		--where CAST(SM.PENNumber AS NVARCHAR(200)) COLLATE DATABASE_DEFAULT = CAST(@lPENNumber AS NVARCHAR(200)) COLLATE DATABASE_DEFAULT 
		--AND OM.OrgGroupId = @rOrgGroupId AND SM.Id<>@1StudentId))         
		--added by dhananjay for mantis : 41797
		IF Exists ((select 1 from sStudent.tStudentMaster SM INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SM.OrgId 
					where 
					CAST(SM.PENNumber AS NVARCHAR(200)) COLLATE DATABASE_DEFAULT = CAST(@lPENNumber AS NVARCHAR(200)) COLLATE DATABASE_DEFAULT AND 
					SM.OrgId = @rOrgId AND SM.StatusId = 1 AND SM.Id<>@1StudentId AND ISNULL(SM.ReferenceSourceId,0) != @1StudentId
					   AND SM.Id != (SELECT ISNULL(ReferenceSourceId,0)  FROM sStudent.tStudentMaster WHERE Id = @1StudentId)))	--Mantis - 44014(OrgGroupId to OrgId, Add Status id	
		--added by dhananjay for mantis : 41797
        BEGIN
  		    SET @1ExistPENNumber = @1ExistPENNumber + CAST(@lPENNumber AS NVARCHAR(200)) + ','
	    END	       
	END
--Mantis Start- 0031338	          


--Added by dhananjay for Mantis Start- 38255
	IF(@lApaarIdNumber > 0)
		BEGIN
			--IF Exists ((select 1 from sStudent.tStudentMaster SM INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SM.OrgId where SM.ApaarIdNumber COLLATE DATABASE_DEFAULT = @lApaarIdNumber COLLATE DATABASE_DEFAULT AND OM.OrgGroupId = @rOrgGroupId AND SM.Id<>@1StudentId))         
			--added by dhananjay for mantis : 41797
			IF Exists ((select 1 from sStudent.tStudentMaster SM INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SM.OrgId 
			where SM.ApaarIdNumber COLLATE DATABASE_DEFAULT = @lApaarIdNumber COLLATE DATABASE_DEFAULT AND 
				  SM.OrgId = @rOrgId AND SM.StatusId = 1 AND SM.Id<>@1StudentId AND ISNULL(SM.ReferenceSourceId,0) != @1StudentId
				  AND SM.Id != (SELECT ISNULL(ReferenceSourceId,0)  FROM sStudent.tStudentMaster WHERE Id = @1StudentId)))	--Mantis - 44014(OrgGroupId to OrgId, Add Status id )
			--added by dhananjay for mantis : 41797
			BEGIN
  				SET @1ExistApaarIdNumber = @1ExistApaarIdNumber + @lApaarIdNumber + ','
			END	       
		END
	--Added by dhananjay for Mantis End- 38255 


	IF Exists ((select 1 from sStudent.tStudentMaster where RegistrationNumber COLLATE DATABASE_DEFAULT = @lRegistrationNumber COLLATE DATABASE_DEFAULT AND OrgId = @rOrgId AND Id<>@1StudentId))         
          BEGIN
				IF(ISNULL(@lRegistrationNumber,'')!='')
				BEGIN
  					SET @1ExistStudentRegistrationNumber = @1ExistStudentRegistrationNumber + CAST(@lRegistrationNumber as varchar(max)) + ','
				END
	       END
	IF Exists ((select * from sStudent.tStudentOther SO INNER JOIN sStudent.tStudentMaster SM ON SM.Id = SO.StudentId INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SM.OrgId where SO.AdhaarNumber COLLATE DATABASE_DEFAULT = @lAdhaarNumber COLLATE DATABASE_DEFAULT AND SM.Id<>@1StudentId))         
          BEGIN
          
                IF(ISNULL(@lAdhaarNumber,'')!='')
                BEGIN
  			        SET @1DuplicateAdhaarNumber = @1DuplicateAdhaarNumber + @lAdhaarNumber + ','
  			    END
	       END	
	     
	IF Exists ((select * from sStudent.tStudentOther SO INNER JOIN sStudent.tStudentMaster SM ON SM.Id = SO.StudentId INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SM.OrgId where SO.UIDNumber COLLATE DATABASE_DEFAULT = @lUIDNumber COLLATE DATABASE_DEFAULT AND SM.Id<>@1StudentId))         
	BEGIN
		IF(@lIsStudentUIDNumberUnique='True')		--add
		BEGIN  
			IF(ISNULL(@lUIDNumber,'')!='')
			BEGIN
                
  				SET @1DuplicateUIDNumber = @1DuplicateUIDNumber + @lUIDNumber + ',' 
  			                 
			END 
		END   
	END	
END       
	       
	
	IF(ISDATE(@lAdmissionDate) = 0 AND @lAdmissionDate!='')
	BEGIN
		SET @1ValidAdmissionDate=@1ValidAdmissionDate + @lCode + '-' + @lAdmissionDate+','
	END
	IF(ISDATE(@lDOB) = 0 AND @lDOB!='')
	BEGIN
		SET @1ValidDOB=@1ValidDOB + @lCode + '-' + @lDOB+','
	END
	
	IF(ISDATE(@lLeftDate) = 0 AND @lLeftDate!='')
	BEGIN
		SET @1ValidLeftDate=@1ValidLeftDate + @lCode + '-' + @lLeftDate+','
	END
	
	IF(ISDATE(@lLCDate) = 0 AND @lLCDate!='')
	BEGIN
		SET @1ValidLCDate=@1ValidLCDate + @lCode + '-' + @lLCDate+','
	END
	
     SET @lCount = @lCount - 1	
   END	
   
   SELECT @lCount =  COUNT(Id) FROM #tTable1
 
	WHILE @lCount > 0 
		BEGIN
			SELECT         
         
			 @lClass = Class, 
			 @lDivision = Division
     
			FROM #tTable1 WHERE Id = @lCount
			    
		 --IF(@rOperation=1)
		 BEGIN	
			IF NOT EXISTS (SELECT 1 FROM sSetup.tDivisionMaster DM 
					INNER JOIN sSetup.tClassMaster CM ON CM.Id=DM.ClassId 
						WHERE CM.Title COLLATE DATABASE_DEFAULT =@lClass COLLATE DATABASE_DEFAULT AND DM.Title COLLATE DATABASE_DEFAULT =@lDivision COLLATE DATABASE_DEFAULT AND DM.OrgId=@rOrgId)	
			BEGIN
				
				SELECT 'Enter proper value for Division ' + @lClass + ' ' + @lDivision AS StudentCode
				RETURN
			END
		  END	
			SET @lCount = @lCount - 1	
		END
   	      If(@rOperation=2)
   	      BEGIN
   			  DECLARE @lExistingClassId int
   			  DECLARE @lExcelClassId int
   			  SET @lExistingClassId=(SELECT ClassId From sStudent.tAcademic WHERE StudentId=@1StudentId AND BatchId=@rBatchId)
	   		
   			  SET @lExcelClassId=(select Id from sSetup.tClassMaster where Title=@lClass and OrgId=@rOrgId)
	   		  
   			  IF(@lExcelClassId<>@lExistingClassId)
   		       BEGIN
				  SELECT 'Class Id not match/update.' AS StudentCode
			   END
   			
   	      END
			IF EXISTS(SELECT 1 fROM #tTable1 WHERE Code IS NULL OR Code COLLATE DATABASE_DEFAULT ='' COLLATE DATABASE_DEFAULT)
			BEGIN
				SELECT 'ID No Should not be empty' AS StudentCode
			END
		
		--ELSE IF EXISTS(SELECT 1 fROM #tTable1 WHERE Number IS NULL OR Number='')
		--BEGIN
		--	SELECT 'Number Should not be empty' AS StudentCode
		--END
		--ELSE IF EXISTS(SELECT 1 FROM #tTable1 WHERE LastName IS NULL OR LastName COLLATE DATABASE_DEFAULT ='' COLLATE DATABASE_DEFAULT)
		--BEGIN
		--	SELECT 'Surname Should not be empty' AS StudentCode
		--END
		ELSE IF EXISTS(SELECT 1 fROM #tTable1 WHERE FirstName IS NULL OR FirstName COLLATE DATABASE_DEFAULT='' COLLATE DATABASE_DEFAULT)
		BEGIN
			SELECT 'First Name Should not be empty' AS StudentCode
		END
		ELSE IF EXISTS(SELECT 1 fROM #tTable1 WHERE Class IS NULL OR Class COLLATE DATABASE_DEFAULT ='' COLLATE DATABASE_DEFAULT) AND (@rOperation=1)
		BEGIN
			SELECT 'Class Should not be empty' AS StudentCode
		END
		ELSE IF EXISTS(SELECT 1 fROM #tTable1 WHERE Division IS NULL OR Division COLLATE DATABASE_DEFAULT ='' COLLATE DATABASE_DEFAULT) AND (@rOperation=1)
		BEGIN
			SELECT 'Division Should not be empty' AS StudentCode
		END
		--ELSE IF EXISTS(SELECT 1 fROM #tTable1 WHERE AdmissionStandard IS NULL OR AdmissionStandard='')
		--BEGIN
		--	SELECT 'Admission Standard Should not be empty' AS StudentCode
		--END
		ELSE IF EXISTS(SELECT 1 fROM #tTable1 WHERE Gender IS NULL OR Gender='')
		BEGIN
			SELECT 'Gender Should not be empty' AS StudentCode
		END
		--ELSE IF EXISTS(SELECT 1 fROM #tTable1 WHERE AdmissionCategory IS NULL OR AdmissionCategory='')
		--BEGIN
		--	SELECT 'Admission Category Should not be empty' AS StudentCode
		--END
		ELSE IF EXISTS(SELECT 1 fROM #tTable1 WHERE AdmissionDate IS NULL OR AdmissionDate COLLATE DATABASE_DEFAULT='' COLLATE DATABASE_DEFAULT) AND (@rOperation=1)
		BEGIN
			SELECT 'Admission Date Should not be empty or check the date format' AS StudentCode
		END
		ELSE IF EXISTS(SELECT 1 fROM #tTable1 WHERE Class COLLATE DATABASE_DEFAULT NOT IN(SELECT Title FROM sSetup.tClassMaster WHERE OrgId=@rOrgId)) AND (@rOperation=1)
		BEGIN
			SELECT 'Enter proper value for Class as per Institute Setup > Class Master' AS StudentCode
		END				
		ELSE IF EXISTS(SELECT 1 fROM #tTable1 WHERE AdmissionStandard  COLLATE DATABASE_DEFAULT !='' COLLATE DATABASE_DEFAULT AND AdmissionStandard COLLATE DATABASE_DEFAULT NOT IN(SELECT Title FROM sSetup.tClassMaster WHERE OrgId=@rOrgId)) AND (@rOperation=1)
		BEGIN
			SELECT 'Enter proper value for Admission Class as per Admin Tool > Institute Setup > Class Master' AS StudentCode
		END
		ELSE IF EXISTS(SELECT 1 fROM #tTable1 WHERE Religion COLLATE DATABASE_DEFAULT !='' COLLATE DATABASE_DEFAULT AND Religion COLLATE DATABASE_DEFAULT NOT IN(SELECT Title FROM sCommon.tReligionMaster WHERE OrgGroupId=@rOrgGroupId))
		BEGIN
			SELECT 'Enter proper value / Check spelling for Religion per Admin Tool > Master > Religion Master' AS StudentCode
		END
		ELSE IF EXISTS(SELECT 1 fROM #tTable1 WHERE Gender COLLATE DATABASE_DEFAULT !='' COLLATE DATABASE_DEFAULT AND Gender COLLATE DATABASE_DEFAULT NOT IN(SELECT Title FROM sCommon.tGenderMaster))
		BEGIN
			SELECT 'Enter proper value / Check spelling for gender ( Male / Female )' AS StudentCode
		END
		ELSE IF EXISTS(SELECT 1 fROM #tTable1 WHERE CastCategory COLLATE DATABASE_DEFAULT !='' COLLATE DATABASE_DEFAULT AND CastCategory COLLATE DATABASE_DEFAULT NOT IN(SELECT Title FROM sCommon.tCastCategoryMaster))
		BEGIN
			SELECT 'Enter proper value for Cast Category (OBC,SC,ST,GENERAL)' AS StudentCode
		END
		ELSE IF EXISTS(SELECT 1 fROM #tTable1 WHERE (LeftDate IS NULL OR LeftDate COLLATE DATABASE_DEFAULT ='' COLLATE DATABASE_DEFAULT AND LeftStandard COLLATE DATABASE_DEFAULT !='' COLLATE DATABASE_DEFAULT) AND @lStatusId<>1) AND (@rOperation=1)
		BEGIN
			SELECT 'Left Date Should not be empty or check the date format' AS StudentCode
		END
		ELSE IF EXISTS(SELECT 1 fROM #tTable1 WHERE (LCDate IS NULL OR LCDate COLLATE DATABASE_DEFAULT ='' COLLATE DATABASE_DEFAULT AND LeftStandard COLLATE DATABASE_DEFAULT !='' COLLATE DATABASE_DEFAULT) AND @lStatusId<>1)
		BEGIN
			SELECT 'LC Date Should not be empty or check the date format' AS StudentCode
		END
	
		--ELSE IF EXISTS(SELECT 1 fROM #tTable1 WHERE  LeftStandard COLLATE DATABASE_DEFAULT NOT IN(SELECT Title FROM sSetup.tClassMaster WHERE OrgId=@rOrgId) AND @lLeftDate!='')
		--BEGIN
		--	SELECT 'Enter proper value for Left Standard as per Institute Setup > Class Master' AS StudentCode
		--END	
		--ELSE IF EXISTS(SELECT 1 fROM #tTable1 WHERE LeftDate IS NULL OR LeftDate COLLATE DATABASE_DEFAULT ='' COLLATE DATABASE_DEFAULT AND LeftStandard COLLATE DATABASE_DEFAULT !='' COLLATE DATABASE_DEFAULT)
		--BEGIN
		--	SELECT 'LeftDate Should not be empty or check the date format' AS StudentCode
		--END
		ELSE
		BEGIN
	
		IF (@1NotExistStudentCode IS NOT NULL AND @1NotExistStudentCode COLLATE DATABASE_DEFAULT != '' COLLATE DATABASE_DEFAULT)
		BEGIN
		
			SET @1NotExistStudentCode = 'Not Exist Code ' + @1NotExistStudentCode
			Select @1NotExistStudentCode AS StudentCode
		END		
		
		SELECT @1DuplicateStudentCode=COALESCE(@1DuplicateStudentCode ,'') + Code + ',' FROM #tTable1 GROUP BY Code HAVING ( COUNT(Code) > 1 )	
		
		SELECT @1DuplicateStudentSUId=COALESCE(@1DuplicateStudentSUId ,'') + SUId + ',' FROM #tTable1 GROUP BY SUId HAVING ( COUNT(SUId) > 1 )	
			IF(@1DuplicateStudentSUId IS NOT NULL AND @1DuplicateStudentSUId != '' AND @lIsActivateUniqueId=1)
				BEGIN
				
					SET @1DuplicateStudentSUId = 'Duplicate SUId ' + @1DuplicateStudentSUId
					SELECT @1DuplicateStudentSUId AS StudentCode
				END
--Mantis Start- 0031338	

	SELECT @1DuplicatePENNumber=COALESCE(@1DuplicatePENNumber ,'') + CAST(PENNumber AS nvarchar(30))+ ',' FROM #tTable1 GROUP BY PENNumber HAVING ( COUNT(PENNumber) > 1 )	
			IF(@1DuplicatePENNumber IS NOT NULL AND @1DuplicatePENNumber != '' AND @lIsActivateUniquePENNumber=1)
				BEGIN
					SET @1DuplicatePENNumber = 'Duplicate PENNumber ' + @1DuplicatePENNumber
					SELECT @1DuplicatePENNumber AS StudentCode
				END
--Mantis end- 0031338	


--Added by dhananjay for Mantis Start- 38255
	SELECT @1DuplicateApaarIdNumber=COALESCE(@1DuplicateApaarIdNumber ,'') + ApaarIdNumber + ',' FROM #tTable1 GROUP BY ApaarIdNumber HAVING ( COUNT(ApaarIdNumber) > 1 )	
			IF(@1DuplicateApaarIdNumber IS NOT NULL AND @1DuplicateApaarIdNumber != '' AND @lIsActivateUniqueApaarIdNumber=1)
				BEGIN
					SET @1DuplicateApaarIdNumber = 'Duplicate Apaar Id Number ' + @1DuplicateApaarIdNumber
					SELECT @1DuplicateApaarIdNumber AS StudentCode
				END
--Added by dhananjay for Mantis End- 38255  


			ELSE IF(@1DuplicateStudentCode IS NOT NULL AND @1DuplicateStudentCode COLLATE DATABASE_DEFAULT != '' COLLATE DATABASE_DEFAULT)
				BEGIN
				  
					SET @1DuplicateStudentCode = 'Duplicate Code ' + @1DuplicateStudentCode
					
					SELECT @1DuplicateStudentCode AS StudentCode
				END
			ELSE			
				BEGIN
				SELECT @1DuplicateStudentRegistrationNumber=COALESCE(@1DuplicateStudentRegistrationNumber ,'') + CONVERT(VARCHAR(20),RegistrationNumber) + ',' FROM #tTable1 GROUP BY RegistrationNumber HAVING ( COUNT(RegistrationNumber) > 1 AND ISNULL(RegistrationNumber,'')!='')	
				IF(@1DuplicateStudentRegistrationNumber IS NOT NULL AND @1DuplicateStudentRegistrationNumber  COLLATE DATABASE_DEFAULT != '' COLLATE DATABASE_DEFAULT)
				BEGIN
					SET @1DuplicateStudentRegistrationNumber = 'Duplicate Registration Number ' + @1DuplicateStudentRegistrationNumber
					SELECT @1DuplicateStudentRegistrationNumber AS StudentCode
				END
		
		ELSE IF (@1DuplicateAdhaarNumber IS NOT NULL AND @1DuplicateAdhaarNumber COLLATE DATABASE_DEFAULT != '' COLLATE DATABASE_DEFAULT)
		BEGIN
		  
			SET @1DuplicateAdhaarNumber = 'Exist Adhaar Number ' + @1DuplicateAdhaarNumber
			Select @1DuplicateAdhaarNumber AS StudentCode
		END
		
		
		ELSE IF (@1DuplicateUIDNumber IS NOT NULL AND @1DuplicateUIDNumber COLLATE DATABASE_DEFAULT != '' COLLATE DATABASE_DEFAULT AND @lIsStudentUIDNumberUnique='True') --add
		BEGIN
			SET @1DuplicateUIDNumber = 'Exist UID Number ' + @1DuplicateUIDNumber
			Select @1DuplicateUIDNumber AS StudentCode
		END
		--Mantis Start- 0031338
		ELSE IF (@1ExistPENNumber IS NOT NULL AND @1ExistPENNumber != '' AND @lIsActivateUniquePENNumber=1)
		BEGIN
			SET @1ExistPENNumber = 'Exist PENNumber ' + @1ExistPENNumber
			Select @1ExistPENNumber AS StudentCode
		END
		--Mantis End- 0031338	

		--Added by dhananjay for Mantis Start- 38255
		ELSE IF (@1ExistApaarIdNumber IS NOT NULL AND @1ExistApaarIdNumber != '' AND @lIsActivateUniqueApaarIdNumber=1)
		BEGIN
			SET @1ExistApaarIdNumber = 'Exist ApaarIdNumber ' + @1ExistApaarIdNumber
			Select @1ExistApaarIdNumber AS StudentCode
		END
	--Added by dhananjay for Mantis End- 38255 
		
		ELSE IF((@1ExistStudentSUId IS NULL OR @1ExistStudentSUId = '' OR @lIsActivateUniqueId=0) AND (@1ExistStudentCode IS NULL OR @1ExistStudentCode = '') AND (@1ExistStudentRegistrationNumber IS NULL OR @1ExistStudentRegistrationNumber = '')
		AND (@1ValidAdmissionDate IS NULL OR @1ValidAdmissionDate = '') AND (@1ValidDOB IS NULL OR @1ValidDOB = ''))
		BEGIN
			SELECT '' AS StudentCode
		END
		ELSE IF (@1ExistStudentSUId IS NOT NULL AND @1ExistStudentSUId != '' AND @lIsActivateUniqueId=1)
		BEGIN
			SET @1ExistStudentSUId = 'Exist SUId ' + @1ExistStudentSUId
			Select @1ExistStudentSUId AS StudentCode
		END
		ELSE IF (@1ExistStudentCode IS NOT NULL AND @1ExistStudentCode COLLATE DATABASE_DEFAULT != '' COLLATE DATABASE_DEFAULT)
		BEGIN
			SET @1ExistStudentCode = 'Exist Code ' + @1ExistStudentCode
			Select @1ExistStudentCode AS StudentCode
		END
		
		ELSE IF (@1ExistStudentRegistrationNumber IS NOT NULL AND @1ExistStudentRegistrationNumber COLLATE DATABASE_DEFAULT != '' COLLATE DATABASE_DEFAULT)
		BEGIN
			SET @1ExistStudentRegistrationNumber = 'Exist Registration Number ' + @1ExistStudentRegistrationNumber
			Select @1ExistStudentRegistrationNumber AS StudentCode
		END
		ELSE IF (@1ValidAdmissionDate IS NOT NULL AND @1ValidAdmissionDate != '')
		BEGIN
			SET @1ValidAdmissionDate = 'Wrong Admission Date ' + @1ValidAdmissionDate
			Select @1ValidAdmissionDate AS StudentCode
		END
		ELSE IF (@1ValidDOB IS NOT NULL AND @1ValidDOB != '')
		BEGIN
			SET @1ValidDOB = 'Wrong DOB ' + @1ValidDOB
			Select @1ValidDOB AS StudentCode
		END
		ELSE IF (@1ValidLeftDate IS NOT NULL AND @1ValidLeftDate != '' AND @lLCDate!='')
		BEGIN
			SET @1ValidLeftDate = 'Wrong LeftDate ' + @1ValidLeftDate
			Select @1ValidLeftDate AS StudentCode
		END
		ELSE IF (@1ValidLCDate IS NOT NULL AND @1ValidLCDate != '' AND @lLCDate!='')
		BEGIN
			SET @1ValidLCDate = 'Wrong LCDate ' + @1ValidLCDate
			Select @1ValidLCDate AS StudentCode
		END
		
		ELSE IF (@lIsSurnameAndFatherNameMandatory = 'True' )
		BEGIN
			IF EXISTS(SELECT 1 fROM #tTable1 WHERE MiddleName IS NULL OR MiddleName COLLATE DATABASE_DEFAULT='' COLLATE DATABASE_DEFAULT)
			BEGIN
				SELECT 'FatherName Should not be empty' AS StudentCode
			END
			IF EXISTS(SELECT 1 fROM #tTable1 WHERE LastName IS NULL OR LastName COLLATE DATABASE_DEFAULT='' COLLATE DATABASE_DEFAULT)
			BEGIN
				SELECT 'Surname Should not be empty' AS StudentCode
			END
			ELSE 
			BEGIN
				SELECT '' AS StudentCode
			END
						
		END
		END
		END
END
GO
PRINT N'Altering Procedure [sStudent].[pValidateStudentBulkDateUpdate]...';


GO


ALTER PROCEDURE [sStudent].[pValidateStudentBulkDateUpdate]

	@rOrgGroupId int,
    @rOrgId int,
    @rSubCategoryType varchar(100),
	@rXmldoc [nvarchar](max)
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
DECLARE @lCount INT
DECLARE @lInterrorCode INT,
		@intDoc INT,
        @lCode nvarchar(50),             
        @1ReturnCode int = 1,
        @1DuplicateCode nvarchar(400) = '' ,
        
        @lStudentId bigint,
        @lSubCategory nvarchar(max)
       
        
       
EXECUTE @lInterrorCode = sp_xml_preparedocument @intDoc OUTPUT, @rXmlDoc
 
CREATE TABLE #tTable1 
 (
		Id bigint identity,
        StudentId bigint,
        SubCategory nvarchar(100),
        Code nvarchar(100)
 
  )
  INSERT INTO #tTable1
	(
	    StudentId,
	    SubCategory,
	    Code
    ) 
   SELECT
      StudentId,
      SubCategory,
      Code
   
   FROM OPENXML (@intDoc, 'Students/Students', 1)
   With
   (
        StudentId bigint 'StudentId',
        SubCategory nvarchar(100) 'SubCategory',
        Code nvarchar(50) 'Code'
        
   )   
EXEC sp_xml_removedocument @intDoc


SELECT @lCount =  COUNT(Id) FROM #tTable1
 
WHILE @lCount > 0 
  BEGIN
     --SELECT @lCount
       SELECT         
        
         @lStudentId = StudentId,
         @lSubCategory = SubCategory
     
        FROM #tTable1 WHERE Id = @lCount 


	
       
        IF (@rSubCategoryType='AdhaarNumber')
        BEGIN
			IF Exists ((select * from sStudent.tStudentOther SO INNER JOIN sStudent.tStudentMaster SM ON SM.Id = SO.StudentId INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SM.OrgId where SO.AdhaarNumber COLLATE DATABASE_DEFAULT = @lSubCategory COLLATE DATABASE_DEFAULT AND SO.StudentId <> @lStudentId AND SM.OrgId=@rOrgId))         
			  BEGIN
					IF(ISNULL(@lSubCategory,'')!='')
					BEGIN
	                   
  						SET @1DuplicateCode = @1DuplicateCode + @lSubCategory + ','
	  			        
  					END
			   END	
	     END  
	     
	   IF (@rSubCategoryType='UIDNumber')
        BEGIN
			IF Exists ((select * from sStudent.tStudentOther SO INNER JOIN sStudent.tStudentMaster SM ON SM.Id = SO.StudentId INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SM.OrgId where SO.UIDNumber COLLATE DATABASE_DEFAULT = @lSubCategory COLLATE DATABASE_DEFAULT AND SO.StudentId <> @lStudentId AND SM.OrgId=@rOrgId))         
			  BEGIN
					IF(ISNULL(@lSubCategory,'')!='')
					BEGIN
	                    
  						SET @1DuplicateCode = @1DuplicateCode + @lSubCategory + ','
	  			        
  					END
			   END	
	     END 

		IF (@rSubCategoryType='PENNumber')
        BEGIN
			--Mantis Start- 0031338	
			DECLARE @lPENNumberActive nvarchar(50)='',
			 @lReferenceSourceId bigint=0
			SELECT @lPENNumberActive = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 544 AND SourceTypeId = 2010 AND SourceId = @rOrgGroupId
			--Mantis END- 0031338	
			IF (@lPENNumberActive = 'True')
			Begin
				IF(ISNULL(@lSubCategory, '') <> '' AND CAST(@lSubCategory AS bigint) > 0)
				BEGIN
					IF Exists ((select 1 from sStudent.tStudentMaster SM INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SM.OrgId 
					where 
					CAST(SM.PENNumber AS NVARCHAR(200)) COLLATE DATABASE_DEFAULT = @lSubCategory COLLATE DATABASE_DEFAULT AND SM.Id <> @lStudentId AND
					SM.OrgId = @rOrgId AND SM.StatusId = 1 AND ISNULL(SM.ReferenceSourceId,0) != @lStudentId	--Mantis - 44014(OrgGroupId to OrgId, Add Status id )
					   AND SM.Id != (SELECT ISNULL(ReferenceSourceId,0)  FROM sStudent.tStudentMaster WHERE Id = @lStudentId)))  --changes condition by dhananjay for mantis : 41797  
					BEGIN
						IF(ISNULL(@lSubCategory,'')!='')
						BEGIN
  							SET @1DuplicateCode = @1DuplicateCode + @lSubCategory + ','
  						END
					END	
				END
			END
	     END  

		 --Added by dhananjay for Mantis Start- 38255
		IF (@rSubCategoryType='ApaarIdNumber')
        BEGIN
			--Mantis Start- 0031338	
			DECLARE @lApaarIdNumberActive nvarchar(50)=''
			SELECT @lApaarIdNumberActive = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 587 AND SourceTypeId = 2010 AND SourceId = @rOrgGroupId
			--Mantis END- 0031338	
			IF (@lApaarIdNumberActive = 'True')
			Begin
				IF(ISNULL(@lSubCategory, '') <> '')
				BEGIN
					IF Exists ((select 1 from sStudent.tStudentMaster SM INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SM.OrgId 
			       where SM.ApaarIdNumber COLLATE DATABASE_DEFAULT = @lSubCategory COLLATE DATABASE_DEFAULT AND SM.Id <> @lStudentId AND 
						SM.OrgId = @rOrgId AND SM.StatusId = 1 AND ISNULL(SM.ReferenceSourceId,0) != @lStudentId  --Mantis - 44014(OrgGroupId to OrgId, Add Status id )
				   AND SM.Id != (SELECT ISNULL(ReferenceSourceId,0)  FROM sStudent.tStudentMaster WHERE Id = @lStudentId)))  --changes condition by dhananjay for mantis : 41797
					BEGIN
						IF(ISNULL(@lSubCategory,'')!='')
						BEGIN
  							SET @1DuplicateCode = @1DuplicateCode + @lSubCategory + ','
  						END
					END	
				END
			END
	     END  
		 --Added by dhananjay for Mantis End - 38255
	     
	      --   IF (@rSubCategoryType='AdmissionDate')
   --     BEGIN
			--IF Exists ((select * from sStudent.tStudentAdmission SA INNER JOIN sStudent.tStudentOther SO ON SO.StudentId = SA.StudentId 
			--INNER JOIN sStudent.tStudentMaster SM ON SM.Id = SO.StudentId
			--INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SM.OrgId
			--where 
			--SA.AdmissionDate = @lSubCategory 
			--AND SA.StudentId <> @lStudentId AND SM.OrgId=@rOrgId
			--AND SA.AdmissionDate=SO.DateOfBirth
			--AND SA.AdmissionDate<=SO.DateOfBirth))         
			--  BEGIN
			--		IF(ISNULL(@lSubCategory,'')!='')
			--		BEGIN
	                    
  	--					SET @1DuplicateCode = @1DuplicateCode + @lSubCategory + ','
	  			        
  	--				END
			--   END	
	  --   END 
	     
	     
	     
	      
	    --IF Exists ((select * from sStudent.tStudentOther SO INNER JOIN sStudent.tStudentMaster SM ON SM.Id = SO.StudentId INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SM.OrgId where SO.UIDNumber COLLATE DATABASE_DEFAULT = @lSubCategory COLLATE DATABASE_DEFAULT))         
     --     BEGIN
     --           IF(ISNULL(@lSubCategory,'')!='')
     --           BEGIN
  			--        SET @1DuplicateCode = @1DuplicateCode + @lSubCategory + ',' 
  			       	        
  			--    END    
	    --   END
	       
	       
  SET @lCount = @lCount - 1		               
  END       
 
--select * from sStudent.tStudentOther SO where AdhaarNumber='8327'



--SELECT @lCount =  COUNT(Id) FROM #tTable1


 --SELECT @1DuplicateCode=COALESCE(@1DuplicateCode ,'') + SubCategory + ',' FROM #tTable1 GROUP BY SubCategory HAVING ( COUNT(SubCategory) > 1 )
 	
 --  IF(@1DuplicateCode IS NOT NULL AND @1DuplicateCode != '' )
	--			BEGIN
	--				--SET @1DuplicateCode = 'Duplicate '+@rSubCategoryType+' ' + @1DuplicateCode
	--				SELECT @1DuplicateCode AS StudentCode
	--				--Select right(@1DuplicateCode, len(@1DuplicateCode)-1) as StudentCode
	--			END
   
 SELECT @1DuplicateCode AS StudentCode 		
END
GO
PRINT N'Altering Procedure [sStudent].[pValidateStudentImport]...';


GO

ALTER PROCEDURE [sStudent].[pValidateStudentImport]

	@rOrgGroupId int,
    @rOrgId int,
	@rXmldoc [nvarchar](max),
	@rOperation int=0,
	@rBatchId int=0
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	DECLARE @lSUIdActivate nvarchar(50)=''
	DECLARE @lPENNumberActive nvarchar(50)='' 
	DECLARE @lApaarIdNumberActive nvarchar(50)=''--mantis - 38255
	DECLARE @lIsActivateUniquePENNumber bit = 0 
	DECLARE @lIsActivateUniqueApaarIdNumber bit = 0 --mantis - 38255
	DECLARE @lIsSurnameAndFatherNameMandatory nvarchar(50)=''
	DECLARE @lIsActivateUniqueId bit = 0
	DECLARE @lOrgGroupId int = 0
	DECLARE @lIsStudentUIDNumberUnique nvarchar(50)=''
	SELECT @lOrgGroupId=OrgGroupId FROM sSetup.tOrganizationMaster WHERE Id = @rOrgId
	SELECT @lSUIdActivate = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 167 AND SourceTypeId = 2010 AND SourceId = @lOrgGroupId
	SELECT @lPENNumberActive = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 544 AND SourceTypeId = 2010 AND SourceId = @lOrgGroupId --Mantis- 0031338	
	SELECT @lApaarIdNumberActive = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 587 AND SourceTypeId = 2010 AND SourceId = @lOrgGroupId --mantis - 38255
	SELECT @lIsStudentUIDNumberUnique = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 534 AND SourceTypeId = 2010 AND SourceId = @lOrgGroupId		--add
	IF (@lSUIdActivate = '') OR (@lSUIdActivate = 'False')
		SET @lIsActivateUniqueId = 0
	ELSE
		SET @lIsActivateUniqueId = 1	

	IF (ISNULL(@lPENNumberActive, '') = '') OR (@lPENNumberActive = 'False')
		SET @lIsActivateUniquePENNumber = 0
	ELSE
		SET @lIsActivateUniquePENNumber = 1	
	--mantis - 38255
	IF (ISNULL(@lApaarIdNumberActive, '') = '') OR (@lApaarIdNumberActive = 'False')
		SET @lIsActivateUniqueApaarIdNumber = 0
	ELSE
		SET @lIsActivateUniqueApaarIdNumber = 1	
	--mantis - 38255
	DECLARE @lCount INT
	DECLARE @lInterrorCode INT,
		@intDoc INT,
        @lCode nvarchar(50),
        @lClass nvarchar(100),
        @lDivision nvarchar(100),        
        @lRegistrationNumber nvarchar(20),  
        @lAdmissionDate nvarchar(15),        
        @lDOB nvarchar(15),             
        @1ReturnCode int = 1,
        @1ExistStudentCode nvarchar(max) = '',
        @1NotExistStudentCode nvarchar(max) = '',
        @1ExistStudentRegistrationNumber nvarchar(max) = '',
        @1ValidAdmissionDate nvarchar(max) = '',
        @1ValidDOB nvarchar(max) = '',
        @1DuplicateStudentCode nvarchar(max) = '',
        @1DuplicateStudentRegistrationNumber nvarchar(max) = '',
        @lSUId nvarchar(50),
        @1ExistStudentSUId nvarchar(max) = '',
        @1DuplicateStudentSUId nvarchar(max) = '',
        @lLeftDate nvarchar(15),
        @lLCDate nvarchar(15),
        @1ValidLeftDate nvarchar(max) = '',
        @1ValidLCDate nvarchar(max) = '',
        @lStatusId smallint,        
        @lAdhaarNumber nvarchar(50),  
        @1DuplicateAdhaarNumber nvarchar(max) = '',        
        @lUIDNumber nvarchar(50),  
        @1DuplicateUIDNumber nvarchar(max) = '',        
        @1StudentId BIGINT = 0,
		@lPENNumber BIGINT = 0,
		@1ExistPENNumber nvarchar(max) = '',
		@1DuplicatePENNumber nvarchar(max) = '',
		@lApaarIdNumber nvarchar(50) = '',               --mantis - 38255
		@1ExistApaarIdNumber nvarchar(max) = '',--mantis - 38255
		@1DuplicateApaarIdNumber nvarchar(max) = ''--mantis - 38255

	EXECUTE @lInterrorCode = sp_xml_preparedocument @intDoc OUTPUT, @rXmlDoc
 
	CREATE TABLE #tTable1 
 (
		Id bigint identity,
        Code nvarchar(50),
        RegistrationNumber nvarchar(20),
        FirstName nvarchar(100),
		MiddleName nvarchar(100),
        LastName nvarchar(100),
		Class nvarchar(100),
		Division nvarchar(100),
		AdmissionStandard nvarchar(100),
		AdmissionDate nvarchar(15),
        DOB nvarchar(15),
        Gender nvarchar(10),
		Religion nvarchar(100),
		CastCategory nvarchar(100),
        SUId nvarchar(50),
        LeftDate nvarchar(15),
        LCDate nvarchar(15),
        LeftStandard nvarchar(100),
        StatusId smallint,
        AdhaarNumber varchar(100),
        UIDNumber varchar(100),
		PENNumber BIGINT ,
		ApaarIdNumber nvarchar(50)--mantis - 38255
 
  )
	INSERT INTO #tTable1
	(
	    Code,
	    RegistrationNumber, 
	    FirstName,
		MiddleName,
	    LastName,
	    Class,
	    Division,
	    AdmissionStandard,
	    AdmissionDate,
	    DOB,
	    Gender,
	    Religion,
	    CastCategory,
	    SUId,
	    LeftDate,
        LCDate,
        LeftStandard,
        StatusId,
        AdhaarNumber,
        UIDNumber,
		PENNumber,
		ApaarIdNumber --mantis - 38255
    ) 
   SELECT
        Code,
	    RegistrationNumber, 
	    sSetup.fPortalXMLTagsReplaceReverse(FirstName) AS FirstName,
		sSetup.fPortalXMLTagsReplaceReverse(MiddleName) AS MiddleName,
	    sSetup.fPortalXMLTagsReplaceReverse(LastName) AS LastName,
	    Class,
	    Division,
	    AdmissionStandard,
	    AdmissionDate,
	    DOB,
	    Gender,
	    sSetup.fPortalXMLTagsReplaceReverse(Religion) AS Religion,
	    sSetup.fPortalXMLTagsReplaceReverse(CastCategory) AS CastCategory,
	    SUId,
	    LeftDate,
        LCDate,
        LeftStandard,
        StatusId,
        AdhaarNumber,
        UIDNumber,
		PENNumber,
		ApaarIdNumber --mantis - 38255
   
   FROM OPENXML (@intDoc, '/Table/ImportStudent', 1)
   With
   (
        Code nvarchar(50) '@Code',
        RegistrationNumber nvarchar(20) '@RegistrationNumber',
        FirstName nvarchar(100) '@FirstName',
		MiddleName nvarchar(100) '@MiddleName',
        LastName nvarchar(100) '@LastName',
		Class nvarchar(100) '@Class',
		Division nvarchar(100) '@Division',
		AdmissionStandard nvarchar(100) '@AdmissionStandard',
		AdmissionDate nvarchar(15) '@AdmissionDate',
		DOB nvarchar(15) '@DOB',
		Gender nvarchar(10) '@Gender',
		Religion nvarchar(100) '@Religion',
		CastCategory nvarchar(100) '@CastCategory',
		SUId nvarchar(50) '@SUId',
		LeftDate nvarchar(15) '@LeftDate',
		LCDate nvarchar(15) '@LCDate',
		LeftStandard nvarchar(100) '@LeftStandard',
		StatusId smallint '@StatusId',
		AdhaarNumber varchar(100) '@AdhaarNumber',
		UIDNumber varchar(100) '@UIDNumber',
		PENNumber BIGINT '@PENNumber',
		ApaarIdNumber nvarchar(50) '@ApaarIdNumber'--mantis - 38255
   )   
	EXEC sp_xml_removedocument @intDoc
		
	SELECT @lCount =  COUNT(Id) FROM #tTable1
	DECLARE @lValidationMsg nvarchar(max) = ''
	WHILE @lCount > 0 
	BEGIN	
    SELECT
         @lCode = Code, 
         @lRegistrationNumber = RegistrationNumber,
         @lAdmissionDate = AdmissionDate,
         @lDOB=DOB,
         @lSUId = SUId,
         @lLeftDate = LeftDate,
         @lLCDate = LCDate,
         @lStatusId = StatusId,
         @lAdhaarNumber = AdhaarNumber,
         @lUIDNumber = UIDNumber,
		 @lPENNumber = PENNumber ,
		 @lApaarIdNumber = ApaarIdNumber--mantis - 38255
        FROM #tTable1 WHERE Id = @lCount 

	IF(@rOperation=2)
	BEGIN   
		IF Exists(SELECT Id FROM sStudent.tStudentMaster WHERE Code COLLATE DATABASE_DEFAULT = @lCode COLLATE DATABASE_DEFAULT AND OrgId = @rOrgId)    
		 SET @1StudentId = (SELECT Id FROM sStudent.tStudentMaster WHERE Code COLLATE DATABASE_DEFAULT = @lCode COLLATE DATABASE_DEFAULT AND OrgId = @rOrgId)
		ELSE
		  SET @1NotExistStudentCode = @1NotExistStudentCode + @lCode + ','    
   END     
        
	IF(@rOperation=1 OR @rOperation=0)     
	BEGIN    
		IF Exists ((select 1 from sStudent.tStudentMaster where Code COLLATE DATABASE_DEFAULT = @lCode COLLATE DATABASE_DEFAULT AND OrgId = @rOrgId))         
		  BEGIN
 			 SET @1ExistStudentCode = @1ExistStudentCode + @lCode + ','
		  END	  
		IF Exists ((select 1 from sStudent.tStudentMaster SM INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SM.OrgId where SM.SUId COLLATE DATABASE_DEFAULT = @lSUId COLLATE DATABASE_DEFAULT AND OM.OrgGroupId = @rOrgGroupId))         
		BEGIN
  		    SET @1ExistStudentSUId = @1ExistStudentSUId + @lSUId + ','
		END	 
 
		IF(@lPENNumber > 0)
		BEGIN
			IF Exists ((select 1 from sStudent.tStudentMaster SM INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SM.OrgId where CAST(SM.PENNumber AS NVARCHAR(200)) COLLATE DATABASE_DEFAULT = CAST(@lPENNumber AS NVARCHAR(200)) COLLATE DATABASE_DEFAULT AND SM.OrgId = @rOrgId AND SM.StatusId = 1 AND SM.Id NOT IN (SELECT ReferenceSourceId FROM sStudent.tStudentMaster)))	--Mantis - 44014(OrgGroupId to OrgId, Add Status id )
			BEGIN
  				SET @1ExistPENNumber = @1ExistPENNumber + CAST(@lPENNumber AS NVARCHAR(200)) + ','
			END	       
		END
		--mantis - 38255
		IF(ISNULL(@lApaarIdNumber,'')!='')
		BEGIN
			IF Exists ((select 1 from sStudent.tStudentMaster SM INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SM.OrgId where SM.ApaarIdNumber COLLATE DATABASE_DEFAULT = @lApaarIdNumber COLLATE DATABASE_DEFAULT AND SM.OrgId = @rOrgId AND SM.StatusId = 1 AND SM.Id NOT IN (SELECT ReferenceSourceId FROM sStudent.tStudentMaster)))    
			--Mantis - 44014(OrgGroupId to OrgId, Add Status id )
			BEGIN
  				SET @1ExistApaarIdNumber = @1ExistApaarIdNumber + @lApaarIdNumber + ','
			END	       
		END
		 --mantis - 38255       
		IF Exists ((select 1 from sStudent.tStudentMaster where RegistrationNumber COLLATE DATABASE_DEFAULT = @lRegistrationNumber COLLATE DATABASE_DEFAULT AND OrgId = @rOrgId))         
		BEGIN
			IF(ISNULL(@lRegistrationNumber,'')!='')
			BEGIN
				SET @1ExistStudentRegistrationNumber = @1ExistStudentRegistrationNumber + CAST(@lRegistrationNumber as varchar(max)) + ','
			END
		END
		
		IF Exists ((select * from sStudent.tStudentOther SO INNER JOIN sStudent.tStudentMaster SM ON SM.Id = SO.StudentId INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SM.OrgId where SO.AdhaarNumber COLLATE DATABASE_DEFAULT = @lAdhaarNumber COLLATE DATABASE_DEFAULT))         
		BEGIN
			IF(ISNULL(@lAdhaarNumber,'')!='')
			BEGIN
  				SET @1DuplicateAdhaarNumber = @1DuplicateAdhaarNumber + @lAdhaarNumber + ','
	 		END
		END	
		     
		IF Exists ((select * from sStudent.tStudentOther SO INNER JOIN sStudent.tStudentMaster SM ON SM.Id = SO.StudentId INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SM.OrgId where SO.UIDNumber COLLATE DATABASE_DEFAULT = @lUIDNumber COLLATE DATABASE_DEFAULT))         
	BEGIN
		IF(@lIsStudentUIDNumberUnique='True')	--add
		BEGIN
			IF(ISNULL(@lUIDNumber,'')!='')
			BEGIN
                
  				SET @1DuplicateUIDNumber = @1DuplicateUIDNumber + @lUIDNumber + ',' 
  			                 
			END 
		END
	END	
	END

	ELSE
	BEGIN    
    IF Exists ((select 1 from sStudent.tStudentMaster where Code COLLATE DATABASE_DEFAULT = @lCode COLLATE DATABASE_DEFAULT AND OrgId = @rOrgId AND Id<>@1StudentId))         
    BEGIN
  		SET @1ExistStudentCode = @1ExistStudentCode + @lCode + ','
	END	  
	IF Exists ((select 1 from sStudent.tStudentMaster SM INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SM.OrgId where SM.SUId COLLATE DATABASE_DEFAULT = @lSUId COLLATE DATABASE_DEFAULT AND OM.OrgGroupId = @rOrgGroupId AND SM.Id<>@1StudentId))         


    BEGIN
  		SET @1ExistStudentSUId = @1ExistStudentSUId + @lSUId + ','
	END	

	IF(@lPENNumber > 0)
	BEGIN 
		--IF Exists ((select 1 from sStudent.tStudentMaster SM INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SM.OrgId where CAST(SM.PENNumber AS NVARCHAR(200)) COLLATE DATABASE_DEFAULT = CAST(@lPENNumber AS NVARCHAR(200)) COLLATE DATABASE_DEFAULT AND OM.OrgGroupId = @rOrgGroupId AND SM.Id<>@1StudentId))         
        --changes condition by dhananjay for mantis : 41797
		 IF Exists ((select 1 from sStudent.tStudentMaster SM INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SM.OrgId 
			where 
			CAST(SM.PENNumber AS NVARCHAR(200)) COLLATE DATABASE_DEFAULT = CAST(@lPENNumber AS NVARCHAR(200)) COLLATE DATABASE_DEFAULT AND SM.OrgId = @rOrgId AND SM.StatusId = 1 AND SM.Id<>@1StudentId AND ISNULL(SM.ReferenceSourceId,0) != @1StudentId
					   AND SM.Id != (SELECT ISNULL(ReferenceSourceId,0)  FROM sStudent.tStudentMaster WHERE Id = @1StudentId))) --Mantis - 44014(OrgGroupId to OrgId, Add Status id )
		--changes condition by dhananjay for mantis : 41797
		BEGIN
  		    SET @1ExistPENNumber = @1ExistPENNumber + CAST(@lPENNumber AS NVARCHAR(200)) + ','
	    END	       
	END
	--mantis - 38255
	IF(ISNULL(@lApaarIdNumber,'')!='')
	BEGIN 
		--IF Exists ((select 1 from sStudent.tStudentMaster SM INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SM.OrgId where SM.ApaarIdNumber COLLATE DATABASE_DEFAULT = @lApaarIdNumber COLLATE DATABASE_DEFAULT AND OM.OrgGroupId = @rOrgGroupId AND SM.Id<>@1StudentId))         
		--changes condition by dhananjay for mantis : 41797
		IF Exists ((select 1 from sStudent.tStudentMaster SM INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SM.OrgId 
			where SM.ApaarIdNumber COLLATE DATABASE_DEFAULT = @lApaarIdNumber COLLATE DATABASE_DEFAULT AND SM.OrgId = @rOrgId AND SM.StatusId = 1 AND SM.Id<>@1StudentId 
				  AND ISNULL(SM.ReferenceSourceId,0) != @1StudentId
				  AND SM.Id != (SELECT ISNULL(ReferenceSourceId,0)  FROM sStudent.tStudentMaster WHERE Id = @1StudentId))) --Mantis - 44014(OrgGroupId to OrgId, Add Status id )
		--changes condition by dhananjay for mantis : 41797
        BEGIN
  		    SET @1ExistApaarIdNumber = @1ExistApaarIdNumber + @lApaarIdNumber + ','
	    END	       
	END
    --mantis - 38255      
	IF Exists ((select 1 from sStudent.tStudentMaster where RegistrationNumber COLLATE DATABASE_DEFAULT = @lRegistrationNumber COLLATE DATABASE_DEFAULT AND OrgId = @rOrgId AND Id<>@1StudentId))         
          BEGIN
				IF(ISNULL(@lRegistrationNumber,'')!='')
				BEGIN
  					SET @1ExistStudentRegistrationNumber = @1ExistStudentRegistrationNumber + CAST(@lRegistrationNumber as varchar(max)) + ','
				END
	       END
	IF Exists ((select * from sStudent.tStudentOther SO INNER JOIN sStudent.tStudentMaster SM ON SM.Id = SO.StudentId INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SM.OrgId where SO.AdhaarNumber COLLATE DATABASE_DEFAULT = @lAdhaarNumber COLLATE DATABASE_DEFAULT AND SM.Id<>@1StudentId))         
          BEGIN
          
                IF(ISNULL(@lAdhaarNumber,'')!='')
                BEGIN
  			        SET @1DuplicateAdhaarNumber = @1DuplicateAdhaarNumber + @lAdhaarNumber + ','
  			    END
	       END	
	     
	IF Exists ((select * from sStudent.tStudentOther SO INNER JOIN sStudent.tStudentMaster SM ON SM.Id = SO.StudentId INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SM.OrgId where SO.UIDNumber COLLATE DATABASE_DEFAULT = @lUIDNumber COLLATE DATABASE_DEFAULT AND SM.Id<>@1StudentId))         
	BEGIN
		IF(@lIsStudentUIDNumberUnique='True')		--add
		BEGIN  
			IF(ISNULL(@lUIDNumber,'')!='')
			BEGIN
  				SET @1DuplicateUIDNumber = @1DuplicateUIDNumber + @lUIDNumber + ',' 
			END 
		END   
	END	
END       
	
	IF(ISDATE(@lAdmissionDate) = 0 AND @lAdmissionDate!='')
	BEGIN
		SET @1ValidAdmissionDate=@1ValidAdmissionDate + @lCode + '-' + @lAdmissionDate+','
	END
	
	IF(ISDATE(@lDOB) = 0 AND @lDOB!='')
	BEGIN
		SET @1ValidDOB=@1ValidDOB + @lCode + '-' + @lDOB+','
	END
	
	IF(ISDATE(@lLeftDate) = 0 AND @lLeftDate!='')
	BEGIN
		SET @1ValidLeftDate=@1ValidLeftDate + @lCode + '-' + @lLeftDate+','
	END
	
	IF(ISDATE(@lLCDate) = 0 AND @lLCDate!='')
	BEGIN
		SET @1ValidLCDate=@1ValidLCDate + @lCode + '-' + @lLCDate+','
	END
	
     SET @lCount = @lCount - 1	
   END	
   
	SELECT @lCount =  COUNT(Id) FROM #tTable1
 	WHILE @lCount > 0 		
	BEGIN
		SELECT @lClass = Class, @lDivision = Division FROM #tTable1 WHERE Id = @lCount
		
		IF NOT EXISTS (SELECT 1 FROM sSetup.tDivisionMaster DM INNER JOIN sSetup.tClassMaster CM ON CM.Id=DM.ClassId 
					WHERE CM.Title COLLATE DATABASE_DEFAULT =@lClass COLLATE DATABASE_DEFAULT AND DM.Title COLLATE DATABASE_DEFAULT =@lDivision COLLATE DATABASE_DEFAULT AND DM.OrgId=@rOrgId)	
		BEGIN
			SET @lValidationMsg = 'Enter proper value for Division ' + @lClass + ' ' + @lDivision +','
		END

		If(@rOperation=2)
   	    BEGIN
   			DECLARE @lExistingClassId int
   			DECLARE @lExcelClassId int
   			SET @lExistingClassId=(SELECT ClassId From sStudent.tAcademic WHERE StudentId=@1StudentId AND BatchId=@rBatchId)
	   		
   			SET @lExcelClassId=(select Id from sSetup.tClassMaster where Title=@lClass and OrgId=@rOrgId)
	   		
   			IF(@lExcelClassId<>@lExistingClassId)
   			BEGIN
				SET @lValidationMsg+='Class Id not match/update,'
			END   			
   	    END

		IF EXISTS(SELECT 1 fROM #tTable1 WHERE Code IS NULL OR Code COLLATE DATABASE_DEFAULT ='' COLLATE DATABASE_DEFAULT)
		BEGIN
			SET @lValidationMsg+='ID No Should not be empty,'
		END
		
		IF EXISTS(SELECT 1 fROM #tTable1 WHERE FirstName IS NULL OR FirstName COLLATE DATABASE_DEFAULT='' COLLATE DATABASE_DEFAULT)
		BEGIN
			SET @lValidationMsg+='First Name Should not be empty,'			
		END

		IF EXISTS(SELECT 1 fROM #tTable1 WHERE Class IS NULL OR Class COLLATE DATABASE_DEFAULT ='' COLLATE DATABASE_DEFAULT) AND (@rOperation=1)
		BEGIN
			SET @lValidationMsg+='Class Should not be empty,'
		END
		IF EXISTS(SELECT 1 fROM #tTable1 WHERE Division IS NULL OR Division COLLATE DATABASE_DEFAULT ='' COLLATE DATABASE_DEFAULT) AND (@rOperation=1)
		BEGIN
			SET @lValidationMsg+='Division Should not be empty,'
		END
		
		IF EXISTS(SELECT 1 fROM #tTable1 WHERE Gender IS NULL OR Gender='')
		BEGIN
			SET @lValidationMsg+='Gender Should not be empty,'
		END
		
		IF EXISTS(SELECT 1 fROM #tTable1 WHERE AdmissionDate IS NULL OR AdmissionDate COLLATE DATABASE_DEFAULT='' COLLATE DATABASE_DEFAULT) AND (@rOperation=1)
		BEGIN
			SET @lValidationMsg+='Admission Date Should not be empty or check the date format,'
		END
		IF EXISTS(SELECT 1 fROM #tTable1 WHERE Class COLLATE DATABASE_DEFAULT NOT IN(SELECT Title FROM sSetup.tClassMaster WHERE OrgId=@rOrgId)) AND (@rOperation=1)
		BEGIN
			SET @lValidationMsg+='Enter proper value for Class as per Institute Setup > Class Master,'
		END
		
		IF EXISTS(SELECT 1 fROM #tTable1 WHERE AdmissionStandard  COLLATE DATABASE_DEFAULT !='' COLLATE DATABASE_DEFAULT AND AdmissionStandard COLLATE DATABASE_DEFAULT NOT IN(SELECT Title FROM sSetup.tClassMaster WHERE OrgId=@rOrgId)) AND (@rOperation=1)
		BEGIN
			SET @lValidationMsg+='Enter proper value for Admission Class as per Admin Tool > Institute Setup > Class Master,'
		END
		IF EXISTS(SELECT 1 fROM #tTable1 WHERE Religion COLLATE DATABASE_DEFAULT !='' COLLATE DATABASE_DEFAULT AND Religion COLLATE DATABASE_DEFAULT NOT IN(SELECT Title FROM sCommon.tReligionMaster WHERE OrgGroupId=@rOrgGroupId))
		BEGIN
			SET @lValidationMsg+='Enter proper value / Check spelling for Religion per Admin Tool > Master > Religion Master,'
		END
		IF EXISTS(SELECT 1 fROM #tTable1 WHERE Gender COLLATE DATABASE_DEFAULT !='' COLLATE DATABASE_DEFAULT AND Gender COLLATE DATABASE_DEFAULT NOT IN(SELECT Title FROM sCommon.tGenderMaster))
		BEGIN
			SET @lValidationMsg+='Enter proper value / Check spelling for gender ( Male / Female ),'
		END
		IF EXISTS(SELECT 1 fROM #tTable1 WHERE CastCategory COLLATE DATABASE_DEFAULT !='' COLLATE DATABASE_DEFAULT AND CastCategory COLLATE DATABASE_DEFAULT NOT IN(SELECT Title FROM sCommon.tCastCategoryMaster))
		BEGIN
			SET @lValidationMsg+='Enter proper value for Cast Category (OBC,SC,ST,GENERAL),'
		END
		IF EXISTS(SELECT 1 fROM #tTable1 WHERE (LeftDate IS NULL OR LeftDate COLLATE DATABASE_DEFAULT ='' COLLATE DATABASE_DEFAULT AND LeftStandard COLLATE DATABASE_DEFAULT !='' COLLATE DATABASE_DEFAULT) AND @lStatusId<>1) AND (@rOperation=1)
		BEGIN
			SET @lValidationMsg+='Left Date Should not be empty or check the date format,'
		END	
		
		IF EXISTS(SELECT 1 fROM #tTable1 WHERE (LCDate IS NULL OR LCDate COLLATE DATABASE_DEFAULT ='' COLLATE DATABASE_DEFAULT AND LeftStandard COLLATE DATABASE_DEFAULT !='' COLLATE DATABASE_DEFAULT) AND @lStatusId<>1)
		BEGIN
			SET @lValidationMsg+='LC Date Should not be empty or check the date format,'
		END
		
		IF (@1NotExistStudentCode IS NOT NULL AND @1NotExistStudentCode COLLATE DATABASE_DEFAULT != '' COLLATE DATABASE_DEFAULT)
		BEGIN
			SET @lValidationMsg+='Not Exist Code ' + @1NotExistStudentCode+','
		END	
		
		SELECT @1DuplicateStudentCode=COALESCE(@1DuplicateStudentCode ,'') + Code + ',' FROM #tTable1 GROUP BY Code HAVING ( COUNT(Code) > 1 )	
		
		SELECT @1DuplicateStudentSUId=COALESCE(@1DuplicateStudentSUId ,'') + SUId + ',' FROM #tTable1 GROUP BY SUId HAVING ( COUNT(SUId) > 1 )	
		IF(@1DuplicateStudentSUId IS NOT NULL AND @1DuplicateStudentSUId != '' AND @lIsActivateUniqueId=1)
		BEGIN
			SET @lValidationMsg+='Duplicate SUId ' + @1DuplicateStudentSUId +','
		END						

		SELECT @1DuplicatePENNumber=COALESCE(@1DuplicatePENNumber ,'') + CAST(PENNumber AS nvarchar(30))+ ',' FROM #tTable1 GROUP BY PENNumber HAVING ( COUNT(PENNumber) > 1 )	
		IF(@1DuplicatePENNumber IS NOT NULL AND @1DuplicatePENNumber != '' AND @lIsActivateUniquePENNumber=1)
		BEGIN
			SET @lValidationMsg+='Duplicate PENNumber ' + @1DuplicatePENNumber +','
		END

		SELECT @1DuplicateApaarIdNumber=COALESCE(@1DuplicateApaarIdNumber ,'') + CAST(ApaarIdNumber AS nvarchar(30))+ ',' FROM #tTable1 GROUP BY ApaarIdNumber HAVING ( COUNT(ApaarIdNumber) > 1 )	
		IF(@1DuplicateApaarIdNumber IS NOT NULL AND @1DuplicateApaarIdNumber != '' AND @lIsActivateUniqueApaarIdNumber=1)
		BEGIN
			SET @lValidationMsg+='Duplicate ApaarIdNumber ' + @1DuplicateApaarIdNumber +','
		END

		IF(@1DuplicateStudentCode IS NOT NULL AND @1DuplicateStudentCode COLLATE DATABASE_DEFAULT != '' COLLATE DATABASE_DEFAULT)
		BEGIN
			SET @lValidationMsg+='Duplicate Code ' + @1DuplicateStudentCode +','
		END

		SELECT @1DuplicateStudentRegistrationNumber=COALESCE(@1DuplicateStudentRegistrationNumber ,'') + CONVERT(VARCHAR(20),RegistrationNumber) + ',' FROM #tTable1 GROUP BY RegistrationNumber HAVING ( COUNT(RegistrationNumber) > 1 AND ISNULL(RegistrationNumber,'')!='')	
		IF(@1DuplicateStudentRegistrationNumber IS NOT NULL AND @1DuplicateStudentRegistrationNumber  COLLATE DATABASE_DEFAULT != '' COLLATE DATABASE_DEFAULT)
		BEGIN
			SET @lValidationMsg+='Duplicate Registration Number ' + @1DuplicateStudentRegistrationNumber +','
		END

		IF (@1DuplicateAdhaarNumber IS NOT NULL AND @1DuplicateAdhaarNumber COLLATE DATABASE_DEFAULT != '' COLLATE DATABASE_DEFAULT)
		BEGIN
			SET @lValidationMsg+='Exist Adhaar Number ' + @1DuplicateAdhaarNumber +','
		END

		IF (@1DuplicateUIDNumber IS NOT NULL AND @1DuplicateUIDNumber COLLATE DATABASE_DEFAULT != '' COLLATE DATABASE_DEFAULT AND @lIsStudentUIDNumberUnique='True') --add
		BEGIN
			SET @lValidationMsg+='Exist UID Number ' + @1DuplicateUIDNumber +','
		END

		IF (@1ExistPENNumber IS NOT NULL AND @1ExistPENNumber != '' AND @lIsActivateUniquePENNumber=1)
		BEGIN
			SET @lValidationMsg+='Exist PENNumber ' + @1ExistPENNumber +','
		END
		--mantis - 38255
		IF (@1ExistApaarIdNumber IS NOT NULL AND @1ExistApaarIdNumber != '' AND @lIsActivateUniqueApaarIdNumber=1)
		BEGIN
			SET @lValidationMsg+='Exist ApaarIdNumber ' + @1ExistApaarIdNumber +','
		END
		--mantis - 38255
		IF((@1ExistStudentSUId IS NULL OR @1ExistStudentSUId = '' OR @lIsActivateUniqueId=0) AND (@1ExistStudentCode IS NULL OR @1ExistStudentCode = '') AND (@1ExistStudentRegistrationNumber IS NULL OR @1ExistStudentRegistrationNumber = '')
		AND (@1ValidAdmissionDate IS NULL OR @1ValidAdmissionDate = '') AND (@1ValidDOB IS NULL OR @1ValidDOB = ''))
		BEGIN
			SET @lValidationMsg +=''
		END

		IF (@1ExistStudentSUId IS NOT NULL AND @1ExistStudentSUId != '' AND @lIsActivateUniqueId=1)
		BEGIN
			SET @lValidationMsg+='Exist SUId ' + @1ExistStudentSUId +','
		END

		IF (@1ExistStudentCode IS NOT NULL AND @1ExistStudentCode COLLATE DATABASE_DEFAULT != '' COLLATE DATABASE_DEFAULT)
		BEGIN
			SET @lValidationMsg+='Exist Code ' + @1ExistStudentCode +','
		END

		IF (@1ExistStudentRegistrationNumber IS NOT NULL AND @1ExistStudentRegistrationNumber COLLATE DATABASE_DEFAULT != '' COLLATE DATABASE_DEFAULT)
		BEGIN
			SET @lValidationMsg+='Exist Registration Number ' + @1ExistStudentRegistrationNumber +','
		END

		IF (@1ValidAdmissionDate IS NOT NULL AND @1ValidAdmissionDate != '')
		BEGIN
			SET @lValidationMsg+= 'Wrong Admission Date ' + @1ValidAdmissionDate +','
		END

		IF (@1ValidDOB IS NOT NULL AND @1ValidDOB != '')
		BEGIN
			SET @lValidationMsg+= 'Wrong DOB ' + @1ValidDOB +','
		END

		IF (@1ValidLeftDate IS NOT NULL AND @1ValidLeftDate != '' AND @lLCDate!='')
		BEGIN
			SET @lValidationMsg+= 'Wrong LeftDate ' + @1ValidLeftDate +','
		END

		IF (@1ValidLCDate IS NOT NULL AND @1ValidLCDate != '' AND @lLCDate!='')
		BEGIN
			SET @lValidationMsg+= 'Wrong LCDate ' + @1ValidLCDate +','
		END

		IF (@lIsSurnameAndFatherNameMandatory = 'True' )
		BEGIN
			IF EXISTS(SELECT 1 fROM #tTable1 WHERE MiddleName IS NULL OR MiddleName COLLATE DATABASE_DEFAULT='' COLLATE DATABASE_DEFAULT)
			BEGIN
				SET @lValidationMsg+= 'FatherName Should not be empty,'
			END

			IF EXISTS(SELECT 1 fROM #tTable1 WHERE LastName IS NULL OR LastName COLLATE DATABASE_DEFAULT='' COLLATE DATABASE_DEFAULT)
			BEGIN
				SET @lValidationMsg+= 'Surname Should not be empty,'
			END
		END

		SET @lCount = @lCount - 1			  
	END
	SELECT @lValidationMsg AS Validate
END
GO
PRINT N'Altering Procedure [sTimetable].[pWebExchangeLecutres]...';


GO
ALTER PROCEDURE [sTimetable].[pWebExchangeLecutres]
    @rFirstLectureTableIndex int,
    @rSecondLectureTableIndex int,
    @rFirstLectureLectureNumber int,
    @rSecondLectureLectureNumber int,
    @rFirstEmployeeId bigint,
    @rSecondEmployeeId bigint,
    @rFirstSubjectId int,
    @rSecondSubjectId int,
    @rDivisionId int,
    @rSchemaId int,
    @rDayIdOne int,
	@rDayIdTwo int
AS
BEGIN
    SET NOCOUNT ON;  -- Disable "xx rows affected" message

	IF EXISTS (SELECT 1 FROM sTimetable.tTempSTimeTable WHERE EmployeeId = @rFirstEmployeeId AND @rFirstEmployeeId <> 0 AND LectureNumber = @rSecondLectureLectureNumber AND TimeTableSchemaId = @rSchemaId AND DayId = @rDayIdTwo)
    BEGIN
        SELECT -2 as Result; --Teacher First Is Busy
    END
	ELSE IF EXISTS (SELECT 1 FROM sTimetable.tTempSTimeTable WHERE EmployeeId = @rSecondEmployeeId AND @rSecondEmployeeId <> 0 AND LectureNumber = @rFirstLectureLectureNumber AND TimeTableSchemaId = @rSchemaId AND DayId = @rDayIdOne)
    BEGIN
        SELECT -3 as Result; --Teacher Second Is Busy
    END
	ELSE IF EXISTS (SELECT 1 FROM sTimetable.tTeacherTimeOff WHERE EmployeeId = @rFirstEmployeeId AND LectureNumber = @rSecondLectureLectureNumber AND TimeTableSchemaId = @rSchemaId AND DayId = @rDayIdTwo)
    BEGIN
        SELECT -4 as Result; -- Teacher First isn't available (Timeoff)
    END
	ELSE IF EXISTS (SELECT 1 FROM sTimetable.tTeacherTimeOff WHERE EmployeeId = @rSecondEmployeeId AND LectureNumber = @rFirstLectureLectureNumber AND TimeTableSchemaId = @rSchemaId AND DayId = @rDayIdOne)
    BEGIN
        SELECT -5 as Result; -- Teacher Second isn't available (Timeoff)
    END
	ELSE IF EXISTS (SELECT 1 FROM sTimetable.tSubjectTimeOff WHERE SubjectId = @rFirstSubjectId AND LectureNumber = @rSecondLectureLectureNumber AND TimeTableSchemaId = @rSchemaId AND DayId = @rDayIdTwo)
    BEGIN
        SELECT -6 as Result; --Subject First is at TimeOff
    END
	ELSE IF EXISTS (SELECT 1 FROM sTimetable.tSubjectTimeOff WHERE SubjectId = @rSecondSubjectId AND LectureNumber = @rFirstLectureLectureNumber AND TimeTableSchemaId = @rSchemaId AND DayId = @rDayIdOne)
    BEGIN
        SELECT -7 as Result; --Subject Second is at TimeOff
    END
	ELSE IF EXISTS (SELECT 1 FROM sTimetable.tTempSTimeTable WHERE LockNo = 1 AND LectureNumber = @rFirstLectureLectureNumber AND TimeTableSchemaId = @rSchemaId AND DayId = @rDayIdTwo)
    BEGIN
        SELECT -8 as Result; --Lecture Number 1 is Locked
    END
	ELSE IF EXISTS (SELECT 1 FROM sTimetable.tTempSTimeTable WHERE LockNo = -1 AND LectureNumber = @rFirstLectureLectureNumber AND TimeTableSchemaId = @rSchemaId AND DayId = @rDayIdTwo)
    BEGIN
        SELECT -9 as Result; --Lecture Number is Blocked
    END
	ELSE IF EXISTS (SELECT 1 FROM sTimetable.tTempSTimeTable WHERE LockNo = 1 AND LectureNumber = @rSecondLectureLectureNumber AND TimeTableSchemaId = @rSchemaId AND DayId = @rDayIdOne)
    BEGIN
        SELECT -10 as Result; --Lecture Number 2 is Locked
    END
	ELSE IF EXISTS (SELECT 1 FROM sTimetable.tTempSTimeTable WHERE LockNo = -1 AND LectureNumber = @rSecondLectureLectureNumber AND TimeTableSchemaId = @rSchemaId AND DayId = @rDayIdOne)
    BEGIN
        SELECT -11 as Result; --Lecture Number 2 is Blocked
    END
	ELSE
	BEGIN
		BEGIN TRY
		update stimetable.tTempstimetable
		set EmployeeId=@rSecondEmployeeId,SubjectId=@rSecondSubjectId
		where Id=@rFirstLectureTableIndex

		update stimetable.tTempstimetable
		set EmployeeId=@rFirstEmployeeId,SubjectId=@rFirstSubjectId
		where Id=@rSecondLectureTableIndex
			SELECT 1 as Result;
		END TRY
		BEGIN CATCH
			ROLLBACK;
			SELECT -1 as Result;
		END CATCH
	END
END;
GO
PRINT N'Altering Procedure [sTimetable].[pWebFetchInitialClassTeacher]...';


GO

Create or ALTER   PROCEDURE [sTimetable].[pWebFetchInitialClassTeacher] --991100022,9912,991200001,991200002  -- 993700010  --993700007
(
	@rSchemaId INT,
	@rOrgId INT,
	@rClassId INT,
	@rDivisionId INT
)
AS
BEGIN
		SELECT
			OM.Id AS OrgId,
			D.Id AS DivisionId,
			D.InchargeEmployeeId AS ClassTeacherId,
			D.ClassId AS ClassId
		FROM sTimetable.tTeacherworkload TW
		INNER JOIN sSetup.tDivisionMaster D ON TW.DivisionId = D.Id
		INNER JOIN sSetup.tOrganizationMaster OM ON D.OrgId = OM.Id
		INNER JOIN sTimetable.tAssignOrg AO ON AO.OrgId = D.OrgId
		WHERE
			TW.TimetableschemaId = @rSchemaId
			AND D.InchargeEmployeeId > 0
			AND (OM.Id = @rOrgId OR (@rOrgId = 0))
			AND (D.Id = @rDivisionId OR (@rDivisionId = 0))
			AND (D.ClassId = @rClassId OR (@rClassId = 0))
		GROUP BY
			OM.Id, D.Id, D.InchargeEmployeeId, D.ClassId;
END
GO
PRINT N'Altering Procedure [sTimetable].[pWebGetDivisionWorkLoadbyDivisionId]...';


GO
---- exec [sTimetable].[pWebGetDivisionWorkLoadbyDivisionId] 102200001,102200016
ALTER Procedure [sTimetable].[pWebGetDivisionWorkLoadbyDivisionId]
@rDivisionId int,
@rSchemaId int
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	IF EXISTS(select * from  sTimetable.tDivisionWorkLoad where DivisionId = @rDivisionId
			AND TimetableSchemaId=@rSchemaId)
	BEGIN
		SELECT DISTINCT
			tw.employeeid,
			dw.DivisionId,
			dw.NoOfLecture - ISNULL(tt.CountSubjectId, 0) AS DivisionWorkLoad,
			dw.SubjectId,
			tw.nooflecture - ISNULL(tt.CountTeacherId, 0) AS TeacherWorkLoad
		FROM
			sTimetable.tDivisionWorkLoad AS dw
		INNER JOIN
			sTimetable.tTeacherWorkLoad AS tw ON dw.DivisionId = tw.divisionid
											   AND dw.SubjectId = tw.subjectid -- This condition ensures only teacher workloads for the subjects taught in the division are considered
											   AND dw.TimeTableSchemaId=tw.TimeTableSchemaId
		LEFT JOIN (
			SELECT
				DivisionId,
				SubjectId,
				COUNT(*) AS CountSubjectId,
				EmployeeId,
				COUNT(EmployeeId) AS CountTeacherId
			FROM
				sTimetable.tTempSTimeTable
			WHERE
				(DivisionId = @rDivisionId  OR @rDivisionId = 0) And TimetableschemaId=@rSchemaId
			GROUP BY
				DivisionId,
				SubjectId,
				EmployeeId
		) AS tt ON dw.DivisionId = tt.DivisionId AND dw.SubjectId = tt.SubjectId AND tw.employeeid = tt.EmployeeId
		WHERE
			(dw.DivisionId = @rDivisionId OR @rDivisionId = 0)
			AND dw.TimetableSchemaId=@rSchemaId;

	END
	ELSE
	BEGIN
		SELECT DISTINCT
			tw.employeeid,
			tw.DivisionId,
			--dw.NoOfLecture - ISNULL(tt.CountSubjectId, 0)
			tw.nooflecture - ISNULL(tt.CountTeacherId, 0) AS DivisionWorkLoad,
			tw.SubjectId,
			tw.nooflecture - ISNULL(tt.CountTeacherId, 0) AS TeacherWorkLoad
		FROM
			sTimetable.tTeacherWorkLoad AS tw
		LEFT JOIN (
			SELECT
				DivisionId,
				SubjectId,
				COUNT(*) AS CountSubjectId,
				EmployeeId,
				COUNT(EmployeeId) AS CountTeacherId
			FROM
				sTimetable.tTempSTimeTable
			WHERE
				(DivisionId = @rDivisionId  OR @rDivisionId = 0) And TimetableschemaId=@rSchemaId
			GROUP BY
				DivisionId,
				SubjectId,
				EmployeeId
		) AS tt ON tw.DivisionId = tt.DivisionId AND tw.SubjectId = tt.SubjectId AND tw.employeeid = tt.EmployeeId
		WHERE
			(tw.DivisionId = @rDivisionId OR @rDivisionId = 0)
			AND tw.TimetableSchemaId=@rSchemaId;
	END
END
GO
PRINT N'Altering Procedure [sTimetable].[pWebGetGridBySchemaId]...';


GO
ALTER PROCEDURE [sTimetable].[pWebGetGridBySchemaId]
	@rSchemaId int,
	@rClassId int,
	@rOrgId int
AS
BEGIN
	IF(@rClassId = 0)
	BEGIN
		Select  Distinct TS.DayId, TS.ClassId, Max(TS.NoOfPeriod)
		from sTimetable.tTimeSetup TS
		Inner Join sTimetable.tAssignOrg AO ON AO.TimeTableSchemaId=TS.TimeTableSchemaId
		WHERE TS.TimeTableSchemaId=@rSchemaId
		AND (TS.ClassId=@rClassId OR @rClassId = 0)
		And AO.OrgId=@rOrgId
		Group By DayId, ClassId
	END
	ELSE
	BEGIN
		Select  Distinct TS.DayId, Max(TS.NoOfPeriod)
		from sTimetable.tTimeSetup TS
		Inner Join sTimetable.tAssignOrg AO ON AO.TimeTableSchemaId=TS.TimeTableSchemaId
		WHERE TS.TimeTableSchemaId=@rSchemaId
		AND TS.ClassId=@rClassId
		And AO.OrgId=@rOrgId
		Group By DayId
	END
END
GO
PRINT N'Altering Procedure [sTimetable].[pWebGetLectureNumberOfEmployeeOfDay]...';


GO

----exec [sTimetable].[pWebGetLectureNumberOfEmployeeOfDay]991100022, '9912000000012,9912000000013'
ALTER PROCEDURE [sTimetable].[pWebGetLectureNumberOfEmployeeOfDay]
    @rSchemaId bigint,
    @rEmployeeId nvarchar(max)
AS
BEGIN

Declare @EmpId nvarchar(max)
SET @EmpId = @rEmployeeId
SET @rEmployeeId = REPLACE(@rEmployeeId, ',', ''',''');
		DECLARE @sql NVARCHAR(MAX)
		SET @sql = 'Select LectureNumber, DayId , EmployeeId from sTimetable.tTempSTimeTable where TimeTableSchemaId='''+CAST(@rSchemaId as nvarchar(max))+'''  and (''' + @EmpId + ''' = '''' OR EmployeeId in (''' + @rEmployeeId + ''')) union all
		Select LectureNumber,DayId , EmployeeId  from sTimetable.tTeacherTimeOff where TimeTableSchemaId='''+CAST(@rSchemaId as nvarchar(max))+'''  and (''' + @EmpId + ''' = '''' OR EmployeeId in (''' + @rEmployeeId + ''')) order by DayId , LectureNumber';

		EXEC sp_executesql @sql;
    --Select LectureNumber from sTimetable.tTempSTimeTable where EmployeeId=@rEmployeeId  and TimeTableSchemaId=@rSchemaId
    --union all
    --select LectureNumber from sTimetable.tTeacherTimeOff where EmployeeId=@rEmployeeId and TimeTableSchemaId=@rSchemaId
END
GO
PRINT N'Altering Procedure [sTimetable].[pWebGetSubjectTimetOff]...';


GO
---- exec [sTimetable].[pWebGetSubjectTimetOff] 991100022, '991200001,991200003'
ALTER PROCEDURE [sTimetable].[pWebGetSubjectTimetOff]
@rSchemaId int,
@rSubjectId nvarchar(MAX)
AS
BEGIN

Declare @SubId nvarchar(max)
SET @SubId = @rSubjectId
SET @rSubjectId = REPLACE(@rSubjectId, ',', ''',''');
		DECLARE @sql NVARCHAR(MAX)
		SET @sql = 'Select DayId,LectureNumber, SubjectId from sTimetable.tSubjectTimeOff where TimetableSchemaId= '''+CAST(@rSchemaId as nvarchar(max))+''' and (''' + @SubId + ''' = '''' OR SubjectId in (''' + @rSubjectId + '''))';

		EXEC sp_executesql @sql;


END
GO
PRINT N'Creating Procedure [sFee].[pRptFeeReceiptAllBatchGet]...';


GO
CREATE PROCEDURE [sFee].[pRptFeeReceiptAllBatchGet]		
    @rOrgId INT,
	@rStudentId BIGINT
AS		 
BEGIN  
	SELECT
		BM.Title AS BatchName,
		--SUM(ISNULL(FST.Amount, 0) + ISNULL(FA.VariableAmount, 0.00)) AS TotalAmount,
		SUM(
			ISNULL(FST.Amount, 0.00) +
			ISNULL(FA.VariableAmount, 0.00) +
			ISNULL(FA.AdditionalAmount, 0.00) -
			ISNULL(FA.DiscountAmount, 0.00) -
			ISNULL(FA.NotApplicableAmount, 0.00)
		) AS TotalAmount,
		--SUM(
		--	ISNULL(FST.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 TotalPendingAmount,
		0 AS TotalPendingAmount,
		SUM(ISNULL(R.PaidAmount, 0.00)) AS TotalPaidAmount
    FROM 
	sStudent.vStudentAcademic SA
	INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId
	INNER JOIN 
		(
			SELECT
				ISNULL(FS1.IsOptional,0)AS IsOptional,
				ISNULL(FS1.IsVariable,0)AS IsVariable,
				ISNULL(FS1.Amount,0)AS Amount,
				SA1.AcademicId,
				FS1.Id
			FROM sFee.tFeeSetup FS1
			INNER JOIN sStudent.vStudentAcademic SA1 ON FS1.BatchId = SA1.BatchId
			AND SA1.ClassId = FS1.ClassId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
			WHERE FS1.IsOptional = 0

			UNION ALL
				
			SELECT
				ISNULL(FS1.IsOptional,0)AS IsOptional,
				ISNULL(FS1.IsVariable,0)AS IsVariable,
				ISNULL(FS1.Amount,0)AS Amount,
				SA1.AcademicId,
				FS1.Id
			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
		WHERE SA1.StudentId = @rStudentId
		)FST ON FST.AcademicId=SA.AcademicId
	LEFT JOIN sFee.tFeeAllocation FA ON FA.SourceId = SA.AcademicId AND FA.FeeSetupId = FST.Id
    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
		GROUP BY FeeSetupId,R.SourceId
		
		)R ON R.FeeSetupId = FST.Id 
		AND SA.AcademicId = R.SourceId
	WHERE SA.StudentId = @rStudentId
		  AND SA.OrgId = @rOrgId
		  AND SA.BatchId IN 
		  (
			SELECT TOP 2 Id 
			FROM sSetup.tBatchMaster 
			WHERE OrgId = @rOrgId 
			ORDER BY Title DESC
		  )
	GROUP BY --FST.Id,
             BM.Id, BM.Title;
END
GO
PRINT N'Creating Procedure [sHrm].[pEmployeeDataUpdatetoUppperCase]...';


GO
CREATE PROCEDURE [sHrm].[pEmployeeDataUpdatetoUppperCase]
	@rId int
 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 

	IF(@rId = 1)
	BEGIN
		UPDATE sHrm.tEmployeeMaster SET FirstName = UPPER(FirstName), MiddleName = UPPER(MiddleName)
			, LastName = UPPER(LastName), ShortName = UPPER(ShortName)
	END

	IF(@rId = 2)
	BEGIN
		UPDATE sHrm.tEmployeeJobDetail SET JobRemark = UPPER(JobRemark), ReasonOfleaving = UPPER(ReasonOfleaving)
			,ReferenceRemark = UPPER(ReferenceRemark), Subjects = UPPER(Subjects)
	END

	IF(@rId = 3)
	BEGIN
		UPDATE [sHrm].[tEmployeePersonalDetail] SET IdentificationMark1 = UPPER(IdentificationMark1), Qualification = UPPER(Qualification)
			,FamilyCast = UPPER(FamilyCast)
	END

	IF(@rId = 4)
	BEGIN
		UPDATE [sHrm].[tEmployeeCommunications] SET PresentStreetOne = UPPER(PresentStreetOne), PresentStreetTwo = UPPER(PresentStreetTwo)
			,PresentStreetThree = UPPER(PresentStreetThree), PresentCountry = UPPER(PresentCountry), PresentState = UPPER(PresentState)
			,PermanentStreetOne = UPPER(PermanentStreetOne), PresentCity = UPPER(PresentCity), PresentZipCode = UPPER(PresentZipCode)
			,PresentContactNo = UPPER(PresentContactNo), PermanentStreetTwo = UPPER(PermanentStreetTwo), PermanentStreetThree = UPPER(PermanentStreetThree)
			,PermanentCountry = UPPER(PermanentCountry), PermanentState = UPPER(PermanentState), PermanentCity = UPPER(PermanentCity) 
			,PermanentZipCode = UPPER(PermanentZipCode), PermanentContactNo = UPPER(PermanentContactNo), EmergencyStreetOne = UPPER(EmergencyStreetOne)
			,EmergencyStreetTwo = UPPER(EmergencyStreetTwo), EmergencyStreetThree = UPPER(EmergencyStreetThree), EmergencyCountry = UPPER(EmergencyCountry)
			,EmergencyState = UPPER(EmergencyState), EmergencyCity = UPPER(EmergencyCity), EmergencyZipCode = UPPER(EmergencyZipCode)
			,EmergencyContactNo = UPPER(EmergencyContactNo), CompanyEmail = UPPER(CompanyEmail), PersonalEmail = UPPER(PersonalEmail)
			,PhoneNoCompany = UPPER(PhoneNoCompany), ExtensionNo = UPPER(ExtensionNo), MobileNumber = UPPER(MobileNumber)
			,WhatsAppContactNo = UPPER(WhatsAppContactNo)
	END

	IF(@rId = 5)
	BEGIN
		UPDATE [sHrm].[tEmployeeStatutoryAndOther] SET EPFNumber = UPPER(EPFNumber), ESINumber = UPPER(ESINumber)
			,BankName = UPPER(BankName), Branch = UPPER(Branch), IFSCNumber = UPPER(IFSCNumber)
			,AccountHolderName = UPPER(AccountHolderName)
	END
     
END
GO
PRINT N'Altering Procedure [sAdmission].[pAdmissionInquiryAdd]...';


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

	DECLARE @lConfigValueAdmissionAlphaNUmeric nvarchar(50)=''
	SELECT @lConfigValueAdmissionAlphaNUmeric = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 595 AND SourceTypeId = 2010 AND SourceId = @rOrgGroupId 
	
	DECLARE @lInquiryNumber BIGINT = 0

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

		SET @lInquiryNumber= @rNumber

	END
	--Changes for mantis Id: 0042910,44866
	ELSE IF((@lConfigValueForAdmissionNumber = 'False' OR @lConfigValueForAdmissionNumber = '') AND @lInquiryNumber= 0 AND (@lConfigValueAdmissionAlphaNUmeric = '' OR @lConfigValueAdmissionAlphaNUmeric = 'False'))
	BEGIN
		IF(@lConfigValue='OrgGroupBatch')
		BEGIN
			SELECT @rNumber = (ISNULL(MAX(InquiryNumber),0) + 1) FROM sAdmission.tAdmissionInquiry AI
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForbatchId 
			WHERE BM.OrgGroupBatchId = @lOrgGroupBatchId
		END
		ELSE IF(@lConfigValue='Batch')
		BEGIN
			SELECT @rNumber = (ISNULL(MAX(InquiryNumber),0) + 1) FROM sAdmission.tAdmissionInquiry AI
			WHERE AI.ForBatchId = @rForBatchId
		END
		ELSE IF (@lConfigValue = 'Continuous')
		BEGIN
			SELECT @rNumber =(ISNULL(MAX(InquiryNumber),0) + 1) FROM sAdmission.tAdmissionInquiry  
			WHERE OrgGroupId = @rOrgGroupId
		END

		SET @lInquiryNumber= @rNumber
	END
	--Changes End for mantis Id: 0042910
	
	Declare @lStatusId smallint,@lIsValidateBirthdate bit,@lFromDateOfBirth date,@lToDateOfBirth date
	SET @lStatusId= 0
	
	if(@rIsValidateInquiryAsPerAdmission=1)
	Begin
		Select @lIsValidateBirthdate=IsValidateBirthdate,@lFromDateOfBirth=FromDateOfBirth,@lToDateOfBirth=ToDateOfBirth from  sAdmission.tAdmissionCriteria where ClassId=@rForClassId AND BatchID=@rForBatchId
		
		if(@lIsValidateBirthdate=1 AND @rDateOfBirth NOT between @lFromDateOfBirth And @lToDateOfBirth)
		BEGIN
			Select  -101 AS Result
			return
		End
	End
	 
	 

 BEGIN TRANSACTION	
	IF(@rId = 0)	
	BEGIN	

	DECLARE @lNextNumber BIGINT 
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sAdmission.tAdmissionInquiry', 0, 1, 1,@outNextNumber = @lNextNumber output

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


PRINT N'Update complete.';
GO

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

