

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


GO
PRINT N'Starting rebuilding table [sAccounting].[tBudget]...';


GO
BEGIN TRANSACTION;

SET TRANSACTION ISOLATION LEVEL SERIALIZABLE;

SET XACT_ABORT ON;

CREATE TABLE [sAccounting].[tmp_ms_xx_tBudget] (
    [Id]               INT             NOT NULL,
    [LedgerId]         INT             NOT NULL,
    [BudgetAmount]     DECIMAL (20, 5) NULL,
    [AccountingYearId] INT             NULL,
    [CreatedUserId]    BIGINT          NOT NULL,
    [CreatedDateTime]  DATETIME        NOT NULL,
    [UpdatedUserId]    BIGINT          NULL,
    [UpdatedDateTime]  DATETIME        NULL,
    CONSTRAINT [tmp_ms_xx_constraint_PK_tBudget1] PRIMARY KEY CLUSTERED ([Id] ASC) WITH (FILLFACTOR = 85)
);

IF EXISTS (SELECT TOP 1 1 
           FROM   [sAccounting].[tBudget])
    BEGIN
        INSERT INTO [sAccounting].[tmp_ms_xx_tBudget] ([Id], [LedgerId], [BudgetAmount], [AccountingYearId], [CreatedUserId], [CreatedDateTime], [UpdatedUserId], [UpdatedDateTime])
        SELECT   [Id],
                 [LedgerId],
                 CAST ([BudgetAmount] AS DECIMAL (20, 5)),
                 [AccountingYearId],
                 [CreatedUserId],
                 [CreatedDateTime],
                 [UpdatedUserId],
                 [UpdatedDateTime]
        FROM     [sAccounting].[tBudget]
        ORDER BY [Id] ASC;
    END

DROP TABLE [sAccounting].[tBudget];

EXECUTE sp_rename N'[sAccounting].[tmp_ms_xx_tBudget]', N'tBudget';

EXECUTE sp_rename N'[sAccounting].[tmp_ms_xx_constraint_PK_tBudget1]', N'PK_tBudget', N'OBJECT';

COMMIT TRANSACTION;

SET TRANSACTION ISOLATION LEVEL READ COMMITTED;


GO
PRINT N'Starting rebuilding table [sAccounting].[tExpense]...';


GO
BEGIN TRANSACTION;

SET TRANSACTION ISOLATION LEVEL SERIALIZABLE;

SET XACT_ABORT ON;

CREATE TABLE [sAccounting].[tmp_ms_xx_tExpense] (
    [Id]                 INT             NOT NULL,
    [EmployeeId]         BIGINT          NULL,
    [ExpenseDate]        DATE            NOT NULL,
    [ExpenseGroupId]     INT             NOT NULL,
    [Amount]             DECIMAL (20, 5) NULL,
    [Remark]             NVARCHAR (200)  NULL,
    [CreatedUserId]      BIGINT          NOT NULL,
    [CreatedDateTime]    DATETIME        NOT NULL,
    [UpdatedUserId]      BIGINT          NULL,
    [UpdatedDateTime]    DATETIME        NULL,
    [OrgId]              SMALLINT        NULL,
    [StatusId]           INT             NULL,
    [StatusReason]       NVARCHAR (100)  NULL,
    [BatchId]            INT             NULL,
    [ActionByEmployeeId] BIGINT          NULL,
    CONSTRAINT [tmp_ms_xx_constraint_PK_tExpense1] PRIMARY KEY CLUSTERED ([Id] ASC) WITH (FILLFACTOR = 85)
);

IF EXISTS (SELECT TOP 1 1 
           FROM   [sAccounting].[tExpense])
    BEGIN
        INSERT INTO [sAccounting].[tmp_ms_xx_tExpense] ([Id], [EmployeeId], [ExpenseDate], [ExpenseGroupId], [Amount], [Remark], [CreatedUserId], [CreatedDateTime], [UpdatedUserId], [UpdatedDateTime], [OrgId], [StatusId], [StatusReason], [BatchId], [ActionByEmployeeId])
        SELECT   [Id],
                 [EmployeeId],
                 [ExpenseDate],
                 [ExpenseGroupId],
                 CAST ([Amount] AS DECIMAL (20, 5)),
                 [Remark],
                 [CreatedUserId],
                 [CreatedDateTime],
                 [UpdatedUserId],
                 [UpdatedDateTime],
                 [OrgId],
                 [StatusId],
                 [StatusReason],
                 [BatchId],
                 [ActionByEmployeeId]
        FROM     [sAccounting].[tExpense]
        ORDER BY [Id] ASC;
    END

DROP TABLE [sAccounting].[tExpense];

EXECUTE sp_rename N'[sAccounting].[tmp_ms_xx_tExpense]', N'tExpense';

EXECUTE sp_rename N'[sAccounting].[tmp_ms_xx_constraint_PK_tExpense1]', N'PK_tExpense', N'OBJECT';

COMMIT TRANSACTION;

SET TRANSACTION ISOLATION LEVEL READ COMMITTED;


GO
PRINT N'Starting rebuilding table [sAccounting].[tExpenseDetail]...';


GO
BEGIN TRANSACTION;

SET TRANSACTION ISOLATION LEVEL SERIALIZABLE;

SET XACT_ABORT ON;

CREATE TABLE [sAccounting].[tmp_ms_xx_tExpenseDetail] (
    [Id]                INT             IDENTITY (1, 1) NOT NULL,
    [ExpenseId]         INT             NULL,
    [ExpenseSubGroupId] INT             NULL,
    [Amount]            DECIMAL (20, 5) NULL,
    [Remark]            NVARCHAR (200)  NULL,
    CONSTRAINT [tmp_ms_xx_constraint_PK_tExpenseDetail1] PRIMARY KEY CLUSTERED ([Id] ASC) WITH (FILLFACTOR = 85)
);

IF EXISTS (SELECT TOP 1 1 
           FROM   [sAccounting].[tExpenseDetail])
    BEGIN
        SET IDENTITY_INSERT [sAccounting].[tmp_ms_xx_tExpenseDetail] ON;
        INSERT INTO [sAccounting].[tmp_ms_xx_tExpenseDetail] ([Id], [ExpenseId], [ExpenseSubGroupId], [Amount], [Remark])
        SELECT   [Id],
                 [ExpenseId],
                 [ExpenseSubGroupId],
                 CAST ([Amount] AS DECIMAL (20, 5)),
                 [Remark]
        FROM     [sAccounting].[tExpenseDetail]
        ORDER BY [Id] ASC;
        SET IDENTITY_INSERT [sAccounting].[tmp_ms_xx_tExpenseDetail] OFF;
    END

DROP TABLE [sAccounting].[tExpenseDetail];

EXECUTE sp_rename N'[sAccounting].[tmp_ms_xx_tExpenseDetail]', N'tExpenseDetail';

EXECUTE sp_rename N'[sAccounting].[tmp_ms_xx_constraint_PK_tExpenseDetail1]', N'PK_tExpenseDetail', N'OBJECT';

COMMIT TRANSACTION;

SET TRANSACTION ISOLATION LEVEL READ COMMITTED;


GO
PRINT N'Starting rebuilding table [sAccounting].[tExpenseSubGroupMaster]...';


GO
BEGIN TRANSACTION;

SET TRANSACTION ISOLATION LEVEL SERIALIZABLE;

SET XACT_ABORT ON;

CREATE TABLE [sAccounting].[tmp_ms_xx_tExpenseSubGroupMaster] (
    [Id]              INT             NOT NULL,
    [ExpenseGroupId]  INT             NOT NULL,
    [Code]            NVARCHAR (100)  NOT NULL,
    [Title]           NVARCHAR (100)  NOT NULL,
    [IsObsolete]      BIT             NOT NULL,
    [CreatedUserId]   BIGINT          NOT NULL,
    [CreatedDateTime] DATETIME        NOT NULL,
    [UpdatedUserId]   BIGINT          NULL,
    [UpdatedDateTime] DATETIME        NULL,
    [OrgId]           SMALLINT        NULL,
    [AmountLimit]     DECIMAL (20, 5) NULL,
    CONSTRAINT [tmp_ms_xx_constraint_PK_tExpenseSubGroupMaster1] PRIMARY KEY CLUSTERED ([Id] ASC) WITH (FILLFACTOR = 85)
);

IF EXISTS (SELECT TOP 1 1 
           FROM   [sAccounting].[tExpenseSubGroupMaster])
    BEGIN
        INSERT INTO [sAccounting].[tmp_ms_xx_tExpenseSubGroupMaster] ([Id], [ExpenseGroupId], [Code], [Title], [IsObsolete], [CreatedUserId], [CreatedDateTime], [UpdatedUserId], [UpdatedDateTime], [OrgId], [AmountLimit])
        SELECT   [Id],
                 [ExpenseGroupId],
                 [Code],
                 [Title],
                 [IsObsolete],
                 [CreatedUserId],
                 [CreatedDateTime],
                 [UpdatedUserId],
                 [UpdatedDateTime],
                 [OrgId],
                 CAST ([AmountLimit] AS DECIMAL (20, 5))
        FROM     [sAccounting].[tExpenseSubGroupMaster]
        ORDER BY [Id] ASC;
    END

DROP TABLE [sAccounting].[tExpenseSubGroupMaster];

EXECUTE sp_rename N'[sAccounting].[tmp_ms_xx_tExpenseSubGroupMaster]', N'tExpenseSubGroupMaster';

EXECUTE sp_rename N'[sAccounting].[tmp_ms_xx_constraint_PK_tExpenseSubGroupMaster1]', N'PK_tExpenseSubGroupMaster', N'OBJECT';

COMMIT TRANSACTION;

SET TRANSACTION ISOLATION LEVEL READ COMMITTED;


GO
PRINT N'Altering Table [sAccounting].[tLedgerMaster]...';


GO
ALTER TABLE [sAccounting].[tLedgerMaster] ALTER COLUMN [OpeningBalance] DECIMAL (20, 5) NULL;


GO
PRINT N'Starting rebuilding table [sAccounting].[tTransactionApproveDetail]...';


GO
BEGIN TRANSACTION;

SET TRANSACTION ISOLATION LEVEL SERIALIZABLE;

SET XACT_ABORT ON;

CREATE TABLE [sAccounting].[tmp_ms_xx_tTransactionApproveDetail] (
    [Id]                BIGINT          NOT NULL,
    [TransactionId]     BIGINT          NOT NULL,
    [Number]            BIGINT          NULL,
    [TransactionTypeId] NVARCHAR (10)   NULL,
    [LedgerId]          BIGINT          NULL,
    [Amount]            DECIMAL (20, 5) NULL,
    CONSTRAINT [tmp_ms_xx_constraint_PK_tTransactionApproveDetail1] PRIMARY KEY CLUSTERED ([Id] ASC) WITH (FILLFACTOR = 85)
);

IF EXISTS (SELECT TOP 1 1 
           FROM   [sAccounting].[tTransactionApproveDetail])
    BEGIN
        INSERT INTO [sAccounting].[tmp_ms_xx_tTransactionApproveDetail] ([Id], [TransactionId], [Number], [TransactionTypeId], [LedgerId], [Amount])
        SELECT   [Id],
                 [TransactionId],
                 [Number],
                 [TransactionTypeId],
                 [LedgerId],
                 CAST ([Amount] AS DECIMAL (20, 5))
        FROM     [sAccounting].[tTransactionApproveDetail]
        ORDER BY [Id] ASC;
    END

DROP TABLE [sAccounting].[tTransactionApproveDetail];

EXECUTE sp_rename N'[sAccounting].[tmp_ms_xx_tTransactionApproveDetail]', N'tTransactionApproveDetail';

EXECUTE sp_rename N'[sAccounting].[tmp_ms_xx_constraint_PK_tTransactionApproveDetail1]', N'PK_tTransactionApproveDetail', N'OBJECT';

COMMIT TRANSACTION;

SET TRANSACTION ISOLATION LEVEL READ COMMITTED;


GO
PRINT N'Altering Table [sAccounting].[tTransactionDetail]...';


GO
ALTER TABLE [sAccounting].[tTransactionDetail] ALTER COLUMN [Amount] DECIMAL (25, 5) NULL;


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


GO
ALTER TABLE [sAssessment].[tTempAllExam]
    ADD [BMI]                    DECIMAL (10, 2) NULL,
        [SubjectGroupOrderIndex] SMALLINT        NULL,
        [ExamMaximum]            DECIMAL (10, 2) NULL;


GO
PRINT N'Creating Table [dbo].[tExamReportTemplate]...';


GO
CREATE TABLE [dbo].[tExamReportTemplate] (
    [Id]             INT            IDENTITY (1, 1) NOT NULL,
    [HeaderContent]  NVARCHAR (MAX) NULL,
    [DetailsContent] NVARCHAR (MAX) NULL,
    [FooterContent]  NVARCHAR (MAX) NULL,
    PRIMARY KEY CLUSTERED ([Id] ASC)
);


GO

/******************************************************************************  
 Purpose          : To get Batch Wise  Class
 Created date     : 21 Nov 2013
 Author           : Kundan Patel 
 Copyright©       : Copyright © Sapphire Software Solutions
 ******************************************************************************/  
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.PresentCountry, ''), '') +
           COALESCE(',' + NULLIF(SC.PresentState, ''), '') +
           COALESCE(',' + NULLIF(SC.PresentCity, ''), '') +
            COALESCE(',' + NULLIF(SC.PresentZipCode, ''), '') +
            COALESCE(',' + NULLIF(SC.PresentContactNo, ''), ''),
           1, 1, '') AS LocalAddress
		    
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
GO
PRINT N'Altering View [sFee].[vFeeCustomSearch]...';


GO










/******************************************************************************  
 Purpose          : To get Batch Wise  Class
 Created date     : 21 Nov 2013
 Author           : Kundan Patel 
 Copyright©       : Copyright © Sapphire Software Solutions
 ******************************************************************************/  
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.PresentCountry, ''), '') +
           COALESCE(',' + NULLIF(SC.PresentState, ''), '') +
           COALESCE(',' + NULLIF(SC.PresentCity, ''), '') +
            COALESCE(',' + NULLIF(SC.PresentZipCode, ''), '') +
            COALESCE(',' + NULLIF(SC.PresentContactNo, ''), ''),
           1, 1, '') AS LocalAddress
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
GO
PRINT N'Altering Function [sFee].[fNextInstallmentDetailsGet]...';


GO

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

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

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


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

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


GO

ALTER PROCEDURE [sAccounting].[pBudgetAdd]
	@rId	int,
	@rLedgerId	int,
	@rBudgetAmount	decimal(20, 5), --Changed for mantis : 32211 by Nilesh
	@rAccountingYearId	int,
	@rUserId	bigint,
	@rOrgGroupId int
	
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 	
BEGIN TRY
 BEGIN TRANSACTION
 DECLARE @lNextNumber int
 IF(@rId = 0)	
	BEGIN
	EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sAccounting.tBudget', 0, 1, 1,@outNextNumber = @lNextNumber output
	INSERT INTO sAccounting.tBudget
	          (
	            Id,
				LedgerId,
				BudgetAmount,
				AccountingYearId,
				CreatedUserId,
				CreatedDateTime
			)
				VALUES
				( 
				@lNextNumber,
				@rLedgerId,
				@rBudgetAmount,
				@rAccountingYearId,
				@rUserId,
				sCommon.fGetDate()
				)
				SELECT 1 AS Result
	END
	  ELSE
	BEGIN
			UPDATE  sAccounting.tBudget SET
 
				LedgerId=@rLedgerId,
				BudgetAmount=@rBudgetAmount,
				UpdatedUserId=	@rUserId,
				UpdatedDateTime=sCommon.fGetDate()
			  WHERE AccountingYearId=@rAccountingYearId AND LedgerId=@rLedgerId AND Id=@rId
			  SELECT 11 AS Result
	END
	COMMIT TRANSACTION
	END TRY
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH
		
END
GO
PRINT N'Altering Procedure [sAccounting].[pExpenseOfCandidateAdd]...';


GO



ALTER PROCEDURE [sAccounting].[pExpenseOfCandidateAdd]
	 
	 @rOrgId smallint,
	   @rBatchId int,
	 @rId int,
	 @rEmployeeId bigint,
	 @rExpenseDate date,
	 @rExpenseGroupId int,
	 @rAmount decimal(20,5), --Changed for mantis : 32211 by Nilesh
	 @rRemark nvarchar(200),
	 @rCreatedUserId bigint,
	 --@rCreatedDateTime datetime,
	 @rUpdatedUserId bigint,
	 --@rUpdatedDateTime datetime,
	 @rStatusId int,
	 @rExpenseDetailXml nvarchar(max)
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
DECLARE @loDoc INT
EXEC sp_xml_preparedocument @loDoc OUTPUT, @rExpenseDetailXml
BEGIN
	--BEGIN TRY
	
	-- BEGIN TRANSACTION	
	 DECLARE @lNextNumber int

			IF(@rId = 0)	
			BEGIN
			EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sAccounting.tExpense', 0, 1, 1,@outNextNumber = @lNextNumber output
			--EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sCanteen.tCanteenMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
			INSERT INTO  sAccounting.tExpense
			(
			OrgId,
			 BatchId,
			Id,
			EmployeeId	,
			ExpenseDate	,
			ExpenseGroupId,
			Amount,
			Remark,
			CreatedUserId,
			CreatedDateTime,
			UpdatedUserId,
			UpdatedDateTime,
			StatusId	
			)
			VALUES
			(
		    @rOrgId ,
		    @rBatchId,
			@lNextNumber ,
			@rEmployeeId ,
			@rExpenseDate ,
			@rExpenseGroupId ,
			@rAmount ,
			@rRemark ,
			@rCreatedUserId ,
			sCommon.fGetDate() ,
			@rUpdatedUserId ,
			sCommon.fGetDate(),	
			@rStatusId 								
			)
		
			INSERT INTO sAccounting.tExpenseDetail
			(ExpenseId,
			ExpenseSubGroupId,
			Amount,Remark)
			SELECT @lNextNumber,ExpenseSubGroupId,Amount,sSetup.fPortalXMLTagsReplaceReverse(Remark)
			FROM OPENXML (@loDoc, '/Table/ExpenseDetail', 1)
			WITH (ExpenseSubGroupId int,Amount decimal(20,5),Remark nvarchar(200)) --Added for mantis : 32211 by Nilesh
		    SELECT @lNextNumber AS Result
			END	 

	ELSE
			BEGIN
			SET @lNextNumber = @rId
			UPDATE  sAccounting.tExpense
		    SET
	    
			ExpenseDate=@rExpenseDate,
			ExpenseGroupId=@rExpenseGroupId,
			Amount=@rAmount,
			Remark=@rRemark,			
			UpdatedUserId=@rCreatedUserId,
			UpdatedDateTime=sCommon.fGetDate(),
			StatusId=@rStatusId
	    
			WHERE Id = @rId
			DELETE sAccounting.tExpenseDetail WHERE ExpenseId= @rId
			INSERT INTO sAccounting.tExpenseDetail
			(ExpenseId,ExpenseSubGroupId,Amount,Remark)
			SELECT @lNextNumber,ExpenseSubGroupId,Amount,sSetup.fPortalXMLTagsReplaceReverse(Remark)
			FROM OPENXML (@loDoc, '/Table/ExpenseDetail', 1)
			WITH (ExpenseSubGroupId int,Amount decimal(20,5),Remark nvarchar(200)) --Added for mantis : 32211 by Nilesh
	 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 [sAccounting].[pRptExpenseListGet]...';


GO

