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

PRINT N'Altering Table [sAssessment].[tTempAllExamResultSheet]...';


GO
ALTER TABLE [sAssessment].[tTempAllExamResultSheet]
    ADD [ResultSheetAdditionalTitle] NVARCHAR (100) NULL;


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


GO
ALTER TABLE [sAssessment].[tTempAllExamWithAllTerm]
    ADD [ResultIndicator]          NVARCHAR (50) NULL,
        [IsDisplayResultIndicator] BIT           NULL;


GO
PRINT N'Altering Table [sCommunication].[tBehaviour]...';


GO
ALTER TABLE [sCommunication].[tBehaviour] ALTER COLUMN [Remark] NVARCHAR (1000) NOT NULL;


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


GO
CREATE TABLE [sFee].[tFeeReceiptLog] (
    [AutoId]               INT             IDENTITY (1, 1) NOT NULL,
    [OrgId]                INT             NOT NULL,
    [Id]                   BIGINT          NOT NULL,
    [SourceTypeId]         SMALLINT        NULL,
    [SourceId]             BIGINT          NULL,
    [ReceiptNumber]        INT             NULL,
    [ReceiptDate]          DATE            NULL,
    [ReceiptAmount]        DECIMAL (12, 2) NULL,
    [TotalReceiptAmount]   DECIMAL (12, 2) NULL,
    [DiscountAmount]       DECIMAL (12, 2) NULL,
    [PayTypeId]            TINYINT         NULL,
    [ChequeNo]             NVARCHAR (40)   NULL,
    [BankName]             NVARCHAR (200)  NULL,
    [ReceiptBookId]        INT             NULL,
    [IsObsolete]           BIT             NULL,
    [CreatedUserId]        BIGINT          NULL,
    [BatchId]              INT             NULL,
    [OrgGroupBatchId]      INT             NULL,
    [Remark]               NVARCHAR (200)  NULL,
    [ReceiptDetailXml]     NVARCHAR (MAX)  NULL,
    [ChequeDate]           DATE            NULL,
    [Charge]               DECIMAL (12, 2) NULL,
    [FeeInvoiceId]         BIGINT          NULL,
    [CollectionGroupId]    INT             NULL,
    [DepositedLedgerId]    INT             NULL,
    [PaymentTransactionId] BIGINT          NULL,
    [ReceiptPrintGroupId]  NVARCHAR (100)  NULL,
    [IsDiscountCoupon]     BIT             NULL,
    [LogDateTime]          DATETIME        NULL,
    [Activity]             NVARCHAR (200)  NULL,
    PRIMARY KEY CLUSTERED ([AutoId] ASC) WITH (FILLFACTOR = 85)
);


GO
PRINT N'Creating Table [sSecurity].[tMigrationModulePermission]...';


GO
CREATE TABLE [sSecurity].[tMigrationModulePermission] (
    [AutoId]          INT           IDENTITY (1, 1) NOT NULL,
    [OrgGroupId]      SMALLINT      NULL,
    [Key]             VARCHAR (MAX) NOT NULL,
    [Value]           VARCHAR (MAX) NULL,
    [ERPProductId]    SMALLINT      NULL,
    [Status]          BIT           NULL,
    [CreatedDateTime] DATETIME      NOT NULL,
    [UpdatedDateTime] DATETIME      NULL,
    PRIMARY KEY CLUSTERED ([AutoId] ASC)
);


GO
PRINT N'Creating Index [sCommon].[tTableRowId].[IX_tTableRowId_Org_Table]...';


GO
CREATE NONCLUSTERED INDEX [IX_tTableRowId_Org_Table]
    ON [sCommon].[tTableRowId]([OrgId] ASC, [TableTitle] ASC);


GO
PRINT N'Creating Index [sCommon].[tTableRowId].[IX_tTableRowId_TableTitle]...';


GO
CREATE NONCLUSTERED INDEX [IX_tTableRowId_TableTitle]
    ON [sCommon].[tTableRowId]([TableTitle] ASC)
    INCLUDE([CurrentNumber]);


GO
PRINT N'Creating Default Constraint unnamed constraint on [sSecurity].[tMigrationModulePermission]...';


GO
ALTER TABLE [sSecurity].[tMigrationModulePermission]
    ADD DEFAULT (getdate()) FOR [CreatedDateTime];


GO
PRINT N'Altering View [sFee].[vFeeColumnName]...';


GO
ALTER VIEW [sFee].[vFeeColumnName]

AS

SELECT
		--SA.AcademicId,
		--SA.ClassId,
		--SA.DivisionId,
		SA.SUId,
		SA.RollNo,
		--SA.OrgId,
		--SA.BatchId,
		OGBM.Title AS OrgGroupBatch,
		OM.Title AS Organization,
		BM.Title AS Batch,
		--SA.StudentId,
		SA.Code AS [ID No],
		SA.Code AS [GR No],
		SA.Number,
		SA.FirstName,
		SA.LastName,
		SA.Name,
		--SA.DepartmentId,
		--SA.StatusId,
		SA.ClassName,
		SA.DivisionName,
		SA.StatusName,
		--FA.VariableAmount,
		--FA.DiscountAmount,
		--FA.AdditionalAmount,
		--FA.NotApplicable,
		--FCM.Number AS FeeCategoryNumber,
		--FCM.Code AS FeeCategoryCode,
		--FCM.Title AS FeeCategoryName,
		--FCM.OrderIndex AS FeeCategoryOrderIndex,
		--FHM.Code AS FeeHeadCode,
		--FHM.Title AS FeeHeadTitle,
		--FM.Code AS FeeCode,
		--FM.Number AS FeeNumber,
		--FM.Title AS FeeName,
		--FM.OrderIndex AS FeeOrderIndex,
		--FS.Amount AS FeeSetupAmount,
		--FS.StartDate,
		--FS.EndDate,
		R.ReceiptNumber,
		R.ReceiptDate,
		R.ReceiptAmount,
		R.ChequeNo,
		R.ChequeDate,
		R.ChequeClearDate,
		R.BankName,
		R.Remark,
		RBM.Code AS ReceiptBookCode,
		RBM.Title AS ReceiptBookName,
		RBM.Address1,
		RBM.Address2,
		RBM.BankAccountNumber,
		--RD.Amount AS ReceiptDetailAmount,
		PTM.Title AS PayType,
		U.DisplayTitle AS CreatedUserName,
		SC.ParentContactNo,
		R.CreatedDateTime,
		STUFF(
			COALESCE(',' + NULLIF(SC.PresentStreetOne, ''), '')  +
			COALESCE(',' + NULLIF(SC.PresentStreetTwo, ''), '') +
			COALESCE(',' + NULLIF(SC.PresentStreetThree, ''), '') +
			COALESCE(',' + NULLIF(SC.PresentCity, ''), '') +
			COALESCE(',' + NULLIF(SC.PresentState, ''), '') +
			COALESCE(',' + NULLIF(SC.PresentCountry, ''), '') +
			COALESCE(',' + NULLIF(SC.PresentZipCode, ''), '') +
			COALESCE(',' + NULLIF(SC.PresentContactNo, ''), ''),
			1, 1, '') AS LocalAddress,  --changes the Sequence of the country, City, State by dhanajay for Mantis :40680
		ISNULL(ACM.Title,'') AS [Fees Category]  --mantis: 42471, add

FROM
		sStudent.vStudentAcademic SA
		INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=SA.OrgGroupBatchId
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=SA.OrgId
		INNER JOIN sSetup.tBatchMaster BM ON BM.Id=SA.BatchId
		--INNER JOIN sFee.tFeeAllocation FA ON FA.SourceId=SA.AcademicId
		INNER JOIN sFee.tReceipt R ON R.SourceId=SA.AcademicId
		INNER JOIN sFee.tReceiptBookMaster RBM ON RBM.Id=R.ReceiptBookId
		--INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId=R.Id
		--INNER JOIN sFee.tFeeSetup FS ON FS.Id=RD.FeeSetupId
		--INNER JOIN sFee.tFeeCategoryMaster FCM ON FCM.Id=FS.FeeCategoryId
		--INNER JOIN sFee.tFeeCategoryClass FCC ON FCC.FeeCategoryId=FCM.Id
		--INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS.FeeId
		--INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FM.FeeHeadId
		INNER JOIN sFinanceCommon.tPayTypeMaster PTM ON PTM.Id=R.PayTypeId
		INNER JOIN sSecurity.tUser U ON U.Id=R.CreatedUserId
		LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId=SA.StudentId
		LEFT JOIN sStudent.tAdmissionCategoryMaster ACM ON ACM.Id=SA.AdmissionCategoryId  --mantis: 42471, add
GO
PRINT N'Altering View [sFee].[vFeeCustomSearch]...';


GO
ALTER VIEW [sFee].[vFeeCustomSearch]

AS

SELECT
		SA.AcademicId,
		SA.ClassId,
		SA.DivisionId,
		SA.RollNo,
		SA.OrgGroupBatchId,
		SA.OrgId,
		SA.BatchId,
		OGBM.Title AS OrgGroupBatch,
		OM.Title AS Organization,
		BM.Title AS Batch,
		SA.StudentId,
		SA.Code,
		SA.Number,
		SA.FirstName,
		SA.LastName,
		SA.Name,
		SA.StatusId,
		SA.ClassName,
		SA.DivisionName,
		SA.StatusName,
		--FA.Id AS FeeAllocationId,
		--FA.VariableAmount,
		--FA.DiscountAmount,
		--FA.AdditionalAmount,
		--FA.NotApplicable,
		--FCC.IsCommon,
		--FCM.Id AS FeeCategoryId,
		--FCM.Number AS FeeCategoryNumber,
		--FCM.Code AS FeeCategoryCode,
		--FCM.Title AS FeeCategoryName,
		--FCM.OrderIndex AS FeeCategoryOrderIndex,
		--FHM.Id AS FeeHeadId,
		--FHM.Code AS FeeHeadCode,
		--FHM.Title AS FeeHeadTitle,
		--FM.Id AS FeeId,
		--FM.Code AS FeeCode,
		--FM.Number AS FeeNumber,
		--FM.Title AS FeeName,
		--FM.OrderIndex AS FeeOrderIndex,
		--FS.Id AS FeeSetupId,
		--FS.IsVariable,
		--FS.Amount AS FeeSetupAmount,
		--FS.StartDate,
		--FS.EndDate,
		R.Id AS ReceiptId,
		R.ReceiptNumber,
		R.ReceiptDate,
		R.ReceiptAmount,
		R.ChequeNo,
		R.ChequeDate,
		R.ChequeClearDate,
		R.BankName,
		R.Remark,
		R.IsObsolete,
		RBM.Id AS FeeReceiptBookId,
		RBM.Code AS ReceiptBookCode,
		RBM.Title AS ReceiptBookName,
		RBM.Address1,
		RBM.Address2,
		RBM.BankAccountNumber,
		--RD.Amount AS ReceiptDetailAmount,
		PTM.Id AS PayTypeId,
		PTM.Title AS PayType,
		U.Id AS CreatedUserId,
		U.DisplayTitle AS CreatedUserName,
		SA.SUId,
		SA.AdmissionCategoryId,
		SC.ParentContactNo,
		R.CreatedDateTime,
		STUFF(
			COALESCE(',' + NULLIF(SC.PresentStreetOne, ''), '')  +
			COALESCE(',' + NULLIF(SC.PresentStreetTwo, ''), '') +
			COALESCE(',' + NULLIF(SC.PresentStreetThree, ''), '') +
			COALESCE(',' + NULLIF(SC.PresentCity, ''), '') +
			COALESCE(',' + NULLIF(SC.PresentState, ''), '') +
			COALESCE(',' + NULLIF(SC.PresentCountry, ''), '') +
			COALESCE(',' + NULLIF(SC.PresentZipCode, ''), '') +
			COALESCE(',' + NULLIF(SC.PresentContactNo, ''), ''),
			1, 1, '') AS LocalAddress,--changes the Sequence of the country, City, State by dhanajay for Mantis :40680
		ISNULL(ACM.Title,'') AS [Fees Category]  --mantis: 42471, add

FROM
		sStudent.vStudentAcademic SA
		INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=SA.OrgGroupBatchId
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=SA.OrgId
		INNER JOIN sSetup.tBatchMaster BM ON BM.Id=SA.BatchId
		--LEFT JOIN sFee.tFeeAllocation FA ON FA.SourceId=SA.AcademicId
		INNER JOIN sFee.tReceipt R ON R.SourceId=SA.AcademicId
		INNER JOIN sFee.tReceiptBookMaster RBM ON RBM.Id=R.ReceiptBookId
		--INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId=R.Id
		--LEFT JOIN sFee.tFeeSetup FS ON FS.Id=RD.FeeSetupId
		--LEFT JOIN sFee.tFeeCategoryMaster FCM ON FCM.Id=FS.FeeCategoryId
		--LEFT JOIN sFee.tFeeCategoryClass FCC ON FCC.FeeCategoryId=FCM.Id
		--INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS.FeeId
		--INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FM.FeeHeadId
		INNER JOIN sFinanceCommon.tPayTypeMaster PTM ON PTM.Id=R.PayTypeId
		LEFT JOIN sSecurity.tUser U ON U.Id=R.CreatedUserId
		LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId = SA.StudentId
		LEFT JOIN sStudent.tAdmissionCategoryMaster ACM ON ACM.Id=SA.AdmissionCategoryId  --mantis: 42471, add
GO
PRINT N'Creating View [sHrm].[vPrintTemplateJoiningCertificateGet]...';


GO

CREATE VIEW [sHrm].[vPrintTemplateJoiningCertificateGet]  

 AS
   
 SELECT   
   EM.Id AS EmployeeId,
   CJ.Number,
   EM.EmployeeName,
   EM.FirstName,  
   EM.MiddleName,  
   EM.LastName,      
   EM.Code,    
   EM.ShortName,  
   EM.OrgID,  
   EM.DepartmentId,  
   EM.DepartmentName,  
   EM.DesignationId,  
   EM.Designation,  
   EM.EmployeePhoto, 
   EM.DateOfJoining,    
   OI.CertificateHeaderA4 ,  
   CJ.Remark,  
   ISNULL(CJ.CertificateDate,'') AS CertificateDate,  
   EM.MaritalStatusId,  
   CJ.PayScale,  
   CJ.AgreementPeriod,
   CJ.CertificateRemark,
   OM.Title As OrgTitle,
   CJ.CreatedDateTime As CreatedDateTime,
   U.DisplayTitle As UserDisplayName,
   EDM.Title AS EmployeeDesignation,
   OM.DisplayTitle As ShortTitle,
   DM.Title AS DepartmentName1,
   EM.MobileNumber,
    EC.PresentStreetOne  
	,EC.PresentStreetTwo 
	,EC.PresentStreetThree 
   ,EC.PresentCity
   ,EC.PresentState
   ,EC.PresentZipCode
   ,EC.PresentContactNo 	
   ,ISNULL(EDM1.Title,'Admin') AS UserDesignation,   
	ISNULL(CJ.DateOfJoining,'') As CertificateDateOfJoining,
	EM.GenderId
	,'[Number],[EmployeeName],[FirstName],[LastName],[Code],[ShortName],[DepartmentName],[Designation],[EmployeePhoto],[DateOfJoining],[CertificateHeaderA4]
	,[Remark],[CertificateDate],[PayScale],[AgreementPeriod],[CertificateRemark],[OrgTitle],[CreatedDateTime],[UserDisplayName]
	,[EmployeeDesignation],[ShortTitle],[DepartmentName1],[MobileNumber],[PresentStreetOne],[PresentStreetTwo],[PresentStreetThree]
	,[PresentCity],[PresentState],[PresentZipCode],[PresentContactNo],[UserDesignation],[CertificateDateOfJoining]' AS ColumnList

 FROM   
	  sHrm.tCertificateJoining CJ   
      INNER JOIN [sHrm].[vExtEmployeeMaster] EM  ON EM.EmployeeId=CJ.EmployeeId 
      INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=EM.OrgId   
      INNER JOIN  sSecurity.tUser U ON U.Id=CJ.CreatedUserId 
	  --AND U.SourceTypeId = 95
      INNER JOIN  sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.Id
	  INNER JOIN  sSetup.tDepartmentMaster DM ON DM.Id=CJ.DepartmentId
	  LEFT JOIN  sHrm.tEmployeeDesignationMaster EDM ON EDM.Id=EJD.EmployeeDesignationId  --added
	  LEFT JOIN  sHrm.tEmployeeCommunications EC ON EC.EmployeeId=CJ.EmployeeId  --added
	  LEFT JOIN sSetup.tOrgImages OI ON OI.OrgId = OM.Id 
      LEFT JOIN  sHrm.tEmployeeJobDetail EJD1 ON EJD1.EmployeeId=U.SourceId
	  LEFT JOIN  sHrm.tEmployeeDesignationMaster EDM1 ON EDM1.Id=EJD1.EmployeeDesignationId
GO
PRINT N'Altering Function [sFee].[fFeeActualAmountSumGet]...';


GO
ALTER 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.Id AS AcademicId,
				FM.Title AS FeeName			 
			FROM sFee.tFeeSetup FS1
			INNER JOIN sStudent.tAcademic SA1 -- Changed View to Academic Table for Optimization by Foram
			 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
			AND SA1.BatchId = BM.Id -- Added as changed View to Academic Table for Optimization by Foram
			WHERE 
			    --SA1.OrgGroupBatchId = @rOrgGroupBatchId AND -- Removed as changed View to Academic Table for Optimization by Foram
					((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.Id = @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].[fFeeAmountSumGet]...';


GO
ALTER FUNCTION [sFee].[fFeeAmountSumGet] (@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)+ISNULL(FA.AdditionalAmount,0.00) 
								-ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,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.Id AS AcademicId,
				FM.Title AS FeeName			 
			FROM sFee.tFeeSetup FS1
			INNER JOIN --sStudent.vStudentAcademic SA1 
				sStudent.tAcademic SA1 -- Changed View to Academic Table for Optimization by Foram
				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
			AND SA1.BatchId = BM.Id -- Added as changed View to Academic Table for Optimization by Foram
			WHERE 
			    --SA1.OrgGroupBatchId = @rOrgGroupBatchId AND -- Removed as changed View to Academic Table for Optimization by Foram
					((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.Id = @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.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 --sStudent.vStudentAcademic SA1
				sStudent.tAcademic SA1 -- Changed View to Academic Table for Optimization by Foram
				ON SA1.Id=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
		AND SA1.BatchId = BM.Id -- Added as changed View to Academic Table for Optimization by Foram
		WHERE
		        --SA1.OrgGroupBatchId = @rOrgGroupBatchId AND  -- Removed as changed View to Academic Table for Optimization by Foram
				 ((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.Id = @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].[fFeeHeadMonthNameGet]...';


GO
ALTER FUNCTION [sFee].[fFeeHeadMonthNameGet](@rReceiptId BIGINT, @rFeeHeadId INT)
RETURNS NVARCHAR(200) WITH EXECUTE AS CALLER
AS 
BEGIN
    DECLARE @rResult NVARCHAR(200)

    ;WITH FeeMonths AS
    (
        SELECT 
            FirstFee = [sCommon].[fGetMonthName](Month(S.StartDate)),
            LastFee = [sCommon].[fGetMonthName](Month(S.EndDate))
        FROM 
            sFee.tReceiptDetail D
        INNER JOIN sFee.tFeeSetup S ON D.FeeSetupId = S.Id
        INNER JOIN sFee.tFeeMaster F ON S.FeeId = F.Id
        WHERE 
            D.ReceiptId = @rReceiptId 
            AND F.FeeHeadId = @rFeeHeadId
            AND F.Number <> 100
        ORDER BY F.OrderIndex
        OFFSET 0 ROWS FETCH NEXT 1 ROWS ONLY
    )
    SELECT 
        @rResult = 
            CASE 
                WHEN FirstFee = LastFee THEN FirstFee
                ELSE FirstFee + ' To ' + LastFee
            END
    FROM FeeMonths

    RETURN @rResult
END
GO
PRINT N'Altering Function [sFee].[fFeeMonthNameGet]...';


GO
ALTER FUNCTION [sFee].[fFeeMonthNameGet](@rReceiptId BIGINT, @rFeeId INT)
RETURNS NVARCHAR(200) WITH EXECUTE AS CALLER
AS 
BEGIN
    DECLARE @rResult NVARCHAR(200)

    ;WITH FeeMonths AS
    (
        SELECT 
            FirstFee = [sCommon].[fGetMonthName](Month(S.StartDate)),
            LastFee = [sCommon].[fGetMonthName](Month(S.EndDate))
        FROM 
            sFee.tReceiptDetail D
        INNER JOIN sFee.tFeeSetup S ON D.FeeSetupId = S.Id
        INNER JOIN sFee.tFeeMaster F ON S.FeeId = F.Id
        WHERE 
            D.ReceiptId = @rReceiptId 
            AND F.Id = @rFeeId
            AND F.Number <> 100
        ORDER BY F.OrderIndex
        OFFSET 0 ROWS FETCH NEXT 1 ROWS ONLY
    )
    SELECT 
        @rResult = 
            CASE 
                WHEN FirstFee = LastFee THEN FirstFee
                ELSE FirstFee + ' To ' + LastFee
            END
    FROM FeeMonths

    RETURN @rResult
END
GO
PRINT N'Altering Function [sFee].[fFeeReceiptDiscountSumGet]...';


GO
ALTER FUNCTION [sFee].[fFeeReceiptDiscountSumGet] (@rAcademicId bigint)
RETURNS decimal(12,0) WITH EXECUTE AS CALLER
AS 
BEGIN
    DECLARE @rTotalDicountAmount decimal(12,0)--,@rBatchId int, @rOrgId int
    --SELECT @rOrgId=OrgId,@rBatchId=BatchId FROM sStudent.tAcademic WHERE Id = @rAcademicId -- Commented for optmization By Foram
    
    (
    SELECT 
		@rTotalDicountAmount = SUM(ISNULL(FA.DiscountAmount,0.00))
    FROM 
			 sStudent.tAcademic A
		INNER JOIN sFee.tFeeAllocation FA ON FA.SourceId=A.Id AND FA.SourceTypeId = 2001
	WHERE	
		A.Id = @rAcademicId
		--AND ((A.OrgId=@rOrgId) OR (@rOrgId=0))	-- Commented for optmization By Foram
		--AND ((A.BatchId=@rBatchId) OR (@rBatchId=0))  -- Commented for optmization By Foram
	)
			
	RETURN ISNULL(@rTotalDicountAmount,0) 
END
GO
PRINT N'Altering Function [sFee].[fPendingFeeAmountReceiptBookwiseGet]...';


GO
ALTER FUNCTION [sFee].[fPendingFeeAmountReceiptBookwiseGet] (
	@rAcademicId BIGINT
	,@rReceiptBookId INT
	)
RETURNS DECIMAL(12, 0)
	WITH EXECUTE AS CALLER
AS
BEGIN
	DECLARE @rReceiptAmount 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 @rReceiptAmount 
	= SUM(ISNULL(FS.Amount, 0.00) + ISNULL(FA.VariableAmount, 0.00) + ISNULL(FA.AdditionalAmount, 0.00) 
	- ISNULL(FA.DiscountAmount, 0.00) - ISNULL(FA.NotApplicableAmount, 0.00) - ISNULL(R.PaidAmount, 0.00)) 
	
	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.Id AS AcademicId
				,FM.Title AS FeeName
			FROM sFee.tFeeSetup FS1
			INNER JOIN --sStudent.vStudentAcademic SA1 
				sStudent.tAcademic SA1 -- Changed View to Academic Table for Optimization by Foram
				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 
			AND SA1.BatchId = BM.Id -- Added as changed View to Academic Table for Optimization by Foram
			WHERE --SA1.OrgGroupBatchId = @rOrgGroupBatchId AND -- Removed as changed View to Academic Table for Optimization by Foram
				(
					(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.Id = @rAcademicId
				AND (
					FS1.ReceiptBookId = @rReceiptBookId
					OR @rReceiptBookId = 0
					)
			
			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 --sStudent.vStudentAcademic SA1
				sStudent.tAcademic SA1 -- Changed View to Academic Table for Optimization by Foram
				ON SA1.Id = 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
				AND SA1.BatchId = BM.Id -- Added as changed View to Academic Table for Optimization by Foram
			WHERE 
			--SA1.OrgGroupBatchId = @rOrgGroupBatchId AND  -- Removed as changed View to Academic Table for Optimization by Foram
				 (
					(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.Id = @rAcademicId
				AND (
					FS1.ReceiptBookId = @rReceiptBookId
					OR @rReceiptBookId = 0
					)
			) 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 
			LEFT JOIN (
			SELECT ISNULL(SUM(RD.Amount), 0) AS PaidAmount
				,RD.FeeSetupId
				,R.SourceId
			FROM sFee.tReceipt R
			INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id
			INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id
			INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id
			INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId = R.SourceId
				AND (SA1.ClassId = @lClassId OR @lClassId = 0)
				AND ((SA1.DivisionId = @lDivisionId) OR (@lDivisionId = 0))
				AND (SA1.DivisionId = @lDivisionId OR @lDivisionId = 0)
			WHERE (R.SourceTypeId = 2001)
				AND (
					(SA1.OrgId = @rOrgId)
					OR (@rOrgId = 0)
					)
				AND (R.IsObsolete = 0)
				AND ((SA1.OrgGroupBatchId = @rOrgGroupBatchId))
				AND (R.OrgGroupBatchId = @rOrgGroupBatchId)
				AND (
					(R.BatchId = @rBatchId)
					OR (@rBatchId = 0)
					)
				AND SA1.AcademicId = @rAcademicId
				AND (
					R.ReceiptBookId = @rReceiptBookId
					OR @rReceiptBookId = 0
					)
			GROUP BY FeeSetupId
				,R.SourceId
			) R ON R.FeeSetupId = FS.Id
			AND SA.AcademicId = R.SourceId WHERE SA.AcademicId = @rAcademicId
			AND SA.OrgGroupBatchId = @rOrgGroupBatchId
			AND (
				(SA.OrgId = @rOrgId)
				OR (@rOrgId = 0)
				)
			AND (
				(SA.BatchId = @rBatchId)
				OR (@rBatchId = 0)
				)
			AND (ISNULL(FS.Amount, 0.00) + ISNULL(FA.VariableAmount, 0.00) + ISNULL(FA.AdditionalAmount, 0.00) - ISNULL(FA.DiscountAmount, 0.00) - ISNULL(FA.NotApplicableAmount, 0.00) - ISNULL(R.PaidAmount, 0.00) > 0))

	RETURN @rReceiptAmount
END
GO
PRINT N'Altering Function [sFee].[fReceiptNumberGet]...';


GO
ALTER FUNCTION [sFee].[fReceiptNumberGet](@rReceiptBookId int,@rOrgGroupBatchId int, @rPayTypeId tinyint, @rFeeReceiptBasedOn nvarchar(50))
RETURNS [int] WITH EXECUTE AS CALLER
AS 
BEGIN

    --DECLARE @rReceiptBookId int

    DECLARE @lReceiptNumber int
	DECLARE @lResult  int

	IF(@rFeeReceiptBasedOn = 'ReceiptBookWise')
	BEGIN
      SELECT @lReceiptNumber= max(ReceiptNumber) from sFee.tReceipt WITH (NOLOCK) where ReceiptBookId=@rReceiptBookId AND OrgGroupBatchId = @rOrgGroupBatchId
	END
	ELSE IF(@rFeeReceiptBasedOn = 'PayTypeWise')
	BEGIN
	  SELECT @lReceiptNumber= max(ReceiptNumber) from sFee.tReceipt WITH (NOLOCK) where ReceiptBookId=@rReceiptBookId AND OrgGroupBatchId = @rOrgGroupBatchId AND PayTypeId = @rPayTypeId
	END
	-- #Start Mantis Id : 0036287
	ELSE IF(@rFeeReceiptBasedOn = 'Continuous Batch')
	BEGIN
	  SELECT @lReceiptNumber= max(ReceiptNumber) from sFee.tReceipt WITH (NOLOCK) where ReceiptBookId=@rReceiptBookId
	END
	-- #End Mantis Id : 0036287
	ELSE
	BEGIN
		SELECT @lReceiptNumber= max(ReceiptNumber) from sFee.tReceipt WITH (NOLOCK) where ReceiptBookId=@rReceiptBookId AND OrgGroupBatchId = @rOrgGroupBatchId
	END

	IF(@lReceiptNumber IS NULL)  
	BEGIN
		SET @lResult = 1
	END
	ELSE
	BEGIN
		 SET @lResult= @lReceiptNumber + 1
	END    

   return  @lResult 
      
END
GO
PRINT N'Creating Function [sFee].[fFeeActualAmountSumGet_OGOLD]...';


GO
CREATE FUNCTION [sFee].[fFeeActualAmountSumGet_OGOLD] (@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'Creating Function [sFee].[fFeeAmountSumGet_OGOLD]...';


GO
CREATE FUNCTION [sFee].[fFeeAmountSumGet_OGOLD] (@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)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,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'Creating Function [sFee].[fFeeHeadMonthNameGet_OGOLD]...';


GO
CREATE FUNCTION [sFee].[fFeeHeadMonthNameGet_OGOLD](@rReceiptId bigint, @rFeeHeadId int)
RETURNS nvarchar(200) WITH EXECUTE AS CALLER
AS 
BEGIN

DECLARE @rFirstFee nvarchar(20)
DECLARE @rLastFee nvarchar(20)
DECLARE @rResult nvarchar(20)

SELECT TOP 1 
		@rFirstFee =[sCommon].[fGetMonthName](Month(S.StartDate))
			 FROM 
			 sFee.tReceiptDetail D
			 INNER JOIN sFee.tFeeSetup S ON D.FeeSetupId = s.Id
			 INNER JOIN sFee.tFeeMaster F ON S.FeeId = F.Id
			 WHERE D.ReceiptId = @rReceiptId AND F.FeeHeadId=@rFeeHeadId
			 AND F.Number <> 100	
			 ORDER BY F.OrderIndex

SELECT TOP 1 
		@rLastFee = [sCommon].[fGetMonthName](Month(S.EndDate))
			 FROM 
			 sFee.tReceiptDetail D
			 INNER JOIN sFee.tFeeSetup S ON D.FeeSetupId = s.Id
			 INNER JOIN sFee.tFeeMaster F ON S.FeeId = F.Id
			 WHERE D.ReceiptId = @rReceiptId AND F.FeeHeadId=@rFeeHeadId
			 AND F.Number <> 100	
			 ORDER BY F.OrderIndex DESC			 
			 
			 IF(@rFirstFee=@rLastFee)
			 BEGIN
				SET @rResult = @rFirstFee
			 END
			 ELSE
			 BEGIN
				SET @rResult = @rFirstFee	+ ' To ' +	@rLastFee
			 END
			 
			 RETURN @rResult
			 
END
GO
PRINT N'Creating Function [sFee].[fFeeMonthNameGet_OGOLD]...';


GO


CREATE FUNCTION [sFee].[fFeeMonthNameGet_OGOLD](@rReceiptId bigint, @rFeeId int)
RETURNS nvarchar(200) WITH EXECUTE AS CALLER
AS 
BEGIN

DECLARE @rFirstFee nvarchar(20)
DECLARE @rLastFee nvarchar(20)
DECLARE @rResult nvarchar(20)

SELECT TOP 1 
		@rFirstFee =[sCommon].[fGetMonthName](Month(S.StartDate))
			 FROM 
			 sFee.tReceiptDetail D
			 INNER JOIN sFee.tFeeSetup S ON D.FeeSetupId = s.Id
			 INNER JOIN sFee.tFeeMaster F ON S.FeeId = F.Id
			 WHERE D.ReceiptId = @rReceiptId AND F.Id=@rFeeId
			 AND F.Number <> 100	
			 ORDER BY F.OrderIndex

SELECT TOP 1 
		@rLastFee = [sCommon].[fGetMonthName](Month(S.EndDate))
			 FROM 
			 sFee.tReceiptDetail D
			 INNER JOIN sFee.tFeeSetup S ON D.FeeSetupId = s.Id
			 INNER JOIN sFee.tFeeMaster F ON S.FeeId = F.Id
			 WHERE D.ReceiptId = @rReceiptId AND F.Id=@rFeeId
			 AND F.Number <> 100	
			 ORDER BY F.OrderIndex DESC			 
			 
			 IF(@rFirstFee=@rLastFee)
			 BEGIN
				SET @rResult = @rFirstFee
			 END
			 ELSE
			 BEGIN
				SET @rResult = @rFirstFee	+ ' To ' +	@rLastFee
			 END
			 
			 RETURN @rResult
			 
END
GO
PRINT N'Creating Function [sFee].[fFeeReceiptDiscountSumGet_OGOLD]...';


GO
CREATE FUNCTION [sFee].[fFeeReceiptDiscountSumGet_OGOLD] (@rAcademicId bigint)
RETURNS decimal(12,0) WITH EXECUTE AS CALLER
AS 
BEGIN
    DECLARE @rTotalDicountAmount decimal(12,0),@rBatchId int, @rOrgId int
    SELECT @rOrgId=OrgId,@rBatchId=BatchId FROM sStudent.tAcademic WHERE Id = @rAcademicId
    
    (
    SELECT 
		@rTotalDicountAmount = SUM(ISNULL(FA.DiscountAmount,0.00))
    FROM 
			 sStudent.tAcademic A
		INNER JOIN sFee.tFeeAllocation FA ON FA.SourceId=A.Id AND FA.SourceTypeId = 2001
		WHERE	
			A.Id = @rAcademicId
			AND ((A.OrgId=@rOrgId) OR (@rOrgId=0)) 
			AND ((A.BatchId=@rBatchId) OR (@rBatchId=0)) 
			)
			
	RETURN ISNULL(@rTotalDicountAmount,0)
END
GO
PRINT N'Creating Function [sFee].[fPendingFeeAmountReceiptBookwiseGet_OGOLD]...';


GO
CREATE FUNCTION [sFee].[fPendingFeeAmountReceiptBookwiseGet_OGOLD] (@rAcademicId bigint,@rReceiptBookId int)
RETURNS decimal(12,0) WITH EXECUTE AS CALLER
AS 
BEGIN
    DECLARE @rReceiptAmount 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 
		@rReceiptAmount = SUM(ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00))
    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
				AND (FS1.ReceiptBookId = @rReceiptBookId OR @rReceiptBookId=0)
				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
				AND (FS1.ReceiptBookId = @rReceiptBookId OR @rReceiptBookId=0)
		) 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
		LEFT JOIN
		(
		    SELECT 
					ISNULL(SUM(RD.Amount),0) AS PaidAmount,RD.FeeSetupId ,R.SourceId
		    FROM
				sFee.tReceipt R 
				INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id 
				INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id
				INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id
				INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=R.SourceId				
				AND (SA1.ClassId=@lClassId OR @lClassId=0) 
				AND ((SA1.DivisionId=@lDivisionId) OR (@lDivisionId=0))
				AND (SA1.DivisionId=@lDivisionId OR @lDivisionId=0)
				
			WHERE		
				(R.SourceTypeId = 2001)
				AND ((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND (R.IsObsolete = 0) 
				AND ((SA1.OrgGroupBatchId = @rOrgGroupBatchId))
				AND (R.OrgGroupBatchId = @rOrgGroupBatchId)
				AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
				AND SA1.AcademicId = @rAcademicId
				AND (R.ReceiptBookId = @rReceiptBookId OR @rReceiptBookId=0)
				GROUP BY FeeSetupId,R.SourceId
		) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
		 
	WHERE	
			SA.AcademicId = @rAcademicId
			AND SA.OrgGroupBatchId = @rOrgGroupBatchId
			AND ((SA.OrgId=@rOrgId) OR (@rOrgId=0)) 
			AND ((SA.BatchId=@rBatchId) OR (@rBatchId=0)) 
			AND (ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00) -ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00) > 0)
			)
			
	RETURN @rReceiptAmount
END
GO
PRINT N'Creating Function [sFee].[GetStudentPendingFeeTesting]...';


GO
CREATE FUNCTION [sFee].[GetStudentPendingFeeTesting](@rAcademicId BIGINT,@rReceiptBookId int = 0)
RETURNS DECIMAL(12, 0)
	WITH EXECUTE AS CALLER
AS
BEGIN
DECLARE @rReceiptAmount DECIMAL(12, 0)
SELECT @rReceiptAmount = SUM(FSAmount) + SUM(VariableAmount) + SUM(AdditionalAmount) - SUM(DiscountAmount) - SUM(NotApplicableAmount) - SUM(PaidAmount)
FROM
(    
    SELECT 
        SA.AcademicId,
        CASE WHEN FS.IsOptional = 0 THEN FS.Amount 
             WHEN FS.IsOptional = 1 AND FO.SourceId IS NOT NULL THEN FS.Amount
             ELSE 0.00 END AS FSAmount,
        ISNULL(FA.VariableAmount, 0) AS VariableAmount,
        ISNULL(FA.AdditionalAmount, 0) AS AdditionalAmount,
        ISNULL(FA.DiscountAmount, 0) AS DiscountAmount,
        ISNULL(FA.NotApplicableAmount, 0) AS NotApplicableAmount,
        ISNULL(R.PaidAmount, 0) AS PaidAmount
    FROM 
        sStudent.vStudentAcademic SA
        INNER JOIN sFee.tFeeSetup FS ON SA.ClassId = FS.ClassId AND SA.BatchId = FS.BatchId AND FS.AdmissionCategoryId = SA.AdmissionCategoryId
        LEFT JOIN sFee.tFeeOptional FO ON FO.FeeSetupId = FS.Id AND SA.AcademicId = FO.SourceId AND FO.SourceTypeId = 2001
        LEFT JOIN sFee.tFeeAllocation FA ON FA.FeeSetupId = FS.Id AND FA.SourceId = SA.AcademicId AND FA.SourceTypeId = 2001
        LEFT JOIN (
            SELECT 
                ISNULL(SUM(RD.Amount), 0) AS PaidAmount,
                RD.FeeSetupId,
                R.SourceId
            FROM
                sFee.tReceipt R 
                INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id 
            WHERE 
                R.SourceId = @rAcademicId
                AND R.SourceTypeId = 2001
                AND R.IsObsolete = 0
				AND (R.ReceiptBookId = @rReceiptBookId OR @rReceiptBookId <= 0)
            GROUP BY 
                RD.FeeSetupId, R.SourceId
        ) R ON R.SourceId = SA.AcademicId AND R.FeeSetupId = FS.Id
    WHERE  SA.AcademicId = @rAcademicId
	AND (FS.ReceiptBookId = @rReceiptBookId OR @rReceiptBookId <= 0)
) AS FeeSummary
GROUP BY AcademicId;

RETURN Isnull(@rReceiptAmount,0)

END
GO
PRINT N'Creating Function [sFinanceCommon].[fNumberToWordsGet]...';


GO
CREATE FUNCTION [sFinanceCommon].[fNumberToWordsGet]
(
    @rNumber DECIMAL(38, 0),
    @rCurrencyType TINYINT = 0,
    @rOrgGroupId SMALLINT = 0,
	@rDefaultCurrencyTitle nvarchar(200)
)
RETURNS VARCHAR(8000)
WITH EXECUTE AS CALLER
AS
BEGIN
    DECLARE @lInputNumber VARCHAR(38),
            @lOutputString VARCHAR(8000) = '',
            @lLength INT,
            @lCounter INT = 1,
            @lCount INT,
            @lPosition INT,
            @lChunk CHAR(3),
            @lTensones CHAR(2),
            @lHundreds CHAR(1),
            @lTens CHAR(1),
            @lOnes CHAR(1);

    DECLARE @lNumberTable TABLE (cNumber CHAR(2) PRIMARY KEY, cWord VARCHAR(10));

    IF @rNumber = 0 RETURN 'Zero';

    -- Initialize
    SELECT @lInputNumber = CONVERT(VARCHAR(38), @rNumber),
           @lLength = LEN(@lInputNumber),
           @lPosition = LEN(@lInputNumber) - 2,
           @lCount = (@lLength + 2) / 3;

    -- Insert number-to-word mapping
    INSERT INTO @lNumberTable (cNumber, cWord)
    VALUES
        ('00', ''), ('01', 'One'), ('02', 'Two'), ('03', 'Three'), ('04', 'Four'),
        ('05', 'Five'), ('06', 'Six'), ('07', 'Seven'), ('08', 'Eight'), ('09', 'Nine'),
        ('10', 'Ten'), ('11', 'Eleven'), ('12', 'Twelve'), ('13', 'Thirteen'), ('14', 'Fourteen'),
        ('15', 'Fifteen'), ('16', 'Sixteen'), ('17', 'Seventeen'), ('18', 'Eighteen'), ('19', 'Nineteen'),
        ('20', 'Twenty'), ('30', 'Thirty'), ('40', 'Forty'), ('50', 'Fifty'),
        ('60', 'Sixty'), ('70', 'Seventy'), ('80', 'Eighty'), ('90', 'Ninety');

    -- Loop through each 3-digit group
    WHILE @lCounter <= @lCount
    BEGIN
        SET @lChunk = RIGHT('000' + SUBSTRING(@lInputNumber, @lPosition, 3), 3);

        IF @lChunk <> '000'
        BEGIN
            SELECT
                @lHundreds = SUBSTRING(@lChunk, 1, 1),
                @lTens = SUBSTRING(@lChunk, 2, 1),
                @lOnes = SUBSTRING(@lChunk, 3, 1),
                @lTensones = SUBSTRING(@lChunk, 2, 2);

            DECLARE @lGroupWord VARCHAR(100) = '';

            -- Hundreds place
            IF @lHundreds <> '0'
                SET @lGroupWord = (SELECT cWord FROM @lNumberTable WHERE cNumber = '0' + @lHundreds) + ' Hundred ';

            -- Tens and Ones place
            IF CONVERT(INT, @lTensones) <= 20 OR @lOnes = '0'
                SET @lGroupWord += (SELECT cWord FROM @lNumberTable WHERE cNumber = @lTensones);
            ELSE
                SET @lGroupWord += (SELECT cWord FROM @lNumberTable WHERE cNumber = @lTens + '0')
                                  + '-' +
                                  (SELECT cWord FROM @lNumberTable WHERE cNumber = '0' + @lOnes);

            -- Add unit (Thousand, Million, etc.)
            SET @lGroupWord += CASE @lCounter
                                 WHEN 2 THEN ' Thousand'
                                 WHEN 3 THEN ' Million'
                                 WHEN 4 THEN ' Billion'
                                 WHEN 5 THEN ' Trillion'
                                 WHEN 6 THEN ' Quadrillion'
                                 WHEN 7 THEN ' Quintillion'
                                 WHEN 8 THEN ' Sextillion'
                                 WHEN 9 THEN ' Septillion'
                                 WHEN 10 THEN ' Octillion'
                                 WHEN 11 THEN ' Nonillion'
                                 WHEN 12 THEN ' Decillion'
                                 WHEN 13 THEN ' Undecillion'
							   ELSE ''
                               END;

            -- Prepend group word
            SET @lOutputString = LTRIM(RTRIM(@lGroupWord)) + ' ' + @lOutputString;
        END

        -- Next chunk
        SET @lCounter += 1;
        SET @lPosition -= 3;
    END

    -- Cleanup double spaces
    SET @lOutputString = LTRIM(RTRIM(REPLACE(@lOutputString, '  ', ' ')));
    SET @lOutputString = UPPER(LEFT(@lOutputString, 1)) + SUBSTRING(@lOutputString, 2, LEN(@lOutputString));

    -- Add currency if needed
    IF @rCurrencyType <> 0
	BEGIN
        SET @lOutputString = @rDefaultCurrencyTitle + ' ' + @lOutputString;
	END

    RETURN @lOutputString;
END
GO
PRINT N'Creating Function [sFinanceCommon].[fNumberToWordsWithDecimalGet]...';


GO
CREATE FUNCTION [sFinanceCommon].[fNumberToWordsWithDecimalGet]
(@rAmount [decimal](38, 8), @rCurrencyType [tinyint] = 0, @rScale [tinyint] = 2,@rOrgGroupId [smallint] = 0, @rDefaultCurrencyTitle nvarchar(200))
RETURNS [nvarchar](4000) WITH EXECUTE AS CALLER
AS 
/*
DECLARE @rAmount DECIMAL(38, 8)
DECLARE @rCurrencyType dTinyInt --// 0 = Without Currency Type, 1 = Accounting, 2 = Foreign, 3 = Reporting
DECLARE @rScale  TINYINT

SET @rAmount = 0
SET @rCurrencyType = 0
SET @rScale = 0
*/		
BEGIN
	DECLARE @lIntPart NVARCHAR(1000),
	 @lDecimalPart NVARCHAR(100),
	 @lAmountChar NVARCHAR(38),
	 @lDecimalPartAmount SMALLINT,
	 @lWords NVARCHAR(4000),
	 @lCHARINDEX int = 0

	SET @lAmountChar = @rAmount

	SELECT @lWords = + '' + @rDefaultCurrencyTitle +' '+ [sFee].[fNumberToWordsGet](FLOOR(@rAmount)) 
	
	SET @lDecimalPartAmount = CAST(ROUND((@rAmount - FLOOR(@rAmount)) * POWER(10, @rScale), 0) AS INT)
	IF @lDecimalPartAmount > 0 
	BEGIN	
		SET @lWords = @lWords + ' and'
						
		IF @rCurrencyType <> 0
		BEGIN
			SET @lWords = @lWords + ' ' + @rDefaultCurrencyTitle
		END		   
						
		SET @lWords = @lWords + ' ' + [sFinanceCommon].[fNumberToWordsGet](@lDecimalPartAmount, @rCurrencyType,@rOrgGroupId,@rDefaultCurrencyTitle)
	END

	RETURN @lWords 
END
GO
PRINT N'Creating Function [sHrm].[fEmployeeJoiningCertificateTemplate]...';


GO



CREATE FUNCTION [sHrm].[fEmployeeJoiningCertificateTemplate]
(
	@EmployeeId [bigint]= 0,
    @Template NVARCHAR(MAX)
)
RETURNS NVARCHAR(MAX)
AS
BEGIN
    DECLARE 
        --@EmployeeId  BIGINT,
        @Number INT,
        @EmployeeName NVARCHAR(200),
        @FirstName NVARCHAR(100),
        @MiddleName NVARCHAR(100),
        @LastName NVARCHAR(100),
        @Code NVARCHAR(20),
        @ShortName NVARCHAR(50),
        @DepartmentName NVARCHAR(100),
        @Designation NVARCHAR(100),
        @EmployeePhoto NVARCHAR(MAX),     
        @DateOfJoining DATE,
		@CertificateHeaderA4 NVARCHAR(MAX),

        @Remark NVARCHAR(500),
        @CertificateDate DATE,
        @PayScale NVARCHAR(150),
        @AgreementPeriod NVARCHAR(150),
        @CertificateRemark NVARCHAR(500),
        @OrgTitle NVARCHAR(100),
        @CreatedDateTime DATETIME,
        @UserDisplayName NVARCHAR(100),
        @EmployeeDesignation NVARCHAR(100),
        @ShortTitle NVARCHAR(100),
        @DepartmentName1 NVARCHAR(100),
        @MobileNumber NVARCHAR(20),

        @PresentStreetOne NVARCHAR(150),
        @PresentStreetTwo NVARCHAR(150),
        @PresentStreetThree NVARCHAR(150),
        @PresentCity NVARCHAR(50),
        @PresentState NVARCHAR(50),
        @PresentZipCode NVARCHAR(20),
        @PresentContactNo NVARCHAR(20),
        @UserDesignation NVARCHAR(100),
        @CertificateDateOfJoining DATE
        
    -- Fetch the values from the database
    SELECT 
        @EmployeeId = ISNULL(EmployeeId, 0),
        @Number = ISNULL(Number, 0),
        @EmployeeName = ISNULL(EmployeeName, ''),
        @FirstName = ISNULL(FirstName, ''),
        @MiddleName = ISNULL(MiddleName, ''),
        @LastName = ISNULL(LastName, ''),
        @Code= ISNULL(Code, ''),
        @ShortName = ISNULL(ShortName, ''),
        @DepartmentName = ISNULL(DepartmentName, ''),
        @Designation = ISNULL(Designation, ''),
		@EmployeePhoto = ISNULL(CAST('data:image/jpeg;base64,' AS NVARCHAR(MAX)) +
                      CAST(N'' AS XML).value('xs:base64Binary(xs:hexBinary(sql:column("EmployeePhoto")))', 'NVARCHAR(MAX)'),''),
        @DateOfJoining = ISNULL(DateOfJoining, ''),
        @CertificateHeaderA4 = ISNULL(CAST('data:image/jpeg;base64,' AS NVARCHAR(MAX)) +
                      CAST(N'' AS XML).value('xs:base64Binary(xs:hexBinary(sql:column("CertificateHeaderA4")))', 'NVARCHAR(MAX)'),''),
        @Remark = ISNULL(Remark, ''),
        @CertificateDate = ISNULL(CertificateDate, ''),
        @PayScale = ISNULL(PayScale, ''),
        @AgreementPeriod = ISNULL(AgreementPeriod, ''),
        @CertificateRemark = ISNULL(CertificateRemark, ''),
        @OrgTitle = ISNULL(OrgTitle, ''),
        @CreatedDateTime = ISNULL(CreatedDateTime, ''),
        @UserDisplayName = ISNULL(UserDisplayName, ''),
        @EmployeeDesignation = ISNULL(EmployeeDesignation, ''),
        @ShortTitle = ISNULL(ShortTitle, ''),
        @DepartmentName1= ISNULL(DepartmentName1, ''),
        @MobileNumber = ISNULL(MobileNumber, ''),
        @PresentStreetOne = ISNULL(PresentStreetOne, ''),
        @PresentStreetTwo = ISNULL(PresentStreetTwo, ''),
        @PresentStreetThree = ISNULL(PresentStreetThree, ''),
        @PresentCity = ISNULL(PresentCity, ''),
        @PresentState = ISNULL(PresentState, ''),
        @PresentZipCode = ISNULL(PresentZipCode, ''),
        @PresentContactNo = ISNULL(PresentContactNo, ''),
        @UserDesignation = ISNULL(UserDesignation, ''),

        @CertificateDateOfJoining = ISNULL(CertificateDateOfJoining, '')
       
    FROM 
      [sHrm].[vPrintTemplateJoiningCertificateGet]  
    WHERE 
        EmployeeId = @EmployeeId

    -- Replace placeholders in the template with actual values
    SET @Template = REPLACE(@Template, '[EmployeeId]', @EmployeeId);
    --SET @Template = REPLACE(@Template, '[AdmissionDate]', CONVERT(NVARCHAR, @AdmissionDate, 103));
    SET @Template = REPLACE(@Template, '[Number]', @Number);
    SET @Template = REPLACE(@Template, '[EmployeeName]', @EmployeeName);
    SET @Template = REPLACE(@Template, '[FirstName]', @FirstName);
    SET @Template = REPLACE(@Template, '[MiddleName]', @MiddleName);
    SET @Template = REPLACE(@Template, '[LastName]', @LastName);
    --SET @Template = REPLACE(@Template, '[BonafideDate]', CONVERT(NVARCHAR, @BonafideDate, 103));
    SET @Template = REPLACE(@Template, '[Code]', @Code);
    SET @Template = REPLACE(@Template, '[ShortName]', @ShortName);
    SET @Template = REPLACE(@Template, '[DepartmentName]', @DepartmentName);
    SET @Template = REPLACE(@Template, '[Designation]', @Designation);
    SET @Template = REPLACE(@Template, '[EmployeePhoto]', @EmployeePhoto);
    SET @Template = REPLACE(@Template, '[DateOfJoining]',CONVERT(NVARCHAR, @DateOfJoining,103));
    SET @Template = REPLACE(@Template, '[CertificateHeaderA4]', @CertificateHeaderA4 );
    SET @Template = REPLACE(@Template, '[Remark]', @Remark);
    SET @Template = REPLACE(@Template, '[CertificateDate]', CONVERT(NVARCHAR,@CertificateDate,103));
    SET @Template = REPLACE(@Template, '[PayScale]', @PayScale);
    SET @Template = REPLACE(@Template, '[AgreementPeriod]', @AgreementPeriod);
    SET @Template = REPLACE(@Template, '[CertificateRemark]', @CertificateRemark);
    SET @Template = REPLACE(@Template, '[OrgTitle]', @OrgTitle);
    SET @Template = REPLACE(@Template, '[CreatedDateTime]', CONVERT(NVARCHAR,@CreatedDateTime,103));
    SET @Template = REPLACE(@Template, '[UserDisplayName]', @UserDisplayName);
    SET @Template = REPLACE(@Template, '[EmployeeDesignation]', @EmployeeDesignation);
    SET @Template = REPLACE(@Template, '[ShortTitle]', @ShortTitle);
    SET @Template = REPLACE(@Template, '[DepartmentName1]', @DepartmentName1);
    SET @Template = REPLACE(@Template, '[MobileNumber]', @MobileNumber);

	SET @Template = REPLACE(@Template, '[PresentStreetOne]', @PresentStreetOne);
    SET @Template = REPLACE(@Template, '[PresentStreetTwo]', @PresentStreetTwo);
	SET @Template = REPLACE(@Template, '[PresentStreetThree]', @PresentStreetThree);
    SET @Template = REPLACE(@Template, '[PresentCity]', @PresentCity);
    SET @Template = REPLACE(@Template, '[PresentState]', @PresentState);
    SET @Template = REPLACE(@Template, '[PresentZipCode]', @PresentZipCode);
	SET @Template = REPLACE(@Template, '[PresentContactNo]', @PresentContactNo);

    SET @Template = REPLACE(@Template, '[UserDesignation]', @UserDesignation);
    SET @Template = REPLACE(@Template, '[CertificateDateOfJoining]',CONVERT(NVARCHAR, @CertificateDateOfJoining,103));
    
    RETURN @Template;
END;
GO
PRINT N'Creating Function [sStudent].[fStudentOptionalSubjectList]...';


GO
CREATE FUNCTION [sStudent].[fStudentOptionalSubjectList]( @AcademicId BIGINT )
RETURNS NVARCHAR (2000) WITH EXECUTE AS CALLER
AS
BEGIN

DECLARE @OptionalSubList NVARCHAR(2000)

SELECT 
 @OptionalSubList  = COALESCE(@OptionalSubList+',','') + SubM.Code

 FROM
 	
	sAssessment.tOptionalSubject OS 
	INNER JOIN sSetup.tClassSubject CS ON CS.Id =  OS.ClassSubjectId
	INNER JOIN sSetup.tSubjectMaster SubM ON SubM.Id =  CS.SubjectId
	
	WHERE  OS.AcademicId =  @AcademicId

	RETURN ISNULL(@OptionalSubList,'') 

END
GO
PRINT N'Creating Function [sFinanceCommon].[fDefaultCurrencyValueGet]...';


GO
CREATE FUNCTION [sFinanceCommon].[fDefaultCurrencyValueGet]
(
    @rOrgGroupId INT
)
RETURNS TABLE
AS
RETURN
(
    SELECT 
        CurrencyTitle = ISNULL(
            (SELECT TOP 1 ISNULL(CS.ItemValue, CM.ItemValue)
             FROM sConfig.tConfigurationMaster CM
             LEFT JOIN sConfig.tConfigurationSetup CS
                 ON CM.Id = CS.ConfigurationId
                 AND CS.SourceTypeId = 2010
                 AND CS.SourceId = @rOrgGroupId
             WHERE CM.Id = 153), 'Rupees'),
        CurrencyCode = ISNULL(
            (SELECT TOP 1 ISNULL(CS.ItemValue, CM.ItemValue)
             FROM sConfig.tConfigurationMaster CM
             LEFT JOIN sConfig.tConfigurationSetup CS
                 ON CM.Id = CS.ConfigurationId
                 AND CS.SourceTypeId = 2010
                 AND CS.SourceId = @rOrgGroupId
             WHERE CM.Id = 154), 'Rs.')
)
GO
PRINT N'Altering Procedure [sAcademic].[pLessonPlanGet]...';


GO


ALTER PROCEDURE [sAcademic].[pLessonPlanGet]

	 @rId bigint=0,
	 @rClassId int=0,
	 @rSubjectId int=0,
	 @rDivisionId int=0,
	 @rIsCompleted bit=0,
	 @rBatchId int=0,
	 @rEmployeeId bigint=0,
	 @rDepartmentid int=0,
	 @rFromDate datetime='',
     @rToDate datetime='',
     @rCreatedUserId bigint=0,
	 @rStatus int = 0,
	 @rIsWithHeader bit=0,
	 --Addded by dhananjay mantis - 0035004
	 @rBuilder1 nvarchar(max) = '',
	 @rBuilder2 nvarchar(max)  = ''
	--Addded by dhananjay mantis - 0035004
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
	
	IF(@rStatus = 0)
	BEGIN
	SELECT 
			LP.Id,
			TM.ClassId,
		    LP.DivisionId,
			TM.SubjectId,
			LP.TopicId,
			LP.NoOfPeriodRequired,
			LP.Objective,
			LP.IndicativeHomework,
			LP.Summary,
			ISNULL(LP.StartDate,'') AS StartDate ,
			ISNULL(LP.EndDate,'') AS EndDate,
			ISNULL(LP.IsCompleted,0) AS IsCompleted,
			LP.EmployeeId,
			LP.BatchId,
			LP.CreatedUserId,
			LP.CreatedDateTime,
			TM.Title AS TopicName,
			DM.Code AS ClassDivisionName,
			SM.Title AS SubjectName,
			[sHrm].[fEmployeeNameGet](EM.FirstName , EM.MiddleName, EM.LastName,ISNULL(OM.EmployeeNameFormatId,1)) AS EmployeeName,
			LP.LearningExperience,
			LP.ToolsAndTechniques,
			LP.EssentialMaterial,
			LP.AssessmentQuestion,
			LP.TeacherExample,
			LP.GuidedPractice,
			LP.IndependentPractice,
			LP.SubTopic,
			@rIsWithHeader AS IsWithHeader,
			(CASE WHEN @rIsWithHeader=1 THEN OI.CertificateHeaderA4 ELSE NULL END)AS MarksheetHeaderA4 ,
			ISNULL(LP.[Session] ,'') As [Session] ,
			ISNULL(LP.TrainingMethod,'') As TrainingMethod,
			ISNULL(LP.PeriodCount,0) As PeriodCount ,
			ISNULL(LP.Remark,'') As Remark,
			--Addded by dhananjay mantis - 0035004
			ISNULL(@rBuilder1,'') AS Builder1,
			ISNULL(@rBuilder2,'') AS Builder2 
			--Addded by dhananjay mantis - 0035004
	FROM 
			sAcademic.tLessonPlan LP
			INNER JOIN sSetup.tDivisionMaster DM ON LP.DivisionId = DM.Id
			INNER JOIN sSetup.tClassMaster CM ON CM.Id = DM.ClassId
			LEFT JOIN sHrm.tEmployeeMaster EM ON EM.Id=LP.EmployeeId
			INNER JOIN sSetup.tOrganizationMaster OM ON EM.OrgID = OM.Id
			INNER JOIN sAcademic.tTopicMaster TM ON TM.Id=LP.TopicId 
			INNER JOIN sSetup.tSubjectMaster SM ON SM.Id = TM.SubjectId   
			LEFT JOIN sSetup.tOrgImages OI ON OI.Orgid = CM.OrgId
			--sAcademic.tLessonPlan LP
			--INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id=LP.EmployeeId
			--INNER JOIN sAcademic.tTopicMaster TM ON TM.Id=LP.TopicId
			--INNER JOIN sAcademic.vTeacherSubjectDivision vTSD ON vTSD.DivisionId = LP.DivisionId
			--AND vTSD.ClassId = TM.ClassId 
			--AND vTSD.SubjectId = TM.SubjectId 
			--AND vTSD.EmployeeId = LP.EmployeeId
			--INNER JOIN sSetup.tClassMaster CM ON CM.Id = vTSD.ClassId
	WHERE 
		((LP.BatchId = @rBatchId) OR (@rBatchId = 0))
		 AND ((LP.EmployeeId = @rEmployeeId) OR (@rEmployeeId=0))
		AND ((LP.Id = @rId) OR (@rId = 0))
		AND ((TM.ClassId = @rClassId) OR (@rClassId = 0))
		AND ((LP.DivisionId = @rDivisionId) OR (@rDivisionId = 0))
		AND ((TM.SubjectId = @rSubjectId) OR (@rSubjectId = 0))
		AND ((LP.IsCompleted='False') OR (LP.IsCompleted=@rIsCompleted))		
		AND ((CM.DepartmentId = @rDepartmentid) OR (@rDepartmentid=0))
		--AND (LP.StartDate>=@rFromDate OR ISNULL(@rFromDate,'')='')
		--AND (LP.StartDate<=@rToDate OR ISNULL(@rToDate,'')='')
		--AND ((LP.StartDate >= @rFromDate OR ISNULL(@rFromDate,'')='' )AND (LP.StartDate <= @rToDate OR ISNULL(@rToDate,'')='')
		--OR (LP.EndDate >= @rFromDate OR ISNULL(@rFromDate,'')='' )AND (LP.EndDate <= @rToDate OR ISNULL(@rToDate,'')='')
		--)
		--comment above condition because OR is wrong
		AND ( ((LP.StartDate >= @rFromDate OR ISNULL(@rFromDate,'')='' )AND (LP.StartDate <= @rToDate OR ISNULL(@rToDate,'')='')
		OR (LP.EndDate >= @rFromDate OR ISNULL(@rFromDate,'')='' )AND (LP.EndDate <= @rToDate OR ISNULL(@rToDate,'')='')
		))
		--comment above condition due to mantisid - 0029580
		--AND ((LP.StartDate = @rFromDate OR ISNULL(@rFromDate,'')='' ))
		--AND ((LP.EndDate = @rToDate OR ISNULL(@rToDate,'')='' ))
		AND (LP.CreatedUserId=@rCreatedUserId OR ISNULL(@rCreatedUserId,'')='')
		AND ISNULL(EM.IsOtherUser,0) = 0
		--Added by dhananjay mantis : 43006	
		AND ISNULL(CM.IsObsolete,0) = 0
		AND ISNULL(DM.IsObsolete,0) = 0
		--Added by dhananjay mantis : 43006	
	ORDER BY
		LP.id 
	END
	ELSE
	BEGIN
	SELECT 
			LP.Id,
			TM.ClassId,
		    LP.DivisionId,
			TM.SubjectId,
			LP.TopicId,
			LP.NoOfPeriodRequired,
			LP.Objective,
			LP.IndicativeHomework,
			LP.Summary,
			ISNULL(LP.StartDate,'') AS StartDate ,
			ISNULL(LP.EndDate,'') AS EndDate,
			ISNULL(LP.IsCompleted,0) AS IsCompleted,
			LP.EmployeeId,
			LP.BatchId,
			LP.CreatedUserId,
			LP.CreatedDateTime,
			TM.Title AS TopicName,
			DM.Code AS ClassDivisionName,
			SM.Title AS SubjectName,
			[sHrm].[fEmployeeNameGet](EM.FirstName , EM.MiddleName, EM.LastName,ISNULL(OM.EmployeeNameFormatId,1)) AS EmployeeName,
			LP.LearningExperience,
			LP.ToolsAndTechniques,
			LP.EssentialMaterial,
			LP.AssessmentQuestion,
			LP.TeacherExample,
			LP.GuidedPractice,
			LP.IndependentPractice,
			LP.SubTopic,
			@rIsWithHeader AS IsWithHeader,
			(CASE WHEN @rIsWithHeader=1 THEN OI.CertificateHeaderA4 ELSE NULL END)AS MarksheetHeaderA4 ,
			ISNULL(LP.Session ,'') As [Session],
			ISNULL(LP.TrainingMethod,'') As TrainingMethod,
			ISNULL(LP.PeriodCount,0) As PeriodCount,
			ISNULL(LP.Remark,'') As Remark,
			--Addded by dhananjay mantis - 0035004
			ISNULL(@rBuilder1,'') AS Builder1,
			ISNULL(@rBuilder2,'') AS Builder2 
			--Addded by dhananjay mantis - 0035004
	FROM 
			sAcademic.tLessonPlan LP
			INNER JOIN sSetup.tDivisionMaster DM ON LP.DivisionId = DM.Id
			INNER JOIN sSetup.tClassMaster CM ON CM.Id = DM.ClassId
			LEFT JOIN sHrm.tEmployeeMaster EM ON EM.Id=LP.EmployeeId
			INNER JOIN sSetup.tOrganizationMaster OM ON EM.OrgID = OM.Id
			INNER JOIN sAcademic.tTopicMaster TM ON TM.Id=LP.TopicId 
			INNER JOIN sSetup.tSubjectMaster SM ON SM.Id = TM.SubjectId 
			LEFT JOIN sSetup.tOrgImages OI ON OI.Orgid = CM.OrgId  

			--sAcademic.tLessonPlan LP
			--INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id=LP.EmployeeId
			--INNER JOIN sAcademic.tTopicMaster TM ON TM.Id=LP.TopicId
			--INNER JOIN sAcademic.vTeacherSubjectDivision vTSD ON vTSD.DivisionId = LP.DivisionId
			--AND vTSD.ClassId = TM.ClassId 
			--AND vTSD.SubjectId = TM.SubjectId 
			--AND vTSD.EmployeeId = LP.EmployeeId
			--INNER JOIN sSetup.tClassMaster CM ON CM.Id = vTSD.ClassId
	WHERE 
		((LP.BatchId = @rBatchId) OR (@rBatchId = 0))
		 AND ((LP.EmployeeId = @rEmployeeId) OR (@rEmployeeId=0))
		AND ((LP.Id = @rId) OR (@rId = 0))
		AND ((TM.ClassId = @rClassId) OR (@rClassId = 0))
		AND ((LP.DivisionId = @rDivisionId) OR (@rDivisionId = 0))
		AND ((TM.SubjectId = @rSubjectId) OR (@rSubjectId = 0))
		AND ((@rStatus = 2) OR (LP.IsCompleted=@rIsCompleted))
		AND ((CM.DepartmentId = @rDepartmentid) OR (@rDepartmentid=0))
		--AND (LP.StartDate>=@rFromDate OR ISNULL(@rFromDate,'')='')
		--AND (LP.StartDate<=@rToDate OR ISNULL(@rToDate,'')='')
	 --   AND ((LP.StartDate >= @rFromDate OR ISNULL(@rFromDate,'')='' )AND (LP.StartDate <= @rToDate OR ISNULL(@rToDate,'')='')
		--OR (LP.EndDate >= @rFromDate OR ISNULL(@rFromDate,'')='' )AND (LP.EndDate <= @rToDate OR ISNULL(@rToDate,'')='')
		--)
		--comment above condition because OR is wrong
		AND (((LP.StartDate >= @rFromDate OR ISNULL(@rFromDate,'')='' )AND (LP.StartDate <= @rToDate OR ISNULL(@rToDate,'')='')
		OR (LP.EndDate >= @rFromDate OR ISNULL(@rFromDate,'')='' )AND (LP.EndDate <= @rToDate OR ISNULL(@rToDate,'')='')
		))
		--comment above condition due to mantisid - 0029580
		--AND ((LP.StartDate = @rFromDate OR ISNULL(@rFromDate,'')='' ))
		--AND ((LP.EndDate = @rToDate OR ISNULL(@rToDate,'')='' ))
		AND (LP.CreatedUserId=@rCreatedUserId OR ISNULL(@rCreatedUserId,'')='')
		AND ISNULL(EM.IsOtherUser,0) = 0
		--Added by dhananjay mantis : 43006	
		AND ISNULL(CM.IsObsolete,0) = 0
		AND ISNULL(DM.IsObsolete,0) = 0
		--Added by dhananjay mantis : 43006	
	ORDER BY
		LP.id 
	END
END
GO
PRINT N'Altering Procedure [sAcademic].[pLessonPlanMobileGet]...';


GO

ALTER PROCEDURE [sAcademic].[pLessonPlanMobileGet]

	 @rId bigint=0,
	 @rClassId int=0,
	 @rSubjectId int=0,
	 @rDivisionId int=0,
	 @rIsCompleted bit=0,
	 @rBatchId int=0,
	 @rEmployeeId bigint=0,
	 @rDepartmentid int=0,
	 @rFromDate datetime='',
     @rToDate datetime='',
     @rIsCompletedAPI tinyint=0,
     @rCreatedUserId bigint=0
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
DECLARE @lIsCompleted bit = 0
	
	If(@rIsCompletedAPI=1)
		SET @lIsCompleted = 1
	else If(@rIsCompletedAPI=2)
		SET @lIsCompleted = 0
	
	SELECT 
			LP.Id,
			TM.ClassId,
		    LP.DivisionId,
			TM.SubjectId,
			LP.TopicId,
			LP.NoOfPeriodRequired,
			LP.Objective,
			LP.IndicativeHomework,
			LP.Summary,
			ISNULL(LP.StartDate,'') AS StartDate ,
			ISNULL(LP.EndDate,'') AS EndDate,
			LP.IsCompleted,
			LP.EmployeeId,
			LP.BatchId,
			LP.CreatedUserId,
			LP.CreatedDateTime,
			TM.Title AS TopicName,
			DM.Code AS ClassDivisionName,
			SM.Title AS SubjectName,
			--vTSD.ClassTitle+' - '+ vTSD.DivisionTitle AS ClassDivisionName,
			 
			--vTSD.SubjectName,
			ISNULL(EM.FirstName,'') + ' ' + ISNULL(EM.LastName,'') AS  EmployeeName,
			LP.LearningExperience,
			LP.ToolsAndTechniques,
			LP.EssentialMaterial,
			LP.AssessmentQuestion,
			LP.TeacherExample,
			LP.GuidedPractice,
			LP.IndependentPractice,
			LP.SubTopic ,
			ISNULL(LP.[Session] ,'') As [Session] ,
			ISNULL(LP.TrainingMethod,'') As TrainingMethod,
			ISNULL(LP.PeriodCount,0) As PeriodCount
	FROM 
			sAcademic.tLessonPlan LP
			INNER JOIN sSetup.tDivisionMaster DM ON LP.DivisionId = DM.Id
			INNER JOIN sSetup.tClassMaster CM ON CM.Id = DM.ClassId
			LEFT JOIN sHrm.tEmployeeMaster EM ON EM.Id=LP.EmployeeId
			INNER JOIN sAcademic.tTopicMaster TM ON TM.Id=LP.TopicId 
			INNER JOIN sSetup.tSubjectMaster SM ON SM.Id = TM.SubjectId   
	WHERE 
		((LP.BatchId = @rBatchId) OR (LP.BatchId = 0))
		AND ((TM.SubjectId = @rSubjectId) OR (@rSubjectId = 0))
		AND((LP.IsCompleted=@lIsCompleted) OR (@rIsCompletedAPI=0))
		--AND (LP.StartDate>=@rFromDate OR ISNULL(@rFromDate,'')='')
		--AND (LP.StartDate<=@rToDate OR ISNULL(@rToDate,'')='')
		AND (((LP.StartDate >= @rFromDate OR ISNULL(@rFromDate,'')='' )AND (LP.StartDate <= @rToDate OR ISNULL(@rToDate,'')='')
		OR (LP.EndDate >= @rFromDate OR ISNULL(@rFromDate,'')='' )AND (LP.EndDate <= @rToDate OR ISNULL(@rToDate,'')='')
		))
		--AND (LP.CreatedUserId=@rCreatedUserId OR ISNULL(@rCreatedUserId,0)=0) 
		AND  (LP.EmployeeId = @rEmployeeId OR (ISNULL(@rEmployeeId,0)=0))
		AND ISNULL(EM.IsOtherUser,0) = 0
		--Added by dhananjay mantis : 43006	
		AND ISNULL(CM.IsObsolete,0) = 0
		AND ISNULL(DM.IsObsolete,0) = 0
		--Added by dhananjay mantis : 43006	
	ORDER BY
		LP.StartDate,LP.EndDate,LP.id 
END
GO
PRINT N'Altering Procedure [sAcademic].[pRptLessonPlanGet]...';


GO


ALTER PROCEDURE [sAcademic].[pRptLessonPlanGet]

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

BEGIN 
IF(@rStatus = 0)
	BEGIN
	SELECT 
			--LP.Id,
			--TM.ClassId,
			--LP.DivisionId,
			--TM.SubjectId,
			--LP.TopicId,
			--LP.NoOfPeriodRequired,
			--LP.Objective,
			--LP.IndicativeHomework,
			--LP.Summary,
			--LP.StartDate,
			--LP.EndDate,
			--LP.IsCompleted,
			--LP.EmployeeId,
			--LP.BatchId,
			--LP.CreatedUserId,
			--LP.CreatedDateTime,
			--TM.Title AS TopicName,
			--vTSD.ClassTitle+' - '+ vTSD.DivisionTitle AS ClassDivisionName,
			--vTSD.SubjectName,
			----ISNULL(EM.FirstName,'') + ' ' + ISNULL(EM.LastName,'') AS  EmployeeName,
			--LP.LearningExperience,
			--LP.ToolsAndTechniques,
			--LP.EssentialMaterial,
			--LP.AssessmentQuestion ,
		 -- datepart(MONTH,Lp.StartDate) AS MonthId,
		 -- datename(MONTH,Lp.StartDate) AS Monthname
		  
		  LP.Id,
			TM.ClassId,
		    LP.DivisionId,
			TM.SubjectId,
			LP.TopicId,
			LP.NoOfPeriodRequired,
			LP.Objective,
			LP.IndicativeHomework,
			LP.Summary,
			ISNULL(LP.StartDate,'') AS StartDate ,
			ISNULL(LP.EndDate,'') AS EndDate,
			LP.IsCompleted,
			LP.EmployeeId,
			LP.BatchId,
			LP.CreatedUserId,
			LP.CreatedDateTime,
			TM.Title AS TopicName,
			DM.Code AS ClassDivisionName,
			SM.Title AS SubjectName,
			--vTSD.ClassTitle+' - '+ vTSD.DivisionTitle AS ClassDivisionName,
			 
			--vTSD.SubjectName,
			ISNULL(EM.FirstName,'') + ' ' + ISNULL(EM.LastName,'') AS  EmployeeName,
			LP.LearningExperience,
			LP.ToolsAndTechniques,
			LP.EssentialMaterial,
			LP.AssessmentQuestion,
			LP.TeacherExample,
			LP.GuidedPractice,
			LP.IndependentPractice,
			LP.SubTopic,
			datepart(MONTH,Lp.StartDate) AS MonthId,
		    datename(MONTH,Lp.StartDate) AS Monthname,
			@rIsWithHeader AS IsWithHeader,
			(CASE WHEN @rIsWithHeader=1 THEN OI.CertificateHeaderA4 ELSE NULL END)AS MarksheetHeaderA4,
			--Added by dhananjay for mantis start - 37295
			ISNULL(LP.PeriodCount,0) AS PeriodCount,
			ISNULL(LP.Session,'') AS Session,
			ISNULL(LP.Remark,'') AS Remark,
			ISNULL(SM.Code,'') AS SubjectCode,
			'' AS BatchName
			--Added by dhananjay for mantis end - 37295
	FROM 
			--sAcademic.tLessonPlan LP
			----INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id=LP.EmployeeId
			--inner JOIN sAcademic.tTopicMaster TM ON TM.Id=LP.TopicId
			-- INNER JOIN sAcademic.vTeacherSubjectDivision vTSD ON vTSD.DivisionId = LP.DivisionId
			--AND vTSD.ClassId = TM.ClassId 
			--AND vTSD.SubjectId = TM.SubjectId 
			--AND vTSD.EmployeeId = LP.EmployeeId
			
			sAcademic.tLessonPlan LP
			INNER JOIN sSetup.tDivisionMaster DM ON LP.DivisionId = DM.Id
			INNER JOIN sSetup.tClassMaster CM ON CM.Id = DM.ClassId
			LEFT JOIN sHrm.tEmployeeMaster EM ON EM.Id=LP.EmployeeId
			INNER JOIN sAcademic.tTopicMaster TM ON TM.Id=LP.TopicId 
			INNER JOIN sSetup.tSubjectMaster SM ON SM.Id = TM.SubjectId   
			LEFT JOIN sSetup.tOrgImages OI ON OI.Orgid = CM.OrgId

	WHERE 
		--(LP.BatchId = @rBatchId) 
		--AND ((LP.EmployeeId = @rEmployeeId) OR (@rEmployeeId = 0))
		----AND ((LP.Id = @rId) OR (@rId = 0))
		--AND ((TM.ClassId = @rClassId) OR (@rClassId = 0))
		--AND ((vTSD.DivisionId = @rDivisionId) OR (@rDivisionId = 0))
		--AND ((TM.SubjectId = @rSubjectId) OR (@rSubjectId = 0))
		--AND ((LP.IsCompleted='False') OR (LP.IsCompleted=@rIsCompleted))
		--AND ((LP.StartDate >= @rStartDate) OR (@rStartDate= ''))
		----AND ((LP.StartDate <= @rEndDate)  OR (@rEndDate= ''))
 
		(LP.BatchId = @rBatchId) 
		AND ((LP.EmployeeId = @rEmployeeId) OR (@rEmployeeId=0))
		AND ((TM.ClassId = @rClassId) OR (@rClassId = 0))
		AND ((LP.DivisionId = @rDivisionId) OR (@rDivisionId = 0))
		AND ((TM.SubjectId = @rSubjectId) OR (@rSubjectId = 0))
		AND ((LP.IsCompleted='False') OR (LP.IsCompleted=@rIsCompleted))
		AND ((LP.StartDate >= @rStartDate) OR (@rStartDate= ''))
		AND ((LP.StartDate <= @rEndDate)  OR (@rEndDate= ''))
		AND  ISNULL(EM.IsOtherUser,0) = 0
		--Added by dhananjay mantis : 43006	
		AND ISNULL(CM.IsObsolete,0) = 0
		AND ISNULL(DM.IsObsolete,0) = 0
		--Added by dhananjay mantis : 43006	
	ORDER BY
		LP.id 
	END
	ELSE
	BEGIN
	
	SELECT 
			--LP.Id,
			--TM.ClassId,
			--LP.DivisionId,
			--TM.SubjectId,
			--LP.TopicId,
			--LP.NoOfPeriodRequired,
			--LP.Objective,
			--LP.IndicativeHomework,
			--LP.Summary,
			--LP.StartDate,
			--LP.EndDate,
			--LP.IsCompleted,
			--LP.EmployeeId,
			--LP.BatchId,
			--LP.CreatedUserId,
			--LP.CreatedDateTime,
			--TM.Title AS TopicName,
			--vTSD.ClassTitle+' - '+ vTSD.DivisionTitle AS ClassDivisionName,
			--vTSD.SubjectName,
			----ISNULL(EM.FirstName,'') + ' ' + ISNULL(EM.LastName,'') AS  EmployeeName,
			--LP.LearningExperience,
			--LP.ToolsAndTechniques,
			--LP.EssentialMaterial,
			--LP.AssessmentQuestion ,
		 -- datepart(MONTH,Lp.StartDate) AS MonthId,
		 -- datename(MONTH,Lp.StartDate) AS Monthname
		  
		  LP.Id,
			TM.ClassId,
		    LP.DivisionId,
			TM.SubjectId,
			LP.TopicId,
			LP.NoOfPeriodRequired,
			LP.Objective,
			LP.IndicativeHomework,
			LP.Summary,
			ISNULL(LP.StartDate,'') AS StartDate ,
			ISNULL(LP.EndDate,'') AS EndDate,
			LP.IsCompleted,
			LP.EmployeeId,
			LP.BatchId,
			LP.CreatedUserId,
			LP.CreatedDateTime,
			TM.Title AS TopicName,
			DM.Code AS ClassDivisionName,
			SM.Title AS SubjectName,
			--vTSD.ClassTitle+' - '+ vTSD.DivisionTitle AS ClassDivisionName,
			 
			--vTSD.SubjectName,
			ISNULL(EM.FirstName,'') + ' ' + ISNULL(EM.LastName,'') AS  EmployeeName,
			LP.LearningExperience,
			LP.ToolsAndTechniques,
			LP.EssentialMaterial,
			LP.AssessmentQuestion,
			LP.TeacherExample,
			LP.GuidedPractice,
			LP.IndependentPractice,
			LP.SubTopic,
			datepart(MONTH,Lp.StartDate) AS MonthId,
		    datename(MONTH,Lp.StartDate) AS Monthname,
			@rIsWithHeader AS IsWithHeader,
			(CASE WHEN @rIsWithHeader=1 THEN OI.CertificateHeaderA4 ELSE NULL END)AS MarksheetHeaderA4,
			--Added by dhananjay for mantis start - 37295
			ISNULL(LP.PeriodCount,0) AS PeriodCount,
			ISNULL(LP.Session,'') AS Session,
			ISNULL(LP.Remark,'') AS Remark,
			ISNULL(SM.Code,'') AS SubjectCode,
			BM.Title AS BatchName
			--Added by dhananjay for mantis end - 37295
	FROM 
			--sAcademic.tLessonPlan LP
			----INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id=LP.EmployeeId
			--inner JOIN sAcademic.tTopicMaster TM ON TM.Id=LP.TopicId
			-- INNER JOIN sAcademic.vTeacherSubjectDivision vTSD ON vTSD.DivisionId = LP.DivisionId
			--AND vTSD.ClassId = TM.ClassId 
			--AND vTSD.SubjectId = TM.SubjectId 
			--AND vTSD.EmployeeId = LP.EmployeeId
			
			sAcademic.tLessonPlan LP
			INNER JOIN sSetup.tDivisionMaster DM ON LP.DivisionId = DM.Id
			INNER JOIN sSetup.tClassMaster CM ON CM.Id = DM.ClassId
			LEFT JOIN sHrm.tEmployeeMaster EM ON EM.Id=LP.EmployeeId
			INNER JOIN sAcademic.tTopicMaster TM ON TM.Id=LP.TopicId 
			INNER JOIN sSetup.tSubjectMaster SM ON SM.Id = TM.SubjectId   
			LEFT JOIN sSetup.tOrgImages OI ON OI.Orgid = CM.OrgId
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = LP.BatchId--Added by dhananjay for mantis  - 37295
			
	WHERE 
		--(LP.BatchId = @rBatchId) 
		--AND ((LP.EmployeeId = @rEmployeeId) OR (@rEmployeeId = 0))
		----AND ((LP.Id = @rId) OR (@rId = 0))
		--AND ((TM.ClassId = @rClassId) OR (@rClassId = 0))
		--AND ((vTSD.DivisionId = @rDivisionId) OR (@rDivisionId = 0))
		--AND ((TM.SubjectId = @rSubjectId) OR (@rSubjectId = 0))
		--AND ((LP.IsCompleted='False') OR (LP.IsCompleted=@rIsCompleted))
		--AND ((LP.StartDate >= @rStartDate) OR (@rStartDate= ''))
		----AND ((LP.StartDate <= @rEndDate)  OR (@rEndDate= ''))
 
		(LP.BatchId = @rBatchId) 
		AND ((LP.EmployeeId = @rEmployeeId) OR (@rEmployeeId=0))
		AND ((TM.ClassId = @rClassId) OR (@rClassId = 0))
		AND ((LP.DivisionId = @rDivisionId) OR (@rDivisionId = 0))
		AND ((TM.SubjectId = @rSubjectId) OR (@rSubjectId = 0))
		AND ((@rStatus = 2) OR (LP.IsCompleted=@rIsCompleted))
		AND ((LP.StartDate >= @rStartDate) OR (ISNULL(@rStartDate,'')= ''))
		AND ((LP.StartDate <= @rEndDate)  OR (ISNULL(@rEndDate,'')= ''))
		AND  ISNULL(EM.IsOtherUser,0) = 0
		--Added by dhananjay mantis : 43006	
		AND ISNULL(CM.IsObsolete,0) = 0
		AND ISNULL(DM.IsObsolete,0) = 0
		--Added by dhananjay mantis : 43006	
	ORDER BY
		LP.id 
	END
END
GO
PRINT N'Altering Procedure [sAcademic].[pTaskConsolidatedDashboardGet]...';


GO
ALTER PROCEDURE [sAcademic].[pTaskConsolidatedDashboardGet]

     @rOrgGroupId smallint,
     @rTypeId int,
     @rDate date,
     @rType nvarchar(20),
     @rCommonOrgGroupBatchId int=0
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 

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

SELECT @lConfigValueDashboard = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 592  AND SourceTypeId = 2010 AND SourceId = @rOrgGroupId;

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


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

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

	---Attendance Task Wise 
	IF( @rType = 'Attendance')
		BEGIN
			IF(@rTypeId = 1)
				BEGIN
				SELECT 				
			OGM.Id AS OrgGroupId,
			OGM.Title AS OrgGroupName,
			 (
				 SELECT ISNULL(Count(StudentCount),0) AS DoneAttendance FROM
				(SELECT 
				(SELECT COUNT(Id) FROM sStudent.tAcademic WHERE DivisionId= A.DivisionId AND BatchId = A.BatchId) AS StudentCount,O.Id  AS OrgGroupId,
				ROW_NUMBER() OVER ( PARTITION BY A.DivisionId,A.OrgId order by A.DivisionId) as rowno
				FROM sStudent.tAcademic A
				INNER JOIN sStudent.tStudentMaster SM  ON SM.Id= A.StudentId AND SM.StatusId =1
				INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId
				INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BM.OrgId
				INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
				INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
				INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
				INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId
				WHERE  OGM.Id = O.Id AND COGBM.Id=@rCommonOrgGroupBatchId AND    A.Id  NOT in 
				( select AcademicId from sAttendance.tStudentRegister SR  WHERE SR.AttendanceDate = CONVERT(char(10),@rDate,126))
				 -- IsInContext
				 AND BM.IsInContext = 1
				) Temp WHERE rowno=1
			 ) AS Pending,
			 (SELECT
					COUNT(DISTINCT DM.Id) AS TotalDivision
			  FROM
					sSetup.tDivisionMaster DM
					INNER JOIN sStudent.tAcademic SA ON SA.DivisionId = DM.Id
					INNER JOIN sStudent.tStudentMaster SM  ON SM.Id= SA.StudentId AND SM.StatusId =1
					INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId
					INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
					INNER JOIN sSetup.tOrgGroupMaster OGMR ON OGMR.Id =  OGBM.OrgGroupId		    
					INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
					INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SA.OrgId
				   
			  WHERE OGM.Id =OGMR.Id
			  AND DM.IsObsolete=0 AND OGMR.IsObsolete = 0 --AND BM.IsActive = 1 
					AND COGBM.Id=@rCommonOrgGroupBatchId  AND((OGMR.Id= @rOrgGroupId)OR(@rOrgGroupId=0))
					-- IsInContext
					AND BM.IsInContext = 1
			) AS Total,
			(
			SELECT ISNULL(Count(StudentCount),0) AS DoneAttendance FROM
				(SELECT 
				(SELECT COUNT(Id) FROM sStudent.tAcademic WHERE DivisionId= A.DivisionId AND BatchId = A.BatchId) AS StudentCount,O.Id  AS OrgGroupId,
				ROW_NUMBER() OVER ( PARTITION BY A.DivisionId,A.OrgId order by A.DivisionId) as rowno
				FROM sStudent.tAcademic A
				INNER JOIN sStudent.tStudentMaster SM  ON SM.Id= A.StudentId AND SM.StatusId =1
				INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId
				INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BM.OrgId
				INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
				INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		   
				INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
				INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId
				WHERE  OGM.Id = O.Id AND COGBM.Id=@rCommonOrgGroupBatchId AND    A.Id   in 
				( select AcademicId from sAttendance.tStudentRegister SR  WHERE SR.AttendanceDate = CONVERT(char(10),@rDate,126))
				-- IsInContext
				AND BM.IsInContext = 1
				) Temp WHERE rowno=1) AS Complated
      FROM 
			sSetup.tOrgGroupMaster OGM
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.OrgGroupId = OGM.Id
			
			INNER JOIN sStudent.tAcademic SA ON SA.OrgId = OM.Id
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId
		    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
				
					 WHERE 
		    OGM.IsObsolete = 0 AND BM.IsActive = 1 AND COGBM.Id=@rCommonOrgGroupBatchId AND((OGM.Id= @rOrgGroupId)OR(@rOrgGroupId=0)) 
			-- IsInContext
			AND BM.IsInContext = 1
	 GROUP BY
			OGM.Id, OGM.Title
	 ORDER BY
			OGM.Id	
				
				
		--			  SELECT 				
		--	OGM.Id AS OrgGroupId,
		--	OGM.Title AS OrgGroupName,
		--	 CONVERT(nvarchar(10),ISNULL(AT1.DivisionPresent,0)) AS Pending
		--	,CONVERT(nvarchar(10),ISNULL(AT2.TotalDivision,0)) AS Total
		--	,CONVERT(nvarchar(10),ISNULL(AT3.DoneAttendance,0)) AS Complated
  --    FROM 
		--	sSetup.tOrgGroupMaster OGM
		--	INNER JOIN sSetup.tOrganizationMaster OM ON OM.OrgGroupId = OGM.Id
			
		--	INNER JOIN sStudent.tAcademic SA ON SA.OrgId = OM.Id
		--	INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId
		--    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		--    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		--    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
		    
		--	LEFT JOIN --Attendance Pending
		--	(
		--	SELECT ISNULL(Count(StudentCount),0) AS DivisionPresent,OrgGroupId FROM
		--		(SELECT 
		--		(SELECT COUNT(Id) FROM sStudent.tAcademic WHERE DivisionId= A.DivisionId AND BatchId = A.BatchId) AS StudentCount,O.Id  AS OrgGroupId,
		--		ROW_NUMBER() OVER ( PARTITION BY A.DivisionId,A.OrgId order by A.DivisionId) as rowno
		--		FROM sStudent.tAcademic A
		--		INNER JOIN sStudent.tStudentMaster SM  ON SM.Id= A.StudentId AND SM.StatusId =1
		--		INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId
		--		INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BM.OrgId
		--		INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		--		INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		--		INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
		--		INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId
		--		WHERE  COGBM.Id=@rCommonOrgGroupBatchId AND    A.Id  not in 
		--		( select AcademicId from sAttendance.tStudentRegister SR  WHERE SR.AttendanceDate = CONVERT(char(10),@rDate,126))
		--		) Temp WHERE rowno=1  GROUP BY OrgGroupId
		--		) AT1 ON AT1.OrgGroupId = OGM.Id
		--	  --SELECT
		--		 --  COUNT(DISTINCT DM.Id) AS DivisionPresent,
		--		 --  OGM.Id AS OrgGroupId
		--	  --FROM
		--		 -- sSetup.tDivisionMaster DM
		--		 -- INNER JOIN sStudent.tAcademic SA ON SA.DivisionId = DM.Id
		--		 -- INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId
		--		 -- INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		--		 -- INNER JOIN sSetup.tOrgGroupMaster OGM ON OGM.Id =  OGBM.OrgGroupId		    
		--		 -- INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
		--		 -- INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SA.OrgId
		--		 -- INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=SA.Id 
		--	  --WHERE
		--		 -- SR.IsPresent = 1 AND SR.AttendanceDate = @rDate 
		--		 -- --AND BM.IsActive=1 
		--		 -- AND DM.IsObsolete=0 AND COGBM.Id=@rCommonOrgGroupBatchId  AND((OGM.Id= @rOrgGroupId)OR(@rOrgGroupId=0))
		--	  --GROUP BY
		--		 -- OGM.Id
		--	--) AT1 ON AT1.OrgGroupId = OGM.Id
		--	LEFT JOIN  --Attendance Total
		--	(
		--	  SELECT
		--			COUNT(DISTINCT DM.Id) AS TotalDivision,
		--			OGM.Id AS OrgGroupId
		--	  FROM
		--			sSetup.tDivisionMaster DM
		--			INNER JOIN sStudent.tAcademic SA ON SA.DivisionId = DM.Id
		--			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId
		--			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		--			INNER JOIN sSetup.tOrgGroupMaster OGM ON OGM.Id =  OGBM.OrgGroupId		    
		--			INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
		--			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SA.OrgId
				   
		--	  WHERE
		--			DM.IsObsolete=0 AND OGM.IsObsolete = 0 --AND BM.IsActive = 1 
		--			AND COGBM.Id=@rCommonOrgGroupBatchId  AND((OGM.Id= @rOrgGroupId)OR(@rOrgGroupId=0))
		--	  GROUP BY
		--			OGM.Id
		--	) AT2 ON AT2.OrgGroupId = OGM.Id
		--	LEFT JOIN --Attendance Done
		--	(
		--	SELECT ISNULL(Count(StudentCount),0) AS DoneAttendance,OrgGroupId FROM
		--		(SELECT 
		--		(SELECT COUNT(Id) FROM sStudent.tAcademic WHERE DivisionId= A.DivisionId AND BatchId = A.BatchId) AS StudentCount,O.Id  AS OrgGroupId,
		--		ROW_NUMBER() OVER ( PARTITION BY A.DivisionId,A.OrgId order by A.DivisionId) as rowno
		--		FROM sStudent.tAcademic A
		--		INNER JOIN sStudent.tStudentMaster SM  ON SM.Id= A.StudentId AND SM.StatusId =1
		--		INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId
		--		INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BM.OrgId
		--		INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		--		INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		--		INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
		--		INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId
		--		WHERE  COGBM.Id=@rCommonOrgGroupBatchId AND    A.Id   in 
		--		( select AcademicId from sAttendance.tStudentRegister SR  WHERE SR.AttendanceDate = CONVERT(char(10),@rDate,126))
		--		) Temp WHERE rowno=1  GROUP BY OrgGroupId
		--		) AT3 ON AT3.OrgGroupId = OGM.Id

			
	 --WHERE 
		--    OGM.IsObsolete = 0 AND BM.IsActive = 1 AND COGBM.Id=@rCommonOrgGroupBatchId AND((OGM.Id= @rOrgGroupId)OR(@rOrgGroupId=0)) 
	 --GROUP BY
		--	OGM.Id, OGM.Title,DivisionPresent,TotalDivision,DoneAttendance
	 --ORDER BY
		--	OGM.Id	
				END
				ELSE IF( @rTypeId = 11)
					BEGIN
						
		SELECT OrgGroupId,OrgGroupName,DivisionId,ClassDivision,EmployeeCode,ISNULL(EmployeeName,'') AS EmployeeName,ISNULL(EmployeeContact,'')AS EmployeeContact
		,ClassOrderIndex,DivisionOrderIndex--add f or mantis : 0042058
		FROM(SELECT 
						O.Id as OrgGroupId,
						O.Title As OrgGroupName,
						OMEL.Id As OrgId,
						(OMEL.Title) As Organization,
						A.ClassId,
						DM.Id AS DivisionId,
						DM.Code AS ClassDivision,
						(SELECT COUNT(Id) FROM sStudent.tAcademic WHERE DivisionId= A.DivisionId AND BatchId = A.BatchId) AS StudentCount,
						A.Id As AcademicId,
						EM.Code As EmployeeCode,
						(EM.FirstName+' '+Em.LastName) AS EmployeeName,
						(EC.MobileNumber) AS EmployeeContact,
						ROW_NUMBER() OVER ( PARTITION BY A.DivisionId,A.OrgId order by A.DivisionId) as rowno
						,CM.OrderIndex AS ClassOrderIndex --add f or mantis : 0042058
						,DM.OrderIndex AS DivisionOrderIndex --add f or mantis : 0042058
			FROM sStudent.tAcademic A
						INNER JOIN sStudent.tStudentMaster SM  ON SM.Id= A.StudentId AND SM.StatusId =1
						INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId
						INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BM.OrgId
						INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
						INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
						INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
						INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId
						LEFT JOIN sHrm.tEmployeeMaster EM ON EM.ID=DM.InchargeEmployeeId AND  ISNULL(EM.IsOtherUser,0) = 0
						LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
						INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId --add f or mantis : 0042058
			WHERE  O.id = @rOrgGroupId AND COGBM.Id=@rCommonOrgGroupBatchId
				   -- IsInContext
				   AND BM.IsInContext = 1
						--AND A.Id not in (select AcademicId from sAttendance.tStudentRegister SR  WHERE SR.AttendanceDate = CONVERT(char(10),  @rDate,126))
						) Temp 
		WHERE 
						rowno=1
						ORDER BY OrgId, ClassOrderIndex,DivisionOrderIndex --add f or mantis : 0042058
					END
				ELSE IF( @rTypeId = 12)
					BEGIN
						
		SELECT OrgGroupId,OrgGroupName,DivisionId,ClassDivision,EmployeeCode,ISNULL(EmployeeName,'') AS EmployeeName,ISNULL(EmployeeContact,'')AS EmployeeContact
		,ClassOrderIndex,DivisionOrderIndex--add f or mantis : 0042058
		FROM(SELECT 
						O.Id as OrgGroupId,
						O.Title As OrgGroupName,
						OMEL.Id As OrgId,
						(OMEL.Title) As Organization,
						A.ClassId,
						DM.Id AS DivisionId,
						DM.Code AS ClassDivision,
						(SELECT COUNT(Id) FROM sStudent.tAcademic WHERE DivisionId= A.DivisionId AND BatchId = A.BatchId) AS StudentCount,
						A.Id As AcademicId,
						EM.Code As EmployeeCode,
						(EM.FirstName+' '+Em.LastName) AS EmployeeName,
						(EC.MobileNumber) AS EmployeeContact,
						ROW_NUMBER() OVER ( PARTITION BY A.DivisionId,A.OrgId order by A.DivisionId) as rowno
						,CM.OrderIndex AS ClassOrderIndex --add f or mantis : 0042058
						,DM.OrderIndex AS DivisionOrderIndex --add f or mantis : 0042058
			FROM sStudent.tAcademic A
						INNER JOIN sStudent.tStudentMaster SM  ON SM.Id= A.StudentId AND SM.StatusId =1
						INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId
						INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BM.OrgId
						INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
						INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
						INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
						INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId
						LEFT JOIN sHrm.tEmployeeMaster EM ON EM.ID=DM.InchargeEmployeeId AND  ISNULL(EM.IsOtherUser,0) = 0
						LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
						INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId --add f or mantis : 0042058
			WHERE  O.id = @rOrgGroupId AND COGBM.Id=@rCommonOrgGroupBatchId
						AND A.Id not in (select AcademicId from sAttendance.tStudentRegister SR  WHERE SR.AttendanceDate = CONVERT(char(10),  @rDate,126))
						-- IsInContext
						AND BM.IsInContext = 1
						) Temp 
		WHERE 
						rowno=1
						ORDER BY OrgId,ClassOrderIndex,DivisionOrderIndex --add f or mantis : 0042058
					END
				ELSE IF (@rTypeId = 13)
					BEGIN
						
		SELECT OrgGroupId,OrgGroupName,DivisionId,ClassDivision,EmployeeCode,ISNULL(EmployeeName,'') AS EmployeeName,ISNULL(EmployeeContact,'')AS EmployeeContact
		,ClassOrderIndex,DivisionOrderIndex--add f or mantis : 0042058
		FROM(SELECT 
						O.Id as OrgGroupId,
						O.Title As OrgGroupName,
						OMEL.Id As OrgId,
						(OMEL.Title) As Organization,
						A.ClassId,
						DM.Id AS DivisionId,
						DM.Code AS ClassDivision,
						(SELECT COUNT(Id) FROM sStudent.tAcademic WHERE DivisionId= A.DivisionId AND BatchId = A.BatchId) AS StudentCount,
						A.Id As AcademicId,
						EM.Code As EmployeeCode,
						(EM.FirstName+' '+Em.LastName) AS EmployeeName,
						(EC.MobileNumber) AS EmployeeContact,
						ROW_NUMBER() OVER ( PARTITION BY A.DivisionId,A.OrgId order by A.DivisionId) as rowno
						,CM.OrderIndex AS ClassOrderIndex --add f or mantis : 0042058
						,DM.OrderIndex AS DivisionOrderIndex --add f or mantis : 0042058
			FROM sStudent.tAcademic A
						INNER JOIN sStudent.tStudentMaster SM  ON SM.Id= A.StudentId AND SM.StatusId =1
						INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId
						INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BM.OrgId
						INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
						INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
						INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
						INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId
						LEFT JOIN sHrm.tEmployeeMaster EM ON EM.ID=DM.InchargeEmployeeId AND  ISNULL(EM.IsOtherUser,0) = 0
						LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
						INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId --add f or mantis : 0042058
			WHERE  O.id = @rOrgGroupId AND COGBM.Id=@rCommonOrgGroupBatchId
						AND A.Id  in (select AcademicId from sAttendance.tStudentRegister SR  WHERE SR.AttendanceDate = CONVERT(char(10),  @rDate,126))
						-- IsInContext
						AND BM.IsInContext = 1
						) Temp 
		WHERE 
						rowno=1
						ORDER BY OrgId,ClassOrderIndex,DivisionOrderIndex --add f or mantis : 0042058
					END
		END
	IF(@rType = 'CW/HW')
			IF(@rTypeId=2)
				BEGIN
					SELECT 				
						OGM.Id AS OrgGroupId,
						OGM.Title AS OrgGroupName,
						ISNULL((
-- ClassworkAssigned								
					SELECT COUNT( AC.SubjectId) AS Classwork
					FROM sAcademic.tClasswork AC
						INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = AC.DivisionId
						INNER JOIN sSetup.tBatchMaster BM On BM.Id= AC.BatchId
						INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = BM.OrgId
						INNER JOIN sSetup.tOrgGroupMaster OGM1 ON OGM1.Id = OM.OrgGroupId
						INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.OrgGroupId=OGM.Id
						INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
					WHERE ((OGM1.Id = @rOrgGroupId) OR(@rOrgGroupId = 0)) 
					 
						AND COGBM.Id=@rCommonOrgGroupBatchId 
						AND AC.ClassWorkDate=@rDate 
						AND ClassworkStatusId = 1 
						AND (Classwork != '' OR  Classwork = NULL)
						-- IsInContext
						AND BM.IsInContext = 1 
						AND OGM.Id = OGM1.Id),0) 
					AS ClassworkAssigned,
					ISNULL((
--ClassworkNotAssigned
					SELECT COUNT(*)
					FROM sAcademic.tTeacherSubjectDivision TSD1 
					INNER JOIN sSetup.tSubjectMaster SM ON TSD1.SubjectId=SM.Id 
					INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=TSD1.DivisionId 
					INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = DM.Orgid
					INNER JOIN sSetup.tOrgGroupMaster OGM1 ON OGM1.Id = OM.OrgGroupId
					Where 
					OGM1.Id= OGM.Id
					AND 
					NOT EXISTS(SELECT  *
					FROM sAcademic.tTeacherSubjectDivision TSD 
					INNER JOIN sSetup.tSubjectMaster SM ON TSD.SubjectId=SM.Id 
					INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=TSD.DivisionId 
					INNER JOIN sAcademic.tClasswork AC ON TSD.SubjectId=AC.SubjectId and  TSD.DivisionId=AC.DivisionId
					Where TSD.DivisionId = TSD1.DivisionId AND ((OGM1.Id = @rOrgGroupId) OR(@rOrgGroupId = 0)) AND TSD.SubjectId = TSD1.SubjectId AND AC.ClassWorkDate=@rDate)),0) 
					AS ClassworkNotAssigned,
					ISNULL((
--ClassworkNotApplicable
					SELECT COUNT( AC.SubjectId) AS Classwork 
					FROM sAcademic.tClasswork AC
						INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = AC.DivisionId
						INNER JOIN sSetup.tBatchMaster BM ON BM.Id= AC.BatchId
						INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = BM.OrgId
						INNER JOIN sSetup.tOrgGroupMaster OGM1 ON OGM1.Id = OM.OrgGroupId
						INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.OrgGroupId=OGM1.Id
						INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
					WHERE AC.ClassWorkDate=@rDate 
						AND ClassworkStatusId = 2 
						AND COGBM.Id=@rCommonOrgGroupBatchId  
						-- IsInContext
						AND BM.IsInContext = 1
						AND OGM.Id = OGM1.Id),0) 
					AS ClassworkNotApplicable,
					ISNULL((
--HomeWorkAssigned
					SELECT COUNT( AC.SubjectId) AS Classwork
					FROM sAcademic.tClasswork AC
						INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = AC.DivisionId
						INNER JOIN sSetup.tBatchMaster BM On BM.Id= AC.BatchId
						INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = BM.OrgId
						INNER JOIN sSetup.tOrgGroupMaster OGM1 ON OGM1.Id = OM.OrgGroupId
						INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.OrgGroupId=OGM.Id
						INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
					 WHERE ((OGM1.Id = @rOrgGroupId) OR(@rOrgGroupId = 0)) 
					 
						AND COGBM.Id=@rCommonOrgGroupBatchId 
						AND AC.ClassWorkDate=@rDate 
						AND HomeWorkStatusId = 1 
						AND (HomeWork != '' OR HomeWork=NULL) 
						-- IsInContext
						AND BM.IsInContext = 1
						AND OGM.Id = OGM1.Id),0) 
					AS HomeWorkAssigned,
					ISNULL((
--HomeWorkNotAssigned
					SELECT COUNT(*)
					FROM sAcademic.tTeacherSubjectDivision TSD1 
					INNER JOIN sSetup.tSubjectMaster SM ON TSD1.SubjectId=SM.Id 
					INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=TSD1.DivisionId 
					INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = DM.Orgid
					INNER JOIN sSetup.tOrgGroupMaster OGM1 ON OGM1.Id = OM.OrgGroupId
					Where 
					OGM1.Id= OGM.Id
					AND 
					NOT EXISTS(SELECT  *
					FROM sAcademic.tTeacherSubjectDivision TSD 
					INNER JOIN sSetup.tSubjectMaster SM ON TSD.SubjectId=SM.Id 
					INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=TSD.DivisionId 
					INNER JOIN sAcademic.tClasswork AC ON TSD.SubjectId=AC.SubjectId and  TSD.DivisionId=AC.DivisionId
					INNER JOIN sSetup.tBatchMaster BM ON BM.Id= AC.BatchId
					Where TSD.DivisionId = TSD1.DivisionId AND BM.IsInContext = 1 AND ((OGM1.Id = @rOrgGroupId) OR(@rOrgGroupId = 0)) AND TSD.SubjectId = TSD1.SubjectId 
					AND AC.ClassWorkDate=@rDate)),0) 
					AS HomeWorkNotAssigned,
					ISNULL((
--HomeWorkNotApplicable
					SELECT COUNT( AC.SubjectId) AS Classwork 
					FROM sAcademic.tClasswork AC
						INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = AC.DivisionId
						INNER JOIN sSetup.tBatchMaster BM ON BM.Id= AC.BatchId
						INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = BM.OrgId
						INNER JOIN sSetup.tOrgGroupMaster OGM1 ON OGM1.Id = OM.OrgGroupId
						INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.OrgGroupId=OGM1.Id
						INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
					WHERE
						AC.ClassWorkDate=@rDate 
						AND HomeWorkStatusId = 2
						AND COGBM.Id=@rCommonOrgGroupBatchId  
						-- IsInContext
						AND BM.IsInContext = 1
						AND OGM.Id = OGM1.Id),0) 
					AS HomeWorkNotApplicable
						 FROM 
								sSetup.tOrgGroupMaster OGM
								INNER JOIN sSetup.tOrganizationMaster OM ON OM.OrgGroupId = OGM.Id
								INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.OrgGroupId=OM.OrgGroupId
								INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
								INNER JOIN sStudent.tAcademic A ON A.OrgId = OM.Id
								INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId
								--LEFT JOIN 
								--(
								--  SELECT 
								--		COUNT(DISTINCT AC.SubjectId) AS Classwork,
								--		OGM.Id AS OrgGroupId
								--  FROM sAcademic.tClasswork AC
								--		INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = AC.DivisionId
								--		INNER JOIN sSetup.tBatchMaster BM On BM.Id= AC.BatchId
								--		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = BM.OrgId
								--		INNER JOIN sSetup.tOrgGroupMaster OGM ON OGM.Id = OM.OrgGroupId
								--		INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.OrgGroupId=OGM.Id
								--		INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
								--  WHERE ((OGM.Id = @rOrgGroupId) OR(@rOrgGroupId = 0)) AND BM.IsActive = 1 AND COGBM.Id=@rCommonOrgGroupBatchId 
								--		AND AC.ClassWorkDate=@rDate AND ClassworkStatusId = 1 AND (Classwork != '' OR  Classwork = NULL)
								--  GROUP BY 
								--		OGM.Id
								--) CW1 ON CW1.OrgGroupId = OGM.Id
				--				LEFT JOIN(
				--					  SELECT
				--							COUNT(DISTINCT SM.Id) AS ClassWork,
				--							OGM.Id AS OrgGroupId
				--					  FROM
				--							sSetup.tSubjectMaster SM
				--							INNER JOIN sSetup.tClassSubject CS ON CS.SubjectId = SM.Id
				--							INNER JOIN sStudent.tAcademic SA ON SA.ClassId = CS.ClassId
				--							INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId
				--							INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
				--							INNER JOIN sSetup.tOrgGroupMaster OGM ON OGM.Id =  OGBM.OrgGroupId		    
				--							INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
				--							INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SA.OrgId
				    
				--					  WHERE
				--							--BM.IsActive=1 AND 
				--							SM.IsObsolete=0 AND OGM.IsObsolete = 0 AND COGBM.Id=@rCommonOrgGroupBatchId  AND((OGM.Id= @rOrgGroupId)OR(@rOrgGroupId=0))
				--					  GROUP BY
				--							OGM.Id
				--						) CW2 ON CW2.OrgGroupId = OGM.Id

				--				--LEFT JOIN 
				--				--(
				--				--  SELECT 
				--				--		COUNT(DISTINCT AC.SubjectId) AS Classwork,
				--				--		OGM.Id AS OrgGroupId
				--				--  FROM sAcademic.tClasswork AC
				--				--	   INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = AC.DivisionId
				--				--	   INNER JOIN sSetup.tBatchMaster BM On BM.Id= AC.BatchId
				--				--	   INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = BM.OrgId
				--				--	   INNER JOIN sSetup.tOrgGroupMaster OGM ON OGM.Id = OM.OrgGroupId
				--				--	   INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.OrgGroupId=OGM.Id
				--				--	   INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
				--				--  WHERE 
				--				--	   AC.ClassWorkDate=@rDate AND (Classwork = NULL OR Classwork='') AND BM.IsActive = 1 AND COGBM.Id=@rCommonOrgGroupBatchId 
				--				--  GROUP BY 
				--				--		OGM.Id
				--				--) CW2 ON CW2.OrgGroupId = OGM.Id
				--				LEFT JOIN 
				--				(
				--				  SELECT 
				--						COUNT(DISTINCT AC.SubjectId) AS Classwork,
				--						OGM.Id AS OrgGroupId
				--				  FROM sAcademic.tClasswork AC
				--					   INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = AC.DivisionId
				--					   INNER JOIN sSetup.tBatchMaster BM ON BM.Id= AC.BatchId
				--					   INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = BM.OrgId
				--					   INNER JOIN sSetup.tOrgGroupMaster OGM ON OGM.Id = OM.OrgGroupId
				--					   INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.OrgGroupId=OGM.Id
				--					   INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
				--				  WHERE 
				--					   AC.ClassWorkDate=@rDate AND ClassworkStatusId = 2 AND BM.IsActive = 1 AND COGBM.Id=@rCommonOrgGroupBatchId 
				--				  GROUP BY 
				--						OGM.Id
				--				) CW3 ON CW3.OrgGroupId = OGM.Id
				--				LEFT JOIN 
				--(
				--  SELECT 
				--		COUNT(DISTINCT AC.SubjectId) AS Homework,
				--		OGM.Id AS OrgGroupId
				--  FROM sAcademic.tClasswork AC
				--	   INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = AC.DivisionId
				--	   INNER JOIN sStudent.tAcademic SA ON SA.DivisionId = DM.Id
				--	   INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId
				--	   INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
				--	   INNER JOIN sSetup.tOrgGroupMaster OGM ON OGM.Id = OGBM.OrgGroupId		    
				--	   INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
				--	   INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = BM.OrgId
					   
				--  WHERE 
				--	   AC.ClassWorkDate=@rDate AND HomeWorkStatusId = 1 AND (HomeWork != '' OR HomeWork=NULL)
				--	   --AND BM.IsActive = 1 
				--	   AND COGBM.Id=@rCommonOrgGroupBatchId 
				--  GROUP BY 
				--		OGM.Id
				--) HW1 ON HW1.OrgGroupId = OGM.Id
				--LEFT JOIN 
				--(
				--  SELECT 
				--		COUNT(DISTINCT AC.SubjectId) AS Homework,
				--		OGM.Id AS OrgGroupId
				--  FROM sAcademic.tClasswork AC
				--	   INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = AC.DivisionId
				--	   INNER JOIN sStudent.tAcademic SA ON SA.DivisionId = DM.Id
				--	   INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId
				--	   INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
				--	   INNER JOIN sSetup.tOrgGroupMaster OGM ON OGM.Id =  OGBM.OrgGroupId		    
				--	   INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
				--	   INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = BM.OrgId
					   
				--  WHERE 
				--	   AC.ClassWorkDate=@rDate AND HomeWorkStatusId = 1 AND(HomeWork = NULL OR HomeWork='')
				--	   --AND BM.IsActive = 1 
				--	   AND COGBM.Id=@rCommonOrgGroupBatchId 
				--  GROUP BY 
				--		OGM.Id
				--) HW2 ON HW2.OrgGroupId = OGM.Id
				--LEFT JOIN 
				--(
				--  SELECT 
				--		COUNT(DISTINCT AC.SubjectId) AS Homework,
				--		OGM.Id AS OrgGroupId
				--  FROM sAcademic.tClasswork AC
				--	   INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = AC.DivisionId
				--	   INNER JOIN sSetup.tBatchMaster BM ON BM.Id= AC.BatchId
				--	   INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
				--	   INNER JOIN sSetup.tOrgGroupMaster OGM ON OGM.Id =  OGBM.OrgGroupId		    
				--	   INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
				--	   INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = BM.OrgId
					 
				--  WHERE 
				--	   AC.ClassWorkDate=@rDate AND HomeWorkStatusId = 2 AND BM.IsActive = 1 AND COGBM.Id=@rCommonOrgGroupBatchId 
				--  GROUP BY 
				--		OGM.Id
				--) HW3 ON HW3.OrgGroupId = OGM.Id
						 WHERE 
								OGM.IsObsolete = 0  AND Bm.IsActive = 1 AND COGBM.Id=@rCommonOrgGroupBatchId  AND((OGM.Id= @rOrgGroupId)OR(@rOrgGroupId=0))
								-- IsInContext
								AND BM.IsInContext = 1
						 GROUP BY OGM.Id, OGM.Title
							--	OGM.Id, OGM.Title,CW1.Classwork,CW2.Classwork, CW3.Classwork,HW1.HomeWork,HW2.HomeWork, HW3.HomeWork
						 ORDER BY
								OGM.Id
				END
				ELSE IF( @rTypeId = 21)
					BEGIN
						SELECT OGM.Id AS OrgGroupId, OGM.Title AS OrgGroupName,DM.Code AS ClassDivision,SM.Title AS SubjectName,EM.Code AS EmployeeCode,EM.FirstName +' '+EM.LastName AS EmployeeName,EC.PresentContactNo AS EmployeeContact,DM.Id AS DivisionId,EM.Id AS EmployeeId,DM.ClassId,SM.Id AS SubjectId,OMM.Id AS OrgId
						,CM.OrderIndex AS ClassOrderIndex,-- add for mantis : 0042058
						DM.OrderIndex AS DivisionOrder -- add for mantis : 0042058
					FROM sAcademic.tClasswork AC
						INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = AC.DivisionId
						INNER JOIN sSetup.tClassMaster CM ON CM.Id=DM.ClassId -- add for mantis : 0042058
						INNER JOIN sSetup.tSubjectMaster SM ON AC.SubjectId=SM.Id 
						INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id = AC.EmployeeId AND  ISNULL(EM.IsOtherUser,0) = 0
						LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
						INNER JOIN sSetup.tBatchMaster BM On BM.Id= AC.BatchId
						INNER JOIN sSetup.tOrganizationMaster OMM ON OMM.Id = BM.OrgId
						INNER JOIN sSetup.tOrgGroupMaster OGM ON OGM.Id = OMM.OrgGroupId
						INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.OrgGroupId=OGM.Id
						INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
					WHERE ((OGM.Id = @rOrgGroupId) OR(@rOrgGroupId = 0)) 
						AND COGBM.Id=@rCommonOrgGroupBatchId 
						AND AC.ClassWorkDate=@rDate 
						AND ClassworkStatusId = 1 
						AND (Classwork != '' OR  Classwork = NULL) 
						-- IsInContext
						AND BM.IsInContext = 1
					Order By OMM.Id ,CM.OrderIndex,DM.OrderIndex --CM.OrderIndex add for mantis : 0042058
					END
				ELSE IF( @rTypeId = 22)
					BEGIN
						SELECT OGM.Id AS OrgGroupId, OGM.Title AS OrgGroupName,DM.Code AS ClassDivision,SM.Title AS SubjectName,
						EM.Code AS EmployeeCode,EM.FirstName +' '+EM.LastName AS EmployeeName,EC.PresentContactNo AS EmployeeContact,
						DM.Id AS DivisionId,EM.Id AS EmployeeId,DM.ClassId,SM.Id AS SubjectId,OM.Id AS OrgId
						,CM.OrderIndex AS ClassOrderIndex,-- add for mantis : 0042058
						DM.OrderIndex AS DivisionOrder -- add for mantis : 0042058
						FROM sAcademic.tTeacherSubjectDivision TSD1 
						INNER JOIN sSetup.tSubjectMaster SM ON TSD1.SubjectId=SM.Id 
						INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=TSD1.DivisionId
						INNER JOIN sSetup.tClassMaster CM ON CM.Id=DM.ClassId -- add for mantis : 0042058
						INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id = TSD1.EmployeeId AND  ISNULL(EM.IsOtherUser,0) = 0
						LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID 
						INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = DM.Orgid
						INNER JOIN sSetup.tOrgGroupMaster OGM ON OGM.Id = OM.OrgGroupId
						Where ((OGM.Id= @rOrgGroupId)OR(@rOrgGroupId=0))
						AND 
						NOT EXISTS(SELECT  *
						FROM sAcademic.tTeacherSubjectDivision TSD 
						INNER JOIN sSetup.tSubjectMaster SM ON TSD.SubjectId=SM.Id 
						INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=TSD.DivisionId 
						INNER JOIN sAcademic.tClasswork AC ON TSD.SubjectId=AC.SubjectId and  TSD.DivisionId=AC.DivisionId
						INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = DM.Orgid
						INNER JOIN sSetup.tOrgGroupMaster OGM1 ON OGM1.Id = OM.OrgGroupId
						INNER JOIN sSetup.tBatchMaster BM On BM.Id= AC.BatchId

						Where TSD.DivisionId = TSD1.DivisionId AND BM.IsInContext = 1 AND((OGM1.Id= @rOrgGroupId)OR(@rOrgGroupId=0)) AND TSD.SubjectId = TSD1.SubjectId AND AC.ClassWorkDate=@rDate )
						Order By OM.Id, CM.OrderIndex,DM.OrderIndex --CM.OrderIndex add for mantis : 0042058
					END
				ELSE IF (@rTypeId = 23)
					BEGIN
						SELECT OGM.Id AS OrgGroupId, OGM.Title AS OrgGroupName,DM.Code AS ClassDivision,SM.Title AS SubjectName,EM.Code AS EmployeeCode,EM.FirstName +' '+EM.LastName AS EmployeeName,EC.PresentContactNo AS EmployeeContact,
						DM.Id AS DivisionId,EM.Id AS EmployeeId,DM.ClassId,SM.Id AS SubjectId,OMM.Id AS OrgId
						,CM.OrderIndex AS ClassOrderIndex,-- add for mantis : 0042058
						DM.OrderIndex AS DivisionOrder -- add for mantis : 0042058
					FROM sAcademic.tClasswork AC
						INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = AC.DivisionId
						INNER JOIN sSetup.tClassMaster CM ON CM.Id=DM.ClassId -- add for mantis : 0042058
						INNER JOIN sSetup.tSubjectMaster SM ON AC.SubjectId=SM.Id 
						INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id = AC.EmployeeId AND  ISNULL(EM.IsOtherUser,0) = 0
						LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
						INNER JOIN sSetup.tBatchMaster BM On BM.Id= AC.BatchId
						INNER JOIN sSetup.tOrganizationMaster OMM ON OMM.Id = BM.OrgId
						INNER JOIN sSetup.tOrgGroupMaster OGM ON OGM.Id = OMM.OrgGroupId
						INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.OrgGroupId=OGM.Id
						INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
					WHERE ((OGM.Id = @rOrgGroupId) OR(@rOrgGroupId = 0)) 
						AND COGBM.Id=@rCommonOrgGroupBatchId 
						AND AC.ClassWorkDate=@rDate 
						AND ClassworkStatusId = 2 
						AND (Classwork != '' OR  Classwork = NULL) 
						-- IsInContext
						AND BM.IsInContext = 1
						Order By OMM.Id,CM.OrderIndex,DM.OrderIndex --CM.OrderIndex add for mantis : 0042058
					END
					ELSE IF (@rTypeId = 24)
						BEGIN
						SELECT OGM.Id AS OrgGroupId, OGM.Title AS OrgGroupName,DM.Code AS ClassDivision,SM.Title AS SubjectName,EM.Code AS EmployeeCode,EM.FirstName +' '+EM.LastName AS EmployeeName,EC.PresentContactNo AS EmployeeContact,
						DM.Id AS DivisionId,EM.Id AS EmployeeId,DM.ClassId,SM.Id AS SubjectId,OMM.Id AS OrgId
						,CM.OrderIndex AS ClassOrderIndex,-- add for mantis : 0042058
						DM.OrderIndex AS DivisionOrder -- add for mantis : 0042058
					FROM sAcademic.tClasswork AC
						INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = AC.DivisionId
						INNER JOIN sSetup.tClassMaster CM ON CM.Id=DM.ClassId -- add for mantis : 0042058
						INNER JOIN sSetup.tSubjectMaster SM ON AC.SubjectId=SM.Id 
						INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id = AC.EmployeeId AND  ISNULL(EM.IsOtherUser,0) = 0
						LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
						INNER JOIN sSetup.tBatchMaster BM On BM.Id= AC.BatchId
						INNER JOIN sSetup.tOrganizationMaster OMM ON OMM.Id = BM.OrgId
						INNER JOIN sSetup.tOrgGroupMaster OGM ON OGM.Id = OMM.OrgGroupId
						INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.OrgGroupId=OGM.Id
						INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
					WHERE ((OGM.Id = @rOrgGroupId) OR(@rOrgGroupId = 0)) 
						AND COGBM.Id=@rCommonOrgGroupBatchId 
						AND AC.ClassWorkDate=@rDate 
						AND HomeWorkStatusId = 1 
						AND (HomeWork != '' OR HomeWork=NULL) 
						-- IsInContext
						AND BM.IsInContext = 1
					Order By OMM.Id, CM.OrderIndex,DM.OrderIndex --CM.OrderIndex add for mantis : 0042058
									
					END
				ELSE IF( @rTypeId = 25)
					BEGIN
						SELECT OGM.Id AS OrgGroupId, OGM.Title AS OrgGroupName,DM.Code AS ClassDivision,SM.Title AS SubjectName,
						EM.Code AS EmployeeCode,EM.FirstName +' '+EM.LastName AS EmployeeName,EC.PresentContactNo AS EmployeeContact,
						DM.Id AS DivisionId,EM.Id AS EmployeeId,DM.ClassId,SM.Id AS SubjectId,OM.Id AS OrgId
						FROM sAcademic.tTeacherSubjectDivision TSD1 
						INNER JOIN sSetup.tSubjectMaster SM ON TSD1.SubjectId=SM.Id 
						INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=TSD1.DivisionId
						INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id = TSD1.EmployeeId AND  ISNULL(EM.IsOtherUser,0) = 0
						LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID 
						INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = DM.Orgid
						INNER JOIN sSetup.tOrgGroupMaster OGM ON OGM.Id = OM.OrgGroupId
						Where ((OGM.Id= @rOrgGroupId)OR(@rOrgGroupId=0))
						AND 
						NOT EXISTS(SELECT  *
						FROM sAcademic.tTeacherSubjectDivision TSD 
						INNER JOIN sSetup.tSubjectMaster SM ON TSD.SubjectId=SM.Id 
						INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=TSD.DivisionId 
						INNER JOIN sAcademic.tClasswork AC ON TSD.SubjectId=AC.SubjectId and  TSD.DivisionId=AC.DivisionId
						INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = DM.Orgid
						INNER JOIN sSetup.tOrgGroupMaster OGM1 ON OGM1.Id = OM.OrgGroupId
						INNER JOIN sSetup.tBatchMaster BM On BM.Id= AC.BatchId
						Where TSD.DivisionId = TSD1.DivisionId AND BM.IsInContext = 1 AND((OGM1.Id= @rOrgGroupId)OR(@rOrgGroupId=0)) AND TSD.SubjectId = TSD1.SubjectId AND AC.ClassWorkDate=@rDate )
						Order By DM.OrderIndex
					END
				ELSE IF (@rTypeId = 26)
					BEGIN
						SELECT OGM.Id AS OrgGroupId, OGM.Title AS OrgGroupName,DM.Code AS ClassDivision,SM.Title AS SubjectName,EM.Code AS EmployeeCode,EM.FirstName +' '+EM.LastName AS EmployeeName,EC.PresentContactNo AS EmployeeContact,DM.Id AS DivisionId,EM.Id AS EmployeeId,DM.ClassId,SM.Id AS SubjectId,OMM.Id AS OrgId
						,CM.OrderIndex AS ClassOrderIndex,-- add for mantis : 0042058
						DM.OrderIndex AS DivisionOrder -- add for mantis : 0042058
					FROM sAcademic.tClasswork AC
						INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = AC.DivisionId
						INNER JOIN sSetup.tClassMaster CM ON CM.Id=DM.ClassId -- add for mantis : 0042058
						INNER JOIN sSetup.tSubjectMaster SM ON AC.SubjectId=SM.Id 
						INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id = AC.EmployeeId AND  ISNULL(EM.IsOtherUser,0) = 0
						LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
						INNER JOIN sSetup.tBatchMaster BM On BM.Id= AC.BatchId
						INNER JOIN sSetup.tOrganizationMaster OMM ON OMM.Id = BM.OrgId
						INNER JOIN sSetup.tOrgGroupMaster OGM ON OGM.Id = OMM.OrgGroupId
						INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.OrgGroupId=OGM.Id
						INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
					WHERE ((OGM.Id = @rOrgGroupId) OR(@rOrgGroupId = 0)) 
						AND COGBM.Id=@rCommonOrgGroupBatchId 
						AND AC.ClassWorkDate=@rDate 
						AND HomeWorkStatusId = 2 
						AND (HomeWork != '' OR HomeWork=NULL)
						-- IsInContext
						AND BM.IsInContext = 1
						Order By OMM.Id, CM.OrderIndex,DM.OrderIndex --CM.OrderIndex add for mantis : 0042058
					END
END
GO
PRINT N'Altering Procedure [sAlert].[pNotificationLogGet]...';


GO



ALTER PROCEDURE [sAlert].[pNotificationLogGet]

		@rOSTypeId tinyint,
		@rUserId bigint,
		@rUserSourceTypeId smallint,
		@rUserSourceId bigint,
		@rSyncedNotificationId bigint,
		@rFromDate Date='',
		@rToDate Date='',
		@rEventId int=0
			 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
	
	DECLARE @lAcademicId bigint
	DECLARE @lEmployeeId bigint
	DECLARE @lStudentId bigint
	DECLARE @lDivisionId int
	DECLARE @lClassId int
	DECLARE @lDepartmentId int
	DECLARE @lOrgId int
	
	IF(@rUserSourceTypeId=2003)
	BEGIN
		SELECT 
		@lAcademicId=AcademicId,
		@lStudentId=StudentId,
		@lDivisionId=DivisionId,
		@lClassId=ClassId,
		@lDepartmentId=DepartmentId,
		@lOrgId=OrgId
		FROM sStudent.vStudentAcademic WHERE StudentId = @rUserSourceId AND IsActiveBatch=1
	 
		SELECT 
				NL.Id AS NotificationId,
				NL.EventId,
				NL.DocumentId,
				NL.MessageTitle,
				NL.NotificationMessage AS 'Message',
				CONVERT(VARCHAR,NL.CreatedDateTime,103)+' '+ left(right('0'+LTRIM(RIGHT(CONVERT(varchar,NL.CreatedDateTime,100),8)),7),5)+ ' ' + right(RIGHT('0'+LTRIM(RIGHT(CONVERT(varchar,NL.CreatedDateTime,100),8)),7),2) AS CreatedDateTime,
				--CONVERT(VARCHAR(25), NL.CreatedDateTime, 100) AS CreatedDateTime
				EM.Title as EventName,
				u.DisplayTitle as CreatedName -- This changes done by parth as discussed with rajendrasir (Just added createdname)
		FROM 
			sAlert.tNotificationLog NL
			Inner join [sSecurity].[tUser] u ON u.Id = NL.CreatedUserId
			LEFT JOIN sAlert.tEventMaster EM ON EM.Id = NL.EventId
		WHERE 
		(
		(NL.SourceId=@lAcademicId) AND (NL.SourceTypeId=2001)
		OR (NL.SourceId=@lStudentId) AND (NL.SourceTypeId=2003)
		OR (NL.SourceId=@lDivisionId) AND (NL.SourceTypeId=2005)
		OR (NL.SourceId=@lClassId) AND (NL.SourceTypeId=2016)
		OR (NL.SourceId=@lDepartmentId) AND (NL.SourceTypeId=2017)
		OR (NL.SourceId=@lOrgId) AND (NL.SourceTypeId=2021)	
		) AND NL.Id > @rSyncedNotificationId AND OSTypeId=@rOSTypeId
		AND ((NL.EventId = @rEventId) OR (@rEventId = 0))
		AND NL.EventId NOT IN (14,15)
		AND (convert(date,NL.CreatedDateTime)>=@rFromDate OR ISNULL(@rFromDate,'')='')
		AND (convert(date,NL.CreatedDateTime)<=@rToDate OR ISNULL(@rToDate,'')='' )
		
		UNION ALL
		
		SELECT 
				NL.Id AS NotificationId,
				NL.EventId,
				NL.DocumentId,
				NL.MessageTitle,
				NL.NotificationMessage AS 'Message',
				CONVERT(VARCHAR,NL.CreatedDateTime,103)+' '+ left(right('0'+LTRIM(RIGHT(CONVERT(varchar,NL.CreatedDateTime,100),8)),7),5)+ ' ' + right(RIGHT('0'+LTRIM(RIGHT(CONVERT(varchar,NL.CreatedDateTime,100),8)),7),2) AS CreatedDateTime,
				--CONVERT(VARCHAR(25), NL.CreatedDateTime, 100) AS CreatedDateTime
				EM.Title as EventName,
				u.DisplayTitle as CreatedName
		FROM 
			sAlert.tNotificationLog NL
			Inner join [sSecurity].[tUser] u ON u.Id = NL.CreatedUserId
			LEFT JOIN sAlert.tEventMaster EM ON EM.Id = NL.EventId
		WHERE 
		(
		(NL.SourceId=@lAcademicId) AND (NL.SourceTypeId=2001)
		OR (NL.SourceId=@lStudentId) AND (NL.SourceTypeId=2003)
		OR (NL.SourceId=@lDivisionId) AND (NL.SourceTypeId=2005)
		OR (NL.SourceId=@lClassId) AND (NL.SourceTypeId=2016)
		OR (NL.SourceId=@lDepartmentId) AND (NL.SourceTypeId=2017)
		OR (NL.SourceId=@lOrgId) AND (NL.SourceTypeId=2021)	
		) AND NL.Id > @rSyncedNotificationId AND OSTypeId=@rOSTypeId
		AND ((NL.EventId = @rEventId) OR (@rEventId = 0))
		AND (NL.EventId = 14) AND (NL.SourceTypeId=2001 OR NL.SourceTypeId=2003 OR  NL.SourceTypeId=2005 OR NL.SourceTypeId=2016)
		AND (convert(date,NL.CreatedDateTime)>=@rFromDate OR ISNULL(@rFromDate,'')='')
		AND (convert(date,NL.CreatedDateTime)<=@rToDate OR ISNULL(@rToDate,'')='' )
		
		
		UNION ALL
		
		SELECT 
				NL.Id AS NotificationId,
				NL.EventId,
				NL.DocumentId,
				NL.MessageTitle,
				NL.NotificationMessage AS 'Message',
				CONVERT(VARCHAR,NL.CreatedDateTime,103)+' '+ left(right('0'+LTRIM(RIGHT(CONVERT(varchar,NL.CreatedDateTime,100),8)),7),5)+ ' ' + right(RIGHT('0'+LTRIM(RIGHT(CONVERT(varchar,NL.CreatedDateTime,100),8)),7),2) AS CreatedDateTime,
				--CONVERT(VARCHAR(25), NL.CreatedDateTime, 100) AS CreatedDateTime
				EM.Title as EventName,
				u.DisplayTitle as CreatedName
		FROM 
			sAlert.tNotificationLog NL
			Inner join [sSecurity].[tUser] u ON u.Id = NL.CreatedUserId
			INNER JOIN sCommunication.tCircularScope CS ON CS.SourceTypeId = NL.SourceTypeId AND CS.SourceId = NL.SourceId AND CS.CircularId=NL.DocumentId AND CS.AssigneeToId = 2
			INNER JOIN sCommunication.tCircular C ON C.Id = CS.CircularId AND CS.CircularId=NL.DocumentId  AND (C.AssigneeId=2 OR C.AssigneeId=1) 
			LEFT JOIN sAlert.tEventMaster EM ON EM.Id = NL.EventId
		WHERE 
		(
		(NL.SourceId=@lAcademicId) AND (NL.SourceTypeId=2001)
		OR (NL.SourceId=@lStudentId) AND (NL.SourceTypeId=2003)
		OR (NL.SourceId=@lDivisionId) AND (NL.SourceTypeId=2005)
		OR (NL.SourceId=@lClassId) AND (NL.SourceTypeId=2016)
		OR (NL.SourceId=@lDepartmentId) AND (NL.SourceTypeId=2017)
		OR (NL.SourceId=@lOrgId) AND (NL.SourceTypeId=2021)	
		) AND NL.Id > @rSyncedNotificationId AND OSTypeId=@rOSTypeId
		AND ((NL.EventId = @rEventId) OR (@rEventId = 0))
		AND NL.EventId = 14 AND NL.SourceTypeId=2021
		AND (convert(date,NL.CreatedDateTime)>=@rFromDate OR ISNULL(@rFromDate,'')='')
		AND (convert(date,NL.CreatedDateTime)<=@rToDate OR ISNULL(@rToDate,'')='' )
		 
		UNION ALL
		
		SELECT 
				NL.Id AS NotificationId,
				NL.EventId,
				NL.DocumentId,
				NL.MessageTitle,
				NL.NotificationMessage AS 'Message',
				CONVERT(VARCHAR,NL.CreatedDateTime,103)+' '+ left(right('0'+LTRIM(RIGHT(CONVERT(varchar,NL.CreatedDateTime,100),8)),7),5)+ ' ' + right(RIGHT('0'+LTRIM(RIGHT(CONVERT(varchar,NL.CreatedDateTime,100),8)),7),2) AS CreatedDateTime,
				--CONVERT(VARCHAR(25), NL.CreatedDateTime, 100) AS CreatedDateTime
				EM.Title as EventName,
				u.DisplayTitle as CreatedName
		FROM 
			sAlert.tNotificationLog NL
			Inner join [sSecurity].[tUser] u ON u.Id = NL.CreatedUserId
			INNER JOIN sCommunication.tCircularScope CS ON CS.SourceTypeId = NL.SourceTypeId AND CS.SourceId = NL.SourceId AND CS.CircularId=NL.DocumentId AND CS.AssigneeToId = 2
			INNER JOIN sCommunication.tCircular C ON C.Id = CS.CircularId AND CS.CircularId=NL.DocumentId AND (C.AssigneeId=2 OR C.AssigneeId=1)
			LEFT JOIN sAlert.tEventMaster EM ON EM.Id = NL.EventId
		WHERE 
		(
		(NL.SourceId=@lAcademicId) AND (NL.SourceTypeId=2001)
		OR (NL.SourceId=@lStudentId) AND (NL.SourceTypeId=2003)
		OR (NL.SourceId=@lDivisionId) AND (NL.SourceTypeId=2005)
		OR (NL.SourceId=@lClassId) AND (NL.SourceTypeId=2016)
		OR (NL.SourceId=@lDepartmentId) AND (NL.SourceTypeId=2017)
		OR (NL.SourceId=@lOrgId) AND (NL.SourceTypeId=2021)	
		) AND NL.Id > @rSyncedNotificationId AND OSTypeId=@rOSTypeId
		AND ((NL.EventId = @rEventId) OR (@rEventId = 0))
		AND NL.EventId = 14 AND NL.SourceTypeId=2017
		AND (convert(date,NL.CreatedDateTime)>=@rFromDate OR ISNULL(@rFromDate,'')='')
		AND (convert(date,NL.CreatedDateTime)<=@rToDate OR ISNULL(@rToDate,'')='' )

		UNION ALL
		--Commented for mantis : 42198
		--SELECT 
		--		NL.Id AS NotificationId,
		--		NL.EventId,
		--		NL.DocumentId,
		--		NL.MessageTitle,
		--		NL.NotificationMessage AS 'Message',
		--		CONVERT(VARCHAR,NL.CreatedDateTime,103)+' '+ left(right('0'+LTRIM(RIGHT(CONVERT(varchar,NL.CreatedDateTime,100),8)),7),5)+ ' ' + right(RIGHT('0'+LTRIM(RIGHT(CONVERT(varchar,NL.CreatedDateTime,100),8)),7),2) AS CreatedDateTime,
		--		--CONVERT(VARCHAR(25), NL.CreatedDateTime, 100) AS CreatedDateTime
		--		EM.Title as EventName,
		--		u.DisplayTitle as CreatedName
		--FROM 
		--	sAlert.tNotificationLog NL
		--	Inner join [sSecurity].[tUser] u ON u.Id = NL.CreatedUserId
		--	INNER JOIN sCommunication.tAssignmentScope AC ON AC.SourceTypeId = NL.SourceTypeId AND AC.SourceId = NL.SourceId AND AC.AssignmentId=NL.DocumentId
		--	INNER JOIN sCommunication.tAssignment A ON A.Id = AC.AssignmentId AND AC.AssignmentId=NL.DocumentId 
		--	LEFT JOIN sAlert.tEventMaster EM ON EM.Id = NL.EventId
		--WHERE 
		--(
		--(NL.SourceId=@lDivisionId) AND (NL.SourceTypeId=2005)
		--OR(NL.SourceId=@lStudentId) AND (NL.SourceTypeId=2003)
		--) AND NL.Id > @rSyncedNotificationId AND OSTypeId=@rOSTypeId
		--AND ((NL.EventId = @rEventId) OR (@rEventId = 0))
		--AND (NL.EventId = 15) AND (NL.SourceTypeId=2003 OR NL.SourceTypeId=2005)
		--AND (convert(date,NL.CreatedDateTime)>=@rFromDate OR ISNULL(@rFromDate,'')='')
		--AND (convert(date,NL.CreatedDateTime)<=@rToDate OR ISNULL(@rToDate,'')='' )
		--Commented for mantis : 42198

		--Added for mantis : 42198
		SELECT 
	NL.Id AS NotificationId,
	NL.EventId,
	NL.DocumentId,
	NL.MessageTitle,
	NL.NotificationMessage AS 'Message',
	CONVERT(VARCHAR,NL.CreatedDateTime,103)+' '+ left(right('0'+LTRIM(RIGHT(CONVERT(varchar,NL.CreatedDateTime,100),8)),7),5)+ ' ' + right(RIGHT('0'+LTRIM(RIGHT(CONVERT(varchar,NL.CreatedDateTime,100),8)),7),2) AS CreatedDateTime,
				--CONVERT(VARCHAR(25), NL.CreatedDateTime, 100) AS CreatedDateTime
	EM.Title as EventName,
	U.DisplayTitle as CreatedName
FROM 
	sAlert.tNotificationLog NL
	Inner join [sSecurity].[tUser] u ON u.Id = NL.CreatedUserId
	INNER JOIN sCommunication.tAssignmentScope AC ON AC.SourceTypeId = NL.SourceTypeId AND NL.SourceTypeId = 2005 
		AND AC.SourceId = NL.SourceId AND AC.AssignmentId=NL.DocumentId
	INNER JOIN sCommunication.tAssignment A ON A.Id = AC.AssignmentId AND AC.AssignmentId=NL.DocumentId 
	INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = AC.SourceId 
	INNER JOIN [sSetup].[tClassSubject] CS ON CS.SubjectId = A.SubjectId AND DM.ClassId = CS.ClassId
	LEFT JOIN sAlert.tEventMaster EM ON EM.Id = NL.EventId
WHERE 
CS.IsOptional = 0 AND
(
(NL.SourceId=@lDivisionId) AND (NL.SourceTypeId=2005)
OR(NL.SourceId=@lStudentId) AND (NL.SourceTypeId=2003)
) AND NL.Id > @rSyncedNotificationId AND OSTypeId=@rOSTypeId
AND ((NL.EventId = @rEventId) OR (@rEventId = 0))
AND (NL.EventId = 15) AND (NL.SourceTypeId=2003 OR NL.SourceTypeId=2005)
AND (convert(date,NL.CreatedDateTime)>=@rFromDate OR ISNULL(@rFromDate,'')='')
AND (convert(date,NL.CreatedDateTime)<=@rToDate OR ISNULL(@rToDate,'')='' )

UNION ALL

SELECT 
	NL.Id AS NotificationId,
	NL.EventId,
	NL.DocumentId,
	NL.MessageTitle,
	NL.NotificationMessage AS 'Message',
	CONVERT(VARCHAR,NL.CreatedDateTime,103)+' '+ left(right('0'+LTRIM(RIGHT(CONVERT(varchar,NL.CreatedDateTime,100),8)),7),5)+ ' ' + right(RIGHT('0'+LTRIM(RIGHT(CONVERT(varchar,NL.CreatedDateTime,100),8)),7),2) AS CreatedDateTime,
				--CONVERT(VARCHAR(25), NL.CreatedDateTime, 100) AS CreatedDateTime
	EM.Title as EventName,
	U.DisplayTitle as CreatedName
FROM 
	sAlert.tNotificationLog NL
	Inner join [sSecurity].[tUser] u ON u.Id = NL.CreatedUserId
	INNER JOIN sStudent.vStudentAcademic SA ON SA.StudentId = NL.SourceId AND NL.SourceTypeId = 2003  AND IsActiveBatch=1
	INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = SA.DivisionId
	INNER JOIN sCommunication.tAssignmentScope AC ON NL.SourceTypeId = 2003 AND AC.SourceId = DM.Id AND AC.AssignmentId=NL.DocumentId
	INNER JOIN sCommunication.tAssignment A ON A.Id = AC.AssignmentId AND AC.AssignmentId=NL.DocumentId 
	INNER JOIN [sSetup].[tClassSubject] CS ON CS.SubjectId = A.SubjectId AND DM.ClassId = CS.ClassId AND SA.ClassId = CS.ClassId
	INNER JOIN [sAssessment].[tOptionalSubject] AS OS ON OS.ClassSubjectId = CS.Id AND OS.AcademicId = SA.AcademicId
	LEFT JOIN sAlert.tEventMaster EM ON EM.Id = NL.EventId
WHERE 
CS.IsOptional = 1 AND
((NL.SourceId=@lStudentId) AND (NL.SourceTypeId=2003)) 
AND NL.Id > @rSyncedNotificationId 
AND OSTypeId=@rOSTypeId
AND ((NL.EventId = @rEventId) OR (@rEventId = 0))
AND (NL.EventId = 15) AND (NL.SourceTypeId=2003)
AND (convert(date,NL.CreatedDateTime)>=@rFromDate OR ISNULL(@rFromDate,'')='')
AND (convert(date,NL.CreatedDateTime)<=@rToDate OR ISNULL(@rToDate,'')='' )
--Added for mantis : 42198		
	END
		
	IF(@rUserSourceTypeId=95)
	BEGIN
	
		SELECT 
		@lEmployeeId=EmployeeId,
		@lDepartmentId=OrganizationDepartmentId,
		@lOrgId=OrgId
		FROM sHrm.tEmployeeJobDetail WHERE EmployeeId = @rUserSourceId
		SELECT 
				NL.Id AS NotificationId,
				NL.EventId,
				NL.DocumentId,
				NL.MessageTitle,
				NL.NotificationMessage AS 'Message',
				CONVERT(VARCHAR,NL.CreatedDateTime,103)+' '+ left(right('0'+LTRIM(RIGHT(CONVERT(varchar,NL.CreatedDateTime,100),8)),7),5)+ ' ' + right(RIGHT('0'+LTRIM(RIGHT(CONVERT(varchar,NL.CreatedDateTime,100),8)),7),2) AS CreatedDateTime,
				--CONVERT(VARCHAR(25), NL.CreatedDateTime, 100) AS CreatedDateTime
				EM.Title as EventName,
				u.DisplayTitle as CreatedName
		FROM 
			sAlert.tNotificationLog NL
			Inner join [sSecurity].[tUser] u ON u.Id = NL.CreatedUserId
			LEFT JOIN sAlert.tEventMaster EM ON EM.Id = NL.EventId
		WHERE 
		(
		(NL.SourceId=@lEmployeeId) AND (NL.SourceTypeId=95)
		OR (NL.SourceId=@lDepartmentId) AND (NL.SourceTypeId=2017)
		OR (NL.SourceId=@lOrgId) AND (NL.SourceTypeId=2021)	
		) AND NL.Id > @rSyncedNotificationId AND OSTypeId=@rOSTypeId
		AND ((NL.EventId = @rEventId) OR (@rEventId = 0))
		AND NL.EventId != 14
		AND (convert(date,NL.CreatedDateTime)>=@rFromDate OR ISNULL(@rFromDate,'')='')
		AND (convert(date,NL.CreatedDateTime)<=@rToDate OR ISNULL(@rToDate,'')='' )
		
		
		
		UNION ALL
		
		SELECT 
				NL.Id AS NotificationId,
				NL.EventId,
				NL.DocumentId,
				NL.MessageTitle,
				NL.NotificationMessage AS 'Message',
				CONVERT(VARCHAR,NL.CreatedDateTime,103)+' '+ left(right('0'+LTRIM(RIGHT(CONVERT(varchar,NL.CreatedDateTime,100),8)),7),5)+ ' ' + right(RIGHT('0'+LTRIM(RIGHT(CONVERT(varchar,NL.CreatedDateTime,100),8)),7),2) AS CreatedDateTime,
				--CONVERT(VARCHAR(25), NL.CreatedDateTime, 100) AS CreatedDateTime
				EM.Title as EventName,
				u.DisplayTitle as CreatedName
		FROM 
			sAlert.tNotificationLog NL
			Inner join [sSecurity].[tUser] u ON u.Id = NL.CreatedUserId
			LEFT JOIN sAlert.tEventMaster EM ON EM.Id = NL.EventId
		WHERE 
		(
		(NL.SourceId=@lEmployeeId) AND (NL.SourceTypeId=95)
		OR (NL.SourceId=@lDepartmentId) AND (NL.SourceTypeId=2017)
		OR (NL.SourceId=@lOrgId) AND (NL.SourceTypeId=2021)	
		) AND NL.Id > @rSyncedNotificationId AND OSTypeId=@rOSTypeId
		AND ((NL.EventId = @rEventId) OR (@rEventId = 0))
		AND (NL.EventId = 14 AND NL.SourceTypeId=95)
		AND (convert(date,NL.CreatedDateTime)>=@rFromDate OR ISNULL(@rFromDate,'')='')
		AND (convert(date,NL.CreatedDateTime)<=@rToDate OR ISNULL(@rToDate,'')='' )
		
		UNION ALL
		
		SELECT 
				NL.Id AS NotificationId,
				NL.EventId,
				NL.DocumentId,
				NL.MessageTitle,
				NL.NotificationMessage AS 'Message',
				CONVERT(VARCHAR,NL.CreatedDateTime,103)+' '+ left(right('0'+LTRIM(RIGHT(CONVERT(varchar,NL.CreatedDateTime,100),8)),7),5)+ ' ' + right(RIGHT('0'+LTRIM(RIGHT(CONVERT(varchar,NL.CreatedDateTime,100),8)),7),2) AS CreatedDateTime,
				--CONVERT(VARCHAR(25), NL.CreatedDateTime, 100) AS CreatedDateTime
				EM.Title as EventName,
				u.DisplayTitle as CreatedName
		FROM 
			sAlert.tNotificationLog NL
			Inner join [sSecurity].[tUser] u ON u.Id = NL.CreatedUserId
			INNER JOIN sCommunication.tCircularScope CS ON CS.SourceTypeId = NL.SourceTypeId AND CS.SourceId = NL.SourceId AND CS.CircularId=NL.DocumentId AND CS.AssigneeToId = 3
			INNER JOIN sCommunication.tCircular C ON C.Id = CS.CircularId AND CS.CircularId=NL.DocumentId  AND (C.AssigneeId=3 OR C.AssigneeId=1)
			LEFT JOIN sAlert.tEventMaster EM ON EM.Id = NL.EventId
		WHERE 
		(
		(NL.SourceId=@lEmployeeId) AND (NL.SourceTypeId=95)
		OR (NL.SourceId=@lDepartmentId) AND (NL.SourceTypeId=2017)
		OR (NL.SourceId=@lOrgId) AND (NL.SourceTypeId=2021)	
		) AND NL.Id > @rSyncedNotificationId AND OSTypeId=@rOSTypeId
		AND ((NL.EventId = @rEventId) OR (@rEventId = 0))
		AND NL.EventId = 14 AND NL.SourceTypeId=2021
		AND (convert(date,NL.CreatedDateTime)>=@rFromDate OR ISNULL(@rFromDate,'')='')
		AND (convert(date,NL.CreatedDateTime)<=@rToDate OR ISNULL(@rToDate,'')='' )

		UNION ALL
		
		SELECT 
				NL.Id AS NotificationId,
				NL.EventId,
				NL.DocumentId,
				NL.MessageTitle,
				NL.NotificationMessage AS 'Message',
				CONVERT(VARCHAR,NL.CreatedDateTime,103)+' '+ left(right('0'+LTRIM(RIGHT(CONVERT(varchar,NL.CreatedDateTime,100),8)),7),5)+ ' ' + right(RIGHT('0'+LTRIM(RIGHT(CONVERT(varchar,NL.CreatedDateTime,100),8)),7),2) AS CreatedDateTime,
				--CONVERT(VARCHAR(25), NL.CreatedDateTime, 100) AS CreatedDateTime
				EM.Title as EventName,
				u.DisplayTitle as CreatedName
		FROM 
			sAlert.tNotificationLog NL
			Inner join [sSecurity].[tUser] u ON u.Id = NL.CreatedUserId
			INNER JOIN sCommunication.tCircularScope CS ON CS.SourceTypeId = NL.SourceTypeId AND CS.SourceId = NL.SourceId AND CS.CircularId=NL.DocumentId AND CS.AssigneeToId = 3
			INNER JOIN sCommunication.tCircular C ON C.Id = CS.CircularId AND CS.CircularId=NL.DocumentId AND (C.AssigneeId=3 OR C.AssigneeId=1)
			LEFT JOIN sAlert.tEventMaster EM ON EM.Id = NL.EventId
		WHERE 
		(
		(NL.SourceId=@lEmployeeId) AND (NL.SourceTypeId=95)
		OR (NL.SourceId=@lDepartmentId) AND (NL.SourceTypeId=2017)
		OR (NL.SourceId=@lOrgId) AND (NL.SourceTypeId=2021)	
		) AND NL.Id > @rSyncedNotificationId AND OSTypeId=@rOSTypeId
		AND ((NL.EventId = @rEventId) OR (@rEventId = 0))
		AND NL.EventId = 14 AND NL.SourceTypeId=2017
		AND (convert(date,NL.CreatedDateTime)>=@rFromDate OR ISNULL(@rFromDate,'')='')
		AND (convert(date,NL.CreatedDateTime)<=@rToDate OR ISNULL(@rToDate,'')='' )
		
	END
END
GO
PRINT N'Altering Procedure [sAlert].[pStudentGatePassGet]...';


GO
ALTER PROCEDURE [sAlert].[pStudentGatePassGet]
	
		 @rStudentGatePassId int,
	 	 @rAcademicId bigint,
	 	 @rOrgId int,
	 	 @rTemplate nvarchar(max)
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	
	SELECT 
			SC.OrgGroupId,
			SC.OrgId,
			SC.AcademicId,
			SC.Code,
			SC.Name,
			SC.ParentContactNo AS MobileNo,	
			SC.ParentEmail AS EmailId,
			replace (		--mantis: 42879
			replace (		--mantis: 42879
			replace (		--add for mantis: 35426
			replace (
			replace (
			replace (
			replace (
			replace (
			replace(@rTemplate,'[Name]',SC.Name),
			'[EntryModeStatus]',SM.Title),
			'[GatePassDate]',CONVERT(varchar(11),ISNULL(SGP.GatePassDate,'') ,103)),
			'[GatePassTime]',CONVERT(varchar(15),ISNULL(SGP.GatePassTime,''),100)),
			'[ReasonOfGatePass]',SGP.ReasonOfGatePass),
			'[ReceivedBy]',SGP.VisitorName),
			'[Class]',SC.ClassName),		--add for mantis: 35426
			'[Relation]',ISNULL(SGP.Relation,'')),		--mantis: 42879
			'[VisitorName]',ISNULL(SGP.VisitorName,''))	--mantis: 42879
			AS MsgText,
			'' AS Subject,
			 2001 AS ReceiverSourceTypeId,
			 SC.AcademicId AS ReceiverSourceId,
			 2001 AS SourceTypeId,
			 SC.AcademicId AS SourceId,
			 SM.Title AS EntryModeStatus,
			 CONVERT(varchar(11),ISNULL(SGP.GatePassDate,'') ,103) AS GatePassDate,
			 CONVERT(varchar(15),ISNULL(SGP.GatePassTime,''),100) AS GatePassTime,
			 SGP.ReasonOfGatePass AS ReasonOfGatePass,
			 SGP.VisitorName AS ReceivedBy,
			 SC.WhatsAppContactNo

	FROM 
		sStudent.vStudentCommunication SC
	INNER JOIN 	sFrontOffice.tStudentGatePass SGP ON SC.AcademicId = SGP.AcademicId
	INNER JOIN sCommon.tStatusMaster SM ON SM.Id = SGP.EntryModeStatusId
	WHERE
		SGP.Id=@rStudentGatePassId
		AND SC.AcademicId = @rAcademicId
		AND ((SC.OrgId=@rOrgId) OR (@rOrgId=0))
		AND (SC.StatusId=1) AND SC.IsBlockAllAlert=0
END
GO
PRINT N'Altering Procedure [sAssessment].[pRptAllClassSubjectGradeAnalysis]...';


GO


ALTER PROCEDURE [sAssessment].[pRptAllClassSubjectGradeAnalysis]
	 
	  
	 @rClassId int=0,
	 @rDivisionId int=0,
	 @rDepartmentId int=0,
	 @rExamSubGroupId int=0,
	 @rBuilder1 nvarchar(MAX)='',
	 @rBatchId int,
	 @rOrgId int=0,
	 @rClass nvarchar(MAX)='',
	 @rStatusId int = 0,
	 @rClassStatusId int=0
	 
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	 
		
		
 
	 DECLARE @GradeSetId int
	 Declare @G1 nvarchar(20),@G2 nvarchar(20),@G3 nvarchar(20),@G4 nvarchar(20),@G5 nvarchar(20),@G6 nvarchar(20),@G7 nvarchar(20),@G8 nvarchar(20),@G9 nvarchar(20),@G10 nvarchar(20)	
		
	 --Set @GradeSetId =(select TOP(1)GradeSetId from sAssessment.tExamMaster  where ExamSubGroupId = @rExamSubGroupId AND BatchId=@rBatchId AND (ClassId = @rClassId OR @rClassId = 0))

	 --According to AssessmentConfiguration
	 Set @GradeSetId = (Select AnalysisGradeSetId from sAssessment.tConfiguration Where OrgId = @rOrgId)
		  --Select @GradeSetId
	CREATE Table #Temp
	(
		Id Int Identity (1,1),
		GradeCode nvarchar(20),
		MinimumScore decimal(6,2),
	)
	Insert into #Temp
	
		select GradeCode,MinimumScore from  sAssessment.tGradeSetDetail where GradeSetId=@GradeSetId
	 
	 	 Set @G1=(Select GradeCode from #Temp where Id=1) 
	 	 Set @G2=(Select GradeCode from #Temp where Id=2) 
	 	 Set @G3=(Select GradeCode from #Temp where Id=3) 
	 	 Set @G4=(Select GradeCode from #Temp where Id=4) 
	     Set @G5=(Select GradeCode from #Temp where Id=5) 
         Set @G6=(Select GradeCode from #Temp where Id=6) 
	     Set @G7=(Select GradeCode from #Temp where Id=7) 
	 	 Set @G8=(Select GradeCode from #Temp where Id=8) 
	 	 Set @G9=(Select GradeCode from #Temp where Id=9) 
		 Set @G10=(Select GradeCode from #Temp where Id=10)  
	   
	 select 
		@rBuilder1 AS Builder1,
		Cm.Classid As ClassId,
		Dm.id As DivisionId,
		Cm.ClassName As ClassName,
		DM.DisplayTitle As DivisionName,
		
		 
	  
	  (select COUNT(RD.Id) from sAssessment.tResultDetail RD INNER JOIN  sAssessment.tResult R ON RD.ResultId = R.Id  
	  INNER JOIN sStudent.vStudentAcademic A ON R.AcademicId = A.AcademicId 
	  INNER JOIN sAssessment.tExamDetail ED ON ED.ID=RD.ExamDetailId
	  	INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
		INNER JOIN  sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId  
	  where 
	  A.DivisionId = DM.Id AND EM.ExamSubGroupId = @rExamSubGroupId AND EM.BatchId = @rBatchId AND ((A.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0)) AND CS.SubjectId=SM.Id AND ((A.StatusId=@rStatusId) OR (@rStatusId=0)) AND ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0))) AS NoOfStudent,
	  
	 

	  (select MAX(RD.Obtain) from  sAssessment.tResultDetail RD INNER JOIN  sAssessment.tResult R ON RD.ResultId = R.Id  
	  INNER JOIN sStudent.vStudentAcademic A ON R.AcademicId = A.AcademicId 
	   INNER JOIN sAssessment.tExamDetail ED ON ED.ID=RD.ExamDetailId
	  	INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
		INNER JOIN  sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId  
	  where 
	  A.DivisionId = DM.Id AND EM.ExamSubGroupId = @rExamSubGroupId AND EM.BatchId = @rBatchId AND ((A.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0)) AND CS.SubjectId=SM.Id AND ((A.StatusId=@rStatusId) OR (@rStatusId=0)) AND ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0))) AS HighestPerMark,

	  (select AVG(RD.Obtain) from  sAssessment.tResultDetail RD INNER JOIN  sAssessment.tResult R  ON RD.ResultId = R.Id   
	    INNER JOIN sStudent.vStudentAcademic A ON R.AcademicId = A.AcademicId 
	   INNER JOIN sAssessment.tExamDetail ED ON ED.ID=RD.ExamDetailId
	  	INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
		INNER JOIN  sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId  
	  where 
	  A.DivisionId = DM.Id AND EM.ExamSubGroupId = @rExamSubGroupId AND EM.BatchId = @rBatchId AND ((A.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0)) AND CS.SubjectId=SM.Id AND ((A.StatusId=@rStatusId) OR (@rStatusId=0)) AND ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0)) AND RD.IsPresent = 1) AS AveragePerMark, -- Add RD.IsPresent = 1 for Mantis : 0028928
	  
	  (select MIN(RD.Obtain) from sAssessment.tResultDetail RD INNER JOIN  sAssessment.tResult R ON RD.ResultId = R.Id 
	  INNER JOIN sStudent.vStudentAcademic A ON R.AcademicId = A.AcademicId 
	    INNER JOIN sAssessment.tExamDetail ED ON ED.ID=RD.ExamDetailId
	  	INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
		INNER JOIN  sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId  
	  where 
	  A.DivisionId = DM.Id AND EM.ExamSubGroupId = @rExamSubGroupId AND EM.BatchId = @rBatchId AND ((A.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0)) AND CS.SubjectId=SM.Id AND ((A.StatusId=@rStatusId) OR (@rStatusId=0)) AND ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0)) AND RD.IsPresent = 1) AS LowestPerMark , -- Add RD.IsPresent = 1 for Mantis : 0028928
	  
	  (Select COUNT(R.AcademicId) from sAssessment.tResultDetail RD INNER JOIN  sAssessment.tResult R ON RD.ResultId = R.Id  
	  INNER JOIN sStudent.vStudentAcademic A ON R.AcademicId = A.AcademicId 
	 INNER JOIN sAssessment.tExamDetail ED ON ED.ID=RD.ExamDetailId
		INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
		INNER JOIN  sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId  
	  where 
	  A.DivisionId = DM.Id AND EM.ExamSubGroupId = @rExamSubGroupId AND EM.BatchId = @rBatchId AND ((A.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0)) AND  SubjectGrade = @G1  AND CS.SubjectId=SM.Id AND ((A.StatusId=@rStatusId) OR (@rStatusId=0)) AND ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0)) AND (EM.ClassId=@rClassId OR @rClassId=0))AS GradeCount1,
	  
  (Select COUNT(R.AcademicId) from sAssessment.tResultDetail RD INNER JOIN  sAssessment.tResult R   ON RD.ResultId = R.Id   
  INNER JOIN sStudent.vStudentAcademic A ON R.AcademicId = A.AcademicId 
	  INNER JOIN sAssessment.tExamDetail ED ON ED.ID=RD.ExamDetailId
	  INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
		INNER JOIN  sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId  
	  where 
	  A.DivisionId = DM.Id AND EM.ExamSubGroupId = @rExamSubGroupId AND EM.BatchId = @rBatchId AND ((A.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0)) AND  SubjectGrade = @G2  AND CS.SubjectId=SM.Id AND ((A.StatusId=@rStatusId) OR (@rStatusId=0)) AND ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0)) AND (EM.ClassId=@rClassId OR @rClassId=0))AS GradeCount2,
	 

  (Select COUNT(R.AcademicId)from sAssessment.tResultDetail RD INNER JOIN  sAssessment.tResult R   ON RD.ResultId = R.Id   
  INNER JOIN sStudent.vStudentAcademic A ON R.AcademicId = A.AcademicId 
	 INNER JOIN sAssessment.tExamDetail ED ON ED.ID=RD.ExamDetailId
	  INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
		INNER JOIN  sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId  
	  where 
	  A.DivisionId = DM.Id AND EM.ExamSubGroupId = @rExamSubGroupId AND EM.BatchId = @rBatchId AND ((A.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0)) AND  SubjectGrade = @G3  AND CS.SubjectId=SM.Id AND ((A.StatusId=@rStatusId) OR (@rStatusId=0)) AND ((A
.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0)) AND (EM.ClassId=@rClassId OR @rClassId=0))AS GradeCount3,
	 

  (Select COUNT(R.AcademicId) from sAssessment.tResultDetail RD INNER JOIN  sAssessment.tResult R  ON RD.ResultId = R.Id  
  INNER JOIN sStudent.vStudentAcademic A ON R.AcademicId = A.AcademicId 
	  INNER JOIN sAssessment.tExamDetail ED ON ED.ID=RD.ExamDetailId
	  INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
		INNER JOIN  sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId  
	  where 
	  A.DivisionId = DM.Id AND EM.ExamSubGroupId = @rExamSubGroupId AND EM.BatchId = @rBatchId  AND ((A.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0)) AND  SubjectGrade = @G4  AND CS.SubjectId=SM.Id AND ((A.StatusId=@rStatusId) OR (@rStatusId=0)) AND ((
A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0)) AND (EM.ClassId=@rClassId OR @rClassId=0))AS GradeCount4,
	 
  (Select COUNT(R.AcademicId) from sAssessment.tResultDetail RD INNER JOIN  sAssessment.tResult R ON RD.ResultId = R.Id   
  INNER JOIN sStudent.vStudentAcademic A ON R.AcademicId = A.AcademicId 
	  INNER JOIN sAssessment.tExamDetail ED ON ED.ID=RD.ExamDetailId
	  INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
		INNER JOIN  sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId  
	  where 
	  A.DivisionId = DM.Id AND EM.ExamSubGroupId = @rExamSubGroupId AND EM.BatchId = @rBatchId AND ((A.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0)) AND  SubjectGrade = @G5  AND CS.SubjectId=SM.Id AND ((A.StatusId=@rStatusId) OR (@rStatusId=0)) AND ((A
.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0))AND (EM.ClassId=@rClassId OR @rClassId=0))AS GradeCount5,
	 
  (Select COUNT(R.AcademicId) from sAssessment.tResultDetail RD INNER JOIN  sAssessment.tResult R ON RD.ResultId = R.Id  
  INNER JOIN sStudent.vStudentAcademic A ON R.AcademicId = A.AcademicId 
	 INNER JOIN sAssessment.tExamDetail ED ON ED.ID=RD.ExamDetailId
	  INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
		INNER JOIN  sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId  
	  where 
	  A.DivisionId = DM.Id AND EM.ExamSubGroupId = @rExamSubGroupId AND EM.BatchId = @rBatchId AND ((A.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0)) AND  SubjectGrade = @G6  AND CS.SubjectId=SM.Id AND ((A.StatusId=@rStatusId) OR (@rStatusId=0)) AND ((A
.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0))AND (EM.ClassId=@rClassId OR @rClassId=0))AS GradeCount6,
	 
  (Select COUNT(R.AcademicId) from sAssessment.tResultDetail RD INNER JOIN  sAssessment.tResult R ON RD.ResultId = R.Id  
  INNER JOIN sStudent.vStudentAcademic A ON R.AcademicId = A.AcademicId 
	  INNER JOIN sAssessment.tExamDetail ED ON ED.ID=RD.ExamDetailId
	  INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
		INNER JOIN  sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId  
	  where 
	  A.DivisionId = DM.Id AND EM.ExamSubGroupId = @rExamSubGroupId AND EM.BatchId = @rBatchId  AND ((A.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0)) AND  SubjectGrade = @G7  AND CS.SubjectId=SM.Id  AND ((A.StatusId=@rStatusId) OR (@rStatusId=0)) AND (
(A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0)) AND (EM.ClassId=@rClassId OR @rClassId=0))AS GradeCount7,
	 
  (Select COUNT(R.AcademicId) from sAssessment.tResultDetail RD INNER JOIN  sAssessment.tResult R ON RD.ResultId = R.Id   
  INNER JOIN sStudent.vStudentAcademic A ON R.AcademicId = A.AcademicId 
	   INNER JOIN sAssessment.tExamDetail ED ON ED.ID=RD.ExamDetailId
	  INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
		INNER JOIN  sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId  
	  where 
	  A.DivisionId = DM.Id AND EM.ExamSubGroupId = @rExamSubGroupId AND EM.BatchId = @rBatchId  AND ((A.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0)) AND  SubjectGrade = @G8  AND CS.SubjectId=SM.Id AND ((A.StatusId=@rStatusId) OR (@rStatusId=0)) AND ((
A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0)) AND (EM.ClassId=@rClassId OR @rClassId=0))AS GradeCount8,
	 
  (Select COUNT(R.AcademicId) from sAssessment.tResultDetail RD INNER JOIN  sAssessment.tResult R  ON RD.ResultId = R.Id  
  INNER JOIN sStudent.vStudentAcademic A ON R.AcademicId = A.AcademicId 
	   INNER JOIN sAssessment.tExamDetail ED ON ED.ID=RD.ExamDetailId
	  INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
		INNER JOIN  sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId  
	  where 
	  A.DivisionId = DM.Id AND EM.ExamSubGroupId = @rExamSubGroupId AND EM.BatchId = @rBatchId  AND ((A.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0)) AND  SubjectGrade = @G9  AND CS.SubjectId=SM.Id AND ((A.StatusId=@rStatusId) OR (@rStatusId=0)) AND ((
A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0)) AND (EM.ClassId=@rClassId OR @rClassId=0))AS GradeCount9,
	 
  (Select COUNT(R.AcademicId) from sAssessment.tResultDetail RD INNER JOIN  sAssessment.tResult R ON RD.ResultId = R.Id   
  INNER JOIN sStudent.vStudentAcademic A ON R.AcademicId = A.AcademicId 
	 INNER JOIN sAssessment.tExamDetail ED ON ED.ID=RD.ExamDetailId
	  INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
		INNER JOIN  sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId  
	  where 
	  A.DivisionId = DM.Id AND EM.ExamSubGroupId = @rExamSubGroupId AND EM.BatchId = @rBatchId AND ((A.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0)) AND  SubjectGrade = @G10  AND CS.SubjectId=SM.Id AND ((A.StatusId=@rStatusId) OR (@rStatusId=0)) AND ((
A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0))AND (EM.ClassId=@rClassId OR @rClassId=0))AS GradeCount10,
	  
	  
   
	  ISNULL(@G1,'*') AS Grade1,
	  ISNULL(@G2,'*') AS Grade2,
	  ISNULL(@G3,'*') AS Grade3,
	  ISNULL(@G4,'*') AS Grade4,
	  ISNULL(@G5,'*') As Grade5,
	  ISNULL(@G6,'*') As Grade6,
	  ISNULL(@G7,'*') AS Grade7,
	  ISNULL(@G8,'*') AS Grade8,
	  ISNULL(@G9,'*') AS Grade9,
	 ISNULL(@G10,'*')  AS Grade10,
	 Sm.Id AS SubjectId,
	  SM.Title AS SubjectName,
	  CS.OrderIndex AS OrderIndex,
	  (select COUNT(R.AcademicId) from  sAssessment.tResultDetail RD INNER JOIN  sAssessment.tResult R ON RD.ResultId = R.Id  
		INNER JOIN sStudent.vStudentAcademic A ON R.AcademicId = A.AcademicId 
		INNER JOIN sAssessment.tExamDetail ED ON ED.ID=RD.ExamDetailId
	  	INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
		INNER JOIN  sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId  
		where 
			A.DivisionId = DM.Id AND EM.ExamSubGroupId = @rExamSubGroupId AND EM.BatchId = @rBatchId 
			AND ((A.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0)) AND CS.SubjectId=SM.Id 
			AND ((A.StatusId=@rStatusId) OR (@rStatusId=0)) AND ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0)) AND ISNULL(RD.IsPresent,0) = 0 
		) AS AbsentCount,
		(select MAX(ED.Maximum) from  sAssessment.tResultDetail RD INNER JOIN  sAssessment.tResult R ON RD.ResultId = R.Id  
	  INNER JOIN sStudent.vStudentAcademic A ON R.AcademicId = A.AcademicId 
	   INNER JOIN sAssessment.tExamDetail ED ON ED.ID=RD.ExamDetailId
	  	INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
		INNER JOIN  sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId  
	  where 
	  A.DivisionId = DM.Id AND EM.ExamSubGroupId = @rExamSubGroupId AND EM.BatchId = @rBatchId AND ((A.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0)) AND CS.SubjectId=SM.Id AND ((A.StatusId=@rStatusId) OR (@rStatusId=0)) AND ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0))) AS MaximumMark, --Mantis : 0028713

	  	(select COUNT(RD.Id) from  sAssessment.tResultDetail RD 
		INNER JOIN  sAssessment.tResult R ON RD.ResultId = R.Id  
		INNER JOIN sStudent.vStudentAcademic A ON R.AcademicId = A.AcademicId 
		INNER JOIN sAssessment.tExamDetail ED ON ED.ID=RD.ExamDetailId
		INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
		INNER JOIN  sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId  
	  where 
	  A.DivisionId = DM.Id AND EM.ExamSubGroupId = @rExamSubGroupId AND 
	  EM.BatchId = @rBatchId AND CS.SubjectId=SM.Id AND ((RD.Obtain<ED.Minimum) OR (RD.IsPresent = 0)) AND ((A.StatusId=@rStatusId) OR (@rStatusId=0)) AND ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0))) AS FailStudent, -- add for mantis : 0035813

	  (select COUNT(RD.Id) from  sAssessment.tResultDetail RD 
		INNER JOIN  sAssessment.tResult R ON RD.ResultId = R.Id  
		INNER JOIN sStudent.vStudentAcademic A ON R.AcademicId = A.AcademicId 
		INNER JOIN sAssessment.tExamDetail ED ON ED.ID=RD.ExamDetailId
		INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
		INNER JOIN  sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId  
	  where 
	  A.DivisionId = DM.Id AND EM.ExamSubGroupId = @rExamSubGroupId AND 
	  --EM.BatchId = @rBatchId AND CS.SubjectId=SM.Id AND RD.Obtain > 0.9 * ED.Maximum AND ((A.StatusId=@rStatusId) OR (@rStatusId=0)) AND ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0)) AND RD.IsPresent = 1) AS Above90PercentStudent -- add for mantis : 0035813
	  EM.BatchId = @rBatchId AND CS.SubjectId=SM.Id AND (RD.Obtain * 100/ ED.Maximum) > 90 AND ((A.StatusId=@rStatusId) OR (@rStatusId=0)) AND ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0)) AND RD.IsPresent = 1) AS Above90PercentStudent -- addfor mantis : 0035813
	  
	 from
 

		sAssessment.tExamDetail ED		
		INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId	
		INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId		
		INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
		INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=CS.SubjectId					 
		INNER JOIN sSetup.tClassMaster CLM ON CLM.Id=EM.ClassId
		INNER JOIN sSetup.tDivisionMaster DM ON DM.ClassId=CLM.Id
		INNER JOIN sSetup.vBatchClass CM ON CM.ClassId = DM.ClassId
		
	
		WHERE 
 
			
			EM.BatchId = @rBatchId 
			AND (EM.ClassId=@rClassId OR @rClassId=0) 
			AND (DM.Id=@rDivisionId OR @rDivisionId=0)			
			AND ((ESGM.Id = @rExamSubGroupId) OR (@rExamSubGroupId = 0))
			AND CM.BatchId = @rBatchId
			AND (CLM.DepartmentId=@rDepartmentId OR @rDepartmentId=0)	
			AND (ISNULL(CLM.Id,0) IN( SELECT item FROM  sCommon.fnsplit(@rClass,','))OR @rClass='')
			AND CLM.IsObsolete = 0 AND DM.IsObsolete=0

  	
END

-- SP Drag and Drop
--BEGIN
	--SELECT 
	-- '' AS Builder1,
	-- 0 AS ClassId,
	-- 0 AS DivisionId,
	-- '' AS ClassName,
	-- '' AS DivisionName,
	-- 0 AS NoOfStudent,
	-- Convert(DECIMAL,0) HighestPerMark,
	-- Convert(DECIMAL,0) AveragePerMark,
	-- Convert(DECIMAL,0) LowestPerMark,
	-- 0 AS GradeCount1,
	-- 0 AS GradeCount2,
	-- 0 AS GradeCount3,
	-- 0 AS GradeCount4,
	-- 0 AS GradeCount5,
	-- 0 AS GradeCount6,
	-- 0 AS GradeCount7,
	-- 0 AS GradeCount8,
	-- 0 AS GradeCount9,
	-- 0 AS GradeCount10,
	-- '' AS Grade1,
	-- '' AS Grade2,
	-- '' AS Grade3,
	-- '' AS Grade4,
	-- '' AS Grade5,
	-- '' AS Grade6,
	-- '' AS Grade7,
	-- '' AS Grade8,
	-- '' AS Grade9,
	-- '' AS Grade10,
	-- 0 AS SubjectId,
	-- '' AS SubjectName,
	-- 0 AS OrderIndex,
	-- 0 AS AbsentCount,
	-- Convert(DECIMAL,0) MaximumMark,
	-- 0 AS FailStudent,
	-- 0 AS Above90PercentStudent

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


GO
ALTER PROCEDURE [sAssessment].[pRptExamAdmitcard]
	  
	  @rBatchId int,
	  @rClassId int,
	  @rDivisionId int,
	 -- @rExamId int=0,
	  @rExamSubGroupId int=0,
	  @rCode nvarchar(20),
	  @rFromRollNo Int,
	  @rToRollNo Int,
	  @rDepartmentId int,
	  @rSubjectId int=0,
	  @rStatusId int=0,
	  @rClassStatusId int=0
	  
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON 
BEGIN 	
	SELECT 		
	       	ESGM.Title AS ExamName,
	       	ISNULL(ED.DisplayOrder,0) as DisplayOrder,
	        ISNULL(ED.ExamDate,sCommon.fGetDate()) as ExamDate,
	        ISNULL(ED.ExamTime,'') as ExamTime,
	        V.SubjectName AS SubjectName,
	        CM.DisplayTitle+' / '+DM.DisplayTitle AS ClassDivision,
	         CM.DisplayTitle AS ClassName,
	         CM.Id As ClassId,
	         DM.Id AS DiVisionId,
	        V.ClassSubjectId AS ClassSubjectId,
	        SA.Name,
	        SA.RollNo,
	        SA.Code,
	        SF.FatherName,
	        So.DateOfBirth,
	        GM.Title AS Gender,
	        EM.Remark1,
	        EM.Remark2,
	        EM.Remark3,
	        SA.AcademicId,
	        SI.StudentPhoto,
	        SF.MotherName,
	        SR. ExamCenter,
	        SR.ExamSeatNo,
	        V.SubjectCode AS SubjectCode,
		
	         
		(CASE EM.IsDisplayImageHeader WHEN 1 THEN
			OI.CertificateHeaderA4 
			ELSE NULL END)AS  MarksheetHeaderA4 ,
			ISNULL(EM.IsDisplayImageHeader,0) AS IsImageHeader,
			EM.IsOnPrePrinted ,
	        --EM.Id As ExamId,
			EM.IsDisplayPhoto,
			SR.ExamBlock,
			EI.EmployeeSign,
			EM.TeacherSignCaption,
			EM.PrincipalSignCaption,
			EM.ParentSignCaption,
			ISNULL(EM.DisplayTitle,'') AS DisplayTitle ,
			ISNULL(ED.ExamTopic,'') AS ExamTopic,
			ISNULL(ED.ExamLanguage,'') AS ExamLanguage,
			ISNULL(SA.OrganizationName,'') AS OrganizationName,
			ISNULL(SA.SUId,'') AS SUId ,
			EM.IsDisplayPrincipalSign AS IsDisplayPrincipalSign,
			ISNULL(SO.UIDNumber,'') AS UId ,
			CSM.Title As CasteCategory ,
		    ISNULL(SO.AdhaarNumber,'') AS AdhaarNumber,
			ISNULL(SO.FamilySubCast,'') AS FamilySubCast,
			DM.DisplayTitle AS DivisionName,   -- 30455
			--mantis Start - 36986		
			ISNULL(SR.ResultRemark1,'') AS ResultRemark1,
			ISNULL(SR.ResultRemark2,'') AS ResultRemark2,
			ISNULL(SR.ResultRemark3,'') AS ResultRemark3,
			--mantis End - 36986	
			(CASE EM.IsDisplayImageHeader WHEN 1 THEN
			OI.MarksheetHeaderA4 
			ELSE NULL END)AS  MarksheetHeader, --Mantis - 40209
			--Added by dhananjay For mantis : 43184
			EMI.EmployeeSign AS ExamCoordinatorSignature, 
			ISNULL(SC.PresentStreetOne,'') AS PresentStreetOne,
			ISNULL(SC.PresentStreetTwo,'') AS PresentStreetTwo,
			ISNULL(SC.PresentStreetThree,'') AS PresentStreetThree,
			ISNULL(SC.PresentCountry,'') AS PresentCountry,
			ISNULL(SC.PresentState,'') AS PresentState,
			ISNULL(SC.PresentCity,'') AS PresentCity,
			ISNULL(SC.PresentZipCode,'') AS PresentZipCode,
			--Added by dhananjay For mantis : 43184
			EM.ResultSheetAdditionalTitle	--Mantis - 43319


			FROM
			sStudent.vStudentAcademic SA 
			INNER JOIN sSetup.tClassMaster CM ON SA.ClassId=CM.Id 
			INNER JOIN sSetup.tDivisionMaster DM ON DM.ClassId=CM.Id AND SA.DivisionId=DM.Id
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id  ANd Em.BatchId=SA.BatchId 
			INNER JOIN sAssessment.tExamSubGroupMaster	ESGM ON ESGM.Id = EM.ExamSubGroupId
			INNER JOIN sAssessment.tExamGroupMaster EGM ON EGM.Id=ESGM.ExamGroupId
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sStudent.tStudentCommunication SC ON SC.StudentId = SA.StudentId--Added by dhananjay For mantis : 43184
			LEFT JOIN sSetup.vClassSubject V ON V.ClassSubjectId = Ed.ClassSubjectId  
			LEFT JOIN sAssessment.tOptionalSubject OS on OS.AcademicId=SA.AcademicId and OS.ClassSubjectId=V.ClassSubjectId
			LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId=SA.StudentId  
			LEFT JOIN sStudent.tStudentOther SO ON So.StudentId=SA.StudentId  
			LEFT JOIN sCommon.tGenderMaster GM ON GM.Id=So.GenderId   
			LEFT JOIN  sStudent.tStudentImages SI ON SI.StudentId=SA.StudentId 
			LEFT JOIN sAssessment.tStudentRemark SR ON SR.ExamId=EM.Id AND SR.AcademicId=SA.AcademicId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=SA.OrgId
			LEFT JOIN sSetup.tOrgImages OI ON OI.Orgid = OM.Id
			LEFT JOIN sHrm.tEmployeeImages EI ON EI.EmployeeId = DM.InchargeEmployeeId
			LEFT JOIN sCommon.tCastCategoryMaster CSM ON CSM.Id=SO.CastCategoryId
			LEFT JOIN sHrm.tEmployeeImages EMI ON EMI.EmployeeId = EM.CoordinatorEmployeeId --Added by dhananjay For mantis : 43184

	WHERE 
			SA.BatchId = @rBatchId 
		 AND (SA.ClassId=@rClassId OR @rClassId=0) 
		 AND (SA.DivisionId=@rDivisionId OR @rDivisionId=0)
		 AND ((SA.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
		 AND ((SA.RollNo <= @rToRollNo) OR (@rToRollNo=0))
		 AND ((ESGM.Id = @rExamSubGroupId) OR (@rExamSubGroupId = 0))	
	     AND ((SA.Code=@rCode) OR (@rCode=''))
	     AND (SA.DepartmentId=@rDepartmentId OR @rDepartmentId=0) 
	     AND (V.SubjectId=@rSubjectId OR @rSubjectId=0) 
	    AND ((V.IsOptional = 1 AND  isnull(OS.AcademicId,0) <> 0) OR (V.IsOptional = 0))
		AND ((SA.StatusId=@rStatusId) OR (@rStatusId = 0))
		AND (SA.ClassStatusId=@rClassStatusId OR @rClassStatusId=0)
	
	Order by ED.ExamDate
END
GO
PRINT N'Altering Procedure [sAssessment].[pRptGraphicalTeacherEvaluationAnalysis3Get]...';


GO



ALTER PROCEDURE [sAssessment].[pRptGraphicalTeacherEvaluationAnalysis3Get]
	 
	 @rBuilder1 nvarchar(max)='', 
	 @rBuilder2 nvarchar(max)='', 
	 @rBatchId int = 0,
	 @rClassId int=0,
	 @rDivisionId int=0,
	 @rExamSubGroupId int = 0,
	 @rOrgId int=0, 
	 @rGroupByid int=0,
	 @rEmployeeId bigint=0,
	 @rExamSubGroupIds nvarchar(max)=''--Added by dhananjay : 42465
	 		 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN

SELECT 
	@rBuilder1 AS Builder1,
	@rBuilder2 AS Builder2,
	ESGM.Title AS ExamName,
	ESGM.Id AS ExamSubGroupId,
	TSD.EmployeeId,
	EmpM.Code AS EmployeeCode,
	SM.Id AS SubjectId,
	SM.Code AS SubjectCode,
	SM.Title AS SubjectName,
	SM.OrderIndex AS SubjectOrderIndex,
	CS.Id AS ClassSubjectId,
	DM.Id AS DivisionId,
	DM.DisplayTitle AS DivisionName,
	CM.Id AS ClassId,
	CM.DisplayTitle AS ClassName,
	A.Id As AcademicId,
	EM.Id AS ExamId,
	RD.IsPresent,
	RD.Obtain AS SubjectObtain,
	ED.Maximum AS SubjectMaximum,
	ED.Minimum AS SubjectMinimum,
	CAST(ROUND((ISNULL(RD.Obtain, 0) * 100.0) / NULLIF(ED.Maximum, 0), 2) AS DECIMAL(5,2)) AS SubjectPercentage,
	ED.DisplayOrder,
	--EmpM.ShortName AS TeacherName,
	ISNULL(EmpM.FirstName, '') + ' ' + ISNULL(EmpM.LastName, '') AS TeacherName,
	EmpM.FirstName,
	EmpM.MiddleName,
	EmpM.LastName,
	R.ResultStatus

	FROM 
		sAssessment.tResultDetail RD
		INNER JOIN sAssessment.tResult R ON R.Id = RD.ResultId
		INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId
		INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId 		
		INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId
		INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
		INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=CS.SubjectId					 
		INNER JOIN sStudent.tAcademic A ON A.Id=R.AcademicId			
		INNER JOIN sStudent.tStudentMaster StuM ON StuM.Id=A.StudentId			
		INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId
		INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId
		INNER JOIN sSetup.tOrganizationMaster OM ON StuM.OrgId = OM.Id
		INNER JOIN sSetup.tDepartmentMaster DP ON DP.Id=CM.DepartmentId						
		INNER JOIN sAcademic.tTeacherSubjectDivision TSD ON SM.Id = TSD.SubjectId AND DM.Id = TSD.DivisionId
		INNER JOIN sHrm.tEmployeeMaster EmpM ON TSD.EmployeeId = EmpM.Id AND EmpM.StatusId = 7			
			
	WHERE (ESGM.Id = @rExamSubGroupId OR @rExamSubGroupId = 0)
		AND ((EM.BatchId = @rBatchId) OR  (@rBatchId = 0))
		AND ((A.ClassId=@rClassId) OR (@rClassId=0)) 
		AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		AND TSD.EmployeeId=@rEmployeeId
		AND (ISNULL(ESGM.Id ,0) IN( SELECT cast(item as nvarchar(20)) FROM  sCommon.fnsplit(@rExamSubGroupIds,',')) OR @rExamSubGroupIds='')--Added by dhananjay : 42465
END
GO
PRINT N'Altering Procedure [sAssessment].[pRptResultSheetStandardGet]...';


GO



ALTER PROCEDURE [sAssessment].[pRptResultSheetStandardGet]
	 
	 @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,
	 @rClassStatusId int=0,
	 @rMultiCode nvarchar(max)=''
	
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 

DECLARE @GradeString nvarchar(1000),  @GradeStringRemark nvarchar(500),
@GradeSetId int,@lGradeStringText nvarchar(1000)
 
SELECT @GradeSetId = GradesetId FROM sAssessment.tExamMaster WHERE Id = @rExamId
 SELECT @GradeString = [sAssessment].[fGradeStringGet](@GradeSetId)
 Select @lGradeStringText = GradeStringText from sAssessment.tGradeSetMaster where Id=@Gradesetid
   
Select @GradeStringRemark = GradeStringText from sAssessment.tGradeSetMaster Where Id =@GradeSetId

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

--add for 28663 mantis start
DECLARE @lAbsentRemarkConfig nvarchar(20) = ''
SELECT @lAbsentRemarkConfig =ItemValue From sConfig.tConfigurationSetup WHERE ConfigurationId = 515 AND SourceTypeId = 1016 AND SourceId = @lOrgId
--add for 28663 mantis end
 
	SELECT 
	R.examId,
		Convert(nvarchar(20),A.Id) AS AcademicIdText,
		Convert(nvarchar(20),@rExamId) AS ExamIdText,
		Convert(nvarchar(20),EM.CoScholasticScopeId) AS CoScholasticScopeIdText,
		Convert(nvarchar(20),ISNULL(EM.IsDisplayMonthlyAttendance,0)) AS IsDisplayMonthlyAttendanceText,
		Convert(nvarchar(20),@rBatchId) AS BatchIdText,
		ESGM.Title AS Exam,
		StuM.Code,
		[sStudent].[fStudentNameGet](stum.FirstName , StuM.MiddleName, StuM.LastName,OM.StudentNameFormatId ) AS Name,
		A.RollNo,
		R.AcademicId,			
		R.ResultStatus,
		CM.DisplayTitle AS Class,
		DM.DisplayTitle AS Division,
		R.TotalMarks,
		R.TotalObtain,
		R.Percentage,
		R.RankNumber,
		R.ResultGrade,
		R.Percentile,			
		RD.Id AS ResultDetailId,		
		ED.IsDisplayInMarksheet,
		ED.IsShowSubjectGrade,
		ED.IsIncludeInTotal,
		RD.Obtain AS SubjectObtain,
		ED.Minimum AS SubjectMinimum,
		ED.Maximum AS SubjectMaximum,
		RD.SubjectGrade,
		SM.Code AS SubjectCode,
		SM.Title AS SubjectName,
		(CASE ISNULL(ED.DisplayOrder,0)
		WHEN 0 THEN CS.OrderIndex
		ELSE ED.DisplayOrder END) AS SubjectOrderIndex,
		R.Id AS ResultId,
		CS.Id AS SubjectId,			 	
		EM.IsMarksInDecimal,
		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.IsMarksInDecimal,
		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,
		EM.TermScopeId,
		(CASE EM.IsDisplayPhoto WHEN 1 THEN
			SI.StudentPhoto
		ELSE NULL END) AS StudentPhoto,
		RD.IsPresent,
		CASE @GradeStringRemark WHEN '' THEN @GradeString  ELSE @GradeStringRemark END AS GradeString,
		EM.IsDisplayGradeString,
		(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,			
		OM.SmallAddress1,
		EM.IsDisplayParentName,
		SF.FatherName,
		SF.MotherName,
		ISNULL(ED.IsShowSubjectMark,1) AS IsShowSubjectMark,
		
		EM.IsDisplayTeacherSign,
		Em.IsDisplayPrincipalSign,
		(CASE 	EM.IsDisplayTeacherSign WHEN 1 THEN
			EI.EmployeeSign
		ELSE NULL END)AS EmployeeSign,
		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,
		
		SR.StudentHeight,
		SR.StudentWeight,		
		SR.PresentDays,			
		SR.TotalDays,
		SR.ResultRemark1,
		SR.ResultRemark2,
		SR.Resultremark3,
		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.DentalHygiene,'') AS DentalHygiene,
		ISNULL(SR.VisionLeft,'') AS VisionLeft,
		ISNULL(SR.VisionRight,'') AS VisionRight,
		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(Emp.FirstName,'') +' ' + ISNULL(EMp.LastName,'') AS ClassTeacherName,
		BM.Title AS BatchName,
		Em.DecimalFormat,
		RD.GraceMark,
		ISNULL(SM.SubjectGroupId,0) AS SubjectGroupId,
		ISNULL(SG.Title,'')AS SubjectGroupTitle,
		ISNULL(SG.Code,'') AS SubjectGroupCode,
		@lGradeStringText AS GradeStringText,
		ISNULL(HM.Title,'') AS House,
		ISNULL(EM.TeacherSignCaption,'') As TeacherSignCaption,
		ISNULL(EM.PrincipalSignCaption,'') As PrincipalSignCaption,
		ISNULL(EM.ParentSignCaption,'') As ParentSignCaption,
		ISNULL(BGM.Title,'') AS BloodGroup,
		GS.GradeTitle,
		GS.GradePoint,
		RAD.SubjectHighestDivisionGrade,
		RAD.SubjectHighestDivisionMark,
		GM.Title AS Gender,
		RD.KrupaMark,
		RD.Remark AS OtherDetailRemark,
		ISNULL(SO.AdhaarNumber,'') AS AdharNumber,
		ISNULL(SO.UIDNumber,'') AS UIDNumber,
		ISNULL(SC.PresentStreetOne,'')+' '+ISNULL(SC.PresentStreetTwo,'')+' '+ISNULL(SC.PresentStreetThree,'')+' '+ISNULL(SC.PresentCity,'')+' '+ISNULL(SC.PresentState,'') AS PresentAddress,
		ISNULL(SC.ParentContactNo,'') AS ContactNo,
		(CASE  When EM.IsDisplayAbsentCount=1 then ([sAssessment].[fGetAbsentCount](@rExamId,R.AcademicId, CS.Id)) ELSE 0 END) AS AbsentCount,
		(CASE  When EM.CoordinatorEmployeeId IS NOT NULL AND EM.CoordinatorEmployeeId !=0 then EICoordinator.EmployeeSign ELSE NULL END) AS CoordinatorEmployeeSign,
		ISNULL((SELECT ISNULL(Template,'') FROM sCommon.tReportTemplate WHERE ReportId = 20438 AND OrgId=A.OrgId),0) AS ReportTemplate,
		StuM.SUId As SUID,
		ISNULL(SO.MotherTongue,'') as MotherTongue,
		CONVERT(bit,@DecimalConfigid) AS IsDecimal,
		ISNULL(Stum.RegistrationNumber,'') as RegistrationNumber,
		EM.IsDisplayHighestDivisionMark,
		EM.ResultSheetAdditionalTitle,
		SR.ExamSeatNo,
		ISNULL(R.ResultIndicator,'') AS ResultIndicator,
		CONVERT(bit,@lAbsentRemarkConfig) AS IsAbsentRemark,	--add for 28663 mantis
		ISNULL(RD.AbsentRemark,'') AS AbsentRemark,				--add for 28663 mantis
		ISNUll(SF.FatherContactNo,'') AS FatherContactNo,		--Mantis - 0033000
		ISNUll(SF.MotherContactNo,'') AS MotherContactNo,		--Mantis - 0033000
		ISNUll(ED.ExamTopic,'') AS ExamTopic,        --Mantis : 0035823
		ISNULL(StuM.PENNumber, 0 ) AS PENNumber, --Mantis : 36466
		ISNULL(CM1.Title,'') AS StudentCategory, --Added for mantis : 37293
		ISNULL(SO.BirthDateInWord,'') AS BirthDateInWord, --Added for mantis : 37293
		ISNULL(EM.ExamMaximum,0) AS ExamMaximum, --Add for mantis : 0037275
		--Added by dhananjay for mantis - 37594
		ISNULL(StuM.FirstName,'') AS FirstName,
		ISNULL(StuM.LastName,'') AS LastName,
		ISNULL(SGM.Title,'') AS StudentGroup,
		--Added by dhananjay for mantis - 37594
		ISNULL(StuA.AdmissionNumber,0) AS AdmissionNo, -- add for mantis : 0037908
		ED.ExamDate AS ExamDate,   --Mantis - 38799
		--add for 42003 mantis start
		ISNULL(SC.PermanentStreetOne,'') AS PermanentStreetOne,
		ISNULL(SC.PermanentStreetTwo,'') AS PermanentStreetTwo,
		ISNULL(SC.PermanentStreetThree,'') AS PermanentStreetThree,
		--add for 42003 mantis End
		ISNULL(StuM.ApaarIdNumber,'') AS ApaarIdNumber,		--Mantis - 42192
		--Added by dhannanjay mantis : 42409
		ISNULL(RM.Title,'') AS Religion,
		ISNULL(SO.FamilyCast,'') AS FamilyCast,
		ISNULL(SO.FamilySubCast,'') AS FamilySubCast,
		SC.StudentContactNo AS StudentContactNo,
		--Added by dhannanjay mantis : 42409
		--Added by dhannanjay mantis : 42836
		ISNULL(SC.PermanentCountry,'') AS PermanentCountry,
		ISNULL(SC.PermanentState,'') AS PermanentState,
		ISNULL(SC.PermanentCity,'') AS PermanentCity,
		ISNULL(SC.PermanentZipCode,'') AS PermanentZipCode,
		--Added by dhannanjay mantis : 42836
		ISNULL(OM.University,'') AS University
		--Added by dhannanjay mantis : 42925

	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
		LEFT JOIN sStudent.tAcademicDetail AD ON AD.AcademicId=A.Id
		INNER JOIN sStudent.tStudentMaster StuM ON StuM.Id=A.StudentId
		LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId=A.StudentId
		LEFT JOIN scommon.tReligionMaster RM On RM.Id = SO.ReligionId--Added by dhananjay for mantis : 42409
		LEFT JOIN sCommon.tGenderMaster GM ON GM.Id = SO.GenderId
		LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId=StuM.Id
		INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId
		INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId
		LEFT JOIN sHrm.tEmployeeMaster Emp ON Emp.Id=DM.InchargeEmployeeId AND ISNULL(EMP.IsOtherUser,0) = 0
		LEFT JOIN sHrm.tEmployeeImages EI ON EI.EmployeeId = Dm.InchargeEmployeeId
		INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id = EM.EXAMSUBGROUPID
		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
		INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.batchId
		LEFT JOIN sActivity.tHouseMaster HM ON HM.Id=SO.HouseId
		LEFT JOIN 	sCommon.tBloodGroupMaster BGM ON BGM.Id=So.BloodGroupId
		LEFT JOIN sAssessment.tGradeSetDetail GS ON GS.GradeSetId=ED.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 sStudent.tStudentCommunication SC ON SC.StudentId=A.StudentId
		LEFT JOIN sHrm.tEmployeeImages EICoordinator ON EICoordinator.EmployeeId = EM.CoordinatorEmployeeId
		LEFT JOIN sCommon.tCastCategoryMaster CM1 ON CM1.Id = SO.CastCategoryId --Added for mantis : 37293
		LEFT JOIN sStudent.tStudentGroupMaster SGM ON SGM.Id = StuM.StudentGroupId--Added by dhananjay for mantis : 37594
		LEFT JOIN sStudent.tStudentAdmission StuA ON StuM.Id = StuA.StudentId -- add for mantis : 0037908
	WHERE 
			
		((EM.BatchId = @rBatchId) OR  (@rBatchId = 0))
		AND ((A.ClassId=@rClassId) OR (@rClassId=0)) 
		AND ((SM.Id=@rSubjectId) OR (@rSubjectId=0))
		AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId=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 (R.ExamId = @rExamId)
		AND ((StuM.Code=@rCode) OR (@rCode=''))
		AND ((R.Id = @rResultId) OR (@rResultId = 0))
		AND ((StuM.StatusId=@rStatusId)OR(@rStatusId=0))
		AND ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0)) 
		--AND  ISNULL(EMP.IsOtherUser,0) = 0
		AND (ISNULL(StuM.Code,0) IN( SELECT cast(item as nvarchar(20)) FROM  sCommon.fnsplit(@rMultiCode,',')) OR @rMultiCode='')
		order by A.RollNo,ED.DisplayOrder
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)='' ,
	 @rOrderBy int = 0    --Added by dhananjay for mantis : 39391
	 --,@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(2000),
		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,
		BMI decimal(10,2),
		--Mantis End - 0032150
		SubjectGroupOrderIndex smallint,		-- MantisId : 0033292
		RelativeName nvarchar(100), -- Added by dhananjay mantis id : 36622
		SubjectMinTerm1 decimal(10,2), -- add for mantis : 0036630
		SubjectMinTerm2 decimal(10,2), -- add for mantis : 0036630
		SubjectMinTerm3 decimal(10,2),  -- add for mantis : 0036630
		BirthDateInWord nvarchar(150), --added by dhananjay for mantis - 37292
		SchoolStamp varbinary(max),  --Mantis - 38100
		SubjectWiseTeacher nvarchar(max), --Mantis - 38469
		RelativeContactNo nvarchar(50), -- Mantis : 0038696
		FilterWiseOrderBy int, --Added  by dhananjay for mantis : 39391
		PENNumber BigInt, --Added  by dhananjay for mantis : 39863
		ApaarIdNumber nvarchar(50)--Added by dhananjay for mantis : 40247
		,MinimumMark1 decimal(10,2)
		,MinimumMark2 decimal(10,2)
		,MinimumMark3 decimal(10,2)
		,MinimumMark4 decimal(10,2)
		,MinimumMark5 decimal(10,2)
		,MinimumMark6 decimal(10,2)
		,MinimumMark7 decimal(10,2)
		,MinimumMark8 decimal(10,2)
		,MinimumMark9 decimal(10,2)
		,MinimumMark10 decimal(10,2)
		,MinimumMark11 decimal(10,2)
		,MinimumMark12 decimal(10,2)
		,MinimumMark13 decimal(10,2)
		,SubjectRemarkOther Nvarchar(1000), --Added by dhananjay for mantis : 41047
		PresentCity Nvarchar(100), --Mantis - 41591
		--start mantis : 0041741
		IsGrade1 bit,
		IsGrade2 bit,
		IsGrade3 bit,
		IsGrade4 bit,
		IsGrade5 bit,
		IsGrade6 bit,
		IsGrade7 bit,
		IsGrade8 bit,
		IsGrade9 bit,
		IsGrade10 bit,
		IsGrade11 bit,
		IsGrade12 bit,
		IsGrade13 bit,
		--end mantis : 0041741
		--Added by dhannanjay mantis : 42226
		IsDisplayTotalMark1 bit,
		IsDisplayTotalMark2 bit,
		IsDisplayTotalMark3 bit,
		IsDisplayTotalMark4 bit,
		IsDisplayTotalMark5 bit,
		IsDisplayTotalMark6 bit,
		IsDisplayTotalMark7 bit,
		IsDisplayTotalMark8 bit,
		IsDisplayTotalMark9 bit,
		IsDisplayTotalMark10 bit,
		IsDisplayTotalMark11 bit,
		IsDisplayTotalMark12 bit,
		IsDisplayTotalMark13 bit,
		--Added by dhannanjay mantis : 42226
		--Added by dhannanjay mantis : 42409
		Religion nvarchar (50),
		FamilyCast nvarchar (100),
		FamilySubCast nvarchar (100),
		MotherTongue  nvarchar(100),
		--Added by dhannanjay mantis : 42409
		--Added by dhannanjay mantis : 42836
		PermanentCountry nvarchar(50),
		PermanentState  nvarchar(50),
		PermanentCity  nvarchar(50),
		PermanentZipCode  nvarchar(20)
		--Added by dhannanjay mantis : 42836

		)
	 --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
	BMI,
	SubjectGroupOrderIndex,		--MantisId : 0033292
	RelativeName,  -- Added by dhananjay mantis id : 36622
	BirthDateInWord, --added by dhananjay for mantis - 37292
	SchoolStamp,  --Mantis - 38100
	SubjectWiseTeacher, --Mantis - 38469
	RelativeContactNo, -- Mantis : 0038696
	FilterWiseOrderBy,  --Added  by dhananjay for mantis : 39391
	PENNumber,--Added  by dhananjay for mantis : 39863
	ApaarIdNumber, --Added by dhananjay for mantis : 40247
	SubjectRemarkOther, --Added by dhananjay for mantis : 41047
	PresentCity,	--Mantis - 41591
	--Added by dhannanjay mantis : 42409
	Religion,
	FamilyCast,
	FamilySubCast,
	MotherTongue,
	--Added by dhannanjay mantis : 42409
	--Added by dhannanjay mantis : 42836
	PermanentCountry,
	PermanentState,
	PermanentCity,
	PermanentZipCode
	--Added by dhannanjay mantis : 42836
	)
	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
		CASE
				WHEN ISNULL(AD.HeightAnnual,0)=0 THEN 0
				ELSE CONVERT(decimal(10,2),(ISNULL(AD.WeightAnnual,0)/POWER((ISNULL(AD.HeightAnnual,0)/100),2))) END AS BMI,    -- Mantisid - 0033160
		SG.OrderIndex AS SubjectGroupOrderIndex,			-- MantisId : 0033292
		ISNULL(SF.RelativeName,'') AS RelativeName, -- Added by dhananjay mantis id : 36622
		ISNULL(SO.BirthDateInWord,'') AS BirthDateInWord, --added by dhananjay for mantis - 37292
		OI.SchoolStamp AS SchoolStamp,		--Mantis - 38100
		[sAttendance].[fSubjectTeacherGet](DM.Id,SM.Id) AS SubjectWiseTeacher,		--Mantis - 38469
		ISNULL(SF.RelativeContactNo,'') AS RelativeContactNo ,--add for mantis : 0038696
		@rOrderBy, --Added by dhananjay for Mantis : 39391
		ISNULL(StuM.PENNumber,0) AS PENNumber,--Added  by dhananjay for mantis : 39863
		ISNULL(StuM.ApaarIdNumber,'') AS ApaarIdNumber,--Added  by dhananjay for mantis : 40247
		ISNULL(RDO.Remark,'') AS SubjectRemarkOther, --Added by dhananjay for mantis : 41047
		ISNULL(SC.PresentCity,'') AS City,	--Mantis - 41591
		--Added by dhannanjay mantis : 42409
		ISNULL(RM.Title,'') AS Religion,
		ISNULL(SO.FamilyCast,'') AS FamilyCast,
		ISNULL(SO.FamilySubCast,'') AS FamilySubCast,
		ISNULL(SO.MotherTongue,'') AS MotherTongue,
		--Added by dhannanjay mantis : 42409
		--Added by dhannanjay mantis : 42836
		ISNULL(SC.PermanentCountry,'') AS PermanentCountry,
		ISNULL(SC.PermanentState,'') AS PermanentState,
		ISNULL(SC.PermanentCity,'') AS PermanentCity ,
		ISNULL(SC.PermanentZipCode,'') AS PermanentZipCode
		--Added by dhannanjay mantis : 42836
				
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 scommon.tReligionMaster RM On RM.Id = SO.ReligionId--Added by dhananjay for mantis : 42409
	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.  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
	LEFT JOIN sAssessment.tResultDetailOther RDO ON  RDO.ExamId = EM.Id AND R.Academicid =RDO.AcademicId AND ED.ClassSubjectId = RDO.ClassSubjectId --Added by dhananjay for mantis: 41047
	 
	 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	
					,MinimumMark' + convert(nvarchar(15),@lCount)+ '=ED.Minimum		--add for mantis : 0041047				
					 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, 
					IsGrade'+convert(nvarchar(15),@lCount)+'=EM.IsGrade,
					IsDisplayTotalMark'+convert(nvarchar(15),@lCount)+'=EM.IsDisplayTotalMark  					
					 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)  --added IsDisplayTotalMark by dhananjay mantis : 42226
						
		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,
					 SubjectMinTerm1 = ED.Minimum 
					 							 
					 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) --SubjectMinTerm1 add for mantis : 0036630
				
		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,
					SubjectMinTerm2= ED.Minimum
									 
					 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)  --SubjectMinTerm2 add for mantis : 0036630
		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,
					SubjectMinTerm3= ED.Minimum
					 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)  -- SubjectMinTerm3 add for mantis : 0036630
		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
	
 
	END

--	SELECT @rBuilder1 AS Builder1,@rBuilder2 AS Builder2, T.*, 0 AS FilterWiseOrderBy,Convert (BigInt, 0)AS PENNumber, '' AS ApaarIdNumber,
--	Convert (decimal, 0) AS MinimumMark1 
--	,Convert (decimal, 0) AS MinimumMark2 
--	,Convert (decimal, 0) AS MinimumMark3 
--	,Convert (decimal, 0) AS MinimumMark4 
--	,Convert (decimal, 0) AS MinimumMark5 
--	,Convert (decimal, 0) AS MinimumMark6 
--	,Convert (decimal, 0) AS MinimumMark7 
--	,Convert (decimal, 0) AS MinimumMark8 
--	,Convert (decimal, 0) AS MinimumMark9 
--	,Convert (decimal, 0) AS MinimumMark10
--	,Convert (decimal, 0) AS MinimumMark11
--	,Convert (decimal, 0) AS MinimumMark12
--	,Convert (decimal, 0) AS MinimumMark13
--	,'' As SubjectRemarkOther
--  ,'' AS PresentCity,	
--		Convert (bit,0) AS IsGrade1,
--		Convert (bit,0) AS IsGrade2,
--		Convert (bit,0) AS IsGrade3,
--		Convert (bit,0) AS IsGrade4,
--		Convert (bit,0) AS IsGrade5,
--		Convert (bit,0) AS IsGrade6,
--		Convert (bit,0) AS IsGrade7,
--		Convert (bit,0) AS IsGrade8,
--		Convert (bit,0) AS IsGrade9,
--		Convert (bit,0) AS IsGrade10,
--		Convert (bit,0) AS IsGrade11,
--		Convert (bit,0) AS IsGrade12,
--		Convert (bit,0) AS IsGrade13,
--		Convert (bit,0) AS IsDisplayTotalmark1,
--		Convert (bit,0) AS IsDisplayTotalmark2,
--		Convert (bit,0) AS IsDisplayTotalmark3,
--		Convert (bit,0) AS IsDisplayTotalmark4,
--		Convert (bit,0) AS IsDisplayTotalmark5,
--		Convert (bit,0) AS IsDisplayTotalmark6,
--		Convert (bit,0) AS IsDisplayTotalmark7,
--		Convert (bit,0) AS IsDisplayTotalmark8,
--		Convert (bit,0) AS IsDisplayTotalmark9,
--		Convert (bit,0) AS IsDisplayTotalmark10,
--		Convert (bit,0) AS IsDisplayTotalmark11,
--		Convert (bit,0) AS IsDisplayTotalmark12,
--		Convert (bit,0) AS IsDisplayTotalmark13,
--		'' AS Religion, 
--		'' AS FamilyCast, 
--		'' AS FamilySubCast,
--		'' AS MotherTongue,
--		'' AS PermanentCountry,
--		'' AS PermanentState,
--		'' AS PermanentCity ,
--		'' AS PermanentZipCode

--	 FROM sAssessment.tTempAllExam T
	
	
--end
GO
PRINT N'Altering Procedure [sAssessment].[pRptResultSheetStandardMultiExamGetwithResultDetailOther]...';


GO
 ALTER PROCEDURE [sAssessment].[pRptResultSheetStandardMultiExamGetwithResultDetailOther]
	@rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 @rSubjectId int = 0,
	 @rBatchId int=0,
	 @rClassId int=0,
	 @rDivisionId int=0,
	 @rExamId int,
	 @rCode nvarchar(20)='',
	 @rFromRollNo int=0,
	 @rToRollNo int=0,
	 @rFromRank int=0,
	 @rToRank int=0,
	 @rGrade nvarchar(20)='',
	 @rResultId bigint=0,
	 @rStatusId int=0,
	 @rAcademicId bigint=0,
	 @rFromPercentage decimal(5,2)=0,
	 @rToPercentage decimal(5,2)=0,
	 @rIsDetail bit=0,
	 @rIsShowWithDetail bit=0,
	 @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
 
  
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

--#TempAllExam
	CREATE TABLE #TempAllExam
	(
		AcademicIdText nvarchar(20),
		ExamIdText nvarchar(20),
		DivisionIdText nvarchar(50),
		CoScholasticScopeIdText nvarchar(20),
		IsDisplayMonthlyAttendanceText nvarchar(20),
		ClassIdText nvarchar(50),
		AcademicId bigint,
		ExamName Nvarchar(150),
		StudCode NVarchar(20),
		StudentName Nvarchar(150),
		RollNo int,
		ResultStatus Nvarchar(20),	
		ClassName NVarchar(50),		
		Division NVarchar(50),
		TotalMark decimal(8,2),
		TotalObtain decimal(8,2),
		Percentage decimal(8,2),
		RankNumber int,
		ResultGrade NVarchar(50),
		
		MaximumMark1 decimal(8,2),		
		SubjectGrade1 NVarchar(50),
		Obtain1 decimal(8,2) Default 0,
		ExamMaximum1 decimal(8,2),
		IsPresent1 bit,
						
		MaximumMark2 decimal(8,2),	
		SubjectGrade2 NVarchar(50),
		Obtain2 decimal(8,2) Default 0,
		ExamMaximum2 decimal(8,2),
		IsPresent2 bit,
				
		MaximumMark3 decimal(8,2),
		SubjectGrade3 NVarchar(50),
		Obtain3 decimal(8,2) Default 0,
		ExamMaximum3 decimal(8,2),
		IsPresent3 bit,		
		
		MaximumMark4 decimal(8,2),	
		SubjectGrade4 NVarchar(50),
		Obtain4 decimal(8,2) Default 0,
		ExamMaximum4 decimal(8,2),
		IsPresent4 bit,	
				
		MaximumMark5 decimal(8,2),		
		SubjectGrade5 NVarchar(50),
		Obtain5 decimal(8,2) Default 0,
		ExamMaximum5 decimal(8,2),
		IsPresent5 bit,	
				
		MaximumMark6 decimal(8,2),		
		SubjectGrade6 NVarchar(50),
		Obtain6 decimal(8,2) Default 0,
		ExamMaximum6 decimal(8,2),
		IsPresent6 bit,	
		
		MaximumMark7 decimal(8,2),		
		SubjectGrade7 NVarchar(50),
		Obtain7 decimal(8,2) Default 0,
		ExamMaximum7 decimal(8,2),
		IsPresent7 bit,	
		
		MaximumMark8 decimal(8,2),	
		SubjectGrade8 NVarchar(50),
		Obtain8 decimal(8,2) Default 0,
		ExamMaximum8 decimal(8,2),
		IsPresent8 bit,	
		
		MaximumMark9 decimal(8,2),		
		SubjectGrade9 NVarchar(50),
		Obtain9 decimal(8,2) Default 0,
		ExamMaximum9 decimal(8,2),
		IsPresent9 bit,	
		
		
		MaximumMark10 decimal(8,2),		
		SubjectGrade10 NVarchar(50),
		Obtain10 decimal(8,2) Default 0,
		ExamMaximum10 decimal(8,2),
		IsPresent10 bit,	
		
		MaximumMark11 decimal(8,2),		
		SubjectGrade11 NVarchar(50),
		Obtain11 decimal(8,2) Default 0,
		ExamMaximum11 decimal(8,2),
		IsPresent11 bit,
		
		MaximumMark12 decimal(8,2),		
		SubjectGrade12 NVarchar(50),
		Obtain12 decimal(8,2) Default 0,
		ExamMaximum12 decimal(8,2),
		IsPresent12 bit,		
		 
		 
		SubjectGradeTerm1 NVarchar(50),
		SubjectGradeTerm2 NVarchar(50),
		SubjectGradeTerm3 NVarchar(50),
		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(500),
		Remark3 nvarchar(500),
		DisplayTitle nvarchar(150),		
		IsRankNo bit, 
		IsGrade bit,
		IsPercentile bit,
		IsPercentage bit,
		IsSubjectPercentile bit,
		IsProcessResult bit,
		IsNegativeMarks bit,
		IsIncludeCoScholastic bit,
		IsOnPrePrinted bit,
		IsDisplayPhoto bit,
		IsDisplayBirthDate bit,
		IsLockForEdit bit,
		IsDisplaySchoolName bit,			
		IsDisplayAttendance bit,
		IsDisplayHeightWeight bit,
		IsResultStatus bit,
		FooterAdjustmentText nvarchar(max),
		DetailAdjustmentText nvarchar(max),
		FooterAdjustment smallint,
		DetailAdjustment smallint,
		ResultRemark nvarchar(200),
		DateOfBirth date,
		HeightTerm1 decimal(5,2),
		WeightTerm1 decimal(5,2),
		HeightTerm2 decimal(5,2),
		WeightTerm2 decimal(5,2),
		HeightAnnual decimal(5,2),
		WeightAnnual decimal(5,2),
		PresentDaysTerm1 smallint,
		PresentDaysTerm2 smallint,
		PresentDaysAnnual smallint,
		TotalDaysTerm1 smallint,
		TotalDaysTerm2 smallint,
		TotalDaysAnnual smallint,
		TotalMarkTerm1 decimal(8,2),
		TotalObtainTerm1 decimal(8,2),
		PercentageTerm1 decimal(8,2),
		RankNumberTerm1 int,
		ResultGradeTerm1 NVarchar(50),
		PercentileTerm1 decimal(8,2),
		ResultStatusTerm1 Nvarchar(20),		   
		TotalMarkTerm2 decimal(8,2),
		TotalObtainTerm2 decimal(8,2),
		PercentageTerm2 decimal(8,2),
		RankNumberTerm2 int,
		ResultGradeTerm2 NVarchar(50),
		PercentileTerm2 decimal(8,2),
		ResultStatusTerm2 Nvarchar(20), 
		TotalMarkTerm3 		decimal(8,2),
		TotalObtainTerm3 decimal(8,2),
		PercentageTerm3 decimal(8,2),
		RankNumberTerm3 int,
		ResultGradeTerm3 NVarchar(50),
		PercentileTerm3 decimal(8,2),
		ResultStatusTerm3 Nvarchar(20), 
		
		TermScopeId tinyint,		 
		StudentPhoto varbinary(max),
		GradeString nvarchar(1000),
		IsDisplayGradeString bit,		 
		IsDisplayInMarksheet bit,
		IsShowSubjectGrade bit,
		IsIncludeInTotal bit,
		ClassSubjectID int,
		SubjectId int,
		--Maximum decimal(5,2),
		SubjectOrderIndex smallint,
		SubjectGrade NVarchar(50),
		SubjectName NVarchar(150),
		SubjectCode Nvarchar(50),	
		SubjectMinimum decimal(8,2),		
		SubjectMaximum decimal(8,2),
		SubjectObtain  decimal(8,2),
		
		Exam1Name Nvarchar(150),		
		TotalMarks1 decimal(8,2),		
		TotalObtain1 decimal(8,2),
		Percentage1 decimal(8,2),
		RankNumber1 int,
		ResultGrade1 NVarchar(50),
		Percentile1 decimal(8,2),
		ResultStatus1 Nvarchar(20),
		
		Exam2Name nvarchar(150),	
		TotalMarks2 decimal(8,2),
		TotalObtain2 decimal(8,2),
		Percentage2 decimal(8,2),
		RankNumber2 int,
		ResultGrade2 NVarchar(50),
		Percentile2 decimal(8,2),
		ResultStatus2 Nvarchar(20),
		
		Exam3Name nvarchar(150),	
		TotalMarks3 decimal(8,2),
		TotalObtain3 decimal(8,2),
		Percentage3 decimal(8,2),
		RankNumber3 int,
		ResultGrade3 NVarchar(50),
		Percentile3 decimal(8,2),		
		ResultStatus3 Nvarchar(20),
		
		Exam4Name nvarchar(150),	
		TotalMarks4 decimal(8,2),
		TotalObtain4 decimal(8,2),
		Percentage4 decimal(8,2),
		RankNumber4 int,
		ResultGrade4 NVarchar(50),
		Percentile4 decimal(8,2),
		ResultStatus4 Nvarchar(20),
		
		Exam5Name nvarchar(150),		
		TotalMarks5 decimal(8,2),
		TotalObtain5 decimal(8,2),
		Percentage5 decimal(8,2),
		RankNumber5 int,
		ResultGrade5 NVarchar(50),
		Percentile5 decimal(8,2),
		ResultStatus5 Nvarchar(20),
		
		Exam6Name nvarchar(150),	
		TotalMarks6 decimal(8,2),
		TotalObtain6 decimal(8,2),
		Percentage6 decimal(8,2),
		RankNumber6 int,
		ResultGrade6 NVarchar(50),
		Percentile6 decimal(8,2),
		ResultStatus6 Nvarchar(20),
		
		Exam7Name nvarchar(150),		
		TotalMarks7 decimal(8,2),
		TotalObtain7 decimal(8,2),
		Percentage7 decimal(8,2),
		RankNumber7 int,
		ResultGrade7 NVarchar(50),
		Percentile7 decimal(8,2),
		ResultStatus7 Nvarchar(20),
		
		Exam8Name nvarchar(150),
		TotalMarks8 decimal(8,2),
		TotalObtain8 decimal(8,2),
		Percentage8 decimal(8,2),
		RankNumber8 int,
		ResultGrade8 NVarchar(50),
		Percentile8 decimal(8,2),
		ResultStatus8 Nvarchar(20),
		
		
		Exam9Name nvarchar(150),	
		TotalMarks9 decimal(8,2),
		TotalObtain9 decimal(8,2),
		Percentage9 decimal(8,2),
		RankNumber9 int,
		ResultGrade9 NVarchar(50),
		Percentile9 decimal(8,2),
		ResultStatus9 Nvarchar(20),
		
		Exam10Name nvarchar(150),	
		TotalMarks10 decimal(8,2),
		TotalObtain10 decimal(8,2),
		Percentage10 decimal(8,2),
		RankNumber10 int,
		ResultGrade10 NVarchar(50),
		Percentile10 decimal(8,2),
		ResultStatus10 Nvarchar(20),
		
		Exam11Name nvarchar(150),	
		TotalMarks11 decimal(8,2),
		TotalObtain11 decimal(8,2),
		Percentage11 decimal(8,2),
		RankNumber11 int,
		ResultGrade11 NVarchar(50),
		Percentile11 decimal(8,2),
		ResultStatus11 Nvarchar(20),
		
		Exam12Name nvarchar(150),	
		TotalMarks12 decimal(8,2),
		TotalObtain12 decimal(8,2),
		Percentage12 decimal(8,2),
		RankNumber12 int,
		ResultGrade12 NVarchar(50),
		Percentile12 decimal(8,2),
		ResultStatus12 Nvarchar(20),
		
		ResultRemark1 nvarchar(200),
		ResultRemark2 nvarchar(200),
		
		TotalDays decimal(6,2),
		PresentDays decimal(6,2),
		StudentHeight decimal(6,2),
		StudentWeight decimal(6,2),
		ExamSeatNo nvarchar(20),
		ExamId int,
		
		ExamCode nvarchar(20),
		Exam1Code nvarchar(20),
		Exam2Code nvarchar(20),
		Exam3Code nvarchar(20),
		Exam4Code nvarchar(20),
		Exam5Code nvarchar(20),
		Exam6Code Nvarchar(20),
		Exam7Code Nvarchar(20),
		Exam8Code nvarchar(20),
		Exam9Code nvarchar(20),
		Exam10Code nvarchar(20),
		Exam11Code nvarchar(20),
		Exam12Code nvarchar(20),
		
		IsDisplayParentName bit,
		FatherName nvarchar(100),
		MotherName nvarchar(100),
		IsShowSubjectMark bit, 
		IsOptionalSubject bit,
		CoScholasticScopeId tinyint,
		IsDisplayPrincipalSign bit,
		IsDisplayTeacherSign bit,
		EmployeeSign varbinary(max),
		Batch nvarchar(100),
		ExamNameTerm1 NVarchar(100),
		ExamNameTerm2 NVarchar(100) ,
		ExamNameTerm3 NVarchar(100),
		ClassTeacherName Nvarchar(max),
		InchargeEmployeeName Nvarchar(max),
		FirstName nvarchar(50),
		LastName nvarchar(50),
		IsDisplayMonthlyAttendance bit,
		MarksheetHeaderA4 varbinary(max),
		IsImageHeader bit,
		MyGoal nvarchar(200),
		AreaOfInterest nvarchar(200),
		Responsibility nvarchar(200),
		MyInterestHobby nvarchar(200),
		MyStrength nvarchar(200),
		Achievements nvarchar(200),
		
		DentalHygiene nvarchar(200),
		VisionLeft nvarchar(50),
		VisionRight nvarchar(50), 
		IsDetail bit,
		SubjectGroupId int,
		SubjectGroupTitle nvarchar(50),
		SubjectGroupCode nvarchar(50),
		DecimalFormat nvarchar(10),
		SubjectRemark nvarchar(1000),
		GraceMark decimal(5,2),
		KrupaMark decimal(5,2),
		GradeStringHtml nvarchar(500),
		ResultRemark3 nvarchar(200),
		IsDisplayTotalMark bit,
		SubjectObtainTerm1 decimal(8,2),	
		SubjectObtainTerm2 decimal(8,2),
		SubjectObtainTerm3  decimal(8,2),
		SubjectMaxTerm1 decimal(8,2),
		SubjectMaxTerm2 decimal(8,2),
		SubjectMaxTerm3 decimal(8,2),
		ContactNo nvarchar(20),
		PresentAddress nvarchar(max),
		TeacherSignCaption nvarchar(100),
		PrincipalSignCaption nvarchar(100),
		ParentSignCaption nvarchar(100),
		ImprovementArea nvarchar(200),
		ProgressArea nvarchar(200),
		GeneralRemark nvarchar(1000),
		MyActivity nvarchar(200),
		ClassTeacherRemark nvarchar(1000),
		 
		HouseRemark nvarchar(1000),
		BloodGroup Nvarchar(100),
		TotalDays1 decimal(6,2),
		PresentDays1 decimal(6,2),
		TotalDays2 decimal(6,2),
		PresentDays2 decimal(6,2),
		TotalDays3 decimal(6,2),
		PresentDays3 decimal(6,2),
		TotalDays4 decimal(6,2),
		PresentDays4 decimal(6,2),
		TotalDays5 decimal(6,2),
		PresentDays5 decimal(6,2),
		TotalDays6 decimal(6,2),
		PresentDays6 decimal(6,2),
		TotalDays7 decimal(6,2),
		PresentDays7 decimal(6,2), 
		TotalDays8 decimal(6,2),
		PresentDays8 decimal(6,2),
		TotalDays9 decimal(6,2),
		PresentDays9 smallint,
		TotalDays10 decimal(6,2),
		PresentDays10 decimal(6,2),
		TotalDays11 decimal(6,2),
		PresentDays11 decimal(6,2),
		TotalDays12 decimal(6,2),
		PresentDays12 decimal(6,2),
		BatchIdText nvarchar(20),
		IsShowWithDetail bit,
		IsPresent bit,
		GradeTitle nvarchar(50),
		SubjectHighestDivisionGrade nvarchar(50),
		SubjectHighestDivisionMark decimal(5, 2),
		
		AchievementsTerm1 nvarchar(200),
		AchievementsTerm2 nvarchar(200),
		GeneralRemarkTerm1 nvarchar(200),
		GeneralRemarkTerm2 nvarchar(200),
		ResultRemark1Term1 nvarchar(200),
		ResultRemark2Term1 nvarchar(200),
		ResultRemark1Term2 nvarchar(200),
		ResultRemark2Term2 nvarchar(200),
		SR_HeightTerm1 decimal(5,2),
		SR_WeightTerm1 decimal(5,2),
		SR_HeightTerm2 decimal(5,2),
		SR_WeightTerm2 decimal(5,2),
		SR_PresentDaysTerm1 decimal(6,2),
		SR_PresentDaysTerm2 decimal(6,2),
		SR_TotalDaysTerm1 decimal(6,2),
		SR_TotalDaysTerm2 decimal(6,2),
		TotalCount smallint,
		PresentCount smallint,
		Remark4 nvarchar(1000),
		IsDecimal bit,
		ClassTeacherShortName nvarchar(50),--added by dhananjay for mantis - 37151
		SchoolStamp varbinary(max),  --Mantis - 38100
		ResultSheetAdditionalTitle nvarchar(100)  --Mantis - 43012
	
		
	)	
	 --print 'temp created'    	
	INSERT INTO  #TempAllExam 
	(
	AcademicIdText,
	ExamIdText,
	DivisionIdText,
	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,
	InchargeEmployeeName,
	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,
	TotalCount,
	PresentCount,
	Remark4,
	IsDecimal,
	ClassTeacherShortName, --added by dhananjay for mantis - 37151
	SchoolStamp,  --Mantis - 38100
	ResultSheetAdditionalTitle	--Mantis - 43012

	)
	SELECT 
		Convert(nvarchar(20),A.Id),
		Convert(nvarchar(20),@rExamId),
		Convert(nvarchar(50),@rDivisionId),
		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,
		--ISNULL(Emp.FirstName,'') +' ' + ISNULL(EMp.LastName,'') AS ClassTeacherName,
		[sAssessment].[fSubjectEmployeeGet](DM.Id,SM.Id) As ClassTeacherName,
		ISNULL(Emp.FirstName,'') +' ' + ISNULL(EMp.LastName,'') AS InchargeEmployeeName,
		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,
	    ISNULL(RDO.TotalCount,0) As TotalCount,
	    ISNULL(RDO.PresentCount,0) As PresentCount,
	    Isnull(RDO.Remark,'') As Remark4,
	    ---[sAssessment].[fSubjectEmployeeGet](DM.Id,SM.Id) As ClassTeacherName
	   	CONVERT(bit,@lDecimalConfig) AS IsDecimal,
		ISNULL(EMP.ShortName,'') as ClassTeacherShortName,
		OI.SchoolStamp AS SchoolStamp,
		ISNULL(EM.ResultSheetAdditionalTitle, '') AS ResultSheetAdditionalTitle		--Mantis - 43012
FROM 
	sAssessment.tResultDetail RD
	INNER JOIN sAssessment.tResult R ON R.Id = RD.ResultId
	INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId
	INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId		
	INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
	INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=CS.SubjectId	
	LEFT JOIN sSetup.tSubjectGroupMaster SG ON SG.Id = Sm.SubjectGroupId				 
	INNER JOIN sStudent.tAcademic A ON A.Id=R.AcademicId
	INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=A.OrgId
	LEFT JOIN sSetup.tOrgImages OI ON OI.Orgid = OM.Id
	INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId
	INNER JOIN sStudent.tStudentMaster StuM ON StuM.Id=A.StudentId
	INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId
	INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId
	LEFT JOIN sHrm.tEmployeeImages EI ON EI.EmployeeId = Dm.InchargeEmployeeId
	LEFT JOIN sHrm.tEmployeeMaster EMP ON EMP.Id = DM.InchargeEmployeeId
	INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id = EM.EXAMSUBGROUPID
	LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId=StuM.Id
	LEFT JOIN sStudent.tAcademicDetail AD ON AD.AcademicId=A.Id
	LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId=StuM.Id
	LEFT JOIN sAssessment.tStudentRemark SR ON R.AcademicId = SR.AcademicId AND R.ExamId = SR.ExamId
	LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId = StuM.Id
	LEFT JOIN sAssessment.tOptionalSubject OS ON OS.AcademicId = R.AcademicId AND OS.ClassSubjectId = ED.ClassSubjectId  AND ED.ExamId = R.ExamId
	LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId=A.StudentId
	LEFT JOIN 	sCommon.tBloodGroupMaster BGM ON BGM.Id=So.BloodGroupId
	LEFT JOIN sAssessment.tGradeSetDetail GS ON GS.GradeSetId=ED.GradeSetId AND ED.GradeSetId = @GradeSetId and RD.SubjectGrade = GS.GradeCode
	LEFT JOIN sAssessment.tResultAnalysisDivisionDetail RAD ON RAD.ClassSubjectId = CS.Id AND RAD.DivisionId = A.DivisionId AND RAD.ExamId = Em.Id
	LEFT JOIN sAssessment.tResultDetailOther RDO ON  RDO.ExamId = EM.Id AND R.Academicid =RDO.AcademicId AND ED.ClassSubjectId = RDO.ClassSubjectId
	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 sAcademic.tTeacherSubjectDivision TSD ON TSD.SubjectId=SM.Id AND TSD.DivisionId = A.DivisionId
	--LEFT JOIN sHrm.tEmployeeMaster EMP ON TSD.EmployeeId = EMP.Id
	
	 WHERE
		R.ExamId = @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.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
	--ON 
	
	-- Order By ExamOrder ASC
	--WHERE ExamId in (SELECT SUBEXAMID FROM sAssessment.tExamCombine WHERE ExamId  = @rExamId Order By ExamOrder ASC)
	
	DECLARE @lCount int,@query  AS NVARCHAR(MAX),@lSubExamId int,@lCount1 int
  
	Select @lCount = MAX(Id) from #tempcombineExam
	--SET @lCount1 = @lCount+1
	DECLARE @ExamTitle nvarchar(150)
	while (@lCount > 0)
	begin
		select @lSubExamId = ExamID from #tempcombineExam Where Id = @lCount
		--select @ExamTitle = Title from sAssessment.tExamMaster Where Id = @lSubExamId	
		set @query ='update T SET
					 MaximumMark' + convert(nvarchar(15),@lCount)+ '=ED.Maximum,
					 Obtain' + convert(nvarchar(15),@lCount)+'= ISNULL(RD.Obtain,0),
					 IsPresent' + convert(nvarchar(15),@lCount)+'=RD.IsPresent,	
					 				
					 SubjectGrade' + convert(nvarchar(15),@lCount)+ '=RD.SubjectGrade,
					 TotalDays'+convert(nvarchar(15),@lCount)+'=SR.TotalDays,
					 PresentDays'+convert(nvarchar(15),@lCount)+'=SR.PresentDays										
					 From
						sAssessment.tResultDetail RD
						INNER JOIN sAssessment.tResult R ON R.Id = RD.ResultId
						INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
						INNER JOIN sAssessment.tExamSubgroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId					
						INNER JOIN 	#TempAllExam  T ON T.ClassSubjectID = ED.ClassSubjectId And T.AcademicId = R.AcademicId	
						LEFT JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND T.AcademicId = SR.AcademicId 									
						WHERE EM.Id =' + convert(nvarchar(15), @lSubExamId)  
						
	
	 execute(@query)
	
						
			set @query ='update T set 
				    TotalMarks' + convert(nvarchar(15),@lCount)+ '=R.TotalMarks,
					TotalObtain' + convert(nvarchar(15),@lCount)+ '=R.TotalObtain,
					Percentage' + convert(nvarchar(15),@lCount)+ '=R.Percentage,
					RankNumber' + convert(nvarchar(15),@lCount)+'=R.RankNumber,
					ResultGrade' + convert(nvarchar(15),@lCount)+'=R.ResultGrade,
					Percentile' + convert(nvarchar(15),@lCount)+'=R.Percentile,
					ResultStatus' + convert(nvarchar(15),@lCount)+'=R.ResultStatus,
					Exam' + convert(nvarchar(15),@lCount)+ 'Name=ESGM.ExamSubGroupDisplayTitle,
					--Exam' + convert(nvarchar(15),@lCount)+ 'Code=ESGM.Code,
					ExamMaximum' + convert(nvarchar(15),@lCount)+'=ISNULL(EM.ExamMaximum,0)
					 From						
						sAssessment.tResult R						
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id=R.ExamId
						INNER JOIN sAssessment.tExamSubgroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId					
						INNER JOIN 	#TempAllExam  T ON  T.AcademicId = R.AcademicId						
						WHERE EM.Id =' + convert(nvarchar(15), @lSubExamId)  
						
		execute(@query)
		
		
	set @lCount = @lCount -1
	end
	

	IF (@IsIncludeSubExam = 1)
	BEGIN	
		select @lSubExamId = SubExamId from sAssessment.tExamCombine  Where ExamId  = @rExamId AND ExamOrder = 1
		--select @ExamTitle = Title from sAssessment.tExamMaster Where Id = @lSubExamId	
		
		
			set @query ='update T set					 
					SubjectGradeTerm1=RD.SubjectGrade,
					SubjectObtainTerm1 = RD.Obtain,
					 SubjectMaxTerm1 = ED.Maximum
							 
					 From
						 sAssessment.tResultDetail RD
						INNER JOIN  sAssessment.tResult R ON R.Id = RD.ResultId
						INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId
						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
					
					From
					 
						sAssessment.tResult  R 				
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id = R.ExamId
						LEFT JOIN sAssessment.tStudentRemark SR ON SR.AcademicId = R.AcademicId AND SR.ExamId = EM.Id
						INNER JOIN sAssessment.tExamSubgroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId					
						INNER JOIN 	#TempAllExam  T ON  T.AcademicId = R.AcademicId						
						WHERE EM.Id =' + convert(nvarchar(15), @lSubExamId)  
						
		 	
						
		execute(@query)
		
					select @lSubExamId = SubExamId from sAssessment.tExamCombine  Where ExamId  = @rExamId AND ExamOrder = 2
		--select @ExamTitle = Title from sAssessment.tExamMaster Where Id = @lSubExamId	
		set @query ='update T set					 
					SubjectGradeTerm2=RD.SubjectGrade,
					SubjectObtainTerm2 = RD.Obtain,
					SubjectMaxTerm2= ED.Maximum,
					AchievementsTerm2 = SR.Achievements,
					GeneralRemarkTerm2 = SR.GeneralRemark,
					ResultRemark1Term2 = SR.ResultRemark1,
					ResultRemark2Term2 = SR.ResultRemark2,
					SR_HeightTerm2 = SR.StudentHeight,
					SR_WeightTerm2 = SR.StudentWeight,
					SR_PresentDaysTerm2 = SR.PresentDays,
					SR_TotalDaysTerm2 = SR.TotalDays
									 
					 From
						sAssessment.tResultDetail RD
						INNER JOIN sAssessment.tResult R ON R.Id = RD.ResultId
						INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId
						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			
					 From						 
					   sAssessment.tResult R  				 
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id=R.ExamId
						INNER JOIN sAssessment.tExamSubgroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId					
						INNER JOIN 	#TempAllExam  T ON  T.AcademicId = R.AcademicId						
						WHERE EM.Id =' + convert(nvarchar(15), @lSubExamId)  
		execute(@query)
		
		select @lSubExamId = SubExamId from sAssessment.tExamCombine  Where ExamId  = @rExamId AND ExamOrder = 3
		set @query ='update T set					 
					SubjectGradeTerm3=RD.SubjectGrade,
					SubjectObtainTerm3 = RD.Obtain,
					SubjectMaxTerm3= ED.Maximum				 
					 From
						sAssessment.tResultDetail RD
						INNER JOIN sAssessment.tResult R ON R.Id = RD.ResultId
						INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
						INNER JOIN sAssessment.tExamSubgroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId					
						INNER JOIN 	#TempAllExam  T ON T.ClassSubjectID = ED.ClassSubjectId And T.AcademicId = R.AcademicId						
						WHERE EM.Id =' + convert(nvarchar(15), @lSubExamId)  
		execute(@query)
		set @query ='update T set
 
					TotalMarkTerm3 = R.TotalMarks,
					TotalObtainTerm3=R.TotalObtain,
					PercentageTerm3=R.Percentage,
					RankNumberTerm3=R.RankNumber,
					ResultGradeTerm3=R.ResultGrade,
					PercentileTerm3 = R.Percentile,
					ResultStatusTerm3 = R.ResultStatus,
					ExamNameTerm3 = ESGM.Code			
					 From						 
					   sAssessment.tResult R  				 
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id=R.ExamId
						INNER JOIN sAssessment.tExamSubgroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId					
						INNER JOIN 	#TempAllExam  T ON  T.AcademicId = R.AcademicId						
						WHERE EM.Id =' + convert(nvarchar(15), @lSubExamId)  
		execute(@query)
	END
	
	
	
	
	
	--WHILE (@lCount1 <= 6)
	--BEGIN
	--	set @query ='ALTER TABLE #TempAllExam DROP COLUMN MaximumMark' + convert(nvarchar(15),@lCount1)
	--	execute(@query)
	--	set @query ='ALTER TABLE #TempAllExam DROP COLUMN Exam' + convert(nvarchar(150),@lCount1)+ 'Name'
	--	execute(@query)
	--	set @query ='ALTER TABLE #TempAllExam DROP COLUMN SubjectGrade' + convert(nvarchar(150),@lCount1)
	--	execute(@query)		
	--	set @query ='ALTER TABLE #TempAllExam DROP COLUMN Obtain' + convert(nvarchar(15),@lCount1)
	--	execute(@query)
	--	set @query ='ALTER TABLE #TempAllExam DROP COLUMN ExamMaximum' + convert(nvarchar(15),@lCount1)
	--	execute(@query)
	--	SET @lCount1 = @lCount1 + 1
	--END
	
	SELECT @rBuilder1,@rBuilder2, T.*
	FROM #TempAllExam T
	
	--INNER JOIN SSETUP.TCLASSSUBJECT CS ON CS.ID = T.CLASSSUBJECTID
	--WHERE
	--	((T.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
	--	AND ((T.RollNo <= @rToRollNo) OR (@rToRollNo=0))
	--	AND ((T.RankNumber >= @rFromRank) OR (@rFromRank=0))
	--	AND ((T.RankNumber <= @rToRank) OR (@rToRank=0))
	--	AND ((T.ResultGrade = @rGrade) OR (@rGrade=''))
	--	AND ((T.StudCode=@rCode) OR (@rCode=''))		
		--order by T.RollNo,CS.ORDERINDEX
		
	drop table #tempcombineExam
	Drop table #TempAllExam
	END


--SELECT @rBuilder1,@rBuilder2, T.* FROM sAssessment.tTempAllExamResultSheet T
--end
GO
PRINT N'Altering Procedure [sAssessment].[pRptResultSheetStandardMultiExamWithAllTermGet]...';


GO


ALTER PROCEDURE [sAssessment].[pRptResultSheetStandardMultiExamWithAllTermGet]
	 
	 @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.tTempAllExamWithAllTerm
 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

--#TempAllExam
	CREATE TABLE #TempAllExam
	(
		AcademicIdText nvarchar(20),
		ExamIdText nvarchar(20),
		CoScholasticScopeIdText nvarchar(20),
		IsDisplayMonthlyAttendanceText nvarchar(20),
		ClassIdText nvarchar(50),
		AcademicId bigint,
		ExamName Nvarchar(150),
		StudCode NVarchar(20),
		StudentName Nvarchar(150),
		RollNo int,
		ResultStatus Nvarchar(20),	
		ClassName NVarchar(50),		
		Division NVarchar(50),
		TotalMark decimal(8,2),
		TotalObtain decimal(8,2),
		Percentage decimal(8,2),
		RankNumber int,
		ResultGrade NVarchar(50),
		
		MaximumMark1 decimal(8,2),		
		SubjectGrade1 NVarchar(50),
		Obtain1 decimal(8,2) Default 0,
		ExamMaximum1 decimal(8,2),
		IsPresent1 bit,
						
		MaximumMark2 decimal(8,2),	
		SubjectGrade2 NVarchar(50),
		Obtain2 decimal(8,2) Default 0,
		ExamMaximum2 decimal(8,2),
		IsPresent2 bit,
				
		MaximumMark3 decimal(8,2),
		SubjectGrade3 NVarchar(50),
		Obtain3 decimal(8,2) Default 0,
		ExamMaximum3 decimal(8,2),
		IsPresent3 bit,		
		
		MaximumMark4 decimal(8,2),	
		SubjectGrade4 NVarchar(50),
		Obtain4 decimal(8,2) Default 0,
		ExamMaximum4 decimal(8,2),
		IsPresent4 bit,	
				
		MaximumMark5 decimal(8,2),		
		SubjectGrade5 NVarchar(50),
		Obtain5 decimal(8,2) Default 0,
		ExamMaximum5 decimal(8,2),
		IsPresent5 bit,	
				
		MaximumMark6 decimal(8,2),		
		SubjectGrade6 NVarchar(50),
		Obtain6 decimal(8,2) Default 0,
		ExamMaximum6 decimal(8,2),
		IsPresent6 bit,	
		
		MaximumMark7 decimal(8,2),		
		SubjectGrade7 NVarchar(50),
		Obtain7 decimal(8,2) Default 0,
		ExamMaximum7 decimal(8,2),
		IsPresent7 bit,	
		
		MaximumMark8 decimal(8,2),	
		SubjectGrade8 NVarchar(50),
		Obtain8 decimal(8,2) Default 0,
		ExamMaximum8 decimal(8,2),
		IsPresent8 bit,	
		
		MaximumMark9 decimal(8,2),		
		SubjectGrade9 NVarchar(50),
		Obtain9 decimal(8,2) Default 0,
		ExamMaximum9 decimal(8,2),
		IsPresent9 bit,	
		
		
		MaximumMark10 decimal(8,2),		
		SubjectGrade10 NVarchar(50),
		Obtain10 decimal(8,2) Default 0,
		ExamMaximum10 decimal(8,2),
		IsPresent10 bit,	
		
		MaximumMark11 decimal(8,2),		
		SubjectGrade11 NVarchar(50),
		Obtain11 decimal(8,2) Default 0,
		ExamMaximum11 decimal(8,2),
		IsPresent11 bit,
		
		MaximumMark12 decimal(8,2),		
		SubjectGrade12 NVarchar(50),
		Obtain12 decimal(8,2) Default 0,
		ExamMaximum12 decimal(8,2),
		IsPresent12 bit,
		
		MaximumMark13 decimal(8,2),		
		SubjectGrade13 NVarchar(50),
		Obtain13 decimal(8,2) Default 0,
		ExamMaximum13 decimal(8,2),
		IsPresent13 bit,		
		 
		 
		SubjectGradeTerm1 NVarchar(50),
		SubjectGradeTerm2 NVarchar(50),
		SubjectGradeTerm3 NVarchar(50),
		SubjectGradeTerm4 NVarchar(50),
		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(1000),
		Remark3 nvarchar(1000),
		DisplayTitle nvarchar(150),		
		IsRankNo bit, 
		IsGrade bit,
		IsPercentile bit,
		IsPercentage bit,
		IsSubjectPercentile bit,
		IsProcessResult bit,
		IsNegativeMarks bit,
		IsIncludeCoScholastic bit,
		IsOnPrePrinted bit,
		IsDisplayPhoto bit,
		IsDisplayBirthDate bit,
		IsLockForEdit bit,
		IsDisplaySchoolName bit,			
		IsDisplayAttendance bit,
		IsDisplayHeightWeight bit,
		IsResultStatus bit,
		FooterAdjustmentText nvarchar(max),
		DetailAdjustmentText nvarchar(max),
		FooterAdjustment smallint,
		DetailAdjustment smallint,
		ResultRemark nvarchar(200),
		DateOfBirth date,
		HeightTerm1 decimal(5,2),
		WeightTerm1 decimal(5,2),
		HeightTerm2 decimal(5,2),
		WeightTerm2 decimal(5,2),
		HeightAnnual decimal(5,2),
		WeightAnnual decimal(5,2),
		PresentDaysTerm1 smallint,
		PresentDaysTerm2 smallint,
		PresentDaysAnnual smallint,
		TotalDaysTerm1 smallint,
		TotalDaysTerm2 smallint,
		TotalDaysAnnual smallint,
		TotalMarkTerm1 decimal(8,2),
		TotalObtainTerm1 decimal(8,2),
		PercentageTerm1 decimal(8,2),
		RankNumberTerm1 int,
		ResultGradeTerm1 NVarchar(50),
		PercentileTerm1 decimal(8,2),
		ResultStatusTerm1 Nvarchar(20),		   
		TotalMarkTerm2 decimal(8,2),
		TotalObtainTerm2 decimal(8,2),
		PercentageTerm2 decimal(8,2),
		RankNumberTerm2 int,
		ResultGradeTerm2 NVarchar(50),
		PercentileTerm2 decimal(8,2),
		ResultStatusTerm2 Nvarchar(20), 
		TotalMarkTerm3 		decimal(8,2),
		TotalObtainTerm3 decimal(8,2),
		PercentageTerm3 decimal(8,2),
		RankNumberTerm3 int,
		ResultGradeTerm3 NVarchar(50),
		PercentileTerm3 decimal(8,2),
		ResultStatusTerm3 Nvarchar(20), 

		TotalMarkTerm4	decimal(8,2),
		TotalObtainTerm4 decimal(8,2),
		PercentageTerm4 decimal(8,2),
		RankNumberTerm4 int,
		ResultGradeTerm4 NVarchar(50),
		PercentileTerm4 decimal(8,2),
		ResultStatusTerm4 Nvarchar(20), 
		
		TermScopeId tinyint,		 
		StudentPhoto varbinary(max),
		GradeString nvarchar(1000),
		IsDisplayGradeString bit,		 
		IsDisplayInMarksheet bit,
		IsShowSubjectGrade bit,
		IsIncludeInTotal bit,
		ClassSubjectID int,
		SubjectId int,
		--Maximum decimal(5,2),
		SubjectOrderIndex smallint,
		SubjectGrade NVarchar(50),
		SubjectName NVarchar(150),
		SubjectCode Nvarchar(50),	
		SubjectMinimum decimal(8,2),		
		SubjectMaximum decimal(8,2),
		SubjectObtain  decimal(8,2),
		
		Exam1Name Nvarchar(150),		
		TotalMarks1 decimal(8,2),		
		TotalObtain1 decimal(8,2),
		Percentage1 decimal(8,2),
		RankNumber1 int,
		ResultGrade1 NVarchar(50),
		Percentile1 decimal(8,2),
		ResultStatus1 Nvarchar(20),
		Exam1CombineExamName Nvarchar(150),
				
		Exam2Name nvarchar(150),	
		TotalMarks2 decimal(8,2),
		TotalObtain2 decimal(8,2),
		Percentage2 decimal(8,2),
		RankNumber2 int,
		ResultGrade2 NVarchar(50),
		Percentile2 decimal(8,2),
		ResultStatus2 Nvarchar(20),
		Exam2CombineExamName Nvarchar(150),
		
		Exam3Name nvarchar(150),	
		TotalMarks3 decimal(8,2),
		TotalObtain3 decimal(8,2),
		Percentage3 decimal(8,2),
		RankNumber3 int,
		ResultGrade3 NVarchar(50),
		Percentile3 decimal(8,2),		
		ResultStatus3 Nvarchar(20),
		Exam3CombineExamName Nvarchar(150),
		
		Exam4Name nvarchar(150),	
		TotalMarks4 decimal(8,2),
		TotalObtain4 decimal(8,2),
		Percentage4 decimal(8,2),
		RankNumber4 int,
		ResultGrade4 NVarchar(50),
		Percentile4 decimal(8,2),
		ResultStatus4 Nvarchar(20),
		Exam4CombineExamName Nvarchar(150),
		
		Exam5Name nvarchar(150),		
		TotalMarks5 decimal(8,2),
		TotalObtain5 decimal(8,2),
		Percentage5 decimal(8,2),
		RankNumber5 int,
		ResultGrade5 NVarchar(50),
		Percentile5 decimal(8,2),
		ResultStatus5 Nvarchar(20),
		Exam5CombineExamName Nvarchar(150),
		
		Exam6Name nvarchar(150),	
		TotalMarks6 decimal(8,2),
		TotalObtain6 decimal(8,2),
		Percentage6 decimal(8,2),
		RankNumber6 int,
		ResultGrade6 NVarchar(50),
		Percentile6 decimal(8,2),
		ResultStatus6 Nvarchar(20),
		Exam6CombineExamName Nvarchar(150),
		
		Exam7Name nvarchar(150),		
		TotalMarks7 decimal(8,2),
		TotalObtain7 decimal(8,2),
		Percentage7 decimal(8,2),
		RankNumber7 int,
		ResultGrade7 NVarchar(50),
		Percentile7 decimal(8,2),
		ResultStatus7 Nvarchar(20),
		Exam7CombineExamName Nvarchar(150),
		
		Exam8Name nvarchar(150),
		TotalMarks8 decimal(8,2),
		TotalObtain8 decimal(8,2),
		Percentage8 decimal(8,2),
		RankNumber8 int,
		ResultGrade8 NVarchar(50),
		Percentile8 decimal(8,2),
		ResultStatus8 Nvarchar(20),
		Exam8CombineExamName Nvarchar(150),
		
		
		Exam9Name nvarchar(150),	
		TotalMarks9 decimal(8,2),
		TotalObtain9 decimal(8,2),
		Percentage9 decimal(8,2),
		RankNumber9 int,
		ResultGrade9 NVarchar(50),
		Percentile9 decimal(8,2),
		ResultStatus9 Nvarchar(20),
		Exam9CombineExamName Nvarchar(150),
		
		Exam10Name nvarchar(150),	
		TotalMarks10 decimal(8,2),
		TotalObtain10 decimal(8,2),
		Percentage10 decimal(8,2),
		RankNumber10 int,
		ResultGrade10 NVarchar(50),
		Percentile10 decimal(8,2),
		ResultStatus10 Nvarchar(20),
		Exam10CombineExamName Nvarchar(150),
		
		Exam11Name nvarchar(150),	
		TotalMarks11 decimal(8,2),
		TotalObtain11 decimal(8,2),
		Percentage11 decimal(8,2),
		RankNumber11 int,
		ResultGrade11 NVarchar(50),
		Percentile11 decimal(8,2),
		ResultStatus11 Nvarchar(20),
		Exam11CombineExamName Nvarchar(150),
		
		Exam12Name nvarchar(150),	
		TotalMarks12 decimal(8,2),
		TotalObtain12 decimal(8,2),
		Percentage12 decimal(8,2),
		RankNumber12 int,
		ResultGrade12 NVarchar(50),
		Percentile12 decimal(8,2),
		ResultStatus12 Nvarchar(20),
		Exam12CombineExamName Nvarchar(150),

		Exam13Name nvarchar(150),	
		TotalMarks13 decimal(8,2),
		TotalObtain13 decimal(8,2),
		Percentage13 decimal(8,2),
		RankNumber13 int,
		ResultGrade13 NVarchar(50),
		Percentile13 decimal(8,2),
		ResultStatus13 Nvarchar(20),
		Exam13CombineExamName Nvarchar(150),
		
		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),
		ExamNameTerm4 NVarchar(100),
		ClassTeacherName Nvarchar(100),
		FirstName nvarchar(50),
		LastName nvarchar(50),
		IsDisplayMonthlyAttendance bit,
		MarksheetHeaderA4 varbinary(max),
		IsImageHeader bit,
		MyGoal nvarchar(200),
		AreaOfInterest nvarchar(200),
		Responsibility nvarchar(200),
		MyInterestHobby nvarchar(200),
		MyStrength nvarchar(200),
		Achievements nvarchar(1000),
		
		DentalHygiene nvarchar(200),
		VisionLeft nvarchar(50),
		VisionRight nvarchar(50), 
		IsDetail bit,
		SubjectGroupId int,
		SubjectGroupTitle nvarchar(50),
		SubjectGroupCode nvarchar(50),
		DecimalFormat nvarchar(10),
		SubjectRemark nvarchar(1000),
		GraceMark decimal(5,2),
		KrupaMark decimal(5,2),
		GradeStringHtml nvarchar(500),
		ResultRemark3 nvarchar(200),
		IsDisplayTotalMark bit,
		SubjectObtainTerm1 decimal(8,2),	
		SubjectObtainTerm2 decimal(8,2),
		SubjectObtainTerm3  decimal(8,2),
		SubjectObtainTerm4  decimal(8,2),
		SubjectMaxTerm1 decimal(8,2),
		SubjectMaxTerm2 decimal(8,2),
		SubjectMaxTerm3 decimal(8,2),
		SubjectMaxTerm4 decimal(8,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(100),
		TotalDays1 decimal(6,2),
		PresentDays1 decimal(6,2),
		TotalDays2 decimal(6,2),
		PresentDays2 decimal(6,2),
		TotalDays3 decimal(6,2),
		PresentDays3 decimal(6,2),
		TotalDays4 decimal(6,2),
		PresentDays4 decimal(6,2),
		TotalDays5 decimal(6,2),
		PresentDays5 decimal(6,2),
		TotalDays6 decimal(6,2),
		PresentDays6 decimal(6,2),
		TotalDays7 decimal(6,2),
		PresentDays7 decimal(6,2), 
		TotalDays8 decimal(6,2),
		PresentDays8 decimal(6,2),
		TotalDays9 decimal(6,2),
		PresentDays9 decimal(6,2),
		TotalDays10 decimal(6,2),
		PresentDays10 decimal(6,2),
		TotalDays11 decimal(6,2),
		PresentDays11 decimal(6,2),
		TotalDays12 decimal(6,2),
		PresentDays12 decimal(6,2),
		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(200),
		GeneralRemarkTerm2 nvarchar(200),
		ResultRemark1Term1 nvarchar(200),
		ResultRemark2Term1 nvarchar(200),
		ResultRemark1Term2 nvarchar(200),
		ResultRemark2Term2 nvarchar(200),
		SR_HeightTerm1 decimal(5,2),
		SR_WeightTerm1 decimal(5,2),
		SR_HeightTerm2 decimal(5,2),
		SR_WeightTerm2 decimal(5,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(100),
		UIdNumber nvarchar(100),
		FatherContactNo nvarchar(50),
		MotherContactNo nvarchar(50),
		FatherMail nvarchar(max),
		MotherMail nvarchar(max),
		Gender nvarchar(100),
		CoordinatorEmployeeSign varbinary(max),
		StudentAddress nvarchar(max),
		SUId nvarchar(50),
		HighestDivisionMark decimal(5, 2),
		HighestDivisionGrade nvarchar(50),
		StreamTitle nvarchar(50),
		AdmissionNo nvarchar(50),
		AdmissionDate Date,
		MiddleName nvarchar(50) ,
		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),
		ExamMaximumTerm4 decimal(6,2),
		--Added by dhananjay mantis : 43188
		ResultIndicator nvarchar(50),
		IsDisplayResultIndicator bit
		--Added by dhananjay mantis : 43188

		)	
	 --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,
	--Added by dhananjay mantis : 43188
	ResultIndicator,
	IsDisplayResultIndicator 
	--Added by dhananjay mantis : 43188
	)
	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,
		--Added by dhananjay mantis : 43188
		ISNULL(R.ResultIndicator,'') AS ResultIndicator,
		EM.IsDisplayResultIndicator 
		--Added by dhananjay mantis : 43188
				
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
	
	 WHERE
		R.ExamId = @rExamId 
		AND ((A.DivisionId =  @rDivisionId) OR (@rDivisionId=0))
		AND ((A.ClassId =  @rClassId) OR (@rClassId=0))		 
		AND ((A.BatchId =  @rBatchId) OR (@rBatchId=0))
		AND ((A.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
		AND ((A.RollNo <= @rToRollNo) OR (@rToRollNo=0))
		AND ((R.RankNumber >= @rFromRank) OR (@rFromRank=0))
		AND ((R.RankNumber <= @rToRank) OR (@rToRank=0))
		AND ((R.ResultGrade = @rGrade) OR (@rGrade=''))
		AND ((StuM.Code=@rCode) OR (@rCode=''))	
		AND ((R.Id = @rResultId) OR (@rResultId = 0))	
		AND ((StuM.StatusId=@rStatusId)OR(@rStatusId=0))
		AND((A.Id=@rAcademicId)OR (@rAcademicId=0))
		AND ((CS.SubjectId=@rSubjectId) OR(@rSubjectId=0) ) 
		AND ((R.TotalObtain>=@rFromObtain) OR (@rFromObtain=0))
		AND ((R.TotalObtain<=@rToObtain) OR (@rToObtain=0))
		AND ((R.Percentage>=@rFromPercentage) OR (@rFromPercentage=0))
		AND ((R.Percentage<=@rToPercentage) OR (@rToPercentage=0))
		
		 AND (
	 (@rFilterId = 0) -- All
     OR (@rFilterId = 2 AND isnull(AR.SourceId,0)!=0) -- Hostel
     OR (@rFilterId = 3 AND isnull(RT.SourceId,0)!=0) -- Transport
     OR ((@rFilterId =1) AND ((isnull(AR.SourceId,0)=0) AND (isnull(RT.SourceId,0)=0)))
    )
	AND ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0)) 
	AND (ISNULL(StuM.Code,0) IN( SELECT cast(item as nvarchar(20)) FROM  sCommon.fnsplit(@rMultiCode,',')) OR @rMultiCode='')
	    
	Order By ED.DisplayOrder

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

	IF (@IsIncludeSubExam = 0)
	BEGIN	
	INSERT INTO #tempcombineExam (ExamID) 
	SELECT SUBEXAMID FROM sAssessment.tExamCombine WHERE ExamId  = @rExamId Order By ExamOrder ASC
 	END
 	ELSE
 	BEGIN
 	-- if we want to display result for both the term with all exam select this option
 	INSERT INTO #tempcombineExam (ExamID) 
	SELECT C.SUBEXAMID FROM sAssessment.tExamCombine C
	INNER JOIN (SELECT SUBEXAMID,ExamOrder FROM sAssessment.tExamCombine WHERE ExamId  = @rExamId) E
	ON C.ExamId = E.SubExamId
	ORDER BY E.ExamOrder,C.ExamOrder
	END
	--print ('tempcombine')
	--SELECT * FROM #tempcombineExam
	--ON 
	
	-- Order By ExamOrder ASC
	--WHERE ExamId in (SELECT SUBEXAMID FROM sAssessment.tExamCombine WHERE ExamId  = @rExamId Order By ExamOrder ASC)
	
	DECLARE @lCount int,@query  AS NVARCHAR(MAX),@lSubExamId int,@lCount1 int
  
	Select @lCount = MAX(Id) from #tempcombineExam
	--SET @lCount1 = @lCount+1
	DECLARE @ExamTitle nvarchar(150)
	while (@lCount > 0)
	begin
		select @lSubExamId = ExamID from #tempcombineExam Where Id = @lCount
		--select @ExamTitle = Title from sAssessment.tExamMaster Where Id = @lSubExamId	
		set @query ='update T SET
					 MaximumMark' + convert(nvarchar(15),@lCount)+ '=ED.Maximum,
					 Obtain' + convert(nvarchar(15),@lCount)+'= ISNULL(RD.Obtain,0),
					 IsPresent' + convert(nvarchar(15),@lCount)+'=RD.IsPresent,	
					 AbsentRemark' + convert(nvarchar(15),@lCount)+'= ISNULL(RD.AbsentRemark,' + CHAR(39)+CHAR(39) + '),
					 		
					 SubjectGrade' + convert(nvarchar(15),@lCount)+ '=RD.SubjectGrade,
					 TotalDays'+convert(nvarchar(15),@lCount)+'=SR.TotalDays,
					 PresentDays'+convert(nvarchar(15),@lCount)+'=SR.PresentDays										
					 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	
						LEFT JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND T.AcademicId = SR.AcademicId 									
						WHERE EM.Id =' + convert(nvarchar(15), @lSubExamId)  
						
--print(@query)
	 execute(@query)
	
						
			set @query ='update T set 
				    TotalMarks' + convert(nvarchar(15),@lCount)+ '=R.TotalMarks,
					TotalObtain' + convert(nvarchar(15),@lCount)+ '=R.TotalObtain,
					Percentage' + convert(nvarchar(15),@lCount)+ '=R.Percentage,
					RankNumber' + convert(nvarchar(15),@lCount)+'=R.RankNumber,
					ResultGrade' + convert(nvarchar(15),@lCount)+'=R.ResultGrade,
					Percentile' + convert(nvarchar(15),@lCount)+'=R.Percentile,
					ResultStatus' + convert(nvarchar(15),@lCount)+'=R.ResultStatus,
					Exam' + convert(nvarchar(15),@lCount)+ 'Name=ESGM.ExamSubGroupDisplayTitle,
					Exam' + convert(nvarchar(15),@lCount)+ 'Code=ESGM.Code,
					ExamMaximum' + convert(nvarchar(15),@lCount)+'=ISNULL(EM.ExamMaximum,0)
					 From						
						sAssessment.tResult R						
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id=R.ExamId
						INNER JOIN sAssessment.tExamSubgroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId					
						INNER JOIN 	#TempAllExam  T ON  T.AcademicId = R.AcademicId						
						WHERE EM.Id =' + convert(nvarchar(15), @lSubExamId)  
						
		execute(@query)
		
		Declare @lCombineExamId int
			SELECT @lCombineExamId = EC.ExamId  FROM [sAssessment].[tExamMaster] EM 
										INNER JOIN SASSESSMENT.TEXAMSUBGROUPmASTER ESGM ON ESGM.ID = EM.ExamSubGroupId  
										INNER JOIN sAssessment.tExamCombine EC ON EC.SubExamId=EM.Id AND EC.ExamId in (SELECT SubExamId  FROM sAssessment.tExamCombine WHERE examid=@rExamId) 
										WHERE   (EM.ClassId=@rClassId) AND EM.BatchId =@rBatchId AND EM.Id = @lSubExamId
			--SELECT @lSubCombineExamName
		set @query ='update T set 
					 Exam' + convert(nvarchar(15),@lCount)+ 'CombineExamName =  EM.DisplayTitle
					  From						
						sAssessment.tResult R						
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id=R.ExamId
						INNER JOIN sAssessment.tExamSubgroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId					
						INNER JOIN 	#TempAllExam  T ON  T.AcademicId = R.AcademicId						
						WHERE EM.Id =' + convert(nvarchar(15), @lCombineExamId) 
				
				--Print @query		
		execute(@query)
		
	set @lCount = @lCount -1
	end
	

	IF (@IsIncludeSubExam = 1)
	BEGIN	
		select @lSubExamId = SubExamId from sAssessment.tExamCombine  Where ExamId  = @rExamId AND ExamOrder = 1
		--select @ExamTitle = Title from sAssessment.tExamMaster Where Id = @lSubExamId	
		
		
			set @query ='update T set					 
					SubjectGradeTerm1=RD.SubjectGrade,
					SubjectObtainTerm1 = RD.Obtain,
					 SubjectMaxTerm1 = ED.Maximum
							 
					 From
						 sAssessment.tResultDetail RD
						INNER JOIN  sAssessment.tResult R ON R.Id = RD.ResultId
						INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId AND R.ExamId = ED.ExamId
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
						INNER JOIN sAssessment.tExamSubgroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId					
						INNER JOIN 	#TempAllExam  T ON T.ClassSubjectID = ED.ClassSubjectId And T.AcademicId = R.AcademicId						
						WHERE EM.Id =' + convert(nvarchar(15), @lSubExamId)  
		
				execute(@query)
				
		set @query ='update T set					 
					 
					TotalMarkTerm1 = R.TotalMarks,
					TotalObtainTerm1=R.TotalObtain,
					PercentageTerm1=R.Percentage,
					RankNumberTerm1=R.RankNumber,
					ResultGradeTerm1=R.ResultGrade,
					PercentileTerm1 = R.Percentile,
					ResultStatusTerm1 = R.ResultStatus,
					ExamNameTerm1 = ESGM.Code,
					AchievementsTerm1 = SR.Achievements,
					GeneralRemarkTerm1 = SR.GeneralRemark,
					ResultRemark1Term1 = SR.ResultRemark1,
					ResultRemark2Term1 = SR.ResultRemark2,
					SR_HeightTerm1 = SR.StudentHeight,
					SR_WeightTerm1 = SR.StudentWeight,
					SR_PresentDaysTerm1 = SR.PresentDays,
					SR_TotalDaysTerm1 = SR.TotalDays,
					ExamMaximumTerm1 = EM.ExamMaximum
					
					From
					 
						sAssessment.tResult  R 				
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id = R.ExamId
						LEFT JOIN sAssessment.tStudentRemark SR ON SR.AcademicId = R.AcademicId AND SR.ExamId = EM.Id
						INNER JOIN sAssessment.tExamSubgroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId					
						INNER JOIN 	#TempAllExam  T ON  T.AcademicId = R.AcademicId						
						WHERE EM.Id =' + convert(nvarchar(15), @lSubExamId)  
						
		 	
						
		execute(@query)
		
		select @lSubExamId = SubExamId from sAssessment.tExamCombine  Where ExamId  = @rExamId AND ExamOrder = 2
		--select @ExamTitle = Title from sAssessment.tExamMaster Where Id = @lSubExamId	
		set @query ='update T set					 
					SubjectGradeTerm2=RD.SubjectGrade,
					SubjectObtainTerm2 = RD.Obtain,
					SubjectMaxTerm2= ED.Maximum,
					AchievementsTerm2 = SR.Achievements,
					GeneralRemarkTerm2 = SR.GeneralRemark,
					ResultRemark1Term2 = SR.ResultRemark1,
					ResultRemark2Term2 = SR.ResultRemark2,
					SR_HeightTerm2 = SR.StudentHeight,
					SR_WeightTerm2 = SR.StudentWeight,
					SR_PresentDaysTerm2 = SR.PresentDays,
					SR_TotalDaysTerm2 = SR.TotalDays
									 
					 From
						sAssessment.tResultDetail RD
						INNER JOIN sAssessment.tResult R ON R.Id = RD.ResultId
						INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId AND R.ExamId = ED.ExamId
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
						LEFT JOIN sAssessment.tStudentRemark SR ON SR.AcademicId = R.AcademicId AND SR.ExamId = EM.Id
						INNER JOIN sAssessment.tExamSubgroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId					
						INNER JOIN 	#TempAllExam  T ON T.ClassSubjectID = ED.ClassSubjectId And T.AcademicId = R.AcademicId						
						WHERE EM.Id =' + convert(nvarchar(15), @lSubExamId)  
		execute(@query)
		
		
				set @query ='update T set
 
					TotalMarkTerm2 = R.TotalMarks,
					TotalObtainTerm2=R.TotalObtain,
					PercentageTerm2=R.Percentage,
					RankNumberTerm2=R.RankNumber,
					ResultGradeTerm2=R.ResultGrade,
					PercentileTerm2 = R.Percentile,
					ResultStatusTerm2 = R.ResultStatus,
					ExamNameTerm2 = ESGM.Code,
					ExamMaximumTerm2 = EM.ExamMaximum			
					 From						 
					   sAssessment.tResult R  				 
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id=R.ExamId
						INNER JOIN sAssessment.tExamSubgroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId					
						INNER JOIN 	#TempAllExam  T ON  T.AcademicId = R.AcademicId						
						WHERE EM.Id =' + convert(nvarchar(15), @lSubExamId)  
		execute(@query)
		
		select @lSubExamId = SubExamId from sAssessment.tExamCombine  Where ExamId  = @rExamId AND ExamOrder = 3
		set @query ='update T set					 
					SubjectGradeTerm3=RD.SubjectGrade,
					SubjectObtainTerm3 = RD.Obtain,
					SubjectMaxTerm3= ED.Maximum				 
					 From
						sAssessment.tResultDetail RD
						INNER JOIN sAssessment.tResult R ON R.Id = RD.ResultId
						INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId AND R.ExamId = ED.ExamId
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
						INNER JOIN sAssessment.tExamSubgroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId					
						INNER JOIN 	#TempAllExam  T ON T.ClassSubjectID = ED.ClassSubjectId And T.AcademicId = R.AcademicId						
						WHERE EM.Id =' + convert(nvarchar(15), @lSubExamId)  
		execute(@query)
		set @query ='update T set
 
					TotalMarkTerm3 = R.TotalMarks,
					TotalObtainTerm3=R.TotalObtain,
					PercentageTerm3=R.Percentage,
					RankNumberTerm3=R.RankNumber,
					ResultGradeTerm3=R.ResultGrade,
					PercentileTerm3 = R.Percentile,
					ResultStatusTerm3 = R.ResultStatus,
					ExamNameTerm3 = ESGM.Code,
					ExamMaximumTerm3 = EM.ExamMaximum			
					 From						 
					   sAssessment.tResult R  				 
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id=R.ExamId
						INNER JOIN sAssessment.tExamSubgroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId					
						INNER JOIN 	#TempAllExam  T ON  T.AcademicId = R.AcademicId						
						WHERE EM.Id =' + convert(nvarchar(15), @lSubExamId)  
		execute(@query)

		--for 4 Term
		select @lSubExamId = SubExamId from sAssessment.tExamCombine  Where ExamId  = @rExamId AND ExamOrder = 4
		--select @ExamTitle = Title from sAssessment.tExamMaster Where Id = @lSubExamId	
		set @query ='update T set					 
					SubjectGradeTerm4=RD.SubjectGrade,
					SubjectObtainTerm4 = RD.Obtain,
					SubjectMaxTerm4= ED.Maximum
									 
					From
					sAssessment.tResultDetail RD
					INNER JOIN sAssessment.tResult R ON R.Id = RD.ResultId
					INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId AND R.ExamId = ED.ExamId
					INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
					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
 
					TotalMarkTerm4 = R.TotalMarks,
					TotalObtainTerm4 =R.TotalObtain,
					PercentageTerm4 =R.Percentage,
					RankNumberTerm4 =R.RankNumber,
					ResultGradeTerm4 =R.ResultGrade,
					PercentileTerm4  = R.Percentile,
					ResultStatusTerm4  = R.ResultStatus,
					ExamNameTerm4 = ESGM.Code,
					ExamMaximumTerm4 = 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,
 --			'' AS ResultIndicator AS ResultIndicator,
 --		    0 AS IsDisplayResultIndicator 

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


GO

ALTER PROCEDURE [sAssessment].[pRptResultSheetSubjectAcivityMultiExamGet]
	 
	 @rBuilder1 nvarchar(max)='',
	 @rSubjectId int = 0,
	 @rBatchId int=0,
	 @rClass 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,
	 @rOrgId int=0,
	 @rMultiCode nvarchar(max)=''

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
 begin
 	

 --Select * from   sAssessment.tTempAllExamSubjectActivity
DECLARE @GradeString nvarchar(1000)
DECLARE @GradeStringRemark nvarchar(1000),
@GradeSetId int , @IsIncludeSubExam bit
SELECT @GradeSetId = GradesetId,
	   @IsIncludeSubExam = ISNULL(IsIncludeSubExam,0)  FROM sAssessment.tExamMaster WHERE Id = @rExamId
SELECT @GradeString = [sAssessment].[fGradeStringGet](@GradeSetId)
SELECT @GradeStringRemark = GradeStringText from sAssessment.tGradeSetMaster Where Id =@GradeSetId

Declare @lDecimalConfig nvarchar(20)=''
SELECT @lDecimalConfig =ItemValue From sConfig.tConfigurationSetup WHERE ConfigurationId = 496 AND SourceTypeId = 1016 AND SourceId = @rOrgId
 
--#TempAllExam
	CREATE TABLE #TempAllExam
	(
		AcademicIdText nvarchar(20),
		ExamIdText nvarchar(20),
		CoScholasticScopeIdText nvarchar(20),
		
		AcademicId bigint,
		ExamName Nvarchar(150),
		StudCode NVarchar(20),
		StudentName Nvarchar(150),
		RollNo int,
		
		ResultStatus Nvarchar(50),	
		
		ClassName NVarchar(100),
				
		Division NVarchar(100),
		TotalMark decimal(8,2),
		TotalObtain decimal(8,2),
		Percentage decimal(8,2),
		RankNumber int,
		ResultGrade NVarchar(50),
		
		--MaximumMark1 decimal(8,2),		
		SubjectGrade1 NVarchar(50),
		--Obtain1 decimal(8,2),
		--ExamMaximum1 decimal(8,2),
		IsPresent1 bit,
						
		MaximumMark2 decimal(8,2),	
		SubjectGrade2 NVarchar(50),
		Obtain2 decimal(8,2),
		ExamMaximum2 decimal(8,2),
		IsPresent2 bit,
				
		MaximumMark3 decimal(8,2),
		SubjectGrade3 NVarchar(50),
		Obtain3 decimal(8,2),
		ExamMaximum3 decimal(8,2),
		IsPresent3 bit,		
		
		MaximumMark4 decimal(8,2),	
		SubjectGrade4 NVarchar(50),
		Obtain4 decimal(8,2),
		ExamMaximum4 decimal(8,2),
		IsPresent4 bit,	
				
		MaximumMark5 decimal(8,2),		
		SubjectGrade5 NVarchar(50),
		Obtain5 decimal(8,2),
		ExamMaximum5 decimal(8,2),
		IsPresent5 bit,	
				
		MaximumMark6 decimal(8,2),		
		SubjectGrade6 NVarchar(50),
		Obtain6 decimal(8,2),
		ExamMaximum6 decimal(8,2),
		IsPresent6 bit,	
		
		MaximumMark7 decimal(8,2),		
		SubjectGrade7 NVarchar(50),
		Obtain7 decimal(8,2),
		ExamMaximum7 decimal(8,2),
		IsPresent7 bit,	
		
		MaximumMark8 decimal(8,2),	
		SubjectGrade8 NVarchar(50),
		Obtain8 decimal(8,2),
		ExamMaximum8 decimal(8,2),
		IsPresent8 bit,	

		SubjectGrade9 NVarchar(50),
		IsPresent9 bit,

		SubjectGrade10 NVarchar(50),
		IsPresent10 bit,

		SubjectGrade11 NVarchar(50),
		IsPresent11 bit,

		SubjectGrade12 NVarchar(50),
		IsPresent12 bit,

		SubjectGrade13 NVarchar(50),
		IsPresent13 bit,
		
		SubjectGradeTerm1 NVarchar(50),
		SubjectGradeTerm2 NVarchar(50),
		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(8,2),
		RankNumberTerm1 int,
		ResultGradeTerm1 NVarchar(50),
		PercentileTerm1 decimal(8,2),
		ResultStatusTerm1 Nvarchar(20),		   
		TotalMarkTerm2 decimal(8,2),
		TotalObtainTerm2 decimal(8,2),
		PercentageTerm2 decimal(8,2),
		RankNumberTerm2 int,
		ResultGradeTerm2 NVarchar(50),
		PercentileTerm2 decimal(8,2),
		ResultStatusTerm2 Nvarchar(20), 
		TermScopeId tinyint,		 
		StudentPhoto varbinary(max),
		GradeString nvarchar(1000),
		IsDisplayGradeString bit,		 
		IsDisplayInMarksheet bit,
		IsShowSubjectGrade bit,
		IsIncludeInTotal bit,
		ClassSubjectID int,
		SubjectId int,
		--Maximum decimal(5,2),
		SubjectOrderIndex smallint,
		SubjectGrade NVarchar(50),
		SubjectName NVarchar(150),
		SubjectCode Nvarchar(50),	
		SubjectMinimum decimal(8,2),		
		SubjectMaximum decimal(8,2),
		SubjectObtain  decimal(8,2),
		
		Exam1Name Nvarchar(150),		
		TotalMarks1 decimal(8,2),		
		TotalObtain1 decimal(8,2),
		Percentage1 decimal(8,2),
		RankNumber1 int,
		ResultGrade1 NVarchar(50),
		Percentile1 decimal(8,2),
		ResultStatus1 Nvarchar(20),
		
		SubActivityGrade1 nvarchar(50),
		ActivityGrade1 nvarchar(50),
		
		Exam2Name nvarchar(150),	
		TotalMarks2 decimal(8,2),
		TotalObtain2 decimal(8,2),
		Percentage2 decimal(8,2),
		RankNumber2 int,
		ResultGrade2 NVarchar(50),
		Percentile2 decimal(8,2),
		ResultStatus2 Nvarchar(20),
		
		SubActivityGrade2 nvarchar(50),
		ActivityGrade2 nvarchar(50),
		
		Exam3Name nvarchar(150),	
		TotalMarks3 decimal(8,2),
		TotalObtain3 decimal(8,2),
		Percentage3 decimal(8,2),
		RankNumber3 int,
		ResultGrade3 NVarchar(50),
		Percentile3 decimal(8,2),		
		ResultStatus3 Nvarchar(20),
		
		SubActivityGrade3 nvarchar(50),
		ActivityGrade3 nvarchar(50),
		
		Exam4Name nvarchar(150),	
		TotalMarks4 decimal(8,2),
		TotalObtain4 decimal(8,2),
		Percentage4 decimal(8,2),
		RankNumber4 int,
		ResultGrade4 NVarchar(50),
		Percentile4 decimal(8,2),
		ResultStatus4 Nvarchar(20),
		
		SubActivityGrade4 nvarchar(50),
		ActivityGrade4 nvarchar(50),
		
		Exam5Name nvarchar(150),		
		TotalMarks5 decimal(8,2),
		TotalObtain5 decimal(8,2),
		Percentage5 decimal(8,2),
		RankNumber5 int,
		ResultGrade5 NVarchar(50),
		Percentile5 decimal(8,2),
		ResultStatus5 Nvarchar(20),
		
		SubActivityGrade5 nvarchar(50),
		ActivityGrade5 nvarchar(50),
		
		Exam6Name nvarchar(150),	
		TotalMarks6 decimal(8,2),
		TotalObtain6 decimal(8,2),
		Percentage6 decimal(8,2),
		RankNumber6 int,
		ResultGrade6 NVarchar(50),
		Percentile6 decimal(8,2),
		ResultStatus6 Nvarchar(20),
		
		SubActivityGrade6 nvarchar(50),
		ActivityGrade6 nvarchar(50),
		
		Exam7Name nvarchar(150),		
		TotalMarks7 decimal(8,2),
		TotalObtain7 decimal(8,2),
		Percentage7 decimal(8,2),
		RankNumber7 int,
		ResultGrade7 NVarchar(50),
		Percentile7 decimal(8,2),
		ResultStatus7 Nvarchar(20),
		
		SubActivityGrade7 nvarchar(50),
		ActivityGrade7 nvarchar(50),
		
		Exam8Name nvarchar(150),
		TotalMarks8 decimal(8,2),
		TotalObtain8 decimal(8,2),
		Percentage8 decimal(8,2),
		RankNumber8 int,
		ResultGrade8 NVarchar(50),
		Percentile8 decimal(8,2),
		ResultStatus8 Nvarchar(20),

		SubActivityGrade8 nvarchar(50),
		ActivityGrade8 nvarchar(50),

		Exam9Name Nvarchar(150),
		Exam10Name Nvarchar(150),
		Exam11Name Nvarchar(150),
		Exam12Name Nvarchar(150),
		Exam13Name Nvarchar(150),

		SubActivityGrade9 nvarchar(50),
		ActivityGrade9 nvarchar(50),

		SubActivityGrade10 nvarchar(50),
		ActivityGrade10 nvarchar(50),

		SubActivityGrade11 nvarchar(50),
		ActivityGrade11 nvarchar(50),

		SubActivityGrade12 nvarchar(50),
		ActivityGrade12 nvarchar(50),

		SubActivityGrade13 nvarchar(50),
		ActivityGrade13 nvarchar(50),

		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,
		IsDisplayParentName bit,
		
		FatherName nvarchar(100),
		MotherName nvarchar(100),
		IsShowSubjectMark bit, 
		IsOptionalSubject bit,
		CoScholasticScopeId tinyint,
		IsDisplayPrincipalSign bit,
		IsDisplayTeacherSign bit,
		EmployeeSign varbinary(max),
		
		ActivityName nvarchar(200),
		SubActivityName nvarchar(200),
		SubActivityId int,
		ActivityId Int,
		 SubActivityGrade nvarchar(50),
		 ActivityGrade nvarchar(50),
		SubActivityGradeIndicator nvarchar(50),
		SubActivityDescriptiveIndicator nvarchar(200),
		SubjectActivityOrderIndex Smallint,
		SubActivityOrderIndex smallint,
		ColumnSubjectCount SmallInt,
		MarksheetHeaderA4 varbinary(max),
		IsImageHeader bit,
		Height1 decimal(6,2),
		Height2 decimal(6,2),
		Height3 decimal(6,2),
		Height4 decimal(6,2),
		Height5 decimal(6,2),
		Height6 decimal(6,2),
		Height7 decimal(6,2),
		Height8 decimal(6,2),
		Height9 decimal(6,2),
		Height10 decimal(6,2),
		Height11 decimal(6,2),
		Height12 decimal(6,2),
		Height13 decimal(6,2),
		Weight1 decimal(6,2),
		Weight2 decimal(6,2),
		Weight3 decimal(6,2),
		Weight4 decimal(6,2),
		Weight5 decimal(6,2),
		Weight6 decimal(6,2),
		Weight7 decimal(6,2),
		Weight8 decimal(6,2),
		Weight9 decimal(6,2),
		Weight10 decimal(6,2),
		Weight11 decimal(6,2),
		Weight12 decimal(6,2),
		Weight13 decimal(6,2),
		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),
		--Manits - 41461(Increase size 200 to 2000)
		MyActivity1 nvarchar(2000),  
		MyActivity2 nvarchar(2000),
		MyActivity3 nvarchar(2000),
		MyActivity4 nvarchar(2000),
		MyActivity5 nvarchar(2000),
		MyActivity6 nvarchar(2000),
		MyActivity7 nvarchar(2000),
		MyActivity8 nvarchar(2000),
		MyActivity9 nvarchar(2000),
		MyActivity10 nvarchar(2000),
		MyActivity11 nvarchar(2000),
		MyActivity12 nvarchar(2000),
		MyActivity13 nvarchar(2000),
		--Manits - 41461
		GeneralRemark1 nvarchar(1000),
		GeneralRemark2 nvarchar(1000),
		GeneralRemark3 nvarchar(1000),
		GeneralRemark4 nvarchar(1000),
		GeneralRemark5 nvarchar(1000),
		GeneralRemark6 nvarchar(1000),
		GeneralRemark7 nvarchar(1000),
		GeneralRemark8 nvarchar(1000),
		GeneralRemark9 nvarchar(1000),
		GeneralRemark10 nvarchar(1000),
		GeneralRemark11 nvarchar(1000),
		GeneralRemark12 nvarchar(1000),
		GeneralRemark13 nvarchar(1000),
		PresentAddress nvarchar(500) ,
		MobileNo nvarchar(50),
		House nvarchar(100),
		 
		AttendanceTerm1 decimal(6, 2) ,
		AttendanceTerm2 decimal(6, 2),
		WorkingDaysTerm1 decimal(6, 2),
		WorkingDaysTerm2 decimal(6, 2),
		
		BloodGroup nvarchar(20),
		GradeSetIdText nvarchar(50),
		IsDisplayMonthlyAttendanceText nvarchar(20),
		DentalHygiene nvarchar(200),
		VisionLeft nvarchar(50),
		VisionRight nvarchar(50),
		TeacherSignCaption nvarchar(100),
		PrincipalSignCaption nvarchar(100),
		ParentSignCaption nvarchar(100),
		ParentEmail nvarchar(500),
		MyGoal nvarchar(200),
		MyStrength nvarchar(200),
		MyInterestHobby nvarchar(200),
		AreaOfInterest nvarchar(200),
		Responsibility nvarchar(200),
		Achievements nvarchar(1000),
		ImprovementArea nvarchar(200),
		ProgressArea nvarchar(200),
		MyActivity nvarchar(2000),
		ClassTeacherRemark nvarchar(1000),
		ClassTeacherName Nvarchar(100),
		HouseRemark nvarchar(1000),
		GeneralRemark nvarchar(1000),
		FatherContactNo nvarchar(50),
		MotherContactNo nvarchar(50),
		FatherMail nvarchar(max),
		MotherMail nvarchar(max),
		IsDecimal bit,
		Name nvarchar(150),
		--mantis 0029914
		PermanentStreetOne nvarchar(150),
		PermanentStreetTwo nvarchar(150),
		PermanentStreetThree nvarchar(150),
		AdmissionNo nvarchar(50),
		StudentContactNo nvarchar(50),
		DescriptiveIndicator nvarchar(200),
		DescriptiveIndicator1 nvarchar(200),
		DescriptiveIndicator2 nvarchar(200),
		DescriptiveIndicator3 nvarchar(200),
		DescriptiveIndicator4 nvarchar(200),
		DescriptiveIndicator5 nvarchar(200),
		DescriptiveIndicator6 nvarchar(200),
		DescriptiveIndicator7 nvarchar(200),
		DescriptiveIndicator8 nvarchar(200),
		DescriptiveIndicator9 nvarchar(200),
		DescriptiveIndicator10 nvarchar(200),
		DescriptiveIndicator11 nvarchar(200),
		DescriptiveIndicator12 nvarchar(200),
		DescriptiveIndicator13 nvarchar(200),
		--for mantis Start - 36640 
		RelativeName varchar(100),
		PresentCity varchar (50),
		--for mantis End - 36640 ,
		--for mantis Start: 0039950
		Exam1DisplayTitle nvarchar(200),
		Exam2DisplayTitle nvarchar(200),
		Exam3DisplayTitle nvarchar(200),
		Exam4DisplayTitle nvarchar(200),
		Exam5DisplayTitle nvarchar(200),
		Exam6DisplayTitle nvarchar(200),
		Exam7DisplayTitle nvarchar(200),
		Exam8DisplayTitle nvarchar(200),
		Exam9DisplayTitle nvarchar(200),
		Exam10DisplayTitle nvarchar(200),
		Exam11DisplayTitle nvarchar(200),
		Exam12DisplayTitle nvarchar(200),
		Exam13DisplayTitle nvarchar(200),
		ResultSheetAdditionalTitle nvarchar(200) --Mantis - 40152
		--for mantis End: 0039950
		,UIDNumber nvarchar(200)
	)	
	
	 --print 'temp created'    	
	INSERT INTO  #TempAllExam 
	(
	AcademicIdText,
	ExamIdText,
	CoScholasticScopeIdText,
	
	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,
	IsDisplayParentName,
	FatherName,
	MotherName,
	IsShowSubjectMark,
	IsOptionalSubject,
	CoScholasticScopeId,
	IsDisplayPrincipalSign,
	IsDisplayTeacherSign,
	EmployeeSign,
	SubActivityGrade,
	ActivityGrade,
	ActivityName,
	SubActivityName,
	SubActivityId,
	ActivityId,
	SubActivityGradeIndicator,
	SubActivityDescriptiveIndicator,
	SubjectActivityOrderIndex,
	SubActivityOrderIndex,
	ColumnSubjectCount,
	MarksheetHeaderA4,
	IsImageHeader,
	PresentAddress,
 	MobileNo,
	House,
	AttendanceTerm1   ,
	AttendanceTerm2  ,
	WorkingDaysTerm1  ,
	WorkingDaysTerm2  ,
	BloodGroup,
	GradeSetIdText,
	IsDisplayMonthlyAttendanceText,
	DentalHygiene,
	VisionLeft,
	VisionRight,
	TeacherSignCaption,
	PrincipalSignCaption,ParentSignCaption,
	ParentEmail,
	MyGoal ,
	MyStrength ,
	MyInterestHobby ,
	AreaOfInterest ,
	Responsibility ,
	Achievements ,
	ImprovementArea ,
	ProgressArea ,
	MyActivity ,
	ClassTeacherRemark ,
	ClassTeacherName ,
	HouseRemark ,
	GeneralRemark ,
	FatherContactNo ,
	MotherContactNo ,
	FatherMail,
	MotherMail,
	IsDecimal,
	Name,
	-- mantis-0029914
	PermanentStreetOne,
	PermanentStreetTwo,
	PermanentStreetThree,
	AdmissionNo,
	StudentContactNo,
	DescriptiveIndicator,
	--for mantis Start - 36640 
	RelativeName,
	PresentCity,
	ResultSheetAdditionalTitle --Mantis - 40152
	--for mantis End - 36640 
	,UIDNumber
	)
	
	SELECT 
		Convert(nvarchar(20),A.Id),
		Convert(nvarchar(20),@rExamId),
		Convert(nvarchar(20),EM.CoScholasticScopeId),
		A.Id,
		ISNULL(ESGM.Title,'') AS EXAMNAME,
		StuM.Code AS StudCode,
		StuM.FirstName+' '+StuM.MiddleName+' '+StuM.LastName AS StudentName,
		A.RollNo,
		R.ResultStatus,
		CM.DisplayTitle AS ClassName,
		DM.DisplayTitle AS Division,
		R.TotalMarks AS TotalMark,
		R.TotalObtain,
		R.Percentage,
		R.RankNumber,
		R.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 WHEN EM.IsDisplayPhoto = 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,
	    SAM.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,
		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,
		SSA.Grade AS SubActivityGrade,
		ISNULL(SAS.Grade,'') AS ActivityGrade,
		SAM.Title AS ActivityName,
		SSAM.Title AS SubActivityName,
		SSA.SubjectSubActivityId AS SubActivityId,
		SAM.Id AS ActivityId,
		SSA.GradeIndicator AS SubActivityGradeIndicator,
		SSA.DescriptiveIndicator AS SubActivityDescriptiveIndicator,
		SAM.OrderIndex AS SubjectActivityOrderIndex,
		SSAM.OrderIndex AS SubActivityOrderIndex,
		CASE WHEN CS.OrderIndex % 2 = 0 THEN 2 
				ELSE 1 END   AS   ColumnSubjectCount,
		(CASE EM.IsDisplayImageHeader WHEN 1 THEN
			OI.MarksheetHeaderA4
			ELSE NULL END)AS  MarksheetHeaderA4,
		ISNULL(EM.IsDisplayImageHeader,0) AS IsImageHeader	,
		ISNULL(SC.PresentStreetONe,'')+' '+ISNULL(SC.PresentStreetTwo,'')+' '+ISNULL(SC.PresentStreetThree,'')+' '+ISNULL(SC.PresentCity,'')+' '+ISNULL(SC.PresentState,'') AS PresentAddress,
		 SC.ParentContactNo,
		ISNULL(HM.Title,'') AS House,
		ISNULL(CCER.AttendanceTerm1,0) AS AttendanceTerm1,
		ISNULL(CCER.AttendanceTerm2,0) AS AttendanceTerm2,
		ISNULL(CCER.WorkingDaysTerm1,0) AS WorkingDaysTerm1,
		ISNULL(CCER.WorkingDaysTerm2,0) AS WorkingDaysTerm2,
		ISNULL(BGM.Title,'') AS BloodGroup,
		CONVERT (nvarchar(50),EM.GradeSetId) AS GradeSetIdText,
		Convert(nvarchar(20),ISNULL(EM.IsDisplayMonthlyAttendance,0)) AS IsDisplayMonthlyAttendanceText,
		ISNULL(SR.DentalHygiene,'') AS DentalHygiene,
		ISNULL(SR.VisionLeft,'') AS VisionLeft,
		ISNULL(SR.VisionRight,'') AS VisionRight,
		--CASE WHEN EM.IsDisplayTeacherSign = 1 THEN EM.TeacherSignCaption ELSE NULL END AS TeacherSignCaption,
		--CASE WHEN EM.IsDisplayPrincipalSign = 1 THEN EM.PrincipalSignCaption ELSE NULL END AS PrincipalSignCaption,
		ISNULL(EM.TeacherSignCaption,'') AS TeacherSignCaption,
		ISNULL(EM.PrincipalSignCaption,'') AS PrincipalSignCaption,
		ISNULL(ParentSignCaption,'') AS ParentSignCaption,
		SC.ParentEmail As ParentEmail,
		ISNULL(SR.MyGoal,'') AS MyGoal,
		ISNULL(SR.MyStrength,'') AS MyStrength,
		ISNULL(SR.MyInterestHobby,'') AS MyInterestHobby,
		ISNULL(SR.AreaOfInterest,'') AS AreaOfInterest,
		ISNULL(SR.Responsibility,'') AS Responsibility,
		ISNULL(SR.Achievements,'') AS Achievements,
		ISNULL(SR.ImprovementArea,'') As ImprovementArea,
		ISNULL(SR.ProgressArea,'') AS ProgressArea,
		ISNULL(SR.MyActivity,'') AS MyActivity,
		ISNULL(SR.ClassTeacherRemark,'') As ClassTeacherRemark,
		EMP.FirstName + ' ' + EMP.LastName AS ClassTeacherName,
		ISNULL(SR.HouseRemark,'') As HouseRemark,
		ISNULL(SR.GeneralRemark,'') As GeneralRemark,
		SF.FatherContactNo,
		SF.MotherContactNo,
		SF.FatherMail,
		SF.MotherMail,
		CONVERT(bit,@lDecimalConfig) AS IsDecimal,
		[sStudent].[fStudentNameGet](stum.FirstName , StuM.MiddleName, StuM.LastName,OM.StudentNameFormatId ) AS Name,
		-- mantis-0029914
		SC.PermanentStreetOne,
		SC.PermanentStreetTwo,
		SC.PermanentStreetThree,
		StuA.AdmissionNumber,
		SC.StudentContactNo,
		SSA.DescriptiveIndicator AS DescriptiveIndicator,
		--for mantis Start - 36640 
		ISNULL(SF.RelativeName,'') AS RelativeName,
		ISNULL(SC.PresentCity,'') AS PresentCity,
		--for mantis End - 36640 
		ISNULL(EM.ResultSheetAdditionalTitle, '') AS ResultSheetAdditionalTitle	--Mantis - 40152
		,ISNULL(SO.UIDNumber,'') AS UIDNumber --add for mantis : 0042613	
	FROM 
		sAssessment.tCCESubjectSubActivityExamScore SSA
		INNER JOIN sAssessment.tCCESubjectSubActivityMaster SSAM ON SSAM.Id = SSA.SubjectSubActivityId
		INNER JOIN sAssessment.tCCESubjectActivityMaster SAM ON SAM.Id = SSAM.SubjectActivityId
		LEFT JOIN sAssessment.tCCESubjectActivityExamScore SAS ON SAS.SubjectActivityId= SAM.Id AND SSA.AcademicId = SAS.AcademicId AND SSA.ExamId = SAS.ExamId
		INNER JOIN sSetup.tClassSubject CS ON CS.Id=SAM.ClassSubjectId	
		INNER JOIN sAssessment.tExamMaster EM ON EM.Id=SSA.ExamId
		INNER JOIN sAssessment.tExamDetail ED ON EM.Id=ED.ExamId AND ED.ClassSubjectId = SAM.ClassSubjectId
		--INNER JOIN sSetup.tClassSubject CS ON CS.Id=SAM.ClassSubjectId
		INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=CS.SubjectId					 
    	INNER JOIN sStudent.tAcademic  A ON   SSA.AcademicId = A.Id
		LEFT JOIN sAssessment.tCCEResult CCER    ON  CCER.AcademicId=A.Id
		INNER JOIN sStudent.tStudentMaster StuM ON StuM.Id=A.StudentId
		INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId
		INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId
		LEFT JOIN sHrm.tEmployeeMaster EMP ON EMP.Id = DM.InchargeEmployeeId
		LEFT JOIN sHrm.tEmployeeImages EI ON EI.EmployeeId = Dm.InchargeEmployeeId
		INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id = EM.EXAMSUBGROUPID
		LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId=StuM.Id
		LEFT JOIN sCommon.tBloodGroupMaster BGM ON BGM.Id=SO.BloodGroupId
		LEFT JOIN sStudent.tAcademicDetail AD ON AD.AcademicId=A.Id
		LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId=StuM.Id
		LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId = StuM.Id
		LEFT JOIN sAssessment.tOptionalSubject OS ON OS.AcademicId = A.Id AND OS.ClassSubjectId = ED.ClassSubjectId  
		LEFT JOIN sAssessment.tResult R ON R.AcademicId = SSA.AcademicId AND R.ExamId = SSA.ExamId
		LEFT JOIN sAssessment.tResultDetail RD  ON R.Id = RD.ResultId AND ED.ID = RD.ExamDetailId 
		LEFT JOIN sAssessment.tStudentRemark SR ON A.Id = SR.AcademicId AND EM.Id = SR.ExamId
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = StuM.OrgId
		LEFT JOIN sSetup.tOrgImages OI ON OI.OrgId = OM.Id
		LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId =Stum.ID
		LEFT JOIN sActivity.tHouseMaster HM ON HM.Id=SO.HouseId
		--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
		--0029914
		LEFT JOIN sStudent.tStudentAdmission StuA ON StuM.Id = StuA.StudentId
	
	 WHERE
		SSA.ExamId = @rExamId 
		AND ((A.DivisionId =  @rDivisionId) OR (@rDivisionId=0))
		AND ((A.ClassId =  @rClass) OR (@rClass=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)) --uncommented by Dhananjay for mantis : 41990
		AND((A.Id=@rAcademicId)OR (@rAcademicId=0))
		--AND ((CS.SubjectId=@rSubjectId) OR(@rSubjectId=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.SubExamId = E.SubExamId
	ORDER BY E.ExamOrder,C.ExamOrder
	END
	 
	--ON 
	
	-- Order By ExamOrder ASC
	--WHERE ExamId in (SELECT SUBEXAMID FROM sAssessment.tExamCombine WHERE ExamId  = @rExamId Order By ExamOrder ASC)
	
	DECLARE @lCount int,@query  AS NVARCHAR(MAX),@lSubExamId int,@lCount1 int  
	Select @lCount = MAX(Id) from #tempcombineExam	
	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
					
					 IsPresent' + convert(nvarchar(15),@lCount)+'=RD.IsPresent,					
					 SubjectGrade' + convert(nvarchar(15),@lCount)+ '=RD.SubjectGrade,
					 Exam' + convert(nvarchar(15),@lCount)+ 'Name=ESGM.Title,
					 Height' + convert(nvarchar(15),@lCount)+ '=SR.StudentHeight,
					 Weight' + convert(nvarchar(15),@lCount)+ '=SR.StudentWeight,				
					 TotalDays'+convert(nvarchar(15),@lCount)+'=SR.TotalDays,
					 PresentDays'+convert(nvarchar(15),@lCount)+'=SR.PresentDays,
					 MyActivity'+convert(nvarchar(15),@lCount)+'=SR.MyActivity,
					 GeneralRemark'+convert(nvarchar(15),@lCount)+'=SR.GeneralRemark,
					 Exam' + convert(nvarchar(15),@lCount)+ 'DisplayTitle=ESGM.ExamSubGroupDisplayTitle 
					 									
					 From
						 
						 sAssessment.tResult R 
						INNER JOIN  sAssessment.tResultDetail RD ON RD.ResultId = R.Id						
						INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
						INNER JOIN sAssessment.tExamSubgroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId					
						INNER JOIN 	#TempAllExam  T ON T.ClassSubjectID = ED.ClassSubjectId And T.AcademicId = R.AcademicId	
						LEFT JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND T.AcademicId = SR.AcademicId 							
						WHERE EM.Id =' + convert(nvarchar(15), @lSubExamId)  
						
	
	 execute(@query)
 
	 set @query ='update T SET
					
					 
					 SubActivityGrade' + convert(nvarchar(15),@lCount)+ '=SSA.Grade,
					 DescriptiveIndicator' + convert(nvarchar(15),@lCount)+ '=SSA.DescriptiveIndicator	
					 						
					 From
						sAssessment.tCCESubjectSubActivityExamScore SSA				
						inner JOIN 	#TempAllExam  T ON T.SubActivityId = SSA.SubjectSubActivityId And T.AcademicId = SSA.AcademicId	 					
						WHERE SSA.ExamId =' + convert(nvarchar(15), @lSubExamId)  


						
	
 --PRINT(@QUERY)	
   EXECUTE(@query)
 
  set @query ='update T SET
					
					  ActivityGrade' + convert(nvarchar(15),@lCount)+ '=SAS.Grade	
					 						
					 From
						sAssessment.tCCESubjectActivityExamScore SAS				
						inner JOIN 	#TempAllExam  T ON T.ActivityId = SAS.SubjectActivityId And T.AcademicId = SAS.AcademicId	 					
						WHERE SAS.ExamId =' + convert(nvarchar(15), @lSubExamId)  
						
	
 --PRINT(@QUERY)	
   EXECUTE(@query)
	-- set @query ='update T SET
					
	--				 Height' + convert(nvarchar(15),@lCount)+ '=SR.StudentHeight,
	--				 Weight' + convert(nvarchar(15),@lCount)+ '=SR.StudentWeight,				
	--				 TotalDays'+convert(nvarchar(15),@lCount)+'=SR.TotalDays,
	--				 PresentDays'+convert(nvarchar(15),@lCount)+'=SR.PresentDays,
	--				 MyActivity'+convert(nvarchar(15),@lCount)+'=SR.MyActivity,
	--				 GeneralRemark'+convert(nvarchar(15),@lCount)+'=SR.GeneralRemark
	--				 From
	--					sAssessment.tCCESubjectSubActivityExamScore SSA
						
	--					inner JOIN sAssessment.tCCESubjectSubActivityMaster SSAM ON SSAM.Id = SSA.SubjectSubActivityId
	--					inner JOIN sAssessment.tCCESubjectActivityMaster SAM ON SAM.Id = SSAM.SubjectActivityId
	--					INNER JOIN sAssessment.tExamMaster EM ON EM.Id=SSA.ExamId
	--					inner JOIN 	#TempAllExam  T ON T.SubActivityId = SSA.SubjectSubActivityId And T.AcademicId = SSA.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.Title,
					ExamMaximum' + convert(nvarchar(15),@lCount)+'=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)*/
		
		
	set @lCount = @lCount -1
	end
	SELECT @rBuilder1 , T.*
	FROM #TempAllExam T
	
	
		
	drop table #tempcombineExam
	Drop table #TempAllExam

	--Select 
	-- '' As AcademicIdText,
	--	'' As ExamIdText,
	--	'' As CoScholasticScopeIdText ,
		
	--	CONVERT(bigint , 0) As AcademicId,
	--	'' As ExamName,
	--	'' As StudCode,
	--	'' As StudentName ,
	--	0 As RollNo,
	--	'' As ResultStatus ,	
	--	'' As ClassName ,		
	--	'' As Division ,
	--	CONVERT(decimal , 0) As TotalMark ,
	--	CONVERT(decimal , 0) As TotalObtain,
	--	CONVERT(decimal , 0) As Percentage ,
	--	0 As RankNumber ,
	--	'' As ResultGrade ,
		
	--	--MaximumMark1 decimal(8,2),		
	--	'' As SubjectGrade1 ,
	--	--Obtain1 decimal(8,2),
	--	--ExamMaximum1 decimal(8,2),
	--	CONVERT(bit , 0) As IsPresent1,
						
	--	CONVERT(decimal , 0) As MaximumMark2 ,	
	--	'' As SubjectGrade2 ,
	--	CONVERT(decimal , 0) As Obtain2 ,
	--	CONVERT(decimal , 0) As ExamMaximum2 ,
	--	CONVERT(bit , 0) As IsPresent2,
				
	--	CONVERT(decimal , 0) As MaximumMark3 ,
	--	'' As SubjectGrade3 ,
	--	CONVERT(decimal , 0) As Obtain3 ,
	--	CONVERT(decimal , 0) As ExamMaximum3 ,
	--	CONVERT(bit , 0) As IsPresent3 ,		
		
	--	CONVERT(decimal , 0) As MaximumMark4 ,	
	--	'' As SubjectGrade4 ,
	--	CONVERT(decimal , 0) As Obtain4 ,
	--	CONVERT(decimal , 0) As ExamMaximum4 ,
	--	CONVERT(bit , 0) As IsPresent4 ,	
				
	--	CONVERT(decimal , 0) As MaximumMark5 ,		
	--	'' As SubjectGrade5 ,
	--	CONVERT(decimal , 0) As Obtain5 ,
	--	CONVERT(decimal , 0) As ExamMaximum5 ,
	--	CONVERT(bit , 0) As IsPresent5 ,	
				
	--	CONVERT(decimal , 0) As MaximumMark6 ,		
	--	'' As SubjectGrade6,
	--	CONVERT(decimal , 0) As Obtain6 ,
	--	CONVERT(decimal , 0) As ExamMaximum6 ,
	--	CONVERT(bit , 0) As IsPresent6 ,	
		
	--	CONVERT(decimal , 0) As MaximumMark7 ,		
	--	'' As SubjectGrade7,
	--	CONVERT(decimal , 0) As Obtain7 ,
	--	CONVERT(decimal , 0) As ExamMaximum7 ,
	--	CONVERT(bit , 0) As IsPresent7 ,	
	
	--	CONVERT(decimal , 0) As MaximumMark8 ,	
	--	'' As SubjectGrade8,
	--	CONVERT(decimal , 0) As Obtain8 ,
	--	CONVERT(decimal , 0) As ExamMaximum8 ,
	--	CONVERT(bit , 0) As IsPresent8 ,	
		
	--	'' As SubjectGrade9,
	--	CONVERT(bit , 0) As IsPresent9 ,

	--	'' As SubjectGrade10,
	--	CONVERT(bit , 0) As IsPresent10 ,

	--	'' As SubjectGrade11,
	--	CONVERT(bit , 0) As IsPresent11 ,

	--	'' As SubjectGrade12,
	--	CONVERT(bit , 0) As IsPresent12 ,

	--	'' As SubjectGrade13,
	--	CONVERT(bit , 0) As IsPresent13 ,

	--	'' As SubjectGradeTerm1,
	--	'' As SubjectGradeTerm2 ,
	--	CONVERT(bit , 0) As IsMarksInDecimal ,
	--	CONVERT(bit , 0) As column_visible ,
	--	--Obtain decimal(5,2),
	--	CONVERT(decimal , 0) As Percentile,
	--	--ClassSubject nvarchar(100),
	--	CONVERT(bigint , 0) As ResultDetailId ,
	--	CONVERT(bigint , 0) As ResultId ,	
	--	'' As Remark1 ,
	--	'' As Remark2 ,
	--	'' As Remark3 ,
	--	'' As DisplayTitle ,		
	--	CONVERT(bit , 0) As IsRankNo , 
	--	CONVERT(bit , 0) As IsGrade ,
	--	CONVERT(bit , 0) As IsPercentile ,
	--	CONVERT(bit , 0) As IsPercentage ,
	--	CONVERT(bit , 0) As IsSubjectPercentile ,
	--	CONVERT(bit , 0) As IsProcessResult ,
	--	CONVERT(bit , 0) As IsNegativeMarks ,
	--	CONVERT(bit , 0) As IsIncludeCoScholastic ,
	--	CONVERT(bit,0) As IsOnPrePrinted ,
	--	CONVERT(bit , 0) As IsDisplayPhoto ,
	--	CONVERT(bit , 0) As IsDisplayBirthDate ,
	--	CONVERT(bit , 0) As IsLockForEdit ,
	--	CONVERT(bit , 0) As IsDisplaySchoolName ,			
	--	CONVERT(bit , 0) As IsDisplayAttendance ,
	--	CONVERT(bit , 0) As IsDisplayHeightWeight ,
	--	CONVERT(bit , 0) As IsResultStatus ,
	--	'' As FooterAdjustmentText ,
	--	'' As DetailAdjustmentText ,
	--	0 As FooterAdjustment ,
	--	0 As DetailAdjustment ,
	--	'' As ResultRemark ,
	--	CONVERT(Date , null) As DateOfBirth ,
	--	CONVERT(decimal , 0) As HeightTerm1 ,
	--	CONVERT(decimal , 0) As WeightTerm1 ,
	--	CONVERT(decimal , 0) As HeightTerm2,
	--	CONVERT(decimal , 0) As WeightTerm2 ,
	--	CONVERT(decimal , 0) As HeightAnnual ,
	--	CONVERT(decimal , 0) As WeightAnnual ,
	--	0 As PresentDaysTerm1,
	--	0 As PresentDaysTerm2 ,
	--	0 As PresentDaysAnnual ,
	--	0 As TotalDaysTerm1 ,
	--	0 As TotalDaysTerm2 ,
	--	0 As TotalDaysAnnual ,
	--	CONVERT(decimal , 0) As TotalMarkTerm1 ,
	--	CONVERT(decimal , 0) As TotalObtainTerm1 ,
	--	CONVERT(decimal , 0) As PercentageTerm1,
	--	0 As RankNumberTerm1 ,
	--	'' As ResultGradeTerm1,
	--	CONVERT(decimal , 0) As PercentileTerm1 ,
	--	'' As ResultStatusTerm1,		   
	--	CONVERT(decimal , 0) As TotalMarkTerm2 ,
	--	CONVERT(decimal , 0) As TotalObtainTerm2 ,
	--	CONVERT(decimal , 0) As PercentageTerm2 ,
	--	0 As RankNumberTerm2 ,
	--	'' As ResultGradeTerm2 ,
	--	CONVERT(decimal , 0) As PercentileTerm2 ,
	--	'' As ResultStatusTerm2 , 
	--	CONVERT(tinyInt , 0) As TermScopeId ,		 
	--	Convert (varbinary(max) , '') As StudentPhoto ,
	--	'' As GradeString,
	--	CONVERT(bit , 0) As IsDisplayGradeString ,		 
	--	CONVERT(bit , 0) As IsDisplayInMarksheet ,
	--	CONVERT(bit , 0) As IsShowSubjectGrade ,
	--	CONVERT(bit , 0) As IsIncludeInTotal ,
	--	0 As ClassSubjectID ,
	--	0 As SubjectId ,
	--	--Maximum decimal(5,2),
	--	0 As SubjectOrderIndex ,
	--	'' As SubjectGrade ,
	--	'' As SubjectName ,
	--	'' As SubjectCode ,	
	--	CONVERT(decimal , 0) As SubjectMinimum ,		
	--	CONVERT(decimal , 0) As SubjectMaximum ,
	--	CONVERT(decimal , 0) As SubjectObtain ,
		
	--	'' As Exam1Name ,		
	--	CONVERT(decimal , 0) As TotalMarks1 ,		
	--	CONVERT(decimal , 0) As TotalObtain1 ,
	--	CONVERT(decimal , 0) As Percentage1 ,
	--	0 As RankNumber1 ,
	--	'' As ResultGrade1,
	--	CONVERT(decimal , 0) As Percentile1 ,
	--	'' As ResultStatus1 ,
		
	--	'' As SubActivityGrade1,
	--	'' As ActivityGrade1,
		
	--	'' As Exam2Name ,	
	--	CONVERT(decimal , 0) As TotalMarks2 ,
	--	CONVERT(decimal , 0) As TotalObtain2 ,
	--	CONVERT(decimal , 0) As Percentage2 ,
	--	0 As RankNumber2 ,
	--	'' As ResultGrade2 ,
	--	CONVERT(decimal , 0) As Percentile2 ,
	--	'' As ResultStatus2 ,
		
	--	'' As SubActivityGrade2,
	--	'' As ActivityGrade2 ,
		
	--	'' As Exam3Name ,	
	--	CONVERT(decimal , 0) As TotalMarks3 ,
	--	CONVERT(decimal , 0) As TotalObtain3 ,
	--	CONVERT(decimal , 0) As Percentage3 ,
	--	0 As RankNumber3 ,
	--	'' As ResultGrade3 ,
	--	CONVERT(decimal , 0) As Percentile3 ,		
	--	'' As ResultStatus3,
		
	--	'' As SubActivityGrade3 ,
	--	'' As ActivityGrade3 ,
		
	--	'' As Exam4Name ,	
	--	CONVERT(decimal , 0) As TotalMarks4 ,
	--	CONVERT(decimal , 0) As TotalObtain4,
	--	CONVERT(decimal , 0) As Percentage4 ,
	--	0 As RankNumber4 ,
	--	'' As ResultGrade4 ,
	--	CONVERT(decimal , 0) As Percentile4 ,
	--	'' As ResultStatus4 ,
		
	--	'' As SubActivityGrade4,
	--	'' As ActivityGrade4 ,
		
	--	'' As Exam5Name ,		
	--	CONVERT(decimal , 0) As TotalMarks5 ,
	--	CONVERT(decimal , 0) As TotalObtain5 ,
	--	CONVERT(decimal , 0) As Percentage5 ,
	--	0 As RankNumber5 ,
	--	'' As ResultGrade5 ,
	--	CONVERT(decimal , 0) As Percentile5 ,
	--	'' As ResultStatus5 ,
		
	--	'' As SubActivityGrade5 ,
	--	'' As ActivityGrade5 ,
		
	--	'' As Exam6Name ,	
	--	CONVERT(decimal , 0) As TotalMarks6 ,
	--	CONVERT(decimal , 0) As TotalObtain6,
	--	CONVERT(decimal , 0) As Percentage6 ,
	--	0 As RankNumber6 ,
	--	'' As ResultGrade6 ,
	--	CONVERT(decimal , 0) As Percentile6 ,
	--	'' As ResultStatus6 ,
		
	--	'' As SubActivityGrade6 ,
	--	'' As ActivityGrade6 ,
		
	--	'' As Exam7Name ,		
	--	CONVERT(decimal , 0) As TotalMarks7 ,
	--	CONVERT(decimal , 0) As TotalObtain7,
	--	CONVERT(decimal , 0) As Percentage7 ,
	--	0 As RankNumber7 ,
	--	'' As ResultGrade7,
	--	CONVERT(decimal , 0) As Percentile7 ,
	--	'' As ResultStatus7 ,
		
	--	--SubActivityGrade7 nvarchar(10),
		
	--	'' As Exam8Name,
	--	CONVERT(decimal , 0) As TotalMarks8 ,
	--	CONVERT(decimal , 0) As TotalObtain8 ,
	--	CONVERT(decimal , 0) As Percentage8,
	--	0 As RankNumber8 ,
	--	'' As ResultGrade8 ,
	--	CONVERT(decimal , 0) As Percentile8,
	--	'' As ResultStatus8,

	--	'' As Exam9Name,
	--	'' As Exam10Name,
	--	'' As Exam11Name,
	--	'' As Exam12Name,
	--	'' As Exam13Name,

	--	'' As ResultRemark1 ,
	--	'' As ResultRemark2,
	--	CONVERT(decimal , 0) As TotalDays ,
	--	CONVERT(decimal , 0) As PresentDays ,
	--	CONVERT(decimal , 0) As StudentHeight,
	--	CONVERT(decimal , 0) As StudentWeight ,
	--	'' As ExamSeatNo ,
	--	0 As ExamId ,
	--	CONVERT(bit , 0) As IsDisplayParentName ,
	--	'' As FatherName ,
	--	'' As MotherName ,
	--	CONVERT(bit , 0) As IsShowSubjectMark , 
	--	CONVERT(bit , 0) As IsOptionalSubject ,
	--	CONVERT(tinyInt , 0) As CoScholasticScopeId ,
	--	CONVERT(bit , 0) As IsDisplayPrincipalSign ,
	--	CONVERT(bit , 0) As IsDisplayTeacherSign ,
	--	Convert (varbinary(max) , '') As EmployeeSign,
		
	--	'' As ActivityName ,
	--	'' As SubActivityName ,
	--	0 As SubActivityId ,
	--	0 As ActivityId ,
	--	 '' As SubActivityGrade,
	--	 '' As ActivityGrade ,
	--	'' As SubActivityGradeIndicator ,
	--	'' As SubActivityDescriptiveIndicator,
	--	0 As SubjectActivityOrderIndex ,
	--	0 As SubActivityOrderIndex ,
	--	0 As ColumnSubjectCount ,
	--	Convert (varbinary(max) , '') As MarksheetHeaderA4 ,
	--	CONVERT(bit,0) As IsImageHeader ,
	--	CONVERT(decimal , 0) As Height1 ,
	--	CONVERT(decimal , 0) As Height2 ,
	--	CONVERT(decimal , 0) As Height3,
	--	CONVERT(decimal , 0) As Height4 ,
	--	CONVERT(decimal , 0) As Height5,
	--	CONVERT(decimal , 0) As Height6 ,
	--	CONVERT(decimal , 0) As Height7 ,
	--	CONVERT(decimal , 0) As Height8 ,
	--	CONVERT(decimal , 0) As Height9,
	--	CONVERT(decimal , 0) As Height10 ,
	--	CONVERT(decimal , 0) As Height11,
	--	CONVERT(decimal , 0) As Height12 ,
	--	CONVERT(decimal , 0) As Height13 ,

	--	CONVERT(decimal , 0) As Weight1 ,
	--	CONVERT(decimal , 0) As Weight2 ,
	--	CONVERT(decimal , 0) As Weight3 ,
	--	CONVERT(decimal , 0) As Weight4,
	--	CONVERT(decimal , 0) As Weight5 ,
	--	CONVERT(decimal , 0) As Weight6 ,
	--	CONVERT(decimal , 0) As Weight7 ,
	--	CONVERT(decimal , 0) As Weight8 ,
	--	CONVERT(decimal , 0) As Weight9 ,
	--	CONVERT(decimal , 0) As Weight10,
	--	CONVERT(decimal , 0) As Weight11 ,
	--	CONVERT(decimal , 0) As Weight12 ,
	--	CONVERT(decimal , 0) As Weight13 ,

	--	CONVERT(decimal , 0) As TotalDays1 ,
	--	CONVERT(decimal , 0) As PresentDays1 ,
	--	CONVERT(decimal , 0) As TotalDays2 ,
	--	CONVERT(decimal , 0) As PresentDays2 ,
	--	CONVERT(decimal , 0) As TotalDays3 ,
	--	CONVERT(decimal , 0) As PresentDays3 ,
	--	CONVERT(decimal , 0) As TotalDays4 ,
	--	CONVERT(decimal , 0) As PresentDays4 ,
	--	CONVERT(decimal , 0) As TotalDays5 ,
	--	CONVERT(decimal , 0) As PresentDays5 ,
	--	CONVERT(decimal , 0) As TotalDays6 ,
	--	CONVERT(decimal , 0) As PresentDays6 ,
	--	CONVERT(decimal , 0) As TotalDays7 ,
	--	CONVERT(decimal , 0) As PresentDays7 ,
	--	CONVERT(decimal , 0) As TotalDays8 ,
	--	CONVERT(decimal , 0) As PresentDays8 ,
	--	CONVERT(decimal , 0) As TotalDays9 ,
	--	CONVERT(decimal , 0) As PresentDays9 ,
	--	CONVERT(decimal , 0) As TotalDays10 ,
	--	CONVERT(decimal , 0) As PresentDays10 ,
	--	CONVERT(decimal , 0) As TotalDays11 ,
	--	CONVERT(decimal , 0) As PresentDays11 ,
	--	CONVERT(decimal , 0) As TotalDays12 ,
	--	CONVERT(decimal , 0) As PresentDays12 ,
	--	CONVERT(decimal , 0) As TotalDays13 ,
	--	CONVERT(decimal , 0) As PresentDays13 ,

	--	'' As MyActivity1,
	--	'' As MyActivity2 ,
	--	'' As MyActivity3,
	--	'' As MyActivity4 ,
	--	'' As MyActivity5,
	--	'' As MyActivity6,
	--	'' As MyActivity7,
	--	'' As MyActivity8 ,
	--	'' As MyActivity9,
	--	'' As MyActivity10 ,
	--	'' As MyActivity11,
	--	'' As MyActivity12,
	--	'' As MyActivity13,

	--	'' As GeneralRemark1,
	--	'' As GeneralRemark2 ,
	--	'' As GeneralRemark3 ,
	--	'' As GeneralRemark4,
	--	'' As GeneralRemark5,
	--	'' As GeneralRemark6,
	--	'' As GeneralRemark7,
	--	'' As GeneralRemark8 ,
	--	'' As GeneralRemark9 ,
	--	'' As GeneralRemark10,
	--	'' As GeneralRemark11,
	--	'' As GeneralRemark12,
	--	'' As GeneralRemark13,

	--	'' As PresentAddress ,
	--	'' As  MobileNo,
	--	'' As House ,
		 
	--	CONVERT(decimal , 0) As AttendanceTerm1  ,
	--	CONVERT(decimal , 0) As AttendanceTerm2 ,
	--	CONVERT(decimal , 0) As WorkingDaysTerm1 ,
	--	CONVERT(decimal , 0) As WorkingDaysTerm2 ,
	--	  '' As BloodGroup ,
	--	  '' As GradeSetIdText ,
	--	  '' As IsDisplayMonthlyAttendanceText ,
	--	  '' As DentalHygiene ,
	--	'' As VisionLeft ,
	--	'' As VisionRight ,
	--	'' As TeacherSignCaption ,
	--	'' As PrincipalSignCaption ,
	--	'' As ParentSignCaption ,
	--	'' As ParentEmail ,
	--  '' AS MyGoal,
	--	'' AS MyStrength,
	--	'' AS MyInterestHobby,
	--	'' AS AreaOfInterest,
	--	'' AS Responsibility,
	--	'' AS Achievements,
	--	'' As ImprovementArea,
	--	'' AS ProgressArea,
	--	'' AS MyActivity,
	--	'' As ClassTeacherRemark,
	--	'' AS ClassTeacherName,
	--	'' As HouseRemark,
	--	'' As GeneralRemark,
	--	'' AS FatherContactNo,
	--	'' AS MotherContactNo,
	--	'' AS FatherMail,
	--	'' AS MotherMail,
	--  CONVERT(bit , 0) As IsDecimal,
	--  '' As Name,
	--'' AS PermanentStreetOne,
	--'' AS PermanentStreetTwo,
	--'' AS PermanentStreetThree,
	--'' AS AdmissionNo,
	--'' AS StudentContactNo,
	--'' AS DescriptiveIndicator ,
	--'' AS DescriptiveIndicator1,
	--'' AS DescriptiveIndicator2,
	--'' AS DescriptiveIndicator3,
	--'' AS DescriptiveIndicator4,
	--'' AS DescriptiveIndicator5,
	--'' AS DescriptiveIndicator6,
	--'' AS DescriptiveIndicator7,
	--'' AS DescriptiveIndicator8,
	--'' AS DescriptiveIndicator9,
	--'' AS DescriptiveIndicator10,
	--'' AS DescriptiveIndicator11,
	--'' AS DescriptiveIndicator12,
	--'' AS DescriptiveIndicator13,
	--'' AS RelativeName,
	--'' AS PresentCity,
	--'' AS Exam1DisplayTitle,
	--'' AS Exam2DisplayTitle	,
	--'' AS Exam3DisplayTitle	,
	--'' AS Exam4DisplayTitle	,
	--'' AS Exam5DisplayTitle	,
	--'' AS Exam6DisplayTitle	,
	--'' AS Exam7DisplayTitle	,
	--'' AS Exam8DisplayTitle	,
	--'' AS Exam9DisplayTitle	,
	--'' AS Exam10DisplayTitle,	
	--'' AS Exam11DisplayTitle,	
	--'' AS Exam12DisplayTitle,	
	--'' AS Exam13DisplayTitle,
	--'' AS ResultSheetAdditionalTitle	--Mantis - 40152
	--,'' AS UIDNumber --add for mantis : 0042613	
		


end
/*
 MaximumMark' + convert(nvarchar(15),@lCount)+ '=ED.Maximum,
Obtain' + convert(nvarchar(15),@lCount)+'=RD.Obtain,
					
					--sAssessment.tCCESubjectActivityMaster SAM 	
	--		INNER JOIN sAssessment.tCCESubjectSubActivityMaster SSAM ON SSAM.SubjectActivityId=SAM.Id  
	--		INNER JOIN sAssessment.vCCEExamClassSubject CS ON CS.ClassSubjectId=SAM.ClassSubjectId
	--		INNER JOIN sSetup.tClassMaster CMM ON CMM.Id=CS.ClassId 
	--		 INNER JOIN sStudent.vStudentAcademic  A ON   A.ClassId = CS.ClassId AND  A.StatusId = 1
	--		 LEFT JOIN sAssessment.tCCESubjectSubActivityExamScore SSA ON SSA.AcademicId = A.AcademicId AND SSA.SubjectSubActivityId= SSAM.Id  	
			  */
GO
PRINT N'Altering Procedure [sAttendance].[pStudentAttendaceDashboardGet]...';


GO
ALTER PROCEDURE [sAttendance].[pStudentAttendaceDashboardGet]
	 @rTypeId smallint,
	 @rUptoDate date='',
	 @rOrgGroupId int=0,
	 @rOrgId int=0,
	 @rDivisionId int=0,
	 @rClassId int =0,
	 @rGenderType int=0,
	 @rCommonOrgGroupBatchId int=0,
	 @rSyncDate int =0,
	 @rUserId Bigint,
	 @rAttendanceTypeId int = 0

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

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

SELECT @lConfigValueDashboard = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 592 AND SourceTypeId = 2010 AND SourceId = @rOrgGroupId;

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


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

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

IF @rClassId=0
  BEGIN
--Orggroup wise Attendance
   IF @rTypeId=1 
   BEGIN
--Update Attendance
	IF(@rSyncDate =1) 
		BEGIN 
			--DELETE  sAttendance.tTempStudentAttendance WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))
			--IF EXISTS (SELECT 1 FROM sAttendance.tTempStudentAttendance WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0)))
			--				BEGIN
							IF(@rOrgGroupId !=0)
									--INSERT INTO sAttendance.tTempStudentAttendance
--Total Student All Orggroup
				   SELECT 
					OGM.Id AS OrgGroupId,
					OGM.Title As OrgGroupTitle,
					0 As OrgId,'' As OrgTitle,       
					(Select count(SM1.ID)
					 FROM sStudent.tStudentMaster SM1
						 INNER JOIN sStudent.tAcademic A ON A.StudentId= SM1.ID and SM1.StatusId=1
						 INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId 
						 INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = BM.OrgId
						 INNER JOIN sSetup.tOrgGroupMaster OGMR ON OGMR.Id=OM.OrgGroupId
						 INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BM.OrgGroupBatchId
						 INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
					 WHERE 
						 OGM.Id = OGMR.Id  AND COGBM.Id=@rCommonOrgGroupBatchId 
						  -- IsInContext
						  AND BM.IsInContext = 1
						 ) AS Total,       
--PresentStudent All Orggroup
					 (select count(*) from sAttendance.tStudentRegister SME 
						INNER JOIN sStudent.tAcademic AE ON SME.Academicid=AE.id 
						INNER JOIN sStudent.tStudentMaster SM1 ON SM1.Id = AE.StudentId and SM1.StatusId=1
						INNER JOIN sSetup.tBatchMaster BME ON BME.Id = AE.BatchId 
						INNER JOIN sSetup.tOrganizationMaster OME ON OME.Id = BME.OrgId
						INNER JOIN sSetup.tOrgGroupMaster OGME ON OGME.Id=OME.OrgGroupId
						INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BME.OrgGroupBatchId
						INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
					  WHERE 
						OGM.Id = OGME.Id AND COGBM.Id=@rCommonOrgGroupBatchId and SME.IsPresent=1 and SME.AttendanceDate = CONVERT(char(10), @rUptoDate,126)
						AND (SME.AttendanceTypeId = @rAttendanceTypeId OR @rAttendanceTypeId = 0)
						-- IsInContext
						AND BME.IsInContext = 1
						) AS PresentStudent,
--AbsentStudent All Orggroup
					 (select count(*) from sAttendance.tStudentRegister SME 
						INNER JOIN sStudent.tAcademic AE ON SME.Academicid=AE.id
						INNER JOIN sStudent.tStudentMaster SM1 ON SM1.Id = AE.StudentId and SM1.StatusId=1
						INNER JOIN sSetup.tBatchMaster BME ON BME.Id = AE.BatchId 
						INNER JOIN sSetup.tOrganizationMaster OME ON OME.Id = BME.OrgId
						INNER JOIN sSetup.tOrgGroupMaster OGMEA ON OGMEA.Id=OME.OrgGroupId
						INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BME.OrgGroupBatchId
						INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
					  WHERE 
						OGM.Id = OGMEA.Id AND COGBM.Id=@rCommonOrgGroupBatchId AND SME.IsPresent=0 and SME.AttendanceDate = CONVERT(char(10), @rUptoDate,126)
						AND (SME.AttendanceTypeId = @rAttendanceTypeId OR @rAttendanceTypeId = 0)
						-- IsInContext
						AND BME.IsInContext = 1
						) AS AbsentStudent,
--LessThen70 % All Orggroup
				   (select Count(StudentID) from(
						select  (SMD.Id)StudentID
						 
					FROM sAttendance.tStudentRegister SMEL
						  INNER JOIN sStudent.tAcademic AEL ON SMEL.Academicid=AEL.id
						  INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = AEL.BatchId 
						  INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
						  INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
						  INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BMEl.OrgGroupBatchId
						  INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId						
						  INNER JOIN sSetup.tDivisionMaster DM ON DM.ID=AEL.DivisionID						
						  INNER JOIN sStudent.tStudentMaster SMD ON SMD.Id=AEL.StudentID and SMD.StatusId=1						
						  LEFT JOIN sStudent.tStudentCommunication SC on SMD.Id=SC.StudentID	     
					where 
						  OGM.Id = OGMEL.Id AND COGBM.Id=@rCommonOrgGroupBatchId AND		
						  SMEL.AttendanceDate <= CONVERT(char(10), @rUptoDate,126)
						  AND (SMEL.AttendanceTypeId = @rAttendanceTypeId OR @rAttendanceTypeId = 0)
						  -- IsInContext
						  AND BMEL.IsInContext = 1
						  GROUP BY SMD.Id
					--GROUP BY OGMEL.Id,OGMEL.Title,OMEL.Id,OMEL.Title,SMEL.AcademicId,DM.Code,SMD.Id,(SMD.FirstName+' '+SMD.LastName),(SC.ParentContactNo)
					HAVING convert(numeric(10,2), ((count(CAST((case when IsPresent=1 then 1 end) AS float))/CAST(Count(AcademicId)AS float))*100))<70) AS Tmp
					
					--HAVING convert(numeric(10,2), ((count(CAST((case when IsPresent=1 then 1 end) AS float))/CAST(Count(AcademicId)AS float))*100))<70
					)  As LessThen70,
--100% Attendance All Orggroup
				  (select Count(StudentID) from  (
					select  
						  OGMEL.Id AS OrgGroupId,
						  OGMEL.Title AS OrgGroupTitle,
						  OMEL.Id AS OrgId,
						  (OMEL.Title) As OrgTitle ,
						  DM.Code AS DivisionCode,
						  (SMD.Id)StudentID,
						  (SMD.FirstName+' '+SMD.LastName) AS StudentName,         
						  (SC.ParentContactNo) AS ContactNo,
						  ((count(CAST((case when IsPresent=1 then 1 end) AS float)))) As IsPresentCount,CAST(Count(AcademicId)AS float) As AcademicCount
					FROM sAttendance.tStudentRegister SMEL
						   INNER JOIN sStudent.tAcademic AEL ON SMEL.Academicid=AEL.id
						   INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = AEL.BatchId
						   INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
						   INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId						
						   INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BMEL.OrgGroupBatchId
						   INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
						   INNER JOIN sSetup.tDivisionMaster DM ON DM.ID=AEL.DivisionID						
						   INNER JOIN sStudent.tStudentMaster SMD ON SMD.Id=AEL.StudentID and SMD.StatusId=1					
						   LEFT JOIN sStudent.tStudentCommunication SC on SMD.Id=SC.StudentID
					WHERE OGM.Id = OGMEL.Id AND COGBM.Id=@rCommonOrgGroupBatchId AND		
						   SMEL.AttendanceDate <= CONVERT(char(10), @rUptoDate,126)
						   AND (SMEL.AttendanceTypeId = @rAttendanceTypeId OR @rAttendanceTypeId = 0)
						   -- IsInContext
						   AND BMEL.IsInContext = 1
					GROUP BY OGMEL.Id,OGMEL.Title,OMEL.Id,OMEL.Title,SMEL.AcademicId,DM.Code,SMD.Id,(SMD.FirstName+' '+SMD.LastName),(SC.ParentContactNo)		
					HAVING convert(numeric(10,2), ((count(CAST((case when IsPresent=1 then 1 end) AS float))/CAST(Count(AcademicId)AS float))*100))=100) AS Tmp
					) AS HundredPer,
--Absent>3 All Orggroup
				   (SELECT COUNT(AcademicId) FROM(
					  SELECT 
						ROW_NUMBER() OVER ( PARTITION BY AcademicId ORDER BY MIN(AttendanceDate) DESC) as rowno,
						AcademicId,AttendanceDate
					  FROM sAttendance.tStudentRegister d 		
						 INNER JOIN sStudent.tAcademic AEL ON d.Academicid=AEL.id
						 INNER JOIN sStudent.tStudentMaster SM1 ON SM1.Id = AEL.StudentId and SM1.StatusId=1
						 INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = AEL.BatchId
						 INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
						 INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
						 INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BMEL.OrgGroupBatchId
						 INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
		
					  WHERE
						 OGM.Id = OGMEL.Id AND COGBM.Id=@rCommonOrgGroupBatchId AND
						 IsPresent IN(0) 
						 AND AttendanceDate between DATEADD(DAY, -2, convert(date, @rUptoDate, 126)) AND @rUptoDate
						 and IsPresent=0
						 AND (d.AttendanceTypeId = @rAttendanceTypeId OR @rAttendanceTypeId = 0)
						 -- IsInContext
						 AND BMEL.IsInContext = 1
					  GROUP BY AcademicId,AttendanceDate) as AbsCnt WHERE rowno=3
					  ) AS AbsentCount,
--Leave Request All Orggroup
					(SELECT 
						COUNT(AcademicId) AS LeaveRequest
					 FROM sAttendance.tStudentLeaveRequest STSL
						INNER JOIN sStudent.tAcademic AEL ON STSL.Academicid=AEL.id
						INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = AEL.BatchId
						INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
						INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
						INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BMEL.OrgGroupBatchId
						INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
						INNER JOIN sSetup.tDivisionMaster DM ON DM.ID=AEL.DivisionID
						INNER JOIN sStudent.tStudentMaster SMD ON SMD.Id=AEL.StudentID and SMD.StatusId=1
						INNER JOIN sStudent.tStudentCommunication SC on SMD.Id=SC.StudentID
					WHERE OGM.Id = OGMEL.Id AND COGBM.Id=@rCommonOrgGroupBatchId AND
					CONVERT(char(10), @rUptoDate,126) between LeaveFromDate AND LeaveToDate
					-- IsInContext
					AND BMEL.IsInContext = 1
					) AS LeaveRequest,
--AttnNotTakenClass All Orggroup
					(Select count(SM1.ID)
					 FROM sStudent.tStudentMaster SM1
						 INNER JOIN sStudent.tAcademic A ON A.StudentId= SM1.ID and SM1.StatusId=1
						 INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId
						 INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = BM.OrgId
						 INNER JOIN sSetup.tOrgGroupMaster OGMR ON OGMR.Id=OM.OrgGroupId
						 INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BM.OrgGroupBatchId
						 INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
         
					 WHERE 
						 OGM.Id = OGMR.Id  and SM1.statusid =1 AND COGBM.Id=@rCommonOrgGroupBatchId AND A.Id  not in 
					(select AcademicId from sAttendance.tStudentRegister SR  WHERE SR.AttendanceDate = CONVERT(char(10),@rUptoDate,126) AND (SR.AttendanceTypeId = @rAttendanceTypeId OR @rAttendanceTypeId = 0))
					-- IsInContext
					AND BM.IsInContext = 1
					) 
					As AttnNotTakenClass,

				@rUptoDate AS StudentAttendanceDate
				,@rCommonOrgGroupBatchId AS CommonOrgGroupBatchId
				,GetDate() as UpdateDate
				FROM sSetup.tOrgGroupMaster OGM 
				WHERE OGM.Id<>1 AND ISNULL(OGM.IsObsolete,0) = 0
				AND  ((OGM.Id = @rOrgGroupId)OR(@rOrgGroupId=0))	
--				SELECT * FROM sAttendance.tTempStudentAttendance 
--			SELECT * FROM sAttendance.tTempStudentAttendance  WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0)) AND Total !=0 ORDER BY OrgGroupId
--							END
--						ELSE
--							BEGIN
--									INSERT INTO sAttendance.tTempStudentAttendance
----Total Student All Orggroup
--				   SELECT 
--					OGM.Id AS OrgGroupId,
--					OGM.Title As OrgGroupTitle,
--					0 As OrgId,'' As OrgTitle,       
--					(Select count(SM1.ID)
--					 FROM sStudent.tStudentMaster SM1
--						 INNER JOIN sStudent.tAcademic A ON A.StudentId= SM1.ID and SM1.StatusId=1
--						 INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId 
--						 INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = BM.OrgId
--						 INNER JOIN sSetup.tOrgGroupMaster OGMR ON OGMR.Id=OM.OrgGroupId
--						 INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BM.OrgGroupBatchId
--						 INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
--					 WHERE 
--						 OGM.Id = OGMR.Id  AND COGBM.Id=@rCommonOrgGroupBatchId 
--						 -- IsInContext
--						 AND BM.IsInContext = 1
--						 ) AS Total,       
----PresentStudent All Orggroup
--					 (select count(*) from sAttendance.tStudentRegister SME 
--						INNER JOIN sStudent.tAcademic AE ON SME.Academicid=AE.id 
--						INNER JOIN sStudent.tStudentMaster SM1 ON SM1.Id = AE.StudentId and SM1.StatusId=1
--						INNER JOIN sSetup.tBatchMaster BME ON BME.Id = AE.BatchId 
--						INNER JOIN sSetup.tOrganizationMaster OME ON OME.Id = BME.OrgId
--						INNER JOIN sSetup.tOrgGroupMaster OGME ON OGME.Id=OME.OrgGroupId
--						INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BME.OrgGroupBatchId
--						INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
--					  WHERE 
--						OGM.Id = OGME.Id AND COGBM.Id=@rCommonOrgGroupBatchId and SME.IsPresent=1 and SME.AttendanceDate = CONVERT(char(10), @rUptoDate,126)
--						AND (SME.AttendanceTypeId = @rAttendanceTypeId OR @rAttendanceTypeId = 0)
--						-- IsInContext
--						AND BME.IsInContext = 1
--						) AS PresentStudent,
----AbsentStudent All Orggroup
--					 (select count(*) from sAttendance.tStudentRegister SME 
--						INNER JOIN sStudent.tAcademic AE ON SME.Academicid=AE.id
--						INNER JOIN sStudent.tStudentMaster SM1 ON SM1.Id = AE.StudentId and SM1.StatusId=1
--						INNER JOIN sSetup.tBatchMaster BME ON BME.Id = AE.BatchId 
--						INNER JOIN sSetup.tOrganizationMaster OME ON OME.Id = BME.OrgId
--						INNER JOIN sSetup.tOrgGroupMaster OGMEA ON OGMEA.Id=OME.OrgGroupId
--						INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BME.OrgGroupBatchId
--						INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
--					  WHERE 
--						OGM.Id = OGMEA.Id AND COGBM.Id=@rCommonOrgGroupBatchId AND SME.IsPresent=0 and SME.AttendanceDate = CONVERT(char(10), @rUptoDate,126)
--						AND (SME.AttendanceTypeId = @rAttendanceTypeId OR @rAttendanceTypeId = 0)
--						-- IsInContext
--						AND BME.IsInContext = 1
--						) AS AbsentStudent,
----LessThen70 % All Orggroup
--				   (select Count(StudentID) from(
--						select  
--						 OGMEL.Id AS OrgGroupId,
--						 OGMEL.Title AS OrgGroupTitle,
--						 OMEL.Id AS OrgId,
--						 (OMEL.Title) AS OrgTitle ,
--						 DM.Code As DivisionCode,
--						 (SMD.Id)StudentID,
--						 (SMD.FirstName + ' ' + SMD.LastName) AS StudentName,
--						 (SC.ParentContactNo) AS ContactNo,
--						 ((count(CAST((case when IsPresent=1 then 1 end) AS float)))) As IsPresentCount,CAST(Count(AcademicId)AS float) As AcademicCount
--					FROM sAttendance.tStudentRegister SMEL
--						  INNER JOIN sStudent.tAcademic AEL ON SMEL.Academicid=AEL.id
--						  INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = AEL.BatchId 
--						  INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
--						  INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
--						  INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BMEl.OrgGroupBatchId
--						  INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId						
--						  INNER JOIN sSetup.tDivisionMaster DM ON DM.ID=AEL.DivisionID						
--						  INNER JOIN sStudent.tStudentMaster SMD ON SMD.Id=AEL.StudentID and SMD.StatusId=1						
--						  LEFT JOIN sStudent.tStudentCommunication SC on SMD.Id=SC.StudentID	     
--					where 
--						  OGM.Id = OGMEL.Id AND COGBM.Id=@rCommonOrgGroupBatchId AND		
--						  SMEL.AttendanceDate <= CONVERT(char(10), @rUptoDate,126)
--						  AND (SMEL.AttendanceTypeId = @rAttendanceTypeId OR @rAttendanceTypeId = 0)
--						  -- IsInContext
--						  AND BMEL.IsInContext = 1
--					GROUP BY 
--						 OGMEL.Id,OGMEL.Title,OMEL.Id,OMEL.Title,SMEL.AcademicId,DM.Code,SMD.Id,(SMD.FirstName+' '+SMD.LastName),(SC.ParentContactNo)
--					HAVING convert(numeric(10,2), ((count(CAST((case when IsPresent=1 then 1 end) AS float))/CAST(Count(AcademicId)AS float))*100))<70) AS Tmp
--					)  As LessThen70,
----100% Attendance All Orggroup
--				  (select Count(StudentID) from  (
--					select  
--						  OGMEL.Id AS OrgGroupId,
--						  OGMEL.Title AS OrgGroupTitle,
--						  OMEL.Id AS OrgId,
--						  (OMEL.Title) As OrgTitle ,
--						  DM.Code AS DivisionCode,
--						  (SMD.Id)StudentID,
--						  (SMD.FirstName+' '+SMD.LastName) AS StudentName,         
--						  (SC.ParentContactNo) AS ContactNo,
--						  ((count(CAST((case when IsPresent=1 then 1 end) AS float)))) As IsPresentCount,CAST(Count(AcademicId)AS float) As AcademicCount
--					FROM sAttendance.tStudentRegister SMEL
--						   INNER JOIN sStudent.tAcademic AEL ON SMEL.Academicid=AEL.id
--						   INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = AEL.BatchId
--						   INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
--						   INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId						
--						   INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BMEL.OrgGroupBatchId
--						   INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
--						   INNER JOIN sSetup.tDivisionMaster DM ON DM.ID=AEL.DivisionID						
--						   INNER JOIN sStudent.tStudentMaster SMD ON SMD.Id=AEL.StudentID and SMD.StatusId=1					
--						   LEFT JOIN sStudent.tStudentCommunication SC on SMD.Id=SC.StudentID
--					WHERE OGM.Id = OGMEL.Id AND COGBM.Id=@rCommonOrgGroupBatchId AND		
--						   SMEL.AttendanceDate <= CONVERT(char(10), @rUptoDate,126)
--						   AND (SMEL.AttendanceTypeId = @rAttendanceTypeId OR @rAttendanceTypeId = 0)
--						   -- IsInContext
--						   AND BMEL.IsInContext = 1
--					GROUP BY OGMEL.Id,OGMEL.Title,OMEL.Id,OMEL.Title,SMEL.AcademicId,DM.Code,SMD.Id,(SMD.FirstName+' '+SMD.LastName),(SC.ParentContactNo)		
--					HAVING convert(numeric(10,2), ((count(CAST((case when IsPresent=1 then 1 end) AS float))/CAST(Count(AcademicId)AS float))*100))=100) AS Tmp
--					) AS HundredPer,
----Absent>3 All Orggroup
--				   (SELECT COUNT(AcademicId) FROM(
--					  SELECT 
--						ROW_NUMBER() OVER ( PARTITION BY AcademicId ORDER BY MIN(AttendanceDate) DESC) as rowno,
--						AcademicId,AttendanceDate
--					  FROM sAttendance.tStudentRegister d 		
--						 INNER JOIN sStudent.tAcademic AEL ON d.Academicid=AEL.id
--						 INNER JOIN sStudent.tStudentMaster SM1 ON SM1.Id = AEL.StudentId and SM1.StatusId=1
--						 INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = AEL.BatchId
--						 INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
--						 INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
--						 INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BMEL.OrgGroupBatchId
--						 INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
		
--					  WHERE
--						 OGM.Id = OGMEL.Id AND COGBM.Id=@rCommonOrgGroupBatchId AND
--						 IsPresent IN(0) 
--						 AND AttendanceDate between DATEADD(DAY, -2, convert(date, @rUptoDate, 126)) AND @rUptoDate
--						 and IsPresent=0
--						 AND (d.AttendanceTypeId = @rAttendanceTypeId OR @rAttendanceTypeId = 0)
--						 -- IsInContext
--						 AND BMEL.IsInContext = 1
--					  GROUP BY AcademicId,AttendanceDate) as AbsCnt WHERE rowno=3
--					  ) AS AbsentCount,
----Leave Request All Orggroup
--					(SELECT 
--						COUNT(AcademicId) AS LeaveRequest
--					 FROM sAttendance.tStudentLeaveRequest STSL
--						INNER JOIN sStudent.tAcademic AEL ON STSL.Academicid=AEL.id
--						INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = AEL.BatchId
--						INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
--						INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
--						INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BMEL.OrgGroupBatchId
--						INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
--						INNER JOIN sSetup.tDivisionMaster DM ON DM.ID=AEL.DivisionID
--						INNER JOIN sStudent.tStudentMaster SMD ON SMD.Id=AEL.StudentID and SMD.StatusId=1
--						INNER JOIN sStudent.tStudentCommunication SC on SMD.Id=SC.StudentID
--					WHERE OGM.Id = OGMEL.Id AND COGBM.Id=@rCommonOrgGroupBatchId AND
--					CONVERT(char(10), @rUptoDate,126) between LeaveFromDate AND LeaveToDate
--					-- IsInContext
--					AND BMEL.IsInContext = 1
--					) AS LeaveRequest,
----AttnNotTakenClass All Orggroup
--					(Select count(SM1.ID)
--					 FROM sStudent.tStudentMaster SM1
--						 INNER JOIN sStudent.tAcademic A ON A.StudentId= SM1.ID and SM1.StatusId=1
--						 INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId
--						 INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = BM.OrgId
--						 INNER JOIN sSetup.tOrgGroupMaster OGMR ON OGMR.Id=OM.OrgGroupId
--						 INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BM.OrgGroupBatchId
--						 INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
         
--					 WHERE 
--						 OGM.Id = OGMR.Id  and SM1.statusid =1 AND COGBM.Id=@rCommonOrgGroupBatchId AND A.Id  not in 
--					(select AcademicId from sAttendance.tStudentRegister SR  WHERE SR.AttendanceDate = CONVERT(char(10),@rUptoDate,126) AND (SR.AttendanceTypeId = @rAttendanceTypeId OR @rAttendanceTypeId = 0))
--					-- IsInContext
--					AND BM.IsInContext = 1
--					) 
--					As AttnNotTakenClass,

--				@rUptoDate,@rCommonOrgGroupBatchId,GetDate()
--				FROM sSetup.tOrgGroupMaster OGM 
--				WHERE OGM.Id<>1 AND ISNULL(OGM.IsObsolete,0) = 0
--				AND  ((OGM.Id = @rOrgGroupId)OR(@rOrgGroupId=0))	
--			SELECT * FROM sAttendance.tTempStudentAttendance  WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0)) AND Total !=0 ORDER BY OrgGroupId
--							END
--			INSERT INTO sAttendance.tTempStudentAttendance
----Total Student All Orggroup
--				   SELECT 
--					OGM.Id AS OrgGroupId,
--					OGM.Title As OrgGroupTitle,
--					0 As OrgId,'' As OrgTitle,       
--					(Select count(SM1.ID)
--					 FROM sStudent.tStudentMaster SM1
--						 INNER JOIN sStudent.tAcademic A ON A.StudentId= SM1.ID and SM1.StatusId=1
--						 INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId 
--						 INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = BM.OrgId
--						 INNER JOIN sSetup.tOrgGroupMaster OGMR ON OGMR.Id=OM.OrgGroupId
--						 INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BM.OrgGroupBatchId
--						 INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
--					 WHERE 
--						 OGM.Id = OGMR.Id  AND COGBM.Id=@rCommonOrgGroupBatchId 
--						 ) AS Total,       
----PresentStudent All Orggroup
--					 (select count(*) from sAttendance.tStudentRegister SME 
--						INNER JOIN sStudent.tAcademic AE ON SME.Academicid=AE.id 
--						INNER JOIN sStudent.tStudentMaster SM1 ON SM1.Id = AE.StudentId and SM1.StatusId=1
--						INNER JOIN sSetup.tBatchMaster BME ON BME.Id = AE.BatchId 
--						INNER JOIN sSetup.tOrganizationMaster OME ON OME.Id = BME.OrgId
--						INNER JOIN sSetup.tOrgGroupMaster OGME ON OGME.Id=OME.OrgGroupId
--						INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BME.OrgGroupBatchId
--						INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
--					  WHERE 
--						OGM.Id = OGME.Id AND COGBM.Id=@rCommonOrgGroupBatchId and SME.IsPresent=1 and SME.AttendanceDate = CONVERT(char(10), @rUptoDate,126)
--						) AS PresentStudent,
----AbsentStudent All Orggroup
--					 (select count(*) from sAttendance.tStudentRegister SME 
--						INNER JOIN sStudent.tAcademic AE ON SME.Academicid=AE.id
--						INNER JOIN sStudent.tStudentMaster SM1 ON SM1.Id = AE.StudentId and SM1.StatusId=1
--						INNER JOIN sSetup.tBatchMaster BME ON BME.Id = AE.BatchId 
--						INNER JOIN sSetup.tOrganizationMaster OME ON OME.Id = BME.OrgId
--						INNER JOIN sSetup.tOrgGroupMaster OGMEA ON OGMEA.Id=OME.OrgGroupId
--						INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BME.OrgGroupBatchId
--						INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
--					  WHERE 
--						OGM.Id = OGMEA.Id AND COGBM.Id=@rCommonOrgGroupBatchId AND SME.IsPresent=0 and SME.AttendanceDate = CONVERT(char(10), @rUptoDate,126)
--						) AS AbsentStudent,
----LessThen70 % All Orggroup
--				   (select Count(StudentID) from(
--						select  
--						 OGMEL.Id AS OrgGroupId,
--						 OGMEL.Title AS OrgGroupTitle,
--						 OMEL.Id AS OrgId,
--						 (OMEL.Title) AS OrgTitle ,
--						 DM.Code As DivisionCode,
--						 (SMD.Id)StudentID,
--						 (SMD.FirstName + ' ' + SMD.LastName) AS StudentName,
--						 (SC.ParentContactNo) AS ContactNo,
--						 ((count(CAST((case when IsPresent=1 then 1 end) AS float)))) As IsPresentCount,CAST(Count(AcademicId)AS float) As AcademicCount
--					FROM sAttendance.tStudentRegister SMEL
--						  INNER JOIN sStudent.tAcademic AEL ON SMEL.Academicid=AEL.id
--						  INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = AEL.BatchId 
--						  INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
--						  INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
--						  INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BMEl.OrgGroupBatchId
--						  INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId						
--						  INNER JOIN sSetup.tDivisionMaster DM ON DM.ID=AEL.DivisionID						
--						  INNER JOIN sStudent.tStudentMaster SMD ON SMD.Id=AEL.StudentID and SMD.StatusId=1						
--						  LEFT JOIN sStudent.tStudentCommunication SC on SMD.Id=SC.StudentID	     
--					where 
--						  OGM.Id = OGMEL.Id AND COGBM.Id=@rCommonOrgGroupBatchId AND		
--						  SMEL.AttendanceDate <= CONVERT(char(10), @rUptoDate,126)
--					GROUP BY 
--						 OGMEL.Id,OGMEL.Title,OMEL.Id,OMEL.Title,SMEL.AcademicId,DM.Code,SMD.Id,(SMD.FirstName+' '+SMD.LastName),(SC.ParentContactNo)
--					HAVING convert(numeric(10,2), ((count(CAST((case when IsPresent=1 then 1 end) AS float))/CAST(Count(AcademicId)AS float))*100))<70) AS Tmp
--					)  As LessThen70,
----100% Attendance All Orggroup
--				  (select Count(StudentID) from  (
--					select  
--						  OGMEL.Id AS OrgGroupId,
--						  OGMEL.Title AS OrgGroupTitle,
--						  OMEL.Id AS OrgId,
--						  (OMEL.Title) As OrgTitle ,
--						  DM.Code AS DivisionCode,
--						  (SMD.Id)StudentID,
--						  (SMD.FirstName+' '+SMD.LastName) AS StudentName,         
--						  (SC.ParentContactNo) AS ContactNo,
--						  ((count(CAST((case when IsPresent=1 then 1 end) AS float)))) As IsPresentCount,CAST(Count(AcademicId)AS float) As AcademicCount
--					FROM sAttendance.tStudentRegister SMEL
--						   INNER JOIN sStudent.tAcademic AEL ON SMEL.Academicid=AEL.id
--						   INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = AEL.BatchId
--						   INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
--						   INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId						
--						   INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BMEL.OrgGroupBatchId
--						   INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
--						   INNER JOIN sSetup.tDivisionMaster DM ON DM.ID=AEL.DivisionID						
--						   INNER JOIN sStudent.tStudentMaster SMD ON SMD.Id=AEL.StudentID and SMD.StatusId=1					
--						   LEFT JOIN sStudent.tStudentCommunication SC on SMD.Id=SC.StudentID
--					WHERE OGM.Id = OGMEL.Id AND COGBM.Id=@rCommonOrgGroupBatchId AND		
--						   SMEL.AttendanceDate <= CONVERT(char(10), @rUptoDate,126)
--					GROUP BY OGMEL.Id,OGMEL.Title,OMEL.Id,OMEL.Title,SMEL.AcademicId,DM.Code,SMD.Id,(SMD.FirstName+' '+SMD.LastName),(SC.ParentContactNo)		
--					HAVING convert(numeric(10,2), ((count(CAST((case when IsPresent=1 then 1 end) AS float))/CAST(Count(AcademicId)AS float))*100))=100) AS Tmp
--					) AS HundredPer,
----Absent>3 All Orggroup
--				   (SELECT COUNT(AcademicId) FROM(
--					  SELECT 
--						ROW_NUMBER() OVER ( PARTITION BY AcademicId ORDER BY MIN(AttendanceDate) DESC) as rowno,
--						AcademicId,AttendanceDate
--					  FROM sAttendance.tStudentRegister d 		
--						 INNER JOIN sStudent.tAcademic AEL ON d.Academicid=AEL.id
--						 INNER JOIN sStudent.tStudentMaster SM1 ON SM1.Id = AEL.StudentId and SM1.StatusId=1
--						 INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = AEL.BatchId
--						 INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
--						 INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
--						 INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BMEL.OrgGroupBatchId
--						 INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
		
--					  WHERE
--						 OGM.Id = OGMEL.Id AND COGBM.Id=@rCommonOrgGroupBatchId AND
--						 IsPresent IN(0) 
--						 AND AttendanceDate between DATEADD(DAY, -2, convert(date, @rUptoDate, 126)) AND @rUptoDate
--						 and IsPresent=0
--					  GROUP BY AcademicId,AttendanceDate) as AbsCnt WHERE rowno=3
--					  ) AS AbsentCount,
----Leave Request All Orggroup
--					(SELECT 
--						COUNT(AcademicId) AS LeaveRequest
--					 FROM sAttendance.tStudentLeaveRequest STSL
--						INNER JOIN sStudent.tAcademic AEL ON STSL.Academicid=AEL.id
--						INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = AEL.BatchId
--						INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
--						INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
--						INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BMEL.OrgGroupBatchId
--						INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
--						INNER JOIN sSetup.tDivisionMaster DM ON DM.ID=AEL.DivisionID
--						INNER JOIN sStudent.tStudentMaster SMD ON SMD.Id=AEL.StudentID and SMD.StatusId=1
--						INNER JOIN sStudent.tStudentCommunication SC on SMD.Id=SC.StudentID
--					WHERE OGM.Id = OGMEL.Id AND COGBM.Id=@rCommonOrgGroupBatchId AND
--					CONVERT(char(10), @rUptoDate,126) between LeaveFromDate AND LeaveToDate
--					) AS LeaveRequest,
----AttnNotTakenClass All Orggroup
--					(Select count(SM1.ID)
--					 FROM sStudent.tStudentMaster SM1
--						 INNER JOIN sStudent.tAcademic A ON A.StudentId= SM1.ID and SM1.StatusId=1
--						 INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId
--						 INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = BM.OrgId
--						 INNER JOIN sSetup.tOrgGroupMaster OGMR ON OGMR.Id=OM.OrgGroupId
--						 INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BM.OrgGroupBatchId
--						 INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
         
--					 WHERE 
--						 OGM.Id = OGMR.Id  and SM1.statusid =1 AND COGBM.Id=@rCommonOrgGroupBatchId AND A.Id  not in 
--					(select AcademicId from sAttendance.tStudentRegister SR  WHERE SR.AttendanceDate = CONVERT(char(10),@rUptoDate,126))) 
--					As AttnNotTakenClass,

--				@rUptoDate,@rCommonOrgGroupBatchId,GetDate()
--				FROM sSetup.tOrgGroupMaster OGM 
--				WHERE OGM.Id<>1 AND OGM.IsObsolete = 0
--				AND  ((OGM.Id = @rOrgGroupId)OR(@rOrgGroupId=0))	
--			SELECT * FROM sAttendance.tTempStudentAttendance  WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0)) AND Total !=0 ORDER BY OrgGroupId
		END
	ELSE
----Temp Atble Attendance
		BEGIN
			DELETE  sAttendance.tTempStudentAttendance WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId  AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))
			--IF EXISTS (SELECT 1 FROM sAttendance.tTempStudentAttendance WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0)))
			--				BEGIN
							IF(@rOrgGroupId !=0)
			INSERT INTO sAttendance.tTempStudentAttendance
--Total Student All Orggroup Temp		
				   SELECT 
					OGM.Id AS OrgGroupId,
					OGM.Title As OrgGroupTitle,
					0 As OrgId,'' As OrgTitle,       
					(Select count(SM1.ID)
					 FROM sStudent.tStudentMaster SM1
						 INNER JOIN sStudent.tAcademic A ON A.StudentId= SM1.ID and SM1.StatusId=1
						 INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId
						 INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = BM.OrgId
						 INNER JOIN sSetup.tOrgGroupMaster OGMR ON OGMR.Id=OM.OrgGroupId
						 INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BM.OrgGroupBatchId
						 INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
					 WHERE 
						 OGM.Id = OGMR.Id  AND COGBM.Id=@rCommonOrgGroupBatchId 
						 -- IsInContext
						 AND BM.IsInContext = 1
						 ) AS Total,       
--PresentStudent All Orggroup Temp
					 (select count(*) from sAttendance.tStudentRegister SME 
						INNER JOIN sStudent.tAcademic AE ON SME.Academicid=AE.id
						INNER JOIN sStudent.tStudentMaster SM1 ON SM1.Id = AE.StudentId and SM1.StatusId=1
						INNER JOIN sSetup.tBatchMaster BME ON BME.Id = AE.BatchId
						INNER JOIN sSetup.tOrganizationMaster OME ON OME.Id = BME.OrgId
						INNER JOIN sSetup.tOrgGroupMaster OGME ON OGME.Id=OME.OrgGroupId
						INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BME.OrgGroupBatchId
						INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
					  WHERE 
						OGM.Id = OGME.Id AND COGBM.Id=@rCommonOrgGroupBatchId and SME.IsPresent=1 and SME.AttendanceDate = CONVERT(char(10), @rUptoDate,126)
						-- IsInContext
						AND BME.IsInContext = 1
						) AS PresentStudent,
--AbsentStudent All Orggroup Temp
					 (select count(*) from sAttendance.tStudentRegister SME 
						INNER JOIN sStudent.tAcademic AE ON SME.Academicid=AE.id
						INNER JOIN sStudent.tStudentMaster SM1 ON SM1.Id = AE.StudentId and SM1.StatusId=1
						INNER JOIN sSetup.tBatchMaster BME ON BME.Id = AE.BatchId
						INNER JOIN sSetup.tOrganizationMaster OME ON OME.Id = BME.OrgId
						INNER JOIN sSetup.tOrgGroupMaster OGMEA ON OGMEA.Id=OME.OrgGroupId
						INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BME.OrgGroupBatchId
						INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
					  WHERE 
						OGM.Id = OGMEA.Id AND COGBM.Id=@rCommonOrgGroupBatchId AND SME.IsPresent=0 and SME.AttendanceDate = CONVERT(char(10), @rUptoDate,126)
						-- IsInContext
						AND BME.IsInContext = 1
						) AS AbsentStudent,
--LessThen70 All Orggroup Temp
				   (select Count(StudentID) from(
						select  
						 OGMEL.Id AS OrgGroupId,
						 OGMEL.Title AS OrgGroupTitle,
						 OMEL.Id AS OrgId,
						 (OMEL.Title) AS OrgTitle ,
						 DM.Code As DivisionCode,
						 (SMD.Id)StudentID,
						 (SMD.FirstName + ' ' + SMD.LastName) AS StudentName,
						 (SC.ParentContactNo) AS ContactNo,
						 ((count(CAST((case when IsPresent=1 then 1 end) AS float)))) As IsPresentCount,CAST(Count(AcademicId)AS float) As AcademicCount
					FROM sAttendance.tStudentRegister SMEL
						  INNER JOIN sStudent.tAcademic AEL ON SMEL.Academicid=AEL.id
						  INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = AEL.BatchId
						  INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
						  INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
						  INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BMEl.OrgGroupBatchId
						  INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId						
						  INNER JOIN sSetup.tDivisionMaster DM ON DM.ID=AEL.DivisionID						
						  INNER JOIN sStudent.tStudentMaster SMD ON SMD.Id=AEL.StudentID and SMD.StatusId=1					
						  LEFT JOIN sStudent.tStudentCommunication SC on SMD.Id=SC.StudentID	     
					where 
						  OGM.Id = OGMEL.Id AND COGBM.Id=@rCommonOrgGroupBatchId AND		
						  SMEL.AttendanceDate <= CONVERT(char(10), @rUptoDate,126)
						  -- IsInContext
						  AND BMEL.IsInContext = 1
					GROUP BY 
						 OGMEL.Id,OGMEL.Title,OMEL.Id,OMEL.Title,SMEL.AcademicId,DM.Code,SMD.Id,(SMD.FirstName+' '+SMD.LastName),(SC.ParentContactNo)
		
					HAVING convert(numeric(10,2), ((count(CAST((case when IsPresent=1 then 1 end) AS float))/CAST(Count(AcademicId)AS float))*100))<70) AS Tmp
					)As LessThen70,
--100 % HundredPer All Orggroup Temp
				  (select Count(StudentID) from  (
					select  
						  OGMEL.Id AS OrgGroupId,
						  OGMEL.Title AS OrgGroupTitle,
						  OMEL.Id AS OrgId,
						  (OMEL.Title) As OrgTitle ,
						  DM.Code AS DivisionCode,
						  (SMD.Id)StudentID,
						  (SMD.FirstName+' '+SMD.LastName) AS StudentName,         
						  (SC.ParentContactNo) AS ContactNo,
						  ((count(CAST((case when IsPresent=1 then 1 end) AS float)))) As IsPresentCount,CAST(Count(AcademicId)AS float) As AcademicCount
					FROM sAttendance.tStudentRegister SMEL
						   INNER JOIN sStudent.tAcademic AEL ON SMEL.Academicid=AEL.id
						   INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = AEL.BatchId
						   INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
						   INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId						
						   INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BMEL.OrgGroupBatchId
						   INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
						   INNER JOIN sSetup.tDivisionMaster DM ON DM.ID=AEL.DivisionID						
						   INNER JOIN sStudent.tStudentMaster SMD ON SMD.Id=AEL.StudentID	and SMD.StatusId=1					
						   LEFT JOIN sStudent.tStudentCommunication SC on SMD.Id=SC.StudentID
					WHERE OGM.Id = OGMEL.Id AND COGBM.Id=@rCommonOrgGroupBatchId AND		
						   SMEL.AttendanceDate <= CONVERT(char(10), @rUptoDate,126)
						   -- IsInContext
						   AND BMEL.IsInContext = 1
					GROUP BY OGMEL.Id,OGMEL.Title,OMEL.Id,OMEL.Title,SMEL.AcademicId,DM.Code,SMD.Id,(SMD.FirstName+' '+SMD.LastName),(SC.ParentContactNo)		
					HAVING convert(numeric(10,2), ((count(CAST((case when IsPresent=1 then 1 end) AS float))/CAST(Count(AcademicId)AS float))*100))=100) AS Tmp
					) AS HundredPer,
--AbsentCount All Orggroup Temp
				   (SELECT COUNT(AcademicId) FROM(
					  SELECT 
						ROW_NUMBER() OVER ( PARTITION BY AcademicId ORDER BY MIN(AttendanceDate) DESC) as rowno,
						AcademicId,AttendanceDate
					  FROM sAttendance.tStudentRegister d 		
						 INNER JOIN sStudent.tAcademic AEL ON d.Academicid=AEL.id
						 INNER JOIN sStudent.tStudentMaster SM1 ON SM1.Id = AEL.StudentId and SM1.StatusId=1
						 INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = AEL.BatchId
						 INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
						 INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
						 INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BMEL.OrgGroupBatchId
						 INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
					  WHERE
						 OGM.Id = OGMEL.Id AND COGBM.Id=@rCommonOrgGroupBatchId AND
						 IsPresent IN(0) 
						 AND AttendanceDate between DATEADD(DAY, -2, convert(date, @rUptoDate, 126)) AND @rUptoDate
						 and IsPresent=0
						 -- IsInContext
						 AND BMEL.IsInContext = 1
					  GROUP BY AcademicId,AttendanceDate) as AbsCnt WHERE rowno=3
					  ) AS AbsentCount,
--LeaveRequest All Orggroup Temp
					(SELECT COUNT(AcademicId) AS LeaveRequest
					FROM sAttendance.tStudentLeaveRequest STSL
						INNER JOIN sStudent.tAcademic AEL ON STSL.Academicid=AEL.id
						INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = AEL.BatchId
						INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
						INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
						INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BMEL.OrgGroupBatchId
						INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
						INNER JOIN sSetup.tDivisionMaster DM ON DM.ID=AEL.DivisionID
						INNER JOIN sStudent.tStudentMaster SMD ON SMD.Id=AEL.StudentID and SMD.StatusId=1
						INNER JOIN sStudent.tStudentCommunication SC on SMD.Id=SC.StudentID
					WHERE OGM.Id = OGMEL.Id AND COGBM.Id=@rCommonOrgGroupBatchId AND
					CONVERT(char(10), @rUptoDate,126) between LeaveFromDate AND LeaveToDate
					-- IsInContext
					AND BMEL.IsInContext = 1
					) AS LeaveRequest,
--AttnNotTakenClass All Orggroup Temp
					(Select count(SM1.ID)
					FROM sStudent.tStudentMaster SM1
						 INNER JOIN sStudent.tAcademic A ON A.StudentId= SM1.ID and SM1.StatusId=1
						 INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId
						 INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = BM.OrgId
						 INNER JOIN sSetup.tOrgGroupMaster OGMR ON OGMR.Id=OM.OrgGroupId
						 INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BM.OrgGroupBatchId
						 INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
					 WHERE 
						 OGM.Id = OGMR.Id  
						 and SM1.statusid =1 
						 AND COGBM.Id=@rCommonOrgGroupBatchId 
						 AND A.Id  not in (select AcademicId from sAttendance.tStudentRegister SR  WHERE SR.AttendanceDate = CONVERT(char(10),@rUptoDate,126) AND (SR.AttendanceTypeId = @rAttendanceTypeId OR @rAttendanceTypeId = 0))
						 -- IsInContext
						 AND BM.IsInContext = 1
					) 
					As AttnNotTakenClass,
				@rUptoDate AS StudentAttendanceDate
				,@rCommonOrgGroupBatchId AS CommonOrgGroupBatchId
				,GetDate() as UpdateDate
				FROM sSetup.tOrgGroupMaster OGM 
				WHERE OGM.Id<>1 AND  ((OGM.Id = @rOrgGroupId)OR(@rOrgGroupId=0))
			SELECT * FROM sAttendance.tTempStudentAttendance  WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0)) AND Total !=0
							--END
			
		END
	END

--Organization wise Attendance

ELSE IF @rTypeId=2
    BEGIN
    SELECT 
       OGMT.Id As OrgGroupId,
       OM.Id AS OrgId, 
       OM.Title AS OrgTitle,
       OGMT.Title As OrgGroupTitle,
       
--Total Organization wise
		   (Select count(SM1.ID)
			FROM sStudent.tStudentMaster SM1
				 INNER JOIN sStudent.tAcademic A ON A.StudentId= SM1.ID and SM1.StatusId=1
				 INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId
				 INNER JOIN sSetup.tOrganizationMaster OMR ON OM.Id = BM.OrgId
				 INNER JOIN sSetup.tOrgGroupMaster OGM ON OGM.Id=OM.OrgGroupId		
				 INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
				 INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
			WHERE OM.Id = OMR.Id AND COGBM.Id=@rCommonOrgGroupBatchId
			      -- IsInContext
			      AND BM.IsInContext = 1
				 ) as Total,

--PresentStudent Organization wise
		 (SELECT count(*) 
			FROM sAttendance.tStudentRegister SME 
			   INNER JOIN sStudent.tAcademic AE ON SME.Academicid=AE.id
			   INNER JOIN sStudent.tStudentMaster SM1 ON SM1.Id = AE.StudentId and SM1.StatusId=1
			   INNER JOIN sSetup.tBatchMaster BME ON BME.Id = AE.BatchId
			   INNER JOIN sSetup.tOrganizationMaster OME ON OME.Id = BME.OrgId
			   INNER JOIN sSetup.tOrgGroupMaster OGME ON OGME.Id=OME.OrgGroupId
			   INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BME.OrgGroupBatchId
			   INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
			WHERE OM.Id = OME.Id and SME.IsPresent=1 AND SME.AttendanceDate = CONVERT(char(10), @rUptoDate,126) AND COGBM.Id=@rCommonOrgGroupBatchId
			AND (SME.AttendanceTypeId = @rAttendanceTypeId OR @rAttendanceTypeId = 0)
			-- IsInContext
			AND BME.IsInContext = 1
			) AS PresentStudent,

--AbsentStudent Organization wise
		  (SELECT count(*) 
			FROM sAttendance.tStudentRegister SME 
				INNER JOIN sStudent.tAcademic AE ON SME.Academicid=AE.id
				INNER JOIN sStudent.tStudentMaster SM1 ON SM1.Id = AE.StudentId and SM1.StatusId=1
				INNER JOIN sSetup.tBatchMaster BME ON BME.Id = AE.BatchId
				INNER JOIN sSetup.tOrganizationMaster OME ON OME.Id = BME.OrgId
				INNER JOIN sSetup.tOrgGroupMaster OGMEA ON OGMEA.Id=OME.OrgGroupId
				INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BME.OrgGroupBatchId
				INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
			WHERE OM.Id = OME.Id AND SME.IsPresent=0 AND COGBM.Id=@rCommonOrgGroupBatchId AND SME.AttendanceDate = CONVERT(char(10), @rUptoDate,126)
			AND (SME.AttendanceTypeId = @rAttendanceTypeId OR @rAttendanceTypeId = 0)
			-- IsInContext
			AND BME.IsInContext = 1
			) AS AbsentStudent,
        
--LessThen70 Organization wise
			(SELECT COUNT(StudentID) 
			   FROM (
				 SELECT   
				   OGMEL.Id as OrgGroupId,
				   OGMEL.Title As OrgGroupTitle,
				   OMEL.Id As OrgId,
				   (OMEL.Title) As OrgTitle ,
				   DM.Code As DivisionCode,
				   (SMD.Id)StudentID,
				   (SMD.FirstName+' '+SMD.LastName) AS StudentName,
					(SC.ParentContactNo) AS ContactNo,
					((COUNT(CAST((case when IsPresent=1 then 1 end) AS float)))) As IsPresentCount,CAST(Count(AcademicId)AS float) As AcademicCount
				 FROM sAttendance.tStudentRegister SMEL
					INNER JOIN sStudent.tAcademic AEL ON SMEL.Academicid=AEL.id
					INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = AEL.BatchId
					INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
					INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId	
					INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BMEL.OrgGroupBatchId
					INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId					
					INNER JOIN sSetup.tDivisionMaster DM ON DM.ID=AEL.DivisionID						
					INNER JOIN sStudent.tStudentMaster SMD ON SMD.Id=AEL.StudentID	and SMD.StatusId=1					
					LEFT JOIN sStudent.tStudentCommunication SC on SMD.Id=SC.StudentID
			     
				WHERE OM.Id = OMEL.Id AND SMEL.AttendanceDate <= CONVERT(char(10), @rUptoDate,126) AND COGBM.Id=@rCommonOrgGroupBatchId
				AND (SMEL.AttendanceTypeId = @rAttendanceTypeId OR @rAttendanceTypeId = 0)
				-- IsInContext
				AND BMEL.IsInContext = 1
				GROUP BY OGMEL.Id,OGMEL.Title,OMEL.Id,OMEL.Title,SMEL.AcademicId,DM.Code,SMD.Id,(SMD.FirstName+' '+SMD.LastName),(SC.ParentContactNo)		
			   HAVING convert(numeric(10,2), ((count(CAST((case when IsPresent=1 then 1 end) AS float))/CAST(Count(AcademicId)AS float))*100))<70
			   ) AS Tmp)  
			   As LessThen70,
        
--HundredPer Organization wise
			 (SELECT COUNT(StudentID) from  (
				 SELECT  
				 OGMEL.Id as OrgGroupId,
				 OGMEL.Title As OrgGroupTitle,
				 OMEL.Id As OrgId,
				 (OMEL.Title) As OrgTitle ,
				 DM.Code As DivisionCode,
				 (SMD.Id)StudentID,(SMD.FirstName+' '+SMD.LastName) AS StudentName,
				 (SC.ParentContactNo) AS ContactNo,
				 ((count(CAST((case when IsPresent=1 then 1 end) AS float)))) As IsPresentCount,CAST(Count(AcademicId)AS float) As AcademicCount
			 
			 FROM sAttendance.tStudentRegister SMEL
				 INNER JOIN sStudent.tAcademic AEL ON SMEL.Academicid=AEL.id
				 INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = AEL.BatchId
				 INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
				 INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
				 INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BMEL.OrgGroupBatchId
				 INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId						
				 INNER JOIN sSetup.tDivisionMaster DM ON DM.ID=AEL.DivisionID						
				 INNER JOIN sStudent.tStudentMaster SMD ON SMD.Id=AEL.StudentID	and SMD.StatusId=1						
				 LEFT JOIN sStudent.tStudentCommunication SC on SMD.Id=SC.StudentID
			     
			 WHERE OM.Id = OMEL.Id AND
				   SMEL.AttendanceDate <= CONVERT(char(10), @rUptoDate,126) AND COGBM.Id=@rCommonOrgGroupBatchId 
				   AND (SMEL.AttendanceTypeId = @rAttendanceTypeId OR @rAttendanceTypeId = 0)
				   -- IsInContext
				   AND BMEL.IsInContext = 1
			 GROUP BY OGMEL.Id,OGMEL.Title,OMEL.Id,OMEL.Title,SMEL.AcademicId,DM.Code,SMD.Id,(SMD.FirstName+' '+SMD.LastName),(SC.ParentContactNo)
				
				
			 HAVING convert(numeric(10,2), ((count(CAST((case when IsPresent=1 then 1 end) AS float))/CAST(Count(AcademicId)AS float))*100))=100
			 ) AS Tmp)  
			 As HundredPer,
        
--AbsentCount Organization wise
			(SELECT COUNT(AcademicId) FROM(
				SELECT 
				  ROW_NUMBER() OVER ( PARTITION BY AcademicId ORDER BY MIN(AttendanceDate) DESC) as rowno,
				  AcademicId,
				  AttendanceDate
				FROM sAttendance.tStudentRegister d 
				 INNER JOIN sStudent.tAcademic AEL ON d.Academicid=AEL.id
				 INNER JOIN sStudent.tStudentMaster SM1 ON SM1.Id = AEL.StudentId and SM1.StatusId=1
				 INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = AEL.BatchId
				 INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
				 INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
				 INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BMEL.OrgGroupBatchId
				 INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId				
				WHERE OM.Id = OMEL.Id AND
				IsPresent IN(0) 
				AND AttendanceDate between DATEADD(DAY, -2, convert(date, @rUptoDate, 126)) AND @rUptoDate
				AND IsPresent=0 AND COGBM.Id=@rCommonOrgGroupBatchId
				AND (d.AttendanceTypeId = @rAttendanceTypeId OR @rAttendanceTypeId = 0)
				-- IsInContext
				AND BMEL.IsInContext = 1
				GROUP BY AcademicId,AttendanceDate
				) as sfsf
				WHERE rowno=3) 
				as AbsentCount,
        
--LeaveRequest Organization wise
			 (SELECT 
				COUNT(AcademicId) AS LeaveRequest
				FROM sAttendance.tStudentLeaveRequest STSL
				  INNER JOIN sStudent.tAcademic AEL ON STSL.Academicid=AEL.id
				  INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = AEL.BatchId
				  INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
				  INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
				  INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BMEL.OrgGroupBatchId
				  INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
				  INNER JOIN sSetup.tDivisionMaster DM ON DM.ID=AEL.DivisionID
				  INNER JOIN sStudent.tStudentMaster SMD ON SMD.Id=AEL.StudentID and SMD.StatusId=1
				  INNER JOIN sStudent.tStudentCommunication SC on SMD.Id=SC.StudentID

				WHERE OM.Id = OMEL.Id AND COGBM.Id=@rCommonOrgGroupBatchId AND
				CONVERT(char(10), @rUptoDate,126) between LeaveFromDate AND LeaveToDate
				-- IsInContext
				AND BMEL.IsInContext = 1)
				As LeaveRequest,
        
--AttnNotTakenClass Organization wise
			(Select count(SM1.ID)
					 FROM sStudent.tStudentMaster SM1
						 INNER JOIN sStudent.tAcademic A ON A.StudentId= SM1.ID and SM1.StatusId=1
						 INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId
						 INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BM.OrgId
						 INNER JOIN sSetup.tOrgGroupMaster OGMR ON OGMR.Id=OMEL.OrgGroupId
						 INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BM.OrgGroupBatchId
						 INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
         
					 WHERE 
						 OM.Id = OMEL.Id  AND COGBM.Id=@rCommonOrgGroupBatchId AND A.Id  not in 
					(select AcademicId from sAttendance.tStudentRegister SR  WHERE SR.AttendanceDate = CONVERT(char(10),@rUptoDate,126) AND (SR.AttendanceTypeId = @rAttendanceTypeId OR @rAttendanceTypeId = 0))
					-- IsInContext
					AND BM.IsInContext = 1
					) 
					As AttnNotTakenClass,
			getdate() AS UpdateDate		  
              
     FROM sSetup.tOrgGroupMaster OGMT 
        INNER join sSetup.tOrganizationMaster OM ON OGMT.Id=OM.OrgGroupId 
        --INNER JOIN sSecurity.tUserOrganization U ON U.OrgId = OM.Id  Comment for Mantis Id:0036412
     WHERE OGMT.Id=@rOrgGroupId 
	    -- AND U.UserId = @rUserId   Comment for Mantis Id:0036412
    ORDER BY OM.OrderIndex
    END

ELSE IF @rTypeId=11
	BEGIN
     	SELECT OGMR.Id AS OrgGroupId,
			OGMR.Title AS OrgGroupTitle,
			OM.Id As OrgId,(OM.Title) AS OrgTitle,
			CM.ID AS ClassId,CM.Code AS ClassCode,
			0 AS SourceId,
			COUNT(A.StudentID) AS TotalStudent,
			COUNT(CASE WHEN SOD.GenderID=1 then 1 end) AS Male,
			COUNT(CASE WHEN SOD.GenderID=2 then 1 end) AS Female,
			OM.OrderIndex
		FROM sStudent.tStudentMaster SM
			INNER JOIN sStudent.tAcademic A ON A.StudentId= SM.ID and SM.StatusId=1 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = BM.OrgId
			INNER JOIN sSetup.tOrgGroupMaster OGMR ON OGMR.Id=OM.OrgGroupId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BM.OrgGroupBatchId
			INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
			INNER JOIN sSetup.tClassMaster CM ON CM.ID=A.ClassId
			LEFT JOIN sStudent.tStudentOther SOD ON SOD.StudentId=A.StudentId
		WHERE OGMR.Id=@rOrgGroupId
			AND COGBM.Id=@rCommonOrgGroupBatchId 
			-- IsInContext
			AND BM.IsInContext = 1
		GROUP BY OGMR.Id ,OGMR.Title,OM.Id ,OM.Title,CM.ID,CM.Code,OM.OrderIndex,CM.OrderIndex
		ORDER BY OM.OrderIndex,CM.OrderIndex-- CM.OrderIndex :add for mantis : 0042058	
    END

ELSE IF @rTypeId=21
    BEGIN
		SELECT OGMR.Id as OrgGroupId,
			OGMR.Title As OrgGroupTitle,
			OM.Id As OrgId,(OM.Title) As OrgTitle,
			CM.ID AS ClassId,CM.Code AS ClassCode,
			0 AS SourceId,
			COUNT(A.StudentID) AS TotalStudent,
			COUNT(case when SOD.GenderID=1 then 1 end) AS Male,
			COUNT(case when SOD.GenderID=2 then 1 end) AS Female,
			OM.OrderIndex
		FROM sStudent.tStudentMaster SM
			INNER JOIN sStudent.tAcademic A ON A.StudentId= SM.ID and SM.StatusId=1 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = BM.OrgId
			INNER JOIN sSetup.tOrgGroupMaster OGMR ON OGMR.Id=OM.OrgGroupId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BM.OrgGroupBatchId
			INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
			INNER JOIN sSetup.tClassMaster CM ON CM.ID=A.ClassId
			LEFT JOIN sStudent.tStudentOther SOD ON SOD.StudentId=A.StudentId
		WHERE OM.Id=@rOrgId
			AND COGBM.Id=@rCommonOrgGroupBatchId
			-- IsInContext
			AND BM.IsInContext = 1 
		GROUP BY OGMR.Id ,OGMR.Title,OM.Id ,OM.Title,CM.ID,CM.Code,OM.OrderIndex
		ORDER BY OM.OrderIndex
     END
     
ELSE IF @rTypeId=12
    BEGIN
		SELECT OGME.Id as OrgGroupId,
			OGME.Title As OrgGroupTitle,
			OME.Id As OrgId,(OME.Title) As OrgTitle,
			CM.ID AS ClassId,CM.Code AS ClassCode,
			0 AS SourceId,
			COUNT(AE.StudentID) AS TotalStudent,
			COUNT(case when SOD.GenderID=1 then 1 end) AS Male,
			COUNT(case when SOD.GenderID=2 then 1 end) AS Female,
			OME.OrderIndex				 
		FROM sAttendance.tStudentRegister SME 
			INNER JOIN sStudent.tAcademic AE ON SME.Academicid=AE.id
			INNER JOIN sSetup.tBatchMaster BME ON BME.Id = AE.BatchId
			INNER JOIN sSetup.tOrganizationMaster OME ON OME.Id = BME.OrgId
			INNER JOIN sSetup.tOrgGroupMaster OGME ON OGME.Id=OME.OrgGroupId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BME.OrgGroupBatchId
			INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId		
			INNER JOIN sSetup.tClassMaster CM ON CM.ID=AE.ClassId
			INNER JOIN sStudent.tStudentMaster SMD ON SMD.Id=AE.StudentID and SMD.StatusId=1	
			LEFT JOIN sStudent.tStudentOther SOD ON SOD.StudentId=SMD.Id
		WHERE OGME.Id=@rOrgGroupId and SME.IsPresent=1 AND COGBM.Id=@rCommonOrgGroupBatchId   
			and SME.AttendanceDate = CONVERT(char(10), @rUptoDate,126)
			AND (SME.AttendanceTypeId = @rAttendanceTypeId OR @rAttendanceTypeId = 0)
			-- IsInContext
			AND BME.IsInContext = 1 
		GROUP BY OGME.Id,OGME.Title,OME.Id,OME.Title,CM.ID,CM.Code,OME.OrderIndex,CM.OrderIndex-- CM.OrderIndex :add for mantis : 0042058	
		ORDER BY OME.OrderIndex, CM.OrderIndex -- CM.OrderIndex :add for mantis : 0042058	
	
         
    END
   
ELSE IF @rTypeId=22
	BEGIN
          SELECT 
				OGME.Id as OrgGroupId,OGME.Title As OrgGroupTitle,
				OME.Id As OrgId,(OME.Title) As OrgTitle,
				 CM.ID AS ClassId,CM.Code AS ClassCode,
				 0 AS SourceId,
				COUNT(AE.StudentID) AS TotalStudent,
				COUNT(case when SOD.GenderID=1 then 1 end) as Male,
				COUNT(case when SOD.GenderID=2 then 1 end) as Female
		  FROM sAttendance.tStudentRegister SME 
				INNER JOIN sStudent.tAcademic AE ON SME.Academicid=AE.id
				INNER JOIN sSetup.tBatchMaster BME ON BME.Id = AE.BatchId
				INNER JOIN sSetup.tOrganizationMaster OME ON OME.Id = BME.OrgId
				INNER JOIN sSetup.tOrgGroupMaster OGME ON OGME.Id=OME.OrgGroupId
				INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BME.OrgGroupBatchId
			    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
				INNER JOIN sSetup.tClassMaster CM ON CM.ID=AE.ClassId
				INNER JOIN sStudent.tStudentMaster SMD ON SMD.Id=AE.StudentID and SMD.StatusId=1	
				LEFT JOIN sStudent.tStudentOther SOD ON SOD.StudentId=SMD.Id 
		  WHERE OME.Id=@rOrgId and SME.IsPresent=1 AND COGBM.Id=@rCommonOrgGroupBatchId  
				AND SME.AttendanceDate = CONVERT(char(10), @rUptoDate,126)
				AND (SME.AttendanceTypeId = @rAttendanceTypeId OR @rAttendanceTypeId = 0)
				-- IsInContext
				AND BME.IsInContext = 1 
		  GROUP BY OGME.Id,OGME.Title,OME.Id,OME.Title,CM.ID,CM.Code          
	END
   
ELSE IF @rTypeId=13
      BEGIN
      
          SELECT 
				OGMEA.Id as OrgGroupId,
				OGMEA.Title As OrgGroupTitle,
				OME.Id As OrgId,
				(OME.Title) As OrgTitle,
				CM.ID As ClassId,
				CM.Code As ClassCode,
				0 AS SourceId,
				COUNT(AE.StudentID) AS TotalStudent,
			    COUNT(case when SOD.GenderID=1 then 1 end) as Male,
				COUNT(case when SOD.GenderID=2 then 1 end) as Female,
				OME.OrderIndex
			FROM sAttendance.tStudentRegister SME 
				INNER JOIN sStudent.tAcademic AE ON SME.Academicid=AE.id
				INNER JOIN sSetup.tBatchMaster BME ON BME.Id = AE.BatchId
				INNER JOIN sSetup.tOrganizationMaster OME ON OME.Id = BME.OrgId
				INNER JOIN sSetup.tOrgGroupMaster OGMEA ON OGMEA.Id=OME.OrgGroupId
				INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BME.OrgGroupBatchId
			    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
				INNER JOIN sSetup.tClassMaster CM ON CM.ID=AE.ClassID
				INNER JOIN sStudent.tStudentMaster SMD ON SMD.Id=AE.StudentID and SMD.StatusId=1	
				Left JOIN sStudent.tStudentOther SOD ON SOD.StudentId=SMD.Id
			WHERE OGMEA.Id=@rOrgGroupId and SME.IsPresent=0  AND COGBM.Id=@rCommonOrgGroupBatchId  
				 and SME.AttendanceDate = CONVERT(char(10), @rUptoDate,126)
				 AND (SME.AttendanceTypeId = @rAttendanceTypeId OR @rAttendanceTypeId = 0)
				 -- IsInContext
				 AND BME.IsInContext = 1 
			GROUP BY OGMEA.Id,OGMEA.Title,OME.Id,OME.Title,CM.ID,CM.Code,OME.OrderIndex,CM.OrderIndex-- CM.OrderIndex :add for mantis : 0042058	
			ORDER BY OME.OrderIndex, CM.OrderIndex -- CM.OrderIndex :add for mantis : 0042058	
			
		 
       END
       
ELSE IF @rTypeId=23
       BEGIN
          (SELECT 
				OGMEA.Id as OrgGroupId,
				OGMEA.Title As OrgGroupTitle,
				OME.Id As OrgId,
				(OME.Title) As OrgTitle,
				CM.ID AS ClassId,CM.Code AS ClassCode,
				0 AS SourceId,
				COUNT(AE.StudentID) AS TotalStudent,
				COUNT(case when SOD.GenderID=1 then 1 end) as Male,
				COUNT(case when SOD.GenderID=2 then 1 end) as Female
		   FROM sAttendance.tStudentRegister SME 
				INNER JOIN sStudent.tAcademic AE ON SME.Academicid=AE.id
				INNER JOIN sSetup.tBatchMaster BME ON BME.Id = AE.BatchId
				INNER JOIN sSetup.tOrganizationMaster OME ON OME.Id = BME.OrgId
				INNER JOIN sSetup.tOrgGroupMaster OGMEA ON OGMEA.Id=OME.OrgGroupId
				INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BME.OrgGroupBatchId
			    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
				INNER JOIN sSetup.tClassMaster CM ON CM.ID=AE.ClassId
				INNER JOIN sStudent.tStudentMaster SMD ON SMD.Id=AE.StudentID and SMD.StatusId=1	
				LEFT JOIN sStudent.tStudentOther SOD ON SOD.StudentId=SMD.Id
		   WHERE OME.Id=@rOrgId 
				AND SME.IsPresent=0 AND SME.AttendanceDate = CONVERT(char(10), @rUptoDate,126) AND COGBM.Id=@rCommonOrgGroupBatchId  
				AND (SME.AttendanceTypeId = @rAttendanceTypeId OR @rAttendanceTypeId = 0)
				-- IsInContext
				AND BME.IsInContext = 1
		   GROUP BY OGMEA.Id,OGMEA.Title,OME.Id,OME.Title,CM.ID,CM.Code
		  )
    
       END       
       
ELSE IF @rTypeId=14  
      BEGIN
			
       (SELECT *FROM  (
          SELECT 
				OGMEL.Id as OrgGroupId,
				OGMEL.Title As OrgGroupTitle,
				OMEL.Id As OrgId,
				(OMEL.Title) As OrgTitle,
				DM.Code As DivisionCode,
				(SMD.Code)StudentID,
				AEL.Id AS SourceId,
				(SMD.FirstName+' '+SMD.LastName) AS StudentName,
				(SC.ParentContactNo) AS ContactNo
					FROM sAttendance.tStudentRegister SMEL
						  INNER JOIN sStudent.tAcademic AEL ON SMEL.Academicid=AEL.id
						  INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = AEL.BatchId 
						  INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
						  INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
						  INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BMEl.OrgGroupBatchId
						  INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId						
						  INNER JOIN sSetup.tDivisionMaster DM ON DM.ID=AEL.DivisionID						
						  INNER JOIN sStudent.tStudentMaster SMD ON SMD.Id=AEL.StudentID and SMD.StatusId=1						
						  LEFT JOIN sStudent.tStudentCommunication SC on SMD.Id=SC.StudentID	     
					where 
						  OGMEL.Id=@rOrgGroupId AND COGBM.Id=@rCommonOrgGroupBatchId AND		
						  SMEL.AttendanceDate <= CONVERT(char(10), @rUptoDate,126)
						  AND (SMEL.AttendanceTypeId = @rAttendanceTypeId OR @rAttendanceTypeId = 0)
						  -- IsInContext
						  AND BMEL.IsInContext = 1
						  --GROUP BY SMD.Id
					 GROUP BY AEL.Id,OGMEL.Id,OGMEL.Title,OMEL.Id,OMEL.Title,SMEL.AcademicId,DM.Code,SMD.code,(SMD.FirstName+' '+SMD.LastName),(SC.ParentContactNo)
					HAVING convert(numeric(10,2), ((count(CAST((case when IsPresent=1 then 1 end) AS float))/CAST(Count(AcademicId)AS float))*100))<70
	   ) AS Tmp) 

      END
   
ELSE IF @rTypeId=24     
      BEGIN

      (SELECT *FROM  (
           SELECT 
              OGMEL.Id as OrgGroupId,
              OGMEL.Title As OrgGroupTitle,
              OMEL.Id As OrgId,
              (OMEL.Title) As OrgTitle,
              DM.Code As DivisionCode,
              (SMD.Code)StudentID,
        AEL.Id AS SourceId,
              (SMD.FirstName+' '+SMD.LastName) AS StudentName,
			  (SC.ParentContactNo) AS ContactNo
	   FROM sAttendance.tStudentRegister SMEL
			   INNER JOIN sStudent.tAcademic AEL ON SMEL.Academicid=AEL.id
			   INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = AEL.BatchId
			   INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
			   INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
			   INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BMEL.OrgGroupBatchId
			    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId			
			   INNER JOIN sSetup.tDivisionMaster DM ON DM.ID=AEL.DivisionID
			   INNER JOIN sStudent.tStudentMaster SMD ON SMD.Id=AEL.StudentID and SMD.StatusId=1	
			   LEFT JOIN sStudent.tStudentCommunication SC on SMD.Id=SC.StudentID
		WHERE OMEL.Id=@rOrgId AND
		      SMEL.AttendanceDate <= CONVERT(char(10), @rUptoDate,126) AND COGBM.Id=@rCommonOrgGroupBatchId  
			  AND (SMEL.AttendanceTypeId = @rAttendanceTypeId OR @rAttendanceTypeId = 0)
			  -- IsInContext
			  AND BMEL.IsInContext = 1
		GROUP BY AEL.Id,OGMEL.Id,OGMEL.Title,OMEL.Id,OMEL.Title,SMEL.AcademicId,DM.Code,SMD.Code,(SMD.FirstName+' '+SMD.LastName),(SC.ParentContactNo)

	  HAVING convert(numeric(10,2), ((count(CAST((case when IsPresent=1 then 1 end) AS float))/CAST(Count(AcademicId)AS float))*100))<70
	 ) AS Tmp) 
		
          
      END   
   
ELSE IF @rTypeId=15
	   BEGIN	
		(SELECT *FROM(
              SELECT  
                  OGMEL.Id as OrgGroupId,
                  OGMEL.Title As OrgGroupTitle,
                  OMEL.Id As OrgId,(OMEL.Title) As OrgTitle,
                  DM.Code As DivisionCode,
                  (SMD.Code)StudentID,
                  (SMD.FirstName+' '+SMD.LastName) AS StudentName,
				  (SC.ParentContactNo) AS ContactNo,
				  AEL.Id AS SourceId
		      FROM sAttendance.tStudentRegister SMEL
				   INNER JOIN sStudent.tAcademic AEL ON SMEL.Academicid=AEL.id
				   INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = AEL.BatchId --AND BMEL.IsActive = 1
				   INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
				   INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
				   INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BMEL.OrgGroupBatchId
			       INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId						
				   INNER JOIN sSetup.tDivisionMaster DM ON DM.ID=AEL.DivisionID
				   INNER JOIN sStudent.tStudentMaster SMD ON SMD.Id=AEL.StudentID and SMD.StatusId=1	
				   Left JOIN sStudent.tStudentCommunication SC on SMD.Id=SC.StudentID
			   WHERE OGMEL.Id=@rOrgGroupId AND
				   SMEL.AttendanceDate <= CONVERT(char(10), @rUptoDate,126) AND COGBM.Id=@rCommonOrgGroupBatchId
				   AND (SMEL.AttendanceTypeId = @rAttendanceTypeId OR @rAttendanceTypeId = 0)
				   -- IsInContext
				   AND BMEL.IsInContext = 1
			   GROUP BY AEL.Id,OGMEL.Id,OGMEL.Title,OMEL.Id,OMEL.Title,SMEL.AcademicId,DM.Code,SMD.Code,(SMD.FirstName+' '+SMD.LastName),(SC.ParentContactNo)
	      HAVING convert(numeric(10,2), ((count(CAST((case when IsPresent=1 then 1 end) AS float))/CAST(Count(AcademicId)AS float))*100))=100
	    ) AS Tmp) 
	   END
	   
ELSE IF @rTypeId=25
	BEGIN	
	 (SELECT *FROM(
           SELECT  
                OGMEL.Id as OrgGroupId,
                OGMEL.Title As OrgGroupTitle,
                OMEL.Id As OrgId,
                (OMEL.Title) As OrgTitle,
                DM.Code As DivisionCode,
                (SMD.Code)StudentID,
                (SMD.FirstName+' '+SMD.LastName) AS StudentName,
				(SC.ParentContactNo) AS ContactNo,
				AEL.Id AS SourceId
			FROM sAttendance.tStudentRegister SMEL
				INNER JOIN sStudent.tAcademic AEL ON SMEL.Academicid=AEL.id
				INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = AEL.BatchId
				INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
				INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
				INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BMEL.OrgGroupBatchId
			    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
				INNER JOIN sSetup.tDivisionMaster DM ON DM.ID=AEL.DivisionID
				INNER JOIN sStudent.tStudentMaster SMD ON SMD.Id=AEL.StudentID and SMD.StatusId=1	
				Left JOIN sStudent.tStudentCommunication SC on SMD.Id=SC.StudentID
		    WHERE OMEL.Id=@rOrgId AND
				  SMEL.AttendanceDate <= CONVERT(char(10), @rUptoDate,126) AND COGBM.Id=@rCommonOrgGroupBatchId
				  AND (SMEL.AttendanceTypeId = @rAttendanceTypeId OR @rAttendanceTypeId = 0)
				  -- IsInContext
				  AND BMEL.IsInContext = 1
			GROUP BY AEL.Id,OGMEL.Id,OGMEL.Title,OMEL.Id,OMEL.Title,SMEL.AcademicId,DM.Code,SMD.Code,(SMD.FirstName+' '+SMD.LastName),(SC.ParentContactNo)
	    HAVING convert(numeric(10,2), ((count(CAST((case when IsPresent=1 then 1 end) AS float))/CAST(Count(AcademicId)AS float))*100))=100
	  ) AS Tmp) 

	   END
	   	   
ELSE IF @rTypeId=16   
   BEGIN
        
        (SELECT * FROM 
             (SELECT 
				OGMEL.Id as OrgGroupId,
				OGMEL.Title As OrgGroupTitle,
				OMEL.Id As OrgId,(OMEL.Title) As OrgTitle,
				DM.Code As DivisionCode,
				(SMD.Code)StudentID,
				(SMD.FirstName+' '+SMD.LastName) AS StudentName,
				(SC.ParentContactNo) AS ContactNo,
						 AEL.Id AS SourceId
			  FROM sAttendance.tStudentLeaveRequest STSL
				INNER JOIN sStudent.tAcademic AEL ON STSL.Academicid=AEL.id
				INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = AEL.BatchId
				INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
				INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
				INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BMEL.OrgGroupBatchId
			    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
				INNER JOIN sSetup.tDivisionMaster DM ON DM.ID=AEL.DivisionID
				INNER JOIN sStudent.tStudentMaster SMD ON SMD.Id=AEL.StudentID and SMD.StatusId=1	
				INNER JOIN sStudent.tStudentCommunication SC on SMD.Id=SC.StudentID	
			  WHERE OGMEL.Id=@rOrgGroupId 
				AND COGBM.Id=@rCommonOrgGroupBatchId 
				AND CONVERT(char(10), @rUptoDate,126) between LeaveFromDate 
				AND LeaveToDate
				-- IsInContext
				AND BMEL.IsInContext = 1
		) as a) 
   END
      
ELSE IF @rTypeId=26   
   BEGIN
      
      (SELECT * FROM 
          (SELECT 
			  OGMEL.Id as OrgGroupId,
			  OGMEL.Title As OrgGroupTitle,
			  OMEL.Id As OrgId,(OMEL.Title) As OrgTitle,
			  DM.Code As DivisionCode,(SMD.Code)StudentID,
			  (SMD.FirstName+' '+SMD.LastName) AS StudentName,
			  (SC.ParentContactNo) AS ContactNo,
			  AEL.Id AS SourceId
		   FROM sAttendance.tStudentLeaveRequest STSL 
			   INNER JOIN sStudent.tAcademic AEL ON STSL.Academicid=AEL.id
			   INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = AEL.BatchId
			   INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
			   INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
			   INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BMEL.OrgGroupBatchId
			   INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
			   INNER JOIN sSetup.tDivisionMaster DM ON DM.ID=AEL.DivisionID
			   INNER JOIN sStudent.tStudentMaster SMD ON SMD.Id=AEL.StudentID and SMD.StatusId=1	
			   INNER JOIN sStudent.tStudentCommunication SC on SMD.Id=SC.StudentID		 
		   WHERE OMEL.Id=@rOrgId 
				AND COGBM.Id=@rCommonOrgGroupBatchId 
				AND CONVERT(char(10), @rUptoDate,126) between LeaveFromDate 
				AND LeaveToDate
				-- IsInContext
				AND BMEL.IsInContext = 1
		) as a) 
   END
   
ELSE IF @rTypeId=17   
   BEGIN
       
       (SELECT OrgGroupId,
                OrgGroupTitle,
                OrgId,
                OrgTitle,
                Code As DivisionCode,
                StudentID,
                SourceId,
                StudentName,
                ContactNo FROM( SELECT ROW_NUMBER() OVER ( PARTITION BY AcademicId ORDER BY MIN(AttendanceDate) DESC) as rowno,
				OGMEL.Id as OrgGroupId,
				OGMEL.Title As OrgGroupTitle,
				OMEL.Id As OrgId,
				(OMEL.Title) As OrgTitle,
				AcademicId AS SourceId,
				AttendanceDate, 
				DM.Code,
				(SMD.Code)StudentID,
				(SMD.FirstName+' '+SMD.LastName) AS StudentName,(SC.ParentContactNo) As ContactNo
			 FROM sAttendance.tStudentRegister d 							
		 		INNER JOIN sStudent.tAcademic AEL ON d.Academicid=AEL.id
				INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = AEL.BatchId
				INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
				INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
				INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BMEL.OrgGroupBatchId
			    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
				INNER JOIN sSetup.tDivisionMaster DM ON DM.ID=AEL.DivisionID
				INNER JOIN sStudent.tStudentMaster SMD ON SMD.Id=AEL.StudentID and SMD.StatusId=1	
				INNER JOIN sStudent.tStudentCommunication SC on SMD.Id=SC.StudentID
		     WHERE
				OGMEL.Id=@rOrgGroupId AND
				IsPresent IN(0) 
				AND AttendanceDate between DATEADD(DAY, -2, convert(date, @rUptoDate, 126)) AND @rUptoDate   
				AND IsPresent=0 AND COGBM.Id=@rCommonOrgGroupBatchId
				AND (d.AttendanceTypeId = @rAttendanceTypeId OR @rAttendanceTypeId = 0)
				-- IsInContext
				AND BMEL.IsInContext = 1
			 Group By AEL.Id,OGMEL.Id,OGMEL.Title,OMEL.Id,OMEL.Title,AcademicId,AttendanceDate, DM.Code,(SMD.Code),(SMD.FirstName+' '+SMD.LastName),SC.ParentContactNo 
			 ) as T
		WHERE rowno=3) 
   END
      
ELSE IF @rTypeId=27   
   BEGIN
       
        (SELECT OrgGroupId,
                OrgGroupTitle,
                OrgId,OrgTitle, 
                Code As DivisionCode,SourceId,
                StudentID,StudentName,
                ContactNo  FROM(
			SELECT 
				ROW_NUMBER() OVER ( PARTITION BY AcademicId ORDER BY MIN(AttendanceDate) DESC) as rowno,
				OGMEL.Id as OrgGroupId,
				OGMEL.Title As OrgGroupTitle,
				OMEL.Id As OrgId,(OMEL.Title) As OrgTitle,
                AcademicId AS SourceId,AttendanceDate, 
                DM.Code,
                (SMD.Code)StudentID,
                (SMD.FirstName+' '+SMD.LastName) AS StudentName,
                (SC.ParentContactNo) As ContactNo		
			FROM sAttendance.tStudentRegister d 		
		 		INNER JOIN sStudent.tAcademic AEL ON d.Academicid=AEL.id
				INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = AEL.BatchId
				INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
				INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
				INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BMEL.OrgGroupBatchId
			    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
				INNER JOIN sSetup.tDivisionMaster DM ON DM.ID=AEL.DivisionID
				INNER JOIN sStudent.tStudentMaster SMD ON SMD.Id=AEL.StudentID and SMD.StatusId=1	
				INNER JOIN sStudent.tStudentCommunication SC on SMD.Id=SC.StudentID		
			WHERE
				OMEL.Id=@rOrgId AND
				IsPresent IN(0) 
				AND AttendanceDate between DATEADD(DAY, -2, convert(date, @rUptoDate, 126)) AND @rUptoDate
			    AND IsPresent=0 AND COGBM.Id=@rCommonOrgGroupBatchId
				AND (d.AttendanceTypeId = @rAttendanceTypeId OR @rAttendanceTypeId = 0)
				-- IsInContext
				AND BMEL.IsInContext = 1
			Group By AEL.Id,OGMEL.Id,OGMEL.Title,OMEL.Id,OMEL.Title,AcademicId,AttendanceDate, DM.Code,(SMD.Code),(SMD.FirstName+' '+SMD.LastName),SC.ParentContactNo
			) as sfsf
	   WHERE rowno=3) 
        
   END
   
ELSE IF @rTypeId=18
   BEGIN
			SELECT 
				OrgGroupId,
				OrgGroupTitle,
				OrgId,
				OrgTitle,
				ClassCode,
				StudentCount,
				SourceId,
				ISNULL(TeacherName,'') AS TeacherName,
				ISNULL(ContactNo,'')AS ContactNo  FROM(SELECT 
				O.Id as OrgGroupId,
				O.Title As OrgGroupTitle,
				OMEL.Id As OrgId,
				(OMEL.Title) As OrgTitle,
				A.ClassId,
				DM.Code AS ClassCode,
				CM.OrderIndex as ClassOrderIndex	--add for mantis : 0042058
				,DM.OrderIndex AS DivisionOrderIndex,	--add for mantis : 0042058
				--(SELECT COUNT(A.Id) FROM sStudent.tAcademic A INNER JOIN sStudent.tStudentMaster SM  ON SM.Id= A.StudentId AND SM.StatusId =1 WHERE  
				--DivisionId= DM.Id AND BatchId = BM.Id) AS StudentCount,
				(Select count(SM1.ID)
					 FROM sStudent.tStudentMaster SM1
						 INNER JOIN sStudent.tAcademic A1 ON A1.StudentId= SM1.ID and SM1.StatusId=1
						 INNER JOIN sSetup.tBatchMaster BM1 ON BM1.Id = A1.BatchId
						 INNER JOIN sSetup.tOrganizationMaster OM1 ON OM1.Id = BM1.OrgId
						 INNER JOIN sSetup.tOrgGroupMaster OGMR1 ON OGMR1.Id=OM1.OrgGroupId
						 INNER JOIN sSetup.tOrgGroupBatchMaster OGBM1 ON OGBM1.Id=BM1.OrgGroupBatchId
						 INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM1 ON COGBM1.Id=OGBM1.CommonOrgGroupBatchId
         
					 WHERE 
						 O.Id = OGMR1.Id  and SM1.statusid =1 AND COGBM1.Id=@rCommonOrgGroupBatchId 
						 AND DivisionId= DM.Id AND BatchId = BM.Id AND A1.Id  not in 
					(select AcademicId from sAttendance.tStudentRegister SR1  WHERE SR1.AttendanceDate = CONVERT(char(10),@rUptoDate,126) AND (SR1.AttendanceTypeId = @rAttendanceTypeId OR @rAttendanceTypeId = 0))
						-- IsInContext
						AND BM1.IsInContext = 1
					) 
					As StudentCount,
				--(SELECT COUNT(Id) FROM sStudent.tAcademic WHERE DivisionId= A.DivisionId AND BatchId = A.BatchId) AS StudentCount,
				A.Id As SourceId,
				(EM.FirstName+' '+Em.LastName) AS TeacherName,(EC.MobileNumber) AS ContactNo,
				ROW_NUMBER() OVER ( PARTITION BY A.DivisionId,A.OrgId order by A.DivisionId) as rowno
			FROM sStudent.tAcademic A
				INNER JOIN sStudent.tStudentMaster SM  ON SM.Id= A.StudentId AND SM.StatusId =1
				INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId
				INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BM.OrgId
				INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
				INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
				INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
				INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId
				LEFT JOIN sHrm.tEmployeeMaster EM ON EM.ID=DM.InchargeEmployeeId
				LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
				INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId	--add for mantis : 0042058
			WHERE  O.id = @rOrgGroupId AND  ISNULL(EM.IsOtherUser,0) = 0 AND COGBM.Id=@rCommonOrgGroupBatchId AND    A.Id  not in  ( select AcademicId from sAttendance.tStudentRegister SR  WHERE SR.AttendanceDate = CONVERT(char(10),  @rUptoDate,126))
				   -- IsInContext
				   AND BM.IsInContext = 1
				) Temp 
		WHERE rowno=1  
		ORDER BY OrgId,
		--ClassCode desc
		ClassOrderIndex, DivisionOrderIndex --add for mantis : 0042058
		
   END
     
ELSE IF @rTypeId=28
   
   BEGIN

	SELECT 
				OrgGroupId,
				OrgGroupTitle,
				OrgId,
				OrgTitle,
				ClassCode,
				StudentCount,
				SourceId,
				ISNULL(TeacherName,'') AS TeacherName,
				ISNULL(ContactNo,'')AS ContactNo  FROM(SELECT 
				O.Id as OrgGroupId,
				O.Title As OrgGroupTitle,
				OMEL.Id As OrgId,
				(OMEL.Title) As OrgTitle,
				A.ClassId,
				DM.Code AS ClassCode,
				(SELECT COUNT(Id) FROM sStudent.tAcademic WHERE DivisionId= A.DivisionId AND BatchId = A.BatchId) AS StudentCount,
				A.Id As SourceId,
				(EM.FirstName+' '+Em.LastName) AS TeacherName,(EC.MobileNumber) AS ContactNo,
				ROW_NUMBER() OVER ( PARTITION BY A.DivisionId,A.OrgId order by A.DivisionId) as rowno
				FROM sStudent.tAcademic A
				INNER JOIN sStudent.tStudentMaster SM  ON SM.Id= A.StudentId AND SM.StatusId =1
				INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId
				INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BM.OrgId
				INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
				INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
				INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
				INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId
				LEFT JOIN sHrm.tEmployeeMaster EM ON EM.ID=DM.InchargeEmployeeId
				LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
				WHERE  OMEL.id = @rOrgId AND  ISNULL(EM.IsOtherUser,0) = 0 AND COGBM.Id=@rCommonOrgGroupBatchId AND    A.Id  not in  ( select AcademicId from sAttendance.tStudentRegister SR  WHERE SR.AttendanceDate = CONVERT(char(10),  @rUptoDate,126) AND (SR.AttendanceTypeId = @rAttendanceTypeId OR @rAttendanceTypeId = 0))
				-- IsInContext
				AND BM.IsInContext = 1
				) Temp 
				WHERE 
				rowno=1  
				ORDER BY OrgId,ClassCode desc
	   
   END

ELSE IF @rTypeId=1110
   BEGIN
	  SELECT 
	      (DM.Id) AS DivisionId,
	       SMD.Code As StudentId,
	       A.Id AS SourceId,
	       (SMD.FirstName+' '+SMD.LastName) AS StudentName,
		   (SC.ParentContactNo) AS ContactNo
							
	  FROM sSetup.tDivisionMaster DM
			INNER JOIN sStudent.tAcademic A ON A.DivisionID=DM.id
			INNER JOIN sStudent.tStudentMaster SMD ON SMD.Id=A.StudentID and SMD.StatusId=1	
			INNER JOIN sStudent.tStudentOther SOD ON SOD.StudentId=SMD.Id
			INNER JOIN sStudent.tStudentCommunication SC on SMD.Id=SC.StudentID
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId
	   WHERE DM.ID=@rDivisionId 
			 AND DM.OrgId=@rOrgId
			 AND BM.IsInContext = 1
	   ORDER BY SMD.Code												          
   END

ELSE IF @rTypeId=1111
	BEGIN
      SELECT 
         (DM.Id) AS DivisionId,
         SMD.Code As StudentId,
         A.Id AS SourceId,
         (SMD.FirstName+' '+SMD.LastName) AS StudentName,
		 (SC.ParentContactNo) AS ContactNo
								
	  FROM sSetup.tDivisionMaster DM
		 INNER JOIN sStudent.tAcademic A ON A.DivisionID=DM.id
		 INNER JOIN sStudent.tStudentMaster SMD ON SMD.Id=A.StudentID and SMD.StatusId=1	
		 INNER JOIN sStudent.tStudentOther SOD ON SOD.StudentId=SMD.Id
		 INNER JOIN sStudent.tStudentCommunication SC on SMD.Id=SC.StudentID
		 INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId
	   WHERE DM.ID=@rDivisionId 
			AND SOD.GenderID=1 
			AND BM.IsInContext = 1
	   ORDER BY SMD.Code           
	END
	
ELSE IF @rTypeId=1112
	BEGIN	  
	  SELECT 
	    (DM.Id) AS DivisionId,
	    A.Id AS SourceId,
	    SMD.Code As StudentId,
	    (SMD.FirstName+' '+SMD.LastName) AS StudentName,
		(SC.ParentContactNo) AS ContactNo								
	  FROM sSetup.tDivisionMaster DM
		INNER JOIN sStudent.tAcademic A ON A.DivisionID=DM.id
		INNER JOIN sStudent.tStudentMaster SMD ON SMD.Id=A.StudentID and SMD.StatusId=1	
		INNER JOIN sStudent.tStudentOther SOD ON SOD.StudentId=SMD.Id
		INNER JOIN sStudent.tStudentCommunication SC on SMD.Id=SC.StudentID	
		INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId
	  WHERE DM.ID=@rDivisionId 
		AND SOD.GenderID=2 
		AND BM.IsInContext = 1
	  ORDER BY SMD.Code
	END 
	
  END
  ELSE
    BEGIN

     if @rTypeId=11 OR @rTypeId=21     
        BEGIN
			SELECT 
				(DM.Id) AS DivisionId,
				DM.Code AS ClassDivision,
				SM.Code As StudentId,
				A.Id AS SourceId,
				(SM.FirstName+' '+SM.LastName) AS StudentName,
				(SC.ParentContactNo) AS ContactNo
			FROM sStudent.tStudentMaster SM 
				INNER JOIN sStudent.tAcademic A ON A.StudentId= SM.ID and SM.StatusId=1 
				INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId
				INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = BM.OrgId
				INNER JOIN sSetup.tOrgGroupMaster OGMR ON OGMR.Id=OM.OrgGroupId
				INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BM.OrgGroupBatchId
				INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
				INNER JOIN sSetup.tClassMaster CM ON CM.ID=A.ClassId
				INNER JOIN sSetup.tDivisionMaster DM ON DM.ID=A.DivisionID
				LEFT JOIN sStudent.tStudentOther SOD ON SOD.StudentId=A.StudentId
				Left JOIN sStudent.tStudentCommunication SC on SM.Id=SC.StudentID
			WHERE 
				((@rOrgGroupId <>0 AND OGMR.Id=@rOrgGroupId) OR (@rOrgId<>0 AND OM.Id=@rOrgId))
				AND DM.ClassId=@rClassId AND COGBM.Id=@rCommonOrgGroupBatchId
				AND ((@rGenderType=1 AND SOD.GenderID=1) OR (@rGenderType=2 AND SOD.GenderID=2) OR (@rGenderType=0 AND 0=0))
				-- IsInContext
				AND BM.IsInContext = 1
		    ORDER BY SM.Code
        END
        
     ELSE IF @rTypeId=12 OR @rTypeId=22
      
        BEGIN
         
            SELECT 				
			   (DM.Id) AS DivisionId,
			   DM.Code AS ClassDivision,
			    SMD.Code As StudentId,
			    AE.Id AS SourceId,
			    (SMD.FirstName+' '+SMD.LastName) AS StudentName,
			    (SC.ParentContactNo) AS ContactNo
			FROM sAttendance.tStudentRegister SME 
				INNER JOIN sStudent.tAcademic AE ON SME.Academicid=AE.id
				INNER JOIN sSetup.tBatchMaster BME ON BME.Id = AE.BatchId
				INNER JOIN sSetup.tOrganizationMaster OME ON OME.Id = BME.OrgId
				INNER JOIN sSetup.tOrgGroupMaster OGME ON OGME.Id=OME.OrgGroupId
				INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BME.OrgGroupBatchId
                INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
				INNER JOIN sSetup.tDivisionMaster DM ON DM.ID=AE.DivisionID
				INNER JOIN sStudent.tStudentMaster SMD ON SMD.Id=AE.StudentID
				INNER JOIN sStudent.tStudentOther SOD ON SOD.StudentId=SMD.Id and SMD.StatusId=1	
				Left JOIN sStudent.tStudentCommunication SC on SMD.Id=SC.StudentID
			WHERE ((@rOrgGroupId <>0 AND OGME.Id=@rOrgGroupId) OR (@rOrgId<>0 AND OME.Id=@rOrgId))
					AND SME.IsPresent=1 AND COGBM.Id=@rCommonOrgGroupBatchId 
					AND SME.AttendanceDate=CONVERT(char(10), @rUpToDate,126)
					AND DM.ClassId=@rClassId AND COGBM.Id=@rCommonOrgGroupBatchId  
				    AND((@rGenderType=1 AND SOD.GenderID=1) OR (@rGenderType=2 AND SOD.GenderID=2) OR (@rGenderType=0 AND 0=0))
					AND (SME.AttendanceTypeId = @rAttendanceTypeId OR @rAttendanceTypeId = 0)
					-- IsInContext
					AND BME.IsInContext = 1
			ORDER BY SMD.Code
       END  
    
     ELSE IF @rTypeId=13 OR @rTypeId=23
        BEGIN
         select 
			(DM.Id) AS DivisionId,
			   DM.Code AS ClassDivision,
			    SMD.Code As StudentId,
			    AE.Id AS SourceId,
			    (SMD.FirstName+' '+SMD.LastName) AS StudentName,
			    (SC.ParentContactNo) AS ContactNo
		  FROM sAttendance.tStudentRegister SME 
			 INNER JOIN sStudent.tAcademic AE ON SME.Academicid=AE.id
			 INNER JOIN sSetup.tBatchMaster BME ON BME.Id = AE.BatchId --AND BME.IsActive = 1
			 INNER JOIN sSetup.tOrganizationMaster OME ON OME.Id = BME.OrgId
			 INNER JOIN sSetup.tOrgGroupMaster OGMEA ON OGMEA.Id=OME.OrgGroupId
			 INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BME.OrgGroupBatchId
             INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
			 INNER JOIN sSetup.tDivisionMaster DM ON DM.ID=AE.DivisionID
			 INNER JOIN sStudent.tStudentMaster SMD ON SMD.Id=AE.StudentID and SMD.StatusId=1	
			 INNER JOIN sStudent.tStudentOther SOD ON SOD.StudentId=SMD.Id
			 Left JOIN sStudent.tStudentCommunication SC on SMD.Id=SC.StudentID
					
		   WHERE ((@rOrgGroupId <>0 AND OGMEA.Id=@rOrgGroupId) OR (@rOrgId<>0 AND OME.Id=@rOrgId))
					AND SME.IsPresent=0 AND COGBM.Id=@rCommonOrgGroupBatchId AND COGBM.Id=@rCommonOrgGroupBatchId  
					AND SME.AttendanceDate=CONVERT(char(10), @rUpToDate,126)--@rUptoDate
					AND DM.ClassId=@rClassId AND ((@rGenderType=1 AND SOD.GenderID=1) OR (@rGenderType=2 AND SOD.GenderID=2) OR (@rGenderType=0 AND 0=0))
					AND (SME.AttendanceTypeId = @rAttendanceTypeId OR @rAttendanceTypeId = 0)
					-- IsInContext
					AND BME.IsInContext = 1
		  ORDER BY SMD.Code
        END
    END
END
GO
PRINT N'Altering Procedure [sAttendance].[pStudentAttendaceDashboardNewGet]...';


GO
ALTER PROCEDURE [sAttendance].[pStudentAttendaceDashboardNewGet]
	 
	 @rTypeId smallint,
	 @rFromDate date=NULL,
	 @rToDate date=NULL,
	 @rOrgGroupId int=0,
	 @rOrgId int=0,
	 @rDivisionId int=0,
	 @rClassId int =0,
	 @rGenderType int=0,
	 @rCommonOrgGroupBatchId int=0,
	 @rSyncDate int =0,
	 @rUserId Bigint,
	 @rAttendanceTypeId int = 0

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

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

SELECT @lConfigValueDashboard = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 592 AND SourceTypeId = 2010 AND SourceId = @rOrgGroupId;

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


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

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

--Orggroup wise Attendance
   IF @rTypeId=1 
   BEGIN
		  SELECT 
					OGM.Id AS OrgGroupId,
					OGM.Title As OrgGroupTitle,
					0 As OrgId,'' As OrgTitle,       
					(Select count(SM1.ID)
					 FROM sStudent.tStudentMaster SM1
						 INNER JOIN sStudent.tAcademic A ON A.StudentId= SM1.ID and SM1.StatusId=1
						 INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId 
						 INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = BM.OrgId
						 INNER JOIN sSetup.tOrgGroupMaster OGMR ON OGMR.Id=OM.OrgGroupId
						 INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BM.OrgGroupBatchId
						 INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
					 WHERE 
						 OGM.Id = OGMR.Id  AND COGBM.Id=@rCommonOrgGroupBatchId 
						  -- IsInContext
						  AND BM.IsInContext = 1
						 ) AS Total,       
--PresentStudent All Orggroup
					 (select count(*) from sAttendance.tStudentRegister SME 
						INNER JOIN sStudent.tAcademic AE ON SME.Academicid=AE.id 
						INNER JOIN sStudent.tStudentMaster SM1 ON SM1.Id = AE.StudentId and SM1.StatusId=1
						INNER JOIN sSetup.tBatchMaster BME ON BME.Id = AE.BatchId 
						INNER JOIN sSetup.tOrganizationMaster OME ON OME.Id = BME.OrgId
						INNER JOIN sSetup.tOrgGroupMaster OGME ON OGME.Id=OME.OrgGroupId
						INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BME.OrgGroupBatchId
						INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
					  WHERE 
						OGM.Id = OGME.Id AND COGBM.Id=@rCommonOrgGroupBatchId and SME.IsPresent=1 
						--and SME.AttendanceDate = CONVERT(char(10), @rUptoDate,126)
						AND	((SME.AttendanceDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = '')) AND
						((SME.AttendanceDate <= @rToDate) OR (ISNULL(@rToDate,'') = ''))
						AND (SME.AttendanceTypeId = @rAttendanceTypeId OR @rAttendanceTypeId = 0)
						-- IsInContext
						AND BME.IsInContext = 1
						) AS PresentStudent,
--AbsentStudent All Orggroup
					 (select count(*) from sAttendance.tStudentRegister SME 
						INNER JOIN sStudent.tAcademic AE ON SME.Academicid=AE.id
						INNER JOIN sStudent.tStudentMaster SM1 ON SM1.Id = AE.StudentId and SM1.StatusId=1
						INNER JOIN sSetup.tBatchMaster BME ON BME.Id = AE.BatchId 
						INNER JOIN sSetup.tOrganizationMaster OME ON OME.Id = BME.OrgId
						INNER JOIN sSetup.tOrgGroupMaster OGMEA ON OGMEA.Id=OME.OrgGroupId
						INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BME.OrgGroupBatchId
						INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
					  WHERE 
						OGM.Id = OGMEA.Id AND COGBM.Id=@rCommonOrgGroupBatchId AND SME.IsPresent=0 
						--and SME.AttendanceDate = CONVERT(char(10), @rUptoDate,126)
						AND ((SME.AttendanceDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = '')) AND
						((SME.AttendanceDate <= @rToDate) OR (ISNULL(@rToDate,'') = ''))
						AND (SME.AttendanceTypeId = @rAttendanceTypeId OR @rAttendanceTypeId = 0)
						-- IsInContext
						AND BME.IsInContext = 1
						) AS AbsentStudent,
--LessThen70 % All Orggroup
				   (select Count(StudentID) from(
						select  (SMD.Id)StudentID
						 
					FROM sAttendance.tStudentRegister SMEL
						  INNER JOIN sStudent.tAcademic AEL ON SMEL.Academicid=AEL.id
						  INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = AEL.BatchId 
						  INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
						  INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
						  INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BMEl.OrgGroupBatchId
						  INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId						
						  INNER JOIN sSetup.tDivisionMaster DM ON DM.ID=AEL.DivisionID						
						  INNER JOIN sStudent.tStudentMaster SMD ON SMD.Id=AEL.StudentID and SMD.StatusId=1						
						  LEFT JOIN sStudent.tStudentCommunication SC on SMD.Id=SC.StudentID	     
					where 
						  OGM.Id = OGMEL.Id AND COGBM.Id=@rCommonOrgGroupBatchId AND		
						  --SMEL.AttendanceDate <= CONVERT(char(10), @rUptoDate,126)
						  ((SMEL.AttendanceDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = '')) AND
						  ((SMEL.AttendanceDate <= @rToDate) OR (ISNULL(@rToDate,'') = ''))
						  AND (SMEL.AttendanceTypeId = @rAttendanceTypeId OR @rAttendanceTypeId = 0)
						  -- IsInContext
						  AND BMEL.IsInContext = 1
						  GROUP BY SMD.Id
					--GROUP BY OGMEL.Id,OGMEL.Title,OMEL.Id,OMEL.Title,SMEL.AcademicId,DM.Code,SMD.Id,(SMD.FirstName+' '+SMD.LastName),(SC.ParentContactNo)
					HAVING convert(numeric(10,2), ((count(CAST((case when IsPresent=1 then 1 end) AS float))/CAST(Count(AcademicId)AS float))*100))<70) AS Tmp
					
					--HAVING convert(numeric(10,2), ((count(CAST((case when IsPresent=1 then 1 end) AS float))/CAST(Count(AcademicId)AS float))*100))<70
					)  As LessThen70,
--100% Attendance All Orggroup
				  (select Count(StudentID) from  (
					select  
						  OGMEL.Id AS OrgGroupId,
						  OGMEL.Title AS OrgGroupTitle,
						  OMEL.Id AS OrgId,
						  (OMEL.Title) As OrgTitle ,
						  DM.Code AS DivisionCode,
						  (SMD.Id)StudentID,
						  (SMD.FirstName+' '+SMD.LastName) AS StudentName,         
						  (SC.ParentContactNo) AS ContactNo,
						  ((count(CAST((case when IsPresent=1 then 1 end) AS float)))) As IsPresentCount,CAST(Count(AcademicId)AS float) As AcademicCount
					FROM sAttendance.tStudentRegister SMEL
						   INNER JOIN sStudent.tAcademic AEL ON SMEL.Academicid=AEL.id
						   INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = AEL.BatchId
						   INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
						   INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId						
						   INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BMEL.OrgGroupBatchId
						   INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
						   INNER JOIN sSetup.tDivisionMaster DM ON DM.ID=AEL.DivisionID						
						   INNER JOIN sStudent.tStudentMaster SMD ON SMD.Id=AEL.StudentID and SMD.StatusId=1					
						   LEFT JOIN sStudent.tStudentCommunication SC on SMD.Id=SC.StudentID
					WHERE OGM.Id = OGMEL.Id AND COGBM.Id=@rCommonOrgGroupBatchId AND		
						   --SMEL.AttendanceDate <= CONVERT(char(10), @rUptoDate,126)
						 ((SMEL.AttendanceDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = '')) AND
						 ((SMEL.AttendanceDate <= @rToDate) OR (ISNULL(@rToDate,'') = ''))
						 AND (SMEL.AttendanceTypeId = @rAttendanceTypeId OR @rAttendanceTypeId = 0)
						  -- IsInContext
						  AND BMEL.IsInContext = 1
					GROUP BY OGMEL.Id,OGMEL.Title,OMEL.Id,OMEL.Title,SMEL.AcademicId,DM.Code,SMD.Id,(SMD.FirstName+' '+SMD.LastName),(SC.ParentContactNo)		
					HAVING convert(numeric(10,2), ((count(CAST((case when IsPresent=1 then 1 end) AS float))/CAST(Count(AcademicId)AS float))*100))=100) AS Tmp
					) AS HundredPer,
--Absent>3 All Orggroup
				   (SELECT COUNT(AcademicId) FROM(
					  SELECT 
						ROW_NUMBER() OVER ( PARTITION BY AcademicId ORDER BY MIN(AttendanceDate) DESC) as rowno,
						AcademicId,AttendanceDate
					  FROM sAttendance.tStudentRegister d 		
						 INNER JOIN sStudent.tAcademic AEL ON d.Academicid=AEL.id
						 INNER JOIN sStudent.tStudentMaster SM1 ON SM1.Id = AEL.StudentId and SM1.StatusId=1
						 INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = AEL.BatchId
						 INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
						 INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
						 INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BMEL.OrgGroupBatchId
						 INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
		
					  WHERE
						 OGM.Id = OGMEL.Id AND COGBM.Id=@rCommonOrgGroupBatchId AND
						 IsPresent IN(0) 
						 --AND AttendanceDate between DATEADD(DAY, -2, convert(date, @rUptoDate, 126)) AND @rUptoDate
						AND ((AttendanceDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = '')) AND
						((AttendanceDate <= @rToDate) OR (ISNULL(@rToDate,'') = ''))
						 and IsPresent=0 AND (d.AttendanceTypeId = @rAttendanceTypeId OR @rAttendanceTypeId = 0)
						 -- IsInContext
						 AND BMEL.IsInContext = 1
					  GROUP BY AcademicId,AttendanceDate) as AbsCnt WHERE rowno=3
					  ) AS AbsentCount,
--Leave Request All Orggroup
					(SELECT 
						COUNT(AcademicId) AS LeaveRequest
					 FROM sAttendance.tStudentLeaveRequest STSL
						INNER JOIN sStudent.tAcademic AEL ON STSL.Academicid=AEL.id
						INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = AEL.BatchId
						INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
						INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
						INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BMEL.OrgGroupBatchId
						INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
						INNER JOIN sSetup.tDivisionMaster DM ON DM.ID=AEL.DivisionID
						INNER JOIN sStudent.tStudentMaster SMD ON SMD.Id=AEL.StudentID and SMD.StatusId=1
						INNER JOIN sStudent.tStudentCommunication SC on SMD.Id=SC.StudentID
					WHERE OGM.Id = OGMEL.Id AND COGBM.Id=@rCommonOrgGroupBatchId AND
					--CONVERT(char(10), @rUptoDate,126) between LeaveFromDate AND LeaveToDate
						((LeaveFromDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = '')) AND
						((LeaveToDate <= @rToDate) OR (ISNULL(@rToDate,'') = ''))
						-- IsInContext
						AND BMEL.IsInContext = 1
					) AS LeaveRequest,
--AttnNotTakenClass All Orggroup
					(Select count(SM1.ID)
					 FROM sStudent.tStudentMaster SM1
						 INNER JOIN sStudent.tAcademic A ON A.StudentId= SM1.ID and SM1.StatusId=1
						 INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId
						 INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = BM.OrgId
						 INNER JOIN sSetup.tOrgGroupMaster OGMR ON OGMR.Id=OM.OrgGroupId
						 INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BM.OrgGroupBatchId
						 INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
         
					 WHERE 
						 OGM.Id = OGMR.Id  and SM1.statusid =1 AND COGBM.Id=@rCommonOrgGroupBatchId AND A.Id  not in 
					(select AcademicId from sAttendance.tStudentRegister SR  WHERE 
					--SR.AttendanceDate = CONVERT(char(10),@rUptoDate,126))) 
					((SR.AttendanceDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = '')) AND
					((SR.AttendanceDate <= @rToDate) OR (ISNULL(@rToDate,'') = ''))
					 AND (SR.AttendanceTypeId = @rAttendanceTypeId OR @rAttendanceTypeId = 0)
					 --AND SR.AttendanceTypeId = 1
					 -- IsInContext
					 AND BM.IsInContext = 1
					 ))
					As AttnNotTakenClass,

				--@rUptoDate,
				@rCommonOrgGroupBatchId,GetDate()
				FROM sSetup.tOrgGroupMaster OGM 
				WHERE OGM.Id<>1 AND ISNULL(OGM.IsObsolete,0) = 0
				AND  ((OGM.Id = @rOrgGroupId)OR(@rOrgGroupId=0))	
	END

--Organization wise Attendance

ELSE IF @rTypeId=2
    BEGIN
    SELECT 
       OGMT.Id As OrgGroupId,
       OM.Id AS OrgId, 
       OM.Title AS OrgTitle,
       OGMT.Title As OrgGroupTitle,
       
--Total Organization wise
		   (Select count(SM1.ID)
			FROM sStudent.tStudentMaster SM1
				 INNER JOIN sStudent.tAcademic A ON A.StudentId= SM1.ID and SM1.StatusId=1
				 INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId
				 INNER JOIN sSetup.tOrganizationMaster OMR ON OM.Id = BM.OrgId
				 INNER JOIN sSetup.tOrgGroupMaster OGM ON OGM.Id=OM.OrgGroupId		
				 INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
				 INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
			WHERE OM.Id = OMR.Id AND COGBM.Id=@rCommonOrgGroupBatchId
				  -- IsInContext
				  AND BM.IsInContext = 1
				 ) as Total,

--PresentStudent Organization wise
		 (SELECT count(*) 
			FROM sAttendance.tStudentRegister SME 
			   INNER JOIN sStudent.tAcademic AE ON SME.Academicid=AE.id
			   INNER JOIN sStudent.tStudentMaster SM1 ON SM1.Id = AE.StudentId and SM1.StatusId=1
			   INNER JOIN sSetup.tBatchMaster BME ON BME.Id = AE.BatchId
			   INNER JOIN sSetup.tOrganizationMaster OME ON OME.Id = BME.OrgId
			   INNER JOIN sSetup.tOrgGroupMaster OGME ON OGME.Id=OME.OrgGroupId
			   INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BME.OrgGroupBatchId
			   INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
			WHERE OM.Id = OME.Id and SME.IsPresent=1 AND 
			--SME.AttendanceDate = CONVERT(char(10), @rUptoDate,126) 
			((SME.AttendanceDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = '')) AND
			((SME.AttendanceDate <= @rToDate) OR (ISNULL(@rToDate,'') = ''))
			AND COGBM.Id=@rCommonOrgGroupBatchId
			--AND SME.AttendanceTypeId = 1
			AND (SME.AttendanceTypeId = @rAttendanceTypeId OR @rAttendanceTypeId = 0)
			-- IsInContext
			AND BME.IsInContext = 1
			) AS PresentStudent,

--AbsentStudent Organization wise
		  (SELECT count(*) 
			FROM sAttendance.tStudentRegister SME 
				INNER JOIN sStudent.tAcademic AE ON SME.Academicid=AE.id
				INNER JOIN sStudent.tStudentMaster SM1 ON SM1.Id = AE.StudentId and SM1.StatusId=1
				INNER JOIN sSetup.tBatchMaster BME ON BME.Id = AE.BatchId
				INNER JOIN sSetup.tOrganizationMaster OME ON OME.Id = BME.OrgId
				INNER JOIN sSetup.tOrgGroupMaster OGMEA ON OGMEA.Id=OME.OrgGroupId
				INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BME.OrgGroupBatchId
				INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
			WHERE OM.Id = OME.Id AND SME.IsPresent=0 AND COGBM.Id=@rCommonOrgGroupBatchId 
			--AND SME.AttendanceDate = CONVERT(char(10), @rUptoDate,126)
			AND ((SME.AttendanceDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = '')) AND
			((SME.AttendanceDate <= @rToDate) OR (ISNULL(@rToDate,'') = ''))
			--AND SME.AttendanceTypeId = 1
			AND (SME.AttendanceTypeId = @rAttendanceTypeId OR @rAttendanceTypeId = 0)
			-- IsInContext
			AND BME.IsInContext = 1
			) AS AbsentStudent,
        
--LessThen70 Organization wise
			(SELECT COUNT(StudentID) 
			   FROM (
				 SELECT   
				   OGMEL.Id as OrgGroupId,
				   OGMEL.Title As OrgGroupTitle,
				   OMEL.Id As OrgId,
				   (OMEL.Title) As OrgTitle ,
				   DM.Code As DivisionCode,
				   (SMD.Id)StudentID,
				   (SMD.FirstName+' '+SMD.LastName) AS StudentName,
					(SC.ParentContactNo) AS ContactNo,
					((COUNT(CAST((case when IsPresent=1 then 1 end) AS float)))) As IsPresentCount,CAST(Count(AcademicId)AS float) As AcademicCount
				 FROM sAttendance.tStudentRegister SMEL
					INNER JOIN sStudent.tAcademic AEL ON SMEL.Academicid=AEL.id
					INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = AEL.BatchId
					INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
					INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId	
					INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BMEL.OrgGroupBatchId
					INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId					
					INNER JOIN sSetup.tDivisionMaster DM ON DM.ID=AEL.DivisionID						
					INNER JOIN sStudent.tStudentMaster SMD ON SMD.Id=AEL.StudentID	and SMD.StatusId=1					
					LEFT JOIN sStudent.tStudentCommunication SC on SMD.Id=SC.StudentID
			     
				WHERE OM.Id = OMEL.Id 
				--AND SMEL.AttendanceDate <= CONVERT(char(10), @rUptoDate,126) 
				 AND ((SMEL.AttendanceDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = '')) AND
			    ((SMEL.AttendanceDate <= @rToDate) OR (ISNULL(@rToDate,'') = ''))
				AND COGBM.Id=@rCommonOrgGroupBatchId
				--AND SMEL.AttendanceTypeId = 1
				AND (SMEL.AttendanceTypeId = @rAttendanceTypeId OR @rAttendanceTypeId = 0)
				-- IsInContext
				AND BMEL.IsInContext = 1
				GROUP BY OGMEL.Id,OGMEL.Title,OMEL.Id,OMEL.Title,SMEL.AcademicId,DM.Code,SMD.Id,(SMD.FirstName+' '+SMD.LastName),(SC.ParentContactNo)		
			   HAVING convert(numeric(10,2), ((count(CAST((case when IsPresent=1 then 1 end) AS float))/CAST(Count(AcademicId)AS float))*100))<70
			   ) AS Tmp)  
			   As LessThen70,
        
--HundredPer Organization wise
			 (SELECT COUNT(StudentID) from  (
				 SELECT  
				 OGMEL.Id as OrgGroupId,
				 OGMEL.Title As OrgGroupTitle,
				 OMEL.Id As OrgId,
				 (OMEL.Title) As OrgTitle ,
				 DM.Code As DivisionCode,
				 (SMD.Id)StudentID,(SMD.FirstName+' '+SMD.LastName) AS StudentName,
				 (SC.ParentContactNo) AS ContactNo,
				 ((count(CAST((case when IsPresent=1 then 1 end) AS float)))) As IsPresentCount,CAST(Count(AcademicId)AS float) As AcademicCount
			 FROM sAttendance.tStudentRegister SMEL
				 INNER JOIN sStudent.tAcademic AEL ON SMEL.Academicid=AEL.id
				 INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = AEL.BatchId
				 INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
				 INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
				 INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BMEL.OrgGroupBatchId
				 INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId						
				 INNER JOIN sSetup.tDivisionMaster DM ON DM.ID=AEL.DivisionID						
				 INNER JOIN sStudent.tStudentMaster SMD ON SMD.Id=AEL.StudentID	and SMD.StatusId=1						
				 LEFT JOIN sStudent.tStudentCommunication SC on SMD.Id=SC.StudentID
			     
			 WHERE OM.Id = OMEL.Id AND
				   --SMEL.AttendanceDate <= CONVERT(char(10), @rUptoDate,126) 
				   	((SMEL.AttendanceDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = '')) AND
					((SMEL.AttendanceDate <= @rToDate) OR (ISNULL(@rToDate,'') = ''))
				   AND COGBM.Id=@rCommonOrgGroupBatchId 
				   --AND SMEL.AttendanceTypeId = 1
				   AND (SMEL.AttendanceTypeId = @rAttendanceTypeId OR @rAttendanceTypeId = 0)
				   -- IsInContext
				   AND BMEL.IsInContext = 1
			 GROUP BY OGMEL.Id,OGMEL.Title,OMEL.Id,OMEL.Title,SMEL.AcademicId,DM.Code,SMD.Id,(SMD.FirstName+' '+SMD.LastName),(SC.ParentContactNo)
				
				
			 HAVING convert(numeric(10,2), ((count(CAST((case when IsPresent=1 then 1 end) AS float))/CAST(Count(AcademicId)AS float))*100))=100
			 ) AS Tmp)  
			 As HundredPer,
        
--AbsentCount Organization wise
			(SELECT COUNT(AcademicId) FROM(
				SELECT 
				  ROW_NUMBER() OVER ( PARTITION BY AcademicId ORDER BY MIN(AttendanceDate) DESC) as rowno,
				  AcademicId,
				  AttendanceDate
				FROM sAttendance.tStudentRegister d 
				 INNER JOIN sStudent.tAcademic AEL ON d.Academicid=AEL.id
				 INNER JOIN sStudent.tStudentMaster SM1 ON SM1.Id = AEL.StudentId and SM1.StatusId=1
				 INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = AEL.BatchId
				 INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
				 INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
				 INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BMEL.OrgGroupBatchId
				 INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId				
				WHERE OM.Id = OMEL.Id AND
				IsPresent IN(0) 
				--AND AttendanceDate between DATEADD(DAY, -2, convert(date, @rUptoDate, 126)) AND @rUptoDate
				AND ((AttendanceDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = '')) AND
			    ((AttendanceDate <= @rToDate) OR (ISNULL(@rToDate,'') = ''))
				AND IsPresent=0 AND COGBM.Id=@rCommonOrgGroupBatchId
				--AND d.AttendanceTypeId = 1
				AND (d.AttendanceTypeId = @rAttendanceTypeId OR @rAttendanceTypeId = 0)
				-- IsInContext
				AND BMEL.IsInContext = 1
				GROUP BY AcademicId,AttendanceDate
				) as sfsf
				WHERE rowno=3) 
				as AbsentCount,
        
--LeaveRequest Organization wise
			 (SELECT 
				COUNT(AcademicId) AS LeaveRequest
				FROM sAttendance.tStudentLeaveRequest STSL
				  INNER JOIN sStudent.tAcademic AEL ON STSL.Academicid=AEL.id
				  INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = AEL.BatchId
				  INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
				  INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
				  INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BMEL.OrgGroupBatchId
				  INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
				  INNER JOIN sSetup.tDivisionMaster DM ON DM.ID=AEL.DivisionID
				  INNER JOIN sStudent.tStudentMaster SMD ON SMD.Id=AEL.StudentID and SMD.StatusId=1
				  INNER JOIN sStudent.tStudentCommunication SC on SMD.Id=SC.StudentID

				WHERE OM.Id = OMEL.Id AND COGBM.Id=@rCommonOrgGroupBatchId AND
				--CONVERT(char(10), @rUptoDate,126) between LeaveFromDate AND LeaveToDate
				((LeaveFromDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = '')) AND
			    ((LeaveToDate <= @rToDate) OR (ISNULL(@rToDate,'') = ''))
				-- IsInContext
				AND BMEL.IsInContext = 1
				) 
				As LeaveRequest,
        
--AttnNotTakenClass Organization wise
			(Select count(SM1.ID)
					 FROM sStudent.tStudentMaster SM1
						 INNER JOIN sStudent.tAcademic A ON A.StudentId= SM1.ID and SM1.StatusId=1
						 INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId
						 INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BM.OrgId
						 INNER JOIN sSetup.tOrgGroupMaster OGMR ON OGMR.Id=OMEL.OrgGroupId
						 INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BM.OrgGroupBatchId
						 INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
         
					 WHERE 
						 OM.Id = OMEL.Id  AND COGBM.Id=@rCommonOrgGroupBatchId AND A.Id  not in 
					(select AcademicId from sAttendance.tStudentRegister SR  WHERE 
					--SR.AttendanceDate = CONVERT(char(10),@rUptoDate,126))) 
					((SR.AttendanceDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = '')) AND
					((SR.AttendanceDate <= @rToDate) OR (ISNULL(@rToDate,'') = ''))
					 AND (SR.AttendanceTypeId = @rAttendanceTypeId OR @rAttendanceTypeId = 0)
					--AND SR.AttendanceTypeId = 1
					-- IsInContext
					AND BM.IsInContext = 1
					))
					As AttnNotTakenClass,
			getdate() AS UpdateDate		  
              
     FROM sSetup.tOrgGroupMaster OGMT 
        INNER join sSetup.tOrganizationMaster OM ON OGMT.Id=OM.OrgGroupId 
        --INNER JOIN sSecurity.tUserOrganization U ON U.OrgId = OM.Id 
     WHERE OGMT.Id=@rOrgGroupId 
	 --AND U.UserId = @rUserId
   
    END

ELSE IF @rTypeId=11
	BEGIN
     	SELECT OGMR.Id AS OrgGroupId,
			OGMR.Title AS OrgGroupTitle,
			OM.Id As OrgId,(OM.Title) AS OrgTitle,
			CM.ID AS ClassId,CM.Code AS ClassCode,
			0 AS SourceId,
			COUNT(A.StudentID) AS TotalStudent,
			COUNT(CASE WHEN SOD.GenderID=1 then 1 end) AS Male,
			COUNT(CASE WHEN SOD.GenderID=2 then 1 end) AS Female
		FROM sStudent.tStudentMaster SM
			INNER JOIN sStudent.tAcademic A ON A.StudentId= SM.ID and SM.StatusId=1 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = BM.OrgId
			INNER JOIN sSetup.tOrgGroupMaster OGMR ON OGMR.Id=OM.OrgGroupId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BM.OrgGroupBatchId
			INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
			INNER JOIN sSetup.tClassMaster CM ON CM.ID=A.ClassId
			LEFT JOIN sStudent.tStudentOther SOD ON SOD.StudentId=A.StudentId
		WHERE OGMR.Id=@rOrgGroupId
			AND COGBM.Id=@rCommonOrgGroupBatchId 
			-- IsInContext
			AND BM.IsInContext = 1
		GROUP BY OGMR.Id ,OGMR.Title,OM.Id ,OM.Title,CM.ID,CM.Code
    END

ELSE IF @rTypeId=21
    BEGIN
		SELECT OGMR.Id as OrgGroupId,
			OGMR.Title As OrgGroupTitle,
			OM.Id As OrgId,(OM.Title) As OrgTitle,
			CM.ID AS ClassId,CM.Code AS ClassCode,
			0 AS SourceId,
			COUNT(A.StudentID) AS TotalStudent,
			COUNT(case when SOD.GenderID=1 then 1 end) AS Male,
			COUNT(case when SOD.GenderID=2 then 1 end) AS Female
		FROM sStudent.tStudentMaster SM
			INNER JOIN sStudent.tAcademic A ON A.StudentId= SM.ID and SM.StatusId=1 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = BM.OrgId
			INNER JOIN sSetup.tOrgGroupMaster OGMR ON OGMR.Id=OM.OrgGroupId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BM.OrgGroupBatchId
			INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
			INNER JOIN sSetup.tClassMaster CM ON CM.ID=A.ClassId
			LEFT JOIN sStudent.tStudentOther SOD ON SOD.StudentId=A.StudentId
		WHERE OM.Id=@rOrgId
			AND COGBM.Id=@rCommonOrgGroupBatchId 
			-- IsInContext
			AND BM.IsInContext = 1
		GROUP BY OGMR.Id ,OGMR.Title,OM.Id ,OM.Title,CM.ID,CM.Code
     END
     
ELSE IF @rTypeId=12
    BEGIN
		SELECT OGME.Id as OrgGroupId,
			OGME.Title As OrgGroupTitle,
			OME.Id As OrgId,(OME.Title) As OrgTitle,
			CM.ID AS ClassId,CM.Code AS ClassCode,
			0 AS SourceId,
			COUNT(AE.StudentID) AS TotalStudent,
			COUNT(case when SOD.GenderID=1 then 1 end) AS Male,
			COUNT(case when SOD.GenderID=2 then 1 end) AS Female				 
		FROM sAttendance.tStudentRegister SME 
			INNER JOIN sStudent.tAcademic AE ON SME.Academicid=AE.id
			INNER JOIN sSetup.tBatchMaster BME ON BME.Id = AE.BatchId
			INNER JOIN sSetup.tOrganizationMaster OME ON OME.Id = BME.OrgId
			INNER JOIN sSetup.tOrgGroupMaster OGME ON OGME.Id=OME.OrgGroupId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BME.OrgGroupBatchId
			INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId		
			INNER JOIN sSetup.tClassMaster CM ON CM.ID=AE.ClassId
			INNER JOIN sStudent.tStudentMaster SMD ON SMD.Id=AE.StudentID and SMD.StatusId=1	
			LEFT JOIN sStudent.tStudentOther SOD ON SOD.StudentId=SMD.Id
		WHERE OGME.Id=@rOrgGroupId and SME.IsPresent=1 AND COGBM.Id=@rCommonOrgGroupBatchId   
			--and SME.AttendanceDate = CONVERT(char(10), @rUptoDate,126)
			AND ((SME.AttendanceDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = '')) AND
			((SME.AttendanceDate <= @rToDate) OR (ISNULL(@rToDate,'') = ''))
			AND SME.AttendanceTypeId = 1
			-- IsInContext
			AND BME.IsInContext = 1
		GROUP BY OGME.Id,OGME.Title,OME.Id,OME.Title,CM.ID,CM.Code
         
    END
   
ELSE IF @rTypeId=22
	BEGIN
          SELECT 
				OGME.Id as OrgGroupId,OGME.Title As OrgGroupTitle,
				OME.Id As OrgId,(OME.Title) As OrgTitle,
				 CM.ID AS ClassId,CM.Code AS ClassCode,
				 0 AS SourceId,
				COUNT(AE.StudentID) AS TotalStudent,
				COUNT(case when SOD.GenderID=1 then 1 end) as Male,
				COUNT(case when SOD.GenderID=2 then 1 end) as Female
		  FROM sAttendance.tStudentRegister SME 
				INNER JOIN sStudent.tAcademic AE ON SME.Academicid=AE.id
				INNER JOIN sSetup.tBatchMaster BME ON BME.Id = AE.BatchId
				INNER JOIN sSetup.tOrganizationMaster OME ON OME.Id = BME.OrgId
				INNER JOIN sSetup.tOrgGroupMaster OGME ON OGME.Id=OME.OrgGroupId
				INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BME.OrgGroupBatchId
			    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
				INNER JOIN sSetup.tClassMaster CM ON CM.ID=AE.ClassId
				INNER JOIN sStudent.tStudentMaster SMD ON SMD.Id=AE.StudentID and SMD.StatusId=1	
				LEFT JOIN sStudent.tStudentOther SOD ON SOD.StudentId=SMD.Id 
		  WHERE OME.Id=@rOrgId and SME.IsPresent=1 AND COGBM.Id=@rCommonOrgGroupBatchId  
				--AND SME.AttendanceDate = CONVERT(char(10), @rUptoDate,126)
				AND ((SME.AttendanceDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = '')) AND
			   ((SME.AttendanceDate <= @rToDate) OR (ISNULL(@rToDate,'') = ''))
			   AND SME.AttendanceTypeId = 1
			   -- IsInContext
			   AND BME.IsInContext = 1
		  GROUP BY OGME.Id,OGME.Title,OME.Id,OME.Title,CM.ID,CM.Code          
	END
   
ELSE IF @rTypeId=13
      BEGIN
      
          (SELECT 
				OGMEA.Id as OrgGroupId,
				OGMEA.Title As OrgGroupTitle,
				OME.Id As OrgId,
				(OME.Title) As OrgTitle,
				CM.ID As ClassId,
				CM.Code As ClassCode,
				0 AS SourceId,
				COUNT(AE.StudentID) AS TotalStudent,
			    COUNT(case when SOD.GenderID=1 then 1 end) as Male,
				COUNT(case when SOD.GenderID=2 then 1 end) as Female
			FROM sAttendance.tStudentRegister SME 
				INNER JOIN sStudent.tAcademic AE ON SME.Academicid=AE.id
				INNER JOIN sSetup.tBatchMaster BME ON BME.Id = AE.BatchId
				INNER JOIN sSetup.tOrganizationMaster OME ON OME.Id = BME.OrgId
				INNER JOIN sSetup.tOrgGroupMaster OGMEA ON OGMEA.Id=OME.OrgGroupId
				INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BME.OrgGroupBatchId
			    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
				INNER JOIN sSetup.tClassMaster CM ON CM.ID=AE.ClassID
				INNER JOIN sStudent.tStudentMaster SMD ON SMD.Id=AE.StudentID and SMD.StatusId=1	
				Left JOIN sStudent.tStudentOther SOD ON SOD.StudentId=SMD.Id
			WHERE OGMEA.Id=@rOrgGroupId and SME.IsPresent=0  AND COGBM.Id=@rCommonOrgGroupBatchId  
				 --and SME.AttendanceDate = CONVERT(char(10), @rUptoDate,126)
				AND ((SME.AttendanceDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = '')) AND
			    ((SME.AttendanceDate <= @rToDate) OR (ISNULL(@rToDate,'') = ''))
				AND SME.AttendanceTypeId = 1
				-- IsInContext
			    AND BME.IsInContext = 1
			GROUP BY OGMEA.Id,OGMEA.Title,OME.Id,OME.Title,CM.ID,CM.Code
		 )
       END
       
ELSE IF @rTypeId=23
       BEGIN
          (SELECT 
				OGMEA.Id as OrgGroupId,
				OGMEA.Title As OrgGroupTitle,
				OME.Id As OrgId,
				(OME.Title) As OrgTitle,
				CM.ID AS ClassId,CM.Code AS ClassCode,
				0 AS SourceId,
				COUNT(AE.StudentID) AS TotalStudent,
				COUNT(case when SOD.GenderID=1 then 1 end) as Male,
				COUNT(case when SOD.GenderID=2 then 1 end) as Female
		   FROM sAttendance.tStudentRegister SME 
				INNER JOIN sStudent.tAcademic AE ON SME.Academicid=AE.id
				INNER JOIN sSetup.tBatchMaster BME ON BME.Id = AE.BatchId
				INNER JOIN sSetup.tOrganizationMaster OME ON OME.Id = BME.OrgId
				INNER JOIN sSetup.tOrgGroupMaster OGMEA ON OGMEA.Id=OME.OrgGroupId
				INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BME.OrgGroupBatchId
			    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
				INNER JOIN sSetup.tClassMaster CM ON CM.ID=AE.ClassId
				INNER JOIN sStudent.tStudentMaster SMD ON SMD.Id=AE.StudentID and SMD.StatusId=1	
				LEFT JOIN sStudent.tStudentOther SOD ON SOD.StudentId=SMD.Id
		   WHERE OME.Id=@rOrgId 
				AND SME.IsPresent=0 
				--AND SME.AttendanceDate = CONVERT(char(10), @rUptoDate,126)
				AND ((SME.AttendanceDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = '')) AND
			    ((SME.AttendanceDate <= @rToDate) OR (ISNULL(@rToDate,'') = '')) 
				AND COGBM.Id=@rCommonOrgGroupBatchId  
				AND SME.AttendanceTypeId = 1
				-- IsInContext
			    AND BME.IsInContext = 1
		   GROUP BY OGMEA.Id,OGMEA.Title,OME.Id,OME.Title,CM.ID,CM.Code
		  )
    
       END       
       
ELSE IF @rTypeId=14  
      BEGIN
			
       (SELECT *FROM  (
          SELECT 
				OGMEL.Id as OrgGroupId,
				OGMEL.Title As OrgGroupTitle,
				OMEL.Id As OrgId,
				(OMEL.Title) As OrgTitle,
				DM.Code As DivisionCode,
				(SMD.Code)StudentID,
				AEL.Id AS SourceId,
				(SMD.FirstName+' '+SMD.LastName) AS StudentName,
				(SC.ParentContactNo) AS ContactNo
				,CM.OrderIndex as ClassOrderIndex--add for mantis : 0042058
				,DM.OrderIndex AS DivisionOrderIndex	--add for mantis : 0042058
					FROM sAttendance.tStudentRegister SMEL
						  INNER JOIN sStudent.tAcademic AEL ON SMEL.Academicid=AEL.id
						  INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = AEL.BatchId 
						  INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
						  INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
						  INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BMEl.OrgGroupBatchId
						  INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId						
						  INNER JOIN sSetup.tDivisionMaster DM ON DM.ID=AEL.DivisionID						
						  INNER JOIN sStudent.tStudentMaster SMD ON SMD.Id=AEL.StudentID and SMD.StatusId=1						
						  LEFT JOIN sStudent.tStudentCommunication SC on SMD.Id=SC.StudentID
						  INNER JOIN sSetup.tClassMaster CM ON CM.ID=AEL.ClassId	--add for mantis : 0042058     
					where 
						  OGMEL.Id=@rOrgGroupId AND COGBM.Id=@rCommonOrgGroupBatchId AND		
						  --SMEL.AttendanceDate <= CONVERT(char(10), @rUptoDate,126)
						  	((SMEL.AttendanceDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = '')) AND
							((SMEL.AttendanceDate <= @rToDate) OR (ISNULL(@rToDate,'') = ''))
						  --GROUP BY SMD.Id
						  --AND SMEL.AttendanceTypeId = 1
						  AND (SMEL.AttendanceTypeId = @rAttendanceTypeId OR @rAttendanceTypeId = 0)
						  -- IsInContext
						  AND BMEL.IsInContext = 1
					 GROUP BY AEL.Id,OGMEL.Id,OGMEL.Title,OMEL.Id,OMEL.Title,SMEL.AcademicId,DM.Code,SMD.code,(SMD.FirstName+' '+SMD.LastName),(SC.ParentContactNo)
					 ,CM.OrderIndex,DM.OrderIndex--add for mantis : 0042058
					HAVING convert(numeric(10,2), ((count(CAST((case when IsPresent=1 then 1 end) AS float))/CAST(Count(AcademicId)AS float))*100))<70
	   ) AS Tmp)  ORDER BY Tmp.ClassOrderIndex, Tmp.DivisionOrderIndex --add for mantis : 0042058

      END
   
ELSE IF @rTypeId=24     
      BEGIN

      (SELECT *FROM  (
           SELECT 
              OGMEL.Id as OrgGroupId,
              OGMEL.Title As OrgGroupTitle,
              OMEL.Id As OrgId,
              (OMEL.Title) As OrgTitle,
              DM.Code As DivisionCode,
              (SMD.Code)StudentID,
              AEL.Id AS SourceId,
              (SMD.FirstName+' '+SMD.LastName) AS StudentName,
			  (SC.ParentContactNo) AS ContactNo
	   FROM sAttendance.tStudentRegister SMEL
			   INNER JOIN sStudent.tAcademic AEL ON SMEL.Academicid=AEL.id
			   INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = AEL.BatchId
			   INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
			   INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
			   INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BMEL.OrgGroupBatchId
			    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId			
			   INNER JOIN sSetup.tDivisionMaster DM ON DM.ID=AEL.DivisionID
			   INNER JOIN sStudent.tStudentMaster SMD ON SMD.Id=AEL.StudentID and SMD.StatusId=1	
			   LEFT JOIN sStudent.tStudentCommunication SC on SMD.Id=SC.StudentID
		WHERE OMEL.Id=@rOrgId AND
		      --SMEL.AttendanceDate <= CONVERT(char(10), @rUptoDate,126) 
			  	((SMEL.AttendanceDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = '')) AND
			    ((SMEL.AttendanceDate <= @rToDate) OR (ISNULL(@rToDate,'') = ''))
			  AND COGBM.Id=@rCommonOrgGroupBatchId  
			  AND SMEL.AttendanceTypeId = 1
			  -- IsInContext
			  AND BMEL.IsInContext = 1
		GROUP BY AEL.Id,OGMEL.Id,OGMEL.Title,OMEL.Id,OMEL.Title,SMEL.AcademicId,DM.Code,SMD.Code,(SMD.FirstName+' '+SMD.LastName),(SC.ParentContactNo)

	  HAVING convert(numeric(10,2), ((count(CAST((case when IsPresent=1 then 1 end) AS float))/CAST(Count(AcademicId)AS float))*100))<70
	 ) AS Tmp) 
		
          
      END   
   
ELSE IF @rTypeId=15
	   BEGIN	
		(SELECT *FROM(
              SELECT  
                  OGMEL.Id as OrgGroupId,
                  OGMEL.Title As OrgGroupTitle,
                  OMEL.Id As OrgId,(OMEL.Title) As OrgTitle,
                  DM.Code As DivisionCode,
                  (SMD.Code)StudentID,
                  (SMD.FirstName+' '+SMD.LastName) AS StudentName,
				  (SC.ParentContactNo) AS ContactNo,
				  AEL.Id AS SourceId
				  ,CM.OrderIndex as ClassOrderIndex--add for mantis : 0042058
				,DM.OrderIndex AS DivisionOrderIndex	--add for mantis : 0042058
		      FROM sAttendance.tStudentRegister SMEL
				   INNER JOIN sStudent.tAcademic AEL ON SMEL.Academicid=AEL.id
				   INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = AEL.BatchId --AND BMEL.IsActive = 1
				   INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
				   INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
				   INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BMEL.OrgGroupBatchId
			       INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId						
				   INNER JOIN sSetup.tDivisionMaster DM ON DM.ID=AEL.DivisionID
				   INNER JOIN sStudent.tStudentMaster SMD ON SMD.Id=AEL.StudentID and SMD.StatusId=1	
				   Left JOIN sStudent.tStudentCommunication SC on SMD.Id=SC.StudentID
				   INNER JOIN sSetup.tClassMaster CM ON CM.ID=AEL.ClassId	--add for mantis : 0042058 
			   WHERE OGMEL.Id=@rOrgGroupId AND
				   --SMEL.AttendanceDate <= CONVERT(char(10), @rUptoDate,126) 
				   	((SMEL.AttendanceDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = '')) AND
					((SMEL.AttendanceDate <= @rToDate) OR (ISNULL(@rToDate,'') = ''))
				   AND COGBM.Id=@rCommonOrgGroupBatchId
				   --AND SMEL.AttendanceTypeId = 1
				   AND (SMEL.AttendanceTypeId = @rAttendanceTypeId OR @rAttendanceTypeId = 0)
				   -- IsInContext
				   AND BMEL.IsInContext = 1
			   GROUP BY AEL.Id,OGMEL.Id,OGMEL.Title,OMEL.Id,OMEL.Title,SMEL.AcademicId,DM.Code,SMD.Code,(SMD.FirstName+' '+SMD.LastName),(SC.ParentContactNo)
			    ,CM.OrderIndex,DM.OrderIndex--add for mantis : 0042058
	      HAVING convert(numeric(10,2), ((count(CAST((case when IsPresent=1 then 1 end) AS float))/CAST(Count(AcademicId)AS float))*100))=100
	    ) AS Tmp)
		ORDER BY Tmp.ClassOrderIndex, Tmp.DivisionOrderIndex --add for mantis : 0042058 
	   END
	   
ELSE IF @rTypeId=25
	BEGIN	
	 (SELECT *FROM(
           SELECT  
                OGMEL.Id as OrgGroupId,
                OGMEL.Title As OrgGroupTitle,
                OMEL.Id As OrgId,
                (OMEL.Title) As OrgTitle,
                DM.Code As DivisionCode,
                (SMD.Code)StudentID,
                (SMD.FirstName+' '+SMD.LastName) AS StudentName,
				(SC.ParentContactNo) AS ContactNo,
				AEL.Id AS SourceId
			FROM sAttendance.tStudentRegister SMEL
				INNER JOIN sStudent.tAcademic AEL ON SMEL.Academicid=AEL.id
				INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = AEL.BatchId
				INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
				INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
				INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BMEL.OrgGroupBatchId
			    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
				INNER JOIN sSetup.tDivisionMaster DM ON DM.ID=AEL.DivisionID
				INNER JOIN sStudent.tStudentMaster SMD ON SMD.Id=AEL.StudentID and SMD.StatusId=1	
				Left JOIN sStudent.tStudentCommunication SC on SMD.Id=SC.StudentID
		    WHERE OMEL.Id=@rOrgId AND
				  --SMEL.AttendanceDate <= CONVERT(char(10), @rUptoDate,126) 
				  	((SMEL.AttendanceDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = '')) AND
					((SMEL.AttendanceDate <= @rToDate) OR (ISNULL(@rToDate,'') = ''))
				  AND COGBM.Id=@rCommonOrgGroupBatchId
				  AND SMEL.AttendanceTypeId = 1
				  -- IsInContext
				  AND BMEL.IsInContext = 1
			GROUP BY AEL.Id,OGMEL.Id,OGMEL.Title,OMEL.Id,OMEL.Title,SMEL.AcademicId,DM.Code,SMD.Code,(SMD.FirstName+' '+SMD.LastName),(SC.ParentContactNo)
	    HAVING convert(numeric(10,2), ((count(CAST((case when IsPresent=1 then 1 end) AS float))/CAST(Count(AcademicId)AS float))*100))=100
	  ) AS Tmp) 

	   END
	   	   
ELSE IF @rTypeId=16   
   BEGIN
        
        (SELECT * FROM 
             (SELECT 
				OGMEL.Id as OrgGroupId,
				OGMEL.Title As OrgGroupTitle,
				OMEL.Id As OrgId,(OMEL.Title) As OrgTitle,
				DM.Code As DivisionCode,
				(SMD.Code)StudentID,
				(SMD.FirstName+' '+SMD.LastName) AS StudentName,
				(SC.ParentContactNo) AS ContactNo,
						 AEL.Id AS SourceId
						 ,CM.OrderIndex as ClassOrderIndex--add for mantis : 0042058
				,DM.OrderIndex AS DivisionOrderIndex	--add for mantis : 0042058
			  FROM sAttendance.tStudentLeaveRequest STSL
				INNER JOIN sStudent.tAcademic AEL ON STSL.Academicid=AEL.id
				INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = AEL.BatchId
				INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
				INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
				INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BMEL.OrgGroupBatchId
			    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
				INNER JOIN sSetup.tDivisionMaster DM ON DM.ID=AEL.DivisionID
				INNER JOIN sStudent.tStudentMaster SMD ON SMD.Id=AEL.StudentID and SMD.StatusId=1	
				INNER JOIN sStudent.tStudentCommunication SC on SMD.Id=SC.StudentID	
				 INNER JOIN sSetup.tClassMaster CM ON CM.ID=AEL.ClassId	--add for mantis : 0042058 
			  WHERE OGMEL.Id=@rOrgGroupId 
				AND COGBM.Id=@rCommonOrgGroupBatchId 
				--AND CONVERT(char(10), @rUptoDate,126) between LeaveFromDate 
				--AND LeaveToDate
				AND ((LeaveFromDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = '')) AND
				((LeaveToDate <= @rToDate) OR (ISNULL(@rToDate,'') = ''))
				-- IsInContext
				AND BMEL.IsInContext = 1
		) as a) 
		ORDER BY a.ClassOrderIndex, a.DivisionOrderIndex --add for mantis : 0042058
   END
      
ELSE IF @rTypeId=26   
   BEGIN
      
      (SELECT * FROM 
          (SELECT 
			  OGMEL.Id as OrgGroupId,
			  OGMEL.Title As OrgGroupTitle,
			  OMEL.Id As OrgId,(OMEL.Title) As OrgTitle,
			  DM.Code As DivisionCode,(SMD.Code)StudentID,
			  (SMD.FirstName+' '+SMD.LastName) AS StudentName,
			  (SC.ParentContactNo) AS ContactNo,
			  AEL.Id AS SourceId
		   FROM sAttendance.tStudentLeaveRequest STSL 
			   INNER JOIN sStudent.tAcademic AEL ON STSL.Academicid=AEL.id
			   INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = AEL.BatchId
			   INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
			   INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
			   INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BMEL.OrgGroupBatchId
			   INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
			   INNER JOIN sSetup.tDivisionMaster DM ON DM.ID=AEL.DivisionID
			   INNER JOIN sStudent.tStudentMaster SMD ON SMD.Id=AEL.StudentID and SMD.StatusId=1	
			   INNER JOIN sStudent.tStudentCommunication SC on SMD.Id=SC.StudentID		 
		   WHERE OMEL.Id=@rOrgId 
				AND COGBM.Id=@rCommonOrgGroupBatchId 
				--AND CONVERT(char(10), @rUptoDate,126) between LeaveFromDate 
				--AND LeaveToDate
				AND ((LeaveFromDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = '')) AND
				((LeaveToDate <= @rToDate) OR (ISNULL(@rToDate,'') = ''))
				-- IsInContext
				AND BMEL.IsInContext = 1
		) as a) 
   END
   
ELSE IF @rTypeId=17   
   BEGIN
       
       --(
	   SELECT OrgGroupId,
                OrgGroupTitle,
                OrgId,
                OrgTitle,
                Code As DivisionCode,
                StudentID,
                SourceId,
                StudentName,
                ContactNo FROM( SELECT ROW_NUMBER() OVER ( PARTITION BY AcademicId ORDER BY MIN(AttendanceDate) DESC) as rowno,
				OGMEL.Id as OrgGroupId,
				OGMEL.Title As OrgGroupTitle,
				OMEL.Id As OrgId,
				(OMEL.Title) As OrgTitle,
				AcademicId AS SourceId,
				AttendanceDate, 
				DM.Code,
				(SMD.Code)StudentID,
				(SMD.FirstName+' '+SMD.LastName) AS StudentName,(SC.ParentContactNo) As ContactNo
				 ,CM.OrderIndex as ClassOrderIndex--add for mantis : 0042058
				,DM.OrderIndex AS DivisionOrderIndex	--add for mantis : 0042058

			 FROM sAttendance.tStudentRegister d 							
		 		INNER JOIN sStudent.tAcademic AEL ON d.Academicid=AEL.id
				INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = AEL.BatchId
				INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
				INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
				INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BMEL.OrgGroupBatchId
			    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
				INNER JOIN sSetup.tDivisionMaster DM ON DM.ID=AEL.DivisionID
				INNER JOIN sStudent.tStudentMaster SMD ON SMD.Id=AEL.StudentID and SMD.StatusId=1	
				INNER JOIN sStudent.tStudentCommunication SC on SMD.Id=SC.StudentID
				INNER JOIN sSetup.tClassMaster CM ON CM.ID=AEL.ClassId	--add for mantis : 0042058 
		     WHERE
				OGMEL.Id=@rOrgGroupId AND
				IsPresent IN(0) 
				--AND AttendanceDate between DATEADD(DAY, -2, convert(date, @rUptoDate, 126)) AND @rUptoDate   
				AND ((AttendanceDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = '')) AND
			   ((AttendanceDate <= @rToDate) OR (ISNULL(@rToDate,'') = ''))
				AND IsPresent=0 AND COGBM.Id=@rCommonOrgGroupBatchId
				--AND d.AttendanceTypeId = 1
				AND (d.AttendanceTypeId = @rAttendanceTypeId OR @rAttendanceTypeId = 0)
				-- IsInContext
				AND BMEL.IsInContext = 1
			 Group By AEL.Id,OGMEL.Id,OGMEL.Title,OMEL.Id,OMEL.Title,AcademicId,AttendanceDate, DM.Code,(SMD.Code),(SMD.FirstName+' '+SMD.LastName),SC.ParentContactNo 
			  ,CM.OrderIndex,DM.OrderIndex--add for mantis : 0042058
			 ) as T
		WHERE rowno=3
		ORDER BY T.ClassOrderIndex, T.DivisionOrderIndex --add for mantis : 0042058
		--) 
   END
      
ELSE IF @rTypeId=27   
   BEGIN
       
        (SELECT OrgGroupId,
                OrgGroupTitle,
                OrgId,OrgTitle, 
                Code As DivisionCode,SourceId,
                StudentID,StudentName,
                ContactNo  FROM(
			SELECT 
				ROW_NUMBER() OVER ( PARTITION BY AcademicId ORDER BY MIN(AttendanceDate) DESC) as rowno,
				OGMEL.Id as OrgGroupId,
				OGMEL.Title As OrgGroupTitle,
				OMEL.Id As OrgId,(OMEL.Title) As OrgTitle,
                AcademicId AS SourceId,AttendanceDate, 
                DM.Code,
                (SMD.Code)StudentID,
                (SMD.FirstName+' '+SMD.LastName) AS StudentName,
                (SC.ParentContactNo) As ContactNo		
			FROM sAttendance.tStudentRegister d 		
		 		INNER JOIN sStudent.tAcademic AEL ON d.Academicid=AEL.id
				INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = AEL.BatchId
				INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
				INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
				INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BMEL.OrgGroupBatchId
			    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
				INNER JOIN sSetup.tDivisionMaster DM ON DM.ID=AEL.DivisionID
				INNER JOIN sStudent.tStudentMaster SMD ON SMD.Id=AEL.StudentID and SMD.StatusId=1	
				INNER JOIN sStudent.tStudentCommunication SC on SMD.Id=SC.StudentID		
			WHERE
				OMEL.Id=@rOrgId AND
				IsPresent IN(0) 
				--AND AttendanceDate between DATEADD(DAY, -2, convert(date, @rUptoDate, 126)) AND @rUptoDate
				AND ((AttendanceDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = '')) AND
				((AttendanceDate <= @rToDate) OR (ISNULL(@rToDate,'') = ''))
			    AND IsPresent=0 AND COGBM.Id=@rCommonOrgGroupBatchId
				AND d.AttendanceTypeId = 1
				-- IsInContext
				AND BMEL.IsInContext = 1
			Group By AEL.Id,OGMEL.Id,OGMEL.Title,OMEL.Id,OMEL.Title,AcademicId,AttendanceDate, DM.Code,(SMD.Code),(SMD.FirstName+' '+SMD.LastName),SC.ParentContactNo
			) as sfsf
	   WHERE rowno=3) 
        
   END
   
ELSE IF @rTypeId=18
   BEGIN
			SELECT 
				OrgGroupId,
				OrgGroupTitle,
				OrgId,
				OrgTitle,
				ClassCode,
				StudentCount,
				SourceId,
				ISNULL(TeacherName,'') AS TeacherName,
				ISNULL(ContactNo,'')AS ContactNo  FROM(SELECT 
				O.Id as OrgGroupId,
				O.Title As OrgGroupTitle,
				OMEL.Id As OrgId,
				(OMEL.Title) As OrgTitle,
				A.ClassId,
				DM.Code AS ClassCode,
				(SELECT COUNT(A.Id) FROM sStudent.tAcademic A INNER JOIN sStudent.tStudentMaster SM  ON SM.Id= A.StudentId AND SM.StatusId =1 WHERE  
				DivisionId= DM.Id AND BatchId = BM.Id) AS StudentCount,
				--(SELECT COUNT(Id) FROM sStudent.tAcademic WHERE DivisionId= A.DivisionId AND BatchId = A.BatchId) AS StudentCount,
				A.Id As SourceId,
				(EM.FirstName+' '+Em.LastName) AS TeacherName,(EC.MobileNumber) AS ContactNo,
				ROW_NUMBER() OVER ( PARTITION BY A.DivisionId,A.OrgId order by A.DivisionId) as rowno
			FROM sStudent.tAcademic A
				INNER JOIN sStudent.tStudentMaster SM  ON SM.Id= A.StudentId AND SM.StatusId =1
				INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId
				INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BM.OrgId
				INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
				INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
				INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
				INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId
				LEFT JOIN sHrm.tEmployeeMaster EM ON EM.ID=DM.InchargeEmployeeId
				LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
			WHERE  O.id = @rOrgGroupId AND  ISNULL(EM.IsOtherUser,0) = 0 AND COGBM.Id=@rCommonOrgGroupBatchId AND    A.Id  not in  ( select AcademicId from sAttendance.tStudentRegister SR  WHERE 
			--SR.AttendanceDate = CONVERT(char(10),  @rUptoDate,126))
			((SR.AttendanceDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = '')) AND
			((SR.AttendanceDate <= @rToDate) OR (ISNULL(@rToDate,'') = '')) 
			 AND (SR.AttendanceTypeId = @rAttendanceTypeId OR @rAttendanceTypeId = 0)
			 -- IsInContext
			 AND BM.IsInContext = 1
			--AND SR.AttendanceTypeId = 1
				)) Temp 
		WHERE rowno=1  
		ORDER BY OrgId,ClassCode desc
   END
     
ELSE IF @rTypeId=28
   
   BEGIN

	SELECT 
				OrgGroupId,
				OrgGroupTitle,
				OrgId,
				OrgTitle,
				ClassCode,
				StudentCount,
				SourceId,
				ISNULL(TeacherName,'') AS TeacherName,
				ISNULL(ContactNo,'')AS ContactNo  FROM(SELECT 
				O.Id as OrgGroupId,
				O.Title As OrgGroupTitle,
				OMEL.Id As OrgId,
				(OMEL.Title) As OrgTitle,
				A.ClassId,
				DM.Code AS ClassCode,
				(SELECT COUNT(Id) FROM sStudent.tAcademic WHERE DivisionId= A.DivisionId AND BatchId = A.BatchId) AS StudentCount,
				A.Id As SourceId,
				(EM.FirstName+' '+Em.LastName) AS TeacherName,(EC.MobileNumber) AS ContactNo,
				ROW_NUMBER() OVER ( PARTITION BY A.DivisionId,A.OrgId order by A.DivisionId) as rowno
				FROM sStudent.tAcademic A
				INNER JOIN sStudent.tStudentMaster SM  ON SM.Id= A.StudentId AND SM.StatusId =1
				INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId
				INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BM.OrgId
				INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
				INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
				INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
				INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId
				LEFT JOIN sHrm.tEmployeeMaster EM ON EM.ID=DM.InchargeEmployeeId
				LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
				WHERE  OMEL.id = @rOrgId AND  ISNULL(EM.IsOtherUser,0) = 0 AND COGBM.Id=@rCommonOrgGroupBatchId AND    A.Id  not in  ( select AcademicId from sAttendance.tStudentRegister SR  WHERE 
				--SR.AttendanceDate = CONVERT(char(10),  @rUptoDate,126))
				((SR.AttendanceDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = '')) AND
				((SR.AttendanceDate <= @rToDate) OR (ISNULL(@rToDate,'') = ''))
				 AND (SR.AttendanceTypeId = @rAttendanceTypeId OR @rAttendanceTypeId = 0)
				-- IsInContext
				AND BM.IsInContext = 1
				--AND SR.AttendanceTypeId = 1
				)) Temp 
				WHERE 
				rowno=1  
				ORDER BY OrgId,ClassCode desc
	   
   END

ELSE IF @rTypeId=1110
   BEGIN
	  SELECT 
	      (DM.Id) AS DivisionId,
	       SMD.Code As StudentId,
	       A.Id AS SourceId,
	       (SMD.FirstName+' '+SMD.LastName) AS StudentName,
		   (SC.ParentContactNo) AS ContactNo
							
	  FROM sSetup.tDivisionMaster DM
			INNER JOIN sStudent.tAcademic A ON A.DivisionID=DM.id
			INNER JOIN sStudent.tStudentMaster SMD ON SMD.Id=A.StudentID and SMD.StatusId=1	
			INNER JOIN sStudent.tStudentOther SOD ON SOD.StudentId=SMD.Id
			INNER JOIN sStudent.tStudentCommunication SC on SMD.Id=SC.StudentID
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId
	   WHERE DM.ID=@rDivisionId 
			 AND DM.OrgId=@rOrgId
			 AND BM.IsInContext = 1
	   ORDER BY A.StudentID														          
   END

ELSE IF @rTypeId=1111
	BEGIN
      SELECT 
         (DM.Id) AS DivisionId,
         SMD.Code As StudentId,
         A.Id AS SourceId,
         (SMD.FirstName+' '+SMD.LastName) AS StudentName,
		 (SC.ParentContactNo) AS ContactNo
								
	  FROM sSetup.tDivisionMaster DM
		 INNER JOIN sStudent.tAcademic A ON A.DivisionID=DM.id
		 INNER JOIN sStudent.tStudentMaster SMD ON SMD.Id=A.StudentID and SMD.StatusId=1	
		 INNER JOIN sStudent.tStudentOther SOD ON SOD.StudentId=SMD.Id
		 INNER JOIN sStudent.tStudentCommunication SC on SMD.Id=SC.StudentID
		 INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId
	   WHERE DM.ID=@rDivisionId 
			AND SOD.GenderID=1 
			AND BM.IsInContext = 1
	   ORDER BY A.StudentID            
	END
	
ELSE IF @rTypeId=1112
	BEGIN	  
	  SELECT 
	    (DM.Id) AS DivisionId,
	    A.Id AS SourceId,
	    SMD.Code As StudentId,
	    (SMD.FirstName+' '+SMD.LastName) AS StudentName,
		(SC.ParentContactNo) AS ContactNo								
	  FROM sSetup.tDivisionMaster DM
		INNER JOIN sStudent.tAcademic A ON A.DivisionID=DM.id
		INNER JOIN sStudent.tStudentMaster SMD ON SMD.Id=A.StudentID and SMD.StatusId=1	
		INNER JOIN sStudent.tStudentOther SOD ON SOD.StudentId=SMD.Id
		INNER JOIN sStudent.tStudentCommunication SC on SMD.Id=SC.StudentID	
		INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId
	  WHERE DM.ID=@rDivisionId 
		AND SOD.GenderID=2 
		AND BM.IsInContext = 1
	  ORDER BY A.StudentID
	END 

  ELSE
    BEGIN

     if @rTypeId=11 OR @rTypeId=21     
        BEGIN
			SELECT 
				(DM.Id) AS DivisionId,
				DM.Code AS ClassDivision,
				SM.Code As StudentId,
				A.Id AS SourceId,
				(SM.FirstName+' '+SM.LastName) AS StudentName,
				(SC.ParentContactNo) AS ContactNo
			FROM sStudent.tStudentMaster SM 
				INNER JOIN sStudent.tAcademic A ON A.StudentId= SM.ID and SM.StatusId=1 
				INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId
				INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = BM.OrgId
				INNER JOIN sSetup.tOrgGroupMaster OGMR ON OGMR.Id=OM.OrgGroupId
				INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BM.OrgGroupBatchId
				INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
				INNER JOIN sSetup.tClassMaster CM ON CM.ID=A.ClassId
				INNER JOIN sSetup.tDivisionMaster DM ON DM.ID=A.DivisionID
				LEFT JOIN sStudent.tStudentOther SOD ON SOD.StudentId=A.StudentId
				Left JOIN sStudent.tStudentCommunication SC on SM.Id=SC.StudentID
			WHERE 
				((@rOrgGroupId <>0 AND OGMR.Id=@rOrgGroupId) OR (@rOrgId<>0 AND OM.Id=@rOrgId))
				AND DM.ClassId=@rClassId AND COGBM.Id=@rCommonOrgGroupBatchId
				AND ((@rGenderType=1 AND SOD.GenderID=1) OR (@rGenderType=2 AND SOD.GenderID=2) OR (@rGenderType=0 AND 0=0))
				-- IsInContext
				AND BM.IsInContext = 1
        END
        
     ELSE IF @rTypeId=12 OR @rTypeId=22
      
        BEGIN
         
            SELECT 				
			   (DM.Id) AS DivisionId,
			   DM.Code AS ClassDivision,
			    SMD.Code As StudentId,
			    AE.Id AS SourceId,
			    (SMD.FirstName+' '+SMD.LastName) AS StudentName,
			    (SC.ParentContactNo) AS ContactNo
			FROM sAttendance.tStudentRegister SME 
				INNER JOIN sStudent.tAcademic AE ON SME.Academicid=AE.id
				INNER JOIN sSetup.tBatchMaster BME ON BME.Id = AE.BatchId
				INNER JOIN sSetup.tOrganizationMaster OME ON OME.Id = BME.OrgId
				INNER JOIN sSetup.tOrgGroupMaster OGME ON OGME.Id=OME.OrgGroupId
				INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BME.OrgGroupBatchId
        INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
				INNER JOIN sSetup.tDivisionMaster DM ON DM.ID=AE.DivisionID
				INNER JOIN sStudent.tStudentMaster SMD ON SMD.Id=AE.StudentID
				INNER JOIN sStudent.tStudentOther SOD ON SOD.StudentId=SMD.Id and SMD.StatusId=1	
				Left JOIN sStudent.tStudentCommunication SC on SMD.Id=SC.StudentID
			WHERE ((@rOrgGroupId <>0 AND OGME.Id=@rOrgGroupId) OR (@rOrgId<>0 AND OME.Id=@rOrgId))
					AND SME.IsPresent=1 AND COGBM.Id=@rCommonOrgGroupBatchId 
					--AND SME.AttendanceDate=CONVERT(char(10), @rUpToDate,126)
					AND ((SME.AttendanceDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = '')) 
					AND ((SME.AttendanceDate <= @rToDate) OR (ISNULL(@rToDate,'') = ''))
					AND DM.ClassId=@rClassId AND COGBM.Id=@rCommonOrgGroupBatchId  
				    AND((@rGenderType=1 AND SOD.GenderID=1) OR (@rGenderType=2 AND SOD.GenderID=2) OR (@rGenderType=0 AND 0=0))
					AND SME.AttendanceTypeId = 1
					-- IsInContext
					AND BME.IsInContext = 1
       END  
    
     ELSE IF @rTypeId=13 OR @rTypeId=23
        BEGIN
         (select 
			(DM.Id) AS DivisionId,
			   DM.Code AS ClassDivision,
			    SMD.Code As StudentId,
			    AE.Id AS SourceId,
			    (SMD.FirstName+' '+SMD.LastName) AS StudentName,
			    (SC.ParentContactNo) AS ContactNo
		  FROM sAttendance.tStudentRegister SME 
			 INNER JOIN sStudent.tAcademic AE ON SME.Academicid=AE.id
			 INNER JOIN sSetup.tBatchMaster BME ON BME.Id = AE.BatchId --AND BME.IsActive = 1
			 INNER JOIN sSetup.tOrganizationMaster OME ON OME.Id = BME.OrgId
			 INNER JOIN sSetup.tOrgGroupMaster OGMEA ON OGMEA.Id=OME.OrgGroupId
			 INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BME.OrgGroupBatchId
             INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
			 INNER JOIN sSetup.tDivisionMaster DM ON DM.ID=AE.DivisionID
			 INNER JOIN sStudent.tStudentMaster SMD ON SMD.Id=AE.StudentID and SMD.StatusId=1	
			 INNER JOIN sStudent.tStudentOther SOD ON SOD.StudentId=SMD.Id
			 Left JOIN sStudent.tStudentCommunication SC on SMD.Id=SC.StudentID
					
		   WHERE ((@rOrgGroupId <>0 AND OGMEA.Id=@rOrgGroupId) OR (@rOrgId<>0 AND OME.Id=@rOrgId))
					AND SME.IsPresent=0 AND COGBM.Id=@rCommonOrgGroupBatchId AND COGBM.Id=@rCommonOrgGroupBatchId  
					--AND SME.AttendanceDate=CONVERT(char(10), @rUpToDate,126)--@rUptoDate
					AND ((SME.AttendanceDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = '')) AND
					((SME.AttendanceDate <= @rToDate) OR (ISNULL(@rToDate,'') = ''))
					AND DM.ClassId=@rClassId AND ((@rGenderType=1 AND SOD.GenderID=1) OR (@rGenderType=2 AND SOD.GenderID=2) OR (@rGenderType=0 AND 0=0)) AND SME.AttendanceTypeId = 1
					-- IsInContext
					AND BME.IsInContext = 1)
					
					
        END
    END
END
GO
PRINT N'Altering Procedure [sBiometric].[pRptEmployeeTimesheetInOutListGet]...';


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

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

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

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

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

	WHILE (@lCount>0)
	BEGIN
		--SET @lDay = format(@lCount,'00')
		SET @lDay = RIGHT('0' + CONVERT(varchar(2),@lCount), 2)

		SET @Query = 
		'INSERT INTO #tmpBiometricData
		SELECT EM.Id AS EmployeeId, EM.Code AS EmployeeCode, ISNULL(EM.FirstName,'''') + '' '' + ISNULL(EM.MiddleName,'''') + '' '' + ISNULL(EM.LastName,'''') AS EmployeeName,
			ISNULL(CAST(RTRIM(YEAR(MT.Attn_Dt) *10000+ MONTH(MT.Attn_Dt) *100+ '+CONVERT(nvarchar(2),@lDay)+') AS datetime),CAST(RTRIM('+CONVERT(nvarchar(4),@rForYear)+' *10000+ '+CONVERT(nvarchar(2),@rForMonth)+' *100+ '+CONVERT(nvarchar(2),@lDay)+') AS datetime)) AS Attn_Date,
			D'+CONVERT(nvarchar(2),@lDay)+' AS PresentStatus,
			D'+CONVERT(nvarchar(2),@lDay)+'_IN AS FirstIn,
			D'+CONVERT(nvarchar(2),@lDay)+'_OUT AS LastOut,
			D'+CONVERT(nvarchar(2),@lDay)+'_O AS OverTime,
			D'+CONVERT(nvarchar(2),@lDay)+'_L AS LateBy,
			D'+CONVERT(nvarchar(2),@lDay)+'_T AS Duration,
			D'+CONVERT(nvarchar(2),@lDay)+'_E AS EarlyBy,
			D'+CONVERT(nvarchar(2),@lDay)+'_S AS ShiftName,
			EJD.EmployeeDesignationId,
			EJD.OrganizationDepartmentId, 
			EJD.OrgGroupDepartmentID
		FROM sHRM.tEmployeeMaster EM
			INNER JOIN sHrm.tEmployeeJobDetail EJD ON EM.Id=EJD.EmployeeId
			LEFT JOIN sBiometric.tMonthTrans MT ON EM.Id=MT.EmployeeId AND MT.ATTN_DT >= CAST(RTRIM('+CONVERT(nvarchar(4),@rForYear)+' *10000+ '+CONVERT(nvarchar(2),@rForMonth)+' *100+ 01) AS datetime) AND MT.Attn_Dt <= CAST(RTRIM('+CONVERT(nvarchar(4),@rForYear)+' *10000+ '+CONVERT(nvarchar(2),@rForMonth)+' *100+ 01) AS datetime)
		WHERE (EM.Id = '+CONVERT(nvarchar(max),@rEmployeeId)+' OR '+CONVERT(nvarchar(max),@rEmployeeId)+' = 0)
			AND (EM.OrgId = '+CONVERT(nvarchar(4),@rOrgId)+' OR '+CONVERT(nvarchar(4),@rOrgId)+' = 0)
			AND (EJD.DateOfJoining<= '''+CONVERT(nvarchar(max),@lLasteDate)+''')
			AND ((EJD.DateOfleaving>= '''+CONVERT(nvarchar(max),@lFirstDate)+''') OR ISNULL(EJD.DateOfleaving,'''')='''')
			AND (ISNULL(MT.SourceTypeId,95) = 95 OR MT.SourceTypeId = 0)
			AND (EM.StatusId='+CONVERT(nvarchar(max),@rEmployeeStatusId)+' OR '+CONVERT(nvarchar(max),@rEmployeeStatusId)+'=0)'

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

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

	DROP TABLE #tmpBiometricData

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

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


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

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

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


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

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


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

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

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

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

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


GO

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

BEGIN 

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

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

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


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

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

-- Execute the dynamic SQL
	EXEC sp_executesql @sql;

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


GO

ALTER PROCEDURE [sCertificate].[pTemplateFunctionalFieldsGet]
           @rPrintTemplateFuctionalId int           
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON		
BEGIN	 	
	       IF(@rPrintTemplateFuctionalId=1)
	         BEGIN	            
	   --         SELECT SUBSTRING(
				--	(SELECT ',' + '['+ s.COLUMN_NAME +']'
				--	FROM (SELECT
				--		COLUMN_NAME
				--FROM
  		--			INFORMATION_SCHEMA.COLUMNS
				--WHERE
				--    TABLE_NAME = 'vPrintTemplateStudentBasicDetails') s
				--ORDER BY s.COLUMN_NAME
				--FOR XML PATH('')),2,200000) AS ColumnList	
				select TOP 1  ColumnList
                  FROM [sCertificate].[vPrintTemplateStudentBasicDetails]		    
			 END   
		   IF(@rPrintTemplateFuctionalId=2)
		     BEGIN
		  --      SELECT SUBSTRING(
				--	(SELECT ',' + '['+ s.COLUMN_NAME +']'
				--	FROM (SELECT
				--		COLUMN_NAME
				--FROM
  		--			INFORMATION_SCHEMA.COLUMNS
				--WHERE
				--    TABLE_NAME = 'vPrintTemplateBonafideCertificate') s
				--ORDER BY s.COLUMN_NAME
				--FOR XML PATH('')),2,200000) AS ColumnList	
				
				select TOP 1  ColumnList
                  FROM [sCertificate].[vPrintTemplateBonafideCertificate]
				
				
				
		     END
		     IF(@rPrintTemplateFuctionalId=3)
		     BEGIN
		  --      SELECT SUBSTRING(
				--	(SELECT ',' + '['+ s.COLUMN_NAME +']'
				--	FROM (SELECT
				--		COLUMN_NAME
				--FROM
  		--			INFORMATION_SCHEMA.COLUMNS
				--WHERE
				--    TABLE_NAME = 'vPrintTemplateCharacterCertificate') s
				--ORDER BY s.COLUMN_NAME
				--FOR XML PATH('')),2,200000) AS ColumnList	
				
				
				select TOP 1 ColumnList
                  FROM [sCertificate].[vPrintTemplateCharacterCertificate]
		     END
		     IF(@rPrintTemplateFuctionalId=4)
		     BEGIN
		  --      SELECT SUBSTRING(
				--	(SELECT ',' + '['+ s.COLUMN_NAME +']'
				--	FROM (SELECT
				--		COLUMN_NAME
				--FROM
  		--			INFORMATION_SCHEMA.COLUMNS
				--WHERE
				--    TABLE_NAME = 'vPrintTemplateFirstTrialCertificate') s
				--ORDER BY s.COLUMN_NAME
				--FOR XML PATH('')),2,200000) AS ColumnList	
				
				select TOP 1 ColumnList
                  FROM [sCertificate].[vPrintTemplateFirstTrialCertificate]
		     END
		      IF(@rPrintTemplateFuctionalId=5)
		     BEGIN
		  --      SELECT SUBSTRING(
				--	(SELECT ',' + '['+ s.COLUMN_NAME +']'
				--	FROM (SELECT
				--		COLUMN_NAME
				--FROM
  		--			INFORMATION_SCHEMA.COLUMNS
				--WHERE
				--    TABLE_NAME = 'vPrintTemplateLeavingCertificate') s
				--ORDER BY s.COLUMN_NAME
				--FOR XML PATH('')),2,200000) AS ColumnList	
				select TOP 1 ColumnList
                  FROM [sCertificate].[vPrintTemplateLeavingCertificate]
				
		     END
		     IF(@rPrintTemplateFuctionalId=6)
		     BEGIN
		  --      SELECT SUBSTRING(
				--	(SELECT ',' + '['+ s.COLUMN_NAME +']'
				--	FROM (SELECT
				--		COLUMN_NAME
				--FROM
  		--			INFORMATION_SCHEMA.COLUMNS
				--WHERE
				--    TABLE_NAME = 'vPrintTemplateTransferCertificate') s
				--ORDER BY s.COLUMN_NAME
				--FOR XML PATH('')),2,200000) AS ColumnList	
				
				--Changes for mantis 0040777/0040865 :  By Krunal K Patel : for Transfer Certificate Options Added.
				select TOP 1 ColumnList
                  --FROM [sCertificate].[vPrintTemplateTransferCertificate]
				  FROM [sCertificate].[vPrintTemplateTransferCertificateReport]
		     END
		      IF(@rPrintTemplateFuctionalId=7)
		     BEGIN
		  
				select TOP 1 ColumnList
                 
				  FROM [sHrm].[vPrintTemplateJoiningCertificateGet]
		     END
		     	 			
END
GO
PRINT N'Altering Procedure [sCommon].[pOrgGroupSetupRemove]...';


GO
ALTER PROCEDURE [sCommon].[pOrgGroupSetupRemove]
	 
	 @rOrgGroupId smallint
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
    BEGIN TRY
	
	IF EXISTS(SELECT TOP 1 1 FROM sSetup.tOrganizationMaster WHERE OrgGroupId = @rOrgGroupId)
	BEGIN
	SELECT -101 AS Result
	RETURN
	END
	
	
	BEGIN TRANSACTION
	 
	EXEC sp_msforeachtable "ALTER TABLE ? NOCHECK CONSTRAINT all"
    




DELETE FROM sAccounting.tAccountingYearMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sAccounting.tAccountMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sAccounting.tLedgerGroupMaster  WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sAccounting.tLedgerMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sAccounting.tTransaction WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sAccounting.tTransactionDetail WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgGroupId
DELETE FROM sActivity.tActivityTypeMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sActivity.tClubMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sActivity.tImmunizationChart WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sAdmission.tInquiryReferenceMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sAttendance.tAbsentReasonMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCertificate.tLeavingConductMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCertificate.tLeavingProgressMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCertificate.tLeavingReasonMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCertificate.tLeavingRemarkMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCommon.tAreaMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCommon.tBirthPlaceMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCommon.tCityMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCommon.tCountryMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCommon.tDistrictMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCommon.tHobbyMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCommon.tHostelMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCommon.tMotherTongueMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCommon.tNationalityMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCommon.tOccupationMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCommon.tPreviousSchoolMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCommon.tReligionMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCommon.tStateMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCommon.tSurnameMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCommunication.tBehaviourTypeMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCommunication.tBlog WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCommunication.tBlogComment WHERE CAST(LEFT(BlogId, 4) AS BIGINT) = @rOrgGroupId
DELETE FROM sCommunication.tBlogFavorite WHERE CAST(LEFT(BlogId, 4) AS BIGINT) = @rOrgGroupId
DELETE FROM sCommunication.tBlogScope WHERE CAST(LEFT(BlogId, 4) AS BIGINT) = @rOrgGroupId
DELETE FROM sCommunication.tCircular WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCommunication.tCircularScope WHERE CAST(LEFT(CircularId, 4) AS BIGINT) = @rOrgGroupId
DELETE FROM sCommunication.tCircularView WHERE CAST(LEFT(CircularId, 4) AS BIGINT) =@rOrgGroupId
DELETE FROM sCommunication.tNews WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCommunication.tNewsComment WHERE CAST(LEFT(NewsId, 4) AS BIGINT) = @rOrgGroupId
DELETE FROM sCommunication.tNewsScope WHERE CAST(LEFT(NewsId, 4) AS BIGINT) = @rOrgGroupId
DELETE FROM sCommunication.tPhotoCategoryMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCommunication.tPoll WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCommunication.tPollAnswer WHERE CAST(LEFT(PollId, 4) AS BIGINT) = @rOrgGroupId
DELETE FROM sCommunication.tPollMember WHERE CAST(LEFT(PollId, 4) AS BIGINT) = @rOrgGroupId
DELETE FROM sCommunication.tPollResult WHERE CAST(LEFT(PollId, 4) AS BIGINT) = @rOrgGroupId
DELETE FROM sCommunication.tQuery WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCommunication.tQueryCategoryAssignedTo WHERE CAST(LEFT(QueryCategoryId, 4) AS BIGINT) = @rOrgGroupId
DELETE FROM sCommunication.tQueryCategoryMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCommunication.tQueryComment WHERE CAST(LEFT(QueryId, 4) AS BIGINT) =  @rOrgGroupId
DELETE FROM sEExam.tDataBankMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sEExam.tDataSubjectMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sEExam.tDataTopicMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sEExam.tDataTopicTypeMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sEExam.tQuestionMaster WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgGroupId
DELETE FROM sEExam.tQuestionOption WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgGroupId
DELETE FROM sEExam.tQuestionParagraph WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgGroupId
DELETE FROM sEExam.tTestTemplateMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgGroupId
DELETE FROM sEExam.tTestTemplateQuestion WHERE CAST(LEFT(TestTemplateId, 4) AS INT) = @rOrgGroupId
DELETE FROM sFee.tChargeCategoryMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sFee.tChargeMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sFee.tFeeHeadMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sFee.tFeeMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sFee.tReceiptBookMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sFinanceCommon.tBankMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sFinanceCommon.tStockUomMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgGroupId
DELETE FROM sGSEB.tActivityGroupMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sGSEB.tActivityIndicatorMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sGSEB.tActivityMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sHostel.tHostelMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sHostel.tRoomCategoryMaster WHERE CAST(LEFT(HostelId, 4) AS int) = @rOrgGroupId
DELETE FROM sHostel.tRoomMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgGroupId
DELETE FROM sHrm.tQualificationMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sIp.tItemMainGroupMaster WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgGroupId
DELETE FROM sIp.tItemSubGroupMaster WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgGroupId
DELETE FROM sIp.tStockItemCategoryMaster WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgGroupId
DELETE FROM sIp.tStockItemMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sIp.tStoreLocationMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sLibrary.tBookAgeGroupMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sLibrary.tBookAuthorMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sLibrary.tBookLanguageMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sLibrary.tBookLocationMaster WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgGroupId
DELETE FROM sLibrary.tBookMaster WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgGroupId
DELETE FROM sLibrary.tBookPublisherMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgGroupId
DELETE FROM sLibrary.tBookSubjectMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgGroupId
DELETE FROM sLibrary.tBookSupplierMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgGroupId
DELETE FROM sLibrary.tBookTagMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgGroupId
DELETE FROM sLibrary.tLibraryMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sPayroll.tEsiProcess WHERE CAST(LEFT(PayProcessElementId, 4) AS BIGINT) = @rOrgGroupId
DELETE FROM sPayroll.tEsiSetup WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgGroupId
DELETE FROM sPayroll.tPayElement WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgGroupId
DELETE FROM sPayroll.tPayProcess WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgGroupId
DELETE FROM sPayroll.tPayProcessElement WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgGroupId
DELETE FROM sPayroll.tPayProcessEmployee WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgGroupId
DELETE FROM sPayroll.tPaySetup WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgGroupId
DELETE FROM sPayroll.tPaySetupDependent WHERE CAST(LEFT(PaySetupId, 4) AS INT) = @rOrgGroupId
DELETE FROM sPayroll.tPfProcess WHERE CAST(LEFT(PayProcessElementId, 4) AS BIGINT) = @rOrgGroupId
DELETE FROM sPayroll.tPfProcessCharge WHERE CAST(LEFT(PayProcessElementId, 4) AS BIGINT) = @rOrgGroupId
DELETE FROM sPayroll.tPfSetup WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgGroupId
DELETE FROM sPayroll.tProfessionalTaxRange WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgGroupId
DELETE FROM sProcurement.tVendorCategoryMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sProcurement.tVendorMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sSecurity.tModulePermission WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sSecurity.tOrganizationTask WHERE CAST(LEFT(OrgGroupId, 4) AS SMALLINT) = @rOrgGroupId
DELETE FROM sSecurity.tPermission WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sSecurity.tPermissionUser WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sSecurity.tRole WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgGroupId

 
DELETE FROM sStudent.tAdmissionCategoryMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgGroupId
DELETE FROM sTax.tTaxGroupMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sTransport.tBusRouteDestinationMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sTransport.tBusRouteMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sTransport.tVehicleMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCommon.tFamiliyCastMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sFee.tDepositHeadMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sScholarship.tScholarshipTypeMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sSetup.tOrgMainGroupMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sSetup.tOrgSubGroupMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sFee.tFeeMainGroupOrgGroupwise WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sHostel.tVisitorGatePass WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgGroupId
DELETE FROM sFee.tChargeReceiptBookMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sPayroll.tPayrollGroupMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sPayroll.tPayrollMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sPayroll.tPayrollYearMaster WHERE OrgGroupId = @rOrgGroupId

DELETE FROM sActivity.tEventTypeMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sSecurity.tRoleDashlet WHERE CAST(LEFT(RoleId, 4) AS INT) = @rOrgGroupId


DELETE FROM sCommon.tFrequencyMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCommon.tRangeDetail WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgGroupId
DELETE FROM sCommon.tRangeMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgGroupId
DELETE FROM sCommunication.tCircularTypeMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgGroupId
DELETE FROM sFinanceCommon.tCurrencyMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sFrontOffice.tCourierDispatch WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sFrontOffice.tCourierReceive WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sHostel.tBuildingMaster WHERE CAST(LEFT(HostelId, 4) AS INT) = @rOrgGroupId
DELETE FROM sHostel.tChangeRoom WHERE CAST(LEFT(RoomId, 4) AS INT) = @rOrgGroupId
DELETE FROM sHostel.tHostelAdmission WHERE CAST(LEFT(Hosteld, 4) AS INT) = @rOrgGroupId

DELETE FROM sLibrary.tLibraryAttendance WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgGroupId
DELETE FROM sLibrary.tMagazineMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgGroupId
DELETE FROM sLibrary.tMagazineReceive WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgGroupId
DELETE FROM sTransport.tExpenseTypeMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sTransport.tFuelLogs WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgGroupId
DELETE FROM sTransport.tFuelTypeMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgGroupId
DELETE FROM sTransport.tVehicleDocumentMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgGroupId

DELETE FROM sStudent.tCustomTagMaster WHERE OrgGroupId = @rOrgGroupId

DELETE FROM sTransport.tVehicleDocuments WHERE CAST(LEFT(VehicleId, 4) AS INT) = @rOrgGroupId
DELETE FROM sTransport.tVehicleMaintenance WHERE CAST(LEFT(VehicleId, 4) AS INT) = @rOrgGroupId
DELETE FROM sTransport.tVehicleMaintenanceDetail WHERE CAST(LEFT(VehicleMaintenanceId, 4) AS INT) = @rOrgGroupId
DELETE FROM sTransport.tVehicleTypeMaster WHERE OrgGroupId = @rOrgGroupId

--DELETE FROM sTimetable.tAssignSchoolRoom WHERE CAST(LEFT(TimeTableSchemaId, 4) AS INT) = @rOrgGroupId
DELETE FROM sTimetable.tDivisionTimeOff WHERE CAST(LEFT(TimeTableSchemaId, 4) AS INT) = @rOrgGroupId
--DELETE FROM sTimetable.tSchoolBuildingMaster WHERE  OrgGroupId = @rOrgGroupId
--DELETE FROM sTimetable.tSchoolRoomMaster WHERE  CAST(LEFT(SchoolBuildingId, 4) AS INT) = @rOrgGroupId
--DELETE FROM sTimetable.tSchoolRoomTimeOff WHERE  CAST(LEFT(TimeTableSchemaId, 4) AS INT) = @rOrgGroupId
DELETE FROM sTimetable.tTeacherTimeOff WHERE  CAST(LEFT(TimeTableSchemaId, 4) AS INT) = @rOrgGroupId

DELETE FROM sCommunication.tEbook WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCommunication.tEbookScope WHERE  CAST(LEFT(EbookId, 4) AS BIGINT) = @rOrgGroupId

DELETE FROM sActivity.tClubTypeMaster WHERE  OrgGroupId = @rOrgGroupId
DELETE FROM sActivity.tHouseGroupMaster WHERE  OrgGroupId = @rOrgGroupId
DELETE FROM sAdmission.tInquiryStatusMaster WHERE  OrgGroupId = @rOrgGroupId
DELETE FROM sCommunication.tCustomGroup WHERE  OrgGroupId = @rOrgGroupId
DELETE FROM sCommunication.tCustomGroupMember WHERE  CAST(LEFT(CustomGroupId, 4) AS BIGINT) = @rOrgGroupId
DELETE FROM sTally.tFeeLedgerMapping WHERE CAST(LEFT(FeeId, 4) AS INT) = @rOrgGroupId
DELETE FROM sTally.tReceiptBookCompanyMapping WHERE CAST(LEFT(OrgGroupBatchId, 4) AS INT) = @rOrgGroupId
DELETE FROM sTally.tReceiptPosting WHERE CAST(LEFT(OrgGroupBatchId, 4) AS INT) = @rOrgGroupId
DELETE FROM sTimetable.tClassRoom WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgGroupId
DELETE FROM sTimetable.tClassRoomTimeOff WHERE CAST(LEFT(ClassRoomId, 4) AS INT) = @rOrgGroupId
DELETE FROM sTimetable.tSchoolBuilding WHERE  OrgGroupId = @rOrgGroupId
 DELETE FROM sCommon.tCastCategoryMaster WHERE  OrgGroupId = @rOrgGroupId
DELETE FROM sCommon.tQuotaMaster WHERE  OrgGroupId = @rOrgGroupId
DELETE FROM sTransport.tTransportMaster WHERE  OrgGroupId = @rOrgGroupId

DELETE FROM sAlert.tOtherGroupDetail WHERE  CAST(LEFT(OtherGroupId, 4) AS INT) = @rOrgGroupId
DELETE FROM sAlert.tOtherGroupMaster WHERE  OrgGroupId = @rOrgGroupId
DELETE FROM sCommon.tAdmissionQuotaMaster WHERE  OrgGroupId = @rOrgGroupId
DELETE FROM sFee.tCollectionGroupMaster WHERE  CAST(LEFT(OrgGroupBatchId, 4) AS INT) = @rOrgGroupId

DELETE FROM sHrm.tWorkAreaMaster WHERE  OrgGroupId = @rOrgGroupId
DELETE FROM sIp.tUniformItem WHERE  OrgGroupId = @rOrgGroupId
DELETE FROM sIp.tUniformItemSize WHERE  CAST(LEFT(Id, 4) AS INT) = @rOrgGroupId
DELETE FROM sSetup.tShiftMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sTimetable.tAssignClassRoom WHERE CAST(LEFT(ClassRoomId, 4) AS INT) = @rOrgGroupId
DELETE FROM sIp.tUniformStock WHERE  CAST(LEFT(UniformSizeId, 4) AS INT) = @rOrgGroupId

DELETE FROM sSetup.tShiftMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sTimetable.tAssignClassRoom WHERE CAST(LEFT(ClassRoomId, 4) AS INT) = @rOrgGroupId
DELETE FROM sCommon.tReportOrgGroup WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sFee.tExemptionTypeMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sOp.tGatewayConfiguration WHERE OrgGroupId = @rOrgGroupId
DELETE FROM  sTimetable.tDivisionClassRoom WHERE CAST(LEFT(TimeTableSchemaId, 4) AS INT) = @rOrgGroupId
DELETE FROM  sTimetable.tSubjectClassRoom WHERE CAST(LEFT(TimeTableSchemaId, 4) AS INT) = @rOrgGroupId
DELETE FROM  sTimetable.tTimeTableDetail WHERE CAST(LEFT(TimetableId, 4) AS INT) = @rOrgGroupId
DELETE FROM sFee.tExemptionTypeDetail WHERE CAST(LEFT(ExemptionTypeId, 4) AS INT) = @rOrgGroupId
DELETE FROM sSecurity.tRoleModulePermission WHERE CAST(LEFT(RoleId, 4) AS INT) = @rOrgGroupId

/* -- Date : 13/06/2016 -- */
DELETE FROM sAlert.tNotificationLog WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgGroupId
DELETE FROM sAlert.tNotificationLog WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgGroupId
DELETE FROM sCanteen.tCanteenIssueDetail WHERE CAST(LEFT(CanteenIssueId, 4) AS INT) = @rOrgGroupId
DELETE FROM sCanteen.tCanteenMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCanteen.tFoodItemMaster WHERE CAST(LEFT(CanteenId, 4) AS INT) = @rOrgGroupId
DELETE FROM sFrontOffice.tLostFoundRegister WHERE OrgGroupId = @rOrgGroupId

DELETE FROM sHostel.tAssetTypeMaster WHERE CAST(LEFT(HostelId, 4) AS INT) = @rOrgGroupId
DELETE FROM sHostel.tAssignRoomAsset WHERE CAST(LEFT(HostelId, 4) AS INT) = @rOrgGroupId
DELETE FROM sHostel.tRoomAssetMaster WHERE CAST(LEFT(HostelId, 4) AS INT) = @rOrgGroupId
DELETE FROM sHrm.tLeaveReasonMaster WHERE OrgGroupId = @rOrgGroupId

DELETE FROM sSetup.tOrgGroupSetting WHERE OrgGroupId = @rOrgGroupId
 
DELETE FROM sStudent.tSUIdConfig WHERE OrgGroupId = @rOrgGroupId

DELETE FROM sTimetable.tAssignDivision WHERE CAST(LEFT(TimeTableSchemaId, 4) AS INT) = @rOrgGroupId

/* -- Date : 12/08/2016 -- */
DELETE FROM sHostel.tHostelDepositAdd WHERE CAST(LEFT(HostelId, 4) AS INT) = @rOrgGroupId
DELETE FROM sHostel.tHostelDepositAdjustment WHERE CAST(LEFT(HostelId, 4) AS INT) = @rOrgGroupId
DELETE FROM sHostel.tHostelDepositHeadMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sHostel.tHostelDepositRefund WHERE CAST(LEFT(HostelId, 4) AS INT) = @rOrgGroupId
DELETE FROM sSystem.tExceptionLog WHERE OrgGroupId = @rOrgGroupId

/* -- Date : 17/09/2016 -- */
DELETE FROM sCommon.tReportClient WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCommunication.tTempCircularScope WHERE CAST(LEFT(SourceID, 4) AS BIGINT) = @rOrgGroupId

DELETE FROM sErp.tCustomerMaster WHERE OrgGroupId = @rOrgGroupId

/* -- Date : 05/10/2016 -- */
DELETE FROM sHostel.tAttendanceRegister WHERE CAST(LEFT(HostelId, 4) AS INT) = @rOrgGroupId
DELETE FROM sRecruitment.tCandidateCommunications WHERE CAST(LEFT(CandidateId, 4) AS BIGINT) = @rOrgGroupId
DELETE FROM sRecruitment.tCandidateImages WHERE CAST(LEFT(CandidateId, 4) AS BIGINT) = @rOrgGroupId
DELETE FROM sRecruitment.tCandidateMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sRecruitment.tCandidatePreviousEmployment WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sRecruitment.tCandidateQualification WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sRecruitment.tCandidateVacancyCriteriaScore WHERE CAST(LEFT(CandidateId, 4) AS BIGINT) = @rOrgGroupId
DELETE FROM sRecruitment.tInterviewCriteria WHERE CAST(LEFT(VacancyId, 4) AS BIGINT) = @rOrgGroupId
DELETE FROM sRecruitment.tRecruitmentStatusLog WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sRecruitment.tVacancy WHERE OrgGroupId = @rOrgGroupId

/* -- Date : 24/11/2016 -- */

DELETE FROM siTax.tAssessmentYear WHERE OrgGroupId = @rOrgGroupId
DELETE FROM siTax.tForm16 WHERE OrgGroupId = @rOrgGroupId
DELETE FROM siTax.tForm16Detail WHERE CAST(LEFT(Form16Id, 4) AS BIGINT) = @rOrgGroupId
DELETE FROM siTax.tIncomeTaxChallan WHERE CAST(LEFT(AssesmentYearId, 4) AS INT) = @rOrgGroupId
DELETE FROM siTax.tIncomeTaxGroup WHERE OrgGroupId = @rOrgGroupId
DELETE FROM siTax.tIncomeTaxSlab WHERE OrgGroupId = @rOrgGroupId
DELETE FROM siTax.tIncomeTaxSubGroup WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sSetup.tBatchGroupMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sActivity.tPlacementCompanyMaster WHERE OrgGroupId = @rOrgGroupId


DELETE FROM sAppraisal.tConductTypeMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sErp.tCustomerActivationLog WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sSecurity.tIpPolicy WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sSecurity.tIpPolicyDetail WHERE  CAST(LEFT(IpPolicyId, 4) AS int) = @rOrgGroupId
DELETE FROM sSecurity.tTimePolicy WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sSecurity.tUserPolicy WHERE  CAST(LEFT(TimePolicyId, 4) AS int) = @rOrgGroupId


DELETE FROM sAppraisal.tKPATemplateDetail WHERE CAST(LEFT(KPATemplateId, 4) AS int) = @rOrgGroupId
DELETE FROM sAppraisal.tKPATemplateMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sOp.tGatewayProduct WHERE CAST(LEFT(GatewayConfigurationId, 4) AS int) = @rOrgGroupId
DELETE FROM sOp.tGatewayProductReceiptBookMapping WHERE CAST(LEFT(ReceiptBookId, 4) AS int) = @rOrgGroupId
DELETE FROM sProcurement.tSstockIssueTypeMaster WHERE OrgGroupId = @rOrgGroupId

DELETE FROM sFee.tFeeDepositExpenseTypeMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sHostel.tHostelAttendanceTypeMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sHostel.tHostelExpenseSubTypeMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sHostel.tHostelExpenseTypeMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sHostel.tHostelGatePassReasonMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sIp.tUniformOrderItem WHERE CAST(LEFT(StockItemId, 4) AS int) = @rOrgGroupId
DELETE FROM sProcurement.tStockIssueReturn WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sProcurement.tStockIssueReturnBatch WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sStudent.tStudentGroupMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sStudent.tStudentOtherGroupMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sStudent.tStudentUIdMaster WHERE OrgGroupId = @rOrgGroupId


DELETE FROM sAssetManagement.tAssetCheck WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sAssetManagement.tAssetInchargeUser WHERE CAST(LEFT(AssetId, 4) AS int) = @rOrgGroupId
DELETE FROM sCanteen.tBreakTypeMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCanteen.tDailyMenu WHERE CAST(LEFT(CanteenId, 4) AS int) = @rOrgGroupId

DELETE FROM sAlert.tAdVendorMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sFee.tChargeAccountMapping WHERE CAST(LEFT(ChargeId, 4) AS int) = @rOrgGroupId
DELETE FROM sFee.tChargeAccountPosting WHERE CAST(LEFT(ReceiptBookId, 4) AS int) = @rOrgGroupId
DELETE FROM sFee.tDepositeAccountMapping WHERE CAST(LEFT(DepositeHeadId, 4) AS int) = @rOrgGroupId
DELETE FROM sFee.tDepositeAccountPosting WHERE CAST(LEFT(DepositeHeadId, 4) AS int) = @rOrgGroupId

DELETE FROM sCommunication.tFeedback WHERE CAST(LEFT(OrgGroupBatchId, 4) AS int) = @rOrgGroupId
DELETE FROM sCommunication.tFeedbackAnswerTypeDetail WHERE CAST(LEFT(FeedbackAnswerTypeId, 4) AS int) = @rOrgGroupId
DELETE FROM sCommunication.tFeedbackAnswerTypeMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCommunication.tFeedbackAssign WHERE CAST(LEFT(FeedbackId, 4) AS bigint) = @rOrgGroupId
DELETE FROM sCommunication.tFeedbackFor WHERE CAST(LEFT(FeedbackId, 4) AS bigint) = @rOrgGroupId
DELETE FROM sCommunication.tFeedbackQuestionResponse WHERE CAST(LEFT(FeedbackResponseId, 4) AS bigint) = @rOrgGroupId
DELETE FROM sCommunication.tFeedbackResponse WHERE CAST(LEFT(Id, 4) AS bigint) = @rOrgGroupId
DELETE FROM sCommunication.tFeedbackTemplate WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCommunication.tFeedbackTemplateQuestion WHERE CAST(LEFT(FeedbackTemplateId, 4) AS bigint) = @rOrgGroupId
DELETE FROM sProcurement.tStockReset WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sProcurement.tStockResetBatch WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sSystem.tBackupLog WHERE CAST(LEFT(CreatedUserId, 4) AS bigint) = @rOrgGroupId
DELETE FROM sSystem.tPortalSync WHERE OrgGroupId = @rOrgGroupId

DELETE FROM sAccounting.tBudget WHERE CAST(LEFT(LedgerId, 4) AS int) = @rOrgGroupId
DELETE FROM sAccounting.tTransactionApprove WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sAccounting.tTransactionApproveDetail WHERE CAST(LEFT(LedgerId, 4) AS bigint) = @rOrgGroupId
DELETE FROM sSetup.tScreenMandatoryFeild WHERE OrgGroupId = @rOrgGroupId


DELETE FROM sCommunication.tPhotoCategoryScope WHERE CAST(LEFT(PhotoCategoryId, 4) AS int) = @rOrgGroupId
DELETE FROM sTool.tTestCase WHERE CAST(LEFT(Id, 4) AS int) = @rOrgGroupId

DELETE FROM sLibrary.tMagazineTypeMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sSecurity.tOrgGroupMobileAppDetail WHERE OrgGroupId = @rOrgGroupId

DELETE FROM sLibrary.tBookCategoryMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sLibrary.tBookSubCategoryMaster WHERE OrgGroupId = @rOrgGroupId


/*============================================*/

	-- special case will come orgwise and orggroupwise

DELETE FROM sCommon.tTableRowId WHERE OrgId = @rOrgGroupId 
DELETE FROM sConfig.tConfigurationSetup WHERE SourceTypeId = 2010 AND SourceId = @rOrgGroupId
DELETE FROM sSetup.tOrgGroupBatchMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgGroupId
DELETE FROM sSetup.tOrgGroupMaster WHERE Id=@rOrgGroupId


DELETE FROM sCanteen.tGuestRequest WHERE CAST(LEFT(CanteenId, 4) AS int) = @rOrgGroupId
DELETE FROM sSecurity.tPermissionUser WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sSystem.tLimitLog WHERE OrgGroupId = @rOrgGroupId


DELETE FROM sProcurement.tOtherStockBatch WHERE CAST(LEFT(StockBatchId, 4) AS int) = @rOrgGroupId
DELETE FROM sProcurement.tOtherStockIssue WHERE CAST(LEFT(StoreLocationId, 4) AS int) = @rOrgGroupId
DELETE FROM sProcurement.tOtherStockIssueBatch WHERE CAST(LEFT(OtherStockBatchId, 4) AS bigint) = @rOrgGroupId
DELETE FROM sProcurement.tOtherStockLocationMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sVts.tvtsOrgGroupMaster WHERE OrgGroupId = @rOrgGroupId

DELETE FROM sLibrary.tBookGroup1Master WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sLibrary.tBookGroup2Master WHERE OrgGroupId = @rOrgGroupId

DELETE FROM sHostel.tHostelEventAssign WHERE CAST(LEFT(HostelEventScheduleId, 4) AS int) = @rOrgGroupId
DELETE FROM sHostel.tHostelEventAttendance WHERE CAST(LEFT(HostelEventScheduleId, 4) AS int) = @rOrgGroupId

DELETE FROM sHostel.tHostelEventSchedule WHERE CAST(LEFT(OrgGroupBatchId, 4) AS int) = @rOrgGroupId
DELETE FROM sHostel.tHostelEventTypeMaster WHERE CAST(LEFT(HostelId, 4) AS int) = @rOrgGroupId

DELETE FROM sSetup.tOrgGroupConfiguration WHERE OrgGroupId = @rOrgGroupId



DELETE FROM sCommon.tOrgGroupDepartmentMaster WHERE OrgGroupId = @rOrgGroupId

DELETE FROM sFee.tFeeExpenseTypeMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sSecurity.tUserOrgGroup WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sSetup.tOrgGroupEIS WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sTransport.tBusRouteTripLog WHERE CAST(LEFT(BusRouteId, 4) AS int) = @rOrgGroupId
DELETE FROM sTransport.tBusRouteTripTemplate WHERE CAST(LEFT(BusRouteId, 4) AS int) = @rOrgGroupId


DELETE FROM sCommunication.tCircularTypeAssignedTo WHERE CAST(LEFT(CircularTypeId, 4) AS int) = @rOrgGroupId
DELETE FROM sErp.tSupportTicket WHERE OrgGroupId= @rOrgGroupId
DELETE FROM siTax.tTaxPlanning WHERE OrgGroupId= @rOrgGroupId
DELETE FROM sStudent.tStudentCustomFieldMaster WHERE OrgGroupId= @rOrgGroupId

DELETE FROM sErp.tCustomerPlugInLog WHERE OrgGroupId= @rOrgGroupId

DELETE FROM sErp.tScreenFunctionalityTraining WHERE OrgGroupId= @rOrgGroupId
DELETE FROM sCommon.tPhysicalDisabilityCategoryMaster WHERE OrgGroupId= @rOrgGroupId

DELETE FROM siTax.tForm16SubDetail WHERE CAST(LEFT(Form16Id, 4) AS bigint) = @rOrgGroupId
DELETE FROM sSecurity.tAssignSubRole WHERE CAST(LEFT(RoleId, 4) AS int) = @rOrgGroupId

DELETE FROM sCommunication.tChatGroupMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCommunication.tChatGroupScope WHERE CAST(LEFT(ChatGroupId, 4) AS int) = @rOrgGroupId


DELETE FROM sAcademic.tOnlineMeetingAccount WHERE OrgGroupId= @rOrgGroupId
DELETE FROM sCommunication.teContentTypeMaster WHERE OrgGroupId= @rOrgGroupId
DELETE FROM sCommunication.teContent WHERE CAST(LEFT(OrgGroupBatchId, 4) AS int) = @rOrgGroupId
DELETE FROM sPayroll.tPayElementHistory WHERE CAST(LEFT([PayrollId], 4) AS int) = @rOrgGroupId

DELETE FROM [sHrm].[tEmployeeCustomFieldMaster] WHERE OrgGroupId= @rOrgGroupId

DELETE FROM [sCommunication].[tDailyThoughtMaster] WHERE OrgGroupId= @rOrgGroupId
DELETE FROM [sCommunication].[tDailyThoughtSubjectMaster] WHERE OrgGroupId= @rOrgGroupId
DELETE FROM [sCommunication].[tDailyThoughtTemp] WHERE OrgGroupId= @rOrgGroupId

DELETE FROM [sErp].[tCustomerMessage] WHERE OrgGroupId= @rOrgGroupId

DELETE FROM[sCommunication].[tPlaylistMaster] WHERE OrgGroupId= @rOrgGroupId
DELETE FROM [sCommunication].[tPlaylistDetails] WHERE CAST(LEFT(PlaylistId, 4) AS int) =  @rOrgGroupId

DELETE FROM sRecruitment.tRecruitmentCriteriaDocument WHERE CAST(LEFT([VacancyId], 4) AS bigint) = @rOrgGroupId
DELETE FROM sRecruitment.tRecruitmentRecruiterDocument WHERE CAST(LEFT([RecruitmentId], 4) AS bigint) =  @rOrgGroupId
DELETE FROM [sCommon].[tPublishDocumentMaster] WHERE OrgGroupId = @rOrgGroupId

DELETE FROM [sFee].[tApplicablePayType] WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sRecruitment.tCandidateFamilyDetails WHERE OrgGroupId = @rOrgGroupId

DELETE FROM[sCommunication].[tQueryCategoryScope] WHERE CAST(LEFT([QueryCategoryId], 4) AS int) = @rOrgGroupId
DELETE FROM [sTransport].[tVehicleLog] WHERE OrgGroupId = @rOrgGroupId

DELETE FROM sIp.tStockChargeMapping  WHERE CAST(LEFT([ChargeId], 4) AS int) = @rOrgGroupId

DELETE FROM [sCommon].[tFamiliySubCasteMaster] WHERE OrgGroupId = @rOrgGroupId

DELETE FROM [sSetup].[tOnlineFormSetup] WHERE OrgGroupId = @rOrgGroupId
DELETE FROM [sLibrary].[tNewspaperMaster] WHERE CAST(LEFT([Id], 4) AS int) = @rOrgGroupId

DELETE FROM [sHrm].[tCommitteeMaster] WHERE OrgGroupId = @rOrgGroupId
DELETE FROM [sHrm].[tHouseMaster] WHERE OrgGroupId = @rOrgGroupId
DELETE FROM [sHrm].[tClubMaster] WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sHrm.tAssignClub WHERE CAST(LEFT([ClubId], 4) AS int) = @rOrgGroupId
DELETE FROM sHrm.tAssignHouse WHERE CAST(LEFT([HouseId], 4) AS int) = @rOrgGroupId
DELETE FROM sHrm.tAssignCommittee WHERE CAST(LEFT([CommitteeId], 4) AS int) = @rOrgGroupId
DELETE FROM sIp.tStockDefectiveItemMaster WHERE OrgGroupId = @rOrgGroupId
	
DELETE FROM sCommon.tTribeMaster WHERE OrgGroupId = @rOrgGroupId

DELETE FROM[sCommunication].[tMultiPhotoCategoryMaster] WHERE [OrgGroupId] = @rOrgGroupId
DELETE FROMsCommunication.tMultiPhotoCategoryScope WHERE CAST(LEFT([MultiPhotoCategoryId], 4) AS bigint) = @rOrgGroupId


DELETE FROM [sAssetManagement].[tAssetCustomFieldMaster] WHERE [OrgGroupId] = @rOrgGroupId
DELETE FROM sAssetManagement.tAssetCustomFieldData WHERE CAST(LEFT([AssetCustomFieldId], 4) AS int) = @rOrgGroupId

--remove from VitorTypeMaster
DELETE FROM [sFrontOffice].[tVisitorTypeMaster] WHERE OrgGroupId = @rOrgGroupId

DELETE FROM sProcurement.tStockKitMaster WHERE OrgGroupId = @rOrgGroupId

DELETE FROM sSetup.tCustomFieldMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sRecruitment.tVacancyCustomFieldMaster WHERE OrgGroupId = @rOrgGroupId

DELETE FROM sSecurity.tMigrationModulePermission WHERE OrgGroupId = @rOrgGroupId -- For Migration Redirection Entry Remove

EXEC sp_msforeachtable "ALTER TABLE ? WITH CHECK CHECK CONSTRAINT all"

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


GO
ALTER PROCEDURE [sCommon].[pTableRowIdModify]
	@rOrgGroupId [int],
	@rTableTitle [nvarchar](100),
	@rCurrentNumber [bigint] = NULL,
	@rSeed [bigint] = NULL,
	@rIncrement [bigint] = NULL,
	@rIsCurrentNumber [bit] = 0,
	@rNextNumber [bigint] = NULL OUTPUT
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	IF @rCurrentNumber > 0
		BEGIN
			UPDATE sCommon.tTableRowId WITH (ROWLOCK)
			   SET CurrentNumber = @rCurrentNumber
			  -- ,UpdatedDateTime = sCommon.fGetDate()
			 WHERE TableTitle = @rTableTitle AND
					OrgId = @rOrgGroupId
			 
		END
	ELSE
		BEGIN
			--SELECT CurrentNumber, 
			--		@rSeed, Seed,
			--		@rIncrement, Increment
			-- FROM sCommon.tTableRowId
			--  WHERE TableTitle = @rTableTitle
			  
			 UPDATE sCommon.tTableRowId WITH (ROWLOCK)
				SET @rNextNumber = CurrentNumber 
								 = (CASE @rIsCurrentNumber 
										 WHEN 1 THEN CurrentNumber
									ELSE (CASE WHEN CurrentNumber < Seed
											   THEN Seed
										  ELSE CurrentNumber + Increment END)
									END),
					Seed = ISNULL(@rSeed, Seed),
					Increment = ISNULL(@rIncrement, Increment),
					 UpdatedDateTime = sCommon.fGetDate()
			  WHERE TableTitle = @rTableTitle AND
					OrgId = @rOrgGroupId
		END
END
GO
PRINT N'Altering Procedure [sTool].[pUpgradeVersion]...';


GO

ALTER PROCEDURE [sTool].[pUpgradeVersion]
	 
	@rVersionId int,
	@rVersion nvarchar(20),
	@rOrgGroupId int

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

if 	@rVersionId = 0
BEGIN
SELECT 'Enter Version Id'
return	
END


if 	@rVersion = ''
BEGIN
SELECT 'Enter Version Detail'
return	
END

if 	@rOrgGroupId = 0
BEGIN
SELECT 'Enter Org Group Id'
return	
END



--if 	@rOrgGroupId = 1
--BEGIN
--SELECT '1 OrgGroup Not Valid'
--return	
--END

IF NOT EXISTS (SELECT 1 FROM sSetup.tOrgGroupMaster WHERE Id = @rOrgGroupId)
BEGIN
SELECT 'Org Group Not Exists'
return	
END

-- For Upgrade Vesion Start
INSERT INTO [sSystem].[tVersionUpdate] ([VersionNumber],[VersionId],[Status],[UpdateScript],[StartDateTime],[EndDateTime],[OrgGroupId])
VALUES(@rVersion,@rVersionId,'BEGIN','Upgrade Vesion',sCommon.fGetDate(),sCommon.fGetDate(),@rOrgGroupId)

--exec [sTool].[pInsertStaticData]
		
-- add newly added task for admin role
exec [sSecurity].[pNewTaskAdd] @rOrgGroupId

-- update tablerowid master data from excel to table

--pass orgGroupId
-- add new table row ids added
exec [sTool].[pTableRowIdAdd] @rOrgGroupId

-- Pass OrgGroupId
-- Remove tablrowid for organization
--exec sTool.pTableRowChangeOrgToOrgGroupRemove @rOrgGroupId

update sstudent.tAcademic   set rollno = 0 where RollNo is null



delete from sSecurity.tPermission where TaskId in (select ID from sSecurity.tTask where IsObsolete = 1)
delete from sSecurity.tPermission where TaskId not in (select ID from sSecurity.tTask)




exec [sTool].[pTableRowIdCurrentNumberSet] @rOrgGroupId

IF NOT EXISTS(SELECT 1 FROM sCommunication.teContentTypeMaster WHERE Id = sCommon.fGetIntIdForOrg(1,@rOrgGroupId))
 BEGIN
				INSERT INTO sCommunication.teContentTypeMaster
					   ([Id]
					   ,[Code]
					   ,[Title]
					   ,[IsObsolete]
					   ,[CreatedUserId]
					   ,[CreatedDateTime]
					   ,[UpdatedUserId]
					   ,[UpdatedDateTime]
					   ,[OrgGroupId])
				 SELECT
						 sCommon.fGetIntIdForOrg(1,@rOrgGroupId)
						,'Subject'
						,'Subject'
						,0
						,1
						,getdate()
						,1
						,getdate()
						,@rOrgGroupId
						
 END


IF NOT EXISTS(SELECT 1 FROM sCommunication.tCircularTypeMaster WHERE Id = sCommon.fGetIntIdForOrg(1,@rOrgGroupId))
 BEGIN
				INSERT INTO sCommunication.tCircularTypeMaster
					   ([Id]
					   ,[Code]
					   ,[Title]
					   ,[IsObsolete]
					   ,[CreatedUserId]
					   ,[CreatedDateTime]
					   ,[UpdatedUserId]
					   ,[UpdatedDateTime]
					   ,[OrgGroupId]
					   ,HighlightColor)
				 SELECT
						 sCommon.fGetIntIdForOrg(1,@rOrgGroupId)
						,'Circular'
						,'Circular'
						,0
						,1
						,getdate()
						,1
						,getdate()
						,@rOrgGroupId
						,NULL
 END

IF NOT EXISTS(SELECT 1 FROM sCommon.tPublishDocumentMaster WHERE Id = sCommon.fGetIntIdForOrg(1,@rOrgGroupId))
BEGIN				
				INSERT INTO sCommon.tPublishDocumentMaster
					   ([Id]
					   ,[Code]
					   ,[Title]
					   ,[IsObsolete]
					   ,[CreatedUserId]
					   ,[CreatedDateTime]
					   ,[UpdatedUserId]
					   ,[UpdatedDateTime]
					   ,[OrgGroupId])
				 VALUES
						(sCommon.fGetIntIdForOrg(1,@rOrgGroupId),'Fee Receipt','Fee Receipt',0,1,Getdate(),1,Getdate(),@rOrgGroupId),
						(sCommon.fGetIntIdForOrg(2,@rOrgGroupId),'Bonafide','Bonafide',0,1,Getdate(),1,Getdate(),@rOrgGroupId),
						(sCommon.fGetIntIdForOrg(3,@rOrgGroupId),'Trial','Trial',0,1,Getdate(),1,Getdate(),@rOrgGroupId),
						(sCommon.fGetIntIdForOrg(4,@rOrgGroupId),'Charactor','Charactor',0,1,Getdate(),1,Getdate(),@rOrgGroupId),
						(sCommon.fGetIntIdForOrg(5,@rOrgGroupId),'Id Card','Id Card',0,1,Getdate(),1,Getdate(),@rOrgGroupId)
						
END


IF NOT EXISTS(SELECT 1 FROM sAdmission.tInquiryStatusMaster WHERE OrgGroupId = @rOrgGroupId)
BEGIN				
				INSERT INTO sAdmission.tInquiryStatusMaster
					   ([Id]
					   ,[Code]
					   ,[Title]
					   ,[IsObsolete]
					   ,[CreatedUserId]
					   ,[CreatedDateTime]
					   ,[UpdatedUserId]
					   ,[UpdatedDateTime]
					   ,[OrgGroupId]
					   ,StatusId
					   --,HighlightColor
					   --,InquiryMainStatusId
					   )
				 SELECT
						 sCommon.fGetIntIdForOrg(Id,@rOrgGroupId)
						,Title
						,Title
						,0
						,1
						,getdate()
						,NULL
						,NULL
						,@rOrgGroupId
						,Id	
						--,ISM.HighlightColor
						--,ISM.InquiryMainStatusId					
						FROM sCommon.tStatusMaster
						--INNER JOIN sAdmission.tInquiryStatusMaster ISM ON SM.Id = ISM.StatusId AND ISM.OrgGroupId = 1
						where statustypeId = 104


						UPDATE ISM  
							SET ISM.HighlightColor = ISM1.HighlightColor ,
								ISM.InquiryMainStatusId = ISM1.InquiryMainStatusId
							FROM sAdmission.tInquiryStatusMaster ISM  
							INNER JOIN sAdmission.tInquiryStatusMaster ISM1 ON ISM.StatusId = ISM1.StatusId AND ISM1.OrgGroupId = 1
							INNER JOIN sCommon.tStatusMaster SM ON SM.Id = ISM1.StatusId 
							where SM.statustypeId = 104 AND ISM.OrgGroupId = @rOrgGroupId

						
	DECLARE @lMaxId int
	SET @lMaxId = sCommon.fGetIntIdForOrg(213,@rOrgGroupId)					
	EXECUTE sCommon.pTableRowIdModify @rOrgGroupId, @rTableTitle = 'sAdmission.tInquiryStatusMaster', @rCurrentNumber = @lMaxId
						
END

--static entry in tVisitorTypeMaster

IF NOT EXISTS(SELECT 1 FROM sFrontOffice.tVisitorTypeMaster WHERE Id = 1)
BEGIN	
	INSERT INTO [sFrontOffice].[tVisitorTypeMaster]
           ([Id]
           ,[Code]
           ,[Title]
           ,[IsObsolete]
           ,[CreatedUserId]
           ,[CreatedDateTime]
           ,[UpdatedUserId]
           ,[UpdatedDateTime]
           ,[OrgGroupId])
     VALUES
           (1,
		   'Visitor',
		   'Visitor',
		   0,
		   1,
		   GetDate(),
		   NULL,
		   NULL,
		   1)
END

IF NOT EXISTS(SELECT 1 FROM sFrontOffice.tVisitorTypeMaster WHERE Id = 2)
BEGIN	
	INSERT INTO [sFrontOffice].[tVisitorTypeMaster]
           ([Id]
           ,[Code]
           ,[Title]
           ,[IsObsolete]
           ,[CreatedUserId]
           ,[CreatedDateTime]
           ,[UpdatedUserId]
           ,[UpdatedDateTime]
           ,[OrgGroupId])
     VALUES
           (2,
		   'Parents',
		   'Parents',
		   0,
		   1,
		   GetDate(),
		   NULL,
		   NULL,
		   1)
END

--OrgGoup wise VisitorTypeMaster entry
IF NOT EXISTS(SELECT 1 FROM sFrontOffice.tVisitorTypeMaster WHERE OrgGroupId = @rOrgGroupId AND Id = sCommon.fGetIntIdForOrg(1,@rOrgGroupId))
BEGIN
	INSERT INTO [sFrontOffice].[tVisitorTypeMaster]
			   (
			    [Id]
			   ,[Code]
			   ,[Title]
			   ,[IsObsolete]
			   ,[CreatedUserId]
			   ,[CreatedDateTime]
			   ,[UpdatedUserId]
			   ,[UpdatedDateTime]
			   ,[OrgGroupId])
		 VALUES
			   (
			   sCommon.fGetIntIdForOrg(1,@rOrgGroupId),
			   'Visitor',
			   'Visitor',
			   0,
			   --1,
			   [sCommon].[fGetBigIntIdForOrg](3,@rOrgGroupId),
			   GetDate(),
			   NULL,
			   NULL,
			   @rOrgGroupId)
END

IF NOT EXISTS(SELECT 1 FROM sFrontOffice.tVisitorTypeMaster WHERE OrgGroupId = @rOrgGroupId AND Id = sCommon.fGetIntIdForOrg(2,@rOrgGroupId))
BEGIN
	INSERT INTO [sFrontOffice].[tVisitorTypeMaster]
			   (
			    [Id]
			   ,[Code]
			   ,[Title]
			   ,[IsObsolete]
			   ,[CreatedUserId]
			   ,[CreatedDateTime]
			   ,[UpdatedUserId]
			   ,[UpdatedDateTime]
			   ,[OrgGroupId])
		 VALUES
			   (
			   sCommon.fGetIntIdForOrg(2,@rOrgGroupId),
			   'Parents',
			   'Parents',
			   0,
			   --1,
			   [sCommon].[fGetBigIntIdForOrg](3,@rOrgGroupId),
			   GetDate(),
			   NULL,
			   NULL,
			   @rOrgGroupId)
END

--PeriodNoMaster Entry

IF NOT EXISTS(SELECT 1 FROM [sAttendance].[tPeriodNoMaster])
BEGIN	

INSERT INTO [sAttendance].[tPeriodNoMaster]
           ([Id]
           ,[Title]
           ,[IsObsolete])
     VALUES
          (1, '1', 0),
		  (2, '2', 0),
		  (3, '3', 0),
		  (4, '4', 0),
		  (5, '5', 0),
		  (6, '6', 0),
		  (7, '7', 0),
		  (8, '8', 0),
		  (9, '9', 0),
		  (10,'10', 0),
		  (11,'11', 0),
		  (12,'12', 0)

END

IF NOT EXISTS(SELECT 1 FROM sCommon.tCastCategoryMaster WHERE OrgGroupId = @rOrgGroupId)
BEGIN				
				INSERT INTO sCommon.tCastCategoryMaster
					   ([Id]
					   ,[Number]
					   ,[Code]
					   ,[Title]
					   ,[IsObsolete]
					   ,[CreatedUserId]
					   ,[CreatedDateTime]
					   ,[UpdatedUserId]
					   ,[UpdatedDateTime]
					   ,[OrgGroupId]
					   , MainCastCategoryId 
					   ,OrderIndex)
				 SELECT
						 sCommon.fGetIntIdForOrg(Id,@rOrgGroupId)
						,Id	
						,Code
						,Title
						,0
						,1
						,getdate()
						,1
						,getdate()
						,@rOrgGroupId
						,Id
						,Id						
						FROM sCommon.tMainCastCategoryMaster
						 
						
	DECLARE @lMaxCatId int
	SET @lMaxCatId = sCommon.fGetIntIdForOrg(100,@rOrgGroupId)					
	EXECUTE sCommon.pTableRowIdModify @rOrgGroupId, @rTableTitle = 'sCommon.tCastCategoryMaster', @rCurrentNumber = @lMaxCatId

UPDATE
    o
SET
    o.CastCategoryId	=  sCommon.fGetIntIdForOrg(o.CastCategoryId,@rOrgGroupId)
FROM
    sStudent.tStudentOther o
    INNER JOIN
    sStudent.tStudentMaster S ON S.Id = o.StudentId
WHERE
o.CastCategoryId < 100 
AND CastCategoryId IS NOT NULL
AND S.OrgId IN (SELECT Id From sSetup.tOrganizationMaster WHERE OrgGroupId = @rOrgGroupId)		
			
UPDATE sAdmission.tAdmissionForm SET CastCategoryId	= sCommon.fGetIntIdForOrg(CastCategoryId,@rOrgGroupId)	
WHERE CastCategoryId IS NOT NULL AND CastCategoryId < 100 
AND OrgId IN (SELECT Id From sSetup.tOrganizationMaster WHERE OrgGroupId = @rOrgGroupId)

UPDATE sCommon.tFamiliyCastMaster SET 	CastCategoryId	=  sCommon.fGetIntIdForOrg(CastCategoryId,@rOrgGroupId)	
WHERE CastCategoryId IS NOT NULL AND CastCategoryId < 100   AND OrgGroupId = @rOrgGroupId

UPDATE sCommon.tSurnameMaster SET 	CastCategoryId	=  sCommon.fGetIntIdForOrg(CastCategoryId,@rOrgGroupId)	
WHERE CastCategoryId IS NOT NULL AND CastCategoryId < 100 AND OrgGroupId = @rOrgGroupId
			
			
END


IF NOT EXISTS(SELECT 1 FROM sTransport.tTransportMaster WHERE OrgGroupId = @rOrgGroupId)
BEGIN				
				INSERT INTO sTransport.tTransportMaster
					   ([Id]
					   ,[Number]
					   ,[Code]
					   ,[Title]
					   ,[IsObsolete]
					   ,[CreatedUserId]
					   ,[CreatedDateTime]
					   ,[UpdatedUserId]
					   ,[UpdatedDateTime]
					   ,[OrgGroupId]					    
					   )
				 SELECT
						 sCommon.fGetIntIdForOrg(1,@rOrgGroupId)
						,1
						,'Common'
						,'Common'
						,0
						,1
						,getdate()
						,1
						,getdate()
						,@rOrgGroupId
						 
		DECLARE @lMaxTranId int
	SET @lMaxTranId = sCommon.fGetIntIdForOrg(1,@rOrgGroupId)					
	EXECUTE sCommon.pTableRowIdModify @rOrgGroupId, @rTableTitle = 'sTransport.tTransportMaster', @rCurrentNumber = @lMaxTranId
						 
					 				
	INSERT INTO sTransport.tAssignTransportOrg
					   (TransportId
					   ,OrgId					    				    
					   )
	SELECT 		
	@lMaxTranId
	,Id
	FROM
	sSetup.tOrganizationMaster
	WHERE OrgGroupId = 		@rOrgGroupId	 
						 
						

UPDATE sTransport.tBusRouteMaster
SET TransportId = @lMaxTranId WHERE OrgGroupId = @rOrgGroupId

UPDATE sTransport.tVehicleMaster
SET TransportId = @lMaxTranId WHERE OrgGroupId = @rOrgGroupId


			
			
END


IF NOT EXISTS(SELECT 1 FROM sSetup.tBatchGroupMaster WHERE OrgGroupId = @rOrgGroupId AND Id =  sCommon.fGetIntIdForOrg(1,@rOrgGroupId))
BEGIN				
				INSERT INTO sSetup.tBatchGroupMaster
					   ([Id]
					   ,[Number]
					   ,[Code]
					   ,[Title]
					   ,[OrgGroupId]					    
					   ,[OrderIndex]
					   ,[CreatedUserId]
					   ,[CreatedDateTime]
					   ,[UpdatedUserId]
					   ,[UpdatedDateTime]
					   )
				 SELECT
						 sCommon.fGetIntIdForOrg(1,@rOrgGroupId)
						,1
						,'Common'
						,'Common'
						,@rOrgGroupId
						,1
						
						,1
						,getdate()
						,1
						,getdate()
						
						 
	--DECLARE @lBatchGroupId int
	--SET @lMaxTranId = sCommon.fGetIntIdForOrg(1,@rOrgGroupId)					
	--EXECUTE sCommon.pTableRowIdModify @rOrgGroupId, @rTableTitle = 'sSetup.tBatchGroupMaster', @rCurrentNumber = @lBatchGroupId
	
	UPDATE B    
	SET BatchGroupId = sCommon.fGetIntIdForOrg(1,@rOrgGroupId)
	FROM sSetup.tBatchMaster B INNER JOIN sSetup.tOrganizationMaster O ON B.OrgId = O.ID
	WHERE O.OrgGroupId = @rOrgGroupId AND B.BatchGroupId IS NULL

END


UPDATE sSetup.tClassMaster SET DepartmentId = sCommon.fGetIntIdForOrg(OrgId,1) where DepartmentId is null

if (@rOrgGroupId <> 1154)
BEGIN
UPDATE sCommon.tReport SET IsObsolete = 1
 Where Id in (20642,20643,20644,20645,20646,20647,20648,20649,20650,20665,20718,20779,20692,20693,20694)

END

UPDATE sSystem.tDatabaseInfo SET ApplicationId = 1

UPDATE sSystem.tDatabaseInfo SET 
VersionNumber = @rVersion,
VersionId = @rVersionId,
LastVersionUpdateDateTime = getdate() ,
IsNewVersion = 1
WHERE ApplicationId = 1 
 
-- for student - remove permission for employee center
DECLARE @lRoleId int = 0
DECLARE @lDefaultRoleId int = 10
SET @lRoleId = (@rOrgGroupId * 100000) + @lDefaultRoleId
 
--DELETE P FROM sSecurity.tPermission P INNER JOIN sSecurity.tTask T ON P.TaskId = T.Id 
--WHERE P.RoleId = @lRoleId AND P.OrgGroupId=@rOrgGroupId AND T.ModuleId =  234

---- for employee - remove permisiion for student center
--SET @lDefaultRoleId = 22
--SET @lRoleId = (@rOrgGroupId * 100000) + @lDefaultRoleId
--DELETE P FROM sSecurity.tPermission P INNER JOIN sSecurity.tTask T ON P.TaskId = T.Id 
--WHERE P.RoleId = @lRoleId AND P.OrgGroupId=@rOrgGroupId AND T.ModuleId =  233

-- for SysSuperAdmin
SET @lDefaultRoleId = 1
SET @lRoleId = (@rOrgGroupId * 100000) + @lDefaultRoleId
DELETE P FROM sSecurity.tPermission P INNER JOIN sSecurity.tTask T ON P.TaskId = T.Id 
WHERE P.RoleId = @lRoleId AND P.OrgGroupId=@rOrgGroupId
AND T.Id IN (30258,30262,30266,30257,30160,30243,30244)

IF NOT EXISTS (SELECT 1 FROM sSecurity.tOrganizationTask  T   WHERE TaskId = 20596  AND OrgGroupId = @rOrgGroupId)
BEGIN
	INSERT INTO sSecurity.tOrganizationTask 
	(OrgGroupId, TaskId, AvailablePermission)
	SELECT  @rOrgGroupId,20596,2
END

--default permission for Lesson Plan Complete Task for Admin only (for execute permission)
IF NOT EXISTS (SELECT 1 FROM sSecurity.tOrganizationTask  T   WHERE TaskId = 31244  AND OrgGroupId = @rOrgGroupId)
BEGIN
	INSERT INTO sSecurity.tOrganizationTask 
	(OrgGroupId, TaskId, AvailablePermission)
	SELECT  @rOrgGroupId,31244,64
END

IF NOT EXISTS (SELECT * FROM sSecurity.tPermission   WHERE RoleId =sCommon.fGetIntIdForOrg(2,@rOrgGroupId) AND TaskId = 20596  AND OrgGroupId = @rOrgGroupId)
BEGIN
	INSERT INTO sSecurity.tPermission(TaskId, RoleId, Permission, IsObsolete, CreatedUserId, CreatedDateTime, UpdatedUserId, UpdatedDateTime,OrgGroupId)
	SELECT  20596,sCommon.fGetIntIdForOrg(2,@rOrgGroupId),2,0,1,sCommon.fGetDate(),1,sCommon.fGetDate(),@rOrgGroupId
	FROM sSecurity.tOrganizationTask WHERE OrgGroupId = @rOrgGroupId
END

---- for SysSuperAdmin update password
--UPDATE sSecurity.tUser SET LoginPassword='XAqFcL/nd0bnDNhkyF/PxobplNJ+ggbN9370AHxj7oU=' WHERE Id = sCommon.fGetBigIntIdForOrg(1,@rOrgGroupId)
--UPDATE sSecurity.tUser SET LoginPassword='XAqFcL/nd0bnDNhkyF/PxobplNJ+ggbN9370AHxj7oU=' WHERE Id = 1

-- for SysSuperAdmin update password
UPDATE sSecurity.tUser SET LoginPassword='5MM16xTaq777OzqQHkRp4g==' WHERE Id = sCommon.fGetBigIntIdForOrg(1,@rOrgGroupId)
UPDATE sSecurity.tUser SET LoginPassword='5MM16xTaq777OzqQHkRp4g==' WHERE Id = 1

 -- For Upgrade Vesion END
INSERT INTO [sSystem].[tVersionUpdate] ([VersionNumber],[VersionId],[Status],[UpdateScript],[StartDateTime],[EndDateTime],[OrgGroupId])
VALUES(@rVersion,@rVersionId,'END','Upgrade Vesion',sCommon.fGetDate(),sCommon.fGetDate(),@rOrgGroupId)

END
GO
PRINT N'Altering Procedure [sCommunication].[pAssignmentGetWithScope]...';


GO

ALTER PROCEDURE [sCommunication].[pAssignmentGetWithScope]
	 @rId bigint = 0,
	 @rSubjectId int,
	 @rTitle nvarchar(100),
	 @rFromDate date,
	 @rToDate date,
	 @rBatchId int,
	 @rIsSearch bit = 1,
	 @rCreatedUserId bigint=0,
	 @rClassId int = 0,
	 @rDivisionId int = 0
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	 IF @rIsSearch = 1
		BEGIN
			SET @rTitle = sCommon.fSearchStringGet(@rTitle)
		END
	
	DECLARE @lIsOptional int 
	SET @lIsOptional = (Select TOP 1 1 from sSetup.tSubjectMaster AS SM INNER JOIN [sSetup].[tClassSubject] As CS ON CS.SubjectId = SM.Id INNER JOIN sSetup.tDivisionMaster AS DM ON DM.ClassId = CS.ClassId WHERE CS.IsOptional = 1 AND SubjectId = @rSubjectId AND DM.Id = @rDivisionId Order by CS.ClassId)

	SELECT 
		DISTINCT
			A.Id as AssignmentId,
			A.SubjectId,
			SM.Title as SubjectName,
			A.Title,
			A.Remark,
			A.StartDate,
			A.EndDate,
			U.DisplayTitle as CreatedUserName,
			CASE WHEN @lIsOptional = 1
			THEN
			STUFF((			  
			SELECT ',' + SM.Code FROM [sCommunication].[tAssignmentScope] CAS INNER JOIN sStudent.tStudentMaster SM ON CAS.SourceId = SM.Id Where CAS.AssignmentId = A.Id AND CAS.SourceTypeId = 2003		  
			FOR XML PATH ('')), 1, 1, '') --Added for mantis : 42198
			ELSE
			STUFF((
			SELECT ',' + DM.Code FROM [sCommunication].[tAssignmentScope] CAS INNER JOIN sSetup.tDivisionMaster DM ON CAS.SourceId = DM.Id Where  CAS.AssignmentId = A.Id AND CAS.SourceTypeId = 2005 
			FOR XML PATH ('')), 1, 1, '') END as StudentSource ,			 
			STUFF((			  
			SELECT ',' + Code FROM [sCommunication].[tAssignmentScope] CAS INNER JOIN sSetup.tDepartmentMaster CM ON CAS.SourceId = CM.Id Where CAS.AssignmentId = A.Id AND CAS.SourceTypeId = 2017			  
			FOR XML PATH ('')), 1, 1, '') as EmployeeSource,			
			A.CreatedDateTime
		    
  FROM 
   --         sCommunication.tAssignment A
			--INNER JOIN [sCommunication].[tAssignmentScope] CAS on A.Id = CAS.AssignmentId
   --         INNER JOIN sSecurity.tUser U ON U.Id=A.CreatedUserId
   --         INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=A.SubjectId
			--INNER JOIN [sSetup].[tClassSubject] CS on CS.SubjectId = SM.Id												
			--LEFT JOIN [sSetup].[tDivisionMaster] DM on DM.Id = CAS.SourceId and CS.ClassId = Dm.classId 

			 sCommunication.tAssignment A
			INNER JOIN [sCommunication].[tAssignmentScope] CAS on A.Id = CAS.AssignmentId
            INNER JOIN sSecurity.tUser U ON U.Id=A.CreatedUserId
            INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=A.SubjectId
			LEFT JOIN [sSetup].[tDivisionMaster] DM on DM.Id = CAS.SourceId AND CAS.SourceTypeId = 2005
			LEFT JOIN sStudent.vStudentAcademic AS SA ON SA.StudentId = CAS.SourceId AND CAS.SourceTypeId = 2003 AND SA.IsActiveBatch = 1
  WHERE  
  
      ((A.Id = @rId) OR (@rId = 0))
    AND ((A.SubjectId = @rSubjectId) OR (@rSubjectId = 0))
	AND ((A.Title like @rTitle) OR (ISNULL(@rTitle,'') = ''))
	AND ((A.StartDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
	AND ((A.StartDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
	AND ((A.CreatedUserId = @rCreatedUserId) OR (@rCreatedUserId = 0))
	AND ((DM.ClassId = @rClassId) OR (@rClassId = 0))
	AND ((DM.Id = @rDivisionId) OR (@rDivisionId = 0))
	AND A.BatchId=@rBatchId
	ORDER BY A.StartDate DESC
END
GO
PRINT N'Altering Procedure [sCommunication].[pAssignmentScopeAdd]...';


GO


ALTER PROCEDURE [sCommunication].[pAssignmentScopeAdd]
			@rAssignmentId bigint
           ,@rSourceTypeId smallint
           ,@rSourceId bigint
           ,@rIsDeleted bit
           	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

	 
If(@rIsDeleted=1)
BEGIN
	Delete from sCommunication.tAssignmentScope where AssignmentId=@rAssignmentId AND SourceTypeId=@rSourceTypeId
AND SourceId=@rSourceId
	Select @rSourceId as Result
END	
ELSE
BEGIN 

		BEGIN TRY
	
	 BEGIN TRANSACTION	    
	If Exists(select AssignmentId from sCommunication.tAssignmentScope where AssignmentId=@rAssignmentId AND SourceTypeId=@rSourceTypeId
	AND SourceId=@rSourceId)
		BEGIN
			SELECT @rSourceId AS Result
			--RETURN
	  END 
	ELSE
			BEGIN
			INSERT INTO sCommunication.tAssignmentScope
			(
				AssignmentId
			   ,SourceTypeId
			   ,SourceId
			)
			VALUES
			(	
				@rAssignmentId
			   ,@rSourceTypeId
			   ,@rSourceId
			)		
			SELECT @rAssignmentId AS Result
	END
	
	COMMIT TRANSACTION
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
	
	
END 	             
	
		
END
GO
PRINT N'Altering Procedure [sCommunication].[pAssignmentScopeGet]...';


GO

ALTER PROCEDURE [sCommunication].[pAssignmentScopeGet]
	 @rAssignmentId bigint,
	 @rOrgId smallint,
	 @rUserId bigint=0
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
	
	DECLARE @lOrgGroupId int = 0
	SELECT @lOrgGroupId=OrgGroupId FROM sSetup.tOrganizationMaster WHERE Id = @rOrgId
	
	DECLARE @lAssignmentEntryBasedOn nvarchar(100)
	SELECT @lAssignmentEntryBasedOn = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 256 AND SourceTypeId = 2010 AND SourceId = @lOrgGroupId
	
	
	IF (@lAssignmentEntryBasedOn IS NULL)
	BEGIN
		
		SELECT 
			DISTINCT DM.Id  as SourceId,
			CM.Title+'-'+DM.Title as ClassDept,
			2005 as SourceTypeId,
			CASE WHEN CS.SourceId IS NULL OR CS.AssignmentId!=@rAssignmentId THEN 0 ELSE 1 END AS IsObsolete,
			CM.OrderIndex+DM.OrderIndex AS OrderIndex
		FROM 
			sSetup.tDivisionMaster DM
			INNER JOIN sSetup.tClassMaster CM ON CM.Id=DM.ClassId AND CM.OrgId=@rOrgId
			LEFT JOIN sCommunication.tAssignmentScope CS ON CS.SourceId=DM.Id AND CS.SourceTypeId=2005 AND CS.AssignmentId=@rAssignmentId
			INNER JOIN sSecurity.tUserAccess U ON U.SourceId = DM.Id AND U.SourceTypeId=2005
		WHERE DM.OrgId=@rOrgId
		AND (U.UserId = @rUserId OR @rUserId =0)
		
		UNION ALL
		
		SELECT 
			DISTINCT ODM.Id  as SourceId,
			ODM.Title as ClassDept,
			2017 as SourceTypeId,
			CASE WHEN CS.SourceId IS NULL OR CS.AssignmentId!=@rAssignmentId THEN 0 ELSE 1 END AS IsObsolete,
			0 AS OrderIndex
		FROM 
			sSetup.tDepartmentMaster ODM  
			LEFT JOIN sCommunication.tAssignmentScope CS ON CS.SourceId=ODM.Id AND CS.SourceTypeId=2017 AND CS.AssignmentId=@rAssignmentId
			INNER JOIN sSecurity.tUserAccess U ON U.SourceId = ODM.Id AND U.SourceTypeId=2017
		WHERE ODM.OrgId=@rOrgId
		AND (U.UserId = @rUserId OR @rUserId =0)
	END
	ELSE 
	BEGIN
		IF(@lAssignmentEntryBasedOn='Common')
		BEGIN
			
			SELECT 
				DISTINCT DM.Id  as SourceId,
				CM.Title+'-'+DM.Title as ClassDept,
				2005 as SourceTypeId,
				CASE WHEN CS.SourceId IS NULL OR CS.AssignmentId!=@rAssignmentId THEN 0 ELSE 1 END AS IsObsolete,
				CM.OrderIndex+DM.OrderIndex AS OrderIndex
			FROM 
				sSetup.tDivisionMaster DM
				INNER JOIN sSetup.tClassMaster CM ON CM.Id=DM.ClassId AND CM.OrgId=@rOrgId
				LEFT JOIN sCommunication.tAssignmentScope CS ON CS.SourceId=DM.Id AND CS.SourceTypeId=2005 AND CS.AssignmentId=@rAssignmentId
				INNER JOIN sSecurity.tUserAccess U ON U.SourceId = DM.Id AND (U.SourceTypeId=2005)
			WHERE DM.OrgId=@rOrgId
			AND (U.UserId = @rUserId OR @rUserId =0)
			
			UNION ALL
			
			SELECT 
				DISTINCT ODM.Id  as SourceId,
				ODM.Title as ClassDept,
				2017 as SourceTypeId,
				CASE WHEN CS.SourceId IS NULL OR CS.AssignmentId!=@rAssignmentId THEN 0 ELSE 1 END AS IsObsolete,
				0 AS OrderIndex
			FROM 
				sSetup.tDepartmentMaster ODM  
				LEFT JOIN sCommunication.tAssignmentScope CS ON CS.SourceId=ODM.Id AND CS.SourceTypeId=2017 AND CS.AssignmentId=@rAssignmentId
				INNER JOIN sSecurity.tUserAccess U ON U.SourceId = ODM.Id AND U.SourceTypeId=2017
			WHERE ODM.OrgId=@rOrgId
			AND (U.UserId = @rUserId OR @rUserId =0)
		END
		ELSE
		BEGIN
			DECLARE @lEmployeeId bigint  = 0
			SELECT @lEmployeeId=SourceId FROM sSecurity.tUser WHERE Id=@rUserId
			
			SELECT 
				DISTINCT DM.Id  as SourceId,
				CM.Title+'-'+DM.Title as ClassDept,
				2005 as SourceTypeId,
				CASE WHEN CS.SourceId IS NULL OR CS.AssignmentId!=@rAssignmentId THEN 0 ELSE 1 END AS IsObsolete,
				CM.OrderIndex+DM.OrderIndex AS OrderIndex
			FROM 
				sSetup.tDivisionMaster DM
				INNER JOIN sSetup.tClassMaster CM ON CM.Id=DM.ClassId AND CM.OrgId=@rOrgId
				LEFT JOIN sCommunication.tAssignmentScope CS ON CS.SourceId=DM.Id AND CS.SourceTypeId=2005 AND CS.AssignmentId=@rAssignmentId
				INNER JOIN sAcademic.tTeacherSubjectDivision TSD ON TSD.DivisionId = DM.Id 
			WHERE DM.OrgId=@rOrgId  AND (TSD.EmployeeId = @lEmployeeId or ISNULL(@lEmployeeId,0)=0)
			
			UNION ALL
			
			SELECT 
				DISTINCT ODM.Id  as SourceId,
				ODM.Title as ClassDept,
				2017 as SourceTypeId,
				CASE WHEN CS.SourceId IS NULL OR CS.AssignmentId!=@rAssignmentId THEN 0 ELSE 1 END AS IsObsolete,
				0 AS OrderIndex
			FROM 
				sSetup.tDepartmentMaster ODM  
				LEFT JOIN sCommunication.tAssignmentScope CS ON CS.SourceId=ODM.Id AND CS.SourceTypeId=2017 AND CS.AssignmentId=@rAssignmentId
				INNER JOIN sSecurity.tUserAccess U ON U.SourceId = ODM.Id AND U.SourceTypeId=2017
			WHERE ODM.OrgId=@rOrgId
			AND (U.UserId = @rUserId OR @rUserId =0)
		END
	END
END
GO
PRINT N'Altering Procedure [sCommunication].[pFeedbackAssignGet]...';


GO
ALTER PROCEDURE [sCommunication].[pFeedbackAssignGet]   
	  
        @rFeedbackId bigint=0,
        @rId bigint=0,
        @rAssignToSourceTypeId smallint
		
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	--if(@rAssignToSourceTypeId=2001)
	--BEGIN
	--SELECT
		 
	--	 FA.Id,
	--	 SM.ID AS SourceId,
	--	 FeedbackId,
	--	 AssignToSourceTypeId,
	--	 ForName,
		 
	--	 Isnull(A.DivisionId,0) AS DivisionId,
	--	 Firstname+' '+MiddleName+' ' +LastName AS Name,  AssignToSourceId ,
	--	 SM.Code
	--	 FROM  sCommunication.tFeedbackAssign FA
	--	 INNER JOIN sStudent.tAcademic A  ON FA.AssignToSourceId=A.ID 
	--	 INNER  JOIN sStudent.tStudentMaster SM ON SM.ID=A.StudentID
		 
	--	 WHERE  ((FeedbackId=@rFeedbackId) OR (@rFeedbackId=0))  AND AssignToSourceTypeId=2001
	--END
	
	--else if(@rAssignToSourceTypeId=95)
	--BEGIN
	--	SELECT
		 
	--	 FA.Id,
	--	 Em.ID AS SourceId,
	--	 FeedbackId,
	--	 AssignToSourceTypeId,
	--	 ForName,
	--	 Code,
	--	 --Isnull(A.DivisionId,0) AS DivisionId,
	--	 Firstname+' '+MiddleName+' ' +LastName AS Name,  AssignToSourceId 
	--	 FROM  sCommunication.tFeedbackAssign FA
	--	 INNER JOIN sHrm.tEmployeeMaster Em ON FA.AssignToSourceId=Em.ID 
		 
	--	 WHERE  ((FeedbackId=@rFeedbackId) OR (@rFeedbackId=0))  AND AssignToSourceTypeId=95
	--END
	--else
	--BEGIN
	--	SELECT
		 
	--	 FA.Id,
	--	 --Em.ID AS SourceId,
	--	 FeedbackId,
	--	 ISNULL(AssignToSourceTypeId,0) AS AssignToSourceTypeId,
	--	 ForName ,
	--	 '' AS Code,
	--	 --Isnull(A.DivisionId,0) AS DivisionId,
	--	  '' AS Name,
	--	  ISNULL(AssignToSourceId,0) AS AssignToSourceId
	--	 FROM  sCommunication.tFeedbackAssign FA
		 
	--	 WHERE  ((FeedbackId=@rFeedbackId) OR (@rFeedbackId=0)) 
	--END
WITH CTE 
AS 
  (
	Select 
		 (CASE AssignToSourceTypeId WHen  95
		 THEN
			(Select 
			 FirstName +' ' + MiddleName+' ' + LastName
			From sHrm.tEmployeeMaster Where  Id=FB.AssignToSourceId And FB.AssignToSourceTypeId=95 AND ISNULL(IsOtherUser,0) = 0 )
		 WHEN  2001
		 THEN
			(Select
			 FirstName +' ' + MiddleName+' ' + LastName
			   
			From sStudent.tAcademic A 
			INNER JOIN sStudent.tStudentMaster SM ON A.StudentId=SM.Id 
			Where A.Id=FB.AssignToSourceId ANd FB.AssignToSourceTypeId=2001)
		 Else
			ForName
		 END) AS Name,
		 
		 (CASE AssignToSourceTypeId WHen  95
		 THEN
			(Select 
			 Code
			From sHrm.tEmployeeMaster Where  Id=FB.AssignToSourceId And FB.AssignToSourceTypeId=95 AND ISNULL(IsOtherUser,0) = 0 )
		 WHEN  2001
		 THEN
			(Select
			 Code
			From sStudent.tAcademic A
			INNER JOIN  sStudent.tStudentMaster SM ON SM.Id=A.StudentID
			Where A.Id=FB.AssignToSourceId ANd FB.AssignToSourceTypeId=2001)
		 Else
			ForName
		 END) AS Code,
		 
		  (CASE AssignToSourceTypeId WHen  95
		 THEN
			(Select 
			 Id
			From sHrm.tEmployeeMaster Where  Id=FB.AssignToSourceId And FB.AssignToSourceTypeId=95 AND ISNULL(IsOtherUser,0) = 0 )
		 WHEN  2001
		 THEN
			(Select
			 A.Id
			From sStudent.tAcademic A
			INNER JOIN  sStudent.tStudentMaster SM ON SM.Id=A.StudentID
			Where A.Id=FB.AssignToSourceId ANd FB.AssignToSourceTypeId=2001)
		 Else
			ForName
		 END) AS SourceId,
		 
		 
		FB.Id,
		Isnull(AssignToSourceTypeId,0) AS AssignToSourceTypeId,
		Isnull(AssignToSourceId,0)AS AssignToSourceId,
		FeedbackId,
		ForName 
	  
		
	from sCommunication.tFeedbackAssign FB
	 
	Where  ((FeedbackId=@rFeedbackId) OR (@rFeedbackId=0))
	AND ((FB.Id=@rId) OR (@rId=0))
)
--Added by dhananjay for mantis : 42594
SELECT 
        Name,
        Code,
        SourceId,
        Id,
        ISNULL(AssignToSourceTypeId, 0) AS AssignToSourceTypeId,
        ISNULL(AssignToSourceId, 0) AS AssignToSourceId,
        FeedbackId,
        ForName
From CTE
ORDER BY	
    CASE 
        WHEN ISNUMERIC(Code) = 1 THEN TRY_CAST(Code AS DECIMAL(38, 0))
        ELSE NULL
    END,    
Code;
--Added by dhananjay for mantis : 42594
	 
END
GO
PRINT N'Altering Procedure [sFee].[pConsolidateFeeStatusDashboardGet]...';


GO
ALTER PROCEDURE [sFee].[pConsolidateFeeStatusDashboardGet]
	@rType int =0,
	@rCommonOrgGroupBatchId int=0,
	@rOrgGroupId smallint=0,
	@rReceiptBookId int =0,
	@rOrgId int  =0,
	@rFeeHeadId int =0,
	@rFeeId int =0
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
	
	--Changes for Mantis Id: 0039838
DECLARE @lConfigValue nvarchar(50)='', @lFromTime nvarchar(50)='', @lToTime nvarchar(50)='';

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

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


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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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


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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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


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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

END

ELSE IF(@rType ='FeeStatusPaidSubPartAmountMonthWise')
BEGIN 
	CREATE TABLE #tempPaidSubPartMonthWise (
	AcademicId bigint,
	OrgGroupId int,
	OrgGroupName nvarchar(100),
	CollectionGroupId bigint,
	CollectionGroup nvarchar(200),
	RecepitTitle nvarchar(100),
	ReceiptBookId bigint,
	PaidAmount DECIMAL(12,0),
	PendingAmount DECIMAL(12,0),
	MonthName nvarchar(15),
	)
   
    CREATE TABLE #tempPFSMonthWise (
       Id INT,
       Amount DECIMAL(12,0),
       FeeHeadId INT,
       CollectionGroupId INT,
       ReceiptBookId INT,
       AcademicId BIGINT  
    )
    
    INSERT INTO #tempPFSMonthWise	
    SELECT 
		FS1.Id,
		ISNULL(FS1.Amount,0)AS Amount,
		FM.FeeHeadId,
		FS1.CollectionGroupId,
		ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
		SA1.Id AS AcademicId
	FROM sFee.tFeeSetup FS1
		INNER JOIN sStudent.tAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
	    INNER JOIN sStudent.tStudentMaster SM ON SA1.StudentId = SM.Id
		INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA1.BatchId
	    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
	    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
	    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
		INNER JOIN  sSetup.tOrganizationMaster OM ON SA1.OrgId = OM.Id 
	   
		INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
	WHERE 
	   (FS1.IsOptional=0)
	   --AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
		AND (LEFT(BM.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0)) --AND BM.IsActive=1 
		AND ((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0))
		--And ISNULL(O.IsObsolete,0) = 0
		And O.IsObsolete <> 1
		-- IsInContext
		AND BM.IsInContext = 1
		--AND FS1.StartDate>=@rFromDate AND FS1.EndDate<=@rToDate   
		--AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
		--AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
	UNION ALL
				
	SELECT 
		FS1.Id,
		ISNULL(FS1.Amount,0)AS Amount,
		FM.FeeHeadId,
		FS1.CollectionGroupId,
		ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
		SA1.Id AS AcademicId
	FROM sFee.tFeeSetup FS1
		INNER JOIN sFee.tFeeOptional FO ON FO.FeeSetupId=FS1.Id 
	    INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
		INNER JOIN sStudent.tAcademic SA1 ON SA1.Id=FO.SourceId
		INNER JOIN sStudent.tStudentMaster SM ON SA1.StudentId = SM.Id
	    INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA1.BatchId
	    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
	    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
	    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
		INNER JOIN  sSetup.tOrganizationMaster OM ON SA1.OrgId = OM.Id 
	   
		AND FS1.BatchId = SA1.BatchId AND SA1.ClassId=FS1.ClassId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId 
		--AND BM.IsActive=1 
		AND ((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0))
		--And ISNULL(O.IsObsolete,0) = 0
		And O.IsObsolete <> 1
		--AND FS1.StartDate>=@rFromDate AND FS1.EndDate<=@rToDate  
	WHERE
				
	    (FS1.IsOptional=1)
		AND (LEFT(BM.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))
		-- IsInContext
		AND BM.IsInContext = 1
		--AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))


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

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

	WHERE		
		(R.SourceTypeId = 2001)
		AND (LEFT(BM.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0)) --AND BM.IsActive=1 
		AND ((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0))--AND FS.StartDate>=@rFromDate AND FS.EndDate<=@rToDate   
		AND (R.IsObsolete = 0) 
		-- IsInContext
	AND BM.IsInContext = 1  
		--AND ((SA1.OrgGroupBatchId = @rOrgGroupBatchId) OR(@rOrgGroupBatchId=0))
	GROUP BY FeeSetupId,R.SourceId,R.ReceiptDate  
   
	
	INSERT INTO #tempPaidSubPartMonthWise
		SELECT 
		ISNULL(SA.AcademicId,0) AS AcademicId,
		 O.Id AS OrgGroupId,
		 O.Title As OrgGroupName,		
		ISNULL(CGM.Id,0) AS CollectionGroupId,
		ISNULL(CGM.Code,'') AS CollectionGroup,
		ISNULL(RBM.Title,'')  AS ReceiptTitle,
		ISNULL(RBM.Id,0) As ReceiptBookId,
		SUM(ISNULL(TPR1.PaidAmount,0)) AS PaidAmount,
		SUM(ISNULL(TPFS1.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(TPR1.PaidAmount,0.00))AS PendingAmount,
		TPR1.ReceiptDate
	FROM 
		sStudent.vStudentAcademic SA
		 LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId = SA.StudentId
		INNER JOIN #tempPFSMonthWise1 TPFS1 ON TPFS1.AcademicId=SA.AcademicId
		LEFT JOIN sFee.tFeeAllocation FA
			ON FA.FeeSetupId=TPFS1.Id AND FA.SourceId=SA.AcademicId
		LEFT JOIN #tempPRMonthWise1 TPR1 ON TPR1.FeeSetupId = TPFS1.Id AND SA.AcademicId = TPR1.SourceId
	    INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId
	    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
	    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
	    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
		
		   INNER JOIN sFee.tReceiptBookMaster RBM 
			ON TPFS1.ReceiptBookId=RBM.Id
		   LEFT JOIN sFee.tCollectionGroupMaster CGM 
			ON TPFS1.CollectionGroupId=CGM.Id AND RBM.Id = CGM.ReceiptBookId --AND (CGM.OrgGroupBatchId = 0 OR(0=0))
			 INNER JOIN sFee.tFeeHeadMaster FHM 
			ON FHM.Id=TPFS1.FeeHeadId	
	WHERE
	 (LEFT(SA.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))	
	 AND ((RBM.Id = @rReceiptBookId) OR (@rReceiptBookId=0))
	AND ((CGM.Id = @rCollectionGroupId) OR (@rCollectionGroupId=0))
	-- ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
	--AND(SA.IsActiveBatch =1) 
	AND ((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0)) 
	--And ISNULL(O.IsObsolete,0) = 0
	And O.IsObsolete <> 1
	-- IsInContext
		AND BM.IsInContext = 1
		GROUP by O.Id,O.Title,SA.AcademicId,CGM.Id,CGM.Code,RBM.Title,RBM.Id,TPR1.ReceiptDate
	
	select T.OrgGroupId,T.OrgGroupName,ISNULL(SUM(T.PaidAmount),0) AS PaidAmount,COUNT(T.AcademicId) As StudentCount,
		ISNULL(T.CollectionGroupId,0) AS CollectionGroupId,T.ReceiptBookId AS ReceiptBookId,DATENAME(month,T.MonthName)MonthName,DATEPART(M, T.MonthName) AS Month from #tempPaidSubPartMonthWise T
		group by T.OrgGroupId,T.CollectionGroupId,T.ReceiptBookId,T.OrgGroupName,DATENAME(month,T.MonthName),DATEPART(M, T.MonthName)
		HAVING ISNULL(SUM(T.PaidAmount),0) > 0
		--ORDER BY DATEPART(MONTH, T.MonthName)
	END
	
	DROP TABLE #tempPaidSubPartMonthWise
	DROP TABLE #tempPFSMonthWise
	DROP TABLE #tempPRMonthWise
	DROP TABLE #tempPFSMonthWise1
	DROP TABLE #tempPRMonthWise1
	
END

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

IF(@rCollectionGroupId = 0)
	BEGIN

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

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

)

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

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

IF(@rCollectionGroupId = 0)
	BEGIN

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

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

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

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

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

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

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

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

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

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

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

)

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


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



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

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

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

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


















)


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

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

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


GO
--@rOrgId = 9911@rBatchId=991100101,@rAcademicId = 9911000000366,@rReceiptId=,@rCreatedUserId=
ALTER PROCEDURE [sFee].[pFeeProcessGeneratePaidFeeAdd]
		@rOrgId int,
		@rBatchId int,
	    @rAcademicId bigint,
		@rReceiptId bigint,
		@rCreatedUserId bigint

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	IF EXISTS (SELECT 1 FROM [sFee].[tFeeAllocationStudent] FAS WITH (NOLOCK) INNER JOIN sStudent.tAcademic A WITH (NOLOCK) ON A.Id =FAS.AcademicId 
	INNER JOIN sFee.tFeeSetup FS WITH (NOLOCK) ON FS.Id=FAS.feesetupid AND FS.AdmissionCategoryId = A.AdmissionCategoryId AND FS.ClassId = A.ClassId 
	WHERE FAS.AcademicId = @rAcademicId AND A.OrgId=@rOrgId AND A.BatchId=@rBatchId)
	BEGIN
		  SELECT ROW_NUMBER() OVER (ORDER BY FS.Id) as RowNumberFeeSetup,FS.Id AS FeeSetupId,PaidAmount AS PaidAmount,ToPayAmount AS PendingAmount 
		  INTO  #temptFeeSetup 
		  FROM [sFee].[tFeeAllocationStudent] FAS WITH (NOLOCK)
		  INNER JOIN sStudent.tAcademic A WITH (NOLOCK) ON A.Id =FAS.AcademicId 
		  INNER JOIN sFee.tFeeSetup FS WITH (NOLOCK) ON FS.Id=FAS.feesetupid AND FS.AdmissionCategoryId = A.AdmissionCategoryId 
		  AND FS.ClassId = A.ClassId
		  WHERE FAS.AcademicId = @rAcademicId AND A.OrgId=@rOrgId AND A.BatchId=@rBatchId

		  DECLARE @rowcountFeesetup BIGINT=0
		  SELECT @rowcountFeesetup = COUNT(RowNumberFeeSetup) FROM #temptFeeSetup

		  WHILE (@rowcountFeesetup!=0)
		  BEGIN	
				DECLARE @FeeSetupId BIGINT=0
				DECLARE @PaidAmount DECIMAL(12,2) = 0.00
				DECLARE @PendingAmount DECIMAL(12,2) = 0.00
				DECLARE @ReceiptPaidAmount DECIMAL(12,2) = 0.00

				SELECT @FeeSetupId=FeeSetupId,@PaidAmount=PaidAmount,@PendingAmount=PendingAmount FROM #temptFeeSetup WHERE RowNumberFeeSetup=@rowcountFeesetup

				SELECT @ReceiptPaidAmount = Amount FROM sFee.tReceiptDetail RD WITH (NOLOCK) INNER JOIN sFee.tReceipt R WITH (NOLOCK) ON R.Id = RD.ReceiptId 
				WHERE ReceiptId = @rReceiptId AND FeeSetupId = @FeeSetupId AND R.SourceId = @rAcademicId

				SET @PaidAmount = @PaidAmount + @ReceiptPaidAmount
				SET @PendingAmount = @PendingAmount - @ReceiptPaidAmount

				UPDATE [sFee].[tFeeAllocationStudent] 
				SET 
					ToPayAmount = @PendingAmount,
					PaidAmount = @PaidAmount,
					UpdatedUserId = @rCreatedUserId,
					UpdatedDateTime = sCommon.fGetDate()
				WHERE 
					AcademicId = @rAcademicId
					AND FeeSetupId = @FeeSetupId

				SET @rowcountFeesetup=@rowcountFeesetup-1
		  END

		  DROP TABLE #temptFeeSetup
	END
	ELSE 
	BEGIN
		  SELECT RowNumFeeSetup,Id AS FeeSetupId,Amount AS FeeAmount,IsOptional,IsVariable 
		  INTO  #tempFeeSetup 
		  FROM
		  (SELECT ROW_NUMBER() OVER (ORDER BY FS.id) RowNumFeeSetup,FS.Id,FS.Amount,FS.IsOptional,FS.IsVariable 
		  FROM sFee.tFeeSetup FS WITH (NOLOCK)
		  INNER JOIN sStudent.tAcademic A WITH (NOLOCK) ON FS.ClassId = A.ClassId AND FS.AdmissionCategoryId = A.AdmissionCategoryId
		  WHERE FS.BatchId=@rBatchId  AND A.Id= @rAcademicId
		  AND FS.FeeId IN (SELECT Id FROM sFee.tFeeMaster WHERE IsObsolete=0) AND 
		  FS.ReceiptBookId IN (SELECT Id FROM sFee.tReceiptBookMaster WHERE IsObsolete=0)
		  ) AS tFeeSetup
		  
		  
		  DECLARE @RowFeesetup BIGINT=0
		  SELECT @RowFeesetup = COUNT(RowNumFeeSetup) FROM #tempFeeSetup

		  WHILE (@RowFeesetup!=0)
		  BEGIN
				DECLARE @FPFeeSetupId BIGINT=0
				DECLARE @FeeAmount DECIMAL(12,2)=0.00			
				DECLARE @IsOptional Bit=0
				DECLARE @IsVariable Bit=0					
				SELECT @IsOptional=IsOptional,@IsVariable=IsVariable,@FPFeeSetupId=FeeSetupId,@FeeAmount=ISNULL(FeeAmount,0) FROM #tempFeeSetup WHERE RowNumFeeSetup=@RowFeesetup

				DECLARE @ToPayAmount DECIMAL(12,2)=0.00
				DECLARE @FPPaidAmount DECIMAL(12,2)=0.00
				DECLARE @VariableAmount DECIMAL(12,2)=0.00
				DECLARE @DiscountAmount DECIMAL(12,2)=0.00
				DECLARE @AdditionalAmount DECIMAL(12,2)=0.00
				DECLARE @NotApplicableAmount DECIMAL(12,2)=0.00
				DECLARE @Remark NVARCHAR(400)=''

				SELECT @FPPaidAmount=ISNULL(SUM(RD.Amount),0) 
				FROM sFee.tReceipt  R WITH (NOLOCK)
				INNER JOIN sFee.tReceiptDetail RD WITH (NOLOCK) ON RD.ReceiptId = R.Id AND R.IsObsolete = 0
				WHERE R.SourceId=@rAcademicId AND RD.FeeSetupId=@FPFeeSetupId 
				GROUP BY R.sourceid,RD.feesetupid

				SELECT @VariableAmount=ISNULL(FA.[VariableAmount],0),@DiscountAmount=ISNULL(FA.[DiscountAmount],0)
					,@AdditionalAmount=ISNULL(FA.[AdditionalAmount],0),@NotApplicableAmount=ISNULL(FA.[NotApplicableAmount],0),@Remark=ISNULL(FA.Remark,'')
					FROM [sFee].[tFeeAllocation] AS FA WITH (NOLOCK)					  			
					WHERE FA.sourceid=@rAcademicId AND FA.feesetupid=@FPFeeSetupId

				IF(@IsOptional=1 AND @IsVariable=1)
				BEGIN
					IF(@VariableAmount>0)BEGIN SET @FeeAmount=0 END
				END
			
				IF(@IsOptional=1 AND @IsVariable=0)
				BEGIN
					IF(@VariableAmount>0)BEGIN SET @FeeAmount=0 END
				END

				IF(@IsOptional=0 AND @IsVariable=1)
				BEGIN
					IF(@VariableAmount>0)BEGIN SET @FeeAmount=0 END
				END

				IF(@IsOptional=0 AND @IsVariable=0)
				BEGIN
					IF(@VariableAmount>0)BEGIN SET @VariableAmount=0 END
				END

				SET @ToPayAmount=(@FeeAmount+@VariableAmount+@AdditionalAmount)-(@NotApplicableAmount+@DiscountAmount+@FPPaidAmount)

				IF(@IsOptional=0)
				BEGIN
					IF NOT EXISTS (SELECT 1 FROM [sFee].[tFeeAllocationStudent] FAS WITH (NOLOCK) WHERE FAS.AcademicId=@rAcademicId AND FAS.FeeSetupId=@FPFeeSetupId)
					BEGIN
						 
						INSERT INTO [sFee].[tFeeAllocationStudent]
								([AcademicId],[FeeSetupId],[FeeAmount],[VariableAmount],[DiscountAmount],[AdditionalAmount],[NotApplicableAmount],[ToPayAmount]
								,[PaidAmount],[Remark],[CreatedUserId],[CreatedDateTime],[UpdatedUserId],[UpdatedDateTime])
						VALUES
							(@rAcademicId,@FPFeeSetupId,@FeeAmount,@VariableAmount,@DiscountAmount,@AdditionalAmount,@NotApplicableAmount,@ToPayAmount
							,@FPPaidAmount,@Remark,@rCreatedUserId,sCommon.fGetDate(),@rCreatedUserId,sCommon.fGetDate())				
				
					END
				END

				IF EXISTS (SELECT 1 FROM [sFee].[tFeeOptional] WITH (NOLOCK) WHERE FeeSetupId=@feesetupid AND SourceId=@rAcademicId AND BatchId=@rBatchId AND (@IsOptional=1))
				BEGIN
					IF NOT EXISTS (SELECT 1 FROM [sFee].[tFeeAllocationStudent] FAS WITH (NOLOCK) WHERE FAS.academicid=@rAcademicId AND FAS.feesetupid=@FPFeeSetupId)
					BEGIN
						
						INSERT INTO [sFee].[tFeeAllocationStudent]
								([AcademicId],[FeeSetupId],[FeeAmount],[VariableAmount],[DiscountAmount],[AdditionalAmount],[NotApplicableAmount],[ToPayAmount]
								,[PaidAmount],[Remark],[CreatedUserId],[CreatedDateTime],[UpdatedUserId],[UpdatedDateTime])
						VALUES
							(@rAcademicId,@FPFeeSetupId,@FeeAmount,@VariableAmount,@DiscountAmount,@AdditionalAmount,@NotApplicableAmount,@ToPayAmount
							,@FPPaidAmount,@Remark,@rCreatedUserId,sCommon.fGetDate(),@rCreatedUserId,sCommon.fGetDate())
					END 
				END 
			 SET @RowFeesetup=@RowFeesetup-1
		  END

		  DROP TABLE #tempFeeSetup
	END

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


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

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

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

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

				DECLARE @lCount1 int = 0

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

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

						-- For Fee Process Added By Foram on 2025-01-31
						IF EXISTS(SELECT 1 FROM sFee.tFeeAllocationStudent WHERE AcademicId = @lAcademicId AND FeeSetupId = @lFeeSetupId)
						BEGIN
							UPDATE FAS
							SET FAS.DiscountAmount = ISNULL(FA.DiscountAmount,0), 
							FAS.ToPayAmount = (ISNULL(FAS.FeeAmount,0) + ISNULL(FAS.VariableAmount,0) + ISNULL(FAS.AdditionalAmount ,0)
												- ISNULL(FA.DiscountAmount,0) - ISNULL(FAS.NotApplicableAmount,0) - ISNULL(FAS.PaidAmount,0)),
							FAS.UpdatedUserId = @rCreatedUserId, 
							FAS.UpdatedDateTime = sCommon.fGetDate()
							FROM sFee.tFeeAllocationStudent FAS
							INNER JOIN sFee.tFeeAllocation FA ON FAS.AcademicId = FA.SourceId AND FA.SourceTypeId = 2001
							WHERE FAS.AcademicId = @lAcademicId AND FAS.FeeSetupId = @lFeeSetupId
						END
						ELSE
						BEGIN
							DECLARE @lFeeAmount decimal(12,2) = 0
							SELECT @lFeeAmount = ISNULL(Amount, 0) FROM sFee.tFeeSetup WHERE Id = @lFeeSetupId

							INSERT INTO sFee.tFeeAllocationStudent
							(
								AcademicId
								,FeeSetupId
								,FeeAmount
								,VariableAmount
								,DiscountAmount
								,AdditionalAmount
								,NotApplicableAmount
								,ToPayAmount
								,PaidAmount
								,Remark
								,CreatedUserId
								,CreatedDateTime
								,UpdatedUserId
								,UpdatedDateTime
							)
							SELECT 
								FA.SourceId
								,FA.FeeSetupId
								,@lFeeAmount
								,ISNULL(VariableAmount,0)
								,ISNULL(DiscountAmount,0)
								,ISNULL(AdditionalAmount,0)
								,ISNULL(NotApplicableAmount,0)
								,(@lFeeAmount + ISNULL(VariableAmount,0) + ISNULL(AdditionalAmount,0)  - ISNULL(DiscountAmount,0)  - ISNULL(NotApplicableAmount,0) )
								,0
								,Remark
								,CreatedUserId
								,CreatedDateTime
								,UpdatedUserId
								,UpdatedDateTime
							FROM sFee.tFeeAllocation FA
							WHERE FA.SourceTypeId = 2001 AND FA.SourceId = @lAcademicId AND FA.FeeSetupId = @lFeeSetupId
						END
						-- For Fee Process Added By Foram on 2025-01-31

					END
				END
		END
		 
		SET @lCount = @lCount - 1
	END
	 
	DROP TABLE #TempOldExemptionFeeImport
	SELECT 1 AS Result
	COMMIT TRANSACTION
END TRY

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


GO
ALTER PROCEDURE [sFee].[pOldFeeDetailsImportAdd] 
	@rOldOrgGroupBatchId INT
	,@rNewOrgGroupBatchId INT
	,@rOldBatchId INT
	,@rNewBatchId INT
	,@rOrgId INT
	,@rCreatedUserId BIGINT
	,@rOldClassId BIGINT
	,@rNewClassId BIGINT

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
		CREATE TABLE #TempOldFeeImport (
			[AutoId] INT identity
			,[StudentId] BIGINT NULL
			,[AcademicId] BIGINT NULL
			,[Amount] DECIMAL(12, 2) NULL
			,[DiscountAmount] DECIMAL(12, 2) NULL
			,[AdditionalAmount] DECIMAL(12, 2) NULL
			,[NotApplicableAmount] DECIMAL(12, 2) NULL
			,[AdmissionCategoryId] BIGINT
			,[FeeSetupId] BIGINT
			)

		INSERT INTO #TempOldFeeImport
		SELECT SA.StudentId
			,SA.AcademicId
			,
			--SUM(ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00)) AS PendingAmount
			ISNULL(FA.VariableAmount, 0.00) AS Amount
			,ISNULL(FA.DiscountAmount, 0.00) AS DiscountAmount
			,ISNULL(FA.AdditionalAmount, 0.00) AS AdditionalAmount
			,ISNULL(FA.NotApplicableAmount, 0.00) AS NotApplicableAmount
			,SA.AdmissionCategoryId
			,FA.FeeSetupId
		FROM sStudent.vStudentAcademic SA
		INNER JOIN sSetup.tBatchMaster BM ON SA.BatchId = BM.Id
			AND BM.OrgGroupBatchId = @rOldOrgGroupBatchId
		LEFT JOIN sFee.tFeeAllocation FA ON FA.SourceId = SA.AcademicId
		WHERE SA.OrgGroupBatchId = @rOldOrgGroupBatchId
			AND (
				(SA.BatchId = @rOldBatchId)
				OR (@rOldBatchId = 0)
				)
			AND (
				(SA.OrgId = @rOrgId)
				OR (@rOrgId = 0)
				)
			AND (
				(SA.ClassId = @rOldClassId)
				OR (@rOldClassId = 0)
				)
			AND SA.StatusId = 1

		--Select * from #TempOldFeeImport
		BEGIN TRANSACTION

		DECLARE @lCount INT

		SELECT @lCount = COUNT(AutoId)
		FROM #TempOldFeeImport

		WHILE (@lCount > 0)
		BEGIN
			DECLARE @lAcademicId BIGINT = NULL
			DECLARE @lOldAcademicId BIGINT = NULL
			DECLARE @lStudentId BIGINT = NULL
			DECLARE @lClassId INT = NULL
			DECLARE @lFeeSetupId INT = NULL
			--DECLARE @lPendingAmount decimal(12,2)
			DECLARE @lDiscountAmount DECIMAL(12, 2)
			DECLARE @lAdditionalAmount DECIMAL(12, 2)
			DECLARE @lNotApplicableAmount DECIMAL(12, 2)
			DECLARE @rNewAdmissionCategoryId BIGINT
			DECLARE @rOldAdmissionCategoryId BIGINT
			DECLARE @OldFeeName NVARCHAR(200)
			DECLARE @newFeeName NVARCHAR(200)
			DECLARE @lOldAmount DECIMAL(12, 2)
			DECLARE @lNewAmount DECIMAL(12, 2)
			DECLARE @FeeName NVARCHAR(500)
			DECLARE @lOldFeeSetupId BIGINT

			SELECT @lStudentId = StudentId
				,@lOldAcademicId = AcademicId
				,@lOldAmount = Amount
				,@lDiscountAmount = DiscountAmount
				,@lAdditionalAmount = AdditionalAmount
				,@lNotApplicableAmount = NotApplicableAmount
				,@rOldAdmissionCategoryId = AdmissionCategoryId
				,@lOldFeeSetupId = FeeSetupId
			FROM #TempOldFeeImport
			WHERE AutoId = @lCount

			SELECT @lAcademicId = AcademicId
				,@lClassId = ClassId
				,@rNewAdmissionCategoryId = AdmissionCategoryId
			FROM sStudent.vStudentAcademic SA
			WHERE StudentId = @lStudentId
				AND BatchId = @rNewBatchId

			SELECT @OldFeeName = FM.Code
			FROM sFee.tFeeSetup FS1
			INNER JOIN sFee.tFeeMaster FM ON FM.Id = FS1.FeeId
			INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.ClassId = FS1.ClassId
				AND FS1.BatchId = SA1.BatchId
			WHERE FS1.ClassId = @rOldClassId
				AND FS1.BatchId = @rOldBatchId
				AND FS1.AdmissionCategoryId = @rOldAdmissionCategoryId
				AND FS1.Id = @lOldFeeSetupId

			SELECT @lFeeSetupId = FS1.Id
			FROM sFee.tFeeSetup FS1
			INNER JOIN sFee.tFeeMaster FM ON FM.Id = FS1.FeeId
			INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.ClassId = FS1.ClassId
				AND FS1.BatchId = SA1.BatchId
			WHERE FS1.ClassId = @lClassId
				AND FS1.BatchId = @rNewBatchId
				AND FS1.AdmissionCategoryId = @rNewAdmissionCategoryId
				AND FM.Code = @OldFeeName

			SELECT @lNewAmount = FS1.Amount
			FROM sFee.tFeeSetup FS1
			INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.ClassId = FS1.ClassId
				AND FS1.BatchId = SA1.BatchId
			WHERE FS1.ClassId = @lClassId
				AND FS1.BatchId = @rNewBatchId
				AND FS1.AdmissionCategoryId = @rNewAdmissionCategoryId
				AND FS1.Id = @lFeeSetupId

			--Select @OldFeeName=FM.Code FROM sFee.tFeeSetup FS1 INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
			--WHERE  ClassId = @rOldClassId  AND BatchId=@rOldBatchId AND AdmissionCategoryId = @rOldAdmissionCategoryId AND FS1.Id=@lOldFeeSetupId
			SELECT @NewFeeName = FM.Code
			FROM sFee.tFeeSetup FS1
			INNER JOIN sFee.tFeeMaster FM ON FM.Id = FS1.FeeId
			INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.ClassId = FS1.ClassId
				AND FS1.BatchId = SA1.BatchId
			WHERE FS1.ClassId = @lClassId
				AND FS1.BatchId = @rNewBatchId
				AND FS1.AdmissionCategoryId = @rNewAdmissionCategoryId
				AND FS1.Id = @lFeeSetupId

			--Select @lOldAcademicId,@lAcademicId,@lFeeSetupId,@OldFeeName,@NewFeeName,@lNewAmount,@lDiscountAmount,@FeeName,@OldFeeName
			--Select @OldFeeName,@NewFeeName
			--SELECT @lFeeSetupId,@lAcademicId,@lStudentId
			IF NOT EXISTS (SELECT 1 FROM sFee.tFeeAllocation WHERE SourceId = @lAcademicId AND FeeSetupId = @lFeeSetupId)
			BEGIN
				IF @lAcademicId IS NOT NULL
					AND @lFeeSetupId IS NOT NULL
					AND @lClassId IS NOT NULL
					AND @OldFeeName IS NOT NULL
					AND @NewFeeName IS NOT NULL
					AND (@OldFeeName = @NewFeeName)
					AND (ISNULL(@lNewAmount, 0) >= ISNULL(@lDiscountAmount, 0))
				BEGIN
					INSERT INTO sFee.tFeeAllocation (
						SourceTypeId
						,SourceId
						,FeeSetupId
						,VariableAmount
						,DiscountAmount
						,AdditionalAmount
						,NotApplicableAmount
						,Remark
						,ReferenceTypeId
						,ReferenceSourceId
						,CreatedUserId
						,CreatedDateTime
						,UpdatedUserId
						,UpdatedDateTime
						)
					VALUES (
						2001
						,@lAcademicId
						,@lFeeSetupId
						,0
						,@lDiscountAmount
						,@lAdditionalAmount
						,@lNotApplicableAmount
						,'Old Year Discount,Additional,NotApplicable Fee'
						,NULL
						,NULL
						,@rCreatedUserId
						,sCommon.fGetDate()
						,NULL
						,NULL
						)

					-- For Fee Process Added By Foram on 2025-01-31
					IF EXISTS(SELECT 1 FROM sFee.tFeeAllocationStudent WHERE AcademicId = @lAcademicId AND FeeSetupId = @lFeeSetupId)
					BEGIN
						UPDATE FAS
						SET FAS.DiscountAmount = FA.DiscountAmount,
							FAS.AdditionalAmount = FA.AdditionalAmount,
							FAS.NotApplicableAmount = FA.NotApplicableAmount, 
							FAS.ToPayAmount = (FAS.FeeAmount + FAS.VariableAmount + FA.AdditionalAmount - FA.DiscountAmount - FA.NotApplicableAmount - FAS.PaidAmount),
							FAS.UpdatedUserId = @rCreatedUserId,
							FAS.UpdatedDateTime = sCommon.fGetDate()
						FROM sFee.tFeeAllocationStudent FAS
						INNER JOIN sFee.tFeeAllocation FA ON FAS.AcademicId = FA.SourceId AND FA.SourceTypeId = 2001
						WHERE FAS.AcademicId = @lAcademicId AND FAS.FeeSetupId = @lFeeSetupId
					END
					ELSE
					BEGIN
						DECLARE @lFeeAmount1 decimal(12,2) = 0
						SELECT @lFeeAmount1 = ISNULL(Amount, 0) FROM sFee.tFeeSetup WHERE Id = @lFeeSetupId

						INSERT INTO sFee.tFeeAllocationStudent
						(
							AcademicId
							,FeeSetupId
							,FeeAmount
							,VariableAmount
							,DiscountAmount
							,AdditionalAmount
							,NotApplicableAmount
							,ToPayAmount
							,PaidAmount
							,Remark
							,CreatedUserId
							,CreatedDateTime
							,UpdatedUserId
							,UpdatedDateTime
						)
						SELECT 
							FA.SourceId
							,FA.FeeSetupId
							,@lFeeAmount1
							,VariableAmount
							,DiscountAmount
							,AdditionalAmount
							,NotApplicableAmount
							,(@lFeeAmount1 + VariableAmount + AdditionalAmount - DiscountAmount - NotApplicableAmount)
							,0
							,Remark
							,CreatedUserId
							,CreatedDateTime
							,UpdatedUserId
							,UpdatedDateTime
						FROM sFee.tFeeAllocation FA
						WHERE FA.SourceTypeId = 2001 AND FA.SourceId = @lAcademicId AND FA.FeeSetupId = @lFeeSetupId
					END
					-- For Fee Process Added By Foram on 2025-01-31
				END
				ELSE
				BEGIN
					SELECT - 102 AS Result
				END
			END
			ELSE
			BEGIN
				IF @lAcademicId IS NOT NULL
					AND @lFeeSetupId IS NOT NULL
					AND @lClassId IS NOT NULL
					AND @OldFeeName IS NOT NULL
					AND @NewFeeName IS NOT NULL
					AND (@OldFeeName = @NewFeeName)
					AND (ISNULL(@lNewAmount, 0) >= ISNULL(@lDiscountAmount, 0))
				BEGIN
					-- Update Fee Allocation
					UPDATE sFee.tFeeAllocation
					SET SourceTypeId = 2001
						,SourceId = @lAcademicId
						,FeeSetupId = @lFeeSetupId
						,
						--VariableAmount = 0,
						DiscountAmount = @lDiscountAmount
						,AdditionalAmount = @lAdditionalAmount
						,NotApplicableAmount = @lNotApplicableAmount
						,Remark = 'Old Year Discount,Additional,NotApplicable Fee'
						,ReferenceTypeId = NULL
						,ReferenceSourceId = NULL
						,CreatedUserId = @rCreatedUserId
						,CreatedDateTime = sCommon.fGetDate()
						,UpdatedUserId = NULL
						,UpdatedDateTime = NULL
					WHERE SourceId = @lAcademicId
						AND SourceTypeId = 2001
						AND FeeSetupId = @lFeeSetupId


					-- For Fee Process Added By Foram on 2025-01-31
					IF EXISTS(SELECT 1 FROM sFee.tFeeAllocationStudent WHERE AcademicId = @lAcademicId AND FeeSetupId = @lFeeSetupId)
					BEGIN
						UPDATE FAS
						SET FAS.DiscountAmount = ISNULL(FA.DiscountAmount,0),
							FAS.AdditionalAmount = ISNULL(FA.AdditionalAmount,0),
							FAS.NotApplicableAmount = ISNULL(FA.NotApplicableAmount,0), 
							FAS.ToPayAmount = (ISNULL(FAS.FeeAmount,0) + ISNULL(FAS.VariableAmount,0) + ISNULL(FA.AdditionalAmount,0)
											- ISNULL(FA.DiscountAmount,0) - ISNULL(FA.NotApplicableAmount,0) - ISNULL(FAS.PaidAmount,0)),
							FAS.UpdatedUserId = @rCreatedUserId,
							FAS.UpdatedDateTime = sCommon.fGetDate()
						FROM sFee.tFeeAllocationStudent FAS
						INNER JOIN sFee.tFeeAllocation FA ON FAS.AcademicId = FA.SourceId AND FA.SourceTypeId = 2001
						WHERE FAS.AcademicId = @lAcademicId AND FAS.FeeSetupId = @lFeeSetupId
					END
					ELSE
					BEGIN
						DECLARE @lFeeAmount2 decimal(12,2) = 0
						SELECT @lFeeAmount2 = ISNULL(Amount, 0) FROM sFee.tFeeSetup WHERE Id = @lFeeSetupId

						INSERT INTO sFee.tFeeAllocationStudent
						(
							AcademicId
							,FeeSetupId
							,FeeAmount
							,VariableAmount
							,DiscountAmount
							,AdditionalAmount
							,NotApplicableAmount
							,ToPayAmount
							,PaidAmount
							,Remark
							,CreatedUserId
							,CreatedDateTime
							,UpdatedUserId
							,UpdatedDateTime
						)
						SELECT 
							FA.SourceId
							,FA.FeeSetupId
							,ISNULL(@lFeeAmount2,0)
							,ISNULL(VariableAmount,0)
							,ISNULL(DiscountAmount,0)
							,ISNULL(AdditionalAmount,0)
							,ISNULL(NotApplicableAmount,0)
							,(ISNULL(@lFeeAmount2,0) + ISNULL(VariableAmount,0)  + ISNULL(AdditionalAmount,0) - ISNULL(DiscountAmount,0) - ISNULL(NotApplicableAmount,0))
							,0
							,Remark
							,CreatedUserId
							,CreatedDateTime
							,UpdatedUserId
							,UpdatedDateTime
						FROM sFee.tFeeAllocation FA
						WHERE FA.SourceTypeId = 2001 AND FA.SourceId = @lAcademicId AND FA.FeeSetupId = @lFeeSetupId
					END
					-- For Fee Process Added By Foram on 2025-01-31

				END
				ELSE
				BEGIN
					SELECT - 102 AS Result
				END
			END

			SET @lCount = @lCount - 1
		END

		DROP TABLE #TempOldFeeImport

		SELECT 1 AS Result

		COMMIT TRANSACTION
	END TRY

	BEGIN CATCH
		ROLLBACK TRANSACTION

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


GO
ALTER PROCEDURE [sFee].[pOldFeewiseImportAdd]
	
	@rOldOrgGroupBatchId int,
	@rNewOrgGroupBatchId int,
	@rOldBatchId int,
	@rNewBatchId int,
	@rOldAdmissionCategoryId int,
	@rNewAdmissionCategoryId int,
	@rOldReceiptBookId int,
	@rNewReceiptBookId int,
	@rOldFeeIds nvarchar(max),
	@rNewFeeId int,
	@rOrgId int,
	@rCreatedUserId bigint,
	@rIdNos nvarchar(max)=''
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
BEGIN TRY 

	DECLARE @lCount int
	-- Old Fee Import Temp Table
	CREATE TABLE #TempOldFeeImport
	(
		[AutoId] int identity,
		[StudentId] bigint NULL ,
		[AcademicId] bigint NULL,
		[PendingAmount] decimal(12,2) NULL
	)
	-- End Old Fee Import Temp Table
	
	
	INSERT INTO #TempOldFeeImport 
	SELECT 
		SA.StudentId,
		SA.AcademicId,
		SUM(ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00)) AS PendingAmount
	FROM
		sStudent.vStudentAcademic SA
		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.AdmissionCategoryId=@rOldAdmissionCategoryId) OR (@rOldAdmissionCategoryId=0))
			INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
			INNER JOIN sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOldOrgGroupBatchId
			WHERE 
			    SA1.OrgGroupBatchId = @rOldOrgGroupBatchId
			    AND ((FS1.AdmissionCategoryId=@rOldAdmissionCategoryId) OR (@rOldAdmissionCategoryId=0))
			    AND ((FS1.ReceiptBookId=@rOldReceiptBookId) OR (@rOldReceiptBookId=0))
				AND (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 int) FROM  sCommon.fnsplit(@rOldFeeIds,','))
				AND (SA1.Code IN (SELECT item from sCommon.fnSplit(@rIdNos, ',')) OR ISNULL(@rIdNos,'')='')
				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.AdmissionCategoryId=@rOldAdmissionCategoryId) OR (@rOldAdmissionCategoryId=0))
		INNER JOIN sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOldOrgGroupBatchId
		WHERE
		        SA1.OrgGroupBatchId = @rOldOrgGroupBatchId
		        AND ((FS1.AdmissionCategoryId=@rOldAdmissionCategoryId) OR (@rOldAdmissionCategoryId=0))
		        AND ((FS1.ReceiptBookId=@rOldReceiptBookId) OR (@rOldReceiptBookId=0))
				AND (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 int) FROM  sCommon.fnsplit(@rOldFeeIds,','))
				AND (SA1.Code IN (SELECT item from sCommon.fnSplit(@rIdNos, ',')) OR ISNULL(@rIdNos,'')='')
				
		) FS ON FS.AcademicId=SA.AcademicId
		LEFT JOIN sFee.tFeeAllocation FA
			ON FA.FeeSetupId=FS.Id AND FA.SourceId=SA.AcademicId
		LEFT JOIN
		(
		    SELECT 
					ISNULL(SUM(RD.Amount),0) AS PaidAmount,RD.FeeSetupId ,R.SourceId
		    FROM
				sFee.tReceipt R 
				INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id 
				INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id
				INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id
				INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=R.SourceId				
				
			WHERE		
				(R.SourceTypeId = 2001)
				AND ((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND (R.IsObsolete = 0) 
				AND ((SA1.OrgGroupBatchId = @rOldOrgGroupBatchId))
				AND (R.OrgGroupBatchId = @rOldOrgGroupBatchId)
				AND ((R.BatchId=@rOldBatchId) OR (@rOldBatchId=0))
				AND FM.Id IN (SELECT cast(item as int) FROM  sCommon.fnsplit(@rOldFeeIds,','))
				AND (SA1.Code IN (SELECT item from sCommon.fnSplit(@rIdNos, ',')) OR ISNULL(@rIdNos,'')='')
				GROUP BY FeeSetupId,R.SourceId
		) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
				 
	WHERE	
			SA.OrgGroupBatchId = @rOldOrgGroupBatchId
			AND SA.OrgId = @rOrgId 
			AND SA.BatchId=@rOldBatchId
			AND (ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00) -ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00) > 0)
			AND (SA.Code IN (SELECT item from sCommon.fnSplit(@rIdNos, ',')) OR ISNULL(@rIdNos,'')='')
			GROUP BY SA.StudentId,SA.AcademicId
	
	SELECT @lCount = COUNT(AutoId) FROM #TempOldFeeImport
	
	IF EXISTS 
	(
		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.AdmissionCategoryId = @rNewAdmissionCategoryId AND FS.FeeId = @rNewFeeId 
		AND FS.ReceiptBookId = @rNewReceiptBookId
		AND (SA.Code IN (SELECT item from sCommon.fnSplit(@rIdNos, ',')) OR ISNULL(@rIdNos,'')='')
	)
	BEGIN
		SELECT -101 AS Result
		RETURN
	END
	
	BEGIN TRANSACTION
	
	---- Delete Fee Optional
	DELETE FO FROM sFee.tFeeOptional FO 
	INNER JOIN sStudent.tAcademic SA ON FO.SourceId = SA.Id AND SA.BatchId = @rNewBatchId
	INNER JOIN sFee.tFeeSetup FS ON FO.FeeSetupId = FS.Id AND SA.ClassId = FS.ClassId
	INNER JOIN sStudent.vStudentAcademic SA1 ON SA.Id = SA1.AcademicId AND SA1.BatchId = @rNewBatchId
	AND FS.BatchId = @rNewBatchId 
	AND FS.AdmissionCategoryId = @rNewAdmissionCategoryId 
	AND FS.FeeId = @rNewFeeId  
	AND FS.ReceiptBookId = @rNewReceiptBookId
	AND (SA1.Code IN (SELECT item from sCommon.fnSplit(@rIdNos, ',')) OR ISNULL(@rIdNos,'')='')
	INNER JOIN #TempOldFeeImport TOFI ON TOFI.StudentId = SA.StudentId 

	-- Delete Fee Allocation
	DELETE FA FROM sFee.tFeeAllocation FA 
	INNER JOIN sStudent.tAcademic SA ON FA.SourceId = SA.Id AND SA.BatchId = @rNewBatchId
	INNER JOIN sFee.tFeeSetup FS ON FA.FeeSetupId = FS.Id AND SA.ClassId = FS.ClassId
	INNER JOIN sStudent.vStudentAcademic SA1 ON SA.Id = SA1.AcademicId AND SA1.BatchId = @rNewBatchId
	AND FS.BatchId = @rNewBatchId 
	AND FS.AdmissionCategoryId = @rNewAdmissionCategoryId 
	AND FS.FeeId = @rNewFeeId AND FA.FeeSetupId = FS.Id
	AND FS.ReceiptBookId = @rNewReceiptBookId
	AND (SA1.Code IN (SELECT item from sCommon.fnSplit(@rIdNos, ',')) OR ISNULL(@rIdNos,'')='')
	INNER JOIN #TempOldFeeImport TOFI ON TOFI.StudentId = SA.StudentId 

	WHILE (@lCount > 0)
	BEGIN
		DECLARE @lAcademicId bigint = NULL
		DECLARE @lStudentId bigint = NULL
		DECLARE @lClassId int = NULL
		DECLARE @lFeeSetupId int = NULL
		DECLARE @lPendingAmount decimal(12,2)
		
		SELECT @lStudentId = StudentId,@lPendingAmount=PendingAmount FROM #TempOldFeeImport WHERE AutoId = @lCount
		SELECT @lAcademicId = Id, @lClassId=ClassId FROM  sStudent.tAcademic SA WHERE StudentId = @lStudentId AND BatchId = @rNewBatchId
		SELECT @lFeeSetupId = Id FROM sFee.tFeeSetup WHERE  ClassId = @lClassId AND AdmissionCategoryId = @rNewAdmissionCategoryId AND BatchId=@rNewBatchId AND FeeId = @rNewFeeId AND ReceiptBookId = @rNewReceiptBookId
		
		IF @lAcademicId IS NOT NULL AND @lFeeSetupId IS NOT NULL AND @lClassId IS NOT NULL
		BEGIN
			-- Insert Fee Optional
			INSERT INTO sFee.tFeeOptional
			   (
			    FeeSetupId,
			    SourceTypeId,
			    SourceId,
			    BatchId
			   )
				VALUES
			   (
				@lFeeSetupId,
				2001,
				@lAcademicId,
				@rNewBatchId
			   )
			 
				-- 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,
				@lPendingAmount,
				0,
				NULL,
				NULL,
				'Old Year Pending Fee',
				NULL,
				NULL,
				@rCreatedUserId,
				sCommon.fGetDate(),
				NULL,
				NULL
			   )

			   -- For Fee Process Added By Foram on 2025-01-31
				IF EXISTS(SELECT 1 FROM sFee.tFeeAllocationStudent WHERE AcademicId = @lAcademicId AND FeeSetupId = @lFeeSetupId)
				BEGIN
					UPDATE FAS
					SET FAS.VariableAmount = ISNULL(FA.VariableAmount,0), 
					FAS.ToPayAmount = (ISNULL(FAS.FeeAmount,0) + ISNULL(FA.VariableAmount,0) + ISNULL(FAS.AdditionalAmount,0) - ISNULL(FAS.DiscountAmount,0) - ISNULL(FAS.NotApplicableAmount,0) - ISNULL(FAS.PaidAmount,0)),
					FAS.UpdatedUserId = @rCreatedUserId,
					FAS.UpdatedDateTime = sCommon.fGetDate()
					FROM sFee.tFeeAllocationStudent FAS
					INNER JOIN sFee.tFeeAllocation FA ON FAS.AcademicId = FA.SourceId AND FA.SourceTypeId = 2001
					WHERE FAS.AcademicId = @lAcademicId AND FAS.FeeSetupId = @lFeeSetupId
				END
				ELSE
				BEGIN
					DECLARE @lFeeAmount1 decimal(12,2) = 0
					SELECT @lFeeAmount1 = ISNULL(Amount, 0) FROM sFee.tFeeSetup WHERE Id = @lFeeSetupId

					INSERT INTO sFee.tFeeAllocationStudent
					(
						AcademicId
						,FeeSetupId
						,FeeAmount
						,VariableAmount
						,DiscountAmount
						,AdditionalAmount
						,NotApplicableAmount
						,ToPayAmount
						,PaidAmount
						,Remark
						,CreatedUserId
						,CreatedDateTime
						,UpdatedUserId
						,UpdatedDateTime
					)
					SELECT 
						FA.SourceId
						,FA.FeeSetupId
						,ISNULL(@lFeeAmount1,0)
						,ISNULL(VariableAmount,0)
						,ISNULL(DiscountAmount,0)
						,ISNULL(AdditionalAmount,0)
						,ISNULL(NotApplicableAmount,0)
						,(ISNULL(@lFeeAmount1,0) + ISNULL(VariableAmount,0) + ISNULL(AdditionalAmount,0) - ISNULL(DiscountAmount,0) - ISNULL(NotApplicableAmount,0))
						,0
						,Remark
						,CreatedUserId
						,CreatedDateTime
						,UpdatedUserId
						,UpdatedDateTime
					FROM sFee.tFeeAllocation FA
					WHERE FA.SourceTypeId = 2001 AND FA.SourceId = @lAcademicId AND FA.FeeSetupId = @lFeeSetupId
				END
				-- For Fee Process Added By Foram on 2025-01-31
		END
		 
		SET @lCount = @lCount -1
	END
	 
	DROP TABLE #TempOldFeeImport
	SELECT 1 AS Result
	COMMIT TRANSACTION
END TRY

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


GO
ALTER PROCEDURE [sFee].[pReceiptAddValidate] 
	@rAcademicId BIGINT
	,@rFeeSetupIds NVARCHAR(max) = ''
	,@rReceiptDetailXml [nvarchar] (max)
	,@rPayTypeId TINYINT = 0
	,@rPaymentTransactionId BIGINT = 0
	,@rReceiptBookId INT = 0
	,@rChequeNo nvarchar(40) = '' -- Added for mantis 0035484 by Foram
	,@rIsCreated INT OUTPUT

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	DECLARE @loDoc INT

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

	EXEC sp_xml_preparedocument @loDoc OUTPUT,@rReceiptDetailXml

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

	INSERT INTO #temptable (
		FeeId
		,Id
		,Amount
		,ReceiptBookId
		,AcademicId
		)
	SELECT FS1.FeeId
		,FS1.Id
		,
		--ISNULL(FS1.IsOptional,0)AS IsOptional,
		--ISNULL(FS1.IsVariable,0)AS IsVariable,
		ISNULL(FS1.Amount, 0) AS Amount
		,
		--ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
		--ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
		--FS1.BatchId,
		ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
		SA1.Id AS AcademicId
	--FM.Title AS FeeName			 
	FROM sFee.tFeeSetup FS1 WITH (NOLOCK)
	INNER JOIN sStudent.tAcademic SA1 WITH (NOLOCK) ON SA1.ClassId = FS1.ClassId
		AND FS1.BatchId = SA1.BatchId
	INNER JOIN sStudent.tStudentMaster SM WITH (NOLOCK) ON SA1.StudentId = SM.Id
		AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
	INNER JOIN sFee.tFeeMaster FM WITH (NOLOCK) ON FM.Id = FS1.FeeId
	INNER JOIN sFee.tFeeHeadMaster FHM WITH (NOLOCK) 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 WITH (NOLOCK)
	INNER JOIN sFee.tFeeOptional FO WITH (NOLOCK) ON FO.FeeSetupId = FS1.Id
	INNER JOIN sFee.tFeeMaster FM WITH (NOLOCK) ON FM.Id = FS1.FeeId
	INNER JOIN sFee.tFeeHeadMaster FHM WITH (NOLOCK) ON FM.FeeHeadId = FHM.Id
	INNER JOIN sStudent.tAcademic SA1 WITH (NOLOCK) 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 WITH (NOLOCK)
	INNER JOIN sFee.tReceiptDetail RD WITH (NOLOCK) ON RD.ReceiptId = R.Id AND R.SourceTypeId = 2001
	INNER JOIN sFee.tFeeSetup FS WITH (NOLOCK) ON RD.FeeSetupId = FS.Id
	INNER JOIN sStudent.tAcademic SA1 WITH (NOLOCK) 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,0038190 by Foram Start
	IF (@rAcademicId > 0)
	BEGIN
		--changes for Mantis ID:0041386 by Hemali
		IF NOT EXISTS (
				SELECT 1
				FROM #temptable FS
				INNER JOIN (
					SELECT FeeSetupId
						,Amount
						,@rReceiptBookId AS ReceiptBookId
					FROM OPENXML(@loDoc, '/Table/ReceiptDetail', 1) WITH (
							FeeSetupId INT
							,Amount DECIMAL(12, 2)
							)
					) AS RD ON RD.FeeSetupId = FS.Id 
				)
		BEGIN
			SELECT @lWrongFeeSetupOrReceiptBook = 1
		END
		--changes for Mantis ID:0041386 by Hemali
		ELSE
		BEGIN
			IF EXISTS (
					SELECT 1
					FROM #temptable FS
					INNER JOIN (
						SELECT FeeSetupId
							,Amount
							,@rReceiptBookId AS ReceiptBookId
						FROM OPENXML(@loDoc, '/Table/ReceiptDetail', 1) WITH (
								FeeSetupId INT
								,Amount DECIMAL(12, 2)
								)
						) AS RD ON RD.FeeSetupId = FS.Id AND RD.ReceiptBookId <> FS.ReceiptBookId
					)
			BEGIN
				SELECT @lWrongFeeSetupOrReceiptBook = 1
			END
		END
	END -- For Mantis 0032370,0038190 by Foram End
	
	
	IF EXISTS (
			SELECT 1
			FROM sStudent.tAcademic SA WITH (NOLOCK)
			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 WITH (NOLOCK) ON FA.FeeSetupId = FS.Id AND FA.SourceId = SA.Id
			LEFT JOIN #temptable1
				--(
				--	SELECT 
				--			ISNULL(SUM(RD.Amount),0) AS PaidAmount,RD.FeeSetupId ,R.SourceId
				--    FROM
				--		sFee.tReceipt R 
				--		INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id AND R.SourceTypeId = 2001
				--		INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id
				--		INNER JOIN sStudent.tAcademic SA1 ON SA1.Id=R.SourceId AND SA1.AdmissionCategoryId = FS.AdmissionCategoryId	 
				--	WHERE	
				--	(R.SourceTypeId = 2001)
				--		 AND R.SourceId = @rAcademicId				
				--		AND (R.IsObsolete = 0) 
				--		AND (ISNULL(FS.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeSetupIds,','))OR @rFeeSetupIds='')
				--		GROUP BY FeeSetupId,R.SourceId	
				--)
				R ON R.FeeSetupId = FS.Id AND SA.Id = R.SourceId
			LEFT JOIN (
				SELECT FeeSetupId
					,Amount
				FROM OPENXML(@loDoc, '/Table/ReceiptDetail', 1) WITH (
						FeeSetupId INT
						,Amount DECIMAL(12, 2)
						)
				) AS RD ON RD.FeeSetupId = FS.Id
			WHERE SA.Id = @rAcademicId
				AND (ISNULL(FS.Amount, 0.00) + ISNULL(FA.VariableAmount, 0.00) + ISNULL(FA.AdditionalAmount, 0.00) - ISNULL(FA.DiscountAmount, 0.00) - ISNULL(FA.NotApplicableAmount, 0.00) - ISNULL(R.PaidAmount, 0.00) - RD.Amount < 0)
			)
	BEGIN
		SELECT @lAlreadyPaid = 1
	END
	
	--Start for mantis 0031290 By Foram
	IF (@rPayTypeId = 8 AND (@rPaymentTransactionId > 0 OR LEN(@rChequeNo) > 0)) -- Added @rChequeNo for mantis 0035484 by Foram
	BEGIN
		IF EXISTS (
				SELECT 1
				FROM sFee.tReceipt R WITH (NOLOCK)
				INNER JOIN sFee.tReceiptDetail RD WITH (NOLOCK) ON RD.ReceiptId = R.Id
					AND R.SourceTypeId = 2001
				INNER JOIN sFee.tFeeSetup FS WITH (NOLOCK) ON RD.FeeSetupId = FS.Id
				INNER JOIN sStudent.tAcademic SA1 WITH (NOLOCK) 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 OR R.ChequeNo = @rChequeNo) -- Added @rChequeNo for mantis 0035484 by Foram
					AND ((
						ISNULL(R.PaymentTransactionId, 0) > 0 AND 
						(ISNULL(R.PaymentTransactionId, 0) = @rPaymentTransactionId OR 
							R.PaymentTransactionId = CASE WHEN ISNUMERIC(@rChequeNo) = 1 THEN CAST(@rChequeNo AS BIGINT) ELSE 0 END)
						) 
						OR 
						(
						ISNULL(R.ChequeNo, '') <> '' AND 
						(ISNULL(R.ChequeNo, '') = @rChequeNo OR R.ChequeNo = CAST(@rPaymentTransactionId AS NVARCHAR(20)))
						) 
					) -- Changes For Mantis Id: 0037034 by Hemali
					AND R.PayTypeId = 8
				)
		BEGIN
			SELECT @lDuplicateReceipt = 1
		END
	END
	--end for mantis 0031290 By Foram
	
	--@lWrongFeeSetupOrReceiptBook			-1
	--@lAlreadyPaid,@lDuplicateReceipt		1

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

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


GO
ALTER PROCEDURE [sFee].[pReceiptChargeAdd] 
	@rSourceTypeId SMALLINT
	,@rSourceId BIGINT
	,@rReceiptId BIGINT
	,@rCreatedUserId BIGINT
	,@rOrgId INT
	,@rBatchId INT
	,@rCharge DECIMAL(12, 2) = 0
	,@rReceiptBookId INT

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	DECLARE @lClassId INT
		,@lFeeSetupId INT
		,@lAdmissionCategoryId BIGINT

	SELECT @lClassId = A.ClassId
		,@lAdmissionCategoryId = A.AdmissionCategoryId
	FROM sStudent.tAcademic A WITH (NOLOCK)
	INNER JOIN sStudent.tStudentMaster S WITH (NOLOCK) ON A.StudentId = S.Id
	WHERE A.Id = @rSourceId

	SELECT @lFeeSetupId = FS.ID
	FROM sFee.tFeeSetup FS WITH (NOLOCK)
	INNER JOIN sFee.tFeeMaster FM WITH (NOLOCK) ON FS.FeeId = FM.Id
	INNER JOIN sFee.tFeeHeadMaster FH WITH (NOLOCK) ON FM.FeeHeadId = FH.Id
	WHERE FS.BatchId = @rBatchId
		AND FS.ClassId = @lClassId
		AND FS.AdmissionCategoryId = @lAdmissionCategoryId
		AND FH.Number = '100'
		AND FS.IsVariable = 1
		AND FS.ReceiptBookId = @rReceiptBookId

	IF @lFeeSetupId IS NULL
		RETURN

	IF EXISTS (
			SELECT 1
			FROM sFee.tFeeAllocation WITH (NOLOCK)
			WHERE SourceTypeId = 2001
				AND SourceId = @rSourceId
				AND FeeSetupId = @lFeeSetupId
			)
	BEGIN
		UPDATE sFee.tFeeAllocation
		SET VariableAmount = (VariableAmount + @rCharge)
		WHERE SourceTypeId = 2001
			AND SourceId = @rSourceId
			AND FeeSetupId = @lFeeSetupId
	END
	ELSE
	BEGIN
		INSERT INTO sFee.tFeeAllocation (
			SourceTypeId
			,SourceId
			,FeeSetupId
			,VariableAmount
			,DiscountAmount
			,NotApplicableAmount
			,AdditionalAmount
			,Remark
			,CreatedUserId
			,CreatedDateTime
			)
		SELECT 2001
			,@rSourceId
			,@lFeeSetupId
			,@rCharge
			,0
			,0
			,0
			,''
			,@rCreatedUserId
			,sCommon.fGetDate()
	END

	--IF NOT EXISTS (SELECT 1 FROM sFee.tFeeOptional WHERE SourceTypeId = 2001 AND SourceId = @rSourceId 
	--	 AND FeeSetupId = @lFeeSetupId )
	--	 BEGIN
	--			 INSERT INTO sFee.tFeeOptional
	--			(
	--			   FeeSetupId,
	--				SourceTypeId,
	--				SourceId,
	--				BatchId
	--			)
	--			SELECT 
	--			 @lFeeSetupId,
	--			 2001,
	--			 @rSourceId,
	--			 @rBatchId
	--END
	INSERT INTO sFee.tReceiptDetail (
		ReceiptId
		,FeeSetupId
		,Amount
		)
	SELECT @rReceiptId
		,@lFeeSetupId
		,@rCharge

	UPDATE sFee.tReceipt
	SET ReceiptAmount = (ReceiptAmount + @rCharge)
		,TotalReceiptAmount = (TotalReceiptAmount + @rCharge)
	WHERE Id = @rReceiptId
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 WITH (NOLOCK) INNER JOIN sFee.tFeeSetup S WITH (NOLOCK) ON D.FeeSetupId = S.Id
	WHERE D.ReceiptId = @rReceiptId AND S.IsServiceTax = 1

SELECT @lTaxTypeId = TaxTypeId FROM sFee.tReceiptBookMaster WITH (NOLOCK) 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 WITH (NOLOCK) 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 WITH (NOLOCK) 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
 select @lTaxAmount
UPDATE sFee.tReceipt SET ReceiptAmount = (TotalReceiptAmount + @lTaxAmount) , -- DiscountAmount =  @lTaxAmount, Remove for Mantis : 0031923
		TaxPercentage = @rTaxRate WHERE Id =@rReceiptId
 
	END
GO
PRINT N'Altering Procedure [sFee].[pRptFeePendingDetailListGet]...';


GO

ALTER PROCEDURE [sFee].[pRptFeePendingDetailListGet]

	@rReportId int=0,
	@rReceiptBookId int=0,
	@rReceiptBookIds nvarchar(max) = '',
	@rAdmissionCategoryId int=0,
	@rAdmissionCategoryIds nvarchar(max) = '',
	@rClassId int=0,
	@rDivisionId int=0,
	@rUptoDate date='',
	@rBatchId int=0,
	@rUserId bigint=0,
	@rBuilder1 nvarchar(max) = '',
	@rBuilder2 nvarchar(max) = '',
	@rIsDetail bit=0,
	@rOrgId int=0,
	@rOrgGroupBatchId int=0,
	@rStatusId int=0,
	@rCommonBatch nvarchar(100) = '',
	@rDepartmentId int=0,
	@rFromRollNo int=0,
	@rToRollNo int=0,
	@rCode nvarchar(20)='',
	@rIsFilter bit=0,
	@rIsHeader bit=0,
	@rCreatedUserName nvarchar(20) = '',
	@rIsReceiptBookGroup bit=0,
	@rFeeHeadId nvarchar(max) = '',
	@rIsDisplayOrgGroup bit=0,
	@rFeeId nvarchar(max) = '',
	@rFilterId int=0,
	@rOrgIds  nvarchar(max) = '',
	@rPayDate date='',
	@rCollectionGroupId int =0,
	@rCastCategoryId int = 0,
	@rReportType int=0,
	@rClassStatusId int=0 ,
	@rCollectionGrupId nvarchar(max) ='',
	@rClassIds nvarchar(max) = '',
	@rDivisionIds nvarchar(max) = ''

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

	CREATE TABLE #TempIsOptional
	(
		FeeId int,
		Id int,
		IsOptional bit,
		IsVariable bit,
		Amount decimal(12,2),
		StartDate date,
		EndDate date,
		BatchId int,
		ReceiptBookId int,
		AcademicId bigint,
		FeeName nvarchar(100),
		FeeHeadId int,
		CollectionGroupId int,
		CollectionGroup nvarchar(max),
		FeeOrderIndex int,
		CollectionGroupOrderIndex int,
		CollectionGroupMasterRemark nvarchar(500),
		FeeDuration nvarchar(100)						--add
	)

	INSERT INTO #TempIsOptional
		SELECT
			FS1.FeeId,
			FS1.Id,
			ISNULL(FS1.IsOptional,0)AS IsOptional,
			ISNULL(FS1.IsVariable,0)AS IsVariable,
			ISNULL(FS1.Amount,0)AS Amount,
			ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
			ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
			FS1.BatchId,
			ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
			SA1.Id AS AcademicId,
			FM.Title AS FeeName,
			FM.FeeHeadId,
			ISNULL(CGM.Id,0) AS CollectionGroupId,
		    ISNULL(CGM.Title,'') AS CollectionGroup,
			FM.OrderIndex,
			CGM.OrderIndex  AS CollectionGroupOrderIndex,
			CGM.Remark AS CollectionGroupMasterRemark,
			FS1.FeeDuration AS FeeDuration							--add
		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
			AND ((SA1.ClassId=@rClassId) OR (@rClassId=0))
			AND (ISNULL(SA1.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='')
			AND ((SA1.DivisionId=@rDivisionId) OR (@rDivisionId=0))
			AND (ISNULL(SA1.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='')
			AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
			INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
			INNER JOIN sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
			LEFT JOIN sFee.tCollectionGroupMaster CGM ON FS1.CollectionGroupId=CGM.Id
			--AND RBM.Id = CGM.ReceiptBookId
			AND CGM.OrgGroupBatchId = @rOrgGroupBatchId
		WHERE
			BM.OrgGroupBatchId = @rOrgGroupBatchId
			AND ((FS1.ClassId=@rClassId) OR (@rClassId=0))
			AND ((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
			AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
			AND (FS1.AdmissionCategoryId IN(SELECT cast(item as int) FROM  sCommon.fnsplit(@rAdmissionCategoryIds,',')) OR @rAdmissionCategoryIds='')
			AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
			AND (FS1.ReceiptBookId IN(SELECT cast(item as int) FROM  sCommon.fnsplit(@rReceiptBookIds,',')) OR @rReceiptBookIds='')
			AND ((FS1.CollectionGroupId=@rCollectionGroupId) OR (@rCollectionGroupId=0))
			AND (FS1.IsOptional=0)
			AND ((BM.Title = @rCommonBatch) OR (@rCommonBatch = ''))
			AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
			AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
			AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
			AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
			AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')
			AND (ISNULL(CGM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rCollectionGrupId,','))OR @rCollectionGrupId='')
			AND (ISNULL(FS1.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='')
			AND (ISNULL(SA1.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='')

	UNION ALL

		SELECT
			FS1.FeeId,
			FS1.Id,
			ISNULL(FS1.IsOptional,0)AS IsOptional,
			ISNULL(FS1.IsVariable,0)AS IsVariable,
			ISNULL(FS1.Amount,0)AS Amount,
			ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
			ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
			FS1.BatchId,
			ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
			SA1.Id AS AcademicId,
			FM.Title AS FeeName,
			FM.FeeHeadId,
			ISNULL(CGM.Id,0) AS CollectionGroupId,
		    ISNULL(CGM.Title,'') AS CollectionGroup,
			FM.OrderIndex,
			CGM.OrderIndex  AS CollectionGroupOrderIndex,
			CGM.Remark AS CollectionGroupMasterRemark,
			FS1.FeeDuration AS FeeDuration					--add
		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.tAcademic SA1 ON SA1.Id=FO.SourceId
			AND SA1.BatchId = FS1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId AND SA1.ClassId = FS1.ClassId

			AND ((SA1.ClassId=@rClassId) OR (@rClassId=0))
			AND (ISNULL(SA1.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='')
			AND ((SA1.DivisionId=@rDivisionId) OR (@rDivisionId=0))
			AND (ISNULL(SA1.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='')
			AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
			INNER JOIN sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
			LEFT JOIN sFee.tCollectionGroupMaster CGM ON FS1.CollectionGroupId=CGM.Id
			--AND RBM.Id = CGM.ReceiptBookId
			AND CGM.OrgGroupBatchId = @rOrgGroupBatchId
		WHERE
			BM.OrgGroupBatchId = @rOrgGroupBatchId
			AND ((FS1.ClassId=@rClassId) OR (@rClassId=0))
			AND ((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
			AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
			AND (FS1.AdmissionCategoryId IN(SELECT cast(item as int) FROM  sCommon.fnsplit(@rAdmissionCategoryIds,',')) OR @rAdmissionCategoryIds='')
			AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
			AND (FS1.ReceiptBookId IN(SELECT cast(item as int) FROM  sCommon.fnsplit(@rReceiptBookIds,',')) OR @rReceiptBookIds='')
			AND ((FS1.CollectionGroupId=@rCollectionGroupId) OR (@rCollectionGroupId=0))
			AND (FS1.IsOptional=1)
			AND ((BM.Title = @rCommonBatch) OR (@rCommonBatch = ''))
			AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
			AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
			AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
			AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
			AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')
			AND (ISNULL(CGM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rCollectionGrupId,','))OR @rCollectionGrupId='')
			AND (ISNULL(FS1.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='')
			AND (ISNULL(SA1.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='')

	CREATE TABLE #TempReceipt
	(
		PaidAmount decimal(12,2),
		FeeSetupId int,
		SourceId bigint
	)

	INSERT INTO #TempReceipt
	SELECT
		ISNULL(SUM(RD.Amount),0) AS PaidAmount,RD.FeeSetupId ,R.SourceId
	FROM
		sFee.tReceipt R
		INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id
		INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id
		INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id
		INNER JOIN sStudent.tAcademic SA1 ON SA1.Id=R.SourceId
		INNER JOIN sSetup.tBatchMaster BM ON BM.Id=SA1.BatchId
		AND (SA1.ClassId=@rClassId OR @rClassId=0)
		AND (ISNULL(SA1.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='')
		AND ((SA1.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		AND (ISNULL(SA1.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='')
		AND (SA1.DivisionId=@rDivisionId OR @rDivisionId=0)
	WHERE
		(R.SourceTypeId = 2001)
		AND ((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
		AND (R.IsObsolete = 0)
		AND ((BM.OrgGroupBatchId = @rOrgGroupBatchId))
		AND (R.OrgGroupBatchId = @rOrgGroupBatchId)
		AND (R.ReceiptDate <= @rUptoDate) -- added condition after nes issue on 09/08/2016
		-- OR (@rOrgGroupBatchId = @rOrgGroupBatchId))
		AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
		AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))
		AND ((BM.Title = @rCommonBatch) OR (@rCommonBatch = ''))
		AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
		AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
		AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')
	GROUP BY FeeSetupId,R.SourceId

	CREATE TABLE #TempAssignRoute
	(
		SourceId bigint
	)

	INSERT INTO #TempAssignRoute
	SELECT
		AT.SourceId
	FROM
		sTransport.tAssignRoute AT
		INNER JOIN sTransport.tBusRouteDestinationMaster BM ON BM.Id=AT.PickupDestinationId
		INNER JOIN sTransport.tBusRouteMaster B ON B.Id=BM.BusRouteId AND  AT.SourceTypeId=2003 AND ((B.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))

	IF(@rReportType=1)
	BEGIN
		SELECT
		@rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,
		@rIsDetail AS IsDetail,
		@rIsFilter As IsFilter,
		@rIsHeader As IsHeader,
		@rIsDisplayOrgGroup AS IsDisplayOrgGroup,
		SA.AcademicId,
		SA.RollNo,
		SA.Name,
		SA.Code,
		SA.ClassId,
		SA.DivisionId,
		SA.ClassName,
		SA.DivisionName,
		SA.DivisionOrder,
		SA.ClassName+' - '+SA.DivisionName AS ClassDivision,
		FS.Id AS FeeSetupId,
		ISNULL(FS.IsVariable,0)AS IsVariable,
		ISNULL(FS.Amount,0)AS Amount,
		ISNULL(FS.StartDate,'1900-01-01')AS StartDate,
		ISNULL(FS.EndDate,'1900-01-01')AS EndDate,
		ISNULL(FA.VariableAmount,0.00)AS FAAmount,
		ISNULL(FA.DiscountAmount,0.00)AS DiscountAmount,
		ISNULL(FA.AdditionalAmount,0.00)AS AdditionalAmount,
		ISNULL(R.PaidAmount,0) AS PaidAmount,
		ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00)AS PendingAmount,
		ISNULL(FA.Remark,'') AS Remark,
		FS.FeeName,
		FHM.Id AS FeeHeadId,
		FHM.Title AS FeeHeadName,
		FHM.OrderIndex AS FeeHeadOrderIndex,
		SA.OrgId,
		O.Title AS OrgName,
		O.OrderIndex AS OrgOrderIndex,
		(CASE WHEN @rIsReceiptBookGroup = 0 THEN 0
		WHEN @rIsReceiptBookGroup = 1 THEN FS.ReceiptBookId
		END) AS ReceiptBookId,
		(CASE WHEN @rIsReceiptBookGroup = 0 THEN 'ALL'
		WHEN @rIsReceiptBookGroup = 1 THEN ISNULL(RBM.Title,'')
		END) AS ReceiptBookTitle,
		(CASE WHEN @rIsReceiptBookGroup = 0 THEN 0
		WHEN @rIsReceiptBookGroup = 1 THEN ISNULL(RBM.OrderIndex,0)
		END) AS ReceiptOrderIndex,
		--FS.ReceiptBookId,
		ISNULL(RBM.FullTitle,'') AS ReceiptBookFullTitle,
		ISNULL(RBM.Address1,'') AS RecieptBookAddress1,
		IsNULL(RBM.Address2,'') As RecieptBookAddress2,
		IsNULL(RBM.Remark1,'') As Remark1,
		--ISNULL(RBM.OrderIndex,0) AS ReceiptOrderIndex,
		SA.OrgGroupBatchId,
		SA.DepartmentId,
		SA.DepartmentName,
		ISNULL(SC.ParentContactNo,'') AS ParentContactNo,
		ISNULL(SO.ReferenceRemark,'') AS ReferenceRemark,
		@rPayDate AS PayDate,
		ISNULL(CCM.MainCastCategoryId,0) AS CastCategoryId,
		ISNULL(CCM.Title,'') AS CastCategoryName,
		ISNULL(CCM.OrderIndex,'') AS CastCategoryOrderIndex,
		ISNULL((SELECT ISNULL(Template,'') FROM sCommon.tReportTemplate WHERE ReportId = @rReportId AND OrgId=SA.OrgId),0) AS ReportTemplate,
		FS.CollectionGroupId,
		FS.CollectionGroup,
		SA.BatchName,
		ISNULL(SSF.FatherName, '') AS FatherName,
		ISNULL(SSF.FatherContactNo, '') AS FatherContactNo,
		ISNULL(SSF.MotherName, '') AS MotherName,
		ISNULL(SSF.MotherContactNo, '') AS MotherContactNo,
		FS.FeeOrderIndex AS FeeOrderIndex,
		ISNULL(SC.PresentStreetOne,'')+' '+ISNULL(SC.PresentStreetTwo,'')+' '+ISNULL(SC.PresentStreetThree,'')+' '+ISNULL(SC.PresentCity,'')+' '+ISNULL(SC.PresentState,'') AS [Address],
		ISNULL(SC.StudentContactNo,'') AS StudentContactNo,
	 SA.GenderId,
	 SA.FirstName as StudentName,
	 FS.CollectionGroupOrderIndex,
	 SA.SUId AS SUId,
	 FS.CollectionGroupMasterRemark,
	 SA.LastName as LastName,
	 FS.FeeDuration as FeeDuration,	--add
	 --Mantis: 31868, start
	 case when @rReportId=10147
		then O.OrgLogo
		else null end AS OrgLogo,
	 O.SmallAddress1 AS OrgAddress,
	 --Mantis: 31868, end
	 ISNULL(SC.WhatsAppContactNo,'') AS WhatsAppContactNo,       --Mantis - 0032963
	 ISNULL(ACM.Title,'') AS FeeCategory, -- Added by Dhananjay for Mantis Id - 35029
	 ISNULL(SSF.FatherMail,'') AS FatherMail, --add for mantis : 0036510
	 ISNULL(SSF.MotherMail,'') AS MotherMail, --add for mantis : 0036510
	 ISNULL(SC.ParentEmail,'') AS ParentEmail, -- add for mantis : 0039011
	 ISNULL(DM.OrderIndex,9999) AS DepartmentOrderIndex-- Added by Dhananjay for Mantis Id - 42557
	FROM
		sStudent.vStudentAcademic SA
		INNER JOIN #TempIsOptional FS ON FS.AcademicId=SA.AcademicId
		LEFT JOIN sFee.tFeeAllocation FA
		ON FA.FeeSetupId=FS.Id AND FA.SourceId=SA.AcademicId
		LEFT JOIN #TempReceipt R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
		INNER JOIN sSetup.tOrganizationMaster O ON
		SA.OrgId = O.Id
		INNER JOIN sFee.tReceiptBookMaster RBM
		ON FS.ReceiptBookId=RBM.Id
		LEFT JOIN sStudent.tStudentCommunication SC
		ON SC.StudentId = SA.StudentId
		LEFT JOIN sStudent.tStudentOther SO
		ON SO.StudentId = SA.StudentId
		LEFT JOIN sCommon.tCastCategoryMaster CCM
		ON CCM.Id = SO.CastCategoryId
		INNER JOIN sFee.tFeeHeadMaster FHM
		ON FHM.Id = FS.FeeHeadId

		LEFT JOIN sHostel.tAssignRoom AR ON  AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003 AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) AND ((AR.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))
		LEFT JOIN #TempAssignRoute RT ON RT.SourceId = SA.StudentId AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))
		LEFT JOIN sStudent.tStudentFamily SSF ON SSF.StudentId = SA .StudentId
		INNER JOIN sStudent.tAdmissionCategoryMaster ACM ON ACM.Id = SA.AdmissionCategoryId -- Added by Dhananjay for Mantis Id - 35029
		INNER JOIN sSetup.tDepartmentMaster DM On DM.Id = SA.DepartmentId-- Added by Dhananjay for Mantis Id - 42557
	WHERE
		SA.OrgGroupBatchId = @rOrgGroupBatchId
		AND ((SA.BatchId=@rBatchId) OR (@rBatchId=0))
		AND (SA.StatusId = @rStatusId OR @rStatusId=0)
		AND ((FS.StartDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
		AND ((SA.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
		AND ((SA.RollNo <= @rToRollNo) OR (@rToRollNo=0))
		AND ((SA.Code=@rCode) OR (@rCode=''))
		AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
		AND (ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00) -ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00) != 0)
		AND (
				(@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 (ISNULL(SA.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')
		AND ((CCM.Id=@rCastCategoryId) OR (@rCastCategoryId=0))
		AND ((SA.ClassStatusId=@rClassStatusId) OR (@rClassStatusId=0))
	Order by SA.RollNo
	END
	ELSE
	BEGIN
	SELECT
		@rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,
		@rIsDetail AS IsDetail,
		@rIsFilter As IsFilter,
		@rIsHeader As IsHeader,
		@rIsDisplayOrgGroup AS IsDisplayOrgGroup,
		SA.AcademicId,
		SA.RollNo,
		SA.Name,
		SA.Code,
		SA.ClassId,
		SA.DivisionId,
		SA.ClassName,
		SA.DivisionName,
		SA.DivisionOrder,
		SA.ClassName+' - '+SA.DivisionName AS ClassDivision,
		FS.Id AS FeeSetupId,
		ISNULL(FS.IsVariable,0)AS IsVariable,
		ISNULL(FS.Amount,0)AS Amount,
		ISNULL(FS.StartDate,'1900-01-01')AS StartDate,
		ISNULL(FS.EndDate,'1900-01-01')AS EndDate,
		ISNULL(FA.VariableAmount,0.00)AS FAAmount,
		ISNULL(FA.DiscountAmount,0.00)AS DiscountAmount,
		ISNULL(FA.AdditionalAmount,0.00)AS AdditionalAmount,
		ISNULL(FAS.PaidAmount,0) AS PaidAmount,
		ISNULL(FAS.ToPayAmount,0.00) PendingAmount,
		ISNULL(FA.Remark,'') AS Remark,
		--FS.FeeName,
		FM.Title AS FeeName,
		FHM.Id AS FeeHeadId,
		FHM.Title AS FeeHeadName,
		FHM.OrderIndex AS FeeHeadOrderIndex,
		SA.OrgId,
		O.Title AS OrgName,
		O.OrderIndex AS OrgOrderIndex,
		(CASE WHEN @rIsReceiptBookGroup = 0 THEN 0
		WHEN @rIsReceiptBookGroup = 1 THEN FS.ReceiptBookId
		END) AS ReceiptBookId,
		(CASE WHEN @rIsReceiptBookGroup = 0 THEN 'ALL'
		WHEN @rIsReceiptBookGroup = 1 THEN ISNULL(RBM.Title,'')
		END) AS ReceiptBookTitle,
		(CASE WHEN @rIsReceiptBookGroup = 0 THEN 0
		WHEN @rIsReceiptBookGroup = 1 THEN ISNULL(RBM.OrderIndex,0)
		END) AS ReceiptOrderIndex,
		ISNULL(FS.ReceiptBookId,'0') As ReceiptBookId,
		ISNULL(RBM.FullTitle,'') AS ReceiptBookFullTitle,
		ISNULL(RBM.Address1,'') AS RecieptBookAddress1,
		IsNULL(RBM.Address2,'') As RecieptBookAddress2,
		IsNULL(RBM.Remark1,'') As Remark1,
		ISNULL(RBM.OrderIndex,0) AS ReceiptOrderIndex,
		SA.OrgGroupBatchId,
		SA.DepartmentId,
		SA.DepartmentName,
		ISNULL(SC.ParentContactNo,'') AS ParentContactNo,
		ISNULL(SO.ReferenceRemark,'') AS ReferenceRemark,
		@rPayDate AS PayDate,
		ISNULL(CCM.MainCastCategoryId,0) AS CastCategoryId,
		ISNULL(CCM.Title,'') AS CastCategoryName,
		ISNULL(CCM.OrderIndex,'') AS CastCategoryOrderIndex,
		ISNULL((SELECT ISNULL(Template,'') FROM sCommon.tReportTemplate WHERE ReportId = @rReportId AND OrgId=SA.OrgId),0) AS ReportTemplate,
		ISNULL(CGM.Id,0) AS CollectionGroupId,
		ISNULL(CGM.Title,'') AS CollectionGroup,
		SA.BatchName,
		ISNULL(SSF.FatherName, '') AS FatherName,
		ISNULL(SSF.FatherContactNo, '') AS FatherContactNo,
		ISNULL(SSF.MotherName, '') AS MotherName,
		ISNULL(SSF.MotherContactNo, '') AS MotherContactNo,
		FM.OrderIndex AS FeeOrderIndex,
		ISNULL(SC.PresentStreetOne,'')+' '+ISNULL(SC.PresentStreetTwo,'')+' '+ISNULL(SC.PresentStreetThree,'')+' '+ISNULL(SC.PresentCity,'')+' '+ISNULL(SC.PresentState,'') AS [Address],
		ISNULL(SC.StudentContactNo,'') AS StudentContactNo,
		CGM.OrderIndex  AS CollectionGroupOrderIndex,
		SA.SUId AS SUId,
		ISNULL(SC.WhatsAppContactNo,'') AS WhatsAppContactNo, --Mantis - 0032963
		ISNULL(ACM.Title,'') AS FeeCategory, -- Added by Dhananjay for Mantis Id - 35029
		ISNULL(SSF.FatherMail,'') AS FatherMail, --add for mantis : 0036510
		ISNULL(SSF.MotherMail,'') AS MotherMail, --add for mantis : 0036510
		ISNULL(SC.ParentEmail,'') AS ParentEmail, --add for mantis : 0039011
		ISNULL(DM.OrderIndex,9999) AS DepartmentOrderIndex-- Added by Dhananjay for Mantis Id - 42557

	FROM
		sStudent.vStudentAcademic SA
		INNER JOIN sFee.tFeeAllocationStudent FAS ON FAS.AcademicId=  SA.AcademicId
		INNER JOIN sFee.tFeeSetup FS ON FS.ID=FAS.FeeSetupId
		INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS.FeeId
		INNER JOIN sSetup.tOrganizationMaster O ON SA.OrgId = O.Id
		INNER JOIN sFee.tReceiptBookMaster RBM ON FS.ReceiptBookId=RBM.Id
		INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FM.FeeHeadId
		LEFT JOIN sFee.tFeeAllocation FA ON FA.FeeSetupId=FAS.FeeSetupId AND FA.SourceId=SA.AcademicId
		LEFT JOIN sStudent.tStudentCommunication SC	ON SC.StudentId = SA.StudentId
		LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId = SA.StudentId
		LEFT JOIN sCommon.tCastCategoryMaster CCM ON CCM.Id = SO.CastCategoryId
		LEFT JOIN sHostel.tAssignRoom AR ON  AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003 AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  AND ((AR.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))
        LEFT JOIN
		(SELECT AT.SourceId FROM sTransport.tAssignRoute AT
		INNER JOIN sTransport.tBusRouteDestinationMaster BM ON BM.Id=AT.PickupDestinationId
		INNER JOIN sTransport.tBusRouteMaster B ON B.Id=BM.BusRouteId AND  AT.SourceTypeId=2003 AND ((B.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))) RT
		ON RT.SourceId = SA.StudentId AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))
		LEFT JOIN sFee.tCollectionGroupMaster CGM ON FS.CollectionGroupId=CGM.Id
		AND CGM.OrgGroupBatchId = @rOrgGroupBatchId
		LEFT JOIN sStudent.tStudentFamily SSF ON SSF.StudentId = SA .StudentId
		INNER JOIN sStudent.tAdmissionCategoryMaster ACM ON ACM.Id = SA.AdmissionCategoryId -- Added by Dhananjay for Mantis Id - 35029
		INNER JOIN sSetup.tDepartmentMaster DM On DM.Id = SA.DepartmentId-- Added by Dhananjay for Mantis Id - 42557
	WHERE
		SA.OrgGroupBatchId = @rOrgGroupBatchId
		AND ((SA.BatchId=@rBatchId) OR (@rBatchId=0))
		AND (SA.StatusId = @rStatusId OR @rStatusId=0)
		AND ((FS.StartDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
		AND ((SA.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
		AND ((SA.RollNo <= @rToRollNo) OR (@rToRollNo=0))
		AND ((SA.Code=@rCode) OR (@rCode=''))
		AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
		--AND (ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00) -ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00) != 0)
		AND ISNULL(FAS.ToPayAmount,0.00) !=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 (ISNULL(SA.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')
		AND ((CCM.Id=@rCastCategoryId) OR (@rCastCategoryId=0))
		AND ((SA.ClassStatusId=@rClassStatusId) OR (@rClassStatusId=0))
		AND (ISNULL(CGM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rCollectionGrupId,','))OR @rCollectionGrupId='')
	Order by SA.RollNo
	END

	DROP TABLE #TempIsOptional
	DROP TABLE #TempReceipt
	DROP TABLE #TempAssignRoute



	--SELECT
	--    '' as Builder1,
	--	'' as Builder2,
	--	Convert(bit,0) as IsDetail,
	--	Convert(bit,0) as IsFilter,
	--	Convert(bit,0) as IsHeader,
	--	Convert(bit,0) as IsDisplayOrgGroup,
	--	Convert(bigint,0) as AcademicId,
	--	0 As RollNo,
	--	'' as Name,
	--	'' As Code,
	--	0 as ClassId,
	--	0 as DivisionId,
	--	'' as ClassName,
	--	'' as DivisionName,
	--	0 as DivisionOrder,
	--	 '' as ClassDivision,
	--	0 as FeeSetupId,
	--	Convert(bit,0) as IsVariable,
	--	 0.00 As Amount,
	--	'2001-01-30' AS StartDate,
	--	'2001-01-30' As EndDate,
	--	0.00 As FAAmount,
	--	0.00 As DiscountAmount,
	--	0.00 As AdditionalAmount,
	--	0.00 As PaidAmount,
	--	0.00 As  PendingAmount,
	--	'' AS Remark,
	--	--FS.FeeName,
	--	'' AS FeeName,
	--	0 AS FeeHeadId,
	--	'' AS FeeHeadName,
	--	0 As FeeHeadOrderIndex,
	--	0 As OrgId,
	--	'' AS OrgName,
	--	0 AS OrgOrderIndex,
	--	0 AS ReceiptBookId,
	--	'' AS ReceiptBookTitle,
	--	0 AS ReceiptOrderIndex,
	--	'' AS ReceiptBookFullTitle,
	--	'' AS RecieptBookAddress1,
	--	'' AS RecieptBookAddress2,
	--	'' As Remark1,
	--	0 As OrgGroupBatchId,
	--	0 As DepartmentId,
	--	'' AS DepartmentName,
	--	'' AS ParentContactNo,
	--	'' AS ReferenceRemark,
	--	'2001-01-30' AS PayDate ,
	--	0 AS CastCategoryId,
	--	'' AS CastCategoryName,
	--	0 AS CastCategoryOrderIndex,
	--	'' AS ReportTemplate,
	--	0 AS CollectionGroupId,
	--	'' AS CollectionGroup,
	--	'' AS BatchName,
	--	'' AS FatherName,
	--	 '' AS FatherContactNo,
	--	 '' AS MotherName,
	--	 '' AS MotherContactNo,
	--	0 AS FeeOrderIndex,
	--	'' AS Address,
	--	'' AS StudentContactNo,
	--    '' as StudentName,
	--	0 As GenderId,
	-- 0 AS CollectionGroupOrderIndex,
	-- '' AS SUId,
	-- '' AS CollectionGroupMasterRemark,
	-- '' AS LastName,
	-- '' AS FeeDuration,
	----Mantis: 31868, start
	-- Convert(varbinary(max),'') AS OrgLogo,
	-- '' AS OrgAddress,
	----Mantis: 31868, end
	--'' As WhatsAppContactNo,
	--'' As FeeCategory,
	--'' AS FatherMail,
	--'' AS MotherMail,
	--'' AS ParentEmail
	--0 AS DepartmentOrderIndex

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


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

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

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

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

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

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

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

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

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

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


GO
ALTER PROCEDURE [sFee].[pRptReceiptListCollectionGroupwiseListGet]  
	@rReportId int,  
	@rReceiptBookId int,  
	@rAdmissionCategoryId int,  
	@rClassId int,  
	@rDivisionId int,  
	@rFromDate date,  
	@rToDate date,  
	@rFromReceiptNo int,  
	@rToReceiptNo int,  
	@rBatchId int,  
	@rUserId bigint,  
	@rBuilder1 nvarchar(max),  
	@rBuilder2 nvarchar(max),  
	@rIsCancel bit,  
	@rOrgId int,  
	@rOrgGroupBatchId int,  
	@rStatusId int,  
	@rCommonBatch nvarchar(100),  
	@rDepartmentId int,  
	@rFromRollNo int,  
	@rToRollNo int,  
	@rCode nvarchar(20),  
	@rIsDetail bit=0,  
	@rIsFilter bit,  
	@rIsHeader bit,  
	@rCreatedUserName nvarchar(100)='',  
	@rFeeHeadId nvarchar(max) = '',  
	@rIsDisplayOrgGroup bit=0,  
	@rPayTypeId int=0,  
	@rFeeId nvarchar(max) = '',  
	@rFilterId int=0,
	@rOrgIds nvarchar(max) = '',
	@rClassStatusId int=0,
	@rPayTypeIds nvarchar(max) = '',
	@rCollectionGroupId int =0  
  
WITH EXECUTE AS CALLER  
AS  
SET NOCOUNT ON  
      
BEGIN    
	-- Added for optimization by Foram, Mantis : 0042814
	-- Pre-split inputs
	DECLARE @FeeHeadIds TABLE (Id INT);
	DECLARE @FeeIds TABLE (Id INT);
	DECLARE @OrgIds TABLE (Id INT);
	DECLARE @PayTypeIds TABLE (Id TINYINT);
	DECLARE @AssignRouteStudentIds TABLE (SourceId BIGINT);

	INSERT INTO @FeeHeadIds
	SELECT CAST(item AS INT) FROM sCommon.fnsplit(@rFeeHeadId, ',');

	INSERT INTO @FeeIds
	SELECT CAST(item AS INT) FROM sCommon.fnsplit(@rFeeId, ',');

	INSERT INTO @OrgIds
	SELECT CAST(item AS INT) FROM sCommon.fnsplit(@rOrgIds, ',');

	INSERT INTO @PayTypeIds
	SELECT CAST(item AS TINYINT) FROM sCommon.fnsplit(@rPayTypeIds, ',');

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

	DECLARE @lDefaultCurrencyTitle NVARCHAR(100)

	SELECT @lDefaultCurrencyTitle = ISNULL(COALESCE(CS.ItemValue, CM.ItemValue), 'Rupees')
	FROM sConfig.tConfigurationMaster CM
	LEFT JOIN sConfig.tConfigurationSetup CS ON CS.ConfigurationId = CM.Id AND CS.SourceTypeId = 2010 AND CS.SourceId = LEFT(@rOrgGroupBatchId, 4)
	WHERE CM.Id = 153;
	-- Added for optimization by Foram, Mantis : 0042814

	SELECT   
		@rBuilder1 AS Builder1,  
		@rBuilder2 AS Builder2,  
		@rIsCancel AS IsCancel,  
		@rIsDetail AS IsDetail,  
		@rIsFilter As IsFilter,  
		@rIsHeader As IsHeader,  
		@rIsDisplayOrgGroup AS IsDisplayOrgGroup,  
		R.Id AS ReceiptId,  
		R.ReceiptNumber,  
		SA.ClassId,  
		SA.ClassName,  
		SA.DivisionId,  
		SA.DivisionName,  
		SA.ClassName+' - '+SA.DivisionName AS ClassDivision,  
		SA.RollNo,  
		SA.AcademicId,  
		SA.FirstName,  
		SA.MiddleName,  
		SA.LastName,  
		SA.Code,  
		SA.Name,  
		PTM.Title AS PayType,  
		--R.ChequeNo,  
		--CASE WHEN ISNULL(R.ChequeNo,'') != '' THEN R.ChequeNo ELSE CONVERT(nvarchar(20),R.PaymentTransactionId) END AS ChequeNo, -- Commented for optimization by Foram, Mantis : 0042814
		ISNULL(NULLIF(R.ChequeNo, ''), CONVERT(NVARCHAR(20), R.PaymentTransactionId)) AS ChequeNo,    -- Added for optimization by Foram, Mantis : 0042814
		R.BankName,
		--R.ReceiptAmount,  ,
		CASE WHEN ROW_NUMBER() OVER (PARTITION BY R.Id  ORDER BY R.Id ) =1 THEN R.ReceiptAmount ELSE 0 END AS ReceiptAmount,
		R.ReceiptDate,  
		FM.Title AS FeeDetail,  
		FM.Code AS FeeCode,  
		FM.OrderIndex AS FeeOrderIndex,  
		RD.Amount AS DetailAmount,  
		ISNULL(R.ReceiptBookId,'0') As ReceiptBookId,  
		ISNULL(RBM.Title,'') AS ReceiptBookTitle,  
		ISNULL(RBM.OrderIndex,0) AS ReceiptOrderIndex,  
		ISNULL(FHM.Title,'') AS FeeHead,  
		ISNULL(FHM.Code,'') AS FeeHeadCode,  
		ISNULL(FHM.OrderIndex,0) AS FeeHeadOrderIndex,  
		SA.OrgId,  
		O.DisplayTitle AS OrgName,  
		O.OrderIndex AS OrgOrderIndex,  
		ISNULL(R.Remark,'') AS Remark,  
		DM.Id AS DepartmentId,  
		DM.Title AS DepartmentName,  
		SA.ClassOrderIndex,  
		--ISNULL(SO.GenderId,0) AS GenderId,  -- Commented for optimization by Foram, Mantis : 0042814
		ISNULL(SA.GenderId,0) AS GenderId, -- Added for optimization by Foram, Mantis : 0042814
		ISNULL(SA.BatchName,'') BatchName,  
		ISNULL(FM.FeeHeadId,0) AS FeeHeadId,  
		--sFinanceCommon.fNumberToWordsWithDecimal(ISNULL(R.ReceiptAmount,0.00),1,2,O.OrgGroupId) AS ReceiptAmountInWords,  -- Commented for optimization by Foram, Mantis : 0042814
		sFinanceCommon.fNumberToWordsWithDecimalGet(ISNULL(R.ReceiptAmount,0.00),1,2,O.OrgGroupId,@lDefaultCurrencyTitle) AS ReceiptAmountInWords, -- Added for optimization by Foram, Mantis : 0042814
		R.ChequeDate,  
		ISNULL(FM.Id,0) AS FeeId,  
		ISNULL(FM.Title,'') AS Fee,  
		ISNULL(SF.FatherName,'' ) AS FatherName,  
		ISNULL(SF.MotherName,'' ) AS MotherNameDiscount,
		CASE WHEN ROW_NUMBER() OVER (PARTITION BY R.Id  ORDER BY R.Id ) =1 THEN R.DiscountAmount ELSE 0 END AS Discount,
		RD.Amount AS PaidAmount,
		ISNULL(CGM.Id,0) AS CollectionGroupId,
		ISNULL(CGM.Title,'') AS CollectionGroup  ,
		ISNULL(U.LoginTitle,'') AS UserName,
		SA.SUId AS SUId
	FROM   
		sFee.tReceipt R WITH (NOLOCK) 
		INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.SourceId AND ((SA.OrgId=@rOrgId) OR (@rOrgId=0))  
		INNER JOIN sFinanceCommon.tPayTypeMaster PTM WITH (NOLOCK) ON PTM.Id=R.PayTypeId  
		INNER JOIN sFee.tReceiptDetail RD WITH (NOLOCK) ON RD.ReceiptId=R.Id  
		INNER JOIN sFee.tFeeSetup FS WITH (NOLOCK) ON FS.Id=RD.FeeSetupId  
		INNER JOIN sFee.tFeeMaster FM WITH (NOLOCK) ON FM.Id=FS.FeeId  
		INNER JOIN sFee.tFeeHeadMaster FHM WITH (NOLOCK) ON FHM.Id=FM.FeeHeadId  
		INNER JOIN sFee.tReceiptBookMaster RBM WITH (NOLOCK) ON RBM.Id=R.ReceiptBookId  
		INNER JOIN sSetup.tDepartmentMaster DM WITH (NOLOCK) ON SA.DepartmentId=DM.Id  
		INNER JOIN sSetup.tOrganizationMaster O  WITH (NOLOCK) ON O.Id=sa.OrgId  
		LEFT JOIN sSecurity.tUser U  WITH (NOLOCK) ON U.Id=R.CreatedUserId 
		--LEFT JOIN sStudent.tStudentOther SO  WITH (NOLOCK) ON SO.StudentId = SA.StudentId  -- Commented for optimization by Foram, Mantis : 0042814
		LEFT JOIN sStudent.tStudentFamily SF  WITH (NOLOCK) ON SF.StudentId = SA.StudentId  
		LEFT JOIN sHostel.tAssignRoom AR WITH (NOLOCK) ON AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003 AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  AND ((AR.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  
		-- Commented for optimization by Foram, Mantis : 0042814
		--LEFT JOIN (SELECT AT.SourceId FROM sTransport.tAssignRoute AT WITH (NOLOCK)  
		--INNER JOIN sTransport.tBusRouteDestinationMaster BM WITH (NOLOCK) ON BM.Id=AT.PickupDestinationId  
		--INNER JOIN sTransport.tBusRouteMaster B WITH (NOLOCK) ON B.Id=BM.BusRouteId AND  AT.SourceTypeId=2003 
		--AND ((B.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))) RT  
		--ON RT.SourceId = SA.StudentId AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) 
		-- Commented for optimization by Foram, Mantis : 0042814
		LEFT JOIN @AssignRouteStudentIds RT ON RT.SourceId = SA.StudentId AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) -- Added for optimization by Foram, Mantis : 0042814
		LEFT JOIN sFee.tCollectionGroupMaster CGM ON FS.CollectionGroupId=CGM.Id  
	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)  
		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 ((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 ((R.PayTypeId=@rPayTypeId) OR (@rPayTypeId=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 ((SA.ClassStatusId=@rClassStatusId) OR (@rClassStatusId=0))
		AND ((FS.CollectionGroupId=@rCollectionGroupId) OR (@rCollectionGroupId=0)) 
		
		-- Commented for optimization by Foram, Mantis : 0042814 
		--AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')  
		--AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')  
		--AND (ISNULL(R.PayTypeId,0) IN (SELECT cast(item as tinyint) FROM sCommon.fnsplit(@rPayTypeIds,',')) OR @rPayTypeIds='') 
		--AND (ISNULL(SA.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='') 
		-- Commented for optimization by Foram, Mantis : 0042814

		-- Added for optimization by Foram, Mantis : 0042814
		AND (@rFeeHeadId='' OR ISNULL(FM.FeeHeadId,0) IN (SELECT Id FROM @FeeHeadIds))
		AND (@rFeeId='' OR ISNULL(FM.Id,0) IN (SELECT Id FROM @FeeIds)) 
		AND (@rPayTypeIds='' OR ISNULL(R.PayTypeId,0) IN (SELECT Id FROM @PayTypeIds))
		AND (@rOrgIds='' OR ISNULL(SA.OrgId,0) IN (SELECT Id FROM @OrgIds))
		-- Added for optimization by Foram, Mantis : 0042814

	ORDER BY R.ReceiptNumber  

 --ORDER BY R.Id 
-- UNION ALL  
   
-- SELECT   
--  R.Id AS ReceiptId,  
--  0 AS ClassId,  
--  --SA.ClassName,  
--  0 AS DivisionId,  
--  --SA.DivisionName,  
--  EM.DepartmentId,  
--  EM.DepartmentName AS ClassDept,  
--  0 AS RollNo,  
--  EM.Code,  
--  EM.EmployeeName,  
--  PTM.Title AS PayType,  
--  R.ReceiptAmount  
     
--  FROM   
--   sFee.tReceipt R  
--  INNER JOIN sCommon.tSourceTypeMaster STM  
--   ON STM.Id=R.SourceTypeId AND R.SourceTypeId = 95  
--  INNER JOIN sHrm.vExtEmployeeMaster EM  
--   ON EM.EmployeeId=R.SourceId  
--  INNER JOIN sFinanceCommon.tPayTypeMaster PTM  
--   ON PTM.Id=R.PayTypeId  
     
--WHERE   
--  ((EM.DepartmentId = @rDepartmentId) OR (@rDepartmentId = 0))  
-- AND ((R.ReceiptNumber >= @rFromReceiptNo) OR (@rFromReceiptNo = 0))  
-- AND ((R.ReceiptNumber <= @rToReceiptNo) OR (@rToReceiptNo = 0))  
-- AND ((R.ReceiptDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))  
-- AND ((R.ReceiptDate <= @rToDate) OR (ISNULL(@rToDate,'') = ''))  
-- AND (R.BatchId = @rBatchId)  
END
GO
PRINT N'Altering Procedure [sFee].[pRptStudentOptionalFeeListGet]...';


GO

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

		WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

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


GO

ALTER PROCEDURE [sFrontOffice].[pStudentGatePassGet]

			@rId int,
			@rOrgId int=0,
			@rFromGatePassDate datetime='',
			@rToGatePassDate datetime='',
			@rEntryModeStatusId smallint=0,
			@rCode nvarchar(20)='',
			@rIsPrintView bit=0,
			@rOrgGroupId int=0,
			@rUserId bigint= 0,
			@rDepartmentId int=0,
			@rClassId int=0,
			@rDivisionId int=0,
			@rUserSourceTypeId int = 0,
			@rBatchId int = 0
AS
SET NOCOUNT ON
BEGIN
	Declare @GatePassConfig nvarchar(20)=''
	SELECT @GatePassConfig =ItemValue From sConfig.tConfigurationSetup WHERE ConfigurationId = 241 AND SourceId = @rOrgGroupId
	IF (@rUserSourceTypeId = 0 OR @rUserSourceTypeId = 1)
	BEGIN
		SELECT
			SGP.Id,
			vSA.Code,
			vSA.FirstName+' '+vSA.MiddleName+' '+vSA.LastName AS Name,
			VSA.ClassName+' - '+VSA.DivisionName AS Class,
			SGP.AcademicId,
			ISNULL(SGP.RelationshipId,0) AS RelationshipId,
			RM.Title AS Relationship,
			SGP.Relation,
			SGP.VisitorName,
			ISNULL(SGP.VisitorMobile,0) As VisitorMobile,
			SGP.ReasonOfGatePass,
			--(CASE WHEN @rIsPrintView=1 THEN SGP.VisitorPhoto
			--	ELSE ISNULL(SGP.VisitorPhoto, CONVERT(VARBINARY(MAX), 0)) END) AS VisitorPhoto,
			CASE 
				WHEN @rIsPrintView = 1 THEN 
					CASE 
						WHEN ISNULL(DATALENGTH(SGP.VisitorPhoto), 0) > 4 THEN SGP.VisitorPhoto
						ELSE NULL  -- -- Add DATALENGTH Condition Report not open if VisitorPhoto = 0x00000000	MantisId : 0042932
					END
				ELSE 
					ISNULL(SGP.VisitorPhoto, CONVERT(VARBINARY(MAX), 0))
			END AS VisitorPhoto,
			--ISNULL(SGP.VisitorPhoto, CONVERT(VARBINARY(MAX), 0)) AS VisitorPhoto,
			ISNULL(SGP.GatePassDate,'') As GatePassDate,
			ISNULL(SGP.ReturnGatePassDate,'') As ReturnGatePassDate,
			ISNULL(SGP.GatePassTime,'') As GatePassTime,
			ISNULL(SGP.ReturnGatePassTime,'') As ReturnGatePassTime,
			ISNULL(SGP.EntryModeStatusId,0) AS EntryModeStatusId,
			ISNULL(SM.Title,'')  AS EntryModeStatus,
			OM.Id AS OrgId,
			OM.OrgLogo,
			OM.DisplayTitle AS Organization,
			(CASE WHEN @rIsPrintView=1 THEN SI.StudentPhoto
				ELSE ISNULL(SI.StudentPhoto, CONVERT(VARBINARY(MAX), 0)) END) AS StudentPhoto,

			(CASE WHEN @rIsPrintView=1 THEN SI.FatherPhoto
				ELSE ISNULL(SI.FatherPhoto, CONVERT(VARBINARY(MAX), 0)) END) AS FatherPhoto,

			(CASE WHEN @rIsPrintView=1 THEN SI.MotherPhoto
				ELSE ISNULL(SI.MotherPhoto, CONVERT(VARBINARY(MAX), 0)) END) AS MotherPhoto,

			(CASE WHEN @rIsPrintView=1 THEN SI.RelativePhoto
				ELSE ISNULL(SI.RelativePhoto, CONVERT(VARBINARY(MAX), 0)) END) AS RelativePhoto,

			--ISNULL(SI.StudentPhoto, CONVERT(VARBINARY(MAX), 0)) AS StudentPhoto,
			ISNULL(U.DisplayTitle,'') AS UserName,
			vSA.SUId,
			Remark,
			@GatePassConfig AS ConfigValue,
			SF.FatherContactNo,
			SF.MotherContactNo,
			SF.RelativeContactNo,
			SF.FatherName,
			SF.MotherName,
			SF.RelativeName,
			ISNULL(SGP.GatePassNo,'') AS GatePassNo,	--mantis: 39477, change ISNULL(SGP.GatePassNo,0) => ISNULL(SGP.GatePassNo,'')
		    --added by megha for 0027081
			CONVERT(VARCHAR, ISNULL(SGP.GatePassTime,''), 100) AS GatePassTime_12hours,
			(CASE WHEN @GatePassConfig='Image' THEN					--Add For 27089 mantis
				OI.CertificateHeaderA4
				ELSE NULL END) AS CertificateHeaderA4,
			ISNULL(SC.StudentContactNo,'') AS StudentContactNo
		FROM
			sStudent.vStudentAcademic vSA
				INNER JOIN sFrontOffice.tStudentGatePass SGP ON SGP.AcademicId = vSA.AcademicId
				INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=vSA.OrgId
				INNER JOIN sCommon.tRelationshipMaster RM ON RM.Id=SGP.RelationshipId
				INNER JOIN sCommon.tStatusMaster SM ON SM.Id=SGP.EntryModeStatusId
				INNER JOIN sSecurity.tUserOrganization UO ON UO.OrgId = SGP.OrgId AND UO.UserId = @rUserId
				LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId=vSA.StudentId
				LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId = SI.StudentId
				LEFT JOIN sSecurity.tUser U	ON U.Id=SGP.CreatedUserId
				LEFT JOIN sSetup.tOrgImages OI ON OI.OrgId = vSA.OrgId			--Add For 27089 mantis
				LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId = SI.StudentId

		WHERE
			((SGP.Id=@rId) OR (@rId=0))
				AND ((SGP.OrgId=@rOrgId) OR (@rOrgId=0))
				AND ((SGP.GatePassDate>=@rFromGatePassDate) OR (ISNULL(@rFromGatePassDate,'')=''))
				AND ((SGP.GatePassDate<=@rToGatePassDate) OR (ISNULL(@rToGatePassDate,'')=''))
				AND ((SGP.EntryModeStatusId=@rEntryModeStatusId) OR (@rEntryModeStatusId=0))
				AND ((vSA.Code=@rCode) OR (ISNULL(@rCode,'')=''))
				AND (OM.OrgGroupId=@rOrgGroupId)
				AND ((vSA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
				AND ((vSA.ClassId=@rClassId) OR (@rClassId=0))
				AND ((vSA.DivisionId=@rDivisionId) OR (@rDivisionId=0))
				--AND vSA.IsActiveBatch=1
		ORDER BY SGP.GatePassDate,SGP.GatePassTime DESC
	END

	ELSE				-- Mantis id : 0038701 ( Add Else condition for User wise Data get)
	BEGIN
		IF OBJECT_ID('tempdb..#DivisionTemp') IS NOT NULL
			DROP TABLE #DivisionTemp;

		CREATE TABLE #DivisionTemp
		(
			DivisionId int
		);

		DECLARE @lStudentGatePassEntryBasedOn nvarchar(50)=''
		SELECT @lStudentGatePassEntryBasedOn = ItemValue From sConfig.tConfigurationSetup
		WHERE ConfigurationId = 591 AND SourceId = @rOrgGroupId
		DECLARE @lTeacherId bigint=0;
		SELECT @lTeacherId=SourceId From sSecurity.tUser Where Id=@rUserId AND SourceTypeId=95

		IF(@lStudentGatePassEntryBasedOn = 'Class Teacher')
		BEGIN
			INSERT INTO #DivisionTemp
			SELECT DISTINCT DM.Id AS DivisionId
			FROM sSetup.tClassMaster CM
				INNER JOIN sSetup.tDivisionMaster DM ON DM.ClassId = CM.Id
				INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=CM.OrgId
			WHERE DM.InchargeemployeeID=@lTeacherId AND OM.OrgGroupId=@rOrgGroupId
		END
		ELSE IF(@lStudentGatePassEntryBasedOn = 'Class Teacher Batch')
		BEGIN
			INSERT INTO #DivisionTemp
			SELECT DISTINCT  DM.Id AS DivisionId
			FROM sSetup.tClassMaster CM
				INNER JOIN sSetup.tDivisionMaster DM ON DM.ClassId = CM.Id
				INNER JOIN sSetup.tDivisionInchargeEmployee DIE ON DIE.DivisionId = DM.Id
				INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=CM.OrgId
			WHERE DIE.EmployeeID=@lTeacherId   AND OM.OrgGroupId=@rOrgGroupId	AND (DIE.BatchId = @rBatchId OR @rBatchId = 0)
		END
		ELSE IF(@lStudentGatePassEntryBasedOn = 'Academic Setup')
		BEGIN
			INSERT INTO #DivisionTemp
			SELECT DISTINCT DivisionId
			FROM sAcademic.vTeacherSubjectDivision TSD INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=TSD.OrgId
			WHERE  TSD.EmployeeId= @lTeacherId
		END
		ELSE IF(@lStudentGatePassEntryBasedOn = 'User Access')
		BEGIN
			INSERT INTO #DivisionTemp
			SELECT DISTINCT DM.Id AS DivisionId
			FROM sSetup.tDivisionMaster DM
				INNER JOIN sSetup.tClassMaster CM ON CM.Id=DM.ClassId
				INNER JOIN sSecurity.tUserAccess U ON U.SourceId = DM.Id AND U.SourceTypeId= 2005
				INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=CM.OrgId
			WHERE  UserId = @rUserId
		END

		SELECT
			SGP.Id,
			vSA.Code,
			vSA.FirstName+' '+vSA.MiddleName+' '+vSA.LastName AS Name,
			VSA.ClassName+' - '+VSA.DivisionName AS Class,
			SGP.AcademicId,
			ISNULL(SGP.RelationshipId,0) AS RelationshipId,
			RM.Title AS Relationship,
			SGP.Relation,
			SGP.VisitorName,
			ISNULL(SGP.VisitorMobile,0) As VisitorMobile,
			SGP.ReasonOfGatePass,
			--(CASE  WHEN @rIsPrintView=1 THEN SGP.VisitorPhoto
			--	ELSE ISNULL(SGP.VisitorPhoto, CONVERT(VARBINARY(MAX), 0)) END) AS VisitorPhoto,
			CASE 
				WHEN @rIsPrintView = 1 THEN 
					CASE 
						WHEN ISNULL(DATALENGTH(SGP.VisitorPhoto), 0) > 4 THEN SGP.VisitorPhoto
						ELSE NULL  -- -- Add DATALENGTH Condition Report not open if VisitorPhoto = 0x00000000		MantisId : 0042932
					END
				ELSE 
					ISNULL(SGP.VisitorPhoto, CONVERT(VARBINARY(MAX), 0))
			END AS VisitorPhoto,
			--ISNULL(SGP.VisitorPhoto, CONVERT(VARBINARY(MAX), 0)) AS VisitorPhoto,
			ISNULL(SGP.GatePassDate,'') As GatePassDate,
			ISNULL(SGP.ReturnGatePassDate,'') As ReturnGatePassDate,
			ISNULL(SGP.GatePassTime,'') As GatePassTime,
			ISNULL(SGP.ReturnGatePassTime,'') As ReturnGatePassTime,
			ISNULL(SGP.EntryModeStatusId,0) AS EntryModeStatusId,
			ISNULL(SM.Title,'')  AS EntryModeStatus,
			OM.Id AS OrgId,
			OM.OrgLogo,
			OM.DisplayTitle AS Organization,
			(CASE  WHEN @rIsPrintView=1 THEN SI.StudentPhoto
				ELSE ISNULL(SI.StudentPhoto, CONVERT(VARBINARY(MAX), 0)) END) AS StudentPhoto,

			(CASE  WHEN @rIsPrintView=1 THEN SI.FatherPhoto
				ELSE ISNULL(SI.FatherPhoto, CONVERT(VARBINARY(MAX), 0)) END) AS FatherPhoto,

			(CASE  WHEN @rIsPrintView=1 THEN SI.MotherPhoto
				ELSE ISNULL(SI.MotherPhoto, CONVERT(VARBINARY(MAX), 0)) END) AS MotherPhoto,

			(CASE  WHEN @rIsPrintView=1 THEN SI.RelativePhoto
				ELSE ISNULL(SI.RelativePhoto, CONVERT(VARBINARY(MAX), 0)) END) AS RelativePhoto,

			--ISNULL(SI.StudentPhoto, CONVERT(VARBINARY(MAX), 0)) AS StudentPhoto,
			ISNULL(U.DisplayTitle,'') AS UserName,
			vSA.SUId,
			Remark,
			@GatePassConfig AS ConfigValue,
			SF.FatherContactNo,
			SF.MotherContactNo,
			SF.RelativeContactNo,
			SF.FatherName,
			SF.MotherName,
			SF.RelativeName,
			ISNULL(SGP.GatePassNo,'') AS GatePassNo,	--mantis: 39477, change ISNULL(SGP.GatePassNo,0) => ISNULL(SGP.GatePassNo,'')
		    --added by megha for 0027081
			CONVERT(VARCHAR, ISNULL(SGP.GatePassTime,''), 100) AS GatePassTime_12hours,
			(CASE WHEN @GatePassConfig='Image' THEN					--Add For 27089 mantis
				OI.CertificateHeaderA4
				ELSE NULL END) AS CertificateHeaderA4,
			ISNULL(SC.StudentContactNo,'') AS StudentContactNo
		FROM
		    sStudent.vStudentAcademic vSA
			INNER JOIN sFrontOffice.tStudentGatePass SGP ON SGP.AcademicId = vSA.AcademicId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=vSA.OrgId
			INNER JOIN sCommon.tRelationshipMaster RM ON RM.Id=SGP.RelationshipId
			INNER JOIN sCommon.tStatusMaster SM ON SM.Id=SGP.EntryModeStatusId
			INNER JOIN sSecurity.tUserOrganization UO ON UO.OrgId = SGP.OrgId AND UO.UserId = @rUserId
			LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId=vSA.StudentId
			LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId = SI.StudentId
			LEFT JOIN sSecurity.tUser U	ON U.Id=SGP.CreatedUserId
			LEFT JOIN sSetup.tOrgImages OI ON OI.OrgId = vSA.OrgId			--Add For 27089 mantis
			LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId = SI.StudentId
			INNER JOIN #DivisionTemp TempDiv On TempDiv.DivisionId= vSA.DivisionId

		WHERE
			((SGP.Id=@rId) OR (@rId=0))
			AND ((SGP.OrgId=@rOrgId) OR (@rOrgId=0))
			AND ((SGP.GatePassDate>=@rFromGatePassDate) OR (ISNULL(@rFromGatePassDate,'')=''))
			AND ((SGP.GatePassDate<=@rToGatePassDate) OR (ISNULL(@rToGatePassDate,'')=''))
			AND ((SGP.EntryModeStatusId=@rEntryModeStatusId) OR (@rEntryModeStatusId=0))
			AND ((vSA.Code=@rCode) OR (ISNULL(@rCode,'')=''))
			AND (OM.OrgGroupId=@rOrgGroupId)
			AND ((vSA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
			AND ((vSA.ClassId=@rClassId) OR (@rClassId=0))
			AND ((vSA.DivisionId=@rDivisionId) OR (@rDivisionId=0))
			--AND vSA.IsActiveBatch=1
			ORDER BY SGP.GatePassDate,SGP.GatePassTime DESC
	END

	--mantis: 39477, add below select for the rdlc report of the studentgatepass because when we replace the dataset then it will give an error of temp table
	--SELECT
	--	0 AS Id,
	--	'' AS Code,
	--	'' AS Name,
	--	'' AS Class,
	--	CONVERT(bigint,0) AS AcademicId,
	--	CONVERT(tinyint,0) AS RelationshipId,
	--	'' AS Relationship,
	--	'' AS Relation,
	--	'' AS VisitorName,
	--	'' AS VisitorMobile,
	--	'' AS ReasonOfGatePass,
	--	CONVERT(VARBINARY(MAX), '0x') AS VisitorPhoto,
	--	CONVERT(date,'') AS GatePassDate,
	--	CONVERT(date,'') AS ReturnGatePassDate,
	--	CONVERT(TIME,'') AS GatePassTime,
	--	CONVERT(TIME,'') As ReturnGatePassTime,
	--	CONVERT(smallint,0) AS EntryModeStatusId,
	--	''  AS EntryModeStatus,
	--	CONVERT(smallint,0) AS OrgId,
	--	CONVERT(VARBINARY(MAX), '0x') AS OrgLogo,
	--	'' AS Organization,
	--	CONVERT(VARBINARY(MAX), '0x') AS StudentPhoto,
	--	CONVERT(VARBINARY(MAX), '0x') AS FatherPhoto,
	--	CONVERT(VARBINARY(MAX), '0x') AS MotherPhoto,
	--	CONVERT(VARBINARY(MAX), '0x') AS RelativePhoto,
	--	'' AS UserName,
	--	'' AS SUId,
	--	'' AS Remark,
	--	'' AS ConfigValue,
	--	'' AS FatherContactNo,
	--	'' AS MotherContactNo,
	--	'' AS RelativeContactNo,
	--	'' AS FatherName,
	--	'' AS MotherName,
	--	'' AS RelativeName,
	--	'' AS GatePassNo,
	--	'' AS GatePassTime_12hours,
	--	CONVERT(VARBINARY(MAX), '0x') AS CertificateHeaderA4,
	--	'' AS StudentContactNo
END
GO
PRINT N'Altering Procedure [sFrontOffice].[pStudentGatePassUserControlStudentSearchGet]...';


GO
ALTER PROCEDURE [sFrontOffice].[pStudentGatePassUserControlStudentSearchGet]
	 
	@rClassId int=0,
	@rDivisionId int=0,
	@rRollNo int=NULL,
	@rOrgId int,
	@rCode nvarchar(20),
	@rStatusId smallint=0,
	@rFirstName nvarchar(100)='',
	@rLastName nvarchar(100)='',
	@rBatchId int = 0,
	@rOrgGroupBatchId int = 0,
	@rSUId nvarchar(50)='',
	@rUserId Bigint = 0

	
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON			 

BEGIN 	 
BEGIN
	SET @rFirstName = sCommon.fSearchStringGet(@rFirstName)
	SET @rLastName = sCommon.fSearchStringGet(@rLastName)
END
	
	DECLARE @lOrgGroupId int=0
	DECLARE @lConfigValue nvarchar(50), @lIsStudentCommonSearchBatchWise nvarchar(50)
	DECLARE @lIsInContext bit=0

	--Get Configuration value OrgGroup wise -- 0037540
	SELECT @lOrgGroupId = OGBM.OrgGroupId FROM sSetup.tBatchMaster BM INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id = BM.OrgGroupBatchId WHERE BM.Id=@rBatchId
	SELECT @lIsStudentCommonSearchBatchWise = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 508 AND SourceTypeId = 2010 AND SourceId = @lOrgGroupId	
	SELECT @lConfigValue = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 480 AND SourceTypeId = 2010 AND SourceId = @lOrgGroupId

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

		CREATE TABLE #DivisionTemp
		(
			DivisionId int
		);

		DECLARE @lStudentGatePassEntryBasedOn nvarchar(50)=''
		SELECT @lStudentGatePassEntryBasedOn = ItemValue From sConfig.tConfigurationSetup
		WHERE ConfigurationId = 591 AND SourceId = @lOrgGroupId
		DECLARE @lTeacherId bigint=0;
		SELECT @lTeacherId=SourceId From sSecurity.tUser Where Id=@rUserId AND SourceTypeId=95 

			IF(@lStudentGatePassEntryBasedOn = 'Class Teacher') 
				BEGIN
					INSERT INTO #DivisionTemp
					SELECT DISTINCT DM.Id AS DivisionId
					FROM sSetup.tClassMaster CM INNER JOIN sSetup.tDivisionMaster DM ON DM.ClassId = CM.Id 
					INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=CM.OrgId 
					WHERE DM.InchargeemployeeID=@lTeacherId   AND OM.OrgGroupId=@lOrgGroupId    
				END
			ELSE IF(@lStudentGatePassEntryBasedOn = 'Class Teacher Batch')
				BEGIN
					INSERT INTO #DivisionTemp
					SELECT DISTINCT  DM.Id AS DivisionId
					FROM sSetup.tClassMaster CM INNER JOIN sSetup.tDivisionMaster DM ON DM.ClassId = CM.Id 
					INNER JOIN sSetup.tDivisionInchargeEmployee DIE ON DIE.DivisionId = DM.Id
					INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=CM.OrgId 
					WHERE DIE.EmployeeId=@lTeacherId   AND OM.OrgGroupId=@lOrgGroupId   AND DIE.BatchId = @rBatchId
				END
			ELSE IF(@lStudentGatePassEntryBasedOn = 'Academic Setup')
				BEGIN
					INSERT INTO #DivisionTemp
					SELECT DISTINCT DivisionId
					 FROM sAcademic.vTeacherSubjectDivision  TSD INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=TSD.OrgId   
					 WHERE  TSD.EmployeeId= @lTeacherId
				END
			ELSE IF(@lStudentGatePassEntryBasedOn = 'User Access')
				BEGIN
					INSERT INTO #DivisionTemp
					SELECT DISTINCT DM.Id AS DivisionId
					FROM sSetup.tDivisionMaster DM INNER JOIN sSetup.tClassMaster CM ON CM.Id=DM.ClassId INNER JOIN sSecurity.tUserAccess U ON U.SourceId = DM.Id AND U.SourceTypeId= 2005
					INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=CM.OrgId   WHERE  UserId = @rUserId
				END
	
	IF (@lIsStudentCommonSearchBatchWise = 'True')
	BEGIN
		IF(@rRollNo IS NULL)  
		BEGIN  
			SELECT   
			  SA.AcademicId,  
			  SA.StudentId,  
			  SA.FirstName,  
			  SA.LastName,  
			  SA.MiddleName,  
			  SA.Name, 
			  [sStudent].[fStudentNameGet](SA.FirstName , SA.MiddleName, SA.LastName,OM.StudentNameFormatId ) AS FullName,  -- Add for Mantis Id:0036025
			  SA.Code,  
			  SA.ClassId,  
			  SA.ClassName,  
			  SA.DivisionId,  
			  SA.DivisionName,  
			  SA.Number,  
			  SA.RollNo,  
			  SA.StatusId,  
			  SA.StatusName,  
			  SA.OrgId,  
			  ISNULL(SA.AdmissionCategoryId,0) AS AdmissionCategoryId,  
			  SA.BatchId,  
			  SA.SUId,  
			  ISNULL(So.GenderId,0) AS GenderId,
			  ISNULL(SC.ParentContactNo,'') AS ParentContactNo,
			  SA.FeesRemark 
			   
			 FROM   sStudent.vStudentAcademic SA 
				INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SA.OrgId 
			    LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId=SA.StudentId  
				LEFT JOIN sStudent.tStudentCommunication SC ON SA.StudentId = SC.StudentId
				INNER JOIN #DivisionTemp TempDiv On TempDiv.DivisionId= SA.DivisionId
			 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 ( OrgGroupBatchId = @rOrgGroupBatchId or @rOrgGroupBatchId = 0)   
			 AND(SA.BatchId=@rBatchId or @rBatchId = 0)  
			 AND((SA.SUId=@rSUId) OR (ISNULL(@rSUId,'') = ''))  
			 
			ORDER BY SA.ClassId,SA.DivisionId,SA.RollNo  
		END  
		ELSE  
		BEGIN  
			SELECT   
			  SA.AcademicId,  
			  SA.StudentId,  
			  SA.FirstName,  
			  SA.LastName,  
			  SA.MiddleName,  
			  SA.Name,  
			  [sStudent].[fStudentNameGet](SA.FirstName , SA.MiddleName, SA.LastName,OM.StudentNameFormatId ) AS FullName, 
			  SA.Code,  
			  SA.ClassId,  
			  SA.ClassName,  
			  SA.DivisionId,  
			  SA.DivisionName,  
			  SA.Number,  
			  SA.RollNo,  
			  SA.StatusId,  
			  SA.StatusName,  
			  SA.OrgId,
			  ISNULL(SA.AdmissionCategoryId,0) AS AdmissionCategoryId ,  
			  SA.SUId,  
			  ISNULL(So.GenderId,0) AS GenderId,
			  ISNULL(SC.ParentContactNo,'') AS ParentContactNo, 
			  SA.FeesRemark

			 FROM  sStudent.vStudentAcademic SA      
				INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SA.OrgId 
			    LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId=SA.StudentId           
				LEFT JOIN sStudent.tStudentCommunication SC ON SA.StudentId = SC.StudentId
				INNER JOIN #DivisionTemp TempDiv On TempDiv.DivisionId= SA.DivisionId
			 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 ( OrgGroupBatchId = @rOrgGroupBatchId or @rOrgGroupBatchId = 0)   
			 AND(SA.BatchId=@rBatchId or @rBatchId = 0) 
			 AND((SA.SUId=@rSUId) OR (ISNULL(@rSUId,'') = ''))    
			 
			ORDER BY SA.ClassId,SA.DivisionId,SA.RollNo  
		END  
	END

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

		IF(@rRollNo IS NULL)
		BEGIN
			SELECT 
				SA.AcademicId,
				SA.StudentId,
				SA.FirstName,
				SA.LastName,
				SA.MiddleName,
				SA.Name,
				[sStudent].[fStudentNameGet](SA.FirstName , SA.MiddleName, SA.LastName,OM.StudentNameFormatId ) AS FullName, 
				SA.Code,
				SA.ClassId,
				SA.ClassName,
				SA.DivisionId,
				SA.DivisionName,
				SA.Number,
				SA.RollNo,
				SA.StatusId,
				SA.StatusName,
				SA.OrgId,
				ISNULL(SA.AdmissionCategoryId,0) AS AdmissionCategoryId,
				SA.BatchId,
				SA.SUId,
				ISNULL(So.GenderId,0) AS GenderId,
				ISNULL(SC.ParentContactNo,'') AS ParentContactNo,
				SA.FeesRemark
		
			FROM sStudent.vStudentAcademic SA
				INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SA.OrgId
				INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId AND SA.OrgGroupBatchId = BM.OrgGroupBatchId 
	            LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId=SA.StudentId	            
				LEFT JOIN sStudent.tStudentCommunication SC ON SA.StudentId = SC.StudentId
				INNER JOIN #DivisionTemp TempDiv On TempDiv.DivisionId= SA.DivisionId
			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.SUId=@rSUId) OR (ISNULL(@rSUId,'') = ''))
				AND BM.IsInContext = @lIsInContext
	
			ORDER BY SA.ClassId,SA.DivisionId,SA.RollNo
		END

		ELSE
		BEGIN
			SELECT 
					SA.AcademicId,
					SA.StudentId,
					SA.FirstName,
					SA.LastName,
					SA.MiddleName,
					SA.Name,
					[sStudent].[fStudentNameGet](SA.FirstName , SA.MiddleName, SA.LastName,OM.StudentNameFormatId ) AS FullName, 
					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.SUId,
					ISNULL(So.GenderId,0) AS GenderId,
					SA.FeesRemark 
					
			FROM  sStudent.vStudentAcademic SA
				INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SA.OrgId   
				INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId AND SA.OrgGroupBatchId = BM.OrgGroupBatchId  
		        LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId=SA.StudentId 
				INNER JOIN #DivisionTemp TempDiv On TempDiv.DivisionId= SA.DivisionId
			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.SUId=@rSUId) OR (ISNULL(@rSUId,'') = '')) 
					AND BM.IsInContext = @lIsInContext
			ORDER BY SA.ClassId,SA.DivisionId,SA.RollNo
		END
	END
END
GO
PRINT N'Altering Procedure [sFrontOffice].[pVisitorLogGet]...';


GO
ALTER PROCEDURE [sFrontOffice].[pVisitorLogGet]
          
           @rVisitorId int=0,
           --@rOutTimeFrom datetime,
           --@rOutTimeTo datetime,
           @rFromVisitDate datetime,
           @rToVisitDate datetime,
           @rOrgId int=0,
           @rWhomToMeetName nvarchar(100)='',
           @rIsPrintView bit=0,
           @rOrgGroupId int=0,
           @rTypeId int=0 ,
		   @rStatusId int=0, 
           --@rIsWildCardSearch bit
		   @rVisitorName nvarchar(100)='' --Added for mantis : 36642
          
AS
SET NOCOUNT ON

		--IF @rIsWildCardSearch = 1
		--BEGIN
			SET @rWhomToMeetName = sCommon.fSearchStringGet(@rWhomToMeetName)
		--END
		Declare @GatePassConfig nvarchar(20)=''
		SELECT @GatePassConfig =ItemValue From sConfig.tConfigurationSetup WHERE ConfigurationId = 241 AND SourceId = @rOrgGroupId


BEGIN
SELECT  
	   VL.Id As VisitorId,
       VL.VisitorName,
       VL.NoOfVisitor,
       VL.PurposeOfVisit,
       VL.WhomToMeet AS WhomToMeetId,
	   (isnull(case when isnull(VL.WhomToMeet,0)!=0 then isnull(EM.EmployeeName,'') else ISNULL(VL.WhomToMeetName,'') end,'' )
	   --+ (case when isnull(VL.StudentId,0)!=0 AND isnull(VL.WhomToMeet,0)!=0 then ',' else '' end)
	   --+isnull(case when  isnull(VL.StudentId,0)!=0 Then sStudent.fStudentNameGet(STM.FirstName, STM.MiddleName,STM.LastName, OM1.StudentNameFormatId) end,'')
	   ) AS WhomToMeetName,
	   ISNULL(VL.InTime,'00:00') AS InTime,
       ISNULL(VL.OutTime,'00:00') AS OutTime,
       ISNULL(VL.VisitDate,'1900-01-01 00:00:00') AS VisitDate,
       --VL.CreatedDateTime ,
       (CASE  WHEN @rIsPrintView=1 THEN 
				VL.VisitorPhoto		
			ELSE ISNULL(VL.VisitorPhoto, CONVERT(VARBINARY(MAX), 0)) END) AS VisitorPhoto,
       --ISNULL(VL.VisitorPhoto, CONVERT(VARBINARY(MAX), 0)) AS VisitorPhoto,
       VL.OrgId,
       ISNULL(OM.DisplayTitle,'') AS Organization,
       ISNULL(Remark,'') AS Remark,
       @GatePassConfig AS ConfigValue,
	   ISNUll(VisitorContactNumber,'') AS VisitorContactNumber,
	   ISNULL(STM.Id,0) AS StudentId,
	   ISNULL(VTM.Title, '') AS VisitorType,
	   --(CASE WHEN ISNULL(VL.TypeId,'')!='' then case when VL.TypeId=1 then 'Visitor' else 'Parents' end
			 --when ISNULL(VL.StudentId,0)=0 THEN 'Visitor'
			 --ELSE 'Parents' END) AS VisitorType,
	   (CASE WHEN ISNULL(VL.OutTime,'00:00:00')='00:00:00' THEN 0
			 ELSE 1 END) AS InOutStatus,
		OM.OrgGroupId AS OrgGroupId,
		SM.Title as Status,
		ISNULL(VL.StatusId,0) as StatusId,
		ISNULL(VL.TypeId, 0) AS VisitorTypeId,
		--(CASE WHEN ISNULL(VL.TypeId,'')!='' then case when VL.TypeId=1 then 1 else 2 end
		--	 when ISNULL(VL.StudentId,0)=0 THEN 1
		--	 ELSE 2 END) AS VisitorTypeId,
		ISNULL(STM.Code,'') AS StudentCode,
		ISNULL(STM.FirstName,'') +' '+ ISNULL(STM.LastName,'') AS  StudentName,
		 (select ISNULL(CM.Title,'') from sSetup.tClassMaster CM Inner join sStudent.tAcademic A ON A.ClassId=CM.Id AND A.StudentId=STM.Id INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId AND BM.IsActive=1 GROUP BY CM.Title) AS StudentClass
		,(select ISNULL(DM.Title,'') from sSetup.tDivisionMaster DM Inner join sStudent.tAcademic A ON A.DivisionId=DM.Id AND A.StudentId=STM.Id INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId AND BM.IsActive=1 GROUP BY DM.Title) AS StudentDivision
		--ISNULL(CM.Title,'') AS StudentClass,
		--ISNULL(DM.Title,'') AS StudentDivision
		,ISNULL(VL.VisitorName,'') AS VisitorName --Added for mantis : 36642
		,OI.CertificateHeaderA4		--Mantis - 43061
		 		
  FROM  sFrontOffice.tVisitorLog VL 
  INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=VL.OrgId
  LEFT JOIN sCommon.tStatusMaster SM ON SM.Id = VL.StatusId
  LEFT JOIN sHrm.vExtEmployeeMaster EM ON EM.EmployeeId=VL.WhomToMeet
  LEFT JOIN sStudent.tStudentMaster STM On STM.Id=VL.StudentId  
  --LEFT JOIN sStudent.tAcademic A ON A.StudentId = STM.Id
  --LEFT JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId AND BM.IsActive=1
  --LEFT JOIN sSetup.tClassMaster CM ON CM.Id = A.ClassId
  --LEFT JOIN sSetup.tDivisionMaster DM ON DM.Id = A.DivisionId
  LEFT JOIN sSetup.tOrganizationMaster AS OM1 ON STM.OrgId = OM1.Id 
  LEFT JOIN [sFrontOffice].[tVisitorTypeMaster] AS VTM ON VTM.Id = VL.TypeId 
  LEFT JOIN sSetup.tOrgImages OI ON OI.Orgid = OM.Id
 
  WHERE 
	(VL.OrgId=@rOrgId OR @rOrgId=0) AND OM.OrgGroupId=@rOrgGroupId
	AND (VL.Id=@rVisitorId OR @rVisitorId=0)
	AND (((VL.WhomToMeetName LIKE @rWhomToMeetName) OR  (isnull(EM.EmployeeId,0)>0 AND EM.EmployeeName Like  @rWhomToMeetName) OR (isnull(STM.Id,0)>0 AND sStudent.fStudentNameGet(STM.FirstName, STM.MiddleName,STM.LastName, OM1.StudentNameFormatId) like  @rWhomToMeetName)) OR (ISNULL(@rWhomToMeetName,'')=''))
	AND (VL.VisitDate>=@rFromVisitDate OR ISNULL(@rFromVisitDate,'')='')
	AND (VL.VisitDate<=@rToVisitDate OR ISNULL(@rToVisitDate,'')='')
	--AND ((ISNULL(VL.TypeId,0)=0 AND (ISNULL(VL.StudentId,1) = @rTypeId) OR  (@rTypeId=0) OR (((VL.StudentId > 0 AND @rTypeId=2) OR  @rTypeId=0)))  OR (ISNULL(VL.TypeId,0)!=0 AND ((VL.TypeId=@rTypeId) or (@rTypeId=0)))) -- Visitor 
	AND ((VL.TypeId = @rTypeId) OR (@rTypeId = 0))
	AND ((VL.StatusId = @rStatusId) OR (ISNULL(@rStatusId,0) = 0)) 
	--AND BM.IsActive=1
	 -- Parents
	 AND ((VL.VisitorName LIKE '%' + @rVisitorName + '%') OR (ISNULL(@rVisitorName,'')='')) --Added for mantis : 36642
  ORDER BY VL.VisitDate DESC,VL.InTime DESC
END
GO
PRINT N'Altering Procedure [sHrm].[pRptEmployeeLeaveDetailsGet]...';


GO
ALTER PROCEDURE [sHrm].[pRptEmployeeLeaveDetailsGet]
	 
	@rBuilder1 nvarchar(max)='',
	@rBuilder2 nvarchar(max)='',
	@rEmployeeName nvarchar(200)='',
	@rEmployeeCode nvarchar (200),
	@rEmployeeId bigint=0,
	@rDepartmentId int=0,
	@rEmployeeGradeId int=0,
	@rForYear  smallint='',
	@rForMonth tinyint='',
	@rBatchId int,
	@rOrgId int,
	@rFromDate date,
	@rToDate date,
	@rLeaveReson nvarchar(100)='',
	@rStatusId int=0,
	@rEmployeeStatusId int = 0 ,
	@rLeaveTypeId 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(AT.LWP,0) AS LWP,
				 --CONVERT(INT,(ISNULL(AT.TotalWorkingDays,0) - ISNULL(AT.LWP,0))) AS PresentDays,
				 --MM.Title AS MonthName,
		   --      (SELECT  t1.MonthTitle FROM (SELECT MonthTitle,MonthNumber FROM [sSetup].[fMonthYearForBatchGet] (100100001))  AS T1
				 --WHERE MonthNumber = 4) AS MonthName,
				 --(SELECT  t2.YearNumber FROM (SELECT YearNumber,MonthNumber FROM [sSetup].[fMonthYearForBatchGet] (100100001))  AS T2
				 --WHERE YearNumber = 2014 AND MonthNumber = 4 ) AS YearName,
				 --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,
				 ISNULL(SM.Title,'') AS StatusName,
				 OM.Title AS OrganizationTitle,
				 ISNULL(OM.StreetOne,'') AS StreetOne,
				 ISNULL(OM.StreetTwo,'')AS StreetTwo,
				 ISNULL(OM.StreetThree,'')AS StreetThree,
				 ISNULL(OM.CityName,'')AS CityName,
				 ISNULL(OM.StateName,'')AS StateName,
				 ISNULL(OM.CountryName,'')AS CountryName,
				 ISNULL(OM.ZipCode,'')AS ZipCode,
				 ISNULL(EM.EmployeeDesignation,'')AS EmployeeDesignation ,
				 ISNULL(LM.BalanceLeave,0) AS TotalLeave ,
				 ISNULL(EC.MobileNumber,'')AS MobileNumber,
				 ISNULL((SELECT    
						SUM(NoOfLeave) AS UsedLeave
					FROM 
						sHrm.tLeave L1  
					WHERE 
						(L1.EmployeeId = EM.EmployeeId) 
						AND (L1.LeaveTypeId = L.LeaveTypeId)      
						AND BatchId = @rBatchId AND L.OrgId = @rOrgId 
						AND L1.StatusId = 550 -- apporved
						GROUP BY L1.EmployeeId,L1.LeaveTypeId),0) AS UsedLeave, -- Mantis : 0027600
				L.Id AS LeaveId		-- MantisId : 0035002
				,ISNULL(EI.EmployeeSign,0x) AS EmployeeSign-- add for mantis : 0042373	

        FROM 
				sHrm.vEmployeeCommonDetail EM 
		--LEFT JOIN sHrm.tEmployeeAttendance AT ON AT.EmployeeId=EM.EmployeeId
		--LEFT JOIN sCommon.tMonthMaster MM ON MM.Id=AT.ForMonth
		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
		LEFT JOIN sCommon.tStatusMaster SM ON SM.Id = L.StatusId
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = EM.OrgID
		--INNER JOIN sHrm.tLeaveBalance LM ON LM.EmployeeId = EM.EmployeeId 
		LEFT JOIN sHrm.tLeaveBalance LM ON LM.EmployeeId = EM.EmployeeId AND LM.BatchId = L.BatchId AND LM.LeaveTypeId = L.LeaveTypeId
		LEFT JOIN sHrm.tEmployeeCommunications EC ON EC.EmployeeId = EM.EmployeeId
		LEFT JOIN sHrm.tEmployeeImages EI ON EI.EmployeeId = EM.EmployeeId -- add for mantis : 0042373	
    	WHERE 
    	EM.OrgID = @rOrgId 
    	AND L.BatchId=@rBatchId
    	AND (YEAR(L.FromDate) = @rForYear OR @rForYear='') 
    	AND (MONTH(L.FromDate) = @rForMonth OR @rForMonth='') 
    	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 ((L.FromDate>=@rFromDate) OR (ISNULL(@rFromDate,'')=''))
    	AND ((L.ToDate<=@rToDate) OR (ISNULL(@rToDate,'')=''))
    	AND ((L.LeaveReason Like '%'+@rLeaveReson+'%' ) OR (ISNULL(@rLeaveReson,'')=''))
    	AND ((L.StatusId=@rStatusId) OR (@rStatusId=0))
    	AND ((EM.EmployeeStatusId=@rEmployeeStatusId) OR (@rEmployeeStatusId=0))
		AND ((LM.LeaveTypeId=@rLeaveTypeId) OR (@rLeaveTypeId=0))
	ORDER BY L.FromDate DESC
END
GO
PRINT N'Altering Procedure [sHrm].[pRptJoiningCertificateGet]...';


GO

ALTER PROCEDURE [sHrm].[pRptJoiningCertificateGet]  
 
  @rEmployeeId [bigint]= 0, 
  @rBuilder1 nvarchar(max)='',  
  @rBuilder2 nvarchar(max)='',    
  @rOrgId smallint,  
  @rCode nvarchar(20)='',  
  @rFromNo int=0,  
  @rToNo int=0,  
  @rFromDate date='',  
  @rToDate date='',  
  @rName nvarchar(20)='',
  @rBatchName nvarchar(100)='' --added for mantis - 37085
  ,@rPrintTemplateId int = 0

WITH EXECUTE AS CALLER  
AS  
SET NOCOUNT ON  
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED  
  
BEGIN  
DECLARE @lIsOnPrePrinted bit = 0  
  
DECLARE @lConfigValue nvarchar(50)  
DECLARE @lIsDisplayImageHeader bit=0  

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

SELECT @lConfigValue = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 182 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  
   @rBuilder1 AS Builder1,  
   @rBuilder2 AS Builder2,  
   EM.Id AS EmployeeId,
   CJ.Number,
   EM.EmployeeName,
   EM.FirstName,  
   EM.MiddleName,  
   EM.LastName,      
   EM.Code,    
   EM.ShortName,  
   EM.OrgID,  
   EM.DepartmentId,  
   EM.DepartmentName,  
   EM.DesignationId,  
   EM.Designation,  
   EM.EmployeePhoto, 
   EM.DateOfJoining, 
   @lIsOnPrePrinted AS IsOnPrePrinted,  
   @lIsDisplayImageHeader AS IsDisplayImageHeader,  
   OI.CertificateHeaderA4 ,  
   CJ.Remark,  
   ISNULL(CJ.CertificateDate,'') AS CertificateDate,  
   EM.MaritalStatusId,  
   CJ.PayScale,  
   CJ.AgreementPeriod,
   CJ.CertificateRemark,
   OM.Title As OrgTitle,
   CJ.CreatedDateTime As CreatedDateTime,
   U.DisplayTitle As UserDisplayName,
   EDM.Title AS EmployeeDesignation,
   OM.DisplayTitle As ShortTitle,
   DM.Title AS DepartmentName1,
   EM.MobileNumber,
   --EC.PresentStreetOne+'-'+EC.PresentStreetTwo+ '-' +EC.PresentStreetThree AS LocalAddress,
    EC.PresentStreetOne  + CASE WHEN EC.PresentStreetOne = '' OR (EC.PresentStreetTwo = '' AND EC.PresentStreetThree = '') Then '' ELSE '-' END 
   		    + EC.PresentStreetTwo + CASE WHEN EC.PresentStreetTwo = '' OR EC.PresentStreetThree = '' Then '' ELSE '-' END	
			+ EC.PresentStreetThree AS LocalAddress,
   --EC.PresentCity+ '-'+EC.PresentState+'-'+EC.PresentZipCode+'-'+EC.PresentContactNo As LocalAddress1,
	EC.PresentCity  + CASE WHEN EC.PresentCity = '' OR (EC.PresentState = '' AND EC.PresentZipCode = '' AND EC.PresentContactNo = '') Then '' ELSE '-' END 
		+ EC.PresentState + CASE WHEN EC.PresentState = '' OR (EC.PresentZipCode = '' AND EC.PresentContactNo = '') Then '' ELSE '-' END	
		+ EC.PresentZipCode + CASE WHEN EC.PresentZipCode = '' OR EC.PresentContactNo = '' Then '' ELSE '-' END
		+ EC.PresentContactNo AS LocalAddress1,
   ISNULL(EDM1.Title,'Admin') AS UserDesignation,
   --Replace(Replace(RTrim(Ltrim(EC.PresentCity +' '+ EC.PresentState +' '+ EC.PresentZipCode)),'  ',' '),' ','-') AS LocalAddress2
   EC.PresentCity  + CASE WHEN EC.PresentCity = '' OR (EC.PresentState = '' AND EC.PresentZipCode = '') Then '' ELSE '-' END 
   		    + EC.PresentState + CASE WHEN EC.PresentState = '' OR EC.PresentZipCode = '' Then '' ELSE '-' END	
			+ EC.PresentZipCode AS LocalAddress2,
	ISNULL(CJ.DateOfJoining,'') As CertificateDateOfJoining,
	EM.GenderId,
	@rBatchName AS BatchName --added for mantis - 37085
	,[sHrm].[fEmployeeJoiningCertificateTemplate](EM.EmployeeId,@lTemplate) AS Template --add for mantis : 42473

 FROM   
        
	  sHrm.tCertificateJoining CJ   
      INNER JOIN [sHrm].[vExtEmployeeMaster] EM  ON EM.EmployeeId=CJ.EmployeeId 
      INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=EM.OrgId   
      INNER JOIN  sSecurity.tUser U ON U.Id=CJ.CreatedUserId 
	  --AND U.SourceTypeId = 95
      INNER JOIN  sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.Id
	  LEFT JOIN  sHrm.tEmployeeDesignationMaster EDM ON EDM.Id=EJD.EmployeeDesignationId  --added
	  INNER JOIN  sSetup.tDepartmentMaster DM ON DM.Id=CJ.DepartmentId
	  LEFT JOIN  sHrm.tEmployeeCommunications EC ON EC.EmployeeId=CJ.EmployeeId  --added
	  LEFT JOIN sSetup.tOrgImages OI ON OI.OrgId = OM.Id 
      LEFT JOIN  sHrm.tEmployeeJobDetail EJD1 ON EJD1.EmployeeId=U.SourceId
	  LEFT JOIN  sHrm.tEmployeeDesignationMaster EDM1 ON EDM1.Id=EJD1.EmployeeDesignationId
 WHERE    
 
    ((EM.Code LIKE @rCode)OR (@rCode = '' ))     
    AND ((EM.EmployeeId = @rEmployeeId) OR (@rEmployeeId = 0))    
    AND ((EM.EmployeeName like @rName) OR (ISNULL(@rName,'') = ''))
    AND ((CJ.Number >= @rFromNo) OR (ISNULL(@rFromNo,0)=0))  
    AND ((CJ.Number <= @rToNo) OR (ISNULL(@rToNo,0)=0))  
    AND ((CJ.CertificateDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))  
    AND ((CJ.CertificateDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))    
    AND  EM.OrgId = @rOrgId
END
GO
PRINT N'Altering Procedure [sMis].[pRptAverageAttendanceClassWise]...';


GO

 
 
ALTER PROCEDURE [sMis].[pRptAverageAttendanceClassWise]
	
		@rBuilder1 nvarchar(max)='',
		@rBuilder2 nvarchar(max)='', 
		--@rBatchId int,
		@rClassId int,
		@rDepartmentId int,
		@rOrgMainGroupId int,
		@rOrgSubGroupId int,
		@rOrgId smallint,
		@rOrgGroupBatchId int,
		@rFromDate Date,
		@rToDate Date,
		@rStrOrgMainGroupId nvarchar(max),
		@rStrOrgSubGroupId nvarchar(max),
		@rStrOrgId nvarchar(max),
		@rStrDepartmentId nvarchar(max),
		@rStrClassId nvarchar(max),
		@rOrgGroupId int,
		@rIsTestMainGroup bit =0,
		@rIsTestSubGroup bit =0,
		@rIsTestOrg bit=0,
		@rIsTestClass bit=0,
		@rIsTestDepartment bit=0,
		@rIsDisplayOrgGroup bit=0,
		@rBatchGroupId int=0,
		@rStatusId int=0,
		@rStudentStatusId int=0,
		@rIsDisplayGender bit = 0,
		@rIsTestDivision bit = 0,		-- Mantis Id : 0042610
		@rDivisionId int = 0,
		@rStrDivisionId nvarchar(max) = ''
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
	SELECT 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			@rIsTestMainGroup AS IsTestMainGroup,
			@rIsTestSubGroup AS IsTestSubGroup,
			@rIsTestOrg AS IsTestOrg,
			@rIsTestClass AS IsTestClass,
			@rIsTestDepartment AS IsTestDepartment,
			@rIsDisplayOrgGroup AS IsDisplayOrgGroup,
			CM.Id AS ClassId,
			CM.DisplayTitle AS ClassName,
			CM.OrderIndex,
			CM.DepartmentId,
			DM.DisplayTitle AS DepartmentName,
			OMGM.Id AS OrgMainGroupId,
			OMGM.Title AS OrgMainGroupTitle,
			OSGM.Id AS OrgSubGroupId,
			OSGM.Title AS OrgSubGroupTitle,
			OM.Id AS OrgId,
			OM.DisplayTitle AS OrgDisplayTitle,
			@rIsDisplayGender AS IsDisplayGender,
			
			(select ISNULL(count(1),0) from sAttendance.tStudentRegister SR
					INNER JOIN sStudent.tAcademic A ON SR.AcademicId = A.Id 
					--INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId AND BM.IsActive = 1	
					INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId AND BM.IsActive = @rStatusId
					LEFT JOIN sSetup.tBatchGroupMaster BGM ON BGM.Id=Bm.batchGroupId AND ((BGM.Id=@rBatchGroupId) OR (@rBatchGroupId=0))
					INNER JOIN sStudent.tStudentMaster SM ON SM.Id=A.StudentId
					INNER JOIN sStudent.tStudentOther SO ON SO.StudentId = SM.Id 
					WHERE CM.Id = A.ClassId
					AND AttendanceTypeId = 1
					AND SR.IsPresent=1
					AND SR.AttendanceDate >= @rFromDate
					AND SR.AttendanceDate <= @rToDate
					AND BM.IsActive =@rStatusId
					AND ((SM.StatusID=@rStudentStatusId) OR (@rStudentStatusId=0))
					AND A.DivisionId = DivM.Id		-- Mantis Id : 0042610
			) PresentCount,
			(select ISNULL(count(1),0) from sAttendance.tStudentRegister SR
					INNER JOIN sStudent.tAcademic A ON SR.AcademicId = A.Id 
					INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId AND BM.IsActive = @rStatusId
					LEFT JOIN sSetup.tBatchGroupMaster BGM ON BGM.Id=Bm.batchGroupId AND ((BGM.Id=@rBatchGroupId) OR (@rBatchGroupId=0))
					INNER JOIN sStudent.tStudentMaster SM ON SM.Id=A.StudentId
					INNER JOIN sStudent.tStudentOther SO ON SO.StudentId = SM.Id 
					WHERE CM.Id = A.ClassId
					AND AttendanceTypeId = 1
					AND SR.IsPresent=0
					AND SR.AttendanceDate >= @rFromDate
					AND SR.AttendanceDate <= @rToDate
					AND BM.IsActive =@rStatusId
					AND ((SM.StatusID=@rStudentStatusId) OR (@rStudentStatusId=0))
					AND A.DivisionId = DivM.Id		-- Mantis Id : 0042610
			) AbsentCount,
			@rIsTestDivision AS IsTestDivision,
			DivM.Id AS DivisionId,
			DivM.OrderIndex AS DivisionOrderIndex,
			DivM.Title AS DivisionName



		FROM 
			sSetup.tClassMaster CM			
			INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id=CM.DepartmentId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = DM.OrgId
			INNER JOIN sSetup.tOrgSubGroupMaster OSGM ON OSGM.Id = OM.OrgSubGroupId
			INNER JOIN sSetup.tOrgMainGroupMaster OMGM ON OMGM.Id = OSGM.OrgMainGroupId
			INNER JOIN sSetup.tDivisionMaster DivM ON DivM.ClassId = CM.Id				-- Mantis Id : 0042610
			
	WHERE 
			
		   ((CM.Id=@rClassId) OR (@rClassId=0))
			AND	((CM.DepartmentId = @rDepartmentId) OR (@rDepartmentId = 0))
			AND ((OMGM.Id=@rOrgMainGroupId) OR (@rOrgMainGroupId=0))
			AND ((OSGM.Id=@rOrgSubGroupId) OR (@rOrgSubGroupId=0))
			AND ((OM.Id=@rOrgId) OR (@rOrgId=0))
			AND ((OM.OrgGroupId = @rOrgGroupId))
			AND (OMGM.Id IN (SELECT cast(item as int) FROM  sCommon.fnsplit(@rStrOrgMainGroupId,','))OR @rStrOrgMainGroupId='')
			AND (OSGM.Id IN (SELECT cast(item as int) FROM  sCommon.fnsplit(@rStrOrgSubGroupId,','))OR @rStrOrgSubGroupId='')
			AND (OM.Id IN (SELECT cast (item as int) FROM  sCommon.fnsplit (@rStrOrgId,','))OR @rStrOrgId='')
			AND (DM.Id IN (SELECT cast(item as int) FROM  sCommon.fnsplit  (@rStrDepartmentId,','))OR @rStrDepartmentId='')
			AND (CM.Id IN (SELECT cast(item as int) FROM  sCommon.fnsplit  (@rStrClassId,','))OR @rStrClassId='') 
			AND (DivM.Id = @rDivisionId OR @rDivisionId = 0)		-- Mantis Id : 0042610
			AND (@rStrDivisionId = '' OR DivM.Id IN (SELECT cast(item as int) FROM  sCommon.fnsplit  (@rStrDivisionId,',')))		-- Mantis Id : 0042610

			ORDER BY CM.OrderIndex ASC


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	
	 @rBatchId int = 0
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN  
	
	DECLARE @lMonthDay int=0
	SELECT @lMonthDay=[sCommon].[fGetDaysInMonth] (@rForMonth,@rForYear)
	
	DECLARE @lFirstDate Date
	DECLARE @lLasteDate Date
	IF(@rForMonth!=0 and @rForYear!=0)
	BEGIN
		SET @lFirstDate = CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'/'+CONVERT(NVARCHAR(2),@rForMonth)+'/01'))
		SET @lLasteDate=DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,@lFirstDate)+1,0))
	END
	
	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,
			(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,
			(CASE WHEN ISNULL(PM.HeaderDisplayId,1) = 3 THEN ISNULL(PM.PayrollHeader,0x) ELSE NULL END) AS PayrollHeader,
			ISNULL(PM.HeaderDisplayId,1)AS HeaderDisplayId,
			ISNULL(ESO.IFSCNumber,'') AS IFSCNumber,
			ISNULL(EPD.AdhaarNumber,'') AS AdhaarNumber,
			EM.DepartmentName, --Mantis : 0029371
			ESO.ESINumber,
			CASE 
				WHEN ISNULL(P.IsEmployeeSpecific,0) = 1
				THEN
					(SELECT PS.Amount 
						FROM sPayroll.tPaySetup PS 
						WHERE PS.PayElementId = P.Id 
						AND (PS.SourceId = tEM.Id AND PS.SourceTypeId = 95) 
						AND PS.PayrollYearId = PP.PayrollYearId)
				ELSE
					(SELECT PS.Amount 
						FROM sPayroll.tPaySetup PS 
						WHERE PS.PayElementId = P.Id 
						AND (PS.SourceId = PPE.PayrollGroupId AND PS.SourceTypeId = 2020) 
						AND PS.PayrollYearId = PP.PayrollYearId) 
			END AS PaySetupAmount,					--MantisId = 0030726
			tEM.CreatedDateTime AS CreatedDateTime, --mantis - 0030732
			[sHrm].[fEmployeeNameGet](tEM.FirstName, tEM.MiddleName, tEm.LastName, OM.EmployeeNameFormatId) AS EmployeeNameFormatWise,	--MantisId = 0030726
			ISNULL(PPR.ChequeNo,'') ChequeNo,	--#Start Mantis Id : 0031036
			PPR.PayDate,
			CASE WHEN ISNULL(PPR.PayTypeId,0) = 0 THEN ISNULL(ESO.PayTypeId,0)
				ELSE ISNULL(PPR.PayTypeId,0) END AS PayTypeId,
			CASE WHEN ISNULL(PPR.PayTypeId,0) = 0 THEN ISNULL(PTM2.Title,'')
				ELSE ISNULL(PTM.Title,'') END AS PayTypeName,	--#End Mantis Id : 0031036
			ESO.RetirementDate AS RetirementDate, --Mantis - 0031406
			PM.Title AS PayrollTitle,				-- Mantis Id : 0032059
			ISNULL(EI.EmployeePhoto,0x) AS EmployeePhoto,               -- Add for mentis : 0034079
			ESO.IncrementDate , --Add for mantis : 0036465

			   --Mantis Start - 43067
			   (
				SELECT TOP 1 ISNULL(WD.TotalDays, 0)
					FROM sHrm.tWorkingDays WD
					WHERE 
						PP.SalaryYear = WD.ForYear
						AND PP.SalaryMonth = WD.ForMonth
						AND WD.EmployeeGradeId = EJD.EmployeeGradeId
						AND (WD.BatchId = @rBatchId OR @rBatchId = 0)
				) AS TotalDays,
			 (
				SELECT TOP 1 ISNULL(EA.TotalWorkingDays, 0) - (ISNULL(EA.LWP, 0) + ISNULL(EA.PaidLeave, 0))
				FROM sHrm.tEmployeeAttendance EA
				WHERE 
					EA.EmployeeId = EM.EmployeeId
					AND PP.SalaryYear = EA.ForYear
					AND PP.SalaryMonth = EA.ForMonth
					AND (EA.BatchId = @rBatchId OR @rBatchId = 0)
			) AS PresentDays
			--Mantis End - 43067

		FROM 
			sPayroll.tPayProcess PP 
			INNER JOIN sPayroll.tPayProcessEmployee PPE ON PPE.PayProcessId = PP.ID 
			INNER JOIN sHrm.vEmployeeCommonDetail EM ON EM.EmployeeId = PPE.EmployeeId 
			INNER JOIN sHrm.tEmployeeMaster tEM ON tEM.Id = PPE.EmployeeId 
			INNER JOIN sPayroll.tPayProcessElement PE ON PE.PayProcessEmployeeId=PPE.ID
			INNER JOIN sPayroll.tPayElement P ON PE.PayElementId=P.ID AND P.IsIncludeInPaySlip = 1
			LEFT JOIN sHrm.tEmployeeStatutoryAndOther ESO ON ESO.EmployeeId=PPE.EmployeeId	
			LEFT JOIN sHrm.tEmployeePersonalDetail EPD ON EPD.EmployeeId=PPE.EmployeeId	
			LEFT JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=PPE.EmployeeId	
			INNER JOIN sCommon.tMonthMaster MM ON MM.Id=PP.SalaryMonth
			INNER JOIN sPayroll.tPayrollYearMaster PY ON PP.PayrollYearId = PY.Id 
			INNER JOIN sPayroll.tPayrollGroupMaster PGM ON PGM.Id = PPE.PayrollGroupId
			LEFT JOIN sCommon.tReportOrgGroup ROG ON ROG.OrgGroupId=PY.OrgGroupId AND (ROG.ReportId = @rReportId OR @rReportId = 0) 
			LEFT JOIN sCommon.tReportRemarkGroupOrg RGO ON RGO.OrgId = tEM.OrgID AND RGO.ReportRemarkGroupId =  4
			LEFT JOIN sPayroll.tPayProcessEmployeeRemark PPR ON PPR.SalaryMonth = PP.SalaryMonth
			AND PPR.SalaryYear = PP.SalaryYear AND PPR.PayrollYearId = PP.PayrollYearId AND  PPR.EmployeeId = PPE.EmployeeId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=tEM.OrgId
			LEFT JOIN sSetup.tOrgImages OI ON OI.OrgId = OM.Id
			INNER JOIN sPayroll.tPayrollMaster PM ON PY.PayrollId = PM.Id
			LEFT JOIN sFinanceCommon.tPayTypeMaster PTM ON PTM.Id = PPR.PayTypeId		--#Start Mantis Id : 0031036
			LEFT JOIN sFinanceCommon.tPayTypeMaster PTM2 ON PTM2.Id = ESO.PayTypeId		--#End Mantis Id : 0031036
			LEFT JOIN sHrm.tEmployeeImages EI ON EI.EmployeeId = tEM.Id                -- Add for mentis : 0034079
		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 ((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 [sProcurement].[pStockIssueReturnDataGet]...';


GO
ALTER PROCEDURE [sProcurement].[pStockIssueReturnDataGet]
	@rNumber [nvarchar](30) = '',
	@rStoreLocationId int
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	SELECT DISTINCT SIR.Id,
		SIR.Number,
		ISNULL(SIR.ReturnedByName,'') AS ReturnedByName,
		SIR.ToStoreLocationId,
		SIR.Remark,
		SIR.StockIssueId,
		SIRB.StockIssueBatchId,
		SIRB.ReturnQuantity,
		SIM.Code AS StockItemCode,
		SIM.Title AS StockItemName,
		SIM.Id AS StockItemId,
		SIB.StockBatchId AS StockBatchId,
		SIR.CreatedUserId,
		SI.Number AS IssueNumber,
		SIRB.ReasonId,
		Sb.Number AS 'StockBatchNumber',
		CASE WHEN SIR.TransactionDate is not null THEN SIR.TransactionDate ELSE SIR.CreatedDateTime END AS TransactionDate,
		(SELECT ISNULL(SUM(SIRB.ReturnQuantity),0) 
		FROM sProcurement.tStockIssueReturn SIR 
			INNER JOIN sProcurement.tStockIssueReturnBatch SIRB ON SIRB.StockIssueReturnId=SIR.Id 
		WHERE SIR.StockIssueId=SI.Id AND SIRB.StockIssueBatchId=SIB.Id) AS ReturnedQuantity,
		SIND.IssuedQuantity AS IssuedQuantity,
		ISNULL(SI.IssueToSourceTypeId,0) AS IssueToSourceTypeId, --mantis: 42319
		ISNULL(SI.IssueToSourceId,0) AS IssueToSourceId --mantis: 42319

	FROM sProcurement.tStockIssueReturn SIR 
		INNER JOIN sProcurement.tStockIssueReturnBatch SIRB ON SIRB.StockIssueReturnId=SIR.Id
		INNER JOIN sProcurement.tStockIssueBatch SIB ON SIB.Id=SIRB.StockIssueBatchId
		LEFT JOIN sProcurement.tStockBatch Sb ON sb.id = SIB.StockBatchId AND sb.Number is not null
		INNER JOIN sProcurement.tStockIssueDetail SIND ON SIND.Id=SIB.StockIssueDetailId
		INNER JOIN sIp.tStockItemMaster SIM ON SIM.Id=SIND.StockItemId
		INNER JOIN sProcurement.tStockIssue SI ON SI.Id=SIR.StockIssueId

	WHERE ((SIR.Number = @rNumber) OR (@rNumber = ''))
		AND SIR.ToStoreLocationId = @rStoreLocationId

END
GO
PRINT N'Altering Procedure [sSecurity].[pDashletGet]...';


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


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

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

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

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

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



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

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

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

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

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

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

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

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

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

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

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

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

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


GO


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

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

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

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


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

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

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

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


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

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

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

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

  SELECT

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

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

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


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

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

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

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


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

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


GO
ALTER PROCEDURE [sStudent].[pRptStudentRegisterGet]
	 
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 @rOrgId smallint,
	 @rBatchId int,
	 @rStrCode nvarchar(max),
	 @rClassId int,
	 @rDivisionId int,
	 @rStudentId bigint,
	 @rFromRollNo int,
	 @rToRollNo int,
	 @rStatusId int,
	 @rClassStatusId int,
	 @rDateOfBirth int,
	 @rDepartmentId int,
	 @rFromAdmissionDate date='', 
     @rToAdmissionDate date='',
     @rFromStudentCode nvarchar(max)='',
     @rToStudentCode nvarchar(max)='',
	 @rFromNumber int = 0,
	 @rToNumber int = 0 ,
	  --Added by dhannajay for mantis : 42884
	 @rFromLeftDate date ='',
	 @rToLeftDate date ='' 
	  --Added by dhannajay for mantis : 42884
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 

	SELECT  
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			SD.AcademicId,
			SD.StudentId, 
			SD.ClassId,
			SD.DivisionId,
			SD.ClassDivision,
			SD.Code,
			SD.RollNo,			
			SD.FirstName,
			SD.MiddleName,			
			SD.LastName,
			SD.Name,		
			SD.ClassName,
			SD.DivisionName,
			SD.StatusName,
			SD.StatusId,
			SD.LCProgress,
			SD.Religion,
			SD.FamilyCast,
			SD.FamilySubCast,
			SD.LCConduct,
			SD.BirthPlace,
			SD.BirthTaluka,
			SD.BirthDistrict,
			SD.LeftDate,
			SD.PreviousSchool,
			SD.DateOfBirth,
			SD.BirthDateInWord,
			SD.LeftReason,
			SD.AdmissionDate,
			SD.AdmissionStandard,
			SD.LeftStandard,
			SD.LCNumber,
			SD.LCDate,
			SD.StudentPhoto,
			SD.BloodGroup,
			SD.PresentAddress,
			SD.ContactNo,
			SD.Batch,
			SD.InactiveDate,
			OM.Title AS OrgName,
			SF.MotherName,
			SD.DivisionOrder,
			SD.Number AS StudentNumber,
			SF.FatherName,
			SD.Nationality,
			SD.MotherTongue,
			SD.BirthState,
			SD.BirthCountry,
			SD.SUId,
            SD.AdhaarNumber,
            SD.ClassStatusId,
            SD.ClassStatusName,
			SD.UIDNumber,
			SD.Gender,
			SF.FatherOfficeContactNo,
			SF.MotherOfficeContactNo,
			SD.ParentContactNo --mantis id : 0035187
			
	FROM 
			sStudent.vStudentAllDetail SD
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=SD.OrgId
			LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId=SD.StudentId
			INNER JOIN sSetup.tBatchClass BC ON BC.ClassID =  SD.ClassID AND BC.BatchId = SD.BatchId AND SD.BatchId= @rBatchId
			--LEFT JOIN sStudent.tStudentAdmission SAM ON SD.StudentId=SAM.StudentId				
			--AND ((SAM.AdmissionDate>=@rFromAdmissionDate)OR(ISNULL(@rFromAdmissionDate,'')=''))    
			--AND ((SAM.AdmissionDate<=@rToAdmissionDate)OR(ISNULL(@rToAdmissionDate,'')=''))  
			--AND	SAM.BatchId = @rBatchId   
	WHERE 
		SD.OrgId=@rOrgId
		AND (ISNULL(SD.Code,0) IN( SELECT cast(item as nvarchar(20)) FROM  sCommon.fnsplit(@rStrCode,',')) OR @rStrCode='') 
		AND ((SD.ClassId=@rClassId) OR (@rClassId=0))
		AND ((SD.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		AND ((SD.StudentId=@rStudentId) OR (@rStudentId=0))
		AND ((SD.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
		AND ((SD.RollNo <= @rToRollNo) OR (@rToRollNo=0))
		AND ((SD.StatusId=@rStatusId)OR(@rStatusId=0))
		AND ((SD.ClassStatusId=@rClassStatusId) OR (@rClassStatusId=0))
		AND ((MONTH(SD.DateOfBirth)=@rDateOfBirth OR @rDateOfBirth=0))
	    AND ((SD.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
	    AND((SD.Code>=@rFromStudentCode) OR (ISNULL(@rFromStudentCode,'')=''))
	    AND((SD.Code<=@rToStudentCode) OR (ISNULL(@rToStudentCode,'')=''))
		AND((SD.Number>=@rFromNumber) OR (ISNULL(@rFromNumber,0)=0))
	    AND((SD.Number<=@rToNumber) OR (ISNULL(@rToNumber,0)=0))
		AND((SD.AdmissionDate>=@rFromAdmissionDate) OR (ISNULL(@rFromAdmissionDate,'')=''))		
		AND((SD.AdmissionDate<=@rToAdmissionDate) OR (ISNULL(@rToAdmissionDate,'')=''))	
		--Added by dhannajay for mantis : 42884
		AND ((SD.LeftDate>=@rFromLeftDate) OR (ISNULL(@rFromLeftDate,'')=''))		
		AND ((SD.LeftDate<=@rToLeftDate) OR (ISNULL(@rToLeftDate,'')=''))
	    --Added by dhannajay for mantis : 42884
	 Order by
	 SD.RollNo
END
GO
PRINT N'Altering Procedure [sStudent].[pStudentFullProfileGet]...';


GO
ALTER PROCEDURE [sStudent].[pStudentFullProfileGet]

	@rBatchId int,
	@rStudentId bigint,
	@rReportId int=0,
	@rOrgId int,
	@rStrCode nvarchar(max)='',
	@rClassId int=0,
	@rDivisionId int=0,
	@rFromRollNo int=0,
	@rToRollNo int=0,
	@rStatusId int=0,
	@rClassStatusId int=0,
	@rDateOfBirth int=0,
	@rDepartmentId int=0,
	@rBuilder1 nvarchar(max)='',
	@rBuilder2 nvarchar(max)='',
	@rOrgGroupBatchId int,
	@rFromAdmissionDate date = '',
	@rToAdmissionDate date = ''

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

	DECLARE @lAcademicId bigint
	SELECT @lAcademicId = Id from sStudent.tAcademic Where StudentId = @rStudentId AND BatchId = @rBatchId

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

END
GO
PRINT N'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

IF(@lUserSourceTypeId = 95)
BEGIN
	IF(@lItemValue = 'Class Teacher')
	BEGIN
		IF(@rUserId=0)
		BEGIN
		 SELECT DISTINCT --Add Distict for Mantis Id:0033687
			  --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 DISTINCT  --Add Distict for Mantis Id:0033687
		      --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
		IF(@rUserId=0)
		BEGIN
		   SELECT DISTINCT   
			  --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  DISTINCT 
				--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
		IF(@rUserId=0)
		BEGIN
			SELECT DISTINCT
				 --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
			SELECT  DISTINCT
			  --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  DISTINCT
			  --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)
								--mantis: 42680, commit the below WHEN condition and add new WHEN condition
								--WHEN UA.SourceTypeId = 2017 THEN (Select DepartmentId from sStudent.vStudentAcademic SA1 WHERE SA1.AcademicId = SA.AcademicId)
								WHEN UA.SourceTypeId = 2017 THEN 0
								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  
	--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  DISTINCT 
	     -- 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
	  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)
								--mantis: 42680, commit the below WHEN condition and add new WHEN condition
								--WHEN UA.SourceTypeId = 2017 THEN (Select DepartmentId from sStudent.vStudentAcademic SA1 WHERE SA1.AcademicId = SA.AcademicId)
								WHEN UA.SourceTypeId = 2017 THEN 0
								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  DISTINCT
		--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  DISTINCT
	  --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].[pStudentSummaryGet]...';


GO
ALTER PROCEDURE [sStudent].[pStudentSummaryGet]

	@rOrgGroupId int=0,
	@rType nvarchar(100),
	@rCommonOrgGroupBatchId int,
	@rOrgId int =0,
	@rOrgSubGroupId int = 0,
	@rDepartmentId int = 0,
	@rClassId int = 0,
	@rStatusId int  = 0
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 

	IF(@rType='OrgGroupwiseStudentCount')
	BEGIN
		SELECT 
			OGM.Id AS OrgGroupId,
			OGM.Title As OrgGroupTitle,
			0 As OrgId,
			'' As OrgTitle,
			0 AS DepartmentId,
			'' AS DepartmentTitle,
			[sStudent].[fGetDashboardStudentCount](1,@rCommonOrgGroupBatchId,@rType,0) AS ActiveStudent,
			[sStudent].[fGetDashboardStudentCount](3,@rCommonOrgGroupBatchId,@rType,0) AS LeftStudent,
			[sStudent].[fGetDashboardStudentCount](2,@rCommonOrgGroupBatchId,@rType,0) AS InActiveStudent,
			[sStudent].[fGetDashboardStudentCount](0,@rCommonOrgGroupBatchId,@rType,0) AS TotalStudent
		FROM sSetup.tOrgGroupMaster OGM
		WHERE OGM.Id<>1 AND ISNULL(OGM.IsObsolete,0) = 0 AND ((OGM.Id = @rOrgGroupId)OR(@rOrgGroupId=0))	
	END
	ELSE IF(@rType='OrgwiseStudentCount')
	BEGIN
		SELECT 
			OM.Id As OrgId,
			OM.Title As OrgTitle,
			0 As OrgGroupId,
			'' As OrgGroupTitle,
			0 AS DepartmentId,
			'' AS DepartmentTitle,
			[sStudent].[fGetDashboardStudentCount](1,@rCommonOrgGroupBatchId,@rType,OM.Id) AS ActiveStudent,
			[sStudent].[fGetDashboardStudentCount](3,@rCommonOrgGroupBatchId,@rType,OM.Id) AS LeftStudent,
			[sStudent].[fGetDashboardStudentCount](2,@rCommonOrgGroupBatchId,@rType,OM.Id) AS InActiveStudent,
			[sStudent].[fGetDashboardStudentCount](0,@rCommonOrgGroupBatchId,@rType,OM.Id) AS TotalStudent
		FROM sSetup.tOrganizationMaster OM
		INNER JOIN sSetup.tOrgGroupMaster OGMR ON OGMR.Id=OM.OrgGroupId
		WHERE OM.Id<>1 AND ISNULL(OM.IsObsolete,0) = 0  AND OM.OrgSubGroupId = @rOrgSubGroupId
	END

	ELSE IF(@rType='OrgSubGroupwiseStudentCount')
	BEGIN
		SELECT 
			OSGM.Id As OrgSubGroupId,
			OSGM.Title As OrgSubGroupTitle,
			OSGM.OrgGroupId As OrgGroupId,
			OGM.Title AS OrgGroupTitle,
			0 AS DepartmentId,
			'' AS DepartmentTitle,
			[sStudent].[fGetDashboardStudentCount](1,@rCommonOrgGroupBatchId,@rType,OSGM.Id) AS ActiveStudent,
			[sStudent].[fGetDashboardStudentCount](3,@rCommonOrgGroupBatchId,@rType,OSGM.Id) AS LeftStudent,
			[sStudent].[fGetDashboardStudentCount](2,@rCommonOrgGroupBatchId,@rType,OSGM.Id) AS InActiveStudent,
			[sStudent].[fGetDashboardStudentCount](0,@rCommonOrgGroupBatchId,@rType,OSGM.Id) AS TotalStudent
		FROM  sSetup.tOrgSubGroupMaster OSGM 
		INNER JOIN sSetup.tOrgGroupMaster OGM ON OGM.Id = OSGM.OrgGroupId
		WHERE OSGM.Id<>1 AND ISNULL(OSGM.IsObsolete,0) = 0  AND ((OSGM.OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))	
	END

	ELSE IF(@rType='DeptwiseStudentCount')
	BEGIN
		SELECT 
			0 AS OrgGroupId,
			'' As OrgGroupTitle,
			DM.OrgId As OrgId,
			'' As OrgTitle,
			DM.Id AS DepartmentId,
			DM.Title AS DepartmentTitle,
			[sStudent].[fGetDashboardStudentCount](1,@rCommonOrgGroupBatchId,@rType,DM.Id) AS ActiveStudent,
			[sStudent].[fGetDashboardStudentCount](3,@rCommonOrgGroupBatchId,@rType,DM.Id) AS LeftStudent,
			[sStudent].[fGetDashboardStudentCount](2,@rCommonOrgGroupBatchId,@rType,DM.Id) AS InActiveStudent,
			[sStudent].[fGetDashboardStudentCount](0,@rCommonOrgGroupBatchId,@rType,DM.Id) AS TotalStudent
		FROM sSetup.tDepartmentMaster DM 
		WHERE DM.Id <> 1 AND ISNULL(DM.IsObsolete,0) = 0 AND DM.OrgId = @rOrgId 	
	END

	ELSE IF(@rType='ClasswiseStudentCount')
	BEGIN
		SELECT 
			CM.Id AS ClassId,
			CM.Title AS ClassName,
			CM.DepartmentId AS DepartmentId,
			[sStudent].[fGetDashboardStudentCount](1,@rCommonOrgGroupBatchId,@rType,CM.Id) AS ActiveStudent,
			[sStudent].[fGetDashboardStudentCount](3,@rCommonOrgGroupBatchId,@rType,CM.Id) AS LeftStudent,
			[sStudent].[fGetDashboardStudentCount](2,@rCommonOrgGroupBatchId,@rType,CM.Id) AS InActiveStudent,
			[sStudent].[fGetDashboardStudentCount](0,@rCommonOrgGroupBatchId,@rType,CM.Id) AS TotalStudent
		FROM sSetup.tClassMaster CM
		WHERE CM.IsObsolete = 0 AND CM.DepartmentId= @rDepartmentId	
		ORDER BY CM.OrderIndex --add for mantis : 0042058
	END

	ELSE IF(@rType='StudentStatusWiseCount')
	BEGIN
		SELECT  SM.Id AS StudentId,
				DM.Id AS DivisionId,
				DM.Code +' - ' + CM.Code AS ClassDivisionName,
				SM.Code As StudentCode,
				[sStudent].[fStudentNameGet](SM.FirstName,SM.MiddleName,SM.LastName,OM.StudentNameFormatId) AS StudentName,
				ISNULL(SC.ParentContactNo,'') AS ContactNo,
				CM.DepartmentId
		FROM sStudent.tStudentMaster SM
				 INNER JOIN sStudent.tAcademic A ON A.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 sSetup.tOrganizationMaster OM ON OM.Id = BM.OrgId
				 INNER JOIN sSetup.tOrgGroupMaster OG ON OG.Id = OM.OrgGroupId
				 INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BM.OrgGroupBatchId
				 INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
				 Left JOIN sStudent.tStudentCommunication SC on SM.Id=SC.StudentId
		WHERE COGBM.Id = @rCommonOrgGroupBatchId AND CM.Id= @rClassId AND BM.IsInContext = 1
			AND (SM.StatusId=@rStatusId OR @rStatusId=0)
		ORDER BY SM.Id	
	END
END
GO
PRINT N'Altering Procedure [sTally].[pReceiptTallyPostingAdd]...';


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

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

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

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


GO

ALTER PROCEDURE [sTimetable].[pWebDragAndDrop]
	--@rOrgGroupId int,
	@rOrgId int,
	@rSchemaId int,
	@rDivisionId int,
	@rDayId int,
	@rLectureNo int,
	@rTeacherId bigint,
	@rSubjectId int,
	@rClassId int= 0,
	@rLockNo int = 0,
	@rLockColour nvarchar(50) ='',
	@rSchoolRoomId int = 0,
	@rIsBreak bit = 0,
	@rIsMergeDivision bit = 0,
	@rIsBreakBefore bit = 0
AS
BEGIN
		 BEGIN TRY
        BEGIN TRANSACTION;
	SET NOCOUNT ON;
	-------NEw changes
		DECLARE @WorkloadData TABLE (
        SubjectId INT,
        Subject NVARCHAR(200),
		Division NVARCHAR(200),
		DivisionId INT,
		Teacher NVARCHAR(200),
		TeacherId BIGINT,
		Code NVARCHAR(500),
		Total int,
		Remain int
		);
		DECLARE @count int
		DECLARE @timeofflecturecount int


			INSERT INTO @WorkloadData (SubjectId, Subject,Division , DivisionId ,Teacher,TeacherId,Code,Total,Remain)
			EXEC [sTimetable].[pWebGetSuggestedSubjectList] @rSchemaId , @rOrgId ,@rClassId,@rDivisionId, @rSubjectId, @rTeacherId,0,0

			if exists(SELECT Id
			FROM sTimeTable.tTempSTimeTable TTT
			INNER JOIN sTimeTable.tAssignOrg AO ON AO.TimeTableSchemaId = TTT.TimeTableSchemaId
			WHERE TTT.TimeTableSchemaId = @rSchemaId
			AND TTT.DivisionId = @rDivisionId
			AND TTT.DayId = @rDayId
			AND TTT.LectureNumber = @rLectureNo
			AND AO.OrgId = @rOrgId
			AND TTT.EmployeeId >0)
				 BEGIN

					select 2 As Result -- Period is Busy
				 END
				ELSE
				BEGIN
					IF ((select Remain FROM @WorkloadData) <= 0 )
					BEGIN
						-- logc check for  get remian from workload
						select 3 as Result-- All Lecture Given For Teacher
					END
					ELSE
					BEGIN

						IF((select DivisionId  FROM @WorkloadData) != @rDivisionId)
						BEGIN
							-- check division id with the  division drag and drop
							select 7 as Result-- Wrong Division ! Check The Division
						END
						ELSE
						BEGIN
							set @count = (SELECT COUNT(*) from sTimeTable.tTempSTimeTable WHERE
							EmployeeId = @rTeacherId AND
							DayId = @rDayId AND LectureNumber = @rLectureNo AND TimeTableSchemaId = @rSchemaId)

							IF(@count > 0 )
							BEGIN
								select 1 as Result -- Employee is Engaged
							END
							ELSE
							BEGIN
								EXEC [sTimetable].[pWebTimeOffLecture] @rSchemaId,@rDivisionId,@rDayId,@rLectureNo,@rSubjectId,@rTeacherId,@rSchoolRoomId, @Return = @timeofflecturecount OUTPUT
								IF(@timeofflecturecount >=1)
								BEGIN
									SELECT 6 as Result-- For this Lecture Timeoff set
								END
								ELSE
								BEGIN
									set @count = (SELECT Count(*) from [sTimetable].[tTempSTimeTable]  where TimeTableSchemaId = @rSchemaId AND DivisionId = @rDivisionId AND DayId = @rDayId AND LectureNumber = @rLectureNo AND LockNo <> 0)
									IF(@count != 1)
									BEGIN
										--update [sTimetable].[tTempSTimeTable] set EmployeeId = @rEmployeeId AND SubjectId = @rSubjectId WHERE TimeTableSchemaId = @rSchemaId AND DivisionId = @rDivisionId AND DayId = @rDayId AND LectureNumber = @rLectureNo AND LockNo != 1)
										Update [sTimetable].[tTempSTimeTable] set TimeTableSchemaId =@rSchemaId , EmployeeId = @rTeacherId , DivisionId  = @rDivisionId,
										SubjectId =  @rSubjectId , DayId = @rDayId , LectureNumber = @rLectureNo , LockNo = @rLockNo , LockColour = @rLockColour , SchoolRoomId = @rSchoolRoomId,
										IsBreak = @rIsBreak, IsMergeDivision = @rIsMergeDivision , IsBreakBefore = @rIsBreakBefore
										where  TimeTableSchemaId = @rSchemaId AND DivisionId = @rDivisionId AND DayId = @rDayId AND LectureNumber = @rLectureNo

										select 5 as Result -- Success
									END
									ELSE
									BEGIN
										SELECT 4 as Result -- lecture is locked
									END
								END
							END
						END

					END


				END



        COMMIT TRANSACTION;
    END TRY
    BEGIN CATCH
        ROLLBACK TRANSACTION;
        select -101 AS result;
    END CATCH
END
GO
PRINT N'Altering Procedure [sTimetable].[pWebFetchSubjectsForTeacherInTheDivision]...';


GO

Create or ALTER   procedure [sTimetable].[pWebFetchSubjectsForTeacherInTheDivision] --991100017,9911000000165,991100035
(
	@rSchemaId int,
	@rEmployeeId bigint,
	@rDivisionId int
)
as
begin
		select SubjectId,NoOfLecture
		from sTimetable.tTeacherWorkLoad
		where EmployeeId=@rEmployeeId and  timetableschemaid=@rschemaid and  DivisionId=@rDivisionId
end
GO
PRINT N'Altering Procedure [sTimetable].[pWebFetchWorkloadForSubjectsForTeacherInDivision]...';


GO

CREATE or ALTER   PROCEDURE [sTimetable].[pWebFetchWorkloadForSubjectsForTeacherInDivision]
(
	@rSchemaId INT,
	@rSubjectId INT,
	@rDivisionId INT,
	@rEmployeeId BIGINT
)
AS
BEGIN
	IF EXISTS (SELECT 1 FROM sTimetable.tTeacherTimeOff WHERE TimeTableSchemaId = @rSchemaId AND EmployeeId = @rEmployeeId AND LectureNumber = 1)
	BEGIN
		--SELECT DayId, EmployeeId, 95 FROM sTimetable.tTeacherTimeOff WHERE TimeTableSchemaId = @rSchemaId AND EmployeeId = @rEmployeeId AND LectureNumber = 1
		SELECT -1
	END
	ELSE IF EXISTS (SELECT 1 FROM sTimetable.tSubjectTimeOff WHERE TimeTableSchemaId = @rSchemaId AND SubjectId = @rSubjectId AND LectureNumber = 1)
	BEGIN
		--SELECT DayId, SubjectId, 100 FROM sTimetable.tSubjectTimeOff WHERE TimeTableSchemaId = @rSchemaId AND SubjectId = @rSubjectId AND LectureNumber = 1
		SELECT -1
	END
	ELSE
	BEGIN
		IF EXISTS (SELECT NoOfLecture FROM sTimetable.tDivisionWorkLoad WHERE SubjectId = @rSubjectId AND DivisionId = @rDivisionId AND TimetableSchemaId = @rSchemaId)
		BEGIN
			SELECT NoOfLecture FROM sTimetable.tDivisionWorkLoad WHERE SubjectId = @rSubjectId AND DivisionId = @rDivisionId AND TimetableSchemaId = @rSchemaId
		END
		ELSE
		BEGIN
			SELECT NoOfLecture FROM sTimetable.tTeacherWorkLoad WHERE SubjectId = @rSubjectId AND DivisionId = @rDivisionId AND TimetableSchemaId = @rSchemaId AND EmployeeId = @rEmployeeId
		END
	END
END
GO
PRINT N'Creating Procedure [sAssessment].[pRptTeacherEvaluationSubjectAnalysis]...';


GO


CREATE PROCEDURE [sAssessment].[pRptTeacherEvaluationSubjectAnalysis]
	 
	  
	 @rClassId int=0,
	 @rDivisionId int=0,
	 @rDepartmentId int=0,
	 @rExamSubGroupId int=0,
	 @rBuilder1 nvarchar(MAX)='',
	 @rBatchId int,
	 @rOrgId int=0,
	 @rClass nvarchar(MAX)='',
	 @rStatusId int = 0,
	 @rClassStatusId int=0
	,@rEmployeeId bigint=0
	 ,@rFromRollNo int
	 ,@rToRollNo int
	 ,@rCode nvarchar(20)
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	 
		
		
 
	 DECLARE @GradeSetId int
	 Declare @G1 nvarchar(20),@G2 nvarchar(20),@G3 nvarchar(20),@G4 nvarchar(20),@G5 nvarchar(20),@G6 nvarchar(20),@G7 nvarchar(20),@G8 nvarchar(20),@G9 nvarchar(20),@G10 nvarchar(20)	
		
	 --Set @GradeSetId =(select TOP(1)GradeSetId from sAssessment.tExamMaster  where ExamSubGroupId = @rExamSubGroupId AND BatchId=@rBatchId AND (ClassId = @rClassId OR @rClassId = 0))

	 --According to AssessmentConfiguration
	 Set @GradeSetId = (Select AnalysisGradeSetId from sAssessment.tConfiguration Where OrgId = @rOrgId)
		  --Select @GradeSetId
	CREATE Table #Temp
	(
		Id Int Identity (1,1),
		GradeCode nvarchar(20),
		MinimumScore decimal(6,2),
	)
	Insert into #Temp
	
		select GradeCode,MinimumScore from  sAssessment.tGradeSetDetail where GradeSetId=@GradeSetId
	 
	 	 Set @G1=(Select GradeCode from #Temp where Id=1) 
	 	 Set @G2=(Select GradeCode from #Temp where Id=2) 
	 	 Set @G3=(Select GradeCode from #Temp where Id=3) 
	 	 Set @G4=(Select GradeCode from #Temp where Id=4) 
	     Set @G5=(Select GradeCode from #Temp where Id=5) 
         Set @G6=(Select GradeCode from #Temp where Id=6) 
	     Set @G7=(Select GradeCode from #Temp where Id=7) 
	 	 Set @G8=(Select GradeCode from #Temp where Id=8) 
	 	 Set @G9=(Select GradeCode from #Temp where Id=9) 
		 Set @G10=(Select GradeCode from #Temp where Id=10)  
	   
	 select 
		@rBuilder1 AS Builder1,
		Cm.Classid As ClassId,
		Dm.id As DivisionId,
		Cm.ClassName As ClassName,
		DM.DisplayTitle As DivisionName,
		
		 
	  
	  (select COUNT(RD.Id) from sAssessment.tResultDetail RD INNER JOIN  sAssessment.tResult R ON RD.ResultId = R.Id  
	  INNER JOIN sStudent.vStudentAcademic A ON R.AcademicId = A.AcademicId 
	  INNER JOIN sAssessment.tExamDetail ED ON ED.ID=RD.ExamDetailId
	  	INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
		INNER JOIN  sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId  
	  where 
	  A.DivisionId = DM.Id AND EM.ExamSubGroupId = @rExamSubGroupId AND EM.BatchId = @rBatchId AND ((A.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0)) AND CS.SubjectId=SM.Id	  AND ((A.StatusId=@rStatusId) OR (@rStatusId=0)) 
	  AND ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0))
	  AND ((A.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
	  AND ((A.RollNo <= @rToRollNo) OR (@rToRollNo=0))
	  AND ((A.Code=@rCode) OR (@rCode=''))
	  ) AS NoOfStudent,
	  
	 

	  (select MAX(RD.Obtain) from  sAssessment.tResultDetail RD INNER JOIN  sAssessment.tResult R ON RD.ResultId = R.Id  
	  INNER JOIN sStudent.vStudentAcademic A ON R.AcademicId = A.AcademicId 
	   INNER JOIN sAssessment.tExamDetail ED ON ED.ID=RD.ExamDetailId
	  	INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
		INNER JOIN  sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId  
	  where 
	  A.DivisionId = DM.Id AND EM.ExamSubGroupId = @rExamSubGroupId AND EM.BatchId = @rBatchId AND ((A.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0)) AND CS.SubjectId=SM.Id		AND ((A.StatusId=@rStatusId) OR (@rStatusId=0)) AND ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0))
		AND ((A.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
		AND ((A.RollNo <= @rToRollNo) OR (@rToRollNo=0))
		AND ((A.Code=@rCode) OR (@rCode=''))
	  ) AS HighestPerMark,

	  (select AVG(RD.Obtain) from  sAssessment.tResultDetail RD INNER JOIN  sAssessment.tResult R  ON RD.ResultId = R.Id   
	    INNER JOIN sStudent.vStudentAcademic A ON R.AcademicId = A.AcademicId 
	   INNER JOIN sAssessment.tExamDetail ED ON ED.ID=RD.ExamDetailId
	  	INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
		INNER JOIN  sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId  
	  where 
	  A.DivisionId = DM.Id AND EM.ExamSubGroupId = @rExamSubGroupId AND EM.BatchId = @rBatchId AND ((A.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0)) AND CS.SubjectId=SM.Id		AND ((A.StatusId=@rStatusId) OR (@rStatusId=0)) AND ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0)) AND RD.IsPresent = 1
		AND ((A.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
		AND ((A.RollNo <= @rToRollNo) OR (@rToRollNo=0))
		AND ((A.Code=@rCode) OR (@rCode=''))
	  ) AS AveragePerMark, -- Add RD.IsPresent = 1 for Mantis : 0028928
	  
	  (select MIN(RD.Obtain) from sAssessment.tResultDetail RD INNER JOIN  sAssessment.tResult R ON RD.ResultId = R.Id 
	  INNER JOIN sStudent.vStudentAcademic A ON R.AcademicId = A.AcademicId 
	    INNER JOIN sAssessment.tExamDetail ED ON ED.ID=RD.ExamDetailId
	  	INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
		INNER JOIN  sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId  
	  where 
	  A.DivisionId = DM.Id AND EM.ExamSubGroupId = @rExamSubGroupId AND EM.BatchId = @rBatchId AND ((A.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0)) AND CS.SubjectId=SM.Id		AND ((A.StatusId=@rStatusId) OR (@rStatusId=0)) AND ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0)) AND RD.IsPresent = 1
		AND ((A.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
		AND ((A.RollNo <= @rToRollNo) OR (@rToRollNo=0))
		AND ((A.Code=@rCode) OR (@rCode=''))
	  ) AS LowestPerMark , 
	  
	  (Select COUNT(R.AcademicId) from sAssessment.tResultDetail RD INNER JOIN  sAssessment.tResult R ON RD.ResultId = R.Id  
	  INNER JOIN sStudent.vStudentAcademic A ON R.AcademicId = A.AcademicId 
	 INNER JOIN sAssessment.tExamDetail ED ON ED.ID=RD.ExamDetailId
		INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
		INNER JOIN  sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId  
	  where 
	  A.DivisionId = DM.Id AND EM.ExamSubGroupId = @rExamSubGroupId AND EM.BatchId = @rBatchId AND ((A.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0)) AND  SubjectGrade = @G1		AND CS.SubjectId=SM.Id AND ((A.StatusId=@rStatusId) OR (@rStatusId=0)) AND ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0)) 
		AND (EM.ClassId=@rClassId OR @rClassId=0)
		AND ((A.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
		AND ((A.RollNo <= @rToRollNo) OR (@rToRollNo=0))
		AND ((A.Code=@rCode) OR (@rCode=''))
	  )AS GradeCount1,
	  
  (Select COUNT(R.AcademicId) from sAssessment.tResultDetail RD INNER JOIN  sAssessment.tResult R   ON RD.ResultId = R.Id   
  INNER JOIN sStudent.vStudentAcademic A ON R.AcademicId = A.AcademicId 
	  INNER JOIN sAssessment.tExamDetail ED ON ED.ID=RD.ExamDetailId
	  INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
		INNER JOIN  sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId  
	  where 
	  A.DivisionId = DM.Id AND EM.ExamSubGroupId = @rExamSubGroupId AND EM.BatchId = @rBatchId AND ((A.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0)) AND  SubjectGrade = @G2		AND CS.SubjectId=SM.Id AND ((A.StatusId=@rStatusId) OR (@rStatusId=0)) AND ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0)) 
		AND (EM.ClassId=@rClassId OR @rClassId=0)
		AND ((A.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
		AND ((A.RollNo <= @rToRollNo) OR (@rToRollNo=0))
		AND ((A.Code=@rCode) OR (@rCode=''))
	  )AS GradeCount2,
	 

  (Select COUNT(R.AcademicId)from sAssessment.tResultDetail RD INNER JOIN  sAssessment.tResult R   ON RD.ResultId = R.Id   
  INNER JOIN sStudent.vStudentAcademic A ON R.AcademicId = A.AcademicId 
	 INNER JOIN sAssessment.tExamDetail ED ON ED.ID=RD.ExamDetailId
	  INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
		INNER JOIN  sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId  
	  where 
	  A.DivisionId = DM.Id AND EM.ExamSubGroupId = @rExamSubGroupId AND EM.BatchId = @rBatchId AND ((A.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0)) AND  SubjectGrade = @G3		AND CS.SubjectId=SM.Id AND ((A.StatusId=@rStatusId) OR (@rStatusId=0)) AND ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0)) 
		AND (EM.ClassId=@rClassId OR @rClassId=0) AND ((A.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
		AND ((A.RollNo <= @rToRollNo) OR (@rToRollNo=0))
		AND ((A.Code=@rCode) OR (@rCode=''))
	  )AS GradeCount3,
	 

  (Select COUNT(R.AcademicId) from sAssessment.tResultDetail RD INNER JOIN  sAssessment.tResult R  ON RD.ResultId = R.Id  
  INNER JOIN sStudent.vStudentAcademic A ON R.AcademicId = A.AcademicId 
	  INNER JOIN sAssessment.tExamDetail ED ON ED.ID=RD.ExamDetailId
	  INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
		INNER JOIN  sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId  
	  where 
	  A.DivisionId = DM.Id AND EM.ExamSubGroupId = @rExamSubGroupId AND EM.BatchId = @rBatchId  AND ((A.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0)) 
		AND  SubjectGrade = @G4  AND CS.SubjectId=SM.Id AND ((A.StatusId=@rStatusId) OR (@rStatusId=0)) 
		AND ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0)) AND (EM.ClassId=@rClassId OR @rClassId=0)
		AND ((A.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
		AND ((A.RollNo <= @rToRollNo) OR (@rToRollNo=0))
		AND ((A.Code=@rCode) OR (@rCode=''))
	)AS GradeCount4,
	 
  (Select COUNT(R.AcademicId) from sAssessment.tResultDetail RD INNER JOIN  sAssessment.tResult R ON RD.ResultId = R.Id   
  INNER JOIN sStudent.vStudentAcademic A ON R.AcademicId = A.AcademicId 
	  INNER JOIN sAssessment.tExamDetail ED ON ED.ID=RD.ExamDetailId
	  INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
		INNER JOIN  sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId  
	  where 
	  A.DivisionId = DM.Id AND EM.ExamSubGroupId = @rExamSubGroupId AND EM.BatchId = @rBatchId AND ((A.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0)) AND  SubjectGrade = @G5		AND CS.SubjectId=SM.Id AND ((A.StatusId=@rStatusId) OR (@rStatusId=0)) AND ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0)) 
		AND (EM.ClassId=@rClassId OR @rClassId=0)
		AND ((A.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
		AND ((A.RollNo <= @rToRollNo) OR (@rToRollNo=0))
		AND ((A.Code=@rCode) OR (@rCode=''))
	  )AS GradeCount5,
	 
  (Select COUNT(R.AcademicId) from sAssessment.tResultDetail RD INNER JOIN  sAssessment.tResult R ON RD.ResultId = R.Id  
  INNER JOIN sStudent.vStudentAcademic A ON R.AcademicId = A.AcademicId 
	 INNER JOIN sAssessment.tExamDetail ED ON ED.ID=RD.ExamDetailId
	  INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
		INNER JOIN  sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId  
	  where 
	  A.DivisionId = DM.Id AND EM.ExamSubGroupId = @rExamSubGroupId AND EM.BatchId = @rBatchId AND ((A.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0)) AND  SubjectGrade = @G6		AND CS.SubjectId=SM.Id AND ((A.StatusId=@rStatusId) OR (@rStatusId=0)) AND ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0)) 
		AND (EM.ClassId=@rClassId OR @rClassId=0)
		AND ((A.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
		AND ((A.RollNo <= @rToRollNo) OR (@rToRollNo=0))
		AND ((A.Code=@rCode) OR (@rCode=''))
	  )AS GradeCount6,
	 
  (Select COUNT(R.AcademicId) from sAssessment.tResultDetail RD INNER JOIN  sAssessment.tResult R ON RD.ResultId = R.Id  
  INNER JOIN sStudent.vStudentAcademic A ON R.AcademicId = A.AcademicId 
	  INNER JOIN sAssessment.tExamDetail ED ON ED.ID=RD.ExamDetailId
	  INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
		INNER JOIN  sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId  
	  where 
	  A.DivisionId = DM.Id AND EM.ExamSubGroupId = @rExamSubGroupId AND EM.BatchId = @rBatchId  AND ((A.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0)) 
		AND  SubjectGrade = @G7  AND CS.SubjectId=SM.Id  AND ((A.StatusId=@rStatusId) OR (@rStatusId=0)) 
		AND ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0)) AND (EM.ClassId=@rClassId OR @rClassId=0)
		AND ((A.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
		AND ((A.RollNo <= @rToRollNo) OR (@rToRollNo=0))
		AND ((A.Code=@rCode) OR (@rCode=''))
		)AS GradeCount7,
	 
  (Select COUNT(R.AcademicId) from sAssessment.tResultDetail RD INNER JOIN  sAssessment.tResult R ON RD.ResultId = R.Id   
  INNER JOIN sStudent.vStudentAcademic A ON R.AcademicId = A.AcademicId 
	   INNER JOIN sAssessment.tExamDetail ED ON ED.ID=RD.ExamDetailId
	  INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
		INNER JOIN  sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId  
	  where 
	  A.DivisionId = DM.Id AND EM.ExamSubGroupId = @rExamSubGroupId AND EM.BatchId = @rBatchId  AND ((A.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0)) 
		AND  SubjectGrade = @G8	  AND CS.SubjectId=SM.Id AND ((A.StatusId=@rStatusId) OR (@rStatusId=0)) AND ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0)) 
		AND (EM.ClassId=@rClassId OR @rClassId=0)
		AND ((A.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
		AND ((A.RollNo <= @rToRollNo) OR (@rToRollNo=0))
		AND ((A.Code=@rCode) OR (@rCode=''))
	)AS GradeCount8,
	 
  (Select COUNT(R.AcademicId) from sAssessment.tResultDetail RD INNER JOIN  sAssessment.tResult R  ON RD.ResultId = R.Id  
  INNER JOIN sStudent.vStudentAcademic A ON R.AcademicId = A.AcademicId 
	   INNER JOIN sAssessment.tExamDetail ED ON ED.ID=RD.ExamDetailId
	  INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
		INNER JOIN  sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId  
	  where 
	  A.DivisionId = DM.Id AND EM.ExamSubGroupId = @rExamSubGroupId AND EM.BatchId = @rBatchId  AND ((A.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0)) 
	  AND  SubjectGrade = @G9  AND CS.SubjectId=SM.Id AND ((A.StatusId=@rStatusId) OR (@rStatusId=0)) AND ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0)) 
	AND (EM.ClassId=@rClassId OR @rClassId=0)
	AND ((A.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
	AND ((A.RollNo <= @rToRollNo) OR (@rToRollNo=0))
	AND ((A.Code=@rCode) OR (@rCode=''))
	)AS GradeCount9,
	 
  (Select COUNT(R.AcademicId) from sAssessment.tResultDetail RD INNER JOIN  sAssessment.tResult R ON RD.ResultId = R.Id   
  INNER JOIN sStudent.vStudentAcademic A ON R.AcademicId = A.AcademicId 
	 INNER JOIN sAssessment.tExamDetail ED ON ED.ID=RD.ExamDetailId
	  INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
		INNER JOIN  sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId  
	  where 
	  A.DivisionId = DM.Id AND EM.ExamSubGroupId = @rExamSubGroupId AND EM.BatchId = @rBatchId AND ((A.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0)) AND  SubjectGrade = @G10		AND CS.SubjectId=SM.Id AND ((A.StatusId=@rStatusId) OR (@rStatusId=0)) AND ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0)) 
		AND (EM.ClassId=@rClassId OR @rClassId=0)
		AND ((A.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
		AND ((A.RollNo <= @rToRollNo) OR (@rToRollNo=0))
		AND ((A.Code=@rCode) OR (@rCode=''))
	)AS GradeCount10,
	  
	  
   
	  ISNULL(@G1,'*') AS Grade1,
	  ISNULL(@G2,'*') AS Grade2,
	  ISNULL(@G3,'*') AS Grade3,
	  ISNULL(@G4,'*') AS Grade4,
	  ISNULL(@G5,'*') As Grade5,
	  ISNULL(@G6,'*') As Grade6,
	  ISNULL(@G7,'*') AS Grade7,
	  ISNULL(@G8,'*') AS Grade8,
	  ISNULL(@G9,'*') AS Grade9,
	 ISNULL(@G10,'*')  AS Grade10,
	 Sm.Id AS SubjectId,
	  SM.Title AS SubjectName,
	  CS.OrderIndex AS OrderIndex,
	  (select COUNT(R.AcademicId) from  sAssessment.tResultDetail RD INNER JOIN  sAssessment.tResult R ON RD.ResultId = R.Id  
		INNER JOIN sStudent.vStudentAcademic A ON R.AcademicId = A.AcademicId 
		INNER JOIN sAssessment.tExamDetail ED ON ED.ID=RD.ExamDetailId
	  	INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
		INNER JOIN  sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId  
		where 
			A.DivisionId = DM.Id AND EM.ExamSubGroupId = @rExamSubGroupId AND EM.BatchId = @rBatchId 
			AND ((A.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0)) AND CS.SubjectId=SM.Id 
			AND ((A.StatusId=@rStatusId) OR (@rStatusId=0)) AND ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0)) 
			AND ISNULL(RD.IsPresent,0) = 0 
			AND ((A.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
			AND ((A.RollNo <= @rToRollNo) OR (@rToRollNo=0))
		) AS AbsentCount,
		(select MAX(ED.Maximum) from  sAssessment.tResultDetail RD INNER JOIN  sAssessment.tResult R ON RD.ResultId = R.Id  
	  INNER JOIN sStudent.vStudentAcademic A ON R.AcademicId = A.AcademicId 
	   INNER JOIN sAssessment.tExamDetail ED ON ED.ID=RD.ExamDetailId
	  	INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
		INNER JOIN  sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId  
	  where 
	  A.DivisionId = DM.Id AND EM.ExamSubGroupId = @rExamSubGroupId AND EM.BatchId = @rBatchId AND ((A.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0)) 
	  AND CS.SubjectId=SM.Id		AND ((A.StatusId=@rStatusId) OR (@rStatusId=0)) AND ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0))
		AND ((A.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
		AND ((A.RollNo <= @rToRollNo) OR (@rToRollNo=0))
		AND ((A.Code=@rCode) OR (@rCode=''))
	  ) AS MaximumMark, 

	  	(select COUNT(RD.Id) from  sAssessment.tResultDetail RD 
		INNER JOIN  sAssessment.tResult R ON RD.ResultId = R.Id  
		INNER JOIN sStudent.vStudentAcademic A ON R.AcademicId = A.AcademicId 
		INNER JOIN sAssessment.tExamDetail ED ON ED.ID=RD.ExamDetailId
		INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
		INNER JOIN  sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId  
	  where 
	  A.DivisionId = DM.Id AND EM.ExamSubGroupId = @rExamSubGroupId AND 
	  EM.BatchId = @rBatchId AND CS.SubjectId=SM.Id AND ((RD.Obtain<ED.Minimum) OR (RD.IsPresent = 0)) AND ((A.StatusId=@rStatusId) OR (@rStatusId=0)) 
	  AND ((A.ClassStatusId = @rClassStatusId) OR (@rClassStatusId=0))
	  AND ((A.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
	  AND ((A.RollNo <= @rToRollNo) OR (@rToRollNo=0))
	  AND ((A.Code=@rCode) OR (@rCode=''))
	  ) AS FailStudent, 

	  (select COUNT(RD.Id) from  sAssessment.tResultDetail RD 
		INNER JOIN  sAssessment.tResult R ON RD.ResultId = R.Id  
		INNER JOIN sStudent.vStudentAcademic A ON R.AcademicId = A.AcademicId 
		INNER JOIN sAssessment.tExamDetail ED ON ED.ID=RD.ExamDetailId
		INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
		INNER JOIN  sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId  
	  where 
	  A.DivisionId = DM.Id AND EM.ExamSubGroupId = @rExamSubGroupId AND 
	  
	  EM.BatchId = @rBatchId AND CS.SubjectId=SM.Id AND (CASE WHEN ED.Maximum <> 0 THEN (RD.Obtain * 100.0 / ED.Maximum) ELSE 0 END) > 90 AND ((A.StatusId=@rStatusId) OR			(@rStatusId=0)) AND ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0)) AND RD.IsPresent = 1
	  AND ((A.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
		AND ((A.RollNo <= @rToRollNo) OR (@rToRollNo=0))
		AND ((A.Code=@rCode) OR (@rCode=''))
	  ) AS Above90PercentStudent -- add for mantis : 0035813
	  ,TSD.EmployeeId
	,ISNULL(EmpM.FirstName, '') + ' ' + ISNULL(EmpM.LastName, '') AS TeacherName,
	EmpM.FirstName,
	EmpM.MiddleName,
	EmpM.LastName,
	EmpM.Code AS EmployeeCode
	  
	 from
 

		sAssessment.tExamDetail ED		
		INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId	
		INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId		
		INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
		INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=CS.SubjectId					 
		INNER JOIN sSetup.tClassMaster CLM ON CLM.Id=EM.ClassId
		INNER JOIN sSetup.tDivisionMaster DM ON DM.ClassId=CLM.Id
		INNER JOIN sSetup.vBatchClass CM ON CM.ClassId = DM.ClassId
		INNER JOIN sAcademic.tTeacherSubjectDivision TSD ON SM.Id = TSD.SubjectId AND DM.Id = TSD.DivisionId
		INNER JOIN sHrm.tEmployeeMaster EmpM ON TSD.EmployeeId = EmpM.Id 
		AND EmpM.StatusId = 7		
	
		WHERE 
 
			
			EM.BatchId = @rBatchId 
			AND (EM.ClassId=@rClassId OR @rClassId=0) 
			AND (DM.Id=@rDivisionId OR @rDivisionId=0)			
			AND ((ESGM.Id = @rExamSubGroupId) OR (@rExamSubGroupId = 0))
			AND CM.BatchId = @rBatchId
			AND (CLM.DepartmentId=@rDepartmentId OR @rDepartmentId=0)	
			AND (ISNULL(CLM.Id,0) IN( SELECT item FROM  sCommon.fnsplit(@rClass,','))OR @rClass='')
			AND CLM.IsObsolete = 0 AND DM.IsObsolete=0
			AND TSD.EmployeeId = @rEmployeeId
  	
END

-- SP Drag and Drop
--BEGIN
--	SELECT 
--	 '' AS Builder1,
--	 0 AS ClassId,
--	 0 AS DivisionId,
--	 '' AS ClassName,
--	 '' AS DivisionName,
--	 0 AS NoOfStudent,
--	 Convert(DECIMAL,0) HighestPerMark,
--	 Convert(DECIMAL,0) AveragePerMark,
--	 Convert(DECIMAL,0) LowestPerMark,
--	 0 AS GradeCount1,
--	 0 AS GradeCount2,
--	 0 AS GradeCount3,
--	 0 AS GradeCount4,
--	 0 AS GradeCount5,
--	 0 AS GradeCount6,
--	 0 AS GradeCount7,
--	 0 AS GradeCount8,
--	 0 AS GradeCount9,
--	 0 AS GradeCount10,
--	 '' AS Grade1,
--	 '' AS Grade2,
--	 '' AS Grade3,
--	 '' AS Grade4,
--	 '' AS Grade5,
--	 '' AS Grade6,
--	 '' AS Grade7,
--	 '' AS Grade8,
--	 '' AS Grade9,
--	 '' AS Grade10,
--	 0 AS SubjectId,
--	 '' AS SubjectName,
--	 0 AS OrderIndex,
--	 0 AS AbsentCount,
--	 Convert(DECIMAL,0) MaximumMark,
--	 0 AS FailStudent,
--	 0 AS Above90PercentStudent
--	, '' AS TeacherName
--	, '' AS FirstName
--	, '' AS MiddleName
--	, '' AS LastName
--	, '' AS EmployeeCode

--END
GO
PRINT N'Creating Procedure [sAttendance].[pRptStudentAttendancewithStudentGroup]...';


GO

  
CREATE PROCEDURE [sAttendance].[pRptStudentAttendancewithStudentGroup]
	
		@rBuilder1 nvarchar(max)='',
		@rBuilder2 nvarchar(max)='', 
		@rBatchId int,
		@rClassId int,
		@rDivisionId int,
		@rDepartmentId int,		
		@rOrgId smallint,
		@rAttendanceTypeId int,
		@rDate date,		 
		@rDivisionGroup bit=0
		,@rStudentGroupId int=0
		
		
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
	SELECT 
			 
			@rDivisionGroup AS DivisionGroup,
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2, 
			CM.Id AS ClassId,
			CM.DisplayTitle AS ClassName,
			CM.OrderIndex  ,
			DM.Id AS DivisionId,
			DM.Title AS DivisionName,
			DM.OrderIndex AS DivisionOrderIndex
			,SO.GenderId 
			,ISNULL(SR.AttendanceTypeId,0) AS AttendanceTypeId
			,ISNULL(SR.IsPresent,0) AS IsPresent
			,ISNULL(SR.Academicid,0) AS Academicid	
			,ISNULL(SR.AttendanceDate,'') AS AttendanceDate
			,ATM.Title AS AttendanceType
			,ISNULL(SGM.Title,'Group Not Selected') AS StudentGroup
			,ISNULL(SGM.Id,0) AS StudentGroupId
			,ISNULL(SGM.Code,'') AS StudentGroupCode
		
	FROM 
			 sStudent.tAcademic A
			INNER JOIN sStudent.tStudentOther SO ON SO.StudentId=A.StudentId				 
			INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId
			INNER JOIN sSetup.tDivisionMaster DM  ON CM.Id = DM.ClassId
			INNER JOIN sSetup.tDepartmentMaster Dept ON Dept.Id=CM.DepartmentId 
			 INNER JOIN sSetup.tBatchClass BC ON BC.ClassID =  CM.Id and BC.BatchId= @rBatchId
			 INNER JOIN sStudent.tStudentMaster SM ON SM.Id = A.StudentId
			 LEFT JOIN sStudent.tStudentGroupMaster SGM ON SGM.Id = SM.StudentGroupId
			LEFT JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id AND  SR.AttendanceDate=@rDate AND SR.AttendanceTypeId =@rAttendanceTypeId 
			LEFT JOIN sAttendance.tAttendanceTypeMaster ATM ON ATM.Id = SR.AttendanceTypeId
			
		 
	WHERE 
		  DM.OrgId=@rOrgId
		AND ((DM.ClassId=@rClassId) OR (@rClassId=0))
		AND ((DM.Id=@rDivisionId) OR (@rDivisionId=0))
		AND ((Dept.Id=@rDepartmentId) OR (@rDepartmentId=0))
		AND DM.IsObsolete = 0
		AND CM.IsObsolete = 0
		AND Dept.IsObsolete = 0
		AND A.BatchId = @rBatchId  
	    
	    AND A.ClassId =CM.Id 
		AND A.DivisionId=DM.Id  AND  CM.DepartmentId =Dept.Id 
		
		--AND SR.IsPresent =1 
		AND A.OrgId = @rOrgId
		AND ((DM.Id=@rDivisionId) OR (@rDivisionId=0))
		AND ((SGM.Id=@rStudentGroupId) OR (@rStudentGroupId=0))
			 
			ORDER BY CM.OrderIndex ASC
END
GO
PRINT N'Creating Procedure [sCommunication].[pAssignmentListGet_OGOLD]...';


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

BEGIN
	DECLARE @lOrgGroupBatchId INT = 0

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

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

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

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

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

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


GO

CREATE PROCEDURE [sCommunication].[pAssignmentNotificationListGet] 
@rSourceId bigint,
@rSubjectId int,
@rBatchId int,
@rSourceTypeId int,
@rIsObsolete bit,
@rOrgId int

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

Select DISTINCT SA.StudentId AS SourceId from [sSetup].[tClassSubject] AS CS 
INNER JOIN sSetup.tDivisionMaster AS DM ON DM.ClassId = CS.ClassId
INNER JOIN sStudent.vStudentAcademic AS SA ON SA.ClassId = CS.ClassId AND SA.DivisionId = DM.Id
INNER JOIN [sAssessment].[tOptionalSubject] As OS ON OS.AcademicId = SA.AcademicId AND OS.ClassSubjectId = CS.Id
where CS.IsOptional = 1 AND CS.SubjectId = @rSubjectId 
AND DM.Id = @rSourceId AND SA.IsActiveBatch = 1 AND SA.OrgId = @rOrgId AND SA.BatchId = @rBatchId

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


GO

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

 WITH EXECUTE AS CALLER    
AS    
SET NOCOUNT ON    

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

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

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

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

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


GO

CREATE or Alter PROCEDURE [sFee].[pRptFeeStatusStudentAndReceiptWiseGet]
		
	@rReportId int,
	@rReceiptBookId int,
	@rAdmissionCategoryId int,
	@rClassId int,
	@rDivisionId int,
	@rUptoDate date,
	@rBatchId int,
	@rUserId bigint,
	@rBuilder1 nvarchar(max),
	@rBuilder2 nvarchar(max),
	@rIsDetail bit,
	@rOrgId int,
	@rOrgGroupBatchId int,
	@rIsExemption bit =0,
	@rStatusId int = 0,
	@rCommonBatch nvarchar(100),
	@rDepartmentId int,
	@rFromRollNo int,
    @rToRollNo int,
    @rCode nvarchar(20),
    @rIsFilter bit,
	@rIsHeader bit,
	@rCreatedUserName nvarchar(100)='',
	@rFeeHeadId nvarchar(max) = '',
	@rIsDisplayOrgGroup bit=0,
	@rExemptionTypeId int=0,
	@rFeeId nvarchar(max) = '',
	@rFilterId int=0,
	@rFeeGroupId int=0,
	@rOrgGroupId int=0,
	@rOrgIds nvarchar(max) = '',
	@rIsReceiptBookGroup bit=0,
	@rClassStatusId int=0
			
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
BEGIN
--Added by dhananjay For Mantis : 42599
CREATE TABle  #LastFeePaymentDetails
(
AcademicId BIGINT, 
FeeHeadId INT,
FeeId INT,
LastPaymentDate DATETIME,
LastPaidAmount DECIMAL(12,2),
RowNumber INT  
)

Insert into #LastFeePaymentDetails
(
AcademicId,
FeeHeadId,
FeeId,
LastPaymentDate,
LastPaidAmount,
RowNumber 
)
Select
  R.SourceId, 
  FHM.Id,
  FM.Id,
  MAX(R.CreatedDateTime) AS LastPaymentDate,
  ISNULL(SUM(RD.Amount), 0) AS LastPaidAmount,
  ROW_NUMBER() OVER (PARTITION BY R.SourceId, FHM.Id, FM.Id ORDER BY MAX(R.CreatedDateTime) DESC) AS RowNumber 


				FROM
					sFee.tReceipt R 
					INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id 
					INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id
					INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id
					INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FM.FeeHeadId
					
					WHERE 	
					--R.SourceId = SA.AcademicId AND  FHM.Id = FS.FeeHeadId
					(R.SourceTypeId = 2001)
					AND (R.IsObsolete = 0) 
					AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
					AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))
					AND (R.ReceiptDate <= @rUptoDate)
					AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
					
					GROUP BY R.SourceId,R.CreatedDateTime, FHM.Id ,FM.Id
					ORDER BY R.CreatedDateTime DESC
--Select * from #LastFeePaymentDetails
	--Added by dhananjay For Mantis : 42599
	
		SELECT 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			@rIsDetail AS IsDetail,
			@rIsFilter As IsFilter,
			@rIsHeader As IsHeader, 
			@rIsDisplayOrgGroup AS IsDisplayOrgGroup,
			SA.AcademicId,
			SA.RollNo,
			SA.Name,
			SA.Code,
			SA.ClassId,
			SA.DivisionId,
			SA.ClassName,
			SA.DivisionName,
			SA.DivisionOrder AS DivisionOrderIndex,
			SA.ClassOrderIndex AS ClassOrderIndex,
			SA.ClassName+' - '+SA.DivisionName AS ClassDivision,
			FS.Id AS FeeSetupId,
			ISNULL(FS.IsVariable,0)AS IsVariable,
			ISNULL(FS.Amount,0)AS Amount,
			ISNULL(FS.StartDate,'1900-01-01')AS StartDate,
			ISNULL(FS.EndDate,'1900-01-01')AS EndDate,
			ISNULL(FA.VariableAmount,0.00)AS FAAmount,
			ISNULL(FA.DiscountAmount,0.00)AS DiscountAmount,
			ISNULL(FA.AdditionalAmount,0.00)AS AdditionalAmount,
			ISNULL(FA.NotApplicableAmount,0.00)AS NotApplicableAmount,
			ISNULL(R.PaidAmount,0) AS PaidAmount,
			ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00)AS PendingAmount,
			ISNULL(FA.Remark,'') AS Remark,
			FS.ReceiptBookId,
			FS.FeeName,
			FS.FeeCode,
			FS.FeeOrderIndex,
			SA.OrgId,
			O.DisplayTitle AS OrgName,
			O.OrderIndex AS OrgOrderIndex,
			ISNULL(RBM.Title,'') AS ReceiptBookTitle,
			ISNULL(RBM.OrderIndex,0) AS ReceiptOrderIndex,
			SA.DepartmentId,
			SA.DepartmentName,
			SA.ExemptionTypeId,
			ISNULL(ETM.Title,'') AS ExemptionType,
			FHM.Id AS FeeHeadId,
			FHM.Title AS FeeHeadName,
			FHM.OrderIndex AS FeeHeadOrderIndex,
			@rFeeGroupId As FeeGroup,
			SA.OrgGroupBatchId AS BatchId,
			SA.BatchName AS BatchName,
			0.00 AS CancelAmount,
			0.00 AS Discount,
			SM.Title AS Status,
			FA.Remark AS Remark,
			LFPD.LastPaymentDate,
			LFPD.LastPaidAmount
		FROM 
			sStudent.vStudentAcademic SA
			INNER JOIN sStudent.tStudentAdmission tSA ON tSA.StudentId = SA.StudentId
			INNER JOIN 
			(
				SELECT 
					FS1.FeeId,
					FS1.Id,
					ISNULL(FS1.IsOptional,0)AS IsOptional,
					ISNULL(FS1.IsVariable,0)AS IsVariable,
					ISNULL(FS1.Amount,0)AS Amount,
					ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
					ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
					FS1.BatchId,
					ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
					SA1.AcademicId,
					FM.Title AS FeeName,
					FM.Code AS FeeCode,
					FM.FeeHeadId,
					FM.OrderIndex AS FeeOrderIndex
				FROM sFee.tFeeSetup FS1
				INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				AND ((SA1.ClassId=@rClassId) OR (@rClassId=0))
				AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
				WHERE 
					((FS1.ClassId=@rClassId) OR (@rClassId=0))
					AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
					AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
					AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
					AND (FS1.IsOptional=0)
					AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
					AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
					AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
					AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
					AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
					AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
					AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')  
					UNION ALL
					
				SELECT 
					FS1.FeeId,
					FS1.Id,
					ISNULL(FS1.IsOptional,0)AS IsOptional,
					ISNULL(FS1.IsVariable,0)AS IsVariable,
					ISNULL(FS1.Amount,0)AS Amount,
					ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
					ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
					FS1.BatchId,
					ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
					SA1.AcademicId,
					FM.Title AS FeeName,
					FM.Code As FeeCode,
					FM.FeeHeadId,
					FM.OrderIndex AS FeeOrderIndex
				FROM sFee.tFeeSetup FS1
			INNER JOIN sFee.tFeeOptional FO ON FO.FeeSetupId=FS1.Id 
			INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
			INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=FO.SourceId AND FS1.BatchId = SA1.BatchId
			AND SA1.ClassId=FS1.ClassId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				AND ((SA1.ClassId=@rClassId) OR (@rClassId=0)) 
				AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')  
			WHERE
				((FS1.ClassId=@rClassId) OR (@rClassId=0))
				AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
				AND (FS1.IsOptional=1)
				AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
				AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
				AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
				AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
				AND (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR @rOrgGroupId=0)
			) FS ON FS.AcademicId=SA.AcademicId
			LEFT JOIN sFee.tFeeAllocation FA ON FA.FeeSetupId=FS.Id AND FA.SourceId=SA.AcademicId
			LEFT JOIN
			(
				SELECT 
						ISNULL(SUM(RD.Amount),0) AS PaidAmount,RD.FeeSetupId ,R.SourceId
				FROM
						sFee.tReceipt R 
					INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id 
					INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id
					INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id
					INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=R.SourceId 
					INNER JOIN sStudent.tStudentAdmission tSA ON tSA.StudentId = SA1.StudentId
					AND ((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
					AND (SA1.ClassId=@rClassId OR @rClassId=0) 
					AND (SA1.DivisionId=@rDivisionId OR @rDivisionId=0)
				WHERE		
					(R.SourceTypeId = 2001)
					AND (R.IsObsolete = 0) 
					AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
					AND (SA1.OrgGroupBatchId = @rOrgGroupBatchId OR @rOrgGroupBatchId=0)
					AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
					AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))
					AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
					AND (R.ReceiptDate <= @rUptoDate)
					AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
					AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
					AND (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR @rOrgGroupId=0)
					AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')  
					--AND ((tSA.LeftDate > @rUptoDate) OR (tSA.LeftDate Is null))
					AND (tSA.AdmissionDate <= @rUptoDate)
						GROUP BY FeeSetupId,R.SourceId
			
			) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
			 INNER JOIN sSetup.tOrganizationMaster O ON SA.OrgId = O.Id
			 INNER JOIN sFee.tReceiptBookMaster RBM ON FS.ReceiptBookId=RBM.Id
			 INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FS.FeeHeadId	
			 
			 LEFT JOIN #LastFeePaymentDetails LFPD ON LFPD.AcademicId = R.SourceId AND LFPD.FeeHeadId = FS.FeeHeadId AND LFPD.RowNumber = 1 AND LFPD.FeeId = FS.FeeId
			 
			 LEFT JOIN sFee.tExemptionTypeMaster ETM ON ETM.Id = SA.ExemptionTypeId
			 LEFT JOIN sHostel.tAssignRoom AR ON  AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003 AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  AND ((AR.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) 
			 LEFT JOIN
			(SELECT AT.SourceId FROM sTransport.tAssignRoute AT 
			INNER JOIN sTransport.tBusRouteDestinationMaster BM ON BM.Id=AT.PickupDestinationId
			INNER JOIN sTransport.tBusRouteMaster B ON B.Id=BM.BusRouteId AND  AT.SourceTypeId=2003 AND ((B.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))) RT
			ON RT.SourceId = SA.StudentId AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) 
			INNER JOIN sStudent.tStatusMaster SM ON SA.StatusId = SM.Id
			WHERE	
			((@rIsExemption = 0 AND  1 = 1) OR (@rIsExemption = 1  AND  ISNULL(FA.DiscountAmount,0) > 0))
			AND	((SA.BatchId=@rBatchId) OR (@rBatchId=0))   
			AND	((SA.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))   
			AND (SA.StatusId=@rStatusId OR @rStatusId=0)
			--AND ((FS.StartDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
			AND ((SA.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
			AND ((SA.RollNo <= @rToRollNo) OR (@rToRollNo=0))
			AND ((SA.Code=@rCode) OR (@rCode=''))
			AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))		
			AND ((SA.ExemptionTypeId=@rExemptionTypeId) OR (@rExemptionTypeId=0))		
			AND ((SA.ClassId=@rClassId) OR (@rClassId=0))
			AND ((SA.DivisionId=@rDivisionId) OR (@rDivisionId=0))
			 AND (
					 (@rFilterId = 0) -- All
					 OR (@rFilterId = 2 AND isnull(AR.SourceId,0)!=0) -- Hostel
					 OR (@rFilterId = 3 AND isnull(RT.SourceId,0)!=0) -- Transport
					 OR ((@rFilterId =1) AND ((isnull(AR.SourceId,0)=0) AND (isnull(RT.SourceId,0)=0)))
					 )	
		AND (O.OrgGroupId = @rOrgGroupId OR @rOrgGroupId=0)
		AND (ISNULL(SA.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')  
		--AND ((tSA.LeftDate > @rUptoDate) OR (tSA.LeftDate Is null))
		AND (tSA.AdmissionDate <= @rUptoDate)
		 AND ((SA.ClassStatusId=@rClassStatusId) OR (@rClassStatusId=0))  	
		Order by  FHM.OrderIndex,FS.FeeOrderIndex,SA.RollNo
	
	
END
GO
PRINT N'Creating Procedure [sSecurity].[pMigrationModulePermissionAdd]...';


GO
CREATE PROCEDURE [sSecurity].[pMigrationModulePermissionAdd]
          
   @rOrgGroupId smallint,
   @rXML nvarchar(max)
 
AS
SET NOCOUNT ON
DECLARE @lInterrorCode INT
DECLARE @loDoc INT

BEGIN

	BEGIN TRY
	BEGIN TRANSACTION	
	
	EXEC sp_xml_preparedocument @loDoc OUTPUT,@rXML
	CREATE TABLE #ListofData(AutoId int, [Key] VARCHAR(MAX),[Status] bit,Value VARCHAR(MAX),ERPProductId int,OrgGroupId int)
	insert into #ListofData
		select E.AutoId,E.[Key],E.[Status],E.Value,E.ERPProductId,E.OrgGroupId
		from
		(
			SELECT AutoId,[Key],[Status],Value,ERPProductId,OrgGroupId FROM
			OPENXML (@loDoc, '/Modules/Module', 2)
			WITH (
					AutoId int,
					[Key] VARCHAR(MAX), 
					[Status] bit,
					Value VARCHAR(MAX),
					ERPProductId int,
					OrgGroupId int
				)	
		)E 	
		
	 -- UPSERT logic: Update if AutoId > 0 and exists, else insert
    MERGE sSecurity.tMigrationModulePermission AS target
    USING (
        SELECT AutoId, [Key], [Status], Value, ERPProductId, OrgGroupId
        FROM #ListofData
    ) AS source
    ON target.OrgGroupId = source.OrgGroupId AND target.[Key] = source.[Key]
    WHEN MATCHED AND source.AutoId > 0 THEN
        UPDATE SET
            target.Value = source.Value,
            target.ERPProductId = source.ERPProductId,
            target.[Status] = source.[Status],
			target.UpdatedDateTime = GETDATE()
    WHEN NOT MATCHED BY TARGET THEN
        INSERT (OrgGroupId, [Key], Value, ERPProductId, [Status])
        VALUES (source.OrgGroupId, source.[Key], source.Value, source.ERPProductId, source.[Status]);

	--INSERT INTO sSecurity.tMigrationModulePermission(OrgGroupId,[Key],Value,ERPProductId,[Status])
	--SELECT OrgGroupId,[Key],Value,ERPProductId,[Status] FROM #ListofData WHERE [Status] = 1

	Drop Table #ListofData

	SELECT 1 AS Result
	COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
	
END
GO
PRINT N'Creating Procedure [sSecurity].[pMigrationModulePermissionGet]...';


GO
CREATE PROCEDURE [sSecurity].[pMigrationModulePermissionGet]
       @rOrgGroupId int

AS
SET NOCOUNT ON
BEGIN
	SELECT 
		MMP.AutoId,
		ISNULL(MMP.OrgGroupId,0) AS OrgGroupId ,
		ISNULL(MMP.[Key],'') AS [Key] ,
		ISNULL(MMP.Value,'') AS Value,
		ISNULL(MMP.[Status],0) AS [Status],
		ISNULL(MMP.ERPProductId,0) AS ERPProductId
	FROM 
		sSecurity.tMigrationModulePermission MMP
	WHERE MMP.OrgGroupId = 1

	UNION ALL 

	SELECT 
		MMP.AutoId,
		ISNULL(MMP.OrgGroupId,0) AS OrgGroupId ,
		ISNULL(MMP.[Key],'') AS [Key] ,
		ISNULL(MMP.Value,'') AS Value,
		ISNULL(MMP.[Status],0) AS [Status],
		ISNULL(MMP.ERPProductId,0) AS ERPProductId
	FROM 
		sSecurity.tMigrationModulePermission MMP
	WHERE MMP.OrgGroupId = @rOrgGroupId
END
GO
PRINT N'Altering Procedure [sCommon].[pTableRowIdGet]...';


GO
ALTER PROCEDURE [sCommon].[pTableRowIdGet]
	@rOrgId [bigint],
	@rTableTitle [nvarchar](100),
	@rIsCurrentNumber [bit] = 0,
	@rSeed [bigint] = 1,
	@rIncrement [bigint] = 1,
	@outNextNumber [bigint] OUTPUT  
WITH EXECUTE AS CALLER
AS
BEGIN
	SET NOCOUNT ON;

	-- Check if record exists
	IF NOT EXISTS(SELECT 1
				    FROM sCommon.tTableRowId WITH (NOLOCK) --(ROWLOCK)
			        WHERE TableTitle = @rTableTitle AND OrgId = @rOrgId)
	BEGIN
		RAISERROR('Add Table RowId detail in table-Row for TableTitle [%s] and OrgId [%d] not found in tTableRowId.',16, 1, @rTableTitle, @rOrgId);
	END

	-- Call the modify procedure
	EXECUTE sCommon.pTableRowIdModify
		@rOrgId,
		@rTableTitle = @rTableTitle,
		@rIsCurrentNumber = @rIsCurrentNumber,
		@rSeed = @rSeed,
		@rIncrement = @rIncrement,
		@rNextNumber = @outNextNumber OUTPUT;
	
END
GO
PRINT N'Altering Procedure [sFee].[pChargeReceiptAdd]...';


GO
ALTER PROCEDURE [sFee].[pChargeReceiptAdd] 
	@rId BIGINT
	,@rSourceTypeId SMALLINT
	,@rSourceId BIGINT
	,@rGuestName NVARCHAR(200)
	,@rReceiptBookId INT
	,@rRemark NVARCHAR(200)
	,@rReceiptNumber INT
	,@rReceiptDate DATE
	,@rPayTypeId TINYINT
	,@rChequeNo NVARCHAR(20)
	,@rBankName NVARCHAR(200)
	,@rIsObsolete BIT
	,@rOrgId INT
	,@rBatchId INT
	,@rOrgGroupBatchId INT
	,@rCreatedUserId BIGINT
	,@rReceiptAmount DECIMAL(12, 2)
	,@rChequeDate DATE = ''

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
		IF (@rId = 0)
		BEGIN
			--  EXECUTE sCommon.pPrefixSetupNextNumberGet @rOrgId = @rOrgId, @rPrefixFunctionalityId = 2002,@rStoreLocationId = 0, @rNextNumber  = @rReceiptNumber OUTPUT
			--SET @rReceiptNumber = ISNULL(@rReceiptNumber, '-300')
			--		IF @rReceiptNumber = '-300'
			--	  BEGIN
			--		SELECT -300 AS Result, '' AS ReceiptNumber, 0 AS Id 
			--		RETURN
			--	  END
			SELECT @rOrgGroupBatchId = OrgGroupBatchId
			FROM sSetup.tBatchMaster
			WHERE Id = @rBatchId

			IF (@rReceiptNumber <> 0)
			BEGIN
				IF EXISTS (
						SELECT 1
						FROM sFee.tChargeReceipt
						WHERE ReceiptNumber = @rReceiptNumber
							AND ChargeReceiptBookId = @rReceiptBookId
							AND OrgGroupBatchId = @rOrgGroupBatchId
						)
				BEGIN
					SELECT - 102 AS Result
					RETURN
				END
			END
			ELSE
				SET @rReceiptNumber = sFee.fChargeReceiptNumberGet(@rReceiptBookId, @rOrgGroupBatchId)

			BEGIN TRANSACTION

			DECLARE @lNextNumber BIGINT

			EXECUTE sCommon.pTableRowIdGet @rOrgId
				,'sFee.tChargeReceipt'
				,0
				,1
				,1
				,@outNextNumber = @lNextNumber OUTPUT

			INSERT INTO sFee.tChargeReceipt (
				Id
				,SourceTypeId
				,SourceId
				,GuestName
				,ChargeReceiptBookId
				,Remark
				,ReceiptNumber
				,ReceiptDate
				,PayTypeId
				,ChequeNo
				,BankName
				,IsObsolete
				,CreatedUserId
				,CreatedDateTime
				,OrgId
				,BatchId
				,OrgGroupBatchId
				,ReceiptAmount
				,ChequeDate
				)
			VALUES (
				@lNextNumber
				,@rSourceTypeId
				,@rSourceId
				,@rGuestName
				,@rReceiptBookId
				,@rRemark
				,@rReceiptNumber
				,@rReceiptDate
				,@rPayTypeId
				,@rChequeNo
				,@rBankName
				,@rIsObsolete
				,@rCreatedUserId
				,sCommon.fGetDate()
				,@rOrgId
				,@rBatchId
				,@rOrgGroupBatchId
				,@rReceiptAmount
				,@rChequeDate
				)
			
			COMMIT TRANSACTION
		END
		ELSE
		BEGIN
			BEGIN TRANSACTION
			SET @lNextNumber = @rId

			UPDATE sFee.tChargeReceipt
			SET SourceTypeId = @rSourceTypeId
				,SourceId = @rSourceId
				,GuestName = @rGuestName
				,ChargeReceiptBookId = @rReceiptBookId
				,Remark = @rRemark
				,ReceiptNumber = @rReceiptNumber
				,ReceiptDate = @rReceiptDate
				,PayTypeId = @rPayTypeId
				,ChequeNo = @rChequeNo
				,BankName = @rBankName
				,IsObsolete = @rIsObsolete
				,UpdatedUserId = @rCreatedUserId
				,UpdatedDateTime = sCommon.fGetDate()
				,ReceiptAmount = @rReceiptAmount
				,ChequeDate = @rChequeDate
			WHERE Id = @rId
			
			COMMIT TRANSACTION
		END
		SELECT @lNextNumber AS Result
	END TRY

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


GO
ALTER PROCEDURE [sFee].[pFeeGenerateReport]
	
	@rId bigint,
	@rTitle nvarchar(50),
	@rColumnName nvarchar(max) = '',
	@rOrderBy nvarchar(max) = 'ReceiptNumber',
	@rOrgGroupBatchId int,
	@rOrgId smallint,
	@rBatchId int,
	@rCurrentOrgId smallint,
	@rCode [nvarchar](20) = '',
	@rFirstName [nvarchar](50) = '',	
	@rLastName [nvarchar](50) = '',
	--@rClassId nvarchar(max) = '',
	@rDivisionId nvarchar(max) = '',
	@rReceiptBookId nvarchar(max) = '',
	@rFromReceiptDate Date = '0001-01-01',
	@rToReceiptDate Date = '9999-12-31',
	@rFromReceiptNo int,
	@rToReceiptNo int,
	@rIsObsolete bit,
	@rIsCommon bit,
	@rCreatedUserId bigint,
	@rInsertUserId bigint,
	@rDropDownStatusId int,
	@rDropDownClassId int,
	@rDropDownDivisionId int,
	@rDropDownReceiptBookId int,
	@rIsCommonForOrg bit,
	@rAdmissionCategoryId int = 0
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	 BEGIN TRANSACTION	
	
	IF(@rFromReceiptDate IS NULL)
			SET @rFromReceiptDate='0001-01-01'
	IF(@rToReceiptDate IS NULL)
		SET @rToReceiptDate='9999-12-31'
	
	IF(@rTitle != '' AND @rId = 0)
	BEGIN
	DECLARE @lNextNumber BIGINT     
	EXECUTE sCommon.pTableRowIdGet @rCurrentOrgId, 'sFee.tFeeCustomSearch', 0, 1, 1,@outNextNumber = @lNextNumber output

	INSERT INTO sFee.tFeeCustomSearch
		(
			Id,
			Title,
			ColumnName,
			OrderBy,
			OrgGroupBatchId,
			OrgId,
			BatchId,
			Code,
			FirstName,	
			LastName,
			DivisionId,
			ReceiptBookId,
			FromReceiptDate,
			ToReceiptDate,
			FromReceiptNo,
			ToReceiptNo,
			IsObsolete,
			IsCommon,
			UserId,
			CreatedUserId,
			CreatedDateTime,
			IsCommonForOrg
		)
	VALUES
		(
			@lNextNumber,
			@rTitle,
			@rColumnName,
			@rOrderBy,
			@rOrgGroupBatchId,
			@rOrgId,
			@rBatchId,
			@rCode,
			@rFirstName,	
			@rLastName,
			@rDivisionId,
			@rReceiptBookId,
			@rFromReceiptDate,
			@rToReceiptDate,
			@rFromReceiptNo,
			@rToReceiptNo,
			@rIsObsolete,
			@rIsCommon,
			@rCreatedUserId,
			@rInsertUserId,
			sCommon.fGetDate(),
			@rIsCommonForOrg
		)
		--SELECT @lNextNumber AS Result
	END
	IF(@rId > 0)
	BEGIN
		Select
				@rColumnName=ColumnName,
				@rOrderBy=OrderBy,
				@rOrgGroupBatchId=OrgGroupBatchId,
				@rOrgId=OrgId,
				@rBatchId=BatchId,
				@rCode=Code,
				@rFirstName=FirstName,	
				@rLastName=LastName,
				@rDivisionId=DivisionId,
				@rReceiptBookId=ReceiptBookId,
				@rFromReceiptDate=FromReceiptDate,
				@rToReceiptDate=ToReceiptDate,
				@rFromReceiptNo=FromReceiptNo,
				@rToReceiptNo=ToReceiptNo,
				@rIsObsolete=IsObsolete,
				@rCreatedUserId=UserId
		FROM
			sFee.tFeeCustomSearch
		WHERE
			Id=@rId
	END
	 
		SET @rColumnName=Replace(@rColumnName,'ID No','Code')
		SET @rOrderBy=Replace(@rOrderBy,'ID No','Code')
	  
		SET @rColumnName=Replace(@rColumnName,'GR No','Code')
		SET @rOrderBy=Replace(@rOrderBy,'GR No','Code')
	 
		DECLARE @Sql nvarchar(MAX)
		
		SET @rCode = sCommon.fSearchStringGet(@rCode)
		SET @rFirstName = sCommon.fSearchStringGet(@rFirstName)
		SET @rLastName = sCommon.fSearchStringGet(@rLastName)
	
		SELECT 
				*
		INTO sFee.tTempFee
		FROM sFee.vFeeCustomSearch FCS
		WHERE 
				(FCS.OrgGroupBatchId = @rOrgGroupBatchId)
				AND	((FCS.OrgId = @rOrgId) OR (@rOrgId=0))
				AND ((FCS.BatchId = @rBatchId) OR (@rBatchId=0))
				AND ((FCS.Code Like @rCode + '%') OR (@rCode = ''))
				AND ((FCS.FirstName Like @rFirstName  + '%') OR (@rFirstName = ''))	 			 
				AND ((FCS.LastName Like @rLastName + '%')OR(@rLastName = ''))
				AND ((FCS.ReceiptNumber >= @rFromReceiptNo) OR (@rFromReceiptNo=0))
				AND ((FCS.ReceiptNumber <= @rToReceiptNo) OR (@rToReceiptNo=0))
				AND ((ISNULL(FCS.ReceiptDate,'0001-01-01') >= @rFromReceiptDate) OR (ISNULL(@rFromReceiptDate,'') = ''))
				AND ((ISNULL(FCS.ReceiptDate,'9999-12-31') <= @rToReceiptDate) OR (ISNULL(@rToReceiptDate,'') = ''))
				--AND ((ISNULL(FCS.EndDate,'9999-12-31') <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
				--AND (FCS.ClassId In( SELECT item FROM  sCommon.fnsplit(@rClassId,','))OR @rClassId=''))
			    
				AND (FCS.DivisionId In( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionId,','))OR @rDivisionId='')
			         	          
				AND (FCS.FeeReceiptBookId In( SELECT cast(item as int) FROM  sCommon.fnsplit(@rReceiptBookId,','))OR @rReceiptBookId='')	
				AND ((FCS.CreatedUserId=@rCreatedUserId) OR (@rCreatedUserId=0))
				AND (FCS.IsObsolete=@rIsObsolete)
				AND ((FCS.StatusId = @rDropDownStatusId) OR (@rDropDownStatusId=0))
				AND ((FCS.ClassId = @rDropDownClassId) OR (@rDropDownClassId=0))
				AND ((FCS.DivisionId = @rDropDownDivisionId) OR (@rDropDownDivisionId=0))
				AND ((FCS.FeeReceiptBookId = @rDropDownReceiptBookId) OR (@rDropDownReceiptBookId=0))
				AND ((FCS.AdmissionCategoryId = @rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
	     
	     
		SET @rColumnName=Replace(@rColumnName,',ID No',',Code')
		SET @rOrderBy=Replace(@rOrderBy,'ID No','Code')
    
		SET @rColumnName=Replace(@rColumnName,',GR No',',Code')
		SET @rOrderBy=Replace(@rOrderBy,'GR No','Code')
		
		SET @rColumnName=Replace(@rColumnName,'Fees Category','[Fees Category]') --mantis: 42471, add
		SET @rOrderBy=Replace(@rOrderBy,'Fees Category','[Fees Category]') --mantis: 42471, add
			
		 
		--SET @rOrderBy=Replace(@rOrderBy,',Code',',Code AS [ID No]')    
		
		
		SET @sql=
		'SELECT '+
		@rColumnName+' 
		FROM sFee.tTempFee ORDER BY '+@rOrderBy
			 
		 --print @sql;
		exec(@Sql)
		
		DROP Table sFee.tTempFee
	
		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

DECLARE @lIsEnableLog bit = 1 -- Set to 1 If want to add log for receipt add process

BEGIN
	BEGIN TRY
		
		IF(@lIsEnableLog = 1)
		BEGIN
		 INSERT INTO [sFee].[tFeeReceiptLog]
		 VALUES (@rOrgId,@rId,@rSourceTypeId,@rSourceId,@rReceiptNumber,@rReceiptDate,@rReceiptAmount
			    ,@rTotalReceiptAmount,@rDiscountAmount,@rPayTypeId,@rChequeNo,@rBankName,@rReceiptBookId,@rIsObsolete,@rCreatedUserId
			    ,@rBatchId,@rOrgGroupBatchId,@rRemark,@rReceiptDetailXml,@rChequeDate,@rCharge,@rFeeInvoiceId,@rCollectionGroupId
			    ,@rDepositedLedgerId,@rPaymentTransactionId,@rReceiptPrintGroupId,@rIsDiscountCoupon,GETDATE(),'Receipt SP Main Process Start')
		END

		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 WITH (NOLOCK) 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 WITH (NOLOCK) where ReceiptNumber=@rReceiptNumber AND ReceiptBookId=@rReceiptBookId AND  PayTypeId=@rPayTypeId AND OrgGroupBatchId = @rOrgGroupBatchId)
					BEGIN
						SELECT -102 AS Result
						RETURN	
					END
				END
				-- #Start Mantis Id : 0036287
				ELSE IF(@lConfigValue='Continuous Batch')
				BEGIN
					IF EXISTS(SELECT 1 from sFee.tReceipt WITH (NOLOCK) where ReceiptNumber=@rReceiptNumber AND ReceiptBookId=@rReceiptBookId)
					BEGIN
						SELECT -102 AS Result
						RETURN	
					END
				END
				-- #End Mantis Id : 0036287

				-- Mantis - 0030695
				IF(@rChequeNo <> '' AND @lConfigValue1 = 'True')
				BEGIN
					IF EXISTS(SELECT 1 from sFee.tReceipt WITH (NOLOCK) where ChequeNo=@rChequeNo)
					BEGIN
						SELECT -103 AS Result
						RETURN	
					END
				END
				-- Mantis - 0030695

				-- For Mantis 0038951, By Foram
				IF EXISTS(SELECT 1 FROM sFee.tPostDatePayment WITH (NOLOCK) WHERE BatchId = @rBatchId AND OrgGroupBatchId = @rOrgGroupBatchId 
														AND SourceTypeId = @rSourceTypeId AND SourceId = @rSourceId AND ReceiptBookId = @rReceiptBookId 
														AND PayTypeId = @rPayTypeId AND ChequeNo = @rChequeNo AND BankName = @rBankName AND Amount = @rTotalReceiptAmount AND ReceiptId > 0)
				BEGIN
					SELECT -104 AS Result
					RETURN	
				END
				-- For Mantis 0038951, By Foram
			END
			ELSE
			BEGIN
				IF(@lConfigValue='ReceiptBookWise')
				BEGIN
					IF EXISTS(SELECT 1 from sFee.tReceipt WITH (NOLOCK) 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 WITH (NOLOCK) where ReceiptNumber=@rReceiptNumber AND ReceiptBookId=@rReceiptBookId AND  PayTypeId=@rPayTypeId AND OrgGroupBatchId = @rOrgGroupBatchId AND Id != @rId)
					BEGIN
						SELECT -102 AS Result
						RETURN	
					END
				END
				-- #Start Mantis Id : 0036287
				ELSE IF(@lConfigValue='Continuous Batch')
				BEGIN
					IF EXISTS(SELECT 1 from sFee.tReceipt WITH (NOLOCK) where ReceiptNumber=@rReceiptNumber AND ReceiptBookId=@rReceiptBookId AND Id != @rId)
					BEGIN
						SELECT -102 AS Result
						RETURN	
					END
				END
				-- #End Mantis Id : 0036287

				-- Mantis - 0030695
				IF(@rChequeNo <> '' AND @lConfigValue1 = 'True')
				BEGIN
					IF EXISTS(SELECT 1 from sFee.tReceipt WITH (NOLOCK) 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	

		IF(@lIsEnableLog = 1)
		BEGIN
			INSERT INTO [sFee].[tFeeReceiptLog]
			 VALUES
			 (@rOrgId,@rId,@rSourceTypeId,@rSourceId,@rReceiptNumber,@rReceiptDate,@rReceiptAmount
				,@rTotalReceiptAmount,@rDiscountAmount,@rPayTypeId,@rChequeNo,@rBankName,@rReceiptBookId,@rIsObsolete,@rCreatedUserId
				,@rBatchId,@rOrgGroupBatchId,@rRemark,@rReceiptDetailXml,@rChequeDate,@rCharge,@rFeeInvoiceId,@rCollectionGroupId
				,@rDepositedLedgerId,@rPaymentTransactionId,@rReceiptPrintGroupId,@rIsDiscountCoupon,GETDATE(),'Receipt No Generated and pReceiptAddValidate SP Start')
		END

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

		IF(@lIsEnableLog = 1)
		BEGIN
			INSERT INTO [sFee].[tFeeReceiptLog]
			 VALUES
			 (@rOrgId,@rId,@rSourceTypeId,@rSourceId,@rReceiptNumber,@rReceiptDate,@rReceiptAmount
				,@rTotalReceiptAmount,@rDiscountAmount,@rPayTypeId,@rChequeNo,@rBankName,@rReceiptBookId,@rIsObsolete,@rCreatedUserId
				,@rBatchId,@rOrgGroupBatchId,@rRemark,@rReceiptDetailXml,@rChequeDate,@rCharge,@rFeeInvoiceId,@rCollectionGroupId
				,@rDepositedLedgerId,@rPaymentTransactionId,@rReceiptPrintGroupId,@rIsDiscountCoupon,GETDATE(),'pReceiptAddValidate SP End : ' + CAST(@lIsCreated AS NVARCHAR(10)))
		END

		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
		IF(@lIsCreated = -2)	-- For Mantis 0035484 by Foram
 		BEGIN
			SELECT -503 AS Result
			RETURN
		END
	END TRY
	BEGIN CATCH 
		SELECT -1 AS Result, ERROR_Message()
	END CATCH	

	BEGIN TRY
	
	IF(@rId = 0)	
	BEGIN
		
		--Added By Dhruv
		IF(@lConfigValue='ReceiptBookWise')
		BEGIN
			IF EXISTS(SELECT 1 from sFee.tReceipt WITH (NOLOCK) 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 WITH (NOLOCK) where ReceiptNumber=@rReceiptNumber AND ReceiptBookId=@rReceiptBookId AND  PayTypeId=@rPayTypeId AND OrgGroupBatchId = @rOrgGroupBatchId)
			BEGIN
				SELECT -102 AS Result
				RETURN	
			END
		END
		--Added By Dhruv

		-- #Start Mantis Id : 0036287
			ELSE IF(@lConfigValue='Continuous Batch')
			BEGIN
			IF EXISTS(SELECT 1 from sFee.tReceipt WITH (NOLOCK) where ReceiptNumber=@rReceiptNumber AND ReceiptBookId=@rReceiptBookId)
			BEGIN
				SELECT -102 AS Result
				RETURN	
			END
		END
			-- #End Mantis Id : 0036287

		-- Mantis - 0030695
		IF(@rChequeNo <> '' AND @lConfigValue1 = 'True')
		BEGIN
			IF EXISTS(SELECT 1 from sFee.tReceipt WITH (NOLOCK) where ChequeNo=@rChequeNo)
			BEGIN
				SELECT -103 AS Result
				RETURN	
			END
		END
		-- Mantis - 0030695

		-- For Mantis 0038951, By Foram
		IF EXISTS(SELECT 1 FROM sFee.tPostDatePayment WITH (NOLOCK) WHERE BatchId = @rBatchId AND OrgGroupBatchId = @rOrgGroupBatchId 
												AND SourceTypeId = @rSourceTypeId AND SourceId = @rSourceId AND ReceiptBookId = @rReceiptBookId 
												AND PayTypeId = @rPayTypeId AND ChequeNo = @rChequeNo AND BankName = @rBankName AND Amount = @rTotalReceiptAmount AND ReceiptId > 0)
		BEGIN
			SELECT -104 AS Result
			RETURN	
		END
		-- For Mantis 0038951, By Foram

		Declare @lSourceTypeId int 
		SET @lSourceTypeId =(select ISNULL(SourceTypeId,0) from sSecurity.tUser WITH (NOLOCK) 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 

		

		BEGIN TRANSACTION

		DECLARE @lNextNumber BIGINT  , @lMaxReceiptId bigint = 0  
		--EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sFee.tReceipt', 0, 1, 1,@outNextNumber = @lNextNumber output
		SELECT @lMaxReceiptId = ISNULL(MAX(R.Id), 0) FROM sFee.tReceipt R WITH (NOLOCK) INNER JOIN sSetup.tBatchMaster BM WITH (NOLOCK)  ON BM.id = R.BatchId WHERE Bm.OrgId = @rOrgId

		IF EXISTS(SELECT 1 FROM sAudit.tReceiptDelete WITH (NOLOCK) WHERE Id = @lMaxReceiptId)
		BEGIN
			SELECT @lMaxReceiptId = ISNULL(MAX(RD.Id), 0) FROM sAudit.tReceiptDelete RD WITH (NOLOCK) INNER JOIN sSetup.tBatchMaster BM WITH (NOLOCK)  ON BM.Id = RD.BatchId WHERE Bm.OrgId = @rOrgId
		END

		IF(@lMaxReceiptId = 0)
		BEGIN
			IF(@lIsEnableLog = 1)
			BEGIN
				INSERT INTO [sFee].[tFeeReceiptLog]
				VALUES
				(@rOrgId,@rId,@rSourceTypeId,@rSourceId,@rReceiptNumber,@rReceiptDate,@rReceiptAmount
					,@rTotalReceiptAmount,@rDiscountAmount,@rPayTypeId,@rChequeNo,@rBankName,@rReceiptBookId,@rIsObsolete,@rCreatedUserId
					,@rBatchId,@rOrgGroupBatchId,@rRemark,@rReceiptDetailXml,@rChequeDate,@rCharge,@rFeeInvoiceId,@rCollectionGroupId
					,@rDepositedLedgerId,@rPaymentTransactionId,@rReceiptPrintGroupId,@rIsDiscountCoupon,GETDATE(),'pTableRowIdGet SP Start')
			END

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

			IF(@lIsEnableLog = 1)
			BEGIN
				INSERT INTO [sFee].[tFeeReceiptLog]
				 VALUES
				 (@rOrgId,@rId,@rSourceTypeId,@rSourceId,@rReceiptNumber,@rReceiptDate,@rReceiptAmount
					,@rTotalReceiptAmount,@rDiscountAmount,@rPayTypeId,@rChequeNo,@rBankName,@rReceiptBookId,@rIsObsolete,@rCreatedUserId
					,@rBatchId,@rOrgGroupBatchId,@rRemark,@rReceiptDetailXml,@rChequeDate,@rCharge,@rFeeInvoiceId,@rCollectionGroupId
					,@rDepositedLedgerId,@rPaymentTransactionId,@rReceiptPrintGroupId,@rIsDiscountCoupon,GETDATE(),CAST(@lNextNumber AS NVARCHAR(100))+'-pTableRowIdGet SP End & Receipt Add Start')
			END
		END
		ELSE
		BEGIN
			SET @lNextNumber =  @lMaxReceiptId + 1 
		END
		
	
		IF(@lIsEnableLog = 1)
		BEGIN
			INSERT INTO [sFee].[tFeeReceiptLog]
			 VALUES
			 (@rOrgId,@rId,@rSourceTypeId,@rSourceId,@rReceiptNumber,@rReceiptDate,@rReceiptAmount
				,@rTotalReceiptAmount,@rDiscountAmount,@rPayTypeId,@rChequeNo,@rBankName,@rReceiptBookId,@rIsObsolete,@rCreatedUserId
				,@rBatchId,@rOrgGroupBatchId,@rRemark,@rReceiptDetailXml,@rChequeDate,@rCharge,@rFeeInvoiceId,@rCollectionGroupId
				,@rDepositedLedgerId,@rPaymentTransactionId,@rReceiptPrintGroupId,@rIsDiscountCoupon,GETDATE(),CAST(@lNextNumber AS NVARCHAR(100))+'- ReceiptId - Receipt Add Start')
		END

		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
		   --Added for default value
		    ,IsChequeCleared
			,ChequeClearDate
			,AmountAfterDiscount
			,CGSTPercentage
			,SGSTPercentage
			,CGSTAmount
			,SGSTAmount
			,CancelStatusId
			,CancelStatusRemark
			,FirmReceiptBookId
			,TaxPercentage
			,CancelDateTime
        )
		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
			,0,NULL,0,0,0,0,0,0,NULL,0,0,NULL
		)
		
		IF(@lIsEnableLog = 1)
		BEGIN
			INSERT INTO [sFee].[tFeeReceiptLog]
			VALUES
			(@rOrgId,@rId,@rSourceTypeId,@rSourceId,@rReceiptNumber,@rReceiptDate,@rReceiptAmount
			,@rTotalReceiptAmount,@rDiscountAmount,@rPayTypeId,@rChequeNo,@rBankName,@rReceiptBookId,@rIsObsolete,@rCreatedUserId
			,@rBatchId,@rOrgGroupBatchId,@rRemark,@rReceiptDetailXml,@rChequeDate,@rCharge,@rFeeInvoiceId,@rCollectionGroupId
			,@rDepositedLedgerId,@rPaymentTransactionId,@rReceiptPrintGroupId,@rIsDiscountCoupon,GETDATE(),'Receipt Add End and Receipt Detail Start') 
		END

		INSERT INTO sFee.tReceiptDetail
		(
		   ReceiptId,
		   FeeSetupId,
		   Amount
        )
        SELECT  	
		  @lNextNumber,
		  FeeSetupId,
		  Amount
		FROM OPENXML (@loDoc, '/Table/ReceiptDetail', 1)
		WITH ( 
				FeeSetupId int,
				Amount decimal(12,2)
			  ) 
		
		 IF(@lIsEnableLog = 1)
		         BEGIN
		         	INSERT INTO [sFee].[tFeeReceiptLog]
		         	VALUES
		         	(@rOrgId,@rId,@rSourceTypeId,@rSourceId,@rReceiptNumber,@rReceiptDate,@rReceiptAmount
		         	,@rTotalReceiptAmount,@rDiscountAmount,@rPayTypeId,@rChequeNo,@rBankName,@rReceiptBookId,@rIsObsolete,@rCreatedUserId
		         	,@rBatchId,@rOrgGroupBatchId,@rRemark,@rReceiptDetailXml,@rChequeDate,@rCharge,@rFeeInvoiceId,@rCollectionGroupId
		         	,@rDepositedLedgerId,@rPaymentTransactionId,@rReceiptPrintGroupId,@rIsDiscountCoupon,GETDATE(),'Receipt Detail End') 
		         END

		SELECT @lNextNumber AS Result
		EXEC sp_xml_removedocument @loDoc
		
	    IF (@rCharge > 0)
		BEGIN
		    IF(@lIsEnableLog = 1)
		    BEGIN
		    	INSERT INTO [sFee].[tFeeReceiptLog]
		    	VALUES
		    	(@rOrgId,@rId,@rSourceTypeId,@rSourceId,@rReceiptNumber,@rReceiptDate,@rReceiptAmount
		    	,@rTotalReceiptAmount,@rDiscountAmount,@rPayTypeId,@rChequeNo,@rBankName,@rReceiptBookId,@rIsObsolete,@rCreatedUserId
		    	,@rBatchId,@rOrgGroupBatchId,@rRemark,@rReceiptDetailXml,@rChequeDate,@rCharge,@rFeeInvoiceId,@rCollectionGroupId
		    	,@rDepositedLedgerId,@rPaymentTransactionId,@rReceiptPrintGroupId,@rIsDiscountCoupon,GETDATE(),'Charge Add Start') 
		    END
			
			EXEC [sFee].[pReceiptChargeAdd] @rSourceTypeId,@rSourceId,@lNextNumber,@lCreatedUserId,@rOrgId,@rBatchId,@rCharge,@rReceiptBookId
			
			IF(@lIsEnableLog = 1)
		    BEGIN
		    	INSERT INTO [sFee].[tFeeReceiptLog]
		    	VALUES
		    	(@rOrgId,@rId,@rSourceTypeId,@rSourceId,@rReceiptNumber,@rReceiptDate,@rReceiptAmount
		    	,@rTotalReceiptAmount,@rDiscountAmount,@rPayTypeId,@rChequeNo,@rBankName,@rReceiptBookId,@rIsObsolete,@rCreatedUserId
		    	,@rBatchId,@rOrgGroupBatchId,@rRemark,@rReceiptDetailXml,@rChequeDate,@rCharge,@rFeeInvoiceId,@rCollectionGroupId
		    	,@rDepositedLedgerId,@rPaymentTransactionId,@rReceiptPrintGroupId,@rIsDiscountCoupon,GETDATE(),'Charge Add End') 
		    END
		END
			
		DECLARE @lIsServiceTaxApplicable bit
	    DECLARE @lServiceTaxPercentage decimal(6,2)
	
	    SELECT @lIsServiceTaxApplicable = ISNULL(IsServiceTaxApplicable,0),@lServiceTaxPercentage = ISNULL(ServiceTaxPercentage,0) 
		FROM sFee.tReceiptBookMaster WITH (NOLOCK) where Id = @rReceiptBookId
		
		IF (@lIsServiceTaxApplicable > 0 AND @lServiceTaxPercentage > 0)
		BEGIN
			IF(@lIsEnableLog = 1)
			BEGIN
				INSERT INTO [sFee].[tFeeReceiptLog]
				VALUES
				(@rOrgId,@rId,@rSourceTypeId,@rSourceId,@rReceiptNumber,@rReceiptDate,@rReceiptAmount
				,@rTotalReceiptAmount,@rDiscountAmount,@rPayTypeId,@rChequeNo,@rBankName,@rReceiptBookId,@rIsObsolete,@rCreatedUserId
				,@rBatchId,@rOrgGroupBatchId,@rRemark,@rReceiptDetailXml,@rChequeDate,@rCharge,@rFeeInvoiceId,@rCollectionGroupId
				,@rDepositedLedgerId,@rPaymentTransactionId,@rReceiptPrintGroupId,@rIsDiscountCoupon,GETDATE(),'pReceiptServiceTaxAdd SP Add Start')
			END

			EXEC [sFee].[pReceiptServiceTaxAdd] @rSourceTypeId,@rSourceId,@lNextNumber,@lCreatedUserId,@rOrgId,@rBatchId,@lServiceTaxPercentage
			
			IF(@lIsEnableLog = 1)
			BEGIN
				INSERT INTO [sFee].[tFeeReceiptLog]
				VALUES
				(@rOrgId,@rId,@rSourceTypeId,@rSourceId,@rReceiptNumber,@rReceiptDate,@rReceiptAmount
				,@rTotalReceiptAmount,@rDiscountAmount,@rPayTypeId,@rChequeNo,@rBankName,@rReceiptBookId,@rIsObsolete,@rCreatedUserId
				,@rBatchId,@rOrgGroupBatchId,@rRemark,@rReceiptDetailXml,@rChequeDate,@rCharge,@rFeeInvoiceId,@rCollectionGroupId
				,@rDepositedLedgerId,@rPaymentTransactionId,@rReceiptPrintGroupId,@rIsDiscountCoupon,GETDATE(),'pReceiptServiceTaxAdd SP Add End')
			END
		END

	    IF(@lIsEnableLog = 1)
		BEGIN
			INSERT INTO [sFee].[tFeeReceiptLog]
			VALUES
			(@rOrgId,@rId,@rSourceTypeId,@rSourceId,@rReceiptNumber,@rReceiptDate,@rReceiptAmount
			,@rTotalReceiptAmount,@rDiscountAmount,@rPayTypeId,@rChequeNo,@rBankName,@rReceiptBookId,@rIsObsolete,@rCreatedUserId
			,@rBatchId,@rOrgGroupBatchId,@rRemark,@rReceiptDetailXml,@rChequeDate,@rCharge,@rFeeInvoiceId,@rCollectionGroupId
			,@rDepositedLedgerId,@rPaymentTransactionId,@rReceiptPrintGroupId,@rIsDiscountCoupon,GETDATE(),'pFeeProcessGeneratePaidFeeAdd SP Start')
		END
		
		EXEC [sFee].[pFeeProcessGeneratePaidFeeAdd] @rOrgId,@rBatchId,@rSourceId,@lNextNumber,@lCreatedUserId
		
		IF(@lIsEnableLog = 1)
		BEGIN
			INSERT INTO [sFee].[tFeeReceiptLog]
			VALUES
			(@rOrgId,@rId,@rSourceTypeId,@rSourceId,@rReceiptNumber,@rReceiptDate,@rReceiptAmount
			,@rTotalReceiptAmount,@rDiscountAmount,@rPayTypeId,@rChequeNo,@rBankName,@rReceiptBookId,@rIsObsolete,@rCreatedUserId
			,@rBatchId,@rOrgGroupBatchId,@rRemark,@rReceiptDetailXml,@rChequeDate,@rCharge,@rFeeInvoiceId,@rCollectionGroupId
			,@rDepositedLedgerId,@rPaymentTransactionId,@rReceiptPrintGroupId,@rIsDiscountCoupon,GETDATE(),'pFeeProcessGeneratePaidFeeAdd SP End')
		END
			
		SET @rId = @lNextNumber

		-- 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 WITH (NOLOCK) 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, ReceiptDate = @rReceiptDate, 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 = CASE WHEN ISNULL(DepositedDate, '') <> '' THEN 753 ELSE 751 END WHERE ReceiptId = @rId
		END
		-- For Mantis 0023321 By Foram on 14/03/2024 END

		IF(@lIsEnableLog = 1)
		BEGIN
			INSERT INTO [sFee].[tFeeReceiptLog]
			VALUES
			(@rOrgId,@rId,@rSourceTypeId,@rSourceId,@rReceiptNumber,@rReceiptDate,@rReceiptAmount
			,@rTotalReceiptAmount,@rDiscountAmount,@rPayTypeId,@rChequeNo,@rBankName,@rReceiptBookId,@rIsObsolete,@rCreatedUserId
			,@rBatchId,@rOrgGroupBatchId,@rRemark,@rReceiptDetailXml,@rChequeDate,@rCharge,@rFeeInvoiceId,@rCollectionGroupId
			,@rDepositedLedgerId,@rPaymentTransactionId,@rReceiptPrintGroupId,@rIsDiscountCoupon,GETDATE(),'PDC Entry Done')
		END

		COMMIT TRANSACTION
	END 
	ELSE
	BEGIN
		IF(@lIsEnableLog = 1)
		BEGIN
			INSERT INTO [sFee].[tFeeReceiptLog]
			VALUES
			(@rOrgId,@rId,@rSourceTypeId,@rSourceId,@rReceiptNumber,@rReceiptDate,@rReceiptAmount
			,@rTotalReceiptAmount,@rDiscountAmount,@rPayTypeId,@rChequeNo,@rBankName,@rReceiptBookId,@rIsObsolete,@rCreatedUserId
			,@rBatchId,@rOrgGroupBatchId,@rRemark,@rReceiptDetailXml,@rChequeDate,@rCharge,@rFeeInvoiceId,@rCollectionGroupId
			,@rDepositedLedgerId,@rPaymentTransactionId,@rReceiptPrintGroupId,@rIsDiscountCoupon,GETDATE(),'Fee Receipt Update Start')
		END

		IF EXISTS(SELECT 1 FROM sFee.tReceipt WITH (NOLOCK) where ReceiptNumber=@rReceiptNumber AND Id = @rId)
		BEGIN
			BEGIN TRANSACTION
				UPDATE sFee.tReceipt SET
					ReceiptDate=@rReceiptDate,
					PayTypeId=@rPayTypeId,
					ChequeDate=@rChequeDate,
					ChequeNo=@rChequeNo,
					BankName=@rBankName,
					Remark=@rRemark
				WHERE Id=@rId

				-- For Mantis 0023321 By Foram on 14/03/2024 START
				DECLARE @lSourceId_1 bigint, @lSourceTypeId1_1 smallint, @lBatchId_1 int, @lOrgGroupBatchId_1 int, @lReceiptBookId_1 int, 
						@lPayTypeId_1 smallint, @lChequeNo_1 nvarchar(40), @lBankName_1 nvarchar(200), @lTotalReceiptAmount_1 decimal(12,2)

				SELECT
					@lSourceId_1 = SourceId, 
					@lSourceTypeId1_1 = SourceTypeId, 
					@lBatchId_1 = BatchId, 
					@lOrgGroupBatchId_1 = OrgGroupBatchId, 
					@lReceiptBookId_1 = ReceiptBookId, 
					@lPayTypeId_1 = PayTypeId, 
					@lChequeNo_1 = ChequeNo, 
					@lBankName_1 = BankName, 
					@lTotalReceiptAmount_1 = TotalReceiptAmount
				FROM sFee.tReceipt WHERE Id = @rId

				IF EXISTS(SELECT 1 FROM sFee.tPostDatePayment WITH (NOLOCK) WHERE BatchId = @lBatchId_1 AND OrgGroupBatchId = @lOrgGroupBatchId_1
																AND SourceTypeId = @lSourceTypeId1_1 AND SourceId = @lSourceId_1 AND ReceiptBookId = @lReceiptBookId_1 
																AND PayTypeId = @lPayTypeId_1 AND ChequeNo = @lChequeNo_1 AND BankName = @lBankName_1 AND Amount = @lTotalReceiptAmount_1)
				BEGIN
					UPDATE sFee.tPostDatePayment 
					SET ReceiptId = @rId, ReceiptDate = @rReceiptDate, StatusId = 752 
					WHERE BatchId = @lBatchId_1 AND OrgGroupBatchId = @lOrgGroupBatchId_1 
						AND SourceTypeId = @lSourceTypeId1_1 AND SourceId = @lSourceId_1 AND ReceiptBookId = @lReceiptBookId_1 
						AND PayTypeId = @lPayTypeId_1 AND ChequeNo = @lChequeNo_1 AND BankName = @lBankName_1 AND Amount = @lTotalReceiptAmount_1
				END
				ELSE
				BEGIN
					UPDATE sFee.tPostDatePayment SET ReceiptId = 0, StatusId = CASE WHEN ISNULL(DepositedDate, '') <> '' THEN 753 ELSE 751 END WHERE ReceiptId = @rId
				END
				-- For Mantis 0023321 By Foram on 14/03/2024 END
								
			COMMIT TRANSACTION
		
			SELECT @rId AS RESULT
		END
		ELSE
		IF(@rReceiptNumber <> 0)
		BEGIN
			IF(@lConfigValue='ReceiptBookWise')
			BEGIN
				IF EXISTS(SELECT 1 from sFee.tReceipt WITH (NOLOCK) 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 WITH (NOLOCK) where ReceiptNumber=@rReceiptNumber AND ReceiptBookId=@rReceiptBookId AND  PayTypeId=@rPayTypeId AND OrgGroupBatchId = @rOrgGroupBatchId)
				BEGIN
					SELECT -102 AS Result
					RETURN	
				END
			END

		-- #Start Mantis Id : 0036287
			ELSE IF(@lConfigValue='Continuous Batch')
			BEGIN
				IF EXISTS(SELECT 1 from sFee.tReceipt WITH (NOLOCK) where ReceiptNumber=@rReceiptNumber AND ReceiptBookId=@rReceiptBookId)
				BEGIN
					SELECT -102 AS Result
					RETURN	
				END
			END
			-- #End Mantis Id : 0036287

		-- Mantis - 0030695
			IF(@rChequeNo <> '' AND @lConfigValue1 = 'True')
			BEGIN
				IF EXISTS(SELECT 1 from sFee.tReceipt WITH (NOLOCK) where ChequeNo=@rChequeNo AND Id != @rId)
				BEGIN
					SELECT -103 AS Result
					RETURN	
				END
			END
			-- Mantis - 0030695

			BEGIN TRANSACTION

				UPDATE sFee.tReceipt SET
					ReceiptNumber = @rReceiptNumber,
					ReceiptDate=@rReceiptDate,
					PayTypeId=@rPayTypeId,
					ChequeDate=@rChequeDate,
					ChequeNo=@rChequeNo,
					BankName=@rBankName,
					Remark=@rRemark
				WHERE Id=@rId
		
				-- For Mantis 0023321 By Foram on 14/03/2024 START
				DECLARE @lSourceId_2 bigint, @lSourceTypeId1_2 smallint, @lBatchId_2 int, @lOrgGroupBatchId_2 int, @lReceiptBookId_2 int, 
						@lPayTypeId_2 smallint, @lChequeNo_2 nvarchar(40), @lBankName_2 nvarchar(200), @lTotalReceiptAmount_2 decimal(12,2)

				SELECT
					@lSourceId_2 = SourceId, 
					@lSourceTypeId1_2 = SourceTypeId, 
					@lBatchId_2 = BatchId, 
					@lOrgGroupBatchId_2 = OrgGroupBatchId, 
					@lReceiptBookId_2 = ReceiptBookId, 
					@lPayTypeId_2 = PayTypeId, 
					@lChequeNo_2 = ChequeNo, 
					@lBankName_2 = BankName, 
					@lTotalReceiptAmount_2 = TotalReceiptAmount
				FROM sFee.tReceipt WHERE Id = @rId

				IF EXISTS(SELECT 1 FROM sFee.tPostDatePayment WITH (NOLOCK) WHERE BatchId = @lBatchId_2 AND OrgGroupBatchId = @lOrgGroupBatchId_2
																AND SourceTypeId = @lSourceTypeId1_2 AND SourceId = @lSourceId_2 AND ReceiptBookId = @lReceiptBookId_2 
																AND PayTypeId = @lPayTypeId_2 AND ChequeNo = @lChequeNo_2 AND BankName = @lBankName_2 AND Amount = @lTotalReceiptAmount_2)
				BEGIN
					UPDATE sFee.tPostDatePayment 
					SET ReceiptId = @rId, ReceiptDate = @rReceiptDate, StatusId = 752 
					WHERE BatchId = @lBatchId_2 AND OrgGroupBatchId = @lOrgGroupBatchId_2
						AND SourceTypeId = @lSourceTypeId1_2 AND SourceId = @lSourceId_2 AND ReceiptBookId = @lReceiptBookId_2 
						AND PayTypeId = @lPayTypeId_2 AND ChequeNo = @lChequeNo_2 AND BankName = @lBankName_2 AND Amount = @lTotalReceiptAmount_2
				END
				ELSE
				BEGIN
					UPDATE sFee.tPostDatePayment SET ReceiptId = 0, StatusId = CASE WHEN ISNULL(DepositedDate, '') <> '' THEN 753 ELSE 751 END WHERE ReceiptId = @rId
				END
				-- For Mantis 0023321 By Foram on 14/03/2024 END
								
				SELECT @rId AS RESULT
			COMMIT TRANSACTION 
		END
	
			IF(@lIsEnableLog = 1)
			BEGIN
				INSERT INTO [sFee].[tFeeReceiptLog]
				VALUES
				(@rOrgId,@rId,@rSourceTypeId,@rSourceId,@rReceiptNumber,@rReceiptDate,@rReceiptAmount
				,@rTotalReceiptAmount,@rDiscountAmount,@rPayTypeId,@rChequeNo,@rBankName,@rReceiptBookId,@rIsObsolete,@rCreatedUserId
				,@rBatchId,@rOrgGroupBatchId,@rRemark,@rReceiptDetailXml,@rChequeDate,@rCharge,@rFeeInvoiceId,@rCollectionGroupId
				,@rDepositedLedgerId,@rPaymentTransactionId,@rReceiptPrintGroupId,@rIsDiscountCoupon,GETDATE(),'Fee Receipt Update End')
			END
		END
	
	IF(@lIsEnableLog = 1)
	BEGIN
		INSERT INTO [sFee].[tFeeReceiptLog]
		VALUES
		(@rOrgId,@rId,@rSourceTypeId,@rSourceId,@rReceiptNumber,@rReceiptDate,@rReceiptAmount
		,@rTotalReceiptAmount,@rDiscountAmount,@rPayTypeId,@rChequeNo,@rBankName,@rReceiptBookId,@rIsObsolete,@rCreatedUserId
		,@rBatchId,@rOrgGroupBatchId,@rRemark,@rReceiptDetailXml,@rChequeDate,@rCharge,@rFeeInvoiceId,@rCollectionGroupId
		,@rDepositedLedgerId,@rPaymentTransactionId,@rReceiptPrintGroupId,@rIsDiscountCoupon,GETDATE(),'Receipt SP Main Process End')
	END
	END TRY
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		IF(@lIsEnableLog = 1)
		BEGIN
			INSERT INTO [sFee].[tFeeReceiptLog]
			VALUES
			(@rOrgId,@rId,@rSourceTypeId,@rSourceId,@rReceiptNumber,@rReceiptDate,@rReceiptAmount
			,@rTotalReceiptAmount,@rDiscountAmount,@rPayTypeId,@rChequeNo,@rBankName,@rReceiptBookId,@rIsObsolete,@rCreatedUserId
			,@rBatchId,@rOrgGroupBatchId,@rRemark,@rReceiptDetailXml,@rChequeDate,@rCharge,@rFeeInvoiceId,@rCollectionGroupId
			,@rDepositedLedgerId,@rPaymentTransactionId,@rReceiptPrintGroupId,@rIsDiscountCoupon,GETDATE(),Error_Message())
			SELECT -1 AS Result, ERROR_Message()
		END
	END CATCH	
		
END
GO
PRINT N'Altering Procedure [sFrontOffice].[pLostFoundRegisterAdd]...';


GO

ALTER  PROCEDURE [sFrontOffice].[pLostFoundRegisterAdd]
	  
		@rOrgGroupId smallint,
		@rOrgId smallint=0,
        @rId int,
        @rFoundNumber int,
        @rFoundDate date,
        @rItemType nvarchar(150),
		@rItemDescription nvarchar(300),
		@rLostFoundStatusId smallint,
		@rOwnerSourceTypeId smallint,
		@rOwnwerSourceId bigint,
		@rOwnerDetail nvarchar(200),
		@rCreatedUserId bigint,
		@rUpdatedUserId bigint
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY

	
	
	 BEGIN TRANSACTION	
	 DECLARE @lNextNumber BIGINT 

	IF(@rId = 0)	
	BEGIN
		
		IF EXISTS (SELECT Id FROM sFrontOffice.tLostFoundRegister WHERE OrgGroupId = @rOrgGroupId AND FoundNumber= @rFoundNumber)
		BEGIN
		SELECT  -101 AS  Result
		COMMIT TRANSACTION
		RETURN
		END
		
	EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sFrontOffice.tLostFoundRegister', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	INSERT INTO sFrontOffice.tLostFoundRegister
		(
			OrgGroupId,
			OrgId,
			Id,
			FoundNumber,
			FoundDate,
			ItemType,
			ItemDescription,
			LostFoundStatusId,
			OwnerSourceTypeId,
			OwnwerSourceId,
			OwnerDetail,
			CreatedUserId,
			CreatedDateTime,
			UpdatedUserId,
			UpdatedDateTime
			
		)
	VALUES
		(
			@rOrgGroupId,
			@rOrgId,
			@lNextNumber,
			@rFoundNumber,
			@rFoundDate,
			@rItemType,
			@rItemDescription,
			@rLostFoundStatusId,
			@rOwnerSourceTypeId,
			@rOwnwerSourceId,
			@rOwnerDetail,
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rUpdatedUserId	,	
			sCommon.fGetDate()
		)
		   
		    SELECT @lNextNumber AS Result
	
	--COMMIT TRANSACTION  
	END	 

ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE  sFrontOffice.tLostFoundRegister
	    SET
			
			OrgGroupId=@rOrgGroupId,
			OrgId=@rOrgId,
			Id=@rId,
			FoundNumber=@rFoundNumber,
			FoundDate=@rFoundDate,
			ItemType=@rItemType,
			ItemDescription=@rItemDescription,
			LostFoundStatusId=@rLostFoundStatusId,
			OwnerSourceTypeId=@rOwnerSourceTypeId,
			OwnwerSourceId=@rOwnwerSourceId,
			OwnerDetail=@rOwnerDetail,
			UpdatedUserId=@rCreatedUserId,
			UpdatedDateTime=sCommon.fGetDate()
	      
	      
	      WHERE Id = @rId
	       AND  OrgGroupId=@rOrgGroupId
	     
	      --AND 
	    --  OrgId=@rOrgId

	      SELECT @lNextNumber AS Result
	
		--COMMIT TRANSACTION
	 END  	

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


GO

ALTER PROCEDURE [sPayroll].[pPayElementAdd] 
	      
			@rId int
	       ,@rCode nvarchar(20)
           ,@rTitle nvarchar(100)
           ,@rPayElementTypeId tinyint
           ,@rPaidCategoryId tinyint
           ,@rIsLwp bit
           ,@rIsEmployeeSpecific bit
           ,@rIsDepend bit
           ,@rIsAvailDuringProbation bit
           ,@rIsIncludeInPaySlip bit
           ,@rSortOrder tinyint
           ,@rIsObsolete bit
           ,@rOrgGroupId int
           ,@rCreatedUserId bigint
		   ,@rPayElementDefaultId int
		   ,@rPayrollId int
		   ,@rIsIncludeInTotal bit=0
      
        
           
          
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN

	BEGIN TRY
	BEGIN TRANSACTION  
	DECLARE @lNextNumber BIGINT

	--Add Validation of code because if in Earning and Deduction both there are same code then issue in Pay Process Employee screen in SP(pPayrollProcessEmployeeDetailGet) for pivot - mantisid - 0027028
	IF (@rId = 0)
    BEGIN
		IF EXISTS (Select 1 from sPayroll.tPayElement WHERE Code=@rCode AND PayrollId = @rPayrollId)
		BEGIN
			SELECT -101 AS Result
			COMMIT TRANSACTION
			RETURN
		END 
	END
	ELSE
	BEGIN
		IF EXISTS (Select 1 from sPayroll.tPayElement WHERE Code=@rCode AND PayrollId = @rPayrollId AND Id != @rId)
			BEGIN
				SELECT -101 AS Result
				COMMIT TRANSACTION
				RETURN
			END 
	END
  
  IF (@rId = 0)
    
    BEGIN	
	EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sPayroll.tPayElement', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	INSERT INTO [sPayroll].[tPayElement]
           (
            [ID]
           ,[Code]
           ,[Title]
           ,[PayElementTypeId]
           ,[PaidCategoryId]
           ,[IsLwp]
           ,[IsEmployeeSpecific]
           ,[IsDepend]
           ,[IsAvailDuringProbation]
           ,[IsIncludeInPaySlip]
           ,[SortOrder]
           ,[IsObsolete]
           ,[CreatedUserId]
           ,[CreatedDateTime]
           ,[UpdatedUserId]
           ,[UpdatedDateTime]
           ,[PayElementDefaultId]
           ,[PayrollId]
           ,[IsIncludeInTotal]
           )
     VALUES
           (
            @lNextNumber
           ,@rCode 
           ,@rTitle 
           ,@rPayElementTypeId 
           ,@rPaidCategoryId 
           ,@rIsLwp 
           ,@rIsEmployeeSpecific 
           ,@rIsDepend 
           ,@rIsAvailDuringProbation 
           ,@rIsIncludeInPaySlip 
           ,@rSortOrder 
           ,@rIsObsolete 
           ,@rCreatedUserId 
           ,sCommon.fGetDate()  
           ,@rCreatedUserId 
           ,sCommon.fGetDate() 
           ,@rPayElementDefaultId
           ,@rPayrollId
           ,@rIsIncludeInTotal
           )
    	END
    ELSE
		BEGIN    
		     SET @lNextNumber = @rId
		    UPDATE  [sPayroll].[tPayElement]
			   SET   
			       [Code] = @rCode
				  ,[Title] = @rTitle 
				  ,[PayElementTypeId] = @rPayElementTypeId 
				  ,[PaidCategoryId] = @rPaidCategoryId 
				  ,[IsLwp] = @rIsLwp 
				  ,[IsEmployeeSpecific] = @rIsEmployeeSpecific 
				  ,[IsDepend] = @rIsDepend 
				  ,[IsAvailDuringProbation] = @rIsAvailDuringProbation 
				  ,[IsIncludeInPaySlip] = @rIsIncludeInPaySlip 
				  ,[SortOrder] = @rSortOrder 
				  ,[IsObsolete] = @rIsObsolete  
				  ,[UpdatedUserId] = @rCreatedUserId 
				  ,[UpdatedDateTime] = sCommon.fGetDate() 
				  --,[PayElementDefaultId] = @rPayElementDefaultId
				  ,[PayrollId]=@rPayrollId
				  ,[IsIncludeInTotal]=@rIsIncludeInTotal
			   WHERE Id = @rId   		     		    
			END        
	SELECT @lNextNumber AS Result	
	COMMIT TRANSACTION
	END TRY
	BEGIN CATCH
	ROLLBACK TRANSACTION
	 RAISERROR ('Error Creating Pay Element Detail', -- Message text.
               16, -- Severity.
               1 -- State.
               );
	--SELECT -1 AS RESULT
	END CATCH	
END
GO
PRINT N'Altering Procedure [sPayroll].[pPayProcessEmployeeAdd]...';


GO

ALTER PROCEDURE [sPayroll].[pPayProcessEmployeeAdd] 
	      	        
            @rPayProcessId int            
           ,@rOrgGroupId int
		   ,@rPayrollId int
		   ,@rPayrollYearId int
		   ,@rSalaryMonth tinyint
           ,@rSalaryYear smallint
           ,@rEmployeeId bigint=0
		   ,@rIsAllow bit=0 --mantis: 40774
           
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	DECLARE @lNextNumber BIGINT
	DECLARE @1PayProcessElementId bigint
	DECLARE @1Count int
	DECLARE @1EmployeeId bigint
	DECLARE @lPayrollGroupId int
	DECLARE @1PayElementCount int
	DECLARE @1TotalEarningAmount DECIMAL(22,6)
	DECLARE @1PaySetupId int
	DECLARE @1SourceId bigint
    DECLARE @1Percentage decimal(5,2)
	DECLARE @1Result decimal(22,6)
	DECLARE @1Amount decimal(22,6)
	DECLARE @1IsDepend bit
	DECLARE @1PayElementId int
	DECLARE @1LWPDeduction decimal(22,6) 
	DECLARE @1IsLwp Bit
	DECLARE @1PayElementTypeId int
	DECLARE @1TotalDeductionAmount DECIMAL(22,6)
	DECLARE @1EmployeeBasicPay DECIMAL(22,6)
	
	DECLARE @1WorkingDays int
	DECLARE @1Lwp Decimal(12,2)
	DECLARE @lPaidLeave Decimal(12,2)
	DECLARE @1GrossBasic Decimal(12,2)
	DECLARE @1PayElementDefaultId int
    DECLARE @lIsIncludeInTotal Bit
	DECLARE @lFormula nvarchar(200)=''
    
    
    DECLARE @lLastDayOfMonth int = DAY(sCommon.GetLastDateofMonth (CONVERT(nvarchar(4),@rSalaryYear)+'-'+CONVERT(nvarchar(2),@rSalaryMonth)+'-01'))
    -- Loan Configuration
    DECLARE @lConfigValue nvarchar(50)
	SELECT @lConfigValue = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 206 AND SourceTypeId = 2010 AND SourceId = @rOrgGroupId
	
	DECLARE @lIsCalculateAllPayElementAsPerJoining nvarchar(50)
	SELECT @lIsCalculateAllPayElementAsPerJoining = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 307 AND SourceTypeId = 2010 AND SourceId = @rOrgGroupId
	
	DECLARE @lIsPayrollCountBasedOnWorkingDays nvarchar(50)
	SELECT @lIsPayrollCountBasedOnWorkingDays = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 310 AND SourceTypeId = 2010 AND SourceId = @rOrgGroupId
    
    DECLARE @lIsPayrollEvaluationOnFixDay nvarchar(50)
	SELECT @lIsPayrollEvaluationOnFixDay = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 324 AND SourceTypeId = 2010 AND SourceId = @rOrgGroupId
    
	DECLARE @lIsRoundOffToWholeNumber nvarchar(50)
	DECLARE @lRoundOffToWholeNumber int
	SELECT @lIsRoundOffToWholeNumber = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 248 AND SourceTypeId = 2010 AND SourceId = @rOrgGroupId
	
	IF (@lIsRoundOffToWholeNumber IS NULL) OR (@lIsRoundOffToWholeNumber = 'True')
		SET @lRoundOffToWholeNumber = 0
	ELSE
		SET @lRoundOffToWholeNumber = 2	
	--IF (@rId = 0)
	IF(@rEmployeeId=0)
	BEGIN
		CREATE TABLE #tmpEmpDetail
		(
			Id INT IDENTITY (1, 1),
			EmployeeId  bigint,
			PayrollGroupId int
		)
		 
		INSERT INTO #tmpEmpDetail
		Select ES.EmployeeId,PayrollGroupId FROM sHrm.tEmployeeStatutoryAndOther ES
		INNER JOIN  sHrm.tEmployeeAttendance EA ON ES.EmployeeId = EA.EmployeeId
		INNER JOIN sSetup.tBatchMaster BM ON EA.BatchId = BM.Id AND BM.IsActive = 1
		Where PayrollId = @rPayrollId AND PayrollGroupId IS NOT NULL
		AND EA.ForMonth = @rSalaryMonth AND EA.ForYear = @rSalaryYear
   
		Select @1Count = COUNT(*) FROM #tmpEmpDetail 
      
		WHILE @1Count > 0 
		BEGIN	 
			EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sPayroll.tPayProcessEmployee', 0, 1, 1,@outNextNumber = @lNextNumber output	
		    SELECT @1EmployeeId = EmployeeId,@lPayrollGroupId = PayrollGroupId FROM #tmpEmpDetail WHERE ID = @1Count
		   
		    SELECT @1WorkingDays = TotalWorkingDays,@1Lwp = LWP, @lPaidLeave=ISNULL(PaidLeave,0) FROM sHrm.tEmployeeAttendance EA
		    INNER JOIN sSetup.tBatchMaster BM ON EA.BatchId = BM.Id AND BM.IsActive = 1
		    Where EA.EmployeeId=@1EmployeeId AND EA.ForYear=@rSalaryYear AND EA.ForMonth=@rSalaryMonth
					
		    SELECT @1GrossBasic = PS.Amount FROM sPayroll.tPaySetup PS 
			INNER JOIN sPayroll.tPayElement PE ON PE.Id=PS.PayElementId
			Where PS.SourceTypeId = 95 
			AND PS.SourceId=@1EmployeeId 
			AND PS.PayrollId=@rPayrollId 
			AND PS.PayrollYearId = @rPayrollYearId 
			AND PE.PayElementDefaultId=1 
		   
		    IF EXISTS (SELECT 1 FROM sPayroll.tPaySetup WHERE SourceTypeId=2020 AND SourceId=@lPayrollGroupId AND PayrollId=@rPayrollId AND PayrollYearId=@rPayrollYearId)
		    BEGIN		    
		    INSERT INTO  [sPayroll].[tPayProcessEmployee]
				   (
				    [ID]
				   ,[PayProcessId]
				   ,[EmployeeId]
				   ,[PayrollGroupId]
				   ,TotalEarning
				   ,TotalDeduction
				   ,NetAmount
				   ,WorkingDays
				   ,Lwp
				   ,GrossBasic
				   ,PaidLeave
				   )
			VALUES
				   (
				    @lNextNumber
				   ,@rPayProcessId
				   ,@1EmployeeId 
				   ,@lPayrollGroupId
				   ,0.0
				   ,0.0
				   ,0.0
				   ,@1WorkingDays
				   ,@1Lwp
				   ,@1GrossBasic
				   ,@lPaidLeave
				   )
				   
		      
	     -- FOR Counting Total Earning
	 
		 CREATE TABLE #tmpPaysetupElement
		(
		   Id INT IDENTITY (1, 1),
		   PaySetupId int,
		   SourceId bigint,
		   SourceTypeId int,
		   PayElementId int,
		   Amount DECIMAl(22,6) NULL,
		   Percentage DECIMAl(5,2) NULL,
		   IsDepend bit,
		   PayElementTypeId int,
		   ProcessOrder int,
		   PayElementDefaultId int  ,
		   Formula nvarchar(200)
		)  
		   
		   BEGIN
		 --IF EXISTS (select 1 from sPayroll.tpaysetup where SourceId = @1EmployeeId AND SourceTypeId = 3016) --For Pay Setup Employee
		     INSERT INTO #tmpPaysetupElement
		     SELECT PE.ID,PE.SourceId,PE.SourceTypeId,PE.PayElementId,PE.Amount,PE.Percentage,PE.IsDepend,PE.PayElementTypeId,PE.ProcessOrder,PayElementDefaultId,PE.Formula FROM 
		     (		     
		     SELECT PS.ID,SourceId,95 AS SourceTypeId ,PayElementId,Amount,Percentage,ISNULL(IsDepend,0) AS IsDepend,PayElementTypeId,ProcessOrder,PE.PayElementDefaultId,ISNULL(PS.Formula,'') As Formula
		     FROM sPayroll.tPaySetup PS INNER JOIN sPayroll.tPayElement  PE ON PE.ID = PS.PayElementId
			 WHERE SourceId = @1EmployeeId 
			 AND SourceTypeId = 95 
			 AND PS.PayrollId=@rPayrollId 
			 AND PS.PayrollYearId = @rPayrollYearId
		 
		 --ELSE 
		     UNION ALL
		      
		     --INSERT INTO #tmpPaysetupElement
		     SELECT PS.ID,SourceId,2020 AS SourceTypeId,PayElementId,Amount,Percentage,IsDepend,PayElementTypeId,ProcessOrder 
			 ,PE.PayElementDefaultId,ISNULL(PS.Formula,'') As Formula
		     FROM sPayroll.tPaySetup  PS  INNER JOIN sPayroll.tPayElement  PE ON PE.ID = PS.PayElementId
			 WHERE SourceId = @lPayrollGroupId AND SourceTypeId = 2020 AND PS.PayrollId=@rPayrollId AND PS.PayrollYearId = @rPayrollYearId
			 AND PayElementId NOT IN (SELECT  PayElementId FROM sPayroll.tPaySetup  PS 
		     INNER JOIN sPayroll.tPayElement  PE ON PE.ID = PS.PayElementId 
		     WHERE SourceId = @1EmployeeId 
		     AND SourceTypeId = 95 
		     AND PS.PayrollId=@rPayrollId 
		     AND PS.PayrollYearId = @rPayrollYearId)  			 
			 
		     ) PE  ORDER BY ProcessOrder  DESC
		  	END	
		  	  
		    --Select * FROM #tmpPaysetupElement
		  
		  	SELECT @1PayElementCount = COUNT(*) FROM #tmpPaysetupElement
			
			SET @1TotalDeductionAmount = 0
			SET   @1TotalEarningAmount = 0
			WHILE @1PayElementCount > 0
				BEGIN				
					SET @1PaySetupId = 0
					SET @1SourceId = 0
					SET @1Percentage = 0.0
					SET @1Result = 0.0
					SET @1Amount = 0.0 			
					SET @1PayElementId = 0
					SET @1IsLwp = 0
					SET @1LWPDeduction = 0
					SET @1PayElementDefaultId = 0
					SET @lFormula = ''
			  
			    SELECT @1PaySetupId = PaySetupId,@1SourceId = SourceId,@1PayElementId = PayElementId,@1Result = Amount,
			    @1Percentage = Percentage,@1IsDepend = IsDepend,@1PayElementTypeId=PayElementTypeId,@1PayElementDefaultId =PayElementDefaultId,
				@lFormula=Formula
				FROM #tmpPaysetupElement WHERE Id = @1PayElementCount
			      
			    SELECT @1IsLwp = IsLwp, @lIsIncludeInTotal=IsIncludeInTotal FROM sPayroll.tPayElement Where Id = @1PayElementId AND PayrollId = @rPayrollId
			    
			    IF(@1PayElementDefaultId=1)
			    BEGIN
					IF (@lIsPayrollCountBasedOnWorkingDays IS NULL) OR (@lIsPayrollCountBasedOnWorkingDays = 'False')
						BEGIN
							IF (@lIsPayrollEvaluationOnFixDay IS NULL) OR (@lIsPayrollEvaluationOnFixDay = 'False')
								SET @1Result = (ISNULL(@1Result,0)/@lLastDayOfMonth) * @1WorkingDays
							ELSE
								SET @1Result = (ISNULL(@1Result,0)/30) * @1WorkingDays
						END	
					ELSE
						SET @1Result = (ISNULL(@1Result,0)/@1WorkingDays) * @1WorkingDays 
			    END
			    
			    --IF(@1PayElementDefaultId!=1 AND @1IsDepend = 0 AND @lIsCalculateAllPayElementAsPerJoining IS NULL) OR (@lIsCalculateAllPayElementAsPerJoining = 'False')
			    IF(@1PayElementDefaultId!=1 AND @1IsDepend = 0 AND (@lIsCalculateAllPayElementAsPerJoining IS NULL OR @lIsCalculateAllPayElementAsPerJoining = 'False'))		-- Mantis Id : 0043289
			    BEGIN 
					IF (@lIsPayrollCountBasedOnWorkingDays IS NULL) OR (@lIsPayrollCountBasedOnWorkingDays = 'False')	
						BEGIN
							IF (@lIsPayrollEvaluationOnFixDay IS NULL) OR (@lIsPayrollEvaluationOnFixDay = 'False')
								SET @1Result = (ISNULL(@1Result,0)/@lLastDayOfMonth) * @1WorkingDays
							ELSE
								SET @1Result = (ISNULL(@1Result,0)/30) * @1WorkingDays
						END	
					ELSE
						SET @1Result = (ISNULL(@1Result,0)/@1WorkingDays) * @1WorkingDays 
			    END	    
			       
			    IF(@1IsLwp = 1) 			     
			        SELECT @1LWPDeduction = [sPayroll].[fCalculateLWP] (@1EmployeeId, @rPayProcessId,ISNULL(@1Result,0))			      
			               
			    IF(@1IsDepend = 1 AND @1PayElementDefaultId NOT IN(55,56,57)) -- ESI,PF,PT seperatly calculated
			        EXECUTE [sPayroll].[pCalculatePayrollAmount]  @1PaySetupId,@1PayElementId,@1Percentage,@1SourceId,@rOrgGroupId,@1EmployeeId,@lNextNumber,@rPayrollId,@rPayrollYearId,@lFormula,@1Result OUTPUT
			    
			    IF(@1WorkingDays = 0)      
					SET @1Result =  0    
			    ELSE
					SET @1Result =  ROUND(ISNULL(@1Result,0.0) -  ISNULL(@1LWPDeduction,0.00),@lRoundOffToWholeNumber)	         
			      
			    EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sPayroll.tPayProcessElement', 0, 1, 1,@outNextNumber = @1PayProcessElementId output	
		
	        	IF (@lConfigValue IS NULL) OR (@lConfigValue = 'False')	
	        	BEGIN
	        		INSERT INTO  [sPayroll].[tPayProcessElement]
						   (
						    [ID]
						   ,[PayProcessEmployeeId]
						   ,[PayElementId]
						   ,[Amount]
						   )
					 VALUES
						   (
						    @1PayProcessElementId
						   ,@lNextNumber
						   ,@1PayElementId
						   ,@1Result
						   )  
	        	END
	        	ELSE
	        	BEGIN
	        		IF(@1PayElementDefaultId = 58)
	        		BEGIN
						SET @1Result= [sLoan].[fEmployeeLoanInstalmentGet](@rSalaryMonth,@rSalaryYear,@1EmployeeId,58)
	        		INSERT INTO  [sPayroll].[tPayProcessElement]
						   (
						    [ID]
						   ,[PayProcessEmployeeId]
						   ,[PayElementId]
						   ,[Amount]
						   )
					 VALUES
						   (
						    @1PayProcessElementId
						   ,@lNextNumber
						   ,@1PayElementId
						  ,[sLoan].[fEmployeeLoanInstalmentGet](@rSalaryMonth,@rSalaryYear,@1EmployeeId,58)
						   )  
					END
					
	        		ELSE IF(@1PayElementDefaultId = 63)
	        		BEGIN
					SET @1Result= [sLoan].[fEmployeeLoanInstalmentGet](@rSalaryMonth,@rSalaryYear,@1EmployeeId,63)
	        		INSERT INTO  [sPayroll].[tPayProcessElement]
						   (
						    [ID]
						   ,[PayProcessEmployeeId]
						   ,[PayElementId]
						   ,[Amount]
						   )
					 VALUES
						   (
						    @1PayProcessElementId
						   ,@lNextNumber
						   ,@1PayElementId
						   ,[sLoan].[fEmployeeLoanInstalmentGet](@rSalaryMonth,@rSalaryYear,@1EmployeeId,63)
						   )  
					END
					ELSE
					BEGIN
					INSERT INTO  [sPayroll].[tPayProcessElement]
						   (
						    [ID]
						   ,[PayProcessEmployeeId]
						   ,[PayElementId]
						   ,[Amount]
						   )
					 VALUES
						   (
						 @1PayProcessElementId
						   ,@lNextNumber
						   ,@1PayElementId
						   ,@1Result
						   )  
					END
						   
				END
			       
			    
			    
			     IF( @1PayElementTypeId = 1)
			     BEGIN	      	 
			      IF(@lIsIncludeInTotal = 1)
					SET @1TotalEarningAmount = ISNULL(@1TotalEarningAmount,0) + ISNULL(@1Result,0)		      
				  ELSE
					SET @1TotalEarningAmount = ISNULL(@1TotalEarningAmount,0)	      
			     END
			     
			     ELSE 
			       BEGIN 
			        IF(@lIsIncludeInTotal = 1)
						SET @1TotalDeductionAmount = ISNULL(@1TotalDeductionAmount,0) + ISNULL(@1Result,0) 	      
					ELSE
						SET @1TotalDeductionAmount = ISNULL(@1TotalDeductionAmount,0)	  
			            --- ISNULL(@1LWPDeduction,0)      
			       END   
			     		    
			    SET @1PayElementCount = @1PayElementCount -1			     
			  END	 
		    --SELECT * from #tmpPaysetupElement
			DROP TABLE #tmpPaysetupElement
		       
			END	   
		   EXECUTE [sPayroll].[pCalculateStaticPayElement]  @lNextNumber,@rOrgGroupId,@1TotalEarningAmount,@1SourceId,@1TotalDeductionAmount,@rPayrollId,@rPayrollYearId,@lPayrollGroupId,@rSalaryMonth,@rSalaryYear,@1EmployeeId,@rIsAllow --mantis: 40774, add @rIsAllow
			--SELECT  TOP 1 @lTax = Tax  FROM sPayroll.tProfessionalTaxRange where Salary < @rSalary Order By Salary Desc
  		    
		 SET @1Count = @1Count - 1	
	END	    
	--DROP TABLE #tmpPaysetupElement
	DROP TABLE #tmpEmpDetail
	SELECT @lNextNumber AS Result	
	
	END
	ELSE
	BEGIN
			EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sPayroll.tPayProcessEmployee', 0, 1, 1,@outNextNumber = @lNextNumber output	
		    
			SELECT @lPayrollGroupId = PayrollGroupId FROM sHrm.tEmployeeStatutoryAndOther WHERE EmployeeId = @rEmployeeId
		    
		    SELECT @1WorkingDays = TotalWorkingDays,@1Lwp = LWP, @lPaidLeave=ISNULL(PaidLeave,0) FROM sHrm.tEmployeeAttendance EA
		    INNER JOIN sSetup.tBatchMaster BM ON EA.BatchId = BM.Id AND BM.IsActive = 1
		     Where EA.EmployeeId=@rEmployeeId AND EA.ForYear=@rSalaryYear AND EA.ForMonth=@rSalaryMonth


		    SELECT @1GrossBasic = PS.Amount FROM sPayroll.tPaySetup PS 
			INNER JOIN sPayroll.tPayElement PE ON PE.Id=PS.PayElementId
			Where PS.SourceTypeId = 95 
			AND PS.SourceId=@rEmployeeId 
			AND PS.PayrollId=@rPayrollId 
			AND PS.PayrollYearId = @rPayrollYearId 
			AND PE.PayElementDefaultId=1 
					  
		   INSERT INTO  [sPayroll].[tPayProcessEmployee]
				   (
				    [ID]
				   ,[PayProcessId]
				   ,[EmployeeId]
				   ,[PayrollGroupId]
				   ,TotalEarning
				   ,TotalDeduction
				   ,NetAmount
				   ,WorkingDays
				   ,Lwp
				   ,GrossBasic
				   ,PaidLeave
				   )
			 VALUES
				   (
				    @lNextNumber
				   ,@rPayProcessId
				   ,@rEmployeeId 
				   ,@lPayrollGroupId
				   ,0.0
				   ,0.0
				   ,0.0
				   ,@1WorkingDays
				   ,@1Lwp
				   ,@1GrossBasic
				   ,@lPaidLeave
				   )
		   
	     -- FOR Counting Total Earning
	 
			CREATE TABLE #TempPaysetupElement
		(
		   Id INT IDENTITY (1, 1),
		   PaySetupId int,
		   SourceId bigint,
		   SourceTypeId int,
		   PayElementId int,
		   Amount DECIMAl(22,6) NULL,
		   Percentage DECIMAl(5,2) NULL,
		   IsDepend bit,
		   PayElementTypeId int,
		   ProcessOrder int,
		   PayElementDefaultId int,
		   Formula nvarchar(200)
		)  
		   
			BEGIN
		     INSERT INTO #TempPaysetupElement
		     SELECT PE.ID,PE.SourceId,PE.SourceTypeId,PE.PayElementId,PE.Amount,PE.Percentage,PE.IsDepend,PE.PayElementTypeId,PE.ProcessOrder,PayElementDefaultId,PE.Formula FROM 
		     (		     
		     SELECT PS.ID,SourceId,95 AS SourceTypeId ,PayElementId,Amount,Percentage,ISNULL(IsDepend,0) AS IsDepend,PayElementTypeId,ProcessOrder,PE.PayElementDefaultId,ISNULL(PS.Formula,'') AS  Formula
		     FROM sPayroll.tPaySetup PS INNER JOIN sPayroll.tPayElement  PE ON PE.ID = PS.PayElementId
			 WHERE SourceId = @rEmployeeId 
			 AND SourceTypeId = 95 
			 AND PS.PayrollId=@rPayrollId 
			 AND PS.PayrollYearId = @rPayrollYearId
		     UNION ALL
		     SELECT PS.ID,SourceId,2020 AS SourceTypeId,PayElementId,Amount,Percentage,IsDepend,PayElementTypeId,ProcessOrder ,PE.PayElementDefaultId,ISNULL(PS.Formula,'') AS  Formula
		     FROM sPayroll.tPaySetup  PS  INNER JOIN sPayroll.tPayElement  PE ON PE.ID = PS.PayElementId
			 WHERE SourceId = @lPayrollGroupId AND SourceTypeId = 2020 AND PS.PayrollId=@rPayrollId AND PS.PayrollYearId = @rPayrollYearId
			 AND PayElementId NOT IN (SELECT  PayElementId FROM sPayroll.tPaySetup  PS 
		     INNER JOIN sPayroll.tPayElement  PE ON PE.ID = PS.PayElementId 
		     WHERE SourceId = @rEmployeeId 
		     AND SourceTypeId = 95 
		     AND PS.PayrollId=@rPayrollId 
		     AND PS.PayrollYearId = @rPayrollYearId)  			 
		     ) PE  ORDER BY ProcessOrder  DESC
		  	END	
		  	  
		  	SELECT @1PayElementCount = COUNT(*) FROM #TempPaysetupElement
			
			SET @1TotalDeductionAmount = 0
			SET   @1TotalEarningAmount = 0
			WHILE @1PayElementCount > 0
			BEGIN				
					SET @1PaySetupId = 0
					SET @1SourceId = 0
					SET @1Percentage = 0.0
					SET @1Result = 0.0
					SET @1Amount = 0.0 			
					SET @1PayElementId = 0
					SET @1IsLwp = 0
					SET @1LWPDeduction = 0
					SET @1PayElementDefaultId = 0
					SET @lFormula=''
			  
			    SELECT @1PaySetupId = PaySetupId,@1SourceId = SourceId,@1PayElementId = PayElementId,@1Result = Amount,
			    @1Percentage = Percentage,@1IsDepend = IsDepend,@1PayElementTypeId=PayElementTypeId,@1PayElementDefaultId =PayElementDefaultId, @lFormula=Formula FROM #TempPaysetupElement WHERE Id = @1PayElementCount
			      
			    SELECT @1IsLwp = IsLwp, @lIsIncludeInTotal=IsIncludeInTotal FROM sPayroll.tPayElement Where Id = @1PayElementId AND PayrollId = @rPayrollId
			    					      
			    IF(@1PayElementDefaultId=1)
			    BEGIN
					IF (@lIsPayrollCountBasedOnWorkingDays IS NULL) OR (@lIsPayrollCountBasedOnWorkingDays = 'False')
						BEGIN
							IF (@lIsPayrollEvaluationOnFixDay IS NULL) OR (@lIsPayrollEvaluationOnFixDay = 'False')
								SET @1Result = (ISNULL(@1Result,0)/@lLastDayOfMonth) * @1WorkingDays
							ELSE
								SET @1Result = (ISNULL(@1Result,0)/30) * @1WorkingDays
						END	
					ELSE
						SET @1Result = (ISNULL(@1Result,0)/@1WorkingDays) * @1WorkingDays 
			    END
			    
			    IF(@1PayElementDefaultId!=1 AND @1IsDepend = 0 AND @lIsCalculateAllPayElementAsPerJoining IS NULL) OR (@lIsCalculateAllPayElementAsPerJoining = 'False')
			    BEGIN 
					IF (@lIsPayrollCountBasedOnWorkingDays IS NULL) OR (@lIsPayrollCountBasedOnWorkingDays = 'False')	
						BEGIN
							IF (@lIsPayrollEvaluationOnFixDay IS NULL) OR (@lIsPayrollEvaluationOnFixDay = 'False')
								SET @1Result = (ISNULL(@1Result,0)/@lLastDayOfMonth) * @1WorkingDays
							ELSE
								SET @1Result = (ISNULL(@1Result,0)/30) * @1WorkingDays
						END	
					ELSE
						SET @1Result = (ISNULL(@1Result,0)/@1WorkingDays) * @1WorkingDays 
			    END	    
			    
			  --  IF(@1PayElementDefaultId=1)
			  --  BEGIN 
					--IF (@lIsPayrollCountBasedOnWorkingDays IS NULL) OR (@lIsPayrollCountBasedOnWorkingDays = 'False')	
					--	SET @1Result = (ISNULL(@1Result,0)/@lLastDayOfMonth) * @1WorkingDays
					--ELSE
					--	SET @1Result = (ISNULL(@1Result,0)/@1WorkingDays) * @1WorkingDays 
			  --  END	 
			    
			  --  IF(@1PayElementDefaultId!=1 AND @1IsDepend = 0 AND @lIsCalculateAllPayElementAsPerJoining IS NULL) OR (@lIsCalculateAllPayElementAsPerJoining = 'False')
			  --  BEGIN 
					--IF (@lIsPayrollCountBasedOnWorkingDays IS NULL) OR (@lIsPayrollCountBasedOnWorkingDays = 'False')	
					--	SET @1Result = (ISNULL(@1Result,0)/@lLastDayOfMonth) * @1WorkingDays
					--ELSE
					--	SET @1Result = (ISNULL(@1Result,0)/@1WorkingDays) * @1WorkingDays
			  --  END	    
			       
			    IF(@1IsLwp = 1) 			     
			        SELECT @1LWPDeduction = [sPayroll].[fCalculateLWP] (@rEmployeeId, @rPayProcessId,ISNULL(@1Result,0))			      
			           
			    IF(@1IsDepend = 1 AND @1PayElementDefaultId NOT IN(55,56,57)) -- ESI,PF,PT seperatly calculated
					BEGIN 
						
						EXECUTE [sPayroll].[pCalculatePayrollAmount]  @1PaySetupId,@1PayElementId,@1Percentage,@1SourceId,@rOrgGroupId,@rEmployeeId,@lNextNumber,@rPayrollId,@rPayrollYearId,@lFormula,@1Result OUTPUT
						-- PRINT CAST(@1Result As varchar) + 'FormulaAmount' + CAST(@1PayElementDefaultId As nvarchar) 
					END
			    
			           
			    IF(@1WorkingDays = 0)      
					SET @1Result =  0    
			    ELSE
					SET @1Result =  ROUND(ISNULL(@1Result,0.0) -  ISNULL(@1LWPDeduction,0.00),@lRoundOffToWholeNumber)	       
				
			    EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sPayroll.tPayProcessElement', 0, 1, 1,@outNextNumber = @1PayProcessElementId output	
			        
			    IF (@lConfigValue IS NULL) OR (@lConfigValue = 'False')	
	        	BEGIN
	        		INSERT INTO  [sPayroll].[tPayProcessElement]
						   (
						    [ID]
						   ,[PayProcessEmployeeId]
						   ,[PayElementId]
						   ,[Amount]
						   )
					 VALUES
						   (
						    @1PayProcessElementId
						   ,@lNextNumber
						   ,@1PayElementId
						   ,@1Result
						   ) 
						   -- PRINT CAST(@1Result As varchar) + ' Config, '  + CAST(@1PayProcessElementId  As varchar) 
	        	END
	        	ELSE
	        	BEGIN
	        		IF(@1PayElementDefaultId = 58)
	        		BEGIN
	        		INSERT INTO  [sPayroll].[tPayProcessElement]
						   (
						    [ID]
						   ,[PayProcessEmployeeId]
						   ,[PayElementId]
						   ,[Amount]
						   )
					 VALUES
						   (
						    @1PayProcessElementId
						   ,@lNextNumber
						   ,@1PayElementId
						  ,[sLoan].[fEmployeeLoanInstalmentGet](@rSalaryMonth,@rSalaryYear,@1EmployeeId,58)
						  
						   )  
						   -- PRINT CAST(@1Result As varchar) + ' 58, '  + CAST(@1PayProcessElementId  As varchar)
					END
	        		ELSE IF(@1PayElementDefaultId = 63)
	        		BEGIN
	        		INSERT INTO  [sPayroll].[tPayProcessElement]
						   (
						    [ID]
						   ,[PayProcessEmployeeId]
						   ,[PayElementId]
						   ,[Amount]
						   )
					 VALUES
						   (
						    @1PayProcessElementId
						   ,@lNextNumber
						   ,@1PayElementId
						   ,[sLoan].[fEmployeeLoanInstalmentGet](@rSalaryMonth,@rSalaryYear,@1EmployeeId,63)
						   
						   )  
						   -- PRINT CAST(@1Result As varchar) + ' 63, '  + CAST(@1PayProcessElementId  As varchar)
					END
					ELSE
					BEGIN
					INSERT INTO  [sPayroll].[tPayProcessElement]
						   (
						    [ID]
						   ,[PayProcessEmployeeId]
						   ,[PayElementId]
						   ,[Amount]
						   )
					 VALUES
						   (
						    @1PayProcessElementId
						   ,@lNextNumber
						   ,@1PayElementId
						   ,@1Result
						   ) 
						   -- PRINT CAST(@1Result As varchar) + ' else, '  + CAST(@1PayProcessElementId  As varchar)
					END	
					
				END
			    
			      IF(@1WorkingDays = 0)
			      BEGIN
						IF( @1PayElementTypeId = 1)
						 BEGIN	      	 
						  IF(@lIsIncludeInTotal = 1)
							SET @1TotalEarningAmount = 0 
						  ELSE
							SET @1TotalEarningAmount = 0
						 END
						 ELSE 
						 BEGIN 
							IF(@lIsIncludeInTotal = 1)
								SET @1TotalDeductionAmount = 0
							ELSE
								SET @1TotalDeductionAmount = 0
						 END   
			      END
			      ELSE
			      BEGIN
			             IF( @1PayElementTypeId = 1)
						 BEGIN	      	 
						  IF(@lIsIncludeInTotal = 1)
							SET @1TotalEarningAmount = ISNULL(@1TotalEarningAmount,0) + ISNULL(@1Result,0)		      
						  ELSE
							SET @1TotalEarningAmount = ISNULL(@1TotalEarningAmount,0)	      
						 END
						 ELSE 
						 BEGIN 
							IF(@lIsIncludeInTotal = 1)
								SET @1TotalDeductionAmount = ISNULL(@1TotalDeductionAmount,0) + ISNULL(@1Result,0) 	      
							ELSE
								SET @1TotalDeductionAmount = ISNULL(@1TotalDeductionAmount,0)	  
						 END   
			      END
			       
			     SET @1PayElementCount = @1PayElementCount -1	
			   	
			   	 END
			   	 
			DROP TABLE #TempPaysetupElement
				   
		   EXECUTE [sPayroll].[pCalculateStaticPayElement]  @lNextNumber,@rOrgGroupId,@1TotalEarningAmount,@1SourceId,@1TotalDeductionAmount,@rPayrollId,@rPayrollYearId,@lPayrollGroupId,@rSalaryMonth,@rSalaryYear,@rEmployeeId,@rIsAllow --mantis: 40774, add @rIsAllow
	    
		
	SELECT @lNextNumber AS Result	
	
	END	
    
	 
END
GO
PRINT N'Altering Procedure [sTransport].[pVehicleMasterAdd]...';


GO
ALTER PROCEDURE [sTransport].[pVehicleMasterAdd]
	 
	@rId int,
	@rTitle nvarchar(100),
	@rRegistrationNumber nvarchar(100)='',
	@rVehicleTypeId int,
	@rNoOfSeats int,
	@rCreatedUserId bigint,
	@rIsObsolete bit,
	@rOrgGroupId int,
	@rLastServiceDate date='',
	@rNextServiceDate date='',
	@rFuelTypeId int=0,
	@rServiceCenter nvarchar(200)='',
	@rServiceCenterContact nvarchar(50)='',
	@rTransportId int=0
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	 BEGIN TRANSACTION	
 IF(@rId = 0)	
BEGIN
		If Exists(select Id from sTransport.tVehicleMaster where Title=@rTitle  AND OrgGroupId=@rOrgGroupId AND TransportId = @rTransportId)
			BEGIN
			select -103 as Result
			COMMIT TRANSACTION
			RETURN
		END 
	END	
	DECLARE @lNextNumber BIGINT     
		
	IF(@rId = 0)	
	BEGIN
	
EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sTransport.tVehicleMaster', 0, 1, 1,@outNextNumber = @lNextNumber output

	INSERT INTO sTransport.tVehicleMaster
		(
			Id,
			Title,
			RegistrationNumber,
			VehicleTypeId,
			NoOfSeats,
			CreatedUserId,
			CreatedDateTime,
			IsObsolete,
			OrgGroupId,
			LastServiceDate,
			NextServiceDate,
			FuelTypeId,
	        ServiceCenter,
	        ServiceCenterContact,
	        TransportId
		)
	VALUES
		(
			@lNextNumber,
			@rTitle,
			ISNULL(@rRegistrationNumber,''),
			@rVehicleTypeId,
			@rNoOfSeats,
			@rCreatedUserId,
			sCommon.fGetDate(), 
			@rIsObsolete,
			@rOrgGroupId,
			@rLastServiceDate,
			@rNextServiceDate,
			@rFuelTypeId,
			@rServiceCenter,
	        @rServiceCenterContact,
	        @rTransportId
			
		)
		    select @lNextNumber as Result         
	END	 
	 ELSE
		If  Exists(select Id from sTransport.tVehicleMaster where Title=@rTitle  AND Id<>@rId  AND TransportId = @rTransportId)
		Begin
			select -103 as Result
			COMMIT TRANSACTION
			RETURN
		
	END	
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE  sTransport.tVehicleMaster
	    SET
			Title=@rTitle,
			RegistrationNumber=@rRegistrationNumber,
			VehicleTypeId=@rVehicleTypeId,
			NoOfSeats=@rNoOfSeats,
			UpdatedUserId=@rCreatedUserId,
			UpdatedDateTime=sCommon.fGetDate(), 
			IsObsolete=@rIsObsolete,
			LastServiceDate=@rLastServiceDate,
			NextServiceDate=@rNextServiceDate,
			FuelTypeId=@rFuelTypeId,
			ServiceCenter=@rServiceCenter,
	        ServiceCenterContact=@rServiceCenterContact
	      
	      
	      WHERE Id = @rId and OrgGroupId=@rOrgGroupId and TransportId = @rTransportId
	       SELECT 105 AS Result
	
	 END  
		
		COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Altering Procedure [sCommunication].[pBehaviourEntryAdd]...';


GO

ALTER PROCEDURE [sCommunication].[pBehaviourEntryAdd]
	 
	@rId bigint,
	@rBehaviourDate date,
	@rAcademicId  bigint,
	@rBehaviourTypeId int,
	@rTitle nvarchar(100),
	@rRemark nvarchar(1000), --length 500 to 1000 add for mantis : 0043364
	@rCreatedUserId bigint,
	@rCreatedDateTime datetime,
	@rOrgGroupId smallint
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
		--IF(@rId = 0)	
--	IF Exists(Select @rCode from	sLibrary.tBookMaster where Code=@rCode)
--BEGIN
--Select -103 AS Result
--RETURN
--END	
BEGIN TRANSACTION

IF(@rId = 0)

    BEGIN
DECLARE @lNextNumber BIGINT     
	EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sCommunication.tBehaviour', 0, 1, 1,@outNextNumber = @lNextNumber output

	INSERT INTO sCommunication.tBehaviour
		(
			Id,
			BehaviourDate,
			AcademicId,
			BehaviourTypeId,
			Title,
			Remark,
			CreatedUserId,
			CreatedDateTime
		)
	VALUES
		(
			@lNextNumber,
			@rBehaviourDate,
			@rAcademicId,
			@rBehaviourTypeId,
			@rTitle,
			ISNULL(@rRemark,''),
			@rCreatedUserId,
			sCommon.fGetDate()
		)
		   Select @lNextNumber AS Result
	END
	ELSE
	
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE  sCommunication.tBehaviour
	    SET
			BehaviourDate=@rBehaviourDate,
			AcademicId=@rAcademicId,
			BehaviourTypeId=@rBehaviourTypeId,
			Title=@rTitle,
			Remark=ISNULL(@rRemark,'')
	--		BehaviourIndicatorId=@rBehaviourIndicatorId,
	--		OrgId=@rOrgId,
	--		IsObsolete=@rIsObsolete,
	--		UpdatedUserId=@rUpdatedUserId,
	--		UpdatedDateTime= sCommon.fGetDate()
			
	      
	      WHERE Id = @rId 
     SELECT @lNextNumber AS Result
	
END	
	
	COMMIT TRANSACTION
END TRY

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


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

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

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

		SET @lInquiryNumber= @rNumber

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

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

 BEGIN TRANSACTION	
	IF(@rId = 0)	
	BEGIN	

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

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


GO

ALTER PROCEDURE [sCertificate].[pBonafideAdd]

	@rId bigint
   ,@rAcademicId bigint
   ,@rNumber int
   ,@rBonafideDate date
   ,@rCreatedUserId bigint
   ,@rOrgId int
   ,@rRemark nvarchar(MAX)
   ,@rBonafiedReason nvarchar(200)
   ,@rBatchId int
   ,@rIsNumberBatchWise bit = 0
           	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

	--DECLARE @lOrgGroupId smallint
	--SELECT @lOrgGroupId = OrgGroupId from sSetup.tOrganizationMaster Where Id = @rOrgId

	--DECLARE @lIsBonafideCertificateNumberBatchWise bit
	--SELECT @lIsBonafideCertificateNumberBatchWise = ISNULL(CS.ItemValue,CM.ItemValue) From sConfig.tConfigurationMaster CM
	--	    LEFT JOIN sConfig.tConfigurationSetup CS ON CM.Id = CS.ConfigurationId AND SourceTypeId = 2010 AND SourceId = @lOrgGroupId
	--	    WHERE CS.ConfigurationId = 290 

	BEGIN TRY	
	 BEGIN TRANSACTION	
	 
	 If(@rIsNumberBatchWise = 0)
	 BEGIN
		IF(@rNumber = 0)	
		BEGIN
			SELECT @rNumber = ISNULL(MAX(Number),0) + 1 FROM sCertificate.tBonafide WHERE OrgId=@rOrgId
		END	
			
		IF(@rId = 0)	
		BEGIN
			IF EXISTS(SELECT 1 FROM sCertificate.tBonafide WHERE Number=@rNumber AND OrgId=@rOrgId)
			BEGIN
				SELECT -103 AS Result
				COMMIT TRANSACTION
				RETURN
			END
		END
	 END
	 
	 If(@rIsNumberBatchWise = 1)
	 BEGIN
		IF(@rNumber = 0)	
		BEGIN
			SELECT @rNumber = ISNULL(MAX(Number),0) + 1 FROM sCertificate.tBonafide WHERE OrgId=@rOrgId AND BatchId = @rBatchId
		END	
			
		IF(@rId = 0)	
		BEGIN
			IF EXISTS(SELECT 1 FROM sCertificate.tBonafide WHERE Number=@rNumber AND OrgId=@rOrgId AND BatchId = @rBatchId)
			BEGIN
				SELECT -103 AS Result
				COMMIT TRANSACTION
				RETURN
			END
		END
	 END
	
	  DECLARE @lNextNumber BIGINT
	  IF(@rId = 0)	
		BEGIN
			EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sCertificate.tBonafide', 0, 1, 1,@outNextNumber = @lNextNumber output
				INSERT INTO sCertificate.tBonafide
				(
					Id
				   ,AcademicId
				   ,Number
				   ,BonafideDate
				   ,OrgId
				   ,CreatedUserId
				   ,CreatedDateTime
				   ,Remark
				   ,BonafiedReason
				   ,BatchId
				)
				VALUES
				(	@lNextNumber
				   ,@rAcademicId
				   ,@rNumber
				   ,@rBonafideDate
				   ,@rOrgId
				   ,@rCreatedUserId
				   ,sCommon.fGetDate()
				   ,@rRemark 
				   ,@rBonafiedReason
				   ,@rBatchId
				)
		END
		
		ELSE
		
		BEGIN
			SET @lNextNumber = @rId
				UPDATE  sCertificate.tBonafide
				SET
					AcademicId=@rAcademicId,
					BonafideDate=@rBonafideDate,
					UpdatedUserId=@rCreatedUserId,
					UpdatedDateTime=sCommon.fGetDate(),
					Remark=@rRemark,
					BonafiedReason=@rBonafiedReason,
					BatchId = @rBatchId
				WHERE Id = @rId
		 END  	
		
		SELECT @lNextNumber AS Result
	
	COMMIT TRANSACTION
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
	
END
GO
PRINT N'Altering Procedure [sCertificate].[pFirstTrialAdd]...';


GO


ALTER PROCEDURE [sCertificate].[pFirstTrialAdd]
			
		@rId bigint
       ,@rAcademicId bigint
       ,@rNumber int
       ,@rFirstTrialDate date
       ,@rExamYear nvarchar(20)
       ,@rExamCentre nvarchar(100)
       ,@rSeatNo nvarchar(50)
       ,@rTrial nvarchar(20)
       ,@rCreatedUserId bigint
       ,@rOrgId int
       ,@rRemark nvarchar(200)
       ,@rBatchId int
       ,@rIsNumberBatchWise bit = 0
	   ,@rLastExamName nvarchar(150) = '' -- Mantis : 0027927 #Start
	   ,@rObtainedMark nvarchar(100) = ''
	   ,@rAdditionalRemark nvarchar(max) = '' -- #End

           	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN	
	If(@rIsNumberBatchWise = 1)
	BEGIN
		IF(@rNumber = 0)	
		BEGIN
			SELECT @rNumber = ISNULL(MAX(Number),0) FROM sCertificate.tFirstTrial WHERE OrgId=@rOrgId AND BatchId = @rBatchId
			SET @rNumber = @rNumber + 1
		END	
			
		IF(@rId = 0)	
		BEGIN
			IF EXISTS (SELECT Id FROM sCertificate.tFirstTrial WHERE AcademicId=@rAcademicId AND BatchId = @rBatchId)
			BEGIN
				SELECT -103 AS Result
				RETURN
			END
			
			IF EXISTS(SELECT 1 FROM sCertificate.tFirstTrial WHERE Number=@rNumber AND OrgId=@rOrgId AND BatchId = @rBatchId)
			BEGIN
				SELECT -104 AS Result
				RETURN
			END
		END
	 END
	 ELSE
	 BEGIN
		IF(@rNumber = 0)	
		BEGIN
			SELECT @rNumber = ISNULL(MAX(Number),0) FROM sCertificate.tFirstTrial WHERE OrgId=@rOrgId AND BatchId = @rBatchId
			SET @rNumber = @rNumber + 1
		END	
			
		IF(@rId = 0)	
		BEGIN
			IF EXISTS (SELECT Id FROM sCertificate.tFirstTrial WHERE AcademicId=@rAcademicId)
			BEGIN
				SELECT -103 AS Result
				RETURN
			END
			
			IF EXISTS(SELECT 1 FROM sCertificate.tFirstTrial WHERE Number=@rNumber AND OrgId=@rOrgId AND BatchId = @rBatchId)
			BEGIN
				SELECT -104 AS Result
				RETURN
			END
		END
	  END
	 
	  DECLARE @lNextNumber BIGINT
	  BEGIN TRY
	BEGIN TRANSACTION
	  IF(@rId = 0)	
		BEGIN
			
			EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sCertificate.tFirstTrial', 0, 1, 1,@outNextNumber = @lNextNumber output
			
			INSERT INTO sCertificate.tFirstTrial
			(
				Id
			   ,AcademicId
			   ,Number
			   ,FirstTrialDate
			   ,ExamYear
			   ,ExamCentre
			   ,SeatNo
			   ,Trial
			   ,OrgId
			   ,CreatedUserId
			   ,CreatedDateTime
			   ,Remark
			   ,BatchId
			   ,LastExamName -- Mantis : 0027927 #Start
			   ,ObtainedMark
			   ,AdditionalRemark -- #End
			)
			VALUES
			(	@lNextNumber
			   ,@rAcademicId
			   ,@rNumber
			   ,@rFirstTrialDate
			   ,@rExamYear
			   ,@rExamCentre
			   ,@rSeatNo
			   ,@rTrial
			   ,@rOrgId
			   ,@rCreatedUserId
			   ,sCommon.fGetDate()
			   ,@rRemark 
			   ,@rBatchId
			   ,@rLastExamName  -- Mantis : 0027927 #Start
			   ,@rObtainedMark
			   ,@rAdditionalRemark  -- #End
			)		
			SELECT @lNextNumber AS Result
		END
		
		ELSE
		 BEGIN
		 IF  EXISTS(SELECT Id FROM sCertificate.tFirstTrial WHERE AcademicId=@rAcademicId AND Id<>@rId)
		BEGIN
			SELECT -103 AS Result
			COMMIT TRANSACTION
			RETURN
		END
		 SET @lNextNumber = @rId
			UPDATE  sCertificate.tFirstTrial
			SET
				AcademicId=@rAcademicId,
				FirstTrialDate=@rFirstTrialDate,
				ExamYear=@rExamYear,
				ExamCentre=@rExamCentre,
				SeatNo=@rSeatNo,
				Trial=@rTrial,
				UpdatedUserId=@rCreatedUserId,
				UpdatedDateTime=sCommon.fGetDate(),
				Remark=@rRemark,
				BatchId = @rBatchId,
				LastExamName = @rLastExamName, -- Mantis : 0027927 #Start
				ObtainedMark = @rObtainedMark,
				AdditionalRemark = @rAdditionalRemark -- #End
			  WHERE Id = @rId
			  SELECT @lNextNumber AS Result
		 END  	
	
	COMMIT TRANSACTION
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
	
END
GO
PRINT N'Altering Procedure [sPayroll].[pPayProcessAdd]...';


GO
ALTER PROCEDURE [sPayroll].[pPayProcessAdd] 
	      
	        @rID int
           ,@rSalaryMonth tinyint
           ,@rSalaryYear smallint
           ,@rIsApproved bit
           ,@rStartDateTime datetime           
           ,@rStatusId smallint
           ,@rCreatedUserId bigint        
           ,@rPayrollYearId int
           ,@rOrgGroupId int
           ,@rPayrollId int
           ,@rEmployeeId bigint=0
		   ,@rIsAllow bit=0 --mantis: 40774
           
          
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	DECLARE @lNextNumber bigint
	DECLARE @lPayProcessId int=0
	
	IF(@rEmployeeId=0)
	BEGIN 
		IF EXISTS(Select 1 FROM sPayroll.tPayProcess Where SalaryMonth = @rSalaryMonth AND SalaryYear = @rSalaryYear AND PayrollYearId = @rPayrollYearId)
		BEGIN
				SELECT -101 as Result
				RETURN
		END		
	END
	ELSE 
	BEGIN
		IF EXISTS(SELECT 1 FROM sPayroll.tPayProcess PP INNER JOIN sPayroll.tPayProcessEmployee PPE ON PP.Id = PPE.PayProcessId Where PP.SalaryMonth = @rSalaryMonth AND PP.SalaryYear = @rSalaryYear AND PP.PayrollYearId = @rPayrollYearId AND PPE.EmployeeId = @rEmployeeId)
		BEGIN
				SELECT -101 as Result
				RETURN
		END		
		
		SELECT @lPayProcessId = ID  FROM sPayroll.tPayProcess Where  SalaryMonth = @rSalaryMonth AND SalaryYear = @rSalaryYear AND PayrollYearId = @rPayrollYearId
	END
	
		
	BEGIN TRY
	BEGIN TRANSACTION  
    IF(@rEmployeeId=0)
	BEGIN 
     IF EXISTS(Select 1 FROM sPayroll.tPayProcess Where SalaryMonth = @rSalaryMonth AND SalaryYear = @rSalaryYear AND PayrollYearId = @rPayrollYearId)
      BEGIN      
		
		SELECT @lPayProcessId = ID  FROM sPayroll.tPayProcess Where  SalaryMonth = @rSalaryMonth AND SalaryYear = @rSalaryYear AND PayrollYearId = @rPayrollYearId
		 
		DELETE PE from sPayroll.tPayProcessEmployee  PPE
		INNER JOIN sPayroll.tPayProcessElement PE ON PE.PayProcessEmployeeId = PPE.ID
		WHERE PayProcessId = @lPayProcessId 
		
		DELETE FROM sPayroll.tPayProcessEmployee where PayProcessId = @lPayProcessId
        
        DELETE FROM sPayroll.tPayProcess Where  SalaryMonth = @rSalaryMonth AND SalaryYear = @rSalaryYear AND PayrollYearId = @rPayrollYearId        
        
        DELETE FROM sPayroll.tPfProcess Where PayProcessElementId NOT IN (Select ID From sPayroll.tPayProcessElement)
		DELETE FROM sPayroll.tEsiProcess Where PayProcessElementId NOT IN (Select ID From sPayroll.tPayProcessElement)
      END
     END 
    
    
    IF(@lPayProcessId=0)
    BEGIN
	EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sPayroll.tPayProcess', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	INSERT INTO  [sPayroll].[tPayProcess]
           (
            [ID]
           ,[SalaryMonth]
           ,[SalaryYear]
           ,[IsApproved]
           ,[StartDateTime]   
           ,EndDateTime     
           ,[StatusId]
           ,[CreatedUserId]
           ,[CreatedDateTime]
           ,[PayrollYearId]
           )
     VALUES
           (
            @lNextNumber
           ,@rSalaryMonth
           ,@rSalaryYear
           ,@rIsApproved
           ,sCommon.fGetDate()
           ,NULL
           ,@rStatusId
           ,@rCreatedUserId
           ,sCommon.fGetDate()
           ,@rPayrollYearId
           )
		    Print @lNextNumber
     SELECT @lNextNumber AS Result   --Added by dhananjay for mantis : 
    EXECUTE [sPayroll].[pPayProcessEmployeeAdd] @lNextNumber,@rOrgGroupId,@rPayrollId,@rPayrollYearId,@rSalaryMonth,@rSalaryYear,@rEmployeeId,@rIsAllow --mantis: 40774, add @rIsAllow
	
	END
	ELSE
	BEGIN
		SELECT @lPayProcessId AS Result --Added by dhananjay for mantis : 
	  EXECUTE [sPayroll].[pPayProcessEmployeeAdd] @lPayProcessId,@rOrgGroupId,@rPayrollId,@rPayrollYearId,@rSalaryMonth,@rSalaryYear,@rEmployeeId,@rIsAllow --mantis: 40774, add @rIsAllow
	 
	END
	
	COMMIT TRANSACTION
	END TRY
	BEGIN CATCH
	ROLLBACK TRANSACTION
	 RAISERROR ('Error Creating Pay Process Detail', -- Message text.
               16, -- Severity.
               1 -- State.
               );
	SELECT -1 AS RESULT
	END CATCH	
END
GO

-- To Update TimeTable Table RowId - Migration
IF EXISTS(SELECT * FROM [sCommon].[tTableRowIdMaster] WHERE TableTitle = 'sTimetable.tTempSTimeTable')
BEGIN
	UPDATE [sCommon].[tTableRowIdMaster] SET IdDataType = 'int' WHERE TableTitle = 'sTimetable.tTempSTimeTable' AND IdDataType = 'bigint'
	IF NOT EXISTS(SELECT TOP 1 * FROM sTimetable.tTempSTimeTable)
	BEGIN
		IF EXISTS(SELECT * FROM [sCommon].[tTableRowId] WHERE TableTitle = 'sTimetable.tTempSTimeTable')
		BEGIN
			DELETE FROM [sCommon].[tTableRowId] WHERE TableTitle = 'sTimetable.tTempSTimeTable'
		END
	END
	ELSE
	BEGIN
		IF EXISTS(SELECT * FROM [sCommon].[tTableRowId] WHERE TableTitle = 'sTimetable.tTempSTimeTable'  and (Seed >= 1000000000 OR CurrentNumber >= 1000000000))
		BEGIN
			DELETE FROM [sCommon].[tTableRowId] WHERE TableTitle = 'sTimetable.tTempSTimeTable' and (Seed >= 1000000000 OR CurrentNumber >= 1000000000)
		END
	END
END
GO

PRINT N'Update complete.';

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

