

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


GO
PRINT N'Altering Table [sCommon].[tReportFormatGroupOrg]...';


GO
ALTER TABLE [sCommon].[tReportFormatGroupOrg]
    ADD [PrintTemplateId] INT NULL;


GO
PRINT N'Altering Table [sFee].[tPostDatePayment]...';


GO
ALTER TABLE [sFee].[tPostDatePayment]
    ADD [DepositedDate] DATETIME NULL;


GO
PRINT N'Altering Table [sStudent].[tStudentMasterDelete]...';


GO
ALTER TABLE [sStudent].[tStudentMasterDelete] ALTER COLUMN [SUId] NVARCHAR (50) NULL;


GO
PRINT N'Altering Table [sTally].[tReceiptPosting]...';


GO
ALTER TABLE [sTally].[tReceiptPosting] ALTER COLUMN [Narration] NVARCHAR (MAX) NULL;


GO
--PRINT N'Creating Table [sStudent].[tTempStudentId]...';


--GO
--CREATE TABLE [sStudent].[tTempStudentId] (
--    [NewStudentId]        BIGINT        NULL,
--    [StudentId]           BIGINT        NULL,
--    [Code]                NVARCHAR (24) NULL,
--    [AdmissionCategoryId] INT           NULL
--);


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


GO
ALTER VIEW [sCertificate].[vPrintTemplateBonafideCertificate]
AS
	SELECT
		B.Id,
		B.Number,
		B.AcademicId,
		SM.Code,
		[sStudent].[fStudentNameGet](SM.FirstName , SM.MiddleName, SM.LastName,OM.StudentNameFormatId ) AS Name,
		CM.DisplayTitle+' - '+DM.DisplayTitle AS Class,
		BM.Title AS Batch,
		SM.FirstName,
		SM.MiddleName,
		SM.LastName,
		SO.DateOfBirth,
		ISNULL(SO.BirthDateInWord,'') AS DOBInWords,
		ISNULL(SO.BirthPlace,'') AS BirthPlace,
		ISNULL(SO.BirthTaluka,'') AS Taluka,
		ISNULL(SO.BirthDistrict,'')	AS District,
		B.BonafideDate,
		ISNULL(SO.FamilyCast,'') AS Caste,
		ISNULL(SO.FamilySubCast,'') AS SubCaste,
		ISNULL(OM.CityName,'') AS City,
		ISNULL(OM.StateName,'') AS CityState,
		SO.GenderId,
		SI.StudentPhoto,
		OM.OrgLogo,
		OM.Title AS OrgTitle,
		SM.StatusId,
		A.RollNo,
		DM.OrderIndex AS DivisionOrder,
		ATM.Title AS AffiliationType,
		OM.ReportOrgTitle,
		OM.SmallAddress1,
		OM.SmallAddress2,
		OM.RegistrationDetail,
		ISNULL(RM.Title,'') AS ReligionName,
		B.Remark AS ReceiptNo,
		SF.FatherName,
		SA.AdmissionDate,
		DP.Title AS DepartmentName,
		ISNULL(OM.DegreeAwarded,'') AS DegreeAwarded,
		OI.CertificateHeaderA4,
		REPLICATE(',',OM.LetterHeadMargin)    AS LetterHeadMargin,
		ISNULL(B.BonafiedReason,'') AS BonafiedReason,
		CT.Title AS Category,
		SF.MotherName,
		C.PermanentStreetOne,
		C.PermanentStreetTwo,
		C.PermanentStreetThree,
		C.PermanentCountry,
		C.PermanentState,
		C.PermanentCity,
		C.PermanentZipCode,
		C.PermanentContactNo,
		C.PresentStreetOne,
		C.PresentStreetTwo,
		C.PresentStreetThree,
		C.PresentCountry,
		C.PresentState,
		C.PresentCity,
		C.PresentContactNo,
		C.PresentZipCode,
		SM.SUId,
		SO.AdhaarNumber,
		CM.DisplayTitle AS ClassName,
		ISNULL(CTM.Nationality,'') AS Nationality,
		OM.PrincipalSignature,
		ISnull(AR.SourceId,0) AS StudentidForhostel,
		DM.DisplayTitle AS Divisionname,
		SM.RecordStatusId,
		SO.BirthState AS BirthState,
		CM1.Title AS AdmissionStandard,
		A.BatchId,
		GM.Title AS Gender,
		ISNULL(SM.LocalName,'') AS LocalName,	--Add for Mantis: 32199
		ISNULL(SM.PENNumber,'') AS PENNo,	--Add for Mantis: 33853
        '[AdhaarNumber],[AdmissionDate],[AdmissionStandard],[AffiliationType],[Batch],[BirthPlace],[BirthState],[BonafideDate],[BonafiedReason],[Caste],[Category],[CertificateHeaderA4],[City],[CityState],[Class],[ClassName],[Code],[ColumnList],[DateOfBirth],[DegreeAwarded],[DepartmentName],[District],[Divisionname],[DivisionOrder],[DOBInWords],[FatherName],[FirstName],[Gender],[LastName],[LetterHeadMargin],[MiddleName],[MotherName],[Name],[Nationality],[Number],[OrgLogo],[OrgTitle],[PermanentCity],[PermanentContactNo],[PermanentCountry],[PermanentState],[PermanentStreetOne],[PermanentStreetThree],[PermanentStreetTwo],[PermanentZipCode],[PresentCity],[PresentContactNo],[PresentCountry],[PresentState],[PresentStreetOne],[PresentStreetThree],[PresentStreetTwo],[PresentZipCode],[PrincipalSignature],[ReceiptNo],[RecordStatusId],[RegistrationDetail],[ReligionName],[ReportOrgTitle],[RollNo],[SmallAddress1],[SmallAddress2],[StudentPhoto],[SubCaste],[Taluka],[LocalName],[PENNo],[SUID]' As ColumnList
		--Mantis: 32199, add LocalName in ColumnList
		--Manits: 33853, add PENNo and SUID in ColumnList
	FROM
		sCertificate.tBonafide B
		INNER JOIN sStudent.tAcademic A ON B.AcademicId=A.Id
		LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId=A.StudentId
		INNER JOIN sStudent.tStudentMaster SM ON SM.Id=A.StudentId
		LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId=A.StudentId
		INNER JOIN sSetup.tDivisionMaster DM ON A.DivisionId = DM.Id
		INNER JOIN sSetup.tClassMaster CM ON CM.Id= DM.ClassId
		INNER JOIN sSetup.tBatchMaster BM ON BM.Id=A.BatchId
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=A.OrgId
		left JOIN sSetup.tOrgImages OI ON OI.OrgId = OM.Id
		INNER JOIN sSetup.tAffiliationMaster AM ON OM.AffiliationId = AM.Id
		INNER JOIN sSetup.tAffiliationTypeMaster ATM ON AM.AffiliationTypeId = ATM.Id
		LEFT JOIN sCommon.tReligionMaster RM ON SO.ReligionId=RM.Id
		LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId = SM.Id
		INNER JOIN sStudent.tStudentAdmission SA ON SA.StudentId = SM.Id
		LEFT JOIN sSetup.tClassMaster CM1 ON CM1.Id = SA.AdmissionStandardId
		INNER JOIN sSetup.tDepartmentMaster DP ON CM.DepartmentId = DP.Id
		LEFT JOIN sCommon.tCastCategoryMaster CT ON CT.Id = SO.CastCategoryId
		LEFT JOIN sStudent.tStudentCommunication C ON C.StudentId = A.StudentId
		LEFT JOIN sCommon.tCountryMaster CTM ON CTM.Id=SO.NationalityId
		LEFT JOIN SHostel.tAssignRoom Ar On Ar.SourceId=A.StudentId
		INNER JOIN sCommon.tGenderMaster GM ON GM.Id = SO.GenderId
GO
PRINT N'Altering View [sCertificate].[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
		'[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],[SmallAddress1],[SmallAddress2],[SubCaste],[SubjectNAme],[TermsInInstitute],[ToCollege],[ToCollegeAddress],[TotalDaysSum],[UIDNumber],[University],[PrintDate],[LocalName]' As ColumnList
		--Mantis: 32199, add LocalName in ColumnList
	FROM
		sCertificate.tLeaving L
		INNER JOIN sStudent.vStudentAcademic vSA ON vSA.AcademicId=L.AcademicId
		LEFT JOIN sStudent.tStudentAdmission SA ON SA.StudentId=vSA.StudentId
		INNER JOIN sStudent.tStudentMaster SM ON SM.Id=vSA.StudentId
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=vSA.OrgId
		LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId=vSA.StudentId
		LEFT JOIN sCommon.tReligionMaster RM ON SO.ReligionId=RM.Id
		LEFT JOIN sSetup.tClassMaster CM ON CM.Id=SA.AdmissionStandardId
		INNER JOIN sSetup.tDivisionMaster DM ON vSA.DivisionId = DM.Id
		INNER JOIN sSetup.tClassMaster CMS ON CMS.Id= DM.ClassId
		LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId=vSA.StudentId
		LEFT JOIN sCommon.tCountryMaster CTM ON CTM.Id=SO.NationalityId
		LEFT JOIN sStudent.tAcademicDetail AD ON AD.AcademicId=vSA.AcademicId
		LEFT JOIN sSetup.tOrgImages OI ON OI.OrgId = OM.Id
		LEFT JOIN sCommon.tCastCategoryMaster CSM ON CSM.Id=SO.CastCategoryId
		LEFT JOIN sSetup.tClassGroupMaster CSG ON CSG.Id=CMS.ClassGroupId
		INNER JOIN sSetup.tBatchMaster BM ON BM.Id=vSA.BatchId
		LEFT JOIN sStudent.tStudentAdditional SD ON SD.StudentId=vSA.StudentId
		LEFT JOIN sHrm.tEmployeeMaster EM ON DM.InchargeEmployeeId = EM.Id			-- MantisId : 0033805
GO
PRINT N'Creating Function [sCertificate].[fBonafideCertificateTemplate]...';


GO

CREATE FUNCTION [sCertificate].[fBonafideCertificateTemplate]
(
    @AcademicId BIGINT,
	@BatchId INT,
    @Template NVARCHAR(MAX)
)
RETURNS NVARCHAR(MAX)
AS
BEGIN
    DECLARE 
        @AdhaarNumber NVARCHAR(20),
        @AdmissionDate DATE,
        @AdmissionStandard NVARCHAR(100),
        @AffiliationType NVARCHAR(50),
        @Batch NVARCHAR(100),
        @BirthPlace NVARCHAR(150),
        @BirthState NVARCHAR(150),
        @BonafideDate DATE,
        @BonafiedReason NVARCHAR(255),
        @Caste NVARCHAR(100),
        @Category NVARCHAR(50),
        @CertificateHeaderA4 NVARCHAR(MAX),
        @City NVARCHAR(100),
        @CityState NVARCHAR(100),
        @Class NVARCHAR(200),
        @ClassName NVARCHAR(100),
        @Code NVARCHAR(20),
        @ColumnList NVARCHAR(MAX),
        @DateOfBirth DATE,
        @DegreeAwarded NVARCHAR(100),
        @DepartmentName NVARCHAR(100),
        @District NVARCHAR(150),
        @Divisionname NVARCHAR(100),
        @DivisionOrder SMALLINT,
        @DOBInWords NVARCHAR(150),
        @FatherName NVARCHAR(100),
        @FirstName NVARCHAR(100),
        @Gender NVARCHAR(20),
        @LastName NVARCHAR(100),
        @LetterHeadMargin NVARCHAR(50),
        @MiddleName NVARCHAR(100),
        @MotherName NVARCHAR(100),
        @Name NVARCHAR(255),
        @Nationality NVARCHAR(50),
        @Number INT,
        @OrgLogo NVARCHAR(MAX),
        @OrgTitle NVARCHAR(100),
        @PermanentCity NVARCHAR(50),
        @PermanentContactNo NVARCHAR(20),
        @PermanentCountry NVARCHAR(50),
        @PermanentState NVARCHAR(50),
        @PermanentStreetOne NVARCHAR(150),
        @PermanentStreetThree NVARCHAR(150),
        @PermanentStreetTwo NVARCHAR(150),
        @PermanentZipCode NVARCHAR(20),
        @PresentCity NVARCHAR(50),
        @PresentContactNo NVARCHAR(20),
        @PresentCountry NVARCHAR(50),
        @PresentState NVARCHAR(50),
        @PresentStreetOne NVARCHAR(150),
        @PresentStreetThree NVARCHAR(150),
        @PresentStreetTwo NVARCHAR(150),
        @PresentZipCode NVARCHAR(20),
        @PrincipalSignature NVARCHAR(max),
        @ReceiptNo NVARCHAR(MAX), 	
        @RecordStatusId SMALLINT,
        @RegistrationDetail NVARCHAR(200),
        @ReligionName NVARCHAR(50),
        @ReportOrgTitle NVARCHAR(200),
        @RollNo INT,
        @SmallAddress1 NVARCHAR(200),
        @SmallAddress2 NVARCHAR(200),
        @StudentPhoto NVARCHAR(MAX),
        @SubCaste NVARCHAR(100),
        @Taluka NVARCHAR(150),
        @LocalName NVARCHAR(100),
        @PENNo BIGINT,
        @SUID NVARCHAR(50)

    -- Fetch the values from the database
    SELECT 
        @AdhaarNumber = ISNULL(AdhaarNumber, ''),
        @AdmissionDate = ISNULL(AdmissionDate, ''),
        @AdmissionStandard = ISNULL(AdmissionStandard, ''),
        @AffiliationType = ISNULL(AffiliationType, ''),
        @Batch = ISNULL(Batch, ''),
        @BirthPlace = ISNULL(BirthPlace, ''),
        @BirthState = ISNULL(BirthState, ''),
        @BonafideDate = ISNULL(BonafideDate, ''),
        @BonafiedReason = ISNULL(BonafiedReason, ''),
        @Caste = ISNULL(Caste, ''),
        @Category = ISNULL(Category, ''),
        @CertificateHeaderA4 = ISNULL(CAST('data:image/jpeg;base64,' AS NVARCHAR(MAX)) +
                      CAST(N'' AS XML).value('xs:base64Binary(xs:hexBinary(sql:column("CertificateHeaderA4")))', 'NVARCHAR(MAX)'),''),
        @City = ISNULL(City, ''),
        @CityState = ISNULL(CityState, ''),
        @Class = ISNULL(Class, ''),
        @ClassName = ISNULL(ClassName, ''),
        @Code = ISNULL(Code, ''),
        @ColumnList = ISNULL(ColumnList, ''),
        @DateOfBirth = ISNULL(DateOfBirth, ''),
        @DegreeAwarded = ISNULL(DegreeAwarded, ''),
        @DepartmentName = ISNULL(DepartmentName, ''),
        @District = ISNULL(District, ''),
        @Divisionname = ISNULL(Divisionname, ''),
        @DivisionOrder = ISNULL(DivisionOrder, ''),
        @DOBInWords = ISNULL(DOBInWords, ''),
        @FatherName = ISNULL(FatherName, ''),
        @FirstName = ISNULL(FirstName, ''),
        @Gender = ISNULL(Gender, ''),
        @LastName = ISNULL(LastName, ''),
        @LetterHeadMargin = ISNULL(LetterHeadMargin, ''),
        @MiddleName = ISNULL(MiddleName, ''),
        @MotherName = ISNULL(MotherName, ''),
        @Name = ISNULL(Name, ''),
        @Nationality = ISNULL(Nationality, ''),
        @Number = ISNULL(Number, 0),
        @OrgLogo = ISNULL(CAST('data:image/jpeg;base64,' AS NVARCHAR(MAX)) +
                      CAST(N'' AS XML).value('xs:base64Binary(xs:hexBinary(sql:column("OrgLogo")))', 'NVARCHAR(MAX)'),''),
        @OrgTitle = ISNULL(OrgTitle, ''),
        @PermanentCity = ISNULL(PermanentCity, ''),
        @PermanentContactNo = ISNULL(PermanentContactNo, ''),
        @PermanentCountry = ISNULL(PermanentCountry, ''),
        @PermanentState = ISNULL(PermanentState, ''),
        @PermanentStreetOne = ISNULL(PermanentStreetOne, ''),
        @PermanentStreetThree = ISNULL(PermanentStreetThree, ''),
        @PermanentStreetTwo = ISNULL(PermanentStreetTwo, ''),
        @PermanentZipCode = ISNULL(PermanentZipCode, ''),
        @PresentCity = ISNULL(PresentCity, ''),
        @PresentContactNo = ISNULL(PresentContactNo, ''),
        @PresentCountry = ISNULL(PresentCountry, ''),
        @PresentState = ISNULL(PresentState, ''),
        @PresentStreetOne = ISNULL(PresentStreetOne, ''),
        @PresentStreetThree = ISNULL(PresentStreetThree, ''),
        @PresentStreetTwo = ISNULL(PresentStreetTwo, ''),
        @PresentZipCode = ISNULL(PresentZipCode, ''),
        @PrincipalSignature = ISNULL(CAST('data:image/jpeg;base64,' AS NVARCHAR(MAX)) +
                      CAST(N'' AS XML).value('xs:base64Binary(xs:hexBinary(sql:column("PrincipalSignature")))', 'NVARCHAR(MAX)'),''),
        @ReceiptNo = ISNULL(ReceiptNo, ''),
        @RecordStatusId = ISNULL(RecordStatusId, 0),
        @RegistrationDetail = ISNULL(RegistrationDetail, ''),
        @ReligionName = ISNULL(ReligionName, ''),
        @ReportOrgTitle = ISNULL(ReportOrgTitle, ''),
        @RollNo = ISNULL(RollNo, 0),
        @SmallAddress1 = ISNULL(SmallAddress1, ''),
        @SmallAddress2 = ISNULL(SmallAddress2, ''),
        @StudentPhoto = ISNULL(CAST('data:image/jpeg;base64,' AS NVARCHAR(MAX)) +
                      CAST(N'' AS XML).value('xs:base64Binary(xs:hexBinary(sql:column("StudentPhoto")))', 'NVARCHAR(MAX)'),''),
        @SubCaste = ISNULL(SubCaste, ''),
        @Taluka = ISNULL(Taluka, ''),
        @LocalName = ISNULL(LocalName, ''),
        @PENNo = ISNULL(PENNo, 0),
        @SUID = ISNULL(SUID, '')
    FROM 
        sCertificate.vPrintTemplateBonafideCertificate 
    WHERE 
        Academicid = @AcademicId AND BatchId = @BatchId

    -- Replace placeholders in the template with actual values
    SET @Template = REPLACE(@Template, '[AdhaarNumber]', @AdhaarNumber);
    SET @Template = REPLACE(@Template, '[AdmissionDate]', CONVERT(NVARCHAR, @AdmissionDate, 103));
    SET @Template = REPLACE(@Template, '[AdmissionStandard]', @AdmissionStandard);
    SET @Template = REPLACE(@Template, '[AffiliationType]', @AffiliationType);
    SET @Template = REPLACE(@Template, '[Batch]', @Batch);
    SET @Template = REPLACE(@Template, '[BirthPlace]', @BirthPlace);
    SET @Template = REPLACE(@Template, '[BirthState]', @BirthState);
    SET @Template = REPLACE(@Template, '[BonafideDate]', CONVERT(NVARCHAR, @BonafideDate, 103));
    SET @Template = REPLACE(@Template, '[BonafiedReason]', @BonafiedReason);
    SET @Template = REPLACE(@Template, '[Caste]', @Caste);
    SET @Template = REPLACE(@Template, '[Category]', @Category);
    SET @Template = REPLACE(@Template, '[CertificateHeaderA4]', @CertificateHeaderA4);
    SET @Template = REPLACE(@Template, '[City]', @City);
    SET @Template = REPLACE(@Template, '[CityState]', @CityState);
    SET @Template = REPLACE(@Template, '[Class]', @Class);
    SET @Template = REPLACE(@Template, '[ClassName]', @ClassName);
    SET @Template = REPLACE(@Template, '[Code]', @Code);
    SET @Template = REPLACE(@Template, '[ColumnList]', @ColumnList);
    SET @Template = REPLACE(@Template, '[DateOfBirth]', CONVERT(NVARCHAR, @DateOfBirth, 103));
    SET @Template = REPLACE(@Template, '[DegreeAwarded]', @DegreeAwarded);
    SET @Template = REPLACE(@Template, '[DepartmentName]', @DepartmentName);
    SET @Template = REPLACE(@Template, '[District]', @District);
    SET @Template = REPLACE(@Template, '[Divisionname]', @Divisionname);
    SET @Template = REPLACE(@Template, '[DivisionOrder]', CAST(@DivisionOrder AS NVARCHAR));
    SET @Template = REPLACE(@Template, '[DOBInWords]', @DOBInWords);
    SET @Template = REPLACE(@Template, '[FatherName]', @FatherName);
    SET @Template = REPLACE(@Template, '[FirstName]', @FirstName);
    SET @Template = REPLACE(@Template, '[Gender]', @Gender);
    SET @Template = REPLACE(@Template, '[LastName]', @LastName);
    SET @Template = REPLACE(@Template, '[LetterHeadMargin]', @LetterHeadMargin);
    SET @Template = REPLACE(@Template, '[MiddleName]', @MiddleName);
    SET @Template = REPLACE(@Template, '[MotherName]', @MotherName);
    SET @Template = REPLACE(@Template, '[Name]', @Name);
    SET @Template = REPLACE(@Template, '[Nationality]', @Nationality);
    SET @Template = REPLACE(@Template, '[Number]', CAST(@Number AS NVARCHAR));
    SET @Template = REPLACE(@Template, '[OrgLogo]', @OrgLogo);
    SET @Template = REPLACE(@Template, '[OrgTitle]', @OrgTitle);
    SET @Template = REPLACE(@Template, '[PermanentCity]', @PermanentCity);
    SET @Template = REPLACE(@Template, '[PermanentContactNo]', @PermanentContactNo);
    SET @Template = REPLACE(@Template, '[PermanentCountry]', @PermanentCountry);
    SET @Template = REPLACE(@Template, '[PermanentState]', @PermanentState);
    SET @Template = REPLACE(@Template, '[PermanentStreetOne]', @PermanentStreetOne);
    SET @Template = REPLACE(@Template, '[PermanentStreetThree]', @PermanentStreetThree);
    SET @Template = REPLACE(@Template, '[PermanentStreetTwo]', @PermanentStreetTwo);
    SET @Template = REPLACE(@Template, '[PermanentZipCode]', @PermanentZipCode);
    SET @Template = REPLACE(@Template, '[PresentCity]', @PresentCity);
    SET @Template = REPLACE(@Template, '[PresentContactNo]', @PresentContactNo);
    SET @Template = REPLACE(@Template, '[PresentCountry]', @PresentCountry);
    SET @Template = REPLACE(@Template, '[PresentState]', @PresentState);
    SET @Template = REPLACE(@Template, '[PresentStreetOne]', @PresentStreetOne);
    SET @Template = REPLACE(@Template, '[PresentStreetThree]', @PresentStreetThree);
    SET @Template = REPLACE(@Template, '[PresentStreetTwo]', @PresentStreetTwo);
    SET @Template = REPLACE(@Template, '[PresentZipCode]', @PresentZipCode);
    SET @Template = REPLACE(@Template, '[PrincipalSignature]', @PrincipalSignature);
    SET @Template = REPLACE(@Template, '[ReceiptNo]', @ReceiptNo);
    SET @Template = REPLACE(@Template, '[RecordStatusId]', CAST(@RecordStatusId AS NVARCHAR));
    SET @Template = REPLACE(@Template, '[RegistrationDetail]', @RegistrationDetail);
    SET @Template = REPLACE(@Template, '[ReligionName]', @ReligionName);
    SET @Template = REPLACE(@Template, '[ReportOrgTitle]', @ReportOrgTitle);
    SET @Template = REPLACE(@Template, '[RollNo]', CAST(@RollNo AS NVARCHAR));
    SET @Template = REPLACE(@Template, '[SmallAddress1]', @SmallAddress1);
    SET @Template = REPLACE(@Template, '[SmallAddress2]', @SmallAddress2);
    SET @Template = REPLACE(@Template, '[StudentPhoto]', @StudentPhoto);
    SET @Template = REPLACE(@Template, '[SubCaste]', @SubCaste);
    SET @Template = REPLACE(@Template, '[Taluka]', @Taluka);
    SET @Template = REPLACE(@Template, '[LocalName]', @LocalName);
    SET @Template = REPLACE(@Template, '[PENNo]', CAST(@PENNo AS NVARCHAR));
    SET @Template = REPLACE(@Template, '[SUID]', @SUID);

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


GO


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

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

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

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

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


GO


CREATE FUNCTION [sCertificate].[fFirstTrialCertificateTemplate]
(
    @AcademicId BIGINT,
	@BatchId INT,
    @Template NVARCHAR(MAX)
)
RETURNS NVARCHAR(MAX)
AS
BEGIN
    DECLARE 
        @AdmissionDate DATE,
		@BirthDateInWord NVARCHAR(150),
        @CertificateHeaderA4 NVARCHAR(MAX),
        @City NVARCHAR(100),
        @CityState NVARCHAR(100),
        @Class NVARCHAR(200),
        @ClassName NVARCHAR(100),
        @Code NVARCHAR(20),
        @DateOfBirth DATE,
        @DivisionOrder SMALLINT,
		@Exam NVARCHAR(54),
		@ExamCentre NVARCHAR(100),
		@ExamYear NVARCHAR(20),
        @FatherName NVARCHAR(100),
		@FirstTrialDate DATE,
        @Name NVARCHAR(300),
        @Number INT,
		@OrgAddress NVARCHAR(152),
        @OrgLogo NVARCHAR(MAX),
        @OrgTitle NVARCHAR(100),
        @PhoneNo NVARCHAR(50),
        @RegistrationDetail NVARCHAR(200),
		@Remark NVARCHAR(100),
        @ReportOrgTitle NVARCHAR(200),
        @RollNo INT,
		@SeatNo NVARCHAR(50),
        @SmallAddress1 NVARCHAR(200),
        @SmallAddress2 NVARCHAR(200),
        @StudentPhoto NVARCHAR(MAX),
        @SUID NVARCHAR(50),
		@Surname NVARCHAR(100),
		@Trial NVARCHAR(20),
		@LocalName NVARCHAR(100)

    -- Fetch the values from the database
    SELECT 

        @AdmissionDate = ISNULL(AdmissionDate, ''),
		@BirthDateInWord = ISNULL(BirthDateInWord, ''),
        @CertificateHeaderA4 = ISNULL(CAST('data:image/jpeg;base64,' AS NVARCHAR(MAX)) +
                      CAST(N'' AS XML).value('xs:base64Binary(xs:hexBinary(sql:column("CertificateHeaderA4")))', 'NVARCHAR(MAX)'),''),
        @City = ISNULL(City, ''),
        @CityState = ISNULL(CityState, ''),
        @Class = ISNULL(Class, ''),
        @ClassName = ISNULL(ClassName, ''),
        @Code = ISNULL(Code, ''),
        @DateOfBirth = ISNULL(DateOfBirth, ''),
        @DivisionOrder = ISNULL(DivisionOrder, ''),
		@Exam = ISNULL(Exam, ''),
		@ExamCentre = ISNULL(ExamCentre, ''),
		@ExamYear = ISNULL(ExamYear, ''),
        @FatherName = ISNULL(FatherName, ''),
		@FirstTrialDate = ISNULL(FirstTrialDate, ''),
        @Name = ISNULL(Name, ''),
        @Number = ISNULL(Number, 0),
		@OrgAddress = ISNULL(OrgAddress, ''),
        @OrgLogo = ISNULL(CAST('data:image/jpeg;base64,' AS NVARCHAR(MAX)) +
                      CAST(N'' AS XML).value('xs:base64Binary(xs:hexBinary(sql:column("OrgLogo")))', 'NVARCHAR(MAX)'),''),
        @OrgTitle = ISNULL(OrgTitle, ''),
        @PhoneNo = ISNULL(PhoneNo, ''),
        @RegistrationDetail = ISNULL(RegistrationDetail, ''),
		@Remark = ISNULL(Remark, ''),
        @ReportOrgTitle = ISNULL(ReportOrgTitle, ''),
        @RollNo = ISNULL(RollNo, 0),
		@SeatNo = ISNULL(SeatNo, ''),
        @SmallAddress1 = ISNULL(SmallAddress1, ''),
        @SmallAddress2 = ISNULL(SmallAddress2, ''),
        @StudentPhoto = ISNULL(CAST('data:image/jpeg;base64,' AS NVARCHAR(MAX)) +
                      CAST(N'' AS XML).value('xs:base64Binary(xs:hexBinary(sql:column("StudentPhoto")))', 'NVARCHAR(MAX)'),''),
        @SUID = ISNULL(SUID, ''),
		@Surname  = ISNULL(Surname, ''),
		@Trial = ISNULL(Trial, ''),
		@LocalName = ISNULL(LocalName, '')

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

    -- Replace placeholders in the template with actual values

    SET @Template = REPLACE(@Template, '[AdmissionDate]', CONVERT(NVARCHAR, @AdmissionDate, 103));
	SET @Template = REPLACE(@Template, '[BirthDateInWord]', @BirthDateInWord);
    SET @Template = REPLACE(@Template, '[CertificateHeaderA4]',  @CertificateHeaderA4);
    SET @Template = REPLACE(@Template, '[City]', @City);
    SET @Template = REPLACE(@Template, '[CityState]', @CityState);
    SET @Template = REPLACE(@Template, '[Class]', @Class);
    SET @Template = REPLACE(@Template, '[ClassName]', @ClassName);
    SET @Template = REPLACE(@Template, '[Code]', @Code);
    SET @Template = REPLACE(@Template, '[DateOfBirth]', CONVERT(NVARCHAR, @DateOfBirth, 103));
    SET @Template = REPLACE(@Template, '[DivisionOrder]', CAST(@DivisionOrder AS NVARCHAR));
	SET @Template = REPLACE(@Template, '[Exam]', @Exam);
	SET @Template = REPLACE(@Template, '[ExamCentre]', @ExamCentre);
	SET @Template = REPLACE(@Template, '[ExamYear]', @ExamYear);
    SET @Template = REPLACE(@Template, '[FatherName]', @FatherName);
	SET @Template = REPLACE(@Template, '[FirstTrialDate]', CONVERT(NVARCHAR, @FirstTrialDate, 103));
    SET @Template = REPLACE(@Template, '[Name]', @Name);
    SET @Template = REPLACE(@Template, '[Number]', CAST(@Number AS NVARCHAR));
	SET @Template = REPLACE(@Template, '[OrgAddress]', @OrgAddress);
    SET @Template = REPLACE(@Template, '[OrgLogo]', @OrgLogo);
    SET @Template = REPLACE(@Template, '[OrgTitle]', @OrgTitle);
    SET @Template = REPLACE(@Template, '[PhoneNo]', @PhoneNo);
    SET @Template = REPLACE(@Template, '[RegistrationDetail]', @RegistrationDetail);
	SET @Template = REPLACE(@Template, '[Remark]', @Remark);
    SET @Template = REPLACE(@Template, '[ReportOrgTitle]', @ReportOrgTitle);
    SET @Template = REPLACE(@Template, '[RollNo]', CAST(@RollNo AS NVARCHAR));
	SET @Template = REPLACE(@Template, '[SeatNo]', @SeatNo);
    SET @Template = REPLACE(@Template, '[SmallAddress1]', @SmallAddress1);
    SET @Template = REPLACE(@Template, '[SmallAddress2]', @SmallAddress2);
    SET @Template = REPLACE(@Template, '[StudentPhoto]', @StudentPhoto);
    SET @Template = REPLACE(@Template, '[SUID]', @SUID);
	SET @Template = REPLACE(@Template, '[Surname]', @Surname);
	SET @Template = REPLACE(@Template, '[Trial]', @Trial);
	SET @Template = REPLACE(@Template, '[LocalName]', @LocalName);

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


GO


CREATE 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)

    -- 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, '')
    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);

    RETURN @Template;
END;
GO
PRINT N'Altering Procedure [sCommon].[pReportFormatGroupMasterGet]...';


GO
ALTER PROCEDURE [sCommon].[pReportFormatGroupMasterGet]
	 
	 @rOrgGroupId smallint,
	 @rReportFormatGroupId smallint
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
		
BEGIN 
	SELECT 
			DISTINCT(OM.Id) AS OrgId,
			OM.DisplayTitle AS Organization,
			CASE WHEN RFGO.OrgId IS NULL OR RFGO.ReportFormatGroupId!=@rReportFormatGroupId THEN 'False' ELSE 'True' END AS IsObsolete,
			CASE WHEN RFGO.OrgId IS NULL OR RFGO.ReportFormatGroupId!=@rReportFormatGroupId THEN 0 ELSE RFGO.ReportId END AS ReportId,
			CASE WHEN RFGO.OrgId IS NULL OR RFGO.ReportFormatGroupId!=@rReportFormatGroupId THEN '0-0' ELSE Convert(Nvarchar(50),RFGO.ReportId) + '-' + Convert(Nvarchar(50),IsNull(RFGO.PrintTemplateId, 0)) END AS ReportPrintTemplate
  FROM 
            sSetup.tOrganizationMaster OM
       LEFT JOIN sCommon.tReportFormatGroupOrg RFGO ON RFGO.OrgId=OM.Id AND (RFGO.ReportFormatGroupId=@rReportFormatGroupId)
       
  WHERE 
			(OM.OrgGroupId=@rOrgGroupId)
		ORDER BY OM.DisplayTitle
END
GO
PRINT N'Altering Procedure [sCommon].[pReportFormatGroupOrgAdd]...';


GO

ALTER PROCEDURE [sCommon].[pReportFormatGroupOrgAdd]
    
    @rReportFormatGroupId smallint,
	@rXmldoc [nvarchar](max)

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
BEGIN TRY

DECLARE @lCount INT
DECLARE @lInterrorCode INT,
		@intDoc INT,
		@lOrgId SMALLINT,
		@lReportId SMALLINT,
		@lPrintTemplateId INT
		
BEGIN TRANSACTION
			
	DELETE FROM sCommon.tReportFormatGroupOrg WHERE ReportFormatGroupId=@rReportFormatGroupId	
			
	EXECUTE @lInterrorCode = sp_xml_preparedocument @intDoc OUTPUT, @rXmlDoc
		
	CREATE TABLE #tTable  
	(
		Id bigint identity,	 
		OrgId smallint,
		ReportId smallint,
		PrintTemplateId Int
	)
		
	INSERT INTO #tTable
	(
		OrgId,
		ReportId,
		PrintTemplateId
	)
	SELECT
		OrgId,
		ReportId,
		PrintTemplateId
	FROM OPENXML (@intDoc, '/Table/ReportFormatGroup', 1)
	WITH
	( 
		OrgId smallint '@OrgId',			
		ReportId smallint '@ReportId',
		PrintTemplateId Int '@PrintTemplateId'
	)
		
	EXEC sp_xml_removedocument @intDoc
				
	SELECT @lCount =  COUNT(Id) FROM #tTable

	WHILE @lCount > 0 
	BEGIN
		SELECT		
				@lOrgId=OrgId,
				@lReportId=ReportId,
				@lPrintTemplateId=PrintTemplateId
													 	 
		FROM #tTable WHERE Id = @lCount  

		INSERT INTO sCommon.tReportFormatGroupOrg
		(
			OrgId,
			ReportId,
			ReportFormatGroupId,
			PrintTemplateId
		)
		VALUES
		(
			@lOrgId,
			@lReportId,
			@rReportFormatGroupId,
			@lPrintTemplateId
		)
		SET @lCount = @lCount - 1
	END			
COMMIT TRANSACTION			
	
SELECT 1
END TRY
BEGIN CATCH
ROLLBACK TRANSACTION
SELECT -1 
END CATCH
	
END
GO
PRINT N'Altering Procedure [sFee].[pPostDatedPaymentGet]...';


GO
ALTER PROCEDURE sFee.pPostDatedPaymentGet
	@rId bigint = 0,
	@rOrgGroupBatchId int=0,
	@rOrgId int = 0,
	@rBatchId int = 0,
	@rAdmissionCategoryId int = 0,
	@rIdNo nvarchar(20) = NULL,
	@rDepartmentId int = 0,
	@rClassId int = 0,
	@rDivisionId int = 0,
	@rReceiptBookId int = 0,
	@rCollectionGroupId int = 0,
	@rPayTypeId int = 0,
	@rStatusId int = 0,
	@rFirstName nvarchar(50) = NULL,
	@rFromReceiptNumber nvarchar(50) = NULL,
	@rToReceiptNumber nvarchar(50) = NULL,
	@rChequeNo nvarchar(50) = NULL,
	@rFromPaymentClearanceDate date = NULL,
	@rToPaymentClearanceDate date = NULL,
	@rOrgGroupId int = 0,
	@rSourceId bigint =0,
	@rSourceTypeId smallint = 0,
	@rUserId bigint = 0,
	@rStatusIds nvarchar(100) = ''

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 		
	BEGIN
		SET @rFirstName = sCommon.fSearchStringGet(@rFirstName)
		SET @rChequeNo = sCommon.fSearchStringGet(@rChequeNo)  
	END

	SELECT DISTINCT 	 
		 PDP.Id
		,PDP.OrgId
		,ISNULL(OM.Title, '') AS Organization
		,PDP.BatchId
		,ISNULL(BM.Title, '') AS Batch
		,ISNULL(SA.Code, '') AS IdNo
		,ISNULL(SA.ClassName, '') + ' - ' + ISNULL(SA.DivisionName, '') AS ClassDivision
		,ISNULL(SA.Name, '') AS StudentName
		,PDP.OrgGroupBatchId
		,PDP.SourceTypeId
		,PDP.SourceId
		,ISNULL(PDP.ReceiptId, 0) AS ReceiptId
		,PDP.ReceiptBookId
		,PDP.PayTypeId
		,PDP.PaymentClearanceDate
		,PDP.ChequeNo
		,PDP.BankName
		,PDP.Amount AS ReceiptAmount
		,ISNULL(PDP.Remark, '') AS Remark
		,PDP.CreatedUserId
		,PDP.CreatedDateTime
		,PDP.UpdatedUserId
		,PDP.UpdatedDateTime
		,PDP.StatusId
		,ISNULL(R.ReceiptNumber, '') AS ReceiptNumber
		,ISNULL(RBM.Title, '') AS ReceiptBookTitle
		,ISNULL(R.ReceiptDate, '') AS ReceiptDate
		,ISNULL(PTM.Title, '') AS PayType
        ,ISNULL(SM.Title, '') AS StatusTitle
		,ISNULL(PDP.DepositedDate, '') AS DepositedDate
	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
		INNER JOIN sFinanceCommon.tPayTypeMaster PTM ON PTM.Id = PDP.PayTypeId
		INNER JOIN sFee.vUserReceiptBook RBM ON RBM.Id=PDP.ReceiptBookId AND RBM.UserId=@rUserId    
		--INNER JOIN sFee.tReceiptBookMaster RBM ON RBM.Id = PDP.ReceiptBookId
		INNER JOIN sCommon.tStatusMaster SM ON SM.Id = PDP.StatusId
		LEFT JOIN sFee.tReceipt R ON R.Id = PDP.ReceiptId
		LEFT JOIN sFee.tCollectionGroupMaster CGM ON CGM.ReceiptBookId = RBM.Id
	WHERE
		(PDP.Id = @rId OR @rId = 0)
		AND (PDP.OrgGroupBatchId = @rOrgGroupBatchId OR @rOrgGroupBatchId = 0)
		AND (PDP.OrgId = @rOrgId OR @rOrgId = 0)
		AND (PDP.BatchId = @rBatchId OR @rBatchId = 0)
		AND (SA.AdmissionCategoryId = @rAdmissionCategoryId OR @rAdmissionCategoryId = 0)
		AND ((SA.Code like @rIdNo) OR (ISNULL(@rIdNo,'')=''))
		AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
		AND (SA.ClassId = @rClassId OR @rClassId = 0)
		AND (SA.DivisionId = @rDivisionId OR @rDivisionId = 0)
		AND (PDP.ReceiptBookId = @rReceiptBookId OR @rReceiptBookId = 0)
		AND (CGM.Id = @rCollectionGroupId OR @rCollectionGroupId = 0)
		AND (PDP.PayTypeId = @rPayTypeId OR @rPayTypeId = 0)
		AND (PDP.StatusId = @rStatusId OR @rStatusId = 0)
		AND ((SA.FirstName like @rFirstName) OR(ISNULL(@rFirstName,'')=''))
		AND (PDP.ChequeNo like @rChequeNo OR ISNULL(@rChequeNo, '') = '')
		AND ((R.ReceiptNumber>=@rFromReceiptNumber)OR(ISNULL(@rFromReceiptNumber, 0) =0))    
		AND ((R.ReceiptNumber<=@rToReceiptNumber)OR(ISNULL(@rToReceiptNumber,0)=0))   
		AND (PDP.PaymentClearanceDate >= @rFromPaymentClearanceDate OR ISNULL(@rFromPaymentClearanceDate, '') = '')
		AND (PDP.PaymentClearanceDate <= @rToPaymentClearanceDate OR ISNULL(@rToPaymentClearanceDate, '') = '')
		AND (PDP.SourceId = @rSourceId OR @rSourceId = 0)
		AND (PDP.SourceTypeId = @rSourceTypeId OR @rSourceTypeId = 0)
		AND (PDP.StatusId IN (SELECT item FROM sCommon.fnSplit(@rStatusIds,',')) OR ISNULL(@rStatusIds, '') = '')
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
	FROM
	(
		SELECT	
			FeeId,
			PayTypeId,
			Amount,
			Narration,
			ReceiptDate			
			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'	
			))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
	
	

	INSERT INTO sTally.tReceiptPosting
		(
		TransactionDate,
		ReceiptBookId,
		FeeId,
		StudentId,
		OrgGroupBatchId,
		PayTypeId,		
		VoucherNumber,
		Amount,
		Narration
		)
	SELECT
		A.ReceiptDate,
		@rReceiptId,
		0,
		A.FeeId,
		@rOrgGroupBatchId,
		A.PayTypeId,
		@rVoucherNumber  + ROW_NUMBER() OVER(ORDER BY ReceiptBookId),
		A.Amount,
		A.Narration
		
	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'			
	)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
	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 [sAcademic].[pClassworkStudentGet]...';