ALTER PROCEDURE [sAccounting].[pRptExpenseListGet]
	 
	@rBuilder1 nvarchar(max)='',
	@rBuilder2 nvarchar(max)='',
	@rEmployeeCode nvarchar(100),
    @rEmployeeName nvarchar(100) ,
	@rEmployeeId  bigint=0, 
	@rFromDate date,
    @rTodate date,   
    @rExpenseGroupId int=0,    
    @rStatusId int=0,
    @rOrgId smallint,
    @rIsDetail bit,
      @rBatchId int
	

	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 

		/**Added for mantis : 32211 by Nilesh**/
	 Declare @DecimalCount INT
	 SELECT @DecimalCount = ItemValue from sConfig.tConfigurationSetup where ConfigurationId = 548

       SELECT 
			 @rBuilder1 AS Builder1,
			 @rBuilder2 AS Builder2, 
			 E.Id AS ExpenseId,
			 E.EmployeeId,
			 --E.Amount, --Commented for mantis : 32211 by Nilesh
			 (SELECT [dbo].[fDecimalValueGet] (E.Amount, @DecimalCount)), --Added for mantis : 32211 by Nilesh
			 E.Remark,
			 E.CreatedUserId,
			 E.CreatedDateTime,			 
			 E.UpdatedUserId,
			 E.UpdatedDateTime,
			 E.ExpenseDate,
			 E.ExpenseGroupId,
			 EGM.Title AS ExpenseGroupName,
			 EM.EmployeeName,
			 EM.Code AS EmployeeCode,
			 E.StatusReason,
			 ISNULL(E.StatusId,0) AS StatusId,
			 ISNULL(SM.Title,'Pending') AS StatusName,
			 --OM.DisplayTitle AS OrganizationName,
			 --ED.Amount AS ExpenseDetailAmount, --Commented for mantis : 32211 by Nilesh
			 (SELECT [dbo].[fDecimalValueGet] (ED.Amount, @DecimalCount)) AS ExpenseDetailAmount, --Added for mantis : 32211 by Nilesh
			 ESGM.Title As ExpenseTitle,
			 ESGM.Id As ExpenseSubGroupId,
			 @rIsDetail AS IsDetail,
			 ED.Remark AS ExpenseSubRemark
			 
        FROM 
				sAccounting.tExpense E
	  INNER JOIN sAccounting.tExpenseGroupMaster EGM ON EGM.Id = E.ExpenseGroupId
	  INNER JOIN sAccounting.tExpenseSubGroupMaster ESGM ON ESGM.ExpenseGroupId= EGM.Id
	  LEFT JOIN sAccounting.tExpenseDetail ED ON E.Id=ED.ExpenseId ANd ED.ExpenseSubGroupId = ESGM.Id
	  INNER JOIN sHrm.vEmployeeCommonDetail EM ON EM.EmployeeId = E.EmployeeId 
	  INNER JOIN sCommon.tStatusMaster SM ON SM.Id = E.StatusId
	  --INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = E.OrgId
    	WHERE 
    		
    		
    		--(E.Id = @rId OR @rId = 0)
     (E.EmployeeId = @rEmployeeId OR @rEmployeeId = 0)
      AND ((E.ExpenseDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
      AND ((E.ExpenseDate <= @rToDate) OR (ISNULL(@rToDate,'') = ''))
      AND (E.ExpenseGroupId = @rExpenseGroupId OR @rExpenseGroupId = 0)      
       AND ((E.OrgId = @rOrgId) OR (@rOrgId = 0))
           AND (E.BatchId = @rBatchId OR @rBatchId = 0)
      AND (EM.Code = @rEmployeeCode OR ISNULL(@rEmployeeCode,'') = '')
      AND (EM.EmployeeName like @rEmployeeName+'%' OR ISNULL(@rEmployeeName,'') = '')
      AND (E.StatusId = @rStatusId OR @rStatusId = 0)
      Order By ExpenseDate DESC
    		
END
GO
PRINT N'Altering Procedure [sAccounting].[pExpenseSubGroupMasterAdd]...';


GO
 
ALTER PROCEDURE [sAccounting].[pExpenseSubGroupMasterAdd]	 	   
        @rOrgId smallint,
        @rId int, 
        @rExpenseGroupId int,
        @rCode nvarchar(100),
        @rTitle nvarchar(100),  
		@rIsObsolete bit,	
		@rCreatedUserId bigint,
		@rUpdatedUserId bigint,
		@rAmountLimit decimal(20,5) --Changed for mantis : 32211 by Nilesh
		
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	--BEGIN TRY
	
	IF(@rId = 0)	
	BEGIN  
	 
		If Exists(select Id from  sAccounting.tExpenseSubGroupMaster where Code=@rCode AND OrgId=@rOrgId
		AND ExpenseGroupId=@rExpenseGroupId)
			BEGIN
			select -103 as Result
			RETURN
		END 
			If Exists(select Id from sAccounting.tExpenseSubGroupMaster  where Title=@rTitle AND OrgId=@rOrgId
			AND ExpenseGroupId=@rExpenseGroupId)
			BEGIN
			select -102 as Result
			RETURN
		END
	END
	ELSE
	BEGIN
			If  Exists(select Id from  sAccounting.tExpenseSubGroupMaster where Code=@rCode AND OrgId=@rOrgId 
			AND ExpenseGroupId=@rExpenseGroupId  AND Id<>@rId)
		Begin
			select -103 as Result
			RETURN
		End
		If  Exists(select Id from  sAccounting.tExpenseSubGroupMaster where Title=@rTitle AND OrgId=@rOrgId 
		AND ExpenseGroupId=@rExpenseGroupId AND Id<>@rId)
		Begin
			select -102 as Result
			RETURN
		End
	

	END
	
	
	
	 --BEGIN TRANSACTION	
	 DECLARE @lNextNumber int

	IF(@rId = 0)	
	BEGIN
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sAccounting.tExpenseSubGroupMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
	--EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sCanteen.tCanteenMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
	INSERT INTO sAccounting.tExpenseSubGroupMaster
		(
			OrgId,			
			Id,
			ExpenseGroupId,
			Code,
			Title, 
			IsObsolete,			
		    CreatedUserId, 
		    CreatedDateTime, 
		    UpdatedUserId, 
            UpdatedDateTime,
            AmountLimit
		)
	VALUES
		(
		    @rOrgId ,
			@lNextNumber , 
			@rExpenseGroupId,
			@rCode ,      
			@rTitle ,	
			@rIsObsolete,				
			@rCreatedUserId ,
			sCommon.fGetDate() ,
			@rUpdatedUserId ,
			sCommon.fGetDate(),
			@rAmountLimit									
		)
		
		   SELECT 1 AS Result
	END	 

ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE sAccounting.tExpenseSubGroupMaster
	    SET
			ExpenseGroupId=@rExpenseGroupId,
			Code=@rCode, 
	        Title=@rTitle,
	        IsObsolete=@rIsObsolete,
	        UpdatedUserId=@rCreatedUserId, 
            UpdatedDateTime=sCommon.fGetDate(),
            AmountLimit=@rAmountLimit
	      WHERE Id = @rId
	       SELECT 11 AS Result
	 END  	

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


GO
ALTER PROCEDURE [sAccounting].[pLedgerMasterAdd]
	 
	@rId int,
	@rCode nvarchar(100),
	@rTitle nvarchar(100),
	@rLedgerGroupId int,
	@rAccountingYearId int,
	@rCreatedUserId bigint,
	@rUpdatedUserId bigint,
	@rOpeningBalance decimal(20,5),
	@rLedgerTypeId int,
	@rIsObsolete bit,
	@rOrgGroupId int 
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY 
		IF(@rId = 0)	
	BEGIN
		IF Exists(select 1 from sAccounting.tLedgerMaster where Code=@rCode  AND AccountingYearId = @rAccountingYearId)
			BEGIN
			SELECT -101 AS Result
			RETURN
		END  
		   IF Exists(select 1 from sAccounting.tLedgerMaster where   Title = @rTitle AND AccountingYearId = @rAccountingYearId)
			BEGIN
			SELECT -102 AS Result
			RETURN
		END  
	END
	ELSE
	BEGIN
 
	   IF Exists(select 1 from sAccounting.tLedgerMaster where Code=@rCode  AND AccountingYearId = @rAccountingYearId AND ID <> @rId)
			BEGIN
			SELECT -101 AS Result
			RETURN
		END  
		   IF Exists(select 1 from sAccounting.tLedgerMaster where   Title = @rTitle AND AccountingYearId = @rAccountingYearId AND ID <> @rId)
			BEGIN
			SELECT -102 AS Result
			RETURN
		END  

	END 
	 BEGIN TRANSACTION	
 IF(@rId = 0)	
 BEGIN 
	DECLARE @lNextNumber INT
	EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sAccounting.tLedgerMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
	--EXECUTE [sCommon].[pGetIntMaxIdForOrgGroup] @rOrgGroupId, 'sAccounting.tLedgerMaster',@lNextNumber = @lNextNumber output

	INSERT INTO sAccounting.tLedgerMaster
		(
			Id,
			Code,
			Title,
			LedgerGroupId,
			AccountingYearId,
			CreatedUserId,
			CreatedDateTime,
			OpeningBalance,
			LedgerTypeId,
		    IsObsolete,
		    OrgGroupId			
		)
	VALUES
		(
			@lNextNumber,
			@rCode,
			@rTitle,
			@rLedgerGroupId,
			@rAccountingYearId,
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rOpeningBalance,
			@rLedgerTypeId,
			@rIsObsolete,
			@rOrgGroupId			
		)
		 SELECT 1 AS RESULT            
	END	 
	 ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE sAccounting.tLedgerMaster
	    SET
	      Code=@rCode,
	      Title=@rTitle,
	      LedgerGroupId=@rLedgerGroupId,	    
	      IsObsolete=@rIsObsolete,
	      UpdatedUserId=@rUpdatedUserId,
	      UpdatedDateTime= sCommon.fGetDate(),
	      OpeningBalance=@rOpeningBalance,
	      LedgerTypeId=@rLedgerTypeId 
	      WHERE Id = @rId 	AND AccountingYearId = @rAccountingYearId   
	 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 [sAccounting].[pLedgerMasterGet]...';


GO
ALTER PROCEDURE [sAccounting].[pLedgerMasterGet]

		@rBuilder1 nvarchar(max)='',
		@rBuilder2 nvarchar(max)='', 
		@rId int = 0,
		--@rAffiliationId int,
		@rTitle nvarchar(100),
		@rCode nvarchar(20),
		@rLedgerGroupId int,
		@rAccountingYearId int,
		@rOrgGroupId int,
		@rAccountId int=0
	 
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	Declare @1AccountId int
      
	BEGIN
		select @1AccountId = AccountId from sAccounting.tAccountingYearMaster Where Id = @rAccountingYearId
			
		SET @rTitle = sCommon.fSearchStringGet(@rTitle)
		SET @rCode = sCommon.fSearchStringGet(@rCode)
	END

	--change by dhruvik
	Declare @DecimalCount INT
	SELECT @DecimalCount = CASE WHEN CS.Id IS NOT NULL THEN ISNULL(CS.ItemValue,'') ELSE ISNULL(CM.ItemValue,'') END
	FROM sConfig.tConfigurationMaster CM
		LEFT JOIN sConfig.tConfigurationSetup CS ON CM.Id = CS.ConfigurationId
		AND SourceTypeId = 2010 AND SourceId = @rOrgGroupId WHERE CM.Id = 548
	 
	  SELECT 
		@rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2, 
		LM.Id,
		LM.Code,
		LM.Title,
		([sAccounting].[fDecimalValueGet] (LM.OpeningBalance, @DecimalCount)) AS OpeningBalance,	--change by dhruvik
		LM.IsObsolete,
		LGM.Id AS LedgerGroupId,
		LTM.Id AS LedgerTypeId,
		LGM.Title AS LedgerGroupTitle,
		LTM.Title AS LedgerTypeTitle,
		AM.ReportOrgTitle As OrgTitle,
			AM.SmallAddress1 AS SmallAddress1,
			AM.SmallAddress2 AS SmallAddress2 
	      
	  FROM 
		   sAccounting.tLedgerMaster LM
			INNER JOIN sAccounting.tLedgerTypeMaster LTM
			ON LM.LedgerTypeId= LTM.Id
			 INNER JOIN sAccounting.tLedgerGroupMaster LGM
			ON LM.LedgerGroupId= LGM.Id 
			  LEFT JOIN sAccounting.tAccountMaster AM ON AM.Id=LGM.AccountId
        
  WHERE  
        ((LM.Id = @rId) OR (@rId = 0))
        AND  ((LM.Title like @rTitle) OR (ISNULL(@rTitle,'') = '')) 
        AND  ((LM.Code like @rCode) OR (ISNULL(@rCode,'') = '')) 
        AND  ((LM.LedgerGroupId = @rLedgerGroupId) OR (@rLedgerGroupId = 0))
        AND ((LM.AccountingYearId =  @rAccountingYearId))
        AND ((LGM.AccountingYearId = @rAccountingYearId))
        And LGM.AccountId = @1AccountId AND LM.OrgGroupId = @rOrgGroupId
        	AND (LGM.AccountId=@rAccountId OR @rAccountId=0) 
        --AND ((LGM.OrgGroupId=@rOrgGroupId))
        
        --Do not Change Order By 
        order by LM.Id asc
		
END
GO
PRINT N'Altering Procedure [sAccounting].[pRptVoucherEntryApproveGet]...';


GO



ALTER PROCEDURE [sAccounting].[pRptVoucherEntryApproveGet]
	
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 @rTransactionId bigint,
	 @rAccountingYearId int,
	 @rTransactionDate date,
	 @rOrgGroupId int,
	 @rAccountId int
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN  

		/**Added for mantis : 32211 by Nilesh**/
	 Declare @DecimalCount INT
	 SELECT @DecimalCount = CASE WHEN CS.Id IS NOT NULL THEN ISNULL(CS.ItemValue,'') ELSE ISNULL(CM.ItemValue,'') END
						  FROM sConfig.tConfigurationMaster CM
						  LEFT JOIN sConfig.tConfigurationSetup CS ON CM.Id = CS.ConfigurationId
						  AND SourceTypeId = 2010 AND SourceId = @rOrgGroupId WHERE CM.Id = 548


  SELECT    @rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			T.Id AS Id,
			T.Narration,
			T.TransactionDate,
			T.VoucherNumber,
			--TD.Amount,
			[sAccounting].[fDecimalValueGet] (TD.Amount,@DecimalCount) Amount,
			TD.Id as TransactionDetailId,
			LM.Title AS Ledger,
			VTM.Title AS VoucherType,
			TD.TransactionTypeId ,
			--(CASE WHEN TD.Amount > 0 THEN TD.Amount
			--ELSE 0 END) DebitAmount,  --Commented for mantis : 32211 by Nilesh
			--(CASE WHEN TD.Amount < 0 THEN -1 * TD.Amount
			--ELSE 0 END) CreditAmount, --Commented for mantis : 32211 by Nilesh
			([sAccounting].[fDecimalValueGet] ((CASE WHEN TD.Amount > 0 THEN TD.Amount
												ELSE 0 END), @DecimalCount)) DebitAmount, --Added for mantis : 32211 by Nilesh
			([sAccounting].[fDecimalValueGet] ((CASE WHEN TD.Amount < 0 THEN  -1 * TD.Amount
												ELSE 0 END), @DecimalCount)) CreditAmount, --Added for mantis : 32211 by Nilesh
			AM.ReportOrgTitle As OrgTitle,
			AM.SmallAddress1 AS SmallAddress1,
			AM.SmallAddress2 AS SmallAddress2
			
			  
  FROM 
       sAccounting.tTransactionApprove T
       INNER JOIN sAccounting.tTransactionApproveDetail TD ON T.Id=TD.TransactionId
       LEFT JOIN sAccounting.tLedgerMaster LM On LM.Id=TD.LedgerId
       LEFT JOIN sAccounting.tVoucherTypeMaster VTM ON VTM.Id=T.VoucherTypeId
       LEFT JOIN sAccounting.tAccountMaster AM ON AM.Id=T.AccountId
      
      
  WHERE 
			(T.Id=@rTransactionId OR @rTransactionId = 0 )  
			AND (T.AccountingYearId=@rAccountingYearId)  AND LM.AccountingYearId = @rAccountingYearId
			ANd (T.TransactionDate=@rTransactionDate OR ISNULL(@rTransactionDate,'')='1900-01-01')     
			AND (T.OrgGroupId=@rOrgGroupId)
			AND (T.AccountId=@rAccountId )  
   Order By T.VoucherTypeId,T.VoucherNumber
END
GO
PRINT N'Altering Procedure [sAccounting].[pRptVoucherEntryGet]...';


GO

ALTER PROCEDURE [sAccounting].[pRptVoucherEntryGet]
	
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 @rTransactionId bigint,
	 @rAccountingYearId int,
	 @rTransactionDate date,
	 @rOrgGroupId int,
	 @rAccountId int
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
BEGIN  
Declare @DecimalCount INT
	 SELECT @DecimalCount = CASE WHEN CS.Id IS NOT NULL THEN ISNULL(CS.ItemValue,'') ELSE ISNULL(CM.ItemValue,'') END
						  FROM sConfig.tConfigurationMaster CM
						  LEFT JOIN sConfig.tConfigurationSetup CS ON CM.Id = CS.ConfigurationId
						  AND SourceTypeId = 2010 AND SourceId = @rOrgGroupId WHERE CM.Id = 548
	 
  SELECT    
        @rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,
		T.Id AS TransactionId,
		T.Narration,
		T.TransactionDate,
		T.VoucherNumber,
		TD.Amount,
		TD.Id as TransactionDetailId,
		LM.Title AS Ledger,
		VTM.Title AS VoucherType,
		TD.TransactionTypeId ,
		--(CASE WHEN TD.Amount > 0 THEN TD.Amount --Commented for mantis : 32211
		--ELSE 0 END) DebitAmount,
		--(CASE WHEN TD.Amount < 0 THEN -1 * TD.Amount Commented for mantis : 32211
		--ELSE 0 END) CreditAmount,
		([sAccounting].[fDecimalValueGet] ((CASE WHEN TD.Amount > 0 THEN TD.Amount
		ELSE 0 END), @DecimalCount)) DebitAmount, --Added for mantis : 32211
		([sAccounting].[fDecimalValueGet] ((CASE WHEN TD.Amount < 0 THEN  -1 * TD.Amount
		ELSE 0 END), @DecimalCount)) CreditAmount, --Added for mantis : 32211
		AM.ReportOrgTitle As OrgTitle,
		AM.SmallAddress1 AS SmallAddress1,
		AM.SmallAddress2 AS SmallAddress2,
		T.ChequeNo,
		T.ChequeDate,
		AM.Title as AccountTitle,
		U.DisplayTitle As CreatedUserName

		--sFinanceCommon.fNumberToWordsWithDecimal(ISNULL(TD.Amount,0.00),1,2,@rOrgGroupId) AS AmountInWords
			  
  FROM 
       sAccounting.tTransaction T
       INNER JOIN sAccounting.tTransactionDetail TD ON T.Id=TD.TransactionId
       LEFT JOIN sAccounting.tLedgerMaster LM On LM.Id=TD.LedgerId
       LEFT JOIN sAccounting.tVoucherTypeMaster VTM ON VTM.Id=T.VoucherTypeId
       LEFT JOIN sAccounting.tAccountMaster AM ON AM.Id=T.AccountId
	   LEFT JOIN sSecurity.tUser U ON U.Id = T.CreatedUserId
      
  WHERE 
		(T.Id=@rTransactionId OR @rTransactionId = 0 )  
		AND (T.AccountingYearId=@rAccountingYearId)  AND LM.AccountingYearId = @rAccountingYearId
		ANd (T.TransactionDate=@rTransactionDate OR ISNULL(@rTransactionDate,'')='1900-01-01')     
		AND (T.OrgGroupId=@rOrgGroupId)
		AND (T.AccountId=@rAccountId )  
   Order By T.VoucherTypeId,T.VoucherNumber
END
GO
PRINT N'Altering Procedure [sAccounting].[pTarij]...';


GO

ALTER PROCEDURE [sAccounting].[pTarij]

	@rBuilder1 nvarchar(max)='',
	@rBuilder2 nvarchar(max)='', 
	@rStartDate Date,
	@rEndDate Date,
	@rOrgGroupId int = 0,
	@rAccountingYearId [int],
	@rOrderBy smallint,
	@rTarij Smallint,
	@rAccountId  int=0
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN

   --SELECT '' AS Builder1,
	  --    '' AS Builder2,
   --       '' As Id,
		 -- '' As CreditBalance,
		 -- '' AS DebitBalance,
		 -- '' As CashOpBalance,
		 -- '' AS LedgerId,
		 -- '' AS LedgerName,
		 -- '' As LedgerTypeId,
		 -- '' AS OpeningBalance,
		 -- '' AS LedgerGroup,
		 -- '' AS LedgerMainGroup,
		 -- '' AS OrgTitle,
		 --'' AS  SmallAddress1,
		 -- '' AS SmallAddress2

Declare @lLedgerId int 
Declare @lCashOpBalance Decimal (12,2)
Declare @lOpeningBalance Decimal (12,2)
Declare @lCreditBalance Decimal (12,2)
Declare @lDebitBalance Decimal (12,2)
Declare @lLOpeningBalance Decimal(12,2)
Declare @lCount int
Declare @lLedgerTypeId int
Declare @lLedgerName Nvarchar(150)
Declare @lLedgerGroupName Nvarchar(150)
Declare @lLedgerMainGroupName Nvarchar(150)
Declare @ReportOrgTitle Nvarchar(200)
Declare @SmallAddress1  Nvarchar(200)
Declare	@SmallAddress2 Nvarchar(200)

	
	 SELECT @ReportOrgTitle=ReportOrgTitle ,@SmallAddress1=SmallAddress1, @SmallAddress2= SmallAddress2  
  From sAccounting.tAccountMaster AM Where AM.Id= @rAccountId  
	--EXEC [sAccounting].[pUpdateClosingBalance] @rStartDate,@rEndDate,@rOrgGroupId,@rAccountingYearId,@rLedgerId,@rLedgerMainGroupId,@rISProfitLoss
	
	SELECT @lLOpeningBalance = Sum(OpeningBalance) From sAccounting.tLedgerMaster L
	INNER JOIN sAccounting.tLedgerGroupMaster LG ON L.LedgerGroupId=LG.Id AND LG.LedgerMainGroupId = 2 and L.AccountingYearId=@rAccountingYearId And LG.OrgGroupId = @rOrgGroupId
    
	--change by dhruvik
	Declare @DecimalCount INT
	SELECT @DecimalCount = CASE WHEN CS.Id IS NOT NULL THEN ISNULL(CS.ItemValue,'') ELSE ISNULL(CM.ItemValue,'') END
	FROM sConfig.tConfigurationMaster CM
		LEFT JOIN sConfig.tConfigurationSetup CS ON CM.Id = CS.ConfigurationId
		AND SourceTypeId = 2010 AND SourceId = @rOrgGroupId WHERE CM.Id = 548

	CREATE TABLE #tTarij
 		(	Id INT IDENTITY (1,1),
 			CreditBalance decimal(12,2),
 			DebitBalance decimal(12,2),
 			CashOpBalance Decimal(12,2),
 			LedgerId int,
 			LedgerName varchar(100),
 			LedgerTypeId int,
 			OpeningBalance decimal(12,2),
 			LedgerGroup varchar(100),
			LedgerMainGroup Varchar(100)		
		
 		) 
 	IF @rTarij =1 
 	BEGIN	
 		INSERT INTO #tTarij    
		SELECT 
		(Select ISNULL(Sum(Amount),0) From sAccounting.tTransaction T INNER JOIN sAccounting.tTransactionDetail TD ON T.Id= TD.TransactionId And TD.LedgerId = L.Id And TD.TransactionTypeId= 1 And T.TransactionDate>=@rStartDate And T.TransactionDate <=@rEndDate AND T.AccountingYearID=@rAccountingYearId) as CreditBalance, 
		(Select ISNULL(Sum(Amount),0) From sAccounting.tTransaction T INNER JOIN sAccounting.tTransactionDetail TD ON T.Id= TD.TransactionId And TD.LedgerId = L.Id And TD.TransactionTypeId= 2 And T.TransactionDate>=@rStartDate And T.TransactionDate <=@rEndDate AND T.AccountingYearID=@rAccountingYearId) as DebitBalance, 
		(Select ISNULL(Sum(OpeningBalance),0) From sAccounting.tLedgerMaster L1 INNER JOIN sAccounting.tLedgerGroupMaster LG ON LG.Id=L1.LedgerGroupId AND LG.OrgGroupId=@rOrgGroupId AND L1.AccountingYearId=@rAccountingYearId) as CashOpBalance, 
		L.Id, L.Title, L.LedgerTypeId,L.OpeningBalance, 
		LG.Title AS GName, LGM.Title AS MGName 
		
       		
		FROM sAccounting.tLedgerMaster L INNER JOIN sAccounting.tLedgerGroupMaster LG on LG.Id=L.LedgerGroupId
		INNER JOIN sAccounting.tLedgerMainGroupMaster LGM ON LGM.Id = LG.LEDGERMAINGROUPID
		And LG.OrgGroupId= @rOrgGroupId AND L.AccountingYearId=@rAccountingYearId AND LG.AccountingYearId = @rAccountingYearId
		AND LG.LedgerMainGroupID <> 2
    END
     
    ELSE
    
    BEGIN
 		INSERT INTO #tTarij    
		SELECT 
		(Select ISNULL(Sum(Amount),0) From sAccounting.tTransaction T INNER JOIN sAccounting.tTransactionDetail TD ON T.Id= TD.TransactionId And TD.LedgerId = L.Id And TD.TransactionTypeId= 1 And T.TransactionDate>=@rStartDate And T.TransactionDate <=@rEndDate AND T.AccountingYearID=@rAccountingYearId) as CreditBalance, 
		(Select ISNULL(Sum(Amount),0) From sAccounting.tTransaction T INNER JOIN sAccounting.tTransactionDetail TD ON T.Id= TD.TransactionId And TD.LedgerId = L.Id And TD.TransactionTypeId= 2 And T.TransactionDate>=@rStartDate And T.TransactionDate <=@rEndDate AND T.AccountingYearID=@rAccountingYearId) as DebitBalance, 
		(Select ISNULL(Sum(OpeningBalance),0) From sAccounting.tLedgerMaster L1 INNER JOIN sAccounting.tLedgerGroupMaster LG ON LG.Id=L1.LedgerGroupId AND LG.OrgGroupId=@rOrgGroupId AND L1.AccountingYearId=@rAccountingYearId) as CashOpBalance, 
		L.Id, L.Title, L.LedgerTypeId,L.OpeningBalance, 
		LG.Title AS GName, LGM.Title AS MGName 
		
		FROM sAccounting.tLedgerMaster L INNER JOIN sAccounting.tLedgerGroupMaster LG on LG.Id=L.LedgerGroupId
		INNER JOIN sAccounting.tLedgerMainGroupMaster LGM ON LGM.Id = LG.LEDGERMAINGROUPID
		And LG.OrgGroupId= @rOrgGroupId AND L.AccountingYearId=@rAccountingYearId AND LG.AccountingYearId = @rAccountingYearId    
    END
		
	

	SELECT @lCount =  COUNT(Id) FROM #tTarij
	WHILE (@lCount > 0)
	BEGIN
		SELECT @lLedgerId=LedgerId,@lCreditBalance=CreditBalance,@lDebitBalance=DebitBalance,@lCashOpBalance=CashOpBalance,
		@lLedgerName=LedgerName,@lLedgerTypeId=LedgerTypeId,@lOpeningBalance=OpeningBalance,@lLedgerGroupName=LedgerGroup,
		@lLedgerMainGroupName=LedgerMainGroup	FROM #tTarij WHERE Id= @lCount
		if @rTarij=1 
		BEGIN
				SET @lCreditBalance = @lCreditBalance + @lLOpeningBalance
		END
		ELSE
		BEGIN
				SET @lCreditBalance = @lLOpeningBalance
		END
		
		SET @lCreditBalance = @lCreditBalance + (-1) * @lCreditBalance
		SET @lDebitBalance = @lDebitBalance + (-1) * @lDebitBalance
		SET @lCount = @lCount - 1
	END	
	
	Update #tTarij Set CreditBalance = -1 * CreditBalance Where CreditBalance < 0
	 
		
	IF @rOrderBy = 1 
	BEGIN
	  
	    
		
		SELECT @ReportOrgTitle  AS OrgTitle,
	@SmallAddress1 AS SmallAddress1,
	@SmallAddress2 AS SmallAddress2, @rBuilder1 AS Builder1,
	@rBuilder2 AS Builder2,([sAccounting].[fDecimalValueGet] (CreditBalance, @DecimalCount)) as CreditBalance, -- Added for mantis 32211 by Nilesh
	-- Added for mantis 32211 by Nilesh
				([sAccounting].[fDecimalValueGet] (DebitBalance, @DecimalCount)) as DebitBalance, * FROM #tTarij ORDER BY LEDGERMAINGROUP
	END
	
	ELSE
	BEGIN
		SELECT	@ReportOrgTitle  AS OrgTitle,
				@SmallAddress1 AS SmallAddress1,
				@SmallAddress2 AS SmallAddress2, 
				@rBuilder1 AS Builder1,
				@rBuilder2 AS Builder2,
				--change by dhruvik
				([sAccounting].[fDecimalValueGet] (CreditBalance, @DecimalCount)) as CreditBalance,
				([sAccounting].[fDecimalValueGet] (DebitBalance, @DecimalCount)) as DebitBalance,
				CashOpBalance, LedgerId,LedgerName,LedgerTypeId,OpeningBalance,LedgerGroup,LedgerMainGroup 
		FROM #tTarij ORDER BY 	LEDGERNAME
	END
END
GO
PRINT N'Altering Procedure [sAccounting].[pUpdateClosingBalance]...';


GO


ALTER PROCEDURE [sAccounting].[pUpdateClosingBalance]
	
	@rStartDate Date,
	@rEndDate Date,
	@rOrgGroupId int = 0,
	@rAccountingYearId [int],
	@rLedgerId [int],
	@rISProfitLoss [smallint]

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN

Declare @OpeningBalance decimal(25,5) -- Changed for mantis : 32211 by Nilesh
Declare @AccOpBalance decimal(25,5) = 0
Declare @ClosingBalance decimal(25,5) -- Changed for mantis : 32211 by Nilesh
Declare @TransactionBalance decimal(25,5) -- Changed for mantis : 32211 by Nilesh
Declare @LedgerId int 
Declare @lCount int
Declare @LedgerTypeId int
	
	
	CREATE TABLE #tempUpdateClosingBalance123
 		(	
 		    Id INT IDENTITY (1, 1),
 			LedgerId int,
 			Temp_Op_Balance decimal(25,5), -- Changed for mantis : 32211 by Nilesh
 			Closing_Balance decimal(25,5), -- Changed for mantis : 32211 by Nilesh
 			Trasaction_Balance decimal(25,5) not null -- Changed for mantis : 32211 by Nilesh
  		) 
	
	CREATE TABLE #tempLedgerMaster
 	    (
 	        Id INT IDENTITY (1, 1),
 			LedgerId int,
 			AccOpBalance decimal(25,5),
 			LedgerTypeId int				 
 		) 
 	INSERT INTO #tempLedgerMaster
	SELECT Id,OpeningBalance,LedgerTypeId FROM sAccounting.tLedgerMaster  
	WHERE AccountingYearId=@rAccountingYearId AND (ID=@rLedgerId OR @rLedgerId=0)
	ORDER BY Id Asc
	
	SELECT @lCount =  COUNT(Id) FROM #tempLedgerMaster
	WHILE (@lCount > 0)
	BEGIN
			SELECT @AccOpBalance =AccOpBalance,@LedgerTypeId= LedgerTypeId,
			@LedgerId =LedgerId FROM #tempLedgerMaster WHERE Id = @lCount	
	 -- Opening Balance Calulation
				IF @rISProfitLoss = 1 
				  BEGIN
					SELECT @OpeningBalance = ISNULL(SUM(AMOUNT),0) FROM sAccounting.tTransactionDetail TD
					INNER JOIN sAccounting.tTransaction T ON T.ID = TD.TransactionId
					WHERE T.OrgGroupId = @rOrgGroupId AND T.AccountingYearId = @rAccountingYearId
					AND T.TransactionDate < @rStartDate AND TD.LedgerId=@LedgerId AND
					(TD.LedgerId = @rLedgerId OR @rLedgerId = 0) AND T.IsProfitAndLoss <> 1
				  END
				ELSE
				  BEGIN
					SELECT @OpeningBalance = ISNULL(SUM(AMOUNT),0) FROM sAccounting.tTransactionDetail TD
					INNER JOIN sAccounting.tTransaction T ON T.ID = TD.TransactionId
					WHERE T.OrgGroupId = @rOrgGroupId AND T.AccountingYearId = @rAccountingYearId
					AND T.TransactionDate < @rStartDate AND TD.LedgerId=@LedgerId AND
				    (TD.LedgerId = @rLedgerId OR @rLedgerId = 0)
				  END				
   -- Transaction Balance
   				IF @rISProfitLoss = 1 
				  BEGIN
					SELECT @TransactionBalance = ISNULL(SUM(AMOUNT),0) FROM sAccounting.tTransactionDetail TD
					INNER JOIN sAccounting.tTransaction T ON T.ID = TD.TransactionId
					WHERE T.OrgGroupId = @rOrgGroupId AND T.AccountingYearId = @rAccountingYearId
					AND T.TransactionDate >= @rStartDate  AND T.TransactionDate <= @rEndDate 
					AND TD.LedgerId=@LedgerId AND
					(TD.LedgerId = @rLedgerId OR @rLedgerId = 0) AND T.IsProfitAndLoss <> 1
				  END
				ELSE
				  BEGIN
					SELECT @TransactionBalance = ISNULL(SUM(AMOUNT),0) FROM sAccounting.tTransactionDetail TD
					INNER JOIN sAccounting.tTransaction T ON T.ID = TD.TransactionId
					WHERE T.OrgGroupId = @rOrgGroupId AND T.AccountingYearId = @rAccountingYearId
					AND T.TransactionDate >= @rStartDate  AND T.TransactionDate <= @rEndDate 
					AND TD.LedgerId=@LedgerId AND (TD.LedgerId = @rLedgerId OR @rLedgerId = 0)
				  END				
	--
				IF @LedgerTypeId = 1 
				BEGIN
					SET @TransactionBalance = -1 * @TransactionBalance
					SET @OpeningBalance = -1 * @OpeningBalance
				END
				ELSE
				BEGIN
					SET @TransactionBalance = @TransactionBalance
					SET @OpeningBalance = @OpeningBalance
				END
								    
				    SET @OpeningBalance = @OpeningBalance + @AccOpBalance				
					SET @ClosingBalance = @OpeningBalance + @TransactionBalance				
				    --Select @OpeningBalance AS OPBal ,@ClosingBalance AS CloseIng				
				
				INSERT INTO #tempUpdateClosingBalance123 (LedgerId ,Temp_Op_Balance ,Closing_Balance,Trasaction_Balance)
				VALUES (@LedgerId,@OpeningBalance,@ClosingBalance,ISNULL(@TransactionBalance,0)) -- Changed for mantis : 32211 by Nilesh

				SET @lCount = @lCount - 1
	END	
		SELECT LedgerId,Temp_Op_Balance,Closing_Balance,Trasaction_Balance FROM #tempUpdateClosingBalance123 ORDER BY LedgerId
		TRUNCATE TABLE #tempUpdateClosingBalance123
END
GO
PRINT N'Altering Procedure [sAccounting].[pVoucherListGet]...';


GO


 
ALTER PROCEDURE [sAccounting].[pVoucherListGet]

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

BEGIN 

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

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

	 SELECT @DecimalCount = CASE WHEN CS.Id IS NOT NULL THEN ISNULL(CS.ItemValue,'') ELSE ISNULL(CM.ItemValue,'') END
						  FROM sConfig.tConfigurationMaster CM
						  LEFT JOIN sConfig.tConfigurationSetup CS ON CM.Id = CS.ConfigurationId
						  AND SourceTypeId = 2010 AND SourceId = @lOrgGroupId WHERE CM.Id = 548
	 
  SELECT   @rBuilder1 AS Builder1
		  ,@rBuilder2 AS Builder2
		  ,T.Id
		  ,VTM.Title AS VoucherType
		  ,T.VoucherNumber AS VoucherNo
		  ,T.TransactionDate AS VoucherDate
		  ,LM.Title AS Ledger
		  --,CASE WHEN ISNULL(TD.Amount,0) < 0 THEN ISNULL(TD.Amount,0) * -1 ELSE 0 END AS Credit --Commented for mantis : 32211 by Nilesh
		  ,([sAccounting].[fDecimalValueGet] ((CASE WHEN ISNULL(TD.Amount,0) < 0 THEN ISNULL(TD.Amount,0) * -1 
			ELSE 0 END), @DecimalCount)) Credit --Commented for mantis : 32211 by Nilesh
		  --,CASE WHEN ISNULL(TD.Amount,0) > 0 THEN ISNULL(TD.Amount,0) ELSE 0 END AS Debit --Commented for mantis : 32211 by Nilesh
		  ,([sAccounting].[fDecimalValueGet] ((CASE WHEN ISNULL(TD.Amount,0) > 0 THEN ISNULL(TD.Amount,0) 
			ELSE 0 END),@DecimalCount)) Debit --Commented for mantis : 32211 by Nilesh
		  ,T.Narration AS Narration
		  ,AM.ReportOrgTitle As OrgTitle
		  ,AM.SmallAddress1 AS SmallAddress1
		  ,AM.SmallAddress2 AS SmallAddress2,
		  T.TransactionApproveId	  	      
  FROM 
          sAccounting.tTransaction T
          INNER JOIN sAccounting.tTransactionDetail TD ON T.Id=TD.TransactionId
          INNER JOIN sAccounting.tVoucherTypeMaster VTM ON VTM.Id = T.VoucherTypeId
          INNER JOIN sAccounting.tLedgerMaster LM ON LM.Id=TD.LedgerId 
          INNER JOIN sAccounting.tAccountMaster AM ON AM.Id=T.AccountId            
  WHERE 
				(T.VoucherTypeId=@rVoucherTypeId OR @rVoucherTypeId = 0) 
			AND ((T.Narration like @rNarration) OR (ISNULL(@rNarration,'') = '')) 		
			AND (T.TransactionDate >= @rTransactionDate OR ISNULL(@rTransactionDate,'') = '') 
			And (T.TransactionDate <= @rTransactionDateTo OR ISNULL(@rTransactionDateTo,'') = '')
			AND (T.VoucherNumber >= @rVoucherNumber OR @rVoucherNumber=0) 
			AND (T.VoucherNumber <=@rVoucherNumberTo OR @rVoucherNumberTo=0)
			AND (TD.LedgerId = @rLedgerId OR @rLedgerId=0)
			AND (TD.Amount = @rAmount OR ISNULL(@rAmount,0) = 0)
			AND LM.AccountingYearId = @rAccountingYearId
			AND T.AccountingYearId = @rAccountingYearId
			AND ((@rIsApproved=1 AND  ISNULL(T.TransactionApproveId,0) !=0) OR (@rIsApproved = 0) )
			
            Order By T.TransactionDate,T.VoucherNumber, LM.Id
END
GO
PRINT N'Altering Procedure [sFee].[pAccountMappingGet]...';


GO

ALTER PROCEDURE [sFee].[pAccountMappingGet]
				
		   @rBuilder1 nvarchar(max)='',
		   @rBuilder2 nvarchar(max)='', 
		   @rClassId int,
           @rAdmissionCategoryId int,
		   @rBatchId int,
		   @rOrgGroupId int,
		   @rReceiptBookId int,
		   @rPayTypeId int = 0,
		   @rFeeId int = 0,
		   @rFeeHeadId int = 0
           
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
BEGIN 
	SELECT  
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			ISNULL(FS.Id,0)AS FeeSetupId,
			ISNULL(AM.FeeSetupId,0)AS AMFeeSetupId,
			ISNULL(FS.ClassId,0)AS ClassId,
			ISNULL(CM.Title,'') AS ClassName,
			ISNULL(FS.AdmissionCategoryId,0) AS AdmissionCategoryId,
			ISNULL(FS.BatchId,0)AS BatchId,
			ISNULL(FM.Id,0)AS FeeId,
			ISNULL(FM.Title,'') AS FeeTitle,
			ISNULL(FHM.Id,0) AS FeeHeadId,
			ISNULL(FHM.Title,'') AS FeeHeadName,
			ISNULL(FS.ReceiptBookId,0) AS ReceiptBookId,
			ISNULL(RBM.Title,'') AS ReceiptBookTitle,
			ISNULL(AYM.AccountId,0) AS AccountId,
			ISNULL(AM.CreditLedgerId,0) AS CreditLedgerId,
			ISNULL(AM.DebitLedgerId,0) AS DebitLedgerId,
			ISNULL(AM.AccountingYearId,0) AS AccountingYearId,
			ISNULL(AM.PayTypeId,0) AS AMPayTypeId,
			ISNULL(PTM.Id,0) AS PayTypeId,
			ISNULL(PTM.Title,'') AS PayTypeName
  FROM 
			sFee.tFeeMaster FM
		INNER JOIN sFee.tFeeSetup FS ON FM.Id=FS.FeeId 
		AND (FS.ClassId=@rClassId) AND (FS.AdmissionCategoryId=@rAdmissionCategoryId) AND (FS.BatchId=@rBatchId)
		INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FM.FeeHeadId 
		INNER JOIN sFee.tReceiptBookMaster RBM ON RBM.Id=FS.ReceiptBookId AND (RBM.Id = @rReceiptBookId OR @rReceiptBookId=0)
		INNER JOIN sSetup.tClassMaster CM ON CM.Id=FS.ClassId		
		CROSS JOIN (SELECT PTM.Id,PTM.Title FROM sFinanceCommon.tPayTypeMaster PTM WHERE (PTM.Id = @rPayTypeId OR @rPayTypeId = 0)) PTM
		INNER JOIN sFee.tApplicablePayType APT ON APT.PayTypeId=PTM.Id -- Mentis Id : 0033089 by Vishruti
		LEFT JOIN sFee.tAccountMapping AM ON AM.FeeSetupId=FS.Id AND AM.PayTypeId=PTM.Id
		LEFT JOIN sAccounting.tLedgerMaster CLM ON (CLM.Id=AM.CreditLedgerId)  AND CLM.AccountingYearId = AM.AccountingYearId
		LEFT JOIN sAccounting.tLedgerMaster DLM ON (DLM.Id=AM.DebitLedgerId) AND DLM.AccountingYearId = AM.AccountingYearId
		LEFT JOIN sAccounting.tAccountingYearMaster AYM ON AYM.Id=CLM.AccountingYearId AND AYM.Id=DLM.AccountingYearId
WHERE 
		FM.OrgGroupId=@rOrgGroupId	
		AND (FM.Id = @rFeeId OR @rFeeId=0)	
		AND (FHM.Id = @rFeeHeadId OR @rFeeHeadId = 0)
ORDER BY FM.OrderIndex,PTM.Id

END
GO
PRINT N'Altering Procedure [sAccounting].[pTransactionApproveDetailAdd]...';


GO

ALTER PROCEDURE [sAccounting].[pTransactionApproveDetailAdd]
	 
	        @rId bigint
           ,@rTransactionId bigint
           ,@rNumber bigint
		   ,@rTransactionTypeId int
		   ,@rLedgerId bigint
		   ,@rAmount decimal(20,5) --Changed for mantis : 32211 by Nilesh
		   ,@rOrgId int
		  	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	 BEGIN TRANSACTION	
	 DECLARE @lNextNumber BIGINT 

IF(@rId = 0)	
BEGIN
EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sAccounting.tTransactionApproveDetail', 0, 1, 1,@outNextNumber = @lNextNumber output
	INSERT INTO sAccounting.tTransactionApproveDetail
			   (
			    [Id]
			   ,[TransactionId] 
			   ,[Number] 
			   ,[TransactionTypeId]
			   ,[LedgerId]
			   ,[Amount]
			   )
		 VALUES
			   (
				@lNextNumber
			   ,@rTransactionId
			   ,@rNumber
			   ,@rTransactionTypeId
			   ,@rLedgerId
			   ,@rAmount
			   )
		    SELECT @lNextNumber AS Result
	
		
	END	 
	 ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE  sAccounting.tTransactionApproveDetail
	    SET
			 
	          Number=@rNumber
	         ,TransactionTypeId=@rTransactionTypeId
	         ,LedgerId=@rLedgerId
			 ,Amount=@rAmount
	      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 [sAccounting].[pTransactionDetailAdd]...';


GO


ALTER PROCEDURE [sAccounting].[pTransactionDetailAdd]
	 
	        @rId bigint
           ,@rTransactionId bigint
           ,@rNumber bigint
		   ,@rTransactionTypeId int
		   ,@rLedgerId bigint
		   ,@rAmount decimal(20,5) --Changed for mantis : 32211 by Nilesh
		   ,@rOrgId int
		  	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	 BEGIN TRANSACTION	
	 DECLARE @lNextNumber BIGINT 

IF(@rId = 0)	
BEGIN
EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sAccounting.tTransactionDetail', 0, 1, 1,@outNextNumber = @lNextNumber output
	--EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sAccounting.tTransactionDetail', 0, 1, 1,@outNextNumber = @lNextNumber output
	INSERT INTO [sAccounting].[tTransactionDetail]
			   (
			    [Id]
			   ,[TransactionId] 
			   ,[Number] 
			   ,[TransactionTypeId]
			   ,[LedgerId]
			   ,[Amount]
			   )
		 VALUES
			   (
				@lNextNumber
			   ,@rTransactionId
			   ,@rNumber
			   ,@rTransactionTypeId
			   ,@rLedgerId
			   ,@rAmount
			   )
		    SELECT @lNextNumber AS Result
	
		--COMMIT TRANSACTION         
	END	 
	 ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE  [sAccounting].[tTransactionDetail]
	    SET
			  --Number=@rNumber
	         --,Code=@rCode
	          Number=@rNumber
	         ,TransactionTypeId=@rTransactionTypeId
	         ,LedgerId=@rLedgerId
			 ,Amount=@rAmount
	      WHERE Id = @rId 	   
	      SELECT @lNextNumber AS Result
	
		--COMMIT TRANSACTION
	 END  
		
	--END
--END	
COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Altering Procedure [sAlert].[pSubjectwiseAttendanceGet]...';


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

	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.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
	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)='' 
	
	 --,@rcolumn_visible bit
	

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

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

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

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


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

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

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

		)
	 --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
	)
	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
				
