

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

PRINT N'Dropping Procedure [sAssessment].[pReportHistoryAdd]...';


GO
DROP PROCEDURE [sAssessment].[pReportHistoryAdd];


GO
PRINT N'Dropping Procedure [sAssessment].[pReportHistoryGet]...';


GO
DROP PROCEDURE [sAssessment].[pReportHistoryGet];


GO
PRINT N'Dropping Table [sAssessment].[tReportHistory]...';


GO
DROP TABLE [sAssessment].[tReportHistory];


GO



PRINT N'Altering Table [sAlert].[tAlertQueueLog]...';


GO
ALTER TABLE [sAlert].[tAlertQueueLog]
    ADD [TokenId] UNIQUEIDENTIFIER NULL;


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


GO
ALTER TABLE [sAssessment].[tTempAllExam]
    ADD [IsPercentage1]  BIT NULL,
        [IsPercentage2]  BIT NULL,
        [IsPercentage3]  BIT NULL,
        [IsPercentage4]  BIT NULL,
        [IsPercentage5]  BIT NULL,
        [IsPercentage6]  BIT NULL,
        [IsPercentage7]  BIT NULL,
        [IsPercentage8]  BIT NULL,
        [IsPercentage9]  BIT NULL,
        [IsPercentage10] BIT NULL,
        [IsPercentage11] BIT NULL,
        [IsPercentage12] BIT NULL,
        [IsPercentage13] BIT NULL;


GO

PRINT N'Altering Table [sFee].[tReceipt]...';


GO
ALTER TABLE [sFee].[tReceipt]
    ADD [TaxPercentage] DECIMAL (5, 2) NULL;


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


GO
ALTER TABLE [sFee].[tReceiptBookMaster]
    ADD [TaxLabel]  NVARCHAR (50) NULL,
        [TaxTypeId] TINYINT       NULL;


GO
PRINT N'Altering Table [sOp].[tGatewayProduct]...';


GO
ALTER TABLE [sOp].[tGatewayProduct]
    ADD [RazorpaySubMerchantId] NVARCHAR (50) NULL;


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


GO
ALTER TABLE [sStudent].[tStudentCustomSearch] ALTER COLUMN [FromCode] NVARCHAR (20) NULL;

ALTER TABLE [sStudent].[tStudentCustomSearch] ALTER COLUMN [ToCode] NVARCHAR (20) NULL;


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


GO
ALTER TABLE [sStudent].[tStudentMaster]
    ADD [LocalName] NVARCHAR (100) NULL;


GO

PRINT N'Creating Table [sCommon].[tReportHistory]...';


GO
CREATE TABLE [sCommon].[tReportHistory] (
    [Id]              BIGINT         IDENTITY (1, 1) NOT NULL,
    [ScreenId]        INT            NOT NULL,
    [ReportName]      NVARCHAR (MAX) NOT NULL,
    [StatusId]        INT            NOT NULL,
    [CreatedUserId]   BIGINT         NOT NULL,
    [CreatedDateTime] DATETIME       NOT NULL,
    [UpdatedUserId]   BIGINT         NULL,
    [UpdatedDateTime] DATETIME       NULL,
    [Guid]            NVARCHAR (MAX) NULL,
    CONSTRAINT [PK_ReportHistory] PRIMARY KEY CLUSTERED ([Id] ASC)
);


GO
PRINT N'Creating Table [sFee].[tReceiptTaxDetail]...';


GO
CREATE TABLE [sFee].[tReceiptTaxDetail] (
    [ReceiptId]    BIGINT          NOT NULL,
    [FeeSetupId]   INT             NOT NULL,
    [TaxAmount]    DECIMAL (12, 2) NULL,
    [TaxTypeId]    TINYINT         NULL,
    [IsTaxInclude] BIT             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
        '[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]' As ColumnList
		--Mantis: 32199, add LocalName 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].[vPrintTemplateCharacterCertificate]...';


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


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


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


GO
ALTER VIEW [sCertificate].[vPrintTemplateStudentDetail] 
AS
	SELECT
		A.Id AS AcademicId,
		DivM.Id AS DivisionId,
		DivM.DisplayTitle AS DivisionName,
		CM.Id AS ClassId,
		CM.DisplayTitle AS ClassName,
		CM.DisplayTitle+'-'+DivM.DisplayTitle AS ClassDivision,
		DM.Id AS DepartmentId,
		DM.DisplayTitle AS DepartmentName,
		SM.FirstName AS FirstName,
		SM.MiddleName AS MiddleName,
		SM.LastName AS LastName,
		SM.Code,
		A.RollNo,
		A.BatchId,
		BM.Title AS BatchName,
		CONVERT(VARCHAR(10),SO.DateOfBirth,103) AS DateOfBirth,
		SA.PreviousSchool,
		ISNULL(GM.Title,'') AS Gender,
		SO.FamilyCast AS Caste,
		SO.FamilySubCast AS SubCaste,
		SO.BirthPlace,
		SO.BirthDateInWord AS DOBInWords,
		SA.PreviousLCDate AS PreviousLCDate,
		SA.PreviousLCResult AS PreviousLCResult,
		SA.PreviousLCNumber AS PreviousLCNumber,
		SA.AdmissionNumber AS OldGRNo,
		SA.PassingYear AS PreviousSchoolYear,
		SA.PreviousStandard AS PreviousStandard,
		SO.BirthTaluka AS BirthTaluka,
		SO.BirthState AS BirthState,
		SO.BirthCountry AS BirthCountry,
		SO.BirthDistrict AS BirthDistrict,
		ISNULL(SC.PresentStreetOne,'')+' '+ISNULL(SC.PresentStreetTwo,'')+' '+ISNULL(SC.PresentStreetThree,'')+' '+ISNULL(SC.PresentCity,'')+' '+ISNULL(SC.PresentState,'')+' '+ISNULL(SC.PresentZipCode,'') AS Address,
		SC.ParentContactNo AS ContactNo,
		SC.ParentEmail AS Email,
		ISNULL(RM.Title,'') AS Religion,
		SO.FamilyCast AS FamilyCaste,
		ISNULL(CCM.Title,'') AS CasteCategory,
		ISNULL(NM.Title,'') AS Nationality,
		ISNULL(SO.MotherTongue,'') AS MotherTongue,
		ISNULL(BGM.Title,'') As BloodGroup,
		ISNULL(SO.AdhaarNumber,'') AS AadhaarNumber,
		ISNULL(PDCM.Title,'') AS PhysicalCategory,
		SF.FatherName AS FatherName,
		SF.FatherQualification AS FatherQualification,
		SF.FatherOccupation AS FatherOccupation,
		SF.FatherContactNo AS FatherContactNo,
		SF.FatherOfficeAddress AS FatherOfficeAddress,
		SF.FatherMail AS FatherEmail,
		SF.IsFatherExStudent AS FatherExStudent,
		SF.FatherPassOutYear AS FatherPassingYear,
		SF.FatherIncome AS FatherIncome,
		SF.MotherName AS MotherName,
		SF.MotherQualification AS MotherQualification,
		SF.MotherOccupation AS MotherOccupation,
		SF.MotherContactNo AS MotherContactNo,
		SF.MotherOfficeAddress AS MotherOfficeAddress,
		SF.MotherMail AS MotherEmail,
		SF.IsMotherExStudent AS MotherExStudent,
		SF.MotherPassOutYear AS MotherPassingYear,
		SF.MotherIncome AS MotherIncome,
		SA.AdmissionDate AS AdmissionDate,
		CM1.Title AS AdmissionStandard,
		SO.UIDNumber AS UIDNumber,
		ISNULL(StuA.BankAccountHolderName,'') AS BankHolderName,
		ISNULL(StuA.BankName,'') AS BankName,
		ISNULL(StuA.BankBranch,'') AS BankBranch,
		ISNULL(StuA.BankIFSCcode,'') AS BankIFSCcode,
		ISNULL(StuA.BankAccountNumber,'') AS BankAccountNo,
		ISNULL(SI.StudentPhoto, CONVERT(VARBINARY(MAX), 0)) AS StudentPhoto,
		ISNULL(SC.WhatsAppContactNo,'') AS WhatsAppContactNo,
		GetDate() AS PrintDate, -- Change for Mantis id 29447 added "[PrintDate]"
		SM.SUId AS SUIDNumber,	--Add for Manits: 31034
		ISNULL(SM.LocalName,'') AS LocalName	--Add for Mantis: 32199
	FROM
		sStudent.tAcademic A
		INNER JOIN sStudent.tStudentMaster SM ON SM.Id=A.StudentId
		INNER JOIN sStudent.tStudentOther SO ON SO.StudentId=SM.Id
		INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId
		INNER JOIN sSetup.tDivisionMaster DivM ON DivM.Id=A.DivisionId
		INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id = CM.DepartmentId
		INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId
		LEFT JOIN sStudent.tStudentAdmission SA ON SA.StudentId=A.StudentId
		LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId = A.StudentId
		LEFT JOIN sCommon.tBloodGroupMaster BGM ON BGM.Id=SO.BloodGroupId
		LEFT JOIN sCommon.tCastCategoryMaster CCM  ON CCM.Id=SO.CastCategoryId
		LEFT JoIN sCommon.tReligionMaster RM ON RM.Id=SO.ReligionId
		LEFT JOIN sCommon.tMotherTongueMaster MT ON MT.Id = SO.MotherTongueId
		LEFT JOIN sCommon.tCountryMaster NM ON NM.Id = SO.NationalityId
		LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId = A.StudentId
		LEFT JOIN sStudent.tStudentHealth SH ON SH.StudentId = A.StudentId
		LEFT JOIN sCommon.tPhysicalDisabilityCategoryMaster PDCM ON PDCM.Id = SH.PhysicalDisabilityCategoryId
		LEFT JOIN sCommon.tGenderMaster GM ON GM.Id = SO.GenderId
		LEFT JOIN sSetup.tClassMaster CM1 ON CM1.Id=SA.AdmissionStandardId
		LEFT JOIN sStudent.tStudentAdditional StuA ON StuA.StudentId = SM.Id
		LEFT JOIN sStudent.tStudentImages SI ON SM.Id = SI.StudentId
GO
PRINT N'Altering View [sStudent].[vStudentAcademic]...';


GO

ALTER VIEW [sStudent].[vStudentAcademic]
AS
SELECT        A.Id AS AcademicId, A.ClassId, A.DivisionId, A.RollNo, A.OrgId, A.BatchId, SM.Id AS StudentId, SM.Code, ISNULL(SM.Number, 0) AS Number, SM.RegistrationNumber, SM.FirstName, SM.MiddleName, SM.LastName, 
                         sStudent.fStudentNameGet(SM.FirstName, SM.MiddleName, SM.LastName, OM.StudentNameFormatId) AS Name, CONVERT(Nvarchar(20), A.RollNo) + '-' + SM.FirstName + ' ' + SM.LastName AS RollNoName, SM.StatusId, 
                         CM.DisplayTitle AS ClassName, DM.DisplayTitle AS DivisionName, STM.Title AS StatusName, SM.RecordStatusId, DM.InchargeEmployeeId, BM.OrgGroupBatchId, ISNULL(A.AdmissionCategoryId, 0) AS AdmissionCategoryId, 
                         DM.OrderIndex AS DivisionOrder, BM.IsActive AS IsActiveBatch, BM.Title AS BatchName, ISNULL(DeptM.Id, 0) AS DepartmentId, ISNULL(DeptM.Title, '') AS DepartmentName, SM.IsBlackList, SM.BlackListReason, 
                         CM.OrderIndex AS ClassOrderIndex, ISNULL(A.ExemptionTypeId, 0) AS ExemptionTypeId, ISNULL(OM.DisplayTitle, '') AS OrganizationName, OM.StreetOne, OM.StreetTwo, OM.StreetThree, OM.ZipCode, ISNULL(SM.SUId, '') 
                         AS SUId, ISNULL(OM.ReportOrgGroupTitle, '') AS ReportOrgGroupTitle, ISNULL(OM.ReportOrgTitle, '') AS ReportOrgTitle, ISNULL(A.FeeStructureId, 0) AS FeeStructureId, SM.ReferenceSourceId, SM.StudentGroupId, 
                         SM.StudentOtherGroupId, A.BatchStatusId, A.ClassStatusId, STM1.Title AS ClassStatusName, ISNULL(SO.GenderId, 0) AS GenderId, ISNULL(A.FeesRemark, '') AS FeesRemark,
						 --Mantis Start -0031338  
						 ISNULL(SM.PENNumber, 0) AS PENNumber,
						 --Mantis End -0031338 
						 ISNULL(SM.LocalName,'') AS LocalName

FROM            sStudent.tAcademic AS A INNER JOIN
                         sStudent.tStudentMaster AS SM ON A.StudentId = SM.Id INNER JOIN
                         sSetup.tClassMaster AS CM ON CM.Id = A.ClassId INNER JOIN
                         sSetup.tDivisionMaster AS DM ON DM.Id = A.DivisionId INNER JOIN
                         sSetup.tBatchMaster AS BM ON BM.Id = A.BatchId INNER JOIN
                         sStudent.tStatusMaster AS STM ON STM.Id = SM.StatusId INNER JOIN
                         sSetup.tDepartmentMaster AS DeptM ON DeptM.Id = CM.DepartmentId INNER JOIN
                         sSetup.tOrganizationMaster AS OM ON A.OrgId = OM.Id INNER JOIN
                         sStudent.tStatusMaster AS STM1 ON STM1.Id = A.ClassStatusId LEFT OUTER JOIN
                         sStudent.tStudentOther AS SO ON SO.StudentId = SM.Id
GO

PRINT N'Altering Procedure [sAccounting].[pRptReceiptsAndPaymentsGet]...';


GO



ALTER PROCEDURE [sAccounting].[pRptReceiptsAndPaymentsGet]
		   	
	@rBuilder1 nvarchar(max)='',
	@rBuilder2 nvarchar(max)='', 
	@rStartDate Date,
	@rEndDate Date,
	@rOrgGroupId int = 0,
	@rAccountingYearId [int],
	@rAccountId  int=0
          
AS
SET NOCOUNT ON

BEGIN

DECLARE @lIsReportClient bit=0

IF EXISTS (SELECT 1 FROM [sCommon].[tReportClient] WHERE ReportId = 30724 AND OrgGroupId = @rOrgGroupId)
	SET @lIsReportClient = 1
	
	


DECLARE @1OpeningBalance DECIMAL(22,2)
DECLARE @1ClosingBalance DECIMAl(22,2)
DECLARE @1Credit DECIMAl(12,2)
DECLARE @1Debit DECIMAl(12,2)

DECLARE @Credit_Closing DECIMAl(12,2)
DECLARE @Debit_Closing DECIMAl(12,2)

SET @Debit_Closing=Isnull((select ABS(sum(td1.Amount)) from sAccounting.tTransaction T1 INNER JOIN sAccounting.tTransactionDetail TD1 
			 ON TD1.TransactionId=T1.Id WHERE T1.AccountingYearId = @rAccountingYearId AND VoucherTypeId=2	AND TransactionTypeId = 2 
			 AND (T1.TransactionDate >= @rStartDate OR ISNULL(@rStartDate,'')='') AND (T1.TransactionDate <= @rEndDate OR ISNULL(@rEndDate,'')='')),0)
SET @Credit_Closing=Isnull((select ABS(sum(td1.Amount)) from sAccounting.tTransaction T1 INNER JOIN sAccounting.tTransactionDetail TD1 
			ON TD1.TransactionId=T1.Id WHERE T1.AccountingYearId = @rAccountingYearId AND VoucherTypeId=3 AND TransactionTypeId = 1
			AND (T1.TransactionDate >= @rStartDate OR ISNULL(@rStartDate,'')='') AND (T1.TransactionDate <= @rEndDate OR ISNULL(@rEndDate,'')='')),0)

SET @1Debit=Isnull((select ABS(sum(td1.Amount)) from sAccounting.tTransaction T1 INNER JOIN sAccounting.tTransactionDetail TD1 
			 ON TD1.TransactionId=T1.Id WHERE T1.AccountingYearId = @rAccountingYearId AND VoucherTypeId=2	AND TransactionTypeId = 2 
			 AND (T1.TransactionDate < @rStartDate)),0)
SET @1Credit=Isnull((select ABS(sum(td1.Amount)) from sAccounting.tTransaction T1 INNER JOIN sAccounting.tTransactionDetail TD1 
			ON TD1.TransactionId=T1.Id WHERE T1.AccountingYearId = @rAccountingYearId AND VoucherTypeId=3 AND TransactionTypeId = 1
			AND (T1.TransactionDate < @rStartDate)),0)


     
	CREATE TABLE #tempUpdateClosingBalance
	(	
	    Id INT IDENTITY (1, 1),
		LedgerId int,
		Temp_Op_Balance decimal(12,2),
		Closing_Balance decimal(12,2),
		Transaction_Balance decimal(12,2)	    
	) 
	
	INSERT INTO #tempUpdateClosingBalance (LedgerId,Temp_Op_Balance,Closing_Balance,Transaction_Balance)
	EXEC [sAccounting].[pUpdateClosingBalance] @rStartDate,@rEndDate,@rOrgGroupId,@rAccountingYearId,0,''
	
	select @1OpeningBalance = OpeningBalance from sAccounting.tLedgerMaster where Code = '2' and AccountingYearId = @rAccountingYearId
	--SELECT @1OpeningBalance = Temp_Op_Balance,@1ClosingBalance = Closing_Balance 	FROM #tempUpdateClosingBalance 
	

	SELECT  
	L.LedgerTypeId,
	LGM.Title AS LedgerGroupTitle,
	L.Title AS LedgerTitle,
	@rBuilder1 AS Builder1,
	@rBuilder2 AS Builder2,
	T.Id AS TransactionId,	
	--Isnull((select ABS(sum(td1.Amount)) from sAccounting.tTransaction T1 INNER JOIN sAccounting.tTransactionDetail TD1 
	--		 ON TD1.TransactionId=T1.Id AND T.Id=T1.Id Inner join sAccounting.tLedgerMaster L ON L.Id=TD1.LedgerId AND L.AccountingYearId = T1.AccountingYearId 
	--		 WHERE T1.AccountingYearId = @rAccountingYearId AND VoucherTypeId=2	AND TransactionTypeId = 2),0) AS Credit,
	--Isnull((select ABS(sum(td1.Amount)) from sAccounting.tTransaction T1 INNER JOIN sAccounting.tTransactionDetail TD1 
	--		ON TD1.TransactionId=T1.Id AND T.Id=T1.Id Inner join sAccounting.tLedgerMaster L ON L.Id=TD1.LedgerId AND L.AccountingYearId = T1.AccountingYearId 
	--		WHERE T1.AccountingYearId = @rAccountingYearId	AND VoucherTypeId=3 AND TransactionTypeId = 1),0) AS Debit,
			
	Isnull((select ABS(sum(td1.Amount)) from sAccounting.tTransaction T1 INNER JOIN sAccounting.tTransactionDetail TD1 
			 ON TD1.TransactionId=T1.Id AND T.Id=T1.Id Inner join sAccounting.tLedgerMaster L ON L.Id=TD1.LedgerId AND L.AccountingYearId = T1.AccountingYearId 
			 WHERE T1.AccountingYearId = @rAccountingYearId AND VoucherTypeId=2	AND TransactionTypeId = 2),0) AS Debit,
	Isnull((select ABS(sum(td1.Amount)) from sAccounting.tTransaction T1 INNER JOIN sAccounting.tTransactionDetail TD1 
			ON TD1.TransactionId=T1.Id AND T.Id=T1.Id Inner join sAccounting.tLedgerMaster L ON L.Id=TD1.LedgerId AND L.AccountingYearId = T1.AccountingYearId 
			WHERE T1.AccountingYearId = @rAccountingYearId	AND VoucherTypeId=3 AND TransactionTypeId = 1),0) AS Credit,

	--@1OpeningBalance + @1Debit-@1Credit AS ClosingBalance,
	TD.LedgerId,
	CONVERT(nvarchar,ISNULL(T.TransactionDate,''),103) AS TransactionDate,
	T.VoucherNumber,
	T.Narration,
	VTM.Title As VoucherType,
	T.VoucherTypeId,	
	L.TITLE,
	CASE WHEN @lIsReportClient = 1 THEN (@1OpeningBalance + @1Debit-@1Credit) ELSE ISNULL(@1OpeningBalance,0) END AS OpeningBalance,
	CASE WHEN @lIsReportClient = 1 THEN ((@1OpeningBalance + @1Debit-@1Credit) + @Debit_Closing - @Credit_Closing) ELSE (@1OpeningBalance + @1Debit-@1Credit) END AS ClosingBalance,
	--ISNULL(@1OpeningBalance,0) AS OpeningBalance,	
	AM.ReportOrgTitle As OrgTitle,
	AM.SmallAddress1 AS SmallAddress1,
	AM.SmallAddress2 AS SmallAddress2,
	T.ChequeNo
	FROM 		
		sAccounting.tTransaction T 
		INNER JOIN sAccounting.tTransactionDetail TD ON TD.TransactionId=T.Id 
		INNER JOIN sAccounting.tLedgerMaster L ON L.Id=TD.LedgerId
		INNER JOIN sAccounting.tVoucherTypeMaster VTM ON VTM.Id=T.VoucherTypeId
		INNER JOIN sAccounting.tLedgerGroupMaster LGM ON LGM.Id = L.LedgerGroupId
		INNER JOIN sAccounting.tAccountMaster AM ON AM.Id=T.AccountId
	WHERE 		
		(T.TransactionDate >= @rStartDate OR ISNULL(@rStartDate,'')='')  
		AND	(T.TransactionDate <= @rEndDate OR ISNULL(@rEndDate,'')='') 
		AND(LGM.OrgGroupId = @rOrgGroupId OR @rOrgGroupId=0) 
		AND	(LGM.AccountingYearId=@rAccountingYearId or @rAccountingYearId=0) 
		AND	(T.AccountingYearId=@rAccountingYearId OR @rAccountingYearId = 0)		
		AND (L.AccountingYearId=@rAccountingYearId)
		AND (T.AccountId=@rAccountId OR @rAccountId=0)  
		AND LGM.Code not IN ( '2','3') AND VoucherTypeid in (2,3)
	
	GROUP BY 	
	TD.LedgerId,T.TransactionDate,T.VoucherNumber,T.Id,TD.TransactionTypeId,L.Title,T.VoucherTypeId,VTM.Title,T.Narration,AM.ReportOrgTitle,AM.SmallAddress1,AM.SmallAddress2,T.ChequeNo,L.LedgerTypeId,
	LGM.Title,L.Title
	ORDER BY 
	T.TransactionDate,T.VoucherNumber
END

----For Report

--ALTER PROCEDURE [sAccounting].[pRptReceiptsAndPaymentsGet]
		   	
--	@rBuilder1 nvarchar(max)='',
--	@rBuilder2 nvarchar(max)='', 
--	@rStartDate Date,
--	@rEndDate Date,
--	@rOrgGroupId int = 0,
--	@rAccountingYearId [int],
--	@rLedgerId [int],
--	@rLedgerGroupId [int],
--	@rAccountId  int=0
          
--AS
--SET NOCOUNT ON

--BEGIN
--SELECT
--	L.LedgerTypeId,
--	@rBuilder1 AS Builder1,
--	@rBuilder2 AS Builder2,
--	T.Id AS TransactionId,
--	Convert(Decimal,0) AS Credit,
--	Convert(Decimal,0) AS Debit,
--	TD.LedgerId,
--	T.TransactionDate,
--	T.VoucherNumber,
--	T.Narration,
--	VTM.Title As VoucherType,
--	T.VoucherTypeId,
--	Convert(Decimal,0) AS OpeningBalance,
--	Convert(Decimal,0) AS ClosingBalance,
--	AM.ReportOrgTitle As OrgTitle,
--	AM.SmallAddress1 AS SmallAddress1,
--	AM.SmallAddress2 AS SmallAddress2,
--	T.ChequeNo,
--	LGM.Title AS LedgerGroupTitle,
--	L.Title AS LedgerTitle,
--	LGM.Id AS LedgerGroupId

--FROM 		
--		sAccounting.tTransaction T 
--		INNER JOIN sAccounting.tTransactionDetail TD ON TD.TransactionId=T.Id --AND (TD.LedgerId <> @rLedgerId)
--		INNER JOIN sAccounting.tLedgerMaster L ON L.Id=TD.LedgerId
--		INNER JOIN sAccounting.tVoucherTypeMaster VTM ON VTM.Id=T.VoucherTypeId
--		INNER JOIN sAccounting.tLedgerGroupMaster LGM ON LGM.Id = L.LedgerGroupId
--		INNER JOIN sAccounting.tAccountMaster AM ON AM.Id=T.AccountId
--END
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,
		DM.InchargeEmployeeId 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
GO
PRINT N'Altering View [sCertificate].[vPrintTemplateTransferCertificate]...';


GO

ALTER VIEW [sCertificate].[vPrintTemplateTransferCertificate]
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,
		DM.InchargeEmployeeId AS ClassTeacher,
		vSA.BatchName AS BatchName,
		CSM.Title As CasteCategory,
		vSA.BatchId,
		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],[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
GO
PRINT N'Creating Function [sAccounting].[fDecimalValueGet]...';


GO
CREATE FUNCTION [sAccounting].[fDecimalValueGet] (@rValue decimal(20,5), @rDecimal int)
RETURNS nvarchar(200)
AS
BEGIN
	
	DECLARE @len INT, @lastNonSpacePosition INT, @return nvarchar(200)
	set	@len = LEN(@rValue)
	if(@rDecimal>0)
	BEGIN
		set @lastNonSpacePosition = @len - PATINDEX('%.%', REVERSE(@rValue)) + 1 + @rDecimal
	END
	ELSE
	BEGIN
		set @lastNonSpacePosition = @len - PATINDEX('%.%', REVERSE(@rValue))
	END
	set @return = LEFT(ROUND(@rValue, @rDecimal),@lastNonSpacePosition)
	return @return
END
GO
PRINT N'Creating Function [sAssessment].[fGetConfigurationGrade]...';

GO

CREATE FUNCTION [sAssessment].[fGetConfigurationGrade](@rOrgId nvarchar(200),@rObtain decimal(6,2))
RETURNS   nvarchar(10) WITH EXECUTE AS CALLER
AS 
BEGIN
	Declare @lGrade nvarchar(10)
	DECLARE @GradeSetId int
	 Declare @M1 decimal(6,2),@M2 decimal(6,2),@M3 decimal(6,2),@M4 decimal(6,2),@M5 decimal(6,2),@M6 decimal(6,2),@M7 decimal(6,2),@M8 decimal(6,2),@M9 decimal(6,2),@M10 decimal(6,2)
	 
	Set @GradeSetId =(Select AnalysisGradeSetId from sAssessment.tConfiguration Where OrgId=@rOrgId)

	
	Declare @Temp Table
	(
		Id Int Identity (1,1),
		GradeCode nvarchar(20),
		MinimumScore decimal(6,2)
	)

	insert into @Temp(GradeCode,MinimumScore)

		select GradeCode,MinimumScore from  sAssessment.tGradeSetDetail where GradeSetId=@GradeSetId ORDER BY MinimumScore DESC
	 --Select * from #Temp1
	 	 Set @M1=(Select MinimumScore from @Temp where Id=1) 
	 	 Set @M2=(Select MinimumScore from @Temp where Id=2) 
	 	 Set @M3=(Select MinimumScore from @Temp where Id=3) 
	 	 Set @M4=(Select MinimumScore from @Temp where Id=4) 
	     Set @M5=(Select MinimumScore from @Temp where Id=5) 
         Set @M6=(Select MinimumScore from @Temp where Id=6) 
	     Set @M7=(Select MinimumScore from @Temp where Id=7) 
	 	 Set @M8=(Select MinimumScore from @Temp where Id=8) 
	 	 Set @M9=(Select MinimumScore from @Temp where Id=9) 
		 Set @M10=(Select MinimumScore from @Temp where Id=10)

		 IF(@rObtain >= @M1)
		 BEGIN
			Select @lGrade= GradeCode from @Temp where Id=1
		 END
		 ELSE IF((@rObtain >= @M2 )AND (@rObtain < @M1))
		 BEGIN
			Select @lGrade= GradeCode from @Temp where Id=2
		 END
		 ELSE IF((@rObtain >= @M3)AND (@rObtain < @M2))
		 BEGIN
			Select @lGrade= GradeCode from @Temp where Id=3
		 END
		 ELSE IF((@rObtain >= @M4 )AND (@rObtain < @M3))
		 BEGIN
			Select @lGrade= GradeCode from @Temp where Id=4
		 END
		 ELSE IF((@rObtain >= @M5 )AND (@rObtain < @M4))
		 BEGIN
			Select @lGrade= GradeCode from @Temp where Id=5
		 END
		 ELSE IF((@rObtain >= @M6)AND (@rObtain < @M5))
		 BEGIN
			Select @lGrade= GradeCode from @Temp where Id=6
		 END
		 ELSE IF((@rObtain >= @M7)AND (@rObtain < @M6))
		 BEGIN
			Select @lGrade= GradeCode from @Temp where Id=7
		 END
		 ELSE IF((@rObtain >= @M8)AND (@rObtain < @M7))
		 BEGIN
			Select @lGrade= GradeCode from @Temp where Id=8
		 END
		 ELSE IF((@rObtain >= @M9)AND (@rObtain < @M8))
		 BEGIN
			Select @lGrade= GradeCode from @Temp where Id=9
		 END
		 ELSE IF((@rObtain >= @M10)AND (@rObtain < @M9))
		 BEGIN
			Select @lGrade= GradeCode from @Temp where Id=10
		 END


	return  @lGrade 
END
GO
PRINT N'Creating Function [sAttendance].[fAbsentDatesGet]...';


GO
CREATE FUNCTION [sAttendance].[fAbsentDatesGet](@rFromDate date,@rToDate date, @rAttendanceTypeId tinyint,@rSubjectId int,@rAcademicId bigint)
RETURNS nvarchar(500) WITH EXECUTE AS CALLER
AS 
BEGIN
    declare @rAbsentDates nvarchar(500)
(Select 
			@rAbsentDates=COALESCE(@rAbsentDates+',','') + cast(SR.attendancedate AS varchar(10))
			 FROM 		
		    sAttendance.tStudentRegister SR 
			WHERE SR.AcademicId=@rAcademicId 
			AND SR.IsPresent=0
			AND SR.AttendanceTypeId=@rAttendanceTypeId
			AND (SR.AttendanceDate >= @rFromDate OR ISNULL(@rFromDate,'')='')
			AND (SR.AttendanceDate <= @rToDate OR ISNULL(@rToDate,'')='') 		 
			AND ((SR.SubjectId=@rSubjectId) OR (ISNULL(@rSubjectId,0)=0)))
			ORDER BY SR.attendancedate
			
			
    RETURN ISNULL(@rAbsentDates,'') 
END
GO
PRINT N'Creating Function [sFee].[fFeeActualAmountSumGet]...';


GO
CREATE FUNCTION [sFee].[fFeeActualAmountSumGet] (@rAcademicId bigint)
RETURNS decimal(12,0) WITH EXECUTE AS CALLER
AS 
BEGIN
    DECLARE @rTotalFeeAmount decimal(12,0),@lClassId int, @lDivisionId int, @lAdmissionCategoryId int, @rBatchId int, @rOrgId int, @rOrgGroupBatchId int
    SELECT @rOrgGroupBatchId=OrgGroupBatchId,@rOrgId=OrgId,@rBatchId=BatchId,@lClassId=ClassId,@lDivisionId=DivisionId,@lAdmissionCategoryId=AdmissionCategoryId FROM sStudent.vStudentAcademic WHERE AcademicId = @rAcademicId
    
    (
    SELECT 
		@rTotalFeeAmount = SUM(ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00))
    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
				AND ((SA1.ClassId=@lClassId) OR (@lClassId=0)) AND ((SA1.DivisionId=@lDivisionId) OR (@lDivisionId=0))
				AND ((SA1.AdmissionCategoryId=@lAdmissionCategoryId) OR (@lAdmissionCategoryId=0))
			INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
			INNER JOIN sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
			WHERE 
			    SA1.OrgGroupBatchId = @rOrgGroupBatchId
				AND	((FS1.ClassId=@lClassId) OR (@lClassId=0))				
				AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND ((FS1.AdmissionCategoryId=@lAdmissionCategoryId) OR (@lAdmissionCategoryId=0))
				AND (FS1.IsOptional=0)
				AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))				
				AND SA1.AcademicId = @rAcademicId
				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
			AND ((SA1.ClassId=@lClassId) OR (@lClassId=0)) AND ((SA1.DivisionId=@lDivisionId) OR (@lDivisionId=0))
			AND ((SA1.AdmissionCategoryId=@lAdmissionCategoryId) OR (@lAdmissionCategoryId=0))
		INNER JOIN sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
		WHERE
		        SA1.OrgGroupBatchId = @rOrgGroupBatchId
				AND ((FS1.ClassId=@lClassId) OR (@lClassId=0))
				AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND ((FS1.AdmissionCategoryId=@lAdmissionCategoryId) OR (@lAdmissionCategoryId=0))
				AND (FS1.IsOptional=1)
				AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))				
				AND SA1.AcademicId = @rAcademicId
		) FS ON FS.AcademicId=SA.AcademicId
		LEFT JOIN sFee.tFeeAllocation FA
			ON FA.FeeSetupId=FS.Id AND FA.SourceId=SA.AcademicId AND SA.AcademicId = @rAcademicId

		WHERE	
			SA.AcademicId = @rAcademicId
			AND SA.OrgGroupBatchId = @rOrgGroupBatchId
			AND ((SA.OrgId=@rOrgId) OR (@rOrgId=0)) 
			AND ((SA.BatchId=@rBatchId) OR (@rBatchId=0)) 
			)
			
	RETURN @rTotalFeeAmount
END
GO
PRINT N'Altering Function [sFee].[fNextInstallmentDetailsGet]...';


GO

ALTER FUNCTION [sFee].[fNextInstallmentDetailsGet](@rReceiptBookId int, @rReceiptId bigint)
RETURNS  @List TABLE (
		PendingAmount decimal(12,2),
		CollectionGroupId int,
		StartDate date,
		EndDate date,
		CollectionGroupName nvarchar(100),
		OrderIndex smallint,
		ReceiptId bigint,
		SourceId bigint,
		SourceTypeId smallint
)  
WITH EXECUTE AS CALLER
AS 
BEGIN

	DECLARE @lClassId int
	DECLARE @lAdmissionCategoryId int,@lOrgId int,@lOrgGorupId int
	DECLARE @lSourceId bigint, @lSourceTypeId int, @lBatchId int
	--DECLARE @lConfigValue nvarchar(50)

	SELECT @lSourceId = SourceId, @lSourceTypeId = SourceTypeId FROM sFee.tReceipt WHERE Id = @rReceiptId
	SELECT @lClassId=ClassId,@lAdmissionCategoryId=AdmissionCategoryId,@lOrgId = OrgId, @lBatchId=BatchId FROM sStudent.vStudentAcademic WHERE AcademicId=@lSourceId	
	SELECT @lOrgGorupId = OrgGroupId FROM sSetup.tOrganizationMaster WHERE Id = @lOrgId
	--SELECT @lConfigValue = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 487 AND SourceTypeId = 2010 AND SourceId = @lOrgGorupId


	-- Start mantisid - 0032734 
	DECLARE @lReceiptStartDate Date
	SELECT @lReceiptStartDate = CGM1.StartDate
								FROM
									sFee.tReceipt R 
									INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id	
									INNER JOIN sFee.tFeeSetup FSR ON FSR.Id = RD.FeeSetupId 	
									INNER JOIN sFee.tCollectionGroupMaster CGM1 ON CGM1.Id = FSR.CollectionGroupId -- Change by me
								WHERE						
									(R.ReceiptBookId = 0	OR 0 = 0)	
									AND R.SourceId= @lSourceId
									AND ((R.SourceTypeId=@lSourceTypeId) OR (@lSourceTypeId=0))
									AND R.IsObsolete = 0 	
									AND R.Id = @rReceiptId		 
								GROUP BY FeeSetupId,R.Id,CGM1.StartDate

	-- End mantisid - 0032734 
	
	INSERT INTO @List 
	SELECT TOP 1 *, @lSourceId AS SourceId, @lSourceTypeId AS SourceTypeId FROM
	(
		SELECT 
			SUM(CG.PayableAmount) AS PendingAmount,
			CollectionGroupId,
			StartDate,
			EndDate,
			CollectionGroupName,
			OrderIndex,
			ReceiptId
		FROM
		(SELECT	
			ISNULL(FS.Amount,0) +  ISNULL(FA.VariableAmount,0) -  ISNULL(FA.DiscountAmount,0) -  ISNULL(FA.NotApplicableAmount,0) + ISNULL(FA.AdditionalAmount,0.00)-ISNULL(R.PaidAmount,0)AS PayableAmount,
			FS.CollectionGroupId,
			CGM.StartDate,
			CGM.EndDate,
			CGM.Title AS CollectionGroupName,
			CGM.OrderIndex,
			R.ReceiptId
		 FROM 
			sFee.tFeeMaster FM
			INNER JOIN 
			(
				SELECT 
					FS1.FeeId,
					FS1.Id,
					ISNULL(FS1.Amount,0)AS Amount,
					FS1.BatchId,
					ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
					ISNULL(FS1.CollectionGroupId,0) AS CollectionGroupId
				FROM sFee.tFeeSetup FS1
				WHERE FS1.ClassId=@lClassId AND FS1.BatchId = @lBatchId
					AND FS1.AdmissionCategoryId=@lAdmissionCategoryId AND IsOptional=0
				
				UNION ALL
				
				SELECT 
					FS1.FeeId,
					FS1.Id,
					ISNULL(FS1.Amount,0)AS Amount,
					FS1.BatchId,
					ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
					ISNULL(FS1.CollectionGroupId,0) AS CollectionGroupId
				FROM 
					sFee.tFeeSetup FS1
					INNER JOIN sFee.tFeeOptional FO ON FO.FeeSetupId=FS1.Id AND (FO.SourceId=@lSourceId) AND ((FO.SourceTypeId=@lSourceTypeId) OR (@lSourceTypeId=0))
				WHERE
					FS1.ClassId=@lClassId 
					AND FS1.BatchId =@lBatchId 
					AND FS1.AdmissionCategoryId=@lAdmissionCategoryId 
					AND IsOptional=1
			) FS ON FS.FeeId=FM.Id
			INNER JOIN sFee.tCollectionGroupMaster CGM ON CGM.Id = FS.CollectionGroupId
			INNER JOIN sFee.tReceiptBookMaster RBM ON RBM.Id=FS.ReceiptBookId
			LEFT JOIN
			(
				SELECT 
					ISNULL(SUM(RD.Amount),0) AS PaidAmount,
					RD.FeeSetupId,
					R.Id AS ReceiptId
				FROM
					sFee.tReceipt R 
					INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id	
					INNER JOIN sFee.tFeeSetup FSR ON FSR.Id = RD.FeeSetupId 	
				WHERE						
					(R.ReceiptBookId = @rReceiptBookId	OR @rReceiptBookId = 0)	
					AND R.SourceId= @lSourceId
					AND ((R.SourceTypeId=@lSourceTypeId) OR (@lSourceTypeId=0))
					AND R.IsObsolete = 0 	
					AND R.Id = @rReceiptId		 
				GROUP BY FeeSetupId,R.Id
			) R ON R.FeeSetupId = FS.Id 
			LEFT JOIN sFee.tFeeAllocation FA ON FA.FeeSetupId=FS.Id AND (FA.SourceId=@lSourceId) AND ((FA.SourceTypeId=@lSourceTypeId) OR (@lSourceTypeId=0))			
			WHERE 
				((FS.ReceiptBookId=@rReceiptBookId)OR(@rReceiptBookId=0))
				AND (((ISNULL(FS.Amount,0) +  ISNULL(FA.VariableAmount,0) -  ISNULL(FA.NotApplicableAmount,0) -  ISNULL(FA.DiscountAmount,0) + ISNULL(FA.AdditionalAmount,0.00)-ISNULL(R.PaidAmount,0))>0))
				AND(FS.BatchId=@lBatchId)
				--AND (@lConfigValue = 'True' AND (CAST(sCommon.fGetDate() AS DATE) <= CAST(CGM.EndDate AS DATE)))
				AND CGM.IsObsolete = 0
				AND  @lReceiptStartDate <= CGM.StartDate -- mantisid - 0032734 
		) AS CG
		GROUP BY CollectionGroupId,StartDate,EndDate,CollectionGroupName,OrderIndex,ReceiptId
	) AS PendingFee
	ORDER BY PendingFee.StartDate,PendingFee.OrderIndex
		
	RETURN  
END
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

 	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

--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,
		 @rIsCreated int OUTPUT
	    
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
BEGIN 

DECLARE @loDoc INT
EXEC sp_xml_preparedocument @loDoc OUTPUT, @rReceiptDetailXml
	 
create table #temptable (FeeId int,Id int,Amount decimal(12,2), AcademicId bigint ) 
INSERT INTO #temptable (FeeId,Id ,Amount , 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 NOT EXISTS(
	SELECT 1
	FROM #temptable FS
	INNER JOIN (
				SELECT FeeSetupId
					,Amount
				FROM OPENXML(@loDoc, '/Table/ReceiptDetail', 1) WITH (
						FeeSetupId INT
						,Amount DECIMAL(12, 2)
						)
				) AS RD ON RD.FeeSetupId = FS.Id)
	BEGIN 
		SELECT @rIsCreated = -1
	END -- For Mantis 0032370 by Foram End
	ELSE
	BEGIN
	
	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 @rIsCreated = 1
	END 
	ELSE
	BEGIN
		--Start for mantis 0031290 By Foram
		IF(@rPayTypeId = 8)
		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 @rIsCreated = 1
			END
			ELSE
			BEGIN
				SELECT @rIsCreated = 0
			END
		END
		--end for mantis 0031290 By Foram
		ELSE
		BEGIN
			SELECT @rIsCreated = 0
		END
 END 
 
	END
 	EXEC sp_xml_removedocument @loDoc
END
GO
PRINT N'Altering Procedure [sFee].[pReceiptServiceTaxAdd]...';


GO



ALTER PROCEDURE [sFee].[pReceiptServiceTaxAdd]
    
		   @rSourceTypeId smallint,
		   @rSourceId bigint,
		   @rReceiptId bigint,	 
		   @rCreatedUserId bigint,
		   @rOrgId int,
		   @rBatchId int,
		   @rTaxRate decimal(12,2)=0	 
		  
		   

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN	

DECLARE @lTotalAmount decimal(12,2)
DECLARE @lTaxAmount decimal(12,2)
DECLARE @lTaxTypeId tinyint

SELECT @lTotalAmount = ISNULL(SUM(D.Amount),0) 
	FROM sFee.tReceiptDetail D INNER JOIN sFee.tFeeSetup S ON D.FeeSetupId = S.Id
	WHERE D.ReceiptId = @rReceiptId AND S.IsServiceTax = 1

SELECT @lTaxTypeId = TaxTypeId FROM sFee.tReceiptBookMaster WHERE Id = (SELECT ReceiptBookId FROM sFee.tReceipt WHERE Id = @rReceiptId)
 
--SET @lTaxAmount = round((@lTotalAmount) * (@rTaxRate/100),0)

-- #Start MantisId : 0031923
IF @lTaxTypeId = 2		-- Exclusive 
	BEGIN
		SET @lTaxAmount = round((@lTotalAmount) * (@rTaxRate/100),0)

		IF NOT EXISTS(SELECT 1 FROM sFee.tReceiptTaxDetail WHERE ReceiptId = @rReceiptId)
		BEGIN
		INSERT INTO sFee.tReceiptTaxDetail
		SELECT 
			@rReceiptId,
			D.FeeSetupId,
			CASE WHEN S.IsServiceTax = 1 THEN round((D.Amount) * (@rTaxRate/100),0)
				ELSE 0 END,
			@lTaxTypeId,
			S.IsServiceTax

		FROM sFee.tReceiptDetail D INNER JOIN sFee.tFeeSetup S ON D.FeeSetupId = S.Id
		WHERE 
		D.ReceiptId = @rReceiptId
		END
	END
ELSE					-- Inclusive
	BEGIN
		SET @lTaxAmount = 0

		IF NOT EXISTS(SELECT 1 FROM sFee.tReceiptTaxDetail WHERE ReceiptId = @rReceiptId)
		BEGIN
		INSERT INTO sFee.tReceiptTaxDetail
		SELECT 
			@rReceiptId,
			D.FeeSetupId,
			0,
			@lTaxTypeId,
			S.IsServiceTax

		FROM sFee.tReceiptDetail D INNER JOIN sFee.tFeeSetup S ON D.FeeSetupId = S.Id
		WHERE 
		D.ReceiptId = @rReceiptId
		END
	END					
-- #End MantisId : 0031923
 
UPDATE sFee.tReceipt SET ReceiptAmount = (TotalReceiptAmount + @lTaxAmount) , -- DiscountAmount =  @lTaxAmount, Remove for Mantis : 0031923
		TaxPercentage = @rTaxRate WHERE Id =@rReceiptId
 
	END
GO
PRINT N'Altering Procedure [sStudent].[pStudentMasterGet]...';


GO

ALTER PROCEDURE [sStudent].[pStudentMasterGet]
	 
	 @rCode nvarchar(20),
	 @rOrgId int,
	 @rNumber bigint,
	 @rBatchId int,
	 @rStudentId bigint,
	 @rOrgGroupBatchId int=0
	 --@rIsSearch bit
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 

	DECLARE @lAcademicId bigint
	DECLARE @lIsAdmissionCategoryChange bit
	SET @lIsAdmissionCategoryChange=1
	SELECT @lAcademicId=AcademicId FROM sStudent.vStudentAcademic SA 
	WHERE 
			((SA.Code=@rCode)OR(ISNULL(@rCode,'')=''))
			AND ((SA.StudentId=@rStudentId)OR(@rStudentId=0))
			AND(SA.OrgId=@rOrgId)
			AND(SA.BatchId=@rBatchId)
			
	IF(ISNULL(@lAcademicId,0) != 0)
	BEGIN
		IF EXISTS (SELECT 1 FROM sFee.tFeeAllocation WHERE SourceTypeId=2001 AND SourceId=@lAcademicId)
		BEGIN
			SET @lIsAdmissionCategoryChange=0
		END
		ELSE IF EXISTS (SELECT 1 FROM sFee.tFeeOptional WHERE SourceTypeId=2001 AND SourceId=@lAcademicId)
		BEGIN
			SET @lIsAdmissionCategoryChange=0
		END
		ELSE IF EXISTS (SELECT 1 FROM sFee.tReceipt WHERE SourceTypeId=2001 AND SourceId=@lAcademicId)
		BEGIN
			SET @lIsAdmissionCategoryChange=0
		END
	END	
			
	 --IF(@rIsSearch=1)
		--BEGIN
		--	SET @rCode = sCommon.fSearchStringGet(@rCode)
		--	SET @rTitle = sCommon.fSearchStringGet(@rTitle)
		--END
	
	SELECT 
			SA.StudentId AS Id,
			ISNULL(SA.Code,'') AS Code,
			ISNULL(SA.Number,0)AS Number,
			ISNULL(SA.RegistrationNumber,'') AS RegistrationNumber,
			SA.FirstName,
			ISNULL(SA.MiddleName,'')AS MiddleName,
			SA.LastName,
			SA.OrgId,
			ISNULL(SA.AdmissionCategoryId,0) AS AdmissionCategoryId,
			SA.StatusId,
			SA.RecordStatusId,
			--SA.FirstName+' '+SA.LastName AS Name,
			SA.Name,
			@lAcademicId AS AcademicId,
			SA.ClassId,
			SA.DivisionId,
			ISNULL(SA.RollNo,0) AS RollNo,
			SA.BatchId,
			ISNULL(SO.DateOfBirth,'') AS DateOfBirth,
			ISNULL(SO.GenderId,0) AS GenderId,
			SA.ClassName+'-'+SA.DivisionName AS ClassDiv,
			ISNULL(SA.AdmissionCategoryId,0) AS AdmissionCategoryId,
			@lIsAdmissionCategoryChange AS IsAdmissionCategoryChange,
			SA.SUId,
			ISNULL(AD.RepeatCount,1) AS RepeatCount,
			ISNULL(SA.DepartmentId,0) AS DepartmentId,
			ISNULL(RM.HostelId,0) AS HostelId,
			ISNULL(AR.RoomId,0) AS RoomId,
			ISNULL(A.TransportId,0) AS TransportId,
			ISNULL(A.BusRouteId,0) AS BusRouteId,
			ISNULL(A.PickupDestinationId,0) AS PickupDestinationId,
			ISNULL(SA.StudentGroupId,0) AS StudentGroupId,
			ISNULL(SA.StudentOtherGroupId,0) AS StudentOtherGroupId,
			ISNULL(SA.ClassStatusId,0) AS ClassStatusId,
			ISNULL(SA.FeesRemark,'') AS FeesRemark,
			ISNULL(SO.TransportModeId,0) AS TransportModeId,
			ISNULL(SO.BirthDateInWord, '') AS BirthDateInWord,
			ISNULL(SM.PENNumber,0) AS PENNumber, --Mantis- 0031338
			ISNULL(SM.LocalName,'') AS LocalName
			
  FROM 
           sStudent.vStudentAcademic SA
     LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId=SA.StudentId
     LEFT JOIN sStudent.tAcademicDetail AD ON AD.AcademicID = SA.AcademicId
     LEFT JOIN sHostel.tAssignRoom AR ON AR.SourceId = SA.StudentId AND AR.SourceTypeId = 2003  AND AR.OrgGroupBatchId=@rOrgGroupBatchId
     LEFT JOIN sHostel.tRoomMaster RM ON RM.Id = AR.RoomId
     LEFT JOIN
     (SELECT ATR.SourceId,ISNULL(ATR.PickupDestinationId,0) AS PickupDestinationId,	ISNULL(BRM.TransportId,0) AS TransportId,ISNULL(BRM.Id,0) AS BusRouteId FROM sTransport.tAssignRoute ATR 
     INNER JOIN sTransport.tBusRouteDestinationMaster BRDM ON BRDM.Id=ATR.PickupDestinationId
     INNER JOIN sTransport.tBusRouteMaster BRM ON BRM.Id=BRDM.BusRouteId  AND BRM.OrgGroupBatchId=@rOrgGroupBatchId   AND ATR.SourceTypeId = 2003 ) A ON A.SourceId = SA.StudentId AND SA.OrgGroupBatchId=@rOrgGroupBatchId
     LEFT JOIN  sStudent.tStudentGroupMaster GM ON GM.Id=SA.StudentGroupId
     LEFT JOIN sStudent.tStudentOtherGroupMaster OGM  ON OGM.Id=SA.StudentOtherGroupId
	 LEFT JOIN sStudent.tStudentMaster SM ON SM.Id = SA.StudentId --Mantis- 0031338
  WHERE 
 
			((SA.Code=@rCode)OR(ISNULL(@rCode,'')=''))
			AND ((SA.StudentId=@rStudentId)OR(@rStudentId=0))
			AND((SA.Number=@rNumber) OR (@rNumber=0))
			AND(SA.OrgId=@rOrgId)
			AND(SA.BatchId=@rBatchId)
  ORDER BY SA.Code
END
GO
PRINT N'Altering Procedure [sFee].[pFeeSetupGet]...';


GO
ALTER PROCEDURE [sFee].[pFeeSetupGet]
				
		   @rBuilder1 nvarchar(max)='',
		   @rBuilder2 nvarchar(max)='', 
		   @rClassId int,
           @rAdmissionCategoryId int,
		   @rBatchId int,
		   @rOrgGroupId int
           
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
BEGIN 
	SELECT 
	
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			ISNULL(FS.Id,0)AS Id,
			ISNULL(CM.Id,0)AS ClassId,
			ISNULL(CM.Title,'') AS ClassName,
			ISNULL(FS.AdmissionCategoryId,0) AS AdmissionCategoryId,
			FM.Title AS FeeTitle,
			ISNULL(FS.BatchId,0)AS BatchId,
			ISNULL(FM.Id,0)AS FeeId,
			ISNULL(FS.IsOptional,0)AS IsOptional,
			ISNULL(FS.IsVariable,0)AS IsVariable,
			ISNULL(FS.Amount,0)AS Amount,
			ISNULL(FS.StartDate,'0001-01-01 00:00:00.00')AS StartDate,
			ISNULL(FS.EndDate,'0001-01-01 00:00:00.00')AS EndDate,
			ISNULL(FS.ReceiptBookId,0) AS ReceiptBookId,
			ISNULL(RBM.Title,'') AS ReceiptBookTitle,
			ISNULL(FHM.Id,0) AS FeeHeadId,
			ISNULL(FHM.Title,'') AS FeeHeadName,
			--CASE WHEN ((SELECT COUNT(*) FROM sFee.tReceiptDetail WHERE FeeSetupId=FS.Id) <= 0) AND ((SELECT COUNT(1) FROM sFee.tPostDatePayment WHERE ReceiptBookId=FS.ReceiptBookId) <=0) THEN 'True' 
			CASE WHEN ((SELECT COUNT(*) FROM sFee.tReceiptDetail WHERE FeeSetupId=FS.Id) <= 0) AND ((SELECT COUNT(1) FROM sFee.tPostDatePayment PDP INNER JOIN sStudent.tAcademic A ON A.Id = PDP.SourceId AND PDP.SourceTypeId = 2001 WHERE A.ClassId = FS.ClassId AND ReceiptBookId=FS.ReceiptBookId) <=0) THEN 'True'  -- Changed PDC condition for mantis : 0032937
			ELSE 'False' END AS IsReceiptBookChange,
			ISNULL(FS.IsServiceTax,0)AS IsServiceTax,
			ISNULL(FS.CollectionGroupId,0) AS CollectionGroupId,
			ISNULL(FS.FeeDuration,'')  AS FeeDuration,
			ISNULL(FS.LevelAmount,0) AS LevelAmount,
			ISNULL(FHM.Number,0) AS FeeHeadNumber,
			ISNULL(CGM.Title,'') AS CollectionGroupTitle,
			ISNULL(FS.LateFeeRuleId, 0) AS LateFeeRuleId
  FROM 
			sFee.tFeeMaster FM
		LEFT JOIN sFee.tFeeSetup FS ON FM.Id=FS.FeeId 
		AND (FS.ClassId=@rClassId OR @rClassId= 0) 
		AND (FS.AdmissionCategoryId=@rAdmissionCategoryId OR @rAdmissionCategoryId= 0) 
		AND (FS.BatchId=@rBatchId)
		LEFT JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FM.FeeHeadId
		LEFT JOIN sFee.tReceiptBookMaster RBM ON RBM.Id=FS.ReceiptBookId
		LEFT JOIN sSetup.tClassMaster CM ON CM.Id=FS.ClassId
		LEFT JOIN sFee.tCollectionGroupMaster CGM ON CGM.Id = FS.CollectionGroupId
WHERE 
		FM.OrgGroupId=@rOrgGroupId
		ORDER BY FS.StartDate,FHM.OrderIndex,FM.OrderIndex
END
GO
PRINT N'Altering Procedure [sFee].[pReceiptBookMasterAdd]...';


GO

/* 
Mantis Id : 0031923	
TaxTypeId :
	Inclusive = 1
	Exclusive = 2
*/
 
 
ALTER PROCEDURE [sFee].[pReceiptBookMasterAdd]
	 
	        @rId int
	       ,@rCode nvarchar(20)
           ,@rTitle nvarchar(100)
           ,@rFullTitle nvarchar(200)
           ,@rAddress1 nvarchar(200)
           ,@rAddress2 nvarchar(200)
           ,@rBankAccountNumber nvarchar(50)
           ,@rIsObsolete bit
           ,@rRemark1 nvarchar(500)
           ,@rRemark2 nvarchar(500)
           ,@rCreatedUserId bigint           
           ,@rOrgGroupId int
           ,@rIsOnPrePrinted bit
           ,@rReportId int
           ,@rIsSupressLogo bit
           ,@rOrderIndex int
           ,@rIsDisplaySchoolName bit
           ,@rIsMonthDetailOnly bit
           ,@rIsServiceTaxApplicable bit
           ,@rServiceTaxPercentage decimal(6,2)
           ,@rBankName nvarchar(150)=''
           ,@rIsFeeInvoiceHeadwise bit = 0
           ,@rGroupTitle nvarchar(200)=''
           ,@rIsSuppressFeeDetail bit=0
		   ,@rReceiptLogo varbinary(max)=NULL
		   ,@rHeaderDisplayId tinyint
		   ,@rReceiptBookHeader varbinary(max)=NULL
		   ,@rFeeInvoiceHeaderDisplayId tinyint
		   ,@rFeeInvoiceHeader varbinary(max)=NULL
		   ,@rCGSTPercentage decimal(5,2) = 0 
		   ,@rSGSTPercentage decimal(5,2) = 0
		   ,@rIsDisplayPendingFeeAmount bit = 0
		   ,@rDigitalSignature varbinary(max)=NULL
		   ,@rTaxLabel	nvarchar(50) = ''		-- Mantis Id : 0031923	
		   ,@rTaxTypeId tinyint = 0				-- Mantis Id : 0031923	
		   
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	 BEGIN TRANSACTION	
	 DECLARE @lNextNumber INT     
	
If Exists(select top(1)* from sFee.tReceiptBookMaster where Title=@rTitle AND OrgGroupId=@rOrgGroupId) 
BEGIN
	If NOT Exists(select top(1)* from sFee.tReceiptBookMaster where Title=@rTitle AND OrgGroupId=@rOrgGroupId AND Id=@rId)
	BEGIN
		select -101 as Result
	END
	ELSE
	BEGIN
	 SET @lNextNumber = @rId
	    UPDATE  [sFee].[tReceiptBookMaster]
	    SET
			  --Code=@rCode
	          Title=@rTitle
	          ,FullTitle=@rFullTitle
	         ,Address1=@rAddress1
	         ,Address2=@rAddress2
	         ,BankAccountNumber=@rBankAccountNumber
	         ,[IsObsolete] = @rIsObsolete      
	         ,[Remark1] = @rRemark1
	         ,[Remark2] = @rRemark2
             ,[UpdatedUserId] = @rCreatedUserId
             ,[UpdatedDateTime] = sCommon.fGetDate()
             ,IsOnPrePrinted=@rIsOnPrePrinted
             ,ReportId=@rReportId
             ,IsSupressLogo=@rIsSupressLogo   
             ,OrderIndex=@rOrderIndex
             ,IsDisplaySchoolName=@rIsDisplaySchoolName
             ,IsMonthDetailOnly=@rIsMonthDetailOnly
             ,IsServiceTaxApplicable=@rIsServiceTaxApplicable
			 ,ServiceTaxPercentage=@rServiceTaxPercentage
			 ,BankName=@rBankName
			 ,IsFeeInvoiceHeadwise=@rIsFeeInvoiceHeadwise
			 ,GroupTitle =@rGroupTitle
			 ,IsSuppressFeeDetail=@rIsSuppressFeeDetail
			 ,ReceiptLogo = @rReceiptLogo
			 ,ReceiptBookHeader=@rReceiptBookHeader
			 ,HeaderDisplayId=@rHeaderDisplayId
			 ,FeeInvoiceHeader=@rFeeInvoiceHeader
			 ,FeeInvoiceHeaderDisplayId=@rFeeInvoiceHeaderDisplayId
			 ,CGSTPercentage=@rCGSTPercentage
			 ,SGSTPercentage=@rSGSTPercentage
			 ,IsDisplayPendingFeeAmount=@rIsDisplayPendingFeeAmount
			 ,DigitalSignature=@rDigitalSignature
			 ,TaxLabel = @rTaxLabel
			 ,TaxTypeId = @rTaxTypeId
             
	      WHERE Id = @rId 	 
	      SELECT @lNextNumber AS Result
	 END  
END
ELSE
BEGIN
IF(@rId = 0)	
BEGIN

	EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sFee.tReceiptBookMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	
	INSERT INTO [sFee].[tReceiptBookMaster]
			   (
			    [Id]
			   ,[Code]
			   ,[Title]
			   ,[FullTitle]
			   ,[Address1] 
			   ,[Address2] 
			   ,[BankAccountNumber] 
			   ,[IsObsolete]
			   ,[Remark1] 
			   ,[Remark2] 
			   ,[CreatedUserId]
			   ,[CreatedDateTime]
			   ,[OrgGroupId]
			   ,IsOnPrePrinted
			   ,ReportId
			   ,IsSupressLogo
			   ,OrderIndex
			   ,IsDisplaySchoolName
			   ,IsMonthDetailOnly
			   ,IsServiceTaxApplicable
			   ,ServiceTaxPercentage
			   ,BankName
			   ,IsFeeInvoiceHeadwise
			   ,GroupTitle
			   ,IsSuppressFeeDetail
			   ,ReceiptLogo
			   ,HeaderDisplayId
			   ,ReceiptBookHeader
			   ,FeeInvoiceHeader
			   ,FeeInvoiceHeaderDisplayId
			   ,CGSTPercentage
			   ,SGSTPercentage
			   ,IsDisplayPendingFeeAmount
			   ,DigitalSignature
			   ,TaxLabel
			   ,TaxTypeId
			   )
		 VALUES
			   (
				@lNextNumber
			   ,@rCode
			   ,@rTitle
			   ,@rFullTitle
			   ,@rAddress1
			   ,@rAddress2
			   ,@rBankAccountNumber
			   ,@rIsObsolete
			   ,@rRemark1
			   ,@rRemark2
			   ,@rCreatedUserId
			   ,sCommon.fGetDate()
			   ,@rOrgGroupId
			   ,@rIsOnPrePrinted
			   ,@rReportId
			   ,@rIsSupressLogo
			   ,@rOrderIndex
			   ,@rIsDisplaySchoolName
			   ,@rIsMonthDetailOnly
			   ,@rIsServiceTaxApplicable
			   ,@rServiceTaxPercentage
			   ,@rBankName
			   ,@rIsFeeInvoiceHeadwise
			   ,@rGroupTitle
			   ,@rIsSuppressFeeDetail
			   ,@rReceiptLogo
			   ,@rHeaderDisplayId
			   ,@rReceiptBookHeader
			   ,@rFeeInvoiceHeader
			   ,@rFeeInvoiceHeaderDisplayId
			   ,@rCGSTPercentage
			   ,@rSGSTPercentage
			   ,@rIsDisplayPendingFeeAmount
			   ,@rDigitalSignature
			   ,@rTaxLabel
			   ,@rTaxTypeId
			   )
			   
 
INSERT INTO sSecurity.tUserAccess
           (
            SourceTypeId
            ,SourceId
           ,[UserId]
           
           )
SELECT 
		   2013
		   ,@lNextNumber
		  ,@rCreatedUserId
			   
			   
		    SELECT @lNextNumber AS Result
	END	 
	 ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE  [sFee].[tReceiptBookMaster]
	    SET
			  --Code=@rCode
	          Title=@rTitle
	          ,FullTitle=@rFullTitle
	         ,Address1=@rAddress1
	         ,Address2=@rAddress2
	         ,BankAccountNumber=@rBankAccountNumber
	         ,[IsObsolete] = @rIsObsolete          
	         ,[Remark1] = @rRemark1
	         ,[Remark2] = @rRemark2                     
             ,[UpdatedUserId] = @rCreatedUserId
             ,[UpdatedDateTime] = sCommon.fGetDate()   
             ,IsOnPrePrinted=@rIsOnPrePrinted
             ,ReportId=@rReportId
             ,IsSupressLogo=@rIsSupressLogo
             ,OrderIndex=@rOrderIndex              
             ,IsDisplaySchoolName=@rIsDisplaySchoolName
             ,IsMonthDetailOnly=@rIsMonthDetailOnly
             ,IsServiceTaxApplicable=@rIsServiceTaxApplicable
			 ,ServiceTaxPercentage=@rServiceTaxPercentage
			 ,BankName=@rBankName
			 ,IsFeeInvoiceHeadwise=@rIsFeeInvoiceHeadwise
			 ,GroupTitle =@rGroupTitle
			 ,IsSuppressFeeDetail=@rIsSuppressFeeDetail
			 ,ReceiptLogo = @rReceiptLogo
			 ,HeaderDisplayId=@rHeaderDisplayId
			 ,ReceiptBookHeader=@rReceiptBookHeader
              ,FeeInvoiceHeaderDisplayId=@rFeeInvoiceHeaderDisplayId
			 ,FeeInvoiceHeader=@rFeeInvoiceHeader
			 ,CGSTPercentage=@rCGSTPercentage
			 ,SGSTPercentage=@rSGSTPercentage
			 ,IsDisplayPendingFeeAmount=@rIsDisplayPendingFeeAmount
			 ,DigitalSignature=@rDigitalSignature
			 ,TaxLabel=@rTaxLabel
			 ,TaxTypeId=@rTaxTypeId
	      WHERE Id = @rId 	   
	      SELECT @lNextNumber AS Result
	 END  
		
	
	END
	If Not Exists(Select 1 from sSystem.tPortalSync where OrgGRoupId=@rOrgGroupId)
	BEGIN
	Insert into sSystem.tPortalSync
	(
		OrgGroupId,
		FeeChange
	)
	Values
	(
		@rOrgGroupId,
		1
	)
	 
	END
	
	Else
	BEGIN
		Update sSystem.tPortalSync 
		Set
			FeeChange=1
		Where OrgGroupId=@rOrgGroupId
	END
	
COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Altering Procedure [sFee].[pReceiptBookMasterGet]...';


GO
 
ALTER PROCEDURE [sFee].[pReceiptBookMasterGet]
          
           @rId bigint,
           @rCode nvarchar(20),
           @rTitle nvarchar(100),
           @rOrgGroupId int,
           @rIsWildCardSearch bit
 
AS
SET NOCOUNT ON

		IF @rIsWildCardSearch = 1
		BEGIN
			SET @rCode = sCommon.fSearchStringGet(@rCode)
			SET @rTitle = sCommon.fSearchStringGet(@rTitle)
		END

BEGIN
SELECT RBM.Id 
	  ,RBM.Code
      ,RBM.Title
      ,RBM.FullTitle
      ,RBM.Address1
      ,RBM.Address2
      ,RBM.BankAccountNumber
      ,RBM.IsObsolete
      ,RBM.Remark1
      ,RBM.Remark2
      ,ISNULL(RBM.IsOnPrePrinted ,0) AS IsOnPrePrinted
      ,ISNULL(RBM.IsSupressLogo,0) AS IsSupressLogo
      ,RBM.ReportId  
       --,RBM.OrderIndex  
      ,ISNULL(RBM.OrderIndex,0) AS OrderIndex
      ,ISNULL(RBM.IsDisplaySchoolName,0) AS IsDisplaySchoolName
      ,ISNULL(RBM.IsMonthDetailOnly,0) AS IsMonthDetailOnly
      ,ISNULL(RBM.IsServiceTaxApplicable,0) AS IsServiceTaxApplicable
	  ,ISNULL(RBM.ServiceTaxPercentage,0) AS ServiceTaxPercentage
	  ,ISNULL(RBM.BankName,'') AS BankName
	  ,ISNULL(RBM.IsFeeInvoiceHeadwise,0) AS IsFeeInvoiceHeadwise
	  ,ISNULL(RBM.GroupTitle,'') AS GroupTitle
	  ,ISNULL(RBM.IsSuppressFeeDetail,0) AS IsSuppressFeeDetail
	  ,RBM.ReceiptLogo
	  ,ISNULL(RBM.HeaderDisplayId,1) AS HeaderDisplayId
	  ,RBM.ReceiptBookHeader
	  ,ISNULL(RBM.FeeInvoiceHeaderDisplayId,1) AS FeeInvoiceHeaderDisplayId
	  ,RBM.FeeInvoiceHeader
	  ,ISNULL(RBM.CGSTPercentage,0) AS CGSTPercentage
	  ,ISNULL(RBM.SGSTPercentage,0) AS SGSTPercentage
	  ,ISNULL(RBM.IsDisplayPendingFeeAmount,0) AS IsDisplayPendingFeeAmount
      ,ISNULL(R.Title,'') AS ReportName
	  ,ISNULL(HDM.Title,'') AS ReceiptHeader
	  ,RBM.DigitalSignature
	  ,ISNULL(RBM.TaxLabel,'') AS TaxLabel		-- Mantis Id : 0031923	
	  ,ISNULL(RBM.TaxTypeId,0) AS TaxTypeId		-- Mantis Id : 0031923	
     
  FROM [sFee].[tReceiptBookMaster] RBM 
	INNER JOIN [sCommon].[tReport] R ON RBM.ReportId = R.Id
	LEFT JOIN [sCommon].[tHeaderDisplayMaster] HDM ON RBM.HeaderDisplayid = HDM.Id       
  
  WHERE 
		 RBM.Id = @rId OR @rId = 0
	AND ((RBM.Code Like @rCode)OR(ISNULL(@rCode,'') = ''))
	AND ((RBM.Title Like @rTitle)OR(ISNULL(@rTitle,'') = ''))
	AND  RBM.OrgGroupId = @rOrgGroupId 
	--AND  QM.IsObsolete = 0
         
END
GO
PRINT N'Altering Procedure [sOp].[pGatewayProductAdd]...';


GO
ALTER PROCEDURE [sOp].[pGatewayProductAdd]
	 
    @rId int,
	@rGatewayConfigurationId int,
	@rTitle nvarchar(150),
	@rGatewayURL nvarchar(1000),
	@rServerPort nvarchar(50),
	@rLoginId nvarchar(50),
	@rLoginPassword nvarchar(50),
	@rProductId nvarchar(100),
	@rOrgGroupId int,
		
	@rCCAvenueMerchantID nvarchar(50)='',
	@rCCAvenueAccessCode nvarchar(100)='',
	@rCCAvenueWorkingKey nvarchar(100)='',
	@rCCAvenueWhitelistURL nvarchar(500)='',
	@rCCAvenueSubAccountId nvarchar(100)='',
		
	@rAtomReqHashKey nvarchar(100)='',
	@rAtomRespHashKey nvarchar(100)='',
		
	@rPaytmMID nvarchar(50)='',
	@rPaytmMerchantKey nvarchar(50)='',
	@rPaytmChannelId nvarchar(20)='',
	@rPaytmIndustryTypeId nvarchar(20)='',
	@rPaytmWebsite nvarchar(20)='',
	@rPaytmStatusCheckURL nvarchar(500)='',
		
	@rPayUMoneyMERCHANTID nvarchar(20)='',
	@rPayUMoneyMERCHANTKEY nvarchar(20)='',
	@rPayUMoneySALT nvarchar(20)='',
	@rPayUMoneyHASHSEQUENCE nvarchar(200)='',
	@rPayUMoneyAUTHHEADER nvarchar(50)='',
		
	@rBillDeskMerchantID nvarchar(50)='',
	@rBillDeskChecksumKey nvarchar(50)='',
	@rBillDeskSecurityID nvarchar(50)='',
	@rBillDeskUniqueIdentifier nvarchar(50)='',
		
	@rEazypayMerchantId nvarchar(50)='',
	@rEazypayAESKey nvarchar(50)='',
		
	@rAxisMerchantId nvarchar(50)='',
	@rAxisAPIKey nvarchar(50)='',
	@rAxisResponseKey nvarchar(50)='',
		
	@rRazorpayMID nvarchar(50)='',
	@rRazorpayKeyID nvarchar(50)='',
	@rRazorpaySecretKey nvarchar(50)='',
	@rRazorpaySubMerchantId nvarchar(50)='',
	
	@rBBPSCharge nvarchar(500) = '',
	@rBBPSGST decimal(12,2) = 0,
		
	@rGrayQuestClientId nvarchar(50)='',
	@rGrayQuestSecretKey nvarchar(50)='',
	@rGrayQuestApiKey nvarchar(50)='',

	@rEasebuzzKey nvarchar(50)='',
	@rEasebuzzSalt nvarchar(50)='',
	@rEasebuzzIsLiveEnvironment bit = null,
	@rEasebuzzIsEnableiFrame bit = null,
	@rEasebuzzSubMerchantId nvarchar(50)='',

	@rHesabeAccessCode nvarchar(50)='',
	@rHesabeMerchantCode nvarchar(50)='',
	@rHesabeMerchantKey nvarchar(50) = '',
	@rHesabeMerchantIV nvarchar(50)='',
	@rHesabeVersion nvarchar(10) = '2.0',
	@rHesabeIsLiveEnvironment bit = null
		
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY

	IF(@rId = 0)	
	BEGIN
		IF EXISTS(SELECT Id FROM [sOp].[tGatewayProduct] WHERE GatewayConfigurationId=@rGatewayConfigurationId AND Title=@rTitle AND ProductId = @rProductId)
		BEGIN
			SELECT -101 AS Result
			RETURN
		END 
	END
	ELSE
	BEGIN
		IF  EXISTS(SELECT Id FROM [sOp].[tGatewayProduct] WHERE GatewayConfigurationId=@rGatewayConfigurationId AND Title=@rTitle AND ProductId = @rProductId AND Id<>@rId)
		BEGIN
			SELECT -101 AS Result
			RETURN
		END
	END	

	BEGIN TRANSACTION	
	DECLARE @lNextNumber INT     
	IF(@rId = 0)	
	BEGIN

	EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sOp.tGatewayProduct', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	INSERT INTO [sOp].[tGatewayProduct]
		(
			[Id],
			[GatewayConfigurationId],
			[Title],
			[GatewayURL],
			[ServerPort],
			[LoginId],
			[LoginPassword],
			[ProductId],
			[CCAvenueMerchantID],
			[CCAvenueAccessCode],
			[CCAvenueWorkingKey],
			[CCAvenueWhitelistURL],
			[CCAvenueSubAccountId],
			[AtomReqHashKey],
			[AtomRespHashKey],
			[PaytmMID],
			[PaytmMerchantKey],
			[PaytmChannelId],
			[PaytmIndustryTypeId],
			[PaytmWebsite],
			[PaytmStatusCheckURL],
			[PayUMoneyMERCHANTID],
			[PayUMoneyMERCHANTKEY],
			[PayUMoneySALT],
			[PayUMoneyHASHSEQUENCE],
			[PayUMoneyAUTHHEADER],
			[BillDeskMerchantID],
			[BillDeskChecksumKey],
			[BillDeskSecurityID],
			[BillDeskUniqueIdentifier],
			[EazypayMerchantId],
			[EazypayAESKey],
			[AxisMerchantId],
			[AxisAPIKey],
			[AxisResponseKey],
			[RazorpayMID],
			[RazorpayKeyID],
			[RazorpaySecretKey],
			[BBPSCharges],
			[BBPSGST],
			[GrayQuestClientId],
			[GrayQuestSecretKey],
			[GrayQuestAPIKey],
			[EasebuzzKey],
			[EasebuzzSalt],
			[EasebuzzIsLiveEnvironment],
			[EasebuzzIsEnableiFrame],
			[EasebuzzSubMerchantId],
			HesabeAccessCode,
			HesabeMerchantKey,
			HesabeMerchantIV,
			HesabeMerchantCode,
			HesabeVersion,
			HesabeIsLiveEnvironment,
			RazorpaySubMerchantId
		)
		VALUES
		(
			@lNextNumber,
			@rGatewayConfigurationId,
			@rTitle,
			@rGatewayURL,
			@rServerPort,
			@rLoginId,
			@rLoginPassword,
			@rProductId,
			@rCCAvenueMerchantID,
			@rCCAvenueAccessCode,
			@rCCAvenueWorkingKey,
			@rCCAvenueWhitelistURL,
			@rCCAvenueSubAccountId,
			@rAtomReqHashKey,
			@rAtomRespHashKey,
			@rPaytmMID,
			@rPaytmMerchantKey,
			@rPaytmChannelId,
			@rPaytmIndustryTypeId,
			@rPaytmWebsite,
			@rPaytmStatusCheckURL,
			@rPayUMoneyMERCHANTID,
			@rPayUMoneyMERCHANTKEY,
			@rPayUMoneySALT,
			@rPayUMoneyHASHSEQUENCE,
			@rPayUMoneyAUTHHEADER,
			@rBillDeskMerchantID,
			@rBillDeskChecksumKey,
			@rBillDeskSecurityID,
			@rBillDeskUniqueIdentifier,
			@rEazypayMerchantId,
			@rEazypayAESKey,
			@rAxisMerchantId,
			@rAxisAPIKey,
			@rAxisResponseKey,
			@rRazorpayMID,
			@rRazorpayKeyID,
			@rRazorpaySecretKey,
			@rBBPSCharge,
			@rBBPSGST,
			@rGrayQuestClientId,
			@rGrayQuestSecretKey,
			@rGrayQuestApiKey,
			@rEasebuzzKey,
			@rEasebuzzSalt,
			@rEasebuzzIsLiveEnvironment,
			@rEasebuzzIsEnableiFrame,
			@rEasebuzzSubMerchantId,
			@rHesabeAccessCode,
			@rHesabeMerchantKey,
			@rHesabeMerchantIV,
			@rHesabeMerchantCode,
			@rHesabeVersion,
			@rHesabeIsLiveEnvironment,
			@rRazorpaySubMerchantId
		)
		    SELECT 1 AS Result
	END	 
ELSE
	 BEGIN
		SET @lNextNumber = @rId
	    UPDATE  [sOp].[tGatewayProduct]
	    SET
			[GatewayConfigurationId]=@rGatewayConfigurationId,
			[Title]=@rTitle,
			[GatewayURL]=@rGatewayURL,
			[ServerPort]=@rServerPort,
			[LoginId]=@rLoginId,
			[LoginPassword]=@rLoginPassword,
			[ProductId]=@rProductId,
			[CCAvenueMerchantID]=@rCCAvenueMerchantID,
			[CCAvenueAccessCode]=@rCCAvenueAccessCode,
			[CCAvenueWorkingKey]=@rCCAvenueWorkingKey,
			[CCAvenueWhitelistURL]=@rCCAvenueWhitelistURL,
			[CCAvenueSubAccountId]=@rCCAvenueSubAccountId,
			[AtomReqHashKey]=@rAtomReqHashKey,
			[AtomRespHashKey]=@rAtomRespHashKey,
			[PaytmMID]=@rPaytmMID,
			[PaytmMerchantKey]=@rPaytmMerchantKey,
			[PaytmChannelId]=@rPaytmChannelId,
			[PaytmIndustryTypeId]=@rPaytmIndustryTypeId,
			[PaytmWebsite]=@rPaytmWebsite,
			[PaytmStatusCheckURL]=@rPaytmStatusCheckURL,
			[PayUMoneyMERCHANTID]=@rPayUMoneyMERCHANTID,
			[PayUMoneyMERCHANTKEY]=@rPayUMoneyMERCHANTKEY,
			[PayUMoneySALT]=@rPayUMoneySALT,
			[PayUMoneyHASHSEQUENCE]=@rPayUMoneyHASHSEQUENCE,
			[PayUMoneyAUTHHEADER]=@rPayUMoneyAUTHHEADER,
			[BillDeskMerchantID]=@rBillDeskMerchantID,
			[BillDeskChecksumKey]=@rBillDeskChecksumKey,
			[BillDeskSecurityID]=@rBillDeskSecurityID,
			[BillDeskUniqueIdentifier]=@rBillDeskUniqueIdentifier,
			[EazypayMerchantId]=@rEazypayMerchantId,
			[EazypayAESKey]=@rEazypayAESKey,
			[AxisMerchantId]=@rAxisMerchantId,
			[AxisAPIKey]=@rAxisAPIKey,
			[AxisResponseKey]=@rAxisResponseKey,
			[RazorpayMID]=@rRazorpayMID,
			[RazorpayKeyID]=@rRazorpayKeyID,
			[RazorpaySecretKey]=@rRazorpaySecretKey,
			[BBPSCharges] = @rBBPSCharge,
			[BBPSGST] = @rBBPSGST,
			GrayQuestClientId = @rGrayQuestClientId,
			GrayQuestSecretKey = @rGrayQuestSecretKey,
			GrayQuestAPIKey = @rGrayQuestApiKey,
			[EasebuzzKey] = @rEasebuzzKey,
			[EasebuzzSalt] = @rEasebuzzSalt,
			[EasebuzzIsLiveEnvironment] = @rEasebuzzIsLiveEnvironment,
			[EasebuzzIsEnableiFrame] = @rEasebuzzIsEnableiFrame,
			[EasebuzzSubMerchantId] = @rEasebuzzSubMerchantId,
			HesabeAccessCode = @rHesabeAccessCode,
			HesabeMerchantKey = @rHesabeMerchantKey,
			HesabeMerchantIV = @rHesabeMerchantIV,
			HesabeMerchantCode = @rHesabeMerchantCode,
			HesabeVersion = @rHesabeVersion,
			HesabeIsLiveEnvironment = @rHesabeIsLiveEnvironment,
			RazorpaySubMerchantId = @rRazorpaySubMerchantId
	    WHERE Id = @rId
	    SELECT 11 AS Result
	 END  	

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


GO
ALTER PROCEDURE [sOp].[pGatewayProductGet]

	 @rId int,
	 @rGatewayConfigurationId int,
	 @rTitle nvarchar(150),
	 @rOrgGroupId int
	 	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
	BEGIN
		SET @rTitle = sCommon.fSearchStringGet(@rTitle)
	END
	
	SELECT 
			GP.Id,
			GP.GatewayConfigurationId,
			PGM.Title AS PaymentGatewayName,
			GP.Title AS GatewayProductName,
			ISNULL(GP.GatewayURL,'') AS GatewayURL,
			ISNULL(GP.ServerPort,'') AS ServerPort,
			ISNULL(GP.LoginId,'') AS LoginId,
			ISNULL(GP.LoginPassword,'') AS LoginPassword,
			ISNULL(GP.ProductId,'') AS ProductId,
			
			ISNULL(GP.CCAvenueMerchantID,'') AS CCAvenueMerchantID,
			ISNULL(GP.CCAvenueAccessCode,'') AS CCAvenueAccessCode,
			ISNULL(GP.CCAvenueWorkingKey,'') AS CCAvenueWorkingKey,
			ISNULL(GP.CCAvenueWhitelistURL,'') AS CCAvenueWhitelistURL,
			ISNULL(GP.CCAvenueSubAccountId,'') AS CCAvenueSubAccountId,
			
			ISNULL(GP.AtomReqHashKey,'') AS AtomReqHashKey,
			ISNULL(GP.AtomRespHashKey,'') AS AtomRespHashKey,
			ISNULL(GP.PaytmMID,'') AS PaytmMID,
			ISNULL(GP.PaytmMerchantKey,'') AS PaytmMerchantKey,
			ISNULL(GP.PaytmChannelId,'') AS PaytmChannelId,
			ISNULL(GP.PaytmIndustryTypeId,'') AS PaytmIndustryTypeId,
			ISNULL(GP.PaytmWebsite,'') AS PaytmWebsite,
			ISNULL(GP.PaytmStatusCheckURL,'') AS PaytmStatusCheckURL,
			ISNULL(GP.PayUMoneyMERCHANTID,'') AS PayUMoneyMERCHANTID,
			ISNULL(GP.PayUMoneyMERCHANTKEY,'') AS PayUMoneyMERCHANTKEY,
			ISNULL(GP.PayUMoneySALT,'') AS PayUMoneySALT,
			ISNULL(GP.PayUMoneyHASHSEQUENCE,'') AS PayUMoneyHASHSEQUENCE,
			ISNULL(GP.PayUMoneyAUTHHEADER,'') AS PayUMoneyAUTHHEADER,
			
			ISNULL(GP.BillDeskMerchantID,'') AS BillDeskMerchantID,
			ISNULL(GP.BillDeskChecksumKey,'') AS BillDeskChecksumKey,
			ISNULL(GP.BillDeskSecurityID,'') AS BillDeskSecurityID,
			ISNULL(GP.BillDeskUniqueIdentifier,'') AS BillDeskUniqueIdentifier,
			ISNULL(GP.EazypayMerchantId,'') AS EazypayMerchantId,
			ISNULL(GP.EazypayAESKey,'') AS EazypayAESKey,

			ISNULL(GP.AxisMerchantId,'') AS AxisMerchantId,
			ISNULL(GP.AxisAPIKey,'') AS AxisAPIKey,
			ISNULL(GP.AxisResponseKey,'') AS AxisResponseKey,

			ISNULL(GP.RazorpayMID,'') AS RazorpayMID,
			ISNULL(GP.RazorpayKeyID,'') AS RazorpayKeyID,
			ISNULL(GP.RazorpaySecretKey,'') AS RazorpaySecretKey,

			ISNULL(GP.BBPSCharges,'') AS BBPSCharges,
			ISNULL(GP.BBPSGST,0) AS BBPSGST,

			ISNULL(GP.GrayQuestClientId,'') AS GrayQuestClientId,
			ISNULL(GP.GrayQuestSecretKey,'') AS GrayQuestSecretKey,
			ISNULL(GP.GrayQuestApiKey,'') AS GrayQuestApiKey,

			ISNULL(GP.EasebuzzKey,'') AS EasebuzzKey,
			ISNULL(GP.EasebuzzSalt,'') AS EasebuzzSalt,
			ISNULL(GP.EasebuzzIsLiveEnvironment, 0) AS EasebuzzIsLiveEnvironment,
			ISNULL(GP.EasebuzzIsEnableiFrame, 0) AS EasebuzzIsEnableiFrame,
			ISNULL(GP.EasebuzzSubMerchantId,'') AS EasebuzzSubMerchantId,

			ISNULL(GP.HesabeAccessCode,'') AS HesabeAccessCode,
			ISNULL(GP.HesabeMerchantKey,'') AS HesabeMerchantKey,
			ISNULL(GP.HesabeMerchantIV, '') AS HesabeMerchantIV,
			ISNULL(GP.HesabeMerchantCode, '') AS HesabeMerchantCode,
			ISNULL(GP.HesabeVersion, '2.0') AS HesabeVersion,
			ISNULL(GP.HesabeIsLiveEnvironment,0) AS HesabeIsLiveEnvironment,

			ISNULL(GP.RazorpaySubMerchantId, '') AS RazorpaySubMerchantId
	FROM 
			[sOp].[tGatewayProduct] GP
			INNER JOIN [sOp].[tGatewayConfiguration] GC ON GC.Id = GP.GatewayConfigurationId
			INNER JOIN [sOp].[tPaymentGatewayMaster] PGM ON PGM.Id = GC.PaymentGatewayId
	WHERE 
			(GC.OrgGroupId = @rOrgGroupId)
			AND	((GP.Id = @rId) OR (@rId = 0))
			AND	((GP.GatewayConfigurationId = @rGatewayConfigurationId) OR (@rGatewayConfigurationId = 0))
			AND ((GP.Title like @rTitle) OR (ISNULL(@rTitle,'') = ''))
			AND ISNULL(GC.IsObsolete,0) = 0
END
GO
PRINT N'Altering Procedure [sStudent].[pStudentGenerateReport]...';


GO


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

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

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


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

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

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

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

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


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

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

		Exam13Name nvarchar(100),	
		TotalMarks13 decimal(8,2),
		TotalObtain13 decimal(8,2),
		Percentage13 decimal(5,2),
		RankNumber13 int,
		ResultGrade13 NVarchar(10),
		Percentile13 decimal(5,2),
		ResultStatus13 Nvarchar(50),
		Exam13CombineExamName Nvarchar(100),
		
		ResultRemark1 nvarchar(200),
		ResultRemark2 nvarchar(200),
		
		TotalDays decimal(6,2),
		PresentDays decimal(6,2),
		StudentHeight decimal(6,2),
		StudentWeight decimal(6,2),
		ExamSeatNo nvarchar(20),
		ExamId int,
		
		ExamCode nvarchar(20),
		Exam1Code nvarchar(20),
		Exam2Code nvarchar(20),
		Exam3Code nvarchar(20),
		Exam4Code nvarchar(20),
		Exam5Code nvarchar(20),
		Exam6Code Nvarchar(20),
		Exam7Code Nvarchar(20),
		Exam8Code nvarchar(20),
		Exam9Code nvarchar(20),
		Exam10Code nvarchar(20),
		Exam11Code nvarchar(20),
		Exam12Code nvarchar(20),
		Exam13Code nvarchar(20),
		
		IsDisplayParentName bit,
		FatherName nvarchar(100),
		MotherName nvarchar(100),
		IsShowSubjectMark bit, 
		IsOptionalSubject bit,
		CoScholasticScopeId tinyint,
		IsDisplayPrincipalSign bit,
		IsDisplayTeacherSign bit,
		EmployeeSign varbinary(max),
		Batch nvarchar(100),
		ExamNameTerm1 NVarchar(100),
		ExamNameTerm2 NVarchar(100) ,
		ExamNameTerm3 NVarchar(100),
		ClassTeacherName Nvarchar(100),
		FirstName nvarchar(100),
		LastName nvarchar(100),
		IsDisplayMonthlyAttendance bit,
		MarksheetHeaderA4 varbinary(max),
		IsImageHeader bit,
		MyGoal nvarchar(200),
		AreaOfInterest nvarchar(200),
		Responsibility nvarchar(200),
		MyInterestHobby nvarchar(200),
		MyStrength nvarchar(200),
		Achievements nvarchar(1000),
		
		DentalHygiene nvarchar(50),
		VisionLeft nvarchar(50),
		VisionRight nvarchar(50), 
		IsDetail bit,
		SubjectGroupId int,
		SubjectGroupTitle nvarchar(100),
		SubjectGroupCode nvarchar(20),
		DecimalFormat nvarchar(10),
		SubjectRemark nvarchar(100),
		GraceMark decimal(5,2),
		KrupaMark decimal(5,2),
		GradeStringHtml nvarchar(500),
		ResultRemark3 nvarchar(200),
		IsDisplayTotalMark bit,
		SubjectObtainTerm1 decimal(5,2),	
		SubjectObtainTerm2 decimal(5,2),
		SubjectObtainTerm3  decimal(5,2),
		SubjectMaxTerm1 decimal(10,2),
		SubjectMaxTerm2 decimal(10,2),
		SubjectMaxTerm3 decimal(10,2),
		ContactNo nvarchar(50),
		PresentAddress nvarchar(max),
		TeacherSignCaption nvarchar(100),
		PrincipalSignCaption nvarchar(100),
		ParentSignCaption nvarchar(100),
		ImprovementArea nvarchar(200),
		ProgressArea nvarchar(200),
		GeneralRemark nvarchar(1000),
		MyActivity nvarchar(200),
		ClassTeacherRemark nvarchar(1000),
		 
		HouseRemark nvarchar(1000),
		BloodGroup Nvarchar(20),
		TotalDays1 decimal(6,2),
		PresentDays1 decimal(6,2),
		TotalDays2 decimal(6,2),
		PresentDays2 decimal(6,2),
		TotalDays3 decimal(6,2),
		PresentDays3 decimal(6,2),
		TotalDays4 decimal(6,2),
		PresentDays4 decimal(6,2),
		TotalDays5 decimal(6,2),
		PresentDays5 decimal(6,2),
		TotalDays6 decimal(6,2),
		PresentDays6 decimal(6,2),
		TotalDays7 decimal(6,2),
		PresentDays7 decimal(6,2), 
		TotalDays8 decimal(6,2),
		PresentDays8 decimal(6,2),
		TotalDays9 decimal(6,2),
		PresentDays9 decimal(6,2),
		TotalDays10 decimal(6,2),
		PresentDays10 decimal(6,2),
		TotalDays11 decimal(6,2),
		PresentDays11 decimal(6,2),
		TotalDays12 decimal(6,2),
		PresentDays12 decimal(6,2),
		TotalDays13 decimal(6,2),
		PresentDays13 decimal(6,2),
		BatchIdText nvarchar(20),
		IsShowWithDetail bit,
		IsPresent bit,
		GradeTitle nvarchar(50),
		SubjectHighestDivisionGrade nvarchar(50),
		SubjectHighestDivisionMark decimal(5, 2),
		
		AchievementsTerm1 nvarchar(1000),
		AchievementsTerm2 nvarchar(1000),
		GeneralRemarkTerm1 nvarchar(1000),
		GeneralRemarkTerm2 nvarchar(1000),
		ResultRemark1Term1 nvarchar(200),
		ResultRemark2Term1 nvarchar(200),
		ResultRemark1Term2 nvarchar(200),
		ResultRemark2Term2 nvarchar(200),
		SR_HeightTerm1 decimal(6,2),
		SR_WeightTerm1 decimal(6,2),
		SR_HeightTerm2 decimal(6,2),
		SR_WeightTerm2 decimal(6,2),
		SR_PresentDaysTerm1 decimal(6,2),
		SR_PresentDaysTerm2 decimal(6,2),
		SR_TotalDaysTerm1 decimal(6,2),
		SR_TotalDaysTerm2 decimal(6,2),
		HouseId int,
		HouseName nvarchar(100),
		AdhaarNumber nvarchar(20),
		UIdNumber nvarchar(50),
		FatherContactNo nvarchar(50),
		MotherContactNo nvarchar(50),
		FatherMail nvarchar(50),
		MotherMail nvarchar(50),
		Gender nvarchar(100),
		CoordinatorEmployeeSign varbinary(max),
		StudentAddress nvarchar(max),
		SUId nvarchar(50),
		HighestDivisionMark decimal(5, 2),
		HighestDivisionGrade nvarchar(10),
		StreamTitle nvarchar(50),
		AdmissionNo nvarchar(50),
		AdmissionDate Date,
		MiddleName nvarchar(100) ,
		FatherOccupation nvarchar(50),
		ResultSheetAdditionalTitle nvarchar(100),
		IsDecimal bit,
		IsAbsentRemark bit,
		FinalAbsentRemark nvarchar(100),
		AbsentRemark1 nvarchar(100),
		AbsentRemark2 nvarchar(100),
		AbsentRemark3 nvarchar(100),
		AbsentRemark4 nvarchar(100),
		AbsentRemark5 nvarchar(100),
		AbsentRemark6 nvarchar(100),
		AbsentRemark7 nvarchar(100),
		AbsentRemark8 nvarchar(100),
		AbsentRemark9 nvarchar(100),
		AbsentRemark10 nvarchar(100),
		AbsentRemark11 nvarchar(100),
		AbsentRemark12 nvarchar(100),
		AbsentRemark13 nvarchar(100),
		ExamMaximumTerm1 decimal(6,2),
		ExamMaximumTerm2 decimal(6,2),
		ExamMaximumTerm3 decimal(6,2),
		--add for 29923 mantis start
		PermanentStreetOne nvarchar(150),
		PermanentStreetTwo nvarchar(150),
		PermanentStreetThree nvarchar(150),
		--add for 29923 mantis end
		CasteCategory nvarchar(50),--Mantis 0030303
		--Mantis Start - 0031091
		FeeCategory nvarchar(100),
		StudentContactNo nvarchar(50),
		--Mantis End - 0031091
		ObtainedMaximum1 decimal(10,2),
		ObtainedMaximum2 decimal(10,2),
		ObtainedMaximum3 decimal(10,2),
		ObtainedMaximum4 decimal(10,2),
		ObtainedMaximum5 decimal(10,2),
		ObtainedMaximum6 decimal(10,2),
		ObtainedMaximum7 decimal(10,2),
		ObtainedMaximum8 decimal(10,2),
		ObtainedMaximum9 decimal(10,2),
		ObtainedMaximum10 decimal(10,2),
		ObtainedMaximum11 decimal(10,2),
		ObtainedMaximum12 decimal(10,2),
		ObtainedMaximum13 decimal(10,2),
		ResultIndicator nvarchar(50),   -- Mantis - 31306
		IsResultIndicator bit,		-- Mantis - 31306
		ExamBlock nvarchar(100), --Mantis - 31848
		AbsentRemarkTerm1 nvarchar(100),    ---Mantis - 32090 - Start
		AbsentRemarkTerm2 nvarchar(100),
		AbsentRemarkTerm3 nvarchar(100),
		IsPresentTerm1 bit,
		IsPresentTerm2 bit,
		IsPresentTerm3 bit ,        ---Mantis - 32090 - End
		--Mantis Start - 0032150
		IsPercentage1 bit,
		IsPercentage2 bit,
		IsPercentage3 bit,
		IsPercentage4 bit,
		IsPercentage5 bit,
		IsPercentage6 bit,
		IsPercentage7 bit,
		IsPercentage8 bit,
		IsPercentage9 bit,
		IsPercentage10 bit,
		IsPercentage11 bit,
		IsPercentage12 bit,
		IsPercentage13 bit
		--Mantis End - 0032150

		)
	 --print 'temp created'    	
	INSERT INTO  #TempAllExam 
	(
	AcademicIdText,
	ExamIdText,
	CoScholasticScopeIdText,
	IsDisplayMonthlyAttendanceText,
	ClassIdText,
	AcademicId,
	ExamName,
	StudCode,
	StudentName,
	RollNo,
	ResultStatus,
	ClassName,
	Division,
	TotalMark,
	TotalObtain,
	Percentage,
	RankNumber,
	ResultGrade,
	IsMarksInDecimal,
	column_visible,
	--Obtain,
	Percentile,
	--ClassSubject,
	ResultDetailId,
	ResultId,

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


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

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

= AR.OrgGroupBatchId)) 
    LEFT JOIN
	(SELECT AT.SourceId,B.OrgGroupBatchId FROM sTransport.tAssignRoute AT 
    INNER JOIN sTransport.tBusRouteDestinationMaster BM ON BM.Id=AT.PickupDestinationId 
    INNER JOIN sTransport.tBusRouteMaster B ON B.Id=BM.BusRouteId AND  AT.SourceTypeId=2003 AND ((B.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))) RT
    ON RT.SourceId = StuM.Id 
	LEFT JOIN sHrm.tEmployeeImages EICoordinator ON EICoordinator.EmployeeId = EM.CoordinatorEmployeeId		  
	--LEFT JOIN sAcademic.tTeacherSubjectDivision TSD ON TSD.SubjectId=SM.Id AND TSD.DivisionId = A.DivisionId
	--LEFT JOIN sHrm.tEmployeeMaster EMP ON TSD.EmployeeId = EMP.Id
	LEFT JOIN sStudent.tStudentAdmission StuA ON StuM.Id = StuA.StudentId
	LEFT JOIN sCommon.tCastCategoryMaster CSM ON CSM.Id=SO.CastCategoryId        --Mantis 0030303
	LEFT JOIN sStudent.tAdmissionCategoryMaster ACM ON ACM.Id=StuM.AdmissionCategoryId	--Mantis - 0031091
	 
	 WHERE
		R.ExamId = @rExamId 
		AND ((A.DivisionId =  @rDivisionId) OR (@rDivisionId=0))
		AND ((A.ClassId =  @rClassId) OR (@rClassId=0))		 
		AND ((A.BatchId =  @rBatchId) OR (@rBatchId=0))
		AND ((A.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
		AND ((A.RollNo <= @rToRollNo) OR (@rToRollNo=0))
		AND ((R.RankNumber >= @rFromRank) OR (@rFromRank=0))
		AND ((R.RankNumber <= @rToRank) OR (@rToRank=0))
		AND ((R.ResultGrade = @rGrade) OR (@rGrade=''))
		AND ((StuM.Code=@rCode) OR (@rCode=''))	
		AND ((R.Id = @rResultId) OR (@rResultId = 0))	
		AND ((StuM.StatusId=@rStatusId)OR(@rStatusId=0))
		AND((A.Id=@rAcademicId)OR (@rAcademicId=0))
		AND ((CS.SubjectId=@rSubjectId) OR(@rSubjectId=0) ) 
		AND ((R.TotalObtain>=@rFromObtain) OR (@rFromObtain=0))
		AND ((R.TotalObtain<=@rToObtain) OR (@rToObtain=0))
		AND ((R.Percentage>=@rFromPercentage) OR (@rFromPercentage=0))
		AND ((R.Percentage<=@rToPercentage) OR (@rToPercentage=0))
		
		 AND (
	 (@rFilterId = 0) -- All
     OR (@rFilterId = 2 AND isnull(AR.SourceId,0)!=0) -- Hostel
     OR (@rFilterId = 3 AND isnull(RT.SourceId,0)!=0) -- Transport
     OR ((@rFilterId =1) AND ((isnull(AR.SourceId,0)=0) AND (isnull(RT.SourceId,0)=0)))
    )
	AND ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0)) 
	AND (ISNULL(StuM.Code,0) IN( SELECT cast(item as nvarchar(20)) FROM  sCommon.fnsplit(@rMultiCode,',')) OR @rMultiCode='')
	    
	Order By ED.DisplayOrder

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

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

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

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

 --             0 As Percentile ,

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

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

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

 --       '' AS ExamCode,

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

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

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

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

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

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


GO


ALTER PROCEDURE [sMis].[pRptResultAnalysisSubjectWiseWithAttendanceGet]
	 
		@rBuilder1 nvarchar(max)='',
		@rBuilder2 nvarchar(max)='', 	
		@rOrgGroupBatchId int,
		@rExamId int,
		@rOrgId int = 0,
		@rClassId int = 0,
		@rDivisionId int = 0,
		@rClassSubjectId int = 0

	 
	
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 		
 
 
 
		Select Distinct
		@rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,
		OMGM.Id AS OrgMainGroupId,
		OMGM.Code AS OrgMainGroupName,
		OSGM.Id AS OrgSubGroupId,
		OSGM.Code AS SubGroupName,
		OM.Title AS OrgName,
		DM.Id AS DepartmentId,
		stum.OrgId,
		Stum.Code,
		[sStudent].[fStudentNameGet](stum.FirstName , StuM.MiddleName, StuM.LastName,OM.StudentNameFormatId ) AS Name,
		A.RollNo,
		A.Id AS AcademicId,			
		CM.DisplayTitle AS Class,
		CM.Id As ClassId,
		DM.DisplayTitle AS Division,
		DM.Id AS DivisionId,
		ESGM.Title AS Exam,
		CS.Id AS SubjectId,	
		SM.Code AS SubjectCode,
		SM.Title AS SubjectName,
		BM.OrgGroupBatchId,
		RD.Obtain,
		[sAssessment].[fGetConfigurationGrade](stum.OrgId,RD.Obtain) AS SubjectGrade,
		R.Percentage,
		[sAssessment].[fGetConfigurationGrade](stum.OrgId,R.Percentage)AS ResultGrade,
		@rExamId AS ExamId,
		(CASE WHEN (SR.PresentDays<>0 AND SR.TotalDays<>0) THEN ROUND(((CAST(SR.PresentDays AS FLOAT)/CAST(SR.TotalDays AS FLOAT))*100),2) ELSE 0 END)AS Attendance,
		ISNULL(SR.PresentDays,0)AS PresentDays,
		ISNULL(SR.TotalDays,0)AS TotalDays
		
		
		 from sStudent.tStudentMaster Stum 
		INNER JOIN  sStudent.tAcademic A ON Stum.Id=A.StudentId
		INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId
		INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId
		INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId
		INNER JOIN sSetup.tOrganizationMaster OM ON Stum.OrgId = OM.Id
		INNER JOIN sAssessment.tResult R ON A.Id=R.AcademicId
		INNER JOIN sAssessment.tResultDetail RD ON R.Id = RD.ResultId
		INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId
		INNER JOIN sAssessment.tExamMaster EM ON EM.Id=R.ExamId
		INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id = EM.EXAMSUBGROUPID
		--INNER JOIN sAssessment.tExamTypeMaster ETM ON ETM.Id=ESGM.ExamTypeId
		INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
		INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=CS.SubjectId
		INNER JOIN sSetup.tOrgSubGroupMaster OSGM ON OSGM.Id = OM.OrgSubGroupId
		INNER JOIN sSetup.tOrgMainGroupMaster OMGM ON OMGM.Id = OSGM.OrgMainGroupId	
		INNER JOIN sSetup.tDepartmentMaster DeptM ON DeptM.Id=CM.DepartmentId
		LEFT JOIN sAssessment.tStudentRemark SR ON R.AcademicId = SR.AcademicId AND R.ExamId = SR.ExamId

		WHERE		
			EM.Id=@rExamId
			AND (OM.Id = @rOrgId OR @rOrgId = 0)
			AND BM.OrgGroupBatchId = @rOrgGroupBatchId
			AND CM.Id = @rClassId
			AND (DM.Id = @rDivisionId OR @rDivisionId = 0)
			AND (CS.Id = @rClassSubjectId OR @rClassSubjectId = 0)

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


GO

 
ALTER PROCEDURE [sProcurement].[pRptStockIssueStudent]
 
	@rId int = 0,
	@rStoreLocationId int = 0,
	@rMainGroupId int=0,
	@rSubGroupId int=0,
	@rItemCode nvarchar(50)='',
	@rItemName nvarchar(50)='',
	@rOrgGroupId int=0,
	@rBuilder1 nvarchar(max)='',
	@rBuilder2 nvarchar(max)='',
	@rReportId int=0,
	@rStockItemCategoryId int=0,
	@rFromDate date='',
	@rTodate date='',
	@rToDepartmentId int =0,
	@rNumber nvarchar(10)='',
	@rAcademicId bigint = 0,
	@rOrgId smallint = 0,
	@rBatchId int = 0
	
WITH EXECUTE AS CALLER
AS
BEGIN
	
	SET NOCOUNT ON;
	SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED
	Declare @lIDConfigValue nvarchar(50)=''
	SELECT @lIDConfigValue =ItemValue From sConfig.tConfigurationSetup
	WHERE ConfigurationId = 236 AND SourceId = @rOrgGroupId

       SELECT  
			@rBuilder1 AS Builder1,
			SIM.Code AS ItemNumber,
			SIM.Title AS ItemName,		
			SI.IssuedByName,	
			SI.Number, 	
			SI.CreatedDateTime AS IssuedDate,
			ID.IssuedQuantity,
			ID.RequestedQuantity,
			SM.FirstName +' '+SM.MiddleName As StudentName,
			Sm.Code AS StudentCode,
			SG.Code AS ItemSubGroup,
			SG.Id AS ItemSubGroupId,
			OM.DisplayTitle,
			BM.Title AS BatchTitle,
			CM.Title +'-'+ DM.TItle As Class,
			(SELECT ISNULL(SUM(AvailableQuantity),0) FROM sProcurement.tStockBatch SB 
		    WHERE SB.StockItemId = SIM.Id 
		    AND ((SB.StorelocationId = @rStoreLocationId) OR (@rStoreLocationId = 0))
			) AS Quantity ,
			A.OrgId,
			A.BatchId,
			ISNULL(CAST(SIP.WeightedAverageCost AS DECIMAL(18, 2)), '0') AS WeightedAverageCost,
			@lIDConfigValue AS IdNoLabel,
			((ISNULL(CAST(SIP.WeightedAverageCost AS DECIMAL(18, 2)), '0')) * (ID.IssuedQuantity)) AS Amount,

			(sFinanceCommon.fNumberToWordsWithDecimal(
			((ISNULL(CAST(SIP.WeightedAverageCost AS DECIMAL(18, 2)), '0')) * (ID.IssuedQuantity)),1,2,SI.OrgGroupId)
			) AS AmountInWords,
			SI.Remark--Mantis - 0032620
		
		FROM  
			sProcurement.tStockIssue SI		
			INNER JOIN sProcurement.tStockIssueDetail ID ON SI.Id = ID.StockIssueId
			INNER JOIN sIp.tStockItemMaster SIM ON ID.StockItemId  = SIM.Id 
			LEFT JOIN sIp.tStockItemPlanning SIP ON SIP.StockItemId=SIM.Id AND SIP.StoreLocationId=@rStoreLocationId
			INNER JOIN sStudent.tAcademic A on A.Id=IssueToSourceId
			INNER JOIN sStudent.tStudentMaster SM ON SM.Id = A.StudentID
			INNER JOIN sIp.tItemSubGroupMaster SG ON SG.Id=SIM.ItemSubGroupId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=A.OrgId
			INNER JOIN sSetup.tClassMaster CM on CM.id =A.ClassId 
			INNER JOIN sSetup.tDivisionMaster DM on DM.Id=A.DivisionId
			INNER JOIn sSetup.tBatchMaster BM ON BM.Id = A.BatchId
		WHERE 
			 ((SI.Id = @rId) OR (@rId=0))
			 AND SI.FromStoreLocationId =@rStoreLocationId
			 AND ((SIM.ItemSubGroupId= @rSubGroupId) OR (@rSubGroupId=0))
			 AND ((SIM.Code = @rItemCode) OR (@rItemCode=''))	
			 AND ((SIM.Title = @rItemName) OR (@rItemName=''))
			 AND ((convert(Date,ISNULL(SI.CreatedDateTime,'')) >= @rFromDate) OR (convert(date,ISNULL(@rFromDate,''))=''))
			 AND ((convert(date,ISNULL(SI.CreatedDateTime,'')) <= @rToDate) OR (convert(date,ISNULL(@rToDate,''))=''))
			 AND SI.OrgGroupId = @rOrgGroupId
			 AND ((SI.ToOrganizationDepartmentId=@rToDepartmentId) OR (@rToDepartmentId=0))
			 AND ((SI.Number like @rNumber) OR  (ISNULL(@rNumber,'')= ''))
			 AND ((SI.IssueToSourceId= @rAcademicId) OR (ISNULL(@rAcademicId,0)=0))
			 AND SI.IssueToSourceTypeId = 2001
			 AND ((A.OrgId = @rOrgId) OR (ISNULL(@rOrgId,0) = 0))
			 --AND ((A.BatchId = @rBatchId) OR (ISNULL(@rBatchId,0) = 0))
END




/****** Object:  StoredProcedure [sProcurement].[pRptStockItemMaxInventory]    Script Date: 07/09/2013 16:27:32 ******/
SET ANSI_NULLS ON
GO
PRINT N'Altering Procedure [sCertificate].[pRptLeavingCertificateGet]...';


GO

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

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

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


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

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


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

	--add for 27638 mantis start
	DECLARE @lIsShowPhoto bit = 0
	SELECT @lConfigValue = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 124 AND SourceTypeId = 1016 AND SourceId = @rOrgId
	
	IF (@lConfigValue IS NULL) OR (@lConfigValue = 'False')
	SET @lIsShowPhoto = 0
	ELSE
	SET @lIsShowPhoto = 1
	--add for 27638 mantis end
	
	SELECT
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			--MR.PresentCount AS PresentDays ,
			--MR.TotalCount AS TotalDays ,
			L.Id,
			--(SELECT SUM(MR.PresentCount) FROM sAttendance.tMonthlyRegister MR WHERE MR.AcademicId=A.Id) AS PresentDaysSum ,
			--(SELECT SUM(MR.TotalCount) FROM sAttendance.tMonthlyRegister MR WHERE MR.AcademicId=A.Id) AS TotalDaysSum ,
			SM.Code,
			L.AcademicId,
			SM.FirstName,SM.MiddleName,SM.LastName,
			[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,
			--0 As CastCategoryId,
			--ISNULL(SO.CastCategoryId,0) As CastCategoryId,
			ISNULL(RM.Title,'') AS Religion,
			ISNULL(so.BirthPlace,'') AS BirthPlace,
			ISNULL(SO.BirthTaluka,'') AS BirthTaluka,
			ISNULL(SO.BirthDistrict,'') AS BirthDistrict,
			SO.DateOfBirth,
			ISNULL(SO.BirthDateInWord,'') AS BirthDateInWord,
			SA.PreviousSchool,
			SA.AdmissionDate,
			L.LCNumber,
			L.LeftDate,
			L.LCReason,
			L.LCProgress,
			L.LCConduct,
			L.LCRemark,
			L.LCDate,
			L.LCBookNumber,
			SO.GenderId,
			
			ISNULL(SO.FamilySubCast,'') AS SubCaste,
			ISNULL(SO.FamilyCast,'') AS Caste,
			ISNULL(OM.CityName,'') AS City,
			ISNULL(SC.PresentState,'') AS CityState,
			CM.DisplayTitle AS AdmissionStandard,
			CMS.DisplayTitle AS CurrentStandard,
			CMS.Title AS CurrentStandardTitle,
			--'' AS CurrentStandardInWords,
			SM.StatusId,
			L.LastExamName AS Result,
			L.LastExamResult AS FailOrPass,
			L.SubjectStudied AS SubjectNAme,
			L.RepeatDetail as PromotedorNot,
			--ISNULL(SubM.Title,'') AS SubjectNAme,
			--'' AS PromotedorNot,
			ISNULL(L.PromoteToClass,'')  AS PromotedToClass,
			L.FeeDetail AS LastFeesPaid,
			L.FeeConcessionDetail AS AnyConcession,
			L.NCCScoutDetail  AS NCCScoutDetail,
			L.ExtraCurricularActivities AS GamesPlayed,
			OM.OrgLogo,
			OM.Title AS OrgTitle,
			OM.StreetOne+' '+OM.StreetTwo+' '+OM.StreetThree AS OrgAddress,
			OM.PhoneNo,
			vSA.RollNo,
			DM.OrderIndex AS DivisionOrder,
			OM.SmallAddress1,
			OM.SmallAddress2,
			OM.RegistrationDetail,
			@lIsOnPrePrinted AS IsOnPrePrinted,
			@lIsDisplayReligion AS IsDisplayReligion,
			AD.PresentDaysAnnual AS PresentDaysSum,
			AD.TotalDaysAnnual AS TotalDaysSum,
			vSA.ClassName AS ClassName,
			vSA.DivisionName AS DivisionName,
			@lIsDisplayImageHeader AS IsDisplayImageHeader,
			--OI.CertificateHeaderA4  ,
			isnull(MainCastCategoryId,0) AS CastCategoryId,
			ISNULL(L.ToCollege,'') AS ToCollege ,
			ISNULL(L.ToCollegeAddress,'')AS ToCollegeAddress,
			ISNULL(OM.University,'')AS University,
			@lSchoolRemark1 AS SchoolRemark1 ,
			@lSchoolRemark2 AS SchoolRemark2 ,
			@lSchoolRemark3 AS SchoolRemark3 ,
			@lSchoolRequiredSignature AS SchoolRequiredSignature,
			ISNULL(CMS.ClassNameInWord,'')AS CurrentStandardInWords,
			SO.MotherTongue,
			SO.AdhaarNumber,
			vSA.SUId,
			CASE WHEN isnull(BM.FromDate,'')>Isnull(SA.AdmissionDate,'') THEN BM.FromDate ELSE SA.AdmissionDate END AS BatchDate,
			SO.BirthState,
			SO.BirthCountry,
			SD.BankAccountNumber,
			SO.UIDNumber,
			SD.BankName,
			SD.BankIFSCCode,
			SA.PreviousStandard 
			,L.TermsInInstitute,
			@lIDConfigValue AS ItemValue 
			,L.LCCopy
			,DM.InchargeEmployeeId AS ClassTeacher
			,vSA.BatchName AS BatchName,
			CSM.Title As CasteCategory,
			ISNULL(SA.AdmissionNumber,'') AS AdmissionNumber,
			SI.StudentPhoto,
			SA.AdmissionFormNumber,
			BM.FromDate as BatchStartDate,
			BM.ToDate as BatchEndDate,
			SO.UIDNumber,
			SC.PresentStreetOne AS Address1,
			SC.PresentStreetTwo AS Address2,
			SC.PresentStreetThree AS Address3,
			SC.PresentCity AS PresentCity,
			SC.PresentZipCode AS PresentZipCode,
			ISNULL(OM.ReportOrgGroupTitle,'') AS ReportOrgGroupTitle,
			OM.ReportOrgTitle,
			OI.CertificateHeaderA4Portrait AS CertificateHeaderA4,
			ISNULL(SA.PreviousSchool,'') AS PreviousSchool,
			L.TotalDays,
			L.PresentDays,
			ISNULL(CMS.ClassNameInWord,'') AS ClassNameInWord,
			vSA.ClassId AS ClassId,
		--sFinanceCommon.fNumberToWords(ISNULL(CM.ClassGroupId,0),'',OM.OrgGroupId) AS CurrentStandardInWords
		--CASE WHEN @rIsTransferCerti=1
		--THEN ISNULL(MR.PresentCount,0)
		--WHEN @rIsTransferCerti=0
		--THEN SUM(ISNULL(MR.PresentCount,0))
		--END AS Presentdays,
		--CASE WHEN @rIsTransferCerti=1
		--THEN ISNULL(MR.TotalCount,0)
		--WHEN @rIsTransferCerti=0
		--THEN SUM(ISNULL(MR.TotalCount,0))
		--END AS TotalCount
		@rUserName AS UserName,
		EI.EmployeeSign,
		EI1.EmployeeSign AS DivisionInchargeEmployeeSign,
		ISNULL(L.ProofOfDOB,'')AS ProofOfDOB,
		U.LoginTitle AS CreatedUserName,
		OM.PrincipalSignature,
		CM.ClassNameInWord AS AdmissionStandardInWord,
		LM.Title AS LanguageTitle,
		@lIsShowPhoto AS IsShowPhoto,		--add for 27638 mantis start
		CAST((CASE WHEN SI.QRCode IS NULL THEN 0 ELSE 1 END) AS bit) AS IsDisplayQRCode,
		ISNULL(SI.QRCode,'') AS QRCode		--add for 27638 mantis end 
		,ISNULL(L.LCCopyRemark,'') AS LCCopyRemark    --add for 28079 mantis end 
		,SH.IdentificationMark1 AS IdentificationMark1,
		ISNULL(L.LastExamName ,'') AS LastExamName,--Mantis - 0032104
		vSA.PENNumber     --mantis - 0032285
		                                    
	FROM 
			sCertificate.tLeaving L
			INNER JOIN sStudent.vStudentAcademic vSA ON vSA.AcademicId=L.AcademicId
			--INNER JOIN sStudent.tAcademic A ON L.AcademicId=A.Id
			LEFT JOIN sStudent.tStudentAdmission SA ON SA.StudentId=vSA.StudentId
			INNER JOIN sStudent.tStudentMaster SM ON SM.Id=vSA.StudentId			
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=vSA.OrgId 
			INNER JOIN sSecurity.tUser U ON U.Id = L.CreatedUserId
			LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId=vSA.StudentId 
			LEFT JOIN sCommon.tReligionMaster RM ON SO.ReligionId=RM.Id
			--LEFT JOIN  sAttendance.tMonthlyRegister MR ON MR.AcademicId=A.Id 
			LEFT JOIN sSetup.tClassMaster CM ON CM.Id=SA.AdmissionStandardId
			INNER JOIN sSetup.tDivisionMaster DM ON vSA.DivisionId = DM.Id  
			INNER JOIN sSetup.tClassMaster CMS ON CMS.Id= DM.ClassId 
			LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId=vSA.StudentId
			LEFT JOIN sCommon.tCountryMaster CTM ON CTM.Id=SO.NationalityId
			LEFT JOIN sStudent.tAcademicDetail AD ON AD.AcademicId=vSA.AcademicId
			--LEFT JOIN sSetup.tClassSubject CS ON CS.ClassId=A.ClassId
			--LEFT JOIN sSetup.tSubjectMaster SubM ON SM.Id=CS.SubjectId
			LEFT JOIN sSetup.tOrgImages OI ON OI.OrgId = OM.Id
			LEFT JOIN sCommon.tCastCategoryMaster CSM ON CSM.Id=SO.CastCategoryId
			--LEFT JOIN sSetup.tClassGroupMaster CSG ON CSG.Id=CMS.ClassGroupId
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id=vSA.BatchId 
			--AND BM.OrgGroupBatchId=vSA.OrgGroupBatchId
			LEFT JOIN sStudent.tStudentAdditional SD ON SD.StudentId=vSA.StudentId
			LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId=SM.Id
			LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId=SM.Id
			LEFT JOIN sHrm.tEmployeeImages EI ON EI.EmployeeId = DM.InchargeEmployeeId
			LEFT JOIN sSetup.tDivisionInchargeEmployee DIE ON vSA.DivisionId = DIE.DivisionId AND DIE.BatchId = vSA.BatchId
			AND DIE.Number = (SELECT MIN(Number) FROM sSetup.tDivisionInchargeEmployee WHERE  DIE.DivisionId = vSA.DivisionId AND DIE.BatchId = vSA.BatchId)
			LEFT JOIN sHrm.tEmployeeImages EI1 ON EI1.EmployeeId = DIE.EmployeeId
			INNER JOIN sSetup.tLanguageMaster LM ON LM.Id = OM.LanguageId
			LEFT JOIN sStudent.tStudentHealth SH ON SH.StudentId=vSA.StudentId 
	WHERE 
				L.OrgId=@rOrgId
				AND	vSA.BatchId = @rBatchId 
				AND ((SM.Code = @rCode) OR (ISNULL(@rCode,'') = ''))
				AND ((SM.FirstName = @rName) OR (ISNULL(@rName,'') = ''))
				--AND ((L.LCNumber=@rNumber) OR (@rNumber=''))
				AND ((L.LCDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
				AND ((L.LCDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
				--AND ((L.LCDate=@rLCDate) OR (ISNULL(@rLCDate,'')=''))
				--AND ((L.LeftDate=@rLeftDate) OR (ISNULL(@rLeftDate,'')=''))
				--AND ((L.LCCopy=@rLCCopy) OR (@rLCCopy=0))
				--AND ((L.LCBookNumber=@rLCBookNumber) OR (@rLCBookNumber=''))
				AND ((vSA.ClassId=@rClassId) OR(@rClassId=0))
				AND ((vSA.DivisionId=@rDivisionId) OR (@rDivisionId=0))
				AND ((L.LCNumber=@rLCNumber) OR (@rLCNumber=''))
				AND ((L.LCNumber >= @rFromNo) OR (@rFromNo=''))
				AND ((L.LCNumber <= @rToNo) OR (@rToNo=''))
				AND ((DM.ClassId=@rClassId) OR(@rClassId=0))
				--group by MR.PresentCount,MR.TotalCount, SubM.Title, SM.Code,L.AcademicId,SM.FirstName,SM.LastName,SM.MiddleName,SF.FatherName,SF.MotherName,NM.Title,
				--SO.CastCategoryId,RM.Title,so.BirthPlace,SO.BirthTaluka,SO.BirthDistrict,SO.DateOfBirth,SO.BirthDateInWord,SA.PreviousSchool,
				--	SA.AdmissionDate,L.LeftDate,L.LCReason,L.LCProgress,L.LCConduct,L.LCRemark,L.LCDate,SO.GenderId,
				--	OM.CityName,OM.StateName,CM.DisplayTitle,CMS.DisplayTitle,SM.StatusId,OM.OrgLogo,OM.PhoneNo,OM.Title,OM.StreetOne,OM.StreetTwo,OM.StreetThree
END
GO
PRINT N'Altering Procedure [sProcurement].[pStockIss_Get]...';


GO

ALTER PROCEDURE [sProcurement].[pStockIss_Get]
	@rOrgGroupId int,
	@rNumber [nvarchar](20) = '',
	@rFromDate date='',
	@rToDate date='',
	@rStoreLocationId int=0,
	@rAcademicId bigint=0,
	@rId int=0
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN	  
SELECT		
SI.Id AS  StockId,SI.Number,isnull(SI.StockIssueRequestId,0) as StockIssueRequestId,
SI.IssuedByName,Convert(varchar,SI.TransactionDate,103) AS IssuedDate,
SM.FirstName AS StudentName,SID.IssuedQuantity as Quantity,
MS.Title,IG.Title As StockItemName,IG.Id as ItemSubGroupId,SI.ToOrganizationdepartmentid,
MG.Id As MainGroupId,MS.Id As StockItemId,
ISNULL(SI.PayTypeId,14) as PayTypeId,
ISNULL(SI.ReceiptNumber,0) as ReceiptNumber,
ISNULL(SI.BankName,'') as BankName,
ISNULL(SI.ChequeNo,'') as ChequeNo,
ISNULL(SI.ChequeDate,'') as ChequeDate,
SI.Remark--mantis - 0032618


FROM sProcurement.tStockIssue SI
INNER JOIN sProcurement.tStockIssueDetail SID ON SI.Id=SID.StockIssueId
INNER JOIN sStudent.tAcademic A ON A.Id=SI.IssueToSourceId AND SI.IssueToSourceTypeId=2001
INNER JOIN sStudent.tStudentMaster SM on SM.Id=A.StudentID
INNER JOIN sIp.tStockItemMaster MS ON MS.id=SID.StockItemId
INNER JOIN sIp.tItemSubGroupMaster IG on IG.Id=MS.ItemSubGroupId
INNER JOIN sIp.tItemMainGroupMaster MG on MG.iD=IG.ItemMainGroupId 
 
WHERE 
(( SI.Number like '%' + @rNumber + '%' ) OR (@rNumber = '*'))
AND  SI.OrgGroupId = @rOrgGroupId
AND (( Convert(Date,SI.CreatedDateTime)>= @rFromDate ) OR (ISNULL(@rFromDate,'')=''))
AND (( Convert(Date,SI.CreatedDateTime)<= @rToDate ) OR (ISNULL(@rToDate,'')=''))
AND SI.FromStoreLocationId=@rStoreLocationId 
AND ((SI.IssueToSourceId =@rAcademicId) OR (@rAcademicId=0))
Order by SI.CreatedDateTime desc
END
GO
PRINT N'Altering Procedure [sStudent].[pChangeStudentClassAdd]...';


GO
ALTER PROCEDURE [sStudent].[pChangeStudentClassAdd]	 
	@rStudentId bigint=0,
	@rClassId int=0,
	@rDivisionId int=0,
	@rRollNo int=0,
	@rOrgId int=0,
	@rBatchId int=0,
	@rCreatedUserId bigint=0 
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	 
	DECLARE @lNextNumber BIGINT,@lExistCode NVARCHAR(MAX)   
	SET @rRollNo = ISNULL(@rRollNo,0)
	
	 
	IF EXISTS(SELECT Id FROM sStudent.tAcademic where StudentId=@rStudentId AND BatchId=@rBatchId AND OrgId=@rOrgId AND ClassId=@rClassId)
	BEGIN
		SELECT @lExistCode  = COALESCE(@lExistCode ,'') + CONVERT(VARCHAR(15),SM.Code) + ' , ' from sStudent.tStudentMaster SM
		INNER JOIN sStudent.tAcademic A ON A.StudentId=SM.Id AND A.BatchId=@rBatchId   AND A.ClassId=@rClassId
		SELECT  @lExistCode   
		Return
	END	 
	   
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sStudent.tAcademic', 0, 1, 1,@outNextNumber = @lNextNumber output
 
	INSERT INTO sStudent.tAcademic
		(
			Id,
			StudentId,
			ClassId,
			DivisionId,
			RollNo,
			OrgId,
			BatchId,
			CreatedUserId,
			CreatedDateTime,
			IsCurrent,
			BatchStatusId,
			ClassStatusId --Mantis ID: 0032242
		)
	VALUES
		(
			@lNextNumber,
			@rStudentId,
			@rClassId,
			@rDivisionId,
			@rRollNo,
			@rOrgId,
			@rBatchId,
			@rCreatedUserId,
			sCommon.fGetDate()
			,1
			,1
			,1
		)	
	 
--if ISNULL(@rRollNo,0) <> 0
--BEGIN
--IF EXISTS(Select Id from sStudent.tAcademic where RollNo = @rRollNo AND DivisionId = @rDivisionId AND Id <> @rAcademicId )
--BEGIN
--SET @rRollNo = 0
--END
--END 
		SELECT 101 AS Result
END
GO
PRINT N'Altering Procedure [sStudent].[pStudentMasterAdd]...';


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

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

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

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

	BEGIN TRY
	
	 BEGIN TRANSACTION	
	IF(@rId=0)
	BEGIN	
	DECLARE @lNextNumber BIGINT     
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sStudent.tStudentMaster', 0, 1, 1,@outNextNumber = @lNextNumber output

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


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

		--UNION ALL 

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


GO
ALTER PROCEDURE [sAssessment].[pMarkEntryPercentileClassWiseUpdate]
	 @rExamId int,
	 --@rDivisionId int,
	 @rClassId int,
	 @rBatchId int
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	
BEGIN 	
BEGIN TRY 
 BEGIN TRANSACTION		
DECLARE @AcademicId int
DECLARE @TotalObtain Decimal(6,2)
DECLARE @lCount int
DECLARE @TotalStudent int
DECLARE @CountStuent int
DECLARE @Percentile Decimal(6,2)

begin
	CREATE TABLE #tempPercentile
 		(
 			Id INT IDENTITY (1, 1),
			AcademicId bigint, 			
 			TotalObtain decimal(6,2)
 		) 
 		INSERT INTO #tempPercentile
 		SELECT R.AcademicId,R.TotalObtain		
		FROM sAssessment.tResult R
		--INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId = R.AcademicId AND SA.DivisionId=@rDivisionId AND SA.BatchId = @rBatchId AND StatusId=1
		INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId = R.AcademicId AND SA.ClassId=@rClassId AND SA.BatchId = @rBatchId AND StatusId=1
		where R.ExamId=@rExamId 		
		order by R.TotalObtain ASC,R.AcademicId

--SELECT * FROM #tempPercentile 	
SELECT @lCount =  COUNT(Id) FROM #tempPercentile
SET @TotalStudent=@lCount

while (@lCount > 0 )
BEGIN
	    SELECT @CountStuent=count(R.Id)	
		FROM sAssessment.tResult R
		INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId = R.AcademicId AND SA.ClassId=@rClassId AND SA.BatchId = @rBatchId	AND StatusId=1	
		where R.ExamId=@rExamId AND R.TotalObtain < (Select TotalObtain From #tempPercentile Where Id = @lCount)

		SET @Percentile = @CountStuent*100/@TotalStudent
		
		Update R Set R.Percentile = @Percentile From sAssessment.tResult R
		INNER JOIN 		#tempPercentile tP	ON R.AcademicId=tP.AcademicId
		Where R.ExamId=@rExamId AND tp.Id=@lCount
		
		SET @lCount = @lCount - 1
 END	
END
Drop Table #tempPercentile
SELECT 1 AS Result
	COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH			
 	 
END
GO
PRINT N'Altering Procedure [sAttendance].[pSubjectwiseAttendanceGet]...';


GO

 

ALTER PROCEDURE [sAttendance].[pSubjectwiseAttendanceGet]
	 	 
	 	 @rClassId int,
	 	 @rDivisionId int,
		 @rAttendanceDate date,
		 @rSubjectId int,
	 	 @rBatchId int,
	 	 @rOrgId int,
	 	 @rAttendanceGroupId int = 0,
	 	 @rPeriodNo int

	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 

    DECLARE @lIsOptional bit=0
	SELECT @lIsOptional = ISNULL(IsOptional,0) FROM sSetup.vClassSubject  WHERE SubjectId=@rSubjectId and classid = @rClassId
	IF (@lIsOptional=0)
	BEGIN
		IF(@rAttendanceGroupId=0)
		BEGIN
			SELECT 
				CASE WHEN SR.AcademicId > 0 THEN 'true' ELSE 'false' END AS AttendanceTaken, -- mantisid 0032631
				SA.AcademicId,
				ISNULL(SA.RollNo,0) as RollNo,
				SA.Name,
				SA.Code,
				ISNULL(SR.IsPresent,'true') as IsPresent,
				ISNULL(SR.AbsentReasonId,0) as AbsentReasonId,
				case when SR.CreatedUserId IS NULL then 'false' else 'true' end as IsDeleted,
				SR.RepeatCount,
				EM.EmployeeId,
				EM.Code AS EmployeeCode,
				EM.EmployeeName,
				ISNULL(SR.AttendanceTagId,0) AS AttendanceTagId,
				ISNULL(SR.PeriodNo,0) AS PeriodNo,
				SA.ClassName+' - '+SA.DivisionName AS Class,
				ISNULL(SI.StudentPhoto, CONVERT(VARBINARY(MAX), 0)) AS StudentPhoto,
				SA.StudentId
			FROM 
				sStudent.vStudentAcademic SA 
				 LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId=SA.StudentId
				INNER JOIN sStudent.tStudentAdmission AD ON SA.StudentId = AD.StudentId
				LEFT JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=SA.AcademicId 
					AND (SR.AttendanceTypeId=5)
					AND (SR.AttendanceDate=@rAttendanceDate)
					AND ((ISNULL(SR.SubjectId,0)=@rSubjectId) OR (@rSubjectId=0))
					AND ((ISNULL(SR.PeriodNo,0)=@rPeriodNo) OR (@rPeriodNo=0))
					AND  ISNULL(SR.AttendanceGroupId,0) = @rAttendanceGroupId
				LEFT JOIN sHrm.vExtEmployeeMaster EM ON EM.EmployeeId=SA.InchargeEmployeeId
			WHERE 
				((SA.ClassId=@rClassId) OR (@rClassId=0))
				AND ((SA.DivisionId=@rDivisionId) OR (@rDivisionId=0))
				AND (SA.OrgId = @rOrgId)
				AND (SA.BatchId = @rBatchID)
				AND (AD.LeftDate > @rAttendanceDate OR ISNULL(AD.LeftDate,'')= '')
				AND (AD.AdmissionDate <= @rAttendanceDate)
				AND (SA.StatusId NOT IN(2,3))
				ORDER BY SA.ClassOrderIndex,SA.DivisionOrder,RollNo
		END
		ELSE
		BEGIN
			SELECT 
				CASE WHEN SR.AcademicId > 0 THEN 'true' ELSE 'false' END AS AttendanceTaken, -- mantisid 0032631
				SA.AcademicId,
				ISNULL(SA.RollNo,0) as RollNo,
				SA.Name,
				SA.Code,
				ISNULL(SR.IsPresent,'true') as IsPresent,
				ISNULL(SR.AbsentReasonId,0) as AbsentReasonId,
				case when SR.CreatedUserId IS NULL then 'false' else 'true' end as IsDeleted,
				SR.RepeatCount,
				EM.EmployeeId,
				EM.Code AS EmployeeCode,
				EM.EmployeeName,
				ISNULL(SR.AttendanceTagId,0) AS AttendanceTagId,
				ISNULL(SR.PeriodNo,0) AS PeriodNo,
				SA.ClassName+' - '+SA.DivisionName AS Class,
				ISNULL(SI.StudentPhoto, CONVERT(VARBINARY(MAX), 0)) AS StudentPhoto,
				SA.StudentId
			FROM 
			sStudent.vStudentAcademic SA 
			 LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId=SA.StudentId
			INNER JOIN sAttendance.tAttendanceGroupStudent AGS ON AGS.AcademicId = SA.AcademicId 
				AND AGS.AttendanceGroupId=@rAttendanceGroupId
			INNER JOIN sStudent.tStudentAdmission AD ON SA.StudentId = AD.StudentId
			LEFT JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=SA.AcademicId 
				AND (SR.AttendanceTypeId=5)
				AND (SR.AttendanceDate=@rAttendanceDate)
				AND ((ISNULL(SR.SubjectId,0)=@rSubjectId) OR (@rSubjectId=0))
				AND ((ISNULL(SR.PeriodNo,0)=@rPeriodNo) OR (@rPeriodNo=0))
				AND SR.AttendanceGroupId=@rAttendanceGroupId
			LEFT JOIN sHrm.vExtEmployeeMaster EM ON EM.EmployeeId=SA.InchargeEmployeeId
			WHERE 
			(SA.OrgId = @rOrgId)
			AND (SA.BatchId = @rBatchID)
			AND (AD.LeftDate > @rAttendanceDate OR ISNULL(AD.LeftDate,'')= '')
			AND (AD.AdmissionDate <= @rAttendanceDate)
			AND (SA.StatusId NOT IN(2,3))
			ORDER BY SA.ClassOrderIndex,SA.DivisionOrder,RollNo
		END	
	END 
	ELSE 
	BEGIN
		IF(@rAttendanceGroupId=0)
		BEGIN
			SELECT 
				CASE WHEN SR.AcademicId > 0 THEN 'true' ELSE 'false' END AS AttendanceTaken, -- mantisid 0032631
				SA.AcademicId,
				ISNULL(SA.RollNo,0) as RollNo,
				SA.Name,
				SA.Code,
				ISNULL(SR.IsPresent,'true') as IsPresent,
				ISNULL(SR.AbsentReasonId,0) as AbsentReasonId,
				case when SR.CreatedUserId IS NULL then 'false' else 'true' end as IsDeleted,
				SR.RepeatCount,
				EM.EmployeeId,
				EM.Code AS EmployeeCode,
				EM.EmployeeName,
				ISNULL(SR.AttendanceTagId,0) AS AttendanceTagId,
				ISNULL(SR.PeriodNo,0) AS PeriodNo,
				SA.ClassName+' - '+SA.DivisionName AS Class,
				ISNULL(SI.StudentPhoto, CONVERT(VARBINARY(MAX), 0)) AS StudentPhoto,
				SA.StudentId
			FROM 
				sStudent.vStudentAcademic SA 
				 LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId=SA.StudentId
				INNER JOIN sStudent.tStudentAdmission AD ON SA.StudentId = AD.StudentId
				INNER JOIN sAssessment.tOptionalSubject OS ON OS.AcademicId= SA.AcademicId
				INNER JOIN sSetup.tClassSubject CS ON CS.Id = OS.ClassSubjectId 
				INNER JOIN sSetup.tSubjectMaster SM ON SM.Id= CS.SubjectId AND (SubjectId=@rSubjectId OR @rSubjectId=0)
				LEFT JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=SA.AcademicId 
					AND (SR.AttendanceTypeId=5)
					AND (SR.AttendanceDate=@rAttendanceDate)
					AND ((ISNULL(SR.SubjectId,0)=@rSubjectId) OR (@rSubjectId=0))
					AND ((ISNULL(SR.PeriodNo,0)=@rPeriodNo) OR (@rPeriodNo=0))
					AND  ISNULL(SR.AttendanceGroupId,0) = @rAttendanceGroupId
				LEFT JOIN sHrm.vExtEmployeeMaster EM ON EM.EmployeeId=SA.InchargeEmployeeId
			WHERE 
				((SA.ClassId=@rClassId) OR (@rClassId=0))
				AND ((SA.DivisionId=@rDivisionId) OR (@rDivisionId=0))
				AND (SA.OrgId = @rOrgId)
				AND (SA.BatchId = @rBatchID)
				AND (AD.LeftDate > @rAttendanceDate OR ISNULL(AD.LeftDate,'')= '')
				AND (AD.AdmissionDate <= @rAttendanceDate)
				AND (SA.StatusId NOT IN(2,3))
				ORDER BY SA.ClassOrderIndex,SA.DivisionOrder,RollNo
		END
		ELSE
		BEGIN
			SELECT 
				CASE WHEN SR.AcademicId > 0 THEN 'true' ELSE 'false' END AS AttendanceTaken, -- mantisid 0032631
				SA.AcademicId,
				ISNULL(SA.RollNo,0) as RollNo,
				SA.Name,
				SA.Code,
				ISNULL(SR.IsPresent,'true') as IsPresent,
				ISNULL(SR.AbsentReasonId,0) as AbsentReasonId,
				case when SR.CreatedUserId IS NULL then 'false' else 'true' end as IsDeleted,
				SR.RepeatCount,
				EM.EmployeeId,
				EM.Code AS EmployeeCode,
				EM.EmployeeName,
				ISNULL(SR.AttendanceTagId,0) AS AttendanceTagId,
				ISNULL(SR.PeriodNo,0) AS PeriodNo,
				SA.ClassName+' - '+SA.DivisionName AS Class,
				ISNULL(SI.StudentPhoto, CONVERT(VARBINARY(MAX), 0)) AS StudentPhoto,
				SA.StudentId
			FROM 
			sStudent.vStudentAcademic SA 
			 LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId=SA.StudentId
			INNER JOIN sAttendance.tAttendanceGroupStudent AGS ON AGS.AcademicId = SA.AcademicId 
				AND AGS.AttendanceGroupId=@rAttendanceGroupId
			INNER JOIN sStudent.tStudentAdmission AD ON SA.StudentId = AD.StudentId
			INNER JOIN sAssessment.tOptionalSubject OS ON OS.AcademicId= SA.AcademicId
				INNER JOIN sSetup.tClassSubject CS ON CS.Id = OS.ClassSubjectId 
				INNER JOIN sSetup.tSubjectMaster SM ON SM.Id= CS.SubjectId AND (SubjectId=@rSubjectId OR @rSubjectId=0)
			LEFT JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=SA.AcademicId 
				AND (SR.AttendanceTypeId=5)
				AND (SR.AttendanceDate=@rAttendanceDate)
				AND ((ISNULL(SR.SubjectId,0)=@rSubjectId) OR (@rSubjectId=0))
				AND ((ISNULL(SR.PeriodNo,0)=@rPeriodNo) OR (@rPeriodNo=0))
				AND SR.AttendanceGroupId=@rAttendanceGroupId
			LEFT JOIN sHrm.vExtEmployeeMaster EM ON EM.EmployeeId=SA.InchargeEmployeeId
			WHERE 
			(SA.OrgId = @rOrgId)
			AND (SA.BatchId = @rBatchID)
			AND (AD.LeftDate > @rAttendanceDate OR ISNULL(AD.LeftDate,'')= '')
			AND (AD.AdmissionDate <= @rAttendanceDate)
			AND (SA.StatusId NOT IN(2,3))
			ORDER BY SA.ClassOrderIndex,SA.DivisionOrder,RollNo
		END 
	END
END
GO
PRINT N'Altering Procedure [sFee].[pChargeReceiptListGet]...';


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

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

			print @rSourceCode
		--Declare @rSourceTypeId smallint
		--select @rSourceTypeId=SourceTypeId from sFee.tChargeReceipt where ReceiptNumber=@rReceiptNumber and OrgId=@rOrgId
		--END
IF @rSourceTypeId=95
BEGIN
		SELECT 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			--CRD.Id as DetailId,
			CR.Id,
			'Employee' as SourceType,
			ISNULL(EM.Code,'') AS Code,
			CR.SourceTypeId,
			--EM.Code as SourceCode,
			EM.FirstName+' '+EM.LastName as GuestName,
			--CR.Remark,
			CR.ReceiptNumber,
			CR.ReceiptDate,
			PTM.Title AS PayType,  
			--CR.PayTypeId,
			CR.ChequeNo,
			CR.BankName,
			--CR.IsObsolete,
			--CRD.Id as DetailId,
			--CRD.ChargeId,
			--CRD.Remark as DetailRemark,
			sum(CRD.Amount) as Amount,
			--Amount=(select sum(Amount) from sFee.tChargeReceiptDetail group by ChargeReceiptId),
			--CM.Code,
			--CM.Title,
			CCM.Title as ChargeCategory,
			CM.ChargeCategoryId,
			CR.OrgId,
			CR.BatchId,
			RBM.Title AS ReceiptBook,
			CR.ChargeReceiptBookId,
			OM.DisplayTitle AS OrganizationName,
			DM.DisplayTitle AS ClassName,
			CR.Remark ,
			--OM.DisplayTitle AS School,
			--OM.OrgGroupId,
			--CM.Id AS ChargeId
			CR.CreatedDateTime AS CreatedDateTime ,
			U.DisplayTitle As CreatedUser ,
			ISNULL(CR.CancelRemark,'') As CancelRemark ,
			'' As SUId ,
			BM.Title As Batch ,
			ISNULL(CR.ChequeDate,'') As ChequeDate

  FROM 
           sFee.tChargeReceipt CR
		   INNER JOIN sFee.tChargeReceiptDetail CRD ON CRD.ChargeReceiptId=CR.Id
		   INNER JOIN sHRM.tEmployeeMaster EM ON EM.Id=CR.SourceId AND (CR.SourceTypeId = @rSourceTypeId)
		   INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id 
		   INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id = EJD.OrganizationDepartmentId
		   --AND EM.StatusId=7
		    INNER JOIN sFinanceCommon.tPayTypeMaster PTM  ON PTM.Id=CR.PayTypeId 
		   INNER JOIN sFee.tChargeMaster CM ON CM.Id=CRD.ChargeId
		   INNER JOIN sFee.tChargeCategoryMaster CCM ON CCM.Id=CM.ChargeCategoryId
		   INNER JOIN sFee.tChargeReceiptBookMaster RBM ON RBM.Id=CR.ChargeReceiptBookId
		   INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=CR.OrgId
		   INNER JOIN sSecurity.tUser U ON U.Id = CR.CreatedUserId
		   Inner JOIN sSetup.tBatchMaster BM ON BM.Id = CR.BatchId
		   --INNER JOIN sSetup.tOrgGroupBatchMaster OBM ON OBM.Id=CR.OrgGroupBatchId
		   --INNER JOIN sSetup.tOrganizationMaster OM ON OM.OrgGroupId=OBM.OrgGroupId
  WHERE 
			--(CR.ReceiptNumber=@rReceiptNumber OR ISNULL(@rReceiptNumber,'')='')
			--AND 
			((EM.FirstName+' '+EM.LastName Like @rGuestName) OR (ISNULL(@rGuestName,'') = ''))
			AND ((EM.Code Like @rSourceCode) OR (ISNULL(@rSourceCode,'') = ''))
			AND ((CR.ReceiptDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
			AND ((CR.ReceiptDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
			AND ((CR.ReceiptNumber>=@rFromNo) OR (ISNULL(@rFromNo,0)=0))
			AND ((CR.ReceiptNumber<=@rToNo) OR (ISNULL(@rToNo,0)=0))
			AND ((CR.ChargeReceiptBookId = @rReceiptBookId) OR (ISNULL(@rReceiptBookId,0) = 0))
			AND ((CM.ChargeCategoryId = @rChargeCategoryId) OR (ISNULL(@rChargeCategoryId,0) = 0))
			AND (CR.IsObsolete=@rIsObsolete)
			AND ((CR.OrgId=@rOrgId) OR (@rOrgId=0))
			And ((CR.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
			AND ((CR.BatchId=@rBatchId) OR (@rBatchId=0))
			AND (CRD.IsObsolete=0) 
			AND (OM.OrgGroupId = @rOrgGroupId or @rOrgGroupId=0)
			AND ((EM.StatusId=@rStatusId) OR (@rStatusId=0))
			AND ISNULL(EM.IsOtherUser,0) = 0 
			AND ((CR.ReceiptNumber>=@rFromReceiptNumber)OR(@rFromReceiptNumber=0))    
			AND ((CR.ReceiptNumber<=@rToReceiptNumber)OR(@rToReceiptNumber=0))    
GROUP BY 
			CR.Id,EM.FirstName,EM.LastName,CR.ReceiptNumber,CR.ReceiptDate,CCM.Title,CR.OrgId,CR.BatchId,RBM.Title,
			CR.ChargeReceiptBookId,CM.ChargeCategoryId,CR.SourceTypeId,OM.DisplayTitle, DM.DisplayTitle
			,PTM.Title,CR.ChequeNo,CR.BankName,EM.Code,CR.Remark ,CR.CreatedDateTime ,U.DisplayTitle,CR.CancelRemark
			,BM.Title ,CR.ChequeDate
END
ELSE IF @rSourceTypeId=2001
BEGIN
		SELECT 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			CR.Id,
			'Student' as SourceType,
			CR.SourceTypeId,
			ISNULL(SA.Code,'') as Code,
			SA.FirstName+' '+SA.LastName as GuestName,
			--CR.Remark,
			CR.ReceiptNumber,
			CR.ReceiptDate,
			PTM.Title AS PayType,  
			--CR.PayTypeId,
			CR.ChequeNo,
			CR.BankName,
			--CR.IsObsolete,
			--CRD.Id as DetailId,
			--CRD.ChargeId,
			--CRD.Remark as DetailRemark,
			sum(CRD.Amount) as Amount,
			--CM.Code,
			--CM.Title,
			CCM.Title as ChargeCategory,
			CM.ChargeCategoryId,
			CR.OrgId,
			CR.BatchId,
			RBM.Title AS ReceiptBook,
			CR.ChargeReceiptBookId,
			OM.DisplayTitle AS OrganizationName,
			CMM.DisplayTitle + '-' + DM.DisplayTitle AS ClassName ,
			CR.Remark,
			U.DisplayTitle As CreatedUser,
			CR.CreatedDateTime ,U.DisplayTitle,
			SA.SUId As SUId ,
			ISNULL(CR.CancelRemark,'') As CancelRemark ,
			SA.BatchName As Batch ,
			ISNULL(CR.ChequeDate,'') As ChequeDate
			--CLM.Id AS ClassId,
			--CLM.DisplayTitle AS ClassName,
			--DM.Id AS DivisionId,
			--DM.DisplayTitle AS DivisionName
			--OM.DisplayTitle AS School,
			--OM.OrgGroupId,
			--CM.Id AS ChargeId
  FROM 
           sFee.tChargeReceipt CR
		   INNER JOIN sFee.tChargeReceiptDetail CRD ON CRD.ChargeReceiptId=CR.Id
		   INNER JOIN sFee.tChargeMaster CM ON CM.Id=CRD.ChargeId
		   INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=CR.SourceId AND CR.SourceTypeId=2001 --AND SA.StatusId=1
		   INNER JOIN sFinanceCommon.tPayTypeMaster PTM  ON PTM.Id=CR.PayTypeId 
		   INNER JOIN sSetup.tClassMaster CMM ON CMM.Id = SA.ClassId
		   INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = SA.DivisionId
		   INNER JOIN sFee.tChargeCategoryMaster CCM ON CCM.Id=CM.ChargeCategoryId
		   INNER JOIN sFee.tChargeReceiptBookMaster RBM ON RBM.Id=CR.ChargeReceiptBookId
		   INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=CR.OrgId
		    INNER JOIN sSecurity.tUser U ON U.Id = CR.CreatedUserId
		   --INNER JOIN sSetup.tClassMaster CLM ON CLM.Id = SA.ClassId
		   --INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = SA.DivisionId
		   --INNER JOIN sSetup.tOrgGroupBatchMaster OBM ON OBM.Id=CR.OrgGroupBatchId
		   --INNER JOIN sSetup.tOrganizationMaster OM ON OM.OrgGroupId=OBM.OrgGroupId
  WHERE 
			--(CR.ReceiptNumber=@rReceiptNumber OR ISNULL(@rReceiptNumber,'')='')
			--AND 
			((SA.FirstName+' '+SA.LastName Like @rGuestName) OR (ISNULL(@rGuestName,'') = ''))
			AND ((SA.Code Like @rSourceCode) OR (ISNULL(@rSourceCode,'') = ''))
			AND ((CR.ReceiptDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
			AND ((CR.ReceiptDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
			AND ((CR.ChargeReceiptBookId = @rReceiptBookId) OR (ISNULL(@rReceiptBookId,0) = 0))
			AND ((CM.ChargeCategoryId = @rChargeCategoryId) OR (ISNULL(@rChargeCategoryId,0) = 0))
			AND (CR.IsObsolete=@rIsObsolete)
			AND ((CR.OrgId=@rOrgId) OR (@rOrgId=0))
			AND ((CR.BatchId=@rBatchId) OR (@rBatchId=0))
			AND (CRD.IsObsolete=0)
			AND ((SA.Code=@rStudentCode) OR (@rStudentCode=''))
			AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0)) 
			AND (OM.OrgGroupId = @rOrgGroupId or @rOrgGroupId=0)
			AND ((SA.StatusId=@rStatusId) OR (@rStatusId=0))
			And ((CR.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
			AND ((CR.ReceiptNumber>=@rFromReceiptNumber)OR(@rFromReceiptNumber=0))    
			AND ((CR.ReceiptNumber<=@rToReceiptNumber)OR(@rToReceiptNumber=0)) 
			AND ((CR.ReceiptNumber>=@rFromNo) OR (ISNULL(@rFromNo,0)=0))			-- MantisId : 0032573
			AND ((CR.ReceiptNumber<=@rToNo) OR (ISNULL(@rToNo,0)=0))				-- MantisId : 0032573
 GROUP BY   CR.Id,SA.FirstName,SA.LastName,CR.ReceiptNumber,CR.ReceiptDate,CCM.Title,CR.OrgId,CR.BatchId,RBM.Title,CM.ChargeCategoryId,
            CR.ChargeReceiptBookId,CR.SourceTypeId,OM.DisplayTitle, CMM.DisplayTitle, DM.DisplayTitle
			,PTM.Title,CR.ChequeNo,CR.BankName,SA.Code ,CR.Remark ,CR.CreatedDateTime ,U.DisplayTitle ,SA.SUId ,CR.CancelRemark
            --CLM.Id,CLM.DisplayTitle, DM.Id, DM.DisplayTitle
			,SA.BatchName ,CR.ChequeDate
END
ELSE IF @rSourceTypeId=3
BEGIN
		SELECT 
		@rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,
		CR.Id,
		'Other' as SourceType,
		'' AS Code,
		CR.SourceTypeId,
		--EM.Code as SourceCode,
		CR.GuestName as GuestName,
		--CR.Remark,
		CR.ReceiptNumber,
		CR.ReceiptDate,
		  PTM.Title AS PayType,  
		--CR.PayTypeId,
		CR.ChequeNo,
		CR.BankName,
		--CR.IsObsolete,
		--CRD.Id as DetailId,
		--CRD.ChargeId,
		--CRD.Remark as DetailRemark,
		sum(CRD.Amount) as Amount,
		--CM.Code,
		--CM.Title,
		CCM.Title as ChargeCategory,
		CM.ChargeCategoryId,
		CR.OrgId,
		CR.BatchId,
		RBM.Title AS ReceiptBook,
		CR.ChargeReceiptBookId,
		OM.DisplayTitle AS OrganizationName,
		'' AS ClassName ,
		CR.Remark ,
		U.DisplayTitle As CreatedUser,
		CR.CreatedDateTime AS CreatedDateTime ,
		'' As SUId ,
		ISNULL(CR.CancelRemark,'') As CancelRemark,
		BM.Title As Batch ,
		ISNULL(CR.ChequeDate,'') As ChequeDate
		--OM.DisplayTitle AS School,
		--OM.OrgGroupId,
		--CM.Id AS ChargeId
		--CRD.IsObsolete
  FROM 
       sFee.tChargeReceipt CR
	   INNER JOIN sFee.tChargeReceiptDetail CRD ON CRD.ChargeReceiptId=CR.Id
	   INNER JOIN sFee.tChargeMaster CM ON CM.Id=CRD.ChargeId
	   INNER JOIN sFee.tChargeCategoryMaster CCM ON CCM.Id=CM.ChargeCategoryId
	   INNER JOIN sFee.tChargeReceiptBookMaster RBM ON RBM.Id=CR.ChargeReceiptBookId
	   INNER JOIN sFinanceCommon.tPayTypeMaster PTM  ON PTM.Id=CR.PayTypeId 
	   INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=CR.OrgId
	    INNER JOIN sSecurity.tUser U ON U.Id = CR.CreatedUserId
		 Inner JOIN sSetup.tBatchMaster BM ON BM.Id = CR.BatchId
	   --INNER JOIN sSetup.tOrgGroupBatchMaster OBM ON OBM.Id=CR.OrgGroupBatchId
	   --INNER JOIN sSetup.tOrganizationMaster OM ON OM.OrgGroupId=OBM.OrgGroupId
  WHERE 
		--(CR.ReceiptNumber=@rReceiptNumber OR ISNULL(@rReceiptNumber,'')='')
		--AND 
		(ISNULL(CR.SourceTypeId,0)=3)
		AND	((CR.GuestName Like @rGuestName) OR (ISNULL(@rGuestName,'') = ''))
		--AND (ISNULL(@rSourceCode,'') = '')
		AND ((CR.ReceiptDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
		AND ((CR.ReceiptDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
		AND ((CR.ChargeReceiptBookId = @rReceiptBookId) OR (ISNULL(@rReceiptBookId,0) = 0))
		AND ((CM.ChargeCategoryId = @rChargeCategoryId) OR (ISNULL(@rChargeCategoryId,0) = 0))
		AND (CR.IsObsolete=@rIsObsolete)
		AND ((CR.OrgId=@rOrgId) OR (@rOrgId=0))
		AND ((CR.BatchId=@rBatchId) OR (@rBatchId=0))
		AND (CRD.IsObsolete=0) 
		AND (OM.OrgGroupId = @rOrgGroupId or @rOrgGroupId=0)
		And ((CR.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
		AND ((CR.ReceiptNumber>=@rFromReceiptNumber)OR(@rFromReceiptNumber=0))    
		AND ((CR.ReceiptNumber<=@rToReceiptNumber)OR(@rToReceiptNumber=0)) 
		AND ((CR.ReceiptNumber>=@rFromNo) OR (ISNULL(@rFromNo,0)=0))			-- MantisId : 0032573
		AND ((CR.ReceiptNumber<=@rToNo) OR (ISNULL(@rToNo,0)=0))				-- MantisId : 0032573
		group by CR.Id,CR.GuestName,CR.ReceiptNumber,CR.ReceiptDate,CCM.Title,CR.OrgId,CR.BatchId,RBM.Title,CR.ChargeReceiptBookId,CM.ChargeCategoryId,CR.SourceTypeId,OM.DisplayTitle
		,PTM.Title,CR.ChequeNo,CR.BankName ,CR.Remark ,CR.CreatedDateTime ,U.DisplayTitle ,CR.CancelRemark
		,BM.Title ,CR.ChequeDate
END	
ELSE
BEGIN
	SELECT 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			--CRD.Id as DetailId,
			CR.Id,
			'Employee' as SourceType,
			CR.SourceTypeId,
			ISNULL(EM.Code,'') as Code,
			EM.FirstName+' '+EM.LastName as GuestName,
			--CR.Remark,
			CR.ReceiptNumber,
			CR.ReceiptDate,
			  PTM.Title AS PayType,  
			--CR.PayTypeId,
			CR.ChequeNo,
			CR.BankName,
			--CR.IsObsolete,
			--CRD.Id as DetailId,
			--CRD.ChargeId,
			--CRD.Remark as DetailRemark,
			sum(CRD.Amount) as Amount,
			--Amount=(select sum(Amount) from sFee.tChargeReceiptDetail group by ChargeReceiptId),
			--CM.Code,
			--CM.Title,
			CCM.Title as ChargeCategory,
			CM.ChargeCategoryId,
			CR.OrgId,
			CR.BatchId,
			RBM.Title AS ReceiptBook,
			CR.ChargeReceiptBookId,
			OM.DisplayTitle AS OrganizationName,
			DM.DisplayTitle AS ClassName,
			CR.Remark ,
			U.DisplayTitle As CreatedUser ,
			CR.CreatedDateTime AS CreatedDateTime ,
				'' As SUId,
            ISNULL(CR.CancelRemark,'') As CancelRemark ,
			BM.Title As Batch ,
			ISNULL(CR.ChequeDate,'') As ChequeDate
			--OM.DisplayTitle AS School,
			--OM.OrgGroupId,
			--CM.Id AS ChargeId
			--CRD.IsObsolete
  FROM 
           sFee.tChargeReceipt CR
		   INNER JOIN sFee.tChargeReceiptDetail CRD ON CRD.ChargeReceiptId=CR.Id
		   INNER JOIN sHRM.tEmployeeMaster EM ON EM.Id=CR.SourceId AND (CR.SourceTypeId = 95) 
		   INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id 
		   INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id = EJD.OrganizationDepartmentId
		   --AND EM.StatusId=7
		   INNER JOIN sFee.tChargeMaster CM ON CM.Id=CRD.ChargeId
		   INNER JOIN sFee.tChargeCategoryMaster CCM ON CCM.Id=CM.ChargeCategoryId
		   INNER JOIN sFee.tChargeReceiptBookMaster RBM ON RBM.Id=CR.ChargeReceiptBookId
		   INNER JOIN sFinanceCommon.tPayTypeMaster PTM  ON PTM.Id=CR.PayTypeId 
		   INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=CR.OrgId
		    INNER JOIN sSecurity.tUser U ON U.Id = CR.CreatedUserId
			 Inner JOIN sSetup.tBatchMaster BM ON BM.Id = CR.BatchId
		   --INNER JOIN sSetup.tOrgGroupBatchMaster OBM ON OBM.Id=CR.OrgGroupBatchId
		   --INNER JOIN sSetup.tOrganizationMaster OM ON OM.OrgGroupId=OBM.OrgGroupId
       
  WHERE 
			--(CR.ReceiptNumber=@rReceiptNumber OR ISNULL(@rReceiptNumber,'')='')
			--AND 
			((EM.FirstName+' '+EM.LastName Like @rGuestName) OR (ISNULL(@rGuestName,'') = ''))
			AND ((EM.Code Like @rSourceCode) OR (ISNULL(@rSourceCode,'') = ''))
			AND ((CR.ReceiptDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
			AND ((CR.ReceiptDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
			AND ((CR.ChargeReceiptBookId = @rReceiptBookId) OR (ISNULL(@rReceiptBookId,0) = 0))
			AND ((CM.ChargeCategoryId = @rChargeCategoryId) OR (ISNULL(@rChargeCategoryId,0) = 0))
			AND (CR.IsObsolete=@rIsObsolete)
			AND ((CR.OrgId=@rOrgId) OR (@rOrgId=0))
			AND ((CR.BatchId=@rBatchId) OR (@rBatchId=0))
			AND (CRD.IsObsolete=0)
			AND (OM.OrgGroupId = @rOrgGroupId or @rOrgGroupId=0)
			And ((CR.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
			AND ISNULL(EM.IsOtherUser,0) = 0 
			AND ((CR.ReceiptNumber>=@rFromReceiptNumber)OR(@rFromReceiptNumber=0))    
			AND ((CR.ReceiptNumber<=@rToReceiptNumber)OR(@rToReceiptNumber=0)) 
			AND ((CR.ReceiptNumber>=@rFromNo) OR (ISNULL(@rFromNo,'')=''))
			AND ((CR.ReceiptNumber<=@rToNo) OR (ISNULL(@rToNo,'')=''))
			AND (CR.PayTypeId = @rPaytypeId OR @rPaytypeId=0)             -- Mantis - 32487
			AND ((CR.ReceiptNumber>=@rFromNo) OR (ISNULL(@rFromNo,0)=0))		-- MantisId : 0032573
			AND ((CR.ReceiptNumber<=@rToNo) OR (ISNULL(@rToNo,0)=0))			-- MantisId : 0032573
			group by CR.Id,EM.FirstName,EM.LastName,CR.ReceiptNumber,CR.ReceiptDate,CCM.Title,CR.OrgId,
			CR.BatchId,RBM.Title,CM.ChargeCategoryId,CR.ChargeReceiptBookId,CR.SourceTypeId,OM.DisplayTitle, DM.DisplayTitle
			,PTM.Title,CR.ChequeNo,CR.BankName,EM.Code ,CR.Remark ,CR.CreatedDateTime ,U.DisplayTitle ,CR.CancelRemark
			,BM.Title ,CR.ChequeDate
			UNION ALL
			
			SELECT 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			CR.Id,
			'Student' as SourceType,
			CR.SourceTypeId,
			ISNULL(SA.Code,'') as Code,
			SA.FirstName+' '+SA.LastName as GuestName,
			--CR.Remark,
			CR.ReceiptNumber,
			CR.ReceiptDate,
			  PTM.Title AS PayType,  
			--CR.PayTypeId,
			CR.ChequeNo,
			CR.BankName,
			--CR.IsObsolete,
			--CRD.Id as DetailId,
			--CRD.ChargeId,
			--CRD.Remark as DetailRemark,
			sum(CRD.Amount) as Amount,
			--CM.Code,
			--CM.Title,
			CCM.Title as ChargeCategory,
			CM.ChargeCategoryId,
			CR.OrgId,
			CR.BatchId,
			RBM.Title AS ReceiptBook,
			CR.ChargeReceiptBookId,
			OM.DisplayTitle AS OrganizationName,
			CMM.DisplayTitle + '-' + DM.DisplayTitle AS ClassName ,
			CR.Remark ,
			U.DisplayTitle As CreatedUser,
			CR.CreatedDateTime AS CreatedDateTime ,
				'' As SUId ,
			ISNULL(CR.CancelRemark,'') As CancelRemark,
			SA.BatchName as Batch ,
			ISNULL(CR.ChequeDate,'') As ChequeDate
			--OM.DisplayTitle AS School,
			--OM.OrgGroupId,
			--CM.Id AS ChargeId
			--CRD.IsObsolete
  FROM 
           sFee.tChargeReceipt CR
		   INNER JOIN sFee.tChargeReceiptDetail CRD ON CRD.ChargeReceiptId=CR.Id
		   INNER JOIN sFee.tChargeMaster CM ON CM.Id=CRD.ChargeId
		   INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=CR.SourceId AND CR.SourceTypeId=2001
		   INNER JOIN sSetup.tClassMaster CMM ON CMM.Id = SA.ClassId
		   INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = SA.DivisionId 
		   --AND SA.StatusId=1
		   INNER JOIN sFee.tChargeCategoryMaster CCM ON CCM.Id=CM.ChargeCategoryId
		   INNER JOIN sFee.tChargeReceiptBookMaster RBM ON RBM.Id=CR.ChargeReceiptBookId   --Mantis - 32487
		   INNER JOIN sFinanceCommon.tPayTypeMaster PTM  ON PTM.Id=CR.PayTypeId 
		   INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=CR.OrgId
		   INNER JOIN sSecurity.tUser U ON U.Id = CR.CreatedUserId
		   --INNER JOIN sSetup.tOrgGroupBatchMaster OBM ON OBM.Id=CR.OrgGroupBatchId
		   --INNER JOIN sSetup.tOrganizationMaster OM ON OM.OrgGroupId=OBM.OrgGroupId
       
  WHERE 
			--(CR.ReceiptNumber=@rReceiptNumber OR ISNULL(@rReceiptNumber,'')='')
			--AND 
			((SA.FirstName+' '+SA.LastName Like @rGuestName) OR (ISNULL(@rGuestName,'') = ''))
			AND ((SA.Code Like @rSourceCode) OR (ISNULL(@rSourceCode,'') = ''))
			AND ((CR.ReceiptDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
			AND ((CR.ReceiptDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
			AND ((CR.ChargeReceiptBookId = @rReceiptBookId) OR (ISNULL(@rReceiptBookId,0) = 0))
			AND ((CM.ChargeCategoryId = @rChargeCategoryId) OR (ISNULL(@rChargeCategoryId,0) = 0))
			AND (CR.IsObsolete=@rIsObsolete)
			AND ((CR.OrgId=@rOrgId) OR (@rOrgId=0))
			AND ((CR.BatchId=@rBatchId) OR (@rBatchId=0))
			AND (CRD.IsObsolete=0)
			AND ((SA.Code=@rStudentCode) OR (@rStudentCode=''))
			AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))  
			AND (OM.OrgGroupId = @rOrgGroupId or @rOrgGroupId=0)
			And ((CR.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
			AND ((CR.ReceiptNumber>=@rFromReceiptNumber)OR(@rFromReceiptNumber=0))    
			AND ((CR.ReceiptNumber<=@rToReceiptNumber)OR(@rToReceiptNumber=0)) 
			AND ((CR.ReceiptNumber>=@rFromNo) OR (ISNULL(@rFromNo,0)=0))
			AND ((CR.ReceiptNumber<=@rToNo) OR (ISNULL(@rToNo,0)=0))
			AND (CR.PayTypeId = @rPaytypeId OR @rPaytypeId=0)               -- Mantis - 32487
			group by CR.Id,SA.FirstName,SA.LastName,CR.ReceiptNumber,CR.ReceiptDate,CCM.Title,CR.OrgId,CR.BatchId,
			RBM.Title,CR.ChargeReceiptBookId,CM.ChargeCategoryId,CR.SourceTypeId,OM.DisplayTitle, CMM.DisplayTitle, DM.DisplayTitle
			,PTM.Title,CR.ChequeNo,CR.BankName,SA.Code,CR.Remark ,CR.CreatedDateTime ,U.DisplayTitle ,CR.CancelRemark
			,SA.BatchName ,CR.ChequeDate
			UNION ALL
			
			SELECT 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			CR.Id,
			'Other' as SourceType,
			CR.SourceTypeId,
			'' AS Code,
			CR.GuestName as GuestName,
			--CR.Remark,
			CR.ReceiptNumber,
			CR.ReceiptDate,
			  PTM.Title AS PayType,  
			--CR.PayTypeId,
			CR.ChequeNo,
			CR.BankName,
			--CR.IsObsolete,
			--CRD.Id as DetailId,
			--CRD.ChargeId,
			--CRD.Remark as DetailRemark,
			sum(CRD.Amount) as Amount,
			--CM.Code,
			--CM.Title,
			CCM.Title as ChargeCategory,
			CM.ChargeCategoryId,
			CR.OrgId,
			CR.BatchId,
			RBM.Title AS ReceiptBook,
			CR.ChargeReceiptBookId,
			OM.DisplayTitle AS OrganizationName,
			'' AS ClassName ,
			CR.Remark ,
			U.DisplayTitle As CreatedUser ,
			CR.CreatedDateTime AS CreatedDateTime ,
				'' As SUId ,
				ISNULL(CR.CancelRemark,'') As CancelRemark ,
				BM.Title As Batch ,
				ISNULL(CR.ChequeDate,'') As ChequeDate
			--OM.DisplayTitle AS School,
			--OM.OrgGroupId,
			--CM.Id AS ChargeId
			--CRD.IsObsolete
  FROM 
           sFee.tChargeReceipt CR
		   INNER JOIN sFee.tChargeReceiptDetail CRD ON CRD.ChargeReceiptId=CR.Id
		   INNER JOIN sFee.tChargeMaster CM ON CM.Id=CRD.ChargeId
		   INNER JOIN sFee.tChargeCategoryMaster CCM ON CCM.Id=CM.ChargeCategoryId
		   INNER JOIN sFee.tChargeReceiptBookMaster RBM ON RBM.Id=CR.ChargeReceiptBookId
		   INNER JOIN sFinanceCommon.tPayTypeMaster PTM  ON PTM.Id=CR.PayTypeId 
		   INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=CR.OrgId
		   INNER JOIN sSecurity.tUser U ON U.Id = CR.CreatedUserId
		    Inner JOIN sSetup.tBatchMaster BM ON BM.Id = CR.BatchId
		   --INNER JOIN sSetup.tOrgGroupBatchMaster OBM ON OBM.Id=CR.OrgGroupBatchId
		   --INNER JOIN sSetup.tOrganizationMaster OM ON OM.OrgGroupId=OBM.OrgGroupId
  WHERE 
			--(CR.ReceiptNumber=@rReceiptNumber OR ISNULL(@rReceiptNumber,'')='')
			--AND 
			(ISNULL(CR.SourceTypeId,0)=3)
			AND	((CR.GuestName Like @rGuestName) OR (ISNULL(@rGuestName,'') = ''))
			AND ((CR.ReceiptDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
			AND ((CR.ReceiptDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
			AND ((CR.ChargeReceiptBookId = @rReceiptBookId) OR (ISNULL(@rReceiptBookId,0) = 0))
			AND ((CM.ChargeCategoryId = @rChargeCategoryId) OR (ISNULL(@rChargeCategoryId,0) = 0))
			AND (CR.IsObsolete=@rIsObsolete)
			AND ((CR.OrgId=@rOrgId) OR (@rOrgId=0))
			AND ((CR.BatchId=@rBatchId) OR (@rBatchId=0))
			AND (CRD.IsObsolete=0) 
			AND (OM.OrgGroupId = @rOrgGroupId or @rOrgGroupId=0)
			And ((CR.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
			AND ((CR.ReceiptNumber>=@rFromReceiptNumber)OR(@rFromReceiptNumber=0))    
			AND ((CR.ReceiptNumber<=@rToReceiptNumber)OR(@rToReceiptNumber=0)) 
			AND ((CR.ReceiptNumber>=@rFromNo) OR (ISNULL(@rFromNo,0)=0))
			AND ((CR.ReceiptNumber<=@rToNo) OR (ISNULL(@rToNo,0)=0))
			AND (CR.PayTypeId = @rPaytypeId OR @rPaytypeId=0)          -- Mantis - 32487
			--AND ((ISNULL(@rSourceCode,'%') = '%'))
			group by CR.Id,CR.GuestName,CR.ReceiptNumber,CR.ReceiptDate,CCM.Title,CR.OrgId,CR.BatchId,RBM.Title,CR.ChargeReceiptBookId,CM.ChargeCategoryId,CR.SourceTypeId,OM.DisplayTitle
			,PTM.Title,CR.ChequeNo,CR.BankName ,CR.Remark ,CR.CreatedDateTime ,U.DisplayTitle ,CR.CancelRemark
			,BM.Title ,CR.ChequeDate
END
END

GO

GO
PRINT N'Altering Procedure [sHostel].[pUserControlStudentSearchGet]...';


GO
ALTER PROCEDURE [sHostel].[pUserControlStudentSearchGet]
	 
	@rClassId int=0,
	@rDivisionId int=0,
	@rRollNo int=NULL,
	@rOrgId int,
	--@rNumber bigint,
	@rCode nvarchar(20),
	@rStatusId smallint=0,
	@rFirstName nvarchar(100)='',
	@rLastName nvarchar(100)='',
	@rBatchId int = 0,
	@rOrgGroupBatchId int = 0,
	@rSUId nvarchar(50)='',
	@rHostelId int=0
	
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON			 

BEGIN 	 

DECLARE @lInContextBatch int
SELECT @lInContextBatch = Id From sSetup.tBatchMaster BM Where BM.OrgGroupBatchId = @rOrgGroupBatchId AND IsInContext = 1


		BEGIN
			SET @rFirstName = sCommon.fSearchStringGet(@rFirstName)
			SET @rLastName = sCommon.fSearchStringGet(@rLastName)
		END

		IF(@rRollNo=0) 
		SET @rRollNo=NULL

 IF(@rRollNo IS NULL)
	BEGIN

	SELECT 
			SA.AcademicId,
			SA.StudentId,
			SA.FirstName,
			SA.LastName,
			SA.MiddleName,
			SA.Name,
			SA.Code,
			SA.ClassId,
			SA.ClassName,
			SA.DivisionId,
			SA.DivisionName,
			SA.Number,
			SA.RollNo,
			SA.StatusId,
			SA.StatusName,
			SA.OrgId,
			--SA.Age,
			ISNULL(SA.AdmissionCategoryId,0) AS AdmissionCategoryId,
			SA.BatchId,
			SA.SUId,
			ISNULL(SC.ParentContactNo,'') AS ParentContactNo,
			SA.FeesRemark
  FROM 
          sStudent.vStudentAcademic SA 
          INNER JOIN sHostel.tAssignRoom AR ON AR.SourceId=SA.StudentId AND  AR.SourceTypeId=2003
          INNER JOIN sHostel.tRoomMaster RM ON RM.Id=AR.RoomId 
          INNER JOIN sSetup.tBatchMaster BM ON BM.OrgGroupBatchId = AR.OrgGroupBatchId AND BM.Id = SA.BatchId
		  INNER JOIN sStudent.tStudentCommunication SC ON SA.StudentId = SC.StudentId
  WHERE 
 
		((SA.ClassId=@rClassId)OR(@rClassId=0))
		AND((SA.DivisionId=@rDivisionId)OR(@rDivisionId=0))
		AND((SA.Code=@rCode) OR (ISNULL(@rCode,'') = '')) 
		AND((SA.FirstName like @rFirstName) OR (ISNULL(@rFirstName,'') = '')) 
		AND((SA.LastName like @rLastName) OR (ISNULL(@rLastName,'') = '')) 
		AND((SA.StatusId=@rStatusId)OR(@rStatusId=0))	
		AND(SA.OrgId=@rOrgId OR @rOrgId = 0)
		AND ( SA.OrgGroupBatchId = @rOrgGroupBatchId	or @rOrgGroupBatchId = 0)	
		AND(SA.BatchId=@rBatchId or @rBatchId = 0)
		--AND((SA.Number=@rNumber)OR(@rNumber=0))	
		AND((SA.SUId=@rSUId) OR (ISNULL(@rSUId,'') = ''))
		AND  RM.HostelId=@rHostelId
	  AND ( AR.OrgGroupBatchId = @rOrgGroupBatchId	or @rOrgGroupBatchId = 0)
	  AND BM.IsInContext = 1

ORDER BY SA.ClassId,SA.DivisionId,SA.RollNo
END
ELSE
BEGIN
	SELECT 
			SA.AcademicId,
			SA.StudentId,
			SA.FirstName,
			SA.LastName,
			SA.MiddleName,
			SA.Name,
			SA.Code,
			SA.ClassId,
			SA.ClassName,
			SA.DivisionId,
			SA.DivisionName,
			SA.Number,
			SA.RollNo,
			SA.StatusId,
			SA.StatusName,
			SA.OrgId,
			--SA.Age,
			ISNULL(SA.AdmissionCategoryId,0) AS AdmissionCategoryId,
			SA.FeesRemark
  FROM 
          sStudent.vStudentAcademic SA   
           INNER JOIN sHostel.tAssignRoom AR ON AR.SourceId=SA.StudentId AND  AR.SourceTypeId=2003
           INNER JOIN sHostel.tRoomMaster RM ON RM.Id=AR.RoomId           
  WHERE 
 
		((SA.ClassId=@rClassId)OR(@rClassId=0))
		AND((SA.DivisionId=@rDivisionId)OR(@rDivisionId=0))
		AND((SA.Code=@rCode) OR (ISNULL(@rCode,'') = '')) 
		AND((SA.FirstName like @rFirstName) OR (ISNULL(@rFirstName,'') = '')) 
		AND((SA.LastName like @rLastName) OR (ISNULL(@rLastName,'') = '')) 
		AND(SA.RollNo=@rRollNo) 
		AND((SA.StatusId=@rStatusId)OR(@rStatusId=0))	
		AND((SA.OrgId=@rOrgId) OR (@rOrgId=0))
		AND (SA.OrgGroupBatchId = @rOrgGroupBatchId	or @rOrgGroupBatchId = 0)	
		AND(SA.BatchId=@rBatchId or @rBatchId = 0)
		--AND(SA.BatchId=@rBatchId)
		--AND((SA.Number=@rNumber)OR(@rNumber=0))
		AND((SA.SUId=@rSUId) OR (ISNULL(@rSUId,'') = '')) 	
		AND  RM.HostelId=@rHostelId
		  AND ( AR.OrgGroupBatchId = @rOrgGroupBatchId	or @rOrgGroupBatchId = 0)	

ORDER BY SA.ClassId,SA.DivisionId,SA.RollNo
END
		
END
GO
PRINT N'Altering Procedure [sLibrary].[pRptBookListCirculationGet]...';


GO
ALTER PROCEDURE [sLibrary].[pRptBookListCirculationGet]

	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	--@rReaderSourceTypeId smallint,
	 --@rReaderSourceId bigint,
	-- @rOrgId smallint,
	 --@rBatchId int,
	 --@rClassId int,
	 --@rDivisionId int,
	 @rFromLogDate date,
	 @rToLogDate date,
	 @rLibraryId int,
	 @rTopFrequency  smallint,
	 @rBookPublisher nvarchar(200),     --Mantis - 32621
	 @rAuthor nvarchar(200)          --Mantis - 32621
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
		SET @rBookPublisher = sCommon.fSearchStringGet(@rBookPublisher)
		SET @rAuthor = sCommon.fSearchStringGet(@rAuthor)

		SELECT 
				Top(@rTopFrequency) BM.Id,BM.Code,BM.Title, COUNT(BL.Id)AS IssueCount ,@rBuilder1 AS Builder1,@rBuilder2 AS Builder2
	        
	FROM 
			sLibrary.tBookLog BL
			INNER JOIN sLibrary.tBookMaster BM ON BM.Id=BL.ResourceSourceId
			INNER JOIN sStudent.vStudentAcademic SA ON SA.StudentId=BL.ReaderSourceId AND BL.ReaderSourceTypeId=2003 AND SA.BatchId = BL.BatchId
	WHERE 
			(BL.LibraryId=@rLibraryId)  AND BL.StatusId = 523 --AND IsCurrentStatus =0
			AND ((BL.LogDate >= @rFromLogDate) OR (ISNULL(@rFromLogDate,'') = ''))
			AND ((BL.LogDate <= @rToLogDate) OR (ISNULL(@rToLogDate,'') = ''))
			AND (BL.ReaderSourceTypeId != 0)
			AND ((BM.Publisher like @rBookPublisher) OR (@rBookPublisher=''))    --Mantis - 32621
			AND ((BM.Author like @rAuthor) OR (@rAuthor=''))            --Mantis - 32621
			GROUP  by BM.Id,BM.Code,BM.Title--,BL.ReaderSourceId
			
	UNION

	SELECT 
				Top(@rTopFrequency) BM.Id,BM.Code,BM.Title, COUNT(BL.Id)AS IssueCount ,@rBuilder1 AS Builder1,@rBuilder2 AS Builder2
	FROM 
			sLibrary.tBookLog BL
			INNER JOIN sLibrary.tBookMaster BM ON BM.Id=BL.ResourceSourceId
			INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id=BL.ReaderSourceId AND BL.ReaderSourceTypeId=95

	WHERE 
			(BL.LibraryId=@rLibraryId)  AND BL.StatusId = 523 --AND IsCurrentStatus =0
			AND ((BL.LogDate >= @rFromLogDate) OR (ISNULL(@rFromLogDate,'') = ''))
			AND ((BL.LogDate <= @rToLogDate) OR (ISNULL(@rToLogDate,'') = ''))
			AND (BL.ReaderSourceTypeId != 0)
			AND  ISNULL(EM.IsOtherUser,0) = 0
			AND ((BM.Publisher like @rBookPublisher) OR (@rBookPublisher=''))     --Mantis - 32621
			AND ((BM.Author like @rAuthor) OR (@rAuthor=''))                  --Mantis - 32621
			GROUP  by BM.Id,BM.Code,BM.Title--,BL.ReaderSourceId
			
			
	UNION 

	SELECT 
	Top(@rTopFrequency) BM.Id,BM.Code,BM.Title, COUNT(BL.Id)AS IssueCount,@rBuilder1 AS Builder1,@rBuilder2 AS Builder2 
	FROM 
			sLibrary.tBookLog BL
			INNER JOIN sLibrary.tBookMaster BM ON BM.Id=BL.ResourceSourceId
	WHERE (BL.LibraryId=@rLibraryId)  AND BL.StatusId = 523 --AND IsCurrentStatus =0
			AND (ISNULL(BL.ReaderSourceTypeId,0)=0 AND 0=0)
			AND ((BL.LogDate >= @rFromLogDate) OR (ISNULL(@rFromLogDate,'') = ''))
			AND ((BL.LogDate <= @rToLogDate) OR (ISNULL(@rToLogDate,'') = ''))
			AND (BL.ReaderSourceTypeId != 0)
			AND ((BM.Publisher like @rBookPublisher) OR (@rBookPublisher=''))           --Mantis - 32621
			AND ((BM.Author like @rAuthor) OR (@rAuthor=''))           --Mantis - 32621
			GROUP  by BM.Id,BM.Code,BM.Title--,BL.ReaderSourceId
			ORDER BY COUNT(BL.Id) desc


		
		--SELECT Top(@rTopFrequency) BM.Id,BM.Code,BM.Title, COUNT(BL.Id)AS IssueCount,@rBuilder1 AS Builder1,
		--	@rBuilder2 AS Builder2 FROM sLibrary.tBookLog BL
		--	INNER JOIN sLibrary.tBookMaster BM ON BM.Id=BL.ResourceSourceId
		--	--INNER JOIN sStudent.vStudentLastAcademic SA ON SA.StudentId=BL.ReaderSourceId
		--WHERE (BL.LibraryId=@rLibraryId) AND ReaderSourceTypeId = 2003 AND BL.StatusId = 523 AND IsCurrentStatus =0
		--	AND ((BL.LogDate >= @rFromLogDate) OR (ISNULL(@rFromLogDate,'') = ''))
		--	AND ((BL.LogDate <= @rToLogDate) OR (ISNULL(@rToLogDate,'') = ''))
		 
		--	GROUP  by BM.Id,BM.Code,BM.Title--,BL.ReaderSourceId
		--	ORDER BY COUNT(BL.Id) desc

END
GO
PRINT N'Altering Procedure [sStudent].[pStudentLeaveListingGet]...';


GO

ALTER PROCEDURE [sStudent].[pStudentLeaveListingGet]
(  
	@rOrgId int,  
    --@rId bigint = 0, 
	@rAcademicId bigint=0,
    @rStudentId  bigint=0,     
    @rFromDate date='',   
    @rTodate date='',  
    @rOrgGroupBatchId int=0,  
    @rStudentCode nvarchar(100)='',  
    @rStudentName nvarchar(100)='',  
    @rStatusId int = 0,  
	@rClassId int =0,
    @rOrgGroupId int=0,  
    --@rIsSearchLeaveHierarchyWise int = 0,  
    --@rDepartmentId int,	
	@rDivisionId bigint=0,
	@rUserId bigint = 0,
	@rBatchId int = 0

 )  
AS  
SET NOCOUNT ON  

DECLARE @lItemValue nvarchar(20) = '' , @lUserSourceId bigint , @lUserSourceTypeId int
	
SELECT @lItemValue = CASE WHEN CS.Id IS NOT NULL THEN ISNULL(CS.ItemValue,'') ELSE ISNULL(CM.ItemValue,'') END
FROM sConfig.tConfigurationMaster CM
LEFT JOIN sConfig.tConfigurationSetup CS ON CM.Id = CS.ConfigurationId
AND SourceTypeId = 1016 AND SourceId = @rOrgId WHERE CM.Id = 186

SELECT @lUserSourceId = SourceId , @lUserSourceTypeId = ISNULL(SourceTypeId,0) from sSecurity.tUser WHERE Id = @rUserId

--SELECT @lItemValue,@lUserSourceTypeId

IF(@lUserSourceTypeId = 95)
BEGIN
--select 555
	IF(@lItemValue = 'Class Teacher')
	BEGIN
		IF(@rUserId=0)
		BEGIN
		 SELECT   
			  ROW_NUMBER() OVER(ORDER BY L.CreatedDateTime desc) AS Id,
			  L.AcademicId AS AcademicId,  
			  SA.[StudentId],  
			  L.CreatedDateTime AS ReportDate,  
			  L.[LeaveFromDate] AS FromDate,  
			  L.[LeaveToDate] AS ToDate,  
			  ISNULL(L.LeaveReason,'') as LeaveReason,  
			  --EM.EmployeeName,  
			  SA.Name AS StudentName,
			  SA.Code AS StudentCode,  
			  DATEDIFF(day,L.LeaveFromDate, L.LeaveToDate)+1 AS NoOfLeave,  
			  ISNULL(L.StatusId,0) AS StatusId,  
			  ISNULL(SM.Title,'Pending') AS StatusName,  
			  ISNULL(L.StatusReason,'') AS  StatusReason,  
			  OM.DisplayTitle AS OrganizationName,  
			  ISNULL(L.ActionByEmployeeId,'') as ActionByEmployeeId,  
			  CASE WHEN ISNULL(L.ActionByEmployeeId,0) = 0 AND ISNULL(L.StatusId,549) = 549 THEN '' 	  
			  ELSE EMP.FirstName + ' ' + EMP.LastName END AS ActionByEmployee,  
			  OM.Id AS OrgId,  
			  SA.BatchId AS BatchId, 
			  SA.DivisionId,
			  SA.DivisionName,
			  SA.ClassId,
			  SA.ClassName, 
			  SA.DepartmentId AS DepartmentId,  
			  SA.DepartmentName As DepartmentName
			  --US.Id As UserId
		  FROM   
			  sAttendance.tStudentLeaveRequest L   
			  INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId = L.AcademicId  
			  INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId    
			  INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = BM.OrgId  
			  LEFT JOIN sCommon.tStatusMaster SM ON SM.Id = L.StatusId  
			 --LEFT JOIN sSecurity.tUser US ON US.Id = L.CreatedUserId 
			  LEFT JOIN sHrm.tEmployeeMaster EMP ON EMP.Id = L.ActionByEmployeeId AND ISNULL(EMP.IsOtherUser,0)=0 
			 -- INNER JOIN sSecurity.tUserAccess U ON U.SourceId = EM.DepartmentId AND U.SourceTypeId=2017     

		  WHERE   
			  ((L.LeaveFromDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))  
			  AND ((L.LeaveFromDate <= @rToDate) OR (ISNULL(@rToDate,'') = ''))         
			  AND BM.OrgGroupBatchId = @rOrgGroupBatchId  
			  AND (SA.DivisionId=@rDivisionId OR @rDivisionId=0)
			  AND (SA.ClassId=@rClassId OR @rClassId=0)
			  AND (SA.[StudentId]=@rStudentId or ISNULL(@rStudentId,0)=0)
			  And(SA.[AcademicId]=@rAcademicId or ISNULL(@rAcademicId,0)=0)
			  AND ((SA.OrgId = @rOrgId) OR (@rOrgId = 0))  
			  AND (SA.Code = @rStudentCode OR ISNULL(@rStudentCode,'') = '')  
			  AND (SA.Name like @rStudentName+'%' OR ISNULL(@rStudentName,'') = '')  
			  AND (ISNULL(L.StatusId,0) = @rStatusId OR (@rStatusId = 0 OR (@rStatusId=549 AND  ISNULL(L.StatusId,0)=0))) 
			  --AND ((SA.DepartmentId = @rDepartmentId ) OR (@rDepartmentId = 0)) 
			  AND ISNULL(EMP.IsOtherUser,0)=0 
			  AND SA.InchargeEmployeeId = @lUserSourceId
			 -- AND U.UserId = @rUserId     
		  ORDER BY   
			  L.CreatedDateTime DESC  
		END
		ELSE
		BEGIN 
		--Select 111      
		  SELECT   
		      ROW_NUMBER() OVER(ORDER BY L.CreatedDateTime desc) AS Id,
			  L.AcademicId AS AcademicId,  
			  SA.[StudentId],  
			  L.CreatedDateTime AS ReportDate,  
			  L.[LeaveFromDate] AS FromDate,  
			  L.[LeaveToDate] AS ToDate,  
			  ISNULL(L.LeaveReason,'') as LeaveReason,  
			  --EM.EmployeeName,  
			  SA.Name AS StudentName,
			  SA.Code AS StudentCode,  
			  DATEDIFF(day,L.LeaveFromDate, L.LeaveToDate)+1 AS NoOfLeave,  
			  ISNULL(L.StatusId,0) AS StatusId,  
			  ISNULL(SM.Title,'Pending') AS StatusName,  
			  ISNULL(L.StatusReason,'') AS  StatusReason,  
			  OM.DisplayTitle AS OrganizationName,  
			  ISNULL(L.ActionByEmployeeId,'') as ActionByEmployeeId,  
			  CASE WHEN ISNULL(L.ActionByEmployeeId,0) = 0 AND ISNULL(L.StatusId,549) = 549 THEN '' 	  
			  ELSE EMP.FirstName + ' ' + EMP.LastName END AS ActionByEmployee,  
			  OM.Id AS OrgId,  
			  SA.BatchId AS BatchId, 
			  SA.DivisionId,
			  SA.DivisionName,
			  SA.ClassId,
			  SA.ClassName, 
			  SA.DepartmentId AS DepartmentId,  
			  SA.DepartmentName As DepartmentName
			  --US.Id As UserId
		  FROM   
			  sAttendance.tStudentLeaveRequest L   
			  INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId = L.AcademicId  
			  INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId    
			  INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = BM.OrgId  
			  LEFT JOIN sCommon.tStatusMaster SM ON SM.Id = L.StatusId  
			  --LEFT JOIN sSecurity.tUser US ON US.Id = L.CreatedUserId 
			  LEFT JOIN sHrm.tEmployeeMaster EMP ON EMP.Id = L.ActionByEmployeeId AND ISNULL(EMP.IsOtherUser,0)=0 
			  -- INNER JOIN sSecurity.tUserAccess U ON U.SourceId = EM.DepartmentId AND U.SourceTypeId=2017   
			  INNER JOIN sSecurity.tUserOrganization UO ON UO.OrgId=OM.Id  

		  WHERE   
			  ((L.LeaveFromDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))  
			  AND ((L.LeaveFromDate <= @rToDate) OR (ISNULL(@rToDate,'') = ''))         
			  AND BM.OrgGroupBatchId = @rOrgGroupBatchId  
			  AND (SA.DivisionId=@rDivisionId OR @rDivisionId=0)
			  AND (SA.ClassId=@rClassId OR @rClassId=0)
			  AND (SA.[StudentId]=@rStudentId or ISNULL(@rStudentId,0)=0)
			  And(SA.[AcademicId]=@rAcademicId or ISNULL(@rAcademicId,0)=0)
			  AND ((SA.OrgId = @rOrgId) OR (@rOrgId = 0))  
			  AND (SA.Code = @rStudentCode OR ISNULL(@rStudentCode,'') = '')  
			  AND (SA.Name like @rStudentName+'%' OR ISNULL(@rStudentName,'') = '')  
			  AND (ISNULL(L.StatusId,0) = @rStatusId OR (@rStatusId = 0 OR (@rStatusId=549 AND  ISNULL(L.StatusId,0)=0))) 
			  --AND ((SA.DepartmentId = @rDepartmentId ) OR (@rDepartmentId = 0)) 
			  AND ISNULL(EMP.IsOtherUser,0)=0 
			  AND UO.UserId = @rUserId 
			  AND SA.InchargeEmployeeId = @lUserSourceId
			 -- AND U.UserId = @rUserId     
		  ORDER BY   
			  L.CreatedDateTime DESC        
		END
	END

	IF(@lItemValue = 'Class Teacher Batch')
	BEGIN
	--print 111
		IF(@rUserId=0)
		BEGIN
		   SELECT   
			  ROW_NUMBER() OVER(ORDER BY L.CreatedDateTime desc) AS Id,
			  L.AcademicId AS AcademicId,  
			  SA.[StudentId],  
			  L.CreatedDateTime AS ReportDate,  
			  L.[LeaveFromDate] AS FromDate,  
			  L.[LeaveToDate] AS ToDate,  
			  ISNULL(L.LeaveReason,'') as LeaveReason,  
			  --EM.EmployeeName,  
			  SA.Name AS StudentName,
			  SA.Code AS StudentCode,  
			  DATEDIFF(day,L.LeaveFromDate, L.LeaveToDate)+1 AS NoOfLeave,  
			  ISNULL(L.StatusId,0) AS StatusId,  
			  ISNULL(SM.Title,'Pending') AS StatusName,  
			  ISNULL(L.StatusReason,'') AS  StatusReason,  
			  OM.DisplayTitle AS OrganizationName,  
			  ISNULL(L.ActionByEmployeeId,'') as ActionByEmployeeId,  
			  CASE WHEN ISNULL(L.ActionByEmployeeId,0) = 0 AND ISNULL(L.StatusId,549) = 549 THEN '' 	  
			  ELSE EMP.FirstName + ' ' + EMP.LastName END AS ActionByEmployee,  
			  OM.Id AS OrgId,  
			  SA.BatchId AS BatchId, 
			  SA.DivisionId,
			  SA.DivisionName,
			  SA.ClassId,
			  SA.ClassName, 
			  SA.DepartmentId AS DepartmentId,  
			  SA.DepartmentName As DepartmentName
			  --US.Id As UserId
		  FROM   
			  sAttendance.tStudentLeaveRequest L   
			  INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId = L.AcademicId  
			  INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId    
			  INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = BM.OrgId  
			  LEFT JOIN sCommon.tStatusMaster SM ON SM.Id = L.StatusId  
			 --LEFT JOIN sSecurity.tUser US ON US.Id = L.CreatedUserId 
			  LEFT JOIN sHrm.tEmployeeMaster EMP ON EMP.Id = L.ActionByEmployeeId AND ISNULL(EMP.IsOtherUser,0)=0 
			 -- INNER JOIN sSecurity.tUserAccess U ON U.SourceId = EM.DepartmentId AND U.SourceTypeId=2017     
			 INNER JOIN sSetup.tDivisionInchargeEmployee DIE ON DIE.DivisionId = SA.DivisionId
		  WHERE   
			  ((L.LeaveFromDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))  
			  AND ((L.LeaveFromDate <= @rToDate) OR (ISNULL(@rToDate,'') = ''))         
			  AND BM.OrgGroupBatchId = @rOrgGroupBatchId  
			  AND (SA.DivisionId=@rDivisionId OR @rDivisionId=0)
			  AND (SA.ClassId=@rClassId OR @rClassId=0)
			  AND (SA.[StudentId]=@rStudentId or ISNULL(@rStudentId,0)=0)
			  And(SA.[AcademicId]=@rAcademicId or ISNULL(@rAcademicId,0)=0)
			  AND ((SA.OrgId = @rOrgId) OR (@rOrgId = 0))  
			  AND (SA.Code = @rStudentCode OR ISNULL(@rStudentCode,'') = '')  
			  AND (SA.Name like @rStudentName+'%' OR ISNULL(@rStudentName,'') = '')  
			  AND (ISNULL(L.StatusId,0) = @rStatusId OR (@rStatusId = 0 OR (@rStatusId=549 AND  ISNULL(L.StatusId,0)=0))) 
			  --AND ((SA.DepartmentId = @rDepartmentId ) OR (@rDepartmentId = 0)) 
			  AND ISNULL(EMP.IsOtherUser,0)=0 
			  AND DIE.EmployeeId = @lUserSourceId
			  AND DIE.BatchId = @rBatchId
			 --BatchId required only for Class Teacher Batch
			 -- AND U.UserId = @rUserId     
			ORDER BY   
			  L.CreatedDateTime DESC  
		END
	    ELSE
	    BEGIN       
		   SELECT   
				ROW_NUMBER() OVER(ORDER BY L.CreatedDateTime desc) AS Id,
				L.AcademicId AS AcademicId,  
				SA.[StudentId],  
				L.CreatedDateTime AS ReportDate,  
				L.[LeaveFromDate] AS FromDate,  
				L.[LeaveToDate] AS ToDate,  
				ISNULL(L.LeaveReason,'') as LeaveReason,  
				--EM.EmployeeName,  
				SA.Name AS StudentName,
				SA.Code AS StudentCode,  
				DATEDIFF(day,L.LeaveFromDate, L.LeaveToDate)+1 AS NoOfLeave,  
				ISNULL(L.StatusId,0) AS StatusId,  
				ISNULL(SM.Title,'Pending') AS StatusName,  
				ISNULL(L.StatusReason,'') AS  StatusReason,  
				OM.DisplayTitle AS OrganizationName,  
				ISNULL(L.ActionByEmployeeId,'') as ActionByEmployeeId,  
				CASE WHEN ISNULL(L.ActionByEmployeeId,0) = 0 AND ISNULL(L.StatusId,549) = 549 THEN '' 	  
				ELSE EMP.FirstName + ' ' + EMP.LastName END AS ActionByEmployee,  
				OM.Id AS OrgId,  
				SA.BatchId AS BatchId, 
				SA.DivisionId,
				SA.DivisionName,
				SA.ClassId,
				SA.ClassName, 
				SA.DepartmentId AS DepartmentId,  
				SA.DepartmentName As DepartmentName
				--US.Id As UserId
			FROM   
				sAttendance.tStudentLeaveRequest L   
				INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId = L.AcademicId  
				INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId    
				INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = BM.OrgId  
				LEFT JOIN sCommon.tStatusMaster SM ON SM.Id = L.StatusId  
				--LEFT JOIN sSecurity.tUser US ON US.Id = L.CreatedUserId 
				LEFT JOIN sHrm.tEmployeeMaster EMP ON EMP.Id = L.ActionByEmployeeId AND ISNULL(EMP.IsOtherUser,0)=0 
				-- INNER JOIN sSecurity.tUserAccess U ON U.SourceId = EM.DepartmentId AND U.SourceTypeId=2017   
				INNER JOIN sSecurity.tUserOrganization UO ON UO.OrgId=OM.Id  
				INNER JOIN sSetup.tDivisionInchargeEmployee DIE ON DIE.DivisionId = SA.DivisionId
			WHERE   
				((L.LeaveFromDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))  
				AND ((L.LeaveFromDate <= @rToDate) OR (ISNULL(@rToDate,'') = ''))         
				AND BM.OrgGroupBatchId = @rOrgGroupBatchId  
				AND (SA.DivisionId=@rDivisionId OR @rDivisionId=0)
				AND (SA.ClassId=@rClassId OR @rClassId=0)
				AND (SA.[StudentId]=@rStudentId or ISNULL(@rStudentId,0)=0)
				And(SA.[AcademicId]=@rAcademicId or ISNULL(@rAcademicId,0)=0)
				AND ((SA.OrgId = @rOrgId) OR (@rOrgId = 0))  
				AND (SA.Code = @rStudentCode OR ISNULL(@rStudentCode,'') = '')  
				AND (SA.Name like @rStudentName+'%' OR ISNULL(@rStudentName,'') = '')  
				AND (ISNULL(L.StatusId,0) = @rStatusId OR (@rStatusId = 0 OR (@rStatusId=549 AND  ISNULL(L.StatusId,0)=0))) 
				--AND ((SA.DepartmentId = @rDepartmentId ) OR (@rDepartmentId = 0)) 
				AND ISNULL(EMP.IsOtherUser,0)=0 
				AND UO.UserId = @rUserId 
				AND DIE.EmployeeId = @lUserSourceId
				AND DIE.BatchId = @rBatchId
				--BatchId required only for Class Teacher Batch
				-- AND U.UserId = @rUserId     
			ORDER BY   
				L.CreatedDateTime DESC        
	    END
	END

	IF(@lItemValue = 'Academic Setup')
	BEGIN
		--print 333
		IF(@rUserId=0)
		BEGIN
			SELECT   
				 
				 ROW_NUMBER() OVER(ORDER BY L.CreatedDateTime desc) AS Id,
				  L.AcademicId AS AcademicId,  
				  SA.[StudentId],  
				  L.CreatedDateTime AS ReportDate,  
				  L.[LeaveFromDate] AS FromDate,  
				  L.[LeaveToDate] AS ToDate,  
				  ISNULL(L.LeaveReason,'') as LeaveReason,  
				  --EM.EmployeeName,  
				  SA.Name AS StudentName,
				  SA.Code AS StudentCode,  
				  DATEDIFF(day,L.LeaveFromDate, L.LeaveToDate)+1 AS NoOfLeave,  
				  ISNULL(L.StatusId,0) AS StatusId,  
				  ISNULL(SM.Title,'Pending') AS StatusName,  
				  ISNULL(L.StatusReason,'') AS  StatusReason,  
				  OM.DisplayTitle AS OrganizationName,  
				  ISNULL(L.ActionByEmployeeId,'') as ActionByEmployeeId,  
				  CASE WHEN ISNULL(L.ActionByEmployeeId,0) = 0 AND ISNULL(L.StatusId,549) = 549 THEN '' 	  
				  ELSE EMP.FirstName + ' ' + EMP.LastName END AS ActionByEmployee,  
				  OM.Id AS OrgId,  
				  SA.BatchId AS BatchId, 
				  SA.DivisionId,
				  SA.DivisionName,
				  SA.ClassId,
				  SA.ClassName, 
				  SA.DepartmentId AS DepartmentId,  
				  SA.DepartmentName As DepartmentName
				  --US.Id As UserId
			  FROM   
				  sAttendance.tStudentLeaveRequest L   
				  INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId = L.AcademicId  
				  INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId    
				  INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = BM.OrgId  
				  LEFT JOIN sCommon.tStatusMaster SM ON SM.Id = L.StatusId  
				 --LEFT JOIN sSecurity.tUser US ON US.Id = L.CreatedUserId 
				  LEFT JOIN sHrm.tEmployeeMaster EMP ON EMP.Id = L.ActionByEmployeeId AND ISNULL(EMP.IsOtherUser,0)=0 
				 -- INNER JOIN sSecurity.tUserAccess U ON U.SourceId = EM.DepartmentId AND U.SourceTypeId=2017     
				 --INNER JOIN sAcademic.vTeacherSubjectDivision TSD ON SA.ClassId = TSD.ClassId AND SA.DivisionId = TSD.DivisionId

			  WHERE   
				  ((L.LeaveFromDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))  
				  AND ((L.LeaveFromDate <= @rToDate) OR (ISNULL(@rToDate,'') = ''))         
				  AND BM.OrgGroupBatchId = @rOrgGroupBatchId  
				  AND (SA.DivisionId=@rDivisionId OR @rDivisionId=0)
				  AND (SA.ClassId=@rClassId OR @rClassId=0)
				  AND (SA.[StudentId]=@rStudentId or ISNULL(@rStudentId,0)=0)
				  And(SA.[AcademicId]=@rAcademicId or ISNULL(@rAcademicId,0)=0)
				  AND ((SA.OrgId = @rOrgId) OR (@rOrgId = 0))  
				  AND (SA.Code = @rStudentCode OR ISNULL(@rStudentCode,'') = '')  
				  AND (SA.Name like @rStudentName+'%' OR ISNULL(@rStudentName,'') = '')  
				  AND (ISNULL(L.StatusId,0) = @rStatusId OR (@rStatusId = 0 OR (@rStatusId=549 AND  ISNULL(L.StatusId,0)=0))) 
				  --AND ((SA.DepartmentId = @rDepartmentId ) OR (@rDepartmentId = 0)) 
				  AND ISNULL(EMP.IsOtherUser,0)=0 
				  --AND TSD.EmployeeId = @lUserSourceId
				  AND @lUserSourceId IN (Select EmployeeId From sAcademic.vTeacherSubjectDivision WHERE ClassId = SA.ClassId AND DivisionId = SA.DivisionId AND OrgId = SA.OrgId)
				 -- AND U.UserId = @rUserId     
			  ORDER BY   
				  L.CreatedDateTime DESC  
		END
		ELSE
		BEGIN      
		--print 222 
			SELECT   
			  	
			  ROW_NUMBER() OVER(ORDER BY L.CreatedDateTime desc) AS Id,
			  L.AcademicId AS AcademicId,  
			  SA.[StudentId],  
			  L.CreatedDateTime AS ReportDate,  
			  L.[LeaveFromDate] AS FromDate,  
			  L.[LeaveToDate] AS ToDate,  
			 ISNULL(L.LeaveReason,'') as LeaveReason,  
			  --EM.EmployeeName,  
			  SA.Name AS StudentName,
			  SA.Code AS StudentCode,  
			  DATEDIFF(day,L.LeaveFromDate, L.LeaveToDate)+1 AS NoOfLeave,  
			  ISNULL(L.StatusId,0) AS StatusId,  
			  ISNULL(SM.Title,'Pending') AS StatusName,  
			  ISNULL(L.StatusReason,'') AS  StatusReason,  
			  OM.DisplayTitle AS OrganizationName,  
			  ISNULL(L.ActionByEmployeeId,'') as ActionByEmployeeId,  
			  CASE WHEN ISNULL(L.ActionByEmployeeId,0) = 0 AND ISNULL(L.StatusId,549) = 549 THEN '' 	  
			  ELSE EMP.FirstName + ' ' + EMP.LastName END AS ActionByEmployee,  
			  OM.Id AS OrgId,  
			  SA.BatchId AS BatchId, 
			  SA.DivisionId,
			  SA.DivisionName,
			  SA.ClassId,
			  SA.ClassName, 
			  SA.DepartmentId AS DepartmentId,  
			  SA.DepartmentName As DepartmentName
			  --US.Id As UserId
		  FROM   
			  sAttendance.tStudentLeaveRequest L   
			  INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId = L.AcademicId  
			  INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId    
			  INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = BM.OrgId  
			  LEFT JOIN sCommon.tStatusMaster SM ON SM.Id = L.StatusId  
			  --LEFT JOIN sSecurity.tUser US ON US.Id = L.CreatedUserId 
			  LEFT JOIN sHrm.tEmployeeMaster EMP ON EMP.Id = L.ActionByEmployeeId AND ISNULL(EMP.IsOtherUser,0)=0 
			  -- INNER JOIN sSecurity.tUserAccess U ON U.SourceId = EM.DepartmentId AND U.SourceTypeId=2017   
			  INNER JOIN sSecurity.tUserOrganization UO ON UO.OrgId=OM.Id
			  --INNER JOIN sAcademic.vTeacherSubjectDivision TSD ON SA.ClassId = TSD.ClassId AND SA.DivisionId = TSD.DivisionId AND TSD.OrgId = SA.OrgId 

		  WHERE   
			  ((L.LeaveFromDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))  
			  AND ((L.LeaveFromDate <= @rToDate) OR (ISNULL(@rToDate,'') = ''))         
			  AND BM.OrgGroupBatchId = @rOrgGroupBatchId  
			  AND (SA.DivisionId=@rDivisionId OR @rDivisionId=0)
			  AND (SA.ClassId=@rClassId OR @rClassId=0)
			  AND (SA.[StudentId]=@rStudentId or ISNULL(@rStudentId,0)=0)
			  And(SA.[AcademicId]=@rAcademicId or ISNULL(@rAcademicId,0)=0)
			  AND ((SA.OrgId = @rOrgId) OR (@rOrgId = 0))  
			  AND (SA.Code = @rStudentCode OR ISNULL(@rStudentCode,'') = '')  
			  AND (SA.Name like @rStudentName+'%' OR ISNULL(@rStudentName,'') = '')  
			  AND (ISNULL(L.StatusId,0) = @rStatusId OR (@rStatusId = 0 OR (@rStatusId=549 AND  ISNULL(L.StatusId,0)=0))) 
			  --AND ((SA.DepartmentId = @rDepartmentId ) OR (@rDepartmentId = 0)) 
			  AND ISNULL(EMP.IsOtherUser,0)=0 
			  AND UO.UserId = @rUserId 
			  --AND TSD.EmployeeId = @lUserSourceId
			  AND @lUserSourceId IN (Select EmployeeId From sAcademic.vTeacherSubjectDivision WHERE ClassId = SA.ClassId AND DivisionId = SA.DivisionId AND OrgId = SA.OrgId)
			 -- AND U.UserId = @rUserId     
		  ORDER BY   
			  L.CreatedDateTime DESC        
		END
	END

	IF(@lItemValue = 'User Access')
	BEGIN
		IF(@rUserId=0)
		BEGIN
		 	SELECT   
			  ROW_NUMBER() OVER(ORDER BY L.CreatedDateTime desc) AS Id,
			  L.AcademicId AS AcademicId,  
			  SA.[StudentId],  
			  L.CreatedDateTime AS ReportDate,  
			  L.[LeaveFromDate] AS FromDate,  
			  L.[LeaveToDate] AS ToDate,  
			  ISNULL(L.LeaveReason,'') as LeaveReason,  
			  --EM.EmployeeName,  
			  SA.Name AS StudentName,
			  SA.Code AS StudentCode,  
			  DATEDIFF(day,L.LeaveFromDate, L.LeaveToDate)+1 AS NoOfLeave,  
			  ISNULL(L.StatusId,0) AS StatusId,  
			  ISNULL(SM.Title,'Pending') AS StatusName,  
			  ISNULL(L.StatusReason,'') AS  StatusReason,  
			  OM.DisplayTitle AS OrganizationName,  
			  ISNULL(L.ActionByEmployeeId,'') as ActionByEmployeeId,  
			  CASE WHEN ISNULL(L.ActionByEmployeeId,0) = 0 AND ISNULL(L.StatusId,549) = 549 THEN '' 	  
			  ELSE EMP.FirstName + ' ' + EMP.LastName END AS ActionByEmployee,  
			  OM.Id AS OrgId,  
			  SA.BatchId AS BatchId, 
			  SA.DivisionId,
			  SA.DivisionName,
			  SA.ClassId,
			  SA.ClassName, 
			  SA.DepartmentId AS DepartmentId,  
			  SA.DepartmentName As DepartmentName
			  --US.Id As UserId
		  FROM   
			  sAttendance.tStudentLeaveRequest L   
			  INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId = L.AcademicId  
			  INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId    
			  INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = BM.OrgId  
			  LEFT JOIN sCommon.tStatusMaster SM ON SM.Id = L.StatusId  
			 --LEFT JOIN sSecurity.tUser US ON US.Id = L.CreatedUserId 
			  LEFT JOIN sHrm.tEmployeeMaster EMP ON EMP.Id = L.ActionByEmployeeId AND ISNULL(EMP.IsOtherUser,0)=0 
			  INNER JOIN sSecurity.tUserAccess UA ON 
			  (UA.SourceId = CASE WHEN UA.SourceTypeId = 2021 THEN (Select OrgId from sStudent.vStudentAcademic SA1 WHERE SA1.AcademicId = SA.AcademicId)
								WHEN UA.SourceTypeId = 2017 THEN (Select DepartmentId from sStudent.vStudentAcademic SA1 WHERE SA1.AcademicId = SA.AcademicId)
								WHEN UA.SourceTypeId = 2016 THEN (Select ClassId from sStudent.vStudentAcademic SA1 WHERE SA1.AcademicId = SA.AcademicId)
								WHEN UA.SourceTypeId = 2005 THEN (Select DivisionId from sStudent.vStudentAcademic SA1 WHERE SA1.AcademicId = SA.AcademicId)
								WHEN UA.SourceTypeId = 2003 THEN (Select StudentId from sStudent.vStudentAcademic SA1 WHERE SA1.AcademicId = SA.AcademicId)
								END) AND UA.UserId = @rUserId


		  WHERE   
			  ((L.LeaveFromDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))  
			  AND ((L.LeaveFromDate <= @rToDate) OR (ISNULL(@rToDate,'') = ''))         
			  AND BM.OrgGroupBatchId = @rOrgGroupBatchId  
			  AND (SA.DivisionId=@rDivisionId OR @rDivisionId=0)
			  AND (SA.ClassId=@rClassId OR @rClassId=0)
			  AND (SA.[StudentId]=@rStudentId or ISNULL(@rStudentId,0)=0)
			  And(SA.[AcademicId]=@rAcademicId or ISNULL(@rAcademicId,0)=0)
			  AND ((SA.OrgId = @rOrgId) OR (@rOrgId = 0))  
			  AND (SA.Code = @rStudentCode OR ISNULL(@rStudentCode,'') = '')  
			  AND (SA.Name like @rStudentName+'%' OR ISNULL(@rStudentName,'') = '')  
			  AND (ISNULL(L.StatusId,0) = @rStatusId OR (@rStatusId = 0 OR (@rStatusId=549 AND  ISNULL(L.StatusId,0)=0))) 
			  --AND ((SA.DepartmentId = @rDepartmentId ) OR (@rDepartmentId = 0)) 
			  AND ISNULL(EMP.IsOtherUser,0)=0 
	  
			 -- AND U.UserId = @rUserId     
	  ORDER BY   
		  L.CreatedDateTime DESC  
		END
	ELSE
	BEGIN   
	--print 111    
	--CREATE TABLE #tmp
	--(
	--	SourceTypeId int,
	--	SourceId int,
	--	UserId bigint
	--)
	--INSERT INTO #tmp
	--SELECT 
	--SourceTypeId ,SourceId ,UserId 
	--FROM 
	--sSecurity.tUserAccess WHERE UserId = @rUserId

	--Select * from #tmp
	  SELECT   
	      ROW_NUMBER() OVER(ORDER BY L.CreatedDateTime desc) AS Id,
		  L.AcademicId AS AcademicId,  
		  SA.[StudentId],  
		  L.CreatedDateTime AS ReportDate,  
		  L.[LeaveFromDate] AS FromDate,  
		  L.[LeaveToDate] AS ToDate,  
		 ISNULL(L.LeaveReason,'') as LeaveReason,  
		  --EM.EmployeeName,  
		  SA.Name AS StudentName,
		  SA.Code AS StudentCode,  
		  DATEDIFF(day,L.LeaveFromDate, L.LeaveToDate)+1 AS NoOfLeave,  
		  ISNULL(L.StatusId,0) AS StatusId,  
		  ISNULL(SM.Title,'Pending') AS StatusName,  
		  ISNULL(L.StatusReason,'') AS  StatusReason,  
		  OM.DisplayTitle AS OrganizationName,  
		  ISNULL(L.ActionByEmployeeId,'') as ActionByEmployeeId,  
		  CASE WHEN ISNULL(L.ActionByEmployeeId,0) = 0 AND ISNULL(L.StatusId,549) = 549 THEN '' 	  
		  ELSE EMP.FirstName + ' ' + EMP.LastName END AS ActionByEmployee,  
		  OM.Id AS OrgId,  
		  SA.BatchId AS BatchId, 
		  SA.DivisionId,
		  SA.DivisionName,
		  SA.ClassId,
		  SA.ClassName, 
		  SA.DepartmentId AS DepartmentId,  
		  SA.DepartmentName As DepartmentName
		  --US.Id As UserId
	  FROM   
		  sAttendance.tStudentLeaveRequest L   
		  INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId = L.AcademicId  
		  INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId    
		  INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = BM.OrgId  
		  LEFT JOIN sCommon.tStatusMaster SM ON SM.Id = L.StatusId  
		  --LEFT JOIN sSecurity.tUser US ON US.Id = L.CreatedUserId 
		  LEFT JOIN sHrm.tEmployeeMaster EMP ON EMP.Id = L.ActionByEmployeeId AND ISNULL(EMP.IsOtherUser,0)=0 
		  -- INNER JOIN sSecurity.tUserAccess U ON U.SourceId = EM.DepartmentId AND U.SourceTypeId=2017   
		  INNER JOIN sSecurity.tUserOrganization UO ON UO.OrgId=OM.Id  
		  --INNER JOIN #tmp tmp ON 
		  --(tmp.SourceId = CASE WHEN tmp.SourceTypeId = 2021 THEN SA.OrgId
				--		       WHEN tmp.SourceTypeId = 2017 THEN SA.DepartmentId
				--			   WHEN tmp.SourceTypeId = 2016 THEN SA.ClassId
				--			   WHEN tmp.SourceTypeId = 2005 THEN SA.DivisionId
				--			   WHEN tmp.SourceTypeId = 2003 THEN SA.StudentId
				--			   END
		  --)AND tmp.UserId = @rUserId

		  INNER JOIN sSecurity.tUserAccess UA ON 
			(UA.SourceId = CASE WHEN UA.SourceTypeId = 2021 THEN (Select OrgId from sStudent.vStudentAcademic SA1 WHERE SA1.AcademicId = SA.AcademicId)
								WHEN UA.SourceTypeId = 2017 THEN (Select DepartmentId from sStudent.vStudentAcademic SA1 WHERE SA1.AcademicId = SA.AcademicId)
								WHEN UA.SourceTypeId = 2016 THEN (Select ClassId from sStudent.vStudentAcademic SA1 WHERE SA1.AcademicId = SA.AcademicId)
								WHEN UA.SourceTypeId = 2005 THEN (Select DivisionId from sStudent.vStudentAcademic SA1 WHERE SA1.AcademicId = SA.AcademicId)
								WHEN UA.SourceTypeId = 2003 THEN (Select StudentId from sStudent.vStudentAcademic SA1 WHERE SA1.AcademicId = SA.AcademicId)
								END) AND UA.UserId = @rUserId

	  WHERE   
		  ((L.LeaveFromDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))  
		  AND ((L.LeaveFromDate <= @rToDate) OR (ISNULL(@rToDate,'') = ''))         
		  AND BM.OrgGroupBatchId = @rOrgGroupBatchId  
		  AND (SA.DivisionId=@rDivisionId OR @rDivisionId=0)
		  AND (SA.ClassId=@rClassId OR @rClassId=0)
		  AND (SA.[StudentId]=@rStudentId or ISNULL(@rStudentId,0)=0)
		  And(SA.[AcademicId]=@rAcademicId or ISNULL(@rAcademicId,0)=0)
		  AND ((SA.OrgId = @rOrgId) OR (@rOrgId = 0))  
		  AND (SA.Code = @rStudentCode OR ISNULL(@rStudentCode,'') = '')  
		  AND (SA.Name like @rStudentName+'%' OR ISNULL(@rStudentName,'') = '')  
		  AND (ISNULL(L.StatusId,0) = @rStatusId OR (@rStatusId = 0 OR (@rStatusId=549 AND  ISNULL(L.StatusId,0)=0))) 
		  --AND ((SA.DepartmentId = @rDepartmentId ) OR (@rDepartmentId = 0)) 
		  AND ISNULL(EMP.IsOtherUser,0)=0 
		  AND UO.UserId = @rUserId 
	  
		 -- AND U.UserId = @rUserId     
	  ORDER BY   
		  L.CreatedDateTime DESC    
		  
	 --DROP TABLE #tmp    
	END
	END
END

--old Code
ELSE
BEGIN
	IF(@rUserId=0)
	BEGIN
	 SELECT   
	  ROW_NUMBER() OVER(ORDER BY L.CreatedDateTime desc) AS Id,
			L.AcademicId AS AcademicId,  
		  SA.[StudentId],  
		  L.CreatedDateTime AS ReportDate,  
		  L.[LeaveFromDate] AS FromDate,  
		  L.[LeaveToDate] AS ToDate,  
		 ISNULL(L.LeaveReason,'') as LeaveReason,  
		  --EM.EmployeeName,  
		  SA.Name AS StudentName,
		  SA.Code AS StudentCode,  
		  DATEDIFF(day,L.LeaveFromDate, L.LeaveToDate)+1 AS NoOfLeave,  
		  ISNULL(L.StatusId,0) AS StatusId,  
		  ISNULL(SM.Title,'Pending') AS StatusName,  
		  ISNULL(L.StatusReason,'') AS  StatusReason,  
		  OM.DisplayTitle AS OrganizationName,  
		  ISNULL(L.ActionByEmployeeId,'') as ActionByEmployeeId,  
		  CASE WHEN ISNULL(L.ActionByEmployeeId,0) = 0 AND ISNULL(L.StatusId,549) = 549 THEN '' 	  
		  ELSE EMP.FirstName + ' ' + EMP.LastName END AS ActionByEmployee,  
		  OM.Id AS OrgId,  
		  SA.BatchId AS BatchId, 
		  SA.DivisionId,
		  SA.DivisionName,
		  SA.ClassId,
		  SA.ClassName, 
		  SA.DepartmentId AS DepartmentId,  
		  SA.DepartmentName As DepartmentName
		  --US.Id As UserId
	  FROM   
		  sAttendance.tStudentLeaveRequest L   
		  INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId = L.AcademicId  
		  INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId    
		  INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = BM.OrgId  
		  LEFT JOIN sCommon.tStatusMaster SM ON SM.Id = L.StatusId  
		 --LEFT JOIN sSecurity.tUser US ON US.Id = L.CreatedUserId 
		  LEFT JOIN sHrm.tEmployeeMaster EMP ON EMP.Id = L.ActionByEmployeeId AND ISNULL(EMP.IsOtherUser,0)=0 
		 -- INNER JOIN sSecurity.tUserAccess U ON U.SourceId = EM.DepartmentId AND U.SourceTypeId=2017     

	  WHERE   
		  ((L.LeaveFromDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))  
		  AND ((L.LeaveFromDate <= @rToDate) OR (ISNULL(@rToDate,'') = ''))         
		  AND BM.OrgGroupBatchId = @rOrgGroupBatchId  
		  AND (SA.DivisionId=@rDivisionId OR @rDivisionId=0)
		  AND (SA.ClassId=@rClassId OR @rClassId=0)
		  AND (SA.[StudentId]=@rStudentId or ISNULL(@rStudentId,0)=0)
		  And(SA.[AcademicId]=@rAcademicId or ISNULL(@rAcademicId,0)=0)
		  AND ((SA.OrgId = @rOrgId) OR (@rOrgId = 0))  
		  AND (SA.Code = @rStudentCode OR ISNULL(@rStudentCode,'') = '')  
		  AND (SA.Name like @rStudentName+'%' OR ISNULL(@rStudentName,'') = '')  
		  AND (ISNULL(L.StatusId,0) = @rStatusId OR (@rStatusId = 0 OR (@rStatusId=549 AND  ISNULL(L.StatusId,0)=0))) 
		  --AND ((SA.DepartmentId = @rDepartmentId ) OR (@rDepartmentId = 0)) 
		  AND ISNULL(EMP.IsOtherUser,0)=0 
	  
		 -- AND U.UserId = @rUserId     
	  ORDER BY   
		  L.CreatedDateTime DESC  
	END
	ELSE
	BEGIN       
	  SELECT   
	  ROW_NUMBER() OVER(ORDER BY L.CreatedDateTime desc) AS Id,
			L.AcademicId AS AcademicId,  
		  SA.[StudentId],  
		  L.CreatedDateTime AS ReportDate,  
		  L.[LeaveFromDate] AS FromDate,  
		  L.[LeaveToDate] AS ToDate,  
		 ISNULL(L.LeaveReason,'') as LeaveReason,  
		  --EM.EmployeeName,  
		  SA.Name AS StudentName,
		  SA.Code AS StudentCode,  
		  DATEDIFF(day,L.LeaveFromDate, L.LeaveToDate)+1 AS NoOfLeave,  
		  ISNULL(L.StatusId,0) AS StatusId,  
		  ISNULL(SM.Title,'Pending') AS StatusName,  
		  ISNULL(L.StatusReason,'') AS  StatusReason,  
		  OM.DisplayTitle AS OrganizationName,  
		  ISNULL(L.ActionByEmployeeId,'') as ActionByEmployeeId,  
		  CASE WHEN ISNULL(L.ActionByEmployeeId,0) = 0 AND ISNULL(L.StatusId,549) = 549 THEN '' 	  
		  ELSE EMP.FirstName + ' ' + EMP.LastName END AS ActionByEmployee,  
		  OM.Id AS OrgId,  
		  SA.BatchId AS BatchId, 
		  SA.DivisionId,
		  SA.DivisionName,
		  SA.ClassId,
		  SA.ClassName, 
		  SA.DepartmentId AS DepartmentId,  
		  SA.DepartmentName As DepartmentName
		  --US.Id As UserId
	  FROM   
		  sAttendance.tStudentLeaveRequest L   
		  INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId = L.AcademicId  
		  INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId    
		  INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = BM.OrgId  
		  LEFT JOIN sCommon.tStatusMaster SM ON SM.Id = L.StatusId  
		  --LEFT JOIN sSecurity.tUser US ON US.Id = L.CreatedUserId 
		  LEFT JOIN sHrm.tEmployeeMaster EMP ON EMP.Id = L.ActionByEmployeeId AND ISNULL(EMP.IsOtherUser,0)=0 
		  -- INNER JOIN sSecurity.tUserAccess U ON U.SourceId = EM.DepartmentId AND U.SourceTypeId=2017   
		  INNER JOIN sSecurity.tUserOrganization UO ON UO.OrgId=OM.Id  

	  WHERE   
		  ((L.LeaveFromDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))  
		  AND ((L.LeaveFromDate <= @rToDate) OR (ISNULL(@rToDate,'') = ''))         
		  AND BM.OrgGroupBatchId = @rOrgGroupBatchId  
		  AND (SA.DivisionId=@rDivisionId OR @rDivisionId=0)
		  AND (SA.ClassId=@rClassId OR @rClassId=0)
		  AND (SA.[StudentId]=@rStudentId or ISNULL(@rStudentId,0)=0)
		  And(SA.[AcademicId]=@rAcademicId or ISNULL(@rAcademicId,0)=0)
		  AND ((SA.OrgId = @rOrgId) OR (@rOrgId = 0))  
		  AND (SA.Code = @rStudentCode OR ISNULL(@rStudentCode,'') = '')  
		  AND (SA.Name like @rStudentName+'%' OR ISNULL(@rStudentName,'') = '')  
		  AND (ISNULL(L.StatusId,0) = @rStatusId OR (@rStatusId = 0 OR (@rStatusId=549 AND  ISNULL(L.StatusId,0)=0))) 
		  --AND ((SA.DepartmentId = @rDepartmentId ) OR (@rDepartmentId = 0)) 
		  AND ISNULL(EMP.IsOtherUser,0)=0 
		  AND UO.UserId = @rUserId 
	  
		 -- AND U.UserId = @rUserId     
	  ORDER BY   
		  L.CreatedDateTime DESC        
	END

END
GO
PRINT N'Altering Procedure [sStudent].[pRptStudentInformationFormGet]...';


GO
ALTER PROCEDURE [sStudent].[pRptStudentInformationFormGet]
	 
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 @rOrgId smallint,
	 @rBatchId int,
	 @rStrStudentId nvarchar(max),
	 @rStrCode nvarchar(max),
	 @rClassId int,
	 @rDivisionId int,
	 @rStudentId bigint,
	 @rFromRollNo int,
	 @rToRollNo int,
	 @rStatusId int,
	 @rClassStatusId int,
	 @rDateOfBirth int,
	 @rDepartmentId int,
	 @rRemark nvarchar(500),
	 @rNote nvarchar(500)

	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	SELECT 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			@rRemark AS Remark,
			@rNote AS Note,
			SA.AcademicId,
			SA.StudentId, 			
			SA.Code,						
			SA.Name,		
			SA.ClassDivision AS ClassDiv,	
			SA.ParentEmail,
			ISNULL(SF.FatherName,'') AS FatherName,
			ISNULL(SF.FatherContactNo,'') AS FatherContactNo,
			ISNULL(SF.MotherName,'') AS MotherName,
			ISNULL(SF.MotherContactNo,'') AS MotherContactNo,
			ISNULL(SA.Religion,'') AS Religion,
			ISNULL(SA.Gender,'') AS Gender,
			SA.DateOfBirth AS DateOfBirth,
			ISNULL(SA.BloodGroup,'') AS BloodGroup,
			ISNULL(SA.AdhaarNumber,'') AS AdhaarNumber,
			ISNULL(SA.PresentStreetone,'') + ' ' + ISNULL(SA.PresentStreetTwo,'') + ' ' + ISNULL(SA.PresentStreetThree,'') AS PresentAddress,
			
			SF.FatherIncome AS FatherIncome,
			SF.MotherIncome AS MotherIncome,
			SD.BankAccountNumber AS BankAccountNo,
			SD.BankName AS BankName,
			SD.BankBranch AS BranchName,
			SD.BankIFSCCode AS BankIFSCCode,
			CM.Id AS CategoryId,
			CM.Title AS Category,
			SF.IsSingleChild,
			SA.FamilyCast AS Cast,
			 CASE WHEN EXISTS (SELECT StudentId FROM sStudent.tStudentSibling AS SS WHERE SS.StudentId = SA.StudentId)
				THEN 'No' 
					ELSE 'Yes'
				 END AS OnlyOneChild,
				 SA.ClassID,
				 SA.DivisionId,
			SA.ClassStatusId,
			SA.UIDNumber,
			SA.ClassStatusName,
			ISNULL(SA.FamilySubCast,'') SubCast,
			ISNULL(SA.BirthPlace,'') BirthPlace,
			ISNULL(SA.BirthTaluka,'') BirthTaluka,
			ISNULL(SA.BirthDistrict,'') BirthDistrict,
			SA.ClassName,
			SA.DivisionName,
			SA.RollNo,
			SA.AdmissionDate,
			ISNULL(SA.AdmissionStandard,'') AdmissionStandard,
			--Mantis Start -0031790
			SA.PresentStreetone, 
			SA.PresentStreetTwo,
			SA.PresentStreetThree, 
			SA.PresentCity AS PresentDistrict,
			SA.PresentState AS PresentState,
			SA.PresentZipCode As PresentPINCode
			--Mantis End -0031790
			
	FROM 
		 	 sStudent.vStudentAllDetail SA
		 	 --LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId=SA.StudentId
		 	 LEFT JOIN sCommon.tCastCategoryMaster CM ON CM.Id=SA.CastCategoryId
		 	 -- LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId = SA.StudentId
		 	  LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId = SA.StudentId 
		 	  LEFT JOIN sStudent.tStudentAdditional SD ON SD.StudentId=SA.StudentId 
		 	INNER JOIN sSetup.tBatchClass BC ON BC.ClassID =  SA.ClassId and BC.BatchId= @rBatchId
	WHERE 
			SA.OrgId=@rOrgId
		AND	SA.BatchId = @rBatchId
		AND (ISNULL(SA.StudentId,0) NOT IN( SELECT cast(item as bigint) FROM  sCommon.fnsplit(@rStrStudentId,',')) OR @rStrStudentId='') 
		AND (ISNULL(SA.Code,0) IN( SELECT cast(item as nvarchar(20)) FROM  sCommon.fnsplit(@rStrCode,',')) OR @rStrCode='') 
		AND ((SA.ClassId=@rClassId) OR (@rClassId=0))
		AND ((SA.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		AND ((SA.StudentId=@rStudentId) OR (@rStudentId=0))
		AND ((SA.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
		AND ((SA.RollNo <= @rToRollNo) OR (@rToRollNo=0))
		AND ((SA.StatusId=@rStatusId)OR(@rStatusId=0))
		AND ((SA.ClassStatusId=@rClassStatusId)OR(@rClassStatusId=0))
		AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
END
GO
PRINT N'Altering Procedure [sSecurity].[pForgotPasswordFailureLogGet]...';


GO
ALTER PROCEDURE [sSecurity].[pForgotPasswordFailureLogGet]
	 @rFromDate date='',
     @rToDate date='',
     @rOrgId int=0,
	 @rOrgGroupId smallint = 0,
	 @rOsTypeId smallint=0
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

	SELECT DISTINCT
		 FL.AutoId  AS FailureLogId
		,U.Id AS UserId
		,FL.UserName
		,FL.Code
		,FL.SourceId AS UserSourceId
		,FL.SourceTypeId AS UserSourceTypeId
		,CASE WHEN FL.SourceTypeId = 95 THEN 'Employee' 
			  WHEN FL.SourceTypeId = 2003 THEN 'Student' ELSE 'Other' END AS SourceType
		,FL.OrgId
		,FL.IsSendAlert
		,FL.IsResetPassword
		,FL.CreatedDateTime AS FailureLogDate
		,SC.Name AS Name
		,SC.ParentContactNo as MobileNo
		,SC.ParentEmail AS EmailId
		,SC.WhatsAppContactNo
		,OM.Title AS OrgName
        ,OST.Title AS OSTypeTitle
            
		FROM  [sSecurity].[tForgotPasswordFailureLog] FL
		INNER JOIN sSecurity.tUser U ON U.Id = FL.UserId
		INNER JOIN sStudent.vStudentCommunication SC ON SC.StudentId = FL.SourceId AND SC.StudentId = U.sourceId AND U.SourceTypeId = 2003
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = U.OrgId
		LEFT JOIN sAlert.tOSType OST ON OST.Id = FL.OSTypeId	
			
        WHERE ((FL.OrgId = @rOrgId) OR (@rOrgId=0))
		    AND (FL.CreatedDateTime >= @rFromDate OR  ISNULL(@rFromDate,'')='')
			AND (CAST(FL.CreatedDateTime AS DATE) <= @rToDate OR ISNULL(@rToDate,'')='' ) 
			AND ((OST.Id=@rOsTypeId) OR (@rOsTypeId=0)) 
			AND FL.IsResetPassword = 0
	UNION

	SELECT DISTINCT
		 FL.AutoId  AS FailureLogId
		,U.Id AS UserId
		,FL.UserName
		,FL.Code
		,FL.SourceId AS UserSourceId
		,FL.SourceTypeId AS UserSourceTypeId
		,CASE WHEN FL.SourceTypeId = 95 THEN 'Employee' 
			  WHEN FL.SourceTypeId = 2003 THEN 'Student'
			  ELSE 'Other' END AS SourceType
		,FL.OrgId
		,FL.IsSendAlert
		,FL.IsResetPassword
		,FL.CreatedDateTime AS FailureLogDate
		,EC.EmployeeName AS Name
		,EC.MobileNumber as MobileNo
		,EC.CompanyEmail AS EmailId
		,EC.WhatsAppContactNo
		,OM.Title AS OrgName
        ,OST.Title AS OSTypeTitle
		FROM  [sSecurity].[tForgotPasswordFailureLog] FL
		INNER JOIN sSecurity.tUser U ON U.Id = FL.UserId
		INNER JOIN sHrm.vEmployeeCommunication EC ON EC.EmployeeId = FL.SourceId AND EC.EmployeeId = U.sourceId AND U.SourceTypeId = 95
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = U.OrgId
		LEFT JOIN sAlert.tOSType OST ON OST.Id = FL.OSTypeId	
			
        WHERE ((FL.OrgId = @rOrgId) OR (@rOrgId=0))
		    AND (FL.CreatedDateTime >= @rFromDate OR  ISNULL(@rFromDate,'')='')
			AND (CAST(FL.CreatedDateTime AS DATE) <= @rToDate OR ISNULL(@rToDate,'')='' ) 
			AND ((OST.Id=@rOsTypeId) OR (@rOsTypeId=0)) 
			AND FL.IsResetPassword = 0	
END
GO
PRINT N'Altering Procedure [sLibrary].[pRptBookListNotReturnGet]...';


GO
ALTER PROCEDURE [sLibrary].[pRptBookListNotReturnGet]
	 
	       @rBuilder1 nvarchar(max)='',
	       @rBuilder2 nvarchar(max)='',
           @rLibraryId int=0,
           @rSourceTypeId int=0,
           @rFromLogDate date='',
           @rToLogDate date='',
           @rOrgId smallint=0,
           @rBatchId int=0,
           @rFromDueDate date='',
		   @rToDueDate date='',
		   @rBookPublisher nvarchar(200), --Mantis - 32621
		   @rAuthor nvarchar(200)         --Mantis - 32621
		    
           
AS
SET NOCOUNT ON
BEGIN
		SET @rBookPublisher = sCommon.fSearchStringGet(@rBookPublisher)
		SET @rAuthor = sCommon.fSearchStringGet(@rAuthor)
SELECT   
	   @rBuilder1 AS Builder1,
	   @rBuilder2 AS Builder2,
	   BL.Id AS BookLogId,
	   BL.LibraryId,
		(CASE WHEN BL.ReaderSourceTypeId = 95 THEN	'Employee'
			 WHEN BL.ReaderSourceTypeId = 2003 THEN	'Student'
			 ELSE 'Other' END) AS TypeName,

		(CASE WHEN BL.ReaderSourceTypeId = 95 THEN Emp.EmployeeName
			WHEN BL.ReaderSourceTypeId = 2003 THEN vSF.Name
			ELSE
			''
			END) AS Name,
			
		(CASE WHEN BL.ReaderSourceTypeId = 95 THEN Emp.DepartmentName
			WHEN BL.ReaderSourceTypeId = 2003 THEN (vSF.ClassName + ' - '+ vSF.DivisionName)
			ELSE '' END) AS ClassDepartmentName,	
		 
		(CASE WHEN BL.ReaderSourceTypeId = 95 THEN	Emp.Code
			 WHEN BL.ReaderSourceTypeId = 2003 THEN	vSF.Code
			 ELSE '' END) AS Code, 	
	   BL.ReaderSourceTypeId,
	   BL.ReaderSourceId,
	   BL.LogDate,
	   BL.DueDate,
	   BL.ReturnDate,
	   BM.Code AS BookCode,
	   BM.Title AS BookName,
	   OM.DisplayTitle AS OrganizationName,
	    LM.ReportOrgTitle,
	    LM.SmallAddress1,
	    LM.SmallAddress2
	   
  FROM  
		sLibrary.tBookLog BL
		INNER JOIN sLibrary.tBookMaster BM ON BM.Id=BL.ResourceSourceId
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = BL.OrgId
		LEFT JOIN sHrm.vExtEmployeeMaster Emp
			ON Emp.Id = BL.ReaderSourceId AND BL.ReaderSourceTypeId = 95 
		LEFT JOIN sStudent.vStudentLastAcademic vSF
			ON vSF.StudentId = BL.ReaderSourceId AND BL.ReaderSourceTypeId = 2003 
			AND (SELECT IsActive FROM sSetup.tBatchMaster WHERE Id=vSF.BatchId AND IsActive = 1) = 1	
		LEFT JOIN sLibrary.tLibraryMaster LM ON LM.Id=BL.LibraryId			
 
  WHERE 
    BL.StatusId = 523 
	AND BL.LibraryId=@rLibraryId
	--AND (BL.LogDate>=@rFromLogDate OR ISNULL(@rFromLogDate,'')='')
	--AND (BL.LogDate<=@rToLogDate OR ISNULL(@rToLogDate,'')='')
	AND ((BL.DueDate >= @rFromDueDate) OR (ISNULL(@rFromDueDate,'') = ''))
	AND ((BL.DueDate <= @rToDueDate) OR (ISNULL(@rToDueDate,'') = ''))
	AND ((BL.ReaderSourceTypeId=@rSourceTypeId) OR (@rSourceTypeId=0))
	AND ((BL.OrgId=@rOrgId) OR (@rOrgId=0))
	AND ((BL.BatchId=@rBatchId) OR (@rBatchId=0))
	AND (ISNULL(BL.ReturnDate,'')='')
	AND ((BM.Publisher like @rBookPublisher) OR (@rBookPublisher=''))    --Mantis - 32621
	AND ((BM.Author like @rAuthor) OR (@rAuthor=''))            --Mantis - 32621



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


GO
ALTER PROCEDURE [sLibrary].[pRptBookLogRegisterGet]
	 
	       @rBuilder1 nvarchar(max)='',
	       @rBuilder2 nvarchar(max)='',
           @rLibraryId int=0,
           @rSourceTypeId int=0,
           @rFromLogDate date='',
           @rToLogDate date='',
           @rOrgId smallint=0,
           @rBatchId int=0,
           @rFromDueDate date='',
		   @rToDueDate date='',
		   @rBookPublisher nvarchar(200),      --Mantis - 32621
	 	   @rAuthor nvarchar(200)         --Mantis - 32621
		         
           
AS
SET NOCOUNT ON
BEGIN
		SET @rBookPublisher = sCommon.fSearchStringGet(@rBookPublisher)
		SET @rAuthor = sCommon.fSearchStringGet(@rAuthor)
SELECT   
	   @rBuilder1 AS Builder1,
	   @rBuilder2 AS Builder2,
	   BL.Id AS BookLogId,
	   BL.LibraryId,
		(CASE WHEN BL.ReaderSourceTypeId = 95 THEN	'Employee'
			 WHEN BL.ReaderSourceTypeId = 2003 THEN	'Student'
			 ELSE 'Other' END) AS TypeName,

		(CASE WHEN BL.ReaderSourceTypeId = 95 THEN Emp.EmployeeName
			WHEN BL.ReaderSourceTypeId = 2003 THEN vSF.Name
			ELSE
			''
			END) AS Name,
			
		(CASE WHEN BL.ReaderSourceTypeId = 95 THEN Emp.DepartmentName
			WHEN BL.ReaderSourceTypeId = 2003 THEN (vSF.ClassName + ' - '+ vSF.DivisionName)
			ELSE '' END) AS ClassDepartmentName,	
		 
		(CASE WHEN BL.ReaderSourceTypeId = 95 THEN	Emp.Code
			 WHEN BL.ReaderSourceTypeId = 2003 THEN	vSF.Code
			 ELSE '' END) AS Code, 	
	   BL.ReaderSourceTypeId,
	   BL.ReaderSourceId,
	   BL.LogDate,
	   BL.DueDate,
	   BL.ReturnDate,
	   BM.Code AS BookCode,
	   BM.Title AS BookName,
	   OM.DisplayTitle AS OrganizationName,
	    LM.ReportOrgTitle,
	    LM.SmallAddress1,
	    LM.SmallAddress2
	   
  FROM  
		sLibrary.tBookLog BL
		INNER JOIN sLibrary.tBookMaster BM ON BM.Id=BL.ResourceSourceId
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = BL.OrgId
		LEFT JOIN sHrm.vExtEmployeeMaster Emp
			ON Emp.Id = BL.ReaderSourceId AND BL.ReaderSourceTypeId = 95 
		LEFT JOIN sStudent.vStudentLastAcademic vSF
			ON vSF.StudentId = BL.ReaderSourceId AND BL.ReaderSourceTypeId = 2003 
			--AND (SELECT IsActive FROM sSetup.tBatchMaster WHERE Id=vSF.BatchId AND IsActive = 1) = 1	 edited by Jash for Issue no :- 0018773
		LEFT JOIN sLibrary.tLibraryMaster LM ON LM.Id=BL.LibraryId			
 
  WHERE 
    BL.StatusId = 523 
	AND BL.LibraryId=@rLibraryId
	AND (BL.LogDate>=@rFromLogDate OR ISNULL(@rFromLogDate,'')='')
	AND (BL.LogDate<=@rToLogDate OR ISNULL(@rToLogDate,'')='')
	AND ((BL.DueDate >= @rFromDueDate) OR (ISNULL(@rFromDueDate,'') = ''))
	AND ((BL.DueDate <= @rToDueDate) OR (ISNULL(@rToDueDate,'') = ''))
	AND ((BL.ReaderSourceTypeId=@rSourceTypeId) OR (@rSourceTypeId=0))
	AND ((BL.OrgId=@rOrgId) OR (@rOrgId=0))
	AND ((BL.BatchId=@rBatchId) OR (@rBatchId=0)) 
	AND ((BM.Publisher like @rBookPublisher) OR (@rBookPublisher=''))   --Mantis - 32621
	AND ((BM.Author like @rAuthor) OR (@rAuthor=''))         --Mantis - 32621


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


GO
ALTER PROCEDURE [sLibrary].[pRptReaderBookListGet]

	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 @rReaderSourceTypeId smallint,
	 --@rReaderSourceId bigint,
	 @rOrgId smallint,
	 @rBatchId int,
	 @rClassId int,
	 @rDivisionId int,
	 @rFromLogDate date,
	 @rToLogDate date,
	 @rLibraryId int,
	 @rCode nvarchar(20) = '',  --added
	 @rBookPublisher nvarchar(200),      --Mantis - 32621
	 @rAuthor nvarchar(200)	 --Mantis - 32621
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
If(@rReaderSourceTypeId=2003)
BEGIN
	SELECT 
	     
	        @rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			BL.Id AS BookLogId,
			BM.Code AS ResourceCode,
			BM.Title AS ResourceName,
			BL.LogDate,
			BL.DueDate,
			IS1.NoOfBookIssuable,
			BL.StatusId ,
			SM.Title AS Status,
			SA.Name,
			SA.RollNo,
			SA.Code,
			SA.ClassName,
			SA.DivisionName,
			LM.ReportOrgTitle,
	        LM.SmallAddress1,
	        LM.SmallAddress2
			
			
	FROM 
			sLibrary.tBookLog BL
			INNER JOIN sLibrary.tBookMaster BM ON BM.Id=BL.ResourceSourceId
			INNER JOIN sCommon.tStatusMaster SM ON SM.Id=BL.StatusId
			INNER JOIN sStudent.vStudentLastAcademic SA ON SA.StudentId=BL.ReaderSourceId
			INNER JOIN sLibrary.tIssueSetting IS1 ON IS1.SourceId=SA.ClassId AND IS1.SourceTypeId=2005
			INNER JOIN sSetup.tBatchMaster B ON SA.BatchId = B.Id --AND B.IsActive = 1
			LEFT JOIN sLibrary.tLibraryMaster LM ON LM.Id=BL.LibraryId
	WHERE 
			((BL.ReaderSourceTypeId=@rReaderSourceTypeId) OR (@rReaderSourceTypeId=0))
		--AND (BL.ReaderSourceId=@rReaderSourceId OR @rReaderSourceId=0)
		AND (SA.ClassId=@rClassId OR @rClassId=0)
		AND (SA.DivisionId=@rDivisionId OR @rDivisionId=0)
		AND ((BL.LogDate >= @rFromLogDate) OR (ISNULL(@rFromLogDate,'') = ''))
		AND ((BL.LogDate <= @rToLogDate) OR (ISNULL(@rToLogDate,'') = ''))
		AND (BL.StatusId=523) 
		AND ((BL.OrgId=@rOrgId) OR (@rOrgId=0))
		AND ((BL.BatchId=@rBatchId) OR (@rBatchId=0))
		AND (BL.LibraryId=@rLibraryId)
		AND (SA.Code=@rCode OR @rCode='') --added
		AND ((BM.Publisher like @rBookPublisher) OR (@rBookPublisher=''))    --Mantis - 32621
	AND ((BM.Author like @rAuthor) OR (@rAuthor=''))            --Mantis - 32621
END
ELSE If(@rReaderSourceTypeId=95)
BEGIN
		SET @rBookPublisher = sCommon.fSearchStringGet(@rBookPublisher)
		SET @rAuthor = sCommon.fSearchStringGet(@rAuthor)
	SELECT 
	
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			BL.Id AS BookLogId,
			BM.Code AS ResourceCode,
			BM.Title AS ResourceName,
			BM.BookSubject,
			BL.LogDate,
			BL.DueDate,
			IS1.NoOfBookIssuable,			
			BL.StatusId,
			SM.Title AS Status,
			BL.IsCurrentStatus ,
			EM.FirstName+' '+EM.LastName AS Name,
			EM.Code,
			ODM.Title AS EmpDept,
			LM.ReportOrgTitle,
	        LM.SmallAddress1,
	        LM.SmallAddress2
	FROM 
			sLibrary.tBookLog BL
			LEFT JOIN sLibrary.tBookMaster BM ON BM.Id=BL.ResourceSourceId
			INNER JOIN sCommon.tStatusMaster SM ON SM.Id=BL.StatusId
			INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id=BL.ReaderSourceId	
			INNER JOIN sHrm.tEmployeeJobDetail EJD ON EM.Id = EJD.EmployeeId
			INNER JOIN sSetup.tDepartmentMaster ODM ON ODM.Id = EJD.OrganizationDepartmentId
			INNER JOIN sLibrary.tIssueSetting IS1 ON IS1.SourceId=ODM.Id AND IS1.SourceTypeId=2004
			LEFT JOIN sLibrary.tLibraryMaster LM ON LM.Id=BL.LibraryId
				WHERE 
			((BL.ReaderSourceTypeId=@rReaderSourceTypeId) OR (@rReaderSourceTypeId=0))
		--AND (BL.ReaderSourceId=@rReaderSourceId OR @rReaderSourceId=0)
		AND ((BL.LogDate >= @rFromLogDate) OR (ISNULL(@rFromLogDate,'') = ''))
		AND ((BL.LogDate <= @rToLogDate) OR (ISNULL(@rToLogDate,'') = ''))
		AND (BL.StatusId=523)
		AND ((BL.OrgId=@rOrgId) OR (@rOrgId=0))
		AND ((BL.BatchId=@rBatchId) OR (@rBatchId=0))
		AND (BL.LibraryId=@rLibraryId)
		AND  ISNULL(EM.IsOtherUser,0) = 0
		AND ((BM.Publisher like @rBookPublisher) OR (@rBookPublisher=''))    --Mantis - 32621
		AND ((BM.Author like @rAuthor) OR (@rAuthor=''))		   --Mantis - 32621
END              
END
GO
PRINT N'Altering Procedure [sAttendance].[pMonthlyRegisterStudentGet]...';


GO
ALTER PROCEDURE [sAttendance].[pMonthlyRegisterStudentGet]
	 	 
	 	 @rBatchId int,
	 	 @rAcademicId bigint,
	 	 @rAttendanceTypeId tinyint,
	 	 @rSubjectId int
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

declare @lAttedanceGrid nvarchar(max)=''
declare @lCuurentMonthAttedanceGrid nvarchar(max)=''
declare @lCuurentMonthAttedanceGrid1 nvarchar(max)=''

IF EXISTS (SELECT 1 FROM  sSetup.fMonthYearForBatchGET(@rBatchId) WHERE  YearNumber = Year(GETDATE()) AND MonthNumber = MONTH(GETDATE()))
--For Current Batch
BEGIN
IF NOT EXISTS(select 1 From sAttendance.tMonthlyRegister MR  where AcademicId=@rAcademicId and ForMonth=Month(GETDATE()) and ForYear=Year(GETDATE()))
--Current Month Count If Exists

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

		SET @YearNumber =Year(GETDATE())

		print @YearNumber

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

		SET @AttendanceCount = (select count(AttendanceDate) AS PresentCount from sAttendance.tStudentRegister 
		where AcademicId=@rAcademicId and Month(AttendanceDate) =Month(Getdate()) and Year(AttendanceDate)=Year(Getdate()) AND (AttendanceTypeId=@rAttendanceTypeId))		
		
		IF(@AttendanceCount<>0.00)		
		    SET @AveragePresence= (@PresentCount/@AttendanceCount)*100		
		ELSE
		 SET @AveragePresence= 0
		 print @AveragePresence
		 IF(@AttendanceCount<>0.00)		
		    SET @AverageAbsent= (@AbsentCount/@AttendanceCount)*100		
		ELSE
		 SET @AverageAbsent= 0

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

		ORDER BY AcademicId
		FOR XML PATH('')),2,200000) AS CSV
)
SELECT *  FROM (Select 
		SN.AcademicId,
		MY.MonthTitle AS ForMonthInWord,
		MY.MonthNumber AS ForMonth, 
		MY.YearNumber AS ForYear,
		ISNULL(MR.TotalCount,0) AS TotalCount,
		ISNULL(MR.AttendanceCount,0) AS AttendanceCount,
		ISNULL(MR.PresentCount,0) AS PresentCount,
		ISNULL(MR.AbsentCount,0) AS AbsentCount,
		ISNULL(MR.AveragePresence,0) AS AveragePresence,
		ISNULL(MR.AbsentDays,'') AS AbsentDays,
		ISNULL(100.00-MR.AveragePresence,0) As AverageAbsent
		
		
	From sStudent.vStudentName SN 
	INNER JOIN sSetup.fMonthYearForBatchGET(@rBatchId) AS MY ON MY.BatchId=SN.BatchId AND SN.AcademicId=@rAcademicId 
	LEFT JOIN sAttendance.tMonthlyRegister MR ON MR.AcademicId=SN.AcademicId 
		AND (MR.AttendanceTypeId=@rAttendanceTypeId) 
		AND ((MR.SubjectId=@rSubjectId) OR (@rSubjectId=0))
		AND MR.ForMonth=MY.MonthNumber 
		AND MR.ForYear=MY.YearNumber
	WHERE
		(SN.AcademicId=@rAcademicId) 
		AND MY.MonthNumber <> Month(GetDate())

   UNION ALL
   
   SELECT 
           @rAcademicId AS AcademicId,
           Isnull(LEFT(DATENAME(MONTH,Getdate()),10),'') AS ForMonthInWord,
           MONTH(Getdate()) AS ForMonth,
           YEAR(Getdate()) AS ForYear,
           ISNULL(CAST(@AttendanceCount AS int),0) AS TotalCount,
           ISNULL(CAST(@AttendanceCount AS int),0) AS AttendanceCount,                    
           ISNULL(CAST(@PresentCount AS int),0) AS PresentCount,
           ISNULL(CAST(@AbsentCount AS int),0) AS AbsentCount,
           ISNULL(@AveragePresence,0) AS AveragePresence,
		   ISNULL(@AbsentDays,0) AS AbsentDays,
		   ISNULL(@AverageAbsent,0) AS AverageAbsent) AS TempStudentAttendance	
	ORDER BY ForYear,ForMonth
	END	
	ELSE  --Changes for Mantis Id :0032381
	BEGIN
		Select 
			SN.AcademicId,
			MY.MonthTitle AS ForMonthInWord,
			MY.MonthNumber AS ForMonth, 
			MY.YearNumber AS ForYear,
			ISNULL(MR.TotalCount,0) AS TotalCount,
			ISNULL(MR.AttendanceCount,0) AS AttendanceCount,
			ISNULL(MR.PresentCount,0) AS PresentCount,
			ISNULL(MR.AbsentCount,0) AS AbsentCount,
			ISNULL(MR.AveragePresence,0) AS AveragePresence,
			ISNULL(MR.AbsentDays,'') AS AbsentDays,
			ISNULL(100.00-MR.AveragePresence,0) As AverageAbsent		
		From sStudent.vStudentName SN 
		INNER JOIN sSetup.fMonthYearForBatchGET(@rBatchId) AS MY ON MY.BatchId=SN.BatchId AND SN.AcademicId=@rAcademicId 
		LEFT JOIN sAttendance.tMonthlyRegister MR ON MR.AcademicId=SN.AcademicId 
			AND (MR.AttendanceTypeId=@rAttendanceTypeId) 
			AND ((MR.SubjectId=@rSubjectId) OR (@rSubjectId=0))
			AND MR.ForMonth=MY.MonthNumber 
			AND MR.ForYear=MY.YearNumber
		WHERE
			(SN.AcademicId=@rAcademicId) 
	END
END
ELSE --For Past Batch
	BEGIN
	Select 
		SN.AcademicId,
		MY.MonthTitle AS ForMonthInWord,
		MY.MonthNumber AS ForMonth, 
		MY.YearNumber AS ForYear,
		ISNULL(MR.TotalCount,0) AS TotalCount,
		ISNULL(MR.AttendanceCount,0) AS AttendanceCount,
		ISNULL(MR.PresentCount,0) AS PresentCount,
		ISNULL(MR.AbsentCount,0) AS AbsentCount,
		ISNULL(MR.AveragePresence,0) AS AveragePresence,
		ISNULL(MR.AbsentDays,'') AS AbsentDays,
		ISNULL(100.00-MR.AveragePresence,0) As AverageAbsent
		
		
	From sStudent.vStudentName SN 
	INNER JOIN sSetup.fMonthYearForBatchGET(@rBatchId) AS MY ON MY.BatchId=SN.BatchId AND SN.AcademicId=@rAcademicId 
	LEFT JOIN sAttendance.tMonthlyRegister MR ON MR.AcademicId=SN.AcademicId 
		AND (MR.AttendanceTypeId=@rAttendanceTypeId) 
		AND ((MR.SubjectId=@rSubjectId) OR (@rSubjectId=0))
		AND MR.ForMonth=MY.MonthNumber 
		AND MR.ForYear=MY.YearNumber
	WHERE
		(SN.AcademicId=@rAcademicId) 
	END
END
GO
PRINT N'Altering Procedure [sAcademic].[pRptPreLessonPlanGet]...';


GO
ALTER PROCEDURE [sAcademic].[pRptPreLessonPlanGet]

	 @rClassId int,
	 @rSubjectId int,
	 @rBatchId int,
	 @rEmployeeId bigint,
	 @rStartDate date='',
	 @rEndDate date=''
	 ,@rDivisionId int=0
	
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
	If @rStartDate = '01/01/0001' OR @rStartDate IS NULL SET @rStartDate = ''
	If @rEndDate = '01/01/0001' OR @rEndDate IS NULL SET @rEndDate = ''

	SELECT 
			DISTINCT LP.Id,
			LP.ClassId,
			LP.SubjectId,
			--vTSD.DivisionId AS DivisionId,
			LP.SubTopic,
			LP.Objective,
			LP.Summary,
			LP.StartDate,
			LP.EndDate,
			LP.EmployeeId,
			LP.BatchId,
			LP.CreatedUserId,
			LP.CreatedDateTime,
			vTSD.ClassTitle +'-'+ vTSD.DivisionTitle AS ClassDivisionName,
			vTSD.SubjectName,
			EM.FirstName+' '+EM.LastName AS Name,
		ISNULL(LP.DivisionId,0) AS DivisionId,
		  datepart(MONTH,Lp.StartDate) AS MonthId,
		  datename(MONTH,Lp.StartDate) AS Monthname,
		  vTSD.SubjectName,
		  TM.Title AS TopicName      --Mantis - 32891
			
	FROM 
			sAcademic.tPreLessonPlan LP
			INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id=LP.EmployeeId
			 INNER JOIN sAcademic.vTeacherSubjectDivision vTSD ON vTSD.SubjectId = LP.SubjectId
			AND vTSD.ClassId = LP.ClassId 
				AND ((vTSD.DivisionId = LP.DivisionId) OR (ISNULL(LP.DivisionId,-1) = -1)) --changes for mantis Id : 0032142
			AND vTSD.EmployeeId = LP.EmployeeId
			INNER JOIN sAcademic.tTopicMaster TM ON TM.Id=LP.TopicId  --Mantis - 32891
	WHERE 
		(LP.BatchId = @rBatchId) 
		AND ((LP.EmployeeId = @rEmployeeId) OR (@rEmployeeId = 0))
		--AND ((LP.Id = @rId) OR (@rId = 0))
		AND ((LP.ClassId = @rClassId) OR (@rClassId = 0))
		--AND ((vTSD.ClassTitle = @rClassTitle) OR (@rClassTitle = 0))
		AND ((LP.SubjectId = @rSubjectId) OR (@rSubjectId = 0))
		--AND ((LP.IsCompleted='False') OR (LP.IsCompleted=@rIsCompleted))
		AND ((LP.StartDate >= @rStartDate) OR (@rStartDate= ''))
		AND ((LP.DivisionId = @rDivisionId)OR(ISNULL(@rDivisionId,0)=0))
		AND ((LP.StartDate <= @rEndDate)  OR (@rEndDate= ''))
 AND  ISNULL(EM.IsOtherUser,0) = 0
		
END
GO
PRINT N'Altering Procedure [sAdmission].[pAdmissionInquiryGet]...';


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

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

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

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


GO
 

ALTER PROCEDURE [sAlert].[pRecruitmentStatusGet]
	
	@rCandidateId bigint,
	@rTemplate nvarchar(max),
	@rSubject nvarchar(100)='',
	@rOrgGroupId int

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	
SELECT 
		
CM.CandidateNumber AS CandidateNumber,
CM.FirstName+' '+CM.MiddleName+' '+CM.LastName AS Name,
CM.MobileNo AS MobileNo,	
CM.PersonalEmail AS EmailId,
REPLACE (
REPLACE (
REPLACE (
REPLACE (
REPLACE(@rTemplate,
		'[Name]',CM.FirstName+' '+CM.MiddleName+' '+CM.LastName),
		'[ContactNumber]',ISNULL(CM.MobileNo,'')),
		'[EmailId]',ISNULL(CM.PersonalEmail,'')),
		'[CurrentStatus]',ISNULL(RSM.Title,'')),
		'[Address]',ISNULL(CC.PresentStreetOne,'')+' '+ISNULL(CC.PresentStreetTwo,'')+' '+ISNULL(CC.PresentStreetThree,'')+' '+ISNULL(CC.PresentCountry,'')+' '+ISNULL(CC.PresentState,'')+' '+ISNULL(CC.PresentCity,''))		
		AS MsgText,
		
@rSubject AS [Subject],
0 As ReceiverSourceId,
0 As ReceiverSourceTypeId,
ISNULL(CM.CandidateNumber,'') AS CandidateNo,
ISNULL(CM.ApplicationNumber,0) AS ApplicationNo,
CM.MobileNo AS WhatsAppContactNo

FROM sRecruitment.tCandidateMaster CM
INNER JOIN sRecruitment.tRecruitmentStatusLog  RSL ON CM.Id = RSL.CandidateId AND CM.OrgGroupID = RSL.OrgGroupId
LEFT JOIN sRecruitment.tRecruitmentStatusMaster RSM on RSM.Id=RSL.RecruitmentStatusId	
LEFT JOIN sRecruitment.tCandidateCommunications	 CC ON 	CC.CandidateId=CM.Id
WHERE	
		
	CM.Id = @rCandidateId
	AND CM.OrgGroupId = @rOrgGroupId
	AND RSL.CreatedDateTime = (SELECT MAX(t2.CreatedDateTime)FROM sRecruitment.tRecruitmentStatusLog t2 WHERE t2.CandidateId = RSL.CandidateId) -- in alert RecruitmentStatus send wrong due to multiple rows mantisid -- 0032651
END
GO
PRINT N'Altering Procedure [sAppraisal].[pAppraisalStatusGet]...';


GO



--exec sAppraisal.pAppraisalStatusGet @rAppraisalTypeId=148800008,@rOrgGroupDeptId=0,@rDepartmentId=0,@rGradeId=0,@rDesignationId=0,@rEmployeeTypeId=0,@rEmployeeGroupId=0,@rGenderId=0,@rStatusId=7,@rEmpCode=N'T-HMEC-098',@rOrgId=N'1488'
--go
ALTER PROCEDURE [sAppraisal].[pAppraisalStatusGet]  
   
 @rOrgGroupDeptId int,  
 @rAppraisalTypeId int,   
 @rDepartmentId int,  
 @rGradeId int,  
 @rDesignationId int,  
 @rEmployeeTypeId int,  
 @rEmployeeGroupId smallint,  
 @rGenderId smallint,  
 @rStatusId smallint,  
 @rEmpCode nvarchar(10),  
 @rOrgId smallint  
   
WITH EXECUTE AS CALLER  
AS  
SET NOCOUNT ON  
BEGIN   
     
  SELECT  
     DISTINCT EM.Id AS EmployeeId,  
     EM.Code AS EmpCode,  
     EM.Number As Number,  
     ISNULL(EM.FirstName + ' ' + EM.LastName,'') AS EmployeeName,  
     ECD.DepartmentName AS EmpDept,  
     CASE WHEN ISNULL(ERD.MyRating,0) > 0 THEN 'Completed' ELSE 'Pending' END AS EmployeeStatus,  
     ISNULL(EM1.FirstName + ' ' + EM1.LastName,'') AS EmpManagerName,  
     CASE WHEN ISNULL(ERD.ManagerRating,0) > 0 THEN 'Completed' ELSE 'Pending' END AS EmpManagerRatingStatus,  
     ISNULL(EM2.FirstName + ' ' + EM2.LastName,'') AS EmpBusinessHeadName,  
     CASE WHEN ISNULL(KER.BusinessHeadRating,0) > 0 THEN 'Completed' ELSE 'Pending' END AS EmpBusinessHeadRatingStatus  
  FROM  
     sHrm.tEmployeeMaster EM  
     INNER JOIN sHrm.vEmployeeCommonDetail ECD ON ECD.EmployeeId = EM.Id   
     INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id  
     LEFT JOIN sHrm.tEmployeeMaster EM1 ON EM1.Id = EJD.EmployeeManagerId  
     LEFT JOIN sHrm.tEmployeeMaster EM2 ON EM2.Id = EJD.EmployeeBusinessHeadId  
     INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = EM.OrgId  
     LEFT JOIN sHrm.tEmployeeMaster EM3 ON EM3.Id = OM.EmployeeId  
     LEFT JOIN sAppraisal.tKPAEmployee KPA ON KPA.EmployeeId=EM.Id   
     LEFT JOIN sAppraisal.tKPAEmployeeDetail KPAD ON KPAD.KPAEmployeeId=KPA.Id   
     LEFT JOIN sAppraisal.tKPATypeMaster KTM ON KTM.Id = KPAD.KPATypeId  
     LEFT JOIN sAppraisal.tKPAEmployeeRating KER ON KER.KPAEmployeeId=KPA.Id  
     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) OR (@rOrgGroupDeptId = 0))  
  WHERE  
     ((EM.Code = @rEmpCode) OR (@rEmpCode = ''))   
     AND (ECD.EmployeeTypeId = @rEmployeeTypeId OR @rEmployeeTypeId = 0)  
     AND (ECD.OrganizationDepartmentId = @rDepartmentId OR @rDepartmentId = 0)  
     AND (ECD.EmployeeStatusId = @rStatusId OR @rStatusId = 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)   
     AND (OM.Id = @rOrgId)  
	 AND KER.AppraisalTypeId = @rAppraisalTypeId  
      
  ORDER BY  
     EM.Number  
   
END
GO
PRINT N'Altering Procedure [sAudit].[pActivityLogGet]...';


GO
ALTER PROCEDURE [sAudit].[pActivityLogGet]
	@rOrgGroupId int,
	@rOrgId int,
	@rUserName nvarchar(100),
	@rScreenName nvarchar(100),
	@rActivity nvarchar(500),
	@rFromDate date,
	@rToDate date,
	@rOSTypeId tinyint=0,
	@rIsHistory bit = 0
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
SET @rScreenName = sCommon.fSearchStringGet(@rScreenName)
SET @rActivity = sCommon.fSearchStringGet(@rActivity)
SET @rToDate = DATEADD(day,1,@rToDate)

	IF(@rIsHistory = 1)
	BEGIN
       SELECT 
            AL.OrgGroupId,
            AL.OrgId,
            OM.Title AS OrganizationName,
            AL.UserId,
			U.DisplayTitle AS UserName,
			U.LoginTitle,
			U.SessionId,
			S.Title AS ScreenName,
			AL.AuditDate,
			(CASE WHEN AL.ScreenId=126
				  THEN AL.Activity		
			      WHEN AL.ScreenId=20878
				  THEN AL.Activity		
				  WHEN AL.ScreenId=30179
				  THEN AL.Activity
				  WHEN AL.ScreenId=20196
				  THEN AL.Activity
				  WHEN AL.ScreenId=30788
				  THEN AL.Activity
				  WHEN AL.ScreenId=30780
				  THEN AL.Activity
				  WHEN AL.ScreenId=30790
				  THEN AL.Activity
				  WHEN AL.ScreenId=20745
				  THEN AL.Activity
				  WHEN AL.ScreenId=31257
				  THEN AL.Activity
				  WHEN AL.ScreenId IN (31341, 130)
				  THEN AL.Activity
			 ELSE SUBSTRING(AL.Activity, CHARINDEX(' ', AL.Activity)+1, LEN(AL.Activity)-(CHARINDEX(' ', AL.Activity)-1))  END)AS  Activity,			
			ISNULL(AL.RecordSourceId,0) AS RecordSourceId,
			ISNULL(AL.RecordDetail,'') AS RecordDetail,
			ISNULL(OS.Title,'') AS OSType
			
       FROM 
		   sAudit.tActivityLogHistory AL
		   INNER JOIN sSecurity.tUser U ON U.Id = AL.UserId
		   INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = AL.OrgId
		   INNER JOIN sSecurity.tScreen S ON S.Id = AL.ScreenId
		   LEFT JOIN sAlert.tOSType OS ON OS.Id = AL.OSTypeId
       WHERE
		   AL.OrgGroupId = @rOrgGroupId
		   AND ((AL.OrgId = @rOrgId) OR (@rOrgId=0))
		   AND ((U.DisplayTitle = @rUserName) OR (@rUserName = ''))
		   AND ((S.Title LIKE @rScreenName) OR (@rScreenName = ''))
		   AND ((AL.Activity LIKE @rActivity) OR (@rActivity = ''))
		   AND (AL.AuditDate >= @rFromDate)
		   AND (AL.AuditDate <= @rToDate)
		   AND ((AL.OSTypeId = @rOSTypeId) OR (@rOSTypeId=0))
       ORDER BY 
			AL.AuditDate DESC
	END
	ELSE
	BEGIN
		SELECT 
            AL.OrgGroupId,
            AL.OrgId,
            OM.Title AS OrganizationName,
            AL.UserId,
			U.DisplayTitle AS UserName,
			U.LoginTitle,
			U.SessionId,
			S.Title AS ScreenName,
			AL.AuditDate,
			(CASE WHEN AL.ScreenId=126
				  THEN AL.Activity		
			      WHEN AL.ScreenId=20878
				  THEN AL.Activity		
				  WHEN AL.ScreenId=30179
				  THEN AL.Activity
				  WHEN AL.ScreenId=20196
				  THEN AL.Activity
				  WHEN AL.ScreenId=30788
				  THEN AL.Activity
				  WHEN AL.ScreenId=30780
				  THEN AL.Activity
				  WHEN AL.ScreenId=30790
				  THEN AL.Activity
				  WHEN AL.ScreenId=20884
				  THEN AL.Activity
				  WHEN AL.ScreenId=20745
				  THEN AL.Activity
				  WHEN AL.ScreenId=31257
				  THEN AL.Activity
				  WHEN AL.ScreenId IN (31341, 130)
				  THEN AL.Activity
			 ELSE SUBSTRING(AL.Activity, CHARINDEX(' ', AL.Activity)+1, LEN(AL.Activity)-(CHARINDEX(' ', AL.Activity)-1))  END) AS  Activity,			
			ISNULL(AL.RecordSourceId,0) AS RecordSourceId,
			ISNULL(AL.RecordDetail,'') AS RecordDetail,
			ISNULL(OS.Title,'') AS OSType
			
       FROM 
		   sAudit.tActivityLog AL
		   INNER JOIN sSecurity.tUser U ON U.Id = AL.UserId
		   INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = AL.OrgId
		   INNER JOIN sSecurity.tScreen S ON S.Id = AL.ScreenId
		   LEFT JOIN sAlert.tOSType OS ON OS.Id = AL.OSTypeId
       WHERE
		   AL.OrgGroupId = @rOrgGroupId
		   AND ((AL.OrgId = @rOrgId) OR (@rOrgId=0))
		   AND ((U.DisplayTitle = @rUserName) OR (@rUserName = ''))
		   AND ((S.Title LIKE @rScreenName) OR (@rScreenName = ''))
		   AND ((AL.Activity LIKE @rActivity) OR (@rActivity = ''))
		   AND (AL.AuditDate >= @rFromDate)
		   AND (AL.AuditDate <= @rToDate)
		   AND ((AL.OSTypeId = @rOSTypeId) OR (@rOSTypeId=0))
       ORDER BY 
			AL.AuditDate DESC
	END
END
GO
PRINT N'Altering Procedure [sBiometric].[pBiometricStudentAttendanceGet]...';


GO

ALTER PROCEDURE [sBiometric].[pBiometricStudentAttendanceGet]
	 	 @rClassId int,
	 	 @rDivisionId int,
	 	 @rAttendanceTypeId tinyint,
		 @rAttendanceDate date,
		-- @rRepeatCount tinyint,
	 	 @rBatchId int,
	 	 @rOrgId int,
		 @TimeSheetStatusId nvarchar(10) = '0'
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 

Declare @lQuery nvarchar(Max)
DECLARE @strQuery nvarchar(Max)
DECLARE @lDate date
DECLARE @lDay as nvarchar(3)
DECLARE @lMonth as nvarchar(3)
DECLARE @lYear as nvarchar(4)
  BEGIN
	Select @lDay  = RIGHT('00' + CAST(DATEPART(dd,@rAttendanceDate) AS varchar(2)), 2)
	Select @lMonth = RIGHT('00' + CAST(DATEPART(MM,@rAttendanceDate) AS varchar(2)), 2)
	Select @lYear  = RIGHT('0000' + CAST(DATEPART(yyyy,@rAttendanceDate) AS varchar(4)), 4)

	set @strQuery ='Select SA.AcademicId AS AcademicId,SA.Code AS StudentCode,SA.Name AS StudentName,ISNULL(SA.RollNo,0) as RollNo,ISNULL(SR.IsPresent,''true'') as IsPresent,
					ISNULL(SR.AbsentReasonId,0) as AbsentReasonId,SR.RepeatCount,CASE WHEN SR.CreatedUserId IS NULL THEN cast(0 as bit) ELSE cast(1 as bit) END AS IsDeleted,ISNULL(SR.AttendanceTagId,0) AS AttendanceTagId,
					ISNULL(D'+convert(nvarchar(15),@lDay)+'_IN,''00:00'') AS FirstIn,ISNULL(D'+convert(nvarchar(15),@lDay)+'_Out,''00:00'') AS LastOut,ISNULL(D'+convert(nvarchar(15),@lDay)+'_L,''00:00'') AS LateBy,
					ISNULL(D'+convert(nvarchar(15),@lDay)+'_E,''00:00'') AS EarlyBy, ISNULL(D'+convert(nvarchar(15),@lDay)+'_T,''00:00'') AS Duration,ISNULL(D'+convert(nvarchar(15),@lDay)+',''XX'') AS PresentStatus 
					From sStudent.vStudentAcademic SA 
					--Mantis:32909, change in below left join, change from SA.StudentId to SA.AcademicId
					LEFT JOIN sBiometric.tMonthTrans T1 ON SA.AcademicId = T1.EmployeeId AND T1.SourceTypeId=2003 AND ATTN_DT = cast(rtrim(YEAR(''' + convert(nvarchar(15),@rAttendanceDate) + ''') *10000+ Month(''' + convert(nvarchar(15),@rAttendanceDate) + ''') *100+ 01
)
 as datetime)
					LEFT JOIN sAttendance.tStudentRegister SR  ON SR.AcademicId=SA.AcademicId AND SR.AttendanceDate ='''+convert(nvarchar(15),@rAttendanceDate)+''' AND  (SR.AttendanceTypeId='+convert(nvarchar(15),@rAttendanceTypeId)+')
					INNER JOIN sStudent.tStudentAdmission AD ON SA.StudentId = AD.StudentId
				WHERE 
					((SA.ClassId='+convert(nvarchar(15),@rClassId)+') OR ('+convert(nvarchar(15),@rClassId)+'=0))
					  AND ((SA.DivisionId='+convert(nvarchar(15),@rDivisionId)+') OR ('+convert(nvarchar(15),@rDivisionId)+'=0))
					  AND (SA.OrgId = '+convert(nvarchar(15),@rOrgId)+')
					  AND (SA.BatchId = '+convert(nvarchar(15),@rBatchId)+')
					  AND (SA.StatusId NOT IN (2,3))
					  AND (AD.LeftDate > '''+convert(nvarchar(15),@rAttendanceDate)+''' OR ISNULL(AD.LeftDate,'''')= '''')
					  AND (AD.AdmissionDate <= '''+convert(nvarchar(15),@rAttendanceDate)+''')
					AND  (( '''+convert(nvarchar(15),@TimeSheetStatusId)+''' = ''1'' AND (ISNULL(D'+convert(nvarchar(15),@lDay)+'_T,''00:00'') < ''09:30'')) OR ( '''+convert(nvarchar(15),@TimeSheetStatusId)+'''  != ''1'' AND ((ISNULL(D'+convert(nvarchar(15),@lDay)+',''X

X'') = '''+convert(nvarchar(15),@TimeSheetStatusId)+'''  OR '''+convert(nvarchar(15),@TimeSheetStatusId)+''' =''0''))))
				ORDER BY SA.RollNo'
	execute (@strQuery )
	--print @strQuery
  END
END

GO
PRINT N'Altering Procedure [sCommunication].[pXMLCircularAdd]...';


GO
ALTER PROCEDURE [sCommunication].[pXMLCircularAdd]
	
	@rXML nvarchar(max),
	@rOrgId smallint
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	
BEGIN
	BEGIN TRY					-- Uncommented for mantis 0032762
	
	BEGIN TRANSACTION			-- Uncommented for mantis 0032762
	
	DECLARE @lOrgGroupId int = 0

	SELECT @lOrgGroupId=OrgGroupId FROM sSetup.tOrganizationMaster WHERE Id = @rOrgId
	 
	SET @rXML=REPLACE(@rXML,'&','AND')
	DECLARE @lCount INT
	DECLARE @lInterrorCode INT,
			@intDoc INT
	EXECUTE @lInterrorCode = sp_xml_preparedocument @intDoc OUTPUT, @rXML
	
	DECLARE @lNextNumber BIGINT  
	DECLARE @lFromNextNumber BIGINT  
	EXECUTE sCommon.pTableRowIdGet @lOrgGroupId, 'sCommunication.tCircular', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	SET @lFromNextNumber=@lNextNumber-1
	INSERT INTO sCommunication.tCircular
		(
			Id,
			Title,
			Remark,
			StartDate,
			CreatedUserId,
			CreatedDateTime,
			OrgGroupId,
			OrgGroupBatchId,
			AssigneeId,
			CircularTypeId,
			PublishDateTime
		)
	SELECT
			@lFromNextNumber + ROW_NUMBER() OVER(ORDER BY SourceId),
			Title,
			Remark,
			sCommon.fGetDate(), 
			CreatedUserId,
			sCommon.fGetDate(), 
			OrgGroupId,
			OrgGroupBatchId,
			AssigneeId,
			sCommon.fGetIntIdForOrg(2,@lOrgGroupId),
			sCommon.fGetDate()
		
	FROM OPENXML (@intDoc, '/Table/Circular', 1)
	WITH
	(
		SourceId bigint 'SourceId',
		Title nvarchar(100) 'Title',
		Remark nvarchar(200) 'Remark',
		CreatedUserId bigint 'CreatedUserId',
		OrgGroupId smallint 'OrgGroupId',
		OrgGroupBatchId int 'OrgGroupBatchId',
		AssigneeId tinyint 'AssigneeId',
		SourceTypeId smallint 'SourceTypeId'
	)
	
	
	INSERT INTO sCommunication.tCircularScope
		(
			CircularId,
			SourceTypeId,
			SourceId,
			AssigneeToId
		)
	SELECT
			@lFromNextNumber + ROW_NUMBER() OVER(ORDER BY SourceId),
			SourceTypeId,
			SourceId,
			AssigneeToId
					
	FROM OPENXML (@intDoc, '/Table/Circular', 1)
	WITH
	(
		SourceId bigint 'SourceId',
		SourceTypeId smallint 'SourceTypeId',
		AssigneeToId smallint 'AssigneeToId'
	)
	
	
	SELECT @lCount = COUNT(1) FROM OPENXML (@intDoc, '/Table/Circular', 1)
				 WITH ( AcademicId bigint)
		SET @lNextNumber  = @lCount + @lFromNextNumber 
		
		EXECUTE sCommon.pTableRowIdModify @lOrgGroupId, @rTableTitle = 'sCommunication.tCircular', @rCurrentNumber = @lNextNumber 
		
		EXEC sp_xml_removedocument @intDoc
		
		SELECT 1 AS Result,@lFromNextNumber+1 AS FromId,@lNextNumber AS ToId
	
		COMMIT TRANSACTION		-- Uncommented for mantis 0032762
								
	END TRY						-- Uncommented for mantis 0032762
						
	BEGIN CATCH 				-- Uncommented for mantis 0032762
		ROLLBACK TRANSACTION	-- Uncommented for mantis 0032762
		SELECT -1 AS Result		-- Uncommented for mantis 0032762
	END CATCH					-- Uncommented for mantis 0032762
END
GO
PRINT N'Altering Procedure [sHrm].[pDigitalFormFieldApprove]...';


GO

ALTER PROCEDURE [sHrm].[pDigitalFormFieldApprove]
			@rId BIGINT = 0,
			@rUpdateFieldId INT=0,
			@rOldValue NVARCHAR(500)='',
			@rNewValue NVARCHAR(500)='',
			@rActionRemark NVARCHAR(500) = '',
			@rActionUserId BIGINT,
			@rActionDateTime DATETIME,
			@rStatusId INT,
			@rRequestId INT =0,
			@rOldValueImage VARBINARY(MAX) = 0x00000000,
			@rNewValueImage VARBINARY(MAX) = 0x00000000
			 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

	BEGIN
	BEGIN TRY
	
	BEGIN TRANSACTION

		IF EXISTS(SELECT 1 FROM sHrm.vEmployeeCommonDetail WHERE EmployeeId = @rId)
		BEGIN
		    
			DECLARE @lResult INT
			DECLARE @lDataTypeId NVARCHAR(1)
			SELECT @lDataTypeId=DataTypeId FROM sCommon.tUpdateFieldMaster WHERE Id=@rUpdateFieldId

			IF(@lDataTypeId = 4)
			BEGIN
				SET @rNewValue = CONVERT(DATETIME,@rNewValue,104)
				SET @rOldValue = CONVERT(DATETIME,@rOldValue,104)
			END

			DECLARE @lUpdateField NVARCHAR(100)
			DECLARE @lUpdateFieldImage VARBINARY(MAX)
			DECLARE @lSubFunctionality NVARCHAR(100)
			DECLARE @lEmployeeId BIGINT

			SET @lUpdateField = (SELECT Field FROM sCommon.tUpdateFieldMaster WHERE Id = @rUpdateFieldId)

			SET @lSubFunctionality = (SELECT SubFunctionalityName FROM sCommon.tUpdateFieldMaster WHERE Id = @rUpdateFieldId)
			SET @lEmployeeId = (SELECT EmployeeId FROM sHrm.vEmployeeCommonDetail WHERE EmployeeId = @rId)

			IF(@lUpdateField = 'Gender' OR @lUpdateField = 'Religion' OR @lUpdateField = 'MaritalStatus' OR @lUpdateField = 'BloodGroup' 
			 OR @lUpdateField = 'EmployeeDesignation' OR @lUpdateField = 'OrganizationDepartment' OR @lUpdateField = 'EmployeeType' 
			 OR @lUpdateField = 'EmployeeGroup' OR @lUpdateField = 'EmployeeGrade' OR @lUpdateField = 'OrgGroupDepartment' 
			 OR @lUpdateField = 'EmployeeManager'  OR @lUpdateField = 'Payroll' OR  @lUpdateField = 'PayrollGroup' OR @lUpdateField = 'Tribe')
			
			BEGIN
			SET @lUpdateField =@lUpdateField + 'Id'
			END
			IF(@lUpdateField = 'OrganizationHeadManager' )
			BEGIN
				SET @lUpdateField = 'EmployeeBusinessHeadId'
			END
			IF(@lUpdateField = 'CasteCategory' )
			BEGIN
			SET @lUpdateField = REPLACE(@lUpdateField,'Caste','Cast') + 'Id'
			END
			
			IF(@lUpdateField = 'FamilyCast' )
			BEGIN
				SET @lUpdateField = REPLACE(@lUpdateField,'Caste','Cast') 
			END
	
			Declare @Sql nvarchar(MAX)

			IF OBJECT_ID('ListofEmpData') IS NOT NULL	
			BEGIN 
				DROP TABLE ListofEmpData
			END	
			
			--Select @lSubFunctionality	
			IF(@rStatusId = 550)
			BEGIN
				
				IF(@lSubFunctionality = 'EmployeeImage')
				-----------------EmployeeImage--------------
					BEGIN
						IF(@lUpdateField = 'EmployeeImage')
						BEGIN
							SET @lUpdateField = 'EmployeePhoto'
						END

						CREATE TABLE ListofData(Id BIGINT,EmployeeId BIGINT,SubCategory VARBINARY(MAX),UpdatedUserId BIGINT,IsExist BIT);
						INSERT INTO ListofData VALUES (@rId,@lEmployeeId,@rNewValueImage,@rActionUserId,0)

						UPDATE ListofData SET IsExist=1 WHERE EmployeeId NOT IN(SELECT EmployeeId FROM sHrm.tEmployeeImages)

						SET @sql='INSERT INTO sHrm.tEmployeeImages 
								(EmployeeId,'+@lUpdateField+',EmployeeSign,UpdatedDateTime)
								SELECT
									LD.EmployeeId,Ld.SubCategory,Ld.SubCategory,sCommon.fGetDate()
								FROM
									ListofData LD WHERE LD.IsExist=1'
					
						PRINT @sql		
						EXEC sp_executesql @sql
						SET  @sql='UPDATE sHrm.tEmployeeImages  set '+@lUpdateField+' = LD.SubCategory,
									EmployeeSign = LD.SubCategory,
									UpdatedDateTime=sCommon.fGetDate()  
									from sHrm.tEmployeeImages  EI 
									INNER JOIN ListofData LD ON EI.EmployeeId=LD.EmployeeId AND IsExist=0'
		
						EXEC sp_executesql @sql

						DROP TABLE ListofData
						SET @lResult = 1;
					END

				ELSE

				BEGIN

					CREATE TABLE ListofEmpData(Id BIGINT,EmployeeId BIGINT,SubCategory NVARCHAR(150),UpdatedUserId BIGINT,IsExist BIT);
					INSERT INTO ListofEmpData VALUES (@rId,@lEmployeeId,@rNewValue,@rActionUserId,0)
		
					IF(@lSubFunctionality = 'EmployeeCommunication')  ----EmployeeCommunication
						BEGIN
							UPDATE ListofEmpData SET IsExist=1 WHERE EmployeeId NOT IN(SELECT EmployeeId FROM sHrm.tEmployeeCommunications)
								SET @sql='INSERT INTO sHrm.tEmployeeCommunications 
											(EmployeeId,'+@lUpdateField+',CreatedUserId,CreatedDateTime)
											SELECT
												LD.EmployeeId,Ld.SubCategory,LD.UpdatedUserId,sCommon.fGetDate()
											FROM
												ListofEmpData LD WHERE LD.IsExist=1'
									
								PRINT @sql		
								EXEC sp_executesql @sql
								SET @sql='UPDATE sHrm.tEmployeeCommunications set '+@lUpdateField+' = LD.SubCategory,
											UpdatedUserId=LD.UpdatedUserId,
											UpdatedDateTime=sCommon.fGetDate()  
											from sHrm.tEmployeeCommunications EC 
											INNER JOIN ListofEmpData LD ON EC.EmployeeId=LD.EmployeeId AND IsExist=0'
		
								EXEC sp_executesql @sql
	
		
								DROP TABLE ListofEmpData
									 SET @lResult = 1;
						END
						
					ELSE IF(@lSubFunctionality = 'EmployeeOther')         -------EmployeeOther
						BEGIN
							UPDATE ListofEmpData SET IsExist=1 WHERE EmployeeId NOT IN(SELECT EmployeeId FROM sHrm.tEmployeePersonalDetail) 
			
								IF(@lUpdateField = 'DateOfBirth')
								BEGIN			
									SET @sql='INSERT INTO sHrm.tEmployeePersonalDetail 
											(EmployeeId,'+@lUpdateField+',UpdatedUserId,UpdatedDateTime)
											SELECT
												LD.EmployeeId,Ld.SubCategory,LD.UpdatedUserId,sCommon.fGetDate()
											FROM
												ListofEmpData LD WHERE LD.IsExist=1'
									EXEC sp_executesql @sql				
			 							
									SET @sql='UPDATE sHrm.tEmployeePersonalDetail set '+@lUpdateField+' = LD.SubCategory,
												UpdatedUserId=LD.UpdatedUserId,
												UpdatedDateTime=sCommon.fGetDate()  
												from sHrm.tEmployeePersonalDetail EPD 
												INNER JOIN ListofEmpData LD ON EPD.EmployeeId=LD.EmployeeId'			
									EXEC sp_executesql @sql
									SET @sql='UPDATE sHrm.tEmployeePersonalDetail SET '+@lUpdateField+' = null WHERE DateOfBirth=''1900-01-01'''
									EXEC sp_executesql @sql
								END
								ELSE
								BEGIN
									SET @sql='INSERT INTO sHrm.tEmployeePersonalDetail
												(EmployeeId,'+@lUpdateField+',UpdatedUserId,UpdatedDateTime)
												SELECT
													LD.EmployeeId,Ld.SubCategory,LD.UpdatedUserId,sCommon.fGetDate()
												FROM
													ListofEmpData LD WHERE LD.IsExist=1'
									EXEC sp_executesql @sql				
			 							
									SET @sql='UPDATE sHrm.tEmployeePersonalDetail set '+@lUpdateField+' = LD.SubCategory,
												UpdatedUserId=LD.UpdatedUserId,
												UpdatedDateTime=sCommon.fGetDate()  
												from sHrm.tEmployeePersonalDetail EPD 
												INNER JOIN ListofEmpData LD ON EPD.EmployeeId=LD.EmployeeId'
									
									EXEC sp_executesql @sql
									
								END
								DROP TABLE ListofEmpData
									 SET @lResult = 1;
						END	
							
					ELSE IF(@lSubFunctionality = 'JobDetail')		--------JobDetail
						BEGIN
							UPDATE ListofEmpData SET IsExist=1 WHERE EmployeeId NOT IN(SELECT EmployeeId FROM sHrm.tEmployeeJobDetail) 
							IF(@lUpdateField = 'DateOfJoining')
							BEGIN			
								SET @sql='INSERT INTO sHrm.tEmployeeJobDetail 
										(EmployeeId,'+@lUpdateField+',UpdatedUserId,UpdatedDateTime)
										SELECT
											LD.EmployeeId,Ld.SubCategory,LD.UpdatedUserId,sCommon.fGetDate()
										FROM
											ListofEmpData LD WHERE LD.IsExist=1'
								EXEC sp_executesql @sql				
			 						
								SET @sql='UPDATE sHrm.tEmployeeJobDetail  set '+@lUpdateField+' = LD.SubCategory,
											UpdatedUserId=LD.UpdatedUserId,
											UpdatedDateTime=sCommon.fGetDate()  
											from sHrm.tEmployeeJobDetail  EJD 
											INNER JOIN ListofEmpData LD ON EJD.EmployeeId=LD.EmployeeId'			
								EXEC sp_executesql @sql
								SET @sql='UPDATE sHrm.tEmployeeJobDetail SET '+@lUpdateField+' = null WHERE DateOfJoining=''1900-01-01'''
								EXEC sp_executesql @sql
							END
					ELSE IF(@lUpdateField = 'DateOfleaving')
					BEGIN			
						SET @sql='INSERT INTO sHrm.tEmployeeJobDetail 
								(EmployeeId,'+@lUpdateField+',UpdatedUserId,UpdatedDateTime)
								SELECT
									LD.EmployeeId,Ld.SubCategory,LD.UpdatedUserId,sCommon.fGetDate()
								FROM
									ListofEmpData LD WHERE LD.IsExist=1'
						EXEC sp_executesql @sql				
			 				
						SET @sql='UPDATE sHrm.tEmployeeJobDetail  set '+@lUpdateField+' = LD.SubCategory,
									UpdatedUserId=LD.UpdatedUserId,
									UpdatedDateTime=sCommon.fGetDate()  
									from sHrm.tEmployeeJobDetail  EJD 
									INNER JOIN ListofEmpData LD ON EJD.EmployeeId=LD.EmployeeId'			
						EXEC sp_executesql @sql
						SET @sql='UPDATE sHrm.tEmployeeJobDetail SET '+@lUpdateField+' = null WHERE DateOfleaving=''1900-01-01'''
						EXEC sp_executesql @sql
					END
					ELSE IF(@lUpdateField = 'ProbationUptoDate')
					BEGIN			
						SET @sql='INSERT INTO sHrm.tEmployeeJobDetail 
								(EmployeeId,'+@lUpdateField+',UpdatedUserId,UpdatedDateTime)
								SELECT
									LD.EmployeeId,Ld.SubCategory,LD.UpdatedUserId,sCommon.fGetDate()
								FROM
									ListofEmpData LD WHERE LD.IsExist=1'
						EXEC sp_executesql @sql				
			 				
						SET @sql='UPDATE sHrm.tEmployeeJobDetail  set '+@lUpdateField+' = LD.SubCategory,
									UpdatedUserId=LD.UpdatedUserId,
									UpdatedDateTime=sCommon.fGetDate()  
									from sHrm.tEmployeeJobDetail  EJD 
									INNER JOIN ListofEmpData LD ON EJD.EmployeeId=LD.EmployeeId'			
						EXEC sp_executesql @sql
						SET @sql='UPDATE sHrm.tEmployeeJobDetail SET '+@lUpdateField+' = null WHERE ProbationUptoDate=''1900-01-01'''
						EXEC sp_executesql @sql
					END
					ELSE IF(@lUpdateField = 'AhdocUptoDate')
					BEGIN			
						SET @sql='INSERT INTO sHrm.tEmployeeJobDetail 
								(EmployeeId,'+@lUpdateField+',UpdatedUserId,UpdatedDateTime)
								SELECT
									LD.EmployeeId,Ld.SubCategory,LD.UpdatedUserId,sCommon.fGetDate()
								FROM
									ListofEmpData LD WHERE LD.IsExist=1'
						EXEC sp_executesql @sql				
			 				
						SET  @sql='UPDATE sHrm.tEmployeeJobDetail  set '+@lUpdateField+' = LD.SubCategory,
							 		UpdatedUserId=LD.UpdatedUserId,
							 		UpdatedDateTime=sCommon.fGetDate()  
							 		from sHrm.tEmployeeJobDetail  EJD 
							 		INNER JOIN ListofEmpData LD ON EJD.EmployeeId=LD.EmployeeId'			
						EXEC sp_executesql @sql
						SET  @sql='UPDATE sHrm.tEmployeeJobDetail SET '+@lUpdateField+' = null WHERE AhdocUptoDate=''1900-01-01'''
						EXEC sp_executesql @sql
					END
					ELSE IF(@lUpdateField = 'PermanentDate')
					BEGIN			
						SET @sql='INSERT INTO sHrm.tEmployeeJobDetail 
								(EmployeeId,'+@lUpdateField+',UpdatedUserId,UpdatedDateTime)
								SELECT
									LD.EmployeeId,Ld.SubCategory,LD.UpdatedUserId,sCommon.fGetDate()
								FROM
									ListofEmpData LD WHERE LD.IsExist=1'
						EXEC sp_executesql @sql				
			 				
						SET  @sql='UPDATE sHrm.tEmployeeJobDetail  set '+@lUpdateField+' = LD.SubCategory,
									UpdatedUserId=LD.UpdatedUserId,
									UpdatedDateTime=sCommon.fGetDate()  
									from sHrm.tEmployeeJobDetail  EJD 
									INNER JOIN ListofEmpData LD ON EJD.EmployeeId=LD.EmployeeId'			
						EXEC sp_executesql @sql
						SET  @sql='UPDATE sHrm.tEmployeeJobDetail SET '+@lUpdateField+' = null WHERE PermanentDate=''1900-01-01'''
						EXEC sp_executesql @sql
					END
					ELSE
					BEGIN
						SET  @sql='INSERT INTO sHrm.tEmployeeJobDetail
							 		(EmployeeId,'+@lUpdateField+',UpdatedUserId,UpdatedDateTime)
									SELECT
										LD.EmployeeId,Ld.SubCategory,LD.UpdatedUserId,sCommon.fGetDate()
									FROM
										ListofEmpData LD WHERE LD.IsExist=1'
						EXEC sp_executesql @sql				
			 				
						SET  @sql='UPDATE sHrm.tEmployeeJobDetail set '+@lUpdateField+' = LD.SubCategory,
									UpdatedUserId=LD.UpdatedUserId,
									UpdatedDateTime=sCommon.fGetDate()  
									from sHrm.tEmployeeJobDetail EJD 
									INNER JOIN ListofEmpData LD ON EJD.EmployeeId=LD.EmployeeId'
			
						EXEC sp_executesql @sql
					END
					DROP TABLE ListofEmpData
						 SET @lResult = 1;
					END	

					ELSE IF(@lSubFunctionality = 'EmployeeGeneral')			---------EmployeeGeneral
						BEGIN
						
							UPDATE ListofEmpData SET IsExist=1 WHERE EmployeeId NOT IN(SELECT Id FROM sHrm.tEmployeeMaster) 
							-- MantisId : 	0029269 Add EUID
							SET  @sql='INSERT INTO sHrm.tEmployeeMaster
										(Id,'+@lUpdateField+',CreatedUserId,CreatedDateTime,EUId)
										SELECT
											LD.EmployeeId,Ld.SubCategory,LD.UpdatedUserId,sCommon.fGetDate(),LD.EmployeeId
										FROM
											ListofEmpData LD WHERE LD.IsExist=1'				 
							EXEC sp_executesql @sql
							SET  @sql='UPDATE sHrm.tEmployeeMaster set '+@lUpdateField+' = LD.SubCategory,
										UpdatedUserId=LD.UpdatedUserId,
										UpdatedDateTime=sCommon.fGetDate()  
										from sHrm.tEmployeeMaster EM 
										INNER JOIN ListofEmpData LD ON EM.Id=LD.EmployeeId AND IsExist=0'
		
							EXEC sp_executesql @sql
					
							DROP TABLE ListofEmpData
								 SET @lResult = 1;
						END
						--Add IsVPFDeduction because table not allow to insert null value in IsVPFDeduction column  mantisid -- 0032446
					ELSE IF(@lSubFunctionality = 'Statutory')	   ----------Statutory
						BEGIN
							UPDATE ListofEmpData SET IsExist=1 WHERE EmployeeId NOT IN(SELECT EmployeeId FROM sHrm.tEmployeeStatutoryAndOther) 
							SET @sql='INSERT INTO sHrm.tEmployeeStatutoryAndOther 
										(EmployeeId,IsVPFDeduction,'+@lUpdateField+',UpdatedUserId,UpdatedDateTime)
										SELECT
											LD.EmployeeId,0,Ld.SubCategory,LD.UpdatedUserId,sCommon.fGetDate()
										FROM
											ListofEmpData LD WHERE LD.IsExist=1'				
							EXEC sp_executesql @sql
							
							SET @sql='UPDATE sHrm.tEmployeeStatutoryAndOther set '+@lUpdateField+' = LD.SubCategory,
											UpdatedUserId=LD.UpdatedUserId,
											UpdatedDateTime=sCommon.fGetDate()  
											from sHrm.tEmployeeStatutoryAndOther ES 
											INNER JOIN ListofEmpData LD ON ES.EmployeeId=LD.EmployeeId AND IsExist=0'

							EXEC sp_executesql @sql
							 
							DROP TABLE ListofEmpData
							 SET @lResult = 1;
						END
				END	

				IF(@lResult = 1)
				BEGIN
					UPDATE sHrm.tDigitalFormEmployee
					SET
						StatusId = @rStatusId
						,ActionRemark = @rActionRemark
						,ActionUserId = @rActionUserId
						,ActionDateTime = @rActionDateTime
					WHERE 
						AutoId = @rRequestId
				END
			
				SELECT 1 AS Result
			END

			ELSE IF(@rStatusId = 551)
			IF(@lSubFunctionality = 'EmployeeImage')
				BEGIN
					IF(@lUpdateField = 'EmployeeImage')
						BEGIN
							SET @lUpdateField = 'EmployeePhoto'
						END

					CREATE TABLE ListofData(Id BIGINT,EmployeeId BIGINT,SubCategory VARBINARY(MAX),UpdatedUserId BIGINT,IsExist BIT);
					INSERT INTO ListofData VALUES (@rId,@lEmployeeId,@rOldValueImage,@rActionUserId,0)

					UPDATE ListofData SET IsExist=1 WHERE EmployeeId NOT IN(SELECT EmployeeId FROM sHrm.tEmployeeImages)

					SET @sql='INSERT INTO sHrm.tEmployeeImages 
						(EmployeeId,'+@lUpdateField+',EmployeeSign,UpdatedDateTime)
						SELECT
							LD.EmployeeId,Ld.SubCategory,Ld.SubCategory,sCommon.fGetDate()
						FROM
							ListofData LD WHERE LD.IsExist=1'

					EXEC sp_executesql @sql

					DROP TABLE ListofData
					SET @lResult = 1;
				END

			ELSE
			BEGIN

				CREATE TABLE ListofEmpData(Id BIGINT,EmployeeId BIGINT,SubCategory NVARCHAR(150),UpdatedUserId BIGINT,IsExist BIT);
				INSERT INTO ListofEmpData VALUES (@rId,@lEmployeeId,@rNewValue,@rActionUserId,0)

			--UPDATE ListofEmpData SET IsExist=1 WHERE EmployeeId NOT IN(SELECT EmployeeId FROM sHrm.tEmployeeCommunications)
			
				IF(@lSubFunctionality = 'EmployeeCommunication')  ----EmployeeCommunication
					BEGIN
						UPDATE ListofEmpData SET IsExist=1 WHERE EmployeeId NOT IN(SELECT EmployeeId FROM sHrm.tEmployeeCommunications)
							SET  @sql='INSERT INTO sHrm.tEmployeeCommunications 
										(EmployeeId,'+@lUpdateField+',CreatedUserId,CreatedDateTime)
										SELECT
											LD.EmployeeId,Ld.SubCategory,LD.UpdatedUserId,sCommon.fGetDate()
										FROM
											ListofEmpData LD WHERE LD.IsExist=1'
								
							PRINT @sql		
							EXEC sp_executesql @sql
							SET  @sql='UPDATE sHrm.tEmployeeCommunications set '+@lUpdateField+' = LD.SubCategory,
										UpdatedUserId=LD.UpdatedUserId,
										UpdatedDateTime=sCommon.fGetDate()  
										from sHrm.tEmployeeCommunications EC 
										INNER JOIN ListofEmpData LD ON EC.EmployeeId=LD.EmployeeId AND IsExist=0'
		
							EXEC sp_executesql @sql
	
		
							DROP TABLE ListofEmpData
								 SET @lResult = 1;
						END
					
				ELSE IF(@lSubFunctionality = 'EmployeeOther')         -------EmployeeOther
					BEGIN
						UPDATE ListofEmpData SET IsExist=1 WHERE EmployeeId NOT IN(SELECT EmployeeId FROM sHrm.tEmployeePersonalDetail) 
							IF(@lUpdateField = 'DateOfBirth')
							BEGIN			
								SET @sql='INSERT INTO sHrm.tEmployeePersonalDetail 
										(EmployeeId,'+@lUpdateField+',UpdatedUserId,UpdatedDateTime)
										SELECT
											LD.EmployeeId,Ld.SubCategory,LD.UpdatedUserId,sCommon.fGetDate()
										FROM
											ListofEmpData LD WHERE LD.IsExist=1'
								EXEC sp_executesql @sql				
			 						
								SET @sql='UPDATE sHrm.tEmployeePersonalDetail set '+@lUpdateField+' = LD.SubCategory,
											UpdatedUserId=LD.UpdatedUserId,
											UpdatedDateTime=sCommon.fGetDate()  
											from sHrm.tEmployeePersonalDetail EPD 
											INNER JOIN ListofEmpData LD ON EPD.EmployeeId=LD.EmployeeId'			
								EXEC sp_executesql @sql
								SET @sql='UPDATE sHrm.tEmployeePersonalDetail SET '+@lUpdateField+' = null WHERE DateOfBirth=''1900-01-01'''
								EXEC sp_executesql @sql
						END
					ELSE
						BEGIN
							SET @sql='INSERT INTO sHrm.tEmployeePersonalDetail
										(EmployeeId,'+@lUpdateField+',UpdatedUserId,UpdatedDateTime)
										SELECT
											LD.EmployeeId,Ld.SubCategory,LD.UpdatedUserId,sCommon.fGetDate()
										FROM
											ListofEmpData LD WHERE LD.IsExist=1'
							EXEC sp_executesql @sql				
			 					
							SET @sql='UPDATE sHrm.tEmployeePersonalDetail set '+@lUpdateField+' = LD.SubCategory,
										UpdatedUserId=LD.UpdatedUserId,
										UpdatedDateTime=sCommon.fGetDate()  
										from sHrm.tEmployeePersonalDetail EPD 
										INNER JOIN ListofEmpData LD ON EPD.EmployeeId=LD.EmployeeId'
			
							EXEC sp_executesql @sql
						END
						DROP TABLE ListofEmpData
							 SET @lResult = 1;
						END	

				Else IF(@lSubFunctionality = 'JobDetail')		--------JobDetail
					BEGIN
						UPDATE ListofEmpData SET IsExist=1 WHERE EmployeeId NOT IN(SELECT EmployeeId FROM sHrm.tEmployeeJobDetail) 
						IF(@lUpdateField = 'DateOfJoining')
						BEGIN			
							SET @sql='INSERT INTO sHrm.tEmployeeJobDetail 
									(EmployeeId,'+@lUpdateField+',UpdatedUserId,UpdatedDateTime)
									SELECT
										LD.EmployeeId,Ld.SubCategory,LD.UpdatedUserId,sCommon.fGetDate()
									FROM
										ListofEmpData LD WHERE LD.IsExist=1'
							EXEC sp_executesql @sql				
			 					
							SET @sql='UPDATE sHrm.tEmployeeJobDetail  set '+@lUpdateField+' = LD.SubCategory,
										UpdatedUserId=LD.UpdatedUserId,
										UpdatedDateTime=sCommon.fGetDate()  
										from sHrm.tEmployeeJobDetail  EJD 
										INNER JOIN ListofEmpData LD ON EJD.EmployeeId=LD.EmployeeId'			
							EXEC sp_executesql @sql
							SET @sql='UPDATE sHrm.tEmployeeJobDetail SET '+@lUpdateField+' = null WHERE DateOfJoining=''1900-01-01'''
							EXEC sp_executesql @sql
					END

					ELSE IF(@lUpdateField = 'DateOfleaving')
						BEGIN			
							SET @sql='INSERT INTO sHrm.tEmployeeJobDetail 
									(EmployeeId,'+@lUpdateField+',UpdatedUserId,UpdatedDateTime)
									SELECT
										LD.EmployeeId,Ld.SubCategory,LD.UpdatedUserId,sCommon.fGetDate()
									FROM
										ListofEmpData LD WHERE LD.IsExist=1'
							EXEC sp_executesql @sql				
			 					
							SET @sql='UPDATE sHrm.tEmployeeJobDetail  set '+@lUpdateField+' = LD.SubCategory,
										UpdatedUserId=LD.UpdatedUserId,
										UpdatedDateTime=sCommon.fGetDate()  
										from sHrm.tEmployeeJobDetail  EJD 
										INNER JOIN ListofEmpData LD ON EJD.EmployeeId=LD.EmployeeId'			
							EXEC sp_executesql @sql
							SET  @sql='UPDATE sHrm.tEmployeeJobDetail SET '+@lUpdateField+' = null WHERE DateOfleaving=''1900-01-01'''
							EXEC sp_executesql @sql
						END

					ELSE IF(@lUpdateField = 'ProbationUptoDate')
					BEGIN			
						SET @sql='INSERT INTO sHrm.tEmployeeJobDetail 
								(EmployeeId,'+@lUpdateField+',UpdatedUserId,UpdatedDateTime)
								SELECT
									LD.EmployeeId,Ld.SubCategory,LD.UpdatedUserId,sCommon.fGetDate()
								FROM
									ListofEmpData LD WHERE LD.IsExist=1'
						EXEC sp_executesql @sql				
			 				
						SET @sql='UPDATE sHrm.tEmployeeJobDetail  set '+@lUpdateField+' = LD.SubCategory,
									UpdatedUserId=LD.UpdatedUserId,
									UpdatedDateTime=sCommon.fGetDate()  
									from sHrm.tEmployeeJobDetail  EJD 
									INNER JOIN ListofEmpData LD ON EJD.EmployeeId=LD.EmployeeId'			
						EXEC sp_executesql @sql
						SET @sql='UPDATE sHrm.tEmployeeJobDetail SET '+@lUpdateField+' = null WHERE ProbationUptoDate=''1900-01-01'''
						EXEC sp_executesql @sql
					END
					ELSE IF(@lUpdateField = 'AhdocUptoDate')
					BEGIN			
						SET @sql='INSERT INTO sHrm.tEmployeeJobDetail 
								(EmployeeId,'+@lUpdateField+',UpdatedUserId,UpdatedDateTime)
								SELECT
									LD.EmployeeId,Ld.SubCategory,LD.UpdatedUserId,sCommon.fGetDate()
								FROM
									ListofEmpData LD WHERE LD.IsExist=1'
						EXEC sp_executesql @sql				
			 				
						SET @sql='UPDATE sHrm.tEmployeeJobDetail  set '+@lUpdateField+' = LD.SubCategory,
									UpdatedUserId=LD.UpdatedUserId,
									UpdatedDateTime=sCommon.fGetDate()  
									from sHrm.tEmployeeJobDetail  EJD 
									INNER JOIN ListofEmpData LD ON EJD.EmployeeId=LD.EmployeeId'			
						EXEC sp_executesql @sql
						SET @sql='UPDATE sHrm.tEmployeeJobDetail SET '+@lUpdateField+' = null WHERE AhdocUptoDate=''1900-01-01'''
						EXEC sp_executesql @sql
					END
					ELSE IF(@lUpdateField = 'PermanentDate')
					BEGIN			
						SET @sql='INSERT INTO sHrm.tEmployeeJobDetail 
								(EmployeeId,'+@lUpdateField+',UpdatedUserId,UpdatedDateTime)
								SELECT
									LD.EmployeeId,Ld.SubCategory,LD.UpdatedUserId,sCommon.fGetDate()
								FROM
									ListofEmpData LD WHERE LD.IsExist=1'
						EXEC sp_executesql @sql				
			 				
						SET @sql='UPDATE sHrm.tEmployeeJobDetail  set '+@lUpdateField+' = LD.SubCategory,
									UpdatedUserId=LD.UpdatedUserId,
									UpdatedDateTime=sCommon.fGetDate()  
									from sHrm.tEmployeeJobDetail  EJD 
									INNER JOIN ListofEmpData LD ON EJD.EmployeeId=LD.EmployeeId'			
						EXEC sp_executesql @sql
						SET @sql='UPDATE sHrm.tEmployeeJobDetail SET '+@lUpdateField+' = null WHERE PermanentDate=''1900-01-01'''
						EXEC sp_executesql @sql
					END
					ELSE
						BEGIN
							SET @sql='INSERT INTO sHrm.tEmployeeJobDetail
										(EmployeeId,'+@lUpdateField+',UpdatedUserId,UpdatedDateTime)
										SELECT
											LD.EmployeeId,Ld.SubCategory,LD.UpdatedUserId,sCommon.fGetDate()
										FROM
											ListofEmpData LD WHERE LD.IsExist=1'
							EXEC sp_executesql @sql				
			 					
							SET @sql='UPDATE sHrm.tEmployeeJobDetail set '+@lUpdateField+' = LD.SubCategory,
										UpdatedUserId=LD.UpdatedUserId,
										UpdatedDateTime=sCommon.fGetDate()  
										from sHrm.tEmployeeJobDetail EJD 
										INNER JOIN ListofEmpData LD ON EJD.EmployeeId=LD.EmployeeId'
			
							EXEC sp_executesql @sql
						END
					DROP TABLE ListofEmpData
						 SET @lResult = 1;
					END	

				ELSE IF(@lSubFunctionality = 'EmployeeGeneral')			---------EmployeeGeneral
					BEGIN
					
						UPDATE ListofEmpData SET IsExist=1 WHERE EmployeeId NOT IN(SELECT Id FROM sHrm.tEmployeeMaster) 
						-- MantisId : 	0029269 Add EUID									
						SET @sql='INSERT INTO sHrm.tEmployeeMaster
									(Id,'+@lUpdateField+',CreatedUserId,CreatedDateTime,EUId)
									SELECT
										LD.EmployeeId,Ld.SubCategory,LD.UpdatedUserId,sCommon.fGetDate(),LD.EmployeeId
									FROM
										ListofEmpData LD WHERE LD.IsExist=1'				
						EXEC sp_executesql @sql
						SET @sql='UPDATE sHrm.tEmployeeMaster set '+@lUpdateField+' = LD.SubCategory,
									UpdatedUserId=LD.UpdatedUserId,
									UpdatedDateTime=sCommon.fGetDate()  
									from sHrm.tEmployeeMaster EM 
									INNER JOIN ListofEmpData LD ON EM.Id=LD.EmployeeId AND IsExist=0'
		
						EXEC sp_executesql @sql
						
						DROP TABLE ListofEmpData
							 SET @lResult = 1;
					END
					--Add IsVPFDeduction because table not allow to insert null value in IsVPFDeduction column  mantisid -- 0032446
				 Else IF(@lSubFunctionality = 'Statutory')	   ----------Statutory
					BEGIN
						 UPDATE ListofEmpData SET IsExist=1 WHERE EmployeeId NOT IN(SELECT EmployeeId FROM sHrm.tEmployeeStatutoryAndOther) 
						 SET @sql='INSERT INTO sHrm.tEmployeeStatutoryAndOther 
									(EmployeeId,IsVPFDeduction,'+@lUpdateField+',UpdatedUserId,UpdatedDateTime)
									SELECT
										LD.EmployeeId,0,Ld.SubCategory,LD.UpdatedUserId,sCommon.fGetDate()
									FROM
										ListofEmpData LD WHERE LD.IsExist=1'				
						 EXEC sp_executesql @sql
						 
						 SET @sql='UPDATE sHrm.tEmployeeStatutoryAndOther set '+@lUpdateField+' = LD.SubCategory,
										UpdatedUserId=LD.UpdatedUserId,
										UpdatedDateTime=sCommon.fGetDate()  
										from sHrm.tEmployeeStatutoryAndOther ES 
										INNER JOIN ListofEmpData LD ON ES.EmployeeId=LD.EmployeeId AND IsExist=0'

						EXEC sp_executesql @sql
						  
						DROP TABLE ListofEmpData
							SET @lResult = 1;
					END
				
			END

			IF(@lResult = 1)
			BEGIN
				UPDATE sHrm.tDigitalFormEmployee
				SET
					StatusId = @rStatusId
					,ActionRemark = @rActionRemark
					,ActionUserId = @rActionUserId
					,ActionDateTime = @rActionDateTime
				WHERE 
					AutoId = @rRequestId
			END
			SELECT 2 AS Result
		END

		ELSE
		BEGIN
		   SELECT -101 As Result
		END
		
		COMMIT TRANSACTION

		END TRY	
	BEGIN CATCH
		ROLLBACK TRANSACTION
		SELECT -1 AS RESULT
		SELECT ERROR_MESSAGE() AS Error
	END CATCH
		
END
GO
PRINT N'Altering Procedure [sHrm].[pIDNoGenerationUpdate]...';


GO
ALTER PROCEDURE [sHrm].[pIDNoGenerationUpdate]
	 
	@rEmployeeId bigint,
	@rIDNo nvarchar(20),
	@rCreatedUserId bigint,
	@rOrgId smallint 
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

		   DECLARE @lCode nvarchar(20)
		   SELECT @lCode=Code FROM sHrm.tEmployeeMaster WHERE Code=@rIDNo AND OrgId=@rOrgId AND Id<>@rEmployeeId --AND ISNULL(IsOtherUser,0) = 0
		   IF @lCode IS NOT NULL
		   BEGIN
					SELECT -103 AS Result,@lCode AS Code
					RETURN
		   END 
		   
		 --  IF EXISTS(SELECT @lCode=Code FROM sStudent.tStudentMaster WHERE Code=@rIDNo AND OrgId=@rOrgId AND Id<>@rStudentId)
			--	BEGIN
			--	SELECT -103 AS RESULT
			--	RETURN
			--END 
	BEGIN TRY
	 BEGIN TRANSACTION	
	 BEGIN
	    UPDATE  sHrm.tEmployeeMaster
	    SET
		    Code=@rIDNo, 	  
			UpdatedUserId=@rCreatedUserId,
			UpdatedDateTime=sCommon.fGetDate() 
	      WHERE Id = @rEmployeeId AND ISNULL(IsOtherUser,0) = 0	   
	 END  
		SELECT 1 AS RESULT
		COMMIT TRANSACTION
	END TRY
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS RESULT
	END CATCH	
		
END
GO
PRINT N'Altering Procedure [sHrm].[pRptEmployeeAttendanceGet]...';


GO

ALTER PROCEDURE [sHrm].[pRptEmployeeAttendanceGet]
	 
	@rBuilder1 nvarchar(max)='',
	@rBuilder2 nvarchar(max)='',
	@rEmployeeName nvarchar(200),
	@rEmployeeCode nvarchar (200),
	@rEmployeeId bigint,
	@rDepartmentId int,
	@rEmployeeGradeId int,
	@rForYear  smallint,
	@rForMonth tinyint,
	@rBatchId int,
	@rOrgId int,
	@rEmployeeStatusId int = 0
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
       SELECT 
			 @rBuilder1 AS Builder1,
			 @rBuilder2 AS Builder2, 
			 EM.Code AS EmployeeCode,
			 EM.EmployeeName,   
			 EM.EmployeeId,
			 EM.DepartmentName,
			 EM.EmployeeGrade,     
			 ISNULL(WD.TotalDays,ISNULL(AT.TotalWorkingDays,0)) As TotalDays,
			 ISNULL(AT.TotalWorkingDays,ISNULL(WD.WorkingDays,0)) AS WorkingDays, 
			 ISNULL(AT.LWP,0) AS LWP,
			-- CONVERT(INT,(ISNULL(AT.TotalWorkingDays,0) - ISNULL(AT.LWP,0))) AS PresentDays,
			 (ISNULL(AT.TotalWorkingDays,0) - (ISNULL(AT.LWP,0) + ISNULL(AT.PaidLeave,0))) AS PresentDays,
			 MM.Title AS MonthName,
			 AT.ForYear As YearName,			
			 --L.LeaveReason,
			 --L.NoOfLeave,
			 --L.ReportDate,
			 --L.FromDate,
			 --L.ToDate,
			 --LPM.Title As LeavePeriod,
			 --LTM.Title As LeaveType,
			 --LTM.IsCarryForward,
			 --LTM.IsLWP
			  EM.EmployeeDesignation As Designation, -- Mantis 0030721
			  [sHrm].[fEmployeeNameGet](EM.FirstName, EM.MiddleName, Em.LastName, OM.EmployeeNameFormatId) AS EmployeeNameFormatWise, --Mantis 0031250
			  EM.Number -- Added for Mantis : 32040 by Nilesh
        FROM 
			sHrm.vEmployeeCommonDetail EM 
			LEFT JOIN sHrm.tEmployeeAttendance AT ON AT.EmployeeId=EM.EmployeeId
			LEFT JOIN sCommon.tMonthMaster MM ON MM.Id=AT.ForMonth
			LEFT JOIN sHrm.tWorkingDays WD ON  EM.EmployeeGradeId = WD.EmployeeGradeId
			AND WD.ForMonth=@rForMonth AND WD.ForYear=@rForYear AND WD.BatchId = @rBatchId			
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=EM.OrgId
			--INNER JOIN sHrm.tLeave L ON L.EmployeeId = EM.EmployeeId
			--INNER JOIN sHrm.tLeavePeriodMaster LPM ON LPM.Id=L.LeavePeriodId
			--INNER JOIN sHrm.tLeaveTypeMaster LTM ON LTM.Id=L.LeaveTypeId
    	WHERE 
    			EM.OrgID = @rOrgId 
    		AND (AT.BatchId=@rBatchId)
    		AND ((AT.ForMonth=@rForMonth) OR (@rForMonth=0))
    		AND ((AT.ForYear=@rForYear) OR (@rForYear=0))
    		AND ((EM.EmployeeGradeId=@rEmployeeGradeId) OR (@rEmployeeGradeId=0))
    		AND ((EM.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
    		AND ((EM.Code like @rEmployeeCode) OR (@rEmployeeCode=''))
    		AND ((EM.EmployeeName like @rEmployeeName) OR (@rEmployeeName=''))
    		AND ((EM.EmployeeId=@rEmployeeId) OR (@rEmployeeId=0))
    		AND ((EM.EmployeeStatusId=@rEmployeeStatusId) OR (@rEmployeeStatusId=0))
    		--AND ((L.FromDate>=@rFromDate) OR (ISNULL(@rFromDate,'')=''))
    		--AND ((L.ToDate>=@rToDate) OR (ISNULL(@rToDate,'')=''))
    		AND EM.IsOtherUser = 0
    		ORDER BY EM.Number
    		
END
GO
PRINT N'Altering Procedure [sLibrary].[pRptBookListGet]...';


GO
ALTER PROCEDURE [sLibrary].[pRptBookListGet]
	 
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='',
	 @rBookSupplier nvarchar(200),
	 @rBookPublisher nvarchar(200),      
	 @rBookSubjectText nvarchar(200),
	 @rBookLanguage nvarchar(200),
	 @rBookTag nvarchar(200),
	 @rBookCustomTag nvarchar(200),
	 @rLibraryId int,
	 @rBookDepartment nvarchar(150)='',
	 @rIsDetail bit=0,
	 @rFromPurchaseDate date='',
	 @rToPurchaseDate date='',
	 @rBookGroup1Id int,
	 @rBookGroup2Id int,
	 --@rOrgGroupId int,
	 @rFromCode nvarchar(25) ='',
	 @rToCode nvarchar(25) ='',
	 @rSpecificCode nvarchar(max) ='',
	 @rBookSubjectDrop nvarchar(500)='',
	 @rFromDate date ='',
	 @rToDate date ='',
	 --Start For Mantis: 31829
	 @rFromBookCode bigint=0,
	 @rToBookCode bigint=0,
	 --End For Mantis: 31829
	 @rAuthor nvarchar(200)         --Mantis - 32621
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
		
BEGIN 
	--DECLARE @rFromCodeInt INT, @rToCodeInt INT
	--DECLARE @BookConfig NVARCHAR, @rFromCodeString NVARCHAR, @rToCodeString NVARCHAR
	--SELECT @BookConfig = ItemValue From sConfig.tConfigurationSetup	WHERE ConfigurationId = 260 AND SourceId = @rOrgGroupId
	
	--SET @rFromCodeInt = Convert(Int,ISNULL(@rFromCode,0))
	--SET @rToCodeInt = Convert(Int,ISNULL(@rToCode,0))
	--SET @rFromCodeString = Convert(nvarchar,ISNULL(@rFromCode,''))
	--SET @rToCodeString = Convert(nvarchar,ISNULL(@rToCode,''))
	
	DECLARE @ListofBookCodes TABLE(Code nvarchar(25), ID INT IDENTITY(1,1));
		INSERT INTO @ListofBookCodes
	
	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
		

	BEGIN	  
		SET @rBookSupplier = sCommon.fSearchStringGet(@rBookSupplier)
		SET @rBookPublisher = sCommon.fSearchStringGet(@rBookPublisher)
		SET @rAuthor = sCommon.fSearchStringGet(@rAuthor)
		SET @rBookSubjectText = sCommon.fSearchStringGet(@rBookSubjectText)
		SET @rBookLanguage = sCommon.fSearchStringGet(@rBookLanguage)
		SET @rBookTag = sCommon.fSearchStringGet(@rBookTag)
		SET @rBookCustomTag = sCommon.fSearchStringGet(@rBookCustomTag)
		SET @rBookDepartment = sCommon.fSearchStringGet(@rBookDepartment)
    END

	SELECT 
		@rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,
		BM.Code,
		BM.Title As BookTitle,
		BM.Publisher,BM.Supplier,
		BM.BookSubject,
		BM.Code AS BookCode,
		BM.BookLanguage,
		BM.BookCustomTag,
		BM.BookCustomTag,
		BM.Location,
		BM.ISBNNumber,
		LM.ReportOrgTitle,
        LM.SmallAddress1,
        LM.SmallAddress2,
        CASE WHEN BM.BookDepartment is null THEN 'Blank'
            WHEN BM.BookDepartment='' THEN 'Blank'  ELSE BM.BookDepartment END AS  BookDepartment,
        BM.NoOfCopies,
        @rIsDetail AS IsDetail,
        LM.Code AS LibraryCode,	       
         LM.Title AS LibraryTitle,
        BM.AccessionNo AS AccessionNo
		
	FROM 
		sLibrary.tBookMaster BM
		LEFT JOIN sLibrary.tLibraryMaster LM ON LM.Id=BM.LibraryId
	WHERE 
		BM.LibraryId=@rLibraryId
		AND ((BM.Supplier like @rBookSupplier) OR (@rBookSupplier=''))
		AND ((BM.Publisher like @rBookPublisher) OR (@rBookPublisher=''))
		AND ((BM.BookSubject like @rBookSubjectText) OR (@rBookSubjectText=''))
		AND ((BM.BookSubject = @rBookSubjectDrop) OR (@rBookSubjectDrop=''))
		AND ((BM.BookLanguage like @rBookLanguage) OR (@rBookLanguage=''))
		AND ((BM.BookTag like @rBookTag) OR (@rBookTag=''))
		AND ((BM.BookCustomTag like @rBookCustomTag) OR (@rBookCustomTag=''))
		AND ((BM.BookDepartment like @rBookDepartment) OR (@rBookDepartment=''))
		AND ((BM.PurchaseDate >= @rFromPurchaseDate) OR (ISNULL(@rFromPurchaseDate,'') = ''))
		AND ((BM.PurchaseDate <= @rToPurchaseDate) OR (ISNULL(@rToPurchaseDate,'') =''))
		AND ((BM.BookGroup1Id = @rBookGroup1Id) OR (@rBookGroup1Id=0))
		AND ((BM.BookGroup2Id = @rBookGroup2Id) OR (@rBookGroup2Id=0))
		AND ((Convert(nvarchar(25),ISNULL(BM.Code,'')) >= @rFromCode) OR (ISNULL(@rFromCode,'') = ''))
		AND ((Convert(nvarchar(25),ISNULL(BM.Code,'')) <= @rToCode) OR (ISNULL(@rToCode,'') = ''))
		AND ((BM.Code IN(SELECT Code FROM @ListofBookCodes)) OR (ISNULL(@rSpecificCode,'') = ''))
		--AND CASE WHEN @BookConfig = 'True' THEN BM.Code >= @rFromCodeString ELSE BM.Code > @rFromCodeInt END AS BM.Code
		--AND CASE WHEN @BookConfig = 'True' THEN BM.Code <= @rToCodeString ELSE BM.Code > @rToCodeInt END AS BM.Code
		AND ((BM.BookEntryDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
		AND ((BM.BookEntryDate <= @rToDate) OR (ISNULL(@rToDate,'') = ''))
		--Start For Mantis: 31829
		AND (ISNUMERIC(BM.Code) = 1 AND (CAST(BM.Code AS bigint) >= @rFromBookCode OR Convert(bigint, ISNULL(@rFromBookCode, '0')) = 0) OR (ISNUMERIC(BM.Code) = 0 AND Convert(bigint, ISNULL(@rFromBookCode, '0')) = 0))
		AND (ISNUMERIC(BM.Code) = 1 AND (CAST(BM.Code AS bigint) <= @rToBookCode OR Convert(bigint, ISNULL(@rToBookCode, '0')) = 0) OR (ISNUMERIC(BM.Code) = 0 AND Convert(bigint, ISNULL(@rToBookCode, '0')) = 0))
		--End For Mantis: 31829
		AND ((BM.Author like @rAuthor) OR (@rAuthor=''))            --Mantis - 32621

		ORDER BY
		CASE WHEN BM.Code like '%[0-9]%' 
		 THEN Replicate('0', 100 - Len(BM.Code)) + BM.Code
		 ELSE BM.Code  END
		--ORDER BY CONVERT(INT, BM.Code)
		
	END
GO
PRINT N'Altering Procedure [sPayroll].[pPayProcessEmployeeRemarkList]...';


GO

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

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


GO

ALTER PROCEDURE [sPayroll].[pRptBankStatement]
	
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 @rEmployeeId bigint,
	 @rEmployeeCode nvarchar(200),
	 @rEmployeeName nvarchar(200),
	 @rDepartmentId int,
	 @rForMonth int,
	 @rForYear int,
	 @rPayrollId int,
	 @rPayrollGroupId int,
	 @rPayrollYearId int,
	 @rOrderByField nvarchar(20)='',
	 @rOrgId int = 0,
	 @rStatusId int = 0,
	 @rEmployeeGroupId int = 0,
	 @rPayTypeId tinyint =0,   -- Mantis #Start - 32058
	 @rDesignationId int= 0,
	 @rGradeId int= 0,
	 @rBankName nvarchar(200)=''  -- Mantis #End - 32058
	  
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

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

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

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

		
	FROM sPayroll.tPayProcess PP 
	INNER JOIN sPayroll.tPayProcessEmployee PPE ON PPE.PayProcessId=PP.ID
	INNER JOIN sHrm.vEmployeeCommonDetail EM ON EM.EmployeeId = PPE.EmployeeId 
	INNER JOIN sHrm.tEmployeeMaster tEM ON tEM.Id = PPE.EmployeeId 
	INNER JOIN sPayroll.tPayProcessElement PE ON PE.PayProcessEmployeeId=PPE.ID
	INNER JOIN sPayroll.tPayElement P ON PE.PayElementId=P.ID 
	LEFT JOIN sHrm.tEmployeeStatutoryAndOther ESO ON ESO.EmployeeId=PPE.EmployeeId	
	INNER JOIN sCommon.tMonthMaster MM ON MM.Id=PP.SalaryMonth	
	INNER JOIN sPayroll.tPayrollYearMaster PY ON PP.PayrollYearId = PY.Id 
	INNER JOIN sPayroll.tPayrollGroupMaster PGM ON PGM.Id = PPE.PayrollGroupId
	INNER JOIN sPayroll.tPayrollMaster PM ON PY.PayrollId = PM.Id
	INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = tEM.OrgId
	LEFT JOIN sPayroll.tPayProcessEmployeeRemark PER ON
		PER.SalaryMonth=@rForMonth AND PER.SalaryYear=@rForYear	AND PER.PayrollYearId=@rPayrollYearId AND EM.EmployeeId = PER.EmployeeId
where 
      (PPE.EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
      AND ((EM.Code Like '%' +  @rEmployeeCode + '%' ) OR (@rEmployeeCode = ''))
	  AND ((EM.EmployeeName Like '%' + @rEmployeeName  + '%') OR (@rEmployeeName = ''))
	  AND (EM.DepartmentId = @rDepartmentId OR @rDepartmentId = 0)
	  AND (PP.SalaryMonth = @rForMonth OR @rForMonth = 0)
	  AND (PP.SalaryYear = @rForYear OR @rForYear = 0) 
	  AND ((PY.PayrollId=@rPayrollId) OR (@rPayrollId=0))
	  AND (PPE.PayrollGroupId = @rPayrollGroupId OR @rPayrollGroupId = 0) 
	  AND (PP.PayrollYearId = @rPayrollYearId OR @rPayrollYearId = 0) 
	  AND ((tEM.OrgID = @rOrgId) OR (@rOrgId = 0))
	  AND ((tEM.StatusId = @rStatusId) OR (@rStatusId = 0))
	  AND ((EM.EmployeeGroupId = @rEmployeeGroupId) OR (@rEmployeeGroupId = 0))
	  AND ((UPPER(ESO.BankName) like UPPER(@rBankName)) OR(ISNULL(@rBankName,'')=''))    -- Mantis Start - 32058
	  AND (PER.PayTypeId = @rPayTypeId OR @rPayTypeId = 0)
	  AND (EM.EmployeeGradeId = @rGradeId OR @rGradeId = 0)
	  AND (EM.EmployeeDesignationId = @rDesignationId OR @rDesignationId = 0)           -- Mantis End - 32058
	 
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
	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.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 [sPayroll].[pRptMonthlyPayElementwiseListGet]...';


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

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


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


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

BEGIN 
	DECLARE @lMonthDay int=0
	SELECT @lMonthDay=[sCommon].[fGetDaysInMonth] (@rForMonth,@rForYear)
	DECLARE @lBasicPayElementId int
	SELECT @lBasicPayElementId = Id FROM sPayroll.tPayElement WHERE PayrollId = @rPayrollId AND PayElementDefaultId = 1

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

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


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


	FROM 
		sPayroll.tPayProcess PP 
		INNER JOIN sPayroll.tPayProcessEmployee PPE ON PPE.PayProcessId=PP.ID
		INNER JOIN sHrm.vEmployeeCommonDetail EM ON EM.EmployeeId = PPE.EmployeeId
		INNER JOIN sHrm.tEmployeeMaster tEM ON tEM.Id=PPE.EmployeeId
		LEFT JOIN sHrm.tEmployeeStatutoryAndOther ESO ON ESO.EmployeeId=EM.EmployeeId
		INNER JOIN sPayroll.tPayProcessElement PE ON PE.PayProcessEmployeeId=PPE.ID
		INNER JOIN sPayroll.tPayElement P ON PE.PayElementId=P.ID 
		INNER JOIN sPayroll.tPayrollYearMaster PY ON PP.PayrollYearId = PY.Id
		INNER JOIN sCommon.tMonthMaster MM ON MM.Id=PP.SalaryMonth
		INNER JOIN sHrm.tEmployeeAttendance AT ON AT.EmployeeId=EM.EmployeeId AND ((AT.ForMonth = @rForMonth) OR (@rForMonth = 0))  AND ((AT.ForYear = @rForYear) OR (@rForYear = 0)) 
		INNER JOIN sPayroll.tPayrollMaster PM ON PY.PayrollId = PM.Id
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=tEM.OrgId
		LEFT JOIN sPayroll.tPayProcessEmployeeRemark PER ON
			PER.SalaryMonth=@rForMonth AND PER.SalaryYear=@rForYear	AND PER.PayrollYearId=@rPayrollYearId AND EM.EmployeeId = PER.EmployeeId
		LEFT JOIN sFinanceCommon.tPayTypeMaster PTM ON PTM.Id = PER.PayTypeId
		LEFT JOIN sFinanceCommon.tPayTypeMaster PTM2 ON PTM2.Id = ESO.PayTypeId
WHERE 
		(PPE.EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
		AND ((EM.Code Like @rEmployeeCode) OR (@rEmployeeCode = ''))
		AND ((EM.EmployeeName Like @rEmployeeName) OR (@rEmployeeName = ''))
		AND ((PP.SalaryMonth = @rForMonth) OR (@rForMonth = 0))
	    AND ((PP.SalaryYear = @rForYear) OR (@rForYear = 0))
		AND ((PY.PayrollId=@rPayrollId) OR (@rPayrollId=0))
		AND (PPE.PayrollGroupId = @rPayrollGroupId OR @rPayrollGroupId = 0) 
		AND (PP.PayrollYearId = @rPayrollYearId OR @rPayrollYearId = 0) 
		AND ((EM.DateOfleaving >= @lFirstDate) OR ISNULL(EM.DateOfleaving,'') = '' OR ISNULL(@lFirstDate,'')='')
        AND ((EM.DateOfJoining <= @lLasteDate) OR ISNULL(EM.DateOfJoining,'') = '' OR ISNULL(@lLasteDate,'')='')
		AND ((tEM.OrgID = @rOrgId) OR (@rOrgId = 0))
		AND (EM.DepartmentId = @rDepartmentId OR @rDepartmentId = 0)
		AND ((tEM.StatusId = @rStatusId) OR (@rStatusId = 0))
		AND ((EM.EmployeeGroupId = @rEmployeeGroupId) OR (@rEmployeeGroupId = 0))
		AND (EM.EmployeeGradeId = @rGradeId OR @rGradeId = 0)						-- Mantis Start - 32061
	  AND (EM.EmployeeDesignationId = @rDesignationId OR @rDesignationId = 0)       -- Mantis End - 32061
END
GO
PRINT N'Altering Procedure [sProcurement].[pRptStockIssueEmployee]...';


GO

ALTER PROCEDURE [sProcurement].[pRptStockIssueEmployee]
 
	@rId int = 0,
	@rStoreLocationId int = 0,
	@rMainGroupId int=0,
	@rSubGroupId int=0,
	@rItemCode nvarchar(50)='',
	@rItemName nvarchar(50)='',
	@rOrgGroupId int=0,
	@rBuilder1 nvarchar(max)='',
	@rBuilder2 nvarchar(max)='',
	@rReportId int=0,
	@rStockItemCategoryId int=0,
	@rFromDate date='',
	@rTodate date='',
	@rToDepartmentId int =0,
	@rNumber nvarchar(10)='',
	@rEmployeeId bigint = 0,
	@rOrgId smallint = 0,
	@rBatchId int = 0
	
WITH EXECUTE AS CALLER
AS
BEGIN
	
	SET NOCOUNT ON;
	SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED

       SELECT  
			@rBuilder1 AS Builder1,
			SIM.Code AS ItemNumber,
			SIM.Title AS ItemName,		
			SI.IssuedByName,	
			SI.Number, 	
			SI.CreatedDateTime AS IssuedDate,
			ID.IssuedQuantity,
			ID.RequestedQuantity,
			EM.FirstName +' '+EM.MiddleName As EmployeeName,
			EM.Code AS EmployeeCode,
			SG.Code AS ItemSubGroup,
			SG.Id AS ItemSubGroupId,
			OM.DisplayTitle,
			EM.DepartmentName AS Department,
			(SELECT ISNULL(SUM(AvailableQuantity),0) FROM sProcurement.tStockBatch SB 
		    WHERE SB.StockItemId = SIM.Id 
		    AND ((SB.StorelocationId = @rStoreLocationId) OR (@rStoreLocationId = 0))
			) AS Quantity ,
			EM.OrgID,
			ISNULL(CAST(SIP.WeightedAverageCost AS DECIMAL(18, 2)), '0') AS WeightedAverageCost,
			SI.Remark--mantis - 0032620

		FROM  
			sProcurement.tStockIssue SI		
			INNER JOIN sProcurement.tStockIssueDetail ID ON SI.Id = ID.StockIssueId
			INNER JOIN sIp.tStockItemMaster SIM ON ID.StockItemId  = SIM.Id 
			LEFT JOIN sIp.tStockItemPlanning SIP ON SIP.StockItemId=SIM.Id AND SIP.StoreLocationId=@rStoreLocationId
			INNER JOIN sHrm.vExtEmployeeMaster EM ON EM.EmployeeId = SI.IssueToSourceId
			INNER JOIN sIp.tItemSubGroupMaster SG ON SG.Id=SIM.ItemSubGroupId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=EM.OrgID
			 
		WHERE 
			 ((SI.Id = @rId) OR (@rId=0))
			 AND SI.FromStoreLocationId =@rStoreLocationId
			 AND ((SIM.ItemSubGroupId= @rSubGroupId) OR (@rSubGroupId=0))
			 AND ((SIM.Code = @rItemCode) OR (@rItemCode=''))	
			 AND ((SIM.Title = @rItemName) OR (@rItemName=''))
			 AND ((convert(Date,ISNULL(SI.CreatedDateTime,'')) >= @rFromDate) OR (convert(date,ISNULL(@rFromDate,''))=''))
			 AND ((convert(date,ISNULL(SI.CreatedDateTime,'')) <= @rToDate) OR (convert(date,ISNULL(@rToDate,''))=''))
			 AND SI.OrgGroupId = @rOrgGroupId
			 AND ((SI.ToOrganizationDepartmentId=@rToDepartmentId) OR (@rToDepartmentId=0))
			 AND ((SI.Number like @rNumber) OR  (ISNULL(@rNumber,'')= ''))
			 AND ((SI.IssueToSourceId= @rEmployeeId) OR (ISNULL(@rEmployeeId,0)=0))
			 AND SI.IssueToSourceTypeId = 95
			 AND ((EM.OrgId = @rOrgId) OR (ISNULL(@rOrgId,0) = 0))
			 
END
GO
PRINT N'Altering Procedure [sProcurement].[pRptStockIssueRegisterGet]...';


GO

ALTER PROCEDURE [sProcurement].[pRptStockIssueRegisterGet]
    @rBuilder1 nvarchar(max)='',
	@rBuilder2 nvarchar(max)='',
	@rReportId int,
	@rStoreLocationId int,
	@rMainGroupId int,
	@rSubGroupId int,
	@rStockItemCategoryId int,
	@rItemCode nvarchar(100),
	@rItemName nvarchar(100),
	@rOrgGroupId int,
	@rFromDate date = '',
	@rToDate date = '',
	@rDetail bit =0,
	@rToDepartmentId int=0,
	@rIssuedToName nvarchar(100)
	
WITH EXECUTE AS CALLER
AS
BEGIN
   SELECT  
		SIM.Code AS ItemCode,
		SIM.Title AS ItemName,		
		SI.IssuedByName,	
		SI.Number AS Billno, 	
		SI.CreatedDateTime AS IssuedDate,
		ID.IssuedQuantity,
		ID.RequestedQuantity,
		 
		--SI.POReference AS POReference,
		--SI.InvoiceReference AS InvoiceReference,
		--VM.Code As SupplierCode,
		--VM.Title As SupplierName,
		SB.ExpiryDate,
		SIP.WeightedAverageCost AS Amount,
		SB.Number As BatchNumber,
		SI.Id AS  StockInwardId,
		@rDetail AS Detail,
		@rBuilder1 As Builder1,
		@rBuilder2 AS Builder2,
		SUOM.Title AS UOM,
		SI.IssueToName,
		SI.TransactionDate ,
		SI.Remark --Mantis - 0032620
				
   FROM  sProcurement.tStockIssue SI		
		INNER JOIN sProcurement.tStockIssueDetail ID ON SI.Id = ID.StockIssueId
		INNER JOIN sProcurement.tStockIssueBatch SIB ON ID.Id = SIB.StockIssueDetailId
		INNER JOIN sIp.tStockItemMaster SIM ON ID.StockItemId  = SIM.Id 
		INNER JOIN sIp.tStockItemPlanning SIP ON SIP.StockItemId=SIM.Id AND SIP.StoreLocationId=@rStoreLocationId
	    LEFT JOIN sProcurement.tStockBatch SB ON SB.Id = SIB.StockBatchId
	    --LEFT JOIN sProcurement.tVendorMaster VM ON VM.Id = SI.VendorId
	    INNER JOIN sIp.tItemSubGroupMaster ISGM ON ISGM.Id=SIM.ItemSubGroupId
		INNER JOIN sIp.tItemMainGroupMaster IMGM ON IMGM.Id=ISGM.ItemMainGroupId
		LEFT JOIN sIp.tStockItemCategoryMaster SICM ON SICM.Id=SIM.StockItemCategoryId	
		INNER JOIN sFinanceCommon.tStockUomMaster SUOM ON SUOM.Id = SIM.IssueStockUomId
		 
   WHERE	     
	     SIM.IsObsolete=0
		AND(SB.StoreLocationId= @rStoreLocationId)
		AND (IMGM.Id = @rMainGroupId OR @rMainGroupId=0)
		AND (ISGM.Id = @rSubGroupId OR @rSubGroupId=0)
		AND (SICM.Id = @rStockItemCategoryId OR @rStockItemCategoryId = 0)
		AND (SIM.Code = @rItemCode OR @rItemCode = '')
		AND (SIM.Title = @rItemName OR @rItemName = '')
		AND ((convert(Date,ISNULL(SI.CreatedDateTime,'')) >= @rFromDate) OR (convert(date,ISNULL(@rFromDate,''))=''))
	    AND ((convert(date,ISNULL(SI.CreatedDateTime,'')) <= @rToDate) OR (convert(date,ISNULL(@rToDate,''))=''))
		AND (SI.OrgGroupId = @rOrgGroupId)
		AND ((SI.ToOrganizationDepartmentId = @rToDepartmentId) OR (@rToDepartmentId=0))
		AND ((SI.IssueToName = @rIssuedToName) OR (@rIssuedToName = ''))		
    Order  by SIM.Title	
	
END
GO
PRINT N'Altering Procedure [sProcurement].[pRptStockIssueReturnRegisterGet]...';


GO
ALTER PROCEDURE [sProcurement].[pRptStockIssueReturnRegisterGet]
  @rBuilder1 nvarchar(max)='',
	@rBuilder2 nvarchar(max)='',
	@rReportId int,
	@rStoreLocationId int,
	@rMainGroupId int,
	@rSubGroupId int,
	@rStockItemCategoryId int,
	@rItemCode nvarchar(100),
	@rItemName nvarchar(100),
	@rOrgGroupId int,
	@rFromDate datetime = '',
	@rToDate datetime = '',
	@rDetail bit =0
	
WITH EXECUTE AS CALLER
AS
BEGIN
   SELECT  
				SIM.Code AS ItemCode,
				SIM.Title AS ItemName,		
				SI.ReturnedByName,	
				SI.Number AS Billno, 	
				SI.CreatedDateTime AS IssuedDate,
				SIND.IssuedQuantity,
				 
				 
				 SB.ExpiryDate,
				 SB.ItemRate AS Amount,
				--SB.Number As BatchNumber,
				SI.Id, 
				@rDetail AS Detail,
				@rBuilder1 As Builder1,
				@rBuilder2 AS Builder2,
				SIRB.ReturnQuantity,
				PSI.Remark--mantis - 0032620
				
				
		FROM  sProcurement.tStockIssueReturn SI
		INNER JOIN sProcurement.tStockIssueReturnBatch SIRB ON SIRB.StockIssueReturnId=SI.Id
		INNER JOIN sProcurement.tStockIssueBatch SIB ON SIB.Id=SIRB.StockIssueBatchId
		INNER JOIN sProcurement.tStockIssueDetail SIND ON SIND.Id=SIB.StockIssueDetailId
		INNER JOIN sIp.tStockItemMaster SIM ON SIND.StockItemId  = SIM.Id 
		LEFT JOIN sProcurement.tStockBatch SB ON SB.Id = SIB.StockBatchId
	     
	    INNER JOIN sIp.tItemSubGroupMaster ISGM ON ISGM.Id=SIM.ItemSubGroupId
		INNER JOIN sIp.tItemMainGroupMaster IMGM ON IMGM.Id=ISGM.ItemMainGroupId
		LEFT JOIN sIp.tStockItemCategoryMaster SICM ON SICM.Id=SIM.StockItemCategoryId	
		LEFT Join sProcurement.tStockIssue PSI on PSI.ID = SI.StockIssueId--mantis - 0032620
		 
		  WHERE	     
	     SIM.IsObsolete=0
		--AND(SB.StoreLocationId= @rStoreLocationId)
		AND (IMGM.Id = @rMainGroupId OR @rMainGroupId=0)
		
		AND (ISGM.Id = @rSubGroupId OR @rSubGroupId=0)
		AND (SICM.Id = @rStockItemCategoryId OR @rStockItemCategoryId = 0)
		AND (SIM.Code = @rItemCode OR @rItemCode = '')
		AND (SIM.Title = @rItemName OR @rItemName = '')
		AND ((SI.CreatedDateTime >= @rFromDate) OR (ISNULL(@rFromDate,'') = '')) 
		AND ((SI.CreatedDateTime <= @rToDate) OR (ISNULL(@rToDate,'') = '') )
		AND SI.OrgGroupId=@rOrgGroupId
		AND SB.StoreLocationId =@rStoreLocationId
		----AND (SB.OrgId = @rOrgId)
		 
    Order  by SIM.Title	
END
GO
PRINT N'Altering Procedure [sProcurement].[pStockIssue_Get]...';


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

BEGIN
	  
SELECT		 
		SIDE.Id,
		SIDE.RequestedQuantity,
		SIDE.IssuedQuantity,
		SI.Remark, 
		--SIDE.Remark, -- mantisid - 0032618
		SIM.Code AS StockItemCode,
		SIM.TItle As StockItemName,
		SUMa.Code AS UOM,
		isnull(SB.Number,'') AS Number,
		isnull(SB.ExpiryDate,'') as ExpiryDate , 
		SB.AvailableQuantity,
		SIM.ID AS StockItemID,
		SI.ToOrganizationdepartmentid,
		SI.IssuedByName,
		case when SI.TransactionDate is not null then  SI.TransactionDate  else  SI.CreatedDateTime end as 'TransactionDate',
		SI.CreatedDateTime,
		SI.IssueToName,
		SIReq.Number AS 'reqnumb',
		SIReq.CreatedDateTime as 'ReqDate'

		
			
			
FROM		
		sProcurement.tStockIssueDetail SIDE
		INNER JOIN sProcurement.tStockIssue SI ON SI.ID= SIDE.StockIssueId
		INNER JOIN sIp.tStockItemMaster SIM ON SIM.Id = SIDE.StockItemID
		INNER JOIN  sFinanceCommon.tStockUomMaster SUMa ON SUMa.Id = SIM.IssueStockUomId
		LEFT JOIN sProcurement.tStockIssueBatch SIB ON SIB.StockIssueDetailId= SIDE.Id
		LEFT JOIN	sProcurement.tStockBatch SB ON SB.Id = SIB.StockBatchId
		LEFT JOIN	sProcurement.tStockIssueRequest SIReq ON SIReq.Id = SI.StockIssueRequestId
WHERE		
		SI.ID=@rId
		AND ((SI.Number = @rNumber) OR (ISNULL(@rNumber, '') = ''))
		AND SI.OrgGroupId = @rOrgGroupId
		AND SI.FromStoreLocationId  = @rStoreLocationId
END
GO
PRINT N'Altering Procedure [sProcurement].[pStockIssueAdd_New]...';


GO

ALTER PROCEDURE [sProcurement].[pStockIssueAdd_New]
	(
		@rOrgGroupId [int],
		@rNumber						Nvarchar(20) = '',
		@rStockIssueRequestId			Int=0, 
		@rIssuedByName					Nvarchar(100) = '',
		@rToOrganizationDepartmentId	Int,
		@rFromStoreLocationId			Int,
		@rFirstAidId					Int,
		@rRemark						Nvarchar(300) = '',
		@rCreatedUserId					BigInt,
		@rDetail						Nvarchar(Max),
		@rOrgId int,
		@rLocationId int,
		@rIssuedToName nvarchar(50)='',
		@rIssueDate datetime = null,
		@rCreatedOnDate datetime = null,
		@rIssueToSourceTypeId int = null,
		@rIssueToSourceId BigInt = null
	)
AS

SET NOCOUNT ON

BEGIN
EXECUTE sCommon.pPrefixSetupNextNumberGet @rOrgId = @rOrgGroupId, @rPrefixFunctionalityId = 26,@rStoreLocationId = @rFromStoreLocationId, @rNextNumber  = @rNumber OUTPUT

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

IF @rNumber = '-300'
BEGIN
 
SELECT -300 AS Result, '' AS Number, 0 AS Id 
RETURN
END

	DECLARE @lNextNumberStockIssue INT
	 DECLARE @loXML XML
		SET @loXML = CAST(@rDetail AS XML)
	 DECLARE @tStockIssueDetail TABLE
		(
			Id Int IDENTITY(1,1),StockIssueRequestDetailId int,StockItemId Int,StockItemName nvarchar(50),
			StockItemCode nvarchar(50),IssuedQuantity Decimal(12,2),RequestedQuantity Decimal(12,2),
			ItemBatch Nvarchar(300) NULL,StockBatchId int 
		)

	INSERT INTO @tStockIssueDetail
		SELECT
		(
			CASE WHEN T.c.value('@StockIssueRequestDetailId','Nvarchar(300)') = 0 THEN 
				NULL
			ELSE T.c.value('@StockIssueRequestDetailId','Nvarchar(300)') END
		),
		T.c.value('@StockItemId','int') AS StockItemId,
		T.c.value('@StockItemCode','nvarchar(50)') AS StockItemCode,
		T.c.value('@StockItemName','nvarchar(50)') AS StockItemName,
		T.c.value('@IssuedQuantity','decimal(12,2)') AS IssuedQuantity,
		T.c.value('@RequestedQuantity','decimal(12,2)') AS RequestedQuantity,
		T.c.value('@ItemBatch','Nvarchar(300)') AS ItemBatch,
		T.c.value('@StockBatchId','int') AS StockBatchId
		FROM @loXML.nodes('/Table/StockIssue')T(c)
	 
	 BEGIN TRANSACTION
	 
	EXECUTE [sCommon].[pGetIntMaxIdForOrgGroup] @rOrgGroupId, 'sProcurement.tStockIssue',@lNextNumber = @lNextNumberStockIssue output



if @rFirstAidId < 0 
SET @rFirstAidId =  NULL

	INSERT INTO sProcurement.tStockIssue
		(
			Id,
			Number,
			StockIssueRequestId, 
			IssuedByName,
			ToOrganizationDepartmentId,
			FromStoreLocationId,
			FirstAidId,
			Remark,
			TransactionDate,
			CreatedUserId,
			CreatedDateTime,
			OrgGroupId,
			IssueToSourceTypeId,
			IssueToSourceId,
			IssueToName
		)
	VALUES
		(
			@lNextNumberStockIssue,
			@rNumber,
		   (CASE WHEN @rStockIssueRequestId = 0 THEN NULL ELSE @rStockIssueRequestId END),	 
			@rIssuedByName,
			@rToOrganizationDepartmentId,
			@rFromStoreLocationId,
			@rFirstAidId,
			@rRemark,
			@rIssueDate,
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rOrgGroupId,
			@rIssueToSourceTypeId,
			@rIssueToSourceId,
			@rIssuedToName
		)


	DECLARE @lNextNumberStockIssueDetail BigInt,@lQuantity decimal(12,2),@lStockItemCode nvarchar(50)
		Declare @lCOunt int , @lItemId int,@lIssueQuantity decimal(12,2),@lRequestedQuantity decimal(12,2),
		@lbatchId int,@lIsBatchWise bit,@lBatch nvarchar(300),@lNextNumberStockBatch int,@lNextNumberBatch int,
		@lWeightedAverageCost decimal(12,2),@lInwardValue decimal(12,2),@lStockItemName nvarchar(50),
		@lNextNumberOtherStockBatch bigint
		Select @lCOunt = count(*) from @tStockIssueDetail
		while @lcount>0
		BEGIN
			Select @lItemId = StockItemId , @lIssueQuantity = IssuedQuantity , 
			@lRequestedQuantity=RequestedQuantity,@lCOunt=Id,@lBatch=ItemBatch,
			@lStockItemCode=StockItemCode,@lBatchId=StockBatchId,@lStockItemName=StockItemName
			from @tStockIssueDetail where Id=@lCOunt
			
			Select @lIsBatchWise=IsBatchWiseTracking from sIp.tStockItemMaster Where Id = @lItemId   
			Select @lWeightedAverageCost=ISNULL(WeightedAverageCost,0) from sIp.tStockItemPlanning
			Where StockItemId = @lItemId AND StoreLocationId =  @rFromStoreLocationId  
			
			Select @lQuantity=AvailableQuantity from sProcurement.tStockBatch where Id =@lBatchId
			AND StockItemId = @lItemId ANd StorelocationId=@rFromStoreLocationId
			
			if(ISNULL(@lbatchId,0)=0)
			BEGIN
				ROLLBACK TRANSACTION
				Select -102 As Result,@lStockItemCode AS StockItemCode
				Return
			END 
			IF @lQuantity < @lIssueQuantity 
			BEGIN
				ROLLBACK TRANSACTION
				Select -101 AS Result,@lStockItemCode AS StockItemCode
				return
			END
			IF Exists(Select Id from sProcurement.tStockIssueDetail where StockIssueId = @lNextNumberStockIssue and StockItemId = @lItemId)					
			BEGIN
				Select @lNextNumberStockIssueDetail= Id from sProcurement.tStockIssueDetail
				Where StockIssueId = @lNextNumberStockIssue AND StockIteMid =@lItemId					 
			END	
			ELSE
			BEGIN
				EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sProcurement.tStockIssueDetail', 0, 1, 1,@outNextNumber = @lNextNumberStockIssueDetail output
				-- use remark existing parameter in StockIssue there for in Stockdetail table pass '' string in remark -- in old functionality remark pass as a '' string and div hide from page side mantisid - 0032618
				INSERT INTO sProcurement.tStockIssueDetail
				(
					Id,StockIssueId,StockItemId,IssuedQuantity,RequestedQuantity,
					StockIssueRequestDetailId,Remark,OrgGroupId
				)
				SELECT @lNextNumberStockIssueDetail,@lNextNumberStockIssue,StockItemId,IssuedQuantity,
				RequestedQuantity,StockIssueRequestDetailId,'',@rOrgGroupId
				from @tStockIssueDetail where Id=@lcount	
			END
			EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sProcurement.tStockIssueBatch', 0, 1, 1,@outNextNumber = @lNextNumberBatch output

			INSERT INTO sProcurement.tStockIssueBatch
			(
				Id,StockIssueDetailId,StockBatchId,Quantity,OrgGroupId
			)
		Select @lNextNumberBatch,@lNextNumberStockIssueDetail,@lbatchId,@lIssueQuantity,@rOrgID

		SET @lInwardValue = ISNULL(@lWeightedAverageCost,0) * ISNULL(@lIssueQuantity,0)
		
		Exec sIp.pWeightedAverageCostLogAdd_New @rOrgGroupId =@rOrgGroupId,@rSourceTypeId=51,@rSourceId=@lNextNumberBatch,
			@rItemSourceTypeId = 34,@rItemSourceId=@lItemId,@rQuantity=@lIssueQuantity ,@rValue=@lInwardValue,@rIsReceipt=0,
			@rCreatedUserId = @rCreatedUserId,@rStoreLocationId = @rFromStoreLocationId ,@rLocationId=@rLocationId,
			@rItemBatchId = @lbatchId,@rItemName =@lStockItemName,@rOrgId=@rOrgId
		set @lcount =@lcount-1
		
		END
	 

	--DECLARE @lIntErrorCode INT, @lIntDoc INT
	--EXEC @lIntErrorCode = sp_xml_preparedocument @lIntDoc OUTPUT, @rDetail	
		
	--DECLARE @tStockIssueDetail TABLE
	--(
	--Id						Int IDENTITY(0, 1),
	--StockIssueDetailId		Int, 
	--StockIssueRequestDetailId	Int, 
	--StockIssueId 			Int, 
	--StockItemId				Int, 
	--IssuedQuantity			Decimal(12,2),
	--RequestedQuantity		Decimal(12,2),  
	--Remark					Nvarchar(300)
	--)
	
	--INSERT INTO @tStockIssueDetail  
	--(  
	--	StockIssueId,
	--	StockItemId,
	--	IssuedQuantity,
	--	RequestedQuantity,
	--	StockIssueRequestDetailId, 
	--	Remark
	--)
	--SELECT	@lNextNumberStockIssue, 
	--		StockItemId,
	--		IssuedQuantity,
	--		RequestedQuantity,
	--		(CASE WHEN StockIssueRequestDetailId = 0 THEN NULL ELSE StockIssueRequestDetailId END), 			
	--		Remark
			
	--FROM OPENXML (@lIntDoc, '/Root/StockIssueDetail', 1)  
	--	WITH  
	--	(  
	--		StockItemId				Nvarchar(300)	'@StockItemId', 
	--		IssuedQuantity			Nvarchar(300)	'@IssuedQuantity', 
	--		RequestedQuantity		Nvarchar(300)	'@RequestedQuantity', 
	--		StockIssueRequestDetailId  Nvarchar(300)'@StockIssueRequestDetailId', 
	--		Remark					Nvarchar(300)	'@Remark'
	--	) XmlTable
	
	--DECLARE @lNextNumberStockIssueDetail BigInt
	--EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sProcurement.tStockIssueDetail', 0, 1, 1,@outNextNumber = @lNextNumberStockIssueDetail output
	
	
	--INSERT INTO sProcurement.tStockIssueDetail
	--	(
	--		Id,
	--		StockIssueId,
	--		StockItemId,
	--		IssuedQuantity,
	--		RequestedQuantity,
	--		StockIssueRequestDetailId, 
	--		Remark,
	--		OrgGroupId
	--	)
	--SELECT 	@lNextNumberStockIssueDetail + Id, 
	--		StockIssueId, 
	--		StockItemId, 
	--		IssuedQuantity,
	--		RequestedQuantity, 
	--		StockIssueRequestDetailId, 
	--		Remark,
	--		@rOrgGroupId
	--FROM	@tStockIssueDetail
	
	--UPDATE @tStockIssueDetail SET StockIssueDetailId = @lNextNumberStockIssueDetail + Id 
	--SELECT @lNextNumberStockIssueDetail = MAX(Id) + @lNextNumberStockIssueDetail FROM @tStockIssueDetail
	--EXECUTE sCommon.pTableRowIdModify @rOrgGroupId = @rOrgGroupId, @rTableTitle = 'sProcurement.tStockIssueDetail', @rCurrentNumber = @lNextNumberStockIssueDetail 
	
	--DECLARE @tBatch TABLE
	--(
	--	Id						Int IDENTITY(0, 1), 
	--	StockIssueDetailId	Int,
	--	StockBatchId Int,		
	--	Quantity				Decimal(12,2),
	--	StockItemId				Int				
	--)
	
	--INSERT INTO @tBatch  
	--		(  
	--		StockIssueDetailId,	
	--		StockBatchId, 
	--		Quantity,
	--		StockItemId									
	--		)
	--SELECT	1, 
	--		StockBatchId, 
	--		Quantity,
	--		StockItemId
	--FROM OPENXML (@lIntDoc, '/Root/StockIssueDetail/StockIssueBatch', 1)  
	--	WITH  
	--	(  
	--		StockBatchId 	Nvarchar(200)	'@StockBatchId', 
	--		Quantity					Nvarchar(200)	'@Quantity',
	--		StockItemId					Nvarchar(200)	'@StockItemId' 			
	--	) XmlTable	
		
		
	--DECLARE @lNextNumberBatch BIGINT
	--EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sProcurement.tStockIssueBatch', 0, 1, 1,@outNextNumber = @lNextNumberBatch output
	
	--INSERT INTO sProcurement.tStockIssueBatch
	--	(
	--		Id,
	--		StockIssueDetailId,
	--		StockBatchId,
	--		Quantity,
	--		OrgGroupId
	--	)
	--SELECT 		@lNextNumberBatch + TD.Id, 
	--			STD.StockIssueDetailId, 
	--			StockBatchId, 
	--			Quantity,
	--			@rOrgGroupId
	--FROM		@tStockIssueDetail STD 
	--INNER JOIN	@tBatch TD 
	--			ON TD.StockItemId = STD.StockItemId
				
	--SELECT @lNextNumberBatch = MAX(Id) + @lNextNumberBatch FROM @tBatch
	--EXECUTE sCommon.pTableRowIdModify @rOrgGroupId = @rOrgGroupId, @rTableTitle = 'sProcurement.tStockIssueBatch', @rCurrentNumber = @lNextNumberBatch 
	
	SELECT 1 AS Result, @rNumber AS Number, @lNextNumberStockIssue AS Id 
		COMMIT TRANSACTION
END
GO
PRINT N'Altering Procedure [sProcurement].[pStockIssueStudentAdd_New]...';


GO
ALTER PROCEDURE [sProcurement].[pStockIssueStudentAdd_New]
(
	@rOrgGroupId [int],
	@rNumber						nvarchar(20) = '',
	@rStockIssueRequestId			int=0, 
	@rIssuedByName					nvarchar(100) = '',
	@rToOrganizationDepartmentId	int,
	@rFromStoreLocationId			int,
	@rFirstAidId					int,
	@rCreatedUserId					bigint,
	@rDetail						Nvarchar(Max)='',
	@rOrgId int,
	@rLocationId int,
	@rIssuedToName nvarchar(50)='',
	@rIssueToSourceTypeId int,
	@rIssueToSourceId bigint,
	@rIssueDate datetime = null,
    @rCreatedOnDate datetime = null ,
	@rPayTypeId tinyint=null,
	@rReceiptNumber int=null,
	@rBankName  nvarchar(200)=null,
	@rChequeNo  nvarchar(40)=null,
	@rChequeDate Date=null,
	@rRemark Nvarchar(300) ='' --mantis - 0032618
)
AS

SET NOCOUNT ON

BEGIN
EXECUTE sCommon.pPrefixSetupNextNumberGet @rOrgId = @rOrgGroupId, @rPrefixFunctionalityId = 26,@rStoreLocationId = @rFromStoreLocationId, @rNextNumber  = @rNumber OUTPUT

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

IF @rNumber = '-300'
BEGIN
 
SELECT -300 AS Result, '' AS Number, 0 AS Id 
RETURN
END
 
	  DECLARE @lNextNumberStockIssue INT
	  DECLARE @loXML XML
		SET @loXML = CAST(@rDetail AS XML)
	  DECLARE @tStockIssueDetail TABLE
		(
			Id Int IDENTITY(1,1),StockItemId Int,IssuedQuantity Decimal(12,2)
		)

	  INSERT INTO @tStockIssueDetail
		SELECT
		T.c.value('@StockItemId','int') AS StockItemId,
		T.c.value('@IssuedQuantity','decimal(12,2)') AS IssuedQuantity 
		FROM @loXML.nodes('/Table/StockIssue')T(c)
	 
	 BEGIN TRANSACTION
	 
	EXECUTE [sCommon].[pGetIntMaxIdForOrgGroup] @rOrgGroupId, 'sProcurement.tStockIssue',@lNextNumber = @lNextNumberStockIssue output



If @rFirstAidId < 0 
SET @rFirstAidId =  NULL

	INSERT INTO sProcurement.tStockIssue
		(
			Id,
			Number,
			StockIssueRequestId, 
			IssuedByName,
			ToOrganizationDepartmentId,
			FromStoreLocationId,
			FirstAidId,
			Remark,
			CreatedUserId,
			CreatedDateTime,
			OrgGroupId,
			IssueToName,
			IssueToSourceTypeId,
			IssueToSourceId,
			TransactionDate,
			PayTypeId,
			ReceiptNumber,
			BankName,
			ChequeNo,
			ChequeDate
		)
	VALUES
		(
			@lNextNumberStockIssue,
			@rNumber,
		   (CASE WHEN @rStockIssueRequestId = 0 THEN NULL ELSE @rStockIssueRequestId END),	 
			@rIssuedByName,
			@rToOrganizationDepartmentId,
			@rFromStoreLocationId,
			@rFirstAidId,
			@rRemark,-- replace '' with @rRemark for mantis - 0032618
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rOrgGroupId,
			@rIssuedToName,
			@rIssueToSourceTypeId,
			@rIssueToSourceId,
			@rIssueDate,
			@rPayTypeId,
			@rReceiptNumber,
			@rBankName,
			@rChequeNo,
			@rChequeDate
		)


	DECLARE @lNextNumberStockIssueDetail BigInt,@lQuantity decimal(12,2),@lStockItemCode nvarchar(50)
		Declare @lCOunt int , @lItemId int,@lIssueQuantity decimal(12,2),
		@lbatchId int,@lIsBatchWise bit,@lBatch nvarchar(300),@lNextNumberStockBatch int,@lNextNumberBatch int,
		@lWeightedAverageCost decimal(12,2),@lInwardValue decimal(12,2),@lStockItemName nvarchar(50),
		@lNextNumberOtherStockBatch bigint
		Select @lCOunt = count(*) from @tStockIssueDetail
		
		IF @lcount = 0
		BEGIN
			ROLLBACK TRANSACTION
			Select -211 As Result,@lStockItemCode AS StockItemCode
			Return
		END
		
		while @lcount>0
		BEGIN
			Select @lItemId = StockItemId , @lIssueQuantity = IssuedQuantity ,@lCOunt=Id
			from @tStockIssueDetail where Id=@lCOunt
			
			Select @lWeightedAverageCost=ISNULL(WeightedAverageCost,0) from sIp.tStockItemPlanning
			Where StockItemId = @lItemId AND StoreLocationId =  @rFromStoreLocationId  
			 
			Select @lQuantity=AvailableQuantity,@lbatchId=Id from sProcurement.tStockBatch where  StockItemId = @lItemId ANd StorelocationId=@rFromStoreLocationId
			  
			if(ISNULL(@lbatchId,0)=0)
			BEGIN
				ROLLBACK TRANSACTION
				Select -102 As Result,@lStockItemCode AS StockItemCode
				Return
			END 
			IF @lQuantity = 0 
			BEGIN
				ROLLBACK TRANSACTION
				Select -103 AS Result,@lStockItemCode AS StockItemCode
				return
			END
			IF @lQuantity < @lIssueQuantity 
			BEGIN
				ROLLBACK TRANSACTION
				Select -101 AS Result,@lStockItemCode AS StockItemCode
				return
			END
			
			IF Exists(Select Id from sProcurement.tStockIssueDetail where StockIssueId = @lNextNumberStockIssue and StockItemId = @lItemId)					
			BEGIN
				Select @lNextNumberStockIssueDetail= Id from sProcurement.tStockIssueDetail
				Where StockIssueId = @lNextNumberStockIssue AND StockIteMid =@lItemId					 
			END	
			ELSE
			BEGIN
				EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sProcurement.tStockIssueDetail', 0, 1, 1,@outNextNumber = @lNextNumberStockIssueDetail output

				INSERT INTO sProcurement.tStockIssueDetail
				(
					Id,StockIssueId,StockItemId,IssuedQuantity,RequestedQuantity,
					StockIssueRequestDetailId,Remark,OrgGroupId
				)
				SELECT @lNextNumberStockIssueDetail,@lNextNumberStockIssue,StockItemId,IssuedQuantity,
				0,NULL,'',@rOrgGroupId
				from @tStockIssueDetail where Id=@lcount	
			END
			EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sProcurement.tStockIssueBatch', 0, 1, 1,@outNextNumber = @lNextNumberBatch output

			INSERT INTO sProcurement.tStockIssueBatch
			(
				Id,StockIssueDetailId,StockBatchId,Quantity,OrgGroupId
			)
		Select @lNextNumberBatch,@lNextNumberStockIssueDetail,@lbatchId,@lIssueQuantity,@rOrgID

		SET @lInwardValue = ISNULL(@lWeightedAverageCost,0) * ISNULL(@lIssueQuantity,0)
		
		Exec sIp.pWeightedAverageCostLogAdd_New @rOrgGroupId =@rOrgGroupId,@rSourceTypeId=51,@rSourceId=@lNextNumberBatch,
			@rItemSourceTypeId = 34,@rItemSourceId=@lItemId,@rQuantity=@lIssueQuantity ,@rValue=@lInwardValue,@rIsReceipt=0,
			@rCreatedUserId = @rCreatedUserId,@rStoreLocationId = @rFromStoreLocationId ,@rLocationId=@rLocationId,
			@rItemBatchId = @lbatchId,@rItemName =@lStockItemName,@rOrgId=@rOrgId
		set @lcount =@lcount-1
END
	--DECLARE @lIntErrorCode INT, @lIntDoc INT
	--EXEC @lIntErrorCode = sp_xml_preparedocument @lIntDoc OUTPUT, @rDetail	
		
	--DECLARE @tStockIssueDetail TABLE
	--(
	--Id						Int IDENTITY(0, 1),
	--StockIssueDetailId		Int, 
	--StockIssueRequestDetailId	Int, 
	--StockIssueId 			Int, 
	--StockItemId				Int, 
	--IssuedQuantity			Decimal(12,2),
	--RequestedQuantity		Decimal(12,2),  
	--Remark					Nvarchar(300)
	--)
	
	--INSERT INTO @tStockIssueDetail  
	--(  
	--	StockIssueId,
	--	StockItemId,
	--	IssuedQuantity,
	--	RequestedQuantity,
	--	StockIssueRequestDetailId, 
	--	Remark
	--)
	--SELECT	@lNextNumberStockIssue, 
	--		StockItemId,
	--		IssuedQuantity,
	--		RequestedQuantity,
	--		(CASE WHEN StockIssueRequestDetailId = 0 THEN NULL ELSE StockIssueRequestDetailId END), 			
	--		Remark
			
	--FROM OPENXML (@lIntDoc, '/Root/StockIssueDetail', 1)  
	--	WITH  
	--	(  
	--		StockItemId				Nvarchar(300)	'@StockItemId', 
	--		IssuedQuantity			Nvarchar(300)	'@IssuedQuantity', 
	--		RequestedQuantity		Nvarchar(300)	'@RequestedQuantity', 
	--		StockIssueRequestDetailId  Nvarchar(300)'@StockIssueRequestDetailId', 
	--		Remark					Nvarchar(300)	'@Remark'
	--	) XmlTable
	
	--DECLARE @lNextNumberStockIssueDetail BigInt
	--EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sProcurement.tStockIssueDetail', 0, 1, 1,@outNextNumber = @lNextNumberStockIssueDetail output
	
	
	--INSERT INTO sProcurement.tStockIssueDetail
	--	(
	--		Id,
	--		StockIssueId,
	--		StockItemId,
	--		IssuedQuantity,
	--		RequestedQuantity,
	--		StockIssueRequestDetailId, 
	--		Remark,
	--		OrgGroupId
	--	)
	--SELECT 	@lNextNumberStockIssueDetail + Id, 
	--		StockIssueId, 
	--		StockItemId, 
	--		IssuedQuantity,
	--		RequestedQuantity, 
	--		StockIssueRequestDetailId, 
	--		Remark,
	--		@rOrgGroupId
	--FROM	@tStockIssueDetail
	
	--UPDATE @tStockIssueDetail SET StockIssueDetailId = @lNextNumberStockIssueDetail + Id 
	--SELECT @lNextNumberStockIssueDetail = MAX(Id) + @lNextNumberStockIssueDetail FROM @tStockIssueDetail
	--EXECUTE sCommon.pTableRowIdModify @rOrgGroupId = @rOrgGroupId, @rTableTitle = 'sProcurement.tStockIssueDetail', @rCurrentNumber = @lNextNumberStockIssueDetail 
	
	--DECLARE @tBatch TABLE
	--(
	--	Id						Int IDENTITY(0, 1), 
	--	StockIssueDetailId	Int,
	--	StockBatchId Int,		
	--	Quantity				Decimal(12,2),
	--	StockItemId				Int				
	--)
	
	--INSERT INTO @tBatch  
	--		(  
	--		StockIssueDetailId,	
	--		StockBatchId, 
	--		Quantity,
	--		StockItemId									
	--		)
	--SELECT	1, 
	--		StockBatchId, 
	--		Quantity,
	--		StockItemId
	--FROM OPENXML (@lIntDoc, '/Root/StockIssueDetail/StockIssueBatch', 1)  
	--	WITH  
	--	(  
	--		StockBatchId 	Nvarchar(200)	'@StockBatchId', 
	--		Quantity					Nvarchar(200)	'@Quantity',
	--		StockItemId					Nvarchar(200)	'@StockItemId' 			
	--	) XmlTable	
		
		
	--DECLARE @lNextNumberBatch BIGINT
	--EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sProcurement.tStockIssueBatch', 0, 1, 1,@outNextNumber = @lNextNumberBatch output
	
	--INSERT INTO sProcurement.tStockIssueBatch
	--	(
	--		Id,
	--		StockIssueDetailId,
	--		StockBatchId,
	--		Quantity,
	--		OrgGroupId
	--	)
	--SELECT 		@lNextNumberBatch + TD.Id, 
	--			STD.StockIssueDetailId, 
	--			StockBatchId, 
	--			Quantity,
	--			@rOrgGroupId
	--FROM		@tStockIssueDetail STD 
	--INNER JOIN	@tBatch TD 
	--			ON TD.StockItemId = STD.StockItemId
				
	--SELECT @lNextNumberBatch = MAX(Id) + @lNextNumberBatch FROM @tBatch
	--EXECUTE sCommon.pTableRowIdModify @rOrgGroupId = @rOrgGroupId, @rTableTitle = 'sProcurement.tStockIssueBatch', @rCurrentNumber = @lNextNumberBatch 
	
	SELECT 1 AS Result, @rNumber AS Number, @lNextNumberStockIssue AS Id 
		COMMIT TRANSACTION
END
GO
PRINT N'Altering Procedure [sRecruitment].[pCandidateApplicationEmploymentAdd]...';


GO

ALTER PROCEDURE [sRecruitment].[pCandidateApplicationEmploymentAdd]
	
	@rCandidateApplicationEmployementXml [nvarchar](max),
	@rId bigint,
	@rOrgGroupId smallint,
	@rCandidateId bigint,
	@rCreatedUserId bigint
	
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
--DECLARE @loDoc INT
--EXEC sp_xml_preparedocument @loDoc OUTPUT, @rCandidateApplicationEmployementXml

	DECLARE @lInterrorCode INT,@intDoc INT
	DECLARE @lNextNumber BIGINT			
 
	EXECUTE @lInterrorCode = sp_xml_preparedocument @intDoc OUTPUT, @rCandidateApplicationEmployementXml


		
	BEGIN TRY
	--BEGIN TRANSACTION

	--comment old code because TableRowId not Updated proper in xml form

	--DECLARE @lCount INT
	--DELETE FROM sRecruitment.tCandidatePreviousEmployment WHERE  CandidateId=@rCandidateId
	--DECLARE @lNextNumber BIGINT
	--	EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sRecruitment.tCandidatePreviousEmployment', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	-- INSERT INTO sRecruitment.tCandidatePreviousEmployment
	--	(	
	--			Id,
	--			OrgGroupId,
	--			CandidateId,
	--			CompanyName,
	--			Duration,						 
	--			Designation,
	--			LastSalary,
	--			ReasonForLeaving,				
	--			CreatedUserId,
	--			CreatedDateTime,
	--			UpdatedUserId,
	--			UpdatedDateTime,
	--			JobDescription,
	--			IsCurrentlyWorking,
	--			FromDate,
	--			ToDate
				  
	--		)
	--	SELECT
	--			@lNextNumber + ROW_NUMBER() OVER(ORDER BY CandidateId)AS NewEmploymentId,
	--			@rOrgGroupId,
	--			@rCandidateId,
	--			CompanyName,
	--			Duration,						 
	--			Designation,
	--			LastSalary,
	--			ReasonForLeaving,
	--			@rCreatedUserId,
	--			sCommon.fGetDate(),
	--			@rCreatedUserId,
	--			sCommon.fGetDate(),
	--			JobDescription,
	--			IsCurrentlyWorking,
	--			(CASE WHEN FromDate ='1900-01-01' THEN NULL ELSE CONVERT(Date,FromDate ,103)   END) AS FromDate,
	--			(CASE WHEN ToDate ='1900-01-01' THEN NULL ELSE CONVERT(Date,ToDate ,103) END) AS ToDate
			
	--	FROM OPENXML (@loDoc, '/Table/CandidatePreviousEmployment', 1)
	--	WITH ( 
	--			Id int,	
	--			CandidateId bigint,			
	--			CompanyName nvarchar(100),
	--			Duration nvarchar(50),						 
	--			Designation nvarchar(100),
	--			LastSalary int,
	--			ReasonForLeaving nvarchar(200),
	--			JobDescription nvarchar(200),
	--			IsCurrentlyWorking bit,
	--			FromDate varchar(100),
	--			ToDate varchar(100)
				
	--		  ) 
	--	SELECT @lCount = COUNT(1) FROM OPENXML (@loDoc, '/Table/CandidatePreviousEmployment', 1)
	--			 WITH ( Id int )
	--SET @lNextNumber  = @lCount + @lNextNumber 

	DELETE FROM sRecruitment.tCandidatePreviousEmployment WHERE  CandidateId=@rCandidateId
	CREATE TABLE #tempTable  
	(
		Id bigint identity,
		OrgGroupId smallint ,
		CandidateId bigint ,
		CompanyName nvarchar(100) ,
		Designation nvarchar(100) ,
		Duration nvarchar(50) ,
		--Remark nvarchar(200) ,
		LastSalary int ,
		ReasonForLeaving nvarchar(200) ,
		JobDescription nvarchar(200) ,
		CreatedUserId bigint ,
		CreatedDateTime datetime ,
		UpdatedUserId bigint ,
		UpdatedDateTime datetime ,
		IsCurrentlyWorking bit ,
		FromDate date ,
		ToDate date 
	)
	INSERT INTO #tempTable(
		OrgGroupId  ,
		CandidateId  ,
		CompanyName  ,
		Designation  ,
		Duration ,
		LastSalary ,
		ReasonForLeaving ,
		JobDescription ,
		CreatedUserId ,
		CreatedDateTime ,
		UpdatedUserId ,
		UpdatedDateTime ,
		IsCurrentlyWorking ,
		FromDate ,
		ToDate  
		)
		SELECT
				--@lNextNumber + ROW_NUMBER() OVER(ORDER BY CandidateId)AS NewEmploymentId,
				@rOrgGroupId,
				@rCandidateId,
				CompanyName,
				Designation,
				Duration,						 
				LastSalary,
				ReasonForLeaving,
				JobDescription,
				@rCreatedUserId,
				sCommon.fGetDate(),
				@rCreatedUserId,
				sCommon.fGetDate(),
				IsCurrentlyWorking,
				(CASE WHEN FromDate ='1900-01-01' THEN NULL ELSE CONVERT(Date,FromDate ,103)   END) AS FromDate,
				(CASE WHEN ToDate ='1900-01-01' THEN NULL ELSE CONVERT(Date,ToDate ,103) END) AS ToDate
			
		FROM OPENXML (@intDoc, '/Table/CandidatePreviousEmployment', 1)
		WITH ( 
				--Id int,	
				CandidateId bigint,			
				CompanyName nvarchar(100),
				Designation nvarchar(100),
				Duration nvarchar(50),						 
				LastSalary int,
				ReasonForLeaving nvarchar(200),
				JobDescription nvarchar(200),
				IsCurrentlyWorking bit,
				FromDate varchar(100),
				ToDate varchar(100)
			  )
			  --Select * from #tempTable
	   --SELECT 1 AS Result
	DECLARE @lCount int,@lId int
	SELECT @lCount = COUNT(Id) FROM #tempTable
	SELECT Top 1 @lId=Id FROM #tempTable

	WHILE @lId <= @lCount 
	BEGIN
		EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sRecruitment.tCandidatePreviousEmployment', 0, 1, 1,@outNextNumber = @lNextNumber output

		INSERT INTO sRecruitment.tCandidatePreviousEmployment
		(	
			Id,
			OrgGroupId,
			CandidateId,
			CompanyName,
			Duration,						 
			Designation,
			LastSalary,
			ReasonForLeaving,				
			CreatedUserId,
			CreatedDateTime,
			UpdatedUserId,
			UpdatedDateTime,
			JobDescription,
			IsCurrentlyWorking,
			FromDate,
			ToDate
				  
		)
		Select
		@lNextNumber,
		tmp.OrgGroupId,
		tmp.CandidateId,
		tmp.CompanyName,
		tmp.Duration,
		tmp.Designation,
		tmp.LastSalary,
		tmp.ReasonForLeaving,
		tmp.CreatedUserId,
		tmp.CreatedDateTime,
		tmp.UpdatedUserId,
		tmp.UpdatedDateTime,
		tmp.JobDescription,
		tmp.IsCurrentlyWorking,
		tmp.FromDate,
		tmp.ToDate
		FROM  #tempTable tmp 
		where  Id = @lId

		SET @lId=@lId+1
	END

	EXEC sp_xml_removedocument @intDoc
	SELECT 1 as Result
	DROP Table #tempTable
	END TRY	

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


GO


ALTER PROCEDURE [sRecruitment].[pCandidateApplicationQualificationAdd]
	
	@rCandidateApplicationQualificationXml [nvarchar](max),
   @rId bigint,
	@rOrgGroupId smallint,
	@rCandidateId [bigint],
	@rCreatedUserId [bigint]
	--@rRelationshipId tinyint
	--,
	--@rFeeMainGroupId int,
	--@rFeeHeadId int
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

--DECLARE @loDoc INT
--EXEC sp_xml_preparedocument @loDoc OUTPUT, @rCandidateApplicationQualificationXml
BEGIN
	

	DECLARE @lInterrorCode INT,@intDoc INT
	DECLARE @lNextNumber BIGINT			
 
	EXECUTE @lInterrorCode = sp_xml_preparedocument @intDoc OUTPUT, @rCandidateApplicationQualificationXml
	--comment old code because TableRowId not Updated proper in xml form
	--DECLARE @lCount INT
	--DELETE FROM sRecruitment.tCandidateQualification WHERE CandidateId=@rCandidateId
	--DECLARE @lNextNumber BIGINT
	--	EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sRecruitment.tCandidateQualification', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	-- INSERT INTO sRecruitment.tCandidateQualification
	--	(Id,	
	--		    OrgGroupId,
	--			CandidateId,
	--			ExamPassed,
	--			PassYear,
	--			Percentage,
	--			Grade,
	--			InstituteDetail,
	--			CreatedUserId,
	--			CreatedDateTime,
	--			UpdatedUserId,
	--			UpdatedDateTime,				
	--			BoardDetail,
	--			Subjects,
	--			Medium
				
				
	--			--BoardDetail,
	--			--Subjects,
	--			--Remark,
				
	--			--CreatedDateTime,
	--			--UpdatedUserId,
	--			--UpdatedDateTime
	--		)
	--	SELECT
	--	@lNextNumber + ROW_NUMBER() OVER(ORDER BY CandidateId)AS NewQualificationId,
	--			@rOrgGroupId,
	--			@rCandidateId,
	--			ExamPassed,
	--			PassYear,
	--			Percentage,
	--			Grade,
	--			InstituteDetail,
	--			@rCreatedUserId,
	--			sCommon.fGetDate(),
	--			@rCreatedUserId,
	--			sCommon.fGetDate(),
	--			BoardDetail,
	--			Subjects,
	--			Medium
	--	FROM OPENXML (@loDoc, '/Table/CandidateQualification', 1)
	--	WITH ( 
	--		Id int,	
	
	--CandidateId bigint,
	--ExamPassed nvarchar(100),
	--PassYear nvarchar(20),
	--Percentage decimal(8,2),
	--Grade nvarchar(50),
	--InstituteDetail nvarchar(200),
	--BoardDetail nvarchar(200),
	--			Subjects nvarchar(200),
	--			Medium nvarchar(100)
				
	--		  ) 
	--	SELECT @lCount = COUNT(1) FROM OPENXML (@loDoc, '/Table/CandidateQualification', 1)
	--			 WITH ( Id int )
	--SET @lNextNumber  = @lCount + @lNextNumber 
	--   SELECT 1 AS Result

	BEGIN TRY

	DELETE FROM sRecruitment.tCandidateQualification WHERE CandidateId=@rCandidateId

	CREATE TABLE #tempTable  
	(
		Id bigint identity,
		OrgGroupId smallint,
		CandidateId bigint,
		ExamPassed nvarchar(100),
		PassYear nvarchar(20),
		Percentage decimal(8, 2),
		Grade nvarchar(50),
		InstituteDetail nvarchar(200),
		BoardDetail nvarchar(200),
		Subjects nvarchar(200),
		--Remark nvarchar(100),
		CreatedUserId bigint,
		CreatedDateTime datetime,
		UpdatedUserId bigint,
		UpdatedDateTime datetime,
		Medium nvarchar(100)
	)
	INSERT INTO #tempTable
	(
		--Id,	
		OrgGroupId,
		CandidateId,
		ExamPassed,
		PassYear,
		Percentage,
		Grade,
		InstituteDetail,
		BoardDetail,
		Subjects,
		CreatedUserId,
		CreatedDateTime,
		UpdatedUserId,
		UpdatedDateTime,				
		Medium
	)
	SELECT
		--@lNextNumber + ROW_NUMBER() OVER(ORDER BY CandidateId)AS NewQualificationId,
		@rOrgGroupId,
		@rCandidateId,
		ExamPassed,
		PassYear,
		Percentage,
		Grade,
		InstituteDetail,
		BoardDetail,
		Subjects,
		@rCreatedUserId,
		sCommon.fGetDate(),
		@rCreatedUserId,
		sCommon.fGetDate(),
		Medium
	FROM OPENXML (@intDoc, '/Table/CandidateQualification', 1)
	WITH ( 
			--CandidateId bigint,
			ExamPassed nvarchar(100),
			PassYear nvarchar(20),
			Percentage decimal(8,2),
			Grade nvarchar(50),
			InstituteDetail nvarchar(200),
			BoardDetail nvarchar(200),
			Subjects nvarchar(200),
			Medium nvarchar(100)
			) 
	DECLARE @lCount int,@lId int
	SELECT @lCount = COUNT(Id) FROM #tempTable
	SELECT Top 1 @lId=Id FROM #tempTable

	WHILE @lId <= @lCount 
	BEGIN
			EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sRecruitment.tCandidateQualification', 0, 1, 1,@outNextNumber = @lNextNumber output

			INSERT INTO sRecruitment.tCandidateQualification
			(
				Id,	
				OrgGroupId,
				CandidateId,
				ExamPassed,
				PassYear,
				Percentage,
				Grade,
				InstituteDetail,
				CreatedUserId,
				CreatedDateTime,
				UpdatedUserId,
				UpdatedDateTime,				
				BoardDetail,
				Subjects,
				Medium
			)
			Select
				@lNextNumber,
				tmp.OrgGroupId,
				tmp.CandidateId,
				tmp.ExamPassed,
				tmp.PassYear,
				tmp.Percentage,
				tmp.Grade,
				tmp.InstituteDetail,
				tmp.CreatedUserId,
				tmp.CreatedDateTime,
				tmp.UpdatedUserId,
				tmp.UpdatedDateTime,				
				tmp.BoardDetail,
				tmp.Subjects,
				tmp.Medium
				FROM  #tempTable tmp 
				where  Id = @lId

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

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


GO

ALTER PROCEDURE [sRecruitment].[pCandidatePreviousEmploymentAdd]
	
	@rId bigint,
	@rOrgGroupId smallint,
	@rCandidateId [bigint],
	@rCompanyName [nvarchar](300),	
	@rDesignation nvarchar(100), 
	@rDuration [nvarchar](300),
	@rRemark nvarchar(200),
	@rLastSalary int,
	@rReasonForLeaving nvarchar(100),
	@rJobDescription nvarchar(100),
	--@rIsInternal bit,
	@rCreatedUserId [bigint],
	@rIsCurrentlyWorking bit,
	@rFromDate Date ='',
	@rToDate Date = ''
 
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
	BEGIN TRANSACTION
	
 IF NOT EXISTS(SELECT 1 FROM sRecruitment.tCandidatePreviousEmployment WHERE Id = @rId AND CandidateId = @rCandidateId AND OrgGroupId = @rOrgGroupId)
		
		BEGIN		
		DECLARE @lNextNumber BIGINT
		EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sRecruitment.tCandidatePreviousEmployment', 0, 1, 1,@outNextNumber = @lNextNumber output

		INSERT INTO sRecruitment.tCandidatePreviousEmployment
			(
				Id,
				CandidateId,
				CompanyName,						 
				Designation,
				Remark,
				Duration,
				CreatedUserId,
				CreatedDateTime,
				UpdatedUserId,
				UpdatedDateTime,
				OrgGroupId,
			    LastSalary,
			    ReasonForLeaving,
			    JobDescription,
				IsCurrentlyWorking,
				FromDate,
				ToDate
			 
			)
		VALUES
			(
				@lNextNumber,
				@rCandidateId,
				@rCompanyName, 			
				@rDesignation,
				@rRemark,
				@rDuration,
				@rCreatedUserId,
				sCommon.fGetDate(),
				@rCreatedUserId,
				sCommon.fGetDate(),
				@rOrgGroupId,
				@rLastSalary,
			    @rReasonForLeaving,
			    @rJobDescription,
				@rIsCurrentlyWorking,
				@rFromDate,
				@rToDate
			    
			)
		END
  ELSE
    BEGIN
       SET @lNextNumber = @rId
      UPDATE sRecruitment.tCandidatePreviousEmployment
		SET 			
			CompanyName = @rCompanyName,				
			Designation = @rDesignation,
			Remark = @rRemark,		 
			Duration = @rDuration,		 
			UpdatedUserId = @rCreatedUserId,
			UpdatedDateTime = sCommon.fGetDate(),
			LastSalary = @rLastSalary,
			ReasonForLeaving = @rReasonForLeaving,
			JobDescription = @rJobDescription,
			IsCurrentlyWorking=@rIsCurrentlyWorking,
			FromDate = @rFromDate,
			ToDate = @rToDate
			
	  WHERE 
			Id = @rId 
		AND CandidateId = @rCandidateId
    END		
		SELECT @lNextNumber AS Result
	COMMIT TRANSACTION
	END TRY
	BEGIN CATCH
	ROLLBACK TRANSACTION
	SELECT -1 AS RESULT
	--Select ERROR_Message()
	END CATCH	
END
GO
PRINT N'Altering Procedure [sSecurity].[pForgotPasswordFailureLogUpdate]...';


GO
ALTER PROCEDURE [sSecurity].[pForgotPasswordFailureLogUpdate]   
	@rFailureLogIds nvarchar(max)='',
	@rIsAlert bit,
	@rCode nvarchar(100)='',
	@rUserId bigint =0

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	IF(@rIsAlert = 1)
	BEGIN
		Update sSecurity.tForgotPasswordFailureLog SET IsSendAlert = 1 
		WHERE AutoId IN (SELECT cast(item AS NVARCHAR(MAX)) FROM  sCommon.fnsplit(@rFailureLogIds,','))
	END

	ELSE 
	BEGIN
		DECLARE @lUserId bigint 
		SELECT @lUserId = Id from  sSecurity.tUser where isnull(TempPasswordCode,'') = @rCode
		IF(@lUserId IS NULL OR @lUserId = 0)
			SET @lUserId = @rUserId
		Update sSecurity.tForgotPasswordFailureLog SET IsResetPassword = 1, IsSendAlert = 1 
		WHERE UserId  = @lUserId
	END
END
GO
PRINT N'Altering Procedure [sSecurity].[pMobValidateUser]...';


GO
ALTER PROCEDURE [sSecurity].[pMobValidateUser]

    @rOrgId int = 0,
    @rUserTitle nvarchar(100)='',
    @rUserMobileNumber nvarchar(50)=''
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
		DECLARE @rUserSourceId bigint=0
		DECLARE @rUserId bigint=0
		DECLARE @rUserSourceTypeId smallint=0
		DECLARE @newpwd VARCHAR(100)
		SELECT @rUserId=Id,@rUserSourceId = SourceId,@rUserSourceTypeId=SourceTypeId FROM sSecurity.tUser WHERE UPPER(LoginTitle) = UPPER(@rUserTitle) AND OrgId = @rOrgId
		IF(@rUserId = 0 AND @rUserSourceTypeId=0)
		BEGIN
			SELECT -11 AS Result, 'User does not exist' AS [Message], '' AS OTP
			Return
		END
		IF(@rUserSourceTypeId = 95)
		BEGIN
			IF EXISTS (SELECT 1 FROM sHrm.tEmployeeCommunications WHERE MobileNumber = @rUserMobileNumber and EmployeeId = @rUserSourceId)
			BEGIN
				IF EXISTS (SELECT 1 FROM sSecurity.tUser WHERE Id = @rUserId AND OrgId = @rOrgId)
				BEGIN				
					EXEC [sSecurity].[pNumericOTPGenerate] @len=6, @min=48, @range=9, @exclude='', @output=@newpwd OUT
					UPDATE sSecurity.tUser
					SET	TempPasswordCode=@newpwd,CreatedDateTime=sCommon.fGetDate(),OTPExpiryDate=DATEADD(SECOND,120,GETDATE())				
					WHERE Id = @rUserId AND OrgId = @rOrgId

					SELECT 1 AS Result,'' AS [Message],TempPasswordCode AS OTP FROM sSecurity.tUser WHERE Id = @rUserId AND OrgId = @rOrgId					
				END
				ELSE
				BEGIN
					SELECT -101 AS Result,'User does not exist' AS [Message],'' AS OTP
				END
			END
			ELSE
			BEGIN
				SELECT -102 AS Result,'Mobile number is wrong' AS [Message],'' AS OTP
			END	
		END
		IF(@rUserSourceTypeId = 2003)
		BEGIN
			IF EXISTS (SELECT 1 FROM sStudent.tStudentCommunication WHERE ParentContactNo = @rUserMobileNumber and StudentId = @rUserSourceId)
			BEGIN
				IF EXISTS (SELECT 1 FROM sSecurity.tUser WHERE Id = @rUserId AND OrgId = @rOrgId)
				BEGIN				
					EXEC [sSecurity].[pNumericOTPGenerate] @len=6, @min=48, @range=9, @exclude='', @output=@newpwd OUT
					UPDATE sSecurity.tUser
					SET	TempPasswordCode=@newpwd,CreatedDateTime=sCommon.fGetDate(),OTPExpiryDate=DATEADD(SECOND,120,GETDATE())				
					WHERE Id = @rUserId AND OrgId = @rOrgId
					SELECT 1 AS Result,'' AS [Message],TempPasswordCode AS OTP FROM sSecurity.tUser WHERE Id = @rUserId  AND OrgId = @rOrgId					
				END
				ELSE
				BEGIN
					SELECT -101 AS Result,'User does not exist' AS [Message],'' AS OTP
				END
			END
			ELSE
			BEGIN
				SELECT -102 AS Result,'Mobile number is wrong' AS [Message],'' AS OTP
			END		
		END
END
GO
PRINT N'Altering Procedure [sSetup].[pBulkMasterDataUpdateGet]...';


GO
ALTER PROCEDURE [sSetup].[pBulkMasterDataUpdateGet]
	 
	 @rCategoryId int,
	 @rSubCategory nvarchar(100),
	 @rOrgId int,
	 @rOrgGroupId int,
	 @rIsBlank int=0

AS
SET NOCOUNT ON

BEGIN
		DECLARE @lDataTypeId nvarchar(1)
		SELECT @lDataTypeId=DataTypeId FROM sCommon.tUpdateFieldMaster WHERE Field=@rSubCategory --and Id=@rCategoryId
		
		IF(@rSubCategory = 'InchargeEmployee')
		BEGIN
			SET @rSubCategory = Replace(@rSubCategory ,'InchargeEmployee','InchargeEmployeeId')			
		END 
		
		IF(@rSubCategory = 'DisplayTitle' AND @rCategoryId=9)
		BEGIN
		SET @rSubCategory = Replace(@rSubCategory ,'DisplayTitle','ExamSubGroupDisplayTitle	')
		END
		
		 Declare @Sql nvarchar(max)
		
		 SET @Sql =  CASE @rCategoryId	
		 				  
					 WHEN 1 THEN -- Organization
						'Select OM.Id,OM.Code,OM.Title,
						CASE WHEN '+@lDataTypeId+'=1 THEN
						ISNULL(OM.'+@rSubCategory+','''') 
						WHEN '+@lDataTypeId+'=2 THEN
						ISNULL(OM.'+@rSubCategory+',''0'')
						WHEN '+@lDataTypeId+'=3 THEN
						ISNULL(OM.'+@rSubCategory+',''False'') 
						WHEN '+@lDataTypeId+'=4 THEN
						ISNULL(OM.'+@rSubCategory+',''0001/01/01'') 
						WHEN '+@lDataTypeId+'=5 THEN
						ISNULL(OM.'+@rSubCategory+',''0'') 
						--END AS OrderIndex
						END AS SubCategory
							FROM 
							sSetup.tOrganizationMaster OM where OM.OrgGroupId='+CAST(@rOrgGroupId AS nvarchar(15))+'							
							 AND 
							('+CAST(@rIsBlank AS nvarchar(1))+'=0 
								OR ('+@lDataTypeId+'=1 AND ISNULL(OM.'+@rSubCategory+','''')='''')
								OR ('+@lDataTypeId+'=2 AND ISNULL(OM.'+@rSubCategory+',''0'')=''0'')
								OR ('+@lDataTypeId+'=3 AND ISNULL(OM.'+@rSubCategory+',''False'')=''False'')
								OR ('+@lDataTypeId+'=4 AND ISNULL(OM.'+@rSubCategory+',''0001/01/01'')=''0001/01/01'') 
							) order by SubCategory
							 '
							
					 WHEN 2 THEN -- Class
						'Select CM.Id,CM.Code,CM.Title,
						CASE WHEN '+@lDataTypeId+'=1 THEN
						ISNULL(CM.'+@rSubCategory+','''')
						WHEN '+@lDataTypeId+'=2 THEN
						ISNULL(CM.'+@rSubCategory+',''0'')
						WHEN '+@lDataTypeId+'=3 THEN
						ISNULL(CM.'+@rSubCategory+',''False'')
						WHEN '+@lDataTypeId+'=4 THEN
						CM.'+@rSubCategory+'
						WHEN '+@lDataTypeId+'=5 THEN
						ISNULL(CM.'+@rSubCategory+',''0'')
						--END AS OrderIndex
						END AS SubCategory
							FROM 
							sSetup.tClassMaster CM where CM.OrgId='+CAST(@rOrgId AS nvarchar(15))+'	 						
							AND 
							('+CAST(@rIsBlank AS nvarchar(1))+'=0 
								OR ('+@lDataTypeId+'=1 AND ISNULL(CM.'+@rSubCategory+','''')='''')
								OR ('+@lDataTypeId+'=2 AND ISNULL(CM.'+@rSubCategory+',''0'')=''0'')
								OR ('+@lDataTypeId+'=3 AND ISNULL(CM.'+@rSubCategory+',''False'')=''False'')
								OR ('+@lDataTypeId+'=4 AND ISNULL(CM.'+@rSubCategory+',''0001/01/01'')=''0001/01/01'') 
							) order by SubCategory
							 '
							
					WHEN 3 THEN -- Division
						'Select DM.Id,DM.Code,DM.Title,
						CASE WHEN '+@lDataTypeId+'=1 THEN
						ISNULL(DM.'+@rSubCategory+','''')
						WHEN '+@lDataTypeId+'=2 THEN
						ISNULL(DM.'+@rSubCategory+',''0'')
						WHEN '+@lDataTypeId+'=3 THEN
						ISNULL(DM.'+@rSubCategory+',''False'')
						WHEN '+@lDataTypeId+'=4 THEN
						ISNULL(DM.'+@rSubCategory+',''0001/01/01'')
						WHEN '+@lDataTypeId+'=5 THEN
						ISNULL(DM.'+@rSubCategory+',''0'')
						--END AS OrderIndex 
						END AS SubCategory
							FROM 
							sSetup.tDivisionMaster DM where DM.OrgId='+CAST(@rOrgId AS nvarchar(15))+'							
							AND 
							('+CAST(@rIsBlank AS nvarchar(1))+'=0 
								OR ('+@lDataTypeId+'=1 AND ISNULL(DM.'+@rSubCategory+','''')='''')
								OR ('+@lDataTypeId+'=2 AND ISNULL(DM.'+@rSubCategory+',''0'')=''0'')
								OR ('+@lDataTypeId+'=3 AND ISNULL(DM.'+@rSubCategory+',''False'')=''False'')
								OR ('+@lDataTypeId+'=4 AND ISNULL(DM.'+@rSubCategory+',''0001/01/01'')=''0001/01/01'') 
							) order by SubCategory
							 '
					 
					WHEN 4 THEN --SubjectMaster
					   'Select SM.Id,SM.Code,SM.Title,
						CASE WHEN '+@lDataTypeId+'=1 THEN
						ISNULL(SM.'+@rSubCategory+','''')
						WHEN '+@lDataTypeId+'=2 THEN
						ISNULL(SM.'+@rSubCategory+',''0'')
						WHEN '+@lDataTypeId+'=3 THEN
						ISNULL(SM.'+@rSubCategory+',''False'')
						WHEN '+@lDataTypeId+'=4 THEN
						ISNULL(SM.'+@rSubCategory+',''0001/01/01'')
						WHEN '+@lDataTypeId+'=5 THEN
						ISNULL(SM.'+@rSubCategory+',''0'')
						--END AS OrderIndex
						END AS SubCategory
							FROM 
							sSetup.tSubjectMaster SM where SM.OrgId='+CAST(@rOrgId AS nvarchar(15))+'
							AND 
							('+CAST(@rIsBlank AS nvarchar(1))+'=0 
								OR ('+@lDataTypeId+'=1 AND ISNULL(SM.'+@rSubCategory+','''')='''')
								OR ('+@lDataTypeId+'=2 AND ISNULL(SM.'+@rSubCategory+',''0'')=''0'')
								OR ('+@lDataTypeId+'=3 AND ISNULL(SM.'+@rSubCategory+',''False'')=''False'')
								OR ('+@lDataTypeId+'=4 AND ISNULL(SM.'+@rSubCategory+',''0001/01/01'')=''0001/01/01'') 
							) order by SubCategory
							 '
				   
					WHEN 5 THEN --tOrgGroupBatchMaster
					   'Select OGM.Id,OGM.Code,OGM.Title,
						CASE WHEN '+@lDataTypeId+'=1 THEN
						ISNULL(OGM.'+@rSubCategory+','''')
						WHEN '+@lDataTypeId+'=2 THEN
						ISNULL(OGM.'+@rSubCategory+',''0'')
						WHEN '+@lDataTypeId+'=3 THEN
						ISNULL(OGM.'+@rSubCategory+',''False'')
						WHEN '+@lDataTypeId+'=4 THEN
						ISNULL(OGM.'+@rSubCategory+',''0001/01/01'')
						WHEN '+@lDataTypeId+'=5 THEN
						ISNULL(OGM.'+@rSubCategory+',''0'')
						--END AS OrderIndex
						END AS SubCategory
							FROM 
							sSetup.tOrgGroupBatchMaster OGM	where OGM.OrgGroupId='+CAST(@rOrgGroupId AS nvarchar(15))+'						
							AND 
							('+CAST(@rIsBlank AS nvarchar(1))+'=0 
								OR ('+@lDataTypeId+'=1 AND ISNULL(OGM.'+@rSubCategory+','''')='''')
								OR ('+@lDataTypeId+'=2 AND ISNULL(OGM.'+@rSubCategory+',''0'')=''0'')
								OR ('+@lDataTypeId+'=3 AND ISNULL(OGM.'+@rSubCategory+',''False'')=''False'')
								OR ('+@lDataTypeId+'=4 AND ISNULL(OGM.'+@rSubCategory+',''0001/01/01'')=''0001/01/01'') 
							) order by SubCategory
							 '
					WHEN 6 THEN --BatchMaster
					   'Select BM.Id,BM.Code,BM.Title,
						CASE WHEN '+@lDataTypeId+'=1 THEN
						ISNULL(BM.'+@rSubCategory+','''')
						WHEN '+@lDataTypeId+'=2 THEN
						ISNULL(BM.'+@rSubCategory+',''0'')						
						WHEN '+@lDataTypeId+'=3 THEN
						ISNULL(BM.'+@rSubCategory+',''False'')
						WHEN '+@lDataTypeId+'=4 THEN
						ISNULL(BM.'+@rSubCategory+',''0001/01/01'')	
						WHEN '+@lDataTypeId+'=5 AND ''' + @rSubCategory + '''=''RepeatCount'' THEN
						ISNULL(BM.'+@rSubCategory+',''1'')
						WHEN '+@lDataTypeId+'=5 AND ''' + @rSubCategory + '''<>''RepeatCount'' THEN
						ISNULL(BM.'+@rSubCategory+',''0'')
						--END AS OrderIndex
						END AS SubCategory
							FROM 
							sSetup.tBatchMaster BM where BM.OrgId='+CAST(@rOrgId AS nvarchar(15))+'
							AND 
							('+CAST(@rIsBlank AS nvarchar(1))+'=0 
								OR ('+@lDataTypeId+'=1 AND ISNULL(BM.'+@rSubCategory+','''')='''')
								OR ('+@lDataTypeId+'=2 AND ISNULL(BM.'+@rSubCategory+',''0'')=''0'')
								OR ('+@lDataTypeId+'=3 AND ISNULL(BM.'+@rSubCategory+',''False'')=''False'')
								OR ('+@lDataTypeId+'=4 AND ISNULL(BM.'+@rSubCategory+',''0001/01/01'')=''0001/01/01'') 
							) order by SubCategory
							 '
							
					WHEN 7 THEN --DepartmentMaster
					   'Select DM.Id,DM.Code,DM.Title,
						CASE WHEN '+@lDataTypeId+'=1 THEN
						ISNULL(DM.'+@rSubCategory+','''')
						WHEN '+@lDataTypeId+'=2 THEN
						ISNULL(DM.'+@rSubCategory+',''0'')						
						WHEN '+@lDataTypeId+'=3 THEN
						ISNULL(DM.'+@rSubCategory+',''False'')
						WHEN '+@lDataTypeId+'=4 THEN
						ISNULL(DM.'+@rSubCategory+',''0001/01/01'')	
						WHEN '+@lDataTypeId+'=5 AND ''' + @rSubCategory + '''=''RepeatCount'' THEN
						ISNULL(DM.'+@rSubCategory+',''1'')
						WHEN '+@lDataTypeId+'=5 AND ''' + @rSubCategory + '''<>''RepeatCount'' THEN
						ISNULL(DM.'+@rSubCategory+',''0'')
						--END AS OrderIndex
						END AS SubCategory
							FROM 
							sSetup.tDepartmentMaster DM where DM.OrgId='+CAST(@rOrgId AS nvarchar(15))+'
							AND 
							('+CAST(@rIsBlank AS nvarchar(1))+'=0 
								OR ('+@lDataTypeId+'=1 AND ISNULL(DM.'+@rSubCategory+','''')='''')
								OR ('+@lDataTypeId+'=2 AND ISNULL(DM.'+@rSubCategory+',''0'')=''0'')
								OR ('+@lDataTypeId+'=3 AND ISNULL(DM.'+@rSubCategory+',''False'')=''False'')
								OR ('+@lDataTypeId+'=4 AND ISNULL(DM.'+@rSubCategory+',''0001/01/01'')=''0001/01/01'') 
							) order by SubCategory
							 '
							
					WHEN 8 THEN --OrgGroupDepartmentMaster
					   'Select GDM.Id,GDM.Code,GDM.Title,
						CASE WHEN '+@lDataTypeId+'=1 THEN
						ISNULL(GDM.'+@rSubCategory+','''')
						WHEN '+@lDataTypeId+'=2 THEN
						ISNULL(GDM.'+@rSubCategory+',''0'')						
						WHEN '+@lDataTypeId+'=3 THEN
						ISNULL(GDM.'+@rSubCategory+',''False'')
						WHEN '+@lDataTypeId+'=4 THEN
						ISNULL(GDM.'+@rSubCategory+',''0001/01/01'')	
						WHEN '+@lDataTypeId+'=5 AND ''' + @rSubCategory + '''=''RepeatCount'' THEN
						ISNULL(GDM.'+@rSubCategory+',''1'')
						WHEN '+@lDataTypeId+'=5 AND ''' + @rSubCategory + '''<>''RepeatCount'' THEN
						ISNULL(GDM.'+@rSubCategory+',''0'')
						--END AS OrderIndex
						END AS SubCategory
							FROM 
							sCommon.tOrgGroupDepartmentMaster GDM where GDM.OrgGroupId='+CAST(@rOrgGroupId AS nvarchar(15))+'
							AND 
							('+CAST(@rIsBlank AS nvarchar(1))+'=0 
								OR ('+@lDataTypeId+'=1 AND ISNULL(GDM.'+@rSubCategory+','''')='''')
								OR ('+@lDataTypeId+'=2 AND ISNULL(GDM.'+@rSubCategory+',''0'')=''0'')
								OR ('+@lDataTypeId+'=3 AND ISNULL(GDM.'+@rSubCategory+',''False'')=''False'')
								OR ('+@lDataTypeId+'=4 AND ISNULL(GDM.'+@rSubCategory+',''0001/01/01'')=''0001/01/01'') 
							) order by SubCategory
							 '
						WHEN 9 THEN --ExamSubGroup
					   'Select ESGM.Id,ESGM.Code,ESGM.Title,ESGM.ExamSubGroupDisplayTitle AS Title,
						CASE WHEN '+@lDataTypeId+'=1 THEN
						ISNULL(ESGM.'+@rSubCategory+','''')
						WHEN '+@lDataTypeId+'=2 THEN
						ISNULL(ESGM.'+@rSubCategory+',''0'')						
						WHEN '+@lDataTypeId+'=3 THEN
						ISNULL(ESGM.'+@rSubCategory+',''False'')
						WHEN '+@lDataTypeId+'=4 THEN
						ISNULL(ESGM.'+@rSubCategory+',''0001/01/01'')	
						WHEN '+@lDataTypeId+'=5 AND ''' + @rSubCategory + '''=''RepeatCount'' THEN
						ISNULL(ESGM.'+@rSubCategory+',''1'')
						WHEN '+@lDataTypeId+'=5 AND ''' + @rSubCategory + '''<>''RepeatCount'' THEN
						ISNULL(ESGM.'+@rSubCategory+',''0'')
						--END AS OrderIndex
						END AS SubCategory
							FROM 
							sAssessment.tExamSubGroupMaster ESGM where ESGM.OrgId='+CAST(@rOrgId AS nvarchar(15))+'
							AND 
							('+CAST(@rIsBlank AS nvarchar(1))+'=0 
								OR ('+@lDataTypeId+'=1 AND ISNULL(ESGM.'+@rSubCategory+','''')='''')
								OR ('+@lDataTypeId+'=2 AND ISNULL(ESGM.'+@rSubCategory+',''0'')=''0'')
								OR ('+@lDataTypeId+'=3 AND ISNULL(ESGM.'+@rSubCategory+',''False'')=''False'')
								OR ('+@lDataTypeId+'=4 AND ISNULL(ESGM.'+@rSubCategory+',''0001/01/01'')=''0001/01/01'') 
							) order by SubCategory
							 '
							WHEN 10 THEN --ReligionMaster
					   'Select GDM.Id,GDM.Code,GDM.Title,
						CASE WHEN '+@lDataTypeId+'=1 THEN
						ISNULL(GDM.'+@rSubCategory+','''')
						WHEN '+@lDataTypeId+'=2 THEN
						ISNULL(GDM.'+@rSubCategory+',''0'')						
						WHEN '+@lDataTypeId+'=3 THEN
						ISNULL(GDM.'+@rSubCategory+',''False'')
						WHEN '+@lDataTypeId+'=4 THEN
						ISNULL(GDM.'+@rSubCategory+',''0001/01/01'')	
						WHEN '+@lDataTypeId+'=5 AND ''' + @rSubCategory + '''=''RepeatCount'' THEN
						ISNULL(GDM.'+@rSubCategory+',''1'')
						WHEN '+@lDataTypeId+'=5 AND ''' + @rSubCategory + '''<>''RepeatCount'' THEN
						ISNULL(GDM.'+@rSubCategory+',''0'')
						--END AS OrderIndex
						END AS SubCategory
							FROM 
							sCommon.tReligionMaster GDM where GDM.OrgGroupId='+CAST(@rOrgGroupId AS nvarchar(15))+'
							AND 
							('+CAST(@rIsBlank AS nvarchar(1))+'=0 
								OR ('+@lDataTypeId+'=1 AND ISNULL(GDM.'+@rSubCategory+','''')='''')
								OR ('+@lDataTypeId+'=2 AND ISNULL(GDM.'+@rSubCategory+',''0'')=''0'')
								OR ('+@lDataTypeId+'=3 AND ISNULL(GDM.'+@rSubCategory+',''False'')=''False'')
								OR ('+@lDataTypeId+'=4 AND ISNULL(GDM.'+@rSubCategory+',''0001/01/01'')=''0001/01/01'') 
							) order by SubCategory'

					WHEN 11 THEN --Topic
					   'Select TM.Id,TM.Title AS Code,TM.Title,
						CASE WHEN '+@lDataTypeId+'=1 THEN
						ISNULL(TM.'+@rSubCategory+','''')
						WHEN '+@lDataTypeId+'=2 THEN
						ISNULL(TM.'+@rSubCategory+',''0'')						
						WHEN '+@lDataTypeId+'=3 THEN
						ISNULL(TM.'+@rSubCategory+',''False'')
						WHEN '+@lDataTypeId+'=4 THEN
						ISNULL(TM.'+@rSubCategory+',''0001/01/01'')	
						WHEN '+@lDataTypeId+'=5 THEN
						ISNULL(TM.'+@rSubCategory+',''0'')
						END AS SubCategory
							FROM 
							sAcademic.tTopicMaster TM where TM.OrgId='+CAST(@rOrgId AS nvarchar(15))+'
							AND 
							('+CAST(@rIsBlank AS nvarchar(1))+'=0 
								OR ('+@lDataTypeId+'=1 AND ISNULL(TM.'+@rSubCategory+','''')='''')
								OR ('+@lDataTypeId+'=2 AND ISNULL(TM.'+@rSubCategory+',''0'')=''0'')
								OR ('+@lDataTypeId+'=3 AND ISNULL(TM.'+@rSubCategory+',''False'')=''False'')
								OR ('+@lDataTypeId+'=4 AND ISNULL(TM.'+@rSubCategory+',''0001/01/01'')=''0001/01/01'') 
							) order by SubCategory'
							 
					END		
					
					
			
	
			EXECUTE  sp_executesql @Sql
			Print @Sql
	   
END
GO
PRINT N'Altering Procedure [sSetup].[pMastedDataModify]...';


GO
ALTER PROCEDURE [sSetup].[pMastedDataModify]
	@rCategoryId int,
	@rXML nvarchar(max),
	@rSubCategoryField nvarchar(100)--,
	--@rOrgId int = 0
	
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
DECLARE @lInterrorCode INT
Declare @Sql nvarchar(max) 
DECLARE @loDoc INT

EXEC sp_xml_preparedocument @loDoc OUTPUT,@rXML
BEGIN
	
	IF(@rSubCategoryField = 'InchargeEmployee') 	
		SET @rSubCategoryField = @rSubCategoryField + 'Id'	
		
	IF(@rSubCategoryField = 'DisplayTitle' AND @rCategoryId = 9) 	
		SET @rSubCategoryField = 'ExamSubGroupDisplayTitle'
	
	
	IF OBJECT_ID('ListofData') IS NOT NULL	
			DROP TABLE ListofData
		
	CREATE TABLE ListofData(Id int,SubCategory nvarchar(150),UpdatedUserId bigint,IsExist bit);
	
	IF(@rCategoryId= 1)  
		BEGIN
		
		insert into ListofData
		select E.Id,sSetup.fPortalXMLTagsReplaceReverse(E.SubCategory),E.UpdatedUserId,0
		from
		(
				SELECT Id,SubCategory,UpdatedUserId FROM
				OPENXML (@loDoc, '/Masters/Masters', 2)
				WITH (
						Id BIGINT, 
						SubCategory nvarchar(150),
						UpdatedUserId bigint)	
						)E 	
						
		select *from ListofData				
		UPDATE ListofData SET IsExist=1 WHERE Id NOT IN(SELECT Id FROM sSetup.tOrganizationMaster ) 
		
		set @sql='INSERT INTO sSetup.tOrganizationMaster 
					(Id,'+@rSubCategoryField+',CreatedUserId,CreatedDateTime)
					SELECT
						LD.Id,Ld.SubCategory,LD.UpdatedUserId,sCommon.fGetDate()
					FROM
						ListofData LD WHERE LD.IsExist=1'
					
		print @sql		
		Exec sp_executesql @sql
		set @sql='UPDATE sSetup.tOrganizationMaster  set '+@rSubCategoryField+' = LD.SubCategory,
					UpdatedUserId=LD.UpdatedUserId,
					UpdatedDateTime=sCommon.fGetDate()  
					from sSetup.tOrganizationMaster SC 
					INNER JOIN ListofData LD ON SC.Id=LD.Id AND IsExist=0'
		
		Exec sp_executesql @sql
	
		
		Drop Table ListofData
			 SELECT 1 AS StatusCode
	    END
	    
	else IF(@rCategoryId= 2)     
	 
	 BEGIN
	 
	  insert into ListofData
		select E.Id,sSetup.fPortalXMLTagsReplaceReverse(E.SubCategory),E.UpdatedUserId,0
		from
		(
				SELECT Id,SubCategory,UpdatedUserId FROM
				OPENXML (@loDoc, '/Masters/Masters', 2)
				WITH (
						Id BIGINT, 
						SubCategory nvarchar(150),
						UpdatedUserId bigint)	
						)E 	
	    UPDATE ListofData SET IsExist=1 WHERE Id NOT IN(SELECT Id FROM sSetup.tClassMaster ) 
	    
	    set @sql='INSERT INTO sSetup.tClassMaster 
					(Id,'+@rSubCategoryField+',CreatedUserId,CreatedDateTime)
					SELECT
						LD.Id,Ld.SubCategory,LD.UpdatedUserId,sCommon.fGetDate()
					FROM
						ListofData LD WHERE LD.IsExist=1'
					
		print @sql		
		Exec sp_executesql @sql
		set @sql='UPDATE sSetup.tClassMaster  set '+@rSubCategoryField+' = LD.SubCategory,
					UpdatedUserId=LD.UpdatedUserId,
					UpdatedDateTime=sCommon.fGetDate()  
					from sSetup.tClassMaster SC 
					INNER JOIN ListofData LD ON SC.Id=LD.Id AND IsExist=0'
		
		Exec sp_executesql @sql
	
		
		Drop Table ListofData
			 SELECT 1 AS StatusCode
	  END
	  
	  
	  else IF(@rCategoryId= 3)
	  BEGIN
	     
	     insert into ListofData
		select E.Id,sSetup.fPortalXMLTagsReplaceReverse(E.SubCategory),E.UpdatedUserId,0
		from
		(
				SELECT Id,SubCategory,UpdatedUserId FROM
				OPENXML (@loDoc, '/Masters/Masters', 2)
				WITH (
						Id BIGINT, 
						SubCategory nvarchar(150),
						UpdatedUserId bigint)	
						)E 	
	    UPDATE ListofData SET IsExist=1 WHERE Id NOT IN(SELECT Id FROM sSetup.tDivisionMaster ) 
	    
	    set @sql='INSERT INTO sSetup.tDivisionMaster 
					(Id,'+@rSubCategoryField+',CreatedUserId,CreatedDateTime)
					SELECT
						LD.Id,Ld.SubCategory,LD.UpdatedUserId,sCommon.fGetDate()
					FROM
						ListofData LD WHERE LD.IsExist=1'
					
		print @sql		
		Exec sp_executesql @sql
		set @sql='UPDATE sSetup.tDivisionMaster  set '+@rSubCategoryField+' = LD.SubCategory,
					UpdatedUserId=LD.UpdatedUserId,
					UpdatedDateTime=sCommon.fGetDate()  
					from sSetup.tDivisionMaster SC 
					INNER JOIN ListofData LD ON SC.Id=LD.Id AND IsExist=0'
		--print @sql
		--return
		Exec sp_executesql @sql
	
		
		Drop Table ListofData
			 SELECT 1 AS StatusCode
	    
	  
	  END    
	  
	  else IF(@rCategoryId= 4)
	  BEGIN
	  
	   insert into ListofData
		select E.Id,sSetup.fPortalXMLTagsReplaceReverse(E.SubCategory),E.UpdatedUserId,0
		from
		(
				SELECT Id,SubCategory,UpdatedUserId FROM
				OPENXML (@loDoc, '/Masters/Masters', 2)
				WITH (
						Id BIGINT, 
						SubCategory nvarchar(150),
						UpdatedUserId bigint)	
						)E 	
	    UPDATE ListofData SET IsExist=1 WHERE Id NOT IN(SELECT Id FROM sSetup.tSubjectMaster ) 
	    
	    set @sql='INSERT INTO sSetup.tSubjectMaster 
					(Id,'+@rSubCategoryField+',CreatedUserId,CreatedDateTime)
					SELECT
						LD.Id,Ld.SubCategory,LD.UpdatedUserId,sCommon.fGetDate()
					FROM
						ListofData LD WHERE LD.IsExist=1'
					
		print @sql		
		Exec sp_executesql @sql
		set @sql='UPDATE sSetup.tSubjectMaster  set '+@rSubCategoryField+' = LD.SubCategory,
					UpdatedUserId=LD.UpdatedUserId,
					UpdatedDateTime=sCommon.fGetDate()  
					from sSetup.tSubjectMaster SC 
					INNER JOIN ListofData LD ON SC.Id=LD.Id AND IsExist=0'
		
		Exec sp_executesql @sql
	
		
		Drop Table ListofData
			 SELECT 1 AS StatusCode
	  
	  END 
	    
	 else IF(@rCategoryId= 5)
	 
	 BEGIN
	  
	   insert into ListofData
		select E.Id,sSetup.fPortalXMLTagsReplaceReverse(E.SubCategory),E.UpdatedUserId,0
		from
		(
				SELECT Id,SubCategory,UpdatedUserId FROM
				OPENXML (@loDoc, '/Masters/Masters', 2)
				WITH (
						Id BIGINT, 
						SubCategory nvarchar(150),
						UpdatedUserId bigint)	
						)E 	
	    UPDATE ListofData SET IsExist=1 WHERE Id NOT IN(SELECT Id FROM sSetup.tOrgGroupBatchMaster ) 
	    
	    set @sql='INSERT INTO sSetup.tOrgGroupBatchMaster 
					(Id,'+@rSubCategoryField+',CreatedUserId,CreatedDateTime)
					SELECT
						LD.Id,Ld.SubCategory,LD.UpdatedUserId,sCommon.fGetDate()
					FROM
						ListofData LD WHERE LD.IsExist=1'
					
		print @sql		
		Exec sp_executesql @sql
		set @sql='UPDATE sSetup.tOrgGroupBatchMaster  set '+@rSubCategoryField+' = LD.SubCategory,
					UpdatedUserId=LD.UpdatedUserId,
					UpdatedDateTime=sCommon.fGetDate()  
					from sSetup.tOrgGroupBatchMaster SC 
					INNER JOIN ListofData LD ON SC.Id=LD.Id AND IsExist=0'
		
		Exec sp_executesql @sql
	
		
		Drop Table ListofData
			 SELECT 1 AS StatusCode
	  
	  END 
	  
   else IF(@rCategoryId= 6)
	 BEGIN
	  
	   insert into ListofData
		select E.Id,sSetup.fPortalXMLTagsReplaceReverse(E.SubCategory),E.UpdatedUserId,0
		from
		(
				SELECT Id,SubCategory,UpdatedUserId FROM
				OPENXML (@loDoc, '/Masters/Masters', 2)
				WITH (
						Id BIGINT, 
						SubCategory nvarchar(150),
						UpdatedUserId bigint)	
						)E 	
	    UPDATE ListofData SET IsExist=1 WHERE Id NOT IN(SELECT Id FROM sSetup.tBatchMaster ) 
	    
	    set @sql='INSERT INTO sSetup.tBatchMaster 
					(Id,'+@rSubCategoryField+',CreatedUserId,CreatedDateTime)
					SELECT
						LD.Id,Ld.SubCategory,LD.UpdatedUserId,sCommon.fGetDate()
					FROM
						ListofData LD WHERE LD.IsExist=1'
					
		print @sql		
		Exec sp_executesql @sql
		set @sql='UPDATE sSetup.tBatchMaster  set '+@rSubCategoryField+' = LD.SubCategory,
					UpdatedUserId=LD.UpdatedUserId,
					UpdatedDateTime=sCommon.fGetDate()  
					from sSetup.tBatchMaster SC 
					INNER JOIN ListofData LD ON SC.Id=LD.Id AND IsExist=0'
		
		Exec sp_executesql @sql
	
		
		Drop Table ListofData
			 SELECT 1 AS StatusCode
			
	  END 
	  
	else IF(@rCategoryId= 7)
	 BEGIN
	  insert into ListofData
		select E.Id,sSetup.fPortalXMLTagsReplaceReverse(E.SubCategory),E.UpdatedUserId,0
		from
		(
				SELECT Id,SubCategory,UpdatedUserId FROM
				OPENXML (@loDoc, '/Masters/Masters', 2)
				WITH (
						Id BIGINT, 
						SubCategory nvarchar(150),
						UpdatedUserId bigint)	
						)E 	
	    UPDATE ListofData SET IsExist=1 WHERE Id NOT IN(SELECT Id FROM sSetup.tDepartmentMaster ) 
	    
	    set @sql='INSERT INTO sSetup.tDepartmentMaster
					(Id,'+@rSubCategoryField+',CreatedUserId,CreatedDateTime)
					SELECT
						LD.Id,Ld.SubCategory,LD.UpdatedUserId,sCommon.fGetDate()
					FROM
						ListofData LD WHERE LD.IsExist=1'
					
		print @sql		
		Exec sp_executesql @sql
		set @sql='UPDATE sSetup.tDepartmentMaster  set '+@rSubCategoryField+' = LD.SubCategory,
					UpdatedUserId=LD.UpdatedUserId,
					UpdatedDateTime=sCommon.fGetDate()  
					from sSetup.tDepartmentMaster SC 
					INNER JOIN ListofData LD ON SC.Id=LD.Id AND IsExist=0'
		
		Exec sp_executesql @sql
	
		
		Drop Table ListofData
			 SELECT 1 AS StatusCode
			
	  END 
	  
	  
 else IF(@rCategoryId= 8)
	 BEGIN
	  insert into ListofData
		select E.Id,sSetup.fPortalXMLTagsReplaceReverse(E.SubCategory),E.UpdatedUserId,0
		from
		(
				SELECT Id,SubCategory,UpdatedUserId FROM
				OPENXML (@loDoc, '/Masters/Masters', 2)
				WITH (
						Id BIGINT, 
						SubCategory nvarchar(150),
						UpdatedUserId bigint)	
						)E 	
	    UPDATE ListofData SET IsExist=1 WHERE Id NOT IN(SELECT Id FROM sCommon.tOrgGroupDepartmentMaster ) 
	    
	    set @sql='INSERT INTO sCommon.tOrgGroupDepartmentMaster
					(Id,'+@rSubCategoryField+',CreatedUserId,CreatedDateTime)
					SELECT
						LD.Id,Ld.SubCategory,LD.UpdatedUserId,sCommon.fGetDate()
					FROM
						ListofData LD WHERE LD.IsExist=1'
					
		print @sql		
		Exec sp_executesql @sql
		set @sql='UPDATE sCommon.tOrgGroupDepartmentMaster  set '+@rSubCategoryField+' = LD.SubCategory,
					UpdatedUserId=LD.UpdatedUserId,
					UpdatedDateTime=sCommon.fGetDate()  
					from sCommon.tOrgGroupDepartmentMaster SC 
					INNER JOIN ListofData LD ON SC.Id=LD.Id AND IsExist=0'
		
		Exec sp_executesql @sql
		
		Drop Table ListofData
			 SELECT 1 AS StatusCode
			
	  END 
	    
	   else IF(@rCategoryId= 9)
	 BEGIN
	  insert into ListofData
		select E.Id,sSetup.fPortalXMLTagsReplaceReverse(E.SubCategory),E.UpdatedUserId,0
		from
		(
				SELECT Id,SubCategory,UpdatedUserId FROM
				OPENXML (@loDoc, '/Masters/Masters', 2)
				WITH (
						Id BIGINT, 
						SubCategory nvarchar(150),
						UpdatedUserId bigint)	
						)E 	
	    UPDATE ListofData SET IsExist=1 WHERE Id NOT IN(SELECT Id FROM sAssessment.tExamSubGroupMaster ) 
	    
	    set @sql='INSERT INTO sAssessment.tExamSubGroupMaster
					(Id,'+@rSubCategoryField+',CreatedUserId,CreatedDateTime)
					SELECT
						LD.Id,Ld.SubCategory,LD.UpdatedUserId,sCommon.fGetDate()
					FROM
						ListofData LD WHERE LD.IsExist=1'
					
		print @sql		
		Exec sp_executesql @sql
		set @sql='UPDATE sAssessment.tExamSubGroupMaster  set '+@rSubCategoryField+' = LD.SubCategory,
					UpdatedUserId=LD.UpdatedUserId,
					UpdatedDateTime=sCommon.fGetDate()  
					from sAssessment.tExamSubGroupMaster SC 
					INNER JOIN ListofData LD ON SC.Id=LD.Id AND IsExist=0'
		
		Exec sp_executesql @sql
		
		Drop Table ListofData
			 SELECT 1 AS StatusCode
			
	  END 

	   else IF(@rCategoryId= 10)
	 BEGIN
	  insert into ListofData
		select E.Id,sSetup.fPortalXMLTagsReplaceReverse(E.SubCategory),E.UpdatedUserId,0
		from
		(
				SELECT Id,SubCategory,UpdatedUserId FROM
				OPENXML (@loDoc, '/Masters/Masters', 2)
				WITH (
						Id BIGINT, 
						SubCategory nvarchar(150),
						UpdatedUserId bigint)	
						)E 	
	    UPDATE ListofData SET IsExist=1 WHERE Id NOT IN(SELECT Id FROM sCommon.tReligionMaster ) 
	    

	    set @sql='INSERT INTO sCommon.tReligionMaster
					(Id,'+@rSubCategoryField+',CreatedUserId,CreatedDateTime)
					SELECT
						LD.Id,Ld.SubCategory,LD.UpdatedUserId,sCommon.fGetDate()
					FROM
						ListofData LD WHERE LD.IsExist=1'
					
		print @sql		
		Exec sp_executesql @sql
		set @sql='UPDATE sCommon.tReligionMaster  set '+@rSubCategoryField+' = LD.SubCategory,
					UpdatedUserId=LD.UpdatedUserId,
					UpdatedDateTime=sCommon.fGetDate()  
					from sCommon.tReligionMaster RM 
					INNER JOIN ListofData LD ON RM.Id=LD.Id AND IsExist=0'
		
		Exec sp_executesql @sql
		
		Drop Table ListofData
			 SELECT 1 AS StatusCode
			
	  END 
	    
	else IF(@rCategoryId= 11)
	 BEGIN
	  insert into ListofData
		select E.Id,E.SubCategory,E.UpdatedUserId,0
		from
		(
				SELECT Id,SubCategory,UpdatedUserId FROM
				OPENXML (@loDoc, '/Masters/Masters', 2)
				WITH (
						Id BIGINT, 
						SubCategory nvarchar(150),
						UpdatedUserId bigint)	
						)E 	
	    UPDATE ListofData SET IsExist=1 WHERE Id NOT IN(SELECT Id FROM sAcademic.tTopicMaster) 
	    

	    set @sql='INSERT INTO sAcademic.tTopicMaster
					(Id,'+@rSubCategoryField+',CreatedUserId,CreatedDateTime)
					SELECT
						LD.Id,Ld.SubCategory,LD.UpdatedUserId,sCommon.fGetDate()
					FROM
						ListofData LD WHERE LD.IsExist=1'
					
		print @sql		
		Exec sp_executesql @sql
		set @sql='UPDATE sAcademic.tTopicMaster set '+@rSubCategoryField+' = LD.SubCategory,
					UpdatedUserId=LD.UpdatedUserId,
					UpdatedDateTime=sCommon.fGetDate()  
					from sAcademic.tTopicMaster TM 
					INNER JOIN ListofData LD ON TM.Id=LD.Id AND IsExist=0'
		
		Exec sp_executesql @sql
		
		Drop Table ListofData
			 SELECT 1 AS StatusCode
			
	  END 
	 	
END 
	--   COMMIT TRANSACTION
		
	--END TRY
	
	--BEGIN CATCH 
	--	ROLLBACK TRANSACTION
	--	SELECT -1 AS Result
	--END CATCH
GO

ALTER PROCEDURE [sTransport].[pVehicleDocumentsGet]

           @rVehicleId int,
           @rOrgGroupId int
AS
SET NOCOUNT ON

BEGIN

	SELECT  
			ISNULL(VD.VehicleId,0) AS VehicleId,
			ISNULL(VDM.Id,0) AS VehicleDocumentId,
			ISNULL(VD.IsReminderReuired,0) AS IsReminderReuired,
			ISNULL(VD.ValidityInDays,0) AS ValidityInDays,
			CASE WHEN VD.LastRenewDate = '1900-01-01' THEN '' ELSE VD.LastRenewDate END AS LastRenewDate,
			VDM.Title AS VehicleDocumentName,
			''  As FileName								-- MantisId : 0032433
	FROM
			sTransport.tVehicleDocumentMaster VDM
			LEFT JOIN sTransport.tVehicleDocuments VD 
				ON VDM.Id = VD.VehicleDocumentId AND VD.VehicleId=@rVehicleId
			--Left Join [sCommon].[tUploadDocument] UD ON UD.DocumentId=VDM.Id									-- MantisId : 0032433
				--AND UD.UploadFunctionalityId = 47 AND UserSourceTypeId = 2047 AND UserSourceId = @rVehicleId	-- MantisId : 0032433
	WHERE VDM.OrgGroupId=@rOrgGroupId
END
GO
PRINT N'Creating Procedure [sAcademic].[pXMLVendorMasterAdd]...';


GO
CREATE PROCEDURE [sAcademic].[pXMLVendorMasterAdd]
    (
        @rXml NVARCHAR(MAX),		
        @rCreatedUserId BIGINT,
        @rOrgGroupId INT,
        @rLocationId bigint
    )
AS
BEGIN
    DECLARE @lInterrorCode INT, @intDoc INT;
    DECLARE @lNextNumber BIGINT;

    EXECUTE @lInterrorCode = sp_xml_preparedocument @intDoc OUTPUT, @rXml;
	
    BEGIN TRY

        CREATE TABLE #tempTable (
            Id INT IDENTITY,
            Code NVARCHAR(100),
            Title NVARCHAR(100),
            Area NVARCHAR(100),
            City NVARCHAR(100),
            ContactPersonName NVARCHAR(300),
            Country NVARCHAR(100),
            CreditDays SMALLINT,
            Email NVARCHAR(100),
            FaxNumber NVARCHAR(100),
            PhoneNumberMobile NVARCHAR(100),
            PhoneNumberOffice NVARCHAR(100),
            State NVARCHAR(100),
            StreetOne NVARCHAR(100),
            StreetThree NVARCHAR(100),
            StreetTwo NVARCHAR(100),
            VendorCategoryId INT,
            ZipCode NVARCHAR(20)
        )

        INSERT INTO #tempTable (
        Code, Title, Area, City, ContactPersonName, Country, CreditDays,
        Email, FaxNumber, PhoneNumberMobile, PhoneNumberOffice, State,  StreetOne,
        StreetThree, StreetTwo, VendorCategoryId, ZipCode
		)
		SELECT 
			VM.Code,
			VM.Title,
			VM.Area,
			VM.City,
			VM.ContactPersonName,
			VM.Country,
			VM.CreditDays,
			VM.Email,
			VM.FaxNumber,
			VM.PhoneNumberMobile,
			VM.PhoneNumberOffice,
			VM.State,
			VM.StreetOne,
			VM.StreetThree,
			VM.StreetTwo,
			VM.VendorCategoryId,
			VM.ZipCode
    FROM OPENXML (@intDoc, '/Table/VendorMaster', 1)
    WITH
    (
        Code NVARCHAR(100) '@Code',
        Title NVARCHAR(100) '@Title',
        Area NVARCHAR(100) '@Area',
        City NVARCHAR(100) '@City',
        ContactPersonName NVARCHAR(300) '@ContactPerson',
        Country NVARCHAR(100) '@Country',
        CreditDays SMALLINT '@CreditDays',
        Email NVARCHAR(100) '@Email',
        FaxNumber NVARCHAR(100) '@FaxNumber',
        PhoneNumberMobile NVARCHAR(100) '@PhoneNumberMobile',
        PhoneNumberOffice NVARCHAR(100) '@PhoneNumberOffice',
        State NVARCHAR(100) '@State',
        StreetOne NVARCHAR(100) '@Address1',
        StreetThree NVARCHAR(100) '@Address3',
        StreetTwo NVARCHAR(100) '@Address2',
        VendorCategoryId INT '@VendorCategoryId',
        ZipCode NVARCHAR(20) '@ZipCode'
    )VM

    DECLARE @lCount INT, @lId INT;
    SELECT @lCount = COUNT(Id) FROM #tempTable;
    SELECT TOP 1 @lId = Id FROM #tempTable;

    WHILE @lId <= @lCount 
    BEGIN
		EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sProcurement.tVendorMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
		INSERT INTO sProcurement.tVendorMaster
        SELECT @lNextNumber, Code, Title, 0, @rCreatedUserId, sCommon.fGetDate(), @rCreatedUserId, sCommon.fGetDate(), Area, City
			,ContactPersonName, Country, CreditDays, NULL,Email, FaxNumber,PhoneNumberMobile,
            PhoneNumberOffice, State,NULL, StreetOne, StreetThree, StreetTwo, VendorCategoryId, ZipCode, @rOrgGroupId, @rLocationId
        FROM 
            #tempTable 
        WHERE 
            Id = @lId;
        SET @lId = @lId + 1;
	END;

        EXEC sp_xml_removedocument @intDoc;
        SELECT 1 AS Result;
        DROP TABLE #tempTable;
    END TRY
    BEGIN CATCH
        SELECT -1 AS Result
    END CATCH;
END;
GO
PRINT N'Creating Procedure [sAdmission].[pRptAdmissionSlipGet]...';


GO
CREATE PROCEDURE [sAdmission].[pRptAdmissionSlipGet]
	
	 @rDepartmentId int,
	 @rBatchId int,
	 @rClassId int,
	 @rFromDate date,
	 @rToDate date,
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)=''
	
	 --@rOrgId int,
	 
	 --@rFromMeritMarks int,
	 --@rToMeritMarks int
	  
AS
	SET NOCOUNT ON			 
BEGIN 
	
	SELECT
		 AF.Id,
		 AF.FirstName + ' ' + AF.MiddleName + ' ' + AF.LastName AS Name,
		 AF.DateOfBirth,
		 AF.BatchId,
		 AF.OrgId,
		 SA.AdmissionDate AS AdmissionDate,
		 CM.DisplayTitle AS AdmissionStandard,
		 AF.MiddleName AS FatherName,
		 ISNULL(SC.StudentContactNo,'') AS StudentContactNo,
		 @rBuilder1 AS Builder1,
		 @rBuilder2 AS Builder2,
		 BM.Title AS Batch,
		 ISNULL(AF.ContactNo,'') AS ContactNo
	FROM
		sAdmission.tAdmissionForm AF
		INNER JOIN sSetup.tClassMaster CM ON CM.Id=AF.ForClassId
		LEFT JOIN sStudent.tStudentAdmission SA ON SA.StudentId = AF.StudentId
		LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId = SA.StudentId
		LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId = SA.StudentId
		INNER JOIN sSetup.tBatchMaster BM ON BM.Id=AF.BatchId

	WHERE 	
		AF.BatchId = @rBatchId
		AND ((CM.DepartmentId = @rDepartmentId) OR (@rDepartmentId = 0))
		AND ((CM.Id = @rClassId) OR (@rClassId = 0))
		AND ((CONVERT(DATE,AF.CreatedDateTime) >= @rFromDate) OR (isnull(@rFromDate,'')=''))
		AND ((CONVERT(DATE,AF.CreatedDateTime) <= @rToDate) OR (isnull(@rToDate,'')=''))
END
GO
PRINT N'Creating Procedure [sAlert].[pSubjectwiseAttendanceGet]...';


GO
CREATE PROCEDURE [sAlert].[pSubjectwiseAttendanceGet]	 	 
	 	 @rBatchId int,
	 	 @rClassId int,
	 	 @rDivisionId int,
	 	 @rOrgId int,
	 	 @rTemplate nvarchar(max),
	 	 @rAttendanceTypeId tinyint,
	 	 @rSubjectId int=0,
	 	 @rFromDate date,
	 	 @rToDate date,
	 	 @rMailSubject nvarchar(500)=''
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	IF (@rSubjectId = 0 OR @rSubjectId IS NULL)
	BEGIN 
		select 
			SC.AcademicId,
			SC.Code,
			SC.Name,
			SC.ParentContactNo AS MobileNo,	
			SC.ParentEmail AS EmailId,
			ISNULL(SC.StudentContactNo,'') AS StudentContactNo,
			ISNULL(SC.StudentEmail,'') AS StudentEmail,
			ISNULL(SC.FatherContactNo,'') AS FatherContactNo,
			ISNULL(SC.FatherMail,'') AS FatherMail,
			ISNULL(SC.MotherContactNo,'') AS MotherContactNo,
			ISNULL(SC.MotherMail,'') AS MotherMail,
			replace(
			replace (
			replace (
			replace (
			replace (
			replace (
			replace (
			replace (
			replace (
			replace (
			replace(@rTemplate,'[Name]',SC.Name),
			'[Class]',SC.ClassName),
			'[Division]',SC.DivisionName),
			'[FromDate]',@rFromDate),
			'[ToDate]',@rToDate),
			'[TotalCount]',(isnull(TCount,0.00)+isnull(ACount,0.00))),
			'[PresentCount]',convert(decimal(5,2),isnull(TCount,0.00))),
			'[AbsentCount]',convert(decimal(5,2),isnull(ACount,0.00))),
			'[AveragePresence]',case when (isnull(TCount,0.00)+isnull(ACount,0.00))<>0.00 then
								convert(decimal(5,2),(convert(decimal(5,2),isnull(TCount,0.00)*100)/convert(decimal(5,2),isnull(TCount,0.00)+isnull(ACount,0.00))))
								else 0.00 end),
			'[AbsentDates]',[sAttendance].[fAbsentDatesGet](@rFromDate,@rTodate,5,@rSubjectId,SC.AcademicId)),
			'[SubjectName]','All Subject')
			AS MsgText,			 
			@rMailSubject AS Subject,
			2001 AS ReceiverSourceTypeId,
			SC.AcademicId AS ReceiverSourceId,
			SC.ClassName AS Class,
			SC.DivisionName AS Division,
			(isnull(TCount,0.00)+isnull(ACount,0.00)) as TotalCount,
			convert(decimal(5,2),isnull(TCount,0.00)) as PresentCount,
			convert(decimal(5,2),isnull(ACount,0.00)) as AbsentCount,
			case when (isnull(TCount,0.00)+isnull(ACount,0.00))<>0.00 then
							convert(decimal(5,2),(convert(decimal(5,2),isnull(TCount,0.00)*100)/convert(decimal(5,2),isnull(TCount,0.00)+isnull(ACount,0.00))))
							else 0.00 end as AveragePresence,
			[sAttendance].[fAbsentDatesGet](@rFromDate,@rTodate,5,@rSubjectId,SC.AcademicId) AS AbsentDates,
			SC.WhatsAppContactNo
	FROM 
	sStudent.vStudentCommunication SC 
	LEFT JOIN
	(
		Select A.Id AS AcademicId, COUNT(1) AS TCount 
		   FROM sAttendance.tStudentRegister SR1
		   INNER JOIN sStudent.tAcademic A ON SR1.AcademicId = A.Id 
		   WHERE 		
			SR1.AttendanceTypeId=5
			AND SR1.IsPresent =1 
			AND (SR1.AttendanceDate >= @rFromDate OR ISNULL(@rFromDate,'')='')
			AND (SR1.AttendanceDate <= @rToDate OR ISNULL(@rToDate,'')='') 
			AND (A.BatchId=@rBatchId)			 
			AND (A.ClassId = @rClassId)
			AND (A.DivisionId = @rDivisionId OR @rDivisionId=0)
			GROUP BY A.Id
    ) TC ON TC.AcademicId = SC.AcademicId
    LEFT JOIN
	(
		Select A.Id AS AcademicId, COUNT(1) AS ACount  
		   FROM sAttendance.tStudentRegister SR1
		   INNER JOIN sStudent.tAcademic A ON SR1.AcademicId = A.Id 
		   WHERE 
			SR1.IsPresent = 0		
			AND SR1.AttendanceTypeId=5
			AND (SR1.AttendanceDate >= @rFromDate OR ISNULL(@rFromDate,'')='')
			AND (SR1.AttendanceDate <= @rToDate OR ISNULL(@rToDate,'')='') 	 
			AND (A.BatchId=@rBatchId)			 
			AND (A.ClassId = @rClassId)
			AND (A.DivisionId = @rDivisionId OR @rDivisionId=0)
			GROUP BY A.Id
    ) AC ON AC.AcademicId = SC.AcademicId
	--INner JOIn sSetup.vClassSubject CS  On  CS.IsObsolete = 0 AND CS.ClassId=@rClassId 
	WHERE
	 SC.BatchId = @rBatchId
	 AND ((SC.ClassId = @rClassId))
	 AND ((SC.DivisionId = @rDivisionId) OR @rDivisionId=0)
	 AND (SC.StatusId=1) AND SC.IsBlockAllAlert=0
	 Order by SC.AcademicId 
	END
	ELSE
	BEGIN
		select 
			SC.AcademicId,
			SC.Code,
			SC.Name,
			SC.ParentContactNo AS MobileNo,	
			SC.ParentEmail AS EmailId,
			ISNULL(SC.StudentContactNo,'') AS StudentContactNo,
			ISNULL(SC.StudentEmail,'') AS StudentEmail,
			ISNULL(SC.FatherContactNo,'') AS FatherContactNo,
			ISNULL(SC.FatherMail,'') AS FatherMail,
			ISNULL(SC.MotherContactNo,'') AS MotherContactNo,
			ISNULL(SC.MotherMail,'') AS MotherMail,
			replace(
			replace (
			replace (
			replace (
			replace (
			replace (
			replace (
			replace (
			replace (
			replace (
			replace(@rTemplate,'[Name]',SC.Name),
			'[Class]',SC.ClassName),
			'[Division]',SC.DivisionName),
			'[FromDate]',@rFromDate),
			'[ToDate]',@rToDate),
			'[TotalCount]',(isnull(TCount,0.00)+isnull(ACount,0.00))),
			'[PresentCount]',convert(decimal(5,2),isnull(TCount,0.00))),
			'[AbsentCount]',convert(decimal(5,2),isnull(ACount,0.00))),
			'[AveragePresence]',case when (isnull(TCount,0.00)+isnull(ACount,0.00))<>0.00 then
								convert(decimal(5,2),(convert(decimal(5,2),isnull(TCount,0.00)*100)/convert(decimal(5,2),isnull(TCount,0.00)+isnull(ACount,0.00))))
								else 0.00 end),
			'[AbsentDates]',[sAttendance].[fAbsentDatesGet](@rFromDate,@rTodate,5,@rSubjectId,SC.AcademicId)),
			'[SubjectName]',CS.SubjectName)
			AS MsgText,			 
			@rMailSubject AS Subject,
			2001 AS ReceiverSourceTypeId,
			SC.AcademicId AS ReceiverSourceId,
			SC.ClassName AS Class,
			SC.DivisionName AS Division,
			(isnull(TCount,0.00)+isnull(ACount,0.00)) as TotalCount,
			convert(decimal(5,2),isnull(TCount,0.00)) as PresentCount,
			convert(decimal(5,2),isnull(ACount,0.00)) as AbsentCount,
			case when (isnull(TCount,0.00)+isnull(ACount,0.00))<>0.00 then
							convert(decimal(5,2),(convert(decimal(5,2),isnull(TCount,0.00)*100)/convert(decimal(5,2),isnull(TCount,0.00)+isnull(ACount,0.00))))
							else 0.00 end as AveragePresence,
			[sAttendance].[fAbsentDatesGet](@rFromDate,@rTodate,5,@rSubjectId,SC.AcademicId) AS AbsentDates,
			SC.WhatsAppContactNo
	 from 
	sStudent.vStudentCommunication SC 
	LEFT JOIN
	(
		Select A.Id AS AcademicId, COUNT(1) AS TCount 
		   FROM sAttendance.tStudentRegister SR1
		   INNER JOIN sStudent.tAcademic A ON SR1.AcademicId = A.Id 
		   WHERE 		
			SR1.AttendanceTypeId=5
			AND SR1.IsPresent = 1 
			AND (SR1.SubjectId=@rSubjectId OR (ISNULL(@rSubjectId,0)=0))
			AND (SR1.AttendanceDate >= @rFromDate OR ISNULL(@rFromDate,'')='')
			AND (SR1.AttendanceDate <= @rToDate OR ISNULL(@rToDate,'')='') 
			AND (A.BatchId=@rBatchId)			 
			AND (A.ClassId = @rClassId)
			AND (A.DivisionId = @rDivisionId OR @rDivisionId=0)
			GROUP BY A.Id
    ) TC ON TC.AcademicId = SC.AcademicId
    LEFT JOIN
	(
		Select A.Id AS AcademicId, COUNT(1) AS ACount  
		   FROM sAttendance.tStudentRegister SR1
		   INNER JOIN sStudent.tAcademic A ON SR1.AcademicId = A.Id 
		   WHERE 
		   SR1.IsPresent = 0		
			AND SR1.AttendanceTypeId=5
			AND (SR1.SubjectId=@rSubjectId OR (ISNULL(@rSubjectId,0)=0)) 
			AND (SR1.AttendanceDate >= @rFromDate OR ISNULL(@rFromDate,'')='')
			AND (SR1.AttendanceDate <= @rToDate OR ISNULL(@rToDate,'')='') 	 
			AND (A.BatchId=@rBatchId)			 
			AND (A.ClassId = @rClassId)
			AND (A.DivisionId = @rDivisionId OR @rDivisionId=0)
			GROUP BY A.Id
    ) AC ON AC.AcademicId = SC.AcademicId
	INner JOIn sSetup.vClassSubject CS  On  CS.IsObsolete = 0 AND CS.ClassId=@rClassId 
	WHERE
	 SC.BatchId = @rBatchId
	 AND ((SC.ClassId = @rClassId))
	 AND ((SC.DivisionId = @rDivisionId) OR @rDivisionId=0)
	 AND (SC.StatusId=1) AND SC.IsBlockAllAlert=0
	 AND (CS.SubjectId=@rSubjectId OR @rSubjectId= 0)
	 Order by SC.AcademicId 
	END
	
End
GO
PRINT N'Creating Procedure [sAssessment].[pRptResultListSubjectWiseConsolidatedGet]...';


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

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

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

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

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


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

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

		Exam13Name nvarchar(100),	
		TotalMarks13 decimal(8,2),
		TotalObtain13 decimal(8,2),
		Percentage13 decimal(5,2),
		RankNumber13 int,
		ResultGrade13 NVarchar(10),
		Percentile13 decimal(5,2),
		ResultStatus13 Nvarchar(50),
		Exam13CombineExamName Nvarchar(100),
		
		ResultRemark1 nvarchar(200),
		ResultRemark2 nvarchar(200),
		
		TotalDays decimal(6,2),
		PresentDays decimal(6,2),
		StudentHeight decimal(6,2),
		StudentWeight decimal(6,2),
		ExamSeatNo nvarchar(20),
		ExamId int,
		
		ExamCode nvarchar(20),
		Exam1Code nvarchar(20),
		Exam2Code nvarchar(20),
		Exam3Code nvarchar(20),
		Exam4Code nvarchar(20),
		Exam5Code nvarchar(20),
		Exam6Code Nvarchar(20),
		Exam7Code Nvarchar(20),
		Exam8Code nvarchar(20),
		Exam9Code nvarchar(20),
		Exam10Code nvarchar(20),
		Exam11Code nvarchar(20),
		Exam12Code nvarchar(20),
		Exam13Code nvarchar(20),
		
		IsDisplayParentName bit,
		FatherName nvarchar(100),
		MotherName nvarchar(100),
		IsShowSubjectMark bit, 
		IsOptionalSubject bit,
		CoScholasticScopeId tinyint,
		IsDisplayPrincipalSign bit,
		IsDisplayTeacherSign bit,
		EmployeeSign varbinary(max),
		Batch nvarchar(100),
		ExamNameTerm1 NVarchar(100),
		ExamNameTerm2 NVarchar(100) ,
		ExamNameTerm3 NVarchar(100),
		ClassTeacherName Nvarchar(100),
		FirstName nvarchar(100),
		LastName nvarchar(100),
		IsDisplayMonthlyAttendance bit,
		MarksheetHeaderA4 varbinary(max),
		IsImageHeader bit,
		MyGoal nvarchar(200),
		AreaOfInterest nvarchar(200),
		Responsibility nvarchar(200),
		MyInterestHobby nvarchar(200),
		MyStrength nvarchar(200),
		Achievements nvarchar(1000),
		
		DentalHygiene nvarchar(50),
		VisionLeft nvarchar(50),
		VisionRight nvarchar(50), 
		IsDetail bit,
		SubjectGroupId int,
		SubjectGroupTitle nvarchar(100),
		SubjectGroupCode nvarchar(20),
		DecimalFormat nvarchar(10),
		SubjectRemark nvarchar(100),
		GraceMark decimal(5,2),
		KrupaMark decimal(5,2),
		GradeStringHtml nvarchar(500),
		ResultRemark3 nvarchar(200),
		IsDisplayTotalMark bit,
		SubjectObtainTerm1 decimal(5,2),	
		SubjectObtainTerm2 decimal(5,2),
		SubjectObtainTerm3  decimal(5,2),
		SubjectMaxTerm1 decimal(10,2),
		SubjectMaxTerm2 decimal(10,2),
		SubjectMaxTerm3 decimal(10,2),
		ContactNo nvarchar(50),
		PresentAddress nvarchar(max),
		TeacherSignCaption nvarchar(100),
		PrincipalSignCaption nvarchar(100),
		ParentSignCaption nvarchar(100),
		ImprovementArea nvarchar(200),
		ProgressArea nvarchar(200),
		GeneralRemark nvarchar(1000),
		MyActivity nvarchar(200),
		ClassTeacherRemark nvarchar(1000),
		 
		HouseRemark nvarchar(1000),
		BloodGroup Nvarchar(20),
		TotalDays1 decimal(6,2),
		PresentDays1 decimal(6,2),
		TotalDays2 decimal(6,2),
		PresentDays2 decimal(6,2),
		TotalDays3 decimal(6,2),
		PresentDays3 decimal(6,2),
		TotalDays4 decimal(6,2),
		PresentDays4 decimal(6,2),
		TotalDays5 decimal(6,2),
		PresentDays5 decimal(6,2),
		TotalDays6 decimal(6,2),
		PresentDays6 decimal(6,2),
		TotalDays7 decimal(6,2),
		PresentDays7 decimal(6,2), 
		TotalDays8 decimal(6,2),
		PresentDays8 decimal(6,2),
		TotalDays9 decimal(6,2),
		PresentDays9 decimal(6,2),
		TotalDays10 decimal(6,2),
		PresentDays10 decimal(6,2),
		TotalDays11 decimal(6,2),
		PresentDays11 decimal(6,2),
		TotalDays12 decimal(6,2),
		PresentDays12 decimal(6,2),
		TotalDays13 decimal(6,2),
		PresentDays13 decimal(6,2),
		BatchIdText nvarchar(20),
		IsShowWithDetail bit,
		IsPresent bit,
		GradeTitle nvarchar(50),
		SubjectHighestDivisionGrade nvarchar(50),
		SubjectHighestDivisionMark decimal(5, 2),
		
		AchievementsTerm1 nvarchar(1000),
		AchievementsTerm2 nvarchar(1000),
		GeneralRemarkTerm1 nvarchar(1000),
		GeneralRemarkTerm2 nvarchar(1000),
		ResultRemark1Term1 nvarchar(200),
		ResultRemark2Term1 nvarchar(200),
		ResultRemark1Term2 nvarchar(200),
		ResultRemark2Term2 nvarchar(200),
		SR_HeightTerm1 decimal(6,2),
		SR_WeightTerm1 decimal(6,2),
		SR_HeightTerm2 decimal(6,2),
		SR_WeightTerm2 decimal(6,2),
		SR_PresentDaysTerm1 decimal(6,2),
		SR_PresentDaysTerm2 decimal(6,2),
		SR_TotalDaysTerm1 decimal(6,2),
		SR_TotalDaysTerm2 decimal(6,2),
		HouseId int,
		HouseName nvarchar(100),
		AdhaarNumber nvarchar(20),
		UIdNumber nvarchar(50),
		FatherContactNo nvarchar(50),
		MotherContactNo nvarchar(50),
		FatherMail nvarchar(50),
		MotherMail nvarchar(50),
		Gender nvarchar(100),
		CoordinatorEmployeeSign varbinary(max),
		StudentAddress nvarchar(max),
		SUId nvarchar(50),
		HighestDivisionMark decimal(5, 2),
		HighestDivisionGrade nvarchar(10),
		StreamTitle nvarchar(50),
		AdmissionNo nvarchar(50),
		AdmissionDate Date,
		MiddleName nvarchar(100) ,
		FatherOccupation nvarchar(50),
		ResultSheetAdditionalTitle nvarchar(100),
		IsDecimal bit,
		IsAbsentRemark bit,
		FinalAbsentRemark nvarchar(100),
		AbsentRemark1 nvarchar(100),
		AbsentRemark2 nvarchar(100),
		AbsentRemark3 nvarchar(100),
		AbsentRemark4 nvarchar(100),
		AbsentRemark5 nvarchar(100),
		AbsentRemark6 nvarchar(100),
		AbsentRemark7 nvarchar(100),
		AbsentRemark8 nvarchar(100),
		AbsentRemark9 nvarchar(100),
		AbsentRemark10 nvarchar(100),
		AbsentRemark11 nvarchar(100),
		AbsentRemark12 nvarchar(100),
		AbsentRemark13 nvarchar(100),
		ExamMaximumTerm1 decimal(6,2),
		ExamMaximumTerm2 decimal(6,2),
		ExamMaximumTerm3 decimal(6,2),
		--add for 29923 mantis start
		PermanentStreetOne nvarchar(150),
		PermanentStreetTwo nvarchar(150),
		PermanentStreetThree nvarchar(150),
		--add for 29923 mantis end
		CasteCategory nvarchar(50),--Mantis 0030303
		--Mantis Start - 0031091
		FeeCategory nvarchar(100),
		StudentContactNo nvarchar(50),
		--Mantis End - 0031091
		ObtainedMaximum1 decimal(10,2),
		ObtainedMaximum2 decimal(10,2),
		ObtainedMaximum3 decimal(10,2),
		ObtainedMaximum4 decimal(10,2),
		ObtainedMaximum5 decimal(10,2),
		ObtainedMaximum6 decimal(10,2),
		ObtainedMaximum7 decimal(10,2),
		ObtainedMaximum8 decimal(10,2),
		ObtainedMaximum9 decimal(10,2),
		ObtainedMaximum10 decimal(10,2),
		ObtainedMaximum11 decimal(10,2),
		ObtainedMaximum12 decimal(10,2),
		ObtainedMaximum13 decimal(10,2),
		ResultIndicator nvarchar(50),   -- Mantis - 31306
		IsResultIndicator bit,		-- Mantis - 31306
		ExamBlock nvarchar(100), --Mantis - 31848
		AbsentRemarkTerm1 nvarchar(100),    ---Mantis - 32090 - Start
		AbsentRemarkTerm2 nvarchar(100),
		AbsentRemarkTerm3 nvarchar(100),
		IsPresentTerm1 bit,
		IsPresentTerm2 bit,
		IsPresentTerm3 bit ,        ---Mantis - 32090 - End
		--Mantis Start - 0032150
		IsPercentage1 bit,
		IsPercentage2 bit,
		IsPercentage3 bit,
		IsPercentage4 bit,
		IsPercentage5 bit,
		IsPercentage6 bit,
		IsPercentage7 bit,
		IsPercentage8 bit,
		IsPercentage9 bit,
		IsPercentage10 bit,
		IsPercentage11 bit,
		IsPercentage12 bit,
		IsPercentage13 bit
		--Mantis End - 0032150

		)
	 --print 'temp created'    	
	INSERT INTO  #TempAllExam 
	(
	AcademicIdText,
	ExamIdText,
	CoScholasticScopeIdText,
	IsDisplayMonthlyAttendanceText,
	ClassIdText,
	AcademicId,
	ExamName,
	StudCode,
	StudentName,
	RollNo,
	ResultStatus,
	ClassName,
	Division,
	TotalMark,
	TotalObtain,
	Percentage,
	RankNumber,
	ResultGrade,
	IsMarksInDecimal,
	column_visible,
	--Obtain,
	Percentile,
	--ClassSubject,
	ResultDetailId,
	ResultId,

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


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

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

= AR.OrgGroupBatchId)) 
    LEFT JOIN
	(SELECT AT.SourceId,B.OrgGroupBatchId FROM sTransport.tAssignRoute AT 
    INNER JOIN sTransport.tBusRouteDestinationMaster BM ON BM.Id=AT.PickupDestinationId 
    INNER JOIN sTransport.tBusRouteMaster B ON B.Id=BM.BusRouteId AND  AT.SourceTypeId=2003 AND ((B.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))) RT
    ON RT.SourceId = StuM.Id 
	LEFT JOIN sHrm.tEmployeeImages EICoordinator ON EICoordinator.EmployeeId = EM.CoordinatorEmployeeId		  
	--LEFT JOIN sAcademic.tTeacherSubjectDivision TSD ON TSD.SubjectId=SM.Id AND TSD.DivisionId = A.DivisionId
	--LEFT JOIN sHrm.tEmployeeMaster EMP ON TSD.EmployeeId = EMP.Id
	LEFT JOIN sStudent.tStudentAdmission StuA ON StuM.Id = StuA.StudentId
	LEFT JOIN sCommon.tCastCategoryMaster CSM ON CSM.Id=SO.CastCategoryId        --Mantis 0030303
	LEFT JOIN sStudent.tAdmissionCategoryMaster ACM ON ACM.Id=StuM.AdmissionCategoryId	--Mantis - 0031091
	 
	 WHERE
		R.ExamId = @rExamId 
		AND ((A.DivisionId =  @rDivisionId) OR (@rDivisionId=0))
		AND ((A.ClassId =  @rClassId) OR (@rClassId=0))		 
		AND ((A.BatchId =  @rBatchId) OR (@rBatchId=0))
		AND ((A.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
		AND ((A.RollNo <= @rToRollNo) OR (@rToRollNo=0))
		AND ((R.RankNumber >= @rFromRank) OR (@rFromRank=0))
		AND ((R.RankNumber <= @rToRank) OR (@rToRank=0))
		AND ((R.ResultGrade = @rGrade) OR (@rGrade=''))
		AND ((StuM.Code=@rCode) OR (@rCode=''))	
		AND ((R.Id = @rResultId) OR (@rResultId = 0))	
		AND ((StuM.StatusId=@rStatusId)OR(@rStatusId=0))
		AND((A.Id=@rAcademicId)OR (@rAcademicId=0))
		AND ((CS.SubjectId=@rSubjectId) OR(@rSubjectId=0) ) 
		AND ((R.TotalObtain>=@rFromObtain) OR (@rFromObtain=0))
		AND ((R.TotalObtain<=@rToObtain) OR (@rToObtain=0))
		AND ((R.Percentage>=@rFromPercentage) OR (@rFromPercentage=0))
		AND ((R.Percentage<=@rToPercentage) OR (@rToPercentage=0))
		
		 AND (
	 (@rFilterId = 0) -- All
     OR (@rFilterId = 2 AND isnull(AR.SourceId,0)!=0) -- Hostel
     OR (@rFilterId = 3 AND isnull(RT.SourceId,0)!=0) -- Transport
     OR ((@rFilterId =1) AND ((isnull(AR.SourceId,0)=0) AND (isnull(RT.SourceId,0)=0)))
    )
	AND ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0)) 
	AND (ISNULL(StuM.Code,0) IN( SELECT cast(item as nvarchar(20)) FROM  sCommon.fnsplit(@rMultiCode,',')) OR @rMultiCode='')
	    
	Order By ED.DisplayOrder

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

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

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

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

 --             0 As Percentile ,

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

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

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

 --       '' AS ExamCode,

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

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

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

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

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

-- SELECT @rBuilder1 AS Builder1,@rBuilder2 AS Builder2, @rFromObtainExam AS FromObtainExam, @rToObtainExam AS ToObtainExam, T.* FROM sAssessment.tTempAllExam T
 
	END
--	SELECT @rBuilder1 AS Builder1,@rBuilder2 AS Builder2, @rFromObtainExam AS FromObtainExam, @rToObtainExam AS ToObtainExam, T.* FROM sAssessment.tTempAllExam T
	
--end
GO
PRINT N'Creating Procedure [sCommon].[pReportHistoryAdd]...';


GO

CREATE PROCEDURE [sCommon].[pReportHistoryAdd]
	 
	        --@rId int,
	        @rScreenId int,
	        @rReportName nvarchar(max),
            @rStatusId int,
            @rUserId bigint

	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	--BEGIN TRY
	
	INSERT INTO [sCommon].[tReportHistory]
           (
		    ScreenId
           ,ReportName
           ,StatusId
           ,CreatedUserId
           ,CreatedDateTime
			)
     VALUES
           (
		    @rScreenId
           ,@rReportName
           ,@rStatusId
           ,@rUserId
           ,sCommon.fGetDate()
           )
	--Select 1 AS Result

	SELECT @@Identity AS Result
	--COMMIT TRANSACTION		
	--END TRY
	
	--BEGIN CATCH 
	--	ROLLBACK TRANSACTION
	--	SELECT -1 AS RESULT
	--END CATCH	
		
END
GO
PRINT N'Creating Procedure [sCommon].[pReportHistoryGet]...';


GO

CREATE PROCEDURE [sCommon].[pReportHistoryGet]
	 
	        @rUserId bigint,
	        @rScreenId int
	  
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	
	SELECT 
			Id,
			ReportName,
		   (CASE WHEN StatusId = 1 THEN 'Completed' 
				 WHEN StatusId = 2 THEN 'No Record'
				 WHEN StatusId = 3 THEN 'Error'
				 ELSE 'Pending' END) AS Status,
		   CreatedDateTime,
		   UpdatedDateTime,
		   ISNULL(Guid,'') AS ReportPath,
		   StatusId
	FROM
			 sCommon.tReportHistory
	WHERE 
	ScreenId = @rScreenId
	AND CreatedUserId = @rUserId
	AND CAST(CreatedDateTime AS Date) > CAST(DATEADD(day, -2, GETDATE()) AS DATE)
	Order By CreatedDateTime DESC
   
END
GO

PRINT N'Creating Procedure [sFee].[pOldExemptionFeeToExceptionAdd]...';


GO
CREATE 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
		
		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'Creating Procedure [sFee].[pOldExemptionFeeToExemptionGet]...';


GO
CREATE 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
		
			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'Creating Procedure [sFee].[pOldPaidFeeToNotApplicableAdd]...';


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

		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'Creating Procedure [sFee].[pOldPaidFeeToNotApplicableGet]...';


GO
CREATE 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
		
			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'Creating Procedure [sFee].[pRptFeeReceiptListWithTaxGet]...';


GO

CREATE PROCEDURE [sFee].[pRptFeeReceiptListWithTaxGet]  
	@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   

	BEGIN
		SELECT   
			@rBuilder1 AS Builder1,  
			@rBuilder2 AS Builder2,  
			@rIsDetail AS IsDetail,  
			@rIsCancel AS IsCancel,  
			@rIsFilter As IsFilter,  
			@rIsHeader As IsHeader,  
			@rIsDisplayOrgGroup AS IsDisplayOrgGroup,  
			R.Id AS ReceiptId,  
			R.ReceiptNumber,  
			SA.ClassId,  
			SA.DivisionId,  
			SA.ClassName+' - '+SA.DivisionName AS ClassDivision,  
			SA.RollNo,  
			SA.Code,  
			SA.Name,  
			ISNULL(PTM.Title,'') AS PayType,    
			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,  
			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,  
			'' 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,  
			SA.OrgGroupBatchId AS BatchId,  
			SA.BatchName,  
			R.ChequeDate,  
			R.ChequeClearDate,
			CAST(CASE WHEN ISNULL(RTD.TaxTypeId,0) = 1 AND ISNULL(RTD.IsTaxInclude,0) = 1
				THEN (RD.Amount - (RD.Amount * 100) / (ISNULL(R.TaxPercentage,0) + 100))
				ELSE ISNULL(RTD.TaxAmount,0) END AS DECIMAL(12, 2)) AS TaxAmount,	
			CAST(CASE WHEN ISNULL(RTD.TaxTypeId,0) = 1 AND ISNULL(RTD.IsTaxInclude,0) = 1
				THEN (RD.Amount * 100) / (ISNULL(R.TaxPercentage,0) + 100) 
				ELSE RD.Amount END AS DECIMAL(12, 2)) AS TotalWithoutTax,
			CAST(CASE WHEN ISNULL(RTD.TaxTypeId,0) = 2
				THEN (RD.Amount + (RD.Amount * ISNULL(R.TaxPercentage,0) / 100))
				ELSE RD.Amount END AS DECIMAL(12, 2)) AS TotalWithTax

		  FROM   
			sFee.tReceipt R   
    
			INNER JOIN sStudent.vStudentAcademic SA  
			ON SA.AcademicId=R.SourceId AND ((SA.OrgId=@rOrgId) OR (@rOrgId=0)) 
			INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id
			INNER JOIN sFee.tReceiptTaxDetail RTD ON RD.ReceiptId = RTD.ReceiptId AND RD.FeeSetupId = RTD.FeeSetupId 
			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 (  
		  (@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 (ISNULL(SA.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')    
		 AND (ISNULL(R.PayTypeId,0) IN (SELECT cast(item as tinyint) FROM sCommon.fnsplit(@rPayTypeIds,',')) OR @rPayTypeIds='')  		 
	END 
END
GO
PRINT N'Creating Procedure [sFee].[pRptFeeReceiptWithTaxDetailsGet]...';


GO


CREATE PROCEDURE [sFee].[pRptFeeReceiptWithTaxDetailsGet]
						
			@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.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,			
			CASE WHEN ISNULL(FR.ChequeNo,'') != '' THEN FR.ChequeNo ELSE CONVERT(nvarchar(20),ISNULL(FR.PaymentTransactionId,''))  END 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,
			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 = 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,					
			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,
			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,
			(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,
			ISNULL(FRTD.TaxAmount,0) AS TaxAmount,
			ISNULL(FR.TaxPercentage,0) AS TaxPercentage,
			RBM.TaxLabel,
			RBM.TaxTypeId		-- 1 : Inclusive and 2 : Exclusive
	
		FROM
			sFee.tReceipt FR				
			INNER JOIN sFee.tReceiptDetail FRD ON FR.Id=FRD.ReceiptId AND FR.SourceTypeId=2001
			LEFT JOIN sFee.tReceiptTaxDetail FRTD ON FRD.ReceiptId=FRTD.ReceiptId	AND FRD.FeeSetupId = FRTD.FeeSetupId
			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
			LEFT JOIN (SELECT * FROM [sFee].[fNextInstallmentDetailsGet](@rReceiptBookId, @rReceiptId)) NID
			ON NID.SourceId = FR.SourceId AND NID.SourceTypeId = FR.SourcetypeId
	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,
--Convert(Decimal,0) AS TaxAmount,
--Convert(Decimal,0) AS TaxPercentage,
--'' AS TaxLabel,
--0 AS TaxTypeId
--END
GO
PRINT N'Creating Procedure [sFee].[pRptReceiptSummaryWithTaxGet]...';


GO

 
CREATE PROCEDURE [sFee].[pRptReceiptSummaryWithTaxGet]
	@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,
	@rOrgIds nvarchar(max) = '',
	@rClassStatusId int=0,
	@rPayTypeIds nvarchar(max) = '' 
	    
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
BEGIN 
	SELECT 
		@rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,
		@rIsDetail AS IsDetail,
		@rIsCancel AS IsCancel,
		@rIsFilter As IsFilter,
		@rIsHeader As IsHeader,
		@rIsDisplayOrgGroup AS IsDisplayOrgGroup,
		R.Id AS ReceiptId,
		R.ReceiptNumber,
		SA.ClassId,
		SA.DivisionId,
		SA.ClassName+' - '+SA.DivisionName AS ClassDivision,
		SA.RollNo,
		SA.Code,
		SA.Name,
		ISNULL(PTM.Id,0) AS PayTypeId,
		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,
		R.CreatedUserId,
		ISNULL(U.LoginTitle,'') AS UserName,
		ISNULL(RBM.Id,0) As ReceiptBookId,
		ISNULL(RBM.OrderIndex,0) As ReceiptBookOrderIndex,
		ISNULL(RBM.Title,'') AS ReceiptBookTitle,
		ISNULL(RBM.BankName,'') AS ReceiptBookBank,
		ISNULL(RBM.BankAccountNumber,'') AS BankAccountNumber,
		R.Remark,
		SA.OrgId,
		SA.OrganizationName,
		@rCustomGroupId AS CustomGroupId,
		FM.Id AS FeeId,
		FM.Title AS FeeName,
		FM.OrderIndex AS FeeOrderIndex,
		FHM.Id AS FeeHeadId,
		FHM.OrderIndex AS FeeHeadOrderIndex,
		FHM.Title AS FeeHeadName,
		[sFee].[fDatewiseFromToReceiptNumberGet](R.ReceiptBookId,R.BatchId,R.ReceiptDate) AS FromToReceiptNumber,
		CAST(CASE WHEN ISNULL(RTD.TaxTypeId,0) = 1 AND ISNULL(RTD.IsTaxInclude,0) = 1
				THEN (RD.Amount - (RD.Amount * 100) / (ISNULL(R.TaxPercentage,0) + 100))
				ELSE ISNULL(RTD.TaxAmount,0) END AS DECIMAL(12, 2)) AS TaxAmount,		
		ISNULL(RTD.TaxTypeId,0) AS TaxTypeId,
		CASE WHEN ISNULL(RTD.TaxTypeId,0) = 1 THEN 'Inclusive'
			 WHEN ISNULL(RTD.TaxTypeId,0) = 2 THEN 'Exclusive'
			 ELSE '' END AS TaxType,
		ISNULL(RTD.IsTaxInclude,0) AS IsTaxInclude,
		ISNULL(R.TaxPercentage,0) AS TaxPercentage,
		CAST(CASE WHEN ISNULL(RTD.TaxTypeId,0) = 1 AND ISNULL(RTD.IsTaxInclude,0) = 1
				THEN (RD.Amount * 100) / (ISNULL(R.TaxPercentage,0) + 100) 
				ELSE RD.Amount END AS DECIMAL(12, 2)) AS TotalWithoutTax,
		CAST(CASE WHEN ISNULL(RTD.TaxTypeId,0) = 2
				THEN (RD.Amount + (RD.Amount * ISNULL(R.TaxPercentage,0) / 100))
				ELSE RD.Amount END AS DECIMAL(12, 2)) AS TotalWithTax

	FROM 
		sFee.tReceipt R
		INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id
		INNER JOIN sFee.tReceiptTaxDetail RTD ON RD.ReceiptId = RTD.ReceiptId AND RD.FeeSetupId = RTD.FeeSetupId
		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
		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 (SA.StatusId=@rStatusId OR @rStatusId=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 (
				(@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 (ISNULL(SA.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='') 
		AND ((SA.ClassStatusId=@rClassStatusId) OR (@rClassStatusId=0)) 
		AND (ISNULL(R.PayTypeId,0) IN (SELECT cast(item as tinyint) FROM sCommon.fnsplit(@rPayTypeIds,',')) OR @rPayTypeIds='')
		--AND ISNULL(RTD.TaxAmount,0) <> 0     
	ORDER BY 
		R.ReceiptNumber
END
GO
PRINT N'Creating Procedure [sPayroll].[pGetTaxDetails]...';


GO
CREATE PROCEDURE [sPayroll].[pGetTaxDetails]
	 @rEmployeeId bigint,
	 @rAssesmentYearId bigint,
	 @rOrgGroupId int
AS
SET NOCOUNT ON

BEGIN

SELECT ITG.Id as 'GroupID'
		  ,ITSG.Id as 'SubGroupID'
		  ,ISNULL(ITG.GroupCode,'') +'  '+ ISNULL(ITG.DisplayName,'') +'  '+ ISNULL(ITG.ActionName,'') as 'GroupName'
		  ,ITSG.SubGroupName 
		  ,ISNULL(d.GrossAmount,0)GrossAmount
		  ,ITSG.QualifyingLimit as  QualifyingAmount
		  ,ISNULL(d.DeductibleAmount,0)DeductibleAmount
		  ,ITSG.IsEditable
		  ,d.Form16Id
	FROM [siTax].[tStaticIncomeTaxGroup] AS ITG 
		 LEFT JOIN [siTax].[tStaticIncomeTaxSubGroup] AS ITSG on ITG.Id=ITSG.StaticIncomeTaxGroupId
		 LEFT JOIN (SELECT f.Id AS Form16Id,fd.IncomeTaxSubgroupId,	fd.GrossAmount,	fd.QualifyingAmount,	fd.DeductibleAmount
				    FROM [siTax].[tForm16] as f
					INNER JOIN [siTax].[tForm16Detail] as fd on f.id =fd.Form16Id
	                WHERE f.EmployeeId=@rEmployeeId AND AssesmentYearId=@rAssesmentYearId 
	                AND OrgGroupId=@rOrgGroupId) AS d ON d.IncomeTaxSubgroupId=ITSG.id
	
	ORDER by ITG.OrderIndex,ITSG.OrderIndex

END
GO
PRINT N'Creating Procedure [sPayroll].[pPayrollGetForIncomeTax]...';


GO
CREATE PROCEDURE [sPayroll].[pPayrollGetForIncomeTax]
	 @rEmployeeId BIGINT,
     @rPayrollYearId INT
AS
SET NOCOUNT ON

BEGIN
	  SELECT PPE.PayElementId,
			 PE.Code AS PayElement,
			 PPE.Amount,
			 PET.Title AS PayElementType,
			 PayElementTypeId,
			 PPE.PayProcessEmployeeId,
			 ISNULL(PE.IsIncludeInTotal,0) AS IsIncludeInTotal
		 FROM 
			 sPayroll.tPayProcessElement PPE 
			 INNER JOIN sPayroll.tPayElement PE ON PPE.PayElementId = PE.ID
			 INNER JOIN sPayroll.tPayElementType PET ON PET.Id = PE.PayElementTypeId
		 WHERE 
		 PayProcessEmployeeId in 
		 (select PPE.Id from sPayroll.tPayProcessEmployee PPE
			INNER JOIN sPayroll.tPayProcess AS PP ON PP.ID=PPE.PayProcessId   
			where EmployeeId = @rEmployeeId AND PP.PayrollYearId = (select TOP 1 PayRollId from sPayroll.tPayrollYearMaster Where Id = @rPayrollYearId))
		 AND PE.IsIncludeInPaySlip = 1
		 ORDER BY SortOrder
END
GO
PRINT N'Creating Procedure [sRecruitment].[pCandidateFamilyDetailsXMLAdd]...';


GO

CREATE PROCEDURE [sRecruitment].[pCandidateFamilyDetailsXMLAdd]
    
	@rCandidateFamilyDetailsXml [nvarchar](max),
    @rId bigint,
	@rOrgGroupId smallint,
	@rCandidateId bigint,
	@rCreatedUserId bigint

	WITH EXECUTE AS CALLER
	AS
	SET NOCOUNT ON

	BEGIN
		DECLARE @lInterrorCode INT,@intDoc INT
		DECLARE @lNextNumber BIGINT	

		EXECUTE @lInterrorCode = sp_xml_preparedocument @intDoc OUTPUT, @rCandidateFamilyDetailsXml

		BEGIN TRY
		DELETE FROM sRecruitment.tCandidateFamilyDetails WHERE  CandidateId=@rCandidateId

		CREATE TABLE #tempTable  
		(
		Id bigint identity,
		OrgGroupId smallint ,
		CandidateId bigint ,
		RelationshipId Int ,
		Name nvarchar(100) ,
		DateOfBirth date,
		BloodGroupId Int ,
		IsActive bit ,
		Occupation nvarchar(100) ,
		CreatedUserId bigint ,
		CreatedDateTime datetime ,
		UpdatedUserId bigint ,
		UpdatedDateTime datetime 
		)

		INSERT INTO #tempTable(
		OrgGroupId  ,
		CandidateId  ,
		RelationshipId ,
		Name ,
		DateOfBirth,
		BloodGroupId ,
		IsActive ,
		Occupation,
		CreatedUserId ,
		CreatedDateTime ,
		UpdatedUserId ,
		UpdatedDateTime   
		)

		SELECT
				@rOrgGroupId,
				@rCandidateId,
				RelationshipId,
				Name,
				(CASE WHEN DateOfBirth ='1900-01-01' THEN NULL ELSE CONVERT(Date,DateOfBirth ,103)   END) AS DateOfBirth,					 
				BloodGroupId,
				0,
				Occupation,
				@rCreatedUserId,
				sCommon.fGetDate(),
				@rCreatedUserId,
				sCommon.fGetDate()				

		FROM OPENXML (@intDoc, '/Table/CandidateFamilyDetails', 1)
		WITH ( 
				CandidateId bigint ,
				RelationshipId Int ,
				Name nvarchar(100) ,
				DateOfBirth varchar(100),
				BloodGroupId Int ,
				IsActive bit,
				Occupation nvarchar(100)
			  )

		DECLARE @lCount int,@lId int
		SELECT @lCount = COUNT(Id) FROM #tempTable
		SELECT Top 1 @lId=Id FROM #tempTable

		WHILE @lId <= @lCount 

		BEGIN

		EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sRecruitment.tCandidateFamilyDetails', 0, 1, 1,@outNextNumber = @lNextNumber output

		INSERT INTO sRecruitment.tCandidateFamilyDetails
		(	
			Id,
			OrgGroupId  ,
			CandidateId  ,
			RelationshipId ,
			Name ,
			DateOfBirth,
			BloodGroupId ,
			IsActive ,
			Occupation,			
			CreatedUserId,
			CreatedDateTime,
			UpdatedUserId,
			UpdatedDateTime
				  
		)
		Select
		@lNextNumber,
		tmp.OrgGroupId,
		tmp.CandidateId,
		tmp.RelationshipId,
		tmp.Name,
		tmp.DateOfBirth,
		tmp.BloodGroupId,
		tmp.IsActive,
		tmp.Occupation,
		tmp.CreatedUserId,
		tmp.CreatedDateTime,
		tmp.UpdatedUserId,
		tmp.UpdatedDateTime
		FROM  #tempTable tmp 
		where  Id = @lId

		SET @lId=@lId+1

	END
    EXEC sp_xml_removedocument @intDoc
    SELECT 1 as Result
    DROP Table #tempTable
    END TRY	

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


GO
CREATE PROCEDURE [sStudent].[pXMLBirthDateInWordUpdate]
	(
		@rXmlDoc nvarchar(MAX)
	)
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 sStudent.tStudentOther
		Set
			BirthDateInWord=A.BirthDateInWord,
			UpdatedUserId = A.UserId,
			UpdatedDateTime =sCommon.fGetDate()
		FROM
		(SELECT
			StudentId ,
			BirthDateInWord,
			UserId	
			FROM OPENXML (@intDoc, '/Table/StudentBirthDateInWord', 1)
			WITH
			(
			StudentId Bigint,
			BirthDateInWord nvarchar(150),
			UserId nvarchar(25)
		))A
		WHERE A.StudentId = sStudent.tStudentOther.StudentId
		
		EXEC sp_xml_removedocument @intDoc
	COMMIT TRANSACTION
		SELECT 1
	END TRY
	BEGIN CATCH
		ROLLBACK TRANSACTION
		SELECT -1
	END CATCH
END
GO

PRINT N'Altering Procedure [sFee].[pFeeReceiptImportValidate]...';


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

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

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

BEGIN

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

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

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


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

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

	DECLARE @lItemValue nvarchar(20) = ''
	SELECT @lItemValue = CASE WHEN CS.Id IS NOT NULL THEN ISNULL(CS.ItemValue,'') ELSE ISNULL(CM.ItemValue,'') END
	FROM sConfig.tConfigurationMaster CM
	LEFT JOIN sConfig.tConfigurationSetup CS ON CM.Id = CS.ConfigurationId
	AND SourceTypeId = 1016 AND SourceId = @rOrgId WHERE CM.Id = 239

	-- GST
	DECLARE @lAmountAfterDiscount decimal(12,2) = NULL
	DECLARE @lCGSTPercentage decimal(12,2)  = NULL
	DECLARE @lSGSTPercentage decimal(12,2)  = NULL
	DECLARE @lCGSTAmount decimal(12,2)  = NULL
	DECLARE @lSGSTAmount decimal(12,2)  = NULL

	IF(@lItemValue='True' AND @rPayTypeId = 1)
	BEGIN 
		SET @lAmountAfterDiscount = 0
		SET @lCGSTAmount = 0
		SET @lSGSTAmount = 0
		SET @lCGSTPercentage = 0
		SET @lSGSTPercentage = 0
	END
	ELSE
	BEGIN 		
		SET @lAmountAfterDiscount = @rTotalReceiptAmount - @rDiscountAmount
		SELECT @lCGSTPercentage = CGSTPercentage,@lSGSTPercentage = SGSTPercentage FROM sFee.tReceiptBookMaster WHERE Id = @rReceiptBookId
		SET @lCGSTAmount = @rReceiptAmount*@lCGSTPercentage / 100
		SET @lSGSTAmount = @rReceiptAmount*@lSGSTPercentage / 100
		SET @rReceiptAmount = @lAmountAfterDiscount + @lCGSTAmount + @lSGSTAmount
	END
-- GST
	
	DECLARE @loDoc INT
	DECLARE @lIsCreated INT
	EXEC sp_xml_preparedocument @loDoc OUTPUT, @rReceiptDetailXml

	BEGIN
	BEGIN TRY

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

	 IF @lConfigValue IS NULL 
		SET @lConfigValue = 'ReceiptBookWise'
	 
	IF(@rReceiptNumber <> 0)
	BEGIN
		IF(@lConfigValue='ReceiptBookWise')
		BEGIN
			IF EXISTS(SELECT 1 from sFee.tReceipt where ReceiptNumber=@rReceiptNumber AND ReceiptBookId=@rReceiptBookId AND OrgGroupBatchId = @rOrgGroupBatchId)
			BEGIN
				SELECT -102 AS Result
				RETURN	
			END
		END
		ELSE IF(@lConfigValue='PayTypeWise')
		BEGIN
			IF EXISTS(SELECT 1 from sFee.tReceipt where ReceiptNumber=@rReceiptNumber AND ReceiptBookId=@rReceiptBookId AND  PayTypeId=@rPayTypeId AND OrgGroupBatchId = @rOrgGroupBatchId)
			BEGIN
				SELECT -102 AS Result
				RETURN	
			END
		END
	END
	ELSE
	BEGIN
		SET @rReceiptNumber = sFee.fReceiptNumberGet(@rReceiptBookId,@rOrgGroupBatchId,@rPayTypeId,@lConfigValue)
		Print @rReceiptNumber
	END	

	EXECUTE [sFee].[pReceiptAddValidate] @rSourceId,'',@rReceiptDetailXml,@rPayTypeId,@rPaymentTransactionId,@rIsCreated = @lIsCreated OUTPUT
 	
	IF(@lIsCreated = 1)
 	BEGIN
		SELECT -501 AS Result
		RETURN
	END
	
	IF(@lIsCreated = -1)	-- For Mantis 0032370 by Foram
 	BEGIN
		SELECT -502 AS Result
		RETURN
	END
 
	 BEGIN TRANSACTION	
	 IF(@rId = 0)	
	 BEGIN

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


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

		SET @rId = @lNextNumber
	END 
	ELSE
	BEGIN
		UPDATE sFee.tReceipt SET
			ReceiptDate=@rReceiptDate,
			PayTypeId=@rPayTypeId,
			ChequeDate=@rChequeDate,
		    ChequeNo=@rChequeNo,
		    BankName=@rBankName,
		    Remark=@rRemark
		WHERE Id=@rId
		
		SELECT @rId AS RESULT
	END 
		
	-- For Mantis 0023321 By Foram on 14/03/2024 START
	DECLARE @lSourceId bigint, @lSourceTypeId1 smallint, @lBatchId int, @lOrgGroupBatchId int, @lReceiptBookId int, 
		    @lPayTypeId smallint, @lChequeNo nvarchar(40), @lBankName nvarchar(200), @lTotalReceiptAmount decimal(12,2)

	SELECT 
		@lSourceId = SourceId, 
		@lSourceTypeId1 = SourceTypeId, 
		@lBatchId = BatchId, 
		@lOrgGroupBatchId = OrgGroupBatchId, 
		@lReceiptBookId = ReceiptBookId, 
		@lPayTypeId = PayTypeId, 
		@lChequeNo = ChequeNo, 
		@lBankName = BankName, 
		@lTotalReceiptAmount = TotalReceiptAmount
	FROM sFee.tReceipt WHERE Id = @rId


	IF EXISTS(SELECT 1 FROM sFee.tPostDatePayment WHERE BatchId = @lBatchId AND OrgGroupBatchId = @lOrgGroupBatchId 
													AND SourceTypeId = @lSourceTypeId1 AND SourceId = @lSourceId AND ReceiptBookId = @lReceiptBookId 
													AND PayTypeId = @lPayTypeId AND ChequeNo = @lChequeNo AND BankName = @lBankName AND Amount = @lTotalReceiptAmount)
	BEGIN
		UPDATE sFee.tPostDatePayment 
		SET ReceiptId = @rId, StatusId = 752 
		WHERE BatchId = @lBatchId AND OrgGroupBatchId = @lOrgGroupBatchId 
			AND SourceTypeId = @lSourceTypeId1 AND SourceId = @lSourceId AND ReceiptBookId = @lReceiptBookId 
			AND PayTypeId = @lPayTypeId AND ChequeNo = @lChequeNo AND BankName = @lBankName AND Amount = @lTotalReceiptAmount
	END
	ELSE
	BEGIN
		UPDATE sFee.tPostDatePayment SET ReceiptId = 0, StatusId = 751 WHERE ReceiptId = @rId
	END
	-- For Mantis 0023321 By Foram on 14/03/2024 END
	
	COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Altering Procedure [sFee].[pReceiptAdd]...';


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

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

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

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

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

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

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

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

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

	EXECUTE [sFee].[pReceiptAddValidate] @rSourceId,'',@rReceiptDetailXml,@rPayTypeId,@rPaymentTransactionId,@rIsCreated = @lIsCreated OUTPUT -- Added ,@rPayTypeId,@rPaymentTransactionId for mantis 0031290 By Foram	

	IF(@lIsCreated = 1)
 	BEGIN
		SELECT -501 AS Result
		RETURN
	END
	IF(@lIsCreated = -1)	-- For Mantis 0032370 by Foram
 	BEGIN
		SELECT -502 AS Result
		RETURN
	END
 
	 BEGIN TRANSACTION	
	IF(@rId = 0)	
	BEGIN

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

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

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

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

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

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

		BEGIN
		UPDATE sFee.tReceipt SET
			ReceiptNumber = @rReceiptNumber,
			ReceiptDate=@rReceiptDate,
			PayTypeId=@rPayTypeId,
			ChequeDate=@rChequeDate,
		    ChequeNo=@rChequeNo,
		    BankName=@rBankName,
		    Remark=@rRemark
		WHERE Id=@rId
		
	SELECT @rId AS RESULT
	END 
	END
	
	-- For Mantis 0023321 By Foram on 14/03/2024 START
	DECLARE @lSourceId bigint, @lSourceTypeId1 smallint, @lBatchId int, @lOrgGroupBatchId int, @lReceiptBookId int, 
		    @lPayTypeId smallint, @lChequeNo nvarchar(40), @lBankName nvarchar(200), @lTotalReceiptAmount decimal(12,2)

	SELECT 
		@lSourceId = SourceId, 
		@lSourceTypeId1 = SourceTypeId, 
		@lBatchId = BatchId, 
		@lOrgGroupBatchId = OrgGroupBatchId, 
		@lReceiptBookId = ReceiptBookId, 
		@lPayTypeId = PayTypeId, 
		@lChequeNo = ChequeNo, 
		@lBankName = BankName, 
		@lTotalReceiptAmount = TotalReceiptAmount
	FROM sFee.tReceipt WHERE Id = @rId


	IF EXISTS(SELECT 1 FROM sFee.tPostDatePayment WHERE BatchId = @lBatchId AND OrgGroupBatchId = @lOrgGroupBatchId 
													AND SourceTypeId = @lSourceTypeId1 AND SourceId = @lSourceId AND ReceiptBookId = @lReceiptBookId 
													AND PayTypeId = @lPayTypeId AND ChequeNo = @lChequeNo AND BankName = @lBankName AND Amount = @lTotalReceiptAmount)
	BEGIN
		UPDATE sFee.tPostDatePayment 
		SET ReceiptId = @rId, StatusId = 752 
		WHERE BatchId = @lBatchId AND OrgGroupBatchId = @lOrgGroupBatchId 
			AND SourceTypeId = @lSourceTypeId1 AND SourceId = @lSourceId AND ReceiptBookId = @lReceiptBookId 
			AND PayTypeId = @lPayTypeId AND ChequeNo = @lChequeNo AND BankName = @lBankName AND Amount = @lTotalReceiptAmount
	END
	ELSE
	BEGIN
		UPDATE sFee.tPostDatePayment SET ReceiptId = 0, StatusId = 751 WHERE ReceiptId = @rId
	END
	-- For Mantis 0023321 By Foram on 14/03/2024 END

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

PRINT N'Update complete.';


GO


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