GO
ALTER PROCEDURE [sAcademic].[pClassworkStudentGet]

	 @rStudentId bigint,
	 @rBatchId int,	 
	 @rFromDate date='',
     @rToDate date='',
     @rHomeWorkEndDate	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,@lAcademicId Bigint
	SELECT @lDivisionId = DivisionId, @lAcademicId=ID FROM sStudent.tAcademic WHERE StudentId = @rStudentId AND BatchId = @rBatchId
	
	DECLARE @lConfigValue nvarchar(50)
	DECLARE @lIsClassworkHomeworkBasedOnApproval bit=0
	SELECT @lConfigValue = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 323 AND SourceTypeId = 2010 AND SourceId = LEFT(@lOrgGroupBatchId,4)

	IF (@lConfigValue IS NULL) OR (@lConfigValue = 'False')
	SET @lIsClassworkHomeworkBasedOnApproval = 0
	ELSE
	SET @lIsClassworkHomeworkBasedOnApproval = 1	
	
	SELECT distinct
			AC.Id,
			AC.EmployeeId,
			AC.ClassId,
			AC.DivisionId,
			AC.SubjectId,
		    AC.Classwork,
		    AC.Homework,
		    AC.ClassWorkDate,
		    AC.HomeWorkEndDate,
		    --ISNULL(AC.HomeWorkEndDate,'') AS HomeWorkEndDate,
		    ISNULL(SM.Title,'') as SubjectName,
		    ISNULL(EM.FirstName +' ' + EM.LastName,'') AS TeacherName,
		    ISNULL(CM.Title,'') AS ClassName,
		    ISNULL(DM.Title,'') AS DivisionName,
		    OM.OrgGroupId AS OrgId,
			ISNULL(AC.IsSubmitHomework,0) AS IsSubmitHomework
	FROM 
			sAcademic.tClasswork AC			 
			INNER Join sSetup.tSubjectMaster SM On SM.Id=AC.SubjectId
			INNER Join sHrm.tEmployeeMaster EM On EM.Id = AC.EmployeeId
			INNER Join sSetup.tClassMaster CM On CM.Id = AC.ClassId
			INNER Join sSetup.tDivisionMaster DM On DM.Id = AC.DivisionId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = DM.OrgId
			INNER JOIN sStudent.vStudentAcademic SA  ON AC.ClassId=SA.ClassId AND AC.DivisionId=SA.DivisionId
			INNER JOIN [sSetup].[tClassSubject] CS ON CS.ClassId = AC.ClassId AND CS.SubjectId = SM.Id
			LEFT JOIN [sAssessment].[tOptionalSubject] OS ON OS.ClassSubjectId = CS.Id AND Os.AcademicId = SA.AcademicId
	WHERE 
	    AC.DivisionId = @lDivisionId		 
		AND (AC.ClassWorkDate>=@rFromDate OR ISNULL(@rFromDate,'')='')
		AND (AC.ClassWorkDate<=@rToDate OR ISNULL(@rToDate,'')='')
		AND (AC.HomeWorkEndDate>=@rHomeWorkEndDate OR ISNULL(@rHomeWorkEndDate,'')='')
		AND ((@lIsClassworkHomeworkBasedOnApproval=0) OR (@lIsClassworkHomeworkBasedOnApproval=1 AND AC.StatusId=550))
		AND ISNULL(EM.IsOtherUser,0) = 0 
		AND OS.AcademicId IS NULL AND Sa.AcademicID =@lAcademicId
	--	order by  AC.CreatedDateTime desc
END
GO
PRINT N'Altering Procedure [sAcademic].[pClassworkStudentWithStatusGet]...';


GO
ALTER PROCEDURE [sAcademic].[pClassworkStudentWithStatusGet]

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

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

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

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

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


GO
ALTER PROCEDURE [sAccounting].[pCashBankBook]
	
	@rBuilder1 nvarchar(max)='',
	@rBuilder2 nvarchar(max)='', 
	@rStartDate Date,
	@rEndDate Date,
	@rOrgGroupId int = 0,
	@rAccountingYearId [int],
	@rLedgerId [int],
	@rLedgerMainGroupId [int],
	@rLedgerGroupId [int],
	 @rAccountId int=0
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN

Declare @LedgerId int 
Declare @LOpeningBalance Decimal (25,5) -- Changed for mantis 32211 by Nilesh
Declare @OpeningBalance Decimal (25,5)
Declare @lClOsingBalance Decimal (25,5) -- Changed for mantis 32211 by Nilesh
Declare @CreditBalance Decimal (25,5) -- Changed for mantis 32211 by Nilesh
Declare @DebitBalance Decimal (25,5) -- Changed for mantis 32211 by Nilesh
Declare @lCount int
Declare @lLedgerTypeId int
Declare @LedgerName Nvarchar(150)
Declare @LedgerGroupId int
Declare @ReportOrgTitle Nvarchar(200)
Declare @SmallAddress1  Nvarchar(200)
Declare	@SmallAddress2 Nvarchar(200)
	
	Declare @DecimalCount INT
	 SELECT @DecimalCount = CASE WHEN CS.Id IS NOT NULL THEN ISNULL(CS.ItemValue,'') ELSE ISNULL(CM.ItemValue,'') END
						  FROM sConfig.tConfigurationMaster CM
						  LEFT JOIN sConfig.tConfigurationSetup CS ON CM.Id = CS.ConfigurationId
						  AND SourceTypeId = 2010 AND SourceId = @rOrgGroupId WHERE CM.Id = 548
	--EXEC [sAccounting].[pUpdateClosingBalance] @rStartDate,@rEndDate,@rOrgGroupId,@rAccountingYearId,@rLedgerId,@rLedgerMainGroupId,@rISProfitLoss
  
  SELECT @ReportOrgTitle=ReportOrgTitle ,@SmallAddress1=SmallAddress1, @SmallAddress2= SmallAddress2  
  From sAccounting.tAccountMaster AM Where AM.Id= @rAccountId  
  
  
   CREATE TABLE #tempUpdateClosingBalance
	(	
	    Id INT IDENTITY (1, 1),
		LedgerId int,
		Temp_Op_Balance decimal(25,5), -- Changed for mantis 32211 by Nilesh
		Closing_Balance decimal(25,5), -- Changed for mantis 32211 by Nilesh
		Transaction_Balance decimal(25,5) -- Changed for mantis 32211 by Nilesh
	) 
 	
	CREATE TABLE #tCashBankBookTemp
 		(	Id INT IDENTITY (1, 1),
 			LedgerId int,
 			LedgerName nvarchar(150),
 			OpBalance Decimal(25,5), -- Changed for mantis 32211 by Nilesh
 			CrBalance Decimal(25,5), -- Changed for mantis 32211 by Nilesh
 			DrBalance Decimal(25,5), -- Changed for mantis 32211 by Nilesh
 			ClBalance Decimal(25,5), -- Changed for mantis 32211 by Nilesh
 			LedgerGroupId int
 		) 
	
	CREATE TABLE #tCashBankBook
 		(	Id INT IDENTITY (1, 1),
 			LedgerId int,
 			LedgerName nvarchar(150),
 			OpBalance Decimal(25,5), -- Changed for mantis 32211 by Nilesh
 			LedgerTypeId int,
 			LedgerGroupId int
 		) 
 	INSERT INTO #tCashBankBook
	select L.Id,L.Title,L.OpeningBalance,LedgerTypeId,L.LedgerGroupId from sAccounting.tLedgerMaster L INNER JOIN 
	sAccounting.tLedgerGroupMaster LG ON L.LedgerGroupId = LG.Id
	where LG.OrgGroupId = L.OrgGroupId AND
	(L.ID = @rLedgerId or @rLedgerId =0)
	AND LG.OrgGroupId = @rOrgGroupId and L.AccountingYearId = @rAccountingYearId AND LG.AccountingYearId = @rAccountingYearId
	AND (L.LedgerGroupId = @rLedgerGroupId OR @rLedgerGroupId=0)
	AND ((@rLedgerMainGroupId= 1 AND LG.Code IN ('2','3'))  OR (@rLedgerMainGroupId = 0) )
	
	ORDER BY L.Id Asc
	
	
	SELECT @lCount =  COUNT(Id) FROM #tCashBankBook    
	WHILE (@lCount > 0)
	BEGIN		
		SELECT @LedgerId =LedgerId,@LedgerName= LedgerName,@OpeningBalance=ISNULL(OpBalance,0),@LedgerGroupId = LedgerGroupId, 
		@lLedgerTypeId=LedgerTypeId FROM #tCashBankBook WHERE Id = @lCount				

		-- Update Closing Balance
		INSERT INTO #tempUpdateClosingBalance (LedgerId,Temp_Op_Balance,Closing_Balance,Transaction_Balance)
		EXEC [sAccounting].[pUpdateClosingBalance] @rStartDate,@rEndDate,@rOrgGroupId,@rAccountingYearId,@LedgerId,'' -- change @rLedgerId to @LedgerId
		
		 SELECT @LOpeningBalance=ISNULL(Sum(TD.Amount) ,0)
		 FROM  sAccounting.tTransaction T INNER JOIN sAccounting.tTransactionDetail TD
		 ON T.Id=TD.TransactionId And TD.LedgerId=@LedgerId
			AND T.AccountingYearId = @rAccountingYearId 
			AND T.TransactionDate < @rStartDate

		 SELECT @CreditBalance= -1 * ISNULL(SUM(AMOUNT), 0)
		 FROM  sAccounting.tTransaction T INNER JOIN sAccounting.tTransactionDetail TD
		 ON T.Id=TD.TransactionId 		 
			AND T.AccountingYearId = @rAccountingYearId 
			AND T.TransactionDate >= @rStartDate AND T.TransactionDate <= @rEndDate
			AND TD.TransactionTypeId = 1 And TD.LedgerId=@LedgerId
			
			
		 SELECT @DebitBalance=  ISNULL(Sum(TD.Amount) ,0)
		 FROM  sAccounting.tTransaction T INNER JOIN sAccounting.tTransactionDetail TD
		 ON T.Id=TD.TransactionId 
		 --INNER JOIN sAccounting.tLedgerMaster L ON L.ID = TD.LedgerId
			AND T.AccountingYearId = @rAccountingYearId 
			AND T.TransactionDate >= @rStartDate AND T.TransactionDate <= @rEndDate
			AND TD.TransactionTypeId = 2 And TD.LedgerId=@LedgerId
			
			SET @LOpeningBalance = @LOpeningBalance  +  @OpeningBalance          
			
			SELECT  @lClOsingBalance = Closing_Balance FROM #tempUpdateClosingBalance WHERE LedgerId=@LedgerId
			
			--IF @lLedgerTypeId =1 
			--	BEGIN
			--		SET @lClOsingBalance = @LOpeningBalance  + @DebitBalance - @CreditBalance
			--	END
			--ELSE
			--	BEGIN
			--		SET @lClOsingBalance = @LOpeningBalance  - @DebitBalance + @CreditBalance
			--	END
							
			INSERT INTO #tCashBankBookTemp  (LedgerId,LedgerName,OpBalance,CrBalance,DrBalance,ClBalance,LedgerGroupId)
			VALUES 	(@LedgerId,@LedgerName,@LOpeningBalance,@CreditBalance,@DebitBalance,@lClOsingBalance,@LedgerGroupId)
			
			SET @lCount = @lCount - 1
		END	
	SELECT @ReportOrgTitle  AS OrgTitle,
	@SmallAddress1 AS SmallAddress1,
	@SmallAddress2 AS SmallAddress2, 
	 @rBuilder1 AS Builder1
		  ,@rBuilder2 AS Builder2,Id,LedgerId,LedgerName,
		  ([sAccounting].[fDecimalValueGet] (OpBalance, @DecimalCount)) AS OpBalance,
		  ([sAccounting].[fDecimalValueGet] (ISNULL(CrBalance,0), @DecimalCount)) AS CrBalance -- Changed for mantis 32211 by Nilesh
		  ,([sAccounting].[fDecimalValueGet] (ISNULL(DrBalance,0), @DecimalCount)) AS DrBalance,-- Changed for mantis 32211 by Nilesh
		   ([sAccounting].[fDecimalValueGet] (ClBalance, @DecimalCount)) AS ClBalance, -- Changed for mantis 32211 by Nilesh
		   LedgerGroupId FROM #tCashBankBookTemp	
	DROP TABLE #tCashBankBook
	DROP TABLE #tCashBankBookTemp
END
GO
PRINT N'Altering Procedure [sAdmission].[pRptAdmissionFormGet]...';


GO
ALTER PROCEDURE [sAdmission].[pRptAdmissionFormGet]
 
	
	@rId bigint = 0,
	@rRelationShipId int=0,
	@rClassId int = 0,	 	
	@rFromDate date = '',
	@rToDate date = '',
	@rOrgId int = 0,
	@rDepartmentId int = 0,
	@rFromMeritMarks int = 0,
	@rToMeritMarks int = 0,
	@rBatchId int = 0

AS
 SET NOCOUNT ON

BEGIN 
	
	select 
	 Convert(nvarchar(20),AF.Id) AS AdmissionFormIdText,
	 Convert(nvarchar(20),@rRelationShipId) AS RelationShipIdText,
	 ISNULL(AF.Id,0) AS AdmissionFromId,
	 ISNULL(AF.FormNo,0) AS FormNo,
	 [sStudent].[fStudentNameGet](AF.FirstName , ISNULL(AF.MiddleName,'') , AF.LastName,OM.StudentNameFormatId ) AS Name,
	 ISNULL(AF.FirstName,'')AS FirstName,
	 ISNULL(AF.ForClassId,0) AS ForClassId,
	 ISNULL(AF.DateOfBirth,'') AS DateOfBirth,
	 ISNULL(AF.BatchId,0)AS BatchId,
	 ISNULL(CM.Title,'') AS ClassName,
	 ISNULL(AF.OrgId,0)AS OrgId,
	 ISNULL(AF.StreetOne,'')AS StreetOne,
	 ISNULL(AF.StreetTwo,'')AS StreetTwo,
	 ISNULL(AF.StreetThree,'')AS StreetThree,
	 ISNULL(AF.Country,'')AS Country,
	 ISNULL(AF.City,'')AS City,
	 ISNULL(AF.State,'')AS State,
	 ISNULL(AF.ZipCode,'') AS ZipCode,
	 ISNULL(AF.ContactEmail,'')AS ContactEmail,
	 ISNULL(AF.ContactNo,'') AS ContactNo,
	 ISNULL(AF.PreviousSchool,'')AS PreviousSchool,
	 ISNULL(AF.StudentPhoto,0x) As StudentPhoto,
	 ISNULL(AF.ReligionId,0) AS ReligionId,
	 IsNULL(RM.Title,'') AS ReligionName,
	 ISNULL(AF.MeritGrade,'')AS MeritGrade,
	 ISNULL(AF.MeritMarks,0) AS MeritMarks,
	 ISNULL(AF.GenderId,0) AS GenderId,
	 ISNULL(GM.Title,'') AS Gender,
	 ISNULL(AF.FamilyCast,'')AS FamilyCast,
	 ISNULL(AF.FamilySubCast,'')AS FamilySubCast,
	 ISNULL(AF.CastCategoryId,0) AS CastCategoryId,
	 ISNULL(CCM.Title,'') AS CastCategory ,
	 ISNULL(OM.DisplayTitle,'')AS DisplayTitle ,
	 ISNULL(BM.Title,'') As Batch,
	 ISNULL(AFM.FatherName,'') AS FatherName ,
	 ISNULL(AFM.FatherDateOfBirth,'')As FatherDateOfBirth,
	 ISNULL(AFM.FatherOccupation,'') AS FatherOccupation,
	 ISNULL(AFM.FatherOfficeAddress,'') AS FatherOfficeAddress,
	 ISNULL(AFM.FatherIncome,0) AS FatherIncome,
	 ISNULL(AFM.FatherQualification,'') AS FatherQualification,
	 ISNULL(AFM.FatherContactNo,'') AS FatherContactNo ,
	 ISNULL(AFM.FatherMail,'') AS FatherMail,
	 ISNULL(AFM.FatherOrganization,'') AS FatherOrganization,
	 ISNULL(AFM.MotherName,'') AS MotherName,
	 IsNull(AFM.MotherDateOfBirth,'')As MotherDateOfBirth,
	 ISNULL(AFM.MotherIncome,0) AS MotherIncome,
	 ISNULL(AFM.MotherOccupation,'') AS MotherOccupation,
	 ISNULL(AFM.MotherOfficeAddress,'') AS MotherOfficeAddress,
	 ISNULL(AFM.MotherQualification,'') AS MotherQualification,
	 ISNULL(AFM.MotherContactNo,'') AS MotherContactNo,
	 ISNULL(AFM.MotherMail,'') AS MotherMail,
	 ISNULL(AFM.MotherOrganization,'') AS MotherOrganization,
	 isnull(AFM.RelativeName,'') AS RelativeName ,
	 ISNULL(AFM.RelativeDateOfBirth,'') AS RelativeDateOfBirth,
	 ISNULL(AFM.RelativeOccupation,'') AS RelativeOccupation,
	 ISNULL(AFM.RelativeContactNo,'') AS RelativeContactNo,
	 ISNULL(AFM.RelativeMail,'') AS RelativeMail,
	 ISNULL(AFM.RelativeOfficeAddress,'') AS RelativeOfficeAddress,
	 ISNULL(AFM.RelativeIncome,0) AS RelativeIncome,
	 ISNULL(AFM.RelativeQualification,'') AS RelativeQualification,
	 ISNULL(AFM.RelationshipName,'') AS RelationshipName ,
	 ISNULL(AC.IsFixParentAcademic,0) AS IsParentAcademicRequired ,
	 ISNULL (AC.IsStudentAcademicRequired,0) AS IsStudentAcademicRequired ,
	 ISNULL(AC.IsSiblingDetailRequired,0) AS IsSiblingDetailRequired,
	 ISNULL(AC.IsReferenceDetailRequired,0) AS IsReferenceDetailRequired ,
	 ISNULL(AC.IsFamilyDetailRequired,0) AS IsFamilyDetailRequired ,
	 ISNULL(AC.IsFixStudentAcademic,0) AS IsFixStudentAcademic,
	 ISNULL(AC.ConfirmationRemark,'') AS ConfirmationRemark,
	 ISNULL(AC.IsHostelDetailRequired,0) AS IsHostelDetailRequired ,
	 ISNULL (AC.IsTransportDetailRequired,0) AS IsTransportDetailRequired ,
	 ISNULL(AC.IsHealthDetailRequired,0) AS IsHealthDetailRequired,
	 ISNULL(AC.IsBirthPlaceDetailRequired,0) AS IsBirthPlaceDetailRequired ,
	 ISNULL(AC.IsAadhaarDetailRequired,0) AS IsAadhaarDetailRequired ,
	 ISNULL(AC.IsBloodGroupDetailRequired,0) AS IsBloodGroupDetailRequired,
	
	 ISNULL(AF.IsPysicalDeformity,0) AS IsPysicalDeformity,
	 ISNULL(AF.PysicalDeformityRemark,'') AS PysicalDeformityRemark,
	 ISNULL(AF.IsMajorIllness,0) AS IsMajorIllness,
	 ISNULL(AF.MajorIllnessRemark, '') As MajorIllnessRemark,
	 ISNULL(AF.IsAllergy,0)AS IsAllergy,
	 ISNULL(AF.AllergyRemark,'') As AllergyRemark,
	 ISNULL(AF.BirthPlace,'') As BirthPlace,
	 ISNULL(AF.BirthTaluka,'') As BirthTaluka,
	 ISNULL(AF.BirthDistrict,'') As BirthDistrict,
	 Isnull(BGM.Title,'') As BloodGroupName,
	 ISNULL(AF.AdhaarNumber,'') AS AdhaarNumber,
	 ISNULL(AF.IsHostelRequired,0)AS IsHostelRequired,
	 ISNULL(AF.IsTransportRequired,0)AS IsTransportRequired,
	 ISNULL(AFM.FatherPhoto,0x)As FatherPhoto,
	  ISNULL(AFM.MotherPhoto,0x) As MotherPhoto,
	 ISNULL(AFM.RelativePhoto,0x) As RelativePhoto,
	 ISNULL(AF.BirthState,'')AS BirthState,
	 ISNULL(AF.BirthCountry,'') AS BirthCountry,
	 ISNULL(AC.CustomField1Remark,'') AS CustomField1Remark,
	 ISNULL(AC.CustomField2Remark,'') AS CustomField2Remark,
	 ISNULL(AC.CustomField3Remark,'') AS CustomField3Remark,
	 ISNULL(AF.CustomField1Answer,'')As CustomField1Answer,
	 ISNULL(AF.CustomField2Answer,'')As CustomField2Answer,
	 ISNULL(AF.CustomField3Answer,'')As CustomField3Answer,
	 ISNULL(AF.Nationality,'') AS Nationality,
	 ISNULL(AF.MotherTongue,'') AS MotherTongue,
	 ISNULL(AF.OtherInformation,'') AS OtherInformation,
	 ISNULL(LWM.Title,'') AS LiveWith,
	 ISNULL(AC.AgeCutOffDate,'') AS AgeCutOffDate,
	 ISNULL(AC.Remark1,'') AS ExtraRemark1,
	 ISNULL(AC.Remark2,'') AS ExtraRemark2,
	 ISNULL(AC.Remark3,'') AS ExtraRemark3,
	 ISNULL(AF.DateOfBirthInWord,'') AS DOBInWords,
	 ISNULL(AF.CreatedDateTime,'') As FormDate,
	  ISNULL(AC.IsFatherDetail,0) AS IsFatherDetail,
	 ISNULL(AC.IsFatherFullDetail,0) AS IsFatherFullDetail,
	 ISNULL (AC.IsFatherAcademic,0) As IsFatherAcademic,
	 ISNULL (AC.IsMotherDetail,0) As IsMotherDetail,
	 ISNULL (AC.IsMotherFullDetail,0)As IsMotherFullDetail,
	 ISNULL (AC.IsMotherAcademic,0)As IsMotherAcademic,
	 ISNULL (AC.IsGuardianDetail,0)As IsGuardianDetail,
	 ISNULL (AC.IsGuardianFullDetail,0)As IsGuardianFullDetail,
	 ISNULL (AC.IsGuardianAcademic,0)As IsGuardianAcademic,
	 ISNULL (AC.IsOtherInformationRequired,0)As IsOtherInformationRequired,
	 ISNULL (AC.IsHealthDetailRequired,0) As IsHealthDetailRequired,
	 ISNULL (AC.IsCustomField1Required,0) As IsCustomField1Required,
	 ISNULL (AC.IsCustomField2Required,0) As IsCustomField2Required,
	 ISNULL (AC.IsCustomField3Required,0) As IsCustomField3Required,
	 ISNULL (AFM.FatherAdhaarNumber,'') AS FatherAadhaarNumber,
	 ISNULL (AFM.MotherAadhaarNumber,'') AS MotherAadhaarNumber,
	 ISNULL (AFM.RelativeAadhaarNumber,'') AS RelativeAadhaarNumber,
	 ISNULL( (SELECT (CASE WHEN DFO.DisplayFieldId Is Null THEN 0  ELSE 1 END) 
	 FROM sConfig.tDisplayFieldMaster DFM LEFT JOIN sConfig.tDisplayFieldOrg DFO ON 
	 DFO.DisplayFieldId = DFM.Id AND DFO.OrgId =AF.OrgId AND DFO.OrgId=AF.OrgId
	 WHERE DFM.Id=324
	 ),0)AS IsOtherDetailsLiveWith,
	 ISNULL( (SELECT (CASE WHEN DFO.DisplayFieldId Is Null THEN 0  ELSE 1 END) 
	 FROM sConfig.tDisplayFieldMaster DFM LEFT JOIN sConfig.tDisplayFieldOrg DFO ON 
	 DFO.DisplayFieldId = DFM.Id AND DFO.OrgId =AF.OrgId AND DFO.OrgId=AF.OrgId
	 WHERE DFM.Id=323
	 ),0)AS IsOtherDetailsOtherInformation,
	 ISNULL(AF.MiddleName,'') AS MiddleName,
	 ISNULL(AF.LastName,'')AS LastName,
	 ISNULL(PT.Id,0) AS PaymentTransactionId,
	 ISNULL(PT.PayAmount,0.00) AS PayAmount,
	 ISNULL(PT.TransactionStatusId,0) AS TransactionStatusId,
	 ISNULL(PT.PayDateTime,'') AS PayDateTime,
	 ISNULL(AFM.IsFatherExStudent,0) AS IsFatherExStudent,
	 ISNULL(AFM.IsMotherExStudent,0) AS IsMotherExStudent,
	 ISNULL(AFM.IsRelativeExStudent,0)AS IsRelativeExStudent,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](302,OM.Id) AS IsBirthPlace,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](303,OM.Id) AS IsBirthTaluka,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](304,OM.Id) AS IsBirthDistrict,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](305,OM.Id) AS IsBirthState,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](306,OM.Id) AS IsBirthCountry,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](307,OM.Id) AS IsPreviousSchool,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](308,OM.Id) AS IsStudentPhoto,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](316,OM.Id) AS IsContactEmail,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](317,OM.Id) AS IsReligion,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](318,OM.Id) AS IsFamilyCaste,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](319,OM.Id) AS IsNationality,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](320,OM.Id) AS IsCasteCategory,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](388,OM.Id) AS IsFamilySubCaste,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](321,OM.Id) AS IsMotherTongue,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](322,OM.Id) AS IsAadhaarNo,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](323,OM.Id) AS IsOtherInformation,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](324,OM.Id) AS IsLiveWith,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](325,OM.Id) AS IsHotelRequired,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](326,OM.Id) AS IsTransportRequired,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](327,OM.Id) AS IsMotherFullName,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](328,OM.Id) AS IsMotherMobilNo,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](329,OM.Id) AS IsMotherQualification,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](330,OM.Id) AS IsMotherOccupation,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](331,OM.Id) AS IsMotherEmail,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](332,OM.Id) AS IsMotherIncome,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](333,OM.Id) AS IsMotherOrganization,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](334,OM.Id) AS IsMotherDesignation,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](337,OM.Id) AS IsMotherOfficeAddress,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](338,OM.Id) AS IsMotherPhoto,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](410,OM.Id) AS IsMotherAadhaarNo,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](349,OM.Id) AS IsFatherFullName,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](350,OM.Id) AS IsFatherMobileNo,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](351,OM.Id) AS IsFatherQualification,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](352,OM.Id) AS IsFatherOccupation,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](353,OM.Id) AS IsFatherEmail,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](354,OM.Id) AS IsFatherIncome,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](355,OM.Id) AS IsFatherOrganization,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](356,OM.Id) AS IsFatherDesignation,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](359,OM.Id) AS IsFatherOfficeAddress,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](360,OM.Id) AS IsFatherPhoto,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](409,OM.Id) AS IsFatherAadhaarNo,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](361,OM.Id) AS IsGuardianFullName,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](362,OM.Id) AS IsGuardianMobileNo,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](363,OM.Id) AS IsGuardianPhoto,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](396,OM.Id) AS IsGuardianQualification,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](397,OM.Id) AS IsGuardianOccupation,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](398,OM.Id) AS IsGuardianEmail,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](399,OM.Id) AS IsGuardianIncome,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](400,OM.Id) AS IsGuardianOrganization,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](401,OM.Id) AS IsGuardianDesignation,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](403,OM.Id) AS IsGuardianRelationship,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](405,OM.Id) AS IsGuardianOfficeAddress,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](411,OM.Id) AS IsGuardianAadhaarNo,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](369,OM.Id) AS IsPhysicalDeformity,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](370,OM.Id) AS IsPhysicalDeformityRemark,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](371,OM.Id) AS IsMajorIllness,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](372,OM.Id) AS IsMajorIllnessRemark,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](373,OM.Id) AS IsAllergy,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](374,OM.Id) AS IsAllergyRemark,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](407,OM.Id) AS IsMeritMarks,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](408,OM.Id) AS IsMeritGrade,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](395,OM.Id) AS IsBloodGroup,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](309,OM.Id) AS IsStreetOneAddress ,

	  ISNULL(AFM.FatherDesignation,'') AS FatherDesignation ,
	  ISNULL(AFM.FatherPassOutYear,'') AS FatherPassOutYear ,
	  ISNULL(AFM.MotherDesignation,'') AS MotherDesignation ,
	  ISNULL(AFM.MotherPassOutYear,'') AS MotherPassOutYear ,
	  AF.AdmissionDate --add for Mentis : 0034078

  FROM  
		    sAdmission.tAdmissionForm AF 
		     
			--INNER JOIN sCommon.tStatusMaster SM ON SM.Id=AF.StatusId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=AF.OrgId
			INNER JOIN sSetup.tBatchMaster BM  ON  BM.Id=AF.BatchId
			INNER JOIN sSetup.tClassMaster CM ON CM.Id=AF.ForClassId
			LEFT JoIN sCommon.tReligionMaster RM ON RM.Id=AF.ReligionId
			LEFT JOIN sCommon.tGenderMaster GM ON GM.Id=AF.GenderId
			LEFT JOIN sCommon.tBloodGroupMaster BGM ON BGM.Id=AF.BloodGroupId
			--LEFT JOIN sAdmission.tAdmissionFormParentAcademic PA ON PA.AdmissionFormId=AF.Id
			--INNER JOIN sCommon.tRelationshipMaster RSM ON RSM.Id=PA.RelationshipId
			LEFT JOIN sCommon.tCastCategoryMaster CCM  ON CCM.Id=AF.CastCategoryId
			LEFT JOIN sAdmission.tAdmissionFormFamilyDetail AFM ON AFM.AdmissionFormId=AF.Id
			LEFT JOIN sCommon.tLiveWithMaster LWM ON LWM.Id = AFM.LiveWithId
			LEFT JOIN  sAdmission.tAdmissionCriteria AC ON AC.ClassId=CM.Id  AND AC.BatchId=AF.BatchId		
			LEFT JOIN sOp.tPaymentTransaction PT ON PT.PayerSourceId = AF.Id AND PT.PayerSourceTypeId = 2027 AND (PT.TransactionStatusId = 2 OR PT.TransactionStatusId = 4)
 WHERE 	
  (AF.Id = @rId OR @rId = 0)
  AND ((AF.ForClassId=@rClassId) OR (@rClassId=0))	
  AND ((AF.BatchId = @rBatchId) OR (@rBatchId = 0))
	AND ((CM.DepartmentId=@rDepartmentId) OR (@rDepartmentId = 0))
	AND ((AF.MeritMarks >= @rFromMeritMarks) OR (@rFromMeritMarks=0))
	AND ((AF.MeritMarks <= @rToMeritMarks) OR (@rToMeritMarks=0))		
	AND ((CONVERT(DATE,AF.CreatedDateTime) >= @rFromDate) OR (isnull(@rFromDate,'')=''))
	AND ((CONVERT(DATE,AF.CreatedDateTime) <= @rToDate) OR (isnull(@rToDate,'')=''))
 

				
END
GO
PRINT N'Altering Procedure [sAdmission].[pRptAdmissionReceiptGet]...';


GO

ALTER PROCEDURE [sAdmission].[pRptAdmissionReceiptGet] 
	 	 
	 	 @rBatchId int,
	 	 @rOrgId int ,
	 	 @rFormNo int
	 	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	SELECT 
			ISNULL(AF.FirstName,'') + ' ' + ISNULL(AF.MiddleName, '') + ' ' + ISNULL(AF.LastName,'') AS StudentName,
			AFF.FatherName AS FatherName,
			AFF.MotherName AS MotherName,
			AF.StreetOne+' ' +AF.StreetTwo+' ' +AF.StreetThree+' ' +AF.City +' ' +AF.State+' '+AF.Country AS StudentAddress,
			AF.ContactNo AS MobileNo,
			AF.FormNo as FormNo,
			0 as ReceiptNumber,
			Convert(date,ISNULL(AF.CreatedDateTime,'')) as ReceiptDate,
			CM.DisplayTitle AS ClassName,
			BM.Title AS BatchName,
			AC.FormFeeAmount as FormFeeAmount,
			AC.FormFeeName AS FormFeeName,
			ACF.FeeNumber ,
			ACF.FeeName,
			ACF.FeeOrder,
			AFFE.FeeAmount,
			ISNULL(AF.Remark,'') AS Remark,
			ISNULL(AF.DateOfBirth,'') AS DateOfBirth,
			ISNULL(AF.FirstName,'') AS StudentFirstName,
			ISNULL(AF.MiddleName, '') AS StudentMiddleName,
			ISNULL(AF.LastName,'') AS StudentLastName,
			ISNULL(GM.Title,'') as Gender,
			AFR.ReceiptNumber AS ReceiptNo --Added for mantis : 33847 by Nilesh
			
	FROM 
			sAdmission.tAdmissionForm AF 
			INNER JOIN sSetup.tClassMaster CM ON CM.Id = AF.ForClassId 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AF.BatchId 
			INNER JOIN sAdmission.tAdmissionCriteria AC ON AC.ClassId=CM.Id AND AC.BatchId = @rBatchId
			LEFT JOIN sAdmission.tAdmissionFormFamilyDetail AFF ON AFF.AdmissionFormId= AF.Id 
			LEFT JOIN sAdmission.tAdmissionFormFee  AFFE ON AFFE.AdmissionFormId = AF.Id
			LEFT JOIN sAdmission.tAdmissionCriteriaFee ACF ON ACF.Id = AFFE.AdmissionCriteriaFeeId
			LEFT JOIN sCommon.tGenderMaster GM ON GM.Id=AF.GenderId
			LEFT JOIN sAdmission.tAdmissionFormReceipt AFR ON AF.Id = AFR.SourceId --Added for mantis : 33847 by Nilesh
			
	WHERE
			AF.BatchId = @rBatchId
			AND AF.OrgId = @rOrgId
			AND AF.FormNo =@rFormNo
END
GO
PRINT N'Altering Procedure [sAlert].[pAbsentEmployeeGet]...';


GO
ALTER PROCEDURE sAlert.pAbsentEmployeeGet

	 	 @rFromDate date='',
	 	 @rBatchId int=0,
	 	 @rOrgId int=0,
		 @rIsPresent bit,
		 @rMailSubject nvarchar(500)='',
		 @rTemplate nvarchar(max),
		 @rSourceId bigint=0,
		 @rEmployeeIds nvarchar(max) = ''

	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

	Select
			EC.EmployeeId,
			EC.Code,
			EC.EmployeeName,
			ISNULL(EC.MobileNumber,'') AS MobileNo,
			ISNULL(EC.CompanyEmail,'') AS EmailId,
			Convert(Varchar,EAR.AttendanceDate,105) AS AttendanceDate,
			CASE WHEN @rIsPresent=0 THEN										
			replace(replace(replace(@rTemplate,'[Name]',EC.EmployeeName),		
			'[AbsentReason]',IsNULL(LR.Title,'')),
			'[AbsentDates]',Convert(Varchar,EAR.AttendanceDate,105))	
			ELSE
			replace(replace(replace(@rTemplate,'[Name]',EC.EmployeeName),
			'[PresentDates]',Convert(Varchar,EAR.AttendanceDate,105)),
			'[Department]',EC.DepartmentName)										
			END
			AS MsgText,
			@rMailSubject AS Subject,
			EC.EmployeeId AS SourceId,
			95 AS SourceTypeId,
			EC.OrgId,
			OM.OrgGroupId,
			EC.EmployeeId AS ReceiverSourceId,
			95 AS ReceiverSourceTypeId,
			EC.DepartmentName,
			EAR.AttendanceDate AS AbsentDates,
			ISNULL(LR.Title,'') AS AbsentReason,
			EAR.AttendanceDate AS PresentDates,
			EC.WhatsAppContactNo

	From
		sHrm.vEmployeeCommunication EC
	INNER JOIN sHrm.tEmployeeAttendanceRegister EAR  ON EAR.EmployeeId = EC.EmployeeId
	INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = EC.OrgId
	LEFT JOIN sHrm.tLeaveReasonMaster LR ON EAR.AbsentReasonId = LR.Id

	WHERE
		(EC.OrgId=@rOrgId)
		AND (ISNULL(EC.EmployeeId,0) IN( SELECT cast(item as bigint) FROM  sCommon.fnsplit(@rEmployeeIds,','))OR ISNULL(@rEmployeeIds,'')='')
		AND (EAR.BatchId=@rBatchId)
		AND (EC.StatusId=7)
		AND ((EAR.AttendanceDate = @rFromDate) OR (ISNULL(@rFromDate,'')=''))
		AND (EAR.IsPresent = @rIsPresent)
		AND EC.IsOtherUser=0 