FROM 
	sAssessment.tResultDetail RD
	INNER JOIN sAssessment.tResult R ON R.Id = RD.ResultId
	INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId AND R.ExamId = ED.ExamId
	INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId		
	INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
	INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=CS.SubjectId	
	LEFT JOIN sSetup.tSubjectGroupMaster SG ON SG.Id = Sm.SubjectGroupId				 
	INNER JOIN sStudent.tAcademic A ON A.Id=R.AcademicId
	INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=A.OrgId
	LEFT JOIN sSetup.tOrgImages OI ON OI.Orgid = OM.Id
	INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId
	INNER JOIN sStudent.tStudentMaster StuM ON StuM.Id=A.StudentId
	INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId
	INNER JOIN sSetup.tStreamMaster StM ON CM.StreamId = Stm.Id
	INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId
	LEFT JOIN sHrm.tEmployeeImages EI ON EI.EmployeeId = Dm.InchargeEmployeeId
	LEFT JOIN sHrm.tEmployeeMaster EMP ON EMP.Id = DM.InchargeEmployeeId AND  ISNULL(EMP.IsOtherUser,0) = 0
	INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id = EM.EXAMSUBGROUPID
	LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId=StuM.Id
	Left JOIN sActivity.tHouseMaster HM ON SO.HouseId = HM.Id
	LEFT JOIN sStudent.tAcademicDetail AD ON AD.AcademicId=A.Id
	LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId=StuM.Id
	LEFT JOIN sAssessment.tStudentRemark SR ON R.AcademicId = SR.AcademicId AND R.ExamId = SR.ExamId
	LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId = StuM.Id
	LEFT JOIN sAssessment.tOptionalSubject OS ON OS.AcademicId = R.AcademicId AND OS.ClassSubjectId = ED.ClassSubjectId  AND ED.ExamId = R.ExamId
	LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId=A.StudentId
	LEFT JOIN 	sCommon.tBloodGroupMaster BGM ON BGM.Id=So.BloodGroupId
	LEFT JOIN sAssessment.tGradeSetDetail GS ON GS.GradeSetId=ED.GradeSetId AND ED.GradeSetId = @GradeSetId and RD.SubjectGrade = GS.GradeCode
	LEFT JOIN sAssessment.tResultAnalysisDivisionDetail RAD ON RAD.ClassSubjectId = CS.Id AND RAD.DivisionId = A.DivisionId AND RAD.ExamId = Em.Id
	
	LEFT JOIN sHostel.tAssignRoom AR ON  AR.SourceId=StuM.Id AND AR.SourceTypeId=2003 AND ((BM.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  AND ((AR.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0) AND (BM.OrgGroupBatchId 


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

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

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

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

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


GO

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

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

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


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

			ISNULL(U.DisplayTitle,'') AS UserName ,
		
		    ISNULL(EM.FirstName,'') +' '+ISNULL(EM.LastName,'') AS PrincipalName,
			ISNULL(CM.ClassNameInWord,'') AS ClassNameInWord,
			CM2.Title AS LeftStandard,
			CAST((CASE WHEN SI.QRCode IS NULL THEN 0 ELSE 1 END) AS bit) AS IsDisplayQRCode,			--add for 27638 mantis
			ISNULL(SI.QRCode,'') AS QRCode,							--add for 27638 mantis
			SA.LeftDate AS LeftDate,	
			SM.PENNumber -- add for Mentis : 0033432
	FROM 
			sCertificate.tBonafide B
			
			INNER JOIN sStudent.tAcademic A ON B.AcademicId=A.Id
			LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId=A.StudentId
			INNER JOIN sStudent.tStudentMaster SM ON SM.Id=A.StudentId
			LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId=A.StudentId
			INNER JOIN sSetup.tDivisionMaster DM ON A.DivisionId = DM.Id  
			INNER JOIN sSetup.tClassMaster CM ON CM.Id= DM.ClassId
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id=A.BatchId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=A.OrgId
			left JOIN sSetup.tOrgImages OI ON OI.OrgId = OM.Id
			INNER JOIN sSetup.tAffiliationMaster AM ON OM.AffiliationId = AM.Id
			INNER JOIN sSetup.tAffiliationTypeMaster ATM ON AM.AffiliationTypeId = ATM.Id
			LEFT JOIN sCommon.tReligionMaster RM ON SO.ReligionId=RM.Id
			LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId = SM.Id
			INNER JOIN sStudent.tStudentAdmission SA ON SA.StudentId = SM.Id
			LEFT JOIN sSetup.tClassMaster CM1 ON CM1.Id = SA.AdmissionStandardId
			INNER JOIN sSetup.tDepartmentMaster DP ON CM.DepartmentId = DP.Id
			LEFT JOIN sCommon.tCastCategoryMaster CT ON CT.Id = SO.CastCategoryId
			LEFT JOIN sStudent.tStudentCommunication C ON C.StudentId = A.StudentId
			LEFT JOIN sCommon.tCountryMaster CTM ON CTM.Id=SO.NationalityId
			LEFT JOIN SHostel.tAssignRoom Ar On Ar.SourceId=A.StudentId AND Ar.OrgGroupBatchId=@rOrgGroupBatchId 
			LEFT JOIN sCommon.tReportRemarkGroupOrg RRG ON RRG.OrgId = OM.Id AND ReportRemarkGroupId=6
			LEFT JOIN sHrm.tEmployeeImages EI ON EI.EmployeeId = DM.InchargeEmployeeId 
			LEFT JOIN sSecurity.tUser U	ON U.Id=B.CreatedUserId

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

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

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


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

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


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

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


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

BEGIN 
DECLARE @lIsOnPrePrinted bit = 0,@lIsDisplayReligion bit=0,@lConfigValue nvarchar(50),@lIsDisplayImageHeader bit = 0,@lOrgId smallint
Declare @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 @lConfigValue = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 218 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

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

	SELECT  
		T.Number,
		T.TCDate AS TransferDate,
		T.ExamName,
		T.ExamSeatNo,
		T.ExamYear,
		T.ExamResult,
		T.PromotedClass,
		T.TransferConduct,
		T.OptionalSubject,
		T.Remark,
		A.Name,
		A.OrganiZationName,
	    SO.GenderId,
	    SO.DateOfBirth,
	    A.ClassName AS ClassName,
		A.DivisionName AS DivisionName,
		A.Code As StudentCode,
		SO.AdhaarNumber,
		T.SemesterDuration,
		A.StudentId,
		@lIsOnPrePrinted AS IsOnPrePrinted,
		@lIsDisplayImageHeader AS IsDisplayImageHeader,
		OM.OrgLogo,
		OM.ReportOrgTitle AS OrgTitle,
		OM.SmallAddress1,
		OM.SmallAddress2,
		OM.RegistrationDetail,
		--OI.CertificateHeaderA4,
		@lIDConfigValue AS ItemValue,
		OI.CertificateHeaderA4Portrait AS CertificateHeaderA4,
		ISNULL(SF.FatherName,'') As FatherName,			--add for 27638 mantis start
		ISNULL(SF.MotherName,'') As MotherName,
		A.StatusId,
		SI.StudentPhoto,
		@lIsShowPhoto AS IsShowPhoto,
		CAST((CASE WHEN SI.QRCode IS NULL THEN 0 ELSE 1 END) AS bit) AS IsDisplayQRCode,
		ISNULL(SI.QRCode,'') AS QRCode,
		SC.PresentStreetOne,
		SC.PresentStreetTwo,
		SC.PresentStreetThree,
		SC.PresentCountry,
		SC.PresentState,
		SC.PresentCity,
		SC.PresentZipCode,
		SC.PresentContactNo,
		SC.PermanentStreetOne,
		SC.PermanentStreetTwo,
		SC.PermanentStreetThree,
		SC.PermanentCountry,
		SC.PermanentState,
		SC.PermanentCity,
		SC.PermanentZipCode,
		SC.PermanentContactNo,		--add for 27638 mantis end
		SO.UIDNumber  --add for 0032936 mantis end
		
	From sCertificate.tTransfer T 
	INNER JOIN sStudent.vStudentAcademic A On A.AcademicId=T.AcademicId
	LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId=A.StudentId  
	INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=A.OrgId 
	LEFT JOIN sSetup.tOrgImages OI ON OI.OrgId = OM.Id
	LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId=A.StudentId		--add for 27638 mantis
	LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId = A.StudentId			--add for 27638 mantis
	LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId=A.StudentId		--add for 27638 mantis
	WHERE 
		T.OrgId=@rOrgId
		AND	A.BatchId = @rBatchId 
		AND ((A.Code = @rCode) OR (ISNULL(@rCode,'') = ''))
		AND ((A.FirstName = @rName) OR (ISNULL(@rName,'') = ''))
		AND ((T.TCDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
		AND ((T.TCDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
		AND ((A.ClassId=@rClassId) OR(@rClassId=0))
		AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		AND ((T.Number=@rNumber) OR (@rNumber=''))
		AND ((T.Number >= @rFromNo) OR (@rFromNo=''))
		AND ((T.Number <= @rToNo) OR (@rToNo=''))
	
END
GO


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


GO
ALTER PROCEDURE [sFee].[pFeeSetupRemove] 
	@rId INT
	,@rClassId INT
	,@rAdmissionCategoryId INT
	,@rBatchId INT
	,@rCheck BIT
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	IF (@rCheck = 1)
	BEGIN
		IF EXISTS (
				SELECT FeeSetupId
				FROM sFee.tFeeAllocation
				WHERE FeeSetupId = @rId
				)
		BEGIN
			SELECT - 50 AS Result

			RETURN
		END
		ELSE IF EXISTS (
				SELECT FeeSetupId
				FROM sFee.tReceiptDetail
				WHERE FeeSetupId = @rId
				)
		BEGIN
			SELECT - 51 AS Result

			RETURN
		END
		ELSE IF EXISTS (
				SELECT FeeSetupId
				FROM sFee.tFeeOptional
				WHERE FeeSetupId = @rId
				)
		BEGIN
			SELECT - 52 AS Result

			RETURN
		END
		ELSE IF EXISTS (
				SELECT FeeSetupId
				FROM sFee.tOnlineFeeDetail
				WHERE FeeSetupId = @rId
				)
		BEGIN
			SELECT - 53 AS Result

			RETURN
		END
		ELSE IF EXISTS (
				--SELECT 1
				--FROM [sFee].[tPostDatePayment]
				--WHERE ReceiptBookId = (SELECT ReceiptBookId FROM sFee.tFeeSetup WHERE Id = @rId)
				SELECT 1 FROM sFee.tPostDatePayment PDP 
				INNER JOIN sStudent.tAcademic A ON A.Id = PDP.SourceId AND PDP.SourceTypeId = 2001 
				WHERE A.ClassId = (SELECT ClassId FROM sFee.tFeeSetup WHERE Id = @rId) AND ReceiptBookId=(SELECT ReceiptBookId FROM sFee.tFeeSetup WHERE Id = @rId)
			)
		BEGIN
			SELECT - 54 AS Result

			RETURN
		END

		--else If Exists(select FeeSetupId from sFee.tFeeAllocationStudent where FeeSetupId=@rId)
		--	    BEGIN
		--			select -50 as Result
		--			RETURN
		--		END 
		SELECT 0 AS Result
	END
	ELSE
	BEGIN
		BEGIN TRY
			BEGIN TRANSACTION

			ALTER TABLE sfee.tReceiptDetail
				WITH CHECK CHECK CONSTRAINT FK_sFee_tReceiptDetail_FeeSetupId

			ALTER TABLE sFee.tFeeOptional
				WITH CHECK CHECK CONSTRAINT FK_sFee_tFeeOptional_tFeeSetupId

			ALTER TABLE sFee.tFeeAllocation
				WITH CHECK CHECK CONSTRAINT FK_sFee_tFeeAllocation_FeeSetupId

			DELETE
			FROM sFee.tFeeSetup
			WHERE ClassId = @rClassId
				AND AdmissionCategoryId = @rAdmissionCategoryId
				AND BatchId = @rBatchId
				AND (
					(Id = @rId)
					OR (@rId = 0)
					)

			COMMIT TRANSACTION
		END TRY

		BEGIN CATCH
			ROLLBACK TRANSACTION

			SELECT - 1 AS Result
		END CATCH

		SELECT 11 AS Result
	END
END
GO
PRINT N'Altering Procedure [sFee].[pReceiptAddValidate]...';


GO
ALTER PROCEDURE [sFee].[pReceiptAddValidate]
 
	@rAcademicId bigint,
	@rFeeSetupIds nvarchar(max) = '',
	@rReceiptDetailXml [nvarchar](max),
	@rPayTypeId tinyint = 0,
	@rPaymentTransactionId bigint = 0,
	@rIsCreated int OUTPUT
	    
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
BEGIN 

DECLARE @loDoc INT
EXEC sp_xml_preparedocument @loDoc OUTPUT, @rReceiptDetailXml
	 
create table #temptable (FeeId int,Id int,Amount decimal(12,2), AcademicId bigint ) 
INSERT INTO #temptable (FeeId,Id ,Amount , AcademicId)
SELECT 
				FS1.FeeId,
				FS1.Id,
				--ISNULL(FS1.IsOptional,0)AS IsOptional,
				--ISNULL(FS1.IsVariable,0)AS IsVariable,
				ISNULL(FS1.Amount,0) AS Amount,
				--ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
				--ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
				--FS1.BatchId,
				--ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
				SA1.Id AS AcademicId
				--FM.Title AS FeeName			 
			FROM sFee.tFeeSetup FS1
			INNER JOIN sStudent.tAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId 
			INNER JOIN sStudent.tStudentMaster SM ON SA1.StudentId = SM.Id
			AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId 
			INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
			INNER JOIN sFee.tFeeHeadMaster FHM ON FM.FeeHeadId = FHM.Id 
			WHERE 
			    (FS1.IsOptional=0)
			    AND SA1.Id = @rAcademicId				
				AND (ISNULL(FS1.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeSetupIds,','))OR @rFeeSetupIds='')
				
				UNION ALL
				
			SELECT 
				FS1.FeeId,
				FS1.Id,
				--ISNULL(FS1.IsOptional,0)AS IsOptional,
				--ISNULL(FS1.IsVariable,0)AS IsVariable,
				ISNULL(FS1.Amount,0)AS Amount,
				--ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
				--ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
				--FS1.BatchId,
				--ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
				SA1.Id AS AcademicId
				--FM.Title AS FeeName				
			FROM sFee.tFeeSetup FS1
				INNER JOIN sFee.tFeeOptional FO	ON FO.FeeSetupId=FS1.Id
				INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
	    					INNER JOIN sFee.tFeeHeadMaster FHM ON FM.FeeHeadId = FHM.Id 
				INNER JOIN sStudent.tAcademic SA1 ON SA1.Id=FO.SourceId 
				AND SA1.BatchId = FS1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId

		WHERE
				  (FS1.IsOptional=1)
				   AND SA1.Id = @rAcademicId	
				  	
				AND (ISNULL(FS1.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeSetupIds,','))OR @rFeeSetupIds='') 

create table #temptable1 (PaidAmount decimal(12,2),FeeSetupId int, SourceId bigint ) 
INSERT INTO #temptable1 (PaidAmount ,FeeSetupId , SourceId )
SELECT 
					ISNULL(SUM(RD.Amount),0) AS PaidAmount,RD.FeeSetupId ,R.SourceId
		    FROM
				sFee.tReceipt R 
				INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id AND R.SourceTypeId = 2001
				INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id
				INNER JOIN sStudent.tAcademic SA1 ON SA1.Id=R.SourceId AND SA1.AdmissionCategoryId = FS.AdmissionCategoryId	 
				
			WHERE	
			
			(R.SourceTypeId = 2001)
				 AND R.SourceId = @rAcademicId				
				AND (R.IsObsolete = 0) 
				AND (ISNULL(FS.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeSetupIds,','))OR @rFeeSetupIds='')
				GROUP BY FeeSetupId,R.SourceId	
	
	-- For Mantis 0032370 by Foram Start
	IF(@rAcademicId > 0)
	BEGIN
		IF NOT EXISTS(
		SELECT 1
		FROM #temptable FS
		INNER JOIN (
					SELECT FeeSetupId
						,Amount
					FROM OPENXML(@loDoc, '/Table/ReceiptDetail', 1) WITH (
							FeeSetupId INT
							,Amount DECIMAL(12, 2)
							)
					) AS RD ON RD.FeeSetupId = FS.Id)
		BEGIN 
			SELECT @rIsCreated = -1
		END
	END -- For Mantis 0032370 by Foram End
	ELSE
	BEGIN
	
	IF EXISTS(	
	SELECT 1
	FROM 
		sStudent.tAcademic SA
		INNER JOIN #temptable
		--(
		--SELECT 
		--		FS1.FeeId,
		--		FS1.Id,
		--		--ISNULL(FS1.IsOptional,0)AS IsOptional,
		--		--ISNULL(FS1.IsVariable,0)AS IsVariable,
		--		ISNULL(FS1.Amount,0) AS Amount,
		--		--ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
		--		--ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
		--		--FS1.BatchId,
		--		--ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
		--		SA1.Id AS AcademicId
		--		--FM.Title AS FeeName			 
		--	FROM sFee.tFeeSetup FS1
		--	INNER JOIN sStudent.tAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId 
		--	--INNER JOIN sStudent.tStudentMaster SM ON SA1.StudentId = SM.Id
		--	AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId 
		--	--INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
		--	--INNER JOIN sFee.tFeeHeadMaster FHM ON FM.FeeHeadId = FHM.Id 
		--	WHERE 
		--	    (FS1.IsOptional=0)
		--	    AND SA1.Id = @rAcademicId				
		--		AND (ISNULL(FS1.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeSetupIds,','))OR @rFeeSetupIds='')
			
		--		UNION ALL
			
		--	SELECT 
		--		FS1.FeeId,
		--		FS1.Id,
		--		--ISNULL(FS1.IsOptional,0)AS IsOptional,
		--		--ISNULL(FS1.IsVariable,0)AS IsVariable,
		--		ISNULL(FS1.Amount,0)AS Amount,
		--		--ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
		--		--ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
		--		--FS1.BatchId,
		--		--ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
		--		SA1.Id AS AcademicId
		--		--FM.Title AS FeeName				
		--	FROM sFee.tFeeSetup FS1
		--		INNER JOIN sFee.tFeeOptional FO	ON FO.FeeSetupId=FS1.Id
		--		--INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
		--   					--INNER JOIN sFee.tFeeHeadMaster FHM ON FM.FeeHeadId = FHM.Id 
		--		INNER JOIN sStudent.tAcademic SA1 ON SA1.Id=FO.SourceId 
		--		AND SA1.BatchId = FS1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId

		--WHERE
		--		  (FS1.IsOptional=1)
		--		   AND SA1.Id = @rAcademicId	
			  	
		--		AND (ISNULL(FS1.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeSetupIds,','))OR @rFeeSetupIds='') 
		--)
		 FS ON FS.AcademicId=SA.Id
		LEFT JOIN sFee.tFeeAllocation FA ON FA.FeeSetupId=FS.Id AND FA.SourceId=SA.Id
		LEFT JOIN #temptable1
		--(
		--	SELECT 
		--			ISNULL(SUM(RD.Amount),0) AS PaidAmount,RD.FeeSetupId ,R.SourceId
		--    FROM
		--		sFee.tReceipt R 
		--		INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id AND R.SourceTypeId = 2001
		--		INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id
		--		INNER JOIN sStudent.tAcademic SA1 ON SA1.Id=R.SourceId AND SA1.AdmissionCategoryId = FS.AdmissionCategoryId	 
			
		--	WHERE	
		
		--	(R.SourceTypeId = 2001)
		--		 AND R.SourceId = @rAcademicId				
		--		AND (R.IsObsolete = 0) 
		--		AND (ISNULL(FS.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeSetupIds,','))OR @rFeeSetupIds='')
		--		GROUP BY FeeSetupId,R.SourceId	
		--)
		R ON R.FeeSetupId = FS.Id AND SA.Id = R.SourceId			
		LEFT JOIN
		(
			SELECT 	    
			FeeSetupId,
			Amount
			FROM OPENXML (@loDoc, '/Table/ReceiptDetail', 1)
			WITH ( 
					FeeSetupId int,
					Amount decimal(12,2)
				  ) 
		 ) AS RD ON RD.FeeSetupId = FS.Id			
		 WHERE 
		 SA.Id =   @rAcademicId         
		 AND (ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00) -ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00) - RD.Amount < 0)			
	)
	BEGIN
		SELECT @rIsCreated = 1
	END 
	ELSE
	BEGIN
		--Start for mantis 0031290 By Foram
		IF(@rPayTypeId = 8)
		BEGIN
			IF EXISTS (SELECT 1
				FROM
					sFee.tReceipt R 
					INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id AND R.SourceTypeId = 2001
					INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id
					INNER JOIN sStudent.tAcademic SA1 ON SA1.Id=R.SourceId AND SA1.AdmissionCategoryId = FS.AdmissionCategoryId	 
				WHERE	
					(R.SourceTypeId = 2001)
					AND R.SourceId = @rAcademicId				
					AND (R.IsObsolete = 0) 
					AND (ISNULL(FS.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeSetupIds,','))OR @rFeeSetupIds='')
					AND R.PaymentTransactionId = @rPaymentTransactionId
					AND R.PayTypeId = 8
				)
			BEGIN
				SELECT @rIsCreated = 1
			END
			ELSE
			BEGIN
				SELECT @rIsCreated = 0
			END
		END
		--end for mantis 0031290 By Foram
		ELSE
		BEGIN
			SELECT @rIsCreated = 0
		END
 END 
 
	END
 	EXEC sp_xml_removedocument @loDoc
END
GO
PRINT N'Altering Procedure [sFee].[pReceiptUpdate]...';


