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

GO
PRINT N'Creating Table [sCommon].[ReportData]...';


GO
--CREATE TABLE [sCommon].[ReportData] (
--    [ID]               BIGINT         IDENTITY (1, 1) NOT NULL,
--    [ReportDetailData] NVARCHAR (MAX) NULL,
--    [ReportId]         INT            NULL,
--    [CreatedUserId]    BIGINT         NULL,
--    PRIMARY KEY CLUSTERED ([ID] ASC) WITH (FILLFACTOR = 85)
--);


GO
PRINT N'Creating Index [sAlert].[tAlertTrack].[IDX_ALERT_ALERTTRACK]...';


GO
CREATE NONCLUSTERED INDEX [IDX_ALERT_ALERTTRACK]
    ON [sAlert].[tAlertTrack]([Id] ASC) WITH (FILLFACTOR = 85);


GO
PRINT N'Creating Index [sCommunication].[tAssignmentScope].[IX_tAssignmentScope_Source_Assignment]...';


GO
CREATE NONCLUSTERED INDEX [IX_tAssignmentScope_Source_Assignment]
    ON [sCommunication].[tAssignmentScope]([SourceTypeId] ASC, [AssignmentId] ASC, [SourceId] ASC);


GO
PRINT N'Creating Index [sFee].[tChargeAccountMapping].[IDX_FEE_ChargeAccountMapping]...';


GO
CREATE NONCLUSTERED INDEX [IDX_FEE_ChargeAccountMapping]
    ON [sFee].[tChargeAccountMapping]([ChargeId] ASC, [AccountingYearId] ASC, [CreditLedgerId] ASC, [DebitLedgerId] ASC, [PayTypeId] ASC) WITH (FILLFACTOR = 85);


GO
PRINT N'Creating Index [sFee].[tChargeReceipt].[IDX_FEE_CHARGERECEIPT]...';


GO
CREATE NONCLUSTERED INDEX [IDX_FEE_CHARGERECEIPT]
    ON [sFee].[tChargeReceipt]([SourceTypeId] ASC, [SourceId] ASC, [IsObsolete] ASC, [ChargeReceiptBookId] ASC) WITH (FILLFACTOR = 85);


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],
		SI.StudentPhoto, ----Cr:0045386
		CASE WHEN SO.GenderId = 1 Then 'Male'  ----Cr:0045386
			WHEN SO.GenderId = 2 Then 'FeMale' END AS [Gender],----Cr:0045386
		ISNULL(L.LCCopyRemark,'') AS LCCopyRemark,		-- Mantis Id : 0045738
		ISNULL(L.ProofOfDOB, '') AS ProofOfDOB,
		ISNULL(SM.PENNumber, 0) AS PENNumber,			-- Mantis Id : 0045843
		ISNULL(SM.ApaarIDNumber, '') AS ApaarIDNumber,
		'[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],[StudentPhoto],[Gender],[LCCopyRemark],[ProofOfDOB],[PENNumber],[ApaarIDNumber]' 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
		LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId=SM.Id ----Cr:0045386
GO
PRINT N'Altering View [sStudent].[vStudentColumnName]...';


GO
ALTER VIEW [sStudent].[vStudentColumnName]  
AS 
SELECT 	
	  --SA.AcademicId,	  
	  --SA.ClassId,
	  --SA.DivisionId,
	  SA.RollNo,
	  --SA.OrgId,
	  --SA.BatchId,
	  OM.Title AS Organization,
	  BM.Title AS Batch,
	  DM.Title AS Department,
	  --SA.StudentId,
	  SA.SUId,
	  SA.Code AS [ID No],
	  SA.Code AS [GR No],
	  SA.Number,
	  SA.FirstName,
	  SA.MiddleName,
	  SA.LastName,
	  SA.Name,
	  --SA.DepartmentId,
	  --SA.StatusId,
	  SA.ClassName,
	  SA.DivisionName,
	  SA.StatusName,
	  SO.UIDNumber,
	  SO.AdhaarNumber,
      SO.DateOfBirth,
      SO.BirthdateInWord,
      --SO.TransportModeId,
      TM.Title AS TransportMode,
      --SO.GenderId,
      GM.Title AS Gender,
      --SO.BloodGroupId,
      BGM.Title AS BloodGroup,
      SO.BirthPlace,
      SO.BirthTaluka,
      SO.BirthDistrict,
      SO.FamilyCast As FamilyCaste,
      --SO.FamilySubCast,
      --SO.CastCategoryId,
      
      CCM.Title AS CasteCategory,
      --SO.ReligionId,
      RM.Title AS Religion,
      --SO.HouseId,
      HM.Title AS House,
      --SO.MotherTongueId,
      MTM.Title AS MotherTongue,
      --SO.NationalityId,
      NM.Title AS Nationality,
      SO.Hobby,
      SH.IdentificationMark1,
      SH.IdentificationMark2,
      SH.IsPysicalDeformity AS IsPhysicalDeformity,
      SH.PysicalDeformityRemark AS PhysicalDeformityRemark,
      SH.IsMajorIllness,
      SH.MajorIllnessRemark,
      SH.FamilyDoctorName,
      SH.FamilyDoctorContactNo,
    STUFF(
        COALESCE(',' + NULLIF(SC.PresentStreetOne, ''), '')  + 
        COALESCE(',' + NULLIF(SC.PresentStreetTwo, ''), '') +
        COALESCE(',' + NULLIF(SC.PresentStreetThree, ''), '') +
        COALESCE(',' + NULLIF(SC.PresentCountry, ''), '') +
        COALESCE(',' + NULLIF(SC.PresentState, ''), '') +
        COALESCE(',' + NULLIF(SC.PresentCity, ''), '') +
        COALESCE(',' + NULLIF(SC.PresentZipCode, ''), '') +
        COALESCE(',' + NULLIF(SC.PresentContactNo, ''), ''),
        1, 1, '') AS PresentAddress,
	  SC.PresentStreetOne,
      SC.PresentStreetTwo,
      SC.PresentStreetThree,
      SC.PresentCountry,
      SC.PresentState,
      SC.PresentCity,
      SC.PresentZipCode,
      SC.PresentContactNo,
	   STUFF(
           COALESCE(',' + NULLIF(SC.PermanentStreetOne, ''), '')  + 
           COALESCE(',' + NULLIF(SC.PermanentStreetTwo, ''), '') +
           COALESCE(',' + NULLIF(SC.PermanentStreetThree, ''), '') +
           COALESCE(',' + NULLIF(SC.PermanentCountry, ''), '') +
           COALESCE(',' + NULLIF(SC.PermanentState, ''), '') +
           COALESCE(',' + NULLIF(SC.PermanentCity, ''), '') +
            COALESCE(',' + NULLIF(SC.PermanentZipCode, ''), '') +
            COALESCE(',' + NULLIF(SC.PermanentContactNo, ''), ''),
           1, 1, '') AS PermanentAddress ,
      SC.PermanentStreetOne,
      SC.PermanentStreetTwo,
      SC.PermanentStreetThree,
      SC.PermanentCountry,
      SC.PermanentState,
      SC.PermanentCity,
      SC.PermanentZipCode,
      SC.PermanentContactNo,
	   
      STUFF(
           COALESCE(',' + NULLIF(SC.EmergencyStreetOne, ''), '')  + 
           COALESCE(',' + NULLIF(SC.EmergencyStreetTwo, ''), '') +
           COALESCE(',' + NULLIF(SC.EmergencyStreetThree, ''), '') +
           COALESCE(',' + NULLIF(SC.EmergencyCountry, ''), '') +
           COALESCE(',' + NULLIF(SC.EmergencyState, ''), '') +
           COALESCE(',' + NULLIF(SC.EmergencyCity, ''), '') +
            COALESCE(',' + NULLIF(SC.EmergencyZipCode, ''), '') +
            COALESCE(',' + NULLIF(SC.EmergencyContactNo, ''), ''),
           1, 1, '') AS EmergencyAddress ,
      SC.EmergencyStreetOne,
      SC.EmergencyStreetTwo,
      SC.EmergencyStreetThree,
      SC.EmergencyCountry,
      SC.EmergencyState,
      SC.EmergencyCity,
      SC.EmergencyZipCode,
      SC.EmergencyContactNo,
      SC.ParentContactNo,
      SC.ParentEmail,
      SC.StudentContactNo,
 SC.StudentEmail,
	  --AR.PickupDestinationId AS BusRouteDestinationId,
	  BDM.Title AS BusRouteDestination,
	  SF.FatherName,
	  SF.FatherDateOfBirth,	 
	  SF.FatherQualification,
	  SF.FatherOccupation,
	  SF.FatherContactNo,
	  SF.FatherMail,
	  SF.FatherOfficeContactNo,
	  SF.FatherOfficeAddress,
	  SF.FatherIncome AS FatherAnnualIncome,	-- MantisId : 0029214
	  SF.MotherName,
	  SF.MotherDateOfBirth,
	  SF.MotherQualification,
	  SF.MotherOccupation,
      SF.MotherContactNo,
      SF.MotherMail,
	  SF.MotherOfficeContactNo,
      SF.MotherOfficeAddress,
      SF.MotherIncome AS MotherAnnualIncome,	-- MantisId : 0029214   
	  AC.Title AS AdmissionCategory,
	  SAD.PreviousSchool,
	  SAD.AdmissionDate,
	  SAD.AdmissionFormNumber,
	  SAD.AdmissionNumber,
	  SAD.IsTransfer,
	  SAD.TransferFrom,
	  SAD.PassingYear,
	  SAD.IsTFWS,
	  SAD.IsCertificateHolder,
	  SAD.CertificateName,
	  AQM.Title AS AdmissionQuota,
      SAD.InactiveDate,
	  SAD.InActiveReason,
	  SAD.LCBook,
	  SAD.LeftStandardId AS LeftStandard,
	  SAD.LeftDate,
	  SAD.LCDate,
	  SAD.LCCopy,
	  SAD.LeftReason,
	  SAD.LCProgress,
	  SAD.LCConduct,
	  SAD.LCRemark,
	  SA.BlackListReason,
	  SA.DivisionOrder,
	  SA.ClassOrderIndex,
	  AD.BankAccountNumber,
	  AD.BankName,
	  AD.BankBranch,
	  AD.BankIFSCCode,
	  AD.BankAccountHolderName,
	  BSM.Title AS StudentBatchStatus,
	  AD.Class9BoardRegistrationNumber,
	  AD.Class11BoardRegistrationNumber,
	  AD.PassportNumber,
	  AD.PassportType,
	  AD.PassportCountryCode,
	  AD.PassportIssueDate,
	  AD.PassportExpiryDate,
	  SS.SiblingName1,
	  SS.SiblingInstitue1,
	  SS.SiblingClass1,
	  SS.SiblingAge1,
	  SS.SiblingRelation1,
	  SS.SiblingName2,
	  SS.SiblingInstitue2,
	  SS.SiblingClass2,
	  SS.SiblingAge2,
	  SS.SiblingRelation2,
	  SS.SiblingName3,
	  SS.SiblingInstitue3,
	  SS.SiblingClass3,
	  SS.SiblingAge3,
	  SS.SiblingRelation3,
	  CD.SSCBoard,
	  CD.SSCSchool,
	  CD.SSCPassingYear,
	  CD.SSCObtainMarks,
	  CD.SSCOutOfMarks,
	  CD.SSCPercentage,
	  CD.SSCMathMarks,
	  CD.SSCMathOutOfMarks,
	  CD.HSCBoard,
	  CD.HSCSchool,
	  CD.HSCPassingYear,
	  CD.HSCObtainMarks,
	  CD.HSCOutOfMarks,
	  CD.HSCPercentage,
	  
	  CD.HSCBiologyMarks,
	  CD.HSCBiologyOutOfMarks,
	 
	  CD.HSCChemistryMarks,
	  CD.HSCChemistryOutOfMarks,
	  CD.HSCMathMarks,
	  CD.HSCMathOutOfMarks,
	  cd.HSCPhysicsMarks,
	  CD.HSCPhysicsOutOfMarks,
	  CD.PCMMarks,
	  CD.PCBMarks,
	  CD.JEERollNo,
	  CD.JEEMeritNo,
	  CD.JEEMeritMarks,
	  CD.JEEOutOfMarks,
	  CD.DiplomaBoard,
	  CD.DiplomaCollege,
	  CD.DiplomaPassingYear,
	  CD.DiplomaObtainMarks,
	  CD.DiplomaOutOfMarks,
	  CD.DiplomaPercentage,
	  CD.ApplicationNo,
	  CD.AdmissionRound,
	  CD.MaritalStatusId,
	  ISNULL(HHM.Title,'') AS HostelName,
	  ISNULL(HRM.Title,'') AS Room,
	  ISNULL(HBM.Title,'') AS BuildingName,
	  ISNULL(HAR.BedNumber,'') AS BedNumber,
	  ISNULL(SGM.Title,'') AS StudentGroup,
	  ISNULL(SGMO.Title,'') AS StudentOtherGroup,
	  SO.BirthState,
	  SO.BirthCountry,
	  ISNULL(BDM.PickupTime,'') AS PickupTime,
	  ISNULL(BDM.DropTime,'') AS DropTime,
	  ISNULL(BRM.Title,'') AS BusRoute,
	  ISNULL(SAD.PreviousStandard,'') AS PreviousStandard,
	  ISNULL(So.ReferenceRemark,'') AS ReferenceRemark,
	  ISNULL(SAD.LCNumber,'') AS LCNumber,
	  CM.Title AS AdmissionStandard,
	  SF.IsFatherExStudent,
	  SF.IsMotherExStudent,
	  SF.FatherOrganization,
	  SF.FatherDesignation,
	  SF.MotherOrganization,
	  SF.MotherDesignation,
	  SF.RelativeOrganization,
	  SF.RelativeDesignation,
	  SH.IsAllergy,
      SH.AllergyRemark,
      SO.FamilySubCast,
      SF.RelativeName,
      SF.RelativeDateOfBirth,
      SF.RelativeOccupation,
      SF.RelativeQualification,
      SF.RelativeContactNo,
      SF.RelativeMail,
      SF.RelativeOfficeAddress,      
      SF.RelativeIncome AS RelativeAnnualIncome,		-- MantisId : 0029214
     
    
		STUFF( (SELECT DISTINCT ',' + CTM.Title FROM sStudent.tStudentCustomTag SCT INNER JOIN sStudent.tCustomTagMaster CTM ON SCT.CustomTagId=CTM.Id 
							WHERE SCT.StudentId = SA.StudentId FOR XML PATH ('')), 1, 1, '')  AS CustomTag,
		STM.Title AS RecordTag,
		SC.WhatsAppContactNo,
        SC.IsStopApplicationAccess,
		CASE WHEN ISNULL(SO.DateOfBirth, '') = '' THEN '' ELSE (SELECT [sCommon].[fGetDateOfBirthInWord](SO.DateOfBirth)) END AS Age,
		BDM.Title AS PickupPoint,
		ISNULL(SA.LocalName,'') AS LocalName, -- Added for mantis : 34211
		ISNULL(BRM2.Title, '') AS DropRoute, -- Added for mantis : 34483
		ISNULL(SA.PENNumber,0) AS PENNumber,    --Mantis - 35453
		 -- added by dhananjay for Mantis - 39234
		ISNULL(SF.FatherAdhaarNumber,'') AS FatherAdhaarNumber,
		ISNULL(SF.MotherAdhaarNumber,'') AS MotherAdhaarNumber,
		-- added by dhananjay for Mantis - 39234
		ISNULL(SA.ApaarIdNumber, '') AS ApaarIdNumber, -- add for mantis : 0040679
		ISNULL(SAD.PreviousLCResult,'') AS PreviousResult		-- Mantis Id : 0043737
		,ISNULL(SAD.PreviousLCDate,'') AS PreviousLCDate-- Mantis Id : 0045175
		,ISNULL(SAD.PreviousLCNumber,'') AS PreviousLCNumber	-- Mantis Id : 0045175

  FROM sStudent.vStudentAcademic SA
	INNER JOIN sStudent.tStudentAdmission SAD ON SAD.StudentId=SA.StudentId
	LEFT JOIN sSetup.tClassMaster CM ON CM.Id=SAD.AdmissionStandardId
	INNER JOIN sCommon.tAdmissionQuotaMaster AQM ON AQM.Id = SAD.AdmissionQuotaId
	INNER JOIN sSetup.tBatchMaster BM ON BM.Id=SA.BatchId
	INNER JOIN sStudent.tStudentOther SO ON SO.StudentId=SA.StudentId
	INNER JOIN sStudent.tStudentCommunication SC ON SC.StudentId=SA.StudentId
	INNER JOIN sTransport.tAssignRoute AR ON AR.SourceId=SA.StudentId
	INNER JOIN sCommon.tTransportModeMaster TM ON TM.Id=SO.TransportModeId
	INNER JOIN sCommon.tGenderMaster GM ON GM.Id=SO.GenderId
	INNER JOIN sCommon.tBloodGroupMaster BGM ON BGM.Id=SO.BloodGroupId
	INNER JOIN sCommon.tCastCategoryMaster CCM ON CCM.Id=SO.CastCategoryId
	INNER JOIN sCommon.tReligionMaster RM ON RM.Id=SO.ReligionId
	INNER JOIN sActivity.tHouseMaster HM ON HM.Id=SO.HouseId
	INNER JOIN sCommon.tMotherTongueMaster MTM ON MTM.Id=SO.MotherTongueId
	INNER JOIN sCommon.tCountryMaster NM ON NM.Id=SO.NationalityId
	INNER JOIN sTransport.tBusRouteDestinationMaster BDM ON BDM.Id=AR.PickupDestinationId
	INNER JOIN sStudent.tStudentFamily SF ON SF.StudentId=SA.StudentId
	INNER JOIN sStudent.tStudentHealth SH ON SH.StudentId=SA.StudentId
	INNER JOIN sStudent.tAdmissionCategoryMaster AC ON AC.Id=SA.AdmissionCategoryId
	INNER JOIN sStudent.tStudentadditional AD ON AD.StudentId= SA.StudentId
	INNER JOIN sStudent.tStudentBatchStatus SBS ON SBS.AcademicId = SA.AcademicId
	INNER JOIN sStudent.tBatchStatusMaster BSM ON BSM.Id = SBS.BatchStatusId
	INNER JOIN sStudent.tStudentSibling SS ON SS.StudentId= SA.StudentId
	INNER JOIN sStudent.tCollegeDetail CD ON CD.StudentId = SA.StudentId
	INNER JOIN sHostel.tAssignRoom HAR ON HAR.SourceId = SA.StudentId
	INNER JOIN sHostel.tRoomMaster HRM ON HRM.Id = HAR.RoomId
	INNER JOIN sHostel.tBuildingMaster HBM ON HBM.HostelId = HRM.HostelId
	INNER JOIN sHostel.tHostelMaster HHM ON HHM.Id = HRM.HostelId
	INNER JOIN sStudent.tStudentGroupMaster SGM ON SGM.Id = SA.StudentGroupId
	INNER JOIN sStudent.tStudentOtherGroupMaster SGMO ON SGMO.Id = SA.StudentOtherGroupId
    INNER JOIN sTransport.tBusRouteMaster BRM ON BRM.Id=BDM.BusRouteId
	INNER JOIN sCommon.tStatusMaster STM ON STM.Id = SA.RecordStatusId AND STM.StatusTypeId=102
	INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SA.OrgId
	INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id = SA.DepartmentId
	LEFT JOIN sTransport.tBusRouteDestinationMaster BDM2 ON BDM2.Id=AR.DropDestinationId -- Added for mantis : 34483
	LEFT JOIN sTransport.tBusRouteMaster BRM2 ON BRM2.Id=BDM2.BusRouteId -- Added for mantis : 34483
GO
PRINT N'Altering View [sStudent].[vStudentCustomSearch]...';


GO
ALTER VIEW [sStudent].[vStudentCustomSearch]  
  
AS  
  
SELECT 	
	  SA.AcademicId,	  
	  SA.ClassId,
	  SA.DivisionId,
	  SA.RollNo,
	  SA.OrgId,
	  OM.Title AS Organization,
	  SA.BatchId,
	  BM.Title AS Batch,
	  BM.OrgGroupBatchId,
	  SA.DepartmentId,
	  DM.Title AS Department,
	  SA.StudentId,
	  SA.SUId,
	  SA.Code,
	  SA.Number,
	  SA.FirstName,
	  SA.MiddleName,
	  SA.LastName,
	  SA.Name,
	  --SA.DepartmentId,
	  SA.StatusId,
	  SA.ClassName,
	  SA.DivisionName,
	  SA.StatusName,
	  SO.UIDNumber,
	  SO.AdhaarNumber,
      CONVERT(VARCHAR(10), SO.DateOfBirth, 111) AS DateOfBirth,
      SO.BirthdateInWord,
      SO.TransportModeId,
      TM.Title AS TransportMode,
      SO.GenderId,
      GM.Title AS Gender,
      SO.BloodGroupId,
      BGM.Title AS BloodGroup,
      SO.BirthPlace,
      SO.BirthTaluka,
      SO.BirthDistrict,
      SO.FamilyCast AS FamilyCaste,
      SO.FamilySubCast,
      
      
      SO.CastCategoryId,
      CCM.Title AS CasteCategory,
      SO.ReligionId,
      RM.Title AS Religion,
      SO.HouseId,
      HM.Title AS House,
      SO.MotherTongueId,
     SO.MotherTongue AS MotherTongue,
      SO.NationalityId,
      NM.Nationality AS Nationality,
      SO.Hobby,
      SH.IdentificationMark1,
      SH.IdentificationMark2,
      SH.IsPysicalDeformity,
      SH.PysicalDeformityRemark,
      SH.IsMajorIllness,
      SH.MajorIllnessRemark,
      SH.FamilyDoctorName,
      SH.FamilyDoctorContactNo,
      
	  SC.PresentStreetOne,
      SC.PresentStreetTwo,
      SC.PresentStreetThree,
      SC.PresentCountry,
      SC.PresentState,
      SC.PresentCity,
      SC.PresentZipCode,
      SC.PresentContactNo,
      SC.PermanentStreetOne,
      SC.PermanentStreetTwo,
      SC.PermanentStreetThree,
      SC.PermanentCountry,
      SC.PermanentState,
      SC.PermanentCity,
      SC.PermanentZipCode,
      SC.PermanentContactNo,
      SC.EmergencyStreetOne,
      SC.EmergencyStreetTwo,
      SC.EmergencyStreetThree,
      SC.EmergencyCountry,
      SC.EmergencyState,
      SC.EmergencyCity,
      SC.EmergencyZipCode,
      SC.EmergencyContactNo,
      SC.ParentContactNo,
      SC.ParentEmail,
      SC.StudentContactNo,
      SC.StudentEmail,
	  ISNULL(SC.WhatsAppContactNo,'') AS WhatsAppContactNo,
	  RT.BusRouteDestinationId AS BusRouteDestinationId,
	  RT.PickupPoint AS BusRouteDestination, -- Changed Value as PickupPoint for mantis : 34483
	  SF.FatherName,
	  CONVERT(VARCHAR(10), SF.FatherDateOfBirth, 111)AS FatherDateOfBirth,
	  SF.FatherQualification,
	  SF.FatherOccupation,
	  SF.FatherContactNo,
	  SF.FatherMail,
	  SF.FatherOfficeAddress,
	  SF.FatherIncome AS FatherAnnualIncome,	-- MantisId : 0029214
	  SF.FatherOfficeContactNo,
	  SF.MotherName,
	 CONVERT(VARCHAR(10),  SF.MotherDateOfBirth,111) AS MotherDateOfBirth,
	  SF.MotherQualification,
	  SF.MotherOccupation,
      SF.MotherContactNo,
      SF.MotherMail,
	  SF.MotherOfficeContactNo,
      SF.MotherOfficeAddress,
      SF.MotherIncome AS MotherAnnualIncome,    -- MantisId : 0029214  
	  ISNULL(SA.AdmissionCategoryId,0) AS AdmissionCategoryId,
	  AC.Title AS AdmissionCategory,
	  SAD.PreviousSchool,
	  CONVERT(VARCHAR(10), SAD.AdmissionDate, 111) AS AdmissionDate,
	  SAD.AdmissionFormNumber,
	  SAD.AdmissionNumber,
	  SAD.IsTransfer,
	  SAD.TransferFrom,
	  SAD.PassingYear,
	  SAD.IsTFWS,
	  SAD.IsCertificateHolder,
	  SAD.CertificateName,
	  AQM.Title AS AdmissionQuota,
	  CONVERT(VARCHAR(10),SAD.LeftDate, 111) AS LeftDate,
	  SA.IsBlackList,
	  SA.BlackListReason,
	  SA.DivisionOrder,
	  SA.ClassOrderIndex,
	  AD.RepeatCount,
	  ADI.BankAccountNumber,
	  ADi.BankBranch,
	  ADI.BankIFSCCode,
	  ADI.BankName,
	  ADI.BankAccountHolderName,
	  ESM.Title AS StudentBatchStatus,
	  EnrollmentStatusId AS StudentStatusId,
	  ADI.Class9BoardRegistrationNumber,
	  ADI.Class11BoardRegistrationNumber,
	  ADI.PassportNumber,
	  ADI.PassportType,
	  ADI.PassportCountryCode,
	CONVERT(VARCHAR(10),ADI.PassportIssueDate,111) AS PassportIssueDate,
	  ADI.PassportExpiryDate,
	  ISNULL(SS.SiblingName1,'') As SiblingName1,
	  ISNULL(SS.SiblingInstitue1,'') As SiblingInstitue1,
	  ISNULL(SS.SiblingClass1,'') As SiblingClass1,
	  ISNULL(SS.SiblingAge1,'') As SiblingAge1,
	  ISNULL(SS.SiblingRelation1,'') As SiblingRelation1,
	  ISNULL(SS.SiblingName2,'') As SiblingName2,
	  ISNULL(SS.SiblingInstitue2,'') As SiblingInstitue2,
	  ISNULL(SS.SiblingClass2,'') As SiblingClass2,
	  ISNULL(SS.SiblingAge2,'') As SiblingAge2,
	  ISNULL(SS.SiblingRelation2,'') As SiblingRelation2,
	  ISNULL(SS.SiblingName3,'') As SiblingName3,
	  ISNULL(SS.SiblingInstitue3,'') As SiblingInstitue3,
	  ISNULL(SS.SiblingClass3,'') As SiblingClass3,
	  ISNULL(SS.SiblingAge3,'') As SiblingAge3,
	  ISNULL(SS.SiblingRelation3,'') As SiblingRelation3,
	  ISNULL(HHM.Title,'') AS HostelName,
	  ISNULL(HRM.Title,'') AS Room,
	  ISNULL(HBM.Title,'') AS BuildingName,
	  ISNULL(HAR.BedNumber,'') AS BedNumber,
	  
	  ISNULL(SM.StudentGroupId,0) AS StudentGroupId,
	  ISNULL(SM.StudentOtherGroupId,0) AS StudentOtherGroupId,
	  
	  SGM.Title AS StudentGroup,
	  SOGM.Title AS StudentOtherGroup,
	  SO.BirthState,
	  So.BirthCountry,
	  ISNULL(RT.BusRouteId,0) AS BusRouteId,
	  ISNULL(RT.PickupTime,'') AS PickupTime,
	  ISNULL(RT.Droptime,'') AS Droptime,
	  ISNULL(RT.BusRoute,'' )AS BusRoute,
	   CD.SSCBoard,
	   CD.SSCSchool,
	  CD.SSCPassingYear,
	  CD.SSCObtainMarks,
	  CD.SSCOutOfMarks,
	  CD.SSCPercentage,
	  CD.SSCMathMarks,
	  CD.SSCMathOutOfMarks,
	  CD.HSCBoard,
	  CD.HSCSchool,
	  CD.HSCPassingYear,
	  CD.HSCObtainMarks,
	  CD.HSCOutOfMarks,
	  CD.HSCPercentage,
	  
	  CD.HSCBiologyMarks,
	  CD.HSCBiologyOutOfMarks,
	 
	  CD.HSCChemistryMarks,
	  CD.HSCChemistryOutOfMarks,
	  CD.HSCMathMarks,
	  CD.HSCMathOutOfMarks,
	  cd.HSCPhysicsMarks,
	  CD.HSCPhysicsOutOfMarks,
	  CD.PCMMarks,
	  CD.PCBMarks,
	  CD.JEERollNo,
	  CD.JEEMeritNo,
	  CD.JEEMeritMarks,
	  CD.JEEOutOfMarks,
	  CD.DiplomaBoard,
	  CD.DiplomaCollege,
	  CD.DiplomaPassingYear,
	  CD.DiplomaObtainMarks,
	  CD.DiplomaOutOfMarks,
	  CD.DiplomaPercentage,
	  CD.ApplicationNo,
	  CD.AdmissionRound,
	  CD.MaritalStatusId,
	  EX.Id As ExemptionTypeId,
	  SAD.PreviousStandard,
	  SO.ReferenceRemark,
	  SAD.LCNumber,
	  CM.Title AS AdmissionStandard,
	  SH.IsAllergy,
      SH.AllergyRemark,
      SF.RelativeName,
      SF.RelativeDateOfBirth,
      SF.RelativeOccupation,
      SF.RelativeQualification,
      SF.RelativeContactNo,
      SF.RelativeMail,
      SF.RelativeOfficeAddress,      
      SF.RelativeIncome AS RelativeAnnualIncome,		-- MantisId : 0029214
      STUFF(
           COALESCE(',' + NULLIF(SC.PresentStreetOne, ''), '')  + 
           COALESCE(',' + NULLIF(SC.PresentStreetTwo, ''), '') +
           COALESCE(',' + NULLIF(SC.PresentStreetThree, ''), '') +
		   COALESCE(',' + NULLIF(SC.PresentCity, ''), '') + -- changed sorting order for mantis : 40447
           COALESCE(',' + NULLIF(SC.PresentState, ''), '') +
           COALESCE(',' + NULLIF(SC.PresentCountry, ''), '') +
            COALESCE(',' + NULLIF(SC.PresentZipCode, ''), '') +
            COALESCE(',' + NULLIF(SC.PresentContactNo, ''), ''),
           1, 1, '') AS PresentAddress,
      STUFF(
           COALESCE(',' + NULLIF(SC.PermanentStreetOne, ''), '')  + 
           COALESCE(',' + NULLIF(SC.PermanentStreetTwo, ''), '') +
           COALESCE(',' + NULLIF(SC.PermanentStreetThree, ''), '') +           
		   COALESCE(',' + NULLIF(SC.PermanentCity, ''), '') + -- changed sorting order for mantis : 40447
           COALESCE(',' + NULLIF(SC.PermanentState, ''), '') +
           COALESCE(',' + NULLIF(SC.PermanentCountry, ''), '') +
            COALESCE(',' + NULLIF(SC.PermanentZipCode, ''), '') +
            COALESCE(',' + NULLIF(SC.PermanentContactNo, ''), ''),
           1, 1, '') AS PermanentAddress ,
      STUFF(
           COALESCE(',' + NULLIF(SC.EmergencyStreetOne, ''), '')  + 
           COALESCE(',' + NULLIF(SC.EmergencyStreetTwo, ''), '') +
           COALESCE(',' + NULLIF(SC.EmergencyStreetThree, ''), '') +
		   COALESCE(',' + NULLIF(SC.EmergencyCity, ''), '') + -- changed sorting order for mantis : 40447
           COALESCE(',' + NULLIF(SC.EmergencyState, ''), '') +
           COALESCE(',' + NULLIF(SC.EmergencyCountry, ''), '') +
            COALESCE(',' + NULLIF(SC.EmergencyZipCode, ''), '') +
            COALESCE(',' + NULLIF(SC.EmergencyContactNo, ''), ''),
           1, 1, '') AS EmergencyAddress ,
	  (SELECT STUFF( (SELECT DISTINCT ',' + CTM.Title FROM sStudent.tStudentCustomTag SCT INNER JOIN sStudent.tCustomTagMaster CTM ON SCT.CustomTagId=CTM.Id 
							WHERE SCT.StudentId = SA.StudentId FOR XML PATH ('')), 1, 1, '')  AS CustomTag FROM sStudent.tStudentMaster SM1 WHERE SM1.Id = SM.Id GROUP BY SM1.Id) AS CustomTag,
		STM.Title AS RecordTag,
		SC.IsStopApplicationAccess,
		CASE WHEN ISNULL(SO.DateOfBirth, '') = '' THEN '' ELSE (SELECT [sCommon].[fGetDateOfBirthInWord](SO.DateOfBirth)) END AS Age,
		RT.PickupPoint as PickupPoint,
		ISNULL(SA.LocalName, '') AS LocalName, -- Added for mantis : 34211
		ISNULL(RT.DropRoute, '') AS DropRoute, -- Added for mantis : 34483
		ISNULL(SA.PENNumber,0) AS PENNumber,    --Mantis - 35453
		 -- added by dhananjay for Mantis - 39234
		ISNULL(SF.FatherAdhaarNumber,'') AS FatherAdhaarNumber,
		ISNULL(SF.MotherAdhaarNumber,'') AS MotherAdhaarNumber,
		-- added by dhananjay for Mantis - 39234
		ISNULL(SA.ApaarIdNumber, '') AS ApaarIdNumber, -- add for mantis : 0040679
		ISNULL(SAD.PreviousLCResult,'') AS PreviousResult			-- Mantis Id : 0043737
		,CONVERT(VARCHAR(10), SAD.PreviousLCDate, 111) AS PreviousLCDate -- Mantis Id : 0045175	
		,ISNULL(SAD.PreviousLCNumber,'') AS PreviousLCNumber	-- Mantis Id : 0045175				

  FROM sStudent.vStudentAcademic SA
    INNER JOIN sStudent.tStudentMaster SM ON SM.Id = SA.StudentId
	LEFT JOIN sStudent.tStudentAdmission SAD ON SAD.StudentId=SA.StudentId
	LEFT JOIN sSetup.tClassMaster CM ON CM.Id=SAD.AdmissionStandardId
	LEFT JOIN sCommon.tAdmissionQuotaMaster AQM ON AQM.Id = SAD.AdmissionQuotaId
	LEFT JOIN sSetup.tBatchMaster BM ON BM.Id=SA.BatchId
	LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId=SA.StudentId
	LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId=SA.StudentId
	--LEFT JOIN sTransport.tAssignRoute AR ON AR.SourceId=SA.StudentId
	LEFT JOIN sCommon.tTransportModeMaster TM ON TM.Id=SO.TransportModeId
	LEFT JOIN sCommon.tGenderMaster GM ON GM.Id=SO.GenderId
	LEFT JOIN sCommon.tBloodGroupMaster BGM ON BGM.Id=SO.BloodGroupId
	LEFT JOIN sCommon.tCastCategoryMaster CCM ON CCM.Id=SO.CastCategoryId
	LEFT JOIN sCommon.tReligionMaster RM ON RM.Id=SO.ReligionId
	LEFT JOIN sActivity.tHouseMaster HM ON HM.Id=SO.HouseId
	LEFT JOIN sCommon.tMotherTongueMaster MTM ON MTM.Id=SO.MotherTongueId
	LEFT JOIN sCommon.tCountryMaster NM ON NM.Id=SO.NationalityId
	--LEFT JOIN sTransport.tBusRouteDestinationMaster BDM ON BDM.Id=AR.PickupDestinationId
	LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId=SA.StudentId
	LEFT JOIN sStudent.tStudentHealth SH ON SH.StudentId=SA.StudentId
	LEFT JOIN sStudent.tAdmissionCategoryMaster AC ON AC.Id=SA.AdmissionCategoryId
	LEFT JOIN sStudent.tAcademicDetail AD ON AD.AcademicId = SA.AcademicId
	LEFT JOIN sStudent.tStudentadditional ADI ON ADI.StudentId = SA.StudentId
	LEFT JOIN sStudent.tEnrollmentStatusMaster ESM ON ESM.Id = SM.EnrollmentStatusId
	LEFT JOIN sStudent.tStudentSibling SS ON SS.StudentId = SA.StudentId
	LEFT JOIN sHostel.tAssignRoom HAR ON HAR.SourceId = SM.Id AND HAR.OrgGroupBatchId = SA.OrgGroupBatchId
	LEFT JOIN sHostel.tRoomMaster HRM ON HRM.Id = HAR.RoomId
	LEFT JOIN sHostel.tBuildingMaster HBM ON HRM.BuildingId = HBM.Id 
	LEFT JOIN sHostel.tHostelMaster HHM ON HHM.Id = HRM.HostelId
	
	LEFT JOIN sStudent.tStudentGroupMaster SGM ON SGM.Id=SM.StudentGroupId
	LEFT JOIN sStudent.tStudentOtherGroupMaster SOGM ON SOGM.Id=SM.StudentOtherGroupId
	--LEFT JOIN sTransport.tBusRouteMaster BRM ON BRM.Id=BDM.BusRouteId
	LEFT JOIN sStudent.tCollegeDetail CD ON CD.StudentId = SA.StudentId
	LEFT JOIN sFee.tExemptionTypeMaster EX ON Ex.Id=SA.ExemptionTypeId
   LEFT JOIN
	(SELECT AR.SourceId,AR.DropDestinationId AS BusRouteDestinationId,BDM2.Title AS BusRouteDestination,AR.PickupDestinationId AS BusRoutePickupDestinationId,BDM.Title AS PickupPoint, ISNULL(BRM.Id,0) AS BusRouteId,
	  ISNULL(BDM.PickupTime,'') AS PickupTime,
	  ISNULL(BDM.Droptime,'') AS Droptime,
	  ISNULL(BRM.Title,'' )AS BusRoute,BRM.OrgGroupBatchId,
	  ISNULL(BRM2.Title,'') AS DropRoute FROM sTransport.tAssignRoute AR  -- Added for mantis : 34483
    INNER JOIN sTransport.tBusRouteDestinationMaster BDM ON BDM.Id=AR.PickupDestinationId
	LEFT JOIN sTransport.tBusRouteDestinationMaster BDM2 ON BDM2.Id=AR.DropDestinationId
    INNER JOIN sTransport.tBusRouteMaster BRM ON BRM.Id=BDM.BusRouteId AND  AR.SourceTypeId=2003
	LEFT JOIN sTransport.tBusRouteMaster BRM2 On BRM2.Id=BDM2.BusRouteId AND AR.SourceTypeId=2003 )  RT -- Added for mantis : 34483
    ON RT.SourceId = SA.StudentId     AND RT.OrgGroupBatchId =SA.OrgGroupBatchId
	INNER JOIN sCommon.tStatusMaster STM ON STM.Id = SA.RecordStatusId AND STM.StatusTypeId=102
	INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SA.OrgId
	INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id = SA.DepartmentId
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),
		@StudentPhoto NVARCHAR(Max),--Cr:0045386
		@Gender NVARCHAR(10),--Cr:0045386
		@LCCopyRemark NVARCHAR(Max),		-- Mantis Id : 0045738
		@ProofOfDOB NVARCHAR(100),
		@PENNumber VARCHAR(20),				-- Mantis Id : 0045843
		@ApaarIDNumber 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,''),
		@StudentPhoto = ISNULL(CAST('data:image/jpeg;base64,' AS NVARCHAR(MAX)) +
                      CAST(N'' AS XML).value('xs:base64Binary(xs:hexBinary(sql:column("StudentPhoto")))', 'NVARCHAR(MAX)'),''), --Cr:0045386
		@Gender = ISNULL([Gender],''),--Cr:0045386
		@LCCopyRemark = ISNULL(LCCopyRemark,''),
		@ProofOfDOB = ISNULL(ProofOfDOB,''),
		@PENNumber = CASE 
                    WHEN ISNULL(PENNumber, 0) = 0 THEN ''
                    ELSE CAST(PENNumber AS VARCHAR(20))
                 END,
		@ApaarIDNumber = ISNULL(ApaarIDNumber,'')
    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);
	SET @Template = REPLACE(@Template ,'[StudentPhoto]', @StudentPhoto);--Cr:0045386
	SET @Template = REPLACE(@Template ,'[Gender]', @Gender);--Cr:0045386
	SET @Template = REPLACE(@Template, '[LCCopyRemark]', @LCCopyRemark);
	SET @Template = REPLACE(@Template, '[ProofOfDOB]', @ProofOfDOB);
	SET @Template = REPLACE(@Template, '[PENNumber]', @PENNumber);
	SET @Template = REPLACE(@Template, '[ApaarIDNumber]', @ApaarIDNumber);

    RETURN @Template;