END
GO
PRINT N'Altering Procedure [sAlert].[pClassworkStudentListGet]...';


GO
ALTER PROCEDURE [sAlert].[pClassworkStudentListGet]
	 
		 @rDivisionId bigint,
		 @rOrgId int,
	 	 @rBatchId int,	 	 	 	
	 	 @rTemplate nvarchar(max) 	,
		 @rMailSubject nvarchar(500)='',
		 @rSubjectId bigint,
		 @rClassworkId bigint
		
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	
	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 [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 (SC.DivisionId = @rDivisionId)
		AND (AC.SubjectId=@rSubjectId)
		AND AC.Id = @rClassworkId
		AND OS.AcademicId IS NULL
END
GO
PRINT N'Altering Procedure [sAppraisal].[pRptTeacherPerformanceGet]...';


GO

ALTER PROCEDURE [sAppraisal].[pRptTeacherPerformanceGet]
    
    @rBatchId int,
    @rEmployeeId bigint,
	@rAppraisalTypeId int,
	@rKPAStatus tinyint,
	@rOrgGroupDeptId int,
	@rEmployeeTypeId [int],
	@rDepartmentId [int]= 0,
	@rGradeId [int]= 0,
	@rDesignationId [int]= 0,
	@rGenderId [int]= 0,
	@rEmployeeCode nvarchar(50)='',
	@rEmployeeGroupId smallint,
	@rEmployeeStatusId smallint,
	@rOrgId smallint
    
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
			  
		SELECT
			  EM.Id AS EmployeeId,
			  ISNULL(EM.FirstName + ' ' + EM.LastName,'') AS EmployeeName,
			  ISNULL(EM1.FirstName + ' ' + EM1.LastName,'') AS EmployeeManagerName,
			  ISNULL(EM2.FirstName + ' ' + EM2.LastName,'') AS EmployeeBusinessHeadName,
			  ISNULL(EM3.FirstName + ' ' + EM3.LastName,'') AS OrgInchargeName,
			  ISNULL([sAppraisal].[fClassTeacherGet](EM.Id),'') AS ClassTeacher,
			  ISNULL([sAppraisal].[fTeacherSujectClassGet](EM.Id),'') AS ClassSubject,
			  ISNULL(KPAD.Indicator,'') AS Indicator,
			  ISNULL(KPAD.Weightage,0.0) AS Weightage,
			  ISNULL(KTM.Code,'') AS KPAType,
			  ISNULL(KER.BusinessHeadRating,0.0) AS BusinessHeadRating,
			  ISNULL(ERD.ManagerRating,0.0) AS ManagerRating,
			  ISNULL(KER.BusinessHeadRecommendationDesignation,'') AS BHReview,
			  ISNULL((Select Title from sSetup.tBatchMaster Where Id = @rBatchId),'') AS BatchName,
			  ISNULL(KPAD.Id,0) AS KPAId,
			  -- Mantis Start - 0033855
			  ISNULL(ERD.MyRating,0.0) AS EmployeeRating,
			  ISNULL(KER.Remark,'') AS EmployeeRemark
			  -- Mantis End - 0033855
		
		FROM
			  sHrm.tEmployeeMaster EM
			  INNER JOIN sHrm.vEmployeeCommonDetail ECD ON ECD.EmployeeId = EM.Id 
			  INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id
			  INNER JOIN sHrm.tEmployeeMaster EM1 ON EM1.Id = EJD.EmployeeManagerId
			  INNER JOIN sHrm.tEmployeeMaster EM2 ON EM2.Id = EJD.EmployeeBusinessHeadId
			  INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = EM.OrgId
			  INNER JOIN sHrm.tEmployeeMaster EM3 ON EM3.Id = OM.EmployeeId
			  LEFT JOIN sAppraisal.tKPAEmployee KPA ON KPA.EmployeeId=EM.Id AND KPA.BatchId = @rBatchId
			  LEFT JOIN sAppraisal.tKPAEmployeeDetail KPAD ON KPAD.KPAEmployeeId=KPA.Id 
			  LEFT JOIN sAppraisal.tKPATypeMaster KTM ON KTM.Id = KPAD.KPATypeId  AND ((KTM.Id = @rKPAStatus) OR (@rKPAStatus = 0))
			  LEFT JOIN sAppraisal.tKPAEmployeeRating KER ON KER.KPAEmployeeId=KPA.Id AND KER.AppraisalTypeId = @rAppraisalTypeId
			  LEFT JOIN sAppraisal.tKPAEmployeeRatingDetail ERD ON ERD.KPAEmployeeRatingId = KER.Id AND ERD.KPAEmployeeDetailId =  KPAD.Id
			  LEFT JOIN sCommon.tOrgGroupDepartmentMaster OGDM ON OGDM.OrgGroupId = OM.OrgGroupId AND OGDM.Id = @rOrgGroupDeptId
		WHERE
			  ((EM.Id = @rEmployeeId) OR (@rEmployeeId = 0)) 
			  AND (ECD.EmployeeTypeId = @rEmployeeTypeId OR @rEmployeeTypeId = 0)
			  AND (ECD.OrganizationDepartmentId = @rDepartmentId OR @rDepartmentId = 0)
			  AND (ECD.EmployeeStatusId = @rEmployeeStatusId OR @rEmployeeStatusId = 0)
			  AND (ECD.EmployeeGroupId=@rEmployeeGroupId OR @rEmployeeGroupId=0)
			  AND (ECD.EmployeeGradeId = @rGradeId OR @rGradeId = 0)
			  AND (ECD.EmployeeDesignationId = @rDesignationId OR @rDesignationId = 0)	 	   
			  AND (ECD.GenderId = @rGenderId OR @rGenderId = 0) 
		ORDER BY
			  EM.Id
			  
END
GO
PRINT N'Altering Procedure [sCanteen].[pCanteenMasterAdd]...';


GO



ALTER PROCEDURE [sCanteen].[pCanteenMasterAdd]
	 
        @rId int,
		@rNumber  int,
		@rCode nvarchar(20),
		@rTitle nvarchar(100),
		@rIsObsolete bit,
		@rOrgGroupId smallint,
		@rCreatedUserId bigint,
		@rUpdatedUserId bigint,
		@rOrderIndex int,
		@rDepositHeadId bigint,
		@rDepositExpenseTypeId bigint
		
		
		
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	IF(@rId = 0)	
	BEGIN  
		
		If Exists(select 1 from sCanteen.tCanteenMaster  where Code=@rCode AND OrgGroupId=@rOrgGroupId )
		Begin
			select -102 as Result
			RETURN
		End
		If Exists(select 1 from sCanteen.tCanteenMaster where Title=@rTitle AND OrgGroupId=@rOrgGroupId)
			BEGIN
			select -103 as Result
			RETURN
		END 
		--mantis Start - 0033603
		If Exists(select 1 from sCanteen.tCanteenMaster where Number=@rNumber AND OrgGroupId=@rOrgGroupId)
			BEGIN
			select -104 as Result
			RETURN
		END 
		If Exists(select 1 from sCanteen.tCanteenMaster where OrderIndex=@rOrderIndex AND OrgGroupId=@rOrgGroupId)
			BEGIN
			select -105 as Result
			RETURN
		END 
		--mantis End - 0033603
	END
	ELSE
	BEGIN
	--mantis Start - 0033603
		If Exists(select 1 from sCanteen.tCanteenMaster  where Code=@rCode AND OrgGroupId=@rOrgGroupId AND Id<>@rId)
		Begin
			select -102 as Result
			RETURN
		End
		--mantis End - 0033603
		If  Exists(select Id from sCanteen.tCanteenMaster where Title=@rTitle AND OrgGroupId=@rOrgGroupId AND Id<>@rId)
		Begin
			select -103 as Result
			RETURN
		End
		--mantis Start - 0033603
		If Exists(select 1 from sCanteen.tCanteenMaster where Number=@rNumber AND OrgGroupId=@rOrgGroupId AND Id<>@rId)
			BEGIN
			select -104 as Result
			RETURN
		END 
		If Exists(select 1 from sCanteen.tCanteenMaster where OrderIndex=@rOrderIndex AND OrgGroupId=@rOrgGroupId AND Id<>@rId)
			BEGIN
			select -105 as Result
			RETURN
		END 
		--mantis End - 0033603

	END
	
	 BEGIN TRANSACTION	
	 DECLARE @lNextNumber int

	IF(@rId = 0)	
	BEGIN
	EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sCanteen.tCanteenMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	INSERT INTO sCanteen.tCanteenMaster
		(
			Id,
			Title,
			Number,
			Code,
			IsObsolete,
			CreatedUserId,
			CreatedDateTime,
			UpdatedUserId,
			UpdatedDateTime,
			OrgGroupId ,
			OrderIndex,
			DepositHeadId,
			DepositExpenseTypeId
		)
	VALUES
		(
			@lNextNumber,
			@rTitle,
			@rNumber,
			@rCode,
			@rIsObsolete,
			@rCreatedUserId,
			sCommon.fGetDate(), 
			@rUpdatedUserId,
			sCommon.fGetDate(),
			@rOrgGroupId,
			@rOrderIndex,
			@rDepositHeadId,
			@rDepositExpenseTypeId
		)
		
		  INSERT INTO sSecurity.tUserAccess
           (
           SourceTypeId
           ,SourceId
           ,[UserId]
           
           )
		   SELECT 
		   2026
		   ,@lNextNumber
		   ,@rCreatedUserId
		   
		    SELECT @lNextNumber AS Result
		   
	END	 

ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE  sCanteen.tCanteenMaster
	    SET
			Title=@rTitle,
			Number=@rNumber,
			Code=@rCode,
			IsObsolete=@rIsObsolete,
			UpdatedUserId=@rCreatedUserId,
			UpdatedDateTime=sCommon.fGetDate(),
			OrderIndex=@rOrderIndex,
			DepositHeadId=@rDepositHeadId,
			DepositExpenseTypeId=@rDepositExpenseTypeId
			
	      
	      WHERE Id = @rId
	      SELECT @lNextNumber AS Result
	 END  	

	COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Altering Procedure [sFee].[pOldExemptionFeeToExceptionAdd]...';


GO
ALTER PROCEDURE sFee.pOldExemptionFeeToExceptionAdd
	
	@rOldBatchId int,
	@rNewBatchId int,
	@rOldFeeId nvarchar(max),
	@rNewFeeId int,
	@rOrgId int,
	@rCreatedUserId bigint,
	@rXml  nvarchar(MAX)
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
BEGIN TRY 
	IF OBJECT_ID('tempdb..#TempOldExemptionFeeImport') IS NOT NULL DROP TABLE #TempOldExemptionFeeImport

	DECLARE @lInterrorCode INT,@intDoc INT
	DECLARE @lCount int
	EXECUTE @lInterrorCode = sp_xml_preparedocument @intDoc OUTPUT, @rXml
	
	CREATE TABLE #TempOldExemptionFeeImport
	(
		[AutoId] int identity,
		[StudentId] bigint NULL ,
		[AcademicId] bigint NULL,
		[ExemptionAmount] decimal(12,2) NULL
	)
	
	INSERT INTO #TempOldExemptionFeeImport 
	(
		StudentId,
		AcademicId,
		ExemptionAmount
	)	
	SELECT	
			A.StudentId,
			A.AcademicId,
			A.ExemptionAmount
	FROM OPENXML (@intDoc, '/Table/OldExemptionFeeImport', 1)
	WITH
	(
			StudentId bigint '@StudentId',
			AcademicId bigint '@AcademicId',
			ExemptionAmount decimal(12,2) '@ExemptionAmount'
	)A 
	
	SELECT @lCount = COUNT(AutoId) FROM #TempOldExemptionFeeImport
	
	--SELECT * FROM #TempOldExemptionFeeImport
	BEGIN TRANSACTION
	
	WHILE (@lCount > 0)
	BEGIN
		DECLARE @lAcademicId bigint = NULL
		DECLARE @lStudentId bigint = NULL
		DECLARE @lClassId int = NULL
		DECLARE @lFeeSetupId int = NULL
		DECLARE @lExemptionAmount decimal(12,2)
		DECLARE @lAdmissionCategoryId int

		SELECT @lStudentId = StudentId,@lExemptionAmount=ExemptionAmount FROM #TempOldExemptionFeeImport WHERE AutoId = @lCount
		SELECT @lAcademicId = Id, @lClassId=ClassId,@lAdmissionCategoryId=AdmissionCategoryId FROM  sStudent.tAcademic SA WHERE StudentId = @lStudentId AND BatchId = @rNewBatchId
		SELECT @lFeeSetupId = Id FROM sFee.tFeeSetup WHERE  ClassId = @lClassId AND BatchId=@rNewBatchId AND FeeId = @rNewFeeId AND AdmissionCategoryId = @lAdmissionCategoryId
		
		IF (ISNULL(@lAcademicId,0) > 0 AND ISNULL(@lFeeSetupId, 0) > 0 AND ISNULL(@lClassId, 0) > 0)
		BEGIN
				IF OBJECT_ID('tempdb..#TempFeeSetup') IS NOT NULL DROP TABLE #TempFeeSetup

				SELECT
					FM.Id AS FeeId,
					FS.Id AS FeeSetupId,
					ISNULL(FS.IsOptional,0)AS IsOptional,
					ISNULL(FS.IsVariable,0)AS IsVariable,
					ISNULL(FS.Amount,0)AS Amount,
					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.NotApplicableAmount,0.00) AS NotApplicableAmount
				INTO #TempFeeSetup 
				FROM sFee.tFeeMaster FM
				INNER JOIN 
				(SELECT 
					FS1.FeeId,
					FS1.Id,
					ISNULL(FS1.IsOptional,0)AS IsOptional,
					ISNULL(FS1.IsVariable,0)AS IsVariable,
					ISNULL(FS1.Amount,0)AS Amount,
					ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
					ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
					FS1.BatchId,
					ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
					ISNULL(FS1.CollectionGroupId,0) AS CollectionGroupId,
					ISNULL(FS1.FeeDuration,'')  AS FeeDuration
				FROM sFee.tFeeSetup FS1
				WHERE FS1.ClassId=@lClassId AND FS1.AdmissionCategoryId=@lAdmissionCategoryId AND IsOptional=0
				AND FS1.Id = @lFeeSetupId
				AND FS1.BatchId = @rNewBatchId
					
				UNION ALL
				
				SELECT 
					FS1.FeeId,
					FS1.Id,
					ISNULL(FS1.IsOptional,0)AS IsOptional,
					ISNULL(FS1.IsVariable,0)AS IsVariable,
					ISNULL(FS1.Amount,0)AS Amount,
					ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
					ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
					FS1.BatchId,
					ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
					ISNULL(FS1.CollectionGroupId,0) AS CollectionGroupId ,
					ISNULL(FS1.FeeDuration,'') AS FeeDuration
				FROM sFee.tFeeSetup FS1
				INNER JOIN sFee.tFeeOptional FO ON FO.FeeSetupId=FS1.Id AND (FO.SourceId=@lAcademicId) AND(FO.SourceTypeId=2001)
				WHERE FS1.BatchId = @rNewBatchId
				AND FS1.Id = @lFeeSetupId
				AND	FS1.ClassId=@lClassId AND FS1.AdmissionCategoryId=@lAdmissionCategoryId AND IsOptional=1
				) FS ON FS.FeeId=FM.Id
				LEFT JOIN sFee.tFeeAllocation FA ON FA.FeeSetupId=FS.Id AND (FA.SourceId=@lAcademicId) AND(FA.SourceTypeId=2001)
				LEFT JOIN
				(
					SELECT ISNULL(SUM(RD.Amount),0) AS PaidAmount,RD.FeeSetupId
					FROM sFee.tReceipt R INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id 		
					WHERE						
					 R.SourceId= @lAcademicId
					AND (R.SourceTypeId = 2001)
					AND R.IsObsolete = 0 
					AND R.BatchId = @rNewBatchId
					AND FeeSetupId = @lFeeSetupId
					GROUP BY FeeSetupId
				) R ON R.FeeSetupId = FS.Id	

				DECLARE @lCount1 int = 0

				SET @lCount1  = (SELECT COUNT(1) FROM #TempFeeSetup)

				IF(@lCount1 > 0)
				BEGIN
					DECLARE @lPendingAmount decimal(12,2) = 0
					SET @lPendingAmount = (SELECT PendingAmount FROM #TempFeeSetup WHERE FeeSetupId = @lFeeSetupId)
					
					IF(@lPendingAmount >= @lExemptionAmount)
					BEGIN
						IF EXISTS(SELECT 1 FROM sFee.tFeeAllocation WHERE SourceTypeId = 2001 AND SourceId = @lAcademicId AND FeeSetupId = @lFeeSetupId)
						BEGIN
							-- Update Fee Allocation
							UPDATE sFee.tFeeAllocation SET DiscountAmount = @lExemptionAmount, UpdatedUserId = @rCreatedUserId, UpdatedDateTime = sCommon.fGetDate()
							WHERE SourceTypeId = 2001 AND SourceId = @lAcademicId AND FeeSetupId = @lFeeSetupId
						END
						ELSE
						BEGIN
							-- Insert Fee Allocation
							INSERT INTO sFee.tFeeAllocation
							(
								SourceTypeId,
								SourceId,
								FeeSetupId,
								VariableAmount,
								DiscountAmount,
								AdditionalAmount,
								NotApplicableAmount,
								Remark,
								ReferenceTypeId,
								ReferenceSourceId,
								CreatedUserId,
								CreatedDateTime,
								UpdatedUserId,
								UpdatedDateTime
							)
							VALUES
							(
								2001,
								@lAcademicId,
								@lFeeSetupId,
								0,
								@lExemptionAmount,
								NULL,
								NULL,
								'Old Year Exemption Fee',
								NULL,
								NULL,
								@rCreatedUserId,
								sCommon.fGetDate(),
								NULL,
								NULL
							)
						END
					END
				END
		END
		 
		SET @lCount = @lCount - 1
	END
	 
	DROP TABLE #TempOldExemptionFeeImport
	SELECT 1 AS Result
	COMMIT TRANSACTION
END TRY

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


GO
ALTER PROCEDURE sFee.pOldExemptionFeeToExemptionGet
	
	@rOldBatchId int,
	@rNewBatchId int,
	@rOldFeeId nvarchar(max),
	@rNewFeeId int,
	@rOrgId int
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

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

	BEGIN TRY 

	DECLARE @lCount int
	
	-- Old Exemption Fee Import Temp Table
	CREATE TABLE #TempOldExemptionFeeImport
	(
		[AutoId] int identity,
		[StudentId] bigint NULL,
		[AcademicId] bigint NULL,
		[Code] nvarchar(20),
		[Name] nvarchar(300),
		[RollNo] int,
		[ClassDivision] nvarchar(300),
		[ExemptionAmount] decimal(12,2) NULL,
		[NewExemptionAmount] decimal(12,2) NULL,
		[Status] nvarchar(max) NULL
	)
	-- End Exemption Fee Import Temp Table
	
	INSERT INTO #TempOldExemptionFeeImport 
	SELECT 
		SA.StudentId,
		SA.AcademicId,
		SA.Code,
		SA.Name,
		SA.RollNo,
		ISNULL(SA.ClassName, '') + ' - ' + ISNULL(SA.DivisionName, '') AS ClassDivision,
		SUM(ISNULL(FA.DiscountAmount,0.00)) AS ExemptionAmount,
		0,
		''
	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			 
			FROM sFee.tFeeSetup FS1
			INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId 
			AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
			INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
			INNER JOIN sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id
			WHERE 
				(FS1.IsOptional=0)
				AND ((FS1.BatchId=@rOldBatchId) OR (@rOldBatchId=0))
				AND ((SA1.BatchId=@rOldBatchId) OR (@rOldBatchId=0))
				AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				--AND ((FM.Id=@rOldFeeId) OR (@rOldFeeId=0))
				AND (FM.Id IN (SELECT cast(item as nvarchar(20)) FROM  sCommon.fnsplit(@rOldFeeId,',')) OR @rOldFeeId='') 
			
			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 
			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
			INNER JOIN sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id
			WHERE
				(FS1.IsOptional=1)
				AND ((FS1.BatchId=@rOldBatchId) OR (@rOldBatchId=0))
				AND ((SA1.BatchId=@rOldBatchId) OR (@rOldBatchId=0))	
				AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				--AND ((FM.Id=@rOldFeeId) OR (@rOldFeeId=0))
				AND (FM.Id IN (SELECT cast(item as nvarchar(20)) FROM  sCommon.fnsplit(@rOldFeeId,',')) OR @rOldFeeId='') 
		) FS ON FS.AcademicId=SA.AcademicId
		LEFT JOIN sFee.tFeeAllocation FA ON FA.FeeSetupId=FS.Id AND FA.SourceId=SA.AcademicId
	WHERE	
		SA.OrgId = @rOrgId 
		AND SA.BatchId=@rOldBatchId
		AND ISNULL(FA.DiscountAmount,0.00) > 0
	GROUP BY SA.StudentId,SA.AcademicId,SA.Code,SA.Name,SA.RollNo,ISNULL(SA.ClassName, ''),ISNULL(SA.DivisionName, '')

	SELECT @lCount = COUNT(AutoId) FROM #TempOldExemptionFeeImport
	
	BEGIN TRANSACTION
	
		WHILE (@lCount > 0)
		BEGIN
			DECLARE @lAcademicId bigint = NULL
			DECLARE @lStudentId bigint = NULL
			DECLARE @lClassId int = NULL
			DECLARE @lFeeSetupId int = NULL
			DECLARE @lExemptionAmount decimal(12,2)
			DECLARE @lAdmissionCategoryId int

			SELECT @lStudentId = StudentId,@lExemptionAmount=ExemptionAmount FROM #TempOldExemptionFeeImport WHERE AutoId = @lCount
			SELECT @lAcademicId = Id, @lClassId=ClassId,@lAdmissionCategoryId=AdmissionCategoryId FROM sStudent.tAcademic SA WHERE StudentId = @lStudentId AND BatchId = @rNewBatchId
			SELECT @lFeeSetupId = Id FROM sFee.tFeeSetup WHERE  ClassId = @lClassId AND BatchId=@rNewBatchId AND FeeId = @rNewFeeId AND AdmissionCategoryId = @lAdmissionCategoryId
		
			IF (ISNULL(@lAcademicId,0) > 0 AND ISNULL(@lFeeSetupId, 0) > 0 AND ISNULL(@lClassId, 0) > 0)
			BEGIN
				IF OBJECT_ID('tempdb..#TempFeeSetup') IS NOT NULL DROP TABLE #TempFeeSetup

				SELECT
					FM.Id AS FeeId,
					FS.Id AS FeeSetupId,
					ISNULL(FS.IsOptional,0)AS IsOptional,
					ISNULL(FS.IsVariable,0)AS IsVariable,
					ISNULL(FS.Amount,0)AS Amount,
					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.NotApplicableAmount,0.00) AS NotApplicableAmount
				INTO #TempFeeSetup 
				FROM sFee.tFeeMaster FM
				INNER JOIN 
				(SELECT 
					FS1.FeeId,
					FS1.Id,
					ISNULL(FS1.IsOptional,0)AS IsOptional,
					ISNULL(FS1.IsVariable,0)AS IsVariable,
					ISNULL(FS1.Amount,0)AS Amount,
					ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
					ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
					FS1.BatchId,
					ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
					ISNULL(FS1.CollectionGroupId,0) AS CollectionGroupId,
					ISNULL(FS1.FeeDuration,'')  AS FeeDuration
				FROM sFee.tFeeSetup FS1
				WHERE FS1.ClassId=@lClassId AND FS1.AdmissionCategoryId=@lAdmissionCategoryId AND IsOptional=0
				AND FS1.Id = @lFeeSetupId
				AND FS1.BatchId = @rNewBatchId
					
				UNION ALL
				
				SELECT 
					FS1.FeeId,
					FS1.Id,
					ISNULL(FS1.IsOptional,0)AS IsOptional,
					ISNULL(FS1.IsVariable,0)AS IsVariable,
					ISNULL(FS1.Amount,0)AS Amount,
					ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
					ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
					FS1.BatchId,
					ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
					ISNULL(FS1.CollectionGroupId,0) AS CollectionGroupId ,
					ISNULL(FS1.FeeDuration,'') AS FeeDuration
				FROM sFee.tFeeSetup FS1
				INNER JOIN sFee.tFeeOptional FO ON FO.FeeSetupId=FS1.Id AND (FO.SourceId=@lAcademicId) AND(FO.SourceTypeId=2001)
				WHERE FS1.BatchId = @rNewBatchId
				AND FS1.Id = @lFeeSetupId
				AND	FS1.ClassId=@lClassId AND FS1.AdmissionCategoryId=@lAdmissionCategoryId AND IsOptional=1
				) FS ON FS.FeeId=FM.Id
				LEFT JOIN sFee.tFeeAllocation FA ON FA.FeeSetupId=FS.Id AND (FA.SourceId=@lAcademicId) AND(FA.SourceTypeId=2001)
				LEFT JOIN
				(
					SELECT ISNULL(SUM(RD.Amount),0) AS PaidAmount,RD.FeeSetupId
					FROM sFee.tReceipt R INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id 		
					WHERE						
					 R.SourceId= @lAcademicId
					AND (R.SourceTypeId = 2001)
					AND R.IsObsolete = 0 
					AND R.BatchId = @rNewBatchId
					AND FeeSetupId = @lFeeSetupId
					GROUP BY FeeSetupId
				) R ON R.FeeSetupId = FS.Id	

				DECLARE @lCount1 int = 0
				SET @lCount1  = (SELECT COUNT(1) FROM #TempFeeSetup)

				IF(@lCount1 > 0)
				BEGIN
					DECLARE @lPendingAmount decimal(12,2) = 0
					SET @lPendingAmount = (SELECT PendingAmount FROM #TempFeeSetup WHERE FeeSetupId = @lFeeSetupId)
					
					DECLARE @lIsReceiptGenerated bit = 0
				
					SET @lIsReceiptGenerated = (
					SELECT 1 FROM 
					sFee.tReceipt R
					INNER JOIN sFee.tReceiptDetail RD ON R.Id = RD.ReceiptId
					INNER JOIN sStudent.vStudentAcademic SA ON R.SourceId = SA.AcademicId AND SA.BatchId = @rNewBatchId
					INNER JOIN sFee.tFeeSetup FS ON FS.Id = RD.FeeSetupId AND FS.ClassId = SA.ClassId AND FS.BatchId = @rNewBatchId AND FS.FeeId = @rNewFeeId 
					LEFT JOIN sFee.tFeeAllocation FA ON FA.FeeSetupId=FS.Id AND FA.SourceId=SA.AcademicId
					WHERE (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(RD.Amount,0.00) = 0)
					AND R.SourceId = @lAcademicId
					)

					IF(@lPendingAmount < @lExemptionAmount)
					BEGIN
						UPDATE #TempOldExemptionFeeImport SET Status = 'Amount assigned in New Fee is less than Old Paid Fee', NewExemptionAmount = @lPendingAmount WHERE AutoId = @lCount 
					END
					else if(@lIsReceiptGenerated = 1)
					begin
						UPDATE #TempOldExemptionFeeImport SET Status = 'Receipt Generated or Fee Already Paid in New Batch', NewExemptionAmount = @lPendingAmount WHERE AutoId = @lCount
					end
					else
					begin
						UPDATE #TempOldExemptionFeeImport SET Status = '', NewExemptionAmount = @lPendingAmount WHERE AutoId = @lCount
					end
				END
			END
			ELSE
			BEGIN
				UPDATE #TempOldExemptionFeeImport SET Status = 'Fee Setup not assigned in New Batch', NewExemptionAmount = 0 WHERE AutoId = @lCount
			END
			SET @lCount = @lCount - 1
		END
	 
		SELECT * FROM #TempOldExemptionFeeImport
	
	COMMIT TRANSACTION
	END TRY
	BEGIN CATCH 
		DROP TABLE #TempOldExemptionFeeImport
		ROLLBACK TRANSACTION
		SELECT -1 AS Result, ERROR_LINE(), ERROR_MESSAGE()
	END CATCH	
END
GO
PRINT N'Altering Procedure [sFee].[pOldPaidFeeToNotApplicableAdd]...';


GO
ALTER PROCEDURE sFee.pOldPaidFeeToNotApplicableAdd
	
	@rOldBatchId int,
	@rNewBatchId int,
	@rOldFeeId nvarchar(max),
	@rNewFeeId int,
	@rOrgId int,
	@rCreatedUserId bigint,
	@rXml  nvarchar(MAX)
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
BEGIN TRY 
	IF OBJECT_ID('tempdb..#TempOldPaidFeeImport') IS NOT NULL DROP TABLE #TempOldPaidFeeImport

	DECLARE @lInterrorCode INT,@intDoc INT
	DECLARE @lCount int
	EXECUTE @lInterrorCode = sp_xml_preparedocument @intDoc OUTPUT, @rXml
	
	CREATE TABLE #TempOldPaidFeeImport
	(
		[AutoId] int identity,
		[StudentId] bigint NULL ,
		[AcademicId] bigint NULL,
		[PaidAmount] decimal(12,2) NULL
	)
	
	INSERT INTO #TempOldPaidFeeImport 
	(
		StudentId,
		AcademicId,
		PaidAmount
	)	
	SELECT	
			A.StudentId,
			A.AcademicId,
			A.PaidAmount
	FROM OPENXML (@intDoc, '/Table/OldPaidFeeImport', 1)
	WITH
	(
			StudentId bigint '@StudentId',
			AcademicId bigint '@AcademicId',
			PaidAmount decimal(12,2) '@PaidAmount'
	)A 
	
	SELECT @lCount = COUNT(AutoId) FROM #TempOldPaidFeeImport
	
	BEGIN TRANSACTION
	
	WHILE (@lCount > 0)
	BEGIN
		DECLARE @lAcademicId bigint = NULL
		DECLARE @lStudentId bigint = NULL
		DECLARE @lClassId int = NULL
		DECLARE @lFeeSetupId int = NULL
		DECLARE @lPaidAmount decimal(12,2)
		DECLARE @lAdmissionCategoryId int

		SELECT @lStudentId = StudentId,@lPaidAmount=PaidAmount FROM #TempOldPaidFeeImport WHERE AutoId = @lCount
		SELECT @lAcademicId = Id, @lClassId=ClassId,@lAdmissionCategoryId=AdmissionCategoryId FROM  sStudent.tAcademic SA WHERE StudentId = @lStudentId AND BatchId = @rNewBatchId
		SELECT @lFeeSetupId = Id FROM sFee.tFeeSetup WHERE  ClassId = @lClassId AND BatchId=@rNewBatchId AND FeeId = @rNewFeeId AND AdmissionCategoryId = @lAdmissionCategoryId

		IF (ISNULL(@lAcademicId,0) > 0 AND ISNULL(@lFeeSetupId, 0) > 0 AND ISNULL(@lClassId, 0) > 0)
		BEGIN
				IF OBJECT_ID('tempdb..#TempFeeSetup') IS NOT NULL DROP TABLE #TempFeeSetup

				SELECT
					FM.Id AS FeeId,
					FS.Id AS FeeSetupId,
					ISNULL(FS.IsOptional,0)AS IsOptional,
					ISNULL(FS.IsVariable,0)AS IsVariable,
					ISNULL(FS.Amount,0)AS Amount,
					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.NotApplicableAmount,0.00) AS NotApplicableAmount
				INTO #TempFeeSetup 
				FROM sFee.tFeeMaster FM
				INNER JOIN 
				(SELECT 
					FS1.FeeId,
					FS1.Id,
					ISNULL(FS1.IsOptional,0)AS IsOptional,
					ISNULL(FS1.IsVariable,0)AS IsVariable,
					ISNULL(FS1.Amount,0)AS Amount,
					ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
					ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
					FS1.BatchId,
					ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
					ISNULL(FS1.CollectionGroupId,0) AS CollectionGroupId,
					ISNULL(FS1.FeeDuration,'')  AS FeeDuration
				FROM sFee.tFeeSetup FS1
				WHERE FS1.ClassId=@lClassId AND FS1.AdmissionCategoryId=@lAdmissionCategoryId AND IsOptional=0
				AND FS1.Id = @lFeeSetupId
				AND FS1.BatchId = @rNewBatchId
					
				UNION ALL
				
				SELECT 
					FS1.FeeId,
					FS1.Id,
					ISNULL(FS1.IsOptional,0)AS IsOptional,
					ISNULL(FS1.IsVariable,0)AS IsVariable,
					ISNULL(FS1.Amount,0)AS Amount,
					ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
					ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
					FS1.BatchId,
					ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
					ISNULL(FS1.CollectionGroupId,0) AS CollectionGroupId ,
					ISNULL(FS1.FeeDuration,'') AS FeeDuration
				FROM sFee.tFeeSetup FS1
				INNER JOIN sFee.tFeeOptional FO ON FO.FeeSetupId=FS1.Id AND (FO.SourceId=@lAcademicId) AND(FO.SourceTypeId=2001)
				WHERE FS1.BatchId = @rNewBatchId
				AND FS1.Id = @lFeeSetupId
				AND	FS1.ClassId=@lClassId AND FS1.AdmissionCategoryId=@lAdmissionCategoryId AND IsOptional=1
				) FS ON FS.FeeId=FM.Id
				LEFT JOIN sFee.tFeeAllocation FA ON FA.FeeSetupId=FS.Id AND (FA.SourceId=@lAcademicId) AND(FA.SourceTypeId=2001)
				LEFT JOIN
				(
					SELECT ISNULL(SUM(RD.Amount),0) AS PaidAmount,RD.FeeSetupId
					FROM sFee.tReceipt R INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id 		
					WHERE						
					 R.SourceId= @lAcademicId
					AND (R.SourceTypeId = 2001)
					AND R.IsObsolete = 0 
					AND R.BatchId = @rNewBatchId
					AND FeeSetupId = @lFeeSetupId
					GROUP BY FeeSetupId
				) R ON R.FeeSetupId = FS.Id	

				DECLARE @lCount1 int = 0

				SET @lCount1  = (SELECT COUNT(1) FROM #TempFeeSetup)

				IF(@lCount1 > 0)
				BEGIN
					DECLARE @lPendingAmount decimal(12,2) = 0
					SET @lPendingAmount = (SELECT PendingAmount FROM #TempFeeSetup WHERE FeeSetupId = @lFeeSetupId)
					
					IF(@lPendingAmount >= @lPaidAmount)
					BEGIN
						IF EXISTS(SELECT 1 FROM sFee.tFeeAllocation WHERE SourceTypeId = 2001 AND SourceId = @lAcademicId AND FeeSetupId = @lFeeSetupId)
						BEGIN
							-- Update Fee Allocation
							UPDATE sFee.tFeeAllocation SET NotApplicableAmount = @lPaidAmount, UpdatedUserId = @rCreatedUserId, UpdatedDateTime = sCommon.fGetDate()
							WHERE SourceTypeId = 2001 AND SourceId = @lAcademicId AND FeeSetupId = @lFeeSetupId
						END
						ELSE
						BEGIN
							-- Insert Fee Allocation
							INSERT INTO sFee.tFeeAllocation
							(
								SourceTypeId,
								SourceId,
								FeeSetupId,
								VariableAmount,
								DiscountAmount,
								AdditionalAmount,
								NotApplicableAmount,
								Remark,
								ReferenceTypeId,
								ReferenceSourceId,
								CreatedUserId,
								CreatedDateTime,
								UpdatedUserId,
								UpdatedDateTime
							)
							VALUES
							(
								2001,
								@lAcademicId,
								@lFeeSetupId,
								0,
								0,
								0,
								@lPaidAmount,
								'Old Year Paid Fee',
								NULL,
								NULL,
								@rCreatedUserId,
								sCommon.fGetDate(),
								NULL,
								NULL
							)
						END
					END
				END
		END
		 
		SET @lCount = @lCount - 1
	END
	 
	DROP TABLE #TempOldPaidFeeImport
	SELECT 1 AS Result
	COMMIT TRANSACTION
END TRY

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


GO
ALTER PROCEDURE sFee.pOldPaidFeeToNotApplicableGet
	
	@rOldBatchId int,
	@rNewBatchId int,
	@rOldFeeId nvarchar(max),
	@rNewFeeId int,
	@rOrgId int
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

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

	BEGIN TRY 

	DECLARE @lCount int
	
	-- Old Exemption Fee Import Temp Table
	CREATE TABLE #TempOldPaidFeeImport
	(
		[AutoId] int identity,
		[StudentId] bigint NULL,
		[AcademicId] bigint NULL,
		[Code] nvarchar(20),
		[Name] nvarchar(300),
		[RollNo] int,
		[ClassDivision] nvarchar(300),
		[PaidAmount] decimal(12,2) NULL,
		[NewPaidAmount] decimal(12,2) NULL,
		[Status] nvarchar(max) NULL
	)
	-- End Exemption Fee Import Temp Table
	
	INSERT INTO #TempOldPaidFeeImport 
	SELECT 
		SA.StudentId,
		SA.AcademicId,
		SA.Code,
		SA.Name,
		SA.RollNo,
		ISNULL(SA.ClassName, '') + ' - ' + ISNULL(SA.DivisionName, '') AS ClassDivision,
		SUM(ISNULL(R.PaidAmount,0.00)) AS PaidAmount,
		0,
		''
	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			 
			FROM sFee.tFeeSetup FS1
			INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId 
			AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
			INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
			INNER JOIN sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id
			WHERE 
				(FS1.IsOptional=0)
				AND ((FS1.BatchId=@rOldBatchId) OR (@rOldBatchId=0))
				AND ((SA1.BatchId=@rOldBatchId) OR (@rOldBatchId=0))
				AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND (FM.Id IN (SELECT cast(item as nvarchar(20)) FROM  sCommon.fnsplit(@rOldFeeId,',')) OR @rOldFeeId='') 
			
			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 
			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
			INNER JOIN sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id
			WHERE
				(FS1.IsOptional=1)
				AND ((FS1.BatchId=@rOldBatchId) OR (@rOldBatchId=0))
				AND ((SA1.BatchId=@rOldBatchId) OR (@rOldBatchId=0))	
				AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND (FM.Id IN (SELECT cast(item as nvarchar(20)) FROM  sCommon.fnsplit(@rOldFeeId,',')) OR @rOldFeeId='') 
		) FS ON FS.AcademicId=SA.AcademicId
		LEFT JOIN sFee.tFeeAllocation FA ON FA.FeeSetupId=FS.Id AND FA.SourceId=SA.AcademicId
		INNER 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 		
			WHERE R.SourceTypeId = 2001
			AND R.IsObsolete = 0 
			AND R.BatchId = @rOldBatchId
			GROUP BY RD.FeeSetupId, R.SourceId
		) R ON R.FeeSetupId = FS.Id AND R.SourceId = SA.AcademicId
	WHERE	
		SA.OrgId = @rOrgId 
		AND SA.BatchId=@rOldBatchId
		AND ISNULL(R.PaidAmount,0.00) > 0
	GROUP BY SA.StudentId,SA.AcademicId,SA.Code,SA.Name,SA.RollNo,ISNULL(SA.ClassName, ''),ISNULL(SA.DivisionName, '')

	SELECT @lCount = COUNT(AutoId) FROM #TempOldPaidFeeImport
	
	BEGIN TRANSACTION
	
		WHILE (@lCount > 0)
		BEGIN
			DECLARE @lAcademicId bigint = NULL
			DECLARE @lStudentId bigint = NULL
			DECLARE @lClassId int = NULL
			DECLARE @lFeeSetupId int = NULL
			DECLARE @lPaidAmount decimal(12,2)
			DECLARE @lAdmissionCategoryId int

			SELECT @lStudentId = StudentId,@lPaidAmount=PaidAmount FROM #TempOldPaidFeeImport WHERE AutoId = @lCount
			SELECT @lAcademicId = Id, @lClassId=ClassId,@lAdmissionCategoryId=AdmissionCategoryId FROM sStudent.tAcademic SA 
			WHERE StudentId = @lStudentId AND BatchId = @rNewBatchId
			SELECT @lFeeSetupId = Id FROM sFee.tFeeSetup WHERE ClassId = @lClassId AND BatchId=@rNewBatchId AND FeeId = @rNewFeeId AND AdmissionCategoryId = @lAdmissionCategoryId
		
			IF (ISNULL(@lAcademicId,0) > 0 AND ISNULL(@lFeeSetupId, 0) > 0 AND ISNULL(@lClassId, 0) > 0)
			BEGIN
				IF OBJECT_ID('tempdb..#TempFeeSetup') IS NOT NULL DROP TABLE #TempFeeSetup

				SELECT
					FM.Id AS FeeId,
					FS.Id AS FeeSetupId,
					ISNULL(FS.IsOptional,0)AS IsOptional,
					ISNULL(FS.IsVariable,0)AS IsVariable,
					ISNULL(FS.Amount,0)AS Amount,
					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.NotApplicableAmount,0.00) AS NotApplicableAmount
				INTO #TempFeeSetup 
				FROM sFee.tFeeMaster FM
				INNER JOIN 
				(SELECT 
					FS1.FeeId,
					FS1.Id,
					ISNULL(FS1.IsOptional,0)AS IsOptional,
					ISNULL(FS1.IsVariable,0)AS IsVariable,
					ISNULL(FS1.Amount,0)AS Amount,
					ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
					ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
					FS1.BatchId,
					ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
					ISNULL(FS1.CollectionGroupId,0) AS CollectionGroupId,
					ISNULL(FS1.FeeDuration,'')  AS FeeDuration
				FROM sFee.tFeeSetup FS1
				WHERE FS1.ClassId=@lClassId AND FS1.AdmissionCategoryId=@lAdmissionCategoryId AND IsOptional=0
				AND FS1.Id = @lFeeSetupId
				AND FS1.BatchId = @rNewBatchId
					
				UNION ALL
				
				SELECT 
					FS1.FeeId,
					FS1.Id,
					ISNULL(FS1.IsOptional,0)AS IsOptional,
					ISNULL(FS1.IsVariable,0)AS IsVariable,
					ISNULL(FS1.Amount,0)AS Amount,
					ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
					ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
					FS1.BatchId,
					ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
					ISNULL(FS1.CollectionGroupId,0) AS CollectionGroupId ,
					ISNULL(FS1.FeeDuration,'') AS FeeDuration
				FROM sFee.tFeeSetup FS1
				INNER JOIN sFee.tFeeOptional FO ON FO.FeeSetupId=FS1.Id AND (FO.SourceId=@lAcademicId) AND(FO.SourceTypeId=2001)
				WHERE FS1.BatchId = @rNewBatchId
				AND FS1.Id = @lFeeSetupId
				AND	FS1.ClassId=@lClassId AND FS1.AdmissionCategoryId=@lAdmissionCategoryId AND IsOptional=1
				) FS ON FS.FeeId=FM.Id
				LEFT JOIN sFee.tFeeAllocation FA ON FA.FeeSetupId=FS.Id AND (FA.SourceId=@lAcademicId) AND(FA.SourceTypeId=2001)
				LEFT JOIN
				(
					SELECT ISNULL(SUM(RD.Amount),0) AS PaidAmount,RD.FeeSetupId
					FROM sFee.tReceipt R INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id 		
					WHERE						
					 R.SourceId= @lAcademicId
					AND (R.SourceTypeId = 2001)
					AND R.IsObsolete = 0 
					AND R.BatchId = @rNewBatchId
					AND FeeSetupId = @lFeeSetupId
					GROUP BY FeeSetupId
				) R ON R.FeeSetupId = FS.Id	

				DECLARE @lCount1 int = 0
				SET @lCount1  = (SELECT COUNT(1) FROM #TempFeeSetup)

				IF(@lCount1 > 0)
				BEGIN
					DECLARE @lPendingAmount decimal(12,2) = 0
					SET @lPendingAmount = (SELECT PendingAmount FROM #TempFeeSetup WHERE FeeSetupId = @lFeeSetupId)
					
					DECLARE @lIsReceiptGenerated bit = 0
				
					SET @lIsReceiptGenerated = (
					SELECT 1 FROM 
					sFee.tReceipt R
					INNER JOIN sFee.tReceiptDetail RD ON R.Id = RD.ReceiptId
					INNER JOIN sStudent.vStudentAcademic SA ON R.SourceId = SA.AcademicId AND SA.BatchId = @rNewBatchId
					INNER JOIN sFee.tFeeSetup FS ON FS.Id = RD.FeeSetupId AND FS.ClassId = SA.ClassId AND FS.BatchId = @rNewBatchId AND FS.FeeId = @rNewFeeId 
					LEFT JOIN sFee.tFeeAllocation FA ON FA.FeeSetupId=FS.Id AND FA.SourceId=SA.AcademicId
					WHERE (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(RD.Amount,0.00) = 0)
					AND R.SourceId = @lAcademicId
					)

					IF(@lPendingAmount < @lPaidAmount)
					BEGIN
						UPDATE #TempOldPaidFeeImport SET Status = 'Amount assigned in New Fee is less than Old Paid Fee', NewPaidAmount = @lPendingAmount WHERE AutoId = @lCount 
					END
					ELSE IF(@lIsReceiptGenerated = 1)
					BEGIN
						UPDATE #TempOldPaidFeeImport SET Status = 'Receipt Generated or Fee Already Paid in New Batch', NewPaidAmount = @lPendingAmount WHERE AutoId = @lCount
					END
					ELSE
					BEGIN
						UPDATE #TempOldPaidFeeImport SET Status = '', NewPaidAmount = @lPendingAmount WHERE AutoId = @lCount
					END
				END
			END
			ELSE
			BEGIN
				UPDATE #TempOldPaidFeeImport SET Status = 'Fee Setup not assigned in New Batch', NewPaidAmount = 0 WHERE AutoId = @lCount
			END
			SET @lCount = @lCount - 1
		END
	 
		SELECT * FROM #TempOldPaidFeeImport
	
	COMMIT TRANSACTION
	END TRY
	BEGIN CATCH 
		DROP TABLE #TempOldPaidFeeImport
		ROLLBACK TRANSACTION
		SELECT -1 AS Result, ERROR_LINE(), ERROR_MESSAGE()
	END CATCH	
END
GO
PRINT N'Altering Procedure [sFee].[pOnlineFeeAdd]...';


GO
ALTER PROCEDURE [sFee].[pOnlineFeeAdd]
	
			@rId bigint=0,
			@rSourceTypeId smallint,
			@rSourceId bigint,
			@rFeeAmount decimal(12, 2),
			@rPenaltyAmount decimal(12, 2),
			@rNetAmount decimal(12, 2),
			@rOnlineFeeDetailXml [nvarchar](max),
			@rOrgId int,
			@rReceiptBookId int

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

DECLARE @loDoc INT
EXEC sp_xml_preparedocument @loDoc OUTPUT, @rOnlineFeeDetailXml

BEGIN
		BEGIN TRY
		BEGIN TRANSACTION	
			
			DECLARE @lWrongFeeSetupOrReceiptBook int = 0
			IF NOT EXISTS (
					SELECT 1
					FROM sFee.tFeeSetup FS
					INNER JOIN (
						SELECT FeeSetupId
							,@rReceiptBookId AS ReceiptBookId
						FROM OPENXML(@loDoc, '/Table/OnlineFeeDetail', 1) WITH (FeeSetupId INT)
						) AS RD ON RD.FeeSetupId = FS.Id AND RD.ReceiptBookId = FS.ReceiptBookId
					)
			BEGIN
				SELECT @lWrongFeeSetupOrReceiptBook = 1
			END

			IF(@lWrongFeeSetupOrReceiptBook = 0)
			BEGIN
				DECLARE @lNextNumber BIGINT     
				EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sFee.tOnlineFee', 0, 1, 1,@outNextNumber = @lNextNumber output

				INSERT INTO sFee.tOnlineFee
				(
					Id,
					SourceTypeId,
					SourceId,
					PayDateTime,
					FeeAmount,
					PenaltyAmount,
					NetAmount,
					ReceiptBookId
				)
				VALUES
				(
					@lNextNumber,
					@rSourceTypeId,
					@rSourceId,
					sCommon.fGetDate(),
					@rFeeAmount,
					@rPenaltyAmount,
					@rNetAmount,
					@rReceiptBookId
				)	
		
				INSERT INTO sFee.tOnlineFeeDetail
				(
					OnlineFeeId,
					FeeSetupId,
					Amount
				)
				SELECT  	
					@lNextNumber,
					FeeSetupId,
					Amount
				FROM OPENXML (@loDoc, '/Table/OnlineFeeDetail', 1)
				WITH ( 
						FeeSetupId int,
						Amount decimal(12,2)
					  ) 

				SELECT @lNextNumber AS Result
			END
			ELSE 
			BEGIN
				SELECT -1 AS Result
			END

			EXEC sp_xml_removedocument @loDoc
	
		COMMIT TRANSACTION
	END TRY
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
END
GO
PRINT N'Altering Procedure [sFee].[pReceiptAddValidate]...';


GO
ALTER PROCEDURE [sFee].[pReceiptAddValidate] 
	@rAcademicId BIGINT
	,@rFeeSetupIds NVARCHAR(max) = ''
	,@rReceiptDetailXml [nvarchar] (max)
	,@rPayTypeId TINYINT = 0
	,@rPaymentTransactionId BIGINT = 0
	,@rReceiptBookId INT = 0
	,@rIsCreated INT OUTPUT

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	DECLARE @loDoc INT

	DECLARE @lWrongFeeSetupOrReceiptBook int = 0, @lAlreadyPaid int = 0, @lDuplicateReceipt int = 0

	EXEC sp_xml_preparedocument @loDoc OUTPUT,@rReceiptDetailXml

	CREATE TABLE #temptable (
		FeeId INT
		,Id INT
		,Amount DECIMAL(12, 2)
		,ReceiptBookId INT
		,AcademicId BIGINT
		)

	INSERT INTO #temptable (
		FeeId
		,Id
		,Amount
		,ReceiptBookId
		,AcademicId
		)
	SELECT FS1.FeeId
		,FS1.Id
		,
		--ISNULL(FS1.IsOptional,0)AS IsOptional,
		--ISNULL(FS1.IsVariable,0)AS IsVariable,
		ISNULL(FS1.Amount, 0) AS Amount
		,
		--ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
		--ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
		--FS1.BatchId,
		ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
		SA1.Id AS AcademicId
	--FM.Title AS FeeName			 
	FROM sFee.tFeeSetup FS1
	INNER JOIN sStudent.tAcademic SA1 ON SA1.ClassId = FS1.ClassId
		AND FS1.BatchId = SA1.BatchId
	INNER JOIN sStudent.tStudentMaster SM ON SA1.StudentId = SM.Id
		AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
	INNER JOIN sFee.tFeeMaster FM ON FM.Id = FS1.FeeId
	INNER JOIN sFee.tFeeHeadMaster FHM ON FM.FeeHeadId = FHM.Id
	WHERE (FS1.IsOptional = 0)
		AND SA1.Id = @rAcademicId
		AND (ISNULL(FS1.Id, 0) IN (SELECT cast(item AS INT) FROM sCommon.fnsplit(@rFeeSetupIds, ',')) OR @rFeeSetupIds = '')
	
	UNION ALL
	
	SELECT FS1.FeeId
		,FS1.Id
		,
		--ISNULL(FS1.IsOptional,0)AS IsOptional,
		--ISNULL(FS1.IsVariable,0)AS IsVariable,
		ISNULL(FS1.Amount, 0) AS Amount
		,
		--ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
		--ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
		--FS1.BatchId,
		ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
		SA1.Id AS AcademicId
	--FM.Title AS FeeName				
	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 sFee.tFeeHeadMaster FHM ON FM.FeeHeadId = FHM.Id
	INNER JOIN sStudent.tAcademic SA1 ON SA1.Id = FO.SourceId AND SA1.BatchId = FS1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
	WHERE (FS1.IsOptional = 1)
		AND SA1.Id = @rAcademicId
		AND (ISNULL(FS1.Id, 0) IN (SELECT cast(item AS INT) FROM sCommon.fnsplit(@rFeeSetupIds, ',')) OR @rFeeSetupIds = '')

	CREATE TABLE #temptable1 (
		PaidAmount DECIMAL(12, 2)
		,FeeSetupId INT
		,SourceId BIGINT
		)

	INSERT INTO #temptable1 (
		PaidAmount
		,FeeSetupId
		,SourceId
		)
	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 AND R.SourceTypeId = 2001
	INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id
	INNER JOIN sStudent.tAcademic SA1 ON SA1.Id = R.SourceId AND SA1.AdmissionCategoryId = FS.AdmissionCategoryId
	WHERE (R.SourceTypeId = 2001)
		AND R.SourceId = @rAcademicId
		AND (R.IsObsolete = 0)
		AND (ISNULL(FS.Id, 0) IN (SELECT cast(item AS INT) FROM sCommon.fnsplit(@rFeeSetupIds, ',')) OR @rFeeSetupIds = '')
	GROUP BY FeeSetupId,R.SourceId

	-- For Mantis 0032370 by Foram Start
	IF (@rAcademicId > 0)
	BEGIN
		IF NOT EXISTS (
				SELECT 1
				FROM #temptable FS
				INNER JOIN (
					SELECT FeeSetupId
						,Amount
						,@rReceiptBookId AS ReceiptBookId
					FROM OPENXML(@loDoc, '/Table/ReceiptDetail', 1) WITH (
							FeeSetupId INT
							,Amount DECIMAL(12, 2)
							)
					) AS RD ON RD.FeeSetupId = FS.Id AND RD.ReceiptBookId = FS.ReceiptBookId
				)
		BEGIN
			SELECT @lWrongFeeSetupOrReceiptBook = 1
		END
	END -- For Mantis 0032370 by Foram End
	
	
	IF EXISTS (
			SELECT 1
			FROM sStudent.tAcademic SA
			INNER JOIN #temptable
				--(
				--SELECT 
				--		FS1.FeeId,
				--		FS1.Id,
				--		--ISNULL(FS1.IsOptional,0)AS IsOptional,
				--		--ISNULL(FS1.IsVariable,0)AS IsVariable,
				--		ISNULL(FS1.Amount,0) AS Amount,
				--		--ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
				--		--ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
				--		--FS1.BatchId,
				--		--ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
				--		SA1.Id AS AcademicId
				--		--FM.Title AS FeeName			 
				--	FROM sFee.tFeeSetup FS1
				--	INNER JOIN sStudent.tAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId 
				--	--INNER JOIN sStudent.tStudentMaster SM ON SA1.StudentId = SM.Id
				--	AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId 
				--	--INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
				--	--INNER JOIN sFee.tFeeHeadMaster FHM ON FM.FeeHeadId = FHM.Id 
				--	WHERE 
				--	    (FS1.IsOptional=0)
				--	    AND SA1.Id = @rAcademicId				
				--		AND (ISNULL(FS1.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeSetupIds,','))OR @rFeeSetupIds='')
				--		UNION ALL
				--	SELECT 
				--		FS1.FeeId,
				--		FS1.Id,
				--		--ISNULL(FS1.IsOptional,0)AS IsOptional,
				--		--ISNULL(FS1.IsVariable,0)AS IsVariable,
				--		ISNULL(FS1.Amount,0)AS Amount,
				--		--ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
				--		--ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
				--		--FS1.BatchId,
				--		--ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
				--		SA1.Id AS AcademicId
				--		--FM.Title AS FeeName				
				--	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 sFee.tFeeHeadMaster FHM ON FM.FeeHeadId = FHM.Id 
				--		INNER JOIN sStudent.tAcademic SA1 ON SA1.Id=FO.SourceId 
				--		AND SA1.BatchId = FS1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				--WHERE
				--		  (FS1.IsOptional=1)
				--		   AND SA1.Id = @rAcademicId	
				--		AND (ISNULL(FS1.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeSetupIds,','))OR @rFeeSetupIds='') 
				--)
				FS ON FS.AcademicId = SA.Id
			LEFT JOIN sFee.tFeeAllocation FA ON FA.FeeSetupId = FS.Id AND FA.SourceId = SA.Id
			LEFT JOIN #temptable1
				--(
				--	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 AND R.SourceTypeId = 2001
				--		INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id
				--		INNER JOIN sStudent.tAcademic SA1 ON SA1.Id=R.SourceId AND SA1.AdmissionCategoryId = FS.AdmissionCategoryId	 
				--	WHERE	
				--	(R.SourceTypeId = 2001)
				--		 AND R.SourceId = @rAcademicId				
				--		AND (R.IsObsolete = 0) 
				--		AND (ISNULL(FS.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeSetupIds,','))OR @rFeeSetupIds='')
				--		GROUP BY FeeSetupId,R.SourceId	
				--)
				R ON R.FeeSetupId = FS.Id AND SA.Id = R.SourceId
			LEFT JOIN (
				SELECT FeeSetupId
					,Amount
				FROM OPENXML(@loDoc, '/Table/ReceiptDetail', 1) WITH (
						FeeSetupId INT
						,Amount DECIMAL(12, 2)
						)
				) AS RD ON RD.FeeSetupId = FS.Id
			WHERE SA.Id = @rAcademicId
				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) - RD.Amount < 0)
			)
	BEGIN
		SELECT @lAlreadyPaid = 1
	END
	
	--Start for mantis 0031290 By Foram
	IF (@rPayTypeId = 8 AND @rPaymentTransactionId > 0)
	BEGIN
		IF EXISTS (
				SELECT 1
				FROM sFee.tReceipt R
				INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id
					AND R.SourceTypeId = 2001
				INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id
				INNER JOIN sStudent.tAcademic SA1 ON SA1.Id = R.SourceId
					AND SA1.AdmissionCategoryId = FS.AdmissionCategoryId
				WHERE (R.SourceTypeId = 2001)
					AND R.SourceId = @rAcademicId
					AND (R.IsObsolete = 0)
					AND (
						ISNULL(FS.Id, 0) IN (
							SELECT cast(item AS INT)
							FROM sCommon.fnsplit(@rFeeSetupIds, ',')
							)
						OR @rFeeSetupIds = ''
						)
					AND R.PaymentTransactionId = @rPaymentTransactionId
					AND R.PayTypeId = 8
				)
		BEGIN
			SELECT @lDuplicateReceipt = 1
		END
	END
			--end for mantis 0031290 By Foram
	
	--@lWrongFeeSetupOrReceiptBook			-1
	--@lAlreadyPaid,@lDuplicateReceipt		1

	IF(@lWrongFeeSetupOrReceiptBook = 1)
	BEGIN
		SELECT @rIsCreated = -1
	END
	ELSE IF(@lAlreadyPaid = 1 OR @lDuplicateReceipt = 1)
	BEGIN
		SELECT @rIsCreated = 1
	END
	ELSE
	BEGIN
		SELECT @rIsCreated = 0	
	END

	EXEC sp_xml_removedocument @loDoc