GO
ALTER PROCEDURE [sFee].[pReceiptUpdate]
	
		   @rId bigint,
		   @rIsChequeCleared bit,
		   @rChequeClearDate date

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
BEGIN TRY
BEGIN TRANSACTION	
	BEGIN
		
		IF(@rIsChequeCleared = 1)
		BEGIN
			-- Mantis - 0032950 By Foram
			DECLARE @lConfigValue nvarchar(50)='',@lOrgGroupBatchId int = 0
			SELECT @lOrgGroupBatchId = OrgGroupBatchId FROM sFee.tReceipt WHERE Id = @rId
			SELECT @lConfigValue = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 552 AND SourceTypeId = 2010 AND SourceId = LEFT(@lOrgGroupBatchId,4)
			
			IF(@lConfigValue = 'True')
			BEGIN
				UPDATE sFee.tReceipt SET
				IsChequeCleared=@rIsChequeCleared,
				ChequeClearDate=@rChequeClearDate,
				ReceiptDate=@rChequeClearDate
				WHERE Id=@rId
			END
			-- Mantis - 0032950	By Foram 
			ELSE
			BEGIN
				UPDATE sFee.tReceipt SET
				IsChequeCleared=@rIsChequeCleared,
				ChequeClearDate=@rChequeClearDate
				WHERE Id=@rId
			END
		END
		ELSE
		BEGIN
			UPDATE sFee.tReceipt SET
			IsChequeCleared=@rIsChequeCleared,
		    ChequeClearDate=NULL
			WHERE Id=@rId
		END
		
		SELECT 1 AS RESULT
	END 
		COMMIT TRANSACTION
	END TRY
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
END
GO
PRINT N'Altering Procedure [sFee].[pRptChargeReceiptDetailsGet]...';


GO


ALTER PROCEDURE [sFee].[pRptChargeReceiptDetailsGet]
	 
		@rReceiptId bigint
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	
BEGIN
DECLARE @lOrgGroupId int = 0
DECLARE @lCurrencyCode nvarchar(20) = ''
Declare @lIDConfigValue nvarchar(50)=''

 SELECT @lOrgGroupId = OrgGroupId   FROM sFee.tChargeReceipt R 
 INNER JOIN sSetup.tOrgGroupBatchMaster OB ON R.OrgGroupBatchId = OB.Id 
 WHERE R.Id = @rReceiptId
SELECT  @lCurrencyCode = [sFinanceCommon].[fDefaultCurrencyCodeGet](@lOrgGroupId)   
SELECT @lIDConfigValue =ItemValue From sConfig.tConfigurationSetup
WHERE ConfigurationId = 236 AND SourceId = @lOrgGroupId	 
/*******Changed for mantis : 32211 By Nilesh********/
--Declare @DecimalCount INT
--SELECT @DecimalCount = CASE WHEN CS.Id IS NOT NULL THEN ISNULL(CS.ItemValue,'') ELSE ISNULL(CM.ItemValue,'') END
--						  FROM sConfig.tConfigurationMaster CM
--						  LEFT JOIN sConfig.tConfigurationSetup CS ON CM.Id = CS.ConfigurationId
--						  AND SourceTypeId = 2010 AND SourceId = @lOrgGroupId WHERE CM.Id = 548

	SELECT 
			CRD.ChargeReceiptId,
			CR.ReceiptNumber,
			CR.ReceiptDate,
			SA.AcademicId,
			--For Name
			(CASE WHEN CR.SourceTypeId = 2001 THEN SA.Name 
			WHEN CR.SourceTypeId = 3 THEN CR.GuestName
			WHEN CR.SourceTypeId = 95 THEN EM.FirstName + ' ' + EM.LastName
			END ) AS NAME, 
			--For Code
			(CASE WHEN CR.SourceTypeId = 2001 THEN SA.Code 
			WHEN CR.SourceTypeId = 95 THEN EM.Code
			END ) AS Code,
			--SA.Code,
			SA.RollNo,
			SA.ClassId,
			SA.DivisionId,
			SA.ClassName,
			SA.DivisionName,
			SA.ClassName+' - '+SA.DivisionName AS ClassDivision,
			CM.Id AS ChargeId,
			CM.Title AS ChargeName,
			CRD.Amount AS PaidAmount,
			--[sAccounting].[fDecimalValueGet] (ISNULL(CRD.Amount,0), @DecimalCount) AS PaidAmount, -- Added for mantis : 32211 by Nilesh
			PTM.Title AS PayType,
			ISNULL(CR.ChequeNo,'') AS ChequeNo,
			ISNULL(CR.BankName,'') AS BankName,
			ISNULL(RBM.Address1,'') AS Address1,
			ISNULL(RBM.Address2,'') AS Address2,
			ISNULL(RBM.FullTitle,'') AS FullTitle,
			CR.Remark,
			U.DisplayTitle AS UserName,
			OM.OrgLogo,
			CR.SourceTypeId,
			ISNULL(RBM.Title,'') AS ChargeReceiptBookName,
			ISNULL(CCM.Title,'') AS ChargeCategoryName,
			ISNULL(RBM.IsOnPrePrinted,0) AS IsOnPrePrinted,
			ISNULL(RBM.IsSupressLogo,0) AS IsSupressLogo,
			ISNULL(RBM.IsDisplaySchoolName,0) AS IsDisplaySchoolName,
			sFinanceCommon.fNumberToWordsWithDecimal (ISNULL(CR.ReceiptAmount,0.00),1,2,OM.OrgGroupId) AS ReceiptAmountInWords,
			OM.Title AS OrganizationName,
			CR.ReceiptAmount,
			CM.OrderIndex,
			BM.Title AS Batch,
			@lCurrencyCode AS CurrencyCode,
		    ISNULL(GroupTitle,'') AS GroupTitle,
		    RBM.Remark1,
		    RBM.Remark2,
		    CR.ChequeDate,
		   @lIDConfigValue AS  ItemValue,
		    CASE
				 WHEN RBM.IsOnPrePrinted=1       
				 THEN 2
				 ELSE  ISNULL(RBM.HeaderDisplayId,1)
				END AS HeaderDisplayId,
	        RBM.ReceiptBookHeader
		    
			
	FROM 
			sFee.tChargeMaster CM
			INNER JOIN sFee.tChargeReceiptDetail CRD
				ON CRD.ChargeId=CM.Id
			INNER JOIN sFee.tChargeReceipt CR
				ON CR.Id=CRD.ChargeReceiptId 	 
			INNER JOIN sFee.tChargeCategoryMaster CCM
				ON CCM.ChargeReceiptBookId=	CR.ChargeReceiptBookId AND CCM.Id=CM.ChargeCategoryId
			INNER JOIn sFinanceCommon.tPayTypeMaster PTM
				ON PTM.Id=CR.PayTypeId
			INNER JOIN sFee.tChargeReceiptBookMaster RBM 
				ON RBM.Id=CR.ChargeReceiptBookId
			INNER JOIN sSecurity.tUser U
				ON U.Id=CR.CreatedUserId
			LEFT JOIN sStudent.vStudentAcademic SA
				ON SA.AcademicId=CR.SourceId AND CR.SourceTypeId = 2001	
			LEFT JOIN sHrm.tEmployeeMaster EM
				ON EM.Id=CR.SourceId AND CR.SourceTypeId = 95	
			LEFT JOIN sSetup.tOrganizationMaster OM
				ON OM.Id=SA.OrgId
	       INNER JOIN sSetup.tBatchMaster BM ON BM.Id = CR.BatchId				
	WHERE 
			CRD.ChargeReceiptId=@rReceiptId AND  ISNULL(EM.IsOtherUser,0) = 0

ORDER BY CM.OrderIndex ASC

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


GO


ALTER PROCEDURE [sFee].[pRptDepositAdjustmentGet]
          
		   @rOrgId int,          
           @rDepositHeadId int,
           @rFromAmount decimal(12,2),
           @rToAmount decimal(12,2),
           @rFromAdjustmentDate date,
           @rToAdjustmentDate date,
           @rBatchId int,
           @rCode nvarchar(20),
           @rOrgGroupBatchId int=0,
           @rFeeDepositExpenseTypeId int
           
AS
SET NOCOUNT ON

BEGIN
DECLARE @lOrgGroupId int = 0
Declare @lIDConfigValue nvarchar(50)=''
	SELECT @lOrgGroupId=OrgGroupId FROM sSetup.tOrganizationMaster WHERE Id = @rOrgId
	SELECT @lIDConfigValue =ItemValue From sConfig.tConfigurationSetup WHERE ConfigurationId = 308 AND SourceId = @lOrgGroupId
	/**Added for mantis : 32211 by Nilesh**/
	
	 --SELECT @DecimalCount = CASE WHEN CS.Id IS NOT NULL THEN ISNULL(CS.ItemValue,'') ELSE ISNULL(CM.ItemValue,'') END
		--				  FROM sConfig.tConfigurationMaster CM
		--				  LEFT JOIN sConfig.tConfigurationSetup CS ON CM.Id = CS.ConfigurationId
		--				  AND SourceTypeId = 2010 AND SourceId = @lOrgGroupId WHERE CM.Id = 548
SELECT  
		DHM.Title AS DepositHeadName,
		DA.Id,
		DA.DepositHeadId,
	--	DA.StudentId AS StudentId,
		VSA.AcademicId AS AcademicId,
		DA.Amount,
		--([sAccounting].[fDecimalValueGet] (DA.Amount, @DecimalCount)) ,
		DA.AdjustmentDate,
		DA.Remark,
		DA.CreatedDateTime,
		vSA.Code,
        vSA.Name AS StudentName,        
        vSA.ClassName+' - '+vSA.DivisionName AS ClassDivisionName,
        OM.Id AS OrgId,
        OM.DisplayTitle AS OrganizationName,
		@lIDConfigValue AS ItemValue
  FROM 		
		sStudent.vStudentAcademic vSA
		INNER JOIN sFee.tDepositAdjustment DA ON DA.AcademicId = vSA.AcademicId
		INNER JOIN sFee.tDepositHeadMaster DHM ON DHM.Id = DA.DepositHeadId
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=vSA.OrgId
  WHERE  
		 
		 (vSA.OrgId=@rOrgId OR @rOrgId=0)
		AND (DA.DepositHeadId=@rDepositHeadId OR @rDepositHeadId=0)
		AND ((DA.Amount >= @rFromAmount) OR (@rFromAmount = 0))
		AND ((DA.Amount <= @rToAmount) OR (@rToAmount = 0))
		AND ((DA.AdjustmentDate >= @rFromAdjustmentDate) OR (ISNULL(@rFromAdjustmentDate,'') = ''))
		AND ((DA.AdjustmentDate <= @rToAdjustmentDate) OR (ISNULL(@rToAdjustmentDate,'') = ''))
		AND ((vSA.Code=@rCode) OR (ISNULL(@rCode,'')=''))
		AND vSA.OrgGRoupBatchId=@rOrgGroupBatchId
		AND (DA.FeeDepositExpenseTypeId=@rFeeDepositExpenseTypeId OR @rFeeDepositExpenseTypeId=0)
		AND (vSA.BatchId = @rBatchId OR @rBatchId='')
		Order By DA.CreatedDateTime
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

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

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


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

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

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

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

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

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

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

--END
GO
PRINT N'Altering Procedure [sHostel].[pUserControlFeePaidStudentSearchGet]...';


GO


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

BEGIN 	 
		BEGIN
			SET @rFirstName = sCommon.fSearchStringGet(@rFirstName)
			SET @rLastName = sCommon.fSearchStringGet(@rLastName)
		END
 IF(@rRollNo IS NULL)
	BEGIN
	SELECT 
			DISTINCT
			SA.AcademicId,
			SA.StudentId,
			SA.FirstName,
			SA.LastName,
			SA.MiddleName,
			SA.Name,
			SA.Code,
			SA.ClassId,
			SA.ClassName,
			SA.DivisionId,
			SA.DivisionName,
			SA.Number,
			SA.RollNo,
			SA.StatusId,
			SA.StatusName,
			SA.OrgId,
			--SA.Age,
			ISNULL(SA.AdmissionCategoryId,0) AS AdmissionCategoryId,
			SA.BatchId,
			SA.SUId,
			SA.FeesRemark -- Changed for Mantis - 32729 by Nilesh
  FROM 
          sStudent.vStudentAcademic SA 
          INNER JOIN sFee.tFeeAllocation FA ON FA.SourceId = SA.AcademicId
		  INNER JOIN sFee.tFeeSetup FS ON FS.Id = FA.FeeSetupId
		  INNER JOIN sFee.tFeeMaster FM ON FM.Id = FS.FeeId 
		  INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id = FM.FeeHeadId AND FHM.Number = 1002
       
  WHERE 
 
		((SA.ClassId=@rClassId)OR(@rClassId=0))
		AND((SA.DivisionId=@rDivisionId)OR(@rDivisionId=0))
		AND((SA.Code=@rCode) OR (ISNULL(@rCode,'') = '')) 
		AND((SA.FirstName like @rFirstName) OR (ISNULL(@rFirstName,'') = '')) 
		AND((SA.LastName like @rLastName) OR (ISNULL(@rLastName,'') = '')) 
		AND((SA.StatusId=@rStatusId)OR(@rStatusId=0))	
		AND(SA.OrgId=@rOrgId OR @rOrgId = 0)
		AND ( SA.OrgGroupBatchId = @rOrgGroupBatchId	or @rOrgGroupBatchId = 0)	
		AND(SA.BatchId=@rBatchId or @rBatchId = 0)
		--AND((SA.Number=@rNumber)OR(@rNumber=0))	
		AND((SA.SUId=@rSUId) OR (ISNULL(@rSUId,'') = ''))

ORDER BY SA.ClassId,SA.DivisionId,SA.RollNo
END
ELSE
BEGIN
	SELECT 
			DISTINCT
			SA.AcademicId,
			SA.StudentId,
			SA.FirstName,
			SA.LastName,
			SA.MiddleName,
			SA.Name,
			SA.Code,
			SA.ClassId,
			SA.ClassName,
			SA.DivisionId,
			SA.DivisionName,
			SA.Number,
			SA.RollNo,
			SA.StatusId,
			SA.StatusName,
			SA.OrgId,
			--SA.Age,
			ISNULL(SA.AdmissionCategoryId,0) AS AdmissionCategoryId,
			SA.FeesRemark -- Changed for Mantis - 32729 by Nilesh 
  FROM 
          sStudent.vStudentAcademic SA 
          INNER JOIN sFee.tFeeAllocation FA ON FA.SourceId = SA.AcademicId
		  INNER JOIN sFee.tFeeSetup FS ON FS.Id = FA.FeeSetupId
		  INNER JOIN sFee.tFeeMaster FM ON FM.Id = FS.FeeId 
		  INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id = FM.FeeHeadId AND FHM.Number = 1002
              
  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.Number=@rNumber)OR(@rNumber=0))
		AND((SA.SUId=@rSUId) OR (ISNULL(@rSUId,'') = '')) 	

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


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

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

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

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

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

	DROP TABLE #EmpAutoSearchTemp
END
GO
PRINT N'Altering Procedure [sLibrary].[pLibraryAttendanceGet]...';


GO


ALTER PROCEDURE [sLibrary].[pLibraryAttendanceGet]
          
           @rId bigint,
           @rLibraryId int,
           @rSourceTypeId smallint,
           @rName nvarchar(200),
           @rCode nvarchar(20),
           @rFromAttendanceDate date,
           @rToAttendanceDate date,
           @rOrgGroupBatchId int,
           @rOrgId int=0
           
AS
SET NOCOUNT ON
			SET @rName = sCommon.fSearchStringGet(@rName)
			SET @rCode = sCommon.fSearchStringGet(@rCode)
BEGIN
SELECT   
	   LA.Id AS LibraryAttendanceId,
	   LA.LibraryId,
	   
		(CASE WHEN LA.SourceTypeId = 95 THEN	'Employee'
			 WHEN LA.SourceTypeId = 2003 THEN	'Student'
			 ELSE 'Other' END) AS TypeName,

		(CASE WHEN LA.SourceTypeId = 95 THEN Emp.EmployeeName
			WHEN LA.SourceTypeId = 2003 THEN vSF.Name
			ELSE
			ISNULL(LA.GuestName,'') 
			END) AS Name,
			
		(CASE WHEN LA.SourceTypeId = 95 THEN Emp.DepartmentName
			WHEN LA.SourceTypeId = 2003 THEN DM.Title
			ELSE '' END) AS DepartmentName,		 	
		 
		(CASE WHEN LA.SourceTypeId = 95 THEN	Emp.Code
			 WHEN LA.SourceTypeId = 2003 THEN	vSF.Code
			 ELSE '' END) AS Code, 	
			
		(CASE WHEN LA.SourceTypeId = 95 THEN Emp.DepartmentName
			WHEN LA.SourceTypeId = 2003 THEN (vSF.ClassName + ' - '+ vSF.DivisionName)
			ELSE '' END) AS ClassDepartmentName,	
			 	 
	   LA.SourceId,
	   LA.SourceTypeId,
	   LA.GuestName,
	   LA.AttendanceDate,
	   LA.InTime,
	   LA.OutTime,
	   LA.Remark,
	   (CASE WHEN LA.OutTime = Convert(time,'00:00:00') THEN ''
		ELSE convert(varchar(5),DateDiff(SECOND, LA.InTime, LA.OutTime)/3600)+
		':'+convert(varchar(5),DateDiff(SECOND, LA.InTime, LA.OutTime)%3600/60)+
		':'+convert(varchar(5),(DateDiff(SECOND, LA.InTime, LA.OutTime)%60))
		END) AS TotalTime,
		ISNULL(OM.Id,0) AS OrgId,
		ISNULL(OM.DisplayTitle,'') AS OrgName
		--(CASE WHEN LA.SourceTypeId = 95 THEN ''
		--	WHEN LA.SourceTypeId = 2003 THEN vSF.SUId
		--	ELSE '' END) AS SUId		 
		
	   
  FROM  sLibrary.tLibraryAttendance LA
		LEFT JOIN sHrm.vExtEmployeeMaster Emp
			ON Emp.Id = LA.SourceId AND LA.SourceTypeId = 95 
				--AND(((Emp.Code like @rCode) OR (ISNULL(@rCode,'') = '')) AND @rSourceTypeId = 95  )
				--AND(((Emp.EmployeeName like @rName) OR (ISNULL(@rName,'') = '')) AND @rSourceTypeId = 95 )
				
		LEFT JOIN 
		sStudent.vStudentAcademic vSF ON vSF.StudentId = LA.SourceId AND LA.SourceTypeId = 2003
		and vsf.statusid = 1  -- Added for mantis : 33185 by Nilesh
		and vsf.isactivebatch = 1 -- Added for mantis : 33185 by Nilesh
		--sStudent.vStudentLastAcademic vSF ON vSF.StudentId = LA.SourceId AND LA.SourceTypeId = 2003 -- Commented
		
		--AND(((vSF.Code like @rCode) OR (ISNULL(@rCode,'') = '')) AND @rSourceTypeId = 2003)
		--AND(((vSF.Name like @rName) OR (ISNULL(@rName,'') = '')) AND @rSourceTypeId = 2003)
		--AND(vSF.BatchId= @rBatchId)
		LEFT JOIN sSetup.tDepartmentMaster DM ON DM.Id = vSF.DepartmentId		
		LEFT JOIN sSetup.tOrganizationMaster OM ON ((OM.Id = Emp.OrgId) OR (OM.Id = vSF.OrgId))
  WHERE 
  
	LA.LibraryId=@rLibraryId
	AND LA.OrgGroupBatchId=@rOrgGroupBatchId
	AND ((LA.Id=@rId) OR (@rId=0))
	AND ((OM.Id=@rOrgId) OR (@rOrgId=0))
	AND ((LA.SourceTypeId=@rSourceTypeId) OR (@rSourceTypeId=0))
	AND (((@rSourceTypeId =2003 OR(@rSourceTypeId=0)) AND vSF.Name like @rName) 
		OR (ISNULL(@rName,'')='') OR ((@rSourceTypeId =95 OR(@rSourceTypeId=0)) AND Emp.EmployeeName LIKE @rName) OR (ISNULL(@rName,'')='') 
		OR ((@rSourceTypeId =1 OR (@rSourceTypeId=0)) AND LA.GuestName LIKE @rName) OR (ISNULL(@rName,'')=''))
    AND (((@rSourceTypeId =2003 OR(@rSourceTypeId=0)) AND vSF.Code LIKE @rCode) OR (ISNULL(@rCode,'')='') 
        OR ((@rSourceTypeId =95 OR(@rSourceTypeId=0)) AND Emp.Code LIKE @rCode) OR (ISNULL(@rCode,'')=''))
	AND (LA.AttendanceDate>=@rFromAttendanceDate OR ISNULL(@rFromAttendanceDate,'')='')
	AND (LA.AttendanceDate<=@rToAttendanceDate OR ISNULL(@rToAttendanceDate,'')='')
	--AND vSF.StatusId = 1 -- Commented for mantis : 33185 by Nilesh
	--AND (vSF.IsActiveBatch = 1 OR Emp.StatusId = 7) -- Commented for mantis : 33185 by Nilesh
    ORDER BY LA.AttendanceDate,LA.InTime DESC
	
END
GO
PRINT N'Altering Procedure [sPayroll].[pGetTaxDetails]...';


GO
--exec [sPayroll].[pGetTaxDetails] 9911000000065,
ALTER PROCEDURE [sPayroll].[pGetTaxDetails]
	 @rEmployeeId bigint,
	 @rAssesmentYearId bigint = 0,
	 @rOrgGroupId int
AS
SET NOCOUNT ON

BEGIN

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

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


GO

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

	WITH EXECUTE AS CALLER
	AS
	SET NOCOUNT ON

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

		EXECUTE @lInterrorCode = sp_xml_preparedocument @intDoc OUTPUT, @rCandidateFamilyDetailsXml

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

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

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

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

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

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

		WHILE @lId <= @lCount 

		BEGIN

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

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

		SET @lId=@lId+1

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

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