END;
GO
PRINT N'Altering Procedure [sAdmission].[pRptStudentNewAdmissionListGet]...';


GO

ALTER PROCEDURE [sAdmission].[pRptStudentNewAdmissionListGet]
	
	 @rBatchId int,
	 @rClassId int,
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='',
	 @rFromDate date,
	 @rToDate date,
	 @rOrgId int = 0,
	 @rDepartmentId int = 0,
	 @rDivisionId int,
	 @rStatusId int
AS
 SET NOCOUNT ON
			 

BEGIN 
  SELECT 
		@rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,
		SM.FirstName+' '+SM.MiddleName+' '+SM.LastName AS Name,
		SA.AdmissionDate,
		SM.Code,
		A.RollNo,
		CM.Title+'-'+DM.DisplayTitle As ClassDivision,
		CM.Title As Class,
		A.BatchId as Batch,
		SA.BatchId As AdmissionBatch,
		--AF.ContactNo AS ContactNo
		SC.ParentContactNo AS ContactNo,
		CM.OrderIndex AS ClassOrderIndex	--Mantis - 45173
  FROM 
		sStudent.tAcademic A 
		INNER JOIN sStudent.tStudentMaster SM ON A.StudentId=SM.Id
		INNER JOIN sStudent.tStudentAdmission SA ON SA.StudentId=SM.Id AND SA.BatchId = A.BatchId
		INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId  				 
		INNER JOIN sSetup.tClassMaster CM ON CM.Id=DM.ClassId
		--LEFT JOIN sAdmission.tAdmissionForm AF ON AF.StudentId=A.StudentId AND AF.BatchId=A.BatchId AND AF.OrgId=A.OrgId
		LEFT JOIN sStudent.tStudentCommunication SC ON SM.Id = SC.StudentId
  WHERE 	
		A.BatchId=@rBatchId 
		AND ((ISNULL(SA.AdmissionDate,'') >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
		AND ((ISNULL(SA.AdmissionDate,'') <= @rToDate) OR (ISNULL(@rToDate,'')=''))
		AND ((CM.DepartmentId=@rDepartmentId) OR (@rDepartmentId = 0))
		AND ((CM.Id=@rClassId) OR (@rClassId = 0))
		AND ((DM.Id=@rDivisionId) OR (@rDivisionId = 0))
		AND ((SM.StatusId=@rStatusId) OR (@rStatusId = 0))
END
GO
PRINT N'Altering Procedure [sAssessment].[pActivityIndicatorScoreAdd]...';


GO

ALTER PROCEDURE [sAssessment].[pActivityIndicatorScoreAdd]

			@rAcademicId bigint
			,@rExamId int
			,@rSubActivityId int
			,@rGrade nvarchar(10),
			@rGradeIndicator nvarchar(50)
			,@rDescriptiveIndicator nvarchar(200)
			,@rIndicatodIds nvarchar(50),
			@rMarks decimal(18,0)
			,@rIsIndicatodIds bit

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRANSACTION	--add for mantis: 39511
		IF NOT EXISTS(SELECT SubjectSubActivityId FROM sAssessment.tCCESubjectSubActivityExamScore WHERE SubjectSubActivityId=@rSubActivityId AND  AcademicId=@rAcademicId AND ExamId = @rExamId)
		BEGIN
			INSERT INTO sAssessment.tCCESubjectSubActivityExamScore
			(
				[ExamId]
				,[AcademicId],
				SubjectSubActivityId
				,[Grade]
				,[GradeIndicator]
				,[DescriptiveIndicator]
				,[IndicatorIds],
				Marks
			)
			VALUES
			(
				@rExamId
				,@rAcademicId
				,@rSubActivityId
				,@rGrade
				,@rGradeIndicator
				,@rDescriptiveIndicator
				,@rIndicatodIds,
				@rMarks
			)
		END
		ELSE
		BEGIN
			UPDATE  [sAssessment].[tCCESubjectSubActivityExamScore]
			SET
				[AcademicId]=@rAcademicId
				,[ExamId] =@rExamId
				,[Grade]=@rGrade
				,[GradeIndicator] =@rGradeIndicator
				,DescriptiveIndicator=@rDescriptiveIndicator
				,IndicatorIds = @rIndicatodIds,
				Marks= @rMarks
			WHERE SubjectSubActivityId=@rSubActivityId AND AcademicId=@rAcademicId AND ExamId =@rExamId
		END
		print @rIsIndicatodIds
		if @rIsIndicatodIds = 1
		BEGIN
			Declare @lQuery Nvarchar(max)
			SET @lQuery = 'UPDATE A SET A.DescriptiveIndicator = 
 							stuff((select '','' + B.Title from sAssessment.tCCESubjectSubActivityIndicatorMaster B
						WHERE A.SubjectSubActivityId=B.CCESubjectSubActivityId
								and '',''+ (replace(IndicatorIds,''.'','','') )+'','' like ''%,''+CAST(Number as varchar(10))+'',%'' 				
						for xml path('''')),1,1,'''') 
				 From sAssessment.tCCESubjectSubActivityExamScore A WHERE A.SubjectSubActivityId='+ CAST(@rSubActivityId AS NVARCHAR(50)) +' 
				 AND A.AcademicId= '+ CAST (@rAcademicId  AS NVARCHAR(50))+'
				  AND A.ExamId ='+ CAST(@rExamId AS NVARCHAR(50))

			EXECUTE (@lQuery)
			print @lQuery
		END

		SELECT 1 AS Result
	COMMIT TRANSACTION

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


GO

ALTER PROCEDURE [sAssessment].[pExamRemarkSetupGet]
          
   @rId int,
   @rTitle nvarchar(100),
   @rOrgId int,
   @rClassId int,
   @rExamId int,
   @rBatchId int=0          
          
AS
SET NOCOUNT ON

   SET @rTitle = sCommon.fSearchStringGet(@rTitle)

BEGIN
  SELECT 
	   ERS.Id as Id
	  ,ERS.Title as Title
	  ,ISNULL(ERS.Code,'') as Code
	  --,ISNULL(EM.DisplayTitle,'') AS ExamTitle
	  ,ISNULL(ESGM.Title,'') AS ExamTitle
	  ,ERS.ExamId AS ExamId
	  ,ISNULL(ERS.OrderIndex,0) AS OrderIndex
       ,ISNULL(EM.ClassId,0) AS ClassId
  FROM [sAssessment].[tExamRemarkSetup] ERS 
	   INNER JOIN [sAssessment].[tExamMaster] EM ON EM.Id = ERS.ExamId
	   --inner Join sAssessment.tExamGroupMaster EGM ON EGM.Id=EM.ExamSubGroupId 
	   INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.ID = EM.ExamSubGroupId
	   INNER JOIN sAssessment.tExamGroupMaster EGM ON EGM.Id=ESGM.ExamGroupId 
  WHERE 
	    ((ERS.Code Like @rTitle)OR(ISNULL(@rTitle,'') = '')) --ERS.Title to ERS.Code : mantis : 0045852
	    AND (ERS.ExamId=@rExamId OR @rExamId=0)
		AND EGM.OrgId = @rOrgId
		AND (ERS.Id = @rId  OR @rId = 0)
		AND(EM.ClassId=@rClassId OR @rClassId=0)
		AND (EM.BatchId=@rBatchId OR @rBatchId=0)
   Order by OrderIndex 
END
GO
PRINT N'Altering Procedure [sAttendance].[pHoliDayCountGet]...';


GO



ALTER PROCEDURE [sAttendance].[pHoliDayCountGet]
	
	@rMonth int=0,
	@rYear int=0,
	@rBatchId int=0,
	@rOrgId int=0,
	@rClassId int=0
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
	CREATE table #Table1 (Id bigint identity,FromDate Date,ToDate Date,DivId int,IsExists bit)
	
	CREATE table #Table2 (Id bigint identity,FromDate Date,ToDate Date,DivId int)
	
	INSERT INTO #Table2 
	SELECT 
	ES.FromDate, 
	ES.ToDate,0
	from sActivity.tEventSchedule ES
	INNER JOIN sActivity.tEventAssign EA ON EA.EventScheduleId = ES.Id
	INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = EA.SourceId
	INNER JOIN sSetup.tClassMaster CM ON CM.Id = DM.ClassId
	Where (MONTH(FromDate)<= @rMonth AND MONTH(ToDate) >= @rMonth) AND ES.IsHoliDay =1 
	AND (YEAR(FromDate)=@rYear AND YEAR(ToDate) = @rYear)
	AND EA.SourceTypeId = 2005 AND CM.Id = @rClassId
	AND ((ES.BatchId = @rBatchId)OR(@rBatchId=0))
	GROUP BY ES.FromDate,ES.ToDate
	  
	INSERT INTO #Table1 
	select FromDate,ToDate,Max(DivId),0
	from
	( 
	SELECT case when MONTH(FromDate)=@rMonth then FromDate
				when MONTH(FromDate)<>@rMonth and MONTH(ToDate)=@rMonth then DATEADD(DD,-Day(ToDate)+1,ToDate)
				when MONTH(FromDate)<@rMonth and MONTH(ToDate)>@rMonth then cast(rtrim(@rYear *10000+ @rMonth *100+ 01) as date) --mantis:28433
				else FromDate end as FromDate,
				ToDate,
				DivId	
	From #Table2
	GROUP BY  FromDate,ToDate,DivId
	)As Tmp
	GROUP BY  Tmp.FromDate,Tmp.ToDate,Tmp.DivId
	
	DECLARE @lTempCount int=0
	SELECT @lTempCount = count(Id) from #Table1
	WHILE @lTempCount > 0 
	BEGIN
		DECLARE @lFromDate Date,@lToDate Date

		SELECT @lFromDate = FromDate, @lToDate = ToDate FROM #Table1 WHERE Id=@lTempCount
		IF EXISTS(SELECT 1 FROM #Table1 WHERE Id <> @lTempCount AND ((@lFromDate between FromDate and ToDate) AND (@lToDate between FromDate and ToDate)))
		BEGIN
			UPDATE #Table1 SET IsExists = 1 WHERE Id = @lTempCount	
		END
		SET @lTempCount = @lTempCount - 1
	END

	 
	DECLARE @lCount int
	SELECT @lCount = count(Id) from #Table1
	DECLARE @lStatus nvarchar(5),@lFromYear int,@lFromMonth int,@lFromDay int,@lDivision int,@lToYear int,@lToMonth int,@lToDay int
	DECLARE @lHoliDayCount int,@lBeginCount int ,@lEndCount int , @lTotalMonth int 
	SET @lHoliDayCount =0
	
		WHILE @lCount > 0 
					BEGIN
						SELECT
							@lFromYear = YEAR(FromDate),
							@lFromMonth = MONTH(FromDate),
							@lFromDay = DAY(FromDate),
							@lToYear = YEAR(ToDate),
							@lToMonth = MONTH(ToDate),
							@lToDay = DAY(ToDate),
							@lDivision = DivId,
							@lBeginCount = DAY(FromDate),
							@lEndCount = DAY(ToDate)
						FROM #Table1 T WHERE Id = @lCount AND IsExists = 0
					
						IF(@lFromDay = @lToDay  AND @lFromMonth = @lToMonth)
						BEGIN
							
							SELECT @lStatus = [sAttendance].[fWeekHOffGet]
							(@lFromYear,@lFromMonth,@lFromDay,@rBatchId,@rClassId,@lDivision,'',@rOrgId)
							IF(@lStatus = 'H')SET @lHoliDayCount=@lHoliDayCount+1
							
							
						END
						ELSE --IF(@lFromDay != @lToDay)		-- Mantis Id : 0045421
						BEGIN
							IF(@lFromMonth = @lToMonth)
							BEGIN
								WHILE (@lBeginCount <= @lEndCount)
								BEGIN
								  
									SELECT @lStatus = [sAttendance].[fWeekHOffGet] 	(@lFromYear,@lFromMonth,@lBeginCount,@rBatchId,@rClassId,@lDivision,'',@rOrgId)
									IF(@lStatus = 'H')
										SET @lHoliDayCount=@lHoliDayCount+1
									
									SET @lBeginCount = @lBeginCount +1	
							   END
							END
							ELSE
							BEGIN
								SET @lTotalMonth = @lToMonth - @lFromMonth
								 WHILE (@lTotalMonth > 0 AND @rMonth=@lFromMonth)
								 BEGIN
									 DECLARE @lDays int = 0
									 SELECT @lDays = sCommon.fGetDaysInMonth(@lFromMonth,@lFromYear)
									 WHILE (@lBeginCount  <= @lDays)
									 BEGIN
										
										SELECT @lStatus = [sAttendance].[fWeekHOffGet] 	(@lFromYear,@lFromMonth,@lBeginCount,@rBatchId,@rClassId,@lDivision,'',@rOrgId)
										IF(@lStatus = 'H')
											SET @lHoliDayCount=@lHoliDayCount+1
											
										SET @lBeginCount = @lBeginCount +1
									END
									SET @lTotalMonth = @lTotalMonth-1
								 END
							END
						END
						SET @lCount = @lCount - 1
					END
	SELECT @lHoliDayCount
	DROP TABLE #Table1
	DROP TABLE #Table2
END
GO
PRINT N'Altering Procedure [sAttendance].[pRptAttendanceSubjectwiseGet]...';


GO

ALTER PROCEDURE [sAttendance].[pRptAttendanceSubjectwiseGet]  
         
   @rBuilder1 nvarchar(max)='',  
   @rBuilder2 nvarchar(max)='',   
   @rOrgId smallint,  
   @rBatchId int,  
   @rClassId int,  
   @rDivisionId int,  
   @rSubjectId int,  
   @rFromDate date,  
   @rToDate date,  
   @rStudentCode nvarchar(20),  
   @rReportId int,  
   @rDepartmentId int,  
   @rStatusId int=0  
      
 WITH EXECUTE AS CALLER  
AS  
SET NOCOUNT ON  
BEGIN  
SET @rToDate = DATEADD (d,1,@rToDate)  
 Select   
  @rBuilder1 AS Builder1,  
  @rBuilder2 AS Builder2,  
  SA.AcademicId,  
  SA.Name,  
  SA.Code,  
  SA.RollNo,  
  SA.ClassId,  
  SA.ClassName,  
  SA.DivisionId,  
  SA.DivisionName,  
  SR.AttendanceDate,  
  --SA.TotalCount,  
  --SA.PresentCount,  
  --SA.AbsentDays,  
  --SA.AbsentCount,  
  ISNULL(SM.Id,0) AS SubjectId,  
  ISNULL(SM.Code,'') AS SubjectCode,  
  ISNULL(SM.Title,'') AS SubjectName,  
  ISNULL(SR.PeriodNo,'') As PeriodNo,
  --CAST(ISNULL(SR.IsPresent,'') as int) AS IsPresent
  
  --case when SR.IsPresent = 1 then 1 when SR.IsPresent = 0 then 0 else '' end AS IsPresent,
  SR.IsPresent,		-- Mantis Id : 0045546
  -- Commented for mantis : 38791
  --EMP.FirstName + ' ' + EMP.LastName  AS EmployeeNameSubjectwise--Added by dhananjay for mantis  - 37271
  ISNULL(U.DisplayTitle, '') AS EmployeeNameSubjectwise -- Added for mantis : 38791

 
   
 FROM   
	sAttendance.tStudentRegister SR    
	INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=SR.AcademicId  
	INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=SR.SubjectId 
	--Added by dhananjay for mantis start - 37271
	INNER JOIN sSecurity.tUser U ON U.Id = SR.CreatedUserId --AND SourceTypeId = 95
	--INNER JOIN sHrm.tEmployeeMaster EMP on EMP.Id = U.SourceId -- Commented for mantis : 38791
	--Added by dhananjay for mantis end - 37271

 WHERE  
	((SR.SubjectId=@rSubjectId) OR (@rSubjectId=0))  
	AND (SA.OrgId=@rOrgId)  
	AND (SA.BatchId = @rBatchId)   
	AND ((SA.ClassId=@rClassId) OR (@rClassId=0))  
	AND ((SA.DivisionId=@rDivisionId) OR (@rDivisionId=0))  
	----AND ((SR.AttendanceTypeId=@rAttendanceTypeId) OR (@rAttendanceTypeId=0))  
	AND ((SR.AttendanceDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))  
	AND ((SR.AttendanceDate < @rToDate) OR (ISNULL(@rToDate,'')=''))  
	--AND ((SA.AcademicId=@rAcademicId) OR (@rAcademicId=0))  
	AND ((@rReportId = 20463 AND SR.IsPresent = 1) OR (@rReportId = 20466 AND SR.IsPresent = 0) 
	OR (@rReportId = 30718)
	OR (@rReportId = 30903)
	OR (@rReportId = 30924))  
	AND SR.AttendanceTypeId = 5  
	AND ((SA.Code=@rStudentCode) OR (@rStudentCode=''))  
	AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))  
	AND ((SA.StatusID=@rStatusId) OR (@rStatusId=0))  
	--AND (SA.StatusId != 3)  
   
END
GO
PRINT N'Altering Procedure [sAttendance].[pRptStudentMonthlyRegisterGet]...';


GO
ALTER PROCEDURE [sAttendance].[pRptStudentMonthlyRegisterGet]
	 
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 @rOrgId smallint,
	 @rBatchId int,
	 @rClassId int,
	 @rDivisionId int,
	 @rAttendanceTypeId tinyint=0,
	 @rSubjectId int=0,
	 @rForYear smallint,
	 @rForMonth tinyint,
	 @rStudentCode nvarchar(20)='',
	 @rDepartmentId int,
	 @rFromAverage decimal(5,2) = 0,
	 @rToAverage decimal(5,2) = 0,
	 @rIsDetail bit=0,
	 @rReportId int = 0,
	 @rStatus smallint = 0
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
--Added ((@rReportId <> 31414))by dhananjay for mantis : 39584
	IF((@rReportId <> 10132) AND (@rReportId <> 10131) AND (@rReportId <> 31414))     --Mantis 30087
	BEGIN
	SELECT 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			@rIsDetail AS IsDetail,
			SA.AcademicId,
			SA.ClassId,
			SA.DivisionId,
			SA.ClassName,
			SA.DivisionName,
			SA.ClassName+' - '+SA.DivisionName AS ClassDivision,
			SA.Code,
			SA.RollNo,			
			SA.Name,
			MR.ForMonth,
			MR.ForYear,
			M.Code +' - '+Convert(nvarchar(4),MR.ForYear) AS ForMonthYear,
			MR.TotalCount,
			ISNULL(MR.AttendanceCount,0) AS AttendanceCount,
			MR.PresentCount,
			MR.AbsentCount,
			MR.AveragePresence,
			MR.AbsentDays,
			ISNULL(SO.DateOfBirth,NULL) AS DateOfBirth,
			SM.Title AS SubjectName,
			SA.DivisionOrder
			
	FROM 
			sStudent.vStudentAcademic SA
        INNER JOIN sStudent.tStudentOther SO ON SA.StudentId = SO.StudentId 			
		INNER JOIN sAttendance.tMonthlyRegister MR ON MR.AcademicId=SA.AcademicId
		LEFT JOIN sSetup.tSubjectMaster SM ON SM.Id=MR.SubjectId
		INNER JOIN sCommon.tMonthMaster M ON MR.ForMonth = M.Id
		INNER JOIN sSetup.tBatchClass BC ON BC.ClassID =  SA.ClassID and BC.BatchId= @rBatchId
	WHERE 
			(SA.OrgId=@rOrgId)
		AND	(SA.BatchId = @rBatchId) 
		AND ((SA.ClassId=@rClassId) OR (@rClassId=0))
		AND ((SA.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		AND ((MR.AttendanceTypeId=@rAttendanceTypeId) OR (@rAttendanceTypeId=0))
		AND ((MR.SubjectId=@rSubjectId) OR (@rSubjectId=0))
		AND ((MR.ForYear=@rForYear) OR (@rForYear=0))
		AND ((MR.ForMonth=@rForMonth) OR (@rForMonth=0))
		AND (SA.StatusId != 3)
		AND ((SA.Code=@rStudentCode) OR (@rStudentCode=''))
		AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
		AND ((MR.AveragePresence >= @rFromAverage) OR (@rFromAverage=0))
		AND ((MR.AveragePresence <= @rToAverage) OR (@rToAverage=0))
	END
	ELSE 
	BEGIN
	--start : mantis : 0045248
	;WITH StudentAverageCTE AS (
    SELECT 
        SA.AcademicId,
        CAST(ROUND(AVG(MR.AveragePresence), 2) AS decimal(5,2)) AS StudentAvgPresence
    FROM 
        sStudent.vStudentAcademic SA
        INNER JOIN sAttendance.tMonthlyRegister MR ON MR.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 ((MR.AttendanceTypeId = @rAttendanceTypeId) OR (@rAttendanceTypeId = 0))
        AND ((MR.SubjectId = @rSubjectId) OR (@rSubjectId = 0))
        AND ((MR.ForYear = @rForYear) OR (@rForYear = 0))
        AND ((MR.ForMonth = @rForMonth) OR (@rForMonth = 0))
        AND ((SA.StatusId = @rStatus) OR (@rStatus = 0))
        AND ((SA.Code = @rStudentCode) OR (@rStudentCode = ''))
        AND ((SA.DepartmentId = @rDepartmentId) OR (@rDepartmentId = 0))
    GROUP BY SA.AcademicId
    --HAVING 
    --    (AVG(MR.AveragePresence) >= @rFromAverage OR @rFromAverage = 0)
    --    AND (AVG(MR.AveragePresence) <= @rToAverage OR @rToAverage = 0)
)
--end : mantis : 0045248
		SELECT 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			@rIsDetail AS IsDetail,
			SA.AcademicId,
			SA.ClassId,
			SA.DivisionId,
			SA.ClassName,
			SA.DivisionName,
			SA.ClassName+' - '+SA.DivisionName AS ClassDivision,
			SA.Code,
			SA.RollNo,			
			SA.Name,
			MR.ForMonth,
			MR.ForYear,
			M.Code +' - '+Convert(nvarchar(4),MR.ForYear) AS ForMonthYear,
			MR.TotalCount,
			ISNULL(MR.AttendanceCount,0) AS AttendanceCount,
			MR.PresentCount,
			MR.AbsentCount,
			MR.AveragePresence,
			MR.AbsentDays,
			ISNULL(SO.DateOfBirth,NULL) AS DateOfBirth,
			SM.Title AS SubjectName,
			SA.DivisionOrder
			--,AVG(MR.AveragePresence) OVER() AS AveragePresenceAvg
			,CAST(SAvg.StudentAvgPresence AS decimal(5,2))--mantis : 0045248
	FROM 
			sStudent.vStudentAcademic SA
        INNER JOIN sStudent.tStudentOther SO ON SA.StudentId = SO.StudentId 			
		INNER JOIN sAttendance.tMonthlyRegister MR ON MR.AcademicId=SA.AcademicId
		LEFT JOIN sSetup.tSubjectMaster SM ON SM.Id=MR.SubjectId
		INNER JOIN sCommon.tMonthMaster M ON MR.ForMonth = M.Id
		INNER JOIN sSetup.tBatchClass BC ON BC.ClassID =  SA.ClassID and BC.BatchId= @rBatchId
		INNER JOIN StudentAverageCTE SAvg ON SA.AcademicId = SAvg.AcademicId --mantis : 0045248
	WHERE 
			(SA.OrgId=@rOrgId)
		AND	(SA.BatchId = @rBatchId) 
		AND ((SA.ClassId=@rClassId) OR (@rClassId=0))
		AND ((SA.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		AND ((MR.AttendanceTypeId=@rAttendanceTypeId) OR (@rAttendanceTypeId=0))
		AND ((MR.SubjectId=@rSubjectId) OR (@rSubjectId=0))
		AND ((MR.ForYear=@rForYear) OR (@rForYear=0))
		AND ((MR.ForMonth=@rForMonth) OR (@rForMonth=0))
		AND ((SA.StatusId = @rStatus) OR (@rStatus = 0))
		AND ((SA.Code=@rStudentCode) OR (@rStudentCode=''))
		AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
		--mantis : start : 0045248
		AND (((@rReportId IN (10132, 10131)) 
			AND ((SAvg.StudentAvgPresence >= @rFromAverage) OR (@rFromAverage = 0))
			AND ((SAvg.StudentAvgPresence <= @rToAverage) OR (@rToAverage = 0)))
		OR
		((@rReportId NOT IN (10132, 10131)) 
			AND ((MR.AveragePresence >= @rFromAverage) OR (@rFromAverage = 0))
			AND ((MR.AveragePresence <= @rToAverage) OR (@rToAverage = 0))
		))
		--mantis : end : 0045248
	END
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].[pRptEmployeeTimesheetInOutListGet]...';


GO
ALTER PROCEDURE [sBiometric].[pRptEmployeeTimesheetInOutListGet]
		@rBuilder1 nvarchar(max),
		@rBuilder2 nvarchar(max),
		@rOrgId int,
		@rDepartmentId int,
		@rOrgGroupDepartmentId int,
		@rForYear int,
		@rForMonth int,
		@rEmployeeStatusId int,
		@rEmployeeId bigint,
		@rBatchId int	--Mantis - 45609

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	DECLARE @lCount int=0, @lFirstDate date='', @lLasteDate date='', @Query nvarchar(max)='', @lDay nvarchar(2)='', @lAttendanceDate date=''
	--SET @lFirstDate = DATEFROMPARTS(@rForYear, @rForMonth, 1)
	--SET @lLasteDate = EOMONTH(DATEFROMPARTS(@rForYear, @rForMonth, 1))
	--SET @lCount = DAY(EOMONTH(DATEFROMPARTS(@rForYear, @rForMonth, 1)))

	SET @lFirstDate = CONVERT(date, (CONVERT(varchar(4),@rForYear) + '-' + RIGHT('0' + CONVERT(varchar(2),@rForMonth), 2) + '-01'))
	SET @lLasteDate = DATEADD(DAY,-1,DATEADD(MONTH, 1,@lFirstDate))
	SET @lCount = DAY(@lLasteDate)

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

	CREATE TABLE #tmpBiometricData
	(
		EmployeeId bigint,
		EmployeeCode nvarchar(max),
		EmployeeName nvarchar(max),
		Attn_Date DateTime,
		PresentStatus nvarchar(15),
		FirstIn nvarchar(20),
		LastOut nvarchar(20),
		OverTime nvarchar(20),
		LateBy nvarchar(20),
		Duration nvarchar(20),
		EarlyBy nvarchar(20),
		ShiftName nvarchar(25),
		EmployeeDesignationId int,
		OrganizationDepartmentId int,
		OrgGroupDepartmentID int
	)

	WHILE (@lCount>0)
	BEGIN
		--SET @lDay = format(@lCount,'00')
		SET @lDay = RIGHT('0' + CONVERT(varchar(2),@lCount), 2)
		SET @lAttendanceDate = CAST(RTRIM(CONVERT(nvarchar(4),@rForYear) *10000+ CONVERT(nvarchar(2),@rForMonth) *100+ CONVERT(nvarchar(2),@lDay)) AS datetime)


		SET @Query = 
		'INSERT INTO #tmpBiometricData
		SELECT EM.Id AS EmployeeId, EM.Code AS EmployeeCode, ISNULL(EM.FirstName,'''') + '' '' + ISNULL(EM.MiddleName,'''') + '' '' + ISNULL(EM.LastName,'''') AS EmployeeName,
			ISNULL(CAST(RTRIM(YEAR(MT.Attn_Dt) *10000+ MONTH(MT.Attn_Dt) *100+ '+CONVERT(nvarchar(2),@lDay)+') AS datetime),CAST(RTRIM('+CONVERT(nvarchar(4),@rForYear)+' *10000+ '+CONVERT(nvarchar(2),@rForMonth)+' *100+ '+CONVERT(nvarchar(2),@lDay)+') AS datetime)) AS Attn_Date,
		/*Mantis Start - 45609*/
			CASE When (([sHrm].[fWeekHOffGetBio](EM.Id, '+convert(nvarchar(15),@rForYear)+' ,'+convert(nvarchar(15),@rForMonth)+' ,'+convert(nvarchar(15),@lDay)+' ,'+convert(nvarchar(15), @rBatchId)+' ,OrganizationDepartmentId ,'+convert(nvarchar(15),@rOrgId)+' )=''H'') AND (ISNULL(D'+convert(nvarchar(15),@lDay)+'_IN,''00:00'') !=''00:00''))  then ''PH''
			 When (([sHrm].[fWeekHOffGetBio](EM.Id , '+convert(nvarchar(15),@rForYear)+' ,'+convert(nvarchar(15),@rForMonth)+' ,'+convert(nvarchar(15),@lDay)+' ,'+convert(nvarchar(15), @rBatchId)+' ,OrganizationDepartmentId ,'+convert(nvarchar(15),@rOrgId)+' )=''H'') AND (ISNULL(D'+convert(nvarchar(15),@lDay)+'_IN,''00:00'')=''00:00'')) THEN ''H''  
			 When (([sHrm].[fWeekHOffGetBio](EM.Id , '+convert(nvarchar(15),@rForYear)+' ,'+convert(nvarchar(15),@rForMonth)+' ,'+convert(nvarchar(15),@lDay)+' ,'+convert(nvarchar(15), @rBatchId)+' ,OrganizationDepartmentId ,'+convert(nvarchar(15),@rOrgId)+' )=''W'') AND (ISNULL(D'+convert(nvarchar(15),@lDay)+'_IN,''00:00'') !=''00:00''))  then ''PW''
			 When (([sHrm].[fWeekHOffGetBio](EM.Id , '+convert(nvarchar(15),@rForYear)+' ,'+convert(nvarchar(15),@rForMonth)+' ,'+convert(nvarchar(15),@lDay)+' ,'+convert(nvarchar(15), @rBatchId)+' ,OrganizationDepartmentId ,'+convert(nvarchar(15),@rOrgId)+' )=''W'') AND (ISNULL(D'+convert(nvarchar(15),@lDay)+'_IN,''00:00'') =''00:00''))  then ''W''
			 When ((ISNULL(D'+convert(nvarchar(15),@lDay)+',''XX'')=''W'')AND ([sHrm].[fWeekHOffGetBio](EM.Id , '+convert(nvarchar(15),@rForYear)+' ,'+convert(nvarchar(15),@rForMonth)+' ,'+convert(nvarchar(15),@lDay)+' ,'+convert(nvarchar(15), @rBatchId)+' ,OrganizationDepartmentId ,'+convert(nvarchar(15),@rOrgId)+' )!=''W'') AND (ISNULL(D'+convert(nvarchar(15),@lDay)+'_IN,''00:00'') !=''00:00''))  then ''P''
			 When ((ISNULL(D'+convert(nvarchar(15),@lDay)+',''XX'')=''PW'')AND ([sHrm].[fWeekHOffGetBio](EM.Id , '+convert(nvarchar(15),@rForYear)+' ,'+convert(nvarchar(15),@rForMonth)+' ,'+convert(nvarchar(15),@lDay)+' ,'+convert(nvarchar(15), @rBatchId)+' ,OrganizationDepartmentId ,'+convert(nvarchar(15),@rOrgId)+' )!=''W'') AND (ISNULL(D'+convert(nvarchar(15),@lDay)+'_IN,''00:00'') !=''00:00''))  then ''P''
			 When ((ISNULL(D'+convert(nvarchar(15),@lDay)+',''XX'')=''W'')AND ([sHrm].[fWeekHOffGetBio](EM.Id , '+convert(nvarchar(15),@rForYear)+' ,'+convert(nvarchar(15),@rForMonth)+' ,'+convert(nvarchar(15),@lDay)+' ,'+convert(nvarchar(15), @rBatchId)+' ,OrganizationDepartmentId ,'+convert(nvarchar(15),@rOrgId)+' )!=''W'') AND (ISNULL(D'+convert(nvarchar(15),@lDay)+'_IN,''00:00'') =''00:00''))  then ''A''
			 WHEN ((ISNULL(D'+convert(nvarchar(15),@lDay)+',''XX'')=''W'') AND (ISNULL(D'+convert(nvarchar(15),@lDay)+'_IN,''00:00'') !=''00:00'')) THEN ''PW''
			 When ((ISNULL(D'+convert(nvarchar(15),@lDay)+',''XX'')=''XX'')AND (Cast('''+convert(nvarchar(15),@lAttendanceDate)+''' as date)<GETDATE()) And (cast(EJD.DateOfJoining as date)<= Cast('''+convert(nvarchar(15),@lAttendanceDate)+''' as date) OR ISNULL(EJD.DateOfJoining,'''')='''')AND (EJD.DateOfleaving>= Cast('''+convert(nvarchar(15),@lAttendanceDate)+''' as date) OR ISNULL(EJD.DateOfleaving,'''')='''') AND (ISNULL(D'+convert(nvarchar(15),@lDay)+'_IN,''00:00'') =''00:00''))  then ''A''
			 ELSE
			 ISNULL(D'+convert(nvarchar(15),@lDay)+',''XX'') END as PresentStatus,
		 /*Mantis End - 45609(Old : D'+CONVERT(nvarchar(2),@lDay)+' AS PresentStatus)*/
			D'+CONVERT(nvarchar(2),@lDay)+'_IN AS FirstIn,
			D'+CONVERT(nvarchar(2),@lDay)+'_OUT AS LastOut,
			D'+CONVERT(nvarchar(2),@lDay)+'_O AS OverTime,
			D'+CONVERT(nvarchar(2),@lDay)+'_L AS LateBy,
			D'+CONVERT(nvarchar(2),@lDay)+'_T AS Duration,
			D'+CONVERT(nvarchar(2),@lDay)+'_E AS EarlyBy,
			D'+CONVERT(nvarchar(2),@lDay)+'_S AS ShiftName,
			EJD.EmployeeDesignationId,
			EJD.OrganizationDepartmentId, 
			EJD.OrgGroupDepartmentID
		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('+CONVERT(nvarchar(4),@rForYear)+' *10000+ '+CONVERT(nvarchar(2),@rForMonth)+' *100+ 01) AS datetime) AND MT.Attn_Dt <= CAST(RTRIM('+CONVERT(nvarchar(4),@rForYear)+' *10000+ '+CONVERT(nvarchar(2),@rForMonth)+' *100+ 01) AS datetime)
		WHERE (EM.Id = '+CONVERT(nvarchar(max),@rEmployeeId)+' OR '+CONVERT(nvarchar(max),@rEmployeeId)+' = 0)
			AND (EM.OrgId = '+CONVERT(nvarchar(4),@rOrgId)+' OR '+CONVERT(nvarchar(4),@rOrgId)+' = 0)
			AND (EJD.DateOfJoining<= '''+CONVERT(nvarchar(max),@lLasteDate)+''')
			AND ((EJD.DateOfleaving>= '''+CONVERT(nvarchar(max),@lFirstDate)+''') OR ISNULL(EJD.DateOfleaving,'''')='''')
			AND (ISNULL(MT.SourceTypeId,95) = 95 OR MT.SourceTypeId = 0)
			AND (EM.StatusId='+CONVERT(nvarchar(max),@rEmployeeStatusId)+' OR '+CONVERT(nvarchar(max),@rEmployeeStatusId)+'=0)'

		--print @Query
		EXEC(@Query)
		SET @lCount = @lCount-1
	END

	SELECT @rBuilder1 AS Builder1, @rBuilder2 AS Builder2, TMP.EmployeeId, TMP.EmployeeCode, TMP.EmployeeName, TMP.Attn_Date,
		ISNULL(CONVERT(varchar(5),SM.StartTime,114),'00:00') AS ShiftStartTime, ISNULL(CONVERT(varchar(5),SM.EndTime,114),'00:00') AS ShiftEndTime, 
		ISNULL(CONVERT(varchar(5),CONVERT(time,SM.ShiftDur),114),'00:00') AS ShiftHours, 
		ISNULL(TMP.FirstIn,'00:00') AS FirstIn, ISNULL(TMP.LastOut,'00:00')LastOut,
		CASE WHEN ISNULL(LastOut,'00:00')<>'00:00' THEN CONVERT(varchar(5), CAST(ISNULL(LastOut,'00:00') AS datetime) - CAST(ISNULL(FirstIn,'00:00') AS datetime), 114)
			ELSE '00:00' END AS Hours,
		[sBiometric].[fEmployeeLeaveTypeGet] (TMP.Attn_Date,TMP.EmployeeId) AS LeaveStatus,
		CASE WHEN ISNULL(FirstIn,'00:00')<>'00:00' AND ISNULL(SM.StartTime,'00:00')<>'00:00' AND ISNULL(FirstIn,'00:00')>ISNULL(SM.StartTime,'00:00') THEN CONVERT(varchar(5), CAST(ISNULL(FirstIn,'00:00') AS datetime) - CAST(ISNULL(SM.StartTime,'00:00') AS datetime), 114)
			ELSE '' END AS LateIn,
		CASE WHEN ISNULL(LastOut,'00:00')<>'00:00' AND ISNULL(SM.EndTime,'00:00')<>'00:00' AND ISNULL(LastOut,'00:00')>ISNULL(SM.EndTime,'00:00') THEN CONVERT(varchar(5), CAST(ISNULL(LastOut,'00:00') AS datetime) - CAST(ISNULL(SM.EndTime,'00:00') AS datetime), 114)
			ELSE '' END AS LateOut,
		CASE WHEN ISNULL(FirstIn,'00:00')<>'00:00' AND ISNULL(SM.StartTime,'00:00')<>'00:00' AND ISNULL(SM.StartTime,'00:00')>ISNULL(FirstIn,'00:00') THEN CONVERT(varchar(5), CAST(ISNULL(SM.StartTime,'00:00') AS datetime) - CAST(ISNULL(FirstIn,'00:00') AS datetime), 114)
			ELSE '' END AS EarlyIn,		
			CASE WHEN ISNULL(LastOut,'00:00')<>'00:00' AND ISNULL(SM.EndTime,'00:00')<>'00:00' AND ISNULL(SM.EndTime,'00:00')>ISNULL(LastOut,'00:00') THEN CONVERT(varchar(5), CAST(ISNULL(SM.EndTime,'00:00') AS DATETIME) - CAST(ISNULL(LastOut,'00:00') AS DATETIME), 114)
			ELSE '' END AS EarlyOut,
		EDM.Title AS EmployeeDesignation,
		DM.Title AS DepartmentName,
		OGD.Title AS OrgGroupDepartmentName,
		ISNULL(TMP.PresentStatus,'') AS PresentStatus	--Mantis - 45609
	FROM #tmpBiometricData TMP LEFT JOIN sBiometric.tShiftMasterCloud SM ON SM.ShiftName=TMP.ShiftName
		INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id=TMP.OrganizationDepartmentId
		LEFT JOIN sCommon.tOrgGroupDepartmentMaster OGD ON OGD.Id=TMP.OrgGroupDepartmentId
		LEFT JOIN sHrm.tEmployeeDesignationMaster EDM ON EDM.Id=TMP.EmployeeDesignationId
	WHERE (DM.Id=@rDepartmentId OR @rDepartmentId=0)
		and (OGD.Id=@rOrgGroupDepartmentId OR @rOrgGroupDepartmentId=0)

	DROP TABLE #tmpBiometricData

	--SELECT 
	--	'' AS Builder1,
	--	'' AS Builder2,
	--	CONVERT(bigint,0) AS EmployeeId,
	--	'' AS EmployeeCode,
	--	'' AS EmployeeName,
	--	CONVERT(date,'') AS Attn_Date,
	--	'' AS ShiftStartTime,
	--	'' AS ShiftEndTime,
	--	'' AS ShiftHours,
	--	'' AS FirstIn,
	--	'' AS LastOut,
	--	'' AS Hours,
	--	'' AS LeaveStatus,
	--	'' AS LateIn,
	--	'' AS LateOut,
	--	'' AS EarlyIn,
	--	'' AS EarlyOut,
	--	'' AS EmployeeDesignation,
	--	'' AS DepartmentName,
	--	'' AS OrgGroupDepartmentName,
	--  '' AS PresentStatus --Mantis - 45609

END
GO
PRINT N'Altering Procedure [sCertificate].[pBonafideGet]...';


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

BEGIN 
	 IF @rIsSearch = 1
		BEGIN
			SET @rCode = sCommon.fSearchStringGet(@rCode)
			SET @rName = sCommon.fSearchStringGet(@rName)
		END
	
	SELECT 
	
			BC.Id,
			BC.AcademicId,
			SA.Code,
			SA.Name,
			SA.ClassName+'-'+SA.DivisionName as ClassDivision,
			BC.Number,
			BC.BonafideDate,
			BC.Remark,
			ISNULL(BC.BonafiedReason,'') AS BonafiedReason
			
  FROM 
            sCertificate.tBonafide BC
       INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=BC.AcademicId AND SA.OrgId=@rOrgId AND SA.BatchId=@rBatchId
  WHERE 
  
	((BC.Id = @rId) OR (@rId = 0))
	AND ((SA.Code like @rCode) OR (ISNULL(@rCode,'') = ''))
	AND ((SA.Name like @rName) OR (ISNULL(@rName,'') = ''))
	AND ((BC.Number >= @rFromNo) OR (@rFromNo=0))
	AND ((BC.Number <= @rToNo) OR (@rToNo=0))
	AND ((BC.BonafideDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
	AND ((BC.BonafideDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
	AND (SA.ClassId = @rClassId OR @rClassId = 0)
	AND (SA.DivisionId = @rDivisionId OR @rDivisionId = 0)
	ORDER BY BC.BonafideDate DESC,BC.Number -- 45624 - Add BC.BonafideDate DESC
END
GO
PRINT N'Altering Procedure [sCertificate].[pRptBonafiedCertificateGet]...';


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

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

DECLARE @lConfigValue nvarchar(50)
Declare @lIDConfigValue nvarchar(50)='',@lOrgGroupId int=0


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

			ISNULL(U.DisplayTitle,'') AS UserName ,
		
		    ISNULL(EM.FirstName,'') +' '+ISNULL(EM.LastName,'') AS PrincipalName,
			ISNULL(CM.ClassNameInWord,'') AS ClassNameInWord,
			CM2.Title AS LeftStandard,
			CAST((CASE WHEN SI.QRCode IS NULL THEN 0 ELSE 1 END) AS bit) AS IsDisplayQRCode,			--add for 27638 mantis
			ISNULL(SI.QRCode,'') AS QRCode,							--add for 27638 mantis
			SA.LeftDate AS LeftDate,	
			SM.PENNumber, -- add for Mentis : 0033432
			ISNULL(SO.BirthCountry,'') AS BirthCountry,--added by dhananjay for mantis id : 0035561
			ISNULL(SM.LocalName,'')	AS LocalName,  -- add for mantis : 0035669
			B.Number as BonafideNumber,  --Mantis - 35686
			STM.Title AS Stream, -- Added by dhannajay for mantis - 36807
			B.CreatedDateTime, -- add for mantis : 0039370
			ISNULL(SA.PreviousStandard,'') AS PreviousStandard,  --Mantis - 40321
			ISNULL(SM.ApaarIdNumber,'') AS ApaarIdNumber		--Mantis - 40718
			,ISNULL(SO.MotherTongue,'') AS MotherTongue--mantis : 0042384	

	FROM 
			sCertificate.tBonafide B
			
			INNER JOIN sStudent.tAcademic A ON B.AcademicId=A.Id
			LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId=A.StudentId
			INNER JOIN sStudent.tStudentMaster SM ON SM.Id=A.StudentId
			LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId=A.StudentId
			INNER JOIN sSetup.tDivisionMaster DM ON A.DivisionId = DM.Id  
			INNER JOIN sSetup.tClassMaster CM ON CM.Id= DM.ClassId
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id=A.BatchId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=A.OrgId
			left JOIN sSetup.tOrgImages OI ON OI.OrgId = OM.Id
			INNER JOIN sSetup.tAffiliationMaster AM ON OM.AffiliationId = AM.Id
			INNER JOIN sSetup.tAffiliationTypeMaster ATM ON AM.AffiliationTypeId = ATM.Id
			LEFT JOIN sCommon.tReligionMaster RM ON SO.ReligionId=RM.Id
			LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId = SM.Id
			INNER JOIN sStudent.tStudentAdmission SA ON SA.StudentId = SM.Id
			LEFT JOIN sSetup.tClassMaster CM1 ON CM1.Id = SA.AdmissionStandardId
			INNER JOIN sSetup.tDepartmentMaster DP ON CM.DepartmentId = DP.Id
			LEFT JOIN sCommon.tCastCategoryMaster CT ON CT.Id = SO.CastCategoryId
			LEFT JOIN sStudent.tStudentCommunication C ON C.StudentId = A.StudentId
			LEFT JOIN sCommon.tCountryMaster CTM ON CTM.Id=SO.NationalityId
			LEFT JOIN SHostel.tAssignRoom Ar On Ar.SourceId=A.StudentId AND Ar.OrgGroupBatchId=@rOrgGroupBatchId 
			LEFT JOIN sCommon.tReportRemarkGroupOrg RRG ON RRG.OrgId = OM.Id AND ReportRemarkGroupId=6
			LEFT JOIN sHrm.tEmployeeImages EI ON EI.EmployeeId = DM.InchargeEmployeeId 
			LEFT JOIN sSecurity.tUser U	ON U.Id=B.CreatedUserId

			Left join sHrm.tEmployeeMaster EM on EM.Id = OM.EmployeeId
			LEFT JOIN sSetup.tClassMaster CM2 ON CM2.Id = SA.LeftStandardId
			--INNER JOIN sSetup.tTermMaster TM ON  TM.ID=
			INNER JOIN sSetup.tStreamMaster STM ON STM.Id = CM.StreamId -- Added by dhannajay for mantis - 36807
	WHERE 
			A.OrgId=@rOrgId
			AND	A.BatchId = @rBatchId 
			AND ((A.ClassId=@rClassId) OR (@rClassId=0))
			AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId=0))
			AND ((SM.Code = @rCode) OR (ISNULL(@rCode,'') = ''))
			AND ((SM.FirstName = @rName) OR (ISNULL(@rName,'') = ''))
			--AND ((B.BonafideDate=@rBonafiedDate) OR (ISNULL(@rBonafiedDate,'')=''))
			AND ((B.Number=@rNumber) OR (@rNumber=''))
			AND ((B.Number >= @rFromNo) OR (@rFromNo=''))
			AND ((B.Number <= @rToNo) OR (@rToNo=''))
			AND ((B.BonafideDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
			AND ((B.BonafideDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
			--Group By B.AcademicId,SM.Code,SM.FirstName,SM.LastName,SM.MiddleName,CM.DisplayTitle,BM.Title,SO.DateOfBirth,SO.BirthDateInWord,
			--SO.BirthPlace,SO.BirthTaluka,SO.BirthDistrict,B.BonafideDate,OM.CityName,OM.StateName,SO.FamilyCast,SO.FamilySubCast,SO.GenderId,SI.StudentPhoto,SM.StatusId,
			--OM.OrgLogo,OM.PhoneNo,OM.Title,OM.StreetOne,OM.StreetTwo,OM.StreetThree
			Order by B.BonafideDate Desc -- 45814
	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].[pMaxAdmissionInquiryNumberWithPrefixGet]...';


GO
ALTER PROCEDURE [sCommon].[pMaxAdmissionInquiryNumberWithPrefixGet]
	 
	 @rPrefixFunctionalityId smallint,
	 @rOrgId smallint,
	 @rOrgGroupId int,
	 @rOrgGroupBatchId int=0,
	 @rBatchId int=0
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
BEGIN 
BEGIN TRY
	
	DECLARE @lSourceTypeId int
	DECLARE @lOutCode nvarchar(20)
	DECLARE @lPrefix nvarchar(10)
	DECLARE @lNumberLength tinyint
	
	DECLARE @lOrgGroupBatchId int=0
	
	SELECT @lOrgGroupBatchId=OrgGroupBatchId FROM sSetup.tBatchMaster BM WHERE BM.Id = @rBatchId
	
	DECLARE @lConfigValue nvarchar(50)=''
	SELECT @lConfigValue = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 341 AND SourceTypeId = 2010 AND SourceId = @rOrgGroupId
	
	IF @rPrefixFunctionalityId=2013 -- Admission Inquiry
	BEGIN
		SELECT @lSourceTypeId=SourceTypeId FROM sCommon.tPrefixConfig WHERE PrefixFunctionalityId = @rPrefixFunctionalityId AND OrgId =@rOrgId
		IF @lSourceTypeId IS NOT NULL
		BEGIN
			IF @lSourceTypeId = 2021 -- Organization
			BEGIN
				SELECT @lPrefix=Prefix,@lNumberLength=NumberLength FROM sCommon.tPrefixConfig WHERE PrefixFunctionalityId = @rPrefixFunctionalityId AND SourceId = @rOrgId
			END

			IF(@lConfigValue='OrgGroupBatch')
			BEGIN
				SELECT @lOutCode = (MAX(InquiryNumber)) FROM sAdmission.tAdmissionInquiry AI
				INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForbatchId 
				WHERE BM.OrgGroupBatchId = @lOrgGroupBatchId AND Number LIKE @lPrefix+'%'
			END
			ELSE IF(@lConfigValue='Batch')
			BEGIN
				SELECT @lOutCode = MAX(InquiryNumber) FROM sAdmission.tAdmissionInquiry AI
				WHERE AI.ForBatchId = @rBatchId AND Number LIKE @lPrefix+'%'
			END
			ELSE IF (@lConfigValue = 'Continuous' OR @lConfigValue = '' OR @lConfigValue IS NULL) --changes for mantis id:0045586
			BEGIN
				SELECT @lOutCode =MAX(InquiryNumber) FROM sAdmission.tAdmissionInquiry  
				WHERE OrgGroupId = @rOrgGroupId AND Number LIKE @lPrefix+'%'
			END

			IF CHARINDEX(@lPrefix,@lOutCode) > 0
			BEGIN
					SELECT @lOutCode = RIGHT(@lOutCode, LEN(@lOutCode)-LEN(@lPrefix))
					SELECT @lOutCode = (CONVERT(bigint, @lOutCode)+1)
					SELECT @lOutCode = RIGHT(REPLICATE('0', @lNumberLength), @lNumberLength-LEN(@lPrefix)-LEN(@lOutCode))+@lOutCode
					SELECT @lOutCode = @lPrefix + @lOutCode
				END
			ELSE
			BEGIN
				SELECT @lOutCode = 1
				IF @lNumberLength != 0
				BEGIN
					SELECT @lOutCode = RIGHT(REPLICATE('0', @lNumberLength), @lNumberLength-LEN(@lPrefix)-LEN(@lOutCode))+@lOutCode
				END
				SELECT @lOutCode = @lPrefix + @lOutCode
			END
		END
		ELSE 
		BEGIN
			IF(@lConfigValue='OrgGroupBatch')
			BEGIN
				SELECT @lOutCode = (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 @lOutCode = (ISNULL(MAX(InquiryNumber),0) + 1) FROM sAdmission.tAdmissionInquiry AI
				WHERE AI.ForBatchId = @rBatchId
			END
			ELSE IF (@lConfigValue = 'Continuous' OR @lConfigValue = '' OR @lConfigValue IS NULL)  --changes for mantis id:0045586
			BEGIN
				SELECT @lOutCode = (ISNULL(MAX(InquiryNumber),0) + 1) FROM sAdmission.tAdmissionInquiry AI 
				WHERE OrgGroupId = @rOrgGroupId 
			END
		END
	END
	
	END TRY
	BEGIN CATCH
		SET @lOutCode = ''
	END CATCH
	
	SELECT @lOutCode Result
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 [sProcurement].[pStockFreezeAdjustmentDetailAdd]...';


GO
ALTER   PROCEDURE [sProcurement].[pStockFreezeAdjustmentDetailAdd]
	@rOrgId [int],
	@rStockFreezeAdjustmentId [int],
	@rStoreLocationId [int],
	@rCreatedUserId [bigint],
	@rStockFreezeAdjustmentDetailXml [nvarchar](max)
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	--Commented on 19/06/2025 - Invalid column name 'OrgId'.
	--DECLARE @loIdoc INT
	--DECLARE @lStockFreezeAdjustmentDetailCurrentId INT
	--DECLARE @lCount INT 
		
	--SET @lCount = 0	

	--EXEC sp_xml_preparedocument @loIdoc OUTPUT, @rStockFreezeAdjustmentDetailXml
	--EXEC sCommon.pTableRowIdGet @rOrgId,  'sProcurement.tStockFreezeAdjustmentDetail', 1, 1, 1,@outNextNumber = @lStockFreezeAdjustmentDetailCurrentId output

	--INSERT INTO sProcurement.tStockFreezeAdjustmentDetail
	--	(
	--		Id,
	--		StockFreezeAdjustmentId,
	--		StockBatchId,
	--		StockItemId,
	--		StoreLocationId,
	--		SystemQuantity,
	--		PhysicalQuantity,			
	--		StockVerificationApprovalId
	--		,OrgId 
	--	)
	--SELECT  
	--	@lStockFreezeAdjustmentDetailCurrentId + ROW_NUMBER() OVER(ORDER BY StockBatchId) AS Id, 
	--	@rStockFreezeAdjustmentId,
	--	StockBatchId,
	--	StockItemId,
	--	@rStoreLocationId,
	--	SystemQuantity,		
	--	ApprovalQuantity,
	--	StockVerificationApprovalId
	--	,@rOrgId 
	--FROM OPENXML (@loIdoc, '/StockFreeze/StockFreezeAdjustmentDetail', 1)
	--	WITH ( 
	--			StockBatchId INT, 
	--			StockItemId INT,
	--			SystemQuantity DECIMAL(22, 6),
	--			PhysicalQuantity DECIMAL(22, 6),
	--			ApprovalQuantity DECIMAL(22, 6),
	--			StockVerificationApprovalId BIGINT
	--		  ) 
		
	--	SELECT @lCount = COUNT(1) FROM OPENXML (@loIdoc, '/StockFreeze/StockFreezeAdjustmentDetail', 1)
	--			 WITH ( AssetId INT)
		
		
	--	UPDATE sProcurement.tStockBatch
	--	SET AvailableQuantity = XmlTable.ApprovalQuantity,
	--	UpdatedUserId = @rCreatedUserId,
	--	UpdatedDateTime = sCommon.fGetDate()
	--	,OrgId = @rOrgId 
	--	FROM		
	--	OPENXML (@loIdoc, '/StockFreeze/StockFreezeAdjustmentDetail', 1)
	--			WITH (
	--					StockBatchId INT, 
	--					ApprovalQuantity DECIMAL(22, 6)				 
						
	--				 ) XmlTable
	--	WHERE sProcurement.tStockBatch.Id = XmlTable.StockBatchId	
		
	--	SET @lStockFreezeAdjustmentDetailCurrentId  = @lCount + @lStockFreezeAdjustmentDetailCurrentId 
		
	--	EXECUTE sCommon.pTableRowIdModify @rOrgId = @rOrgId, @rTableTitle = 'sProcurement.tStockFreezeAdjustmentDetail', @rCurrentNumber = @lStockFreezeAdjustmentDetailCurrentId 
	SELECT 0 AS Result
END
GO
PRINT N'Altering Procedure [sProcurement].[pStockItemFreezeAdd]...';


GO
ALTER   PROCEDURE [sProcurement].[pStockItemFreezeAdd]
	@rOrgId int,
	@rStockItemFreezeDataXML [nvarchar](max)
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	SELECT 1
	--Commented on 19/06/2025 - Invalid column name 'OrgId'.
--	DECLARE @loIdoc INT
--	DECLARE @lNextNumber BIGINT
--	DECLARE @lCount BIGINT 
		
--	SET @lCount = 0
	
--	EXEC sp_xml_preparedocument @loIdoc OUTPUT, @rStockItemFreezeDataXML
--	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sProcurement.tStockItemFreeze', 0, 1, 1,@outNextNumber = @lNextNumber output

--	INSERT INTO sProcurement.tStockItemFreeze
--		(
--			Id,
--			ItemMainGroupId,
--			StoreLocationId,
--			StatusId,			
--			CreatedUserId,
--			CreatedDateTime
--			--,OrgId --Commented as No orgid is there in table
		
--		)
--SELECT  
--		@lNextNumber + ROW_NUMBER() OVER(ORDER BY StoreLocationId) AS Id, 
--		ItemMainGroupId,
--		StoreLocationId,
--		IsObsolete,
--		CreatedUserId,
--		sCommon.fGetDate()
--		--,@rOrgId
		
		
--	FROM OPENXML (@loIdoc, '/StockItemFreeze/StockItemFreezeDetail', 1)
--		WITH ( 
--				ItemMainGroupId INT, 
--				StoreLocationId INT, 
--				SystemQuantity INT,
--				IsObsolete INT,
--				CreatedUserId BIGINT
			
--			  ) 
		
--		SELECT @lCount = COUNT(1) FROM OPENXML (@loIdoc, '/StockItemFreeze/StockItemFreezeDetail', 1)
--				 WITH ( StoreLocationId INT)
				 
--				 SET @lNextNumber  = @lCount + @lNextNumber 
		
--		EXECUTE sCommon.pTableRowIdModify @rOrgId = @rOrgId, @rTableTitle = 'sProcurement.tStockItemFreeze', @rCurrentNumber = @lNextNumber 
END
GO
PRINT N'Altering Procedure [sProcurement].[pStockFreezeAdjustmentAdd]...';


GO
ALTER   PROCEDURE [sProcurement].[pStockFreezeAdjustmentAdd]
	@rNumber [nvarchar](20) OUTPUT,
	@rCreatedUserId [bigint],
	@rStoreLocationId [int],
	@rStockFreezeAdjustmentDetailXml [nvarchar](max),
	@rOrgId int
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	--Commented on 19/06/2025 - Invalid column name 'OrgId'.
	--DECLARE @lNextNumber INT
	--EXECUTE sCommon.pTableRowIdGet @rOrgId,'sProcurement.tStockFreezeAdjustment', 0, 1, 1,@outNextNumber = @lNextNumber output

	--DECLARE @loNextNumber nVarchar(20)
	--EXECUTE sCommon.pPrefixSetupNextNumberGet @rOrgId=@rOrgId,@rPrefixFunctionalityId = 102,@rStoreLocationId=@rStoreLocationId, @rNextNumber = @loNextNumber OUTPUT
	----SELECT @loNextNumber
	--IF (@loNextNumber IS NULL)
	--BEGIN
	--	RAISERROR('5000', 15, 106)
	--	RETURN
	--END
		
	--INSERT INTO sProcurement.tStockFreezeAdjustment
	--	(
	--		Id,
	--		Number,			
	--		CreatedUserId,
	--		CreatedDateTime
	--		,OrgId 
	--	)
	--VALUES
	--	(
	--		@lNextNumber,
	--		@loNextNumber,			
	--		@rCreatedUserId,
	--		sCommon.fGetDate()
	--		,@rOrgId
	--	)
		
	--SET @rNumber = @loNextNumber
	--EXEC sProcurement.pStockFreezeAdjustmentDetailAdd @rOrgId,@lNextNumber, @rStoreLocationId, @rCreatedUserId,@rStockFreezeAdjustmentDetailXml



----select * from sProcurement.tStockFreezeAdjustment
--	--DECLARE @lIntErrorCode INT, @lIntDoc INT
--	--EXEC @lIntErrorCode = sp_xml_preparedocument @lIntDoc OUTPUT, @rDetail	
		
--	--DECLARE @tStockFreezeAdjustmentDetail TABLE
--	--(
--	--Id								Int IDENTITY(0, 1),
--	--StockFreezeAdjustmentId			Int, 
--	--StockBatchId					Int, 
--	--StockItemId						Int,
--	--SystemQuantity					Decimal(12,2),
--	--PhysicalQuantity				Decimal(12,2),  
--	--StockVerificationApprovalId 	Int
--	--)
	
--	--INSERT INTO @tStockFreezeAdjustmentDetail  
--	--(  
--	--	StockFreezeAdjustmentId,
--	--	StockBatchId,
--	--	StockItemId,
--	--	SystemQuantity,
--	--	PhysicalQuantity,
--	--	StockVerificationApprovalId
--	--)
--	--SELECT	@lNextNumber,
--	--		StockBatchId, 
--	--		StockItemId,
--	--		SystemQuantity,
--	--		PhysicalQuantity,
--	--		StockVerificationApprovalId
			
			
--	--FROM OPENXML (@lIntDoc, '/Root/StockFreezeAdjustmentDetail', 1)  
--	--	WITH  
--	--	(   
--	--		StockBatchId					Nvarchar(300)		'@StockBatchId', 
--	--		StockItemId						Nvarchar(300)		'@StockItemId'
--	--		SystemQuantity					Nvarchar(300)		'@SystemQuantity', 
--	--		PhysicalQuantity				Nvarchar(300)		'@PhysicalQuantity', 
--	--		ApprovalQuantity				Nvarchar(300)		'@ApprovalQuantity'
--	--		StockVerificationApprovalId		Nvarchar(300)		'@StockVerificationApprovalId'
--	--	) XmlTable
	
--	--DECLARE @lNextNumberStockFreezeAdjustmentDetail BigInt
--	--EXECUTE @lNextNumberStockFreezeAdjustmentDetail = sCommon.pTableRowIdGet @rOrgId, 'sProcurement.tStockFreezeAdjustment', 0, 1, 1
	
	
--	--INSERT INTO sProcurement.tStockFreezeAdjustmentDetail
--	--	(
--	--		Id,
--	--		StockFreezeAdjustmentId,
--	--		StockBatchId,
--	--		StockItemId,
--	--		StoreLocationId,
--	--		SystemQuantity,
--	--		PhysicalQuantity,
--	--		StockVerificationApprovalId, 
--	--		OrgId
--	--	)
--	--SELECT 	@lNextNumberStockFreezeAdjustmentDetail + Id, 
--	--		StockFreezeAdjustmentId,
--	--		StockBatchId, 
--	--		StockItemId, 
--	--		@rStoreLocationId,
--	--		SystemQuantity,
--	--		PhysicalQuantity, 
--	--		StockVerificationApprovalId, 
--	--		@rOrgId
--	--FROM	@tStockFreezeAdjustmentDetail
	
--	--UPDATE @tStockFreezeAdjustmentDetail SET StockFreezeAdjustmentDetailId = @lNextNumberStockFreezeAdjustmentDetail + Id 
--	--SELECT @lNextNumberStockFreezeAdjustmentDetail = MAX(Id) + @lNextNumberStockFreezeAdjustmentDetail FROM @tStockFreezeAdjustmentDetail
--	--EXECUTE sCommon.pTableRowIdModify @rOrgId = @rOrgId, @rTableTitle = 'sProcurement.tStockFreezeAdjustmentDetail', @rCurrentNumber = @lNextNumberStockFreezeAdjustmentDetail 
SELECT 0 AS Result
END
GO
PRINT N'Altering Procedure [sHrm].[pExperienceCertificateAdd]...';


GO
ALTER PROCEDURE [sHrm].[pExperienceCertificateAdd]
    @rId bigint,
    @rEmployeeId bigint,
    @rNumber int,
    @rCertificateDate date,
    @rCreatedUserId bigint,
    @rOrgId int,
    @rRemark nvarchar(200),
    @rDesignationId int,
    @rCertificateReason nvarchar(200)
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
    BEGIN TRY
        BEGIN TRANSACTION

        IF (@rNumber = 0)
        BEGIN
            SELECT @rNumber = ISNULL(MAX(Number), 0) + 1
            FROM sHrm.tCertificateExperience
            WHERE OrgId = @rOrgId
        END

        IF (@rId = 0)
        BEGIN
            IF EXISTS
            (
                SELECT 1
                FROM sHrm.tCertificateExperience
                WHERE Number = @rNumber
                      AND OrgId = @rOrgId
            )
            BEGIN
                SELECT -103 AS Result
                RETURN
            END
        END
        DECLARE @lNextNumber BIGINT
        IF (@rId = 0)
        BEGIN
            EXECUTE sCommon.pTableRowIdGet @rOrgId,
                                           'sHrm.tCertificateExperience',
                                           0,
                                           1,
                                           1,
                                           @outNextNumber = @lNextNumber output
            INSERT INTO sHrm.tCertificateExperience
            (
                Id,
                EmployeeId,
                Number,
                CertificateDate,
                OrgId,
                CreatedUserId,
                CreatedDateTime,
                Remark,
                EmployeeDesignationId,
                CertificateReason
            )
            VALUES
            (@lNextNumber,
             @rEmployeeId,
             @rNumber,
             @rCertificateDate,
             @rOrgId,
             @rCreatedUserId,
             sCommon.fGetDate(),
             @rRemark,
             @rDesignationId,
             @rCertificateReason
            )
        END
        ELSE
        BEGIN
            SET @lNextNumber = @rId
            UPDATE sHrm.tCertificateExperience
            SET EmployeeId = @rEmployeeId,
                CertificateDate = @rCertificateDate,
                UpdatedUserId = @rCreatedUserId,
                UpdatedDateTime = sCommon.fGetDate(),
                Remark = @rRemark,
                EmployeeDesignationId = @rDesignationId,
                CertificateReason = @rCertificateReason
            WHERE Id = @rId
        END

        SELECT @lNextNumber AS Result

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

END
GO
PRINT N'Altering Procedure [sProcurement].[pStockAuditAdd]...';


GO
ALTER   PROCEDURE [sProcurement].[pStockAuditAdd]
	@rOrgId int,
	@rStoreLocationId [int],
	@rCreatedUserId [bigint],
	@rStockAuditDetailXml [nvarchar](max),
	@rNumber [nvarchar](20) OUTPUT
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	--Commented on 19/06/2025 - Invalid column name 'OrgId'.
	--DECLARE @lNextNumber BIGINT
	--EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sProcurement.tStockAudit', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	--DECLARE @loNextNumber nVarchar(20)
	--EXECUTE sCommon.pPrefixSetupNextNumberGet @rOrgId = @rOrgId, @rPrefixFunctionalityId = 29,@rStoreLocationId = @rStoreLocationId, @rNextNumber = @loNextNumber OUTPUT
	
	
	--IF (@loNextNumber IS NULL)
	--	BEGIN
	--		RAISERROR('5000', 15, 106)
	--		RETURN
	--	END
	--INSERT INTO sProcurement.tStockAudit
	--	(
	--		Id,
	--		Number,
	--		StoreLocationId,
	--		CreatedUserId,
	--		CreatedDateTime,
	--		OrgId
	--	)
	--VALUES
	--	(
	--		@lNextNumber,
	--		@loNextNumber,
	--		@rStoreLocationId,
	--		@rCreatedUserId,
	--		sCommon.fGetDate(),
	--		@rOrgId
	--	)
	--	SET @rNumber = @loNextNumber
	--	EXEC sProcurement.pStockAuditDetailAdd @rOrgId,  @lNextNumber, @rStockAuditDetailXml
	SELECT 0 AS Result
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
				   ,CS.ClassId --MantisId:0045284
			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 AssignmentId, SubjectId, SubjectName, Title, Remark,
			   StartDate, EndDate, UserId, CreatedUserName, OrgId, IsAssignmentDocumentUpload,CreatedDateTime
		from (
				SELECT AB.AssignmentId, AB.SubjectId, AB.SubjectName, AB.Title, AB.Remark,
					   AB.StartDate, AB.EndDate, AB.UserId, AB.CreatedUserName, AB.OrgId, AB.IsAssignmentDocumentUpload, AB.CreatedDateTime
				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,AB.CreatedDateTime
				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.ClassId --MantisId:0045284
				WHERE AB.IsOptional = 1 AND SA.StudentId = @rUserSourceId
		) as TT Order by CreatedDateTime DESC -- 45571 Add Order 

		--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].[pAccountMappingImport]...';


GO
ALTER PROCEDURE [sFee].[pAccountMappingImport]

	@rOldAccountingYearId int=0,
	@rNewAccountingYearId int=0
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	
	IF EXISTS (SELECT 1 FROM sFee.tAccountMapping WHERE AccountingYearId = @rNewAccountingYearId)
	BEGIN
		SELECT -101 AS RESULT
		RETURN
	END

	BEGIN TRY 
	BEGIN TRANSACTION
	
	DECLARE @lCount int
	
	--  Account Mapping Temp Table
	CREATE TABLE #TempAccountMapping(
		[AutoId] int identity,
		[FeeSetupId] [int] NOT NULL,
		[AccountingYearId] [int] NOT NULL,
		[CreditLedgerId] [int] NULL,
		[DebitLedgerId] [int] NULL,
		[PayTypeId] [tinyint] NULL,
		CreditLedgerName nvarchar(100) NOT NULL,
		DebitLedgerName nvarchar(100) NOT NULL
	)
	-- End Create Table
	
	INSERT INTO #TempAccountMapping 
		(
			FeeSetupId,
			AccountingYearId,
			CreditLedgerId,
			DebitLedgerId,
			PayTypeId,
			CreditLedgerName,
			DebitLedgerName
		)
	SELECT AM.*, LM1.TItle,LM2.Title FROM sFee.tAccountMapping  AM
		INNER JOIN [sAccounting].[tLedgerMaster] LM1 ON LM1.Id = AM.CreditLedgerId
		INNER JOIN [sAccounting].[tLedgerMaster] LM2 ON LM2.Id = AM.DebitLedgerId 
		WHERE AM.AccountingYearId=@rOldAccountingYearId
	
	SELECT @lCount = COUNT(AutoId) FROM #TempAccountMapping
	WHILE (@lCount > 0)
	BEGIN
		-- Account Mapping Entry
		
		DECLARE @lNewFeeSetupId int = 0,@lOldFeeSetupId int=0
		DECLARE @lNewCreditLedgerName nvarchar(100), @lNewDebitLedgerName nvarchar(100)
		DECLARE @lNewCreditLedgerId int, @lNewDebitLedgerId int

		SELECT @lOldFeeSetupId=ISNULL(FeeSetupId,0) FROM #TempAccountMapping WHERE AutoId = @lCount
		SELECT @lNewFeeSetupId=ISNULL(Id,0) FROM sFee.tFeeSetup WHERE OldFeeSetupId = @lOldFeeSetupId
		
		SELECT @lNewCreditLedgerName = CreditLedgerName from #TempAccountMapping WHERE AutoId = @lCount
		SELECT @lNewDebitLedgerName = DebitLedgerName from #TempAccountMapping WHERE AutoId = @lCount

		SELECT @lNewCreditLedgerId = Id from [sAccounting].[tLedgerMaster] 
			WHERE Title = @lNewCreditLedgerName AND AccountingYearID = @rNewAccountingYearId
		SELECT @lNewDebitLedgerId = Id from [sAccounting].[tLedgerMaster] 
			WHERE Title = @lNewDebitLedgerName AND AccountingYearID = @rNewAccountingYearId

		IF(@lOldFeeSetupId>0 AND @lNewFeeSetupId>0)
		BEGIN
			INSERT INTO sFee.tAccountMapping
			SELECT @lNewFeeSetupId,@rNewAccountingYearId,@lNewCreditLedgerId,@lNewDebitLedgerId,PayTypeId
			FROM #TempAccountMapping Where AutoId = @lCount
		END		
		-- End of Account Mapping Entry
		
		SET @lCount = @lCount -1
		
	END

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

BEGIN CATCH 
DROP TABLE #TempAccountMapping 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
END CATCH	
END
GO
PRINT N'Altering Procedure [sFee].[pChangeClassFeeReceiptDetailUpdate]...';


GO
ALTER PROCEDURE [sFee].[pChangeClassFeeReceiptDetailUpdate]
	
	@rAcademicId bigint,
	@rOldClassId int,
	@rOldDivisionId int,
	@rNewClassId int,
	@rNewDivisionId int,	 
	@rBatchId int,
	@rOrgId int,
	@rCreatedUserId bigint = 0

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

DECLARE @rAdmissionCategoryId int
DECLARE @rOldFeeSetupCount int
DECLARE @rNewFeeSetupCount int
DECLARE @rFinalFeeSetupCount int

		--IF Exists (SELECT R.SourceId FROM sFee.tReceipt R WHERE R.SourceId = @rAcademicId)
		--BEGIN
		--SELECT -111 AS Result
		--RETURN		
		--END
		--IF Exists (SELECT R.SourceId FROM sFee.tFeeOptional R WHERE R.SourceId = @rAcademicId)
		--BEGIN
		--SELECT -112 AS Result
		--RETURN		
		--END
		--IF Exists (SELECT R.SourceId FROM sFee.tFeeAllocation R WHERE R.SourceId = @rAcademicId)
		--BEGIN
		--SELECT -113 AS Result
		--RETURN		
		--END

		IF Exists (SELECT 1 FROM sAssessment.tOptionalSubject R WHERE R.AcademicId = @rAcademicId)
		BEGIN
		SELECT -114 AS Result
		RETURN		
		END

		IF Exists (SELECT 1 FROM sAssessment.tResult R WHERE R.AcademicId = @rAcademicId)
		BEGIN
		SELECT -115 AS Result
		RETURN		
		END
		
		IF Exists (SELECT 1 FROM sAssessment.tCCECSExamScore R WHERE R.AcademicId = @rAcademicId)
		BEGIN
		SELECT -116 AS Result
		RETURN		
		END
		
		IF Exists (SELECT 1 FROM sAssessment.tGradeSujbectExamScore R WHERE R.AcademicId = @rAcademicId)
		BEGIN
		SELECT -117 AS Result
		RETURN		
		END

		BEGIN

			-- Added , FS.IsOptional, FS.IsVariable, RD.Amount AS RDAmount: 0045256
			SELECT DISTINCT FS.AdmissionCategoryId,FS.FeeId,FS.Amount,RD.ReceiptId,RD.FeeSetupId, FS.IsOptional, FS.IsVariable, RD.Amount AS RDAmount INTO #OldFeeSteupTempTable 
			FROM sFee.tFeeSetup FS INNER JOIN sFee.tReceiptDetail RD ON RD.FeeSetupId = FS.ID INNER JOIN sFee.tReceipt FR ON FR.ID = RD.RECEIPTID 
			INNER JOIN sStudent.tAcademic A ON  A.Id = FR.SourceId 
			where A.Id=@rAcademicId and FS.ClassId=@rOldClassId AND A.BatchId=@rBatchId order by FS.FeeId

			SET @rOldFeeSetupCount = (SELECT ISNULL(COUNT(1),0) FROM #OldFeeSteupTempTable)
			IF(@rOldFeeSetupCount > 0)
			BEGIN			 
				-- Added Validation if optional and variable fee paid for Fee Transfer: 0045256
				IF EXISTS(SELECT 1 FROM #OldFeeSteupTempTable WHERE IsOptional = 1 AND IsVariable = 1 ANd RDAmount > 0 AND ReceiptId > 0)
				BEGIN
					SELECT -106 AS Result
					RETURN
				END
				
				SET @rAdmissionCategoryId = (SELECT TOP 1 AdmissionCategoryId  FROM #OldFeeSteupTempTable)

				SELECT Id AS NewFeeSetupId,FS.FeeId,FS.Amount,OFS.ReceiptId INTO #NewFeeSteupTempTable  FROM sFee.tFeeSetup FS 
				LEFT JOIN #OldFeeSteupTempTable OFS ON OFS.FeeId = FS.FeeId
				WHERE ClassId=@rNewClassId and BatchId=@rBatchId and FS.AdmissionCategoryId=@rAdmissionCategoryId 
				And FS.FeeId IN (SELECT FeeId from #OldFeeSteupTempTable)
				order by FeeId

				SET @rNewFeeSetupCount = (SELECT ISNULL(COUNT(1),0) FROM #NewFeeSteupTempTable)
				 
				IF(@rOldFeeSetupCount > @rNewFeeSetupCount)
				BEGIN
				SELECT -103 AS Result
				RETURN
				END

				IF(@rNewFeeSetupCount > 0)
					BEGIN

					IF EXISTS(SELECT 1 FROM #OldFeeSteupTempTable OldFee
					INNER JOIN #NewFeeSteupTempTable NewFee on NewFee.FeeId = OldFee.FeeId
					WHERE OldFee.Amount > NewFee.Amount)
					BEGIN
						SELECT -105 AS Result
						RETURN
					END

					SELECT OldFee.ReceiptId,OldFee.FeeSetupId AS OldFeeSetupId,NewFee.NewFeeSetupId INTO #FinalFeeSteupTempTable  FROM #OldFeeSteupTempTable OldFee
					INNER JOIN #NewFeeSteupTempTable NewFee on NewFee.FeeId = OldFee.FeeId
					WHERE OldFee.Amount <= NewFee.Amount order by OldFee.FeeId

					SET @rFinalFeeSetupCount = (SELECT ISNULL(COUNT(1),0) FROM #FinalFeeSteupTempTable)
						IF(@rFinalFeeSetupCount > 0)
							BEGIN
								BEGIN TRY
								BEGIN TRANSACTION							 
									BEGIN
										BEGIN										
										    
											UPDATE RD SET FeeSetupId =FS.NewFeeSetupId from sFee.tReceiptDetail RD 
											INNER JOIN #FinalFeeSteupTempTable FS ON FS.ReceiptId = RD.ReceiptId AND FS.OldFeeSetupId=RD.FeeSetupId

											
											UPDATE sStudent.tAcademic set ClassId=@rNewClassId,DivisionId=@rNewDivisionId 
											WHERE Id=@rAcademicId AND ClassId=@rOldClassId AND DivisionId=@rOldDivisionId AND BatchId=@rBatchId AND OrgId=@rOrgId  

											-- Added for Process Fee after Class Change : 0045256
											EXEC [sFee].[pFeeProcessGenerate] @rOrgId,@rBatchId,@rNewClassId,@rNewDivisionId,@rAcademicId,@rCreatedUserId,0
										
										END		
										SELECT 1 AS RESULT
									END 
									COMMIT TRANSACTION
								END TRY
								BEGIN CATCH 
									ROLLBACK TRANSACTION
									SELECT -104 AS Result
								END CATCH	
							END
						ELSE
							BEGIN
								SELECT -103 AS Result
							END
					END
				ELSE
					BEGIN
					SELECT -102 AS Result
					END
			END
		ELSE
		BEGIN
			SELECT -101 AS Result
		END
	END
END
GO
PRINT N'Altering Procedure [sFee].[pChargePostingDetailGet]...';


GO
ALTER PROCEDURE [sFee].[pChargePostingDetailGet]
				
		  -- @rClassId int, 		   
		   @rOrgGroupId int,
		   @rReceiptDate date,
           @rReceiptDateTo date
            
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
BEGIN 
	SELECT  
			
		--AM.FeeSetupId,
		AMast.Id AS AccountId,
		AMast.Title AS AccountName,
		AM.AccountingYearId,
		AYM.Title AS AccountingYearName,
		AM.CreditLedgerId,
		CLM.Title AS CreditLedgerName,
		AM.DebitLedgerId,
		DLM.Title AS DebitLedgerName,
		AM.PayTypeId,
		PTM.Title AS PayTypeName,
		FM.Id AS ChargeId,
		FM.Title AS ChargeTitle,
		--FHM.Id AS FeeHeadId,
		--FHM.Title AS FeeHeadName,
		--FS.ReceiptBookId AS ReceiptBookId,
		RBM.Title AS ReceiptBookTitle,
		SUM(RD.Amount) AS ReceiptAmount,
		R.ChargeReceiptBookId
			
	FROM 
		sFee.tChargeAccountMapping AM
		INNER JOIN sAccounting.tAccountingYearMaster AYM ON AYM.Id=AM.AccountingYearId
        INNER JOIN sAccounting.tAccountMaster AMast ON AMast.Id=AYM.AccountId
        INNER JOIN sAccounting.tLedgerMaster CLM ON (CLM.Id=AM.CreditLedgerId)  AND CLM.AccountingYearId = AM.AccountingYearId
        INNER JOIN sAccounting.tLedgerMaster DLM ON (DLM.Id=AM.DebitLedgerId) AND DLM.AccountingYearId = AM.AccountingYearId
		INNER JOIN sFinanceCommon.tPayTypeMaster PTM ON PTM.Id = AM.PayTypeId
		INNER JOIN sFee.tChargeMaster FM ON FM.Id=AM.ChargeId 
		INNER JOIN sFee.tChargeReceiptDetail RD ON RD.ChargeId = AM.ChargeId  
		INNER JOIN sFee.tChargeReceipt R ON R.Id = RD.ChargeReceiptId AND R.PayTypeId = AM.PayTypeId
			AND R.ReceiptDate >= @rReceiptDate AND R.ReceiptDate <= @rReceiptDateTo
		INNER JOIN sFee.tChargeReceiptBookMaster RBM ON RBM.Id=R.ChargeReceiptBookId
	WHERE 
		FM.OrgGroupId=@rOrgGroupId
	GROUP BY 
		AMast.Id,AMast.Title, AM.AccountingYearId,AYM.Title,AM.CreditLedgerId,CLM.Title,
		AM.DebitLedgerId,DLM.Title,AM.PayTypeId,PTM.Title,FM.Id,FM.Title ,ChargeReceiptBookId,
		RBM.Title
END
GO
PRINT N'Altering Procedure [sFee].[pChargePostingGet]...';


GO
ALTER PROCEDURE [sFee].[pChargePostingGet]
				
		   --@rClassId int,
           @rReceiptBookId int=0,
		   @rBatchId int,
		   @rOrgGroupId int,
		   @rReceiptDate date,
		   @rReceiptDateTo date,
		   @rChequePosting nvarchar(50),
		   @rOrgGroupBatchID int=0,
		   @rSourceTypeId int
           
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
BEGIN 
	IF @rChequePosting = 'Single'
	BEGIN
			SELECT  
					R.ReceiptDate,
					AMast.Title AS AccountName,
					AYM.Title AS AccountingYearName,
					AM.CreditLedgerId,
					CLM.Title AS CreditLedgerName,
					AM.DebitLedgerId,
					DLM.Title AS DebitLedgerName,
					SUM(RD.Amount) AS ReceiptAmount,
					'' AS ChequeNo,'' AS ChequeDate,'' AS BankName,0 AS PayTypeId,
					ISNULL(AYM.ISLocked,0) AS ISLocked	,R.SourceTypeId,	
					--ISNULL(CASE WHEN R.SourceTypeId = 2001 Then 'Student' END,0) AS SourceName,
					--ISNULL(CASE WHEN R.SourceTypeId = 95 Then 'Employee' END,0) AS SourceName,
					CASE WHEN R.SourceTypeId = 2001 Then 'Student' WHEN R.SourceTypeId = 3 then 'Other'
					ELSE 'Employee' END AS Name,
					CRB.Title AS ChargeReceiptBook
					 		
			FROM 
					sFee.tChargeAccountMapping AM
					INNER JOIN sFee.tChargeReceiptDetail RD ON RD.ChargeId = AM.ChargeId  
					INNER JOIN sFee.tChargeReceipt R ON R.Id = RD.ChargeReceiptId 
						AND R.PayTypeId = AM.PayTypeId 
						AND R.ReceiptDate >= @rReceiptDate 
						AND R.ReceiptDate <= @rReceiptDateTo AND R.IsObsolete = 0
					--INNER JOIN sFee.tFeeSetup FS ON FS.Id=AM.ChargeId 
					----AND (FS.ClassId=@rClassId) 
					AND (R.ChargeReceiptBookId=@rReceiptBookId) 
					--	AND (R.OrgGroupBatchId=@rBatchId)
					INNER JOIN sFee.tChargeMaster FM ON FM.Id=AM.ChargeId 
					INNER JOIN sAccounting.tAccountingYearMaster AYM ON AYM.Id=AM.AccountingYearId
					INNER JOIN sAccounting.tAccountMaster AMast ON AMast.Id=AYM.AccountId
					INNER JOIN sAccounting.tLedgerMaster CLM ON (CLM.Id=AM.CreditLedgerId)  AND CLM.AccountingYearId = AM.AccountingYearId
					INNER JOIN sAccounting.tLedgerMaster DLM ON (DLM.Id=AM.DebitLedgerId) AND DLM.AccountingYearId = AM.AccountingYearId					
					LEFT JOIN sStudent.tAcademic A On A.Id=R.SourceId  AND (R.SourceTypeId = 2001  OR @rSourceTypeId=0)
					LEFT JOIN sHrm.tEmployeeMaster EM On EM.Id=R.SourceId AND (R.SourceTypeId = 95  OR @rSourceTypeId=0)
					INNER JOIN sSetup.tBatchMaster BM ON BM.Id = R.BatchId  
					INNER JOIN sFee.tChargeReceiptBookMaster CRB ON CRB.Id = R.ChargeReceiptBookId
				WHERE 	(R.SourceTypeId =@rSourceTypeId OR @rSourceTypeId=0) AND			    
					AMast.OrgGroupId=@rOrgGroupId	AND BM.OrgGroupBatchId=@rOrgGroupBatchID	
					AND ISNULL(EM.IsOtherUser,0) = 0 	 
					GROUP BY R.ReceiptDate,AM.CreditLedgerId,	AM.DebitLedgerId,AMast.Title,AYM.Title,CLM.Title,DLM.Title,AYM.IsLocked,R.SourceTypeId,CRB.Title
	 END
	 ELSE
		BEGIN		
		SELECT  
			R.ReceiptDate,
			AMast.Title AS AccountName,
			AYM.Title AS AccountingYearName,
			AM.CreditLedgerId,
			CLM.Title AS CreditLedgerName,
			AM.DebitLedgerId,
			DLM.Title AS DebitLedgerName,
			SUM(RD.Amount) AS ReceiptAmount,
			'' AS ChequeNo,'' AS ChequeDate,'' AS BankName,0 AS PayTypeId,
			ISNULL(AYM.ISLocked,0) AS ISLocked	,R.SourceTypeId,
			CASE WHEN R.SourceTypeId = 2001 Then 'Student' WHEN R.SourceTypeId = 3 then 'Other' ELSE 'Employee' END AS Name,
			CRB.Title AS ChargeReceiptBook			
		FROM 
			sFee.tChargeAccountMapping AM
			INNER JOIN sAccounting.tAccountingYearMaster AYM ON AYM.Id=AM.AccountingYearId
            INNER JOIN sAccounting.tAccountMaster AMast ON AMast.Id=AYM.AccountId
            INNER JOIN sAccounting.tLedgerMaster CLM ON (CLM.Id=AM.CreditLedgerId)  AND CLM.AccountingYearId = AM.AccountingYearId
            INNER JOIN sAccounting.tLedgerMaster DLM ON (DLM.Id=AM.DebitLedgerId) AND DLM.AccountingYearId = AM.AccountingYearId
			INNER JOIN sFee.tChargeReceiptDetail RD ON RD.ChargeId = AM.ChargeId  
			INNER JOIN sFee.tChargeReceipt R ON R.Id = RD.ChargeReceiptId 
				AND R.PayTypeId = AM.PayTypeId
				AND R.ReceiptDate >= @rReceiptDate 
				AND R.ReceiptDate <= @rReceiptDateTo AND R.IsObsolete = 0
				--INNER JOIN sFee.tFeeSetup FS ON FS.Id=AM.ChargeId 
				--AND (FS.ClassId=@rClassId) 
				AND (R.ChargeReceiptBookId=@rReceiptBookId) 
				--AND (R.OrgGroupBatchId=@rBatchId)
            INNER JOIN sSetup.tBatchMaster BM ON BM.Id = R.BatchId  
            INNER JOIN sFee.tChargeReceiptBookMaster CRB ON CRB.Id = R.ChargeReceiptBookId
			LEFT JOIN sStudent.tAcademic A On A.Id=R.SourceId AND (R.SourceTypeId = 2001  OR @rSourceTypeId=0)
			LEFT JOIN sHrm.tEmployeeMaster EM On EM.Id=R.SourceId AND (R.SourceTypeId = 95  OR @rSourceTypeId=0)
            
		WHERE (R.SourceTypeId =@rSourceTypeId OR @rSourceTypeId=0) AND
			AMast.OrgGroupId=@rOrgGroupId AND R.PayTypeId = 1 AND BM.OrgGroupBatchId=@rOrgGroupBatchID
			AND ISNULL(EM.IsOtherUser,0) = 0 
			GROUP BY R.ReceiptDate,AM.CreditLedgerId,	AM.DebitLedgerId,AMast.Title,AYM.Title,CLM.Title,DLM.Title,AYM.IsLocked,R.SourceTypeId,CRB.Title
			
		UNION ALL
		
		SELECT  
			R.ReceiptDate,
			AMast.Title AS AccountName,
			AYM.Title AS AccountingYearName,
			AM.CreditLedgerId,
			CLM.Title AS CreditLedgerName,
			AM.DebitLedgerId,
			DLM.Title AS DebitLedgerName,
			Sum(RD.Amount) AS ReceiptAmount,
			R.ChequeNo,R.ChequeDate,R.BankName,R.PayTypeId AS PayTypeId,
			ISNULL(AYM.ISLocked,0) AS ISLocked,
			R.SourceTypeId,
			CASE WHEN R.SourceTypeId = 2001 Then 'Student' WHEN R.SourceTypeId = 3 then 'Other'	ELSE 'Employee' END AS Name,
			CRB.Title AS ChargeReceiptBook
						
		FROM 
			sFee.tChargeAccountMapping AM
			INNER JOIN sAccounting.tAccountingYearMaster AYM ON AYM.Id=AM.AccountingYearId
            INNER JOIN sAccounting.tAccountMaster AMast ON AMast.Id=AYM.AccountId
            INNER JOIN sAccounting.tLedgerMaster CLM ON (CLM.Id=AM.CreditLedgerId)  AND CLM.AccountingYearId = AM.AccountingYearId
            INNER JOIN sAccounting.tLedgerMaster DLM ON (DLM.Id=AM.DebitLedgerId) AND DLM.AccountingYearId = AM.AccountingYearId
			INNER JOIN sFee.tChargeReceiptDetail RD ON RD.ChargeId = AM.ChargeId  
			INNER JOIN sFee.tChargeReceipt R ON R.Id = RD.ChargeId 
				AND R.PayTypeId = AM.PayTypeId
				AND R.ReceiptDate >= @rReceiptDate  
				AND R.ReceiptDate <= @rReceiptDateTo AND R.IsObsolete = 0
				--INNER JOIN sFee.tFeeSetup FS ON FS.Id=AM.FeeSetupId 
				AND (R.ChargeReceiptBookId=@rReceiptBookId) 
				--	AND (R.OrgGroupBatchId=@rBatchId)
            INNER JOIN sSetup.tBatchMaster BM ON BM.Id = R.BatchId  
            INNER JOIN sFee.tChargeReceiptBookMaster CRB ON CRB.Id = R.ChargeReceiptBookId
            LEFT JOIN sStudent.tAcademic A On A.Id=R.SourceId AND (R.SourceTypeId = 2001  OR @rSourceTypeId=0)
			LEFT JOIN sHrm.tEmployeeMaster EM On EM.Id=R.SourceId AND (R.SourceTypeId = 95  OR @rSourceTypeId=0)
            
		WHERE (R.SourceTypeId =@rSourceTypeId OR @rSourceTypeId=0) AND R.PayTypeId <> 1 AND	 AMast.OrgGroupId=@rOrgGroupId	  AND BM.OrgGroupBatchId=@rOrgGroupBatchID		
		AND ISNULL(EM.IsOtherUser,0) = 0 
		GROUP BY R.ReceiptDate,AM.CreditLedgerId,	AM.DebitLedgerId,AMast.Title,AYM.Title,CLM.Title,DLM.Title,AYM.IsLocked,R.ChequeNo,R.ChequeDate,R.BankName,R.PayTypeId,R.SourceTypeId,CRB.Title
		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.AcademicId			--Mantis Id : 0045783 Change colunname SA.AcademicI to 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 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].[pFeePostingGet]...';


GO
ALTER PROCEDURE [sFee].[pFeePostingGet]
				
	--@rClassId int,
    @rReceiptBookId int,
	@rBatchId int,
	@rOrgGroupId int,
	@rReceiptDate date,
	@rReceiptDateTo date,
	@rChequePosting nvarchar(50),
	@rPayTypeId int = 0, -- mantisid -- 0034607
	@rOrgId int = 0		-- Mantis Id : 0045030
           
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
BEGIN 

	--Mantis Start - 38660
		Declare @IsFeePostingWithoutDiscount nvarchar(50)=''
		SELECT @IsFeePostingWithoutDiscount =ItemValue From sConfig.tConfigurationSetup WHERE ConfigurationId = 589 AND SourceTypeId = 2010 AND SourceId = @rOrgGroupId
	--Mantis End - 38660
	IF @rChequePosting = 'Single'
	BEGIN
			SELECT  
					R.ReceiptDate,
					AMast.Title AS AccountName,
					AYM.Title AS AccountingYearName,
					AM.CreditLedgerId,
					CLM.Title AS CreditLedgerName,
					AM.DebitLedgerId,
					DLM.Title AS DebitLedgerName,
					--Mantis Start - 38660
					CASE 
					WHEN 
						@IsFeePostingWithoutDiscount = 'True' 
					THEN 
					SUM(ISNULL(R.ReceiptAmount, 0.00))				
					ELSE 
						SUM(ISNULL(RD.Amount, 0.00))
					END AS ReceiptAmount,
					--Mantis End - 38660

					CASE WHEN ISNULL(R.ChequeNo,'') != '' THEN R.ChequeNo ELSE CONVERT(nvarchar(20),R.PaymentTransactionId) END AS ChequeNo,
					R.ChequeDate AS ChequeDate, 
					ISNULL(R.BankName, '') AS BankName,
					R.ChequeClearDate AS ChequeClearDate,R.PayTypeId AS PayTypeId	, 
					ISNULL(AYM.ISLocked,0) AS ISLocked,
					R.ReceiptNumber,
					ISNULL(R.ReceiptBookId, 0) AS ReceiptBookId,  -- Added for mantis 0035150 by Foram
					--Mantis Start - 37360
					ISNULL(R.ChequeNo, '') AS ChequeNo,
					ISNULL(vSA.Name, '') AS Name,
					ISNULL(vSA.Code, '') AS Code,
					ISNULL(PTM.Title, 0) AS PayType
					--Mantis End - 37360
					

			FROM 
					sFee.tAccountMapping AM
					INNER JOIN sFee.tReceiptDetail RD ON RD.FeeSetupId = AM.FeeSetupId  
					INNER JOIN sFee.tReceipt R ON R.Id = RD.ReceiptId 
						AND R.PayTypeId = AM.PayTypeId
						AND R.ReceiptDate >= @rReceiptDate 
						AND R.ReceiptDate <= @rReceiptDateTo AND R.IsObsolete = 0
						AND ((R.PayTypeId=@rPayTypeId)OR(@rPayTypeId=0)) -- mantisid -- 0034607
					INNER JOIN sFee.tFeeSetup FS ON FS.Id=AM.FeeSetupId 
					--AND (FS.ClassId=@rClassId) 
						AND (FS.ReceiptBookId=@rReceiptBookId OR @rReceiptBookId = 0) -- Added OR @rReceiptBookId = 0 for mantis 0035150 by Foram
						AND (R.OrgGroupBatchId=@rBatchId)
					INNER JOIN sAccounting.tAccountingYearMaster AYM ON AYM.Id=AM.AccountingYearId
					INNER JOIN sAccounting.tAccountMaster AMast ON AMast.Id=AYM.AccountId
					INNER JOIN sAccounting.tLedgerMaster CLM ON (CLM.Id=AM.CreditLedgerId)  AND CLM.AccountingYearId = AM.AccountingYearId
					INNER JOIN sAccounting.tLedgerMaster DLM ON (DLM.Id=AM.DebitLedgerId) AND DLM.AccountingYearId = AM.AccountingYearId
					LEFT JOIN sStudent.vStudentAcademic vSA ON vSA.AcademicId = R.SourceId AND R.SourceTypeId = 2001
					LEFT JOIN sFinanceCommon.tPayTypeMaster PTM ON PTM.id = R.PayTypeId
					INNER JOIN sSetup.tBatchMaster BM ON BM.Id = FS.BatchId				-- Mantis Id : 0045030
				WHERE 
					AMast.OrgGroupId=@rOrgGroupId AND (BM.OrgId = @rOrgId OR @rOrgId = 0)
					GROUP BY R.ReceiptDate,AM.CreditLedgerId,	AM.DebitLedgerId,AMast.Title,AYM.Title,CLM.Title,DLM.Title,AYM.IsLocked,R.ReceiptNumber	
					,R.ChequeNo,R.ChequeDate,R.BankName,R.ChequeClearDate,R.PayTypeId,R.ReceiptBookId,R.BankName,R.ChequeNo,vSA.Name,vSA.Code,PTM.Title,ChequeNo,PaymentTransactionId -- Add for kenya client for check details
	 END
	 ELSE
		BEGIN		
		
			
		DECLARE @lConfigValue nvarchar(50)
		DECLARE @lIsAccountPostingBankNameWise bit=0

		SELECT @lConfigValue = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 244 AND SourceTypeId = 2010 AND SourceId = @rOrgGroupId

		IF (@lConfigValue IS NULL) OR (@lConfigValue = 'False')
		SET @lIsAccountPostingBankNameWise = 0
		ELSE
		SET @lIsAccountPostingBankNameWise = 1	
		
		IF @lIsAccountPostingBankNameWise = 1	
			BEGIN
				  SELECT  
						R.ReceiptDate,
						AMast.Title AS AccountName,
						AYM.Title AS AccountingYearName,
						AM.CreditLedgerId,
						CLM.Title AS CreditLedgerName,
						AM.DebitLedgerId,
						DLM.Title AS DebitLedgerName,
					--Mantis Start - 38546
					CASE 
					WHEN 
						@IsFeePostingWithoutDiscount = 'True' 
					THEN 
					SUM(ISNULL(R.ReceiptAmount, 0.00))				
					ELSE 
						SUM(ISNULL(RD.Amount, 0.00))
					END AS ReceiptAmount,
					--Mantis End - 38546
						'' AS ChequeNo,'' AS ChequeDate,'' AS BankName,'' AS ChequeClearDate,0 AS PayTypeId	,
						ISNULL(AYM.ISLocked,0) AS ISLocked,
						0 as ReceiptNumber,
						ISNULL(R.ReceiptBookId, 0) AS ReceiptBookId,	 -- Added for mantis 0035150 by Foram
						'' AS BankName,
						'' AS ChequeNo,
						'' AS Name,
						'' AS Code,
						0 AS PayType
					FROM 
						sFee.tAccountMapping AM
						INNER JOIN sFee.tReceiptDetail RD ON RD.FeeSetupId = AM.FeeSetupId  
						INNER JOIN sFee.tReceipt R ON R.Id = RD.ReceiptId 
							AND R.PayTypeId = AM.PayTypeId
							AND R.ReceiptDate >= @rReceiptDate 
							AND R.ReceiptDate <= @rReceiptDateTo AND R.IsObsolete = 0
							AND ((R.PayTypeId=@rPayTypeId)OR(@rPayTypeId=0)) -- mantisid -- 0034607
						INNER JOIN sFee.tFeeSetup FS ON FS.Id=AM.FeeSetupId 
						--AND (FS.ClassId=@rClassId) 
							AND (FS.ReceiptBookId=@rReceiptBookId OR @rReceiptBookId = 0) -- Added OR @rReceiptBookId = 0 for mantis 0035150 by Foram
							AND (R.OrgGroupBatchId=@rBatchId)
						INNER JOIN sAccounting.tAccountingYearMaster AYM ON AYM.Id=AM.AccountingYearId
						INNER JOIN sAccounting.tAccountMaster AMast ON AMast.Id=AYM.AccountId
						INNER JOIN sAccounting.tLedgerMaster CLM ON (CLM.Id=AM.CreditLedgerId)  AND CLM.AccountingYearId = AM.AccountingYearId
						INNER JOIN sAccounting.tLedgerMaster DLM ON (DLM.Id=AM.DebitLedgerId) AND DLM.AccountingYearId = AM.AccountingYearId
						INNER JOIN sSetup.tBatchMaster BM ON BM.Id = FS.BatchId				-- Mantis Id : 0045030
					WHERE 
						AMast.OrgGroupId=@rOrgGroupId AND R.PayTypeId = 1 
						AND (BM.OrgId = @rOrgId OR @rOrgId = 0)
					GROUP BY R.ReceiptDate,AM.CreditLedgerId,	AM.DebitLedgerId,AMast.Title,AYM.Title,CLM.Title,DLM.Title,AYM.IsLocked,R.ReceiptBookId
						
					UNION ALL
					
					SELECT  
						R.ReceiptDate,
						AMast.Title AS AccountName,
						AYM.Title AS AccountingYearName,
						AM.CreditLedgerId,
						CLM.Title AS CreditLedgerName,
						R.DepositedLedgerId AS DebitLedgerId, 
						DLM.Title AS DebitLedgerName,
					--Mantis Start - 38546
						CASE 
						WHEN 
							@IsFeePostingWithoutDiscount = 'True' 
						THEN 
						SUM(ISNULL(R.ReceiptAmount, 0.00))				
						ELSE 
							SUM(ISNULL(RD.Amount, 0.00))
						END AS ReceiptAmount,
					--Mantis End - 38546
						R.ChequeNo,R.ChequeDate,R.BankName,R.ChequeClearDate,2 AS PayTypeId,
						ISNULL(AYM.ISLocked,0) AS ISLocked,			
						R.ReceiptNumber,
						ISNULL(R.ReceiptBookId, 0) AS ReceiptBookId, -- Added for mantis 0035150 by Foram
						'' AS BankName,
						'' AS ChequeNo,
						'' AS Name,
						'' AS Code,
						0 AS PayType
					FROM 
						sFee.tAccountMapping AM
						INNER JOIN sFee.tReceiptDetail RD ON RD.FeeSetupId = AM.FeeSetupId  
						INNER JOIN sFee.tReceipt R ON R.Id = RD.ReceiptId 
							AND R.PayTypeId = AM.PayTypeId
							AND R.ReceiptDate >= @rReceiptDate 
							AND R.ReceiptDate <= @rReceiptDateTo AND R.IsObsolete = 0
							AND ((R.PayTypeId=@rPayTypeId)OR(@rPayTypeId=0)) -- mantisid -- 0034607
						INNER JOIN sFee.tFeeSetup FS ON FS.Id=AM.FeeSetupId 
							AND (FS.ReceiptBookId=@rReceiptBookId OR @rReceiptBookId = 0)  -- Added OR @rReceiptBookId = 0 for mantis 0035150 by Foram
							AND (R.OrgGroupBatchId=@rBatchId)
						INNER JOIN sAccounting.tAccountingYearMaster AYM ON AYM.Id=AM.AccountingYearId
						INNER JOIN sAccounting.tAccountMaster AMast ON AMast.Id=AYM.AccountId
						INNER JOIN sAccounting.tLedgerMaster CLM ON (CLM.Id=AM.CreditLedgerId)  AND CLM.AccountingYearId = AM.AccountingYearId
						INNER JOIN sAccounting.tLedgerMaster DLM ON (DLM.Id=R.DepositedLedgerId) AND DLM.AccountingYearId = AM.AccountingYearId
						INNER JOIN sSetup.tBatchMaster BM ON BM.Id = FS.BatchId				-- Mantis Id : 0045030
					WHERE  R.PayTypeId <> 1 AND	 AMast.OrgGroupId=@rOrgGroupId
					AND (BM.OrgId = @rOrgId OR @rOrgId = 0)		
					Group By R.ReceiptDate,AMast.Title,AYM.Title,AM.CreditLedgerId,
						CLM.Title,R.DepositedLedgerId,DLM.Title,R.ChequeNo,R.ChequeDate,R.BankName,
						R.ChequeClearDate,AYM.IsLocked,R.ReceiptNumber,R.ReceiptBookId
				END
		ELSE
		BEGIN				
				SELECT  
					R.ReceiptDate,
					AMast.Title AS AccountName,
					AYM.Title AS AccountingYearName,
					AM.CreditLedgerId,
					CLM.Title AS CreditLedgerName,
					AM.DebitLedgerId,
					DLM.Title AS DebitLedgerName,
					--Mantis Start - 38546
						CASE 
						WHEN 
							@IsFeePostingWithoutDiscount = 'True' 
						THEN 
						SUM(ISNULL(R.ReceiptAmount, 0.00))				
						ELSE 
							SUM(ISNULL(RD.Amount, 0.00))
						END AS ReceiptAmount,
					--Mantis End - 38546
					'' AS ChequeNo,'' AS ChequeDate,'' AS BankName,'' AS ChequeClearDate,0 AS PayTypeId	,
					ISNULL(AYM.ISLocked,0) AS ISLocked,
					0 as ReceiptNumber,
					ISNULL(R.ReceiptBookId, 0) AS ReceiptBookId, -- Added for mantis 0035150 by Foram
					'' AS BankName,
						'' AS ChequeNo,
						'' AS Name,
						'' AS Code,
						0 AS PayType
				FROM  
					sFee.tAccountMapping AM
					INNER JOIN sFee.tReceiptDetail RD ON RD.FeeSetupId = AM.FeeSetupId  
					INNER JOIN sFee.tReceipt R ON R.Id = RD.ReceiptId 
						AND R.PayTypeId = AM.PayTypeId
						AND R.ReceiptDate >= @rReceiptDate 
						AND R.ReceiptDate <= @rReceiptDateTo AND R.IsObsolete = 0
						AND ((R.PayTypeId=@rPayTypeId)OR(@rPayTypeId=0)) -- mantisid -- 0034607
					INNER JOIN sFee.tFeeSetup FS ON FS.Id=AM.FeeSetupId 
					--AND (FS.ClassId=@rClassId) 
						AND (FS.ReceiptBookId=@rReceiptBookId OR @rReceiptBookId = 0)  -- Added OR @rReceiptBookId = 0 for mantis 0035150 by Foram
						AND (R.OrgGroupBatchId=@rBatchId)
					INNER JOIN sAccounting.tAccountingYearMaster AYM ON AYM.Id=AM.AccountingYearId
					INNER JOIN sAccounting.tAccountMaster AMast ON AMast.Id=AYM.AccountId
					INNER JOIN sAccounting.tLedgerMaster CLM ON (CLM.Id=AM.CreditLedgerId)  AND CLM.AccountingYearId = AM.AccountingYearId
					INNER JOIN sAccounting.tLedgerMaster DLM ON (DLM.Id=AM.DebitLedgerId) AND DLM.AccountingYearId = AM.AccountingYearId
					INNER JOIN sSetup.tBatchMaster BM ON BM.Id = FS.BatchId				-- Mantis Id : 0045030
				WHERE 
					AMast.OrgGroupId=@rOrgGroupId AND R.PayTypeId = 1
					AND (BM.OrgId = @rOrgId OR @rOrgId = 0)
				GROUP BY R.ReceiptDate,AM.CreditLedgerId,AM.DebitLedgerId,
				AMast.Title,AYM.Title,CLM.Title,DLM.Title,AYM.IsLocked,R.ReceiptBookId
					
				UNION ALL
				
				SELECT  
					R.ReceiptDate,
					AMast.Title AS AccountName,
					AYM.Title AS AccountingYearName,
					AM.CreditLedgerId,
					CLM.Title AS CreditLedgerName,
					AM.DebitLedgerId,
					DLM.Title AS DebitLedgerName,
					--Mantis Start - 38546
						CASE 
						WHEN 
							@IsFeePostingWithoutDiscount = 'True' 
						THEN 
						SUM(ISNULL(R.ReceiptAmount, 0.00))				
						ELSE 
							SUM(ISNULL(RD.Amount, 0.00))
						END AS ReceiptAmount,
					--Mantis End - 38546
					R.ChequeNo,R.ChequeDate,R.BankName,R.ChequeClearDate,2 AS PayTypeId,
					ISNULL(AYM.ISLocked,0) AS ISLocked,
					R.ReceiptNumber,
					ISNULL(R.ReceiptBookId, 0) AS ReceiptBookId, -- Added for mantis 0035150 by Foram
					'' AS BankName,
						'' AS ChequeNo,
						'' AS Name,
						'' AS Code,
						0 AS PayType
				FROM 
					sFee.tAccountMapping AM
					INNER JOIN sFee.tReceiptDetail RD ON RD.FeeSetupId = AM.FeeSetupId  
					INNER JOIN sFee.tReceipt R ON R.Id = RD.ReceiptId 
						AND R.PayTypeId = AM.PayTypeId
						AND R.ReceiptDate >= @rReceiptDate 
						AND R.ReceiptDate <= @rReceiptDateTo AND R.IsObsolete = 0
						AND ((R.PayTypeId=@rPayTypeId)OR(@rPayTypeId=0)) -- mantisid -- 0034607
					INNER JOIN sFee.tFeeSetup FS ON FS.Id=AM.FeeSetupId 
						AND (FS.ReceiptBookId=@rReceiptBookId OR @rReceiptBookId = 0)  -- Added OR @rReceiptBookId = 0 for mantis 0035150 by Foram
						AND (R.OrgGroupBatchId=@rBatchId)
					INNER JOIN sAccounting.tAccountingYearMaster AYM ON AYM.Id=AM.AccountingYearId
					INNER JOIN sAccounting.tAccountMaster AMast ON AMast.Id=AYM.AccountId
					INNER JOIN sAccounting.tLedgerMaster CLM ON (CLM.Id=AM.CreditLedgerId)  AND CLM.AccountingYearId = AM.AccountingYearId
					INNER JOIN sAccounting.tLedgerMaster DLM ON (DLM.Id=AM.DebitLedgerId) AND DLM.AccountingYearId = AM.AccountingYearId
					INNER JOIN sSetup.tBatchMaster BM ON BM.Id = FS.BatchId				-- Mantis Id : 0045030
				WHERE  R.PayTypeId <> 1 AND	 AMast.OrgGroupId=@rOrgGroupId
				AND (BM.OrgId = @rOrgId OR @rOrgId = 0)			
				Group By R.ReceiptDate,AMast.Title,AYM.Title,AM.CreditLedgerId,
					CLM.Title,AM.DebitLedgerId,DLM.Title,
					R.ChequeNo,R.ChequeDate,R.BankName,R.ChequeClearDate,AYM.IsLocked,R.ReceiptNumber,R.ReceiptBookId
			END
		END
END
GO
PRINT N'Altering Procedure [sFee].[pRptRoutewiseTransportFeeWithDetailGet]...';


GO

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


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

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

			SELECT
			P.OrgId,			 
			P.ReceiptBookId,
			P.AcademicId,
			P.DivisionId,
			P.ClassDivision,P.RollNo, P.Name,P.Code,ReceiptBookTitle,OrgName,
			SUM(P.PendingAmount) AS PendingAmount, 
			[sFee].[fPendingFeeNamesGet](P.AcademicId,ReceiptBookId,	@p) AS PendingFeeName,
			P.ReceiptOrderIndex,
			BR.Id AS BusRouteId,
			BR.Title AS BusRoute,
			BD.Title AS BusDestination,
			isnull(SC.ParentContactNo,'') AS ParentContactNo,
			P.SUID,
			P.ClassOrderIndex,
			P.DivisionOrderIndex,
			'' AS FatherContactNo,
		    '' AS MotherContactNo,
			--Added by dhananjay for mantis id Start - 35419
			SUM(ISNULL(P.PaidAmount,0)) AS PaidAmount,		--- Add Sum for : 0045211
			--ISNULL(P.Amount,0) AS Amount	 ,
			--Added by dhananjay for mantis id End - 35419
			'' AS WhatsAppContactNo --added by dhananjay for : 37272
			--Start : add for mantis : 0040717
			,ISNULL(SC.PresentStreetOne,'') AS PresentStreetOne	
			,ISNULL(SC.PresentStreetTwo,'') AS	PresentStreetTwo
			,ISNULL(SC.PresentStreetThree,'') AS PresentStreetThree 	
			,ISNULL(SC.PresentCountry,'') AS PresentCountry	
			,ISNULL(SC.PresentState,'') AS	PresentState
			,ISNULL(SC.PresentCity,'')	AS PresentCity
			,ISNULL(SC.PresentZipCode,'') AS PresentZipCode
			--End : add for mantis : 0040717			
			FROM @p P INNER JOIN sStudent.vStudentAcademic VA ON p.AcademicId=VA.AcademicId
			INNER JOIN sTransport.tAssignRoute AR oN VA.StudentId = AR.SourceId AND SourceTypeId = 2003
			INNER JOIN sTransport.tBusRouteDestinationMaster BD ON BD.Id = AR.PickupDestinationId 
			INNER JOIN sTransport.tBusRouteMaster BR ON BR.Id = BD.BusRouteId 
			AND BR.OrgGroupBatchId = @rOrgGroupBatchId
			LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId =  VA.StudentId
			GROUP By P.ReceiptBookId,P.OrgId,P.AcademicId,P.DivisionId,
			P.ClassDivision,P.RollNo, P.Name,P.Code,
			P.ReceiptBookTitle,P.OrgName,P.ReceiptOrderIndex,BR.Title,BD.Title,BR.Id,SC.ParentContactNo	,P.SUID,P.ClassOrderIndex,P.DivisionOrderIndex, --P.PaidAmount, --Added by dhananjay(P.PaidAmount,P.Amount) for mantis id - 35419
			p.WhatsAppContactNo, --added by dhananjay for : 37272
			SC.PresentStreetOne,SC.PresentStreetTwo,SC.PresentStreetThree,SC.PresentCountry,SC.PresentState,SC.PresentCity,SC.PresentZipCode
						
			ORDER BY P.AcademicId
 
END
GO
PRINT N'Altering Procedure [sFee].[pRptStudentOptionalFeeListGet]...';


GO

ALTER PROCEDURE [sFee].[pRptStudentOptionalFeeListGet]	 
		@rClassId int = 0,
		@rDivisionId int = 0,
		@rAdmissionCategoryId int = 0,		
		@rBatchId int = 0,
		@rOrgId int = 0,
		@rReceiptBookId int = 0,
		@rDepartmentId int = 0,
		@rOrgGroupBatchId int = 0,
		@rCommonBatch nvarchar(100)='', --nvarchar for mantis : 0044148
		@rFeeId nvarchar(max) = '',
		@rFromRollNo int = 0,
		@rToRollNo int = 0,
		@rFilterId int = 0,
		@rOrgGroupId int = 0,
		@rCode nvarchar(20) = '',
		@rReportId int = 0,
		@rIsDisplayOrgGroup bit = 0,
		@rIsFilter bit = 0,  
		@rBuilder1 nvarchar(max) = '',  
		@rBuilder2 nvarchar(max) = '',
		@rFeeHeadId int = 0
		,@rStatusId int = 0 -- mantis : 0045286

		WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 		
	SELECT 
			@rIsDisplayOrgGroup AS IsDisplayOrgGroup,
			@rIsFilter AS IsFilter,
			@rBuilder1 AS Builder1,  
			@rBuilder2 AS Builder2,  
			SA.AcademicId,
			SA.Code,
			SA.Name,
			SA.RollNo,
			SA.ClassName,
			SA.DivisionName,
			ISNULL(FO.FeeSetupId,0) AS FeeSetupId,			
			ISNULL(SC.ParentContactNo,'') AS ParentContactNo,
			ISNULL(SC.WhatsAppContactNo,'') AS WhatsAppContactNo,
			FM.Id AS FeeId,
			FM.Title AS FeeName,
			--Added by dhananjay mantis : 42689	
			SA.ClassOrderIndex,
			SA.DivisionOrder
			--Added by dhananjay mantis : 42689
	FROM 
		sFee.tFeeOptional FO
		INNER JOIN sStudent.vStudentAcademic SA ON FO.SourceId=SA.AcademicId
		INNER JOIN sFee.tFeeSetup FS ON FS.Id = FO.FeeSetupId AND FO.SourceTypeId=2001
		INNER JOIN sFee.tReceiptBookMaster RBM ON RBM.Id = FS.ReceiptBookId
		INNER JOIN sFee.tFeeMaster FM ON FM.Id = FS.FeeId
		INNER JOIN sSetup.tBatchMaster BM ON BM.Id = FO.BatchId AND SA.BatchId = BM.Id
		INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id = BM.OrgGroupBatchId
		LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId = SA.StudentId	
		LEFT JOIN sHostel.tAssignRoom AR ON  AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003 AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  AND ((AR.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0) 
		AND (SA.OrgGroupBatchId = AR.OrgGroupBatchId))   
		LEFT JOIN  
		(SELECT AT.SourceId,B.OrgGroupBatchId FROM sTransport.tAssignRoute AT   
			INNER JOIN sTransport.tBusRouteDestinationMaster BM ON BM.Id=AT.PickupDestinationId   
			INNER JOIN sTransport.tBusRouteMaster B ON B.Id=BM.BusRouteId AND  AT.SourceTypeId=2003 
			AND ((B.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))) RT  ON RT.SourceId = SA.StudentId   
			AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))    
			AND (SA.OrgGroupBatchId = RT.OrgGroupBatchId)
	WHERE 
		(RBM.OrgGroupId = @rOrgGroupId)
		AND	((SA.OrgId=@rOrgId) OR (@rOrgId = 0))		
		AND ((BM.Id=@rBatchId) OR (@rBatchId = 0))
		AND ((SA.ClassId=@rClassId) OR (@rClassId=0))
		AND ((SA.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		AND ((SA.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))		
		AND ((FS.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))	
		AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))	
		AND ((OGBM.Id = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))
		--AND ((OGBM.CommonOrgGroupBatchId = @rCommonBatch) OR (@rCommonBatch = 0)) --comment for mantis : 0044148
		AND ((SA.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))--add for mantis : 0044148
		AND ((SA.RollNo >= @rFromRollNo) OR (@rFromRollNo = 0))
		AND ((SA.RollNo <= @rToRollNo) OR (@rToRollNo = 0))		
		AND (ISNULL(FS.FeeId,0) IN (SELECT cast(item as int) FROM sCommon.fnsplit(@rFeeId,',')) OR @rFeeId='')
		AND (  
		  (@rFilterId = 0) -- All  
			 OR (@rFilterId = 2 AND isnull(AR.SourceId,0)!=0) -- Hostel  
			 OR (@rFilterId = 3 AND isnull(RT.SourceId,0)!=0) -- Transport  
			 OR ((@rFilterId =1) AND ((isnull(AR.SourceId,0)=0) AND (isnull(RT.SourceId,0)=0)))  
			)
		AND ((SA.Code = @rCode) OR (@rCode = ''))
		AND (SA.StatusId=@rStatusId OR @rStatusId=0) --mantis : 0045286
		ORDER BY SA.AcademicId
END
GO
PRINT N'Altering Procedure [sIp].[pStockItemPurchaseUomGetlist]...';


GO
ALTER   PROCEDURE [sIp].[pStockItemPurchaseUomGetlist]
	@rOrgId Int,
	@rIsWildCardSearch [bit] = 1
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
IF    @rIsWildCardSearch = 1
BEGIN
	--Commented on 19/06/2025 - Invalid column name 'OrgId'.
	 -- SELECT	0 AS ID, 
		--		0 AS StockItemId, 
		--		Id  AS StockUomId,
		--		0 AS ConversionFactor, 
		--		IsObsolete,
		--		CreatedUserId, 
		--		CreatedDateTime,
		--		UpdatedUserId, 
		--		UpdatedDateTime,
		--		TITLE  AS Title, 
		--		Code 
		--FROM 
		--		sFinanceCommon.tStockUomMaster SUOM 		
		--WHERE 
		--		SUOM.IsObsolete = 0
		--		AND OrgId = @rOrgId

		SELECT	0 AS ID, 
				0 AS StockItemId, 
				0 AS StockUomId,
				0 AS ConversionFactor, 
				0 AS IsObsolete,
				0 AS CreatedUserId, 
				0 AS CreatedDateTime,
				0 AS UpdatedUserId, 
				0 AS UpdatedDateTime,
				0 AS Title, 
				0 AS Code 
END
GO
PRINT N'Altering Procedure [sProcurement].[pRptStockAudjustment]...';


GO
ALTER PROCEDURE [sProcurement].[pRptStockAudjustment]
	@rId [int] = 0
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN

SELECT 
				SIM.Code AS ItemNo,
				SIM.Title AS ItemName,
				SB.Number AS BatchNo,
				LOC.Title AS Location,
				SAD.SystemQuantity,
				SAD.PhysicalQuantity,
				SA.Number,
				SA.CreatedDateTime,				
				SAD.StockBatchId,
				SAD.StoreLocationId,				
				SAD.StockAdjustmentId
				,SAD.Remark	--mantis : 0045739							
				 				
				FROM sProcurement.tStockAdjustmentDetail SAD
				INNER JOIN sProcurement.tStockAdjustment SA
				ON SAD.StockAdjustmentId = SA.Id
				INNER JOIN sIp.tStoreLocationMaster  LOC
				ON LOC.Id = SAD.StoreLocationId 
				LEFT JOIN sProcurement.tStockBatch SB
				ON SAD.StockBatchId = SB.Id
				INNER JOIN sIp.tStockItemMaster SIM 
				ON SIM.Id = SAD.StockItemId		
				
WHERE SAD.StockAdjustmentId = @rId

END
GO
PRINT N'Altering Procedure [sProcurement].[pStockAuditDetailListGet]...';


GO
ALTER   PROCEDURE [sProcurement].[pStockAuditDetailListGet]
	@rOrgId int,
	@rId [int] = 0,
	@rNumber [nvarchar](20) = ''
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON;

BEGIN
	--Commented on 19/06/2025 - Invalid column name 'OrgId'.
	--SELECT	SA.Id,
	--		SA.Number,
	--		SA.StoreLocationId,
	--		SA.CreatedUserId,
	--		SAD.StockAuditId,
	--		SAD.StockItemId,
	--		SAD.SystemQuantity,
	--		SAD.PhysicalQuantity,
	--		SLM.Title AS StoreLocation,
	--		SIM.Title AS ItemName
	--FROM sProcurement.tStockAudit SA
	--INNER JOIN 
	--	sProcurement.tStockAuditDetail SAD
	--ON
	--	SAD.StockAuditId = SA.Id
	--INNER JOIN
	--	sIP.tStoreLocationMaster SLM
	--ON
	--	SLM.Id = SA.StoreLocationId
	--INNER JOIN  sIp.tStockItemMaster SIM
	--ON SIM.ID = SAD.StockItemId
	
	--WHERE ((SA.Id = @rId) OR (@rId = 0))
	--AND ((SA.Number = @rNumber) OR (@rNumber = ''))
	--AND SA.OrgId = @rOrgId
	
	SELECT	0 AS Id,
			0 AS Number,
			0 AS StoreLocationId,
			0 AS CreatedUserId,
			0 AS StockAuditId,
			0 AS StockItemId,
			0 AS SystemQuantity,
			0 AS PhysicalQuantity,
			0 AS StoreLocation,
			0 AS ItemName
END
GO
PRINT N'Altering Procedure [sProcurement].[pStockAuditSearchGet]...';


GO
ALTER   PROCEDURE [sProcurement].[pStockAuditSearchGet]
	@rOrgId [int],	
	@rLocationId [int] = 0,
	@rItemMainGroupId [int] = 0,
	@rItemSubGroupId [int] = 0,
	@rStockItemId [int] = 0
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	--Commented on 19/06/2025 - Invalid column name 'OrgId'.
	--SELECT 
	--	SB.StockItemId,
	--	SIM.Code AS ItemCode,
	--	SIM.Title AS ItemName,
	--	SUM(SB.AvailableQuantity) AS SQuantity								 
	--FROM sIp.tStockItemMaster SIM
	--	INNER JOIN sProcurement.tStockBatch SB
	--	ON SIM.Id = SB.StockItemId	   
	--	INNER JOIN sIp.tItemSubGroupMaster ISG
	--	ON ISG.Id = SIM.ItemSubGroupId
	--    -- WHERE SIM.OrgId = @rOrgId --Commented as No orgid is there in table
	--	GROUP BY SB.StockItemId, SB.StoreLocationId, SIM.ItemSubGroupId, ISG.ItemMainGroupId, SIM.Code, SIM.Title
	--	HAVING ((SB.StockItemId = @rStockItemId) OR (@rStockItemId = 0))
	  
	--	AND ((SB.StoreLocationId = @rLocationId) OR (@rLocationId = 0))
	--	AND ((SIM.ItemSubGroupId = @rItemSubGroupId) OR (@rItemSubGroupId = 0))
	--	AND ((ISG.ItemMainGroupId = @rItemMainGroupId) OR (@rItemMainGroupId = 0))

	SELECT 
		0 AS StockItemId,
		0 AS ItemCode,
		0 AS ItemName,
		0 AS SQuantity	
	 
END
GO
PRINT N'Altering Procedure [sProcurement].[pStockBatchAvailableQuantity]...';


GO
ALTER   PROCEDURE [sProcurement].[pStockBatchAvailableQuantity]
	@rOrgId [int], 
	@rStoreLocationId [int] = 0,
	@rStockItemId [int] = 0
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON      

   DECLARE @rId INT = 0
   DECLARE @rAvailableQuantity DECIMAl(12,2) = 0.00

BEGIN  
	--Commented on 19/06/2025 - Invalid column name 'OrgId'.
   --IF EXISTS(SELECT Id,AvailableQuantity FROM sProcurement.tStockBatch WHERE (StoreLocationId = @rStoreLocationId OR @rStoreLocationId = 0) AND
	 	-- (StockItemId = @rStockItemId OR @rStockItemId = 0) --AND OrgId = @rOrgId  --Commented as No orgid is there in table
		 --)
   --     BEGIN
        
   -- 	SELECT Id,AvailableQuantity
		 --FROM sProcurement.tStockBatch WHERE (StoreLocationId = @rStoreLocationId OR @rStoreLocationId = 0) AND
	 	-- (StockItemId = @rStockItemId OR @rStockItemId = 0)-- AND OrgId = @rOrgId--Commented as No orgid is there in table
    		 
   --     END
   -- ELSE
     
      SELECT 0 AS Id, 0.00 AS AvailableQuantity
       
END
GO
PRINT N'Altering Procedure [sProcurement].[pStockBatchModifyUsingDispense]...';


GO
ALTER   PROCEDURE [sProcurement].[pStockBatchModifyUsingDispense]
	@rOrgId [int], 
	@rStoreLocationId [int] = 0,
	@rStockItemId [int] = 0,
	@rQuantity decimal(12,2) = 0.00
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

       DECLARE @1AvailableQuantity Decimal(12,2) 
       DECLARE @1Id Int    


select @1AvailableQuantity =  AvailableQuantity  FROM sProcurement.tStockBatch WHERE (StoreLocationId = @rStoreLocationId  AND StockItemId = @rStockItemId)

BEGIN      
    --Commented on 19/06/2025 - Invalid column name 'OrgId'.
--    IF(@1AvailableQuantity >= @rQuantity)
    
--		 UPDATE  sProcurement.tStockBatch
                 
--         SET  AvailableQuantity = AvailableQuantity - @rQuantity
--	     WHERE  
--		(StoreLocationId = @rStoreLocationId OR @rStoreLocationId = 0) AND
--		(StockItemId = @rStockItemId OR @rStockItemId = 0) 
--		--(Number = @rNumber OR ISNULL(@rNumber, '') = '') AND
--		--(ExpiryDate = @rExpiryDate OR ISNULL(@rExpiryDate, '') = '') AND
--		AND OrgId = @rOrgId --Commented as No orgid is there in table

--SELECT SB.Id,AvailableQuantity,ISNULL(SIP.WeightedAverageCost,0) AS WeightedAverageCost  
--FROM sProcurement.tStockBatch SB INNER JOIN sIp.tStockItemMaster SIM 
--ON SIM.Id = SB.StockItemId  
--INNER JOIN sIp.tStockItemPlanning SIP 
--ON SIP.StockItemId=SIM.Id AND SIP.StoreLocationId=@rStoreLocationId
--WHERE (SB.StoreLocationId = @rStoreLocationId OR @rStoreLocationId = 0) 
--AND (SB.StockItemId = @rStockItemId OR @rStockItemId = 0) 
--AND SB.OrgId = @rOrgId  
SELECT 0 AS Id, 0 AS AvailableQuantity,0 AS WeightedAverageCost 
END
GO
PRINT N'Altering Procedure [sProcurement].[pStockFreezeAdjustmentDetailGet]...';


GO
ALTER   PROCEDURE [sProcurement].[pStockFreezeAdjustmentDetailGet]
	@rOrgId [int],
	@rStoreLocationId int,
	@rNumber [nvarchar](50)
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	BEGIN
		--Commented on 19/06/2025 - Invalid column name 'OrgId'.
		--SELECT 
		--		sProcurement.tStockFreezeAdjustmentDetail.Id,
		--		StockFreezeAdjustmentId,
		--		StockBatchId,
		--		SIP.StockItemId,
		--		SIP.StoreLocationId,
		--		SystemQuantity,
		--		PhysicalQuantity,
		--		StockVerificationApprovalId,
		--		SIP.WeightedAverageCost
		--FROM 
		--		sProcurement.tStockFreezeAdjustmentDetail
		--INNER JOIN
		--		sProcurement.tStockFreezeAdjustment
		--ON
		--		sProcurement.tStockFreezeAdjustment.Id = sProcurement.tStockFreezeAdjustmentDetail.StockFreezeAdjustmentId
		--INNER JOIN 
		--		sIp.tStockItemMaster SIM
		--ON 
		--		sProcurement.tStockFreezeAdjustmentDetail.StockItemId = SIM.Id
		--INNER JOIN sIp.tStockItemPlanning SIP 
		--ON SIP.StockItemId=SIM.Id AND SIP.StoreLocationId=@rStoreLocationId			
		
		--WHERE
		--		sProcurement.tStockFreezeAdjustment.Number = @rNumber
				--AND SIM.OrgId = @rOrgId 
		SELECT 
				0 AS Id,
				0 AS StockFreezeAdjustmentId,
				0 AS StockBatchId,
				0 AS StockItemId,
				0 AS StoreLocationId,
				0 AS SystemQuantity,
				0 AS PhysicalQuantity,
				0 AS StockVerificationApprovalId,
				0 AS WeightedAverageCost
	END
GO
PRINT N'Altering Procedure [sProcurement].[pStockFreezeAdjustmentGet]...';


GO
ALTER   PROCEDURE [sProcurement].[pStockFreezeAdjustmentGet]
	@rOrgId [int],
	@rStoreLocationId int ,
	@rNumber [nvarchar](50)
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	BEGIN
	--Commented on 19/06/2025 - Invalid column name 'OrgId'.
		--SELECT Id, Number FROM sProcurement.tStockFreezeAdjustment
		--	WHERE Number like @rNumber 
		--	AND OrgId = @rOrgId
		--EXEC sProcurement.pStockFreezeAdjustmentDetailGet @rOrgId,@rStoreLocationId, @rNumber
	SELECT 0 AS Result
	END
GO
PRINT N'Altering Procedure [sProcurement].[pStockTransferRequestGet]...';


GO
ALTER   PROCEDURE [sProcurement].[pStockTransferRequestGet]
	@rOrgId [int], 
	@rId [int] = 0,
	@rStoreLocationId int
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
--Commented on 19/06/2025 - Invalid column name 'OrgId'.
	 --SELECT Id,
		--	Number,
		--	FromStoreLocationId,
		--	ToStoreLocationId,
		--	RequestedByName,
		--	Remark,
		--	CreatedDateTime
	 --  FROM sProcurement.tStockTransferRequest
	 -- WHERE ((Id = @rId) OR (@rId = 0))
	 -- AND OrgId = @rOrgId
	 --AND ((FromStoreLocationId = @rStoreLocationId) OR (@rStoreLocationId = 0))
	  
	 -- EXEC [sProcurement].[pStockTransferRequestDetailGet] @rOrgId, @rId
	 SELECT 0 AS Id,
			0 AS Number,
			0 AS FromStoreLocationId,
			0 AS ToStoreLocationId,
			0 AS RequestedByName,
			0 AS Remark,
			0 AS CreatedDateTime
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,5514,52,22,23,19181046))
	)

  --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
20665,20666,20667,20668,20669,20670,20671,20672,20673,20674, -- Add Alert Screen for Rediretion
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,5514,52,22,23,19181046))
	)
  --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].[pRptStudentDetailListGet]...';


GO
ALTER PROCEDURE [sStudent].[pRptStudentDetailListGet]
	 
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 @rOrgId smallint,
	 @rBatchId int,
	 @rStrStudentId nvarchar(max),
	 @rStrCode nvarchar(max),
	 @rClassId int,
	 @rDivisionId int,
	 @rStudentId bigint,
	 @rFromRollNo int,
	 @rToRollNo int,
	 @rStatusId int,
	 @rClassStatusId int,
	 @rDateOfBirth int,
	 @rDepartmentId int
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 

	SELECT 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			SA.AcademicId,
			SA.StudentId, 
			SA.ClassId,
			SA.DivisionId,
			SA.Code,
			SA.RollNo AS RollNo,			
			SA.FirstName,			
			SA.LastName,
			SA.Name,		
			SA.ClassName,
			SA.DivisionName,
			SA.StatusName,
			SA.DivisionOrder,
			SA.Number AS StudentNumber,
			SO.DateOfBirth,
			SC.ParentContactNo,
			GM.Title AS Gender,
			SO.FamilyCast,
			CCM.Title AS CastCategory,
			HM.Title AS HouseName,
			SA.ClassStatusName,
			tSA.AdmissionDate,
			--Mantis Start - 45285
			ISNULL((SELECT  (STUFF(( SELECT  ',' + ISNULL(SM.Title , ',') FROM sSetup.tSubjectMaster SM
			INNER JOIN sSetup.tClassSubject CS ON CS.SubjectId = SM.Id AND CS.IsOptional = 1
			INNER JOIN sAssessment.tOptionalSubject OS ON OS.AcademicId = SA.AcademicId AND OS.ClassSubjectId = CS.Id
			WHERE ((CS.SubjectId = SM.Id) OR SM.Id = 0)
			FOR XML PATH(''), TYPE).
			value('.','NVARCHAR(MAX)'),1,1,''))),'') As SubjectName
			--Mantis End - 45285
	FROM 
		 	sStudent.vStudentAcademic SA
		 	LEFT JOIN sStudent.tStudentOther SO
		 		ON SA.StudentId = SO.StudentId
		 	LEFT JOIN sStudent.tStudentCommunication SC
		 		ON SA.StudentId = SC.StudentId
		 	LEFT JOIN sActivity.tHouseMaster HM 
		 		ON SO.HouseId = HM.Id 
		 	LEFT JOIN sCommon.tGenderMaster GM 
		 		ON SO.GenderId = GM.Id
		 	LEFT JOIN sCommon.tCastCategoryMaster CCM
		 		ON SO.CastCategoryId = CCM.Id	
		 	INNER JOIN sSetup.tBatchClass BC ON BC.ClassID =  SA.ClassId and BC.BatchId= @rBatchId
		 	LEFT JOIN sStudent.tStudentAdmission tSA ON tSA.StudentId = SA.StudentId
	WHERE 
	
			SA.OrgId=@rOrgId
		AND	SA.BatchId = @rBatchId
		AND (ISNULL(SA.StudentId,0) NOT IN( SELECT cast(item as bigint) FROM  sCommon.fnsplit(@rStrStudentId,',')) OR @rStrStudentId='') 
		AND (ISNULL(SA.Code,0) IN( SELECT cast(item as nvarchar(20)) FROM  sCommon.fnsplit(@rStrCode,',')) OR @rStrCode='') 
		AND ((SA.ClassId=@rClassId) OR (@rClassId=0))
		AND ((SA.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		AND ((SA.StudentId=@rStudentId) OR (@rStudentId=0))
		AND ((SA.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
		AND ((SA.RollNo <= @rToRollNo) OR (@rToRollNo=0))
		AND ((SA.StatusId=@rStatusId)OR(@rStatusId=0))
		AND ((SA.ClassStatusId=@rClassStatusId)OR(@rClassStatusId=0))
		AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
END
GO
PRINT N'Altering Procedure [sStudent].[pRptStudentRegisterWithAddressGet]...';


GO
ALTER PROCEDURE [sStudent].[pRptStudentRegisterWithAddressGet]
	 
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 @rOrgId smallint,
	 @rBatchId int,
	 @rStrCode nvarchar(max),
	 @rClassId int,
	 @rDivisionId int,
	 @rStudentId bigint,
	 @rFromRollNo int,
	 @rToRollNo int,
	 @rStatusId int,
	 @rClassStatusId int,
	 @rDateOfBirth int,
	 @rDepartmentId int
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 

	SELECT 
		 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			SD.RollNo,
			SD.Code,
			SD.FirstName,
			SD.MiddleName,			
			SD.LastName,
			SD.Name,	
			SD.DateOfBirth,
			SD.Religion,
			SD.FamilyCast,
			CCM.Title AS FamilySubCast,
			SF.MotherName,
			SF.FatherName,
			SD.ParentContactNo AS ContactNo,
			SF.FatherOccupation,
			SD.PresentStreetOne + ' ' + SD.PresentStreetTwo +' ' +SD.PresentStreetThree AS Address,
			
			SD.AcademicId,
			SD.StudentId, 
			SD.ClassId,
			SD.DivisionId,
			SD.ClassDivision,
			  
			SD.ClassName,
			SD.DivisionName,
			 
			OM.Title AS OrgName,
			SD.DivisionOrder,
			SD.Number AS StudentNumber,
			SD.Batch,                       
			
			SD.ClassStatusId,
			SD.ClassStatusName,
			ISNULL(SD.AdmissionDate,'') As AdmissionDate,
			ISNULL(SD.Gender,'') AS Gender,
			ISNULL(SD.StudentContactNo,'') AS StudentContactNo,
			ISNULL(SD.BirthPlace,'') AS BirthPlace,				--add for 26920 Mantis
			ISNULL(SD.UIDNUmber,'') AS UIDNumber	--Mantis - 45774
      
	FROM 
			sStudent.vStudentAllDetail SD
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=SD.OrgId
			LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId=SD.StudentId
			--INNER  JOIN sStudent.tStudentCommunication SC ON SC.StudentId = SD.StudentId
			--INNER JOIN sStudent.tStudentOther SO ON SO.StudentId = SD.StudentId
			LEFT JOIN sCommon.tCastCategoryMaster CCM ON CCM.Id = SD.CastCategoryId
			INNER JOIN sSetup.tBatchClass BC ON BC.ClassID =  SD.ClassId and BC.BatchId= @rBatchId 
			
	WHERE 
			SD.OrgId=@rOrgId
		AND	SD.BatchId = @rBatchId 
		AND (ISNULL(SD.Code,0) IN( SELECT cast(item as nvarchar(20)) FROM  sCommon.fnsplit(@rStrCode,',')) OR @rStrCode='') 
		AND ((SD.ClassId=@rClassId) OR (@rClassId=0))
		AND ((SD.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		AND ((SD.StudentId=@rStudentId) OR (@rStudentId=0))
		AND ((SD.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
		AND ((SD.RollNo <= @rToRollNo) OR (@rToRollNo=0))
		AND ((SD.StatusId=@rStatusId)OR(@rStatusId=0))
		AND ((SD.ClassStatusId=@rClassStatusId)OR(@rClassStatusId=0))
		AND ((MONTH(SD.DateOfBirth)=@rDateOfBirth OR @rDateOfBirth=0))
	    AND ((SD.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
END
GO
PRINT N'Altering Procedure [sStudent].[pRptStudentStrengthDivisionStatusWiseGet]...';


GO
ALTER PROCEDURE [sStudent].[pRptStudentStrengthDivisionStatusWiseGet]
	 
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 @rOrgId smallint,
	 @rBatchId int,
	 @rClassId int,
	 @rDivisionId int,
	 @rDepartmentId int,
	 
	 @rFromDate Date='',
	 @rToDate Date=''
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
  DECLARE @lCount Int
  Select
		@rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,
		CM.DisplayTitle AS Class,
		DM.DisplayTitle AS Division,
		CM.Id AS ClassID,
		DM.Id as DivisionId,
		DM.OrderIndex AS DivisionOrder,
		Cm.OrderINdex AS ClassOrderIndex  ,
		--A.StudentId ,
		CM.DisplayTitle+' - '+DM.DisplayTitle AS ClassDivision,
		(
			Select COUNT(A.Id) 
			from 
			sStudent.tAcademic A		
			INNER JOIN sStudent.tStudentMaster SM ON SM.Id=A.StudentId	
			INNER JOIN sStudent.tStudentAdmission SA ON SA.StudentId=SM.Id
			WHERE 
			A.OrgId=@rOrgId
			AND	A.BatchId = @rBatchId 
			AND (A.ClassId=CM.Id)
			AND (A.DivisionId=DM.Id) 
			AND SM.StatusId = 1
			AND ((SA.AdmissionDate>=@rFromDate) OR (ISNULL(@rFromDate,'')=''))
			AND ((SA.AdmissionDate<=@rToDate) OR (ISNULL(@rToDate,'')=''))
		)AS ActiveStudent,
	     (
			Select COUNT(A.Id) 
			from 
			sStudent.tAcademic A		
			INNER JOIN sStudent.tStudentMaster SM ON SM.Id=A.StudentId	
			INNER JOIN sStudent.tStudentAdmission SA ON SA.StudentId=SM.Id
			WHERE 
			A.OrgId=@rOrgId
			AND	A.BatchId = @rBatchId 
			AND (A.ClassId=CM.Id)
			AND (A.DivisionId=DM.Id) 
			AND SM.StatusId = 2
			AND ((SA.InactiveDate>=@rFromDate) OR (ISNULL(@rFromDate,'')=''))
			AND ((SA.InactiveDate<=@rToDate) OR (ISNULL(@rToDate,'')=''))
		)AS InActiveStudent,
		(
			Select COUNT(A.Id) 
			from 
			sStudent.tAcademic A		
			INNER JOIN sStudent.tStudentMaster SM ON SM.Id=A.StudentId	
			INNER JOIN sStudent.tStudentAdmission SA ON SA.StudentId=SM.Id
			WHERE 
			A.OrgId=@rOrgId
			AND	A.BatchId = @rBatchId 
			AND (A.ClassId=CM.Id)
			AND (A.DivisionId=DM.Id) 
			AND SM.StatusId = 3
			AND ((SA.LeftDate>=@rFromDate) OR (ISNULL(@rFromDate,'')=''))
			AND ((SA.LeftDate<=@rToDate) OR (ISNULL(@rToDate,'')=''))
		)AS LeftStudent
			FROM 
			 sSetup.tClassMaster CM  
			INNER JOIN sSetup.tDivisionMaster DM ON DM.ClassId=CM.Id
			INNER JOIN sSetup.tBatchClass BC ON BC.ClassID =  CM.Id and BC.BatchId= @rBatchId
			--LEFT JOIN sCommon.tCastCategoryMaster CCM ON CCM.Id=SO.CastCategoryId
			--LEFT JOIN sCommon.tReligionMaster RM ON RM.Id=SO.ReligionId
			--LEFT JOIN sCommon.tBloodGroupMaster BGM ON BGM.Id=SO.BloodGroupId
			--LEFT JOIN sStudent.tAdmissionCategoryMaster SCM ON SCM.Id=SM.AdmissionCategoryId
			  
    
	WHERE 
		 
		 ((CM.Id=@rClassId) OR (@rClassId=0))
		 AND ((DM.Id=@rDivisionId) OR (@rDivisionId=0))
		 AND CM.OrgId =@rOrgId
		 AND ((CM.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
		 AND DM.IsObsolete = 0	--Mantis - 45430
	   END
GO
PRINT N'Altering Procedure [sTally].[pReceiptPostingGet]...';


GO
ALTER PROCEDURE [sTally].[pReceiptPostingGet] 
	@rOrgGroupBatchId INT
	,@rReceiptBookId INT
	,@rReceiptDate DATE
	,@rToReceiptDate DATE
	,@rPayTypeId INT = 0
	,@rCustomNarration NVARCHAR(max) = ''
	,@rIsCustomNarration BIT = 0

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	DECLARE @lTallyPostingType NVARCHAR(100)
	DECLARE @lOrgGroupId INT

	SET @lOrgGroupId = LEFT(@rOrgGroupBatchId, 4) --Mantis - 38660

	--Mantis Start - 38660
	DECLARE @IsFeePostingWithoutDiscount NVARCHAR(50) = ''

	SELECT @IsFeePostingWithoutDiscount = ItemValue
	FROM sConfig.tConfigurationSetup
	WHERE ConfigurationId = 589
		AND SourceTypeId = 2010
		AND SourceId = @lOrgGroupId

	--Mantis End - 38660
	----Mantis Start - 38661
	DECLARE @IsTallyPostingPaytypeInCheque NVARCHAR(50) = ''

	SELECT @IsTallyPostingPaytypeInCheque = ItemValue
	FROM sConfig.tConfigurationSetup
	WHERE ConfigurationId = 590
		AND SourceTypeId = 2010
		AND SourceId = @lOrgGroupId

	----Mantis End - 38661
	SELECT @lOrgGroupId = OrgGroupId
	FROM sSetup.tOrgGroupBatchMaster
	WHERE Id = @rOrgGroupBatchId

	SELECT @lTallyPostingType = CASE 
			WHEN CS.ItemValue IS NULL
				THEN C.ItemValue
			ELSE CS.ItemValue
			END
	FROM sConfig.tConfigurationMaster C
	INNER JOIN sConfig.tConfigurationLevelMaster CM ON CM.Id = C.ConfigurationLevelId
	LEFT JOIN sConfig.tConfigurationSetup CS ON CS.ConfigurationId = C.Id
		AND CS.SOURCEID = @lOrgGroupId
	WHERE C.ItemKey = 'Tally.PostingType'

	IF @lTallyPostingType = 'FeeHeadWise'
	BEGIN
		SELECT ReceiptDate
			,ISNULL(FHM.Title, '') AS FeeName
			,PM.Title AS PayType
			,
			--Mantis Start - 38660
			CASE 
				WHEN @IsFeePostingWithoutDiscount = 'True'
					THEN SUM(ISNULL(FR.ReceiptAmount, 0.00)) --Mantis - 39608, --Mantis - 41740(Add SUM)
				ELSE SUM(ISNULL(FRD.Amount, 0.00))
				END AS Amount
			--Mantis End - 38660
			,CASE 
				WHEN @rIsCustomNarration = 1
					THEN STUFF((
								SELECT DISTINCT ',' + Replace(replace(replace(Replace(replace(Replace(replace(Replace(replace(Replace(replace(Replace(replace(Replace
								(replace(Replace(replace(replace(@rCustomNarration, '[Class]', isnull(SM1.ClassName, '')), '[Division]', Isnull(SM1.DivisionName, '')), 
								'[StudentsName]', isnull(SM1.Name, '')), '[RollNumber]', isnull(convert(NVARCHAR(200), SM1.RollNo), '0')), '[Batch]', isnull(SM1.BatchName, '')), 
								'[ReceiptNumber]', isnull(Convert(NVARCHAR(100), FR1.ReceiptNumber), '')), '[ReceiptDate]', isnull(Convert(NVARCHAR(100), FR1.ReceiptDate), '')), 
								'[ReceiptAmount]', isnull(Convert(NVARCHAR(100), FR1.ReceiptAmount), '')), '[ChequeNo]', isnull(Convert(NVARCHAR(100), CASE WHEN ISNULL											(FR1.ChequeNo, '') != '' THEN FR1.ChequeNo ELSE CONVERT(nvarchar(20), FR1.PaymentTransactionId) END), '')), 
								'[BankName]', isnull(FR1.BankName, '')), '[FeeName]', isnull(FM1.Title, '')), '[FeeAmount]', isnull(Convert(NVARCHAR(100), Sum(FRD1.Amount)), 
								'0.00')), '[FeeHeadName]', ISNULL(FHM.Title, '')), '[FeeHeadAmount]', isnull(Convert(NVARCHAR(100), Sum(FRD1.Amount)), '0.00')), 
								'[CollectionGroupName]', isNull(CGM1.Title, '')), '[DiscountAmount]', isnull(Convert(NVARCHAR(100), Sum(FR1.DiscountAmount)), 0.00)),
								 --Mantis - 38660
						--Mantis - 45616[(FR1.ChequeNo to CASE WHEN ISNULLb (FR1.ChequeNo, '') != '' THEN FR1.ChequeNo ELSE CONVERT(nvarchar(20), FR1.PaymentTransactionId) END)]
								'[ReceiptFromNumber]', isnull(Convert(NVARCHAR(10), (SELECT Min(ReceiptNumber) FROM sFee.tReceipt WHERE FR.ReceiptDate = ReceiptDate)), '')),										'[ReceiptToNumber]', isnull(Convert(NVARCHAR(10), (SELECT Max(ReceiptNumber) FROM sFee.tReceipt WHERE FR.ReceiptDate = ReceiptDate)), ''))
								FROM sFee.tReceipt FR1
								INNER JOIN sFee.tReceiptDetail FRD1 ON FR1.Id = FRD1.ReceiptId
								INNER JOIN sFee.tFeeSetup FS1 ON FS1.Id = FRD1.FeeSetupId
								INNER JOIN sStudent.vStudentAcademic SM1 ON SM1.ACademicId = FR1.SourceID
									AND SM1.OrgGRoupBatchId = FR1.OrgGRoupBatchId
								INNER JOIN sFee.tFeeMaster FM1 ON FM1.Id = FS1.FeeId --AND FRD.ReceiptId=FRD1.ReceiptId
								LEFT JOIN sFee.tCollectionGroupMaster CGM1 ON CGM1.Id = FS1.CollectionGroupId
								INNER JOIN sFee.tFeeHeadMaster FHM1 ON FHM1.Id = FM1.FeeHeadId
									AND FHM1.Id = FHM.Id
								WHERE FR.ReceiptDate = FR1.ReceiptDate
								GROUP BY SM1.ClassName
									,SM1.DivisionName
									,SM1.Name
									,SM1.RollNo
									,SM1.BatchName
									,FR1.ReceiptNumber
									,FR1.ReceiptDate
									,FR1.ReceiptAmount
									,FR1.ChequeNo
									,FR1.PayTypeId
									,FR1.BankName
									,FM1.Title
									,FHM1.Title
									,CGM1.Title -- Added for Fee amount not show proper in narration
									,FR1.DiscountAmount
									,FR1.PaymentTransactionId	--Mantis - 45616
								FOR XML PATH('')
								), 1, 1, '')
				ELSE 'Receipt generated for Batch : ' + (
						SELECT Title
						FROM sSetup.tOrgGroupBatchMaster
						WHERE Id = @rOrgGroupBatchId
						) + ' Receipt Date : ' + Convert(NVARCHAR(10), ReceiptDate) + ' and Receipt Number From ' + Convert(NVARCHAR(10), (
							SELECT Min(ReceiptNumber)
							FROM sFee.tReceipt
							WHERE FR.ReceiptDate = ReceiptDate
								AND IsObsolete = 0
							)) + ' -  ' + Convert(NVARCHAR(10), (
							SELECT Max(ReceiptNumber)
							FROM sFee.tReceipt
							WHERE FR.ReceiptDate = ReceiptDate
								AND IsObsolete = 0
							))
				END AS Narration
			,
			----Mantis Start - 38661
			CASE WHEN @IsTallyPostingPaytypeInCheque = 'True' THEN CASE WHEN FR.PayTypeId IN (7,8) THEN 2 ELSE FR.PayTypeId END ELSE FR.PayTypeId END AS PayTypeId
			----Mantis End - 38661
			,FHM.Id AS FeeId
			,0 AS ReceiptId
			,'' AS ChequeNo -- Added for mantis 0035195 by Foram(Remove ISNULL(FR.ChequeNo, '') for 45451 )
		FROM sFee.tReceipt FR
		INNER JOIN sFee.tReceiptDetail FRD ON FR.Id = FRD.ReceiptId
		INNER JOIN sFee.tFeeSetup FS ON FS.Id = FRD.FeeSetupId
		INNER JOIN sFee.tFeeMaster FM ON FM.Id = FS.FeeId
		INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id = FM.FeeHeadId
		INNER JOIN sFinanceCommon.tPayTypeMaster PM ON PM.Id = FR.PayTypeId
		WHERE FR.ReceiptBookId = @rReceiptBookId
			AND FR.IsObsolete = 0
			AND FR.OrgGroupBatchId = @rOrgGroupBatchId
			AND FR.ReceiptDate >= @rReceiptDate
			AND FR.ReceiptDate <= @rToReceiptDate
			AND (
				FR.PayTypeId = @rPayTypeId
				OR @rPayTypeId = 0
				)
		GROUP BY ReceiptDate
			,FHM.Title
			,PM.Title
			,FHM.Id
			,FR.PayTypeId
			--,FR.ChequeNo	--Mantis - 45451
			--,FR.ReceiptAmount	--Mantis - 41740
		ORDER BY ReceiptDate DESC
	END
	ELSE IF @lTallyPostingType = 'FeeHeadWiseCustom'
	BEGIN
		SELECT ReceiptDate
			,FR.Id AS FeeName
			,PM.Title AS PayType
			,
			--Mantis Start - 38660
			CASE 
				WHEN @IsFeePostingWithoutDiscount = 'True'
					THEN ISNULL(FR.ReceiptAmount, 0.00) --Mantis - 39608
				ELSE SUM(ISNULL(FRD.Amount, 0.00))
				END AS Amount
			--Mantis End - 38660
			,CASE 
				WHEN @rIsCustomNarration = 1
					THEN STUFF((
								SELECT DISTINCT ',' + Replace(replace(replace(Replace(replace(Replace(replace(Replace(replace(Replace(replace(Replace(replace
								(Replace(replace(Replace(replace(replace(@rCustomNarration, '[Class]', isnull(SM1.ClassName, '')), '[Division]', Isnull(SM1. DivisionName, '')), 
								'[StudentsName]', isnull(SM1.Name, '')), '[RollNumber]', isnull(convert(NVARCHAR(200), SM1.RollNo), '0')), '[Batch]', isnull(SM1.BatchName, '')), 
								'[ReceiptNumber]', isnull(Convert(NVARCHAR(100), FR1.ReceiptNumber), '')), '[ReceiptDate]', isnull(Convert(NVARCHAR(100), FR1.ReceiptDate), '')), 
								'[ReceiptAmount]', isnull(Convert(NVARCHAR(100), FR1.ReceiptAmount), '')), '[ChequeNo]', isnull(Convert(NVARCHAR(100), FR1.ChequeNo), '')), 
								'[BankName]', isnull(FR1.BankName, '')), '[FeeName]', ISNULL(FM1.Title,'')), '[FeeAmount]', isnull(Convert(NVARCHAR(100), Sum(FRD1.Amount)), 
								'0.00')), '[FeeHeadName]', ISNULL(FHM1.Title, '')), '[FeeHeadAmount]', isnull(Convert(NVARCHAR(100), Sum(FRD1.Amount)), '0.00')), 
								'[CollectionGroupName]', isNull(CGM1.Title, '')), '[DiscountAmount]', isnull(Convert(NVARCHAR(100), Sum(FR1.DiscountAmount)), 0.00)), 
								--Mantis - 38660 
								'[ReceiptFromNumber]', isnull(Convert(NVARCHAR(10), (SELECT Min(ReceiptNumber) FROM sFee.tReceipt WHERE FR.ReceiptDate = ReceiptDate 
								AND IsObsolete = 0)), '')), '[ReceiptToNumber]', isnull(Convert(NVARCHAR(10), (SELECT Max(ReceiptNumber) FROM sFee.tReceipt 
								WHERE FR.ReceiptDate = ReceiptDate AND IsObsolete = 0)), ''))
								FROM sFee.tReceipt FR1
								INNER JOIN sFee.tReceiptDetail FRD1 ON FR1.Id = FRD1.ReceiptId
								INNER JOIN sFee.tFeeSetup FS1 ON FS1.Id = FRD1.FeeSetupId
								INNER JOIN sStudent.vStudentAcademic SM1 ON SM1.ACademicId = FR1.SourceID AND SM1.OrgGRoupBatchId = FR1.OrgGRoupBatchId
								INNER JOIN sFee.tFeeMaster FM1 ON FM1.Id = FS1.FeeId --AND FRD.ReceiptId=FRD1.ReceiptId
								LEFT JOIN sFee.tCollectionGroupMaster CGM1 ON CGM1.Id = FS1.CollectionGroupId
								INNER JOIN sFee.tFeeHeadMaster FHM1 ON FHM1.Id = FM1.FeeHeadId
								WHERE FR.ReceiptDate = FR1.ReceiptDate
									AND FR.Id = FR1.Id
									AND FR1.IsObsolete = 0
								GROUP BY SM1.ClassName
									,SM1.DivisionName
									,SM1.Name
									,SM1.RollNo
									,SM1.BatchName
									,FR1.ReceiptNumber
									,FR1.ReceiptDate
									,FR1.ReceiptAmount
									,FR1.ChequeNo
									,FR1.PayTypeId
									,FR1.BankName
									,FM1.Title
									,FHM1.Title
									,CGM1.Title -- Added for Fee amount not show proper in narration
									,FR1.DiscountAmount
								FOR XML PATH('')
								), 1, 1, '')
				ELSE SM.Name + '(' + ClassName + ':' + DivisionName + ') ' + ' # Cheque No. :' + ISNULL(FR.ChequeNo, '') + ' BankName :' + ISNULL(FR.BankName, '')
				END AS Narration
			,
			----Mantis Start - 38661
			CASE WHEN @IsTallyPostingPaytypeInCheque = 'True' THEN CASE WHEN FR.PayTypeId IN (7,8) THEN 2 ELSE FR.PayTypeId END ELSE FR.PayTypeId END AS PayTypeId
			----Mantis End - 38661
			,0 AS FeeId
			,FR.Id AS ReceiptId
			,ISNULL(FR.ChequeNo, '') AS ChequeNo -- Added for mantis 0035195 by Foram
		FROM sFee.tReceipt FR
		INNER JOIN sFee.tReceiptDetail FRD ON FR.Id = FRD.ReceiptId
		INNER JOIN sStudent.vStudentAcademic SM ON SM.ACademicId = FR.SourceID
			AND SM.OrgGRoupBatchId = FR.OrgGRoupBatchId
		INNER JOIN sFee.tFeeSetup FS ON FS.Id = FRD.FeeSetupId
		INNER JOIN sFee.tFeeMaster FM ON FM.Id = FS.FeeId
		INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id = FM.FeeHeadId
		INNER JOIN sFinanceCommon.tPayTypeMaster PM ON PM.Id = FR.PayTypeId
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SM.OrgId
		LEFT JOIN sSetup.tOrgSubGroupMaster OSM ON OSM.id = OM.OrgSubGroupId
		WHERE FR.ReceiptBookId = @rReceiptBookId
			AND FR.IsObsolete = 0
			AND FR.OrgGroupBatchId = @rOrgGroupBatchId
			AND FR.ReceiptDate >= @rReceiptDate
			AND FR.ReceiptDate <= @rToReceiptDate
			AND (
				FR.PayTypeId = @rPayTypeId
				OR @rPayTypeId = 0
				)
		GROUP BY ReceiptDate
			,PM.Title
			,FR.PayTypeId
			,FR.Id
			,SM.Name + '(' + ClassName + ':' + DivisionName + ') ' + ' # Cheque No. :' + ISNULL(FR.ChequeNo, '') + ' BankName :' + ISNULL(FR.BankName, '')
			,FR.ChequeNo
			,FR.ReceiptAmount
		ORDER BY FR.Id
			,ReceiptDate DESC
	END
	ELSE IF @lTallyPostingType = 'OrgMainGroupWise'
	BEGIN
		SELECT ReceiptDate
			,SM.AcademicId AS FeeName
			,PM.Title AS PayType
			,
			--Mantis Start - 38660
			CASE 
				WHEN @IsFeePostingWithoutDiscount = 'True'
					THEN ISNULL(FR.ReceiptAmount, 0.00) --Mantis - 39608
				ELSE SUM(ISNULL(FRD.Amount, 0.00))
				END AS Amount
			--Mantis End - 38660
			,CASE 
				WHEN @rIsCustomNarration = 1
					THEN STUFF((
								SELECT DISTINCT ',' + Replace(replace(replace(Replace(replace(Replace(replace(Replace(replace(Replace(replace(Replace(replace(Replace
								(replace(Replace(replace(replace(@rCustomNarration, '[Class]', isnull(SM1.ClassName, '')), '[Division]', Isnull(SM1. DivisionName, '')), 
								'[StudentsName]', isnull(SM1.Name, '')), '[RollNumber]', isnull(convert(NVARCHAR(200), SM1.RollNo), '0')), '[Batch]', isnull(SM1.BatchName, '')), 
								'[ReceiptNumber]', isnull(Convert(NVARCHAR(100), FR1.ReceiptNumber), '')), '[ReceiptDate]', isnull(Convert(NVARCHAR(100), FR1.ReceiptDate), '')), 
								'[ReceiptAmount]', isnull(Convert(NVARCHAR(100), FR1.ReceiptAmount), '')), '[ChequeNo]', isnull(Convert(NVARCHAR(100), FR1.ChequeNo), '')), 
								'[BankName]', isnull(FR1.BankName, '')), '[FeeName]', ISNULL(FM1.Title ,'')), '[FeeAmount]', isnull(Convert(NVARCHAR(100), Sum(FRD1.Amount)), 
								'0.00')), '[FeeHeadName]', ISNULL(FHM1.Title, '')), '[FeeHeadAmount]', isnull(Convert(NVARCHAR(100), Sum(FRD1.Amount)), '0.00')), 
								'[CollectionGroupName]', isNull(CGM1.Title, '')), '[DiscountAmount]', isnull(Convert(NVARCHAR(100), Sum(FR1.DiscountAmount)), 0.00)), 
								--Mantis - 38660 
								'[ReceiptFromNumber]', isnull(Convert(NVARCHAR(10), FR1.ReceiptNumber), '')), 
								'[ReceiptToNumber]', isnull(Convert(NVARCHAR(10), FR1.ReceiptNumber), ''))
								FROM sFee.tReceipt FR1
								INNER JOIN sFee.tReceiptDetail FRD1 ON FR1.Id = FRD1.ReceiptId
								INNER JOIN sFee.tFeeSetup FS1 ON FS1.Id = FRD1.FeeSetupId
								INNER JOIN sStudent.vStudentAcademic SM1 ON SM1.ACademicId = FR1.SourceID
									AND SM1.OrgGRoupBatchId = FR1.OrgGRoupBatchId
								INNER JOIN sFee.tFeeMaster FM1 ON FM1.Id = FS1.FeeId --AND FRD.ReceiptId=FRD1.ReceiptId
								LEFT JOIN sFee.tCollectionGroupMaster CGM1 ON CGM1.Id = FS1.CollectionGroupId
								INNER JOIN sFinanceCommon.tPayTypeMaster PM1 ON PM1.Id = FR1.PayTypeId
								INNER JOIN sFee.tFeeHeadMaster FHM1 ON FHM1.Id = FM1.FeeHeadId
								WHERE FR.ReceiptDate = FR1.ReceiptDate
									AND PM.Title = PM1.Title
									AND SM.AcademicId = SM1.AcademicId
									AND FR.PayTypeId = FR1.PayTypeId
									AND FR1.IsObsolete = 0
								GROUP BY SM1.ClassName
									,SM1.DivisionName
									,SM1.Name
									,SM1.RollNo
									,SM1.BatchName
									,FR1.ReceiptNumber
									,FR1.ReceiptDate
									,FR1.ReceiptAmount
									,FR1.ChequeNo
									,FR1.PayTypeId
									,FR1.BankName
									,FM1.Title
									,FHM1.Title
									,CGM1.Title -- Added for Fee amount not show proper in narration
									,FR1.DiscountAmount
								FOR XML PATH('')
								), 1, 1, '')
				ELSE SM.Name + '(' + ClassName + ':' + DivisionName + ') ' + ' # Cheque No. :' + ISNULL(FR.ChequeNo, '') + ' BankName :' + ISNULL(FR.BankName, '')
				END AS Narration
			,
			----Mantis Start - 38661
			CASE WHEN @IsTallyPostingPaytypeInCheque = 'True' THEN CASE  WHEN FR.PayTypeId IN (7,8) THEN 2 ELSE FR.PayTypeId END ELSE FR.PayTypeId END AS PayTypeId
			----Mantis End - 38661
			,FR.Id AS FeeId
			,SM.AcademicId AS ReceiptId
			,ISNULL(FR.ChequeNo, '') AS ChequeNo -- Added for mantis 0035195 by Foram
		FROM sFee.tReceipt FR
		INNER JOIN sFee.tReceiptDetail FRD ON FR.Id = FRD.ReceiptId
		INNER JOIN sStudent.vStudentAcademic SM ON SM.ACademicId = FR.SourceID
			AND SM.OrgGRoupBatchId = FR.OrgGRoupBatchId
		INNER JOIN sFee.tFeeSetup FS ON FS.Id = FRD.FeeSetupId
		INNER JOIN sFee.tFeeMaster FM ON FM.Id = FS.FeeId
		INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id = FM.FeeHeadId
		INNER JOIN sFinanceCommon.tPayTypeMaster PM ON PM.Id = FR.PayTypeId
		INNER JOIN sSEtup.tOrganizationMaster OM ON OM.OrgSubGRoupID = @rReceiptBookId
			AND OM.ID = SM.OrgId
		WHERE FR.IsObsolete = 0
			AND FR.OrgGroupBatchId = @rOrgGroupBatchId
			AND FR.ReceiptDate >= @rReceiptDate
			AND FR.ReceiptDate <= @rToReceiptDate
			AND FR.PayTypeID = 2
			AND (
				FR.PayTypeId = @rPayTypeId
				OR @rPayTypeId = 0
				)
		GROUP BY ReceiptDate
			,PM.Title
			,SM.AcademicId
			,FR.PayTypeId
			,FR.Id
			,SM.Name + '(' + ClassName + ':' + DivisionName + ') ' + ' # Cheque No. :' + ISNULL(FR.ChequeNo, '') + ' BankName :' + ISNULL(FR.BankName, '')
			,FR.ChequeNo
			,FR.ReceiptAmount
		ORDER BY FR.Id
			,ReceiptDate DESC
	END
	ELSE IF @lTallyPostingType = 'ReceiptWise'
	BEGIN
		SELECT ReceiptDate
			,ISNULL(SLM.LedgerName, '') AS FeeName
			,PM.Title AS PayType
			,
			--Mantis Start - 38660
			CASE 
				WHEN @IsFeePostingWithoutDiscount = 'True'
					THEN ISNULL(FR.ReceiptAmount, 0.00) --Mantis - 39608
				ELSE SUM(ISNULL(FRD.Amount, 0.00))
				END AS Amount
			--Mantis End - 38660
			,CASE 
				WHEN @rIsCustomNarration = 1
					THEN STUFF((
								SELECT DISTINCT ',' + + Replace(replace(replace(Replace(replace(Replace(replace(Replace(replace(Replace(replace(Replace(replace(Replace(replace
								(Replace(replace(replace(@rCustomNarration, '[Class]', isnull(SM1.ClassName, '')), '[Division]', Isnull(SM1.DivisionName, '')), '[StudentsName]',
								 isnull(SM1.Name, '')), '[RollNumber]', isnull(convert(NVARCHAR(200), SM1.RollNo), '0')), '[Batch]', isnull(SM1.BatchName, '')), '[ReceiptNumber]',
								 isnull(Convert(NVARCHAR(100), FR1.ReceiptNumber), '')), '[ReceiptDate]', isnull(Convert(NVARCHAR(100), FR1.ReceiptDate), '')), '[ReceiptAmount]', 
								 isnull(Convert(NVARCHAR(100), FR1.ReceiptAmount), '')), '[ChequeNo]', isnull(Convert(NVARCHAR(100), FR1.ChequeNo), '')), '[BankName]', isnull
								 (FR1.BankName, '')), '[FeeName]', isnull(FM1.Title, '')), '[FeeAmount]', isnull(Convert(NVARCHAR(100), Sum(FRD1.Amount)), '0.00')), '[FeeHeadName]', 
								 ISNULL(FHM1.Title, '')), '[FeeHeadAmount]', isnull(Convert(NVARCHAR(100), Sum(FRD1.Amount)), '0.00')), '[CollectionGroupName]', isNull(CGM1.Title,'')
								 ), '[DiscountAmount]', isnull(Convert(NVARCHAR(100), Sum(FR1.DiscountAmount)), 0.00)), --Mantis - 38660
								'[ReceiptFromNumber]', isnull(Convert(NVARCHAR(10), FR1.ReceiptNumber), '')), 
								'[ReceiptToNumber]', isnull(Convert(NVARCHAR(10), FR1.ReceiptNumber), ''))
								FROM sFee.tReceipt FR1
								INNER JOIN sFee.tReceiptDetail FRD1 ON FR1.Id = FRD1.ReceiptId
								INNER JOIN sFee.tFeeSetup FS1 ON FS1.Id = FRD1.FeeSetupId
								INNER JOIN sStudent.vStudentAcademic SM1 ON SM1.ACademicId = FR1.SourceID
									AND SM1.OrgGRoupBatchId = FR1.OrgGRoupBatchId
								INNER JOIN sFee.tFeeMaster FM1 ON FM1.Id = FS1.FeeId --AND FRD.ReceiptId=FRD1.ReceiptId
								LEFT JOIN sFee.tCollectionGroupMaster CGM1 ON CGM1.Id = FS1.CollectionGroupId
								INNER JOIN sFinanceCommon.tPayTypeMaster PM1 ON PM1.Id = FR1.PayTypeId
								INNER JOIN sFee.tFeeHeadMaster FHM1 ON FHM1.Id = FM1.FeeHeadId
								LEFT JOIN sTally.tStudentLedgerMapping SLM1 ON SLM1.StudentId = SM1.StudentId
									AND SLM1.ReceiptBookid = FR1.ReceiptBookId
									AND SLM.LedgerName = SLM1.LedgerName
								WHERE FR1.ReceiptDate = FR.ReceiptDate
									AND FR1.PayTypeId = FR.PayTypeId
									AND A.StudentId = SM1.StudentId
									AND FR.ReceiptAmount = FR1.ReceiptAmount
									AND FR1.IsObsolete = 0
								GROUP BY SM1.ClassName
									,SM1.DivisionName
									,SM1.Name
									,SM1.RollNo
									,SM1.BatchName
									,FR1.ReceiptNumber
									,FR1.ReceiptDate
									,FR1.ReceiptAmount
									,FR1.ChequeNo
									,FR1.PayTypeId
									,FR1.BankName
									,FM1.Title
									,FHM1.Title
									,CGM1.Title -- Added for Fee amount not show proper in narration
									,FR1.DiscountAmount
								FOR XML PATH('')
								), 1, 1, '')
				ELSE CASE 
						WHEN FR.PayTypeId = 1
							THEN 'Std-' + ClassName + ':' + DivisionName + ' RollNo :' + convert(NVARCHAR(20), RollNo) + ' ' + BatchName + '-->' + STUFF((
										SELECT ',' + convert(NVARCHAR(20), isnull(FRD1.Amount, '')) + '-' + isnull(FM1.Title, '')
										FROM sFee.tReceipt FR1
										INNER JOIN sFee.tReceiptDetail FRD1 ON FR1.Id = FRD1.ReceiptId
										INNER JOIN sFee.tFeeSetup FS1 ON FS1.Id = FRD1.FeeSetupId
										INNER JOIN sFee.tFeeMaster FM1 ON FM1.Id = FS1.FeeId
											AND FRD.ReceiptId = FRD1.ReceiptId
										FOR XML PATH('')
										), 1, 1, '')
						WHEN FR.PayTypeId <> 1
							THEN 'Std-' + ClassName + ':' + DivisionName + ' RollNo :' + convert(NVARCHAR(20), RollNo) + ' ' + BatchName + '-->' + STUFF((
										SELECT ',' + convert(NVARCHAR(20), isnull(FRD1.Amount, '')) + '-' + isnull(FM1.Title, '')
										FROM sFee.tReceipt FR1
										INNER JOIN sFee.tReceiptDetail FRD1 ON FR1.Id = FRD1.ReceiptId
										INNER JOIN sFee.tFeeSetup FS1 ON FS1.Id = FRD1.FeeSetupId
										INNER JOIN sFee.tFeeMaster FM1 ON FM1.Id = FS1.FeeId
											AND FRD.ReceiptId = FRD1.ReceiptId
										FOR XML PATH('')
										), 1, 1, '') + '  Cheque No. :' + ISNULL(FR.ChequeNo, '') + ' BankName :' + ISNULL(FR.BankName, '')
						END
				END AS Narration
			,
			--A.Name+', '+ClassName + '-' + DivisionName+', '+A.OrganizationName+', ('+BatchName+')'
			--AS Narration,		
			----Mantis Start - 38661
			CASE 
				WHEN @IsTallyPostingPaytypeInCheque = 'True'
					THEN CASE 
							WHEN FR.PayTypeId IN (
									7
									,8
									)
								THEN 2
							ELSE FR.PayTypeId
							END
				ELSE FR.PayTypeId
				END AS PayTypeId
			----Mantis End - 38661
			,A.StudentId AS FeeId
			,FRD.ReceiptId
			,ISNULL(FR.ChequeNo, '') AS ChequeNo -- Added for mantis 0035195 by Foram
		FROM sFee.tReceipt FR
		INNER JOIN sFee.tReceiptDetail FRD ON FR.Id = FRD.ReceiptId
		INNER JOIN sFee.tFeeSetup FS ON FS.Id = FRD.FeeSetupId
		INNER JOIN sFee.tFeeMaster FM ON FM.Id = FS.FeeId
		INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id = FM.FeeHeadId
		INNER JOIN sFinanceCommon.tPayTypeMaster PM ON PM.Id = FR.PayTypeId
		INNER JOIN sStudent.vStudentAcademic A ON A.AcademicId = FR.SourceId
			AND A.OrgGRoupBatchId = FR.OrgGRoupBatchId
		LEFT JOIN sTally.tStudentLedgerMapping SLM ON SLM.StudentId = A.StudentId
			AND SLM.ReceiptBookid = FR.ReceiptBookId
		WHERE FR.ReceiptBookId = @rReceiptBookId
			AND FR.IsObsolete = 0
			AND FR.OrgGroupBatchId = @rOrgGroupBatchId
			AND FR.ReceiptDate >= @rReceiptDate
			AND FR.ReceiptDate <= @rToReceiptDate
			AND (
				FR.PayTypeId = @rPayTypeId
				OR @rPayTypeId = 0
				)
		GROUP BY ReceiptDate
			,PM.Title
			,SLM.LedgerName
			,FR.PayTypeId
			,A.StudentId
			,FRD.ReceiptId
			,Isnull(FR.ChequeNo, '')
			,ISNull(FR.BankName, '')
			,--A.Name+', '+ClassName + '-' + DivisionName+', '+A.OrganizationName+', ('+BatchName+')',
			'Std-' + ClassName + ':' + DivisionName + ' RollNo :' + convert(NVARCHAR(20), RollNo) + ' ' + BatchName
			,FR.ReceiptAmount
		ORDER BY ReceiptDate DESC
	END
	ELSE IF @lTallyPostingType = 'FeeHeadAndReceiptBookWise'
	BEGIN
		SELECT ReceiptDate
			,ISNULL(FHM.Title, '') AS FeeName
			,PM.Title AS PayType
			,
			--Mantis Start - 38660
			CASE 
				WHEN @IsFeePostingWithoutDiscount = 'True'
					THEN ISNULL(FR.ReceiptAmount, 0.00) --Mantis - 39608
				ELSE SUM(ISNULL(FRD.Amount, 0.00))
				END AS Amount
			--Mantis End - 38660
			,CASE 
				WHEN @rIsCustomNarration = 1
					THEN STUFF((
								SELECT DISTINCT ',' + Replace(replace(replace(Replace(replace(Replace(replace(Replace(replace(Replace(replace(Replace(replace(Replace
								(replace(Replace(replace(replace(@rCustomNarration, '[Class]', isnull(SM1.ClassName, '')), '[Division]', Isnull(SM1. DivisionName, '')), 
								'[StudentsName]', isnull(SM1.Name, '')), '[RollNumber]', isnull(convert(NVARCHAR(200), SM1.RollNo), '0')), '[Batch]', isnull(SM1.BatchName, '')), 
								'[ReceiptNumber]', isnull(Convert(NVARCHAR(100), FR1.ReceiptNumber), '')), '[ReceiptDate]', isnull(Convert(NVARCHAR(100), FR1.ReceiptDate), '')), 
								'[ReceiptAmount]', isnull(Convert(NVARCHAR(100), FR1.ReceiptAmount), '')), '[ChequeNo]', isnull(Convert(NVARCHAR(100), FR1.ChequeNo), '')), 
								'[BankName]', isnull(FR1.BankName, '')), '[FeeName]', ISNULL(FM1.Title,'')), '[FeeAmount]', isnull(Convert(NVARCHAR(100), Sum(FRD1.Amount)), 
								'0.00')), '[FeeHeadName]', ISNULL(FHM1.Title, '')), '[FeeHeadAmount]', isnull(Convert(NVARCHAR(100), Sum(FRD1.Amount)), '0.00')), 
								'[CollectionGroupName]', isNull(CGM1.Title, '')), '[DiscountAmount]', isnull(Convert(NVARCHAR(100), Sum(FR1.DiscountAmount)), 0.00)), 
								--Mantis - 38660
								'[ReceiptFromNumber]', isnull(Convert(NVARCHAR(10), FR1.ReceiptNumber), '')), 
								'[ReceiptToNumber]', isnull(Convert(NVARCHAR(10), FR1.ReceiptNumber), ''))
								FROM sFee.tReceipt FR1
								INNER JOIN sFee.tReceiptDetail FRD1 ON FR1.Id = FRD1.ReceiptId
								INNER JOIN sFee.tFeeSetup FS1 ON FS1.Id = FRD1.FeeSetupId
								INNER JOIN sStudent.vStudentAcademic SM1 ON SM1.ACademicId = FR1.SourceID
									AND SM1.OrgGRoupBatchId = FR1.OrgGRoupBatchId
								INNER JOIN sFee.tFeeMaster FM1 ON FM1.Id = FS1.FeeId --AND FRD.ReceiptId=FRD1.ReceiptId
								LEFT JOIN sFee.tCollectionGroupMaster CGM1 ON CGM1.Id = FS1.CollectionGroupId
								INNER JOIN sFinanceCommon.tPayTypeMaster PM1 ON PM1.Id = FR1.PayTypeId
								INNER JOIN sFee.tFeeHeadMaster FHM1 ON FHM1.Id = FM1.FeeHeadId
								LEFT JOIN sTally.tStudentLedgerMapping SLM1 ON SLM1.StudentId = SM1.StudentId
									AND SLM1.ReceiptBookid = FR1.ReceiptBookId
								WHERE FR1.ReceiptDate = FR.ReceiptDate
									AND PM1.Title = PM.Title
									AND FR1.PayTypeId = FR.PayTypeId
									AND FR1.IsObsolete = 0
								GROUP BY SM1.ClassName
									,SM1.DivisionName
									,SM1.Name
									,SM1.RollNo
									,SM1.BatchName
									,FR1.ReceiptNumber
									,FR1.ReceiptDate
									,FR1.ReceiptAmount
									,FR1.ChequeNo
									,FR1.PayTypeId
									,FR1.BankName
									,FM1.Title
									,FHM1.Title
									,CGM1.Title -- Added for Fee amount not show proper in narration
									,FR1.DiscountAmount
								FOR XML PATH('')
								), 1, 1, '')
				ELSE CASE 
						WHEN FR.PayTypeId = 1
							THEN 'Receiptno-' + CONVERT(NVARCHAR, isnull(FR.ReceiptNumber, '')) + STUFF((
										SELECT ',' + convert(NVARCHAR(20), isnull(FM1.title, ''))
										FROM sFee.tReceipt FR1
										INNER JOIN sFee.tReceiptDetail FRD1 ON FR1.Id = FRD1.ReceiptId
											AND FRD1.ReceiptId = FRD.ReceiptId
										INNER JOIN sFee.tFeeSetup FS1 ON FS1.Id = FRD1.FeeSetupId
										INNER JOIN sFee.tFeeMaster FM1 ON FM1.Id = FS1.FeeId
											AND FRD.ReceiptId = FRD1.ReceiptId
										FOR XML PATH('')
										), 1, 1, '')
						WHEN FR.PayTypeId <> 1
							THEN 'Receiptno-' + CONVERT(NVARCHAR, isnull(FR.ReceiptNumber, '')) + STUFF((
										SELECT ',' + convert(NVARCHAR(20), isnull(FM1.title, ''))
										FROM sFee.tReceipt FR1
										INNER JOIN sFee.tReceiptDetail FRD1 ON FR1.Id = FRD1.ReceiptId
											AND FRD1.ReceiptId = FRD.ReceiptId
										INNER JOIN sFee.tFeeSetup FS1 ON FS1.Id = FRD1.FeeSetupId
										INNER JOIN sFee.tFeeMaster FM1 ON FM1.Id = FS1.FeeId
											AND FRD.ReceiptId = FRD1.ReceiptId
										FOR XML PATH('')
										), 1, 1, '') + '  Cheque No. :' + ISNULL(FR.ChequeNo, '') + ' BankName :' + ISNULL(FR.BankName, '')
						END
				END AS Narration
			,
			----Mantis Start - 38661
			CASE 
				WHEN @IsTallyPostingPaytypeInCheque = 'True'
					THEN CASE 
							WHEN FR.PayTypeId IN (
									7
									,8
									)
								THEN 2
							ELSE FR.PayTypeId
							END
				ELSE FR.PayTypeId
				END AS PayTypeId
			----Mantis End - 38661
			,FHM.Id AS FeeId
			,0 AS ReceiptId
			,ISNULL(FR.ChequeNo, '') AS ChequeNo -- Added for mantis 0035195 by Foram
		FROM sFee.tReceipt FR
		INNER JOIN sFee.tReceiptDetail FRD ON FR.Id = FRD.ReceiptId
		INNER JOIN sFee.tFeeSetup FS ON FS.Id = FRD.FeeSetupId
		INNER JOIN sFee.tFeeMaster FM ON FM.Id = FS.FeeId
		INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id = FM.FeeHeadId
		INNER JOIN sFinanceCommon.tPayTypeMaster PM ON PM.Id = FR.PayTypeId
		WHERE FR.ReceiptBookId = @rReceiptBookId
			AND FR.IsObsolete = 0
			AND FR.OrgGroupBatchId = @rOrgGroupBatchId
			AND FR.ReceiptDate >= @rReceiptDate
			AND FR.ReceiptDate <= @rToReceiptDate
			AND (
				FR.PayTypeId = @rPayTypeId
				OR @rPayTypeId = 0
				)
		GROUP BY PM.Title
			,FRD.ReceiptId
			,FR.BankName
			,FR.ChequeNo
			,FM.Title
			,ReceiptDate
			,FHM.Title
			,PM.Title
			,FHM.Id
			,FR.PayTypeId
			,FR.ReceiptNumber
			,FRD.ReceiptId
			,Isnull(FR.ChequeNo, '')
			,ISNull(FR.BankName, '')
			,FM.Title
			,FR.ReceiptAmount
		--,FHM.Title
		ORDER BY ReceiptDate DESC
	END
	ELSE IF @lTallyPostingType = 'FeeHeadWiseReceipt_AllDetail'
	BEGIN
		SELECT ReceiptDate
			,FR.Id AS FeeName
			,PM.Title AS PayType
			,
			--Mantis Start - 38660
			CASE 
				WHEN @IsFeePostingWithoutDiscount = 'True'
					THEN SUM(ISNULL(FRD.Amount, 0.00)) - FR.DiscountAmount --ISNULL(FR.ReceiptAmount, 0.00)	--Mantis - 39608
				ELSE SUM(ISNULL(FRD.Amount, 0.00))
				END AS Amount
			--Mantis End - 38660
			,CASE 
				WHEN @rIsCustomNarration = 1
					THEN STUFF((
								SELECT DISTINCT ',' + Replace(replace(replace(Replace(replace(Replace(replace(Replace(replace(Replace(replace(Replace(replace(Replace
								(replace(Replace(replace(replace(replace(replace(@rCustomNarration, '[Class]', isnull(SM1.ClassName, '')),
								'[Division]', Isnull(SM1.DivisionName, '')), '[StudentsName]', isnull(SM1.Name, '')), '[RollNumber]', isnull(convert(NVARCHAR(200), SM1.RollNo), 
								'0')), '[Batch]', isnull(SM1.BatchName, '')), '[ReceiptNumber]', isnull(Convert(NVARCHAR(100), FR1.ReceiptNumber), '')), 
								'[ReceiptDate]', isnull(Convert(NVARCHAR(100), FR1.ReceiptDate), '')), '[ReceiptAmount]', isnull(Convert(NVARCHAR(100), FR1.ReceiptAmount), '')), 
								'Cheque No. :[ChequeNo]', CASE WHEN FR1.PayTypeId = 1 THEN '' ELSE 'Cheque No. :[ChequeNo]' END), '[ChequeNo]', isnull(Convert(NVARCHAR(100), 
								FR1.ChequeNo), '')), 'BankName :[BankName]', CASE WHEN FR1.PayTypeId = 1 THEN '' ELSE 'BankName :[BankName]' END), 
								'[BankName]', isnull(FR1.BankName, '')), '[FeeName]', isnull(FM1.Title, '')), '[FeeAmount]', isnull(Convert(NVARCHAR(100), Sum(FRD1.Amount)), 
								'0.00')), '[FeeHeadName]', ISNULL(FHM1.Title, '')), '[FeeHeadAmount]', isnull(Convert(NVARCHAR(100), Sum(FRD1.Amount)), '0.00')), 
								'[CollectionGroupName]', isNull(CGM1.Title, '')), '[DiscountAmount]', isnull(Convert(NVARCHAR(100), Sum(FR1.DiscountAmount)), 0.00)), 
								'[ReceiptFromNumber]', isnull(Convert(NVARCHAR(10), (SELECT Min(ReceiptNumber) FROM sFee.tReceipt WHERE FR.ReceiptDate = ReceiptDate 
								AND IsObsolete = 0)), '')), '[ReceiptToNumber]', isnull(Convert(NVARCHAR(10), (SELECT Max(ReceiptNumber) FROM sFee.tReceipt
								WHERE FR.ReceiptDate = ReceiptDate AND IsObsolete = 0)), ''))
								FROM sFee.tReceipt FR1
								INNER JOIN sFee.tReceiptDetail FRD1 ON FR1.Id = FRD1.ReceiptId
								INNER JOIN sFee.tFeeSetup FS1 ON FS1.Id = FRD1.FeeSetupId
								INNER JOIN sStudent.vStudentAcademic SM1 ON SM1.ACademicId = FR1.SourceID
									AND SM1.OrgGRoupBatchId = FR1.OrgGRoupBatchId
								INNER JOIN sFee.tFeeMaster FM1 ON FM1.Id = FS1.FeeId --AND FRD.ReceiptId=FRD1.ReceiptId
								LEFT JOIN sFee.tCollectionGroupMaster CGM1 ON CGM1.Id = FS1.CollectionGroupId
								INNER JOIN sFee.tFeeHeadMaster FHM1 ON FHM1.Id = FM1.FeeHeadId
								WHERE FR.ReceiptDate = FR1.ReceiptDate
									AND FR.Id = FR1.Id
									AND FR1.IsObsolete = 0
								GROUP BY SM1.ClassName
									,SM1.DivisionName
									,SM1.Name
									,SM1.RollNo
									,SM1.BatchName
									,FR1.ReceiptNumber
									,FR1.ReceiptDate
									,FR1.ReceiptAmount
									,FR1.ChequeNo
									,FR1.PayTypeId
									,FR1.BankName
									,FM1.Title
									,FHM1.Title
									,CGM1.Title -- Added for Fee amount not show proper in narration
									,FR1.DiscountAmount
								FOR XML PATH('')
								), 1, 1, '')
				ELSE CASE 
						WHEN FR.PayTypeId = 1
							THEN 'ReceiptNo-' + CONVERT(NVARCHAR, isnull(FR.ReceiptNumber, '')) + '(' + BatchName + ')'
						WHEN FR.PayTypeId <> 1
							THEN 'Receiptno-' + CONVERT(NVARCHAR, isnull(FR.ReceiptNumber, '')) + '(' + BatchName + ')' + '  Cheque No. :' + ISNULL(FR.ChequeNo, '') + ' BankName :' + ISNULL(FR.BankName, '')
						END
				END AS Narration
			,
			--Mantis Start - 38661
			CASE 
				WHEN @IsTallyPostingPaytypeInCheque = 'True' THEN CASE WHEN FR.PayTypeId IN (7,8) THEN 2 ELSE FR.PayTypeId END ELSE FR.PayTypeId
				END AS PayTypeId
			--Mantis End - 38661
			,FR.Id AS FeeId
			,FR.Id AS ReceiptId
			,ISNULL(FR.ChequeNo, '') AS ChequeNo -- Added for mantis 0035195 by Foram
		FROM sFee.tReceipt FR
		INNER JOIN sFee.tReceiptDetail FRD ON FR.Id = FRD.ReceiptId
		INNER JOIN sStudent.vStudentAcademic SM ON SM.ACademicId = FR.SourceID
			AND SM.OrgGRoupBatchId = FR.OrgGRoupBatchId
		INNER JOIN sFee.tFeeSetup FS ON FS.Id = FRD.FeeSetupId
		INNER JOIN sFee.tFeeMaster FM ON FM.Id = FS.FeeId
		INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id = FM.FeeHeadId
		INNER JOIN sFinanceCommon.tPayTypeMaster PM ON PM.Id = FR.PayTypeId
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SM.OrgId
		LEFT JOIN sSetup.tOrgSubGroupMaster OSM ON OSM.id = OM.OrgSubGroupId
		WHERE FR.ReceiptBookId = @rReceiptBookId
			AND FR.IsObsolete = 0
			AND FR.OrgGroupBatchId = @rOrgGroupBatchId
			AND FR.ReceiptDate >= @rReceiptDate
			AND FR.ReceiptDate <= @rToReceiptDate
			AND (
				FR.PayTypeId = @rPayTypeId
				OR @rPayTypeId = 0
				)
		GROUP BY ReceiptDate
			,PM.Title
			,FR.PayTypeId
			,FR.Id
			,isnull(FR.ReceiptNumber, '')
			,BatchName
			,ISNULL(FR.BankName, '')
			,ISNULL(FR.ChequeNo, '')
			,FR.DiscountAmount --FR.ReceiptAmount
		ORDER BY FR.Id
			,ReceiptDate DESC
	END
END
GO
PRINT N'Altering Procedure [sTally].[pReceiptTallyPostingAdd]...';


GO
ALTER PROCEDURE [sTally].[pReceiptTallyPostingAdd]	 
      @rXmlDoc nvarchar(MAX),     
      @rReceiptId Int,
      @rOrgGroupBatchId Int,
      @rVoucherNumber Int    
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

SET @rXmlDoc=REPLACE(@rXmlDoc,'&','AND')
DECLARE @lInterrorCode INT,
			@intDoc INT
		
	BEGIN TRY
	 BEGIN TRANSACTION	
		
	EXECUTE @lInterrorCode = sp_xml_preparedocument @intDoc OUTPUT, @rXmlDoc
	
	UPDATE sTally.tReceiptPosting
	SET
		TransactionDate=A1.ReceiptDate,
		ReceiptBookId=@rReceiptId,
		StudentId=A1.FeeId,
		OrgGroupBatchId=@rOrgGroupBatchId,
		PayTypeId=A1.PayTypeId,		
		Amount = A1.Amount,
		Narration = A1.Narration,
		ChequeNo = A1.ChequeNo	-- Added for mantis 0035195 by Foram
	FROM
	(
		SELECT	
			FeeId,
			PayTypeId,
			Amount,
			Narration,
			ReceiptDate,
			ChequeNo		-- Added for mantis 0035195 by Foram
			FROM OPENXML (@intDoc, '/Table/ReceiptTallyPosting', 1)
			WITH
			(
				FeeId bigint '@FeeId',
				PayTypeId int '@PayTypeId',
				Amount decimal(12,2) '@Amount',
				Narration nvarchar(max) '@Narration',
				ReceiptDate Date '@ReceiptDate',
				ChequeNo nvarchar(40) '@ChequeNo'	-- Added for mantis 0035195 by Foram
			))A1 INNER JOIN sTally.tReceiptPosting RP ON RP.StudentId = A1.FeeId AND RP.OrgGroupBatchId=@rOrgGroupBatchId
			AND RP.ReceiptBookId=@rReceiptId 
			AND RP.TransactionDate= A1.ReceiptDate --AND RP.Narration = A1.Narration
			AND RP.PayTypeId=A1.PayTypeId --Mantis End - 40573
			--AND RP.ChequeNo = A1.ChequeNo	--Mantis End - 45451
			
	

	INSERT INTO sTally.tReceiptPosting
		(
		TransactionDate,
		ReceiptBookId,
		FeeId,
		StudentId,
		OrgGroupBatchId,
		PayTypeId,		
		VoucherNumber,
		Amount,
		Narration,
		ChequeNo	-- Added for mantis 0035195 by Foram
		)
	SELECT
		A.ReceiptDate,
		@rReceiptId,
		0,
		A.FeeId,
		@rOrgGroupBatchId,
		A.PayTypeId,
		@rVoucherNumber  + ROW_NUMBER() OVER(ORDER BY ReceiptBookId),
		A.Amount,
		A.Narration,
		A.ChequeNo		-- Added for mantis 0035195 by Foram
	FROM OPENXML (@intDoc, '/Table/ReceiptTallyPosting', 1)
	WITH
	(
		FeeId bigint '@FeeId',
		PayTypeId int '@PayTypeId',
		Amount decimal(12,2) '@Amount',
		Narration nvarchar(max) '@Narration',
		ReceiptDate Date '@ReceiptDate',
		ChequeNo nvarchar(40) '@ChequeNo'			-- Added for mantis 0035195 by Foram	
	)A LEFT JOIN sTally.tReceiptPosting RP ON RP.StudentId = A.FeeId 
	AND RP.OrgGroupBatchId=@rOrgGroupBatchId
	AND RP.ReceiptBookId=@rReceiptId 
	AND RP.TransactionDate= A.ReceiptDate --AND RP.Narration = A.Narration
	AND RP.PayTypeId=A.PayTypeId --Mantis End - 40573
	--AND RP.ChequeNo = A.ChequeNo	--Mantis End - 45451
	WHERE RP.StudentId IS NULL
	
	SELECT 101 AS RESULT
	
	COMMIT TRANSACTION		
	END TRY

	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Altering Procedure [sTimetable].[pWebGetDropdownOnClassChange]...';


GO
ALTER   PROCEDURE [sTimetable].[pWebGetDropdownOnClassChange]
(
@rOrgId int,
@rSchemaId int,
@rClassId int
)
AS
BEGIN
		--Division
		SELECT D.Id AS DivisionId,D.DisplayTitle AS DivisionTitle FROM sSetup.tDivisionMaster D INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = D.OrgId INNER JOIN sTimetable.tAssignOrg AO ON d.OrgId = AO.OrgId WHERE AO.TimeTableSchemaId = @rSchemaId AND AO.OrgId = @rOrgId AND D.ClassId = @rClassId AND D.Id in(select Distinct DivisionId from sTimetable.tTeacherWorkLoad where TimeTableSchemaId =@rSchemaId);
		--Subject
		SELECT S.Id AS SubjectId, S.Title AS SubjectTitle
		FROM sSetup.tSubjectMaster S
		INNER JOIN sTimetable.tDivisionWorkload DW ON S.Id = DW.SubjectId
		INNER JOIN sSetup.tDivisionMaster D ON DW.DivisionId = D.ID
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = S.OrgId
		INNER JOIN sTimetable.tAssignOrg AO ON S.OrgId = AO.OrgId
		WHERE AO.TimeTableSchemaId = @rSchemaId
		AND AO.OrgId = @rOrgId
		AND D.ClassId = @rClassId
		AND S.Id in (select Distinct SubjectId from sTimetable.tTeacherWorkLoad where TimeTableSchemaId =@rSchemaId)
		GROUP BY S.Id, S.Title;
		--Teacher
		SELECT T.Id AS TeacherId,T.ShortName AS TeacherTitle
		FROM sHrm.tEmployeeMaster T
		INNER JOIN sTimetable.tTeacherworkload TW ON t.Id = Tw.EmployeeId
		INNER JOIN sSetup.tDivisionMaster D ON TW.DivisionId = D.ID
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = T.OrgId
		INNER JOIN sTimetable.tAssignOrg AO ON T.OrgId = AO.OrgId
		WHERE AO.TimeTableSchemaId = @rSchemaId
		AND AO.OrgId = @rOrgId
		AND D.ClassId = @rClassId
		AND T.Id in (select Distinct EmployeeId from sTimetable.tTeacherWorkLoad where TimeTableSchemaId =@rSchemaId)
		group by T.Id, t.ShortName
END
GO
PRINT N'Altering Procedure [sTimetable].[pWebGetDropdownOnDivisionChange]...';


GO
ALTER   PROCEDURE [sTimetable].[pWebGetDropdownOnDivisionChange](
	@rOrgId int,
	@rSchemaId int,
	@rClassId int,
	@rDivisionId int
)
AS
BEGIN
		--Subject
		SELECT S.Id AS SubjectId, S.Title AS SubjectTitle
		FROM sSetup.tSubjectMaster S
		INNER JOIN sTimetable.tDivisionWorkload DW ON S.Id = DW.SubjectId
		INNER JOIN sSetup.tDivisionMaster D ON DW.DivisionId = D.ID
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = S.OrgId
		INNER JOIN sTimetable.tAssignOrg AO ON S.OrgId = AO.OrgId
		--INNER JOIN sTimetable.tTeacherWorkLoad TW ON TW.TimeTableSchemaId = AO.TimeTableSchemaId AND D.Id = TW.DivisionId AND TW.SubjectId = S.Id
		WHERE AO.TimeTableSchemaId = @rSchemaId
		AND AO.OrgId = @rOrgId
		AND D.Id=@rDivisionId
		AND D.ClassId = @rClassId
		AND S.Id in (select Distinct SubjectId from sTimetable.tTeacherWorkLoad where TimeTableSchemaId =@rSchemaId)
		GROUP BY S.Id, S.Title;
		--Teacher

		SELECT T.Id AS TeacherId,T.ShortName AS TeacherTitle
		FROM sHrm.tEmployeeMaster T
		INNER JOIN sTimetable.tTeacherworkload TW ON t.Id = Tw.EmployeeId
		INNER JOIN sSetup.tDivisionMaster D ON TW.DivisionId = D.ID
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = T.OrgId
		INNER JOIN sTimetable.tAssignOrg AO ON T.OrgId = AO.OrgId
		WHERE AO.TimeTableSchemaId = @rSchemaId
		AND AO.OrgId = @rOrgId
		AND D.ClassId = @rClassId
		AND T.Id in (select Distinct EmployeeId from sTimetable.tTeacherWorkLoad where TimeTableSchemaId =@rSchemaId)
		group by T.Id, t.ShortName

END
GO
PRINT N'Altering Procedure [sTimetable].[pWebGetDropdownOnOrganizationChange]...';


GO
ALTER   PROCEDURE [sTimetable].[pWebGetDropdownOnOrganizationChange]
(@rOrgId int,
@rSchemaId int
)
AS
BEGIN
		--Class DropDown
		SELECT DISTINCT CR.Id AS ClassId,CR.Title + '-' + STR(CR.OrgId) AS ClassTitle FROM sSetup.tClassMaster CR INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = CR.OrgId INNER JOIN sTimetable.tAssignOrg AO ON CR.OrgId = AO.OrgId WHERE AO.TimeTableSchemaId = @rSchemaId AND AO.OrgId = @rOrgId and CR.Id in(select Distinct ClassId from sSetup.tDivisionMaster DM inner join sTimetable.tTeacherWorkLoad TL on DM.Id = TL.DivisionId where TL.TimeTableSchemaId =@rSchemaId);
		--Subject Dropdown
		SELECT DISTINCT S.Id AS SubjectId, S.Title AS SubjectTitle FROM sSetup.tSubjectMaster S INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = S.OrgId INNER JOIN sTimetable.tAssignOrg AO ON S.OrgId = AO.OrgId WHERE AO.TimeTableSchemaId = @rSchemaId AND AO.OrgId = @rOrgId and S.Id in(select Distinct SubjectId from sTimetable.tTeacherWorkLoad where TimeTableSchemaId =@rSchemaId);
		--Division Dropwdown
		SELECT DISTINCT D.Id AS DivisionId, D.DisplayTitle AS DivisionTitle FROM sSetup.tDivisionMaster D INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = D.OrgId INNER JOIN sTimetable.tAssignOrg AO ON D.OrgId = AO.OrgId WHERE AO.TimeTableSchemaId = @rSchemaId AND AO.OrgId = @rOrgId and D.Id in(select Distinct DivisionId from sTimetable.tTeacherWorkLoad where TimeTableSchemaId =@rSchemaId);
		--Teachers Dropdown
		SELECT DISTINCT T.ID AS TeacherId, T.ShortName  AS TeacherTitle FROM shRM.TEMPLOYEEMASTER T INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = t.OrgID INNER JOIN sTimetable.tAssignOrg AO ON t.orgid = AO.OrgId WHERE AO.TimeTableSchemaId = @rSchemaId AND AO.OrgId = @rOrgId AND T.Id in(select Distinct EmployeeId from sTimetable.tTeacherWorkLoad where TimeTableSchemaId =@rSchemaId) group by T.Id, t.ShortName
END
GO
PRINT N'Altering Procedure [sTimetable].[pWebGetdropdownTimetableShemachange]...';


GO
ALTER   PROCEDURE [sTimetable].[pWebGetdropdownTimetableShemachange] --991100022
@rSchemaId bigint
AS
BEGIN
        --Org Dropdown
		Select Distinct OM.Id, OM.Title from sSetup.tOrganizationMaster OM inner join sTimetable.tAssignOrg AO on OM.Id=AO.OrgId where AO.TimeTableSchemaId=@rSchemaId
		--Class DropDown
		SELECT DISTINCT CR.Id AS ClassId,CR.Title + '-' + STR(CR.OrgId) AS ClassTitle FROM sSetup.tClassMaster CR INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = CR.OrgId INNER JOIN sTimetable.tAssignOrg AO ON CR.OrgId = AO.OrgId WHERE AO.TimeTableSchemaId = @rSchemaId and CR.Id in(select Distinct ClassId from sSetup.tDivisionMaster DM inner join sTimetable.tTeacherWorkLoad TL on DM.Id = TL.DivisionId where TL.TimeTableSchemaId =@rSchemaId);
		--Subject Dropdown
		SELECT DISTINCT S.Id AS SubjectId, S.Title AS SubjectTitle FROM sSetup.tSubjectMaster S INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = S.OrgId INNER JOIN sTimetable.tAssignOrg AO ON S.OrgId = AO.OrgId WHERE AO.TimeTableSchemaId = @rSchemaId and S.Id in(select Distinct SubjectId from sTimetable.tTeacherWorkLoad where TimeTableSchemaId =@rSchemaId)
		--Division Dropwdown
		SELECT DISTINCT D.Id AS DivisionId, D.DisplayTitle AS DivisionTitle FROM sSetup.tDivisionMaster D INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = D.OrgId  INNER JOIN sTimetable.tAssignOrg AO ON D.OrgId = AO.OrgId WHERE AO.TimeTableSchemaId = @rSchemaId and D.Id in(select Distinct DivisionId from sTimetable.tTeacherWorkLoad where TimeTableSchemaId =@rSchemaId);
		--Teachers Dropdown
		SELECT DISTINCT T.ID AS TeacherId, T.ShortName  AS TeacherTitle FROM shRM.TEMPLOYEEMASTER T INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = t.OrgID INNER JOIN sTimetable.tAssignOrg AO ON t.orgid = AO.OrgId WHERE AO.TimeTableSchemaId = @rSchemaId AND T.Id in(select Distinct EmployeeId from sTimetable.tTeacherWorkLoad where TimeTableSchemaId =@rSchemaId)	group by T.Id, t.ShortName
END
GO
PRINT N'Creating Procedure [sAlert].[pClassworkStudentListApiGet]...';


GO
CREATE PROCEDURE [sAlert].[pClassworkStudentListApiGet]
	 
		 @rDivisionIds nvarchar(Max),
		 @rOrgId int,
	 	 @rBatchId int,	 	 	 	
	 	 @rTemplate nvarchar(max) 	,
		 @rMailSubject nvarchar(500)='',
		 @rSubjectId bigint,
		 @rClassworkIds nvarchar(Max)
		
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	
	SELECT 
		AC.divisionId,AC.Id,CS.IsOptional 
		INTO #DynamicTempTable
	FROM sAcademic.tClasswork AC 
		INNER JOIN [sSetup].[tClassSubject] CS ON CS.ClassId = AC.ClassId AND CS.SubjectId = AC.SubjectId 
		WHERE (ISNULL(AC.DivisionId,0) IN ( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,',')))
			AND AC.SubjectId = @rSubjectId
			AND (ISNULL(AC.Id,0) IN ( SELECT cast(item as bigint) FROM  sCommon.fnsplit(@rClassworkIds,',')))

	Select
		SC.OrgGroupId,
		SC.OrgId,
		SC.AcademicId,
		SC.Code,
		SC.Name,
		SC.ParentContactNo AS MobileNo,	
		SC.ParentEmail AS EmailId,
		ISNULL(SC.StudentContactNo,'') AS StudentContactNo,
		ISNULL(SC.StudentEmail,'') AS StudentEmail,
		ISNULL(SC.FatherContactNo,'') AS FatherContactNo,
		ISNULL(SC.FatherMail,'') AS FatherMail,
		ISNULL(SC.MotherContactNo,'') AS MotherContactNo,
		ISNULL(SC.MotherMail,'') AS MotherMail,
		(replace(replace(replace(replace(replace
		(@rTemplate,'[TeacherName]',EM.FirstName +''+EM.MiddleName+''+EM.LastName), 
		'[SubjectName]',SM.Title),
		'[ClassWork]',AC.Classwork), 
		'[HomeWork]',AC.Homework), 
		'[HomeworkEndDate]',AC.HomeWorkEndDate)) AS MsgText,
		'2003' AS SourceTypeId,
		SC.StudentId AS SourceId,
		2003 AS ReceiverSourceTypeId,
		SC.StudentId AS ReceiverSourceId,
		@rMailSubject AS Subject,
		AC.ClassId,
		AC.DivisionId,
		AC.SubjectId,
		EM.FirstName +''+EM.MiddleName+''+EM.LastName AS TeacherName,
		SM.Title AS SubjectName,
		AC.Classwork,
		AC.Homework,
		AC.HomeWorkEndDate,
		SC.WhatsAppContactNo,
		AC.Id AS DocumentId
				
	From sStudent.vStudentCommunication SC
		INNER JOIN sAcademic.tClasswork AC ON AC.ClassId = SC.ClassId AND AC.DivisionId=SC.DivisionId AND AC.BatchId =SC.BatchId
		INNER JOIN sStudent.vStudentAcademic SA  ON SC.AcademicId=SA.AcademicId AND SC.ClassId=SA.ClassId AND SC.DivisionId=SA.DivisionId
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SA.OrgId AND OM.Id=SC.OrgId
		INNER JOIN sSetup.tSubjectMaster SM ON SM.Id = AC.SubjectId
		INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id=AC.EmployeeId
		INNER JOIN [sSetup].[tClassSubject] CS ON CS.ClassId = SC.ClassId AND CS.SubjectId = SM.Id
		LEFT JOIN #DynamicTempTable DT ON DT.DivisionId = AC.DivisionId AND DT.Id = AC.Id
		LEFT JOIN [sAssessment].[tOptionalSubject] OS ON OS.ClassSubjectId = CS.Id AND Os.AcademicId = SA.AcademicId
	WHERE (SC.OrgId=@rOrgId)
		AND (SC.BatchId=@rBatchId)
		AND (SC.StatusId=1) AND SC.IsBlockAllAlert=0	
		AND (ISNULL(SC.DivisionId,0) IN ( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,',')))
		AND (AC.SubjectId=@rSubjectId)
		AND (ISNULL(AC.Id,0) IN ( SELECT cast(item as bigint) FROM  sCommon.fnsplit(@rClassworkIds,',')))
		AND OS.AcademicId IS NOT NULL
		AND DT.IsOptional=1

	UNION ALL

	SELECT 
		SC.OrgGroupId,
		SC.OrgId,
		SC.AcademicId,
		SC.Code,
		SC.Name,
		SC.ParentContactNo AS MobileNo,	
		SC.ParentEmail AS EmailId,
		ISNULL(SC.StudentContactNo,'') AS StudentContactNo,
		ISNULL(SC.StudentEmail,'') AS StudentEmail,
		ISNULL(SC.FatherContactNo,'') AS FatherContactNo,
		ISNULL(SC.FatherMail,'') AS FatherMail,
		ISNULL(SC.MotherContactNo,'') AS MotherContactNo,
		ISNULL(SC.MotherMail,'') AS MotherMail,
		--@rTemplate AS MsgText,
		(replace
			(replace
				(replace
					(replace
						(replace(@rTemplate,'[TeacherName]',EM.FirstName +''+EM.MiddleName+''+EM.LastName), 
					'[SubjectName]',SM.Title),
				'[ClassWork]',AC.Classwork), 
			'[HomeWork]',AC.Homework), 
		'[HomeworkEndDate]',AC.HomeWorkEndDate)) AS MsgText,
		'2003' AS SourceTypeId,
		SC.StudentId AS SourceId,
		2003 AS ReceiverSourceTypeId,
		SC.StudentId AS ReceiverSourceId,
		@rMailSubject AS Subject,
		AC.ClassId,
		AC.DivisionId,
		AC.SubjectId,
		EM.FirstName +''+EM.MiddleName+''+EM.LastName AS TeacherName,
		SM.Title AS SubjectName,
		AC.Classwork,
		AC.Homework,
		AC.HomeWorkEndDate,
		SC.WhatsAppContactNo,
		AC.Id AS DocumentId
				
	FROM sStudent.vStudentCommunication SC
		INNER JOIN sAcademic.tClasswork AC ON AC.ClassId = SC.ClassId AND AC.DivisionId=SC.DivisionId AND AC.BatchId =SC.BatchId
		INNER JOIN sStudent.vStudentAcademic SA  ON SC.AcademicId=SA.AcademicId AND SC.ClassId=SA.ClassId AND SC.DivisionId=SA.DivisionId
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SA.OrgId AND OM.Id=SC.OrgId
		INNER JOIN sSetup.tSubjectMaster SM ON SM.Id = AC.SubjectId
		INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id=AC.EmployeeId
		LEFT JOIN #DynamicTempTable DT ON DT.DivisionId = AC.DivisionId AND DT.Id = AC.Id
	WHERE (SC.OrgId=@rOrgId)
		AND (SC.BatchId=@rBatchId)
		AND (SC.StatusId=1) AND SC.IsBlockAllAlert=0	
		AND (ISNULL(SC.DivisionId,0) IN ( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,',')))
		AND (AC.SubjectId=@rSubjectId)
		AND (ISNULL(AC.Id,0) IN ( SELECT cast(item as bigint) FROM  sCommon.fnsplit(@rClassworkIds,',')))
		AND DT.IsOptional = 0
END
GO
PRINT N'Creating Procedure [sProcurement].[pRptStockInwardDetail]...';


GO
CREATE PROCEDURE [sProcurement].[pRptStockInwardDetail]
    @rBuilder1 nvarchar(max)='',
	@rBuilder2 nvarchar(max)='',
	@rReportId int,
	@rStoreLocationId int,
	@rMainGroupId int,
	@rSubGroupId int,
	@rStockItemCategoryId int,
	@rItemCode nvarchar(100) = '',
	@rItemName nvarchar(100) = '',
	@rOrgGroupId int
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	 SELECT @rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			SIM.Code AS ItemCode,
			SIM.Title AS ItemTitle,
			SU.Title AS UomTitle,
			SIRD.RequestedQuantity,
			SIRD.Remark,
			SIR.CreatedDateTime AS StockInwardDate,
			ISNULL(CAST(SIP.StandardPrice AS DECIMAL(18, 2)), '0') WeightedAverageCost,
			SB.AvailableQuantity AS AvailableQuantity
	   FROM 
			sProcurement.tStockInwardRequestDetail SIRD
		    INNER JOIN sIP.tStockItemMaster SIM ON SIM.Id = SIRD.StockItemId
			INNER JOIN sIP.tItemSubGroupMaster ISGM ON ISGM.Id = SIM.ItemSubGroupId
		    INNER JOIN sFinanceCommon.tStockUomMaster SU ON SU.Id = SIM.IssueStockUomId
		    INNER JOIN sIp.tStockItemPlanning SIP ON SIP.StockItemId = SIM.Id
			LEFT JOIN sProcurement.tStockBatch SB ON SB.StockItemId=SIm.Id
			LEFT JOIN sProcurement.tStockInwardRequest SIR ON SIR.Id = SIRD.StockInwardRequestId
	   WHERE SIRD.OrgGroupId = @rOrgGroupId
			 AND (SIM.StockItemCategoryId  = @rStockItemCategoryId  OR @rStockItemCategoryId = '')
			 AND (@rItemCode = SIM.Code OR  @rItemCode = '')
			 AND SIM.StoreLocationId = @rStoreLocationId
			 AND (ISGM.Id = @rSubGroupId OR @rSubGroupId = 0)
			 AND (ISGM.ItemMainGroupId = @rMainGroupId OR @rMainGroupId = 0)
END
GO
PRINT N'Altering Procedure [sAcademic].[pClassworkCloneAdd]...';


GO

ALTER PROCEDURE [sAcademic].[pClassworkCloneAdd]
	 
	 	@rBatchId int,
        @rId bigint,
        @rSubjectId int,
        @rClassId int,
        @rDivisionId int,
		@rClasswork nvarchar(max),
		@rHomework nvarchar(max),
		@rClassWorkDate date,
		@rHomeWorkEndDate date,
		@rEmployeeId bigint,
		@rCreatedUserId bigint,
		@rOrgId int,
		@rClassworkStatusId smallint = 1,
		@rHomeWorkStatusId smallint = 1
		
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	DECLARE @lNextNumber BIGINT 
	
	-- Temp Basis Update due to Wrong OrgId,BatchId paseed from Mobile End
	DECLARE @lOrgId smallint, @lOrgGroupBatchId int, @lBatchId int
	SELECT @lOrgId = OrgId from sSetup.tSubjectMaster Where Id = @rSubjectId
	SELECT @lOrgGroupBatchId =  OrgGroupBatchId from sSetup.tBatchMaster Where Id = @rBatchId
	SELECT @lBatchId = Id from sSetup.tBatchMaster Where OrgId = @lOrgId AND OrgGroupBatchId = @lOrgGroupBatchId 
	
	SET @rBatchId = @lBatchId
	SET @rOrgId = @lOrgId
	-- Ends
	
	-- Uncomment for Mantis Id : 0045734
	SELECT @rId = Id FROM sAcademic.tClasswork WHERE	
	        BatchId=@rBatchId AND
			SubjectId=@rSubjectId AND
			ClassId=@rClassId AND
			DivisionId=@rDivisionId AND
			EmployeeId = @rEmployeeId AND
			ClassWorkDate = @rClassWorkDate
	        
	IF(@rId = 0)	
	BEGIN
		
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sAcademic.tClasswork', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	INSERT INTO sAcademic.tClasswork
		(
			BatchId,
			Id,
			SubjectId,
			ClassId,
			DivisionId,
			Classwork,
			Homework,
			ClassWorkDate,
			HomeWorkEndDate,
			EmployeeId,
			CreatedUserId,
			CreatedDateTime,
			ClassworkStatusId,
			HomeWorkStatusId
		)
	VALUES
		(
			@rBatchId,
			@lNextNumber,
			@rSubjectId,
			@rClassId,
			@rDivisionId,
			CASE WHEN @rClassworkStatusId=1 THEN @rClasswork ELSE 'NA' END,
			CASE WHEN @rHomeWorkStatusId=1 THEN @rHomework ELSE 'NA' END,
			@rClassWorkDate,
			@rHomeWorkEndDate,
			@rEmployeeId,
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rClassworkStatusId,
		    @rHomeWorkStatusId
		)
		    SELECT @lNextNumber AS Result
	END	 

ELSE
	 BEGIN
	 
			If @rClassworkStatusId=2 SET @rClasswork='NA'
			If @rHomeWorkStatusId=2 SET  @rHomework='NA'
	 --SET @lNextNumber = @rId
	    UPDATE  sAcademic.tClasswork
	    SET
			BatchId=@rBatchId,
			SubjectId=@rSubjectId,
			ClassId=@rClassId,
			DivisionId=@rDivisionId,
			Classwork=@rClasswork,
			Homework=@rHomework,
			ClassWorkDate=@rClassWorkDate,
			HomeWorkEndDate=@rHomeWorkEndDate,
			EmployeeId=@rEmployeeId,
			UpdatedUserId=@rCreatedUserId,
			UpdatedDateTime=sCommon.fGetDate(),
			ClassworkStatusId=@rClassworkStatusId,
			HomeWorkStatusId=@rHomeWorkStatusId
	      
	      WHERE Id = @rId
	      SELECT 11 AS Result
	 END  	

	
	END TRY
	
	BEGIN CATCH 
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Altering Procedure [sAdmission].[pAdmissionGenerateReport]...';


GO
ALTER PROCEDURE [sAdmission].[pAdmissionGenerateReport]
 
	@rId bigint,
	@rClassId int,
	@rClassIds nvarchar(max)='',
	@rColumnName nvarchar(max) = '',
	@rOrderBy nvarchar(max) = 'RollNo',
	@rOrgId smallint,
	@rFormNo [nvarchar](20) = '',
	@rFirstName [nvarchar](50) = '',	
	@rLastName [nvarchar](50) = '',
	@rFatherName nvarchar(50)='',
	@rMotherName nvarchar(50)='',
	@rCountry [nvarchar](50) = '',
	@rState [nvarchar](50) = '',
	@rCity nvarchar(max) = '',
	@rStatusId nvarchar(max) = '',
	@rBloodGroupId nvarchar(max) = '',
	@rGenderId nvarchar(max) = '',
	@rReligionId nvarchar(max) = '',
	@rCastCategoryId nvarchar(max) = '',
	@rMotherTongue nvarchar(max) = '',
	@rNationality nvarchar(max) = '',
	@rFatherQualification nvarchar(max) = '',
	@rMotherQualification nvarchar(max) = '',
	@rFatherOccupation nvarchar(max) = '',
	@rMotherOccupation nvarchar(max) = '',
	@rPreviousSchool nvarchar(max) = '',
	@rDOBFromDate Date = '0001-01-01',
	@rDOBToDate Date = '9999-12-31',
	@rDOAFromDate Date = '0001-01-01',
	@rDOAToDate Date = '9999-12-31',
	@rBatchId int = 0,
	@rFromFormNo nvarchar(20), 
	@rToFormNo nvarchar(20),
	@rContactNo nvarchar(50) = '',
	@rReportName nvarchar(50) ='',
	@rPageIndex int,
	@rCreatedUserId bigint,
	@rIsCommon bit = 0,
	@rIsCommonForOrg bit = 0,
	@rSavedReport nvarchar(max) = ''
	

AS
BEGIN
	 
	SET NOCOUNT ON;

    IF(@rDOBFromDate IS NULL)
		SET @rDOBFromDate='0001-01-01'
	IF(@rDOBToDate IS NULL)
		SET @rDOBToDate='9990-12-31'
	IF(@rDOAFromDate IS NULL)
		SET @rDOAFromDate='0001-01-01'
	IF(@rDOAToDate IS NULL)
		SET @rDOAToDate='9990-12-31'

	If @rDOBToDate <> '9999-12-31'
		SET @rDOBToDate = DATEADD(d,1,@rDOBToDate)
	If @rDOAToDate <> '9999-12-31'
		SET @rDOAToDate = DATEADD(d,1,@rDOAToDate)
		
		IF(@rReportName != '' AND @rId = 0)
		BEGIN
			DECLARE @lNextNumber BIGINT, @query  AS NVARCHAR(MAX), @lColumnValue nvarchar(max) 
			declare @lColumnName nvarchar(max), @lClmNm nvarchar(max)
			declare @lOrderBy nvarchar(max), @lOrdBy nvarchar(max)
			EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sAdmission.tAdmissionCustomSearch', 0, 1, 1,@outNextNumber = @lNextNumber output
			--PRINT(@lNextNumber)
			--Removing Table Alias while Inserting in Table
			SET @lColumnName = @rColumnName
			SET @lClmNm = Replace(@lColumnName,'AT.','')
			SET @lClmNm = Replace(@lClmNm,'ACF.','')
			
			SET @lOrderBy = @rOrderBy
			SET @lOrdBy = Replace(@lOrderBy,'AT.','')
			SET @lOrdBy = Replace(@lOrdBy,'ACF.','')
			--print(@lOrdBy)
			--print(@lClmNm)
			INSERT INTO sAdmission.tAdmissionCustomSearch
			(
				Id,Title,ColumnName,OrderBy,OrgId,BatchId, ClassId, FormNo, FromFormNo, ToFormNo,StatusId,ClassIds,FirstName,LastName,FatherName, 
				MotherName, DOBFromDate,DOBToDate,DOAFromDate,DOAToDate,Country,State,City,ContactNo,GenderId,ReligionId,CastCategoryId,
				Nationality,BloodGroupId,MotherTongueId,PreviousSchool,FatherQualification,MotherQualification,FatherOccupation,MotherOccupation,
				IsCommonUsers,IsCommonForOrg, CreatedUserId,CreatedDateTime
			)
			VALUES
			(
				@lNextNumber,@rReportName,@lClmNm,@lOrdBy,@rOrgId,@rBatchId,@rClassId,@rFormNo,@rFromFormNo,@rToFormNo,@rStatusId,@rClassIds,@rFirstName,@rLastName,
				@rFatherName,@rMotherName,@rDOBFromDate,@rDOBToDate,@rDOAFromDate,@rDOAToDate,@rCountry,@rState,
				@rCity,@rContactNo,@rGenderId,@rReligionId,@rCastCategoryId,@rNationality,@rBloodGroupId,@rMotherTongue,
				@rPreviousSchool,@rFatherQualification,@rMotherQualification,@rFatherOccupation,@rMotherOccupation,
				@rIsCommon,@rIsCommonForOrg,@rCreatedUserId,sCommon.fGetDate()
			)
		END
		--IF(@rId > 0)
		--BEGIN
		--	Select @rColumnName=ColumnName,@rOrderBy=OrderBy,@rOrgId=OrgId,@rBatchId=BatchId,@rClassId=ClassId,@rFormNo=FormNo,
		--	@rFromFormNo=FromFormNo,@rToFormNo=ToFormNo,@rStatusId=StatusId,@rClassIds=ClassIds,@rFirstName=FirstName,@rLastName=LastName,
		--	@rFatherName=FatherName,@rMotherName=MotherName,@rDOBFromDate=DOBFromDate,@rDOBToDate=DOBToDate,@rDOAFromDate=DOAFromDate,
		--	@rDOAToDate=DOAToDate,@rCountry=Country,@rState=State,@rCity=City,@rContactNo=ContactNo,@rGenderId=GenderId,@rReligionId=ReligionId,
		--	@rCastCategoryId=CastCategoryId,@rNationality=Nationality,@rBloodGroupId=BloodGroupId,@rMotherTongue=MotherTongueId,@rPreviousSchool=PreviousSchool,
		--	@rFatherQualification=FatherQualification,@rMotherQualification=MotherQualification,@rFatherOccupation=FatherOccupation,@rMotherOccupation=MotherOccupation
		--	FROM sAdmission.tAdmissionCustomSearch WHERE Id=@rId
		--END

		DECLARE @Sql nvarchar(MAX)= ''
		
		SET @rFirstName = sCommon.fSearchStringGet(@rFirstName)
		SET @rLastName = sCommon.fSearchStringGet(@rLastName)
		SET @rFatherName = sCommon.fSearchStringGet(@rFatherName)
		SET @rMotherName = sCommon.fSearchStringGet(@rMotherName)
		SET @rCountry = sCommon.fSearchStringGet(@rCountry)
		SET @rState = sCommon.fSearchStringGet(@rState)
		SET @rCity = sCommon.fSearchStringGet(@rCity)
		SET @rNationality = sCommon.fSearchStringGet(@rNationality)
		SET @rMotherTongue = sCommon.fSearchStringGet(@rMotherTongue)
		SET @rPreviousSchool = sCommon.fSearchStringGet(@rPreviousSchool)
		SET @rFatherQualification = sCommon.fSearchStringGet(@rFatherQualification)
		SET @rMotherQualification = sCommon.fSearchStringGet(@rMotherQualification)
		SET @rFatherOccupation = sCommon.fSearchStringGet(@rFatherOccupation)
		SET @rMotherOccupation = sCommon.fSearchStringGet(@rMotherOccupation)
		
	SELECT * INTO #MyAdmissionSearchTable 
	FROM
	(SELECT  CASE 
			WHEN AF.BloodGroupId = 1 THEN 'A+'
			WHEN AF.BloodGroupId = 2 THEN 'A-'
			WHEN AF.BloodGroupId = 3 THEN 'B+'
			WHEN AF.BloodGroupId = 4 THEN 'B-'
			WHEN AF.BloodGroupId = 5 THEN 'O+'
			WHEN AF.BloodGroupId = 6 THEN 'O-'
			WHEN AF.BloodGroupId = 7 THEN 'AB+'
			WHEN AF.BloodGroupId = 8 THEN 'AB-'
			WHEN AF.BloodGroupId = 9 THEN '-'
			WHEN AF.BloodGroupId = 10 THEN 'A Rh+'
			WHEN AF.BloodGroupId = 11 THEN 'A Rh-'
		END AS BloodGroup, 
		CASE 
			WHEN AFD.LiveWithId = 1 THEN 'Both'
			WHEN AFD.LiveWithId = 2 THEN 'Father'
			WHEN AFD.LiveWithId = 3 THEN 'Mother'
			WHEN AFD.LiveWithId = 4 THEN 'Guardian'
		END AS LiveWith,
		CASE 
			WHEN AF.GenderId = 1 THEN 'Male'
			WHEN AF.GenderId = 2 THEN 'Female'
		END AS Gender,
		AF.Id,
		AF.FormNo as FormNo,
		AF.FirstName,
		AF.MiddleName,
		AF.LastName as SurName,
		AF.FirstName + ' '+  AF.LastName AS StudentName,
		AF.DateOfBirth,
		AF.OrgId,
		AF.BatchId,
		AF.StatusId,
		AF.StreetOne,
		AF.StreetTwo,
		AF.StreetThree,
		AF.Country,
		AF.State,
		AF.City,
	   AF.ZipCode,
	   AF.ContactNo,
	   AF.ContactEmail,
	   AF.Remark,
	   AF.PreviousSchool,
	   AF.MeritMarks,
	   AF.MeritGrade,
	   AF.GenderId,
	   AF.ReligionId,
	   AF.FamilyCast,
	   AF.FamilySubCast,
	   AF.CastCategoryId,
	   AF.StudentId,
	   AF.FormPassword,
	   AF.Nationality,
	   AF.MotherTongue,
	   AF.IsPysicalDeformity,
	   AF.PysicalDeformityRemark,
	   AF.IsMajorIllness,
	   AF.MajorIllnessRemark,
	   AF.IsAllergy,
	   AF.AllergyRemark,
	   AF.BirthPlace,
	   AF.BirthTaluka,
	   AF.BirthDistrict,
	   AF.BloodGroupId,
	   AF.AdhaarNumber,
	   AF.BirthState,
	   AF.BirthCountry,
	   AF.OriginalStudentPhoto,
	   AF.OtherInformation as OtherInformation,
	   AF.AdmissionDate AS AdmissionFormDate,
	   CASE WHEN AF.IsHostelRequired = 0 THEN 'No' WHEN AF.IsHostelRequired = 1 THEN 'Yes' END AS HostelRequired,
	   CASE WHEN AF.IsTransportRequired = 0 THEN 'No' WHEN AF.IsTransportRequired = 1 THEN 'Yes' END AS TransportRequired,
	   OM.Title as Organization, 
	   OM.AffiliationId,
	   BM.Title as Batch, 
	   BM.FromDate, 
	   BM.ToDate, 
	   SM.Title as Status,
	   CM.Id as ClassId,
	   CM.Title as Class,
	   RM.Title AS Religion,
	   APA1.AcademicYear as FatherAcademicYear,
	   APA1.AdmissionClass as FatherAdmissionClass,
	   APA1.InstituteName as FatherInstituteName,
	   APA1.InstituteCity as FatherInstituteCity,
	   APA1.InstituteAffiliaton as FatherInstituteAffiliation,
	   APA1.Language as FatherMediumOfStudy,
	   APA2.AcademicYear as MotherAcademicYear,
	   APA2.AdmissionClass as MotherAdmissionClass,
	   APA2.InstituteName as MotherInstituteName,
	   APA2.InstituteCity as MotherInstituteCity,
	   APA2.InstituteAffiliaton as MotherInstituteAffiliation,
	   APA2.Language as MotherMediumOfStudy,
	   APA3.AcademicYear as GuardianAcademicYear, 
	   APA3.AdmissionClass as GuardianAdmissionClass,
	   APA3.InstituteName as GuardianInstituteName,
	   APA3.InstituteCity as GuardianInstituteCity,
	   APA3.InstituteAffiliaton as GuardianInstituteAffiliation,
	   APA3.Language as GuardianMediumOfStudy,
	   RSM.Title,
	   (STUFF((SELECT ',' + ReferenceDetail FROM sAdmission.tAdmissionFormReference WHERE AdmissionFormId = AF.Id FOR XML PATH ('')), 1, 1, '')) AS ReferenceDetail,
	   (STUFF((SELECT ',' + ReferenceName FROM sAdmission.tAdmissionFormReference WHERE AdmissionFormId = AF.Id FOR XML PATH ('')), 1, 1, '')) AS ReferenceName,
	   (STUFF((SELECT ',' + ReferenceRelation FROM sAdmission.tAdmissionFormReference WHERE AdmissionFormId = AF.Id FOR XML PATH ('')), 1, 1, '')) AS ReferenceRelation,
	   (STUFF((SELECT ',' + ReferenceContactNo FROM sAdmission.tAdmissionFormReference WHERE AdmissionFormId = AF.Id FOR XML PATH ('')), 1, 1, '')) AS ReferenceContactNo,
	   AFSA.AcademicYear as StudentAcademicYear,
	   AFSA.AdmissionClass as StudentAdmissionClass,
	   (STUFF((SELECT ',' + SiblingName FROM sAdmission.tAdmissionFormSibling WHERE AdmissionFormId = AF.Id FOR XML PATH ('')), 1, 1, '')) AS SiblingName,
	   (STUFF((SELECT ',' + SiblingRelation FROM sAdmission.tAdmissionFormSibling WHERE AdmissionFormId = AF.Id FOR XML PATH ('')), 1, 1, '')) AS SiblingRelation,
	   (STUFF((SELECT ',' + SiblingStandard FROM sAdmission.tAdmissionFormSibling WHERE AdmissionFormId = AF.Id FOR XML PATH ('')), 1, 1, '')) AS SiblingStandard,
	   (STUFF((SELECT ',' + SiblingSchool FROM sAdmission.tAdmissionFormSibling WHERE AdmissionFormId = AF.Id FOR XML PATH ('')), 1, 1, '')) AS SiblingSchool,
	   (STUFF((SELECT ',' + Code FROM sAdmission.tAdmissionFormSibling WHERE AdmissionFormId = AF.Id FOR XML PATH ('')), 1, 1, '')) AS Code,
	   AFSA.InstituteName as StudentInstituteName,
	   AFSA.InstituteCity as StudentInstituteCity,
	   AFSA.InstituteAffiliaton as StudentInstituteAffiliation, 
	   AFSA.Result, 
	   AFSA.Language,
	   AFD.FatherName, 
	   AFD.FatherDateOfBirth,
	   AFD.FatherOccupation,
	   AFD.FatherQualification,
	   AFD.FatherContactNo,
	   AFD.FatherMail,
	   AFD.FatherOfficeAddress,
	   AFD.FatherIncome AS FatherAnnualIncome, -- MantisId : 0029214 Changed label FatherIncome to FatherAnnualIncome
	   AFD.MotherName,
	   AFD.MOtherDateOfBirth,
	   AFD.MotherOccupation,
	   AFD.MotherQualification,
	   AFD.MotherContactNo,
	   AFD.MotherMail,
	   AFD.MotherOfficeAddress, 
	   AFD.MotherIncome AS MotherAnnualIncome, -- MantisId : 0029214 Changed label MotherIncome to MotherAnnualIncome
	   AFD.RelationshipName,
	   AFD.RelativeName,
	   AFD.RelativeDateOfBirth,
	   AFD.RelativeOccupation,
	   AFD.RelativeQualification,
	   AFD.RelativeContactNo,
	   AFD.RelativeMail,
	   AFD.RelativeOfficeAddress,
	   AFD.RelativeIncome AS RelativeAnnualIncome,	-- MantisId : 0029214 Changed label RelativeIncome to RelativeAnnualIncome
	   AFD.FatherPhoto,
	   AFD.MotherPhoto,
	   AFD.RelativePhoto,
	   AFD.FatherOrganization,
	   AFD.FatherDesignation,
	   AFD.FatherOfficePhone,
	   AFD.MotherOrganization,
	   AFD.MotherDesignation,
	   AFD.MotherOfficePhone,
	   AFD.RelativeOrganization,
	   AFD.RelativeDesignation,
	   AFD.RelativeOfficePhone,
	   AFD.IsFatherExStudent,
	   AFD.FatherPassOutYear,
	   AFD.IsMotherExStudent,
	   AFD.MotherPassOutYear, 
	   AFD.IsRelativeExStudent,
	   AFD.RelativePassOutYear,
	   AFD.FatherAdhaarNumber,
	   AFD.OriginalFatherPhoto,
	   AFD.OriginalMotherPhoto,
	   AFD.OriginalRelativePhoto,
	   AFD.MotherAadhaarNumber,
	   AFD.RelativeAadhaarNumber,
	   U.LoginTitle As AdmissionHandledBy,
	   SM1.CreatedDateTime AS AdmissionFormConvertedDate,
	   ISNULL(AFD.FatherPANCardNumber,'') AS FatherPANCardNumber,	--add for mantis: 38342
	   ISNULL(AFD.MotherPANCardNumber,'') AS MotherPANCardNumber,	--add for mantis: 38342
	   ISNULL(AF.WhatsappContactNo,'') AS WhatsappContactNo		--add for mantis: 38342
		from sAdmission.tAdmissionForm AF
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = AF.OrgId
		INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AF.BatchId
		INNER JOIN  sCommon.tStatusMaster SM ON AF.StatusId = SM.Id
		INNER JOIN sSetup.tClassMaster CM ON CM.Id = AF.ForClassId
		INNER JOIN sSecurity.tUser U ON U.Id = AF.CreatedUserId
		LEFT JOIN  sStudent.tStudentAdmission SA ON SA.AdmissionFormId = AF.Id
		LEFT JOIN  sStudent.tStudentMaster SM1 ON SM1.Id = AF.StudentId AND AF.StatusId=208
		LEFT JOIN sCommon.tReligionMaster RM ON RM.Id = AF.ReligionId
		LEFT JOIN sAdmission.tAdmissionFormParentAcademic APA1 ON APA1.AdmissionFormId = AF.Id AND APA1.RelationShipId = 1
		LEFT JOIN sAdmission.tAdmissionFormParentAcademic APA2 ON APA2.AdmissionFormId = AF.Id AND APA2.RelationShipId = 2
		LEFT JOIN sAdmission.tAdmissionFormParentAcademic APA3 ON APA3.AdmissionFormId = AF.Id AND APA3.RelationShipId = 7
		LEFT JOIN sCommon.tRelationshipMaster RSM ON RSM.Id = APA1.RelationshipId
		LEFT JOIN sCommon.tRelationshipMaster RSM1 ON RSM1.Id = APA2.RelationshipId
		LEFT JOIN sCommon.tRelationshipMaster RSM2 ON RSM2.Id = APA3.RelationshipId
		--LEFT JOIN sAdmission.tAdmissionFormReference AFR ON AFR.AdmissionFormId = AF.Id
		--LEFT JOIN sAdmission.tAdmissionFormSibling AFS ON AFS.AdmissionFormId = AF.Id
		LEFT JOIN sAdmission.tAdmissionFormStudentAcademic AFSA ON AFSA.AdmissionFormId = AF.Id
		LEFT JOIN sAdmission.tAdmissionFormFamilyDetail AFD ON AFD.AdmissionFormId = AF.Id
		WHERE ((AF.OrgId = @rOrgId ) OR (@rOrgId = 0))
				AND ((AF.BatchId = @rBatchId) OR (@rBatchId = 0))
				AND ((AF.ForClassId = @rClassId) OR (@rClassId = 0))
			    AND ((ISNULL(AF.ForClassId,0) IN (SELECT cast(item as int) FROM sCommon.fnsplit(@rClassIds,',')) OR (@rClassIds='')))
				AND ((AF.FormNo = @rFormNo) OR (@rFormNo = ''))
				AND ((AF.FormNo  >= @rFromFormNo) OR (ISNULL(@rFromFormNo,'') = ''))
				AND ((AF.FormNo  <= @rToFormNo) OR (ISNULL(@rToFormNo,'') = ''))
			    AND (AF.StatusId = @rStatusId)
				AND ((AF.FirstName Like @rFirstName) OR (@rFirstName = ''))
				AND ((AF.LastName Like @rLastName)OR(@rLastName = ''))
				AND ((AFD.FatherName like @rFatherName) OR (@rFatherName=''))
				AND ((AFD.MotherName like @rMotherName) OR (@rMotherName=''))
				AND (( AF.DateOfBirth  >= @rDOBFromDate) OR (ISNULL(@rDOBFromDate,'') = ''))
				AND (( AF.DateOfBirth  <= @rDOBToDate) OR (ISNULL(@rDOBToDate,'') = ''))
				--AND (( CAST(AF.CreatedDateTime AS Date)  >= @rDOAFromDate) OR (ISNULL(@rDOAFromDate,'') = ''))
				--AND (( CAST(AF.CreatedDateTime AS Date)  <= @rDOAToDate) OR (ISNULL(@rDOAToDate,'') = ''))
				AND ((Convert(nvarchar(12),AF.CreatedDateTime) >=  @rDOAFromDate) OR (@rDOAFromDate=''))
			    AND ((Convert(nvarchar(12),AF.CreatedDateTime) <=  @rDOAToDate) OR (@rDOAToDate=''))
				AND ((ISNULL(AF.Country,'') Like @rCountry )OR(@rCountry = ''))
				AND ((ISNULL(AF.State,'') Like @rState)OR(@rState = ''))
				AND ((ISNULL(AF.City,'') Like @rCity)OR(@rCity = ''))
				AND ((AF.ContactNo=@rContactNo) OR (@rContactNo=0))
				AND (ISNULL(AF.GenderId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rGenderId,','))OR @rGenderId='') 
				AND (ISNULL(AF.ReligionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rReligionId,','))OR @rReligionId='')
				AND (ISNULL(AF.CastCategoryId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rCastCategoryId,','))OR @rCastCategoryId='')
				AND ((AF.Nationality Like @rNationality) OR (@rNationality = ''))
				AND (ISNULL(AF.BloodGroupId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rBloodGroupId,','))OR @rBloodGroupId='')
				AND ((AF.MotherTongue Like @rMotherTongue) OR (@rMotherTongue = ''))
				AND ((AF.PreviousSchool Like  @rPreviousSchool) OR (@rPreviousSchool = ''))
				AND ((AFD.FatherQualification Like  @rFatherQualification) OR (@rFatherQualification = ''))
				AND ((AFD.MotherQualification Like @rMotherQualification) OR (@rMotherQualification = ''))
				AND ((AFD.FatherOccupation Like @rFatherOccupation) OR (@rFatherOccupation = ''))
				AND ((AFD.MotherOccupation Like @rMotherOccupation) OR (@rMotherOccupation = '')) 
				) AS AdmissionReportGeneration
				
		  --SELECT * FROM #MyAdmissionSearchTable

		  --AdmissionCriteriaFields
		  DECLARE @cols AS NVARCHAR(MAX),@criteriaquery  AS NVARCHAR(MAX)
			-- CTE for Admission Form Field
			;WITH AdmissionCriteriaFormCTE AS (SELECT  DISTINCT FieldRemark FROM sAdmission.tAdmissionCriteriaForm ACF
			LEFT JOIN sAdmission.tAdmissionFormField AFF ON ACF.Id = AFF.AdmissionCriteriaFormId
			--WHERE (ACF.BatchId = @rBatchId OR @rBatchId = 0) AND (ACF.ClassId = @rClassId OR @rClassId = 0)
			GROUP BY Id,FieldRemark,ClassId,BatchId
			)
			SELECT @cols = STUFF((SELECT  ',' + QUOTENAME(FieldRemark) FROM AdmissionCriteriaFormCTE
			GROUP BY FieldRemark
			ORDER BY FieldRemark FOR XML PATH(''), TYPE ).value('.', 'NVARCHAR(MAX)'),1,1,'')
			

			IF object_id('tempdb..##tempAdmissionCriteriaForm') IS NOT NULL 
			BEGIN
			--print('Hi')
			   DROP TABLE ##tempAdmissionCriteriaForm 
			END
			IF(@cols IS NOT NULL)
			BEGIN 
				SET @criteriaquery = 'SELECT DISTINCT AdmissionFormId,' + @cols + ' INTO ##tempAdmissionCriteriaForm FROM 
							 (
								SELECT DISTINCT  AFF.AdmissionFormId,AdmissionFormFieldResponse, FieldRemark
								FROM 
								sAdmission.tAdmissionCriteriaForm ACF
								INNER JOIN sAdmission.tAdmissionFormField AFF ON ACF.Id = AFF.AdmissionCriteriaFormId
								WHERE ((ACF.BatchId = '+CONVERT(nvarchar(10),@rBatchId)+') OR (' +CONVERT(nvarchar(10),@rBatchId)+' = 0)) AND ((ACF.ClassId = '+CONVERT(nvarchar(10),@rClassId)+') OR ('+CONVERT(nvarchar(10),@rClassId)+' = 0))
							) x
							PIVOT
							(
								MAX(AdmissionFormFieldResponse)
								FOR FieldRemark IN (' + @cols + ')
							) p' 
				print(@criteriaquery)
				exec (@criteriaquery)
				
				  --SELECT * FROM #MyAdmissionSearchTable
				--SELECT * FROM ##tempAdmissionCriteriaForm ACF
			END
			IF(@cols IS NULL)
				Declare @lSQLAlt nvarchar(max)=''
				IF(@rOrderBy = '' OR @rOrderBy = NULL)
				BEGIN
					SET @lSQLAlt = @lSQLAlt + 'SELECT ' + @rColumnName + ' FROM #MyAdmissionSearchTable AT '
					print(@lSQLAlt)
					exec(@lSQLAlt)
				END
				ELSE
				BEGIN
				print(@rOrderBy)
				SET @lSQLAlt = @lSQLAlt + 'SELECT ' + @rColumnName + ' FROM #MyAdmissionSearchTable AT GROUP BY ' +@rColumnName+ ',' +@rOrderBy+ ' ORDER BY ' +@rOrderBy+ ';'
				print(@lSQLAlt)
				exec (@lSQLAlt)
				END

		  --
		IF(@cols IS NOT NULL)
		Declare @lSQL nvarchar(max) ='', @lqry nvarchar(max)=''
		IF(@rOrderBy = '' OR @rOrderBy = NULL)
		BEGIN
			--SET @lSQL = @lSQL + 'SELECT ' + @rColumnName + ' FROM #MyAdmissionSearchTable AT'
			SET @lSQL = @lSQL + 'SELECT ' + @rColumnName + ' FROM #MyAdmissionSearchTable AT LEFT JOIN ##tempAdmissionCriteriaForm ACF ON AT.Id = ACF.AdmissionFormId'
			print(@lSQL)
			exec(@lSQL)
		END
		ELSE
		BEGIN
		print(@rOrderBy)
			SET @lSQL = @lSQL + 'SELECT ' + @rColumnName + ' FROM #MyAdmissionSearchTable AT LEFT JOIN ##tempAdmissionCriteriaForm ACF ON AT.Id = ACF.AdmissionFormId ORDER BY ' +@rOrderBy+ ';'
			print(@lSQL)
			exec (@lSQL)
			IF OBJECT_ID(N'dbo.MyTable0', N'U') IS NOT NULL 
			 DROP Table ##tempAdmissionCriteriaForm
		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 AND CS.SourceTypeId = 2010 AND CS.SourceId = @rOrgGroupId
	 
	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.07.15',250715,'END','Script',sCommon.fGetDate(),sCommon.fGetDate(),0)
GO