END
GO
PRINT N'Altering Procedure [sFee].[pRptFeeReceiptDetailsGet]...';


GO

ALTER PROCEDURE [sFee].[pRptFeeReceiptDetailsGet]
						
			@rReportId int=0,
			@rReceiptId bigint = 0,
			@rOrgGroupId int = 0,
			@rReceiptBookId int = 0,
			@rFromReceiptNo int=0,
			@rToReceiptNo int=0,
			@rOrgId int = 0,
			@rBatchId int = 0,
			@rReceiptDate Date='',
			@rClassId int = 0,
			@rOrgIds nvarchar(max) = '',
			@rReceiptPrintGroupId nvarchar(100)='',
			@rDivisionId int = 0,
			@rAdmissionCategoryId int = 0
			

	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	
BEGIN 	
	
	DECLARE @lOrgGroupId int = 0
	DECLARE @lAmountInWord nvarchar(500) = ''
	DECLARE @lReceiptAmount Decimal(12,2) = 0.0
	DECLARE @lCurrencyCode nvarchar(20) = ''
	DECLARE @lCurrencyTitle nvarchar(100) = ''
	Declare @lIDConfigValue nvarchar(50)='',@lOrgGroup_Id int=0
	Select @lOrgGroup_Id = OrgGroupId From  sSetup.tOrganizationMaster Where Id = @rOrgId
	 
	SELECT @lIDConfigValue =ItemValue From sConfig.tConfigurationSetup
	WHERE ConfigurationId = 236 AND SourceId = @rOrgGroupId
	
	IF(@rOrgGroupId=0)
	BEGIN
		SELECT @lOrgGroupId = OrgGroupId ,@lReceiptAmount = R.ReceiptAmount  FROM sFee.tReceipt R 
		INNER JOIN sSetup.tOrgGroupBatchMaster OB ON R.OrgGroupBatchId = OB.Id 
		WHERE R.Id = @rReceiptId

		SELECT  @lAmountInWord = sFinanceCommon.fNumberToWordsWithDecimal(ISNULL(@lReceiptAmount,0.00),1,2,@lOrgGroupId)
		SELECT  @lCurrencyCode = [sFinanceCommon].[fDefaultCurrencyCodeGet](@lOrgGroupId) 
		SELECT  @lCurrencyTitle = [sFinanceCommon].[fDefaultCurrencyTitleGet](@lOrgGroupId) 
	END
	ELSE
	BEGIN
		SELECT  @lCurrencyCode = [sFinanceCommon].[fDefaultCurrencyCodeGet](@rOrgGroupId) 
	END

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

	SELECT 
			FRD.ReceiptId,
			FR.ReceiptNumber,
			FR.ReceiptDate,			
			SA.AcademicId,
			--SA.FirstName+' '+SA.MiddleName+' '+SA.LastName AS Name,
			SA.Name AS Name,
			SA.Code,
			SA.RollNo,
			SA.ClassId,
			SA.DivisionId,
			SA.ClassName,
			SA.DivisionName,
			SA.ClassName+' - '+SA.DivisionName AS ClassDivision,
			FM.FeeHeadId,
			FHM.Title AS FeeHead,
			FM.Id AS FeeId,
			FM.Title AS FeeName,
			FRD.Amount AS PaidAmount,
			PTM.Id AS PayTypeId,
			PTM.Title AS PayType,			
			--changes by Jash on 06/11/2020--%
			CASE WHEN ISNULL(FR.ChequeNo,'') != '' THEN FR.ChequeNo ELSE CONVERT(nvarchar(20),ISNULL(FR.PaymentTransactionId,''))  END AS ChequeNo,
			--CASE WHEN ISNULL(FR.ChequeNo,'') != '' THEN FR.ChequeNo
			--	WHEN ISNULL(PT.BankTransactionId,'') = '' THEN  CONVERT(nvarchar(20),FR.PaymentTransactionId)
			--	ELSE CONVERT(nvarchar(20),FR.PaymentTransactionId) +' - '+ CONVERT(nvarchar(20),PT.BankTransactionId) END AS ChequeNo,
			--%ISNULL(FR.ChequeNo,'') AS ChequeNo,
			ISNULL(FR.BankName,'') AS BankName,
			ISNULL(RBM.Address1,'') AS Address1,
			ISNULL(RBM.Address2,'') AS Address2,
			ISNULL(RBM.FullTitle,'') AS FullTitle,
			ISNULL(FR.TotalReceiptAmount,0.00) AS TotalReceiptAmount,
			ISNULL(FR.ReceiptAmount,0.00) AS ReceiptAmount,					
			(CASE WHEN @rOrgGroupId = 0 -- For Single Receipt
					THEN '' 
				  WHEN @rOrgGroupId != 0 -- For Bulk Receipt
					THEN sFinanceCommon.fNumberToWordsWithDecimal(ISNULL(FR.ReceiptAmount,0.00),1,2,@rOrgGroupId)
			END) AS ReceiptAmountInWords,			
			ISNULL(FR.DiscountAmount,0.00) AS DiscountAmount,
			FR.Remark,
			(CASE WHEN  ISNULL(FR.PaymentTransactionId,0) > 0 
			  THEN -- Navrachana
				'Online Generated'
				ELSE ISNULL(U.DisplayTitle,'') END) AS UserName,
			--ISNULL(U.DisplayTitle,'') AS UserName,
			OM.OrgLogo,
			RBM.Remark1,
			RBM.Remark2,			 
			ISNULL(RBM.IsOnPrePrinted,0) AS IsOnPrePrinted,
			ISNULL(RBM.IsSupressLogo,0) AS IsSupressLogo,
			ISNULL(RBM.IsDisplaySchoolName,0) AS IsDisplaySchoolName,
			RBM.ReportId,
			OM.Title AS OrganizationName,
			--(CASE  WHEN (RBM.ReportId = 20775 OR RBM.ReportId = 20777 OR RBM.ReportId = 20874 OR RBM.ReportId =20427 OR RBM.ReportId =20890 OR RBM.ReportId =20901 OR RBM.ReportId =20902) AND ISNULL(RBM.IsMonthDetailOnly,0) = 0 THEN 
			--	[sFee].[fFeeHeadMonthDetailGet](FR.ID,FHM.Id) -- Fee name in detail	 			  
			(CASE WHEN  RBM.ReportId = 20576
			      THEN -- HM patel report
				  [sFee].[fReceiptMonthDetailGet](FR.ID,0)
			      WHEN RBM.ReportId = 30457 
			      THEN
				  [sFee].[fReceiptMonthDetailGet](FR.ID,1)		
			      WHEN ISNULL(RBM.IsMonthDetailOnly,0) = 1  AND ISNULL(RBM.IsFeeInvoiceHeadwise,0) = 1
			      THEN				
				  [sFee].[fFeeHeadMonthNameGet](FR.ID,FHM.Id) -- Head wise Month name in detail
				  WHEN ISNULL(RBM.IsMonthDetailOnly,0) = 1  AND ISNULL(RBM.IsFeeInvoiceHeadwise,0) = 0
			      THEN				
				  [sFee].[fFeeMonthNameGet](FR.ID,FM.Id) -- Fee wise Month name in detail
			ELSE '' END) 
			AS MonthDetail,    			
			(CASE WHEN ISNULL(RBM.IsFeeInvoiceHeadwise,0) = 1
			      THEN				
					 Stuff((SELECT  N', ' +  FS1.FeeDuration FROM 
					sFee.tReceipt FR1				
					INNER JOIN sFee.tReceiptDetail FRD1	ON FR1.Id=FRD1.ReceiptId AND FR1.SourceTypeId=2001				
					INNER JOIN sFee.tFeeSetup FS1 ON FRD1.FeeSetupId = FS1.Id
					INNER JOIN sFee.tFeeMaster FM1 ON FS1.FeeId=FM1.Id						
					INNER JOIN sFee.tFeeHeadMaster FHM1 ON FHM1.Id=FM1.FeeHeadId 
					INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId = FR1.SourceId
					Where FM1.FeeHeadId = FM.FeeHeadId AND FS.ClassId = FS1.ClassId AND FR1.Id = @rReceiptId
					--Where FM1.Id = FM.Id AND FS.ClassId = FS1.ClassId AND FR1.Id = @rReceiptId
					AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')
					Order By FS1.StartDate
					FOR XML PATH(''),TYPE).value('text()[1]','nvarchar(max)'),1,2,N'' )    -- Fee Head wise Fee Duration
				  WHEN ISNULL(RBM.IsFeeInvoiceHeadwise,0) = 0
			      THEN
					FS.FeeDuration -- Fee wise Fee Duration
				 ELSE '' END) AS FeeDuration,			
			--Stuff((SELECT  N', ' +  FS1.FeeDuration FROM 
			--sFee.tReceipt FR1				
			--INNER JOIN sFee.tReceiptDetail FRD1	ON FR1.Id=FRD1.ReceiptId AND FR1.SourceTypeId=2001				
			--INNER JOIN sFee.tFeeSetup FS1 ON FRD1.FeeSetupId = FS1.Id
			--INNER JOIN sFee.tFeeMaster FM1 ON FS1.FeeId=FM1.Id						
			--INNER JOIN sFee.tFeeHeadMaster FHM1 ON FHM1.Id=FM1.FeeHeadId 
			--INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId = FR1.SourceId
			----Where FM1.FeeHeadId = FM.FeeHeadId AND FS.ClassId = FS1.ClassId AND FR1.Id = @rReceiptId
			--Where FM1.Id = FM.Id AND FS.ClassId = FS1.ClassId AND FR1.Id = @rReceiptId
			--AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')
			-- Order By FS.StartDate
			--FOR XML PATH(''),TYPE).value('text()[1]','nvarchar(max)'),1,2,N'' ) AS FeeDuration,			
			DM.Title AS DepartmentName,
			FM.OrderIndex AS FeeOrderIndex,
			FHM.OrderIndex AS FeeHeadOrderIndex,
			FR.IsObsolete AS IsCancelReceipt,
			@lCurrencyCode AS CurrencyCode,
			@lCurrencyTitle AS CurrencyTitle,
			BM.Title AS Batch,
			FR.ChequeDate AS ChequeDate,
			ISNULL(RBM.IsMonthDetailOnly,0) AS IsMonthDetailOnly,
	        ISNULL(RBM.IsFeeInvoiceHeadwise,0) AS IsFeeInvoiceHeadwise,
	        ISNULL(RBM.GroupTitle,'') AS GroupTitle,
	        ISNULL(RBM.IsSuppressFeeDetail,0) AS IsSuppressFeeDetail,
	        ISNULL(CGM.Title,'') AS CollectionGroupName,
	        ISNULL(FI.InvoiceNumber,0) AS InvoiceNumber,
	        SA.SUID,
	        CASE
				 WHEN RBM.IsOnPrePrinted=1       
				 THEN 2
				 ELSE  ISNULL(RBM.HeaderDisplayId,1)
				END AS HeaderDisplayId,
	        RBM.ReceiptBookHeader,
	        RBM.ServiceTaxPercentage,
	        ISNULL(FR.AmountAfterDiscount,0) AS AmountAfterDiscount,
	        (CASE WHEN  FR.CGSTPercentage IS NULL THEN RBM.CGSTPercentage ELSE FR.CGSTPercentage END) AS CGSTPercentage,
	        (CASE WHEN  FR.SGSTPercentage IS NULL THEN RBM.SGSTPercentage ELSE FR.SGSTPercentage END) AS SGSTPercentage,
	        ISNULL(FR.CGSTAmount,0) AS CGSTAmount,
	        ISNULL(FR.SGSTAmount,0) AS SGSTAmount,
			ISNULL(OOM.GSTINNo,'') AS GSTINNo,
	        ISNULL(OOM.HSNSACCode,'') AS HSNSACCode,
	        @lIDConfigValue AS ItemValue ,
	        SF.FatherName,
	        SF.MotherName,
	        ISNULL(FA.DiscountAmount,0) AS ExemptionAmount,
			ISNULL(FA.Remark,'') AS ExemptionRemark,
			EI.EmployeeSign,
			ISNULL(SC.PresentCity,'') AS PresentCity,
			(ISNULL((CASE WHEN SC.PresentStreetOne IS NOT NULL AND SC.PresentStreetOne!='' THEN ''+ SC.PresentStreetOne END),'')+
			ISNULL((CASE WHEN SC.PresentStreetTwo IS NOT NULL AND SC.PresentStreetTwo!=''  THEN ', '+ SC.PresentStreetTwo END),'')+
			ISNULL((CASE WHEN SC.PresentStreetThree IS NOT NULL AND SC.PresentStreetThree!=''  THEN ', '+ SC.PresentStreetThree END),'')+
			ISNULL((CASE WHEN SC.PresentCity IS NOT NULL AND SC.PresentCity!=''  THEN ', ' + SC.PresentCity  END),'')+
			ISNULL((CASE WHEN SC.PresentState IS NOT NULL AND SC.PresentState!=''  THEN  ', '+ SC.PresentState END),'')+
			ISNULL((CASE WHEN SC.PresentZipCode IS NOT NULL AND SC.PresentZipCode!=''  THEN  ', '+ SC.PresentZipCode  END),''))
			 AS PresentAdress,
			--ISNULL(SC.PresentStreetOne +','+ SC.PresentStreetTwo +','+ SC.PresentStreetThree +','+ SC.PresentCity +','+ SC.PresentState +'-'+ SC.PresentZipCode ,'') AS PresentAdress,
			SC.ParentContactNo,			
			ISNULL(RBM.IsDisplayPendingFeeAmount,0) AS IsDisplayPendingFeeAmount,
			CASE WHEN @rOrgGroupId = 1134 OR @rOrgGroupId = 1742 THEN
			(CASE WHEN  ISNULL(RBM.IsDisplayPendingFeeAmount,0) = 0 THEN 0 ELSE ISNULL([sFee].[fPendingFeeAmountReceiptBookwiseGet](FR.SourceId,RBM.Id),0) END)
			ELSE 
			(CASE WHEN  ISNULL(RBM.IsDisplayPendingFeeAmount,0) = 0 THEN 0 ELSE ISNULL([sFee].[fPendingFeeAmountReceiptBookwiseGet](FR.SourceId,0),0) END) END AS PendingFeeAmount,
			SA.FirstName,
			SA.LastName,
			ISNULL([sFee].[fFeeAmountSumGet](FR.SourceId),0) AS FeeAmount,
			ISNULL([sFee].[fFeeReceiptDiscountSumGet](FR.SourceId),0) AS ExemptionAmountSum,
			[sFee].[fTransportBusRouteGet](SA.StudentId,FR.OrgGroupBatchId) AS TransportBusRoute,
			ISNULL(RBM.BankAccountNumber,'') AS BankAccountNumber,
			ISNULL(FHM.Number,0) AS FeeHeadNumber,
			ISNULL(FM.Number,0) AS FeeNumber,
			ISNULL(RBM.DigitalSignature,0x) AS DigitalSignature,
			ISNULL(FR.CancelStatusRemark,'') AS CancelStatusRemark,
			FS.Amount AS FeeSetupAmount,
			FR.CreatedDateTime ,
			ISNULL(FR.PaymentTransactionId,0) As PaymentTransactionId,
			SA.MiddleName,
			CONVERT(char(5),FR.CreatedDateTime,108) AS CreatedTime,
			--by megha - 0026430

			(CASE WHEN ISNULL(FA.VariableAmount,0) > 0 Then FA.VariableAmount 
			      When ISNULL(FS.Amount,0) > 0 Then FS.Amount END) + ISNULL(FA.AdditionalAmount,0) - ISNULL(FA.DiscountAmount,0) - ISNULL(FA.NotApplicableAmount,0) As TotalPayableAmount,
			OGM.Title AS OrgGroupTitle,
			 NID.CollectionGroupName AS NextInstallmentName, --Mantis End- 0031305
			ISNULL(HM.Title,'') AS House,	--add for mantis: 32658
			NID.StartDate AS NextInstallmentStartDate, --Mantis -  Start 32760
			NID.EndDate AS NextInstallmentEndDate,
			NID.PendingAmount AS NextInstallmentAmount,   --Mantis -  End 32760			
			ISNULL([sFee].[fFeeActualAmountSumGet](FR.SourceId),0) AS FeeActualAmount,	-- MantisId : 0032658
			ISNULL(SC.StudentContactNo,'') AS StudentContactNo, -- MantisId : 0032895
			--mantis Start - 0033973
			ISNULL(SC.PermanentStreetOne,'')AS PermanentStreetOne,
			ISNULL(SC.PermanentStreetTwo,'')AS PermanentStreetTwo,
			ISNULL(SC.PermanentStreetThree,'')AS PermanentStreetThree
			--mantis Start - 0033973


 	FROM 
	
			sFee.tReceipt FR				
			INNER JOIN sFee.tReceiptDetail FRD ON FR.Id=FRD.ReceiptId AND FR.SourceTypeId=2001				
			INNER JOIN sFee.tFeeSetup FS ON FRD.FeeSetupId = FS.Id				
			INNER JOIN sFee.tFeeMaster FM ON FS.FeeId=FM.Id						
			INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FM.FeeHeadId
			INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId = FR.SourceId
			INNER JOIN sStudent.tStudentCommunication SC ON SC.StudentId = SA.StudentId
			INNER JOIn sFinanceCommon.tPayTypeMaster PTM ON PTM.Id=FR.PayTypeId
			LEFT JOIN sFee.tFeeAllocation FA ON FA.FeeSetupId=FS.Id AND FA.SourceId=SA.AcademicId
			INNER JOIN sFee.tReceiptBookMaster RBM  ON RBM.Id=FR.ReceiptBookId
			LEFT JOIN sSecurity.tUser U ON U.Id=FR.CreatedUserId
			INNER JOIN sSetup.tDepartmentMaster DM ON SA.DepartmentId =DM.Id
			LEFT JOIN sSetup.tOrganizationMaster OM ON OM.Id=DM.OrgId
			LEFT JOIN sSetup.tOrganizationOtherDetail OOM ON OM.Id=OOM.OrgId	
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = FR.BatchId 
			LEFT JOIN sFee.tCollectionGroupMaster CGM ON CGM.Id=FR.CollectionGroupId 
			LEFT JOIN sFee.tFeeInvoice FI ON FI.Id=FR.FeeInvoiceId
			LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId = SA.StudentId
			LEFT JOIN sHrm.tEmployeeImages EI ON EI.EmployeeId = U.SourceId AND U.SourceTypeId=95
			LEFT JOIN sOp.tPaymentTransaction PT ON PT.Id = FR.PaymentTransactionId
			INNER JOIN sSetup.tOrgGroupMaster OGM ON OGM.Id = OM.OrgGroupId  -- Mantis : 0029314
			LEFT JOIN (SELECT * FROM [sFee].[fNextInstallmentDetailsGet](@rReceiptBookId, @rReceiptId)) NID -- Mantis Start - 0031305
			ON NID.SourceId = FR.SourceId AND NID.SourceTypeId = FR.SourcetypeId -- Mantis End - 0031305
			LEFT JOIN sStudent.tStudentOther AS SO ON SO.StudentId = SA.StudentId
			LEFT JOIN sActivity.tHouseMaster HM ON HM.Id=SO.HouseId		--add for mantis: 32658
	WHERE 
			((FR.Id=@rReceiptId) OR (@rReceiptId = 0))
			AND ((RBM.OrgGroupId = @rOrgGroupId) OR (@rOrgGroupId = 0))
			AND ((FR.ReceiptBookId = @rReceiptBookId) OR (@rReceiptBookId = 0))
			AND ((FR.ReceiptNumber >= @rFromReceiptNo) OR (@rFromReceiptNo = 0))
			AND ((FR.ReceiptNumber <= @rToReceiptNo) OR (@rToReceiptNo = 0))
			AND ((FR.BatchId = @rBatchId) OR (@rBatchId = 0))
			AND ((BM.OrgId = @rOrgId) OR (@rOrgId = 0))
			AND ((FR.ReceiptDate = @rReceiptDate) OR (ISNULL(@rReceiptDate,'') = ''))
			AND ((SA.ClassId = @rClassId) OR (@rClassId = 0))
			AND ((SA.DivisionId = @rDivisionId) OR (@rDivisionId = 0))
			AND (ISNULL(SA.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')			
			AND ((ISNULL(FR.ReceiptPrintGroupId,'')=@rReceiptPrintGroupId) OR (ISNULL(@rReceiptPrintGroupId,'') = ''))
			AND ((FS.AdmissionCategoryId = @rAdmissionCategoryId) OR (@rAdmissionCategoryId = 0) )
    ORDER BY 
            FS.StartDate,FHM.OrderIndex,FM.OrderIndex ASC 
END

--BEGIN
--SELECT
-- CAST(0 AS bigint) AS ReceiptId,
-- 0	AS ReceiptNumber,
-- CAST('' AS date) AS ReceiptDate,
-- CAST(0 AS bigint) AS AcademicId,
-- ''	AS Name,
--''	AS Code,
-- 0	AS RollNo,
--0	AS ClassId,
--0	AS DivisionId,
--''	AS ClassName,
--''	AS DivisionName,
--''	AS ClassDivision,
--0	AS FeeHeadId,
--''	AS FeeHead,
--0	AS FeeId,
--''	AS FeeName,
--CAST(0.0 AS decimal(12,2)) AS PaidAmount,
--CAST(0 AS tinyint) AS PayTypeId,
--''	AS PayType,
--''	AS ChequeNo,	
--''	AS BankName,
--''	AS Address1,
--''	AS Address2,
--''	AS FullTitle,
--CAST(0.0 AS decimal(12,2)) AS TotalReceiptAmount,
--CAST(0.0 AS decimal(12,2)) AS ReceiptAmount,					
--''	AS ReceiptAmountInWords,		
--CAST(0.0 AS decimal(12,2)) AS DiscountAmount,
--''	AS Remark,
--''	AS UserName,		
--0x  AS OrgLogo,
--''	AS Remark1,
--''	AS Remark2,			 
--CAST(0 AS bit) AS IsOnPrePrinted,
--CAST(0 AS bit) AS IsSupressLogo,
--CAST(0 AS bit) AS IsDisplaySchoolName,
--0	AS ReportId,
--''	AS OrganizationName,		  
--''	AS MonthDetail,    			
--''	AS FeeDuration,		
--''	AS DepartmentName,
-- 0	AS FeeOrderIndex,
--CAST(0 AS smallint)	AS FeeHeadOrderIndex,
--CAST(0 AS bit) AS IsCancelReceipt,
--''	AS CurrencyCode,
--''	AS CurrencyTitle,
--''	AS Batch,
--CAST('' AS date) AS ChequeDate,
--CAST(0 AS bit) AS IsMonthDetailOnly,
--CAST(0 AS bit) AS IsFeeInvoiceHeadwise,
--''	AS GroupTitle,
--CAST(0 AS bit) AS IsSuppressFeeDetail,
--''	AS CollectionGroupName,
--0	AS InvoiceNumber,
--''	AS SUID,
--CAST(0 AS tinyint) AS HeaderDisplayId,
--0x  AS ReceiptBookHeader,
--CAST(0.0 AS decimal(6,2)) AS ServiceTaxPercentage,
--CAST(0.0 AS decimal(12,2)) AS AmountAfterDiscount,
--CAST(0.0 AS decimal(5,2)) AS CGSTPercentage,
--CAST(0.0 AS decimal(5,2)) AS SGSTPercentage,
--CAST(0.0 AS decimal(12,2)) AS CGSTAmount,
--CAST(0.0 AS decimal(12,2))	AS SGSTAmount,
--''	AS GSTINNo,
--''	AS HSNSACCode,
--''	AS ItemValue ,
--''	AS FatherName,
--''	AS MotherName,
--CAST(0.0 AS decimal(12,2)) AS ExemptionAmount,
--''	AS ExemptionRemark,
--0x AS EmployeeSign,
--''	AS PresentCity,
--''	AS PresentAdress,
--''	AS ParentContactNo,	
--CAST(0 AS bit) AS IsDisplayPendingFeeAmount,
--CAST(0.0 AS decimal(12,0)) AS PendingFeeAmount,
--''	AS FirstName,
--''	AS LastName,
--CAST(0.0 AS decimal(12,0))	AS FeeAmount,
--CAST(0.0 AS decimal(12,0)) AS ExemptionAmountSum,
--''	AS TransportBusRoute,
--''	AS BankAccountNumber,
--0	AS FeeHeadNumber,
--0	AS FeeNumber,
--0x AS DigitalSignature,
--''	AS CancelStatusRemark,
--CAST(0.0 AS decimal(12,2))	AS FeeSetupAmount,
--''	AS CreatedDateTime ,
--CAST(0 AS bigint)	AS PaymentTransactionId,
--''	AS MiddleName,
--'' AS CreatedTime,
-- 0 AS TotalPayableAmount,
-- '' AS OrgGroupTitle,
-- '' AS NextInstallmentName,
-- '' AS House,
-- CAST('' AS date) AS NextInstallmentStartDate,
-- CAST('' AS date) NextInstallmentEndDate,
-- CAST(0.0 AS decimal(12,2)) AS NextInstallmentAmount,
-- CAST(0.0 AS decimal(12,2)) AS FeeActualAmount,
-- '' AS StudentContactNo,
-- '' AS PermanentStreetOne,
-- '' AS PermanentStreetTwo,
-- '' AS PermanentStreetThree

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


GO
ALTER PROCEDURE [sFee].[pRptFeeReceiptListGet]  
  @rReportId int=0,  
  @rReceiptBookId int=0,  
  @rAdmissionCategoryId int=0,  
  @rClassId int=0,  
  @rDivisionId int=0,  
  @rFromDate date='',  
  @rToDate date='',  
  @rFromReceiptNo int=0,  
  @rToReceiptNo int=0,  
  @rBatchId int,  
  @rUserId bigint=0,  
  @rBuilder1 nvarchar(max)=0,  
  @rBuilder2 nvarchar(max)=0,  
  @rIsDetail bit=0,  
  @rIsCancel bit=0,  
  @rOrgId int,  
  @rOrgGroupBatchId int,  
  @rStatusId int=0,  
  @rPaytypeId int=0,  
  @rCommonBatch nvarchar(100)='',  
  @rDepartmentId int=0,  
  @rFromRollNo int=0,  
     @rToRollNo int=0,  
     @rCode nvarchar(20),  
     @rIsFilter bit=0,  
     @rIsHeader bit=0,  
     @rCreatedUserName nvarchar(100)='',  
     @rFeeHeadId nvarchar(max) = '',  
     @rIsDisplayOrgGroup bit=0,  
     @rIsDiscount bit = 0,  
     @rFeeId nvarchar(max) = '',  
     @rFilterId int=0,  
     @rCustomGroupId smallint = 0,  
     @rOrgGroupId int=0,  
     @rFeeStatusId int=0,  
     @rFromChequeDate date='',      
  @rToChequeDate date='',      
     @rBankName nvarchar(100)='',  
     @rOrgIds nvarchar(max) = '',  
     @rBankNames nvarchar(max) = '',  
  
  @rFromChequeClearDate Date = '',  
  @rToChequeClearDate Date = '' ,
  @rClassStatusId int=0 ,
  @rPayTypeIds nvarchar(max) = '',
  @rUserAcessUserId bigint = 0,
  @rReceiptBookIds nvarchar(max) = ''
 WITH EXECUTE AS CALLER  
AS  
SET NOCOUNT ON  
      
BEGIN   
   
  BEGIN      
  SET @rBankName = sCommon.fSearchStringGet(@rBankName)      
    END   
	--OR @rReportId=20547
  IF(@rReportId=10138 OR @rReportId=20456)
	BEGIN
		SELECT   
		  @rBuilder1 AS Builder1,  
		  @rBuilder2 AS Builder2,  
		  @rIsDetail AS IsDetail,  
		  (CASE WHEN @rReportId IN (20456,30804) THEN  R.IsObsolete ELSE @rIsCancel END) AS IsCancel,  
		  --@rIsCancel AS IsCancel,  
		  @rIsFilter As IsFilter,  
		  @rIsHeader As IsHeader,  
		  @rIsDisplayOrgGroup AS IsDisplayOrgGroup,  
		  R.Id AS ReceiptId,  
		  R.ReceiptNumber,  
		  SA.ClassId,  
		  --SA.ClassName,  
		  SA.DivisionId,  
		  --SA.DivisionName,  
		  SA.ClassName+' - '+SA.DivisionName AS ClassDivision,  
		  SA.RollNo,  
		  SA.Code,  
		  SA.Name,  
		  ISNULL(PTM.Title,'') AS PayType,  
		  --ISNULL(R.ChequeNo,'') AS ChequeNo,  
		  CASE WHEN ISNULL(R.ChequeNo,'') != '' THEN R.ChequeNo ELSE CONVERT(nvarchar(20),R.PaymentTransactionId) END AS ChequeNo,
		  ISNULL(R.BankName,'') AS BankName,  
		  R.ReceiptAmount,  
		  --R.ReceiptDate,  
		  CASE  WHEN @rReportId = 30611 AND R.ChequeClearDate IS NOT NULL THEN R.ChequeClearDate ELSE R.ReceiptDate END AS ReceiptDate,  
		  R.CreatedUserId,  
		  ISNULL(U.LoginTitle,'') AS UserName,  
		  ISNULL(RBM.Title,'') AS ReceiptBookTitle,  
		  ISNULL(RBM.BankName,'') AS ReceiptBookBank,  
		  ISNULL(RBM.BankAccountNumber,'') AS BankAccountNumber,  
		  ISNULL(R.ReceiptBookId,'0') As ReceiptBookId,  
		  ISNULL((CASE @rReportId WHEN 20461 THEN [sFee].[fReceiptFeeDetailGet](R.Id)  
		   ELSE '' END),'') AS FeeDetail,  
		   R.Remark,  
		   R.DiscountAmount,  
		   ISNULL(RBM.OrderIndex,0) AS ReceiptBookOrderIndex,  
		   SA.OrgId,  
		   SA.OrganizationName,  
		   ISNULL(R.AmountAfterDiscount,0) AS AmountAfterDiscount,  
		   ISNULL(R.CGSTPercentage,0) AS CGSTPercentage,  
		   ISNULL(R.SGSTPercentage,0) AS SGSTPercentage,  
		   ISNULL(R.CGSTAmount,0) AS CGSTAmount,  
		   ISNULL(R.SGSTAmount,0) AS SGSTAmount,  
		   @rCustomGroupId AS CustomGroupId,  
		   SA.OrgGroupBatchId AS BatchId,  
		   SA.BatchName,  
		   R.ChequeDate,  
		   R.ChequeClearDate ,
		   SA.GenderId,
		  0 AS FeeId,
		  '' AS FeeCode,
		  '' AS FeeTitle,
		   0 AS FeeOrderIndex,
		   R.CancelStatusRemark AS CancelRemark,
		   0 AS FeeHeadId,
		   '' AS FeeHeadName
		  FROM   
		   sFee.tReceipt R  
		  --INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id   
		  --INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id  
		  --INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id  
    
		  INNER JOIN sStudent.vStudentAcademic SA  
		   ON SA.AcademicId=R.SourceId AND ((SA.OrgId=@rOrgId) OR (@rOrgId=0)) 

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

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


		  LEFT JOIN sSecurity.tUser U  
		   ON U.Id=R.CreatedUserId  
		 LEFT JOIN sHostel.tAssignRoom AR ON  AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003 AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  AND ((AR.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0) AND (SA.OrgGroupBatchId = AR.OrgGroupBatchId))   
			LEFT JOIN  
		 (SELECT AT.SourceId,B.OrgGroupBatchId FROM sTransport.tAssignRoute AT   
			INNER JOIN sTransport.tBusRouteDestinationMaster BM ON BM.Id=AT.PickupDestinationId   
			INNER JOIN sTransport.tBusRouteMaster B ON B.Id=BM.BusRouteId AND  AT.SourceTypeId=2003 AND ((B.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))) RT  
			ON RT.SourceId = SA.StudentId   
			AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))    
			AND (SA.OrgGroupBatchId = RT.OrgGroupBatchId)  
		WHERE   
		 R.SourceTypeId = 2001  
		 AND ((SA.AdmissionCategoryId = @rAdmissionCategoryId) OR (@rAdmissionCategoryId = 0))  
		 AND ((SA.ClassId = @rClassId) OR (@rClassId = 0))  
		 AND ((SA.DivisionId = @rDivisionId) OR (@rDivisionId = 0))  
		 AND ((R.ReceiptBookId = @rReceiptBookId) OR (@rReceiptBookId = 0))  
		 AND ((R.ReceiptNumber >= @rFromReceiptNo) OR (@rFromReceiptNo = 0))  
		 AND ((R.ReceiptNumber <= @rToReceiptNo) OR (@rToReceiptNo = 0))  
		 AND ((R.ReceiptDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))  
		 AND ((R.ReceiptDate <= @rToDate) OR (ISNULL(@rToDate,'') = ''))  
		 AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  
		 AND ((SA.OrgId=@rOrgId) OR (@rOrgId=0))  
		 AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))  
		 AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))  
		 AND ((R.IsObsolete =@rIsCancel  AND (@rReportId != 20456 
												--OR @rReportId != 30804
				))  OR   
		  ((@rReportId = 20456 OR @rReportId = 30804) AND ((@rFeeStatusId = 0) -- All  
		  OR (@rFeeStatusId = 1 AND R.IsObsolete = 0) -- Valid  
		  OR (@rFeeStatusId = 2 AND R.IsObsolete = 1) -- Cancel  
		  )))  
		 AND (SA.StatusId=@rStatusId OR @rStatusId=0)  
		 AND (SA.ClassStatusId=@rClassStatusId OR @rClassStatusId=0)  
		 AND (R.PayTypeId = @rPaytypeId OR @rPaytypeId=0)  
		 AND ((SA.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))  
		 AND ((SA.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))  
		 AND ((SA.RollNo <= @rToRollNo) OR (@rToRollNo=0))  
		 AND ((SA.Code=@rCode) OR (@rCode=''))  
		 AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))  
		 AND ((ISNULL(U.LoginTitle,'') like @rCreatedUserName) OR (ISNULL(@rCreatedUserName,'')=''))  
		 AND ((@rIsDiscount =1 AND R.DiscountAmount!=0) OR (@rIsDiscount=0))  
		 --AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')  
		  AND (  
		  (@rFilterId = 0) -- All  
			 OR (@rFilterId = 2 AND isnull(AR.SourceId,0)!=0) -- Hostel  
			 OR (@rFilterId = 3 AND isnull(RT.SourceId,0)!=0) -- Transport  
			 OR ((@rFilterId =1) AND ((isnull(AR.SourceId,0)=0) AND (isnull(RT.SourceId,0)=0)))  
			)  
			AND ((RBM.OrgGroupId=@rOrgGroupId) OR (@rOrgGroupId=0))  
		 AND ((UPPER(R.BankName) like UPPER(@rBankName)) OR(ISNULL(@rBankName,'')=''))  
		 AND (ISNULL(SA.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')    
		 AND (ISNULL(R.BankName,'') IN( SELECT cast(item as nvarchar(100)) FROM  sCommon.fnsplit(@rBankNames,',')) OR @rBankNames='')   
		 AND ((R.ChequeClearDate>=@rFromChequeClearDate)OR(ISNULL(@rFromChequeClearDate,'')=''))      
		 AND ((R.ChequeClearDate<=@rToChequeClearDate)OR(ISNULL(@rToChequeClearDate,'')=''))
		 AND (ISNULL(R.PayTypeId,0) IN (SELECT cast(item as tinyint) FROM sCommon.fnsplit(@rPayTypeIds,',')) OR @rPayTypeIds='')
		 AND (ISNULL(R.ReceiptBookId,0) IN (SELECT cast(item as int) FROM sCommon.fnsplit(@rReceiptBookIds,',')) OR @rReceiptBookIds='')
  
		 ORDER BY R.ReceiptNumber
	END

	ELSE IF(@rReportId=30866)
	BEGIN
		SELECT   
		  @rBuilder1 AS Builder1,  
		  @rBuilder2 AS Builder2,  
		  @rIsDetail AS IsDetail,  
		  (CASE WHEN @rReportId IN (20456,30804) THEN  R.IsObsolete ELSE @rIsCancel END) AS IsCancel,  
		  --@rIsCancel AS IsCancel,  
		  @rIsFilter As IsFilter,  
		  @rIsHeader As IsHeader,  
		  @rIsDisplayOrgGroup AS IsDisplayOrgGroup,  
		  R.Id AS ReceiptId,  
		  R.ReceiptNumber,  
		  SA.ClassId,  
		  --SA.ClassName,  
		  SA.DivisionId,  
		  --SA.DivisionName,  
		  SA.ClassName+' - '+SA.DivisionName AS ClassDivision,  
		  SA.RollNo,  
		  SA.Code,  
		  SA.Name,  
		  ISNULL(PTM.Title,'') AS PayType,  
		  --ISNULL(R.ChequeNo,'') AS ChequeNo,  
		  CASE WHEN ISNULL(R.ChequeNo,'') != '' THEN R.ChequeNo ELSE CONVERT(nvarchar(20),R.PaymentTransactionId) END AS ChequeNo,
		  ISNULL(R.BankName,'') AS BankName,
		  --R.ReceiptAmount,  
		  RD.Amount AS ReceiptAmount,
		  --R.ReceiptDate,  
		  CASE  WHEN @rReportId = 30611 AND R.ChequeClearDate IS NOT NULL THEN R.ChequeClearDate ELSE R.ReceiptDate END AS ReceiptDate,  
		  R.CreatedUserId,  
		  ISNULL(U.LoginTitle,'') AS UserName,  
		  ISNULL(RBM.Title,'') AS ReceiptBookTitle,  
		  ISNULL(RBM.BankName,'') AS ReceiptBookBank,  
		  ISNULL(RBM.BankAccountNumber,'') AS BankAccountNumber,  
		  ISNULL(R.ReceiptBookId,'0') As ReceiptBookId,  
		  ISNULL((CASE @rReportId WHEN 20461 THEN [sFee].[fReceiptFeeDetailGet](R.Id)  
		   WHEN 30940 THEN [sFee].[fReceiptFeeDetailGet](R.Id) ELSE '' END),'') AS FeeDetail,  
		   R.Remark,  
		   R.DiscountAmount,  
		   ISNULL(RBM.OrderIndex,0) AS ReceiptBookOrderIndex,  
		   SA.OrgId,  
		   SA.OrganizationName,  
		   ISNULL(R.AmountAfterDiscount,0) AS AmountAfterDiscount,  
		   ISNULL(R.CGSTPercentage,0) AS CGSTPercentage,  
		   ISNULL(R.SGSTPercentage,0) AS SGSTPercentage,  
		   ISNULL(R.CGSTAmount,0) AS CGSTAmount,  
		   ISNULL(R.SGSTAmount,0) AS SGSTAmount,  
		   @rCustomGroupId AS CustomGroupId,  
		   SA.OrgGroupBatchId AS BatchId,  
		   SA.BatchName,  
		   R.ChequeDate,  
		   R.ChequeClearDate,
		   FM.Id AS FeeId,
		  FM.Code AS FeeCode,
		  FM.Title AS FeeTitle,
		   FM.OrderIndex AS FeeOrderIndex
		      
		  FROM   
		   sFee.tReceipt R  
		  INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id   
		  INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id  
		  INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id  
		  INNER JOIN sStudent.vStudentAcademic SA  
		   ON SA.AcademicId=R.SourceId AND ((SA.OrgId=@rOrgId) OR (@rOrgId=0))  
		  INNER JOIN sFinanceCommon.tPayTypeMaster PTM  
		   ON PTM.Id=R.PayTypeId  
		  INNER JOIN sFee.tReceiptBookMaster RBM   
		   ON RBM.Id=R.ReceiptBookId  
		  LEFT JOIN sSecurity.tUser U  
		   ON U.Id=R.CreatedUserId  
		 LEFT JOIN sHostel.tAssignRoom AR ON  AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003 AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  AND ((AR.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0) AND (SA.OrgGroupBatchId = AR.OrgGroupBatchId))   
			LEFT JOIN  
		 (SELECT AT.SourceId,B.OrgGroupBatchId FROM sTransport.tAssignRoute AT   
			INNER JOIN sTransport.tBusRouteDestinationMaster BM ON BM.Id=AT.PickupDestinationId   
			INNER JOIN sTransport.tBusRouteMaster B ON B.Id=BM.BusRouteId AND  AT.SourceTypeId=2003 AND ((B.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))) RT  
			ON RT.SourceId = SA.StudentId   
			AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))    
			AND (SA.OrgGroupBatchId = RT.OrgGroupBatchId)  
		WHERE   
		 R.SourceTypeId = 2001  
		 AND ((SA.AdmissionCategoryId = @rAdmissionCategoryId) OR (@rAdmissionCategoryId = 0))  
		 AND ((SA.ClassId = @rClassId) OR (@rClassId = 0))  
		 AND ((SA.DivisionId = @rDivisionId) OR (@rDivisionId = 0))  
		 AND ((R.ReceiptBookId = @rReceiptBookId) OR (@rReceiptBookId = 0))  
		 AND ((R.ReceiptNumber >= @rFromReceiptNo) OR (@rFromReceiptNo = 0))  
		 AND ((R.ReceiptNumber <= @rToReceiptNo) OR (@rToReceiptNo = 0))  
		 AND ((R.ReceiptDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))  
		 AND ((R.ReceiptDate <= @rToDate) OR (ISNULL(@rToDate,'') = ''))  
		 AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  
		 AND ((SA.OrgId=@rOrgId) OR (@rOrgId=0))  
		 AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))  
		 AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))  
		 AND ((R.IsObsolete =@rIsCancel  AND (@rReportId != 20456 OR @rReportId != 30804))  OR   
		  ((@rReportId = 20456 OR @rReportId = 30804) AND ((@rFeeStatusId = 0) -- All  
		  OR (@rFeeStatusId = 1 AND R.IsObsolete = 0) -- Valid  
		  OR (@rFeeStatusId = 2 AND R.IsObsolete = 1) -- Cancel  
		  )))  
		 AND (SA.StatusId=@rStatusId OR @rStatusId=0)  
		 AND (SA.ClassStatusId=@rClassStatusId OR @rClassStatusId=0)  
		 AND (R.PayTypeId = @rPaytypeId OR @rPaytypeId=0)  
		 AND ((SA.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))  
		 AND ((SA.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))  
		 AND ((SA.RollNo <= @rToRollNo) OR (@rToRollNo=0))  
		 AND ((SA.Code=@rCode) OR (@rCode=''))  
		 AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))  
		 AND ((ISNULL(U.LoginTitle,'') like @rCreatedUserName) OR (ISNULL(@rCreatedUserName,'')=''))  
		 AND ((@rIsDiscount =1 AND R.DiscountAmount!=0) OR (@rIsDiscount=0))  
		 --AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')  
		  AND (  
		  (@rFilterId = 0) -- All  
			 OR (@rFilterId = 2 AND isnull(AR.SourceId,0)!=0) -- Hostel  
			 OR (@rFilterId = 3 AND isnull(RT.SourceId,0)!=0) -- Transport  
			 OR ((@rFilterId =1) AND ((isnull(AR.SourceId,0)=0) AND (isnull(RT.SourceId,0)=0)))  
			)  
			AND ((RBM.OrgGroupId=@rOrgGroupId) OR (@rOrgGroupId=0))  
		 AND ((UPPER(R.BankName) like UPPER(@rBankName)) OR(ISNULL(@rBankName,'')=''))  
		 AND (ISNULL(SA.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')    
		 AND (ISNULL(R.BankName,'') IN( SELECT cast(item as nvarchar(100)) FROM  sCommon.fnsplit(@rBankNames,',')) OR @rBankNames='')   
		 AND ((R.ChequeClearDate>=@rFromChequeClearDate)OR(ISNULL(@rFromChequeClearDate,'')=''))      
		 AND ((R.ChequeClearDate<=@rToChequeClearDate)OR(ISNULL(@rToChequeClearDate,'')=''))
		 AND (ISNULL(R.PayTypeId,0) IN (SELECT cast(item as tinyint) FROM sCommon.fnsplit(@rPayTypeIds,',')) OR @rPayTypeIds='')  		 
  
		 ORDER BY R.ReceiptNumber  
	END

	ELSE IF(@rReportId=20547)
	BEGIN
		SELECT   
		  @rBuilder1 AS Builder1,  
		  @rBuilder2 AS Builder2,  
		  @rIsDetail AS IsDetail,  
		  (CASE WHEN @rReportId IN (20456,30804) THEN  R.IsObsolete ELSE @rIsCancel END) AS IsCancel,  
		  --@rIsCancel AS IsCancel,  
		  @rIsFilter As IsFilter,  
		  @rIsHeader As IsHeader,  
		  @rIsDisplayOrgGroup AS IsDisplayOrgGroup,  
		  R.Id AS ReceiptId,  
		  R.ReceiptNumber,  
		  SA.ClassId,  
		  --SA.ClassName,  
		  SA.DivisionId,  
		  --SA.DivisionName,  
		  SA.ClassName+' - '+SA.DivisionName AS ClassDivision,  
		  SA.RollNo,  
		  SA.Code,  
		  SA.Name,  
		  ISNULL(PTM.Title,'') AS PayType,  
		  --ISNULL(R.ChequeNo,'') AS ChequeNo,  
		  CASE WHEN ISNULL(R.ChequeNo,'') != '' THEN R.ChequeNo ELSE CONVERT(nvarchar(20),R.PaymentTransactionId) END AS ChequeNo,
		  ISNULL(R.BankName,'') AS BankName,  
		  RD.Amount AS ReceiptAmount,  
		  --R.ReceiptDate,  
		  CASE  WHEN @rReportId = 30611 AND R.ChequeClearDate IS NOT NULL THEN R.ChequeClearDate ELSE R.ReceiptDate END AS ReceiptDate,  
		  R.CreatedUserId,  
		  ISNULL(U.LoginTitle,'') AS UserName,  
		  ISNULL(RBM.Title,'') AS ReceiptBookTitle,  
		  ISNULL(RBM.BankName,'') AS ReceiptBookBank,  
		  ISNULL(RBM.BankAccountNumber,'') AS BankAccountNumber,  
		  ISNULL(R.ReceiptBookId,'0') As ReceiptBookId,  
		  ISNULL((CASE @rReportId WHEN 20461 THEN [sFee].[fReceiptFeeDetailGet](R.Id)  
		   ELSE '' END),'') AS FeeDetail,  
		   R.Remark,  
		   R.DiscountAmount,  
		   ISNULL(RBM.OrderIndex,0) AS ReceiptBookOrderIndex,  
		   SA.OrgId,  
		   SA.OrganizationName,  
		   ISNULL(R.AmountAfterDiscount,0) AS AmountAfterDiscount,  
		   ISNULL(R.CGSTPercentage,0) AS CGSTPercentage,  
		   ISNULL(R.SGSTPercentage,0) AS SGSTPercentage,  
		   ISNULL(R.CGSTAmount,0) AS CGSTAmount,  
		   ISNULL(R.SGSTAmount,0) AS SGSTAmount,  
		   @rCustomGroupId AS CustomGroupId,  
		   SA.OrgGroupBatchId AS BatchId,  
		   SA.BatchName,  
		   R.ChequeDate,  
		   R.ChequeClearDate ,
		   SA.GenderId
		  FROM   
		   sFee.tReceipt R  
		  INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id   
		  INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id  
		  INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id  
    
		  INNER JOIN sStudent.vStudentAcademic SA  
		   ON SA.AcademicId=R.SourceId AND ((SA.OrgId=@rOrgId) OR (@rOrgId=0)) 

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

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


		  LEFT JOIN sSecurity.tUser U  
		   ON U.Id=R.CreatedUserId  
		 LEFT JOIN sHostel.tAssignRoom AR ON  AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003 AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  AND ((AR.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0) AND (SA.OrgGroupBatchId = AR.OrgGroupBatchId))   
			LEFT JOIN  
		 (SELECT AT.SourceId,B.OrgGroupBatchId FROM sTransport.tAssignRoute AT   
			INNER JOIN sTransport.tBusRouteDestinationMaster BM ON BM.Id=AT.PickupDestinationId   
			INNER JOIN sTransport.tBusRouteMaster B ON B.Id=BM.BusRouteId AND  AT.SourceTypeId=2003 AND ((B.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))) RT  
			ON RT.SourceId = SA.StudentId   
			AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))    
			AND (SA.OrgGroupBatchId = RT.OrgGroupBatchId)  
		WHERE   
		 R.SourceTypeId = 2001  
		 AND ((SA.AdmissionCategoryId = @rAdmissionCategoryId) OR (@rAdmissionCategoryId = 0))  
		 AND ((SA.ClassId = @rClassId) OR (@rClassId = 0))  
		 AND ((SA.DivisionId = @rDivisionId) OR (@rDivisionId = 0))  
		 AND ((R.ReceiptBookId = @rReceiptBookId) OR (@rReceiptBookId = 0))  
		 AND ((R.ReceiptNumber >= @rFromReceiptNo) OR (@rFromReceiptNo = 0))  
		 AND ((R.ReceiptNumber <= @rToReceiptNo) OR (@rToReceiptNo = 0))  
		 AND ((R.ReceiptDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))  
		 AND ((R.ReceiptDate <= @rToDate) OR (ISNULL(@rToDate,'') = ''))  
		 AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  
		 AND ((SA.OrgId=@rOrgId) OR (@rOrgId=0))  
		 AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))  
		 AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))  
		 AND ((R.IsObsolete =@rIsCancel  AND (@rReportId != 20456 OR @rReportId != 30804))  OR   
		  ((@rReportId = 20456 OR @rReportId = 30804) AND ((@rFeeStatusId = 0) -- All  
		  OR (@rFeeStatusId = 1 AND R.IsObsolete = 0) -- Valid  
		  OR (@rFeeStatusId = 2 AND R.IsObsolete = 1) -- Cancel  
		  )))  
		 AND (SA.StatusId=@rStatusId OR @rStatusId=0)  
		 AND (SA.ClassStatusId=@rClassStatusId OR @rClassStatusId=0)  
		 AND (R.PayTypeId = @rPaytypeId OR @rPaytypeId=0)  
		 AND ((SA.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))  
		 AND ((SA.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))  
		 AND ((SA.RollNo <= @rToRollNo) OR (@rToRollNo=0))  
		 AND ((SA.Code=@rCode) OR (@rCode=''))  
		 AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))  
		 AND ((ISNULL(U.LoginTitle,'') like @rCreatedUserName) OR (ISNULL(@rCreatedUserName,'')=''))  
		 AND ((@rIsDiscount =1 AND R.DiscountAmount!=0) OR (@rIsDiscount=0))  
		 AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')  
		 AND (ISNULL(FM.Id, 0) IN (SELECT CAST(item as int) FROM sCommon.fnsplit(@rFeeId,',')) OR @rFeeId = '')
		 
		  AND (  
		  (@rFilterId = 0) -- All  
			 OR (@rFilterId = 2 AND isnull(AR.SourceId,0)!=0) -- Hostel  
			 OR (@rFilterId = 3 AND isnull(RT.SourceId,0)!=0) -- Transport  
			 OR ((@rFilterId =1) AND ((isnull(AR.SourceId,0)=0) AND (isnull(RT.SourceId,0)=0)))  
			)  
			AND ((RBM.OrgGroupId=@rOrgGroupId) OR (@rOrgGroupId=0))  
		 AND ((UPPER(R.BankName) like UPPER(@rBankName)) OR(ISNULL(@rBankName,'')=''))  
		 AND (ISNULL(SA.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')    
		 AND (ISNULL(R.BankName,'') IN( SELECT cast(item as nvarchar(100)) FROM  sCommon.fnsplit(@rBankNames,',')) OR @rBankNames='')   
		 AND ((R.ChequeClearDate>=@rFromChequeClearDate)OR(ISNULL(@rFromChequeClearDate,'')=''))      
		 AND ((R.ChequeClearDate<=@rToChequeClearDate)OR(ISNULL(@rToChequeClearDate,'')=''))
		 AND (ISNULL(R.PayTypeId,0) IN (SELECT cast(item as tinyint) FROM sCommon.fnsplit(@rPayTypeIds,',')) OR @rPayTypeIds='')
		 AND (ISNULL(R.ReceiptBookId,0) IN (SELECT cast(item as int) FROM sCommon.fnsplit(@rReceiptBookIds,',')) OR @rReceiptBookIds='')
  
		--GROUP BY R.Id,R.IsObsolete,R.ReceiptNumber,SA.ClassId,SA.DivisionId,SA.ClassName,SA.DivisionName,SA.RollNo, SA.Code,SA.Name,PTM.Title,R.ChequeNo,R.PaymentTransactionId
		--  ,R.BankName,R.ReceiptAmount,R.ChequeClearDate,R.ReceiptDate,R.CreatedUserId,U.LoginTitle,RBM.Title,RBM.BankName,RBM.BankAccountNumber,
		--  R.ReceiptBookId,R.Remark,R.DiscountAmount,RBM.OrderIndex,SA.OrgId,SA.OrganizationName,  
		--  R.AmountAfterDiscount,R.CGSTPercentage,R.SGSTPercentage,R.CGSTAmount,R.SGSTAmount,SA.OrgGroupBatchId,
		--  SA.BatchName,R.ChequeDate,R.ChequeClearDate,SA.GenderId

		 ORDER BY R.ReceiptNumber
	END

	ELSE IF(@rReportId=30630)
	BEGIN
	 
	 SELECT   
		  @rBuilder1 AS Builder1,  
		  @rBuilder2 AS Builder2,  
		  @rIsDetail AS IsDetail,  
		  (CASE WHEN @rReportId IN (20456,30804) THEN  R.IsObsolete ELSE @rIsCancel END) AS IsCancel,  
		  --@rIsCancel AS IsCancel,  
		  @rIsFilter As IsFilter,  
		  @rIsHeader As IsHeader,  
		  @rIsDisplayOrgGroup AS IsDisplayOrgGroup,  
		  R.Id AS ReceiptId,  
		  R.ReceiptNumber,  
		  SA.ClassId,  
		  --SA.ClassName,  
		  SA.DivisionId,  
		  --SA.DivisionName,  
		  SA.ClassName+' - '+SA.DivisionName AS ClassDivision,  
		  SA.RollNo,  
		  SA.Code,  
		  SA.Name,  
		  ISNULL(PTM.Title,'') AS PayType,  
		  --ISNULL(R.ChequeNo,'') AS ChequeNo,  
		  CASE WHEN ISNULL(R.ChequeNo,'') != '' THEN R.ChequeNo ELSE CONVERT(nvarchar(20),R.PaymentTransactionId) END AS ChequeNo,
		  ISNULL(R.BankName,'') AS BankName,
		  --R.ReceiptAmount,  
		  A.ReceiptAmount as ReceiptAmount,
		  --R.ReceiptDate,  
		  CASE  WHEN @rReportId = 30611 AND R.ChequeClearDate IS NOT NULL THEN R.ChequeClearDate ELSE R.ReceiptDate END AS ReceiptDate,  
		  R.CreatedUserId,  
		  ISNULL(U.LoginTitle,'') AS UserName,  
		  ISNULL(RBM.Title,'') AS ReceiptBookTitle,  
		  ISNULL(RBM.BankName,'') AS ReceiptBookBank,  
		  ISNULL(RBM.BankAccountNumber,'') AS BankAccountNumber,  
		  ISNULL(R.ReceiptBookId,'0') As ReceiptBookId,  
		  ISNULL((CASE @rReportId WHEN 20461 THEN [sFee].[fReceiptFeeDetailGet](R.Id)  
		   WHEN 30940 THEN [sFee].[fReceiptFeeDetailGet](R.Id) ELSE '' END),'') AS FeeDetail,  
		   R.Remark,  
		   R.DiscountAmount,  
		   ISNULL(RBM.OrderIndex,0) AS ReceiptBookOrderIndex,  
		   SA.OrgId,  
		   SA.OrganizationName,  
		   ISNULL(R.AmountAfterDiscount,0) AS AmountAfterDiscount,  
		   ISNULL(R.CGSTPercentage,0) AS CGSTPercentage,  
		   ISNULL(R.SGSTPercentage,0) AS SGSTPercentage,  
		   ISNULL(R.CGSTAmount,0) AS CGSTAmount,  
		   ISNULL(R.SGSTAmount,0) AS SGSTAmount,  
		   @rCustomGroupId AS CustomGroupId,  
		   SA.OrgGroupBatchId AS BatchId,  
		   SA.BatchName,  
		   R.ChequeDate,	
		   R.ChequeClearDate,
		   ISNULL(A.FeeHeadId,0) AS FeeHeadId,   --Mantis - 33979
		   ISNULL(A.FeeHeadName,'') AS FeeHeadName --Mantis - 33979
		  FROM   
		   sFee.tReceipt R  
		  --INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id   
		  --INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id  
		  --INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id  
		  INNER JOIN (Select SUM(RD.Amount) AS ReceiptAmount,RD.ReceiptId,
						FM.FeeHeadId AS FeeHeadId, --Mantis - 33979
						FHM.title AS FeeHeadName   --Mantis - 33979
					    FROM
						sFee.tReceiptDetail RD
						INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id  
						INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id
						INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id = FM.FeeHeadId		 --Mantis - 33979				  
						WHERE (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')  
						AND (ISNULL(FM.Id, 0) IN (SELECT CAST(item as int) FROM sCommon.fnsplit(@rFeeId,',')) OR @rFeeId = '')
						Group By  RD.ReceiptId,
								  FM.FeeHeadId,
								  FHM.title) A ON A.ReceiptId = R.Id    --Mantis - 33979
    
		  INNER JOIN sStudent.vStudentAcademic SA  
		   ON SA.AcademicId=R.SourceId AND ((SA.OrgId=@rOrgId) OR (@rOrgId=0))  
		  INNER JOIN sFinanceCommon.tPayTypeMaster PTM  
		   ON PTM.Id=R.PayTypeId  
		  INNER JOIN sFee.tReceiptBookMaster RBM   
		   ON RBM.Id=R.ReceiptBookId  
		  LEFT JOIN sSecurity.tUser U  
		   ON U.Id=R.CreatedUserId  
		 LEFT JOIN sHostel.tAssignRoom AR ON  AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003 AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  AND ((AR.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0) AND (SA.OrgGroupBatchId = AR.OrgGroupBatchId))   
			LEFT JOIN  
		 (SELECT AT.SourceId,B.OrgGroupBatchId FROM sTransport.tAssignRoute AT   
			INNER JOIN sTransport.tBusRouteDestinationMaster BM ON BM.Id=AT.PickupDestinationId   
			INNER JOIN sTransport.tBusRouteMaster B ON B.Id=BM.BusRouteId AND  AT.SourceTypeId=2003 AND ((B.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))) RT  
			ON RT.SourceId = SA.StudentId   
			AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))    
			AND (SA.OrgGroupBatchId = RT.OrgGroupBatchId)  
		WHERE   
		 R.SourceTypeId = 2001  
		 AND ((SA.AdmissionCategoryId = @rAdmissionCategoryId) OR (@rAdmissionCategoryId = 0))  
		 AND ((SA.ClassId = @rClassId) OR (@rClassId = 0))  
		 AND ((SA.DivisionId = @rDivisionId) OR (@rDivisionId = 0))  
		 AND ((R.ReceiptBookId = @rReceiptBookId) OR (@rReceiptBookId = 0))  
		 AND ((R.ReceiptNumber >= @rFromReceiptNo) OR (@rFromReceiptNo = 0))  
		 AND ((R.ReceiptNumber <= @rToReceiptNo) OR (@rToReceiptNo = 0))  
		 AND ((R.ReceiptDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))  
		 AND ((R.ReceiptDate <= @rToDate) OR (ISNULL(@rToDate,'') = ''))  
		 AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  
		 AND ((SA.OrgId=@rOrgId) OR (@rOrgId=0))  
		 AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))  
		 AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))  
		 AND ((R.IsObsolete =@rIsCancel  AND (@rReportId != 20456 OR @rReportId != 30804))  OR   
		  ((@rReportId = 20456 OR @rReportId = 30804) AND ((@rFeeStatusId = 0) -- All  
		  OR (@rFeeStatusId = 1 AND R.IsObsolete = 0) -- Valid  
		  OR (@rFeeStatusId = 2 AND R.IsObsolete = 1) -- Cancel  
		  )))  
		 AND (SA.StatusId=@rStatusId OR @rStatusId=0)  
		 AND (SA.ClassStatusId=@rClassStatusId OR @rClassStatusId=0)  
		 AND (R.PayTypeId = @rPaytypeId OR @rPaytypeId=0)  
		 AND ((SA.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))  
		 AND ((SA.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))  
		 AND ((SA.RollNo <= @rToRollNo) OR (@rToRollNo=0))  
		 AND ((SA.Code=@rCode) OR (@rCode=''))  
		 AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))  
		 AND ((ISNULL(U.LoginTitle,'') like @rCreatedUserName) OR (ISNULL(@rCreatedUserName,'')=''))  
		 AND ((@rIsDiscount =1 AND R.DiscountAmount!=0) OR (@rIsDiscount=0))  
		 --AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')  
		  AND (  
		  (@rFilterId = 0) -- All  
			 OR (@rFilterId = 2 AND isnull(AR.SourceId,0)!=0) -- Hostel  
			 OR (@rFilterId = 3 AND isnull(RT.SourceId,0)!=0) -- Transport  
			 OR ((@rFilterId =1) AND ((isnull(AR.SourceId,0)=0) AND (isnull(RT.SourceId,0)=0)))  
			)  
			AND ((RBM.OrgGroupId=@rOrgGroupId) OR (@rOrgGroupId=0))  
		 AND ((UPPER(R.BankName) like UPPER(@rBankName)) OR(ISNULL(@rBankName,'')=''))  
		 AND (ISNULL(SA.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')    
		 AND (ISNULL(R.BankName,'') IN( SELECT cast(item as nvarchar(100)) FROM  sCommon.fnsplit(@rBankNames,',')) OR @rBankNames='')   
		 AND ((R.ChequeClearDate>=@rFromChequeClearDate)OR(ISNULL(@rFromChequeClearDate,'')=''))      
		 AND ((R.ChequeClearDate<=@rToChequeClearDate)OR(ISNULL(@rToChequeClearDate,'')=''))
		 AND (ISNULL(R.PayTypeId,0) IN (SELECT cast(item as tinyint) FROM sCommon.fnsplit(@rPayTypeIds,',')) OR @rPayTypeIds='')  		
		 ORDER BY R.ReceiptNumber  

	END
	ELSE
	BEGIN
		SELECT   
		  @rBuilder1 AS Builder1,  
		  @rBuilder2 AS Builder2,  
		  @rIsDetail AS IsDetail,  
		  (CASE WHEN @rReportId IN (20456,30804) THEN  R.IsObsolete ELSE @rIsCancel END) AS IsCancel,  
		  --@rIsCancel AS IsCancel,  
		  @rIsFilter As IsFilter,  
		  @rIsHeader As IsHeader,  
		  @rIsDisplayOrgGroup AS IsDisplayOrgGroup,  
		  R.Id AS ReceiptId,  
		  R.ReceiptNumber,  
		  SA.ClassId,  
		  --SA.ClassName,  
		  SA.DivisionId,  
		  --SA.DivisionName,  
		  SA.ClassName+' - '+SA.DivisionName AS ClassDivision,  
		  SA.RollNo,  
		  SA.Code,  
		  SA.Name,  
		  ISNULL(PTM.Title,'') AS PayType,  
		  --ISNULL(R.ChequeNo,'') AS ChequeNo,  
		  CASE WHEN ISNULL(R.ChequeNo,'') != '' THEN R.ChequeNo ELSE CONVERT(nvarchar(20),R.PaymentTransactionId) END AS ChequeNo,
		  ISNULL(R.BankName,'') AS BankName,  
		  R.ReceiptAmount,  
		  --R.ReceiptDate,  
		  CASE  WHEN @rReportId = 30611 AND R.ChequeClearDate IS NOT NULL THEN R.ChequeClearDate ELSE R.ReceiptDate END AS ReceiptDate,  
		  R.CreatedUserId,  
		  ISNULL(U.LoginTitle,'') AS UserName,  
		  ISNULL(RBM.Title,'') AS ReceiptBookTitle,  
		  ISNULL(RBM.BankName,'') AS ReceiptBookBank,  
		  ISNULL(RBM.BankAccountNumber,'') AS BankAccountNumber,  
		  ISNULL(R.ReceiptBookId,'0') As ReceiptBookId,  
		  ISNULL((CASE @rReportId WHEN 20461 THEN [sFee].[fReceiptFeeDetailGet](R.Id)  
		   WHEN 30940 THEN [sFee].[fReceiptFeeDetailGet](R.Id) ELSE '' END),'') AS FeeDetail,  
		   R.Remark,  
		   R.DiscountAmount,  
		   ISNULL(RBM.OrderIndex,0) AS ReceiptBookOrderIndex,  
		   SA.OrgId,  
		   SA.OrganizationName,  
		   ISNULL(R.AmountAfterDiscount,0) AS AmountAfterDiscount,  
		   ISNULL(R.CGSTPercentage,0) AS CGSTPercentage,  
		   ISNULL(R.SGSTPercentage,0) AS SGSTPercentage,  
		   ISNULL(R.CGSTAmount,0) AS CGSTAmount,  
		   ISNULL(R.SGSTAmount,0) AS SGSTAmount,  
		   @rCustomGroupId AS CustomGroupId,  
		   SA.OrgGroupBatchId AS BatchId,  
		   SA.BatchName,  
		   R.ChequeDate,  
		   R.ChequeClearDate   
		  FROM   
		   sFee.tReceipt R  
		  --INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id   
		  --INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id  
		  --INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id  
    
		  INNER JOIN sStudent.vStudentAcademic SA  
		   ON SA.AcademicId=R.SourceId AND ((SA.OrgId=@rOrgId) OR (@rOrgId=0))  
		  INNER JOIN sFinanceCommon.tPayTypeMaster PTM  
		   ON PTM.Id=R.PayTypeId  
		  INNER JOIN sFee.tReceiptBookMaster RBM   
		   ON RBM.Id=R.ReceiptBookId  
		  LEFT JOIN sSecurity.tUser U  
		   ON U.Id=R.CreatedUserId  
		 LEFT JOIN sHostel.tAssignRoom AR ON  AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003 AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  AND ((AR.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0) AND (SA.OrgGroupBatchId = AR.OrgGroupBatchId))   
			LEFT JOIN  
		 (SELECT AT.SourceId,B.OrgGroupBatchId FROM sTransport.tAssignRoute AT   
			INNER JOIN sTransport.tBusRouteDestinationMaster BM ON BM.Id=AT.PickupDestinationId   
			INNER JOIN sTransport.tBusRouteMaster B ON B.Id=BM.BusRouteId AND  AT.SourceTypeId=2003 AND ((B.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))) RT  
			ON RT.SourceId = SA.StudentId   
			AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))    
			AND (SA.OrgGroupBatchId = RT.OrgGroupBatchId)  
		WHERE   
		 R.SourceTypeId = 2001  
		 AND ((SA.AdmissionCategoryId = @rAdmissionCategoryId) OR (@rAdmissionCategoryId = 0))  
		 AND ((SA.ClassId = @rClassId) OR (@rClassId = 0))  
		 AND ((SA.DivisionId = @rDivisionId) OR (@rDivisionId = 0))  
		 AND ((R.ReceiptBookId = @rReceiptBookId) OR (@rReceiptBookId = 0))  
		 AND ((R.ReceiptNumber >= @rFromReceiptNo) OR (@rFromReceiptNo = 0))  
		 AND ((R.ReceiptNumber <= @rToReceiptNo) OR (@rToReceiptNo = 0))  
		 AND ((R.ReceiptDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))  
		 AND ((R.ReceiptDate <= @rToDate) OR (ISNULL(@rToDate,'') = ''))  
		 AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  
		 AND ((SA.OrgId=@rOrgId) OR (@rOrgId=0))  
		 AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))  
		 AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))  
		 AND ((R.IsObsolete =@rIsCancel  AND (@rReportId != 20456 OR @rReportId != 30804))  OR   
		  ((@rReportId = 20456 OR @rReportId = 30804) AND ((@rFeeStatusId = 0) -- All  
		  OR (@rFeeStatusId = 1 AND R.IsObsolete = 0) -- Valid  
		  OR (@rFeeStatusId = 2 AND R.IsObsolete = 1) -- Cancel  
		  )))  
		 AND (SA.StatusId=@rStatusId OR @rStatusId=0)  
		 AND (SA.ClassStatusId=@rClassStatusId OR @rClassStatusId=0)  
		 AND (R.PayTypeId = @rPaytypeId OR @rPaytypeId=0)  
		 AND ((SA.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))  
		 AND ((SA.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))  
		 AND ((SA.RollNo <= @rToRollNo) OR (@rToRollNo=0))  
		 AND ((SA.Code=@rCode) OR (@rCode=''))  
		 AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))  
		 AND ((ISNULL(U.LoginTitle,'') like @rCreatedUserName) OR (ISNULL(@rCreatedUserName,'')=''))  
		 AND ((@rIsDiscount =1 AND R.DiscountAmount!=0) OR (@rIsDiscount=0))  
		 --AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')  
		  AND (  
		  (@rFilterId = 0) -- All  
			 OR (@rFilterId = 2 AND isnull(AR.SourceId,0)!=0) -- Hostel  
			 OR (@rFilterId = 3 AND isnull(RT.SourceId,0)!=0) -- Transport  
			 OR ((@rFilterId =1) AND ((isnull(AR.SourceId,0)=0) AND (isnull(RT.SourceId,0)=0)))  
			)  
			AND ((RBM.OrgGroupId=@rOrgGroupId) OR (@rOrgGroupId=0))  
		 AND ((UPPER(R.BankName) like UPPER(@rBankName)) OR(ISNULL(@rBankName,'')=''))  
		 AND (ISNULL(SA.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')    
		 AND (ISNULL(R.BankName,'') IN( SELECT cast(item as nvarchar(100)) FROM  sCommon.fnsplit(@rBankNames,',')) OR @rBankNames='')   
		 AND ((R.ChequeClearDate>=@rFromChequeClearDate)OR(ISNULL(@rFromChequeClearDate,'')=''))      
		 AND ((R.ChequeClearDate<=@rToChequeClearDate)OR(ISNULL(@rToChequeClearDate,'')=''))
		 AND (ISNULL(R.PayTypeId,0) IN (SELECT cast(item as tinyint) FROM sCommon.fnsplit(@rPayTypeIds,',')) OR @rPayTypeIds='')  		 
  
		 ORDER BY R.ReceiptNumber  
	END
 
-- UNION ALL  
   
-- SELECT   
--  R.Id AS ReceiptId,  
--  0 AS ClassId,  
--  --SA.ClassName,  
--  0 AS DivisionId,  
--  --SA.DivisionName,  
--  EM.DepartmentId,  
--  EM.DepartmentName AS ClassDept,  
--  0 AS RollNo,  
--  EM.Code,  
--  EM.EmployeeName,  
--  PTM.Title AS PayType,  
--  R.ReceiptAmount  
     
--  FROM   
--   sFee.tReceipt R  
--  INNER JOIN sCommon.tSourceTypeMaster STM  
--   ON STM.Id=R.SourceTypeId AND R.SourceTypeId = 95  
--  INNER JOIN sHrm.vExtEmployeeMaster EM  
--   ON EM.EmployeeId=R.SourceId  
--  INNER JOIN sFinanceCommon.tPayTypeMaster PTM  
--   ON PTM.Id=R.PayTypeId  
     
--WHERE   
--  ((EM.DepartmentId = @rDepartmentId) OR (@rDepartmentId = 0))  
-- AND ((R.ReceiptNumber >= @rFromReceiptNo) OR (@rFromReceiptNo = 0))  
-- AND ((R.ReceiptNumber <= @rToReceiptNo) OR (@rToReceiptNo = 0))  
-- AND ((R.ReceiptDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))  
-- AND ((R.ReceiptDate <= @rToDate) OR (ISNULL(@rToDate,'') = ''))  
-- AND (R.BatchId = @rBatchId)  
END
GO
PRINT N'Altering Procedure [sFrontOffice].[pUpdateStudentGatePassOutDate]...';


GO
ALTER PROCEDURE [sFrontOffice].[pUpdateStudentGatePassOutDate]
	 
	@rId int,
	@rOutTime nvarchar(100),
	@rOrgId int,
	@rReturnGatePassDate datetime
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
BEGIN TRY
 BEGIN TRANSACTION	
	BEGIN
	 
	    UPDATE  sFrontOffice.tStudentGatePass
	    SET ReturnGatePassTime=@rOutTime, ReturnGatePassDate=@rReturnGatePassDate
	    WHERE Id = @rId  AND (OrgId=@rOrgId OR @rOrgId=0)	
	       
	 END
	   
		SELECT 
			Id,
			AcademicId,
			VisitorName,
			ReasonOfGatePass,
			ISNULL(GatePassDate,'') AS GatePassDate,
			ISNULL(ReturnGatePassDate,'') AS ReturnGatePassDate,
			ISNULL(GatePassTime,'') AS GatePassTime,
			ISNULL(ReturnGatePassTime,'') AS ReturnGatePassTime,
			ISNULL(VisitorPhoto, CONVERT(VARBINARY(MAX), 0)) AS VisitorPhoto,
			CreatedDateTime
		
		FROM 
			sFrontOffice.tStudentGatePass
	
		COMMIT TRANSACTION
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
END
GO
PRINT N'Altering Procedure [sHrm].[pEmployeeGet]...';


GO
ALTER PROCEDURE [sHrm].[pEmployeeGet] 
	 @rFirstName NVARCHAR(50) = ''
	,@rLastName NVARCHAR(50) = ''
	,@rID NVARCHAR(50) = ''
	,@rOrgGroupId INT = 0
	,@rMiddleName NVARCHAR(50) = ''
	,@rContactNo NVARCHAR(50) = ''
	,@rCommonSearch NVARCHAR(500) = ''
	,@rUserId BIGINT = 0
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

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

	CREATE TABLE #EmpAutoSearchTemp (
		EmployeeId BIGINT
		,EmployeeData NVARCHAR(max)
		,)

	INSERT INTO #EmpAutoSearchTemp
	SELECT EM.Id AS EmployeeId
		,EM.FirstName + ' ' + EM.MiddleName + ' ' + EM.LastName + ' ' + DM.DisplayTitle + ' ' + EM.Code AS EmployeeData
	FROM sHrm.tEmployeeMaster EM
	INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id
	INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id = EJD.OrganizationDepartmentId

	SELECT [sHrm].[fEmployeeNameGet](VEM.FirstName, VEM.MiddleName, VEM.LastName, OM.StudentNameFormatId) AS Name
		,SM.Title AS StatusName
		,VEM.EmployeeId AS EmployeeId
		,VEM.Code
		,OM.DisplayTitle AS Organization
		,VEM.DepartmentName
		,VEM.DepartmentId
		,CASE 
			WHEN RIGHT(REPLACE(([sHrm].[fEmployeeContactsGet](VEM.EmployeeId)), ' ', ''), 1) = ','
				THEN reverse(stuff(reverse(([sHrm].[fEmployeeContactsGet](VEM.EmployeeId))), 1, 1, ''))
			WHEN LEFT(REPLACE(([sHrm].[fEmployeeContactsGet](VEM.EmployeeId)), ' ', ''), 1) = ','
				THEN STUFF(([sHrm].[fEmployeeContactsGet](VEM.EmployeeId)), 1, 1, '')
			ELSE ([sHrm].[fEmployeeContactsGet](VEM.EmployeeId))
			END AS ContactNo
		,EAS.EmployeeData
		,VEM.OrgId
		,ISNULL(EC.MobileNumber, '') AS MobileNumber
		,ISNULL(EC.CompanyEmail, '') AS Email
		,ISNULL(EI.EmployeePhoto, 0x) AS EmployeePhoto
		,ISNULL(U.Id, 0) AS UserId
		,EC.WhatsAppContactNo
	FROM [sHrm].[vEmployeeCommonDetail] VEM
	INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id = VEM.EmployeeId
	INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = VEM.OrgId
	INNER JOIN #EmpAutoSearchTemp EAS ON EAS.EmployeeId = VEM.EmployeeId
	LEFT JOIN sHrm.tEmployeeCommunications EC ON EC.EmployeeId = VEM.EmployeeId
	LEFT JOIN sCommon.tStatusMaster SM ON SM.Id = VEM.EmployeeStatusId
	LEFT JOIN [sHrm].[tEmployeeImages] EI ON EI.EmployeeId = VEM.EmployeeId
	LEFT JOIN sSecurity.tUser U ON U.OrgId = OM.Id AND U.SourceId = VEM.EmployeeId AND U.SourceTypeId = 95
	WHERE ((VEM.FirstName LIKE @rFirstName + '%') OR (@rFirstName = ''))
		AND ((VEM.LastName LIKE @rLastName + '%') OR (@rLastName = ''))
		AND ((VEM.MiddleName LIKE @rMiddleName + '%') OR (@rMiddleName = ''))
		AND ((VEM.Code = @rID) OR (@rID = ''))
		AND ((EC.MobileNumber = @rContactNo) OR (EC.PermanentContactNo = @rContactNo) OR (EC.EmergencyContactNo = @rContactNo)
			OR (EC.PhoneNoCompany = @rContactNo) OR (EC.PresentContactNo = @rContactNo) OR (EC.WhatsAppContactNo = @rContactNo)
			OR (@rContactNo = ''))
		AND OM.OrgGroupId = @rOrgGroupId
		AND ((EAS.EmployeeData LIKE '%' + @rCommonSearch + '%') OR (@rCommonSearch = ''))

	DROP TABLE #EmpAutoSearchTemp
END
GO
PRINT N'Altering Procedure [sOp].[pPaymentTransactionAdd]...';


GO
ALTER PROCEDURE [sOp].[pPaymentTransactionAdd] 
	@rId BIGINT = 0
	,@rTransactionSourceTypeId SMALLINT
	,@rTransactionSourceId BIGINT
	,@rPayerSourceTypeId SMALLINT
	,@rPayerSourceId BIGINT
	,@rPayAmount DECIMAL(12, 2)
	,@rTransactionStatusId INT
	,@rFunctionalityId SMALLINT
	,@rOrgId INT
	,@rOSTypeId SMALLINT = 0
	,@rPaymentGatewayId SMALLINT = 0
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
		BEGIN TRANSACTION

			DECLARE @lWrongFeeSetupOrReceiptBook int = 0
			IF(@rTransactionSourceTypeId = 2024)
			BEGIN
				IF NOT EXISTS (
						SELECT 1
						FROM sFee.tFeeSetup FS
						INNER JOIN sFee.tOnlineFee tOF ON tOF.ReceiptBookId = FS.ReceiptBookId
						INNER JOIN sFee.tOnlineFeeDetail OFD ON OFD.OnlineFeeId = tOF.Id AND OFD.FeeSetupId = FS.Id
						WHERE tOF.Id = @rTransactionSourceId 
						)
				BEGIN
					SELECT @lWrongFeeSetupOrReceiptBook = 1
				END
			END

			IF(@lWrongFeeSetupOrReceiptBook = 0)
			BEGIN

				DECLARE @lNextNumber BIGINT

				EXECUTE sCommon.pTableRowIdGet @rOrgId,'sOp.tPaymentTransaction',0,1,1,@outNextNumber = @lNextNumber OUTPUT

				INSERT INTO sOp.tPaymentTransaction (
					Id
					,TransactionSourceTypeId
					,TransactionSourceId
					,PayerSourceTypeId
					,PayerSourceId
					,PayDateTime
					,PayAmount
					,TransactionStatusId
					,FunctionalityId
					,OSTypeId
					,PaymentGatewayId
					)
				VALUES (
					@lNextNumber
					,@rTransactionSourceTypeId
					,@rTransactionSourceId
					,@rPayerSourceTypeId
					,@rPayerSourceId
					,sCommon.fGetDate()
					,@rPayAmount
					,@rTransactionStatusId
					,@rFunctionalityId
					,@rOSTypeId
					,@rPaymentGatewayId
				)

				SELECT @lNextNumber AS Result
			END
			ELSE
			BEGIN
				SELECT 0 AS Result
			END
		COMMIT TRANSACTION
	END TRY

	BEGIN CATCH
		ROLLBACK TRANSACTION

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


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

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

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


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

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


GO

ALTER PROC [sPortal].[pDepositHeadMasterDropDownLists]
@rOrgGroupId smallint


AS
BEGIN
	SELECT Id, Title FROM sFee.tDepositHeadMaster WHERE IsObsolete = 0 AND OrgGroupId =@rOrgGroupId
   
END
GO
PRINT N'Altering Procedure [sStudent].[pChangeIDNoLogGet]...';


GO

ALTER PROCEDURE [sStudent].[pChangeIDNoLogGet]
	 
	@rId bigint,
	@rOrgId int ,
	@rFromDate Date='',
	@rToDate Date='',
	@rClassId int=0,
	@rDivisionId int=0,
	@rBatchId int =0
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
		Select SM.Id As StudentId,
		CH.OldIdNo,
		CH.NewIdNo,
		SM.FirstName+' ' +SM.MiddleName+' ' +Sm.LastName AS Name,
		CH.CreatedDateTime
		,A.ClassId
		,A.DivisionId
		,A.BatchId

		from  sStudent.tChangeIdLog CH
		INNER JOIN sStudent.tStudentMaster SM ON SM.Id=CH.StudentId
		INNER JOIN sStudent.tAcademic A ON A.StudentId = SM.Id
		 
		Where  ((SM.Id=@rId) OR (@rId=0)) 
		AND SM.OrgId=@rOrgId
		AND A.BatchId=@rBatchId
		AND ((CAST(CH.CreatedDateTime as date )>=@rFromDate)OR(ISNULL(@rFromDate,'')=''))    
		AND ((CAST(CH.CreatedDateTime as date) <=@rToDate)OR(ISNULL(@rToDate,'')=''))
		AND ((A.ClassId=@rClassId)OR(ISNULL(@rClassId,0)=0))
		AND ((A.DivisionId=@rDivisionId)OR(ISNULL(@rDivisionId,0)=0))

		Order by StudentId,CH.CreatedDateTime desc
END
GO
PRINT N'Altering Procedure [sStudent].[pOnlineStudentDocumentGet]...';


GO
ALTER PROCEDURE [sStudent].[pOnlineStudentDocumentGet]
	 
    @rStudentId bigint,
	@rOrgId bigint,
	@rClassId bigint,
	@rBatchId bigint
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
 
	BEGIN

	Select 
		ISNULL(D.Id,0) AS DocumentId,
		ISNULL(D.DocumentName,'')AS DocumentName,
		A.DocumentFileName ,
		A.StudentDocumentId
		from sCommon.tSubmitDocumentMaster D 
		--INNER JOIN sCommon.tSubmitDocumentScope DS ON DS.SubmitDocumentId = D.Id -- Comment for Mantis Id: 0033804
		INNER JOIN 
		(Select D1.DocumentName,D1.Id AS StudentDocumentId,S.DocumentName AS DocumentFileName FROM sCommon.tSubmitDocumentMaster D1
		INNER JOIN sStudent.tOnlineRegistrationStudentDocument  S ON S.SubmitDocumentMasterId=D1.Id 
		WHERE  D1.SubmitDocumentFunctionalityId='5' AND D1.OrgId=@rOrgId AND (S.StudentId= @rStudentId  OR @rStudentId=0)
		AND D1.Id IN (select SubmitDocumentMasterId from sStudent.tOnlineRegistrationCriteriaDocument WHERE ClassId=@rClassId AND BatchId = @rBatchId  ))A ON  A.DocumentName = D.DocumentName

		Where OrgId=@rOrgId AND SubmitDocumentFunctionalityId='5' --AND DS.SourceTypeId = 2016 AND DS.SourceId = @rClassId --Comment for Mantis Id: 0033804
			
END
GO
PRINT N'Altering Procedure [sStudent].[ppImportStudent_Update_Dynamicly]...';


GO

ALTER proc [sStudent].[ppImportStudent_Update_Dynamicly]
@rOrgId int,
@rCreatedUserId bigint,
@rCode nvarchar(20) = '', 
@rFirstName nvarchar(100) = '',
@rMiddleName nvarchar(100) = '',
@rLastName nvarchar(100) = '',
@rGender nvarchar(20) = '',
@rAdmissionStandard nvarchar(100) = '',
@rAdmissionCategory nvarchar(100) = '',
@rAdmissionYear nvarchar(10) = '',
@rAdmissionDate datetime = '',
@rLeftStandard nvarchar(100) = '',
@rLeftDate datetime = '',
@rLeftYear nvarchar(10) = '',
@rLeftReason nvarchar(200) = '',
@rPreviousSchool nvarchar(200) = '',
@rDateOfBirth datetime = '',
@rBirthPlace nvarchar(150) = '',
@rBloodGroup nvarchar(20) = '',
@rBirthTaluka nvarchar(150) = '',
@rBirthDistrict nvarchar(150) = '',
@rFamilySubCast nvarchar(100) = '',
@rFamilyCast nvarchar(100) = '',
@rCastCatagory nvarchar(50) = '',
@rMotherTongue nvarchar(100) = '',
@rNationality nvarchar(50) = '',
@rReligion nvarchar(50) = '',
@rHobby nvarchar(50) = '',
@rFatherName nvarchar(100)='',
@rFatherContactNo nvarchar(50)='',
@rFatherDateOfBirth datetime = '',
@rFatherOccupation nvarchar(50)='',
@rFatherQualification nvarchar(50)='',
@rFatherMail nvarchar(50)='',
@rFatherOfficeAddress nvarchar(500)='',
@rFatherIncome int=0,
@rMotherDateOfBirth datetime = '',
@rMothername nvarchar(100)='',
@rMotherContactNo nvarchar(50)='',
@rMotherOccupation nvarchar(50)='',
@rMotherQualification nvarchar(50)='',
@rMotherMail nvarchar(50)='',
@rMotherOfficeAddress nvarchar(100)='',
@rMotherIncome int=0,
@rRelationshipName nvarchar(100)='',
@rRelativeName nvarchar(100)='',
@rRelativeDateOfBirth datetime='',
@rRelativeOccupation nvarchar(50)='',
@rRelativeQualification	nvarchar(50)='',
@rRelativeContactNo	nvarchar(50)='',
@rRelativeMail nvarchar(50)='',
@rRelativeOfficeAddress nvarchar(500)='',
@rRelativeIncome int=0,
@rPresentStreetOne nvarchar(150)='',
@rPresentStreetTwo nvarchar(150)='',
@rPresentStreetThree nvarchar(150)='',
@rPresentCity nvarchar(50)='',
@rPresentZipCode nvarchar(20)='',
@rPresentState nvarchar(50)='',
@rPresentCountry nvarchar(50)='',
@rPresentContactNo nvarchar(20)='', 
@rParentEmail nvarchar(50)='',
@rStudentContactNo  nvarchar(50)='',
@rStudentEmail nvarchar(50)='', 
@rAccountNumber nvarchar(20)='',
@rBankName nvarchar(100)=0,
@rBranch nvarchar(100)='', 
@rBankIFSCCode  nvarchar(20)='',
@rAdhaarNumber nvarchar(20)='',
@rValidate varchar(250)='' ,
@rOrgGroupId int,
@rBirthState  nvarchar(150)='',
@rUIDNumber nvarchar(50)='', 
@rBirthCountry nvarchar(150)='',
@rFatherOfficeContactNo nvarchar(50)='',
@rMotherOfficeContactNo varchar(50)='',
@rWhatsAppContactNo nvarchar(20)='',
@rPreviousLeftDate datetime = '',
@rMarriageAnniversaryDate datetime = '', -- Added parameter of @rMarriageAnniversaryDate for mantis 29443
@rPENNumber bigint = 0, --Mantis - 0031338
@rStatusId tinyint = 0,	-- MantisId : 0033278
@rBirthdateInWord nvarchar(150) = '' --mantisid - 0033596	

as
begin	
	IF(@rAdmissionDate='') 
	SET @rAdmissionDate = NULL
	IF(@rDateOfBirth='') 
	SET @rDateOfBirth = NULL
	IF(@rFatherDateOfBirth='') 
	SET @rFatherDateOfBirth = NULL
	IF(@rMotherDateOfBirth='') 
	SET @rMotherDateOfBirth = NULL
	IF(@rRelativeDateOfBirth='') 
	SET @rRelativeDateOfBirth = NULL
	IF(@rPreviousLeftDate='') 
	SET @rPreviousLeftDate = NULL
	/**Changes done for mantis 29443**/
	IF(@rMarriageAnniversaryDate='') 
	SET @rMarriageAnniversaryDate = NULL
	
	declare @StudentId bigint = 0
	select @StudentId = Id from sStudent.tStudentMaster where Code = @rCode and OrgID = @rOrgId
	select @StudentId = isnull(@StudentId,0)
	
	declare @genderid int,@AdmissionStandardid int,@LeftStandardid int,@nationalityid int,@religionid int, 
	 @castcategoryid int,@admissioncategoryid int,@bloodgroupid int 
	
	select @rGender = case when upper(@rGender) = 'M' then 'Male'
	when  upper(@rGender) = 'MALE' then 'Male'
	when upper(@rGender) ='FEMALE' then 'Female'
	when upper(@rGender) = 'F' then 'Female' when upper(@rGender) = 'N' then 'Not Known' else 'Not Known' end
	 
	select @genderid = isnull(Id,0) from sCommon.tGenderMaster where Title = @rGender
	
	select @AdmissionStandardid = isnull(Id,0) from sSetup.tClassMaster where Title = @rAdmissionStandard and OrgId = @rOrgId
 
	select @LeftStandardid = isnull(Id,0) from sSetup.tClassMaster where Title = @rLeftStandard and OrgId = @rOrgId
	
	select @nationalityid = isnull(Id,0) from sCommon.tCountryMaster where Nationality = @rNationality and OrgGroupId = @rOrgGroupId
	 
	 select @religionid = isnull(Id,0) from sCommon.tReligionMaster where Title = @rReligion  and OrgGroupId = @rOrgGroupId
	 
	  select @castcategoryid = isnull(Id,0) from sCommon.tCastCategoryMaster where Title = @rcastcatagory and OrgGroupId = @rOrgGroupId
	  
	  select @admissioncategoryid = isnull(Id,0) from sStudent.tAdmissionCategoryMaster where Title = @radmissioncategory and OrgGroupId = @rOrgGroupId
	 
	 select @bloodgroupid = isnull(Id,0) from sCommon.tBloodGroupMaster  where Title = @rBloodGroup  
	  
	select @genderid = isnull(@genderid,0),@AdmissionStandardid = isnull(@AdmissionStandardid,0),@LeftStandardid = isnull(@LeftStandardid,0),
	@nationalityid = isnull(@nationalityid,0),@religionid = isnull(@religionid,0),@castcategoryid = isnull(@castcategoryid,0),
	@admissioncategoryid = isnull(@admissioncategoryid,0),@bloodgroupid = isnull(@bloodgroupid,0) 
	
	declare @lNextNumber bigint,@Title varchar(100)=''
	
	 
	 
	if @rFirstName <> ''
	select @rFirstName = [sSetup].[fPortalXMLTagsReplaceReverse](@rFirstName)
	if @rMiddleName <> ''
	select @rMiddleName = [sSetup].[fPortalXMLTagsReplaceReverse](@rMiddleName)
	if @rLastName <> ''
	select @rLastName = [sSetup].[fPortalXMLTagsReplaceReverse](@rLastName)
	 if @rAdmissionDate <> ''
	select @rAdmissionDate = [sSetup].[fPortalXMLTagsReplaceReverse](@rAdmissionDate)
	 if @rAdmissionYear <> ''
	select @rAdmissionYear = [sSetup].[fPortalXMLTagsReplaceReverse](@rAdmissionYear)
	 if @rLeftDate <> ''
	select @rLeftDate = [sSetup].[fPortalXMLTagsReplaceReverse](@rLeftDate)
	if @rLeftYear <> ''
	select @rLeftYear= [sSetup].[fPortalXMLTagsReplaceReverse](@rLeftYear)
	if @rLeftReason <> ''
	select @rLeftReason= [sSetup].[fPortalXMLTagsReplaceReverse](@rLeftReason)
	if @rPreviousSchool <> ''
	select @rPreviousSchool= [sSetup].[fPortalXMLTagsReplaceReverse](@rPreviousSchool)
	if @rDateOfBirth <> ''
	select @rDateOfBirth= [sSetup].[fPortalXMLTagsReplaceReverse](@rDateOfBirth)
	if @rBirthPlace <> ''
	select @rBirthPlace= [sSetup].[fPortalXMLTagsReplaceReverse](@rBirthPlace)
	if @rBirthTaluka<> ''
	select @rBirthTaluka= [sSetup].[fPortalXMLTagsReplaceReverse](@rBirthTaluka)
	if @rBirthDistrict <> ''
	select @rBirthDistrict= [sSetup].[fPortalXMLTagsReplaceReverse](@rBirthDistrict)
	if @rFamilyCast <> ''
	select @rFamilyCast= [sSetup].[fPortalXMLTagsReplaceReverse](@rFamilyCast)
	if @rFamilySubCast <> ''
	select @rFamilySubCast= [sSetup].[fPortalXMLTagsReplaceReverse](@rFamilySubCast)
	if @rMotherTongue <> ''
	select @rMotherTongue= [sSetup].[fPortalXMLTagsReplaceReverse](@rMotherTongue)
	if @rHobby <> ''
	select @rHobby= [sSetup].[fPortalXMLTagsReplaceReverse](@rHobby)
	if @rFatherName<> ''
	select @rFatherName= [sSetup].[fPortalXMLTagsReplaceReverse](@rFatherName)
	if @rFatherContactNo<> ''
	select @rFatherContactNo= [sSetup].[fPortalXMLTagsReplaceReverse](@rFatherContactNo)
	if @rFatherDateOfBirth<> ''
	select @rFatherDateOfBirth= [sSetup].[fPortalXMLTagsReplaceReverse](@rFatherDateOfBirth)
	if @rFatherOccupation<> ''
	select @rFatherOccupation= [sSetup].[fPortalXMLTagsReplaceReverse](@rFatherOccupation)
	if @rFatherQualification<> ''
	select @rFatherQualification= [sSetup].[fPortalXMLTagsReplaceReverse](@rFatherQualification)
	if @rFatherMail<> ''
	select @rFatherMail= [sSetup].[fPortalXMLTagsReplaceReverse](@rFatherMail)
	if @rFatherOfficeAddress<> ''
	select @rFatherOfficeAddress= [sSetup].[fPortalXMLTagsReplaceReverse](@rFatherOfficeAddress)
	if @rFatherIncome<> ''
	select @rFatherIncome= [sSetup].[fPortalXMLTagsReplaceReverse](@rFatherIncome)
	if @rMothername<> ''
	select @rMothername= [sSetup].[fPortalXMLTagsReplaceReverse](@rMothername)
	if @rMotherContactNo<> ''
	select @rMotherContactNo= [sSetup].[fPortalXMLTagsReplaceReverse](@rMotherContactNo)
	if @rMotherDateOfBirth<> ''
	select @rMotherDateOfBirth= [sSetup].[fPortalXMLTagsReplaceReverse](@rMotherDateOfBirth)
	if @rMotherOccupation<> ''
	select @rMotherOccupation= [sSetup].[fPortalXMLTagsReplaceReverse](@rMotherOccupation)
	if @rMotherQualification <> ''
	select @rMotherQualification= [sSetup].[fPortalXMLTagsReplaceReverse](@rMotherQualification)
	if @rMotherMail<> ''
	select @rMotherMail= [sSetup].[fPortalXMLTagsReplaceReverse](@rMotherMail)
	if @rMotherOfficeAddress<> ''
	select @rMotherOfficeAddress= [sSetup].[fPortalXMLTagsReplaceReverse](@rMotherOfficeAddress)
	if @rMotherIncome<> ''
	select @rMotherIncome= [sSetup].[fPortalXMLTagsReplaceReverse](@rMotherIncome)
	if @rRelationshipName <> ''
	select @rRelationshipName= [sSetup].[fPortalXMLTagsReplaceReverse](@rRelationshipName)
	if @rRelativeName <> ''
	select @rRelativeName= [sSetup].[fPortalXMLTagsReplaceReverse](@rRelativeName)
	if @rRelativeDateOfBirth <> ''
	select @rRelativeDateOfBirth= [sSetup].[fPortalXMLTagsReplaceReverse](@rRelativeDateOfBirth)
	if @rRelativeOccupation <> ''
	select @rRelativeOccupation= [sSetup].[fPortalXMLTagsReplaceReverse](@rRelativeOccupation)
	if @rRelativeQualification <> ''
	select @rRelativeQualification= [sSetup].[fPortalXMLTagsReplaceReverse](@rRelativeQualification)
	if @rRelativeContactNo<> ''
	select @rRelativeContactNo= [sSetup].[fPortalXMLTagsReplaceReverse](@rRelativeContactNo)
	if @rRelativeMail<> ''
	select @rRelativeMail= [sSetup].[fPortalXMLTagsReplaceReverse](@rRelativeMail)
	if @rRelativeOfficeAddress <> ''
	select @rRelativeOfficeAddress= [sSetup].[fPortalXMLTagsReplaceReverse](@rRelativeOfficeAddress)
	if @rRelativeIncome <> ''
	select @rRelativeIncome= [sSetup].[fPortalXMLTagsReplaceReverse](@rRelativeIncome)
	 
	if @rPresentStreetOne <> ''
	select @rPresentStreetOne = [sSetup].[fPortalXMLTagsReplaceReverse](@rPresentStreetOne)
	if @rPresentStreetTwo <> ''
	select @rPresentStreetTwo = [sSetup].[fPortalXMLTagsReplaceReverse](@rPresentStreetTwo)
	if @rPresentStreetThree <> ''
	select @rPresentStreetThree = [sSetup].[fPortalXMLTagsReplaceReverse](@rPresentStreetThree)
	 
	if @rPresentZipCode <> ''
	select @rPresentZipCode = [sSetup].[fPortalXMLTagsReplaceReverse](@rPresentZipCode)
	if @rPresentState <> ''
	select @rPresentState = [sSetup].[fPortalXMLTagsReplaceReverse](@rPresentState)
	if @rPresentCountry <> ''
	select @rPresentCountry = [sSetup].[fPortalXMLTagsReplaceReverse](@rPresentCountry)
	if @rPresentCity <> ''
	select @rPresentCity = [sSetup].[fPortalXMLTagsReplaceReverse](@rPresentCity)
	if @rPresentContactNo <> ''
	select @rPresentContactNo = [sSetup].[fPortalXMLTagsReplaceReverse](@rPresentContactNo)
	if @rPresentState <> ''
	select @rPresentState = [sSetup].[fPortalXMLTagsReplaceReverse](@rPresentState)
	if @rAccountNumber <> ''
	select @rAccountNumber = [sSetup].[fPortalXMLTagsReplaceReverse](@rAccountNumber)
	if @rBankName <> ''
	select @rBankName = [sSetup].[fPortalXMLTagsReplaceReverse](@rBankName)
	if @rBranch <> ''
	select @rBranch = [sSetup].[fPortalXMLTagsReplaceReverse](@rBranch)
	if @rParentEmail<> ''
	select @rParentEmail = [sSetup].[fPortalXMLTagsReplaceReverse](@rParentEmail)
	if @rUIDNumber <> ''
	select @rUIDNumber = [sSetup].[fPortalXMLTagsReplaceReverse](@rUIDNumber)
	if @rAdhaarNumber <> ''
	select @rAdhaarNumber = [sSetup].[fPortalXMLTagsReplaceReverse](@rAdhaarNumber)
	  if @rStudentContactNo <> ''
	select @rStudentContactNo = [sSetup].[fPortalXMLTagsReplaceReverse](@rStudentContactNo)
	if @rStudentEmail <> ''
	select @rStudentEmail= [sSetup].[fPortalXMLTagsReplaceReverse](@rStudentEmail)
	if @rBankIFSCCode <> ''
	select @rBankIFSCCode = [sSetup].[fPortalXMLTagsReplaceReverse](@rBankIFSCCode)
	if @rBirthState<> ''
	select @rBirthState= [sSetup].[fPortalXMLTagsReplaceReverse](@rBirthState)
	if @rBirthCountry<> ''
	select @rBirthCountry= [sSetup].[fPortalXMLTagsReplaceReverse](@rBirthCountry)
	if @rFatherOfficeContactNo<> ''
	select @rFatherOfficeContactNo= [sSetup].[fPortalXMLTagsReplaceReverse](@rFatherOfficeContactNo)
	if @rMotherOfficeContactNo<> ''
	select @rMotherOfficeContactNo= [sSetup].[fPortalXMLTagsReplaceReverse](@rMotherOfficeContactNo)
	if @rWhatsAppContactNo<> ''
	select @rWhatsAppContactNo= [sSetup].[fPortalXMLTagsReplaceReverse](@rWhatsAppContactNo)

	 if @rPreviousLeftDate <> ''
	select @rPreviousLeftDate = [sSetup].[fPortalXMLTagsReplaceReverse](@rPreviousLeftDate)

	/***Changes done for mantis 29443***/
	if @rMarriageAnniversaryDate <> ''
	select @rMarriageAnniversaryDate = [sSetup].[fPortalXMLTagsReplaceReverse](@rMarriageAnniversaryDate)


	--Mantis Start- 0031338	
	DECLARE @lPENNumberActive nvarchar(50)=''
	SELECT @lPENNumberActive = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 544 AND SourceTypeId = 2010 AND SourceId = @rOrgGroupId
	--Mantis END- 0031338	
	begin

		UPDATE sStudent.tStudentMaster
		SET 
		FirstName = case when isnull(@rFirstName,'') <> '' then @rFirstName else FirstName end
		,MiddleName   = case when isnull(@rMiddleName,'') <> '' then @rMiddleName else MiddleName end
		,LastName     = case when isnull(@rLastName,'') <> '' then @rLastName else LastName end
		--,StatusId     = case when isnull(@statusid,0) <> 0 then @statusid else StatusId end
		 ,UpdatedUserId = @rCreatedUserId
		,UpdatedDateTime = sCommon.fGetDate()
		,StatusId = case when isnull(@rStatusId,0) <> 0 then @rStatusId else StatusId end		-- MantisId : 0033278
		WHERE Id = @StudentId and OrgId = @rOrgId
		--Mantis Start- 0031338	
		
		IF (@lPENNumberActive = 'True')
		Begin
			UPDATE sStudent.tStudentMaster
			SET 
			PENNumber =case when isnull(@rPENNumber,0) <> 0 then  @rPENNumber else PENNumber END--Mantis - 0031338
			WHERE Id = @StudentId and OrgId = @rOrgId
		END
--Mantis End- 0031338	

		IF NOT EXISTS(Select * from sStudent.tStudentAdmission where StudentId= @StudentId) 
		BEGIN
			INSERT INTO sStudent.tStudentAdmission(StudentId,CreatedUserId,CreatedDateTime) Values (@StudentId, @rCreatedUserId, sCommon.fGetDate())
		END

		SELECT @rLeftDate,@LeftStandardid			
		UPDATE sStudent.tStudentAdmission
		SET 
			AdmissionStandardId = case when isnull(@AdmissionStandardid,0) <> 0 then @AdmissionStandardid else AdmissionStandardId end,	 
			AdmissionYear = case when isnull(@rAdmissionYear,0) <> 0 then @rAdmissionYear else AdmissionYear end,			
			AdmissionDate = case when isnull(@rAdmissionDate,'') <> '' then @rAdmissionDate else AdmissionDate end,
			LeftStandardId =	case when isnull(@LeftStandardid,'') <> '' then @LeftStandardid else LeftStandardId end,
			LeftDate = case when isnull(@rLeftDate,'') <> '' then @rLeftDate else LeftDate end,	 
			LeftYear = case when isnull(@rLeftYear,0) <> 0 then @rLeftYear else LeftYear end,
			LeftReason = case when isnull(@rLeftReason,'') <> '' then @rLeftReason else LeftReason end,
			PreviousSchool = case when isnull(@rPreviousSchool,'') <> '' then @rPreviousSchool else PreviousSchool end,
			UpdatedUserId = @rCreatedUserId,
			UpdatedDateTime = sCommon.fGetDate(),
			PreviousLeftDate = case when isnull(@rPreviousLeftDate,'') <> '' then @rPreviousLeftDate else PreviousLeftDate end
		WHERE StudentId = @StudentId 
	 

		IF NOT EXISTS(Select * from sStudent.tStudentOther where StudentId= @StudentId) 
		BEGIN
			INSERT INTO sStudent.tStudentOther (StudentId, CreatedUserId, CreatedDateTime) Values (@StudentId, @rCreatedUserId, sCommon.fGetDate())
		END

		Update sStudent.tStudentOther
		set  
		GenderId = case when isnull(@genderid,0) <> 0 then @genderid else GenderId  end,
		ReligionId =  case when isnull(@religionId,0) <> 0 then @religionId else ReligionId  end,
		 BloodGroupId =  case when isnull(@bloodgroupid,0) <> 0 then @bloodgroupid else BloodGroupId  end,
		DateOfBirth =  case when isnull(@rDateOfBirth,'') <> '' then @rDateOfBirth else DateOfBirth  end,
		BirthDateInWord =  case when isnull(@rBirthdateInWord,'') <> '' then @rBirthdateInWord else BirthDateInWord  end, -- mantisid -- 0033596
		BirthPlace = case when isnull(@rBirthPlace,'') <> '' then @rBirthPlace else BirthPlace  end,
		BirthTaluka = case when isnull(@rBirthTaluka,'') <> '' then @rBirthTaluka else BirthTaluka  end,
			BirthDistrict = case when isnull(@rBirthDistrict,'') <> '' then @rBirthDistrict else BirthDistrict  end,
		 UIDNumber =  case when isnull(@rUIDNumber,'') <> '' then @rUIDNumber else UIDNumber  end,
		UpdatedUserId = @rCreatedUserId,
		UpdatedDateTime = sCommon.fGetDate(),
		FamilyCast =case when isnull(@rFamilyCast,'') <> '' then @rFamilyCast else FamilyCast  end,
		AdhaarNumber =case when isnull(@rAdhaarNumber,'') <> '' then @rAdhaarNumber else AdhaarNumber  end,
		FamilySubCast = case when isnull(@rFamilySubCast,'') <> '' then @rFamilySubCast else FamilySubCast  end,
		MotherTongue = case when isnull(@rMotherTongue,'') <>'' then @rMotherTongue else MotherTongue  end,
		NationalityId = case when isnull(@NationalityId,0) <> 0 then @NationalityId else NationalityId  end,
		 Hobby = case when isnull(@rHobby,'') <> '' then @rHobby else Hobby  end,
		CastCategoryId =case when isnull(@castcategoryid,0) <> 0 then @castcategoryid else CastCategoryId  end,
			BirthState = case when isnull(@rBirthState,'') <> '' then @rBirthState else BirthState  end,
				BirthCountry = case when isnull(@rBirthCountry,'') <> '' then @rBirthCountry else BirthCountry  end
		where StudentId = @StudentId 
		
	
		IF NOT EXISTS(Select * from sStudent.tStudentFamily where StudentId= @StudentId) 
		BEGIN
			INSERT INTO sStudent.tStudentFamily (StudentId, CreatedUserId, CreatedDateTime) Values (@StudentId, @rCreatedUserId, sCommon.fGetDate())
		END

  		UPDATE sStudent.tStudentFamily
		SET 
	      
		   FatherName = case when isnull(@rFatherName,'') <> '' then @rFatherName else FatherName end 
		  ,FatherDateOfBirth =  case when isnull(@rFatherDateOfBirth,'') <> '' then @rFatherDateOfBirth else FatherDateOfBirth end 
		  ,FatherOccupation = case when isnull(@rFatherOccupation,'') <> '' then @rFatherOccupation else FatherOccupation end 
		  ,FatherQualification = case when isnull(@rFatherQualification,'') <> '' then @rFatherQualification else FatherQualification end 
		  ,FatherContactNo =  case when isnull(@rFatherContactNo,'') <> '' then @rFatherContactNo else FatherContactNo end 
		  ,FatherMail =  case when isnull(@rFatherMail,'') <> '' then @rFatherMail else FatherMail end 
		  ,FatherOfficeAddress = case when isnull(@rFatherOfficeAddress,'') <> '' then @rFatherOfficeAddress else FatherOfficeAddress end 
		  ,FatherIncome = case when isnull(@rFatherIncome,'') <> '' then @rFatherIncome else FatherIncome end 
		  ,MotherName = case when isnull(@rMotherName,'') <> '' then @rMotherName else MotherName end  
		  ,MotherDateOfBirth =  case when isnull(@rMotherDateOfBirth,'') <> '' then @rMotherDateOfBirth else MotherDateOfBirth  end   
		  ,MotherOccupation =  case when isnull(@rMotherOccupation,'') <> '' then @rMotherOccupation else MotherOccupation  end   
		  ,MotherQualification =  case when isnull(@rMotherQualification,'') <> '' then @rMotherQualification else MotherQualification  end      
		   ,MotherContactNo = case when isnull(@rMotherContactNo,'') <> '' then @rMotherContactNo else MotherContactNo end
		   ,MotherMail = case when isnull(@rMotherMail,'') <> '' then @rMotherMail else MotherMail end
		   ,MotherOfficeAddress = case when isnull(@rMotherOfficeAddress,'') <> '' then @rMotherOfficeAddress else MotherOfficeAddress end
		   ,MotherIncome = case when isnull(@rMotherIncome,'') <> '' then @rMotherIncome else MotherIncome end
		   ,RelationshipName = case when isnull(@rRelationshipName,'') <> '' then @rRelationshipName else RelationshipName end
		   ,RelativeName = case when isnull(@rRelativeName,'') <> '' then @rRelativeName else RelativeName end
			,RelativeDateOfBirth = case when isnull(@rRelativeDateOfBirth,'') <> '' then @rRelativeDateOfBirth else RelativeDateOfBirth end 
			,RelativeOccupation = case when isnull(@rRelativeOccupation,'') <> '' then @rRelativeOccupation else RelativeOccupation end 
			,RelativeQualification = case when isnull(@rRelativeQualification,'') <> '' then @rRelativeQualification else RelativeQualification end 
			,RelativeContactNo = case when isnull(@rRelativeContactNo,'') <> '' then @rRelativeContactNo else RelativeContactNo end 
			,RelativeMail = case when isnull(@rRelativeMail,'') <> '' then @rRelativeMail else RelativeMail end 
			,RelativeOfficeAddress = case when isnull(@rRelativeOfficeAddress,'') <> '' then @rRelativeOfficeAddress else RelativeOfficeAddress end 
			,RelativeIncome = case when isnull(@rRelativeIncome,'') <> '' then @rRelativeIncome else RelativeIncome end 
			,FatherOfficeContactNo = case when isnull(@rFatherOfficeContactNo,'') <> '' then @rFatherOfficeContactNo else FatherOfficeContactNo end 
			,MotherOfficeContactNo = case when isnull(@rMotherOfficeContactNo,'') <> '' then @rMotherOfficeContactNo else MotherOfficeContactNo end 
			,MarriageAnniversaryDate = case when isnull(@rMarriageAnniversaryDate,'') <> '' then @rMarriageAnniversaryDate else MarriageAnniversaryDate end -- Added new field of MarriageAnniversaryDate for mantis : 29443
		  ,[UpdatedUserId] = @rCreatedUserId
		  ,[UpdatedDateTime] =  sCommon.fGetDate() 
		WHERE StudentId = @StudentId
			

		IF NOT EXISTS(Select * from sStudent.tStudentCommunication where StudentId= @StudentId) 
		BEGIN
			INSERT INTO sStudent.tStudentCommunication (StudentId, CreatedUserId, CreatedDateTime) Values (@StudentId, @rCreatedUserId, sCommon.fGetDate())
		END

  		UPDATE sStudent.tStudentCommunication
		SET 
	      
		   [PresentStreetOne] = case when isnull(@rPresentStreetOne,'') <> '' then @rPresentStreetOne else [PresentStreetOne] end 
		  ,[PresentStreetTwo] =  case when isnull(@rPresentStreetTwo,'') <> '' then @rPresentStreetTwo else [PresentStreetTwo] end 
		  ,[PresentStreetThree] = case when isnull(@rPresentStreetThree,'') <> '' then @rPresentStreetThree else [PresentStreetThree] end 
		  ,[PresentCountry] = case when isnull(@rPresentCountry,'') <> '' then @rPresentCountry else [PresentCountry] end 
		  ,[PresentState] =  case when isnull(@rPresentState,'') <> '' then @rPresentState else [PresentState] end 
		  ,[PresentCity] =  case when isnull(@rPresentCity,'') <> '' then @rPresentCity else [PresentCity] end 
		  ,PresentZipCode = case when isnull(@rPresentZipCode,'') <> '' then @rPresentZipCode else PresentZipCode end 
		  ,PresentContactNo = case when isnull(@rPresentContactNo,'') <> '' then @rPresentContactNo else PresentContactNo end 
		  ,ParentEmail = case when isnull(@rParentEmail,'') <> '' then @rParentEmail else ParentEmail end  
		  ,StudentContactNo =  case when isnull(@rStudentContactNo,'') <> '' then @rStudentContactNo else StudentContactNo  end   
		  ,StudentEmail =  case when isnull(@rStudentEmail,'') <> '' then @rStudentEmail else StudentEmail  end   
		   ,[UpdatedUserId] = @rCreatedUserId
		  ,[UpdatedDateTime] =  sCommon.fGetDate() 
		  ,WhatsAppContactNo =  case when isnull(@rWhatsAppContactNo,'') <> '' then @rWhatsAppContactNo else WhatsAppContactNo  end   
		WHERE StudentId = @StudentId
		

		IF NOT EXISTS(Select * from sStudent.tStudentAdditional where StudentId= @StudentId) 
		BEGIN
			INSERT INTO sStudent.tStudentAdditional (StudentId) Values (@StudentId)
		END

		UPDATE sStudent.tStudentAdditional
		SET
			BankBranch = case when isnull(@rBranch,'') <> '' then @rBranch else BankBranch end 
		  ,BankAccountNumber = case when isnull(@rAccountNumber,'') <> '' then @rAccountNumber else BankAccountNumber end 
		  ,BankName = case when isnull(@rBankName,'') <> '' then @rBankName else BankName end 
		  ,BankIFSCCode = case when isnull(@rBankIFSCCode,'') <> '' then @rBankIFSCCode else BankIFSCCode end 
		  
		where StudentId=@StudentId
		
	end	
end
GO
PRINT N'Altering Procedure [sStudent].[pStudentCustomSearchGet]...';


GO
ALTER PROCEDURE [sStudent].[pStudentCustomSearchGet]
(
	@rPageIndex int = null,
	@rOrgId smallint,
	@rOrderBy nvarchar(max) = 'RollNo',
	@rCode nvarchar(max) = '',
	@rFirstName [nvarchar](50) = '',	
	@rLastName [nvarchar](50) = '',
	@rCountry [nvarchar](50) = '',
	@rState [nvarchar](50) = '',
	@rCity nvarchar(max) = '',
	@rArea nvarchar(max) = '',
	--@rClassId nvarchar(max) = '',
	@rDivisionId nvarchar(max) = '',
	@rStatusId nvarchar(max) = '',
	@rTransportModeId nvarchar(max) = '',
	@rBusRouteDestinationId nvarchar(max) = '',
	@rBloodGroupId nvarchar(max) = '',
	@rGenderId nvarchar(max) = '',
	@rReligionId nvarchar(max) = '',
	@rCastCategoryId nvarchar(max) = '',
	@rHouseId nvarchar(max) = '',
	@rMotherTongueId nvarchar(max) = '',
	@rNationalityId nvarchar(max) = '',
	@rHobby nvarchar(50) = '',
	@rFatherQualification nvarchar(max) = '',
	@rMotherQualification nvarchar(max) = '',
	@rFatherOccupation nvarchar(max) = '',
	@rMotherOccupation nvarchar(max) = '',
	@rPreviousSchool nvarchar(max) = '',
	@rAdmissionCategoryId nvarchar(max) = '',
	@rDOBFromDate Date = '0001-01-01',
	@rDOBToDate Date = '9990-12-31',
	@rDOAFromDate Date = '0001-01-01',
	@rDOAToDate Date = '9990-12-31',
	@rDOLFromDate Date = '0001-01-01',
	@rDOLToDate Date = '9990-12-31',
	@rIsPysicalDeformity bit,
	@rIsMajorIllness bit,
	@BatchId int,
	@rIsBlackList bit,
	@rFromCode nvarchar(20), 
	@rToCode nvarchar(20),
	@rSpecificCode nvarchar(max),
	@rDropDownStatusId int,
	@rDropDownClassId int,
	@rDropDownDivisionId int,
	@rCustomTagId nvarchar(max) = '',
	@rCustomGroupId nvarchar(max) = '',
	@rClubId nvarchar(max) = '',
	@rRepeatCount Smallint=0,
	@rStudentStatus Smallint=0,
	@rHostelId nvarchar(max) = '',
	@rFatherName nvarchar(50)='',
	@rMotherName nvarchar(50)='',
	@rStudentGroupId nvarchar(max) = '',
	@rStudentOtherGroupId nvarchar(max) = '',
	@rOrgGroupBatchId int,
	@rBusRouteId nvarchar(max) = '',
	@rFeeExemption  nvarchar(max) = '',
	@rLCNumber nvarchar(20) = '',
	@rStudentNotAssigned int,
	@rRecordTagId nvarchar(max) = '',
	@rContactNo nvarchar(50) = '',
	@rDepartmentId int = 0,
	@rBirthDay int =0,
	@rDateOfMonth int =0,
	@rStopApplicationAccess int = 0
 )
AS
SET NOCOUNT ON
BEGIN

    TRUNCATE Table [sStudent].[TempStudentDetails]
	DECLARE @ListofCodes TABLE(Code nvarchar(25), ID INT IDENTITY(1,1));
		INSERT INTO @ListofCodes
	
	SELECT q2.value from
		(SELECT cast('<x>'+replace(@rSpecificCode,',','</x><x>')+'</x>' as xml) as thexml)q1 CROSS APPLY
		(SELECT x.value('.','nvarchar(max)') as value FROM thexml.nodes('x') as f(x))q2
	

	DECLARE @Sql nvarchar(MAX)
	
	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(@rDOLFromDate IS NULL)
		SET @rDOLFromDate='0001-01-01'
	IF(@rDOLToDate IS NULL)
		SET @rDOLToDate='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 @rDOLToDate <> '9999-12-31'
		SET @rDOLToDate = DATEADD(d,1,@rDOLToDate)
	SET @rSpecificCode = sCommon.fSearchStringGet(@rSpecificCode)
	SET @rFirstName = sCommon.fSearchStringGet(@rFirstName)
	SET @rLastName = sCommon.fSearchStringGet(@rLastName)
	SET @rCountry = sCommon.fSearchStringGet(@rCountry)
	SET @rState = sCommon.fSearchStringGet(@rState)
	
 IF  EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME ='tTempStudent2')
 BEGIN		
	DROP Table sStudent.tTempStudent2
 END
 IF  EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME ='tTempStudent3')
 BEGIN
	DROP Table sStudent.tTempStudent3
 END
 IF  EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME ='tTempStudent4')
 BEGIN
	DROP Table sStudent.tTempStudent4
 END
 IF  EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME ='tTempStudent8')
 BEGIN
	DROP Table sStudent.tTempStudent8
 END
 IF  EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME ='tTempStudent9')
 BEGIN	
	DROP Table sStudent.tTempStudent9
 END
 IF  EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME ='tTempStudent10')
 BEGIN
	DROP Table sStudent.tTempStudent10
 END
 IF  EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME ='tTempStudent11')
 BEGIN
	DROP Table sStudent.tTempStudent11
 END
 IF  EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME ='tTempStudent1')
 BEGIN
	DROP Table sStudent.tTempStudent1
 END
 IF  EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME ='tTempStudent12')
 BEGIN
	DROP Table sStudent.tTempStudent12
 END
 IF  EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME ='tTempStudent13')
 BEGIN
	DROP Table sStudent.tTempStudent13
 END
 IF  EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME ='tTempStudent14')
 BEGIN
	DROP Table sStudent.tTempStudent14
 END
 
		SELECT  DISTINCT SM.Id AS StudentId8,SF.IsFatherExStudent,SF.IsMotherExStudent, SF.FatherOrganization, SF.FatherDesignation,
						 SF.MotherOrganization, SF.MotherDesignation, SF.RelativeOrganization, SF.RelativeDesignation
		INTO sStudent.tTempStudent12
		FROM sStudent.tStudentMaster SM
			 LEFT JOIN sStudent.tAcademic A ON A.StudentId = SM.Id AND ((SM.OrgId = @rOrgId) OR (@rOrgId = 0)) AND ((A.BatchId=@BatchId) OR (@BatchId = 0))
			 LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId = SM.Id
		
		SELECT  DISTINCT SM.Id AS StudentId9, SH.IsAllergy,SH.AllergyRemark 
		INTO sStudent.tTempStudent13
		FROM sStudent.tStudentMaster SM
			 LEFT JOIN sStudent.tStudentHealth SH ON SH.StudentId = SM.Id
		 
	-- For Custom Tag
	IF (@rCustomTagId <> '')
	BEGIN
		SELECT DISTINCT SM.Id AS StudentId1		
		INTO sStudent.tTempStudent2
		FROM sStudent.tStudentMaster SM
		INNER JOIN sStudent.tStudentCustomTag SCT ON SCT.StudentId=SM.Id
		INNER JOIN sStudent.tAcademic A ON A.StudentId = SM.Id
		WHERE ((SM.OrgId = @rOrgId) OR (@rOrgId = 0)) AND ((A.BatchId=@BatchId) OR (@BatchId = 0))
		AND (ISNULL(SCT.CustomTagId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rCustomTagId,','))OR @rCustomTagId='')
	END
	ELSE
	BEGIN
		
		SELECT DISTINCT NULL AS StudentId1
		INTO sStudent.tTempStudent2
	END
	-- For Custom Group
	IF (@rCustomGroupId <> '')
	BEGIN
		SELECT DISTINCT SM.Id AS StudentId2
		INTO sStudent.tTempStudent3
		FROM sStudent.tStudentMaster SM
		INNER JOIN sStudent.tAcademic A ON A.StudentId = SM.Id
		INNER JOIN sCommunication.tCustomGroupMember CGM ON CGM.SourceId = A.Id AND CGM.SourceTypeId=2001
		WHERE ((SM.OrgId = @rOrgId) OR (@rOrgId = 0)) AND ((A.BatchId=@BatchId) OR (@BatchId = 0))
		AND (ISNULL(CGM.CustomGroupId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rCustomGroupId,','))OR @rCustomGroupId='')
	END
	ELSE
	BEGIN
		SELECT DISTINCT NULL AS StudentId2
		INTO sStudent.tTempStudent3
	END
	-- For Club Group
	IF (@rClubId <> '')
	BEGIN
		SELECT DISTINCT SM.Id AS StudentId3
		INTO sStudent.tTempStudent4
		FROM sStudent.tStudentMaster SM
		INNER JOIN sStudent.tAcademic A ON A.StudentId = SM.Id
		INNER JOIN sActivity.tAssignClub AC ON AC.AcademicId = A.Id
		WHERE ((SM.OrgId = @rOrgId) OR (@rOrgId = 0)) AND ((A.BatchId=@BatchId) OR (@BatchId = 0))
		AND (ISNULL(AC.ClubId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClubId,','))OR @rClubId='')
	END
	ELSE
	BEGIN
		SELECT DISTINCT NULL AS StudentId3
		INTO sStudent.tTempStudent4
	END
	-- For Hostel
	IF (@rHostelId <> '')
	BEGIN
		SELECT DISTINCT SM.Id AS StudentId4
		INTO sStudent.tTempStudent8
		FROM sStudent.tStudentMaster SM
		INNER JOIN sStudent.tAcademic A ON A.StudentId = SM.Id
		INNER JOIN sHostel.tAssignRoom AR ON AR.SourceId = A.StudentId
		AND ((AR.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
		INNER JOIN sHostel.tRoomMaster RM ON RM.Id = AR.RoomId
		WHERE ((SM.OrgId = @rOrgId) OR (@rOrgId = 0)) --AND A.BatchId = @BatchId
		AND (ISNULL(RM.HostelId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rHostelId,','))OR @rHostelId='')
	END
	ELSE
	BEGIN
		SELECT DISTINCT NULL AS StudentId4
		INTO sStudent.tTempStudent8
	END
	--Transport
	IF (@rBusRouteId <> '')
	BEGIN
		SELECT DISTINCT SM.Id AS StudentId5
		INTO sStudent.tTempStudent9
		FROM sStudent.tStudentMaster SM
		INNER JOIN sStudent.tAcademic A ON A.StudentId = SM.Id
		INNER JOIN sTransport.tAssignRoute AT ON AT.SourceId = A.StudentId
		INNER JOIN sTransport.tBusRouteDestinationMaster BM ON BM.Id = AT.PickupDestinationId
		INNER JOIN sTransport.tBusRouteMaster BRM ON BRM.Id = BM.BusRouteId
		AND ((BRM.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
		WHERE ((SM.OrgId = @rOrgId) OR (@rOrgId = 0))
		AND (ISNULL(BRM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rBusRouteId,','))OR @rBusRouteId='')
	END
	ELSE
	BEGIN
		SELECT DISTINCT NULL AS StudentId5
		INTO sStudent.tTempStudent9
	END
	IF (@rFeeExemption <> '')
	BEGIN
		SELECT DISTINCT SM.Id AS StudentId6
		INTO sStudent.tTempStudent10
		FROM sStudent.tStudentMaster SM
		INNER JOIN sStudent.tAcademic A ON A.StudentId = SM.Id
		INNER JOIN sFee.tExemptionTypeMaster AT ON AT.Id = A.ExemptionTypeId
		WHERE ((SM.OrgId = @rOrgId) OR (@rOrgId = 0))
		AND (ISNULL(AT.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeExemption,','))OR @rFeeExemption='')
	END
	ELSE
	BEGIN
		SELECT DISTINCT NULL AS StudentId6
		INTO sStudent.tTempStudent10
	END
	-- Not Assign	
	IF (@rStudentNotAssigned <> 0)
	BEGIN
		IF @rStudentNotAssigned = 1  -- Hostel Not Assign
		BEGIN
		 IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE='BASE TABLE' AND TABLE_NAME='sStudent.tTempStudent11')
		 Begin
			SELECT DISTINCT SM.Id AS StudentId7
			INTO sStudent.tTempStudent11
			FROM sStudent.tStudentMaster SM
			INNER JOIN sStudent.tAcademic A ON A.StudentId = SM.Id AND ((SM.OrgId = @rOrgId) OR (@rOrgId = 0)) AND ((A.BatchId=@BatchId) OR (@BatchId = 0)) AND A.StudentID Not in 
			(
			SElect SourceId from sHostel.tAssignRoom AR 
			INNER JOIN sHostel.tRoomMaster RM ON RM.Id = AR.RoomId AND ((AR.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
			WHERE ((SM.OrgId = @rOrgId) OR (@rOrgId = 0))
			AND (ISNULL(RM.HostelId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rHostelId,','))OR @rHostelId=''))
		 end
		END 

		IF @rStudentNotAssigned = 2 -- Transport Not Assign
		BEGIN
			 IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE='BASE TABLE' AND TABLE_NAME='sStudent.tTempStudent11')
			 Begin
				SELECT DISTINCT SM.Id AS StudentId7
				INTO sStudent.tTempStudent11
				FROM sStudent.tStudentMaster SM
				INNER JOIN sStudent.tAcademic A ON A.StudentId = SM.Id AND ((SM.OrgId = @rOrgId) OR (@rOrgId = 0)) AND ((A.BatchId=@BatchId) OR (@BatchId = 0)) AND A.StudentID Not in
				(Select SourceId FRom sTransport.tAssignRoute AT
				INNER JOIN sTransport.tBusRouteDestinationMaster BM ON BM.Id = AT.PickupDestinationId AND AT.SourceTypeId = 2003
				INNER JOIN sTransport.tBusRouteMaster BRM ON BRM.Id = BM.BusRouteId 
				AND  (ISNULL(BRM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rBusRouteId,','))OR @rBusRouteId='')
				AND ((BRM.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0)))
				WHERE ((SM.OrgId = @rOrgId) OR (@rOrgId = 0))
			END			
		END 
		
	END
	ELSE
	BEGIN		
		SELECT DISTINCT NULL AS StudentId7 INTO sStudent.tTempStudent11
		
		
	END

	-- For Record Tag
	IF (@rRecordTagId <> '')
	BEGIN
		SELECT DISTINCT SM.Id AS StudentId14		
		INTO sStudent.tTempStudent14
		FROM sStudent.tStudentMaster SM
		INNER JOIN sStudent.tAcademic A ON A.StudentId = SM.Id
		WHERE ((SM.OrgId = @rOrgId) OR (@rOrgId = 0)) AND ((A.BatchId=@BatchId) OR (@BatchId = 0))
		AND (ISNULL(SM.RecordStatusId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rRecordTagId,','))OR @rRecordTagId='')
	END
	ELSE
	BEGIN
		
		SELECT DISTINCT NULL AS StudentId14
		INTO sStudent.tTempStudent14
	END
	
	--
	SELECT *,SCS.ClassName+'-'+SCS.DivisionName AS ClassName1
	INTO sStudent.tTempStudent1
	FROM sStudent.vStudentCustomSearch SCS
	INNER JOIN sStudent.tTempStudent2 T2 ON SCS.StudentId = T2.StudentId1 OR @rCustomTagId = ''
	INNER JOIN sStudent.tTempStudent3 T3 ON SCS.StudentId = T3.StudentId2 OR @rCustomGroupId = ''
	INNER JOIN sStudent.tTempStudent4 T4 ON SCS.StudentId = T4.StudentId3 OR @rClubId = ''
	INNER JOIN sStudent.tTempStudent8 T8 ON SCS.StudentId = T8.StudentId4 OR @rHostelId = ''
	INNER JOIN sStudent.tTempStudent9 T9 ON SCS.StudentId = T9.StudentId5 OR @rBusRouteId = ''
	INNER JOIN sStudent.tTempStudent10 T10 ON SCS.StudentId = T10.StudentId6 OR @rFeeExemption = ''
	INNER JOIN sStudent.tTempStudent11 T11 ON SCS.StudentId = T11.StudentId7 OR @rStudentNotAssigned = 0
	LEFT JOIN sStudent.tTempStudent12 T12 ON SCS.StudentId = T12.StudentId8
	INNER JOIN sStudent.tTempStudent14 T14 ON SCS.StudentId = T14.StudentId14 OR @rRecordTagId = ''
	--INNER JOIN sStudent.tTempStudent13 T13 ON SCS.StudentId = T13.StudentId9
	
	WHERE ((SCS.OrgId = @rOrgId) OR (@rOrgId = 0)) AND ((SCS.BatchId = @BatchId) OR (@BatchId = 0))
	AND SCS.OrgGroupBatchId = @rOrgGroupBatchId
	--AND ((SCS.Code Like @rSpecificCode + '%') OR (@rSpecificCode = ''))
	AND ((SCS.FirstName Like @rFirstName  + '%') OR (@rFirstName = ''))
	AND ((SCS.LastName Like @rLastName + '%')OR(@rLastName = ''))
	AND ((ISNULL(SCS.PermanentCountry,'') Like @rCountry + '%')OR(@rCountry = ''))
	AND ((ISNULL(SCS.PermanentState,'') Like @rState + '%')OR(@rState = ''))
	AND (( SCS.DateOfBirth  >= @rDOBFromDate) OR (ISNULL(SCS.DateOfBirth,'') = ''))
	AND (( SCS.DateOfBirth  < @rDOBToDate) OR (ISNULL(SCS.DateOfBirth,'') = ''))
	AND (( SCS.AdmissionDate >= @rDOAFromDate) OR (ISNULL(SCS.AdmissionDate,'') = ''))
	AND (( SCS.AdmissionDate < @rDOAToDate) OR (ISNULL(SCS.AdmissionDate,'') = ''))
	AND (( SCS.LeftDate  >= @rDOLFromDate) OR (ISNULL(SCS.LeftDate,'') = ''))
	AND (( SCS.LeftDate   < @rDOLToDate) OR (ISNULL(SCS.LeftDate,'') = ''))
	AND ((SCS.Hobby Like '%' + @rHobby + '%') OR (@rHobby = ''))
	AND ((SCS.RepeatCount=@rRepeatCount)OR (@rRepeatCount=0))
	AND (ISNULL(SCS.PermanentCity,0) IN( SELECT item FROM  sCommon.fnsplit(@rCity,','))OR @rCity='')
	AND (ISNULL(SCS.PermanentStreetThree,0) IN( SELECT item FROM  sCommon.fnsplit(@rArea,','))OR @rArea='')
	AND (SCS.DivisionId In( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionId,','))OR @rDivisionId='')
	AND (SCS.StatusId In( SELECT cast(item as int) FROM  sCommon.fnsplit(@rStatusId,','))OR @rStatusId='')
	AND (SCS.TransportModeId In( SELECT cast(item as int) FROM  sCommon.fnsplit(@rTransportModeId,','))OR @rTransportModeId='')
	AND (ISNULL(SCS.BloodGroupId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rBloodGroupId,','))OR @rBloodGroupId='')
	AND (ISNULL(SCS.GenderId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rGenderId,','))OR @rGenderId='')
	AND (ISNULL(SCS.ReligionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rReligionId,','))OR @rReligionId='')
	AND (ISNULL(SCS.CastCategoryId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rCastCategoryId,','))OR @rCastCategoryId='')
	AND (ISNULL(SCS.HouseId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rHouseId,','))OR @rHouseId='')
	AND (ISNULL(SCS.MotherTongueId,0) IN ( SELECT cast(item as int) FROM  sCommon.fnsplit(@rMotherTongueId,','))OR @rMotherTongueId='')
	AND (ISNULL(SCS.NationalityId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rNationalityId,','))OR @rNationalityId='')
	AND (ISNULL(SCS.BusRouteDestinationId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rBusRouteDestinationId,','))OR @rBusRouteDestinationId='')
	AND (ISNULL(SCS.FatherQualification,'') IN( SELECT item FROM  sCommon.fnsplit(@rFatherQualification,','))OR @rFatherQualification='')
	AND (ISNULL(SCS.FatherOccupation,'') IN( SELECT item FROM  sCommon.fnsplit(@rFatherOccupation,','))OR @rFatherOccupation='')
	AND (ISNULL(SCS.MotherQualification,'') IN( SELECT item FROM  sCommon.fnsplit(@rMotherQualification,','))OR @rMotherQualification='')
	AND (ISNULL(SCS.MotherOccupation,'') IN( SELECT item FROM  sCommon.fnsplit(@rMotherOccupation,','))OR @rMotherOccupation='')
	AND (ISNULL(SCS.AdmissionCategoryId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rAdmissionCategoryId,','))OR @rAdmissionCategoryId='')
	AND (ISNULL(SCS.PreviousSchool,'') IN( SELECT item FROM  sCommon.fnsplit(@rPreviousSchool,','))OR @rPreviousSchool='')
	-- AND (ISNULL(SCS.RepeatCount,1) IN( SELECT item FROM  sCommon.fnsplit(@rRepeatCount,','))OR @rRepeatCount=1)
	AND (ISNULL(SCS.StudentStatusId,'') IN( SELECT item FROM  sCommon.fnsplit(@rStudentStatus,','))OR @rStudentStatus='')
	AND (ISNULL(SCS.StudentGroupId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rStudentGroupId,','))OR @rStudentGroupId='')
	AND (ISNULL(SCS.StudentOtherGroupId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rStudentOtherGroupId,','))OR @rStudentOtherGroupId='')
	AND ((SCS.IsPysicalDeformity=@rIsPysicalDeformity) OR (@rIsPysicalDeformity=0))
	AND ((SCS.IsMajorIllness=@rIsMajorIllness) OR (@rIsMajorIllness=0))
	AND ((SCS.IsBlackList=@rIsBlackList) OR (@rIsBlackList=0))
	AND ((REPLICATE(0, 50 - LEN(SCS.Code)) + SCS.Code) >= (REPLICATE(0, 50 - LEN(@rFromCode)) + @rFromCode) OR (@rFromCode=''))
	AND ((REPLICATE(0, 50 - LEN(SCS.Code)) + SCS.Code) <= (REPLICATE(0, 50 - LEN(@rToCode)) + @rToCode) OR (@rToCode=''))
	AND ((SCS.Code IN(SELECT Code FROM @ListofCodes)) OR (ISNULL(@rSpecificCode,'') = ''))
	AND ((SCS.StatusId = @rDropDownStatusId) OR (@rDropDownStatusId=0))
	AND ((SCS.ClassId = @rDropDownClassId) OR (@rDropDownClassId=0))
	AND ((SCS.DivisionId = @rDropDownDivisionId) OR (@rDropDownDivisionId=0))
	AND ((SCS.MiddleName Like @rFatherName  + '%') OR (@rFatherName = ''))
	AND ((SCS.MotherName Like @rMotherName  + '%') OR (@rMotherName = ''))
	AND (ISNULL(SCS.BusRouteId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rBusRouteId,','))OR @rBusRouteId='')
	AND (ISNULL(SCS.ExemptionTypeId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeExemption,','))OR @rFeeExemption='')
	AND ((SCS.LCNumber=@rLCNumber)OR (@rLCNumber=''))
	AND ((SCS.PresentContactNo=@rContactNo) OR (SCS.PermanentContactNo=@rContactNo) OR (SCS.EmergencyContactNo=@rContactNo) OR (SCS.ParentContactno=@rContactNo) OR (SCS.StudentContactNo=@rContactNo) OR (SCS.FatherContactNo=@rContactNo) OR (SCS.MotherContactNo=@rContactNo) OR (@rContactNo=''))
	AND ((SCS.DepartmentId = @rDepartmentId) OR (@rDepartmentId = 0))
	AND (( DAY(CONVERT(date,SCS.DateOfBirth)) = @rBirthDay) OR (@rBirthDay = 0))
	AND (( MONTH(CONVERT(date,SCS.DateOfBirth)) = @rDateOfMonth) OR (@rDateOfMonth = 0))
	AND ((SCS.IsStopApplicationAccess = @rStopApplicationAccess) OR (@rStopApplicationAccess = -1))

	SET @rOrderBy=Replace(@rOrderBy,'GR No','Code')
	SET @rOrderBy=Replace(@rOrderBy,'ID No','Code')
	SET @rOrderBy=Replace(@rOrderBy,'PhysicalDeformityRemark','PysicalDeformityRemark')
	SET @rOrderBy=Replace(@rOrderBy,'IsPhysicalDeformity','IsPysicalDeformity')
	
	SET @sql='SELECT StudentId,Code AS Code,Name,ClassName1 AS ClassName,StatusName,
	ParentContactNo
	FROM sStudent.tTempStudent1 ORDER BY '+@rOrderBy
	
	exec(@Sql)
	
	
	select @Sql = 'insert into [sStudent].[TempStudentDetails]
	SELECT StudentId,Code,ClassName,StatusName,ParentContactNo FROM sStudent.tTempStudent1 ORDER BY ' + @rOrderBy
	exec (@Sql)
	
	create table #STUDENTTEMP
	(
		tid int identity(1,1),t_StudentId bigint
	)
	select @Sql = 'insert into #STUDENTTEMP
	SELECT StudentId FROM sStudent.tTempStudent1 ORDER BY ' + @rOrderBy
	
	exec (@Sql)
	
	select @rPageIndex = case when isnull(@rPageIndex,0) = 0 then 1 else @rPageIndex end
	declare @lTotalRecords int,@lPageSize int = 10,@lResult nvarchar(max) = '',@lPaging nvarchar(max) = ''
	
	select @lTotalRecords = COUNT(*) FROM #STUDENTTEMP
	select @lPaging = @lPaging + dbo.fnc_SearchPagingFormat(@rPageIndex, @lTotalRecords, @lPageSize)
	
	IF(@rOrgId = 0)
	BEGIN
		select @lResult = @lResult + 
		'<tr><td><a class="disable" style="color: #676767 !important">Select</a></td>
		<td>' + isnull(Organization,'') + '</td><td>' + isnull(Batch,'') + '</td><td>' + isnull(Code,'') + '</td><td>' + isnull(Name,'') + '</td>
		<td>' + isnull(ClassName,'') + '-' + isnull(DivisionName,'') + '</td><td>' + isnull(StatusName,'') + '</td></tr>'	
		from sStudent.tTempStudent1,#STUDENTTEMP
		where t_StudentId = StudentId and tid between ((@lPageSize * (@rPageIndex - 1)) + 1) AND (@lPageSize * @rPageIndex)
		order by tid
	END
	ELSE
	BEGIN
	select @lResult = @lResult + '<tr><td><a style="cursor:pointer;" onclick="SelectStudent(' + convert(varchar,StudentId) + ',''' + isnull(Code,'') + ''')">Select</a></td>
	<td>' + isnull(Organization,'') + '</td><td>' + isnull(Batch,'') + '</td><td>' + isnull(Code,'') + '</td><td>' + isnull(Name,'') + '</td>
	<td>' + isnull(ClassName,'') + '-' + isnull(DivisionName,'') + '</td><td>' + isnull(StatusName,'') + '</td></tr>'	
	from sStudent.tTempStudent1,#STUDENTTEMP
	where t_StudentId = StudentId and tid between ((@lPageSize * (@rPageIndex - 1)) + 1) AND (@lPageSize * @rPageIndex)
	order by tid
	END
	select @lResult as StudentList,@lPaging as Paging,@lTotalRecords as TotalRecords
	
	DROP Table sStudent.tTempStudent1
	DROP Table sStudent.tTempStudent2
	DROP Table sStudent.tTempStudent3
	DROP Table sStudent.tTempStudent4
	DROP Table sStudent.tTempStudent8
	DROP Table sStudent.tTempStudent9
	DROP Table sStudent.tTempStudent10
	DROP Table sStudent.tTempStudent11
	DROP Table sStudent.tTempStudent12
	DROP Table sStudent.tTempStudent13
	DROP Table sStudent.tTempStudent14
	
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

	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
			,Sum(FRD.Amount) AS Amount
			,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(@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(FHM.Title, '')), '[FeeHeadAmount]', isnull(Convert(NVARCHAR(100), Sum(FRD1.Amount)), '0.00')), '[CollectionGroupName]', isNull(CGM1.Title, '')), 
											'[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
								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
			,FR.PayTypeId AS PayTypeId
			,FHM.Id AS FeeId
			,0 AS ReceiptId
		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
		ORDER BY ReceiptDate DESC
	END
	ELSE IF @lTallyPostingType = 'FeeHeadWiseCustom'
	BEGIN
		SELECT ReceiptDate
			,FR.Id AS FeeName
			,PM.Title AS PayType
			,Sum(FRD.Amount) AS Amount
			,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(@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, '')), 
											'[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
								FOR XML PATH('')
								), 1, 1, '')
				ELSE SM.Name + '(' + ClassName + ':' + DivisionName + ') ' + ' # Cheque No. :' + ISNULL(FR.ChequeNo, '') + ' BankName :' + ISNULL(FR.BankName, '')
				END AS Narration
			,FR.PayTypeId AS PayTypeId
			,0 AS FeeId
			,FR.Id AS ReceiptId
		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, '')
		ORDER BY FR.Id
			,ReceiptDate DESC
	END
	ELSE IF @lTallyPostingType = 'OrgMainGroupWise'
	BEGIN
		SELECT ReceiptDate
			,SM.AcademicId AS FeeName
			,PM.Title AS PayType
			,Sum(FRD.Amount) AS Amount
			,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(@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, '')), 
											'[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
								FOR XML PATH('')
								), 1, 1, '')
				ELSE SM.Name + '(' + ClassName + ':' + DivisionName + ') ' + ' # Cheque No. :' + ISNULL(FR.ChequeNo, '') + ' BankName :' + ISNULL(FR.BankName, '')
				END AS Narration
			,FR.PayTypeId AS PayTypeId
			,FR.Id AS FeeId
			,SM.AcademicId AS ReceiptId
		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, '')
		ORDER BY FR.Id
			,ReceiptDate DESC
	END
	ELSE IF @lTallyPostingType = 'ReceiptWise'
	BEGIN
		SELECT ReceiptDate
			,ISNULL(SLM.LedgerName, '') AS FeeName
			,PM.Title AS PayType
			,FR.ReceiptAmount AS Amount
			,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(@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, '')), 
											'[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
								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,					
			FR.PayTypeId AS PayTypeId
			,A.StudentId AS FeeId
			,FRD.ReceiptId
		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
			,Sum(FRD.Amount) AS Amount
			,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(@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, '')), 
											'[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
								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
			,FR.PayTypeId AS PayTypeId
			,FHM.Id AS FeeId
			,0 AS ReceiptId
		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
		--,FHM.Title
		ORDER BY ReceiptDate DESC
	END
	ELSE IF @lTallyPostingType = 'FeeHeadWiseReceipt_AllDetail'
	BEGIN
		SELECT ReceiptDate
			,FR.Id AS FeeName
			,PM.Title AS PayType
			,Sum(FRD.Amount) AS Amount
			,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(@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, '')), '[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
								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
			,FR.PayTypeId AS PayTypeId
			,FR.Id AS FeeId
			,FR.Id AS ReceiptId
		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, '')
		ORDER BY FR.Id
			,ReceiptDate DESC
	END
END
GO
PRINT N'Altering Procedure [sTimetable].[pTimeTableXMLAdd]...';


GO
ALTER PROCEDURE [sTimetable].[pTimeTableXMLAdd] 
	@rOrgGroupId INT
	,@rXMLDoc [nvarchar] (max)
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
		BEGIN TRANSACTION
		
		DECLARE @lInterrorCode INT,@loDoc INT
		DECLARE @lNextNumber BIGINT	

		EXECUTE @lInterrorCode = sp_xml_preparedocument @loDoc OUTPUT, @rXMLDoc
		
		DELETE TT
		FROM sTimeTable.tTimeTable TT
		INNER JOIN sTimeTable.tTimeTableSchema TTS ON TT.TimeTableSchemaID = TTS.Id
		INNER JOIN sSetup.tOrgGroupBatchMaster OGB ON TTS.OrgGroupBatchId = OGB.Id
		INNER JOIN (
			SELECT DISTINCT TimeTableSchemaId
			FROM OPENXML(@loDoc, '/Table/TimeTable', 1) WITH (TimeTableSchemaId INT)
			) OXM ON OXM.TIMETABLESCHEMAID = TTS.ID
			AND OGB.OrgGroupId = @rOrgGroupId

		SELECT
			ROW_NUMBER() OVER(ORDER BY Id) AS AutoId,
			Id,
			TimeTableSchemaId,
			EmployeeId,
			DivisionId,
			SubjectId,					 
			DayId,
			LectureNumber,
			LockNo,
			LockColour,
			SchoolRoomId,
			IsBreak			
		INTO #TempTimeTable
		FROM OPENXML (@loDoc, '/Table/TimeTable', 1)
		WITH 
		( 
			Id bigint,
			TimeTableSchemaId int,
			EmployeeId bigint,
			DivisionId int,
			SubjectId int,
			DayId tinyint,
			LectureNumber tinyint,
			LockNo bigint,
			LockColour varchar(50),
			SchoolRoomId int,
			IsBreak bit
		)

		DECLARE @lCount int,@lId int
		SELECT @lCount = COUNT(Id) FROM #TempTimeTable
		SELECT Top 1 @lId = AutoId FROM #TempTimeTable 
		
		WHILE (@lId <= @lCount)
		BEGIN
			DECLARE @lOrgId int 
			SELECT @lOrgId = LEFT(DivisionId, 4) FROM #TempTimeTable WHERE AutoId = @lId
			EXECUTE sCommon.pTableRowIdGet @lOrgId, 'sTimetable.tTimeTable', 0, 1, 1,@outNextNumber = @lNextNumber OUTPUT 

			INSERT INTO sTimetable.tTimeTable (
				Id
				,TimeTableSchemaId
				,EmployeeId
				,DivisionId
				,SubjectId
				,DayId
				,LectureNumber
				,LockNo
				,LockColour
				,SchoolRoomId
				,IsBreak
				)
			SELECT
				@lNextNumber,
				tmp.TimeTableSchemaId,
				tmp.EmployeeId,
				tmp.DivisionId,
				tmp.SubjectId,
				tmp.DayId,
				tmp.LectureNumber,
				tmp.LockNo,
				tmp.LockColour,
				tmp.SchoolRoomId,
				tmp.IsBreak
			FROM #TempTimeTable tmp
			WHERE AutoId = @lId

			SET @lId = @lId + 1
		END

		EXEC sp_xml_removedocument @loDoc
		SELECT 1 AS Result
		DROP TABLE #TempTimeTable
		COMMIT TRANSACTION
	END TRY
	BEGIN CATCH
		ROLLBACK TRANSACTION
		SELECT - 1 AS Result
	END CATCH
END
GO
PRINT N'Altering Procedure [sTimetable].[pWebGetSuggestedSubjectList]...';


GO
ALTER PROCEDURE [sTimetable].[pWebGetSuggestedSubjectList] --991100006,9911,991100001,991100002,0,9911000000065,0,0
	@rSchemaId INT,
	@rOrgId INT,
	@rClassId INT,
	@rDivisionId INT,
	@rSubjectId INT,
	@rEmployeeId BIGINT,
	@rFromFilter INT,
	@rToFilter INT
AS
BEGIN
    SELECT
        TW.SubjectId,
        S.Title AS Subject,
        D.Code AS Division,
        D.Id AS DivisionId,
        T.ShortName AS Teacher,
        T.Id AS TeacherId,
        (T.FirstName +' - '+ S.Title) AS Code,
        TW.NoOfLecture AS Total,
        (TW.NoOfLecture - (
            SELECT COUNT(LectureNumber)
            FROM sTimetable.tTempSTimeTable
            WHERE  DivisionId = TW.DivisionId 
            AND TimeTableSchemaId = TW.TimeTableSchemaId  AND EmployeeId=T.Id and SubjectId = TW.SubjectId
        )) AS Remain

		
    FROM
        sTimetable.tTeacherWorkLoad TW
    INNER JOIN
        sHrm.tEmployeeMaster T ON TW.EmployeeId = T.Id
    INNER JOIN
        sSetup.tSubjectMaster S ON S.Id = TW.SubjectId
    INNER JOIN
        sSetup.tDivisionMaster D ON D.Id = TW.DivisionId
    INNER JOIN
        sTimetable.tTempSTimeTable TT ON TT.DivisionId = TW.DivisionId
    INNER JOIN 
        sTimetable.tAssignOrg AO ON AO.TimeTableSchemaId = TT.TimeTableSchemaId
    WHERE
        TW.TimeTableSchemaId = @rSchemaId 
        AND (D.OrgId=@rOrgId OR @rOrgId = 0)
        AND (TW.SubjectId=@rSubjectId OR @rSubjectId = 0)
        AND (D.ClassId= @rClassId OR @rClassId = 0)
        AND (Tw.DivisionId = @rDivisionId OR @rDivisionId = 0)
        AND (TW.EmployeeId=@rEmployeeId OR @rEmployeeId = 0)
        AND (TT.LectureNumber>@rFromFilter OR @rFromFilter=0)
        AND (TT.LectureNumber<@rToFilter OR @rToFilter=0)
    GROUP BY
		tw.Timetableschemaid,
		tw.DivisionId,
        TW.SubjectId,
        S.Title,
        D.Code,
        D.Id,
        T.ShortName,
        T.Id,
        (T.FirstName +' - '+ S.Title),
        TW.NoOfLecture;
END
GO
PRINT N'Altering Procedure [sTransport].[pTrackBusRouteGet]...';


GO
ALTER PROCEDURE [sTransport].[pTrackBusRouteGet]
	@rSourceId bigint,
	@rOrgGroupBatchId int
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	SELECT		  
		  ISNULL(VTSSubUserPassword,'') AS VTSSubUserPassword,
		  ISNULL(VTSSubUserName,'') AS VTSSubUserName,
		  ISNULL(BRM.TrackingURL,'') AS TrackingURL,
		  'PickUp' AS RouteType,
		  ISNULL(RegistrationNumber, '') AS VehicleRegistrationNo
	FROM
		sTransport.tAssignRoute AR
		INNER JOIN sTransport.tBusRouteDestinationMaster BRDM ON BRDM.Id=AR.PickupDestinationId
        INNER JOIN sTransport.tBusRouteMaster BRM On BRM.Id=BRDM.BusRouteId
		LEFT JOIN sTransport.tVehicleMaster VM ON VM.Id = BRM.VehicleId
	WHERE 
		SourceId=@rSourceId 
		AND SourceTypeId=2003
		AND OrgGroupBatchId=@rOrgGroupBatchId

	UNION

	SELECT		  
		  ISNULL(VTSSubUserPassword,'') AS VTSSubUserPassword,
		  ISNULL(VTSSubUserName,'') AS VTSSubUserName,
		  ISNULL(BRM.TrackingURL,'') AS TrackingURL,
		  'Drop' AS RouteType,
		  ISNULL(RegistrationNumber, '') AS RegistrationNumber
	FROM
		sTransport.tAssignRoute AR
		INNER JOIN sTransport.tBusRouteDestinationMaster BRDM ON BRDM.Id=AR.DropDestinationId
        INNER JOIN sTransport.tBusRouteMaster BRM On BRM.Id=BRDM.BusRouteId
		LEFT JOIN sTransport.tVehicleMaster VM ON VM.Id = BRM.VehicleId
	WHERE 
		SourceId=@rSourceId 
		AND SourceTypeId=2003
		AND OrgGroupBatchId=@rOrgGroupBatchId
END
GO
PRINT N'Creating Procedure [sAccounting].[pVoucherListWithBalanceGet]...';


GO
CREATE PROCEDURE [sAccounting].[pVoucherListWithBalanceGet]

	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='',
	 @rVoucherTypeId int = 0,
	 @rTransactionDate Date,
	 @rTransactionDateTo Date,
	 @rVoucherNumber int,
	 @rVoucherNumberTo int,
	 @rLedgerId int,
	 @rNarration nvarchar(100),
	 @rAmount Decimal(20,5),
	 @rAccountingYearId int = 0,
	 @rIsApproved bit=0

	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON


BEGIN

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

	  Declare @DecimalCount INT,@lOrgGroupId Int
	  select @lOrgGroupId = OrgGroupId from sAccounting.tTransaction T where AccountingYearId = @rAccountingYearId

	 SELECT @DecimalCount = CASE WHEN CS.Id IS NOT NULL THEN ISNULL(CS.ItemValue,'') ELSE ISNULL(CM.ItemValue,'') END
						  FROM sConfig.tConfigurationMaster CM
						  LEFT JOIN sConfig.tConfigurationSetup CS ON CM.Id = CS.ConfigurationId
						  AND SourceTypeId = 2010 AND SourceId = @lOrgGroupId WHERE CM.Id = 548

	CREATE TABLE #tempTransaction
	(
		AutoId INT PRIMARY KEY Identity(1,1),
		Builder1 nvarchar(max),
		Builder2 nvarchar(max),
		Id bigint,
		VoucherType nvarchar(100),
		VoucherNo bigint,
		VoucherDate date,
		Ledger nvarchar(100),
		Credit decimal(25,5),
		Debit decimal(25,5),
		Narration nvarchar(150),
		OrgTitle nvarchar(200),
		SmallAddress1 nvarchar(200),
		SmallAddress2 nvarchar(200),
		TransactionApproveId bigint
	)

	INSERT INTO #tempTransaction
	SELECT	@rBuilder1 AS Builder1
			,@rBuilder2 AS Builder2
			,T.Id
			,VTM.Title AS VoucherType
			,T.VoucherNumber AS VoucherNo
			,T.TransactionDate AS VoucherDate
			,LM.Title AS Ledger
			,([sAccounting].[fDecimalValueGet] ((CASE WHEN ISNULL(TD.Amount,0) < 0 THEN ISNULL(TD.Amount,0) * -1 
			ELSE 0 END), @DecimalCount)) Credit
			,([sAccounting].[fDecimalValueGet] ((CASE WHEN ISNULL(TD.Amount,0) > 0 THEN ISNULL(TD.Amount,0) 
			ELSE 0 END),@DecimalCount)) Debit
			,T.Narration AS Narration
			,AM.ReportOrgTitle As OrgTitle
			,AM.SmallAddress1 AS SmallAddress1
			,AM.SmallAddress2 AS SmallAddress2,
			T.TransactionApproveId
	FROM
		sAccounting.tTransaction T
          INNER JOIN sAccounting.tTransactionDetail TD ON T.Id=TD.TransactionId
          INNER JOIN sAccounting.tVoucherTypeMaster VTM ON VTM.Id = T.VoucherTypeId
          INNER JOIN sAccounting.tLedgerMaster LM ON LM.Id=TD.LedgerId
          INNER JOIN sAccounting.tAccountMaster AM ON AM.Id=T.AccountId
	WHERE
				(T.VoucherTypeId=@rVoucherTypeId OR @rVoucherTypeId = 0)
			AND ((T.Narration like @rNarration) OR (ISNULL(@rNarration,'') = ''))
			AND (T.TransactionDate >= @rTransactionDate OR ISNULL(@rTransactionDate,'') = '')
			And (T.TransactionDate <= @rTransactionDateTo OR ISNULL(@rTransactionDateTo,'') = '')
			AND (T.VoucherNumber >= @rVoucherNumber OR @rVoucherNumber=0)
			AND (T.VoucherNumber <=@rVoucherNumberTo OR @rVoucherNumberTo=0)
			AND (TD.LedgerId = @rLedgerId OR @rLedgerId=0)
			AND (TD.Amount = @rAmount OR ISNULL(@rAmount,0) = 0)
			AND LM.AccountingYearId = @rAccountingYearId
			AND T.AccountingYearId = @rAccountingYearId
			AND ((@rIsApproved=1 AND  ISNULL(T.TransactionApproveId,0) !=0) OR (@rIsApproved = 0))
	Order By T.TransactionDate,T.VoucherNumber;

	--select * from #tempTransaction

--Common Table Expression
	WITH RunningBalance AS (
		SELECT	AutoId,
				Builder1,
				Builder2,
				Id,
				VoucherType,
				VoucherNo,
				VoucherDate,
				Ledger,
				([sAccounting].[fDecimalValueGet] (Credit,@DecimalCount)) AS Credit,
				([sAccounting].[fDecimalValueGet] (Debit,@DecimalCount)) AS Debit,
				Narration,
				OrgTitle,
				SmallAddress1,
				SmallAddress2,
				TransactionApproveId,
				(Debit - Credit) AS net_amount,
				([sAccounting].[fDecimalValueGet] ((SELECT	SUM(Debit - Credit) 
				FROM #tempTransaction AS inner_trans
				WHERE inner_trans.AutoId <= outer_trans.AutoId),@DecimalCount)) AS Balance
		FROM
			#tempTransaction AS outer_trans
	)

	SELECT	Builder1,
			Builder2,
			Id,
			VoucherType,
			VoucherNo,
			VoucherDate,
			Ledger,
			Credit,
			Debit,
			Narration,
			OrgTitle,
			SmallAddress1,
			SmallAddress2,
			TransactionApproveId,
			Balance
	FROM
		RunningBalance

	drop table #tempTransaction
END

--SELECT	'' AS Builder1,
--		'' AS Builder2,
--		CAST(0 AS bigint) AS Id,
--		'' AS VoucherType,
--		CAST(0 AS bigint) AS VoucherNo,
--		CAST('' AS date) AS VoucherDate,
--		'' AS Ledger,
--		0.00 AS Credit,
--		0.00 AS Debit,
--		'' AS Narration,
--		'' AS OrgTitle,
--		'' AS SmallAddress1,
--		'' AS SmallAddress2,
--		CAST(0 AS bigint) AS TransactionApproveId,
--		0.00 AS Balance

--END
GO
PRINT N'Creating Procedure [sAlert].[pAdmissionInquiryFollowupGet]...';


GO
CREATE PROCEDURE [sAlert].[pAdmissionInquiryFollowupGet]
	
	 @rFromDate date='',
	 @rToDate date='',
	 @rOrgId Smallint=0,
	 @rBatchId int = 0,
     @rTemplate nvarchar(max),
	 @rSubject nvarchar(100)=''	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
	SELECT  
	AF.Id,
	AI.ForBatchId AS BatchId,
	AI.ForClassId AS ClassId,
	AI.OrgId AS OrgId,
	AI.OrgId AS OrgGroupId,
	AI.Number AS InquiryNumber,
	ISNULL(AF.FollowupDate,'') AS  FollowupDate,
	AI.LastName +' ' +AI.FirstName+' '+AI.MiddleName as Name,
	AI.ContactNo AS MobileNo,
	AI.ContactEmail AS EmailId
	,REPLACE (
	 REPLACE (
	 REPLACE (
	 REPLACE(@rTemplate,'[Name]',AI.LastName +' ' +AI.FirstName+' '+AI.MiddleName),
	 '[Organization]',ISNULL(OM.DisplayTitle,'')),
	 '[InquiryNumber]', ISNULL(AI.Number,0)),
	 '[FollowupDate]', CONVERT(VARCHAR(10), AF.FollowupDate, 103))
	  AS Template
	 ,@rSubject AS Subject
	 ,AI.ContactNo AS MobileNo
	 ,AI.ContactNo AS WhatsAppContactNo
	 ,AI.ContactEmail AS EmailId
	 ,ISNULL(AF.Id,0) AS SourceId
	 ,CONVERT(smallint,0) AS SourceTypeId
	 ,ISNULL(AF.Id,0) AS ReceiverSourceId
	 ,CONVERT(smallint,0) AS ReceiverSourceTypeId
	
  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  ((AI.OrgId=@rOrgId) OR (@rOrgId=0))
      AND ((AF.FollowupDate>= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
	  AND ((AF.FollowupDate<= @rToDate) OR (ISNULL(@rToDate,'')=''))
      AND (AI.ForBatchId=@rBatchId)
	  Order by AF.FollowupDate DESC 
END
GO
PRINT N'Creating Procedure [sAlert].[pNewAdmissionInquiryGet]...';


GO
CREATE PROCEDURE [sAlert].[pNewAdmissionInquiryGet]
	 @rClassId int = 0,
	 @rBatchId int = 0,
	 @rStatusId int =0,
	 @rOrgId int,
	 @rFromDate datetime=Null,
	 @rToDate datetime=Null,
	 @rDepartmentId int = 0,
	 @rTemplate nvarchar(max),
	 @rSubject nvarchar(100)=''
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
	
	SELECT
		 AI.ForBatchId AS BatchId
		,AI.ForClassId AS ClassId
		,AI.InquiryStatusId AS StatusId
		,AI.OrgId
		,AI.OrgGroupId
		,ISNULL(AI.Number,0) AS InquiryNumber
		,ISNULL(AI.InquiryDate,'') AS InquiryDate
		,ISNULL(CM.Title,'') AS ClassName
		,[sStudent].[fStudentNameGet](AI.FirstName , ISNULL(AI.MiddleName,'') , AI.LastName,OM.StudentNameFormatId ) AS StudentName
		,AI.LastName +' ' +AI.FirstName+' '+AI.MiddleName as Name
		,REPLACE (
		REPLACE (
		REPLACE (
	    REPLACE (
		REPLACE (
		REPLACE(@rTemplate,'[Name]',AI.LastName +' ' +AI.FirstName+' '+AI.MiddleName),
		'[Organization]',ISNULL(OM.DisplayTitle,'')),
		'[Class]',ISNULL(CM.Title,'')),
		'[InquiryNumber]', ISNULL(AI.Number,0)),
		'[InquiryDate]', CONVERT(VARCHAR(10), AI.InquiryDate, 103)),
		'[InquiryStatus]', ISNULL(SM.Title,''))
		 AS Template
		,@rSubject AS Subject
		,AI.ContactNo AS MobileNo
		,AI.ContactEmail AS EmailId
		,ISNULL(AI.Id,0) AS SourceId
		,CONVERT(smallint,0) AS SourceTypeId
		,ISNULL(AI.WhatsAppContactNo,'') AS WhatsAppContactNo
		,0 AS ReceiverSourceTypeId
		,ISNULL(AI.Id,0) AS ReceiverSourceId
		,ISNULL(OM.DisplayTitle,'') AS Organization
	FROM 

		sAdmission.tAdmissionInquiry AI
		INNER JOIN sAdmission.tInquiryStatusMaster SM ON SM.Id=AI.InquiryStatusId 
		INNER JOIN sSetup.tClassMaster CM ON CM.Id=AI.ForClassId
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=AI.OrgId
		INNER JOIN sSetup.tBatchMaster BM ON AI.ForBatchId = BM.Id
		LEFT JOIN sAdmission.tAdmissionInquiryCriteria AIC ON AIC.ClassId=AI.ForClassId AND AIC.BatchId=AI.ForBatchId 
  WHERE   
		(AI.OrgId=@rOrgId OR @rOrgId=0)
	  AND ((AI.ForBatchId=@rBatchId) OR (@rBatchId=0))
	  AND ((CM.DepartmentId=@rDepartmentId) or (@rDepartmentId = 0))
	  AND ((AI.ForClassId=@rClassId) OR (@rClassId=0))
	  AND (AI.InquiryStatusId  = @rStatusId OR @rStatusId = 0)
	  AND ((AI.InquiryDate>= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
      AND ((AI.InquiryDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))		    
END
GO
PRINT N'Creating Procedure [sAppraisal].[pRptAppraisalReport]...';


GO
CREATE PROCEDURE [sAppraisal].[pRptAppraisalReport]

		@rOrgId SMALLINT=0,
		@rBatchId INT=0,
		@rAppraisalTypeId INT=0,
		@rEmployeeId BIGINT=0,
		@rDepartmentId INT=0

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

	SELECT	EMP.Id,
			EMP.Code,
			EMP.FirstName + ' ' + EMP.LastName AS EmployeeName,
			R.MyRating AS EmployeeRating,
			KER.Remark AS EmployeeRemark,
			R.ManagerRating,
			KER.RecommendationDesignation AS ManagerRemark,
			KER.BusinessHeadRating AS OHRating,
			KER.BusinessHeadRecommendationDesignation AS OHRemark

	FROM [sHrm].[tEmployeeMaster] AS EMP
		INNER JOIN sHrm.vEmployeeCommonDetail AS ECD ON ECD.EmployeeId = EMP.Id   
		LEFT JOIN [sAppraisal].[tKPAEmployee] AS KPA ON KPA.EmployeeId=EMP.Id
		LEFT JOIN [sAppraisal].[tKPAEmployeeRating] AS KER ON KER.KPAEmployeeId=KPA.Id
		LEFT JOIN 
				(
					SELECT KER.KPAEmployeeId,KRD.KPAEmployeeRatingId,CONVERT(DECIMAL(18,2),AVG(KRD.ManagerRating))ManagerRating,CONVERT(DECIMAL(18,2),AVG(KRD.MyRating))MyRating
					FROM [sAppraisal].[tKPAEmployeeRating] AS KER
						INNER JOIN [sAppraisal].[tKPAEmployeeRatingDetail] AS KRD ON KRD.KPAEmployeeRatingId=KER.Id
					GROUP BY KER.KPAEmployeeId,KRD.KPAEmployeeRatingId
				) AS R ON R.KPAEmployeeId=KPA.Id AND R.KPAEmployeeRatingId=KER.Id

	WHERE ((EMP.OrgID=@rOrgId)OR(@rOrgId=0))
		AND EMP.StatusId=7
		AND ((EMP.Id=@rEmployeeId) OR (ISNULL(@rEmployeeId,0)=0))
		AND KPA.BatchId=@rBatchId
		AND KER.AppraisalTypeId=@rAppraisalTypeId
		AND ISNULL(EMP.IsOtherUser,0) = 0
		AND ((ECD.DepartmentId=@rDepartmentId) OR (ISNULL(@rDepartmentId,0)=0))
	ORDER BY EMP.FirstName, EMP.Code
END
GO
PRINT N'Creating Procedure [sCertificate].[pRptBonafiedCertificateTemplateWiseGet]...';


GO


CREATE PROCEDURE [sCertificate].[pRptBonafiedCertificateTemplateWiseGet]
	 
	 @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,
	 @rPrintTemplateId int = 0
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
	
	DECLARE @lTemplate nvarchar(max) = '' 
	SELECT @lTemplate = Template FROM sCertificate.tPrintTemplate WHERE PrintTemplateFunctionalityId = 2 AND Id = @rPrintTemplateId
	
	SELECT 	
			@rBuilder1 AS Builder1,
		    @rBuilder2 AS Builder2,
			B.Id AS BonafideId,
			A.Id AS Academic,
			[sCertificate].[fBonafideCertificateTemplate](A.Id, A.BatchId, @lTemplate) AS Template
		
	FROM 
			sCertificate.tBonafide B		
			INNER JOIN sStudent.tAcademic A ON B.AcademicId=A.Id
			INNER JOIN sStudent.tStudentMaster SM ON SM.Id=A.StudentId
		
	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.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,'')=''))
	END
GO
PRINT N'Creating Procedure [sCertificate].[pRptCharacterCertificateTemplateWiseGet]...';


GO
CREATE PROCEDURE [sCertificate].[pRptCharacterCertificateTemplateWiseGet]
	 
	 @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)='',
	 @rPrintTemplateId int = 0
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
	
	DECLARE @lTemplate nvarchar(max) = '' 
	SELECT @lTemplate = Template FROM sCertificate.tPrintTemplate WHERE PrintTemplateFunctionalityId = 3 AND Id = @rPrintTemplateId

	SELECT 
			@rBuilder1 AS Builder1,
		    @rBuilder2 AS Builder2,
			C.Id AS CharacterId,
			C.AcademicId,
			[sCertificate].[fCharacterCertificateTemplate](A.Id, A.BatchId, @lTemplate) AS Template

	FROM 
			sCertificate.tCharacter C
			INNER JOIN sStudent.tAcademic A ON C.AcademicId=A.Id
			INNER JOIN sStudent.tStudentMaster SM ON SM.Id=A.StudentId

	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 ((C.Number=@rNumber) OR (@rNumber=''))
		AND ((C.Number >= @rFromNo) OR (@rFromNo=''))
		AND ((C.Number <= @rToNo) OR (@rToNo=''))
		AND ((C.characterDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
		AND ((C.characterDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
	END
GO
PRINT N'Creating Procedure [sCertificate].[pRptFirstTrialCertificateTemplateWiseGet]...';


GO
CREATE PROCEDURE [sCertificate].[pRptFirstTrialCertificateTemplateWiseGet]
	 
	 @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)='',
	 @rPrintTemplateId int = 0
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

DECLARE @lTemplate nvarchar(max) = '' 
	SELECT @lTemplate = Template FROM sCertificate.tPrintTemplate WHERE PrintTemplateFunctionalityId = 4 AND Id = @rPrintTemplateId

	SELECT
			@rBuilder1 AS Builder1,
		    @rBuilder2 AS Builder2,
			FT.Id AS FirstTrialId,
			FT.AcademicId,
			[sCertificate].[fFirstTrialCertificateTemplate](A.Id, A.BatchId, @lTemplate) AS Template
	FROM
			sCertificate.tFirstTrial FT
			INNER JOIN sStudent.tAcademic A ON FT.AcademicId=A.Id
			INNER JOIN sStudent.tStudentMaster SM ON SM.Id=A.StudentId
			
	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 ((FT.FirstTrialDate>=@rFromDate) OR (ISNULL(@rFromDate,'')=''))
			AND ((FT.FirstTrialDate<=@rToDate) OR (ISNULL(@rToDate,'')=''))
			AND ((FT.Number=@rNumber) OR (@rNumber=''))
			AND ((FT.Number >= @rFromNo) OR (@rFromNo=''))
			AND ((FT.Number <= @rToNo) OR (@rToNo=''))
	END
GO
PRINT N'Creating Procedure [sCertificate].[pRptLeavingCertificateTemplateWiseGet]...';


GO

CREATE PROCEDURE [sCertificate].[pRptLeavingCertificateTemplateWiseGet]
	 
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 @rOrgId int,
	 @rBatchId int,
	 @rFromNo nvarchar(20)='',
	 @rToNo nvarchar(20)='',
	 @rLCNumber nvarchar(20)='',
	 @rClassId int=0,
	 @rDivisionId int=0,
	 @rFromDate date='',
     @rToDate date='',
     @rCode nvarchar(20)='',
     @rName nvarchar(20)='',
	 @rUserName nvarchar(100)='',
	 @rPrintTemplateId Int = 0
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
	
	DECLARE @lTemplate nvarchar(max) = '' 
	SELECT @lTemplate = Template FROM sCertificate.tPrintTemplate WHERE PrintTemplateFunctionalityId = 5 AND Id = @rPrintTemplateId

	SELECT
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			L.Id AS LeavingId,
			L.AcademicId,
			[sCertificate].[fLeavingCertificateTemplate](vSA.AcademicId, vSA.BatchId, @lTemplate) AS Template
		                                    
	FROM 
			sCertificate.tLeaving L
			INNER JOIN sStudent.vStudentAcademic vSA ON vSA.AcademicId=L.AcademicId
			INNER JOIN sStudent.tStudentMaster SM ON SM.Id=vSA.StudentId			
			INNER JOIN sSetup.tDivisionMaster DM ON vSA.DivisionId = DM.Id  
			
	WHERE 
				L.OrgId=@rOrgId
				AND	vSA.BatchId = @rBatchId 
				AND ((SM.Code = @rCode) OR (ISNULL(@rCode,'') = ''))
				AND ((SM.FirstName = @rName) OR (ISNULL(@rName,'') = ''))
				AND ((L.LCDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
				AND ((L.LCDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
				AND ((vSA.ClassId=@rClassId) OR(@rClassId=0))
				AND ((vSA.DivisionId=@rDivisionId) OR (@rDivisionId=0))
				AND ((L.LCNumber=@rLCNumber) OR (@rLCNumber=''))
				AND ((L.LCNumber >= @rFromNo) OR (@rFromNo=''))
				AND ((L.LCNumber <= @rToNo) OR (@rToNo=''))
				AND ((DM.ClassId=@rClassId) OR(@rClassId=0))
END
GO
PRINT N'Creating Procedure [sFee].[pPostDatedPaymentUpdate]...';


GO
CREATE PROCEDURE sFee.pPostDatedPaymentUpdate 
	@rId BIGINT
	,@rDepositedDate DATETIME
	,@rStatusId smallint

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
		BEGIN TRANSACTION
			IF(@rStatusId > 0)
			BEGIN
				UPDATE sFee.tPostDatePayment
				SET DepositedDate = @rDepositedDate
				,StatusId = @rStatusId
				WHERE Id = @rId
			END
			ELSE
			BEGIN
				UPDATE sFee.tPostDatePayment
				SET DepositedDate = @rDepositedDate
				WHERE Id = @rId
			END

			SELECT 1 AS RESULT

		COMMIT TRANSACTION
	END TRY

	BEGIN CATCH
		ROLLBACK TRANSACTION
		SELECT - 1 AS Result
	END CATCH
END
GO
PRINT N'Creating Procedure [sStudent].[pStudentCustomFieldIdGet]...';


GO
CREATE PROCEDURE [sStudent].[pStudentCustomFieldIdGet]
	@rAutoId int
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	
BEGIN 
	SELECT 
		distinct
		SCM.Id AS CustomFieldId,
		SCM.FieldTitle as FieldRemark,
		SCM.FieldTypeId,
		SCM.FieldList,
		SCM.IsFieldMandatory,
		SCM.FieldGroup,
		SCM.FieldOrder
	
	FROM sStudent.tStudentCustomFieldMaster SCM
		INNER JOIN sStudent.tOnlineRegistrationCriteriaForm ORCF on SCM.FieldTitle=ORCF.FieldRemark 
					AND SCM.FieldGroup=ORCF.FieldGroup AND SCM.FieldTypeId = ORCF.FieldTypeId
		INNER JOIN sStudent.tOnlineRegistrationStudentCustomFieldData ORSC ON ORCF.Id= ORSC.StudentCustomFieldId
		where ORSC.AutoId = @rAutoId		
END

GO
PRINT N'Update complete.';


GO

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