GO
ALTER PROCEDURE [sStudent].[pRptCountCategorywiseStudentGet]
	 
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 @rOrgId smallint,
	 @rBatchId int,
	 @rClassId int,
	 @rDivisionId int,
	 @rAsOnDate date,
	 @rReportId int,
	 @rDepartmentId int,
	 @rStudentCode varchar(20),
	 @rCasteCategoryIds nvarchar(max) = '',
	 @rReligionIds nvarchar(max) = '',
	 @rGenderIds nvarchar(max) = '',
	 @rAdmissionCatgoryIds nvarchar(max) = '',
	 @rClassGroup bit=0,
	 @rDivisionGroup bit=0,
	 @rTribeIds nvarchar(max) = '',
	 --added by megha for 0027269
	 @rMainCasteCategoryIds nvarchar(max) = '',
	 @rStatusId smallint = 0,			-- MantisId : 0032948
	 @rClassStatusId smallint=0			-- MantisId : 0032948
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
  
	SELECT 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			CM.DisplayTitle AS Class,
			DM.DisplayTitle AS Division,
			ISNULL(GM.Title,'') As Gender,
			A.ClassId,
			A.DivisionId,
			A.Id AS AcademicId,
			A.RollNo,
			SO.DateOfBirth,
			SA.AdmissionDate,
			CM.DisplayTitle+' '+DM.DisplayTitle AS ClassDivision,
			SM.FirstName +' '+ SM.MiddleName +' '+ SM.LastName AS Name,
			SM.Code,
			CCM.OrderIndex AS CasteNumber,
			CASE WHEN  @rReportId=10135 OR @rReportId=20702-- Caste Category
			THEN ISNULL(CCM.Title,'')
		    WHEN  @rReportId=10136 OR @rReportId=20703 -- Religion
			THEN ISNULL(RM.Title,'') 
			WHEN  @rReportId=20704 -- Gender
			THEN ISNULL(GM.Title,'') 
			WHEN @rReportId=20328 OR @rReportId=20705 -- Admission Catgory 
			THEN ISNULL(SCM.Title,'')
			WHEN  @rReportId=10152 -- BloodGroupwise Summary
			THEN ISNULL(BGM.Title,'') 
			WHEN  @rReportId=20329 OR @rReportId=20706--Agegroupwise
			THEN  ([sStudent].[fStudentAgeGroupGet](SO.DateOfBirth,@rAsOnDate,@rOrgId))
			--WHEN  @rReportId=20426 OR @rReportId=20707  --Age wise
			--THEN  ([sStudent].[fStudentAgeGet](SO.DateOfBirth,@rAsOnDate,@rOrgId) + ' Y')
			WHEN    @rReportId = 20866 OR @rReportId=20426 OR @rReportId=20707
			
			THEN RIGHT('00'+ CAST([sStudent].[fStudentAgeGet](SO.DateOfBirth,@rAsOnDate,@rOrgId) AS VARCHAR(2)), 2)+' Year '
			
			WHen @rReportId=30236
			THEN ISNULL(HM.Title,'')
			WHEN  @rReportId=31039 OR @rReportId=31040 -- Tribe
			THEN ISNULL(TM.Title,'')
			--added by megha for 0027269
			WHEN @rReportId=31266
			THEN  ISNULL(MCM.Title,'')  --MainCasteCategory

			END AS Head,
			DM.OrderIndex AS DivisionOrder,
			@rClassGroup As ClassGroup,
			@rDivisionGroup As DivisionGroup,
			Cm.OrderINdex AS ClassOrderIndex,
			CASE WHEN  @rReportId=10135 OR @rReportId=20702-- Caste Category
			THEN ISNULL(CCM.OrderIndex,'')
		    WHEN  @rReportId=10136 OR @rReportId=20703 -- Religion
			THEN ISNULL(RM.OrderIndex,'')  
			ELSE ''
			END AS OrderIndex,
			A.OrgId
			FROM 
			sStudent.tAcademic A		
			INNER JOIN sStudent.tStudentMaster SM ON SM.Id=A.StudentId	
			LEFT JOIN sStudent.tStudentOther SO ON A.StudentId=SO.StudentId
			LEFT JOIN sStudent.tStudentAdmission SA ON SA.StudentId=A.StudentId
			LEFT JOIN sCommon.tGenderMaster GM ON GM.Id=SO.GenderId
			INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId
			INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId
			LEFT JOIN sCommon.tCastCategoryMaster CCM ON CCM.Id=SO.CastCategoryId
			LEFT JOIN sCommon.tReligionMaster RM ON RM.Id=SO.ReligionId
			LEFT JOIN sCommon.tBloodGroupMaster BGM ON BGM.Id=SO.BloodGroupId
			LEFT JOIN sStudent.tAdmissionCategoryMaster SCM ON SCM.Id=A.AdmissionCategoryId
			LEFT JOIN sActivity.tHouseMaster HM ON HM.Id=SO.HouseID
			INNER JOIN sSetup.tBatchClass BC ON BC.ClassID =  CM.Id and BC.BatchId= @rBatchId
			LEFT JOIN sCommon.tTribeMaster TM ON TM.Id=SO.TribeId   -- Tribe
			--added by megha for 0027269
			LEFT JOIN sCommon.tMainCastCategoryMaster MCM ON MCM.Id = CCM.MainCastCategoryId   -- MainCastCategory
	WHERE 
		A.OrgId=@rOrgId
		AND	A.BatchId = @rBatchId 
		AND ((A.ClassId=@rClassId) OR (@rClassId=0))
		AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		AND ( SM.StatusId = 1 OR @rReportId = 20328)				-- MantisId : 0032948
		AND ((SM.Code=@rStudentCode) OR (@rStudentCode=''))
		AND ((CM.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
	    AND (ISNULL(CCM.Id,0) IN(SELECT cast(item as int) FROM  sCommon.fnsplit(@rCasteCategoryIds,','))OR @rCasteCategoryIds='')
	    AND (ISNULL(RM.Id,0) IN(SELECT cast(item as int) FROM  sCommon.fnsplit(@rReligionIds,','))OR @rReligionIds='')
	    AND (ISNULL(GM.Id,0) IN(SELECT cast(item as int) FROM  sCommon.fnsplit(@rGenderIds,','))OR @rGenderIds='')
	    AND (ISNULL(SCM.Id,0) IN(SELECT cast(item as int) FROM  sCommon.fnsplit(@rAdmissionCatgoryIds,','))OR @rAdmissionCatgoryIds='')
		AND (ISNULL(TM.Id,0) IN (SELECT cast(item as int) FROM  sCommon.fnsplit(@rTribeIds,','))OR @rTribeIds='')
	    AND ((SA.AdmissionDate<=@rAsOnDate) OR (ISNULL(@rAsOnDate,'') = ''))
		AND (ISNULL(MCM.Id,0) IN(SELECT cast(item as int) FROM  sCommon.fnsplit(@rMainCasteCategoryIds,','))OR @rMainCasteCategoryIds='')
		AND (SM.StatusId = @rStatusId OR @rStatusId = 0)				-- MantisId : 0032948
		AND (A.ClassStatusId = @rClassStatusId OR @rClassStatusId = 0)	-- MantisId : 0032948
END

 
	--Select * from sStudent.tStudentAdmission where AdmissionDate = '2013-05-12'
GO
PRINT N'Altering Procedure [sStudent].[pXMLStudentImportAdd]...';


GO
ALTER PROCEDURE [sStudent].[pXMLStudentImportAdd]
	
	@rStudentImpXml [nvarchar](max),
	@rToOrgId int,
	@rToBatchId int,
	@rToClassId int,
	@rToDivisionId int,
	@rAdmissionDate date,
	@rCreatedUserId bigint,
	@rIsStudentOldCodeWithOrgId bit=0
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

DECLARE @loDoc INT
EXEC sp_xml_preparedocument @loDoc OUTPUT, @rStudentImpXml
BEGIN

	
	DECLARE @lCount INT
	DECLARE @lNextNumber BIGINT 
	Declare @lExistCode nvarchar(max)
	DECLARE @MaxCode AS bigint
	
	IF OBJECT_ID('sStudent.tTempStudentId') IS NOT NULL
    EXEC ('DROP Table sStudent.tTempStudentId')
 
	IF EXISTS(SELECT SM.Code
	from
	(
			SELECT StudentId FROM
			OPENXML (@loDoc, '/Table/StudentImportDetail', 1)
			WITH (
					StudentId bigint)	
	)E
	INNER JOIN sStudent.tStudentMaster SM ON SM.ReferenceSourceId=E.StudentId AND SM.OrgId=@rToOrgId	
	)
	BEGIN
		SELECT @lExistCode  = COALESCE(@lExistCode ,'') + 'Old : '+ CONVERT(VARCHAR(15),E.Code) +' - ' + 'New : '+  SM.Code + ' , ' 
		from
		(
				SELECT StudentId,Code FROM
				OPENXML (@loDoc, '/Table/StudentImportDetail', 1)
				WITH (
						StudentId bigint,
						Code nvarchar(20)
						)
		)E
		INNER JOIN sStudent.tStudentMaster SM ON SM.ReferenceSourceId=E.StudentId AND SM.OrgId=@rToOrgId	
		SELECT @lExistCode
		RETURN
	END
	
	--BEGIN TRY
	--BEGIN TRANSACTION

	EXECUTE sCommon.pTableRowIdGet @rToOrgId, 'sStudent.tStudentMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	SELECT @MaxCode = MAX(Number) FROM sStudent.tStudentMaster WHERE OrgId = @rToOrgId
	--SET @MaxCode = ISNULL(@MaxCode,0) + 1
	
	IF(@rIsStudentOldCodeWithOrgId = 0)
	BEGIN
	SELECT 
			@lNextNumber + ROW_NUMBER() OVER(ORDER BY E.StudentId)AS NewStudentId,
			E.StudentId,
			ISNULL(@MaxCode,0) + ROW_NUMBER() OVER(ORDER BY E.StudentId) AS Code,			
			AdmissionCategoryId
	INTO 
			sStudent.tTempStudentId
	from
	(
			SELECT StudentId,AdmissionCategoryId,Code FROM
			OPENXML (@loDoc, '/Table/StudentImportDetail', 1)
			WITH (
					StudentId bigint,
					AdmissionCategoryId int,
					Code nvarchar(20)
					)	
	)E
	END
	ELSE IF (@rIsStudentOldCodeWithOrgId = 1)
	BEGIN
	SELECT 
			@lNextNumber + ROW_NUMBER() OVER(ORDER BY E.StudentId)AS NewStudentId,
			E.StudentId,
			CONVERT(NVARCHAR(4),LEFT(E.StudentId,4)) + E.Code AS Code,
			AdmissionCategoryId
	INTO 
			sStudent.tTempStudentId
	from
	(
			SELECT StudentId,AdmissionCategoryId,Code FROM
			OPENXML (@loDoc, '/Table/StudentImportDetail', 1)
			WITH (
					StudentId bigint,
					AdmissionCategoryId int,
					Code nvarchar(20)
					)	
	)E
	END

	SELECT @lCount = COUNT(1) FROM OPENXML (@loDoc, '/Table/StudentImportDetail', 1)
				 WITH ( Id int )
	SET @lNextNumber  = @lCount + @lNextNumber 
	
	EXECUTE sCommon.pTableRowIdModify @rToOrgId, @rTableTitle = 'sStudent.tStudentMaster', @rCurrentNumber = @lNextNumber 
		 print 'Academic'
	--Insert Into Student Master
	INSERT INTO sStudent.tStudentMaster
	(
			Id,
			Code,
			Number,
			FirstName,
			MiddleName,
			LastName,
			OrgId,
			StatusId,
			RecordStatusId,
			CreatedUserId,
			CreatedDateTime,
			ReferenceSourceId,
			AdmissionCategoryId,
			RegistrationNumber,
			IsBlackList,
			BlackListReason,
			SUId
		
	)
	SELECT 
			TS.NewStudentId,
			TS.Code,
			CASE WHEN ISNUMERIC(TS.Code) <> 0 THEN TS.Code ELSE TS.NewStudentId END,
			SM.FirstName,
			SM.MiddleName,
			SM.LastName,
			@rToOrgId,
			1,
			502,
			@rCreatedUserId,
			sCommon.fGetDate(),
			TS.StudentId,
			SM.AdmissionCategoryId,
			SM.RegistrationNumber,
			SM.IsBlackList,
			SM.BlackListReason,
			SM.SUId
	FROM
			sStudent.tTempStudentId TS	
		INNER JOIN sStudent.tStudentMaster SM ON SM.ID=TS.StudentId
		
	--Insert Into Academic
		
	EXECUTE sCommon.pTableRowIdGet @rToOrgId, 'sStudent.tAcademic', 0, 1, 1,@outNextNumber = @lNextNumber output


 print 'Academic'
	INSERT INTO sStudent.tAcademic
	(
			Id,
			StudentId,
			ClassId,
			BatchId,
			DivisionId,
			RollNo,
			OrgId,
			CreatedUserId,
			CreatedDateTime,
			AdmissionCategoryId,
			ClassStatusId
	)
	SELECT
			@lNextNumber+ ROW_NUMBER() OVER(ORDER BY StudentId),
			NewStudentId,
			@rToClassId,
			@rToBatchId,
			@rToDivisionId,
			0,
			@rToOrgId,
			@rCreatedUserId,
			sCommon.fGetDate(),
			AdmissionCategoryId,
			1
	FROM 
			sStudent.tTempStudentId

print 'Academic1'		
	SELECT @lCount = COUNT(1) FROM OPENXML (@loDoc, '/Table/StudentImportDetail', 1)
			 WITH ( Id int )
	SET @lNextNumber  = @lCount + @lNextNumber 
	
	EXECUTE sCommon.pTableRowIdModify @rToOrgId, @rTableTitle = 'sStudent.tAcademic', @rCurrentNumber = @lNextNumber 
	
	--Insert Into Student Other
	INSERT INTO sStudent.tStudentOther
	(
		   [StudentId]
		  ,[UIDNumber]
		  ,[DateOfBirth]
		  ,[BirthDateInWord]
		  ,[TransportModeId]
		  ,[GenderId]
		  ,[BloodGroupId]
		  ,[BirthPlace]
		  ,[BirthTaluka]
		  ,[BirthDistrict]
		  ,[FamilyCast]
		  ,[FamilySubCast]
		  ,[CastCategoryId]
		  ,[ReligionId]
		  ,[HouseId]
		  ,[MotherTongueId]
		  ,[NationalityId]
		  ,[Hobby]		   
		  ,[CreatedUserId]
		  ,[CreatedDateTime]
		  ,ReferenceRemark
		  ,AdhaarNumber
		  ,MotherTongue
		  ,QuotaId
		  ,BirthState
		  ,BirthCountry
	)
	SELECT 
		   TS.NewStudentId
		  ,SO.[UIDNumber]
		  ,SO.[DateOfBirth]
		  ,SO.[BirthDateInWord]
		  ,SO.[TransportModeId]
		  ,SO.[GenderId]
		  ,SO.[BloodGroupId]
		  ,SO.[BirthPlace]
		  ,SO.[BirthTaluka]
		  ,SO.[BirthDistrict]
		  ,SO.[FamilyCast]
		  ,SO.[FamilySubCast]
		  ,SO.[CastCategoryId]
		  ,SO.ReligionId		   
		  ,NULL
		  ,so.MotherTongueId
		  ,So.NationalityId		 
		  ,SO.[Hobby] 
		  ,@rCreatedUserId
		  ,sCommon.fGetDate()
		  ,ReferenceRemark
		  ,AdhaarNumber
		  ,MotherTongue
		  ,QuotaId
		  ,BirthState
		  ,BirthCountry
	FROM
			sStudent.tTempStudentId TS	
		INNER JOIN sStudent.tStudentOther SO ON SO.StudentId=TS.StudentId
	
	--Insert Into Student Admission
	INSERT INTO sStudent.tStudentAdmission
	(
		   [StudentId]
		  ,[PreviousStudentId]
		  ,[AdmissionStandardId]
		  ,[AdmissionDate]
		  ,[AdmissionYear]
		  ,[BatchId]
		  ,[CreatedUserId]
		  ,[CreatedDateTime]
		  ,PreviousSchool
	)
	SELECT 
		   TS.NewStudentId
		  ,TS.StudentId
		  ,@rToClassId
		  ,@rAdmissionDate
		  ,YEAR(GETDATE())
		  ,@rToBatchId
		  ,@rCreatedUserId
		  ,sCommon.fGetDate()
		  ,PreviousSchool
	FROM
			sStudent.tTempStudentId TS	
		INNER JOIN sStudent.tStudentAdmission SA ON SA.StudentId=TS.StudentId
	
	
INSERT INTO [sStudent].[tStudentCommunication]
           ([StudentId]
           ,[PresentStreetOne]
           ,[PresentStreetTwo]
           ,[PresentStreetThree]
           ,[PresentCountry]
           ,[PresentState]
           ,[PresentCity]
           ,[PresentZipCode]
           ,[PresentContactNo]
           ,[PermanentStreetOne]
           ,[PermanentStreetTwo]
           ,[PermanentStreetThree]
           ,[PermanentCountry]
           ,[PermanentState]
           ,[PermanentCity]
           ,[PermanentZipCode]
           ,[PermanentContactNo]
           ,[EmergencyStreetOne]
           ,[EmergencyStreetTwo]
           ,[EmergencyStreetThree]
           ,[EmergencyCountry]
           ,[EmergencyState]
           ,[EmergencyCity]
           ,[EmergencyZipCode]
           ,[EmergencyContactNo]
           ,[ParentContactNo]
           ,[ParentEmail]
           ,[StudentContactNo]
           ,[StudentEmail]
           ,[CreatedUserId]
           ,[CreatedDateTime]  
		   ,PresentDistanceFromSchool
		   ,WhatsAppContactNo
		   )
 
 SELECT 
			TS.NewStudentId
           ,[PresentStreetOne]
           ,[PresentStreetTwo]
           ,[PresentStreetThree]
           ,[PresentCountry]
           ,[PresentState]
           ,[PresentCity]
           ,[PresentZipCode]
           ,[PresentContactNo]
           ,[PermanentStreetOne]
           ,[PermanentStreetTwo]
           ,[PermanentStreetThree]
           ,[PermanentCountry]
           ,[PermanentState]
           ,[PermanentCity]
           ,[PermanentZipCode]
           ,[PermanentContactNo]
           ,[EmergencyStreetOne]
           ,[EmergencyStreetTwo]
           ,[EmergencyStreetThree]
           ,[EmergencyCountry]
           ,[EmergencyState]
           ,[EmergencyCity]
           ,[EmergencyZipCode]
           ,[EmergencyContactNo]
           ,[ParentContactNo]
           ,[ParentEmail]
           ,[StudentContactNo]
           ,[StudentEmail]
           ,@rCreatedUserId
           ,sCommon.fGetDate()
		   ,PresentDistanceFromSchool
		   ,WhatsAppContactNo	
	FROM
			sStudent.tTempStudentId TS	
		INNER JOIN [sStudent].[tStudentCommunication] SA ON SA.StudentId=TS.StudentId          
	
	
	
	INSERT INTO  [sStudent].[tStudentFamily]
           ([StudentId]
           ,[FatherName]
           ,[FatherDateOfBirth]
           ,[FatherOccupation]
           ,[FatherQualification]
           ,[FatherContactNo]
           ,[FatherMail]
           ,[FatherOfficeAddress]
           ,[FatherIncome]
           ,[MotherName]
           ,[MotherDateOfBirth]
           ,[MotherOccupation]
           ,[MotherQualification]
           ,[MotherContactNo]
           ,[MotherMail]
           ,[MotherOfficeAddress]
           ,[MotherIncome]
           ,[RelationshipName]
           ,[RelativeName]
           ,[RelativeDateOfBirth]
           ,[RelativeOccupation]
           ,[RelativeQualification]
           ,[RelativeContactNo]
           ,[RelativeMail]
           ,[RelativeOfficeAddress]
           ,[RelativeIncome]
           ,[CreatedUserId]
           ,[CreatedDateTime]
           ,[FatherPhoto]
           ,[MotherPhoto]
           ,[RelativePhoto]
           ,[MarriageAnniversaryDate]
		   ,LiveWithId
		   ,IsFatherExStudent
		   ,FatherPassOutYear
		   ,IsMotherExStudent
		   ,MotherPassOutYear
		   ,IsRelativeExStudent
		   ,RelativePassOutYear)
     SELECT    
			TS.NewStudentId
           ,[FatherName]
           ,[FatherDateOfBirth]
           ,[FatherOccupation]
           ,[FatherQualification]
           ,[FatherContactNo]
           ,[FatherMail]
           ,[FatherOfficeAddress]
           ,[FatherIncome]
           ,[MotherName]
           ,[MotherDateOfBirth]
           ,[MotherOccupation]
           ,[MotherQualification]
           ,[MotherContactNo]
           ,[MotherMail]
           ,[MotherOfficeAddress]
           ,[MotherIncome]
           ,[RelationshipName]
           ,[RelativeName]
           ,[RelativeDateOfBirth]
           ,[RelativeOccupation]
           ,[RelativeQualification]
           ,[RelativeContactNo]
           ,[RelativeMail]
           ,[RelativeOfficeAddress]
           ,[RelativeIncome]
           ,@rCreatedUserId
           ,sCommon.fGetDate()
           ,[FatherPhoto]
           ,[MotherPhoto]
           ,[RelativePhoto]
           ,[MarriageAnniversaryDate]
		   ,LiveWithId
		   ,IsFatherExStudent
		   ,FatherPassOutYear
		   ,IsMotherExStudent
		   ,MotherPassOutYear
		   ,IsRelativeExStudent
		   ,RelativePassOutYear
   	FROM
			sStudent.tTempStudentId TS	
		INNER JOIN sStudent.tStudentFamily SA ON SA.StudentId=TS.StudentId    


INSERT INTO  [sStudent].[tStudentHealth]
           ([StudentId]
           ,[IdentificationMark1]
           ,[IdentificationMark2]
           ,[IsPysicalDeformity]
           ,[PysicalDeformityRemark]
           ,[IsMajorIllness]
           ,[MajorIllnessRemark]
           ,[IsAllergy]
           ,[AllergyRemark]
           ,[IsPastHistory]
           ,[PastHistoryRemark]
           ,[FamilyDoctorName]
           ,[FamilyDoctorContactNo]
           ,[UpdatedUserId]
           ,[UpdatedDateTime])
SELECT

			TS.NewStudentId
           ,[IdentificationMark1]
           ,[IdentificationMark2]
           ,[IsPysicalDeformity]
           ,[PysicalDeformityRemark]
           ,[IsMajorIllness]
           ,[MajorIllnessRemark]
           ,[IsAllergy]
           ,[AllergyRemark]
           ,[IsPastHistory]
           ,[PastHistoryRemark]
           ,[FamilyDoctorName]
           ,[FamilyDoctorContactNo]
           ,@rCreatedUserId
           ,sCommon.fGetDate()

   	FROM
			sStudent.tTempStudentId TS	
		INNER JOIN sStudent.tStudentHealth SA ON SA.StudentId=TS.StudentId 
		
		
		INSERT INTO  [sStudent].[tStudentImages]
           ([StudentId]
           ,[StudentPhoto]
           ,[FatherPhoto]
           ,[MotherPhoto]
           ,[RelativePhoto]
           ,[UpdatedDateTime])
           
           SELECT           
            TS.NewStudentId
           ,[StudentPhoto]
           ,[FatherPhoto]
           ,[MotherPhoto]
           ,[RelativePhoto]
           ,sCommon.fGetDate()
         	FROM
			sStudent.tTempStudentId TS	
		INNER JOIN sStudent.tStudentImages SA ON SA.StudentId=TS.StudentId    
		
		
		
		INSERT INTO [sStudent].[tStudentAdditional]
           (StudentId,
			BankAccountNumber,
			BankName,
			BankBranch,
			BankIFSCCode,
			Class9BoardRegistrationNumber,
			Class11BoardRegistrationNumber,
			PassportNumber,
			PassportType,
			PassportCountryCode,
			PassportIssueDate,
			PassportExpiryDate,
			BankAccountHolderName
           )
           
           SELECT           
            TS.NewStudentId,
            BankAccountNumber,
            BankName,
			BankBranch,
			BankIFSCCode,
			Class9BoardRegistrationNumber,
			Class11BoardRegistrationNumber,
			PassportNumber,
			PassportType,
			PassportCountryCode,
			PassportIssueDate,
			PassportExpiryDate,
			BankAccountHolderName
         	FROM
			sStudent.tTempStudentId TS	
		INNER JOIN sStudent.tStudentAdditional SA ON SA.StudentId=TS.StudentId        
	    

		---Studen Sibling Detail-
			
		INSERT INTO [sStudent].[tStudentSibling]
           (StudentId,
			SiblingName1,
			SiblingInstitue1,
			SiblingClass1,
			SiblingAge1,
			SiblingRelation1,
			SiblingName2,
			SiblingInstitue2,
			SiblingClass2,
			SiblingAge2,
			SiblingRelation2,
			SiblingName3,
			SiblingInstitue3,
			SiblingClass3,
			SiblingAge3,
			SiblingRelation3

           )
           
           SELECT           
            TS.NewStudentId,
            SiblingName1,
			SiblingInstitue1,
			SiblingClass1,
			SiblingAge1,
			SiblingRelation1,
			SiblingName2,
			SiblingInstitue2,
			SiblingClass2,
			SiblingAge2,
			SiblingRelation2,
			SiblingName3,
			SiblingInstitue3,
			SiblingClass3,
			SiblingAge3,
			SiblingRelation3
         	FROM
			sStudent.tTempStudentId TS	
		INNER JOIN [sStudent].[tStudentSibling] SA ON SA.StudentId=TS.StudentId        

		INSERT INTO  [sStudent].[tCollegeDetail]
            (StudentId,
			AdmissionNumber,
			IsTransfer,
			TransferFrom,
			PassingYear,
			IsTFWS,
			IsCertificateHolder,
			CertificateName,
			SSCBoard,
			SSCSchool,
			SSCPassingYear,
			SSCObtainMarks,
			SSCOutOfMarks,
			SSCPercentage,
			SSCMathMarks,
			SSCMathOutOfMarks,
			HSCBoard,
			HSCSchool,
			HSCPassingYear,
			HSCObtainMarks,
			HSCOutOfMarks,
			HSCPercentage,
			HSCPhysicsMarks,
			HSCPhysicsOutOfMarks,
			HSCChemistryMarks,
			HSCChemistryOutOfMarks,
			HSCMathMarks,
			HSCMathOutOfMarks,
			HSCBiologyMarks,
			HSCBiologyOutOfMarks,
			PCMMarks,
			PCBMarks,
			JEERollNo,
			JEEMeritNo,
			JEEMeritMarks,
			JEEOutOfMarks,
			DiplomaBoard,
			DiplomaCollege,
			DiplomaPassingYear,
			DiplomaObtainMarks,
			DiplomaOutOfMarks,
			DiplomaPercentage,
			ApplicationNo,
			AdmissionRound,
			MaritalStatusId
)
SELECT

			TS.NewStudentId,
            AdmissionNumber,
			IsTransfer,
			TransferFrom,
			PassingYear,
			IsTFWS,
			IsCertificateHolder,
			CertificateName,
			SSCBoard,
			SSCSchool,
			SSCPassingYear,
			SSCObtainMarks,
			SSCOutOfMarks,
			SSCPercentage,
			SSCMathMarks,
			SSCMathOutOfMarks,
			HSCBoard,
			HSCSchool,
			HSCPassingYear,
			HSCObtainMarks,
			HSCOutOfMarks,
			HSCPercentage,
			HSCPhysicsMarks,
			HSCPhysicsOutOfMarks,
			HSCChemistryMarks,
			HSCChemistryOutOfMarks,
			HSCMathMarks,
			HSCMathOutOfMarks,
			HSCBiologyMarks,
			HSCBiologyOutOfMarks,
			PCMMarks,
			PCBMarks,
			JEERollNo,
			JEEMeritNo,
			JEEMeritMarks,
			JEEOutOfMarks,
			DiplomaBoard,
			DiplomaCollege,
			DiplomaPassingYear,
			DiplomaObtainMarks,
			DiplomaOutOfMarks,
			DiplomaPercentage,
			ApplicationNo,
			AdmissionRound,
			MaritalStatusId

   	FROM
			sStudent.tTempStudentId TS	
		INNER JOIN sStudent.tCollegeDetail SA ON SA.StudentId=TS.StudentId 

		-- -Student Custom Tag-
		INSERT INTO [sStudent].[tStudentCustomTag]
           (StudentId,CustomTagId
           )
SELECT

			TS.NewStudentId,CustomTagId
       
   	FROM
			sStudent.tTempStudentId TS	
		INNER JOIN sStudent.tStudentCustomTag SA ON SA.StudentId=TS.StudentId 
		

	    -- for update hostel 
	    -- Start
		--UPDATE A SET A.SourceId = T.NewStudentId 
		--FROM sHostel.tAssignRoom A JOIN sStudent.tTempStudentId T ON A.SourceId = T.StudentId AND A.SourceTypeId = 2003
		
		--UPDATE A SET A.SourceId = T.NewStudentId 
		--FROM sHostel.tAssignRoomAsset A JOIN sStudent.tTempStudentId T ON A.SourceId = T.StudentId AND A.SourceTypeId = 2003
		
		--UPDATE A SET A.StudentId = T.NewStudentId 
		--FROM sHostel.tAttendanceRegister A JOIN sStudent.tTempStudentId T ON A.StudentId = T.StudentId
		
		--UPDATE A SET A.SourceId = T.NewStudentId 
		--FROM sHostel.tChangeRoom A JOIN sStudent.tTempStudentId T ON A.SourceId = T.StudentId AND A.SourceTypeId = 2003
		
		--UPDATE A SET A.SourceId = T.NewStudentId 
		--FROM sHostel.tHostelAdmission A JOIN sStudent.tTempStudentId T ON A.SourceId = T.StudentId AND A.SourceTypeId = 2003
		
		--UPDATE A SET A.StudentId = T.NewStudentId 
		--FROM sHostel.tHostelDepositAdd A JOIN sStudent.tTempStudentId T ON A.StudentId = T.StudentId
		
		--UPDATE A SET A.StudentId = T.NewStudentId 
		--FROM sHostel.tHostelDepositAdjustment A JOIN sStudent.tTempStudentId T ON A.StudentId = T.StudentId
		
		--UPDATE A SET A.StudentId = T.NewStudentId 
		--FROM sHostel.tHostelDepositRefund A JOIN sStudent.tTempStudentId T ON A.StudentId = T.StudentId
		
		--UPDATE A SET A.StudentId = T.NewStudentId 
		--FROM sHostel.tStudentGatePass A JOIN sStudent.tTempStudentId T ON A.StudentId = T.StudentId
		
		--UPDATE A SET A.WhomToMeetSourceId = T.NewStudentId 
		--FROM sHostel.tVisitorGatePass A JOIN sStudent.tTempStudentId T ON A.WhomToMeetSourceId = T.StudentId AND WhomToMeetSourceTypeId = 2003
		-- End
		
		
		-- for update transport
		-- Start
		--UPDATE A SET A.SourceId = T.NewStudentId 
		--FROM sTransport.tAssignRoute A JOIN sStudent.tTempStudentId T ON A.SourceId = T.StudentId AND A.SourceTypeId = 2003
		
		--UPDATE A SET A.SourceId = T.NewStudentId 
		--FROM sTransport.tAttendanceRegister A JOIN sStudent.tTempStudentId T ON A.SourceId = T.StudentId AND A.SourceTypeId = 2003
		-- End
		
		-- for update Library
		-- Start
		UPDATE A SET A.ReaderSourceId = T.NewStudentId 
		FROM sLibrary.tBookLog A JOIN sStudent.tTempStudentId T ON A.ReaderSourceId = T.StudentId AND A.ReaderSourceTypeId = 2003
		
		UPDATE A SET A.SourceId = T.NewStudentId 
		FROM sLibrary.tLibraryAttendance A JOIN sStudent.tTempStudentId T 
		ON A.SourceId = T.StudentId AND A.SourceTypeId = 2003
		-- End
		
		-- for update Canteen
		-- Start
		UPDATE A SET A.SourceId = T.NewStudentId 
		FROM sCanteen.tCanteenIssue A JOIN sStudent.tTempStudentId T 
		ON A.SourceId = T.StudentId AND A.SourceTypeId = 2003
		
		-- End
	
	DROP TABLE sStudent.tTempStudentId
	
    SELECT 1 AS Result
	
	--COMMIT TRANSACTION
		
	--END TRY
	
	--BEGIN CATCH 
	--	ROLLBACK TRANSACTION
	--	SELECT Error_message()
	--	SELECT -1 AS Result
	--END CATCH	
		
END
GO

CREATE PROCEDURE [sConfig].[pConfigurationSetupValidate]
	 
	@rConfigurationId [int],
	@rItemValue nvarchar(500),
	@rSourceTypeId [int],
	@rSourceId [bigint]
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	IF(@rConfigurationId = 553)	--Fee.IsCollectionGroupMandatory
	BEGIN
		DECLARE @lIsFeeByCollectionGroupItemValue nvarchar(500) = ''
		Select @lIsFeeByCollectionGroupItemValue = ItemValue From sConfig.tConfigurationSetup Where ConfigurationId = 150 AND SourceId = @rSourceId AND SourceTypeId=@rSourceTypeId --Fee.IsFeeByCollectionGroup

		IF(@rItemValue = 'True' AND @lIsFeeByCollectionGroupItemValue = 'False')
		BEGIN
			SELECT -1 AS Result, 'Kindly change configuration - Fee.IsFeeByCollectionGroup to True' AS Message
		END

		--DECLARE @lIsGenerateMultipleFeeReceiptItemValue nvarchar(500) = ''
		--Select @lIsGenerateMultipleFeeReceiptItemValue = ItemValue From sConfig.tConfigurationSetup Where ConfigurationId = 116 AND SourceId = @rSourceId AND SourceTypeId=@rSourceTypeId --Fee.IsGenerateMultipleFeeReceipt

		--IF(@rItemValue = 'True' AND @lIsGenerateMultipleFeeReceiptItemValue = 'True')
		--BEGIN
		--	SELECT -1 AS Result, 'Kindly change configuration - Fee.IsGenerateMultipleFeeReceipt to False' AS Message
		--END
	END
END
GO
PRINT N'Creating Procedure [sFee].[pChargeReceiptDetailXMLAdd]...';


GO
CREATE PROCEDURE [sFee].[pChargeReceiptDetailXMLAdd]
	
	@rChargeReceiptDetail nvarchar(max),
	@rSourceTypeId int,
	@rOrgId int,
	@rBatchId int,
	@rReceiptBookId int,
	@rOrgGroupBatchId int,
	@rUserId bigint,
	--@rIsChargeAmountEditable bit
	@rIsObsolete bit =0
	
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
--DECLARE @loDoc INT
--EXEC sp_xml_preparedocument @loDoc OUTPUT, @rCandidateApplicationEmployementXml
	
	DECLARE @rChargeReceiptDetailXML XML
	SET @rChargeReceiptDetailXML = CAST(@rChargeReceiptDetail AS XML)
	DECLARE @lInterrorCode INT,@intDoc INT
	DECLARE @lNextNumber BIGINT
	DECLARE @lReceiptDetailXML XML
	DECLARE @lReceiptAmount	DECIMAL(12,2)	
 
	--EXECUTE @lInterrorCode = sp_xml_preparedocument @intDoc OUTPUT, @rChargeReceiptDetailXML
		
	BEGIN TRY
	
		IF OBJECT_ID('tempdb..#TempChargeReceipt') IS NOT NULL
			BEGIN
				-- If the table exists, drop it
				DROP TABLE #TempChargeReceipt;
			END

		CREATE TABLE #TempChargeReceipt  
		(
			Id bigint identity,
			OrgId int ,
			SourceTypeId int ,
			SourceId bigint,
			GuestName nvarchar(300),
			ReceiptDate Date,
			PayTypeId int,
			ChequeNo nvarchar(20),
			BankName nvarchar(200),
			BatchId int,
			ReceiptBookId int,
			OrgGroupBatchId int,
			CreatedUserId bigint,
			ChequeDate date,
			ReceiptDetailXML XML
		)
		INSERT INTO #TempChargeReceipt(
			OrgId ,
			SourceTypeId ,
			SourceId ,
			GuestName ,
			ReceiptDate ,
			PayTypeId ,
			ChequeNo ,
			BankName ,
			BatchId ,
			ReceiptBookId ,
			OrgGroupBatchId ,
			CreatedUserId ,
			ChequeDate ,
			ReceiptDetailXML
			)
			SELECT
				@rOrgId,
				@rSourceTypeId,
				cr.value('@SourceId', 'BIGINT'),
				cr.value('@GuestName', 'NVARCHAR(200)'),
				sCommon.fGetDate(),
				cr.value('@PayTypeId', 'INT'),
				cr.value('@ChequeNo', 'NVARCHAR(20)'),
				cr.value('@BankName', 'NVARCHAR(200)'),
				@rBatchId,
				@rReceiptBookId,
				@rOrgGroupBatchId,
				@rUserId,
				cr.value('@ChequeDate', 'DATE'),
				cr.query('ReceiptDetail') -- Extracting ReceiptDetailXML
			FROM
				@rChargeReceiptDetailXML.nodes('/Table/ChargeReceipt') AS t(cr);

		--Select * from #tempTable
		--SELECT 1 AS Result
		DECLARE @lCount int,@lId int
		SELECT @lCount = COUNT(Id) FROM #TempChargeReceipt
		SELECT Top 1 @lId=Id FROM #TempChargeReceipt

		WHILE @lId <= @lCount 
		BEGIN
			--DECLARE @lNextNumber BIGINT
			SET @lReceiptDetailXML = NULL     
			SELECT @lReceiptDetailXML = ReceiptDetailXML FROM  #TempChargeReceipt WHERE  Id = @lId

			SET @lReceiptDetailXML = (
			SELECT CAST('<ReceiptDetailList>' + CAST(@lReceiptDetailXML AS NVARCHAR(MAX)) + '</ReceiptDetailList>' AS XML)
			)

			EXECUTE @lInterrorCode = sp_xml_preparedocument @intDoc OUTPUT, @lReceiptDetailXML

			IF OBJECT_ID('tempdb..#TempChargeReceiptDetail') IS NOT NULL
			BEGIN
				-- If the table exists, drop it
				DROP TABLE #TempChargeReceiptDetail;
			END

			CREATE TABLE #TempChargeReceiptDetail  
			(
				Id bigint identity,
				ChargeId int,
				Remark nvarchar(100),
				Amount decimal(12,2)
			)

			INSERT INTO #TempChargeReceiptDetail
				(ChargeId,
				Remark,
				Amount
				)
				SELECT
				ChargeId,
				Remark,
				Amount

				FROM OPENXML (@intDoc, '/ReceiptDetailList/ReceiptDetail', 1)
				WITH (
				ChargeId INT,
				Remark NVARCHAR(100),
				Amount DECIMAL(12,2)
				)

			SELECT @lReceiptAmount = SUM(Amount) FROM #TempChargeReceiptDetail

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

			INSERT INTO sFee.tChargeReceipt
			(
				OrgId,
				Id,
				SourceTypeId,
				SourceId,
				GuestName,
				Remark,
				ReceiptNumber,
				ReceiptDate,
				PayTypeId,
				ChequeNo,
				BankName,
				BatchId,
				ChargeReceiptBookId,
				OrgGroupBatchId,
				CreatedUserId,
				CreatedDateTime,
				ReceiptAmount,
				ChequeDate,
				IsObsolete
			)
			Select
				OrgId,
				@lNextNumber,
				SourceTypeId,
				tmp.SourceId,
				tmp.GuestName,
				'',
				sFee.fChargeReceiptNumberGet(@rReceiptBookId,@rOrgGroupBatchId),
				tmp.ReceiptDate,
				tmp.PayTypeId,
				tmp.ChequeNo,
				tmp.BankName,
				tmp.BatchId,
				tmp.ReceiptBookId,
				tmp.OrgGroupBatchId,
				tmp.CreatedUserId,
				sCommon.fGetDate(),
				@lReceiptAmount,
				tmp.ChequeDate,
				@rIsObsolete

			FROM  #TempChargeReceipt tmp 
			where  Id = @lId

			DECLARE @lCount1 int,@lId1 int
			SELECT @lCount1 = COUNT(Id) FROM #TempChargeReceiptDetail
			SELECT Top 1 @lId1=Id FROM #TempChargeReceiptDetail

			WHILE @lId1 <= @lCount1 
			BEGIN

				INSERT INTO sFee.tChargeReceiptDetail
				(
					ChargeReceiptId,
					ChargeId,
					Remark,
					Amount,
					UpdatedUserId,
					UpdatedDateTime,
					IsObsolete
				)
				Select
					@lNextNumber,
					ChargeId,
					Remark,
					Amount,
					@rUserId,
					sCommon.fGetDate(),
					@rIsObsolete
					FROM  #TempChargeReceiptDetail TCR 
					where  Id = @lId1

				SET @lId1=@lId1+1
			END

		SET @lId=@lId+1

	END

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

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


GO
CREATE PROCEDURE [sFee].[pOldFeeImportWithNAAdd] 
	@rOldOrgGroupBatchId int,
	@rNewOrgGroupBatchId int,
	@rOldBatchId int,
	@rNewBatchId int,
	@rOldAdmissionCategoryId int,
	@rNewAdmissionCategoryId int,
	@rOldReceiptBookId int,
	@rNewReceiptBookId int,
	@rFeeId int,
	@rOrgId int,
	@rCreatedUserId bigint,
	@rIdNos nvarchar(max)=''
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
BEGIN TRY 

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

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

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

	DECLARE @lCount int
	-- Old Fee Import Temp Table
	CREATE TABLE #TempOldFeeImportWithNA
	(
		[AutoId] int identity,
		[StudentId] bigint NULL ,
		[AcademicId] bigint NULL,
		[PendingAmount] decimal(12,2) NULL,
		[FeeSetupId] int
	)
	CREATE TABLE #TempTotalOldFeeImportWithNA
	(
		[AutoId] int identity,
		[StudentId] bigint NULL ,
		[AcademicId] bigint NULL,
		[TotalPendingAmount] decimal(12,2) NULL
	)
	-- End Old Fee Import Temp Table
	
	INSERT INTO #TempOldFeeImportWithNA
	SELECT 
		SA.StudentId,
		SA.AcademicId,
		ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00) AS PendingAmount,
		FS.Id AS FeeSetupId
		--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 (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 (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 (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
	
	INSERT INTO #TempTotalOldFeeImportWithNA
	SELECT StudentId, AcademicId, SUM(PendingAmount) AS TotalPendingAmount
	FROM #TempOldFeeImportWithNA
	GROUP BY StudentId, AcademicId

	SELECT @lCount = COUNT(AutoId) FROM #TempTotalOldFeeImportWithNA

	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 = @rFeeId 
		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 = @rFeeId  
		AND FS.ReceiptBookId = @rNewReceiptBookId AND (SA1.Code IN (SELECT item from sCommon.fnSplit(@rIdNos, ',')) OR ISNULL(@rIdNos,'')='')

	-- 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 = @rFeeId AND FA.FeeSetupId = FS.Id
		AND FS.ReceiptBookId = @rNewReceiptBookId AND (SA1.Code IN (SELECT item from sCommon.fnSplit(@rIdNos, ',')) OR ISNULL(@rIdNos,'')='')
	
	WHILE (@lCount > 0)
	BEGIN
		DECLARE @lAcademicId bigint = NULL, @lOldAcademicId bigint = NULL
		DECLARE @lStudentId bigint = NULL
		DECLARE @lClassId int = NULL
		DECLARE @lFeeSetupId int = NULL
		DECLARE @lTotalPendingAmount decimal(12,2)
		
		SELECT @lStudentId = StudentId,@lTotalPendingAmount=TotalPendingAmount,@lOldAcademicId=AcademicId FROM #TempTotalOldFeeImportWithNA 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 = @rFeeId 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,
				@lTotalPendingAmount,
				0,
				NULL,
				NULL,
				'Old Year Pending Fee',
				NULL,
				NULL,
				@rCreatedUserId,
				sCommon.fGetDate(),
				NULL,
				NULL
			)

			--DECLARE @lCount1 int = 0
			--SELECT @lCount1 = COUNT(1) FROM #TempOldFeeImportWithNA WHERE StudentId = @lStudentId AND AcademicId = @lOldAcademicId
		
			CREATE TABLE #TempOldFeeSetup
			(
				[AutoId] int identity,
				[StudentId] bigint NULL ,
				[AcademicId] bigint NULL,
				[PendingAmount] decimal(12,2) NULL,
				[FeeSetupId] int
			)

			INSERT INTO #TempOldFeeSetup
			SELECT StudentId,AcademicId,PendingAmount,FeeSetupId FROM #TempOldFeeImportWithNA WHERE StudentId = @lStudentId AND AcademicId = @lOldAcademicId

			DECLARE @lCount1 int = 0
			SELECT @lCount1 = COUNT(1) FROM #TempOldFeeSetup WHERE StudentId = @lStudentId AND AcademicId = @lOldAcademicId

			WHILE(@lCount1 > 0)
			BEGIN
				DECLARE @lPendingAmount decimal(12,2), @lOldFeeSetupId int
				SELECT @lPendingAmount = PendingAmount, @lOldFeeSetupId = FeeSetupId FROM #TempOldFeeSetup WHERE StudentId = @lStudentId AND AcademicId = @lOldAcademicId AND AutoId = @lCount1
				
				IF EXISTS(SELECT 1 FROM sFee.tFeeAllocation WHERE SourceTypeId = 2001 AND SourceId = @lOldAcademicId AND FeeSetupId = @lOldFeeSetupId)
				BEGIN
					-- Update Fee Allocation
					UPDATE sFee.tFeeAllocation
					SET NotApplicableAmount = NotApplicableAmount + @lPendingAmount, Remark = 'Transferred to New Batch', UpdatedUserId = @rCreatedUserId, UpdatedDateTime = sCommon.fGetDate()
					WHERE SourceTypeId = 2001 AND SourceId = @lOldAcademicId AND FeeSetupId = @lOldFeeSetupId
				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,
						@lOldAcademicId,
						@lOldFeeSetupId,
						0,
						0,
						0,
						@lPendingAmount,
						'Transferred to New Batch',
						NULL,
						NULL,
						@rCreatedUserId,
						sCommon.fGetDate(),
						@rCreatedUserId,
						sCommon.fGetDate()
					)
				END
				SET @lCount1 = @lCount1 - 1
			END
		END
		
		SET @lCount = @lCount - 1
	END

	DROP TABLE #TempTotalOldFeeImportWithNA
	DROP TABLE #TempOldFeeImportWithNA
	--DROP TABLE #TempOldFeeSetup
	SELECT 1 AS Result
	COMMIT TRANSACTION
END TRY

BEGIN CATCH 
	DROP TABLE #TempTotalOldFeeImportWithNA
	DROP TABLE #TempOldFeeImportWithNA
	--DROP TABLE #TempOldFeeSetup
	ROLLBACK TRANSACTION
	SELECT -1 AS Result, ERROR_MESSAGE() AS msg
END CATCH	
END
GO
PRINT N'Creating Procedure [sFee].[pOldFeewiseImportWithNAAdd]...';


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

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

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

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

	DECLARE @lCount int

	-- Old Fee Import Temp Table
	CREATE TABLE #TempOldFeeImportWithNA
	(
		[AutoId] int identity,
		[StudentId] bigint NULL ,
		[AcademicId] bigint NULL,
		[PendingAmount] decimal(12,2) NULL,
		[FeeSetupId] int
	)
	CREATE TABLE #TempTotalOldFeeImportWithNA
	(
		[AutoId] int identity,
		[StudentId] bigint NULL ,
		[AcademicId] bigint NULL,
		[TotalPendingAmount] decimal(12,2) NULL
	)
	-- End Old Fee Import Temp Table
	
	
	INSERT INTO #TempOldFeeImportWithNA 
	SELECT 
		SA.StudentId,
		SA.AcademicId,
		ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00) AS PendingAmount,
		FS.Id AS FeeSetupId
		--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

	INSERT INTO #TempTotalOldFeeImportWithNA
	SELECT StudentId, AcademicId, SUM(PendingAmount) AS TotalPendingAmount
	FROM #TempOldFeeImportWithNA
	GROUP BY StudentId, AcademicId
	
	SELECT @lCount = COUNT(AutoId) FROM #TempTotalOldFeeImportWithNA
	
	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 #TempTotalOldFeeImportWithNA 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 #TempTotalOldFeeImportWithNA TOFI ON TOFI.StudentId = SA.StudentId 

	WHILE (@lCount > 0)
	BEGIN
		DECLARE @lAcademicId bigint = NULL, @lOldAcademicId bigint = NULL
		DECLARE @lStudentId bigint = NULL
		DECLARE @lClassId int = NULL
		DECLARE @lFeeSetupId int = NULL
		DECLARE @lTotalPendingAmount decimal(12,2)
		
		SELECT @lStudentId = StudentId,@lTotalPendingAmount=TotalPendingAmount,@lOldAcademicId=AcademicId FROM #TempTotalOldFeeImportWithNA 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,
				@lTotalPendingAmount,
				0,
				NULL,
				NULL,
				'Old Year Pending Fee',
				NULL,
				NULL,
				@rCreatedUserId,
				sCommon.fGetDate(),
				NULL,
				NULL
			)

			--DECLARE @lCount1 int = 0
			--SELECT @lCount1 = COUNT(1) FROM #TempOldFeeImportWithNA WHERE StudentId = @lStudentId AND AcademicId = @lOldAcademicId

			CREATE TABLE #TempOldFeeSetup
			(
				[AutoId] int identity,
				[StudentId] bigint NULL ,
				[AcademicId] bigint NULL,
				[PendingAmount] decimal(12,2) NULL,
				[FeeSetupId] int
			)

			INSERT INTO #TempOldFeeSetup
			SELECT StudentId,AcademicId,PendingAmount,FeeSetupId FROM #TempOldFeeImportWithNA WHERE StudentId = @lStudentId AND AcademicId = @lOldAcademicId

			DECLARE @lCount1 int = 0
			SELECT @lCount1 = COUNT(1) FROM #TempOldFeeSetup WHERE StudentId = @lStudentId AND AcademicId = @lOldAcademicId

			WHILE(@lCount1 > 0)
			BEGIN
		
				DECLARE @lPendingAmount decimal(12,2), @lOldFeeSetupId int
				SELECT @lPendingAmount = PendingAmount, @lOldFeeSetupId = FeeSetupId FROM #TempOldFeeSetup WHERE StudentId = @lStudentId AND AcademicId = @lOldAcademicId AND AutoId = @lCount1

				IF EXISTS(SELECT 1 FROM sFee.tFeeAllocation WHERE SourceTypeId = 2001 AND SourceId = @lOldAcademicId AND FeeSetupId = @lOldFeeSetupId)
				BEGIN
					-- Update Fee Allocation
					UPDATE sFee.tFeeAllocation
					SET NotApplicableAmount = NotApplicableAmount + @lPendingAmount, Remark = 'Transferred to New Batch', UpdatedUserId = @rCreatedUserId, UpdatedDateTime = sCommon.fGetDate()
					WHERE SourceTypeId = 2001 AND SourceId = @lOldAcademicId AND FeeSetupId = @lOldFeeSetupId
				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,
						@lOldAcademicId,
						@lOldFeeSetupId,
						0,
						0,
						0,
						@lPendingAmount,
						'Transferred to New Batch',
						NULL,
						NULL,
						@rCreatedUserId,
						sCommon.fGetDate(),
						@rCreatedUserId,
						sCommon.fGetDate()
					)
				END
				SET @lCount1 = @lCount1 -1
			END
		END
		 
		SET @lCount = @lCount -1
	END
	 
	DROP TABLE #TempTotalOldFeeImportWithNA
	DROP TABLE #TempOldFeeImportWithNA
	--DROP TABLE #TempOldFeeSetup
	SELECT 1 AS Result
	COMMIT TRANSACTION
END TRY

BEGIN CATCH 
	DROP TABLE #TempTotalOldFeeImportWithNA
	DROP TABLE #TempOldFeeImportWithNA
	--DROP TABLE #TempOldFeeSetup
	ROLLBACK TRANSACTION
	SELECT -1 AS Result
END CATCH	
END
GO
PRINT N'Creating Procedure [sLibrary].[pLibraryWiseBookOrderIndexGet]...';


GO

Create PROCEDURE [sLibrary].[pLibraryWiseBookOrderIndexGet]           
@rLibraryId int
WITH EXECUTE AS CALLER          
AS
SET NOCOUNT ON
BEGIN
DECLARE @lNumberString as nvarchar(1000)

SET @lNumberString = (Select ISNULL(max(BM.OrderIndex)+1,1) AS Number FROM sLibrary.tBookMaster BM WHERE BM.LibraryId=@rLibraryId)

SELECT @lNumberString AS Number

END
GO

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


GO
ALTER PROCEDURE [sAccounting].[pBalanceSheet]

	@rBuilder1 nvarchar(max)='',
	@rBuilder2 nvarchar(max)='', 
	@rStartDate Date,
	@rEndDate Date,
	@rOrgGroupId int = 0,
	@rAccountingYearId [int],
	@rAccountId int=0
	
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN

  --SELECT   '' AS OrgTitle,
--	   '' AS SmallAddress1,
--       '' As SmallAddress2,
  --'' AS Builder1,
	 --    '' AS Builder2,
  --       '' AS IncomeGroup,
	 --    '' AS IncomeLedger,
	 --    '' AS Income,
	 --    '' AS ClosingBalance,
	 --    '' AS ExpenseGroup,
	 --    '' AS ExpenseLedger,
	 --    '' AS Expense,
	 --    '' AS OpeningBalance

Declare @lLedgerId int 
Declare @lOpeningBalance Decimal (12,2)
Declare @ltIncome Decimal (12,2)
Declare @ltExpense Decimal (12,2)
Declare @lInIncome Decimal(12,2)
Declare @lInClosing Decimal(12,2)
Declare @lExOpening Decimal(12,2)
Declare @lExExpense Decimal(12,2)
Declare @lGrossProfit Decimal(12,2)
Declare @lGrossLoss Decimal(12,2)
Declare @lCount int
Declare @lLedgerName Nvarchar(150)
Declare @lLedgerGroupName Nvarchar(150)
Declare @lLedgerMainGroupName Nvarchar(150)
DECLARE @1ExpenceCount int
DECLARE @1IncomeCount int
DECLARE @lProfitLostAmount Decimal(12,2)
DECLARE @lOpenigCrAmount Decimal(12,2)
DECLARE @lOpeningDrAmount Decimal(12,2)
Declare @ReportOrgTitle Nvarchar(200)
Declare @SmallAddress1  Nvarchar(200)
Declare	@SmallAddress2 Nvarchar(200)

	Declare @DecimalCount INT
	SELECT @DecimalCount = CASE WHEN CS.Id IS NOT NULL THEN ISNULL(CS.ItemValue,'') ELSE ISNULL(CM.ItemValue,'') END
						  FROM sConfig.tConfigurationMaster CM
						  LEFT JOIN sConfig.tConfigurationSetup CS ON CM.Id = CS.ConfigurationId
						  AND SourceTypeId = 2010 AND SourceId = @rOrgGroupId WHERE CM.Id = 548
		
		SELECT @ReportOrgTitle=ReportOrgTitle ,@SmallAddress1=SmallAddress1, @SmallAddress2= SmallAddress2  
  From sAccounting.tAccountMaster AM Where AM.Id= @rAccountId  
	
        CREATE TABLE #tempUpdateClosingBalance
 		(	Id INT IDENTITY (1, 1),
 			LedgerId int,
 			Temp_Op_Balance decimal(12,2),
 			Closing_Balance decimal(12,2),
 		    Transaction_Balance decimal(12,2)
 		)
 		  	
 		INSERT INTO #tempUpdateClosingBalance (LedgerId,Temp_Op_Balance,Closing_Balance,Transaction_Balance)
		EXEC [sAccounting].[pUpdateClosingBalance] @rStartDate,@rEndDate,@rOrgGroupId,@rAccountingYearId,'',''
				
		
		---- Start Profilt Loss
			CREATE TABLE #TempExpenseGroup1
		(
		   Id INT IDENTITY(1,1),
		   ExpenseGroupId int,
		   ExpenseGroup nvarchar(200),
		   ExpenseLedger nvarchar(200),
		   Expense decimal(22,2) default 0.0,
		   OpeningBalance decimal(22,2)		 
		)
		
		CREATE TABLE #TempIncomeGroup1
		(
		   Id INT IDENTITY(1,1),
		   IncomeGroupId int,
		   IncomeGroup nvarchar(200),
		   IncomeLedger nvarchar(200),
		   Income decimal(22,2) default 0.0,
		   ClosingBalance decimal		 
		)
		
		INSERT INTO #TempExpenseGroup1
		SELECT 
		ISNULL(LG.Id,0)AS ExpenseGroupId,
		ISNULL(LG.Title,'') AS ExpenseGroup,
		ISNULL(L.Title,'') AS ExpenseLedger,	
		ISNULL(SUM(UC.Closing_Balance),0) AS Expense,
	    ISNULL(SUM(L.OpeningBalance),0) AS OpeningBalance
 
	    FROM sAccounting.tLedgerMaster L
		INNER JOIN sAccounting.tLedgerGroupMaster LG ON L.LedgerGroupId = LG.Id
		INNER JOIN sAccounting.tLedgerMainGroupMaster LMG ON LG.LedgerMainGroupId = LMG.Id
		INNER JOIN #tempUpdateClosingBalance UC ON L.Id=UC.LedgerId
		WHERE LMG.ID  = 4 AND L.AccountingYearId = @rAccountingYearId AND LG.AccountingYearId = @rAccountingYearId
		GROUP BY LG.Title,LMG.ID,L.Title,LG.Id	having ISNULL(SUM(UC.Closing_Balance),0) > 0
		Order By LMG.Id	
		
		
		INSERT INTO #TempIncomeGroup1
        SELECT  		
        ISNULL(LG.Id,0)AS IncomeGroupId,
		ISNULL(LG.Title,'') AS IncomeGroup,
		ISNULL(L.Title,'') AS IncomeLedger,
		ISNULL(SUM(UC.Closing_Balance),0) AS Income,
		ISNULL(SUM(UC.Closing_Balance),0) AS ClosingBalance
		FROM sAccounting.tLedgerMaster L 
		INNER JOIN sAccounting.tLedgerGroupMaster LG ON L.LedgerGroupId = LG.Id
		INNER JOIN sAccounting.tLedgerMainGroupMaster LMG ON LG.LedgerMainGroupId = LMG.Id
		INNER JOIN #tempUpdateClosingBalance UC ON L.Id=UC.LedgerId
		WHERE LMG.ID = 3 AND L.AccountingYearId = @rAccountingYearId AND LG.AccountingYearId = @rAccountingYearId
		GROUP BY LG.Title,LMG.ID,L.Title,LG.Id	having ISNULL(SUM(UC.Closing_Balance),0) >  0
		Order By LMG.Id			
		

		SELECT @1ExpenceCount = count(Id) From #TempExpenseGroup1
	    SELECT @1IncomeCount = Count(Id) From #TempIncomeGroup1
		
		
	   If(@1InComeCount > @1ExpenceCount)
	     BEGIN	          
			if @1ExpenceCount =  0 
			begin
				SELECT @lProfitLostAmount  = isnull(SUM(Income),0) 
				FROM #TempIncomeGroup1 IG 
			end
			else
			begin			
				SELECT @lProfitLostAmount  = isnull(SUM(Income),0) - isnull(SUM(Expense),0)
				FROM #TempIncomeGroup1 IG LEFT JOIN #TempExpenseGroup1 EG ON isnull(EG.Id,0) = isnull(IG.Id,0)
			end
	     END
	     ELSE
	     BEGIN
		 if @1ExpenceCount =  0 
			begin
				SELECT @lProfitLostAmount  = isnull(SUM(Income),0) 
				FROM #TempIncomeGroup1 IG 
			end
			else
			begin		
	           SELECT @lProfitLostAmount=isnull((isnull(SUM(Income),0)-isnull(SUM(Expense),0)),0)
	           FROM  #TempExpenseGroup1 EG   LEFT JOIN #TempIncomeGroup1 IG ON isnull(EG.Id,0) = isnull(IG.Id,0)
			end
	     END	
		
		SELECT @lOpenigCrAmount= SUM(OpeningBalance) from sAccounting.tLedgerMaster L 
		WHERE LedgerTypeId = 1 AND L.AccountingYearId = @rAccountingYearId

		SELECT @lOpeningDrAmount= SUM(OpeningBalance) from sAccounting.tLedgerMaster L 
		WHERE LedgerTypeId = 2 AND L.AccountingYearId = @rAccountingYearId
		
	
		---- End Profit Loass
		
		CREATE TABLE #TempExpenseGroup
		(
		   Id INT IDENTITY(1,1),
		   ExpenseGroupId int,
		   ExpenseGroup nvarchar(200),
		   ExpenseLedger nvarchar(200),
		   Expense decimal(22,2),
		   OpeningBalance decimal(22,2)		 
		)
		
		CREATE TABLE #TempIncomeGroup
		(
		   Id INT IDENTITY(1,1),
		   IncomeGroupId int,
		   IncomeGroup nvarchar(200),
		   IncomeLedger nvarchar(200),
		   Income decimal(22,2),
		   ClosingBalance decimal		 
		)
		
		
		
		
		
		
		INSERT INTO #TempIncomeGroup
		SELECT 
		ISNULL(LG.Id,0)AS ExpenseGroupId,
		ISNULL(LG.Title,'') AS ExpenseGroup,
		ISNULL(L.Title,'') AS ExpenseLedger,	
		ISNULL(SUM(UC.Closing_Balance),0) AS Expense,
	    ISNULL(SUM(L.OpeningBalance),0) AS OpeningBalance
	    
	    FROM sAccounting.tLedgerMaster L
		INNER JOIN sAccounting.tLedgerGroupMaster LG ON L.LedgerGroupId = LG.Id
		INNER JOIN sAccounting.tLedgerMainGroupMaster LMG ON LG.LedgerMainGroupId = LMG.Id
		INNER JOIN #tempUpdateClosingBalance UC ON L.Id=UC.LedgerId
		WHERE LMG.ID  = 2 AND L.AccountingYearId = @rAccountingYearId AND LG.AccountingYearId = @rAccountingYearId
		GROUP BY LG.Title,LMG.ID,L.Title,LG.Id	having ISNULL(SUM(UC.Closing_Balance),0) > 0 
		Order By LG.Title,LMG.Id	
		
		
		INSERT INTO #TempExpenseGroup
        SELECT  	
        ISNULL(LG.Id,0)AS IncomeGroupId,	
		ISNULL(LG.Title,'') AS IncomeGroup,
		ISNULL(L.Title,'') AS IncomeLedger,
		ISNULL(SUM(UC.Closing_Balance),0) AS Income,
		ISNULL(SUM(UC.Closing_Balance),0) AS ClosingBalance
		FROM sAccounting.tLedgerMaster L 
		INNER JOIN sAccounting.tLedgerGroupMaster LG ON L.LedgerGroupId = LG.Id
		INNER JOIN sAccounting.tLedgerMainGroupMaster LMG ON LG.LedgerMainGroupId = LMG.Id
		INNER JOIN #tempUpdateClosingBalance UC ON L.Id=UC.LedgerId
		WHERE LMG.ID = 1 AND L.AccountingYearId = @rAccountingYearId AND LG.AccountingYearId = @rAccountingYearId
		GROUP BY LG.Title,LMG.ID,L.Title,LG.Id	having ISNULL(SUM(UC.Closing_Balance),0) >  0
		Order By LG.Title,LMG.Id	
		
		

	   SELECT @1ExpenceCount = count(Id) From #TempExpenseGroup
	   SELECT @1IncomeCount = Count(Id) From #TempIncomeGroup
		--- profit loss   
		IF  @lProfitLostAmount  is null 
		BEGIN
			SET @lProfitLostAmount  = 0
		END
	   IF @lProfitLostAmount > 0
	   BEGIN
			UPDATE TG SET Income = OpeningBalance 
			FROM #TempIncomeGroup TG INNER JOIN sAccounting.tLedgerMaster LM
			ON TG.IncomeLedger = LM.Title COLLATE DATABASE_DEFAULT  AND LM.Code = '4' AND LM.AccountingYearId = @rAccountingYearId
			INSERT INTO #TempIncomeGroup (IncomeGroup,IncomeLedger,Income,ClosingBalance) VALUES ('','Net Proft',@lProfitLostAmount,@lProfitLostAmount)
			--WHERE IncomeLedger = (SELECT TITLE FROM sAccounting.tLedgerMaster WHERE Code='4' AND
			--AccountingYearId=@rAccountingYearId)
	   END
	   ELSE
	   BEGIN
	  
	   	    UPDATE TG SET Expense = Isnull(lm.OpeningBalance,0) 			 
			FROM #TempExpenseGroup TG INNER JOIN sAccounting.tLedgerMaster LM
			ON  LM.Code = '4' AND LM.AccountingYearId = @rAccountingYearId	AND   TG.ExpenseLedger = LM.Title  	COLLATE DATABASE_DEFAULT 	
			INSERT INTO #TempExpenseGroup (ExpenseGroup,ExpenseLedger,Expense,OpeningBalance) VALUES ('','Net Loss',@lProfitLostAmount,@lProfitLostAmount)

			--UPDATE #TempExpenseGroup SET Expense =@lProfitLostAmount 
			--WHERE ExpenseLedger = (SELECT TITLE FROM sAccounting.tLedgerMaster WHERE Code='4' AND
			--AccountingYearId=@rAccountingYearId)
	   END
	   
	   -- Close Profit loss
		-- Opening Difference
  		IF (@lOpenigCrAmount > @lOpeningDrAmount )
		BEGIN
			INSERT INTO #TempExpenseGroup (ExpenseGroupId,ExpenseGroup,ExpenseLedger,Expense,OpeningBalance) VALUES (0,'','Diff In Opening Balance',@lOpenigCrAmount - @lOpeningDrAmount,0)
		END
		ELSE
		BEGIN
			INSERT INTO #TempIncomeGroup (IncomeGroupId,IncomeGroup,IncomeLedger,Income,ClosingBalance) VALUES (0,'','Diff In Opening Balance',@lOpeningDrAmount-@lOpenigCrAmount,0)
		END
		--end Opening Deifference
	   
	   
	   If(@1InComeCount > @1ExpenceCount)
	     BEGIN	   	       
	           SELECT @ReportOrgTitle  AS OrgTitle,
	             @SmallAddress1 AS SmallAddress1,
				 @SmallAddress2 AS SmallAddress2, 
	             @rBuilder1 AS Builder1
				,@rBuilder2 AS Builder2, 
				   ISNULL(IncomeGroupId,0) AS IncomeGroupId,
	               ISNULL(IncomeGroup,'') AS IncomeGroup, 
	               ISNULL(IncomeLedger,'') AS IncomeLedger,
	               ISNULL(ClosingBalance,0) AS ClosingBalance,
	               ([sAccounting].[fDecimalValueGet] (isnull(Income,0), @DecimalCount)) AS Income,	   
				   ISNULL(ExpenseGroupId,0) AS ExpenseGroupId,           
	               ISNULL(ExpenseGroup,'') AS ExpenseGroup,
	               ISNULL(ExpenseLedger,'') AS ExpenseLedger,
				   ISNULL(OpeningBalance,0) AS OpeningBalance,	          
				   ([sAccounting].[fDecimalValueGet] (ISNULL(Expense,0.00), @DecimalCount)) AS Expense
	           FROM #TempIncomeGroup IG LEFT JOIN #TempExpenseGroup EG ON EG.Id = IG.Id	  
	             
	     END
	     ELSE
	     BEGIN
	         SELECT Isnull(@ReportOrgTitle,'')  AS OrgTitle,
	             isnull(@SmallAddress1,'') AS SmallAddress1,
				 isnull(@SmallAddress2,'') AS SmallAddress2, 
					 @rBuilder1 AS Builder1
					,@rBuilder2 AS Builder2, 
				   ISNULL(IncomeGroupId,0) AS IncomeGroupId,           
	               ISNULL(IncomeGroup,'') AS IncomeGroup, 
	               ISNULL(IncomeLedger,'') AS IncomeLedger,
	               ISNULL(ClosingBalance,0) AS ClosingBalance,
	               ([sAccounting].[fDecimalValueGet] (ISNULL(Income,0), @DecimalCount)) AS Income,
	               ISNULL(ExpenseGroupId,0) AS ExpenseGroupId,           
	               ExpenseGroup AS ExpenseGroup,
	               ExpenseLedger,
				   ISNULL(OpeningBalance,0) AS OpeningBalance,
				   ([sAccounting].[fDecimalValueGet] (ISNULL(Expense,0), @DecimalCount)) AS Expense        
	           FROM  #TempExpenseGroup EG   LEFT JOIN #TempIncomeGroup IG ON EG.Id = IG.Id		        
	          
	     END	
	     
	     DROP TABLE #TempExpenseGroup
	     DROP TABLE #TempIncomeGroup
		
		
		
--SELECT  
		
--		ISNULL(CASE WHEN LMG.ID=2 THEN LG.Title END,'') AS IncomeGroup,
--		ISNULL(CASE WHEN LMG.ID=2 THEN L.Title END,'') AS IncomeLedger,
--		ISNULL(SUM(L.OpeningBalance),0) AS OpeningBalance,
--		ISNULL(CASE WHEN LMG.ID=2 THEN SUM(UC.Closing_Balance) END,0) AS Income,
--		ISNULL(CASE WHEN LMG.ID=1  THEN LG.Title END,'') AS ExpenseGroup,
--		ISNULL(CASE WHEN LMG.ID=1  THEN L.Title END,'') AS ExpenseLedger,
--		ISNULL(CASE WHEN LMG.ID=1 THEN SUM(UC.Closing_Balance) END,0) AS Expense,
--		ISNULL(SUM(UC.Closing_Balance),0) AS ClosingBalance
--		FROM sAccounting.tLedgerMaster L 
--		INNER JOIN #tempUpdateClosingBalance UC ON L.Id=UC.LedgerId
--		INNER JOIN sAccounting.tLedgerGroupMaster LG ON L.LedgerGroupId = LG.Id 
--		INNER JOIN sAccounting.tLedgerMainGroupMaster LMG ON LG.LedgerMainGroupId = LMG.Id AND LMG.Id in (1,2)		
--		GROUP BY LG.Title,LMG.ID
--		,L.Title	
--		Order By LMG.Id	
END
GO
PRINT N'Altering Procedure [sAccounting].[pCashBankBook]...';


GO



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

BEGIN

--SELECT '' AS OrgTitle,
--	   '' AS SmallAddress1,
--       '' As SmallAddress2,
--	   '' As Builder1,
--	   '' As Builder2,
--	   '' As Id,
--	   '' As LedgerId,
--	   '' As LedgerName,
--	   '' As OpBalance,
--	   '' As CrBalance,
--	   '' As DrBalance,
--	   '' As ClBalance,
--       '' As LedgerGroupId




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

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

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


GO


 
ALTER PROCEDURE [sAccounting].[pDayBook]

	@rBuilder1 nvarchar(max)='',
	@rBuilder2 nvarchar(max)='', 
	@rStartDate Date,
	@rEndDate Date,
	@rOrgGroupId int = 0,
	@rAccountingYearId [int],
	@rLedgerId [int],
	  @rAccountId int=0
	

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN  
   
    --DECLARE @1OpeningBalance DECIMAL(22,2) --Commented for mantis : 32211 by Nilesh
    --DECLARE @1ClosingBalance DECIMAl(22,2) --Commented for mantis : 32211 by Nilesh
	DECLARE @1OpeningBalance DECIMAL(22,5) --Added for mantis : 32211 by Nilesh
    DECLARE @1ClosingBalance DECIMAl(22,5) --Added for mantis : 32211 by Nilesh

	/*****************Added for mantis 32211 by Nilesh************************/
	Declare @DecimalCount INT
	SELECT @DecimalCount = CASE WHEN CS.Id IS NOT NULL THEN ISNULL(CS.ItemValue,'') ELSE ISNULL(CM.ItemValue,'') END
						  FROM sConfig.tConfigurationMaster CM
						  LEFT JOIN sConfig.tConfigurationSetup CS ON CM.Id = CS.ConfigurationId
						  AND SourceTypeId = 2010 AND SourceId = @rOrgGroupId WHERE CM.Id = 548
   
   IF(@rLedgerId > 0)
    BEGIN   
    
    CREATE TABLE #tempUpdateClosingBalance
	(	
	    Id INT IDENTITY (1, 1),
		LedgerId int,
		--Temp_Op_Balance decimal(12,2), --Commented for mantis : 32211 by Nilesh
		--Closing_Balance decimal(12,2), --Commented for mantis : 32211 by Nilesh
		--Transaction_Balance decimal(12,2),--Commented for mantis : 32211 by Nilesh
		Temp_Op_Balance decimal(20,5), --Added for mantis : 32211 by Nilesh
		Closing_Balance decimal(20,5), --Added for mantis : 32211 by Nilesh
		Transaction_Balance decimal(20,5) --Added for mantis : 32211 by Nilesh
	) 
	
	INSERT INTO #tempUpdateClosingBalance (LedgerId,Temp_Op_Balance,Closing_Balance,Transaction_Balance)
		EXEC [sAccounting].[pUpdateClosingBalance] @rStartDate,@rEndDate,@rOrgGroupId,@rAccountingYearId,@rLedgerId,''
		
	SELECT @1OpeningBalance = Temp_Op_Balance,@1ClosingBalance = Closing_Balance FROM #tempUpdateClosingBalance WHERE LedgerId = @rLedgerId
    
    END
    	

	SELECT 
	@rBuilder1 AS Builder1
	,@rBuilder2 AS Builder2,
	T.Id AS TransactionId,
	T.TransactionDate,
	T.VoucherNumber,
	L.TITLE,
	VTM.Title As VoucherType,
	T.Narration,
	--ISNULL(CASE WHEN TD.TransactionTypeId = 1 THEN -1 * ISNULL(SUM(TD.AMOUNT),0) END,0) AS CREDIT, --Commented for mantis : 32211 by Nilesh
	--ISNULL(CASE WHEN TD.TransactionTypeId = 2 THEN ISNULL(SUM(TD.AMOUNT),0) END,0) AS DEBIT, --Commented for mantis : 32211 by Nilesh
	([sAccounting].[fDecimalValueGet] ((ISNULL(CASE WHEN TD.TransactionTypeId = 1 THEN -1 * ISNULL(SUM(TD.AMOUNT),0) END,0)),@DecimalCount)) CREDIT, --Added for mantis : 32211 by Nilesh
	([sAccounting].[fDecimalValueGet] ((ISNULL(CASE WHEN TD.TransactionTypeId = 2 THEN ISNULL(SUM(TD.AMOUNT),0) END,0)),@DecimalCount)) DEBIT, --Added for mantis : 32211 by Nilesh
	CASE WHEN TD.TransactionTypeId = 1 THEN 'CREDIT' ELSE 'DEBIT' END AS TOBY, 
	--ISNULL(@1OpeningBalance,0) AS OpeningBalance, --Commented for mantis : 32211 by Nilesh
	--ISNULL(@1ClosingBalance,0) AS ClosingBalance, --Commented for mantis : 32211 by Nilesh
	([sAccounting].[fDecimalValueGet] ((ISNULL(@1OpeningBalance,0)),@DecimalCount)) OpeningBalance, --Added for mantis : 32211 by Nilesh
	([sAccounting].[fDecimalValueGet] ((ISNULL(@1ClosingBalance,0)),@DecimalCount)) ClosingBalance, --Added for mantis : 32211 by Nilesh
	AM.ReportOrgTitle As OrgTitle,
			AM.SmallAddress1 AS SmallAddress1,
			AM.SmallAddress2 AS SmallAddress2
	
	from sAccounting.tTransaction T 
	INNER JOIN sAccounting.tTransactionDetail TD ON TD.TransactionId=T.Id 
	INNER JOIN sAccounting.tLedgerMaster L ON L.Id=TD.LedgerId
	INNER JOIN sAccounting.tVoucherTypeMaster VTM ON VTM.Id=T.VoucherTypeId
	INNER JOIN sAccounting.tLedgerGroupMaster LGM ON LGM.Id = L.LedgerGroupId
	LEFT JOIN sAccounting.tAccountMaster AM ON AM.Id=T.AccountId
	
	WHERE (T.TransactionDate >= @rStartDate)  AND
	(T.TransactionDate <= @rEndDate) AND 
	(LGM.OrgGroupId = @rOrgGroupId OR @rOrgGroupId=0) AND
	(LGM.AccountingYearId=@rAccountingYearId or @rAccountingYearId=0) AND	
	(TD.LedgerId =  @rLedgerId  OR @rLedgerId  =0) AND
	T.AccountingYearID=@rAccountingYearId AND
	 L.AccountingYearId = @rAccountingYearId
	 AND ((L.CODE <> '2' AND VTM.Title ='Contra Voucher' And TransactionTypeId <> 1)
	 Or (L.CODE <> '2' AND VTM.Title ='Payment Voucher' And TransactionTypeId <> 1)
	 Or (L.CODE <> '2' AND VTM.Title ='Receipt Voucher' And TransactionTypeId <> 2)
	 Or (L.CODE <> '2' AND VTM.Title ='Journal Voucher' And TransactionTypeId <> 2)	 
	 or (L.CODE = '2' AND VTM.Title ='Contra Voucher' And TransactionTypeId <> 1)
	 Or (L.CODE = '2' AND VTM.Title ='Payment Voucher' And TransactionTypeId <> 1)
	 Or (L.CODE = '2' AND VTM.Title ='Receipt Voucher' And TransactionTypeId <> 2)
	 Or (L.CODE = '2' AND VTM.Title ='Journal Voucher' And TransactionTypeId <> 2)
	 )

	AND (T.AccountId=@rAccountId OR @rAccountId=0 )  
	 
	GROUP BY 	T.TransactionDate,TD.TransactionTypeId,T.VoucherNumber,T.Id,
				L.Title,VTM.Title,T.Narration,AM.ReportOrgTitle,AM.SmallAddress1,AM.SmallAddress2
END
GO
PRINT N'Altering Procedure [sAccounting].[pLedgerBook]...';


GO
ALTER PROCEDURE [sAccounting].[pLedgerBook]
	
	@rBuilder1 nvarchar(max)='',
	@rBuilder2 nvarchar(max)='', 
	@rStartDate Date,
	@rEndDate Date,
	@rOrgGroupId int = 0,
	@rAccountingYearId [int],
	@rLedgerId [int],
	@rLedgerGroupId [int],
	@rAccountId  int=0
	

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON 
BEGIN

    --  SELECT '' AS Builder1,
			 --'' AS Builder2,
    --         '' AS TransactionId,
			 --'' AS CREDIT,
			 --'' AS DEBIT,
			 --'' AS LedgerId,
			 --'' AS TransactionDate,
			 --'' AS VoucherNumber,
			 --'' AS Narration,
			 --'' AS VoucherType,
			 --'' AS TITLE,
			 --'' AS OpeningBalance,
			 --'' AS ClosingBalance,
			 -- '' AS ChequeNo
      
    
    DECLARE @1OpeningBalance DECIMAL(22,2)
    DECLARE @1ClosingBalance DECIMAl(22,2)
	Declare @DecimalCount INT
	SELECT @DecimalCount = CASE WHEN CS.Id IS NOT NULL THEN ISNULL(CS.ItemValue,'') ELSE ISNULL(CM.ItemValue,'') END
						  FROM sConfig.tConfigurationMaster CM
						  LEFT JOIN sConfig.tConfigurationSetup CS ON CM.Id = CS.ConfigurationId
						  AND SourceTypeId = 2010 AND SourceId = @rOrgGroupId WHERE CM.Id = 548
     
	CREATE TABLE #tempUpdateClosingBalance
	(	
	    Id INT IDENTITY (1, 1),
		LedgerId int,
		Temp_Op_Balance decimal(12,2),
		Closing_Balance decimal(12,2),
		Transaction_Balance decimal(12,2)	    
	) 
	
	INSERT INTO #tempUpdateClosingBalance (LedgerId,Temp_Op_Balance,Closing_Balance,Transaction_Balance)
	EXEC [sAccounting].[pUpdateClosingBalance] @rStartDate,@rEndDate,@rOrgGroupId,@rAccountingYearId,@rLedgerId,''
		
	SELECT @1OpeningBalance = Temp_Op_Balance,@1ClosingBalance = Closing_Balance
	FROM #tempUpdateClosingBalance WHERE LedgerId = @rLedgerId

	SELECT 
	L.LedgerTypeId,
	 @rBuilder1 AS Builder1
	,@rBuilder2 AS Builder2,
	T.Id AS TransactionId,	
	--ISNULL(CASE WHEN TD.TransactionTypeId = 1 THEN -1 * SUM(TD.AMOUNT) END,0) AS CREDIT,
	--ISNULL(CASE WHEN TD.TransactionTypeId = 2 THEN SUM(TD.AMOUNT) END,0) AS DEBIT,

		--Isnull((select ABS(sum(td1.Amount)) from
	--sAccounting.tTransaction T1 
	--INNER JOIN sAccounting.tTransactionDetail TD1 ON TD1.TransactionId=T1.Id AND T.Id=T1.Id
	--Inner join sAccounting.tLedgerMaster L ON L.Id=TD1.LedgerId AND L.AccountingYearId = T1.AccountingYearId
	--WHERE (TD1.LedgerId =@rLedgerId ) AND T1.AccountingYearId = @rAccountingYearId
	--AND TransactionTypeId = 2),0) AS Credit,
	([sAccounting].[fDecimalValueGet] (Isnull((select ABS(sum(td1.Amount)) from
	sAccounting.tTransaction T1 
	INNER JOIN sAccounting.tTransactionDetail TD1 ON TD1.TransactionId=T1.Id AND T.Id=T1.Id
	Inner join sAccounting.tLedgerMaster L ON L.Id=TD1.LedgerId AND L.AccountingYearId = T1.AccountingYearId
	WHERE (TD1.LedgerId =@rLedgerId ) AND T1.AccountingYearId = @rAccountingYearId
	AND TransactionTypeId = 2),0),@DecimalCount)) AS Credit,

	--Isnull((select ABS(sum(td1.Amount)) from
	--sAccounting.tTransaction T1 
	--INNER JOIN sAccounting.tTransactionDetail TD1 ON TD1.TransactionId=T1.Id AND T.Id=T1.Id
	--Inner join sAccounting.tLedgerMaster L ON L.Id=TD1.LedgerId AND L.AccountingYearId = T1.AccountingYearId
	--WHERE (TD1.LedgerId =@rLedgerId ) AND T1.AccountingYearId = @rAccountingYearId
	--AND TransactionTypeId = 1),0) AS Debit,
	([sAccounting].[fDecimalValueGet] (Isnull((select ABS(sum(td1.Amount)) from
	sAccounting.tTransaction T1 
	INNER JOIN sAccounting.tTransactionDetail TD1 ON TD1.TransactionId=T1.Id AND T.Id=T1.Id
	Inner join sAccounting.tLedgerMaster L ON L.Id=TD1.LedgerId AND L.AccountingYearId = T1.AccountingYearId
	WHERE (TD1.LedgerId =@rLedgerId ) AND T1.AccountingYearId = @rAccountingYearId
	AND TransactionTypeId = 1),0),@DecimalCount)) AS Debit,

	--CAse When L.LedgerTypeId = 1 then 
 --  -1 * Isnull((select sum(TD1.Amount)  from
	--sAccounting.tTransaction T1 
	--INNER JOIN sAccounting.tTransactionDetail TD1 ON TD1.TransactionId=T1.Id AND T1.Id=T.Id 
	--AND TD1.TransactionTypeId = 1 
	--WHERE (L.LedgerTypeId = 1 ANd TD1.LedgerId =TD.LedgerId) OR (L.LedgerTypeId = 2 AND TD1.LedgerId =@rLedgerId )
	--GROUP BY 	TD1.LedgerId,T1.TransactionDate,T1.VoucherNumber,T1.Id,
	--			TD1.TransactionTypeId,T1.VoucherTypeId,T1.Narration,
	--			T1.ChequeNo
	--),0) else 0 end as Credit ,
	--CAse When L.LedgerTypeId = 1 then 0 end as debit,

	--Case When L.LedgerTypeId = 2 then 
	---1 * isnull((select sum(TD1.Amount)  from
	--sAccounting.tTransaction T1 
	--INNER JOIN sAccounting.tTransactionDetail TD1 ON TD1.TransactionId=T1.Id AND T1.Id=T.Id  
	--AND TD1.TransactionTypeId = 2
	--WHERE (L.LedgerTypeId = 1 ANd TD1.LedgerId =TD.LedgerId) 
	-- OR(L.LedgerTypeId = 2 AND TD1.LedgerId =@rLedgerId )
	--GROUP BY 	TD1.LedgerId,T1.TransactionDate,T1.VoucherNumber,T1.Id,
	--			TD1.TransactionTypeId,T1.VoucherTypeId,T1.Narration,
	--			T1.ChequeNo
	--),0) else 0 end as Debit,
	--CAse When L.LedgerTypeId = 2 then 0 end as Credit,


	TD.LedgerId,T.TransactionDate,T.VoucherNumber,T.Narration,
	VTM.Title As VoucherType,
	T.VoucherTypeId,
	--LEFT(VTM.Title,2) As VoucherType
	L.TITLE,
	([sAccounting].[fDecimalValueGet] (ISNULL(@1OpeningBalance,0),@DecimalCount)) AS OpeningBalance,	--change by dhruvik
	([sAccounting].[fDecimalValueGet] (ISNULL(@1ClosingBalance,0),@DecimalCount)) AS ClosingBalance,	--change by dhruvik
		AM.ReportOrgTitle As OrgTitle,
			AM.SmallAddress1 AS SmallAddress1,
			AM.SmallAddress2 AS SmallAddress2,
			T.ChequeNo
	
	from sAccounting.tTransaction T 
	INNER JOIN sAccounting.tTransactionDetail TD ON TD.TransactionId=T.Id AND (TD.LedgerId <> @rLedgerId)
	INNER JOIN sAccounting.tLedgerMaster L ON L.Id=TD.LedgerId
	INNER JOIN sAccounting.tVoucherTypeMaster VTM ON VTM.Id=T.VoucherTypeId
	INNER JOIN sAccounting.tLedgerGroupMaster LGM ON LGM.Id = L.LedgerGroupId
	INNER JOIN sAccounting.tAccountMaster AM ON AM.Id=T.AccountId
	
	WHERE (T.TransactionDate >= @rStartDate)  AND
	(T.TransactionDate <= @rEndDate) AND 
	(LGM.OrgGroupId = @rOrgGroupId OR @rOrgGroupId=0) AND
	(LGM.AccountingYearId=@rAccountingYearId or @rAccountingYearId=0) AND	
	(T.AccountingYearId=@rAccountingYearId OR @rAccountingYearId = 0)
	 AND
	(L.LedgerGroupId = @rLedgerGroupId or @rLedgerGroupId = 0) AND L.AccountingYearId=@rAccountingYearId
	AND @rLedgerId IN (SELECT LedgerId FROM sAccounting.tTransactionDetail TD1 WHERE TD1.TRANSACTIONID=T.ID AND TD1.TRansactionTypeID <> TD.TRansactionTypeID)-- L.LedgerTypeId )
	AND (T.AccountId=@rAccountId OR @rAccountId=0)  
	GROUP BY 	TD.LedgerId,T.TransactionDate,T.VoucherNumber,T.Id,
				TD.TransactionTypeId,L.Title,T.VoucherTypeId,VTM.Title,T.Narration,AM.ReportOrgTitle,AM.SmallAddress1,AM.SmallAddress2,
				T.ChequeNo,L.LedgerTypeId
   order by T.TransactionDate,T.VoucherNumber
END
GO
PRINT N'Altering Procedure [sAccounting].[pProfitAndLoss]...';


GO



ALTER PROCEDURE [sAccounting].[pProfitAndLoss]

	@rBuilder1 nvarchar(max)='',
	@rBuilder2 nvarchar(max)='', 
	@rStartDate Date,
	@rEndDate Date,
	@rOrgGroupId int = 0,
	@rAccountingYearId [int],
	@rAccountId int=0
	
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
--SELECT '' AS OrgTitle,
--	   '' AS SmallAddress1,
--       '' As SmallAddress2,
--'' AS Builder1,
--	   '' AS Builder2,
--         '' AS IncomeGroup,
--	     '' AS IncomeLedger,
--	     '' AS Income,
--	     '' AS ClosingBalance,
--	     '' AS ExpenseGroup,
--	     '' AS ExpenseLedger,
--	     '' AS Expense,
--	     '' AS OpeningBalance
	    

Declare @lLedgerId int 
Declare @lOpeningBalance Decimal (12,2)
Declare @ltIncome Decimal (12,2)
Declare @ltExpense Decimal (12,2)
Declare @lInIncome Decimal(12,2)
Declare @lInClosing Decimal(12,2)
Declare @lExOpening Decimal(12,2)
Declare @lExExpense Decimal(12,2)
Declare @lGrossProfit Decimal(12,2)
Declare @lGrossLoss Decimal(12,2)
Declare @lCount int
Declare @lLedgerName Nvarchar(150)
Declare @lLedgerGroupName Nvarchar(150)
Declare @lLedgerMainGroupName Nvarchar(150) 
DECLARE @1ExpenceCount int
DECLARE @1IncomeCount int
Declare @ReportOrgTitle Nvarchar(200)
Declare @SmallAddress1  Nvarchar(200)
Declare	@SmallAddress2 Nvarchar(200)

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

	SELECT @ReportOrgTitle=ReportOrgTitle ,@SmallAddress1=SmallAddress1, @SmallAddress2= SmallAddress2  
	From sAccounting.tAccountMaster AM Where AM.Id= @rAccountId  
  
  
    CREATE TABLE #tempUpdateClosingBalance
 		(	Id INT IDENTITY (1, 1),
 			LedgerId int,
 			Temp_Op_Balance decimal(25,5),
 			Closing_Balance decimal(25,5),
 		    Transaction_Balance decimal(25,5)
 		)  	
 		INSERT INTO #tempUpdateClosingBalance (LedgerId,Temp_Op_Balance,Closing_Balance,Transaction_Balance)
		EXEC [sAccounting].[pUpdateClosingBalance] @rStartDate,@rEndDate,@rOrgGroupId,@rAccountingYearId,'',''
		
		CREATE TABLE #TempExpenseGroup
		(
		   Id INT IDENTITY(1,1),
		   ExpenseGroupId int,
		   ExpenseGroup nvarchar(200),
		   ExpenseLedger nvarchar(200),
		   Expense decimal(25,5),
		   OpeningBalance decimal(25,5)	 
		)
		
		CREATE TABLE #TempIncomeGroup
		(
		   Id INT IDENTITY(1,1),
		   IncomeGroupId int,
		   IncomeGroup nvarchar(200),
		   IncomeLedger nvarchar(200),
		   Income decimal(25,5),
		   ClosingBalance decimal		 
		)
		
		INSERT INTO #TempExpenseGroup
		SELECT 
        Isnull(Lg.Id,0) as ExpenseGroupId,		
		ISNULL(LG.Title,'') AS ExpenseGroup,
		ISNULL(L.Title,'') AS ExpenseLedger,	
		ISNULL(SUM(UC.Closing_Balance),0) AS Expense,
	    ISNULL(SUM(L.OpeningBalance),0) AS OpeningBalance
 
	    FROM sAccounting.tLedgerMaster L
		INNER JOIN sAccounting.tLedgerGroupMaster LG ON L.LedgerGroupId = LG.Id
		INNER JOIN sAccounting.tLedgerMainGroupMaster LMG ON LG.LedgerMainGroupId = LMG.Id
		INNER JOIN #tempUpdateClosingBalance UC ON L.Id=UC.LedgerId
		WHERE LMG.ID  = 4 AND L.AccountingYearId = @rAccountingYearId AND LG.AccountingYearId = @rAccountingYearId
		GROUP BY LG.Title,LMG.ID,L.Title,LG.Id	having ISNULL(SUM(UC.Closing_Balance),0) > 0
		Order By LMG.Id	
		
		
		INSERT INTO #TempIncomeGroup
        SELECT  
        Isnull(Lg.Id,0) as IncomeGroupId,		
		ISNULL(LG.Title,'') AS IncomeGroup,
		ISNULL(L.Title,'') AS IncomeLedger,
		ISNULL(SUM(UC.Closing_Balance),0) AS Income,
		ISNULL(SUM(UC.Closing_Balance),0) AS ClosingBalance
		FROM sAccounting.tLedgerMaster L 
		INNER JOIN sAccounting.tLedgerGroupMaster LG ON L.LedgerGroupId = LG.Id
		INNER JOIN sAccounting.tLedgerMainGroupMaster LMG ON LG.LedgerMainGroupId = LMG.Id
		INNER JOIN #tempUpdateClosingBalance UC ON L.Id=UC.LedgerId
		WHERE LMG.ID = 3 AND L.AccountingYearId = @rAccountingYearId AND LG.AccountingYearId = @rAccountingYearId
		GROUP BY LG.Title,LMG.ID,L.Title,LG.Id having ISNULL(SUM(UC.Closing_Balance),0) > 0	
		Order By LMG.Id			
	      
	     
	   SELECT @1ExpenceCount = count(Id) From #TempExpenseGroup
	   SELECT @1IncomeCount = Count(Id) From #TempIncomeGroup
	   If(@1InComeCount >= @1ExpenceCount)
	     BEGIN		    
	           SELECT @ReportOrgTitle  AS OrgTitle,
				@SmallAddress1 AS SmallAddress1,
				@SmallAddress2 AS SmallAddress2, 
	             @rBuilder1 AS Builder1
				,@rBuilder2 AS Builder2,
	               Isnull(IncomeGroupId,0) AS IncomeGroupId,
	               IncomeGroup, 
	               IncomeLedger,
	               ClosingBalance,
	               ([sAccounting].[fDecimalValueGet] (Income,@DecimalCount)) AS Income,	--change by dhruvik
	               ISNULL(ExpenseGroupId,0) AS ExpenseGroupId,
	               ISNULL(ExpenseGroup,'') AS ExpenseGroup,
	               ISNULL(ExpenseLedger,'') AS ExpenseLedger,
				   ISNULL(OpeningBalance,0) AS OpeningBalance,	          
				   ([sAccounting].[fDecimalValueGet] (ISNULL(Expense,0.00),@DecimalCount)) AS Expense	--change by dhruvik
	           FROM #TempIncomeGroup IG 
	           LEFT JOIN #TempExpenseGroup EG ON EG.Id = IG.Id	  
	          
	     END
	     ELSE
	     BEGIN
	    
	     
	         SELECT @ReportOrgTitle  AS OrgTitle,
	             @SmallAddress1 AS SmallAddress1,
				 @SmallAddress2 AS SmallAddress2, 
				 @rBuilder1 AS Builder1
				,@rBuilder2 AS Builder2, 
				   Isnull(IncomeGroupId,0) AS IncomeGroupId,
	               ISNULL(IncomeGroup,'') AS IncomeGroup, 
	               ISNULL(IncomeLedger,'') AS IncomeLedger,
	               ISNULL(ClosingBalance,0) AS ClosingBalance,
	               ([sAccounting].[fDecimalValueGet] (ISNULL(Income,0),@DecimalCount)) AS Income,	--change by dhruvik
	               Isnull(ExpenseGroupId,0) AS ExpenseGroupId,
	               ExpenseGroup AS ExpenseGroup,
	               ExpenseLedger,
				   OpeningBalance,
				   ([sAccounting].[fDecimalValueGet] (Expense,@DecimalCount)) AS Expense	--change by dhruvik
	           FROM  #TempExpenseGroup EG  LEFT JOIN #TempIncomeGroup IG ON EG.Id = IG.Id	
	                  
	     END	
	     
	     DROP TABLE #TempExpenseGroup
	     DROP TABLE #TempIncomeGroup
		
END
GO
PRINT N'Altering Procedure [sAccounting].[pRptProfitAndLossGet]...';


GO
ALTER PROCEDURE [sAccounting].[pRptProfitAndLossGet]

	@rBuilder1 nvarchar(max)='',
	@rBuilder2 nvarchar(max)='', 
	@rStartDate Date,
	@rEndDate Date,
	@rOrgGroupId int = 0,
	@rAccountingYearId [int],
	@rAccountId int=0
	
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

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

	Declare @lLedgerId int 
	Declare @lOpeningBalance Decimal (12,2)
	Declare @ltIncome Decimal (12,2)
	Declare @ltExpense Decimal (12,2)
	Declare @lInIncome Decimal(12,2)
	Declare @lInClosing Decimal(12,2)
	Declare @lExOpening Decimal(12,2)
	Declare @lExExpense Decimal(12,2)
	Declare @lGrossProfit Decimal(12,2)
	Declare @lGrossLoss Decimal(12,2)
	Declare @lCount int
	Declare @lLedgerName Nvarchar(150)
	Declare @lLedgerGroupName Nvarchar(150)
	Declare @lLedgerMainGroupName Nvarchar(150) 
	DECLARE @1ExpenceCount int
	DECLARE @1IncomeCount int
	Declare @ReportOrgTitle Nvarchar(200)
	Declare @SmallAddress1  Nvarchar(200)
	Declare	@SmallAddress2 Nvarchar(200)

	SELECT @ReportOrgTitle=ReportOrgTitle, @SmallAddress1=SmallAddress1, @SmallAddress2= SmallAddress2  
	FROM sAccounting.tAccountMaster AM 
	WHERE AM.Id= @rAccountId  
  
	CREATE TABLE #tempUpdateClosingBalance
 	(	
		Id INT IDENTITY (1, 1),
 		LedgerId int,
 		Temp_Op_Balance decimal(12,2),
 		Closing_Balance decimal(12,2),
 		Transaction_Balance decimal(12,2)
 	)  	
 	INSERT INTO #tempUpdateClosingBalance 
	(LedgerId,Temp_Op_Balance,Closing_Balance,Transaction_Balance)
	EXEC [sAccounting].[pUpdateClosingBalance] @rStartDate,@rEndDate,@rOrgGroupId,@rAccountingYearId,'',''
		
	--SELECT * FROM #tempUpdateClosingBalance

	CREATE TABLE #TempExpenseGroup
	(
	   Id INT IDENTITY(1,1),
	   ExpenseGroupId int,
	   ExpenseGroup nvarchar(200),
	   ExpenseLedger nvarchar(200),
	   Expense decimal(22,2),
	   OpeningBalance decimal(22,2),
	   ExpenseTransactionBalance decimal(12,2) 
	)
		
	CREATE TABLE #TempIncomeGroup
	(
	   Id INT IDENTITY(1,1),
	   IncomeGroupId int,
	   IncomeGroup nvarchar(200),
	   IncomeLedger nvarchar(200),
	   Income decimal(22,2),
	   ClosingBalance decimal,
	   IncomeTransactionBalance decimal(12,2)
	)
		
	INSERT INTO #TempExpenseGroup
	SELECT 
        ISNULL(Lg.Id,0) as ExpenseGroupId,		
		ISNULL(LG.Title,'') AS ExpenseGroup,
		ISNULL(L.Title,'') AS ExpenseLedger,	
		ISNULL(SUM(UC.Closing_Balance),0) AS Expense,
	    ISNULL(SUM(L.OpeningBalance),0) AS OpeningBalance,
		ISNULL(SUM(UC.Transaction_Balance),0) AS ExpenseTransactionBalance
	FROM 
		sAccounting.tLedgerMaster L
		INNER JOIN sAccounting.tLedgerGroupMaster LG ON L.LedgerGroupId = LG.Id
		INNER JOIN sAccounting.tLedgerMainGroupMaster LMG ON LG.LedgerMainGroupId = LMG.Id
		INNER JOIN #tempUpdateClosingBalance UC ON L.Id=UC.LedgerId
	WHERE LMG.ID  = 4 AND L.AccountingYearId = @rAccountingYearId AND LG.AccountingYearId = @rAccountingYearId
	GROUP BY LG.Title,LMG.ID,L.Title,LG.Id	HAVING ISNULL(SUM(UC.Closing_Balance),0) > 0
	ORDER BY LMG.Id	
		
		
	INSERT INTO #TempIncomeGroup
    SELECT  
        ISNULL(Lg.Id,0) as IncomeGroupId,		
		ISNULL(LG.Title,'') AS IncomeGroup,
		ISNULL(L.Title,'') AS IncomeLedger,
		ISNULL(SUM(UC.Closing_Balance),0) AS Income,
		ISNULL(SUM(UC.Closing_Balance),0) AS ClosingBalance,
		ISNULL(SUM(UC.Transaction_Balance),0) AS IncomeTransactionBalance
	FROM sAccounting.tLedgerMaster L 
		INNER JOIN sAccounting.tLedgerGroupMaster LG ON L.LedgerGroupId = LG.Id
		INNER JOIN sAccounting.tLedgerMainGroupMaster LMG ON LG.LedgerMainGroupId = LMG.Id
		INNER JOIN #tempUpdateClosingBalance UC ON L.Id=UC.LedgerId
	WHERE LMG.ID = 3 AND L.AccountingYearId = @rAccountingYearId AND LG.AccountingYearId = @rAccountingYearId
	GROUP BY LG.Title,LMG.ID,L.Title,LG.Id HAVING ISNULL(SUM(UC.Closing_Balance),0) > 0	
	ORDER BY LMG.Id	
	      
	     
	SELECT @1ExpenceCount = count(Id) From #TempExpenseGroup
	SELECT @1IncomeCount = Count(Id) From #TempIncomeGroup

	IF(@1InComeCount >= @1ExpenceCount)
	BEGIN		    
		SELECT 
			@ReportOrgTitle  AS OrgTitle,
			@SmallAddress1 AS SmallAddress1,
			@SmallAddress2 AS SmallAddress2, 
	        @rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			ISNULL(IncomeGroupId,0) AS IncomeGroupId,
	        IncomeGroup, 
	        IncomeLedger,
	        [sAccounting].[fDecimalValueGet](ClosingBalance,@DecimalCount)AS ClosingBalance,
	        [sAccounting].[fDecimalValueGet](Income,@DecimalCount) AS Income,
	        ISNULL(ExpenseGroupId,0) AS ExpenseGroupId,
	        ISNULL(ExpenseGroup,'') AS ExpenseGroup,
	        ISNULL(ExpenseLedger,'') AS ExpenseLedger,
			[sAccounting].[fDecimalValueGet](ISNULL(OpeningBalance,0),@DecimalCount) AS OpeningBalance,	          
			[sAccounting].[fDecimalValueGet](ISNULL(Expense,0.00),@DecimalCount) AS Expense,
			[sAccounting].[fDecimalValueGet](ISNULL(IG.IncomeTransactionBalance,0.00),@DecimalCount) AS IncomeTransactionBalance,
			[sAccounting].[fDecimalValueGet](ISNULL(EG.ExpenseTransactionBalance,0.00),@DecimalCount) AS ExpenseTransactionBalance
		FROM #TempIncomeGroup IG 
			LEFT JOIN #TempExpenseGroup EG ON EG.Id = IG.Id	  
	          
	END
	ELSE
	BEGIN
	    SELECT 
			@ReportOrgTitle  AS OrgTitle,
	        @SmallAddress1 AS SmallAddress1,
			@SmallAddress2 AS SmallAddress2, 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2, 
			ISNULL(IncomeGroupId,0) AS IncomeGroupId,
	        ISNULL(IncomeGroup,'') AS IncomeGroup, 
	        ISNULL(IncomeLedger,'') AS IncomeLedger,
	        [sAccounting].[fDecimalValueGet](ISNULL(ClosingBalance,0),@DecimalCount) AS ClosingBalance,
	        [sAccounting].[fDecimalValueGet](ISNULL(Income,0),@DecimalCount) AS Income,
	        ISNULL(ExpenseGroupId,0) AS ExpenseGroupId,
	        ExpenseGroup AS ExpenseGroup,
	        ExpenseLedger,
			[sAccounting].[fDecimalValueGet](OpeningBalance,@DecimalCount) AS OpeningBalance,
			[sAccounting].[fDecimalValueGet](Expense,@DecimalCount) AS Expense,
			[sAccounting].[fDecimalValueGet](ISNULL(EG.ExpenseTransactionBalance,0.00),@DecimalCount) AS ExpenseTransactionBalance,
			[sAccounting].[fDecimalValueGet](ISNULL(IG.IncomeTransactionBalance,0.00),@DecimalCount) AS IncomeTransactionBalance
	    FROM #TempExpenseGroup EG  
			LEFT JOIN #TempIncomeGroup IG ON EG.Id = IG.Id	
	 END	
	     
	 DROP TABLE #TempExpenseGroup
	 DROP TABLE #TempIncomeGroup
		

--SELECT
--	'' AS OrgTitle,
--	'' AS SmallAddress1,
--	'' AS SmallAddress2,
--	'' AS Builder1,
--	'' AS Builder2,
--	0 AS IncomeGroupId,
--	'' AS IncomeGroup,
--	'' AS IncomeLedger,
--	0.00 AS ClosingBalance,
--	0.00 AS Income,
--	0 AS ExpenseGroupId,
--	'' AS ExpenseGroup,
--	'' AS ExpenseLedger,
--	0.00 AS OpeningBalance,
--	0.00 AS Expense,
--	0.00 AS ExpenseTransactionBalance,
--	0.00 AS IncomeTransactionBalance
	    
END
GO
PRINT N'Altering Procedure [sAccounting].[pRptReceiptsAndPaymentsGet]...';


GO



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

BEGIN

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

DECLARE @lIsReportClient bit=0

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


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

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

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

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


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

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

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

----For Report

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

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

--FROM 		
--		sAccounting.tTransaction T 
--		INNER JOIN sAccounting.tTransactionDetail TD ON TD.TransactionId=T.Id --AND (TD.LedgerId <> @rLedgerId)
--		INNER JOIN sAccounting.tLedgerMaster L ON L.Id=TD.LedgerId
--		INNER JOIN sAccounting.tVoucherTypeMaster VTM ON VTM.Id=T.VoucherTypeId
--		INNER JOIN sAccounting.tLedgerGroupMaster LGM ON LGM.Id = L.LedgerGroupId
--		INNER JOIN sAccounting.tAccountMaster AM ON AM.Id=T.AccountId
--END
GO
PRINT N'Altering Procedure [sAccounting].[pRptReceiptsAndPaymentsWithDetailsGet]...';


GO

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

BEGIN

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

DECLARE @lIsReportClient bit=0

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


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

DECLARE @2Credit int
DECLARE @2Debit int

DECLARE @Credit_Closing int
DECLARE @Debit_Closing int

SET @Debit_Closing=Isnull((select ABS(sum(td1.Amount)) from sAccounting.tTransaction T1 INNER JOIN sAccounting.tTransactionDetail TD1 ON TD1.TransactionId=T1.Id 
			 INNER JOIN sAccounting.tLedgerMaster L ON L.Id=TD1.LedgerId 
			 INNER JOIN sAccounting.tVoucherTypeMaster VTM ON VTM.Id=T1.VoucherTypeId
			 WHERE T1.AccountingYearId = @rAccountingYearId AND ((L.CODE <> '2' AND VTM.Title ='Contra Voucher' And TransactionTypeId <> 1)
	 Or (L.CODE <> '2' AND VTM.Title ='Payment Voucher' And TransactionTypeId <> 1)
	 Or (L.CODE <> '2' AND VTM.Title ='Receipt Voucher' And TransactionTypeId <> 2)
	 Or (L.CODE <> '2' AND VTM.Title ='Journal Voucher' And (@lIsReportClient = 1 OR TransactionTypeId <> 2))	 
	 or (L.CODE = '2' AND VTM.Title ='Contra Voucher' And TransactionTypeId <> 1)
	 Or (L.CODE = '2' AND VTM.Title ='Payment Voucher' And TransactionTypeId <> 1)
	 Or (L.CODE = '2' AND VTM.Title ='Receipt Voucher' And TransactionTypeId <> 2)
	 Or (L.CODE = '2' AND VTM.Title ='Journal Voucher' And (@lIsReportClient = 1 OR TransactionTypeId <> 2))
	 ) 
		AND (T1.TransactionDate >= @rStartDate OR ISNULL(@rStartDate,'')='') AND (T1.TransactionDate <= @rEndDate OR ISNULL(@rEndDate,'')='')),0)


SET @Credit_Closing=Isnull((select ABS(sum(td1.Amount)) from sAccounting.tTransaction T1 INNER JOIN sAccounting.tTransactionDetail TD1 ON TD1.TransactionId=T1.Id
			INNER JOIN sAccounting.tLedgerMaster L ON L.Id=TD1.LedgerId 
			 INNER JOIN sAccounting.tVoucherTypeMaster VTM ON VTM.Id=T1.VoucherTypeId
			 WHERE T1.AccountingYearId = @rAccountingYearId AND ((L.CODE <> '2' AND VTM.Title ='Contra Voucher' And TransactionTypeId <> 1)
	 Or (L.CODE <> '2' AND VTM.Title ='Payment Voucher' And TransactionTypeId <> 1)
	 Or (L.CODE <> '2' AND VTM.Title ='Receipt Voucher' And TransactionTypeId <> 2)
	 Or (L.CODE <> '2' AND VTM.Title ='Journal Voucher' And (@lIsReportClient = 1 OR TransactionTypeId <> 2))	 
	 or (L.CODE = '2' AND VTM.Title ='Contra Voucher' And TransactionTypeId <> 1)
	 Or (L.CODE = '2' AND VTM.Title ='Payment Voucher' And TransactionTypeId <> 1)
	 Or (L.CODE = '2' AND VTM.Title ='Receipt Voucher' And TransactionTypeId <> 2)
	 Or (L.CODE = '2' AND VTM.Title ='Journal Voucher' And (@lIsReportClient = 1 OR TransactionTypeId <> 2))
	 ) 
		AND (T1.TransactionDate >= @rStartDate OR ISNULL(@rStartDate,'')='') AND (T1.TransactionDate <= @rEndDate OR ISNULL(@rEndDate,'')='')),0)


SELECT * INTO #DayBookTemp
FROM (SELECT 
	@rBuilder1 AS Builder1
	,@rBuilder2 AS Builder2,
	T.Id AS TransactionId,
	T.TransactionDate,
	T.VoucherNumber,
	L.TITLE,
	VTM.Title As VoucherType,
	T.Narration,
	ISNULL(CASE WHEN TD.TransactionTypeId = 1 THEN -1 * ISNULL(SUM(TD.AMOUNT),0) END,0) AS CREDIT,
	ISNULL(CASE WHEN TD.TransactionTypeId = 2 THEN ISNULL(SUM(TD.AMOUNT),0) END,0) AS DEBIT,
	CASE WHEN TD.TransactionTypeId = 1 THEN 'CREDIT' ELSE 'DEBIT' END AS TOBY,
	ISNULL(@1OpeningBalance,0) AS OpeningBalance,
	ISNULL(@1ClosingBalance,0) AS ClosingBalance,
	AM.ReportOrgTitle As OrgTitle,
			AM.SmallAddress1 AS SmallAddress1,
			AM.SmallAddress2 AS SmallAddress2
	
	from sAccounting.tTransaction T 
	INNER JOIN sAccounting.tTransactionDetail TD ON TD.TransactionId=T.Id 
	INNER JOIN sAccounting.tLedgerMaster L ON L.Id=TD.LedgerId
	INNER JOIN sAccounting.tVoucherTypeMaster VTM ON VTM.Id=T.VoucherTypeId
	INNER JOIN sAccounting.tLedgerGroupMaster LGM ON LGM.Id = L.LedgerGroupId
	LEFT JOIN sAccounting.tAccountMaster AM ON AM.Id=T.AccountId
	
	WHERE (T.TransactionDate >= '1900-01-01')  AND
	(T.TransactionDate < @rEndDate) AND 
	(LGM.OrgGroupId = @rOrgGroupId OR @rOrgGroupId=0) AND
	(LGM.AccountingYearId=@rAccountingYearId or @rAccountingYearId=0) AND		
	T.AccountingYearID=@rAccountingYearId AND
	 L.AccountingYearId = @rAccountingYearId
	 AND ((L.CODE <> '2' AND VTM.Title ='Contra Voucher' And TransactionTypeId <> 1)
	 Or (L.CODE <> '2' AND VTM.Title ='Payment Voucher' And TransactionTypeId <> 1)
	 Or (L.CODE <> '2' AND VTM.Title ='Receipt Voucher' And TransactionTypeId <> 2)
	 Or (L.CODE <> '2' AND VTM.Title ='Journal Voucher' And (@lIsReportClient = 1 OR TransactionTypeId <> 2))	 
	 or (L.CODE = '2' AND VTM.Title ='Contra Voucher' And TransactionTypeId <> 1)
	 Or (L.CODE = '2' AND VTM.Title ='Payment Voucher' And TransactionTypeId <> 1)
	 Or (L.CODE = '2' AND VTM.Title ='Receipt Voucher' And TransactionTypeId <> 2)
	 Or (L.CODE = '2' AND VTM.Title ='Journal Voucher' And (@lIsReportClient = 1 OR TransactionTypeId <> 2))
	 )

	AND (T.AccountId=@rAccountId OR @rAccountId=0 )  
	 
	GROUP BY 	T.TransactionDate,TD.TransactionTypeId,T.VoucherNumber,T.Id,
				L.Title,VTM.Title,T.Narration,AM.ReportOrgTitle,AM.SmallAddress1,AM.SmallAddress2) P

--SELECT * FROM #DayBookTemp

SET @1Debit = (SELECT SUM(DEBIT) FROM #DayBookTemp)
SET @1Credit = (SELECT SUM(CREDIT) FROM #DayBookTemp)

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


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

	SELECT  
	L.LedgerTypeId,
	LGM.Title AS LedgerGroupTitle,
	L.Title AS LedgerTitle,
	@rBuilder1 AS Builder1,
	@rBuilder2 AS Builder2,
	T.Id AS TransactionId,	
	[sAccounting].[fDecimalValueGet](ISNULL(CASE WHEN TD.TransactionTypeId = 1 THEN -1 * ISNULL(SUM(TD.AMOUNT),0) END,0),@DecimalCount) AS Credit,
	[sAccounting].[fDecimalValueGet](ISNULL(CASE WHEN TD.TransactionTypeId = 2 THEN ISNULL(SUM(TD.AMOUNT),0) END,0),@DecimalCount) AS Debit,			

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

----For Report

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

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

--FROM 		
--		sAccounting.tTransaction T 
--		INNER JOIN sAccounting.tTransactionDetail TD ON TD.TransactionId=T.Id AND (TD.LedgerId <> @rLedgerId)
--		INNER JOIN sAccounting.tLedgerMaster L ON L.Id=TD.LedgerId
--		INNER JOIN sAccounting.tVoucherTypeMaster VTM ON VTM.Id=T.VoucherTypeId
--		INNER JOIN sAccounting.tLedgerGroupMaster LGM ON LGM.Id = L.LedgerGroupId
--		INNER JOIN sAccounting.tAccountMaster AM ON AM.Id=T.AccountId
--END
GO
PRINT N'Altering Procedure [sAccounting].[pTrialBalance]...';


GO
ALTER PROCEDURE [sAccounting].[pTrialBalance]

	@rBuilder1 nvarchar(max)='',
	@rBuilder2 nvarchar(max)='', 
	@rStartDate Date,
	@rEndDate Date,
	@rOrgGroupId int = 0,
	@rAccountingYearId [int],
	@rOrderBy smallint,
	@rLedgerGroupId int,
	@rAccountId int=0
	
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN

--SELECT '' AS OrgTitle,
--	   '' AS SmallAddress1,
--       '' As SmallAddress2,
-- '' AS Builder1,
--	   '' AS Builder2,
--       '' As Id,
--	   '' As LedgerId,
--	   '' As LedgerName,
--	   '' As LedgerGroup,
--	   '' As LedgerMainGroup,
--	   '' As LedgerTypeId,
--	   '' As CreditBalance,
--	   '' As DebitBalance,
--	   '' As OpeningBalance,
--	   '' As ClosingBalance

Declare @lLedgerId int 
Declare @lCashOpBalance Decimal (12,2)
Declare @lOpeningBalance Decimal (12,2)
Declare @lCreditBalance Decimal (12,2)
Declare @lDebitBalance Decimal (12,2)
Declare @lLOpeningBalance Decimal(12,2)
Declare @lCount int
Declare @lLedgerTypeId int
Declare @lLedgerName Nvarchar(150)
Declare @lLedgerGroupName Nvarchar(150)
Declare @lLedgerMainGroupName Nvarchar(150)
Declare @ReportOrgTitle Nvarchar(200)
Declare @SmallAddress1  Nvarchar(200)
Declare	@SmallAddress2 Nvarchar(200)
	
	--change by dhruvik
	Declare @DecimalCount INT
	SELECT @DecimalCount = CASE WHEN CS.Id IS NOT NULL THEN ISNULL(CS.ItemValue,'') ELSE ISNULL(CM.ItemValue,'') END
						  FROM sConfig.tConfigurationMaster CM
						  LEFT JOIN sConfig.tConfigurationSetup CS ON CM.Id = CS.ConfigurationId
						  AND SourceTypeId = 2010 AND SourceId = @rOrgGroupId WHERE CM.Id = 548


	SELECT @ReportOrgTitle=ReportOrgTitle ,@SmallAddress1=SmallAddress1, @SmallAddress2= SmallAddress2  
	From sAccounting.tAccountMaster AM Where AM.Id= @rAccountId  
	
    CREATE TABLE #tempUpdateClosingBalance
 		(	Id INT IDENTITY (1, 1),
 			LedgerId int,
 			Temp_Op_Balance decimal(12,2),
 			Closing_Balance decimal(12,2),
 			Transaction_Balance decimal(12,2) 			
 		)
 		
	   CREATE TABLE #tTempTrialBalance
 		(	Id INT IDENTITY (1,1),
 			LedgerId int,
 			LedgerName varchar(100),
 			LedgerGroup varchar(100),
			LedgerMainGroup Varchar(100), 			
 			LedgerTypeId int,
 			CreditBalance decimal(12,2),
 			DebitBalance decimal(12,2),
 			OpeningBalance decimal(12,2),
 			ClosingBalance Decimal(12,2)
 		) 
 		INSERT INTO #tTempTrialBalance    
		SELECT L.Id, L.Title,LG.Title AS GName, LGM.Title AS MGName ,L.LedgerTypeId,0,0,L.OpeningBalance,0		
		FROM sAccounting.tLedgerMaster L INNER JOIN sAccounting.tLedgerGroupMaster LG on LG.Id=L.LedgerGroupId
		INNER JOIN sAccounting.tLedgerMainGroupMaster LGM ON LGM.Id = LG.LEDGERMAINGROUPID
		And LG.OrgGroupId= @rOrgGroupId AND L.AccountingYearId=@rAccountingYearId AND LG.AccountingYearId = @rAccountingYearId
		AND (LG.Id = @rLedgerGroupId or @rLedgerGroupId=0 )
	  
	--select * from #tTemptrialBalance
	 
	SELECT @lCount =  COUNT(Id) FROM #tTempTrialBalance
	WHILE (@lCount > 0)
	BEGIN
		SELECT @lLedgerId=LedgerId,@lCreditBalance=CreditBalance,@lDebitBalance=DebitBalance,
		@lLedgerName=LedgerName,@lLedgerTypeId=LedgerTypeId,@lOpeningBalance=OpeningBalance,@lLedgerGroupName=LedgerGroup,
		@lLedgerMainGroupName=LedgerMainGroup	FROM #tTempTrialBalance WHERE Id= @lCount
	
		INSERT INTO #tempUpdateClosingBalance (LedgerId,Temp_Op_Balance,Closing_Balance,Transaction_Balance)
		EXEC [sAccounting].[pUpdateClosingBalance] @rStartDate,@rEndDate,@rOrgGroupId,@rAccountingYearId,@lLedgerId,''
		SET @lCount = @lCount - 1
	END	
	
	--select *  from #tempUpdateClosingBalance UC INNER JOIN #tTemptrialBalance TB ON TB.LedgerId = UC.LedgerId
	
	IF @rOrderBy = 0 
	BEGIN
		SELECT @ReportOrgTitle  AS OrgTitle,
	@SmallAddress1 AS SmallAddress1,
	@SmallAddress2 AS SmallAddress2,  @rBuilder1 AS Builder1
	    ,@rBuilder2 AS Builder2,TB.LedgerId,TB.LedgerName,TB.LedgerGroup,TB.LedgerMainGroup,
		--change by dhruvik
		--T.Temp_Op_Balance AS OpeningBalance,
		([sAccounting].[fDecimalValueGet] (T.Temp_Op_Balance, @DecimalCount)) AS OpeningBalance,
		--ISNULL(CASE WHEN T.Transaction_Balance < 0 THEN -1 * T.Transaction_Balance END,0) AS CreditBalance,
		--ISNULL(CASE WHEN T.Transaction_Balance >= 0 THEN T.Transaction_Balance ENd,0) AS DebitBalance,
		
		--ISNULL(CASE WHEN TB.LedgerTypeId =1 THEN 1 * T.Transaction_Balance END,0) AS CreditBalance,
		([sAccounting].[fDecimalValueGet] (ISNULL(CASE WHEN TB.LedgerTypeId =1 THEN 1 * T.Transaction_Balance END,0),@DecimalCount)) AS CreditBalance,
		--ISNULL(CASE WHEN TB.LedgerTypeId =2 THEN 1 * T.Transaction_Balance ENd,0) AS DebitBalance,
		([sAccounting].[fDecimalValueGet] (ISNULL(CASE WHEN TB.LedgerTypeId =2 THEN 1 * T.Transaction_Balance ENd,0),@DecimalCount)) AS DebitBalance,
		
		--T.Closing_Balance AS ClosingBalance
		([sAccounting].[fDecimalValueGet] (T.Closing_Balance,@DecimalCount)) AS ClosingBalance
		FROM #tempUpdateClosingBalance T 
		INNER JOIN #tTempTrialBalance TB on T.LedgerId=TB.LedgerId ORDER BY TB.LedgerName
	END
	ELSE
	BEGIN
		SELECT @ReportOrgTitle  AS OrgTitle,
	@SmallAddress1 AS SmallAddress1,
	@SmallAddress2 AS SmallAddress2,  @rBuilder1 AS Builder1
	    ,@rBuilder2 AS Builder2,0 AS LedgerId,'' AS LedgerName,TB.LedgerGroup,TB.LedgerMainGroup,
		--change by dhruvik
		--Sum(T.Temp_Op_Balance) AS OpeningBalance,
		([sAccounting].[fDecimalValueGet] (Sum(T.Temp_Op_Balance),@DecimalCount)) AS OpeningBalance,
	 --   Sum(ISNULL(CASE WHEN T.Transaction_Balance < 0 THEN -1 * T.Transaction_Balance END,0)) AS CreditBalance,
		--Sum(ISNULL(CASE WHEN T.Transaction_Balance >= 0 THEN T.Transaction_Balance ENd,0)) AS DebitBalance,
		--Sum(ISNULL(CASE WHEN TB.LedgerTypeId =1 THEN 1 * T.Transaction_Balance END,0)) AS CreditBalance,
		([sAccounting].[fDecimalValueGet] (Sum(ISNULL(CASE WHEN TB.LedgerTypeId =1 THEN 1 * T.Transaction_Balance END,0)),@DecimalCount)) AS CreditBalance,
		--Sum(ISNULL(CASE WHEN TB.LedgerTypeId =2 THEN 1 * T.Transaction_Balance ENd,0)) AS DebitBalance,
		([sAccounting].[fDecimalValueGet] (Sum(ISNULL(CASE WHEN TB.LedgerTypeId =2 THEN 1 * T.Transaction_Balance ENd,0)),@DecimalCount)) AS DebitBalance,
		--Sum(T.Closing_Balance) AS ClosingBalance
		([sAccounting].[fDecimalValueGet] (Sum(T.Closing_Balance),@DecimalCount)) AS ClosingBalance
		FROM #tempUpdateClosingBalance T inner join #tTempTrialBalance TB on T.LedgerId=TB.LedgerId GRoup BY TB.LedgerGroup,TB.LedgerMainGroup
	END
	
	DROP Table #tempUpdateClosingBalance
	
END
GO

PRINT N'Update complete.';


GO


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

