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


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


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


GO
PRINT N'Creating [sFrontOffice].[tVisitorTypeMaster]...';


GO
CREATE TABLE [sFrontOffice].[tVisitorTypeMaster] (
    [Id]              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,
    [OrgGroupId]      SMALLINT       NOT NULL
);


GO
PRINT N'Creating PK_tVisitorTypeMaster...';


GO
ALTER TABLE [sFrontOffice].[tVisitorTypeMaster]
    ADD CONSTRAINT [PK_tVisitorTypeMaster] PRIMARY KEY CLUSTERED ([Id] ASC) WITH (FILLFACTOR = 85, ALLOW_PAGE_LOCKS = ON, ALLOW_ROW_LOCKS = ON, PAD_INDEX = OFF, IGNORE_DUP_KEY = OFF, STATISTICS_NORECOMPUTE = OFF);


GO



PRINT N'Altering [sAcademic].[pDailyStatusGet]...';


GO

 
ALTER PROCEDURE [sAcademic].[pDailyStatusGet]

     @rSearchDate datetime,
     @rOrgId smallint,
     @rBatchId int,     
     @rYear smallint,
     @rMonth smallint,
     @rDate smallint,
	 @rAttendanceTypeId int=1,
	 @rAttendanceStatusId int=0
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 	
	 
 

	SELECT 				
			vCD.ClassDivisionName,
			ISNULL(EM.FirstName+' '+ EM.LastName,'') AS ClassTeacherName,
			[sAttendance].[fWeekHOffGet](@rYear,@rMonth,@rDate,@rBatchId,A.ClassId,A.DivisionId,'',@rOrgId) AS WeekOffStatus, 
			CASE WHEN COUNT(SR.AcademicId)=0 THEN CASE WHEN (Select [sCommon].[fCountAbsentStudent](A.DivisionId,  @rBatchId,@rSearchDate,@rAttendanceTypeId,0)) =0 THEN 'Pending' ELSE 'Complete' END ELSE 'Complete' END AS PresentStatus, 
            sCommon.fCountDivisionStudent(A.DivisionId,@rBatchId) AS TotalCount, 
            [sCommon].[fCountAbsentStudent](A.DivisionId,@rBatchId,@rSearchDate,@rAttendanceTypeId,1) AS PresentCount,
            [sCommon].[fCountAbsentStudent](A.DivisionId,@rBatchId,@rSearchDate,@rAttendanceTypeId,0) AS AbsentCount,
			ISNULL(MAX(SR.UpdatedDateTime),MAX(SR.CreatedDateTime)) as UpdatedDateTime,
			--ISNULL((SELECT TOP 1 U.DisplayTitle FROM sSecurity.tUser U WHERE U.Id = ISNULL(SR.UpdatedUserId,SR.CreatedUserId)),'') AS UserName
			[sCommon].[fGetUserNameforDailyStatus](A.DivisionId,@rSearchDate,@rAttendanceTypeId)AS UserName
    FROM 
			sStudent.tAcademic A 
			INNER JOIN sStudent.tStudentMaster SM ON SM.Id=A.StudentId AND SM.StatusId=1 
			INNER JOIN sSetup.vClassDivision vCD ON vCD.ClassId=A.ClassId 
            AND vCD.DivisionId=A.DivisionId AND A.OrgId=vCD.OrgId AND A.OrgId=@rOrgId AND A.BatchId=@rBatchId AND vCD.IsObsolete=0 
            INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = vCD.DivisionId 
            LEFT JOIN sHrm.tEmployeeMaster EM ON EM.Id = DM.InchargeEmployeeId AND ISNULL(EM.IsOtherUser,0) = 0
            LEFT JOIN sAttendance.tStudentRegister SR ON A.Id = SR.AcademicId AND SR.AttendanceDate=@rSearchDate 
            AND SR.AttendanceTypeId = @rAttendanceTypeId 
			AND SR.IsPresent=1 
					
            GROUP BY A.DivisionId,A.BatchId,vCD.ClassDivisionName,vCD.OrderIndex,EM.FirstName,EM.LastName,SM.StatusId,A.ClassId
			--,SR.UpdatedUserId,SR.CreatedUserId
			Having (@rAttendanceStatusId=1 AND (COUNT(SR.AcademicId)=0 And (Select [sCommon].[fCountAbsentStudent](A.DivisionId,  @rBatchId,@rSearchDate,@rAttendanceTypeId,0)) =0) )
				OR (@rAttendanceStatusId=2 and (COUNT(SR.AcademicId)<>0 OR (Select [sCommon].[fCountAbsentStudent](A.DivisionId,  @rBatchId,@rSearchDate,@rAttendanceTypeId,0))<>0) )
				 OR ( @rAttendanceStatusId=0)	
            ORDER BY vCD.OrderIndex
END
GO
PRINT N'Altering [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  
	 
  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
		ELSE 0 END) DebitAmount,
		(CASE WHEN TD.Amount < 0 THEN -1 * TD.Amount
		ELSE 0 END) CreditAmount,
		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.CreatedUserId = 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 [sActivity].[pRptActivityWiseStudentListGet]...';


GO
ALTER PROCEDURE [sActivity].[pRptActivityWiseStudentListGet]

		   	
	       @rBuilder1 nvarchar(max)='',
	       @rBuilder2 nvarchar(max)='', 	
           @rClassId int,
           @rDivisionId int,
           @rActivityTypeId int,
           @rActivityId int,
           @rOrgId int,
           @rStatusId int,
           @rOrgGroupId int=0,
           @rBatchId int=0
          
AS
SET NOCOUNT ON

BEGIN

IF (@rOrgId = 0)
BEGIN
	 
	SELECT  
		@rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,	
		SA.AcademicId,
		ISNULL(SA.RollNo,0)AS RollNo,
		SA.Code,
		SA.Name,
		SA.ClassId,
		SA.DivisionId,
		SA.DivisionOrder,
		SA.ClassName+'-'+SA.DivisionName AS ClassName,	
		A.Id AS ActivityId,	
		A.Title AS ActivityName,
		ATM.Id AS ActivityTypeId,		
		ATM.Title AS ActivityTypeName,
		OM.Id AS OrgId,
		OM.DisplayTitle AS OrgName,
		SA.StudentId,
		ISNULL(CONVERT(VARCHAR(50),A.FromDate,103),'') AS FromDate,
		ISNULL(CONVERT(VARCHAR(50),A.ToDate,103),'') AS ToDate,
		A.Remark AS Remark,
		AP.Remark AS ActivityRemark
		
	FROM 
		sStudent.vStudentAcademic SA		
		INNER JOIN sActivity.tActivityParticipant AP ON AP.SourceId=SA.StudentId AND AP.SourceTypeId=2003 
		INNER JOIN sActivity.tActivity A ON A.Id=AP.ActivityId AND A.BatchId=SA.BatchId
		INNER JOIN sActivity.tActivityTypeMaster ATM ON ATM.Id = A.ActivityTypeId	
		INNER JOIN sSetup.tOrganizationMaster OM ON SA.OrgId = OM.Id
		INNER JOIN sSetup.tOrgGroupMaster OGM ON OM.OrgGroupId = OGM.Id	
	WHERE 
		(SA.ClassId=@rClassId OR @rClassId=0)
		AND (SA.DivisionId=@rDivisionId OR @rDivisionId=0)
		AND (ATM.Id=@rActivityTypeId OR ISNULL(@rActivityTypeId,0)=0)
		AND (AP.ActivityId=@rActivityId OR ISNULL(@rActivityId,0)=0)
		AND (SA.StatusId=@rStatusId OR @rStatusId=0)
		AND (SA.OrgId=@rOrgId OR @rOrgId=0)
		AND (ISNULL(SA.BatchStatusId,1)=1)
		AND (OGM.Id = @rOrgGroupId OR @rOrgGroupId = 0)		
		AND SA.IsActiveBatch = 1
	Order By SA.ClassId

END
ELSE
BEGIN
	DECLARE @lOrgGroupBatchId int 
	Select @lOrgGroupBatchId = OrgGroupBatchId from [sSetup].[tBatchMaster] Where Id = @rBatchId
	Select @rBatchId = Id from [sSetup].[tBatchMaster] Where OrgId = @rOrgId AND OrgGroupBatchId = @lOrgGroupBatchId

	SELECT  
		@rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,	
		SA.AcademicId,
		ISNULL(SA.RollNo,0)AS RollNo,
		SA.Code,
		SA.Name,
		SA.ClassId,
		SA.DivisionId,
		SA.DivisionOrder,
		SA.ClassName+'-'+SA.DivisionName AS ClassName,	
		A.Id AS ActivityId,	
		A.Title AS ActivityName,
		ATM.Id AS ActivityTypeId,		
		ATM.Title AS ActivityTypeName,
		OM.Id AS OrgId,
		OM.DisplayTitle AS OrgName,
		SA.StudentId,
		ISNULL(CONVERT(VARCHAR(50),A.FromDate,103),'') AS FromDate,
		ISNULL(CONVERT(VARCHAR(50),A.ToDate,103),'') AS ToDate,
		A.Remark AS Remark,
		AP.Remark AS ActivityRemark	 
		
	FROM 
		sStudent.vStudentAcademic SA		
		INNER JOIN sActivity.tActivityParticipant AP ON AP.SourceId=SA.StudentId AND AP.SourceTypeId=2003 
		INNER JOIN sActivity.tActivity A ON A.Id=AP.ActivityId AND A.BatchId=SA.BatchId
		INNER JOIN sActivity.tActivityTypeMaster ATM ON ATM.Id = A.ActivityTypeId	
		INNER JOIN sSetup.tOrganizationMaster OM ON SA.OrgId = OM.Id
		INNER JOIN sSetup.tOrgGroupMaster OGM ON OM.OrgGroupId = OGM.Id	
	WHERE 
		(SA.ClassId=@rClassId OR @rClassId=0)
		AND (SA.DivisionId=@rDivisionId OR @rDivisionId=0)
		AND (ATM.Id=@rActivityTypeId OR ISNULL(@rActivityTypeId,0)=0)
		AND (AP.ActivityId=@rActivityId OR ISNULL(@rActivityId,0)=0)
		AND (SA.StatusId=@rStatusId OR @rStatusId=0)
		AND (SA.OrgId=@rOrgId OR @rOrgId=0)
		AND (ISNULL(SA.BatchStatusId,1)=1)
		AND (OGM.Id = @rOrgGroupId OR @rOrgGroupId = 0)		
		AND A.BatchId=@rBatchId
	Order By SA.ClassId
END

END
GO
PRINT N'Altering [sAdmission].[pRptStudentNewAdmissionListGet]...';


GO

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

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


GO


ALTER PROCEDURE [sAlert].[pEmployeeBiometricAbsentTimeGet]
	@rOrgId int,
	@rOrgGroupId int,
	@rTemplate nvarchar(max),
	@rSubject nvarchar(100),
	@rIntervalTime int
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY	
		BEGIN TRANSACTION 
			declare  @lBatchID INT
			SELECT @lBatchID = Id from sSetup.tBatchMaster Where OrgId = @rOrgId AND IsActive = 1
			if object_id('tempdb..#tShift') is not null
			BEGIN
				DROP TABLE #tShift
			END
			CREATE TABLE #tShift(
					ShiftCode int NOT NULL
				)

			insert #tShift
			Select 
				ShiftCode
			FROM sBiometric.tShiftMasterCloud
			where  ((OrgGroupId = @rOrgGroupId) OR (@rOrgGroupId=0))  
			--AND IsOutTimeAlertTime=1
			AND CAST(DATEADD(MINUTE,AlterGraceTime,StartTime) AS Time)<=cast([sCommon].[fGetDate]() as Time)
			AND CAST(DATEADD(MINUTE,AlterGraceTime,StartTime) AS Time)>=cast(DATEADD(MINUTE,-@rIntervalTime,[sCommon].[fGetDate]()) as Time)

			--select * from #tShift
			declare @lcount int=(SELECT COUNT(ShiftCode) FROM #tShift)

			if object_id('tempdb..#tTable') is not null
			BEGIN
				DROP TABLE #tTable
			END
			CREATE TABLE #tTable(
						SourceId bigint NOT NULL,
						In_Out_Time [datetime] NOT NULL,
						SourceTypeId int NOT NULL
					)

			if(@lcount>0)
			BEGIN
				insert into #tTable
				select SourceId,MIN(In_Out_Time),SourceTypeId
				from [sBiometric].[tCloudTransactionData] CDT
				inner join #tShift tempShift ON tempShift.ShiftCode=CDT.ShiftCode 
				WHERE Attn_Dt=CONVERT(date,[sCommon].[fGetDate]())  AND SourceTypeId=95 Group by SourceId,SourceTypeId
			END
			
			
			--select * from #tTable
			select EM.MobileNumber AS MobileNo,	
					EM.CompanyEmail AS EmailId,
					replace (
					replace(@rTemplate,'[EmployeeName]',EM.EmployeeName),
					'[AbsentDate]',ISNULL(Convert(varchar,[sCommon].[fGetDate](),103),''))
					 AS MsgText,
					@rSubject AS Subject,
					95 AS ReceiverSourceTypeId,
					EM.EmployeeId AS ReceiverSourceId,
					EM.EmployeeName AS EmployeeName,
					EM.Code AS Code,
					ISNULL(EC.WhatsAppContactNo,'') AS WhatsAppContactNo,
					95 AS SourceTypeId,
					EM.EmployeeId AS SourceId,
					EM.OrgId,
					OM.DisplayTitle AS OrganizationTitle
				FROM  
					sHrm.vEmployeeCommonDetail EM 
					Inner Join  [sHrm].[tEmployeeMaster] E on EM.EmployeeId=E.Id
					INNER JOIN #tShift tempshift ON tempshift.ShiftCode=E.ShiftId
					LEFT JOIN #tTable temp ON  temp.SourceId=EM.EmployeeId
					LEFT JOIN sHrm.tEmployeeCommunications EC ON EC.EmployeeId = EM.EmployeeId
					LEFT JOIN sSetup.tOrganizationMaster OM ON EM.OrgID = OM.Id
				where 
				EM.OrgID =@rOrgId
				AND temp.In_Out_Time is null
				AND ( [sHrm].[fWeekHOffGetBio](EM.EmployeeId , YEAR([sCommon].[fGetDate]()) ,MONTH([sCommon].[fGetDate]()) ,DAY([sCommon].[fGetDate]()),@lBatchID ,OrganizationDepartmentId ,@rOrgId )<>'W')
				AND ( [sHrm].[fWeekHOffGetBio](EM.EmployeeId , YEAR([sCommon].[fGetDate]()) ,MONTH([sCommon].[fGetDate]()) ,DAY([sCommon].[fGetDate]()),@lBatchID ,OrganizationDepartmentId ,@rOrgId )<> 'H')
			DROP TABLE #tTable
			DROP TABLE #tShift
		COMMIT TRANSACTION
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH
END
GO
PRINT N'Altering [sAlert].[pEmployeeBiometricFirstInTimeGet]...';


GO

ALTER PROCEDURE [sAlert].[pEmployeeBiometricFirstInTimeGet]
	 	 @rTemplate nvarchar(max)='',
		@rSubject nvarchar(100)='',
		@rOrgId int,
		@rIntervalTime int
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY	
		BEGIN TRANSACTION 
			if object_id('tempdb..#tTable') is not null
			BEGIN
				DROP TABLE #tTable
			END
			CREATE TABLE #tTable(
					SourceId bigint NOT NULL,
					In_Out_Time [datetime] NOT NULL,
					SourceTypeId int NOT NULL,
					CreatedDateTime [datetime] NOT NULL,
				)
			insert into #tTable
			select SourceId,min(In_Out_Time),SourceTypeId,min(CreatedDateTime) 
			from [sBiometric].[tCloudTransactionData] 
			WHERE Attn_Dt=CONVERT(date,[sCommon].[fGetDate]()) AND SourceTypeId=95 Group by SourceId,SourceTypeId
	
			--select * from #tTable

			SELECT 
				EM.MobileNumber AS MobileNo,	
				EM.CompanyEmail AS EmailId,
				replace (
				replace (
				replace (
				replace(@rTemplate,'[EmployeeName]',EM.EmployeeName),
				'[TimeStamp]',ISNULL(Convert(varchar,temp.In_Out_Time,108),'')),
				'[PresentTime]',ISNULL(Convert(varchar,temp.In_Out_Time,108),'')),
				'[PresentDate]',ISNULL(Convert(varchar,[sCommon].[fGetDate](),103),''))
				 AS MsgText,
				@rSubject AS Subject,
				95 AS ReceiverSourceTypeId,
				EM.EmployeeId AS ReceiverSourceId,
				EM.EmployeeName AS EmployeeName,
				EM.Code AS Code,
				ISNULL(EC.WhatsAppContactNo,'') AS WhatsAppContactNo,
				95 AS SourceTypeId,
				EM.EmployeeId AS SourceId,
				EM.OrgId,
				OM.OrgGroupId,
				ISNULL(Convert(varchar,temp.In_Out_Time,108),'') as Time,
				OM.DisplayTitle AS OrganizationTitle
			FROM 
				#tTable temp
				Inner join sHrm.vEmployeeCommonDetail EM ON temp.SourceId=EM.EmployeeId
				LEFT JOIN sHrm.tEmployeeCommunications EC ON EC.EmployeeId = EM.EmployeeId
				INNER JOIN sSetup.tOrganizationMaster OM ON EM.OrgID = OM.Id
			WHERE
				temp.CreatedDateTime >= DATEADD(minute,-(@rIntervalTime),[sCommon].[fGetDate]())
				AND EM.OrgID =@rOrgId

			DROP TABLE #tTable
		COMMIT TRANSACTION
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH


END
GO
PRINT N'Altering [sAlert].[pEmployeeBiometricLastOutTimeGet]...';


GO

ALTER PROCEDURE [sAlert].[pEmployeeBiometricLastOutTimeGet]
	@rTemplate nvarchar(max)='',
	@rSubject nvarchar(100)='',
	@rOrgId int,
	@rOrgGroupId int,
	@rIntervalTime int
 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY	
		BEGIN TRANSACTION 
			if object_id('tempdb..#tShift') is not null
			BEGIN
				DROP TABLE #tShift
			END
			CREATE TABLE #tShift(
					ShiftCode int NOT NULL,
					OutTimeAlertTime time not NUll
				)
			insert #tShift
			Select 
				ShiftCode, 
				CAST(OutTimeAlertTime AS Time)
				--case When DATEDIFF(MINUTE,CAST(OutTimeAlertTime AS Time),cast([sCommon].[fGetDate]() as Time)) < @rIntervalTime then DATEDIFF(MINUTE,CAST(OutTimeAlertTime AS Time),cast([sCommon].[fGetDate]() as Time)) else @rIntervalTime end 
			  FROM sBiometric.tShiftMasterCloud
			where  ((OrgGroupId = @rOrgGroupId) OR (@rOrgGroupId=0))  
			AND IsOutTimeAlertTime=1
			AND CAST(OutTimeAlertTime AS Time)<cast([sCommon].[fGetDate]() as Time)
			AND CAST(OutTimeAlertTime AS Time) > CAST(DATEADD(minute,-(@rIntervalTime),[sCommon].[fGetDate]()) AS Time)

			declare @lcount int=(SELECT COUNT(ShiftCode) FROM #tShift)
	 
			--select * from #tShift
			if object_id('tempdb..#tTable') is not null
			BEGIN
				DROP TABLE #tTable
			END
			CREATE TABLE #tTable(
						SourceId bigint NOT NULL,
						In_Out_Time [datetime] NOT NULL,
						SourceTypeId int NOT NULL,
						OutTimeAlertTime time NOT NULL,
						CreatedDateTime [datetime] NOT NULL
					)
			if(@lcount>0)
			BEGIN
				insert into #tTable
				select SourceId,MAX(In_Out_Time),SourceTypeId,tempShift.OutTimeAlertTime,Max(CreatedDateTime) 
				from [sBiometric].[tCloudTransactionData] CDT 
				inner join #tShift tempShift ON tempShift.ShiftCode=CDT.ShiftCode
				WHERE Attn_Dt=CONVERT(date,[sCommon].[fGetDate]())  AND SourceTypeId=95 Group by SourceId,SourceTypeId,tempShift.OutTimeAlertTime
			END

			select * from #tTable

			SELECT 
				EM.MobileNumber AS MobileNo,	
				EM.CompanyEmail AS EmailId,
				replace (
				replace(@rTemplate,'[EmployeeName]',EM.EmployeeName),
				'[TimeStamp]',ISNULL(Convert(varchar,temp.In_Out_Time,108),''))
				 AS MsgText,
				@rSubject AS Subject,
				95 AS ReceiverSourceTypeId,
				EM.EmployeeId AS ReceiverSourceId,
				EM.EmployeeName AS EmployeeName,
				ISNULL(EC.WhatsAppContactNo,'') AS WhatsAppContactNo,
				95 AS SourceTypeId,
				EM.EmployeeId AS SourceId,
				EM.OrgId,
				OM.OrgGroupId,
				OM.DisplayTitle AS OrganizationTitle
			FROM 
				#tTable temp
				Inner join sHrm.vEmployeeCommonDetail EM ON temp.SourceId=EM.EmployeeId
				LEFT JOIN sHrm.tEmployeeCommunications EC ON EC.EmployeeId = EM.EmployeeId
				INNER JOIN sSetup.tOrganizationMaster OM ON EM.OrgID = OM.Id
			WHERE
				temp.OutTimeAlertTime <= CAST([sCommon].[fGetDate]() AS Time)
				AND temp.OutTimeAlertTime > CAST(DATEADD(minute,-(@rIntervalTime),[sCommon].[fGetDate]()) AS Time)
				AND EM.OrgID =@rOrgId

			DROP TABLE #tTable
			DROP TABLE #tShift
		COMMIT TRANSACTION
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH
END
GO
PRINT N'Altering [sAlert].[pEmployeeBiometricLateTimeGet]...';


GO

ALTER PROCEDURE [sAlert].[pEmployeeBiometricLateTimeGet]
	 	 
	 	 @rOrgId int,
		 @rTemplate nvarchar(max)='',
		@rSubject nvarchar(100)=''
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	DECLARE @lDate date = ''
	SET @lDate = sCommon.fGetDate()

	DECLARE @lDay as nvarchar(3)

	Select @lDay  = RIGHT('00' + CAST(DATEPART(dd,@lDate) AS varchar(2)), 2)

	DECLARE @lColumnName varchar(10) = '',@lShiftColumntName varchar(10) = ''
	SET @lColumnName = 'MT.D' + CAST(@lDay AS VARCHAR) + '_IN'
	SET @lShiftColumntName = 'MT.D' + CAST(@lDay AS VARCHAR) + '_S'

	DECLARE @lGetConfigTime nvarchar(20) = ''
	SELECT @lGetConfigTime =  ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 398 AND SourceId = @rOrgId

	IF(@lGetConfigTime <> '' AND LEN(@lGetConfigTime) > 0)
	BEGIN
	DECLARE @Query NVARCHAR(MAX) = ''
	SET @Query = 'SELECT
					EC.MobileNumber AS MobileNo,	
					EC.CompanyEmail AS EmailId,
					replace (
					replace (
					replace('''+CONVERT(nvarchar(MAX),@rTemplate)+''',''[EmployeeName]'',EC.EmployeeName),
					''[LateTime]'','+@lColumnName+'),
					''[LateDate]'',ISNULL(Convert(varchar,[sCommon].[fGetDate](),103),''''))
					 AS MsgText,
					'''+CONVERT(nvarchar(20),@rSubject)+''' AS Subject,
					95 AS ReceiverSourceTypeId,
					EC.EmployeeId AS ReceiverSourceId,
					EC.EmployeeName AS EmployeeName,
					ISNULL(EC1.WhatsAppContactNo,'''') AS WhatsAppContactNo,
					95 AS SourceTypeId,
					EC.EmployeeId AS SourceId,
					EC.OrgId,
					OM.OrgGroupId,
					EM.Id AS EmployeeId,
					EM.Code,
					ISNULL(EM.FirstName, '''') + '' '' + ISNULL(EM.LastName, '''') AS  EmployeeName,
					 '+@lColumnName+' AS Time,
					OM.DisplayTitle AS OrganizationTitle
		FROM 
				sHrm.tEmployeeMaster EM
				Inner join sHrm.vEmployeeCommonDetail EC ON EM.Id=EC.EmployeeId
				LEFT JOIN sHrm.tEmployeeCommunications EC1 ON EC1.EmployeeId = EC.EmployeeId
				INNER JOIN sBiometric.tMonthTrans MT ON MT.EmployeeId = EM.Id AND MT.SourceTypeId = 95 
				INNER JOIN sSetup.tOrganizationMaster OM ON EM.OrgID = OM.Id
				INNER Join sBiometric.tShiftMasterCloud SM ON SM.ShiftName='+@lShiftColumntName+'
		WHERE
				EM.OrgID = '+CONVERT(nvarchar(20),@rOrgId)+'
				AND MONTH(MT.Attn_dt) = MONTH('''+CONVERT(nvarchar(20),@lDate)+''')
				AND '+@lColumnName+' > DATEADD(minute, SM.GraceAfter,SM.StartTime)
				--AND '+@lColumnName+' > '''+@lGetConfigTime+'''
				AND EM.StatusId = 7	'
		--print (@Query)
		execute (@Query)	
	END

END
GO
PRINT N'Altering [sAlert].[pStudentBiometricAbsentTimeGet]...';


GO

ALTER PROCEDURE [sAlert].[pStudentBiometricAbsentTimeGet]
	 @rOrgId int,
	@rOrgGroupId int,
	@rTemplate nvarchar(max),
	@rSubject nvarchar(100)='',
	@rIntervalTime int

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY	
		BEGIN TRANSACTION 
		declare  @lBatchID INT
		SELECT @lBatchID = Id from sSetup.tBatchMaster Where OrgId = @rOrgId AND IsActive = 1
			
			if object_id('tempdb..#tShift') is not null
			BEGIN
				DROP TABLE #tShift
			END
			CREATE TABLE #tShift(
					ShiftCode int NOT NULL
				)

			insert #tShift
			Select 
				ShiftCode
			FROM sBiometric.tShiftMasterCloud
			where  ((OrgGroupId = @rOrgGroupId) OR (@rOrgGroupId=0))  
			--AND IsOutTimeAlertTime=1
			AND CAST(DATEADD(MINUTE,AlterGraceTime,StartTime) AS Time)<=cast([sCommon].[fGetDate]() as Time)
			AND CAST(DATEADD(MINUTE,AlterGraceTime,StartTime) AS Time)>=cast(DATEADD(MINUTE,-@rIntervalTime,[sCommon].[fGetDate]()) as Time)

			--select * from #tShift
			declare @lcount int=(SELECT COUNT(ShiftCode) FROM #tShift)

			if object_id('tempdb..#tTable') is not null
			BEGIN
				DROP TABLE #tTable
			END
			CREATE TABLE #tTable(
						SourceId bigint NOT NULL,
						In_Out_Time [datetime] NOT NULL,
						SourceTypeId int NOT NULL
					)

			if(@lcount>0)
			BEGIN
				insert into #tTable
				select SourceId,MIN(In_Out_Time),SourceTypeId
				from [sBiometric].[tCloudTransactionData] CDT
				inner join #tShift tempShift ON tempShift.ShiftCode=CDT.ShiftCode 
				WHERE Attn_Dt=CONVERT(date,[sCommon].[fGetDate]())  AND SourceTypeId=2003 Group by SourceId,SourceTypeId
			END
			
			
			--select * from #tTable
			select SC.ParentContactNo AS MobileNo,	
					SC.ParentEmail AS EmailId,
					replace (
					replace(@rTemplate,'[StudentName]',SC.Name),
					'[AbsentDate]',ISNULL(Convert(varchar,[sCommon].[fGetDate](),103),''))
					 AS MsgText,
					@rSubject AS Subject,
					2003 AS ReceiverSourceTypeId,
					SC.StudentId AS ReceiverSourceId,
					SC.Name AS StudentName,
					SC.Code,
					ISNULL(SC.WhatsAppContactNo,'') AS WhatsAppContactNo,
					2003 AS SourceTypeId,
					SC.StudentId AS SourceId,
					SC.OrgId,
					OM.OrgGroupId,
					OM.DisplayTitle AS OrganizationTitle
				FROM  
					sStudent.vStudentCommunication SC 
					Inner Join  [sStudent].[tStudentMaster] SM on SM.Id=SC.StudentId
					INNER JOIN sSetup.tOrganizationMaster OM ON SC.OrgID = OM.Id
					INNER JOIN #tShift tempshift ON tempshift.ShiftCode=SM.ShiftId
					LEFT JOIN #tTable temp ON  temp.SourceId=SC.StudentId 
				where 
					SC.OrgID =@rOrgId
					AND SC.IsActiveBatch=1
					AND SC.StatusId = 1
					AND temp.In_Out_Time is null
					AND ([sAttendance].[fWeekHOffGet](YEAR([sCommon].[fGetDate]()) ,MONTH([sCommon].[fGetDate]()) ,DAY([sCommon].[fGetDate]()),SC.BatchId,SC.ClassId,SC.DivisionId, '',@rOrgId)<>'W')
					AND ([sAttendance].[fWeekHOffGet](YEAR([sCommon].[fGetDate]()) ,MONTH([sCommon].[fGetDate]()) ,DAY([sCommon].[fGetDate]()),SC.BatchId,SC.ClassId,SC.DivisionId, '',@rOrgId)<>'H')

			DROP TABLE #tTable
			DROP TABLE #tShift
		COMMIT TRANSACTION
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH
END
GO
PRINT N'Altering [sAlert].[pStudentBiometricFirstInTimeGet]...';


GO

ALTER PROCEDURE [sAlert].[pStudentBiometricFirstInTimeGet]
	@rTemplate nvarchar(max)='',
	@rSubject nvarchar(100)='',
	@rOrgId int,
	@rIntervalTime int

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY	
		BEGIN TRANSACTION 
			if object_id('tempdb..#tTable') is not null
			BEGIN
				DROP TABLE #tTable
			END
			CREATE TABLE #tTable(
					SourceId bigint NOT NULL,
					In_Out_Time [datetime] NOT NULL,
					SourceTypeId int NOT NULL,
					CreatedDateTime [datetime] NOT NULL,
				)
			insert into #tTable
			select SourceId,min(In_Out_Time),SourceTypeId,min(CreatedDateTime) 
			from [sBiometric].[tCloudTransactionData] 
			WHERE Attn_Dt=CONVERT(date,[sCommon].[fGetDate]())  AND SourceTypeId=2003 Group by SourceId,SourceTypeId
	
			--select * from #tTable
			SELECT 
				SC.ParentContactNo AS MobileNo,	
				SC.ParentEmail AS EmailId,
				replace (
				replace (
				replace (
				replace(@rTemplate,'[StudentName]',SC.Name),
				'[TimeStamp]',ISNULL(Convert(varchar,temp.In_Out_Time,108),'')),
				'[PresentTime]',ISNULL(Convert(varchar,temp.In_Out_Time,108),'')),
				'[PresentDate]',ISNULL(Convert(varchar,[sCommon].[fGetDate](),103),''))
				 AS MsgText,
				@rSubject AS Subject,
				2003 AS ReceiverSourceTypeId,
				SC.StudentId AS ReceiverSourceId,
				SC.Name AS StudentName,
				SC.Code AS Code,
				ISNULL(SC.WhatsAppContactNo,'') AS WhatsAppContactNo,
				2003 AS SourceTypeId,
				SC.StudentId AS SourceId,
				SC.OrgId,
				OM.OrgGroupId,
				ISNULL(Convert(varchar,temp.In_Out_Time,108),'') as Time,
				OM.DisplayTitle AS OrganizationTitle


			FROM 
				#tTable temp
				Inner join sStudent.vStudentCommunication SC ON temp.SourceId=SC.StudentId AND SC.IsActiveBatch=1
				INNER JOIN sSetup.tOrganizationMaster OM ON SC.OrgID = OM.Id
			WHERE
				temp.CreatedDateTime >= DATEADD(minute,-(@rIntervalTime),[sCommon].[fGetDate]())
				AND SC.OrgID =@rOrgId
				AND SC.StatusId = 1
			DROP TABLE #tTable
		COMMIT TRANSACTION
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH

END
GO
PRINT N'Altering [sAlert].[pStudentBiometricLastOutTimeGet]...';


GO

ALTER PROCEDURE [sAlert].[pStudentBiometricLastOutTimeGet]
	@rTemplate nvarchar(max)='',
	@rSubject nvarchar(100)='',
	@rOrgId int,
	@rOrgGroupId int,
	@rIntervalTime int
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY	
		BEGIN TRANSACTION 
			if object_id('tempdb..#tShift') is not null
			BEGIN
				DROP TABLE #tShift
			END
			CREATE TABLE #tShift(
					ShiftCode int NOT NULL,
					OutTimeAlertTime time not NUll
				)

			insert #tShift
			Select 
				ShiftCode,
				CAST(OutTimeAlertTime AS Time) 
				--case When DATEDIFF(MINUTE,CAST(@rIntervalTime AS Time),cast([sCommon].[fGetDate]() as Time)) < @rIntervalTime then DATEDIFF(MINUTE,CAST(OutTimeAlertTime AS Time),cast([sCommon].[fGetDate]() as Time)) else @rIntervalTime end 
			FROM sBiometric.tShiftMasterCloud
			where  ((OrgGroupId = @rOrgGroupId) OR (@rOrgGroupId=0))  
			AND IsOutTimeAlertTime=1
			AND CAST(OutTimeAlertTime AS Time)<cast([sCommon].[fGetDate]() as Time)
			AND CAST(OutTimeAlertTime AS Time) > CAST(DATEADD(minute,-(@rIntervalTime),[sCommon].[fGetDate]()) AS Time)

			--select * from #tShift
			declare @lcount int=(SELECT COUNT(ShiftCode) FROM #tShift)

			if object_id('tempdb..#tTable') is not null
			BEGIN
				DROP TABLE #tTable
			END
			CREATE TABLE #tTable(
				SourceId bigint NOT NULL,
				In_Out_Time [datetime] NOT NULL,
				SourceTypeId int NOT NULL,
				OutTimeAlertTime time NOT NULL,
				CreatedDateTime [datetime] NOT NULL
			)
			if(@lcount>0)
			BEGIN
				insert into #tTable
				select SourceId,MAX(In_Out_Time),SourceTypeId,tempShift.OutTimeAlertTime,Max(CreatedDateTime) 
				from [sBiometric].[tCloudTransactionData] CDT 
				inner join #tShift tempShift ON tempShift.ShiftCode=CDT.ShiftCode
				WHERE Attn_Dt=CONVERT(date,[sCommon].[fGetDate]())  AND SourceTypeId=2003 Group by SourceId,SourceTypeId,tempShift.OutTimeAlertTime
			End
			--select * from #tTable

			SELECT 
				SC.ParentContactNo AS MobileNo,	
				SC.ParentEmail AS EmailId,
				replace (
				replace(@rTemplate,'[StudentName]',SC.Name),
				'[TimeStamp]',ISNULL(Convert(varchar,temp.In_Out_Time,108),''))
				 AS MsgText,
				@rSubject AS Subject,
				2003 AS ReceiverSourceTypeId,
				SC.StudentId AS ReceiverSourceId,
				SC.Name AS StudentName,
				SC.Code,
				ISNULL(SC.WhatsAppContactNo,'') AS WhatsAppContactNo,
				2003 AS SourceTypeId,
				SC.StudentId AS SourceId,
				SC.OrgId,
				OM.OrgGroupId,
				OM.DisplayTitle AS OrganizationTitle


			FROM 
				#tTable temp
				Inner join sStudent.vStudentCommunication SC ON temp.SourceId=SC.StudentId AND SC.IsActiveBatch=1
				INNER JOIN sSetup.tOrganizationMaster OM ON SC.OrgID = OM.Id
			WHERE
				temp.OutTimeAlertTime <= CAST([sCommon].[fGetDate]() AS Time)
				AND temp.OutTimeAlertTime > CAST(DATEADD(minute,-(@rIntervalTime),[sCommon].[fGetDate]()) AS Time)
				AND SC.OrgID =@rOrgId
				AND SC.StatusId = 1

			DROP TABLE #tTable
			DROP TABLE #tShift
		COMMIT TRANSACTION
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH
END
GO
PRINT N'Altering [sAlert].[pStudentBiometricLateTimeGet]...';


GO

ALTER PROCEDURE [sAlert].[pStudentBiometricLateTimeGet]
	 	 
	 	 @rOrgId int,
		@rTemplate nvarchar(max)='',
		@rSubject nvarchar(100)=''
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	DECLARE @lDate date = ''
	SET @lDate = sCommon.fGetDate()

	DECLARE @lDay as nvarchar(3)
	Select @lDay  = RIGHT('00' + CAST(DATEPART(dd,@lDate) AS varchar(2)), 2)

	DECLARE @lColumnName varchar(10) = '',@lShiftColumntName varchar(10) = ''
	SET @lColumnName = 'MT.D' + CAST(@lDay AS VARCHAR) + '_IN'
	SET @lShiftColumntName = 'MT.D' + CAST(@lDay AS VARCHAR) + '_S'

	DECLARE @lGetConfigTime nvarchar(20) = ''
	SELECT @lGetConfigTime =  ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 399 AND SourceId = @rOrgId

	IF(@lGetConfigTime <> '' AND LEN(@lGetConfigTime) > 0)
	BEGIN
	DECLARE @Query NVARCHAR(MAX) = ''
	SET @Query ='SELECT
					SC.ParentContactNo AS MobileNo,	
					SC.ParentEmail AS EmailId,
					replace (
					replace (
					replace('''+CONVERT(nvarchar(MAX),@rTemplate)+''',''[StudentName]'',sStudent.fStudentNameGet(SM.FirstName, SM.MiddleName, SM.LastName,OM.StudentNameFormatId)),
					''[LateTime]'','+@lColumnName+'),
					''[LateDate]'',ISNULL(Convert(varchar,[sCommon].[fGetDate](),103),''''))
					 AS MsgText,
					'''+CONVERT(nvarchar(20),@rSubject)+''' AS Subject,
					2003 AS ReceiverSourceTypeId,
					SC.StudentId AS ReceiverSourceId,
					sStudent.fStudentNameGet(SM.FirstName, SM.MiddleName, SM.LastName,OM.StudentNameFormatId) AS StudentName,
					ISNULL(SC.WhatsAppContactNo,'''') AS WhatsAppContactNo,
					2003 AS SourceTypeId,
					SC.StudentId AS SourceId,
					SM.OrgId,
					OM.OrgGroupId,
					SM.Id AS StudentId,
					SM.Code,
					sStudent.fStudentNameGet(SM.FirstName, SM.MiddleName, SM.LastName,OM.StudentNameFormatId) AS  StudentName,
					 '+@lColumnName+' AS Time,
					OM.DisplayTitle AS OrganizationTitle	
		FROM 
				sStudent.tStudentMaster SM
				Inner join sStudent.tStudentCommunication SC ON SM.Id=SC.StudentId
				INNER JOIN sSetup.tOrganizationMaster OM ON SM.OrgID = OM.Id
				INNER JOIN sBiometric.tMonthTrans MT ON MT.EmployeeId = SM.Id AND MT.SourceTypeId = 2003
				INNER Join sBiometric.tShiftMasterCloud SMC ON SMC.ShiftName='+@lShiftColumntName+'
		WHERE
				SM.OrgId = '+CONVERT(nvarchar(20),@rOrgId)+'
				AND MONTH(MT.Attn_dt) = MONTH('''+CONVERT(nvarchar(20),@lDate)+''')
				--AND '+@lColumnName+' > '''+@lGetConfigTime+'''
				AND '+@lColumnName+' > DATEADD(minute, SMC.GraceAfter,SMC.StartTime)
				AND SM.StatusId = 1'
				
		--print (@Query)
		execute (@Query)			
	END

END
GO
PRINT N'Altering [sAssessment].[ExamSettingApplyAllClassUpdate]...';


GO

 
ALTER PROCEDURE [sAssessment].[ExamSettingApplyAllClassUpdate]
	 
	        @rBatchId int
           ,@rExamSubGroupId int           
           ,@rClassId int
           ,@rIsRankNo bit
           ,@rIsGrade bit
           ,@rIsPercentile bit
           ,@rIsPercentage bit
           ,@rIsSubjectPercentile bit
           ,@rGradeSetId int
           ,@rIsProcessResult bit
           ,@rIsMarkInDecimal bit
           ,@rIsNegativeMarks bit
           ,@rIsPrePrinted bit
           ,@rIsDisplayBirthDate bit
           ,@rIsDisplayPhoto bit
           ,@rIsDisplayschoolName bit
           ,@rIsIncludeCoScholastic bit
           ,@rIsLockForEdit bit
           ,@rRemark1 nvarchar(1000)
           ,@rRemark2 nvarchar(300)
           ,@rDisplayTitle nvarchar(150)
           ,@rFooterAdjustment smallint
           ,@rReportId smallint
           ,@rRemark3 nvarchar(300)
           ,@rIsDisplayHeightWeight bit
           ,@rIsDisplayAttendance bit
           ,@rIsDisplayResultStatus bit
           ,@rDetailAdjustment smallint
           ,@rTermScopeId smallint
           ,@rMaximumMark Decimal
           ,@rOrgId int,
           @rCoScholasticScopeId smallint,
           @rCoScholasticGradeSet int,
           @rPercentileScope smallint,
           @rIsDisplayTeacherSign bit,
           @rIsDisplayPrincipalSign bit,
           @rSubjectGroupPerPage smallint,
           @rIsExcludeAbsentTotal bit,
           @rDecimalUpto nvarchar(10),
          @rIsShowTotalMark bit=0,
          @rRemark1Caption nvarchar(100),
          @rRemark2Caption nvarchar(100),
          @rRemark3Caption nvarchar(100),
          @rTeacherSignCaption nvarchar(100),
          @rPrincipalSignCaption nvarchar(100),
          @rParentSignCaption nvarchar(100),
          @rIsAllExamPassRequired bit=0 , 
		  @rIsGenerateRankNo bit = 0,
		  @rResultSheetAdditionalTitle nvarchar(100)='',
		  @rDisplayAttendanceId Smallint=0,
		  @rReportHeaderId smallint=0
          WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	--BEGIN TRY
	
	IF (@rTermScopeId < 0)
	SET @rTermScopeId = 0
	
	
	
	 BEGIN		
	    UPDATE  [sAssessment].[tExamMaster]
	    SET
			    IsRankNo=@rIsRankNo 
			   ,IsGrade=@rIsGrade 
			   ,IsPercentile =@rIsPercentile 
			   ,IsSubjectPercentile = @rIsSubjectPercentile
			   ,IsPercentage=@rIsPercentage 
			   ,GradeSetId =@rGradeSetId 
			   ,IsProcessResult = @rIsProcessResult
			   ,IsMarksInDecimal = @rIsMarkInDecimal			   
			   ,IsNegativeMarks = @rIsNegativeMarks
			   
			   ,IsOnPrePrinted = @rIsPrePrinted
			   ,IsDisplayBirthDate=@rIsDisplayBirthDate
			   ,IsDisplayPhoto=@rIsDisplayPhoto
			   ,IsDisplaySchoolName=@rIsDisplayschoolName
			   ,IsIncludeCoScholastic=@rIsIncludeCoScholastic
			   ,IsLockForEdit=@rIsLockForEdit
			   ,IsDisplayAttendance=@rIsDisplayAttendance
			   ,IsDisplayHeightWeight=@rIsDisplayHeightWeight
			   ,IsResultStatus=@rIsDisplayResultStatus
			   ,Remark1=@rRemark1
			   ,Remark2=@rRemark2
			   ,Remark3=@rRemark3
			   ,DisplayTitle=@rDisplayTitle
			   ,FooterAdjustment=@rFooterAdjustment
			   ,DetailAdjustment=@rDetailAdjustment
			   ,ReportId = @rReportId
			   ,TermScopeId=@rTermScopeId
			   ,ExamMaximum=@rMaximumMark,
			   CoScholasticScopeId=@rCoScholasticScopeId,
			   coscholasticgradesetid = @rCoScholasticgradeset,
			   percentilescopeid=@rpercentilescope,
			   isdisplayteachersign = @rIsdisplayteachersign,
			   isdisplayprincipalsign = @risdisplayprincipalsign,
			   SubjectGroupPerPage = @rSubjectGroupPerpage,
			   IsExcludeAbsentTotal = @rIsExcludeAbsentTotal,
			   DecimalFormat = @rDecimalUpto,
			   IsDisplayTotalMark = @rIsShowTotalMark,
			   Remark1Caption=@rRemark1Caption,
			   Remark2Caption=@rRemark2Caption,
			   Remark3Caption=@rRemark3Caption,
			   TeacherSignCaption = @rTeacherSignCaption,
			   PrincipalSignCaption =@rPrincipalSignCaption,
			   ParentSignCaption =@rParentSignCaption,
			   IsAllExamPassRequired =@rIsAllExamPassRequired,
			   IsGenerateRankNo = @rIsGenerateRankNo,
			   ResultSheetAdditionalTitle=@rResultSheetAdditionalTitle,
			   DisplayAttendanceId=@rDisplayAttendanceId,
			   ReportHeaderId=@rReportHeaderId
			 
             
	      WHERE ClassId = @rClassId AND ExamSubGroupId=@rExamSubGroupId AND BatchId = @rBatchId
	      
	      SELECT 1 AS Result
	
		--COMMIT TRANSACTION
	 END  	

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


GO

ALTER PROCEDURE [sAssessment].[pMarkEntryRankUpdate]
	 
	 @rExamId int=0,
	 @rDivisionId int=0,
	 @rBatchId int=0
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	
BEGIN 	

-- ROW_NUMBER() OVER (ORDER BY TotalObtain) AS "Row Number"    -- Row number
-- RANK() OVER (ORDER BY TotalObtain) AS Rank                  -- skip next number
-- DENSE_RANK() OVER (ORDER BY TotalObtain) AS "Dense Rank"    -- continue next number 
-- NTILE(4) OVER (ORDER BY TotalObtain) AS Quartile            -- make number of rank group    

DECLARE  @lOrgId smallint,@lSiddhiKrupaApplicable bit, @lIsSkipRankConfigValue bit=0 

SELECT @lOrgId = OM.Id From sSetup.tBatchMaster BM INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = BM.OrgId Where BM.Id = @rBatchId
	 
SELECT @lSiddhiKrupaApplicable = ISNULL(IsApplySiddhiKrupa,0) From sAssessment.tExamMaster Where Id = @rExamId

-- Configuration Value
-- Config Assessment.IsSkipRank						     
SELECT @lIsSkipRankConfigValue = ISNULL(CS.ItemValue,CM.ItemValue) From sConfig.tConfigurationMaster CM LEFT JOIN sConfig.tConfigurationSetup CS ON CM.Id = CS.ConfigurationId	AND SourceId = @lOrgId WHERE CS.ConfigurationId = 315 AND SourceTypeId = 1016							     					     



UPDATE R Set R.RankNumber = 0 From sAssessment.tResult R Inner Join sStudent.tAcademic A ON A.Id = R.AcademicId AND R.ExamId=@rExamId AND A.DivisionId = @rDivisionId AND A.BatchId = @rBatchId

IF @lSiddhiKrupaApplicable = 0
BEGIN
	IF(@lIsSkipRankConfigValue=0)
    BEGIN
		Update R Set R.RankNumber=A.RankNumber From sAssessment.tResult R
		INNER JOIN
		(Select DENSE_RANK() OVER ( ORDER BY Percentage Desc) AS RankNumber,
		AcademicId 
		from sAssessment.tResult RS
		INNER JOIN sStudent.tAcademic SA ON SA.Id= RS.AcademicId 
		AND ExamId=@rExamId AND SA.DivisionId=@rDivisionId  AND SA.BatchId = @rBatchId
		AND ResultStatus='PASS' ) A
		ON A.AcademicId = R.AcademicId 
		WHERE R.ExamId = @rExamId
    END
    ELSE
    BEGIN
	    Update R Set R.RankNumber=A.RankNumber From sAssessment.tResult R
		INNER JOIN
		(Select RANK() OVER ( ORDER BY Percentage Desc) AS RankNumber,
		AcademicId 
		from sAssessment.tResult RS
		INNER JOIN sStudent.tAcademic SA ON SA.Id= RS.AcademicId 
		AND ExamId=@rExamId AND SA.DivisionId=@rDivisionId  AND SA.BatchId = @rBatchId
		AND ResultStatus='PASS' ) A
		ON A.AcademicId = R.AcademicId 
		WHERE R.ExamId = @rExamId
	END
END
ELSE
BEGIN

	
	DECLARE @lIsShowSiddhiKrupaExamField bit, @lIsSetSiddhiAppliedStudentRank0 bit, @lIsMoveSiddhiRankToLast bit,@lMaxRank int
		
	-- Config Assessment.IsShowSiddhiKrupaExamField
	SELECT @lIsShowSiddhiKrupaExamField = ISNULL(CS.ItemValue,CM.ItemValue) From sConfig.tConfigurationSetup CS LEFT JOIN sConfig.tConfigurationMaster CM ON CM.Id = CS.ConfigurationId	WHERE CS.ConfigurationId = 278 AND SourceId = @lOrgId AND SourceTypeId = 1016

	-- Config Assessment.IsSetSiddhiAppliedStudentRank0
	SELECT @lIsSetSiddhiAppliedStudentRank0 = ISNULL(CS.ItemValue,CM.ItemValue) From sConfig.tConfigurationMaster CM LEFT JOIN sConfig.tConfigurationSetup CS ON CM.Id = CS.ConfigurationId	AND SourceId = @lOrgId WHERE CS.ConfigurationId = 280 AND SourceTypeId = 1016

	-- Config Assessment.IsMoveSiddhiRankToLast
	SELECT @lIsMoveSiddhiRankToLast = ISNULL(CS.ItemValue,CM.ItemValue) From sConfig.tConfigurationMaster CM LEFT JOIN sConfig.tConfigurationSetup CS ON CM.Id = CS.ConfigurationId	AND SourceId = @lOrgId	WHERE CS.ConfigurationId = 281 AND SourceTypeId = 1016	

	-- Create temp table for get ResultDetail(GraceMark,KrupaMark)
	CREATE TABLE #TempResultDetail (ResultId bigint,AcademicId bigint,GraceMark Decimal(5,2),KrupaMark Decimal(5,2))
	INSERT INTO #TempResultDetail
	SELECT DISTINCT RD.ResultId,SA.Id AS AcademicId,RD.GraceMark,RD.KrupaMark
	FROM sAssessment.tResult RS INNER JOIN sStudent.tAcademic SA ON SA.Id= RS.AcademicId INNER JOIN sAssessment.tResultDetail RD ON RD.ResultId = RS.Id
	WHERE RS.ExamId=@rExamId AND SA.DivisionId=@rDivisionId  AND SA.BatchId = @rBatchId

	IF(@lIsSkipRankConfigValue=0)
	BEGIN
		Update R Set R.RankNumber=A.RankNumber From sAssessment.tResult R
		INNER JOIN
		(Select DENSE_RANK() OVER ( ORDER BY Percentage Desc) AS RankNumber,
		AcademicId 
		from sAssessment.tResult RS
		INNER JOIN sStudent.tAcademic SA ON SA.Id= RS.AcademicId 
		AND ExamId=@rExamId AND SA.DivisionId=@rDivisionId  AND SA.BatchId = @rBatchId
		AND ResultStatus='PASS' 

		AND RS.Id NOT IN (Select ResultId from #TempResultDetail Where KrupaMark > 0) -- Edited by Kundan. Manage rank only for Grace Mark. (Updated from Grace Mark to Krupa Mark)
		) A
		ON A.AcademicId = R.AcademicId 
		WHERE R.ExamId = @rExamId
		AND R.Id NOT IN (Select ResultId from #TempResultDetail Where KrupaMark > 0) -- Edited by Kundan. Manage rank only for Grace Mark. (Updated from Grace Mark to Krupa Mark)
	END
	ELSE
	BEGIN
	   Update R Set R.RankNumber=A.RankNumber From sAssessment.tResult R
		INNER JOIN
		(Select RANK() OVER ( ORDER BY Percentage Desc) AS RankNumber,
		AcademicId 
		from sAssessment.tResult RS	
		INNER JOIN sStudent.tAcademic SA ON SA.Id= RS.AcademicId 
		AND ExamId=@rExamId AND SA.DivisionId=@rDivisionId  AND SA.BatchId = @rBatchId
		AND ResultStatus='PASS'
		AND RS.Id NOT IN (Select ResultId from #TempResultDetail Where KrupaMark > 0) -- Edited by Kundan. Manage rank only for Grace Mark. (Updated from Grace Mark to Krupa Mark)
		 ) A
		ON A.AcademicId = R.AcademicId 
		WHERE R.ExamId = @rExamId
		AND R.Id NOT IN (Select ResultId from #TempResultDetail Where KrupaMark > 0) -- Edited by Kundan. Manage rank only for Grace Mark. (Updated from Grace Mark to Krupa Mark)
	END

If @lIsShowSiddhiKrupaExamField = 1 AND @lSiddhiKrupaApplicable = 1
BEGIN

-- Set Rank 0 to Those whose Siddhi/GraceMark > 0
IF @lIsSetSiddhiAppliedStudentRank0 = 1 
	BEGIN
		Update R Set R.RankNumber = 0 From sAssessment.tResult R 
		Inner Join sStudent.tAcademic A ON A.Id = R.AcademicId  
		AND R.ExamId=@rExamId
		AND A.DivisionId = @rDivisionId 
		AND A.BatchId = @rBatchId
		
		IF(@lIsSkipRankConfigValue=0)
		BEGIN		
			Update R Set R.RankNumber=A.RankNumber 
			From sAssessment.tResult R
			INNER JOIN
			(Select DENSE_RANK() OVER ( ORDER BY Percentage Desc) AS RankNumber, AcademicId 
			from sAssessment.tResult RS
			INNER JOIN sStudent.tAcademic SA ON SA.Id= RS.AcademicId 
			INNER JOIN sAssessment.tResultDetail RD ON RD.ResultId = RS.Id
			AND RS.ExamId=@rExamId AND SA.DivisionId=@rDivisionId  AND SA.BatchId = @rBatchId
			AND ResultStatus in ('PASS','PROMOTED')
			AND RS.Id NOT IN (Select ResultId from #TempResultDetail Where GraceMark > 0 OR KrupaMark > 0)
			) A
			ON A.AcademicId = R.AcademicId 
			WHERE R.ExamId = @rExamId
			AND R.Id NOT IN (Select ResultId from #TempResultDetail Where GraceMark > 0 OR KrupaMark > 0)
		END
		ELSE
		BEGIN
			Update R Set R.RankNumber=A.RankNumber 
			From sAssessment.tResult R
			INNER JOIN
			(Select RANK() OVER ( ORDER BY Percentage Desc) AS RankNumber, AcademicId 
			from sAssessment.tResult RS
			INNER JOIN sStudent.tAcademic SA ON SA.Id= RS.AcademicId 
			INNER JOIN sAssessment.tResultDetail RD ON RD.ResultId = RS.Id
			AND RS.ExamId=@rExamId AND SA.DivisionId=@rDivisionId  AND SA.BatchId = @rBatchId
			AND ResultStatus in ('PASS','PROMOTED')
			AND RS.Id NOT IN (Select ResultId from #TempResultDetail Where GraceMark > 0 OR KrupaMark > 0)
			) A
			ON A.AcademicId = R.AcademicId 
			WHERE R.ExamId = @rExamId
			AND R.Id NOT IN (Select ResultId from #TempResultDetail Where GraceMark > 0 OR KrupaMark > 0)
		END
	END
ELSE IF @lIsMoveSiddhiRankToLast = 1
	BEGIN
			SELECT @lMaxRank = Max(RankNumber) 
			FROM sAssessment.tResult R 
			INNER JOIN sStudent.tAcademic SA ON SA.Id= R.AcademicId 
			INNER JOIN sAssessment.tExamMaster EM ON EM.Id = R.ExamId
			INNER JOIN sSetup.tDivisionMaster DM ON DM.ClassId = EM.ClassId and DM.Id = SA.DivisionId
			WHERE EM.Id = @rExamId  AND DM.Id = @rDivisionId AND EM.BatchId= @rBatchId AND R.Percentage > 0
 

			IF(@lIsSkipRankConfigValue=0)
			BEGIN				
				Update R Set R.RankNumber= convert(int,@lMaxRank) + convert(int,A.RankNumber) From sAssessment.tResult R
				INNER JOIN
				(Select DENSE_RANK() OVER ( ORDER BY Percentage Desc) AS RankNumber, AcademicId 
				from sAssessment.tResult RS
				INNER JOIN sStudent.tAcademic SA ON SA.Id= RS.AcademicId 
				AND ExamId=@rExamId AND SA.DivisionId=@rDivisionId  AND SA.BatchId = @rBatchId
				AND RS.Id IN (Select ResultId from #TempResultDetail Where GraceMark > 0 AND KrupaMark <= 0 )
				AND ResultStatus in ('PASS','PROMOTED')) A
				ON A.AcademicId = R.AcademicId 
				WHERE R.ExamId = @rExamId
				AND R.Id IN (Select ResultId from #TempResultDetail Where GraceMark > 0 AND KrupaMark <= 0 )
			END
			ELSE
			BEGIN
				Update R Set R.RankNumber=convert(int,@lMaxRank) + convert(int,A.RankNumber) From sAssessment.tResult R
				INNER JOIN
				(Select RANK() OVER ( ORDER BY Percentage Desc) AS RankNumber, AcademicId 
				from sAssessment.tResult RS
				INNER JOIN sStudent.tAcademic SA ON SA.Id= RS.AcademicId 
				AND ExamId=@rExamId AND SA.DivisionId=@rDivisionId  AND SA.BatchId = @rBatchId
				AND RS.Id IN (Select ResultId from #TempResultDetail Where GraceMark > 0 AND KrupaMark <= 0)
				AND ResultStatus in ('PASS','PROMOTED')) A
				ON A.AcademicId = R.AcademicId 
				WHERE R.ExamId = @rExamId 
				AND R.Id IN (Select ResultId from #TempResultDetail Where GraceMark > 0 AND KrupaMark <= 0)	       	       	       
			END
			END		
END

	DROP TABLE #TempResultDetail

END 

	SELECT 1 AS Result
END
GO
PRINT N'Altering [sAssessment].[pRptResultSheetSubjectAcivityMultiExamGet]...';


GO
ALTER PROCEDURE [sAssessment].[pRptResultSheetSubjectAcivityMultiExamGet]
	 
	 @rBuilder1 nvarchar(max)='',
	 @rSubjectId int = 0,
	 @rBatchId int=0,
	 @rClass int=0,
	 @rDivisionId int=0,
	 @rExamId int,
	 @rCode nvarchar(20)='',
	 @rFromRollNo int=0,
	 @rToRollNo int=0,
	 @rFromRank int=0,
	 @rToRank int=0,
	 @rGrade nvarchar(20)='',
	 @rResultId bigint=0,
	 @rStatusId int=0,
	 @rAcademicId bigint=0,
	 @rOrgId int=0,
	 @rMultiCode nvarchar(max)=''

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
 begin
 	

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

Declare @lDecimalConfig nvarchar(20)=''
SELECT @lDecimalConfig =ItemValue From sConfig.tConfigurationSetup WHERE ConfigurationId = 496 AND SourceTypeId = 1016 AND SourceId = @rOrgId
 
--#TempAllExam
	CREATE TABLE #TempAllExam
	(
		AcademicIdText nvarchar(20),
		ExamIdText nvarchar(20),
		CoScholasticScopeIdText nvarchar(20),
		
		AcademicId bigint,
		ExamName Nvarchar(150),
		StudCode NVarchar(20),
		StudentName Nvarchar(150),
		RollNo int,
		
		ResultStatus Nvarchar(50),	
		
		ClassName NVarchar(100),
				
		Division NVarchar(100),
		TotalMark decimal(8,2),
		TotalObtain decimal(8,2),
		Percentage decimal(8,2),
		RankNumber int,
		ResultGrade NVarchar(50),
		
		--MaximumMark1 decimal(8,2),		
		SubjectGrade1 NVarchar(50),
		--Obtain1 decimal(8,2),
		--ExamMaximum1 decimal(8,2),
		IsPresent1 bit,
						
		MaximumMark2 decimal(8,2),	
		SubjectGrade2 NVarchar(50),
		Obtain2 decimal(8,2),
		ExamMaximum2 decimal(8,2),
		IsPresent2 bit,
				
		MaximumMark3 decimal(8,2),
		SubjectGrade3 NVarchar(50),
		Obtain3 decimal(8,2),
		ExamMaximum3 decimal(8,2),
		IsPresent3 bit,		
		
		MaximumMark4 decimal(8,2),	
		SubjectGrade4 NVarchar(50),
		Obtain4 decimal(8,2),
		ExamMaximum4 decimal(8,2),
		IsPresent4 bit,	
				
		MaximumMark5 decimal(8,2),		
		SubjectGrade5 NVarchar(50),
		Obtain5 decimal(8,2),
		ExamMaximum5 decimal(8,2),
		IsPresent5 bit,	
				
		MaximumMark6 decimal(8,2),		
		SubjectGrade6 NVarchar(50),
		Obtain6 decimal(8,2),
		ExamMaximum6 decimal(8,2),
		IsPresent6 bit,	
		
		MaximumMark7 decimal(8,2),		
		SubjectGrade7 NVarchar(50),
		Obtain7 decimal(8,2),
		ExamMaximum7 decimal(8,2),
		IsPresent7 bit,	
		
		MaximumMark8 decimal(8,2),	
		SubjectGrade8 NVarchar(50),
		Obtain8 decimal(8,2),
		ExamMaximum8 decimal(8,2),
		IsPresent8 bit,	
		
		SubjectGradeTerm1 NVarchar(50),
		SubjectGradeTerm2 NVarchar(50),
		IsMarksInDecimal bit,
		column_visible bit,
		--Obtain decimal(5,2),
		Percentile decimal(5,2),
		--ClassSubject nvarchar(100),
		ResultDetailId bigint,
		ResultId bigint,	
		Remark1 nvarchar(1000),
		
		Remark2 nvarchar(300),
		Remark3 nvarchar(300),
		DisplayTitle nvarchar(150),		
		IsRankNo bit, 
		IsGrade bit,
		IsPercentile bit,
		IsPercentage bit,
		IsSubjectPercentile bit,
		IsProcessResult bit,
		IsNegativeMarks bit,
		IsIncludeCoScholastic bit,
		IsOnPrePrinted bit,
		IsDisplayPhoto bit,
		IsDisplayBirthDate bit,
		IsLockForEdit bit,
		IsDisplaySchoolName bit,			
		IsDisplayAttendance bit,
		IsDisplayHeightWeight bit,
		IsResultStatus bit,
		FooterAdjustmentText nvarchar(max),
		DetailAdjustmentText nvarchar(max),
		FooterAdjustment smallint,
		DetailAdjustment smallint,
		ResultRemark nvarchar(200),
		DateOfBirth date,
		HeightTerm1 decimal(5,2),
		WeightTerm1 decimal(5,2),
		HeightTerm2 decimal(5,2),
		WeightTerm2 decimal(5,2),
		HeightAnnual decimal(5,2),
		WeightAnnual decimal(5,2),
		PresentDaysTerm1 smallint,
		PresentDaysTerm2 smallint,
		PresentDaysAnnual smallint,
		TotalDaysTerm1 smallint,
		TotalDaysTerm2 smallint,
		TotalDaysAnnual smallint,
		TotalMarkTerm1 decimal(8,2),
		TotalObtainTerm1 decimal(8,2),
		PercentageTerm1 decimal(8,2),
		RankNumberTerm1 int,
		ResultGradeTerm1 NVarchar(50),
		PercentileTerm1 decimal(8,2),
		ResultStatusTerm1 Nvarchar(20),		   
		TotalMarkTerm2 decimal(8,2),
		TotalObtainTerm2 decimal(8,2),
		PercentageTerm2 decimal(8,2),
		RankNumberTerm2 int,
		ResultGradeTerm2 NVarchar(50),
		PercentileTerm2 decimal(8,2),
		ResultStatusTerm2 Nvarchar(20), 
		TermScopeId tinyint,		 
		StudentPhoto varbinary(max),
		GradeString nvarchar(1000),
		IsDisplayGradeString bit,		 
		IsDisplayInMarksheet bit,
		IsShowSubjectGrade bit,
		IsIncludeInTotal bit,
		ClassSubjectID int,
		SubjectId int,
		--Maximum decimal(5,2),
		SubjectOrderIndex smallint,
		SubjectGrade NVarchar(50),
		SubjectName NVarchar(150),
		SubjectCode Nvarchar(50),	
		SubjectMinimum decimal(8,2),		
		SubjectMaximum decimal(8,2),
		SubjectObtain  decimal(8,2),
		
		Exam1Name Nvarchar(150),		
		TotalMarks1 decimal(8,2),		
		TotalObtain1 decimal(8,2),
		Percentage1 decimal(8,2),
		RankNumber1 int,
		ResultGrade1 NVarchar(50),
		Percentile1 decimal(8,2),
		ResultStatus1 Nvarchar(20),
		
		SubActivityGrade1 nvarchar(50),
		ActivityGrade1 nvarchar(50),
		
		Exam2Name nvarchar(150),	
		TotalMarks2 decimal(8,2),
		TotalObtain2 decimal(8,2),
		Percentage2 decimal(8,2),
		RankNumber2 int,
		ResultGrade2 NVarchar(50),
		Percentile2 decimal(8,2),
		ResultStatus2 Nvarchar(20),
		
		SubActivityGrade2 nvarchar(50),
		ActivityGrade2 nvarchar(50),
		
		Exam3Name nvarchar(150),	
		TotalMarks3 decimal(8,2),
		TotalObtain3 decimal(8,2),
		Percentage3 decimal(8,2),
		RankNumber3 int,
		ResultGrade3 NVarchar(50),
		Percentile3 decimal(8,2),		
		ResultStatus3 Nvarchar(20),
		
		SubActivityGrade3 nvarchar(50),
		ActivityGrade3 nvarchar(50),
		
		Exam4Name nvarchar(150),	
		TotalMarks4 decimal(8,2),
		TotalObtain4 decimal(8,2),
		Percentage4 decimal(8,2),
		RankNumber4 int,
		ResultGrade4 NVarchar(50),
		Percentile4 decimal(8,2),
		ResultStatus4 Nvarchar(20),
		
		SubActivityGrade4 nvarchar(50),
		ActivityGrade4 nvarchar(50),
		
		Exam5Name nvarchar(150),		
		TotalMarks5 decimal(8,2),
		TotalObtain5 decimal(8,2),
		Percentage5 decimal(8,2),
		RankNumber5 int,
		ResultGrade5 NVarchar(50),
		Percentile5 decimal(8,2),
		ResultStatus5 Nvarchar(20),
		
		SubActivityGrade5 nvarchar(50),
		ActivityGrade5 nvarchar(50),
		
		Exam6Name nvarchar(150),	
		TotalMarks6 decimal(8,2),
		TotalObtain6 decimal(8,2),
		Percentage6 decimal(8,2),
		RankNumber6 int,
		ResultGrade6 NVarchar(50),
		Percentile6 decimal(8,2),
		ResultStatus6 Nvarchar(20),
		
		SubActivityGrade6 nvarchar(50),
		ActivityGrade6 nvarchar(50),
		
		Exam7Name nvarchar(150),		
		TotalMarks7 decimal(8,2),
		TotalObtain7 decimal(8,2),
		Percentage7 decimal(8,2),
		RankNumber7 int,
		ResultGrade7 NVarchar(50),
		Percentile7 decimal(8,2),
		ResultStatus7 Nvarchar(20),
		
		--SubActivityGrade7 nvarchar(10),
		
		Exam8Name nvarchar(150),
		TotalMarks8 decimal(8,2),
		TotalObtain8 decimal(8,2),
		Percentage8 decimal(8,2),
		RankNumber8 int,
		ResultGrade8 NVarchar(50),
		Percentile8 decimal(8,2),
		ResultStatus8 Nvarchar(20),
		ResultRemark1 nvarchar(200),
		ResultRemark2 nvarchar(200),
		TotalDays decimal(6, 2),
		PresentDays decimal(6, 2),
		StudentHeight decimal(6,2),
		StudentWeight decimal(6,2),
		ExamSeatNo nvarchar(20),
		ExamId int,
		IsDisplayParentName bit,
		
		FatherName nvarchar(100),
		MotherName nvarchar(100),
		IsShowSubjectMark bit, 
		IsOptionalSubject bit,
		CoScholasticScopeId tinyint,
		IsDisplayPrincipalSign bit,
		IsDisplayTeacherSign bit,
		EmployeeSign varbinary(max),
		
		ActivityName nvarchar(200),
		SubActivityName nvarchar(200),
		SubActivityId int,
		ActivityId Int,
		 SubActivityGrade nvarchar(50),
		 ActivityGrade nvarchar(50),
		SubActivityGradeIndicator nvarchar(50),
		SubActivityDescriptiveIndicator nvarchar(200),
		SubjectActivityOrderIndex Smallint,
		SubActivityOrderIndex smallint,
		ColumnSubjectCount SmallInt,
		MarksheetHeaderA4 varbinary(max),
		IsImageHeader bit,
		Height1 decimal(6,2),
		Height2 decimal(6,2),
		Height3 decimal(6,2),
		Height4 decimal(6,2),
		Height5 decimal(6,2),
		Height6 decimal(6,2),
		Weight1 decimal(6,2),
		Weight2 decimal(6,2),
		Weight3 decimal(6,2),
		Weight4 decimal(6,2),
		Weight5 decimal(6,2),
		Weight6 decimal(6,2),
		TotalDays1 decimal(6, 2),
		PresentDays1 decimal(6, 2),
		TotalDays2 decimal(6, 2),
		PresentDays2 decimal(6, 2),
		TotalDays3 decimal(6, 2),
		PresentDays3 decimal(6, 2),
		TotalDays4 decimal(6, 2),
		PresentDays4 decimal(6, 2),
		TotalDays5 decimal(6, 2),
		PresentDays5 decimal(6, 2),
		TotalDays6 decimal(6, 2),
		PresentDays6 decimal(6, 2),
		MyActivity1 nvarchar(200),
		MyActivity2 nvarchar(200),
		MyActivity3 nvarchar(200),
		MyActivity4 nvarchar(200),
		MyActivity5 nvarchar(200),
		MyActivity6 nvarchar(200),
		GeneralRemark1 nvarchar(200),
		GeneralRemark2 nvarchar(200),
		GeneralRemark3 nvarchar(200),
		GeneralRemark4 nvarchar(200),
		GeneralRemark5 nvarchar(200),
		GeneralRemark6 nvarchar(200),
		PresentAddress nvarchar(500) ,
		MobileNo nvarchar(50),
		House nvarchar(100),
		 
		AttendanceTerm1 decimal(6, 2) ,
		AttendanceTerm2 decimal(6, 2),
		WorkingDaysTerm1 decimal(6, 2),
		WorkingDaysTerm2 decimal(6, 2),
		
		BloodGroup nvarchar(20),
		GradeSetIdText nvarchar(50),
		IsDisplayMonthlyAttendanceText nvarchar(20),
		DentalHygiene nvarchar(200),
		VisionLeft nvarchar(50),
		VisionRight nvarchar(50),
		TeacherSignCaption nvarchar(100),
		PrincipalSignCaption nvarchar(100),
		ParentSignCaption nvarchar(100),
		ParentEmail nvarchar(500),
		MyGoal nvarchar(200),
		MyStrength nvarchar(200),
		MyInterestHobby nvarchar(200),
		AreaOfInterest nvarchar(200),
		Responsibility nvarchar(200),
		Achievements nvarchar(1000),
		ImprovementArea nvarchar(200),
		ProgressArea nvarchar(200),
		MyActivity nvarchar(200),
		ClassTeacherRemark nvarchar(1000),
		ClassTeacherName Nvarchar(100),
		HouseRemark nvarchar(1000),
		GeneralRemark nvarchar(1000),
		FatherContactNo nvarchar(50),
		MotherContactNo nvarchar(50),
		FatherMail nvarchar(max),
		MotherMail nvarchar(max),
		IsDecimal bit,
		Name nvarchar(150)
	)	
	
	 --print 'temp created'    	
	INSERT INTO  #TempAllExam 
	(
	AcademicIdText,
	ExamIdText,
	CoScholasticScopeIdText,
	
	AcademicId,
	ExamName,
	StudCode,
	StudentName,
	RollNo,
	ResultStatus,
	ClassName,
	Division,
	TotalMark,
	TotalObtain,
	Percentage,
	RankNumber,
	ResultGrade,
	IsMarksInDecimal,
	column_visible,
	--Obtain,
	Percentile,
	--ClassSubject,
	ResultDetailId,
	ResultId,

	Remark1,
	Remark2,
    Remark3,
	DisplayTitle,
	IsRankNo, 
	IsGrade,
	IsPercentile,
	IsPercentage,
	IsSubjectPercentile,
	IsProcessResult,
	IsNegativeMarks,
	IsIncludeCoScholastic,
	IsOnPrePrinted,
	IsDisplayPhoto,
	IsDisplayBirthDate,
	IsLockForEdit,
	IsDisplaySchoolName,			
	IsDisplayAttendance,
	IsDisplayHeightWeight,
	IsResultStatus,
	FooterAdjustmentText,
	DetailAdjustmentText,
	FooterAdjustment,
	DetailAdjustment,
	ResultRemark,
	DateOfBirth,
	HeightTerm1,
	WeightTerm1,
	HeightTerm2,
	WeightTerm2,
	HeightAnnual,
	WeightAnnual,
	PresentDaysTerm1,
	PresentDaysTerm2,
	PresentDaysAnnual,
	TotalDaysTerm1,
	TotalDaysTerm2,
	TotalDaysAnnual,
	TermScopeId,
	StudentPhoto,
	GradeString,
	IsDisplayGradeString,	 
	IsDisplayInMarksheet,
	IsShowSubjectGrade,
	IsIncludeInTotal,
	ClassSubjectID,
	SubjectId,
	--Maximum,
	SubjectOrderIndex,
	SubjectGrade,
	SubjectName,
	SubjectCode,
	SubjectMinimum,
	SubjectMaximum,
	SubjectObtain,
	ResultRemark1,
	ResultRemark2,
	TotalDays,
	PresentDays,
	StudentHeight,
	StudentWeight,
	ExamSeatNo,
	ExamId,
	IsDisplayParentName,
	FatherName,
	MotherName,
	IsShowSubjectMark,
	IsOptionalSubject,
	CoScholasticScopeId,
	IsDisplayPrincipalSign,
	IsDisplayTeacherSign,
	EmployeeSign,
	SubActivityGrade,
	ActivityGrade,
	ActivityName,
	SubActivityName,
	SubActivityId,
	ActivityId,
	SubActivityGradeIndicator,
	SubActivityDescriptiveIndicator,
	SubjectActivityOrderIndex,
	SubActivityOrderIndex,
	ColumnSubjectCount,
	MarksheetHeaderA4,
	IsImageHeader,
	PresentAddress,
 	MobileNo,
	House,
	AttendanceTerm1   ,
	AttendanceTerm2  ,
	WorkingDaysTerm1  ,
	WorkingDaysTerm2  ,
	BloodGroup,
	GradeSetIdText,
	IsDisplayMonthlyAttendanceText,
	DentalHygiene,
	VisionLeft,
	VisionRight,
	TeacherSignCaption,
	PrincipalSignCaption,ParentSignCaption,
	ParentEmail,
	MyGoal ,
	MyStrength ,
	MyInterestHobby ,
	AreaOfInterest ,
	Responsibility ,
	Achievements ,
	ImprovementArea ,
	ProgressArea ,
	MyActivity ,
	ClassTeacherRemark ,
	ClassTeacherName ,
	HouseRemark ,
	GeneralRemark ,
	FatherContactNo ,
	MotherContactNo ,
	FatherMail,
	MotherMail,
	IsDecimal,
	Name
	)
	
	SELECT 
		Convert(nvarchar(20),A.Id),
		Convert(nvarchar(20),@rExamId),
		Convert(nvarchar(20),EM.CoScholasticScopeId),
		A.Id,
		ISNULL(ESGM.Title,'') AS EXAMNAME,
		StuM.Code AS StudCode,
		StuM.FirstName+' '+StuM.MiddleName+' '+StuM.LastName AS StudentName,
		A.RollNo,
		R.ResultStatus,
		CM.DisplayTitle AS ClassName,
		DM.DisplayTitle AS Division,
		R.TotalMarks AS TotalMark,
		R.TotalObtain,
		R.Percentage,
		R.RankNumber,
		R.ResultGrade,


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

		ISNULL(EM.Remark1,'') AS Remark1,
		ISNULL(EM.Remark2,'') AS Remark2,
		ISNULL(EM.Remark3,'') AS Remark3,
		EM.DisplayTitle,
		EM.IsRankNo, 
		EM.IsGrade,
		EM.IsPercentile,
		EM.IsPercentage,
		EM.IsSubjectPercentile,
		EM.IsProcessResult,
		EM.IsNegativeMarks,
		EM.IsIncludeCoScholastic,
		EM.IsOnPrePrinted,
		EM.IsDisplayPhoto,
		EM.IsDisplayBirthDate,
		EM.IsLockForEdit,
		EM.IsDisplaySchoolName,			
		EM.IsDisplayAttendance,
		EM.IsDisplayHeightWeight,
		EM.IsResultStatus,
		REPLICATE(',',EM.FooterAdjustment) AS FooterAdjustmentText,
		REPLICATE(',',EM.DetailAdjustment) AS DetailAdjustmentText,
		EM.FooterAdjustment,
		EM.DetailAdjustment,
		ISNULL(R.ResultRemark,'') AS ResultRemark,
		SO.DateOfBirth,
		AD.HeightTerm1,
		AD.WeightTerm1,
		AD.HeightTerm2,
		AD.WeightTerm2,
		AD.HeightAnnual,
		AD.WeightAnnual,
		AD.PresentDaysTerm1,
		AD.PresentDaysTerm2,
		AD.PresentDaysAnnual,
		AD.TotalDaysTerm1,
		AD.TotalDaysTerm2,
		AD.TotalDaysAnnual,
		EM.TermScopeId,
		CASE WHEN EM.IsDisplayPhoto = 1 THEN SI.StudentPhoto ELSE NULL END AS StudentPhoto,
		CASE @GradeStringRemark WHEN '' THEN @GradeString ELSE @GradeStringRemark END AS GradeString,
		EM.IsDisplayGradeString,
		ED.IsDisplayInMarksheet,
		ED.IsShowSubjectGrade,
		ED.IsIncludeInTotal,
	    SAM.ClassSubjectId,
		CS.SubjectId AS SubjectId,
		--ED.Maximum,
		(CASE ISNULL(ED.DisplayOrder,0)
		WHEN 0 THEN CS.OrderIndex
		ELSE ED.DisplayOrder END) AS SubjectOrderIndex,
		
		--SM.OrderIndex AS SubjectOrderIndex,
		RD.SubjectGrade,
		SM.Title AS SubjectName,
		ISNULL(SM.Code,'') AS SubjectCode,
		ED.Minimum,
		ED.Maximum,
		RD.Obtain,
		SR.ResultRemark1,
		SR.ResultRemark2,
		ISNULL(SR.TotalDays,0)AS TotalDays,
		ISNULL(SR.PresentDays,0)AS PresentDays,
		SR.StudentHeight,
		SR.StudentWeight,
		SR.ExamSeatNo,
		@rExamId,
		EM.IsDisplayParentName,
		SF.FatherName,
		SF.MotherName,
		ED.IsShowSubjectMark,
		--EMP.FirstName
		(CASE ISNULL(OS.AcademicId,0)
		WHEN 0 THEN 0
		ELSE 1 END) AS IsOptionalSubject,
		EM.CoScholasticScopeId,
		EM.IsDisplayPrincipalSign,
		Em.IsDisplayTeacherSign,
		EI.EmployeeSign,
		SSA.Grade AS SubActivityGrade,
		ISNULL(SAS.Grade,'') AS ActivityGrade,
		SAM.Title AS ActivityName,
		SSAM.Title AS SubActivityName,
		SSA.SubjectSubActivityId AS SubActivityId,
		SAM.Id AS ActivityId,
		SSA.GradeIndicator AS SubActivityGradeIndicator,
		SSA.DescriptiveIndicator AS SubActivityDescriptiveIndicator,
		SAM.OrderIndex AS SubjectActivityOrderIndex,
		SSAM.OrderIndex AS SubActivityOrderIndex,
		CASE WHEN CS.OrderIndex % 2 = 0 THEN 2 
				ELSE 1 END   AS   ColumnSubjectCount,
		(CASE EM.IsDisplayImageHeader WHEN 1 THEN
			OI.MarksheetHeaderA4
			ELSE NULL END)AS  MarksheetHeaderA4,
		ISNULL(EM.IsDisplayImageHeader,0) AS IsImageHeader	,
		ISNULL(SC.PresentStreetONe,'')+' '+ISNULL(SC.PresentStreetTwo,'')+' '+ISNULL(SC.PresentStreetThree,'')+' '+ISNULL(SC.PresentCity,'')+' '+ISNULL(SC.PresentState,'') AS PresentAddress,
		 SC.ParentContactNo,
		ISNULL(HM.Title,'') AS House,
		ISNULL(CCER.AttendanceTerm1,0) AS AttendanceTerm1,
		ISNULL(CCER.AttendanceTerm2,0) AS AttendanceTerm2,
		ISNULL(CCER.WorkingDaysTerm1,0) AS WorkingDaysTerm1,
		ISNULL(CCER.WorkingDaysTerm2,0) AS WorkingDaysTerm2,
		ISNULL(BGM.Title,'') AS BloodGroup,
		CONVERT (nvarchar(50),EM.GradeSetId) AS GradeSetIdText,
		Convert(nvarchar(20),ISNULL(EM.IsDisplayMonthlyAttendance,0)) AS IsDisplayMonthlyAttendanceText,
		ISNULL(SR.DentalHygiene,'') AS DentalHygiene,
		ISNULL(SR.VisionLeft,'') AS VisionLeft,
		ISNULL(SR.VisionRight,'') AS VisionRight,
		--CASE WHEN EM.IsDisplayTeacherSign = 1 THEN EM.TeacherSignCaption ELSE NULL END AS TeacherSignCaption,
		--CASE WHEN EM.IsDisplayPrincipalSign = 1 THEN EM.PrincipalSignCaption ELSE NULL END AS PrincipalSignCaption,
		ISNULL(EM.TeacherSignCaption,'') AS TeacherSignCaption,
		ISNULL(EM.PrincipalSignCaption,'') AS PrincipalSignCaption,
		ISNULL(ParentSignCaption,'') AS ParentSignCaption,
		SC.ParentEmail As ParentEmail,
		ISNULL(SR.MyGoal,'') AS MyGoal,
		ISNULL(SR.MyStrength,'') AS MyStrength,
		ISNULL(SR.MyInterestHobby,'') AS MyInterestHobby,
		ISNULL(SR.AreaOfInterest,'') AS AreaOfInterest,
		ISNULL(SR.Responsibility,'') AS Responsibility,
		ISNULL(SR.Achievements,'') AS Achievements,
		ISNULL(SR.ImprovementArea,'') As ImprovementArea,
		ISNULL(SR.ProgressArea,'') AS ProgressArea,
		ISNULL(SR.MyActivity,'') AS MyActivity,
		ISNULL(SR.ClassTeacherRemark,'') As ClassTeacherRemark,
		EMP.FirstName + ' ' + EMP.LastName AS ClassTeacherName,
		ISNULL(SR.HouseRemark,'') As HouseRemark,
		ISNULL(SR.GeneralRemark,'') As GeneralRemark,
		SF.FatherContactNo,
		SF.MotherContactNo,
		SF.FatherMail,
		SF.MotherMail,
		CONVERT(bit,@lDecimalConfig) AS IsDecimal,
		[sStudent].[fStudentNameGet](stum.FirstName , StuM.MiddleName, StuM.LastName,OM.StudentNameFormatId ) AS Name
	FROM 
		sAssessment.tCCESubjectSubActivityExamScore SSA
		INNER JOIN sAssessment.tCCESubjectSubActivityMaster SSAM ON SSAM.Id = SSA.SubjectSubActivityId
		INNER JOIN sAssessment.tCCESubjectActivityMaster SAM ON SAM.Id = SSAM.SubjectActivityId
		LEFT JOIN sAssessment.tCCESubjectActivityExamScore SAS ON SAS.SubjectActivityId= SAM.Id AND SSA.AcademicId = SAS.AcademicId AND SSA.ExamId = SAS.ExamId
		INNER JOIN sSetup.tClassSubject CS ON CS.Id=SAM.ClassSubjectId	
		INNER JOIN sAssessment.tExamMaster EM ON EM.Id=SSA.ExamId
		INNER JOIN sAssessment.tExamDetail ED ON EM.Id=ED.ExamId AND ED.ClassSubjectId = SAM.ClassSubjectId
		--INNER JOIN sSetup.tClassSubject CS ON CS.Id=SAM.ClassSubjectId
		INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=CS.SubjectId					 
    	INNER JOIN sStudent.tAcademic  A ON   SSA.AcademicId = A.Id
		LEFT JOIN sAssessment.tCCEResult CCER    ON  CCER.AcademicId=A.Id
		INNER JOIN sStudent.tStudentMaster StuM ON StuM.Id=A.StudentId
		INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId
		INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId
		LEFT JOIN sHrm.tEmployeeMaster EMP ON EMP.Id = DM.InchargeEmployeeId
		LEFT JOIN sHrm.tEmployeeImages EI ON EI.EmployeeId = Dm.InchargeEmployeeId
		INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id = EM.EXAMSUBGROUPID
		LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId=StuM.Id
		LEFT JOIN sCommon.tBloodGroupMaster BGM ON BGM.Id=SO.BloodGroupId
		LEFT JOIN sStudent.tAcademicDetail AD ON AD.AcademicId=A.Id
		LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId=StuM.Id
		LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId = StuM.Id
		LEFT JOIN sAssessment.tOptionalSubject OS ON OS.AcademicId = A.Id AND OS.ClassSubjectId = ED.ClassSubjectId  
		LEFT JOIN sAssessment.tResult R ON R.AcademicId = SSA.AcademicId AND R.ExamId = SSA.ExamId
		LEFT JOIN sAssessment.tResultDetail RD  ON R.Id = RD.ResultId AND ED.ID = RD.ExamDetailId 
		LEFT JOIN sAssessment.tStudentRemark SR ON A.Id = SR.AcademicId AND EM.Id = SR.ExamId
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = StuM.OrgId
		LEFT JOIN sSetup.tOrgImages OI ON OI.OrgId = OM.Id
		LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId =Stum.ID
		LEFT JOIN sActivity.tHouseMaster HM ON HM.Id=SO.HouseId
		--LEFT JOIN sAcademic.tTeacherSubjectDivision TSD ON TSD.SubjectId=SM.Id AND TSD.DivisionId = A.DivisionId
		--LEFT JOIN sHrm.tEmployeeMaster EMP ON TSD.EmployeeId = EMP.Id
	
	 WHERE
		SSA.ExamId = @rExamId 
		AND ((A.DivisionId =  @rDivisionId) OR (@rDivisionId=0))
		AND ((A.ClassId =  @rClass) OR (@rClass=0))		 
		AND ((A.BatchId =  @rBatchId) OR (@rBatchId=0))
		AND ((A.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
		AND ((A.RollNo <= @rToRollNo) OR (@rToRollNo=0))
		--AND ((R.RankNumber >= @rFromRank) OR (@rFromRank=0))
		--AND ((R.RankNumber <= @rToRank) OR (@rToRank=0))
		--AND ((R.ResultGrade = @rGrade) OR (@rGrade=''))
		AND ((StuM.Code=@rCode) OR (@rCode=''))	
		--AND ((R.Id = @rResultId) OR (@rResultId = 0))	
		--AND ((StuM.StatusId=@rStatusId)OR(@rStatusId=0))
		AND((A.Id=@rAcademicId)OR (@rAcademicId=0))
		--AND ((CS.SubjectId=@rSubjectId) OR(@rSubjectId=0) ) 
		 AND (ISNULL(StuM.Code,0) IN( SELECT cast(item as nvarchar(20)) FROM  sCommon.fnsplit(@rMultiCode,',')) OR @rMultiCode='')
	 
	Order By ED.DisplayOrder
 
	
 --print 'temp insert'
  --SET @IsIncludeSubExam = 1
	create TABLE #tempcombineExam
	(	Id int IDENTITY,
		ExamID int )

	IF (@IsIncludeSubExam = 0)
	BEGIN	
	INSERT INTO #tempcombineExam (ExamID) 
	SELECT SUBEXAMID FROM sAssessment.tExamCombine WHERE ExamId  = @rExamId Order By ExamOrder ASC
 	END
 	ELSE
 	BEGIN
 	-- if we want to display result for both the term with all exam select this option
 	INSERT INTO #tempcombineExam (ExamID) 
	SELECT C.SUBEXAMID FROM sAssessment.tExamCombine C
	INNER JOIN (SELECT SUBEXAMID,ExamOrder FROM sAssessment.tExamCombine WHERE ExamId  = @rExamId) E
	ON C.SubExamId = E.SubExamId
	ORDER BY E.ExamOrder,C.ExamOrder
	END
	 
	--ON 
	
	-- Order By ExamOrder ASC
	--WHERE ExamId in (SELECT SUBEXAMID FROM sAssessment.tExamCombine WHERE ExamId  = @rExamId Order By ExamOrder ASC)
	
	DECLARE @lCount int,@query  AS NVARCHAR(MAX),@lSubExamId int,@lCount1 int  
	Select @lCount = MAX(Id) from #tempcombineExam	
	DECLARE @ExamTitle nvarchar(150)
	while (@lCount > 0)
	begin
		select @lSubExamId = ExamID from #tempcombineExam Where Id = @lCount
		--select @ExamTitle = Title from sAssessment.tExamMaster Where Id = @lSubExamId	
		
		set @query ='update T SET
					
					 IsPresent' + convert(nvarchar(15),@lCount)+'=RD.IsPresent,					
					 SubjectGrade' + convert(nvarchar(15),@lCount)+ '=RD.SubjectGrade,
					 Exam' + convert(nvarchar(15),@lCount)+ 'Name=ESGM.Title,
					 Height' + convert(nvarchar(15),@lCount)+ '=SR.StudentHeight,
					 Weight' + convert(nvarchar(15),@lCount)+ '=SR.StudentWeight,				
					 TotalDays'+convert(nvarchar(15),@lCount)+'=SR.TotalDays,
					 PresentDays'+convert(nvarchar(15),@lCount)+'=SR.PresentDays,
					 MyActivity'+convert(nvarchar(15),@lCount)+'=SR.MyActivity,
					 GeneralRemark'+convert(nvarchar(15),@lCount)+'=SR.GeneralRemark 
					 									
					 From
						 
						 sAssessment.tResult R 
						INNER JOIN  sAssessment.tResultDetail RD ON RD.ResultId = R.Id						
						INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
						INNER JOIN sAssessment.tExamSubgroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId					
						INNER JOIN 	#TempAllExam  T ON T.ClassSubjectID = ED.ClassSubjectId And T.AcademicId = R.AcademicId	
						LEFT JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND T.AcademicId = SR.AcademicId 							
						WHERE EM.Id =' + convert(nvarchar(15), @lSubExamId)  
						
	
	 execute(@query)
 
	 set @query ='update T SET
					
					 
					 SubActivityGrade' + convert(nvarchar(15),@lCount)+ '=SSA.Grade	
					 						
					 From
						sAssessment.tCCESubjectSubActivityExamScore SSA				
						inner JOIN 	#TempAllExam  T ON T.SubActivityId = SSA.SubjectSubActivityId And T.AcademicId = SSA.AcademicId	 					
						WHERE SSA.ExamId =' + convert(nvarchar(15), @lSubExamId)  
						
	
 --PRINT(@QUERY)	
   EXECUTE(@query)
 
  set @query ='update T SET
					
					  ActivityGrade' + convert(nvarchar(15),@lCount)+ '=SAS.Grade	
					 						
					 From
						sAssessment.tCCESubjectActivityExamScore SAS				
						inner JOIN 	#TempAllExam  T ON T.ActivityId = SAS.SubjectActivityId And T.AcademicId = SAS.AcademicId	 					
						WHERE SAS.ExamId =' + convert(nvarchar(15), @lSubExamId)  
						
	
 --PRINT(@QUERY)	
   EXECUTE(@query)
	-- set @query ='update T SET
					
	--				 Height' + convert(nvarchar(15),@lCount)+ '=SR.StudentHeight,
	--				 Weight' + convert(nvarchar(15),@lCount)+ '=SR.StudentWeight,				
	--				 TotalDays'+convert(nvarchar(15),@lCount)+'=SR.TotalDays,
	--				 PresentDays'+convert(nvarchar(15),@lCount)+'=SR.PresentDays,
	--				 MyActivity'+convert(nvarchar(15),@lCount)+'=SR.MyActivity,
	--				 GeneralRemark'+convert(nvarchar(15),@lCount)+'=SR.GeneralRemark
	--				 From
	--					sAssessment.tCCESubjectSubActivityExamScore SSA
						
	--					inner JOIN sAssessment.tCCESubjectSubActivityMaster SSAM ON SSAM.Id = SSA.SubjectSubActivityId
	--					inner JOIN sAssessment.tCCESubjectActivityMaster SAM ON SAM.Id = SSAM.SubjectActivityId
	--					INNER JOIN sAssessment.tExamMaster EM ON EM.Id=SSA.ExamId
	--					inner JOIN 	#TempAllExam  T ON T.SubActivityId = SSA.SubjectSubActivityId And T.AcademicId = SSA.AcademicId	
	--					LEFT JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND T.AcademicId = SR.AcademicId 					
	--					WHERE EM.Id =' + convert(nvarchar(15), @lSubExamId)  
						
	
 ----PRINT(@QUERY)	
 --  EXECUTE(@query)
	
						
		/*	set @query ='update T set 
				    TotalMarks' + convert(nvarchar(15),@lCount)+ '=R.TotalMarks,
					TotalObtain' + convert(nvarchar(15),@lCount)+ '=R.TotalObtain,
					Percentage' + convert(nvarchar(15),@lCount)+ '=R.Percentage,
					RankNumber' + convert(nvarchar(15),@lCount)+'=R.RankNumber,
					ResultGrade' + convert(nvarchar(15),@lCount)+'=R.ResultGrade,
					Percentile' + convert(nvarchar(15),@lCount)+'=R.Percentile,
					ResultStatus' + convert(nvarchar(15),@lCount)+'=R.ResultStatus,
					Exam' + convert(nvarchar(15),@lCount)+ 'Name=ESGM.Title,
					ExamMaximum' + convert(nvarchar(15),@lCount)+'=EM.ExamMaximum
					 From						
						sAssessment.tResult R						
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id=R.ExamId
						INNER JOIN sAssessment.tExamSubgroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId					
						INNER JOIN 	#TempAllExam  T ON  T.AcademicId = R.AcademicId						
						WHERE EM.Id =' + convert(nvarchar(15), @lSubExamId)  
						
	execute(@query)*/
		
		
	set @lCount = @lCount -1
	end
	SELECT @rBuilder1 , T.*
	FROM #TempAllExam T
	
	
		
	drop table #tempcombineExam
	Drop table #TempAllExam

	--Select 
	-- '' As AcademicIdText,
	--	'' As ExamIdText,
	--	'' As CoScholasticScopeIdText ,
		
	--	CONVERT(bigint , 0) As AcademicId,
	--	'' As ExamName,
	--	'' As StudCode,
	--	'' As StudentName ,
	--	0 As RollNo,
	--	'' As ResultStatus ,	
	--	'' As ClassName ,		
	--	'' As Division ,
	--	CONVERT(decimal , 0) As TotalMark ,
	--	CONVERT(decimal , 0) As TotalObtain,
	--	CONVERT(decimal , 0) As Percentage ,
	--	0 As RankNumber ,
	--	'' As ResultGrade ,
		
	--	--MaximumMark1 decimal(8,2),		
	--	'' As SubjectGrade1 ,
	--	--Obtain1 decimal(8,2),
	--	--ExamMaximum1 decimal(8,2),
	--	CONVERT(bit , 0) As IsPresent1,
						
	--	CONVERT(decimal , 0) As MaximumMark2 ,	
	--	'' As SubjectGrade2 ,
	--	CONVERT(decimal , 0) As Obtain2 ,
	--	CONVERT(decimal , 0) As ExamMaximum2 ,
	--	CONVERT(bit , 0) As IsPresent2,
				
	--	CONVERT(decimal , 0) As MaximumMark3 ,
	--	'' As SubjectGrade3 ,
	--	CONVERT(decimal , 0) As Obtain3 ,
	--	CONVERT(decimal , 0) As ExamMaximum3 ,
	--	CONVERT(bit , 0) As IsPresent3 ,		
		
	--	CONVERT(decimal , 0) As MaximumMark4 ,	
	--	'' As SubjectGrade4 ,
	--	CONVERT(decimal , 0) As Obtain4 ,
	--	CONVERT(decimal , 0) As ExamMaximum4 ,
	--	CONVERT(bit , 0) As IsPresent4 ,	
				
	--	CONVERT(decimal , 0) As MaximumMark5 ,		
	--	'' As SubjectGrade5 ,
	--	CONVERT(decimal , 0) As Obtain5 ,
	--	CONVERT(decimal , 0) As ExamMaximum5 ,
	--	CONVERT(bit , 0) As IsPresent5 ,	
				
	--	CONVERT(decimal , 0) As MaximumMark6 ,		
	--	'' As SubjectGrade6,
	--	CONVERT(decimal , 0) As Obtain6 ,
	--	CONVERT(decimal , 0) As ExamMaximum6 ,
	--	CONVERT(bit , 0) As IsPresent6 ,	
		
	--	CONVERT(decimal , 0) As MaximumMark7 ,		
	--	'' As SubjectGrade7,
	--	CONVERT(decimal , 0) As Obtain7 ,
	--	CONVERT(decimal , 0) As ExamMaximum7 ,
	--	CONVERT(bit , 0) As IsPresent7 ,	
	
	--	CONVERT(decimal , 0) As MaximumMark8 ,	
	--	'' As SubjectGrade8,
	--	CONVERT(decimal , 0) As Obtain8 ,
	--	CONVERT(decimal , 0) As ExamMaximum8 ,
	--	CONVERT(bit , 0) As IsPresent8 ,	
		
	--	'' As SubjectGradeTerm1,
	--	'' As SubjectGradeTerm2 ,
	--	CONVERT(bit , 0) As IsMarksInDecimal ,
	--	CONVERT(bit , 0) As column_visible ,
	--	--Obtain decimal(5,2),
	--	CONVERT(decimal , 0) As Percentile,
	--	--ClassSubject nvarchar(100),
	--	CONVERT(bigint , 0) As ResultDetailId ,
	--	CONVERT(bigint , 0) As ResultId ,	
	--	'' As Remark1 ,
	--	'' As Remark2 ,
	--	'' As Remark3 ,
	--	'' As DisplayTitle ,		
	--	CONVERT(bit , 0) As IsRankNo , 
	--	CONVERT(bit , 0) As IsGrade ,
	--	CONVERT(bit , 0) As IsPercentile ,
	--	CONVERT(bit , 0) As IsPercentage ,
	--	CONVERT(bit , 0) As IsSubjectPercentile ,
	--	CONVERT(bit , 0) As IsProcessResult ,
	--	CONVERT(bit , 0) As IsNegativeMarks ,
	--	CONVERT(bit , 0) As IsIncludeCoScholastic ,
	--	CONVERT(bit,0) As IsOnPrePrinted ,
	--	CONVERT(bit , 0) As IsDisplayPhoto ,
	--	CONVERT(bit , 0) As IsDisplayBirthDate ,
	--	CONVERT(bit , 0) As IsLockForEdit ,
	--	CONVERT(bit , 0) As IsDisplaySchoolName ,			
	--	CONVERT(bit , 0) As IsDisplayAttendance ,
	--	CONVERT(bit , 0) As IsDisplayHeightWeight ,
	--	CONVERT(bit , 0) As IsResultStatus ,
	--	'' As FooterAdjustmentText ,
	--	'' As DetailAdjustmentText ,
	--	0 As FooterAdjustment ,
	--	0 As DetailAdjustment ,
	--	'' As ResultRemark ,
	--	CONVERT(Date , null) As DateOfBirth ,
	--	CONVERT(decimal , 0) As HeightTerm1 ,
	--	CONVERT(decimal , 0) As WeightTerm1 ,
	--	CONVERT(decimal , 0) As HeightTerm2,
	--	CONVERT(decimal , 0) As WeightTerm2 ,
	--	CONVERT(decimal , 0) As HeightAnnual ,
	--	CONVERT(decimal , 0) As WeightAnnual ,
	--	0 As PresentDaysTerm1,
	--	0 As PresentDaysTerm2 ,
	--	0 As PresentDaysAnnual ,
	--	0 As TotalDaysTerm1 ,
	--	0 As TotalDaysTerm2 ,
	--	0 As TotalDaysAnnual ,
	--	CONVERT(decimal , 0) As TotalMarkTerm1 ,
	--	CONVERT(decimal , 0) As TotalObtainTerm1 ,
	--	CONVERT(decimal , 0) As PercentageTerm1,
	--	0 As RankNumberTerm1 ,
	--	'' As ResultGradeTerm1,
	--	CONVERT(decimal , 0) As PercentileTerm1 ,
	--	'' As ResultStatusTerm1,		   
	--	CONVERT(decimal , 0) As TotalMarkTerm2 ,
	--	CONVERT(decimal , 0) As TotalObtainTerm2 ,
	--	CONVERT(decimal , 0) As PercentageTerm2 ,
	--	0 As RankNumberTerm2 ,
	--	'' As ResultGradeTerm2 ,
	--	CONVERT(decimal , 0) As PercentileTerm2 ,
	--	'' As ResultStatusTerm2 , 
	--	CONVERT(tinyInt , 0) As TermScopeId ,		 
	--	Convert (varbinary(max) , '') As StudentPhoto ,
	--	'' As GradeString,
	--	CONVERT(bit , 0) As IsDisplayGradeString ,		 
	--	CONVERT(bit , 0) As IsDisplayInMarksheet ,
	--	CONVERT(bit , 0) As IsShowSubjectGrade ,
	--	CONVERT(bit , 0) As IsIncludeInTotal ,
	--	0 As ClassSubjectID ,
	--	0 As SubjectId ,
	--	--Maximum decimal(5,2),
	--	0 As SubjectOrderIndex ,
	--	'' As SubjectGrade ,
	--	'' As SubjectName ,
	--	'' As SubjectCode ,	
	--	CONVERT(decimal , 0) As SubjectMinimum ,		
	--	CONVERT(decimal , 0) As SubjectMaximum ,
	--	CONVERT(decimal , 0) As SubjectObtain ,
		
	--	'' As Exam1Name ,		
	--	CONVERT(decimal , 0) As TotalMarks1 ,		
	--	CONVERT(decimal , 0) As TotalObtain1 ,
	--	CONVERT(decimal , 0) As Percentage1 ,
	--	0 As RankNumber1 ,
	--	'' As ResultGrade1,
	--	CONVERT(decimal , 0) As Percentile1 ,
	--	'' As ResultStatus1 ,
		
	--	'' As SubActivityGrade1,
	--	'' As ActivityGrade1,
		
	--	'' As Exam2Name ,	
	--	CONVERT(decimal , 0) As TotalMarks2 ,
	--	CONVERT(decimal , 0) As TotalObtain2 ,
	--	CONVERT(decimal , 0) As Percentage2 ,
	--	0 As RankNumber2 ,
	--	'' As ResultGrade2 ,
	--	CONVERT(decimal , 0) As Percentile2 ,
	--	'' As ResultStatus2 ,
		
	--	'' As SubActivityGrade2,
	--	'' As ActivityGrade2 ,
		
	--	'' As Exam3Name ,	
	--	CONVERT(decimal , 0) As TotalMarks3 ,
	--	CONVERT(decimal , 0) As TotalObtain3 ,
	--	CONVERT(decimal , 0) As Percentage3 ,
	--	0 As RankNumber3 ,
	--	'' As ResultGrade3 ,
	--	CONVERT(decimal , 0) As Percentile3 ,		
	--	'' As ResultStatus3,
		
	--	'' As SubActivityGrade3 ,
	--	'' As ActivityGrade3 ,
		
	--	'' As Exam4Name ,	
	--	CONVERT(decimal , 0) As TotalMarks4 ,
	--	CONVERT(decimal , 0) As TotalObtain4,
	--	CONVERT(decimal , 0) As Percentage4 ,
	--	0 As RankNumber4 ,
	--	'' As ResultGrade4 ,
	--	CONVERT(decimal , 0) As Percentile4 ,
	--	'' As ResultStatus4 ,
		
	--	'' As SubActivityGrade4,
	--	'' As ActivityGrade4 ,
		
	--	'' As Exam5Name ,		
	--	CONVERT(decimal , 0) As TotalMarks5 ,
	--	CONVERT(decimal , 0) As TotalObtain5 ,
	--	CONVERT(decimal , 0) As Percentage5 ,
	--	0 As RankNumber5 ,
	--	'' As ResultGrade5 ,
	--	CONVERT(decimal , 0) As Percentile5 ,
	--	'' As ResultStatus5 ,
		
	--	'' As SubActivityGrade5 ,
	--	'' As ActivityGrade5 ,
		
	--	'' As Exam6Name ,	
	--	CONVERT(decimal , 0) As TotalMarks6 ,
	--	CONVERT(decimal , 0) As TotalObtain6,
	--	CONVERT(decimal , 0) As Percentage6 ,
	--	0 As RankNumber6 ,
	--	'' As ResultGrade6 ,
	--	CONVERT(decimal , 0) As Percentile6 ,
	--	'' As ResultStatus6 ,
		
	--	'' As SubActivityGrade6 ,
	--	'' As ActivityGrade6 ,
		
	--	'' As Exam7Name ,		
	--	CONVERT(decimal , 0) As TotalMarks7 ,
	--	CONVERT(decimal , 0) As TotalObtain7,
	--	CONVERT(decimal , 0) As Percentage7 ,
	--	0 As RankNumber7 ,
	--	'' As ResultGrade7,
	--	CONVERT(decimal , 0) As Percentile7 ,
	--	'' As ResultStatus7 ,
		
	--	--SubActivityGrade7 nvarchar(10),
		
	--	'' As Exam8Name,
	--	CONVERT(decimal , 0) As TotalMarks8 ,
	--	CONVERT(decimal , 0) As TotalObtain8 ,
	--	CONVERT(decimal , 0) As Percentage8,
	--	0 As RankNumber8 ,
	--	'' As ResultGrade8 ,
	--	CONVERT(decimal , 0) As Percentile8,
	--	'' As ResultStatus8,
	--	'' As ResultRemark1 ,
	--	'' As ResultRemark2,
	--	CONVERT(decimal , 0) As TotalDays ,
	--	CONVERT(decimal , 0) As PresentDays ,
	--	CONVERT(decimal , 0) As StudentHeight,
	--	CONVERT(decimal , 0) As StudentWeight ,
	--	'' As ExamSeatNo ,
	--	0 As ExamId ,
	--	CONVERT(bit , 0) As IsDisplayParentName ,
	--	'' As FatherName ,
	--	'' As MotherName ,
	--	CONVERT(bit , 0) As IsShowSubjectMark , 
	--	CONVERT(bit , 0) As IsOptionalSubject ,
	--	CONVERT(tinyInt , 0) As CoScholasticScopeId ,
	--	CONVERT(bit , 0) As IsDisplayPrincipalSign ,
	--	CONVERT(bit , 0) As IsDisplayTeacherSign ,
	--	Convert (varbinary(max) , '') As EmployeeSign,
		
	--	'' As ActivityName ,
	--	'' As SubActivityName ,
	--	0 As SubActivityId ,
	--	0 As ActivityId ,
	--	 '' As SubActivityGrade,
	--	 '' As ActivityGrade ,
	--	'' As SubActivityGradeIndicator ,
	--	'' As SubActivityDescriptiveIndicator,
	--	0 As SubjectActivityOrderIndex ,
	--	0 As SubActivityOrderIndex ,
	--	0 As ColumnSubjectCount ,
	--	Convert (varbinary(max) , '') As MarksheetHeaderA4 ,
	--	CONVERT(bit,0) As IsImageHeader ,
	--	CONVERT(decimal , 0) As Height1 ,
	--	CONVERT(decimal , 0) As Height2 ,
	--	CONVERT(decimal , 0) As Height3,
	--	CONVERT(decimal , 0) As Height4 ,
	--	CONVERT(decimal , 0) As Height5,
	--	CONVERT(decimal , 0) As Height6 ,
	--	CONVERT(decimal , 0) As Weight1 ,
	--	CONVERT(decimal , 0) As Weight2 ,
	--	CONVERT(decimal , 0) As Weight3 ,
	--	CONVERT(decimal , 0) As Weight4,
	--	CONVERT(decimal , 0) As Weight5 ,
	--	CONVERT(decimal , 0) As Weight6 ,
	--	CONVERT(decimal , 0) As TotalDays1 ,
	--	CONVERT(decimal , 0) As PresentDays1 ,
	--	CONVERT(decimal , 0) As TotalDays2 ,
	--	CONVERT(decimal , 0) As PresentDays2 ,
	--	CONVERT(decimal , 0) As TotalDays3 ,
	--	CONVERT(decimal , 0) As PresentDays3 ,
	--	CONVERT(decimal , 0) As TotalDays4 ,
	--	CONVERT(decimal , 0) As PresentDays4 ,
	--	CONVERT(decimal , 0) As TotalDays5 ,
	--	CONVERT(decimal , 0) As PresentDays5 ,
	--	CONVERT(decimal , 0) As TotalDays6 ,
	--	CONVERT(decimal , 0) As PresentDays6 ,
	--	'' As MyActivity1,
	--	'' As MyActivity2 ,
	--	'' As MyActivity3,
	--	'' As MyActivity4 ,
	--	'' As MyActivity5,
	--	'' As MyActivity6,
	--	'' As GeneralRemark1,
	--	'' As GeneralRemark2 ,
	--	'' As GeneralRemark3 ,
	--	'' As GeneralRemark4,
	--	'' As GeneralRemark5,
	--	'' As GeneralRemark6,
	--	'' As PresentAddress ,
	--	'' As  MobileNo,
	--	'' As House ,
		 
	--	CONVERT(decimal , 0) As AttendanceTerm1  ,
	--	CONVERT(decimal , 0) As AttendanceTerm2 ,
	--	CONVERT(decimal , 0) As WorkingDaysTerm1 ,
	--	CONVERT(decimal , 0) As WorkingDaysTerm2 ,
	--	  '' As BloodGroup ,
	--	  '' As GradeSetIdText ,
	--	  '' As IsDisplayMonthlyAttendanceText ,
	--	  '' As DentalHygiene ,
	--	'' As VisionLeft ,
	--	'' As VisionRight ,
	--	'' As TeacherSignCaption ,
	--	'' As PrincipalSignCaption ,
	--	'' As ParentSignCaption ,
	--	'' As ParentEmail ,
	--  '' AS MyGoal,
	--	'' AS MyStrength,
	--	'' AS MyInterestHobby,
	--	'' AS AreaOfInterest,
	--	'' AS Responsibility,
	--	'' AS Achievements,
	--	'' As ImprovementArea,
	--	'' AS ProgressArea,
	--	'' AS MyActivity,
	--	'' As ClassTeacherRemark,
	--	'' AS ClassTeacherName,
	--	'' As HouseRemark,
	--	'' As GeneralRemark,
	--	'' AS FatherContactNo,
	--	'' AS MotherContactNo,
	--	'' AS FatherMail,
	--	'' AS MotherMail,
	--  CONVERT(bit , 0) As IsDecimal,
	--  '' As Name

	--END


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


GO

ALTER PROCEDURE [sAssetManagement].[pAssetAdjustmentSearchGet]
	@rOrgId [int],
	@rFromDate [datetime],
	@rToDate [datetime],
	@rLocationId [int] = 0,
	@rCategoryId [int] = 0,
	@rCode [nvarchar](30) = '',
	@rTitle [nvarchar](30) = '',
	@rStoreLocationId int,
	@rDepartmentId int,
	@rOrgGroupId smallint=0 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
      
    IF(@rLocationId = -1)
    SET @rLocationId = 0
    
    IF(@rCategoryId = -1)
    SET @rCategoryId = 0
    
    IF(@rDepartmentId = -1)
    SET @rDepartmentId = 0
    
    SELECT 
                  AAD.Id AS AssetAuditDetailId,
                  LM.Title AS StoreLocation,
                  SIM.Code AS AssetTag,
                  SIM.Title AS [Description],
                  SIM.ModelNumber AS ModelNumber,
                  SM.Title AS OldStatus,
                  CM.Title AS Category,
                  ODM.Title As Department,
                  AA.Number AS AuditNumber,
				  SIM.AssetCode AS NewAssetCode
                  
      FROM sAssetManagement.tAssetAuditDetail AAD     
      INNER JOIN sAssetManagement.tAssetAudit AA
      ON  AAD.AssetAuditId = AA.Id 
      INNER JOIN sFixedAsset.vExtLocationMaster LM
      ON  LM.Id = AA.LocationId
      INNER JOIN sCommon.tStatusMaster SM
      ON    SM.Id = AA.StatusId
      INNER JOIN sAssetManagement.tAssetMaster SIM
      ON    SIM.ID = AAD.AssetId AND SIM.LocationId=LM.Id
      INNER JOIN sFixedAsset.tCategoryMaster CM
      ON CM.Id = SIM.CategoryId
      	INNER JOIN sSetup.tDepartmentMaster ODM
	ON ODM.Id = SIM.DepartmentID
   --   INNER JOIN (SELECT DISTINCT DepartmentId, DepartmentTitle FROM sAssetManagement.vExtAssetDepartment) AD
	  --ON AD.DepartmentId = SIM.DepartmentID
      WHERE
            (CAST(AA.CreatedDateTime AS DATE) >= CAST(@rFromDate AS DATE) AND CAST(AA.CreatedDateTime AS DATE) <= CAST((@rToDate + 1) AS DATE))
            AND ((SIM.Code = @rCode) OR (@rCode = '')) 
            AND ((SIM.Title = @rTitle) OR (@rTitle = '')) 
            AND ((SIM.LocationId = @rLocationId) OR (@rLocationId = 0)) 
            AND ((SIM.CategoryId = @rCategoryId) OR (@rCategoryId = 0))
            AND (AAD.Id NOT IN ( SELECT AssetAuditDetailId FROM sAssetManagement.tAssetAdjustmentDetail))
          
      --      AND (AAD.AssetCheck = 0)
      --      AND (AAD.Id = (SELECT MAX(TAAD.ID) FROM sAssetManagement.tAssetAuditDetail TAAD WHERE AAD.AssetId = TAAD.AssetId))  
			   --AND ((AA.OrgId = @rOrgId) OR @rOrgId=0)
			   
            AND ((AA.StoreLocationId=@rStoreLocationId) OR @rStoreLocationId=0)
            AND ((SIM.DepartmentId = @rDepartmentId) OR (@rDepartmentId = 0))
            AND ((SIM.OrgGroupId = @rOrgGroupId) OR (@rOrgGroupId = 0))
            
            ORDER BY SIM.Code DESC
END
GO
PRINT N'Altering [sAssetManagement].[pAssetMaintenanceDetailGet]...';


GO
 
ALTER PROCEDURE [sAssetManagement].[pAssetMaintenanceDetailGet]
	@rOrgId int,
	@rNumber nvarchar(20) = '',
	@rAssetId int = 0,
	@rFromMaintenanceDate Date ='',
	@rToMaintenanceDate Date = '',
	@rId int = 0,
	@rStatusId int = 0

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON;

BEGIN
	
	SELECT	AMT.Id,
			AMT.Number,
			AMT.AssetId,
			AMT.CreatedUserId,
			AMT.MaintenenceBy,
			AMT.MaintenenceCost,
			--CONVERT(varchar,AMT.MaintenenceDate, 105) as MaintenenceDate, 
			AMT.MaintenenceDate,
			AMT.MaintenenceReason,
			--CONVERT(varchar,AMT.NextMaintenenceDate, 105) as NextMaintenenceDate,
			AMT.NextMaintenenceDate,
			LM.Title AS LocationName,
			LM.Id,
			AM.StatusId,
			AM.Title AS AssetName,
			AM.Code AS AssetCode,
			AM.CategoryId AS AssetCategoryId,
			LM.Id AS LocationId,
			AMT.DocumentNo,
			AMT.DocumentDate,
			AD.Title AS DepartmentName,
			SM.Title AS StatusName,
			CM.Title AS CategoryName,
			AM.ModelNumber AS ModelNumber,
			ISNULL(AM.AssetCode,'') AS NewAssetCode
			
			
	FROM sAssetManagement.tMaintenence AMT
	INNER JOIN 
		sAssetManagement.tAssetMaster AM
	ON
		AMT.AssetId = AM.Id
	INNER JOIN
		sFixedAsset.vExtLocationMaster LM
	ON
		AM.LocationId = LM.Id
	INNER JOIN sSetup.tDepartmentMaster  AD
	ON	AD.Id=AM.DepartmentId
	INNER JOIN
	    sCommon.tStatusMaster SM
	ON	 SM.Id = AM.StatusId
	INNER JOIN sFixedAsset.tCategoryMaster CM
	ON CM.Id=AM.CategoryId 

	WHERE ((AMT.Number = @rNumber) OR (@rNumber = 0)) AND AM.UsageStatusId <> 124 
	AND AMT.OrgId = @rOrgId AND ((AMT.AssetId = @rAssetId) OR (@rAssetId = 0))
	AND ((AMT.MaintenenceDate >= @rFromMaintenanceDate) OR (ISNULL(@rFromMaintenanceDate,'')='')) 
	AND ((AMT.MaintenenceDate <= @rToMaintenanceDate) OR (ISNULL(@rToMaintenanceDate,'') = '')) 
	AND ((AMT.Id = @rId) OR (@rId = 0))
	AND ((AM.StatusId = @rStatusId) OR (@rStatusId = 0))
END
GO
PRINT N'Altering [sAssetManagement].[pAssetMasterListGet]...';


GO
ALTER PROCEDURE [sAssetManagement].[pAssetMasterListGet]
	@rOrgId [int] ,
	@rAssetTag [int] = 0,
	@rAssetDescription [nvarchar](50) = '',
	@rModelNo [nvarchar](50) = '',
	@rManufacturer [nvarchar](50) = '',
	@rCategoryId [int] = 0,
	@rLocationId [int] = 0,
	@rDepartmentId [int] = 0,
	@rCode [nvarchar](50) = '',
	@rStatusId [int] = 0,
	@rTag [int] = 0,
	@rFromDate [datetime] = '',
	@rToDate [datetime] = '',
	@rIscritical [bit] = 0,
	@rStoreLocationId int
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
        IF @rFromDate IS NULL
         SET @rFromDate = sCommon.fGetDate()
         
       SELECT Tas.Id AS AssetTag,
                  Tas.CODE,
                  Tas.Title AS AssetDescription,
                  Tas.LocationId,
                  LOC.Title AS Location,
                  Tas.StatusId,
                  STAT.title AS status,
                  Tas.ModelNumber AS ModelNo,
                  Tas.CategoryId,
                  Cat.TITLE AS Category,
                  'AS' AS Manufacturer,
                  Tas.MaintenanceAlertPeriod,
                  day(Tas.NextMaintenanceDate) AS NextMaintenanceDate,
                  Tas.NextMaintenanceDate AS DueDate,
                  ISNULL(Tas.NextMaintenanceDate, sCommon.fGetDate()) AS NextDate,
            Tas.LastMaintenanceDate AS lastDate,
            Tas.Iscritical,
            AD.Title AS  DepartmentTitle,
			ISNULL(Tas.AssetCode,'') AS AssetCode 

          FROM sAssetManagement.tAssetMaster Tas
         INNER JOIN  sFixedAsset.tCategoryMaster Cat
         ON TAS.CATEGORYID = CAT.ID and  Tas.OrgId = @rOrgId 
         INNER JOIN  sCommon.tStatusMaster STAT
         ON STAT.ID =  Tas.UsageStatusId 
         INNER JOIN  sFixedAsset.VextLocationMaster LOC
         ON LOC.ID = TAS.LocationId
         INNER JOIN sSetup.tDepartmentMaster  AD
         ON AD.Id = Tas.DepartmentID
           
        WHERE 
        
         ((((Tas.Id = @rAssetTag) OR (@rAssetTag = 0)) 
        AND ((Tas.Code = @rCode) OR (@rCode = '')) 
        AND ((Tas.Title = @rAssetDescription) OR (@rAssetDescription = '')) 
        AND ((Tas.ModelNumber = @rModelNo) OR (@rModelNo = '')) 
        AND ((Tas.CategoryId = @rCategoryId) OR (@rCategoryId = 0))  
        AND ((Tas.LocationId = @rLocationId) OR (@rLocationId = 0))
        AND ((Tas.DepartmentId = @rDepartmentId) OR (@rDepartmentId = 0)) 
        AND((Tas.StoreLocationId=@rStoreLocationId) OR @rStoreLocationId=0)
        AND ((Tas.UsageStatusId = @rStatusId) OR (@rStatusId = 0))) AND @rTag = 0 AND Tas.UsageStatusId <> 124 )
        
        OR ((((Tas.Id = @rAssetTag) OR (@rAssetTag = 0)) 
        AND ((Tas.Code = @rCode) OR (@rCode = '')) 
        AND ((Tas.Title = @rAssetDescription) OR (@rAssetDescription = '')) 
        AND ((Tas.ModelNumber = @rModelNo) OR (@rModelNo = '')) 
        AND ((Tas.CategoryId = @rCategoryId) OR (@rCategoryId = 0))  
        AND ((Tas.LocationId = @rLocationId) OR (@rLocationId = 0))
        AND ((Tas.DepartmentId = @rDepartmentId) OR (@rDepartmentId = 0)) 
         AND  (CONVERT(NVARCHAR(10), DATEADD(DD,(- Tas.MaintenanceAlertPeriod), Tas.NextMaintenanceDate), 111)  <=  CONVERT(NVARCHAR(10), @rFromDate, 111) )  
        AND  (Tas.NextMaintenanceDate  >=  @rFromDate ) 
         AND((Tas.StoreLocationId=@rStoreLocationId) OR @rStoreLocationId=0)
        AND ((Tas.UsageStatusId = @rStatusId) OR (@rStatusId = 0))) AND @rTag = 1 AND Tas.UsageStatusId <> 124  ) 
          OR ((((Tas.Id = @rAssetTag) OR (@rAssetTag = 0)) 
          AND ((Tas.Code = @rCode) OR (@rCode = '')) 
        AND ((Tas.LocationId = @rLocationId) OR (@rLocationId = 0)) 
        AND ((Tas.ModelNumber = @rModelNo) OR (@rModelNo = '')) 
        AND ((Tas.DepartmentId = @rDepartmentId) OR (@rDepartmentId = 0)) 
        AND ((Tas.CategoryId = @rCategoryId) OR (@rCategoryId = 0)) 
        AND ((Tas.LocationId = @rLocationId) OR (@rLocationId = 0))
        AND ((Tas.UsageStatusId = @rStatusId) OR (@rStatusId = 0))
        AND  (CONVERT(NVARCHAR(10), Tas.NextMaintenanceDate, 111)  >=  CONVERT(NVARCHAR(10), @rFromDate, 111) ) 
        AND (Tas.NextMaintenanceDate  <= (@rToDate + 1) )
        AND((Tas.StoreLocationId=@rStoreLocationId) OR (@rStoreLocationId=0))
        AND ((Iscritical = @rIscritical))) AND @rTag = 2 AND Tas.UsageStatusId <> 124 ) 
        
        ORDER BY  Tas.Id DESC
         
        
END
GO
PRINT N'Altering [sAssetManagement].[pMovementSearchGet]...';


GO
 
ALTER PROCEDURE [sAssetManagement].[pMovementSearchGet]
	@rOrgId int,
	@rId int = 0,
	@rMovementDate Date = '',
	@rFromDepartmentId int = 0,
	@rFromLocationId int = 0,
	@rToDepartmentId int = 0,
	@rToLocationId int = 0,
	@rOwnerEmployeeId bigint = 0

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	 SELECT M.Id,
			M.Number,
			CONVERT(varchar, M.MovementDate, 105) as MovementDate,
			ISNULL(M.Remark,''),
			ISNULL(EM.EmployeeName, '') EmployeeName,
			ISNULL(M.OwnerId, 0) OwnerId,
			ISNULL((SELECT Title FROM sSetup.tDepartmentMaster WHERE Id = M.FromDepartmentId),'') as FromDepartment,
			ISNULL((SELECT Title FROM sSetup.tDepartmentMaster WHERE Id = M.ToDepartmentId),'') as ToDepartment,
			ISNULL((SELECT Title FROM sFixedAsset.tLocationMaster WHERE Id = M.FromLocationId),'') as FromLocation,
			ISNULL((SELECT Title FROM sFixedAsset.tLocationMaster WHERE Id = M.ToLocationId),'') as ToLocation,
			AM.Code as AssetTag,
			AM.Title as AssetTitle,
			ISNULL(AM.AssetCode,'') AS AssetCode
	FROM 
		sAssetManagement.tMovement M
		INNER JOIN sAssetManagement.tMovementDetail MD ON M.Id = MD.MovementId
		INNER JOIN sAssetManagement.tAssetMaster AM ON MD.AssetId = AM.Id
		LEFT JOIN sCommon.vEmployeeMaster EM ON EM.Id = M.OwnerId		
	WHERE 
		((M.Id = @rId) OR (@rId = 0)) AND M.OrgId = @rOrgId
		AND ((M.MovementDate = @rMovementDate) OR (@rMovementDate = ''))
		AND ((M.FromDepartmentId = @rFromDepartmentId) OR (@rFromDepartmentId = 0))
		AND ((M.FromLocationId = @rFromLocationId) OR (@rFromLocationId = 0))
		AND ((M.ToDepartmentId = @rToDepartmentId) OR (@rToDepartmentId = 0))
		AND ((M.ToLocationId = @rToLocationId) OR (@rToLocationId = 0))
		AND ((M.OwnerId = @rOwnerEmployeeId) OR (@rOwnerEmployeeId = 0))
END
GO
PRINT N'Altering [sAssetManagement].[pRptAssetMaintenanceListGet]...';


GO
 
ALTER PROCEDURE [sAssetManagement].[pRptAssetMaintenanceListGet]
	@rOrgId [int] ,
	@rNumber nvarchar(100),
	@rStoreLocationId int
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED
BEGIN
	 SELECT 
			LOC.Title AS Location,
			AM.CODE AS AssetTag,
			AM.Title AS AssetDescription,
			STAT.title AS Status,
			Cat.TITLE AS Category,
			AMN.MaintenenceDate AS LastMaintenanceDate,
			AMN.NextMaintenenceDate AS NextMaintenanceDate,
			AM.IsCritical AS Critical,
			VM.Title AS Supplier,
			AD.Title AS DepartmentName,
			AMN.Number AS MaintenanceNumber,
			AMN.MaintenenceCost,
			AMN.MaintenenceBy,
			ISNULL(AM.AssetCode,'') AS AssetCode
			
	FROM
		sAssetManagement.tMaintenence AMN
	INNER JOIN
		sAssetManagement.tAssetMaster AM
	ON AMN.AssetId = AM.Id
	INNER JOIN sSetup.tDepartmentMaster AD
	ON AD.Id=AM.DepartmentId
	INNER JOIN  sFixedAsset.tCategoryMaster Cat
	ON AM.CategoryId = CAT.ID
	INNER JOIN  sCommon.tStatusMaster STAT
	ON STAT.ID =  AM.UsageStatusId 
	INNER JOIN  sFixedAsset.tLocationMaster LOC
	ON LOC.ID = AM.LocationId
	LEFT JOIN
	sProcurement.tVendorMaster VM
	ON VM.Id = AM.AmcVendorId
	
	WHERE (AMN.Number=@rNumber) OR (@rNumber = '')
	AND AMN.OrgId = @rOrgId
	AND AMN.StoreLocationId=@rStoreLocationId
	ORDER BY AMN.MaintenenceDate ASC
				 
END
GO
PRINT N'Altering [sAssetManagement].[pRptAssetMasterListGet]...';


GO
ALTER PROCEDURE [sAssetManagement].[pRptAssetMasterListGet]
	@rOrgId [int] ,
	@rAssetTag [int] = 0,
	@rAssetDescription [nvarchar](50) = '',
	@rModelNo [nvarchar](50) = '',
	@rManufacturer [nvarchar](50) = '',
	@rCategoryId [int] = 0,
	@rLocationId [int] = 0,
	@rCode [nvarchar](50) = '',
	@rStatusId [int] = 0,
	@rTag [int] = 0,
	@rFromDate [datetime] = '',
	@rToDate [datetime] = '',
	@rIscritical [bit] = 0,
	@rStoreLocationId int
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED
DECLARE @lDepartmentId Int
SET @lDepartmentId = @rLocationId
BEGIN
      SELECT Tas.Id AS AssetTag,
                  Tas.CODE,
                  Tas.Title AS AssetDescription,
                  Tas.LocationId,
                  LOC.Title AS Location,
                  Tas.StatusId,
                  STAT.title AS status,
                  Tas.ModelNumber AS ModelNo,
                  Tas.CategoryId,
                  Cat.TITLE AS Category,
                  'AS' AS Manufacturer,
                  Tas.MaintenanceAlertPeriod,
                  day(Tas.NextMaintenanceDate) AS NextMaintenanceDate,
                  Tas.NextMaintenanceDate AS DueDate,
                  sCommon.fReportDateGet(CAST(ISNULL(Tas.NextMaintenanceDate, sCommon.fGetDate())AS DATETIME)) AS NextDate,
            sCommon.fReportDateGet(CAST(Tas.LastMaintenanceDate AS DATETIME)) AS lastDate,
            Tas.Iscritical,
             Cat.TITLE AS HCategory,             
                  STAT.title AS HTitle,
            sCommon.fReportDateGet(CAST(@rFromDate  AS DATETIME)) AS FromDate,
                  sCommon.fReportDateGet(CAST(@rToDate AS DATETIME)) AS ToDate,
                  @rModelNo AS ModelNo,
                  @rCode AS  HAssetTag,
                  @rAssetDescription AS HAssetDescription,
                  ODM.Title AS DeptName,
				  ISNULL(Tas.AssetCode,'') AS AssetCode
            
         FROM sAssetManagement.tAssetMaster Tas
         INNER JOIN  sFixedAsset.tCategoryMaster Cat
         ON TAS.CATEGORYID = CAT.ID
         INNER JOIN  sCommon.tStatusMaster STAT
         ON STAT.ID =  Tas.UsageStatusId 
         INNER JOIN  sFixedAsset.VextLocationMaster LOC
         ON LOC.ID = TAS.LocationId
         --INNER JOIN (SELECT DISTINCT DepartmentId, DepartmentTitle FROM sAssetManagement.vExtAssetDepartment) AD
         --ON AD.DepartmentId = Tas.DepartmentID
          	INNER JOIN sSetup.tDepartmentMaster ODM
      	ON ODM.Id = Tas.DepartmentID
         
        WHERE 
        Tas.OrgId = @rOrgId AND
        ((((Tas.Id = @rAssetTag) OR (@rAssetTag = 0)) 
        AND ((Tas.Code = @rCode) OR (@rCode = '')) 
        AND ((Tas.Title = @rAssetDescription) OR (@rAssetDescription = '')) 
        AND ((Tas.ModelNumber = @rModelNo) OR (@rModelNo = '')) 
        AND ((Tas.CategoryId = @rCategoryId) OR (@rCategoryId = 0))  
        AND ((Tas.LocationId = @rLocationId) OR (@rLocationId = 0))
        AND ((Tas.DepartmentId = @lDepartmentId) OR (@lDepartmentId = 0)) 
        AND((Tas.StoreLocationId=@rStoreLocationId) OR @rStoreLocationId=0)
        AND ((Tas.UsageStatusId = @rStatusId) OR (@rStatusId = 0))) AND @rTag = 0 AND Tas.UsageStatusId <> 124 )
        
        OR ((((Tas.Id = @rAssetTag) OR (@rAssetTag = 0)) 
        AND ((Tas.Code = @rCode) OR (@rCode = '')) 
        AND ((Tas.Title = @rAssetDescription) OR (@rAssetDescription = '')) 
        AND ((Tas.ModelNumber = @rModelNo) OR (@rModelNo = '')) 
        AND ((Tas.CategoryId = @rCategoryId) OR (@rCategoryId = 0))  
        AND ((Tas.LocationId = @rLocationId) OR (@rLocationId = 0))
        AND ((Tas.DepartmentId = @lDepartmentId) OR (@lDepartmentId = 0)) 
         AND  (CONVERT(NVARCHAR(10), DATEADD(DD,(- Tas.MaintenanceAlertPeriod), Tas.NextMaintenanceDate), 111)  <=  CONVERT(NVARCHAR(10), @rFromDate, 111) )  
        AND  (Tas.NextMaintenanceDate  >=  @rFromDate ) 
         AND((Tas.StoreLocationId=@rStoreLocationId) OR @rStoreLocationId=0)
        AND ((Tas.UsageStatusId = @rStatusId) OR (@rStatusId = 0))) AND @rTag = 1 AND Tas.UsageStatusId <> 124  ) 
          OR ((((Tas.Id = @rAssetTag) OR (@rAssetTag = 0)) 
          AND ((Tas.Code = @rCode) OR (@rCode = '')) 
        AND ((Tas.LocationId = @rLocationId) OR (@rLocationId = 0)) 
        AND ((Tas.ModelNumber = @rModelNo) OR (@rModelNo = '')) 
        AND ((Tas.DepartmentId = @lDepartmentId) OR (@lDepartmentId = 0)) 
        AND ((Tas.CategoryId = @rCategoryId) OR (@rCategoryId = 0)) 
        AND ((Tas.LocationId = @rLocationId) OR (@rLocationId = 0))
        AND ((Tas.UsageStatusId = @rStatusId) OR (@rStatusId = 0))
        AND  (CONVERT(NVARCHAR(10), Tas.NextMaintenanceDate, 111)  >=  CONVERT(NVARCHAR(10), @rFromDate, 111) ) 
        AND (Tas.NextMaintenanceDate  <= (@rToDate + 1) )
        AND((Tas.StoreLocationId=@rStoreLocationId) OR (@rStoreLocationId=0))
        AND ((Iscritical = @rIscritical))) AND @rTag = 2 AND Tas.UsageStatusId <> 124 ) 

        ORDER BY  Tas.NextMaintenanceDate  
END
GO
PRINT N'Altering [sBiometric].[pBiometricDailyReportGet]...';


GO
 
 
ALTER PROCEDURE [sBiometric].[pBiometricDailyReportGet]
     @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='',
	 @rFromDate Date,
	 @rOrgId int,
	 @rOrganizationDepartmentId int=0,
	 @rEmployeeTypeId int =0,
	 @rEmployeeId bigint = 0,	
	 @rStatus nvarchar(max) = '',
	 @rEmployeeStatusId int=0,
	 @rOrderBy smallint = 0,
	 @rOrgGroupId int = 0,
	 @rUserId bigint = 0,
	 @rIsDetail bit=0
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
DECLARE  @rToDate Date
SET @rToDate = @rFromDate

DECLARE @TableEmployee TABLE (Id int Identity,EmployeeID BigINT, OrganizationDepartmentId int, EmployeeTypeId Int)
INSERT INTO @TableEmployee
SELECT EM.Id AS EmployeeId,ED.OrganizationDepartmentId,ED.EmployeeTypeId from shrm.tEmployeeMaster EM 
LEFT JOIN sHRM.tEmployeeJobDetail ED ON ED.EmployeeId = EM.Id 
Where (ED.OrganizationDepartmentId =@rOrganizationDepartmentId Or @rOrganizationDepartmentId= 0 )
AND (ED.EmployeeTypeId = @rEmployeeTypeId OR @rEmployeeTypeId = 0 )
AND  EM.ORgId = @rOrgId 
AND (EM.StatusId = @rEmployeeStatusId OR ISNULL(@rEmployeeStatusId,0)=0)
AND ISNULL(EM.IsOtherUser,0) = 0 

DECLARE @lCount int
DECLARE @lCount1 int
Declare @lQuery nvarchar(Max)
DECLARE @strQuery nvarchar(Max)
DECLARE @lDate date
DECLARE @lDay as nvarchar(3)
DECLARE @lMonth as nvarchar(3)
DECLARE @lYear as nvarchar(4)

DECLARE @lBatchID int
DECLARE @lEmployeeId bigint
DECLARE @lEmpCount int

DECLARE @TempDate TABLE(Id int identity,Idate date)
insert into @TempDate
SELECT  TOP (DATEDIFF(DAY, @rFromDate, @rToDate) + 1)
        Date = DATEADD(DAY, ROW_NUMBER() OVER(ORDER BY a.object_id) - 1, @rFromDate)
FROM    sys.all_objects a CROSS JOIN sys.all_objects b;

CREATE TABLE #TempMonthTrans (Id int Identity,EmployeeId bigint,Attn_Date DateTime,DayNumber nvarchar(8),PresentStatus nvarchar(25),
		FirstIn nvarchar(20),LastOut nvarchar(20),OverTime nvarchar(20),LateBy nvarchar(20),Duration nvarchar(20),EarlyBy nvarchar(20))


SELECT @lBatchID = Id from sSetup.tBatchMaster Where OrgId = @rOrgId AND IsActive = 1

Select @lCount = Max(Id) from @TempDate
Select @lEmpCount = Max(Id) from @TableEmployee
While (@lEmpCount > 0)
	BEGIN
		SELECT @lEmployeeId = EmployeeId From @TableEmployee Where Id = @lEmpCount	
	set @lCount1 = 1
	while (@lCount1 <= @lCount)
	begin			
		Select @lDate = Idate from @TempDate Where Id = @lCount1
		Select @lDay  = RIGHT('00' + CAST(DATEPART(dd,@lDate) AS varchar(2)), 2)
		Select @lMonth = RIGHT('00' + CAST(DATEPART(MM,@lDate) AS varchar(2)), 2)
		Select @lYear  = RIGHT('0000' + CAST(DATEPART(yyyy,@lDate) AS varchar(4)), 4)
		
		set @lQuery = 'INSERT INTO #TempMonthTrans
						SELECT Distinct ' + convert(nvarchar(15),@lEmployeeId) + ',''' + convert(nvarchar(15),@lDate) + ''',
						substring(DATENAME( dw, ''' + convert(nvarchar(15),@lDate) + '''),1,3) AS DN1,
											 

											 CASE When [sHrm].[fWeekHOffGetBio](' + convert(nvarchar(15),@lEmployeeId) + ', ' + convert(nvarchar(10),@lYear) + ',' + convert(nvarchar(10),@lMonth) + ',' + convert(nvarchar(15),@lDay)+',
											 ' + convert(nvarchar(15),@lBatchId) + ',' + Convert(nvarchar(10),@rOrganizationDepartmentId) + ',' + convert(nvarchar(10),@rOrgId) + ') <> ''-'' then 
											 [sHrm].[fWeekHOffGetBio](' + convert(nvarchar(15),@lEmployeeId) + ', ' + convert(nvarchar(10),@lYear) + ',' + convert(nvarchar(10),@lMonth) + ',' + convert(nvarchar(15),@lDay)+',
											 ' + convert(nvarchar(15),@lBatchId) + ',' + Convert(nvarchar(10),@rOrganizationDepartmentId) + ',' + convert(nvarchar(10),@rOrgId) + ') 
											 else D'+convert(nvarchar(15),@lDay)+' end AS D'+convert(nvarchar(15),@lDay)+',

											 D'+convert(nvarchar(15),@lDay)+'_IN,
											 D'+convert(nvarchar(15),@lDay)+'_OUT,
											 D'+convert(nvarchar(15),@lDay)+'_O,D'+convert(nvarchar(15),@lDay)+'_L,D'+convert(nvarchar(15),@lDay)+'_T,D'+convert(nvarchar(15),@lDay)+'_E 
						FROM sBiometric.tMonthTrans T1 
						LEFT JOIN sHRM.tEmployeeJobDetail ED ON ED.EmployeeId = T1.EmployeeId	
						WHERE T1.EmployeeId =' + convert(nvarchar(15),@lEmployeeId) + ' AND ATTN_DT >= cast(rtrim(YEAR(''' + convert(nvarchar(15),@lDate) + ''') *10000+ Month(''' + convert(nvarchar(15),@lDate) + ''') *100+ 01) as datetime) 
						AND ATTN_DT <= cast(rtrim(YEAR(''' + convert(nvarchar(15),@lDate) + ''') *10000+ Month(''' + convert(nvarchar(15),@lDate) + ''') *100+ 01) as datetime)'
						--print @lQuery
			execute (@lQuery )
		set @lCount1 = @lCount1 + 1
	end
		SET @lEmpCount = @lEmpCount - 1	
	END
	
	CREATE TABLE #TempMonthTransWitIoOutTime (EmployeeId bigint,Attn_Date DateTime,InTime nvarchar(20),OutTime nvarchar(20))
	if(@rIsDetail=1)
	BEGIN
	INSERT INTO #TempMonthTransWitIoOutTime
		SELECT  SourceId,Attn_Dt,CONVERT(VARCHAR(10), I.In_Out_Time, 108),CONVERT(VARCHAR(10), O.In_Out_Time, 108)
        FROM [sBiometric].[tCloudTransactionData] I
		OUTER APPLY (
						SELECT TOP 1    In_Out_Time,
										Mode
						FROM [sBiometric].[tCloudTransactionData] t
						WHERE       t.SourceId = I.SourceId
								AND t.In_Out_Time > I.In_Out_Time
								AND SourceTypeid=95
								AND t.Attn_Dt =I.Attn_Dt
								AND Mode = 'OUT'
						ORDER BY t.In_Out_Time
					) O
		WHERE I.Mode = 'IN'
		AND SourceTypeid=95
		AND I.Attn_Dt>=@rFromDate
		AND I.Attn_Dt<=@rToDate
		--select * from #TempMonthTransWitIoOutTime
	END
	--Select * from #TempMonthTrans
	--return
	
	IF(@rStatus = '(0)')
	BEGIN
		SET @strQuery = 'select Day(T.Attn_Date), T.*,Isnull(LV.LeaveCode,'''') as LeaveCode1,isnull(LV1.LeaveCode1,'''') AS LeaveCode,
	convert(nvarchar(20),Emp.Code) AS EmpCode,Emp.FirstName +'' '' + Emp.MiddleName +'' ''+ Emp.LastName  AS EmpName,''' +CAST(@rOrderBy AS NVARCHAR(3)) + ''' AS OrderBy,
	DM.Title AS DeptName, Emp.Number AS Number,	OM.Id AS OrgId, OM.Title AS OrganizationTitle,CTD.*,'+Cast(@rIsDetail AS NVARCHAR(10))+' AS IsDetail
	from #TempMonthTrans T
	INNER JOIN sHRM.tEmployeeMaster Emp on Emp.Id = T.EmployeeId AND ISNULL(EMP.IsOtherUser,0) = 0 
	INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = Emp.OrgID
	LEFT JOIN sHRM.tEmployeeJobDetail ED ON ED.EmployeeId = Emp.Id 
	LEFT JOIN sSetup.vDepartment DM ON DM.Id = ED.OrganizationDepartmentId
	LEFT JOIN sHRM.tEmployeeDesignationMaster EDM ON EDM.Id = ED.EmployeeDesignationId 	
	Left Join #TempMonthTransWitIoOutTime CTD ON  CTD.EmployeeId=T.EmployeeId AND CTD.Attn_Date=T.Attn_Date  	
	LEFT Join (Select sum(NoOfLeave) AS CLLeave,EmployeeId,LT.Code as LeaveCode from shrm.tLeave L inner join shrm.tLeaveTypeMaster LT ON LT.Id=L.LeaveTypeId 
	Where FromDate>=''' + Convert(nvarchar(12),@rFromDate) + ''' AND FromDate<=''' + Convert(nvarchar(12),@rToDate) + ''' GRoup By EmployeeId,LT.Code ) AS LV ON LV.EmployeeId = T.EmployeeId

	LEFT Join (select   distinct  EmployeeId,
    ISNULL( stuff((
        select Distinct '','' + LT.Code + '':'' + Convert(nvarchar(10),Sum(NoOfLeave)) 
        from shrm.tLeave L inner join shrm.tLeaveTypeMaster LT ON LT.Id=L.LeaveTypeId
        where  (FromDate >= ''' + Convert(nvarchar(12),@rFromDate) + ''' OR (ISNULL(''' + Convert(nvarchar(12),@rFromDate) + ''','''')='''')) 
        AND (ToDate <= ''' + Convert(nvarchar(12),@rToDate) + ''' OR (ISNULL(''' + Convert(nvarchar(12),@rToDate) + ''','''')='''') )
        AND L.EmployeeId = L1.EmployeeId AND L.StatusId= 550
              
        group by LT.Code
        for xml path('''')
    ),1,1,''''),'''') as LeaveCode1
	from shrm.tLeave L1 
	inner join shrm.tLeaveTypeMaster LT ON LT.Id=L1.LeaveTypeId AND L1.StatusId=550
	group by EmployeeId,LT.Code) AS LV1 ON LV1.EmployeeId = T.EmployeeId
	WHERE (T.EmployeeId = ' + convert(nvarchar(15),@rEmployeeId) + ' OR ' + convert(nvarchar(15),@rEmployeeId) + ' = 0)
	AND (OM.OrgGroupId = ' + convert(nvarchar(15),@rOrgGroupId) + ') AND DM.UserId = ' + convert(nvarchar(15),@rUserId) + ' Order By T.Attn_Date,T.EmployeeId'
	END
	ELSE
	BEGIN
	SET @strQuery = 'select Day(T.Attn_Date), T.*,Isnull(LV.LeaveCode,'''') as LeaveCode1,isnull(LV1.LeaveCode1,'''') AS LeaveCode,
	convert(nvarchar(20),Emp.Code) AS EmpCode,Emp.FirstName +'' '' + Emp.MiddleName +'' ''+ Emp.LastName  AS EmpName,''' +CAST(@rOrderBy AS NVARCHAR(3)) + ''' AS OrderBy,
	DM.Title AS DeptName, Emp.Number AS Number,	OM.Id AS OrgId, OM.Title AS OrganizationTitle,CTD.*,'+Cast(@rIsDetail AS NVARCHAR(10))+' AS IsDetail
	from #TempMonthTrans T
	INNER JOIN sHRM.tEmployeeMaster Emp on Emp.Id = T.EmployeeId AND ISNULL(EMP.IsOtherUser,0) = 0 
	INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = Emp.OrgID
	LEFT JOIN sHRM.tEmployeeJobDetail ED ON ED.EmployeeId = Emp.Id 
	LEFT JOIN sSetup.vDepartment DM ON DM.Id = ED.OrganizationDepartmentId
	LEFT JOIN sHRM.tEmployeeDesignationMaster EDM ON EDM.Id = ED.EmployeeDesignationId 
	Left Join #TempMonthTransWitIoOutTime CTD ON  CTD.EmployeeId=T.EmployeeId AND CTD.Attn_Date=T.Attn_Date
	LEFT Join (Select sum(NoOfLeave) AS CLLeave,EmployeeId,LT.Code as LeaveCode from shrm.tLeave L inner join shrm.tLeaveTypeMaster LT ON LT.Id=L.LeaveTypeId 
	Where FromDate>=''' + Convert(nvarchar(12),@rFromDate) + ''' AND FromDate<=''' + Convert(nvarchar(12),@rToDate) + ''' GRoup By EmployeeId,LT.Code ) AS LV ON LV.EmployeeId = T.EmployeeId

	LEFT Join (select   distinct  EmployeeId,
    ISNULL( stuff((
        select Distinct '','' + LT.Code + '':'' + Convert(nvarchar(10),Sum(NoOfLeave)) 
        from shrm.tLeave L inner join shrm.tLeaveTypeMaster LT ON LT.Id=L.LeaveTypeId
        where  (FromDate >= ''' + Convert(nvarchar(12),@rFromDate) + ''' OR (ISNULL(''' + Convert(nvarchar(12),@rFromDate) + ''','''')='''')) 
        AND (ToDate <= ''' + Convert(nvarchar(12),@rToDate) + ''' OR (ISNULL(''' + Convert(nvarchar(12),@rToDate) + ''','''')='''') )
        AND L.EmployeeId = L1.EmployeeId AND L.StatusId= 550
              
        group by LT.Code
        for xml path('''')
    ),1,1,''''),'''') as LeaveCode1
	from shrm.tLeave L1 
	inner join shrm.tLeaveTypeMaster LT ON LT.Id=L1.LeaveTypeId AND L1.StatusId=550
	group by EmployeeId,LT.Code) AS LV1 ON LV1.EmployeeId = T.EmployeeId
	WHERE PresentStatus IN ' + @rStatus + ' AND (T.EmployeeId = ' + convert(nvarchar(15),@rEmployeeId) + ' OR ' + convert(nvarchar(15),@rEmployeeId) + ' = 0)
	AND (OM.OrgGroupId = ' + convert(nvarchar(15),@rOrgGroupId) + ') AND DM.UserId = ' + convert(nvarchar(15),@rUserId) + ' Order By T.Attn_Date,T.EmployeeId'	
	END
	--WHERE (PresentStatus IN '+ '''' + @rStatus + '''' + ' OR (PresentStatus like ''%L%'')) Order By T.Attn_Date,T.EmployeeId' 


	--WHERE 1=1 and (ED.EmployeeGradeId in (' + convert(nvarchar(100),@rGRadeId) + ') OR (' + convert(nvarchar(100),@rGRadeId) + ') = 0) )' 
	
	
	print (@strQuery)
	execute (@strQuery)
	

	
	DROP TABLE #TempMonthTrans
	--select  
	--@rBuilder1 as Builder1,
	--@rBuilder2 as Builder2,
	--@rIsDetail AS IsDetail,
	--'' as Attn_Date,
	--'' as EmployeeId,
	--'' as Attn_Date,
	--'' as DayNumber ,
	--'' as PresentStatus ,
	--'' as FirstIn,
	--'' as LastOut,
	--'' as OverTime,
	--'' as LateBy,
	--'' as Duration,
	--'' as EarlyBy,
	--'' as TotPresent,
	--'' as TotWeekOff,
	--'' as TotHalfDay,
	--'' as TotHoliday,
	--'' AS TotEarly,
	--'' as CLLeave,
	--'' as LeaveCode,
	--'' as EmpCode,
	--'' as EmpName,
	--'' as DeptName,
	--'' as TotAbsent,
	--'' as IsFirstIn,
	--'' as IsLastOut,
	--'' as IsOT,
	--'' as IsLateBy,
	--'' as IsEarlyBy,
	--'' as IsDuration,
	--'' as OrderBy,
	--'' as Number,
	--'' as OrgId,
	--'' as OrganizationTitle,
	--'' AS OutTime,
	--'' as InTime
END

	--CASE 
	--					When [sHrm].[fWeekHOffGetBio](' + convert(nvarchar(15),@lEmployeeId) + ', Year(''' + convert(nvarchar(15),@lDate) + '''),Month(''' + convert(nvarchar(15),@lDate) + '''),' + @lDay + ',' + convert(nvarchar(15),@lBatchId) + ',ED.OrganizationDepartmentId,' + convert(nvarchar(15),@rOrgId) + ') in (''H'') AND D'+ convert(nvarchar(15),@lDay) +' <> ''A'' then D'+convert(nvarchar(15),@lDay) +'
	--					When [sHrm].[fWeekHOffGetBio](' + convert(nvarchar(15),@lEmployeeId) + ', Year(''' + convert(nvarchar(15),@lDate) + '''),Month(''' + convert(nvarchar(15),@lDate) + '''),' + @lDay + ',' + convert(nvarchar(15),@lBatchId) + ',' + CONVERT(nvarchar(13),@rOrganizationDepartmentId) + ',' + convert(nvarchar(15),@rOrgId) + ') Not in (''-'',''XX'') 
	--					Then [sHrm].[fWeekHOffGetBio](' + convert(nvarchar(15),@lEmployeeId) + ', Year(''' + convert(nvarchar(15),@lDate) + '''),Month(''' + convert(nvarchar(15),@lDate) + '''),' + @lDay + ',' + convert(nvarchar(15),@lBatchId) + ',0,' + convert(nvarchar(15),@rOrgId) + ') 
	--					Else D'+convert(nvarchar(15),@lDay)+' End
GO
PRINT N'Altering [sBiometric].[pRptMonthlySummaryListDateWiseGet]...';


GO
ALTER PROCEDURE [sBiometric].[pRptMonthlySummaryListDateWiseGet]
	@rOrgGroupId int,
	@rOrgId int,
	@rFromDate DateTime,
	@rToDate DateTime, 
	@rStudentId bigint=0,
	 @rClassId int=0,
	@rDivisionId int=0,
	--@rAttendanceTypeId tinyint,
	--@rAttendanceDate date=0,
-- @rRepeatCount tinyint,
	@rOrgGroupBatchId int=0,
	@rTimeSheetStatus nvarchar(10) = '0',
	@rDepartmentId int=0,
	@rStatusId int=0,
	 @rBuilder1 nvarchar(max),
 @rBuilder2 nvarchar(max),
	 @rIsDetail bit=0
	
WITH EXECUTE AS CALLER  
AS  
SET NOCOUNT ON  
BEGIN   
DECLARE @lBatchID int
CREATE TABLE #TempMonthTrans (
	Id int Identity,
	EmployeeId bigint,	
	Attn_Date DateTime,
	PresentStatus nvarchar(5),
	FirstIn nvarchar(20),
	LastOut nvarchar(20),
	OverTime nvarchar(20),
	LateBy nvarchar(20),
	Duration nvarchar(20),	
	EarlyBy nvarchar(20),
 ShiftName nvarchar(25) 
	
	)
	SELECT @lBatchID = Id FROM sSetup.tBatchMaster WHERE OrgId = @rOrgId AND IsActive = 1
	INSERT INTO #TempMonthTrans
	
	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 01) as datetime),D01,D01_IN,D01_OUT,D01_O,D01_L,D01_T,D01_E,D01_S FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rStudentId OR @rStudentId = 0) 
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND ( SourceTypeId =2003)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 02) as datetime),D02,D02_IN,D02_OUT,D02_O,D02_L,D02_T,D02_E,D02_S FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rStudentId OR @rStudentId = 0)
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND ( SourceTypeId = 2003)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 03) as datetime),D03,D03_IN,D03_OUT,D03_O,D03_L,D03_T,D03_E,D03_S FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rStudentId OR @rStudentId = 0)
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND ( SourceTypeId =2003)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 04) as datetime),D04,D04_IN,D04_OUT,D04_O,D04_L,D04_T,D04_E,D04_S FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rStudentId OR @rStudentId = 0)
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND ( SourceTypeId =2003)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 05) as datetime),D05,D05_IN,D05_OUT,D05_O,D05_L,D05_T,D05_E,D05_S FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rStudentId OR @rStudentId = 0)
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND ( SourceTypeId =2003)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 06) as datetime),D06,D06_IN,D06_OUT,D06_O,D06_L,D06_T,D06_E,D06_S FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rStudentId OR @rStudentId = 0)
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND ( SourceTypeId =2003)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 07) as datetime),D07,D07_IN,D07_OUT,D07_O,D07_L,D07_T,D07_E,D07_S FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rStudentId OR @rStudentId = 0)
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND ( SourceTypeId =2003)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 08) as datetime),D08,D08_IN,D08_OUT,D08_O,D08_L,D08_T,D08_E,D08_S FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rStudentId OR @rStudentId = 0)
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND ( SourceTypeId =2003)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 09) as datetime),D09,D09_IN,D09_OUT,D09_O,D09_L,D09_T,D09_E,D09_S FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rStudentId OR @rStudentId = 0)
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND ( SourceTypeId =2003)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 10) as datetime),D10,D10_IN,D10_OUT,D10_O,D10_L,D10_T,D10_E,D10_S FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rStudentId OR @rStudentId = 0)
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND ( SourceTypeId =2003)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 11) as datetime),D11,D11_IN,D11_OUT,D11_O,D11_L,D11_T,D11_E,D11_S FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rStudentId OR @rStudentId = 0)
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND ( SourceTypeId =2003)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 12) as datetime),D12,D12_IN,D12_OUT,D12_O,D12_L,D12_T,D12_E,D12_S FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rStudentId OR @rStudentId = 0)
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND ( SourceTypeId =2003)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 13) as datetime),D13,D13_IN,D13_OUT,D13_O,D13_L,D13_T,D13_E,D13_S FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rStudentId OR @rStudentId = 0)
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND ( SourceTypeId =2003)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 14) as datetime),D14,D14_IN,D14_OUT,D14_O,D14_L,D14_T,D14_E,D14_S FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rStudentId OR @rStudentId = 0)
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND ( SourceTypeId =2003)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 15) as datetime),D15,D15_IN,D15_OUT,D15_O,D15_L,D15_T,D15_E,D15_S FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rStudentId OR @rStudentId = 0)
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND ( SourceTypeId =2003)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 16) as datetime),D16,D16_IN,D16_OUT,D16_O,D16_L,D16_T,D16_E,D16_S FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rStudentId OR @rStudentId = 0)
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND ( SourceTypeId =2003)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 17) as datetime),D17,D17_IN,D17_OUT,D17_O,D17_L,D17_T,D17_E,D17_S FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rStudentId OR @rStudentId = 0)
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND ( SourceTypeId =2003)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 18) as datetime),D18,D18_IN,D18_OUT,D18_O,D18_L,D18_T,D18_E,D18_S FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rStudentId OR @rStudentId = 0)
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND ( SourceTypeId =2003)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 19) as datetime),D19,D19_IN,D19_OUT,D19_O,D19_L,D19_T,D19_E,D19_S FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rStudentId OR @rStudentId = 0)
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND ( SourceTypeId =2003)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 20) as datetime),D20,D20_IN,D20_OUT,D20_O,D20_L,D20_T,D20_E,D20_S FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rStudentId OR @rStudentId = 0)
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND ( SourceTypeId =2003)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 21) as datetime),D21,D21_IN,D21_OUT,D21_O,D21_L,D21_T,D21_E,D21_S FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rStudentId OR @rStudentId = 0)
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND ( SourceTypeId =2003)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 22) as datetime),D22,D22_IN,D22_OUT,D22_O,D22_L,D22_T,D22_E,D22_S FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rStudentId OR @rStudentId = 0)
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND ( SourceTypeId =2003)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 23) as datetime),D23,D23_IN,D23_OUT,D23_O,D23_L,D23_T,D23_E,D23_S FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rStudentId OR @rStudentId = 0)
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND ( SourceTypeId =2003)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 24) as datetime),D24,D24_IN,D24_OUT,D24_O,D24_L,D24_T,D24_E,D24_S FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rStudentId OR @rStudentId = 0)
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND ( SourceTypeId =2003)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 25) as datetime),D25,D25_IN,D25_OUT,D25_O,D25_L,D25_T,D25_E,D25_S FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rStudentId OR @rStudentId = 0)
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND ( SourceTypeId =2003)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 26) as datetime),D26,D26_IN,D26_OUT,D26_O,D26_L,D26_T,D26_E,D26_S FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rStudentId OR @rStudentId = 0)
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND ( SourceTypeId =2003)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 27) as datetime),D27,D27_IN,D27_OUT,D27_O,D27_L,D27_T,D27_E,D27_S FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rStudentId OR @rStudentId = 0)
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND ( SourceTypeId =2003)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 28) as datetime),D28,D28_IN,D28_OUT,D28_O,D28_L,D28_T,D28_E,D28_S FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rStudentId OR @rStudentId = 0)
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND ( SourceTypeId =2003)

	--IF  Month(@rFromDate) <> 2 or (((YEAR(@rFromDate) % 4 = 0 AND YEAR(@rFromDate) % 100 <> 0) OR YEAR(@rFromDate) % 400 = 0 And Month(@rFromDate)  =2)) 
	--BEGIN
		INSERT INTO #TempMonthTrans
		SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 29) as datetime),D29,D29_IN,D29_OUT,D29_O,D29_L,D29_T,D29_E,D29_S FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rStudentId OR @rStudentId = 0)
		 AND (((Month(@rFromDate) <> 2 or (((YEAR(@rFromDate) % 4 = 0 AND YEAR(@rFromDate) % 100 <> 0) OR YEAR(@rFromDate) % 400 = 0 And Month(@rFromDate)  =2))) AND ATTN_DT = cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime)) 
		OR ((Month(@rToDate) <> 2 or (((YEAR(@rToDate) % 4 = 0 AND YEAR(@rToDate) % 100 <> 0) OR YEAR(@rToDate) % 400 = 0 And Month(@rToDate)  =2))) AND ATTN_DT = cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)))
		AND ( SourceTypeId =2003)
	--END
	
	--IF Month(@rFromDate) <> 2
	--BEGIN
	INSERT INTO #TempMonthTrans
	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 30) as datetime),D30,D30_IN,D30_OUT,D30_O,D30_L,D30_T,D30_E,D30_S FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rStudentId OR @rStudentId = 0)
	AND ((Month(@rFromDate) <> 2 AND ATTN_DT = cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime)) Or (Month(@rToDate) <> 2 AND ATTN_DT = cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)))
	 AND ( SourceTypeId =2003)
	--END
	
	--IF Month(@rFromDate) NOT IN (2,4,6,9,11)
	--BEGIN
	INSERT INTO #TempMonthTrans
	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 31) as datetime),D31,D31_IN,D31_OUT,D31_O,D31_L,D31_T,D31_E,D31_S FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rStudentId OR @rStudentId = 0)
	AND ((Month(@rFromDate) NOT IN (2,4,6,9,11) AND ATTN_DT = cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime)) OR (Month(@rToDate) NOT IN (2,4,6,9,11) AND ATTN_DT = cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)))
	 AND ( SourceTypeId =2003)
	--END
	CREATE TABLE #TempMonthTransWitIoOutTime (EmployeeId bigint,Attn_Date DateTime,InTime nvarchar(20),OutTime nvarchar(20))
	if(@rIsDetail=1)
	BEGIN
	INSERT INTO #TempMonthTransWitIoOutTime
		SELECT  SourceId,Attn_Dt,CONVERT(VARCHAR(10), I.In_Out_Time, 108),CONVERT(VARCHAR(10), O.In_Out_Time, 108)
        FROM [sBiometric].[tCloudTransactionData] I
		OUTER APPLY (
						SELECT TOP 1    In_Out_Time,
										Mode
						FROM [sBiometric].[tCloudTransactionData] t
						WHERE       t.SourceId = I.SourceId
								AND t.In_Out_Time > I.In_Out_Time
								AND SourceTypeid=2003
								AND t.Attn_Dt =I.Attn_Dt
								AND Mode = 'OUT'
						ORDER BY t.In_Out_Time
					) O
		WHERE I.Mode = 'IN'
		AND SourceTypeid=2003
		AND I.Attn_Dt>=@rFromDate
		AND I.Attn_Dt<=@rToDate
		--select * from #TempMonthTransWitIoOutTime
	END

	Select 
		@rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2 ,
		SA.AcademicId AS AcademicId,
		SA.Code AS StudentCode,
		SA.Name AS StudentName,
		ISNULL(SA.RollNo,0) as RollNo,
		ISNULL(TM.FirstIn,'00:00') AS FirstIn,
		ISNULL(TM.LastOut,'00:00') AS LastOut,
		ISNULL(TM.LateBy,'00:00') AS LateBy,
		ISNULL(TM.EarlyBy,'00:00') AS EarlyBy,
		 ISNULL(TM.Duration,'00:00') AS Duration,
		 ISNULL(TM.PresentStatus,'XX') AS OldPresentStatus ,
		  CASE When (([sAttendance].[fWeekHOffGet]( YEAR(TM.Attn_Date) ,MONTH(TM.Attn_Date) ,DAY(TM.Attn_Date) ,@lBatchID,SA.ClassId,SA.DivisionId ,'' ,SA.OrgId )='H') AND (TM.FirstIn !='00:00'))  then 'PH'
		 When (([sAttendance].[fWeekHOffGet]( YEAR(TM.Attn_Date) ,MONTH(TM.Attn_Date) ,DAY(TM.Attn_Date) ,@lBatchID,SA.ClassId,SA.DivisionId ,'' ,SA.OrgId )='H') AND (TM.FirstIn='00:00')) THEN 'H'  
		 When (([sAttendance].[fWeekHOffGet]( YEAR(TM.Attn_Date) ,MONTH(TM.Attn_Date) ,DAY(TM.Attn_Date) ,@lBatchID,SA.ClassId,SA.DivisionId ,'' ,SA.OrgId )='W') AND (TM.FirstIn !='00:00'))  then 'PW'
		 When (([sAttendance].[fWeekHOffGet]( YEAR(TM.Attn_Date) ,MONTH(TM.Attn_Date) ,DAY(TM.Attn_Date) ,@lBatchID,SA.ClassId,SA.DivisionId ,'' ,SA.OrgId )='W') AND (TM.FirstIn ='00:00'))  then 'W'
		 When ((TM.PresentStatus='W')AND ([sAttendance].[fWeekHOffGet]( YEAR(TM.Attn_Date) ,MONTH(TM.Attn_Date) ,DAY(TM.Attn_Date) ,@lBatchID,SA.ClassId,SA.DivisionId ,'' ,SA.OrgId )!='W') AND (TM.FirstIn !='00:00'))  then 'P'
		 When ((TM.PresentStatus='PW')AND ([sAttendance].[fWeekHOffGet]( YEAR(TM.Attn_Date) ,MONTH(TM.Attn_Date) ,DAY(TM.Attn_Date) ,@lBatchID,SA.ClassId,SA.DivisionId ,'' ,SA.OrgId )!='W') AND (TM.FirstIn !='00:00'))  then 'P'
		 When ((TM.PresentStatus='W')AND ([sAttendance].[fWeekHOffGet]( YEAR(TM.Attn_Date) ,MONTH(TM.Attn_Date) ,DAY(TM.Attn_Date) ,@lBatchID,SA.ClassId,SA.DivisionId ,'' ,SA.OrgId )!='W') AND (TM.FirstIn ='00:00'))  then 'A'
		 WHEN ((TM.PresentStatus='W') AND (TM.FirstIn !='00:00')) THEN 'PW' 
		 ELSE
		TM.PresentStatus END as PresentStatus,
		TM.Attn_Date,
		OM.DisplayTitle AS Organization,
		CM.DisplayTitle AS ClassName,
		CM.Id AS ClassId,
		DM.DisplayTitle AS DivisionName,
		DM.Id AS DivisionId,
		Dept.DisplayTitle AS Department,
		Dept.Id AS DepartmentId,
		CM.Title+'-'+DM.DisplayTitle As ClassDivision,
		Dept.OrderIndex AS OrderIndex,
		DM.OrderIndex AS DivisionOrderIndex,
		SA.OrgId AS OrgId,
		TM.ShiftName,
		CTD.*,
		@rIsDetail AS IsDetail
				
		From #TempMonthTrans TM   
	 INNER JOIN sBiometric.tMonthTrans MT ON MT.EmployeeId=TM.EmployeeId AND SourceTypeId = 2003  
	 INNER JOIN sStudent.vStudentAcademic SA  ON SA.StudentId = TM.EmployeeId AND MT.SourceTypeId=2003 --AND MT.ATTN_DT = cast(rtrim(YEAR(@rAttendanceDate) *10000+ Month(@rAttendanceDate)  *100+ 01) as datetime)
	INNER JOIN sStudent.tStudentAdmission AD ON SA.StudentId = AD.StudentId
	INNER JOIN sSetup.tDivisionMaster DM  ON  SA.DivisionId=DM.Id
	INNER JOIN sSetup.tClassMaster CM ON CM.Id=DM.ClassId
	INNER JOIN sSetup.tDepartmentMaster Dept ON Dept.Id=CM.DepartmentId 
	INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = DM.OrgId
	INNER JOIN sSetup.tBatchClass BC ON BC.ClassId = CM.Id
	Left Join #TempMonthTransWitIoOutTime CTD ON  CTD.EmployeeId=TM.EmployeeId AND CTD.Attn_Date=TM.Attn_Date  
	INNER JOIN sSetup.tBatchMaster BM ON BC.BatchId = BM.Id AND BM.OrgGroupBatchId=@rOrgGroupBatchId --AND BM.IsActive=1
	WHERE 
		((SA.ClassId=@rClassId) OR (@rClassId=0))
			AND ((SA.DivisionId=@rDivisionId) OR (@rDivisionId=0))
			AND OM.OrgGroupId=@rOrgGroupId
			AND (SA.OrgId=@rOrgId OR @rOrgId=0)
			AND (SA.StudentId=@rStudentId OR @rStudentId=0)
			--AND (SA.BatchId = @rBatchId)
			AND ( (SA.StatusId =  @rStatusId) OR @rStatusId=0)
			AND (AD.LeftDate > @rFromDate OR ISNULL(AD.LeftDate,'')= '')
			AND (AD.AdmissionDate <= @rToDate)
			 AND MT.Attn_dt=cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime)
			 AND (( @rTimeSheetStatus = '1' AND (TM.Duration < '09:30')) OR ( @rTimeSheetStatus != '1' AND ((PresentStatus = @rTimeSheetStatus OR @rTimeSheetStatus='0'))))
			AND (SA.OrgId = @rOrgId OR @rOrgId = 0)
			 AND((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
			 AND(( SA.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
			 AND (TM.Attn_Date>=@rFromDate )
			 AND (TM.Attn_Date<=@rToDate)
	ORDER BY SA.RollNo

	DROP Table #TempMonthTrans	

	--Select 
	--	@rBuilder1 AS Builder1,
	--	@rBuilder2 AS Builder2 ,
	--	@rIsDetail AS IsDetail,
	--	CAST(0 AS bigint) AS AcademicId,
	--	'' AS StudentCode,
	--	'' AS StudentName,
	--	0 as RollNo,
	--	'' AS FirstIn,
	--	'' AS LastOut,
	--	'' AS LateBy,
	--	'' AS EarlyBy,
	--	 '' AS Duration,
	--	'' AS OldPresentStatus ,
	--	'' AS PresentStatus,
	--	CAST('' AS Date) AS Attn_Date, 
	--	'' AS Organization,
	--	'' AS ClassName,
	--	0 AS ClassId,
	--	'' AS DivisionName,
	--	0 AS DivisionId,
	--	'' AS Department,
	--	0 AS DepartmentId,
	--	'' As ClassDivision,
	--	0 AS OrderIndex,
	--	0 AS DivisionOrderIndex,
	--	0 AS OrgId,
	--	'' AS ShiftName,
	--	'' AS OutTime,
	--	'' as InTime

END
GO
PRINT N'Altering [sCertificate].[pRptFirstTrialCertificateGet]...';


GO
ALTER PROCEDURE [sCertificate].[pRptFirstTrialCertificateGet]
	 
	 @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)=''
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
DECLARE @lIsOnPrePrinted bit = 0

DECLARE @lIsDisplayImageHeader bit = 0

DECLARE @lConfigValue nvarchar(50)
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 = 179 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 = 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,
			FT.Id,
			FT.Number,
			FT.AcademicId,
			FT.FirstTrialDate,
			FT.ExamCentre,
			FT.ExamYear,
			FT.SeatNo,
			FT.Trial,
			SM.Code,
			--SM.FirstName+' '+SM.MiddleName+' '+SM.LastName AS Name,
			[sStudent].[fStudentNameGet](SM.FirstName , SM.MiddleName, SM.LastName,OM.StudentNameFormatId ) AS Name,
			SM.LastName as Surname,
			SO.GenderId,
			ISNULL(OM.CityName,'') AS City,
			ISNULL(OM.StateName,'') AS CityState,
			SM.StatusId,
			OM.OrgLogo,
			OM.Title AS OrgTitle,
			OM.StreetOne+' '+OM.StreetTwo+' '+OM.StreetThree AS OrgAddress,
			OM.PhoneNo,
			A.RollNo,
			DM.OrderIndex AS DivisionOrder,
			OM.ReportOrgTitle,
			OM.SmallAddress1,
			OM.SmallAddress2,
			OM.RegistrationDetail,
			@lIsOnPrePrinted AS IsOnPrePrinted,
			CM.DisplayTitle+' - '+DM.DisplayTitle AS Class,
			CM.DisplayTitle  AS ClassName,
			@lIsDisplayImageHeader AS IsDisplayImageHeader,
			--OI.CertificateHeaderA4  ,
			(CASE WHEN CGM.Title='10' THEN  'SSC'
			WHEN  CGM.Title='12'  THEN 'HSC'  ElSE CGM.Title + ' '+'std'
			 END) AS Exam,
			 FT.Remark AS Remark,
			 ISNULL(SF.FatherName,'') As FatherName,
			 ISNULL(SF.MotherName,'') As MotherName,
			 SA.AdmissionDate,
			 SO.BirthDateInWord ,
			 SO.DateOfBirth,
			 SI.StudentPhoto,
			 @lIDConfigValue AS ItemValue,
			 SM.SUID ,
			 STM.Title as StreamName,
			 ISNULL(OM.ReportOrgGroupTitle,'') AS ReportOrgGroupTitle,
			 OM.ReportOrgTitle,
			--(CASE WHEN OI.CertificateHeaderA4Portrait IS NULL THEN
			--OI.CertificateHeaderA4
			--ELSE OI.CertificateHeaderA4Portrait END ) AS CertificateHeader	
			OI.CertificateHeaderA4Portrait AS CertificateHeaderA4,
			BM.Title AS Batch,
			ISNULL(SA.LeftDate,'') AS LeftDate,
			ISNULL(EI.EmployeeSign,0x) AS EmployeeSign,
			ISNULL(OM.PrincipalSignature,0x) AS PrincipalSignature,
			EI.EmployeeId
	FROM 
			sCertificate.tFirstTrial FT
			INNER JOIN sStudent.tAcademic A ON FT.AcademicId=A.Id
			LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId=A.StudentId
			INNER JOIN sStudent.tStudentMaster SM ON SM.Id=A.StudentId			
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=A.OrgId
			INNER JOIN sStudent.tStudentOther SO ON SO.StudentId=A.StudentId
			INNER JOIN sSetup.tDivisionMaster DM ON A.DivisionId = DM.Id  
			INNER JOIN sSetup.tClassMaster CM ON CM.Id= DM.ClassId 
			INNER JOIN  sSetup.tStreamMaster STM ON STM.Id= CM.StreamId 
			Left JOIN sSetup.tOrgImages OI ON OI.OrgId = OM.Id
			LEFT JOIN sSetup.tClassGroupMaster CGM ON CGM.Id = CM.ClassGroupId
			LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId=A.StudentId
			LEFT JOIN sStudent.tStudentAdmission SA ON SA.StudentId=A.StudentId
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id=A.BatchId
			LEFT JOIN sHrm.tEmployeeImages EI ON EI.EmployeeId = DM.InchargeEmployeeId
			
	WHERE 
			A.OrgId=@rOrgId
			AND	A.BatchId = @rBatchId 
			AND ((A.ClassId=@rClassId) OR (@rClassId=0))
			AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId=0))
			AND ((SM.Code = @rCode) OR (ISNULL(@rCode,'') = ''))
			AND ((SM.FirstName = @rName) OR (ISNULL(@rName,'') = ''))
			AND ((FT.FirstTrialDate>=@rFromDate) OR (ISNULL(@rFromDate,'')=''))
			AND ((FT.FirstTrialDate<=@rToDate) OR (ISNULL(@rToDate,'')=''))
			AND ((FT.Number=@rNumber) OR (@rNumber=''))
			AND ((FT.Number >= @rFromNo) OR (@rFromNo=''))
			AND ((FT.Number <= @rToNo) OR (@rToNo=''))
			--Group By FT.AcademicId,SM.Code,SM.FirstName,SM.LastName,SM.MiddleName,FT.SeatNo,FT.Trial,SM.Code,SM.FirstName,OM.StateName,SO.GenderId,
			--OM.CityName,OM.StateName,FT.FirstTrialDate,FT.ExamCentre,FT.ExamYear,SM.MiddleName,SM.LastName,OM.CityName,SM.StatusId
			--,OM.OrgLogo,OM.PhoneNo,OM.Title,OM.StreetOne,OM.StreetTwo,OM.StreetThree
	END
GO
PRINT N'Altering [sCommon].[pCommonSearchGetHeaderList]...';


GO
ALTER PROCEDURE [sCommon].[pCommonSearchGetHeaderList]
	@rTableTitle [nvarchar](300)
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	
   DECLARE @lTableName Nvarchar(300)
   DECLARE @lTableSchema Nvarchar(300)
   SET @lTableName = PARSENAME(@rTableTitle, 1)
   SET @lTableSchema = PARSENAME(@rTableTitle, 2)
  
  PRINT @lTableName

   SELECT COLUMN_NAME AS ColumnName,
          DATA_TYPE AS ColDataType
          FROM INFORMATION_SCHEMA.COLUMNS 
          WHERE TABLE_NAME = @lTableName
	        	AND TABLE_SCHEMA = @lTableSchema 
				AND COLUMN_NAME !='BookImage'
				AND COLUMN_NAME !='AssetImage'

END
GO
PRINT N'Altering [sCommon].[pOrgGroupSetupRemove]...';


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

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




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

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

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


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

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

DELETE FROM sStudent.tCustomTagMaster WHERE OrgGroupId = @rOrgGroupId

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

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

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

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

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

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

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

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

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

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

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

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

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

DELETE FROM sErp.tCustomerMaster WHERE OrgGroupId = @rOrgGroupId

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

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

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


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


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

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


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

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

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

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


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

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

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


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

	-- special case will come orgwise and orggroupwise

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


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


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

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

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

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

DELETE FROM sSetup.tOrgGroupConfiguration WHERE OrgGroupId = @rOrgGroupId



DELETE FROM sCommon.tOrgGroupDepartmentMaster WHERE OrgGroupId = @rOrgGroupId

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


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

DELETE FROM sErp.tCustomerPlugInLog WHERE OrgGroupId= @rOrgGroupId

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

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

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


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

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

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

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

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

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

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

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

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

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

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

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

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


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

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

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

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


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

BEGIN 
	 IF @rIsSearch = 1
		BEGIN
			SET @rTitle = sCommon.fSearchStringGet(@rTitle)
		END
	
	SELECT 
		DISTINCT
			A.Id as AssignmentId,
			A.SubjectId,
			SM.Title as SubjectName,
			A.Title,
			A.Remark,
			A.StartDate,
			A.EndDate,
			U.DisplayTitle as CreatedUserName,
			STUFF((
			SELECT ',' + DM.Code FROM [sCommunication].[tAssignmentScope] CAS INNER JOIN sSetup.tDivisionMaster DM ON CAS.SourceId = DM.Id Where  CAS.AssignmentId = A.Id AND CAS.SourceTypeId = 2005 
			FOR XML PATH ('')), 1, 1, '') as StudentSource ,			 
			STUFF((			  
			SELECT ',' + Code FROM [sCommunication].[tAssignmentScope] CAS INNER JOIN sSetup.tDepartmentMaster CM ON CAS.SourceId = CM.Id Where CAS.AssignmentId = A.Id AND CAS.SourceTypeId = 2017			  
			FOR XML PATH ('')), 1, 1, '') as EmployeeSource,
			A.CreatedDateTime
		    
  FROM 
   --         sCommunication.tAssignment A
			--INNER JOIN [sCommunication].[tAssignmentScope] CAS on A.Id = CAS.AssignmentId
   --         INNER JOIN sSecurity.tUser U ON U.Id=A.CreatedUserId
   --         INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=A.SubjectId
			--INNER JOIN [sSetup].[tClassSubject] CS on CS.SubjectId = SM.Id												
			--LEFT JOIN [sSetup].[tDivisionMaster] DM on DM.Id = CAS.SourceId and CS.ClassId = Dm.classId 

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


GO

 
ALTER PROCEDURE [sEExam].[pDsTestParticipantAnswerAdd]
	 
	@rTestParticipantId bigint,
	@rTestId int,
	@rQuestionDetailXml [nvarchar](max),
	@rQuestionOptionDetailXml [nvarchar](max)
	--@rQuestionAnswer nvarchar(max)=''

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

	DECLARE @loQuestionDoc INT
	EXEC sp_xml_preparedocument @loQuestionDoc OUTPUT, @rQuestionDetailXml
	
	DECLARE @loQuestionOptionDoc INT
	EXEC sp_xml_preparedocument @loQuestionOptionDoc OUTPUT, @rQuestionOptionDetailXml
	
BEGIN

	BEGIN TRY	
	--BEGIN TRANSACTION
	DECLARE @lOrgGroupId int = 0
	Declare @lIDConfigValue nvarchar(50)=''

	SELECT @lOrgGroupId = OM.OrgGroupId FROM sEExam.tTestMaster TM
	INNER JOIN sSetup.tOrganizationMaster OM ON TM.OrgId = OM.Id
	WHERE TM.Id = @rTestId

	SELECT @lIDConfigValue =ItemValue From sConfig.tConfigurationSetup
	WHERE ConfigurationId = 140 AND SourceId = @lOrgGroupId	

	IF(@lIDConfigValue = 'False')
	BEGIN
	
		DELETE FROM sEExam.tTestParticipantAnswer WHERE TestParticipantId=@rTestParticipantId AND TestId=@rTestId
	
		UPDATE sEExam.tTestParticipant
			SET
				TestDate = A.TestDate,
				StartTime = A.StartTime,
				EndTime = A.EndTime,
				TestStatusId = A.TestStatusId,
				TotalMarks = A.TotalMarks,
				ScoredMarks = A.ScoredMarks,
				TotalQuestions = A.TotalQuestions,
				RightQuestions = A.RightQuestions,
				WrongQuestions = A.WrongQuestions,
				SkippQuestions = A.SkippQuestions,
				NotAttemptedQuestions = A.NotAttemptedQuestions
				FROM
			 (
		  SELECT TOP 1
				@rTestParticipantId AS TestParticipantId,
				@rTestId AS TestId,
				TestDate,
				StartTime,
				EndTime,
				TestStatusId,
				TotalMarks,
				ScoredMarks,
				TotalQuestions,
				RightQuestions,
				WrongQuestions,
				SkippQuestions,
				NotAttemptedQuestions
			FROM OPENXML (@loQuestionDoc, '/Table/QuestionDetail', 1)
			WITH ( 
					SourceTypeId smallint,
					SourceId bigint,
					TestDate date,
					StartTime time,
					EndTime time,
					TestStatusId smallint,
					TotalMarks decimal(6,2),
					ScoredMarks decimal(6,2),
					TotalQuestions int,
					RightQuestions int,
					WrongQuestions int,
					SkippQuestions int,
					NotAttemptedQuestions int
				  ))A	
					WHERE 
					--A.TestParticipantId = @rTestParticipantId AND A.TestId = @rTestId
					--AND 
					sEExam.tTestParticipant.Id = A.TestParticipantId
			    
		INSERT INTO sEExam.tTestParticipantAnswer
			(
				TestId,
				QuestionId,
				QuestionOptionId,
				ScoredMark,
				AnswerStatusId,
				OrderIndex,
				TestParticipantId,
				QuestionAnswer
			)
		  SELECT 
				@rTestId,
				QuestionId,
				QuestionOptionId,
				ScoredMark,
				AnswerStatusId,
				OrderIndex,
				@rTestParticipantId,
				sSetup.fPortalXMLTagsReplaceReverse(QuestionAnswer)
			
			FROM OPENXML (@loQuestionOptionDoc, '/Table/QuestionOptionDetail', 1)
			WITH ( 
					TestId Int,
					QuestionId bigint,
					QuestionOptionId bigint,
					ScoredMark decimal(6,2),
					AnswerStatusId smallint,
					OrderIndex smallint,
					QuestionAnswer nvarchar(max)
				  ) 
			SELECT 1 AS Result   
		END
		SELECT IsDisplayResultOnComplete FROM sEExam.tTestMaster WHERE Id =@rTestId
		
		EXEC sp_xml_removedocument @loQuestionDoc
		EXEC sp_xml_removedocument @loQuestionOptionDoc
		--COMMIT TRANSACTION
	END TRY
	BEGIN CATCH 
		--ROLLBACK TRANSACTION
		SELECT -1 AS Result
		EXEC sp_xml_removedocument @loQuestionDoc
		EXEC sp_xml_removedocument @loQuestionOptionDoc
	END CATCH	 
	 
	
   
END
GO
PRINT N'Altering [sFee].[pCollectionGroupGet]...';


GO
ALTER PROCEDURE [sFee].[pCollectionGroupGet]
		
		@rSourceId bigint,
		@rSourceTypeId int=0,
		@rReceiptBookId int=0,
		@rReceiptId bigint=0,
		@rBatchId int,
		@rCollectionGroupId int =0 
		
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
		
BEGIN 	
	DECLARE @lClassId int
		DECLARE @lAdmissionCategoryId int,@lOrgId int,@lOrgGorupId int
		SELECT @lClassId=ClassId,@lAdmissionCategoryId=AdmissionCategoryId,@lOrgId = OrgId FROM sStudent.vStudentAcademic WHERE AcademicId=@rSourceId	

		Select @lOrgGorupId = OrgGroupId from sSetup.tOrganizationMaster Where Id = @lOrgId
				
DECLARE @lConfigValue nvarchar(50)
--,@lOrgGroupBatchId int
--SELECT @lOrgGroupBatchId = OrgGroupBatchId FROM [sSetup].[tBatchMaster] WHERE Id = @rBatchId
SELECT @lConfigValue = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 487 AND SourceTypeId = 2010 AND SourceId = @lOrgGorupId


IF(@lConfigValue = 'True')
BEGIN
SELECT SUM(CG.PayableAmount) AS PendingAmount 
,CollectionGroupId,StartDate,EndDate,CollectionGroupName,ReceiptBookId,ReceiptBook FROM

(SELECT 
			FM.Id AS FeeId,
			FM.Title AS FeeName,
			FS.Id AS FeeSetupId,			 
			FS.ReceiptBookId,
			RBM.Title AS ReceiptBook,
			ISNULL(R.PaidAmount,0) AS PaidAmount,
			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,
			--FM.OrderIndex,
			FS.CollectionGroupId,
			CGM.StartDate,
			CGM.EndDate,
			CGM.Title AS CollectionGroupName,
			CGM.OrderIndex
  FROM 
		sFee.tFeeMaster FM
		INNER JOIN 
		(
			SELECT 
				FS1.FeeId,
				FS1.Id,
				ISNULL(FS1.IsOptional,0)AS IsOptional,
				ISNULL(FS1.IsVariable,0)AS IsVariable,
				ISNULL(FS1.Amount,0)AS Amount,
				ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
				ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
				FS1.BatchId,
				ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
				ISNULL(FS1.CollectionGroupId,0) AS CollectionGroupId
			FROM sFee.tFeeSetup FS1
				WHERE FS1.ClassId=@lClassId AND FS1.BatchId = @rBatchId  
				AND ((FS1.CollectionGroupId=@rCollectionGroupId) OR (@rCollectionGroupId=0))
				AND FS1.AdmissionCategoryId=@lAdmissionCategoryId AND IsOptional=0
				
				UNION ALL
				
			SELECT 
				FS1.FeeId,
				FS1.Id,
				ISNULL(FS1.IsOptional,0)AS IsOptional,
				ISNULL(FS1.IsVariable,0)AS IsVariable,
				ISNULL(FS1.Amount,0)AS Amount,
				ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
				ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
				FS1.BatchId,
				ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
				ISNULL(FS1.CollectionGroupId,0) AS CollectionGroupId
			FROM sFee.tFeeSetup FS1
		INNER JOIN sFee.tFeeOptional FO
			ON FO.FeeSetupId=FS1.Id AND (FO.SourceId=@rSourceId) AND ((FO.SourceTypeId=@rSourceTypeId) OR (@rSourceTypeId=0))
		WHERE
				FS1.ClassId=@lClassId AND FS1.BatchId =@rBatchId AND FS1.AdmissionCategoryId=@lAdmissionCategoryId AND IsOptional=1
				AND ((FS1.CollectionGroupId=@rCollectionGroupId) OR (@rCollectionGroupId=0))
				
		) 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 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 ((FSR.CollectionGroupId=@rCollectionGroupId) OR (@rCollectionGroupId=0))
			AND R.SourceId= @rSourceId
			AND ((R.SourceTypeId=@rSourceTypeId) OR (@rSourceTypeId=0))
			AND R.IsObsolete = 0 			 
			 GROUP BY FeeSetupId
		
		) R ON R.FeeSetupId = FS.Id 
		LEFT JOIN sFee.tFeeAllocation FA
			ON FA.FeeSetupId=FS.Id AND 
			(FA.SourceId=@rSourceId) AND ((FA.SourceTypeId=@rSourceTypeId) OR (@rSourceTypeId=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(@rReceiptId=0) OR(@rReceiptId<>0))
AND(FS.BatchId=@rBatchId)
AND CAST(sCommon.fGetDate() AS DATE) <= CAST(CGM.EndDate AS DATE)
AND CGM.IsObsolete = 0
  ) AS CG
  GROUP BY CollectionGroupId,StartDate,EndDate,CollectionGroupName,OrderIndex,ReceiptBookId,ReceiptBook
  ORDER BY CG.StartDate,CG.OrderIndex

END
ELSE
BEGIN
SELECT SUM(CG.PayableAmount) AS PendingAmount 
,CollectionGroupId,StartDate,EndDate,CollectionGroupName,ReceiptBookId,ReceiptBook FROM

(SELECT 
			FM.Id AS FeeId,
			FM.Title AS FeeName,
			FS.Id AS FeeSetupId,			 
			FS.ReceiptBookId,
			RBM.Title AS ReceiptBook,
			ISNULL(R.PaidAmount,0) AS PaidAmount,
			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,
			--FM.OrderIndex,
			FS.CollectionGroupId,
			CGM.StartDate,
			CGM.EndDate,
			CGM.Title AS CollectionGroupName,
			CGM.OrderIndex
  FROM 
		sFee.tFeeMaster FM
		INNER JOIN 
		(
			SELECT 
				FS1.FeeId,
				FS1.Id,
				ISNULL(FS1.IsOptional,0)AS IsOptional,
				ISNULL(FS1.IsVariable,0)AS IsVariable,
				ISNULL(FS1.Amount,0)AS Amount,
				ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
				ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
				FS1.BatchId,
				ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
				ISNULL(FS1.CollectionGroupId,0) AS CollectionGroupId
			FROM sFee.tFeeSetup FS1
				WHERE FS1.ClassId=@lClassId AND FS1.BatchId = @rBatchId  
				AND ((FS1.CollectionGroupId=@rCollectionGroupId) OR (@rCollectionGroupId=0))
				AND FS1.AdmissionCategoryId=@lAdmissionCategoryId AND IsOptional=0
				
				UNION ALL
				
			SELECT 
				FS1.FeeId,
				FS1.Id,
				ISNULL(FS1.IsOptional,0)AS IsOptional,
				ISNULL(FS1.IsVariable,0)AS IsVariable,
				ISNULL(FS1.Amount,0)AS Amount,
				ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
				ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
				FS1.BatchId,
				ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
				ISNULL(FS1.CollectionGroupId,0) AS CollectionGroupId
			FROM sFee.tFeeSetup FS1
		INNER JOIN sFee.tFeeOptional FO
			ON FO.FeeSetupId=FS1.Id AND (FO.SourceId=@rSourceId) AND ((FO.SourceTypeId=@rSourceTypeId) OR (@rSourceTypeId=0))
		WHERE
				FS1.ClassId=@lClassId AND FS1.BatchId =@rBatchId AND FS1.AdmissionCategoryId=@lAdmissionCategoryId AND IsOptional=1
				AND ((FS1.CollectionGroupId=@rCollectionGroupId) OR (@rCollectionGroupId=0))
				
		) 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 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 ((FSR.CollectionGroupId=@rCollectionGroupId) OR (@rCollectionGroupId=0))
			AND R.SourceId= @rSourceId
			AND ((R.SourceTypeId=@rSourceTypeId) OR (@rSourceTypeId=0))
			AND R.IsObsolete = 0 			 
			 GROUP BY FeeSetupId
		
		) R ON R.FeeSetupId = FS.Id 
		LEFT JOIN sFee.tFeeAllocation FA
			ON FA.FeeSetupId=FS.Id AND 
			(FA.SourceId=@rSourceId) AND ((FA.SourceTypeId=@rSourceTypeId) OR (@rSourceTypeId=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(@rReceiptId=0) OR(@rReceiptId<>0))
AND(FS.BatchId=@rBatchId)
AND CGM.IsObsolete = 0
  ) AS CG
  GROUP BY CollectionGroupId,StartDate,EndDate,CollectionGroupName,OrderIndex,ReceiptBookId,ReceiptBook
  ORDER BY CG.StartDate,CG.OrderIndex
END
END
GO
PRINT N'Altering [sFee].[pRptFeePendingDetailListOtherGet]...';


GO

ALTER PROCEDURE [sFee].[pRptFeePendingDetailListOtherGet]
		@rReportId int=0,
		@rReceiptBookId int,
		@rAdmissionCategoryId int,
		@rClassId int,
		@rDivisionId int,
		@rUptoDate date,
		@rBatchId int,
		@rUserId bigint,
		@rBuilder1 nvarchar(max),
		@rBuilder2 nvarchar(max),
		@rIsDetail bit,
		@rOrgId int,
		@rOrgGroupBatchId int,
		@rStatusId int,
		@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) = '',
		@rReportType int=1,
		@rClassStatusId int=0,
		@rClassIds nvarchar(max) = '',
		@rDivisionIds nvarchar(max) = ''
	    
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
BEGIN 	
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.FeeId,
		FS.FeeName,
		FS.FeeOrderIndex,
		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.Title,'') AS ReceiptBookTitle,
		--ISNULL(RBM.OrderIndex,0) AS ReceiptOrderIndex,
		SA.OrgGroupBatchId,
		SA.DepartmentId,
		SA.DepartmentName,
		ISNULL(SC.ParentContactNo,'') AS ParentContactNo,
		SAD.LeftDate AS LeftDate,
		SO.ReferenceRemark
  FROM 
  
			 sStudent.vStudentAcademic SA
		INNER JOIN 
		(
			SELECT 
				FS1.FeeId,
				FS1.Id,
				ISNULL(FS1.IsOptional,0)AS IsOptional,
				ISNULL(FS1.IsVariable,0)AS IsVariable,
				ISNULL(FS1.Amount,0)AS Amount,
				ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
				ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
				FS1.BatchId,
				ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
				SA1.Id AS AcademicId,
				FM.Title AS FeeName,
				FM.FeeHeadId,
				FM.OrderIndex AS FeeOrderIndex
			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
			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.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=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 ((FS1.StartDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
				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.AcademicId,
				FM.Title AS FeeName,
				FM.FeeHeadId,
				FM.OrderIndex AS FeeOrderIndex
			FROM sFee.tFeeSetup FS1
		INNER JOIN sFee.tFeeOptional FO
			ON FO.FeeSetupId=FS1.Id
	    INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
		INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=FO.SourceId AND SA1.BatchId = FS1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId AND SA1.ClassId = FS1.ClassId
			AND ((SA1.ClassId=@rClassId) OR (@rClassId=0)) AND ((SA1.DivisionId=@rDivisionId) OR (@rDivisionId=0))
			AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
		INNER JOIN sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
		AND (ISNULL(SA1.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='')		
		WHERE
		        SA1.OrgGroupBatchId = @rOrgGroupBatchId
				AND ((FS1.ClassId=@rClassId) OR (@rClassId=0))
				AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
				AND (FS1.IsOptional=1)
				AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
				AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))				
				AND (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 ((FS1.StartDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
				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='')
		) 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.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 (SA1.DivisionId=@rDivisionId OR @rDivisionId=0)
				AND (ISNULL(SA1.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='')
			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)
				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
				
				
		
		) 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
		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
	(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 sStudent.tStudentAdmission SAD ON SAD.StudentId=SA.StudentId
	LEFT JOIN sStudent.tStudentOther SO ON SA.StudentId = SO.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 ((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(FAS.VariableAmount,0.00)AS FAAmount,
		ISNULL(FAS.DiscountAmount,0.00)AS DiscountAmount,
		ISNULL(FAS.AdditionalAmount,0.00)AS AdditionalAmount,
		ISNULL(FAS.PaidAmount,0) AS PaidAmount,
		ISNULL(FAS.ToPayAmount,0)AS PendingAmount,
		--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(FAS.Remark,'') AS Remark,
		FS.FeeId,
		--FS.FeeName,
		FM.Title AS FeeName, 
		--FS.FeeOrderIndex,
		FM.OrderIndex AS FeeOrderIndex,
		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.Title,'') AS ReceiptBookTitle,
		--ISNULL(RBM.OrderIndex,0) AS ReceiptOrderIndex,
		SA.OrgGroupBatchId,
		SA.DepartmentId,
		SA.DepartmentName,
		ISNULL(SC.ParentContactNo,'') AS ParentContactNo,
		SAD.LeftDate AS LeftDate,
		SO.ReferenceRemark
  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 sStudent.tStudentCommunication SC ON SC.StudentId = SA.StudentId		
		LEFT JOIN sHostel.tAssignRoom AR ON  AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003 AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  AND ((AR.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) 
        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 sStudent.tStudentAdmission SAD ON SAD.StudentId=SA.StudentId
	LEFT JOIN sStudent.tStudentOther SO ON SA.StudentId = SO.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) !=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 (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 ((SA.ClassStatusId=@rClassStatusId) OR (@rClassStatusId=0)) 
			Order by SA.RollNo
END 
END
GO
PRINT N'Altering [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
	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(Time,FR.CreatedDateTime,108) AS CreatedTime
	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
	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,'') = ''))
    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,
--CAST('' AS Time) AS CreatedTime
--END
GO
PRINT N'Altering [sFee].[pRptFeeReceiptListGet]...';


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

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

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


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

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

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

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

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


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

		 ORDER BY R.ReceiptNumber
	END

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

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


GO
ALTER PROCEDURE [sFee].[pRptFeeStatusFeeHeadandBusRouteWiseGet]  

	@rOrgGroupBatchId int=0,
	@rCommonBatch nvarchar(100) = '',
	@rReceiptBookId int=0,
	--@rCollectionGroupId int =0,
	@rOrgId int=0,
	@rBatchId int=0,
	@rDepartmentId int=0,
	@rAdmissionCategoryId int=0,
	@rClassId int=0,  
	@rDivisionId int=0,
	@rUptoDate date='',
	@rStatusId int=0,
	@rBuilder1 nvarchar(max) = '',  
	@rBuilder2 nvarchar(max) = '', 
	@rClassStatusId int=0 ,
	@rBusRouteId int = 0 ,
	@rFeeGroupId int=0
	
	 
WITH EXECUTE AS CALLER  
AS  
SET NOCOUNT ON  
BEGIN 

	SELECT 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
		
			SA.AcademicId,
			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,
			FHM.Id AS FeeHeadId,
			FHM.Title AS FeeHeadName,
			RT.RouteNumber,
			ISNULL(RT.BusRoute,'') AS BusRoute,
			FHM.Number,
			FS.FeeName,
			@rFeeGroupId As FeeGroup,
			FS.OrderIndex AS FeeWiseOrderIndex
		
	  FROM 
			sStudent.vStudentAcademic SA
			INNER JOIN sStudent.tStudentAdmission tSA ON tSA.StudentId = SA.StudentId
			INNER JOIN 
			(
				SELECT 
					FS1.FeeId,
					FS1.Id,
					ISNULL(FS1.IsOptional,0)AS IsOptional,
					ISNULL(FS1.IsVariable,0)AS IsVariable,
					ISNULL(FS1.Amount,0)AS Amount,
					ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
					ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
					FS1.BatchId,
					ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
					SA1.AcademicId,
					FM.Title AS FeeName,
					--FM.Code AS FeeCode,
					FM.FeeHeadId,
					FM.OrderIndex
				FROM sFee.tFeeSetup FS1
				INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				AND ((SA1.ClassId=@rClassId) OR (@rClassId=0))
				AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
				WHERE 
					((FS1.ClassId=@rClassId) OR (@rClassId=0))
					AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
					AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
					AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
					AND (FS1.IsOptional=0)
					AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
					AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
					AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
					AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
				
					UNION ALL
					
				SELECT 
					FS1.FeeId,
					FS1.Id,
					ISNULL(FS1.IsOptional,0)AS IsOptional,
					ISNULL(FS1.IsVariable,0)AS IsVariable,
					ISNULL(FS1.Amount,0)AS Amount,
					ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
					ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
					FS1.BatchId,
					ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
					SA1.AcademicId,
					FM.Title AS FeeName,
					--FM.Code AS FeeCode,
					FM.FeeHeadId,
					FM.OrderIndex
				FROM sFee.tFeeSetup FS1
			INNER JOIN sFee.tFeeOptional FO ON FO.FeeSetupId=FS1.Id 
			INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
			INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=FO.SourceId AND FS1.BatchId = SA1.BatchId
			AND SA1.ClassId=FS1.ClassId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				AND ((SA1.ClassId=@rClassId) OR (@rClassId=0)) 
				AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				--AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='') 
				--AND (ISNULL(SA1.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='') 
			WHERE
				((FS1.ClassId=@rClassId) OR (@rClassId=0))
				AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
				AND (FS1.IsOptional=1)
				AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
				AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
				--AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
				--AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
				--AND (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR @rOrgGroupId=0)
			
			) FS ON FS.AcademicId=SA.AcademicId
			LEFT JOIN sFee.tFeeAllocation FA ON FA.FeeSetupId=FS.Id AND FA.SourceId=SA.AcademicId
			LEFT JOIN
			(
				SELECT 
						ISNULL(SUM(RD.Amount),0) AS PaidAmount,RD.FeeSetupId ,R.SourceId
				FROM
						sFee.tReceipt R 
					INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id 
					INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id
					INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id
					INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=R.SourceId 
					AND ((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
					AND (SA1.ClassId=@rClassId OR @rClassId=0) 
					AND (SA1.DivisionId=@rDivisionId OR @rDivisionId=0)
			
				WHERE		
					(R.SourceTypeId = 2001)
					AND (R.IsObsolete = 0) 
					AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
					AND (SA1.OrgGroupBatchId = @rOrgGroupBatchId OR @rOrgGroupBatchId=0)
					AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
					--AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))
					AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
					AND (R.ReceiptDate <= @rUptoDate)
					
						GROUP BY FeeSetupId,R.SourceId
			
			) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
			 INNER JOIN sSetup.tOrganizationMaster O ON SA.OrgId = O.Id
			 INNER JOIN sFee.tReceiptBookMaster RBM ON FS.ReceiptBookId=RBM.Id
			 INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FS.FeeHeadId	
			 LEFT JOIN sFee.tExemptionTypeMaster ETM ON ETM.Id = SA.ExemptionTypeId
			 LEFT JOIN sHostel.tAssignRoom AR ON  AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003 AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  AND ((AR.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) 
			 LEFT JOIN
			(SELECT AT.SourceId,B.RouteNumber,B.Title AS BusRoute 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))
			AND ((B.Id = @rBusRouteId) OR (@rBusRouteId = 0))) RT
			ON RT.SourceId = SA.StudentId AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) 
			LEFT JOIN sStudent.tStudentAdmission SAD ON SAD.StudentId=SA.StudentId
			WHERE	
			((SA.BatchId=@rBatchId) OR (@rBatchId=0))   
			AND	((SA.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))   
			AND (SA.StatusId=@rStatusId OR @rStatusId=0)
			AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))		
			AND ((SA.ClassId=@rClassId) OR (@rClassId=0))
			AND ((SA.DivisionId=@rDivisionId) OR (@rDivisionId=0))
			 AND (
					 --(@rFilterId = 0) -- All
					 --OR (@rFilterId = 2 AND isnull(AR.SourceId,0)!=0) -- Hostel
					 (isnull(RT.SourceId,0)!=0) -- Transport
					 --OR ((@rFilterId =1) AND ((isnull(AR.SourceId,0)=0) AND (isnull(RT.SourceId,0)=0)))
					 )	

		 AND ((SA.ClassStatusId=@rClassStatusId) OR (@rClassStatusId=0)) 
		 AND ((FS.StartDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
		 AND (FHM.Number=1001)
		Order by SA.RollNo

		--SELECT
		--'' AS Builder1,  
		--'' AS Builder2,  
		--0 AS AcademicId,  
		--0 PaidAmount,  
		--0 AS PendingAmount,  
		--0 AS FeeHeadId,  
		--'' AS FeeHeadName, 
		--0 AS RouteNumber,
		--'' AS BusRoute
	

END
GO
PRINT N'Altering [sFrontOffice].[pVisitorLogGet]...';


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

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


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


GO
 
ALTER PROCEDURE [sFrontOffice].[pVisitorLogListingGet]
       
    @rVisitorId int=0,
    @rFromVisitDate datetime='',
    @rToVisitDate datetime='',
    @rOrgId int=0,
    @rWhomToMeetName nvarchar(100)='',
    @rIsPrintView bit=0,
    @rOrgGroupId int =0,
    @rTypeId int=0 ,
	@rStatusId int=0 ,
	@rUserSourceId bigint = 0
          
AS
SET NOCOUNT ON

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


BEGIN
SELECT  
	   VL.Id As VisitorId,
       VL.VisitorName,
       VL.NoOfVisitor,
       VL.PurposeOfVisit,
       VL.WhomToMeet AS WhomToMeetId,
       isnull(case when isnull(VL.WhomToMeet,0)!=0 then isnull(EM.EmployeeName,'') end,'' )+ (case when isnull(VL.StudentId,0)!=0 AND isnull(VL.WhomToMeet,0)!=0 then ',' else '' end)+
	   isnull(case when  isnull(VL.StudentId,0)!=0 Then sStudent.fStudentNameGet(STM.FirstName, STM.MiddleName,STM.LastName, OM1.StudentNameFormatId) end,'') AS  WhomToMeetName,
       CONVERT(Varchar,VL.InTime,108)AS InTime,
       CONVERT(Varchar,VL.OutTime,108)AS OutTime,
       ISNULL(VL.VisitDate,'1900-01-01 00:00:00') AS VisitDate,
       --VL.CreatedDateTime ,
       (CASE  WHEN @rIsPrintView=1 THEN 
				VL.VisitorPhoto		
			ELSE ISNULL(VL.VisitorPhoto, CONVERT(VARBINARY(MAX), 0)) END) AS VisitorPhoto,
       --ISNULL(VL.VisitorPhoto, CONVERT(VARBINARY(MAX), 0)) AS VisitorPhoto,
       VL.OrgId,
       ISNULL(OM.DisplayTitle,'') AS Organization,
       ISNULL(Remark,'') AS Remark,
       @GatePassConfig AS ConfigValue,
	   ISNUll(VisitorContactNumber,'') AS VisitorContactNumber,
	   ISNULL(StudentId,0) AS StudentId,
	   ISNULL(VTM.Title, '') AS VisitorType,
	   --(CASE WHEN ISNULL(VL.TypeId,'')!='' then case when VL.TypeId=1 then 'Visitor' else 'Parents' end
			 --when ISNULL(VL.StudentId,0)=0 THEN 'Visitor'
			 --ELSE 'Parents' END) AS VisitorType,
	   (CASE WHEN ISNULL(VL.OutTime,'00:00:00')='00:00:00' THEN 0
			 ELSE 1 END) AS InOutStatus,
		OM.OrgGroupId AS OrgGroupId,
		ISNULL(VL.StatusId,0) as StatusId,
		SM.Title as Status,
		ISNULL(VL.TypeId, 0) AS VisitorTypeId
		--(CASE WHEN ISNULL(VL.TypeId,'')!='' then case when VL.TypeId=1 then 1 else 2 end
		--	 when ISNULL(VL.StudentId,0)=0 THEN 1
		--	 ELSE 2 END) AS VisitorTypeId
		
  FROM  sFrontOffice.tVisitorLog VL 
  INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=VL.OrgId
  LEFT JOIN sCommon.tStatusMaster SM ON SM.Id = VL.StatusId
  Left Join  sHrm.vExtEmployeeMaster EM on EM.EmployeeId=VL.WhomToMeet
  left Join sStudent.tStudentMaster STM On STM.Id=VL.StudentId  
  left JOIN sSetup.tOrganizationMaster AS OM1 ON STM.OrgId = OM1.Id 
  LEFT JOIN [sFrontOffice].[tVisitorTypeMaster] AS VTM ON VTM.Id = VL.TypeId 

  WHERE 
	(VL.OrgId=@rOrgId OR @rOrgId=0) 
	AND OM.OrgGroupId=@rOrgGroupId
	AND (VL.Id=@rVisitorId OR @rVisitorId=0)
	AND (((VL.WhomToMeetName LIKE @rWhomToMeetName) OR  (isnull(EM.EmployeeId,0)>0 AND EM.EmployeeName Like  @rWhomToMeetName) OR (isnull(STM.Id,0)>0 AND sStudent.fStudentNameGet(STM.FirstName, STM.MiddleName,STM.LastName, OM1.StudentNameFormatId) like  @rWhomToMeetName)) OR (ISNULL(@rWhomToMeetName,'')=''))
	AND (VL.VisitDate>=@rFromVisitDate OR ISNULL(@rFromVisitDate,'')='')
	AND (VL.VisitDate<=@rToVisitDate OR ISNULL(@rToVisitDate,'')='')
	--AND ((ISNULL(VL.TypeId,0)=0 AND (ISNULL(VL.StudentId,1) = @rTypeId) OR  (@rTypeId=0) OR (((VL.StudentId > 0 AND @rTypeId=2) OR  @rTypeId=0)))  OR (ISNULL(VL.TypeId,0)!=0 AND ((VL.TypeId=@rTypeId) or (@rTypeId=0)))) -- Visitor 
	AND ((VL.TypeId = @rTypeId) OR (@rTypeId = 0))
	AND ((VL.StatusId = @rStatusId) OR (ISNULL(@rStatusId,0) = 0)) 
	--AND (ISNULL(VL.StatusId,0) != 0)
	AND ((VL.WhomToMeet = @rUserSourceId) OR (ISNULL(@rUserSourceId,0) = 0))
	
  ORDER BY VL.VisitDate DESC,VL.InTime DESC
END
GO
PRINT N'Altering [sHrm].[pEmployeeAttendanceRegisterReportProcess]...';


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

BEGIN 
		Declare @ldate datetime,@lDays int
		declare @Days int
		Declare @Firstdate datetime
		Declare @Lastdate datetime
		
		Set @ldate= CONVERT(nvarchar(10), @rForYear)+ '-' +  CONVERT(nvarchar(10), @rForMonth) + '-' + CONVERT(nvarchar(10), 01)
		Select @lDays=day(dateadd(mm,DateDiff(mm, -1, @ldate),0) -1) 
		select @Days=sCommon.fGetDaysInMonth(@rForMonth,@rForYear)
		
		set @Firstdate=CONVERT(nvarchar(10), @rForYear)+ '-' +  CONVERT(nvarchar(10), @rForMonth) + '-' + CONVERT(nvarchar(10), 01)
		set @Lastdate=CONVERT(nvarchar(10), @rForYear)+ '-' +  CONVERT(nvarchar(10), @rForMonth) + '-' + CONVERT(nvarchar(10), @Days)
		
		
		DELETE FROM [sHrm].[tTempEmployeeAttendanceRegister]
			INSERT INTO [sHrm].[tTempEmployeeAttendanceRegister]
			SELECT 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2, 
			EM.Code AS EmployeeCode,
			EM.EmployeeId,
			EM.EmployeeName,   
			EM.DepartmentName,
			EM.EmployeeGrade,      
		   	sCommon.fGetDaysInMonth (@rForMonth,@rForYear) AS TotalDays,
		    [sHrm].[fAttendanceWithLeaveGet](EM.EmployeeId,@rForYear,@rForMonth,'01',@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-01')),EM.DateOfJoining,EM.DateOfLeaving,'') AS P1,
			[sHrm].[fAttendanceWithLeaveGet](EM.EmployeeId,@rForYear,@rForMonth,'02',@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-02')),EM.DateOfJoining,EM.DateOfLeaving,'') AS P2,
			[sHrm].[fAttendanceWithLeaveGet](EM.EmployeeId,@rForYear,@rForMonth,'03',@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-03')),EM.DateOfJoining,EM.DateOfLeaving,'') AS P3,
			[sHrm].[fAttendanceWithLeaveGet](EM.EmployeeId,@rForYear,@rForMonth,'04',@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-04')),EM.DateOfJoining,EM.DateOfLeaving,'') AS P4,
			[sHrm].[fAttendanceWithLeaveGet](EM.EmployeeId,@rForYear,@rForMonth,'05',@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-05')),EM.DateOfJoining,EM.DateOfLeaving,'') AS P5,
			[sHrm].[fAttendanceWithLeaveGet](EM.EmployeeId,@rForYear,@rForMonth,'06',@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-06')),EM.DateOfJoining,EM.DateOfLeaving,'') AS P6,
			[sHrm].[fAttendanceWithLeaveGet](EM.EmployeeId,@rForYear,@rForMonth,'07',@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-07')),EM.DateOfJoining,EM.DateOfLeaving,'') AS P7,
			[sHrm].[fAttendanceWithLeaveGet](EM.EmployeeId,@rForYear,@rForMonth,'08',@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-08')),EM.DateOfJoining,EM.DateOfLeaving,'') AS P8,
			[sHrm].[fAttendanceWithLeaveGet](EM.EmployeeId,@rForYear,@rForMonth,'09',@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-09')),EM.DateOfJoining,EM.DateOfLeaving,'') AS P9,
			[sHrm].[fAttendanceWithLeaveGet](EM.EmployeeId,@rForYear,@rForMonth,'10',@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-10')),EM.DateOfJoining,EM.DateOfLeaving,'') AS P10,
			[sHrm].[fAttendanceWithLeaveGet](EM.EmployeeId,@rForYear,@rForMonth,'11',@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-11')),EM.DateOfJoining,EM.DateOfLeaving,'') AS P11,
			[sHrm].[fAttendanceWithLeaveGet](EM.EmployeeId,@rForYear,@rForMonth,'12',@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-12')),EM.DateOfJoining,EM.DateOfLeaving,'') AS P12,
			[sHrm].[fAttendanceWithLeaveGet](EM.EmployeeId,@rForYear,@rForMonth,'13',@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-13')),EM.DateOfJoining,EM.DateOfLeaving,'') AS P13,
			[sHrm].[fAttendanceWithLeaveGet](EM.EmployeeId,@rForYear,@rForMonth,'14',@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-14')),EM.DateOfJoining,EM.DateOfLeaving,'') AS P14,
			[sHrm].[fAttendanceWithLeaveGet](EM.EmployeeId,@rForYear,@rForMonth,'15',@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-15')),EM.DateOfJoining,EM.DateOfLeaving,'') AS P15,
			[sHrm].[fAttendanceWithLeaveGet](EM.EmployeeId,@rForYear,@rForMonth,'16',@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-16')),EM.DateOfJoining,EM.DateOfLeaving,'') AS P16,
			[sHrm].[fAttendanceWithLeaveGet](EM.EmployeeId,@rForYear,@rForMonth,'17',@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-17')),EM.DateOfJoining,EM.DateOfLeaving,'') AS P17,
			[sHrm].[fAttendanceWithLeaveGet](EM.EmployeeId,@rForYear,@rForMonth,'18',@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-18')),EM.DateOfJoining,EM.DateOfLeaving,'') AS P18,
			[sHrm].[fAttendanceWithLeaveGet](EM.EmployeeId,@rForYear,@rForMonth,'19',@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-19')),EM.DateOfJoining,EM.DateOfLeaving,'') AS P19,
			[sHrm].[fAttendanceWithLeaveGet](EM.EmployeeId,@rForYear,@rForMonth,'20',@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-20')),EM.DateOfJoining,EM.DateOfLeaving,'') AS P20,
			[sHrm].[fAttendanceWithLeaveGet](EM.EmployeeId,@rForYear,@rForMonth,'21',@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-21')),EM.DateOfJoining,EM.DateOfLeaving,'') AS P21,
			[sHrm].[fAttendanceWithLeaveGet](EM.EmployeeId,@rForYear,@rForMonth,'22',@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-22')),EM.DateOfJoining,EM.DateOfLeaving,'') AS P22,
			[sHrm].[fAttendanceWithLeaveGet](EM.EmployeeId,@rForYear,@rForMonth,'23',@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-23')),EM.DateOfJoining,EM.DateOfLeaving,'') AS P23,
			[sHrm].[fAttendanceWithLeaveGet](EM.EmployeeId,@rForYear,@rForMonth,'24',@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-24')),EM.DateOfJoining,EM.DateOfLeaving,'') AS P24,
			[sHrm].[fAttendanceWithLeaveGet](EM.EmployeeId,@rForYear,@rForMonth,'25',@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-25')),EM.DateOfJoining,EM.DateOfLeaving,'') AS P25,
			[sHrm].[fAttendanceWithLeaveGet](EM.EmployeeId,@rForYear,@rForMonth,'26',@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-26')),EM.DateOfJoining,EM.DateOfLeaving,'') AS P26,
			[sHrm].[fAttendanceWithLeaveGet](EM.EmployeeId,@rForYear,@rForMonth,'27',@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-27')),EM.DateOfJoining,EM.DateOfLeaving,'') AS P27,
			[sHrm].[fAttendanceWithLeaveGet](EM.EmployeeId,@rForYear,@rForMonth,'28',@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-28')),EM.DateOfJoining,EM.DateOfLeaving,'') AS P28,
			CASE WHEN @Days>=29 THEN[sHrm].[fAttendanceWithLeaveGet](EM.EmployeeId,@rForYear,@rForMonth,'29',@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-29')),EM.DateOfJoining,EM.DateOfLeaving,'') end AS P29,
			CASE WHEN @Days>=30 THEN[sHrm].[fAttendanceWithLeaveGet](EM.EmployeeId,@rForYear,@rForMonth,'30',@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-30')),EM.DateOfJoining,EM.DateOfLeaving,'')end AS P30,
			CASE WHEN @Days>=31 THEN[sHrm].[fAttendanceWithLeaveGet](EM.EmployeeId,@rForYear,@rForMonth,'31',@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-31')),EM.DateOfJoining,EM.DateOfLeaving,'')end AS P31
			,LTM.Code
			,EM.Number
			,(SELECT ISNULL(SUM(CONVERT(decimal(12,2), '.'+PARSENAME(NoOfLeave,1))),0) FROM sHrm.tLeave WHERE LeaveTypeId = LTM.Id AND FromDate BETWEEN @FirstDate AND @LastDate AND StatusId!=551 AND OrgId = @rOrgId AND BatchId = @rBatchId AND EmployeeId = EM.EmployeeId) AS LeaveCount
			
			FROM
			sHrm.vEmployeeCommonDetail EM
			INNER JOIN sHrm.tEmployeeMaster E ON E.Id = EM.EmployeeId				
			INNER JOIN sHrm.tLeaveTypeMaster LTM ON E.OrgID=LTM.OrgId						
			
    		WHERE 
    		EM.OrgID = @rOrgId 
    		AND ((EM.EmployeeGradeId=@rEmployeeGradeId) OR (@rEmployeeGradeId=0))
    		AND ((EM.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
    		AND ((EM.Code like @rEmployeeCode) OR (@rEmployeeCode=''))
    		AND ((EM.EmployeeName like @rEmployeeName) OR (@rEmployeeName=''))
    		AND ((EM.EmployeeId=@rEmployeeId) OR (@rEmployeeId=0))
    		AND ((EM.EmployeeStatusId=@rStatusId) OR (@rStatusId=0))
    		AND ((EM.EmployeeStatusId=@rEmployeeStatusId) OR (@rEmployeeStatusId=0))
    		AND (EM.DateOfJoining<= @Lastdate OR ISNULL(EM.DateOfJoining,'')='')
    		AND (EM.DateOfleaving>= @Firstdate OR ISNULL(EM.DateOfleaving,'')='')
    		--AND ((ISNULL(EM.DateOfJoining,''))<=CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-'+CONVERT(NVARCHAR(2),IN(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31)))))			
			AND EM.IsOtherUser = 0

			SELECT 1 AS Result
			--SELECT * FROM [sHrm].[tTempEmployeeAttendanceRegister]
		
END
GO
PRINT N'Altering [sHrm].[pImportUser]...';


GO
ALTER PROCEDURE [sHrm].[pImportUser]
    
    @rOrgId int,
	@rXmldoc [nvarchar](max),
	@rCreatedUserId bigint 
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

	DECLARE @loXML XML,@lCount int,
			@lUserType nvarchar(100),
			@lEmployeeCode nvarchar(100),
			@lUserName nvarchar(100),
			@lDisplayName nvarchar(100),
			@lPassword nvarchar(500),
			@lRole nvarchar(100),
			@lRoleId bigint
	
	SET @loXML = CAST(@rXmldoc AS XML)
	
	CREATE TABLE #tTable1 (
	Id bigint identity,
	UserType nvarchar(50) collate SQL_Latin1_General_CP1_CI_AS ,
	EmployeeCode nvarchar(100) collate SQL_Latin1_General_CP1_CI_AS ,
	UserName nvarchar(100) collate SQL_Latin1_General_CP1_CI_AS ,
	DisplayName nvarchar(100) collate SQL_Latin1_General_CP1_CI_AS ,
	[Password] nvarchar(500) collate SQL_Latin1_General_CP1_CI_AS ,
	[Role] nvarchar(100) collate SQL_Latin1_General_CP1_CI_AS ,
	RoleId bigint)
	
	INSERT INTO #tTable1(
		UserType,
		EmployeeCode,
		UserName,
		DisplayName, 
		[Password],
		[Role],
		RoleId)      
	SELECT
		 T.c.value('@UserType','nvarchar(50)') AS UserType,
		 T.c.value('@EmployeeCode','nvarchar(100)') AS EmployeeCode,
		 T.c.value('@UserName','nvarchar(100)') AS UserName,
		 T.c.value('@DisplayName','nvarchar(100)') AS DisplayName,
		 T.c.value('@Password','nvarchar(500)') AS [Password],
		 T.c.value('@Role','nvarchar(100)') AS [Role],
		 T.c.value('@RolId','nvarchar(100)') AS RoleId
	FROM @loXML.nodes('/Table/ImportUser')T(c)
  			
BEGIN

	DECLARE @rUserSourceId bigint = NULL, @rUserSourceTypeId bigInt = NULL, @EmployeeId bigint = NULL, @tmp varchar(500),@tmp1 varchar(500)

	SET @tmp = ''
	SET @tmp1 =''
	
	SELECT @tmp = @tmp + T.EmployeeCode  + ', '  from #tTable1 T 
	LEFT JOIN  sHrm.tEmployeeMaster EM ON T.EmployeeCode  = EM.Code 
	AND EM.OrgId = @rOrgId 
	WHERE EM.ID IS NULL AND T.EmployeeCode <> '' AND ISNULL(EM.IsOtherUser,0) = 0 AND upper(T.UserType) = 'EMPLOYEE' 
 
	SELECT @tmp1 = @tmp1 + T.EmployeeCode  + ', '  from #tTable1 T 
	LEFT JOIN  sStudent.tStudentMaster SM ON T.EmployeeCode  = SM.Code 
	AND SM.OrgId = @rOrgId  
	WHERE SM.ID IS NULL AND T.EmployeeCode <> '' AND upper(T.UserType) = 'STUDENT'

	IF @tmp <> ''
	BEGIN
		SELECT -101 AS Result, SUBSTRING(@tmp, 0, LEN(@tmp)) AS ResultDetail
		RETURN
	END

	IF @tmp1 <> ''
	BEGIN
		SELECT -102 AS Result, SUBSTRING(@tmp1, 0, LEN(@tmp1)) AS ResultDetail
		RETURN
	END

	SELECT @lCount =  COUNT(Id) FROM #tTable1
 
	WHILE @lCount > 0 
	BEGIN		
		SELECT         
			@lUserType = UserType ,
			@lEmployeeCode = EmployeeCode,
			@lUserName = UserName,
			@lDisplayName = DisplayName,
			@lPassword = [Password],
			@lRole = [Role],
			@lRoleId = RoleId
		FROM #tTable1 WHERE Id = @lCount    
	     
		IF UPPER(@lUserType) = 'EMPLOYEE'
		BEGIN
		 SELECT @rUserSourceId = Id FROM sHrm.tEmployeeMaster WHERE Code = @lEmployeeCode AND OrgID=@rOrgId AND ISNULL(IsOtherUser,0) = 0
		 SELECT @rUserSourceTypeId = 95
		END

		ELSE IF(UPPER(@lUserType) = 'STUDENT')
		BEGIN
			SELECT @rUserSourceId = Id FROM sStudent.tStudentMaster WHERE Code = @lEmployeeCode AND OrgID=@rOrgId 
			SELECT @rUserSourceTypeId =2003
		END

		ELSE
		BEGIN
			 SELECT @rUserSourceId = 0
			 SELECT @rUserSourceTypeId = 1
		END
							
		IF EXISTS(SELECT Id FROM sSecurity.tUser WHERE SourceId = @rUserSourceId AND OrgId=@rOrgId)
		BEGIN
			UPDATE sSecurity.tUser
			SET	
				LoginPassword = @lPassword,				
				IsObsolete = 0,			
				UpdatedUserId = @rCreatedUserId,
				UpdatedDateTime = sCommon.fGetDate(),
				LoginTitle = @lUserName,
				DisplayTitle = @lDisplayName
			WHERE 
				SourceId = @rUserSourceId AND OrgId=@rOrgId			
		END
		ELSE
		BEGIN
			DECLARE @lNextNumber BIGINT	
			EXECUTE  sCommon.pTableRowIdGet @rOrgId, 'sSecurity.tUser', 0, 101, 1,@outNextNumber = @lNextNumber output
			INSERT INTO sSecurity.tUser
				(
					Id,		
					DisplayTitle,
					LoginTitle,
					LoginPassword,
					LastLockOutDate,
					NumberOfLogonAttempt,
					IsObsolete,
					CreatedUserId,
					CreatedDateTime,
					UpdatedUserId,
					UpdatedDateTime,
					OrgId,
					SourceId,
					SourceTypeId	
				)
			VALUES
				(
					@lNextNumber,
					@lDisplayName,					
					@lUserName,
					@lPassword,
					sCommon.fGetDate(),
					0,
					0,
					@rCreatedUserId,
					sCommon.fGetDate(),
					@rCreatedUserId,
					sCommon.fGetDate(),
					@rOrgId,
					@rUserSourceId,
					@rUserSourceTypeId
				)
				
			IF NOT EXISTS(Select 1 From [sSecurity].[tUserRole]  WHERE RoleId = @lRoleId AND UserId=@lNextNumber)
			BEGIN
				INSERT INTO 
				[sSecurity].[tUserRole] (RoleId, UserId, IsObsolete, CreatedUserId, CreatedDateTime, UpdatedUserId, UpdatedDateTime, IsPrimary)
				VALUES
				(@lRoleId,@lNextNumber,0,@rCreatedUserId,sCommon.fGetDate(),@rCreatedUserId,sCommon.fGetDate(),1)
			END
		END
		SET @lCount = @lCount-1
	  END 
	SELECT 1 AS Result, '' AS ResultDetail
 END
END
GO
PRINT N'Altering [sHrm].[pRptJoiningCertificateGet]...';


GO
ALTER PROCEDURE [sHrm].[pRptJoiningCertificateGet]  
 
  @rEmployeeId [bigint]= 0, 
  @rBuilder1 nvarchar(max)='',  
  @rBuilder2 nvarchar(max)='',    
  @rOrgId smallint,  
  @rCode nvarchar(20)='',  
  @rFromNo int=0,  
  @rToNo int=0,  
  @rFromDate date='',  
  @rToDate date='',  
  @rName nvarchar(20)=''

WITH EXECUTE AS CALLER  
AS  
SET NOCOUNT ON  
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED  
  
BEGIN  
DECLARE @lIsOnPrePrinted bit = 0  
  
DECLARE @lConfigValue nvarchar(50)  
DECLARE @lIsDisplayImageHeader bit=0  
  
SELECT @lConfigValue = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 182 AND SourceTypeId = 1016 AND SourceId = @rOrgId  
   
 IF (@lConfigValue IS NULL) OR (@lConfigValue = 'Default')  
 BEGIN  
 SET @lIsOnPrePrinted = 0  
 SET @lIsDisplayImageHeader = 0  
 END  
 ELSE IF (@lConfigValue = 'Blank')  
 BEGIN  
 SET @lIsOnPrePrinted = 1  
 SET @lIsDisplayImageHeader = 0  
 END  
 ELSE IF (@lConfigValue = 'Image')  
 BEGIN  
 SET @lIsOnPrePrinted = 0  
 SET @lIsDisplayImageHeader = 1  
 END  
   
 SELECT  
   @rBuilder1 AS Builder1,  
   @rBuilder2 AS Builder2,  
   EM.Id AS EmployeeId,
   CJ.Number,
   EM.EmployeeName,
   EM.FirstName,  
   EM.MiddleName,  
   EM.LastName,      
   EM.Code,    
   EM.ShortName,  
   EM.OrgID,  
   EM.DepartmentId,  
   EM.DepartmentName,  
   EM.DesignationId,  
   EM.Designation,  
   EM.EmployeePhoto, 
   EM.DateOfJoining, 
   @lIsOnPrePrinted AS IsOnPrePrinted,  
   @lIsDisplayImageHeader AS IsDisplayImageHeader,  
   OI.CertificateHeaderA4 ,  
   CJ.Remark,  
   ISNULL(CJ.CertificateDate,'') AS CertificateDate,  
   EM.MaritalStatusId,  
   CJ.PayScale,  
   CJ.AgreementPeriod,
   CJ.CertificateRemark,
   OM.Title As OrgTitle,
   CJ.CreatedDateTime As CreatedDateTime,
   U.DisplayTitle As UserDisplayName,
   EDM.Title AS EmployeeDesignation,
   OM.DisplayTitle As ShortTitle,
   DM.Title AS DepartmentName1,
   EM.MobileNumber,
   --EC.PresentStreetOne+'-'+EC.PresentStreetTwo+ '-' +EC.PresentStreetThree AS LocalAddress,
    EC.PresentStreetOne  + CASE WHEN EC.PresentStreetOne = '' OR (EC.PresentStreetTwo = '' AND EC.PresentStreetThree = '') Then '' ELSE '-' END 
   		    + EC.PresentStreetTwo + CASE WHEN EC.PresentStreetTwo = '' OR EC.PresentStreetThree = '' Then '' ELSE '-' END	
			+ EC.PresentStreetThree AS LocalAddress,
   --EC.PresentCity+ '-'+EC.PresentState+'-'+EC.PresentZipCode+'-'+EC.PresentContactNo As LocalAddress1,
	EC.PresentCity  + CASE WHEN EC.PresentCity = '' OR (EC.PresentState = '' AND EC.PresentZipCode = '' AND EC.PresentContactNo = '') Then '' ELSE '-' END 
		+ EC.PresentState + CASE WHEN EC.PresentState = '' OR (EC.PresentZipCode = '' AND EC.PresentContactNo = '') Then '' ELSE '-' END	
		+ EC.PresentZipCode + CASE WHEN EC.PresentZipCode = '' OR EC.PresentContactNo = '' Then '' ELSE '-' END
		+ EC.PresentContactNo AS LocalAddress1,
   ISNULL(EDM1.Title,'Admin') AS UserDesignation,
   --Replace(Replace(RTrim(Ltrim(EC.PresentCity +' '+ EC.PresentState +' '+ EC.PresentZipCode)),'  ',' '),' ','-') AS LocalAddress2
   EC.PresentCity  + CASE WHEN EC.PresentCity = '' OR (EC.PresentState = '' AND EC.PresentZipCode = '') Then '' ELSE '-' END 
   		    + EC.PresentState + CASE WHEN EC.PresentState = '' OR EC.PresentZipCode = '' Then '' ELSE '-' END	
			+ EC.PresentZipCode AS LocalAddress2,
	ISNULL(CJ.DateOfJoining,'') As CertificateDateOfJoining

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


GO
ALTER PROCEDURE [sIp].[pImportStockIem]
	@rOrgId int,
	@rXmldoc [nvarchar](max),
	@rUserId bigint,
	@rStoreLocationId int,
	@rOrgGroupId smallint,
	@rLocationId int
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	DECLARE @lCount INT
	DECLARE @lInterrorCode INT,@intDoc INT,@lCode nvarchar(20),
	@lName nvarchar(100),@lSubGroup nvarchar(100),
	@lStockItemCategory nvarchar(100),@lIssueUOM nvarchar(50),
	@lSubGroupId int,@lStockItemCategoryId int,@lIssuUOMId int,
	@lResult int,@lresultCode nvarchar(100),@lIsBatchWiseTracking bit,
	@lSafetyStock decimal(12,2),@lStandardDose nvarchar(500),@lReminder nvarchar(500),@lStandardPrice decimal(22,6)
	Declare @lbinCode nvarchar(20),@lVendorCode nvarchar(50),@lVendorCategory nvarchar(50),
	@lBinId int,@lVendorId int, @lVendorCategoryId int

	Declare @loXML XML
    SET @loXML = CAST(@rXmldoc AS XML)

	EXECUTE @lInterrorCode = sp_xml_preparedocument @intDoc OUTPUT, @rXmlDoc

	CREATE TABLE #tTable1 
	(
		Id int identity,Code nvarchar(50),Name nvarchar(100),SubGroup nvarchar(100),
		StockItemCategory nvarchar(100),IssueUOM nvarchar(50),SafetyStock decimal(12,2),
		BinCode nvarchar(50),VendorCode nvarchar(50), IsBatchWiseTracking bit ,StandardPrice decimal(22,6)
	)
	INSERT INTO #tTable1
	Select 
		 T.c.value('@Code','nvarchar(20)') AS Code,
            T.c.value('@Name','nvarchar(100)') AS Name,
            T.c.value('@SubGroup','nvarchar(100)') AS SubGroup,
            T.c.value('@StockItemCategory','Nvarchar(100)') AS StockItemCategory,
            T.c.value('@IssueUOM','nvarchar(50)')   AS IssueUOM,
            T.c.value('@SafetyStock','Decimal(12,2)') AS SafetyStock,
            T.c.value('@BinCode','nvarchar(50)') AS BinCode,
            T.c.value('@VendorCode','nvarchar(50)') AS VendorCode,
			T.c.value('@IsBatchWiseTracking','bit') AS IsBatchWiseTracking,
			T.c.value('@StandardPrice','decimal(22,6)') AS StandardPrice
	
	FROM 
            @loXML.nodes('/Table/ImportStockItem')T(c)
	--INSERT INTO #tTable1
	--(
	--	Code,Name,SubGroup,StockItemCategory,IssueUOM,SafetyStock,BinCode,
	--	VendorCode, IsBatchWiseTracking
	--)      
	--SELECT Code,Name,SubGroup,StockItemCategory,IssueUOM,SafetyStock,BinCode,
	--VendorCode, IsBatchWiseTracking
	--FROM OPENXML (@intDoc, '/Table/ImportStockItem', 1)
	--With
	--(   
	--	Code nvarchar(20) '@Code',Name nvarchar(100) '@Name',
	--	SubGroup nvarchar(100) '@SubGroup',
	--	StockItemCategory nvarchar(100) '@StockItemCategory',
	--	IssueUOM nvarchar(50) '@IssueUOM',
	--	SafetyStock decimal(12,2) '@SafetyStock',
	--	BinCode nvarchar(50) '@BinCode',
	--	VendorCode nvarchar(50) '@VendorCode',
	--	--VendorCategory nvarchar(50) '@VendorCategory',
	--	IsBatchWiseTracking  '@IsBatchWiseTracking'
	--)
	EXEC sp_xml_removedocument @intDoc
	SELECT @lCount = COUNT(Id) FROM #tTable1
	PRINT @lCount
	WHILE @lCount > 0 
	BEGIN
		SELECT @lCode = Code,@lName = [ssetup].[fPortalXMLTagsReplaceReverse](Name),@lSubGroup = SubGroup,
		@lStockItemCategory = StockItemCategory,@lIssueUOM = IssueUOM,
		@lSafetyStock=SafetyStock,@lbinCode=BinCode,
		@lVendorCode=VendorCode, @lIsBatchWiseTracking=IsBatchWiseTracking, @lStandardPrice = StandardPrice
		FROM #tTable1 WHERE Id = @lCount
		
		IF NOT EXISTS(SELECT 1 FROM sIp.tStockItemMaster where Code = @lCode AND StoreLocationId = @rStoreLocationId)           
		BEGIN
			SELECT @lSubGroupId = Id From sIp.tItemSubGroupMaster where Title = @lSubGroup
			SELECT @lStockItemCategoryId= Id From sIp.tStockItemCategoryMaster where Title = @lStockItemCategory AND Storelocationid=@rStoreLocationId
			
			Select @lBinId = Id from sIp.tBinMaster where StoreLocationId =@rStoreLocationId And Code = @lBinCode
			Select @lVendorId = Id from sProcurement.tVendorMaster where LocationId= @rStoreLocationId And Code=@lVendorCode
			--Select @lVendorCategoryId=Id from sProcurement.tVendorCategoryMaster Where OrgGroupId =@rOrgGroupId And Code=@lVendorCategory
			
			SELECT @lIssuUOMId= Id From sFinanceCommon.tStockUomMaster where Title = @lIssueUOM AND OrgGroupId=@rOrgGroupId
			
			if  @lBinId is null	
			BEGIN
				Select -1 As Result
				Return
			END

			if @lVendorId is null
			BEGIN
				Select -2 As Result
				Return
			END
			
			if @lIssuUOMId is null
			BEGIN
				Select -11 As Result
				Return
			END
			--Select @lIssuUOMId AS IssuUOMId,@lStockItemCategoryId AS StockItemCategoryId,@lSubGroupId AS SubGroupId
			--SET @lResult = -101
			print @lIssuUOMId
			print @lSubGroupId

			IF(@lSubGroupId > 0  AND @lIssuUOMId>0)
			BEGIN
				DECLARE @lNextNumber INT
				EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sIp.tStockItemMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
				  
				INSERT INTO	sIp.tStockItemMaster
				(
					Id,Code,Title,CreatedUserId,CreatedDateTime,UpdatedUserId,
					UpdatedDateTime,StockItemCategoryId,IsBatchWiseTracking,
					IssueStockUomId,ItemSubGroupId,SafetyStock,VendorId,
					IsObsolete,OrgGroupId,TaxGroupId,Remark,IsBlockedForIssue,
					StoreLocationId,LocationId,StandardDose,BinId,Reminder
				)
				VALUES
				(
					@lNextNumber,@lCode,@lName,@rUserId,sCommon.fGetDate(),
					@rUserId,sCommon.fGetDate(),@lStockItemCategoryId,
					@lIsBatchWiseTracking,@lIssuUOMId,@lSubGroupId,
					@lSafetyStock,@lVendorId,0,@rOrgGroupId,null,null,0,
					@rStoreLocationId,@rLocationId,null,@lBinId,@lReminder
				)
				
				
				EXECUTE [sIp].[pStockItemPlanningAdd] 0,@lNextNumber,0,0,0,@lStandardPrice,null,null,@rStoreLocationId,@rOrgGroupId
  				EXECUTE sProcurement.pStockBatchAdd  @rOrgGroupId,@rStoreLocationId,@lNextNumber,null,null,0,@rUserId ,0 
  	
				--EXECUTE	sIp.pStockItemPurchaseUomAdd @rOrgGroupId,@lNextNumber,@rIssueStockUomId,1,0,@rCreatedUserId	
				--EXEC [sIp].[pItemStandardPriceLogAdd] @lNextNumber, @rStandardPrice, @rCreatedUserId,@rOrgGroupId
 
				SET @lResult = 1
				
				Set @lresultCode= @lCode
				 
			END
		END
		  
		ELSE
		BEGIN
			Set @lResult=-101
			Set @lresultCode= @lCode
		END
		SET @lCount = @lCount - 1
	END
	Select @lResult AS Result,@lresultCode AS Code
END
GO
PRINT N'Altering [sLibrary].[pRptReaderBookListGet]...';


GO
ALTER PROCEDURE [sLibrary].[pRptReaderBookListGet]

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

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


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

		@rEasebuzzKey nvarchar(50)='',
		@rEasebuzzSalt nvarchar(50)='',
		@rEasebuzzIsLiveEnvironment bit = null,
		@rEasebuzzIsEnableiFrame bit = null,
		@rEasebuzzSubMerchantId nvarchar(50)=''
		
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY

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

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

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

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


GO
 
 
 ALTER PROCEDURE [sOp].[pGatewayProductGet]

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

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

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

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

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

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

			ISNULL(GP.EasebuzzKey,'') AS EasebuzzKey,
			ISNULL(GP.EasebuzzSalt,'') AS EasebuzzSalt,
			ISNULL(GP.EasebuzzIsLiveEnvironment, '') AS EasebuzzIsLiveEnvironment,
			ISNULL(GP.EasebuzzIsEnableiFrame, '') AS EasebuzzIsEnableiFrame,
			ISNULL(GP.EasebuzzSubMerchantId,'') AS EasebuzzSubMerchantId
	FROM 
			[sOp].[tGatewayProduct] GP
			INNER JOIN [sOp].[tGatewayConfiguration] GC ON GC.Id = GP.GatewayConfigurationId
			INNER JOIN [sOp].[tPaymentGatewayMaster] PGM ON PGM.Id = GC.PaymentGatewayId
	WHERE 
			(GC.OrgGroupId = @rOrgGroupId)
			AND	((GP.Id = @rId) OR (@rId = 0))
			AND	((GP.GatewayConfigurationId = @rGatewayConfigurationId) OR (@rGatewayConfigurationId = 0))
			AND ((GP.Title like @rTitle) OR (ISNULL(@rTitle,'') = ''))
			AND ISNULL(GC.IsObsolete,0) = 0
END
GO
PRINT N'Altering [sSetup].[pOrgGroupMasterAdd]...';


GO
ALTER PROCEDURE [sSetup].[pOrgGroupMasterAdd]
	 
	@rId int,
	@rCode nvarchar(20),
	@rTitle nvarchar(100),
	@rCRMLicenceNo int,
	@rPunchLine nvarchar(200),
	@rOrgGroupBatchName nvarchar(20),
	@rFromDate date,
	@rToDate date,
	@rIsWindowSupport bit=0,
	  @rIsSync bit = 0
	
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	 
	IF(@rId=0)
		BEGIN
		IF EXISTS(SELECT 1 FROM sSetup.tOrgGroupMaster WHERE Code=@rCode)
		BEGIN
			SELECT -100 AS Result
			RETURN
		END
	END
	
	BEGIN TRANSACTION	
		IF(@rId=0)
		BEGIN
		
			DECLARE @lOrgGroupId smallint
			DECLARE @lOrgGroupBatchId int
			SET @lOrgGroupId=@rCode
			DECLARE @lCreatedUserId Int
			SET @lCreatedUserId = 1
			DECLARE @lCreatedDateTime DATETIME
			SET @lCreatedDateTime =  sCommon.fGetDate()
			
	
			
			INSERT INTO sSetup.tOrgGroupMaster
			(
				Id,
				Code,
				Title,
				PunchLine,
				CRMLicenceNo,
				IsWindowSupport
			)
			VALUES
			(
				@rCode,
				@rCode,
				@rTitle,
				@rPunchLine,
				@rCRMLicenceNo,
				@rIsWindowSupport
			)
			
	 IF ( @rIsSync = 0)
 BEGIN
			
			SELECT @lOrgGroupBatchId=ISNULL(MIN(Id),(Convert(nvarchar(10),Convert(nvarchar(10),@lOrgGroupId))+'00000')+1) 
			FROM sSetup.tOrgGroupBatchMaster WHERE OrgGroupId=@lOrgGroupId
			
					 INSERT INTO [sSetup].[tOrgGroupBatchMaster]
					   ([Id]
					   ,[Code]
					   ,[Title]
					   ,[OrgGroupId]
					   ,[IsHistory]
					   ,[IsActive]
					   ,[IsObsolete]
					   ,[OrderIndex]
					   ,[FromDate]
					   ,[ToDate]
					   ,[CreatedUserId]
					   ,[CreatedDateTime]
					   ,[UpdatedUserId]
					   ,[UpdatedDateTime])
			     
				  SELECT @lOrgGroupBatchId
					   ,@rOrgGroupBatchName
					   ,@rOrgGroupBatchName
					   ,@lOrgGroupId
					   ,0
					   ,1
					   ,0
					   ,1
					   ,@rFromDate
					   ,@rToDate
					  ,@lCreatedUserId
					  ,@lCreatedDateTime
					  ,@lCreatedUserId
					  ,@lCreatedDateTime
 END
			
			 INSERT INTO [sSecurity].[tRole]
				   ([Id]
				   ,[Title]
				   ,[Remark]
				   ,[IsObsolete]
				   ,[CreatedUserId]
				   ,[CreatedDateTime]
				   ,[UpdatedUserId]
				   ,[UpdatedDateTime]
				   ,[IsSystem]
				   ,[OrgGroupId])
			SELECT
				   sCommon.fGetIntIdForOrg(Id,@lOrgGroupId)
				  ,[Title]
				  ,[Remark]
				  ,[IsObsolete]
				  ,@lCreatedUserId
				  ,@lCreatedDateTime
				  ,@lCreatedUserId
				  ,@lCreatedDateTime
				  ,[IsSystem]
				  ,@lOrgGroupId
			  FROM [sSecurity].[tRole] WHere OrgGroupId=1          

			INSERT INTO [sFinanceCommon].[tStockUomMaster]
					   ([Id]
					   ,[Code]
					   ,[Title]
					   ,[IsObsolete]
					   ,[CreatedUserId]
					   ,[CreatedDateTime]
					   ,[UpdatedUserId]
					   ,[UpdatedDateTime]
					   ,[OrgGroupId])
				 SELECT
						 sCommon.fGetIntIdForOrg(6,@lOrgGroupId)
						,'Nos'
						,'Nos'
						,0
						,@lCreatedUserId
						,@lCreatedDateTime
						,@lCreatedUserId
						,@lCreatedDateTime
						,@lOrgGroupId
				 --FROM [sFinanceCommon].[tStockUomMaster] WHERE OrgGroupId=1
	
	
	
				INSERT INTO [sStudent].[tAdmissionCategoryMaster]
					   ([Id]
					   ,[Code]
					   ,[Title]
					   ,[IsObsolete]
					   ,[CreatedUserId]
					   ,[CreatedDateTime]
					   ,[UpdatedUserId]
					   ,[UpdatedDateTime]
					   ,[OrgGroupId])
				 SELECT
						 sCommon.fGetIntIdForOrg(1,@lOrgGroupId)
						,'General'
						,'General'
						,0
						,@lCreatedUserId
						,@lCreatedDateTime
						,@lCreatedUserId
						,@lCreatedDateTime
						,@lOrgGroupId
				 --FROM [sStudent].[tAdmissionCategoryMaster]
				 -- WHERE OrgGroupId=1

				
				
				INSERT INTO [sCommon].[tTableRowId]
					   ([OrgId]
					   ,[TableTitle]
					   ,[CurrentNumber]
					   ,[Seed]
					   ,[Increment])
				SELECT
					   @lOrgGroupId
					  ,[TableTitle]
					  
					  ,CASE 
				  WHEN IdDataType = 'int' THEN sCommon.fGetIntIdForOrg(ISNULL(CurrentNumber,0),@lOrgGroupId) 
				  WHEN IdDataType = 'bigint' THEN sCommon.fGetbigIntIdForOrg(ISNULL(CurrentNumber,0),@lOrgGroupId )
					END 
					
					  ,CASE 
				  WHEN IdDataType = 'int' THEN sCommon.fGetIntIdForOrg(ISNULL(CurrentNumber,0),@lOrgGroupId) 
				  WHEN IdDataType = 'bigint' THEN sCommon.fGetbigIntIdForOrg(ISNULL(CurrentNumber,0),@lOrgGroupId )
					END  
					   ,1
				  FROM [sCommon].[tTableRowIdMaster] where 
				  (tableType = 'Non Static' or tableType = '100Static' )
				  AND iddatatype <> '' AND IdScope = 'OrgGroup'

				
			--		INSERT INTO [sCommon].[tTableRowId]
			--           ([OrgId]
			--           ,[TableTitle]
			--           ,[CurrentNumber]
			--           ,[Seed]
			--           ,[Increment])
			--SELECT
			--		   0
			--		  ,[TableTitle]		  
			--		  ,CurrentNumber		
			--		  ,CurrentNumber
			--		  ,1
			--	  FROM [sCommon].[tTableRowIdMaster] where 
			--	  (tableType =   '100StaticCommon') 
			--	  AND IdScope = 'OrgGroup' 
			
			
			
				INSERT INTO sCommunication.tCircularTypeMaster
					   ([Id]
					   ,[Code]
					   ,[Title]
					   ,[IsObsolete]
					   ,[CreatedUserId]
					   ,[CreatedDateTime]
					   ,[UpdatedUserId]
					   ,[UpdatedDateTime]
					   ,[OrgGroupId]
					   ,HighlightColor)
				 SELECT
						 sCommon.fGetIntIdForOrg(1,@lOrgGroupId)
						,'Circular'
						,'Circular'
						,0
						,@lCreatedUserId
						,@lCreatedDateTime
						,@lCreatedUserId
						,@lCreatedDateTime
						,@lOrgGroupId
						,'#0000CC'
						
				INSERT INTO sCommunication.tCircularTypeMaster
					   ([Id]
					   ,[Code]
					   ,[Title]
					   ,[IsObsolete]
					   ,[CreatedUserId]
					   ,[CreatedDateTime]
					   ,[UpdatedUserId]
					   ,[UpdatedDateTime]
					   ,[OrgGroupId]
					   ,HighlightColor)
				 SELECT
						 sCommon.fGetIntIdForOrg(2,@lOrgGroupId)
						,'Alert'
						,'Alert'
						,0
						,@lCreatedUserId
						,@lCreatedDateTime
						,@lCreatedUserId
						,@lCreatedDateTime
						,@lOrgGroupId
						,'#006600'



			INSERT INTO sCommon.tReligionMaster
					   ([Id]
					   ,[Code]
					   ,[Title]
					   ,[IsObsolete]
					   ,[CreatedUserId]
					   ,[CreatedDateTime]
					   ,[UpdatedUserId]
					   ,[UpdatedDateTime]
					   ,[OrgGroupId]
					    )
				 SELECT						
						sCommon.fGetIntIdForOrg(ID,@lOrgGroupId)
					   ,[Code]
					   ,[Title]
					   ,[IsObsolete]
					   ,[CreatedUserId]
					   ,[CreatedDateTime]
					   ,[UpdatedUserId]
					   ,[UpdatedDateTime]
					   ,@lOrgGroupId
					   FROM sCommon.tReligionMaster WHERE OrgGroupId = 1
						

			INSERT INTO [sFrontOffice].[tVisitorTypeMaster]
					   (
						[Id]
					   ,[Code]
					   ,[Title]
					   ,[IsObsolete]
					   ,[CreatedUserId]
					   ,[CreatedDateTime]
					   ,[UpdatedUserId]
					   ,[UpdatedDateTime]
					   ,[OrgGroupId]
					   )
				 SELECT
					  
					   sCommon.fGetIntIdForOrg(ID,@lOrgGroupId)
					   ,[Code]
					   ,[Title]
					   ,[IsObsolete]
					   ,[CreatedUserId]
					   ,[CreatedDateTime]
					   ,[UpdatedUserId]
					   ,[UpdatedDateTime]
					   ,@lOrgGroupId
					   FROM [sFrontOffice].[tVisitorTypeMaster] WHERE OrgGroupId = 1
					   
					   
 			
				INSERT INTO sAdmission.tInquiryStatusMaster
					   ([Id]
					   ,[Code]
					   ,[Title]
					   ,[IsObsolete]
					   ,[CreatedUserId]
					   ,[CreatedDateTime]
					   ,[UpdatedUserId]
					   ,[UpdatedDateTime]
					   ,[OrgGroupId]
					   ,StatusId
					   )

				 SELECT
						 sCommon.fGetIntIdForOrg(Id,@lOrgGroupId)
						,Title
						,Title
						,0
						,1
						,sCommon.fGetDate()
						,NULL
						,NULL
						,@lOrgGroupId
						,Id	
						FROM sCommon.tStatusMaster SM
						where statustypeId = 104

				UPDATE ISM  
						SET ISM.HighlightColor = ISM1.HighlightColor ,
							ISM.InquiryMainStatusId = ISM1.InquiryMainStatusId
						FROM sAdmission.tInquiryStatusMaster ISM  
						INNER JOIN sAdmission.tInquiryStatusMaster ISM1 ON ISM.StatusId = ISM1.StatusId AND ISM1.OrgGroupId = 1
						INNER JOIN sCommon.tStatusMaster SM ON SM.Id = ISM1.StatusId 
						where SM.statustypeId = 104 AND ISM.OrgGroupId = @lOrgGroupId
						
				 Insert Into sCommunication.tFeedbackAnswerTypeMaster
				(
						Id,
						Code,
						Title,
						IsObsolete,
						OrgGroupId,
						CreatedUserId,
						CreatedDateTime,
						UpdatedUserId,
						UpdatedDateTime,
						FeedBackAnswerGroupMasterId
				)
				Values
				(
						sCommon.fGetIntIdForOrg(1,@lOrgGroupId),
						'Numeric',
						'Numeric',
						0,
						@lOrgGroupId,
						@lCreatedUserId,
						@lCreatedDateTime,
						NULL,
						NULL,
						2
				)
						
				Insert Into sCommunication.tFeedbackAnswerTypeMaster
				(
						Id,
						Code,
						Title,
						IsObsolete,
						OrgGroupId,
						CreatedUserId,
						CreatedDateTime,
						UpdatedUserId,
						UpdatedDateTime,
						FeedBackAnswerGroupMasterId
				)
				Values
				(
						sCommon.fGetIntIdForOrg(2,@lOrgGroupId),
						'Free Text',
						'Free Text',
						0,
						@lOrgGroupId,
						@lCreatedUserId,
						@lCreatedDateTime,
						NULL,
						NULL,
						3
				)
						
	DECLARE @lMaxId int
	SET @lMaxId = sCommon.fGetIntIdForOrg(213,@lOrgGroupId)					
	EXECUTE sCommon.pTableRowIdModify @lOrgGroupId, @rTableTitle = 'sAdmission.tInquiryStatusMaster', @rCurrentNumber = @lMaxId
						
 
					   
		END
		ELSE
		BEGIN
			UPDATE sSetup.tOrgGroupMaster
			SET
				Title=@rTitle,
				PunchLine=@rPunchLine,
				CRMLicenceNo=@rCRMLicenceNo,
				IsWindowSupport=@rIsWindowSupport
				
			  WHERE Id = @rId 
	    END
	      
	  
	  
	  
	  IF NOT EXISTS(SELECT 1 FROM sCommon.tCastCategoryMaster WHERE OrgGroupId = @rCode)
BEGIN				
				INSERT INTO sCommon.tCastCategoryMaster
					   ([Id]
					   ,[Number]
					   ,[Code]
					   ,[Title]
					   ,[IsObsolete]
					   ,[CreatedUserId]
					   ,[CreatedDateTime]
					   ,[UpdatedUserId]
					   ,[UpdatedDateTime]
					   ,[OrgGroupId]
					   , MainCastCategoryId 
					   ,OrderIndex)
				 SELECT
						 sCommon.fGetIntIdForOrg(Id,@rCode)
						,Id	
						,Code
						,Title
						,0
						,1
						,sCommon.fGetDate()
						,1
						,sCommon.fGetDate()
						,@rCode
						,Id
						,Id						
						FROM sCommon.tMainCastCategoryMaster
						 
						
	DECLARE @lMaxCatId int
	SET @lMaxCatId = sCommon.fGetIntIdForOrg(100,@rCode)					
	EXECUTE sCommon.pTableRowIdModify @rCode, @rTableTitle = 'sCommon.tCastCategoryMaster', @rCurrentNumber = @lMaxCatId


			
			
END
	   

IF NOT EXISTS(SELECT 1 FROM sSetup.tBatchGroupMaster WHERE OrgGroupId = @rCode)
BEGIN				
				INSERT INTO sSetup.tBatchGroupMaster
					   ([Id]
					   ,[Number]
					   ,[Code]
					   ,[Title]					  
					   ,[CreatedUserId]
					   ,[CreatedDateTime]
					   ,[UpdatedUserId]
					   ,[UpdatedDateTime]
					   ,[OrgGroupId]					   
					   ,OrderIndex)
				 SELECT
						 sCommon.fGetIntIdForOrg(1,@rCode)
						,1	
						,'Common'
						,'Common'					
						,1
						,sCommon.fGetDate()
						,1
						,sCommon.fGetDate()
						,@rCode						 
						,1						
						 
						 
END						
	 


			
			

	      
	      SELECT @rCode AS Result	
		COMMIT TRANSACTION
		
		--  exec  [sCommon].[pOrganizationSetupAdd] @rId
		
	 
		
END
GO
PRINT N'Altering [sStudent].[pRptStudentRegisterWithSUIDAndDemographicDetailGet]...';


GO


ALTER PROCEDURE [sStudent].[pRptStudentRegisterWithSUIDAndDemographicDetailGet]
	 
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 @rOrgId smallint,
	 @rBatchId int,
	 @rStrCode nvarchar(max),
	 @rClassId int,
	 @rDivisionId int,
	 @rStudentId bigint,
	 @rFromRollNo int,
	 @rToRollNo int,
	 @rStatusId int,
	 @rClassStatusId int,
	 @rDateOfBirth int,
	 @rDepartmentId int,
	 --@rFromAdmissionDate date='', 
  --   @rToAdmissionDate date='',
     @rFromStudentCode nvarchar(max)='',
     @rToStudentCode nvarchar(max)='',
	 @rFromNumber int = 0,
	 @rToNumber int = 0  
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON


BEGIN

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

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


	SELECT  
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			SD.AcademicId,
			SD.OrgId ,
			SD.StudentId, 
			SD.ClassId,
			SD.DivisionId,
			SD.ClassDivision,
			SD.Code,
			SD.RollNo,			
			SD.FirstName,
			SD.MiddleName,			
			SD.LastName,
			SD.Name,		
			SD.ClassName,
			SD.ClassId ,
			SD.DivisionId,
			SD.DivisionName,
			SD.StatusName,
			SD.StatusId,
			SD.LCProgress,
			SD.Religion,
			SD.FamilyCast,
			SD.FamilySubCast,
			SD.LCConduct,
			SD.BirthPlace,
			SD.BirthTaluka,
			SD.BirthDistrict,
			SD.LeftDate,
			SD.PreviousSchool,
			SD.DateOfBirth,
			SD.BirthDateInWord,
			SD.LeftReason,
			SD.AdmissionDate,
			SD.AdmissionStandard,
			SD.LeftStandard,
			SD.LCNumber,
			SD.LCDate,
			SD.StudentPhoto,
			SD.BloodGroup,
			SD.PresentAddress,
			SD.ContactNo,
			SD.Batch,
			SD.BatchId,
			SD.InactiveDate,
			OM.Title AS OrgName,
			SF.MotherName,
			SD.DivisionOrder,
			SD.Number AS StudentNumber,
			SF.FatherName,
			SD.Nationality,
			SD.MotherTongue,
			SD.BirthState,
			SD.BirthCountry,
			SD.SUId,
            SD.AdhaarNumber,
            SD.ClassStatusId,
            SD.ClassStatusName,
			SD.UIDNumber ,
			SD.Gender ,
			HM.Title As HouseName ,
			SO.ReferenceRemark as ReferenceRemark ,
			TM.Title as TribeTitle,
			ISNULL(STUFF((
			SELECT ', ' +  ISNULL(CTM.Title,'')
			FROM [sStudent].[tStudentCustomTag] CT 
			INNER JOIN [sStudent].[tCustomTagMaster] CTM ON CT.CustomTagId=CTM.Id 
			WHERE CT.StudentId = SD.StudentId
			FOR XML PATH('')
			), 1, 1, ''),'') AS CustomTags ,
			CCM.Title As CasteCategory ,
		    @lIDConfigValue AS ItemValue 
			
	FROM 
			sStudent.vStudentAllDetail SD
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=SD.OrgId
			LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId=SD.StudentId
			INNER JOIN sSetup.tBatchClass BC ON BC.ClassID =  SD.ClassID AND BC.BatchId = SD.BatchId AND SD.BatchId= @rBatchId
			--LEFT JOIN sStudent.tStudentAdmission SAM ON SD.StudentId=SAM.StudentId
			--AND ((SAM.AdmissionDate>=@rFromAdmissionDate)OR(ISNULL(@rFromAdmissionDate,'')=''))    
			--AND ((SAM.AdmissionDate<=@rToAdmissionDate)OR(ISNULL(@rToAdmissionDate,'')=''))  
			--AND	SAM.BatchId = @rBatchId 
			LEFT JOIN sActivity.tHouseMaster HM ON HM.ID = SD.HouseId
			LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId = SD.StudentId
			LEFT JOIN sCommon.tTribeMaster TM ON TM.ID = SO.TribeId
			LEFT JOIN sCommon.tCastCategoryMaster CCM ON CCM.Id = SD.CastCategoryId

			 
	WHERE 
			SD.OrgId=@rOrgId
		AND (ISNULL(SD.Code,0) IN( SELECT cast(item as nvarchar(20)) FROM  sCommon.fnsplit(@rStrCode,',')) OR @rStrCode='') 
		AND ((SD.ClassId=@rClassId) OR (@rClassId=0))
		AND ((SD.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		AND ((SD.StudentId=@rStudentId) OR (@rStudentId=0))
		AND ((SD.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
		AND ((SD.RollNo <= @rToRollNo) OR (@rToRollNo=0))
		AND ((SD.StatusId=@rStatusId)OR(@rStatusId=0))
		AND ((SD.ClassStatusId=@rClassStatusId) OR (@rClassStatusId=0))
		AND ((MONTH(SD.DateOfBirth)=@rDateOfBirth OR @rDateOfBirth=0))
	    AND ((SD.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
	    AND((SD.Code>=@rFromStudentCode) OR (ISNULL(@rFromStudentCode,'')=''))
	    AND((SD.Code<=@rToStudentCode) OR (ISNULL(@rToStudentCode,'')=''))
		AND((SD.Number>=@rFromNumber) OR (ISNULL(@rFromNumber,0)=0))
	    AND((SD.Number<=@rToNumber) OR (ISNULL(@rToNumber,0)=0))
END
GO
PRINT N'Altering [sStudent].[pStudentMasterAdd]...';


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

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

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

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

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

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


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

BEGIN 

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


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

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

	SELECT @lIsStudentCommonSearchBatchWise = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 508 AND SourceTypeId = 2010 AND SourceId = @rOrgId

	SELECT @lOrgGroupId = OGBM.OrgGroupId FROM sSetup.tBatchMaster BM INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id = BM.OrgGroupBatchId WHERE BM.Id=@rBatchId
	SELECT @lConfigValue = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 480 AND SourceTypeId = 2010 AND SourceId = @rOrgId
	
	IF (@lIsStudentCommonSearchBatchWise = 'True')
	BEGIN
		IF(@rRollNo IS NULL)  
		BEGIN  
			SELECT   
			  SA.AcademicId,  
			  SA.StudentId,  
			  SA.FirstName,  
			  SA.LastName,  
			  SA.MiddleName,  
			  SA.Name,  
			  SA.Code,  
			  SA.ClassId,  
			  SA.ClassName,  
			  SA.DivisionId,  
			  SA.DivisionName,  
			  SA.Number,  
			  SA.RollNo,  
			  SA.StatusId,  
			  SA.StatusName,  
			  SA.OrgId,  
			  ISNULL(SA.AdmissionCategoryId,0) AS AdmissionCategoryId,  
			  SA.BatchId,  
			  SA.SUId,  
			  ISNULL(So.GenderId,0) AS GenderId  
			 FROM   
			         sStudent.vStudentAcademic SA  
			          LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId=SA.StudentId  
			 WHERE   
			  
			 ((SA.ClassId=@rClassId)OR(@rClassId=0))  
			 AND((SA.DivisionId=@rDivisionId)OR(@rDivisionId=0))  
			 AND((SA.Code=@rCode) OR (ISNULL(@rCode,'') = ''))   
			 AND((SA.FirstName like @rFirstName) OR (ISNULL(@rFirstName,'') = ''))   
			 AND((SA.LastName like @rLastName) OR (ISNULL(@rLastName,'') = ''))   
			 AND((SA.StatusId=@rStatusId)OR(@rStatusId=0))   
			 AND(SA.OrgId=@rOrgId OR @rOrgId = 0)  
			 AND ( OrgGroupBatchId = @rOrgGroupBatchId or @rOrgGroupBatchId = 0)   
			 AND(SA.BatchId=@rBatchId or @rBatchId = 0)  
			 AND((SA.SUId=@rSUId) OR (ISNULL(@rSUId,'') = ''))  
			 
			ORDER BY SA.ClassId,SA.DivisionId,SA.RollNo  
		END  
		ELSE  
		BEGIN  
			SELECT   
			  SA.AcademicId,  
			  SA.StudentId,  
			  SA.FirstName,  
			  SA.LastName,  
			  SA.MiddleName,  
			  SA.Name,  
			  SA.Code,  
			  SA.ClassId,  
			  SA.ClassName,  
			  SA.DivisionId,  
			  SA.DivisionName,  
			  SA.Number,  
			  SA.RollNo,  
			  SA.StatusId,  
			  SA.StatusName,  
			  SA.OrgId,
			  ISNULL(SA.AdmissionCategoryId,0) AS AdmissionCategoryId ,  
			  SA.SUId,  
			  ISNULL(So.GenderId,0) AS GenderId  
			 FROM   
			         sStudent.vStudentAcademic SA      
			          LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId=SA.StudentId           
			 WHERE   
			  
			 ((SA.ClassId=@rClassId)OR(@rClassId=0))  
			 AND((SA.DivisionId=@rDivisionId)OR(@rDivisionId=0))  
			 AND((SA.Code=@rCode) OR (ISNULL(@rCode,'') = ''))   
			 AND((SA.FirstName like @rFirstName) OR (ISNULL(@rFirstName,'') = ''))   
			 AND((SA.LastName like @rLastName) OR (ISNULL(@rLastName,'') = ''))   
			 AND(SA.RollNo=@rRollNo)  
			 AND((SA.StatusId=@rStatusId)OR(@rStatusId=0))   
			 AND((SA.OrgId=@rOrgId) OR (@rOrgId=0))  
			 AND ( OrgGroupBatchId = @rOrgGroupBatchId or @rOrgGroupBatchId = 0)   
			 AND(SA.BatchId=@rBatchId or @rBatchId = 0) 
			 AND((SA.SUId=@rSUId) OR (ISNULL(@rSUId,'') = ''))    
			 
			ORDER BY SA.ClassId,SA.DivisionId,SA.RollNo  
		END  
	END

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

		IF(@rRollNo IS NULL)
		BEGIN
			SELECT 
				SA.AcademicId,
				SA.StudentId,
				SA.FirstName,
				SA.LastName,
				SA.MiddleName,
				SA.Name,
				SA.Code,
				SA.ClassId,
				SA.ClassName,
				SA.DivisionId,
				SA.DivisionName,
				SA.Number,
				SA.RollNo,
				SA.StatusId,
				SA.StatusName,
				SA.OrgId,
				ISNULL(SA.AdmissionCategoryId,0) AS AdmissionCategoryId,
				SA.BatchId,
				SA.SUId,
				ISNULL(So.GenderId,0) AS GenderId,
				ISNULL(SC.ParentContactNo,'') AS ParentContactNo
		
			FROM 
	            sStudent.vStudentAcademic SA
	            LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId=SA.StudentId
	            INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId AND SA.OrgGroupBatchId = BM.OrgGroupBatchId
				LEFT JOIN sStudent.tStudentCommunication SC ON SA.StudentId = SC.StudentId
			WHERE 
				((SA.ClassId=@rClassId)OR(@rClassId=0))
				AND((SA.DivisionId=@rDivisionId)OR(@rDivisionId=0))
				AND((SA.Code=@rCode) OR (ISNULL(@rCode,'') = '')) 
				AND((SA.FirstName like @rFirstName) OR (ISNULL(@rFirstName,'') = '')) 
				AND((SA.LastName like @rLastName) OR (ISNULL(@rLastName,'') = '')) 
				AND((SA.StatusId=@rStatusId)OR(@rStatusId=0))	
				AND(SA.OrgId=@rOrgId OR @rOrgId = 0)
				AND (SA.OrgGroupBatchId = @rOrgGroupBatchId	or @rOrgGroupBatchId = 0)	
				AND(SA.BatchId=@rBatchId or @rBatchId = 0)
				AND((SA.SUId=@rSUId) OR (ISNULL(@rSUId,'') = ''))
				AND BM.IsInContext = @lIsInContext
	
			ORDER BY SA.ClassId,SA.DivisionId,SA.RollNo
		END

		ELSE
		BEGIN
			SELECT 
					SA.AcademicId,
					SA.StudentId,
					SA.FirstName,
					SA.LastName,
					SA.MiddleName,
					SA.Name,
					SA.Code,
					SA.ClassId,
					SA.ClassName,
					SA.DivisionId,
					SA.DivisionName,
					SA.Number,
					SA.RollNo,
					SA.StatusId,
					SA.StatusName,
					SA.OrgId,
					--SA.Age,
					ISNULL(SA.AdmissionCategoryId,0) AS AdmissionCategoryId ,
					SA.SUId,
					ISNULL(So.GenderId,0) AS GenderId
					
			FROM 
		            sStudent.vStudentAcademic SA    
		            LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId=SA.StudentId       
		            INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId AND SA.OrgGroupBatchId = BM.OrgGroupBatchId  
			WHERE 
					((SA.ClassId=@rClassId)OR(@rClassId=0))
					AND((SA.DivisionId=@rDivisionId)OR(@rDivisionId=0))
					AND((SA.Code=@rCode) OR (ISNULL(@rCode,'') = '')) 
					AND((SA.FirstName like @rFirstName) OR (ISNULL(@rFirstName,'') = '')) 
					AND((SA.LastName like @rLastName) OR (ISNULL(@rLastName,'') = '')) 
					AND(SA.RollNo=@rRollNo)
					AND((SA.StatusId=@rStatusId)OR(@rStatusId=0))	
					AND((SA.OrgId=@rOrgId) OR (@rOrgId=0))
					AND (SA.OrgGroupBatchId = @rOrgGroupBatchId	or @rOrgGroupBatchId = 0)	
					AND(SA.BatchId=@rBatchId or @rBatchId = 0)
					AND((SA.SUId=@rSUId) OR (ISNULL(@rSUId,'') = '')) 
					AND BM.IsInContext = @lIsInContext
			ORDER BY SA.ClassId,SA.DivisionId,SA.RollNo
		END
	END
END
GO
PRINT N'Altering [sTimetable].[pRptDivisionWorkLoadGet]...';


GO



ALTER PROCEDURE [sTimetable].[pRptDivisionWorkLoadGet]
	  
	 
	 @rDivisionId int,
	 @rClassId int=0,
	 @rTimeTableSchemaId int,
	 @rEmployeeId bigint ,
	 @rOrgId  smallint
	 --@rSubjectId int = 0

	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 

	 
   Select  
		CS.SubjectId AS SubjectId,
		Sub.Title AS SubjectTitle,
		
		ISNULL(DWL.NoOfLecture,0) AS DivisionWiseLecture,
		DM.Id AS DivisionId,
		ISNULL(CM.DisplayTitle,'')+'-'+ISNULL(DM.Title,'') as ClassDivisionName,	
		ISNULL(SUM(TWL.NoOfLecture),0) TeacherwiseLeacture,
		 --VEM.FirstName + ' ' + VEM.LastName AS  EmployeeTitle,
		DM.ClassId AS ClassId,
	 --ISNULL(VEM.Id,0) AS EmployeeId,
		CM.OrderIndex AS ClassOrderIndex,
		DM.OrderIndex AS DivisionOrderIndex
		
		
		FROM  sSetup.tClassMaster CM
		INNER JOIN sSetup.tDivisionMaster DM ON DM.ClassId = CM.Id AND DM.OrgId=@rOrgId And DM.IsObsolete = 0
		INNER JOIN sSetup.tClassSubject CS ON CS.ClassId = DM.ClassId  
		INNER JOIN sSetup.tSubjectMaster Sub  ON Sub.Id = CS.SubjectId 
		LEFT JOIN sTimetable.tDivisionWorkLoad DWL ON DWL.DivisionId = DM.Id AND DWL.SUBJECTID = CS.SUBJECTID AND DWL.TimeTableSchemaId = @rTimeTableSchemaId 
		LEFT JOIN  sTimetable.tTeacherWorkLoad TWL ON TWL.SUBJECTID= DWL.SUBJECTID AND TWL.DivisionId = DWL.DivisionId AND TWL.TimeTableSchemaId = @rTimeTableSchemaId 
		--LEFT JOIN sHrm.vExtEmployeeMaster VEM  ON VEM.Id=TWL.EmployeeId 
      WHERE 
			((DM.ClassId =@rClassId) OR (@rClassId=0))
		AND ((DM.Id = @rDivisionId) OR (@rDivisionId=0))
      AND ((TWL.EmployeeId=@rEmployeeId) or (@rEmployeeId=0))
      	
     
      GROUP BY 
		CS.SubjectId,
		DWL.NoOfLecture,
		Sub.Title
		,DM.Id,CS.OrderIndex,CM.DisplayTitle,DM.Title,
		 --VEM.FirstName,
		 --VEM.LastName,
		DM.ClassId,
		 --VEM.Id,
		CM.OrderIndex,DM.OrderIndex 
	--order by cs.orderindex
	
      
        
	
		
END
GO
PRINT N'Altering [sTool].[pUpgradeVersion]...';


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

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

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


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

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



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

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

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

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

-- update tablerowid master data from excel to table

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

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

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



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




exec [sTool].[pTableRowIdCurrentNumberSet] @rOrgGroupId

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


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

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


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


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

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

--static entry in tVisitorTypeMaster

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

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

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

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

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

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

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

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


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

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

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


			
			
END


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

END


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

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

END

UPDATE sSystem.tDatabaseInfo SET ApplicationId = 1

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

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

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

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

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

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

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

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

END
GO
PRINT N'Altering [sTransport].[pRptRoutewiseStudentListGet]...';


GO

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

		UNION ALL 

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


GO
CREATE PROCEDURE [sAdmission].[pRptAdmissionBlankFormFieldGet]

	@rClassId int = 0
	
AS
SET NOCOUNT ON

BEGIN 
	SELECT DISTINCT
		ACF.ClassId,
		ACF.FieldGroup,
		ACF.FieldRemark
	FROM  
		sAdmission.tAdmissionCriteriaForm ACF
	WHERE 	
		ACF.ClassId = @rClassId
END
GO
PRINT N'Creating [sAdmission].[pRptAdmissionBlankFormGet]...';


GO
CREATE PROCEDURE [sAdmission].[pRptAdmissionBlankFormGet]
	@rClassId int = 0,
	@rBatchId int = 0

AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;

   select 
	 ISNULL(AC.ClassId,0) AS ClassId,
	 ISNULL(AC.IsFixParentAcademic,0) AS IsParentAcademicRequired ,
	 ISNULL (AC.IsStudentAcademicRequired,0) AS IsStudentAcademicRequired ,
	 ISNULL(AC.IsSiblingDetailRequired,0) AS IsSiblingDetailRequired,
	 ISNULL(AC.IsReferenceDetailRequired,0) AS IsReferenceDetailRequired ,
	 ISNULL(AC.IsFamilyDetailRequired,0) AS IsFamilyDetailRequired ,
	 ISNULL(AC.IsFixStudentAcademic,0) AS IsFixStudentAcademic,
	 ISNULL(AC.ConfirmationRemark,'') AS ConfirmationRemark,
	 ISNULL(AC.IsHostelDetailRequired,0) AS IsHostelDetailRequired ,
	 ISNULL (AC.IsTransportDetailRequired,0) AS IsTransportDetailRequired ,
	 ISNULL(AC.IsHealthDetailRequired,0) AS IsHealthDetailRequired,
	 ISNULL(AC.IsBirthPlaceDetailRequired,0) AS IsBirthPlaceDetailRequired ,
	 ISNULL(AC.IsAadhaarDetailRequired,0) AS IsAadhaarDetailRequired ,
	 ISNULL(AC.IsBloodGroupDetailRequired,0) AS IsBloodGroupDetailRequired,
	 ISNULL(AC.CustomField1Remark,'') AS CustomField1Remark,
	 ISNULL(AC.CustomField2Remark,'') AS CustomField2Remark,
	 ISNULL(AC.CustomField3Remark,'') AS CustomField3Remark,
	 ISNULL(AC.AgeCutOffDate,'') AS AgeCutOffDate,
	 ISNULL(AC.Remark1,'') AS ExtraRemark1,
	 ISNULL(AC.Remark2,'') AS ExtraRemark2,
	 ISNULL(AC.Remark3,'') AS ExtraRemark3,
	 ISNULL(AC.IsFatherDetail,0) AS IsFatherDetail,
	 ISNULL(AC.IsFatherFullDetail,0) AS IsFatherFullDetail,
	 ISNULL (AC.IsFatherAcademic,0) As IsFatherAcademic,
	 ISNULL (AC.IsMotherDetail,0) As IsMotherDetail,
	 ISNULL (AC.IsMotherFullDetail,0)As IsMotherFullDetail,
	 ISNULL (AC.IsMotherAcademic,0)As IsMotherAcademic,
	 ISNULL (AC.IsGuardianDetail,0)As IsGuardianDetail,
	 ISNULL (AC.IsGuardianFullDetail,0)As IsGuardianFullDetail,
	 ISNULL (AC.IsGuardianAcademic,0)As IsGuardianAcademic,
	 ISNULL (AC.IsOtherInformationRequired,0)As IsOtherInformationRequired,
	 ISNULL (AC.IsHealthDetailRequired,0) As IsHealthDetailRequired,
	 ISNULL (AC.IsCustomField1Required,0) As IsCustomField1Required,
	 ISNULL (AC.IsCustomField2Required,0) As IsCustomField2Required,
	 ISNULL (AC.IsCustomField3Required,0) As IsCustomField3Required,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](302,OM.Id) AS IsBirthPlace,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](303,OM.Id) AS IsBirthTaluka,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](304,OM.Id) AS IsBirthDistrict,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](305,OM.Id) AS IsBirthState,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](306,OM.Id) AS IsBirthCountry,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](307,OM.Id) AS IsPreviousSchool,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](308,OM.Id) AS IsStudentPhoto,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](316,OM.Id) AS IsContactEmail,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](317,OM.Id) AS IsReligion,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](318,OM.Id) AS IsFamilyCaste,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](319,OM.Id) AS IsNationality,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](320,OM.Id) AS IsCasteCategory,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](388,OM.Id) AS IsFamilySubCaste,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](321,OM.Id) AS IsMotherTongue,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](322,OM.Id) AS IsAadhaarNo,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](323,OM.Id) AS IsOtherInformation,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](324,OM.Id) AS IsLiveWith,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](325,OM.Id) AS IsHotelRequired,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](326,OM.Id) AS IsTransportRequired,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](327,OM.Id) AS IsMotherFullName,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](328,OM.Id) AS IsMotherMobilNo,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](329,OM.Id) AS IsMotherQualification,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](330,OM.Id) AS IsMotherOccupation,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](331,OM.Id) AS IsMotherEmail,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](332,OM.Id) AS IsMotherIncome,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](333,OM.Id) AS IsMotherOrganization,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](334,OM.Id) AS IsMotherDesignation,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](337,OM.Id) AS IsMotherOfficeAddress,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](338,OM.Id) AS IsMotherPhoto,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](410,OM.Id) AS IsMotherAadhaarNo,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](349,OM.Id) AS IsFatherFullName,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](350,OM.Id) AS IsFatherMobileNo,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](351,OM.Id) AS IsFatherQualification,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](352,OM.Id) AS IsFatherOccupation,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](353,OM.Id) AS IsFatherEmail,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](354,OM.Id) AS IsFatherIncome,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](355,OM.Id) AS IsFatherOrganization,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](356,OM.Id) AS IsFatherDesignation,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](359,OM.Id) AS IsFatherOfficeAddress,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](360,OM.Id) AS IsFatherPhoto,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](409,OM.Id) AS IsFatherAadhaarNo,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](361,OM.Id) AS IsGuardianFullName,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](362,OM.Id) AS IsGuardianMobileNo,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](363,OM.Id) AS IsGuardianPhoto,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](396,OM.Id) AS IsGuardianQualification,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](397,OM.Id) AS IsGuardianOccupation,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](398,OM.Id) AS IsGuardianEmail,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](399,OM.Id) AS IsGuardianIncome,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](400,OM.Id) AS IsGuardianOrganization,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](401,OM.Id) AS IsGuardianDesignation,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](403,OM.Id) AS IsGuardianRelationship,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](405,OM.Id) AS IsGuardianOfficeAddress,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](411,OM.Id) AS IsGuardianAadhaarNo,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](369,OM.Id) AS IsPhysicalDeformity,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](370,OM.Id) AS IsPhysicalDeformityRemark,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](371,OM.Id) AS IsMajorIllness,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](372,OM.Id) AS IsMajorIllnessRemark,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](373,OM.Id) AS IsAllergy,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](374,OM.Id) AS IsAllergyRemark,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](407,OM.Id) AS IsMeritMarks,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](408,OM.Id) AS IsMeritGrade,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](395,OM.Id) AS IsBloodGroup,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](309,OM.Id) AS IsStreetOneAddress

	FROM  
		    sAdmission.tAdmissionCriteria AC 
		    INNER JOIN sSetup.tClassMaster CM ON CM.Id=AC.ClassId
			INNER JOIN sSetup.tBatchMaster BM  ON  BM.Id=AC.BatchId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=BM.OrgId
	WHERE 	
	((AC.ClassId = @rClassId) OR (@rClassId = 0))	
	AND ((AC.BatchId = @rBatchId) OR (@rBatchId = 0))
END
GO
PRINT N'Creating [sAdmission].[pRptAdmissionSummaryGet]...';


GO


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

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


GO

CREATE PROCEDURE [sAssessment].[pMarkEntryRankUpdateRankNotApplyToSiddhi]
	 
	 @rExamId int=0,
	 @rDivisionId int=0,
	 @rBatchId int=0
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	
BEGIN 	
--for Siddhi Rank not Apply
-- ROW_NUMBER() OVER (ORDER BY TotalObtain) AS "Row Number"    -- Row number
-- RANK() OVER (ORDER BY TotalObtain) AS Rank                  -- skip next number
-- DENSE_RANK() OVER (ORDER BY TotalObtain) AS "Dense Rank"    -- continue next number 
-- NTILE(4) OVER (ORDER BY TotalObtain) AS Quartile            -- make number of rank group    

DECLARE  @lOrgId smallint,@lSiddhiKrupaApplicable bit, @lIsSkipRankConfigValue bit=0 

SELECT @lOrgId = OM.Id From sSetup.tBatchMaster BM INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = BM.OrgId Where BM.Id = @rBatchId
	 
SELECT @lSiddhiKrupaApplicable = ISNULL(IsApplySiddhiKrupa,0) From sAssessment.tExamMaster Where Id = @rExamId

-- Configuration Value
-- Config Assessment.IsSkipRank						     
SELECT @lIsSkipRankConfigValue = ISNULL(CS.ItemValue,CM.ItemValue) From sConfig.tConfigurationMaster CM LEFT JOIN sConfig.tConfigurationSetup CS ON CM.Id = CS.ConfigurationId	AND SourceId = @lOrgId WHERE CS.ConfigurationId = 315 AND SourceTypeId = 1016							     					     



UPDATE R Set R.RankNumber = 0 From sAssessment.tResult R Inner Join sStudent.tAcademic A ON A.Id = R.AcademicId AND R.ExamId=@rExamId AND A.DivisionId = @rDivisionId AND A.BatchId = @rBatchId

IF @lSiddhiKrupaApplicable = 0
BEGIN
	IF(@lIsSkipRankConfigValue=0)
    BEGIN
		Update R Set R.RankNumber=A.RankNumber From sAssessment.tResult R
		INNER JOIN
		(Select DENSE_RANK() OVER ( ORDER BY Percentage Desc) AS RankNumber,
		AcademicId 
		from sAssessment.tResult RS
		INNER JOIN sStudent.tAcademic SA ON SA.Id= RS.AcademicId 
		AND ExamId=@rExamId AND SA.DivisionId=@rDivisionId  AND SA.BatchId = @rBatchId
		AND ResultStatus='PASS' ) A
		ON A.AcademicId = R.AcademicId 
		WHERE R.ExamId = @rExamId
    END
    ELSE
    BEGIN
	    Update R Set R.RankNumber=A.RankNumber From sAssessment.tResult R
		INNER JOIN
		(Select RANK() OVER ( ORDER BY Percentage Desc) AS RankNumber,
		AcademicId 
		from sAssessment.tResult RS
		INNER JOIN sStudent.tAcademic SA ON SA.Id= RS.AcademicId 
		AND ExamId=@rExamId AND SA.DivisionId=@rDivisionId  AND SA.BatchId = @rBatchId
		AND ResultStatus='PASS' ) A
		ON A.AcademicId = R.AcademicId 
		WHERE R.ExamId = @rExamId
	END
END
ELSE
BEGIN

	
	DECLARE @lIsShowSiddhiKrupaExamField bit, @lIsSetSiddhiAppliedStudentRank0 bit, @lIsMoveSiddhiRankToLast bit,@lMaxRank int
		
	-- Config Assessment.IsShowSiddhiKrupaExamField
	SELECT @lIsShowSiddhiKrupaExamField = ISNULL(CS.ItemValue,CM.ItemValue) From sConfig.tConfigurationSetup CS LEFT JOIN sConfig.tConfigurationMaster CM ON CM.Id = CS.ConfigurationId	WHERE CS.ConfigurationId = 278 AND SourceId = @lOrgId AND SourceTypeId = 1016

	-- Config Assessment.IsSetSiddhiAppliedStudentRank0
	SELECT @lIsSetSiddhiAppliedStudentRank0 = ISNULL(CS.ItemValue,CM.ItemValue) From sConfig.tConfigurationMaster CM LEFT JOIN sConfig.tConfigurationSetup CS ON CM.Id = CS.ConfigurationId	AND SourceId = @lOrgId WHERE CS.ConfigurationId = 280 AND SourceTypeId = 1016

	-- Config Assessment.IsMoveSiddhiRankToLast
	SELECT @lIsMoveSiddhiRankToLast = ISNULL(CS.ItemValue,CM.ItemValue) From sConfig.tConfigurationMaster CM LEFT JOIN sConfig.tConfigurationSetup CS ON CM.Id = CS.ConfigurationId	AND SourceId = @lOrgId	WHERE CS.ConfigurationId = 281 AND SourceTypeId = 1016	

	-- Create temp table for get ResultDetail(GraceMark,KrupaMark)
	CREATE TABLE #TempResultDetail (ResultId bigint,AcademicId bigint,GraceMark Decimal(5,2),KrupaMark Decimal(5,2))
	INSERT INTO #TempResultDetail
	SELECT DISTINCT RD.ResultId,SA.Id AS AcademicId,RD.GraceMark,RD.KrupaMark
	FROM sAssessment.tResult RS INNER JOIN sStudent.tAcademic SA ON SA.Id= RS.AcademicId INNER JOIN sAssessment.tResultDetail RD ON RD.ResultId = RS.Id
	WHERE RS.ExamId=@rExamId AND SA.DivisionId=@rDivisionId  AND SA.BatchId = @rBatchId

	IF(@lIsSkipRankConfigValue=0)
	BEGIN
		Update R Set R.RankNumber=A.RankNumber From sAssessment.tResult R
		INNER JOIN
		(Select DENSE_RANK() OVER ( ORDER BY Percentage Desc) AS RankNumber,
		AcademicId 
		from sAssessment.tResult RS
		INNER JOIN sStudent.tAcademic SA ON SA.Id= RS.AcademicId 
		AND ExamId=@rExamId AND SA.DivisionId=@rDivisionId  AND SA.BatchId = @rBatchId
		AND ResultStatus='PASS' 
		AND RS.Id NOT IN (Select ResultId from #TempResultDetail Where GraceMark > 0)
		) A
		ON A.AcademicId = R.AcademicId 
		WHERE R.ExamId = @rExamId
		AND R.Id NOT IN (Select ResultId from #TempResultDetail Where GraceMark > 0)
	END
	ELSE
	BEGIN
	   Update R Set R.RankNumber=A.RankNumber From sAssessment.tResult R
		INNER JOIN
		(Select RANK() OVER ( ORDER BY Percentage Desc) AS RankNumber,
		AcademicId 
		from sAssessment.tResult RS	
		INNER JOIN sStudent.tAcademic SA ON SA.Id= RS.AcademicId 
		AND ExamId=@rExamId AND SA.DivisionId=@rDivisionId  AND SA.BatchId = @rBatchId
		AND ResultStatus='PASS'
		AND RS.Id NOT IN (Select ResultId from #TempResultDetail Where GraceMark > 0)
		 ) A
		ON A.AcademicId = R.AcademicId 
		WHERE R.ExamId = @rExamId
		AND R.Id NOT IN (Select ResultId from #TempResultDetail Where GraceMark > 0)
	END

If @lIsShowSiddhiKrupaExamField = 1 AND @lSiddhiKrupaApplicable = 1
BEGIN

-- Set Rank 0 to Those whose Siddhi/GraceMark > 0
IF @lIsSetSiddhiAppliedStudentRank0 = 1 
	BEGIN
		Update R Set R.RankNumber = 0 From sAssessment.tResult R 
		Inner Join sStudent.tAcademic A ON A.Id = R.AcademicId  
		AND R.ExamId=@rExamId
		AND A.DivisionId = @rDivisionId 
		AND A.BatchId = @rBatchId
		
		IF(@lIsSkipRankConfigValue=0)
		BEGIN		
			Update R Set R.RankNumber=A.RankNumber 
			From sAssessment.tResult R
			INNER JOIN
			(Select DENSE_RANK() OVER ( ORDER BY Percentage Desc) AS RankNumber, AcademicId 
			from sAssessment.tResult RS
			INNER JOIN sStudent.tAcademic SA ON SA.Id= RS.AcademicId 
			INNER JOIN sAssessment.tResultDetail RD ON RD.ResultId = RS.Id
			AND RS.ExamId=@rExamId AND SA.DivisionId=@rDivisionId  AND SA.BatchId = @rBatchId
			AND ResultStatus in ('PASS','PROMOTED')
			AND RS.Id NOT IN (Select ResultId from #TempResultDetail Where GraceMark > 0 OR KrupaMark > 0)
			) A
			ON A.AcademicId = R.AcademicId 
			WHERE R.ExamId = @rExamId
			AND R.Id NOT IN (Select ResultId from #TempResultDetail Where GraceMark > 0 OR KrupaMark > 0)
		END
		ELSE
		BEGIN
			Update R Set R.RankNumber=A.RankNumber 
			From sAssessment.tResult R
			INNER JOIN
			(Select RANK() OVER ( ORDER BY Percentage Desc) AS RankNumber, AcademicId 
			from sAssessment.tResult RS
			INNER JOIN sStudent.tAcademic SA ON SA.Id= RS.AcademicId 
			INNER JOIN sAssessment.tResultDetail RD ON RD.ResultId = RS.Id
			AND RS.ExamId=@rExamId AND SA.DivisionId=@rDivisionId  AND SA.BatchId = @rBatchId
			AND ResultStatus in ('PASS','PROMOTED')
			AND RS.Id NOT IN (Select ResultId from #TempResultDetail Where GraceMark > 0 OR KrupaMark > 0)
			) A
			ON A.AcademicId = R.AcademicId 
			WHERE R.ExamId = @rExamId
			AND R.Id NOT IN (Select ResultId from #TempResultDetail Where GraceMark > 0 OR KrupaMark > 0)
		END
	END
ELSE IF @lIsMoveSiddhiRankToLast = 1
	BEGIN
			SELECT @lMaxRank = Max(RankNumber) 
			FROM sAssessment.tResult R 
			INNER JOIN sStudent.tAcademic SA ON SA.Id= R.AcademicId 
			INNER JOIN sAssessment.tExamMaster EM ON EM.Id = R.ExamId
			INNER JOIN sSetup.tDivisionMaster DM ON DM.ClassId = EM.ClassId and DM.Id = SA.DivisionId
			WHERE EM.Id = @rExamId  AND DM.Id = @rDivisionId AND EM.BatchId= @rBatchId AND R.Percentage > 0
 

			IF(@lIsSkipRankConfigValue=0)
			BEGIN				
				Update R Set R.RankNumber= convert(int,@lMaxRank) + convert(int,A.RankNumber) From sAssessment.tResult R
				INNER JOIN
				(Select DENSE_RANK() OVER ( ORDER BY Percentage Desc) AS RankNumber, AcademicId 
				from sAssessment.tResult RS
				INNER JOIN sStudent.tAcademic SA ON SA.Id= RS.AcademicId 
				AND ExamId=@rExamId AND SA.DivisionId=@rDivisionId  AND SA.BatchId = @rBatchId
				AND RS.Id IN (Select ResultId from #TempResultDetail Where GraceMark > 0 AND KrupaMark <= 0 )
				AND ResultStatus in ('PASS','PROMOTED')) A
				ON A.AcademicId = R.AcademicId 
				WHERE R.ExamId = @rExamId
				AND R.Id IN (Select ResultId from #TempResultDetail Where GraceMark > 0 AND KrupaMark <= 0 )
			END
			ELSE
			BEGIN
				Update R Set R.RankNumber=convert(int,@lMaxRank) + convert(int,A.RankNumber) From sAssessment.tResult R
				INNER JOIN
				(Select RANK() OVER ( ORDER BY Percentage Desc) AS RankNumber, AcademicId 
				from sAssessment.tResult RS
				INNER JOIN sStudent.tAcademic SA ON SA.Id= RS.AcademicId 
				AND ExamId=@rExamId AND SA.DivisionId=@rDivisionId  AND SA.BatchId = @rBatchId
				AND RS.Id IN (Select ResultId from #TempResultDetail Where GraceMark > 0 AND KrupaMark <= 0)
				AND ResultStatus in ('PASS','PROMOTED')) A
				ON A.AcademicId = R.AcademicId 
				WHERE R.ExamId = @rExamId 
				AND R.Id IN (Select ResultId from #TempResultDetail Where GraceMark > 0 AND KrupaMark <= 0)	       	       	       
			END
			END		
END

	DROP TABLE #TempResultDetail

END 

	SELECT 1 AS Result
END
GO
PRINT N'Creating [sAssetManagement].[AssetMasterCodeItemGet]...';


GO

CREATE PROCEDURE [sAssetManagement].[AssetMasterCodeItemGet]
    @rOrgId int,
	@rId [int] = 0,
	@rCode [nvarchar](10),  
	@rTitle [nvarchar](100),  
	@rIsObsolete [bit] = 0,
	@rIsWildCardSearch [bit] = 1,
	@rStoreLocationId int = 0
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
IF @rIsObsolete = 0
	BEGIN
		IF @rIsWildCardSearch = 1
			BEGIN
				SET @rCode = sCommon.fSearchStringGet(@rCode)
				SET @rTitle = sCommon.fSearchStringGet(@rTitle)
			END
	END
	
	SELECT 	 Id AS AssetId,
			 Code AS Code,
			 Title AS AssetName,
			 OrgId,
			 StoreLocationId,
			 AssetCode AS AssetCode
			 
	   FROM	 
		sAssetManagement.tAssetMaster 
	 WHERE
		((Id=@rId) OR (@rId=0))
	  AND ((OrgId=@rOrgId) OR (@rOrgId=0))
	  AND ((StoreLocationId=@rStoreLocationId) OR (@rStoreLocationId=0))
	  AND ((AssetCode LIKE @rCode) OR (ISNULL(@rCode, '') = ''))
	  AND (((Title LIKE @rTitle) AND @rIsObsolete = 0) OR (@rTitle = '' AND @rIsObsolete = 0) OR ((Title = @rTitle ) AND @rIsObsolete = 1))
	 --((SIM.Id = @rId) OR (@rId = 0)) 
		--AND	((SIM.Code LIKE @rCode) OR (ISNULL(@rCode, '') = ''))
		--AND	(((SIM.Title LIKE @rTitle) AND @rIsAbsoluteTitle = 0) OR (@rTitle = '' AND @rIsAbsoluteTitle = 0) OR ((SIM.Title = @rTitle ) AND @rIsAbsoluteTitle = 1))
		--AND SIM.OrgId = @rOrgId
		--AND ((SIM.LocationId = @rLocationId) OR (@rLocationId = 0)) 
		
END
GO
PRINT N'Creating [sEExam].[pDsTestParticipantQuestionAdd]...';


GO
CREATE PROCEDURE [sEExam].[pDsTestParticipantQuestionAdd]
	 
	@rTestId bigint,
	@rTestParticipantId bigint
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	BEGIN TRANSACTION	
		IF NOT EXISTS(SELECT 1 FROM sEExam.tTestParticipantAnswer WHERE TestId = @rTestId AND TestParticipantId = @rTestParticipantId)
		BEGIN
			INSERT INTO sEExam.tTestParticipantAnswer
			(
				TestId,
				QuestionId,
				QuestionOptionId,
				ScoredMark,
				AnswerStatusId,
				OrderIndex,
				TestParticipantId,
				QuestionAnswer
			)
			SELECT 
				TestId, 
				QuestionId, 
				0,
				0,
				532,
				0,
				@rTestParticipantId,
				0
			FROM
				sEExam.tTestQuestion 
			WHERE 
				TestId = @rTestId
		END
		SELECT 1 AS Result
		COMMIT TRANSACTION		
	END TRY
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
END
GO



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

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

CREATE 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
	
	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
		) AS CG
		GROUP BY CollectionGroupId,StartDate,EndDate,CollectionGroupName,OrderIndex,ReceiptId
	) AS PendingFee
	ORDER BY PendingFee.StartDate,PendingFee.OrderIndex
		
	RETURN  
END


GO

/*
Deployment script for NetVidyalayaVersionBlank
*/

GO
SET ANSI_NULLS, ANSI_PADDING, ANSI_WARNINGS, ARITHABORT, CONCAT_NULL_YIELDS_NULL, QUOTED_IDENTIFIER ON;

SET NUMERIC_ROUNDABORT OFF;


GO

GO
PRINT N'Altering [sAcademic].[pClassworkGet]...';


GO
ALTER PROCEDURE [sAcademic].[pClassworkGet]

	 @rId bigint=0,	 
	 @rSubjectId int=0,
	 @rClassId int=0,
	 @rEmployeeId bigint=0,
	 @rDivisionid int=0,
	 @rFromDate datetime='',
     @rToDate datetime='',
     @rOrgId int=0,
     --@rBatchId int
     @rOrgGroupBatchId int=0,
    @rUserId bigint =0
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
	IF(@rEmployeeId = -1)
	BEGIN
		SET @rEmployeeId = 0
	END

	if(@rId = 0)
		BEGIN
			SELECT 
			AC.Id,
			AC.EmployeeId,
			AC.ClassId,
			AC.DivisionId,
			AC.SubjectId,
			AC.ClassWorkDate,
			AC.Classwork,
			AC.Homework,
			ISNULL(ClassworkStatusId,1) AS ClassworkStatusId,
			ISNULL(HomeWorkStatusId,1) AS HomeWorkStatusId,
			--AC.HomeWorkEndDate,
			ISNULL(AC.HomeWorkEndDate,'') AS HomeWorkEndDate,
			AC.CreatedDateTime,
			AC.BatchId,
			BM.Title AS Batch,
		    ISNULL(vTSD.SubjectName,'') as SubjectName,
		    ISNULL(EM.FirstName + ' ' + EM.LastName,'') AS TeacherName,
		    ISNULL(vTSD.ClassTitle,'') AS ClassName,
		    ISNULL(vTSD.DivisionTitle,'') AS DivisionName,
		    BM.OrgId,
		    OM.DisplayTitle AS Organization,
		    REPLACE(CONVERT(VARCHAR(20), AC.ClassWorkDate, 103),'/','') +'_'+ CONVERT(nvarchar(10),AC.DivisionId) +'_'+CONVERT(nvarchar(10),AC.SubjectId) AS UniqueId,
			ISNULL(AC.IsSubmitHomework,0) AS IsSubmitHomework,
			AC.Id AS ClassworkId
	FROM 
			sAcademic.tClasswork AC
			INNER JOIN sAcademic.vTeacherSubjectDivision vTSD ON vTSD.SubjectId = AC.SubjectId AND vTSD.DivisionId = AC.DivisionId AND vTSD.ClassId=AC.ClassId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = vTSD.OrgId
			INNER JOIN sSetup.tOrgGroupMaster OGM ON OGM.Id = OM.OrgGroupId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.OrgGroupId = OGM.Id
			INNER JOIN sHrm.tEmployeeMaster EM ON  AC.EmployeeId = EM.Id AND vTSD.EmployeeId = AC.EmployeeId
			INNER JOIN sHrm.tEmployeeJobdetail EJD ON EJD.EmployeeId = EM.Id
			INNER JOIN sSetup.tBatchMaster BM On BM.Id= AC.BatchId AND BM.OrgGroupBatchId = OGBM.Id
			INNER JOIN sSecurity.tUserOrganization U ON U.OrgId = OM.Id 
	WHERE 
	        --((AC.BatchId = @rBatchId) OR (@rBatchId = 0))
			((AC.Id = @rId) OR (@rId = 0))
			AND ((AC.EmployeeId= @rEmployeeId) OR (@rEmployeeId = 0))
			AND	((AC.ClassId = @rClassId) OR (@rClassId = 0))
			AND	((vTSD.OrgId = @rOrgId) OR (@rOrgId = 0))
			AND ((AC.SubjectId =@rSubjectId) OR (@rSubjectId=0))
			AND ((AC.DivisionId =@rDivisionId) OR (@rDivisionId=0))
			AND (AC.ClassWorkDate>=@rFromDate OR ISNULL(@rFromDate,'')='')
			AND (AC.ClassWorkDate<=@rToDate OR ISNULL(@rToDate,'')='')
			AND (OGBM.Id = @rOrgGroupBatchId) 
			AND ((U.UserId = @rUserId)OR(@rUserId=0))
			AND ISNULL(EM.IsOtherUser,0) = 0 
	order by 
			AC.HomeWorkEndDate DESC
		END 
	ELSE
		BEGIN
		SELECT 
			AC.Id,
			AC.EmployeeId,
			AC.ClassId,
			AC.DivisionId,
			AC.SubjectId,
			AC.ClassWorkDate,
			AC.Classwork,
			AC.Homework,
			ISNULL(ClassworkStatusId,1) AS ClassworkStatusId,
			ISNULL(HomeWorkStatusId,1) AS HomeWorkStatusId,
			--AC.HomeWorkEndDate,
			ISNULL(AC.HomeWorkEndDate,'') AS HomeWorkEndDate,
			AC.CreatedDateTime,
			AC.BatchId,
			BM.Title AS Batch,
		    ISNULL(vTSD.SubjectName,'') as SubjectName,
		    ISNULL(EM.FirstName + ' ' + EM.LastName,'') AS TeacherName,
		    ISNULL(vTSD.ClassTitle,'') AS ClassName,
		    ISNULL(vTSD.DivisionTitle,'') AS DivisionName,
		    BM.OrgId,
		    OM.DisplayTitle AS Organization,
		    REPLACE(CONVERT(VARCHAR(20), AC.ClassWorkDate, 103),'/','') +'_'+ CONVERT(nvarchar(10),AC.DivisionId) +'_'+CONVERT(nvarchar(10),AC.SubjectId) AS UniqueId,
			ISNULL(AC.IsSubmitHomework,0) AS IsSubmitHomework,
			AC.Id AS ClassworkId
	FROM 
			sAcademic.tClasswork AC
			INNER JOIN sAcademic.vTeacherSubjectDivision vTSD ON vTSD.SubjectId = AC.SubjectId AND vTSD.DivisionId = AC.DivisionId AND vTSD.ClassId=AC.ClassId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = vTSD.OrgId
			INNER JOIN sSetup.tOrgGroupMaster OGM ON OGM.Id = OM.OrgGroupId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.OrgGroupId = OGM.Id
			INNER JOIN sHrm.tEmployeeMaster EM ON  AC.EmployeeId = EM.Id AND vTSD.EmployeeId = AC.EmployeeId
			INNER JOIN sHrm.tEmployeeJobdetail EJD ON EJD.EmployeeId = EM.Id
			INNER JOIN sSetup.tBatchMaster BM On BM.Id= AC.BatchId AND BM.OrgGroupBatchId = OGBM.Id
			INNER JOIN sSecurity.tUserOrganization U ON U.OrgId = OM.Id 
	WHERE 
	        --((AC.BatchId = @rBatchId) OR (@rBatchId = 0))
			((AC.Id = @rId) OR (@rId = 0))
			AND ((AC.EmployeeId= @rEmployeeId) OR (@rEmployeeId = 0))
			AND	((AC.ClassId = @rClassId) OR (@rClassId = 0))
			AND	((vTSD.OrgId = @rOrgId) OR (@rOrgId = 0))
			AND ((AC.SubjectId =@rSubjectId) OR (@rSubjectId=0))
			AND ((AC.DivisionId =@rDivisionId) OR (@rDivisionId=0))
			AND (AC.ClassWorkDate>=@rFromDate OR ISNULL(@rFromDate,'')='')
			AND (AC.ClassWorkDate<=@rToDate OR ISNULL(@rToDate,'')='')
			AND (OGBM.Id = @rOrgGroupBatchId) 
			AND ((U.UserId = @rUserId)OR(@rUserId=0))
			AND ISNULL(EM.IsOtherUser,0) = 0 
			GROUP BY AC.Id,
			AC.EmployeeId,
			AC.ClassId,
			AC.DivisionId,
			AC.SubjectId,
			AC.ClassWorkDate,
			AC.Classwork,
			AC.Homework,
			ClassworkStatusId,
			HomeWorkStatusId,
			--AC.HomeWorkEndDate,
			AC.HomeWorkEndDate,
			AC.CreatedDateTime,
			AC.BatchId,
			BM.Title,
		  vTSD.SubjectName,
		    EM.FirstName,  EM.LastName,
		    vTSD.ClassTitle,
		   vTSD.DivisionTitle,
		    BM.OrgId,
		    OM.DisplayTitle,
		     AC.ClassWorkDate, AC.DivisionId,AC.SubjectId
			 ,AC.IsSubmitHomework
	order by 
			AC.HomeWorkEndDate DESC
		END
	
END
GO
PRINT N'Altering [sAcademic].[pLessonPlanAdd]...';


GO
 
ALTER PROCEDURE [sAcademic].[pLessonPlanAdd]
	 
        @rId bigint=0,
        @rTopicId int,
        @rDivisionId int, 
        @rNoOfPeriodRequired smallint,
        @rObjective nvarchar(1000),
        @rIndicativeHomework nvarchar(200),
        @rSummary nvarchar(200),
        @rStartDate date='',
        @rEndDate date='',
        @rIsCompleted bit=0,
        @rEmployeeId bigint,
        @rBatchId int,
        @rCreatedUserId bigint,
        @rOrgId smallint,
        @rLearningExperience nvarchar(1000)='',
        @rToolsAndTechniques nvarchar(500)='',
        @rEssentialMaterial nvarchar(500)='',
		@rAssessmentQuestion	nvarchar(1000)='',	
		@rTeacherExample	nvarchar(1000)='',
		@rGuidedPractice	nvarchar(1000)='',
		@rIndependentPractice	nvarchar(1000)	='',
		@rSubTopic nvarchar(1000)='' ,
	    @rSession nvarchar(100)='' ,
		@rTrainingMethod  nvarchar(100)='' ,
		@rPeriodCount int =0

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	 
	--IF(@rId = 0)	
	--BEGIN
	--	--If Exists(select Id from sCommunication.tNews where Code=@rCode AND OrgGroupBatchId=@rOrgGroupBatchId)
	--	--	BEGIN
	--	--	select -102 as Result
	--	--	RETURN
	--	--END 
	
	--	If Exists(select Id from sAcademic.tTopicMaster where Number=@rNumber AND OrgId=@rOrgId)
	--		BEGIN
	--		select -103 as Result
	--		RETURN
	--	END 
	--END
	--ELSE
	--BEGIN
	--	--If Exists(select Id from sCommunication.tNews where Code=@rCode AND OrgGroupBatchId=@rOrgGroupBatchId AND Id<>@rId)
	--	--Begin
	--	--	select -102 as Result
	--	--	RETURN
	--	--End
	--	If  Exists(select Id from sAcademic.tTopicMaster where Number=@rNumber AND OrgId=@rOrgId AND Id<>@rId)
	--	Begin
	--		select -103 as Result
	--		RETURN
	--	End

	--END
	
	IF(@rId = 0)	
	BEGIN
		IF EXISTS(SELECT Id FROM sAcademic.tLessonPlan WHERE DivisionId=@rDivisionId AND TopicId = @rTopicId AND StartDate = @rStartDate AND EndDate = @rEndDate)
		BEGIN
			SELECT -101 AS Result
			RETURN
		END 
	END
	ELSE
	BEGIN
		IF  EXISTS(SELECT Id FROM sAcademic.tLessonPlan WHERE DivisionId=@rDivisionId AND TopicId = @rTopicId AND StartDate = @rStartDate AND EndDate = @rEndDate AND Id <> @rId)
		BEGIN
			SELECT -101 AS Result
			RETURN
		END
	END

	DECLARE @lNextNumber BIGINT 

	IF(@rId = 0)	
	BEGIN
		
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sAcademic.tLessonPlan', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	INSERT INTO sAcademic.tLessonPlan
		(
			Id,
			TopicId,
			DivisionId,
			NoOfPeriodRequired,
			Objective,
			IndicativeHomework,
			Summary,
			StartDate,
			EndDate,
			IsCompleted,
			EmployeeId,
			BatchId,
			CreatedUserId,
			CreatedDateTime,
			LearningExperience,
			ToolsAndTechniques,
			EssentialMaterial,
			AssessmentQuestion,
			TeacherExample,
			GuidedPractice,
			IndependentPractice,
			SubTopic ,
			[Session] ,
			TrainingMethod ,
			PeriodCount
		)
	VALUES
		(
			@lNextNumber,
			@rTopicId,
			@rDivisionId,
			@rNoOfPeriodRequired,
			@rObjective,
			@rIndicativeHomework,
			@rSummary,
			@rStartDate,
			@rEndDate,
			@rIsCompleted,
			@rEmployeeId,
			@rBatchId,
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rLearningExperience,
			@rToolsAndTechniques,
			@rEssentialMaterial,
			@rAssessmentQuestion,
			@rTeacherExample,
			@rGuidedPractice,
			@rIndependentPractice,
			CASE WHEN @rSubTopic = '-1' Then '' ELSE @rSubTopic END ,
			@rSession ,
		    @rTrainingMethod ,
			@rPeriodCount
		)
		    SELECT 1 AS Result , @lNextNumber As Id
	END	 

ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE  sAcademic.tLessonPlan
	    SET
			TopicId=@rTopicId,
			DivisionId=@rDivisionId,
			NoOfPeriodRequired=@rNoOfPeriodRequired,
			Objective=@rObjective,
			IndicativeHomework=@rIndicativeHomework,
			Summary=@rSummary,
			StartDate=@rStartDate,
			EndDate=@rEndDate,
			IsCompleted=@rIsCompleted,
			UpdatedUserId=@rCreatedUserId,
			UpdatedDateTime=sCommon.fGetDate(),
			LearningExperience = @rLearningExperience,
			ToolsAndTechniques = @rToolsAndTechniques,
			EssentialMaterial =@rEssentialMaterial,
			EmployeeId = @rEmployeeId,
			AssessmentQuestion=@rAssessmentQuestion,
			TeacherExample=@rTeacherExample,
			GuidedPractice=@rGuidedPractice,
			IndependentPractice=@rIndependentPractice,
			SubTopic= CASE WHEN @rSubTopic = '-1' Then '' ELSE @rSubTopic END ,
			[Session] = @rSession ,
			TrainingMethod =@rTrainingMethod ,
			PeriodCount =@rPeriodCount
	      WHERE Id = @rId
	      SELECT 11 AS Result, @lNextNumber As Id
	 END  	

END
GO
PRINT N'Altering [sAcademic].[pXMLTopicMasterAdd]...';


GO
ALTER PROCEDURE [sAcademic].[pXMLTopicMasterAdd]
	(
		@rXml  nvarchar(MAX),
		@rOrgId int,
		@rClassId int,
		@rSubjectId int,
		@rCreatedUserId bigint 
		
	)
AS

SET NOCOUNT ON

BEGIN

	DECLARE @lInterrorCode INT,@intDoc INT
	DECLARE @lNextNumber BIGINT			
 
	EXECUTE @lInterrorCode = sp_xml_preparedocument @intDoc OUTPUT, @rXml
	
	BEGIN TRY

	CREATE TABLE #tempTable  
	(
		Id bigint identity,
		Number smallint,
		Title nvarchar(500)
	)

	INSERT INTO #tempTable
	(
		Number,
		Title
	)
	SELECT	
			A.Number,
			A.Title
	FROM OPENXML (@intDoc, '/Table/TopicMaster', 1)
	WITH
	(
			Number nvarchar(100) '@Number',
			Title nvarchar(100) '@Title' 
			 
	)A 
	 
	DECLARE @lCount int,@lId int
	SELECT @lCount = COUNT(Id) FROM #tempTable
	SELECT Top 1 @lId=Id FROM #tempTable
	
	WHILE @lId <= @lCount 
	BEGIN

		DECLARE @lNumber smallint, @lTitle nvarchar(500), @lSubjectId Int, @lClassId int, @lOrgId smallint
		
		SELECT @lNumber = Number from #tempTable where  Id = @lId
		SELECT @lTitle = Title from #tempTable where  Id = @lId
		
		If Exists(select Id from sAcademic.tTopicMaster where Title=@lTitle AND OrgId=@rOrgId AND ClassId=@rClassId AND SubjectId=@rSubjectId)
		BEGIN
			select -102 as Result, 'Title Already Exists' AS MSG
			RETURN
		END 
	
		If Exists(select Id from sAcademic.tTopicMaster where Number=@lNumber AND OrgId=@rOrgId AND ClassId=@rClassId AND SubjectId=@rSubjectId)
		BEGIN
			select -103 as Result, 'Number Already Exists' AS MSG
			RETURN
		END 

			EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sAcademic.tTopicMaster', 0, 1, 1,@outNextNumber = @lNextNumber output

			print @lNextNumber

			INSERT INTO sAcademic.tTopicMaster
			(		Id,
					Number,
					Title,
					SubjectId,
					ClassID,
					OrgId,
					CreatedUserId,
					CreatedDateTime 
					
			)
			Values
			(	
					@lNextNumber,
					@lNumber,
					@lTitle,
					@rSubjectId,
					@rClassID,
					@rOrgId,
					@rCreatedUserId,
					sCommon.fGetDate()   
			)

		EXEC sp_xml_removedocument @intDoc
	
		SELECT @lNextNumber = MAX(ID) FROM sAcademic.tTopicMaster Where OrgId=@rOrgId
		EXECUTE sCommon.pTableRowIdModify @rOrgId, @rTableTitle = 'sAcademic.tTopicMaster', @rCurrentNumber = @lNextNumber 

		SET @lId=@lId+1
		
	END
	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 [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  
	 
  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
		ELSE 0 END) DebitAmount,
		(CASE WHEN TD.Amount < 0 THEN -1 * TD.Amount
		ELSE 0 END) CreditAmount,
		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 [sAdmission].[pAdmissionFormGet]...';


GO
 
  

ALTER PROCEDURE [sAdmission].[pAdmissionFormGet]

	 @rAdmissionFormId bigint = 0,
	 @rFormNo int,
	 @rForClassId int,
	 @rBatchId int=0,
	 @rStatusId smallint='',
	 @rOrgId int,
	 @rFirstName nvarchar(100),
	 @rLastName nvarchar(100),
	 @rMeritMarks decimal(10,2),
	 @rFromDate datetime= '1900-01-01',
	 @rToDate datetime = '9990-12-31',
	 @rDepartmentId int=0,
	 @rIsTransportFilter int=2,
	 @rIsHostelFilter int=2,
	 @rDataEntryStatusId smallint=0,
	 @rIsCommonSearch bit=0
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	
	SET @rToDate = DATEADD(d,1,@rToDate)		 

BEGIN 
		--IF @rIsSearch = 1
		BEGIN
		SET @rFirstName = ISNULL(@rFirstName,'')
		SET @rLastName = ISNULL(@rLastName,'')
			SET @rFirstName = sCommon.fSearchStringGet(@rFirstName)
			SET @rLastName = sCommon.fSearchStringGet(@rLastName)
		END
	
	SELECT 
			 AF.Id
			,AF.FormNo
			,AF.FirstName
			,AF.MiddleName
			,AF.LastName

			--,AF.FirstName+' '+AF.LastName as Name
			,[sStudent].[fStudentNameGet](AF.FirstName , ISNULL(AF.MiddleName,'') , AF.LastName,OM.StudentNameFormatId ) AS Name

			,AF.ForClassId
			,AF.BatchId
			,CM.Title AS ClassName
			,AF.ForBatch
			,ISNULL(AF.DateOfBirth,'') AS DateOfBirth
			,AF.DateOfBirthInWord
			,AF.StatusId
			,SM.Title as StatusName
			,ISNULL(ASM.Title,'') AS FormStatus
			,AF.StreetOne
			,AF.StreetTwo
			,AF.StreetThree
			,AF.Country
			,AF.State
			,AF.City
			,AF.ZipCode
			,AF.ContactNo
			,AF.ContactEmail
			,AF.Remark
			,AF.PreviousSchool
			,AF.MeritMarks
			,AF.MeritGrade
			,AF.GenderId
			,ISNULL(GM.Title,'') AS Gender
			,ISNULL(AF.ReligionId,0) AS ReligionId
			,AF.FamilyCast
			,AF.FamilySubCast
			,ISNULL(AF.CastCategoryId,0) AS CastCategoryId
			,AF.CreatedDateTime AS AdmissionFormDate
			,ISNULL(AF.StudentId,0) AS StudentId
			,ISNULL(AF.AdmissionDate,'') AS AdmissionDate
			--,AF.StudentPhoto,
			,(CASE WHEN @rIsCommonSearch=0 THEN ISNULL(AF.StudentPhoto,0) ELSE NULL END) AS StudentPhoto
			
			,ISNULL(AFFD.FatherName,'') AS FatherName,
			Isnull(AFFD.FatherDateOfBirth,'') AS FatherDateOfBirth,
			Isnull(AFFD.FatherOccupation,'') AS FatherOccupation,
			Isnull(AFFD.FatherQualification,'') AS FatherQualification,
			Isnull(AFFD.FatherContactNo,'') AS FatherContactNo,
			Isnull(AFFD.FatherMail,'') AS FatherMail,
			Isnull(AFFD.FatherOfficeAddress,'') As FatherOfficeAddress,
			isnull(AFFD.FatherOrganization,'') as FatherOrganization,
			isnull(AFFD.FatherDesignation,'') as FatherDesignation,
			Isnull(AFFD.FatherIncome,'') as FatherIncome,
			Isnull(AFFD.MotherName,'') AS MotherName,
			iSNULL(AFFD.MotherDateOfBirth,'')AS MotherDateOfBirth,
			isnull(AFFD.MotherOccupation,'') AS MotherOccupation,
			isnull(AFFD.MotherQualification,'') AS MotherQualification,
			isnull(AFFD.MotherContactNo,'') as MotherContactNo,
			isnull(AFFD.MotherMail,'') As MotherMail,
			isnull(AFFD.MotherOfficeAddress,'') as MotherOfficeAddress,
			isnull(AFFD.MotherOrganization,'') as MotherOrganization,
			isnull(AFFD.MotherDesignation,'') as MotherDesignation,
			isnull(AFFD.MotherIncome,'') as MotherIncome,
			AF.MotherTongue AS MotherTongue,
		 
			isnull(AFFD.RelationshipName,'') as RelationshipName,
			isnull(AFFD.RelativeName,'')  AS GuardianName ,
			isnull(AFFD.RelativeDateOfBirth ,'')AS GuardianDateOfBirth,
			isnull(AFFD.RelativeOccupation,'') AS GuardianOccupation,
			isnull(AFFD.RelativeQualification,'') AS GuardianQualification,
			isnull(AFFD.RelativeContactNo,'') AS GuardianContactNo,
			isnull(AFFD.RelativeMail,'')  AS GuardianMail,
			isnull(AFFD.RelativeOfficeAddress,'') AS GuardianOfficeAddress,
			isnull(AFFD.RelativeOrganization,'') as RelativeOrganization,
			isnull(AFFD.RelativeDesignation,'') as RelativeDesignation,
			isnull(AFFD.RelativeIncome,'') AS GuardianIncome  ,
			isnull(AF.IsHostelRequired,0) AS IsHostelRequired  ,
			isnull(AF.IsTransportRequired,0) AS IsTransportRequired,
			isnull(AF.BirthPlace,'') AS BirthPlace,
			isnull(AF.BirthTaluka,'') AS BirthTaluka,
			isnull(AF.BirthDistrict,'') AS BirthDistrict,
			isnull(AF.BloodGroupId,0) AS BloodGroupId,
			isnull(AF.AdhaarNumber,'') AS AdhaarNumber,
			isnull(AF.IsPysicalDeformity,0) AS IsPysicalDeformity,
			isnull(AF.PysicalDeformityRemark,'') AS PysicalDeformityRemark,
			isnull(AF.IsMajorIllness,0) AS IsMajorIllness,
			isnull(AF.MajorIllnessRemark,'') AS MajorIllnessRemark,
			isnull(AF.IsAllergy,0) AS IsAllergy,
			isnull(AF.AllergyRemark,'') AS AllergyRemark,
			isnull(AF.BirthState,'') AS BirthState,
			isnull(AF.BirthCountry,'') AS BirthCountry,
			isnull(SA.PreviousStandard,'') As PreviousStandard,
	        isnull(AFFD.LiveWithId,0) AS LiveWithId,
			--isnull(ASB.SiblingName,'') AS SiblingName,
			--isnull(ASB.SiblingRelation,'')AS SiblingRelation,
			
			--isnull(ASB.SiblingStandard,'') AS SiblingStandard,
			--isnull(ASB.SiblingSchool,'')AS SiblingSchool
			
			 ISNULL(AF.CustomField1Answer,'') AS CustomField1Answer,
			 ISNULL(AF.CustomField2Answer,'') AS CustomField2Answer,
			 ISNULL(AF.CustomField3Answer,'') AS CustomField3Answer,
			 SM1.Title AS DataEntryStatus,
			 AF.Nationality,
			 ISNULL(AFFD.FatherAdhaarNumber,'') AS FatherAdhaarNumber,
			 AF.CreatedDateTime AS AdmissionFormDate,
			 ISNULL(AFFD.MotherAadhaarNumber,'') AS MotherAadhaarNumber,
			 ISNULL(AFFD.RelativeAadhaarNumber,'') AS RelativeAadhaarNumber,
			 ISNULL(AFFD.FatherOfficePhone,'') AS FatherOfficePhone,
			 ISNULL(AFFD.MotherOfficePhone,'') AS MotherOfficePhone,
			 CASE WHEN AF.DataEntryModeId = 561 THEN 'Online' ELSE 'Offline' END DataEntryMode
			 
  FROM 
            sAdmission.tAdmissionForm AF
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = AF.OrgId
			INNER JOIN sCommon.tStatusMaster SM ON SM.Id=AF.StatusId
			INNER JOIN sCommon.tStatusMaster SM1 ON SM1.Id=AF.DataEntryStatusId			
			INNER JOIN sSetup.tClassMaster CM ON CM.Id=AF.ForClassId
			LEFT JOIN sCommon.tGenderMaster GM ON GM.Id=AF.GenderId
			LEFT JOIN sAdmission.tAdmissionFormSelected AFS ON AF.Id = AFS.AdmissionFormId
			LEFT JOIN sAdmission.tAdmissionStatusMaster ASM ON ASM.Id = AFS.AdmissionStatusId
			LEFT JOIN sAdmission.tAdmissionFormFamilyDetail AFFD ON AFFD.AdmissionFormId = AF.Id
			LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId = AF.StudentId
			 --LEFT JOIN sAdmission.tAdmissionFormSibling ASB ON ASB.AdmissionFormId = AF.Id
			LEFT JOIN sStudent.tStudentAdmission SA ON SA.StudentID=AF.StudentID
  WHERE 
  
      ((AF.Id = @rAdmissionFormId) OR (@rAdmissionFormId = 0))
		AND ((AF.FormNo=@rFormNo) OR (@rFormNo=0))
		AND ((AF.FirstName like @rFirstName) OR (@rFirstName=''))
		AND ((AF.LastName like @rLastName) OR (@rLastName=''))
		--AND ((AF.CreatedDateTime>= @rFromDate) OR (@rFromDate=''))
		AND ((Cast(AF.AdmissionDate as datetime)>= @rFromDate) OR (@rFromDate=''))
		--AND ((AF.AdmissionDate is not null AND Cast(AF.AdmissionDate as datetime)>= @rFromDate) or (AF.AdmissionDate is null AND AF.CreatedDateTime>= @rFromDate) or (@rFromDate=''))
		--AND ((AF.CreatedDateTime < @rToDate) OR (@rToDate=''))
		AND ((Cast(AF.AdmissionDate as datetime)< @rToDate) OR (@rToDate=''))
		--AND ((AF.AdmissionDate is not null AND Cast(AF.AdmissionDate as datetime)< @rToDate) or (AF.AdmissionDate is null AND AF.CreatedDateTime< @rToDate) or (@rToDate=''))
		AND ((AF.StatusId=@rStatusId) OR (@rStatusId=0))
		AND ((AF.ForClassId=@rForClassId) OR (@rForClassId=0)) 
		AND ((AF.BatchId=@rBatchId) OR (@rBatchId=0)) 
		--AND ((AF.MeritMarks=@rMeritMarks) OR (@rMeritMarks=0))
		AND ((AF.StatusId=@rStatusId) OR (@rStatusId = ''))
		AND ((AF.DataEntryStatusId=@rDataEntryStatusId) OR (@rDataEntryStatusId = 0))
		AND ((CM.DepartmentId=@rDepartmentId) OR (@rDepartmentId = 0))
		AND AF.OrgId=@rOrgId
        AND ((ISnull(AF.IsHostelRequired,0)=@rIsHostelFilter ) OR   (ISNULL(@rIsHostelFilter,2)=2) )
	   AND ((ISNUll(AF.IsTransportRequired,0)=@rIsTransportFilter) OR (isnull(@rIsTransportFilter,0) = 2))
	  
 order by AF.FormNo
END
GO
PRINT N'Altering [sAdmission].[pAdmissionGenerateReport]...';


GO

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

AS
BEGIN
	 
	SET NOCOUNT ON;

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

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

		DECLARE @Sql nvarchar(MAX)= ''
		
		SET @rFirstName = sCommon.fSearchStringGet(@rFirstName)
		SET @rLastName = sCommon.fSearchStringGet(@rLastName)
		SET @rFatherName = sCommon.fSearchStringGet(@rFatherName)
		SET @rMotherName = sCommon.fSearchStringGet(@rMotherName)
		SET @rCountry = sCommon.fSearchStringGet(@rCountry)
		SET @rState = sCommon.fSearchStringGet(@rState)
		SET @rCity = sCommon.fSearchStringGet(@rCity)
		SET @rNationality = sCommon.fSearchStringGet(@rNationality)
		SET @rMotherTongue = sCommon.fSearchStringGet(@rMotherTongue)
		SET @rPreviousSchool = sCommon.fSearchStringGet(@rPreviousSchool)
		SET @rFatherQualification = sCommon.fSearchStringGet(@rFatherQualification)
		SET @rMotherQualification = sCommon.fSearchStringGet(@rMotherQualification)
		SET @rFatherOccupation = sCommon.fSearchStringGet(@rFatherOccupation)
		SET @rMotherOccupation = sCommon.fSearchStringGet(@rMotherOccupation)
		
		






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

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

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

		  --
		IF(@cols IS NOT NULL)
		Declare @lSQL nvarchar(max) ='', @lqry nvarchar(max)=''
		IF(@rOrderBy = '' OR @rOrderBy = NULL)
		BEGIN
			--SET @lSQL = @lSQL + 'SELECT ' + @rColumnName + ' FROM #MyAdmissionSearchTable AT'
			SET @lSQL = @lSQL + 'SELECT ' + @rColumnName + ' FROM #MyAdmissionSearchTable AT LEFT JOIN ##tempAdmissionCriteriaForm ACF ON AT.Id = ACF.AdmissionFormId'
			print(@lSQL)
			exec(@lSQL)
		END
		ELSE
		BEGIN
		print(@rOrderBy)
			SET @lSQL = @lSQL + 'SELECT ' + @rColumnName + ' FROM #MyAdmissionSearchTable AT LEFT JOIN ##tempAdmissionCriteriaForm ACF ON AT.Id = ACF.AdmissionFormId ORDER BY ' +@rOrderBy+ ';'
			print(@lSQL)
			exec (@lSQL)
			IF OBJECT_ID(N'dbo.MyTable0', N'U') IS NOT NULL 
			 DROP Table ##tempAdmissionCriteriaForm
		END
		
END
GO
PRINT N'Altering [sAdmission].[pRptAdmissionSummaryGet]...';


GO


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

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


GO

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

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


GO
 ALTER PROCEDURE [sAlert].[pVisitorGatePassGet]
	
		 @rVisitorLogId int,
	 	 @rOrgId int,
	 	 @rTemplate nvarchar(max),
		 @rSubject nvarchar(100)='',
		 @rIsOutEntry bit = 0
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	IF(@rIsOutEntry=0)
	BEGIN
		SELECT 
				VL.Id,
				VL.VisitorName,
				EC.MobileNumber AS MobileNo,
				VL.VisitorContactNumber AS ContactNumber,
				EC.CompanyEmail AS EmailId,
				replace (
				replace (
				replace(@rTemplate,'[VisitorName]',VL.VisitorName),
				'[NoOfVisitors]',VL.NoOfVisitor),
				'[PurposeOfVisit]',VL.PurposeOfVisit)
				AS MsgText,
				@rSubject AS Subject,
				95 AS ReceiverSourceTypeId,
				EM.Id AS ReceiverSourceId,
				EM.Id AS SourceId,
				95 AS SourceTypeId,
				OM.OrgGroupId,
				VL.OrgId,
				VL.NoOfVisitor AS NoOfVisitors,
				VL.PurposeOfVisit AS PurposeOfVisit,
				ISNULL(EC.WhatsAppContactNo,'') AS WhatsAppContactNo
		FROM 
			sFrontOffice.tVisitorLog VL
			LEFT JOIN [sHrm].[tEmployeeMaster] EM ON VL.WhomToMeet=EM.Id
			LEFT JOIN [sHrm].[tEmployeeCommunications] EC ON EM.Id=EC.EmployeeId
			LEFT JOIN sSetup.tOrganizationMaster OM ON VL.OrgId = OM.Id	
		WHERE
			((VL.OrgId=@rOrgId) OR (@rOrgId=0))
			AND VL.Id = @rVisitorLogId
	END

	ELSE

	BEGIN
		SELECT 
				VL.Id,
				VL.VisitorName,
				VL.VisitorContactNumber AS MobileNo,
				'' AS EmailId,
				replace (
				replace (
				replace(@rTemplate,'[VisitorName]',VL.VisitorName),
				'[NoOfVisitors]',VL.NoOfVisitor),
				'[PurposeOfVisit]',VL.PurposeOfVisit)
				AS MsgText,
				@rSubject AS Subject,
				0 AS ReceiverSourceTypeId,
				0 AS ReceiverSourceId,
				0 AS SourceId,
				0 AS SourceTypeId,
				OM.OrgGroupId,
				VL.OrgId,
				VL.NoOfVisitor AS NoOfVisitors,
				VL.PurposeOfVisit AS PurposeOfVisit,
				ISNULL(VL.VisitorContactNumber,'') AS WhatsAppContactNo
		FROM 
			sFrontOffice.tVisitorLog VL
			--To Send Alert on Visitor Contact No
			--LEFT JOIN [sHrm].[tEmployeeMaster] EM ON VL.WhomToMeet=EM.Id
			--LEFT JOIN [sHrm].[tEmployeeCommunications] EC ON EM.Id=EC.EmployeeId
			LEFT JOIN sSetup.tOrganizationMaster OM ON VL.OrgId = OM.Id	
		WHERE
			((VL.OrgId=@rOrgId) OR (@rOrgId=0))
			AND VL.Id = @rVisitorLogId
		END
END
GO
PRINT N'Altering [sAssessment].[pRptStudentGradeAnalysisSubjectWise]...';


GO
ALTER PROCEDURE [sAssessment].[pRptStudentGradeAnalysisSubjectWise]
	 
	 @rClassId int=0,
	 @rDivisionId int=0,
	 @rExamSubGroupId int=0,
	 @rBuilder1 nvarchar(MAX)='',
	 @rBatchId int,
	 @rClass nvarchar(MAX)='',
	 @rStatusId int = 0,
	 @rClassStatusId int=0,
	 @rGroupId int=0

	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
   SELECT 
		COUNT(RD.id),
		@rBuilder1 AS Builder1,
		RD.SubjectGrade,
		SM.Title AS SubjectName,
		CS.IsOptional ,
		DM.Id AS DivisionId,
		Dm.DisplayTitle as DivisionName,
		Cm.Id AS ClassId,
		CM.DisplayTitle AS ClassName,
		ISNULL(GD.MarkRange,'') AS MarkRange,
		SM.OrderIndex AS SubjectOrderIndex,
		GM.Title AS Gender,
		GM.Id AS GenderId,
		GD.GradeSetId,
		GD.Minimumscore,

		CASE WHEN @rGroupId=1 THEN DM.Id 
				WHEN @rGroupId=2 THEN CM.Id END AS GroupId,
				
		CASE WHEN @rGroupId=1 THEN CM.DisplayTitle+'/'+DM.DisplayTitle
				WHEN @rGroupId=2 THEN CM.DisplayTitle END AS GroupName,
				
		CASE WHEN @rGroupId=1 THEN Dm.OrderIndex
				WHEN @rGroupId=2  THEN Cm.OrderIndex END AS OrderIndex,
				
		CASE WHEN @rGroupId=1 THEN 'Class/Division'
				WHEN @rGroupId=2  THEN 'Class' END AS GroupTitle,
		@rBatchId AS BatchId
				
  FROM 
		sAssessment.tResultDetail  RD
		Inner join sAssessment.tResult R ON R.Id=Rd.ResultId
		INNER JOIN sStudent.tAcademic A ON R.AcademicId = A.Id 
		INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId
		INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId
		INNER JOIN sAssessment.tExamDetail ED ON ED.ID=RD.ExamDetailId
		INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
		INNER JOIN  sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId 
		INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=CS.SubjectId 
		INNER JOIN sStudent.tStudentOther SO ON SO.StudentId = A.StudentId 	
		INNER JOIN sStudent.tStudentMaster STM ON STM.Id = A.StudentId 	
		INNER JOIN sCommon.tGenderMaster GM ON GM.Id=SO.GenderId
		LEFT JOIN  sAssessment.tGradeSetDetail GD ON
		GD.GradeSetId = ED.GradeSetId AND RD.SubjectGrade = GD.GradeCode
   WHERE 
	    EM.ExamSubGroupId=@rExamSubGroupId
		and EM.BatchId=@rBatchId
		and ((CM.Id=@rClassId)  OR (@rClassId=0))
		AND ((DM.ID=@rDivisionId) OR (@rDivisionId=0))
		AND (ISNULL(Cm.Id,0) IN( SELECT item FROM  sCommon.fnsplit(@rClass,','))OR @rClass='')
	    and((STM.StatusId=@rStatusId) or (@rStatusId=0))
		AND ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0))
   GROUP BY 
		RD.SubjectGrade,GD.MarkRange,SM.Title,CS.IsOptional ,DM.Id,DM.DisplayTitle,CM.Id,CM.DisplayTitle,SM.OrderIndex,GM.Title,GM.Id,GD.GradeSetId,GD.Minimumscore
		,Dm.OrderIndex,Cm.OrderIndex
END
GO
PRINT N'Altering [sAssetManagement].[pImportAssetAdd]...';


GO
ALTER PROCEDURE [sAssetManagement].[pImportAssetAdd] 
	@rOrgGroupId int,
	@rXmldoc [nvarchar](max),
	@rCustomFieldXML nvarchar(max),
	@rCreatedUserId bigint,
	@rOrgId int,
	@rStoreLocationId int
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
SET NOCOUNT ON;
DECLARE @lCount INT
Declare @lResult int, @lresultCode nvarchar(100)
DECLARE @lInterrorCode INT,@intDoc INT
DECLARE @lInterrorCode1 INT,@intDoc1 INT

Declare 
	@lCode nvarchar(20),
	@lName nvarchar(100) = '',
	@lAssetCategory nvarchar(50) = '',
	@lModelNumber nvarchar(50) = '',
	@lSpecification nvarchar(300) = '',
	@lAccessories nvarchar(300) = '',
	@lIsMaintenance bit = null,
	@lServiceEntry date =  Null,
	@lMaitenancePeriod smallint = null,
	@lAlertPeriod smallint = null,
	@lCurrentDepartment nvarchar(50) ='',
	@lCurrentLocation nvarchar(50) ='',
	@lUsageStatus nvarchar(50) ='',
	@lLastServiceCost decimal(22,6) = null,
	@lTotalServiceCost decimal(22,6)  = null,
	@lLastMaintenanceDate datetime = null,
	@lNextMaintenanceDate datetime = null,
	@lIsCheckRequired bit = null,
	@lCheckFrequency nvarchar(50) = '',
	@lCheckList nvarchar(300) = null,
	@lCheckedLastDate date = null,
	@lCheckedByUserId bigint = null,
	@lCheckedStatus nvarchar(300) =  null,
	@lCheckedRemark nvarchar(200) = null,
	@lIsRenewRequired bit = null,
	@lRenewLastDate date = null,
	@lRenewNextDate date = null,
	@lRenewRemark nvarchar(300) =  null,
	@lRenewCheckList nvarchar(300) = null,
	@lRenewAlertBeforeDays smallint = null,
	@lAssetCategoryId bigint = 0,
	@lCurrentDepartmentId bigint = 0,
	@lCurrentLocationId int = 0,
	@lUsageStatusId bigint = 0,
	@lCheckFrequencyId bigint = 0,
	@lCheckedStatusId bigint = 0,
	@lGoodsReceiptNumber nvarchar (20) = '',
	@lGoodsReceiptDate date = null,
	@lQuantity decimal = 1,
	@lNumber Nvarchar(20) = '',
	--@lAssetCode nvarchar(50) = '',
	@lWarrantyDate date = null,
	@lUniqueId INT=0
	
	EXECUTE @lInterrorCode = sp_xml_preparedocument @intDoc OUTPUT, @rXmlDoc
	EXECUTE @lInterrorCode1 = sp_xml_preparedocument @intDoc1 OUTPUT, @rCustomFieldXML

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

	CREATE TABLE #tempTable  
	(
			Id bigint identity,
			Name nvarchar(100),
			AssetCategory nvarchar(50),
			ModelNumber nvarchar(50),
			Quantity decimal null,
			Specification nvarchar(300),
			Accessories nvarchar(300),
			IsMaintenance bit null,
			ServiceEntry date  Null,
			MaitenancePeriod smallint null,
			AlertPeriod smallint null,
			CurrentDepartment nvarchar(50),
			CurrentLocation nvarchar(50),
			UsageStatus nvarchar(50),
			LastServiceCost decimal(22,6) null,
			TotalServiceCost decimal(22,6) null,
			LastMaintenanceDate datetime Default null,
			NextMaintenanceDate datetime Default null,
			IsCheckRequired bit null,
			CheckFrequency nvarchar(50),
			CheckList nvarchar(300) null,
			CheckedLastDate date Default null,
			IsRenewRequired bit null,
			RenewLastDate date Default null,
			RenewNextDate date Default null,
			RenewRemark nvarchar(300) null,
			RenewCheckList nvarchar(300) null,
			RenewAlertBeforeDays smallint null,
			--AssetCode nvarchar(50) null,
			WarrantyDate date null,
			UniqueId Int
	)
	print('Table Created')
	INSERT INTO #tempTable
	(
			Name,
			AssetCategory,
			ModelNumber,
			Quantity,
			Specification,
			Accessories,
			IsMaintenance,
			ServiceEntry,
			MaitenancePeriod,
			AlertPeriod,
			CurrentDepartment,
			CurrentLocation,
			UsageStatus,
			LastServiceCost,
			TotalServiceCost,
			LastMaintenanceDate,
			NextMaintenanceDate,
			IsCheckRequired,
			CheckFrequency,
			CheckList,
			CheckedLastDate,
			IsRenewRequired,
			RenewLastDate,
			RenewNextDate,
			RenewRemark,
			RenewCheckList,
			RenewAlertBeforeDays,
			--AssetCode,
			WarrantyDate,
			UniqueId
	)

	SELECT *
			FROM OPENXML (@intDoc, '/Table/ImportAsset', 1)
	WITH
	(						
			Name nvarchar(100) '@Name',
			AssetCategory nvarchar(50) '@AssetCategory',
			ModelNumber nvarchar(50) '@ModelNumber',
			Quantity decimal '@Quantity',
			Specification nvarchar(300) '@Specification',
			Accessories nvarchar(300) '@Accessories',
			IsMaintenance bit '@IsMaintenance',
			ServiceEntry date '@ServiceEntry',
			MaitenancePeriod smallint '@MaintenancePeriod',
			AlertPeriod smallint '@AlertPeriod',
			CurrentDepartment nvarchar(50)'@CurrentDepartment',
			CurrentLocation nvarchar(50)'@CurrentLocation',
			UsageStatus nvarchar(50)'@UsageStatus',
			LastServiceCost decimal(22,6) '@LastServiceCost',
			TotalServiceCost decimal(22,6) '@TotalServiceCost',
			LastMaintenanceDate datetime '@LastMaintenanceDate',
			NextMaintenanceDate datetime '@NextMaintenanceDate',
			IsCheckRequired bit '@IsCheckRequired',
			CheckFrequency nvarchar(50)'@CheckFrequency',
			CheckList nvarchar(300) '@CheckList',
			CheckedLastDate date '@CheckedLastDate',
			IsRenewRequired bit '@IsRenewRequired',
			RenewLastDate date '@RenewLastDate',
			RenewNextDate date '@RenewNextDate',
			RenewRemark nvarchar(300) '@RenewRemark',
			RenewCheckList nvarchar(300) '@RenewCheckList',
			RenewAlertBeforeDays smallint '@RenewAlertBeforeDays',
			--AssetCode nvarchar(50) '@AssetCode',
			WarrantyDate date '@WarrantyDate',
			UniqueId INT '@UniqueId'
	) A 
	

	print('Master Insert')

	CREATE TABLE #tempTableCustomField
	(
		Id bigint identity,
		UniqueId Int,
		FieldName nvarchar(500),
		FieldData nvarchar(500)
		--AssetId bigint
	)
	print('Created')
	INSERT INTO #tempTableCustomField
	(
		UniqueId,
		FieldName,
		FieldData
		--AssetId
	)

	SELECT A.UniqueId, A.FieldName,A.FieldData
			FROM OPENXML (@intDoc1, '/Table/ImportCustomField', 1)
	WITH
	(
		UniqueId nvarchar(500) '@UniqueId',
		FieldName nvarchar(500) '@FieldName',
		FieldData nvarchar(500) '@FieldData'				
	) A 

	EXEC sp_xml_removedocument @intDoc

	EXEC sp_xml_removedocument @intDoc1

	print('Custom Add')

	DECLARE @lTotal int = 0, @lCustomUniqueId int = 0
	SELECT @lTotal = COUNT(Id) FROM #tempTable
	SELECT @lCount = 1
	
	WHILE @lCount <= @lTotal 
	BEGIN
	SELECT 
			@lName = Name,
			@lAssetCategory = AssetCategory,
			@lModelNumber = ModelNumber,
			@lQuantity = Quantity,
			@lSpecification = Specification,
			@lAccessories = Accessories,
			@lIsMaintenance = IsMaintenance,
			@lServiceEntry = ServiceEntry,
			@lMaitenancePeriod = MaitenancePeriod,
			@lAlertPeriod = AlertPeriod,
			@lCurrentDepartment = CurrentDepartment,
			@lCurrentLocation = CurrentLocation,
			@lUsageStatus = UsageStatus,
			@lLastServiceCost = LastServiceCost,
			@lTotalServiceCost = TotalServiceCost,
			@lLastMaintenanceDate = LastMaintenanceDate,
			@lNextMaintenanceDate = NextMaintenanceDate,
			@lIsCheckRequired = IsCheckRequired,
			@lCheckFrequency = CheckFrequency,
			@lCheckList = CheckList,
			@lCheckedLastDate = CheckedLastDate,
			@lIsRenewRequired = IsRenewRequired,
			@lRenewLastDate = RenewLastDate,
			@lRenewNextDate = RenewNextDate,
			@lRenewRemark = RenewRemark,
			@lRenewCheckList =RenewCheckList,
			@lRenewAlertBeforeDays = RenewAlertBeforeDays,
			--@lAssetCode = AssetCode,
			@lWarrantyDate = WarrantyDate
			FROM #tempTable WHERE Id = @lCount

			SET @lCustomUniqueId = (Select UniqueId from #tempTable WHERE Id = @lCount)

			SET @lAssetCategoryId = '' SET @lCurrentDepartmentId = '' SET @lCurrentLocationId = 0
			SET @lUsageStatusId = ''  SET @lCheckFrequencyId =''     SET @lCheckedStatusId = ''
			SET @lGoodsReceiptNumber = '' SET @lGoodsReceiptDate = ''

			SELECT @lAssetCategoryId = Id FROM sFixedAsset.tCategoryMaster WHERE  Title = @lAssetCategory 
			SELECT @lCurrentDepartmentId = Id FROM sSetup.tDepartmentMaster WHERE  Title = @lCurrentDepartment AND OrgId = @rOrgId
			SELECT @lCurrentLocationId = Id FROM sFixedAsset.tLocationMaster WHERE  Title = @lCurrentLocation AND OrgId = @rOrgId
			--SELECT @lUsageStatusId = Id FROM sFixedAsset.tCategoryMaster WHERE  Title = @lAssetCategory
			SELECT @lCheckFrequencyId = Id FROM sCommon.tCheckFrequencyMaster WHERE  Title = @lCheckFrequency
			--SELECT @lCheckedStatusId = Id FROM sCommon.tStatusMaster WHERE  Title = @lCheckedStatus
			IF(@lUsageStatus = 'Spare')
			BEGIN
				SET @lUsageStatusId = '121'
				SET @lGoodsReceiptNumber = 'GRN01'
			END
			IF(@lUsageStatus = 'Deployed')
			BEGIN
				SET @lUsageStatusId = '122'
			END
			IF(@lUsageStatus = 'Maintenance')
			BEGIN
				SET @lUsageStatusId = '123'
			END
			IF(@lUsageStatus = 'Retired')
			BEGIN
				SET @lUsageStatusId = '124'
			END
			IF(@lUsageStatus = 'Removed')
			BEGIN
				SET @lUsageStatusId = '125'
			END
			IF(LEN(@lCheckList) = 0)
			BEGIN
				SET @lCheckList = Null
			END
			IF(@lCheckedLastDate = '1900-01-01')
			BEGIN
				SET @lCheckedLastDate = Null
			END
			IF(@lRenewLastDate = '1900-01-01')
			BEGIN
				SET @lRenewLastDate = Null
			END
			IF(@lRenewNextDate = '1900-01-01')
			BEGIN
				SET @lRenewNextDate = Null
			END
			IF(LEN(@lRenewRemark) = 0)
			BEGIN
				SET @lRenewRemark = Null
			END
			IF(LEN(@lRenewCheckList) = 0)
			BEGIN
				SET @lRenewCheckList = Null
			END
			IF(@lRenewAlertBeforeDays = 0)
			BEGIN
				SET @lRenewAlertBeforeDays = Null
			END
			IF(@lWarrantyDate = '1900-01-01')
			BEGIN
				SET @lWarrantyDate = Null
			END

			IF(@lQuantity=0)
			BEGIN
				SET @lQuantity=1
			END
			SET @lGoodsReceiptDate =   GETDATE();
			
			DECLARE @lNextNumber INT
			DECLARE @lTotalRecords Int
			
			DECLARE @loNumber Nvarchar(100)
			
		WHILE @lQuantity > 0
		BEGIN

		print @lQuantity
			EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sAssetManagement.tAssetMaster', 0, 1, 1,@outNextNumber = @lNextNumber output

			EXECUTE sCommon.pPrefixSetupNextNumberGet @rOrgId = @rOrgId, @rPrefixFunctionalityId = 2011,@rStoreLocationId = @rStoreLocationId, @rNextNumber  = @loNumber OUTPUT

			SELECT @lNumber = ISNULL(max(convert(int,Code)),0) FROM sAssetManagement.tAssetMaster WHERE StoreLocationId = @rStoreLocationId
			SET @lNumber = @lNumber + 1

			INSERT INTO sAssetManagement.tAssetMaster
			(
				Id,
				Code,
				Title,
				Specification,
				Accessories,
				LocationId,
				StatusId,
				VendorId,
				GoodsReceiptNumber,
				GoodsReceiptDate,
				IsInstallationRequired,
				CategoryId,
				DepreciationUptoDate,
				IsFullyDepreciated,
				StandardPrice,
				MinStockRequired,
				MaintenancePeriod,
				IsAmc,
				MaintenanceAlertPeriod,
				AmcVendorId,
				UsageStatusId,
				LastServiceCost,
				TotalServiceCost,
				LastDownTime,
				TotalDownTime,
				NextMaintenanceDate,
				ModelNumber,
				IsCritical,
				IsObsolete,
				CreatedUserId,
				CreatedDateTime,
				UpdatedUserId,
				UpdatedDateTime,
				DepartmentID,
				ServiceEntry,
				OrgId,
				StoreLocationId,
			
				IsCheckRequired,
				CheckFrequencyId,	
				CheckList,	
				CheckedLastDate,	
				IsRenewRequired,
				RenewLastDate,
				RenewNextDate,
				RenewRemark,
				RenewCheckList,
				RenewAlertBeforeDays,
				IsMaintenanceRequired,
				OrgGroupId,
				WarrantyDate,
				AssetCode
		
			)
		VALUES
			(
				@lNextNumber,
				@lNumber,
				@lName,
				@lSpecification,
				@lAccessories,
				@lCurrentLocationId,
				@lUsageStatusId,
				0,
				@lGoodsReceiptNumber,
				@lGoodsReceiptDate,
				0,
				@lAssetCategoryId,
				'1900-01-01',
				1,
				0,
				0,
				@lMaitenancePeriod,
				0,
				@lAlertPeriod,
				0,
				@lUsageStatusId,
				@lLastServiceCost,
				@lTotalServiceCost,
				0,
				0,
				--@lNextMaintenanceDate,
				DATEADD(dd, @lMaitenancePeriod, sCommon.fGetDate()),
				@lModelNumber,
				0,
				0,
				@rCreatedUserId,
				sCommon.fGetDate(),
				@rCreatedUserId,
				sCommon.fGetDate(),
				@lCurrentDepartmentId,
				@lServiceEntry,
				@rOrgId,
				0,

				@lIsCheckRequired,
				@lCheckFrequencyId,	
				@lCheckList,	
				@lCheckedLastDate,	
				@lIsRenewRequired,
				@lRenewLastDate,
				@lRenewNextDate,
				@lRenewRemark,
				@lRenewCheckList,
				@lRenewAlertBeforeDays,
				@lIsMaintenance,
				@rOrgGroupId,
				@lWarrantyDate,
				@loNumber
			)

			--Execute sAssetManagement.pImportAssetCustomFieldAdd @rCustomFieldXML, @lNextNumber, @rCreatedUserId, @lCustomUniqueId
			--UPDATE #tempTableCustomField SET AssetId = @lNextNumber WHERE UniqueId = @lCustomUniqueId

			DECLARE @lCount1 int,@lId1 int
			SELECT @lCount1 = COUNT(Id) FROM #tempTableCustomField WHERE UniqueId = @lCustomUniqueId
			SELECT Top 1 @lId1 = Id FROM #tempTableCustomField WHERE UniqueId = @lCustomUniqueId

			WHILE @lId1 <= @lCount1 
			BEGIN
				DECLARE @lField1 nvarchar(200), @lCustomFieldId int, @lFieldData1 nvarchar(200)
				
				Select @lField1 = FieldName from #tempTableCustomField where Id = @lId1

				Select @lCustomFieldId = Id from sAssetManagement.tAssetCustomFieldMaster where FieldTitle = @lField1
				
				Select @lFieldData1 = FieldData From #tempTableCustomField where Id = @lId1
				
				INSERT INTO [sAssetManagement].[tAssetCustomFieldData]
				(
				    
					AssetId,
					AssetCustomFieldId,
					FieldData,
					CreatedUserId,
					CreatedDateTime,
					UpdatedUserId,
					UpdatedDateTime
				)
				Values
				(
					 @lNextNumber
					,@lCustomFieldId
					,@lFieldData1
					,@rCreatedUserId
					,sCommon.fGetDate()
					,@rCreatedUserId
					,sCommon.fGetDate()
				)		
				SET @lId1=@lId1+1
			END

			SET @lNextNumber = null
			SET @lQuantity = @lQuantity - 1
		END

		
			--EXECUTE [sIp].[pStockItemPlanningAdd] 0,@lNextNumber,0,0,0,0,null,null,@rStoreLocationId,@rOrgGroupId
  	  --EXECUTE sProcurement.pStockBatchAdd  @rOrgGroupId,@rStoreLocationId,@lNextNumber,null,null,0,@rUserId ,0 
		SET @lResult = 1
		SET @lCount = @lCount + 1;
		SET @lQuantity = ISNULL(@lQuantity, 1)
	END
	
	Select @lResult AS Result
END
GO
PRINT N'Altering [sCommunication].[pQueryListGet]...';


GO
ALTER PROCEDURE [sCommunication].[pQueryListGet]
	 
	 
	  @rQueryCategoryId int = 0,
	 --@rTitle nvarchar(100),
	 @rOrgGroupBatchId int,
	 --@rOrgId int,
	 @rOrgGroupId int=0,
	 @rId bigint,
	 @rCreatedUserId bigint=0,
	 @rSyncedQueryId bigint = 0,
	 @rStatusId int = 0,
	 @rCreatedFromDate date=NULL,
	 @rCreatedToDate date=NULL, 
	 @rFromResolutionDate date=NULL,
	 @rToResolutionDate date=NULL,
	 @rFromSourceTypeId smallint=0,  
	 @rTitle nvarchar(100)='',  
	 @rNumber smallint=0,
	 @rQueryStatus varchar(25)=NULL ,
	 @rAssignedToEmployeeId bigint=0,
	 @rSourceId bigint=0,
	 @FromPage varchar(50)='',
	 @rAssignedToId smallint = 0,
	 @rUserSourceTypeId int= 0 
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			
BEGIN 
	  BEGIN
			SET @rTitle = sCommon.fSearchStringGet(@rTitle)
	  END
	  DECLARE @lAcademicId bigint,@lStudentId bigint,@lClassId int,@lDivisionId int,@lOrgId int,@lDepartmentId int,@lEmployeeId bigint
	  IF @rUserSourceTypeId   = 95 -- For Employee Login
	  BEGIN
		SELECT @lDepartmentId=EJD.OrganizationDepartmentId,@lOrgId = EM.OrgId,@lEmployeeId = EM.Id FROM sHrm.tEmployeeMaster EM INNER JOIN sHrm.tEmployeeJobDetail EJD
				 ON EJD.EmployeeId = EM.Id WHERE EM.Id=@rSourceId


		SELECT 
			QM.Id AS QueryId,
			QCM.Id AS QueryCategoryId,
			--VQCM.OrgId As OrgId,
			ISNULL(QCM.Title,'') AS QueryCategoryMaster,
			QM.Title,
			QM.Remark,
			QM.CreatedDateTime,
			QM.StatusId,
			ISNULL(sm.Title,'') AS StatusMaster,
			QM.IsAssigneeView,
			QM.IsUserView,
			QM.CreatedUserId AS QueryCreatedUserId,
			ISNULL(QM.SubjectId,0) AS SubjectId,
			ISNULL(SubM.Title,'') AS SubjectName,
			ISNULL(QM.Number,0) AS Number,
			ISNULL(QM.AssignedToEmployeeId,0) AS AssignedToEmployeeId,
			ISNULL(QM.AssignedToRemark,'') AS AssignedToRemark,
			ISNULL(EM.Code,'') AS AssignedToEmployeeCode,
			ISNULL(U.SourceTypeId,0) AS FromSourceTypeId,
			--ISNULL(QM.FromSourceId,0) AS FromSourceId,
			CASE 
			   WHEN ISNULL(U.SourceTypeId,0) = 2003 THEN (SELECT Code from sStudent.tStudentMaster SM where SM.Id=U.SourceId)
			   WHEN ISNULL(U.SourceTypeId,0) = 95 THEN (SELECT Code from sHrm.tEmployeeMaster EM where EM.Id=U.SourceId AND ISNULL(EM.IsOtherUser,0) = 0)
			   ELSE ''
			END AS FromSourceId,
			CASE 
			   WHEN ISNULL(U.SourceTypeId,0) = 2003 THEN (SELECT Code from sStudent.tStudentMaster SM where SM.Id=U.SourceId)
			   WHEN ISNULL(U.SourceTypeId,0) = 95 THEN (SELECT Code from sHrm.tEmployeeMaster EM where EM.Id=U.SourceId AND ISNULL(EM.IsOtherUser,0) = 0)
			   ELSE ''
			END AS FromSourceId,
			CASE 
			   WHEN ISNULL(U.SourceTypeId,0) = 2003 THEN (SELECT 
			                                                        DM.Title
			                                                   FROM 
			                                                        [sStudent].[vStudentAcademic] A 
			                                                         INNER JOIN sSetup.tBatchMaster BM On A.BatchId=BM.Id 
			                                                         INNER JOIN sSetup.tDivisionMaster DM On A.DivisionId=DM.Id 
			                                                   WHERE StudentId=U.SourceId and BM.OrgGroupBatchId=@rOrgGroupBatchId
			                                                   )
               WHEN ISNULL(U.SourceTypeId,0) = 95 THEN (SELECT 
			                                                        DM.Title
			                                                   FROM 
			                                                        sHrm.tEmployeeJobDetail EJD
			                                                         INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id=EJD.OrganizationDepartmentId
			                                                   WHERE EmployeeId=U.SourceId
			                                                   )			                                                   
			  
			   ELSE ''
			END AS Code,
			CASE 
			   WHEN ISNULL(U.SourceTypeId,0) = 2003 THEN (SELECT 
			                                                        U.DisplayTitle
			                                                   )
               WHEN ISNULL(U.SourceTypeId,0) = 95 THEN (SELECT 
			                                                        U.DisplayTitle
			                                                   )			                                                   
			  
			   ELSE ''
			END AS Name,
			ISNULL(QM.TargetResolutionDate,'') AS TargetResolutionDate  ,
			(CASE WHEN QM.StatusId=210 then  U.DisplayTitle ELSE '' END) AS UserName
			  
			
  FROM 
			sCommunication.tQuery QM
		INNER JOIN sCommunication.tQueryCategoryMaster QCM ON QM.QueryCategoryId=QCM.Id
		--INNER JOIN sCommunication.vOrgwiseQueryCategory VQCM ON QM.QueryCategoryId=VQCM.Id
        INNER JOIN sCommon.tStatusMaster SM ON SM.Id=QM.StatusId
        INNER JOIN sSecurity.tUser U ON QM.CreatedUserId = U.Id
        LEFT JOIN sHrm.tEmployeeMaster EM ON QM.AssignedToEmployeeId=EM.Id
        LEFT JOIN sSetup.tSubjectMaster SubM ON SubM.Id = QM.SubjectId
		INNER JOIN 
				(SELECT QCS.QueryCategoryId FROM sCommunication.tQueryCategoryScope QCS
				 WHERE (((QCS.SourceTypeId = 2021 AND QCS.SourceId =@lOrgId) OR
				(QCS.SourceTypeId = 2017 AND QCS.SourceId =@lDepartmentId) OR
				(QCS.SourceTypeId = 95 AND QCS.SourceId =@lEmployeeId )) AND ((QCS.AssigneeToId=3) OR (QCS.AssigneeToId IS NULL) OR (ISNULL(QCS.AssigneeToId,0)=0)))
				 ) D
				ON D.QueryCategoryId= QCM.Id
  WHERE 
			((QCM.Id = @rQueryCategoryId) OR (@rQueryCategoryId = 0))
        AND	(QM.OrgGroupBatchId=@rOrgGroupBatchId) 
        AND ((QM.Id=@rId) OR (@rId=0))
        --AND ((QM.CreatedUserId=@rCreatedUserId) OR (@rCreatedUserId=0))
        AND ( QM.Id > @rSyncedQueryId OR @rSyncedQueryId = 0)
        AND ((QM.StatusId=@rStatusId) OR (@rStatusId=0))
        AND ((convert(date,QM.CreatedDateTime)>=convert(date,@rCreatedFromDate))OR(ISNULL(convert(date,@rCreatedFromDate),'')=''))    
        AND ((convert(date,QM.CreatedDateTime)<=convert(date,@rCreatedToDate))OR(ISNULL(convert(date,@rCreatedToDate),'')=''))
        AND ((convert(date,QM.TargetResolutionDate)>=convert(date,@rFromResolutionDate))OR(ISNULL(convert(date,@rFromResolutionDate),'')=''))    
        AND ((convert(date,QM.TargetResolutionDate)<=convert(date,@rToResolutionDate))OR(ISNULL(convert(date,@rToResolutionDate),'')='')) 
        AND ((QM.FromSourceTypeId=@rFromSourceTypeId) OR (@rFromSourceTypeId=0))
        AND ((QM.Title like '%'+@rTitle+'%') OR (ISNULL(@rTitle,'')=''))
        AND ((QM.Number=@rNumber) OR (@rNumber=0))
        AND ((QM.StatusId=@rStatusId) OR (@rStatusId=0))
		AND ((QCM.OrgGroupId = @rOrgGroupId) OR (@rOrgGroupId=0))
		AND ISNULL(EM.IsOtherUser,0) = 0
		--AND ((ISNULL(VQCM.AssignedToId,1) <> @rAssignedToId) OR (@rAssignedToId = 0))
		AND QCM.AssignedToId IN (1,3) 
        ORDER BY QM.CreatedDateTime DESC

	  END
	  ELSE IF @rUserSourceTypeId   = 2003 -- For Student Login
	  BEGIN
		
		SELECT @lAcademicId = A.Id,@lStudentId = A.StudentId,@lClassId = A.ClassId, @lDivisionId = A.DivisionId, @lOrgId= A.OrgId, @lDepartmentId=CM.DepartmentId
		FROM sStudent.tAcademic A INNER JOIN sSetup.tBatchMaster BM
		ON A.BatchId = BM.Id 
		INNER JOIN sSetup.tClassMaster CM ON CM.Id = A.ClassId
		WHERE StudentId = @rSourceId AND BM.OrgGroupBatchId = @rOrgGroupBatchId

		SELECT 
			QM.Id AS QueryId,
			QCM.Id AS QueryCategoryId,
			--VQCM.OrgId As OrgId,
			ISNULL(QCM.Title,'') AS QueryCategoryMaster,
			QM.Title,
			QM.Remark,
			QM.CreatedDateTime,
			QM.StatusId,
			ISNULL(sm.Title,'') AS StatusMaster,
			QM.IsAssigneeView,
			QM.IsUserView,
			QM.CreatedUserId AS QueryCreatedUserId,
			ISNULL(QM.SubjectId,0) AS SubjectId,
			ISNULL(SubM.Title,'') AS SubjectName,
			ISNULL(QM.Number,0) AS Number,
			ISNULL(QM.AssignedToEmployeeId,0) AS AssignedToEmployeeId,
			ISNULL(QM.AssignedToRemark,'') AS AssignedToRemark,
			ISNULL(EM.Code,'') AS AssignedToEmployeeCode,
			ISNULL(U.SourceTypeId,0) AS FromSourceTypeId,
			--ISNULL(QM.FromSourceId,0) AS FromSourceId,
			CASE 
			   WHEN ISNULL(U.SourceTypeId,0) = 2003 THEN (SELECT Code from sStudent.tStudentMaster SM where SM.Id=U.SourceId)
			   WHEN ISNULL(U.SourceTypeId,0) = 95 THEN (SELECT Code from sHrm.tEmployeeMaster EM where EM.Id=U.SourceId AND ISNULL(EM.IsOtherUser,0) = 0)
			   ELSE ''
			END AS FromSourceId,
			CASE 
			   WHEN ISNULL(U.SourceTypeId,0) = 2003 THEN (SELECT Code from sStudent.tStudentMaster SM where SM.Id=U.SourceId)
			   WHEN ISNULL(U.SourceTypeId,0) = 95 THEN (SELECT Code from sHrm.tEmployeeMaster EM where EM.Id=U.SourceId AND ISNULL(EM.IsOtherUser,0) = 0)
			   ELSE ''
			END AS FromSourceId,
			CASE 
			   WHEN ISNULL(U.SourceTypeId,0) = 2003 THEN (SELECT 
			                                                        DM.Title
			                                                   FROM 
			                                                        [sStudent].[vStudentAcademic] A 
			                                                         INNER JOIN sSetup.tBatchMaster BM On A.BatchId=BM.Id 
			                                                         INNER JOIN sSetup.tDivisionMaster DM On A.DivisionId=DM.Id 
			                                                   WHERE StudentId=U.SourceId and BM.OrgGroupBatchId=@rOrgGroupBatchId
			                                                   )
               WHEN ISNULL(U.SourceTypeId,0) = 95 THEN (SELECT 
			                                                        DM.Title
			                                                   FROM 
			                                                        sHrm.tEmployeeJobDetail EJD
			                                                         INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id=EJD.OrganizationDepartmentId
			                                                   WHERE EmployeeId=U.SourceId
			                                                   )			                                                   
			  
			   ELSE ''
			END AS Code,
			CASE 
			   WHEN ISNULL(U.SourceTypeId,0) = 2003 THEN (SELECT 
			                                                        U.DisplayTitle
			                                                   )
               WHEN ISNULL(U.SourceTypeId,0) = 95 THEN (SELECT 
			                                                        U.DisplayTitle
			                                                   )			                                                   
			  
			   ELSE ''
			END AS Name,
			ISNULL(QM.TargetResolutionDate,'') AS TargetResolutionDate  ,
			(CASE WHEN QM.StatusId=210 then  U.DisplayTitle ELSE '' END) AS UserName
			  
			
  FROM 
			sCommunication.tQuery QM
		INNER JOIN sCommunication.tQueryCategoryMaster QCM ON QM.QueryCategoryId=QCM.Id
		--INNER JOIN sCommunication.vOrgwiseQueryCategory VQCM ON QM.QueryCategoryId=VQCM.Id
        INNER JOIN sCommon.tStatusMaster SM ON SM.Id=QM.StatusId
        INNER JOIN sSecurity.tUser U ON QM.CreatedUserId = U.Id
        LEFT JOIN sHrm.tEmployeeMaster EM ON QM.AssignedToEmployeeId=EM.Id
        LEFT JOIN sSetup.tSubjectMaster SubM ON SubM.Id = QM.SubjectId
		INNER JOIN (SELECT QCS.QueryCategoryId FROM sCommunication.tQueryCategoryScope QCS
            WHERE (((QCS.SourceTypeId = 2021 AND QCS.SourceId =@lOrgId) OR
            (QCS.SourceTypeId = 2017 AND QCS.SourceId =@lDepartmentId) OR
            (QCS.SourceTypeId = 2016 AND QCS.SourceId =@lClassId) OR
            (QCS.SourceTypeId = 2005 AND QCS.SourceId =@lDivisionId) OR
            (QCS.SourceTypeId = 2003 AND QCS.SourceId =@lStudentId) OR
            (QCS.SourceTypeId = 2001 AND QCS.SourceId =@lAcademicId) )
            )AND ((QCS.AssigneeToId=2) OR (QCS.AssigneeToId IS NULL) OR (ISNULL(QCS.AssigneeToId,0)=0))) D
			ON	D.QueryCategoryId= QCM.Id
  WHERE 
			((QCM.Id = @rQueryCategoryId) OR (@rQueryCategoryId = 0))
        AND	(QM.OrgGroupBatchId=@rOrgGroupBatchId) 
        AND ((QM.Id=@rId) OR (@rId=0))
        --AND ((QM.CreatedUserId=@rCreatedUserId) OR (@rCreatedUserId=0))
        AND ( QM.Id > @rSyncedQueryId OR @rSyncedQueryId = 0)
        AND ((QM.StatusId=@rStatusId) OR (@rStatusId=0))
        AND ((convert(date,QM.CreatedDateTime)>=convert(date,@rCreatedFromDate))OR(ISNULL(convert(date,@rCreatedFromDate),'')=''))    
        AND ((convert(date,QM.CreatedDateTime)<=convert(date,@rCreatedToDate))OR(ISNULL(convert(date,@rCreatedToDate),'')=''))
        AND ((convert(date,QM.TargetResolutionDate)>=convert(date,@rFromResolutionDate))OR(ISNULL(convert(date,@rFromResolutionDate),'')=''))    
        AND ((convert(date,QM.TargetResolutionDate)<=convert(date,@rToResolutionDate))OR(ISNULL(convert(date,@rToResolutionDate),'')='')) 
        AND ((QM.FromSourceTypeId=@rFromSourceTypeId) OR (@rFromSourceTypeId=0))
        AND ((QM.Title like '%'+@rTitle+'%') OR (ISNULL(@rTitle,'')=''))
        AND ((QM.Number=@rNumber) OR (@rNumber=0))
        AND ((QM.StatusId=@rStatusId) OR (@rStatusId=0))
		AND ((QCM.OrgGroupId = @rOrgGroupId) OR (@rOrgGroupId=0))
		AND ISNULL(EM.IsOtherUser,0) = 0
		--AND ((ISNULL(VQCM.AssignedToId,1) <> @rAssignedToId) OR (@rAssignedToId = 0))
		AND QCM.AssignedToId IN (1,2) 
        ORDER BY QM.CreatedDateTime DESC

	  END
	  ELSE --For Other Login
	  BEGIN
			SELECT 
			QM.Id AS QueryId,
			QCM.Id AS QueryCategoryId,
			--VQCM.OrgId As OrgId,
			ISNULL(QCM.Title,'') AS QueryCategoryMaster,
			QM.Title,
			QM.Remark,
			QM.CreatedDateTime,
			QM.StatusId,
			ISNULL(sm.Title,'') AS StatusMaster,
			QM.IsAssigneeView,
			QM.IsUserView,
			QM.CreatedUserId AS QueryCreatedUserId,
			ISNULL(QM.SubjectId,0) AS SubjectId,
			ISNULL(SubM.Title,'') AS SubjectName,
			ISNULL(QM.Number,0) AS Number,
			ISNULL(QM.AssignedToEmployeeId,0) AS AssignedToEmployeeId,
			ISNULL(QM.AssignedToRemark,'') AS AssignedToRemark,
			ISNULL(EM.Code,'') AS AssignedToEmployeeCode,
			ISNULL(U.SourceTypeId,0) AS FromSourceTypeId,
			--ISNULL(QM.FromSourceId,0) AS FromSourceId,
			CASE 
			   WHEN ISNULL(U.SourceTypeId,0) = 2003 THEN (SELECT Code from sStudent.tStudentMaster SM where SM.Id=U.SourceId)
			   WHEN ISNULL(U.SourceTypeId,0) = 95 THEN (SELECT Code from sHrm.tEmployeeMaster EM where EM.Id=U.SourceId AND ISNULL(EM.IsOtherUser,0) = 0)
			   ELSE ''
			END AS FromSourceId,
			CASE 
			   WHEN ISNULL(U.SourceTypeId,0) = 2003 THEN (SELECT Code from sStudent.tStudentMaster SM where SM.Id=U.SourceId)
			   WHEN ISNULL(U.SourceTypeId,0) = 95 THEN (SELECT Code from sHrm.tEmployeeMaster EM where EM.Id=U.SourceId AND ISNULL(EM.IsOtherUser,0) = 0)
			   ELSE ''
			END AS FromSourceId,
			CASE 
			   WHEN ISNULL(U.SourceTypeId,0) = 2003 THEN (SELECT 
			                                                        DM.Title
			                                                   FROM 
			                                                        [sStudent].[vStudentAcademic] A 
			                                                         INNER JOIN sSetup.tBatchMaster BM On A.BatchId=BM.Id 
			                                                         INNER JOIN sSetup.tDivisionMaster DM On A.DivisionId=DM.Id 
			                                                   WHERE StudentId=U.SourceId and BM.OrgGroupBatchId=@rOrgGroupBatchId
			                                                   )
               WHEN ISNULL(U.SourceTypeId,0) = 95 THEN (SELECT 
			                                                        DM.Title
			                                                   FROM 
			                                                        sHrm.tEmployeeJobDetail EJD
			                                                         INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id=EJD.OrganizationDepartmentId
			                                                   WHERE EmployeeId=U.SourceId
			                                                   )			                                                   
			  
			   ELSE ''
			END AS Code,
			CASE 
			   WHEN ISNULL(U.SourceTypeId,0) = 2003 THEN (SELECT 
			                                                        U.DisplayTitle
			                                                   )
               WHEN ISNULL(U.SourceTypeId,0) = 95 THEN (SELECT 
			                                                        U.DisplayTitle
			                                                   )			                                                   
			  
			   ELSE ''
			END AS Name,
			ISNULL(QM.TargetResolutionDate,'') AS TargetResolutionDate  ,
			(CASE WHEN QM.StatusId=210 then  U.DisplayTitle ELSE '' END) AS UserName
			  
			
  FROM 
			sCommunication.tQuery QM
		INNER JOIN sCommunication.tQueryCategoryMaster QCM ON QM.QueryCategoryId=QCM.Id
		--INNER JOIN sCommunication.vOrgwiseQueryCategory VQCM ON QM.QueryCategoryId=VQCM.Id
        INNER JOIN sCommon.tStatusMaster SM ON SM.Id=QM.StatusId
        INNER JOIN sSecurity.tUser U ON QM.CreatedUserId = U.Id
        LEFT JOIN sHrm.tEmployeeMaster EM ON QM.AssignedToEmployeeId=EM.Id
        LEFT JOIN sSetup.tSubjectMaster SubM ON SubM.Id = QM.SubjectId
  WHERE 
			((QCM.Id = @rQueryCategoryId) OR (@rQueryCategoryId = 0))
        AND	(QM.OrgGroupBatchId=@rOrgGroupBatchId) 
        AND ((QM.Id=@rId) OR (@rId=0))
        --AND ((QM.CreatedUserId=@rCreatedUserId) OR (@rCreatedUserId=0))
        AND ( QM.Id > @rSyncedQueryId OR @rSyncedQueryId = 0)
        AND ((QM.StatusId=@rStatusId) OR (@rStatusId=0))
        AND ((convert(date,QM.CreatedDateTime)>=convert(date,@rCreatedFromDate))OR(ISNULL(convert(date,@rCreatedFromDate),'')=''))    
        AND ((convert(date,QM.CreatedDateTime)<=convert(date,@rCreatedToDate))OR(ISNULL(convert(date,@rCreatedToDate),'')=''))
        AND ((convert(date,QM.TargetResolutionDate)>=convert(date,@rFromResolutionDate))OR(ISNULL(convert(date,@rFromResolutionDate),'')=''))    
        AND ((convert(date,QM.TargetResolutionDate)<=convert(date,@rToResolutionDate))OR(ISNULL(convert(date,@rToResolutionDate),'')='')) 
        AND ((QM.FromSourceTypeId=@rFromSourceTypeId) OR (@rFromSourceTypeId=0))
        AND ((QM.Title like '%'+@rTitle+'%') OR (ISNULL(@rTitle,'')=''))
        AND ((QM.Number=@rNumber) OR (@rNumber=0))
        AND ((QM.StatusId=@rStatusId) OR (@rStatusId=0))
		AND ((QCM.OrgGroupId = @rOrgGroupId) OR (@rOrgGroupId=0))
		AND ISNULL(EM.IsOtherUser,0) = 0
		--AND ((ISNULL(QCM.AssignedToId,1) <> @rAssignedToId) OR (@rAssignedToId = 0))
        ORDER BY QM.CreatedDateTime DESC
	  END

        
END
GO
PRINT N'Altering [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
		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 [sFee].[pFeeAllocationHistoryGet]...';


GO
 
ALTER PROCEDURE [sFee].[pFeeAllocationHistoryGet]

	@rOrgId int,
	@rBatchId bigint,
	@rSourceId bigint,
	@rUserId bigint=0,
	@rFromDate date=NULL,
	@rToDate date=NULL,
	@rHistoryTypeId tinyint=null

	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

	SELECT 
	   
	  (SM.FirstName + ' '+ SM.MiddleName + ' '+ SM.LastName) AS StudentName
	  ,ISNULL(SM.Code, '') AS StudentCode
	  ,FAH.SourceId
	  ,FM.Code AS FeeName
      ,FAH.VariableAmount
      ,FAH.DiscountAmount
      ,FAH.AdditionalAmount
      ,FAH.NotApplicableAmount
      ,FAH.Remark
      ,FAH.ReferenceTypeId
      ,FAH.ReferenceSourceId
      ,FAH.UserId
	  ,U.DisplayTitle AS UserName
      ,FAH.LogDateTime
      ,FAH.DiscountRemark
      ,FAH.AdditionalRemark
      ,FAH.NotApplicableRemark
	FROM sFee.tFeeAllocationHistory FAH
	INNER JOIN sStudent.tAcademic A ON FAH.SourceId=A.Id
	INNER JOIN sStudent.tStudentMaster SM ON SM.Id=A.StudentId
	LEFT JOIN sFee.tFeeSetup FS ON FS.Id=FAH.FeeSetupId
	INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS.FeeId
	INNER JOIN sSecurity.tUser U ON U.Id=FAH.UserId
  Where 
		((FAH.SourceId=@rSourceId )OR(@rSourceId=0))
		AND ((FAH.UserId=@rUserId) OR (@rUserId=0))
		AND SM.OrgId=@rOrgId
		AND A.BatchId=@rBatchId
		AND ((CAST(FAH.LogDateTime AS DATE) >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
		AND ((CAST(FAH.LogDateTime AS DATE) <= @rToDate) OR (ISNULL(@rToDate,'') = ''))
		AND ((ISNULL(FAH.HistoryTypeId,1) = @rHistoryTypeId) OR (ISNULL(@rHistoryTypeId, 0) = 0))
	ORDER BY FAH.LogDateTime DESC
END
GO
PRINT N'Altering [sFee].[pOldFeewiseImportAdd]...';


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

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

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

	WHILE (@lCount > 0)
	BEGIN
		DECLARE @lAcademicId bigint = NULL
		DECLARE @lStudentId bigint = NULL
		DECLARE @lClassId int = NULL
		DECLARE @lFeeSetupId int = NULL
		DECLARE @lPendingAmount decimal(12,2)
		
		SELECT @lStudentId = StudentId,@lPendingAmount=PendingAmount FROM #TempOldFeeImport WHERE AutoId = @lCount
		SELECT @lAcademicId = Id, @lClassId=ClassId FROM  sStudent.tAcademic SA WHERE StudentId = @lStudentId AND BatchId = @rNewBatchId
		SELECT @lFeeSetupId = Id FROM sFee.tFeeSetup WHERE  ClassId = @lClassId AND AdmissionCategoryId = @rNewAdmissionCategoryId AND BatchId=@rNewBatchId AND FeeId = @rNewFeeId AND ReceiptBookId = @rNewReceiptBookId
		
		IF @lAcademicId IS NOT NULL AND @lFeeSetupId IS NOT NULL AND @lClassId IS NOT NULL
		BEGIN
			-- Insert Fee Optional
			INSERT INTO sFee.tFeeOptional
			   (
			    FeeSetupId,
			    SourceTypeId,
			    SourceId,
			    BatchId
			   )
				VALUES
			   (
				@lFeeSetupId,
				2001,
				@lAcademicId,
				@rNewBatchId
			   )
			 
				-- Insert Fee Allocation
				INSERT INTO sFee.tFeeAllocation
			   (
			    SourceTypeId,
			    SourceId,
			    FeeSetupId,
			    VariableAmount,
			    DiscountAmount,
			    AdditionalAmount,
			    NotApplicableAmount,
			    Remark,
			    ReferenceTypeId,
			    ReferenceSourceId,
			    CreatedUserId,
			    CreatedDateTime,
			    UpdatedUserId,
			    UpdatedDateTime
			   )
				VALUES
			   (
				2001,
				@lAcademicId,
				@lFeeSetupId,
				@lPendingAmount,
				0,
				NULL,
				NULL,
				'Old Year Pending Fee',
				NULL,
				NULL,
				@rCreatedUserId,
				sCommon.fGetDate(),
				NULL,
				NULL
			   )
		END
		 
		SET @lCount = @lCount -1
	END
	 
	DROP TABLE #TempOldFeeImport
	SELECT 1 AS Result
	COMMIT TRANSACTION
END TRY

BEGIN CATCH 
DROP TABLE #TempOldFeeImport
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
END CATCH	
END
GO
PRINT N'Altering [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
	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
	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
	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,'') = ''))
    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
--END
GO
PRINT N'Altering [sFrontOffice].[pStudentGatePassGet]...';


GO
ALTER PROCEDURE [sFrontOffice].[pStudentGatePassGet]
          
           @rId int,
           @rOrgId int=0,
           @rFromGatePassDate datetime='',
           @rToGatePassDate datetime='',
           @rEntryModeStatusId smallint=0,
           @rCode nvarchar(20)='',
           @rIsPrintView bit=0,
           @rOrgGroupId int=0,
           @rUserId bigint= 0,
		   @rClassId int=0,
		   @rDivisionId int=0
AS
SET NOCOUNT ON
BEGIN
		Declare @GatePassConfig nvarchar(20)=''
		SELECT @GatePassConfig =ItemValue From sConfig.tConfigurationSetup WHERE ConfigurationId = 241 AND SourceId = @rOrgGroupId
		
		SELECT  
			SGP.Id,
			vSA.Code,
			vSA.FirstName+' '+vSA.MiddleName+' '+vSA.LastName AS Name,
			VSA.ClassName+' - '+VSA.DivisionName AS Class,
			SGP.AcademicId,
			ISNULL(SGP.RelationshipId,0) AS RelationshipId,
			RM.Title AS Relationship,
			SGP.Relation,
			SGP.VisitorName,
			ISNULL(SGP.VisitorMobile,0) As VisitorMobile,
			SGP.ReasonOfGatePass,
			(CASE  WHEN @rIsPrintView=1 THEN 
				SGP.VisitorPhoto		
			ELSE ISNULL(SGP.VisitorPhoto, CONVERT(VARBINARY(MAX), 0)) END) AS VisitorPhoto,
			--ISNULL(SGP.VisitorPhoto, CONVERT(VARBINARY(MAX), 0)) AS VisitorPhoto,
			ISNULL(SGP.GatePassDate,'') As GatePassDate,
			ISNULL(SGP.ReturnGatePassDate,'') As ReturnGatePassDate,
			ISNULL(SGP.GatePassTime,'') As GatePassTime,
			ISNULL(SGP.ReturnGatePassTime,'') As ReturnGatePassTime,
			ISNULL(SGP.EntryModeStatusId,0) AS EntryModeStatusId,
			ISNULL(SM.Title,'')  AS EntryModeStatus,
			OM.Id AS OrgId,
			OM.OrgLogo,
			OM.DisplayTitle AS Organization,
			(CASE  WHEN @rIsPrintView=1 THEN 
				SI.StudentPhoto		
			ELSE ISNULL(SI.StudentPhoto, CONVERT(VARBINARY(MAX), 0)) END) AS StudentPhoto,
			
			(CASE  WHEN @rIsPrintView=1 THEN 
				SI.FatherPhoto		
			ELSE ISNULL(SI.FatherPhoto, CONVERT(VARBINARY(MAX), 0)) END) AS FatherPhoto,
			
			(CASE  WHEN @rIsPrintView=1 THEN 
				SI.MotherPhoto		
			ELSE ISNULL(SI.MotherPhoto, CONVERT(VARBINARY(MAX), 0)) END) AS MotherPhoto,
			
			(CASE  WHEN @rIsPrintView=1 THEN 
				SI.RelativePhoto		
			ELSE ISNULL(SI.RelativePhoto, CONVERT(VARBINARY(MAX), 0)) END) AS RelativePhoto,
			
			--ISNULL(SI.StudentPhoto, CONVERT(VARBINARY(MAX), 0)) AS StudentPhoto,
			ISNULL(U.DisplayTitle,'') AS UserName,
			vSA.SUId,
			Remark,
			@GatePassConfig AS ConfigValue,
				
			SF.FatherContactNo,
			SF.MotherContactNo,
			SF.RelativeContactNo,
			SF.FatherName,
			SF.MotherName,
			SF.RelativeName,
			ISNULL(SGP.GatePassNo,0)AS GatePassNo
		FROM 
		    sStudent.vStudentAcademic vSA
			INNER JOIN sFrontOffice.tStudentGatePass SGP ON SGP.AcademicId = vSA.AcademicId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=vSA.OrgId
			INNER JOIN sCommon.tRelationshipMaster RM ON RM.Id=SGP.RelationshipId
			INNER JOIN sCommon.tStatusMaster SM ON SM.Id=SGP.EntryModeStatusId			
			INNER JOIN sSecurity.tUserOrganization UO ON UO.OrgId = SGP.OrgId AND UO.UserId = @rUserId
			LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId=vSA.StudentId
			LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId = SI.StudentId
			LEFT JOIN sSecurity.tUser U	ON U.Id=SGP.CreatedUserId
			
		WHERE 
		  ((SGP.Id=@rId) OR (@rId=0))
			AND ((SGP.OrgId=@rOrgId) OR (@rOrgId=0))
			AND ((SGP.GatePassDate>=@rFromGatePassDate) OR (ISNULL(@rFromGatePassDate,'')=''))
			AND ((SGP.GatePassDate<=@rToGatePassDate) OR (ISNULL(@rToGatePassDate,'')=''))
			AND ((SGP.EntryModeStatusId=@rEntryModeStatusId) OR (@rEntryModeStatusId=0))
			AND ((vSA.Code=@rCode) OR (ISNULL(@rCode,'')=''))
			AND (OM.OrgGroupId=@rOrgGroupId)
			AND ((vSA.ClassId=@rClassId) OR (ISNULL(@rClassId,'')=''))
			AND ((vSA.DivisionId=@rDivisionId) OR (ISNULL(@rDivisionId,'')=''))
			--AND vSA.IsActiveBatch=1
			ORDER BY SGP.GatePassDate,SGP.GatePassTime DESC
			
END
GO
PRINT N'Altering [sHrm].[pImportUser]...';


GO
ALTER PROCEDURE [sHrm].[pImportUser]
    
    @rOrgId int,
	@rXmldoc [nvarchar](max),
	@rCreatedUserId bigint 
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

	DECLARE @loXML XML,@lCount int,
			@lUserType nvarchar(100),
			@lEmployeeCode nvarchar(100),
			@lUserName nvarchar(100),
			@lDisplayName nvarchar(100),
			@lPassword nvarchar(500),
			@lRole nvarchar(100),
			@lRoleId bigint
	
	SET @loXML = CAST(@rXmldoc AS XML)
	
	CREATE TABLE #tTable1 (
	Id bigint identity,
	UserType nvarchar(50) collate SQL_Latin1_General_CP1_CI_AS ,
	EmployeeCode nvarchar(100) collate SQL_Latin1_General_CP1_CI_AS ,
	UserName nvarchar(100) collate SQL_Latin1_General_CP1_CI_AS ,
	DisplayName nvarchar(100) collate SQL_Latin1_General_CP1_CI_AS ,
	[Password] nvarchar(500) collate SQL_Latin1_General_CP1_CI_AS ,
	[Role] nvarchar(100) collate SQL_Latin1_General_CP1_CI_AS ,
	RoleId bigint)
	
	INSERT INTO #tTable1(
		UserType,
		EmployeeCode,
		UserName,
		DisplayName, 
		[Password],
		[Role],
		RoleId)      
	SELECT
		 T.c.value('@UserType','nvarchar(50)') AS UserType,
		 T.c.value('@EmployeeCode','nvarchar(100)') AS EmployeeCode,
		 T.c.value('@UserName','nvarchar(100)') AS UserName,
		 T.c.value('@DisplayName','nvarchar(100)') AS DisplayName,
		 T.c.value('@Password','nvarchar(500)') AS [Password],
		 T.c.value('@Role','nvarchar(100)') AS [Role],
		 T.c.value('@RolId','nvarchar(100)') AS RoleId
	FROM @loXML.nodes('/Table/ImportUser')T(c)
  			
BEGIN

	DECLARE @rUserSourceId bigint = NULL, @rUserSourceTypeId bigInt = NULL, @EmployeeId bigint = NULL, @tmp varchar(500),@tmp1 varchar(500)

	SET @tmp = ''
	SET @tmp1 =''
	
	SELECT @tmp = @tmp + T.EmployeeCode  + ', '  from #tTable1 T 
	LEFT JOIN  sHrm.tEmployeeMaster EM ON T.EmployeeCode  = EM.Code 
	AND EM.OrgId = @rOrgId 
	WHERE EM.ID IS NULL AND T.EmployeeCode <> '' AND ISNULL(EM.IsOtherUser,0) = 0 AND upper(T.UserType) = 'EMPLOYEE' 
 
	SELECT @tmp1 = @tmp1 + T.EmployeeCode  + ', '  from #tTable1 T 
	LEFT JOIN  sStudent.tStudentMaster SM ON T.EmployeeCode  = SM.Code 
	AND SM.OrgId = @rOrgId  
	WHERE SM.ID IS NULL AND T.EmployeeCode <> '' AND upper(T.UserType) = 'STUDENT'

	IF @tmp <> ''
	BEGIN
		SELECT -101 AS Result, SUBSTRING(@tmp, 0, LEN(@tmp)) AS ResultDetail
		RETURN
	END

	IF @tmp1 <> ''
	BEGIN
		SELECT -102 AS Result, SUBSTRING(@tmp1, 0, LEN(@tmp1)) AS ResultDetail
		RETURN
	END

	SELECT @lCount =  COUNT(Id) FROM #tTable1
 
	WHILE @lCount > 0 
	BEGIN		
		SELECT         
			@lUserType = UserType ,
			@lEmployeeCode = EmployeeCode,
			@lUserName = UserName,
			@lDisplayName = DisplayName,
			@lPassword = [Password],
			@lRole = [Role],
			@lRoleId = RoleId
		FROM #tTable1 WHERE Id = @lCount    
	     
		IF UPPER(@lUserType) = 'EMPLOYEE'
		BEGIN
		 SELECT @rUserSourceId = Id FROM sHrm.tEmployeeMaster WHERE Code = @lEmployeeCode AND OrgID=@rOrgId AND ISNULL(IsOtherUser,0) = 0
		 SELECT @rUserSourceTypeId = 95
		END

		ELSE IF(UPPER(@lUserType) = 'STUDENT')
		BEGIN
			SELECT @rUserSourceId = Id FROM sStudent.tStudentMaster WHERE Code = @lEmployeeCode AND OrgID=@rOrgId 
			SELECT @rUserSourceTypeId =2003
		END

		ELSE
		BEGIN
			 SELECT @rUserSourceId = 0
			 SELECT @rUserSourceTypeId = 1
		END

		IF EXISTS(SELECT Id FROM sSecurity.tUser WHERE OrgId = @rOrgId AND LoginTitle=@lUserName)							
		BEGIN
			Select -103 As Result, 'User Name Already Exist for Code ' + @lEmployeeCode  As ResultDetail
			return
		END
		IF EXISTS(SELECT Id FROM sSecurity.tUser WHERE OrgId = @rOrgId AND SourceTypeId=@rUserSourceTypeId AND SourceId = @rUserSourceId)							
		BEGIN
			Select -104 As Result, 'User Already Exist for Code ' + @lEmployeeCode As ResultDetail
			return
		END

		--IF EXISTS(SELECT Id FROM sSecurity.tUser WHERE SourceId = @rUserSourceId AND OrgId=@rOrgId AND SourceTypeId=@rUserSourceTypeId AND LoginTitle = @lUserName )
		--BEGIN
		--	UPDATE sSecurity.tUser
		--	SET	
		--		LoginPassword = @lPassword,				
		--		IsObsolete = 0,			
		--		UpdatedUserId = @rCreatedUserId,
		--		UpdatedDateTime = sCommon.fGetDate(),
		--		LoginTitle = @lUserName,
		--		DisplayTitle = @lDisplayName
		--	WHERE 
		--		SourceId = @rUserSourceId AND OrgId=@rOrgId	AND SourceTypeId=@rUserSourceTypeId  AND LoginTitle = @lUserName		
		--END
		--ELSE
		--BEGIN
			DECLARE @lNextNumber BIGINT	
			EXECUTE  sCommon.pTableRowIdGet @rOrgId, 'sSecurity.tUser', 0, 101, 1,@outNextNumber = @lNextNumber output
			INSERT INTO sSecurity.tUser
				(
					Id,		
					DisplayTitle,
					LoginTitle,
					LoginPassword,
					LastLockOutDate,
					NumberOfLogonAttempt,
					IsObsolete,
					CreatedUserId,
					CreatedDateTime,
					UpdatedUserId,
					UpdatedDateTime,
					OrgId,
					SourceId,
					SourceTypeId	
				)
			VALUES
				(
					@lNextNumber,
					@lDisplayName,					
					@lUserName,
					@lPassword,
					sCommon.fGetDate(),
					0,
					0,
					@rCreatedUserId,
					sCommon.fGetDate(),
					@rCreatedUserId,
					sCommon.fGetDate(),
					@rOrgId,
					@rUserSourceId,
					@rUserSourceTypeId
				)
				
			IF NOT EXISTS(Select 1 From [sSecurity].[tUserRole]  WHERE RoleId = @lRoleId AND UserId=@lNextNumber)
			BEGIN
				INSERT INTO 
				[sSecurity].[tUserRole] (RoleId, UserId, IsObsolete, CreatedUserId, CreatedDateTime, UpdatedUserId, UpdatedDateTime, IsPrimary)
				VALUES
				(@lRoleId,@lNextNumber,0,@rCreatedUserId,sCommon.fGetDate(),@rCreatedUserId,sCommon.fGetDate(),1)
			END
		--END
		SET @lCount = @lCount-1
	  END 
	SELECT 1 AS Result, '' AS ResultDetail
 END
END
GO
PRINT N'Altering [sHrm].[pJoiningCertificateGet]...';


GO
ALTER PROCEDURE [sHrm].[pJoiningCertificateGet]  
    
  @rId bigint = 0,  
  @rCode nvarchar(20),  
  @rName nvarchar(200),  
  @rFromNo int,  
  @rToNo int,  
  @rFromDate date,  
  @rToDate date,  
  @rOrgId smallint,  
  --@rBatchId int =0,
  @rIsSearch bit = 1,
  @rDepartmentId int = 0,  
  @rEmployeeId bigint=0
      
 WITH EXECUTE AS CALLER  
AS  
SET NOCOUNT ON  
      
  
BEGIN   
  IF @rIsSearch = 1  
  BEGIN  
   SET @rCode = sCommon.fSearchStringGet(@rCode)  
   SET @rName = sCommon.fSearchStringGet(@rName)  
  END  
   
 SELECT   
   
   CJ.Id,  
   CJ.EmployeeId,  
   EEM.FirstName+' '+EEM.LastName as Name,  
   CJ.Number,  
   CJ.CertificateDate ,  
   CJ.Remark,  
   isnull(EEM.Designation,0) AS Designation,    
   EEM.Code , 
	CJ.PayScale,
	CJ.DateOfJoining,
	CJ.AgreementPeriod, 
	CJ.CertificateRemark,
	CJ.DepartmentId,
	EEM.DateofJoining AS EmployeeDateofJoining  --added
	--EEM.DepartmentName As Department
	--BM.Title As Batch
     
  FROM   
            sHrm.tCertificateJoining CJ  
       INNER JOIN sHrm.vExtEmployeeMaster EEM ON EEM.EmployeeId=CJ.EmployeeId AND EEM.OrgId=@rOrgId   
       --LEFT JOIN sSetup.tBatchMaster BM ON BM.Id = CI.BatchId
  WHERE   
    
 ((CJ.Id = @rId) OR (@rId = 0))  
 --AND ((BM.Id = @rBatchId) OR (@rBatchId = 0)) 
 AND ((EEM.Code like @rCode) OR (ISNULL(@rCode,'') = ''))  
 AND ((EEM.EmployeeName like @rName) OR (ISNULL(@rName,'') = ''))  
 AND ((CJ.Number >= @rFromNo) OR (@rFromNo=0))  
 AND ((CJ.Number <= @rToNo) OR (@rToNo=0))  
 AND ((CJ.CertificateDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))  
 AND ((CJ.CertificateDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))  
 AND ((EEM.DepartmentId = @rDepartmentId) OR (@rDepartmentId = 0) )	
 ORDER BY CJ.Number  DESC
END
GO
PRINT N'Altering [sHrm].[pRptJoiningCertificateGet]...';


GO
ALTER PROCEDURE [sHrm].[pRptJoiningCertificateGet]  
 
  @rEmployeeId [bigint]= 0, 
  @rBuilder1 nvarchar(max)='',  
  @rBuilder2 nvarchar(max)='',    
  @rOrgId smallint,  
  @rCode nvarchar(20)='',  
  @rFromNo int=0,  
  @rToNo int=0,  
  @rFromDate date='',  
  @rToDate date='',  
  @rName nvarchar(20)=''

WITH EXECUTE AS CALLER  
AS  
SET NOCOUNT ON  
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED  
  
BEGIN  
DECLARE @lIsOnPrePrinted bit = 0  
  
DECLARE @lConfigValue nvarchar(50)  
DECLARE @lIsDisplayImageHeader bit=0  
  
SELECT @lConfigValue = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 182 AND SourceTypeId = 1016 AND SourceId = @rOrgId  
   
 IF (@lConfigValue IS NULL) OR (@lConfigValue = 'Default')  
 BEGIN  
 SET @lIsOnPrePrinted = 0  
 SET @lIsDisplayImageHeader = 0  
 END  
 ELSE IF (@lConfigValue = 'Blank')  
 BEGIN  
 SET @lIsOnPrePrinted = 1  
 SET @lIsDisplayImageHeader = 0  
 END  
 ELSE IF (@lConfigValue = 'Image')  
 BEGIN  
 SET @lIsOnPrePrinted = 0  
 SET @lIsDisplayImageHeader = 1  
 END  
   
 SELECT  
   @rBuilder1 AS Builder1,  
   @rBuilder2 AS Builder2,  
   EM.Id AS EmployeeId,
   CJ.Number,
   EM.EmployeeName,
   EM.FirstName,  
   EM.MiddleName,  
   EM.LastName,      
   EM.Code,    
   EM.ShortName,  
   EM.OrgID,  
   EM.DepartmentId,  
   EM.DepartmentName,  
   EM.DesignationId,  
   EM.Designation,  
   EM.EmployeePhoto, 
   EM.DateOfJoining, 
   @lIsOnPrePrinted AS IsOnPrePrinted,  
   @lIsDisplayImageHeader AS IsDisplayImageHeader,  
   OI.CertificateHeaderA4 ,  
   CJ.Remark,  
   ISNULL(CJ.CertificateDate,'') AS CertificateDate,  
   EM.MaritalStatusId,  
   CJ.PayScale,  
   CJ.AgreementPeriod,
   CJ.CertificateRemark,
   OM.Title As OrgTitle,
   CJ.CreatedDateTime As CreatedDateTime,
   U.DisplayTitle As UserDisplayName,
   EDM.Title AS EmployeeDesignation,
   OM.DisplayTitle As ShortTitle,
   DM.Title AS DepartmentName1,
   EM.MobileNumber,
   --EC.PresentStreetOne+'-'+EC.PresentStreetTwo+ '-' +EC.PresentStreetThree AS LocalAddress,
    EC.PresentStreetOne  + CASE WHEN EC.PresentStreetOne = '' OR (EC.PresentStreetTwo = '' AND EC.PresentStreetThree = '') Then '' ELSE '-' END 
   		    + EC.PresentStreetTwo + CASE WHEN EC.PresentStreetTwo = '' OR EC.PresentStreetThree = '' Then '' ELSE '-' END	
			+ EC.PresentStreetThree AS LocalAddress,
   --EC.PresentCity+ '-'+EC.PresentState+'-'+EC.PresentZipCode+'-'+EC.PresentContactNo As LocalAddress1,
	EC.PresentCity  + CASE WHEN EC.PresentCity = '' OR (EC.PresentState = '' AND EC.PresentZipCode = '' AND EC.PresentContactNo = '') Then '' ELSE '-' END 
		+ EC.PresentState + CASE WHEN EC.PresentState = '' OR (EC.PresentZipCode = '' AND EC.PresentContactNo = '') Then '' ELSE '-' END	
		+ EC.PresentZipCode + CASE WHEN EC.PresentZipCode = '' OR EC.PresentContactNo = '' Then '' ELSE '-' END
		+ EC.PresentContactNo AS LocalAddress1,
   ISNULL(EDM1.Title,'Admin') AS UserDesignation,
   --Replace(Replace(RTrim(Ltrim(EC.PresentCity +' '+ EC.PresentState +' '+ EC.PresentZipCode)),'  ',' '),' ','-') AS LocalAddress2
   EC.PresentCity  + CASE WHEN EC.PresentCity = '' OR (EC.PresentState = '' AND EC.PresentZipCode = '') Then '' ELSE '-' END 
   		    + EC.PresentState + CASE WHEN EC.PresentState = '' OR EC.PresentZipCode = '' Then '' ELSE '-' END	
			+ EC.PresentZipCode AS LocalAddress2,
	ISNULL(CJ.DateOfJoining,'') As CertificateDateOfJoining

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


GO
ALTER PROCEDURE [sIp].[pImportStockIem]
	@rOrgId int,
	@rXmldoc [nvarchar](max),
	@rUserId bigint,
	@rStoreLocationId int,
	@rOrgGroupId smallint,
	@rLocationId int
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	DECLARE @lCount INT
	DECLARE @lInterrorCode INT,@intDoc INT,@lCode nvarchar(20),
	@lName nvarchar(100),@lSubGroup nvarchar(100),
	@lStockItemCategory nvarchar(100),@lIssueUOM nvarchar(50),
	@lSubGroupId int,@lStockItemCategoryId int,@lIssuUOMId int,
	@lResult int,@lresultCode nvarchar(100),@lIsBatchWiseTracking bit,
	@lSafetyStock decimal(12,2),@lStandardDose nvarchar(500),@lReminder nvarchar(500),@lStandardPrice decimal(22,6)
	Declare @lbinCode nvarchar(20),@lVendorCode nvarchar(50),@lVendorCategory nvarchar(50),
	@lBinId int,@lVendorId int, @lVendorCategoryId int

	Declare @loXML XML
    SET @loXML = CAST(@rXmldoc AS XML)

	EXECUTE @lInterrorCode = sp_xml_preparedocument @intDoc OUTPUT, @rXmlDoc

	CREATE TABLE #tTable1 
	(
		Id int identity,Code nvarchar(50),Name nvarchar(100),SubGroup nvarchar(100),
		StockItemCategory nvarchar(100),IssueUOM nvarchar(50),SafetyStock decimal(12,2),
		BinCode nvarchar(50),VendorCode nvarchar(50), IsBatchWiseTracking bit ,StandardPrice decimal(22,6)
	)
	INSERT INTO #tTable1
	Select 
		 T.c.value('@Code','nvarchar(20)') AS Code,
            T.c.value('@Name','nvarchar(100)') AS Name,
            T.c.value('@SubGroup','nvarchar(100)') AS SubGroup,
            T.c.value('@StockItemCategory','Nvarchar(100)') AS StockItemCategory,
            T.c.value('@IssueUOM','nvarchar(50)')   AS IssueUOM,
            T.c.value('@SafetyStock','Decimal(12,2)') AS SafetyStock,
            T.c.value('@BinCode','nvarchar(50)') AS BinCode,
            T.c.value('@VendorCode','nvarchar(50)') AS VendorCode,
			T.c.value('@IsBatchWiseTracking','bit') AS IsBatchWiseTracking,
			T.c.value('@StandardPrice','decimal(22,6)') AS StandardPrice
	
	FROM 
            @loXML.nodes('/Table/ImportStockItem')T(c)
	--INSERT INTO #tTable1
	--(
	--	Code,Name,SubGroup,StockItemCategory,IssueUOM,SafetyStock,BinCode,
	--	VendorCode, IsBatchWiseTracking
	--)      
	--SELECT Code,Name,SubGroup,StockItemCategory,IssueUOM,SafetyStock,BinCode,
	--VendorCode, IsBatchWiseTracking
	--FROM OPENXML (@intDoc, '/Table/ImportStockItem', 1)
	--With
	--(   
	--	Code nvarchar(20) '@Code',Name nvarchar(100) '@Name',
	--	SubGroup nvarchar(100) '@SubGroup',
	--	StockItemCategory nvarchar(100) '@StockItemCategory',
	--	IssueUOM nvarchar(50) '@IssueUOM',
	--	SafetyStock decimal(12,2) '@SafetyStock',
	--	BinCode nvarchar(50) '@BinCode',
	--	VendorCode nvarchar(50) '@VendorCode',
	--	--VendorCategory nvarchar(50) '@VendorCategory',
	--	IsBatchWiseTracking  '@IsBatchWiseTracking'
	--)
	EXEC sp_xml_removedocument @intDoc
	SELECT @lCount = COUNT(Id) FROM #tTable1
	PRINT @lCount
	WHILE @lCount > 0 
	BEGIN
		SELECT @lCode = Code,@lName = [ssetup].[fPortalXMLTagsReplaceReverse](Name),@lSubGroup = SubGroup,
		@lStockItemCategory = StockItemCategory,@lIssueUOM = IssueUOM,
		@lSafetyStock=SafetyStock,@lbinCode=BinCode,
		@lVendorCode=VendorCode, @lIsBatchWiseTracking=IsBatchWiseTracking, @lStandardPrice = StandardPrice
		FROM #tTable1 WHERE Id = @lCount
		
		IF NOT EXISTS(SELECT 1 FROM sIp.tStockItemMaster where Code = @lCode AND StoreLocationId = @rStoreLocationId)           
		BEGIN
			SELECT @lSubGroupId = Id From sIp.tItemSubGroupMaster where Title = @lSubGroup
			SELECT @lStockItemCategoryId= Id From sIp.tStockItemCategoryMaster where Title = @lStockItemCategory AND Storelocationid=@rStoreLocationId
			
			Select @lBinId = Id from sIp.tBinMaster where StoreLocationId =@rStoreLocationId And Code = @lBinCode
			Select @lVendorId = Id from sProcurement.tVendorMaster where LocationId= @rStoreLocationId And Code=@lVendorCode
			--Select @lVendorCategoryId=Id from sProcurement.tVendorCategoryMaster Where OrgGroupId =@rOrgGroupId And Code=@lVendorCategory
			
			SELECT @lIssuUOMId= Id From sFinanceCommon.tStockUomMaster where Title = @lIssueUOM AND OrgGroupId=@rOrgGroupId
			
			if  @lBinId is null	
			BEGIN
				Select -1 As Result
				Return
			END

			if @lVendorId is null
			BEGIN
				Select -2 As Result
				Return
			END
			
			if @lIssuUOMId is null
			BEGIN
				Select -11 As Result
				Return
			END

			IF @lSubGroupId IS NULL
			BEGIN
				Select -3 As Result
				Return
			END

			--Select @lIssuUOMId AS IssuUOMId,@lStockItemCategoryId AS StockItemCategoryId,@lSubGroupId AS SubGroupId
			--SET @lResult = -101
			print @lIssuUOMId
			print @lSubGroupId

			IF(@lSubGroupId > 0  AND @lIssuUOMId>0)
			BEGIN
				DECLARE @lNextNumber INT
				EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sIp.tStockItemMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
				  
				INSERT INTO	sIp.tStockItemMaster
				(
					Id,Code,Title,CreatedUserId,CreatedDateTime,UpdatedUserId,
					UpdatedDateTime,StockItemCategoryId,IsBatchWiseTracking,
					IssueStockUomId,ItemSubGroupId,SafetyStock,VendorId,
					IsObsolete,OrgGroupId,TaxGroupId,Remark,IsBlockedForIssue,
					StoreLocationId,LocationId,StandardDose,BinId,Reminder
				)
				VALUES
				(
					@lNextNumber,@lCode,@lName,@rUserId,sCommon.fGetDate(),
					@rUserId,sCommon.fGetDate(),@lStockItemCategoryId,
					@lIsBatchWiseTracking,@lIssuUOMId,@lSubGroupId,
					@lSafetyStock,@lVendorId,0,@rOrgGroupId,null,null,0,
					@rStoreLocationId,@rLocationId,null,@lBinId,@lReminder
				)
				
				
				EXECUTE [sIp].[pStockItemPlanningAdd] 0,@lNextNumber,0,0,0,@lStandardPrice,null,null,@rStoreLocationId,@rOrgGroupId
  				EXECUTE sProcurement.pStockBatchAdd  @rOrgGroupId,@rStoreLocationId,@lNextNumber,null,null,0,@rUserId ,0 
  	
				--EXECUTE	sIp.pStockItemPurchaseUomAdd @rOrgGroupId,@lNextNumber,@rIssueStockUomId,1,0,@rCreatedUserId	
				--EXEC [sIp].[pItemStandardPriceLogAdd] @lNextNumber, @rStandardPrice, @rCreatedUserId,@rOrgGroupId
 
				SET @lResult = 1
				
				Set @lresultCode= @lCode
				 
			END
		END
		  
		ELSE
		BEGIN
			Set @lResult=-101
			Set @lresultCode= @lCode
		END
		SET @lCount = @lCount - 1
	END
	Select @lResult AS Result,@lresultCode AS Code
END
GO
PRINT N'Altering [sLibrary].[pBookMasterGet]...';


GO

ALTER PROCEDURE [sLibrary].[pBookMasterGet]
	 
	 @rId bigint = 0,
	 @rCode nvarchar(200),
	 @rTitle nvarchar(100),
	 @rOrgId int,
	 @rPublisher nvarchar(200),
	 @rSupplier nvarchar(200),
	 @rAuthor nvarchar(200),
	 @rSubject nvarchar(200),
	 @rLanguage nvarchar(200),
	 @rLocation nvarchar(200),
	 @rEdition nvarchar(50),
	 @rPrice decimal=0,
	 @rCurrency nvarchar(100),
	 @rISBNNumber nvarchar(100),
	 @rBookTag nvarchar(200),
	 @rBookCustomTag nvarchar(200),
	 @rBookAgeGroupId int,
	 @rResourceTypeId int,
	 @rStatusId smallint,
	 @rCreatedUserId bigint,
	 @rLibraryId int,
	 @rBookDepartment nvarchar(150),
	 @rShowWithPhotoId int=0,
	 @rBookGroup1Id int=0,
	 @rBookGroup2Id int=0,
	 @rAccession nvarchar(50),
	 @rOrderIndex int=0
	
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
--DECLARE @lpaging
BEGIN 


	  --BEGIN
			--SET @rCode = sCommon.fSearchStringGet(@rCode)
			SET @rTitle = sCommon.fSearchStringGet(@rTitle)
			SET @rPublisher = sCommon.fSearchStringGet(@rPublisher)
			SET @rSupplier = sCommon.fSearchStringGet(@rSupplier)
			SET @rAuthor = sCommon.fSearchStringGet(@rAuthor)
			SET @rSubject = sCommon.fSearchStringGet(@rSubject)
			SET @rLanguage = sCommon.fSearchStringGet(@rLanguage)
			SET @rLocation = sCommon.fSearchStringGet(@rLocation)
			SET @rEdition = sCommon.fSearchStringGet(@rEdition)
			SET @rCurrency = sCommon.fSearchStringGet(@rCurrency)
			SET @rISBNNumber = sCommon.fSearchStringGet(@rISBNNumber)
			SET @rBookTag = sCommon.fSearchStringGet(@rBookTag)
			SET @rBookCustomTag = sCommon.fSearchStringGet(@rBookCustomTag)
			SET @rAccession = sCommon.fSearchStringGet(@rAccession)
		
	  --END
	 declare @quer nvarchar(max)=''
	declare @lId bigint = 0,@lCode nvarchar(200),@lTitle nvarchar(100),@lOrgId int,
	@lPublisher nvarchar(200),@lSupplier nvarchar(200),@lAuthor nvarchar(200),
	@lSubject nvarchar(200),@lLanguage nvarchar(200),@lLocation nvarchar(200),
	@lEdition nvarchar(50),@lPrice decimal=0,@lCurrency nvarchar(100),
	@lISBNNumber nvarchar(100),@lBookTag nvarchar(200),@lBookCustomTag nvarchar(200),
	@lBookAgeGroupId int,@lResourceTypeId int,@lStatusId smallint,@lCreatedUserId bigint,
	@lLibraryId int,@lBookDepartment nvarchar(150),@lBookGroup1Id int,@lBookGroup2Id int,@lAccession nvarchar(50),
	@lOrderIndex int
	select @lId = isnull(@rId,0),@lCode = isnull(@rCode,''),@lTitle = isnull(@rTitle,''),
	@lOrgId = isnull(@rOrgId,0),@lPublisher = isnull(@rPublisher,''),@lSupplier = isnull(@rSupplier,''),
	@lAuthor = isnull(@rAuthor,''),@lSubject = isnull(@rSubject,''),
	@lLanguage = isnull(@rLanguage,''),@lLocation = isnull(@rLocation,''),
	@lEdition = isnull(@rEdition,''),@lPrice = isnull(@rPrice,0),@lCurrency = isnull(@rCurrency,''),
	@lISBNNumber = isnull(@rISBNNumber,''),@lBookTag = isnull(@rBookTag,''),
	@lBookCustomTag = isnull(@rBookCustomTag,''),@lBookAgeGroupId = isnull(@rBookAgeGroupId,0),
	@lResourceTypeId = isnull(@rResourceTypeId,0),@lStatusId = isnull(@rStatusId,0),@lCreatedUserId = isnull(@rCreatedUserId,0),
	@lLibraryId = isnull(@rLibraryId,0),@lBookDepartment = isnull(@rBookDepartment,''),
	@lBookGroup1Id = isnull(@rBookGroup1Id,0),@lBookGroup2Id = isnull(@rBookGroup2Id,0),@lAccession = ISNULL(@rAccession,''),
	@lOrderIndex=ISNULL(@rOrderIndex,0)

	 
	SELECT @quer='SELECT BM.Code,
	BM.Title,
	ISNULL(BM.Publisher,'''')AS Publisher,
	ISNULL(BM.Supplier,'''')AS Supplier,
	ISNULL(BM.Author,'''')AS Author,
	ISNULL(BM.BookSubject,'''') AS BookSubject,
	ISNULL(BM.BookLanguage,'''') AS BookLanguage,
	ISNULL(BM.Location,'''') AS Location,
	ISNULL(BM.Edition,'''')AS Edition,
	ISNULL(BM.ISBNNumber,'''') AS ISBNNumber,
	ISNULL(BM.Price,0) AS Price,
	ISNULL(BM.Currency,'''') AS Currency,
	ISNULL(BM.BookTag,'''')AS BookTag,
	ISNULL(BM.BookCustomTag,'''') AS BookCustomTag,
	ISNULL(BM.BookDepartment,'''') AS BookDepartment,
	ISNULL(BM.ClassNumber,'''') AS ClassNumber,
	ISNULL(BM.BookVolume,1) AS BookVolume,
	ISNULL(BM.NoOfCopies,1) AS NoOfCopies,
	SM.Title AS StatusName,
	BM.Id,
	ISNULL(AGM.Id,0)AS BookAgeGroupId,
	ISNULL(RTM.Id,0) AS ResourceTypeId,
	BM.CreatedUserId,
	ISNULL(U1.DisplayTitle,'''') AS CreatedUserName ,
	BM.CreatedDateTime,
	ISNULL(BM.UpdatedUserId,0) AS UpdatedUserId,
	ISNULL(U2.DisplayTitle,'''') AS UpdatedUserName ,
	ISNULL(BM.UpdatedDateTime,'''') AS UpdatedDateTime,
	BM.LibraryId,
	ISNULL(LM.Title,'''') AS LibraryName,
	SM.Id AS StatusId,
	BM.ClassificationNo,
	BM.AccessionNo,
	ISNUll(BM.NoOfPages,0) AS NoOfPages,
	 ISNULL(BM.PurchaseDate,''0001/01/01'') AS PurchaseDate,
    ISNUll(BM.BookRemark,'''') AS BookRemark,
    ISNULL(BM.BillNumber,'''') AS BillNumber,
    BM.YearOfPublication,
    ISNULL(BM.BookEntryDate,''0001/01/01'') AS BookEntryDate,
    CASE WHEN ' + convert(varchar,@rShowWithPhotoId) + '= 1 Then ISNULL(BM.BookImage, CONVERT(VARBINARY(MAX), 0)) ELSE BM.BookImage END AS BookPicture,
    ISNULL(BM.BookGroup1Id,0) AS BookGroup1Id,
    ISNULL(BM.BookGroup2Id,0) AS BookGroup2Id,
	ISNULL(BM.OrderIndex,0) AS OrderIndex 
	
	
	
    

	FROM 
         sLibrary.tBookMaster BM
         LEFT JOIN sLibrary.tBookAgeGroupMaster AGM ON BM.BookAgeGroupId=AGM.Id
         INNER JOIN sLibrary.tResourceTypeMaster RTM ON BM.ResourceTypeId=RTM.Id
         INNER JOIN sLibrary.tBookLog BL ON BL.ResourceSourceId = BM.Id AND IsCurrentStatus=1
         INNER JOIN sCommon.tStatusMaster SM ON SM.Id=BL.StatusId 
		 INNER JOIN sLibrary.tLibraryMaster LM ON LM.Id = BM.LibraryId
		 INNER JOIN sSecurity.tUser U1 ON U1.Id = BM.CreatedUserId
		 INNER JOIN sSecurity.tUser U2 ON U2.Id = BM.UpdatedUserId
		  
         
         WHERE ((BM.Id = ' + convert(varchar,@lId) + ') OR (' + convert(varchar,@lId) + ' = 0))
	AND ((BM.Code = ''' + @lCode + ''') OR (''' + @lCode + ''' = ''''))
	AND ((BM.Title like N''' + @lTitle + ''') OR (''' + @lTitle + ''' = '''')) 
	AND ((BM.AccessionNo like ''' + @lAccession + ''') OR (''' + @lAccession + ''' = '''')) 
	AND ((BM.Publisher like N''' + @lPublisher + ''') OR (''' + @lPublisher + ''' = '''')) 
	AND ((BM.Supplier like ''' + @lSupplier + ''') OR (''' + @lSupplier + ''' = '''')) 
	AND ((BM.Author like N''' + @lAuthor + ''') OR (''' + @lAuthor + ''' = '''')) 
	AND ((BM.BookSubject like N''' + @lSubject + ''') OR (''' + @lSubject + ''' = ''''))  
	AND ((BM.BookLanguage like N''' + @lLanguage + ''') OR (''' + @lLanguage + ''' = ''''))  
	AND ((BM.Location like ''' + @lLocation + ''') OR (''' + @lLocation + ''' = ''''))  
	AND ((BM.Edition like ''' + @lEdition + ''') OR (''' + @lEdition + ''' = ''''))  
	AND ((BM.ISBNNumber like ''' + @lISBNNumber + ''') OR (''' + @lISBNNumber + ''' = ''''))  
	AND ((BM.BookTag like ''' + @lBookTag + ''') OR ( ''' + @lBookTag + ''' = ''''))
	AND ((BM.BookCustomTag like ''' + @lBookCustomTag + ''') OR (''' + @lBookCustomTag + ''' = ''''))
	AND ((BM.BookAgeGroupId = ' + convert(varchar,@lBookAgeGroupId) + ') OR(' + convert(varchar,@lBookAgeGroupId) + ' = 0))
	AND ((BM.ResourceTypeId = ' + convert(varchar,@lResourceTypeId) + ') OR (' + convert(varchar,@lResourceTypeId) + ' = 0))
	AND ((BM.BookGroup1Id = ' + convert(varchar,@lBookGroup1Id) + ') OR (' + convert(varchar,@lBookGroup1Id) + ' = 0))
	AND ((BM.BookGroup2Id = ' + convert(varchar,@lBookGroup2Id) + ') OR (' + convert(varchar,@lBookGroup2Id) + ' = 0))
	AND ((BM.Price = ' + convert(varchar,@lPrice) + ') OR (' + convert(varchar,@lPrice) + ' = 0))
	AND ((BM.Currency like ''' + @lCurrency + ''') OR (''' + @lCurrency  + ''' = ''''))
	AND ((BL.StatusId = ' + convert(varchar,@lStatusId) + ') OR (' + convert(varchar,@lStatusId) + '=0))
	AND ((BM.BookDepartment like ''' + @lBookDepartment + ''') OR (''' + @lBookDepartment + ''' = ''''))
	AND (BM.LibraryId = ' + convert(varchar,@lLibraryId) +')
	ORDER BY BM.OrderIndex ASC'
	print(@quer);
	exec (@quer)
	

  --FROM 
  --      sLibrary.tBookMaster BM
  --       LEFT JOIN sLibrary.tBookAgeGroupMaster AGM
  --       ON BM.BookAgeGroupId=AGM.Id
  --       INNER JOIN sLibrary.tResourceTypeMaster RTM
  --       ON BM.ResourceTypeId=RTM.Id
  --       INNER JOIN sLibrary.tBookLog BL
  --       ON BL.ResourceSourceId=BM.Id AND IsCurrentStatus=1
  --       INNER JOIN sCommon.tStatusMaster SM
  --       ON SM.Id=BL.StatusId 
        -- WHERE 
  
      --((BM.Id = @rId) OR (@rId = 0))
      --ANd ((BM.Code = @rCode) OR (ISNULL(@rCode,'') = ''))
      -- AND  ((BM.Title like @rTitle) OR (ISNULL(@rTitle,'') = '')) 
      --  AND  ((BM.Publisher like @rPublisher) OR (ISNULL(@rPublisher,'') = '')) 
      --   AND  ((BM.Supplier like @rSupplier) OR (ISNULL(@rSupplier,'') = '')) 
      --    AND  ((BM.Author like @rAuthor) OR (ISNULL(@rAuthor,'') = '')) 
      --     AND  ((BM.BookSubject like @rSubject) OR (ISNULL(@rSubject,'') = ''))  
      --      AND  ((BM.BookLanguage like @rLanguage) OR (ISNULL(@rLanguage,'') = ''))  
      --       AND  ((BM.Location like @rLocation) OR (ISNULL(@rLocation,'') = ''))  
      --        AND  ((BM.Edition like @rEdition) OR (ISNULL(@rEdition,'') = ''))  
      --         AND  ((BM.ISBNNumber like @rISBNNumber) OR (ISNULL(@rISBNNumber,'') = ''))  
      --          AND  ((BM.BookTag like @rBookTag) OR (ISNULL(@rBookTag,'') = ''))
      --           AND  ((BM.BookCustomTag like @rBookCustomTag) OR (ISNULL(@rBookCustomTag,'') = ''))
      --            AND  ((BM.BookAgeGroupId = @rBookAgeGroupId) OR(@rBookAgeGroupId=0))
      --             AND  ((BM.ResourceTypeId = @rResourceTypeId) OR (@rResourceTypeId=0))
      --              AND  ((BM.Price = @rPrice) OR (@rPrice=0))
      --               AND  ((BM.Currency like @rCurrency) OR (ISNULL(@rCurrency,'') = ''))
      --                AND  ((BL.StatusId = @rStatusId) OR (@rStatusId=0))
      --                ANd ((BM.BookDepartment like @rBookDepartment) OR (ISNULL(@rBookDepartment,'') = ''))
						--AND ((BL.OrgId=@rOrgId) OR (@rOrgId=0))
	  --AND BM.LibraryId = @rLibraryId
END
GO
PRINT N'Altering [sLibrary].[pReaderBookLogListGet]...';


GO
ALTER PROCEDURE [sLibrary].[pReaderBookLogListGet]
	 @rReaderSourceTypeId smallint=0,
	 @rReaderSourceId bigint,
	 @rOrgId smallint,
	 @rBatchId int,
	 @rLibraryId int
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 	
If(@rReaderSourceTypeId=2003)
BEGIN
	SELECT 
			BL.Id AS BookLogId,
			BM.Code AS ResourceCode,
			BM.Title AS ResourceName,
			BL.LogDate,
			BL.DueDate,
			IS1.NoOfBookIssuable,
			BL.StatusId,
			BM.Id As BookId
	FROM 
			sLibrary.tBookLog BL
			INNER JOIN sLibrary.tBookMaster BM ON BM.Id=BL.ResourceSourceId
			INNER JOIN sStudent.vStudentLastAcademic SA ON SA.StudentId=BL.ReaderSourceId 
			INNER JOIN sLibrary.tIssueSetting IS1 ON IS1.SourceId=SA.ClassId AND IS1.SourceTypeId=2005 AND IS1.LibraryId=@rLibraryId
	WHERE 
			((BL.ReaderSourceTypeId=@rReaderSourceTypeId) OR (@rReaderSourceTypeId=0))
		AND (BL.ReaderSourceId=@rReaderSourceId)
		AND BL.IsCurrentStatus=1
		AND ((BL.StatusId=522) OR (BL.StatusId=523))
		AND (BL.OrgId=@rOrgId)
		AND (BL.BatchId=@rBatchId)
		--AND  SA.IsActiveBatch = 1
		AND (BL.LibraryId=@rLibraryId)
END
ELSE If(@rReaderSourceTypeId=95)
BEGIN
	SELECT 
			BL.Id AS BookLogId,
			BM.Code AS ResourceCode,
			BM.Title AS ResourceName,
			BL.LogDate,
			BL.DueDate,
			IS1.NoOfBookIssuable,
			BL.StatusId,
			BM.Id As BookId   
	FROM 
			sLibrary.tBookLog BL
			INNER JOIN sLibrary.tBookMaster BM ON BM.Id=BL.ResourceSourceId
			INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id=BL.ReaderSourceId	
			INNER JOIN sHrm.tEmployeeJobDetail EJD ON EM.Id = EJD.EmployeeId
			INNER JOIN sSetup.tDepartmentMaster ODM ON ODM.Id = EJD.OrganizationDepartmentId
			INNER JOIN sLibrary.tIssueSetting IS1 ON IS1.SourceId=ODM.Id AND IS1.SourceTypeId=2004 AND IS1.LibraryId=@rLibraryId
	WHERE 
			((BL.ReaderSourceTypeId=@rReaderSourceTypeId) OR (@rReaderSourceTypeId=0))
		AND (BL.ReaderSourceId=@rReaderSourceId)
		AND BL.IsCurrentStatus=1
		AND ((BL.StatusId=522) OR (BL.StatusId=523))
		AND (BL.OrgId=@rOrgId)
		AND (BL.BatchId=@rBatchId)
		AND (BL.LibraryId=@rLibraryId)
		AND ISNULL(EM.IsOtherUser,0) = 0
END
END
GO
PRINT N'Altering [sSecurity].[pNewTaskAdd]...';


GO
ALTER PROCEDURE [sSecurity].[pNewTaskAdd]
 
	@rOrgGroupId smallint
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	BEGIN TRANSACTION
	
	DECLARE @lItemValue nvarchar(20) = ''
	SELECT 
		@lItemValue = CASE WHEN CS.Id IS NOT NULL THEN ISNULL(CS.ItemValue,'') ELSE ISNULL(CM.ItemValue,'') END 
	FROM 
		sConfig.tConfigurationMaster CM
		LEFT JOIN sConfig.tConfigurationSetup CS ON CM.Id = CS.ConfigurationId
		AND SourceTypeId = 2010 AND SourceId = @rOrgGroupId WHERE CM.Id = 494
    
 
	 
	IF EXISTS (SELECT 1 FROM sSystem.tDatabaseInfo WHERE ISNULL(HostedAS,'') <> 'Portal' AND Id = 1)
	 
	BEGIN
	DELETE OT FROM 
	sSecurity.tOrganizationTask OT
	INNER JOIN sSecurity.tTask T ON OT.TaskId = T.Id
	 WHERE OT.OrgGroupId=@rOrgGroupId AND T.IsClientSpecific = 0
			
	INSERT INTO sSecurity.tOrganizationTask 
	(
		OrgGroupId, TaskId, AvailablePermission
	)
	SELECT  @rOrgGroupId, 
			T.Id,
			T.AvailablePermission
	FROM
			sSecurity.tTask T INNER JOIN sSecurity.tModulePermission P
			ON T.ModuleId = P.ModuleId
	WHERE 
			P.OrgGroupId = @rOrgGroupId
			--AND T.AvailablePermission != 0
			AND T.IsObsolete = 0
			AND T.IsClientSpecific = 0
			
	END
	
	--DELETE FROM sSecurity.tPermission WHERE OrgGroupId=@rOrgGroupId AND RoleId =sCommon.fGetIntIdForOrg(2,@rOrgGroupId)
	 
	
	IF(@lItemValue='True')
	BEGIN
		DELETE FROM sSecurity.tPermission WHERE OrgGroupId=@rOrgGroupId AND RoleId =sCommon.fGetIntIdForOrg(2,@rOrgGroupId)

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

		DELETE P FROM sSecurity.tPermission P INNER JOIN sSecurity.tTask T ON P.TaskId = T.Id WHERE P.OrgGroupId=@rOrgGroupId AND P.RoleId =sCommon.fGetIntIdForOrg(2,@rOrgGroupId)
		AND T.IsClientSpecific = 0

		INSERT INTO 
		sSecurity.tPermission
		(
		TaskId, 
		RoleId, 
		Permission, 
		IsObsolete, 
		CreatedUserId, 
		CreatedDateTime, 
		UpdatedUserId, 
		UpdatedDateTime,
		OrgGroupId
		)
		SELECT  
		TaskId,
		sCommon.fGetIntIdForOrg(2,@rOrgGroupId),
		OT.AvailablePermission,
		0,
		1,
		sCommon.fGetDate(),
		1,
		sCommon.fGetDate(),
		@rOrgGroupId
		FROM 
		sSecurity.tOrganizationTask OT
		INNER JOIN sSecurity.tTask T ON T.Id = OT.TaskId
		WHERE 
		OrgGroupId = @rOrgGroupId
		AND T.IsClientSpecific = 0
	END

	
		 
	
	
	--DELETE FROM sSecurity.tPermission WHERE OrgGroupId = @rOrgGroupId

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

END
GO
PRINT N'Altering [sStudent].[pDigitalFormChangeListGet]...';


GO

 
ALTER PROCEDURE [sStudent].[pDigitalFormChangeListGet]

	  @rId int=0,
	  @rOrgId smallint=0,
	  @rStudentCode nvarchar(100),
	  @rClassId bigint=0,
	  @rDivisionId bigint=0,
	  @rFormStatusId smallint = 0
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
	 
		SELECT 
			(SELECT MAX(AutoId) FROM sStudent.tDigitalFormStudent WHERE DigitalFormId = DF.Id AND AcademicId = DFS.AcademicId) as Id,
			DF.Id as DigitalFormId,
			DF.Code,
			DF.Title,
			SA.StudentId,
			SA.AcademicId,
			SA.Code as StudentCode,
			SA.Name,
			SA.ClassName+' - '+SA.DivisionName AS ClassDivision,
			SA.RollNo,
			SA.Number,
			ISNULL(DFSS.StatusId, 0) AS DigitalFormStatusId,
			ISNULL(SM.Title, '') AS DigitalFormStatus,
			ISNULL(DFSS.ActionDateTime, '') AS FormActionDateTime
		FROM 
			sStudent.tDigitalForm DF
			INNER JOIN (SELECT DigitalFormId,AcademicId FROM sStudent.tDigitalFormStudent GROUP By AcademicId,DigitalFormId) DFS ON DFS.DigitalFormId = DF.Id
			INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId = DFS.AcademicId
			LEFT JOIN [sStudent].[tDigitalFormStudentStatus] DFSS ON DFSS.DigitalFormId = DF.Id AND DFSS.AcademicId = SA.AcademicId
			LEFT JOIN sCommon.tStatusMaster SM ON SM.Id = DFSS.StatusId
		WHERE 
			((DF.OrgId = @rOrgId)OR (@rOrgId=0))
			AND ((DF.Id = @rId) OR (@rId = 0))		
			AND ((SA.Code = @rStudentCode) OR (@rStudentCode=''))
			AND ((SA.ClassId = @rClassId) OR (@rClassId = 0))
			AND ((SA.DivisionId = @rDivisionId) OR (@rDivisionId = 0))
			AND ((SA.OrgId = @rOrgId) OR (@rOrgId = 0))
			AND (DFSS.StatusId = @rFormStatusId OR @rFormStatusId = 0)
	   ORDER BY Id Asc
END
GO
PRINT N'Altering [sTally].[pReceiptPostingGet]...';


GO

ALTER PROCEDURE [sTally].[pReceiptPostingGet]

	 @rOrgGroupBatchId int,
	 @rReceiptBookId int,
	 @rReceiptDate Date,
	 @rToReceiptDate Date,
	 @rPayTypeId int = 0,
	 @rCustomNarration nvarchar(max)='',
	 @rIsCustomNarration bit=0
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
	
	DECLARE @lTallyPostingType nVarchar(100)
	DECLARE @lOrgGroupId INT
	
	SELECT @lOrgGroupId = OrgGroupId from sSetup.tOrgGroupBatchMaster Where Id=@rOrgGroupBatchId
	
	SELECT @lTallyPostingType = CASE WHEN CS.ItemValue IS NULL THEN C.ItemValue ELSE CS.ItemValue END 
		FROM sConfig.tConfigurationMaster C
        INNER JOIN sConfig.tConfigurationLevelMaster CM ON CM.Id = C.ConfigurationLevelId
        LEFT JOIN sConfig.tConfigurationSetup CS ON CS.ConfigurationId = C.Id AND CS.SOURCEID= @lOrgGroupId
        WHERE  C.ItemKey = 'Tally.PostingType'
        
		
        IF @lTallyPostingType = 'FeeHeadWise' 
        BEGIN
			   SELECT	ReceiptDate,
						ISNULL(FHM.Title,'') AS FeeName,
						PM.Title AS PayType,
						Sum(FRD.Amount) AS Amount,
						Case when @rIsCustomNarration=1 then STUFF((SELECT ','  +Replace(replace(
																					Replace(
																					replace(
																					Replace(
																					replace(
																					Replace(
																					replace(
																					Replace(
																					replace(
																					Replace(
																					replace(
																					Replace(
																					replace(
																					Replace(
																					replace(
																					replace(
																					@rCustomNarration,'[Class]',isnull(SM1.ClassName,'')
																					),'[Division]',Isnull(SM1.DivisionName,'')
																					),'[StudentsName]',isnull(SM1.Name,'')
																					), '[RollNumber]',isnull(convert(nvarchar(200),SM1.RollNo),'0')
																					),'[Batch]',isnull(SM1.BatchName,'')
																					), '[ReceiptNumber]', isnull(Convert(nvarchar(100),FR1.ReceiptNumber),'')
																					), '[ReceiptDate]',isnull(Convert(nvarchar(100),FR1.ReceiptDate),'')
																					), '[ReceiptAmount]',isnull(Convert(nvarchar(100),FR1.ReceiptAmount),'')
																					), '[ChequeNo]',isnull(Convert(nvarchar(100),FR1.ChequeNo),'')
																					),'[BankName]',isnull(FR1.BankName,'')
																					),'[FeeName]',isnull(FM1.Title,'')
																					), '[FeeAmount]',isnull(Convert(nvarchar(100),Sum(FRD.Amount)),'0.00')
																					),'[FeeHeadName]',ISNULL(FHM.Title,'')
																					), '[FeeHeadAmount]',isnull(Convert(nvarchar(100),Sum(FRD.Amount)),'0.00')
																					), '[CollectionGroupName]',isNull(CGM1.Title,'')
																					),'[ReceiptFromNumber]',isnull(Convert(nvarchar(10),(Select Min(ReceiptNumber) from sFee.tReceipt where   FR.ReceiptDate =ReceiptDate)),'')
																					), '[ReceiptToNumber]',isnull(Convert(nvarchar(10),(Select Max(ReceiptNumber) from sFee.tReceipt Where FR.ReceiptDate = ReceiptDate)),''))
						from sFee.tReceipt FR1  INNER JOIN sFee.tReceiptDetail FRD1 ON FR1.Id = FRD1.ReceiptId
						INNER JOIN sFee.tFeeSetup FS1 ON FS1.Id = FRD1.FeeSetupId 
						INNER JOIN sStudent.vStudentAcademic SM1 ON SM1.ACademicId = FR1.SourceID AND SM1.OrgGRoupBatchId = FR1.OrgGRoupBatchId 						
						INNER JOIN sFee.tFeeMaster FM1 ON FM1.Id = FS1.FeeId --AND FRD.ReceiptId=FRD1.ReceiptId
						LEFT JOIN sFee.tCollectionGroupMaster CGM1 ON CGM1.Id = FS1.CollectionGroupId
						INNER JOIN sFee.tFeeHeadMaster FHM1 ON FHM1.Id = FM1.FeeHeadId AND FHM1.Id=FHM.Id where  FR.ReceiptDate=FR1.ReceiptDate FOR XML PATH('')),1,1,'') else
						 'Receipt generated for Batch : ' + (Select Title from sSetup.tOrgGroupBatchMaster Where Id= @rOrgGroupBatchId) +
						' Receipt Date : ' +  Convert(nvarchar(10),ReceiptDate) + ' and Receipt Number From ' + Convert(nvarchar(10),(Select Min(ReceiptNumber) from sFee.tReceipt where   FR.ReceiptDate =ReceiptDate)) + ' -  ' + 
						Convert(nvarchar(10),(Select Max(ReceiptNumber) from sFee.tReceipt Where FR.ReceiptDate = ReceiptDate)) end as Narration,						
						FR.PayTypeId AS PayTypeId, 
						FHM.Id AS FeeId,
						0 AS ReceiptId
				FROM sFee.tReceipt FR 
					INNER JOIN sFee.tReceiptDetail FRD ON FR.Id = FRD.ReceiptId
					INNER JOIN sFee.tFeeSetup FS ON FS.Id = FRD.FeeSetupId
					INNER JOIN sFee.tFeeMaster FM ON FM.Id = FS.FeeId
					INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id = FM.FeeHeadId
					INNER JOIN sFinanceCommon.tPayTypeMaster PM ON PM.Id = FR.PayTypeId
					WHERE	FR.ReceiptBookId = @rReceiptBookId 
							AND FR.IsObsolete = 0 
							AND FR.OrgGroupBatchId = @rOrgGroupBatchId
							AND FR.ReceiptDate >= @rReceiptDate AND FR.ReceiptDate <= @rToReceiptDate
							AND (FR.PayTypeId = @rPayTypeId OR @rPayTypeId = 0)
				group by ReceiptDate,FHM.Title,PM.Title,FHM.Id,FR.PayTypeId
				Order By ReceiptDate Desc
			END				
       ELSE IF @lTallyPostingType = 'FeeHeadWiseCustom' 
        BEGIN
			   SELECT	ReceiptDate,
						FR.Id AS FeeName,
						PM.Title AS PayType,
						Sum(FRD.Amount) AS Amount,
						Case when @rIsCustomNarration=1 then  STUFF((SELECT ','  +Replace(replace(
																					Replace(
																					replace(
																					Replace(
																					replace(
																					Replace(
																					replace(
																					Replace(
																					replace(
																					Replace(
																					replace(
																					Replace(
																					replace(
																					Replace(
																					replace(
																					replace(
																					@rCustomNarration,'[Class]',isnull(SM1.ClassName,'')
																					),'[Division]',Isnull(SM1.DivisionName,'')
																					),'[StudentsName]',isnull(SM1.Name,'')
																					), '[RollNumber]',isnull(convert(nvarchar(200),SM1.RollNo),'0')
																					),'[Batch]',isnull(SM1.BatchName,'')
																					), '[ReceiptNumber]', isnull(Convert(nvarchar(100),FR1.ReceiptNumber),'')
																					), '[ReceiptDate]',isnull(Convert(nvarchar(100),FR1.ReceiptDate),'')
																					), '[ReceiptAmount]',isnull(Convert(nvarchar(100),FR1.ReceiptAmount),'')
																					), '[ChequeNo]',isnull(Convert(nvarchar(100),FR1.ChequeNo),'')
																					),'[BankName]',isnull(FR1.BankName,'')
																					),'[FeeName]',isnull(FM1.Title,'')
																					), '[FeeAmount]',isnull(Convert(nvarchar(100),Sum(FRD.Amount)),'0.00')
																					),'[FeeHeadName]',ISNULL(FHM1.Title,'')
																					), '[FeeHeadAmount]',isnull(Convert(nvarchar(100),Sum(FRD.Amount)),'0.00')
																					), '[CollectionGroupName]',isNull(CGM1.Title,'')
																					),'[ReceiptFromNumber]',isnull(Convert(nvarchar(10),(Select Min(ReceiptNumber) from sFee.tReceipt where   FR.ReceiptDate =ReceiptDate)),'')
																					), '[ReceiptToNumber]',isnull(Convert(nvarchar(10),(Select Max(ReceiptNumber) from sFee.tReceipt Where FR.ReceiptDate = ReceiptDate)),''))
						from sFee.tReceipt FR1  INNER JOIN sFee.tReceiptDetail FRD1 ON FR1.Id = FRD1.ReceiptId
						INNER JOIN sFee.tFeeSetup FS1 ON FS1.Id = FRD1.FeeSetupId 
						INNER JOIN sStudent.vStudentAcademic SM1 ON SM1.ACademicId = FR1.SourceID AND SM1.OrgGRoupBatchId = FR1.OrgGRoupBatchId 						
						INNER JOIN sFee.tFeeMaster FM1 ON FM1.Id = FS1.FeeId --AND FRD.ReceiptId=FRD1.ReceiptId
						LEFT JOIN sFee.tCollectionGroupMaster CGM1 ON CGM1.Id = FS1.CollectionGroupId
						INNER JOIN sFee.tFeeHeadMaster FHM1 ON FHM1.Id = FM1.FeeHeadId  where  FR.ReceiptDate=FR1.ReceiptDate AND FR.Id=FR1.Id FOR XML PATH('')),1,1,'') else
						SM.Name + '(' + ClassName + ':' + DivisionName + ') ' + ' # Cheque No. :' + ISNULL(FR.ChequeNo,'') + ' BankName :' + ISNULL(FR.BankName,'') end as Narration,						
						FR.PayTypeId AS PayTypeId, 
						0 AS FeeId,
						FR.Id AS ReceiptId
				FROM sFee.tReceipt FR 
					INNER JOIN sFee.tReceiptDetail FRD ON FR.Id = FRD.ReceiptId
					INNER JOIN sStudent.vStudentAcademic SM ON SM.ACademicId = FR.SourceID AND SM.OrgGRoupBatchId = FR.OrgGRoupBatchId 
					INNER JOIN sFee.tFeeSetup FS ON FS.Id = FRD.FeeSetupId
					INNER JOIN sFee.tFeeMaster FM ON FM.Id = FS.FeeId
					INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id = FM.FeeHeadId
					INNER JOIN sFinanceCommon.tPayTypeMaster PM ON PM.Id = FR.PayTypeId
					INNER JOIN sSetup.tOrganizationMaster OM ON  OM.Id=SM.OrgId
					LEFT JOIN sSetup.tOrgSubGroupMaster OSM ON OSM.id=OM.OrgSubGroupId

					WHERE	FR.ReceiptBookId= @rReceiptBookId 
							AND FR.IsObsolete = 0 
							AND FR.OrgGroupBatchId = @rOrgGroupBatchId
							AND FR.ReceiptDate >= @rReceiptDate AND FR.ReceiptDate <= @rToReceiptDate
							AND (FR.PayTypeId = @rPayTypeId OR @rPayTypeId = 0)
				group by ReceiptDate,PM.Title,FR.PayTypeId,FR.Id,SM.Name + '(' + ClassName + ':' + DivisionName + ') ' + ' # Cheque No. :' + ISNULL(FR.ChequeNo,'') + ' BankName :' + ISNULL(FR.BankName,'')
				Order By FR.Id,ReceiptDate Desc
			END	

       ELSE IF @lTallyPostingType = 'OrgMainGroupWise' 
        BEGIN
			   SELECT	ReceiptDate,
						SM.AcademicId AS FeeName,
						PM.Title AS PayType,
						Sum(FRD.Amount) AS Amount,
						Case when @rIsCustomNarration=1 then  STUFF((SELECT ','  +Replace(replace(
																					Replace(
																					replace(
																					Replace(
																					replace(
																					Replace(
																					replace(
																					Replace(
																					replace(
																					Replace(
																					replace(
																					Replace(
																					replace(
																					Replace(
																					replace(
																					replace(
																					@rCustomNarration,'[Class]',isnull(SM1.ClassName,'')
																					),'[Division]',Isnull(SM1.DivisionName,'')
																					),'[StudentsName]',isnull(SM1.Name,'')
																					), '[RollNumber]',isnull(convert(nvarchar(200),SM1.RollNo),'0')
																					),'[Batch]',isnull(SM1.BatchName,'')
																					), '[ReceiptNumber]', isnull(Convert(nvarchar(100),FR1.ReceiptNumber),'')
																					), '[ReceiptDate]',isnull(Convert(nvarchar(100),FR1.ReceiptDate),'')
																					), '[ReceiptAmount]',isnull(Convert(nvarchar(100),FR1.ReceiptAmount),'')
																					), '[ChequeNo]',isnull(Convert(nvarchar(100),FR1.ChequeNo),'')
																					),'[BankName]',isnull(FR1.BankName,'')
																					),'[FeeName]',isnull(FM1.Title,'')
																					), '[FeeAmount]',isnull(Convert(nvarchar(100),Sum(FRD.Amount)),'0.00')
																					),'[FeeHeadName]',ISNULL(FHM1.Title,'')
																					), '[FeeHeadAmount]',isnull(Convert(nvarchar(100),Sum(FRD.Amount)),'0.00')
																					), '[CollectionGroupName]',isNull(CGM1.Title,'')
																					),'[ReceiptFromNumber]',isnull(Convert(nvarchar(10),FR1.ReceiptNumber),'')
																					), '[ReceiptToNumber]',isnull(Convert(nvarchar(10),FR1.ReceiptNumber),''))
						from sFee.tReceipt FR1  INNER JOIN sFee.tReceiptDetail FRD1 ON FR1.Id = FRD1.ReceiptId
						INNER JOIN sFee.tFeeSetup FS1 ON FS1.Id = FRD1.FeeSetupId 
						INNER JOIN sStudent.vStudentAcademic SM1 ON SM1.ACademicId = FR1.SourceID AND SM1.OrgGRoupBatchId = FR1.OrgGRoupBatchId 						
						INNER JOIN sFee.tFeeMaster FM1 ON FM1.Id = FS1.FeeId --AND FRD.ReceiptId=FRD1.ReceiptId
						LEFT JOIN sFee.tCollectionGroupMaster CGM1 ON CGM1.Id = FS1.CollectionGroupId
						INNER JOIN sFinanceCommon.tPayTypeMaster PM1 ON PM1.Id = FR1.PayTypeId
						INNER JOIN sFee.tFeeHeadMaster FHM1 ON FHM1.Id = FM1.FeeHeadId  where  FR.ReceiptDate=FR1.ReceiptDate AND PM.Title=PM1.Title AND SM.AcademicId=SM1.AcademicId AND  FR.PayTypeId=FR1.PayTypeId FOR XML PATH('')),1,1,'') else
						SM.Name + '(' + ClassName + ':' + DivisionName + ') ' + ' # Cheque No. :' + ISNULL(FR.ChequeNo,'') + ' BankName :' + ISNULL(FR.BankName,'') end as Narration,						
						FR.PayTypeId AS PayTypeId, 
						FR.Id AS FeeId,
						SM.AcademicId AS ReceiptId
				FROM sFee.tReceipt FR 
					INNER JOIN sFee.tReceiptDetail FRD ON FR.Id = FRD.ReceiptId
					INNER JOIN sStudent.vStudentAcademic SM ON SM.ACademicId = FR.SourceID AND SM.OrgGRoupBatchId = FR.OrgGRoupBatchId 
					INNER JOIN sFee.tFeeSetup FS ON FS.Id = FRD.FeeSetupId
					INNER JOIN sFee.tFeeMaster FM ON FM.Id = FS.FeeId
					INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id = FM.FeeHeadId
					INNER JOIN sFinanceCommon.tPayTypeMaster PM ON PM.Id = FR.PayTypeId
					INNER JOIN sSEtup.tOrganizationMaster OM ON OM.OrgSubGRoupID =  @rReceiptBookId AND OM.ID = SM.OrgId					
					WHERE	FR.IsObsolete = 0 
							AND FR.OrgGroupBatchId = @rOrgGroupBatchId
							AND FR.ReceiptDate >= @rReceiptDate AND FR.ReceiptDate <= @rToReceiptDate
							AND FR.PayTypeID = 2
							AND (FR.PayTypeId = @rPayTypeId OR @rPayTypeId = 0)
				group by ReceiptDate,PM.Title,SM.AcademicId ,FR.PayTypeId,FR.Id,SM.Name + '(' + ClassName + ':' + DivisionName + ') ' + ' # Cheque No. :' + ISNULL(FR.ChequeNo,'') + ' BankName :' + ISNULL(FR.BankName,'')
				Order By FR.Id,ReceiptDate Desc
			END	
	ELSE IF @lTallyPostingType = 'ReceiptWise' 
			BEGIN	
				SELECT	ReceiptDate,						
						ISNULL(SLM.LedgerName,'') AS FeeName,
						PM.Title AS PayType,						
						FR.ReceiptAmount AS Amount,
						Case when @rIsCustomNarration=1 then  STUFF((SELECT ','+  +Replace(
																					replace(
																					Replace(
																					replace(
																					Replace(
																					replace(
																					Replace(
																					replace(
																					Replace(
																					replace(
																					Replace(
																					replace(
																					Replace(
																					replace(
																					Replace(
																					replace(
																					replace(
																					@rCustomNarration,'[Class]',isnull(SM1.ClassName,'')
																					),'[Division]',Isnull(SM1.DivisionName,'')
																					),'[StudentsName]',isnull(SM1.Name,'')
																					), '[RollNumber]',isnull(convert(nvarchar(200),SM1.RollNo),'0')
																					),'[Batch]',isnull(SM1.BatchName,'')
																					), '[ReceiptNumber]', isnull(Convert(nvarchar(100),FR1.ReceiptNumber),'')
																					), '[ReceiptDate]',isnull(Convert(nvarchar(100),FR1.ReceiptDate),'')
																					), '[ReceiptAmount]',isnull(Convert(nvarchar(100),FR1.ReceiptAmount),'')
																					), '[ChequeNo]',isnull(Convert(nvarchar(100),FR1.ChequeNo),'')
																					),'[BankName]',isnull(FR1.BankName,'')
																					),'[FeeName]',isnull(FM1.Title,'')
																					), '[FeeAmount]',isnull(Convert(nvarchar(100),Sum(FRD.Amount)),'0.00')
																					),'[FeeHeadName]',ISNULL(FHM1.Title,'')
																					), '[FeeHeadAmount]',isnull(Convert(nvarchar(100),Sum(FRD.Amount)),'0.00')
																					), '[CollectionGroupName]',isNull(CGM1.Title,'')
																					),'[ReceiptFromNumber]',isnull(Convert(nvarchar(10),FR1.ReceiptNumber),'')
																					), '[ReceiptToNumber]',isnull(Convert(nvarchar(10),FR1.ReceiptNumber),''))
						from sFee.tReceipt FR1  INNER JOIN sFee.tReceiptDetail FRD1 ON FR1.Id = FRD1.ReceiptId
						INNER JOIN sFee.tFeeSetup FS1 ON FS1.Id = FRD1.FeeSetupId 
						INNER JOIN sStudent.vStudentAcademic SM1 ON SM1.ACademicId = FR1.SourceID AND SM1.OrgGRoupBatchId = FR1.OrgGRoupBatchId 						
						INNER JOIN sFee.tFeeMaster FM1 ON FM1.Id = FS1.FeeId --AND FRD.ReceiptId=FRD1.ReceiptId
						LEFT JOIN sFee.tCollectionGroupMaster CGM1 ON CGM1.Id = FS1.CollectionGroupId
						INNER JOIN sFinanceCommon.tPayTypeMaster PM1 ON PM1.Id = FR1.PayTypeId
						INNER JOIN sFee.tFeeHeadMaster FHM1 ON FHM1.Id = FM1.FeeHeadId
						LEFT JOIN sTally.tStudentLedgerMapping SLM1 ON SLM1.StudentId = SM1.StudentId AND SLM1.ReceiptBookid = FR1.ReceiptBookId AND SLM.LedgerName=SLM1.LedgerName where  FR1.ReceiptDate=FR.ReceiptDate   AND FR1.PayTypeId=FR.PayTypeId AND  A.StudentId=SM1.StudentId AND FR.ReceiptAmount=FR1.ReceiptAmount FOR XML PATH('')),1,1,'') else
						case When FR.PayTypeId = 1 then
						'Std-' + ClassName + ':' + DivisionName + ' RollNo :' + convert(nvarchar(20),RollNo) + ' ' + BatchName + '-->' +
						STUFF((SELECT ','  + convert(nvarchar(20),isnull(FRD1.Amount,'')) + '-' + isnull(FM1.Title ,'') 
						from sFee.tReceipt FR1  INNER JOIN sFee.tReceiptDetail FRD1 ON FR1.Id = FRD1.ReceiptId
						INNER JOIN sFee.tFeeSetup FS1 ON FS1.Id = FRD1.FeeSetupId 						
						INNER JOIN sFee.tFeeMaster FM1 ON FM1.Id = FS1.FeeId AND FRD.ReceiptId=FRD1.ReceiptId  FOR XML PATH('')),1,1,'') 
						when FR.PayTypeId <> 1 then 
						'Std-' + ClassName + ':' + DivisionName + ' RollNo :' + convert(nvarchar(20),RollNo) + ' ' + BatchName + '-->' +
						STUFF((SELECT ','  + convert(nvarchar(20),isnull(FRD1.Amount,'')) + '-' + isnull(FM1.Title ,'') 
						from sFee.tReceipt FR1  INNER JOIN sFee.tReceiptDetail FRD1 ON FR1.Id = FRD1.ReceiptId
						INNER JOIN sFee.tFeeSetup FS1 ON FS1.Id = FRD1.FeeSetupId 						
						INNER JOIN sFee.tFeeMaster FM1 ON FM1.Id = FS1.FeeId AND FRD.ReceiptId=FRD1.ReceiptId  FOR XML PATH('')),1,1,'') + '  Cheque No. :' + ISNULL(FR.ChequeNo,'') + ' BankName :' + ISNULL(FR.BankName,'')  ENd
						end AS Narration,
						--A.Name+', '+ClassName + '-' + DivisionName+', '+A.OrganizationName+', ('+BatchName+')'
						--AS Narration,					
						FR.PayTypeId AS PayTypeId,									
						A.StudentId AS FeeId,
						FRD.ReceiptId					 
				FROM sFee.tReceipt FR 
					INNER JOIN sFee.tReceiptDetail FRD ON FR.Id = FRD.ReceiptId
					INNER JOIN sFee.tFeeSetup FS ON FS.Id = FRD.FeeSetupId
					INNER JOIN sFee.tFeeMaster FM ON FM.Id = FS.FeeId
					INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id = FM.FeeHeadId
					INNER JOIN sFinanceCommon.tPayTypeMaster PM ON PM.Id = FR.PayTypeId
					INNER JOIN sStudent.vStudentAcademic A ON A.AcademicId = FR.SourceId AND A.OrgGRoupBatchId = FR.OrgGRoupBatchId
					LEFT JOIN sTally.tStudentLedgerMapping SLM ON SLM.StudentId = A.StudentId AND SLM.ReceiptBookid = FR.ReceiptBookId
					WHERE							
							FR.ReceiptBookId = @rReceiptBookId 
							AND FR.IsObsolete = 0 
							AND FR.OrgGroupBatchId = @rOrgGroupBatchId
							AND FR.ReceiptDate >= @rReceiptDate	And FR.ReceiptDate <= @rToReceiptDate
							AND (FR.PayTypeId = @rPayTypeId OR @rPayTypeId = 0)
				group by 
				ReceiptDate,PM.Title,
				SLM.LedgerName,FR.PayTypeId,A.StudentId,
				FRD.ReceiptId,Isnull(FR.ChequeNo,''),ISNull(FR.BankName,''),
				--A.Name+', '+ClassName + '-' + DivisionName+', '+A.OrganizationName+', ('+BatchName+')',
				'Std-' + ClassName + ':' + DivisionName + ' RollNo :' + convert(nvarchar(20),RollNo) + ' ' + BatchName,
				FR.ReceiptAmount			
				Order By ReceiptDate desc
			END		
			
	ELSE IF @lTallyPostingType = 'FeeHeadAndReceiptBookWise' 
			BEGIN	
				SELECT	ReceiptDate,						
						ISNULL(SLM.LedgerName,'') AS FeeName,
						PM.Title AS PayType,						
						FR.ReceiptAmount AS Amount,
						Case when @rIsCustomNarration=1 then STUFF((SELECT ','  +Replace(replace(
																					Replace(
																					replace(
																					Replace(
																					replace(
																					Replace(
																					replace(
																					Replace(
																					replace(
																					Replace(
																					replace(
																					Replace(
																					replace(
																					Replace(
																					replace(
																					replace(
																					@rCustomNarration,'[Class]',isnull(SM1.ClassName,'')
																					),'[Division]',Isnull(SM1.DivisionName,'')
																					),'[StudentsName]',isnull(SM1.Name,'')
																					), '[RollNumber]',isnull(convert(nvarchar(200),SM1.RollNo),'0')
																					),'[Batch]',isnull(SM1.BatchName,'')
																					), '[ReceiptNumber]', isnull(Convert(nvarchar(100),FR1.ReceiptNumber),'')
																					), '[ReceiptDate]',isnull(Convert(nvarchar(100),FR1.ReceiptDate),'')
																					), '[ReceiptAmount]',isnull(Convert(nvarchar(100),FR1.ReceiptAmount),'')
																					), '[ChequeNo]',isnull(Convert(nvarchar(100),FR1.ChequeNo),'')
																					),'[BankName]',isnull(FR1.BankName,'')
																					),'[FeeName]',isnull(FM1.Title,'')
																					), '[FeeAmount]',isnull(Convert(nvarchar(100),Sum(FRD.Amount)),'0.00')
																					),'[FeeHeadName]',ISNULL(FHM1.Title,'')
																					), '[FeeHeadAmount]',isnull(Convert(nvarchar(100),Sum(FRD.Amount)),'0.00')
																					), '[CollectionGroupName]',isNull(CGM1.Title,'')
																					),'[ReceiptFromNumber]',isnull(Convert(nvarchar(10),FR1.ReceiptNumber),'')
																					), '[ReceiptToNumber]',isnull(Convert(nvarchar(10),FR1.ReceiptNumber),''))
						from sFee.tReceipt FR1  INNER JOIN sFee.tReceiptDetail FRD1 ON FR1.Id = FRD1.ReceiptId
						INNER JOIN sFee.tFeeSetup FS1 ON FS1.Id = FRD1.FeeSetupId 
						INNER JOIN sStudent.vStudentAcademic SM1 ON SM1.ACademicId = FR1.SourceID AND SM1.OrgGRoupBatchId = FR1.OrgGRoupBatchId 						
						INNER JOIN sFee.tFeeMaster FM1 ON FM1.Id = FS1.FeeId --AND FRD.ReceiptId=FRD1.ReceiptId
						LEFT JOIN sFee.tCollectionGroupMaster CGM1 ON CGM1.Id = FS1.CollectionGroupId
						INNER JOIN sFinanceCommon.tPayTypeMaster PM1 ON PM1.Id = FR1.PayTypeId
						INNER JOIN sFee.tFeeHeadMaster FHM1 ON FHM1.Id = FM1.FeeHeadId 
						LEFT JOIN sTally.tStudentLedgerMapping SLM1 ON SLM1.StudentId = SM1.StudentId AND SLM1.ReceiptBookid = FR1.ReceiptBookId AND SLM.LedgerName=SLM1.LedgerName where  FR1.ReceiptDate=FR.ReceiptDate AND PM1.Title=PM.Title  AND FR1.PayTypeId=FR.PayTypeId AND A.StudentId=SM1.StudentId AND FR.ReceiptAmount=FR1.ReceiptAmount FOR XML PATH('')),1,1,'') else
						case When FR.PayTypeId = 1 then
						'Receiptno-'  + CONVERT(nvarchar,isnull(FR.ReceiptNumber,'')) + 
						STUFF((SELECT ','  + convert(nvarchar(20),isnull(FM1.title,'')) 
						from sFee.tReceipt FR1  INNER JOIN sFee.tReceiptDetail FRD1 ON FR1.Id = FRD1.ReceiptId And FRD1.ReceiptId = FRD.ReceiptId 
						INNER JOIN sFee.tFeeSetup FS1 ON FS1.Id = FRD1.FeeSetupId 						
						INNER JOIN sFee.tFeeMaster FM1 ON FM1.Id = FS1.FeeId AND FRD.ReceiptId=FRD1.ReceiptId  FOR XML PATH('')),1,1,'') 
						when FR.PayTypeId <> 1 then 
						'Receiptno-'  +  CONVERT(nvarchar,isnull(FR.ReceiptNumber,'')) +
						STUFF((SELECT ','  + convert(nvarchar(20),isnull(FM1.title,'')) 
						from sFee.tReceipt FR1  INNER JOIN sFee.tReceiptDetail FRD1 ON FR1.Id = FRD1.ReceiptId And FRD1.ReceiptId = FRD.ReceiptId 
						INNER JOIN sFee.tFeeSetup FS1 ON FS1.Id = FRD1.FeeSetupId 						
						INNER JOIN sFee.tFeeMaster FM1 ON FM1.Id = FS1.FeeId AND FRD.ReceiptId=FRD1.ReceiptId  FOR XML PATH('')),1,1,'') 
						+ '  Cheque No. :' + ISNULL(FR.ChequeNo,'') + ' BankName :' + ISNULL(FR.BankName,'')  ENd
						end AS Narration,
						FR.PayTypeId AS PayTypeId,									
						A.StudentId AS FeeId,
						FRD.ReceiptId		
									 
				FROM sFee.tReceipt FR 
					INNER JOIN sFee.tReceiptDetail FRD ON FR.Id = FRD.ReceiptId
					INNER JOIN sFee.tFeeSetup FS ON FS.Id = FRD.FeeSetupId
					INNER JOIN sFee.tFeeMaster FM ON FM.Id = FS.FeeId
					INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id = FM.FeeHeadId
					INNER JOIN sFinanceCommon.tPayTypeMaster PM ON PM.Id = FR.PayTypeId
					INNER JOIN sStudent.vStudentAcademic A ON A.AcademicId = FR.SourceId AND A.OrgGRoupBatchId = FR.OrgGRoupBatchId
					LEFT JOIN sTally.tStudentLedgerMapping SLM ON SLM.StudentId = A.StudentId AND SLM.ReceiptBookid = FR.ReceiptBookId
					WHERE							
							FR.ReceiptBookId = @rReceiptBookId 
							AND FR.IsObsolete = 0 
							AND FR.OrgGroupBatchId = @rOrgGroupBatchId
							AND FR.ReceiptDate >= @rReceiptDate	And FR.ReceiptDate <= @rToReceiptDate
							AND (FR.PayTypeId = @rPayTypeId OR @rPayTypeId = 0)
				group by 
				ReceiptDate,PM.Title,
				SLM.LedgerName,FR.PayTypeId,A.StudentId,
				FRD.ReceiptId,
				Isnull(FR.ChequeNo,''),ISNull(FR.BankName,''),
				'Std-' + ClassName + ':' + DivisionName + ' RollNo :' + convert(nvarchar(20),RollNo) + ' ' + BatchName,FR.ReceiptAmount,FR.ReceiptNumber
				--,FHM.Title
				
				Order By ReceiptDate desc	
			END			
			
END
GO
PRINT N'Altering [sTimetable].[pProxySettingAdd]...';


GO
 

ALTER PROCEDURE [sTimetable].[pProxySettingAdd]
		
		@rOrgId int,
		@rId int,
		@rTimeTableId int,
		@rEmployeeId bigint,
		@rDivisionId int,
		@rSubjectId int,
		@rDayId smallint,
		@rLectureNumber smallint,
		@rProxyDate Date,
		@rBatchId int,
		@rTimeTableSchemaId int
		
		
           	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

	 
 
BEGIN 

	 --BEGIN TRY	
	 --BEGIN TRANSACTION 
	 
	 -- add divisionid because in same Lecture they want same teacher to take both division proxy - mantisid - 0024866
	--IF NOT EXISTS(Select 1 FROM sTimetable.tProxySetting Where DayId = @rDayId AND EmployeeId = @rEmployeeId AND LectureNumber=@rLectureNumber AND ProxyDate=@rProxyDate And TimeTableSchemaId=@rTimeTableSchemaId)
	IF NOT EXISTS(Select 1 FROM sTimetable.tProxySetting Where DayId = @rDayId AND EmployeeId = @rEmployeeId AND LectureNumber=@rLectureNumber AND ProxyDate=@rProxyDate And TimeTableSchemaId=@rTimeTableSchemaId AND DivisionId = @rDivisionId)
	 
	BEGIN
	DECLARE @lNextNumber BIGINT
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sTimetable.tProxySetting', 0, 1, 1,@outNextNumber = @lNextNumber output
	  
	  BEGIN
		   INSERT INTO sTimetable.tProxySetting		 
		   (
				[Id],
			    TimeTableId
			   ,[EmployeeId]
			   ,[DivisionId]
			   ,[SubjectId]
			   ,[DayId]
			   ,[LectureNumber]
			   ,ProxyDate
			   ,BatchId
			   ,TimeTableSchemaId
            )		 
			VALUES
			(	
				@lNextNumber,
				@rTimeTableId,
				@rEmployeeId,
				@rDivisionId,
				@rSubjectId,
				@rDayId,
				@rLectureNumber,
				@rProxyDate,
				@rBatchId,
				@rTimeTableSchemaId
			)		
			SELECT @lNextNumber AS Result
    	END
      END
    ELSE
    BEGIN       
      SELECT -101 AS Result
    END
	
	--COMMIT TRANSACTION
	--END TRY
	
	--BEGIN CATCH 
	--	ROLLBACK TRANSACTION
	--	SELECT -1 AS Result
	--END CATCH	
	
	
END 	             
	
		
END
GO
PRINT N'Creating [sAcademic].[pTeacherSubjectDivisionCopyToAnotherEmployee]...';


GO


CREATE PROCEDURE [sAcademic].[pTeacherSubjectDivisionCopyToAnotherEmployee]
	
	@rExistingEmployeeId bigint,
	@rNewEmployeeId bigint
	

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	DELETE FROM sAcademic.tTeacherSubject WHERE EmployeeId = @rNewEmployeeId
	DELETE FROM sAcademic.tTeacherSubjectDivision WHERE EmployeeId = @rNewEmployeeId

	INSERT INTO sAcademic.tTeacherSubject
           (
		   EmployeeId
           ,SubjectId
		   )
     SELECT
		    @rNewEmployeeId,
            SubjectId
	
		   FROM sAcademic.tTeacherSubject WHERE EmployeeId = @rExistingEmployeeId

	INSERT INTO sAcademic.tTeacherSubjectDivision
			   (
				EmployeeId
			   ,SubjectId
			   ,DivisionId
			   ,SubjectCordinatorEmployeeId
			   )

		 Select @rNewEmployeeId,
				SubjectId,
				DivisionId,
				SubjectCordinatorEmployeeId

		 FROM sAcademic.tTeacherSubjectDivision WHERE EmployeeId = @rExistingEmployeeId

		 SELECT 1 AS Result
END
GO
PRINT N'Creating [sFee].[pRptFeeReceiptDoubleA5WithNextPendingFeeGet]...';


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

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

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

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

	SELECT 
			FRD.ReceiptId,
			FR.ReceiptNumber,
			FR.ReceiptDate,
			SA.AcademicId,
			SA.Name AS Name,
			SA.Code,
			SA.RollNo,
			SA.ClassId,
			SA.DivisionId,
			SA.ClassName,
			SA.DivisionName,
			SA.ClassName+' - '+SA.DivisionName AS ClassDivision,
			FM.FeeHeadId,
			FHM.Title AS FeeHead,
			FM.Id AS FeeId,
			FM.Title AS FeeName,
			FRD.Amount AS PaidAmount,
			PTM.Id AS PayTypeId,
			PTM.Title AS PayType,
			CASE WHEN ISNULL(FR.ChequeNo,'') != '' THEN FR.ChequeNo ELSE CONVERT(nvarchar(20),ISNULL(FR.PaymentTransactionId,''))  END AS ChequeNo,
			ISNULL(FR.BankName,'') AS BankName,
			ISNULL(RBM.Address1,'') AS Address1,
			ISNULL(RBM.Address2,'') AS Address2,
			ISNULL(RBM.FullTitle,'') AS FullTitle,
			ISNULL(FR.TotalReceiptAmount,0.00) AS TotalReceiptAmount,
			ISNULL(FR.ReceiptAmount,0.00) AS ReceiptAmount,			
			(CASE WHEN @rOrgGroupId = 0 -- For Single Receipt
					THEN '' 
				  WHEN @rOrgGroupId != 0 -- For Bulk Receipt
					THEN sFinanceCommon.fNumberToWordsWithDecimal(ISNULL(FR.ReceiptAmount,0.00),1,2,@rOrgGroupId)
			END) AS ReceiptAmountInWords,
			ISNULL(FR.DiscountAmount,0.00) AS DiscountAmount,
			FR.Remark,
			(CASE WHEN  ISNULL(FR.PaymentTransactionId,0) > 0 
			  THEN -- Navrachana
				'Online Generated'
				ELSE ISNULL(U.DisplayTitle,'') END) AS UserName,
			OM.OrgLogo,
			RBM.Remark1,
			RBM.Remark2,			 
			ISNULL(RBM.IsOnPrePrinted,0) AS IsOnPrePrinted,
			ISNULL(RBM.IsSupressLogo,0) AS IsSupressLogo,
			ISNULL(RBM.IsDisplaySchoolName,0) AS IsDisplaySchorolName,
			RBM.ReportId,
			OM.Title AS OrganizationName,
			(CASE 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
					AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')
					Order By FS1.StartDate
					FOR XML PATH(''),TYPE).value('text()[1]','nvarchar(max)'),1,2,N'' )    -- Fee Head wise Fee Duration
				  WHEN ISNULL(RBM.IsFeeInvoiceHeadwise,0) = 0
			      THEN
					FS.FeeDuration -- Fee wise Fee Duration
				 ELSE '' END) AS FeeDuration,
			DM.Title AS DepartmentName,
			FM.OrderIndex AS FeeOrderIndex,
			FHM.OrderIndex AS FeeHeadOrderIndex,
			FR.IsObsolete AS IsCancelReceipt,
			@lCurrencyCode AS CurrencyCode,
			@lCurrencyTitle AS CurrencyTitle,
			BM.Title AS Batch,
			FR.ChequeDate AS ChequeDate,
			ISNULL(RBM.IsMonthDetailOnly,0) AS IsMonthDetailOnly,
	        ISNULL(RBM.IsFeeInvoiceHeadwise,0) AS IsFeeInvoiceHeadwise,
	        ISNULL(RBM.GroupTitle,'') AS GroupTitle,
	        ISNULL(RBM.IsSuppressFeeDetail,0) AS IsSuppressFeeDetail,
	        ISNULL(CGM.Title,'') AS CollectionGroupName,
	        ISNULL(FI.InvoiceNumber,0) AS InvoiceNumber,
	        SA.SUID,
	        CASE WHEN RBM.IsOnPrePrinted=1 THEN 2
				 ELSE  ISNULL(RBM.HeaderDisplayId,1)
				END AS HeaderDisplayId,
	        RBM.ReceiptBookHeader,
	        RBM.ServiceTaxPercentage,
	        ISNULL(FR.AmountAfterDiscount,0) AS AmountAfterDiscount,
	        (CASE WHEN FR.CGSTPercentage IS NULL THEN RBM.CGSTPercentage ELSE FR.CGSTPercentage END) AS CGSTPercentage,
	        (CASE WHEN FR.SGSTPercentage IS NULL THEN RBM.SGSTPercentage ELSE FR.SGSTPercentage END) AS SGSTPercentage,
	        ISNULL(FR.CGSTAmount,0) AS CGSTAmount,
	        ISNULL(FR.SGSTAmount,0) AS SGSTAmount,
	        ISNULL(OOM.GSTINNo,'') AS GSTINNo,
	        ISNULL(OOM.HSNSACCode,'') AS HSNSACCode,
	        @lIDConfigValue AS ItemValue,
	        SF.FatherName,
	        SF.MotherName,
	        ISNULL(FA.DiscountAmount,0) AS ExemptionAmount,
			ISNULL(FA.Remark,'') AS ExemptionRemark,
			EI.EmployeeSign,
			ISNULL(SC.PresentCity,'') AS PresentCity,
			(ISNULL((CASE WHEN SC.PresentStreetOne IS NOT NULL AND SC.PresentStreetOne!='' THEN ''+ SC.PresentStreetOne END),'')+
			ISNULL((CASE WHEN SC.PresentStreetTwo IS NOT NULL AND SC.PresentStreetTwo!=''  THEN ', '+ SC.PresentStreetTwo END),'')+
			ISNULL((CASE WHEN SC.PresentStreetThree IS NOT NULL AND SC.PresentStreetThree!=''  THEN ', '+ SC.PresentStreetThree END),'')+
			ISNULL((CASE WHEN SC.PresentCity IS NOT NULL AND SC.PresentCity!=''  THEN ', ' + SC.PresentCity  END),'')+
			ISNULL((CASE WHEN SC.PresentState IS NOT NULL AND SC.PresentState!=''  THEN  ', '+ SC.PresentState END),'')+
			ISNULL((CASE WHEN SC.PresentZipCode IS NOT NULL AND SC.PresentZipCode!=''  THEN  ', '+ SC.PresentZipCode  END),''))
			 AS PresentAdress,
			SC.ParentContactNo,
			ISNULL(RBM.IsDisplayPendingFeeAmount,0) AS IsDisplayPendingFeeAmount,
			CASE WHEN @rOrgGroupId = 1134 OR @rOrgGroupId = 1742 THEN
			(CASE WHEN  ISNULL(RBM.IsDisplayPendingFeeAmount,0) = 0 THEN 0 ELSE ISNULL([sFee].[fPendingFeeAmountReceiptBookwiseGet](FR.SourceId,RBM.Id),0) END)
			ELSE 
			(CASE WHEN  ISNULL(RBM.IsDisplayPendingFeeAmount,0) = 0 THEN 0 ELSE ISNULL([sFee].[fPendingFeeAmountReceiptBookwiseGet](FR.SourceId,0),0) END) END AS PendingFeeAmount,
			SA.FirstName,
			SA.LastName,
			ISNULL([sFee].[fFeeAmountSumGet](FR.SourceId),0) AS FeeAmount,
			ISNULL([sFee].[fFeeReceiptDiscountSumGet](FR.SourceId),0) AS ExemptionAmountSum,
			[sFee].[fTransportBusRouteGet](SA.StudentId,FR.OrgGroupBatchId) AS TransportBusRoute,
			ISNULL(RBM.BankAccountNumber,'') AS BankAccountNumber,
			ISNULL(FHM.Number,0) AS FeeHeadNumber,
			ISNULL(FM.Number,0) AS FeeNumber,
			ISNULL(RBM.DigitalSignature,0x) AS DigitalSignature,
			ISNULL(FR.CancelStatusRemark,'') AS CancelStatusRemark,
			FS.Amount AS FeeSetupAmount,
			FR.CreatedDateTime ,
			ISNULL(FR.PaymentTransactionId,0) As PaymentTransactionId,
			ISNULL(SA.MiddleName, '') AS FatherName,
			CONVERT(char(5),FR.CreatedDateTime,108) AS CreatedTime,
			ISNULL(GM.Title, '') AS Gender,
			NID.PendingAmount AS NextInstallmentAmount,
			NID.CollectionGroupId AS NextInstallmentId,
			NID.StartDate AS NextInstallmentStartDate,
			NID.EndDate AS NextInstallmentEndDate,
			NID.CollectionGroupName AS NextInstallmentName		
	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
			LEFT JOIN sCommon.tGenderMaster GM ON GM.Id = SA.GenderId
			LEFT JOIN (SELECT * FROM [sFee].[fNextInstallmentDetailsGet](@rReceiptBookId, @rReceiptId)) NID ON NID.SourceId = FR.SourceId AND NID.SourceTypeId = FR.SourcetypeId
	WHERE 
			((FR.Id=@rReceiptId) OR (@rReceiptId = 0))
			AND ((RBM.OrgGroupId = @rOrgGroupId) OR (@rOrgGroupId = 0))
			AND ((FR.ReceiptBookId = @rReceiptBookId) OR (@rReceiptBookId = 0))
			AND ((FR.ReceiptNumber >= @rFromReceiptNo) OR (@rFromReceiptNo = 0))
			AND ((FR.ReceiptNumber <= @rToReceiptNo) OR (@rToReceiptNo = 0))
			AND ((FR.BatchId = @rBatchId) OR (@rBatchId = 0))
			AND ((BM.OrgId = @rOrgId) OR (@rOrgId = 0))
			AND ((FR.ReceiptDate = @rReceiptDate) OR (ISNULL(@rReceiptDate,'') = ''))
			AND ((SA.ClassId = @rClassId) OR (@rClassId = 0))
			AND ((SA.DivisionId = @rDivisionId) OR (@rDivisionId = 0))
			AND (ISNULL(SA.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')			
			AND ((ISNULL(FR.ReceiptPrintGroupId,'')=@rReceiptPrintGroupId) OR (ISNULL(@rReceiptPrintGroupId,'') = ''))
    ORDER BY 
            FS.StartDate,FHM.OrderIndex,FM.OrderIndex ASC 
END

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


GO



CREATE PROCEDURE [sSecurity].[pCloneUserAccessAdd]
	
	@rUserId bigint,
	@rCloneUserId bigint
	
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	
BEGIN 
	BEGIN TRY
	
	 BEGIN TRANSACTION	
	 
	 DELETE FROM sSecurity.tUserOrganization WHERE UserId=@rCloneUserId 
	 --AND OrgId=@rOrgId
	 DELETE FROM sSecurity.tUserAccess WHERE UserId=@rCloneUserId

	   INSERT INTO sSecurity.tUserOrganization
		(
			UserId,
			OrgId
		)
		SELECT
		@rCloneUserId,
        OrgId
	
		FROM sSecurity.tUserOrganization UO WHERE UserId = @rUserId

		INSERT INTO sSecurity.tUserAccess
		(
			SourceTypeId,
			SourceId,
			UserId
		)
		SELECT
		SourceTypeId,
		SourceId,
		@rCloneUserId
      
		FROM sSecurity.tUserAccess WHERE UserId = @rUserId 
	
	SELECT 1 AS Result
	
	COMMIT TRANSACTION
	
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH
END
GO


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

Update sAdmission.tAdmissionForm Set 
AdmissionDate = Cast(CreatedDatetime as date) 
where AdmissionDate is  null

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

GO
ALTER TABLE [sAcademic].[tLessonPlan]
    ADD [Remark] NVARCHAR (MAX) NULL;


GO

GO
PRINT N'Altering [sConfig].[fDisplayFieldLessionGet]...';


GO
ALTER FUNCTION [sConfig].[fDisplayFieldLessionGet](@rOrgId int)
RETURNS  @List TABLE (
		 IsObjective bit,
		 IsSummary bit,
		 IsLearningExperience bit,
		 IsEssentialMaterial bit,
		 IsToolsTechniques bit,
		 IsIndicativeHomework bit,
		 IsAssessmentQuestion bit,
		 IsTeacherExample bit,
		 IsGuidedPractice bit,
		 IsIndependentPractice bit,
		 IsSubTopicSelect bit,
		 IsSubTopicText bit,
		 IsSession bit,
		 IsTrainingMethod bit,
		 IsPeriodCount bit,
		 OrgId smallint,
		 IsRemark bit,
		 IsAttachment bit
		 
		 
)  WITH EXECUTE AS CALLER
AS 
BEGIN

    declare @rIsObjective bit 
	declare @rIsSummary bit 
    declare @rIsLearningExperience bit
    declare @rIsEssentialMaterial bit 
    declare @rIsToolsTechniques bit
    declare @rIsIndicativeHomework bit 
    declare @rIsAssessmentQuestion bit 
    declare @rIsTeacherExample bit 
    declare @rIsGuidedPractice bit 
    declare @rIsIndependentPractice bit
    declare @rIsSubTopicSelect bit
    declare @rIsSubTopicText bit
	declare @rIsSession bit
	declare @rIsTrainingMethod bit
	declare @rIsPeriodCount bit
	declare @rIsRemark bit
	declare @rIsAttachment bit
   
	select @rIsObjective=DisplayFieldId FROM sConfig.tDisplayFieldOrg where orgId = @rOrgId and DisplayFieldId = 201
	select @rIsSummary=DisplayFieldId FROM sConfig.tDisplayFieldOrg where orgId = @rOrgId and DisplayFieldId = 203
	select @rIsLearningExperience =DisplayFieldId FROM sConfig.tDisplayFieldOrg where orgId = @rOrgId and DisplayFieldId = 202
	select @rIsEssentialMaterial=DisplayFieldId FROM sConfig.tDisplayFieldOrg where orgId = @rOrgId and DisplayFieldId = 204
	select @rIsToolsTechniques=DisplayFieldId FROM sConfig.tDisplayFieldOrg where orgId = @rOrgId and DisplayFieldId = 205
	select @rIsIndicativeHomework=DisplayFieldId FROM sConfig.tDisplayFieldOrg where orgId = @rOrgId and DisplayFieldId = 206
	select @rIsAssessmentQuestion=DisplayFieldId FROM sConfig.tDisplayFieldOrg where orgId = @rOrgId and DisplayFieldId = 207
	select @rIsTeacherExample=DisplayFieldId FROM sConfig.tDisplayFieldOrg where orgId = @rOrgId and DisplayFieldId = 208
	select @rIsGuidedPractice=DisplayFieldId FROM sConfig.tDisplayFieldOrg where orgId = @rOrgId and DisplayFieldId = 209
	select @rIsIndependentPractice=DisplayFieldId  FROM sConfig.tDisplayFieldOrg where orgId = @rOrgId and DisplayFieldId = 210
	select @rIsSubTopicSelect=DisplayFieldId  FROM sConfig.tDisplayFieldOrg where orgId = @rOrgId and DisplayFieldId = 211
	select @rIsSubTopicText=DisplayFieldId  FROM sConfig.tDisplayFieldOrg where orgId = @rOrgId and DisplayFieldId = 212
	select @rIsSession=DisplayFieldId  FROM sConfig.tDisplayFieldOrg where orgId = @rOrgId and DisplayFieldId = 1219
	select @rIsTrainingMethod=DisplayFieldId  FROM sConfig.tDisplayFieldOrg where orgId = @rOrgId and DisplayFieldId = 1220
	select @rIsPeriodCount=DisplayFieldId  FROM sConfig.tDisplayFieldOrg where orgId = @rOrgId and DisplayFieldId = 1221
	select @rIsRemark = DisplayFieldId  FROM sConfig.tDisplayFieldOrg where orgId = @rOrgId and DisplayFieldId = 1223
	select @rIsAttachment = DisplayFieldId  FROM sConfig.tDisplayFieldOrg where orgId = @rOrgId and DisplayFieldId = 1224
	 	
	INSERT INTO @List 
	SELECT 
		(CASE WHEN @rIsObjective Is Null THEN  0 ELSE 1 END) AS IsObjective,
		(CASE WHEN @rIsSummary Is Null THEN 0 ELSE 1 END)AS IsSummary,
		(CASE WHEN @rIsLearningExperience Is Null THEN 0 ELSE 1 END)AS IsLearningExperience,
		(CASE WHEN @rIsEssentialMaterial Is Null THEN 0  ELSE 1 END)AS IsEssentialMaterial,
		(CASE WHEN @rIsToolsTechniques Is Null THEN 0  ELSE 1 END)AS IsToolsTechniques,
		(CASE WHEN @rIsIndicativeHomework Is Null THEN 0  ELSE 1 END)AS IsIndicativeHomework,
		(CASE WHEN @rIsAssessmentQuestion Is Null THEN 0  ELSE 1 END)AS IsAssessmentQuestion ,
		(CASE WHEN @rIsTeacherExample Is Null THEN 0 ELSE  1 END)AS  IsTeacherExample,
		(CASE WHEN @rIsGuidedPractice Is Null THEN 0  ELSE 1 END)AS IsGuidedPractice,
		(CASE WHEN @rIsIndependentPractice Is Null THEN 0 ELSE  1 END)AS IsIndependentPractice,
		(CASE WHEN @rIsSubTopicSelect Is Null THEN 0 ELSE  1 END)AS IsSubTopicSelect,
		(CASE WHEN @rIsSubTopicText Is Null THEN 0 ELSE  1 END)AS IsSubTopicText,
		(CASE WHEN @rIsSession Is Null THEN 0 ELSE  1 END)AS IsSession,
		(CASE WHEN @rIsTrainingMethod Is Null THEN 0 ELSE  1 END)AS IsTrainingMethod,
		(CASE WHEN @rIsPeriodCount Is Null THEN 0 ELSE  1 END)AS IsPeriodCount,
		@rOrgId AS OrgId,
		(CASE WHEN @rIsRemark Is Null THEN 0 ELSE  1 END)AS IsRemark,		  
		(CASE WHEN @rIsAttachment Is Null THEN 0 ELSE  1 END)AS IsAttachment
    RETURN  
    
END
GO




GO
PRINT N'Altering [sAcademic].[pClassworkStudentGet]...';


GO

 
ALTER PROCEDURE [sAcademic].[pClassworkStudentGet]

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

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

	DECLARE @lDivisionId int
	SELECT @lDivisionId = DivisionId FROM sStudent.tAcademic WHERE StudentId = @rStudentId AND BatchId = @rBatchId

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

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


GO
ALTER PROCEDURE [sAcademic].[pGetLessonPlanApi]

	 @rAcademicId bigint,
	 @rBatchId int,
	 @rDivisionId int,
	 @rSubjectId int,
	 @rFromDate datetime='',
     @rToDate datetime='',
	 @rIsCompleted int = 0

	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
    --for IsCompleted false
	IF (@rIsCompleted = 2)
	BEGIN
	 SET @rIsCompleted = 0
	END
	--for IsCompleted true
	ELSE IF(@rIsCompleted = 1)
	BEGIN
		SET @rIsCompleted = 1 
	END
	--for IsCompleted All
	ELSE
	BEGIN
	SET @rIsCompleted = 2
	END

	--Select @rIsCompleted
	SELECT 
		TM.Title AS TopicName,
		LP.NoOfPeriodRequired,
		LP.Objective,
		LP.IndicativeHomework,
		LP.Summary,
		LP.StartDate,
		LP.EndDate,
		--LP.IsCompleted,			
		CASE WHEN (LP.IsCompleted = 'True') THEN  'Completed' ELSE 'InCompleted' END AS IsCompleted,
		LP.LearningExperience,
		LP.ToolsAndTechniques,
		LP.EssentialMaterial,
		LP.AssessmentQuestion,
		LP.TeacherExample,
		LP.GuidedPractice,
		LP.IndependentPractice,
		LP.SubTopic,
		Em.FirstName+' '+EM.LastName AS TeacherName,
		LP.IsCompleted ,
		LP.Session ,
		LP.TrainingMethod ,
		LP.PeriodCount,
		SM.Title AS SubjectName,
		LP.Id as LessonPlanId,
		LP.Remark
	FROM 
		--sAcademic.tLessonPlan LP
		--INNER JOIN  sAcademic.tTopicMaster TM ON TM.Id = LP.TopicId
		--INNER JOIN sSetup.tSubjectMaster SM ON SM.Id = @rSubjectId
		--INNER JOIN sStudent.tAcademic AM ON AM.BatchId = @rBatchId AND AM.DivisionId = @rDivisionId
		--Left Join  sHrm.tEmployeeMaster EM ON Em.Id=Lp.EmployeeId
			sAcademic.tLessonPlan LP
		INNER JOIN  sAcademic.tTopicMaster TM ON TM.Id = LP.TopicId
		INNER JOIN sSetup.tSubjectMaster SM ON SM.Id = TM.SubjectId
		INNER JOIN sStudent.tAcademic AM ON AM.BatchId = LP.BatchId AND AM.DivisionId = LP.DivisionId
		Left Join  sHrm.tEmployeeMaster EM ON Em.Id=Lp.EmployeeId
		
	WHERE 
		((LP.DivisionId = @rDivisionId)  OR (@rDivisionId = 0))
		AND ((LP.BatchId = @rBatchId) OR (@rBatchId = 0))
		--AND ((SM.Id = @rSubjectId) OR (SM.Id = 0))
		AND ((TM.SubjectId = @rSubjectId) OR (@rSubjectId = 0))
		AND AM.Id = @rAcademicId
		--AND (LP.StartDate >= @rFromDate OR ISNULL(@rFromDate,'')='')
		 --   AND (LP.StartDate <= @rToDate OR ISNULL(@rToDate,'')='')
		AND ((LP.StartDate >= @rFromDate OR ISNULL(@rFromDate,'')='' )AND (LP.StartDate <= @rToDate OR ISNULL(@rToDate,'')='')
		OR (LP.EndDate >= @rFromDate OR ISNULL(@rFromDate,'')='' )AND (LP.EndDate <= @rToDate OR ISNULL(@rToDate,'')='')
		)
		AND ((LP.IsCompleted = @rIsCompleted) OR (@rIsCompleted = 2))
		
	ORDER BY SM.Id
	
END
GO
PRINT N'Altering [sAcademic].[pLessonPlanAdd]...';


GO

ALTER PROCEDURE [sAcademic].[pLessonPlanAdd]
	 
        @rId bigint=0,
        @rTopicId int,
        @rDivisionId int, 
        @rNoOfPeriodRequired smallint,
        @rObjective nvarchar(1000),
        @rIndicativeHomework nvarchar(200),
        @rSummary nvarchar(200),
        @rStartDate date='',
        @rEndDate date='',
        @rIsCompleted bit=0,
        @rEmployeeId bigint,
        @rBatchId int,
        @rCreatedUserId bigint,
        @rOrgId smallint,
        @rLearningExperience nvarchar(1000)='',
        @rToolsAndTechniques nvarchar(500)='',
        @rEssentialMaterial nvarchar(500)='',
		@rAssessmentQuestion	nvarchar(1000)='',	
		@rTeacherExample	nvarchar(1000)='',
		@rGuidedPractice	nvarchar(1000)='',
		@rIndependentPractice	nvarchar(1000)	='',
		@rSubTopic nvarchar(1000)='' ,
	    @rSession nvarchar(100)='' ,
		@rTrainingMethod  nvarchar(100)='' ,
		@rPeriodCount int =0,
		@rRemark nvarchar(MAX) = ''

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	 
	--IF(@rId = 0)	
	--BEGIN
	--	--If Exists(select Id from sCommunication.tNews where Code=@rCode AND OrgGroupBatchId=@rOrgGroupBatchId)
	--	--	BEGIN
	--	--	select -102 as Result
	--	--	RETURN
	--	--END 
	
	--	If Exists(select Id from sAcademic.tTopicMaster where Number=@rNumber AND OrgId=@rOrgId)
	--		BEGIN
	--		select -103 as Result
	--		RETURN
	--	END 
	--END
	--ELSE
	--BEGIN
	--	--If Exists(select Id from sCommunication.tNews where Code=@rCode AND OrgGroupBatchId=@rOrgGroupBatchId AND Id<>@rId)
	--	--Begin
	--	--	select -102 as Result
	--	--	RETURN
	--	--End
	--	If  Exists(select Id from sAcademic.tTopicMaster where Number=@rNumber AND OrgId=@rOrgId AND Id<>@rId)
	--	Begin
	--		select -103 as Result
	--		RETURN
	--	End

	--END
	
	IF(@rId = 0)	
	BEGIN
		IF EXISTS(SELECT Id FROM sAcademic.tLessonPlan WHERE DivisionId=@rDivisionId AND TopicId = @rTopicId AND StartDate = @rStartDate AND EndDate = @rEndDate)
		BEGIN
			SELECT -101 AS Result
			RETURN
		END 
	END
	ELSE
	BEGIN
		IF  EXISTS(SELECT Id FROM sAcademic.tLessonPlan WHERE DivisionId=@rDivisionId AND TopicId = @rTopicId AND StartDate = @rStartDate AND EndDate = @rEndDate AND Id <> @rId)
		BEGIN
			SELECT -101 AS Result
			RETURN
		END
	END

	DECLARE @lNextNumber BIGINT 

	IF(@rId = 0)	
	BEGIN
		
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sAcademic.tLessonPlan', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	INSERT INTO sAcademic.tLessonPlan
		(
			Id,
			TopicId,
			DivisionId,
			NoOfPeriodRequired,
			Objective,
			IndicativeHomework,
			Summary,
			StartDate,
			EndDate,
			IsCompleted,
			EmployeeId,
			BatchId,
			CreatedUserId,
			CreatedDateTime,
			LearningExperience,
			ToolsAndTechniques,
			EssentialMaterial,
			AssessmentQuestion,
			TeacherExample,
			GuidedPractice,
			IndependentPractice,
			SubTopic ,
			[Session] ,
			TrainingMethod ,
			PeriodCount,
			Remark
		)
	VALUES
		(
			@lNextNumber,
			@rTopicId,
			@rDivisionId,
			@rNoOfPeriodRequired,
			@rObjective,
			@rIndicativeHomework,
			@rSummary,
			@rStartDate,
			@rEndDate,
			@rIsCompleted,
			@rEmployeeId,
			@rBatchId,
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rLearningExperience,
			@rToolsAndTechniques,
			@rEssentialMaterial,
			@rAssessmentQuestion,
			@rTeacherExample,
			@rGuidedPractice,
			@rIndependentPractice,
			CASE WHEN @rSubTopic = '-1' Then '' ELSE @rSubTopic END ,
			@rSession ,
		    @rTrainingMethod ,
			@rPeriodCount,
			@rRemark
		)
		    SELECT 1 AS Result , @lNextNumber As Id
	END	 

ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE  sAcademic.tLessonPlan
	    SET
			TopicId=@rTopicId,
			DivisionId=@rDivisionId,
			NoOfPeriodRequired=@rNoOfPeriodRequired,
			Objective=@rObjective,
			IndicativeHomework=@rIndicativeHomework,
			Summary=@rSummary,
			StartDate=@rStartDate,
			EndDate=@rEndDate,
			IsCompleted=@rIsCompleted,
			UpdatedUserId=@rCreatedUserId,
			UpdatedDateTime=sCommon.fGetDate(),
			LearningExperience = @rLearningExperience,
			ToolsAndTechniques = @rToolsAndTechniques,
			EssentialMaterial =@rEssentialMaterial,
			EmployeeId = @rEmployeeId,
			AssessmentQuestion=@rAssessmentQuestion,
			TeacherExample=@rTeacherExample,
			GuidedPractice=@rGuidedPractice,
			IndependentPractice=@rIndependentPractice,
			SubTopic= CASE WHEN @rSubTopic = '-1' Then '' ELSE @rSubTopic END ,
			[Session] = @rSession ,
			TrainingMethod =@rTrainingMethod ,
			PeriodCount =@rPeriodCount,
			Remark=@rRemark
	      WHERE Id = @rId
	      SELECT 11 AS Result, @lNextNumber As Id
	 END  	

END
GO
PRINT N'Altering [sAcademic].[pLessonPlanGet]...';


GO

ALTER PROCEDURE [sAcademic].[pLessonPlanGet]

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

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

			--sAcademic.tLessonPlan LP
			--INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id=LP.EmployeeId
			--INNER JOIN sAcademic.tTopicMaster TM ON TM.Id=LP.TopicId
			--INNER JOIN sAcademic.vTeacherSubjectDivision vTSD ON vTSD.DivisionId = LP.DivisionId
			--AND vTSD.ClassId = TM.ClassId 
			--AND vTSD.SubjectId = TM.SubjectId 
			--AND vTSD.EmployeeId = LP.EmployeeId
			--INNER JOIN sSetup.tClassMaster CM ON CM.Id = vTSD.ClassId
	WHERE 
		((LP.BatchId = @rBatchId) OR (LP.BatchId = 0))
		 AND ((LP.EmployeeId = @rEmployeeId) OR (@rEmployeeId=0))
		AND ((LP.Id = @rId) OR (@rId = 0))
		AND ((TM.ClassId = @rClassId) OR (@rClassId = 0))
		AND ((LP.DivisionId = @rDivisionId) OR (@rDivisionId = 0))
		AND ((TM.SubjectId = @rSubjectId) OR (@rSubjectId = 0))
		AND ((@rStatus = 2) OR (LP.IsCompleted=@rIsCompleted))
		AND ((CM.DepartmentId = @rDepartmentid) OR (@rDepartmentid=0))
		--AND (LP.StartDate>=@rFromDate OR ISNULL(@rFromDate,'')='')
		--AND (LP.StartDate<=@rToDate OR ISNULL(@rToDate,'')='')
	    AND ((LP.StartDate >= @rFromDate OR ISNULL(@rFromDate,'')='' )AND (LP.StartDate <= @rToDate OR ISNULL(@rToDate,'')='')
		OR (LP.EndDate >= @rFromDate OR ISNULL(@rFromDate,'')='' )AND (LP.EndDate <= @rToDate OR ISNULL(@rToDate,'')='')
		)

		AND (LP.CreatedUserId=@rCreatedUserId OR ISNULL(@rCreatedUserId,'')='')
		AND ISNULL(EM.IsOtherUser,0) = 0
	ORDER BY
		LP.id 
	END
END
GO
PRINT N'Altering [sAcademic].[pTeacherSubjectDivisionCopyToAnotherEmployee]...';


GO


ALTER PROCEDURE [sAcademic].[pTeacherSubjectDivisionCopyToAnotherEmployee]
	
	@rExistingEmployeeId bigint,
	@rNewEmployeeId bigint
	

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

--this delete will affect all related modules
	DELETE FROM sAcademic.tTeacherSubject WHERE EmployeeId = @rNewEmployeeId
	DELETE FROM sAcademic.tTeacherSubjectDivision WHERE EmployeeId = @rNewEmployeeId

	INSERT INTO sAcademic.tTeacherSubject
           (
		   EmployeeId
           ,SubjectId
		   )
     SELECT
		    @rNewEmployeeId,
            SubjectId
	
		   FROM sAcademic.tTeacherSubject WHERE EmployeeId = @rExistingEmployeeId

	INSERT INTO sAcademic.tTeacherSubjectDivision
			   (
				EmployeeId
			   ,SubjectId
			   ,DivisionId
			   ,SubjectCordinatorEmployeeId
			   )

		 Select @rNewEmployeeId,
				SubjectId,
				DivisionId,
				null

		 FROM sAcademic.tTeacherSubjectDivision WHERE EmployeeId = @rExistingEmployeeId

		 SELECT 1 AS Result
END
GO
PRINT N'Altering [sAdmission].[pAdmissionAndInquiryConsolidateDashBoardGet]...';


GO
ALTER PROCEDURE [sAdmission].[pAdmissionAndInquiryConsolidateDashBoardGet]
                              
    @rTypeId int, -- 1-Admission, 2-Inquiry 
    @rType nvarchar(200), -- OrgGroup, Organization
    @rOrgGroupId int=0,
    @rOrgId int=0,
    @rCommonOrgGroupBatchId int=0,
	@rInquiryStatusId int=0,
	@rClassId int =0,
	@rSyncDate int =0,
	@rInquiryMainStatus int =0
	 
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

	DECLARE @lTempOrgBatchOrder TABLE( OrgId int, BatchOrderIndex int)
	INSERT INTO @lTempOrgBatchOrder ( OrgId,BatchOrderIndex )
	SELECT 
		OM.Id AS OrgId, MAX(BM.OrderIndex) AS BatchOrderIndex
	FROM
		sSetup.tOrganizationMaster OM
		INNER JOIN sSetup.tBatchMaster BM ON BM.OrgId = OM.Id
		INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
	WHERE 
		((OM.OrgGroupId = @rOrgGroupId) OR (@rOrgGroupId = 0))
		AND BM.IsObsolete = 0 AND COGBM.Id=@rCommonOrgGroupBatchId
		AND BM.IsInContext = 1
	GROUP BY
		OM.Id
		
	DECLARE @lTempBatchId TABLE(OrgId int, BatchId int)
	INSERT INTO @lTempBatchId (OrgId , BatchId)
	SELECT 
		BM.OrgId AS OrgId,
		BM.Id AS BatchId
	FROM 
		sSetup.tBatchMaster BM
		INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
		--INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		INNER JOIN @lTempOrgBatchOrder BO ON BO.OrgId = BM.OrgId
	WHERE
		BO.BatchOrderIndex = BM.OrderIndex  AND COGBM.Id=@rCommonOrgGroupBatchId
		AND BM.IsInContext = 1
	
	DECLARE @lConfigValue nvarchar(50)=''
	IF(@rOrgGroupId = 0)
	BEGIN
		DECLARE @lOrgGroupId int
		SELECT @lOrgGroupId = OrgGroupId FROM sSetup.tOrganizationMaster WHERE Id = @rOrgId
		
		SELECT @lConfigValue = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 397 AND SourceTypeId = 2010 AND SourceId = @lOrgGroupId
	END
	ELSE
	BEGIN
		SELECT @lConfigValue = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 397 AND SourceTypeId = 2010 AND SourceId = @rOrgGroupId
	END
	IF @lConfigValue = ''
		SET @lConfigValue = 'False' 

-- For Admission TypeId=1
	IF(@rTypeId=1) 
	BEGIN
		IF(@rType='OrgGroup')
		BEGIN

		IF(@rSyncDate =1)
				BEGIN
				DELETE  sAdmission.tTempAdmissionFormCount WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))  
				IF EXISTS (SELECT 1 FROM sAdmission.tTempAdmissionFormCount WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND (OrgGroupId = @rOrgGroupId))  
				BEGIN  
					IF(@rOrgGroupId !=0)  
					INSERT INTO sAdmission.tTempAdmissionFormCount  
					SELECT ISNULL(OGM.Id,0) AS OrgGroupId,OGM.Title AS OrgGroupTitle,ISNULL(COUNT(AF.Id),0) AS AdmissionCount,@rCommonOrgGroupBatchId,GetDate(),

					(SELECT ISNULL(COUNT(AF1.Id),0) FROM sSetup.tOrgGroupMaster OGM1     
					INNER JOIN sSetup.tOrganizationMaster OM1 ON OGM1.Id = OM1.OrgGroupId   
					INNER JOIN @lTempBatchId TB1 ON TB1.OrgId = OM1.Id  
					LEFT JOIN sSetup.tBatchMaster BM1 ON BM1.Id = TB1.BatchId AND BM1.IsInContext = 1  
					INNER JOIN sSetup.tOrgGroupBatchMaster OGBM1 ON OGBM1.ID=BM1.OrgGroupBatchId AND OGM1.Id = OGBM1.OrgGroupId   
					INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM1 ON COGBM1.Id=OGBM1.CommonOrgGroupBatchId   
					LEFT JOIN sAdmission.tAdmissionForm AF1 ON BM1.Id = AF1.BatchId
					LEFT JOIN sAdmission.tAdmissionFormSelected AFS ON AF1.Id = AFS.AdmissionFormId
				    LEFT JOIN sAdmission.tAdmissionStatusMaster ASM ON ASM.Id = AFS.AdmissionStatusId WHERE OGM1.Id<>1 AND COGBM1.Id = COGBM.Id AND OGM1.Id = OGM.Id AND ASM.Id = null) as PendingCount,

					(SELECT ISNULL(COUNT(AF1.Id),0) FROM sSetup.tOrgGroupMaster OGM1     
					INNER JOIN sSetup.tOrganizationMaster OM1 ON OGM1.Id = OM1.OrgGroupId   
					INNER JOIN @lTempBatchId TB1 ON TB1.OrgId = OM1.Id  
					LEFT JOIN sSetup.tBatchMaster BM1 ON BM1.Id = TB1.BatchId AND BM1.IsInContext = 1
					INNER JOIN sSetup.tOrgGroupBatchMaster OGBM1 ON OGBM1.ID=BM1.OrgGroupBatchId AND OGM1.Id = OGBM1.OrgGroupId   
					INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM1 ON COGBM1.Id=OGBM1.CommonOrgGroupBatchId   
					LEFT JOIN sAdmission.tAdmissionForm AF1 ON BM1.Id = AF1.BatchId
					LEFT JOIN sAdmission.tAdmissionFormSelected AFS ON AF1.Id = AFS.AdmissionFormId
				    LEFT JOIN sAdmission.tAdmissionStatusMaster ASM ON ASM.Id = AFS.AdmissionStatusId WHERE OGM1.Id<>1 AND COGBM1.Id = COGBM.Id AND OGM1.Id = OGM.Id AND ASM.Id = 3) as ConfirmCount
					
					FROM sSetup.tOrgGroupMaster OGM     
					INNER JOIN sSetup.tOrganizationMaster OM ON OGM.Id = OM.OrgGroupId   
					INNER JOIN @lTempBatchId TB ON TB.OrgId = OM.Id  
					LEFT JOIN sSetup.tBatchMaster BM ON BM.Id = TB.BatchId AND BM.IsInContext = 1
					INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId AND OGM.Id = OGBM.OrgGroupId   
					--INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId        
					INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId   
					LEFT JOIN sAdmission.tAdmissionForm AF ON BM.Id = AF.BatchId  
					WHERE   
					OGM.Id<>1 AND  
					COGBM.Id=@rCommonOrgGroupBatchId AND  
					--BM.IsActive = 1  
					BM.Id = TB.BatchId  
					GROUP BY OGM.Id,OGM.Title,COGBM.Id  
					SELECT * FROM sAdmission.tTempAdmissionFormCount WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))  
				END  
				ELSE  
				BEGIN  
					INSERT INTO sAdmission.tTempAdmissionFormCount  
					SELECT ISNULL(OGM.Id,0) AS OrgGroupId,OGM.Title AS OrgGroupTitle,ISNULL(COUNT(AF.Id),0) AS AdmissionCount,@rCommonOrgGroupBatchId,GetDate(),

					(SELECT ISNULL(COUNT(AF1.Id),0) FROM sSetup.tOrgGroupMaster OGM1     
					INNER JOIN sSetup.tOrganizationMaster OM1 ON OGM1.Id = OM1.OrgGroupId   
					INNER JOIN @lTempBatchId TB1 ON TB1.OrgId = OM1.Id  
					LEFT JOIN sSetup.tBatchMaster BM1 ON BM1.Id = TB1.BatchId  AND BM1.IsInContext = 1
					INNER JOIN sSetup.tOrgGroupBatchMaster OGBM1 ON OGBM1.ID=BM1.OrgGroupBatchId AND OGM1.Id = OGBM1.OrgGroupId   
					INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM1 ON COGBM1.Id=OGBM1.CommonOrgGroupBatchId   
					LEFT JOIN sAdmission.tAdmissionForm AF1 ON BM1.Id = AF1.BatchId
					LEFT JOIN sAdmission.tAdmissionFormSelected AFS ON AF1.Id = AFS.AdmissionFormId
				    LEFT JOIN sAdmission.tAdmissionStatusMaster ASM ON ASM.Id = AFS.AdmissionStatusId WHERE OGM1.Id<>1 AND COGBM1.Id = COGBM.Id AND OGM1.Id = OGM.Id AND ASM.Id IS NULL) as PendingCount,

					(SELECT ISNULL(COUNT(AF1.Id),0) FROM sSetup.tOrgGroupMaster OGM1     
					INNER JOIN sSetup.tOrganizationMaster OM1 ON OGM1.Id = OM1.OrgGroupId   
					INNER JOIN @lTempBatchId TB1 ON TB1.OrgId = OM1.Id  
					LEFT JOIN sSetup.tBatchMaster BM1 ON BM1.Id = TB1.BatchId  AND BM1.IsInContext = 1
					INNER JOIN sSetup.tOrgGroupBatchMaster OGBM1 ON OGBM1.ID=BM1.OrgGroupBatchId AND OGM1.Id = OGBM1.OrgGroupId   
					INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM1 ON COGBM1.Id=OGBM1.CommonOrgGroupBatchId   
					LEFT JOIN sAdmission.tAdmissionForm AF1 ON BM1.Id = AF1.BatchId
					LEFT JOIN sAdmission.tAdmissionFormSelected AFS ON AF1.Id = AFS.AdmissionFormId
				    LEFT JOIN sAdmission.tAdmissionStatusMaster ASM ON ASM.Id = AFS.AdmissionStatusId WHERE OGM1.Id<>1 AND COGBM1.Id = COGBM.Id AND OGM1.Id = OGM.Id AND ASM.Id = 3) as ConfirmCount

					FROM sSetup.tOrgGroupMaster OGM     
					INNER JOIN sSetup.tOrganizationMaster OM ON OGM.Id = OM.OrgGroupId   
					INNER JOIN @lTempBatchId TB ON TB.OrgId = OM.Id  
					LEFT JOIN sSetup.tBatchMaster BM ON BM.Id = TB.BatchId AND BM.IsInContext = 1 
					INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId AND OGM.Id = OGBM.OrgGroupId   
					--INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId        
					INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId   
					LEFT JOIN sAdmission.tAdmissionForm AF ON BM.Id = AF.BatchId  
					WHERE   
					OGM.Id<>1 AND  
					COGBM.Id=@rCommonOrgGroupBatchId AND  
					--BM.IsActive = 1  
					BM.Id = TB.BatchId  
					GROUP BY OGM.Id,OGM.Title,COGBM.Id  
					SELECT * FROM sAdmission.tTempAdmissionFormCount WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))  
				END  
		END
		ELSE
			BEGIN
			 IF  Exists(select 1 from sAdmission.tTempAdmissionFormCount   where CONVERT(date,UpdateDate) =  CONVERT(date,getdate(),102) AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0)) AND CommonOrgGroupBatchId=@rCommonOrgGroupBatchId)   
			 BEGIN  
				 SELECT * FROM sAdmission.tTempAdmissionFormCount   WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))  
				 return  
			 END  
			 ELSE  
			 BEGIN  
				DELETE  sAdmission.tTempAdmissionFormCount WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))  
				IF EXISTS (SELECT 1 FROM sAdmission.tTempAdmissionFormCount WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0)))  
				BEGIN  
					IF(@rOrgGroupId !=0)  
        
					INSERT INTO sAdmission.tTempAdmissionFormCount  
					SELECT ISNULL(OGM.Id,0) AS OrgGroupId,OGM.Title AS OrgGroupTitle,ISNULL(COUNT(AF.Id),0) AS AdmissionCount,@rCommonOrgGroupBatchId,GetDate(),
				
					(SELECT ISNULL(COUNT(AF1.Id),0) FROM sSetup.tOrgGroupMaster OGM1     
					INNER JOIN sSetup.tOrganizationMaster OM1 ON OGM1.Id = OM1.OrgGroupId   
					INNER JOIN @lTempBatchId TB1 ON TB1.OrgId = OM1.Id  
					LEFT JOIN sSetup.tBatchMaster BM1 ON BM1.Id = TB1.BatchId AND BM1.IsInContext = 1
					INNER JOIN sSetup.tOrgGroupBatchMaster OGBM1 ON OGBM1.ID=BM1.OrgGroupBatchId AND OGM1.Id = OGBM1.OrgGroupId   
					INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM1 ON COGBM1.Id=OGBM1.CommonOrgGroupBatchId   
					LEFT JOIN sAdmission.tAdmissionForm AF1 ON BM1.Id = AF1.BatchId
					LEFT JOIN sAdmission.tAdmissionFormSelected AFS ON AF1.Id = AFS.AdmissionFormId
					LEFT JOIN sAdmission.tAdmissionStatusMaster ASM ON ASM.Id = AFS.AdmissionStatusId WHERE OGM1.Id<>1 AND COGBM1.Id = COGBM.Id AND OGM1.Id = OGM.Id AND ASM.Id IS NULL) as PendingCount,

					(SELECT ISNULL(COUNT(AF1.Id),0) FROM sSetup.tOrgGroupMaster OGM1     
					INNER JOIN sSetup.tOrganizationMaster OM1 ON OGM1.Id = OM1.OrgGroupId   
					INNER JOIN @lTempBatchId TB1 ON TB1.OrgId = OM1.Id  
					LEFT JOIN sSetup.tBatchMaster BM1 ON BM1.Id = TB1.BatchId  AND BM1.IsInContext = 1
					INNER JOIN sSetup.tOrgGroupBatchMaster OGBM1 ON OGBM1.ID=BM1.OrgGroupBatchId AND OGM1.Id = OGBM1.OrgGroupId   
					INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM1 ON COGBM1.Id=OGBM1.CommonOrgGroupBatchId   
					LEFT JOIN sAdmission.tAdmissionForm AF1 ON BM1.Id = AF1.BatchId
					LEFT JOIN sAdmission.tAdmissionFormSelected AFS ON AF1.Id = AFS.AdmissionFormId
					LEFT JOIN sAdmission.tAdmissionStatusMaster ASM ON ASM.Id = AFS.AdmissionStatusId WHERE OGM1.Id<>1 AND COGBM1.Id = COGBM.Id AND OGM1.Id = OGM.Id AND ASM.Id = 3) as ConfirmCount
					  
					FROM sSetup.tOrgGroupMaster OGM     
					INNER JOIN sSetup.tOrganizationMaster OM ON OGM.Id = OM.OrgGroupId   
					INNER JOIN @lTempBatchId TB ON TB.OrgId = OM.Id  
					LEFT JOIN sSetup.tBatchMaster BM ON BM.Id = TB.BatchId  AND BM.IsInContext = 1
					INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId AND OGM.Id = OGBM.OrgGroupId   
					--INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId        
					INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId   
					LEFT JOIN sAdmission.tAdmissionForm AF ON BM.Id = AF.BatchId  
					WHERE   
					OGM.Id<>1 AND  
					COGBM.Id=@rCommonOrgGroupBatchId AND  
					--BM.IsActive = 1  
					BM.Id = TB.BatchId  
					GROUP BY OGM.Id,OGM.Title,COGBM.Id
					SELECT * FROM sAdmission.tTempAdmissionFormCount WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))  
				END  
				ELSE  
				BEGIN  
					INSERT INTO sAdmission.tTempAdmissionFormCount  
					SELECT ISNULL(OGM.Id,0) AS OrgGroupId,OGM.Title AS OrgGroupTitle,ISNULL(COUNT(AF.Id),0) AS AdmissionCount,@rCommonOrgGroupBatchId,GetDate(),
			
					(SELECT ISNULL(COUNT(AF1.Id),0) FROM sSetup.tOrgGroupMaster OGM1     
					INNER JOIN sSetup.tOrganizationMaster OM1 ON OGM1.Id = OM1.OrgGroupId   
					INNER JOIN @lTempBatchId TB1 ON TB1.OrgId = OM1.Id  
					LEFT JOIN sSetup.tBatchMaster BM1 ON BM1.Id = TB1.BatchId  AND BM1.IsInContext = 1
					INNER JOIN sSetup.tOrgGroupBatchMaster OGBM1 ON OGBM1.ID=BM1.OrgGroupBatchId AND OGM1.Id = OGBM1.OrgGroupId   
					INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM1 ON COGBM1.Id=OGBM1.CommonOrgGroupBatchId   
					LEFT JOIN sAdmission.tAdmissionForm AF1 ON BM1.Id = AF1.BatchId
					LEFT JOIN sAdmission.tAdmissionFormSelected AFS ON AF1.Id = AFS.AdmissionFormId
					LEFT JOIN sAdmission.tAdmissionStatusMaster ASM ON ASM.Id = AFS.AdmissionStatusId WHERE OGM1.Id<>1 AND COGBM1.Id = COGBM.Id AND OGM1.Id = OGM.Id AND ASM.Id IS NULL) as PendingCount,

					(SELECT ISNULL(COUNT(AF1.Id),0) FROM sSetup.tOrgGroupMaster OGM1     
					INNER JOIN sSetup.tOrganizationMaster OM1 ON OGM1.Id = OM1.OrgGroupId   
					INNER JOIN @lTempBatchId TB1 ON TB1.OrgId = OM1.Id  
					LEFT JOIN sSetup.tBatchMaster BM1 ON BM1.Id = TB1.BatchId AND BM1.IsInContext = 1 
					INNER JOIN sSetup.tOrgGroupBatchMaster OGBM1 ON OGBM1.ID=BM1.OrgGroupBatchId AND OGM1.Id = OGBM1.OrgGroupId   
					INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM1 ON COGBM1.Id=OGBM1.CommonOrgGroupBatchId   
					LEFT JOIN sAdmission.tAdmissionForm AF1 ON BM1.Id = AF1.BatchId
					LEFT JOIN sAdmission.tAdmissionFormSelected AFS ON AF1.Id = AFS.AdmissionFormId
					LEFT JOIN sAdmission.tAdmissionStatusMaster ASM ON ASM.Id = AFS.AdmissionStatusId WHERE OGM1.Id<>1 AND COGBM1.Id = COGBM.Id AND OGM1.Id = OGM.Id AND ASM.Id = 3) as ConfirmCount
				     
					FROM sSetup.tOrgGroupMaster OGM     
					INNER JOIN sSetup.tOrganizationMaster OM ON OGM.Id = OM.OrgGroupId   
					INNER JOIN @lTempBatchId TB ON TB.OrgId = OM.Id  
					LEFT JOIN sSetup.tBatchMaster BM ON BM.Id = TB.BatchId AND BM.IsInContext = 1   
					INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId AND OGM.Id = OGBM.OrgGroupId   
					--INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId        
					INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId   
					LEFT JOIN sAdmission.tAdmissionForm AF ON BM.Id = AF.BatchId  
					WHERE   
					OGM.Id<>1 AND  
					COGBM.Id=@rCommonOrgGroupBatchId AND  
					--BM.IsActive = 1  
					BM.Id = TB.BatchId  
					GROUP BY OGM.Id,OGM.Title,COGBM.Id  
					SELECT * FROM sAdmission.tTempAdmissionFormCount WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))  
				END  
			END  
		END
	END
-- For Admission TypeId=1
	IF(@rType='Organization')
		BEGIN
			SELECT ISNULL(OM.Id,0) AS OrgId,OM.Title AS Organization,ISNULL(COUNT(AF.Id),0) AS AdmissionCount,OM.OrderIndex
			FROM sAdmission.tAdmissionForm AF 
			LEFT JOIN  sSetup.tOrganizationMaster OM ON AF.OrgId = OM.Id 
			LEFT JOIN sSetup.tBatchMaster BM ON BM.Id = AF.BatchId AND BM.IsInContext = 1
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
			
			
			LEFT JOIN @lTempBatchId TB ON TB.OrgId = OM.Id and BM.Id = TB.BatchId
			WHERE --BM.IsActive = 1 
			OM.OrgGroupId = @rOrgGroupId 	
			AND BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId 
			And ISNULL(O.IsObsolete,0) = 0
			GROUP BY OM.Id,OM.Title,OM.OrderIndex
			Order BY OM.OrderIndex
		END
-- For Admission TypeId=1
	IF(@rType='Status')
		BEGIN
			SELECT ISNULL(ASM.Id,0) AS InquiryStatusId,ISNULL(OM.Id,0) AS OrgId,OM.Title AS Organization, ISNULL(ASM.Title,'Pending') AS StatusName ,ISNULL(COUNT(AF.Id),0) AS StatusCount ,0 AS InquiryMainStatusId
			,OM.OrderIndex
			FROM sAdmission.tAdmissionForm AF 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AF.BatchId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
			
			INNER JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AF.OrgId = OM.Id
			LEFT JOIN sAdmission.tAdmissionFormSelected AFS ON AF.Id = AFS.AdmissionFormId
			LEFT JOIN sAdmission.tAdmissionStatusMaster ASM ON ASM.Id = AFS.AdmissionStatusId
			WHERE --BM.IsActive = 1 
			BM.Id = TB.BatchId AND OM.Id = @rOrgId AND COGBM.Id=@rCommonOrgGroupBatchId 
			And ISNULL(O.IsObsolete,0) = 0
			AND BM.IsInContext = 1
			GROUP BY OM.Id,OM.Title,ASM.Id,ASM.Title,OM.OrderIndex
			Order By OM.OrderIndex
		END
-- For Admission TypeId=1
	IF(@rType='StatusOrgGroupWise')
		BEGIN
		    CREATE Table #MyTempTable(
						  OrgId Int,
						  Organization nvarchar(100),
                          StatusName nvarchar(100),
                          StatusCount BigInt)
            INSERT INTO #MyTempTable(OrgId,Organization,StatusName,StatusCount)
			SELECT OM.Id,OM.Title AS Organization, ISNULL(ASM.Title,'Pending') AS StatusName ,AF.Id AS StatusCount 			
			FROM sAdmission.tAdmissionForm AF 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AF.BatchId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
			
			INNER JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AF.OrgId = OM.Id
			
			LEFT JOIN sAdmission.tAdmissionFormSelected AFS ON AF.Id = AFS.AdmissionFormId
			LEFT JOIN sAdmission.tAdmissionStatusMaster ASM ON ASM.Id = AFS.AdmissionStatusId
			WHERE --BM.IsActive = 1 
			BM.Id = TB.BatchId
			AND OM.OrgGroupId = @rOrgGroupId AND COGBM.Id=@rCommonOrgGroupBatchId
			And ISNULL(O.IsObsolete,0) = 0
			AND BM.IsInContext = 1

	DECLARE 
    @columns NVARCHAR(MAX) = '', 
    @sql     NVARCHAR(MAX) = '';

	SELECT 
    @columns+=QUOTENAME(ASM.Title) + ','
  FROM 
    sAdmission.tAdmissionStatusMaster ASM
  ORDER BY 
    ASM.Title;
  -- Add Pending Column
  SET @columns = LEFT(@columns, LEN(@columns) - 1)+',Pending';


  -- construct dynamic SQL
  SET @sql ='
  SELECT * FROM #MyTempTable MT  
  PIVOT(
    Count(MT.StatusCount)
    FOR MT.StatusName IN ('+ @columns +')
  ) AS pivot_table;';

  -- execute the dynamic SQL
  EXECUTE sp_executesql @sql;
  DROP Table #MyTempTable
		END

	--For Admission Form Count
	IF(@rType='AdmissionFormOrgGroupWise')
	BEGIN
		SELECT ISNULL(ASM.Id,0) AS InquiryStatusId,ISNULL(OM.Id,0) AS OrgId,OM.Title AS Organization, ISNULL(ASM.Title,'Pending') AS StatusName ,ISNULL(COUNT(AF.Id),0) AS StatusCount , 0 AS InquiryMainStatusId
		,OM.OrderIndex
		FROM sAdmission.tAdmissionForm AF 
		INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AF.BatchId
		INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		   INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		   INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
		
		INNER JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
		INNER JOIN sSetup.tOrganizationMaster OM ON AF.OrgId = OM.Id
		
		LEFT JOIN sAdmission.tAdmissionFormSelected AFS ON AF.Id = AFS.AdmissionFormId
		LEFT JOIN sAdmission.tAdmissionStatusMaster ASM ON ASM.Id = AFS.AdmissionStatusId
		WHERE --BM.IsActive = 1 
		BM.Id = TB.BatchId
		AND BM.IsInContext = 1
		AND OM.OrgGroupId = @rOrgGroupId AND COGBM.Id=@rCommonOrgGroupBatchId
		And ISNULL(O.IsObsolete,0) = 0
		GROUP BY OM.Id,OM.Title,ASM.Id,ASM.Title,OM.OrderIndex
		Order BY OM.OrderIndex	
	END

	IF(@rType='AdmissionFormStatusWise')
	BEGIN
		SELECT ISNULL(ASM.Id,0) AS InquiryStatusId,ISNULL(OM.Id,0) AS OrgId,OM.Title AS Organization, ISNULL(ASM.Title,'Pending') AS StatusName ,ISNULL(COUNT(AF.Id),0) AS StatusCount , 0 AS InquiryMainStatusId
		,OM.OrderIndex
		FROM sAdmission.tAdmissionForm AF 
		INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AF.BatchId
		INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		   INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		   INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
		
		INNER JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
		INNER JOIN sSetup.tOrganizationMaster OM ON AF.OrgId = OM.Id
		
		LEFT JOIN sAdmission.tAdmissionFormSelected AFS ON AF.Id = AFS.AdmissionFormId
		LEFT JOIN sAdmission.tAdmissionStatusMaster ASM ON ASM.Id = AFS.AdmissionStatusId
		WHERE --BM.IsActive = 1 
		BM.Id = TB.BatchId
		AND BM.IsInContext = 1
		AND OM.OrgGroupId = @rOrgGroupId AND COGBM.Id=@rCommonOrgGroupBatchId
		And ISNULL(O.IsObsolete,0) = 0
		AND ISNULL(ASM.Id,0)=@rInquiryStatusId
		GROUP BY OM.Id,OM.Title,ASM.Id,ASM.Title,OM.OrderIndex
		Order BY OM.OrderIndex	
	END
-- For Admission TypeId=1
	ELSE IF(@rType='StatusClassWise')
		BEGIN
		
			SELECT CM.Id AS ClassId,CM.DisplayTitle AS ClassName,ISNULL(COUNT(AF.Id),0) AS StatusCount ,CM.OrderIndex 
			FROM sAdmission.tAdmissionForm AF 
			INNER JOIN sSetup.tClassMaster CM ON CM.Id = AF.ForClassId
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AF.BatchId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
			INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
			INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
			INNER JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AF.OrgId = OM.Id

			LEFT JOIN sAdmission.tAdmissionFormSelected AFS ON AF.Id = AFS.AdmissionFormId
			LEFT JOIN sAdmission.tAdmissionStatusMaster ASM ON ASM.Id = AFS.AdmissionStatusId
			WHERE --BM.IsActive = 1 
			BM.Id = TB.BatchId
			AND OM.OrgGroupId = @rOrgGroupId AND COGBM.Id=@rCommonOrgGroupBatchId
			AND ISNULL(ASM.Id,0)=@rInquiryStatusId
			And ISNULL(O.IsObsolete,0) = 0
			AND((CM.OrgId = @rOrgId)OR(@rOrgId=0))
			AND BM.IsInContext = 1
			GROUP BY CM.Id,CM.DisplayTitle,CM.OrderIndex
		END
-- For Admission TypeId=1
ELSE IF(@rType='StatusClassWise')
		BEGIN
		
			SELECT CM.Id AS ClassId,CM.DisplayTitle AS ClassName,ISNULL(COUNT(AF.Id),0) AS StatusCount ,CM.OrderIndex 
			FROM sAdmission.tAdmissionForm AF 
			INNER JOIN sSetup.tClassMaster CM ON CM.Id = AF.ForClassId
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AF.BatchId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
			INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
			INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
			INNER JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AF.OrgId = OM.Id

			LEFT JOIN sAdmission.tAdmissionFormSelected AFS ON AF.Id = AFS.AdmissionFormId
			LEFT JOIN sAdmission.tAdmissionStatusMaster ASM ON ASM.Id = AFS.AdmissionStatusId
			WHERE --BM.IsActive = 1 
			BM.Id = TB.BatchId
			AND OM.OrgGroupId = @rOrgGroupId AND COGBM.Id=@rCommonOrgGroupBatchId
			AND ISNULL(ASM.Id,0)=@rInquiryStatusId
			And ISNULL(O.IsObsolete,0) = 0
			AND((CM.OrgId = @rOrgId)OR(@rOrgId=0))
			AND BM.IsInContext = 1
			GROUP BY CM.Id,CM.DisplayTitle,CM.OrderIndex
		END
-- For Admission TypeId=1
ELSE IF(@rType='StatusStudentList')
			BEGIN
			SELECT AF.FormNo As InquiryId, AF.FirstName+' '+AF.MiddleName +' '+ AF.LastName AS StudentName,AF.ContactNo AS ContactNo 
			FROM sAdmission.tAdmissionForm AF 
			INNER JOIN sSetup.tClassMaster CM ON CM.Id = AF.ForClassId
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AF.BatchId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
			INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
			INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
			INNER JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AF.OrgId = OM.Id
			LEFT JOIN sAdmission.tAdmissionFormSelected AFS ON AF.Id = AFS.AdmissionFormId
			LEFT JOIN sAdmission.tAdmissionStatusMaster ASM ON ASM.Id = AFS.AdmissionStatusId
			WHERE --BM.IsActive = 1 
			BM.Id = TB.BatchId
			AND OM.OrgGroupId = @rOrgGroupId 
			AND COGBM.Id=@rCommonOrgGroupBatchId
			AND ISNULL(ASM.Id,0)=@rInquiryStatusId
			AND((CM.OrgId = @rOrgId)OR(@rOrgId=0))
			AND((CM.Id = @rClassId)OR(@rClassId=0))
			And ISNULL(O.IsObsolete,0) = 0
			AND BM.IsInContext = 1
			GROUP BY AF.FirstName,AF.MiddleName,AF.LastName,AF.ContactNo,AF.FormNo
			END
			END
	
-- For Inquiry
	IF(@rTypeId=2)
	BEGIN
	IF(@rType='OrgGroup')
		BEGIN
			IF(@rSyncDate =1)
				BEGIN
			DELETE  sAdmission.tTempAdmissionInquiryCount WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))  
			IF EXISTS (SELECT 1 FROM sAdmission.tTempAdmissionInquiryCount WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND (OrgGroupId = @rOrgGroupId))  
				   BEGIN  
				   IF(@rOrgGroupId !=0)  
				   INSERT INTO sAdmission.tTempAdmissionInquiryCount  
					SELECT ISNULL(OGM.Id,0) AS OrgGroupId,OGM.Title AS OrgGroupTitle,ISNULL(COUNT(AI.Id),0) AS AdmissionCount,@rCommonOrgGroupBatchId,GetDate()  
					FROM   
					sSetup.tOrgGroupMaster OGM  
					INNER JOIN sSetup.tOrganizationMaster OM ON OGM.Id = OM.OrgGroupId   
			        
					INNER JOIN @lTempBatchId TB ON TB.OrgId = OM.Id  
					LEFT JOIN sSetup.tBatchMaster BM ON BM.Id = TB.BatchId AND BM.IsInContext = 1
					INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId  
					INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId        
					INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId   
			        
					LEFT JOIN sAdmission.tAdmissionInquiry AI ON BM.Id = AI.ForBatchId    
					WHERE OGM.Id<>1 and BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId   
					--BM.IsActive = 1  
					GROUP BY OGM.Id,OGM.Title  
					SELECT OrgGroupTitle AS OrgGroup,0 AS PendingCount,0 AS ConfirmCount,* FROM sAdmission.tTempAdmissionInquiryCount WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))  
				   END  
      ELSE   
       BEGIN  
		    INSERT INTO sAdmission.tTempAdmissionInquiryCount  
        SELECT ISNULL(OGM.Id,0) AS OrgGroupId,OGM.Title AS OrgGroupTitle,ISNULL(COUNT(AI.Id),0) AS AdmissionCount,@rCommonOrgGroupBatchId,GetDate()  
       FROM   
       sSetup.tOrgGroupMaster OGM  
       INNER JOIN sSetup.tOrganizationMaster OM ON OGM.Id = OM.OrgGroupId   
       
       INNER JOIN @lTempBatchId TB ON TB.OrgId = OM.Id  
       LEFT JOIN sSetup.tBatchMaster BM ON BM.Id = TB.BatchId AND BM.IsInContext = 1
       INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId  
       INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId        
       INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId   
       LEFT JOIN sAdmission.tAdmissionInquiry AI ON BM.Id = AI.ForBatchId  
       WHERE OGM.Id<>1 and BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId   
       --BM.IsActive = 1  
       GROUP BY OGM.Id,OGM.Title  
		  SELECT OrgGroupTitle AS OrgGroup,0 AS PendingCount,0 AS ConfirmCount,* FROM sAdmission.tTempAdmissionInquiryCount WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))  
       END  
				END
			ELSE
				BEGIN
						IF  Exists(select 1 from sAdmission.tTempAdmissionInquiryCount   where CONVERT(date,UpdateDate) =  CONVERT(date,getdate(),102)   AND CommonOrgGroupBatchId=@rCommonOrgGroupBatchId  AND (OrgGroupId = @rOrgGroupId))  
			  BEGIN  
			   SELECT  OrgGroupTitle AS OrgGroup,0 AS PendingCount,0 AS ConfirmCount,* FROM sAdmission.tTempAdmissionInquiryCount   WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))  
			   return  
			  END  
			 ELSE  
			  BEGIN  
			  DELETE  sAdmission.tTempAdmissionInquiryCount WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))  
			  IF EXISTS (SELECT 1 FROM sAdmission.tTempAdmissionInquiryCount WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0)))  
			   BEGIN  
				IF(@rOrgGroupId !=0)  
				INSERT INTO sAdmission.tTempAdmissionInquiryCount  
				 SELECT ISNULL(OGM.Id,0) AS OrgGroupId,OGM.Title AS OrgGroupTitle,ISNULL(COUNT(AI.Id),0) AS AdmissionCount,@rCommonOrgGroupBatchId,GetDate()  
				FROM   
				sSetup.tOrgGroupMaster OGM  
				INNER JOIN sSetup.tOrganizationMaster OM ON OGM.Id = OM.OrgGroupId   
		        
				INNER JOIN @lTempBatchId TB ON TB.OrgId = OM.Id  
				LEFT JOIN sSetup.tBatchMaster BM ON BM.Id = TB.BatchId AND BM.IsInContext = 1
				INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId  
				INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId        
				INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId   
		        
				LEFT JOIN sAdmission.tAdmissionInquiry AI ON BM.Id = AI.ForBatchId  
				WHERE OGM.Id<>1 and BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId   
				--BM.IsActive = 1  
				GROUP BY OGM.Id,OGM.Title  
				SELECT OrgGroupTitle AS OrgGroup,0 AS PendingCount,0 AS ConfirmCount,* FROM sAdmission.tTempAdmissionInquiryCount WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))  
			   END  
			  ELSE  
			   BEGIN  
				DELETE  sAdmission.tTempAdmissionInquiryCount WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))  
				INSERT INTO sAdmission.tTempAdmissionInquiryCount  
				 SELECT ISNULL(OGM.Id,0) AS OrgGroupId,OGM.Title AS OrgGroupTitle,ISNULL(COUNT(AI.Id),0) AS AdmissionCount,@rCommonOrgGroupBatchId,GetDate()  
				FROM   
				sSetup.tOrgGroupMaster OGM  
				INNER JOIN sSetup.tOrganizationMaster OM ON OGM.Id = OM.OrgGroupId   
				INNER JOIN @lTempBatchId TB ON TB.OrgId = OM.Id  
				LEFT JOIN sSetup.tBatchMaster BM ON BM.Id = TB.BatchId AND BM.IsInContext = 1
				INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId  
				INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId        
				INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId   
				LEFT JOIN sAdmission.tAdmissionInquiry AI ON BM.Id = AI.ForBatchId  
				WHERE OGM.Id<>1 and BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId   
				--BM.IsActive = 1  
				GROUP BY OGM.Id,OGM.Title  
				SELECT OrgGroupTitle AS OrgGroup,0 AS PendingCount,0 AS ConfirmCount,* FROM sAdmission.tTempAdmissionInquiryCount WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))  
       END  
		END  
		 END		
		END
-- For Inquiry
	IF(@rType='Organization')
		BEGIN
			SELECT ISNULL(OM.Id,0) AS OrgId,OM.Title AS Organization,ISNULL(COUNT(AI.Id),0) AS AdmissionCount,OM.OrderIndex
			FROM sAdmission.tAdmissionInquiry AI 
			LEFT JOIN sSetup.tOrganizationMaster OM ON AI.OrgId = OM.Id
			LEFT JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForBatchId AND BM.IsInContext = 1
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
			
			LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			
			--sAdmission.tAdmissionForm AF 
			--LEFT JOIN  sSetup.tOrganizationMaster OM ON AF.OrgId = OM.Id 	
			--LEFT JOIN sSetup.tBatchMaster BM ON BM.Id = AF.BatchId
			--LEFT JOIN @lTempBatchId TB ON TB.OrgId = OM.Id and BM.Id = TB.BatchId
			WHERE BM.Id = TB.BatchId
			And ISNULL(O.IsObsolete,0) = 0
			--BM.IsActive = 1 
			AND OM.OrgGroupId = @rOrgGroupId AND COGBM.Id=@rCommonOrgGroupBatchId
			GROUP BY OM.Id,OM.Title,OM.OrderIndex
			ORDER BY OM.OrderIndex
		END
-- For Inquiry
	IF(@rType='Status')
		BEGIN
		IF(@lConfigValue = 'True')
		BEGIN
-- 11
-- Inquiry Form 
			SELECT 
			ISM.Id AS InquiryStatusId,
			ISNULL(OM.Id,0) AS OrgId,
			OM.Title AS Organization,
			ISNULL(ISM.Title,'') AS StatusName,
			(
			SELECT 
			ISNULL(COUNT(ISM.Id),0) AS StatusCount 
			FROM sAdmission.tAdmissionInquiry AI1 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI1.ForBatchId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
			LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AI1.OrgId = OM.Id
			LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI1.InquiryStatusId
			WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
			AND ISM.InquiryMainStatusId >= 11
			AND((OM.Id = @rOrgId)OR(@rOrgId=0)) AND OM.Id = AI.OrgId
			AND BM.IsInContext = 1
			) AS StatusCount,
			ISM.InquiryMainStatusId AS InquiryMainStatusId
			FROM sAdmission.tAdmissionInquiry AI 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForBatchId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
			
			LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AI.OrgId = OM.Id
			LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI.InquiryStatusId
			WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
			AND ISM.InquiryMainStatusId = 11
			--BM.IsActive = 1 
			AND((OM.Id = @rOrgId)OR(@rOrgId=0))
			And ISNULL(O.IsObsolete,0) = 0
			AND BM.IsInContext = 1
			
			GROUP BY OM.Id,OM.Title,ISM.Id,ISM.Title,ISM.InquiryMainStatusId,AI.OrgId
			
			UNION ALL
-- 21
-- Admission Form Given
			SELECT 
			ISM.Id AS InquiryStatusId,
			ISNULL(OM.Id,0) AS OrgId,
			OM.Title AS Organization,
			ISNULL(ISM.Title,'') AS StatusName,
			(
			SELECT 
			ISNULL(COUNT(ISM.Id),0) AS StatusCount 
			FROM sAdmission.tAdmissionInquiry AI1
			INNER JOIN sSetup.tClassMaster CM ON CM.Id = AI1.ForClassId
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI1.ForBatchId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
			LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AI1.OrgId = OM.Id
			LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI1.InquiryStatusId
			WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
			AND ISM.InquiryMainStatusId > 11
			--BM.IsActive = 1 
			AND((OM.Id = @rOrgId)OR(@rOrgId=0)) AND OM.Id = AI.OrgId AND BM.IsInContext = 1
			) AS StatusCount,
			ISM.InquiryMainStatusId AS InquiryMainStatusId
			FROM sAdmission.tAdmissionInquiry AI 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForBatchId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
			
			LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AI.OrgId = OM.Id
			LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI.InquiryStatusId
			WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
			AND ISM.InquiryMainStatusId = 21
			--BM.IsActive = 1 
			AND((OM.Id = @rOrgId)OR(@rOrgId=0))
			And ISNULL(O.IsObsolete,0) = 0
			AND BM.IsInContext = 1
			GROUP BY OM.Id,OM.Title,ISM.Id,ISM.Title,ISM.InquiryMainStatusId,AI.OrgId
			
			UNION ALL
-- 31
-- Admission Form Submitted
			SELECT 
			ISM.Id AS InquiryStatusId,
			ISNULL(OM.Id,0) AS OrgId,
			OM.Title AS Organization,
			ISNULL(ISM.Title,'') AS StatusName,
			(
			SELECT 
			ISNULL(COUNT(ISM.Id),0) AS StatusCount 
			FROM sAdmission.tAdmissionInquiry AI1 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI1.ForBatchId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
			LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AI1.OrgId = OM.Id
			LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI1.InquiryStatusId
			WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
			AND ISM.InquiryMainStatusId > 21
			--BM.IsActive = 1 
			AND((OM.Id = @rOrgId)OR(@rOrgId=0))  AND OM.Id = AI.OrgId
			AND BM.IsInContext = 1
			) AS StatusCount ,
			ISM.InquiryMainStatusId AS InquiryMainStatusId
			FROM sAdmission.tAdmissionInquiry AI 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForBatchId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
			
			LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AI.OrgId = OM.Id
			LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI.InquiryStatusId
			WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
			AND ISM.InquiryMainStatusId =31
			--BM.IsActive = 1 
			AND((OM.Id = @rOrgId)OR(@rOrgId=0))
			And ISNULL(O.IsObsolete,0) = 0
			AND BM.IsInContext = 1
			GROUP BY OM.Id,OM.Title,ISM.Id,ISM.Title,ISM.InquiryMainStatusId,AI.OrgId
			
			UNION ALL
-- 41
-- Appeared For Entrance Exam
			SELECT 
			ISM.Id AS InquiryStatusId,
			ISNULL(OM.Id,0) AS OrgId,
			OM.Title AS Organization,
			ISNULL(ISM.Title,'') AS StatusName,
			(
			SELECT 
			ISNULL(COUNT(ISM.Id),0) AS StatusCount 
			FROM sAdmission.tAdmissionInquiry AI1 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI1.ForBatchId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
			LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AI1.OrgId = OM.Id
			LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI1.InquiryStatusId
			WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
			AND ISM.InquiryMainStatusId > 31
			--BM.IsActive = 1 
			AND((OM.Id = @rOrgId)OR(@rOrgId=0))  AND OM.Id = AI.OrgId
			AND BM.IsInContext = 1
			) AS StatusCount  ,
			ISM.InquiryMainStatusId AS InquiryMainStatusId
			FROM sAdmission.tAdmissionInquiry AI 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForBatchId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
			
			LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AI.OrgId = OM.Id
			LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI.InquiryStatusId
			WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
			AND ISM.InquiryMainStatusId =41
			--BM.IsActive = 1 
			AND((OM.Id = @rOrgId)OR(@rOrgId=0))
			And ISNULL(O.IsObsolete,0) = 0
			AND BM.IsInContext = 1
			GROUP BY OM.Id,OM.Title,ISM.Id,ISM.Title,ISM.InquiryMainStatusId,AI.OrgId
			
			UNION ALL
-- 51
-- Came for Interaction
			SELECT 
			ISM.Id AS InquiryStatusId,
			ISNULL(OM.Id,0) AS OrgId,
			OM.Title AS Organization,
			ISNULL(ISM.Title,'') AS StatusName,
			(
			SELECT 
			ISNULL(COUNT(ISM.Id),0) AS StatusCount 
			FROM sAdmission.tAdmissionInquiry AI1
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI1.ForBatchId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
			LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AI1.OrgId = OM.Id
			LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI1.InquiryStatusId
			WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
			AND ISM.InquiryMainStatusId > 41 and ISM.InquiryMainStatusId <> 61

			--BM.IsActive = 1 
			AND((OM.Id = @rOrgId)OR(@rOrgId=0)) AND OM.Id = AI.OrgId
			AND BM.IsInContext = 1
			) AS StatusCount  ,
			ISM.InquiryMainStatusId AS InquiryMainStatusId
			FROM sAdmission.tAdmissionInquiry AI 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForBatchId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
			
			LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AI.OrgId = OM.Id
			LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI.InquiryStatusId
			WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
			AND ISM.InquiryMainStatusId =51 
			--BM.IsActive = 1 
			AND((OM.Id = @rOrgId)OR(@rOrgId=0))
			And ISNULL(O.IsObsolete,0) = 0
			AND BM.IsInContext = 1
			GROUP BY OM.Id,OM.Title,ISM.Id,ISM.Title,ISM.InquiryMainStatusId,AI.OrgId
			
			UNION ALL
-- 61
-- Not Came for interaction
			SELECT 
			ISM.Id AS InquiryStatusId,
			ISNULL(OM.Id,0) AS OrgId,
			OM.Title AS Organization,
			ISNULL(ISM.Title,'') AS StatusName,
			(
			SELECT 
			ISNULL(COUNT(ISM.Id),0) AS StatusCount 
			FROM sAdmission.tAdmissionInquiry AI1
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI1.ForBatchId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
			LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AI1.OrgId = OM.Id
			LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI1.InquiryStatusId
			WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
			--AND ISM.InquiryMainStatusId > 51  AND ISM.InquiryMainStatusId !=71
			AND ISM.InquiryMainStatusId = 61

			--BM.IsActive = 1 
			AND((OM.Id = @rOrgId)OR(@rOrgId=0))  AND OM.Id = AI.OrgId
			AND BM.IsInContext = 1
			) AS StatusCount  ,
			ISM.InquiryMainStatusId AS InquiryMainStatusId
			FROM sAdmission.tAdmissionInquiry AI 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForBatchId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
			
			LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AI.OrgId = OM.Id
			LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI.InquiryStatusId
			WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
			AND ISM.InquiryMainStatusId = 61 

			--BM.IsActive = 1 
			AND((OM.Id = @rOrgId)OR(@rOrgId=0))
			And ISNULL(O.IsObsolete,0) = 0
			AND BM.IsInContext = 1
			GROUP BY OM.Id,OM.Title,ISM.Id,ISM.Title,ISM.InquiryMainStatusId,AI.OrgId
		
		    UNION ALL
			
-- 71
--Confirmed Admission

			SELECT
			ISM.Id AS InquiryStatusId, 
			ISNULL(OM.Id,0) AS OrgId,
			OM.Title AS Organization,
			ISNULL(ISM.Title,'') AS StatusName,
			(
			SELECT 
			ISNULL(COUNT(ISM.Id),0) AS StatusCount 
			FROM sAdmission.tAdmissionInquiry AI1
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI1.ForBatchId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
			LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AI1.OrgId = OM.Id
			LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI1.InquiryStatusId
			WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
			AND ISM.InquiryMainStatusId > 61 

			--BM.IsActive = 1 
			AND((OM.Id = @rOrgId)OR(@rOrgId=0))  AND OM.Id = AI.OrgId
			AND BM.IsInContext = 1
			) AS StatusCount  ,
			ISM.InquiryMainStatusId AS InquiryMainStatusId
			FROM sAdmission.tAdmissionInquiry AI 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForBatchId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
			
			LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AI.OrgId = OM.Id
			LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI.InquiryStatusId
			WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
			AND ISM.InquiryMainStatusId =71
			--BM.IsActive = 1 
			AND((OM.Id = @rOrgId)OR(@rOrgId=0))
			And ISNULL(O.IsObsolete,0) = 0
			AND BM.IsInContext = 1
			GROUP BY OM.Id,OM.Title,ISM.Id,ISM.Title,ISM.InquiryMainStatusId,AI.OrgId
			UNION ALL
-- 81
-- Rejected Form
			SELECT 
			ISM.Id AS InquiryStatusId,
			ISNULL(OM.Id,0) AS OrgId,
			OM.Title AS Organization,
			ISNULL(ISM.Title,'') AS StatusName,
			(
			SELECT 
			ISNULL(COUNT(ISM.Id),0) AS StatusCount 
			FROM sAdmission.tAdmissionInquiry AI1 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI1.ForBatchId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
			LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AI1.OrgId = OM.Id
			LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI1.InquiryStatusId
			WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
			AND ISM.InquiryMainStatusId =81
			--BM.IsActive = 1 
			AND((OM.Id = @rOrgId)OR(@rOrgId=0)) AND OM.Id = AI.OrgId
			AND BM.IsInContext = 1
			) AS StatusCount  ,
			ISM.InquiryMainStatusId AS InquiryMainStatusId
			FROM sAdmission.tAdmissionInquiry AI 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForBatchId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
			LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AI.OrgId = OM.Id
			LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI.InquiryStatusId
			WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
			AND ISM.InquiryMainStatusId =81
			--BM.IsActive = 1 
			AND((OM.Id = @rOrgId)OR(@rOrgId=0))
			And ISNULL(O.IsObsolete,0) = 0
			AND BM.IsInContext = 1
			GROUP BY OM.Id,OM.Title,ISM.Id,ISM.Title,ISM.InquiryMainStatusId,AI.OrgId
			UNION ALL
-- 91
-- Fees Paid

			SELECT 
			ISM.Id AS InquiryStatusId,
			ISNULL(OM.Id,0) AS OrgId,
			OM.Title AS Organization,
			ISNULL(ISM.Title,'') AS StatusName,
			(
			SELECT 
			ISNULL(COUNT(ISM.Id),0) AS StatusCount 
			FROM sAdmission.tAdmissionInquiry AI1 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI1.ForBatchId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
			LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AI1.OrgId = OM.Id
			LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI1.InquiryStatusId
			WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
			AND ISM.InquiryMainStatusId > 81 AND ISM.InquiryMainStatusId !=101

			--BM.IsActive = 1 
			AND((OM.Id = @rOrgId)OR(@rOrgId=0))  AND OM.Id = AI.OrgId
			AND BM.IsInContext = 1
			) AS StatusCount ,
			ISM.InquiryMainStatusId AS InquiryMainStatusId 
			FROM sAdmission.tAdmissionInquiry AI 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForBatchId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
			
			LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AI.OrgId = OM.Id
			LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI.InquiryStatusId
			WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
			AND ISM.InquiryMainStatusId =91

 
			--BM.IsActive = 1 
			AND((OM.Id = @rOrgId)OR(@rOrgId=0))
			And ISNULL(O.IsObsolete,0) = 0
			AND BM.IsInContext = 1
			GROUP BY OM.Id,OM.Title,ISM.Id,ISM.Title,ISM.InquiryMainStatusId,AI.OrgId
			UNION ALL
-- 101		
-- Fees not paid
			SELECT 
			ISM.Id AS InquiryStatusId,
			ISNULL(OM.Id,0) AS OrgId,
			OM.Title AS Organization,
			ISNULL(ISM.Title,'') AS StatusName,
			(
			SELECT 
			ISNULL(COUNT(ISM.Id),0) AS StatusCount 
			FROM sAdmission.tAdmissionInquiry AI1 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI1.ForBatchId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
			LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AI1.OrgId = OM.Id
			LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI1.InquiryStatusId
			WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
			AND ISM.InquiryMainStatusId =101
			--BM.IsActive = 1 
			AND((OM.Id = @rOrgId)OR(@rOrgId=0))AND OM.Id = AI.OrgId
			AND BM.IsInContext = 1
			) AS StatusCount ,
			ISM.InquiryMainStatusId AS InquiryMainStatusId 
			FROM sAdmission.tAdmissionInquiry AI 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForBatchId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
			LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AI.OrgId = OM.Id
			LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI.InquiryStatusId
			WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
			AND ISM.InquiryMainStatusId =101
			--BM.IsActive = 1 
			AND((OM.Id = @rOrgId)OR(@rOrgId=0))
			And ISNULL(O.IsObsolete,0) = 0
			AND BM.IsInContext = 1
			GROUP BY OM.Id,OM.Title,ISM.Id,ISM.Title,ISM.InquiryMainStatusId,AI.OrgId
			UNION ALL
-- 111			
-- Refunded Fees
			SELECT 
			ISM.Id AS InquiryStatusId,
			ISNULL(OM.Id,0) AS OrgId,
			OM.Title AS Organization,
			ISNULL(ISM.Title,'') AS StatusName,
			(
			SELECT 
			ISNULL(COUNT(ISM.Id),0) AS StatusCount 
			FROM sAdmission.tAdmissionInquiry AI1 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI1.ForBatchId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
			LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AI1.OrgId = OM.Id
			LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI1.InquiryStatusId
			WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
			AND ISM.InquiryMainStatusId > 101

			--BM.IsActive = 1 
			AND OM.OrgGroupId = @rOrgGroupId  AND OM.Id = AI.OrgId
			AND BM.IsInContext = 1
			) AS StatusCount  ,
			ISM.InquiryMainStatusId AS InquiryMainStatusId
			FROM sAdmission.tAdmissionInquiry AI 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForBatchId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
			
			LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AI.OrgId = OM.Id
			LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI.InquiryStatusId
			WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
			AND ISM.InquiryMainStatusId =111
 
			--BM.IsActive = 1 
			AND((OM.Id = @rOrgId)OR(@rOrgId=0))
			And ISNULL(O.IsObsolete,0) = 0
			AND BM.IsInContext = 1
			GROUP BY OM.Id,OM.Title,ISM.Id,ISM.Title,ISM.InquiryMainStatusId,AI.OrgId
		END
		ELSE 
		BEGIN
			SELECT 
			ISM1.Id AS InquiryStatusId,
			ISNULL(OM.Id,0) AS OrgId,
			OM.Title AS Organization,
			ISNULL(ISM1.Title,'') AS StatusName,
			ISNULL(COUNT(ISM1.Id),0) AS StatusCount, 
			ISM1.InquiryMainStatusId AS InquiryMainStatusId
			,OM.OrderIndex
			FROM sAdmission.tAdmissionInquiry AI 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForBatchId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
			LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AI.OrgId = OM.Id
			LEFT JOIN sAdmission.tInquiryStatusMaster ISM1 ON ISM1.Id = AI.InquiryStatusId
			WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
			--AND ISM.InquiryMainStatusId = 11
			--BM.IsActive = 1 
			AND((OM.Id = @rOrgId)OR(@rOrgId=0))
			And ISNULL(O.IsObsolete,0) = 0
			AND BM.IsInContext = 1
			GROUP BY OM.Id,OM.Title,ISM1.Id,ISM1.Title,ISM1.InquiryMainStatusId,AI.OrgId,OM.OrderIndex
			ORDER BY OM.OrderIndex
		END
		END
		
	IF(@rType='StatusOrgGroupWise')
		BEGIN
		IF(@lConfigValue = 'True')
		BEGIN

-- 11
-- Inquiry Form 
			SELECT 
			ISM.Id AS InquiryStatusId,
			ISNULL(OM.Id,0) AS OrgId,
			OM.Title AS Organization,
			ISNULL(ISM.Title,'') AS StatusName,
			(
			SELECT 
			ISNULL(COUNT(ISM.Id),0) AS StatusCount 
			FROM sAdmission.tAdmissionInquiry AI1 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI1.ForBatchId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
			LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AI1.OrgId = OM.Id
			LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI1.InquiryStatusId
			WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
			AND ISM.InquiryMainStatusId >= 11
			AND OM.OrgGroupId = @rOrgGroupId AND OM.Id = AI.OrgId
			AND BM.IsInContext = 1
			) AS StatusCount,
			ISNULL(ISM.InquiryMainStatusId,0) AS InquiryMainStatusId
			FROM sAdmission.tAdmissionInquiry AI 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForBatchId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
			
			LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AI.OrgId = OM.Id
			LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI.InquiryStatusId
			WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
			AND ISM.InquiryMainStatusId = 11
			--BM.IsActive = 1 
			AND OM.OrgGroupId = @rOrgGroupId
			And ISNULL(O.IsObsolete,0) = 0
			AND BM.IsInContext = 1
			GROUP BY OM.Id,OM.Title,ISM.Id,ISM.Title,ISM.InquiryMainStatusId,AI.OrgId
			
			UNION ALL
-- 21
-- Admission Form Given
			SELECT 
			ISM.Id AS InquiryStatusId,
			ISNULL(OM.Id,0) AS OrgId,
			OM.Title AS Organization,
			ISNULL(ISM.Title,'') AS StatusName,
			(
			SELECT 
			ISNULL(COUNT(ISM.Id),0) AS StatusCount 
			FROM sAdmission.tAdmissionInquiry AI1
			INNER JOIN sSetup.tClassMaster CM ON CM.Id = AI1.ForClassId
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI1.ForBatchId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
			LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AI1.OrgId = OM.Id
			LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI1.InquiryStatusId
			WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
			AND ISM.InquiryMainStatusId > 11
			--BM.IsActive = 1 
			AND OM.OrgGroupId = @rOrgGroupId AND OM.Id = AI.OrgId
			AND BM.IsInContext = 1
			) AS StatusCount,
			ISM.InquiryMainStatusId AS InquiryMainStatusId
			FROM sAdmission.tAdmissionInquiry AI 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForBatchId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
			
			LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AI.OrgId = OM.Id
			LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI.InquiryStatusId
			WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
			AND ISM.InquiryMainStatusId = 21
			--BM.IsActive = 1 
			AND OM.OrgGroupId = @rOrgGroupId
			And ISNULL(O.IsObsolete,0) = 0
			AND BM.IsInContext = 1
			GROUP BY OM.Id,OM.Title,ISM.Id,ISM.Title,ISM.InquiryMainStatusId,AI.OrgId
			
			UNION ALL
-- 31
-- Admission Form Submitted
			SELECT 
			ISM.Id AS InquiryStatusId,
			ISNULL(OM.Id,0) AS OrgId,
			OM.Title AS Organization,
			ISNULL(ISM.Title,'') AS StatusName,
			(
			SELECT 
			ISNULL(COUNT(ISM.Id),0) AS StatusCount 
			FROM sAdmission.tAdmissionInquiry AI1 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI1.ForBatchId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
			LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AI1.OrgId = OM.Id
			LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI1.InquiryStatusId
			WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
			AND ISM.InquiryMainStatusId > 21
			--BM.IsActive = 1 
			AND OM.OrgGroupId = @rOrgGroupId  AND OM.Id = AI.OrgId
			AND BM.IsInContext = 1
			) AS StatusCount ,
			ISM.InquiryMainStatusId AS InquiryMainStatusId
			FROM sAdmission.tAdmissionInquiry AI 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForBatchId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
			
			LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AI.OrgId = OM.Id
			LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI.InquiryStatusId
			WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
			AND ISM.InquiryMainStatusId =31
			--BM.IsActive = 1 
			AND OM.OrgGroupId = @rOrgGroupId
			And ISNULL(O.IsObsolete,0) = 0
			AND BM.IsInContext = 1
			GROUP BY OM.Id,OM.Title,ISM.Id,ISM.Title,ISM.InquiryMainStatusId,AI.OrgId
			
			UNION ALL
-- 41
-- Appeared For Entrance Exam
			SELECT 
			ISM.Id AS InquiryStatusId,
			ISNULL(OM.Id,0) AS OrgId,
			OM.Title AS Organization,
			ISNULL(ISM.Title,'') AS StatusName,
			(
			SELECT 
			ISNULL(COUNT(ISM.Id),0) AS StatusCount 
			FROM sAdmission.tAdmissionInquiry AI1 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI1.ForBatchId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
			LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AI1.OrgId = OM.Id
			LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI1.InquiryStatusId
			WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
			AND ISM.InquiryMainStatusId > 31
			--BM.IsActive = 1 
			AND OM.OrgGroupId = @rOrgGroupId  AND OM.Id = AI.OrgId
			AND BM.IsInContext = 1
			) AS StatusCount  ,
			ISM.InquiryMainStatusId AS InquiryMainStatusId
			FROM sAdmission.tAdmissionInquiry AI 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForBatchId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
			
			LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AI.OrgId = OM.Id
			LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI.InquiryStatusId
			WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
			AND ISM.InquiryMainStatusId =41
			--BM.IsActive = 1 
			AND OM.OrgGroupId = @rOrgGroupId
			And ISNULL(O.IsObsolete,0) = 0
			AND BM.IsInContext = 1
			GROUP BY OM.Id,OM.Title,ISM.Id,ISM.Title,ISM.InquiryMainStatusId,AI.OrgId
			
			
			
			UNION ALL
-- 51
-- Came for Interaction
			SELECT 
			ISM.Id AS InquiryStatusId,
			ISNULL(OM.Id,0) AS OrgId,
			OM.Title AS Organization,
			ISNULL(ISM.Title,'') AS StatusName,
			(
			SELECT 
			ISNULL(COUNT(ISM.Id),0) AS StatusCount 
			FROM sAdmission.tAdmissionInquiry AI1
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI1.ForBatchId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
			LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AI1.OrgId = OM.Id
			LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI1.InquiryStatusId
			WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
			AND ISM.InquiryMainStatusId > 41 and ISM.InquiryMainStatusId <> 61

			--BM.IsActive = 1 
			AND OM.OrgGroupId = @rOrgGroupId AND OM.Id = AI.OrgId
			AND BM.IsInContext = 1
			) AS StatusCount  ,
			ISM.InquiryMainStatusId AS InquiryMainStatusId
			FROM sAdmission.tAdmissionInquiry AI 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForBatchId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
			
			LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AI.OrgId = OM.Id
			LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI.InquiryStatusId
			WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
			AND ISM.InquiryMainStatusId =51 
			--BM.IsActive = 1 
			AND OM.OrgGroupId = @rOrgGroupId
			And ISNULL(O.IsObsolete,0) = 0
			AND BM.IsInContext = 1
			GROUP BY OM.Id,OM.Title,ISM.Id,ISM.Title,ISM.InquiryMainStatusId,AI.OrgId
			
			UNION ALL
-- 61
-- Not Came for interaction
			SELECT 
			ISM.Id AS InquiryStatusId,
			ISNULL(OM.Id,0) AS OrgId,
			OM.Title AS Organization,
			ISNULL(ISM.Title,'') AS StatusName,
			(
			SELECT 
			ISNULL(COUNT(ISM.Id),0) AS StatusCount 
			FROM sAdmission.tAdmissionInquiry AI1
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI1.ForBatchId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
			LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AI1.OrgId = OM.Id
			LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI1.InquiryStatusId
			WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
			--AND ISM.InquiryMainStatusId > 51  AND ISM.InquiryMainStatusId !=71
			AND ISM.InquiryMainStatusId = 61

			--BM.IsActive = 1 
			AND OM.OrgGroupId = @rOrgGroupId  AND OM.Id = AI.OrgId
			AND BM.IsInContext = 1
			) AS StatusCount  ,
			ISM.InquiryMainStatusId AS InquiryMainStatusId
			FROM sAdmission.tAdmissionInquiry AI 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForBatchId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
			
			LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AI.OrgId = OM.Id
			LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI.InquiryStatusId
			WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
			AND ISM.InquiryMainStatusId = 61 

			--BM.IsActive = 1 
			AND OM.OrgGroupId = @rOrgGroupId
			And ISNULL(O.IsObsolete,0) = 0
			AND BM.IsInContext = 1
			GROUP BY OM.Id,OM.Title,ISM.Id,ISM.Title,ISM.InquiryMainStatusId,AI.OrgId
		
		UNION ALL
			
-- 71
--Confirmed Admission

			SELECT
			ISM.Id AS InquiryStatusId, 
			ISNULL(OM.Id,0) AS OrgId,
			OM.Title AS Organization,
			ISNULL(ISM.Title,'') AS StatusName,
			(
			SELECT 
			ISNULL(COUNT(ISM.Id),0) AS StatusCount 
			FROM sAdmission.tAdmissionInquiry AI1
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI1.ForBatchId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
			LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AI1.OrgId = OM.Id
			LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI1.InquiryStatusId
			WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
			AND ISM.InquiryMainStatusId > 61 

			--BM.IsActive = 1 
			AND OM.OrgGroupId = @rOrgGroupId  AND OM.Id = AI.OrgId
			AND BM.IsInContext = 1
			) AS StatusCount  ,
			ISM.InquiryMainStatusId AS InquiryMainStatusId
			FROM sAdmission.tAdmissionInquiry AI 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForBatchId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
			
			LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AI.OrgId = OM.Id
			LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI.InquiryStatusId
			WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
			AND ISM.InquiryMainStatusId =71
			--BM.IsActive = 1 
			AND OM.OrgGroupId = @rOrgGroupId
			And ISNULL(O.IsObsolete,0) = 0
			AND BM.IsInContext = 1
			GROUP BY OM.Id,OM.Title,ISM.Id,ISM.Title,ISM.InquiryMainStatusId,AI.OrgId
			UNION ALL
-- 81
-- Rejected Form
			SELECT 
			ISM.Id AS InquiryStatusId,
			ISNULL(OM.Id,0) AS OrgId,
			OM.Title AS Organization,
			ISNULL(ISM.Title,'') AS StatusName,
			(
			SELECT 
			ISNULL(COUNT(ISM.Id),0) AS StatusCount 
			FROM sAdmission.tAdmissionInquiry AI1 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI1.ForBatchId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
			LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AI1.OrgId = OM.Id
			LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI1.InquiryStatusId
			WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
			AND ISM.InquiryMainStatusId =81
			--BM.IsActive = 1 
			AND OM.OrgGroupId = @rOrgGroupId  AND OM.Id = AI.OrgId
			AND BM.IsInContext = 1
			) AS StatusCount  ,
			ISM.InquiryMainStatusId AS InquiryMainStatusId
			FROM sAdmission.tAdmissionInquiry AI 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForBatchId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
			LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AI.OrgId = OM.Id
			LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI.InquiryStatusId
			WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
			AND ISM.InquiryMainStatusId =81
			--BM.IsActive = 1 
			AND OM.OrgGroupId = @rOrgGroupId
			And ISNULL(O.IsObsolete,0) = 0
			AND BM.IsInContext = 1
			GROUP BY OM.Id,OM.Title,ISM.Id,ISM.Title,ISM.InquiryMainStatusId,AI.OrgId
			UNION ALL
-- 91
-- Fees Paid

			SELECT 
			ISM.Id AS InquiryStatusId,
			ISNULL(OM.Id,0) AS OrgId,
			OM.Title AS Organization,
			ISNULL(ISM.Title,'') AS StatusName,
			(
			SELECT 
			ISNULL(COUNT(ISM.Id),0) AS StatusCount 
			FROM sAdmission.tAdmissionInquiry AI1 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI1.ForBatchId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
			LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AI1.OrgId = OM.Id
			LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI1.InquiryStatusId
			WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
			AND ISM.InquiryMainStatusId > 81 AND ISM.InquiryMainStatusId !=101

			--BM.IsActive = 1 
			AND OM.OrgGroupId = @rOrgGroupId  AND OM.Id = AI.OrgId
			AND BM.IsInContext = 1
			) AS StatusCount ,
			ISM.InquiryMainStatusId AS InquiryMainStatusId 
			FROM sAdmission.tAdmissionInquiry AI 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForBatchId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
			
			LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AI.OrgId = OM.Id
			LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI.InquiryStatusId
			WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
			AND ISM.InquiryMainStatusId =91

 
			--BM.IsActive = 1 
			AND OM.OrgGroupId = @rOrgGroupId
			And ISNULL(O.IsObsolete,0) = 0
			AND BM.IsInContext = 1
			GROUP BY OM.Id,OM.Title,ISM.Id,ISM.Title,ISM.InquiryMainStatusId,AI.OrgId
			UNION ALL
-- 101		
-- Fees not paid
			SELECT 
			ISM.Id AS InquiryStatusId,
			ISNULL(OM.Id,0) AS OrgId,
			OM.Title AS Organization,
			ISNULL(ISM.Title,'') AS StatusName,
			(
			SELECT 
			ISNULL(COUNT(ISM.Id),0) AS StatusCount 
			FROM sAdmission.tAdmissionInquiry AI1 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI1.ForBatchId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
			LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AI1.OrgId = OM.Id
			LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI1.InquiryStatusId
			WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
			AND ISM.InquiryMainStatusId =101
			--BM.IsActive = 1 
			AND OM.OrgGroupId = @rOrgGroupId AND OM.Id = AI.OrgId
			AND BM.IsInContext = 1
			) AS StatusCount ,
			ISM.InquiryMainStatusId AS InquiryMainStatusId 
			FROM sAdmission.tAdmissionInquiry AI 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForBatchId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
			LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AI.OrgId = OM.Id
			LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI.InquiryStatusId
			WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
			AND ISM.InquiryMainStatusId =101
			--BM.IsActive = 1 
			AND OM.OrgGroupId = @rOrgGroupId
			And ISNULL(O.IsObsolete,0) = 0
			AND BM.IsInContext = 1
			GROUP BY OM.Id,OM.Title,ISM.Id,ISM.Title,ISM.InquiryMainStatusId,AI.OrgId
			UNION ALL
-- 111			
-- Refunded Fees
			SELECT 
			ISM.Id AS InquiryStatusId,
			ISNULL(OM.Id,0) AS OrgId,
			OM.Title AS Organization,
			ISNULL(ISM.Title,'') AS StatusName,
			(
			SELECT 
			ISNULL(COUNT(ISM.Id),0) AS StatusCount 
			FROM sAdmission.tAdmissionInquiry AI1 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI1.ForBatchId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
			LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AI1.OrgId = OM.Id
			LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI1.InquiryStatusId
			WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
			AND ISM.InquiryMainStatusId > 101

			--BM.IsActive = 1 
			AND OM.OrgGroupId = @rOrgGroupId  AND OM.Id = AI.OrgId
			AND BM.IsInContext = 1
			) AS StatusCount  ,
			ISM.InquiryMainStatusId AS InquiryMainStatusId
			FROM sAdmission.tAdmissionInquiry AI 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForBatchId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
			
			LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AI.OrgId = OM.Id
			LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI.InquiryStatusId
			WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
			AND ISM.InquiryMainStatusId =111
 
			--BM.IsActive = 1 
			AND OM.OrgGroupId = @rOrgGroupId
			And ISNULL(O.IsObsolete,0) = 0
			AND BM.IsInContext = 1
			GROUP BY OM.Id,OM.Title,ISM.Id,ISM.Title,ISM.InquiryMainStatusId,AI.OrgId
		 END
		 ELSE
		 BEGIN
			SELECT 
			ISM1.Id AS InquiryStatusId,
			ISNULL(OM.Id,0) AS OrgId,
			OM.Title AS Organization,
			ISNULL(ISM1.Title,'') AS StatusName,
			ISNULL(COUNT(ISM1.Id),0) AS StatusCount,
			ISNULL(ISM1.InquiryMainStatusId,0) AS InquiryMainStatusId
			,OM.OrderIndex
			FROM sAdmission.tAdmissionInquiry AI 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForBatchId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
			
			LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AI.OrgId = OM.Id
			LEFT JOIN sAdmission.tInquiryStatusMaster ISM1 ON ISM1.Id = AI.InquiryStatusId
			WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
			--AND ISM.InquiryMainStatusId = 11
			--BM.IsActive = 1 
			AND OM.OrgGroupId = @rOrgGroupId
			And ISNULL(O.IsObsolete,0) = 0
			AND BM.IsInContext = 1
			GROUP BY OM.Id,OM.Title,ISM1.Id,ISM1.Title,ISM1.InquiryMainStatusId,AI.OrgId,OM.OrderIndex
			ORDER BY OM.OrderIndex
		 END
		END

	IF(@rType='StatusClassWise')
		BEGIN
				IF(@lConfigValue = 'True')
				BEGIN

				DECLARE @lInquiryMainStatus nvarchar(500)='' 
				IF(@rInquiryMainStatus=11)
				SET  @lInquiryMainStatus = 'AND ISM.InquiryMainStatusId >= 11'
				ELSE IF(@rInquiryMainStatus=21)
				SET  @lInquiryMainStatus = 'AND ISM.InquiryMainStatusId > 11'
				ELSE IF(@rInquiryMainStatus=31)
				SET  @lInquiryMainStatus ='AND ISM.InquiryMainStatusId > 21'
				ELSE IF(@rInquiryMainStatus=41)
				SET  @lInquiryMainStatus ='AND ISM.InquiryMainStatusId > 31'
				ELSE IF(@rInquiryMainStatus=51)
				SET  @lInquiryMainStatus ='AND ISM.InquiryMainStatusId > 41 and ISM.InquiryMainStatusId <> 61'
				ELSE IF(@rInquiryMainStatus=61)
				SET  @lInquiryMainStatus ='AND ISM.InquiryMainStatusId = 61 '
				ELSE IF(@rInquiryMainStatus=71)
				SET  @lInquiryMainStatus ='AND ISM.InquiryMainStatusId > 61'
				ELSE IF(@rInquiryMainStatus=81)
				SET  @lInquiryMainStatus ='AND ISM.InquiryMainStatusId = 81'
				ELSE IF(@rInquiryMainStatus=91)
				SET  @lInquiryMainStatus ='AND ISM.InquiryMainStatusId > 81 AND ISM.InquiryMainStatusId !=101'
				ELSE IF(@rInquiryMainStatus=101)
				SET  @lInquiryMainStatus ='AND ISM.InquiryMainStatusId = 101'
				ELSE IF(@rInquiryMainStatus=111)
				SET  @lInquiryMainStatus ='AND ISM.InquiryMainStatusId > 101'
				ELSE IF(@rInquiryMainStatus = 0)
				SET  @lInquiryMainStatus ='AND ISM.InquiryMainStatusId = 0'


				DECLARE @lSQLString nvarchar(max)=''

				SET @lSQLString = 'DECLARE @lTempOrgBatchOrder TABLE( OrgId int, BatchOrderIndex int)
						INSERT INTO @lTempOrgBatchOrder ( OrgId,BatchOrderIndex )
						SELECT OM.Id AS OrgId, MAX(BM.OrderIndex) AS BatchOrderIndex
						FROM
							sSetup.tOrganizationMaster OM
							INNER JOIN sSetup.tBatchMaster BM ON BM.OrgId = OM.Id
							INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
							INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
						WHERE 
							((OM.OrgGroupId='+CONVERT(nvarchar(20),@rOrgGroupId)+') OR ('+CONVERT(nvarchar(20),@rOrgGroupId)+' = 0))
							AND BM.IsObsolete = 0  AND COGBM.Id='+CONVERT(nvarchar(20),@rCommonOrgGroupBatchId)+'
							AND BM.IsInContext = 1
						GROUP BY
							OM.Id
		
						DECLARE @lTempBatchId TABLE(OrgId int, BatchId int)
						INSERT INTO @lTempBatchId (OrgId , BatchId)
						SELECT 
							BM.OrgId AS OrgId,
							BM.Id AS BatchId
						FROM 
							sSetup.tBatchMaster BM
							INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
							INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
		 
							INNER JOIN @lTempOrgBatchOrder BO ON BO.OrgId = BM.OrgId
						WHERE
							BO.BatchOrderIndex = BM.OrderIndex  AND COGBM.Id='+CONVERT(nvarchar(20),@rCommonOrgGroupBatchId)+'
							AND BM.IsInContext = 1

						SELECT 
							AI2.ForClassId AS ClassId,CM.Title AS ClassName,CM.OrderIndex,
							(SELECT ISNULL(COUNT(ISM.Id),0) AS StatusCount 
							FROM sAdmission.tAdmissionInquiry AI 
							INNER JOIN sSetup.tClassMaster CM ON CM.Id = AI.ForClassId
							INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForBatchId
							INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
							INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
							INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
							LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
							INNER JOIN sSetup.tOrganizationMaster OM ON AI.OrgId = OM.Id
							LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI.InquiryStatusId
							WHERE BM.Id = TB.BatchId AND COGBM.Id='+CONVERT(nvarchar(20),@rCommonOrgGroupBatchId)+'
								'+CONVERT(nvarchar(500),@lInquiryMainStatus)+' and AI2.ForClassId = CM.Id
							AND BM.IsInContext = 1
							--BM.IsActive = 1 And ISNULL(O.IsObsolete,0) = 0
							AND ((OM.OrgGroupId = '+CONVERT(nvarchar(20),@rOrgGroupId)+' )OR('+CONVERT(nvarchar(20),@rOrgGroupId)+'=0)))
							AS StatusCount
						FROM 
							sAdmission.tAdmissionInquiry AI2
							INNER JOIN sSetup.tClassMaster CM ON CM.Id = AI2.ForClassId
							INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI2.ForBatchId
							LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
							LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI2.InquiryStatusId
						WHERE BM.Id = TB.BatchId 
						--and OM.OrgId = @rOrgId
							--and Ai2.ForClassId = CM.Id
							--AND COGBM.Id=1
							AND BM.IsInContext = 1
							AND ((CM.OrgId = '+CONVERT(nvarchar(20),@rOrgId)+' )OR('+CONVERT(nvarchar(20),@rOrgId)+'=0))
							'+CONVERT(nvarchar(500),@lInquiryMainStatus)+'
						Group BY 
							AI2.ForClassId,CM.Title,CM.OrderIndex '

						print @lSQLString

						execute(@lSQLString)
				END
				ELSE 
				BEGIN
						DECLARE @lSQLString1 nvarchar(max)=''

						SET @lSQLString1 = 'DECLARE @lTempOrgBatchOrder TABLE( OrgId int, BatchOrderIndex int)
						INSERT INTO @lTempOrgBatchOrder ( OrgId,BatchOrderIndex )
						SELECT OM.Id AS OrgId, MAX(BM.OrderIndex) AS BatchOrderIndex
						FROM
							sSetup.tOrganizationMaster OM
							INNER JOIN sSetup.tBatchMaster BM ON BM.OrgId = OM.Id
							INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
							INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
						WHERE 
							((OM.OrgGroupId='+CONVERT(nvarchar(20),@rOrgGroupId)+') OR ('+CONVERT(nvarchar(20),@rOrgGroupId)+' = 0))
							AND BM.IsObsolete = 0  AND COGBM.Id='+CONVERT(nvarchar(20),@rCommonOrgGroupBatchId)+'
							AND BM.IsInContext = 1
						GROUP BY
							OM.Id
		
						DECLARE @lTempBatchId TABLE(OrgId int, BatchId int)
						INSERT INTO @lTempBatchId (OrgId , BatchId)
						SELECT 
							BM.OrgId AS OrgId,
							BM.Id AS BatchId
						FROM 
							sSetup.tBatchMaster BM
							INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
							INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
		 
							INNER JOIN @lTempOrgBatchOrder BO ON BO.OrgId = BM.OrgId
						WHERE
							BO.BatchOrderIndex = BM.OrderIndex  AND COGBM.Id='+CONVERT(nvarchar(20),@rCommonOrgGroupBatchId)+'
							AND BM.IsInContext = 1
						SELECT 
							AI2.ForClassId AS ClassId,CM.Title AS ClassName,CM.OrderIndex,
							(SELECT ISNULL(COUNT(ISM.Id),0) AS StatusCount 
							FROM sAdmission.tAdmissionInquiry AI 
							INNER JOIN sSetup.tClassMaster CM ON CM.Id = AI.ForClassId
							INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForBatchId
							INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
							INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
							INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
							LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
							INNER JOIN sSetup.tOrganizationMaster OM ON AI.OrgId = OM.Id
							LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI.InquiryStatusId
							WHERE BM.Id = TB.BatchId AND COGBM.Id='+CONVERT(nvarchar(20),@rCommonOrgGroupBatchId)+'
								and ISM.InquiryMainStatusId = ISM1.InquiryMainStatusId and AI2.ForClassId = CM.Id
							--BM.IsActive = 1 And ISNULL(O.IsObsolete,0) = 0
							AND BM.IsInContext = 1
							AND ((OM.OrgGroupId = '+CONVERT(nvarchar(20),@rOrgGroupId)+' )OR('+CONVERT(nvarchar(20),@rOrgGroupId)+'=0)))
							AS StatusCount
						FROM 
							sAdmission.tAdmissionInquiry AI2
							INNER JOIN sSetup.tClassMaster CM ON CM.Id = AI2.ForClassId
							INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI2.ForBatchId
							LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
							LEFT JOIN sAdmission.tInquiryStatusMaster ISM1 ON ISM1.Id = AI2.InquiryStatusId
						WHERE BM.Id = TB.BatchId 
						--and OM.OrgId = @rOrgId
							--and Ai2.ForClassId = CM.Id
							--AND COGBM.Id=1
							AND ISM1.InquiryMainStatusId  = '+CONVERT(nvarchar(20),@rInquiryMainStatus)+'
							AND ((CM.OrgId = '+CONVERT(nvarchar(20),@rOrgId)+' )OR('+CONVERT(nvarchar(20),@rOrgId)+'=0))
							AND BM.IsInContext = 1
						Group BY 
							AI2.ForClassId,CM.Title,CM.OrderIndex,ISM1.InquiryMainStatusId'

						print @lSQLString1

						execute(@lSQLString1)
				END
			END

	ELSE IF(@rType='StatusStudentList')
		BEGIN
				IF(@lConfigValue = 'True')
				BEGIN

				DECLARE @lInquiryMainStatusStudent nvarchar(500)='' 
				IF(@rInquiryMainStatus=11)
				SET  @lInquiryMainStatusStudent = 'AND ISM.InquiryMainStatusId >=11'
				ELSE IF(@rInquiryMainStatus=21)
				SET  @lInquiryMainStatusStudent = 'AND ISM.InquiryMainStatusId > 11'
				ELSE IF(@rInquiryMainStatus=31)
				SET  @lInquiryMainStatusStudent ='AND ISM.InquiryMainStatusId > 21'
				ELSE IF(@rInquiryMainStatus=41)
				SET  @lInquiryMainStatusStudent ='AND ISM.InquiryMainStatusId > 31'
				ELSE IF(@rInquiryMainStatus=51)
				SET  @lInquiryMainStatusStudent ='AND ISM.InquiryMainStatusId > 41 and ISM.InquiryMainStatusId <> 61'
				ELSE IF(@rInquiryMainStatus=61)
				SET  @lInquiryMainStatusStudent ='AND ISM.InquiryMainStatusId > 51 AND ISM.InquiryMainStatusId !=71'
				ELSE IF(@rInquiryMainStatus=71)
				SET  @lInquiryMainStatusStudent ='AND ISM.InquiryMainStatusId > 61'
				ELSE IF(@rInquiryMainStatus=81)
				SET  @lInquiryMainStatusStudent ='AND ISM.InquiryMainStatusId > 71 AND ISM.InquiryMainStatusId !=91'
				ELSE IF(@rInquiryMainStatus=91)
				SET  @lInquiryMainStatusStudent ='AND ISM.InquiryMainStatusId > 81 AND ISM.InquiryMainStatusId !=101'
				ELSE IF(@rInquiryMainStatus=101)
				SET  @lInquiryMainStatusStudent ='AND ISM.InquiryMainStatusId > 91 AND ISM.InquiryMainStatusId !=111'
				ELSE IF(@rInquiryMainStatus=111)
				SET  @lInquiryMainStatusStudent ='AND ISM.InquiryMainStatusId > 101'
				ELSE IF(@rInquiryMainStatus=0)
				SET  @lInquiryMainStatusStudent ='AND ISM.InquiryMainStatusId = 0'

				DECLARE @lSQLStduentList nvarchar(max)=''

				SET @lSQLStduentList = 'DECLARE @lTempOrgBatchOrder TABLE( OrgId int, BatchOrderIndex int)
						INSERT INTO @lTempOrgBatchOrder ( OrgId,BatchOrderIndex )
						SELECT OM.Id AS OrgId, MAX(BM.OrderIndex) AS BatchOrderIndex
						FROM
							sSetup.tOrganizationMaster OM
							INNER JOIN sSetup.tBatchMaster BM ON BM.OrgId = OM.Id
							INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
							INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
						WHERE 
							((OM.OrgGroupId='+CONVERT(nvarchar(20),@rOrgGroupId)+') OR ('+CONVERT(nvarchar(20),@rOrgGroupId)+' = 0))
							AND BM.IsObsolete = 0 AND COGBM.Id='+CONVERT(nvarchar(20),@rCommonOrgGroupBatchId)+'
							AND BM.IsInContext = 1
						GROUP BY
							OM.Id
		
						DECLARE @lTempBatchId TABLE(OrgId int, BatchId int)
						INSERT INTO @lTempBatchId (OrgId , BatchId)
						SELECT 
							BM.OrgId AS OrgId,
							BM.Id AS BatchId
						FROM 
							sSetup.tBatchMaster BM
							INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
							INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
							--INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
							INNER JOIN @lTempOrgBatchOrder BO ON BO.OrgId = BM.OrgId
						WHERE
							BO.BatchOrderIndex = BM.OrderIndex  AND COGBM.Id='+CONVERT(nvarchar(20),@rCommonOrgGroupBatchId)+'
							AND BM.IsInContext = 1
		
							SELECT AI.Number As InquiryId, AI.FirstName+ SPACE(1) +AI.MiddleName +SPACE(1) +AI.LastName AS StudentName,AI.ContactNo AS ContactNo FROM 
								sAdmission.tAdmissionInquiry AI 
								INNER JOIN sSetup.tClassMaster CM ON CM.Id = AI.ForClassId
								INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForBatchId
								INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
								INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
								INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
			
				
								LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
								INNER JOIN sSetup.tOrganizationMaster OM ON AI.OrgId = OM.Id
								LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI.InquiryStatusId --AND((ISM.Id = '+CONVERT(nvarchar(20),@rInquiryStatusId)+')OR('+CONVERT(nvarchar(20),@rInquiryStatusId)+'=0))
								WHERE BM.Id = TB.BatchId AND COGBM.Id='+CONVERT(nvarchar(20),@rCommonOrgGroupBatchId)+'
								'+CONVERT(nvarchar(500),@lInquiryMainStatusStudent)+'
								AND ((OM.OrgGroupId = '+CONVERT(nvarchar(20),@rOrgGroupId)+' )OR('+CONVERT(nvarchar(20),@rOrgGroupId)+'=0)) 
			
								AND((CM.OrgId = '+CONVERT(nvarchar(20),@rOrgId)+')OR('+CONVERT(nvarchar(20),@rOrgId)+'=0))
								AND((CM.Id ='+CONVERT(nvarchar(20),@rClassId)+' )OR('+CONVERT(nvarchar(20),@rClassId)+'=0))
								AND BM.IsInContext = 1
								GROUP BY AI.FirstName,AI.MiddleName,AI.LastName,AI.ContactNo,AI.Number'

					--print @lSQLStduentList

					execute(@lSQLStduentList)

					END
					ELSE
					BEGIN	
						DECLARE @lSQLStduentList1 nvarchar(max)=''

						SET @lSQLStduentList1 = 'DECLARE @lTempOrgBatchOrder TABLE( OrgId int, BatchOrderIndex int)
								INSERT INTO @lTempOrgBatchOrder ( OrgId,BatchOrderIndex )
								SELECT OM.Id AS OrgId, MAX(BM.OrderIndex) AS BatchOrderIndex
								FROM
									sSetup.tOrganizationMaster OM
									INNER JOIN sSetup.tBatchMaster BM ON BM.OrgId = OM.Id
									INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
									INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
								WHERE 
									((OM.OrgGroupId='+CONVERT(nvarchar(20),@rOrgGroupId)+') OR ('+CONVERT(nvarchar(20),@rOrgGroupId)+' = 0))
									AND BM.IsObsolete = 0 AND COGBM.Id='+CONVERT(nvarchar(20),@rCommonOrgGroupBatchId)+'
									AND BM.IsInContext = 1
								GROUP BY
									OM.Id
		
								DECLARE @lTempBatchId TABLE(OrgId int, BatchId int)
								INSERT INTO @lTempBatchId (OrgId , BatchId)
								SELECT 
									BM.OrgId AS OrgId,
									BM.Id AS BatchId
								FROM 
									sSetup.tBatchMaster BM
									INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
									INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
									--INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
									INNER JOIN @lTempOrgBatchOrder BO ON BO.OrgId = BM.OrgId
								WHERE
									BO.BatchOrderIndex = BM.OrderIndex  AND COGBM.Id='+CONVERT(nvarchar(20),@rCommonOrgGroupBatchId)+'
									AND BM.IsInContext = 1
		
		
									SELECT AI.Number As InquiryId, AI.FirstName+ SPACE(1) +AI.MiddleName +SPACE(1) +AI.LastName AS StudentName,AI.ContactNo AS ContactNo FROM 
										sAdmission.tAdmissionInquiry AI 
										INNER JOIN sSetup.tClassMaster CM ON CM.Id = AI.ForClassId
										INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForBatchId
										INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
										INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
										INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
			
				
										LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
										INNER JOIN sSetup.tOrganizationMaster OM ON AI.OrgId = OM.Id
										LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI.InquiryStatusId --AND((ISM.Id = '+CONVERT(nvarchar(20),@rInquiryStatusId)+')OR('+CONVERT(nvarchar(20),@rInquiryStatusId)+'=0))
										WHERE BM.Id = TB.BatchId AND COGBM.Id='+CONVERT(nvarchar(20),@rCommonOrgGroupBatchId)+'
										 AND ISM.InquiryMainStatusId = '+CONVERT(nvarchar(20),@rInquiryMainStatus)+'
										AND ((OM.OrgGroupId = '+CONVERT(nvarchar(20),@rOrgGroupId)+' )OR('+CONVERT(nvarchar(20),@rOrgGroupId)+'=0)) 
			
										AND((CM.OrgId = '+CONVERT(nvarchar(20),@rOrgId)+')OR('+CONVERT(nvarchar(20),@rOrgId)+'=0))
										AND((CM.Id ='+CONVERT(nvarchar(20),@rClassId)+' )OR('+CONVERT(nvarchar(20),@rClassId)+'=0))
										AND BM.IsInContext = 1
										GROUP BY AI.FirstName,AI.MiddleName,AI.LastName,AI.ContactNo,AI.Number'

					print @lSQLStduentList1

						execute(@lSQLStduentList1)
			END
		END

    ELSE IF(@rType='NotDoneStatusClassWise')
		BEGIN
				IF(@lConfigValue = 'True')
				BEGIN

				DECLARE @lInqMainStatus nvarchar(500)='' 
				SET  @lInqMainStatus = 'AND ISM.Id =' + CONVERT(nvarchar,@rInquiryStatusId)
				--IF(@rInquiryMainStatus=11)
				--SET  @lInquiryMainStatus = 'AND ISM.InquiryMainStatusId >= 11'
				--ELSE IF(@rInquiryMainStatus=21)
				--SET  @lInquiryMainStatus = 'AND ISM.InquiryMainStatusId > 11'
				--ELSE IF(@rInquiryMainStatus=31)
				--SET  @lInquiryMainStatus ='AND ISM.InquiryMainStatusId > 21'
				--ELSE IF(@rInquiryMainStatus=41)
				--SET  @lInquiryMainStatus ='AND ISM.InquiryMainStatusId > 31'
				--ELSE IF(@rInquiryMainStatus=51)
				--SET  @lInquiryMainStatus ='AND ISM.InquiryMainStatusId > 41 and ISM.InquiryMainStatusId <> 61'
				--ELSE IF(@rInquiryMainStatus=61)
				--SET  @lInquiryMainStatus ='AND ISM.InquiryMainStatusId = 61 '
				--ELSE IF(@rInquiryMainStatus=71)
				--SET  @lInquiryMainStatus ='AND ISM.InquiryMainStatusId > 61'
				--ELSE IF(@rInquiryMainStatus=81)
				--SET  @lInquiryMainStatus ='AND ISM.InquiryMainStatusId = 81'
				--ELSE IF(@rInquiryMainStatus=91)
				--SET  @lInquiryMainStatus ='AND ISM.InquiryMainStatusId > 81 AND ISM.InquiryMainStatusId !=101'
				--ELSE IF(@rInquiryMainStatus=101)
				--SET  @lInquiryMainStatus ='AND ISM.InquiryMainStatusId = 101'
				--ELSE IF(@rInquiryMainStatus=111)
				--SET  @lInquiryMainStatus ='AND ISM.InquiryMainStatusId > 101'


				DECLARE @lSQLString3 nvarchar(max)=''

				SET @lSQLString3 = 'DECLARE @lTempOrgBatchOrder TABLE( OrgId int, BatchOrderIndex int)
						INSERT INTO @lTempOrgBatchOrder ( OrgId,BatchOrderIndex )
						SELECT OM.Id AS OrgId, MAX(BM.OrderIndex) AS BatchOrderIndex
						FROM
							sSetup.tOrganizationMaster OM
							INNER JOIN sSetup.tBatchMaster BM ON BM.OrgId = OM.Id
							INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
							INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
						WHERE 
							((OM.OrgGroupId='+CONVERT(nvarchar(20),@rOrgGroupId)+') OR ('+CONVERT(nvarchar(20),@rOrgGroupId)+' = 0))
							AND BM.IsObsolete = 0  AND COGBM.Id='+CONVERT(nvarchar(20),@rCommonOrgGroupBatchId)+'
							AND BM.IsInContext = 1
						GROUP BY
							OM.Id
		
						DECLARE @lTempBatchId TABLE(OrgId int, BatchId int)
						INSERT INTO @lTempBatchId (OrgId , BatchId)
						SELECT 
							BM.OrgId AS OrgId,
							BM.Id AS BatchId
						FROM 
							sSetup.tBatchMaster BM
							INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
							INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
		 
							INNER JOIN @lTempOrgBatchOrder BO ON BO.OrgId = BM.OrgId
						WHERE
							BO.BatchOrderIndex = BM.OrderIndex  AND COGBM.Id='+CONVERT(nvarchar(20),@rCommonOrgGroupBatchId)+'
							AND BM.IsInContext = 1

						SELECT 
							AI2.ForClassId AS ClassId,CM.Title AS ClassName,CM.OrderIndex,
							(SELECT ISNULL(COUNT(ISM.Id),0) AS StatusCount 
							FROM sAdmission.tAdmissionInquiry AI 
							INNER JOIN sSetup.tClassMaster CM ON CM.Id = AI.ForClassId
							INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForBatchId
							INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
							INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
							INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
							LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
							INNER JOIN sSetup.tOrganizationMaster OM ON AI.OrgId = OM.Id
							LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI.InquiryStatusId
							WHERE BM.Id = TB.BatchId AND COGBM.Id='+CONVERT(nvarchar(20),@rCommonOrgGroupBatchId)+'
								'+CONVERT(nvarchar(500),@lInqMainStatus)+' and AI2.ForClassId = CM.Id
							--BM.IsActive = 1 And ISNULL(O.IsObsolete,0) = 0
							AND BM.IsInContext = 1
							AND ((OM.OrgGroupId = '+CONVERT(nvarchar(20),@rOrgGroupId)+' )OR('+CONVERT(nvarchar(20),@rOrgGroupId)+'=0)))
							AS StatusCount
						FROM 
							sAdmission.tAdmissionInquiry AI2
							INNER JOIN sSetup.tClassMaster CM ON CM.Id = AI2.ForClassId
							INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI2.ForBatchId
							LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
							LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI2.InquiryStatusId
						WHERE BM.Id = TB.BatchId 
						--and OM.OrgId = @rOrgId
							--and Ai2.ForClassId = CM.Id
							--AND COGBM.Id=1
							AND ((CM.OrgId = '+CONVERT(nvarchar(20),@rOrgId)+' )OR('+CONVERT(nvarchar(20),@rOrgId)+'=0))
							'+CONVERT(nvarchar(500),@lInqMainStatus)+'
							AND BM.IsInContext = 1
						Group BY 
							AI2.ForClassId,CM.Title,CM.OrderIndex '

						print @lSQLString3

						execute(@lSQLString3)
				END
				ELSE 
				BEGIN
						DECLARE @lSQLString4 nvarchar(max)=''

						SET @lSQLString4 = 'DECLARE @lTempOrgBatchOrder TABLE( OrgId int, BatchOrderIndex int)
						INSERT INTO @lTempOrgBatchOrder ( OrgId,BatchOrderIndex )
						SELECT OM.Id AS OrgId, MAX(BM.OrderIndex) AS BatchOrderIndex
						FROM
							sSetup.tOrganizationMaster OM
							INNER JOIN sSetup.tBatchMaster BM ON BM.OrgId = OM.Id
							INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
							INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
						WHERE 
							((OM.OrgGroupId='+CONVERT(nvarchar(20),@rOrgGroupId)+') OR ('+CONVERT(nvarchar(20),@rOrgGroupId)+' = 0))
							AND BM.IsObsolete = 0  AND COGBM.Id='+CONVERT(nvarchar(20),@rCommonOrgGroupBatchId)+'
							AND BM.IsInContext = 1
						GROUP BY
							OM.Id
		
						DECLARE @lTempBatchId TABLE(OrgId int, BatchId int)
						INSERT INTO @lTempBatchId (OrgId , BatchId)
						SELECT 
							BM.OrgId AS OrgId,
							BM.Id AS BatchId
						FROM 
							sSetup.tBatchMaster BM
							INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
							INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
		 
							INNER JOIN @lTempOrgBatchOrder BO ON BO.OrgId = BM.OrgId
						WHERE
							BO.BatchOrderIndex = BM.OrderIndex  AND COGBM.Id='+CONVERT(nvarchar(20),@rCommonOrgGroupBatchId)+'
							AND BM.IsInContext = 1

						SELECT 
							AI2.ForClassId AS ClassId,CM.Title AS ClassName,CM.OrderIndex,
							(SELECT ISNULL(COUNT(ISM.Id),0) AS StatusCount 
							FROM sAdmission.tAdmissionInquiry AI 
							INNER JOIN sSetup.tClassMaster CM ON CM.Id = AI.ForClassId
							INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForBatchId
							INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
							INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
							INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
							LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
							INNER JOIN sSetup.tOrganizationMaster OM ON AI.OrgId = OM.Id
							LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI.InquiryStatusId
							WHERE BM.Id = TB.BatchId AND COGBM.Id='+CONVERT(nvarchar(20),@rCommonOrgGroupBatchId)+'
								and ISM.InquiryMainStatusId = ISM1.InquiryMainStatusId and AI2.ForClassId = CM.Id
							--BM.IsActive = 1 And ISNULL(O.IsObsolete,0) = 0
							AND BM.IsInContext = 1
							AND ((OM.OrgGroupId = '+CONVERT(nvarchar(20),@rOrgGroupId)+' )OR('+CONVERT(nvarchar(20),@rOrgGroupId)+'=0)))
							AS StatusCount
						FROM 
							sAdmission.tAdmissionInquiry AI2
							INNER JOIN sSetup.tClassMaster CM ON CM.Id = AI2.ForClassId
							INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI2.ForBatchId
							LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
							LEFT JOIN sAdmission.tInquiryStatusMaster ISM1 ON ISM1.Id = AI2.InquiryStatusId
						WHERE BM.Id = TB.BatchId 
						--and OM.OrgId = @rOrgId
							--and Ai2.ForClassId = CM.Id
							--AND COGBM.Id=1
							AND ISM1.InquiryMainStatusId  = '+CONVERT(nvarchar(20),@rInquiryMainStatus)+'
							AND ((CM.OrgId = '+CONVERT(nvarchar(20),@rOrgId)+' )OR('+CONVERT(nvarchar(20),@rOrgId)+'=0))
							AND BM.IsInContext = 1
						Group BY 
							AI2.ForClassId,CM.Title,CM.OrderIndex,ISM1.InquiryMainStatusId'

						print @lSQLString4

						execute(@lSQLString4)
				END
			END

	ELSE IF(@rType='NotDoneStatusStudentList')
		BEGIN
				IF(@lConfigValue = 'True')
				BEGIN

				DECLARE @lInqMainStatusStudent nvarchar(500)='' 
				 
				SET  @lInqMainStatusStudent = 'AND ISM.Id =' + CONVERT(nvarchar,@rInquiryStatusId)
				--IF(@rInquiryMainStatus=11)
				--SET  @lInquiryMainStatusStudent = 'AND ISM.InquiryMainStatusId >=11'
				--ELSE IF(@rInquiryMainStatus=21)
				--SET  @lInquiryMainStatusStudent = 'AND ISM.InquiryMainStatusId > 11'
				--ELSE IF(@rInquiryMainStatus=31)
				--SET  @lInquiryMainStatusStudent ='AND ISM.InquiryMainStatusId > 21'
				--ELSE IF(@rInquiryMainStatus=41)
				--SET  @lInquiryMainStatusStudent ='AND ISM.InquiryMainStatusId > 31'
				--ELSE IF(@rInquiryMainStatus=51)
				--SET  @lInquiryMainStatusStudent ='AND ISM.InquiryMainStatusId > 41 and ISM.InquiryMainStatusId <> 61'
				--ELSE IF(@rInquiryMainStatus=61)
				--SET  @lInquiryMainStatusStudent ='AND ISM.InquiryMainStatusId > 51 AND ISM.InquiryMainStatusId !=71'
				--ELSE IF(@rInquiryMainStatus=71)
				--SET  @lInquiryMainStatusStudent ='AND ISM.InquiryMainStatusId > 61'
				--ELSE IF(@rInquiryMainStatus=81)
				--SET  @lInquiryMainStatusStudent ='AND ISM.InquiryMainStatusId > 71 AND ISM.InquiryMainStatusId !=91'
				--ELSE IF(@rInquiryMainStatus=91)
				--SET  @lInquiryMainStatusStudent ='AND ISM.InquiryMainStatusId > 81 AND ISM.InquiryMainStatusId !=101'
				--ELSE IF(@rInquiryMainStatus=101)
				--SET  @lInquiryMainStatusStudent ='AND ISM.InquiryMainStatusId > 91 AND ISM.InquiryMainStatusId !=111'
				--ELSE IF(@rInquiryMainStatus=111)
				--SET  @lInquiryMainStatusStudent ='AND ISM.InquiryMainStatusId > 101'


				DECLARE @lSQLStduentList3 nvarchar(max)=''

				SET @lSQLStduentList3 = 'DECLARE @lTempOrgBatchOrder TABLE( OrgId int, BatchOrderIndex int)
						INSERT INTO @lTempOrgBatchOrder ( OrgId,BatchOrderIndex )
						SELECT OM.Id AS OrgId, MAX(BM.OrderIndex) AS BatchOrderIndex
						FROM
							sSetup.tOrganizationMaster OM
							INNER JOIN sSetup.tBatchMaster BM ON BM.OrgId = OM.Id
							INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
							INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
						WHERE 
							((OM.OrgGroupId='+CONVERT(nvarchar(20),@rOrgGroupId)+') OR ('+CONVERT(nvarchar(20),@rOrgGroupId)+' = 0))
							AND BM.IsObsolete = 0 AND COGBM.Id='+CONVERT(nvarchar(20),@rCommonOrgGroupBatchId)+'
							AND BM.IsInContext = 1
						GROUP BY
							OM.Id
		
						DECLARE @lTempBatchId TABLE(OrgId int, BatchId int)
						INSERT INTO @lTempBatchId (OrgId , BatchId)
						SELECT 
							BM.OrgId AS OrgId,
							BM.Id AS BatchId
						FROM 
							sSetup.tBatchMaster BM
							INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
							INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
							--INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
							INNER JOIN @lTempOrgBatchOrder BO ON BO.OrgId = BM.OrgId
						WHERE
							BO.BatchOrderIndex = BM.OrderIndex  AND COGBM.Id='+CONVERT(nvarchar(20),@rCommonOrgGroupBatchId)+'
							AND BM.IsInContext = 1
		
							SELECT AI.Number As InquiryId, AI.FirstName+ SPACE(1) +AI.MiddleName +SPACE(1) +AI.LastName AS StudentName,AI.ContactNo AS ContactNo FROM 
								sAdmission.tAdmissionInquiry AI 
								INNER JOIN sSetup.tClassMaster CM ON CM.Id = AI.ForClassId
								INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForBatchId
								INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
								INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
								INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
			
				
								LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
								INNER JOIN sSetup.tOrganizationMaster OM ON AI.OrgId = OM.Id
								LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI.InquiryStatusId --AND((ISM.Id = '+CONVERT(nvarchar(20),@rInquiryStatusId)+')OR('+CONVERT(nvarchar(20),@rInquiryStatusId)+'=0))
								WHERE BM.Id = TB.BatchId AND COGBM.Id='+CONVERT(nvarchar(20),@rCommonOrgGroupBatchId)+'
								'+CONVERT(nvarchar(500),@lInqMainStatusStudent)+'
								AND ((OM.OrgGroupId = '+CONVERT(nvarchar(20),@rOrgGroupId)+' )OR('+CONVERT(nvarchar(20),@rOrgGroupId)+'=0)) 
			
								AND((CM.OrgId = '+CONVERT(nvarchar(20),@rOrgId)+')OR('+CONVERT(nvarchar(20),@rOrgId)+'=0))
								AND((CM.Id ='+CONVERT(nvarchar(20),@rClassId)+' )OR('+CONVERT(nvarchar(20),@rClassId)+'=0))
								AND BM.IsInContext = 1
								GROUP BY AI.FirstName,AI.MiddleName,AI.LastName,AI.ContactNo,AI.Number'

					--print @lSQLStduentList

					execute(@lSQLStduentList3)

					END
					ELSE
					BEGIN	
						DECLARE @lSQLStduentList4 nvarchar(max)=''

						SET @lSQLStduentList4 = 'DECLARE @lTempOrgBatchOrder TABLE( OrgId int, BatchOrderIndex int)
								INSERT INTO @lTempOrgBatchOrder ( OrgId,BatchOrderIndex )
								SELECT OM.Id AS OrgId, MAX(BM.OrderIndex) AS BatchOrderIndex
								FROM
									sSetup.tOrganizationMaster OM
									INNER JOIN sSetup.tBatchMaster BM ON BM.OrgId = OM.Id
									INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
									INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
								WHERE 
									((OM.OrgGroupId='+CONVERT(nvarchar(20),@rOrgGroupId)+') OR ('+CONVERT(nvarchar(20),@rOrgGroupId)+' = 0))
									AND BM.IsObsolete = 0 AND COGBM.Id='+CONVERT(nvarchar(20),@rCommonOrgGroupBatchId)+'
									AND BM.IsInContext = 1
								GROUP BY
									OM.Id
		
								DECLARE @lTempBatchId TABLE(OrgId int, BatchId int)
								INSERT INTO @lTempBatchId (OrgId , BatchId)
								SELECT 
									BM.OrgId AS OrgId,
									BM.Id AS BatchId
								FROM 
									sSetup.tBatchMaster BM
									INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
									INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
									--INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
									INNER JOIN @lTempOrgBatchOrder BO ON BO.OrgId = BM.OrgId
								WHERE
									BO.BatchOrderIndex = BM.OrderIndex  AND COGBM.Id='+CONVERT(nvarchar(20),@rCommonOrgGroupBatchId)+'
									AND BM.IsInContext = 1
		
		
									SELECT AI.Number As InquiryId, AI.FirstName+ SPACE(1) +AI.MiddleName +SPACE(1) +AI.LastName AS StudentName,AI.ContactNo AS ContactNo FROM 
										sAdmission.tAdmissionInquiry AI 
										INNER JOIN sSetup.tClassMaster CM ON CM.Id = AI.ForClassId
										INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForBatchId
										INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
										INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
										INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
			
				
										LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
										INNER JOIN sSetup.tOrganizationMaster OM ON AI.OrgId = OM.Id
										LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI.InquiryStatusId --AND((ISM.Id = '+CONVERT(nvarchar(20),@rInquiryStatusId)+')OR('+CONVERT(nvarchar(20),@rInquiryStatusId)+'=0))
										WHERE BM.Id = TB.BatchId AND COGBM.Id='+CONVERT(nvarchar(20),@rCommonOrgGroupBatchId)+'
										 AND ISM.InquiryMainStatusId = '+CONVERT(nvarchar(20),@rInquiryMainStatus)+'
										AND ((OM.OrgGroupId = '+CONVERT(nvarchar(20),@rOrgGroupId)+' )OR('+CONVERT(nvarchar(20),@rOrgGroupId)+'=0)) 
			
										AND((CM.OrgId = '+CONVERT(nvarchar(20),@rOrgId)+')OR('+CONVERT(nvarchar(20),@rOrgId)+'=0))
										AND((CM.Id ='+CONVERT(nvarchar(20),@rClassId)+' )OR('+CONVERT(nvarchar(20),@rClassId)+'=0))
										AND BM.IsInContext = 1
										GROUP BY AI.FirstName,AI.MiddleName,AI.LastName,AI.ContactNo,AI.Number'

					print @lSQLStduentList4

						execute(@lSQLStduentList4)
			END
		END
	END


	-- For AdmissionConverted Tab
	IF(@rTypeId = 3)
	BEGIN
		IF(@rType='OrgGroupWise')
		BEGIN
			-- Organization wise Count
			SELECT OrgId, Organization, ISNULL(Inquiry, 0) AS InquiryCount, ISNULL(Form, 0) AS FormCount, (ISNULL([Converted Inquiry], 0) + ISNULL([Converted Form], 0)) AS ConvertedCount
			FROM  
			(
				SELECT 
					ISNULL(OM.Id,0) AS OrgId,
					OM.Title AS Organization,
					'Inquiry' AS Type,
					ISNULL(COUNT(AI.Id),0) AS Total
				FROM sAdmission.tAdmissionInquiry AI 
					INNER JOIN sAdmission.tInquiryStatusMaster SM ON SM.Id=AI.InquiryStatusId
					INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForBatchId
					INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
					INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
					INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
					LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
					INNER JOIN sSetup.tOrganizationMaster OM ON AI.OrgId = OM.Id
				WHERE 
					BM.Id = TB.BatchId 
					AND COGBM.Id=@rCommonOrgGroupBatchId
					--AND OM.OrgGroupId = @rOrgGroupId
					And ISNULL(O.IsObsolete,0) = 0
					AND BM.IsInContext = 1
				GROUP BY OM.Id,OM.Title

				UNION ALL

				SELECT 
					OM.Id, 
					OM.Title AS Organization,
					'Form' AS Type,
					COUNT(AF.Id) AS Total
				FROM sAdmission.tAdmissionForm AF 
					INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AF.BatchId
					INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
					INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
					INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
					INNER JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
					INNER JOIN sSetup.tOrganizationMaster OM ON AF.OrgId = OM.Id
				WHERE
					BM.Id = TB.BatchId
					AND OM.OrgGroupId = @rOrgGroupId 
					AND COGBM.Id = @rCommonOrgGroupBatchId
					And ISNULL(O.IsObsolete,0) = 0
					AND BM.IsInContext = 1
				GROUP BY OM.Id, OM.Title

				UNION ALL

				SELECT
					ISNULL(OM.Id,0) AS OrgId,
					OM.Title AS Organization,
					'Converted Inquiry' AS Type,
					COUNT(AI.Id) AS Total
				FROM sAdmission.tAdmissionInquiry AI
					INNER JOIN sAdmission.tInquiryStatusMaster SM ON SM.Id=AI.InquiryStatusId
					LEFT JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForBatchId AND BM.IsInContext = 1
					LEFT JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
					LEFT JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
					LEFT JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
					LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
					LEFT JOIN sSetup.tOrganizationMaster OM ON AI.OrgId = OM.Id
					LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI.InquiryStatusId
				WHERE 
					BM.Id = TB.BatchId 
					AND COGBM.Id=@rCommonOrgGroupBatchId
					AND ISM.InquiryMainStatusId = 71
					--AND OM.OrgGroupId = @rOrgGroupId
					And ISNULL(O.IsObsolete,0) = 0
				GROUP BY OM.Id, OM.Title

				UNION ALL

				SELECT 
					OM.Id, 
					OM.Title AS Organization,
					'Converted Form' AS Type,
					COUNT(AF.Id) AS Total
				FROM sAdmission.tAdmissionForm AF 
					INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AF.BatchId
					INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
					INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
					INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
					INNER JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
					INNER JOIN sSetup.tOrganizationMaster OM ON AF.OrgId = OM.Id
				WHERE
					BM.Id = TB.BatchId
					AND OM.OrgGroupId = @rOrgGroupId 
					AND COGBM.Id = @rCommonOrgGroupBatchId
					And ISNULL(O.IsObsolete,0) = 0
					AND AF.StatusId = 208 --Closed
					AND BM.IsInContext = 1
				GROUP BY OM.Id, OM.Title
			   ) AS A
				PIVOT  
				(SUM(Total) FOR [Type] IN ([Inquiry],[Form],[Converted Inquiry],[Converted Form])) AS A1
		END

		IF(@rType='ClassWise')
		BEGIN
			-- Class wise Count
			SELECT ClassId, ClassName, OrderIndex, ISNULL(Inquiry, 0) AS InquiryCount, ISNULL(Form, 0) AS FormCount,(ISNULL([Converted Inquiry], 0) + ISNULL([Converted Form], 0)) AS ConvertedCount
			FROM  
			(
				--Inquiry
				SELECT 
					AI.ForClassId AS ClassId, CM.Title AS ClassName, 'Inquiry' AS Type, ISNULL(COUNT(AI.Id),0) AS Total, CM.OrderIndex
				FROM sAdmission.tAdmissionInquiry AI
					INNER JOIN sAdmission.tInquiryStatusMaster SM ON SM.Id=AI.InquiryStatusId
					INNER JOIN sSetup.tClassMaster CM ON CM.Id = AI.ForClassId
					INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForBatchId
					LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
				WHERE 
					BM.Id = TB.BatchId 
					AND ((CM.OrgId = @rOrgId) OR (@rOrgId=0))
					AND BM.IsInContext = 1				
				Group BY AI.ForClassId,CM.Title,CM.OrderIndex 

				UNION ALL 

				-- Form
				SELECT 
					CM.Id AS ClassId, CM.DisplayTitle AS ClassName, 'Form' AS Type, ISNULL(COUNT(AF.Id),0) AS Total, CM.OrderIndex 
				FROM sAdmission.tAdmissionForm AF 
					INNER JOIN sSetup.tClassMaster CM ON CM.Id = AF.ForClassId
					INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AF.BatchId
					INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
					INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
					INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
					INNER JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
					INNER JOIN sSetup.tOrganizationMaster OM ON AF.OrgId = OM.Id
				WHERE 
					BM.Id = TB.BatchId
					AND OM.OrgGroupId = 9911 AND COGBM.Id=@rCommonOrgGroupBatchId
					And ISNULL(O.IsObsolete,0) = 0
					AND ((CM.OrgId = @rOrgId) OR (@rOrgId=0))
					AND BM.IsInContext = 1
				GROUP BY CM.Id,CM.DisplayTitle,CM.OrderIndex

				UNION ALL
				
				SELECT 
					AI.ForClassId AS ClassId, CM.Title AS ClassName, 'Converted Inquiry' AS Type, ISNULL(COUNT(AI.Id),0) AS Total, CM.OrderIndex
				FROM sAdmission.tAdmissionInquiry AI
					INNER JOIN sAdmission.tInquiryStatusMaster SM ON SM.Id=AI.InquiryStatusId
					INNER JOIN sSetup.tClassMaster CM ON CM.Id = AI.ForClassId
					INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForBatchId
					LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
					LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI.InquiryStatusId
				WHERE 
					BM.Id = TB.BatchId 
					AND ((CM.OrgId = @rOrgId )OR(@rOrgId=0))
					AND ISM.InquiryMainStatusId = 71		
					AND BM.IsInContext = 1	
				Group BY AI.ForClassId,CM.Title,CM.OrderIndex 

				UNION ALL

				SELECT 
					CM.Id AS ClassId, CM.DisplayTitle AS ClassName, 'Converted Form' AS Type, ISNULL(COUNT(AF.Id),0) AS Total, CM.OrderIndex 
				FROM sAdmission.tAdmissionForm AF 
					INNER JOIN sSetup.tClassMaster CM ON CM.Id = AF.ForClassId
					INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AF.BatchId
					INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
					INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
					INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
					INNER JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
					INNER JOIN sSetup.tOrganizationMaster OM ON AF.OrgId = OM.Id
				WHERE 
					BM.Id = TB.BatchId
					AND OM.OrgGroupId = @rOrgGroupId 
					AND COGBM.Id=@rCommonOrgGroupBatchId
					And ISNULL(O.IsObsolete,0) = 0
					AND AF.StatusId = 208 --Closed
					AND((CM.OrgId = @rOrgId)OR(@rOrgId=0))
					AND BM.IsInContext = 1
				GROUP BY CM.Id,CM.DisplayTitle,CM.OrderIndex
			)  
			AS A
			PIVOT  
			(SUM(Total) FOR [Type] IN ([Inquiry],[Form],[Converted Inquiry],[Converted Form])) AS A2
		END
	END

END
GO
PRINT N'Altering [sAdmission].[pAdmissionFormGet]...';


GO
 
  

ALTER PROCEDURE [sAdmission].[pAdmissionFormGet]

	 @rAdmissionFormId bigint = 0,
	 @rFormNo int,
	 @rForClassId int,
	 @rBatchId int=0,
	 @rStatusId smallint='',
	 @rOrgId int,
	 @rFirstName nvarchar(100),
	 @rLastName nvarchar(100),
	 @rMeritMarks decimal(10,2),
	 @rFromDate datetime= '1900-01-01',
	 @rToDate datetime = '9990-12-31',
	 @rDepartmentId int=0,
	 @rIsTransportFilter int=2,
	 @rIsHostelFilter int=2,
	 @rDataEntryStatusId smallint=0,
	 @rIsCommonSearch bit=0
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	
	SET @rToDate = DATEADD(d,1,@rToDate)		 

BEGIN 
		--IF @rIsSearch = 1
		BEGIN
		SET @rFirstName = ISNULL(@rFirstName,'')
		SET @rLastName = ISNULL(@rLastName,'')
			SET @rFirstName = sCommon.fSearchStringGet(@rFirstName)
			SET @rLastName = sCommon.fSearchStringGet(@rLastName)
		END
	
	SELECT 
			 AF.Id
			,AF.FormNo
			,AF.FirstName
			,AF.MiddleName
			,AF.LastName

			--,AF.FirstName+' '+AF.LastName as Name
			,[sStudent].[fStudentNameGet](AF.FirstName , ISNULL(AF.MiddleName,'') , AF.LastName,OM.StudentNameFormatId ) AS Name

			,AF.ForClassId
			,AF.BatchId
			,CM.Title AS ClassName
			,AF.ForBatch
			,ISNULL(AF.DateOfBirth,'') AS DateOfBirth
			,AF.DateOfBirthInWord
			,AF.StatusId
			,SM.Title as StatusName
			,ISNULL(ASM.Title,'') AS FormStatus
			,AF.StreetOne
			,AF.StreetTwo
			,AF.StreetThree
			,AF.Country
			,AF.State
			,AF.City
			,AF.ZipCode
			,AF.ContactNo
			,AF.ContactEmail
			,AF.Remark
			,AF.PreviousSchool
			,AF.MeritMarks
			,AF.MeritGrade
			,AF.GenderId
			,ISNULL(GM.Title,'') AS Gender
			,ISNULL(AF.ReligionId,0) AS ReligionId
			,AF.FamilyCast
			,AF.FamilySubCast
			,ISNULL(AF.CastCategoryId,0) AS CastCategoryId
			,AF.CreatedDateTime AS AdmissionFormDate
			,ISNULL(AF.StudentId,0) AS StudentId
			,ISNULL(AF.AdmissionDate,'') AS AdmissionDate
			--,AF.StudentPhoto,
			,(CASE WHEN @rIsCommonSearch=0 THEN ISNULL(AF.StudentPhoto,0) ELSE NULL END) AS StudentPhoto
			
			,ISNULL(AFFD.FatherName,'') AS FatherName,
			Isnull(AFFD.FatherDateOfBirth,'') AS FatherDateOfBirth,
			Isnull(AFFD.FatherOccupation,'') AS FatherOccupation,
			Isnull(AFFD.FatherQualification,'') AS FatherQualification,
			Isnull(AFFD.FatherContactNo,'') AS FatherContactNo,
			Isnull(AFFD.FatherMail,'') AS FatherMail,
			Isnull(AFFD.FatherOfficeAddress,'') As FatherOfficeAddress,
			isnull(AFFD.FatherOrganization,'') as FatherOrganization,
			isnull(AFFD.FatherDesignation,'') as FatherDesignation,
			Isnull(AFFD.FatherIncome,'') as FatherIncome,
			Isnull(AFFD.MotherName,'') AS MotherName,
			iSNULL(AFFD.MotherDateOfBirth,'')AS MotherDateOfBirth,
			isnull(AFFD.MotherOccupation,'') AS MotherOccupation,
			isnull(AFFD.MotherQualification,'') AS MotherQualification,
			isnull(AFFD.MotherContactNo,'') as MotherContactNo,
			isnull(AFFD.MotherMail,'') As MotherMail,
			isnull(AFFD.MotherOfficeAddress,'') as MotherOfficeAddress,
			isnull(AFFD.MotherOrganization,'') as MotherOrganization,
			isnull(AFFD.MotherDesignation,'') as MotherDesignation,
			isnull(AFFD.MotherIncome,'') as MotherIncome,
			AF.MotherTongue AS MotherTongue,
		 
			isnull(AFFD.RelationshipName,'') as RelationshipName,
			isnull(AFFD.RelativeName,'')  AS GuardianName ,
			isnull(AFFD.RelativeDateOfBirth ,'')AS GuardianDateOfBirth,
			isnull(AFFD.RelativeOccupation,'') AS GuardianOccupation,
			isnull(AFFD.RelativeQualification,'') AS GuardianQualification,
			isnull(AFFD.RelativeContactNo,'') AS GuardianContactNo,
			isnull(AFFD.RelativeMail,'')  AS GuardianMail,
			isnull(AFFD.RelativeOfficeAddress,'') AS GuardianOfficeAddress,
			isnull(AFFD.RelativeOrganization,'') as RelativeOrganization,
			isnull(AFFD.RelativeDesignation,'') as RelativeDesignation,
			isnull(AFFD.RelativeIncome,'') AS GuardianIncome  ,
			isnull(AF.IsHostelRequired,0) AS IsHostelRequired  ,
			isnull(AF.IsTransportRequired,0) AS IsTransportRequired,
			isnull(AF.BirthPlace,'') AS BirthPlace,
			isnull(AF.BirthTaluka,'') AS BirthTaluka,
			isnull(AF.BirthDistrict,'') AS BirthDistrict,
			isnull(AF.BloodGroupId,0) AS BloodGroupId,
			isnull(AF.AdhaarNumber,'') AS AdhaarNumber,
			isnull(AF.IsPysicalDeformity,0) AS IsPysicalDeformity,
			isnull(AF.PysicalDeformityRemark,'') AS PysicalDeformityRemark,
			isnull(AF.IsMajorIllness,0) AS IsMajorIllness,
			isnull(AF.MajorIllnessRemark,'') AS MajorIllnessRemark,
			isnull(AF.IsAllergy,0) AS IsAllergy,
			isnull(AF.AllergyRemark,'') AS AllergyRemark,
			isnull(AF.BirthState,'') AS BirthState,
			isnull(AF.BirthCountry,'') AS BirthCountry,
			isnull(SA.PreviousStandard,'') As PreviousStandard,
	        isnull(AFFD.LiveWithId,0) AS LiveWithId,
			--isnull(ASB.SiblingName,'') AS SiblingName,
			--isnull(ASB.SiblingRelation,'')AS SiblingRelation,
			
			--isnull(ASB.SiblingStandard,'') AS SiblingStandard,
			--isnull(ASB.SiblingSchool,'')AS SiblingSchool
			
			 ISNULL(AF.CustomField1Answer,'') AS CustomField1Answer,
			 ISNULL(AF.CustomField2Answer,'') AS CustomField2Answer,
			 ISNULL(AF.CustomField3Answer,'') AS CustomField3Answer,
			 SM1.Title AS DataEntryStatus,
			 AF.Nationality,
			 ISNULL(AFFD.FatherAdhaarNumber,'') AS FatherAdhaarNumber,
			 AF.CreatedDateTime AS AdmissionFormDate,
			 ISNULL(AFFD.MotherAadhaarNumber,'') AS MotherAadhaarNumber,
			 ISNULL(AFFD.RelativeAadhaarNumber,'') AS RelativeAadhaarNumber,
			 ISNULL(AFFD.FatherOfficePhone,'') AS FatherOfficePhone,
			 ISNULL(AFFD.MotherOfficePhone,'') AS MotherOfficePhone,
			 CASE WHEN AF.DataEntryModeId = 561 THEN 'Online' ELSE 'Offline' END DataEntryMode
			 
  FROM 
            sAdmission.tAdmissionForm AF
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = AF.OrgId
			INNER JOIN sCommon.tStatusMaster SM ON SM.Id=AF.StatusId
			INNER JOIN sCommon.tStatusMaster SM1 ON SM1.Id=AF.DataEntryStatusId			
			INNER JOIN sSetup.tClassMaster CM ON CM.Id=AF.ForClassId
			LEFT JOIN sCommon.tGenderMaster GM ON GM.Id=AF.GenderId
			LEFT JOIN sAdmission.tAdmissionFormSelected AFS ON AF.Id = AFS.AdmissionFormId
			LEFT JOIN sAdmission.tAdmissionStatusMaster ASM ON ASM.Id = AFS.AdmissionStatusId
			LEFT JOIN sAdmission.tAdmissionFormFamilyDetail AFFD ON AFFD.AdmissionFormId = AF.Id
			LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId = AF.StudentId
			 --LEFT JOIN sAdmission.tAdmissionFormSibling ASB ON ASB.AdmissionFormId = AF.Id
			LEFT JOIN sStudent.tStudentAdmission SA ON SA.StudentID=AF.StudentID
  WHERE 
  
      ((AF.Id = @rAdmissionFormId) OR (@rAdmissionFormId = 0))
		AND ((AF.FormNo=@rFormNo) OR (@rFormNo=0))
		AND ((AF.FirstName like @rFirstName) OR (@rFirstName=''))
		AND ((AF.LastName like @rLastName) OR (@rLastName=''))
		--AND ((AF.CreatedDateTime>= @rFromDate) OR (@rFromDate=''))
		AND ((Cast(AF.AdmissionDate as datetime)>= @rFromDate) OR (@rFromDate=''))
		--AND ((AF.AdmissionDate is not null AND Cast(AF.AdmissionDate as datetime)>= @rFromDate) or (AF.AdmissionDate is null AND AF.CreatedDateTime>= @rFromDate) or (@rFromDate=''))
		--AND ((AF.CreatedDateTime < @rToDate) OR (@rToDate=''))
		AND ((Cast(AF.AdmissionDate as datetime)<= @rToDate) OR (@rToDate=''))
		--AND ((AF.AdmissionDate is not null AND Cast(AF.AdmissionDate as datetime)< @rToDate) or (AF.AdmissionDate is null AND AF.CreatedDateTime< @rToDate) or (@rToDate=''))
		AND ((AF.StatusId=@rStatusId) OR (@rStatusId=0))
		AND ((AF.ForClassId=@rForClassId) OR (@rForClassId=0)) 
		AND ((AF.BatchId=@rBatchId) OR (@rBatchId=0)) 
		--AND ((AF.MeritMarks=@rMeritMarks) OR (@rMeritMarks=0))
		AND ((AF.StatusId=@rStatusId) OR (@rStatusId = ''))
		AND ((AF.DataEntryStatusId=@rDataEntryStatusId) OR (@rDataEntryStatusId = 0))
		AND ((CM.DepartmentId=@rDepartmentId) OR (@rDepartmentId = 0))
		AND AF.OrgId=@rOrgId
        AND ((ISnull(AF.IsHostelRequired,0)=@rIsHostelFilter ) OR   (ISNULL(@rIsHostelFilter,2)=2) )
	   AND ((ISNUll(AF.IsTransportRequired,0)=@rIsTransportFilter) OR (isnull(@rIsTransportFilter,0) = 2))
	  
 order by AF.FormNo
END
GO
PRINT N'Altering [sAlert].[pParentPortalLoginGet]...';


GO

ALTER PROCEDURE [sAlert].[pParentPortalLoginGet]
	 	 
	@rOrgId smallint,
	@rBatchId int,
	--@rIsPendingLogin bit,
	--@rIsCreatedLogin bit,
	@rClassId int =0,
	@rDivisionId int=0,
	--@rNotRegister bit=0,
	@rTemplate nvarchar(max),
	@rStudentId bigint = 0,
	@rSubject nvarchar(100)=''

	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
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(@rTemplate,'[UserName]',U.LoginTitle),'[Password]','[Password]'),'[StudentName]',SC.Name)
			 AS Template,
			 --Add for StudentWise
			 replace(replace(replace(@rTemplate,'[UserName]',U.LoginTitle),'[Password]','[Password]'),'[StudentName]',SC.Name)
			 AS MsgText,
			 @rSubject AS Subject,
			 2003 AS ReceiverSourceTypeId,
			 SC.StudentId AS ReceiverSourceId,
			 SC.StudentId AS SourceId,
			 2003 AS SourceTypeId,
			 SC.OrgGroupId,
			 SC.OrgId,

			 SC.ClassName AS Class,
			 SC.DivisionName AS Division,
			 SC.WhatsAppContactNo,
			 U.LoginPassword AS Password
	FROM 
			sStudent.vStudentCommunication SC
			INNER JOIN sSecurity.tUser U ON U.SourceId = SC.StudentId AND U.SourceTypeId=2003
			INNER JOIN sStudent.tStatusMaster SM ON SM.Id = SC.StatusId 
			 
	WHERE 
			 (SC.OrgId = @rOrgId)
			 AND (SC.BatchId = @rBatchId) 
			 AND ((SC.ClassId = @rClassId) OR(@rClassId=0))
			 AND ((SC.DivisionId = @rDivisionId) OR(@rDivisionId=0))
			 AND SC.StatusId = 1 AND U.ISobsolete = 0
			 AND ((SC.StudentId = @rStudentId) OR (@rStudentId = 0))
END
GO
PRINT N'Altering [sAlert].[pVisitorGatePassGet]...';


GO
ALTER PROCEDURE [sAlert].[pVisitorGatePassGet]
	
		 @rVisitorLogId int,
	 	 @rOrgId int,
	 	 @rTemplate nvarchar(max),
		 @rSubject nvarchar(100)='',
		 @rIsOutEntry bit = 0
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	IF(@rIsOutEntry=0)
	BEGIN
		SELECT 
			VL.Id,
			VL.VisitorName,
			EC.MobileNumber AS MobileNo,
			VL.VisitorContactNumber AS ContactNumber,
			EC.CompanyEmail AS EmailId,
			replace (
			replace (
			replace(@rTemplate,'[VisitorName]',VL.VisitorName),
			'[NoOfVisitors]',VL.NoOfVisitor),
			'[PurposeOfVisit]',VL.PurposeOfVisit)
			AS MsgText,
			@rSubject AS Subject,
			95 AS ReceiverSourceTypeId,
			EM.Id AS ReceiverSourceId,
			EM.Id AS SourceId,
			95 AS SourceTypeId,
			OM.OrgGroupId,
			VL.OrgId,
			VL.NoOfVisitor AS NoOfVisitors,
			VL.PurposeOfVisit AS PurposeOfVisit,
			ISNULL(EC.WhatsAppContactNo,'') AS WhatsAppContactNo
		FROM 
			sFrontOffice.tVisitorLog VL
			INNER JOIN [sHrm].[tEmployeeMaster] EM ON VL.WhomToMeet=EM.Id
			INNER JOIN [sHrm].[tEmployeeCommunications] EC ON EM.Id=EC.EmployeeId
			INNER JOIN sSetup.tOrganizationMaster OM ON VL.OrgId = OM.Id	
		WHERE
			((VL.OrgId=@rOrgId) OR (@rOrgId=0))
			AND VL.Id = @rVisitorLogId
	END
	ELSE
	BEGIN
		SELECT 
			VL.Id,
			VL.VisitorName,
			VL.VisitorContactNumber AS MobileNo,
			'' AS EmailId,
			replace (
			replace (
			replace(@rTemplate,'[VisitorName]',VL.VisitorName),
			'[NoOfVisitors]',VL.NoOfVisitor),
			'[PurposeOfVisit]',VL.PurposeOfVisit)
			AS MsgText,
			@rSubject AS Subject,
			0 AS ReceiverSourceTypeId,
			0 AS ReceiverSourceId,
			0 AS SourceId,
			0 AS SourceTypeId,
			OM.OrgGroupId,
			VL.OrgId,
			VL.NoOfVisitor AS NoOfVisitors,
			VL.PurposeOfVisit AS PurposeOfVisit,
			ISNULL(VL.VisitorContactNumber,'') AS WhatsAppContactNo
		FROM 
			sFrontOffice.tVisitorLog VL
			--To Send Alert on Visitor Contact No
			--LEFT JOIN [sHrm].[tEmployeeMaster] EM ON VL.WhomToMeet=EM.Id
			--LEFT JOIN [sHrm].[tEmployeeCommunications] EC ON EM.Id=EC.EmployeeId
			LEFT JOIN sSetup.tOrganizationMaster OM ON VL.OrgId = OM.Id	
		WHERE
			((VL.OrgId=@rOrgId) OR (@rOrgId=0))
			AND VL.Id = @rVisitorLogId
	END
END
GO
PRINT N'Altering [sAssessment].[pMarkEntryAllSubjectCountGet]...';


GO

ALTER PROCEDURE [sAssessment].[pMarkEntryAllSubjectCountGet]
	 
	 @rExamId int,
	 @rBatchId int,
	 @rClassId int=0,
	 @rDivisionId int=0
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 		
DECLARE @cols AS NVARCHAR(MAX),
@query  AS NVARCHAR(MAX),@query1  AS NVARCHAR(MAX),@query2  AS NVARCHAR(MAX),@query3 AS NVARCHAR(MAX)
select @cols = STUFF((SELECT  distinct ',' +   QUOTENAME(CS.SubjectCode) 
					  From  
					   sSetup.vExamSubject CS  
					   INNER JOIN sAssessment.tExamMaster E ON E.Id=CS.ExamId AND E.ExamSubGroupId =  @rExamId 
					   INNER JOIN sSetup.tClassMaster CL on CL.Id=CS.ClassId
					   INNER JOIN sSetup.tDivisionMaster CM ON CM.ClassId=CL.Id
					    WHere ((CM.ClassId =@rClassID) OR (@rClassId=0)) AND ((CM.Id=@rDivisionId) OR (@rDivisionId=0)) 
						AND E.BatchId=@rBatchId
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')
 
set @query = 'SELECT  ClassId,DivisionId,ClassName,ExamId,

 ' + @cols + '
FROM
(
Select   CM.Id As ClassId,DM.Id as DivisionId,CM.Title+'' ''+DM.Title ClassName,Count(A.AcademicId) AS AcademicId,ED.ExamId, SM.Code as ExamDetailId
FROM sStudent.vStudentAcademic A 
INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
INNER JOIN sSetup.tDivisionMaster DM ON DM.ClassId=CM.Id AND A.DivisionId=DM.Id
INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
LEFT JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.AcademicId
INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
INNER JOIN sSetup.tClassSubject CS ON CS.Id = ED.ClassSubjectId
INNER JOIN sSetup.tSubjectMaster SM ON SM.Id = CS.SubjectId
LEFT JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id 
 
WHERE A.StatusId =1 AND A.BatchId = '+ CONVERT(nvarchar(15),@rBatchId) +' And  EM.ExamSubGroupId = ' + convert(nvarchar(15),@rExamId) + 
'AND ISNULL(RD.Obtain,0)>0 AND ((A.ClassId='+convert(nvarchar(15),@rClassId)+') OR (' +convert(nvarchar(15),@rClassId) + '=0)) 
AND ((A.DivisionId='+Convert(nvarchar(15),@rDivisionId)+') OR ('+Convert(nvarchar(15),@rDivisionId)+'=0))
Group By ED.ExamId,Ed.Id,CM.Title,DM.TItle,Cm.Id,Dm.Id,SM.Code) 
MAIN
PIVOT
(
	MAX(AcademicId )
FOR ExamDetailId IN (' + @cols + ')
)pvt '
--AND ISNULL(RD.Obtain,0)>0 (Ramesh Gurjar)Date: 19/02/2022 Remove this condition, for DPS chas 0 mark entry not count in verify screen
--print (@query)
execute(@query)
		
END
GO
PRINT N'Altering [sAssessment].[pRptExamResultSubCombine]...';


GO




ALTER PROCEDURE [sAssessment].[pRptExamResultSubCombine]
	 
	 -- @rAcademicId bigint=0,
	 @rExamSubGroupId int=0,
	 @rClassId int=0,
	 @rDivisionId int=0,
	 @rOrgId int =0,
	 @rBatchId int ,
	 @rDepartmentid int=0,
	 @rStatusId int=0
	 
	
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	SELECT 
			 
			 CONVERT(nvarchar(20),EM.Id) AS ExamIdText,
			 CONVERT(nvarchar(20),@rClassId) AS ClassIdText,
			 CONVERT(nvarchar(20),DM.Id) AS DivisionIdText,
			 CONVERT(nvarchar(20),@rBatchId) AS BatchIdText,
			 CONVERT(nvarchar(20),@rStatusId) AS StatusIdText,
	 
			 
			CM.DisplayTitle + '-' + DM.DisplayTitle AS ClassDivision,
			DM.Title AS Division,
			CM.Title AS Class,
			E.FirstName + ' ' + E.LastName AS ClassTeacherName,
			BM.Title AS Batch,
			DM.Id AS DivisionId,
			CM.Id AS ClassId
			FROM 
			 
		 
			sAssessment.tExamMaster EM
			--INNER JOIN sAssessment.tResult R ON EM.Id=R.ExamId
		 --   INNER JOIN sStudent.tAcademic A	ON A.Id=R.Academic
			 INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			INNER JOIN sSetup.tClassMaster CM ON CM.Id=EM.ClassId
			--INNER JOIN sSetup.tClassSubject CS ON CS.ClassId=CM.Id
			INNER JOIN sSetup.tDivisionMaster DM ON DM.ClassId=CM.Id
			 LEFT JOIN sHrm.tEmployeeMaster E ON E.Id =DM.InchargeEmployeeId
			--INNER JOIN sSetup.tOrganizationMaster OM ON DM.OrgId = OM.Id
			 INNER JOIN sSetup.tBatchMaster BM ON BM.Id=EM.BatchId
	WHERE 
	 
	     (CM.Id=@rClassId OR @rClassId=0) 
		AND (DM.Id=@rDivisionId OR @rDivisionId=0)
		AND (EM.ExamSubGroupId = @rExamSubGroupId OR @rExamSubGroupId =0)
		AND  ISNULL(E.IsOtherUser,0) = 0
		--AND OM.Id=@rOrgId
		AND BM.Id = @rBatchId
		 
END
GO
PRINT N'Altering [sAssessment].[pRptResultWithSubjectListGet]...';


GO

ALTER PROCEDURE [sAssessment].[pRptResultWithSubjectListGet]
	 
   	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 @rSubjectId int=0,
	 @rBatchId int,
	 @rClassId int,
	 @rDivisionId int,
	 @rExamId int=0,
     @rExamSubGroupId int=0,
	 @rCode nvarchar(20),
	 @rFromRollNo int,
	 @rToRollNo int,
	 @rFromRank int,
	 @rToRank int,
	 @rGrade nvarchar(20),
	 @rStatusId int = 0,
	 @rFromPercentage decimal(5,2)=0,
	 @rToPercentage decimal(5,2)=0,
	 @rResultStatus nvarchar(20)='',
	 @rDepartmentId int=0,
	 @rClassStatusId int=0,
	 @rGenderId int = 0
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			
BEGIN 

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

	SELECT 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			SO.GenderId,
			ESGM.Title AS Exam,
			StuM.Code,
			[sStudent].[fStudentNameGet](StuM.FirstName , StuM.MiddleName, StuM.LastName,OM.StudentNameFormatId ) AS Name,
			A.RollNo,
			R.AcademicId,
			RD.Obtain,
			R.ResultStatus,
			CM.DisplayTitle AS Class,
			Cm.Id AS ClassId,
			DM.DisplayTitle AS Division,
			DM.Id AS DivisionId,
			DM.OrderIndex AS DivisinOrderIndex,
			R.TotalMarks,
			R.TotalObtain,
			R.Percentage,
			R.RankNumber,
			R.ResultGrade,
			SM.Title AS ClassSubject,
			RD.Id AS ResultDetailId,
			R.Id AS ResultId,
			CS.Id AS SubjectId,
			ED.Maximum,
			RD.SubjectGrade, 
			
			EM.IsMarksInDecimal,
			--SM.OrderIndex AS SubjectCode,
			SM.Code AS SubjectCode,
			ED.DisplayOrder AS SubjectOrderIndex,
			CM.OrderIndex AS ClassOrderIndex,
			RD.IsPresent,
			EM.IsGrade,
			EM.IsPercentage,
			EM.IsResultStatus,
			EM.IsRankNo ,
			ED.Minimum,
			RD.GraceMark,
			EM.DecimalFormat,
			CS.IsOptional,
			ISNULL(SR.PresentDays,0)AS PresentDays,
			ISNULL(SR.TotalDays,0)AS TotalDays,
			ED.IsShowSubjectGrade,
			ED.IsShowSubjectMark,
			(EmpM.FirstName + ' ' +EmpM.LastName ) AS InchargeEmployeeName,
			CONVERT(bit,@lAbsentRemarkConfig) AS IsAbsentRemark,
			ISNULL(RD.AbsentRemark,'') AS AbsentRemark

	FROM 
			sAssessment.tResultDetail RD
			INNER JOIN sAssessment.tResult R ON R.Id = RD.ResultId
			INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId
			INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId	
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId		
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=CS.SubjectId					 
			INNER JOIN sStudent.tAcademic A ON A.Id=R.AcademicId
			LEFT JOIN sAssessment.tStudentRemark SR ON SR.AcademicId = A.Id AND SR.ExamId =  EM.Id
			INNER JOIN sStudent.tStudentMaster StuM ON StuM.Id=A.StudentId
			INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId
			INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId
			INNER JOIN sSetup.tOrganizationMaster OM ON StuM.OrgId = OM.Id
			LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId=A.StudentId
			LEFT JOIN sHrm.tEmployeeMaster EmpM ON EmpM.Id = DM.InchargeEmployeeId AND EmpM.StatusId = 7
			
	WHERE 
			
		EM.BatchId = @rBatchId 
		AND (A.ClassId=@rClassId OR @rClassId=0) 
		AND ((SM.Id=@rSubjectId) OR (RD.ExamDetailId=@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 ((ESGM.Id = @rExamSubGroupId) OR (@rExamSubGroupId = 0))		
		AND ((EM.Id=@rExamId )	OR (@rExamId = 0))		
		AND ((StuM.Code=@rCode) OR (@rCode=''))
		AND ((StuM.StatusId=@rStatusId)OR(@rStatusId=0))	
		AND ((R.Percentage>=@rFromPercentage) OR (@rFromPercentage=0))
		AND ((R.Percentage<=@rToPercentage) OR(@rToPercentage=0))	
		AND ((R.ResultStatus=@rResultStatus) OR (@rResultStatus=''))
		AND ((CM.DepartmentId = @rDepartmentId) OR (@rDepartmentId=0))
		AND	A.BatchId = @rBatchId 
		AND (A.ClassStatusId=@rClassStatusId OR @rClassStatusId=0) 
		AND ((SO.GenderId=@rGenderId) OR (@rGenderId=0))
		--AND RD.IsPresent = 0
		order by A.RollNo,CS.OrderIndex 

		
END
GO
PRINT N'Altering [sAssessment].[pRptStudentClassWise]...';


GO



ALTER PROCEDURE [sAssessment].[pRptStudentClassWise]
	 
	  --@rAcademicId bigint=0,
	 @rExamId int=0,
	 @rClassId int=0,
	 @rDivisionId int=0,
	 @rBatchId int =0,
	 @rStatusId int=0	
 
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	SELECT 
			-- CONVERT(nvarchar(20),A.Id) AS AcademicIdText,
			 CONVERT(nvarchar(20),@rExamId) AS ExamIdText,
			 CONVERT(nvarchar(20),@rClassId) AS ClassIdText,
			 CONVERT (nvarchar(20),@rDivisionId) AS DivisionIdText,
			 --CONVERT(nvarchar(20),@rBatchId) AS BatchIdText,
			
			 (Select COUNT(A.Id) from sStudent.tAcademic A	
				INNER JOIN sStudent.tStudentMaster StuM ON StuM.Id=A.StudentId
				INNER JOIN sStudent.tStudentOther SO ON SO.StudentId=A.StudentId
				WHERE A.ClassId=@rClassId AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId=0)) AND ((StuM.StatusId=@rStatusId)OR(@rStatusId=0)) AND A.BatchId=@rBatchId AND SO.GenderId=2) AS TotalGirls,
		
			 (Select COUNT(A.Id) from sStudent.tAcademic A
			 INNER JOIN sStudent.tStudentMaster StuM ON StuM.Id=A.StudentId
				INNER JOIN sStudent.tStudentOther SO ON SO.StudentId=A.StudentId
				WHERE ClassId=@rClassId AND ((DivisionId=@rDivisionId) OR (@rDivisionId = 0)) AND ((StuM.StatusId=@rStatusId)OR(@rStatusId=0)) AND BatchId=@rBatchId AND SO.GenderId=1) AS TotalBoys,
			
			 (Select COUNT(A.Id) from sStudent.tAcademic A
				INNER JOIN sStudent.tStudentMaster SM ON SM.Id=A.StudentId
				INNER JOIN sStudent.tStudentOther SO ON SO.StudentId=A.StudentId
				WHERE ClassId=@rClassId AND ((DivisionId=@rDivisionId) OR (@rDivisionId = 0)) AND ((SM.StatusId=@rStatusId)OR(@rStatusId=0)) AND BatchId=@rBatchId AND SO.GenderId=2 AND SM.StatusId=3) AS LeftGirls,
			
			 (Select COUNT(A.Id) from sStudent.tAcademic A
				INNER JOIN  sStudent.tStudentMaster SM ON SM.Id= A.StudentId
				INNER JOIN sStudent.tStudentOther SO ON SO.StudentId=A.StudentId
				WHERE ClassId=@rClassId AND ((DivisionId=@rDivisionId) OR (@rDivisionId = 0)) AND ((SM.StatusId=@rStatusId)OR(@rStatusId=0)) AND BatchId=@rBatchId AND SO.GenderId=1 AND SM.StatusId=3) AS LeftBoys,
			
			
			(Select COUNT(R.AcademicId) from sAssessment.tResult R 
				 INNER JOIN sStudent.tAcademic A ON A.Id=R.AcademicId
				 INNER JOIN  sStudent.tStudentMaster SM ON SM.Id= A.StudentId
				 INNER JOIN sStudent.tStudentOther SO ON SO.StudentId=A.StudentId
				 WHERE A.ClassId=@rClassId AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId = 0)) AND ((SM.StatusId=@rStatusId)OR(@rStatusId=0)) AND A.BatchId=@rBatchId AND R.ExamId=@rExamId AND SO.GenderId=2) AS AppearedGirls,
				 
			 (Select COUNT(R.AcademicId) from sAssessment.tResult R 
				INNER JOIN sStudent.tAcademic A ON A.Id=R.AcademicId
				INNER JOIN  sStudent.tStudentMaster SM ON SM.Id= A.StudentId
				INNER JOIN sStudent.tStudentOther SO ON SO.StudentId=A.StudentId
				WHERE A.ClassId=@rClassId AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId = 0)) AND ((SM.StatusId=@rStatusId)OR(@rStatusId=0)) AND A.BatchId=@rBatchId AND R.ExamId=@rExamId AND So.GenderId=1) AS AppearedBoys,	
				
			 (Select COUNT(R.AcademicId) from sAssessment.tResult R 
				INNER JOIN sAssessment.tResultDetail RD ON R.Id = RD.ResultId
				INNER JOIN sAssessment.tExamDetail ED ON Rd.ExamDetailId = ED.Id
				INNER JOIN sStudent.tAcademic A ON A.Id=R.AcademicId
				INNER JOIN sStudent.tStudentMaster SM ON SM.Id= A.StudentId
				INNER JOIN sStudent.tStudentOther SO ON SO.StudentId=A.StudentId
				 WHERE A.ClassId=@rClassId AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId = 0)) AND ((SM.StatusId=@rStatusId)OR(@rStatusId=0)) AND A.BatchId=@rBatchId AND R.ExamId=@rExamId AND SO.GenderId=2
				 AND RD.IsPresent=0) AS AbsentGirls,
				 
			 (Select COUNT(R.AcademicId) from sAssessment.tResult R 
				INNER JOIN sAssessment.tResultDetail RD ON R.Id = RD.ResultId
				INNER JOIN sAssessment.tExamDetail ED ON Rd.ExamDetailId = ED.Id
				INNER JOIN sStudent.tAcademic A ON A.Id=R.AcademicId
				INNER JOIN sStudent.tStudentMaster SM ON SM.Id= A.StudentId
				INNER JOIN sStudent.tStudentOther SO ON SO.StudentId=A.StudentId
				 WHERE A.ClassId=@rClassId AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId = 0)) AND ((SM.StatusId=@rStatusId)OR(@rStatusId=0)) AND A.BatchId=@rBatchId AND R.ExamId=@rExamId AND SO.GenderId=1
				  AND RD.IsPresent=0) AS AbsentBoys,
			 
			 (Select COUNT(R.AcademicId) from sAssessment.tResult R 
				 INNER JOIN sStudent.tAcademic A ON A.Id=R.AcademicId
				 INNER JOIN sStudent.tStudentMaster SM ON SM.Id= A.StudentId
				 INNER JOIN sStudent.tStudentOther SO ON SO.StudentId=A.StudentId
				 WHERE A.ClassId=@rClassId AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId = 0)) AND ((SM.StatusId=@rStatusId)OR(@rStatusId=0)) AND A.BatchId=@rBatchId AND R.ExamId=@rExamId AND SO.GenderId=2
					AND R.ResultStatus='PASS') AS PassedGirls,    
				
			 (Select COUNT(R.AcademicId) from sAssessment.tResult R
				INNER JOIN sStudent.tAcademic A ON A.Id = R.AcademicId
				INNER JOIN sStudent.tStudentMaster SM ON SM.Id= A.StudentId
				INNER JOIN sStudent.tStudentOther SO ON SO.StudentId=A.StudentId
				WHERE  A.ClassId=@rClassId  AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId = 0)) AND ((SM.StatusId=@rStatusId)OR(@rStatusId=0)) AND  A.BatchId=@rBatchId  AND  R.ExamId=@rExamId  AND SO.GenderId=1
					AND R.ResultStatus='PASS') AS PassedBoys,      
				
			 (Select COUNT(R.AcademicId) from sAssessment.tResult R
				INNER JOIN sStudent.tAcademic A ON A.Id = R.AcademicId
				INNER JOIN sStudent.tStudentMaster SM ON SM.Id= A.StudentId
				INNER JOIN sStudent.tStudentOther  SO ON SO.StudentId=A.StudentId
				WHERE  A.ClassId=@rClassId AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId = 0)) AND ((SM.StatusId=@rStatusId)OR(@rStatusId=0)) AND  A.BatchId=@rBatchId AND  R.ExamId=@rExamId AND SO.GenderId=2
					 AND R.ResultStatus='PROMOTED') AS PassWithGraceGirls,
				
			 (Select COUNT(R.AcademicId) from  sAssessment.tResult R
				INNER JOIN sStudent.tAcademic A ON A.Id =R.AcademicId
				INNER JOIN sStudent.tStudentMaster SM ON SM.Id= A.StudentId
				INNER JOIN sStudent.tStudentOther  SO ON SO.StudentId=A.StudentId
				WHERE  A.ClassId=@rClassId AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId = 0)) AND ((SM.StatusId=@rStatusId)OR(@rStatusId=0)) AND A.BatchId=@rBatchId AND   R.ExamId=@rExamId AND SO.GenderId=1
					AND R.ResultStatus='PROMOTED') AS PassWithGraceBoys,
				
			 (Select COUNT(R.AcademicId) from sAssessment.tResult R
				INNER JOIN sStudent.tAcademic A ON A.Id=R.AcademicId
				INNER JOIN sStudent.tStudentMaster SM ON SM.Id= A.StudentId
				INNER JOIN sStudent.tStudentOther SO ON  SO.StudentId=A.StudentId
				WHERE   A.ClassId=@rClassId AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId = 0))  AND ((SM.StatusId=@rStatusId)OR(@rStatusId=0)) AND A.BatchId=@rBatchId AND R.ExamId=@rExamId AND SO.GenderId=2
					AND R.ResultStatus='FAIL') AS FailedGirls,
					
			 (Select COUNT(R.AcademicId) from sAssessment.tResult R
				INNER JOIN sStudent.tAcademic A ON A.Id=R.AcademicId
				INNER JOIN sStudent.tStudentMaster SM ON SM.Id= A.StudentId
				INNER JOIN sStudent.tStudentOther SO ON SO.StudentId=A.StudentId
				WHERE A.ClassId=@rClassId AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId = 0)) AND ((SM.StatusId=@rStatusId)OR(@rStatusId=0)) AND A.BatchId=@rBatchId AND R.ExamId=@rExamId AND SO.GenderId=1
						AND R.ResultStatus='FAIL') AS FailedBoys,
						
			 (Select COUNT(A.Id) from sStudent.tAcademic A
				INNER JOIN sStudent.tStudentMaster SM ON SM.Id= A.StudentId
				WHERE A.ClassId=@rClassId AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId = 0)) AND ((SM.StatusId=@rStatusId)OR(@rStatusId=0)) AND A.BatchId=@rBatchId) Total
			 
			FROM 
			sAssessment.tExamMaster EM 
			 INNER JOIN sSetup.tClassMaster CM ON CM.Id=EM.ClassId
			INNER JOIN sSetup.tDivisionMaster DM ON DM.ClassId=CM.Id
 
	WHERE 
		  ((EM.Id=@rExamId) OR (@rExamId=0))
		 AND((CM.Id=@rClassId) OR (@rClassId=0))
		 AND((DM.Id=@rDivisionId) OR (@rDivisionId=0))
 
 		AND EM.BatchId=@rBatchId
END
GO
PRINT N'Altering [sAssessment].[pRptStudentSubjectWise]...';


GO



ALTER PROCEDURE [sAssessment].[pRptStudentSubjectWise]  
	 
	 -- @rAcademicId bigint=0,
	 @rExamId int=0,
	@rClassId int=0,
	@rDivisionId int=0,
 
	@rBatchId int=0,
	@rStatusId int=0
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	SELECT 
			 --CONVERT(nvarchar(20),A.Id) AS AcademicIdText,
			 CONVERT(nvarchar(20),@rExamId) AS ExamIdText,
			 CONVERT(nvarchar(20),@rClassId) AS ClassIdText,
			 CONVERT (nvarchar(20),@rDivisionId) AS DivisionIdText,
	
			 CONVERT (nvarchar(20),SM.Title) AS SubjectName,
			
			 (Select COUNT(A.Id) from sStudent.tAcademic A	
				INNER JOIN sStudent.tStudentMaster StuM ON StuM.Id=A.StudentId
				INNER JOIN sStudent.tStudentOther SO ON SO.StudentId=A.StudentId
				WHERE CS.ClassId=@rClassId AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId = 0)) AND ((StuM.StatusId=@rStatusId)OR(@rStatusId=0)) AND A.BatchId=@rBatchId  AND SO.GenderId=2) AS TotalGirls,
		
			 (Select COUNT(A.Id) from sStudent.tAcademic A
				INNER JOIN sStudent.tStudentMaster StuM ON StuM.Id=A.StudentId
				INNER JOIN sStudent.tStudentOther SO ON SO.StudentId=A.StudentId
				WHERE ClassId=@rClassId AND ((DivisionId=@rDivisionId) OR (@rDivisionId = 0)) AND ((StuM.StatusId=@rStatusId)OR(@rStatusId=0)) AND BatchId=@rBatchId AND SO.GenderId=1) AS TotalBoys,
			
			 (Select COUNT(A.Id) from sStudent.tAcademic A
				INNER JOIN sStudent.tStudentMaster SM ON SM.Id=A.StudentId
				INNER JOIN sStudent.tStudentOther SO ON SO.StudentId=A.StudentId
				WHERE ClassId=@rClassId AND ((DivisionId=@rDivisionId) OR (@rDivisionId = 0)) AND ((SM.StatusId=@rStatusId)OR(@rStatusId=0)) AND BatchId=@rBatchId AND SO.GenderId=2 AND SM.StatusId=3) AS LeftGirls,
			
			 (Select COUNT(A.Id) from sStudent.tAcademic A
				
				INNER JOIN  sStudent.tStudentMaster SM ON SM.Id= A.StudentId
				INNER JOIN sStudent.tStudentOther SO ON SO.StudentId=A.StudentId
				WHERE ClassId=@rClassId AND ((DivisionId=@rDivisionId) OR (@rDivisionId = 0)) AND ((SM.StatusId=@rStatusId)OR(@rStatusId=0)) AND BatchId=@rBatchId AND SO.GenderId=1 AND SM.StatusId=3) AS LeftBoys,
			
			
			 (Select COUNT(R.AcademicId) from sAssessment.tResult R 
				INNER JOIN sAssessment.tResultDetail RD ON R.Id = RD.ResultId
				INNER JOIN sAssessment.tExamDetail ED ON Rd.ExamDetailId = ED.Id
				INNER JOIN sStudent.tAcademic A ON A.Id=R.AcademicId
				INNER JOIN  sStudent.tStudentMaster SM ON SM.Id= A.StudentId
				INNER JOIN sStudent.tStudentOther SO ON SO.StudentId=A.StudentId
				 WHERE A.ClassId=@rClassId AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId = 0)) AND ((SM.StatusId=@rStatusId)OR(@rStatusId=0)) AND A.BatchId=@rBatchId AND R.ExamId=@rExamId AND SO.GenderId=2
				 AND ED.ClassSubjectId = EDO.ClassSubjectId
				 )  AS AppearedGirls,
				 
			(Select COUNT(R.AcademicId) from sAssessment.tResult R 
				INNER JOIN sAssessment.tResultDetail RD ON R.Id = RD.ResultId
				INNER JOIN sAssessment.tExamDetail ED ON Rd.ExamDetailId = ED.Id
				INNER JOIN sStudent.tAcademic A ON A.Id=R.AcademicId
				INNER JOIN  sStudent.tStudentMaster SM ON SM.Id= A.StudentId
				INNER JOIN sStudent.tStudentOther SO ON SO.StudentId=A.StudentId
				 WHERE A.ClassId=@rClassId AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId = 0)) AND ((SM.StatusId=@rStatusId)OR(@rStatusId=0)) AND A.BatchId=@rBatchId AND R.ExamId=@rExamId AND SO.GenderId=1
				 AND ED.ClassSubjectId = EDO.ClassSubjectId
				
				) AS AppearedBoys,	
				
			 (Select COUNT(R.AcademicId) from sAssessment.tResult R 
				INNER JOIN sAssessment.tResultDetail RD ON R.Id = RD.ResultId
				INNER JOIN sAssessment.tExamDetail ED ON Rd.ExamDetailId = ED.Id
				INNER JOIN sStudent.tAcademic A ON A.Id=R.AcademicId
				INNER JOIN  sStudent.tStudentMaster SM ON SM.Id= A.StudentId
				INNER JOIN sStudent.tStudentOther SO ON SO.StudentId=A.StudentId
				 WHERE A.ClassId=@rClassId AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId = 0)) AND ((SM.StatusId=@rStatusId)OR(@rStatusId=0)) AND A.BatchId=@rBatchId AND R.ExamId=@rExamId AND SO.GenderId=2
				 AND ED.ClassSubjectId = EDO.ClassSubjectId AND RD.IsPresent=0
				) AS AbsentGirls,
				
			 (Select COUNT(R.AcademicId) from sAssessment.tResult R 
				INNER JOIN sAssessment.tResultDetail RD ON R.Id = RD.ResultId
				INNER JOIN sAssessment.tExamDetail ED ON Rd.ExamDetailId = ED.Id
				INNER JOIN sStudent.tAcademic A ON A.Id=R.AcademicId
				INNER JOIN  sStudent.tStudentMaster SM ON SM.Id= A.StudentId
				INNER JOIN sStudent.tStudentOther SO ON SO.StudentId=A.StudentId
				 WHERE A.ClassId=@rClassId AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId = 0)) AND ((SM.StatusId=@rStatusId)OR(@rStatusId=0)) AND A.BatchId=@rBatchId AND R.ExamId=@rExamId AND SO.GenderId=1
				 AND ED.ClassSubjectId = EDO.ClassSubjectId AND RD.IsPresent=0
				) AS AbsentBoys,
			 
			 (Select COUNT(R.AcademicId) from sAssessment.tResult R 
				INNER JOIN sAssessment.tResultDetail RD ON R.Id = RD.ResultId
				INNER JOIN sAssessment.tExamDetail ED ON Rd.ExamDetailId = ED.Id
				INNER JOIN sStudent.tAcademic A ON A.Id=R.AcademicId
				INNER JOIN  sStudent.tStudentMaster SM ON SM.Id= A.StudentId
				INNER JOIN sStudent.tStudentOther SO ON SO.StudentId=A.StudentId
				 WHERE A.ClassId=@rClassId AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId = 0)) AND ((SM.StatusId=@rStatusId)OR(@rStatusId=0)) AND A.BatchId=@rBatchId AND R.ExamId=@rExamId AND SO.GenderId=2
				 AND ED.ClassSubjectId = EDO.ClassSubjectId AND RD.Obtain >= ED.Minimum AND ISNULL(RD.GraceMark,0) = 0
				 ) AS PassedGirls,
				
			 (Select COUNT(R.AcademicId) from sAssessment.tResult R 
				INNER JOIN sAssessment.tResultDetail RD ON R.Id = RD.ResultId
				INNER JOIN sAssessment.tExamDetail ED ON Rd.ExamDetailId = ED.Id
				INNER JOIN sStudent.tAcademic A ON A.Id=R.AcademicId
				INNER JOIN  sStudent.tStudentMaster SM ON SM.Id= A.StudentId
				INNER JOIN sStudent.tStudentOther SO ON SO.StudentId=A.StudentId
				 WHERE A.ClassId=@rClassId AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId = 0)) AND ((SM.StatusId=@rStatusId)OR(@rStatusId=0)) AND A.BatchId=@rBatchId AND R.ExamId=@rExamId AND SO.GenderId=1
				 AND ED.ClassSubjectId = EDO.ClassSubjectId AND RD.Obtain >= ED.Minimum AND ISNULL(RD.GraceMark,0)=0
				 ) AS PassedBoys,
				
			 (Select COUNT(R.AcademicId) from sAssessment.tResult R 
				INNER JOIN sAssessment.tResultDetail RD ON R.Id = RD.ResultId
				INNER JOIN sAssessment.tExamDetail ED ON Rd.ExamDetailId = ED.Id
				INNER JOIN sStudent.tAcademic A ON A.Id=R.AcademicId
				INNER JOIN  sStudent.tStudentMaster SM ON SM.Id= A.StudentId
				INNER JOIN sStudent.tStudentOther SO ON SO.StudentId=A.StudentId
				 WHERE A.ClassId=@rClassId AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId = 0)) AND ((SM.StatusId=@rStatusId)OR(@rStatusId=0)) AND A.BatchId=@rBatchId AND R.ExamId=@rExamId AND SO.GenderId=2
				 AND ED.ClassSubjectId = EDO.ClassSubjectId AND RD.Obtain + RD.GraceMark >= ED.Minimum AND ISNULL(RD.GraceMark,0) > 0
				 ) AS PassWithGraceGirls,
				
			 (Select COUNT(R.AcademicId) from sAssessment.tResult R 
				INNER JOIN sAssessment.tResultDetail RD ON R.Id = RD.ResultId
				INNER JOIN sAssessment.tExamDetail ED ON Rd.ExamDetailId = ED.Id
				INNER JOIN sStudent.tAcademic A ON A.Id=R.AcademicId
				INNER JOIN  sStudent.tStudentMaster SM ON SM.Id= A.StudentId
				INNER JOIN sStudent.tStudentOther SO ON SO.StudentId=A.StudentId
				 WHERE A.ClassId=@rClassId AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId = 0)) AND ((SM.StatusId=@rStatusId)OR(@rStatusId=0)) AND A.BatchId=@rBatchId AND R.ExamId=@rExamId AND SO.GenderId=1
				 AND ED.ClassSubjectId = EDO.ClassSubjectId AND RD.Obtain + RD.GraceMark >= ED.Minimum AND ISNULL(RD.GraceMark,0) > 0
				  ) AS PassWithGraceBoys,
				
			 (Select COUNT(R.AcademicId) from sAssessment.tResult R 
				INNER JOIN sAssessment.tResultDetail RD ON R.Id = RD.ResultId
				INNER JOIN sAssessment.tExamDetail ED ON Rd.ExamDetailId = ED.Id
				INNER JOIN sStudent.tAcademic A ON A.Id=R.AcademicId
				INNER JOIN  sStudent.tStudentMaster SM ON SM.Id= A.StudentId
				INNER JOIN sStudent.tStudentOther SO ON SO.StudentId=A.StudentId
				 WHERE A.ClassId=@rClassId AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId = 0)) AND ((SM.StatusId=@rStatusId)OR(@rStatusId=0)) AND A.BatchId=@rBatchId AND R.ExamId=@rExamId AND SO.GenderId=2
				 AND ED.ClassSubjectId = EDO.ClassSubjectId AND RD.Obtain + ISNULL(RD.GraceMark,0) < ED.Minimum 
				 ) AS FailedGirls,
				
			 (Select COUNT(R.AcademicId) from sAssessment.tResult R 
				INNER JOIN sAssessment.tResultDetail RD ON R.Id = RD.ResultId
				INNER JOIN sAssessment.tExamDetail ED ON Rd.ExamDetailId = ED.Id
				INNER JOIN sStudent.tAcademic A ON A.Id=R.AcademicId
				INNER JOIN  sStudent.tStudentMaster SM ON SM.Id= A.StudentId
				INNER JOIN sStudent.tStudentOther SO ON SO.StudentId=A.StudentId
				 WHERE A.ClassId=@rClassId AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId = 0)) AND ((SM.StatusId=@rStatusId)OR(@rStatusId=0)) AND A.BatchId=@rBatchId AND R.ExamId=@rExamId AND SO.GenderId=1
				 AND ED.ClassSubjectId = EDO.ClassSubjectId AND RD.Obtain +ISNULL(RD.GraceMark ,0)< ED.Minimum  
				 ) AS FailedBoys,
				
			 (Select COUNT(A.Id) from sStudent.tAcademic A	
				INNER JOIN sStudent.tStudentMaster SM ON SM.Id= A.StudentId
				INNER JOIN sStudent.tStudentOther SO ON SO.StudentId=A.StudentId
				WHERE A.ClassId=@rClassId AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId = 0)) AND ((SM.StatusId=@rStatusId)OR(@rStatusId=0)) AND A.BatchId=@rBatchId) AS Total,
			--A.RollNo,
			--A.Id AS AcademicId,
			
			SM.Title AS SubjectName,
			SM.Id AS SubjectId
		 
		 
			FROM 
			
			sAssessment.tExamMaster EM
			INNER JOIN sAssessment.tExamDetail EDO ON EDO.ExamId=EM.Id
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=EDO.ClassSubjectId
			INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=CS.SubjectId
			INNER JOIN sSetup.tDivisionMaster DM ON DM.ClassId=CS.ClassId
		
	WHERE 
		 
	 ((EM.Id=@rExamId) OR (@rExamId=0))
	 AND((CS.ClassId =@rClassId) OR (@rClassId=0))
	 AND((DM.Id =@rDivisionId)  OR(@rDivisionId=0))
	 
	 AND(EM.BatchId=@rBatchId)
		order by CS.OrderIndex
	
END
GO
PRINT N'Altering [sAssessment].[pRptStudentTopperClassSectionWise]...';


GO




ALTER PROCEDURE [sAssessment].[pRptStudentTopperClassSectionWise]
	 
	--  @rAcademicId bigint=0,
	 @rExamId int=0,
	 @rClassId int=0, 
	 @rBatchId int=0,
	 --@rDivisionId int=0,
	 @rStatusId int=0
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
SELECT r1.*
FROM
(	
	SELECT  
	 
			R.Percentage,
			ROW_NUMBER() OVER(PARTITION BY 
				  CM.Id 
			 ORDER BY R.Percentage DESC) CM ,
	 		--CONVERT(nvarchar(20),A.Id) AS AcademicIdText,
		    CONVERT(nvarchar(20),@rExamId) AS ExamIdText,
		    CONVERT(nvarchar(20),@rClassId) AS ClassIdText,
		    --CONVERT(nvarchar(20),@rDivisionId) AS DivisionIdText,
					
		      R.RankNumber AS RankNumber,	
		      
			 R.TotalObtain AS ObtMarks,
			   
			 R.TotalMarks AS  OutOfMarks,
				
			 CM.Title + '-' + DM.Title AS ClassDivision,
			STM.FirstName + ' ' + STM.LastName AS Name,
			A.RollNo ,
			 DM.Id AS DivisionId
			 
			 
			
		 FROM
			sAssessment.tExamMaster EM
			INNER JOIN sAssessment.tResult R ON EM.Id=R.ExamId 
		    INNER JOIN sStudent.tAcademic A	ON A.Id=R.AcademicId
			INNER JOIN sStudent.tStudentMaster STM ON STM.Id=A.StudentId
		  
		   INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId
			INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId
			
	 WHERE 
		 ((EM.Id=@rExamId) OR (@rExamId=0))
		 AND ((EM.ClassId=@rClassId) OR (@rClassId=0))
		 
		 AND ((R.RankNumber <=3) AND (R.RankNumber<>0))
		 AND ((STM.StatusId=@rStatusId)OR(@rStatusId=0))
			 
		)r1
		WHERE((r1.CM <=3) OR (r1.Cm=0))
			
			 
		
END
GO
PRINT N'Altering [sAssessment].[pRptStudentTopperClassWise]...';


GO




ALTER PROCEDURE [sAssessment].[pRptStudentTopperClassWise]
	 
	 -- @rAcademicId bigint=0,
	 @rExamId int=0,
	 @rClassId int=0,
	 @rDivisionId int=0,
	 @rBatchId int=0,
	 @rStatusId int=0
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	SELECT  
			
			 
			R.Percentage,
	 		--CONVERT(nvarchar(20),A.Id) AS AcademicIdText,
		    CONVERT(nvarchar(20),@rExamId) AS ExamIdText,
		    CONVERT(nvarchar(20),@rClassId) AS ClassIdText,
		    CONVERT(nvarchar(20),@rDivisionId) AS DivisionIdText,
				
		      R.RankNumber AS RankNumber,	
		      
			R.TotalObtain AS ObtMarks,
			 R.TotalMarks AS OutOfMarks,
			 
			STM.FirstName + ' ' + STM.LastName AS Name,
			A.RollNo,
			A.Id AS AcademicId,
			EM.Id AS ExamId
			
		 
			FROM 
				sAssessment.tExamMaster EM
			INNER JOIN sAssessment.tResult R ON EM.Id=R.ExamId
		    INNER JOIN sStudent.tAcademic A	ON A.Id=R.AcademicId
			INNER JOIN sStudent.tStudentMaster STM ON STM.Id=A.StudentId
		 
		 
	 WHERE 
		 ((EM.Id=@rExamId) OR (@rExamId=0))
		 AND((EM.ClassId=@rClassId) OR (@rClassId=0))
		 AND((A.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		  
		 AND ((R.RankNumber <= 3) AND(R.RankNumber<>0))
		 AND ((STM.StatusId=@rStatusId)OR(@rStatusId=0))
			order by A.DivisionId,R.RankNumber 
	 
END
GO
PRINT N'Altering [sAssessment].[pRptSubjectResultListFloating]...';


GO
ALTER PROCEDURE [sAssessment].[pRptSubjectResultListFloating]
	 
	 @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,
	 @rToRollNo int,
	 @rFromRank int=0,
	 @rToRank int=0,
	 @rGrade nvarchar(20)='',
	 @rResultId bigint=0,
	 @rStatusId int=0,
	 @rAcademicId bigint=0,
	@rIsShowWithDetail bit =0,
	@rFilterId int=0,
	@rOrgGroupBatchId int=0,
	@rClassStatusId int=0
	 
	
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
 --Select * from dbo.Float
 --Select
 --           ''  AS AcademicIdText,
	--		'' AS ExamIdText,
	--		'' AS IsDisplayMonthlyAttendanceText,
	--		'' AS Exam,
	--		'' AS Builder1,
	--		'' Code,
	--		'' AS Name,
	--		0 RollNo,
	--		Convert(BigInt ,0) AS AcademicId,			
	--		'' ResultStatus,
	--		'' AS Class,
	--		'' AS Division,
	--		Convert(decimal , 0) TotalMarks,
	--		Convert(decimal , 0) TotalObtain,
	--		Convert(decimal , 0) Percentage,
	--		0 RankNumber,
	--		'' ResultGrade,
	--		Convert(decimal , 0) Percentile,			
	--		Convert(BigInt ,0) AS ResultDetailId,		
	--		Convert(bit, 0) IsDisplayInMarksheet,
	--		Convert(bit, 0) IsShowSubjectGrade,
	--		Convert(bit, 0) IsIncludeInTotal,
	--		Convert(decimal , 0) AS SubjectObtain,
	--		Convert(decimal , 0) AS SubjectMinimum,
	--		Convert(decimal , 0) AS SubjectMaximum,			
	--		'' AS SubjectCode,
	--		'' AS SubjectName,
	--		0 AS SubjectOrderIndex,
	--		Convert(BigInt ,0) AS ResultId,
	--		0 AS SubjectId,			 	
	--		Convert(bit, 0) IsMarksInDecimal,
			
	--		 '' AS Remark1,
	--		'' AS Remark2,
	--		'' AS Remark3,
	--		'' DisplayTitle,
	--		Convert(bit, 0) IsRankNo, 
	--		Convert(bit, 0) IsGrade,
	--		Convert(bit, 0) IsPercentile,
	--		Convert(bit, 0) IsPercentage,
	--		Convert(bit, 0) IsSubjectPercentile,
	--		Convert(bit, 0) IsProcessResult,
			 
	--		Convert(bit, 0) IsNegativeMarks,
	--		Convert(bit, 0) IsIncludeCoScholastic,
	--		Convert(bit, 0) IsOnPrePrinted,
	--		Convert(bit, 0) IsDisplayPhoto,
	--		Convert(bit, 0) IsDisplayBirthDate,
	--		Convert(bit, 0) IsLockForEdit,
	--		Convert(bit, 0) IsDisplaySchoolName,			
	--		Convert(bit, 0) IsDisplayAttendance,
	--		Convert(bit, 0) IsDisplayHeightWeight,
	--		Convert(bit, 0) IsResultStatus,
	--		'' AS FooterAdjustmentText,
	--		'' AS DetailAdjustmentText,
	--		0 FooterAdjustment,
	--		0 DetailAdjustment,
		 		 
	--		0 TermScopeId,
		 
	--		Convert(bit, 0) IsPresent,
	--		'' AS GradeString,
	--		Convert(bit, 0) IsDisplayGradeString,
	--		Convert(decimal , 0) HighestDivisionMark,
	--		 ''  AS HighestDivisionGrade,			
	--		'' SmallAddress1,
	--		Convert(bit, 0) IsDisplayParentName,
			 
	--		Convert(bit, 0) AS IsShowSubjectMark,
			
	--		Convert(bit, 0) IsDisplayTeacherSign,
	--		Convert(bit, 0) IsDisplayPrincipalSign,
		 
	--		Convert(bit, 0) AS IsDisplayMonthlyAttendance,
			 
	--		Convert(bit, 0) AS IsImageHeader,
			 
	--		0 SubExamId,
	--		0 ExamOrderIndex,
	--		0 AnnualExamId ,
	--		'' DecimalFormat,
	--		0 TermExamId,
	--		'' AS ExamNAme, 			 
	--		'' AS AnnualSubjectGrade,
	--		Convert(decimal , 0) As AnnualSubjectObtain,
	--		'' AS TermSubjectGrade,
	--		Convert(decimal , 0) As TermSubjectObtain ,
	--		'' AS SubjectGrade,
	--      '' AS Remark,
	--      Convert(decimal , 0) AS ExamMaximum,
	--	  Convert(bit, 0) IsAbsentRemark,
	--	  '' AS AbsentRemark
	  
			
 
 
 
DECLARE @GradeString nvarchar(1000),
@GradeSetId int, @lOrgId int, @lAbsentRemarkConfig nvarchar(20) = ''
 
SELECT @GradeSetId = GradesetId FROM sAssessment.tExamMaster WHERE Id = @rExamId
SELECT @GradeString = [sAssessment].[fGradeStringGet](@GradeSetId)  
SELECT @lOrgId=OrgId FROM sSetup.tBatchMaster WHERE Id=@rBatchId
SELECT @lAbsentRemarkConfig =ItemValue From sConfig.tConfigurationSetup WHERE ConfigurationId = 515 AND SourceTypeId = 1016 AND SourceId = @lOrgId

CREATE TABLE #TempExam
(
	SubExamId int, 
	ExamOrderIndex int,
	TermExamId int,
	AnnualExamId int, 
	Exam nvarchar(50),
	ExamMaximum decimal(6,2) 
)
--INSERT INTO #TempExam
--(
--	SubExamId,	 
--	ExamOrderIndex,
--	ExamId,
--	Exam 
--)
--Select 
	 
--	EC.SubExamId,
--	EC.ExamOrder,
--	EM.Id As ExamId,
--	ES.Title AS Exam
--	from sAssessment.tExamMaster EM 
--	INNER JOIN sAssessment.tExamCombine EC ON EC.ExamId = EM.Id 
--	INNER JOIN sAssessment.tExamSubGroupMaster ES ON ES.Id = EM.ExamSubGroupId 
--	WHERE EM.Id=@rExamId 
Declare @lExamMaximum decimal(6,2)
Select @lExamMaximum = ExamMaximum from sAssessment.tExamMaster Where Id = @rExamId
INSERT INTO #TempExam
(
	 SubExamId,
	 ExamOrderIndex,
	 TermExamId,
	 AnnualExamId,
	 Exam,
	 ExamMaximum 
	
)
Select  
	EC.SubExamId,
	EC.ExamOrder,
	EC.ExamId AS TermExamId,
	@rExamId AS AnnualExamId,
	ES.Title AS Exam,
	@lExamMaximum
	from  sAssessment.tExamCombine EC 
	INNER JOIN sAssessment.tExamMaster EM  ON EC.ExamId = EM.Id 
	 INNER JOIN sAssessment.tExamSubGroupMaster ES ON ES.Id = EM.ExamSubGroupId
	 INNER JOIN (select SubExamId from sAssessment.tExamCombine where examId = @rExamId) AS SE
	 ON EC.ExamId = SE.SubExamId  
	--WHere EC.ExamId  in  (select SubExamId from sAssessment.tExamCombine where examId = @rExamId  )
	--Select * from #TempExam
	
 
		
	
	
	
--INSERT INTO #TempExam
--(
--	ExamId, 
--	ExamOrderIndex
--)
--Select 
	 
--	@rExamId,
--	999 
	 --Select * from #TempExam
	SELECT 
			Convert(nvarchar(20),A.Id) AS AcademicIdText,
			Convert(nvarchar(20),@rExamId) AS ExamIdText,
			Convert(nvarchar(20),ISNULL(EM.IsDisplayMonthlyAttendance,0)) AS IsDisplayMonthlyAttendanceText,
			ESGM.Title AS Exam,
			 @rBuilder1 AS Builder1,
			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,			
			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.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,
		 		 
			EM.TermScopeId,
		 
			RD.IsPresent,
			@GradeString 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,
			 
			ISNULL(ED.IsShowSubjectMark,1) AS IsShowSubjectMark,
			
			EM.IsDisplayTeacherSign,
			Em.IsDisplayPrincipalSign,
		 
			ISNULL(EM.IsDisplayMonthlyAttendance,0) AS IsDisplayMonthlyAttendance,
			 
			ISNULL(EM.IsDisplayImageHeader,0) AS IsImageHeader,
			 
			EC.SubExamId,
			EC.ExamOrderIndex,
			EC.AnnualExamId ,
			EM.DecimalFormat,
			EC.TermExamId,
			EC.Exam AS ExamNAme, 			 
			ARD.SubjectGrade AS AnnualSubjectGrade,
			ARD.Obtain As AnnualSubjectObtain,
			TRD.SubjectGrade AS TermSubjectGrade,
			TRD.Obtain As TermSubjectObtain ,
			RD.SubjectGrade AS SubjectGrade,
			ISNULL(ARD.Remark,'')  AS Remark,
			EC.ExamMaximum,
			CONVERT(bit,@lAbsentRemarkConfig) AS IsAbsentRemark,
			ISNULL(RD.AbsentRemark,'') AS AbsentRemark
	FROM 
			sAssessment.tResultDetail RD
			INNER JOIN sAssessment.tResult R ON R.Id = RD.ResultId
			INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId
			INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId		
			INNER JOIN #TempExam EC ON EC.SubExamId = EM.Id 	
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id = EM.EXAMSUBGROUPID
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=CS.SubjectId					 
			INNER JOIN sStudent.tAcademic A ON A.Id=R.AcademicId	
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId		
			INNER JOIN sStudent.tStudentMaster StuM ON StuM.Id=A.StudentId			
			INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId
			INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId			
			INNER JOIN sSetup.tOrganizationMaster OM ON StuM.OrgId = OM.Id			
			INNER JOIN sAssessment.tResult AR ON AR.AcademicId = A.Id AND AR.ExamId = EC.AnnualExamId 
			INNER JOIN sAssessment.tResultDetail ARD ON AR.Id = ARD.ResultId 
			INNER JOIN sAssessment.tExamDetail AED ON ARD.EXamDetailId = AED.Id 
			INNER JOIN sSetup.tClassSubject ACS ON AED.ClassSubjectId = ACS.Id AND ACS.SubjectId = @rSubjectId  
			INNER JOIN sAssessment.tResult TR ON TR.AcademicId = A.Id AND TR.ExamId = EC.TermExamId 
			INNER JOIN sAssessment.tResultDetail TRD ON TR.Id = TRD.ResultId 
			INNER JOIN sAssessment.tExamDetail TED ON TRD.EXamDetailId = TED.Id 
			INNER JOIN sSetup.tClassSubject TCS ON TED.ClassSubjectId = TCS.Id AND TCS.SubjectId = @rSubjectId 
			
			
			LEFT JOIN sHostel.tAssignRoom ARO ON  ARO.SourceId=StuM.Id AND ARO.SourceTypeId=2003 AND ((BM.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  AND ((ARO.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0) AND (BM.OrgGroupBatchId = ARO.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 
				
			--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
			--LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId=A.StudentId
			--LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId=StuM.Id
			--LEFT JOIN sHrm.tEmployeeImages EI ON EI.EmployeeId = Dm.InchargeEmployeeId
			--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
	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 (
	 (@rFilterId = 0) -- All
     OR (@rFilterId = 2 AND isnull(ARO.SourceId,0)!=0) -- Hostel
     OR (@rFilterId = 3 AND isnull(RT.SourceId,0)!=0) -- Transport
     OR ((@rFilterId =1) AND ((isnull(ARO.SourceId,0)=0) AND (isnull(RT.SourceId,0)=0)))
    ) 
	AND ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0))
		--order by A.RollNo,CS.OrderIndex 
		
	 drop table #TempExam
		
END
GO
PRINT N'Altering [sAssessment].[pValidateImportSubjectActivity]...';


GO
ALTER PROCEDURE [sAssessment].[pValidateImportSubjectActivity]
     @rOrgId smallint,
	 @rXmldoc [nvarchar](max)
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
DECLARE @lCount INT
DECLARE @lInterrorCode INT,@intDoc INT, @lCode nvarchar(100),  @lTitle nvarchar(200), @lNumber int,@lClass nvarchar(100), 
        @lSubCode nvarchar(100),  @lSubTitle nvarchar(200), @lSubNumber int,@lSubClass nvarchar(100),@1SubOrderIndex int,
	    @lSubject nvarchar(100), @1OrderIndex int,  @1ReturnCode int = 1,@lGradeSet nvarchar(100),@1SubDuplicateCode nvarchar(max) = '',
        @1ExistCode nvarchar(max) = '',@1DuplicateCode nvarchar(max) = '', @1ExistOrderIndex nvarchar(max) = '',
        @1DuplicateTitle nvarchar(max) = '', @1DuplicateOrderIndex nvarchar(max) = '', @1SubDuplicateTitle nvarchar(max) = '', @1SubDuplicateOrderIndex nvarchar(max) = '',
        @1ExistNumber nvarchar(max) = '',@1ExistTitle nvarchar(max) = '',@lClassSubjectId int,@lOrderIndex int,@1DuplicateNumber nvarchar(max)='',@SubDuplicateNumber nvarchar(max)='',
        @1SubExistNumber nvarchar(max) = '',@1SubExistTitle nvarchar(max) = '', @1SubExistCode nvarchar(max) = '',@1SubExistOrderIndex nvarchar(max) = '',@lSubjectActivityId int=0
EXECUTE @lInterrorCode = sp_xml_preparedocument @intDoc OUTPUT, @rXmlDoc
CREATE TABLE #tTable1 
 (
		Id bigint identity,
		Code nvarchar(100), 
		Name nvarchar(200),
		Number int, 
	    OrderIndex int,
		GradeSet nvarchar(100),
	    Class Nvarchar(100),
	    Subject Nvarchar(100),
	    SubNumber int, 
		SubCode nvarchar(100), 
		SubName nvarchar(200),
		SubOrderIndex int
  )
  INSERT INTO #tTable1(Code,Name,Number,OrderIndex,GradeSet,Class,Subject,SubNumber,SubCode,SubName,SubOrderIndex)
    
   SELECT
          Code,Name,Number,OrderIndex,GradeSet,Class,Subject,SubNumber,SubCode,SubName,SubOrderIndex
   FROM OPENXML (@intDoc, '/Table/ImportSubjectActivity', 1)
   With
   (
        Code nvarchar(100) '@Code',			
		Name nvarchar(200) '@Name',			
		Number int '@Number',			
		GradeSet nvarchar(100) '@GradeSet',			
		OrderIndex int '@OrderIndex',
		Class nvarchar(100) '@Class',
		Subject  nvarchar(100) '@Subject',
		SubNumber int '@SubNumber',
		SubCode nvarchar(100) '@SubCode',			
		SubName nvarchar(200) '@SubName',
		SubOrderIndex int '@SubOrderIndex'
   )     
   
EXEC sp_xml_removedocument @intDoc
			
IF EXISTS(SELECT 1 fROM #tTable1 WHERE Code IS NULL OR Code COLLATE DATABASE_DEFAULT='' COLLATE DATABASE_DEFAULT)
BEGIN
	SELECT 'Code Should not be empty' AS ValidateCode
END
 IF EXISTS(SELECT 1 fROM #tTable1 WHERE Name IS NULL OR Name COLLATE DATABASE_DEFAULT='' COLLATE DATABASE_DEFAULT)
BEGIN
	SELECT 'Name Should not be empty' AS ValidateCode
END
 IF EXISTS(SELECT 1 fROM #tTable1 WHERE Class IS NULL OR Class COLLATE DATABASE_DEFAULT='' COLLATE DATABASE_DEFAULT)
BEGIN
	SELECT 'Class Should not be empty' AS ValidateCode
END
 IF EXISTS(SELECT 1 fROM #tTable1 WHERE Subject IS NULL OR Subject COLLATE DATABASE_DEFAULT='' COLLATE DATABASE_DEFAULT)
BEGIN
	SELECT 'Subject Should not be empty' AS ValidateCode
END
IF EXISTS(SELECT 1 fROM #tTable1 WHERE Number IS NULL OR Number ='')
BEGIN
	SELECT 'Number Should not be empty' AS ValidateCode
END
IF EXISTS(SELECT 1 fROM #tTable1 WHERE OrderIndex IS NULL OR OrderIndex ='')
BEGIN
	SELECT 'OrderIndex Should not be empty' AS ValidateCode
END
IF EXISTS(SELECT 1 fROM #tTable1 WHERE SubName IS NULL OR SubName COLLATE DATABASE_DEFAULT='' COLLATE DATABASE_DEFAULT)
BEGIN
	SELECT 'Sub Name Should not be empty' AS ValidateCode
END
IF EXISTS(SELECT 1 fROM #tTable1 WHERE SubCode IS NULL OR SubCode COLLATE DATABASE_DEFAULT='' COLLATE DATABASE_DEFAULT)
BEGIN
	SELECT 'Sub Code Should not be empty' AS ValidateCode
END
IF EXISTS(SELECT 1 fROM #tTable1 WHERE SubOrderIndex IS NULL OR SubOrderIndex ='')
BEGIN
	SELECT 'Sub OrderIndex Should not be empty' AS ValidateCode
END
IF EXISTS(SELECT 1 fROM #tTable1 WHERE SubNumber IS NULL OR SubNumber ='')
BEGIN
	SELECT 'Sub Number Should not be empty' AS ValidateCode
END
ELSE
BEGIN	
SELECT @lCount =  COUNT(Id) FROM #tTable1
WHILE @lCount > 0 
BEGIN
	SELECT @lCode = Code,@lTitle=Name,@lNumber=Number,@lOrderIndex=OrderIndex,@lSubject=Subject,@lClass=Class,@lGradeSet=GradeSet,
	@lSubCode =SubCode,@lSubTitle=SubName,@1SubOrderIndex=SubOrderIndex,@lSubNumber=SubNumber
	FROM #tTable1 WHERE Id = @lCount  
IF NOT EXists(SELECT  1 FROM sSetup.vClassSubject  VS
	INNER JOIN  sSetup.tClassMaster CM ON CM.Id=VS.ClassId where VS.IsObsolete=0 AND CM.Title=@lClass  AND Vs.SubjectName=@lSubject AND CM.OrgId=@rOrgId)
 BEGIN
     SELECT 'Enter proper value for Class  or Subject  :' + @lClass + '/' + @lSubject AS ValidateCode
    END
    ELSE
    BEGIN
    SET @lClassSubjectId=0
    SELECT @lClassSubjectId= ClassSubjectId FROM sSetup.vClassSubject  VS
	INNER JOIN  sSetup.tClassMaster CM ON CM.Id=VS.ClassId where VS.IsObsolete=0 AND CM.Title=@lClass  AND Vs.SubjectName=@lSubject AND CM.OrgId=@rOrgId 
    END
	 IF NOT EXists( SELECT 1 FROM sAssessment.tGradeSetMaster WHERE  OrgId=@rOrgId  AND Title=@lGradeSet )
  BEGIN
     SELECT 'Enter proper value for Gradeset : ' + @lGradeSet  AS ValidateCode
    END
 IF NOT Exists (select 1  FROM  sAssessment.tCCESubjectActivityMaster where OrgId=@rOrgId AND Code=@lCode AND ClassSubjectId = @lClassSubjectId )
 BEGIN
 SET @lSubjectActivityId=0
 END
 ELSE
 BEGIN
   SELECT @lSubjectActivityId=Id FROM   sAssessment.tCCESubjectActivityMaster   where OrgId=@rOrgId AND Code=@lCode
  IF Exists ((select 1 from sAssessment.tCCESubjectSubActivityMaster where OrgId=@rOrgId AND SubjectActivityId = @lSubjectActivityId AND Code COLLATE DATABASE_DEFAULT = @lSubCode COLLATE DATABASE_DEFAULT))         
    BEGIN
		SET @1SubExistCode = @1SubExistCode + @lSubCode + ','
    END	  
 IF Exists ((select 1 from sAssessment.tCCESubjectSubActivityMaster where OrgId=@rOrgId AND SubjectActivityId = @lSubjectActivityId AND Title COLLATE DATABASE_DEFAULT = @lSubTitle COLLATE DATABASE_DEFAULT))         
    BEGIN
		SET @1SubExistTitle = @1SubExistTitle + @lSubTitle + ','
    END	  
  IF Exists ((select 1 from sAssessment.tCCESubjectSubActivityMaster where OrgId=@rOrgId AND OrderIndex =Convert(varchar,@1SubOrderIndex) AND SubjectActivityId = @lSubjectActivityId AND Convert(varchar,OrderIndex) COLLATE DATABASE_DEFAULT = Convert(varchar,@1SubOrderIndex) COLLATE DATABASE_DEFAULT))         
    BEGIN
		SET @1SubExistOrderIndex= @1SubExistOrderIndex + Convert(varchar,@1SubOrderIndex )+ ','
    END	  
 IF Exists ((select 1 from sAssessment.tCCESubjectSubActivityMaster where OrgId=@rOrgId AND Number =Convert(varchar,@lSubNumber) AND SubjectActivityId = @lSubjectActivityId AND Convert(varchar,Number) COLLATE DATABASE_DEFAULT = Convert(varchar,@lSubNumber) COLLATE DATABASE_DEFAULT))               
    BEGIN
		SET @1SubExistNumber= @1SubExistNumber + Convert(varchar,@lSubNumber) + ','
    END	  
  END
  IF Exists ((select 1 from sAssessment.tCCESubjectActivityMaster where OrgId=@rOrgId AND OrderIndex =Convert(varchar,@lOrderIndex) AND Convert(varchar,OrderIndex) COLLATE DATABASE_DEFAULT = Convert(varchar,@lOrderIndex) COLLATE DATABASE_DEFAULT))         
    BEGIN
		SET @1ExistOrderIndex= @1ExistOrderIndex + Convert(varchar,@lOrderIndex )+ ','
    END	
	SET @lCount = @lCount - 1	
 END
 

	SELECT @1SubDuplicateCode=COALESCE(@1SubDuplicateCode ,'') + SubCode + ',' FROM #tTable1 GROUP BY SubCode,Class,subject,Code,Name HAVING ( COUNT(SubCode) > 1 )	
    SELECT @1SubDuplicateTitle=COALESCE(@1SubDuplicateTitle ,'') + SubName + ',' FROM #tTable1 GROUP BY SubName,Class,subject,Code,Name HAVING ( COUNT(SubName) > 1 )	
  	SELECT @1SubDuplicateOrderIndex=COALESCE(@1SubDuplicateOrderIndex,'')  + convert(varchar,SubOrderIndex) + ',' FROM #tTable1 GROUP BY SubOrderIndex,Class,subject,Code,Name HAVING ( COUNT(SubOrderIndex) > 1 )	
  	SELECT @SubDuplicateNumber=COALESCE(@SubDuplicateNumber,'')  + convert(varchar,SubNumber) + ',' FROM #tTable1 GROUP BY SubNumber,Class,subject,Code,Name HAVING ( COUNT(SubNumber) > 1 )
	SELECT @1DuplicateOrderIndex=COALESCE(@1DuplicateOrderIndex,'')  + convert(varchar,OrderIndex) + ',' FROM #tTable1 GROUP BY OrderIndex,Class,subject,Code,Name HAVING ( COUNT(OrderIndex) > 1 )		
	IF(@1SubDuplicateCode IS NOT NULL AND @1SubDuplicateCode != '')
	BEGIN
		SET @1SubDuplicateCode = 'Duplicate Sub Code : ' + @1SubDuplicateCode
	END
	IF(@1SubDuplicateTitle IS NOT NULL AND @1SubDuplicateTitle != '')
	BEGIN
	SET @1SubDuplicateTitle = 'Duplicate Sub Name : ' + @1SubDuplicateTitle
	END
	IF(@1SubDuplicateOrderIndex IS  NOT NULL AND @1SubDuplicateOrderIndex != '')
	BEGIN
	SET @1SubDuplicateOrderIndex = 'Duplicate Sub OrderIndex : ' + @1SubDuplicateOrderIndex
	END
	IF(@SubDuplicateNumber IS NOT NULL AND @SubDuplicateNumber != '')
	BEGIN
	SET @SubDuplicateNumber = 'Duplicate Sub Number : ' + @SubDuplicateNumber
	END
	 IF (@1SubExistCode IS NOT NULL AND @1SubExistCode != '' )
	BEGIN
		SET @1SubExistCode = 'Exist Sub Code : ' + @1SubExistCode
	END
	ELSE IF (@1SubExistCode IS NOT NULL AND @1SubExistCode = '' )
	BEGIN
		SET @1SubExistCode=''
	END
	 IF (@1SubExistTitle IS NOT NULL AND @1SubExistTitle != '' )
	BEGIN
		SET @1SubExistTitle = 'Exist Sub Title : ' + @1SubExistTitle
	END
	
	 IF (@1SubExistOrderIndex IS NOT NULL  AND @1SubExistOrderIndex != '' )
	BEGIN
		SET @1SubExistOrderIndex = 'Exist Sub OrderIndex : ' + @1SubExistOrderIndex
	END
	
	 IF (@1ExistOrderIndex IS NOT NULL  AND @1ExistOrderIndex != '' )
	BEGIN
		SET @1ExistOrderIndex = 'Exist OrderIndex : ' + @1ExistOrderIndex
	END

  	 IF (@1SubExistNumber IS NOT NULL AND @1SubExistNumber != '' )
	BEGIN
		SET @1SubExistNumber = 'Exist Sub Number : ' + @1SubExistNumber
	END
	END
	Select Isnull(@1SubDuplicateCode,'')+Isnull(@1SubDuplicateTitle,'')+Isnull(@SubDuplicateNumber,'')+Isnull(@1SubDuplicateOrderIndex,'')+
	Isnull(@1SubExistCode,'') +Isnull(@1SubExistTitle,'')+Isnull(@1SubExistNumber,'')+Isnull(@1SubExistOrderIndex,'') +Isnull(@1DuplicateOrderIndex,'')+Isnull(@1ExistOrderIndex,'')
	  AS ValidateCode
END
GO
PRINT N'Altering [sAssetManagement].[pAssetMasterListDataGet]...';


GO
ALTER PROCEDURE [sAssetManagement].[pAssetMasterListDataGet]
 	@rOrgGroupId smallint,

	@rId [int] = 0,
	@rCode [nvarchar](100) = '',
	@rTitle [nvarchar](100) = '',
	@rLocationId [int] = 0,
	@rIsWildCard [bit] = 0,
	@rStoreLocationId int,
	@rDepartmentId int

 	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN

SET @rCode  = ISNULL(@rCode, '') 
SET @rTitle = ISNULL(@rTitle, '') 

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

       SELECT AM.Id,
                  AM.Code,
                  AM.Title,
                  Specification,
                  Accessories,
                  AM.LocationId,
                  StatusId,
                  VendorId,
                  VM.Title AS VendorName,
                  GoodsReceiptNumber,
                  GoodsReceiptDate,
                  IsInstallationRequired,
                  InstallationDate,
                  CategoryId,
                  DepreciationUptoDate,
                  IsFullyDepreciated,
                  StandardPrice,
                  MinStockRequired,
                  MaintenancePeriod,
                  IsAmc,                  
                  MaintenanceAlertPeriod,
                  AmcVendorId,
                  VM1.Title AS AmcVendorName,
                  UsageStatusId,
                  LastServiceCost,
                  TotalServiceCost,
                  LastDownTime,
                  TotalDownTime,
                  LastMaintenanceDate,
                  NextMaintenanceDate,
                  ModelNumber,
                  IsCritical,
                  AM.IsObsolete,
                  AM.CreatedUserId,
                  AM.CreatedDateTime,
                  AM.UpdatedUserId,
                  AM.UpdatedDateTime,
                  AM.DepartmentID,
                  ServiceEntry,
                  ODM.Title AS DepartmentTitle,
                  VAD1.Title AS LocationTitle,
                  FCM.Title AS CategoryTitle,
                  CM.Title AS StatusTitle,
                  
                   AM.IsCheckRequired,
				  ISNULL (AM.CheckFrequencyId,0) AS CheckFrequencyId,	
				  AM.CheckList,	
                  --AM.CheckedLastDate,
                   ISNULL(AM.CheckedLastDate,'0001/01/01') AS CheckedLastDate,
                  AM.CheckedByUserId,
                  ISNULL(AM.CheckedStatusId,0) AS CheckedStatusId,
                  AM.CheckedRemark,
                  IsRenewRequired,
                  ISNULL(RenewLastDate,'0001/01/01') AS RenewLastDate,
                  ISNULL(RenewNextDate,'0001/01/01') AS RenewNextDate,
                --  AM.RenewLastDate,
                  --AM.RenewNextDate,
				  AM.RenewRemark,
				  AM.RenewCheckList,
				  AM.RenewAlertBeforeDays,
				  U.LoginTitle AS UserTitle
				,ISNULL (AM.IsMaintenanceRequired,0) AS IsMaintenanceRequired
				,ISNULL(AM.WarrantyDate,'0001/01/01') AS WarrantyDate
				,AM.AssetImage AS AssetImage
				,ISNULL(AM.AssetCode,'') AS AssetCode
         FROM sAssetManagement.tAssetMaster AM
         LEFT JOIN sProcurement.tVendorMaster VM
                  ON VM.Id = AM.VendorId 
         LEFT JOIN sProcurement.tVendorMaster VM1
                  ON VM1.Id = AM.AmcVendorId 
            --INNER JOIN (SELECT DISTINCT DepartmentId, DepartmentTitle FROM sAssetManagement.vExtAssetDepartment) VAD
            --ON VAD.DepartmentId = AM.DepartmentID
            INNER JOIN sSetup.tDepartmentMaster ODM ON ODM.Id = AM.DepartmentId
             --left JOIN sCommon.tOrganizationDepartmentMaster ODM ON ODM.Id = AM.DepartmentId
            INNER JOIN sFixedAsset.tLocationMaster VAD1
            ON VAD1.Id = AM.LocationId 
            INNER JOIN (SELECT DISTINCT Id, Title FROM sFixedAsset.tCategoryMaster ) FCM
            ON FCM.Id = AM.CategoryId
            INNER JOIN (SELECT DISTINCT Id, Title FROM sCommon.tStatusMaster) CM
            ON CM.Id = AM.UsageStatusId
             LEFT JOIN sSecurity.tUser U ON U.Id=AM.CheckedByUserId
        WHERE ((AM.Id = @rId) OR (@rId = 0)) 
		AND ((AM.Code LIKE @rCode) OR (@rCode = '')) 
		--AND ((AM.AssetCode LIKE @rAssetCode) OR (@rAssetCode = ''))
		AND ((AM.Title LIKE @rTitle) OR (@rTitle = ''))
        AND AM.OrgGroupId = @rOrgGroupId
        AND AM.StoreLocationId=@rStoreLocationId
        AND ((AM.LocationId = @rLocationId) OR (@rLocationId = 0))
        AND ((AM.DepartmentId = @rDepartmentId) OR (@rDepartmentId = 0))
        ORDER BY AM.Code DESC

END
GO
PRINT N'Altering [sAttendance].[pTakeAttendanceList]...';


GO

ALTER PROCEDURE [sAttendance].[pTakeAttendanceList]

	@rOrgId int=0,
	@rOrgGroupId int=0,
	@rUserId bigint =0,
	@rUserSourceId bigint = 0,
	@rAttendanceEntry nvarchar(100),
	@rOrgGroupBatchId int =0,
	@rAttendanceDate Date = null,
	@rAttendanceTypeId int =0,
	@rAttendanceTagId int =0,
	@rAbsentReasonId int =0
	
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
	IF(@rAttendanceEntry = 'Class Teacher')
	BEGIN
		SELECT DISTINCT CM.Id AS ClassId,DM.Id AS DivisionId,OM.Id AS OrgId,CM.DisplayTitle+'-'+DM.Title AS ClassDivision,OM.DisplayTitle AS OrganizationName,
		CM.OrderIndex AS ClassOrderIndex,DM.OrderIndex AS DivisionOrderIndex,OM.OrderIndex AS OrganizationOrderIndex,
		convert(bit,(SELECT CASE WHEN COUNT(*)>0 THEN 1 ELSE 0 END AS IsTakeAttendance  FROM sAttendance.tStudentRegister SR
		INNER JOIN sStudent.tAcademic A ON A.Id = SR.AcademicId 
		INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId 
		WHERE AttendanceTypeId=@rAttendanceTypeId AND AttendanceDate=@rAttendanceDate AND  BM.OrgGroupBatchId = @rOrgGroupBatchId AND A.ClassId=CM.Id AND A.DivisionId=DM.Id )) AS IsTakeAttendance,
		(SELECT ATM.Title FROM sAttendance.tStudentRegister SR INNER JOIN sAttendance.tAttendanceTagMaster ATM ON ATM.Id = SR.AttendanceTagId WHere ATM.Id =@rAttendanceTagId GROUP BY ATM.Title) AS AttendanceTag,
		(SELECT ARM.Title FROM sAttendance.tStudentRegister SR INNER JOIN sAttendance.tAbsentReasonMaster ARM ON ARM.Id =SR.AbsentReasonId  WHere  ARM.Id  =@rAbsentReasonId GROUP BY ARM.Title) AS AbsentReason
		FROM sSetup.tClassMaster CM 
		INNER JOIN sSetup.tDivisionMaster DM ON DM.ClassId = CM.Id
		INNER JOIN sSetup.tOrganizationMaster OM ON CM.OrgId = OM .Id
		WHERE DM.InchargeemployeeID= @rUserSourceId AND OM.OrgGroupId= @rOrgGroupId  AND CM.IsObsolete=0 AND DM.IsObsolete=0 
		ORDER BY OM.OrderIndex,CM.OrderIndex,DM.OrderIndex
	END
	ELSE IF(@rAttendanceEntry ='Academic Setup')
	BEGIN 
		SELECT DISTINCT TD.ClassId AS ClassId,TD.DivisionId AS DivisionId,OM.Id AS OrgId,TD.ClassTitle+'-'+TD.DivisionTitle AS ClassDivision,OM.DisplayTitle AS OrganizationName,
		CONVERT(bit,(SELECT CASE WHEN COUNT(*)>0 THEN 1 ELSE 0 END AS IsTakeAttendance  FROM sAttendance.tStudentRegister SR
		INNER JOIN sStudent.tAcademic A ON A.Id = SR.AcademicId 
		INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId 
		WHERE AttendanceTypeId=@rAttendanceTypeId AND AttendanceDate=@rAttendanceDate AND  BM.OrgGroupBatchId = @rOrgGroupBatchId AND A.ClassId=TD.ClassId AND A.DivisionId=TD.DivisionId )) AS IsTakeAttendance,
		(SELECT ATM.Title FROM sAttendance.tStudentRegister SR INNER JOIN sAttendance.tAttendanceTagMaster ATM ON ATM.Id = SR.AttendanceTagId WHere ATM.Id =@rAttendanceTagId GROUP BY ATM.Title) AS AttendanceTag,
		(SELECT ARM.Title FROM sAttendance.tStudentRegister SR INNER JOIN sAttendance.tAbsentReasonMaster ARM ON ARM.Id =SR.AbsentReasonId  WHere  ARM.Id  =@rAbsentReasonId GROUP BY ARM.Title) AS AbsentReason,
		TD.ClassOrderIndex AS ClassOrderIndex,OM.OrderIndex AS OrganizationOrderIndex 
		FROM sAcademic.vTeacherSubjectDivision TD
		INNER JOIN sSetup.tOrganizationMaster OM ON TD.OrgId = OM.Id
		WHERE TD.EmployeeId= @rUserSourceId  AND OM.OrgGroupId= @rOrgGroupId  AND CMIsObsolete=0  AND DMIsObsolete=0 
		ORDER BY OM.OrderIndex,TD.ClassOrderIndex
	END
	ELSE IF(@rAttendanceEntry ='User Access')
	BEGIN
		SELECT DISTINCT CM.Id AS ClassId,DM.Id AS DivisionId,OM.Id AS OrgId,CM.DisplayTitle+'-'+DM.Title AS ClassDivision,OM.DisplayTitle AS OrganizationName,
		convert(bit,(SELECT CASE WHEN COUNT(*)>0 THEN 1 ELSE 0 END AS IsTakeAttendance  FROM sAttendance.tStudentRegister SR
		INNER JOIN sStudent.tAcademic A ON A.Id = SR.AcademicId 
		INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId 
		WHERE AttendanceTypeId=@rAttendanceTypeId AND AttendanceDate=@rAttendanceDate AND BM.OrgGroupBatchId = @rOrgGroupBatchId AND A.ClassId=CM.Id AND A.DivisionId=DM.Id )) AS IsTakeAttendance,
		(SELECT ATM.Title FROM sAttendance.tStudentRegister SR INNER JOIN sAttendance.tAttendanceTagMaster ATM ON ATM.Id = SR.AttendanceTagId WHere ATM.Id =@rAttendanceTagId GROUP BY ATM.Title) AS AttendanceTag,
		(SELECT ARM.Title FROM sAttendance.tStudentRegister SR INNER JOIN sAttendance.tAbsentReasonMaster ARM ON ARM.Id =SR.AbsentReasonId  WHere  ARM.Id  =@rAbsentReasonId GROUP BY ARM.Title) AS AbsentReason,
		CM.OrderIndex AS ClassOrderIndex,DM.OrderIndex AS DivisionOrderIndex,OM.OrderIndex AS OrganizationOrderIndex
		from sSetup.tClassMaster CM 
		INNER JOIN sSetup.tDivisionMaster DM ON DM.ClassId = CM.Id
		INNER JOIN sSetup.tOrganizationMaster OM ON CM.OrgId = OM.Id
		INNER JOIN sSecurity.tUserAccess U ON U.SourceId = DM.Id 
		Where OM.OrgGroupId= @rOrgGroupId AND U.SourceTypeId=2005 AND U.UserId = @rUserId AND CM.IsObsolete=0 AND DM.IsObsolete=0 
		ORDER BY OM.OrderIndex,CM.OrderIndex,DM.OrderIndex
	END
	ELSE IF(@rAttendanceEntry = 'Class Teacher Batch')
	BEGIN
		SELECT DISTINCT CM.Id AS ClassId,DM.Id AS DivisionId,OM.Id AS OrgId,CM.DisplayTitle+'-'+DM.Title AS ClassDivision,OM.DisplayTitle AS OrganizationName,
		CM.OrderIndex AS ClassOrderIndex,DM.OrderIndex AS DivisionOrderIndex,OM.OrderIndex AS OrganizationOrderIndex,
		convert(bit,(SELECT CASE WHEN COUNT(*)>0 THEN 1 ELSE 0 END AS IsTakeAttendance  FROM sAttendance.tStudentRegister SR
		INNER JOIN sStudent.tAcademic A ON A.Id = SR.AcademicId 
		INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId 
		WHERE AttendanceTypeId=@rAttendanceTypeId AND AttendanceDate=@rAttendanceDate AND  BM.OrgGroupBatchId = @rOrgGroupBatchId AND A.ClassId=CM.Id AND A.DivisionId=DM.Id )) AS IsTakeAttendance,
		(SELECT ATM.Title FROM sAttendance.tStudentRegister SR INNER JOIN sAttendance.tAttendanceTagMaster ATM ON ATM.Id = SR.AttendanceTagId WHere ATM.Id =@rAttendanceTagId GROUP BY ATM.Title) AS AttendanceTag,
		(SELECT ARM.Title FROM sAttendance.tStudentRegister SR INNER JOIN sAttendance.tAbsentReasonMaster ARM ON ARM.Id =SR.AbsentReasonId  WHere  ARM.Id  =@rAbsentReasonId GROUP BY ARM.Title) AS AbsentReason
		FROM sSetup.tClassMaster CM 
		INNER JOIN sSetup.tDivisionMaster DM ON DM.ClassId = CM.Id
		INNER JOIN sSetup.tDivisionInchargeEmployee DIE ON DIE.DivisionId = DM.Id
		INNER JOIN sSetup.tOrganizationMaster OM ON CM.OrgId = OM .Id
		INNER JOIN sSetup.tBatchMaster BM ON BM.Id = DIE.BatchId AND BM.OrgGroupBatchId = @rOrgGroupBatchId
		WHERE DIE.EmployeeId= @rUserSourceId AND OM.OrgGroupId= @rOrgGroupId AND CM.IsObsolete=0 AND DM.IsObsolete=0 
		ORDER BY OM.OrderIndex,CM.OrderIndex,DM.OrderIndex
	END
	
END
GO
PRINT N'Altering [sAudit].[pActivityLogAdd]...';


GO
ALTER PROCEDURE [sAudit].[pActivityLogAdd]
	 
		@rOrgGroupId int=0,
		@rOrgId int,
		@rUserId bigint,
		@rSessionId nvarchar(100),
		@rScreenId int,
		@rActivity nvarchar(500),
		@rRecordSourceId bigint,
		@rRecordDetail nvarchar(max),
		@rOSTypeId tinyint=0
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	BEGIN TRANSACTION	
	
	INSERT INTO sAudit.tActivityLog
		(
			OrgGroupId,
			OrgId,
			UserId,
			SessionId,
			ScreenId,
			AuditDate,
			Activity,
			RecordSourceId,
			RecordDetail,
			OSTypeId
		)
	VALUES
		(
			@rOrgGroupId,
			@rOrgId,
			@rUserId,
			@rSessionId,
			@rScreenId,
			sCommon.fGetDate(),
			@rActivity,
			@rRecordSourceId,
			@rRecordDetail,
			@rOSTypeId
		)
		SELECT 1 AS Result
	
	COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Altering [sAudit].[pActivityLogGet]...';


GO


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

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


GO

ALTER PROCEDURE [sBiometric].[pRptMonthlyLateInSummaryGet]
	@rBuilder1 nvarchar(max)='',
	@rBuilder2 nvarchar(max)='',
	@rOrgId int ,
	@rOrganizationDepartmentId int ,
	@rFromDate Datetime,
	@rToDate Datetime,	 
	@rEmployeeStatusId int,
	@rEmployeeId bigint,
	@rOrgGroupId int,
	@rGradeId nvarchar(max)= '0',
	@rOrgGroupDepartmentId int =0,
	@rTimeSheetStatus nvarchar(50) ='0',
	@rOrderBy smallint = 0

WITH EXECUTE AS CALLER  
AS  
SET NOCOUNT ON  
BEGIN  
	CREATE TABLE #TempMonthTrans  
	 (  
	 Id int ,  
	 EmployeeId bigint,   
	 Attn_Date DateTime,  
	 PresentStatus nvarchar(15),  
	 LateBy nvarchar(20),   
	 EarlyBy nvarchar(20), 
	 FirstIn nvarchar(20),
	 ShiftName nvarchar(25) ,
	 Duration nvarchar(20),
	  LastOut nvarchar(20)
	 ) 
 
 ---select @rFromDate,@rToDate 
	  INSERT INTO #TempMonthTrans 
	  select Id,EmployeeId ,Attn_Date,PresentStatus ,LateBy, EarlyBy,FirstIn,ShiftName,Duration, LastOut
	  from [sBiometric].[fBiometricTempMonthTransGet](@rOrgId ,@rOrganizationDepartmentId ,@rFromDate,@rToDate,@rEmployeeId)
	  --select * from #TempMonthTrans 
	SELECT
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			MT.EmployeeId,
			MT.EmpCode,
			EM.FirstName + ' ' + EM.LastName AS EmployeeName,  
			OM.Id AS OrganizationId,
			OM.DisplayTitle AS OrganizationTitle,
			OM.OrderIndex AS OrganizationOrderIndex,
			EM.Number AS EmployeeNumber,
			IsNull(MT.TotalHour,'00:00') as TotalHour,
			Isnull(MT.Tot_Early,'00:00') as Tot_Early,
			Isnull(MT.Tot_OT,'00:00') as Tot_OT,
			Isnull(MT.Tot_Late,'00:00') as Tot_Late,
			Isnull(Mt.Count_Late, 0) as Count_Late,
			OM.Id AS OrgId,
			OM.Title AS OrganizationTitle,
			TM.Attn_Date as Attn_Date,
			TM.FirstIn as FirstIn,
			TM.LateBy AS LateBy,
			TM.PresentStatus as PresentStatus,
			TM.EarlyBy AS EarlyBy,
			TM.ShiftName AS ShiftName,
			DM.Displaytitle AS DeptName,
			DM.Id As DeptId,
			@rOrderBy AS OrderBy,
			TM.LastOut AS LastOut
		FROM #TempMonthTrans TM   
	 INNER JOIN sBiometric.tMonthTrans MT ON MT.EmployeeId=TM.EmployeeId AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0)  
		INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id = MT.EmployeeId AND (SourceTypeId = 95 OR SourceTypeId=0)
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = EM.OrgId
		LEFT JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id
		LEFT JOIN sSetup.tDepartmentMaster DM ON DM.Id = EJD.OrganizationDepartmentId
	
		WHERE
		(EM.OrgId = @rOrgId OR @rOrgId = 0)
		 and TM.ATTN_DATE >= @rFromDate AND TM.ATTN_DATE <=@rToDate   
		 and  MT.Attn_dt=cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime)
		AND (EJD.OrganizationDepartmentId = @rOrganizationDepartmentId OR @rOrganizationDepartmentId = 0)		 	
		AND (EM.StatusId = @rEmployeeStatusId OR ISNULL(@rEmployeeStatusId,0)=0)
		AND ISNULL(EM.IsOtherUser,0) = 0 
		AND (ISNULL(MT.SourceTypeId,95) = 95 OR MT.SourceTypeId = 0)
		AND (MT.EmployeeId = @rEmployeeId OR @rEmployeeId = 0)
		AND (OM.OrgGroupId = @rOrgGroupId)
		AND (EmployeeGradeId in ( SELECT cast(item as int) FROM  sCommon.fnsplit(@rGradeId,',')) OR @rGradeId=0) 
		AND ((EJD.OrgGroupDepartmentId = @rOrgGroupDepartmentId) OR (@rOrgGroupDepartmentId=0)) 
		AND  ((PresentStatus in ( SELECT cast(item as nvarchar) FROM  sCommon.fnsplit(@rTimeSheetStatus,','))) OR (@rTimeSheetStatus='0')) 


		DROP Table #TempMonthTrans	

		--select
		--	@rBuilder1 AS Builder1,
		--	@rBuilder2 AS Builder2,
		--	CAST(0 AS bigint) AS EmployeeId,
		--	'' as EmpCode,
		--	'' AS EmployeeName,  
		--	'' AS OrganizationId,
		--	'' AS OrganizationTitle,
		--	0 AS OrganizationOrderIndex,
		--	CAST(0 AS bigint) AS EmployeeNumber,
		--	'' as TotalHour,
		--	'' as Tot_Early,
		--	'' as Tot_OT,
		--	'' as Tot_Late,
		--	0 as Count_Late,
		--	0 AS OrgId,
		--	'' AS OrganizationTitle,
		--	CAST('1999-01-01 00:00:00' AS datetime) as Attn_Date,
		--	'' as FirstIn,
		--	'' AS LateBy,
		--	'' as PresentStatus,
		--	'' AS EarlyBy,
		--	'' AS ShiftName,
		--	'' AS DeptName,
		--	0 As DeptId,
		--	@rOrderBy AS OrderBy,
		-- '' as LastOut


End
GO
PRINT N'Altering [sCommon].[pMasterDataAdd]...';


GO
ALTER  PROCEDURE [sCommon].[pMasterDataAdd]
	 
        
		@rTitle nvarchar(100)='',
		@rCode nvarchar(50)='',
		@rIsObsolete bit=0,
		@rCreatedUserId bigint,
		@rOrgGroupId smallint,
		@rOrgId int,
		@rTable_Name int=0,
		@rDependId int=0,
		@rNo int=0
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY

	 DECLARE @lNextNumber BIGINT 
	 DECLARE @lReligionId INT 
			 
		IF(@rTable_Name=1)
		BEGIN
		
			If Exists(select Id from sFinanceCommon.tBankMaster where Title=@rTitle AND OrgGroupId=@rOrgGroupId)
				BEGIN
				select -103 as Result
				RETURN
	 		END 
	 		EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sFinanceCommon.tBankMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
			INSERT INTO sFinanceCommon.tBankMaster
			(
			
				Id,
				Code,
				Title,
				 IsObsolete,
				 OrgGroupId,
				CreatedUserId,
				UpdateduserId,
				CreatedDateTime,
				UpdatedDateTime 
			)
		VALUES
			(
				@lNextNumber,
				@rCode,
				@rTitle,
				 @rIsObsolete,
				 @rOrgGroupId,
				@rCreatedUserId,
				@rCreatedUserId,
				sCommon.fGetDate() ,
				sCommon.fGetDate() 
			)
			END
			
			IF(@rTable_Name=2)
		BEGIN
		
			If Exists(select Id from sCommon.tReligionMaster where Title=@rTitle AND OrgGroupId=@rOrgGroupId)
				BEGIN
				select -103 as Result
				RETURN
	 		END 
	 		EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sCommon.tReligionMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
			INSERT INTO sCommon.tReligionMaster
			(
			
				Id,
				Code,
				Title,
				 IsObsolete,
				 OrgGroupId,
				CreatedUserId,
				UpdateduserId,
				CreatedDateTime,
				UpdatedDateTime 
			)
		VALUES
			(
				@lNextNumber,
				@rCode,
				@rTitle,
				 @rIsObsolete,
				 @rOrgGroupId,
				@rCreatedUserId,
				@rCreatedUserId,
				sCommon.fGetDate() ,
				sCommon.fGetDate() 
			)
			END
			
			IF(@rTable_Name=3)
		BEGIN
		
			If Exists(select Id from sCommon.tOccupationMaster where Title=@rTitle AND OrgGroupId=@rOrgGroupId)
				BEGIN
				select -103 as Result
				RETURN
	 		END 
	 		EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sCommon.tOccupationMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
			INSERT INTO sCommon.tOccupationMaster
			(
			
				Id,
				Code,
				Title,
				 IsObsolete,
				 OrgGroupId,
				CreatedUserId,
				UpdateduserId,
				CreatedDateTime,
				UpdatedDateTime 
			)
		VALUES
			(
				@lNextNumber,
				@rCode,
				@rTitle,
				 @rIsObsolete,
				 @rOrgGroupId,
				@rCreatedUserId,
				@rCreatedUserId,
				sCommon.fGetDate() ,
				sCommon.fGetDate() 
			)
			END
			
			
			IF(@rTable_Name=4)
		BEGIN
		
			If Exists(select Id from sCommon.tMotherTongueMaster where Title=@rTitle AND OrgGroupId=@rOrgGroupId)
				BEGIN
				select -103 as Result
				RETURN
	 		END 
	 		EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sCommon.tMotherTongueMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
			INSERT INTO sCommon.tMotherTongueMaster
			(
			
				Id,
				Code,
				Title,
				 IsObsolete,
				 OrgGroupId,
				CreatedUserId,
				UpdateduserId,
				CreatedDateTime,
				UpdatedDateTime 
			)
		VALUES
			(
				@lNextNumber,
				@rCode,
				@rTitle,
				 @rIsObsolete,
				 @rOrgGroupId,
				@rCreatedUserId,
				@rCreatedUserId,
				sCommon.fGetDate() ,
				sCommon.fGetDate() 
			)
			END
			
		IF(@rTable_Name=5)
		BEGIN
		
			If Exists(select Id from sCommon.tPreviousSchoolMaster where Title=@rTitle AND OrgGroupId=@rOrgGroupId)
				BEGIN
				select -103 as Result
				RETURN
	 		END 
	 		EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sCommon.tPreviousSchoolMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
			INSERT INTO sCommon.tPreviousSchoolMaster
			(
			
				Id,
				Code,
				Title,
				 IsObsolete,
				 OrgGroupId,
				CreatedUserId,
				UpdateduserId,
				CreatedDateTime,
				UpdatedDateTime 
			)
		VALUES
			(
				@lNextNumber,
				@rCode,
				@rTitle,
				 @rIsObsolete,
				 @rOrgGroupId,
				@rCreatedUserId,
				@rCreatedUserId,
				sCommon.fGetDate() ,
				sCommon.fGetDate() 
			)
			END
			
			IF(@rTable_Name=6)
		BEGIN
		
			If Exists(select Id from sHrm.tQualificationMaster where Title=@rTitle AND OrgGroupId=@rOrgGroupId)
				BEGIN
				select -103 as Result
				RETURN
	 		END 
	 		EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sHrm.tQualificationMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
			INSERT INTO sHrm.tQualificationMaster
			(
			
				Id,
				Code,
				Title,
				 IsObsolete,
				 OrgGroupId,
				CreatedUserId,
				UpdateduserId,
				CreatedDateTime,
				UpdatedDateTime 
			)
		VALUES
			(
				@lNextNumber,
				@rCode,
				@rTitle,
				 @rIsObsolete,
				 @rOrgGroupId,
				@rCreatedUserId,
				@rCreatedUserId,
				sCommon.fGetDate() ,
				sCommon.fGetDate() 
			)
			END
			
				IF(@rTable_Name=7)
		BEGIN
		
			If Exists(select Id from sCommon.tCountryMaster where Title=@rTitle AND OrgGroupId=@rOrgGroupId)
				BEGIN
				select -103 as Result
				RETURN
	 		END 
	 		EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sCommon.tCountryMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
			INSERT INTO sCommon.tCountryMaster
			(
			
				Id,
				Title,
				Nationality,
			
				 IsObsolete,
				 OrgGroupId,
				CreatedUserId,
				UpdateduserId,
				CreatedDateTime,
				UpdatedDateTime ,
				IsShow
			)
		VALUES
			(
				@lNextNumber,
				
				@rTitle,
				@rCode,
				 @rIsObsolete,
				 @rOrgGroupId,
				@rCreatedUserId,
				@rCreatedUserId,
				sCommon.fGetDate() ,
				sCommon.fGetDate() ,
				1
			)
			END
			
				IF(@rTable_Name=8)
		BEGIN
			If Exists(select Id from sCommon.tStateMaster where Title=@rTitle AND CountryId=@rDependId AND OrgGroupId=@rOrgGroupId)
				BEGIN
				select -103 as Result
				RETURN
	 		END 
	 		EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sCommon.tStateMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
			INSERT INTO sCommon.tStateMaster
			(
			
				Id,
				Title,
				CountryId,
			
				 IsObsolete,
				 OrgGroupId,
				CreatedUserId,
				UpdateduserId,
				CreatedDateTime,
				UpdatedDateTime ,
				IsShow
			)
		VALUES
			(
				@lNextNumber,
				
				@rTitle,
				@rDependId,
				 @rIsObsolete,
				 @rOrgGroupId,
				@rCreatedUserId,
				@rCreatedUserId,
				sCommon.fGetDate() ,
				sCommon.fGetDate() ,
				1
			)
			END
			
			
				IF(@rTable_Name=9)
		BEGIN
				If Exists(select Id from sCommon.tCityMaster where Title=@rTitle AND StateId =@rDependId AND OrgGroupId=@rOrgGroupId)
				BEGIN
				select -103 as Result
				RETURN
	 		END 
	 		EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sCommon.tCityMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
			INSERT INTO sCommon.tCityMaster
			(
			
				Id,
				Title,
				StateId,
			
				 IsObsolete,
				 OrgGroupId,
				CreatedUserId,
				UpdateduserId,
				CreatedDateTime,
				UpdatedDateTime ,
				IsShow
			)
		VALUES
			(
				@lNextNumber,
				
				@rTitle,
				@rDependId,
				 @rIsObsolete,
				 @rOrgGroupId,
				@rCreatedUserId,
				@rCreatedUserId,
				sCommon.fGetDate() ,
				sCommon.fGetDate() ,
				1
			)
			END
			
				IF(@rTable_Name=10)
		BEGIN
				If Exists(select Id from sCommon.tHobbyMaster where Title=@rTitle AND OrgGroupId=@rOrgGroupId)
				BEGIN
				select -103 as Result
				RETURN
	 		END 
	 		EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sCommon.tHobbyMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
			INSERT INTO sCommon.tHobbyMaster
			(
			
				Id,
				Title,
				Code,
				 IsObsolete,
				 OrgGroupId,
				CreatedUserId,
				UpdateduserId,
				CreatedDateTime,
				UpdatedDateTime 
			 
			)
		VALUES
			(
				@lNextNumber,
				
				@rTitle,
				@rCode,
				 @rIsObsolete,
				 @rOrgGroupId,
				@rCreatedUserId,
				@rCreatedUserId,
				sCommon.fGetDate() ,
				sCommon.fGetDate() 
				 
			)
			END
			
		 IF(@rTable_Name=11)
		BEGIN
				If Exists(select Id from sCommon.tHostelMaster where Title=@rTitle AND OrgGroupId=@rOrgGroupId)
				BEGIN
				select -103 as Result
				RETURN
	 		END 
	 		EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sCommon.tHostelMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
			INSERT INTO sCommon.tHostelMaster
			(
			
				Id,
				Title,
				Code,
				 IsObsolete,
				 OrgGroupId,
				CreatedUserId,
				UpdateduserId,
				CreatedDateTime,
				UpdatedDateTime 
			 
			)
		VALUES
			(
				@lNextNumber,
				
				@rTitle,
				@rCode,
				 @rIsObsolete,
				 @rOrgGroupId,
				@rCreatedUserId,
				@rCreatedUserId,
				sCommon.fGetDate() ,
				sCommon.fGetDate() 
				 
			)
			END
		 
		 	
		 IF(@rTable_Name=12)
		BEGIN
				If Exists(select Id from sCommon.tAreaMaster where Title=@rTitle AND CityId =@rDependId AND OrgGroupId=@rOrgGroupId)
				BEGIN
				select -103 as Result
				RETURN
	 		END 
	 		EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sCommon.tAreaMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
			INSERT INTO sCommon.tAreaMaster
			(
			
				Id,
				Title,
				CityId,
				 IsObsolete,
				 OrgGroupId,
				CreatedUserId,
				UpdateduserId,
				CreatedDateTime,
				UpdatedDateTime,
				IsShow
			 
			)
		VALUES
			(
				@lNextNumber,
				
				@rTitle,
				@rDependId,
				 @rIsObsolete,
				 @rOrgGroupId,
				@rCreatedUserId,
				@rCreatedUserId,
				sCommon.fGetDate() ,
				sCommon.fGetDate() ,
				1
				
				 
			)
			END
		 
		  IF(@rTable_Name=13)
		BEGIN
				If Exists(select Id from sCommon.tFamiliyCastMaster where FamiliyCast=@rTitle AND CastCategoryId=@rDependId AND OrgGroupId=@rOrgGroupId)	--add CastCategoryId
				BEGIN
				select -103 as Result
				RETURN
	 		END 
	 		
	  
	 		EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sCommon.tFamiliyCastMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
			INSERT INTO sCommon.tFamiliyCastMaster
			(
			
				Id,
				FamiliyCast, 
				 FamiliySubCast, 
				 OrgGroupId,
				 IsObsolete,
				CreatedUserId,
				UpdateduserId,
				CreatedDateTime,
				UpdatedDateTime,
				CastCategoryId,		--added
				ReligionId			--added
			 
			 
			)
		VALUES
			(
				@lNextNumber,
				@rTitle, 
				@rCode,
				 @rOrgGroupId,
				 @rIsObsolete,
				@rCreatedUserId,
				@rCreatedUserId,
				sCommon.fGetDate() ,
				sCommon.fGetDate(),
				@rDependId,			--added
				-1					--added
				 
				
				 
			)
			END
			
			
			
			 IF(@rTable_Name=14)
		BEGIN
		If Exists(select Id from sSetup.tSubjectMaster where Code=@rCode AND OrgId=@rOrgId)			--add if condition
			BEGIN
			select -102 as Result
			RETURN
		END
				If Exists(select Id from sSetup.tSubjectMaster where Title=@rTitle   AND OrgId=@rOrgId)
				BEGIN
				select -103 as Result
				RETURN
				END
				If Exists(select Id from sSetup.tSubjectMaster where Number=@rNo and OrgId=@rOrgId)		--add if condition
			BEGIN
			select -104 as Result
			RETURN
	 		END 
	 		
	  
	 		EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sSetup.tSubjectMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
			INSERT INTO sSetup.tSubjectMaster
			(
			
				Id,
				Code, 
				 Number, 
				 Title,
				 IsObsolete,
				 OrgId,
				 OrderIndex,
				CreatedUserId,
				UpdateduserId,
				CreatedDateTime,
				UpdatedDateTime 
			 
			 
			)
		VALUES
			(
				@lNextNumber,
				@rCode,
				@rNo,
				@rTitle, 
				 @rIsObsolete,
				 @rOrgId,
				 @rNo,
				@rCreatedUserId,
				@rCreatedUserId,
				sCommon.fGetDate() ,
				sCommon.fGetDate()  
				 
				
				 
			)
			END
			
			
			SELECT 1 AS Result
			
			
		 
 
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Altering [sCommunication].[pAssignTaskSearchGet]...';


GO

ALTER PROCEDURE [sCommunication].[pAssignTaskSearchGet]

	 @rId bigint,
	 @rOrgId int,
	 @rFromStartDate DateTime,
	 @rToStartDate DateTime,
	 @rFromDueDate DateTime,
	 @rToDueDate DateTime,
	 @rSourceTypeId int,
	 @rIsComplete bit,
	 @rIsClosed bit,
	 @rCreatedUserId bigint,
	 @rCode nvarchar(max)

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
IF(@rSourceTypeId = 95)
	BEGIN
	
		SELECT 
				DISTINCT AT.Id,
				AT.AssignedToSourceTypeId,
				AT.AssignedToSourceId,
				EM.Code AS SourceCode,
				EM.EmployeeName AS SourceName,
				CONVERT(varchar,AT.AssignedDate ,105) AS AssignedDate,
				CONVERT(varchar,AT.DueDate ,105) AS DueDate,
				AT.Remark,
				AT.IsCompleted,
				AT.IsClosed,
				OM.DisplayTitle AS Organization,
				ISNULL(CASE WHEN U.SourceTypeId = 2003 THEN (SELECT Name FROM sStudent.vStudentName WHERE StudentId = U.SourceId)
				ELSE (SELECT ShortName FROM sHrm.vExtEmployeeMaster WHERE EmployeeId = U.SourceId) END,'') AS AssignedBy,
				ISNULL(AT.DueReasonRemark,'') AS DueReasonRemark
				--ISNULL((SELECT ShortName FROM sHrm.vExtEmployeeMaster WHERE EmployeeId = U.SourceId),'') AS AssignedBy
		FROM 
				sCommunication.tAssignTask AT
				INNER JOIN sHrm.vExtEmployeeMaster EM ON EM.Id=AT.AssignedToSourceId AND AT.AssignedToSourceTypeId=95
				INNER JOIN sSecurity.tUser U ON U.Id=AT.CreatedUserId
				INNER JOIN sSetup.tOrganizationMaster OM ON AT.OrgId=OM.Id
		WHERE 
				((AT.Id=@rId) OR (ISNULL(@rId,0) = 0))
			AND ((AT.AssignedDate >= @rFromStartDate) OR (ISNULL(@rFromStartDate,0) = 0))
			AND ((AT.AssignedDate <= @rToStartDate) OR (ISNULL(@rToStartDate,0) = 0)) 
			AND ((AT.DueDate >= @rFromDueDate) OR (ISNULL(@rFromDueDate,0) = 0))
			AND ((AT.DueDate <= @rToDueDate) OR (ISNULL(@rToDueDate,0) = 0))
			AND ((AT.CreatedUserId = @rCreatedUserId) OR (@rCreatedUserId=0))
			AND ((AT.IsCompleted= @rIsComplete))
			AND (AT.IsClosed= @rIsClosed)
			AND (AT.OrgId=@rOrgId OR @rOrgId = 0)
			AND AT.IsDeleted=0
			AND ((EM.Code =@rCode) OR ISNULL(@rCode,'')='')
	END			
ELSE
	BEGIN
	print 'Yes'
		SELECT 
				DISTINCT AT.Id,
				AT.AssignedToSourceTypeId,
				AT.AssignedToSourceId,
				SN.Code AS SourceCode,
				SN.Name AS SourceName,
				CONVERT(varchar,AT.AssignedDate,105) AS AssignedDate,
				CONVERT(varchar,AT.DueDate,105) AS DueDate,
				AT.Remark,
				AT.IsCompleted,
				AT.IsClosed,
				OM.DisplayTitle AS Organization,
				ISNULL(CASE WHEN U.SourceTypeId = 2003 THEN (SELECT [sStudent].[fStudentNameGet](SM.FirstName , SM.MiddleName, SM.LastName,OM.StudentNameFormatId ) FROM sStudent.tStudentMaster SM 
				 INNER JOIN sSetup.tOrganizationMaster OM ON SM.OrgId = OM.Id WHERE SM.Id = U.SourceId)
				 ELSE (SELECT ShortName FROM sHrm.vExtEmployeeMaster WHERE EmployeeId = U.SourceId) END,'') AS AssignedBy
		FROM 
				sCommunication.tAssignTask AT
				INNER JOIN sStudent.vStudentName SN ON SN.StudentId=AT.AssignedToSourceId AND AT.AssignedToSourceTypeId=2003
				INNER JOIN sSecurity.tUser U ON U.Id=AT.CreatedUserId
				INNER JOIN sSetup.tOrganizationMaster OM ON AT.OrgId=OM.Id
		WHERE 
				((AT.Id=@rId) OR (ISNULL(@rId,0) = 0))
				AND ((AT.AssignedDate >= @rFromStartDate) OR (ISNULL(@rFromStartDate,0) = 0))
				AND ((AT.AssignedDate <= @rToStartDate) OR (ISNULL(@rToStartDate,0) = 0)) 
				AND ((AT.DueDate >= @rFromDueDate) OR (ISNULL(@rFromDueDate,0) = 0))
				AND ((AT.DueDate <= @rToDueDate) OR (ISNULL(@rToDueDate,0) = 0))
				AND ((AT.CreatedUserId = @rCreatedUserId) OR (@rCreatedUserId=0))
				AND ((AT.IsCompleted= @rIsComplete))
				AND (AT.IsClosed= @rIsClosed)
				AND (AT.OrgId=@rOrgId OR @rOrgId = 0)
				AND AT.IsDeleted=0
				AND ((SN.Code =@rCode) OR ISNULL(@rCode,'')='') 
	END
END
GO
PRINT N'Altering [sCommunication].[pAssignTaskToMeGet]...';


GO
ALTER PROCEDURE [sCommunication].[pAssignTaskToMeGet]
	 
	 @rOrgId int,
	 @rUserSourceId bigint,
	 @rUserSourceTypeId smallint,
	 @rSyncedDateTime datetime
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	
BEGIN 

IF(@rUserSourceTypeId=95)
BEGIN

	SELECT 
		AT.Id,
		AT.AssignedDate,
		AT.DueDate,
		AT.Remark,
		AT.IsCompleted,
		AT.IsClosed,
		AT.IsDeleted,
		(CASE 
		WHEN U.SourceTypeId=95 
		THEN (SELECT Id FROM sHrm.tEmployeeMaster WHERE Id=U.SourceId AND ISNULL(IsOtherUser,0) = 0 )
		WHEN U.SourceTypeId=2003
		THEN (SELECT Id FROM sStudent.tStudentMaster WHERE Id=U.SourceId)
		END)AS AssignedBySourceId,
		(CASE 
		WHEN U.SourceTypeId=95 
		THEN 95
		WHEN U.SourceTypeId=2003
		THEN 2003
		END)AS AssignedBySourceTypeId,
		(CASE 
		WHEN U.SourceTypeId=95 
		THEN (SELECT FirstName +' '+LastName FROM sHrm.tEmployeeMaster WHERE Id=U.SourceId AND ISNULL(IsOtherUser,0) = 0)
		WHEN U.SourceTypeId=2003
		THEN (SELECT FirstName +' '+LastName FROM sStudent.tStudentMaster WHERE Id=U.SourceId)
		END)AS AssignedByName,
		(CASE 
		WHEN U.SourceTypeId=95 
		THEN (SELECT Code FROM sHrm.tEmployeeMaster WHERE Id=U.SourceId AND ISNULL(IsOtherUser,0) = 0)
		WHEN U.SourceTypeId=2003
		THEN (SELECT Code FROM sStudent.tStudentMaster WHERE Id=U.SourceId)
		END)AS AssignedByCode,
		AT.DueReasonRemark  
						
	FROM 
		sCommunication.tAssignTask AT
		INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id=AT.AssignedToSourceId AND AT.AssignedToSourceTypeId=95
		INNER JOIN sSecurity.tUser U ON AT.CreatedUserId=U.Id
		
	WHERE 
		AT.AssignedToSourceId=@rUserSourceId
		AND (AT.OrgId=@rOrgId OR @rOrgId=0)
		AND (AT.UpdatedDateTime > @rSyncedDateTime OR @rSyncedDateTime IS NULL)
		AND ISNULL(EM.IsOtherUser,0) = 0 
	ORDER BY AT.DueDate
END
ELSE
BEGIN
	
	SELECT 
		AT.Id,
		AT.AssignedDate,
		AT.DueDate,
		AT.Remark,
		AT.IsCompleted,
		AT.IsClosed,
		AT.IsDeleted,
		(CASE 
		WHEN U.SourceTypeId=95 
		THEN (SELECT Id FROM sHrm.tEmployeeMaster WHERE Id=U.SourceId AND ISNULL(IsOtherUser,0) = 0)
		WHEN U.SourceTypeId=2003
		THEN (SELECT Id FROM sStudent.tStudentMaster WHERE Id=U.SourceId)
		END)AS AssignedBySourceId,
		(CASE 
		WHEN U.SourceTypeId=95 
		THEN 95
		WHEN U.SourceTypeId=2003
		THEN 2003
		END)AS AssignedBySourceTypeId,
		(CASE 
		WHEN U.SourceTypeId=95 
		THEN (SELECT FirstName +' '+LastName FROM sHrm.tEmployeeMaster WHERE Id=U.SourceId AND ISNULL(IsOtherUser,0) = 0)
		WHEN U.SourceTypeId=2003
		THEN (SELECT FirstName +' '+LastName FROM sStudent.tStudentMaster WHERE Id=U.SourceId)
		END)AS AssignedByName,
		(CASE 
		WHEN U.SourceTypeId=95 
		THEN (SELECT Code FROM sHrm.tEmployeeMaster WHERE Id=U.SourceId AND ISNULL(IsOtherUser,0) = 0)
		WHEN U.SourceTypeId=2003
		THEN (SELECT Code FROM sStudent.tStudentMaster WHERE Id=U.SourceId)
		END)AS AssignedByCode,
		'' as DueReasonRemark --DueReasonRemark need only in Employee Side
					
	FROM 
		sCommunication.tAssignTask AT
		INNER JOIN sStudent.tStudentMaster SM ON SM.Id=AT.AssignedToSourceId AND AT.AssignedToSourceTypeId=2003
		INNER JOIN sSecurity.tUser U ON AT.CreatedUserId=U.Id
		
	WHERE 
		AT.AssignedToSourceId=@rUserSourceId
		AND (AT.OrgId=@rOrgId OR @rOrgId=0)
		AND (AT.UpdatedDateTime > @rSyncedDateTime OR @rSyncedDateTime IS NULL)
	ORDER BY AT.DueDate
END

END
GO
PRINT N'Altering [sCommunication].[pQueryAdd]...';


GO
 
ALTER PROCEDURE [sCommunication].[pQueryAdd]
	 
	@rOrgGroupId smallint,
	@rOrgGroupBatchId int,
	@rQueryCategoryId int,
	@rId AS bigint,
	@rTitle nvarchar(100),
	@rRemark nvarchar(1000),
	@rIsUserView bit,
	@rIsAssigneeView bit,
	@rStatusId smallint,
	@rCreatedUserId bigint,
	@rCreatedDateTime datetime,
	@rSubjectId int=0,
	@rAssignedToEmployeeId bigint=0,
	@rAssignedToRemark nvarchar(500)='',
	@rIsOfflineEntry bit=0,
	@rFromSourceTypeId smallInt=0,
	@rFromSourceId bigint=0,
	@rTargetResolutionDate datetime=null    
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
	BEGIN TRANSACTION
		IF(@rId = 0)
BEGIN
DECLARE @lNextNumber BIGINT     
	
	EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sCommunication.tQuery', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	DECLARE @lNumber int=0
	SELECT @lNumber=ISNULL(MAX(Number),0)+1 FROM sCommunication.tQuery WHERE OrgGroupBatchId = @rOrgGroupBatchId
	
	
	INSERT INTO sCommunication.tQuery
		(
			OrgGroupId,
			OrgGroupBatchId,
			QueryCategoryId,
			Id,
			Title,
			Number,
			Remark,
			IsUserView,
			IsAssigneeView,
			StatusId,
			CreatedUserId,
			CreatedDateTime,
			SubjectId,
			AssignedToEmployeeId,
			AssignedToRemark,
			IsOfflineEntry,
			FromSourceTypeId,
			FromSourceId,
			TargetResolutionDate
		)
	VALUES
		(
			@rOrgGroupId,
			@rOrgGroupBatchId,
			@rQueryCategoryId,
			@lNextNumber,
			@rTitle,
			@lNumber,
			@rRemark,
			@rIsUserView,
			@rIsAssigneeView,
			@rStatusId,
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rSubjectId,
			@rAssignedToEmployeeId,
			@rAssignedToRemark,
			@rIsOfflineEntry,
			@rFromSourceTypeId,
			@rFromSourceId,
			@rTargetResolutionDate
		)
		select @lNextNumber,1 as result
		--select @lNextNumber,@lNextNumber as result
END
ELSE
BEGIN
		UPDATE sCommunication.tQuery 
		SET IsUserView = @rIsUserView,
		IsAssigneeView=@rIsAssigneeView,
		AssignedToEmployeeId=@rAssignedToEmployeeId,
		AssignedToRemark=@rAssignedToRemark,
		IsOfflineEntry=@rIsOfflineEntry,
		FromSourceTypeId=@rFromSourceTypeId,
		FromSourceId=@rFromSourceId,
		TargetResolutionDate=@rTargetResolutionDate,
		Remark=@rRemark
		
		 WHERE Id = @rId
		select 0,11 as result
END
	
	COMMIT TRANSACTION
	
END TRY

	BEGIN CATCH
	    ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH  
END
GO
PRINT N'Altering [sCommunication].[pQueryCategoryDropdownGet]...';


GO
ALTER PROCEDURE [sCommunication].[pQueryCategoryDropdownGet]
	@rOrgGroupBatchId int,
	@rUserSourceId bigint,
	@rUserSourceTypeId int
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
	DECLARE @lAcademicId bigint,@lStudentId bigint,@lClassId int,@lDivisionId int,@lOrgId int,@lDepartmentId int,@lEmployeeId bigint

	IF @rUserSourceTypeId = 95 -- For Employee Login
	BEGIN
		SELECT 
			@lDepartmentId=EJD.OrganizationDepartmentId,
			@lOrgId = EM.OrgId,
			@lEmployeeId = EM.Id 
		FROM 
			sHrm.tEmployeeMaster EM INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id 
		WHERE 
			EM.Id=@rUserSourceId
		
		SELECT Distinct	
			QCM.Id,
			QCM.Title
		FROM 
			sCommunication.tQueryCategoryMaster QCM           
			INNER JOIN 
			(SELECT QCS.QueryCategoryId FROM sCommunication.tQueryCategoryScope QCS
				WHERE (((QCS.SourceTypeId = 2021 AND QCS.SourceId =@lOrgId) OR
				(QCS.SourceTypeId = 2017 AND QCS.SourceId =@lDepartmentId) OR
				(QCS.SourceTypeId = 95 AND QCS.SourceId =@lEmployeeId )) 
				AND ((QCS.AssigneeToId=3) OR (QCS.AssigneeToId IS NULL) OR (ISNULL(QCS.AssigneeToId,0)=0)))) D
				ON D.QueryCategoryId= QCM.Id
			--INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=QCM.OrgGroupBatchId AND OGBM.Id=@rOrgGroupBatchId
			--INNER JOIN sSecurity.tUser U ON U.Id=QCM.CreatedUserId
		WHERE 
			QCM.AssignedToId IN (1,3) 
			AND QCM.IsObsolete = 0

		--UNION

		--SELECT Distinct	
		--	QCM.Id,
		--	QCM.Title
		--FROM 
		--	sCommunication.tQueryCategoryMaster QCM           
		--	INNER JOIN sCommunication.tQueryCategoryAssignedTo QCA ON QCM.Id = QCA.QueryCategoryId
		--	AND QCA.SourceTypeId = 95 AND QCA.SourceId =@lEmployeeId
	
		--WHERE 
		--	QCM.AssignedToId IN (1,3) 
		--	AND QCM.IsObsolete = 0

	END
	ELSE IF @rUserSourceTypeId = 2003 -- For Student Login
	BEGIN
		SELECT 
			@lAcademicId = A.Id,
			@lStudentId = A.StudentId,
			@lClassId = A.ClassId, 
			@lDivisionId = A.DivisionId, 
			@lOrgId= A.OrgId, 
			@lDepartmentId=CM.DepartmentId
		FROM sStudent.tAcademic A 
			INNER JOIN sSetup.tBatchMaster BM ON A.BatchId = BM.Id 
			INNER JOIN sSetup.tClassMaster CM ON CM.Id = A.ClassId
		WHERE StudentId = @rUserSourceId AND BM.OrgGroupBatchId = @rOrgGroupBatchId
  
		SELECT 	Distinct
			QCM.Id,
			QCM.Title
		FROM 
			sCommunication.tQueryCategoryMaster QCM
			INNER JOIN (SELECT QCS.QueryCategoryId 
				FROM sCommunication.tQueryCategoryScope QCS
				WHERE (((QCS.SourceTypeId = 2021 AND QCS.SourceId =@lOrgId) OR
				(QCS.SourceTypeId = 2017 AND QCS.SourceId =@lDepartmentId) OR
				(QCS.SourceTypeId = 2016 AND QCS.SourceId =@lClassId) OR
				(QCS.SourceTypeId = 2005 AND QCS.SourceId =@lDivisionId) OR
				(QCS.SourceTypeId = 2003 AND QCS.SourceId =@lStudentId) OR
				(QCS.SourceTypeId = 2001 AND QCS.SourceId =@lAcademicId) )
				)AND ((QCS.AssigneeToId=2) OR (QCS.AssigneeToId IS NULL) OR (ISNULL(QCS.AssigneeToId,0)=0))) D ON D.QueryCategoryId= QCM.Id 
		WHERE
			QCM.AssignedToId IN (1,2) 
			AND QCM.IsObsolete = 0
	END
	ELSE
	--For Other Users
	BEGIN
		SELECT 	
			QCM.Id,
			QCM.Title
		FROM 
			sCommunication.tQueryCategoryMaster QCM
		WHERE 
			QCM.AssignedToId IN (1,2,3)
			AND QCM.IsObsolete = 0
	END
END
GO
PRINT N'Altering [sCommunication].[pTempCircularScopeValidate]...';


GO
ALTER PROCEDURE [sCommunication].[pTempCircularScopeValidate]
	 
        @rTempCircularId nvarchar(100),
		@rSourceTypeId smallint,
		@rSourceId bigint,
		@rAssigneeToId int
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
					/* Source Type Value
					   2021 - Organization
					   2017 - Department
					   2016 - Class
					   2005 - Division
					   2003 - Student */


		If EXISTS(select 1 from sCommunication.tTempCircularScope CS where CS.SourceId=@rSourceId AND
					CS.SourceTypeId=@rSourceTypeId AND CS.TempCircularId=@rTempCircularId AND AssigneeToId=@rAssigneeToId) 
			BEGIN
				select -101 as Result,'Item Already Exists' AS Msg
				RETURN
			END 

	
	IF(@rSourceTypeId = 2021) -- Organization	
		BEGIN
			If EXISTS(select 1 from  sCommunication.tTempCircularScope CS
			 INNER JOIN  sSetup.tDepartmentMaster DM 
				ON CS.SourceId=DM.Id AND CS.SourceTypeId= 2017
				where DM.OrgId=@rSourceId  AND CS.TempCircularId=@rTempCircularId AND AssigneeToId=@rAssigneeToId)
					BEGIN
						select -103 as Result,'Department already Exists' AS Msg
						RETURN
					END 
			If EXISTS(select 1 from  sCommunication.tTempCircularScope CS 
			 INNER JOIN  sSetup.tClassMaster CM 
				ON CS.SourceId=CM.Id AND CS.SourceTypeId= 2016
				where CM.OrgId=@rSourceId  AND CS.TempCircularId=@rTempCircularId AND AssigneeToId=@rAssigneeToId)
					BEGIN
						select -103 as Result,'Class already Exists' AS Msg
						RETURN
					END 
					
			If EXISTS(select 1 from  sCommunication.tTempCircularScope CS 
			 INNER JOIN  sSetup.tDivisionMaster DM 
				ON CS.SourceId=DM.Id AND CS.SourceTypeId= 2005
				where DM.OrgId=@rSourceId  AND CS.TempCircularId=@rTempCircularId AND AssigneeToId=@rAssigneeToId)
					BEGIN
						select -103 as Result,'Division already Exists' AS Msg
						RETURN
					END 
					
			If EXISTS(select 1 from  sCommunication.tTempCircularScope CS 
			 INNER JOIN  sStudent.tStudentMaster SM
				ON CS.SourceId=SM.Id AND CS.SourceTypeId= 2003
				where SM.OrgId=@rSourceId  AND CS.TempCircularId=@rTempCircularId AND AssigneeToId=@rAssigneeToId)
					BEGIN
						select -103 as Result,'Student already Exists' AS Msg
						RETURN
					END 		

			If EXISTS(select 1 from  sCommunication.tTempCircularScope CS 
			 INNER JOIN  sHrm.tEmployeeMaster EM
				ON CS.SourceId=EM.Id AND CS.SourceTypeId= 95
				where EM.OrgId=@rSourceId  AND CS.TempCircularId=@rTempCircularId AND AssigneeToId=@rAssigneeToId)
					BEGIN
						select -103 as Result,'Employee already Exists' AS Msg
						RETURN
					END 	
	    END
	
	IF(@rSourceTypeId = 2017) -- Department	
		BEGIN
			If EXISTS(select 1 from  sCommunication.tTempCircularScope CS
			 INNER JOIN  sSetup.tDepartmentMaster DM
				ON CS.SourceId=DM.OrgId AND CS.SourceTypeId= 2021
				where DM.Id=@rSourceId  AND CS.TempCircularId=@rTempCircularId AND AssigneeToId=@rAssigneeToId)
					BEGIN
						select -102 as Result,'Organization already Exists' AS Msg
						RETURN
					END 
			If EXISTS(select 1 from  sCommunication.tTempCircularScope CS
			 INNER JOIN sSetup.tClassMaster CM
				ON CS.SourceId=CM.Id AND CS.SourceTypeId= 2016
				where CM.DepartmentId=@rSourceId  AND CS.TempCircularId=@rTempCircularId  AND AssigneeToId=@rAssigneeToId)
					BEGIN
						select -103 as Result,'Class already Exists' AS Msg
						RETURN
					END 
					
			If EXISTS(select 1 from  sCommunication.tTempCircularScope CS 
			 INNER JOIN  sSetup.tDivisionMaster DM 
				ON CS.SourceId=DM.Id AND CS.SourceTypeId= 2005
			 INNER JOIN sSetup.tClassMaster CM
				ON CM.Id=DM.ClassId
				where CM.DepartmentId=@rSourceId  AND CS.TempCircularId=@rTempCircularId  AND AssigneeToId=@rAssigneeToId)
					BEGIN
						select -103 as Result,'Division already Exists' AS Msg
						RETURN
					END 
					
			If EXISTS(select 1 from  sCommunication.tTempCircularScope CS 
			 INNER JOIN sStudent.tAcademic SA 
				ON CS.SourceId=SA.StudentId AND CS.SourceTypeId=2003
			 INNER JOIN sSetup.tClassMaster CM
				ON CM.Id=SA.ClassId
   			 INNER JOIN sSetup.tBatchMaster BM 
   			    ON BM.Id = SA.BatchId AND BM.IsActive=1
				where CM.DepartmentId=@rSourceId  AND CS.TempCircularId=@rTempCircularId  AND AssigneeToId=@rAssigneeToId)
					BEGIN
						select -103 as Result,'Student already Exists' AS Msg
						RETURN
					END 	
			
			If EXISTS(select 1 from sCommunication.tTempCircularScope CS 
			 INNER JOIN sHrm.tEmployeeMaster  EM ON EM.Id =CS.SourceID AND CS.SourceTypeId= 95
			 INNER JOIN  sHrm.tEmployeeJobDetail EJD ON EM.Id=EJD.EmployeeId 			
			 where  EJD.OrganizationDepartmentId=@rSourceId  AND CS.TempCircularId=@rTempCircularId AND AssigneeToId=@rAssigneeToId)
				BEGIN
					select -103 as Result,'Employee already Exists' AS Msg
					RETURN
				END 
		
	    END
	    
    IF(@rSourceTypeId = 2016) -- Class	
	BEGIN
		If EXISTS(select 1 from  sCommunication.tTempCircularScope CS 
		 INNER JOIN  sSetup.tClassMaster CM
			ON CS.SourceId=CM.OrgId AND CS.SourceTypeId= 2021
			where CM.Id=@rSourceId  AND CS.TempCircularId=@rTempCircularId  AND AssigneeToId=@rAssigneeToId)
				BEGIN
					select -102 as Result,'Organization already Exists' AS Msg
					RETURN
				END 
		If EXISTS(select 1 from  sCommunication.tTempCircularScope CS 
		 INNER JOIN  sSetup.tClassMaster CM
			ON CS.SourceId=CM.DepartmentId AND CS.SourceTypeId= 2017
			where CM.Id=@rSourceId  AND CS.TempCircularId=@rTempCircularId  AND AssigneeToId=@rAssigneeToId)
				BEGIN
					select -102 as Result,'Department already Exists' AS Msg
					RETURN
				END 
				
		If EXISTS(select 1 from  sCommunication.tTempCircularScope CS
		 INNER JOIN  sSetup.tDivisionMaster DM 
			ON CS.SourceId=DM.Id AND CS.SourceTypeId= 2005
			where DM.ClassId=@rSourceId  AND CS.TempCircularId=@rTempCircularId  AND AssigneeToId=@rAssigneeToId)
				BEGIN
					select -103 as Result,'Division already Exists' AS Msg
					RETURN
				END 
				
		If EXISTS(select 1 from sCommunication.tTempCircularScope CS 
		  INNER JOIN sStudent.tAcademic SA 
				ON CS.SourceId=SA.StudentId AND CS.SourceTypeId=2003
		  INNER JOIN sSetup.tBatchMaster BM 
   			    ON BM.Id = SA.BatchId AND BM.IsActive=1
			where SA.ClassId=@rSourceId  AND CS.TempCircularId=@rTempCircularId  AND AssigneeToId=@rAssigneeToId)
				BEGIN
					select -103 as Result,'Student already Exists' AS Msg
					RETURN
				END 			
    END
    
    IF(@rSourceTypeId = 2005) -- Division	
	BEGIN
		If EXISTS(select 1 from  sCommunication.tTempCircularScope CS
		 INNER JOIN  sSetup.tDivisionMaster DM 
			ON CS.SourceId=DM.OrgId AND CS.SourceTypeId= 2021
			where DM.Id=@rSourceId  AND CS.TempCircularId=@rTempCircularId  AND AssigneeToId=@rAssigneeToId)
				BEGIN
					select -102 as Result,'Organization already Exists' AS Msg
					RETURN
				END 
		If EXISTS(select 1 from  sCommunication.tTempCircularScope CS
		 INNER JOIN sSetup.tClassMaster CM 
			ON CS.SourceId=CM.DepartmentId AND CS.SourceTypeId= 2017
		 INNER JOIN  sSetup.tDivisionMaster DM 
			ON DM.ClassId=CM.Id
			where DM.Id=@rSourceId  AND CS.TempCircularId=@rTempCircularId  AND AssigneeToId=@rAssigneeToId)
				BEGIN
					select -102 as Result,'Department already Exists' AS Msg
					RETURN
				END 
				
		If EXISTS(select 1 from  sCommunication.tTempCircularScope CS 
		 INNER JOIN  sSetup.tDivisionMaster DM 
			ON CS.SourceId=DM.ClassId AND CS.SourceTypeId= 2016
			where DM.Id=@rSourceId  AND CS.TempCircularId=@rTempCircularId  AND AssigneeToId=@rAssigneeToId)
				BEGIN
					select -102 as Result,'Class already Exists' AS Msg
					RETURN
				END 
				
		If EXISTS(select 1 from sCommunication.tTempCircularScope CS 
		  INNER JOIN sStudent.tAcademic SA 
				ON CS.SourceId=SA.StudentId AND CS.SourceTypeId=2003
		  INNER JOIN sSetup.tBatchMaster BM 
   			    ON BM.Id = SA.BatchId AND BM.IsActive=1
			where SA.DivisionId=@rSourceId  AND CS.TempCircularId=@rTempCircularId  AND AssigneeToId=@rAssigneeToId)
				BEGIN
					select -103 as Result,'Student already Exists' AS Msg
					RETURN
				END 
				
			If EXISTS(select 1 from sCommunication.tTempCircularScope CS 
		  INNER JOIN sStudent.tAcademic SA 
				ON CS.SourceId=SA.DivisionId AND CS.SourceTypeId=2005
		  INNER JOIN sSetup.tBatchMaster BM 
   			    ON BM.Id = SA.BatchId AND BM.IsActive=1
			where SA.DivisionId=@rSourceId  AND CS.TempCircularId=@rTempCircularId  AND AssigneeToId=@rAssigneeToId)
				BEGIN
					select -103 as Result,'Student already Exists' AS Msg
					RETURN
				END 
								
    END
    
    IF(@rSourceTypeId = 2003) -- Student	
	BEGIN
		If EXISTS(select 1 from  sCommunication.tTempCircularScope CS 
		 INNER JOIN  sStudent.tStudentMaster SM 
			ON CS.SourceId=SM.OrgId AND CS.SourceTypeId= 2021
			where SM.Id=@rSourceId  AND CS.TempCircularId=@rTempCircularId  AND AssigneeToId=@rAssigneeToId)
				BEGIN
					select -102 as Result,'Organization already Exists' AS Msg
					RETURN
				END 
		If EXISTS(select 1 from sCommunication.tTempCircularScope CS 
		 INNER JOIN  sSetup.tClassMaster CM 
			ON CS.SourceId=CM.DepartmentId AND CS.SourceTypeId= 2017
		 INNER JOIN sStudent.tAcademic SA 
				ON CM.Id=SA.ClassId 
		 INNER JOIN sSetup.tBatchMaster BM 
   			    ON BM.Id = SA.BatchId AND BM.IsActive=1
			where SA.StudentId=@rSourceId  AND CS.TempCircularId=@rTempCircularId  AND AssigneeToId=@rAssigneeToId)
				BEGIN
					select -102 as Result,'Department already Exists' AS Msg
					RETURN
				END 
				
		If EXISTS(select 1 from  sCommunication.tTempCircularScope CS 
		 INNER JOIN sStudent.tAcademic SA 
				ON CS.SourceId=SA.ClassId AND CS.SourceTypeId= 2016
		 INNER JOIN sSetup.tBatchMaster BM 
   			    ON BM.Id = SA.BatchId AND BM.IsActive=1
			where SA.StudentId=@rSourceId  AND CS.TempCircularId=@rTempCircularId  AND AssigneeToId=@rAssigneeToId)
				BEGIN
					select -102 as Result,'Class already Exists' AS Msg
					RETURN
				END 
				
		If EXISTS(select 1 from  sCommunication.tTempCircularScope CS
		 INNER JOIN sStudent.tAcademic SA 
				ON CS.SourceId=SA.DivisionId AND CS.SourceTypeId= 2005
		 INNER JOIN sSetup.tBatchMaster BM 
   			    ON BM.Id = SA.BatchId AND BM.IsActive=1
			where SA.StudentId=@rSourceId  AND CS.TempCircularId=@rTempCircularId  AND AssigneeToId=@rAssigneeToId)
				BEGIN
					select -102 as Result,'Division already Exists' AS Msg
					RETURN
				END 			
    END
    
    IF(@rSourceTypeId = 95) -- Employee	
	BEGIN
	
	
		If EXISTS(select 1 from  sCommunication.tTempCircularScope CS 
		 INNER JOIN  sHrm.tEmployeeMaster EM 
			ON CS.SourceId=EM.OrgId AND CS.SourceTypeId= 2021
			where EM.Id=@rSourceId AND  ISNULL(EM.IsOtherUser,0) = 0  AND CS.TempCircularId=@rTempCircularId  AND AssigneeToId=@rAssigneeToId)
				BEGIN
					select -102 as Result,'Organization already Exists' AS Msg
					RETURN
				END 
				
		If EXISTS(select 1 from sCommunication.tTempCircularScope CS 
		 INNER JOIN  sHrm.tEmployeeJobDetail EJD
			ON CS.SourceId=EJD.OrganizationDepartmentId AND CS.SourceTypeId= 2017
			where  EJD.EmployeeId=@rSourceId  AND CS.TempCircularId=@rTempCircularId  AND AssigneeToId=@rAssigneeToId)
				BEGIN
					select -102 as Result,'Department already Exists' AS Msg
					RETURN
				END 
						
		
		 
	 
    END
    IF(@rSourceTypeId = 2001) -- Academic	
	BEGIN
		If EXISTS(select 1 from  sCommunication.tTempCircularScope CS
		 INNER JOIN sStudent.tAcademic SA 
				ON CS.SourceId=SA.DivisionId AND CS.SourceTypeId= 2005
		 INNER JOIN sSetup.tBatchMaster BM 
   			    ON BM.Id = SA.BatchId AND BM.IsActive=1
			where SA.Id=@rSourceId  AND CS.TempCircularId=@rTempCircularId  AND AssigneeToId=@rAssigneeToId)
				BEGIN
					select -102 as Result,'Division already Exists' AS Msg
					RETURN
				END 		
	END
			select 1 as Result,'' AS Msg
	
END
GO
PRINT N'Altering [sCommunication].[pTempMultiPhotoCategoryScopeValidate]...';


GO
ALTER PROCEDURE [sCommunication].[pTempMultiPhotoCategoryScopeValidate]
	 
        @rTempPhotoCategoryId nvarchar(100),
		@rSourceTypeId smallint,
		@rSourceId bigint,
		@rAssigneeToId int,
		@rPhotoCategoryId int=0
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
					/* Source Type Value
					   2021 - Organization
					   2017 - Department
					   2016 - Class
					   2005 - Division
					   2003 - Student */


		If EXISTS(select 1 from [sCommunication].[tTempMultiPhotoCategoryScope] CS where CS.SourceId=@rSourceId AND
					CS.SourceTypeId=@rSourceTypeId AND CS.TempMultiPhotoCategoryId=@rTempPhotoCategoryId AND AssigneeToId=@rAssigneeToId) 
			BEGIN
				select -101 as Result,'Item Already Exists' AS Msg
				RETURN
			END 
		IF(@rPhotoCategoryId > 0)
		BEGIN
			If EXISTS(select 1 from sCommunication.tMultiPhotoCategoryScope CS where CS.ScopeSourceId=@rSourceId AND
				CS.ScopeSourceTypeId=@rSourceTypeId AND CS.MultiPhotoCategoryId=@rPhotoCategoryId AND AssigneeToId=@rAssigneeToId) 
			BEGIN
				select -101 as Result,'Item Already Exists' AS Msg
				RETURN
			END 
		END
	
	IF(@rSourceTypeId = 2021) -- Organization	
		BEGIN
			If EXISTS(select 1 from  [sCommunication].[tTempMultiPhotoCategoryScope] CS
			 INNER JOIN  sSetup.tDepartmentMaster DM 
				ON CS.SourceId=DM.Id AND CS.SourceTypeId= 2017
				where DM.OrgId=@rSourceId  AND CS.TempMultiPhotoCategoryId=@rTempPhotoCategoryId AND AssigneeToId=@rAssigneeToId)
					BEGIN
						select -103 as Result,'Department already Exists' AS Msg
						RETURN
					END 
			If EXISTS(select 1 from  [sCommunication].[tTempMultiPhotoCategoryScope] CS 
			 INNER JOIN  sSetup.tClassMaster CM 
				ON CS.SourceId=CM.Id AND CS.SourceTypeId= 2016
				where CM.OrgId=@rSourceId  AND CS.TempMultiPhotoCategoryId=@rTempPhotoCategoryId AND AssigneeToId=@rAssigneeToId)
					BEGIN
						select -103 as Result,'Class already Exists' AS Msg
						RETURN
					END 
					
			If EXISTS(select 1 from  [sCommunication].[tTempMultiPhotoCategoryScope] CS 
			 INNER JOIN  sSetup.tDivisionMaster DM 
				ON CS.SourceId=DM.Id AND CS.SourceTypeId= 2005
				where DM.OrgId=@rSourceId  AND CS.TempMultiPhotoCategoryId=@rTempPhotoCategoryId AND AssigneeToId=@rAssigneeToId)
					BEGIN
						select -103 as Result,'Division already Exists' AS Msg
						RETURN
					END 
					
			If EXISTS(select 1 from  [sCommunication].[tTempMultiPhotoCategoryScope] CS 
			 INNER JOIN  sStudent.tStudentMaster SM
				ON CS.SourceId=SM.Id AND CS.SourceTypeId= 2003
				where SM.OrgId=@rSourceId  AND CS.TempMultiPhotoCategoryId=@rTempPhotoCategoryId AND AssigneeToId=@rAssigneeToId)
					BEGIN
						select -103 as Result,'Student already Exists' AS Msg
						RETURN
					END 
					
			If EXISTS(select 1 from  sCommunication.tTempMultiPhotoCategoryScope CS 
			 INNER JOIN  sHrm.tEmployeeMaster EM
				ON CS.SourceId=EM.Id AND CS.SourceTypeId= 95
				where EM.OrgId=@rSourceId  AND CS.TempMultiPhotoCategoryId=@rTempPhotoCategoryId AND AssigneeToId=@rAssigneeToId)
					BEGIN
						select -103 as Result,'Employee already Exists' AS Msg
						RETURN
					END 		
	    END
	
	IF(@rSourceTypeId = 2017) -- Department	
		BEGIN
			If EXISTS(select 1 from  [sCommunication].[tTempMultiPhotoCategoryScope] CS
			 INNER JOIN  sSetup.tDepartmentMaster DM
				ON CS.SourceId=DM.OrgId AND CS.SourceTypeId= 2021
				where DM.Id=@rSourceId  AND CS.TempMultiPhotoCategoryId=@rTempPhotoCategoryId AND AssigneeToId=@rAssigneeToId)
					BEGIN
						select -102 as Result,'Organization already Exists' AS Msg
						RETURN
					END 
			If EXISTS(select 1 from  [sCommunication].[tTempMultiPhotoCategoryScope] CS
			 INNER JOIN sSetup.tClassMaster CM
				ON CS.SourceId=CM.Id AND CS.SourceTypeId= 2016
				where CM.DepartmentId=@rSourceId  AND CS.TempMultiPhotoCategoryId=@rTempPhotoCategoryId  AND AssigneeToId=@rAssigneeToId)
					BEGIN
						select -103 as Result,'Class already Exists' AS Msg
						RETURN
					END 
					
			If EXISTS(select 1 from  [sCommunication].[tTempMultiPhotoCategoryScope] CS 
			 INNER JOIN  sSetup.tDivisionMaster DM 
				ON CS.SourceId=DM.Id AND CS.SourceTypeId= 2005
			 INNER JOIN sSetup.tClassMaster CM
				ON CM.Id=DM.ClassId
				where CM.DepartmentId=@rSourceId  AND CS.TempMultiPhotoCategoryId=@rTempPhotoCategoryId  AND AssigneeToId=@rAssigneeToId)
					BEGIN
						select -103 as Result,'Division already Exists' AS Msg
						RETURN
					END 
					
			If EXISTS(select 1 from  [sCommunication].[tTempMultiPhotoCategoryScope] CS 
			 INNER JOIN sStudent.tAcademic SA 
				ON CS.SourceId=SA.StudentId AND CS.SourceTypeId=2003
			 INNER JOIN sSetup.tClassMaster CM
				ON CM.Id=SA.ClassId
   			 INNER JOIN sSetup.tBatchMaster BM 
   			    ON BM.Id = SA.BatchId AND BM.IsActive=1
				where CM.DepartmentId=@rSourceId  AND CS.TempMultiPhotoCategoryId=@rTempPhotoCategoryId  AND AssigneeToId=@rAssigneeToId)
					BEGIN
						select -103 as Result,'Student already Exists' AS Msg
						RETURN
					END
					
			If EXISTS(select 1 from sCommunication.tTempMultiPhotoCategoryScope CS 
			 INNER JOIN sHrm.tEmployeeMaster  EM ON EM.Id =CS.SourceID AND CS.SourceTypeId= 95
			 INNER JOIN  sHrm.tEmployeeJobDetail EJD ON EM.Id=EJD.EmployeeId 			
			 where  EJD.OrganizationDepartmentId=@rSourceId  AND CS.TempMultiPhotoCategoryId=@rTempPhotoCategoryId AND AssigneeToId=@rAssigneeToId)
				BEGIN
					select -103 as Result,'Employee already Exists' AS Msg
					RETURN
				END 			
	    END
	    
    IF(@rSourceTypeId = 2016) -- Class	
	BEGIN
		If EXISTS(select 1 from  [sCommunication].[tTempMultiPhotoCategoryScope] CS 
		 INNER JOIN  sSetup.tClassMaster CM
			ON CS.SourceId=CM.OrgId AND CS.SourceTypeId= 2021
			where CM.Id=@rSourceId  AND CS.TempMultiPhotoCategoryId=@rTempPhotoCategoryId  AND AssigneeToId=@rAssigneeToId)
				BEGIN
					select -102 as Result,'Organization already Exists' AS Msg
					RETURN
				END 
		If EXISTS(select 1 from  [sCommunication].[tTempMultiPhotoCategoryScope] CS 
		 INNER JOIN  sSetup.tClassMaster CM
			ON CS.SourceId=CM.DepartmentId AND CS.SourceTypeId= 2017
			where CM.Id=@rSourceId  AND CS.TempMultiPhotoCategoryId=@rTempPhotoCategoryId  AND AssigneeToId=@rAssigneeToId)
				BEGIN
					select -102 as Result,'Department already Exists' AS Msg
					RETURN
				END 
				
		If EXISTS(select 1 from  [sCommunication].[tTempMultiPhotoCategoryScope] CS
		 INNER JOIN  sSetup.tDivisionMaster DM 
			ON CS.SourceId=DM.Id AND CS.SourceTypeId= 2005
			where DM.ClassId=@rSourceId  AND CS.TempMultiPhotoCategoryId=@rTempPhotoCategoryId  AND AssigneeToId=@rAssigneeToId)
				BEGIN
					select -103 as Result,'Division already Exists' AS Msg
					RETURN
				END 
				
		If EXISTS(select 1 from [sCommunication].[tTempMultiPhotoCategoryScope] CS 
		  INNER JOIN sStudent.tAcademic SA 
				ON CS.SourceId=SA.StudentId AND CS.SourceTypeId=2003
		  INNER JOIN sSetup.tBatchMaster BM 
   			    ON BM.Id = SA.BatchId AND BM.IsActive=1
			where SA.ClassId=@rSourceId  AND CS.TempMultiPhotoCategoryId=@rTempPhotoCategoryId  AND AssigneeToId=@rAssigneeToId)
				BEGIN
					select -103 as Result,'Student already Exists' AS Msg
					RETURN
				END 			
    END
    
    IF(@rSourceTypeId = 2005) -- Division	
	BEGIN
		If EXISTS(select 1 from  [sCommunication].[tTempMultiPhotoCategoryScope] CS
		 INNER JOIN  sSetup.tDivisionMaster DM 
			ON CS.SourceId=DM.OrgId AND CS.SourceTypeId= 2021
			where DM.Id=@rSourceId  AND CS.TempMultiPhotoCategoryId=@rTempPhotoCategoryId  AND AssigneeToId=@rAssigneeToId)
				BEGIN
					select -102 as Result,'Organization already Exists' AS Msg
					RETURN
				END 
		If EXISTS(select 1 from  [sCommunication].[tTempMultiPhotoCategoryScope] CS
		 INNER JOIN sSetup.tClassMaster CM 
			ON CS.SourceId=CM.DepartmentId AND CS.SourceTypeId= 2017
		 INNER JOIN  sSetup.tDivisionMaster DM 
			ON DM.ClassId=CM.Id
			where DM.Id=@rSourceId  AND CS.TempMultiPhotoCategoryId=@rTempPhotoCategoryId  AND AssigneeToId=@rAssigneeToId)
				BEGIN
					select -102 as Result,'Department already Exists' AS Msg
					RETURN
				END 
				
		If EXISTS(select 1 from  [sCommunication].[tTempMultiPhotoCategoryScope] CS 
		 INNER JOIN  sSetup.tDivisionMaster DM 
			ON CS.SourceId=DM.ClassId AND CS.SourceTypeId= 2016
			where DM.Id=@rSourceId  AND CS.TempMultiPhotoCategoryId=@rTempPhotoCategoryId  AND AssigneeToId=@rAssigneeToId)
				BEGIN
					select -102 as Result,'Class already Exists' AS Msg
					RETURN
				END 
				
		If EXISTS(select 1 from [sCommunication].[tTempMultiPhotoCategoryScope] CS 
		  INNER JOIN sStudent.tAcademic SA 
				ON CS.SourceId=SA.StudentId AND CS.SourceTypeId=2003
		  INNER JOIN sSetup.tBatchMaster BM 
   			    ON BM.Id = SA.BatchId AND BM.IsActive=1
			where SA.DivisionId=@rSourceId  AND CS.TempMultiPhotoCategoryId=@rTempPhotoCategoryId  AND AssigneeToId=@rAssigneeToId)
				BEGIN
					select -103 as Result,'Student already Exists' AS Msg
					RETURN
				END 
				
			If EXISTS(select 1 from [sCommunication].[tTempMultiPhotoCategoryScope] CS 
		  INNER JOIN sStudent.tAcademic SA 
				ON CS.SourceId=SA.DivisionId AND CS.SourceTypeId=2005
		  INNER JOIN sSetup.tBatchMaster BM 
   			    ON BM.Id = SA.BatchId AND BM.IsActive=1
			where SA.DivisionId=@rSourceId  AND CS.TempMultiPhotoCategoryId=@rTempPhotoCategoryId  AND AssigneeToId=@rAssigneeToId)
				BEGIN
					select -103 as Result,'Student already Exists' AS Msg
					RETURN
				END 
								
    END
    
    IF(@rSourceTypeId = 2003) -- Student	
	BEGIN
		If EXISTS(select 1 from  [sCommunication].[tTempMultiPhotoCategoryScope] CS 
		 INNER JOIN  sStudent.tStudentMaster SM 
			ON CS.SourceId=SM.OrgId AND CS.SourceTypeId= 2021
			where SM.Id=@rSourceId  AND CS.TempMultiPhotoCategoryId=@rTempPhotoCategoryId  AND AssigneeToId=@rAssigneeToId)
				BEGIN
					select -102 as Result,'Organization already Exists' AS Msg
					RETURN
				END 
		If EXISTS(select 1 from [sCommunication].[tTempMultiPhotoCategoryScope] CS 
		 INNER JOIN  sSetup.tClassMaster CM 
			ON CS.SourceId=CM.DepartmentId AND CS.SourceTypeId= 2017
		 INNER JOIN sStudent.tAcademic SA 
				ON CM.Id=SA.ClassId 
		 INNER JOIN sSetup.tBatchMaster BM 
   			    ON BM.Id = SA.BatchId AND BM.IsActive=1
			where SA.StudentId=@rSourceId  AND CS.TempMultiPhotoCategoryId=@rTempPhotoCategoryId  AND AssigneeToId=@rAssigneeToId)
				BEGIN
					select -102 as Result,'Department already Exists' AS Msg
					RETURN
				END 
				
		If EXISTS(select 1 from  [sCommunication].[tTempMultiPhotoCategoryScope] CS 
		 INNER JOIN sStudent.tAcademic SA 
				ON CS.SourceId=SA.ClassId AND CS.SourceTypeId= 2016
		 INNER JOIN sSetup.tBatchMaster BM 
   			    ON BM.Id = SA.BatchId AND BM.IsActive=1
			where SA.StudentId=@rSourceId  AND CS.TempMultiPhotoCategoryId=@rTempPhotoCategoryId  AND AssigneeToId=@rAssigneeToId)
				BEGIN
					select -102 as Result,'Class already Exists' AS Msg
					RETURN
				END 
				
		If EXISTS(select 1 from  [sCommunication].[tTempMultiPhotoCategoryScope] CS
		 INNER JOIN sStudent.tAcademic SA 
				ON CS.SourceId=SA.DivisionId AND CS.SourceTypeId= 2005
		 INNER JOIN sSetup.tBatchMaster BM 
   			    ON BM.Id = SA.BatchId AND BM.IsActive=1
			where SA.StudentId=@rSourceId  AND CS.TempMultiPhotoCategoryId=@rTempPhotoCategoryId  AND AssigneeToId=@rAssigneeToId)
				BEGIN
					select -102 as Result,'Division already Exists' AS Msg
					RETURN
				END 			
    END
    
    IF(@rSourceTypeId = 95) -- Employee	
	BEGIN
	
	
		If EXISTS(select 1 from  [sCommunication].[tTempMultiPhotoCategoryScope] CS 
		 INNER JOIN  sHrm.tEmployeeMaster EM 
			ON CS.SourceId=EM.OrgId AND CS.SourceTypeId= 2021
			where EM.Id=@rSourceId AND  ISNULL(EM.IsOtherUser,0) = 0  AND CS.TempMultiPhotoCategoryId=@rTempPhotoCategoryId  AND AssigneeToId=@rAssigneeToId)
				BEGIN
					select -102 as Result,'Organization already Exists' AS Msg
					RETURN
				END 
				
		If EXISTS(select 1 from [sCommunication].[tTempMultiPhotoCategoryScope] CS 
		 INNER JOIN  sHrm.tEmployeeJobDetail EJD
			ON CS.SourceId=EJD.OrganizationDepartmentId AND CS.SourceTypeId= 2017
			where  EJD.EmployeeId=@rSourceId  AND CS.TempMultiPhotoCategoryId=@rTempPhotoCategoryId  AND AssigneeToId=@rAssigneeToId)
				BEGIN
					select -102 as Result,'Department already Exists' AS Msg
					RETURN
				END 
						
		
		 
	 
    END
    IF(@rSourceTypeId = 2001) -- Academic	
	BEGIN
		If EXISTS(select 1 from  [sCommunication].[tTempMultiPhotoCategoryScope] CS
		 INNER JOIN sStudent.tAcademic SA 
				ON CS.SourceId=SA.DivisionId AND CS.SourceTypeId= 2005
		 INNER JOIN sSetup.tBatchMaster BM 
   			    ON BM.Id = SA.BatchId AND BM.IsActive=1
			where SA.Id=@rSourceId  AND CS.TempMultiPhotoCategoryId=@rTempPhotoCategoryId  AND AssigneeToId=@rAssigneeToId)
				BEGIN
					select -102 as Result,'Division already Exists' AS Msg
					RETURN
				END 		
	END
			select 1 as Result,'' AS Msg
	
END
GO
PRINT N'Altering [sCommunication].[pTempQueryCategoryScopeValidate]...';


GO
ALTER PROCEDURE [sCommunication].[pTempQueryCategoryScopeValidate]
	 
        @rTempQueryCategoryId nvarchar(100),
		@rSourceTypeId smallint,
		@rSourceId bigint,
		@rAssigneeToId int,
		@rQueryCategoryId int=0
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
					/* Source Type Value
					   2021 - Organization
					   2017 - Department
					   2016 - Class
					   2005 - Division
					   2003 - Student */


		If EXISTS(select 1 from sCommunication.tTempQueryCategoryScope CS where CS.SourceId=@rSourceId AND
					CS.SourceTypeId=@rSourceTypeId AND CS.TempQueryCategoryId=@rTempQueryCategoryId AND AssigneeToId=@rAssigneeToId) 
			BEGIN
				select -101 as Result,'Item Already Exists' AS Msg
				RETURN
			END 
		IF(@rQueryCategoryId > 0)
		BEGIN
			If EXISTS(select 1 from sCommunication.tQueryCategoryScope CS where CS.SourceId=@rSourceId AND
				CS.SourceTypeId=@rSourceTypeId AND CS.QueryCategoryId=@rQueryCategoryId AND AssigneeToId=@rAssigneeToId) 
			BEGIN
				select -101 as Result,'Item Already Exists' AS Msg
				RETURN
			END 
		END

			
	IF(@rSourceTypeId = 2021) -- Organization	
		BEGIN
			If EXISTS(select 1 from  sCommunication.tTempQueryCategoryScope CS
			 INNER JOIN  sSetup.tDepartmentMaster DM 
				ON CS.SourceId=DM.Id AND CS.SourceTypeId= 2017
				where DM.OrgId=@rSourceId  AND CS.TempQueryCategoryId=@rTempQueryCategoryId AND AssigneeToId=@rAssigneeToId)
					BEGIN
						select -103 as Result,'Department already Exists' AS Msg
						RETURN
					END 
			If EXISTS(select 1 from  sCommunication.tTempQueryCategoryScope CS 
			 INNER JOIN  sSetup.tClassMaster CM 
				ON CS.SourceId=CM.Id AND CS.SourceTypeId= 2016
				where CM.OrgId=@rSourceId  AND CS.TempQueryCategoryId=@rTempQueryCategoryId AND AssigneeToId=@rAssigneeToId)
					BEGIN
						select -103 as Result,'Class already Exists' AS Msg
						RETURN
					END 
					
			If EXISTS(select 1 from  sCommunication.tTempQueryCategoryScope CS 
			 INNER JOIN  sSetup.tDivisionMaster DM 
				ON CS.SourceId=DM.Id AND CS.SourceTypeId= 2005
				where DM.OrgId=@rSourceId  AND CS.TempQueryCategoryId=@rTempQueryCategoryId AND AssigneeToId=@rAssigneeToId)
					BEGIN
						select -103 as Result,'Division already Exists' AS Msg
						RETURN
					END 
					
			If EXISTS(select 1 from  sCommunication.tTempQueryCategoryScope CS 
			 INNER JOIN  sStudent.tStudentMaster SM
				ON CS.SourceId=SM.Id AND CS.SourceTypeId= 2003
				where SM.OrgId=@rSourceId  AND CS.TempQueryCategoryId=@rTempQueryCategoryId AND AssigneeToId=@rAssigneeToId)
					BEGIN
						select -103 as Result,'Student already Exists' AS Msg
						RETURN
					END 
			
			If EXISTS(select 1 from  sCommunication.tTempQueryCategoryScope CS 
			 INNER JOIN  sHrm.tEmployeeMaster EM
				ON CS.SourceId=EM.Id AND CS.SourceTypeId= 95
				where EM.OrgId=@rSourceId  AND CS.TempQueryCategoryId=@rTempQueryCategoryId AND AssigneeToId=@rAssigneeToId)
					BEGIN
						select -103 as Result,'Employee already Exists' AS Msg
						RETURN
					END 
				
		IF(@rQueryCategoryId > 0)	
		BEGIN
			If EXISTS(select 1 from  sCommunication.tQueryCategoryScope CS
			 INNER JOIN  sSetup.tDepartmentMaster DM 
				ON CS.SourceId=DM.Id AND CS.SourceTypeId= 2017
				where DM.OrgId=@rSourceId  AND CS.QueryCategoryId=@rQueryCategoryId AND AssigneeToId=@rAssigneeToId)
					BEGIN
						select -103 as Result,'Department already Exists' AS Msg
						RETURN
					END 
			If EXISTS(select 1 from  sCommunication.tQueryCategoryScope CS 
			 INNER JOIN  sSetup.tClassMaster CM 
				ON CS.SourceId=CM.Id AND CS.SourceTypeId= 2016
				where CM.OrgId=@rSourceId  AND CS.QueryCategoryId=@rQueryCategoryId AND AssigneeToId=@rAssigneeToId)
					BEGIN
						select -103 as Result,'Class already Exists' AS Msg
						RETURN
					END 
					
			If EXISTS(select 1 from  sCommunication.tQueryCategoryScope CS 
			 INNER JOIN  sSetup.tDivisionMaster DM 
				ON CS.SourceId=DM.Id AND CS.SourceTypeId= 2005
				where DM.OrgId=@rSourceId  AND CS.QueryCategoryId=@rQueryCategoryId AND AssigneeToId=@rAssigneeToId)
					BEGIN
						select -103 as Result,'Division already Exists' AS Msg
						RETURN
					END 
					
			If EXISTS(select 1 from  sCommunication.tQueryCategoryScope CS 
			 INNER JOIN  sStudent.tStudentMaster SM
				ON CS.SourceId=SM.Id AND CS.SourceTypeId= 2003
				where SM.OrgId=@rSourceId  AND CS.QueryCategoryId=@rQueryCategoryId AND AssigneeToId=@rAssigneeToId)
					BEGIN
						select -103 as Result,'Student already Exists' AS Msg
						RETURN
					END 

			If EXISTS(select 1 from  sCommunication.tQueryCategoryScope CS 
					INNER JOIN  sHrm.tEmployeeMaster EM
				ON CS.SourceId=EM.Id AND CS.SourceTypeId= 95
				where EM.OrgId=@rSourceId  AND CS.QueryCategoryId=@rQueryCategoryId AND AssigneeToId=@rAssigneeToId)
					BEGIN
						select -103 as Result,'Employee already Exists' AS Msg
						RETURN
					END 
		END

							
	    END
	
	IF(@rSourceTypeId = 2017) -- Department	
		BEGIN
			If EXISTS(select 1 from  sCommunication.tTempQueryCategoryScope CS
			 INNER JOIN  sSetup.tDepartmentMaster DM
				ON CS.SourceId=DM.OrgId AND CS.SourceTypeId= 2021
				where DM.Id=@rSourceId  AND CS.TempQueryCategoryId=@rTempQueryCategoryId AND AssigneeToId=@rAssigneeToId)
					BEGIN
						select -102 as Result,'Organization already Exists' AS Msg
						RETURN
					END 
			
			If EXISTS(select 1 from  sCommunication.tTempQueryCategoryScope CS
			 INNER JOIN sSetup.tClassMaster CM
				ON CS.SourceId=CM.Id AND CS.SourceTypeId= 2016
				where CM.DepartmentId=@rSourceId  AND CS.TempQueryCategoryId=@rTempQueryCategoryId  AND AssigneeToId=@rAssigneeToId)
					BEGIN
						select -103 as Result,'Class already Exists' AS Msg
						RETURN
					END 
					
			If EXISTS(select 1 from  sCommunication.tTempQueryCategoryScope CS 
			 INNER JOIN  sSetup.tDivisionMaster DM 
				ON CS.SourceId=DM.Id AND CS.SourceTypeId= 2005
			 INNER JOIN sSetup.tClassMaster CM
				ON CM.Id=DM.ClassId
				where CM.DepartmentId=@rSourceId  AND CS.TempQueryCategoryId=@rTempQueryCategoryId  AND AssigneeToId=@rAssigneeToId)
					BEGIN
						select -103 as Result,'Division already Exists' AS Msg
						RETURN
					END 
					
			If EXISTS(select 1 from  sCommunication.tTempQueryCategoryScope CS 
			 INNER JOIN sStudent.tAcademic SA 
				ON CS.SourceId=SA.StudentId AND CS.SourceTypeId=2003
			 INNER JOIN sSetup.tClassMaster CM
				ON CM.Id=SA.ClassId
   			 INNER JOIN sSetup.tBatchMaster BM 
   			    ON BM.Id = SA.BatchId AND BM.IsActive=1
				where CM.DepartmentId=@rSourceId  AND CS.TempQueryCategoryId=@rTempQueryCategoryId  AND AssigneeToId=@rAssigneeToId)
					BEGIN
						select -103 as Result,'Student already Exists' AS Msg
						RETURN
					END 
					
			If EXISTS(select 1 from sCommunication.tTempQueryCategoryScope CS 
			 INNER JOIN sHrm.tEmployeeMaster  EM ON EM.Id =CS.SourceID AND CS.SourceTypeId= 95
			 INNER JOIN  sHrm.tEmployeeJobDetail EJD ON EM.Id=EJD.EmployeeId 			
			 where  EJD.OrganizationDepartmentId=@rSourceId  AND CS.TempQueryCategoryId=@rTempQueryCategoryId AND AssigneeToId=@rAssigneeToId)
				BEGIN
					select -103 as Result,'Employee already Exists' AS Msg
					RETURN
				END
						
			IF(@rQueryCategoryId > 0)
			BEGIN
				If EXISTS(select 1 from  sCommunication.tQueryCategoryScope CS
				 INNER JOIN  sSetup.tDepartmentMaster DM
					ON CS.SourceId=DM.OrgId AND CS.SourceTypeId= 2021
					where DM.Id=@rSourceId  AND CS.QueryCategoryId=@rQueryCategoryId AND AssigneeToId=@rAssigneeToId)
						BEGIN
							select -102 as Result,'Organization already Exists' AS Msg
							RETURN
						END 
				If EXISTS(select 1 from  sCommunication.tQueryCategoryScope CS
				 INNER JOIN sSetup.tClassMaster CM
					ON CS.SourceId=CM.Id AND CS.SourceTypeId= 2016
					where CM.DepartmentId=@rSourceId  AND CS.QueryCategoryId=@rQueryCategoryId  AND AssigneeToId=@rAssigneeToId)
						BEGIN
							select -103 as Result,'Class already Exists' AS Msg
							RETURN
						END 
					
				If EXISTS(select 1 from  sCommunication.tQueryCategoryScope CS 
				 INNER JOIN  sSetup.tDivisionMaster DM 
					ON CS.SourceId=DM.Id AND CS.SourceTypeId= 2005
				 INNER JOIN sSetup.tClassMaster CM
					ON CM.Id=DM.ClassId
					where CM.DepartmentId=@rSourceId  AND CS.QueryCategoryId=@rQueryCategoryId  AND AssigneeToId=@rAssigneeToId)
						BEGIN
							select -103 as Result,'Division already Exists' AS Msg
							RETURN
						END 
					
				If EXISTS(select 1 from  sCommunication.tQueryCategoryScope CS 
				 INNER JOIN sStudent.tAcademic SA 
					ON CS.SourceId=SA.StudentId AND CS.SourceTypeId=2003
				 INNER JOIN sSetup.tClassMaster CM
					ON CM.Id=SA.ClassId
   				 INNER JOIN sSetup.tBatchMaster BM 
   					ON BM.Id = SA.BatchId AND BM.IsActive=1
					where CM.DepartmentId=@rSourceId  AND CS.QueryCategoryId=@rQueryCategoryId  AND AssigneeToId=@rAssigneeToId)
						BEGIN
							select -103 as Result,'Student already Exists' AS Msg
							RETURN
						END 
			
			If EXISTS(select 1 from sCommunication.tQueryCategoryScope CS 
				INNER JOIN sHrm.tEmployeeMaster  EM ON EM.Id =CS.SourceID AND CS.SourceTypeId= 95
				INNER JOIN  sHrm.tEmployeeJobDetail EJD ON EM.Id=EJD.EmployeeId 			
				where  EJD.OrganizationDepartmentId=@rSourceId  AND CS.QueryCategoryId=@rQueryCategoryId AND AssigneeToId=@rAssigneeToId)
				BEGIN
					select -103 as Result,'Employee already Exists' AS Msg
					RETURN
				END	
			END		
	    END
	    
    IF(@rSourceTypeId = 2016) -- Class	
	BEGIN
		If EXISTS(select 1 from  sCommunication.tTempQueryCategoryScope CS 
		 INNER JOIN  sSetup.tClassMaster CM
			ON CS.SourceId=CM.OrgId AND CS.SourceTypeId= 2021
			where CM.Id=@rSourceId  AND CS.TempQueryCategoryId=@rTempQueryCategoryId  AND AssigneeToId=@rAssigneeToId)
				BEGIN
					select -102 as Result,'Organization already Exists' AS Msg
					RETURN
				END 
		If EXISTS(select 1 from  sCommunication.tTempQueryCategoryScope CS 
		 INNER JOIN  sSetup.tClassMaster CM
			ON CS.SourceId=CM.DepartmentId AND CS.SourceTypeId= 2017
			where CM.Id=@rSourceId  AND CS.TempQueryCategoryId=@rTempQueryCategoryId  AND AssigneeToId=@rAssigneeToId)
				BEGIN
					select -102 as Result,'Department already Exists' AS Msg
					RETURN
				END 
				
		If EXISTS(select 1 from  sCommunication.tTempQueryCategoryScope CS
		 INNER JOIN  sSetup.tDivisionMaster DM 
			ON CS.SourceId=DM.Id AND CS.SourceTypeId= 2005
			where DM.ClassId=@rSourceId  AND CS.TempQueryCategoryId=@rTempQueryCategoryId  AND AssigneeToId=@rAssigneeToId)
				BEGIN
					select -103 as Result,'Division already Exists' AS Msg
					RETURN
				END 
				
		If EXISTS(select 1 from sCommunication.tTempQueryCategoryScope CS 
		  INNER JOIN sStudent.tAcademic SA 
				ON CS.SourceId=SA.StudentId AND CS.SourceTypeId=2003
		  INNER JOIN sSetup.tBatchMaster BM 
   			    ON BM.Id = SA.BatchId AND BM.IsActive=1
			where SA.ClassId=@rSourceId  AND CS.TempQueryCategoryId=@rTempQueryCategoryId  AND AssigneeToId=@rAssigneeToId)
				BEGIN
					select -103 as Result,'Student already Exists' AS Msg
					RETURN
				END 		
				
		IF(@rQueryCategoryId > 0)
		BEGIN	
			If EXISTS(select 1 from  sCommunication.tQueryCategoryScope CS 
			 INNER JOIN  sSetup.tClassMaster CM
				ON CS.SourceId=CM.OrgId AND CS.SourceTypeId= 2021
				where CM.Id=@rSourceId  AND CS.QueryCategoryId=@rQueryCategoryId  AND AssigneeToId=@rAssigneeToId)
					BEGIN
						select -102 as Result,'Organization already Exists' AS Msg
						RETURN
					END 
			If EXISTS(select 1 from  sCommunication.tQueryCategoryScope CS 
			 INNER JOIN  sSetup.tClassMaster CM
				ON CS.SourceId=CM.DepartmentId AND CS.SourceTypeId= 2017
				where CM.Id=@rSourceId  AND CS.QueryCategoryId=@rQueryCategoryId  AND AssigneeToId=@rAssigneeToId)
					BEGIN
						select -102 as Result,'Department already Exists' AS Msg
						RETURN
					END 
				
			If EXISTS(select 1 from  sCommunication.tQueryCategoryScope CS
			 INNER JOIN  sSetup.tDivisionMaster DM 
				ON CS.SourceId=DM.Id AND CS.SourceTypeId= 2005
				where DM.ClassId=@rSourceId  AND CS.QueryCategoryId=@rQueryCategoryId  AND AssigneeToId=@rAssigneeToId)
					BEGIN
						select -103 as Result,'Division already Exists' AS Msg
						RETURN
					END 
				
			If EXISTS(select 1 from sCommunication.tQueryCategoryScope CS 
			  INNER JOIN sStudent.tAcademic SA 
					ON CS.SourceId=SA.StudentId AND CS.SourceTypeId=2003
			  INNER JOIN sSetup.tBatchMaster BM 
   					ON BM.Id = SA.BatchId AND BM.IsActive=1
				where SA.ClassId=@rSourceId  AND CS.QueryCategoryId=@rQueryCategoryId  AND AssigneeToId=@rAssigneeToId)
					BEGIN
						select -103 as Result,'Student already Exists' AS Msg
						RETURN
					END 
		END
    END
    
    IF(@rSourceTypeId = 2005) -- Division	
	BEGIN
		If EXISTS(select 1 from  sCommunication.tTempQueryCategoryScope CS
		 INNER JOIN  sSetup.tDivisionMaster DM 
			ON CS.SourceId=DM.OrgId AND CS.SourceTypeId= 2021
			where DM.Id=@rSourceId  AND CS.TempQueryCategoryId=@rTempQueryCategoryId  AND AssigneeToId=@rAssigneeToId)
				BEGIN
					select -102 as Result,'Organization already Exists' AS Msg
					RETURN
				END 
		If EXISTS(select 1 from  sCommunication.tTempQueryCategoryScope CS
		 INNER JOIN sSetup.tClassMaster CM 
			ON CS.SourceId=CM.DepartmentId AND CS.SourceTypeId= 2017
		 INNER JOIN  sSetup.tDivisionMaster DM 
			ON DM.ClassId=CM.Id
			where DM.Id=@rSourceId  AND CS.TempQueryCategoryId=@rTempQueryCategoryId  AND AssigneeToId=@rAssigneeToId)
				BEGIN
					select -102 as Result,'Department already Exists' AS Msg
					RETURN
				END 
				
		If EXISTS(select 1 from  sCommunication.tTempQueryCategoryScope CS 
		 INNER JOIN  sSetup.tDivisionMaster DM 
			ON CS.SourceId=DM.ClassId AND CS.SourceTypeId= 2016
			where DM.Id=@rSourceId  AND CS.TempQueryCategoryId=@rTempQueryCategoryId  AND AssigneeToId=@rAssigneeToId)
				BEGIN
					select -102 as Result,'Class already Exists' AS Msg
					RETURN
				END 
				
		If EXISTS(select 1 from sCommunication.tTempQueryCategoryScope CS 
		  INNER JOIN sStudent.tAcademic SA 
				ON CS.SourceId=SA.StudentId AND CS.SourceTypeId=2003
		  INNER JOIN sSetup.tBatchMaster BM 
   			    ON BM.Id = SA.BatchId AND BM.IsActive=1
			where SA.DivisionId=@rSourceId  AND CS.TempQueryCategoryId=@rTempQueryCategoryId  AND AssigneeToId=@rAssigneeToId)
				BEGIN
					select -103 as Result,'Student already Exists' AS Msg
					RETURN
				END 
				
		If EXISTS(select 1 from sCommunication.tTempQueryCategoryScope CS 
		  INNER JOIN sStudent.tAcademic SA 
				ON CS.SourceId=SA.DivisionId AND CS.SourceTypeId=2005
		  INNER JOIN sSetup.tBatchMaster BM 
   			    ON BM.Id = SA.BatchId AND BM.IsActive=1
			where SA.DivisionId=@rSourceId  AND CS.TempQueryCategoryId=@rTempQueryCategoryId  AND AssigneeToId=@rAssigneeToId)
				BEGIN
					select -103 as Result,'Student already Exists' AS Msg
					RETURN
				END 

		IF(@rQueryCategoryId > 0)
		BEGIN
		If EXISTS(select 1 from  sCommunication.tQueryCategoryScope CS
		 INNER JOIN  sSetup.tDivisionMaster DM 
			ON CS.SourceId=DM.OrgId AND CS.SourceTypeId= 2021
			where DM.Id=@rSourceId  AND CS.QueryCategoryId=@rQueryCategoryId  AND AssigneeToId=@rAssigneeToId)
				BEGIN
					select -102 as Result,'Organization already Exists' AS Msg
					RETURN
				END 
		If EXISTS(select 1 from  sCommunication.tQueryCategoryScope CS
		 INNER JOIN sSetup.tClassMaster CM 
			ON CS.SourceId=CM.DepartmentId AND CS.SourceTypeId= 2017
		 INNER JOIN  sSetup.tDivisionMaster DM 
			ON DM.ClassId=CM.Id
			where DM.Id=@rSourceId  AND CS.QueryCategoryId=@rQueryCategoryId  AND AssigneeToId=@rAssigneeToId)
				BEGIN
					select -102 as Result,'Department already Exists' AS Msg
					RETURN
				END 
				
		If EXISTS(select 1 from  sCommunication.tQueryCategoryScope CS 
		 INNER JOIN  sSetup.tDivisionMaster DM 
			ON CS.SourceId=DM.ClassId AND CS.SourceTypeId= 2016
			where DM.Id=@rSourceId  AND CS.QueryCategoryId=@rQueryCategoryId  AND AssigneeToId=@rAssigneeToId)
				BEGIN
					select -102 as Result,'Class already Exists' AS Msg
					RETURN
				END 
				
		If EXISTS(select 1 from sCommunication.tQueryCategoryScope CS 
		  INNER JOIN sStudent.tAcademic SA 
				ON CS.SourceId=SA.StudentId AND CS.SourceTypeId=2003
		  INNER JOIN sSetup.tBatchMaster BM 
   			    ON BM.Id = SA.BatchId AND BM.IsActive=1
			where SA.DivisionId=@rSourceId  AND CS.QueryCategoryId=@rQueryCategoryId  AND AssigneeToId=@rAssigneeToId)
				BEGIN
					select -103 as Result,'Student already Exists' AS Msg
					RETURN
				END 
				
		If EXISTS(select 1 from sCommunication.tQueryCategoryScope CS 
		  INNER JOIN sStudent.tAcademic SA 
				ON CS.SourceId=SA.DivisionId AND CS.SourceTypeId=2005
		  INNER JOIN sSetup.tBatchMaster BM 
   			    ON BM.Id = SA.BatchId AND BM.IsActive=1
			where SA.DivisionId=@rSourceId  AND CS.QueryCategoryId=@rQueryCategoryId  AND AssigneeToId=@rAssigneeToId)
				BEGIN
					select -103 as Result,'Student already Exists' AS Msg
					RETURN
				END 
		END	
								
    END
    
    IF(@rSourceTypeId = 2003) -- Student	
	BEGIN
		If EXISTS(select 1 from  sCommunication.tTempQueryCategoryScope CS 
		 INNER JOIN  sStudent.tStudentMaster SM 
			ON CS.SourceId=SM.OrgId AND CS.SourceTypeId= 2021
			where SM.Id=@rSourceId  AND CS.TempQueryCategoryId=@rTempQueryCategoryId  AND AssigneeToId=@rAssigneeToId)
				BEGIN
					select -102 as Result,'Organization already Exists' AS Msg
					RETURN
				END 
		If EXISTS(select 1 from sCommunication.tTempQueryCategoryScope CS 
		 INNER JOIN  sSetup.tClassMaster CM 
			ON CS.SourceId=CM.DepartmentId AND CS.SourceTypeId= 2017
		 INNER JOIN sStudent.tAcademic SA 
				ON CM.Id=SA.ClassId 
		 INNER JOIN sSetup.tBatchMaster BM 
   			    ON BM.Id = SA.BatchId AND BM.IsActive=1
			where SA.StudentId=@rSourceId  AND CS.TempQueryCategoryId=@rTempQueryCategoryId  AND AssigneeToId=@rAssigneeToId)
				BEGIN
					select -102 as Result,'Department already Exists' AS Msg
					RETURN
				END 
				
		If EXISTS(select 1 from  sCommunication.tTempQueryCategoryScope CS 
		 INNER JOIN sStudent.tAcademic SA 
				ON CS.SourceId=SA.ClassId AND CS.SourceTypeId= 2016
		 INNER JOIN sSetup.tBatchMaster BM 
   			    ON BM.Id = SA.BatchId AND BM.IsActive=1
			where SA.StudentId=@rSourceId  AND CS.TempQueryCategoryId=@rTempQueryCategoryId  AND AssigneeToId=@rAssigneeToId)
				BEGIN
					select -102 as Result,'Class already Exists' AS Msg
					RETURN
				END 
				
		If EXISTS(select 1 from  sCommunication.tTempQueryCategoryScope CS
		 INNER JOIN sStudent.tAcademic SA 
				ON CS.SourceId=SA.DivisionId AND CS.SourceTypeId= 2005
		 INNER JOIN sSetup.tBatchMaster BM 
   			    ON BM.Id = SA.BatchId AND BM.IsActive=1
			where SA.StudentId=@rSourceId  AND CS.TempQueryCategoryId=@rTempQueryCategoryId  AND AssigneeToId=@rAssigneeToId)
				BEGIN
					select -102 as Result,'Division already Exists' AS Msg
					RETURN
				END 	
				
		IF(@rQueryCategoryId > 0)
		BEGIN	

		If EXISTS(select 1 from  sCommunication.tQueryCategoryScope CS 
		 INNER JOIN  sStudent.tStudentMaster SM 
			ON CS.SourceId=SM.OrgId AND CS.SourceTypeId= 2021
			where SM.Id=@rSourceId  AND CS.QueryCategoryId=@rQueryCategoryId  AND AssigneeToId=@rAssigneeToId)
				BEGIN
					select -102 as Result,'Organization already Exists' AS Msg
					RETURN
				END 
		If EXISTS(select 1 from sCommunication.tQueryCategoryScope CS 
		 INNER JOIN  sSetup.tClassMaster CM 
			ON CS.SourceId=CM.DepartmentId AND CS.SourceTypeId= 2017
		 INNER JOIN sStudent.tAcademic SA 
				ON CM.Id=SA.ClassId 
		 INNER JOIN sSetup.tBatchMaster BM 
   			    ON BM.Id = SA.BatchId AND BM.IsActive=1
			where SA.StudentId=@rSourceId  AND CS.QueryCategoryId=@rQueryCategoryId  AND AssigneeToId=@rAssigneeToId)
				BEGIN
					select -102 as Result,'Department already Exists' AS Msg
					RETURN
				END 
				
		If EXISTS(select 1 from  sCommunication.tQueryCategoryScope CS 
		 INNER JOIN sStudent.tAcademic SA 
				ON CS.SourceId=SA.ClassId AND CS.SourceTypeId= 2016
		 INNER JOIN sSetup.tBatchMaster BM 
   			    ON BM.Id = SA.BatchId AND BM.IsActive=1
			where SA.StudentId=@rSourceId  AND CS.QueryCategoryId=@rQueryCategoryId  AND AssigneeToId=@rAssigneeToId)
				BEGIN
					select -102 as Result,'Class already Exists' AS Msg
					RETURN
				END 
				
		If EXISTS(select 1 from  sCommunication.tQueryCategoryScope CS
		 INNER JOIN sStudent.tAcademic SA 
				ON CS.SourceId=SA.DivisionId AND CS.SourceTypeId= 2005
		 INNER JOIN sSetup.tBatchMaster BM 
   			    ON BM.Id = SA.BatchId AND BM.IsActive=1
			where SA.StudentId=@rSourceId  AND CS.QueryCategoryId=@rQueryCategoryId  AND AssigneeToId=@rAssigneeToId)
				BEGIN
					select -102 as Result,'Division already Exists' AS Msg
					RETURN
				END 	
		END	
    END
    
    IF(@rSourceTypeId = 95) -- Employee	
	BEGIN
	
	
		If EXISTS(select 1 from  sCommunication.tTempQueryCategoryScope CS 
		 INNER JOIN  sHrm.tEmployeeMaster EM 
			ON CS.SourceId=EM.OrgId AND CS.SourceTypeId= 2021
			where EM.Id=@rSourceId AND  ISNULL(EM.IsOtherUser,0) = 0  AND CS.TempQueryCategoryId=@rTempQueryCategoryId  AND AssigneeToId=@rAssigneeToId)
				BEGIN
					select -102 as Result,'Organization already Exists' AS Msg
					RETURN
				END 
				
		If EXISTS(select 1 from sCommunication.tTempQueryCategoryScope CS 
		 INNER JOIN  sHrm.tEmployeeJobDetail EJD
			ON CS.SourceId=EJD.OrganizationDepartmentId AND CS.SourceTypeId= 2017
			where  EJD.EmployeeId=@rSourceId  AND CS.TempQueryCategoryId=@rTempQueryCategoryId  AND AssigneeToId=@rAssigneeToId)
				BEGIN
					select -102 as Result,'Department already Exists' AS Msg
					RETURN
				END 
						
		IF(@rQueryCategoryId > 0)
		BEGIN	
		If EXISTS(select 1 from  sCommunication.tQueryCategoryScope CS 
		 INNER JOIN  sHrm.tEmployeeMaster EM 
			ON CS.SourceId=EM.OrgId AND CS.SourceTypeId= 2021
			where EM.Id=@rSourceId AND  ISNULL(EM.IsOtherUser,0) = 0  AND CS.QueryCategoryId=@rQueryCategoryId  AND AssigneeToId=@rAssigneeToId)
				BEGIN
					select -102 as Result,'Organization already Exists' AS Msg
					RETURN
				END 
				
		If EXISTS(select 1 from sCommunication.tQueryCategoryScope CS 
		 INNER JOIN  sHrm.tEmployeeJobDetail EJD
			ON CS.SourceId=EJD.OrganizationDepartmentId AND CS.SourceTypeId= 2017
			where  EJD.EmployeeId=@rSourceId  AND CS.QueryCategoryId=@rQueryCategoryId  AND AssigneeToId=@rAssigneeToId)
				BEGIN
					select -102 as Result,'Department already Exists' AS Msg
					RETURN
				END 
		END
		 
	 
    END
    IF(@rSourceTypeId = 2001) -- Academic	
	BEGIN
		If EXISTS(select 1 from  sCommunication.tTempQueryCategoryScope CS
		 INNER JOIN sStudent.tAcademic SA 
				ON CS.SourceId=SA.DivisionId AND CS.SourceTypeId= 2005
		 INNER JOIN sSetup.tBatchMaster BM 
   			    ON BM.Id = SA.BatchId AND BM.IsActive=1
			where SA.Id=@rSourceId  AND CS.TempQueryCategoryId=@rTempQueryCategoryId  AND AssigneeToId=@rAssigneeToId)
				BEGIN
					select -102 as Result,'Division already Exists' AS Msg
					RETURN
				END 	
		IF(@rQueryCategoryId > 0)
		BEGIN
			If EXISTS(select 1 from  sCommunication.tQueryCategoryScope CS
		 INNER JOIN sStudent.tAcademic SA 
				ON CS.SourceId=SA.DivisionId AND CS.SourceTypeId= 2005
		 INNER JOIN sSetup.tBatchMaster BM 
   			    ON BM.Id = SA.BatchId AND BM.IsActive=1
			where SA.Id=@rSourceId  AND CS.QueryCategoryId=@rQueryCategoryId  AND AssigneeToId=@rAssigneeToId)
				BEGIN
					select -102 as Result,'Division already Exists' AS Msg
					RETURN
				END 	
		END	
	END
			select 1 as Result,'' AS Msg
	
END
GO
PRINT N'Altering [sEExam].[pDeactiveALLTestParticipant]...';


GO

ALTER PROCEDURE [sEExam].[pDeactiveALLTestParticipant]
	 
	 @rTestId bigint,	 
	 @rMode int	 
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	BEGIN TRY
		BEGIN TRANSACTION			   	   
		   
		  --IF(@rMode = 1)  --Activate All Participant
		  --  BEGIN
		    
				--CREATE Table #TempTestParticipant
				--(
				--   Id Int Identity(1,1), 
				--   SourceId bigint,
				--   SourceTypeId int,
				--   TestDate Date, 
				--   TotalMarks decimal(6,2)				   
				--)
		  --    SELECT StudentId FROM sStudent.vStudentAcademic VSA Where DivisionId = @rSourceId  
		     
		  --    UPDATE sEExam.tTestParticipant SET TestStatusId = 543 WHERE TestId = @rTestId  
		  -- 	  AND ISNULL(TestStatusId,0) NOT IN (544,545) 		   	   
			 --    -- When I Deactive Div Then Also Deactive Student Which Is Active 	   
			  
			 -- UPDATE sEExam.tTestAssign SET TestStatusId = 543 Where TestId = @rTestId 
			 -- AND ISNULL(TestStatusId,0) NOT IN (544,545) 
			  			  
			 -- SELECT 1 AS Result 			  
		  --  END	   	   
		   	    
		  -- ELSE 
		   IF(@rMode = 0) --DeActivate All Participant 
		   	 BEGIN 
		   	  UPDATE sEExam.tTestParticipant SET TestStatusId = 0 WHERE TestId = @rTestId  
		   	  AND ISNULL(TestStatusId,0) NOT IN (544,545)		   	   
			     -- When I Deactive Div Then Also Deactive Student Which Is Active 	   
			  UPDATE sEExam.tTestAssign SET TestStatusId = 0 Where TestId = @rTestId 
			  AND ISNULL(TestStatusId,0)  NOT IN (544,545) 

			  ----Delete Participant Answer
			  --DELETE TPA FROM sEExam.tTestParticipantAnswer TPA 
			  --INNER JOIN sEExam.tTestParticipant TP ON TPA.TestParticipantId=TP.Id
			  --WHERE TPA.TestId= @rTestId 

			  SELECT 1 AS Result  
		     END		    
		   ELSE   -- Delete All Participant
		     BEGIN
		           
		         Delete from  sEExam.tTestParticipant   WHERE TestId = @rTestId  
		   	     AND ISNULL(TestStatusId,0) NOT IN (544,545)	
		   	      		        		        
				 DELETE FROM sEExam.tTestAssign   Where TestId = @rTestId 
				 AND ISNULL(TestStatusId,0)  NOT IN (544,545) 

			   ----Delete Participant Answer
				  --DELETE TPA FROM sEExam.tTestParticipantAnswer TPA 
				  --INNER JOIN sEExam.tTestParticipant TP ON TPA.TestParticipantId=TP.Id
				  --WHERE TPA.TestId= @rTestId 
				  
				 SELECT 1 AS Result 
		     END 	
		COMMIT TRANSACTION	
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
END
GO
PRINT N'Altering [sEExam].[pDeactiveTestParticipant]...';


GO

ALTER PROCEDURE [sEExam].[pDeactiveTestParticipant]
	 
	 @rTestId bigint,
	 @rSourceId bigint,
	 @rSourceTypeId int,
	 @rBatchId int	
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	BEGIN TRY
		BEGIN TRANSACTION			
		    IF(@rSourceTypeId = 2005)
			   BEGIN           
					 UPDATE  TP 
					 SET TP.TestStatusId = 0
					 FROM sEExam.tTestParticipant TP INNER JOIN sStudent.vStudentAcademic VSA 
					 ON TP.SourceId = VSA.StudentId 
					 Where DivisionId = @rSourceId  AND TP.TestId = @rTestId AND VSA.BatchId = @rBatchId
					 --INSERT INTO sEExam.tTestParticipant
					 --Select @rTestId,2003,StudentId,@rTestDate,@rStartTime,@rEndTime,1,@rTotalMarks,@rScoredMarks,@rTotalQuestions,@rRightQuestions,@rWrongQuestions,@rNotAttemptedQuestions
					 --FROM sStudent.vStudentAcademic VSA Where DivisionId = @rSourceId  
			           
			         UPDATE  TA 
					 SET TA.TestStatusId = 0
					 FROM sEExam.tTestAssign TA INNER JOIN sStudent.vStudentAcademic VSA 
					 ON TA.SourceId = VSA.StudentId 
					 Where DivisionId = @rSourceId AND TA.TestId = @rTestId AND VSA.BatchId = @rBatchId
				     
				  --   UPDATE  TP 
					 --SET TA.TestStatusId = 0
					 --FROM sEExam.tTestParticipant TP INNER JOIN sEExam.tTestAssign TA ON TP.SourceId = TA.SourceId					  
					 --WHERE  TP.SourceTypeId = 2003 AND TA.TestStatusId = 1 

					 ----Delete Participant Answer
					 --DELETE TPA FROM sEExam.tTestParticipantAnswer TPA 
					 --INNER JOIN sEExam.tTestParticipant TP ON TPA.TestParticipantId=TP.Id
					 --INNER JOIN sStudent.vStudentAcademic VSA ON TP.SourceId = VSA.StudentId 
					 --WHERE TPA.TestId= @rTestId  
					 --AND VSA.DivisionId = @rSourceId  AND VSA.BatchId = @rBatchId
			          
					SELECT 1 AS Result 
               END 
			ELSE 
			   BEGIN
			      UPDATE sEExam.tTestParticipant SET TestStatusId = 0 WHERE   SourceId = @rSourceId AND SourceTypeId = @rSourceTypeId AND TestId = @rTestId
			   END			   
			   -- When I Deactive Div Then Also Deactive Student Which Is Active 
			    UPDATE sEExam.tTestAssign SET TestStatusId = 0 Where SourceId = @rSourceId AND SourceTypeId = @rSourceTypeId AND TestId = @rTestId

				----Delete Participant Answer
				--DELETE TPA FROM sEExam.tTestParticipantAnswer TPA 
				--INNER JOIN sEExam.tTestParticipant TP ON TPA.TestParticipantId=TP.Id
				--INNER JOIN sStudent.vStudentAcademic VSA ON TP.SourceId = VSA.StudentId 
				--WHERE TPA.TestId= @rTestId AND  TP.SourceId = @rSourceId AND TP.SourceTypeId = @rSourceTypeId
		  
			SELECT 1 AS Result 
			
		COMMIT TRANSACTION	
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
END
GO
PRINT N'Altering [sEExam].[pTestParticipantIndividualAnswerAdd]...';


GO
 
 
ALTER PROCEDURE [sEExam].[pTestParticipantIndividualAnswerAdd]
	 
	@rTestParticipantId bigint,
	@rTestId int,
	@rQuestionDetailXml [nvarchar](max),
	@rQuestionOptionDetailXml [nvarchar](max),
	@rQuestionId bigint=0, 
	@rQuestionOptionId bigint=0
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

	DECLARE @loQuestionDoc INT
	EXEC sp_xml_preparedocument @loQuestionDoc OUTPUT, @rQuestionDetailXml
	
	DECLARE @loQuestionOptionDoc INT
	EXEC sp_xml_preparedocument @loQuestionOptionDoc OUTPUT, @rQuestionOptionDetailXml
	
BEGIN

	BEGIN TRY	
	BEGIN TRANSACTION
	
	--SELECT * FROM sEExam.tTestParticipantAnswer WHERE TestParticipantId=@rTestParticipantId AND TestId=@rTestId AND QuestionId=@rQuestionId 
	DELETE FROM sEExam.tTestParticipantAnswer WHERE TestParticipantId=@rTestParticipantId AND TestId=@rTestId AND QuestionId=@rQuestionId 
	--AND QuestionOptionId=@rQuestionOptionId
	
	UPDATE sEExam.tTestParticipant
	    SET
			TestDate = A.TestDate,
			StartTime = A.StartTime,
			EndTime = A.EndTime,
			TestStatusId = A.TestStatusId,
			TotalMarks = A.TotalMarks,
			ScoredMarks = A.ScoredMarks,
			TotalQuestions = A.TotalQuestions,
			RightQuestions = A.RightQuestions,
			WrongQuestions = A.WrongQuestions,
			SkippQuestions = A.SkippQuestions,
			NotAttemptedQuestions = A.NotAttemptedQuestions
			FROM
		 (
	  SELECT TOP 1
	        @rTestParticipantId AS TestParticipantId,
	        @rTestId AS TestId,
			TestDate,
			StartTime,
			EndTime,
			TestStatusId,
			TotalMarks,
			ScoredMarks,
			TotalQuestions,
			RightQuestions,
			WrongQuestions,
			SkippQuestions,
			NotAttemptedQuestions
		FROM OPENXML (@loQuestionDoc, '/Table/QuestionDetail', 1)
		WITH ( 
		        SourceTypeId smallint,
			    SourceId bigint,
			    TestDate date,
			    StartTime time,
			    EndTime time,
			    TestStatusId smallint,
				TotalMarks decimal(6,2),
				ScoredMarks decimal(6,2),
				TotalQuestions int,
				RightQuestions int,
				WrongQuestions int,
				SkippQuestions int,
				NotAttemptedQuestions int
			  ))A	
			    WHERE A.TestParticipantId = @rTestParticipantId AND A.TestId = @rTestId
			    AND sEExam.tTestParticipant.Id = A.TestParticipantId
			    
	INSERT INTO sEExam.tTestParticipantAnswer
		(
			TestId,
			QuestionId,
			QuestionOptionId,
			ScoredMark,
			AnswerStatusId,
			OrderIndex,
			TestParticipantId
		)
	  SELECT 
			@rTestId,
			QuestionId,
			QuestionOptionId,
			ScoredMark,
			AnswerStatusId,
			OrderIndex,
			@rTestParticipantId
			
		FROM OPENXML (@loQuestionOptionDoc, '/Table/QuestionOptionDetail', 1)
		WITH ( 
		        TestId Int,
				QuestionId bigint,
				QuestionOptionId bigint,
				ScoredMark decimal(6,2),
				AnswerStatusId smallint,
				OrderIndex smallint
			  ) 
		SELECT 1 AS Result   
		
		SELECT IsDisplayResultOnComplete FROM sEExam.tTestMaster WHERE Id =@rTestId
		
		EXEC sp_xml_removedocument @loQuestionDoc
		EXEC sp_xml_removedocument @loQuestionOptionDoc
		COMMIT TRANSACTION
	END TRY
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
		EXEC sp_xml_removedocument @loQuestionDoc
		EXEC sp_xml_removedocument @loQuestionOptionDoc
	END CATCH	 
	 
	
   
END
GO
PRINT N'Altering [sFee].[pEMandateTransactionGet]...';


GO
 
 
ALTER PROCEDURE [sFee].[pEMandateTransactionGet]
	@rAcademicId bigint = 0,
	@rFromDate nvarchar(10) = '',
	@rToDate nvarchar(10) = '',
	@rOrgGroupId smallint=0,
	@rOrgId int=0,
	@rBatchId int=0,
	@rReferenceNo bigint=0
AS
SET NOCOUNT ON

BEGIN
	 SELECT  
		ISNULL(EM.ResponseStatus,'Pending') as ResponseStatus,
		EM.Customer_DebitAmount,
		EM.Customer_MaxAmount,
		EM.Customer_StartDate,
		EM.Customer_ExpiryDate,
		CONVERT(nvarchar(20),SM.Code) AS Code,
		SM.FirstName + ' ' + SM.LastName AS Name,
		CM.DisplayTitle +' - '+ DM.DisplayTitle AS ClassName,
		EM.Id AS EMandateId
	
	FROM 
		sFee.tEmandate EM
		INNER JOIN sStudent.tAcademic A ON A.Id = EM.AcademicId
		INNER JOIN sStudent.tStudentMaster SM ON SM.Id = A.StudentId
		INNER JOIN sSetup.tClassMaster CM ON CM.Id = A.ClassId
		INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = A.DivisionId
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = CM.OrgId
		INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId
		
	WHERE 
		 ((EM.Customer_StartDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
		 AND ((EM.Customer_StartDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
		 AND ((EM.AcademicId = @rAcademicId) OR (@rAcademicId=0))
		 AND OM.OrgGroupId = @rOrgGroupId
		 AND OM.Id = @rOrgId
		 AND BM.Id = @rBatchId
		 AND (EM.Id= @rReferenceNo OR @rReferenceNo=0)
		 ORDER BY EM.Customer_StartDate DESC
END
GO
PRINT N'Altering [sFee].[pFeeGenerateReport]...';


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

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


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

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

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

	WHILE (@lCount > 0)
	BEGIN
		DECLARE @lAcademicId bigint = NULL
		DECLARE @lStudentId bigint = NULL
		DECLARE @lClassId int = NULL
		DECLARE @lFeeSetupId int = NULL
		DECLARE @lPendingAmount decimal(12,2)
		
		SELECT @lStudentId = StudentId,@lPendingAmount=PendingAmount FROM #TempOldFeeImport WHERE AutoId = @lCount
		SELECT @lAcademicId = Id, @lClassId=ClassId FROM  sStudent.tAcademic SA WHERE StudentId = @lStudentId AND BatchId = @rNewBatchId
		SELECT @lFeeSetupId = Id FROM sFee.tFeeSetup WHERE  ClassId = @lClassId AND AdmissionCategoryId = @rNewAdmissionCategoryId AND BatchId=@rNewBatchId AND FeeId = @rNewFeeId AND ReceiptBookId = @rNewReceiptBookId
		
		IF @lAcademicId IS NOT NULL AND @lFeeSetupId IS NOT NULL AND @lClassId IS NOT NULL
		BEGIN
			-- Insert Fee Optional
			INSERT INTO sFee.tFeeOptional
			   (
			    FeeSetupId,
			    SourceTypeId,
			    SourceId,
			    BatchId
			   )
				VALUES
			   (
				@lFeeSetupId,
				2001,
				@lAcademicId,
				@rNewBatchId
			   )
			 
				-- Insert Fee Allocation
				INSERT INTO sFee.tFeeAllocation
			   (
			    SourceTypeId,
			    SourceId,
			    FeeSetupId,
			    VariableAmount,
			    DiscountAmount,
			    AdditionalAmount,
			    NotApplicableAmount,
			    Remark,
			    ReferenceTypeId,
			    ReferenceSourceId,
			    CreatedUserId,
			    CreatedDateTime,
			    UpdatedUserId,
			    UpdatedDateTime
			   )
				VALUES
			   (
				2001,
				@lAcademicId,
				@lFeeSetupId,
				@lPendingAmount,
				0,
				NULL,
				NULL,
				'Old Year Pending Fee',
				NULL,
				NULL,
				@rCreatedUserId,
				sCommon.fGetDate(),
				NULL,
				NULL
			   )
		END
		 
		SET @lCount = @lCount -1
	END
	 
	DROP TABLE #TempOldFeeImport
	SELECT 1 AS Result
	COMMIT TRANSACTION
END TRY

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


GO
 
ALTER PROCEDURE [sFee].[pRptDepositMinusGet]
          
           @rOrgId int,
           @rBatchId int,
           @rCode nvarchar(20),
           @rOrgGroupBatchId int = 0
AS
SET NOCOUNT ON
BEGIN
SELECT 
		'Student' AS SourceType,
		2003 AS SourceTypeId,
		ISNULL(SA.StudentId,0) as SourceId,
		SA.SUId AS SUId,
		SA.Code as SourceCode,
		SA.Name as StudentName,
		SA.ClassName+'-'+SA.DivisionName as ClassDivisionName,
		SA.RollNo,
--		DA.HostelDepositHeadId,
--		DHM.Title AS DepositHeadName,
		SA.OrgId,
		SA.OrganizationName,
		(D.TotalDeposit - A.TotalAdjustment) AS MinusAmount,
		sA.BatchId
  FROM 		
		sStudent.vStudentAcademic SA
		INNER JOIN
		(SELECT SUM(ISNULL(DA.Amount,0)) AS TotalDeposit,DA.AcademicId FROM sFee.tDepositAdd DA GROUP BY DA.AcademicId  )D 
		ON D.AcademicId=SA.AcademicId
		LEFT JOIN 
		(select SUM(ISNULL(AD.Amount,0)) AS TotalAdjustment,AD.AcademicId   FROM sFee.tDepositAdjustment AD  GROUP BY AD.AcademicId) A 
		ON A.AcademicId=SA.AcademicId
		--INNER JOIN sHostel.tHostelDepositHeadMaster DHM ON DHM.Id = D.HostelDepositHeadId
  WHERE  
       
  	 -- SA.BatchId = @rBatchId 
		 (SA.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 ((SA.Code=@rCode) OR (ISNULL(@rCode,'')=''))
		AND  (SA.OrgGroupBatchId=@rOrgGroupBatchId OR @rOrgGroupBatchId=0)
		AND  D.TotalDeposit - A.TotalAdjustment < 0 
		  
		
END
GO
PRINT N'Altering [sFee].[pRptFeeReceiptListGet]...';


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

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

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


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

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

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

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

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


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

		 ORDER BY R.ReceiptNumber
	END

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

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


GO

 
ALTER PROCEDURE [sFee].[pRptFeeStatusCollectionGroupWiseGet]
		@rReportId int,
		@rReceiptBookId int,
		@rAdmissionCategoryId int,
		@rClassId int,
		@rDivisionId int,
		@rUptoDate date,
		@rBatchId int,
		@rUserId bigint,
		@rBuilder1 nvarchar(max),
		@rBuilder2 nvarchar(max),
		@rIsDetail bit,
		@rOrgId int,
		@rOrgGroupBatchId int,
		@rIsExemption bit =0,
		@rStatusId int,
		@rCommonBatch nvarchar(100),
		@rDepartmentId int,
		@rFromRollNo int,
	    @rToRollNo int,
	    @rCode nvarchar(20),
	    @rIsFilter bit,
		@rIsHeader bit,
		@rCreatedUserName nvarchar(100)='',
		@rFeeHeadId nvarchar(max) = '',
		@rIsDisplayOrgGroup bit=0,
		@rExemptionTypeId int=0,
		@rFeeId nvarchar(max) = '',
		@rFilterId int=0,
		@rFeeGroupId int=0,
		@rCollectionGroupId int = 0,
		@rClassStatusId int=0 --,
		--@rOrgIds 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)
	)
	
	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      
		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 ((SA1.DivisionId=@rDivisionId) OR (@rDivisionId=0))  
			AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))  
			INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId  
			INNER JOIN 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.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))  
			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(CGM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rCollectionGroupId,','))OR @rCollectionGroupId='')  

	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       
		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 ((SA1.DivisionId=@rDivisionId) OR (@rDivisionId=0))  
			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.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))  
			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(CGM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rCollectionGroupId,','))OR @rCollectionGroupId='')  

	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 ((SA1.DivisionId=@rDivisionId) OR (@rDivisionId=0))  
		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='')  
	GROUP BY FeeSetupId,R.SourceId  

	CREATE TABLE #PaidPendingCount
	(
		CollectionGroupMasterId int,
		ReceiptBookMasterId int,
		ClassId int,
		AcademicId bigint,
		ToPayAmount decimal(12,2)
	)
	INSERT INTO #PaidPendingCount

			SELECT 
			CGM1.Id,RBM1.Id,S1.ClassId,S1.Id,FAS.ToPayAmount FROM sStudent.tAcademic S1
			INNER JOIN sFee.tFeeAllocationStudent FAS ON FAS.AcademicId=S1.Id  
		    INNER JOIN sFee.tFeeSetup FS ON FAS.FeeSetupId = FS.Id
			INNER JOIN sFee.tReceiptBookMaster RBM1 ON FS.ReceiptBookId=RBM1.Id
			LEFT JOIN sFee.tCollectionGroupMaster CGM1 ON FS.CollectionGroupId=CGM1.Id AND RBM1.Id = CGM1.ReceiptBookId AND CGM1.OrgGroupBatchId = @rOrgGroupBatchId
	
	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))

	SELECT 
		@rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,
		@rIsDetail AS IsDetail,
		@rIsFilter As IsFilter,
		@rIsHeader As IsHeader, 
		@rIsDisplayOrgGroup AS IsDisplayOrgGroup,
		SA.AcademicId,
		SA.RollNo,
		SA.Name,
		SA.Code,
		SA.ClassId,
		SA.DivisionId,
		SA.ClassName,
		SA.DivisionName,
		SA.DivisionOrder AS DivisionOrderIndex,
		SA.ClassOrderIndex AS ClassOrderIndex,
		SA.ClassName+' - '+SA.DivisionName AS ClassDivision,
		FS.Id AS FeeSetupId,
		
		ISNULL(FS.IsVariable,0)AS IsVariable,
		ISNULL(FS.Amount,0)AS Amount,
		ISNULL(FS.StartDate,'1900-01-01')AS StartDate,
		ISNULL(FS.EndDate,'1900-01-01')AS EndDate,
		ISNULL(FA.VariableAmount,0.00)AS FAAmount,
		ISNULL(FA.DiscountAmount,0.00)AS DiscountAmount,
		ISNULL(FA.AdditionalAmount,0.00)AS AdditionalAmount,
		ISNULL(FA.NotApplicableAmount,0.00)AS NotApplicableAmount,
		ISNULL(R.PaidAmount,0) AS PaidAmount,
		ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00)AS PendingAmount,
		ISNULL(FA.Remark,'') AS Remark,
		FS.ReceiptBookId,
		FS.FeeName,
		SA.OrgId,
		O.DisplayTitle AS OrgName,
		O.OrderIndex AS OrgOrderIndex,
		ISNULL(RBM.Title,'') AS ReceiptBookTitle,
		ISNULL(RBM.OrderIndex,0) AS ReceiptOrderIndex,
		SA.DepartmentId,
		SA.DepartmentName,
		SA.ExemptionTypeId,
		ISNULL(ETM.Title,'') AS ExemptionType,
		FHM.Id AS FeeHeadId,
		FHM.Title AS FeeHeadName,
		FHM.OrderIndex AS FeeHeadOrderIndex,
		@rFeeGroupId As FeeGroup,
		ISNULL(CGM.Id,0) AS CollectionGroupId,
		ISNULL(CGM.Title,'') AS CollectionGroup,
		ISNULL(CGM.OrderIndex,0) AS CollectionGroupOrderIndex,		
		CASE WHEN ROW_NUMBER() OVER (PARTITION BY SA.ClassId  ORDER BY SA.ClassId ) =1 THEN (SELECT COUNT(1) FROM sStudent.tAcademic A INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId WHERE A.ClassId= SA.ClassId AND A.BatchId = SA.BatchId  AND A.OrgId = SA.OrgId AND BM.OrgGroupBatchId = SA.OrgGroupBatchId GROUP BY ClassId) ELSE 0 END AS StudentCount,
		--CASE WHEN ROW_NUMBER() OVER (PARTITION BY SA.AcademicId  ORDER BY SA.AcademicId) =1 THEN (CASE WHEN (SUM(ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00)) > 0) THEN 1 ELSE 0 END) ELSE 0 END AS PendingAmount

		--( SELECT SUM(T.PaidCount) FROM 
		--(SELECT 
		--	COUNT(DISTINCT(S1.Id)) AS PaidCount FROM sStudent.tAcademic S1
		--	INNER JOIN sFee.tFeeAllocationStudent FAS ON FAS.AcademicId=S1.Id  
		-- INNER JOIN sFee.tFeeSetup FS ON FAS.FeeSetupId = FS.Id
		--INNER JOIN sFee.tReceiptBookMaster RBM1 ON FS.ReceiptBookId=RBM1.Id
		--LEFT JOIN sFee.tCollectionGroupMaster CGM1 ON FS.CollectionGroupId=CGM1.Id AND RBM1.Id = CGM1.ReceiptBookId AND CGM1.OrgGroupBatchId = @rOrgGroupBatchId
		--WHERE (CGM1.Id = CGM.Id OR ISNULL(CGM.Id,0) = 0) AND RBM1.Id = RBM.Id AND S1.ClassId = SA.ClassId
		--GROUP BY S1.Id
		--HAVING SUM(ISNULL(FAS.ToPayAmount,0.00)) = 0 
		--) T )			
		--	AS PaidCount,
		--( SELECT SUM(T.PendingCount) FROM 
		--(SELECT 
		--	COUNT(DISTINCT(S1.Id)) AS PendingCount FROM sStudent.tAcademic S1
		--	INNER JOIN sFee.tFeeAllocationStudent FAS ON FAS.AcademicId=S1.Id  
		-- INNER JOIN sFee.tFeeSetup FS ON FAS.FeeSetupId = FS.Id
		--INNER JOIN sFee.tReceiptBookMaster RBM1 ON FS.ReceiptBookId=RBM1.Id
		--LEFT JOIN sFee.tCollectionGroupMaster CGM1 ON FS.CollectionGroupId=CGM1.Id AND RBM1.Id = CGM1.ReceiptBookId AND CGM1.OrgGroupBatchId = @rOrgGroupBatchId
		--WHERE (CGM1.Id = CGM.Id OR ISNULL(CGM.Id,0) = 0) AND RBM1.Id = RBM.Id AND S1.ClassId = SA.ClassId
		--GROUP BY S1.Id
		--HAVING SUM(ISNULL(FAS.ToPayAmount,0.00)) > 0 
		--) T )			
		--	AS PendingCount,
	    --Comment PaidCount and PendingCount due to performance issue and create 2 temp table #PaidPendingCount and #TempAssignRoute--26/05/2023
		(SELECT COUNT(distinct(AcademicId)) FROM #PaidPendingCount WHERE ClassId = SA.ClassId AND ReceiptBookMasterId = RBM.Id AND CollectionGroupMasterId = CGM.Id AND ISNULL(ToPayAmount,0.00) = 0) AS PaidCount,
		(SELECT COUNT(distinct(AcademicId)) FROM #PaidPendingCount WHERE ClassId = SA.ClassId AND ReceiptBookMasterId = RBM.Id AND CollectionGroupMasterId = CGM.Id AND ISNULL(ToPayAmount,0.00) > 0) AS PendingCount,
		ISNULL(SC.PresentStreetOne,'')+' '+ISNULL(SC.PresentStreetTwo,'')+' '+ISNULL(SC.PresentStreetThree,'')+' '+ISNULL(SC.PresentCity,'')+' '+ISNULL(SC.PresentState,'') AS [Address],
		ISNULL(SF.FatherContactNo,'')AS FatherContactNo,
		ISNULL(SF.MotherContactNo,'')AS MotherContactNo
		--CGM.Id,
		--RBM.Id,
		--SA.ClassId

		--( SELECT SUM(T.PaidCount) FROM (SELECT 
		--	COUNT(DISTINCT(S1.AcademicId)) AS PaidCount FROM sStudent.vStudentAcademic S1
		--	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,				 
		--			FS1.CollectionGroupId
		--		FROM sFee.tFeeSetup FS1
		--		INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
		--		AND ((SA1.ClassId=@rClassId) OR (@rClassId=0))
		--		AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))			
		--		WHERE 
		--			((FS1.ClassId=@rClassId) OR (@rClassId=0))
		--			AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
		--			AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
		--			AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
		--			AND (FS1.IsOptional=0)
		--			AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
		--			AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
		--			AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
		--			AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))			 
		--			--AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')
		--			UNION ALL
				
		--		SELECT 
		--			FS1.FeeId,
		--			FS1.Id,
		--			ISNULL(FS1.IsOptional,0)AS IsOptional,
		--			ISNULL(FS1.IsVariable,0)AS IsVariable,
		--			ISNULL(FS1.Amount,0)AS Amount,
		--			ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
		--			ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
		--			FS1.BatchId,
		--			ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
		--			SA1.AcademicId,				 
		--			FS1.CollectionGroupId
		--		FROM sFee.tFeeSetup FS1
		--	INNER JOIN sFee.tFeeOptional FO
		--		ON FO.FeeSetupId=FS1.Id 
		--	--INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
		--	INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=FO.SourceId
		--	AND FS1.BatchId = SA1.BatchId AND SA1.ClassId=FS1.ClassId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
		--		AND ((SA1.ClassId=@rClassId) OR (@rClassId=0)) 
		--	AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
		--WHERE
		--			((FS1.ClassId=@rClassId) OR (@rClassId=0))
		--			AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
		--		AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
		--		AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
		--		AND (FS1.IsOptional=1)
		--		AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
		--		AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
		--		AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
		--		AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))							
		--	) FS ON FS.AcademicId=S1.AcademicId
		--	LEFT JOIN sFee.tFeeAllocation FA
		--		ON FA.FeeSetupId=FS.Id AND FA.SourceId=S1.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 
		--			AND ((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
		--			AND (SA1.ClassId=@rClassId OR @rClassId=0) 
		--			AND (SA1.DivisionId=@rDivisionId OR @rDivisionId=0)
		--		WHERE		
		--			(R.SourceTypeId = 2001)
		--		AND (R.IsObsolete = 0) 
		--		AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
		--		AND (SA1.OrgGroupBatchId = @rOrgGroupBatchId)
		--		AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
		--		AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))
		--		AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
		--		AND (R.ReceiptDate <= @rUptoDate)
		--			AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit('',','))OR ''='')
		--			AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit('',','))OR ''='')
		--			--AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')
		--				GROUP BY FeeSetupId,R.SourceId
		
		--	) R ON R.FeeSetupId = FS.Id AND S1.AcademicId = R.SourceId
		--	INNER JOIN sFee.tReceiptBookMaster RBM1
		--		ON FS.ReceiptBookId=RBM.Id
		--	LEFT JOIN sFee.tCollectionGroupMaster CGM1
		--		ON FS.CollectionGroupId=CGM1.Id AND RBM1.Id = CGM1.ReceiptBookId AND CGM1.OrgGroupBatchId = @rOrgGroupBatchId
		--	WHERE (CGM1.Id = CGM.Id OR ISNULL(CGM.Id,0) = 0) AND RBM1.Id = RBM.Id AND S1.ClassId = SA.ClassId
		--	GROUP BY S1.AcademicId
		--HAVING SUM(ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00)) = 0 
		--) T )			
		--	AS PaidCount,

		--	( SELECT SUM(T.PendingCount) FROM (SELECT 
		--	COUNT(DISTINCT(S1.AcademicId)) AS PendingCount FROM sStudent.vStudentAcademic S1
		--	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,				 
		--			FS1.CollectionGroupId
		--		FROM sFee.tFeeSetup FS1
		--		INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
		--		AND ((SA1.ClassId=@rClassId) OR (@rClassId=0))
		--		AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))			
		--		WHERE 
		--			((FS1.ClassId=@rClassId) OR (@rClassId=0))
		--			AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
		--			AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
		--			AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
		--			AND (FS1.IsOptional=0)
		--			AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
		--			AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
		--			AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
		--			AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))			 
		--			--AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')
		--			UNION ALL
				
		--		SELECT 
		--			FS1.FeeId,
		--			FS1.Id,
		--			ISNULL(FS1.IsOptional,0)AS IsOptional,
		--			ISNULL(FS1.IsVariable,0)AS IsVariable,
		--			ISNULL(FS1.Amount,0)AS Amount,
		--			ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
		--			ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
		--			FS1.BatchId,
		--			ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
		--			SA1.AcademicId,				 
		--			FS1.CollectionGroupId
		--		FROM sFee.tFeeSetup FS1
		--	INNER JOIN sFee.tFeeOptional FO
		--		ON FO.FeeSetupId=FS1.Id 
		--	--INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
		--	INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=FO.SourceId
		--	AND FS1.BatchId = SA1.BatchId AND SA1.ClassId=FS1.ClassId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
		--		AND ((SA1.ClassId=@rClassId) OR (@rClassId=0)) 
		--	AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
		--WHERE
		--			((FS1.ClassId=@rClassId) OR (@rClassId=0))
		--			AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
		--		AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
		--		AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
		--		AND (FS1.IsOptional=1)
		--		AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
		--		AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
		--		AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
		--		AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))							
		--	) FS ON FS.AcademicId=S1.AcademicId
		--	LEFT JOIN sFee.tFeeAllocation FA
		--		ON FA.FeeSetupId=FS.Id AND FA.SourceId=S1.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 
		--			AND ((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
		--			AND (SA1.ClassId=@rClassId OR @rClassId=0) 
		--			AND (SA1.DivisionId=@rDivisionId OR @rDivisionId=0)
		--		WHERE		
		--			(R.SourceTypeId = 2001)
		--		AND (R.IsObsolete = 0) 
		--		AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
		--		AND (SA1.OrgGroupBatchId = @rOrgGroupBatchId)
		--		AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
		--		AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))
		--		AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
		--		AND (R.ReceiptDate <= @rUptoDate)
		--			AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit('',','))OR ''='')
		--			AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit('',','))OR ''='')
		--			--AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')
		--				GROUP BY FeeSetupId,R.SourceId
		
		--	) R ON R.FeeSetupId = FS.Id AND S1.AcademicId = R.SourceId
		--	INNER JOIN sFee.tReceiptBookMaster RBM1
		--		ON FS.ReceiptBookId=RBM.Id
		--	LEFT JOIN sFee.tCollectionGroupMaster CGM1
		--		ON FS.CollectionGroupId=CGM1.Id AND RBM1.Id = CGM1.ReceiptBookId AND CGM1.OrgGroupBatchId = @rOrgGroupBatchId
		--	WHERE (CGM1.Id = CGM.Id OR ISNULL(CGM.Id,0) = 0) AND RBM1.Id = RBM.Id AND S1.ClassId = SA.ClassId
		--	GROUP BY S1.AcademicId
		--HAVING SUM(ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00)) > 0 
		--) T )			
		--	AS PendingCount



  FROM 
  
	    sStudent.vStudentAcademic SA
		INNER JOIN sStudent.tStudentCommunication SC ON SC.StudentId=SA.StudentId
		LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId = SA.StudentId
		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 sFee.tCollectionGroupMaster CGM ON FS.CollectionGroupId=CGM.Id AND RBM.Id = CGM.ReceiptBookId AND CGM.OrgGroupBatchId = @rOrgGroupBatchId
		INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FS.FeeHeadId	
		LEFT JOIN sFee.tExemptionTypeMaster ETM ON ETM.Id = SA.ExemptionTypeId
		LEFT JOIN sHostel.tAssignRoom AR ON  AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003 AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  AND ((AR.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) 
		LEFT JOIN #TempAssignRoute RT ON RT.SourceId = SA.StudentId AND ((SA.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)) 
	WHERE	
	((@rIsExemption = 0 AND  1 = 1) OR (@rIsExemption = 1  AND  ISNULL(FA.DiscountAmount,0) > 0))
    AND	((SA.BatchId=@rBatchId) OR (@rBatchId=0))   
    AND	((SA.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))   
    AND (SA.StatusId=@rStatusId OR @rStatusId=0)
	--AND ((FS.StartDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
	AND ((SA.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
	AND ((SA.RollNo <= @rToRollNo) OR (@rToRollNo=0))
	AND ((SA.Code=@rCode) OR (@rCode=''))
	AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))		
	AND ((SA.ExemptionTypeId=@rExemptionTypeId) OR (@rExemptionTypeId=0))		
	AND ((SA.ClassId=@rClassId) OR (@rClassId=0))
	AND ((SA.DivisionId=@rDivisionId) OR (@rDivisionId=0))
	AND	((CGM.Id=@rCollectionGroupId) OR (@rCollectionGroupId=0))   
		 AND (
				 (@rFilterId = 0) -- All
				 OR (@rFilterId = 2 AND isnull(AR.SourceId,0)!=0) -- Hostel
				 OR (@rFilterId = 3 AND isnull(RT.SourceId,0)!=0) -- Transport
				 OR ((@rFilterId =1) AND ((isnull(AR.SourceId,0)=0) AND (isnull(RT.SourceId,0)=0)))
			     )	
				 AND ((SA.ClassStatusId=@rClassStatusId) OR (@rClassStatusId=0))
    --AND (ISNULL(SA.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')			     
			Order by SA.RollNo
			

	DROP TABLE #TempIsOptional
	DROP TABLE #TempReceipt
	DROP TABLE #PaidPendingCount
	DROP TABLE #TempAssignRoute
	--SELECT 
	--	'' AS Builder1,
	--	'' AS Builder2,
	--	'' AS IsDetail,
	--	'' As IsFilter,
	--	'' As IsHeader, 
	--	'' AS IsDisplayOrgGroup,
	--	0 AS AcademicId,
	--	0 AS RollNo,
	--	'' AS Name,
	--	'' AS Code,
	--	0 AS ClassId,
	--	0 AS DivisionId,
	--	'' AS ClassName,
	--	'' AS DivisionName,
	--	0  AS DivisionOrderIndex,
	--	0 AS ClassOrderIndex,
	--	'' AS ClassDivision,
	--	0 AS FeeSetupId,
		
	--	0 AS IsVariable,
	--	0 AS Amount,
	--	'' AS StartDate,
	--	'' AS EndDate,
	--	0 AS FAAmount,
	--	0 AS DiscountAmount,
	--	0 AS AdditionalAmount,
	--	0 AS NotApplicableAmount,
	--	0 AS PaidAmount,
	--	0 AS PendingAmount,
	--	'' AS Remark,
	--	0 AS ReceiptBookId,
	--	'' AS FeeName,
	--	0 AS OrgId,
	--	'' AS OrgName,
	--	0 AS OrgOrderIndex,
	--	'' AS ReceiptBookTitle,
	--	0 AS ReceiptOrderIndex,
	--	0 AS DepartmentId,
	--	'' AS DepartmentName,
	--	0 AS ExemptionTypeId,
	--	'' AS ExemptionType,
	--	0 AS FeeHeadId,
	--	'' AS FeeHeadName,
	--	0 AS FeeHeadOrderIndex,
	--	0 As FeeGroup,
	--	0 AS CollectionGroupId,
	--	'' AS CollectionGroup,
	--	0 AS CollectionGroupOrderIndex,		
	--	0 AS StudentCount,
	--	0 AS PaidCount,
	--	0 AS PendingCount,
	--	'' AS Address,
	--	'' AS FatherContactNo,
	--	'' AS MotherContactNo
				

END
GO
PRINT N'Altering [sFrontOffice].[pStudentGatePassGet]...';


GO
ALTER PROCEDURE [sFrontOffice].[pStudentGatePassGet]
          
           @rId int,
           @rOrgId int=0,
           @rFromGatePassDate datetime='',
           @rToGatePassDate datetime='',
           @rEntryModeStatusId smallint=0,
           @rCode nvarchar(20)='',
           @rIsPrintView bit=0,
           @rOrgGroupId int=0,
           @rUserId bigint= 0,
		   @rDepartmentId int=0,
		   @rClassId int=0,
		   @rDivisionId int=0
AS
SET NOCOUNT ON
BEGIN
		Declare @GatePassConfig nvarchar(20)=''
		SELECT @GatePassConfig =ItemValue From sConfig.tConfigurationSetup WHERE ConfigurationId = 241 AND SourceId = @rOrgGroupId
		
		SELECT  
			SGP.Id,
			vSA.Code,
			vSA.FirstName+' '+vSA.MiddleName+' '+vSA.LastName AS Name,
			VSA.ClassName+' - '+VSA.DivisionName AS Class,
			SGP.AcademicId,
			ISNULL(SGP.RelationshipId,0) AS RelationshipId,
			RM.Title AS Relationship,
			SGP.Relation,
			SGP.VisitorName,
			ISNULL(SGP.VisitorMobile,0) As VisitorMobile,
			SGP.ReasonOfGatePass,
			(CASE  WHEN @rIsPrintView=1 THEN 
				SGP.VisitorPhoto		
			ELSE ISNULL(SGP.VisitorPhoto, CONVERT(VARBINARY(MAX), 0)) END) AS VisitorPhoto,
			--ISNULL(SGP.VisitorPhoto, CONVERT(VARBINARY(MAX), 0)) AS VisitorPhoto,
			ISNULL(SGP.GatePassDate,'') As GatePassDate,
			ISNULL(SGP.ReturnGatePassDate,'') As ReturnGatePassDate,
			ISNULL(SGP.GatePassTime,'') As GatePassTime,
			ISNULL(SGP.ReturnGatePassTime,'') As ReturnGatePassTime,
			ISNULL(SGP.EntryModeStatusId,0) AS EntryModeStatusId,
			ISNULL(SM.Title,'')  AS EntryModeStatus,
			OM.Id AS OrgId,
			OM.OrgLogo,
			OM.DisplayTitle AS Organization,
			(CASE  WHEN @rIsPrintView=1 THEN 
				SI.StudentPhoto		
			ELSE ISNULL(SI.StudentPhoto, CONVERT(VARBINARY(MAX), 0)) END) AS StudentPhoto,
			
			(CASE  WHEN @rIsPrintView=1 THEN 
				SI.FatherPhoto		
			ELSE ISNULL(SI.FatherPhoto, CONVERT(VARBINARY(MAX), 0)) END) AS FatherPhoto,
			
			(CASE  WHEN @rIsPrintView=1 THEN 
				SI.MotherPhoto		
			ELSE ISNULL(SI.MotherPhoto, CONVERT(VARBINARY(MAX), 0)) END) AS MotherPhoto,
			
			(CASE  WHEN @rIsPrintView=1 THEN 
				SI.RelativePhoto		
			ELSE ISNULL(SI.RelativePhoto, CONVERT(VARBINARY(MAX), 0)) END) AS RelativePhoto,
			
			--ISNULL(SI.StudentPhoto, CONVERT(VARBINARY(MAX), 0)) AS StudentPhoto,
			ISNULL(U.DisplayTitle,'') AS UserName,
			vSA.SUId,
			Remark,
			@GatePassConfig AS ConfigValue,
				
			SF.FatherContactNo,
			SF.MotherContactNo,
			SF.RelativeContactNo,
			SF.FatherName,
			SF.MotherName,
			SF.RelativeName,
			ISNULL(SGP.GatePassNo,0)AS GatePassNo
		FROM 
		    sStudent.vStudentAcademic vSA
			INNER JOIN sFrontOffice.tStudentGatePass SGP ON SGP.AcademicId = vSA.AcademicId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=vSA.OrgId
			INNER JOIN sCommon.tRelationshipMaster RM ON RM.Id=SGP.RelationshipId
			INNER JOIN sCommon.tStatusMaster SM ON SM.Id=SGP.EntryModeStatusId			
			INNER JOIN sSecurity.tUserOrganization UO ON UO.OrgId = SGP.OrgId AND UO.UserId = @rUserId
			LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId=vSA.StudentId
			LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId = SI.StudentId
			LEFT JOIN sSecurity.tUser U	ON U.Id=SGP.CreatedUserId
			
		WHERE 
		  ((SGP.Id=@rId) OR (@rId=0))
			AND ((SGP.OrgId=@rOrgId) OR (@rOrgId=0))
			AND ((SGP.GatePassDate>=@rFromGatePassDate) OR (ISNULL(@rFromGatePassDate,'')=''))
			AND ((SGP.GatePassDate<=@rToGatePassDate) OR (ISNULL(@rToGatePassDate,'')=''))
			AND ((SGP.EntryModeStatusId=@rEntryModeStatusId) OR (@rEntryModeStatusId=0))
			AND ((vSA.Code=@rCode) OR (ISNULL(@rCode,'')=''))
			AND (OM.OrgGroupId=@rOrgGroupId)
			AND ((vSA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
			AND ((vSA.ClassId=@rClassId) OR (@rClassId=0))
			AND ((vSA.DivisionId=@rDivisionId) OR (@rDivisionId=0))
			--AND vSA.IsActiveBatch=1
			ORDER BY SGP.GatePassDate,SGP.GatePassTime DESC
			
END
GO
PRINT N'Altering [sHrm].[pLeaveTypeGradeSeetingListGet]...';


GO

ALTER PROCEDURE [sHrm].[pLeaveTypeGradeSeetingListGet]
    @rEmployeeGradeId int = 0,
    @rOrgId int
AS
SET NOCOUNT ON

BEGIN
       
       SELECT 
				 LTM.Id AS LeaveTypeId,
				 LTM.Title AS LeaveType,
				 ISNULL(LTGS.EmployeeGradeId,0) AS EmployeeGradeId,
				 ISNULL(LTGS.NoOfLeave,'') AS NoOFLeave,
				 ISNULL(LTGS.MaxInMonth,0) AS MaxInMonth,
				 LTGS.LeaveTypeId --,
				 --Isnull(LTGS.LeaveCarryForwordRuleId,1) AS LeaveCarryForwordRuleId
       FROM 
			   sHrm.tLeaveTypeMaster LTM 
		   LEFT JOIN sHrm.tLeaveTypeGradeSettings LTGS ON LTGS.LeaveTypeId = LTM.Id AND EmployeeGradeId = @rEmployeeGradeId
       WHERE 
			   LTM.IsObsolete = 0
			AND LTM.OrgId = @rOrgId   AND IsLWP = 0
END
GO
PRINT N'Altering [sHrm].[pLeaveTypeGradeSettingAdd]...';


GO
ALTER PROCEDURE [sHrm].[pLeaveTypeGradeSettingAdd]
           
           @rLeaveTypeId int,
           @rEmployeeGradeId int,
           @rNoOfLeave int,
           @rMaxInMonth decimal(5,2),          
           @rOrgId smallint--,
		  -- @rLeaveCarryForwordRuleId int=1
        
AS
SET NOCOUNT ON

BEGIN

	BEGIN TRY
	
	BEGIN TRANSACTION

	DECLARE @lNextNumber bigint	  
	
	IF EXISTS(SELECT 1 FROM sHrm.tLeaveTypeGradeSettings WHere LeaveTypeId = @rLeaveTypeId AND OrgId = @rOrgId AND EmployeeGradeId = @rEmployeeGradeId)
	DELETE FROM sHrm.tLeaveTypeGradeSettings WHere LeaveTypeId = @rLeaveTypeId AND OrgId = @rOrgId AND EmployeeGradeId = @rEmployeeGradeId
	
	BEGIN		     
		   INSERT INTO [sHrm].[tLeaveTypeGradeSettings]
           (
            [OrgId]
           ,[LeaveTypeId]
           ,[EmployeeGradeId]
           ,[NoOfLeave]
           ,[MaxInMonth]
		   --,[LeaveCarryForwordRuleId]
           )
     VALUES
           (
            @rOrgId
           ,@rLeaveTypeId
           ,@rEmployeeGradeId
           ,@rNoOfLeave
           ,@rMaxInMonth
		   --,@rLeaveCarryForwordRuleId
           )		 
          END
	   SELECT 1 AS Result	   
	   COMMIT TRANSACTION
	   		
	END TRY	
	BEGIN CATCH
		ROLLBACK TRANSACTION
		SELECT -1 AS RESULT
	END CATCH
	
END
GO
PRINT N'Altering [sHrm].[pStaffCountDashboardGet]...';


GO
 
ALTER PROCEDURE [sHrm].[pStaffCountDashboardGet]
	 
	 @rTypeId smallint,
	 @rOrgGroupId int = 0,
	 @rOrgId int = 0,
	 @rDepartmentId int = 0,
	 @rCommonOrgGroupBatchId int = 0	 
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	IF (@rTypeId=1)
	BEGIN
		 
	SELECT     
		OGM.Id AS OrgGroupId,
		OGM.Title AS OrgGroupTitle,
		EDM.Title AS Designation,
		COUNT(ISNULL(EM.Id, 0)) AS StaffCount
	FROM sHrm.tEmployeeMaster EM 
		INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID
		INNER JOIN sHrm.tEmployeeDesignationMaster EDM  ON EDM.Id = EJD.EmployeeDesignationId
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = EM.OrgID
		INNER JOIN sSetup.tOrgGroupMaster OGM ON OM.OrgGroupId = OGM.Id
		INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.OrgGroupId=OGM.Id
		INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId 
	
	WHERE 
					 
		(OGM.Id=@rOrgGroupId OR @rOrgGroupId=0) 
		AND COGBM.Id = @rCommonOrgGroupBatchId
		AND EDM.IsObsolete = 0
		AND EM.StatusId = 7
		And ISNULL(OGM.IsObsolete,0) = 0
	
	GROUP BY OGM.Id, OGM.Title, EDM.Title
			 
	END
END
GO
PRINT N'Altering [sLibrary].[pBookMasterGet]...';


GO

ALTER PROCEDURE [sLibrary].[pBookMasterGet]
	 
	 @rId bigint = 0,
	 @rCode nvarchar(200),
	 @rTitle nvarchar(100),
	 @rOrgId int,
	 @rPublisher nvarchar(200),
	 @rSupplier nvarchar(200),
	 @rAuthor nvarchar(200),
	 @rSubject nvarchar(200),
	 @rLanguage nvarchar(200),
	 @rLocation nvarchar(200),
	 @rEdition nvarchar(50),
	 @rPrice decimal=0,
	 @rCurrency nvarchar(100),
	 @rISBNNumber nvarchar(100),
	 @rBookTag nvarchar(200),
	 @rBookCustomTag nvarchar(200),
	 @rBookAgeGroupId int,
	 @rResourceTypeId int,
	 @rStatusId smallint,
	 @rCreatedUserId bigint,
	 @rLibraryId int,
	 @rBookDepartment nvarchar(150),
	 @rShowWithPhotoId int=0,
	 @rBookGroup1Id int=0,
	 @rBookGroup2Id int=0,
	 @rAccession nvarchar(50),
	 @rOrderIndex int=0
	
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
--DECLARE @lpaging
BEGIN 


	  --BEGIN
			--SET @rCode = sCommon.fSearchStringGet(@rCode)
			SET @rTitle = sCommon.fSearchStringGet(@rTitle)
			SET @rPublisher = sCommon.fSearchStringGet(@rPublisher)
			SET @rSupplier = sCommon.fSearchStringGet(@rSupplier)
			SET @rAuthor = sCommon.fSearchStringGet(@rAuthor)
			SET @rSubject = sCommon.fSearchStringGet(@rSubject)
			SET @rLanguage = sCommon.fSearchStringGet(@rLanguage)
			SET @rLocation = sCommon.fSearchStringGet(@rLocation)
			SET @rEdition = sCommon.fSearchStringGet(@rEdition)
			SET @rCurrency = sCommon.fSearchStringGet(@rCurrency)
			SET @rISBNNumber = sCommon.fSearchStringGet(@rISBNNumber)
			SET @rBookTag = sCommon.fSearchStringGet(@rBookTag)
			SET @rBookCustomTag = sCommon.fSearchStringGet(@rBookCustomTag)
			SET @rAccession = sCommon.fSearchStringGet(@rAccession)
		
	  --END
	 declare @quer nvarchar(max)=''
	declare @lId bigint = 0,@lCode nvarchar(200),@lTitle nvarchar(100),@lOrgId int,
	@lPublisher nvarchar(200),@lSupplier nvarchar(200),@lAuthor nvarchar(200),
	@lSubject nvarchar(200),@lLanguage nvarchar(200),@lLocation nvarchar(200),
	@lEdition nvarchar(50),@lPrice decimal=0,@lCurrency nvarchar(100),
	@lISBNNumber nvarchar(100),@lBookTag nvarchar(200),@lBookCustomTag nvarchar(200),
	@lBookAgeGroupId int,@lResourceTypeId int,@lStatusId smallint,@lCreatedUserId bigint,
	@lLibraryId int,@lBookDepartment nvarchar(150),@lBookGroup1Id int,@lBookGroup2Id int,@lAccession nvarchar(50),
	@lOrderIndex int
	select @lId = isnull(@rId,0),@lCode = isnull(@rCode,''),@lTitle = isnull(@rTitle,''),
	@lOrgId = isnull(@rOrgId,0),@lPublisher = isnull(@rPublisher,''),@lSupplier = isnull(@rSupplier,''),
	@lAuthor = isnull(@rAuthor,''),@lSubject = isnull(@rSubject,''),
	@lLanguage = isnull(@rLanguage,''),@lLocation = isnull(@rLocation,''),
	@lEdition = isnull(@rEdition,''),@lPrice = isnull(@rPrice,0),@lCurrency = isnull(@rCurrency,''),
	@lISBNNumber = isnull(@rISBNNumber,''),@lBookTag = isnull(@rBookTag,''),
	@lBookCustomTag = isnull(@rBookCustomTag,''),@lBookAgeGroupId = isnull(@rBookAgeGroupId,0),
	@lResourceTypeId = isnull(@rResourceTypeId,0),@lStatusId = isnull(@rStatusId,0),@lCreatedUserId = isnull(@rCreatedUserId,0),
	@lLibraryId = isnull(@rLibraryId,0),@lBookDepartment = isnull(@rBookDepartment,''),
	@lBookGroup1Id = isnull(@rBookGroup1Id,0),@lBookGroup2Id = isnull(@rBookGroup2Id,0),@lAccession = ISNULL(@rAccession,''),
	@lOrderIndex=ISNULL(@rOrderIndex,0)

	 
	SELECT @quer='SELECT BM.Code,
	BM.Title,
	ISNULL(BM.Publisher,'''')AS Publisher,
	ISNULL(BM.Supplier,'''')AS Supplier,
	ISNULL(BM.Author,'''')AS Author,
	ISNULL(BM.BookSubject,'''') AS BookSubject,
	ISNULL(BM.BookLanguage,'''') AS BookLanguage,
	ISNULL(BM.Location,'''') AS Location,
	ISNULL(BM.Edition,'''')AS Edition,
	ISNULL(BM.ISBNNumber,'''') AS ISBNNumber,
	ISNULL(BM.Price,0) AS Price,
	ISNULL(BM.Currency,'''') AS Currency,
	ISNULL(BM.BookTag,'''')AS BookTag,
	ISNULL(BM.BookCustomTag,'''') AS BookCustomTag,
	ISNULL(BM.BookDepartment,'''') AS BookDepartment,
	ISNULL(BM.ClassNumber,'''') AS ClassNumber,
	ISNULL(BM.BookVolume,1) AS BookVolume,
	ISNULL(BM.NoOfCopies,1) AS NoOfCopies,
	SM.Title AS StatusName,
	BM.Id,
	ISNULL(AGM.Id,0)AS BookAgeGroupId,
	ISNULL(RTM.Id,0) AS ResourceTypeId,
	BM.CreatedUserId,
	ISNULL(U1.DisplayTitle,'''') AS CreatedUserName ,
	BM.CreatedDateTime,
	ISNULL(BM.UpdatedUserId,0) AS UpdatedUserId,
	ISNULL(U2.DisplayTitle,'''') AS UpdatedUserName ,
	ISNULL(BM.UpdatedDateTime,'''') AS UpdatedDateTime,
	BM.LibraryId,
	ISNULL(LM.Title,'''') AS LibraryName,
	SM.Id AS StatusId,
	BM.ClassificationNo,
	BM.AccessionNo,
	ISNUll(BM.NoOfPages,0) AS NoOfPages,
	 ISNULL(BM.PurchaseDate,''0001/01/01'') AS PurchaseDate,
    ISNUll(BM.BookRemark,'''') AS BookRemark,
    ISNULL(BM.BillNumber,'''') AS BillNumber,
    BM.YearOfPublication,
    ISNULL(BM.BookEntryDate,''0001/01/01'') AS BookEntryDate,
    CASE WHEN ' + convert(varchar,@rShowWithPhotoId) + '= 1 Then ISNULL(BM.BookImage, CONVERT(VARBINARY(MAX), 0)) ELSE BM.BookImage END AS BookPicture,
    ISNULL(BM.BookGroup1Id,0) AS BookGroup1Id,
    ISNULL(BM.BookGroup2Id,0) AS BookGroup2Id,
	ISNULL(BM.OrderIndex,0) AS OrderIndex 
	
	
	
    

	FROM 
         sLibrary.tBookMaster BM
         LEFT JOIN sLibrary.tBookAgeGroupMaster AGM ON BM.BookAgeGroupId=AGM.Id
         INNER JOIN sLibrary.tResourceTypeMaster RTM ON BM.ResourceTypeId=RTM.Id
         INNER JOIN sLibrary.tBookLog BL ON BL.ResourceSourceId = BM.Id AND IsCurrentStatus=1
         INNER JOIN sCommon.tStatusMaster SM ON SM.Id=BL.StatusId 
		 INNER JOIN sLibrary.tLibraryMaster LM ON LM.Id = BM.LibraryId
		 INNER JOIN sSecurity.tUser U1 ON U1.Id = BM.CreatedUserId
		 Left JOIN sSecurity.tUser U2 ON U2.Id = BM.UpdatedUserId
		  
         
         WHERE ((BM.Id = ' + convert(varchar,@lId) + ') OR (' + convert(varchar,@lId) + ' = 0))
	AND ((BM.Code = ''' + @lCode + ''') OR (''' + @lCode + ''' = ''''))
	AND ((BM.Title like N''' + @lTitle + ''') OR (''' + @lTitle + ''' = '''')) 
	AND ((BM.AccessionNo like ''' + @lAccession + ''') OR (''' + @lAccession + ''' = '''')) 
	AND ((BM.Publisher like N''' + @lPublisher + ''') OR (''' + @lPublisher + ''' = '''')) 
	AND ((BM.Supplier like ''' + @lSupplier + ''') OR (''' + @lSupplier + ''' = '''')) 
	AND ((BM.Author like N''' + @lAuthor + ''') OR (''' + @lAuthor + ''' = '''')) 
	AND ((BM.BookSubject like N''' + @lSubject + ''') OR (''' + @lSubject + ''' = ''''))  
	AND ((BM.BookLanguage like N''' + @lLanguage + ''') OR (''' + @lLanguage + ''' = ''''))  
	AND ((BM.Location like ''' + @lLocation + ''') OR (''' + @lLocation + ''' = ''''))  
	AND ((BM.Edition like ''' + @lEdition + ''') OR (''' + @lEdition + ''' = ''''))  
	AND ((BM.ISBNNumber like ''' + @lISBNNumber + ''') OR (''' + @lISBNNumber + ''' = ''''))  
	AND ((BM.BookTag like ''' + @lBookTag + ''') OR ( ''' + @lBookTag + ''' = ''''))
	AND ((BM.BookCustomTag like ''' + @lBookCustomTag + ''') OR (''' + @lBookCustomTag + ''' = ''''))
	AND ((BM.BookAgeGroupId = ' + convert(varchar,@lBookAgeGroupId) + ') OR(' + convert(varchar,@lBookAgeGroupId) + ' = 0))
	AND ((BM.ResourceTypeId = ' + convert(varchar,@lResourceTypeId) + ') OR (' + convert(varchar,@lResourceTypeId) + ' = 0))
	AND ((BM.BookGroup1Id = ' + convert(varchar,@lBookGroup1Id) + ') OR (' + convert(varchar,@lBookGroup1Id) + ' = 0))
	AND ((BM.BookGroup2Id = ' + convert(varchar,@lBookGroup2Id) + ') OR (' + convert(varchar,@lBookGroup2Id) + ' = 0))
	AND ((BM.Price = ' + convert(varchar,@lPrice) + ') OR (' + convert(varchar,@lPrice) + ' = 0))
	AND ((BM.Currency like ''' + @lCurrency + ''') OR (''' + @lCurrency  + ''' = ''''))
	AND ((BL.StatusId = ' + convert(varchar,@lStatusId) + ') OR (' + convert(varchar,@lStatusId) + '=0))
	AND ((BM.BookDepartment like ''' + @lBookDepartment + ''') OR (''' + @lBookDepartment + ''' = ''''))
	AND (BM.LibraryId = ' + convert(varchar,@lLibraryId) +')
	ORDER BY BM.OrderIndex ASC'
	print(@quer);
	exec (@quer)
	

  --FROM 
  --      sLibrary.tBookMaster BM
  --       LEFT JOIN sLibrary.tBookAgeGroupMaster AGM
  --       ON BM.BookAgeGroupId=AGM.Id
  --       INNER JOIN sLibrary.tResourceTypeMaster RTM
  --       ON BM.ResourceTypeId=RTM.Id
  --       INNER JOIN sLibrary.tBookLog BL
  --       ON BL.ResourceSourceId=BM.Id AND IsCurrentStatus=1
  --       INNER JOIN sCommon.tStatusMaster SM
  --       ON SM.Id=BL.StatusId 
        -- WHERE 
  
      --((BM.Id = @rId) OR (@rId = 0))
      --ANd ((BM.Code = @rCode) OR (ISNULL(@rCode,'') = ''))
      -- AND  ((BM.Title like @rTitle) OR (ISNULL(@rTitle,'') = '')) 
      --  AND  ((BM.Publisher like @rPublisher) OR (ISNULL(@rPublisher,'') = '')) 
      --   AND  ((BM.Supplier like @rSupplier) OR (ISNULL(@rSupplier,'') = '')) 
      --    AND  ((BM.Author like @rAuthor) OR (ISNULL(@rAuthor,'') = '')) 
      --     AND  ((BM.BookSubject like @rSubject) OR (ISNULL(@rSubject,'') = ''))  
      --      AND  ((BM.BookLanguage like @rLanguage) OR (ISNULL(@rLanguage,'') = ''))  
      --       AND  ((BM.Location like @rLocation) OR (ISNULL(@rLocation,'') = ''))  
      --        AND  ((BM.Edition like @rEdition) OR (ISNULL(@rEdition,'') = ''))  
      --         AND  ((BM.ISBNNumber like @rISBNNumber) OR (ISNULL(@rISBNNumber,'') = ''))  
      --          AND  ((BM.BookTag like @rBookTag) OR (ISNULL(@rBookTag,'') = ''))
      --           AND  ((BM.BookCustomTag like @rBookCustomTag) OR (ISNULL(@rBookCustomTag,'') = ''))
      --            AND  ((BM.BookAgeGroupId = @rBookAgeGroupId) OR(@rBookAgeGroupId=0))
      --             AND  ((BM.ResourceTypeId = @rResourceTypeId) OR (@rResourceTypeId=0))
      --              AND  ((BM.Price = @rPrice) OR (@rPrice=0))
      --               AND  ((BM.Currency like @rCurrency) OR (ISNULL(@rCurrency,'') = ''))
      --                AND  ((BL.StatusId = @rStatusId) OR (@rStatusId=0))
      --                ANd ((BM.BookDepartment like @rBookDepartment) OR (ISNULL(@rBookDepartment,'') = ''))
						--AND ((BL.OrgId=@rOrgId) OR (@rOrgId=0))
	  --AND BM.LibraryId = @rLibraryId
END
GO
PRINT N'Altering [sMis].[pRptAttendanceSummaryOrgnizationwiseGet]...';


GO

 
ALTER PROCEDURE [sMis].[pRptAttendanceSummaryOrgnizationwiseGet]
	
		@rBuilder1 nvarchar(max)='',
		@rBuilder2 nvarchar(max)='', 
		@rOrgSubGroupId int=0,
		@rOrgId smallint=0,
		@rFromDate Date='',
		@rToDate Date='',
		@rStrOrgSubGroupId nvarchar(max)='',
		@rStrOrgId nvarchar(max)='',
		@rOrgGroupId int=0,
		@rStatusId int=0,
		@rStudentStatusId int=0,
		@rIsTestOrg bit=0,
		@rIsTestSubGroup bit =0,
		@rStrClassId nvarchar(max)='',
		@rStrDivisionId nvarchar(max)=''
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
CREATE TABLE #PresentAbsentCount
(
OrgSubGroupId int,
OrgSubGroupTitle nvarchar(50),
OrgId smallint,
OrgDisplayTitle nvarchar(100),
AcademicId bigint,
PresentCount int,
AbsentCount int,
OrgOrderIndex int ,
ClassId int,
ClassTitle nvarchar(100),
DivisionId int ,
DivisionTitle nvarchar(100),
DepartmentId int ,
DepartmentTitle nvarchar(100)

)

INSERT INTO #PresentAbsentCount
SELECT		
			--OMGM.Id AS OrgMainGroupId,
			--OMGM.Title AS OrgMainGroupTitle,
			OSGM.Id AS OrgSubGroupId,
			OSGM.Title AS OrgSubGroupTitle,
			OM.Id AS OrgId,
			OM.DisplayTitle AS OrgDisplayTitle,
			SR.AcademicId ,
			COUNT(CASE WHEN  SR.IsPresent=1 THEN 1 END)As PresentCount,
			COUNT(CASE WHEN  SR.IsPresent=0 THEN 1 END)As AbsentCount,
			OM.OrderIndex As OrgOrderIndex ,
			CM.Id As ClassId ,
			CM.Title As ClassTitle ,
			DIM.Id As DivisionId ,
			DIM.Title As DivisionTitle,
			DM.Id As DepartmentId,
			DM.Title As DepartmentTitle

			from sAttendance.tStudentRegister SR
			INNER JOIN sStudent.tAcademic A ON SR.AcademicId = A.Id 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId AND (BM.IsActive = @rStatusId OR @rStatusId IS NULL)
			INNER JOIN sStudent.tStudentMaster SM ON SM.Id=A.StudentId
			INNER JOIN sSetup.tOrganizationMaster OM  ON OM.Id=A.OrgId
			INNER JOIN sSetup.tOrgSubGroupMaster OSGM ON OSGM.Id = OM.OrgSubGroupId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId = CM.Id
			INNER JOIN sSetup.tDivisionMaster DIM ON DIM.ClassId = CM.Id And DIM.Id = A.DivisionId
			INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id = CM.DepartmentId
			--INNER JOIN sSetup.tOrgMainGroupMaster OMGM ON OMGM.Id = OSGM.OrgMainGroupId
			WHERE
			AttendanceTypeId = 1
			AND (SR.AttendanceDate >= @rFromDate OR @rFromDate IS NULL)
			AND SR.AttendanceDate <= @rToDate
			AND   ((BM.IsActive =@rStatusId) OR @rStatusId IS NULL)
			AND ((OSGM.Id=@rOrgSubGroupId) OR (@rOrgSubGroupId=0))
			AND ((OM.Id=@rOrgId) OR (@rOrgId=0))
			--AND ((OM.OrgGroupId = @rOrgGroupId))
			AND ((SM.StatusID =@rStudentStatusId) OR (@rStudentStatusId=0))
			AND (OSGM.Id IN (SELECT cast(item as int) FROM  sCommon.fnsplit(@rStrOrgSubGroupId,','))OR @rStrOrgSubGroupId='')
			AND (OM.Id IN (SELECT cast (item as int) FROM  sCommon.fnsplit (@rStrOrgId,','))OR @rStrOrgId='')
			AND (A.ClassId IN (SELECT cast(item as int) FROM  sCommon.fnsplit  (@rStrClassId,','))OR @rStrClassId='') 
			AND (A.DivisionId IN (SELECT cast(item as int) FROM  sCommon.fnsplit  (@rStrDivisionId,','))OR @rStrDivisionId='')
			GROUP BY AcademicId,OSGM.Id,OSGM.Title,OM.Id,OM.DisplayTitle,OM.OrderIndex,CM.Id,CM.Title,DIM.Id,DIM.Title ,  DM.Id,DM.Title

--SELECT * FROM #PresentAbsentCount
CREATE TABLE #PresentAbsentPercentage
(
OrgSubGroupId int,
OrgSubGroupTitle nvarchar(50),
OrgId smallint,
OrgDisplayTitle nvarchar(100),
AcademicId bigint,
Percentage Decimal,
OrgOrderIndex int,
ClassId int,
ClassTitle nvarchar(100),
DivisionId int ,
DivisionTitle nvarchar(100) ,
DepartmentId int ,
DepartmentTitle nvarchar(100)

)

	INSERT INTO #PresentAbsentPercentage
	SELECT OrgSubGroupId,OrgSubGroupTitle,OrgId,OrgDisplayTitle,AcademicId,
	(PresentCount*100)/(PresentCount+AbsentCount),OrgOrderIndex,ClassId,ClassTitle,DivisionId,DivisionTitle,DepartmentId,DepartmentTitle
		FROM #PresentAbsentCount

	--Select * FROM #PresentAbsentPercentage
		SELECT 
		@rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,
		OrgSubGroupId,
		OrgSubGroupTitle,
		OrgId,
		OrgDisplayTitle,
		COUNT(CASE WHEN Percentage > 80 THEN 1 END) AS Greaterthan80,
		COUNT(CASE WHEN Percentage > 70 AND Percentage <=80  THEN 1 END) AS Between7080,
		COUNT(CASE WHEN Percentage > 60 AND Percentage <=70  THEN 1 END) AS Between6070,
		COUNT(CASE WHEN Percentage > 50 AND Percentage <=60  THEN 1 END) AS Between5160,
		COUNT(CASE WHEN Percentage <= 50 THEN 1 END) AS Lessthan50,
		COUNT(CASE WHEN Percentage =100  THEN 1 END) AS Equal100,
		COUNT(CASE WHEN Percentage >= 91 AND Percentage <=99  THEN 1 END) AS Between9199,
		COUNT(CASE WHEN Percentage >= 81 AND Percentage <=90  THEN 1 END) AS Between8190,
		COUNT(CASE WHEN Percentage >= 21 AND Percentage <=50  THEN 1 END) AS Between2150,
		COUNT(CASE WHEN Percentage > 0 AND Percentage <=20  THEN 1 END) AS Between120,
		COUNT(CASE WHEN Percentage <=0  THEN 1 END) AS Equal0,
		OrgOrderIndex,		
		@rIsTestOrg AS IsTestOrg,
		@rIsTestSubGroup AS IsTestSubGroup,
		ClassId,
		ClassTitle,
		DivisionId,
		DivisionTitle ,
		DepartmentId ,
		DepartmentTitle
		FROM #PresentAbsentPercentage 
		GROUP By OrgSubGroupId,OrgSubGroupTitle,OrgId,OrgDisplayTitle,OrgOrderIndex,ClassId,ClassTitle,DivisionId,DivisionTitle ,DepartmentId ,DepartmentTitle
			
		DROP TABLE #PresentAbsentPercentage
		DROP TABLE #PresentAbsentCount



			 -- SELECT 
			 --'' AS Builder1,
			 --'' AS Builder2,
			 --0 AS OrgSubGroupId,
			 --'' AS OrgSubGroupTitle,
			 --0 AS OrgId,
			 --'' AS OrgDisplayTitle,
			 --0 AS Greaterthan80,
			 --0 AS Between7080,
			 --0 AS Between6070,
			 --0 AS Between5160,
			 --0 AS Lessthan50,
			 --0 AS Equal100,
			--0  AS Between9199,
			--0 AS Between8190,
			 --0 AS Between2150,
			 --0 AS Between120,
			 --0 AS Equal0,
			 --0 AS OrgOrderIndex,
			 --0 AS IsTestOrg,
			 --0 AS IsTestSubGroup ,
			 --0 As ClassId ,
			 --'' As ClassTitle ,
			 --0 As DivisionId ,
			 --'' As DivisionTitle ,
			 --0 As DepartmentId ,
			 --'' As DepartmentTitle
END
GO
PRINT N'Altering [sSecurity].[pDashletGet]...';


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

		AND CONVERT(VARCHAR(5),EM.DateOfBirth,110) <= CONVERT(VARCHAR(5),@TimeZoneDate+@BirthdayDays,110) 
		AND CONVERT(VARCHAR(5),EM.DateOfBirth,110) >= CONVERT(VARCHAR(5),@TimeZoneDate,110)
		AND EM.DateOfBirth!='' AND EM.StatusId=7
		ORDER BY CONVERT(VARCHAR(5),EM.DateOfBirth,110)
		
        END
 if(@rDashletId='7')
        BEGIN
        SELECT SC.FirstName + ' ' + SC.MiddleName + ' ' + SC.LastName AS Name, SC.ClassName+' '+SC.DivisionName AS ClassName FROM sStudent.vStudentAllDetail SC WHERE SC.OrgId=@rOrgId AND SC.BatchId=@rBatchId
         AND (MONTH(SC.DateOfBirth) = CAST(MONTH(@TimeZoneDate) AS varchar(2))) AND SC.DateOfBirth!='' AND SC.StatusId=1
	    AND (DAY(SC.DateOfBirth) = CAST(DAY(@TimeZoneDate) AS varchar(2)))   
        END
         if(@rDashletId='10')
        BEGIN
       exec sAttendance.pDashletAttendanceStatusGet @rAcademicId=@rSourceId
        END
   
   if(@rDashletId='11')
        BEGIN
       SELECT EM.EmployeeName,L.FromDate,L.ToDate FROM  sHrm.tLeave L 
        INNER JOIN sSetup.tBatchMaster BM ON BM.Id = L.BatchId	
        INNER JOIN sHrm.vEmployeeCommonDetail EM ON EM.EmployeeId = L.EmployeeId
        INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = L.EmployeeId
         WHERE  
			   BM.OrgGroupBatchId = @rOrgGroupBatchId
			   AND L.OrgId = @rOrgId
			   AND (EJD.EmployeeManagerId = @rUserSourceId OR @rUserSourceId = 0)
			   AND ((L.FromDate >= @rDate) OR (ISNULL(@rDate,'') = ''))
			   AND EM.EmployeeStatusId=7
             
       -- exec [sHrm].[pLeaveListingGet] @rOrgId=@rOrgId,@rEmployeeId=@rUserSourceId,@rLeaveTypeId=0,@rOrgGroupBatchId=@rOrgGroupBatchId,@rFromDate=@rDate,@rTodate=''
        END
   if(@rDashletId='12')
        BEGIN
     exec sCommunication.pPollGet @rOrgGroupBatchId=@rOrgGroupBatchId,@rSourceTypeId=@rUserSourceTypeId,@rCreatedUserId=@rUserId,@rCreatedDateTime=@rDate
        END
  if(@rDashletId='14')
       BEGIN
        exec sCommunication.pMyBookGet @rReaderSourceTypeId=@rUserSourceTypeId,@rReaderSourceId=@rUserSourceId,@rBatchId=@rBatchId,@rStatusId=@rStatusId

        END
  if(@rDashletId='16')
        BEGIN
      exec [sFee].[pRptFeeReceiptTotalGet] @rFromDate=@rDate,@rToDate=@rDate,@rOrgGroupBatchId=@rOrgGroupBatchId
        END
      
  if(@rDashletId='17')
        BEGIN
      exec [sFee].[pFeeDueAlertGet] @rSourceId=@rSourceId,@rSourceTypeId=@rSourceTypeId,@rBatchId=@rBatchId

        END
  if(@rDashletId='18')
        BEGIN
     exec sCommunication.pBlogGet @rId=0,@rOrgGroupBatchId=@rOrgGroupBatchId,@rTitle=NULL,@rCreatedUserId=0,@rOrgId=@rOrgId,@rCreatedDateTime=@rDate
        END
 if(@rDashletId='19')
        BEGIN
     exec sAssessment.pStudentResultGet @rAcademicId=@rSourceId,@rStudentId=@rUserSourceId,@rBatchId=@rBatchId,@rExamId=@rExamId
     END
  if(@rDashletId='21')
       BEGIN
       SELECT vCD.ClassDivisionName,ISNULL(EM.FirstName+' '+ EM.LastName,'') AS ClassTeacherName,
	   CASE WHEN COUNT(SR.AcademicId)=0 THEN CASE WHEN (Select [sCommon].[fCountAbsentStudent](A.DivisionId,  @rBatchId,@rDate,1,0)) =0 THEN 'Pending' ELSE 'Complete' END ELSE 'Complete' END AS PresentStatus
        FROM sStudent.tAcademic A INNER JOIN sSetup.vClassDivision vCD ON vCD.ClassId=A.ClassId 
       AND vCD.DivisionId=A.DivisionId AND A.OrgId=vCD.OrgId AND A.OrgId=@rOrgId  AND A.BatchId=@rBatchId AND vCD.IsObsolete=0 
       INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = vCD.DivisionId LEFT JOIN sHrm.tEmployeeMaster EM ON EM.Id = DM.InchargeEmployeeId 
       LEFT JOIN sAttendance.tStudentRegister SR ON A.Id = SR.AcademicId AND SR.AttendanceTypeId = 1 
       AND SR.IsPresent=1 AND SR.AttendanceDate=@rDate GROUP BY A.DivisionId,A.BatchId,vCD.ClassDivisionName,vCD.OrderIndex,EM.FirstName,EM.LastName ORDER BY vCD.OrderIndex
         END
  if(@rDashletId='22')
       BEGIN
        SELECT VL.Id,VL.VisitorName, VL.NoOfVisitor,  (isnull(case when isnull(VL.WhomToMeet,0)!=0 then isnull(EM.EmployeeName,'') else ISNULL(VL.WhomToMeetName,'') end,'' )) AS WhomToMeetName
		FROM sFrontOffice.tVisitorLog VL  
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=VL.OrgId 
		 LEFT JOIN sHrm.vExtEmployeeMaster EM ON EM.EmployeeId=VL.WhomToMeet
        WHERE VL.OrgId=@rOrgId AND VL.VisitDate=@rDate ORDER BY VL.VisitDate DESC,VL.InTime DESC
        END
  if(@rDashletId='23')
       BEGIN
        SELECT DispatchedTo, DispatchedCity  FROM sFrontOffice.tCourierDispatch  WHERE OrgGroupId=@rOrgGroupId AND DispatchDate=@rDate  AND @rDashletId='23' ORDER BY DispatchDate
        END
    if(@rDashletId='24')
       BEGIN
        SELECT ReceiveFrom, ReceiveFor  FROM  sFrontOffice.tCourierReceive  WHERE OrgGroupId=@rOrgGroupId  AND ReceiveDate=@rDate  AND @rDashletId='24' ORDER BY ReceiveDate
    END
     if(@rDashletId='25')
        BEGIN
     SELECT ISNULL(Ps.LectureNumber,'') AS LactureNumber,PS.EmployeeId,ISNULL(SMT.Title,'') AS Subject,ISNULL(EM1.FirstName,'') + ' '+ISNULL(EM1.LastName,'') AS EmployeeName,ISNULL(Em.FirstName,'') + ' '+ISNULL(Em.LastName,'') AS ProxyEmployeeName, ISNULL(DV.Code,'') AS ClassDivisionName,ISNULL(SM.Title,'') AS ProxySubject from sTimetable.tProxySetting PS 
     INNER JOIN sSetup.tSubjectMaster SM ON SM.Id = PS.SubjectId INNER JOIN sCommon.tDayMaster DM ON DM.Id = PS.DayId INNER JOIN sSetup.tDivisionMaster DV ON DV.Id = PS.DivisionId
     INNER JOIN sTimetable.tTimeTable TT ON TT.Id=PS.TimeTableId 
     INNER JOIN sSetup.tSubjectMaster SMT ON SMT.Id = TT.SubjectId 
     INNER JOIN sHrm.tEmployeeMaster EM1  ON TT.EmployeeId=EM1.Id 
     INNER JOIN sHrm.tEmployeeMaster Em ON Em.Id = PS.EmployeeId  WHERE PS.ProxyDate=@rDate AND PS.BatchId=@rBatchId AND ((PS.EmployeeId=@rSourceId) OR (@rSourceId=0))  ORDER BY PS.ProxyDate
        END
        
        if(@rDashletId='27')
        BEGIN
     --Asset Check
		SELECT LM.Title AS LocationName, AM.Code AS AssetCode, AM.Title AS AssetName, CONVERT(nvarchar(12),AM.CheckedLastDate,103) AS CheckedLastDate
        FROM sAssetManagement.tAssetMaster AM INNER JOIN sAssetManagement.tAssetInchargeUser AU ON AM.Id = AU.AssetId 
        INNER JOIN sFixedAsset.tLocationMaster LM ON LM.Id = AM.LocationId 
        WHERE ISNULL(AM.IsCheckRequired,0) = 1 AND (AM.CheckFrequencyId=1 AND AM.CheckedLastDate <=  DATEADD(dd,1,@TimeZoneDate) OR AM.CheckFrequencyId=2 AND AM.CheckedLastDate <=  DATEADD(dd,7,@TimeZoneDate) OR AM.CheckFrequencyId=3 AND AM.CheckedLastDate <= DATEADD(dd,30,@TimeZoneDate))
        AND AU.InchargeUserId =   @rUserId AND AM.OrgGroupId = @rOrgGroupId
     
     
     
  --      SELECT LM.Title AS LocationName, AM.Code AS AssetCode, AM.Title AS AssetName,CONVERT(nvarchar(12),
		--AM.LastMaintenanceDate,103) AS LastMaintenanceDate,CONVERT(nvarchar(12),AM.NextMaintenanceDate,103) AS NextMaintenanceDate
		--FROM sAssetManagement.tAssetMaster AM 
		--INNER JOIN sAssetManagement.tAssetInchargeUser AU ON AM.Id = AU.AssetId 
		--INNER JOIN sFixedAsset.tLocationMaster LM ON LM.Id = AM.LocationId
		-- WHERE AU.InchargeUserId = @rUserId AND AM.OrgGroupId = @rOrgGroupId
		 END
		if(@rDashletId='28')
        BEGIN
     --Asset maintenance
			 SELECT LM.Title AS LocationName, AM.Code AS AssetCode, AM.Title AS AssetName,CONVERT(nvarchar(12),
			 AM.LastMaintenanceDate,103) AS LastMaintenanceDate,CONVERT(nvarchar(12),AM.NextMaintenanceDate,103) AS NextMaintenanceDate 
             FROM sAssetManagement.tAssetMaster AM 
             INNER JOIN sAssetManagement.tAssetInchargeUser AU ON AM.Id = AU.AssetId 
             INNER JOIN sFixedAsset.tLocationMaster LM ON LM.Id = AM.LocationId 
                                WHERE AU.InchargeUserId =@rUserId  AND AM.OrgGroupId = @rOrgGroupId
		 END
		if(@rDashletId='29')
        BEGIN
     --Asset Renew
        SELECT LM.Title AS LocationName, AM.Code AS AssetCode, AM.Title AS AssetName, CONVERT(nvarchar(12),
         AM.RenewLastDate,103) AS RenewLastDate, CONVERT(nvarchar(12), AM.RenewNextDate,103) AS RenewNextDate
           FROM sAssetManagement.tAssetMaster AM INNER JOIN sAssetManagement.tAssetInchargeUser AU ON AM.Id = AU.AssetId 
           INNER JOIN sFixedAsset.tLocationMaster LM ON LM.Id = AM.LocationId 
            WHERE ISNULL(AM.IsRenewRequired,0) = 1
            -- AND AM.RenewNextDate >= DATEADD(dd,ISNULL(AM.RenewAlertBeforeDays,0),AM.RenewLastDate) 
             AND convert(Date,@TimeZoneDate) >=  DATEADD(dd,-ISNULL(AM.RenewAlertBeforeDays,0), AM.RenewNextDate)
                           AND AU.InchargeUserId =  @rUserId  AND AM.OrgGroupId = @rOrgGroupId
        END
        --Inward
       IF(@rDashletId='30')
        BEGIN
        DECLARE @InwardRegisterGrid VARCHAR(max)=''
        SELECT  @InwardRegisterGrid = @InwardRegisterGrid + '<tr>
	       <td align="left" scope="col">' + ISNULL(LetterNumber,'') + '</td>
	       <td align="left" scope="col">' + ISNULL(LetterSubject,'') + '</td>
	       <td align="left" scope="col">' + ISNULL(LetterFrom,'') + '</td>
	       <td align="left" scope="col">' + convert(varchar,isnull(ReceivedDate,'01/01/0001'),103) + '</td>
	 	</tr>'		
	 	FROM
	 	 sFrontOffice.tInwardRegister
	 	 WHERE IsReplyRequired=1 AND IsReplied=0 AND OrgId=@rOrgId
	 	 AND ReceivedDate<=convert(Date,@TimeZoneDate)
		 Order by ReceivedDate Desc

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

	   SELECT Isnull(@OutwardRegisterGrid,'') As	OutwardRegisterGrid
	   END
	   
	   IF(@rDashletId='32')
        BEGIN
        DECLARE @ReorderQuantityGrid VARCHAR(max)=''
        SELECT   @ReorderQuantityGrid=@ReorderQuantityGrid+'<tr>
		     <td align="left" scope="col">' + ISNULL(SE.Title,'')  + '</td>
	        <td align="left" scope="col">' +ISNULL(SM.Title,'')  + '</td>
	      <td align="left" scope="col">' +convert(varchar,ISNULL(SUM(SB.AvailableQuantity),0))+ '</td>
	       <td align="left" scope="col">' + convert(varchar,isnull(SP.ReOrderQuantity,0)) + '</td>
	 	 </tr>'	
	 	FROM
	 	 sProcurement.tStockBatch SB
	 	  INNER JOIN sIp.tStockItemMaster SM ON SM.Id=SB.STockItemID
	 	 INNER JOIN sIp.tStoreLocationMaster SE ON SE.Id=SB.StoreLocationId
	 	 INNER JOIN sIp.tStockItemPlanning SP ON SP.STockItemID=SM.Id AND SP.StoreLocationId =SE.Id
	 	 --INNER JOIN  sSecurity.tUserLocation UL ON UL.StoreLocationId = SB.StoreLocationId
	 	 WHERE  SM.OrgGroupId=@rOrgGroupId AND SM.IsObsolete=0 
	 	 group by SE.Title,SM.Title,SP.ReOrderQuantity,SP.ReOrderPoint
	 	 HAVING SUM(SB.AvailableQuantity) < SP.ReOrderPoint
	   
		SELECT Isnull(@ReorderQuantityGrid,'') As	ReorderQuantityGrid
		END
		
		 IF(@rDashletId='33')
        BEGIN
        DECLARE @SafetyStockGrid VARCHAR(max)=''
        SELECT   @SafetyStockGrid=@SafetyStockGrid+'<tr>
		     <td align="left" scope="col">' + ISNULL(SE.Title,'')  + '</td>
	        <td align="left" scope="col">' +ISNULL(SM.Title,'')  + '</td>
	      <td align="left" scope="col">' +convert(varchar,ISNULL(SUM(SB.AvailableQuantity),0))+ '</td>
	       <td align="left" scope="col">' + convert(varchar,isnull(SP.SafetyStock,0)) + '</td>
	 	 </tr>'	
	 	FROM
	 	 sProcurement.tStockBatch SB
	 	  INNER JOIN sIp.tStockItemMaster SM ON SM.Id=SB.STockItemID
	 	 INNER JOIN sIp.tStoreLocationMaster SE ON SE.Id=SB.StoreLocationId
	 	 INNER JOIN sIp.tStockItemPlanning SP ON SP.STockItemID=SM.Id AND SP.StoreLocationId =SE.Id
	 	 --INNER JOIN  sSecurity.tUserLocation UL ON UL.StoreLocationId = SB.StoreLocationId
	 	 WHERE  SM.OrgGroupId=@rOrgGroupId AND SM.IsObsolete=0 
	 	 group by SE.Title,SM.Title,SP.SafetyStock,SP.ReOrderPoint
	 	 HAVING SUM(SB.AvailableQuantity) < SP.SafetyStock
	   
		SELECT Isnull(@SafetyStockGrid,'') As	SafetyStockGrid
        END
		 IF(@rDashletId='34')
		 BEGIN 
		 DECLARE @Increment varchar(max)=''
		 SELECT @Increment=@Increment+'<tr>
		  <td align="left" scope="col">' + ISNULL(EM.FirstName,'') + ' '+ISNULL(EM.LastName,'') + '</td>
	        <td align="left" scope="col">' +convert(varchar,isnull(IncrementDate,'01/01/0001'),103)  + '</td></tr>'
		FROM sHrm.tEmployeeStatutoryAndOther SA
		INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id=SA.EmployeeId
		WHERE IncrementDate BETWEEN GETDATE()-1 AND GETDATE()+7
		AND EM.OrgID=@rOrgId And EM.StatusId=7
		SELECT Isnull(@Increment, '') As	IncrementGrid
		END
		
			 IF(@rDashletId='78')
		 BEGIN 
		 DECLARE @Retirement varchar(max)=''
		 SELECT @Retirement=@Retirement+'<tr>
		  <td align="left" scope="col">' + ISNULL(EM.FirstName,'') + ' '+ISNULL(EM.LastName,'') + '</td>
	        <td align="left" scope="col">' +convert(varchar,isnull(RetirementDate,'01/01/0001'),103)  + '</td></tr>'
		FROM sHrm.tEmployeeStatutoryAndOther SA
		INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id=SA.EmployeeId
		WHERE RetirementDate BETWEEN GETDATE()-1 AND GETDATE()+30
		AND EM.OrgID=@rOrgId And EM.StatusId=7
		SELECT Isnull(@Retirement, '') As RetirementGrid
		END

	if(@rDashletId='83')
        BEGIN
			SELECT SA.Name,L.LeaveFromDate,L.LeaveToDate 
			FROM  sAttendance.tStudentLeaveRequest L   
			INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId = L.AcademicId  
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId    
			WHERE  
				 SA.BatchId = @rBatchId
				AND SA.OrgId = @rOrgId
				AND ((L.LeaveFromDate <= @rDate) OR (ISNULL(@rDate,'') = ''))
				AND ((L.LeaveToDate >= @rDate) OR (ISNULL(@rDate,'') = ''))
				AND SA.StatusId=1
		END
  END
GO
PRINT N'Altering [sSecurity].[pTraceabilityTrackAdd]...';


GO
ALTER PROCEDURE [sSecurity].[pTraceabilityTrackAdd]

@rScreenId int,
@rTraceabilityId int,
@rTraceabilitySourceId int

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
IF EXISTS(Select 1 from sSecurity.tTraceabilityTrack WHERE ScreenId = @rScreenId AND TraceabilityId=@rTraceabilityId AND TraceabilitySourceId=@rTraceabilitySourceId)
BEGIN
	    SELECT -103 AS Result
		RETURN
END

BEGIN TRANSACTION
BEGIN
	INSERT INTO 
		sSecurity.tTraceabilityTrack
		VALUES
		(@rScreenId,
		@rTraceabilityId,
		@rTraceabilitySourceId)
        SELECT 1 AS Result
		END
COMMIT TRANSACTION		
--END TRY
--BEGIN CATCH 
--ROLLBACK TRANSACTION
--		SELECT -1 AS Result
--		RETURN
--	END CATCH
END
GO
PRINT N'Altering [sSetup].[pHistoryTransfer]...';


GO
 
 
ALTER PROCEDURE [sSetup].[pHistoryTransfer]
	 @rType smallint = 0,
	 @rDate date = ''
	 	 	 
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN
BEGIN TRY
		BEGIN TRANSACTION 
	IF(@rType = 1) -- Copy To History Table
	BEGIN

	INSERT INTO [sAlert].[tAlertLogHistory] SELECT * FROM [sAlert].[tAlertLog] WHERE CAST(CreatedDateTime AS DATE) < @rDate
	DELETE FROM [sAlert].[tAlertLog] WHERE CAST(CreatedDateTime AS DATE) < @rDate

	INSERT INTO [sAlert].[tNotificationLogHistory] SELECT * FROM [sAlert].[tNotificationLog] WHERE CAST(CreatedDateTime AS DATE) < @rDate
	DELETE FROM [sAlert].[tNotificationLog] WHERE CAST(CreatedDateTime AS DATE) < @rDate

	INSERT INTO [sAlert].[tWhatsAppLogHistory] SELECT * FROM [sAlert].[tWhatsAppLog] WHERE CAST(CreatedDateTime AS DATE) < @rDate
	DELETE FROM [sAlert].[tWhatsAppLog] WHERE CAST(CreatedDateTime AS DATE) < @rDate

	INSERT INTO [sAudit].[tActivityLogHistory] SELECT * FROM [sAudit].[tActivityLog] WHERE CAST(AuditDate AS DATE) < @rDate
	DELETE FROM [sAudit].[tActivityLog] WHERE CAST(AuditDate AS DATE) < @rDate

	--INSERT INTO [sAudit].[tOperationLogHistory] SELECT * FROM [sAudit].[tOperationLog] WHERE CAST(CreatedDateTime AS DATE) < @rDate
	--DELETE FROM [sAudit].[tOperationLog] WHERE CAST(CreatedDateTime AS DATE) < @rDate

	--INSERT INTO [sHrm].[tLeaveBalanceLogHistory] SELECT * FROM [sHrm].[tLeaveBalanceLog] WHERE CAST(CreatedDateTime AS DATE) < @rDate
	--DELETE FROM [sHrm].[tLeaveBalanceLog] WHERE CAST(CreatedDateTime AS DATE) < @rDate

	--INSERT INTO [sLibrary].[tBookLogHistory] SELECT * FROM [sLibrary].[tBookLog] WHERE CAST(CreatedDateTime AS DATE) < @rDate
	--DELETE FROM [sLibrary].[tBookLog] WHERE CAST(CreatedDateTime AS DATE) < @rDate

	--INSERT INTO [sRecruitment].[tRecruitmentStatusLogHistory] SELECT * FROM [sRecruitment].[tRecruitmentStatusLog] WHERE CAST(CreatedDateTime AS DATE) < @rDate
	--DELETE FROM [sRecruitment].[tRecruitmentStatusLog] WHERE CAST(CreatedDateTime AS DATE) < @rDate

	INSERT INTO [sSecurity].[tUserLogHistory] SELECT * FROM [sSecurity].[tUserLog] WHERE CAST(LoggedInDateTime AS DATE) < @rDate
	DELETE FROM [sSecurity].[tUserLog] WHERE CAST(LoggedInDateTime AS DATE) < @rDate

	INSERT INTO [sSystem].[tBackupLogHistory] SELECT * FROM [sSystem].[tBackupLog] WHERE CAST(BackupDateTime AS DATE) < @rDate
	DELETE FROM [sSystem].[tBackupLog] WHERE CAST(BackupDateTime AS DATE) < @rDate

	INSERT INTO [sAcademic].[tClassworkViewHistory] SELECT * FROM [sAcademic].[tClassworkView] WHERE CAST(ViewByDateTime AS DATE) < @rDate
	DELETE FROM [sAcademic].[tClassworkView] WHERE CAST(ViewByDateTime AS DATE) < @rDate

	INSERT INTO [sAcademic].[tOnlineLearningViewHistory] (OnlineLearningId,AcademicId,IsViewReference,IsViewAssignment,IsViewResource,ViewByUserId,LastViewByDateTime,AssignmentTeacherRemark) SELECT OnlineLearningId,AcademicId,IsViewReference,IsViewAssignment,IsViewResource,ViewByUserId,LastViewByDateTime,AssignmentTeacherRemark FROM [sAcademic].[tOnlineLearningView] WHERE CAST(LastViewByDateTime AS DATE) < @rDate
	DELETE FROM [sAcademic].[tOnlineLearningView] WHERE CAST(LastViewByDateTime AS DATE) < @rDate

	INSERT INTO  [sCommunication].[tAssignmentViewHistory] SELECT * FROM [sCommunication].[tAssignmentView] WHERE CAST(ViewByDateTime AS DATE) < @rDate
	DELETE FROM [sCommunication].[tAssignmentView] WHERE CAST(ViewByDateTime AS DATE) < @rDate

	INSERT INTO  [sCommunication].[tCircularViewHistory] SELECT * FROM [sCommunication].[tCircularView] WHERE CAST(ViewByDateTime AS DATE) < @rDate
	DELETE FROM [sCommunication].[tCircularView] WHERE CAST(ViewByDateTime AS DATE) < @rDate

	--exec [sAcademic].[pOnlineLearningMigrateToHistoryAdd] @rDate
	
	SELECT 1 AS MSG
	END
	ELSE IF(@rType = 2) -- Delete From Exception Table
	BEGIN 
		DELETE FROM [sSystem].[tExceptionLog] WHERE CAST(CreatedDateTime AS DATE) < @rDate
		SELECT 1 AS MSG
	END
	COMMIT TRANSACTION			 
	END TRY
	
	BEGIN CATCH 
		SELECT ERROR_MESSAGE() AS MSG
		ROLLBACK TRANSACTION		
	END CATCH	
END
GO
PRINT N'Altering [sStudent].[pIDRegisterGet]...';


GO
ALTER PROCEDURE [sStudent].[pIDRegisterGet]   
	@rClassId int=0,
	@rDivisionId int=0,
	@rRollNo int=NULL,
	@rOrgId int=0,
	@rBatchId int=0,
	@rFromCode nvarchar(20)='',
	@rToCode nvarchar(20)='',
	@rStatusId smallint=0,
	@rFirstName nvarchar(100)='',
	@rMiddleName nvarchar(100)='',
	@rLastName nvarchar(100)='',
	@rOrgGroupBatchId int=0,
	@rDepartmentId int=0,
	@rBatchStatusId smallint=0,
	@rSUId nvarchar(50)=''

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	BEGIN
	DECLARE @lConfigValue nvarchar(50)=''
	SELECT @lConfigValue = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 104 AND SourceTypeId = 1016 AND SourceId = @rOrgId

		SET @rFirstName = sCommon.fSearchStringGet(@rFirstName)
		SET @rMiddleName = sCommon.fSearchStringGet(@rMiddleName)
		SET @rLastName = sCommon.fSearchStringGet(@rLastName)
	END
	IF(@lConfigValue = 'True')
	BEGIN
		SELECT 
			ISNULL(A.Id,0) AS AcademicId,	  
			ISNULL(A.ClassId,0) AS ClassId,
			ISNULL(A.DivisionId,0) AS DivisionId,
			ISNULL(A.RollNo,0) AS RollNo,
			ISNULL(A.OrgId,0) AS OrgId,
			ISNULL(A.BatchId,0) AS BatchId,
			SM.Id AS StudentId,
			ISNULL(SM.Code,'') AS Code,
			ISNULL(SM.Number,0) AS Number,
			ISNULL(SM.RegistrationNumber,0) AS RegistrationNumber,
			ISNULL(SM.FirstName,'') AS FirstName,
			ISNULL(SM.MiddleName,'') AS MiddleName,
			ISNULL(SM.LastName,'') AS LastName,
			[sStudent].[fStudentNameGet](SM.FirstName , SM.MiddleName, SM.LastName,OM.StudentNameFormatId ) AS Name,
			Convert(Nvarchar(20),A.RollNo) + '-' + SM.FirstName+' '+SM.LastName AS RollNoName,	  
			ISNULL(SM.StatusId,0) AS StatusId,
			ISNULL(CM.DisplayTitle,'')  AS ClassName,
			ISNULL(DM.DisplayTitle,'') AS DivisionName,
			ISNULL(CM.DisplayTitle +'-'+DM.DisplayTitle,'') AS ClassDivision,
			ISNULL(STM.Title,'') AS StatusName,	  
			ISNULL(SM.RecordStatusId,0) AS RecordStatusId,	  
			ISNULL(DM.InchargeEmployeeId,0) AS InchargeEmployeeId, 
			ISNULL(BM.OrgGroupBatchId,0) AS OrgGroupBatchId,	  
			--SM.AdmissionCategoryId,
			ISNULL(A.AdmissionCategoryId,0) AS AdmissionCategoryId,
			DM.OrderIndex DivisionOrder,
			ISNULL(BM.IsActive,0) AS IsActiveBatch,
			ISNULL(BM.Title,'') AS BatchName,
			ISNULL(DeptM.Id,0) AS DepartmentId,
			ISNULL(DeptM.Title,'') AS DepartmentName,
			ISNULL(SM.IsBlackList,0) AS IsBlackList,
			ISNULL(SM.BlackListReason,'') BlackListReason,
			CM.OrderIndex AS ClassOrderIndex,
			ISNULL(A.ExemptionTypeId,0) AS ExemptionTypeId,
			ISNULL(OM.DisplayTitle,'')  AS DisplayTitle,
			ISNULL(OM.StreetOne,'') AS StreetOne,
			ISNULL(OM.StreetTwo,'') AS StreetTwo,
			ISNULL(OM.StreetThree,'') AS StreetThree,
			ISNULL(OM.ZipCode,'') AS ZipCode,
			ISNULL(SM.SUId,'') AS SUId ,
			ISNULL(OM.ReportOrgGroupTitle,'') AS ReportOrgGroupTitle,
			ISNULL(OM.ReportOrgTitle,'') AS ReportOrgTitle,
			ISNULL(SC.ParentContactNo,'') AS ParentContactNo,
			ISNULL(SC.StudentContactNo,'') AS StudentContactNo,
			ISNULL(SD.StatusName,'') AS StatusName,
			ISNULL(SD.StatusId,0) AS StatusId,
			ISNULL(SD.LCProgress,'') AS LCProgress,
			ISNULL(SD.Religion,'') AS Religion,
			ISNULL(SD.FamilyCast,'') AS FamilyCast,
			ISNULL(SD.FamilySubCast,'') AS FamilySubCast,
			ISNULL(SD.LCConduct,'') AS LCConduct,
			ISNULL(SD.BirthPlace,'') AS BirthPlace,
			ISNULL(SD.BirthTaluka,'') AS BirthTaluka,
			ISNULL(SD.BirthDistrict,'') AS BirthDistrict,
			ISNULL(SD.LeftDate,'') AS LeftDate,
			ISNULL(SD.PreviousSchool,'') AS PreviousSchool,
			ISNULL(SD.DateOfBirth,'') AS DateOfBirth,
			ISNULL(SD.BirthDateInWord,'') AS BirthDateInWord,
			ISNULL(SD.LeftReason,'') AS LeftReason,
			ISNULL(SD.AdmissionDate,'') AS AdmissionDate,
			ISNULL(SD.AdmissionStandard,'') AS AdmissionStandard,
			ISNULL(SD.LeftStandard,'') AS LeftStandard,
			ISNULL(SD.LCNumber,0) AS LCNumber,
			ISNULL(SD.LCDate,'') AS LCDate,
			ISNULL(SD.StudentPhoto,0x) AS StudentPhoto,
			ISNULL(SD.BloodGroup,'') AS BloodGroup,
			ISNULL(SD.PresentAddress,'') AS PresentAddress,
			ISNULL(SD.ContactNo,0) AS ContactNo,
			ISNULL(SD.Batch,'') AS Batch,
			ISNULL(SD.InactiveDate,'') AS InactiveDate,
			ISNULL(OM.Title,'') AS OrgName,
			ISNULL(SF.MotherName,'') AS MotherName,
			ISNULL(SD.DivisionOrder,0) AS DivisionOrder,
			ISNULL(SD.Number,'') AS StudentNumber,
			ISNULL(SF.FatherName,'') AS FatherName,
			ISNULL(SD.Nationality,'') AS Nationality,
			ISNULL(SD.MotherTongue,'') AS MotherTongue,
			ISNULL(SD.BirthState,'') AS BirthState,
			ISNULL(SD.BirthCountry,'') AS BirthCountry,
			ISNULL(SD.SUId,0) AS SUId,
            ISNULL(SD.AdhaarNumber,0) AS AdhaarNumber,
            ISNULL(SD.ClassStatusId,0) AS ClassStatusId,
            ISNULL(SD.ClassStatusName,'') AS ClassStatusName


		FROM 
				(
SELECT Id 
FROM (select A.ID,
             ROW_NUMBER() over (partition by studentId ORDER BY BM.OrderIndex DESC) as MAX_ID
      from sStudent.tAcademic A INNER JOIN sSetup.tBatchMaster BM ON A.BatchId = BM.Id
      ) x
WHERE MAX_ID = 1	
) LA INNER JOIN sStudent.tAcademic A ON LA.Id = A.Id
			
			INNER JOIN sStudent.vStudentAllDetail SD ON SD.AcademicId = A.Id
	LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId=SD.StudentId
			INNER JOIN sStudent.tStudentMaster SM
			ON A.StudentId=SM.Id	
			INNER JOIN sSetup.tClassMaster CM
			ON CM.Id=A.ClassId
			INNER JOIN sSetup.tDivisionMaster DM
			ON DM.Id=A.DivisionId
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId 
			INNER JOIN sStudent.tStatusMaster STM
			ON STM.Id=SM.StatusId
			INNER JOIN sSetup.tDepartmentMaster DeptM
			ON DeptM.Id=CM.DepartmentId
			INNER JOIN sSetup.tOrganizationMaster OM 
			ON SM.OrgId = OM.Id
			LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId = SM.Id
		WHERE 
			((A.ClassId=@rClassId)OR(@rClassId=0))
			AND((A.DivisionId=@rDivisionId)OR(@rDivisionId=0))
			--AND ((SM.Code >= CASE WHEN @lConfigValue ='FALSE' THEN CONVERT(int,@rFromCode) ELSE @rFromCode END) 
			--	OR (CASE WHEN @lConfigValue ='FALSE' THEN @rFromCode)
			AND((SM.Code >= @rFromCode) OR (ISNULL(@rFromCode,'') = '')) 
			AND((SM.Code <= @rToCode) OR (ISNULL(@rToCode,'') = '')) 
			AND((SM.FirstName like @rFirstName) OR (ISNULL(@rFirstName,'') = '')) 
			AND((SM.MiddleName like @rMiddleName) OR (ISNULL(@rMiddleName,'') = ''))
			AND((SM.LastName like @rLastName) OR (ISNULL(@rLastName,'') = '')) 
			AND((STM.Id=@rStatusId)OR(@rStatusId=0))	
			AND((A.BatchId=@rBatchId)OR(@rBatchId=0))	
			AND((OM.Id=@rOrgId)OR(@rOrgId=0))
			AND (BM.OrgGroupBatchId = @rOrgGroupBatchId OR @rOrgGroupBatchId = 0)
			AND((DeptM.Id=@rDepartmentId)OR(@rDepartmentId=0))
			AND((A.RollNo=@rRollNo)OR(@rRollNo=0))	
			AND((SM.SUId= @rSUId) OR (ISNULL(@rSUId,'') = '')) 
			ORDER BY SM.Number
	END
	ELSE
	BEGIN
			SELECT 
			ISNULL(A.Id,0) AS AcademicId,	  
			ISNULL(A.ClassId,0) AS ClassId,
			ISNULL(A.DivisionId,0) AS DivisionId,
			ISNULL(A.RollNo,0) AS RollNo,
			ISNULL(A.OrgId,0) AS OrgId,
			ISNULL(A.BatchId,0) AS BatchId,
			SM.Id AS StudentId,
			ISNULL(SM.Code,'') AS Code,
			ISNULL(SM.Number,0) AS Number,
			ISNULL(SM.RegistrationNumber,0) AS RegistrationNumber,
			ISNULL(SM.FirstName,'') AS FirstName,
			ISNULL(SM.MiddleName,'') AS MiddleName,
			ISNULL(SM.LastName,'') AS LastName,
			[sStudent].[fStudentNameGet](SM.FirstName , SM.MiddleName, SM.LastName,OM.StudentNameFormatId ) AS Name,
			Convert(Nvarchar(20),A.RollNo) + '-' + SM.FirstName+' '+SM.LastName AS RollNoName,	  
			ISNULL(SM.StatusId,0) AS StatusId,
			ISNULL(CM.DisplayTitle,'')  AS ClassName,
			ISNULL(DM.DisplayTitle,'') AS DivisionName,
			ISNULL(CM.DisplayTitle +'-'+DM.DisplayTitle,'') AS ClassDivision,
			ISNULL(STM.Title,'') AS StatusName,	  
			ISNULL(SM.RecordStatusId,0) AS RecordStatusId,	  
			ISNULL(DM.InchargeEmployeeId,0) AS InchargeEmployeeId, 
			ISNULL(BM.OrgGroupBatchId,0) AS OrgGroupBatchId,	  
			--SM.AdmissionCategoryId,
			ISNULL(A.AdmissionCategoryId,0) AS AdmissionCategoryId,
			DM.OrderIndex DivisionOrder,
			ISNULL(BM.IsActive,0) AS IsActiveBatch,
			ISNULL(BM.Title,'') AS BatchName,
			ISNULL(DeptM.Id,0) AS DepartmentId,
			ISNULL(DeptM.Title,'') AS DepartmentName,
			ISNULL(SM.IsBlackList,0) AS IsBlackList,
			ISNULL(SM.BlackListReason,'') BlackListReason,
			CM.OrderIndex AS ClassOrderIndex,
			ISNULL(A.ExemptionTypeId,0) AS ExemptionTypeId,
			ISNULL(OM.DisplayTitle,'')  AS DisplayTitle,
			ISNULL(OM.StreetOne,'') AS StreetOne,
			ISNULL(OM.StreetTwo,'') AS StreetTwo,
			ISNULL(OM.StreetThree,'') AS StreetThree,
			ISNULL(OM.ZipCode,'') AS ZipCode,
			ISNULL(SM.SUId,'') AS SUId ,
			ISNULL(OM.ReportOrgGroupTitle,'') AS ReportOrgGroupTitle,
			ISNULL(OM.ReportOrgTitle,'') AS ReportOrgTitle,
			ISNULL(SC.ParentContactNo,'') AS ParentContactNo,
			ISNULL(SC.StudentContactNo,'') AS StudentContactNo,
			ISNULL(SD.StatusName,'') AS StatusName,
			ISNULL(SD.StatusId,0) AS StatusId,
			ISNULL(SD.LCProgress,'') AS LCProgress,
			ISNULL(SD.Religion,'') AS Religion,
			ISNULL(SD.FamilyCast,'') AS FamilyCast,
			ISNULL(SD.FamilySubCast,'') AS FamilySubCast,
			ISNULL(SD.LCConduct,'') AS LCConduct,
			ISNULL(SD.BirthPlace,'') AS BirthPlace,
			ISNULL(SD.BirthTaluka,'') AS BirthTaluka,
			ISNULL(SD.BirthDistrict,'') AS BirthDistrict,
			ISNULL(SD.LeftDate,'') AS LeftDate,
			ISNULL(SD.PreviousSchool,'') AS PreviousSchool,
			ISNULL(SD.DateOfBirth,'') AS DateOfBirth,
			ISNULL(SD.BirthDateInWord,'') AS BirthDateInWord,
			ISNULL(SD.LeftReason,'') AS LeftReason,
			ISNULL(SD.AdmissionDate,'') AS AdmissionDate,
			ISNULL(SD.AdmissionStandard,'') AS AdmissionStandard,
			ISNULL(SD.LeftStandard,'') AS LeftStandard,
			ISNULL(SD.LCNumber,0) AS LCNumber,
			ISNULL(SD.LCDate,'') AS LCDate,
			ISNULL(SD.StudentPhoto,0x) AS StudentPhoto,
			ISNULL(SD.BloodGroup,'') AS BloodGroup,
			ISNULL(SD.PresentAddress,'') AS PresentAddress,
			ISNULL(SD.ContactNo,0) AS ContactNo,
			ISNULL(SD.Batch,'') AS Batch,
			ISNULL(SD.InactiveDate,'') AS InactiveDate,
			ISNULL(OM.Title,'') AS OrgName,
			ISNULL(SF.MotherName,'') AS MotherName,
			ISNULL(SD.DivisionOrder,0) AS DivisionOrder,
			ISNULL(SD.Number,'') AS StudentNumber,
			ISNULL(SF.FatherName,'') AS FatherName,
			ISNULL(SD.Nationality,'') AS Nationality,
			ISNULL(SD.MotherTongue,'') AS MotherTongue,
			ISNULL(SD.BirthState,'') AS BirthState,
			ISNULL(SD.BirthCountry,'') AS BirthCountry,
			ISNULL(SD.SUId,0) AS SUId,
            ISNULL(SD.AdhaarNumber,0) AS AdhaarNumber,
            ISNULL(SD.ClassStatusId,0) AS ClassStatusId,
            ISNULL(SD.ClassStatusName,'') AS ClassStatusName


		FROM 
				(
SELECT Id 
FROM (select A.ID,
             ROW_NUMBER() over (partition by studentId ORDER BY BM.OrderIndex DESC) as MAX_ID
      from sStudent.tAcademic A INNER JOIN sSetup.tBatchMaster BM ON A.BatchId = BM.Id
      ) x
WHERE MAX_ID = 1	
) LA INNER JOIN sStudent.tAcademic A ON LA.Id = A.Id
			
			INNER JOIN sStudent.vStudentAllDetail SD ON SD.AcademicId = A.Id
	LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId=SD.StudentId
			INNER JOIN sStudent.tStudentMaster SM
			ON A.StudentId=SM.Id	
			INNER JOIN sSetup.tClassMaster CM
			ON CM.Id=A.ClassId
			INNER JOIN sSetup.tDivisionMaster DM
			ON DM.Id=A.DivisionId
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId 
			INNER JOIN sStudent.tStatusMaster STM
			ON STM.Id=SM.StatusId
			INNER JOIN sSetup.tDepartmentMaster DeptM
			ON DeptM.Id=CM.DepartmentId
			INNER JOIN sSetup.tOrganizationMaster OM 
			ON SM.OrgId = OM.Id
			LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId = SM.Id
		WHERE 
			((A.ClassId=@rClassId)OR(@rClassId=0))
			AND((A.DivisionId=@rDivisionId)OR(@rDivisionId=0))
			AND((SM.Code >= CONVERT(nvarchar(20),@rFromCode)) OR (ISNULL(@rFromCode,0) = 0)) 
			AND((SM.Code <= CONVERT(nvarchar(20),@rToCode)) OR (ISNULL(@rToCode,0) = 0)) 
			AND((SM.FirstName like @rFirstName) OR (ISNULL(@rFirstName,'') = '')) 
			AND((SM.MiddleName like @rMiddleName) OR (ISNULL(@rMiddleName,'') = ''))
			AND((SM.LastName like @rLastName) OR (ISNULL(@rLastName,'') = '')) 
			AND((STM.Id=@rStatusId)OR(@rStatusId=0))	
			AND((A.BatchId=@rBatchId)OR(@rBatchId=0))	
			AND((OM.Id=@rOrgId)OR(@rOrgId=0))
			AND (BM.OrgGroupBatchId = @rOrgGroupBatchId OR @rOrgGroupBatchId = 0)
			AND((DeptM.Id=@rDepartmentId)OR(@rDepartmentId=0))
			AND((A.RollNo=@rRollNo)OR(@rRollNo=0))	
			AND((SM.SUId= @rSUId) OR (ISNULL(@rSUId,'') = '')) 
			ORDER BY SM.Number
	END

END
GO
PRINT N'Altering [sStudent].[pImportAdmissionInquiry]...';


GO
ALTER PROCEDURE [sStudent].[pImportAdmissionInquiry]
    
    @rOrgGroupId smallint,
    @rOrgId smallint,
	@rXmldoc [nvarchar](max),
	@rUserId bigint,
	@rBatchId int

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
BEGIN TRY

DECLARE @lCount INT
DECLARE @lInterrorCode INT,
			@intDoc INT,
			@lFirstName nvarchar(100),
			@lMiddleName nvarchar(100),
			@lLastName nvarchar(100),
			@lClassId int,
			@lClass nvarchar(50),
			@lDOB date,
			@lStatusId int,
			--@lStatus nvarchar(20),
			@lPresentStreetOne nvarchar(150),
			@lPresentStreetTwo nvarchar(150),
			@lPresentStreetThree nvarchar(150),
			@lPresentCountry nvarchar(50),
			@lPresentState nvarchar(50),
			
			@lPresentCity nvarchar(50),
			@lPresentZipCode nvarchar(20),
			@lParentContactNo nvarchar(20),
			@lParentEmail nvarchar(50),
			@lRemark nvarchar(200),
			@lInquiryModeId smallint,
			@lInquiryMode nvarchar(50),
			@lInquiryReferenceId int,
			@lInquiryReference nvarchar(50),
			@lAdmissionCategoryId int,
			@lAdmissionCategory nvarchar(100),
			@lPreviousSchool nvarchar(200),
			@lMeritMarks decimal(10,2),
			@lMeritGrade nvarchar(20),
			@lMeritMarksBreakup nvarchar(100),
			@lGenderId int,
			@lGender nvarchar(10),
			 @lFollowupDate date,
			@lFollowupRemark nvarchar(150),
			@lInquiryDate date,
			--@lCode nvarchar(20),
			@lNumber bigint,
			@lHandledBy nvarchar(100),
			@lInquiryStatusId int,
			@lInquiryStatus nvarchar(50) 
		 
			 
			 
			
 		
--DECLARE @OutClassId int
--DECLARE @OutDivisionId int
DECLARE @OutStudentId bigint 
--DECLARE @OutAdmissionStandardId int
--DECLARE @OutReligionId int
--DECLARE @OutAdmissionCategoryId int		
SET @lAdmissionCategoryId=sCommon.fGetIntIdForOrg(1,@rOrgGroupId)	
				 
EXECUTE @lInterrorCode = sp_xml_preparedocument @intDoc OUTPUT, @rXmlDoc
	 
	CREATE TABLE #tTable  
	(
		Id bigint identity,	 
		FirstName nvarchar(100),
		MiddleName nvarchar(100),
		LastName nvarchar(100),
		ClassId int  ,
		Class nvarchar(100),
		DOB date,
		StatusId smallint,
		--Status nvarchar(20),
		PresentStreetOne nvarchar(150),
		PresentStreetTwo nvarchar(150),
		PresentStreetThree nvarchar(150),
		PresentCountry nvarchar(50),
		PresentState nvarchar(50),
		PresentCity nvarchar(50),
		PresentZipCode nvarchar(20),
		ParentContactNo nvarchar(20),
		ParentEmail nvarchar(50),
		Remark nvarchar(200),
		InquiryModeId smallint,
		InquiryMode nvarchar(50),
		InquiryReferenceId int,
		InquiryReference nvarchar(50),
		AdmissionCategoryId int,
		AdmissionCategory nvarchar(100),
		PreviousSchool nvarchar(200),
		MeritMarks decimal(10,2),
		MeritGrade nvarchar(20),
		MeritMarksBreakup nvarchar(100),
		GenderId int,
		Gender nvarchar(10),
		 FollowupDate date,
		FollowupRemark nvarchar(150),
		CreatedUserId bigint,
		InquiryDate date,
		Number bigint,
		HandledBy nvarchar(100),
		InquiryStatusId int,
		InquiryStatus nvarchar(50) 
		 
		 
	)
	
	INSERT INTO #tTable
	(
		 
		FirstName,
		MiddleName,
		LastName,
		ClassId,
		Class,
		DOB,
		StatusId,
		--Status,
		PresentStreetOne,
		PresentStreetTwo,
		PresentStreetThree,
		PresentCountry,
		PresentState,
		PresentCity,
		PresentZipCode,
		ParentContactNo,
		ParentEmail,
		Remark,
		InquiryModeId,
		InquiryMode,
		InquiryReferenceId,
		InquiryReference,
		AdmissionCategoryId,
		AdmissionCategory,
		PreviousSchool,
		MeritMarks,
		MeritGrade,
		MeritMarksBreakup,
		GenderId,
		Gender,
		 FollowupDate,
		FollowupRemark,
		CreatedUserId,
		InquiryDate,
		Number,
		HandledBy,
		InquiryStatusId,
		InquiryStatus  
		
		
		 
	)
	
	SELECT
	 
		FirstName,
		MiddleName,
		LastName,
		0,
		Class,
		DOB,
		0,
	   -- Status,
	    PresentStreetOne,
		PresentStreetTwo,
		PresentStreetThree,
		PresentCountry,
		PresentState,
		PresentCity,
		PresentZipCode,
		ParentContactNo,
		ParentEmail,
		Remark,
		0,
		InquiryMode,
		0,
		InquiryReference,
		0,
		AdmissionCategory,
		PreviousSchool,
		MeritMarks,
		MeritGrade,
		MeritMarksBreakup,
		0,
		Gender,
		 FollowupDate,
		FollowupRemark,
		CreatedUserId,
		InquiryDate,
		Number,
		HandledBy,
		0,
		InquiryStatus  
		
		
			
	FROM OPENXML (@intDoc, '/Table/ImportStudent', 1)
	WITH
	( 
		  
		FirstName nvarchar(100) '@FirstName',
		MiddleName nvarchar(100) '@MiddleName',
		LastName nvarchar(100) '@LastName',
		Class nvarchar(100) '@Class',
		DOB DATE '@DOB',
		--Status nvarchar(20) '@Status',
		 PresentStreetOne nvarchar(150) '@PresentStreetOne',
		PresentStreetTwo nvarchar(150) '@PresentStreetTwo',
		PresentStreetThree nvarchar(150) '@PresentStreetThree',
		PresentCountry nvarchar(50) '@PresentCountry',
		PresentState nvarchar(50) '@PresentState',
		PresentCity nvarchar(50) '@PresentCity',
		PresentZipCode nvarchar(20) '@PresentZipCode',
		ParentContactNo nvarchar(20) '@ParentContactNo',
		ParentEmail nvarchar(50) '@ParentEmail',
		Remark nvarchar(200) '@Remark',
		InquiryMode  nvarchar(50) '@InquiryMode',
		InquiryReference nvarchar(50) '@InquiryReference',
		AdmissionCategory nvarchar(100) '@AdmissionCategory',
		PreviousSchool nvarchar(200) '@PreviousSchool',
		MeritMarks decimal(10,2) '@MeritMarks',
		MeritGrade nvarchar(20) '@MeritGrade',
		MeritMarksBreakup nvarchar(100) '@MeritMarksBreakup',
		Gender nvarchar(10) '@Gender',
		 FollowupDate date '@FollowupDate',
		FollowupRemark nvarchar(150) '@FollowupRemark',
		CreatedUserId bigint '@CreatedUserId' ,
		InquiryDate date '@InquiryDate',
		Number bigint '@Number',
		HandledBy nvarchar(100) '@HandledBy',
		InquiryStatus nvarchar(50) '@InquiryStatus'
		 
		
	)
	
	 --print 'check'
 
 
EXEC sp_xml_removedocument @intDoc
			
SELECT @lCount =  COUNT(Id) FROM #tTable

WHILE @lCount > 0 

BEGIN
		 
		SET @lFirstName = ''
		SET @lMiddleName = ''
		SET @lLastName = ''
		SET @lClassId = null
		SET @lClass = ''
		
		SET @lDOB  = ''
		SET @lStatusId =null
		--SET @lStatus  = ''
		SET @lPresentStreetOne = ''
		SET @lPresentStreetTwo = ''
		SET @lPresentStreetThree = ''
		SET @lPresentCountry = ''
		SET @lPresentState = ''
		SET @lPresentCity = ''
		SET @lPresentZipCode = ''
		SET @lParentContactNo = ''
		SET @lParentEmail = ''	
		SEt @lRemark = ''
		SEt @lInquiryModeId =null
		SET @lInquiryMode =''
		SET @lInquiryReferenceId =null
		SET @lInquiryReference =''
		SET @lAdmissionCategoryId =null
		SEt @lAdmissionCategory =''
		SEt @lPreviousSchool =''
		SEt @lMeritMarks =null
		SEt @lMeritGrade  =''
		SET @lMeritMarksBreakup =''
		SEt @lGenderId  =null
		SEt @lGender=''
		SEt @lFollowupDate =''
		SET @lFollowupRemark =''
		SEt @lInquiryDate =''
		SEt @lNumber =null
		SET @lHandledBy =''
		SET @lInquiryStatusId  =null
		SET @lInquiryStatus =''
		
	 
		--SET @OutStudentId = null

		
SELECT		
		 
		@lFirstName = FirstName,
		@lMiddleName = MiddleName,
		@lLastName = LastName,
		@lClass = Class,
		@lDOB = CASE WHEN DOB = '' THEN  NULL ELSE DOB END,
		--@lStatus = Status,
		@lPresentStreetOne = PresentStreetOne,
		@lPresentStreetTwo = PresentStreetTwo,
		@lPresentStreetThree = PresentStreetThree,
		@lPresentCountry = PresentCountry,
		@lPresentState = PresentState,
		@lPresentCity = PresentCity,
		@lPresentZipCode = PresentZipCode,
		@lParentContactNo = ParentContactNo,
		@lParentEmail = ParentEmail,
		@lRemark = Remark,
		@lInquiryMode =InquiryMode,
		@lInquiryReference = InquiryReference,
		@lAdmissionCategory  =AdmissionCategory,
		@lPreviousSchool  = PreviousSchool,
		@lMeritMarks = MeritMarks,
		@lMeritGrade  =MeritGrade,
		@lMeritMarksBreakup  =MeritMarksBreakup,
		@lGender  =Gender,
		@lFollowupDate =CASE WHEN FollowupDate = '' THEN  NULL ELSE FollowupDate END,
		@lFollowupRemark  =FollowupRemark,
		@lInquiryDate  =  CASE WHEN InquiryDate = '' THEN  NULL ELSE InquiryDate END,
		@lNumber =Number,
		@lHandledBy =HandledBy,
		@lInquiryStatus =InquiryStatus 
		
		 
											 	 
FROM #tTable WHERE Id = @lCount  
--print @lInquiryMode 
select *  FROM #tTable
	SELECT	@lGenderId = ID FROM sCommon.tGenderMaster WHERE Title = @lGender
	SELECT	@lClassId  = ID FROM sSetup.tClassMaster WHERE Title = @lClass AND OrgId = @rOrgId
	SELECT  @lInquiryModeId = ID from sAdmission.tInquiryModeMaster WHERE Title = @lInquiryMode 
	SELECT @lInquiryReferenceId =ID from sAdmission.tInquiryReferenceMaster Where Title = @lInquiryReference AND OrgGroupId = @rOrgGroupId
	Select @lInquiryStatusId = ID from sAdmission.tInquiryStatusMaster WHERE Title =@lInquiryStatus  AND  OrgGroupId =@rOrgGroupId
	Select @lStatusId = StatusId from sAdmission.tInquiryStatusMaster WHERE Id = @lInquiryStatusId
	
	SELECT	@lAdmissionCategoryId  = ID FROM tAdmissionCategoryMaster WHERE Title = @lAdmissionCategory AND OrgGroupId = @rOrgGroupId
	--SELECT	@lCastCategoryId  = ID FROM sCommon.tCastCategoryMaster WHERE Title = @lCastCategory AND OrgGroupId = @rOrgGroupId	
 
	
	IF(@lClassId IS NULL)
		SET @lClassId = 0
	IF(@lGenderId IS NULL)
		SET @lGenderId = 0
 
	IF(@lAdmissionCategoryId IS NULL)
		SET	@lAdmissionCategoryId = 0
	 
	 IF (@lInquiryModeId IS NULL)
		SET @lInquiryModeId=0
	IF (@lInquiryReferenceId IS Null)
		SET @lInquiryReferenceId=0
	IF (@lMeritMarks IS Null   )
		SET @lMeritMarks=0
	IF (@lNumber IS Null   )
		SET @lNumber=0 
		
 BEGIN TRANSACTION

 EXEC sAdmission.pAdmissionInquiryAdd 0,@lFirstName,@lMiddleName,@lLastName,@lClassId,@rBatchId,@lDOB,@rOrgId, @lInquiryStatusId,
									 @lPresentStreetOne,@lPresentStreetTwo,@lPresentStreetTwo,@lPresentCountry,@lPresentState,@lPresentCity,
									 @lPresentZipCode,@lParentContactNo,@lParentEmail,@lRemark,@lInquiryModeId,@lInquiryReferenceId,
									  @lAdmissionCategoryId,@lPreviousSchool,@lMeritMarks,@lMeritGrade,@lMeritMarksBreakup,
									  @lGenderId,@lFollowupDate,@lFollowupRemark,@rUserId,@lInquiryDate,@lNumber,@lHandledBy,@rOrgGroupId
	
		SET @lCount = @lCount - 1	
 
		 COMMIT TRANSACTION		
 
 
END
 

	SELECT 1
	END TRY	
	BEGIN CATCH
	ROLLBACK TRANSACTION
	SELECT ERROR_MESSAGE(), ERROR_LINE()
	END CATCH
	
END
GO
PRINT N'Altering [sStudent].[pRptStudentAttendanceSummaryGet]...';


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

BEGIN 
CREATE TABLE #tmp
(
Builder1 nvarchar(max),
Builder2 nvarchar(max),
AcademicId bigint,
ClassId int,
DivisionId int,
DepartmentId int,
ClassName nvarchar(500),
DivisionName nvarchar(500),
IsPresent bit,
ClassOrderIndex int,
DivisionOrder int,
AttendanceDate Date,
RowNo int,
AttendanceType nvarchar(100),
AttendanceTypeId int,
GenderId int,
MonthTitle nvarchar(50),
MonthNumber int,
YearNumber int
)
INSERT INTO #tmp
SELECT 	@rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,
		SA.AcademicId,
		SA.ClassId,
		SA.DivisionId,
		SA.DepartmentId,
		SA.ClassName,
		SA.DivisionName,
		ISNULL(SR.IsPresent,0)AS IsPresent,
		SA.ClassOrderIndex,
		SA.DivisionOrder,
		SR.AttendanceDate,		
		--1 AS AttendanceDay,
		Row_Number() OVER(PARTITION BY SA.ClassId,SA.DivisionId,SR.AttendanceDate ORDER BY SR.AttendanceDate ASC) AS RowNo,
		ATM.Title AS AttendanceType,
		SR.AttendanceTypeId,
		SA.GenderId,
		DATENAME(MONTH,SR.AttendanceDate) AS MonthTitle,
		DATEPART(MONTH,SR.AttendanceDate) AS MonthNumber,
		DATENAME(YEAR,SR.AttendanceDate) AS YearNumber
	FROM 
            sStudent.vStudentAcademic SA 
            INNER JOIN sStudent.tStudentAdmission AD ON SA.StudentId = AD.StudentId
			LEFT JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=SA.AcademicId
			INNER JOIN sAttendance.tAttendanceTypeMaster ATM ON SR.AttendanceTypeId = ATM.Id
			AND (SR.AttendanceTypeId=@rAttendanceTypeId OR @rAttendanceTypeId = 0)
			AND ((SR.AttendanceDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
    		AND ((SR.AttendanceDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
			--INNER JOIN #tmpDates tmp ON tmp.AllDates = SR.AttendanceDate
		Where SA.OrgId = @rOrgId
			  AND SA.BatchId = @rBatchId
			  AND ((SA.ClassId = @rClassId) OR (@rClassId = 0))
			  AND ((SA.DivisionId = @rDivisionId) OR (@rDivisionId = 0))
			  AND ((SA.DepartmentId = @rDepartmentId) OR (@rDepartmentId = 0))
			
			  AND SA.StatusId = 1
			  AND (AD.LeftDate > SR.AttendanceDate OR ISNULL(AD.LeftDate,'')= '')
			  AND (AD.AdmissionDate <= SR.AttendanceDate)
			  Order By SA.ClassOrderIndex,SA.DivisionOrder,SR.AttendanceDate
			   
SELECT
Builder1,
Builder2,
@rIsDetail AS IsDetail,
AcademicId,
ClassId,
DivisionId,
DepartmentId,
ClassName,
DivisionName,
IsPresent,
ClassOrderIndex,
DivisionOrder,
AttendanceDate,
(CASE WHEN RowNo = 1 THEN 1 ELSE 0 END)AS AttendanceDay,
AttendanceType,
AttendanceTypeId,
GenderId,
MonthTitle,
MonthNumber,
YearNumber
FROM
#tmp

DROP TABLE #tmp

--Select
--'' AS Builder1,
--'' AS Builder2,
--0 AS IsDetail,
--CONVERT(bigint,0) AS AcademicId,
--0 AS ClassId,
--0 AS DivisionId,
--0 AS DepartmentId,
--'' AS ClassName,
--'' AS DivisionName,
--CONVERT(bit,0) AS IsPresent,
--0 AS ClassOrderIndex,
--0 AS DivisionOrder,
--CONVERT(DATE,'') AS AttendanceDate,
--0 AS AttendanceDay,
--'' AS AttendanceType,
--0 AS AttendanceTypeId,
--0 AS GenderId,
--'' AS MonthTitle,
--0 AS MonthNumber,
--0 AS YearNumber
END
GO
PRINT N'Altering [sStudent].[pRptStudentRegisterGet]...';


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

BEGIN 

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


GO

ALTER PROCEDURE [sStudent].[pStudentCustomFieldAdd]
		 
	@rId int,
	@rOrgId int,
	@rFieldTitle nvarchar(500),
	@rFieldTypeId tinyint,
	@rFieldList nvarchar(500),
	@rIsFieldMandatory bit,
	@rFieldGroup nvarchar(200),
	@rFieldOrder smallint,
	@rCreatedUserId bigint,	
	@rCreatedDateTime datetime,
	@rUpdatedUserId bigint,
	@rUpdatedDateTime datetime,
	@rIsObsolete int =0,
	@rDataTypeId int = 1

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

BEGIN TRY
BEGIN TRANSACTION	

DECLARE @lOrgGroupId int=0
SELECT @lOrgGroupId= OrgGroupId FROM sSetup.tOrganizationMAster WHERE Id = @rOrgId
 
IF(@rId = 0)	
BEGIN
    IF NOT EXISTS(SELECT 2 FROM sStudent.tStudentCustomFieldMaster WHERE FieldTitle=@rFieldTitle AND FieldGroup=@rFieldGroup AND DataId=@rDataTypeId )
    --IF NOT EXISTS(SELECT 2 FROM sStudent.tStudentCustomFieldMaster WHERE FieldTitle=@rFieldTitle)
	BEGIN
	      DECLARE @lNextNumber int
	      EXECUTE sCommon.pTableRowIdGet @lOrgGroupId, 'sStudent.tStudentCustomFieldMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
Print @lNextNumber
	      INSERT INTO sStudent.tStudentCustomFieldMaster
	      (
		    Id
		   ,FieldTitle
		   ,FieldTypeId
		   ,FieldList
		   ,IsFieldMandatory
		   ,FieldGroup
		   ,FieldOrder
		   ,CreatedUserId
		   ,CreatedDateTime
		   ,OrgGroupId
		   ,IsObsolete
		   ,DataId
	      )
	     VALUES
	     (
		   @lNextNumber
		  ,@rFieldTitle
		  ,@rFieldTypeId
		  ,@rFieldList
		  ,@rIsFieldMandatory
		  ,@rFieldGroup
		  ,@rFieldOrder
		  ,@rCreatedUserId
		  ,@rCreatedDateTime
		  ,@lOrgGroupId
		  ,@rIsObsolete
		  ,@rDataTypeId
	     )
     END
	 ELSE
	 SELECT -101 As RESULT
END
	 	 
ELSE
BEGIN
	SET @lNextNumber = @rId

	
	
		UPDATE sStudent.tStudentCustomFieldMaster
		SET 
		FieldTitle = @rFieldTitle
		,FieldTypeId = @rFieldTypeId
		,FieldList=@rFieldList
		,IsFieldMandatory=@rIsFieldMandatory
		,IsObsolete=@rIsObsolete
		,FieldGroup=@rFieldGroup
		,FieldOrder=@rFieldOrder
		,UpdatedUserId=@rUpdatedUserId
		,UpdatedDateTime=@rUpdatedDateTime
		,DataId = @rDataTypeId
		WHERE Id = @rId 
	
	
END  
	SELECT @lNextNumber AS Result
	
	COMMIT TRANSACTION
	END TRY
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
END
GO
PRINT N'Altering [sStudent].[pStudentFullProfileGet]...';


GO
 
 
ALTER PROCEDURE [sStudent].[pStudentFullProfileGet]
	 
	 @rBatchId int,
	 @rStudentId bigint,
	 @rReportId int=0,
	 @rOrgId int,
	 @rStrCode nvarchar(max)='',
	 @rClassId int=0,
	 @rDivisionId int=0,
	 @rFromRollNo int=0,
	 @rToRollNo int=0,
	 @rStatusId int=0,
	 @rClassStatusId int=0,
	 @rDateOfBirth int=0,
	 @rDepartmentId int=0,
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='',
	 @rOrgGroupBatchId int,
	 @rFromAdmissionDate date = '',
	 @rToAdmissionDate date = ''
	 
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
	
	DECLARE @lAcademicId bigint
	SELECT @lAcademicId = Id from sStudent.tAcademic Where StudentId = @rStudentId AND BatchId = @rBatchId
	
	SELECT 
			--Academic
			@rBuilder1 As Builder1,
			SA.StudentId AS Id,
			--SA.FirstName + ' ' + ISNULL(SA.MiddleName,'') + ' ' + 	SA.LastName AS StudentName,
			SA.Name AS StudentName,
			SA.FirstName as FirstName,
			SA.MiddleName as MiddleName,
			SA.LastName as LastName,
			SA.Batch AS AcademicYear,
			ISNULL(SA.Code,' - ') AS Code,
			SA.ClassDivision AS ClassDiv,			
			SA.RollNo,
			ISNULL(SM.Title,'-') AS House,
			--Other
			CASE WHEN @rReportId=0 THEN ISNULL(SA.DateOfBirth,'0001/01/01')  
			WHEN @rReportId=1 THEN  SA.DateOfBirth END  AS DateOfBirth,
			ISNULL(SA.BirthTaluka,'') AS BirthTaluka,
			ISNULL(SA.BirthPlace,'') AS BirthPlace,	
			ISNULL(SA.BirthDistrict,'') AS BirthDistrict,
			ISNULL(SA.BirthDateInWord,'') AS BirthDateInWord,                           
			ISNULL(SA.Gender,'') AS Gender,
			ISNULL(SA.Religion,'') AS Religion,
			--Admission			
			ISNULL(SA.AdmissionStandard,'') AS AdmissionStandard,
			--ISNULL(SA.AdmissionDate,'0001/01/01') AS AdmissionDate,
			CASE WHEN @rReportId=0 THEN ISNULL(SA.AdmissionDate,'0001/01/01')
			WHEN @rReportId=1 THEN  SA.AdmissionDate END AS AdmissionDate,
	
			ISNULL(SA.PreviousSchool,'') AS PreviousSchool,
			ISNULL(SA.AdmissionCategory,'') AS StudentAdmissionCategory,
			CASE WHEN @rReportId=0 THEN ISNULL(SA.LeftDate,'0001/01/01')
			WHEN @rReportId=1 THEN  SA.LeftDate END AS LeftDate,
						 
			ISNULL(SA.LeftStandard,'') AS LeftStandard,
			--ISNULL(SA.InactiveDate,'0001/01/01') AS InactiveDate,
			CASE WHEN @rReportId=0 THEN ISNULL(SA.InactiveDate,'0001/01/01')
			WHEN @rReportId=1 THEN  SA.InactiveDate END AS InactiveDate,		
			ISNULL(SA.LCNumber,'') AS LCNumber,
			--ISNULL(SA.LCDate,'0001/01/01') AS LCDate,
			 CASE WHEN @rReportId=0 THEN ISNULL(SA.LCDate,'0001/01/01')
			WHEN @rReportId=1 THEN  SA.LCDate END AS LCDate,
			--Communication
			ISNULL(SA.PresentStreetone,'') + ' ' + ISNULL(SA.PresentStreetTwo,'') + ' ' + ISNULL(SA.PresentStreetThree,'') AS PresentAddress,
			ISNULL(SA.PresentCity,'') AS PresentCity,
			ISNULL(SA.PresentState,'') AS PresentState,
			ISNULL(SA.PresentCountry,'') AS PresentCountry,
			ISNULL(SA.PresentZipCode,'') AS PresentZipCode,
			ISNULL(SA.PresentContactNo,'') AS PresentContactNo,
			
			ISNULL(SA.EmergencyStreetOne,'') + ' ' + ISNULL(SA.EmergencyStreetTwo,'') + ' ' + ISNULL(SA.EmergencyStreetThree,'') AS EmergencyAddress,
			ISNULL(SA.EmergencyCity,'') AS EmergencyCity,
			ISNULL(SA.EmergencyState,'') AS EmergencyState,
			ISNULL(SA.EmergencyCountry,'') AS EmergencyCountry,
			ISNULL(SA.EmergencyZipCode,'') AS EmergencyZipCode,
			ISNULL(SA.EmergencyContactNo,'') AS EmergencyContactNo,
			
			ISNULL(SA.PermanentStreetOne,'') + ' ' + ISNULL(SA.PermanentStreetTwo,'') + ' ' + ISNULL(SA.PermanentStreetThree,'') AS PermanentAddress,
			ISNULL(SA.PermanentCity,'') AS PermanentCity,
			ISNULL(SA.PermanentState,'') AS PermanentState,
			ISNULL(SA.PermanentCountry,'') AS PermanentCountry,
			ISNULL(SA.PermanentZipCode,'') AS PermanentZipCode,
			ISNULL(SA.PermanentContactNo,'') AS PermanentContactNo,
			
			--Parent Information
			ISNULL(SF.FatherName,'') AS FatherName,
			ISNULL(SF.FatherOccupation,'') AS FatherOccupation,
			ISNULL(SF.FatherQualification,'') AS FatherQualification,
			ISNULL(SF.FatherContactNo,'') AS FatherContactNo,
			ISNULL(SF.FatherMail,'') AS FatherMail,
			ISNULL(SF.FatherOfficeAddress,'') AS FatherOfficeAddress,
			ISNULL(SF.FatherDesignation,'') AS FatherDesignation,
			ISNULL(SF.FatherOrganization,'') AS FatherOrganization,
			ISNULL(SF.FatherIncome,'') AS FatherIncome,

			ISNULL(SF.MotherName,'') AS MotherName,
			ISNULL(SF.MotherOccupation,'') AS MotherOccupation,
			ISNULL(SF.MotherQualification,'') AS MotherQualification,
			ISNULL(SF.MotherContactNo,'') AS MotherContactNo,
			ISNULL(SF.MotherMail,'') AS MotherMail,
			ISNULL(SF.MotherOfficeAddress,'') AS MotherOfficeAddress,
			ISNULL(SF.MotherDesignation,'') AS MotherDesignation,
			ISNULL(SF.MotherOrganization,'') AS MotherOrganization,
			ISNULL(SF.MotherIncome,'') AS MotherIncome,

			ISNULL(SF.RelationshipName,'') AS RelationShip,
			ISNULL(SF.RelativeName,'') AS RelativeName,
			ISNULL(SF.RelativeOccupation,'') AS RelativeOccupation,
			ISNULL(SF.RelativeQualification,'') AS RelativeQualification,
			ISNULL(SF.RelativeContactNo,'') AS RelativeContactNo,
			ISNULL(SF.RelativeMail,'') AS RelativeMail,
			ISNULL(SF.RelativeOfficeAddress,'') AS RelativeOfficeAddress,
			ISNULL(SF.RelativeDesignation,'') AS RelativeDesignation,
			ISNULL(SF.RelativeOrganization,'') AS RelativeOrganization,
			ISNULL(SF.RelativeIncome,'') AS RelativeIncome,
			
			--Health Information
			ISNULL(SA.BloodGroup,'') AS BloodGroup,
			ISNULL(SH.IdentificationMark1,'')+' '+ISNULL(SH.IdentificationMark2,'') as IdentificationMark,
			
			ISNULL(SH.FamilyDoctorName,'') AS FamilyDoctorName,
			ISNULL(SH.FamilyDoctorContactNo,'') AS FamilyDoctorContactNo,
			
			ISNULL(SH.IsPysicalDeformity,0) AS IsPysicalDeformity,
			ISNULL(SH.PysicalDeformityRemark,'') AS PysicalDeformityRemark,
			ISNULL(SH.IsMajorIllness,0) AS IsMajorIllness,
			ISNULL(SH.MajorIllnessRemark,'') As MajorIllnessRemark,
			ISNULL(SH.IsAllergy,0) AS IsAllergy,
			ISNULL(SH.AllergyRemark,'') As AllergyRemark,
			ISNULL(SH.IsPastHistory,0) As IsPastHistory ,
			ISNULL(SH.PastHistoryRemark,'') As PastHistoryRemark,
			--Hostel
			ISNULL(RM.Title,'') AS RoomNo,			
			ISNULL(HM.Title,'') AS Hostel,
			ISNULL(EMW.FirstName,'')+' '+ISNULL(EMW.LastName,'') AS WardenName,
			ISNULL(ECW.PhoneNoCompany,'') As WardenPhoneNo,
			ISNULL(ECW.ExtensionNo,'') AS WardenExtNo,
			ISNULL(ECW.MobileNumber,'') AS WardenMobileNo,
			ISNULL(EMA.FirstName,'')+' '+ISNULL(EMA.LastName,'') AS AssignedRoomBy,	
			ISNULL(ECA.PhoneNoCompany,'') AS AssignedRoomByPhoneNo,
			ISNULL(ECA.ExtensionNo,'') AS AssignedRoomByExtNo,
			ISNULL(ECA.MobileNumber,'') AS AssignedRoomByMobileNo,
			--Notification Details
			ISNULL(SA.ParentEmail,'') AS ParentEmail,
			ISNULL(SA.ParentContactNo,'') As ParentContactNo,
			ISNULL(SA.StudentEmail,'') AS StudentEmail,
			ISNULL(SA.StudentContactNo,'') AS StudentContactNo,
					
	   	    --ISNULL(SA.StudentPhoto, CONVERT(VARBINARY(MAX), 0))AS StudentPhoto,
	   	   -- ISNULL(SA.FatherPhoto, CONVERT(VARBINARY(MAX), 0)) AS FatherPhoto,
	   	   -- ISNULL(SA.MotherPhoto, CONVERT(VARBINARY(MAX), 0)) AS MotherPhoto,
	   	    --ISNULL(SA.RelativePhoto, CONVERT(VARBINARY(MAX), 0)) AS RelativePhoto,
	   	   CASE WHEN @rReportId=0
			THEN ISNULL(SA.StudentPhoto, CONVERT(VARBINARY(MAX), 0))
			WHEN @rReportId=1
			THEN ISNULL(SA.StudentPhoto, CONVERT(VARBINARY(MAX), ''))
			END AS StudentPhoto,
			
			CASE WHEN @rReportId=0
			THEN ISNULL(SA.MotherPhoto, CONVERT(VARBINARY(MAX), 0))
			WHEN @rReportId=1
			THEN ISNULL(SA.MotherPhoto, CONVERT(VARBINARY(MAX), ''))
			END AS MotherPhoto,
			
			CASE WHEN @rReportId=0
			THEN ISNULL(SA.FatherPhoto, CONVERT(VARBINARY(MAX), 0))
			WHEN @rReportId=1
			THEN ISNULL(SA.FatherPhoto, CONVERT(VARBINARY(MAX), ''))
			END AS FatherPhoto,
			
			CASE WHEN @rReportId=0
			THEN ISNULL(SA.RelativePhoto, CONVERT(VARBINARY(MAX), 0))
			WHEN @rReportId=1
			THEN ISNULL(SA.RelativePhoto, CONVERT(VARBINARY(MAX), ''))
			END AS RelativePhoto,
		   -- Transport Details
		    A.VehicleName AS VehicleName,
		    A.VehicleRegistrationNumber AS VehicleRegistrationNumber,
		    A.TypeOfVehicle AS TypeOfVehicle,
		    ISNULL(A.BusRoute,'') AS BusRoute,
		    A.DriverName,
		    A.DriverMobileNo,
		    A.ConductorName,
		    A.ConductorMobileNo,
		    ISNULL(A.BusRouteDestination,'') AS BusRouteDestination,
		    
		    A.DropVehicleName AS DropVehicleName,
		    A.DropVehicleRegistrationNumber AS DropVehicleRegistrationNumber,
		    A.DropTypeOfVehicle AS DropTypeOfVehicle,
		    ISNULL(A.DropRoute,'') AS DropRoute,
		    A.DropRouteDriverName AS DropRouteDriverName,
		    A.DropRouteDriverMobileNo AS DropRouteDriverMobileNo,
		    A.DropRouteConductorName AS DropRouteConductorName,
		    A.DropRouteConductorMobileNo AS DropRouteConductorMobileNo,
		    ISNULL(A.DropDestination,'') AS DropDestination,
		    
		    --ClassTeacher Details
		    ISNULL(EMT.Id,0) AS TeacherId,
		    EMT.FirstName+' '+EMT.MiddleName+' '+EMT.LastName AS TeacherFullName,
		    EDM.Title AS TeacherDesignation,
		    EPD.Qualification AS TeacherQualification,
		    ISNULL(EI.EmployeePhoto, CONVERT(VARBINARY(MAX), 0)) AS TeacherPhoto,
		    ISNULL(DF.IsDisplayFamilyDetail,0) AS IsDisplayFamilyDetail,
		    ISNULL(DF.IsDisplaySiblingDetail,0) AS IsDisplaySiblingDetail,
		    ISNULL(DF.IsDisplayPassportDetail,0) AS IsDisplayPassportDetail,
		    ISNULL(DF.IsDisplayBankDetail,0) AS IsDisplayBankDetail,
		    ISNULL(DF.IsDisplayCBSEREGDetail,0) AS IsDisplayCBSEREGDetail,
		    ISNULL(DF.IsDisplayCollegeDetail,0) AS IsDisplayCollegeDetail,
		    ISNULL(DF.IsDisplayGOVREGNoDetail,0) AS IsDisplayGOVREGNoDetail,
		    ISNULL(DF.IsDisplayHealthDetail,0) AS IsDisplayHealthDetail,
		    ISNULL(DF.IsDisplayTransportDetail,0) AS IsDisplayTransportDetail,
		    ISNULL(DF.IsDisplayHostelDetail,0) AS IsDisplayHostelDetail,
		    ISNULL(DF.IsDisplayClubDetail,0) AS IsDisplayClubDetail,
		    
		    ISNULL(DF.IsDisplaySSCResultDDetail,0) AS IsDisplaySSCResultDDetail,
		    ISNULL(DF.IsDisplayHSCResultDetail,0) AS IsDisplayHSCResultDetail,
		    ISNULL(DF.IsDisplayJeeDetail,0) AS IsDisplayJeeDetail,
		    ISNULL(DF.IsDisplayDiplomaDetail,0) AS IsDisplayDiplomaDetail,
			ISNULL(DF.IsDisplayClassTeacherDetail,0) AS IsDisplayClassTeacherDetail,
		    --Sibling Detail
		    isnull(SS.SiblingName1,'') AS SiblingName1,
	        ISNULL (SS.SiblingInstitue1,'') AS SiblingInstitue1,
	        ISNULL(SS.SiblingClass1,'')AS SiblingClass1,
	        ISNULL(SS.SiblingAge1,'')AS SiblingAge1,
	        ISNULL(SS.SiblingRelation1,'')AS SiblingRelation1,
	        isnull(SS.SiblingName2,'') AS SiblingName2,
	        ISNULL(SS.SiblingInstitue2,'')AS SiblingInstitue2,
	        ISNULL(SS.SiblingClass2,'')AS SiblingClass2,
	        ISNULL(SS.SiblingAge2,'') AS SiblingAge2,
	        ISNULL(SS.SiblingRelation2,'')AS SiblingRelation2,
	        isnull(SS.SiblingName3,'') AS SiblingName3,
	        ISNULL( SS.SiblingInstitue3,'')AS SiblingInstitue3,
	        ISNULL(SS.SiblingClass3,'')AS SiblingClass3,
	        ISNULL(SS.SiblingAge3,'')AS SiblingAge3,
	        ISNULL(SS.SiblingRelation3,'')AS SiblingRelation3,
	        ISNULL(SAD.BankAccountNumber,'')AS BankAccountNumber,
	        ISNULL(SAD.BankName,'')AS BankName,
	        ISNULL(SAD.BankBranch,'') AS BankBranch,
	        ISNULL(SAD.BankIFSCCode,'')AS BankIFSCCode,
	        ISNULL(SAD.Class9BoardRegistrationNumber,'') AS Class9BoardRegistrationNumber,
	        ISNULL(SAD.Class11BoardRegistrationNumber,'')AS Class11BoardRegistrationNumber,
	        ISNULL(SAD.PassportNumber,'')AS PassportNumber, 
	        ISNULL(SAD.PassportType,'') AS PassportType,
	       ISNULL( SAD.PassportCountryCode,'') AS PassportCountryCode,
	        CASE WHEN @rReportId=0 THEN ISNULL(SAD.PassportIssueDate,'0001/01/01')
			WHEN @rReportId=1 THEN  SAD.PassportIssueDate END AS PassportIssueDate,
			CASE WHEN @rReportId=0 THEN ISNULL(SAD.PassportExpiryDate,'0001/01/01')
			WHEN @rReportId=1 THEN  SAD.PassportExpiryDate END AS PassportExpiryDate,
	        ISNULL(SA.UIDNumber,'')AS UIDNumber,
	        ISNULL(SA.AdhaarNumber,'') AS AdhaarNumber,
	       ISNull(SA.StatusId,0) AS StatusId,
	       ISNUll(SA.IsTransfer,0)AS IsTransfer,
	       ISNULL(SA.TransferFrom,'') AS TransferFrom,
	       ISNULL(SA.CertificateName,'') AS CertificateName,
	       ISNUll(SA.IsTFWS,0)AS IsTFWS,
	       ISNUll(SA.IsCertificateHolder,0)AS IsCertificateHolder,
	       ISNULL(CD.SSCBoard,'') AS SSCBoard,
	       ISNULL(CD.SSCSchool,'') AS SSCSchool,
	       ISNULL(CD.SSCPassingYear,'') AS SSCPassingYear,
	       ISNULL(CD.SSCObtainMarks,0) AS SSCObtainMarks,
	       ISNULL(CD.SSCOutOfMarks,0) AS SSCOutOfMarks,
	       ISNULL(CD.SSCPercentage,0) AS SSCPercentage,
	       ISNULL(CD.SSCMathMarks,0) AS SSCMathMarks,
	       ISNULL(CD.SSCMathOutOfMarks,0) AS SSCMathOutOfMarks,
	       ISNULL(CD.SSCPercentile,0) AS SSCPercentile,
	       ISNULL(CD.SSCGrade,0) AS SSCGrade,
	       ISNULL(CD.HSCBoard,'') AS HSCBoard,
	       ISNULL(CD.HSCSchool,'') AS HSCSchool,
	       ISNULL(CD.HSCPassingYear,0) AS HSCPassingYear,
	       ISNULL(CD.HSCObtainMarks,0) AS HSCObtainMarks,
	       ISNULL(CD.HSCOutOfMarks,0) AS HSCOutOfMarks,
	       ISNULL(CD.HSCPercentage,0) AS HSCPercentage,
	       ISNULL(CD.HSCPhysicsMarks,0) AS HSCPhysicsMarks,
	       ISNULL(CD.HSCPhysicsOutOfMarks,0) AS HSCPhysicsOutOfMarks,
	       ISNULL(CD.HSCChemistryMarks,0) AS HSCChemistryMarks,
	       ISNULL(CD.HSCChemistryOutOfMarks,0) AS HSCChemistryOutOfMarks,
	       ISNULL(CD.HSCMathMarks,0) AS HSCMathMarks,
	       ISNULL(CD.HSCMathOutOfMarks,0) AS HSCMathOutOfMarks,
	       ISNULL(CD.HSCBiologyMarks,0) AS HSCBiologyMarks,
	       ISNULL(CD.HSCBiologyOutOfMarks,0) AS HSCBiologyOutOfMarks,
	       ISNULL(CD.PCMMarks,0) AS PCMMarks,
	       ISNULL(CD.PCBMarks,0) AS PCBMarks,
	       ISNULL(CD.JEERollNo,'') AS JEERollNo,
	       ISNULL(CD.JEEMeritNo,'') AS JEEMeritNo,
	       ISNULL(CD.JEEMeritMarks,0) AS JEEMeritMarks,
	       ISNULL(CD.JEEOutOfMarks,0) AS JEEOutOfMarks,
	       ISNULL(CD.DiplomaBoard,'') AS DiplomaBoard,
	       ISNULL(CD.DiplomaCollege,'') AS DiplomaCollege,
	       ISNULL(CD.DiplomaPassingYear,'') AS DiplomaPassingYear,
	       ISNULL(CD.DiplomaObtainMarks,0) AS DiplomaObtainMarks,
	       ISNULL(CD.DiplomaOutOfMarks,0) AS DiplomaOutOfMarks,
	       ISNULL(CD.DiplomaPercentage,0) AS DiplomaPercentage,
	       ISNULL(CD.ApplicationNo,'') AS ApplicationNo,
	       ISNULL(CD.AdmissionRound,0) AS AdmissionRound,
	       ISNULL(CD.MaritalStatusId,0) AS MaritalStatusId,
	       ISNULL(MS.Title,'') AS MaritalStatus,
	       ISNULL(ACD.RepeatCount,1)AS RepeatCount,
	       ISNULL(SA.MotherTongue,'') As MotherTongue,
	       ISNULL(SA.FamilyCast,'') AS FamilyCast,
	      ISNULL(CM.Nationality,'') AS Nationality,
	       ISNULL(CT.Title,'') AS CasteCategory,
	       ISnull(SA.ClassName,'') AS ClassName ,
	       ISnull( SA.DivisionName,'') AS DivisionName,
	      ISNULL( SF.IsFatherExStudent,0) AS IsFatherExStudent,
	       ISnull(SF.FatherPassOutYear,'') AS FatherPassOutYear,
	       Isnull(SF.IsMotherExStudent,0) AS IsMotherExStudent,
	       Isnull(SF.MotherPassOutYear,'') AS MotherPassOutYear,
	       ISNULL(SF.IsRelativeExStudent,0) AS IsRelativeExStudent,
	       ISNULL(SF.RelativePassOutYear,'') AS RelativePassOutYear,
	       ISNULL(Sa.PresentDistanceFromSchool,0) AS PresentDistanceFromSchool,
	        SA.StudentId,
	        SA.ClassId,
	        SA.DivisionId,
	        SA.BirthState,
	        SA.BirthCountry,
	         ISNULL(SA.PreviousStandard,'')AS PreviousStandard
	        ,ISNULL(CGG.Title,'') AS CustomGroup
			,ISNULL(SGM.Title,'') As StudentGroup
			,ISNULL(SOGM.Title,'') As StudentOtherGroup
			,ISNULL([sStudent].[fAssignedClubGet](@lAcademicId),'') AS ClubName
			,ISNULL([sStudent].[fAssignedCustomTagGet](@lAcademicId),'') AS CustomTag 
	        ,SA.ClassStatusId
	        ,SA.ClassStatusName
	        ,PDCM.Title As PhysicalDisabilityCategory
			,ISNULL(SAM.PreviousLCNumber,'') AS PreviousLCNumber
			,ISNULL(SAM.PreviousLCDate,'') AS PreviousLCDate,
			ISNULL(SAM.AdmissionNumber,'') AS  AdmissionNumber,
			ISNULL(SAM.AdmissionFormNumber,'') AS  AdmissionFormNumber,
			SA.SUId,
	       --[sHostel].[fHostelWardenGet](HM.Id) As WardenName
		   MS.Title AS MaritalStatus

  FROM 
           sStudent.vStudentAllDetail SA
          -- LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId = SA.StudentId
           LEFT JOIN sStudent.tStudentHealth SH ON SA.StudentId=SH.StudentId
           LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId = SA.StudentId 
          -- LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId = SA.StudentId
           LEFT JOIN sActivity.tHouseMaster SM ON SM.ID = SA.HouseId
           LEFT JOIN sHostel.tAssignRoom AR ON AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003  AND ((AR.OrgGroupBatchId=@rOrgGroupBatchId) OR(@rOrgGroupBatchId=0))
           LEFT JOIN sHostel.tRoomMaster RM ON RM.Id=AR.RoomId
           LEFT JOIN sCommon.tPhysicalDisabilityCategoryMaster PDCM ON PDCM.Id = SH.PhysicalDisabilityCategoryId
           LEFT JOIN sHostel.tHostelMaster HM ON HM.Id=RM.HostelId   
            LEFT JOIN
            (
		   SELECT 
		   employeeId, 
		   HostelId,   
		   ROW_NUMBER() OVER (PARTITION BY HostelId ORDER By HostelId ) as ROWNo 		   
		 
		   FROM sHostel.tHostelwarden 
            )  HW ON HW.HostelId=HM.Id AND RowNo = 1       
           --LEFT JOIN sHostel.tHostelWarden HW ON HW.HostelId=HM.Id
           LEFT JOIN sHrm.tEmployeeMaster EMW ON HW.EmployeeId=EMW.Id AND  ISNULL(EMW.IsOtherUser,0) = 0
           LEFT JOIN sHrm.tEmployeeMaster EMA ON RM.AssignedEmployeeId=EMA.Id AND  ISNULL(EMA.IsOtherUser,0) = 0
           LEFT JOIN sHrm.tEmployeeCommunications ECW ON EMW.Id=ECW.EmployeeId 
           LEFT JOIN sHrm.tEmployeeCommunications ECA ON  EMA.Id=ECA.EmployeeId
           LEFT JOIN 
           ( SElect AR1.SourceId,
           VM.Title AS VehicleName,
		    VM.RegistrationNumber AS VehicleRegistrationNumber,
		    TV.Title AS TypeOfVehicle,
		    ISNULL(BRM.Title,'') AS BusRoute,
		    BRM.DriverName,
		    BRM.DriverMobileNo,
		    BRM.ConductorName,
		    BRM.ConductorMobileNo,
		    ISNULL(BRDM.Title,'') AS BusRouteDestination,
		    VM.Title AS DropVehicleName,
		    VM.RegistrationNumber AS DropVehicleRegistrationNumber,
		    TV1.Title AS DropTypeOfVehicle,
		    ISNULL(BRM1.Title,'') AS DropRoute,
		    BRM1.DriverName AS DropRouteDriverName,
		    BRM1.DriverMobileNo AS DropRouteDriverMobileNo,
		    BRM1.ConductorName AS DropRouteConductorName,
		    BRM1.ConductorMobileNo AS DropRouteConductorMobileNo,
		    ISNULL(BRDM1.Title,'') AS DropDestination
		      FROM
             sTransport.tAssignRoute AR1   
           INNER JOIN sTransport.tBusRouteDestinationMaster BRDM ON BRDM.Id=AR1.PickupDestinationId AND AR1.SourceTypeId=2003
           INNER JOIN sTransport.tBusRouteMaster BRM ON BRM.Id=BRDM.BusRouteId AND ((BRM.OrgGroupBatchId=@rOrgGroupBatchId) OR(@rOrgGroupBatchId=0))
           LEFT JOIN sTransport.tVehicleMaster VM ON VM.Id=BRM.VehicleId
           LEFT JOIN sTransport.tVehicleTypeMaster TV ON TV.Id = VM.VehicleTypeId
           LEFT JOIN sTransport.tBusRouteDestinationMaster BRDM1 ON BRDM1.Id=AR1.DropDestinationId
           LEFT JOIN sTransport.tBusRouteMaster BRM1 ON BRM1.Id=BRDM1.BusRouteId AND ((BRM1.OrgGroupBatchId=@rOrgGroupBatchId) OR(@rOrgGroupBatchId=0))
           LEFT JOIN sTransport.tVehicleMaster VM1 ON VM1.Id=BRM1.VehicleId
           LEFT JOIN sTransport.tVehicleTypeMaster TV1 ON TV1.Id = VM1.VehicleTypeId) A ON A.SourceId=SA.StudentId
           LEFT JOIN sSetup.tDivisionMaster DM ON  DM.Id=SA.DivisionId
           LEFT JOIN sHrm.tEmployeeMaster EMT ON EMT.Id=DM.InchargeEmployeeId AND  ISNULL(EMT.IsOtherUser,0) = 0
           LEFT JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EMT.Id
           LEFT JOIN sHrm.tEmployeeDesignationMaster EDM ON EDM.Id=EJD.EmployeeDesignationId
           LEFT JOIN sHrm.tEmployeePersonalDetail EPD ON EPD.EmployeeId=EMT.Id
           LEFT JOIN sHrm.tEmployeeImages EI ON EI.EmployeeId=EMT.Id
           LEFT JOIN sStudent.tStudentSibling  SS ON SS.StudentId=SA.StudentId 
           LEFT JOIN sStudent.tStudentAdditional  SAD ON SAD.StudentId=SA.StudentId 
           LEFT JOIN sStudent.tCollegeDetail  CD ON CD.StudentId=SA.StudentId 
           LEFT JOIN sStudent.tAcademicDetail  ACD ON ACD.AcademicId=SA.AcademicId 
           LEFT JOIN sCommon.tMaritalStatusMaster  MS ON MS.Id=CD.MaritalStatusId
           LEFT JOIN sConfig.fDisplayFieldGet(@rOrgId) AS DF ON DF.OrgId=SA.OrgId
           LEFT JOIN sCommon.tCastCategoryMaster CT ON CT.Id = SA.CastCategoryId
           LEFT JOIN sCommon.tCountryMaster CM ON CM.Id=SA.NationalityId
           INNER JOIN sSetup.tBatchClass BC ON BC.ClassID =  SA.ClassID and BC.BatchId= @rBatchId
           LEFT JOIN sCommunication.tCustomGroupMember CGM ON CGM.SourceId = SA.StudentId AND CGM.SourceTypeId = 2003
           LEFT JOIN sCommunication.tCustomGroup CGG ON CGG.Id = CGM.CustomGroupId
           LEFT JOIN sStudent.tStudentMaster SMM ON SMM.Id = SA.StudentId
           LEFT JOIN sStudent.tStudentGroupMaster SGM ON SGM.Id = SMM.StudentGroupId
           LEFT JOIN sStudent.tStudentOtherGroupMaster SOGM ON SOGM.Id = SMM.StudentOtherGroupId
		   LEFT JOIN sStudent.tStudentAdmission SAM ON SAM.StudentId = SA.StudentId
  WHERE 
			((SA.StudentId=@rStudentId)OR(@rStudentId=0))
			AND((SA.BatchId=@rBatchId) OR(@rBatchId=0))
			AND (ISNULL(SA.Code,0) IN( SELECT cast(item as nvarchar(20)) FROM  sCommon.fnsplit(@rStrCode,',')) OR @rStrCode='') 
			AND ((SA.ClassId=@rClassId) OR (@rClassId=0))
			AND ((SA.DivisionId=@rDivisionId) OR (@rDivisionId=0))
			AND ((SA.StudentId=@rStudentId) OR (@rStudentId=0))
			AND ((SA.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
			AND ((SA.RollNo <= @rToRollNo) OR (@rToRollNo=0))
			AND ((SA.StatusId=@rStatusId)OR(@rStatusId=0))
			AND ((SA.ClassStatusId=@rClassStatusId)OR(@rClassStatusId=0))
			AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
			AND ((SA.OrgGroupBatchId=@rOrgGroupBatchId) OR(@rOrgGroupBatchId=0))
			AND ((SA.AdmissionDate >= @rFromAdmissionDate) OR (ISNULL(@rFromAdmissionDate,'') = ''))
			AND ((SA.AdmissionDate <= @rToAdmissionDate) OR (ISNULL(@rToAdmissionDate,'') = ''))
			--AND(SA.OrgId=@rOrgId)
			
END
GO
PRINT N'Altering [sStudent].[pStudentGenerateReport]...';


GO

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

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

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


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

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

	SELECT @lIsStudentCommonSearchBatchWise = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 508 AND SourceTypeId = 2010 AND SourceId = @rOrgId

	SELECT @lOrgGroupId = OGBM.OrgGroupId FROM sSetup.tBatchMaster BM INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id = BM.OrgGroupBatchId WHERE BM.Id=@rBatchId
	SELECT @lConfigValue = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 480 AND SourceTypeId = 2010 AND SourceId = @rOrgId
	
	IF (@lIsStudentCommonSearchBatchWise = 'True')
	BEGIN
		IF(@rRollNo IS NULL)  
		BEGIN  
			SELECT   
			  SA.AcademicId,  
			  SA.StudentId,  
			  SA.FirstName,  
			  SA.LastName,  
			  SA.MiddleName,  
			  SA.Name,  
			  SA.Code,  
			  SA.ClassId,  
			  SA.ClassName,  
			  SA.DivisionId,  
			  SA.DivisionName,  
			  SA.Number,  
			  SA.RollNo,  
			  SA.StatusId,  
			  SA.StatusName,  
			  SA.OrgId,  
			  ISNULL(SA.AdmissionCategoryId,0) AS AdmissionCategoryId,  
			  SA.BatchId,  
			  SA.SUId,  
			  ISNULL(So.GenderId,0) AS GenderId,
			  ISNULL(SC.ParentContactNo,'') AS ParentContactNo
			   
			 FROM   
			         sStudent.vStudentAcademic SA  
			          LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId=SA.StudentId  
					  LEFT JOIN sStudent.tStudentCommunication SC ON SA.StudentId = SC.StudentId
			 WHERE   
			  
			 ((SA.ClassId=@rClassId)OR(@rClassId=0))  
			 AND((SA.DivisionId=@rDivisionId)OR(@rDivisionId=0))  
			 AND((SA.Code=@rCode) OR (ISNULL(@rCode,'') = ''))   
			 AND((SA.FirstName like @rFirstName) OR (ISNULL(@rFirstName,'') = ''))   
			 AND((SA.LastName like @rLastName) OR (ISNULL(@rLastName,'') = ''))   
			 AND((SA.StatusId=@rStatusId)OR(@rStatusId=0))   
			 AND(SA.OrgId=@rOrgId OR @rOrgId = 0)  
			 AND ( OrgGroupBatchId = @rOrgGroupBatchId or @rOrgGroupBatchId = 0)   
			 AND(SA.BatchId=@rBatchId or @rBatchId = 0)  
			 AND((SA.SUId=@rSUId) OR (ISNULL(@rSUId,'') = ''))  
			 
			ORDER BY SA.ClassId,SA.DivisionId,SA.RollNo  
		END  
		ELSE  
		BEGIN  
			SELECT   
			  SA.AcademicId,  
			  SA.StudentId,  
			  SA.FirstName,  
			  SA.LastName,  
			  SA.MiddleName,  
			  SA.Name,  
			  SA.Code,  
			  SA.ClassId,  
			  SA.ClassName,  
			  SA.DivisionId,  
			  SA.DivisionName,  
			  SA.Number,  
			  SA.RollNo,  
			  SA.StatusId,  
			  SA.StatusName,  
			  SA.OrgId,
			  ISNULL(SA.AdmissionCategoryId,0) AS AdmissionCategoryId ,  
			  SA.SUId,  
			  ISNULL(So.GenderId,0) AS GenderId,
			  ISNULL(SC.ParentContactNo,'') AS ParentContactNo

			 FROM   
			         sStudent.vStudentAcademic SA      
			          LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId=SA.StudentId           
					  LEFT JOIN sStudent.tStudentCommunication SC ON SA.StudentId = SC.StudentId
			 WHERE   
			  
			 ((SA.ClassId=@rClassId)OR(@rClassId=0))  
			 AND((SA.DivisionId=@rDivisionId)OR(@rDivisionId=0))  
			 AND((SA.Code=@rCode) OR (ISNULL(@rCode,'') = ''))   
			 AND((SA.FirstName like @rFirstName) OR (ISNULL(@rFirstName,'') = ''))   
			 AND((SA.LastName like @rLastName) OR (ISNULL(@rLastName,'') = ''))   
			 AND(SA.RollNo=@rRollNo)  
			 AND((SA.StatusId=@rStatusId)OR(@rStatusId=0))   
			 AND((SA.OrgId=@rOrgId) OR (@rOrgId=0))  
			 AND ( OrgGroupBatchId = @rOrgGroupBatchId or @rOrgGroupBatchId = 0)   
			 AND(SA.BatchId=@rBatchId or @rBatchId = 0) 
			 AND((SA.SUId=@rSUId) OR (ISNULL(@rSUId,'') = ''))    
			 
			ORDER BY SA.ClassId,SA.DivisionId,SA.RollNo  
		END  
	END

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

		IF(@rRollNo IS NULL)
		BEGIN
			SELECT 
				SA.AcademicId,
				SA.StudentId,
				SA.FirstName,
				SA.LastName,
				SA.MiddleName,
				SA.Name,
				SA.Code,
				SA.ClassId,
				SA.ClassName,
				SA.DivisionId,
				SA.DivisionName,
				SA.Number,
				SA.RollNo,
				SA.StatusId,
				SA.StatusName,
				SA.OrgId,
				ISNULL(SA.AdmissionCategoryId,0) AS AdmissionCategoryId,
				SA.BatchId,
				SA.SUId,
				ISNULL(So.GenderId,0) AS GenderId,
				ISNULL(SC.ParentContactNo,'') AS ParentContactNo
		
			FROM 
	            sStudent.vStudentAcademic SA
	            LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId=SA.StudentId
	            INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId AND SA.OrgGroupBatchId = BM.OrgGroupBatchId
				LEFT JOIN sStudent.tStudentCommunication SC ON SA.StudentId = SC.StudentId
			WHERE 
				((SA.ClassId=@rClassId)OR(@rClassId=0))
				AND((SA.DivisionId=@rDivisionId)OR(@rDivisionId=0))
				AND((SA.Code=@rCode) OR (ISNULL(@rCode,'') = '')) 
				AND((SA.FirstName like @rFirstName) OR (ISNULL(@rFirstName,'') = '')) 
				AND((SA.LastName like @rLastName) OR (ISNULL(@rLastName,'') = '')) 
				AND((SA.StatusId=@rStatusId)OR(@rStatusId=0))	
				AND(SA.OrgId=@rOrgId OR @rOrgId = 0)
				AND (SA.OrgGroupBatchId = @rOrgGroupBatchId	or @rOrgGroupBatchId = 0)	
				AND(SA.BatchId=@rBatchId or @rBatchId = 0)
				AND((SA.SUId=@rSUId) OR (ISNULL(@rSUId,'') = ''))
				AND BM.IsInContext = @lIsInContext
	
			ORDER BY SA.ClassId,SA.DivisionId,SA.RollNo
		END

		ELSE
		BEGIN
			SELECT 
					SA.AcademicId,
					SA.StudentId,
					SA.FirstName,
					SA.LastName,
					SA.MiddleName,
					SA.Name,
					SA.Code,
					SA.ClassId,
					SA.ClassName,
					SA.DivisionId,
					SA.DivisionName,
					SA.Number,
					SA.RollNo,
					SA.StatusId,
					SA.StatusName,
					SA.OrgId,
					--SA.Age,
					ISNULL(SA.AdmissionCategoryId,0) AS AdmissionCategoryId ,
					SA.SUId,
					ISNULL(So.GenderId,0) AS GenderId
					
			FROM 
		            sStudent.vStudentAcademic SA    
		            LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId=SA.StudentId       
		            INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId AND SA.OrgGroupBatchId = BM.OrgGroupBatchId  
			WHERE 
					((SA.ClassId=@rClassId)OR(@rClassId=0))
					AND((SA.DivisionId=@rDivisionId)OR(@rDivisionId=0))
					AND((SA.Code=@rCode) OR (ISNULL(@rCode,'') = '')) 
					AND((SA.FirstName like @rFirstName) OR (ISNULL(@rFirstName,'') = '')) 
					AND((SA.LastName like @rLastName) OR (ISNULL(@rLastName,'') = '')) 
					AND(SA.RollNo=@rRollNo)
					AND((SA.StatusId=@rStatusId)OR(@rStatusId=0))	
					AND((SA.OrgId=@rOrgId) OR (@rOrgId=0))
					AND (SA.OrgGroupBatchId = @rOrgGroupBatchId	or @rOrgGroupBatchId = 0)	
					AND(SA.BatchId=@rBatchId or @rBatchId = 0)
					AND((SA.SUId=@rSUId) OR (ISNULL(@rSUId,'') = '')) 
					AND BM.IsInContext = @lIsInContext
			ORDER BY SA.ClassId,SA.DivisionId,SA.RollNo
		END
	END
END
GO
PRINT N'Altering [sStudent].[pValidateImportAdmissionInquiry]...';


GO
ALTER PROCEDURE [sStudent].[pValidateImportAdmissionInquiry]

	@rOrgGroupId int,
    @rOrgId int,
	@rXmldoc [nvarchar](max)
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
DECLARE @lCount INT
DECLARE @lInterrorCode INT,
		@intDoc INT,
        
        @lClass nvarchar(100),
        @lInquiryDate nvarchar(15),
		@lInquiryStatus nvarchar(50),
        @lDOB nvarchar(15),             
        @1ReturnCode int = 1,
        @1ValidInquiryDate nvarchar(max)='',
        @1ValidDOB nvarchar(max) = '' 
       
       
EXECUTE @lInterrorCode = sp_xml_preparedocument @intDoc OUTPUT, @rXmlDoc
 
CREATE TABLE #tTable1 
 (
		Id bigint identity,
        FirstName nvarchar(100),
        MiddleName nvarchar(100),
        LastName nvarchar(100),
		Class nvarchar(100),
		
		InquiryDate nvarchar(15), 
        InquiryStatus nvarchar(50),
        DOB nvarchar(15),
        Gender nvarchar(10),
		InquiryMode nvarchar(50)  
	 
 
  )
  INSERT INTO #tTable1
	(
	    
	    FirstName,
	    MiddleName,
	    LastName,
	    Class,
	    InquiryDate,
	    InquiryStatus,
	    DOB,
	    Gender,
		InquiryMode
	    
    ) 
   SELECT
       
	    FirstName,
	    MiddleName,
	    LastName,
	    Class,
	    InquiryDate,
	    InquiryStatus,
	    DOB,
	    Gender,
		InquiryMode
	  
   
   FROM OPENXML (@intDoc, '/Table/ImportStudent', 1)
   With
   (
        
        FirstName nvarchar(100) '@FirstName',
        MiddleName  nvarchar(100) '@MiddleName',
        LastName nvarchar(100) '@LastName',
		Class nvarchar(100) '@Class',
		InquiryDate nvarchar(15) '@InquiryDate',
		InquiryStatus nvarchar(50) '@InquiryStatus',
		DOB nvarchar(15) '@DOB',
		Gender nvarchar(10) '@Gender' ,
		InquiryMode nvarchar(50) '@InquiryMode'
   )   
EXEC sp_xml_removedocument @intDoc
		
SELECT @lCount =  COUNT(Id) FROM #tTable1
 
WHILE @lCount > 0 
  BEGIN
  
    IF(ISDATE(@lInquiryDate) = 0 AND @lInquiryDate!='')
	BEGIN    
		SET @1ValidInquiryDate = @1ValidInquiryDate + @lInquiryDate+','
	END
	IF(ISDATE(@lDOB) = 0 AND @lDOB!='')
	BEGIN
		SET @1ValidDOB=@1ValidDOB +   @lDOB+','
	END
     SET @lCount = @lCount - 1	
   END	
    
   
   SELECT @lCount =  COUNT(Id) FROM #tTable1
 
	WHILE @lCount > 0 
		BEGIN
			SELECT         
			 @lClass = Class 
			FROM #tTable1 WHERE Id = @lCount

			IF NOT EXISTS (SELECT 1 FROM  
					 sSetup.tClassMaster CM  
						WHERE CM.Title COLLATE DATABASE_DEFAULT =@lClass COLLATE DATABASE_DEFAULT  )	
			BEGIN
				
				SELECT 'Enter proper value for Class ' + @lClass   AS StudentCode
				RETURN
			END
			SET @lCount = @lCount - 1	
		END
   	
		   
		 
		  IF EXISTS(SELECT 1 FROM #tTable1 WHERE LastName IS NULL OR LastName COLLATE DATABASE_DEFAULT ='' COLLATE DATABASE_DEFAULT)
		BEGIN
			SELECT 'Surname Should not be empty' AS StudentCode
		END
		ELSE IF EXISTS(SELECT 1 fROM #tTable1 WHERE FirstName IS NULL OR FirstName COLLATE DATABASE_DEFAULT ='' COLLATE DATABASE_DEFAULT)
		BEGIN
			SELECT 'First Name Should not be empty' AS StudentCode
		END
		ELSE IF EXISTS(SELECT 1 fROM #tTable1 WHERE MiddleName IS NULL OR MiddleName COLLATE DATABASE_DEFAULT ='' COLLATE DATABASE_DEFAULT)
		BEGIN
			SELECT 'Middle Name Should not be empty' AS StudentCode
		END
		ELSE IF EXISTS(SELECT 1 fROM #tTable1 WHERE Class IS NULL OR Class COLLATE DATABASE_DEFAULT ='' COLLATE DATABASE_DEFAULT)
		BEGIN
			SELECT 'Class Should not be empty' AS StudentCode
		END
		 
	 
		ELSE IF EXISTS(SELECT 1 fROM #tTable1 WHERE Gender IS NULL OR Gender COLLATE DATABASE_DEFAULT ='' COLLATE DATABASE_DEFAULT)
		BEGIN
			SELECT 'Gender Should not be empty' AS StudentCode
		END
 
		ELSE IF EXISTS(SELECT 1 fROM #tTable1 WHERE Class  COLLATE DATABASE_DEFAULT NOT IN(SELECT Title FROM sSetup.tClassMaster WHERE OrgId=@rOrgId))
		BEGIN
			SELECT 'Enter proper value for Class as per Institute Setup > Class Master' AS StudentCode
		END				
		 
		ELSE IF EXISTS(SELECT 1 fROM #tTable1 WHERE Gender COLLATE DATABASE_DEFAULT !='' COLLATE DATABASE_DEFAULT AND Gender NOT IN(SELECT Title FROM sCommon.tGenderMaster))
		BEGIN
			SELECT 'Enter proper value / Check spelling for gender ( Male / Female )' AS StudentCode
		END
		--ELSE IF EXISTS(SELECT 1 fROM #tTable1 WHERE AdmissionCategory!='' AND AdmissionCategory NOT IN(SELECT Title FROM sStudent.tAdmissionCategoryMaster))
		--BEGIN
		--	SELECT 'Enter proper value for Cast Category (Indian,NRI,General)' AS StudentCode
		--END
			 
		Else if Exists(Select 1 from #tTable1 where InquiryStatus COLLATE DATABASE_DEFAULT !='' COLLATE DATABASE_DEFAULT AND InquiryStatus NOT IN (Select Title from sAdmission.tInquiryStatusMaster))
		Begin
			Select 'Enter proper Value or check Spelling for Inquiry Status' AS StudentCode
		End
		ELSE IF EXISTS(SELECT 1 fROM #tTable1 WHERE InquiryStatus IS NULL OR InquiryStatus COLLATE DATABASE_DEFAULT ='' COLLATE DATABASE_DEFAULT)
		BEGIN
			SELECT 'Inquiry Status Should not be empty ' AS StudentCode
		END
		ELSE IF NOT EXISTS(SELECT 1 FROM #tTable1 WHERE InquiryMode IN(SELECT Title FROM sAdmission.tInquiryModeMaster ) OR InquiryMode='')
		BEGIN
			SELECT 'Inquiry Mode is not proper as per Inquiry Mode Master' AS StudentCode
		END

		ELSE
			
		BEGIN
			IF((@1ValidInquiryDate IS NULL OR @1ValidInquiryDate = '') AND (@1ValidDOB IS NULL OR @1ValidDOB = ''))
		BEGIN
			SELECT '' AS StudentCode
		END
		
		 ELSE IF (@1ValidDOB IS NOT NULL AND @1ValidDOB != '')
		BEGIN
			SET @1ValidDOB = 'Wrong DOB ' + @1ValidDOB
			Select @1ValidDOB AS StudentCode
		END
		
		END
		 
END
GO
PRINT N'Altering [sTally].[pReceiptPostingGet]...';


GO

ALTER PROCEDURE [sTally].[pReceiptPostingGet]

	 @rOrgGroupBatchId int,
	 @rReceiptBookId int,
	 @rReceiptDate Date,
	 @rToReceiptDate Date,
	 @rPayTypeId int = 0,
	 @rCustomNarration nvarchar(max)='',
	 @rIsCustomNarration bit=0
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
	
	DECLARE @lTallyPostingType nVarchar(100)
	DECLARE @lOrgGroupId INT
	
	SELECT @lOrgGroupId = OrgGroupId from sSetup.tOrgGroupBatchMaster Where Id=@rOrgGroupBatchId
	
	SELECT @lTallyPostingType = CASE WHEN CS.ItemValue IS NULL THEN C.ItemValue ELSE CS.ItemValue END 
		FROM sConfig.tConfigurationMaster C
        INNER JOIN sConfig.tConfigurationLevelMaster CM ON CM.Id = C.ConfigurationLevelId
        LEFT JOIN sConfig.tConfigurationSetup CS ON CS.ConfigurationId = C.Id AND CS.SOURCEID= @lOrgGroupId
        WHERE  C.ItemKey = 'Tally.PostingType'
        
		
        IF @lTallyPostingType = 'FeeHeadWise' 
        BEGIN
			   SELECT	ReceiptDate,
						ISNULL(FHM.Title,'') AS FeeName,
						PM.Title AS PayType,
						Sum(FRD.Amount) AS Amount,
						Case when @rIsCustomNarration=1 then STUFF((SELECT ','  +Replace(replace(
																					Replace(
																					replace(
																					Replace(
																					replace(
																					Replace(
																					replace(
																					Replace(
																					replace(
																					Replace(
																					replace(
																					Replace(
																					replace(
																					Replace(
																					replace(
																					replace(
																					@rCustomNarration,'[Class]',isnull(SM1.ClassName,'')
																					),'[Division]',Isnull(SM1.DivisionName,'')
																					),'[StudentsName]',isnull(SM1.Name,'')
																					), '[RollNumber]',isnull(convert(nvarchar(200),SM1.RollNo),'0')
																					),'[Batch]',isnull(SM1.BatchName,'')
																					), '[ReceiptNumber]', isnull(Convert(nvarchar(100),FR1.ReceiptNumber),'')
																					), '[ReceiptDate]',isnull(Convert(nvarchar(100),FR1.ReceiptDate),'')
																					), '[ReceiptAmount]',isnull(Convert(nvarchar(100),FR1.ReceiptAmount),'')
																					), '[ChequeNo]',isnull(Convert(nvarchar(100),FR1.ChequeNo),'')
																					),'[BankName]',isnull(FR1.BankName,'')
																					),'[FeeName]',isnull(FM1.Title,'')
																					), '[FeeAmount]',isnull(Convert(nvarchar(100),Sum(FRD.Amount)),'0.00')
																					),'[FeeHeadName]',ISNULL(FHM.Title,'')
																					), '[FeeHeadAmount]',isnull(Convert(nvarchar(100),Sum(FRD.Amount)),'0.00')
																					), '[CollectionGroupName]',isNull(CGM1.Title,'')
																					),'[ReceiptFromNumber]',isnull(Convert(nvarchar(10),(Select Min(ReceiptNumber) from sFee.tReceipt where   FR.ReceiptDate =ReceiptDate)),'')
																					), '[ReceiptToNumber]',isnull(Convert(nvarchar(10),(Select Max(ReceiptNumber) from sFee.tReceipt Where FR.ReceiptDate = ReceiptDate)),''))
						from sFee.tReceipt FR1  INNER JOIN sFee.tReceiptDetail FRD1 ON FR1.Id = FRD1.ReceiptId
						INNER JOIN sFee.tFeeSetup FS1 ON FS1.Id = FRD1.FeeSetupId 
						INNER JOIN sStudent.vStudentAcademic SM1 ON SM1.ACademicId = FR1.SourceID AND SM1.OrgGRoupBatchId = FR1.OrgGRoupBatchId 						
						INNER JOIN sFee.tFeeMaster FM1 ON FM1.Id = FS1.FeeId --AND FRD.ReceiptId=FRD1.ReceiptId
						LEFT JOIN sFee.tCollectionGroupMaster CGM1 ON CGM1.Id = FS1.CollectionGroupId
						INNER JOIN sFee.tFeeHeadMaster FHM1 ON FHM1.Id = FM1.FeeHeadId AND FHM1.Id=FHM.Id where  FR.ReceiptDate=FR1.ReceiptDate FOR XML PATH('')),1,1,'') else
						 'Receipt generated for Batch : ' + (Select Title from sSetup.tOrgGroupBatchMaster Where Id= @rOrgGroupBatchId) +
						' Receipt Date : ' +  Convert(nvarchar(10),ReceiptDate) + ' and Receipt Number From ' + Convert(nvarchar(10),(Select Min(ReceiptNumber) from sFee.tReceipt where   FR.ReceiptDate =ReceiptDate AND IsObsolete = 0 )) + ' -  ' + 
						Convert(nvarchar(10),(Select Max(ReceiptNumber) from sFee.tReceipt Where FR.ReceiptDate = ReceiptDate AND IsObsolete = 0)) end as Narration,						
						FR.PayTypeId AS PayTypeId, 
						FHM.Id AS FeeId,
						0 AS ReceiptId
				FROM sFee.tReceipt FR 
					INNER JOIN sFee.tReceiptDetail FRD ON FR.Id = FRD.ReceiptId
					INNER JOIN sFee.tFeeSetup FS ON FS.Id = FRD.FeeSetupId
					INNER JOIN sFee.tFeeMaster FM ON FM.Id = FS.FeeId
					INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id = FM.FeeHeadId
					INNER JOIN sFinanceCommon.tPayTypeMaster PM ON PM.Id = FR.PayTypeId
					WHERE	FR.ReceiptBookId = @rReceiptBookId 
							AND FR.IsObsolete = 0 
							AND FR.OrgGroupBatchId = @rOrgGroupBatchId
							AND FR.ReceiptDate >= @rReceiptDate AND FR.ReceiptDate <= @rToReceiptDate
							AND (FR.PayTypeId = @rPayTypeId OR @rPayTypeId = 0)
				group by ReceiptDate,FHM.Title,PM.Title,FHM.Id,FR.PayTypeId
				Order By ReceiptDate Desc
			END				
       ELSE IF @lTallyPostingType = 'FeeHeadWiseCustom' 
        BEGIN
			   SELECT	ReceiptDate,
						FR.Id AS FeeName,
						PM.Title AS PayType,
						Sum(FRD.Amount) AS Amount,
						Case when @rIsCustomNarration=1 then  STUFF((SELECT ','  +Replace(replace(
																					Replace(
																					replace(
																					Replace(
																					replace(
																					Replace(
																					replace(
																					Replace(
																					replace(
																					Replace(
																					replace(
																					Replace(
																					replace(
																					Replace(
																					replace(
																					replace(
																					@rCustomNarration,'[Class]',isnull(SM1.ClassName,'')
																					),'[Division]',Isnull(SM1.DivisionName,'')
																					),'[StudentsName]',isnull(SM1.Name,'')
																					), '[RollNumber]',isnull(convert(nvarchar(200),SM1.RollNo),'0')
																					),'[Batch]',isnull(SM1.BatchName,'')
																					), '[ReceiptNumber]', isnull(Convert(nvarchar(100),FR1.ReceiptNumber),'')
																					), '[ReceiptDate]',isnull(Convert(nvarchar(100),FR1.ReceiptDate),'')
																					), '[ReceiptAmount]',isnull(Convert(nvarchar(100),FR1.ReceiptAmount),'')
																					), '[ChequeNo]',isnull(Convert(nvarchar(100),FR1.ChequeNo),'')
																					),'[BankName]',isnull(FR1.BankName,'')
																					),'[FeeName]',isnull(FM1.Title,'')
																					), '[FeeAmount]',isnull(Convert(nvarchar(100),Sum(FRD.Amount)),'0.00')
																					),'[FeeHeadName]',ISNULL(FHM1.Title,'')
																					), '[FeeHeadAmount]',isnull(Convert(nvarchar(100),Sum(FRD.Amount)),'0.00')
																					), '[CollectionGroupName]',isNull(CGM1.Title,'')
																					),'[ReceiptFromNumber]',isnull(Convert(nvarchar(10),(Select Min(ReceiptNumber) from sFee.tReceipt where   FR.ReceiptDate =ReceiptDate AND IsObsolete = 0)),'')
																					), '[ReceiptToNumber]',isnull(Convert(nvarchar(10),(Select Max(ReceiptNumber) from sFee.tReceipt Where FR.ReceiptDate = ReceiptDate AND IsObsolete = 0)),''))
						from sFee.tReceipt FR1  INNER JOIN sFee.tReceiptDetail FRD1 ON FR1.Id = FRD1.ReceiptId
						INNER JOIN sFee.tFeeSetup FS1 ON FS1.Id = FRD1.FeeSetupId 
						INNER JOIN sStudent.vStudentAcademic SM1 ON SM1.ACademicId = FR1.SourceID AND SM1.OrgGRoupBatchId = FR1.OrgGRoupBatchId 						
						INNER JOIN sFee.tFeeMaster FM1 ON FM1.Id = FS1.FeeId --AND FRD.ReceiptId=FRD1.ReceiptId
						LEFT JOIN sFee.tCollectionGroupMaster CGM1 ON CGM1.Id = FS1.CollectionGroupId
						INNER JOIN sFee.tFeeHeadMaster FHM1 ON FHM1.Id = FM1.FeeHeadId  where   FR.ReceiptDate=FR1.ReceiptDate AND FR.Id=FR1.Id AND FR1.IsObsolete = 0  FOR XML PATH('')),1,1,'') else
						SM.Name + '(' + ClassName + ':' + DivisionName + ') ' + ' # Cheque No. :' + ISNULL(FR.ChequeNo,'') + ' BankName :' + ISNULL(FR.BankName,'') end as Narration,						
						FR.PayTypeId AS PayTypeId, 
						0 AS FeeId,
						FR.Id AS ReceiptId
				FROM sFee.tReceipt FR 
					INNER JOIN sFee.tReceiptDetail FRD ON FR.Id = FRD.ReceiptId
					INNER JOIN sStudent.vStudentAcademic SM ON SM.ACademicId = FR.SourceID AND SM.OrgGRoupBatchId = FR.OrgGRoupBatchId 
					INNER JOIN sFee.tFeeSetup FS ON FS.Id = FRD.FeeSetupId
					INNER JOIN sFee.tFeeMaster FM ON FM.Id = FS.FeeId
					INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id = FM.FeeHeadId
					INNER JOIN sFinanceCommon.tPayTypeMaster PM ON PM.Id = FR.PayTypeId
					INNER JOIN sSetup.tOrganizationMaster OM ON  OM.Id=SM.OrgId
					LEFT JOIN sSetup.tOrgSubGroupMaster OSM ON OSM.id=OM.OrgSubGroupId

					WHERE	FR.ReceiptBookId= @rReceiptBookId 
							AND FR.IsObsolete = 0 
							AND FR.OrgGroupBatchId = @rOrgGroupBatchId
							AND FR.ReceiptDate >= @rReceiptDate AND FR.ReceiptDate <= @rToReceiptDate
							AND (FR.PayTypeId = @rPayTypeId OR @rPayTypeId = 0)
				group by ReceiptDate,PM.Title,FR.PayTypeId,FR.Id,SM.Name + '(' + ClassName + ':' + DivisionName + ') ' + ' # Cheque No. :' + ISNULL(FR.ChequeNo,'') + ' BankName :' + ISNULL(FR.BankName,'')
				Order By FR.Id,ReceiptDate Desc
			END	

       ELSE IF @lTallyPostingType = 'OrgMainGroupWise' 
        BEGIN
			   SELECT	ReceiptDate,
						SM.AcademicId AS FeeName,
						PM.Title AS PayType,
						Sum(FRD.Amount) AS Amount,
						Case when @rIsCustomNarration=1 then  STUFF((SELECT ','  +Replace(replace(
																					Replace(
																					replace(
																					Replace(
																					replace(
																					Replace(
																					replace(
																					Replace(
																					replace(
																					Replace(
																					replace(
																					Replace(
																					replace(
																					Replace(
																					replace(
																					replace(
																					@rCustomNarration,'[Class]',isnull(SM1.ClassName,'')
																					),'[Division]',Isnull(SM1.DivisionName,'')
																					),'[StudentsName]',isnull(SM1.Name,'')
																					), '[RollNumber]',isnull(convert(nvarchar(200),SM1.RollNo),'0')
																					),'[Batch]',isnull(SM1.BatchName,'')
																					), '[ReceiptNumber]', isnull(Convert(nvarchar(100),FR1.ReceiptNumber),'')
																					), '[ReceiptDate]',isnull(Convert(nvarchar(100),FR1.ReceiptDate),'')
																					), '[ReceiptAmount]',isnull(Convert(nvarchar(100),FR1.ReceiptAmount),'')
																					), '[ChequeNo]',isnull(Convert(nvarchar(100),FR1.ChequeNo),'')
																					),'[BankName]',isnull(FR1.BankName,'')
																					),'[FeeName]',isnull(FM1.Title,'')
																					), '[FeeAmount]',isnull(Convert(nvarchar(100),Sum(FRD.Amount)),'0.00')
																					),'[FeeHeadName]',ISNULL(FHM1.Title,'')
																					), '[FeeHeadAmount]',isnull(Convert(nvarchar(100),Sum(FRD.Amount)),'0.00')
																					), '[CollectionGroupName]',isNull(CGM1.Title,'')
																					),'[ReceiptFromNumber]',isnull(Convert(nvarchar(10),FR1.ReceiptNumber),'')
																					), '[ReceiptToNumber]',isnull(Convert(nvarchar(10),FR1.ReceiptNumber),''))
						from sFee.tReceipt FR1  INNER JOIN sFee.tReceiptDetail FRD1 ON FR1.Id = FRD1.ReceiptId
						INNER JOIN sFee.tFeeSetup FS1 ON FS1.Id = FRD1.FeeSetupId 
						INNER JOIN sStudent.vStudentAcademic SM1 ON SM1.ACademicId = FR1.SourceID AND SM1.OrgGRoupBatchId = FR1.OrgGRoupBatchId 						
						INNER JOIN sFee.tFeeMaster FM1 ON FM1.Id = FS1.FeeId --AND FRD.ReceiptId=FRD1.ReceiptId
						LEFT JOIN sFee.tCollectionGroupMaster CGM1 ON CGM1.Id = FS1.CollectionGroupId
						INNER JOIN sFinanceCommon.tPayTypeMaster PM1 ON PM1.Id = FR1.PayTypeId
						INNER JOIN sFee.tFeeHeadMaster FHM1 ON FHM1.Id = FM1.FeeHeadId  where  FR.ReceiptDate=FR1.ReceiptDate AND PM.Title=PM1.Title AND SM.AcademicId=SM1.AcademicId AND  FR.PayTypeId=FR1.PayTypeId AND FR1.IsObsolete = 0  FOR XML PATH('')),1,1,'') else
						SM.Name + '(' + ClassName + ':' + DivisionName + ') ' + ' # Cheque No. :' + ISNULL(FR.ChequeNo,'') + ' BankName :' + ISNULL(FR.BankName,'') end as Narration,						
						FR.PayTypeId AS PayTypeId, 
						FR.Id AS FeeId,
						SM.AcademicId AS ReceiptId
				FROM sFee.tReceipt FR 
					INNER JOIN sFee.tReceiptDetail FRD ON FR.Id = FRD.ReceiptId
					INNER JOIN sStudent.vStudentAcademic SM ON SM.ACademicId = FR.SourceID AND SM.OrgGRoupBatchId = FR.OrgGRoupBatchId 
					INNER JOIN sFee.tFeeSetup FS ON FS.Id = FRD.FeeSetupId
					INNER JOIN sFee.tFeeMaster FM ON FM.Id = FS.FeeId
					INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id = FM.FeeHeadId
					INNER JOIN sFinanceCommon.tPayTypeMaster PM ON PM.Id = FR.PayTypeId
					INNER JOIN sSEtup.tOrganizationMaster OM ON OM.OrgSubGRoupID =  @rReceiptBookId AND OM.ID = SM.OrgId					
					WHERE	FR.IsObsolete = 0 
							AND FR.OrgGroupBatchId = @rOrgGroupBatchId
							AND FR.ReceiptDate >= @rReceiptDate AND FR.ReceiptDate <= @rToReceiptDate
							AND FR.PayTypeID = 2
							AND (FR.PayTypeId = @rPayTypeId OR @rPayTypeId = 0)
				group by ReceiptDate,PM.Title,SM.AcademicId ,FR.PayTypeId,FR.Id,SM.Name + '(' + ClassName + ':' + DivisionName + ') ' + ' # Cheque No. :' + ISNULL(FR.ChequeNo,'') + ' BankName :' + ISNULL(FR.BankName,'')
				Order By FR.Id,ReceiptDate Desc
			END	
	ELSE IF @lTallyPostingType = 'ReceiptWise' 
			BEGIN	
				SELECT	ReceiptDate,						
						ISNULL(SLM.LedgerName,'') AS FeeName,
						PM.Title AS PayType,						
						FR.ReceiptAmount AS Amount,
						Case when @rIsCustomNarration=1 then  STUFF((SELECT ','+  +Replace(
																					replace(
																					Replace(
																					replace(
																					Replace(
																					replace(
																					Replace(
																					replace(
																					Replace(
																					replace(
																					Replace(
																					replace(
																					Replace(
																					replace(
																					Replace(
																					replace(
																					replace(
																					@rCustomNarration,'[Class]',isnull(SM1.ClassName,'')
																					),'[Division]',Isnull(SM1.DivisionName,'')
																					),'[StudentsName]',isnull(SM1.Name,'')
																					), '[RollNumber]',isnull(convert(nvarchar(200),SM1.RollNo),'0')
																					),'[Batch]',isnull(SM1.BatchName,'')
																					), '[ReceiptNumber]', isnull(Convert(nvarchar(100),FR1.ReceiptNumber),'')
																					), '[ReceiptDate]',isnull(Convert(nvarchar(100),FR1.ReceiptDate),'')
																					), '[ReceiptAmount]',isnull(Convert(nvarchar(100),FR1.ReceiptAmount),'')
																					), '[ChequeNo]',isnull(Convert(nvarchar(100),FR1.ChequeNo),'')
																					),'[BankName]',isnull(FR1.BankName,'')
																					),'[FeeName]',isnull(FM1.Title,'')
																					), '[FeeAmount]',isnull(Convert(nvarchar(100),Sum(FRD.Amount)),'0.00')
																					),'[FeeHeadName]',ISNULL(FHM1.Title,'')
																					), '[FeeHeadAmount]',isnull(Convert(nvarchar(100),Sum(FRD.Amount)),'0.00')
																					), '[CollectionGroupName]',isNull(CGM1.Title,'')
																					),'[ReceiptFromNumber]',isnull(Convert(nvarchar(10),FR1.ReceiptNumber),'')
																					), '[ReceiptToNumber]',isnull(Convert(nvarchar(10),FR1.ReceiptNumber),''))
						from sFee.tReceipt FR1  INNER JOIN sFee.tReceiptDetail FRD1 ON FR1.Id = FRD1.ReceiptId
						INNER JOIN sFee.tFeeSetup FS1 ON FS1.Id = FRD1.FeeSetupId 
						INNER JOIN sStudent.vStudentAcademic SM1 ON SM1.ACademicId = FR1.SourceID AND SM1.OrgGRoupBatchId = FR1.OrgGRoupBatchId 						
						INNER JOIN sFee.tFeeMaster FM1 ON FM1.Id = FS1.FeeId --AND FRD.ReceiptId=FRD1.ReceiptId
						LEFT JOIN sFee.tCollectionGroupMaster CGM1 ON CGM1.Id = FS1.CollectionGroupId
						INNER JOIN sFinanceCommon.tPayTypeMaster PM1 ON PM1.Id = FR1.PayTypeId
						INNER JOIN sFee.tFeeHeadMaster FHM1 ON FHM1.Id = FM1.FeeHeadId
						LEFT JOIN sTally.tStudentLedgerMapping SLM1 ON SLM1.StudentId = SM1.StudentId AND SLM1.ReceiptBookid = FR1.ReceiptBookId AND SLM.LedgerName=SLM1.LedgerName where  FR1.ReceiptDate=FR.ReceiptDate   AND FR1.PayTypeId=FR.PayTypeId AND  A.StudentId=SM1.StudentId AND FR.ReceiptAmount=FR1.ReceiptAmount AND FR1.IsObsolete = 0  FOR XML PATH('')),1,1,'') else
						case When FR.PayTypeId = 1 then
						'Std-' + ClassName + ':' + DivisionName + ' RollNo :' + convert(nvarchar(20),RollNo) + ' ' + BatchName + '-->' +
						STUFF((SELECT ','  + convert(nvarchar(20),isnull(FRD1.Amount,'')) + '-' + isnull(FM1.Title ,'') 
						from sFee.tReceipt FR1  INNER JOIN sFee.tReceiptDetail FRD1 ON FR1.Id = FRD1.ReceiptId
						INNER JOIN sFee.tFeeSetup FS1 ON FS1.Id = FRD1.FeeSetupId 						
						INNER JOIN sFee.tFeeMaster FM1 ON FM1.Id = FS1.FeeId AND FRD.ReceiptId=FRD1.ReceiptId  FOR XML PATH('')),1,1,'') 
						when FR.PayTypeId <> 1 then 
						'Std-' + ClassName + ':' + DivisionName + ' RollNo :' + convert(nvarchar(20),RollNo) + ' ' + BatchName + '-->' +
						STUFF((SELECT ','  + convert(nvarchar(20),isnull(FRD1.Amount,'')) + '-' + isnull(FM1.Title ,'') 
						from sFee.tReceipt FR1  INNER JOIN sFee.tReceiptDetail FRD1 ON FR1.Id = FRD1.ReceiptId
						INNER JOIN sFee.tFeeSetup FS1 ON FS1.Id = FRD1.FeeSetupId 						
						INNER JOIN sFee.tFeeMaster FM1 ON FM1.Id = FS1.FeeId AND FRD.ReceiptId=FRD1.ReceiptId  FOR XML PATH('')),1,1,'') + '  Cheque No. :' + ISNULL(FR.ChequeNo,'') + ' BankName :' + ISNULL(FR.BankName,'')  ENd
						end AS Narration,
						--A.Name+', '+ClassName + '-' + DivisionName+', '+A.OrganizationName+', ('+BatchName+')'
						--AS Narration,					
						FR.PayTypeId AS PayTypeId,									
						A.StudentId AS FeeId,
						FRD.ReceiptId					 
				FROM sFee.tReceipt FR 
					INNER JOIN sFee.tReceiptDetail FRD ON FR.Id = FRD.ReceiptId
					INNER JOIN sFee.tFeeSetup FS ON FS.Id = FRD.FeeSetupId
					INNER JOIN sFee.tFeeMaster FM ON FM.Id = FS.FeeId
					INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id = FM.FeeHeadId
					INNER JOIN sFinanceCommon.tPayTypeMaster PM ON PM.Id = FR.PayTypeId
					INNER JOIN sStudent.vStudentAcademic A ON A.AcademicId = FR.SourceId AND A.OrgGRoupBatchId = FR.OrgGRoupBatchId
					LEFT JOIN sTally.tStudentLedgerMapping SLM ON SLM.StudentId = A.StudentId AND SLM.ReceiptBookid = FR.ReceiptBookId
					WHERE							
							FR.ReceiptBookId = @rReceiptBookId 
							AND FR.IsObsolete = 0 
							AND FR.OrgGroupBatchId = @rOrgGroupBatchId
							AND FR.ReceiptDate >= @rReceiptDate	And FR.ReceiptDate <= @rToReceiptDate
							AND (FR.PayTypeId = @rPayTypeId OR @rPayTypeId = 0)
				group by 
				ReceiptDate,PM.Title,
				SLM.LedgerName,FR.PayTypeId,A.StudentId,
				FRD.ReceiptId,Isnull(FR.ChequeNo,''),ISNull(FR.BankName,''),
				--A.Name+', '+ClassName + '-' + DivisionName+', '+A.OrganizationName+', ('+BatchName+')',
				'Std-' + ClassName + ':' + DivisionName + ' RollNo :' + convert(nvarchar(20),RollNo) + ' ' + BatchName,
				FR.ReceiptAmount			
				Order By ReceiptDate desc
			END		
			
	ELSE IF @lTallyPostingType = 'FeeHeadAndReceiptBookWise' 
			BEGIN	
				SELECT	ReceiptDate,						
						ISNULL(SLM.LedgerName,'') AS FeeName,
						PM.Title AS PayType,						
						FR.ReceiptAmount AS Amount,
						Case when @rIsCustomNarration=1 then STUFF((SELECT ','  +Replace(replace(
																					Replace(
																					replace(
																					Replace(
																					replace(
																					Replace(
																					replace(
																					Replace(
																					replace(
																					Replace(
																					replace(
																					Replace(
																					replace(
																					Replace(
																					replace(
																					replace(
																					@rCustomNarration,'[Class]',isnull(SM1.ClassName,'')
																					),'[Division]',Isnull(SM1.DivisionName,'')
																					),'[StudentsName]',isnull(SM1.Name,'')
																					), '[RollNumber]',isnull(convert(nvarchar(200),SM1.RollNo),'0')
																					),'[Batch]',isnull(SM1.BatchName,'')
																					), '[ReceiptNumber]', isnull(Convert(nvarchar(100),FR1.ReceiptNumber),'')
																					), '[ReceiptDate]',isnull(Convert(nvarchar(100),FR1.ReceiptDate),'')
																					), '[ReceiptAmount]',isnull(Convert(nvarchar(100),FR1.ReceiptAmount),'')
																					), '[ChequeNo]',isnull(Convert(nvarchar(100),FR1.ChequeNo),'')
																					),'[BankName]',isnull(FR1.BankName,'')
																					),'[FeeName]',isnull(FM1.Title,'')
																					), '[FeeAmount]',isnull(Convert(nvarchar(100),Sum(FRD.Amount)),'0.00')
																					),'[FeeHeadName]',ISNULL(FHM1.Title,'')
																					), '[FeeHeadAmount]',isnull(Convert(nvarchar(100),Sum(FRD.Amount)),'0.00')
																					), '[CollectionGroupName]',isNull(CGM1.Title,'')
																					),'[ReceiptFromNumber]',isnull(Convert(nvarchar(10),FR1.ReceiptNumber),'')
																					), '[ReceiptToNumber]',isnull(Convert(nvarchar(10),FR1.ReceiptNumber),''))
						from sFee.tReceipt FR1  INNER JOIN sFee.tReceiptDetail FRD1 ON FR1.Id = FRD1.ReceiptId
						INNER JOIN sFee.tFeeSetup FS1 ON FS1.Id = FRD1.FeeSetupId 
						INNER JOIN sStudent.vStudentAcademic SM1 ON SM1.ACademicId = FR1.SourceID AND SM1.OrgGRoupBatchId = FR1.OrgGRoupBatchId 						
						INNER JOIN sFee.tFeeMaster FM1 ON FM1.Id = FS1.FeeId --AND FRD.ReceiptId=FRD1.ReceiptId
						LEFT JOIN sFee.tCollectionGroupMaster CGM1 ON CGM1.Id = FS1.CollectionGroupId
						INNER JOIN sFinanceCommon.tPayTypeMaster PM1 ON PM1.Id = FR1.PayTypeId
						INNER JOIN sFee.tFeeHeadMaster FHM1 ON FHM1.Id = FM1.FeeHeadId 
						LEFT JOIN sTally.tStudentLedgerMapping SLM1 ON SLM1.StudentId = SM1.StudentId AND SLM1.ReceiptBookid = FR1.ReceiptBookId AND SLM.LedgerName=SLM1.LedgerName where  FR1.ReceiptDate=FR.ReceiptDate AND PM1.Title=PM.Title  AND FR1.PayTypeId=FR.PayTypeId AND A.StudentId=SM1.StudentId AND FR.ReceiptAmount=FR1.ReceiptAmount AND FR1.IsObsolete = 0  FOR XML PATH('')),1,1,'') else
						case When FR.PayTypeId = 1 then
						'Receiptno-'  + CONVERT(nvarchar,isnull(FR.ReceiptNumber,'')) + 
						STUFF((SELECT ','  + convert(nvarchar(20),isnull(FM1.title,'')) 
						from sFee.tReceipt FR1  INNER JOIN sFee.tReceiptDetail FRD1 ON FR1.Id = FRD1.ReceiptId And FRD1.ReceiptId = FRD.ReceiptId 
						INNER JOIN sFee.tFeeSetup FS1 ON FS1.Id = FRD1.FeeSetupId 						
						INNER JOIN sFee.tFeeMaster FM1 ON FM1.Id = FS1.FeeId AND FRD.ReceiptId=FRD1.ReceiptId  FOR XML PATH('')),1,1,'') 
						when FR.PayTypeId <> 1 then 
						'Receiptno-'  +  CONVERT(nvarchar,isnull(FR.ReceiptNumber,'')) +
						STUFF((SELECT ','  + convert(nvarchar(20),isnull(FM1.title,'')) 
						from sFee.tReceipt FR1  INNER JOIN sFee.tReceiptDetail FRD1 ON FR1.Id = FRD1.ReceiptId And FRD1.ReceiptId = FRD.ReceiptId 
						INNER JOIN sFee.tFeeSetup FS1 ON FS1.Id = FRD1.FeeSetupId 						
						INNER JOIN sFee.tFeeMaster FM1 ON FM1.Id = FS1.FeeId AND FRD.ReceiptId=FRD1.ReceiptId  FOR XML PATH('')),1,1,'') 
						+ '  Cheque No. :' + ISNULL(FR.ChequeNo,'') + ' BankName :' + ISNULL(FR.BankName,'')  ENd
						end AS Narration,
						FR.PayTypeId AS PayTypeId,									
						A.StudentId AS FeeId,
						FRD.ReceiptId		
									 
				FROM sFee.tReceipt FR 
					INNER JOIN sFee.tReceiptDetail FRD ON FR.Id = FRD.ReceiptId
					INNER JOIN sFee.tFeeSetup FS ON FS.Id = FRD.FeeSetupId
					INNER JOIN sFee.tFeeMaster FM ON FM.Id = FS.FeeId
					INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id = FM.FeeHeadId
					INNER JOIN sFinanceCommon.tPayTypeMaster PM ON PM.Id = FR.PayTypeId
					INNER JOIN sStudent.vStudentAcademic A ON A.AcademicId = FR.SourceId AND A.OrgGRoupBatchId = FR.OrgGRoupBatchId
					LEFT JOIN sTally.tStudentLedgerMapping SLM ON SLM.StudentId = A.StudentId AND SLM.ReceiptBookid = FR.ReceiptBookId
					WHERE							
							FR.ReceiptBookId = @rReceiptBookId 
							AND FR.IsObsolete = 0 
							AND FR.OrgGroupBatchId = @rOrgGroupBatchId
							AND FR.ReceiptDate >= @rReceiptDate	And FR.ReceiptDate <= @rToReceiptDate
							AND (FR.PayTypeId = @rPayTypeId OR @rPayTypeId = 0)
				group by 
				ReceiptDate,PM.Title,
				SLM.LedgerName,FR.PayTypeId,A.StudentId,
				FRD.ReceiptId,
				Isnull(FR.ChequeNo,''),ISNull(FR.BankName,''),
				'Std-' + ClassName + ':' + DivisionName + ' RollNo :' + convert(nvarchar(20),RollNo) + ' ' + BatchName,FR.ReceiptAmount,FR.ReceiptNumber
				--,FHM.Title
				
				Order By ReceiptDate desc	
			END	
	ELSE IF @lTallyPostingType = 'FeeHeadWiseReceipt_AllDetail' 
        BEGIN
			   SELECT	ReceiptDate,
						FR.Id AS FeeName,
						PM.Title AS PayType,
						Sum(FRD.Amount) AS Amount,
						Case when @rIsCustomNarration=1 then  STUFF((SELECT ','  +Replace(replace(
																					Replace(
																					replace(
																					Replace(
																					replace(
																					Replace(
																					replace(
																					Replace(
																					replace(
																					Replace(
																					replace(
																					Replace(
																					replace(
																					Replace(
																					replace(
																					replace(
																					@rCustomNarration,'[Class]',isnull(SM1.ClassName,'')
																					),'[Division]',Isnull(SM1.DivisionName,'')
																					),'[StudentsName]',isnull(SM1.Name,'')
																					), '[RollNumber]',isnull(convert(nvarchar(200),SM1.RollNo),'0')
																					),'[Batch]',isnull(SM1.BatchName,'')
																					), '[ReceiptNumber]', isnull(Convert(nvarchar(100),FR1.ReceiptNumber),'')
																					), '[ReceiptDate]',isnull(Convert(nvarchar(100),FR1.ReceiptDate),'')
																					), '[ReceiptAmount]',isnull(Convert(nvarchar(100),FR1.ReceiptAmount),'')
																					), '[ChequeNo]',isnull(Convert(nvarchar(100),FR1.ChequeNo),'')
																					),'[BankName]',isnull(FR1.BankName,'')
																					),'[FeeName]',isnull(FM1.Title,'')
																					), '[FeeAmount]',isnull(Convert(nvarchar(100),Sum(FRD.Amount)),'0.00')
																					),'[FeeHeadName]',ISNULL(FHM1.Title,'')
																					), '[FeeHeadAmount]',isnull(Convert(nvarchar(100),Sum(FRD.Amount)),'0.00')
																					), '[CollectionGroupName]',isNull(CGM1.Title,'')
																					),'[ReceiptFromNumber]',isnull(Convert(nvarchar(10),(Select Min(ReceiptNumber) from sFee.tReceipt where   FR.ReceiptDate =ReceiptDate AND IsObsolete = 0)),'')
																					), '[ReceiptToNumber]',isnull(Convert(nvarchar(10),(Select Max(ReceiptNumber) from sFee.tReceipt Where FR.ReceiptDate = ReceiptDate AND IsObsolete = 0)),''))
						from sFee.tReceipt FR1  INNER JOIN sFee.tReceiptDetail FRD1 ON FR1.Id = FRD1.ReceiptId
						INNER JOIN sFee.tFeeSetup FS1 ON FS1.Id = FRD1.FeeSetupId 
						INNER JOIN sStudent.vStudentAcademic SM1 ON SM1.ACademicId = FR1.SourceID AND SM1.OrgGRoupBatchId = FR1.OrgGRoupBatchId 						
						INNER JOIN sFee.tFeeMaster FM1 ON FM1.Id = FS1.FeeId --AND FRD.ReceiptId=FRD1.ReceiptId
						LEFT JOIN sFee.tCollectionGroupMaster CGM1 ON CGM1.Id = FS1.CollectionGroupId
						INNER JOIN sFee.tFeeHeadMaster FHM1 ON FHM1.Id = FM1.FeeHeadId  where   FR.ReceiptDate=FR1.ReceiptDate AND FR.Id=FR1.Id AND FR1.IsObsolete = 0  FOR XML PATH('')),1,1,'') else
						SM.Name + '(' + ClassName + ':' + DivisionName + ') ' + ' # Cheque No. :' + ISNULL(FR.ChequeNo,'') + ' BankName :' + ISNULL(FR.BankName,'') end as Narration,						
						FR.PayTypeId AS PayTypeId, 
						FR.Id  AS FeeId,
						FR.Id AS ReceiptId
				FROM sFee.tReceipt FR 
					INNER JOIN sFee.tReceiptDetail FRD ON FR.Id = FRD.ReceiptId
					INNER JOIN sStudent.vStudentAcademic SM ON SM.ACademicId = FR.SourceID AND SM.OrgGRoupBatchId = FR.OrgGRoupBatchId 
					INNER JOIN sFee.tFeeSetup FS ON FS.Id = FRD.FeeSetupId
					INNER JOIN sFee.tFeeMaster FM ON FM.Id = FS.FeeId
					INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id = FM.FeeHeadId
					INNER JOIN sFinanceCommon.tPayTypeMaster PM ON PM.Id = FR.PayTypeId
					INNER JOIN sSetup.tOrganizationMaster OM ON  OM.Id=SM.OrgId
					LEFT JOIN sSetup.tOrgSubGroupMaster OSM ON OSM.id=OM.OrgSubGroupId

					WHERE	FR.ReceiptBookId= @rReceiptBookId 
							AND FR.IsObsolete = 0 
							AND FR.OrgGroupBatchId = @rOrgGroupBatchId
							AND FR.ReceiptDate >= @rReceiptDate AND FR.ReceiptDate <= @rToReceiptDate
							AND (FR.PayTypeId = @rPayTypeId OR @rPayTypeId = 0)
				group by ReceiptDate,PM.Title,FR.PayTypeId,FR.Id,SM.Name + '(' + ClassName + ':' + DivisionName + ') ' + ' # Cheque No. :' + ISNULL(FR.ChequeNo,'') + ' BankName :' + ISNULL(FR.BankName,'')
				Order By FR.Id,ReceiptDate Desc
			END			
			
END
GO
PRINT N'Altering [sTransport].[pAssignRouteLogAdd]...';


GO
ALTER PROCEDURE [sTransport].[pAssignRouteLogAdd]
	 
	@rSourceTypeId smallint,
	@rSourceId bigint,
	@rNewPickupDestinationId int,
	@rNewDropDestinationId int,
	@rStatusId int,
	@rOrgGroupBatchId int,
	@rCreatedUserId bigint
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

IF(@rNewPickupDestinationId > 0 OR @rNewDropDestinationId > 0)
BEGIN
	--IF NOT EXISTS(SELECT * FROM sTransport.tAssignRouteLog WHERE SourceTypeId = @rSourceTypeId AND SourceId = @rSourceId AND OrgGroupBatchId = @rOrgGroupBatchId)
	--BEGIN
	--INSERT INTO sTransport.tAssignRouteLog
	--(
	--	SourceTypeId,
	--	SourceId,
	--	NewPickupDestinationId,
	--	NewDropDestinationId,
	--	StatusId,
	--	OrgGroupBatchId,
	--	CreatedUserId,
	--	CreatedDateTime
	--)
	--VALUES
	--(
	--	@rSourceTypeId,
	--	@rSourceId,
	--	@rNewPickupDestinationId,
	--	@rNewDropDestinationId,
	--	@rStatusId,
	--	@rOrgGroupBatchId ,
	--	@rCreatedUserId ,
	--	sCommon.fGetDate()
	--)
	--END

	--BEGIN
	--DELETE FROM sTransport.tAssignRouteLog WHERE SourceTypeId = @rSourceTypeId AND SourceId = @rSourceId AND OrgGroupBatchId = @rOrgGroupBatchId

	INSERT INTO sTransport.tAssignRouteLog
	(
		SourceTypeId,
		SourceId,
		NewPickupDestinationId,
		NewDropDestinationId,
		StatusId,
		OrgGroupBatchId,
		CreatedUserId,
		CreatedDateTime
	)
	VALUES
	(
		@rSourceTypeId,
		@rSourceId,
		@rNewPickupDestinationId,
		@rNewDropDestinationId,
		@rStatusId,
		@rOrgGroupBatchId ,
		@rCreatedUserId ,
		sCommon.fGetDate()
	)
	--END
END
END
GO
PRINT N'Creating [sAdmission].[pRptAdmissionInquiryBlankFieldGet]...';


GO
CREATE PROCEDURE [sAdmission].[pRptAdmissionInquiryBlankFieldGet]

	@rClassId int = 0,
	@rBatchId int = 0
	
AS
SET NOCOUNT ON

BEGIN 
	SELECT
		AIF.ClassId,
		AIF.BatchId,
		AIF.FieldGroup,
		AIF.FieldRemark
	FROM  
		sAdmission.tAdmissionInquiryForm AIF
	WHERE 	
		AIF.ClassId = @rClassId
		AND AIF.BatchId = @rBatchId
END
GO
PRINT N'Creating [sAdmission].[pRptAdmissionInquiryBlankGet]...';


GO
CREATE PROCEDURE [sAdmission].[pRptAdmissionInquiryBlankGet]
	
	 @rClassId int = 0,
	 @rBatchId int = 0
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
	
	SELECT 
		ISNULL(AIC.AgeCutOffDate,'') AS AgeCutOffDate,
		AIC.ClassId,
		AIC.BatchId

	FROM
        sAdmission.tAdmissionInquiryCriteria AIC
		INNER JOIN sSetup.tClassMaster CM ON CM.Id = AIC.ClassId
		INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AIC.BatchId
	WHERE  
	   ((AIC.ClassId = @rClassId) OR (@rClassId = 0))
		AND ((AIC.BatchId = @rBatchId) OR (@rBatchId = 0))
END
GO
PRINT N'Creating [sAlert].[pBookIssueListGet]...';


GO

CREATE PROCEDURE [sAlert].[pBookIssueListGet]
	 	 
		 --@rBookIssueId bigint,
		 @rOrgId int,
		 @rBatchId int,
		 @rDepartmentId int,
		 @rClassId int,
		 @rDivisionId int,	 	 	 	
	 	 @rLibraryId int,
		 @rIssueDate date,
	 	 @rTemplate nvarchar(max),	 	
	 	 @rMailSubject nvarchar(500)=''
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	
	Select 

			SC.OrgGroupId,
			SC.OrgId,
			SC.AcademicId,
			SC.Code,
			SC.Name,
			SC.ParentContactNo AS MobileNo,	
			SC.ParentEmail AS EmailId,
			ISNULL(SC.StudentContactNo,'') AS StudentContactNo,
			ISNULL(SC.StudentEmail,'') AS StudentEmail,
			ISNULL(SC.FatherContactNo,'') AS FatherContactNo,
			ISNULL(SC.FatherMail,'') AS FatherMail,
			ISNULL(SC.MotherContactNo,'') AS MotherContactNo,
			ISNULL(SC.MotherMail,'') AS MotherMail,
			replace (
			replace (
			replace (
			replace (
			replace(@rTemplate,'[Name]',SC.Name),			
			'[BookCode]',BM.Code),
			'[BookName]',BM.Title),
			'[LibraryName]',LM.Title),
			'[IssueDate]',BL.LogDate)
			 AS Template,
			replace (
			replace (
			replace (
			replace (
			replace(@rTemplate,'[Name]',SC.Name),			
			'[BookCode]',BM.Code),
			'[BookName]',BM.Title),
			'[LibraryName]',LM.Title),
			'[IssueDate]',BL.LogDate)
			 AS MsgText,
			'2003' AS SourceTypeId,
			SC.StudentId AS SourceId,
			@rMailSubject AS Subject,
			2003 AS ReceiverSourceTypeId,
			SC.StudentId AS ReceiverSourceId,
			BM.Code AS BookCode,
			BM.Title AS BookName,
			LM.Title AS LibraryName,
			BL.LogDate AS IssueDate,
			SC.WhatsAppContactNo
		
		
	From 
		sStudent.vStudentCommunication SC
		INNER JOIN sLibrary.tBookLog BL ON BL.ReaderSourceId=SC.StudentId AND BL.ReaderSourceTypeId=2003 AND SC.OrgId = BL.OrgId
		AND BL.IsCurrentStatus=1 
		AND BL.StatusId=523 
		INNER JOIN sLibrary.tLibraryMaster LM on LM.Id=BL.LibraryId
		INNER JOIN sLibrary.tBookMaster BM ON BM.Id=BL.ResourceSourceId AND BL.ResourceSourceTypeId=2009
	WHERE
		(SC.OrgId = @rOrgId)
		AND (SC.BatchId = @rBatchId)
		AND ((SC.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
		AND ((SC.ClassId=@rClassId) OR (@rClassId=0))
		AND ((SC.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		AND BL.LibraryId=@rLibraryId
		AND BL.LogDate <= @rIssueDate
		AND (SC.StatusId=1) AND SC.IsBlockAllAlert=0	
	
END
GO


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

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



GO
PRINT N'Altering [sBiometric].[tShiftMasterCloud]...';


GO
ALTER TABLE [sBiometric].[tShiftMasterCloud]
    ADD [LastOutAlertBasedOnId] INT CONSTRAINT [DF_tShiftMasterCloud_LastOutAlertBasedOnId] DEFAULT ('1') NULL;


GO
PRINT N'Altering [sCertificate].[tBonafide]...';


GO
ALTER TABLE [sCertificate].[tBonafide] ALTER COLUMN [Remark] NVARCHAR (MAX) NULL;


GO
PRINT N'Altering [sCommunication].[tFeedbackTemplate]...';


GO
ALTER TABLE [sCommunication].[tFeedbackTemplate]
    ADD [IsAllAnsRequired] BIT CONSTRAINT [DF_tFeedbackTemplate_IsAllAnsRequired] DEFAULT ('0') NULL;


GO
PRINT N'Altering [sHrm].[tLeaveTypeGradeSettings]...';


GO
ALTER TABLE [sHrm].[tLeaveTypeGradeSettings]
    ADD [LeaveCarryForwordRuleId] INT CONSTRAINT [DF_tLeaveTypeGradeSettings_LeaveCarryForwordRuleId] DEFAULT ('1') NULL;

GO
PRINT N'Refreshing [sHrm].[vEmployeeColumnName]...';


GO
EXECUTE sp_refreshview N'sHrm.vEmployeeColumnName';


GO
PRINT N'Refreshing [sHrm].[vEmployeeCustomSearch]...';


GO
EXECUTE sp_refreshview N'sHrm.vEmployeeCustomSearch';


GO
PRINT N'Refreshing [sCertificate].[vPrintTemplateBonafideCertificate]...';


GO
EXECUTE sp_refreshview N'sCertificate.vPrintTemplateBonafideCertificate';


GO
PRINT N'Refreshing [sHrm].[vAvailableLeaveEmployeeWise]...';


GO
EXECUTE sp_refreshview N'sHrm.vAvailableLeaveEmployeeWise';

GO


PRINT N'Altering [sCommunication].[vOrgwiseQueryCategory]...';


GO




/******************************************************************************  
 Purpose          : To get Batch Wise  Class
 Created date     : 21 Nov 2013
 Author           : Kundan Patel 
 Copyright©       : Copyright © Sapphire Software Solutions
 ******************************************************************************/  
ALTER VIEW [sCommunication].[vOrgwiseQueryCategory]  
  
AS  
  
SELECT 	
	  QCM.Id,
	  QCM.Title,
	  QCM.OrgGroupId,
	  QCM.IsObsolete,
	  QCO.OrgId,
	  ISNULL(QCM.AssignedToId,1) AS AssignedToId
	  	   
  FROM 
  
	sCommunication.tQueryCategoryMaster QCM
	INNER JOIN sCommunication.tQueryCategoryOrg QCO ON QCO.QueryCategoryId=QCM.Id
	--AND QCM.IsObsolete = 0
GO
PRINT N'Altering [sFee].[vFeeColumnName]...';


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




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


GO


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


GO

ALTER PROCEDURE [sAlert].[pEmployeeBiometricLastOutTimeGet]
	@rTemplate nvarchar(max)='',
	@rSubject nvarchar(100)='',
	@rOrgId int,
	@rOrgGroupId int,
	@rIntervalTime int
 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY	
		BEGIN TRANSACTION 
			if object_id('tempdb..#tShift') is not null
			BEGIN
				DROP TABLE #tShift
			END
			CREATE TABLE #tShift(
					ShiftCode int NOT NULL,
					OutTimeAlertTime time not NUll
				)
			insert #tShift
			Select 
				ShiftCode, 
				CAST(OutTimeAlertTime AS Time)
				--case When DATEDIFF(MINUTE,CAST(OutTimeAlertTime AS Time),cast([sCommon].[fGetDate]() as Time)) < @rIntervalTime then DATEDIFF(MINUTE,CAST(OutTimeAlertTime AS Time),cast([sCommon].[fGetDate]() as Time)) else @rIntervalTime end 
			  FROM sBiometric.tShiftMasterCloud
			where  ((OrgGroupId = @rOrgGroupId) OR (@rOrgGroupId=0))  
			AND IsOutTimeAlertTime=1
			AND CAST(OutTimeAlertTime AS Time)<cast([sCommon].[fGetDate]() as Time)
			AND CAST(OutTimeAlertTime AS Time) > CAST(DATEADD(minute,-(@rIntervalTime),[sCommon].[fGetDate]()) AS Time)

			declare @lcount int=(SELECT COUNT(ShiftCode) FROM #tShift)
	 
			--select * from #tShift
			if object_id('tempdb..#tTable') is not null
			BEGIN
				DROP TABLE #tTable
			END
			CREATE TABLE #tTable(
						SourceId bigint NOT NULL,
						In_Out_Time [datetime] NOT NULL,
						SourceTypeId int NOT NULL,
						OutTimeAlertTime time NOT NULL,
						CreatedDateTime [datetime] NOT NULL
					)
			if(@lcount>0)
			BEGIN
				insert into #tTable
				select SourceId,MAX(In_Out_Time),SourceTypeId,tempShift.OutTimeAlertTime,Max(CreatedDateTime) 
				from [sBiometric].[tCloudTransactionData] CDT 
				inner join #tShift tempShift ON tempShift.ShiftCode=CDT.ShiftCode
				WHERE Attn_Dt=CONVERT(date,[sCommon].[fGetDate]())  AND SourceTypeId=95 Group by SourceId,SourceTypeId,tempShift.OutTimeAlertTime
			END

			--select * from #tTable

			SELECT 
				EM.MobileNumber AS MobileNo,	
				EM.CompanyEmail AS EmailId,
				replace (
				replace(@rTemplate,'[EmployeeName]',EM.EmployeeName),
				'[TimeStamp]',ISNULL(Convert(varchar,temp.In_Out_Time,108),''))
				 AS MsgText,
				@rSubject AS Subject,
				95 AS ReceiverSourceTypeId,
				EM.EmployeeId AS ReceiverSourceId,
				EM.EmployeeName AS EmployeeName,
				ISNULL(EC.WhatsAppContactNo,'') AS WhatsAppContactNo,
				95 AS SourceTypeId,
				EM.EmployeeId AS SourceId,
				EM.OrgId,
				OM.OrgGroupId,
				OM.DisplayTitle AS OrganizationTitle
			FROM 
				#tTable temp
				Inner join sHrm.vEmployeeCommonDetail EM ON temp.SourceId=EM.EmployeeId
				LEFT JOIN sHrm.tEmployeeCommunications EC ON EC.EmployeeId = EM.EmployeeId
				INNER JOIN sSetup.tOrganizationMaster OM ON EM.OrgID = OM.Id
			WHERE
				temp.OutTimeAlertTime <= CAST([sCommon].[fGetDate]() AS Time)
				AND temp.OutTimeAlertTime > CAST(DATEADD(minute,-(@rIntervalTime),[sCommon].[fGetDate]()) AS Time)
				AND EM.OrgID =@rOrgId

			DROP TABLE #tTable
			DROP TABLE #tShift
		COMMIT TRANSACTION
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH
END
GO
PRINT N'Altering [sAlert].[pStudentBiometricLastOutTimeGet]...';


GO


ALTER PROCEDURE [sAlert].[pStudentBiometricLastOutTimeGet]
	@rTemplate nvarchar(max)='',
	@rSubject nvarchar(100)='',
	@rOrgId int,
	@rOrgGroupId int,
	@rIntervalTime int
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY	
		BEGIN TRANSACTION 
			if object_id('tempdb..#tShift') is not null
			BEGIN
				DROP TABLE #tShift
			END
			CREATE TABLE #tShift(
					ShiftCode int NOT NULL,
					OutTimeAlertTime time not NUll,
					LastOutAlertBasedOnId int not NUll
				)

			insert #tShift
			Select 
				ShiftCode,
				 case when LastOutAlertBasedOnId=3 THEN 
				 case When DATEDIFF(MINUTE,CAST(EndTime AS Time),cast([sCommon].[fGetDate]() as Time)) < @rIntervalTime THEN CAST(DATEADD(minute,-(GraceBefore),EndTime) AS Time) else  CAST(DATEADD(minute,-(@rIntervalTime),[sCommon].[fGetDate]()) AS Time) end 
				 else  CAST(OutTimeAlertTime AS Time) end,
				 isnull(LastOutAlertBasedOnId,1)
				--case When DATEDIFF(MINUTE,CAST(@rIntervalTime AS Time),cast([sCommon].[fGetDate]() as Time)) < @rIntervalTime then DATEDIFF(MINUTE,CAST(OutTimeAlertTime AS Time),cast([sCommon].[fGetDate]() as Time)) else @rIntervalTime end 
			FROM sBiometric.tShiftMasterCloud
			where  ((OrgGroupId = @rOrgGroupId) OR (@rOrgGroupId=0))  
			AND IsOutTimeAlertTime=1
			AND (
			 ( (LastOutAlertBasedOnId=1 OR LastOutAlertBasedOnId=2) AND CAST(OutTimeAlertTime AS Time)<cast([sCommon].[fGetDate]() as Time)
			AND CAST(OutTimeAlertTime AS Time) > CAST(DATEADD(minute,-(@rIntervalTime),[sCommon].[fGetDate]()) AS Time)) 
			OR 
			(LastOutAlertBasedOnId=3 AND CAST(DATEADD(minute,-@rIntervalTime,EndTime) AS Time)<cast([sCommon].[fGetDate]() as Time)
			AND CAST(OutTimeAlertTime AS Time) > CAST(DATEADD(minute,-(@rIntervalTime),[sCommon].[fGetDate]()) AS Time))
			)

			--select * from #tShift
			declare @lcount int=(SELECT COUNT(ShiftCode) FROM #tShift)

			if object_id('tempdb..#tTable') is not null
			BEGIN
				DROP TABLE #tTable
			END
			CREATE TABLE #tTable(
				SourceId bigint NOT NULL,
				In_Out_Time [datetime] NOT NULL,
				SourceTypeId int NOT NULL,
				OutTimeAlertTime time NOT NULL,
				CreatedDateTime [datetime] NOT NULL,
				LastOutAlertBasedOnId int NOT NULL,
				ShiftCode int NOT NULL
			)
			if(@lcount>0)
			BEGIN
				insert into #tTable
				select SourceId,MAX(In_Out_Time),SourceTypeId,tempShift.OutTimeAlertTime,Max(CreatedDateTime),tempShift.LastOutAlertBasedOnId,CDT.ShiftCode
				from [sBiometric].[tCloudTransactionData] CDT 
				inner join #tShift tempShift ON tempShift.ShiftCode=CDT.ShiftCode
				WHERE Attn_Dt=CONVERT(date,[sCommon].[fGetDate]())  AND SourceTypeId=2003 Group by SourceId,SourceTypeId,tempShift.OutTimeAlertTime,tempShift.LastOutAlertBasedOnId,CDT.ShiftCode
			End
			--select * from #tTable

			SELECT 
				SC.ParentContactNo AS MobileNo,	
				SC.ParentEmail AS EmailId,
				replace (
				replace(@rTemplate,'[StudentName]',SC.Name),
				'[TimeStamp]',ISNULL(Convert(varchar,temp.In_Out_Time,108),''))
				 AS MsgText,
				@rSubject AS Subject,
				2003 AS ReceiverSourceTypeId,
				SC.StudentId AS ReceiverSourceId,
				SC.Name AS StudentName,
				SC.Code,
				ISNULL(SC.WhatsAppContactNo,'') AS WhatsAppContactNo,
				2003 AS SourceTypeId,
				SC.StudentId AS SourceId,
				SC.OrgId,
				OM.OrgGroupId,
				OM.DisplayTitle AS OrganizationTitle


			FROM 
				#tTable temp
				Inner Join sBiometric.tShiftMasterCloud SMC on SMC.ShiftCode=temp.ShiftCode
				Inner join sStudent.vStudentCommunication SC ON temp.SourceId=SC.StudentId AND SC.IsActiveBatch=1
				INNER JOIN sSetup.tOrganizationMaster OM ON SC.OrgID = OM.Id
			WHERE
				((temp.LastOutAlertBasedOnId=1 ) AND temp.OutTimeAlertTime <= CAST([sCommon].[fGetDate]() AS Time)
				AND temp.OutTimeAlertTime > CAST(DATEADD(minute,-(@rIntervalTime),[sCommon].[fGetDate]()) AS Time)
				
				OR( temp.LastOutAlertBasedOnId=2 AND CAST(DATEADD(minute,-(SMC.GraceBefore),SMC.EndTime) AS Time) <= CAST(temp.In_Out_Time  AS Time)
				AND CAST(temp.In_Out_Time AS Time) < CAST([sCommon].[fGetDate]() AS Time)
				)
				OR 
				(  
					(temp.LastOutAlertBasedOnId=3 
					AND (CAST(temp.In_Out_Time  AS Time)  >= CAST(temp.OutTimeAlertTime AS Time) 
					AND CAST(temp.In_Out_Time  AS Time)  <= CAST([sCommon].[fGetDate]() AS Time)))
					))
				AND SC.OrgID =@rOrgId
				AND SC.StatusId = 1

			DROP TABLE #tTable
			DROP TABLE #tShift
		COMMIT TRANSACTION
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH
END
GO
PRINT N'Altering [sAssetManagement].[pAssetAdjustmentGet]...';


GO

ALTER PROCEDURE [sAssetManagement].[pAssetAdjustmentGet]
	@rOrgId [int],
	@rNumber [nvarchar](100) = 0
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	  SELECT 
			ASSTADJ.AssetAuditDetailId AS AssetAuditDetailId,
			LM.Title AS StoreLocation,
			SIM.Code AS AssetTag,
			SIM.Title AS [Description],
			SIM.ModelNumber AS ModelNumber,
			SM.Title AS OldStatus,
			ASSTADJ.StatusId AS StatusId,
			ASSTADJ.ReasonId AS ReasonId,
			ASSTADJ.Remark AS Remark,
			CM.Title AS Category,
			CM.Id AS CategoryId,
			LM.Id AS LocationId,
			SIM.DepartmentId,
			LM.Title AS LocationCode,
			ODM.Title As Department,
			AA.Number AS AuditNumber,
			SIM.AssetCode AS NewAssetCode		
			
	FROM sAssetManagement.tAssetAdjustmentDetail ASSTADJ	
	INNER JOIN sAssetManagement.tAssetAdjustment ASSTA
	ON 	ASSTADJ.AssetAdjustmentId = ASSTA.Id
	INNER JOIN sAssetManagement.tAssetAuditDetail AAD
	ON ASSTADJ.AssetAuditDetailId = AAD.Id
	INNER JOIN sAssetManagement.tAssetAudit AA
	ON  AAD.AssetAuditId = AA.Id
	INNER JOIN sFixedAsset.vExtLocationMaster LM
	ON  LM.Id = AA.LocationId
	INNER JOIN sCommon.tStatusMaster SM
	ON	SM.Id = AA.StatusId
	INNER JOIN sAssetManagement.tAssetMaster SIM
	ON 	SIM.ID = AAD.AssetId
	INNER JOIN sFixedAsset.tCategoryMaster CM
		ON CM.Id = SIM.CategoryId
	INNER JOIN sSetup.tDepartmentMaster ODM
	ON ODM.Id = SIM.DepartmentID
	--INNER JOIN (SELECT DISTINCT DepartmentId, DepartmentTitle FROM sAssetManagement.vExtAssetDepartment) AD
	--	ON AD.DepartmentId = SIM.DepartmentID
	WHERE
		ASSTA.Number = @rNumber
    AND ((ASSTA.OrgId = @rOrgId) OR @rOrgId=0)
    
	ORDER BY SIM.Code DESC
END
GO
PRINT N'Altering [sBiometric].[pShiftMasterCloudAdd]...';


GO

 
ALTER PROCEDURE [sBiometric].[pShiftMasterCloudAdd]
@rShiftCode int = 0,
@rShiftName nvarchar(50),
@rStartTime DateTime = null,
@rEndTime DateTime = null,
@rGraceBefore int = 0,
@rGraceAfter int = 0,
@rShiftDur nvarchar(16) = NULL,
@rMinHrsHalfDay  nvarchar(16) = null,
@rMinHrsFullDay nvarchar(16) = null,
@rAlterGraceTime int = 0,
@IsOutTimeAlertTime bit = 0,
@OutTimeAlertTime DateTime = null,
@rOrgGroupId int = 0,
@rLastOutAlertBasedOnId int=1

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
	IF(@rShiftcode = 0)	
		BEGIN
			If Exists(select ShiftCode from sBiometric.tShiftMasterCloud where ShiftName=@rShiftName and OrgGroupId = @rOrgGroupId)
				BEGIN
				select -103 as Result
				RETURN
			END 
		END
	ELSE
		BEGIN
			If  Exists(select ShiftCode from sBiometric.tShiftMasterCloud where ShiftName=@rShiftName AND Shiftcode<>@rShiftcode and OrgGroupId = @rOrgGroupId)
			Begin
				select -103 as Result
				RETURN
			End
		END	
	
	 BEGIN TRANSACTION	
	 DECLARE @lNextNumber BIGINT 
	 IF EXISTS (SELECT 1 FROM sBiometric.tShiftMasterCloud)
	 BEGIN
		SELECT @lNextNumber = Max(ISNULL(ShiftCode,0)) + 1 FROM sBiometric.tShiftMasterCloud
	 END
	 ELSE
	 BEGIN
		SET @lNextNumber = 1
	 END
	 
	IF(@rShiftcode = 0)	
	BEGIN
	Insert into sBiometric.tShiftMasterCloud 
     (ShiftCode
     , ShiftName
     , StartTime
     , EndTime
     , GraceBefore
     , GraceAfter
     , ShiftDur
     , MinHrsHalfDay
     , MinHrsFullDay    
     , AlterGraceTime
     , IsOutTimeAlertTime
     , OutTimeAlertTime
     , OrgGroupId
	 ,LastOutAlertBasedOnId)
     Values
     (@lNextNumber
     ,@rShiftName
     ,@rStartTime
     ,@rEndTime
     ,@rGraceBefore
     ,@rGraceAfter
     ,@rShiftDur
     ,@rMinHrsHalfDay
     ,@rMinHrsFullDay
     ,@rAlterGraceTime
     ,@IsOutTimeAlertTime
     ,@OutTimeAlertTime
     ,@rOrgGroupId
     ,@rLastOutAlertBasedOnId
	 )
     
     SELECT @lNextNumber AS Result
	
		--COMMIT TRANSACTION         
	END	 

ELSE
	 BEGIN
	    UPDATE sBiometric.tShiftMasterCloud
	    SET
			ShiftName=@rShiftName,
			StartTime=@rStartTime,
			EndTime=@rEndTime,
			GraceBefore=@rGraceBefore,
			shiftDur=@rShiftDur,
			MinHrsHalfDay=@rMinHrsHalfDay,
			MinHrsFullDay=@rMinHrsFullDay,
			AlterGraceTime=@rAlterGraceTime,
		    IsOutTimeAlertTime = @IsOutTimeAlertTime,
			OutTimeAlertTime = @OutTimeAlertTime,
			LastOutAlertBasedOnId=@rLastOutAlertBasedOnId
		
	      WHERE ShiftCode = @rShiftcode and OrgGroupId = @rOrgGroupId
	      
	      SELECT @lNextNumber AS Result
	
		--COMMIT TRANSACTION
	 END  	

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


GO

ALTER PROCEDURE [sCertificate].[pBonafideAdd]

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

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

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

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


GO
ALTER PROCEDURE [sCertificate].[pLeavingBulkGet]
	 
	 @rClassID int,
	 @rDivisionId int,
	 @rOrgId int,
	 @rBatchId int,
	 @rOrderBy int = 0,
	 @rStatusId smallint=0
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	
	SELECT 
			SA.AcademicId,
			ISNULL(SA.RollNo,0) AS RollNo,
			SA.Code,
			SA.Name,
			ISNULL(L.Id,0) AS Id,
			ISNULL(L.LCNumber,0) AS LCNumber,
			ISNULL(L.LCDate,'') AS LCDate,
			ISNULL(L.LCRemark,'')AS LCRemark,
			ISNULL(L.LastExamName,'')AS LastExamName,
			ISNULL(L.LastExamResult,'')AS LastExamResult,
			ISNULL(L.RepeatDetail,'')AS RepeatDetail,
			--ISNULL(L.SubjectStudied,'')AS SubjectStudied,
			ISNULL(L.PromoteToClass,'')AS PromoteToClass,
			ISNULL(L.ExtraCurricularActivities,'')As ExtraCurricularActivities,
			ISNULL(L.NCCScoutDetail,'')AS NCCScoutDetail,
			ISNULL(L.TermsInInstitute,'')As TermsInInstitute,
			ISNULL(L.FeeDetail,'')AS FeeDetail,
			ISNULL(L.FeeConcessionDetail,'')AS FeeConcessionDetail,
			ISNULL(AD.TotalDaysAnnual,0)AS TotalDays,
			ISNULL(AD.PresentDaysAnnual,0)AS PresentDays,
			ISNULL(StuA.ProofOfDOB,'')AS ProofOfDOB,
			CASE WHEN EXISTS(SELECT 1 FROM sSetup.tSubjectMaster S  INNER JOIN sSetup.tClassSubject CS ON  S.Id = CS.SubjectId AND CS.ClassId=@rClassId	
								WHERE S.OrgId=@rOrgId AND CS.IsOptional=0) THEN
			reverse(STUFF(reverse(isnull([sCommon].[fXMLTagsReplaceReverse](STUFF((SELECT ',' + S.Title from sSetup.tSubjectMaster S  
						   INNER JOIN sSetup.tClassSubject CS ON  S.Id = CS.SubjectId AND CS.ClassId=@rClassId	
						   WHERE S.OrgId=@rOrgId AND CS.IsOptional=0 FOR XML PATH('')), 1, 1, '')),'') +',' +
			isnull([sCommon].[fXMLTagsReplaceReverse](STUFF((SELECT ',' + S.Title FROM sAssessment.tOptionalSubject OS 
						   INNER JOIN sSetup.tClassSubject CS ON CS.Id = OS.ClassSubjectId 
						   INNER JOIN sSetup.tSubjectMaster S ON  S.Id = CS.SubjectId 
						   WHERE OS.AcademicId = SA.AcademicId FOR XML PATH('')), 1, 1, '')),'') 
						   ), 1, 1, '')) 
						   
			ELSE

			STUFF(reverse(reverse(isnull([sCommon].[fXMLTagsReplaceReverse](STUFF((SELECT ',' + S.Title from sSetup.tSubjectMaster S  
						   INNER JOIN sSetup.tClassSubject CS ON  S.Id = CS.SubjectId AND CS.ClassId=@rClassId	
						   WHERE S.OrgId=@rOrgId AND CS.IsOptional=0 FOR XML PATH('')), 1, 1, '')),'') +',' +
			isnull([sCommon].[fXMLTagsReplaceReverse](STUFF((SELECT ',' + S.Title FROM sAssessment.tOptionalSubject OS 
						   INNER JOIN sSetup.tClassSubject CS ON CS.Id = OS.ClassSubjectId 
						   INNER JOIN sSetup.tSubjectMaster S ON  S.Id = CS.SubjectId 
						   WHERE OS.AcademicId = SA.AcademicId FOR XML PATH('')), 1, 1, '')),'') 
						   )), 1, 1, '') END AS SubjectStudied,
			(SA.ClassName +'-'+SA.DivisionName)AS ClassDivision


			
			
  FROM 
			[sStudent].[vStudentAcademic]  SA 
			LEFT OUTER JOIN sCertificate.tLeaving L ON L.AcademicId=SA.AcademicId
			LEFT JOIN sStudent.tAcademicDetail AD ON SA.AcademicId=AD.AcademicId
			LEFT JOIN sStudent.tStudentAdmission StuA ON StuA.StudentId = SA.StudentId
  WHERE 
			(SA.ClassId=@rClassId OR @rClassId=0)
			AND (SA.DivisionId=@rDivisionId OR @rDivisionId=0)
			AND SA.BatchId=@rBatchId
			AND SA.OrgID=@rOrgId 
			AND L.Id IS NULL
			AND((SA.StatusId=@rStatusId)OR(@rStatusId=0))
			order by
			CASE @rOrderBy WHEN 2 THEN SA.Code END,
			CASE @rOrderBy WHEN 1 THEN SA.RollNo END,
			CASE @rOrderBy WHEN 0 THEN SA.RollNo END
END
GO
PRINT N'Altering [sCommon].[pGeneralMasterWithValueAdd]...';


GO
 
 
ALTER PROCEDURE [sCommon].[pGeneralMasterWithValueAdd]
	@rTableName [nvarchar](100),
	@rCodeField [nvarchar](100),
	@rRemarkField [nvarchar](100),
	@rCode [nvarchar](50),
	@rRemark [nvarchar](100),
	@rIsObsolete [nvarchar](10),
	@rCreatedUserId [bigint],
	@rIsStatic1to100 [bit],
	@rOrgId int,
	@rVisibilityField nvarchar(100),
	@rVisibilityId int
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON 
BEGIN

	--DECLARE @lSelectClause Nvarchar(2000)
	--DECLARE @lNextNumber BIGINT
	--EXECUTE @lNextNumber = sCommon.pTableRowIdGet @rTableName, 0, 1, 1
	DECLARE @lSelectClause Nvarchar(2000)
	DECLARE @lIsShow Nchar(1)
	DECLARE @lNextNumber BigInt
	DECLARE @lSchemaName Nvarchar(50)
	DECLARE @lTableName	Nvarchar(100)
	DECLARE @lSeed int
	
	SET @lSeed = (CASE WHEN @rIsStatic1to100 = 1 THEN 101 ELSE 1 END)
	EXECUTE  sCommon.pTableRowIdGet  @rOrgId,@rTableName, 0, @lSeed, 1,@outNextNumber = @lNextNumber output
	SET @lNextNumber = @lNextNumber
	SET @lIsShow = '0'
	SET @lSchemaName = SUBSTRING(@rTableName, 1, CHARINDEX('.', @rTableName, 1) - 1)
	SET @lTableName =  SUBSTRING(@rTableName, CHARINDEX('.', @rTableName, 1) + 1, LEN(@rTableName))
     
	--SELECT @lSchemaName, @lTableName
	
	SET @lSelectClause =     'IF EXISTS(SELECT ' + @rRemarkField + ' FROM ' + @rTableName + 
										' WHERE ' +  @rRemarkField + '	= ''' + @rRemark + ''' AND 
												' +  @rVisibilityField + '	= ' + CONVERT(NVARCHAR(20), @rVisibilityId) + ') 
     							BEGIN
									SELECT -102 AS Result
									RETURN
								END ' + 
							   'INSERT INTO ' + @rTableName 
								  + '(Id, ' + @rCodeField 
										   + ', ' + @rRemarkField 
										   + ', ' + ' UpdatedUserId ' 
										   + ', ' + ' UpdatedDateTime ' 
										   + ', ' + ' CreatedUserId ' 
										   + ', ' + ' CreatedDateTime ' 
                                           + ', ' + 'IsObsolete' +                                         
                                           --+' , ' +  'StoreLocationId' +
                                          ', ' + @rVisibilityField +
									      
									 ')
                               VALUES(' + CAST(@lNextNumber AS NVARCHAR(15)) + ', N''' + @rCode + ''', N''' 
							     		   + @rRemark +  ''', '''
                                           + CONVERT(NVARCHAR(25), @rCreatedUserId) + ''', ''' 
										   + CONVERT(NVARCHAR(30), sCommon.fGetDate()) + ''', '''
                                           + CONVERT(NVARCHAR(25), @rCreatedUserId) + ''', ''' 
										   + CONVERT(NVARCHAR(30), sCommon.fGetDate()) + ''', ''' + @rIsObsolete + ''','''										   
										   + CONVERT(NVARCHAR(20), @rVisibilityId) 
										 
								 + ''')
								 
								SELECT 1 AS Result'			
	
							 	
							 	
		PRINT @lSelectClause
	EXECUTE sp_executesql @lSelectClause

END
GO
PRINT N'Altering [sCommon].[pMasterDataAdd]...';


GO
ALTER  PROCEDURE [sCommon].[pMasterDataAdd]
	 
        
		@rTitle nvarchar(100)='',
		@rCode nvarchar(50)='',
		@rIsObsolete bit=0,
		@rCreatedUserId bigint,
		@rOrgGroupId smallint,
		@rOrgId int,
		@rTable_Name int=0,
		@rDependId int=0,
		@rNo int=0
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY

	 DECLARE @lNextNumber BIGINT 
	 DECLARE @lReligionId INT 
			 
		IF(@rTable_Name=1)
		BEGIN
		
			If Exists(select Id from sFinanceCommon.tBankMaster where Title=@rTitle AND OrgGroupId=@rOrgGroupId)
				BEGIN
				select -103 as Result
				RETURN
	 		END 
	 		EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sFinanceCommon.tBankMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
			INSERT INTO sFinanceCommon.tBankMaster
			(
			
				Id,
				Code,
				Title,
				 IsObsolete,
				 OrgGroupId,
				CreatedUserId,
				UpdateduserId,
				CreatedDateTime,
				UpdatedDateTime 
			)
		VALUES
			(
				@lNextNumber,
				@rCode,
				@rTitle,
				 @rIsObsolete,
				 @rOrgGroupId,
				@rCreatedUserId,
				@rCreatedUserId,
				sCommon.fGetDate() ,
				sCommon.fGetDate() 
			)
			END
			
			IF(@rTable_Name=2)
		BEGIN
		
			If Exists(select Id from sCommon.tReligionMaster where Title=@rTitle AND OrgGroupId=@rOrgGroupId)
				BEGIN
				select -103 as Result
				RETURN
	 		END 
	 		EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sCommon.tReligionMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
			INSERT INTO sCommon.tReligionMaster
			(
			
				Id,
				Code,
				Title,
				 IsObsolete,
				 OrgGroupId,
				CreatedUserId,
				UpdateduserId,
				CreatedDateTime,
				UpdatedDateTime 
			)
		VALUES
			(
				@lNextNumber,
				@rCode,
				@rTitle,
				 @rIsObsolete,
				 @rOrgGroupId,
				@rCreatedUserId,
				@rCreatedUserId,
				sCommon.fGetDate() ,
				sCommon.fGetDate() 
			)
			END
			
			IF(@rTable_Name=3)
		BEGIN
		
			If Exists(select Id from sCommon.tOccupationMaster where Title=@rTitle AND OrgGroupId=@rOrgGroupId)
				BEGIN
				select -103 as Result
				RETURN
	 		END 
	 		EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sCommon.tOccupationMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
			INSERT INTO sCommon.tOccupationMaster
			(
			
				Id,
				Code,
				Title,
				 IsObsolete,
				 OrgGroupId,
				CreatedUserId,
				UpdateduserId,
				CreatedDateTime,
				UpdatedDateTime 
			)
		VALUES
			(
				@lNextNumber,
				@rCode,
				@rTitle,
				 @rIsObsolete,
				 @rOrgGroupId,
				@rCreatedUserId,
				@rCreatedUserId,
				sCommon.fGetDate() ,
				sCommon.fGetDate() 
			)
			END
			
			
			IF(@rTable_Name=4)
		BEGIN
		
			If Exists(select Id from sCommon.tMotherTongueMaster where Title=@rTitle AND OrgGroupId=@rOrgGroupId)
				BEGIN
				select -103 as Result
				RETURN
	 		END 
	 		EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sCommon.tMotherTongueMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
			INSERT INTO sCommon.tMotherTongueMaster
			(
			
				Id,
				Code,
				Title,
				 IsObsolete,
				 OrgGroupId,
				CreatedUserId,
				UpdateduserId,
				CreatedDateTime,
				UpdatedDateTime 
			)
		VALUES
			(
				@lNextNumber,
				@rCode,
				@rTitle,
				 @rIsObsolete,
				 @rOrgGroupId,
				@rCreatedUserId,
				@rCreatedUserId,
				sCommon.fGetDate() ,
				sCommon.fGetDate() 
			)
			END
			
		IF(@rTable_Name=5)
		BEGIN
		
			If Exists(select Id from sCommon.tPreviousSchoolMaster where Title=@rTitle AND OrgGroupId=@rOrgGroupId)
				BEGIN
				select -103 as Result
				RETURN
	 		END 
	 		EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sCommon.tPreviousSchoolMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
			INSERT INTO sCommon.tPreviousSchoolMaster
			(
			
				Id,
				Code,
				Title,
				 IsObsolete,
				 OrgGroupId,
				CreatedUserId,
				UpdateduserId,
				CreatedDateTime,
				UpdatedDateTime 
			)
		VALUES
			(
				@lNextNumber,
				@rCode,
				@rTitle,
				 @rIsObsolete,
				 @rOrgGroupId,
				@rCreatedUserId,
				@rCreatedUserId,
				sCommon.fGetDate() ,
				sCommon.fGetDate() 
			)
			END
			
			IF(@rTable_Name=6)
		BEGIN
		
			If Exists(select Id from sHrm.tQualificationMaster where Title=@rTitle AND OrgGroupId=@rOrgGroupId)
				BEGIN
				select -103 as Result
				RETURN
	 		END 
	 		EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sHrm.tQualificationMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
			INSERT INTO sHrm.tQualificationMaster
			(
			
				Id,
				Code,
				Title,
				 IsObsolete,
				 OrgGroupId,
				CreatedUserId,
				UpdateduserId,
				CreatedDateTime,
				UpdatedDateTime 
			)
		VALUES
			(
				@lNextNumber,
				@rCode,
				@rTitle,
				 @rIsObsolete,
				 @rOrgGroupId,
				@rCreatedUserId,
				@rCreatedUserId,
				sCommon.fGetDate() ,
				sCommon.fGetDate() 
			)
			END
			
				IF(@rTable_Name=7)
		BEGIN
		
			If Exists(select Id from sCommon.tCountryMaster where Title=@rTitle AND OrgGroupId=@rOrgGroupId)
				BEGIN
				select -103 as Result
				RETURN
	 		END 
	 		EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sCommon.tCountryMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
			INSERT INTO sCommon.tCountryMaster
			(
			
				Id,
				Title,
				Nationality,
			
				 IsObsolete,
				 OrgGroupId,
				CreatedUserId,
				UpdateduserId,
				CreatedDateTime,
				UpdatedDateTime ,
				IsShow
			)
		VALUES
			(
				@lNextNumber,
				
				@rTitle,
				@rCode,
				 @rIsObsolete,
				 @rOrgGroupId,
				@rCreatedUserId,
				@rCreatedUserId,
				sCommon.fGetDate() ,
				sCommon.fGetDate() ,
				1
			)
			END
			
				IF(@rTable_Name=8)
		BEGIN
			If Exists(select Id from sCommon.tStateMaster where Title=@rTitle AND CountryId=@rDependId AND OrgGroupId=@rOrgGroupId)
				BEGIN
				select -103 as Result
				RETURN
	 		END 
	 		EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sCommon.tStateMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
			INSERT INTO sCommon.tStateMaster
			(
			
				Id,
				Title,
				CountryId,
			
				 IsObsolete,
				 OrgGroupId,
				CreatedUserId,
				UpdateduserId,
				CreatedDateTime,
				UpdatedDateTime ,
				IsShow
			)
		VALUES
			(
				@lNextNumber,
				
				@rTitle,
				@rDependId,
				 @rIsObsolete,
				 @rOrgGroupId,
				@rCreatedUserId,
				@rCreatedUserId,
				sCommon.fGetDate() ,
				sCommon.fGetDate() ,
				1
			)
			END
			
			
				IF(@rTable_Name=9)
		BEGIN
				If Exists(select Id from sCommon.tCityMaster where Title=@rTitle AND StateId =@rDependId AND OrgGroupId=@rOrgGroupId)
				BEGIN
				select -103 as Result
				RETURN
	 		END 
	 		EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sCommon.tCityMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
			INSERT INTO sCommon.tCityMaster
			(
			
				Id,
				Title,
				StateId,
			
				 IsObsolete,
				 OrgGroupId,
				CreatedUserId,
				UpdateduserId,
				CreatedDateTime,
				UpdatedDateTime ,
				IsShow
			)
		VALUES
			(
				@lNextNumber,
				
				@rTitle,
				@rDependId,
				 @rIsObsolete,
				 @rOrgGroupId,
				@rCreatedUserId,
				@rCreatedUserId,
				sCommon.fGetDate() ,
				sCommon.fGetDate() ,
				1
			)
			END
			
				IF(@rTable_Name=10)
		BEGIN
				If Exists(select Id from sCommon.tHobbyMaster where Title=@rTitle AND OrgGroupId=@rOrgGroupId)
				BEGIN
				select -103 as Result
				RETURN
	 		END 
	 		EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sCommon.tHobbyMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
			INSERT INTO sCommon.tHobbyMaster
			(
			
				Id,
				Title,
				Code,
				 IsObsolete,
				 OrgGroupId,
				CreatedUserId,
				UpdateduserId,
				CreatedDateTime,
				UpdatedDateTime 
			 
			)
		VALUES
			(
				@lNextNumber,
				
				@rTitle,
				@rCode,
				 @rIsObsolete,
				 @rOrgGroupId,
				@rCreatedUserId,
				@rCreatedUserId,
				sCommon.fGetDate() ,
				sCommon.fGetDate() 
				 
			)
			END
			
		-- IF(@rTable_Name=11)
		--BEGIN
		--		If Exists(select Id from sCommon.tHostelMaster where Title=@rTitle AND OrgGroupId=@rOrgGroupId)
		--		BEGIN
		--		select -103 as Result
		--		RETURN
	 --		END 
	 --		EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sCommon.tHostelMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
		--	INSERT INTO sCommon.tHostelMaster
		--	(
			
		--		Id,
		--		Title,
		--		Code,
		--		 IsObsolete,
		--		 OrgGroupId,
		--		CreatedUserId,
		--		UpdateduserId,
		--		CreatedDateTime,
		--		UpdatedDateTime 
			 
		--	)
		--VALUES
		--	(
		--		@lNextNumber,
				
		--		@rTitle,
		--		@rCode,
		--		 @rIsObsolete,
		--		 @rOrgGroupId,
		--		@rCreatedUserId,
		--		@rCreatedUserId,
		--		sCommon.fGetDate() ,
		--		sCommon.fGetDate() 
				 
		--	)
		--	END
		 
		 	
		 IF(@rTable_Name=11)
		BEGIN
				If Exists(select Id from sCommon.tAreaMaster where Title=@rTitle AND CityId =@rDependId AND OrgGroupId=@rOrgGroupId)
				BEGIN
				select -103 as Result
				RETURN
	 		END 
	 		EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sCommon.tAreaMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
			INSERT INTO sCommon.tAreaMaster
			(
			
				Id,
				Title,
				CityId,
				 IsObsolete,
				 OrgGroupId,
				CreatedUserId,
				UpdateduserId,
				CreatedDateTime,
				UpdatedDateTime,
				IsShow
			 
			)
		VALUES
			(
				@lNextNumber,
				
				@rTitle,
				@rDependId,
				 @rIsObsolete,
				 @rOrgGroupId,
				@rCreatedUserId,
				@rCreatedUserId,
				sCommon.fGetDate() ,
				sCommon.fGetDate() ,
				1
				
				 
			)
			END
		 
		  IF(@rTable_Name=12)
		BEGIN
				If Exists(select Id from sCommon.tFamiliyCastMaster where FamiliyCast=@rTitle AND CastCategoryId=@rDependId AND OrgGroupId=@rOrgGroupId)	--add CastCategoryId
				BEGIN
				select -103 as Result
				RETURN
	 		END 
	 		
	  
	 		EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sCommon.tFamiliyCastMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
			INSERT INTO sCommon.tFamiliyCastMaster
			(
			
				Id,
				FamiliyCast, 
				 FamiliySubCast, 
				 OrgGroupId,
				 IsObsolete,
				CreatedUserId,
				UpdateduserId,
				CreatedDateTime,
				UpdatedDateTime,
				CastCategoryId,		--added
				ReligionId			--added
			 
			 
			)
		VALUES
			(
				@lNextNumber,
				@rTitle, 
				@rCode,
				 @rOrgGroupId,
				 @rIsObsolete,
				@rCreatedUserId,
				@rCreatedUserId,
				sCommon.fGetDate() ,
				sCommon.fGetDate(),
				@rDependId,			--added
				-1					--added
				 
				
				 
			)
			END
			
			
			
			 IF(@rTable_Name=13	)
		BEGIN
		If Exists(select Id from sSetup.tSubjectMaster where Code=@rCode AND OrgId=@rOrgId)			--add if condition
			BEGIN
			select -102 as Result
			RETURN
		END
				If Exists(select Id from sSetup.tSubjectMaster where Title=@rTitle   AND OrgId=@rOrgId)
				BEGIN
				select -103 as Result
				RETURN
				END
				If Exists(select Id from sSetup.tSubjectMaster where Number=@rNo and OrgId=@rOrgId)		--add if condition
			BEGIN
			select -104 as Result
			RETURN
	 		END 
	 		
	  
	 		EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sSetup.tSubjectMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
			INSERT INTO sSetup.tSubjectMaster
			(
			
				Id,
				Code, 
				 Number, 
				 Title,
				 IsObsolete,
				 OrgId,
				 OrderIndex,
				CreatedUserId,
				UpdateduserId,
				CreatedDateTime,
				UpdatedDateTime 
			 
			 
			)
		VALUES
			(
				@lNextNumber,
				@rCode,
				@rNo,
				@rTitle, 
				 @rIsObsolete,
				 @rOrgId,
				 @rNo,
				@rCreatedUserId,
				@rCreatedUserId,
				sCommon.fGetDate() ,
				sCommon.fGetDate()  
				 
				
				 
			)
			END
			
			
			SELECT 1 AS Result
			
			
		 
 
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Altering [sCommunication].[pAssignedQueryListGet]...';


GO
ALTER PROCEDURE [sCommunication].[pAssignedQueryListGet]
	 
	 @rOrgGroupId smallint,
	 @rOrgGroupBatchId int,
	 @rSourceId bigint,
	 @rSourceTypeId smallint,
	 @rStatusId int,
	 @rFromDate datetime = NULL,
	 @rToDate datetime = NULL
	
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
		
BEGIN 
	SELECT 
			 Q.Id AS QueryId,
			 Q.Title AS QueryTitle,
			 Q.Remark AS QueryRemark,
			 SM.Id AS QueryStatusId,
			 SM.Title AS QueryStatus,
			 QCM.Title AS QueryCategoryTitle,
			 QCA.QueryCategoryId,
			 (CONVERT(VARCHAR(25),Q.CreatedDateTime, 100)) AS QueryCreatedDateTime,
			 (CASE WHEN U.SourceTypeId = 95 THEN 	'Employee'
			 WHEN U.SourceTypeId = 2003 THEN	'Student' END ) AS SourceType,
			 (CASE WHEN U.SourceTypeId = 95 THEN (SELECT EmployeeName FROM sHrm.vEmployeeCommonDetail WHERE EmployeeId= U.SourceId )	 
			 WHEN U.SourceTypeId = 2003 THEN (SELECT Name FROM sStudent.vStudentAcademic WHERE StudentId= U.SourceId AND OrgGroupBatchId = @rOrgGroupBatchId)  END ) AS SourceName,
			  (CASE WHEN U.SourceTypeId = 95 THEN (SELECT DepartmentName FROM sHrm.vEmployeeCommonDetail WHERE EmployeeId= U.SourceId )	 
			 WHEN U.SourceTypeId = 2003 THEN (SELECT ClassName +' - ' + DivisionName FROM sStudent.vStudentAcademic WHERE StudentId= U.SourceId AND OrgGroupBatchId = @rOrgGroupBatchId)  END ) AS ClasDivOrDept,
			 (CASE WHEN U.SourceTypeId = 95 THEN (SELECT OM.Title FROM sHrm.vEmployeeCommonDetail vECD INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = vECD.OrgID WHERE vECD.EmployeeId= U.SourceId )	 
			 WHEN U.SourceTypeId = 2003 THEN (SELECT OrganizationName FROM sStudent.vStudentAcademic WHERE StudentId= U.SourceId AND OrgGroupBatchId = @rOrgGroupBatchId)  END ) AS OrgTitle,
			 ISNULL(Q.Number,0) AS QueryNumber
	FROM 
				sCommunication.tQueryCategoryAssignedTo QCA
			INNER JOIN sCommunication.tQuery Q ON Q.QueryCategoryId = QCA.QueryCategoryId AND (Q.StatusId=@rStatusId)
			INNER JOIN sSecurity.tUser U ON U.Id = Q.CreatedUserId
			INNER JOIN sCommunication.tQueryCategoryMaster QCM ON QCM.Id=QCA.QueryCategoryId AND (QCM.OrgGroupId = @rOrgGroupId)	
			INNER JOIN sCommon.tStatusMaster SM ON SM.Id = Q.StatusId
	WHERE 
			(QCA.SourceTypeId = @rSourceTypeId) 
			AND (QCA.SourceId = @rSourceId) 
			AND ((Q.CreatedDateTime >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
			AND ((Q.CreatedDateTime <= @rToDate) OR (ISNULL(@rToDate,'')=''))
			AND (Q.OrgGroupBatchId = @rOrgGroupBatchId OR @rOrgGroupBatchId = 0)
	ORDER BY Q.CreatedDateTime Asc	
END
GO
PRINT N'Altering [sCommunication].[pBehaviourTypeMasterGet]...';


GO

ALTER PROCEDURE [sCommunication].[pBehaviourTypeMasterGet]
	 
	 @rId int,
	 @rTitle nvarchar(100),
	 @rOrgGroupId smallint,
	 @rBehaviourIndicatorId int = 0
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
	  --BEGIN
			--SET @rTitle = sCommon.fSearchStringGet(@rTitle)
	  --END
	 
	SELECT 
	BTM.Id,
	BTM.Title,
	BTM.Remark,
	BTM.BehaviourIndicatorId,
	BIM.Title AS BehaviourIndicatorTitle,
	BTM.OrgGroupId,
	BTM.IsObsolete,
	BTM.CreatedUserId,
	BIM.Title AS BehaviourType
  FROM 
        sCommunication.tBehaviourTypeMaster BTM
         INNER JOIN sCommunication.tBehaviourIndicatorMaster BIM
         ON BTM.BehaviourIndicatorId=BIM.Id
  WHERE 
      ((BTM.Id = @rId) OR (@rId = 0))
      AND  ((BTM.Title like @rTitle) OR (ISNULL(@rTitle,'') = '')) 
	  AND BTM.OrgGroupId = @rOrgGroupId	
	  AND ((BIM.Id = @rBehaviourIndicatorId) OR (@rBehaviourIndicatorId = 0))
	  
END
GO
PRINT N'Altering [sCommunication].[pFeedbackDataGet]...';


GO
ALTER PROCEDURE [sCommunication].[pFeedbackDataGet]
	  
        --@rFeedbackId bigint=0 ,
        @rOrgId int=0,
        @rBatchId int,
        @rOrgGroupBatchId int ,
        @rSourceId bigint=0
		
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

	--Declare @lSourceTypeId smallint,@lFeedbackId  bigint=0 
	--SELECT @lFeedbackId=FB.Id FROM sCommunication.tFeedback FB
 --   INNER JOIN sCommunication.tFeedbackAssign FA ON Fa.FeedbackId=FB.Id 
 --   WHERE OrgGroupBatchId=@rOrgGroupBatchId and IsClose=0 and IsPublish=1  AND AssignToSourceId =@rSourceId ORDER BY Title
 
	--Select @lSourceTypeId=ForSourceTypeId from sCommunication.tFeedbackFor where FeedbackId=@lFeedbackId
	
	Select 
		 (CASE ForSourceTypeId WHen  95
		 THEN
			(Select 
			 FirstName +' ' + MiddleName+' ' + LastName
			From sHrm.tEmployeeMaster Where  Id=FF.ForSourceId And FF.ForSourceTypeId=95 And  OrgId=@rOrgId AND ISNULL(IsOtherUser,0) = 0  )
		 WHEN  2001
		 THEN
			(Select
			 FirstName +' ' + MiddleName+' ' + LastName
			From sStudent.tAcademic A
			INNER JOIN  sStudent.tStudentMaster SM ON SM.Id=A.StudentID
			Where A.Id=FF.ForSourceId ANd FF.ForSourceTypeId=2001)
		 Else
			FF.ForName
		 END) AS Name, 
		 
		 (CASE ForSourceTypeId WHen  95
		 THEN
			(Select 
			 Code
			From sHrm.tEmployeeMaster Where  Id=FF.ForSourceId And FF.ForSourceTypeId=95 And  OrgId=@rOrgId AND ISNULL(IsOtherUser,0) = 0  )
		 WHEN  2001
		 THEN
			(Select
			 SM.Code
			From sStudent.tAcademic A
			INNER JOIN  sStudent.tStudentMaster SM ON SM.Id=A.StudentID
			Where A.Id=FF.ForSourceId ANd FF.ForSourceTypeId=2001)
		 Else
			FF.ForName
		 END) AS Code, 
		 
		 (CASE ForSourceTypeId WHen  95
		 THEN
			(Select 
			 Id
			From sHrm.tEmployeeMaster Where  Id=FF.ForSourceId And FF.ForSourceTypeId=95 And  OrgId=@rOrgId AND ISNULL(IsOtherUser,0) = 0  )
		 WHEN  2001
		 THEN
			(Select
			 A.Id
			From sStudent.tAcademic A
			INNER JOIN  sStudent.tStudentMaster SM ON SM.Id=A.StudentID
			Where A.Id=FF.ForSourceId ANd FF.ForSourceTypeId=2001)
		 Else
			0  
		 END) AS Id, 
		 FF.Id AS FeedbackForId,
		FB.Id AS FeedbackId,FB.Title ,
		FB.FeedbackTemplateId
	 FROM sCommunication.tFeedbackFor FF 
	 INNER JOIN sCommunication.tFeedback FB ON FB.Id=FF.FeedbackId
	 INNER JOIN sCommunication.tFeedbackAssign FA ON Fa.FeedbackId=FB.Id
	 Where FB.OrgGroupBatchId=@rOrgGroupBatchId and IsClose=0 and IsPublish=1  AND AssignToSourceId =@rSourceId 
	 
	--If @lSourceTypeId=2001
	--BEGIN
	--	SELECT FB.Id AS FeedbackId,FB.Title,A.Id,Code+' - '+FirstName+' '+MiddleName+' '+LastName AS name 
	--	 FROM sCommunication.tFeedback FB
	--	--INNER JOIN sCommunication.tFeedbackAssign FA ON Fa.FeedbackId=FB.Id 
	--	INNER JOIN sCommunication.tFeedbackAssign FA ON Fa.FeedbackId=FB.Id
	--	INNER JOIN sCommunication.tFeedbackFor FO ON FO.FeedbackId=FB.ID
	--	INNER JOIN sStudent.tAcademic A  on FO.ForSourceId=A.Id
	--	INNER JOIN sStudent.tStudentMaster SM ON SM.Id=A.StudentId
	--	Where SM.OrgId=@rOrgId   And A.BatchId=@rBatchId
	--	And FB.OrgGroupBatchId=@rOrgGroupBatchId and IsClose=0 and IsPublish=1  AND AssignToSourceId =@rSourceId 
	
	-- END
	
	--else if  @lSourceTypeId=95
	--BEGIN
	--	SELECT FB.Id AS FeedbackId,FB.Title,EM.Id,Code+' - '+FirstName+' '+MiddleName+' '+LastName AS name 
	--	 FROM sCommunication.tFeedback FB
	--	--INNER JOIN sCommunication.tFeedbackAssign FA ON Fa.FeedbackId=FB.Id 
	--	INNER JOIN sCommunication.tFeedbackAssign FA ON Fa.FeedbackId=FB.Id
	--	INNER JOIN sCommunication.tFeedbackFor FO ON FO.FeedbackId=FB.ID
	--	INNER JOIN sHrm.tEmployeeMaster EM  on FO.ForSourceId=EM.Id
	--	Where EM.OrgId=@rOrgId  and  OrgGroupBatchId=@rOrgGroupBatchId And IsClose=0 and IsPublish=1 and AssignToSourceId =@rSourceId
	--END
	
	--else
	--BEGIN
		 
	--	SELECT FB.Id AS FeedbackId,FB.Title,FO.ForName AS name,0 AS Id
	--	 FROM sCommunication.tFeedback FB
	--	INNER JOIN sCommunication.tFeedbackAssign FA ON Fa.FeedbackId=FB.Id 
	--	LEFT JOIN sCommunication.tFeedbackFor FO ON FO.FeedbackId=FB.ID  
	--	where   OrgGroupBatchId=@rOrgGroupBatchId and IsClose=0 and IsPublish=1  
	--	AND ISNULL(AssignToSourceId,0) =0 AND ISNULL(ASSIgntosourcetypeid,0)=0
		  
	--END  
END
GO
PRINT N'Altering [sCommunication].[pFeedbackResponseGet]...';


GO
ALTER PROCEDURE [sCommunication].[pFeedbackResponseGet]
	 
	 
	 
	 @rUserSourceId bigint,
	 @rUserSourceTypeId int ,
	 @rOrgGroupBatchId int,
	 @rOrgGroupId smallint,
	 @rFeedbackId bigint ,
	  @rFeedbackForId bigint
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	 SELECT	
		FQ.Id As TempateQuestionId,
					FQ.QuestionNumber,
					FQ.Question ,
					FQ.FeedbackAnswerTypeID,			 
					ISNULL(FQR. FeedbackAnswerTypeDetailId,0) AS FeedbackAnswerTypeDetailId,
					FR.SourceId ,
					ISNULL(FQR.FeedbackAnswerDescription,'') AS FeedbackAnswerDescription,
					FR.Id 
					--FB.FeedbackTemplateId
		from sCommunication.tFeedback FB 
		INNER JOIN	sCommunication.tFeedbackTemplateQuestion FQ ON FQ.FeedbackTemplateId = FB.FeedbackTemplateId
		LEFT JOIN sCommunication.tFeedbackResponse FR ON FR.FeedbackId = FB.Id AND FR.FeedbackForId =@rFeedbackForId  AND  SourceId = @rUserSourceId 		
				    AND SourceTypeId=@rUserSourceTypeId 
		Left Join sCommunication.tFeedbackQuestionResponse FQR ON  FQR.FeedBackResponseId = FR.Id 
		AND FQR.FeedbackTemplateQuestionID = FQ.Id
		--AND FQR.FeedBackResponseId = 1001000000001
		--LEFT JOIN sCommunication.tFeedbackAnswerTypeDetail FA ON FA.ID=FQR.FeedbackAnswerTypeDetailId
		WHERE FB.Id = @rFeedbackId ANd OrgGroupBatchId=@rOrgGroupBatchId
	 
		 END
GO
PRINT N'Altering [sCommunication].[pFeedbackTemplateAdd]...';


GO
ALTER PROCEDURE [sCommunication].[pFeedbackTemplateAdd]
	 
	 	@rOrgGroupId smallint,
        @rId bigint=0,
        @rCode nvarchar(200),
        @rTitle nvarchar(200), 
		@rCreatedUserId bigint ,
		@rOrgGroupBatchId int ,
		@rIsAllAnsRequired bit = 0
		
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	 DECLARE @lNextNumber BIGINT 

	 
	IF(@rId = 0)	
	BEGIN
		 
		if exists(Select 1 from sCommunication.tFeedbackTemplate where Code=@rCode AND OrgGroupId=@rOrgGroupId)
	BEGIn
		Select -101 As Result
		Return
	END
	
	If exists(Select 1 from sCommunication.tFeedbackTemplate where Title =@rTitle AND OrgGroupId=@rOrgGroupId)
	BEGIN
		Select -102 As Result
		Return
	END
	
	EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sCommunication.tFeedbackTemplate', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	INSERT INTO sCommunication.tFeedbackTemplate
		(
			Id,
			Code,
			Title, 
			OrgGroupId,
			CreatedUserId,
			CreatedDateTime,
			IsAllAnsRequired 
			 
		)
	VALUES
		(
			@lNextNumber,
			@rCode,
			@rTitle, 
			@rOrgGroupId,
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rIsAllAnsRequired 
		)
		    SELECT @lNextNumber AS Result
	END	 

ELSE
	 BEGIN
		if exists(Select 1 from sCommunication.tFeedbackTemplate where Code=@rCode AND OrgGroupId=@rOrgGroupId AND Id<>@rId)
	BEGIn
		Select -101 As Result
		Return
	END
	
	If exists(Select 1 from sCommunication.tFeedbackTemplate where Title =@rTitle AND OrgGroupId=@rOrgGroupId AND ID<>@rId)
	BEGIN
		Select -102 As Result
		Return
	END
	
	 if exists(Select 1 from sCommunication.tFeedback where OrgGroupBatchId =@rOrgGroupBatchId and FeedbackTemplateId=@rId)
	 BEGIN
		select -111 As Result
		return
	 
	 END
	
	    UPDATE  sCommunication.tFeedbackTemplate
	    SET
			Code=@rCode,
			Title=@rTitle, 
			UpdatedUserId=@rCreatedUserId,
			UpdatedDateTime=sCommon.fGetDate(),
			IsAllAnsRequired  = @rIsAllAnsRequired
	      
	      WHERE Id = @rId
	      SELECT @rId AS Result
	 END  	

	
	END TRY
	
	BEGIN CATCH 
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Altering [sCommunication].[pFeedbackTemplateGet]...';


GO
ALTER PROCEDURE [sCommunication].[pFeedbackTemplateGet]
	 
	 	 
        @rCode nvarchar(200),
        @rTitle nvarchar(200),
        @rId bigint=0,
        @rOrgGroupId int
		
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	Select 
		 Id,
		 Code,
		 Title, 
		 OrgGroupId,
		CreatedUserId,
		CreatedDateTime,
		ISNULL(IsAllAnsRequired,0) AS IsAllAnsRequired
		
	from sCommunication.tFeedbackTemplate  
	Where (( Code=@rCode) OR (ISNULL(@rCode,'')=''))
	AND (( Title=@rTitle) OR (ISNULL(@rTitle,'')=''))
	AND (( Id=@rId) OR (@rId=0))
	AND OrgGroupId=@rOrgGroupId
		
END
GO
PRINT N'Altering [sCommunication].[pMyBookGet]...';


GO
ALTER PROCEDURE [sCommunication].[pMyBookGet]
	 
	 @rReaderSourceTypeId smallint,
	 @rReaderSourceId bigint,
	 @rBatchId int,
	 @rStatusId int=0,
	 @rLibraryId int=0
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 



	select 
		BL.Id AS BookLogId,
		BM.Title AS BookTitle,
		BL.LogDate AS IssueDate,
		--BL.IsCurrentStatus AS IsReturnPending,
		BL.StatusId AS StatusId,
		--SM.Title As StatusName,
		(CASE WHEN (ISNULL(BL.ReturnDate,'')!='' OR BL.BookActionStatusId=1) THEN 'Return'
			 WHEN BL.BookActionStatusId=2 THEN 'Release'
			 ELSE SM.Title END) AS StatusName,
		CASE WHEN BL.IsCurrentStatus = 1 THEN 'Pending' ELSE 'Return' END AS IsReturnPending,
		BL.DueDate,
		BL.LibraryId ,
		ISNULL(BM.Author,'')AS Author
	--CASE WHEN BL.IsCurrentStatus = 0 THEN BL.DueDate ELSE '' END AS DueDate

	  from 
		  sLibrary.tBookLog BL 
		  INNER JOIN sLibrary.tBookMaster BM
		  ON BL.ResourceSourceId = BM.Id AND BL.ResourceSourceTypeId = 2009  
		  LEFT JOIN sCommon.tStatusMaster SM ON SM.Id = BL.StatusId AND SM.statusTypeId = 106
	  WHERE 
		  --BL.statusId = 523
		  BL.ReaderSourceId = @rReaderSourceId
		  AND BL.ReaderSourceTypeId = @rReaderSourceTypeId
		  AND (BL.StatusId = @rStatusId OR @rStatusId=0)
		  AND (BL.LibraryId= @rLibraryId OR @rLibraryId=0)
		  AND (SM.Id!=521 OR ISNULL(BL.BookActionStatusId,0)!=0)
		  AND (BL.BatchId = @rBatchId OR @rBatchId = 0)
	  
	  ORDER BY BL.LogDate DESC,BL.CreatedDateTime DESC

END
GO
PRINT N'Altering [sCommunication].[pQueryCategoryDropdownGet]...';


GO
ALTER PROCEDURE [sCommunication].[pQueryCategoryDropdownGet]
	@rOrgGroupBatchId int,
	@rUserSourceId bigint,
	@rUserSourceTypeId int
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
	DECLARE @lAcademicId bigint,@lStudentId bigint,@lClassId int,@lDivisionId int,@lOrgId int,@lDepartmentId int,@lEmployeeId bigint

	IF @rUserSourceTypeId = 95 -- For Employee Login
	BEGIN
		SELECT 
			@lDepartmentId=EJD.OrganizationDepartmentId,
			@lOrgId = EM.OrgId,
			@lEmployeeId = EM.Id 
		FROM 
			sHrm.tEmployeeMaster EM INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id 
		WHERE 
			EM.Id=@rUserSourceId
		
		SELECT Distinct	
			QCM.Id,
			QCM.Title
		FROM 
			sCommunication.tQueryCategoryMaster QCM           
			INNER JOIN 
			(SELECT QCS.QueryCategoryId FROM sCommunication.tQueryCategoryScope QCS
				WHERE (((QCS.SourceTypeId = 2021 AND QCS.SourceId =@lOrgId) OR
				(QCS.SourceTypeId = 2017 AND QCS.SourceId =@lDepartmentId) OR
				(QCS.SourceTypeId = 95 AND QCS.SourceId =@lEmployeeId )) 
				AND ((QCS.AssigneeToId=3) OR (QCS.AssigneeToId IS NULL) OR (ISNULL(QCS.AssigneeToId,0)=0)))) D
				ON D.QueryCategoryId= QCM.Id
			--INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=QCM.OrgGroupBatchId AND OGBM.Id=@rOrgGroupBatchId
			--INNER JOIN sSecurity.tUser U ON U.Id=QCM.CreatedUserId
		WHERE 
			QCM.AssignedToId IN (1,3) 
			AND QCM.IsObsolete = 0

		UNION

		SELECT Distinct	
			QCM.Id,
			QCM.Title
		FROM 
			sCommunication.tQueryCategoryMaster QCM           
			INNER JOIN sCommunication.tQueryCategoryAssignedTo QCA ON QCM.Id = QCA.QueryCategoryId
			AND QCA.SourceTypeId = 95 AND QCA.SourceId =@lEmployeeId
	
		WHERE 
			QCM.AssignedToId IN (1,3) 
			AND QCM.IsObsolete = 0

	END
	ELSE IF @rUserSourceTypeId = 2003 -- For Student Login
	BEGIN
		SELECT 
			@lAcademicId = A.Id,
			@lStudentId = A.StudentId,
			@lClassId = A.ClassId, 
			@lDivisionId = A.DivisionId, 
			@lOrgId= A.OrgId, 
			@lDepartmentId=CM.DepartmentId
		FROM sStudent.tAcademic A 
			INNER JOIN sSetup.tBatchMaster BM ON A.BatchId = BM.Id 
			INNER JOIN sSetup.tClassMaster CM ON CM.Id = A.ClassId
		WHERE StudentId = @rUserSourceId AND BM.OrgGroupBatchId = @rOrgGroupBatchId
  
		SELECT 	Distinct
			QCM.Id,
			QCM.Title
		FROM 
			sCommunication.tQueryCategoryMaster QCM
			INNER JOIN (SELECT QCS.QueryCategoryId 
				FROM sCommunication.tQueryCategoryScope QCS
				WHERE (((QCS.SourceTypeId = 2021 AND QCS.SourceId =@lOrgId) OR
				(QCS.SourceTypeId = 2017 AND QCS.SourceId =@lDepartmentId) OR
				(QCS.SourceTypeId = 2016 AND QCS.SourceId =@lClassId) OR
				(QCS.SourceTypeId = 2005 AND QCS.SourceId =@lDivisionId) OR
				(QCS.SourceTypeId = 2003 AND QCS.SourceId =@lStudentId) OR
				(QCS.SourceTypeId = 2001 AND QCS.SourceId =@lAcademicId) )
				)AND ((QCS.AssigneeToId=2) OR (QCS.AssigneeToId IS NULL) OR (ISNULL(QCS.AssigneeToId,0)=0))) D ON D.QueryCategoryId= QCM.Id 
		WHERE
			QCM.AssignedToId IN (1,2) 
			AND QCM.IsObsolete = 0
	END
	ELSE
	--For Other Users
	BEGIN
		SELECT 	
			QCM.Id,
			QCM.Title
		FROM 
			sCommunication.tQueryCategoryMaster QCM
		WHERE 
			QCM.AssignedToId IN (1,2,3)
			AND QCM.IsObsolete = 0
	END
END
GO
PRINT N'Altering [sFee].[pAssignOtherFeeGet]...';


GO
ALTER PROCEDURE [sFee].[pAssignOtherFeeGet]
	 
		@rOrgId int,
		@rBatchId int,
		@rAdmissionCategoryId int,
		@rDepartmentId int,
		@rClassId int,
		@rDivisionId int,
		@rFilterId tinyint,
		@rOrgGroupBatchId int,
		@rCode nvarchar(max)=''
		 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 		
		
	SELECT 
			SA.AcademicId AS SourceId,
			SA.ClassName +' - '+SA.DivisionName AS Class,
			SA.Code,
			SA.Name,
			SA.RollNo
	FROM 
			sStudent.vStudentAcademic SA
			LEFT JOIN sHostel.tAssignRoom AR ON  AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003 AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) AND AR.OrgGroupBatchId=SA.OrgGroupBatchId 
			--LEFT JOIN sTransport.tAssignRoute AT ON  AT.SourceId=SA.StudentId AND AT.SourceTypeId=2003 AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))
			LEFT JOIN (
				select AT.SourceId,BRDM.Id,AT.SourceTypeId,isnull(BRM.id,0) as PickupDestinationRoutId,isnull(BRM2.id,0) as DropDestinationRoutId From sTransport.tAssignRoute AT 
				Left JOIN sTransport.tBusRouteDestinationMaster BRDM ON BRDM.Id=AT.PickupDestinationId
				Left JOIN sTransport.tBusRouteMaster BRM On BRm.id=BRDM.BusRouteId  --AnD BRM.OrgGroupBatchId=@rOrgGroupBatchId
				LEFT JOIN sTransport.tBusRouteDestinationMaster BRDM2 ON BRDM2.Id=AT.DropDestinationId	
			    LEFT JOIN sTransport.tBusRouteMaster BRM2 On BRM2.Id=BRDM2.BusRouteId  --AND BRM2.OrgGroupBatchId=@rOrgGroupBatchId
				where  BRM.OrgGroupBatchId=@rOrgGroupBatchId or BRM2.OrgGroupBatchId=@rOrgGroupBatchId
			) A ON  A.SourceId=SA.StudentId AND A.SourceTypeId=2003 AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) 
	WHERE 
		(SA.OrgId=@rOrgId) 
		AND (SA.BatchId=@rBatchId)
		AND ((SA.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
		AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
		AND ((SA.ClassId=@rClassId) OR (@rClassId=0))
		AND ((SA.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		AND (SA.StatusId=1)
		AND (
		(@rFilterId = 0) -- All
		OR (@rFilterId = 2 AND ISNULL(AR.SourceId,0)!=0) -- Hostel
		--OR (@rFilterId = 3 AND ISNULL(AT.SourceId,0)!=0) -- Transport
		OR (@rFilterId = 3 AND ISNULL(A.SourceId,0)!=0) -- Transport
		--OR ((@rFilterId =1) AND ((ISNULL(AR.SourceId,0)=0) AND (ISNULL(AT.SourceId,0)=0))) -- School
		OR ((@rFilterId =1) AND ((ISNULL(AR.SourceId,0)=0) AND (ISNULL(A.SourceId,0)=0))) -- School
		)
		AND (ISNULL(SA.Code,0) IN( SELECT cast(item as nvarchar(20)) FROM  sCommon.fnsplit(@rCode,',')) OR @rCode='') 
		ORDER BY SA.ClassOrderIndex, SA.DivisionOrder, SA.RollNo
END
GO
PRINT N'Altering [sFee].[pFeeAllocationViewGet]...';


GO
ALTER PROCEDURE [sFee].[pFeeAllocationViewGet]
	 
		
		@rSourceId bigint ,
		@rSourceTypeId int,
		@rBatchId int
		--@rStudentId bigint =0
		
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
		
BEGIN 	
	--if (@rStudentId <> 0)
	--SELECT @rSourceId = Id FROM sStudent.tAcademic WHERE StudentId = @rStudentId AND BatchId = @rBatchId
		DECLARE @lClassId int
		DECLARE @lAdmissionCategoryId int
		SELECT @lClassId=ClassId,@lAdmissionCategoryId=AdmissionCategoryId FROM sStudent.vStudentAcademic WHERE AcademicId=@rSourceId

SELECT 
			FM.Title AS FeeName,
			FS.Id AS FeeSetupId,
			ISNULL(FS.IsOptional,0)AS IsOptional,
			ISNULL(FS.IsVariable,0)AS IsVariable,
			--CASE WHEN FA.VariableAmount > 0 THEN FA.VariableAmount ELSE ISNULL(FS.Amount,0) END AS Amount,
			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.NotApplicableAmount,0.00) AS NotApplicableAmount,
			ISNULL(FA.Remark,'') AS Remark,
			FM.OrderIndex,
			0 AS ReceiptNumber,
			'1900-01-01'AS ReceiptDate,
			ISNULL(FS.ReceiptBookId,0) AS ReceiptBookId,
			FS.CollectionGroupId,
			FM.FeeHeadId
			
  FROM 
			sFee.tFeeMaster FM
		INNER JOIN 
		(
			SELECT 
				FS1.FeeId,
				FS1.Id,
				ISNULL(FS1.IsOptional,0)AS IsOptional,
				ISNULL(FS1.IsVariable,0)AS IsVariable,
				ISNULL(FS1.Amount,0)AS Amount,
				ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
				ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
				FS1.BatchId,
				ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
				ISNULL(FS1.CollectionGroupId,0) AS CollectionGroupId
				 
			FROM sFee.tFeeSetup FS1
			   
				WHERE FS1.ClassId=@lClassId AND FS1.AdmissionCategoryId=@lAdmissionCategoryId AND IsOptional=0
				AND FS1.BatchId = @rBatchId
				UNION ALL
				
			SELECT 
				FS1.FeeId,
				FS1.Id,
				ISNULL(FS1.IsOptional,0)AS IsOptional,
				ISNULL(FS1.IsVariable,0)AS IsVariable,
				ISNULL(FS1.Amount,0)AS Amount,
				ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
				ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
				FS1.BatchId,
				ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
				ISNULL(FS1.CollectionGroupId,0) AS CollectionGroupId 
				 
			FROM sFee.tFeeSetup FS1
			 
		INNER JOIN sFee.tFeeOptional FO
			ON FO.FeeSetupId=FS1.Id AND (FO.SourceId=@rSourceId) AND(FO.SourceTypeId=@rSourceTypeId)
			WHERE
			 FS1.BatchId = @rBatchId
			AND	FS1.ClassId=@lClassId AND FS1.AdmissionCategoryId=@lAdmissionCategoryId AND IsOptional=1
		) FS ON FS.FeeId=FM.Id
		LEFT JOIN sFee.tFeeAllocation FA
			ON FA.FeeSetupId=FS.Id AND (FA.SourceId=@rSourceId) AND(FA.SourceTypeId=@rSourceTypeId)
		LEFT JOIN
		(
		    SELECT ISNULL(SUM(RD.Amount),0) AS PaidAmount,RD.FeeSetupId
		    FROM
		    sFee.tReceipt R INNER JOIN sFee.tReceiptDetail RD ON	RD.ReceiptId = R.Id 		
			WHERE						
			 R.SourceId= @rSourceId
			AND ((R.SourceTypeId = @rSourceTypeId) OR (@rSourceTypeId=0))
			AND R.IsObsolete = 0 
			AND R.BatchId = @rBatchId
			 GROUP BY FeeSetupId
		) R ON R.FeeSetupId = FS.Id	
WHERE 
	FS.BatchId=@rBatchId
ORDER BY FS.StartDate ASC,FM.OrderIndex ASC

END
GO
PRINT N'Altering [sHrm].[pLeaveApproveValidate]...';


GO

 
ALTER PROCEDURE [sHrm].[pLeaveApproveValidate]

        @rId bigint,
        @rEmployeeId bigint,
        @rFromDate date,
        @rLeaveTypeId int,
        @rNoOfLeave decimal(5,2),
        @rBatchId int,
        @rOrgId int
        
AS
SET NOCOUNT ON

BEGIN
	IF EXISTS (SELECT 1 FROM  sHrm.tLeaveTypeMaster WHERE Id = @rLeaveTypeId AND isLwp = 0)
	BEGIN
	   DECLARE @lMainLeaveTypeId tinyint
	   SET @lMainLeaveTypeId =0
	   SELECT @lMainLeaveTypeId = ISNULL(MainLeaveTypeId,0) FROM sHrm.tLeaveTypeMaster WHERE Id = @rLeaveTypeId
	   
	   DECLARE @lMaxInMonth decimal(5,2)
	   DECLARE @lNumberOfLeave decimal(5,2)
	   SET @lMaxInMonth =0
	   SET @lNumberOfLeave =0
	   
	   DECLARE @lFirstDate date
	   DECLARE @lLastDate date
	   
	   SET @lFirstDate = DATEADD(mm, DATEDIFF(mm, 0, @rFromDate), 0)
	   SET @lLastDate = DATEADD (dd, -1, DATEADD(mm, DATEDIFF(mm, 0, @rFromDate) + 1, 0))
	   
	   SELECT @lMaxInMonth = ISNULL(LB.MaxInMonth,0) FROM sHrm.tEmployeeJobDetail EJD 
	   INNER JOIN sHrm.tLeaveBalance LB ON LB.EmployeeId=EJD.EmployeeId AND LB.BatchId = @rBatchId
	   WHERE EJD.OrgId = @rOrgId AND LB.LeaveTypeId=@rLeaveTypeId AND EJD.EmployeeId=@rEmployeeId
	   
	   -- For Employee Specific 08/11/2017 - by Ramesh Gurjar
	   IF(@lMaxInMonth=0)
	   BEGIN
			SELECT @lMaxInMonth = ISNULL(LTGS.MaxInMonth,0) FROM sHrm.tEmployeeJobDetail EJD 
			INNER JOIN sHrm.tLeaveTypeGradeSettings LTGS ON EJD.EmployeeGradeId=LTGS.EmployeeGradeId 
			WHERE LTGS.OrgId = @rOrgId 
			AND LTGS.LeaveTypeId=@rLeaveTypeId 
			AND  EJD.EmployeeId=@rEmployeeId
	   END
	   
	   --BEGIN LEAVE CARY FORWARD VALIDATION
		DECLARE @lLeaveCarryForwordRuleId int=1
		DECLARE @lMonthDiffrence int
		Declare @lDateofJoining date = (SELECT DateOfJoining FROM sHrm.tEmployeeJobDetail WHERE EmployeeId = @rEmployeeId)
		 SELECT @lLeaveCarryForwordRuleId=ISNULL(LTGS.LeaveCarryForwordRuleId,1) FROM sHrm.tEmployeeJobDetail EJD
		 INNER JOIN sHrm.tLeaveTypeGradeSettings LTGS ON EJD.EmployeeGradeId=LTGS.EmployeeGradeId 
		 WHERE LTGS.OrgId =@rOrgId
		 AND LTGS.LeaveTypeId=@rLeaveTypeId
		 AND  EJD.EmployeeId=@rEmployeeId

		 
		 if(@lLeaveCarryForwordRuleId=1)
		 Begin
		  set @lMaxInMonth=@lMaxInMonth
		 END
		 else if(@lLeaveCarryForwordRuleId=2)
		 Begin
			 select @lMaxInMonth= Case When @lDateofJoining<LeaveYearFromDate Then @lMaxInMonth*(DATEDIFF(month,LeaveYearFromDate,@rFromDate)+1) else @lMaxInMonth*(DATEDIFF(month,LeaveYearFromDate,@lDateofJoining)+1) end 
			 ,@lFirstDate=Case When @lDateofJoining<LeaveYearFromDate Then LeaveYearFromDate else @lDateofJoining END from [sSetup].[tBatchMaster] WHere Id=@rBatchId
		 END
		
	   --END LEAVE CARY FORWARD VALIDATION
	   


	   SELECT  @lNumberOfLeave= ISNULL(SUM(L.NoOfLeave),0) 
	   FROM     
	   sHrm.tLeave L  
	   WHERE  
	   L.EmployeeId=@rEmployeeId 
	   AND (L.FromDate>=@lFirstDate) AND (L.FromDate<=@lLastDate)
	   AND L.LeaveTypeId=@rLeaveTypeId AND L.StatusId = 550
	   GROUP BY L.EmployeeId
	   
	   IF (@lMaxInMonth < (@lNumberOfLeave+@rNoOfLeave) AND @lMainLeaveTypeId!=3)
	   BEGIN
			SELECT -105  AS RESULT
			RETURN
	   END
	   ELSE
	   BEGIN
			SELECT 1
	   END	
   END
   ELSE 
   SELECT 1
END
GO
PRINT N'Altering [sHrm].[pLeaveTypeGradeSeetingListGet]...';


GO

ALTER PROCEDURE [sHrm].[pLeaveTypeGradeSeetingListGet]
    @rEmployeeGradeId int = 0,
    @rOrgId int
AS
SET NOCOUNT ON

BEGIN
       
       SELECT 
				 LTM.Id AS LeaveTypeId,
				 LTM.Title AS LeaveType,
				 ISNULL(LTGS.EmployeeGradeId,0) AS EmployeeGradeId,
				 ISNULL(LTGS.NoOfLeave,'') AS NoOFLeave,
				 ISNULL(LTGS.MaxInMonth,0) AS MaxInMonth,
				 LTGS.LeaveTypeId ,
				 Isnull(LTGS.LeaveCarryForwordRuleId,1) AS LeaveCarryForwordRuleId
       FROM 
			   sHrm.tLeaveTypeMaster LTM 
		   LEFT JOIN sHrm.tLeaveTypeGradeSettings LTGS ON LTGS.LeaveTypeId = LTM.Id AND EmployeeGradeId = @rEmployeeGradeId
       WHERE 
			   LTM.IsObsolete = 0
			AND LTM.OrgId = @rOrgId   AND IsLWP = 0
END
GO
PRINT N'Altering [sHrm].[pLeaveTypeGradeSettingAdd]...';


GO
ALTER PROCEDURE [sHrm].[pLeaveTypeGradeSettingAdd]
           
           @rLeaveTypeId int,
           @rEmployeeGradeId int,
           @rNoOfLeave int,
           @rMaxInMonth decimal(5,2),          
           @rOrgId smallint,
		   @rLeaveCarryForwordRuleId int=1
        
AS
SET NOCOUNT ON

BEGIN

	BEGIN TRY
	
	BEGIN TRANSACTION

	DECLARE @lNextNumber bigint	  
	
	IF EXISTS(SELECT 1 FROM sHrm.tLeaveTypeGradeSettings WHere LeaveTypeId = @rLeaveTypeId AND OrgId = @rOrgId AND EmployeeGradeId = @rEmployeeGradeId)
	DELETE FROM sHrm.tLeaveTypeGradeSettings WHere LeaveTypeId = @rLeaveTypeId AND OrgId = @rOrgId AND EmployeeGradeId = @rEmployeeGradeId
	
	BEGIN		     
		   INSERT INTO [sHrm].[tLeaveTypeGradeSettings]
           (
            [OrgId]
           ,[LeaveTypeId]
           ,[EmployeeGradeId]
           ,[NoOfLeave]
           ,[MaxInMonth]
		   ,[LeaveCarryForwordRuleId]
           )
     VALUES
           (
            @rOrgId
           ,@rLeaveTypeId
           ,@rEmployeeGradeId
           ,@rNoOfLeave
           ,@rMaxInMonth
		   ,@rLeaveCarryForwordRuleId
           )		 
          END
	   SELECT 1 AS Result	   
	   COMMIT TRANSACTION
	   		
	END TRY	
	BEGIN CATCH
		ROLLBACK TRANSACTION
		SELECT -1 AS RESULT
	END CATCH
	
END
GO
PRINT N'Altering [sHrm].[pRptJoiningCertificateGet]...';


GO

ALTER PROCEDURE [sHrm].[pRptJoiningCertificateGet]  
 
  @rEmployeeId [bigint]= 0, 
  @rBuilder1 nvarchar(max)='',  
  @rBuilder2 nvarchar(max)='',    
  @rOrgId smallint,  
  @rCode nvarchar(20)='',  
  @rFromNo int=0,  
  @rToNo int=0,  
  @rFromDate date='',  
  @rToDate date='',  
  @rName nvarchar(20)=''

WITH EXECUTE AS CALLER  
AS  
SET NOCOUNT ON  
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED  
  
BEGIN  
DECLARE @lIsOnPrePrinted bit = 0  
  
DECLARE @lConfigValue nvarchar(50)  
DECLARE @lIsDisplayImageHeader bit=0  
  
SELECT @lConfigValue = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 182 AND SourceTypeId = 1016 AND SourceId = @rOrgId  
   
 IF (@lConfigValue IS NULL) OR (@lConfigValue = 'Default')  
 BEGIN  
 SET @lIsOnPrePrinted = 0  
 SET @lIsDisplayImageHeader = 0  
 END  
 ELSE IF (@lConfigValue = 'Blank')  
 BEGIN  
 SET @lIsOnPrePrinted = 1  
 SET @lIsDisplayImageHeader = 0  
 END  
 ELSE IF (@lConfigValue = 'Image')  
 BEGIN  
 SET @lIsOnPrePrinted = 0  
 SET @lIsDisplayImageHeader = 1  
 END  
   
 SELECT  
   @rBuilder1 AS Builder1,  
   @rBuilder2 AS Builder2,  
   EM.Id AS EmployeeId,
   CJ.Number,
   EM.EmployeeName,
   EM.FirstName,  
   EM.MiddleName,  
   EM.LastName,      
   EM.Code,    
   EM.ShortName,  
   EM.OrgID,  
   EM.DepartmentId,  
   EM.DepartmentName,  
   EM.DesignationId,  
   EM.Designation,  
   EM.EmployeePhoto, 
   EM.DateOfJoining, 
   @lIsOnPrePrinted AS IsOnPrePrinted,  
   @lIsDisplayImageHeader AS IsDisplayImageHeader,  
   OI.CertificateHeaderA4 ,  
   CJ.Remark,  
   ISNULL(CJ.CertificateDate,'') AS CertificateDate,  
   EM.MaritalStatusId,  
   CJ.PayScale,  
   CJ.AgreementPeriod,
   CJ.CertificateRemark,
   OM.Title As OrgTitle,
   CJ.CreatedDateTime As CreatedDateTime,
   U.DisplayTitle As UserDisplayName,
   EDM.Title AS EmployeeDesignation,
   OM.DisplayTitle As ShortTitle,
   DM.Title AS DepartmentName1,
   EM.MobileNumber,
   --EC.PresentStreetOne+'-'+EC.PresentStreetTwo+ '-' +EC.PresentStreetThree AS LocalAddress,
    EC.PresentStreetOne  + CASE WHEN EC.PresentStreetOne = '' OR (EC.PresentStreetTwo = '' AND EC.PresentStreetThree = '') Then '' ELSE '-' END 
   		    + EC.PresentStreetTwo + CASE WHEN EC.PresentStreetTwo = '' OR EC.PresentStreetThree = '' Then '' ELSE '-' END	
			+ EC.PresentStreetThree AS LocalAddress,
   --EC.PresentCity+ '-'+EC.PresentState+'-'+EC.PresentZipCode+'-'+EC.PresentContactNo As LocalAddress1,
	EC.PresentCity  + CASE WHEN EC.PresentCity = '' OR (EC.PresentState = '' AND EC.PresentZipCode = '' AND EC.PresentContactNo = '') Then '' ELSE '-' END 
		+ EC.PresentState + CASE WHEN EC.PresentState = '' OR (EC.PresentZipCode = '' AND EC.PresentContactNo = '') Then '' ELSE '-' END	
		+ EC.PresentZipCode + CASE WHEN EC.PresentZipCode = '' OR EC.PresentContactNo = '' Then '' ELSE '-' END
		+ EC.PresentContactNo AS LocalAddress1,
   ISNULL(EDM1.Title,'Admin') AS UserDesignation,
   --Replace(Replace(RTrim(Ltrim(EC.PresentCity +' '+ EC.PresentState +' '+ EC.PresentZipCode)),'  ',' '),' ','-') AS LocalAddress2
   EC.PresentCity  + CASE WHEN EC.PresentCity = '' OR (EC.PresentState = '' AND EC.PresentZipCode = '') Then '' ELSE '-' END 
   		    + EC.PresentState + CASE WHEN EC.PresentState = '' OR EC.PresentZipCode = '' Then '' ELSE '-' END	
			+ EC.PresentZipCode AS LocalAddress2,
	ISNULL(CJ.DateOfJoining,'') As CertificateDateOfJoining,
	EM.GenderId

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


GO
ALTER PROCEDURE [sProcurement].[pStockIssueRequestDetailGet]
	@rOrgGroupId int,
	@rStockIssueRequestId [int] = 0
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	 SELECT 
			ISNULL(SIRD.Id,0) As ID,
			ISNULL(SIRD.StockIssueRequestId,0) AS StockIssueRequestId ,
			SIRD.StockItemId,
			ISNULL(SIRD.RequestedQuantity,0) As RequestedQuantity,
			SIRD.Remark,
			SIRD.UpdatedUserID,
			SIRD.UpdatedDateTime,
			SIM.Code ItemCode,
			SIM.Title ItemTitle,
			SU.Code UomCode,
			SU.Title UomTitle,
			ISNULL(SU.Id,0)AS  IssueStockUomId,
			SIM.IsBatchWiseTracking,
			SIM.Code StockItemCode,
			SIM.Title StockItemName,
			SU.Title Uom,
		    '' as Number,
			SIRD.IssuedQuantity,
			SIR.Number,
			SIR.CreatedDateTime as 'ReqDate',
			(
				Select AvailableQuantity
				FROM sProcurement.tStockBatch SB
				INNER JOIN sIP.tStockItemMaster SIM ON SIM.Id = SB.StockItemID
				INNER JOIN sProcurement.tStockIssueRequestDetail SIRD1 ON SIRD1.StockItemId = SIM.Id
				WHERE ((SIRD1.StockIssueRequestId = @rStockIssueRequestId) OR (@rStockIssueRequestId = 0))
				AND SIRD1.OrgGroupId = @rOrgGroupId  AND SB.StockItemId = SIRD.StockItemId
			) AS AvailableQuantity
 
	   FROM 
			sProcurement.tStockIssueRequestDetail SIRD
	   INNER JOIN  sIP.tStockItemMaster SIM
		ON SIM.Id = SIRD.StockItemId
		INNER JOIN sFinanceCommon.tStockUomMaster  SU
		ON SU.Id = SIM.IssueStockUomId
		INNER JOIN sProcurement.tStockIssueRequest SIR ON SIR.ID=SIRD.StockIssueRequestId
		Left Join sCommon.vEmployeeMaster EM ON SIR.CreatedUserId=EM.UserId
		--LEFT JOIN sProcurement.tStockBatch SB ON SB.StockItemID = SIM.Id AND SB.Number!=''
	  WHERE ((SIRD.StockIssueRequestId = @rStockIssueRequestId) OR (@rStockIssueRequestId = 0))
	  AND SIRD.OrgGroupId = @rOrgGroupId
END
GO
PRINT N'Altering [sProcurement].[pStockTransferQueueListing]...';


GO
/******************************************************************************
	Purpose          : To get Pending Records for Transfer/Issue Requests.
	Created date     : 13 May 2012
	Author           : Rajendra Patel
	Copyright©       : Copyright © Sapphire Software
	Last Change Desc : ST.Number is addedremoved
	Test script      : EXECUTE [sProcurement].[pStockTransferQueueListing] @rStatus = 'All', @rFromDate = '5/17/2009', @rToDate = '5/17/2010', @rType = 'All'
*******************************************************************************/
ALTER PROCEDURE [sProcurement].[pStockTransferQueueListing]
	(
	    @rOrgGroupId int,
		@rStatus Nvarchar(30) = '', 
		@rFromDate Nvarchar(100) = '1/1/2009', 
		@rToDate Nvarchar(100) = '1/1/2009', 
		@rType Nvarchar(30) = '',
		@rStoreLocationId int--,
		--@rToDepartmentId int=0
	)
AS

SET NOCOUNT ON
BEGIN
IF @rStatus = 'Pending'
BEGIN
	IF @rType = 'Tran'
		BEGIN
		   SELECT 
			   SR.Number AS [RequestNo],  
			   SR.CreatedDateTime AS [RequestDate],  
			   SR.RequestedByName AS [RequestedBy], 
			   'Tran'AS [Type], 
			   LM.Title AS [Location],
			   0 AS DepartmentId,
			   ST.Number AS [TransferNo],
			   'Pending' AS [Status], 
			   SUM(ISNULL(SRD.RequestedQuantity, 0)) - SUM(ISNULL(STD.TransferredQuantity, 0)) AS [PendingQty],
			   SR.Id [ReqId]
			   --ST.Id [TransferId]		   
		   FROM  
				sProcurement.tStockTransferRequest SR
					INNER JOIN sProcurement.tStockTransferRequestDetail SRD
					ON SR.Id = SRD.StockTransferRequestId
					LEFT OUTER JOIN sProcurement.tStockTransfer ST
					ON ST.StockTransferRequestId = SR.id
					LEFT JOIN sProcurement.tStockTransferDetail STD
					ON ST.Id = STD.StockTransferId
					INNER JOIN sIp.tStoreLocationMaster LM 
					ON SR.ToStoreLocationId = LM.Id
					WHERE 
					--SR.OrgGroupId = @rOrgGroupId AND 
					SR.FromStoreLocationId =  @rStoreLocationId
					
					GROUP BY 
						SR.Number, SR.CreatedDateTime, SR.RequestedByName, LM.Title, ST.Number, SR.Id, ST.Id 
					HAVING 
						SUM(ISNULL(SRD.RequestedQuantity, 0)) - SUM(ISNULL(STD.TransferredQuantity, 0)) > 0
						AND SR.CreatedDateTime BETWEEN @rFromDate AND @rToDate
		END
	IF @rType = 'Issue'
		BEGIN
		   SELECT 
			   SR.Number AS [RequestNo],  
			   SR.CreatedDateTime AS [RequestDate],  
			   SR.RequestedByName AS [RequestedBy], 
			   'Issue'AS [Type], 
			   ISNULL(LM.Title,'') AS [Location], 
			   ISNULL( LM.Id,0) AS DepartmentId,
			   ST.Number AS [TransferNo],
			   'Pending' AS [Status], 
			   SUM(ISNULL(SRD.RequestedQuantity, 0)) - SUM(ISNULL(STD.IssuedQuantity, 0)) AS PendingQty, 
			   SR.Id [ReqId]
			   --ST.Id [TransferId]
		   FROM  
				sProcurement.tStockIssueRequest SR
					INNER JOIN sProcurement.tStockIssueRequestDetail SRD
					ON SR.Id = SRD.StockIssueRequestId
					LEFT OUTER JOIN sProcurement.tStockIssue ST
					ON ST.StockIssueRequestId = SR.id
					LEFT JOIN sProcurement.tStockIssueDetail STD
					ON ST.Id = STD.StockIssueId
					LEFT JOIN sSetup.tDepartmentMaster LM 
					ON SR.ToDepartmentId = LM.Id
					WHERE
					 --SR.OrgGroupId = @rOrgGroupId AND 
					 SR.FromStoreLocationId =  @rStoreLocationId
					-- AND (SR.ToDepartmentId= @rToDepartmentId OR @rToDepartmentId =0)
					GROUP BY 
						SR.Number, SR.CreatedDateTime, SR.RequestedByName, LM.Title,LM.Id, ST.Number, SR.Id, ST.Id 
					HAVING 
						SUM(ISNULL(SRD.RequestedQuantity, 0)) - SUM(ISNULL(STD.IssuedQuantity, 0)) > 0
						AND SR.CreatedDateTime BETWEEN @rFromDate AND @rToDate
		END
	IF @rType = 'All'
		BEGIN
		SELECT 
			   SR.Number AS [RequestNo],  
			   SR.CreatedDateTime AS [RequestDate],  
			   SR.RequestedByName AS [RequestedBy], 
			   'Tran'AS [Type], 
			   LM.Title AS [Location], 
			   0 AS DepartmentId,
			   ST.Number AS [TransferNo],
			   'Pending' AS [Status],
			   SUM(ISNULL(SRD.RequestedQuantity, 0)) - SUM(ISNULL(STD.TransferredQuantity, 0)) AS PendingQty,
			   SR.Id [ReqId]
			   --ST.Id [TransferId]
			   FROM  
					sProcurement.tStockTransferRequest SR
						INNER JOIN sProcurement.tStockTransferRequestDetail SRD
						ON SR.Id = SRD.StockTransferRequestId
						LEFT OUTER JOIN sProcurement.tStockTransfer ST
						ON ST.StockTransferRequestId = SR.id
						LEFT JOIN sProcurement.tStockTransferDetail STD
						ON ST.Id = STD.StockTransferId
						INNER JOIN sIp.tStoreLocationMaster LM 
						ON SR.ToStoreLocationId = LM.Id
						WHERE 
						--SR.OrgGroupId = @rOrgGroupId AND
						 SR.FromStoreLocationId =  @rStoreLocationId 
						GROUP BY 
							SR.Number, SR.CreatedDateTime, SR.RequestedByName, LM.Title, ST.Number, SR.Id, ST.Id
						HAVING 
							SUM(ISNULL(SRD.RequestedQuantity, 0)) - SUM(ISNULL(STD.TransferredQuantity, 0)) > 0
							AND SR.CreatedDateTime BETWEEN @rFromDate AND @rToDate
			UNION ALL
			   SELECT 
			   SR.Number AS [RequestNo],  
			   SR.CreatedDateTime AS [RequestDate],  
			   SR.RequestedByName AS [RequestedBy], 
			   'Issue'AS [Type], 
			   ISNULL(LM.Title,'') AS [Location], 
			   ISNULL( LM.Id,0) AS DepartmentId,
			   ST.Number AS [TransferNo],
			   'Pending' AS [Status], 
			   SUM(ISNULL(SRD.RequestedQuantity, 0)) - SUM(ISNULL(STD.IssuedQuantity, 0)) AS PendingQty,
			   SR.Id [ReqId]
			  -- ST.Id [TransferId]
		   FROM  
				sProcurement.tStockIssueRequest SR
					INNER JOIN sProcurement.tStockIssueRequestDetail SRD
					ON SR.Id = SRD.StockIssueRequestId
					LEFT JOIN sProcurement.tStockIssue ST
					ON ST.StockIssueRequestId = SR.id
					LEFT JOIN sProcurement.tStockIssueDetail STD
					ON ST.Id = STD.StockIssueId
					LEFT JOIN sSetup.tDepartmentMaster LM 
					ON SR.ToDepartmentId = LM.Id
					WHERE 
					--SR.OrgGroupId = @rOrgGroupId AND
					 SR.FromStoreLocationId =  @rStoreLocationId
						-- AND (SR.ToDepartmentId= @rToDepartmentId OR @rToDepartmentId =0)
					GROUP BY 
						SR.Number, SR.CreatedDateTime, SR.RequestedByName, LM.Title,LM.Id, ST.Number, SR.Id, ST.Id
					HAVING 
						SUM(ISNULL(SRD.RequestedQuantity, 0)) - SUM(ISNULL(STD.IssuedQuantity, 0)) > 0
						AND SR.CreatedDateTime BETWEEN @rFromDate AND @rToDate
						Order by SR.Number
		END			
	END
	
	
IF @rStatus = 'Completed'
BEGIN
	IF @rType = 'Tran'
		BEGIN
		   SELECT 
			   SR.Number AS [RequestNo],  
			   SR.CreatedDateTime AS [RequestDate],  
			   SR.RequestedByName AS [RequestedBy], 
			   'Tran'AS [Type], 
			   LM.Title AS [Location],
			   0 AS DepartmentId,
			   ST.Number AS [TransferNo],
			   'Completed' AS [Status], 
			   SUM(ISNULL(SRD.RequestedQuantity, 0)) - SUM(ISNULL(STD.TransferredQuantity, 0)) AS [PendingQty], 
			   SR.Id [ReqId]
			   --ST.Id [TransferId]		   
		   FROM
				sProcurement.tStockTransferRequest SR
					INNER JOIN sProcurement.tStockTransferRequestDetail SRD
					ON SR.Id = SRD.StockTransferRequestId
					INNER JOIN sProcurement.tStockTransfer ST
					ON ST.StockTransferRequestId = SR.id
					INNER JOIN sProcurement.tStockTransferDetail STD
					ON ST.Id = STD.StockTransferId
					INNER JOIN sIp.tStoreLocationMaster LM 
					ON SR.ToStoreLocationId = LM.Id
					WHERE 
					--SR.OrgGroupId = @rOrgGroupId AND 
					SR.FromStoreLocationId =  @rStoreLocationId
					GROUP BY 
						SR.Number, SR.CreatedDateTime, SR.RequestedByName, LM.Title, ST.Number, SR.Id, ST.Id 
					HAVING 
						SUM(ISNULL(SRD.RequestedQuantity, 0)) - SUM(ISNULL(STD.TransferredQuantity, 0)) <= 0
						AND SR.CreatedDateTime BETWEEN @rFromDate AND @rToDate
						Order by  SR.Id,SR.Number
		END
	IF @rType = 'Issue'
		BEGIN
		   SELECT 
			   SR.Number AS [RequestNo],  
			   SR.CreatedDateTime AS [RequestDate],  
			   SR.RequestedByName AS [RequestedBy], 
			   'Issue'AS [Type], 
			   ISNULL(LM.Title,'') AS [Location], 
			   0 AS DepartmentId,
			   ST.Number AS [TransferNo],
			   'Completed' AS [Status], 
			   SUM(ISNULL(SRD.RequestedQuantity, 0)) - SUM(ISNULL(STD.IssuedQuantity, 0)) AS PendingQty, 
			   SR.Id [ReqId]
			   --ST.Id [TransferId]
		   FROM  
				sProcurement.tStockIssueRequest SR
					INNER JOIN sProcurement.tStockIssueRequestDetail SRD
					ON SR.Id = SRD.StockIssueRequestId
					INNER JOIN sProcurement.tStockIssue ST
					ON ST.StockIssueRequestId = SR.id
					INNER JOIN sProcurement.tStockIssueDetail STD
					ON ST.Id = STD.StockIssueId
					LEFT JOIN sSetup.tDepartmentMaster LM 
					ON SR.ToDepartmentId = LM.Id
					WHERE 
					--SR.OrgGroupId = @rOrgGroupId AND
					 SR.FromStoreLocationId =  @rStoreLocationId 
						-- AND (SR.ToDepartmentId= @rToDepartmentId OR @rToDepartmentId =0)
					GROUP BY 
						SR.Number, SR.CreatedDateTime, SR.RequestedByName, LM.Title, ST.Number, SR.Id, ST.Id 
					HAVING 
						SUM(ISNULL(SRD.RequestedQuantity, 0)) - SUM(ISNULL(STD.IssuedQuantity, 0)) <= 0
						AND SR.CreatedDateTime BETWEEN @rFromDate AND @rToDate
						Order by  SR.Id,SR.Number
		END
	IF @rType = 'All'
		BEGIN
		SELECT 
			   SR.Number AS [RequestNo],  
			   SR.CreatedDateTime AS [RequestDate],  
			   SR.RequestedByName AS [RequestedBy], 
			   'Tran'AS [Type], 
			   LM.Title AS [Location], 
			   0 AS DepartmentId,
			   ST.Number AS [TransferNo],
			   'Completed' AS [Status],
			   SUM(ISNULL(SRD.RequestedQuantity, 0)) - SUM(ISNULL(STD.TransferredQuantity, 0)) AS PendingQty,
			   SR.Id [ReqId]
			   --ST.Id [TransferId]
			   FROM  
					sProcurement.tStockTransferRequest SR
						INNER JOIN sProcurement.tStockTransferRequestDetail SRD
						ON SR.Id = SRD.StockTransferRequestId
						INNER JOIN sProcurement.tStockTransfer ST
						ON ST.StockTransferRequestId = SR.id
						INNER JOIN sProcurement.tStockTransferDetail STD
						ON ST.Id = STD.StockTransferId
						INNER JOIN sIp.tStoreLocationMaster LM 
						ON SR.ToStoreLocationId = LM.Id
						WHERE 
						--SR.OrgGroupId = @rOrgGroupId AND 
						SR.FromStoreLocationId =  @rStoreLocationId  
						GROUP BY 
							SR.Number, SR.CreatedDateTime, SR.RequestedByName, LM.Title, ST.Number, SR.Id, ST.Id
						HAVING 
							SUM(ISNULL(SRD.RequestedQuantity, 0)) - SUM(ISNULL(STD.TransferredQuantity, 0)) <= 0
							AND SR.CreatedDateTime BETWEEN @rFromDate AND @rToDate
			UNION ALL
			   SELECT 
			   SR.Number AS [RequestNo],  
			   SR.CreatedDateTime AS [RequestDate],  
			   SR.RequestedByName AS [RequestedBy], 
			   'Issue'AS [Type], 
			   ISNULL(LM.Title,'') AS [Location], 
			   ISNULL( LM.Id,0) AS DepartmentId,
			   ST.Number AS [TransferNo],
			   'Completed' AS [Status], 
			   SUM(ISNULL(SRD.RequestedQuantity, 0)) - SUM(ISNULL(STD.IssuedQuantity, 0)) AS PendingQty,
			   SR.Id [ReqId]
			  -- ST.Id [TransferId]
		   FROM  
				sProcurement.tStockIssueRequest SR
					INNER JOIN sProcurement.tStockIssueRequestDetail SRD
					ON SR.Id = SRD.StockIssueRequestId
					INNER JOIN sProcurement.tStockIssue ST
					ON ST.StockIssueRequestId = SR.id
					INNER JOIN sProcurement.tStockIssueDetail STD
					ON ST.Id = STD.StockIssueId
					LEFT JOIN sSetup.tDepartmentMaster LM 					
					ON SR.ToDepartmentId = LM.Id
					WHERE 
					--SR.OrgGroupId = @rOrgGroupId AND 
					SR.FromStoreLocationId =  @rStoreLocationId
					GROUP BY 
						SR.Number, SR.CreatedDateTime, SR.RequestedByName, LM.Title,LM.Id, ST.Number, SR.Id, ST.Id
					HAVING 
						SUM(ISNULL(SRD.RequestedQuantity, 0)) - SUM(ISNULL(STD.IssuedQuantity, 0)) <= 0
						AND SR.CreatedDateTime BETWEEN @rFromDate AND @rToDate
						Order by  SR.Id,SR.Number
		END			
	END
	
IF @rStatus = 'All'
BEGIN
	IF @rType = 'Tran'
		BEGIN
		   SELECT 
			   SR.Number AS [RequestNo],  
			   SR.CreatedDateTime AS [RequestDate],  
			   SR.RequestedByName AS [RequestedBy], 
			   'Tran'AS [Type], 
			   LM.Title AS [Location],
			   0 AS DepartmentId,
			   ST.Number AS [TransferNo],
			   'Pending' AS [Status], 
			   SUM(ISNULL(SRD.RequestedQuantity, 0)) - SUM(ISNULL(STD.TransferredQuantity, 0)) AS [PendingQty],
			   SR.Id [ReqId]
			   --ST.Id [TransferId]		   
		   FROM  
				sProcurement.tStockTransferRequest SR
					INNER JOIN sProcurement.tStockTransferRequestDetail SRD
					ON SR.Id = SRD.StockTransferRequestId
					LEFT OUTER JOIN sProcurement.tStockTransfer ST
					ON ST.StockTransferRequestId = SR.id
					LEFT JOIN sProcurement.tStockTransferDetail STD
					ON ST.Id = STD.StockTransferId
					INNER JOIN sIp.tStoreLocationMaster LM 
					ON SR.ToStoreLocationId = LM.Id
						WHERE 
						--SR.OrgGroupId = @rOrgGroupId AND 
						SR.FromStoreLocationId =  @rStoreLocationId 
					GROUP BY 
						SR.Number, SR.CreatedDateTime, SR.RequestedByName, LM.Title, ST.Number, SR.Id, ST.Id 
					HAVING 
						SUM(ISNULL(SRD.RequestedQuantity, 0)) - SUM(ISNULL(STD.TransferredQuantity, 0)) > 0
						AND SR.CreatedDateTime BETWEEN @rFromDate AND @rToDate		
		UNION ALL
		SELECT 
			   SR.Number AS [RequestNo],  
			   SR.CreatedDateTime AS [RequestDate],  
			   SR.RequestedByName AS [RequestedBy], 
			   'Tran'AS [Type], 
			   LM.Title AS [Location],
			   0 AS DepartmentId,
			   ST.Number AS [TransferNo],
			   'Completed' AS [Status], 
			   SUM(ISNULL(SRD.RequestedQuantity, 0)) - SUM(ISNULL(STD.TransferredQuantity, 0)) AS [PendingQty], 
			   SR.Id [ReqId]
			   --ST.Id [TransferId]		   
		   FROM
				sProcurement.tStockTransferRequest SR
					INNER JOIN sProcurement.tStockTransferRequestDetail SRD
					ON SR.Id = SRD.StockTransferRequestId
					INNER JOIN sProcurement.tStockTransfer ST
					ON ST.StockTransferRequestId = SR.id
					INNER JOIN sProcurement.tStockTransferDetail STD
					ON ST.Id = STD.StockTransferId
					INNER JOIN sIp.tStoreLocationMaster LM 
					ON SR.ToStoreLocationId = LM.Id
						WHERE 
						--SR.OrgGroupId = @rOrgGroupId AND 
						SR.FromStoreLocationId =  @rStoreLocationId
					GROUP BY 
						SR.Number, SR.CreatedDateTime, SR.RequestedByName, LM.Title, ST.Number, SR.Id, ST.Id 
					HAVING 
						SUM(ISNULL(SRD.RequestedQuantity, 0)) - SUM(ISNULL(STD.TransferredQuantity, 0)) <= 0
						AND SR.CreatedDateTime BETWEEN @rFromDate AND @rToDate
						Order by  SR.Id,SR.Number
		END
	IF @rType = 'Issue'
		BEGIN
		   SELECT 
			   SR.Number AS [RequestNo],  
			   SR.CreatedDateTime AS [RequestDate],  
			   SR.RequestedByName AS [RequestedBy], 
			   'Issue'AS [Type], 
			   ISNULL(LM.Title,'') AS [Location], 
			   ISNULL( LM.Id,0) AS DepartmentId,
			   ST.Number AS [TransferNo],
			   'Pending' AS [Status], 
			   SUM(ISNULL(SRD.RequestedQuantity, 0)) - SUM(ISNULL(STD.IssuedQuantity, 0)) AS PendingQty, 
			   SR.Id [ReqId]
			   --ST.Id [TransferId]
		   FROM  
				sProcurement.tStockIssueRequest SR
					INNER JOIN sProcurement.tStockIssueRequestDetail SRD
					ON SR.Id = SRD.StockIssueRequestId
					LEFT OUTER JOIN sProcurement.tStockIssue ST
					ON ST.StockIssueRequestId = SR.id
					LEFT JOIN sProcurement.tStockIssueDetail STD
					ON ST.Id = STD.StockIssueId
					LEFT JOIN sSetup.tDepartmentMaster LM 
					ON SR.ToDepartmentId = LM.Id
						WHERE 
						--SR.OrgGroupId = @rOrgGroupId AND 
						SR.FromStoreLocationId =  @rStoreLocationId 
						-- AND (SR.ToDepartmentId= @rToDepartmentId OR @rToDepartmentId =0)
					GROUP BY 
						SR.Number, SR.CreatedDateTime, SR.RequestedByName, LM.Title,LM.Id, ST.Number, SR.Id, ST.Id 
					HAVING 
						SUM(ISNULL(SRD.RequestedQuantity, 0)) - SUM(ISNULL(STD.IssuedQuantity, 0)) > 0
						AND SR.CreatedDateTime BETWEEN @rFromDate AND @rToDate
			UNION ALL
			
			SELECT 
			   SR.Number AS [RequestNo],  
			   SR.CreatedDateTime AS [RequestDate],  
			   SR.RequestedByName AS [RequestedBy], 
			   'Issue'AS [Type], 
			   ISNULL(LM.Title,'') AS [Location],
			   ISNULL( LM.Id,0) AS DepartmentId, 
			   ST.Number AS [TransferNo],
			   'Completed' AS [Status], 
			   SUM(ISNULL(SRD.RequestedQuantity, 0)) - SUM(ISNULL(STD.IssuedQuantity, 0)) AS PendingQty, 
			   SR.Id [ReqId]
			   --ST.Id [TransferId]
		   FROM  
				sProcurement.tStockIssueRequest SR
					INNER JOIN sProcurement.tStockIssueRequestDetail SRD
					ON SR.Id = SRD.StockIssueRequestId
					INNER JOIN sProcurement.tStockIssue ST
					ON ST.StockIssueRequestId = SR.id
					INNER JOIN sProcurement.tStockIssueDetail STD
					ON ST.Id = STD.StockIssueId
					LEFT JOIN sSetup.tDepartmentMaster LM 
					ON SR.ToDepartmentId = LM.Id
						WHERE 
						--SR.OrgGroupId = @rOrgGroupId AND 
						SR.FromStoreLocationId =  @rStoreLocationId
						-- AND (SR.ToDepartmentId= @rToDepartmentId OR @rToDepartmentId =0)
					GROUP BY 
						SR.Number, SR.CreatedDateTime, SR.RequestedByName, LM.Title,LM.Id, ST.Number, SR.Id, ST.Id 
					HAVING 
						SUM(ISNULL(SRD.RequestedQuantity, 0)) - SUM(ISNULL(STD.IssuedQuantity, 0)) <= 0
						AND SR.CreatedDateTime BETWEEN @rFromDate AND @rToDate
						Order by  SR.Id,SR.Number
		END
		IF @rType = 'All'
		BEGIN
		SELECT 
			   SR.Number AS [RequestNo],  
			   SR.CreatedDateTime AS [RequestDate],  
			   SR.RequestedByName AS [RequestedBy], 
			   'Tran'AS [Type], 
			   LM.Title AS [Location],
			   0 AS DepartmentId, 
			   ST.Number AS [TransferNo],
			   'Pending' AS [Status],
			   SUM(ISNULL(SRD.RequestedQuantity, 0)) - SUM(ISNULL(STD.TransferredQuantity, 0)) AS PendingQty,
			   SR.Id [ReqId]
			   --ST.Id [TransferId]
			   FROM  
					sProcurement.tStockTransferRequest SR
						INNER JOIN sProcurement.tStockTransferRequestDetail SRD
						ON SR.Id = SRD.StockTransferRequestId
						LEFT OUTER JOIN sProcurement.tStockTransfer ST
						ON ST.StockTransferRequestId = SR.id
						LEFT JOIN sProcurement.tStockTransferDetail STD
						ON ST.Id = STD.StockTransferId
						INNER JOIN sIp.tStoreLocationMaster LM 
						ON SR.ToStoreLocationId = LM.Id
							WHERE 
							--SR.OrgGroupId = @rOrgGroupId AND 
							SR.FromStoreLocationId =  @rStoreLocationId
						GROUP BY 
							SR.Number, SR.CreatedDateTime, SR.RequestedByName, LM.Title, ST.Number, SR.Id, ST.Id
						HAVING 
							SUM(ISNULL(SRD.RequestedQuantity, 0)) - SUM(ISNULL(STD.TransferredQuantity, 0)) > 0
							AND SR.CreatedDateTime BETWEEN @rFromDate AND @rToDate
			UNION ALL
			   SELECT 
			   SR.Number AS [RequestNo],  
			   SR.CreatedDateTime AS [RequestDate],  
			   SR.RequestedByName AS [RequestedBy], 
			   'Issue'AS [Type], 
			   ISNULL(LM.Title,'') AS [Location], 
			   ISNULL( LM.Id,0) AS DepartmentId,
			   ST.Number AS [TransferNo],
			   'Pending' AS [Status], 
			   SUM(ISNULL(SRD.RequestedQuantity, 0)) - SUM(ISNULL(STD.IssuedQuantity, 0)) AS PendingQty,
			   SR.Id [ReqId]
			  -- ST.Id [TransferId]
		   FROM  
				sProcurement.tStockIssueRequest SR
					INNER JOIN sProcurement.tStockIssueRequestDetail SRD
					ON SR.Id = SRD.StockIssueRequestId
					LEFT JOIN sProcurement.tStockIssue ST
					ON ST.StockIssueRequestId = SR.id
					LEFT JOIN sProcurement.tStockIssueDetail STD
					ON ST.Id = STD.StockIssueId
					LEFT JOIN sSetup.tDepartmentMaster LM 
					ON SR.ToDepartmentId = LM.Id
						WHERE 
						--SR.OrgGroupId = @rOrgGroupId AND 
						SR.FromStoreLocationId =  @rStoreLocationId 
						-- AND (SR.ToDepartmentId= @rToDepartmentId OR @rToDepartmentId =0)
					GROUP BY 
						SR.Number, SR.CreatedDateTime, SR.RequestedByName, LM.Title,LM.Id, ST.Number, SR.Id, ST.Id
					HAVING 
						SUM(ISNULL(SRD.RequestedQuantity, 0)) - SUM(ISNULL(STD.IssuedQuantity, 0)) > 0
						AND SR.CreatedDateTime BETWEEN @rFromDate AND @rToDate
			UNION ALL
			SELECT 
			   SR.Number AS [RequestNo],  
			   SR.CreatedDateTime AS [RequestDate],  
			   SR.RequestedByName AS [RequestedBy], 
			   'Tran'AS [Type], 
			   LM.Title AS [Location], 
			   0 AS DepartmentId,
			   ST.Number AS [TransferNo],
			   'Completed' AS [Status],
			   SUM(ISNULL(SRD.RequestedQuantity, 0)) - SUM(ISNULL(STD.TransferredQuantity, 0)) AS PendingQty,
			   SR.Id [ReqId]
			   --ST.Id [TransferId]
			   FROM  
					sProcurement.tStockTransferRequest SR
						INNER JOIN sProcurement.tStockTransferRequestDetail SRD
						ON SR.Id = SRD.StockTransferRequestId
						INNER JOIN sProcurement.tStockTransfer ST
						ON ST.StockTransferRequestId = SR.id
						INNER JOIN sProcurement.tStockTransferDetail STD
						ON ST.Id = STD.StockTransferId
						INNER JOIN sIp.tStoreLocationMaster LM 
						ON SR.ToStoreLocationId = LM.Id
							WHERE 
							--SR.OrgGroupId = @rOrgGroupId AND 
							SR.FromStoreLocationId =  @rStoreLocationId
						GROUP BY 
							SR.Number, SR.CreatedDateTime, SR.RequestedByName, LM.Title, ST.Number, SR.Id, ST.Id
						HAVING 
							SUM(ISNULL(SRD.RequestedQuantity, 0)) - SUM(ISNULL(STD.TransferredQuantity, 0)) <= 0
							AND SR.CreatedDateTime BETWEEN @rFromDate AND @rToDate
			UNION ALL
			   SELECT 
			   SR.Number AS [RequestNo],  
			   SR.CreatedDateTime AS [RequestDate],  
			   SR.RequestedByName AS [RequestedBy], 
			   'Issue'AS [Type], 
			   ISNULL(LM.Title,'') AS [Location], 
			   ISNULL( LM.Id,0) AS DepartmentId,
			   ST.Number AS [TransferNo],
			   'Completed' AS [Status], 
			   SUM(ISNULL(SRD.RequestedQuantity, 0)) - SUM(ISNULL(STD.IssuedQuantity, 0)) AS PendingQty,
			   SR.Id [ReqId]
			  -- ST.Id [TransferId]
		   FROM  
				sProcurement.tStockIssueRequest SR
					INNER JOIN sProcurement.tStockIssueRequestDetail SRD
					ON SR.Id = SRD.StockIssueRequestId
					INNER JOIN sProcurement.tStockIssue ST
					ON ST.StockIssueRequestId = SR.id
					INNER JOIN sProcurement.tStockIssueDetail STD
					ON ST.Id = STD.StockIssueId
					LEFT JOIN sSetup.tDepartmentMaster LM 
					ON SR.ToDepartmentId = LM.Id
						WHERE 
						--SR.OrgGroupId = @rOrgGroupId AND 
						SR.FromStoreLocationId =  @rStoreLocationId
						-- AND (SR.ToDepartmentId= @rToDepartmentId OR @rToDepartmentId =0)
					GROUP BY 
						SR.Number, SR.CreatedDateTime, SR.RequestedByName, LM.Title,LM.Id, ST.Number, SR.Id, ST.Id
					HAVING 
						SUM(ISNULL(SRD.RequestedQuantity, 0)) - SUM(ISNULL(STD.IssuedQuantity, 0)) <= 0
						AND SR.CreatedDateTime BETWEEN @rFromDate AND @rToDate
						Order by  SR.Id,SR.Number
		END		
		END
END
GO
PRINT N'Altering [sStudent].[ppImportStudent_Update_Dynamicly]...';


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

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

		UPDATE sStudent.tStudentMaster
		SET 
		FirstName = case when isnull(@rFirstName,'') <> '' then @rFirstName else FirstName end
		,MiddleName   = case when isnull(@rMiddleName,'') <> '' then @rMiddleName else MiddleName end
		,LastName     = case when isnull(@rLastName,'') <> '' then @rLastName else LastName end
		--,StatusId     = case when isnull(@statusid,0) <> 0 then @statusid else StatusId end
		 ,UpdatedUserId = @rCreatedUserId
		,UpdatedDateTime = sCommon.fGetDate()
		WHERE Id = @StudentId and OrgId = @rOrgId
		
		IF NOT EXISTS(Select * from sStudent.tStudentAdmission where StudentId= @StudentId) 
		BEGIN
			INSERT INTO sStudent.tStudentAdmission(StudentId,CreatedUserId,CreatedDateTime) Values (@StudentId, @rCreatedUserId, sCommon.fGetDate())
		END

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

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

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

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

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

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

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

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


GO
ALTER PROCEDURE [sStudent].[pRptStudentIcardGet]  
  @rBuilder1 nvarchar(max)='',  
  @rBuilder2 nvarchar(max)='',   
  @rOrgId smallint,  
  @rBatchId int,  
  @rStrCode nvarchar(max),  
  @rClassId int,  
  @rDivisionId int,  
  @rStudentId bigint,  
  @rFromRollNo int,  
  @rToRollNo int,  
  @rStatusId int,  
  @rDateOfBirth int,  
  @rDepartmentId int,  
  @rHouseGroupId int=0,  
  @rIsShowBarcode bit=0,  
  @rOrgGroupBatchId int,
  @rHouseId int=0  
 WITH EXECUTE AS CALLER  
AS  
SET NOCOUNT ON  
      
  
BEGIN   
  
DECLARE @lIcardBorder nvarchar(10)  
DECLARE @lSUIdBarcode nvarchar(50)  
--DECLARE @lIsBarcodeBasedOnSUId bit = 0  
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 = 236 AND SourceId = @lOrgGroupId  
  
SELECT @lIcardBorder = ItemValue FROM sConfig.tConfigurationSetup WHERE configurationId = 130 AND SourceTypeId = 1016 AND SourceId = @rOrgId --ItemKey = 'sConfig.tConfigurationSetup'   
SELECT @lSUIdBarcode = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 168 AND SourceTypeId = 2010 AND SourceId = @lOrgGroupId  
   
 --IF (@lSUIdBarcode IS NULL) OR (@lSUIdBarcode = 'False')  
 --SET @lIsBarcodeBasedOnSUId = 0  
 --ELSE  
 --SET @lIsBarcodeBasedOnSUId = 1   
   
 SELECT      
   SD.AcademicId,  
   SD.StudentId,   
   SD.ClassId,  
   SD.DivisionId,  
   SD.ClassName,  
   SD.DivisionName,  
   SD.ClassDivision,  
   SD.Batch,  
   SD.Code,  
   SD.Number AS StudentNumber,  
   SD.RegistrationNumber,   
   SD.RollNo,      
   SD.FirstName,  
   SD.MiddleName,     
   SD.LastName,  
   SF.FatherName,
   [sStudent].[fStudentNameGet](SD.FirstName , SD.MiddleName, SD.LastName,OM.StudentNameFormatId ) AS Name,   
   --SD.FirstName + ' ' + SD.MiddleName + ' ' + SD.LastName As Name,     
   SD.StatusId,  
   SD.DateOfBirth,    
   SD.BloodGroup,  
   ISNULL(SD.PresentStreetone,'') AS PresentStreetone,  
   ISNULL(SD.PresentStreetTwo,'') AS PresentStreetTwo,  
   ISNULL(SD.PresentStreetThree,'') AS PresentStreetThree,  
      ISNULL(SD.PresentCity,'') AS PresentCity, 
	  ISNULL(SD.PresentState,'') AS PresentState, 
      ISNULL(SD.PresentZipCode,'') AS PresentZipCode,  
   SD.PresentContactNo,         
   SD.ParentContactNo AS ParentContactNo,  
   SD.StudentContactNo,     
   SD.StudentPhoto,  
   SD.AdmissionCategory,   
   SD.DivisionOrder,    
   ISNULL(SD.FamilyCast,'')AS FamilyCast, 
   ISNull(SD.AdhaarNumber,'')As AdhaarNumber,
   OM.Title AS OrgName,   
   ISNULL(HM.Title,'') AS HouseName,   
   OM.PrincipalSignature,  
   ISNULL(ICO.ICardOrgTitle,'') AS ICardOrgTitle,  
   ISNULL(ICO.ICardAddress1,'') AS ICardAddress1,  
   ISNULL(ICO.ICardAddress2,'') AS ICardAddress2,  
   ISNULL(ICO.ICardAddress3,'') AS ICardAddress3,     
   OM.OrgLogo AS ICardLogo,  
     
   --ISNULL(ICO.ICardBackground,0) AS ICardBackground,   
   --ISNULL(ICO.ICardBackBackground,0) AS ICardBackBackground,   
     
    ICO.ICardBackground  AS ICardBackground,   
    ICO.ICardBackBackground  AS ICardBackBackground,        
       
   ISNULL(ICO.LabelColor,'Black') AS LabelColor,  
   ISNULL(ICO.DetailColor,'Black') AS DetailColor,  
   ISNULL(ICO.HeaderColor,'Black') AS HeaderColor,  
   ISNULL(SF.FatherName,'') AS FatherName,  
   ISNULL(SF.FatherContactNo,'') AS FatherContactNo,  
   ISNULL(SF.MotherName,'') AS MotherName,  
   ISNULL(SF.MotherContactNo,'') AS MotherContactNo,  
   ISNULL(RT.RouteName,'') AS RouteName,  
   ISNULL(RT.PickupPoint,'') AS PickupPoint,  
   ISNULL(RT.DropPoint,'') AS DropPoint,  
     
   @lIcardBorder AS IcardBorder,  
   HM.ColorCode,  
   OM.OrgLogo,  
   OM.SmallAddress1,  
   --@lSUIdBarcode AS IsBarcodeBasedOnSUId,  
   CASE WHEN @lSUIdBarcode = 'True' THEN SD.SUId  ELSE SD.Code END AS BarcodeNumber,  
    ISNULL(SD.EmergencyStreetOne,'') AS EmergencyStreetOne,  
          ISNULL(SD.EmergencyStreetTwo,'') AS EmergencyStreetTwo,  
         ISNULL(SD.EmergencyStreetThree,'') AS EmergencyStreetThree,  
         ISNULL(SD.EmergencyCountry,'') AS EmergencyCountry,  
         ISNULL(SD.EmergencyState,'') As EmergencyState,  
         ISNULL(SD.EmergencyCity,'') AS EmergencyCity,  
         ISNULL(SD.EmergencyZipCode,'') as EmergencyZipCode,  
         SD.EmergencyContactNo AS EmergencyContactNo,  
   ISNULL(SD.SUId,'') As SUId,  
   ISNULL(RT.RouteNumber,0) AS RouteNumber,  
   @rIsShowBarcode As IsShowBarcode,  
   SD.Name,  
   SM.Title AS Stream,  
   SD.AdmissionDate,  
   ISNULL(DM.Title,'') AS DepartmentName,  
   SD.FatherPhoto,  
   SD.MotherPhoto,  
   SD.RelativePhoto,  
   RT.Transport AS TransPortMode,  
   @lIDConfigValue AS ItemValue,  
   RT.RouteCode,
   ISNULL(LM.Title,'') AS Medium ,
   ISNULL(HA.Hosteld,'') AS HostelId,
   SD.Gender,
   SI.QRCode
   ,  (Select ToDate from sSetup.tBatchMaster where Id = @rBatchId) as LastBatchDate,

   --STUFF(SELECT  ', ' + Title FROM sActivity.tClubMaster CM INNER JOIN sActivity.tAssignClub AC ON AC.AcademicId=SD.AcademicId FOR XML PATH ('') ),0,0,',') AS Club

    STUFF(
         (SELECT DISTINCT  ', ' + Title 
          FROM sActivity.tClubMaster CM INNER JOIN sActivity.tAssignClub AC ON SD.AcademicId  = AC.AcademicId AND CM.OrgGroupId = LEFT(SD.OrgGroupBatchId,4)
		  
          FOR XML PATH (''))
          , 1, 1, '')  AS Club,

	ISNULL(TM.Title,'') AS StudentTransportMode,
	ISNULL(RT.VehicleName,'') AS VehicleName,
	ISNULL(SO.BirthPlace,'') AS BirthPlace
   --CM.Title as Club 

 FROM   
   sStudent.vStudentAllDetail SD  
   INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=SD.OrgId  
   --INNER JOIN sStudent.tStudentOther SO ON SD.StudentId = So.StudentId      
   LEFT JOIN sActivity.tHouseMaster HM ON SD.HouseId = HM.Id   
   LEFT JOIN sActivity.tHouseGroupMaster HGM ON HGM.Id=HM.HouseGroupId  
   LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId = SD.StudentId 
   LEFT JOIN sHostel.tHostelAdmission HA ON HA.SourceId= SD.StudentId 
   LEFT JOIN  sStudent.tStudentImages SI ON SD.StudentId = SI.StudentId
   LEFT JOIN  
   (SELECT TM.Title AS Transport,  AT.SourceId,ISNULL(BRM.RouteCode,0) AS RouteCode,BRM.Title As RouteName,BRDM.Title As PickupPoint,ISNULL(BRM.RouteNumber,0) AS RouteNumber,
		ISNULL(BRDM1.Title,'')As DropPoint, VM.Title AS VehicleName
    FROM 
		sTransport.tAssignRoute AT   
		INNER JOIN sTransport.tBusRouteDestinationMaster BRDM ON BRDM.Id=AT.PickupDestinationId
		INNER JOIN sTransport.tBusRouteMaster BRM ON BRM.Id=BRDM.BusRouteId AND  AT.SourceTypeId=2003 AND ((BRM.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))
		INNER JOIN sTransport.tTransportMaster TM ON TM.Id=BRM.TransportId
		LEFT JOIN sTransport.tBusRouteDestinationMaster BRDM1 ON BRDM1.Id=AT.DropDestinationId AND BRM.Id=BRDM1.BusRouteId
		LEFT JOIN sTransport.tVehicleMaster VM ON VM.Id = BRM.VehicleId
   ) RT  
   ON RT.SourceId = SD.StudentId AND ((SD.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))   
   --LEFT JOIN sTransport.tAssignRoute AR ON AR.SourceId =SD.StudentId   
   --LEFT JOIN sTransport.tBusRouteDestinationMaster BRDM ON BRDM.Id =AR.PickupDestinationId   
   --LEFT JOIN sTransport.tBusRouteMaster BRM ON BRM.Id =BRDM.BusRouteId  AND(( BRM.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))  
   LEFT JOIN sStudent.tICardOrg ICO ON SD.OrgId = ICO.OrgId  
   LEFT JOIN sSetup.tStreamMaster SM ON SM.Id=SD.StreamId  
   LEFT JOIN sSetup.tDepartmentMaster DM ON DM.Id=SD.DepartmentId  
   LEFT JOIN sStudent.tStudentOther SO ON SD.StudentId = SO.StudentId  
   LEFT JOIN sCommon.tTransportModeMaster TM ON so.TransportModeId = TM.Id  
   LEFT JOIN sSetup.tLanguageMaster LM ON OM.LanguageId = LM.Id

   
   
   --LEFT JOIN sSetup.tOrganizationConfiguration OC ON OM.Id = OC.OrgId   
     
 WHERE   
  SD.OrgId=@rOrgId  
  AND SD.BatchId = @rBatchId   
  AND (ISNULL(SD.Code,0) IN( SELECT cast(item as nvarchar(20)) FROM  sCommon.fnsplit(@rStrCode,',')) OR @rStrCode='')   
  AND ((SD.ClassId=@rClassId) OR (@rClassId=0))  
  AND ((SD.DivisionId=@rDivisionId) OR (@rDivisionId=0))  
  AND ((SD.StudentId=@rStudentId) OR (@rStudentId=0))  
  AND ((SD.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))  
  AND ((SD.RollNo <= @rToRollNo) OR (@rToRollNo=0))  
  AND ((SD.StatusId=@rStatusId)OR(@rStatusId=0))  
  AND ((SD.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))  
  AND ((HGM.Id=@rHouseGroupId)OR(@rHouseGroupId=0)) 
  AND ((HM.Id=@rHouseId) OR (Isnull(@rHouseId,0)=0)) 
  AND ((SD.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
END
GO
PRINT N'Altering [sStudent].[pRptStudentRegisterWithAddressGet]...';


GO


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

BEGIN 

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


GO

ALTER PROCEDURE [sStudent].[pValidateImportAdmissionInquiry]

	@rOrgGroupId int,
    @rOrgId int,
	@rXmldoc [nvarchar](max)
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
DECLARE @lCount INT
DECLARE @lInterrorCode INT,
		@intDoc INT,
        
        @lClass nvarchar(100),
        @lInquiryDate nvarchar(15),
		@lInquiryStatus nvarchar(50),
        @lDOB nvarchar(15),             
        @1ReturnCode int = 1,
        @1ValidInquiryDate nvarchar(max)='',
        @1ValidDOB nvarchar(max) = '' 
       
       
EXECUTE @lInterrorCode = sp_xml_preparedocument @intDoc OUTPUT, @rXmlDoc
 
CREATE TABLE #tTable1 
 (
		Id bigint identity,
        FirstName nvarchar(100),
        MiddleName nvarchar(100),
        LastName nvarchar(100),
		Class nvarchar(100),
		
		InquiryDate nvarchar(15), 
        InquiryStatus nvarchar(50),
        DOB nvarchar(15),
        Gender nvarchar(10),
		InquiryMode nvarchar(50)  
	 
 
  )
  INSERT INTO #tTable1
	(
	    
	    FirstName,
	    MiddleName,
	    LastName,
	    Class,
	    InquiryDate,
	    InquiryStatus,
	    DOB,
	    Gender,
		InquiryMode
	    
    ) 
   SELECT
       
	    FirstName,
	    MiddleName,
	    LastName,
	    Class,
	    InquiryDate,
	    InquiryStatus,
	    DOB,
	    Gender,
		InquiryMode
	  
   
   FROM OPENXML (@intDoc, '/Table/ImportStudent', 1)
   With
   (
        
        FirstName nvarchar(100) '@FirstName',
        MiddleName  nvarchar(100) '@MiddleName',
        LastName nvarchar(100) '@LastName',
		Class nvarchar(100) '@Class',
		InquiryDate nvarchar(15) '@InquiryDate',
		InquiryStatus nvarchar(50) '@InquiryStatus',
		DOB nvarchar(15) '@DOB',
		Gender nvarchar(10) '@Gender' ,
		InquiryMode nvarchar(50) '@InquiryMode'
   )   
EXEC sp_xml_removedocument @intDoc
		
SELECT @lCount =  COUNT(Id) FROM #tTable1
 
WHILE @lCount > 0 
  BEGIN
  
	SELECT         
		@lInquiryDate = InquiryDate 
			FROM #tTable1 WHERE Id = @lCount
	IF(@lInquiryDate = '')
	BEGIN    
		SELECT 'Inquiry date Should not be empty'   AS StudentCode
	END
    ELSE IF(ISDATE(@lInquiryDate) = 0 AND @lInquiryDate!='')
	BEGIN    
		SET @1ValidInquiryDate = @1ValidInquiryDate + @lInquiryDate+','
	END

	SELECT         
		@lDOB = DOB 
			FROM #tTable1 WHERE Id = @lCount
	IF(ISDATE(@lDOB) = 0 AND @lDOB!='')
	BEGIN
		SET @1ValidDOB=@1ValidDOB +   @lDOB+','
	END
     SET @lCount = @lCount - 1	
   END	
    
   
   SELECT @lCount =  COUNT(Id) FROM #tTable1
 
	WHILE @lCount > 0 
		BEGIN
			SELECT         
			 @lClass = Class 
			FROM #tTable1 WHERE Id = @lCount

			IF NOT EXISTS (SELECT 1 FROM  
					 sSetup.tClassMaster CM  
						WHERE CM.Title COLLATE DATABASE_DEFAULT =@lClass COLLATE DATABASE_DEFAULT  )	
			BEGIN
				
				SELECT 'Enter proper value for Class ' + @lClass   AS StudentCode
				RETURN
			END
			SET @lCount = @lCount - 1	
		END
   	
		   
		 
		  IF EXISTS(SELECT 1 FROM #tTable1 WHERE LastName IS NULL OR LastName COLLATE DATABASE_DEFAULT ='' COLLATE DATABASE_DEFAULT)
		BEGIN
			SELECT 'Surname Should not be empty' AS StudentCode
		END
		ELSE IF EXISTS(SELECT 1 fROM #tTable1 WHERE FirstName IS NULL OR FirstName COLLATE DATABASE_DEFAULT ='' COLLATE DATABASE_DEFAULT)
		BEGIN
			SELECT 'First Name Should not be empty' AS StudentCode
		END
		ELSE IF EXISTS(SELECT 1 fROM #tTable1 WHERE MiddleName IS NULL OR MiddleName COLLATE DATABASE_DEFAULT ='' COLLATE DATABASE_DEFAULT)
		BEGIN
			SELECT 'Middle Name Should not be empty' AS StudentCode
		END
		ELSE IF EXISTS(SELECT 1 fROM #tTable1 WHERE Class IS NULL OR Class COLLATE DATABASE_DEFAULT ='' COLLATE DATABASE_DEFAULT)
		BEGIN
			SELECT 'Class Should not be empty' AS StudentCode
		END
		 
	 
		ELSE IF EXISTS(SELECT 1 fROM #tTable1 WHERE Gender IS NULL OR Gender COLLATE DATABASE_DEFAULT ='' COLLATE DATABASE_DEFAULT)
		BEGIN
			SELECT 'Gender Should not be empty' AS StudentCode
		END
 
		ELSE IF EXISTS(SELECT 1 fROM #tTable1 WHERE Class  COLLATE DATABASE_DEFAULT NOT IN(SELECT Title FROM sSetup.tClassMaster WHERE OrgId=@rOrgId))
		BEGIN
			SELECT 'Enter proper value for Class as per Institute Setup > Class Master' AS StudentCode
		END				
		 
		ELSE IF EXISTS(SELECT 1 fROM #tTable1 WHERE Gender COLLATE DATABASE_DEFAULT !='' COLLATE DATABASE_DEFAULT AND Gender NOT IN(SELECT Title FROM sCommon.tGenderMaster))
		BEGIN
			SELECT 'Enter proper value / Check spelling for gender ( Male / Female )' AS StudentCode
		END
		--ELSE IF EXISTS(SELECT 1 fROM #tTable1 WHERE AdmissionCategory!='' AND AdmissionCategory NOT IN(SELECT Title FROM sStudent.tAdmissionCategoryMaster))
		--BEGIN
		--	SELECT 'Enter proper value for Cast Category (Indian,NRI,General)' AS StudentCode
		--END
			 
		Else if Exists(Select 1 from #tTable1 where InquiryStatus COLLATE DATABASE_DEFAULT !='' COLLATE DATABASE_DEFAULT AND InquiryStatus NOT IN (Select Title from sAdmission.tInquiryStatusMaster))
		Begin
			Select 'Enter proper Value or check Spelling for Inquiry Status' AS StudentCode
		End
		ELSE IF EXISTS(SELECT 1 fROM #tTable1 WHERE InquiryStatus IS NULL OR InquiryStatus COLLATE DATABASE_DEFAULT ='' COLLATE DATABASE_DEFAULT)
		BEGIN
			SELECT 'Inquiry Status Should not be empty ' AS StudentCode
		END
		ELSE IF NOT EXISTS(SELECT 1 FROM #tTable1 WHERE InquiryMode IN(SELECT Title FROM sAdmission.tInquiryModeMaster ) OR InquiryMode='')
		BEGIN
			SELECT 'Inquiry Mode is not proper as per Inquiry Mode Master' AS StudentCode
		END

		ELSE
			
		BEGIN
			IF((@1ValidInquiryDate IS NULL OR @1ValidInquiryDate = '') AND (@1ValidDOB IS NULL OR @1ValidDOB = ''))
		BEGIN
			SELECT '' AS StudentCode
		END
		
		ELSE IF (@1ValidInquiryDate IS NOT NULL AND @1ValidInquiryDate != '')
			BEGIN
			SET @1ValidInquiryDate = 'Wrong Inquiry Date : ' + LEFT(@1ValidInquiryDate, LEN(@1ValidInquiryDate)-1)
			Select @1ValidInquiryDate AS StudentCode
			END

		ELSE IF (@1ValidDOB IS NOT NULL AND @1ValidDOB != '')
			BEGIN
			SET @1ValidDOB = 'Wrong DOB : ' + LEFT(@1ValidDOB, LEN(@1ValidDOB)-1)
			Select @1ValidDOB AS StudentCode
			END
		
		END
		 
END
GO
PRINT N'Altering [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 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
           )
           
           SELECT           
            TS.NewStudentId,
            BankAccountNumber,
            BankName,
			BankBranch,
			BankIFSCCode,
			Class9BoardRegistrationNumber,
			Class11BoardRegistrationNumber,
			PassportNumber,
			PassportType,
			PassportCountryCode,
			PassportIssueDate,
			PassportExpiryDate
         	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
PRINT N'Altering [sTally].[pFeeLedgerMappingGet]...';


GO

ALTER PROCEDURE [sTally].[pFeeLedgerMappingGet]

	 @rOrgGroupBatchId int,
	 @rReceiptBookId int
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
Declare @lOrgGroupId Int
	Declare @lPostingTYpe nvarchar(100)
	
	SELECT @lOrgGroupId = OrgGroupId from sSetup.tOrgGroupBatchMaster Where Id=@rOrgGroupBatchId

	SELECT @lPostingTYpe = CASE WHEN CS.ItemValue IS NULL THEN C.ItemValue ELSE CS.ItemValue END  
	FROM sConfig.tConfigurationMaster C INNER JOIN sConfig.tConfigurationLevelMaster CM ON CM.Id = C.ConfigurationLevelId
	LEFT JOIN sConfig.tConfigurationSetup CS ON CS.ConfigurationId = C.Id AND CS.SOURCEID=@lOrgGroupId
	WHERE  C.ItemKey = 'Tally.PostingType'
    	
	if @lPostingTYpe = 'OrgMainGroupWise' 
	BEGIN
		SELECT Distinct
			   OM.TITLE AS FeeName,
			   OM.Id AS FeeId,
			    FLM.LedgerName AS LedgerName,
			   RBC.CompanyName 
	    FROM sSetup.tORganizationMAster OM 
		INNER JOIN sSetup.tOrgSubGroupMaster OSM ON OSM.Id = OM.OrgSubGRoupID
		INNER JOIN sTally.tReceiptBookCompanyMapping RBC ON RBC.ReceiptBookId = OSM.Id AND RBC.OrgGroupBatchId = @rOrgGroupBatchId
		LEFT JOIN sTally.tFeeLedgerMapping FLM ON FLM.FeeId= OM.Id
		
		--Where RBC.ReceiptBookId = @rReceiptBookId 
	END
	ELSE IF @lPostingTYpe = 'FeeHeadAndReceiptBookWise' OR @lPostingTYpe = 'FeeHeadWiseReceipt_AllDetail'
	BEGIN
		SELECT Distinct
				   FHM.TITLE AS FeeName,
				   FHM.Id AS FeeId,
				   FLM.LedgerName,
				   RBC.CompanyName 
			FROM sFee.tFeeSetup FS
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = FS.BatchId AND BM.OrgGroupBatchId = @rOrgGroupBatchId
			INNER JOIN sFee.tFeeMaster FM ON FM.Id = FS.FeeId
			INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id = FM.FeeHeadId
			INNER JOIN sTally.tReceiptBookCompanyMapping RBC ON RBC.ReceiptBookId = FS.ReceiptBookId AND RBC.OrgGroupBatchId = @rOrgGroupBatchId
			LEFT JOIN sTally.tFeeLedgerMapping FLM ON FLM.FeeId= FHM.Id AND FLM.ReceiptBookId = FS.ReceiptBookId
			Where FS.ReceiptBookId = @rReceiptBookId 
	END
	ELSE 
	
	BEGIN
		
		SELECT Distinct
			   FHM.TITLE AS FeeName,
			   FHM.Id AS FeeId,
			   FLM.LedgerName,
			   RBC.CompanyName 
	    FROM sFee.tFeeSetup FS
		INNER JOIN sSetup.tBatchMaster BM ON BM.Id = FS.BatchId AND BM.OrgGroupBatchId = @rOrgGroupBatchId
		INNER JOIN sFee.tFeeMaster FM ON FM.Id = FS.FeeId
		INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id = FM.FeeHeadId
		INNER JOIN sTally.tReceiptBookCompanyMapping RBC ON RBC.ReceiptBookId = FS.ReceiptBookId AND RBC.OrgGroupBatchId = @rOrgGroupBatchId
		LEFT JOIN sTally.tFeeLedgerMapping FLM ON FLM.FeeId= FHM.Id 
		Where FS.ReceiptBookId = @rReceiptBookId 
	END
END
GO
PRINT N'Altering [sTally].[pReceiptPostingGet]...';


GO

ALTER PROCEDURE [sTally].[pReceiptPostingGet]

	 @rOrgGroupBatchId int,
	 @rReceiptBookId int,
	 @rReceiptDate Date,
	 @rToReceiptDate Date,
	 @rPayTypeId int = 0,
	 @rCustomNarration nvarchar(max)='',
	 @rIsCustomNarration bit=0
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
	
	DECLARE @lTallyPostingType nVarchar(100)
	DECLARE @lOrgGroupId INT
	
	SELECT @lOrgGroupId = OrgGroupId from sSetup.tOrgGroupBatchMaster Where Id=@rOrgGroupBatchId
	
	SELECT @lTallyPostingType = CASE WHEN CS.ItemValue IS NULL THEN C.ItemValue ELSE CS.ItemValue END 
		FROM sConfig.tConfigurationMaster C
        INNER JOIN sConfig.tConfigurationLevelMaster CM ON CM.Id = C.ConfigurationLevelId
        LEFT JOIN sConfig.tConfigurationSetup CS ON CS.ConfigurationId = C.Id AND CS.SOURCEID= @lOrgGroupId
        WHERE  C.ItemKey = 'Tally.PostingType'
        
		
        IF @lTallyPostingType = 'FeeHeadWise' 
        BEGIN
			   SELECT	ReceiptDate,
						ISNULL(FHM.Title,'') AS FeeName,
						PM.Title AS PayType,
						Sum(FRD.Amount) AS Amount,
						Case when @rIsCustomNarration=1 then STUFF((SELECT ','  +Replace(replace(
																					Replace(
																					replace(
																					Replace(
																					replace(
																					Replace(
																					replace(
																					Replace(
																					replace(
																					Replace(
																					replace(
																					Replace(
																					replace(
																					Replace(
																					replace(
																					replace(
																					@rCustomNarration,'[Class]',isnull(SM1.ClassName,'')
																					),'[Division]',Isnull(SM1.DivisionName,'')
																					),'[StudentsName]',isnull(SM1.Name,'')
																					), '[RollNumber]',isnull(convert(nvarchar(200),SM1.RollNo),'0')
																					),'[Batch]',isnull(SM1.BatchName,'')
																					), '[ReceiptNumber]', isnull(Convert(nvarchar(100),FR1.ReceiptNumber),'')
																					), '[ReceiptDate]',isnull(Convert(nvarchar(100),FR1.ReceiptDate),'')
																					), '[ReceiptAmount]',isnull(Convert(nvarchar(100),FR1.ReceiptAmount),'')
																					), '[ChequeNo]',isnull(Convert(nvarchar(100),FR1.ChequeNo),'')
																					),'[BankName]',isnull(FR1.BankName,'')
																					),'[FeeName]',isnull(FM1.Title,'')
																					), '[FeeAmount]',isnull(Convert(nvarchar(100),Sum(FRD.Amount)),'0.00')
																					),'[FeeHeadName]',ISNULL(FHM.Title,'')
																					), '[FeeHeadAmount]',isnull(Convert(nvarchar(100),Sum(FRD.Amount)),'0.00')
																					), '[CollectionGroupName]',isNull(CGM1.Title,'')
																					),'[ReceiptFromNumber]',isnull(Convert(nvarchar(10),(Select Min(ReceiptNumber) from sFee.tReceipt where   FR.ReceiptDate =ReceiptDate)),'')
																					), '[ReceiptToNumber]',isnull(Convert(nvarchar(10),(Select Max(ReceiptNumber) from sFee.tReceipt Where FR.ReceiptDate = ReceiptDate)),''))
						from sFee.tReceipt FR1  INNER JOIN sFee.tReceiptDetail FRD1 ON FR1.Id = FRD1.ReceiptId
						INNER JOIN sFee.tFeeSetup FS1 ON FS1.Id = FRD1.FeeSetupId 
						INNER JOIN sStudent.vStudentAcademic SM1 ON SM1.ACademicId = FR1.SourceID AND SM1.OrgGRoupBatchId = FR1.OrgGRoupBatchId 						
						INNER JOIN sFee.tFeeMaster FM1 ON FM1.Id = FS1.FeeId --AND FRD.ReceiptId=FRD1.ReceiptId
						LEFT JOIN sFee.tCollectionGroupMaster CGM1 ON CGM1.Id = FS1.CollectionGroupId
						INNER JOIN sFee.tFeeHeadMaster FHM1 ON FHM1.Id = FM1.FeeHeadId AND FHM1.Id=FHM.Id where  FR.ReceiptDate=FR1.ReceiptDate FOR XML PATH('')),1,1,'') else
						 'Receipt generated for Batch : ' + (Select Title from sSetup.tOrgGroupBatchMaster Where Id= @rOrgGroupBatchId) +
						' Receipt Date : ' +  Convert(nvarchar(10),ReceiptDate) + ' and Receipt Number From ' + Convert(nvarchar(10),(Select Min(ReceiptNumber) from sFee.tReceipt where   FR.ReceiptDate =ReceiptDate AND IsObsolete = 0 )) + ' -  ' + 
						Convert(nvarchar(10),(Select Max(ReceiptNumber) from sFee.tReceipt Where FR.ReceiptDate = ReceiptDate AND IsObsolete = 0)) end as Narration,						
						FR.PayTypeId AS PayTypeId, 
						FHM.Id AS FeeId,
						0 AS ReceiptId
				FROM sFee.tReceipt FR 
					INNER JOIN sFee.tReceiptDetail FRD ON FR.Id = FRD.ReceiptId
					INNER JOIN sFee.tFeeSetup FS ON FS.Id = FRD.FeeSetupId
					INNER JOIN sFee.tFeeMaster FM ON FM.Id = FS.FeeId
					INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id = FM.FeeHeadId
					INNER JOIN sFinanceCommon.tPayTypeMaster PM ON PM.Id = FR.PayTypeId
					WHERE	FR.ReceiptBookId = @rReceiptBookId 
							AND FR.IsObsolete = 0 
							AND FR.OrgGroupBatchId = @rOrgGroupBatchId
							AND FR.ReceiptDate >= @rReceiptDate AND FR.ReceiptDate <= @rToReceiptDate
							AND (FR.PayTypeId = @rPayTypeId OR @rPayTypeId = 0)
				group by ReceiptDate,FHM.Title,PM.Title,FHM.Id,FR.PayTypeId
				Order By ReceiptDate Desc
			END				
       ELSE IF @lTallyPostingType = 'FeeHeadWiseCustom' 
        BEGIN
			   SELECT	ReceiptDate,
						FR.Id AS FeeName,
						PM.Title AS PayType,
						Sum(FRD.Amount) AS Amount,
						Case when @rIsCustomNarration=1 then  STUFF((SELECT ','  +Replace(replace(
																					Replace(
																					replace(
																					Replace(
																					replace(
																					Replace(
																					replace(
																					Replace(
																					replace(
																					Replace(
																					replace(
																					Replace(
																					replace(
																					Replace(
																					replace(
																					replace(
																					@rCustomNarration,'[Class]',isnull(SM1.ClassName,'')
																					),'[Division]',Isnull(SM1.DivisionName,'')
																					),'[StudentsName]',isnull(SM1.Name,'')
																					), '[RollNumber]',isnull(convert(nvarchar(200),SM1.RollNo),'0')
																					),'[Batch]',isnull(SM1.BatchName,'')
																					), '[ReceiptNumber]', isnull(Convert(nvarchar(100),FR1.ReceiptNumber),'')
																					), '[ReceiptDate]',isnull(Convert(nvarchar(100),FR1.ReceiptDate),'')
																					), '[ReceiptAmount]',isnull(Convert(nvarchar(100),FR1.ReceiptAmount),'')
																					), '[ChequeNo]',isnull(Convert(nvarchar(100),FR1.ChequeNo),'')
																					),'[BankName]',isnull(FR1.BankName,'')
																					),'[FeeName]',isnull(FM1.Title,'')
																					), '[FeeAmount]',isnull(Convert(nvarchar(100),Sum(FRD.Amount)),'0.00')
																					),'[FeeHeadName]',ISNULL(FHM1.Title,'')
																					), '[FeeHeadAmount]',isnull(Convert(nvarchar(100),Sum(FRD.Amount)),'0.00')
																					), '[CollectionGroupName]',isNull(CGM1.Title,'')
																					),'[ReceiptFromNumber]',isnull(Convert(nvarchar(10),(Select Min(ReceiptNumber) from sFee.tReceipt where   FR.ReceiptDate =ReceiptDate AND IsObsolete = 0)),'')
																					), '[ReceiptToNumber]',isnull(Convert(nvarchar(10),(Select Max(ReceiptNumber) from sFee.tReceipt Where FR.ReceiptDate = ReceiptDate AND IsObsolete = 0)),''))
						from sFee.tReceipt FR1  INNER JOIN sFee.tReceiptDetail FRD1 ON FR1.Id = FRD1.ReceiptId
						INNER JOIN sFee.tFeeSetup FS1 ON FS1.Id = FRD1.FeeSetupId 
						INNER JOIN sStudent.vStudentAcademic SM1 ON SM1.ACademicId = FR1.SourceID AND SM1.OrgGRoupBatchId = FR1.OrgGRoupBatchId 						
						INNER JOIN sFee.tFeeMaster FM1 ON FM1.Id = FS1.FeeId --AND FRD.ReceiptId=FRD1.ReceiptId
						LEFT JOIN sFee.tCollectionGroupMaster CGM1 ON CGM1.Id = FS1.CollectionGroupId
						INNER JOIN sFee.tFeeHeadMaster FHM1 ON FHM1.Id = FM1.FeeHeadId  where   FR.ReceiptDate=FR1.ReceiptDate AND FR.Id=FR1.Id AND FR1.IsObsolete = 0  FOR XML PATH('')),1,1,'') else
						SM.Name + '(' + ClassName + ':' + DivisionName + ') ' + ' # Cheque No. :' + ISNULL(FR.ChequeNo,'') + ' BankName :' + ISNULL(FR.BankName,'') end as Narration,						
						FR.PayTypeId AS PayTypeId, 
						0 AS FeeId,
						FR.Id AS ReceiptId
				FROM sFee.tReceipt FR 
					INNER JOIN sFee.tReceiptDetail FRD ON FR.Id = FRD.ReceiptId
					INNER JOIN sStudent.vStudentAcademic SM ON SM.ACademicId = FR.SourceID AND SM.OrgGRoupBatchId = FR.OrgGRoupBatchId 
					INNER JOIN sFee.tFeeSetup FS ON FS.Id = FRD.FeeSetupId
					INNER JOIN sFee.tFeeMaster FM ON FM.Id = FS.FeeId
					INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id = FM.FeeHeadId
					INNER JOIN sFinanceCommon.tPayTypeMaster PM ON PM.Id = FR.PayTypeId
					INNER JOIN sSetup.tOrganizationMaster OM ON  OM.Id=SM.OrgId
					LEFT JOIN sSetup.tOrgSubGroupMaster OSM ON OSM.id=OM.OrgSubGroupId

					WHERE	FR.ReceiptBookId= @rReceiptBookId 
							AND FR.IsObsolete = 0 
							AND FR.OrgGroupBatchId = @rOrgGroupBatchId
							AND FR.ReceiptDate >= @rReceiptDate AND FR.ReceiptDate <= @rToReceiptDate
							AND (FR.PayTypeId = @rPayTypeId OR @rPayTypeId = 0)
				group by ReceiptDate,PM.Title,FR.PayTypeId,FR.Id,SM.Name + '(' + ClassName + ':' + DivisionName + ') ' + ' # Cheque No. :' + ISNULL(FR.ChequeNo,'') + ' BankName :' + ISNULL(FR.BankName,'')
				Order By FR.Id,ReceiptDate Desc
			END	

       ELSE IF @lTallyPostingType = 'OrgMainGroupWise' 
        BEGIN
			   SELECT	ReceiptDate,
						SM.AcademicId AS FeeName,
						PM.Title AS PayType,
						Sum(FRD.Amount) AS Amount,
						Case when @rIsCustomNarration=1 then  STUFF((SELECT ','  +Replace(replace(
																					Replace(
																					replace(
																					Replace(
																					replace(
																					Replace(
																					replace(
																					Replace(
																					replace(
																					Replace(
																					replace(
																					Replace(
																					replace(
																					Replace(
																					replace(
																					replace(
																					@rCustomNarration,'[Class]',isnull(SM1.ClassName,'')
																					),'[Division]',Isnull(SM1.DivisionName,'')
																					),'[StudentsName]',isnull(SM1.Name,'')
																					), '[RollNumber]',isnull(convert(nvarchar(200),SM1.RollNo),'0')
																					),'[Batch]',isnull(SM1.BatchName,'')
																					), '[ReceiptNumber]', isnull(Convert(nvarchar(100),FR1.ReceiptNumber),'')
																					), '[ReceiptDate]',isnull(Convert(nvarchar(100),FR1.ReceiptDate),'')
																					), '[ReceiptAmount]',isnull(Convert(nvarchar(100),FR1.ReceiptAmount),'')
																					), '[ChequeNo]',isnull(Convert(nvarchar(100),FR1.ChequeNo),'')
																					),'[BankName]',isnull(FR1.BankName,'')
																					),'[FeeName]',isnull(FM1.Title,'')
																					), '[FeeAmount]',isnull(Convert(nvarchar(100),Sum(FRD.Amount)),'0.00')
																					),'[FeeHeadName]',ISNULL(FHM1.Title,'')
																					), '[FeeHeadAmount]',isnull(Convert(nvarchar(100),Sum(FRD.Amount)),'0.00')
																					), '[CollectionGroupName]',isNull(CGM1.Title,'')
																					),'[ReceiptFromNumber]',isnull(Convert(nvarchar(10),FR1.ReceiptNumber),'')
																					), '[ReceiptToNumber]',isnull(Convert(nvarchar(10),FR1.ReceiptNumber),''))
						from sFee.tReceipt FR1  INNER JOIN sFee.tReceiptDetail FRD1 ON FR1.Id = FRD1.ReceiptId
						INNER JOIN sFee.tFeeSetup FS1 ON FS1.Id = FRD1.FeeSetupId 
						INNER JOIN sStudent.vStudentAcademic SM1 ON SM1.ACademicId = FR1.SourceID AND SM1.OrgGRoupBatchId = FR1.OrgGRoupBatchId 						
						INNER JOIN sFee.tFeeMaster FM1 ON FM1.Id = FS1.FeeId --AND FRD.ReceiptId=FRD1.ReceiptId
						LEFT JOIN sFee.tCollectionGroupMaster CGM1 ON CGM1.Id = FS1.CollectionGroupId
						INNER JOIN sFinanceCommon.tPayTypeMaster PM1 ON PM1.Id = FR1.PayTypeId
						INNER JOIN sFee.tFeeHeadMaster FHM1 ON FHM1.Id = FM1.FeeHeadId  where  FR.ReceiptDate=FR1.ReceiptDate AND PM.Title=PM1.Title AND SM.AcademicId=SM1.AcademicId AND  FR.PayTypeId=FR1.PayTypeId AND FR1.IsObsolete = 0  FOR XML PATH('')),1,1,'') else
						SM.Name + '(' + ClassName + ':' + DivisionName + ') ' + ' # Cheque No. :' + ISNULL(FR.ChequeNo,'') + ' BankName :' + ISNULL(FR.BankName,'') end as Narration,						
						FR.PayTypeId AS PayTypeId, 
						FR.Id AS FeeId,
						SM.AcademicId AS ReceiptId
				FROM sFee.tReceipt FR 
					INNER JOIN sFee.tReceiptDetail FRD ON FR.Id = FRD.ReceiptId
					INNER JOIN sStudent.vStudentAcademic SM ON SM.ACademicId = FR.SourceID AND SM.OrgGRoupBatchId = FR.OrgGRoupBatchId 
					INNER JOIN sFee.tFeeSetup FS ON FS.Id = FRD.FeeSetupId
					INNER JOIN sFee.tFeeMaster FM ON FM.Id = FS.FeeId
					INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id = FM.FeeHeadId
					INNER JOIN sFinanceCommon.tPayTypeMaster PM ON PM.Id = FR.PayTypeId
					INNER JOIN sSEtup.tOrganizationMaster OM ON OM.OrgSubGRoupID =  @rReceiptBookId AND OM.ID = SM.OrgId					
					WHERE	FR.IsObsolete = 0 
							AND FR.OrgGroupBatchId = @rOrgGroupBatchId
							AND FR.ReceiptDate >= @rReceiptDate AND FR.ReceiptDate <= @rToReceiptDate
							AND FR.PayTypeID = 2
							AND (FR.PayTypeId = @rPayTypeId OR @rPayTypeId = 0)
				group by ReceiptDate,PM.Title,SM.AcademicId ,FR.PayTypeId,FR.Id,SM.Name + '(' + ClassName + ':' + DivisionName + ') ' + ' # Cheque No. :' + ISNULL(FR.ChequeNo,'') + ' BankName :' + ISNULL(FR.BankName,'')
				Order By FR.Id,ReceiptDate Desc
			END	
	ELSE IF @lTallyPostingType = 'ReceiptWise' 
			BEGIN	
				SELECT	ReceiptDate,						
						ISNULL(SLM.LedgerName,'') AS FeeName,
						PM.Title AS PayType,						
						FR.ReceiptAmount AS Amount,
						Case when @rIsCustomNarration=1 then  STUFF((SELECT ','+  +Replace(
																					replace(
																					Replace(
																					replace(
																					Replace(
																					replace(
																					Replace(
																					replace(
																					Replace(
																					replace(
																					Replace(
																					replace(
																					Replace(
																					replace(
																					Replace(
																					replace(
																					replace(
																					@rCustomNarration,'[Class]',isnull(SM1.ClassName,'')
																					),'[Division]',Isnull(SM1.DivisionName,'')
																					),'[StudentsName]',isnull(SM1.Name,'')
																					), '[RollNumber]',isnull(convert(nvarchar(200),SM1.RollNo),'0')
																					),'[Batch]',isnull(SM1.BatchName,'')
																					), '[ReceiptNumber]', isnull(Convert(nvarchar(100),FR1.ReceiptNumber),'')
																					), '[ReceiptDate]',isnull(Convert(nvarchar(100),FR1.ReceiptDate),'')
																					), '[ReceiptAmount]',isnull(Convert(nvarchar(100),FR1.ReceiptAmount),'')
																					), '[ChequeNo]',isnull(Convert(nvarchar(100),FR1.ChequeNo),'')
																					),'[BankName]',isnull(FR1.BankName,'')
																					),'[FeeName]',isnull(FM1.Title,'')
																					), '[FeeAmount]',isnull(Convert(nvarchar(100),Sum(FRD.Amount)),'0.00')
																					),'[FeeHeadName]',ISNULL(FHM1.Title,'')
																					), '[FeeHeadAmount]',isnull(Convert(nvarchar(100),Sum(FRD.Amount)),'0.00')
																					), '[CollectionGroupName]',isNull(CGM1.Title,'')
																					),'[ReceiptFromNumber]',isnull(Convert(nvarchar(10),FR1.ReceiptNumber),'')
																					), '[ReceiptToNumber]',isnull(Convert(nvarchar(10),FR1.ReceiptNumber),''))
						from sFee.tReceipt FR1  INNER JOIN sFee.tReceiptDetail FRD1 ON FR1.Id = FRD1.ReceiptId
						INNER JOIN sFee.tFeeSetup FS1 ON FS1.Id = FRD1.FeeSetupId 
						INNER JOIN sStudent.vStudentAcademic SM1 ON SM1.ACademicId = FR1.SourceID AND SM1.OrgGRoupBatchId = FR1.OrgGRoupBatchId 						
						INNER JOIN sFee.tFeeMaster FM1 ON FM1.Id = FS1.FeeId --AND FRD.ReceiptId=FRD1.ReceiptId
						LEFT JOIN sFee.tCollectionGroupMaster CGM1 ON CGM1.Id = FS1.CollectionGroupId
						INNER JOIN sFinanceCommon.tPayTypeMaster PM1 ON PM1.Id = FR1.PayTypeId
						INNER JOIN sFee.tFeeHeadMaster FHM1 ON FHM1.Id = FM1.FeeHeadId
						LEFT JOIN sTally.tStudentLedgerMapping SLM1 ON SLM1.StudentId = SM1.StudentId AND SLM1.ReceiptBookid = FR1.ReceiptBookId AND SLM.LedgerName=SLM1.LedgerName where  FR1.ReceiptDate=FR.ReceiptDate   AND FR1.PayTypeId=FR.PayTypeId AND  A.StudentId=SM1.StudentId AND FR.ReceiptAmount=FR1.ReceiptAmount AND FR1.IsObsolete = 0  FOR XML PATH('')),1,1,'') else
						case When FR.PayTypeId = 1 then
						'Std-' + ClassName + ':' + DivisionName + ' RollNo :' + convert(nvarchar(20),RollNo) + ' ' + BatchName + '-->' +
						STUFF((SELECT ','  + convert(nvarchar(20),isnull(FRD1.Amount,'')) + '-' + isnull(FM1.Title ,'') 
						from sFee.tReceipt FR1  INNER JOIN sFee.tReceiptDetail FRD1 ON FR1.Id = FRD1.ReceiptId
						INNER JOIN sFee.tFeeSetup FS1 ON FS1.Id = FRD1.FeeSetupId 						
						INNER JOIN sFee.tFeeMaster FM1 ON FM1.Id = FS1.FeeId AND FRD.ReceiptId=FRD1.ReceiptId  FOR XML PATH('')),1,1,'') 
						when FR.PayTypeId <> 1 then 
						'Std-' + ClassName + ':' + DivisionName + ' RollNo :' + convert(nvarchar(20),RollNo) + ' ' + BatchName + '-->' +
						STUFF((SELECT ','  + convert(nvarchar(20),isnull(FRD1.Amount,'')) + '-' + isnull(FM1.Title ,'') 
						from sFee.tReceipt FR1  INNER JOIN sFee.tReceiptDetail FRD1 ON FR1.Id = FRD1.ReceiptId
						INNER JOIN sFee.tFeeSetup FS1 ON FS1.Id = FRD1.FeeSetupId 						
						INNER JOIN sFee.tFeeMaster FM1 ON FM1.Id = FS1.FeeId AND FRD.ReceiptId=FRD1.ReceiptId  FOR XML PATH('')),1,1,'') + '  Cheque No. :' + ISNULL(FR.ChequeNo,'') + ' BankName :' + ISNULL(FR.BankName,'')  ENd
						end AS Narration,
						--A.Name+', '+ClassName + '-' + DivisionName+', '+A.OrganizationName+', ('+BatchName+')'
						--AS Narration,					
						FR.PayTypeId AS PayTypeId,									
						A.StudentId AS FeeId,
						FRD.ReceiptId					 
				FROM sFee.tReceipt FR 
					INNER JOIN sFee.tReceiptDetail FRD ON FR.Id = FRD.ReceiptId
					INNER JOIN sFee.tFeeSetup FS ON FS.Id = FRD.FeeSetupId
					INNER JOIN sFee.tFeeMaster FM ON FM.Id = FS.FeeId
					INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id = FM.FeeHeadId
					INNER JOIN sFinanceCommon.tPayTypeMaster PM ON PM.Id = FR.PayTypeId
					INNER JOIN sStudent.vStudentAcademic A ON A.AcademicId = FR.SourceId AND A.OrgGRoupBatchId = FR.OrgGRoupBatchId
					LEFT JOIN sTally.tStudentLedgerMapping SLM ON SLM.StudentId = A.StudentId AND SLM.ReceiptBookid = FR.ReceiptBookId
					WHERE							
							FR.ReceiptBookId = @rReceiptBookId 
							AND FR.IsObsolete = 0 
							AND FR.OrgGroupBatchId = @rOrgGroupBatchId
							AND FR.ReceiptDate >= @rReceiptDate	And FR.ReceiptDate <= @rToReceiptDate
							AND (FR.PayTypeId = @rPayTypeId OR @rPayTypeId = 0)
				group by 
				ReceiptDate,PM.Title,
				SLM.LedgerName,FR.PayTypeId,A.StudentId,
				FRD.ReceiptId,Isnull(FR.ChequeNo,''),ISNull(FR.BankName,''),
				--A.Name+', '+ClassName + '-' + DivisionName+', '+A.OrganizationName+', ('+BatchName+')',
				'Std-' + ClassName + ':' + DivisionName + ' RollNo :' + convert(nvarchar(20),RollNo) + ' ' + BatchName,
				FR.ReceiptAmount			
				Order By ReceiptDate desc
			END		
			
	ELSE IF @lTallyPostingType = 'FeeHeadAndReceiptBookWise' 
			BEGIN	
				SELECT	ReceiptDate,						
						ISNULL(SLM.LedgerName,'') AS FeeName,
						PM.Title AS PayType,						
						FR.ReceiptAmount AS Amount,
						Case when @rIsCustomNarration=1 then STUFF((SELECT ','  +Replace(replace(
																					Replace(
																					replace(
																					Replace(
																					replace(
																					Replace(
																					replace(
																					Replace(
																					replace(
																					Replace(
																					replace(
																					Replace(
																					replace(
																					Replace(
																					replace(
																					replace(
																					@rCustomNarration,'[Class]',isnull(SM1.ClassName,'')
																					),'[Division]',Isnull(SM1.DivisionName,'')
																					),'[StudentsName]',isnull(SM1.Name,'')
																					), '[RollNumber]',isnull(convert(nvarchar(200),SM1.RollNo),'0')
																					),'[Batch]',isnull(SM1.BatchName,'')
																					), '[ReceiptNumber]', isnull(Convert(nvarchar(100),FR1.ReceiptNumber),'')
																					), '[ReceiptDate]',isnull(Convert(nvarchar(100),FR1.ReceiptDate),'')
																					), '[ReceiptAmount]',isnull(Convert(nvarchar(100),FR1.ReceiptAmount),'')
																					), '[ChequeNo]',isnull(Convert(nvarchar(100),FR1.ChequeNo),'')
																					),'[BankName]',isnull(FR1.BankName,'')
																					),'[FeeName]',isnull(FM1.Title,'')
																					), '[FeeAmount]',isnull(Convert(nvarchar(100),Sum(FRD.Amount)),'0.00')
																					),'[FeeHeadName]',ISNULL(FHM1.Title,'')
																					), '[FeeHeadAmount]',isnull(Convert(nvarchar(100),Sum(FRD.Amount)),'0.00')
																					), '[CollectionGroupName]',isNull(CGM1.Title,'')
																					),'[ReceiptFromNumber]',isnull(Convert(nvarchar(10),FR1.ReceiptNumber),'')
																					), '[ReceiptToNumber]',isnull(Convert(nvarchar(10),FR1.ReceiptNumber),''))
						from sFee.tReceipt FR1  INNER JOIN sFee.tReceiptDetail FRD1 ON FR1.Id = FRD1.ReceiptId
						INNER JOIN sFee.tFeeSetup FS1 ON FS1.Id = FRD1.FeeSetupId 
						INNER JOIN sStudent.vStudentAcademic SM1 ON SM1.ACademicId = FR1.SourceID AND SM1.OrgGRoupBatchId = FR1.OrgGRoupBatchId 						
						INNER JOIN sFee.tFeeMaster FM1 ON FM1.Id = FS1.FeeId --AND FRD.ReceiptId=FRD1.ReceiptId
						LEFT JOIN sFee.tCollectionGroupMaster CGM1 ON CGM1.Id = FS1.CollectionGroupId
						INNER JOIN sFinanceCommon.tPayTypeMaster PM1 ON PM1.Id = FR1.PayTypeId
						INNER JOIN sFee.tFeeHeadMaster FHM1 ON FHM1.Id = FM1.FeeHeadId 
						LEFT JOIN sTally.tStudentLedgerMapping SLM1 ON SLM1.StudentId = SM1.StudentId AND SLM1.ReceiptBookid = FR1.ReceiptBookId AND SLM.LedgerName=SLM1.LedgerName where  FR1.ReceiptDate=FR.ReceiptDate AND PM1.Title=PM.Title  AND FR1.PayTypeId=FR.PayTypeId AND A.StudentId=SM1.StudentId AND FR.ReceiptAmount=FR1.ReceiptAmount AND FR1.IsObsolete = 0  FOR XML PATH('')),1,1,'') else
						case When FR.PayTypeId = 1 then
						'Receiptno-'  + CONVERT(nvarchar,isnull(FR.ReceiptNumber,'')) + 
						STUFF((SELECT ','  + convert(nvarchar(20),isnull(FM1.title,'')) 
						from sFee.tReceipt FR1  INNER JOIN sFee.tReceiptDetail FRD1 ON FR1.Id = FRD1.ReceiptId And FRD1.ReceiptId = FRD.ReceiptId 
						INNER JOIN sFee.tFeeSetup FS1 ON FS1.Id = FRD1.FeeSetupId 						
						INNER JOIN sFee.tFeeMaster FM1 ON FM1.Id = FS1.FeeId AND FRD.ReceiptId=FRD1.ReceiptId  FOR XML PATH('')),1,1,'') 
						when FR.PayTypeId <> 1 then 
						'Receiptno-'  +  CONVERT(nvarchar,isnull(FR.ReceiptNumber,'')) +
						STUFF((SELECT ','  + convert(nvarchar(20),isnull(FM1.title,'')) 
						from sFee.tReceipt FR1  INNER JOIN sFee.tReceiptDetail FRD1 ON FR1.Id = FRD1.ReceiptId And FRD1.ReceiptId = FRD.ReceiptId 
						INNER JOIN sFee.tFeeSetup FS1 ON FS1.Id = FRD1.FeeSetupId 						
						INNER JOIN sFee.tFeeMaster FM1 ON FM1.Id = FS1.FeeId AND FRD.ReceiptId=FRD1.ReceiptId  FOR XML PATH('')),1,1,'') 
						+ '  Cheque No. :' + ISNULL(FR.ChequeNo,'') + ' BankName :' + ISNULL(FR.BankName,'')  ENd
						end AS Narration,
						FR.PayTypeId AS PayTypeId,									
						A.StudentId AS FeeId,
						FRD.ReceiptId		
									 
				FROM sFee.tReceipt FR 
					INNER JOIN sFee.tReceiptDetail FRD ON FR.Id = FRD.ReceiptId
					INNER JOIN sFee.tFeeSetup FS ON FS.Id = FRD.FeeSetupId
					INNER JOIN sFee.tFeeMaster FM ON FM.Id = FS.FeeId
					INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id = FM.FeeHeadId
					INNER JOIN sFinanceCommon.tPayTypeMaster PM ON PM.Id = FR.PayTypeId
					INNER JOIN sStudent.vStudentAcademic A ON A.AcademicId = FR.SourceId AND A.OrgGRoupBatchId = FR.OrgGRoupBatchId
					LEFT JOIN sTally.tStudentLedgerMapping SLM ON SLM.StudentId = A.StudentId AND SLM.ReceiptBookid = FR.ReceiptBookId
					WHERE							
							FR.ReceiptBookId = @rReceiptBookId 
							AND FR.IsObsolete = 0 
							AND FR.OrgGroupBatchId = @rOrgGroupBatchId
							AND FR.ReceiptDate >= @rReceiptDate	And FR.ReceiptDate <= @rToReceiptDate
							AND (FR.PayTypeId = @rPayTypeId OR @rPayTypeId = 0)
				group by 
				ReceiptDate,PM.Title,
				SLM.LedgerName,FR.PayTypeId,A.StudentId,
				FRD.ReceiptId,
				Isnull(FR.ChequeNo,''),ISNull(FR.BankName,''),
				'Std-' + ClassName + ':' + DivisionName + ' RollNo :' + convert(nvarchar(20),RollNo) + ' ' + BatchName,FR.ReceiptAmount,FR.ReceiptNumber
				--,FHM.Title
				
				Order By ReceiptDate desc	
			END	
	ELSE IF @lTallyPostingType = 'FeeHeadWiseReceipt_AllDetail' 
        BEGIN
			   SELECT	ReceiptDate,
						FR.Id AS FeeName,
						PM.Title AS PayType,
						Sum(FRD.Amount) AS Amount,
						Case when @rIsCustomNarration=1 then  STUFF((SELECT ','  +Replace(replace(
																					Replace(
																					replace(
																					Replace(
																					replace(
																					Replace(
																					replace(
																					Replace(
																					replace(
																					Replace(
																					replace(
																					Replace(
																					replace(
																					Replace(
																					replace(
																					replace(
																					@rCustomNarration,'[Class]',isnull(SM1.ClassName,'')
																					),'[Division]',Isnull(SM1.DivisionName,'')
																					),'[StudentsName]',isnull(SM1.Name,'')
																					), '[RollNumber]',isnull(convert(nvarchar(200),SM1.RollNo),'0')
																					),'[Batch]',isnull(SM1.BatchName,'')
																					), '[ReceiptNumber]', isnull(Convert(nvarchar(100),FR1.ReceiptNumber),'')
																					), '[ReceiptDate]',isnull(Convert(nvarchar(100),FR1.ReceiptDate),'')
																					), '[ReceiptAmount]',isnull(Convert(nvarchar(100),FR1.ReceiptAmount),'')
																					), '[ChequeNo]',isnull(Convert(nvarchar(100),FR1.ChequeNo),'')
																					),'[BankName]',isnull(FR1.BankName,'')
																					),'[FeeName]',isnull(FM1.Title,'')
																					), '[FeeAmount]',isnull(Convert(nvarchar(100),Sum(FRD.Amount)),'0.00')
																					),'[FeeHeadName]',ISNULL(FHM1.Title,'')
																					), '[FeeHeadAmount]',isnull(Convert(nvarchar(100),Sum(FRD.Amount)),'0.00')
																					), '[CollectionGroupName]',isNull(CGM1.Title,'')
																					),'[ReceiptFromNumber]',isnull(Convert(nvarchar(10),(Select Min(ReceiptNumber) from sFee.tReceipt where   FR.ReceiptDate =ReceiptDate AND IsObsolete = 0)),'')
																					), '[ReceiptToNumber]',isnull(Convert(nvarchar(10),(Select Max(ReceiptNumber) from sFee.tReceipt Where FR.ReceiptDate = ReceiptDate AND IsObsolete = 0)),''))
						from sFee.tReceipt FR1  INNER JOIN sFee.tReceiptDetail FRD1 ON FR1.Id = FRD1.ReceiptId
						INNER JOIN sFee.tFeeSetup FS1 ON FS1.Id = FRD1.FeeSetupId 
						INNER JOIN sStudent.vStudentAcademic SM1 ON SM1.ACademicId = FR1.SourceID AND SM1.OrgGRoupBatchId = FR1.OrgGRoupBatchId 						
						INNER JOIN sFee.tFeeMaster FM1 ON FM1.Id = FS1.FeeId --AND FRD.ReceiptId=FRD1.ReceiptId
						LEFT JOIN sFee.tCollectionGroupMaster CGM1 ON CGM1.Id = FS1.CollectionGroupId
						INNER JOIN sFee.tFeeHeadMaster FHM1 ON FHM1.Id = FM1.FeeHeadId  where   FR.ReceiptDate=FR1.ReceiptDate AND FR.Id=FR1.Id AND FR1.IsObsolete = 0  FOR XML PATH('')),1,1,'') else
						case When FR.PayTypeId = 1 then
						'ReceiptNo-'  + CONVERT(nvarchar,isnull(FR.ReceiptNumber,'')) + '('+BatchName+')'
						when FR.PayTypeId <> 1 then 
						'Receiptno-'  +  CONVERT(nvarchar,isnull(FR.ReceiptNumber,'')) + '('+BatchName+')'
						+ '  Cheque No. :' + ISNULL(FR.ChequeNo,'') + ' BankName :' + ISNULL(FR.BankName,'')  ENd 
						END as Narration,						
						FR.PayTypeId AS PayTypeId, 
						FR.Id  AS FeeId,
						FR.Id AS ReceiptId
				FROM sFee.tReceipt FR 
					INNER JOIN sFee.tReceiptDetail FRD ON FR.Id = FRD.ReceiptId
					INNER JOIN sStudent.vStudentAcademic SM ON SM.ACademicId = FR.SourceID AND SM.OrgGRoupBatchId = FR.OrgGRoupBatchId 
					INNER JOIN sFee.tFeeSetup FS ON FS.Id = FRD.FeeSetupId
					INNER JOIN sFee.tFeeMaster FM ON FM.Id = FS.FeeId
					INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id = FM.FeeHeadId
					INNER JOIN sFinanceCommon.tPayTypeMaster PM ON PM.Id = FR.PayTypeId
					INNER JOIN sSetup.tOrganizationMaster OM ON  OM.Id=SM.OrgId
					LEFT JOIN sSetup.tOrgSubGroupMaster OSM ON OSM.id=OM.OrgSubGroupId

					WHERE	FR.ReceiptBookId= @rReceiptBookId 
							AND FR.IsObsolete = 0 
							AND FR.OrgGroupBatchId = @rOrgGroupBatchId
							AND FR.ReceiptDate >= @rReceiptDate AND FR.ReceiptDate <= @rToReceiptDate
							AND (FR.PayTypeId = @rPayTypeId OR @rPayTypeId = 0)
				group by ReceiptDate,PM.Title,FR.PayTypeId,FR.Id,isnull(FR.ReceiptNumber,'') , BatchName,ISNULL(FR.BankName,''),ISNULL(FR.ChequeNo,'')
				Order By FR.Id,ReceiptDate Desc
			END			
			
END
GO
PRINT N'Altering [sTally].[pReceiptTallyPostingAdd]...';


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

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

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

	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Creating [sAdmission].[pRptAdmissionInquiryListGet]...';


GO

CREATE PROCEDURE [sAdmission].[pRptAdmissionInquiryListGet]
	
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='',
	 @rClassId int = 0,
	 @rOrgId int = 0,
	 @rDepartmentId int = 0,
	 @rFromDate datetime='',
	 @rToDate datetime='',
	 @rFromMeritMarks decimal(10,2) = 0,
	 @rToMeritMarks decimal(10,2)=0,
	 @rInquiryStatusId int =0,
	 @rBatchId int = 0 
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 	

	SELECT 
	
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			AI.Id InquiryId,
			ISNULL(AI.Number,0) AS InquiryNumber,
			AI.ForClassId AS ClassId,
			ISNULL(CM.Title,'') AS ClassName,
			AI.FirstName,
			AI.MiddleName,
			AI.LastName,
			[sStudent].[fStudentNameGet](AI.FirstName , ISNULL(AI.MiddleName,'') , AI.LastName,OM.StudentNameFormatId ) AS StudentName,
			ISNULL(AI.InquiryDate,'') AS AdmissionInquiryDate,
			ISNULL(AI.FatherContactNo,'') AS FatherContactNo,
			ISNULL(AI.MotherContactNo,'') AS MotherContactNo,
			SM.Title AS InquiryStatus

  FROM 
            sAdmission.tAdmissionInquiry AI
            INNER JOIN sAdmission.tInquiryStatusMaster SM ON SM.Id=AI.InquiryStatusId 
			INNER JOIN sSetup.tClassMaster CM ON CM.Id=AI.ForClassId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=AI.OrgId
  WHERE  
	((AI.InquiryDate>= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
      AND ((AI.InquiryDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
	  AND ((AI.ForClassId=@rClassId) OR (@rClassId=0)) 
	  AND ((SM.Id=@rInquiryStatusId) OR (@rInquiryStatusId=0))
	  AND (AI.OrgId=@rOrgId OR @rOrgId=0)
	  AND ((CM.DepartmentId=@rDepartmentId) or (@rDepartmentId = 0))
	  AND ((AI.MeritMarks >= @rFromMeritMarks) OR (@rFromMeritMarks=0))
	  AND ((AI.MeritMarks <= @rToMeritMarks) OR (@rToMeritMarks=0))	
	  AND ((AI.ForBatchId=@rBatchId) OR (@rBatchId=0))		    
END
GO
PRINT N'Creating [sAlert].[pIssueBookAllGet]...';


GO
CREATE PROCEDURE [sAlert].[pIssueBookAllGet]
	 
	 @rSourceTypeId smallint,
	 @rFromDate date,
	 @rToDate date,
	 @rOrgId smallint,
	 @rBatchId int,
	 @rDepartmentId int = 0,
	 @rClassId int = 0,
	 @rDivisionId int = 0,
	 @rTemplate nvarchar(max),	 	
	 @rMailSubject nvarchar(max)=''
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			
BEGIN 	
		SELECT distinct
			SC.OrgGroupId,
			SC.OrgId,
			SC.AcademicId,
			SC.Code,
			SC.Name AS Name,
			SC.ParentContactNo AS MobileNo,	
			SC.ParentEmail AS EmailId,
			SC.WhatsAppContactNo,
			replace (
			replace (
			replace(@rTemplate,'[Name]',SC.Name),			
			'[BookCode - BookName - IssueDate]',(SELECT STUFF ((SELECT distinct ',' +' ' + BM1.Code +' - '+BM1.Title+' - '+ CONVERT(nvarchar(100), BL1.LogDate, 103)
					From sLibrary.tBookLog BL1
					INNER JOIN sLibrary.tBookMaster BM1 ON BM1.Id=BL1.ResourceSourceId
					INNER JOIN sStudent.vStudentCommunication SC1 ON SC1.StudentId = BL1.ReaderSourceId AND SC1.BatchId = BL1.BatchId  AND BL1.ReaderSourceTypeId=2003
					INNER JOIN sSetup.tBatchMaster BMM1 ON BMM1.Id = BL1.BatchId 
					INNER JOIN sSetup.tOrganizationMaster OM1 ON OM1.Id = BL1.OrgId
					INNER JOIN sLibrary.tLibraryMaster LM1 ON LM.Id=BL1.LibraryId
					WHERE
							(BL1.ReaderSourceTypeId=@rSourceTypeId OR @rSourceTypeId=0)
						AND ((BL1.LogDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
						AND ((BL1.LogDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
						AND (BL1.OrgId = @rOrgId)
						AND (BL1.BatchId = @rBatchId)
						AND (BL1.ReaderSourceTypeId != 0)
						AND ((SC1.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
						AND ((SC1.ClassId=@rClassId) OR (@rClassId=0))
						AND ((SC1.DivisionId=@rDivisionId) OR (@rDivisionId=0))
						AND BL1.IsCurrentStatus=1 
						AND BL1.ReaderSourceId=BL.ReaderSourceId	
						AND (SC.StatusId=1) AND SC.IsBlockAllAlert=0	
                    FOR XML PATH('')),1,1,''))),
			'[LibraryName]',LM.Title)
			 AS Template,
			replace (
			replace (
			replace(@rTemplate,'[Name]',SC.Name),			
			'[BookCode - BookName - IssueDate]',(SELECT STUFF ((SELECT distinct ',' +' ' + BM1.Code +' - '+BM1.Title+' - '+ CONVERT(nvarchar(100), BL1.LogDate, 103)
					From sLibrary.tBookLog BL1
					INNER JOIN sLibrary.tBookMaster BM1 ON BM1.Id=BL1.ResourceSourceId AND BL1.ReaderSourceTypeId=2003
					AND BL1.ReaderSourceId=BL.ReaderSourceId  AND BL1.ReaderSourceId = SC.StudentId AND BL1.BatchId =SC.BatchId  
					AND BMM.Id = BL1.BatchId  AND BL1.OrgId = OM.Id AND  BL1.LibraryId =LM.Id
					AND (SC.StatusId=1) AND SC.IsBlockAllAlert=0
					AND BL1.IsCurrentStatus=1 		
                    FOR XML PATH('')),1,1,'') )),
			'[LibraryName]',LM.Title)
			 AS MsgText,
			'2003' AS SourceTypeId,
			SC.StudentId AS SourceId,
			@rMailSubject AS Subject,
			2003 AS ReceiverSourceTypeId,
			SC.StudentId AS ReceiverSourceId,
			LM.Title AS LibraryName
	From 
		sLibrary.tBookLog BL
		INNER JOIN sLibrary.tBookMaster BM ON BM.Id=BL.ResourceSourceId
		INNER JOIN sStudent.vStudentCommunication SC ON SC.StudentId = BL.ReaderSourceId AND SC.BatchId = BL.BatchId  AND BL.ReaderSourceTypeId=2003
		INNER JOIN sSetup.tBatchMaster BMM ON BMM.Id = BL.BatchId 
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = BL.OrgId
		INNER JOIN sCommon.tStatusMaster SM ON SM.Id=BL.StatusId
		INNER JOIN sLibrary.tLibraryMaster LM ON LM.Id=BL.LibraryId
	WHERE
		(BL.ReaderSourceTypeId=@rSourceTypeId OR @rSourceTypeId=0)
		AND ((BL.LogDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
		AND ((BL.LogDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
				AND (BL.OrgId = @rOrgId OR @rOrgId=0)
		AND (BL.BatchId = @rBatchId OR @rBatchId = 0)
		AND (BL.ReaderSourceTypeId != 0)
		AND ((SC.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
		AND ((SC.ClassId=@rClassId) OR (@rClassId=0))
		AND ((SC.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		AND (SC.StatusId=1) AND SC.IsBlockAllAlert=0	
		AND BL.IsCurrentStatus=1 

	UNION 

	SELECT distinct
			OM.OrgGroupId,
			EC.OrgId,
			EC.EmployeeId As AcademicId,
			EC.Code,
			EC.EmployeeName AS Name,
			EC.MobileNumber AS MobileNo,	
			EC.CompanyEmail AS EmailId,
			EC.WhatsAppContactNo,
			replace (
			replace (
			replace(@rTemplate,'[Name]',EC.EmployeeName),			
			'[BookCode - BookName - IssueDate]',(SELECT STUFF ((SELECT distinct ',' +' ' + BM1.Code +' - '+BM1.Title+' - '+ CONVERT(nvarchar(100), BL1.LogDate, 103)
						From sLibrary.tBookLog BL1
							INNER JOIN sLibrary.tBookMaster BM1 ON BM1.Id=BL1.ResourceSourceId AND BL1.ReaderSourceTypeId=95
							AND BL1.ReaderSourceId=BL.ReaderSourceId  AND BL1.ReaderSourceId = EC.EmployeeId 
							AND BL1.OrgId = OM.Id AND  BL1.LibraryId =LM.Id AND ODM.Id = EC.DepartmentId
							AND ISNULL(EC.IsOtherUser,0) = 0  AND EC.StatusId = 7
							AND BL1.IsCurrentStatus=1
                    FOR XML PATH('')),1,1,'') )),
			'[LibraryName]',LM.Title)
			 AS Template,
			replace (
			replace (
			replace(@rTemplate,'[Name]',EC.EmployeeName),			
			'[BookCode - BookName - IssueDate]',(SELECT STUFF ((SELECT distinct ',' +' ' + BM1.Code +' - '+BM1.Title+' - '+ CONVERT(nvarchar(100), BL1.LogDate, 103)
						From sLibrary.tBookLog BL1
							INNER JOIN sLibrary.tBookMaster BM1 ON BM1.Id=BL1.ResourceSourceId AND BL1.ReaderSourceTypeId=95
							AND BL1.ReaderSourceId=BL.ReaderSourceId  AND BL1.ReaderSourceId = EC.EmployeeId 
							AND BL1.OrgId = OM.Id AND  BL1.LibraryId =LM.Id AND ODM.Id = EC.DepartmentId
							AND ISNULL(EC.IsOtherUser,0) = 0  AND EC.StatusId = 7
							AND BL1.IsCurrentStatus=1	
                    FOR XML PATH('')),1,1,'') )),
			'[LibraryName]',LM.Title)
			 AS MsgText,
			'95' AS SourceTypeId,
			EC.EmployeeId AS SourceId,
			@rMailSubject AS Subject,
			95 AS ReceiverSourceTypeId,
			EC.EmployeeId AS ReceiverSourceId,
			LM.Title AS LibraryName
	         
	FROM 
		sLibrary.tBookLog BL
		INNER JOIN sLibrary.tBookMaster BM ON BM.Id=BL.ResourceSourceId
		INNER JOIN sHrm.vEmployeeCommunication EC ON EC.EmployeeId=BL.ReaderSourceId AND BL.ReaderSourceTypeId=95 
		INNER JOIN sSetup.tDepartmentMaster ODM ON ODM.Id = EC.DepartmentId
		INNER JOIN [sSetup].[tOrganizationMaster] OM ON OM.Id = EC.OrgId
		INNER JOIN sCommon.tStatusMaster SM ON SM.Id=BL.StatusId
		INNER JOIN sLibrary.tLibraryMaster LM ON LM.Id=BL.LibraryId

	WHERE 

		 (BL.OrgId = @rOrgId OR @rOrgId=0)
		AND (BL.BatchId = @rBatchId OR @rBatchId = 0)
		AND ((EC.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
		AND ((BL.LogDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
		AND ((BL.LogDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
		AND (BL.ReaderSourceTypeId=@rSourceTypeId OR @rSourceTypeId=0)
		AND ISNULL(EC.IsOtherUser,0) = 0  AND EC.StatusId = 7	
		AND BL.IsCurrentStatus=1 
		 
END
GO
PRINT N'Creating [sAssessment].[pExamSettingGet]...';


GO

 
CREATE PROCEDURE [sAssessment].[pExamSettingGet]
	 @rExamId int,
	 @rExamSettingTypeId int
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 		
IF(@rExamSettingTypeId = 1)
BEGIN
SELECT 
			EM.Id,
			EM.BatchId,
			ESGM.Code,
			ESGM.Title AS Name,
			ISNULL(IsProcessResult,0) AS IsProcessResult,
			ISNULL(ISNegativeMarks,0) AS ISNegativeMarks,
			ISNULL(IsLockForEdit,0) AS IsLockForEdit,
			ISNULL(IsPublished,0) AS IsPublished,
			ISNULL(IsPublishExamSchedule,0) As IsPublishExamSchedule

   FROM 
			sAssessment.tExamMaster EM
			INNER JOIN sAssessment.tExamSubGroupMaster	ESGM ON ESGM.Id = EM.ExamSubGroupId
			INNER JOIN sAssessment.tExamGroupMaster EGM ON EGM.Id=ESGM.ExamGroupId
			INNER JOIN sSetup.tClassMaster CM on CM.Id=EM.ClassId
			--INNER Join sSetup.tClassSubject CS ON EM.ClassId=CS.ClassId				
			--INNER JOIN sSetup.tSubjectMaster SM on   CS.SubjectId=SM.Id					
			--LEFT JOIN sAssessment.tExamDetail ED ON ED.ClassSubjectId = CS.Id AND ED.ExamId=EM.Id
			--LEFT Join sAssessment.tGradeSetMaster GSM ON GSM.Id = ED.GradeSetId
   WHERE       
            EM.Id=@rExamId
			order by ESGM.Title Desc
END

ELSE IF(@rExamSettingTypeId = 2)		 
BEGIN
	SELECT 
			EM.Id,
			EM.BatchId,
			ESGM.Code,
			ESGM.Title AS Name,
			EM.IsGrade,
			EM.IsPercentile,
			EM.IsRankNo,
			ISNULL(EM.IsGenerateRankNo,0)As IsGenerateRankNo,
			EM.IsPercentage,
			ISNULL(Em.IsRemovePercentageForFail,0) AS IsFailPercentageZero,
			EM.IsSubjectPercentile,
			ISNULL(IsResultStatus,0) AS IsDisplayResultStatus,
			ISNULL(IsAllExamPassRequired,0) As IsAllExamPassRequired,
			ISNULL(IsExcludeAbsentTotal,0) AS IsExcludeAbsentTotal


   FROM 
			sAssessment.tExamMaster EM
			INNER JOIN sAssessment.tExamSubGroupMaster	ESGM ON ESGM.Id = EM.ExamSubGroupId
			INNER JOIN sAssessment.tExamGroupMaster EGM ON EGM.Id=ESGM.ExamGroupId
			INNER JOIN sSetup.tClassMaster CM on CM.Id=EM.ClassId
			--INNER Join sSetup.tClassSubject CS ON EM.ClassId=CS.ClassId				
			--INNER JOIN sSetup.tSubjectMaster SM on   CS.SubjectId=SM.Id					
			--LEFT JOIN sAssessment.tExamDetail ED ON ED.ClassSubjectId = CS.Id AND ED.ExamId=EM.Id
			--LEFT Join sAssessment.tGradeSetMaster GSM ON GSM.Id = ED.GradeSetId
   WHERE       
            EM.Id=@rExamId
			order by ESGM.Title Desc

END
ELSE IF(@rExamSettingTypeId = 3)		 
BEGIN
	SELECT 
			EM.Id,
			EM.BatchId,
			ESGM.Code,
			ESGM.Title AS Name,
			ISNULL(IsDisplayPhoto,0) AS IsDisplayPhoto,
			ISNULL(IsDisplaySchoolName,0) AS IsDisplaySchoolName,
			ISNULL(IsDisplayBirthDate,0) AS IsDisplayBirthDate,
			ISNULL(IsDisplayParentName,0) AS IsDisplayParentName,
			ISNULL(IsDisplayHeightWeight,0) AS IsDisplayHeightWeight,
			ISNULL(IsDisplayGradeString,0) AS IsDisplayGradeString,
			ISNULL(EM.IsDisplayTotalMark,0) AS IsDisplayTotalMark,
			ISNULL(EM.IsDisplayResultIndicator,0) AS IsDisplayResultIndicator,
			ISNULL(IsDisplayHighestDivisionMark,0) AS IsDisplayHighestDivisionMark,
			ISNULL(IsDisplayHighestDivisionGrade,0) AS IsDisplayHighestDivisionGrade,
			ISNULL(IsDisplayTeacherSign,0) AS IsDisplayTeacherSign,
			ISNULL(IsDisplayPrincipalSign,0) AS IsDisplayPrincipalSign,
			ISNULL(IsDisplayActivityGrade,0) AS IsDisplayActivityGrade
			--ISNULL(EM.DetailAdjustment,0) AS DetailAdjustment,
			--ISNULL(EM.FooterAdjustment,0) AS FooterAdjustment,
			--ISNULL(EM.ExamMaximum,0) AS ExamMaximum
   FROM 
			sAssessment.tExamMaster EM
			INNER JOIN sAssessment.tExamSubGroupMaster	ESGM ON ESGM.Id = EM.ExamSubGroupId
			INNER JOIN sAssessment.tExamGroupMaster EGM ON EGM.Id=ESGM.ExamGroupId
			INNER JOIN sSetup.tClassMaster CM on CM.Id=EM.ClassId
			--INNER Join sSetup.tClassSubject CS ON EM.ClassId=CS.ClassId				
			--INNER JOIN sSetup.tSubjectMaster SM on   CS.SubjectId=SM.Id					
			--LEFT JOIN sAssessment.tExamDetail ED ON ED.ClassSubjectId = CS.Id AND ED.ExamId=EM.Id
			--LEFT Join sAssessment.tGradeSetMaster GSM ON GSM.Id = ED.GradeSetId
   WHERE       
            EM.Id=@rExamId
			order by ESGM.Title Desc

END
ELSE
BEGIN
SELECT 
			EM.Id,
			EM.BatchId,
			ESGM.Code,
			ESGM.Title AS Name,
			ISNULL(IsIncludeCoScholastic,0) AS IsIncludeCoScholastic,
			ISNULL(IsCoScholasticGradeIndicator,0) AS IsCoScholasticGradeIndicator,
			ISNULL(IsCoScholasticGradeDesIndicator,0) AS IsCoScholasticGradeDesIndicator,
			ISNULL(IsCoScholasticGrade,0) AS IsCoScholasticGrade
   FROM 
			sAssessment.tExamMaster EM
			INNER JOIN sAssessment.tExamSubGroupMaster	ESGM ON ESGM.Id = EM.ExamSubGroupId
			INNER JOIN sAssessment.tExamGroupMaster EGM ON EGM.Id=ESGM.ExamGroupId
			INNER JOIN sSetup.tClassMaster CM on CM.Id=EM.ClassId
			--INNER Join sSetup.tClassSubject CS ON EM.ClassId=CS.ClassId				
			--INNER JOIN sSetup.tSubjectMaster SM on   CS.SubjectId=SM.Id					
			--LEFT JOIN sAssessment.tExamDetail ED ON ED.ClassSubjectId = CS.Id AND ED.ExamId=EM.Id
			--LEFT Join sAssessment.tGradeSetMaster GSM ON GSM.Id = ED.GradeSetId
   WHERE       
            EM.Id=@rExamId
			order by ESGM.Title Desc
END


		
END
GO
PRINT N'Creating [sIp].[pImportStockItemCategory]...';


GO
CREATE PROCEDURE [sIp].[pImportStockItemCategory]
	  
	@rStrXml nvarchar(max),
	@rStoreLocationId int,
	@rScreenId int,
	@rOrgId int,
	@rCreatedUserId Bigint
		
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

DECLARE @lInterrorCode INT,@intDoc INT
EXECUTE @lInterrorCode = sp_xml_preparedocument @intDoc OUTPUT, @rStrXml

BEGIN
		
	BEGIN TRY

	CREATE TABLE #tempTable  
	(
		Id bigint identity,
		Code nvarchar(100),
		Name nvarchar(100)
	)

	INSERT INTO #tempTable
	(
		Code,
		Name
	)

	SELECT  A.Code,A.Name
			FROM OPENXML (@intDoc, '/Table/ImportStockMainMasterItem', 1)
	WITH
	(
		Code nvarchar(100) '@Code',
		Name nvarchar(100) '@Name'			
	) A
	
	EXEC sp_xml_removedocument @intDoc

	DECLARE @lCode nvarchar(100),@lTitle nvarchar(100)

	DECLARE @lCount int,@lId int

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

	WHILE @lId <= @lCount 
	BEGIN
		select @lCode = Code from #tempTable where Id = @lId
		select @lTitle = Name from #tempTable where Id = @lId
		
		IF Exists (SELECT Id FROM sIp.tStockItemCategoryMaster WHERE Code = @lCode AND StoreLocationId  = @rStoreLocationId)
		BEGIN
			Select -102 AS Result, 'Code Already Exists ' + @lCode AS Msg
			RETURN
		END

		IF EXISTS(SELECT Id FROM sIp.tStockItemCategoryMaster WHERE Title = @lTitle AND StoreLocationId  = @rStoreLocationId)
		BEGIN
		 Select -103 AS Result, 'Name Already Exists ' + @lTitle AS Msg
		 RETURN
		END

		SET @lId=@lId+1
	END
		

	Declare @lIsStatic1to100 bit, @lNextNumber BigInt, @lSeed int

	SET @lIsStatic1to100 = (SELECT IsStatic1to100 FROM sCommon.tCommonMaster AS tCM  LEFT JOIN sSecurity.tScreen SS ON ((tCM.ScreenId = SS.Id) AND (SS.IsObsolete = 0)) WHERE (ScreenId = @rScreenId))
	
	SET @lSeed = (CASE WHEN @lIsStatic1to100 = 1 THEN 101 ELSE 1 END)

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

	WHILE @lId1 <= @lCount1 
	BEGIN
		EXECUTE  sCommon.pTableRowIdGet  @rOrgId, 'sIp.tStockItemCategoryMaster', 0, @lSeed, 1,@outNextNumber = @lNextNumber output
		SET @lNextNumber = @lNextNumber

		select @lCode = Code from #tempTable where Id = @lId1
		select @lTitle = Name from #tempTable where Id = @lId1
		INSERT INTO sIp.tStockItemCategoryMaster
			(Id, Code, Title, IsObsolete, CreatedUserId,  CreatedDateTime, UpdatedUserId, UpdatedDateTime, StoreLocationId)
		VALUES
			(@lNextNumber, @lCode, @lTitle, 0, @rCreatedUserId, sCommon.fGetDate(), @rCreatedUserId, sCommon.fGetDate(), @rStoreLocationId)

		SET @lId1=@lId1+1
	END

	Select 1 AS Result, '' AS Msg

	DROP Table #tempTable
	END TRY

	BEGIN CATCH 
	SELECT -1 AS Result, error_message() AS Msg
	END CATCH	
END
GO
PRINT N'Creating [sIp].[pImportStockItemSubGroup]...';


GO
CREATE PROCEDURE [sIp].[pImportStockItemSubGroup]
	  
	@rStrXml nvarchar(max),
	@rStoreLocationId int,
	@rOrgGroupId int,
	@rCreatedUserId Bigint
		
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

DECLARE @lInterrorCode INT,@intDoc INT
EXECUTE @lInterrorCode = sp_xml_preparedocument @intDoc OUTPUT, @rStrXml

BEGIN
		
	BEGIN TRY

	CREATE TABLE #tempTable  
	(
		Id bigint identity,
		Code nvarchar(100),
		Name nvarchar(100),
		ItemMainGroup nvarchar(100)
	)

	INSERT INTO #tempTable
	(
		Code,
		Name,
		ItemMainGroup
	)

	SELECT  A.Code,A.Name,A.ItemMainGroup
			FROM OPENXML (@intDoc, '/Table/ImportStockMainMasterItem', 1)
	WITH
	(
		Code nvarchar(100) '@Code',
		Name nvarchar(100) '@Name',
		ItemMainGroup nvarchar(100) '@ItemMainGroup'		
	) A
	
	EXEC sp_xml_removedocument @intDoc

	DECLARE @lCode nvarchar(100),@lTitle nvarchar(100),@lItemMainGroup nvarchar(100)

	DECLARE @lCount int,@lId int

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

	WHILE @lId <= @lCount 
	BEGIN
		select @lCode = Code from #tempTable where Id = @lId
		select @lTitle = Name from #tempTable where Id = @lId
		SELECT @lItemMainGroup= ItemMainGroup from #tempTable where Id = @lId

		IF Exists (SELECT Id FROM sIp.tItemSubGroupMaster WHERE Code = @lCode AND StoreLocationId  = @rStoreLocationId)
		BEGIN
			Select -102 AS Result, 'Code Already Exists ' + @lCode AS Msg
			RETURN
		END

		IF EXISTS(SELECT Id FROM sIp.tItemSubGroupMaster WHERE Title = @lTitle AND StoreLocationId  = @rStoreLocationId)
		BEGIN
		 Select -103 AS Result, 'Name Already Exists ' + @lTitle AS Msg
		 RETURN
		END

		IF NOT EXISTS(SELECT Id FROM sIp.tItemMainGroupMaster WHERE Title = @lItemMainGroup AND StoreLocationId  = @rStoreLocationId)
		BEGIN
		 Select -100 AS Result, 'Item Main Group Not Exists ' + @lItemMainGroup AS Msg
		 RETURN
		END

		SET @lId=@lId+1
	END
		

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

	WHILE @lId1 <= @lCount1 
	BEGIN
		DECLARE @lNextNumber INT,@lItemMainGroupId int
		EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sIp.tItemSubGroupMaster', 0, 1, 1,@outNextNumber = @lNextNumber output

		select @lCode = Code from #tempTable where Id = @lId1
		select @lTitle = Name from #tempTable where Id = @lId1
		SELECT @lItemMainGroup= ItemMainGroup from #tempTable where Id = @lId1

		SET @lItemMainGroupId =(Select Id from sIp.tItemMainGroupMaster WHERE Title = @lItemMainGroup AND StoreLocationId  = @rStoreLocationId)
		
		INSERT INTO sIp.tItemSubGroupMaster
		(
			Id,
			Code,
			Title,
			ItemMainGroupId,			
			IsObsolete,
			CreatedUserId,
			CreatedDateTime,
			UpdatedUserId,
			UpdatedDateTime,
			OrgGroupId,
			StoreLocationId
		)
	VALUES
		(
			@lNextNumber,
			@lCode,
			@lTitle,
			@lItemMainGroupId,			
			0,
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rOrgGroupId,
			@rStoreLocationId
		)

		SET @lId1=@lId1+1
	END

	Select 1 AS Result, '' AS Msg

	DROP Table #tempTable
	END TRY

	BEGIN CATCH 
	SELECT -1 AS Result, error_message() AS Msg
	END CATCH	
END
GO
PRINT N'Creating [sIp].[pImportStockMainGroupMaster]...';


GO
CREATE PROCEDURE [sIp].[pImportStockMainGroupMaster]
	  
	@rStrXml nvarchar(max),
	@rStoreLocationId int,
	@rScreenId int,
	@rOrgId int,
	@rCreatedUserId Bigint
		
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

DECLARE @lInterrorCode INT,@intDoc INT
EXECUTE @lInterrorCode = sp_xml_preparedocument @intDoc OUTPUT, @rStrXml

BEGIN
		
	BEGIN TRY

	CREATE TABLE #tempTable  
	(
		Id bigint identity,
		Code nvarchar(100),
		Name nvarchar(100)
	)

	INSERT INTO #tempTable
	(
		Code,
		Name
	)

	SELECT  A.Code,A.Name
			FROM OPENXML (@intDoc, '/Table/ImportStockMainMasterItem', 1)
	WITH
	(
		Code nvarchar(100) '@Code',
		Name nvarchar(100) '@Name'			
	) A
	
	EXEC sp_xml_removedocument @intDoc

	
	DECLARE @lCode nvarchar(100),@lTitle nvarchar(100)

	DECLARE @lCount int,@lId int

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

	WHILE @lId <= @lCount 
	BEGIN
		select @lCode = Code from #tempTable where Id = @lId
		select @lTitle = Name from #tempTable where Id = @lId
		
		IF Exists (SELECT Id FROM sIp.tItemMainGroupMaster WHERE Code = @lCode AND StoreLocationId  = @rStoreLocationId)
		BEGIN
			Select -102 AS Result, 'Code Already Exists ' + @lCode AS Msg
			RETURN
		END

		IF EXISTS(SELECT Id FROM sIp.tItemMainGroupMaster WHERE Title = @lTitle AND StoreLocationId  = @rStoreLocationId)
		BEGIN
		 Select -103 AS Result, 'Name Already Exists ' + @lTitle AS Msg
		 RETURN
		END

		SET @lId=@lId+1
	END
		

	Declare @lIsStatic1to100 bit, @lNextNumber BigInt, @lSeed int

	SET @lIsStatic1to100 = (SELECT IsStatic1to100 FROM sCommon.tCommonMaster AS tCM  LEFT JOIN sSecurity.tScreen SS ON ((tCM.ScreenId = SS.Id) AND (SS.IsObsolete = 0)) WHERE (ScreenId = @rScreenId))
	
	SET @lSeed = (CASE WHEN @lIsStatic1to100 = 1 THEN 101 ELSE 1 END)

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

	WHILE @lId1 <= @lCount1 
	BEGIN
		EXECUTE  sCommon.pTableRowIdGet  @rOrgId, 'sIp.tItemMainGroupMaster', 0, @lSeed, 1,@outNextNumber = @lNextNumber output
		SET @lNextNumber = @lNextNumber

		select @lCode = Code from #tempTable where Id = @lId1
		select @lTitle = Name from #tempTable where Id = @lId1
		INSERT INTO sIp.tItemMainGroupMaster
			(Id, Code, Title, CreatedUserId,  CreatedDateTime, IsObsolete, StoreLocationId)
		VALUES
			(@lNextNumber, @lCode, @lTitle, @rCreatedUserId, sCommon.fGetDate(), 0,@rStoreLocationId)

		SET @lId1=@lId1+1
	END

	Select 1 AS Result, '' AS Msg

	DROP Table #tempTable
	END TRY

	BEGIN CATCH 
	SELECT -1 AS Result, error_message() AS Msg
	END CATCH	
END
GO


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



ALTER TABLE sAccounting.tLedgerGroupMaster
DROP CONSTRAINT PK_tLedgerGroupMaster;   


GO  
ALTER TABLE sAccounting.tLedgerMaster
DROP CONSTRAINT PK_tLedgerMaster;   
GO
GO 
INSERT INTO [sSystem].[tVersionUpdate] ([VersionNumber],[VersionId],[Status],[UpdateScript],[StartDateTime],[EndDateTime],[OrgGroupId])
VALUES('23.06.30',230630,'BEGIN','Script',sCommon.fGetDate(),sCommon.fGetDate(),0)

GO



GO
PRINT N'Altering [sHrm].[tEmployeeDocument]...';


GO
ALTER TABLE [sHrm].[tEmployeeDocument]
    ADD [IsMigrate] BIT CONSTRAINT [DF_tEmployeeDocument_IsMigrate] DEFAULT ('0') NULL;


GO
PRINT N'Altering [sStudent].[tStudentDocument]...';


GO
ALTER TABLE [sStudent].[tStudentDocument]
    ADD [IsMigrate] BIT CONSTRAINT [DF_tStudentDocument_IsMigrate] DEFAULT ('0') NULL;


GO
PRINT N'Creating [sFee].[tLateFeeRuleMaster]...';


GO
CREATE TABLE [sFee].[tLateFeeRuleMaster] (
    [OrgId]      INT            NOT NULL,
    [Id]         INT            NOT NULL,
    [Title]      NVARCHAR (100) NOT NULL,
    [FeeRule]    NVARCHAR (200) NOT NULL,
    [IsObsolete] BIT            NULL
);


GO
PRINT N'Creating PK_tLateFeeRuleMaster...';


GO
ALTER TABLE [sFee].[tLateFeeRuleMaster]
    ADD CONSTRAINT [PK_tLateFeeRuleMaster] PRIMARY KEY CLUSTERED ([Id] ASC) WITH (ALLOW_PAGE_LOCKS = ON, ALLOW_ROW_LOCKS = ON, PAD_INDEX = OFF, IGNORE_DUP_KEY = OFF, STATISTICS_NORECOMPUTE = OFF);


GO


PRINT N'Creating [sHrm].[fEmployeeDocumentAllBatchDepartmentwiseget]...';


GO
CREATE FUNCTION [sHrm].[fEmployeeDocumentAllBatchDepartmentwiseget] (@rDocumentId int,@rEmployeeId bigint)
RETURNS [nvarchar](max) WITH EXECUTE AS CALLER
AS 
BEGIN

 DECLARE @lDepartmentId int
 DECLARE @lEmployeeId bigint

 SELECT @lDepartmentId = DepartmentId,@lEmployeeId = EmployeeId FROM sHrm.vEmployeeCommunication WHERE Id = @rEmployeeId
      DECLARE @rDocumentName Nvarchar(max)
      BEGIN
		SELECT @rDocumentName = ISNULL(STUFF(
			 (SELECT DISTINCT ',' + DocumentName FROM (SELECT DISTINCT SDM.DocumentName +'-OGB-'+cast(UD.OrgGroupBatchId as nvarchar) as DocumentName
			  FROM sCommon.tSubmitDocumentMaster SDM
			  INNER JOIN  sHrm.tEmployeeDocument ED ON SDM.Id=ED.SubmitDocumentMasterId
			  INNER JOIN sCommon.tSubmitDocumentScope DS ON DS.SubmitDocumentId=SDM.Id AND DS.SourceId = @lDepartmentId
			  Inner Join [sCommon].[tUploadDocument] UD On UD.DocumentId=ED.SubmitDocumentMasterId AND UserSourceTypeId=95 AND UserSourceId=ED.EmployeeId AND ( UD.UploadFunctionalityId=13)
			  where ED.EmployeeId=@lEmployeeId AND SDM.SubmitDocumentFunctionalityId = 2 AND ((SDM.Id=@rDocumentId)OR(@rDocumentId=0))

			  UNION ALL

			  SELECT DISTINCT UD.DocumentName  +'-OGB-'+cast(UD.OrgGroupBatchId as nvarchar) as DocumentName
			  FROM sCommon.tSubmitDocumentMaster SDM
			  INNER JOIN  sHrm.tEmployeeDocument ED ON SDM.Id=ED.SubmitDocumentMasterId
			  LEFT JOIN sCommon.tSubmitDocumentScope DS ON DS.SubmitDocumentId=SDM.Id
			  Left Join [sCommon].[tUploadDocument] UD On UD.DocumentId=ED.SubmitDocumentMasterId AND UserSourceTypeId=95 AND UserSourceId=ED.EmployeeId AND ( UD.UploadFunctionalityId=13)
			  where ED.EmployeeId=@lEmployeeId AND SDM.SubmitDocumentFunctionalityId = 2 AND UD.DocumentName is null   AND ((SDM.Id=@rDocumentId)OR(@rDocumentId=0)))
			  AS DocumentName
			  FOR XML PATH (''))
			  , 1, 1, ''),'')             
                                    
      END

     
      RETURN @rDocumentName
END
GO
PRINT N'Altering [sAssessment].[vGeneralExamColumnName]...';


GO




 
/******************************************************************************  
 Purpose          : To get Batch Wise  Class
 Created date     : 21 Nov 2013
 Author           : Kundan Patel 
 Copyright©       : Copyright © Sapphire Software Solutions
 ******************************************************************************/  
ALTER VIEW [sAssessment].[vGeneralExamColumnName]  
  
AS  
  
SELECT 	
		 --SA.AcademicId,	  
		 --SA.ClassId,
		 --SA.DivisionId,
		 SA.RollNo,
		 --SA.OrgId,
		 --SA.BatchId,
		 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,
		 R.TotalMarks,
		 R.TotalObtain,
		 R.ResultStatus,
		 R.ResultGrade,
		 R.ResultGradePoint,
		 R.RankNumber,
		 R.Percentage,
		 R.Percentile,
		 R.ResultRemark,
		 R.OtherRemark1,
		 ESGM.Code AS ExamCode,
		 ESGM.Title AS ExamName,
		 --EM.Id AS Id,
	     U.DisplayTitle AS CreatedUserName,
	     SR.ExamSeatNo,
	     SR.TotalDays,
	     SR.PresentDays,
	     SR.StudentHeight,
	     SR.StudentWeight,
	     SR.ResultRemark1,
	     SR.ResultRemark2,
	     SR.MyGoal,
	     SR.MyStrength,
	     SR.MyInterestHobby,
	     SR.Achievements,
	     SR.AreaOfInterest,
	     SR.Responsibility,
	     SR.DentalHygiene,
	     SR.VisionLeft,
	     SR.VisionRight,
	     SR.MyActivity,
	     SR.ClassTeacherRemark,
	     SR.HouseRemark,
	     SR.ResultRemark3,
	     SR.GeneralRemark,
		 CCM.Code As CastCategory,
		 SF.FatherName,
		 SF.MotherName,
	     ACM.Title AS FeeCategory,
		 HM.Title AS House
		 --SO.DateOfBirth
	     
	  	  	   
FROM 
		sStudent.vStudentAcademic SA
	INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=SA.OrgId
	INNER JOIN sSetup.tBatchMaster BM ON BM.Id=SA.BatchId
	INNER JOIN sAssessment.tResult R ON R.AcademicId=SA.AcademicId
	INNER JOIN sAssessment.tExamMaster EM ON EM.Id=R.ExamId
	INNER JOIN sSecurity.tUser U ON U.Id=R.UpdatedUserId
	INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId
	LEFT JOIN sAssessment.tStudentRemark SR ON SR.AcademicId=SA.AcademicId
	LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId=SA.StudentId
	LEFT JOIN sCommon.tCastCategoryMaster CCM ON CCM.Id=SO.CastCategoryId
	LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId = SA.StudentId
	LEFT JOIN sStudent.tAdmissionCategoryMaster ACM ON SA.AdmissionCategoryId = ACM.Id
	LEFT JOIN sActivity.tHouseMaster HM ON SO.HouseId = HM.Id
GO
PRINT N'Altering [sAssessment].[vGeneralExamCustomSearch]...';


GO








/******************************************************************************  
 Purpose          : To get Batch Wise  Class
 Created date     : 21 Nov 2013
 Author           : Kundan Patel 
 Copyright©       : Copyright © Sapphire Software Solutions
 ******************************************************************************/  
ALTER VIEW [sAssessment].[vGeneralExamCustomSearch]  
  
AS  
  
SELECT 	
		 SA.AcademicId,	  
		 SA.ClassId,
		 SA.DivisionId,
		 SA.RollNo,
		 SA.OrgId,
		 SA.BatchId,
		 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,
		 R.Id AS ResultId,
		 R.ExamId AS ExamId,
		 R.TotalMarks,
		 R.TotalObtain,
		 R.ResultStatus,
		 R.ResultGrade,
		 R.ResultGradePoint,
		 R.RankNumber,
		 R.Percentage,
		 R.Percentile,
		 R.ResultRemark,
		 R.OtherRemark1,
		 ESGM.Code AS ExamCode,
		 ESGM.Title AS ExamName,
	     U.Id AS CreatedUserId,
	     U.DisplayTitle AS CreatedUserName,
	     EM.ExamSubGroupId,
	     SR.ExamSeatNo,
	     SR.TotalDays,
	     SR.PresentDays,
	     SR.StudentHeight,
	     SR.StudentWeight,
	     SR.ResultRemark1,
	     SR.ResultRemark2,
	     SR.MyGoal,
	     SR.MyInterestHobby,
	     SR.MyStrength,
	     SR.Achievements,
	     SR.AreaOfInterest,
	     SR.Responsibility,
	  	 SR.DentalHygiene,
	  	 SR.VisionLeft,
	  	 SR.VisionRight  ,
	  	  CM.DepartmentId,
	  	  SR. MyActivity,
	  	  SR.ClassTeacherRemark,
	  	  SR.HouseRemark,
	  	  SR.ResultRemark3,
	  	  SR.GeneralRemark,
		  CCM.Id As CastCategoryId,
		  CCM.Code As CastCategory,

		  SF.FatherName,
		  SF.MotherName,
	      ACM.Title AS FeeCategory,
		  HM.Title AS House
		  --CONVERT(VARCHAR(10), SO.DateOfBirth, 103) AS DateOfBirth
		  --SM.Id AS SubjectId,
		  --SM.Title AS SubjectTitle   
FROM 
		sStudent.vStudentAcademic SA
	 INNER JOIN sSetup.tClassMaster  CM ON CM.Id= SA.ClassId
	 --Add By Vishkha
	 --INNER Join sSetup.tClassSubject CS ON CS.ClassId=CM.Id
	 --INNER JOIN sSetup.tSubjectMaster SM on CS.SubjectId=SM.Id AND SM.OrgId = SA.OrgId
	
	INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=SA.OrgId
	INNER JOIN sSetup.tBatchMaster BM ON BM.Id=SA.BatchId
	INNER JOIN sAssessment.tResult R ON R.AcademicId=SA.AcademicId
	INNER JOIN sAssessment.tExamMaster EM ON EM.Id=R.ExamId
	LEFT JOIN sSecurity.tUser U ON U.Id=R.UpdatedUserId
	INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId
	LEFT JOIN sAssessment.tStudentRemark SR ON SR.AcademicId = SA.AcademicId AND SR.ExamId = EM.Id
	LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId=SA.StudentId
	LEFT JOIN sCommon.tCastCategoryMaster CCM ON CCM.Id=SO.CastCategoryId

	LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId = SA.StudentId
	LEFT JOIN sStudent.tAdmissionCategoryMaster ACM ON SA.AdmissionCategoryId = ACM.Id
	LEFT JOIN sActivity.tHouseMaster HM ON SO.HouseId = HM.Id
GO


PRINT N'Altering [sAcademic].[pTopicMasterAdd]...';


GO


ALTER PROCEDURE [sAcademic].[pTopicMasterAdd]
	 
        @rId int,
        @rNumber smallint,
        @rTitle nvarchar(100),
        @rSubjectId int,
        @rClassId int,
        @rOrgId smallint,
        @rCreatedUserId bigint
		--@rIsObsolete bit
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	IF(@rId = 0)	
	BEGIN
		If Exists(select Id from sAcademic.tTopicMaster where Title=@rTitle AND OrgId=@rOrgId AND ClassId=@rClassId AND SubjectId=@rSubjectId)
			BEGIN
			select -102 as Result
			RETURN
		END 
	
		If Exists(select Id from sAcademic.tTopicMaster where Number=@rNumber AND OrgId=@rOrgId AND ClassId=@rClassId AND SubjectId=@rSubjectId)
			BEGIN
			select -103 as Result
			RETURN
		END 
	END
	ELSE
	BEGIN
		If  Exists(select Id from sAcademic.tTopicMaster where Title=@rTitle AND OrgId=@rOrgId AND ClassId=@rClassId AND SubjectId=@rSubjectId AND Id<>@rId)
		Begin
			select -102 as Result
			RETURN
		End
		If  Exists(select Id from sAcademic.tTopicMaster where Number=@rNumber AND OrgId=@rOrgId AND ClassId=@rClassId AND SubjectId=@rSubjectId AND Id<>@rId)
		Begin
			select -103 as Result
			RETURN
		End

	END
	
	
	
	 BEGIN TRANSACTION	
	 DECLARE @lNextNumber BIGINT 

	IF(@rId = 0)	
	BEGIN
		
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sAcademic.tTopicMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	INSERT INTO sAcademic.tTopicMaster
		(
			Id,
			Number,
			Title,
			SubjectId,
			ClassId,
			OrgId,
			CreatedUserId,
			CreatedDateTime
			--IsObsolete
		)
	VALUES
		(
			@lNextNumber,
			@rNumber,
			@rTitle,
			@rSubjectId,
			@rClassId,
			@rOrgId,
			@rCreatedUserId,
			sCommon.fGetDate()
			--@rIsObsolete
		)
		    SELECT 1 AS Result
	END	 

ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE  sAcademic.tTopicMaster
	    SET
			Number=@rNumber,
			Title=@rTitle,
			SubjectId=@rSubjectId,
			ClassId=@rClassId,
			OrgId=@rOrgId,
			UpdatedUserId=@rCreatedUserId,
			UpdatedDateTime=sCommon.fGetDate()
			--IsObsolete = @rIsObsolete
	      
	      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 [sAcademic].[pTopicMasterGet]...';


GO


ALTER PROCEDURE [sAcademic].[pTopicMasterGet]

	 @rId int,
	 @rOrgId smallint,
	 @rClassId int,
	 @rSubjectId int,
	 @rEmployeeId bigint,
	 @rSourceTypeId smallint = 0
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
	IF(@rSourceTypeId = 0)
	BEGIN
		SELECT 
				DISTINCT TM.Id,
				TM.Number,
				TM.Title,
				TM.OrgId,
				TM.ClassId,
				TM.SubjectId,
				TM.CreatedUserId,
				TM.CreatedDateTime,
				CM.DisplayTitle AS ClassName,
				SM.Title AS SubjectName,
				CM.OrderIndex,
				SM.OrderIndex
				--ISNULL(TM.IsObsolete,0) AS IsObsolete
		FROM 
				sAcademic.tTopicMaster TM
				INNER JOIN sSetup.tClassMaster CM ON CM.Id = TM.ClassId
				INNER JOIN sSetup.tSubjectMaster SM ON SM.Id = TM.SubjectId
				LEFT JOIN sAcademic.vTeacherSubjectDivision vTSD ON vTSD.ClassId = TM.ClassId 			
				--AND vTSD.SubjectId = TM.SubjectId 
				AND vTSD.EmployeeId = @rEmployeeId
		WHERE 
			(TM.OrgId=@rOrgId)
			AND ((TM.Id = @rId) OR (@rId = 0))
			AND ((TM.ClassId = @rClassId) OR (@rClassId = 0))
			AND ((TM.SubjectId = @rSubjectId) OR (@rSubjectId = 0))
			--AND ((vTSD.EmployeeId = @rEmployeeId) OR (vTSD.EmployeeId = 0))
			--ORDER BY CM.OrderIndex
		ORDER BY CM.OrderIndex,SM.OrderIndex,TM.Number ASC
	END
	ELSE IF (@rSourceTypeId = 95)
	BEGIN
		SELECT 
				DISTINCT TM.Id,
				TM.Number,
				TM.Title,
				TM.OrgId,
				TM.ClassId,
				TM.SubjectId,
				TM.CreatedUserId,
				TM.CreatedDateTime,
				CM.DisplayTitle AS ClassName,
				SM.Title AS SubjectName,
				CM.OrderIndex,
				SM.OrderIndex
				--ISNULL(TM.IsObsolete,0) AS IsObsolete
		FROM 
				sAcademic.tTopicMaster TM
				INNER JOIN sSetup.tClassMaster CM ON CM.Id = TM.ClassId
				INNER JOIN sSetup.tSubjectMaster SM ON SM.Id = TM.SubjectId
				INNER JOIN sAcademic.vTeacherSubjectDivision vTSD ON vTSD.ClassId = TM.ClassId AND vTSD.SubjectId = TM.SubjectId 
				AND vTSD.EmployeeId = @rEmployeeId
		WHERE 
			(TM.OrgId=@rOrgId)
			AND ((TM.Id = @rId) OR (@rId = 0))
			AND ((TM.ClassId = @rClassId) OR (@rClassId = 0))
			AND ((TM.SubjectId = @rSubjectId) OR (@rSubjectId = 0))
		ORDER BY CM.OrderIndex,SM.OrderIndex,TM.Number ASC
	END
END
GO
PRINT N'Altering [sAcademic].[pXMLTopicMasterAdd]...';


GO
ALTER PROCEDURE [sAcademic].[pXMLTopicMasterAdd]
	(
		@rXml  nvarchar(MAX),
		@rOrgId int,
		@rClassId int,
		@rSubjectId int,
		@rCreatedUserId bigint 
		
	)
AS

SET NOCOUNT ON

BEGIN

	DECLARE @lInterrorCode INT,@intDoc INT
	DECLARE @lNextNumber BIGINT			
 
	EXECUTE @lInterrorCode = sp_xml_preparedocument @intDoc OUTPUT, @rXml
	
	BEGIN TRY

	CREATE TABLE #tempTable  
	(
		Id bigint identity,
		Number smallint,
		Title nvarchar(500)
	)

	INSERT INTO #tempTable
	(
		Number,
		Title
	)
	SELECT	
			A.Number,
			A.Title
	FROM OPENXML (@intDoc, '/Table/TopicMaster', 1)
	WITH
	(
			Number nvarchar(100) '@Number',
			Title nvarchar(100) '@Title' 
			 
	)A 
	 
	DECLARE @lCount int,@lId int
	SELECT @lCount = COUNT(Id) FROM #tempTable
	SELECT Top 1 @lId=Id FROM #tempTable
	
	WHILE @lId <= @lCount 
	BEGIN

		DECLARE @lNumber smallint, @lTitle nvarchar(500), @lSubjectId Int, @lClassId int, @lOrgId smallint
		
		SELECT @lNumber = Number from #tempTable where  Id = @lId
		SELECT @lTitle = Title from #tempTable where  Id = @lId
		
		If Exists(select Id from sAcademic.tTopicMaster where Title=@lTitle AND OrgId=@rOrgId AND ClassId=@rClassId AND SubjectId=@rSubjectId)
		BEGIN
			select -102 as Result, 'Title Already Exists' AS MSG
			RETURN
		END 
	
		If Exists(select Id from sAcademic.tTopicMaster where Number=@lNumber AND OrgId=@rOrgId AND ClassId=@rClassId AND SubjectId=@rSubjectId)
		BEGIN
			select -103 as Result, 'Number Already Exists' AS MSG
			RETURN
		END 

			EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sAcademic.tTopicMaster', 0, 1, 1,@outNextNumber = @lNextNumber output

			print @lNextNumber

			INSERT INTO sAcademic.tTopicMaster
			(		Id,
					Number,
					Title,
					SubjectId,
					ClassID,
					OrgId,
					CreatedUserId,
					CreatedDateTime 
					
			)
			Values
			(	
					@lNextNumber,
					@lNumber,
					@lTitle,
					@rSubjectId,
					@rClassID,
					@rOrgId,
					@rCreatedUserId,
					sCommon.fGetDate()   
			)

		
	
		SELECT @lNextNumber = MAX(ID) FROM sAcademic.tTopicMaster Where OrgId=@rOrgId
		EXECUTE sCommon.pTableRowIdModify @rOrgId, @rTableTitle = 'sAcademic.tTopicMaster', @rCurrentNumber = @lNextNumber 

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


GO

ALTER PROCEDURE [sAdmission].[pRptAdmissionFeeGet]
	
	
	 @rBatchId int,
	 @rClassId int,
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='',
	 @rFromDate date,
	 @rToDate date,
	 @rIsDetail bit =0
AS
 SET NOCOUNT ON
			 

BEGIN 
	
	SELECT 
		 AF.FormNo,
		 AF.FirstName+' '+AF.MiddleName+' '+AF.LastName AS Name,
		 AF.ForClassId,
		 AF.BatchId,
		 AF.OrgId,
		 AF.City,
		 AF.FamilyCast,
		 CM.Title AS Class,
		 AF.FamilySubCast,
		 AF.CastCategoryId,
		 --for online and offline display same feename
		 AC.FormFeeName AS FeeName,
		 --ACF.FeeName,
		 --in online entry display amount from pt  and in offline entry amount display from aff
		 CASE WHEN AF.DataEntryModeId = 561 THEN PT.PayAmount ELSE AFF.FeeAmount END  AS FeeAmount,
		 --AFF.FeeAmount,
		 --ACF.FeeNumber,
		 @rIsDetail AS IsDetail,
		 @rBuilder1 AS Builder1,
		 @rBuilder2 AS Builder2,
		 ISNULL(AF.CreatedDateTime,'') AS CreatedDateTime
	 
	 FROM 
		sAdmission.tAdmissionForm AF	
		INNER JOIN sSetup.tClassMaster CM ON AF.ForClassId=CM.Id
		LEFT JOIN sAdmission.tAdmissionFormFee AFF ON AFF.AdmissionFormId = AF.Id
		LEFT JOIN sAdmission.tAdmissionCriteriaFee ACF ON ACF.Id = AFF.AdmissionCriteriaFeeId
		INNER JOIN sAdmission.tAdmissionCriteria AC ON AC.ClassId=CM.Id AND AC.BatchId = @rBatchId
		LEFT JOIN sOp.tPaymentTransaction PT ON AF.Id = PT.PayerSourceId AND PT.TransactionSourceTypeId = 2027 AND PT.TransactionStatusId IN (2,4)
	WHERE 	
		AF.BatchId=@rBatchId
		--AND AF.OrgId=@rOrgId
		AND ((AF.ForClassId=@rClassId) OR (@rClassId=0))	
		AND ((CONVERT(DATE,AF.CreatedDateTime) >= @rFromDate) OR (isnull(@rFromDate,'')=''))
	    AND ((CONVERT(DATE,AF.CreatedDateTime) <= @rToDate) OR (isnull(@rToDate,'')=''))
	    ORDER BY AF.FormNo
END
GO
PRINT N'Altering [sAdmission].[pRptAdmissionReceiptGet]...';


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


GO

 
ALTER PROCEDURE [sAssessment].[pExamSettingGet]
	 @rExamId int,
	 @rClassId int,
	 @rExamSettingTypeId int
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 	
DECLARE @lExamIds nvarchar(max)	
CREATE TABLE #AllExams
(
ExamIds int
)
INSERT INTO #AllExams
SELECT EM.Id FROM [sAssessment].[tExamMaster] EM 
		WHERE EM.Id =@rExamId  AND EM.CLassId = @rClassId


INSERT INTO #AllExams
SELECT EM.Id 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 =@rExamId  AND EM.CLassId = @rClassId


INSERT INTO #AllExams
SELECT EM.Id 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

		--SELECT * FROM #AllExams

SELECT @lExamIds = STUFF((SELECT ','+ CONVERT(varchar,ExamIds)
                FROM #AllExams
              -- WHERE t.prodtype = 'XYZ'
             FOR XML PATH('')), 1, 1, '')

--SELECT @lExamIds

IF(@rExamSettingTypeId = 1)
BEGIN
SELECT 


			EM.Id,
			EM.BatchId,
			ESGM.Code,
			ESGM.Title AS Name,
			ISNULL(IsProcessResult,0) AS IsProcessResult,
			ISNULL(IsNegativeMarks,0) AS IsNegativeMarks,
			ISNULL(IsLockForEdit,0) AS IsLockForEdit,
			ISNULL(IsPublished,0) AS IsPublished,
			ISNULL(IsPublishExamSchedule,0) As IsPublishExamSchedule

   FROM 
			sAssessment.tExamMaster EM
			INNER JOIN sAssessment.tExamSubGroupMaster	ESGM ON ESGM.Id = EM.ExamSubGroupId
			INNER JOIN sAssessment.tExamGroupMaster EGM ON EGM.Id=ESGM.ExamGroupId
			INNER JOIN sSetup.tClassMaster CM on CM.Id=EM.ClassId
   WHERE      
			(ISNULL(EM.Id,0) IN( SELECT cast(item as nvarchar(500)) FROM  sCommon.fnsplit(@lExamIds,',')) OR @lExamIds='') 
            AND EM.ClassId=@rClassId
			order by ESGM.Title
END

ELSE IF(@rExamSettingTypeId = 2)		 
BEGIN
	SELECT 
			EM.Id,
			EM.BatchId,
			ESGM.Code,
			ESGM.Title AS Name,
			EM.IsGrade,
			EM.IsPercentile,
			EM.IsRankNo,
			ISNULL(EM.IsGenerateRankNo,0)As IsGenerateRankNo,
			ISNULL(EM.IsPercentage,0) AS IsPercentage,
			ISNULL(Em.IsRemovePercentageForFail,0) AS IsFailPercentageZero,
			ISNULL(EM.IsSubjectPercentile,0) AS IsSubjectPercentile,
			ISNULL(IsResultStatus,0) AS IsDisplayResultStatus,
			ISNULL(IsAllExamPassRequired,0) As IsAllExamPassRequired,
			ISNULL(IsExcludeAbsentTotal,0) AS IsExcludeAbsentTotal


   FROM 
			sAssessment.tExamMaster EM
			INNER JOIN sAssessment.tExamSubGroupMaster	ESGM ON ESGM.Id = EM.ExamSubGroupId
			INNER JOIN sAssessment.tExamGroupMaster EGM ON EGM.Id=ESGM.ExamGroupId
			INNER JOIN sSetup.tClassMaster CM on CM.Id=EM.ClassId
			--INNER Join sSetup.tClassSubject CS ON EM.ClassId=CS.ClassId				
			--INNER JOIN sSetup.tSubjectMaster SM on   CS.SubjectId=SM.Id					
			--LEFT JOIN sAssessment.tExamDetail ED ON ED.ClassSubjectId = CS.Id AND ED.ExamId=EM.Id
			--LEFT Join sAssessment.tGradeSetMaster GSM ON GSM.Id = ED.GradeSetId
  WHERE      
			(ISNULL(EM.Id,0) IN( SELECT cast(item as nvarchar(500)) FROM  sCommon.fnsplit(@lExamIds,',')) OR @lExamIds='') 
            AND EM.ClassId=@rClassId
			order by ESGM.Title

END
ELSE IF(@rExamSettingTypeId = 3)		 
BEGIN
	SELECT 
			EM.Id,
			EM.BatchId,
			ESGM.Code,
			ESGM.Title AS Name,
			ISNULL(IsDisplayPhoto,0) AS IsDisplayPhoto,
			ISNULL(IsDisplaySchoolName,0) AS IsDisplaySchoolName,
			ISNULL(IsDisplayBirthDate,0) AS IsDisplayBirthDate,
			ISNULL(IsDisplayParentName,0) AS IsDisplayParentName,
			ISNULL(IsDisplayHeightWeight,0) AS IsDisplayHeightWeight,
			ISNULL(IsDisplayGradeString,0) AS IsDisplayGradeString,
			ISNULL(EM.IsDisplayTotalMark,0) AS IsDisplayTotalMark,
			ISNULL(EM.IsDisplayResultIndicator,0) AS IsDisplayResultIndicator,
			ISNULL(IsDisplayHighestDivisionMark,0) AS IsDisplayHighestDivisionMark,
			ISNULL(Convert(bit,IsDisplayHighestDivisionGrade),0) AS IsDisplayHighestDivisionGrade,
			ISNULL(IsDisplayTeacherSign,0) AS IsDisplayTeacherSign,
			ISNULL(IsDisplayPrincipalSign,0) AS IsDisplayPrincipalSign,
			ISNULL(IsDisplayActivityGrade,0) AS IsDisplayActivityGrade
			
   FROM 
			sAssessment.tExamMaster EM
			INNER JOIN sAssessment.tExamSubGroupMaster	ESGM ON ESGM.Id = EM.ExamSubGroupId
			INNER JOIN sAssessment.tExamGroupMaster EGM ON EGM.Id=ESGM.ExamGroupId
			INNER JOIN sSetup.tClassMaster CM on CM.Id=EM.ClassId
			--INNER Join sSetup.tClassSubject CS ON EM.ClassId=CS.ClassId				
			--INNER JOIN sSetup.tSubjectMaster SM on   CS.SubjectId=SM.Id					
			--LEFT JOIN sAssessment.tExamDetail ED ON ED.ClassSubjectId = CS.Id AND ED.ExamId=EM.Id
			--LEFT Join sAssessment.tGradeSetMaster GSM ON GSM.Id = ED.GradeSetId
   WHERE      
			(ISNULL(EM.Id,0) IN( SELECT cast(item as nvarchar(500)) FROM  sCommon.fnsplit(@lExamIds,',')) OR @lExamIds='') 
            AND EM.ClassId=@rClassId
			order by ESGM.Title

END
ELSE
BEGIN
SELECT 
			EM.Id,
			EM.BatchId,
			ESGM.Code,
			ESGM.Title AS Name,
			ISNULL(IsIncludeCoScholastic,0) AS IsIncludeCoScholastic,
			ISNULL(IsCoScholasticGradeIndicator,0) AS IsCoScholasticGradeIndicator,
			ISNULL(IsCoScholasticGradeDesIndicator,0) AS IsCoScholasticGradeDesIndicator,
			ISNULL(IsCoScholasticGrade,0) AS IsCoScholasticGrade
   FROM 
			sAssessment.tExamMaster EM
			INNER JOIN sAssessment.tExamSubGroupMaster	ESGM ON ESGM.Id = EM.ExamSubGroupId
			INNER JOIN sAssessment.tExamGroupMaster EGM ON EGM.Id=ESGM.ExamGroupId
			INNER JOIN sSetup.tClassMaster CM on CM.Id=EM.ClassId
			--INNER Join sSetup.tClassSubject CS ON EM.ClassId=CS.ClassId				
			--INNER JOIN sSetup.tSubjectMaster SM on   CS.SubjectId=SM.Id					
			--LEFT JOIN sAssessment.tExamDetail ED ON ED.ClassSubjectId = CS.Id AND ED.ExamId=EM.Id
			--LEFT Join sAssessment.tGradeSetMaster GSM ON GSM.Id = ED.GradeSetId
   WHERE      
			(ISNULL(EM.Id,0) IN( SELECT cast(item as nvarchar(500)) FROM  sCommon.fnsplit(@lExamIds,',')) OR @lExamIds='') 
            AND EM.ClassId=@rClassId
			order by ESGM.Title
END

DROP TABLE #AllExams
		
END
GO
PRINT N'Altering [sAttendance].[pAttenanceRegisterGet]...';


GO
ALTER PROCEDURE [sAttendance].[pAttenanceRegisterGet]
     @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 @rAttendanceTypeId smallint,
	 @rOrgId int,
	 @rForMonth smallint,
	 @rForYear smallint,
	 @rClassId int=0,
	 @rDivisionId int=0,
	 @rBatchId int = 0,
	 @rStudentCode nvarchar(20)='',
	 @rDepartmentId int = 0,
	 @rAcademicId bigint = 0,
	 @PageIndex int=0,
	 @rStatus int=0,
	 @rFromStudentCode nvarchar(20)='',
	 @rToStudentCode nvarchar(20)=''
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

--Select * from sAttendance.tTempAttendance

DECLARE @lFirstDate Date
	DECLARE @lResult nvarchar(max)
	DECLARE @li int 
	SET @li=1
	SET @lFirstDate = CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'/'+CONVERT(NVARCHAR(2),@rForMonth)+'/01'))	
	
	
DECLARE @lOrgId  int
--DECLARE @lSchoolRemark1  nvarchar(500)
--DECLARE @lSchoolRemark2  nvarchar(500)
--DECLARE @lSchoolRemark3  nvarchar(500)
DECLARE @lSchoolRequiredSignature  nvarchar(500)

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=1 where RGM.Id=1
 
-- select @lSchoolRequiredSignature as sig
 	Declare @Days int 
 	select @Days=sCommon.fGetDaysInMonth(@rForMonth,@rForYear)
BEGIN 
	 CREATE Table #AttendanceRegistertempTable
(
	TID int identity(1,1),
	ClassDivisionTitle Nvarchar(500),
	Code nvarchar(500),
	RollNo int,
	AcademicId bigint,
	Name nvarchar(500),
	AttendanceTypeId int,
	ForYear int,
	ForMonth int,
	ForMonthInWord nvarchar(500),
	ClassId int,
	DivisionId int,
	ClassName nvarchar(500),
	DivisionName nvarchar(500),
	IsPresent bit,
	DayPart int,
	LeftDate date,
	ClassOrderIndex int,
	DivisionOrderIndex int,
	FooterSignature nvarchar(500),
	StatusId int,
	AttendanceDate date,
	AttendanceTagId int ,
	EmployeeName nvarchar(500),
	DateOfBirth date,
	Religion nvarchar(500),
	MotherName nvarchar(500),
	FamilyCast nvarchar(100),
	Gender tinyint,
	CastCategory nvarchar(50)

)
Insert INTO #AttendanceRegistertempTable
(	
	ClassDivisionTitle,
	Code ,
	RollNo,
	AcademicId,
	Name,
	AttendanceTypeId,
	ForYear,
	ForMonth,
	ForMonthInWord,
	ClassId,
	DivisionId,
	ClassName,
	DivisionName,
	IsPresent,
	DayPart,
	LeftDate,
	ClassOrderIndex,
	DivisionOrderIndex,
	FooterSignature,
	StatusId,
	AttendanceDate,
	AttendanceTagId,
	EmployeeName,
	DateOfBirth,
	Religion,
	MotherName,
	FamilyCast,
	Gender,
	CastCategory
)
Select	    
	ISNULL(SA.ClassName + '-' + SA.DivisionName,'') AS ClassDivisionTitle,
	SA.Code,
	SA.RollNo,
	SA.AcademicId,
	SA.Name,
	SR.AttendanceTypeId ,
	YEAR(SR.AttendanceDate) AS ForYear,
	MONTH(SR.AttendanceDate) AS ForMonth,
	DATENAME(month, SR.AttendanceDate) AS ForMonthInWord,
	SA.ClassId,
	SA.DivisionId,
	SA.ClassName,Sa.DivisionName,
  
	--(CASE SR.IsPresent WHEN 1 THEN 'P' 
	--	WHEN 0 THEN 'A'
	--ELSE  ' ' END )AS  IsPresent,		
	SR.IsPresent,
	 day(SR.AttendanceDate) AS DayPart,
	 
	 A.LeftDate,
	 CM.OrderIndex AS ClassOrderIndex,
	 DM.OrderIndex As DivisionOrderIndex,
	@lSchoolRequiredSignature AS FooterSignature,
	 SA.StatusId,
	 SR.AttendanceDate As AttendanceDate,
	 SR.AttendanceTagId,
	 EM.FirstName+' ' + EM.LastName AS EmployeeName,
	 SO.DateOfBirth,
	 RE.Title As Religion,
	 Sf.MotherName,
	 SO.FamilyCast,
	 --,
	 --SR.IsPresent
	 SO.GenderId,
	 ISNULL(CCM.Title,'') AS CastCategory
	 
    from
            sStudent.vStudentAcademic SA 
            INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=SA.AcademicId 
            INNER JOIN sStudent.tStudentAdmission A ON SA.StudentId = A.StudentId
            INNER JOIN sSetup.tClassMaster CM ON CM.Id = SA.ClassId
            INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = CM.OrgId
            INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=SA.DivisionId
            LEFT JOIN sHrm.tEmployeeMaster EM ON EM.Id = DM.InchargeEmployeeId 
            INNER JOIN sStudent.tStudentOther SO ON SO.StudentId=SA.StudentId
			LEFT JOIN  sStudent.tStudentFamily SF ON Sf.StudentId=Sa.StudentID
            LEFT JOIN sCommon.tReligionMaster RE On RE.Id=SO.ReligionId
			LEFT JOIN sCommon.tCastCategoryMaster CCM ON CCM.Id=SO.CastCategoryId
            
             WHERE  
	        ((SR.AttendanceTypeId=@rAttendanceTypeId) OR (@rAttendanceTypeId= 0))
	         AND ((SA.OrgId=@rOrgId) OR (@rOrgId= 0))
	          AND ((SA.BatchId=@rBatchId) OR (@rBatchId= 0))
	          AND ((YEAR(SR.AttendanceDate)=@rForYear) OR (@rForYear= 0))
	          AND ((MONTH(SR.AttendanceDate)=@rForMonth) OR (@rForMonth= 0))
	           AND ((SA.ClassId=@rClassId) OR (@rClassId= 0))
	           AND ((SA.Code=@rStudentCode) OR (@rStudentCode=''))
	           AND ((SA.AcademicId=@rAcademicId) OR (@rAcademicId=0))	           
				AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
	           AND ((SA.DivisionId=@rDivisionId) OR (@rDivisionId= 0))
	           AND ((SA.StatusId=@rStatus)OR (@rStatus=0))
	           AND ((SA.Code >= @rFromStudentCode) OR (ISNULL(@rFromStudentCode,'')=''))
	           AND ((SA.Code <= @rToStudentCode) OR (ISNULL(@rToStudentCode,'')=''))
	           AND  ISNULL(EM.IsOtherUser,0) = 0 
				
CREATE TABLE #TempDaysTempTable
(
 DayPart int,
 Value nvarchar(20)
 )
WHILE @li<=@Days
BEGIN
INSERT INTO #TempDaysTempTable
(
	DayPart ,
   Value
)

SELECT 
@li AS DayPart,
 [sAttendance].[fWeekHOffGet](@rForYear,@rForMonth,@li,@rBatchId,@rClassId,@rDivisionId,'',@rOrgId) 
SET @li = @li + 1
END

 

SELECT  
			@lFirstDate AS LastDate,
			LeftDate,
            @rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			PivotTable.AcademicId,
			ClassDivisionTitle,isnull(Code,'') as Code,isnull(RollNo,0) as RollNo,
			isnull(Name,'') as Name,isnull(AttendanceTypeId,0) as AttendanceTypeId,ForYear,
			ForMonth,ClassId,ClassName,DivisionId,
			DivisionName,
			ForMonthInWord,
			(ISNULL(TC.TCount,0) - ISNULL(AC.ACount,0)) AS PresentCount,
			ISNULL(ABU.AUCount,0) AS AbsentUpto,
			ISNULL(TC.TCount,0) AS AttendanceCount,
		    ISNULL(AC.ACount,0) As  AbsentCount,
		    ISNULL(PC.PCount,0) As  PresentUpto,	    
		    
		    ClassOrderIndex,
		    DivisionOrderIndex,
		    FooterSignature,
			(ISNULL(TotalPresent,0) + ISNULL(TC.TCount,0)) AS TotalPresent,
			 
			  [sAttendance].[fWeekHOffGet](@rForYear ,@rForMonth ,1 ,@rBatchId ,@rClassId,@rDivisionId , isnull([1],''),@rOrgId )  AS P1,
			[sAttendance].[fWeekHOffGet](@rForYear ,@rForMonth ,2 ,@rBatchId ,@rClassId,@rDivisionId , isnull([2],''),@rOrgId )  AS P2,
			[sAttendance].[fWeekHOffGet](@rForYear ,@rForMonth ,3 ,@rBatchId ,@rClassId,@rDivisionId , isnull([3],''),@rOrgId )  AS P3,
			[sAttendance].[fWeekHOffGet](@rForYear ,@rForMonth ,4 ,@rBatchId ,@rClassId,@rDivisionId , isnull([4],''),@rOrgId )  AS P4,
			[sAttendance].[fWeekHOffGet](@rForYear ,@rForMonth ,5 ,@rBatchId ,@rClassId,@rDivisionId , isnull([5],''),@rOrgId )  AS P5,
			[sAttendance].[fWeekHOffGet](@rForYear ,@rForMonth ,6 ,@rBatchId ,@rClassId,@rDivisionId , isnull([6],''),@rOrgId ) AS P6,
			[sAttendance].[fWeekHOffGet](@rForYear ,@rForMonth ,7 ,@rBatchId ,@rClassId,@rDivisionId , isnull([7],''),@rOrgId ) AS P7,
			[sAttendance].[fWeekHOffGet](@rForYear ,@rForMonth ,8 ,@rBatchId ,@rClassId,@rDivisionId , isnull([8],''),@rOrgId ) AS P8,
			[sAttendance].[fWeekHOffGet](@rForYear ,@rForMonth ,9 ,@rBatchId ,@rClassId,@rDivisionId , isnull([9],''),@rOrgId ) AS P9,
			[sAttendance].[fWeekHOffGet](@rForYear ,@rForMonth ,10 ,@rBatchId ,@rClassId,@rDivisionId , isnull([10],''),@rOrgId ) AS P10,
			[sAttendance].[fWeekHOffGet](@rForYear ,@rForMonth ,11 ,@rBatchId ,@rClassId,@rDivisionId , isnull([11],''),@rOrgId ) AS P11,
			[sAttendance].[fWeekHOffGet](@rForYear ,@rForMonth ,12 ,@rBatchId ,@rClassId,@rDivisionId , isnull([12],''),@rOrgId ) AS P12,
			[sAttendance].[fWeekHOffGet](@rForYear ,@rForMonth ,13 ,@rBatchId ,@rClassId,@rDivisionId , isnull([13],''),@rOrgId ) AS P13,
			[sAttendance].[fWeekHOffGet](@rForYear ,@rForMonth ,14 ,@rBatchId ,@rClassId,@rDivisionId , isnull([14],''),@rOrgId ) AS P14,
			[sAttendance].[fWeekHOffGet](@rForYear ,@rForMonth ,15 ,@rBatchId ,@rClassId,@rDivisionId , isnull([15],''),@rOrgId ) AS P15,
			[sAttendance].[fWeekHOffGet](@rForYear ,@rForMonth ,16 ,@rBatchId ,@rClassId,@rDivisionId , isnull([16],''),@rOrgId ) AS P16,
			[sAttendance].[fWeekHOffGet](@rForYear ,@rForMonth ,17 ,@rBatchId ,@rClassId,@rDivisionId , isnull([17],''),@rOrgId ) AS P17,
			[sAttendance].[fWeekHOffGet](@rForYear ,@rForMonth ,18 ,@rBatchId ,@rClassId,@rDivisionId , isnull([18],''),@rOrgId ) AS P18,
			[sAttendance].[fWeekHOffGet](@rForYear ,@rForMonth ,19 ,@rBatchId ,@rClassId,@rDivisionId , isnull([19],''),@rOrgId ) AS P19,
			[sAttendance].[fWeekHOffGet](@rForYear ,@rForMonth ,20 ,@rBatchId ,@rClassId,@rDivisionId , isnull([20],''),@rOrgId ) AS P20,
			[sAttendance].[fWeekHOffGet](@rForYear ,@rForMonth ,21 ,@rBatchId ,@rClassId,@rDivisionId , isnull([21],''),@rOrgId ) AS P21,
			[sAttendance].[fWeekHOffGet](@rForYear ,@rForMonth ,22 ,@rBatchId ,@rClassId,@rDivisionId , isnull([22],''),@rOrgId ) AS P22,
			[sAttendance].[fWeekHOffGet](@rForYear ,@rForMonth ,23 ,@rBatchId ,@rClassId,@rDivisionId , isnull([23],''),@rOrgId ) AS P23,
			[sAttendance].[fWeekHOffGet](@rForYear ,@rForMonth ,24 ,@rBatchId ,@rClassId,@rDivisionId , isnull([24],''),@rOrgId ) AS P24,
			[sAttendance].[fWeekHOffGet](@rForYear ,@rForMonth ,25 ,@rBatchId ,@rClassId,@rDivisionId , isnull([25],''),@rOrgId ) AS P25,
			[sAttendance].[fWeekHOffGet](@rForYear ,@rForMonth ,26 ,@rBatchId ,@rClassId,@rDivisionId , isnull([26],''),@rOrgId ) AS P26,
			[sAttendance].[fWeekHOffGet](@rForYear ,@rForMonth ,27 ,@rBatchId ,@rClassId,@rDivisionId , isnull([27],''),@rOrgId ) AS P27,
			[sAttendance].[fWeekHOffGet](@rForYear ,@rForMonth ,28 ,@rBatchId ,@rClassId,@rDivisionId , isnull([28],''),@rOrgId ) AS P28,
			CASE WHEN @Days>=29 THEN  [sAttendance].[fWeekHOffGet](@rForYear ,@rForMonth ,29 ,@rBatchId,@rClassId ,@rDivisionId , isnull([29],''),@rOrgId ) end AS P29,
			CASE WHEN @Days>=30 THEN [sAttendance].[fWeekHOffGet](@rForYear ,@rForMonth ,30 ,@rBatchId ,@rClassId,@rDivisionId , isnull([30],''),@rOrgId ) end AS P30,
			CASE WHEN @Days>=31 THEN [sAttendance].[fWeekHOffGet](@rForYear ,@rForMonth ,31 ,@rBatchId ,@rClassId,@rDivisionId , isnull([31],''),@rOrgId )  end AS P31,
			
	 	--	 isnull([1],'') AS P1,
			--isnull([2],'') AS P2,
			--isnull([3],'') AS P3,
			--isnull([4],'') AS P4,
			--isnull([5],'') AS P5,
			--isnull([6],'') AS P6,
			--isnull([7],'') AS P7,
			--isnull([8],'') AS P8,
			--isnull([9],'') AS P9,
			--isnull([10],'') AS P10,
			--isnull([11],'') AS P11,
			--isnull([12],'') AS P12,
			--isnull([13],'') AS P13,
			--isnull([14],'') AS P14,
			--isnull([15],'') AS P15,
			--isnull([16],'') AS P16,
			--isnull([17],'') AS P17,
			--isnull([18],'') AS P18,
			--isnull([19],'') AS P19,
			--isnull([20],'') AS P20,
			--isnull([21],'') AS P21,
			--isnull([22],'') AS P22,
			--isnull([23],'') AS P23,
			--isnull([24],'') AS P24,
			--isnull([25],'') AS P25,
			--isnull([26],'') AS P26,
			--isnull([27],'') AS P27,
			--isnull([28],'') AS P28,
			--isnull([29],'') AS P29,
			--isnull([30],'') AS P30,
			--isnull([31],'') AS P31, 
			 EmployeeName ,
 
             sCommon.fGetDaysInMonth ( @rForMonth,@rForYear) AS DaysInMonth,
              DateOfBirth,Religion,MotherName,FamilyCast,Gender,
			  CastCategory
--,
--AttendanceTagId

 
FROM
(
	Select --TID, 
		ISNULL(ClassName + '-' + DivisionName,'') AS ClassDivisionTitle,
		Code,
		RollNo,
		AcademicId,
		Name,
		AttendanceTypeId ,
		YEAR(ST.AttendanceDate) AS ForYear,
		MONTH(ST.AttendanceDate) AS ForMonth,
		DATENAME(month, ST.AttendanceDate) AS ForMonthInWord,
		ClassId,
		DivisionId,
		ClassName,
		DivisionName,
		(
			CASE  WHEN IsPresent = 1 AND ST.AttendanceTagId = 1 THEN 'LC' 
				  WHEN IsPresent = 1 AND ST.AttendanceTagId = 2 THEN 'EL' 
				  WHEN IsPresent = 1 AND ST.AttendanceTagId = 3 THEN 'N' 
				  WHEN IsPresent = 1 AND ST.AttendanceTagId = 4 THEN 'G' 
			      WHEN IsPresent = 1  THEN 'P' 
				  WHEN IsPresent = 0 THEN 'A'
				  ELSE  DT.Value END 
		)AS  IsPresent,		
		day(ST.AttendanceDate) AS DayPart,
		LeftDate
		,
		ClassOrderIndex,
		DivisionOrderIndex,
		FooterSignature,EmployeeName,
		DateOfBirth,Religion,MotherName,FamilyCast,Gender,
		CastCategory
      -- DO NOT ADD ANY FIELD HERE WITHOUT PERMISSION OF RAJENDRA
	 FROM 
		#AttendanceRegistertempTable ST 
		INNER JOIN #TempDaysTempTable DT ON DT.DayPart = ST.DayPart
	 WHERE
		((LeftDate >= @lFirstDate) OR ISNULL(LeftDate,'') = '')
) AS SourceTable 
 
	           
	        
PIVOT
(	
MIN(IsPresent)
FOR DayPart IN ([0], [1], [2], [3], [4],[5],[6],[7],[8],[9],[10],[11],[12],[13],[14],[15],[16],[17],[18],[19],[20],[21],[22],[23],[24],[25],[26],[27],[28],[29],[30],[31])
) AS PivotTable
	LEFT JOIN
	(
		Select  AcademicId AS AcademicId, COUNT(1) AS TCount 
		   FROM  
				#AttendanceRegistertempTable
		    
			GROUP BY  AcademicId
    ) TC ON TC.AcademicId = PivotTable.AcademicId
    
	LEFT JOIN
	(
		Select AcademicId AS AcademicId, COUNT(1) AS ACount 
		   FROM  #AttendanceRegistertempTable
		    WHERE   IsPresent = 0	 		
            
			GROUP BY  AcademicId
    ) AC ON AC.AcademicId = PivotTable.AcademicId
	LEFT JOIN
	(SELECT A.Id AS AcademicId, COUNT(1) AS PCount  FROM sAttendance.tStudentRegister SR 
			INNER JOIN sStudent.tAcademic A ON SR.AcademicId = A.Id 
		   INNER JOIN sStudent.tStudentMaster SA ON A.StudentId = SA.Id
		   INNER JOIN sSetup.tClassMaster CM ON A.ClassId = CM.Id
			WHERE  
			 SR.AttendanceDate < (convert(date,CONVERT(nvarchar(10), @rForYear)+ '/' +  CONVERT(nvarchar(10), @rForMonth) + '/' + '01' ))
			AND SR.IsPresent = 1	    		
            --AND (SA.StatusId = 1)
	        AND ((SR.AttendanceTypeId=@rAttendanceTypeId) OR (@rAttendanceTypeId= 0))
	        AND ((SA.OrgId=@rOrgId) OR (@rOrgId= 0))
	        AND ((A.BatchId=@rBatchId) OR (@rBatchId= 0))	          
	        AND ((A.ClassId=@rClassId) OR (@rClassId= 0))
	        AND ((SA.Code=@rStudentCode) OR (@rStudentCode=''))
	        AND ((A.Id=@rAcademicId) OR (@rAcademicId=0))	           
			AND ((CM.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))				
	        AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId= 0))
	        AND ((SA.Code>=@rFromStudentCode) OR (ISNULL(@rFromStudentCode,'')=''))
	        AND ((SA.Code<=@rToStudentCode) OR (ISNULL(@rToStudentCode,'')=''))

			GROUP BY A.Id
    ) PC ON PC.AcademicId = PivotTable.AcademicId
		LEFT JOIN
	(SELECT A.Id AS AcademicId, COUNT(1) AS AUCount  FROM sAttendance.tStudentRegister SR 
			INNER JOIN sStudent.tAcademic A ON SR.AcademicId = A.Id 
		   INNER JOIN sStudent.tStudentMaster SA ON A.StudentId = SA.Id
		   INNER JOIN sSetup.tClassMaster CM ON A.ClassId = CM.Id
			WHERE  
			 SR.AttendanceDate < (convert(date,CONVERT(nvarchar(10), @rForYear)+ '/' +  CONVERT(nvarchar(10), @rForMonth) + '/' + '01' ))
			AND SR.IsPresent = 0	    		
            --AND (SA.StatusId = 1)
	        AND ((SR.AttendanceTypeId=@rAttendanceTypeId) OR (@rAttendanceTypeId= 0))
	        AND ((SA.OrgId=@rOrgId) OR (@rOrgId= 0))
	        AND ((A.BatchId=@rBatchId) OR (@rBatchId= 0))	          
	        AND ((A.ClassId=@rClassId) OR (@rClassId= 0))
	        AND ((SA.Code=@rStudentCode) OR (@rStudentCode=''))
	        AND ((A.Id=@rAcademicId) OR (@rAcademicId=0))	           
			AND ((CM.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))				
	        AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId= 0))
	        AND ((SA.Code>=@rFromStudentCode) OR (ISNULL(@rFromStudentCode,'')=''))
	        AND ((SA.Code<=@rToStudentCode) OR (ISNULL(@rToStudentCode,'')=''))

			GROUP BY A.Id
    ) ABU ON ABU.AcademicId = PivotTable.AcademicId
	LEFT JOIN
	(SELECT A.Id AS AcademicId, COUNT(1) AS TotalPresent  FROM sAttendance.tStudentRegister SR 
			INNER JOIN sStudent.tAcademic A ON SR.AcademicId = A.Id 
		   INNER JOIN sStudent.tStudentMaster SA ON A.StudentId = SA.Id
		   INNER JOIN sSetup.tClassMaster CM ON A.ClassId = CM.Id
			WHERE  
			SR.AttendanceDate < (convert(date,CONVERT(nvarchar(10), @rForYear)+ '/' +  CONVERT(nvarchar(10), @rForMonth) + '/' + '01' ))
	        AND
	        ((SR.AttendanceTypeId=@rAttendanceTypeId) OR (@rAttendanceTypeId= 0))
	        AND ((SA.OrgId=@rOrgId) OR (@rOrgId= 0))
	        AND ((A.BatchId=@rBatchId) OR (@rBatchId= 0))	          
	        AND ((A.ClassId=@rClassId) OR (@rClassId= 0))
	        AND ((SA.Code=@rStudentCode) OR (@rStudentCode=''))
	        AND ((A.Id=@rAcademicId) OR (@rAcademicId=0))	           
			AND ((CM.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))				
	        AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId= 0))
	        AND ((SA.Code>=@rFromStudentCode) OR (ISNULL(@rFromStudentCode,'')=''))
	        AND ((SA.Code<=@rToStudentCode) OR (ISNULL(@rToStudentCode,'')=''))

			GROUP BY A.Id
    ) AA ON AA.AcademicId = PivotTable.AcademicId
 
    ORDER BY RollNo;
 

select * from #TempDaysTempTable
 				
drop table #AttendanceRegistertempTable	  
drop table #TempDaysTempTable
	


	--SELECT  
	--		Convert(date,'') AS LastDate,
	--		Convert(date,'') AS LeftDate,
 --           '' AS Builder1,
	--		'' AS Builder2,
	--		Convert(bigint,0) AS AcademicId,
	--		'' AS ClassDivisionTitle,
	--		'' AS Code,
	--		0 as RollNo,
	--		'' AS Name,
	--		0 as AttendanceTypeId,
	--		0 as ForYear,
	--		0 as ForMonth,
	--		0 as ClassId,
	--		'' as ClassName,
	--		0 as DivisionId,
	--		'' as DivisionName,
	--		'' as ForMonthInWord,
	--		0 AS PresentCount,
	--		0 AS AbsentUpto,
	--		0 AS AttendanceCount,
	--	    0 As  AbsentCount,
	--	    0 As  PresentUpto,
	--	    0 as ClassOrderIndex,
	--	    0 as DivisionOrderIndex,
	--	    '' as FooterSignature,
	--		0 AS TotalPresent,
	--		'' AS P1,
	--		'' AS P2,
	--		'' AS P3,
	--		'' AS P4,
	--		'' AS P5,
	--		'' AS P6,
	--		'' AS P7,
	--		'' AS P8,
	--		'' AS P9,
	--		'' AS P10,
	--		'' AS P11,
	--		'' AS P12,
	--		'' AS P13,
	--		'' AS P14,
	--		'' AS P15,
	--		'' AS P16,
	--		'' AS P17,
	--		'' AS P18,
	--		'' AS P19,
	--		'' AS P20,
	--		'' AS P21,
	--		'' AS P22,
	--		'' AS P23,
	--		'' AS P24,
	--		'' AS P25,
	--		'' AS P26,
	--		'' AS P27,
	--		'' AS P28,
	--		'' AS P29,
	--		'' AS P30,
	--		'' AS P31,
	--		'' as EmployeeName ,
 --           0 AS DaysInMonth,
	--		Convert(date,'') AS DateOfBirth,
	--		'' as Religion,
	--		'' as MotherName,
	--		'' as FamilyCast,
	--		0 as Gender,
	--		'' as CastCategory



	
END
GO
PRINT N'Altering [sBiometric].[pShiftMasterCloudGet]...';


GO

ALTER PROCEDURE [sBiometric].[pShiftMasterCloudGet]
@rShiftCode int = 0,
@rShiftName nvarchar(50) = '',
@rOrgGroupId int = 0

AS
BEGIN

	select [ShiftCode]
      ,[ShiftName]
      ,[StartTime]
      ,[EndTime]
      ,[GraceBefore]
      ,[GraceAfter]
      ,[ShiftDur]
      ,[MinHrsHalfDay]
      ,[MinHrsFullDay]
      ,[RecessDur]
      ,[AlterGraceTime]
      ,[SMSScheduleTime]
      ,[ShiftGroupCode]
      ,[IsOutTimeAlertTime]
      ,[OutTimeAlertTime]
      ,[OrgGroupId]
      ,isnull([LastOutAlertBasedOnId],1) as LastOutAlertBasedOnId
	   from sBiometric.tShiftMasterCloud
	where 
	((ShiftCode = @rShiftCode) OR (@rShiftCode=0))     
	AND ((ShiftName = @rShiftName) OR (@rShiftName=''))     
	AND ((OrgGroupId = @rOrgGroupId) OR (@rOrgGroupId=0))     
END
GO
PRINT N'Altering [sCertificate].[pRptCharacterCertificateGet]...';


GO
ALTER PROCEDURE [sCertificate].[pRptCharacterCertificateGet]
	 
	 @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)=''
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
DECLARE @lIsOnPrePrinted bit = 0

DECLARE @lConfigValue nvarchar(50)

DECLARE @lIsDisplayImageHeader bit=0
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 = 180 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 = 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,
			C.Id,
			C.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,
			CM.DisplayTitle AS ClassOnly,
			BM.Title AS Batch,
			SO.DateOfBirth,
			ISNULL(SO.BirthDateInWord,'') AS DOBInWords,
			ISNULL(SO.BirthPlace,'') AS BirthPlace,
			ISNULL(SO.BirthTaluka,'') AS Taluka,
			ISNULL(SO.BirthDistrict,'')	AS District,		
			C.characterDate,
			C.Number,
			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 OrgName,
			OM.StateName+' '+OM.StreetTwo+' '+OM.StreetThree AS OrgAddress,
			OM.PhoneNo,
			SM.StatusId,
			A.RollNo,
			DM.OrderIndex AS DivisionOrder,
			OM.ReportOrgTitle,
			OM.SmallAddress1,
			OM.SmallAddress2,
			OM.RegistrationDetail,
			@lIsOnPrePrinted AS IsOnPrePrinted,
			@lIsDisplayImageHeader AS IsDisplayImageHeader,
			--OI.CertificateHeaderA4  ,
			SA.AdmissionDate,
			SF.FatherName,
			SF.MotherName,
			@lIDConfigValue AS ItemValue,
			OI.CertificateHeaderA4Portrait AS CertificateHeaderA4,
			A.Id,
			SA.LeftDate AS LCDate,
			C.Remark AS Remark,
			ISNULL(EI.EmployeeSign,0x) AS EmployeeSign,
			ISNULL(OM.PrincipalSignature,0x) AS PrincipalSignature,
			SM.FirstName,
			SM.LastName,
			SM.MiddleName,
			SM.SUId As SUID,
			DM.DisplayTitle AS DivisionOnly   --add by dhruvik
	FROM 
			sCertificate.tCharacter C
			INNER JOIN sStudent.tAcademic A ON C.AcademicId=A.Id
			LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId=A.StudentId
			INNER JOIN sStudent.tStudentMaster SM ON SM.Id=A.StudentId
			INNER JOIN sStudent.tStudentOther SO ON SO.StudentId=A.StudentId
			INNER JOIN sSetup.tDivisionMaster DM ON A.DivisionId = DM.Id  
			INNER JOIN sSetup.tClassMaster CM ON CM.Id= DM.ClassId
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id=A.BatchId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=A.OrgId
			LEFT JOIN sSetup.tOrgImages OI ON OI.OrgId = OM.Id
			LEFT JOIN sStudent.tStudentAdmission SA ON SA.StudentId=A.StudentId
			LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId=A.StudentId
			LEFT JOIN sHrm.tEmployeeImages EI ON EI.EmployeeId = DM.InchargeEmployeeId
	WHERE  
			A.OrgId=@rOrgId
		AND	A.BatchId = @rBatchId 
		AND ((A.ClassId=@rClassId) OR (@rClassId=0))
		AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		AND ((SM.Code = @rCode) OR (ISNULL(@rCode,'') = ''))
		AND ((SM.FirstName = @rName) OR (ISNULL(@rName,'') = ''))
		AND ((C.Number=@rNumber) OR (@rNumber=''))
		AND ((C.Number >= @rFromNo) OR (@rFromNo=''))
		AND ((C.Number <= @rToNo) OR (@rToNo=''))
		AND ((C.characterDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
		AND ((C.characterDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
		--Group By C.AcademicId,C.Number,SM.Code,SM.FirstName,SM.LastName,SM.MiddleName,CM.DisplayTitle,BM.Title,SO.DateOfBirth,SO.BirthDateInWord,
		--SO.BirthPlace,SO.BirthTaluka,SO.BirthDistrict,C.characterDate,OM.CityName,OM.StateName,SO.FamilyCast,SO.FamilySubCast,SO.GenderId,SI.StudentPhoto,SM.StatusId,OM.OrgLogo,OM.Title,
		--OM.StreetOne,OM.StreetThree,OM.StreetTwo,OM.PhoneNo
	END
GO
PRINT N'Altering [sCommon].[pOrganizationSetupRemove]...';


GO
 
ALTER PROCEDURE [sCommon].[pOrganizationSetupRemove]
	 
	 @rOrgId bigint
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
  --  BEGIN TRY
	
	 --BEGIN TRANSACTION
	 
	 --EXEC sp_msforeachtable "ALTER TABLE ? NOCHECK CONSTRAINT all"
    
DELETE FROM sAccounting.tExpense WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sAccounting.tExpenseGroupMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sAccounting.tReimbursement WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sAccounting.tReimbursementDetail WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sAccounting.tReimbursementTypeMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sActivity.tActivity WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sActivity.tActivityParticipant WHERE CAST(LEFT(ActivityId, 4) AS INT) = @rOrgId
DELETE FROM sActivity.tAssignClub WHERE CAST(LEFT(ClubId, 4) AS INT) = @rOrgId
DELETE FROM sActivity.tEventAssign WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sActivity.tEventEnrollment WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sActivity.tEventSchedule WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sActivity.tHealthCheckup WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sActivity.tHealthCheckupAssign WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sActivity.tHealthCheckupDetail WHERE CAST(LEFT(HealthCheckupId, 4) AS INT) = @rOrgId
DELETE FROM sActivity.tHealthCheckupParameter WHERE CAST(LEFT(HealthCheckupId, 4) AS INT) = @rOrgId
DELETE FROM sActivity.tHealthCheckupStudent WHERE CAST(LEFT(HealthCheckupId, 4) AS INT) = @rOrgId
DELETE FROM sActivity.tHealthParameterGroupMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sActivity.tHealthParameterList WHERE CAST(LEFT(HealthParameterId, 4) AS INT) = @rOrgId
DELETE FROM sActivity.tHealthParameterMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sActivity.tHealthTrack WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sActivity.tHouseMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sActivity.tPlacement WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sActivity.tPlacementInvite WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sActivity.tStudentImmunizationStatus WHERE CAST(LEFT(ImmunizationChartId, 4) AS INT) = @rOrgId
DELETE FROM sAdmission.tAdmissionForm WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sAdmission.tAdmissionFormIssue WHERE OrgId = @rOrgId
DELETE FROM sAdmission.tAdmissionInquiry WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sAlert.tAlertConfiguration WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sAlert.tAlertLog WHERE OrgId = @rOrgId
DELETE FROM sAlert.tAlertQueue WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sAlert.tAlertQueueDetail WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sAlert.tCustomTemplateMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sAlert.tDepartmentRecipient WHERE CAST(LEFT(DepartmentId, 4) AS INT) = @rOrgId
DELETE FROM sAlert.tEmailConfiguration WHERE CAST(LEFT(OrgId, 4) AS SMALLINT) = @rOrgId
DELETE FROM sAlert.tEventTemplate WHERE CAST(LEFT(OrgId, 4) AS SMALLINT) = @rOrgId
DELETE FROM sAlert.tExternalRecipientMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sAlert.tSMSConfiguration WHERE CAST(LEFT(OrgId, 4) AS SMALLINT) = @rOrgId
DELETE FROM sAlert.tTemplateMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sAssessment.tCCECSClass WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sAssessment.tCCECSGroupMaster WHERE OrgId = @rOrgId
DELETE FROM sAssessment.tCCECSIndicatorGrade WHERE CAST(LEFT(CCECSId, 4) AS INT) = @rOrgId
DELETE FROM sAssessment.tCCECSIndicatorMaster WHERE OrgId = @rOrgId
DELETE FROM sAssessment.tCCECSMaster WHERE OrgId = @rOrgId
DELETE FROM sAssessment.tCCECSScore WHERE CAST(LEFT(CCECSId, 4) AS INT) = @rOrgId
DELETE FROM sAssessment.tCCEExamMapping WHERE CAST(LEFT(BatchId, 4) AS INT) = @rOrgId
DELETE FROM sAssessment.tCCEExamSetting WHERE CAST(LEFT(ClassId, 4) AS INT) = @rOrgId
DELETE FROM sAssessment.tCCEFAGroupMaster WHERE OrgId = @rOrgId
DELETE FROM sAssessment.tCCEFAIndicatorMaster WHERE OrgId = @rOrgId
DELETE FROM sAssessment.tCCEFAMaster WHERE OrgId = @rOrgId
DELETE FROM sAssessment.tCCEFAScore WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sAssessment.tCCEFASubject WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sAssessment.tCCEResult WHERE AcademicId = @rOrgId
DELETE FROM sAssessment.tCCEResultDetail WHERE AcademicId = @rOrgId
DELETE FROM sAssessment.tExamCombine WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sAssessment.tExamDetail WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sAssessment.tExamGroupMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sAssessment.tExamMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sAssessment.tExamStatus WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sAssessment.tExamsubgroupmaster WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sAssessment.tGeneralExamCustomSearch WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sAssessment.tGradeSetDetail WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sAssessment.tGradeSetMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sAssessment.tLevelSetDetail WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sAssessment.tLevelSetMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sAssessment.tOptionalSubject WHERE CAST(LEFT(AcademicId, 4) AS BIGINT) = @rOrgId
DELETE FROM sAssessment.tRankSetDetail WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sAssessment.tRankSetMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sAssessment.tResult WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sAssessment.tResultDetail WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sAssetManagement.tAssetAdjustment WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sAssetManagement.tAssetAdjustmentDetail WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sAssetManagement.tAssetAudit WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sAssetManagement.tAssetAuditDetail WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sAssetManagement.tAssetMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sAssetManagement.tDepartmentLocation WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sAssetManagement.tMaintenence WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sAssetManagement.tMovement WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sAssetManagement.tMovementDetail WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sAssetManagement.tRecordManualEvent WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sAttendance.tApplicableAttendanceType WHERE OrgId = @rOrgId
DELETE FROM sAttendance.tMonthlyRegister WHERE CAST(LEFT(AcademicId, 4) AS BIGINT) = @rOrgId
DELETE FROM sAttendance.tMonthlySetup WHERE CAST(LEFT(ClassId, 4) AS INT) = @rOrgId
DELETE FROM sAttendance.tStudentRegister WHERE CAST(LEFT(AcademicId, 4) AS BIGINT) = @rOrgId
DELETE FROM sAttendance.tStudentSetup WHERE CAST(LEFT(AcademicId, 4) AS BIGINT) = @rOrgId
DELETE FROM sAttendance.tSubjectBatch WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sAttendance.tSubjectBatchStudent WHERE CAST(LEFT(AcademicId, 4) AS BIGINT) = @rOrgId
DELETE FROM sAudit.tAudit WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sAudit.tAuditLog WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sAudit.tAuditLogTransaction WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sAudit.tAuditTable WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sAudit.tAuditTableField WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sAudit.tAuditTransaction WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sBi.tAction WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sBi.tActionStatusMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sBi.tActionTypeMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sBi.tAudit WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sBi.tAuditLocation WHERE CAST(LEFT(AuditId, 4) AS BIGINT) = @rOrgId
DELETE FROM sBi.tAuditReasonMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sBi.tAuditStatusMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sBi.tAuditTypeMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sBi.tDocument WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sBi.tDocumentTypeMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sBi.tFinding WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sBi.tFindingTypeMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sBi.tInspection WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sBi.tQuestionAnswerMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sBi.tQuestionAnswerTypeMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sBi.tQuestionMainGroupMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sBi.tQuestionMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sBi.tQuestionnairesMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sBi.tQuestionResponse WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sBi.tQuestionSubGroupMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sBi.tSeverityMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sBiometric.tPunchMaster WHERE CAST(LEFT(OrgId, 4) AS SMALLINT) = @rOrgId
DELETE FROM sCertificate.tBonafide WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sCertificate.tCharacter WHERE OrgId = @rOrgId
DELETE FROM sCertificate.tFirstTrial WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sCertificate.tLeaving WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sCommon.tAgeGroupMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sCommon.tClinicMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId


DELETE FROM sCommon.tDurationMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sCommon.tExceptions WHERE CAST(LEFT(OrgId, 4) AS SMALLINT) = @rOrgId
DELETE FROM sCommon.tFileUpload WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sCommon.tFirstAidMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sCommon.tFunctionMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sCommon.tLocationMaster WHERE OrgId = @rOrgId
DELETE FROM sCommon.tOrganizationDepartmentMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sCommon.tPrefixSetup WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sCommon.tPublicHolidayMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sCommon.tPublicHolidayTypeMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sCommon.tReasonMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sCommon.tReportFormatGroupOrg WHERE OrgId = @rOrgId
 
DELETE FROM sCommunication.tAssignment WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sCommunication.tAssignmentScope WHERE CAST(LEFT(AssignmentId, 4) AS BIGINT) = @rOrgId
DELETE FROM sCommunication.tAssignmentView WHERE CAST(LEFT(AssignmentId, 4) AS BIGINT) = @rOrgId
DELETE FROM sCommunication.tAssignTask WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sCommunication.tBehaviour WHERE CAST(LEFT(AcademicId, 4) AS BIGINT) = @rOrgId
DELETE FROM sCommunication.tDiscussion WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sCommunication.tDiscussionComment WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sCommunication.tDiscussionGroup WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sCommunication.tDiscussionGroupMember WHERE CAST(LEFT(DiscussionGroupId, 4) AS BIGINT) = @rOrgId
DELETE FROM sCommunication.tPhotoCategoryOrg WHERE OrgId = @rOrgId
DELETE FROM sCommunication.tQueryCategoryOrg WHERE OrgId = @rOrgId
DELETE FROM sCommunication.tUploadBookLog WHERE CAST(LEFT(BookLogId, 4) AS BIGINT) = @rOrgId
DELETE FROM sCommunication.tUploadResult WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sConfig.tColorLegendDetail WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sConfig.tConfigurationSetup WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId AND SourceTypeId <> 2010
DELETE FROM sConfig.tCultureConfiguration WHERE OrgId = @rOrgId
DELETE FROM sConfig.tImport WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sConfig.tLocalDeviceSetting WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sConfig.tMachineMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sConfig.tMachinePrinterMapping WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sConfig.tPrinterMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sEExam.tTestAssign WHERE CAST(LEFT(TestId, 4) AS int) = @rOrgId
DELETE FROM sEExam.tTestMaster WHERE OrgId = @rOrgId
DELETE FROM sEExam.tTestParticipant WHERE CAST(LEFT(TestId, 4) AS BIGINT) = @rOrgId
DELETE FROM sEExam.tTestParticipantAnswer WHERE CAST(LEFT(TestId, 4) AS INT) = @rOrgId
DELETE FROM sEExam.tTestQuestion WHERE CAST(LEFT(TestId, 4) AS INT) = @rOrgId
DELETE FROM sFee.tChargeReceipt WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sFee.tChargeReceiptDetail WHERE CAST(LEFT(ChargeReceiptId, 4) AS BIGINT) = @rOrgId
DELETE FROM sFee.tFeeAllocation WHERE CAST(LEFT(SourceId, 4) AS BIGINT) = @rOrgId
DELETE FROM sFee.tFeeCustomSearch WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sFee.tFeeOptional WHERE CAST(LEFT(SourceId, 4) AS BIGINT) = @rOrgId
DELETE FROM sFee.tFeeSetup WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sFee.tReceipt WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sFee.tReceiptDetail WHERE CAST(LEFT(ReceiptId, 4) AS BIGINT) = @rOrgId
DELETE FROM sFixedAsset.tCategoryMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sFixedAsset.tLocationMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sFrontOffice.tVisitorLog WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sGSEB.tActivityIndicatorScore WHERE CAST(LEFT(ActivityId, 4) AS INT) = @rOrgId
DELETE FROM sGSEB.tAnusuchiB WHERE CAST(LEFT(AcademicId, 4) AS BIGINT) = @rOrgId
DELETE FROM sGSEB.tClassActivity WHERE CAST(LEFT(ActivityId, 4) AS INT) = @rOrgId
DELETE FROM sGSEB.tExamSetting WHERE CAST(LEFT(ClassId, 4) AS INT) = @rOrgId
DELETE FROM sGSEB.tGSEBExamMapping WHERE CAST(LEFT(BatchId, 4) AS INT) = @rOrgId
DELETE FROM sGSEB.tHetuMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sGSEB.tAnusuchiB WHERE CAST(LEFT(AcademicId, 4) AS BIGINT) = @rOrgId
DELETE FROM sGSEB.tResult WHERE CAST(LEFT(AcademicId, 4) AS BIGINT) = @rOrgId
DELETE FROM sGSEB.tResultDetail WHERE CAST(LEFT(AcademicId, 4) AS BIGINT) = @rOrgId
DELETE FROM sGSEB.tResultDetailOptional WHERE CAST(LEFT(AcademicId, 4) AS BIGINT) = @rOrgId
DELETE FROM sGSEB.tSubjectIndicatorMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sHostel.tAssignRoom WHERE CAST(LEFT(RoomId, 4) AS INT) = @rOrgId
DELETE FROM sHostel.tHostelWarden WHERE CAST(LEFT(HostelId, 4) AS INT) = @rOrgId
DELETE FROM sHrm.tEmployeeAttendance WHERE CAST(LEFT(EmployeeId, 4) AS BIGINT) = @rOrgId
DELETE FROM sHrm.tEmployeeCommunications WHERE CAST(LEFT(EmployeeId, 4) AS BIGINT) = @rOrgId
DELETE FROM sHrm.tEmployeeCustomSearch WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sHrm.tEmployeeDesignationMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sHrm.tEmployeeFamilyDetails WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sHrm.tEmployeeGradeMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sHrm.tEmployeeImages WHERE CAST(LEFT(EmployeeId, 4) AS BIGINT) = @rOrgId
DELETE FROM sHrm.tEmployeeJobDetail WHERE CAST(LEFT(EmployeeId, 4) AS BIGINT) = @rOrgId
DELETE FROM sHrm.tEmployeeMaster WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sHrm.tEmployeePersonalDetail WHERE CAST(LEFT(EmployeeId, 4) AS BIGINT) = @rOrgId
DELETE FROM sHrm.tEmployeePreviousEmployment WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sHrm.tEmployeeStatutoryAndOther WHERE CAST(LEFT(EmployeeId, 4) AS BIGINT) = @rOrgId
DELETE FROM sHrm.tEmployeeTypeMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sHrm.tGuestMaster WHERE OrgId = @rOrgId
DELETE FROM sHrm.tLeave WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sHrm.tLeaveTypeGradeSettings WHERE CAST(LEFT(OrgId, 4) AS SMALLINT) = @rOrgId
DELETE FROM sHrm.tLeaveTypeMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sHrm.tWorkingDays WHERE CAST(LEFT(BatchId, 4) AS INT) = @rOrgId
DELETE FROM sIp.tBinMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sIp.tItemStandardPriceLog WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sIp.tStockItemBin WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sIp.tStockItemPlanning WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sIp.tStockItemPurchaseUom WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sIp.tWeightedAverageCostLog WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sLibrary.tAssignOrganization WHERE OrgId = @rOrgId
DELETE FROM sLibrary.tBookLog WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sLibrary.tBookLogPenalty WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sLibrary.tBooksForClass WHERE CAST(LEFT(ClassId, 4) AS INT) = @rOrgId
DELETE FROM sLibrary.tIssueSetting WHERE CAST(LEFT(SourceId, 4) AS BIGINT) = @rOrgId
DELETE FROM sOmr.tAnswerKeySetup WHERE CAST(LEFT(ExamDetailId, 4) AS INT) = @rOrgId
DELETE FROM sOmr.tExamSetup WHERE CAST(LEFT(ExamDetailId, 4) AS INT) = @rOrgId
DELETE FROM sOmr.tScanHistory WHERE CAST(LEFT(AcademicId, 4) AS BIGINT) = @rOrgId
DELETE FROM sOmr.tSetting WHERE CAST(LEFT(OrgId, 4) AS SMALLINT) = @rOrgId
DELETE FROM sOmr.tSheetCallibration WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sOmr.tTempAnsKeyAnalysis WHERE CAST(LEFT(ExamDetailId, 4) AS INT) = @rOrgId
DELETE FROM sOrderEntry.tIssueReturn WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sOrderEntry.tIssueReturnDetail WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sOrderEntry.tOrderEntry WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sOrderEntry.tOrderEntryBatch WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sOrderEntry.tServiceItemTypeMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sProcurement.tFirstAidEmoloyee WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sProcurement.tFirstAidEmployeeDetail WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sProcurement.tFirstAidInspection WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sProcurement.tFirstAidInspectionDetail WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sProcurement.tGoodsReceiptNote WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sProcurement.tGoodsReceiptNoteBatch WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sProcurement.tGoodsReceiptNoteDetail WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sProcurement.tGoodsReceiptNoteReturn WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sProcurement.tGoodsReceiptNoteReturnBatch WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sProcurement.tGoodsReceiptNoteReturnDetail WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sProcurement.tPurchaseOrder WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sProcurement.tPurchaseOrderDetail WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sProcurement.tStockAdjustment WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sProcurement.tStockAdjustmentBatch WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sProcurement.tStockAdjustmentDetail WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sProcurement.tStockAudit WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sProcurement.tStockAuditDetail WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sProcurement.tStockBatch WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sProcurement.tStockFreezeAdjustment WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sProcurement.tStockFreezeAdjustmentDetail WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sProcurement.tStockInward WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sProcurement.tStockInwardBatch WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sProcurement.tStockInwardDetail WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sProcurement.tStockInwardRequest WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sProcurement.tStockInwardRequestDetail WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sProcurement.tStockInwardReturn WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sProcurement.tStockInwardReturnBatch WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sProcurement.tStockIssue WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sProcurement.tStockIssueBatch WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sProcurement.tStockIssueDetail WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sProcurement.tStockIssueRequest WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sProcurement.tStockIssueRequestDetail WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sProcurement.tStockItemFreeze WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sProcurement.tStockTransfer WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sProcurement.tStockTransferBatch WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sProcurement.tStockTransferDetail WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sProcurement.tStockTransferRequest WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sProcurement.tStockTransferRequestDetail WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sProcurement.tStockVerification WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sProcurement.tStockVerificationApproval WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sSecurity.tConfiguration WHERE CAST(LEFT(OrgId, 4) AS SMALLINT) = @rOrgId
DELETE FROM sSecurity.tDivisionPermission WHERE CAST(LEFT(UserId, 4) AS BIGINT) = @rOrgId
DELETE FROM sSecurity.tLdapUser WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sSecurity.tUser WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sSecurity.tUserAccess  WHERE CAST(LEFT(UserId, 4) AS int) = @rOrgId
DELETE FROM sSecurity.tUserFavoriteScreen WHERE CAST(LEFT(UserId, 4) AS BIGINT) = @rOrgId
DELETE FROM sSecurity.tUserLocation WHERE CAST(LEFT(StoreLocationId, 4) AS INT) = @rOrgId
DELETE FROM sSecurity.tUserLog WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sSecurity.tUserOrganization WHERE CAST(LEFT(OrgId, 4) AS SMALLINT) = @rOrgId
DELETE FROM sSecurity.tUserPreference WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sSecurity.tUserProfile WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sSecurity.tUserRole WHERE CAST(LEFT(UserId, 4) AS INT) = @rOrgId
DELETE FROM sSetup.tBatchClass WHERE CAST(LEFT(ClassId, 4) AS INT) = @rOrgId
DELETE FROM sSetup.tBatchMaster WHERE OrgId = @rOrgId
DELETE FROM sSetup.tClassMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sSetup.tClassSubject WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sSetup.tDepartmentMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sSetup.tDivisionMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
 
DELETE FROM sSetup.tReportConfiguration WHERE OrgId = @rOrgId
DELETE FROM sSetup.tReportSetting WHERE CAST(LEFT(OrgId, 4) AS SMALLINT) = @rOrgId
DELETE FROM sSetup.tSubjectMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sSetup.tTermMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sStudent.tAcademic WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sStudent.tAcademicDetail WHERE CAST(LEFT(AcademicId, 4) AS BIGINT) = @rOrgId
DELETE FROM sStudent.tStudentAdmission WHERE CAST(LEFT(StudentId, 4) AS BIGINT) = @rOrgId
DELETE FROM sStudent.tStudentCommunication WHERE CAST(LEFT(StudentId, 4) AS BIGINT) = @rOrgId
DELETE FROM sStudent.tStudentCustomSearch WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sStudent.tStudentFamily WHERE CAST(LEFT(StudentId, 4) AS BIGINT) = @rOrgId
DELETE FROM sStudent.tStudentHealth WHERE CAST(LEFT(StudentId, 4) AS BIGINT) = @rOrgId
DELETE FROM sStudent.tStudentImages WHERE CAST(LEFT(StudentId, 4) AS BIGINT) = @rOrgId
DELETE FROM sStudent.tStudentMaster WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sStudent.tStudentOther WHERE CAST(LEFT(StudentId, 4) AS BIGINT) = @rOrgId
DELETE FROM sSupport.tContactMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sSupport.tContactTypeMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sSupport.tImageMaster WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sSupport.tImageTypeMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sSupport.tLinkMaster WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sSupport.tVideoMaster WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sSupport.tVideoTypeMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sTax.tTaxRateSetup WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sTimetable.tDivisionWorkLoad WHERE CAST(LEFT(DivisionId, 4) AS INT) = @rOrgId
DELETE FROM sTimetable.tProxySetting WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sTimetable.tTeacherWorkLoad WHERE CAST(LEFT(DivisionId, 4) AS INT) = @rOrgId
DELETE FROM sTimetable.tTimeSetup WHERE CAST(LEFT(BatchId, 4) AS INT) = @rOrgId
DELETE FROM sTimetable.tTimeTable WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sTimetable.tTimeTableSchema WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sTransport.tAssignRoute WHERE CAST(LEFT(SourceId, 4) AS BIGINT) = @rOrgId
DELETE FROM sAssessment.tCCECSExamScore WHERE CAST(LEFT(ExamId, 4) AS INT) = @rOrgId
DELETE FROM sAssessment.tCCEFAExamScore WHERE CAST(LEFT(ExamId, 4) AS INT) = @rOrgId
DELETE FROM sAssessment.tExamCombineTerm WHERE CAST(LEFT(ExamId, 4) AS INT) = @rOrgId
DELETE FROM sAssessment.tGradeSujbectExamScore WHERE CAST(LEFT(ExamId, 4) AS INT) = @rOrgId
DELETE FROM sAssessment.tStudentRemark WHERE CAST(LEFT(ExamId, 4) AS INT) = @rOrgId
DELETE FROM sAssessment.tSubjectIndicatorMaster WHERE OrgId = @rOrgId
DELETE FROM sAssessment.tTempAllExam
DELETE FROM sAssessment.tTempCoScholasticExam

DELETE FROM sFee.tAccountMapping WHERE CAST(LEFT(FeeSetupId, 4) AS INT) = @rOrgId
DELETE FROM sFee.tDepositAdd WHERE CAST(LEFT(StudentId, 4) AS BIGINT) = @rOrgId
DELETE FROM sFee.tDepositAdjustment WHERE CAST(LEFT(StudentId, 4) AS BIGINT) = @rOrgId
DELETE FROM sFee.tDepositBalance WHERE CAST(LEFT(ClassId, 4) AS INT) = @rOrgId
DELETE FROM sFee.tDepositRefund WHERE CAST(LEFT(StudentId, 4) AS BIGINT) = @rOrgId
DELETE FROM sScholarship.tScholarshipEligibleStudent WHERE CAST(LEFT(AcademicId, 4) AS BIGINT) = @rOrgId
DELETE FROM sScholarship.tScholarshipMaster WHERE CAST(LEFT(BatchId, 4) AS BIGINT) = @rOrgId
DELETE FROM sScholarship.tScholarshipReceive WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sScholarship.tScholarshipStudentPaid WHERE CAST(LEFT(AcademicId, 4) AS BIGINT) = @rOrgId
DELETE FROM sSetup.tYearChangeDivisionMapping WHERE CAST(LEFT(OldDivisionId, 4) AS INT) = @rOrgId
DELETE FROM sAcademic.tClasswork WHERE CAST(LEFT(BatchId, 4) AS INT) = @rOrgId
DELETE FROM sAcademic.tLessonPlan WHERE CAST(LEFT(BatchId, 4) AS INT) = @rOrgId
DELETE FROM sAcademic.tLessonPlanResource WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sAcademic.tTopicMaster WHERE OrgId = @rOrgId
DELETE FROM sCertificate.tPrintTemplate WHERE OrgId = @rOrgId
DELETE FROM sCertificate.tPrintTemplateStudent WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sHostel.tStudentGatePass WHERE CAST(LEFT(StudentId, 4) AS INT) = @rOrgId
DELETE FROM sFee.tFeeHeadOrgwise WHERE OrgId = @rOrgId
DELETE FROM sFee.tReceiptBookOrgwise WHERE OrgId = @rOrgId

DELETE FROM sAcademic.tTeacherSubject WHERE CAST(LEFT(EmployeeId, 4) AS INT) = @rOrgId
DELETE FROM sAcademic.tTeacherSubjectDivision WHERE CAST(LEFT(EmployeeId, 4) AS INT) = @rOrgId
DELETE FROM sAdmission.tAdmissionCriteriaMaster WHERE OrgId = @rOrgId
--DELETE FROM sAdmission.tAdmissionCriteriaStudent WHERE CAST(LEFT(AdmissionSetupId, 4) AS INT) = @rOrgId
DELETE FROM sAdmission.tAdmissionFormSelected WHERE CAST(LEFT(AdmissionFormId, 4) AS INT) = @rOrgId
DELETE FROM sAdmission.tAdmissionSetup WHERE CAST(LEFT(BatchId, 4) AS INT) = @rOrgId
DELETE FROM sAttendance.tFilterCriteria WHERE OrgId = @rOrgId
DELETE FROM sAttendance.tFilterCriteriaDetail WHERE CAST(LEFT(FilterCriteriaId, 4) AS INT) = @rOrgId
DELETE FROM sAttendance.tYearlyRegister WHERE CAST(LEFT(AcademicId, 4) AS INT) = @rOrgId
DELETE FROM sFee.tWinfeeDetail WHERE CAST(LEFT(AcademicId, 4) AS INT) = @rOrgId
DELETE FROM sHrm.tEmployeeAttendanceRegister WHERE CAST(LEFT(EmployeeId, 4) AS INT) = @rOrgId
DELETE FROM sHrm.tEmployeeICardOrg WHERE OrgId = @rOrgId
DELETE FROM sSecurity.tUserDashlet WHERE CAST(LEFT(UserId, 4) AS INT) = @rOrgId
DELETE FROM sStudent.tICardOrg WHERE OrgId = @rOrgId

DELETE FROM sAdmission.tAdmissionSetupStudent WHERE CAST(LEFT(AdmissionSetupId, 4) AS INT) = @rOrgId
DELETE FROM sAssessment.tCCECSForClass WHERE CAST(LEFT(ClassId, 4) AS INT) = @rOrgId
DELETE FROM sAudit.tActivityLog WHERE CAST(LEFT(OrgId, 4) AS INT)  = @rOrgId
DELETE FROM sAudit.tReceiptDelete WHERE BatchId = @rOrgId
DELETE FROM sAudit.tReceiptDetailDelete WHERE CAST(LEFT(ReceiptId, 4) AS INT) = @rOrgId

DELETE FROM sCommunication.tViewResult WHERE CAST(LEFT(AcademicId, 4) AS INT) = @rOrgId
DELETE FROM sCommunication.tViewResultDetail WHERE CAST(LEFT(ExamId, 4) AS INT) = @rOrgId
DELETE FROM sSetup.tOrgInfo WHERE OrgId = @rOrgId

DELETE FROM sStudent.tStudentCustomTag WHERE CAST(LEFT(StudentId, 4) AS INT) = @rOrgId

DELETE FROM sTimetable.tAssignOrg WHERE OrgId = @rOrgId

DELETE FROM sAdmission.tAdmissionCriteria WHERE CAST(LEFT(BatchId, 4) AS INT) = @rOrgId
DELETE FROM sAdmission.tAdmissionFormFamilyDetail WHERE CAST(LEFT(AdmissionFormId, 4) AS BIGINT) = @rOrgId
DELETE FROM sAdmission.tAdmissionFormParentAcademic WHERE CAST(LEFT(AdmissionFormId, 4) AS BIGINT) = @rOrgId
DELETE FROM sAdmission.tAdmissionFormReference WHERE CAST(LEFT(AdmissionFormId, 4) AS BIGINT) = @rOrgId
DELETE FROM sAdmission.tAdmissionFormSibling WHERE CAST(LEFT(AdmissionFormId, 4) AS BIGINT) = @rOrgId
DELETE FROM sAdmission.tAdmissionFormStudentAcademic WHERE CAST(LEFT(AdmissionFormId, 4) AS BIGINT) = @rOrgId
DELETE FROM sAssessment.tCCESubjectActivityMaster WHERE OrgId = @rOrgId
DELETE FROM sAssessment.tCCESubjectSubActivityExamScore WHERE CAST(LEFT(ExamId, 4) AS BIGINT) = @rOrgId
DELETE FROM sAssessment.tCCESubjectSubActivityMaster WHERE OrgId = @rOrgId
DELETE FROM sAssessment.tResultAnalysis WHERE CAST(LEFT(ExamId, 4) AS BIGINT) = @rOrgId
DELETE FROM sAssessment.tResultAnalysisDetail WHERE CAST(LEFT(ExamId, 4) AS BIGINT) = @rOrgId
DELETE FROM sCommon.tReportOrg WHERE ScopeSourceId = @rOrgId AND ScopeSourceTypeId = 2021
DELETE FROM sAssessment.tCCESubjectSubActivityIndicatorMaster WHERE  OrgId = @rOrgId
DELETE FROM sAssessment.tResultAnalysisDivision WHERE CAST(LEFT(ExamId, 4) AS BIGINT) = @rOrgId
DELETE FROM sAssessment.tResultAnalysisDivisionDetail WHERE CAST(LEFT(ExamId, 4) AS BIGINT) = @rOrgId
DELETE FROM sFrontOffice.tStudentGatePass WHERE OrgId = @rOrgId
DELETE FROM sGoogle.tOrgCalander WHERE OrgId = @rOrgId
DELETE FROM sGoogle.tOrgDrive WHERE OrgId = @rOrgId
DELETE FROM sGoogle.tOrgYouTube WHERE OrgId = @rOrgId
DELETE FROM sHrm.tLeaveBalance WHERE CAST(LEFT(BatchId, 4) AS BIGINT) = @rOrgId
DELETE FROM sHrm.tLeaveBalanceAdd WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sTimetable.tAssignTeacher WHERE CAST(LEFT(EmployeeId, 4) AS BIGINT) = @rOrgId
DELETE FROM sTimetable.tDivision WHERE CAST(LEFT(OrgId, 4) AS INT) = @rOrgId
DELETE FROM sTimetable.tSubject WHERE CAST(LEFT(OrgId, 4) AS INT) = @rOrgId
DELETE FROM sTimetable.tSubjectTimeOff WHERE CAST(LEFT(SubjectId, 4) AS INT) = @rOrgId
DELETE FROM sTimetable.tTeacher WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sHrm.tEmployeeQualification WHERE OrgId = @rOrgId
DELETE FROM sSecurity.tUserDashboardNotification WHERE CAST(LEFT(UserId, 4) AS BIGINT) = @rOrgId
DELETE FROM sTransport.tAssignTransportOrg WHERE OrgId = @rOrgId

--DELETE FROM sFee.tOnlinePayment WHERE  CAST(LEFT(BatchId, 4) AS INT) = @rOrgId
--DELETE FROM sFee.tOnlinePaymentDetail WHERE  CAST(LEFT(OnlinePaymentId, 4) AS BIGINT) = @rOrgId
DELETE FROM sFee.tReceiptRefund WHERE  CAST(LEFT(BatchId, 4) AS INT) = @rOrgId
DELETE FROM sFee.tReceiptRefundDetail WHERE  CAST(LEFT(ReceiptRefundId, 4) AS BIGINT) = @rOrgId
DELETE FROM sIp.tUniformIssue WHERE  CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sIp.tUniformIssue WHERE  CAST(LEFT(AcademicId, 4) AS BIGINT) = @rOrgId
DELETE FROM sIp.tUniformItemForClass WHERE  CAST(LEFT(ClassId, 4) AS INT) = @rOrgId
DELETE FROM sIp.tUniformOrder WHERE  CAST(LEFT(AcademicId, 4) AS BIGINT) = @rOrgId
DELETE FROM sIp.tUniformOrderDetail WHERE  CAST(LEFT(UniformOrderId, 4) AS BIGINT) = @rOrgId
 
DELETE FROM sFee.tFeeInvoice WHERE CAST(LEFT(BatchId, 4) AS INT) = @rOrgId
DELETE FROM sFee.tFeeInvoiceDetail WHERE CAST(LEFT(FeeInvoiceId, 4) AS INT) = @rOrgId
DELETE FROM sFee.tOnlineFee WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sFee.tOnlineFeeDetail WHERE CAST(LEFT(OnlineFeeId, 4) AS INT) = @rOrgId
DELETE FROM sHrm.tCertificateEmployment WHERE CAST(LEFT(EmployeeId, 4) AS INT) = @rOrgId
DELETE FROM sOp.tPaymentTransaction WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sSetup.tOrgImages WHERE OrgId = @rOrgId
DELETE FROM sStudent.tStudentadditional WHERE CAST(LEFT(StudentId, 4) AS INT) = @rOrgId
DELETE FROM sStudent.tStudentBatchStatus WHERE CAST(LEFT(AcademicId, 4) AS INT) = @rOrgId

DELETE FROM sCommon.tPrefixConfig WHERE OrgId = @rOrgId
DELETE FROM sConfig.tDisplayFieldOrg WHERE OrgId = @rOrgId
DELETE FROM sHrm.tCertificateExperience WHERE OrgId = @rOrgId
DELETE FROM sHrm.tCertificateRelieving WHERE OrgId = @rOrgId
DELETE FROM sRFID.tAttendance WHERE OrgId = @rOrgId
DELETE FROM sRFID.tRegistration WHERE CAST(LEFT(RegistrtionId, 4) AS INT) = @rOrgId
DELETE FROM sSetup.tBatchClassLecture WHERE CAST(LEFT(BatchId, 4) AS INT) = @rOrgId
DELETE FROM sStudent.tStudentSibling WHERE CAST(LEFT(StudentId, 4) AS INT) = @rOrgId
DELETE FROM sStudent.tTranscriptAssessment WHERE CAST(LEFT(AcademicId, 4) AS INT) = @rOrgId
DELETE FROM sTally.tStudentLedgerMapping WHERE CAST(LEFT(StudentId, 4) AS INT) = @rOrgId

/* -- Date : 13/06/2016 -- */
DELETE FROM sActivity.tEventAttendance WHERE CAST(LEFT(SourceId, 4) AS INT) = @rOrgId
DELETE FROM sCanteen.tAssignOrganization WHERE OrgId = @rOrgId
DELETE FROM sCommunication.tRegisteredUsers WHERE OrgId = @rOrgId
DELETE FROM sStudent.tCollegeDetail WHERE CAST(LEFT(StudentId, 4) AS INT) = @rOrgId

-- 15.7.2016
DELETE FROM sFrontOffice.tInwardRegister WHERE OrgId = @rOrgId
DELETE FROM sFrontOffice.tOutwardRegister WHERE OrgId = @rOrgId
DELETE FROM sSetup.tSubjectGroupMaster WHERE OrgId = @rOrgId

/* -- Date : 12/08/2016 -- */
DELETE FROM sAssessment.tExamCombineSubject WHERE CAST(LEFT(ExamId, 4) AS INT) = @rOrgId
DELETE FROM sAssessment.tResultDetailOther WHERE CAST(LEFT(ExamId, 4) AS INT) = @rOrgId
DELETE FROM sSetup.tDivisionInchargeEmployee WHERE CAST(LEFT(DivisionId, 4) AS INT) = @rOrgId
DELETE FROM sStudent.tEnrollmentStatusOrg WHERE OrgId = @rOrgId
DELETE FROM sStudent.tEnrollmentStatusStudent WHERE CAST(LEFT(AcademicId, 4) AS INT) = @rOrgId
DELETE FROM sStudent.tLinkSibling WHERE CAST(LEFT(StudentId, 4) AS INT) = @rOrgId

/* -- Date : 17/09/2016 -- */

DELETE FROM sAssessment.tTempAllExamSubjectActivity WHERE CAST(LEFT(AcademicId, 4) AS INT) = @rOrgId
DELETE FROM sAttendance.tTempAttendance WHERE CAST(LEFT(AcademicId, 4) AS INT) = @rOrgId

/* -- Date : 05/10/2016 -- */

DELETE FROM sAdmission.tAdmissionInquiryFollowup WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
--DELETE FROM sAssessment.tStaticCCECSGroupMaster WHERE OrgId = @rOrgId
--DELETE FROM sAssessment.tStaticCCECSMaster WHERE OrgId = @rOrgId

/* -- Date : 20/10/2016 -- */

DELETE FROM sAssessment.tOptionalCCECS WHERE CAST(LEFT(AcademicId, 4) AS BIGINT) = @rOrgId

/* -- Date : 24/11/2016 -- */
DELETE FROM sBiometric.tMonthTrans WHERE CAST(LEFT(EmployeeId, 4) AS BIGINT) = @rOrgId

/* -- Date : 23/12/2016 -- */
DELETE FROM sAdmission.tAdmissionFormReceipt WHERE CAST(LEFT(BatchId, 4) AS INT) = @rOrgId
DELETE FROM sAssessment.tCCEExamStatus WHERE CAST(LEFT(BatchId, 4) AS INT) = @rOrgId
DELETE FROM sAttendance.tAttendanceGroup WHERE CAST(LEFT(BatchId, 4) AS INT) = @rOrgId
DELETE FROM sAttendance.tAttendanceGroupStudent WHERE CAST(LEFT(AcademicId, 4) AS BIGINT) = @rOrgId
DELETE FROM sFee.tAccountPosting WHERE CAST(LEFT(AccountId, 4) AS INT) = @rOrgId
DELETE FROM sHrm.tLeaveBalanceAddRequest WHERE CAST(LEFT(BatchId, 4) AS INT) = @rOrgId

/* -- Date : 14/02/2017 -- */

DELETE FROM sCRM.tChannelPartnerMaster WHERE OrgId = @rOrgId
DELETE FROM sCRM.tInstituteGroupMaster WHERE OrgId = @rOrgId
DELETE FROM sCRM.tInstituteMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sSetup.tOrganizationOtherDetail WHERE OrgId = @rOrgId

DELETE FROM sAppraisal.tConduct WHERE CAST(LEFT(BatchId, 4) AS INT) = @rOrgId
DELETE FROM sAssessment.tAllBatchClassGroup WHERE OrgId= @rOrgId
DELETE FROM sAssessment.tAllBatchResult WHERE CAST(LEFT(StudentId, 4) AS BIGINT) = @rOrgId
DELETE FROM sAssessment.tAllBatchSubject WHERE OrgId= @rOrgId
DELETE FROM sHrm.tEmployeeTravel WHERE OrgId= @rOrgId


DELETE FROM sLoan.tLoanDetail WHERE OrgId= @rOrgId
DELETE FROM sLoan.tLoanEMI WHERE CAST(LEFT(LoanDetailId, 4) AS BIGINT) = @rOrgId
DELETE FROM sLoan.tLoanPayrollMapping WHERE OrgId= @rOrgId
DELETE FROM sLoan.tLoanTypeMaster WHERE OrgId= @rOrgId
DELETE FROM sPayroll.tPayrollCustomSearch WHERE OrgId= @rOrgId
DELETE FROM sErp.tChannelMaster WHERE OrgId = @rOrgId

DELETE FROM sAccounting.tExpenseDetail WHERE CAST(LEFT(ExpenseId, 4) AS int) = @rOrgId
DELETE FROM sAccounting.tExpenseSubGroupMaster WHERE OrgId= @rOrgId
DELETE FROM sAppraisal.tAppraisalTypeMaster WHERE CAST(LEFT(BatchId, 4) AS int) = @rOrgId
DELETE FROM sAppraisal.tBusinessHeadsRatingStatus WHERE CAST(LEFT(AppraisalTypeId, 4) AS int) = @rOrgId
DELETE FROM sAppraisal.tKPAEmployee WHERE CAST(LEFT(BatchId, 4) AS int) = @rOrgId
DELETE FROM sAppraisal.tKPAEmployeeDetail WHERE CAST(LEFT(KPAEmployeeId, 4) AS bigint) = @rOrgId
DELETE FROM sAppraisal.tKPAEmployeeRating WHERE CAST(LEFT(KPAEmployeeId, 4) AS bigint) = @rOrgId
DELETE FROM sAppraisal.tKPAEmployeeRatingDetail WHERE CAST(LEFT(KPAEmployeeRatingId, 4) AS bigint) = @rOrgId
DELETE FROM sPoliciesForms.tFolderFile WHERE OrgId = @rOrgId
DELETE FROM sPoliciesForms.tFolderFilePermission WHERE CAST(LEFT(FolderFileId, 4) AS int) = @rOrgId


DELETE FROM sFee.tFeeMainGroupOptionalFee WHERE OrgId = @rOrgId
DELETE FROM sFee.tFeeStructureDetail WHERE CAST(LEFT(FeeStructureId, 4) AS int) = @rOrgId
DELETE FROM sFee.tFeeStructureMaster WHERE OrgId = @rOrgId
DELETE FROM sFrontOffice.tEmployeeGatePass WHERE OrgId = @rOrgId
DELETE FROM sHostel.tHostelStudentGatePass WHERE CAST(LEFT(StudentId, 4) AS bigint) = @rOrgId
DELETE FROM sHrm.tLeaveBalanceLog WHERE CAST(LEFT(EmployeeId, 4) AS bigint) = @rOrgId
DELETE FROM sTransport.tAttendanceRegister WHERE CAST(LEFT(SourceId, 4) AS bigint) = @rOrgId

DELETE FROM sAssessment.tCCESubjectActivityExamScore WHERE CAST(LEFT(AcademicId, 4) AS bigint) = @rOrgId
DELETE FROM sAssessment.tTempAll_Exam WHERE CAST(LEFT(AcademicId, 4) AS bigint) = @rOrgId
DELETE FROM sCanteen.tAttendanceForBreak WHERE CAST(LEFT(SourceId, 4) AS bigint) = @rOrgId
DELETE FROM sCanteen.tRegisterForBreak WHERE CAST(LEFT(SourceId, 4) AS bigint) = @rOrgId
DELETE FROM sCertificate.tTransfer WHERE OrgId = @rOrgId
DELETE FROM sCanteen.tRegisterForBreak WHERE CAST(LEFT(SourceId, 4) AS bigint) = @rOrgId

DELETE FROM sErp.tLeadFollowup WHERE CAST(LEFT(LeadId, 4) AS int) = @rOrgId
DELETE FROM sErp.tLeadMaster WHERE OrgId = @rOrgId


DELETE FROM sAdmission.tAdmissionHSCDetail WHERE CAST(LEFT(AdmissionFormId, 4) AS bigint) = @rOrgId
DELETE FROM sBiometric.tEmployeeCheckIn WHERE CAST(LEFT(EmployeeId, 4) AS bigint) = @rOrgId

DELETE FROM sBiometric.tEmployeeLateStatus WHERE CAST(LEFT(EmployeeId, 4) AS bigint) = @rOrgId

DELETE FROM sCommon.tSubmitDocumentMaster WHERE OrgId = @rOrgId
DELETE FROM sStudent.tStudentDocument WHERE CAST(LEFT(SubmitDocumentMasterId, 4) AS int) = @rOrgId
DELETE FROM sTimetable.tAnnualSubjectWorkLoad WHERE CAST(LEFT(BatchId, 4) AS int) = @rOrgId

DELETE FROM sFee.tReceiptDeleted WHERE CAST(LEFT(BatchId, 4) AS int) = @rOrgId
DELETE FROM sFee.tReceiptDetailDeleted WHERE CAST(LEFT(ReceiptId, 4) AS bigint) = @rOrgId

DELETE FROM sAttendance.tStudentLeaveRequest WHERE CAST(LEFT(AcademicId, 4) AS bigint) = @rOrgId
DELETE FROM sInfrastructure.tResourceMaster WHERE CAST(LEFT(Id, 4) AS int) = @rOrgId
DELETE FROM sInfrastructure.tResourceRequest WHERE CAST(LEFT(Id, 4) AS bigint) = @rOrgId

DELETE FROM sAlumni.tRegistration WHERE OrgId = @rOrgId
DELETE FROM sBiometric.tMonthlyStatusUpdate WHERE CAST(LEFT(EmployeeId, 4) AS bigint) = @rOrgId
DELETE FROM sErp.tDSR WHERE OrgId = @rOrgId
DELETE FROM sErp.tDSRWorkTypeMaster WHERE OrgId = @rOrgId
DELETE FROM sErp.tProjectMaster WHERE OrgId = @rOrgId
DELETE FROM sFee.tFeeFollowup WHERE CAST(LEFT(AcademicId, 4) AS bigint) = @rOrgId
 
DELETE FROM sActivity.tWeekOffSetting WHERE CAST(LEFT(SourceId, 4) AS bigint) = @rOrgId
DELETE FROM sAssessment.tAllBatchResultCoScholestic WHERE CAST(LEFT(StudentId, 4) AS bigint) = @rOrgId
DELETE FROM sHrm.tEmployeeDocument WHERE CAST(LEFT(EmployeeId, 4) AS bigint) = @rOrgId
DELETE FROM sStudent.tChangeIdLog WHERE CAST(LEFT(StudentId, 4) AS bigint) = @rOrgId
DELETE FROM sAlert.tAssociateRecipient WHERE CAST(LEFT(ForUserId, 4) AS bigint) = @rOrgId

DELETE FROM sAcademic.tPreLessonPlan WHERE CAST(LEFT(BatchId, 4) AS int) = @rOrgId
DELETE FROM sAssessment.tAllBatchResultGrade WHERE CAST(LEFT(StudentId, 4) AS bigint) = @rOrgId

DELETE FROM sVts.tvtsClassMaster WHERE CAST(LEFT(ClassId, 4) AS int) = @rOrgId
DELETE FROM sVts.tvtsOrganizationMaster WHERE OrgId = @rOrgId
DELETE FROM sVts.tvtsStudent WHERE CAST(LEFT(StudentId, 4) AS bigint) = @rOrgId
DELETE FROM sErp.tLeadChannelPartnerMaster WHERE  OrgId = @rOrgId


DELETE FROM sAlumni.tStudentMapping WHERE CAST(LEFT(StudentId, 4) AS bigint) = @rOrgId
DELETE FROM sErp.tUserFeedback WHERE CAST(LEFT(UserId, 4) AS bigint) = @rOrgId
DELETE FROM sFee.tFeeExpense WHERE CAST(LEFT(AcademicId, 4) AS bigint) = @rOrgId


DELETE FROM sAdmission.tAdmissionCriteriaForm WHERE CAST(LEFT(BatchId, 4) AS int) = @rOrgId
DELETE FROM sAdmission.tAdmissionFormField WHERE CAST(LEFT(AdmissionFormId, 4) AS bigint) = @rOrgId
DELETE FROM sAssessment.tGradeSetClassSubjectDetail WHERE CAST(LEFT(Id, 4) AS int) = @rOrgId
DELETE FROM sAssessment.tGradeSetClassSubjectMaster WHERE OrgId = @rOrgId
DELETE FROM sBiometric.BioDetailMapping WHERE OrgId = @rOrgId
DELETE FROM sBiometric.tLog WHERE OrgId = @rOrgId

DELETE FROM sCertificate.tOtherCertificate WHERE OrgId = @rOrgId
DELETE FROM sWorkflow.tApprovalAction WHERE CAST(LEFT(ActionUserId, 4) AS bigint) = @rOrgId
DELETE FROM sWorkflow.tApprovalRequest WHERE CAST(LEFT(BatchId, 4) AS int) = @rOrgId
DELETE FROM sWorkflow.tFunctionalityApprovingAuthority WHERE OrgId = @rOrgId
DELETE FROM sWorkflow.tFunctionalityApprovingDepartment WHERE OrgId = @rOrgId

DELETE FROM sBiometric.tProcess WHERE CAST(LEFT(SourceId, 4) AS bigint) = @rOrgId
DELETE FROM sAssessment.tConfiguration WHERE OrgId = @rOrgId

DELETE FROM sAcademic.tHomeworkCheck WHERE CAST(LEFT(AcademicId, 4) AS bigint) = @rOrgId

DELETE FROM sAdmission.tAdmissionCriteriaFee WHERE CAST(LEFT(BatchId, 4) AS int) = @rOrgId
DELETE FROM sAdmission.tAdmissionFormFee WHERE CAST(LEFT(AdmissionFormId, 4) AS bigint) = @rOrgId


DELETE FROM sFee.tFeeOpening WHERE CAST(LEFT(AcademicId, 4) AS bigint) = @rOrgId
DELETE FROM sTransport.tChangeRouteLog WHERE CAST(LEFT(SourceId, 4) AS bigint) = @rOrgId

DELETE FROM sAcademic.tClassworkConfig WHERE OrgId = @rOrgId
DELETE FROM sBiometric.tPunchData WHERE CAST(LEFT(StudentID, 4) AS bigint) = @rOrgId
DELETE FROM sErp.tCallLog WHERE CAST(LEFT(EmployeeId, 4) AS bigint) = @rOrgId
DELETE FROM sErp.tMarketingActivityPlan WHERE CAST(LEFT(EmployeeId, 4) AS bigint) = @rOrgId
--DELETE FROM tMarketingActivityStatus WHERE CAST(LEFT(EmployeeId, 4) AS bigint) = @rOrgId
DELETE FROM sErp.tTripLog WHERE CAST(LEFT(EmployeeId, 4) AS bigint) = @rOrgId


DELETE FROM sAudit.HistoryLog WHERE CAST(LEFT(SourceId, 4) AS bigint) = @rOrgId
DELETE FROM sAudit.tOperationLog WHERE CAST(LEFT(SourceId, 4) AS int) = @rOrgId

--DELETE FROM sErp.tCustomerTicket WHERE OrgId= @rOrgId
DELETE FROM sPayroll.tPayProcessEmployeeRemark WHERE CAST(LEFT(EmployeeId, 4) AS int) = @rOrgId


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

DELETE FROM sSetup.tOrganizationMaster WHERE Id = @rOrgId
DELETE FROM sCommon.tTableRowId WHERE OrgId = @rOrgId


DELETE FROM sAlert.tAlertLogHistory WHERE OrgId= @rOrgId
DELETE FROM sAlert.tNotificationLogHistory WHERE CAST(LEFT(CreatedUserId, 4) AS bigint) = @rOrgId
DELETE FROM sHrm.tBatchEmployeeCommunications WHERE CAST(LEFT(EmployeeId, 4) AS bigint) = @rOrgId
DELETE FROM sHrm.tBatchEmployeeFamilyDetails WHERE CAST(LEFT(EmployeeId, 4) AS bigint) = @rOrgId
DELETE FROM sHrm.tBatchEmployeeJobDetail WHERE OrgId= @rOrgId
DELETE FROM sHrm.tBatchEmployeeMaster WHERE OrgId= @rOrgId
DELETE FROM sHrm.tBatchEmployeePersonalDetail WHERE OrgId= @rOrgId
DELETE FROM sHrm.tBatchEmployeeStatutoryAndOther WHERE CAST(LEFT(EmployeeId, 4) AS bigint) = @rOrgId
DELETE FROM sSecurity.tUserLogHistory WHERE OrgId= @rOrgId
DELETE FROM sStudent.tAcademicStudent WHERE CAST(LEFT(AcademicId, 4) AS bigint) = @rOrgId
DELETE FROM sStudent.tAcademicStudentAdditional WHERE CAST(LEFT(AcademicId, 4) AS bigint) = @rOrgId
DELETE FROM sStudent.tAcademicStudentCommunication WHERE CAST(LEFT(AcademicId, 4) AS bigint) = @rOrgId
DELETE FROM sStudent.tAcademicStudentFamily WHERE CAST(LEFT(AcademicId, 4) AS bigint) = @rOrgId
DELETE FROM sStudent.tAcademicStudentHealth WHERE CAST(LEFT(AcademicId, 4) AS bigint) = @rOrgId
DELETE FROM sStudent.tAcademicStudentOther WHERE CAST(LEFT(AcademicId, 4) AS bigint) = @rOrgId
DELETE FROM sStudent.tStudentCustomFieldData WHERE CAST(LEFT(StudentId, 4) AS bigint) = @rOrgId
DELETE FROM sStudent.tStudentMasterDelete WHERE OrgId= @rOrgId

DELETE FROM sAudit.ChangeLog WHERE CAST(LEFT(SourceId, 4) AS bigint) = @rOrgId
DELETE FROM sHrm.tCertificateIncrement WHERE OrgId= @rOrgId
DELETE FROM sAudit.ChangeLog WHERE CAST(LEFT(ScreenId, 4) AS bigint) = @rOrgId

DELETE FROM sAcademic.tClassworkView WHERE CAST(LEFT(AcademicId, 4) AS bigint) = @rOrgId
DELETE FROM sBiometric.tPunchCount WHERE CAST(LEFT(SourceId, 4) AS bigint) = @rOrgId

DELETE FROM sFrontOffice.tOTPLog WHERE CAST(LEFT(CreatedUserId, 4) AS bigint) = @rOrgId
DELETE FROM sHrm.tLeaveDeduction WHERE CAST(LEFT(EmployeeId, 4) AS bigint) = @rOrgId


DELETE FROM sAdmission.tAdmissionCriteriaDocument WHERE CAST(LEFT(BatchId, 4) AS int) = @rOrgId
DELETE FROM sAdmission.tAdmissionStudentDocument WHERE CAST(LEFT(AdmissionFormId, 4) AS bigint) = @rOrgId
DELETE FROM sTimetable.tTimeTableTime WHERE CAST(LEFT(DivisionId, 4) AS int) = @rOrgId
DELETE FROM sHrm.tEmployeeWorkingDays WHERE CAST(LEFT(BatchId, 4) AS int) = @rOrgId

DELETE FROM sErp.tContactBookMaster WHERE OrgId= @rOrgId
DELETE FROM sErp.tEmployeeERPDetail WHERE CAST(LEFT(EmployeeId, 4) AS bigint) = @rOrgId
DELETE FROM sFrontOffice.tLostFoundRegisterScope WHERE CAST(LEFT(SourceId, 4) AS int) = @rOrgId
DELETE FROM sHrm.tEmployeeChangeHistory WHERE CAST(LEFT(EmployeeId, 4) AS bigint) = @rOrgId
DELETE FROM sCommon.tReportTemplate WHERE OrgId= @rOrgId
DELETE FROM sTransport.tBusRouteAssignedTo WHERE CAST(LEFT(SourceId, 4) AS bigint) = @rOrgId
DELETE FROM sWorkflow.tStudentDataChange WHERE CAST(LEFT(SourceId, 4) AS bigint) = @rOrgId

DELETE FROM sAcademic.tOnlineLearning WHERE CAST(LEFT(BatchId, 4) AS int) = @rOrgId
DELETE FROM sAcademic.tOnlineLearningAssignment WHERE CAST(LEFT(OnlineLearningId, 4) AS bigint) = @rOrgId
DELETE FROM sAcademic.tOnlineLearningAssignmentSubmit WHERE CAST(LEFT(OnlineLearningId, 4) AS bigint) = @rOrgId
DELETE FROM sAcademic.tOnlineLearningAttendance WHERE CAST(LEFT(OnlineLearningId, 4) AS bigint) = @rOrgId
DELETE FROM sAcademic.tOnlineLearningAttendanceLog WHERE CAST(LEFT(OnlineLearningId, 4) AS bigint) = @rOrgId
DELETE FROM sAcademic.tOnlineLearningReference WHERE CAST(LEFT(OnlineLearningId, 4) AS bigint) = @rOrgId
DELETE FROM sAcademic.tOnlineLearningResource WHERE CAST(LEFT(OnlineLearningId, 4) AS bigint) = @rOrgId
DELETE FROM sAcademic.tOnlineLearningScope WHERE CAST(LEFT(OnlineLearningId, 4) AS bigint) = @rOrgId
DELETE FROM sAcademic.tTempOnlineLearningScope WHERE CAST(LEFT(SourceId, 4) AS bigint) = @rOrgId
DELETE FROM sCommunication.tChat WHERE CAST(LEFT(FromSourceId, 4) AS bigint) = @rOrgId
DELETE FROM sCommunication.tTempChatGroupScope WHERE CAST(LEFT(MemberSourceId, 4) AS bigint) = @rOrgId


DELETE FROM sAcademic.tOnlineMeetingSettings WHERE CAST(LEFT(OnlineLearningId, 4) AS bigint) = @rOrgId
DELETE FROM sStudent.tDigitalForm WHERE OrgId= @rOrgId
DELETE FROM sStudent.tDigitalFormScope WHERE CAST(LEFT(DigitalFormId, 4) AS int) = @rOrgId
DELETE FROM sStudent.tDigitalFormField WHERE CAST(LEFT(DigitalFormId, 4) AS int) = @rOrgId
DELETE FROM sStudent.tDigitalFormStudent WHERE CAST(LEFT(DigitalFormId, 4) AS int) = @rOrgId

DELETE FROM sAcademic.tOnlineLearningView WHERE CAST(LEFT(AcademicId, 4) AS bigint) = @rOrgId

DELETE FROM sOp.tPaymentTransactionHistory WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sFee.tOnlineFeeHistory WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sFee.tOnlineFeeDetailHistory WHERE CAST(LEFT(OnlineFeeId, 4) AS INT) = @rOrgId
DELETE FROM sCommunication.tStudentDocumentUpload WHERE CAST(LEFT(BatchId, 4) AS INT) = @rOrgId

DELETE FROM sFee.tFeeAllocationHistory WHERE CAST(LEFT(SourceId, 4) AS bigint) = @rOrgId

DELETE FROM sCommon.tUploadDocument WHERE CAST(LEFT(CreatedUserId, 4) AS bigint) = @rOrgId

DELETE FROM sFee.tFeeAllocationStudent WHERE CAST(LEFT(AcademicId, 4) AS bigint) = @rOrgId
DELETE FROM sFee.tFeeClassBatchStatus WHERE CAST(LEFT(BatchId, 4) AS int) = @rOrgId
DELETE FROM sHrm.tEmployeeBatch WHERE CAST(LEFT([EmployeeId], 4) AS bigint) = @rOrgId
DELETE FROM sCommunication.tEmployeeDocumentUpload WHERE OrgId = @rOrgId

DELETE FROM [sHrm].[tEmployeeCustomFieldData] WHERE CAST(LEFT([EmployeeId], 4) AS bigint) = @rOrgId

DELETE FROM [sCommunication].[tDailyThoughtAssign] WHERE OrgId= @rOrgId
DELETE FROM [sFee].[tEMandate] WHERE CAST(LEFT(Id, 4) AS bigint) = @rOrgId

DELETE FROM [sAdmission].[tAdmissionInquiryCriteria] WHERE CAST(LEFT([ClassId], 4) AS int) = @rOrgId
DELETE FROM [sCommon].[tSubmitDocumentScope] WHERE CAST(LEFT([SubmitDocumentId], 4) AS int) = @rOrgId

DELETE FROM sAcademic.tOnlineLearningRecording WHERE CAST(LEFT([OnlineLearningId], 4) AS bigint) = @rOrgId

DELETE FROM [sCommon].[tUserToken] WHERE CAST(LEFT([UserId], 4) AS bigint) = @rOrgId

DELETE FROM [sBiometric].[tEmployeeConfiguration] WHERE CAST(LEFT([EmployeeId], 4) AS bigint) = @rOrgId
DELETE FROM sAlert.tWhatsAppConfiguration WHERE OrgId= @rOrgId
DELETE FROM sFee.tDepositSetup WHERE CAST(LEFT([StudentId], 4) AS bigint) = @rOrgId
DELETE FROM [sAlert].[tWhatsAppLog] WHERE CAST(LEFT([SourceId], 4) AS bigint) = @rOrgId

DELETE FROM sAcademic.tOnlineLearningHistoryLog WHERE CAST(LEFT([BatchId], 4) AS int) = @rOrgId

DELETE FROM [sAlert].[tAlertTrack] WHERE OrgId = @rOrgId
DELETE FROM sTally.tJVPosting WHERE CAST(LEFT([StudentId], 4) AS bigint) = @rOrgId

DELETE FROM [sHrm].[tLeavePeriod] WHERE OrgId = @rOrgId
DELETE FROM [sRecruitment].[tAssignOrganization] WHERE OrgId = @rOrgId

DELETE FROM sAdmission.tAdmissionCustomSearch WHERE OrgId = @rOrgId

DELETE FROM[sCommunication].[tTempQueryCategoryScope] WHERE CAST(LEFT([SourceId], 4) AS bigint) = @rOrgId


DELETE FROM [sStudent].[tOnlineRegistrationStudentAdmission] WHERE CAST(LEFT([StudentId], 4) AS bigint) = @rOrgId
DELETE FROM [sStudent].[tOnlineRegistrationStudentCommunication] WHERE CAST(LEFT([StudentId], 4) AS bigint) = @rOrgId
DELETE FROM [sStudent].[tOnlineRegistrationStudentCustomFieldData] WHERE CAST(LEFT([StudentId], 4) AS bigint) = @rOrgId
DELETE FROM [sStudent].[tOnlineRegistrationStudentDocument] WHERE CAST(LEFT([StudentId], 4) AS bigint) = @rOrgId
DELETE FROM [sStudent].[tOnlineRegistrationStudentFamily] WHERE CAST(LEFT([StudentId], 4) AS bigint) = @rOrgId
DELETE FROM [sStudent].[tOnlineRegistrationStudentImages] WHERE CAST(LEFT([StudentId], 4) AS bigint) = @rOrgId
DELETE FROM [sStudent].[tOnlineRegistrationStudentOther] WHERE CAST(LEFT([StudentId], 4) AS bigint) = @rOrgId
DELETE FROM [sStudent].[tOnlineRegistrationCollegeDetail] WHERE CAST(LEFT([StudentId], 4) AS bigint) = @rOrgId
DELETE FROM [sStudent].[tOnlineRegistrationDisplayField]  WHERE CAST(LEFT([BatchId], 4) AS int) = @rOrgId
DELETE FROM [sStudent].[tOnlineRegistrationCriteriaDocument]  WHERE CAST(LEFT([BatchId], 4) AS int) = @rOrgId
DELETE FROM [sStudent].[tOnlineRegistrationCriteriaForm]  WHERE CAST(LEFT([BatchId], 4) AS int) = @rOrgId
DELETE FROM [sStudent].[tOnlineRegistrationStudentMaster] WHERE OrgId = @rOrgId

DELETE FROM [sBiometric].[tShiftAllocationCloud] WHERE CAST(LEFT([SourceId], 4) AS bigint) = @rOrgId
DELETE FROM [sBiometric].[tCloudTransactionData] WHERE CAST(LEFT([SourceId], 4) AS bigint) = @rOrgId

DELETE FROM [sTransport].[tAssignRouteLog] WHERE CAST(LEFT([SourceId], 4) AS bigint) = @rOrgId
DELETE FROM [sAttendance].[tAttendanceFollowup] WHERE CAST(LEFT([AcademicId], 4) AS bigint) = @rOrgId

DELETE FROM sAssessment.tAssessmentLabelSetup WHERE OrgId = @rOrgId
DELETE FROM [sAssessment].[tStudentExamRemark] WHERE CAST(LEFT([AcademicId], 4) AS bigint) = @rOrgId
DELETE FROM [sBiometric].[tDeviceMasterCloud] WHERE OrgId = @rOrgId

DELETE FROM [sHrm].[tDigitalForm] WHERE OrgId = @rOrgId
DELETE FROM [sHrm].[tDigitalFormField] WHERE CAST(LEFT([DigitalFormId], 4) AS int) = @rOrgId
DELETE FROM [sHrm].[tDigitalFormScope] WHERE CAST(LEFT([DigitalFormId], 4) AS int) = @rOrgId
DELETE FROM [sHrm].[tDigitalFormEmployee] WHERE CAST(LEFT([DigitalFormId], 4) AS int) = @rOrgId
DELETE FROM [sAdmission].[tAdmissionOptionalSubject] WHERE CAST(LEFT([AdmissionFormId], 4) AS bigint) = @rOrgId
DELETE FROM [sStudent].[tOnlineRegistrationStudentOptionalSubject] WHERE CAST(LEFT([OnlineRegistrationStudentId], 4) AS bigint) = @rOrgId
DELETE FROM [sStudent].[tOnlineRegistrationCriteria] WHERE CAST(LEFT([BatchId], 4) AS int) = @rOrgId
DELETE FROM [sStudent].[tOnlineRegistrationCriteriaOptionalSubject] WHERE CAST(LEFT([BatchId], 4) AS int) = @rOrgId
DELETE FROM [sAdmission].[tAdmissionCriteriaOptionalSubject] WHERE CAST(LEFT([BatchId], 4) AS int) = @rOrgId

DELETE FROM [sAlert].[tAlertTrackHistory] WHERE OrgId = @rOrgId
DELETE FROM [sActivity].[tEventInchargeAssign] WHERE CAST(LEFT([SourceId], 4) AS bigint) = @rOrgId
DELETE FROM [sLibrary].[tNewspaperLog] WHERE CAST(LEFT([NewspaperId], 4) AS int) = @rOrgId
DELETE FROM sSetup.tClassContentSetup WHERE CAST(LEFT([ClassId], 4) AS int) = @rOrgId

DELETE FROM[sHrm].[tCertificateJoining] WHERE [OrgId] = @rOrgId
DELETE FROM[sCommunication].[tTempMultiPhotoCategoryScope] WHERE CAST(LEFT([SourceId], 4) AS bigint) = @rOrgId

DELETE FROM[sStudent].[tDigitalFormStudentStatus] WHERE CAST(LEFT([AcademicId], 4) AS bigint) = @rOrgId
DELETE FROM[sHrm].[tDigitalFormEmployeeStatus] WHERE CAST(LEFT([EmployeeId], 4) AS bigint) = @rOrgId
DELETE FROM[sHrm].[tLeaveHierarchyLevel] WHERE CAST(LEFT([LeaveId], 4) AS bigint) = @rOrgId

DELETE FROM [sAudit].[tChargeDeleted] WHERE [OrgId] = @rOrgId
DELETE FROM [sAudit].[tChargeDetailDelete] WHERE CAST(LEFT([ChargeReceiptId], 4) AS bigint) = @rOrgId

DELETE FROM sFee.tLateFeeRuleMaster WHERE OrgId = @rOrgId



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

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


GO

ALTER PROCEDURE [sCommunication].[pQueryCategoryDropdownGet]
	@rOrgGroupBatchId int,
	@rUserSourceId bigint,
	@rUserSourceTypeId int
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
	DECLARE @lAcademicId bigint,@lStudentId bigint,@lClassId int,@lDivisionId int,@lOrgId int,@lDepartmentId int,@lEmployeeId bigint

	IF @rUserSourceTypeId = 95 -- For Employee Login
	BEGIN
		SELECT 
			@lDepartmentId=EJD.OrganizationDepartmentId,
			@lOrgId = EM.OrgId,
			@lEmployeeId = EM.Id 
		FROM 
			sHrm.tEmployeeMaster EM INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id 
		WHERE 
			EM.Id=@rUserSourceId
		
		SELECT Distinct	
			QCM.Id,
			QCM.Title
		FROM 
			sCommunication.tQueryCategoryMaster QCM           
			INNER JOIN 
			(SELECT QCS.QueryCategoryId FROM sCommunication.tQueryCategoryScope QCS
				WHERE (((QCS.SourceTypeId = 2021 AND QCS.SourceId =@lOrgId) OR
				(QCS.SourceTypeId = 2017 AND QCS.SourceId =@lDepartmentId) OR
				(QCS.SourceTypeId = 95 AND QCS.SourceId =@lEmployeeId )) 
				AND ((QCS.AssigneeToId=3) OR (QCS.AssigneeToId IS NULL) OR (ISNULL(QCS.AssigneeToId,0)=0)))) D
				ON D.QueryCategoryId= QCM.Id
			--INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=QCM.OrgGroupBatchId AND OGBM.Id=@rOrgGroupBatchId
			--INNER JOIN sSecurity.tUser U ON U.Id=QCM.CreatedUserId
		WHERE 
			QCM.AssignedToId IN (1,3) 
			AND QCM.IsObsolete = 0

		UNION

		SELECT Distinct	
			QCM.Id,
			QCM.Title
		FROM 
			sCommunication.tQueryCategoryMaster QCM           
			INNER JOIN sCommunication.tQueryCategoryAssignedTo QCA ON QCM.Id = QCA.QueryCategoryId
			AND QCA.SourceTypeId = 95 AND QCA.SourceId =@lEmployeeId
	
		WHERE 
			---QCM.AssignedToId IN (1,3) 
			QCM.IsObsolete = 0

	END
	ELSE IF @rUserSourceTypeId = 2003 -- For Student Login
	BEGIN
		SELECT 
			@lAcademicId = A.Id,
			@lStudentId = A.StudentId,
			@lClassId = A.ClassId, 
			@lDivisionId = A.DivisionId, 
			@lOrgId= A.OrgId, 
			@lDepartmentId=CM.DepartmentId
		FROM sStudent.tAcademic A 
			INNER JOIN sSetup.tBatchMaster BM ON A.BatchId = BM.Id 
			INNER JOIN sSetup.tClassMaster CM ON CM.Id = A.ClassId
		WHERE StudentId = @rUserSourceId AND BM.OrgGroupBatchId = @rOrgGroupBatchId
  
		SELECT 	Distinct
			QCM.Id,
			QCM.Title
		FROM 
			sCommunication.tQueryCategoryMaster QCM
			INNER JOIN (SELECT QCS.QueryCategoryId 
				FROM sCommunication.tQueryCategoryScope QCS
				WHERE (((QCS.SourceTypeId = 2021 AND QCS.SourceId =@lOrgId) OR
				(QCS.SourceTypeId = 2017 AND QCS.SourceId =@lDepartmentId) OR
				(QCS.SourceTypeId = 2016 AND QCS.SourceId =@lClassId) OR
				(QCS.SourceTypeId = 2005 AND QCS.SourceId =@lDivisionId) OR
				(QCS.SourceTypeId = 2003 AND QCS.SourceId =@lStudentId) OR
				(QCS.SourceTypeId = 2001 AND QCS.SourceId =@lAcademicId) )
				)AND ((QCS.AssigneeToId=2) OR (QCS.AssigneeToId IS NULL) OR (ISNULL(QCS.AssigneeToId,0)=0))) D ON D.QueryCategoryId= QCM.Id 
		WHERE
			QCM.AssignedToId IN (1,2) 
			AND QCM.IsObsolete = 0
	END
	ELSE
	--For Other Users
	BEGIN
		SELECT 	
			QCM.Id,
			QCM.Title
		FROM 
			sCommunication.tQueryCategoryMaster QCM
		WHERE 
			QCM.AssignedToId IN (1,2,3)
			AND QCM.IsObsolete = 0
	END
END
GO
PRINT N'Altering [sFee].[pAssignOptionalFeeAdd]...';


GO

 
ALTER PROCEDURE [sFee].[pAssignOptionalFeeAdd]
	 
		   @rFeeSetupId int,
           @rSourceTypeId int,
           @rSourceId bigint,
           @rBatchId int

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	 BEGIN TRANSACTION	
IF EXISTS (SELECT 1 FROM [sFee].[tFeeSetup] where Id=@rFeeSetupId AND IsOptional=1)
BEGIN
IF NOT EXISTS(SELECT 1 FROM sFee.tFeeOptional WHERE FeeSetupId=@rFeeSetupId AND SourceId=@rSourceId AND SourceTypeId=@rSourceTypeId AND BatchId=@rBatchId )	
BEGIN

	INSERT INTO sFee.tFeeOptional
		(
		   FeeSetupId,
		   SourceTypeId,
		   SourceId,
		   BatchId
		)
	VALUES
		(
			@rFeeSetupId,
			@rSourceTypeId,
			@rSourceId,
			@rBatchId
		)

		DECLARE @lOrgId NVARCHAR(10) = SUBSTRING(CAST(@rBatchId AS NVARCHAR(10)),1,4)

		EXEC sFee.pFeeProcessGenerateFeeOptionalAdd 0,@rFeeSetupId,@lOrgId,@rBatchId,0,0,3,@rSourceId,@rSourceTypeId

		SELECT 1 AS Result
		             
	END	 
	 ELSE
	 BEGIN

	      SELECT 11 AS Result   
	 END 
END
ELSE 
BEGIN

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


GO
ALTER PROCEDURE [sFee].[pFeeSetupAdd]
	 
		@rId int,
        @rClassId int,
        @rAdmissionCategoryId int,
        @rBatchId int,
        @rFeeId int,
        @rIsOptional bit,
        @rIsVariable bit,
        @rAmount decimal(12,2),
        @rStartDate date,
        @rEndDate date,
        @rReceiptBookId int,
        @rCreatedUserId bigint,
		@rUpdatedUserId bigint,
		@rOrgId int,
		@rCheck bit,
		@rIsServiceTax bit,
		@rCollectionGroupId int = 0,
		@rOrgGroupId int=0,
		@rFeeDuration nvarchar(100) ='',
		@rLevelAmount decimal(12,2)=0
		--@rLateFeeRuleId int = 0

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	DECLARE @lFeeSetupId int=0
	
	 IF(@rCheck=1 AND @rId>0)
	 BEGIN
	 
	 IF(@rIsOptional = 1 AND @rIsVariable = 1)
	 BEGIN
		  SELECT 0 as Result
		  RETURN
	 END
	 ELSE
	 BEGIN
			IF EXists( SELECT * FROM (
			SELECT AcademicId,	   
					(SELECT ISNULL(SUM(RD.Amount),0)  
					FROM sFee.tReceipt R INNER JOIN sFee.tReceiptDetail RD
					ON	RD.ReceiptId = R.Id
					AND RD.FeeSetupId = @rId
					WHERE R.SourceId = VA.AcademicId AND R.IsObsolete = 0) PaidAmount,		      
					(SELECT ISNULL(VariableAmount,0)-ISNULL(DiscountAmount,0) +
					IsNULL(AdditionalAmount,0) - ISNULL(NotApplicableAmount,0)  
					FROM  sFee.tFeeAllocation A		  
					WHERE A.SourceId = VA.AcademicId AND A.FeeSetupId = @rId  ) AllocationAmount
					--,
					--(SELECT Amount FROM sFee.tFeeSetup S WHERE S.Id = @rId 
					----S.ClassId = VA.AcademicId
					----AND S.AdmissionCategoryId = VA.AdmissionCategoryId
					--) AS FeeSetupAmount	   
			FROM sStudent.vStudentAcademic VA	   
			WHERE ClassId = @rClassId AND AdmissionCategoryId = @rAdmissionCategoryId AND VA.BatchId = @rBatchId
			   ) ST WHERE (@rAmount + ISNULL(ST.AllocationAmount,0) - ISNULL(ST.PaidAmount,0) < 0))
			   
			   select @rId as Result
			   ELSE
			   SELECT 0 as Result
			   RETURN
	 END
	 
		   
		   
		  --WHERE ST.Amount + AllocationAmount - PaidAmount > 0
		  
	 
	 
		    
		  
	 
		      
	 -- SELECT @lFeeSetupId=R.FeeSetupId FROM
	 -- sFee.tFeeSetup FS
		--LEFT JOIN
		--(
		--    SELECT ISNULL(SUM(RD.Amount),0) AS PaidAmount,
		--    RD.FeeSetupId,FA.VariableAmount,FA.AdditionalAmount,FA.DiscountAmount,FA.NotApplicableAmount 
		--    FROM
		--    sFee.tReceipt R INNER JOIN sFee.tReceiptDetail RD ON	RD.ReceiptId = R.Id
		--     LEFT JOIN sFee.tFeeAllocation FA ON FA.FeeSetupId=RD.FeeSetupId AND FA.SourceId=R.SourceId 
		--     AND FA.SourceTypeId=R.SourceTypeId	
		--	WHERE						
		--	 R.IsObsolete = 0 
		--	 GROUP BY RD.FeeSetupId,R.SourceId,R.SourceTypeId,FA.VariableAmount,FA.AdditionalAmount,
		--	 FA.DiscountAmount,FA.NotApplicableAmount
		
		--) R ON R.FeeSetupId = FS.Id 
		--where ISNULL(R.FeeSetupId,0)=@rId 
		--AND (@rAmount +  ISNULL(R.VariableAmount,0) + ISNULL(R.AdditionalAmount,0.00) -  ISNULL(R.DiscountAmount,0)-ISNULL(R.NotApplicableAmount,0) -ISNULL(R.PaidAmount,0))<0
		--BEGIN
		

--	select @lFeeSetupId as Result
		--	RETURN
		--END
		
	END
	 
 IF(@rId = 0)	
BEGIN
	
	DECLARE @lNextNumber BIGINT     
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sFee.tFeeSetup', 0, 1, 1,@outNextNumber = @lNextNumber output

	INSERT INTO sFee.tFeeSetup
		(
		   Id,
           ClassId,
           AdmissionCategoryId,
           BatchId,
           FeeId,
           IsOptional,
           IsVariable,
           Amount,
           StartDate,
           EndDate,
           ReceiptBookId,
           CreatedUserId,
           CreatedDateTime,
           IsServiceTax,
           CollectionGroupId,
           FeeDuration,
           LevelAmount
		   --LateFeeRuleId
        )
	VALUES
		(
			@lNextNumber,
			@rClassId,
			@rAdmissionCategoryId,
            @rBatchId,
            @rFeeId,
            @rIsOptional,
            @rIsVariable,
            @rAmount,
            @rStartDate,
            @rEndDate,
            @rReceiptBookId,
            @rCreatedUserId,
			sCommon.fGetDate(),
			@rIsServiceTax,
			@rCollectionGroupId,
			@rFeeDuration,
			@rLevelAmount
			--@rLateFeeRuleId
		)

		SELECT 1 AS Result
	END	 
	 ELSE
	 BEGIN
	 
	 SET @lNextNumber = @rId
	    UPDATE  sFee.tFeeSetup
	    SET
			 --ClassId=@rClassId,
			 --AdmissionCategoryId=@rAdmissionCategoryId,
    --         BatchId=@rBatchId,
             IsOptional=@rIsOptional,
             IsVariable=@rIsVariable,
             Amount=@rAmount,
             StartDate=@rStartDate,
             EndDate=@rEndDate,
             ReceiptBookId=@rReceiptBookId,
             UpdatedUserId=@rUpdatedUserId,
			 UpdatedDateTime=sCommon.fGetDate(),
			 IsServiceTax=@rIsServiceTax,
			 CollectionGroupId=@rCollectionGroupId,
			 FeeDuration=@rFeeDuration,
			 LevelAmount=@rLevelAmount
			 --LateFeeRuleId=@rLateFeeRuleId
	      WHERE (Id = @rId)
	       --AND (FeeId=@rFeeId) 

	      SELECT 11 AS Result   
	 END  
	
	If Not Exists(Select 1 from sSystem.tPortalSync where OrgGroupId=@rOrgGRoupId)
	BEGIN
		Insert INto sSystem.tPortalSync 
		(
			OrgGRoupId,
			FeeChange
		)
		Values
		(
			@rOrgGRoupId,
			1
		)
	END
	Else
	BEGIN
		Update sSystem.tPortalSync 
		Set
			FeeChange=1
		Where OrgGroupId=@rOrgGroupId
		
	END

	EXEC [sFee].[pFeeProcessGenerate] @rOrgId,@rBatchId,@rClassId,NULL,NULL,@rCreatedUserId,@lNextNumber

	END TRY
	
	BEGIN CATCH 
		
		SELECT -1 AS Result
	END CATCH
END
GO
PRINT N'Altering [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

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

END
GO
PRINT N'Altering [sHostel].[pHostelAdmissionGet]...';


GO
ALTER PROCEDURE [sHostel].[pHostelAdmissionGet]
          
           @rHostelId int,
           @rOrgId int,
           @rSourceTypeId smallint,
           @rCode nvarchar(20),
           @rFromAllocateDate date,
           @rToAllocateDate date,
           @rToVacantDate date='',
           @rFromVacantDate date='',
           @rSUID nvarchar(50),
           @rOrgGroupBatchId int       
AS
SET NOCOUNT ON

BEGIN
IF (@rSourceTypeId = 95)
	BEGIN 
		SELECT
			OM.DisplayTitle AS OrganizationName,
			'Employee' AS SourceType,
			Emp.Code AS SourceCode, 
			'' AS SUId,
			Emp.EmployeeName AS SourceName,
			Emp.DepartmentName AS ClassDepartmentName,
			HA.SourceTypeId,
			HA.SourceId,
			HA.AllocateDate,
			(CASE WHEN HA.VacantDate = '1900-01-01' THEN ''
			ELSE HA.VacantDate END) AS VacantDate,	
			ISNULL(HA.VacantReason,'') AS VacantReason,
			ISNULL(RM.Title, '') AS RoomName

		FROM 
			sHostel.tHostelAdmission HA 
			INNER JOIN sHrm.vExtEmployeeMaster Emp ON Emp.Id = HA.SourceId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = Emp.OrgId
			LEFT JOIN sHostel.tAssignRoom AR ON AR.SourceId = Emp.EmployeeId AND AR.SourceTypeId = 95 AND AR.OrgGroupBatchId = HA.OrgGroupBatchId 
			LEFT JOIN sHostel.tRoomMaster RM ON RM.HostelId = HA.Hosteld AND RM.Id = AR.RoomId	 

		WHERE 
			(HA.Hosteld=@rHostelId)
			AND ((OM.Id=@rOrgId) OR (@rOrgId=0))
			AND ((Emp.Code LIKE @rCode) OR (ISNULL(@rCode,'')=''))
			AND ((HA.AllocateDate >= @rFromAllocateDate) OR (ISNULL(@rFromAllocateDate,'') = ''))
			AND ((HA.AllocateDate <= @rToAllocateDate) OR (ISNULL(@rToAllocateDate,'') = ''))
			AND ((HA.VacantDate >= @rFromVacantDate) OR (ISNULL(@rFromVacantDate,'') = ''))
			AND ((HA.VacantDate <= @rToVacantDate) OR (ISNULL(@rToVacantDate,'') = ''))
			AND HA.OrgGroupBatchId=@rOrgGroupBatchId
		--ORDER BY  HA.AllocateDate DESC
	END

ELSE IF (@rSourceTypeId = 2003)
	BEGIN
		SELECT
			OM.DisplayTitle AS OrganizationName,
			'Student' AS SourceType,
			SM.Code AS SourceCode, 
			SM.SUId,
			SM.LastName + ' ' + SM.FirstName  AS SourceName,
			sStudent.fStudentCurrentDivisionGet(SM.StudentId) AS ClassDepartmentName,
			HA.SourceTypeId,
			HA.SourceId,
			HA.AllocateDate,
			(CASE WHEN HA.VacantDate = '1900-01-01' THEN ''
			ELSE HA.VacantDate END) AS VacantDate,	
			ISNULL(HA.VacantReason,'') AS VacantReason,
			ISNULL(RM.Title, '') AS RoomName

		FROM 
			sHostel.tHostelAdmission HA
			INNER JOIN sStudent.vStudentAcademic SM ON SM.StudentId = HA.SourceId AND SM.OrgGroupBatchId=@rOrgGroupBatchId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SM.OrgId
			INNER JOIN sSetup.tBatchMaster BM ON BM.OrgGroupBatchId = SM.OrgGroupBatchId AND BM.Id = SM.BatchId 
			LEFT JOIN sHostel.tAssignRoom AR ON AR.SourceId = SM.StudentId AND AR.SourceTypeId = 2003 AND AR.OrgGroupBatchId = HA.OrgGroupBatchId
			LEFT JOIN sHostel.tRoomMaster RM ON RM.HostelId = HA.Hosteld AND RM.Id = AR.RoomId
			
		WHERE 
	
			(HA.Hosteld=@rHostelId)
			AND ((OM.Id=@rOrgId) OR (@rOrgId=0))
			AND ((SM.Code LIKE @rCode) OR (ISNULL(@rCode,'')='')) 
			AND ((HA.AllocateDate >= @rFromAllocateDate) OR (ISNULL(@rFromAllocateDate,'') = ''))
			AND ((HA.AllocateDate <= @rToAllocateDate) OR (ISNULL(@rToAllocateDate,'') = ''))
			AND ((HA.VacantDate >= @rFromVacantDate) OR (ISNULL(@rFromVacantDate,'') = ''))
			AND ((HA.VacantDate <= @rToVacantDate) OR (ISNULL(@rToVacantDate,'') = ''))
			AND ((SM.SUId=@rSUID) OR (ISNULL(@rSUID,'') = ''))
			AND HA.OrgGroupBatchId=@rOrgGroupBatchId
			AND BM.IsInContext = 1
			--order by  HA.AllocateDate desc	
	END

ELSE
	BEGIN
		SELECT
			OM.DisplayTitle AS OrganizationName,
			'Employee' AS SourceType,
			Emp.Code AS SourceCode, 
			'' AS SUId,
			Emp.EmployeeName AS SourceName,
			Emp.DepartmentName AS ClassDepartmentName,
			HA.SourceTypeId,
			HA.SourceId,
			HA.AllocateDate,
			(CASE WHEN HA.VacantDate = '1900-01-01' THEN ''
			ELSE HA.VacantDate END) AS VacantDate,	
			ISNULL(HA.VacantReason,'') AS VacantReason,
			ISNULL(RM.Title, '') AS RoomName

		FROM 
			sHostel.tHostelAdmission HA 
			INNER JOIN sHrm.vExtEmployeeMaster Emp ON Emp.Id = HA.SourceId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = Emp.OrgId
			LEFT JOIN sHostel.tAssignRoom AR ON AR.SourceId = Emp.EmployeeId AND AR.SourceTypeId = 95 AND AR.OrgGroupBatchId = HA.OrgGroupBatchId 
			LEFT JOIN sHostel.tRoomMaster RM ON RM.HostelId = HA.Hosteld AND RM.Id = AR.RoomId	 

		WHERE 
			(HA.Hosteld=@rHostelId)
			AND ((OM.Id=@rOrgId) OR (@rOrgId=0))
			AND ((Emp.Code LIKE @rCode) OR (ISNULL(@rCode,'')=''))
			AND ((HA.AllocateDate >= @rFromAllocateDate) OR (ISNULL(@rFromAllocateDate,'') = ''))
			AND ((HA.AllocateDate <= @rToAllocateDate) OR (ISNULL(@rToAllocateDate,'') = ''))
			AND ((HA.VacantDate >= @rFromVacantDate) OR (ISNULL(@rFromVacantDate,'') = ''))
			AND ((HA.VacantDate <= @rToVacantDate) OR (ISNULL(@rToVacantDate,'') = ''))
			AND HA.OrgGroupBatchId=@rOrgGroupBatchId

			UNION ALL


			SELECT
			OM.DisplayTitle AS OrganizationName,
			'Student' AS SourceType,
			SM.Code AS SourceCode, 
			SM.SUId,
			SM.LastName + ' ' + SM.FirstName  AS SourceName,
			sStudent.fStudentCurrentDivisionGet(SM.StudentId) AS ClassDepartmentName,
			HA.SourceTypeId,
			HA.SourceId,
			HA.AllocateDate,
			(CASE WHEN HA.VacantDate = '1900-01-01' THEN ''
			ELSE HA.VacantDate END) AS VacantDate,	
			ISNULL(HA.VacantReason,'') AS VacantReason,
			ISNULL(RM.Title, '') AS RoomName

		FROM 
			sHostel.tHostelAdmission HA
			INNER JOIN sStudent.vStudentAcademic SM ON SM.StudentId = HA.SourceId AND SM.OrgGroupBatchId=@rOrgGroupBatchId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SM.OrgId
			INNER JOIN sSetup.tBatchMaster BM ON BM.OrgGroupBatchId = SM.OrgGroupBatchId AND BM.Id = SM.BatchId 
			LEFT JOIN sHostel.tAssignRoom AR ON AR.SourceId = SM.StudentId AND AR.SourceTypeId = 2003 AND AR.OrgGroupBatchId = HA.OrgGroupBatchId
			LEFT JOIN sHostel.tRoomMaster RM ON RM.HostelId = HA.Hosteld AND RM.Id = AR.RoomId
			
		WHERE 
	
			(HA.Hosteld=@rHostelId)
			AND ((OM.Id=@rOrgId) OR (@rOrgId=0))
			AND ((SM.Code LIKE @rCode) OR (ISNULL(@rCode,'')='')) 
			AND ((HA.AllocateDate >= @rFromAllocateDate) OR (ISNULL(@rFromAllocateDate,'') = ''))
			AND ((HA.AllocateDate <= @rToAllocateDate) OR (ISNULL(@rToAllocateDate,'') = ''))
			AND ((HA.VacantDate >= @rFromVacantDate) OR (ISNULL(@rFromVacantDate,'') = ''))
			AND ((HA.VacantDate <= @rToVacantDate) OR (ISNULL(@rToVacantDate,'') = ''))
			AND ((SM.SUId=@rSUID) OR (ISNULL(@rSUID,'') = ''))
			AND HA.OrgGroupBatchId=@rOrgGroupBatchId
			AND BM.IsInContext = 1
			--order by  HA.AllocateDate desc
	END
END
GO
PRINT N'Altering [sHostel].[pHostelStudentGatePassNewGet]...';


GO
ALTER PROCEDURE [sHostel].[pHostelStudentGatePassNewGet]
          
           @rId int,
           @rOrgId int=0,
           @rHostelGatePassReasonId int=0,
           @rFromGatePassDate datetime='',
           @rToGatePassDate datetime='',
           @rEntryModeStatusId smallint=0,
           @rCode nvarchar(20)='',
           @rIsPrintView bit=0,
           @rOrgGroupId int=0,
           @rOrgGroupBatchId int=0,
           @rRoomId int =0,
           @rHostelId int =0
AS
SET NOCOUNT ON
DECLARE @lIsOnPrePrinted bit = 0
DECLARE @lConfigValue nvarchar(50)
BEGIN

--Select @rHostelId
	 SELECT @lConfigValue = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 232 AND SourceTypeId = 2010 AND SourceId = @rOrgGroupId
		IF (@lConfigValue IS NULL) OR (@lConfigValue = 'Default')
		BEGIN
		SET @lIsOnPrePrinted = 0
		END
		ELSE IF (@lConfigValue = 'Blank')
		BEGIN
		SET @lIsOnPrePrinted = 1
	END
	

			SELECT
				HSGP.Id, 
				HSGP.Id AS HostelStudentGatePassId,
				vSA.Code,
				--vSA.FirstName+' '+vSA.LastName AS Name,
				VSA.Name,
				VSA.ClassName+' - '+VSA.DivisionName AS Class,
				HSGP.StudentId,
				HSGP.RelationshipId,		
				RM.Title AS Relationship,
				HSGP.Relation,
				HSGP.VisitorName,
				HSGP.VisitorMobile,
				HSGP.HostelGatePassReasonId,
				HGRM.Title AS HostelGetPassReason,
				HSGP.Remark,
				--HSGP.VisitorPhoto	,


				--CASE  WHEN @rIsPrintView=1 THEN HSGP.VisitorPhoto		
				--ELSE ISNULL(HSGP.VisitorPhoto, CONVERT(VARBINARY(MAX), 0)) END AS VisitorPhoto,
				--ISNULL(SGP.VisitorPhoto, CONVERT(VARBINARY(MAX), 0)) AS VisitorPhoto,
				HSGP.GatePassDate,
				HSGP.GatePassInDate,
				(CASE  WHEN @rIsPrintView=1 THEN 
				ISNULL(HSGP.VisitorPhoto,0x)
				ELSE ISNULL(HSGP.VisitorPhoto, CONVERT(VARBINARY(MAX), 0x)) END) AS VisitorPhoto,
				CONVERT(varchar(15),CAST(HSGP.GatePassTime AS TIME),100) As GatePassTime,
				ISNULL(CONVERT(varchar(15),CAST(HSGP.GatePassInTime AS TIME),100), '12:00AM') As GatePassInTime,

				--ISNULL(HSGP.GatePassTime,'') As GatePassTime,
				HSGP.EntryModeStatusId,
				HSGP.HostelId,
				SM.Title AS EntryModeStatus,
				OM.Id AS OrgId,
				OM.DisplayTitle AS Organization,
				(CASE  WHEN @rIsPrintView=1 THEN 
				ISNULL(SI.StudentPhoto,0x)		
				ELSE ISNULL(SI.StudentPhoto, CONVERT(VARBINARY(MAX), 0x)) END) AS StudentPhoto,
				--ISNULL(SI.StudentPhoto, CONVERT(VARBINARY(MAX), 0)) AS StudentPhoto,
				ISNULL(U.DisplayTitle,'') AS UserName,
				HSGP.OrgGroupBatchId,
				vSA.SUId,
				HM.Title As HostelName,
				HM.ReportOrgTitle AS ReportOrgTitle,
				HM.SmallAddress1 AS SmallAddress1,
				HM.SmallAddress2 AS SmallAddress2,
				@lIsOnPrePrinted AS IsOnPrePrinted,			
				HRM.Id AS RoomId,
				HRM.Title AS RoomTitle

		FROM 
				sStudent.vStudentAcademic vSA
				INNER JOIN sHostel.tHostelStudentGatePass HSGP ON HSGP.StudentId = vSA.StudentId
				LEFT JOIN sSetup.tOrganizationMaster OM ON OM.Id=vSA.OrgId
				LEFT JOIN sHostel.tHostelGatePassReasonMaster HGRM ON HGRM.Id=HSGP.HostelGatePassReasonId
				LEFT JOIN sCommon.tRelationshipMaster RM ON RM.Id=HSGP.RelationshipId
				LEFT JOIN sCommon.tStatusMaster SM ON SM.Id=HSGP.EntryModeStatusId
				LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId=vSA.StudentId
				LEFT JOIN sSecurity.tUser U	ON U.Id=HSGP.CreatedUserId
				LEFT JOIN  sHostel.tAssignRoom AR ON AR.SourceId=HSGP.StudentId AND ((AR.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))AND (AR.SourceId=HSGP.StudentId)
				LEFT JOIN sHostel.tRoomMaster HRM ON HRM.Id = AR.RoomId
				INNER JOIN sHostel.tHostelMaster HM ON HM.Id = HSGP.HostelId
			
		WHERE 
				OM.OrgGroupId=@rOrgGroupId
				AND HSGP.HostelId = @rHostelId
				AND (vSA.OrgGroupBatchId=@rOrgGroupBatchId) 
				--if student remove from Assign room then it is not display in HostelStudentGatePass
				--AND (AR.SourceId=HSGP.StudentId) 
				AND (HSGP.OrgGroupBatchId=@rOrgGroupBatchId) 
				AND ((HSGP.Id=@rId) OR (@rId=0))
				AND ((vSA.OrgId=@rOrgId) OR (@rOrgId=0))
				AND ((HSGP.GatePassDate>=@rFromGatePassDate) OR (ISNULL(@rFromGatePassDate,'')=''))
				AND ((HSGP.GatePassDate<=@rToGatePassDate) OR (ISNULL(@rToGatePassDate,'')=''))
				AND ((HSGP.EntryModeStatusId=@rEntryModeStatusId) OR (@rEntryModeStatusId=0))
				AND ((vSA.Code=@rCode) OR (ISNULL(@rCode,'')=''))
				AND ((HSGP.HostelGatePassReasonId=@rHostelGatePassReasonId) OR (@rHostelGatePassReasonId=0))
				AND ((HRM.Id = @rRoomId) OR (@rRoomId = 0))
				
				ORDER BY HSGP.GatePassDate,HSGP.GatePassTime DESC
END
GO
PRINT N'Altering [sHrm].[pLeaveHierarchyLevelUpdate]...';


GO

ALTER PROCEDURE [sHrm].[pLeaveHierarchyLevelUpdate]
        @rLeaveHierarchyLevelId bigint,   
		@rStatusId int,
		@rHierarchyLevelCount int,
        @rLeaveId bigint,
        @rRemark nvarchar(500),
        @rEmployeeId bigint,
		@rOrgId int
       
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
	
	BEGIN TRANSACTION

	BEGIN
	DECLARE @lActionByEmployeeId bigint
	SELECT @lActionByEmployeeId = EmployeeManagerId from [sHrm].[tEmployeeJobDetail] WHere EmployeeId = @rEmployeeId AND OrgId = @rOrgId

	UPDATE [sHrm].[tLeaveHierarchyLevel] SET StatusId = @rStatusId , Remark = @rRemark WHERE AutoId = @rLeaveHierarchyLevelId

	DECLARE @lLeaveCount int
	SELECT @lLeaveCount = COUNT(AutoId) FROM [sHrm].[tLeaveHierarchyLevel] WHERE LeaveId = @rLeaveId

	IF(@rStatusId = 550)
	BEGIN
		IF(@rHierarchyLevelCount <> @lLeaveCount)
		BEGIN
			 --IF (@rStatusId = 550)
			 --BEGIN
				INSERT INTO [sHrm].[tLeaveHierarchyLevel]
					   (LeaveId
					   ,StatusId
					   ,Remark
					   ,ActionByEmployeeId
					   ,ActionDatetime)
				 VALUES
					   (@rLeaveId
					   ,549
					   ,''
					   ,@lActionByEmployeeId
					   ,sCommon.fGetDate())

						SELECT 0 AS Result 
			 --END
		END
		ELSE
		BEGIN
			 UPDATE [sHrm].[tLeave] SET StatusId = @rStatusId Where Id = @rLeaveId
			 
			 SELECT @rStatusId AS Result 
			
		END
	END
	ELSE
	BEGIN
		UPDATE [sHrm].[tLeave] SET StatusId = @rStatusId Where Id = @rLeaveId
			--IF(@rHierarchyLevelCount = @lLeaveCount)
			--BEGIN
				DELETE FROM [sHrm].[tLeaveHierarchyLevel] Where LeaveId = @rLeaveId AND ActionByEmployeeId = @lActionByEmployeeId
			--END
		SELECT @rStatusId AS Result 
	END
	
	END 	   
	COMMIT TRANSACTION
	END TRY	
	BEGIN CATCH
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH
END
GO
PRINT N'Altering [sMis].[pRptClassCapacityGet]...';


GO
ALTER PROCEDURE [sMis].[pRptClassCapacityGet]
	
		@rBuilder1 nvarchar(max)='',
		@rBuilder2 nvarchar(max)='', 
		--@rBatchId int,
		@rClassId int,
		@rDepartmentId int,
		@rOrgMainGroupId int,
		@rOrgSubGroupId int,
		@rOrgId smallint,
		@rStrOrgMainGroupId nvarchar(max),
		@rStrOrgSubGroupId nvarchar(max),
		@rStrOrgId nvarchar(max),
		@rStrDepartmentId nvarchar(max),
		@rStrClassId nvarchar(max),
		@rOrgGroupId int,
		@rOrgGroupBatchId int,
		@rIsTestMainGroup bit =0,
		@rIsTestSubGroup bit =0,
		@rIsTestOrg bit=0,
		@rIsTestClass bit=0,
		@rIsTestDepartment bit=0,
		@rIsDisplayOrgGroup bit=0,
		@rBatchGroupId int=0,
		@rStatusId int=0,
		@rStudentStatusId int=0,
		@rUptoDate datetime = ''
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
	SELECT 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			@rIsTestMainGroup AS IsTestMainGroup,
			@rIsTestSubGroup AS IsTestSubGroup,
			@rIsTestOrg AS IsTestOrg,
			@rIsTestClass AS IsTestClass,
			@rIsTestDepartment AS IsTestDepartment,
			@rIsDisplayOrgGroup AS IsDisplayOrgGroup,
			CM.Id AS ClassId,
			CM.DisplayTitle AS ClassName,
			CM.OrderIndex,
			CM.DepartmentId,
			DM.DisplayTitle AS DepartmentName,
			OMGM.Id AS OrgMainGroupId,
			OMGM.Title AS OrgMainGroupTitle,
			OSGM.Id AS OrgSubGroupId,
			OSGM.Title AS OrgSubGroupTitle,
			OM.Id AS OrgId,
			OM.DisplayTitle AS OrgDisplayTitle,
			(SELECT COUNT(1) FROM sSetup.tDivisionMaster DM WHERE DM.ClassId=CM.Id) AS DivisionCount,
			ISNULL(CM.Capacity,0) AS Capacity,
			
			(SELECT ISNULL(count(1),0)  FROM sStudent.tAcademic A 
			INNER JOIN sStudent.tStudentMaster SM ON A.StudentId = SM.Id 
			INNER JOIN sSetup.tBatchMaster BM ON A.BatchId = BM.Id
			INNER JOIN sSetup.tBatchGroupMaster BGM ON BGM.Id = BM.BatchGroupId 
			INNER JOIN sStudent.tStudentAdmission  SA on SA.StudentId = SM.Id 
			WHERE A.ClassId = CM.Id 
			AND SA.AdmissionDate <= @rUptoDate
			AND BM.OrgGroupBatchId = @rOrgGroupBatchId
			AND ((BGM.Id = @rBatchGroupId) OR (@rBatchGroupId = 0)) 
			AND ((SM.StatusId = @rStudentStatusId) OR (@rStudentStatusId=0))) 
			AS CurrentStrength,
			
			(SELECT ISNULL(count(1),0) FROM sStudent.tAcademic A 
			INNER JOIN sStudent.tStudentMaster SM ON A.StudentId = SM.Id 
			INNER JOIN sStudent.tStudentAdmission  SA on SA.StudentId = SM.Id AND SA.leftDate <= @rUptoDate
			INNER JOIN sSetup.tBatchMaster BM ON A.BatchId = BM.Id  
			AND BM.OrgId=CM.OrgId AND BM.OrgGroupBatchId=@rOrgGroupBatchId
			WHERE  A.ClassId = CM.Id)
			AS AdmissionLeft,
			
			(SELECT ISNULL(count(1),0) FROM sStudent.tAcademic A 
			INNER JOIN sStudent.tStudentMaster SM ON A.StudentId = SM.Id 
			INNER JOIN sStudent.tStudentAdmission  SA on SA.StudentId = SM.Id AND SA.AdmissionDate = @rUptoDate
			INNER JOIN sSetup.tBatchMaster BM ON A.BatchId = BM.Id  
			AND BM.OrgId=CM.OrgId AND BM.OrgGroupBatchId=@rOrgGroupBatchId AND SM.StatusId = 1
			WHERE  A.ClassId = CM.Id) 
			AS AdmissionGiven,

			(SELECT ISNULL(count(1),0) FROM sStudent.tAcademic A 
			INNER JOIN sStudent.tStudentMaster SM ON A.StudentId = SM.Id 
			INNER JOIN sSetup.tBatchMaster BM ON A.BatchId = BM.Id 
			AND BM.OrderIndex = (SELECT TOP 1 BM.OrderIndex -1 FROM sSetup.tBatchMaster BM	INNER JOIN  sSetup.tOrgGroupBatchMaster ORGM ON BM.OrgGroupBatchId=ORGM.Id
			WHERE BM.OrgId=CM.OrgId 
			AND BM.OrgGroupBatchId=@rOrgGroupBatchId ORDER BY BM.OrderIndex DESC
			) WHERE A.ClassId = CM.Id AND SM.StatusId = 1) 
			AS PreviousStrength
	FROM 
			sSetup.tClassMaster CM
			INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id=CM.DepartmentId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = DM.OrgId
			INNER JOIN sSetup.tOrgSubGroupMaster OSGM ON OSGM.Id = OM.OrgSubGroupId
			INNER JOIN sSetup.tOrgMainGroupMaster OMGM ON OMGM.Id = OSGM.OrgMainGroupId
	WHERE 
			((CM.Id=@rClassId) OR (@rClassId=0))
			AND	((CM.DepartmentId = @rDepartmentId) OR (@rDepartmentId = 0))
			AND ((OMGM.Id=@rOrgMainGroupId) OR (@rOrgMainGroupId=0))
			AND ((OSGM.Id=@rOrgSubGroupId) OR (@rOrgSubGroupId=0))
			AND ((OM.Id=@rOrgId) OR (@rOrgId=0))
			AND ((OM.OrgGroupId = @rOrgGroupId))
			AND (OMGM.Id IN (SELECT cast(item as int) FROM  sCommon.fnsplit(	@rStrOrgMainGroupId,','))OR @rStrOrgMainGroupId='')
			AND (OSGM.Id IN (SELECT cast(item as int) FROM  sCommon.fnsplit(	@rStrOrgSubGroupId,','))OR @rStrOrgSubGroupId='')
			AND (OM.Id IN (SELECT cast (item as int) FROM  sCommon.fnsplit ( @rStrOrgId,','))OR @rStrOrgId='')
			AND (DM.Id IN (SELECT cast(item as int) FROM  sCommon.fnsplit  (@rStrDepartmentId,','))OR @rStrDepartmentId='')
			AND (CM.Id IN (SELECT cast(item as int) FROM  sCommon.fnsplit  (@rStrClassId,','))OR @rStrClassId='')
			ORDER BY CM.OrderIndex ASC
END
GO
PRINT N'Altering [sProcurement].[pStockIssueRequestDetailGet]...';


GO
ALTER PROCEDURE [sProcurement].[pStockIssueRequestDetailGet]
	@rOrgGroupId int,
	@rStockIssueRequestId [int] = 0
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	 SELECT 
			ISNULL(SIRD.Id,0) As ID,
			ISNULL(SIRD.StockIssueRequestId,0) AS StockIssueRequestId ,
			SIRD.StockItemId,
			ISNULL(SIRD.RequestedQuantity,0) As RequestedQuantity,
			SIRD.Remark,
			SIRD.UpdatedUserID,
			SIRD.UpdatedDateTime,
			SIM.Code ItemCode,
			SIM.Title ItemTitle,
			SU.Code UomCode,
			SU.Title UomTitle,
			ISNULL(SU.Id,0)AS  IssueStockUomId,
			SIM.IsBatchWiseTracking,
			SIM.Code StockItemCode,
			SIM.Title StockItemName,
			SU.Title Uom,
		    '' as Number,
			SIRD.IssuedQuantity,
			SIR.Number,
			SIR.CreatedDateTime as 'ReqDate',
			(
				Select sum( AvailableQuantity)
				FROM sProcurement.tStockBatch SB
				INNER JOIN sIP.tStockItemMaster SIM ON SIM.Id = SB.StockItemID
				INNER JOIN sProcurement.tStockIssueRequestDetail SIRD1 ON SIRD1.StockItemId = SIM.Id
				WHERE ((SIRD1.StockIssueRequestId = @rStockIssueRequestId) OR (@rStockIssueRequestId = 0))
				AND SIRD1.OrgGroupId = @rOrgGroupId  AND SB.StockItemId = SIRD.StockItemId
			) AS AvailableQuantity,
			EM.Code AS ReqEmployeeCode
 
	   FROM 
			sProcurement.tStockIssueRequestDetail SIRD
	   INNER JOIN  sIP.tStockItemMaster SIM
		ON SIM.Id = SIRD.StockItemId
		INNER JOIN sFinanceCommon.tStockUomMaster  SU
		ON SU.Id = SIM.IssueStockUomId
		INNER JOIN sProcurement.tStockIssueRequest SIR ON SIR.ID=SIRD.StockIssueRequestId
		Left Join sCommon.vEmployeeMaster EM ON SIR.CreatedUserId=EM.UserId
		--LEFT JOIN sProcurement.tStockBatch SB ON SB.StockItemID = SIM.Id AND SB.Number!=''
	  WHERE ((SIRD.StockIssueRequestId = @rStockIssueRequestId) OR (@rStockIssueRequestId = 0))
	  AND SIRD.OrgGroupId = @rOrgGroupId
END
GO
PRINT N'Altering [sProcurement].[pStockTransferQueueListing]...';


GO
/******************************************************************************
	Purpose          : To get Pending Records for Transfer/Issue Requests.
	Created date     : 13 May 2012
	Author           : Rajendra Patel
	Copyright©       : Copyright © Sapphire Software
	Last Change Desc : ST.Number is addedremoved
	Test script      : EXECUTE [sProcurement].[pStockTransferQueueListing] @rStatus = 'All', @rFromDate = '5/17/2009', @rToDate = '5/17/2010', @rType = 'All'
*******************************************************************************/
ALTER PROCEDURE [sProcurement].[pStockTransferQueueListing]
	(
	    @rOrgGroupId int,
		@rStatus Nvarchar(30) = '', 
		@rFromDate Nvarchar(100) = '1/1/2009', 
		@rToDate Nvarchar(100) = '1/1/2009', 
		@rType Nvarchar(30) = '',
		@rStoreLocationId int,
		@rToDepartmentId int=0
	)
AS

SET NOCOUNT ON
BEGIN
IF @rStatus = 'Pending'
BEGIN
	IF @rType = 'Tran'
		BEGIN
		   SELECT 
			   SR.Number AS [RequestNo],  
			   SR.CreatedDateTime AS [RequestDate],  
			   SR.RequestedByName AS [RequestedBy], 
			   'Tran'AS [Type], 
			   LM.Title AS [Location],
			   0 AS DepartmentId,
			   ST.Number AS [TransferNo],
			   'Pending' AS [Status], 
			   SUM(ISNULL(SRD.RequestedQuantity, 0)) - SUM(ISNULL(STD.TransferredQuantity, 0)) AS [PendingQty],
			   SR.Id [ReqId]
			   --ST.Id [TransferId]		   
		   FROM  
				sProcurement.tStockTransferRequest SR
					INNER JOIN sProcurement.tStockTransferRequestDetail SRD
					ON SR.Id = SRD.StockTransferRequestId
					LEFT OUTER JOIN sProcurement.tStockTransfer ST
					ON ST.StockTransferRequestId = SR.id
					LEFT JOIN sProcurement.tStockTransferDetail STD
					ON ST.Id = STD.StockTransferId
					INNER JOIN sIp.tStoreLocationMaster LM 
					ON SR.ToStoreLocationId = LM.Id
					WHERE 
					--SR.OrgGroupId = @rOrgGroupId AND 
					SR.FromStoreLocationId =  @rStoreLocationId
					
					GROUP BY 
						SR.Number, SR.CreatedDateTime, SR.RequestedByName, LM.Title, ST.Number, SR.Id, ST.Id 
					HAVING 
						SUM(ISNULL(SRD.RequestedQuantity, 0)) - SUM(ISNULL(STD.TransferredQuantity, 0)) > 0
						AND SR.CreatedDateTime BETWEEN @rFromDate AND @rToDate
		END
	IF @rType = 'Issue'
		BEGIN
		   SELECT 
			   SR.Number AS [RequestNo],  
			   SR.CreatedDateTime AS [RequestDate],  
			   SR.RequestedByName AS [RequestedBy], 
			   'Issue'AS [Type], 
			   ISNULL(LM.Title,'') AS [Location], 
			   ISNULL( LM.Id,0) AS DepartmentId,
			   ST.Number AS [TransferNo],
			   'Pending' AS [Status], 
			   SUM(ISNULL(SRD.RequestedQuantity, 0)) - SUM(ISNULL(STD.IssuedQuantity, 0)) AS PendingQty, 
			   SR.Id [ReqId]
			   --ST.Id [TransferId]
		   FROM  
				sProcurement.tStockIssueRequest SR
					INNER JOIN sProcurement.tStockIssueRequestDetail SRD
					ON SR.Id = SRD.StockIssueRequestId
					LEFT OUTER JOIN sProcurement.tStockIssue ST
					ON ST.StockIssueRequestId = SR.id
					LEFT JOIN sProcurement.tStockIssueDetail STD
					ON ST.Id = STD.StockIssueId
					LEFT JOIN sSetup.tDepartmentMaster LM 
					ON SR.ToDepartmentId = LM.Id
					WHERE
					 --SR.OrgGroupId = @rOrgGroupId AND 
					 SR.FromStoreLocationId =  @rStoreLocationId
					AND (SR.ToDepartmentId= @rToDepartmentId OR @rToDepartmentId =0 )
					GROUP BY 
						SR.Number, SR.CreatedDateTime, SR.RequestedByName, LM.Title,LM.Id, ST.Number, SR.Id, ST.Id 
					HAVING 
						SUM(ISNULL(SRD.RequestedQuantity, 0)) - SUM(ISNULL(STD.IssuedQuantity, 0)) > 0
						AND SR.CreatedDateTime BETWEEN @rFromDate AND @rToDate
		END
	IF @rType = 'All'
		BEGIN
		SELECT 
			   SR.Number AS [RequestNo],  
			   SR.CreatedDateTime AS [RequestDate],  
			   SR.RequestedByName AS [RequestedBy], 
			   'Tran'AS [Type], 
			   LM.Title AS [Location], 
			   0 AS DepartmentId,
			   ST.Number AS [TransferNo],
			   'Pending' AS [Status],
			   SUM(ISNULL(SRD.RequestedQuantity, 0)) - SUM(ISNULL(STD.TransferredQuantity, 0)) AS PendingQty,
			   SR.Id [ReqId]
			   --ST.Id [TransferId]
			   FROM  
					sProcurement.tStockTransferRequest SR
						INNER JOIN sProcurement.tStockTransferRequestDetail SRD
						ON SR.Id = SRD.StockTransferRequestId
						LEFT OUTER JOIN sProcurement.tStockTransfer ST
						ON ST.StockTransferRequestId = SR.id
						LEFT JOIN sProcurement.tStockTransferDetail STD
						ON ST.Id = STD.StockTransferId
						INNER JOIN sIp.tStoreLocationMaster LM 
						ON SR.ToStoreLocationId = LM.Id
						WHERE 
						--SR.OrgGroupId = @rOrgGroupId AND
						 SR.FromStoreLocationId =  @rStoreLocationId 
						GROUP BY 
							SR.Number, SR.CreatedDateTime, SR.RequestedByName, LM.Title, ST.Number, SR.Id, ST.Id
						HAVING 
							SUM(ISNULL(SRD.RequestedQuantity, 0)) - SUM(ISNULL(STD.TransferredQuantity, 0)) > 0
							AND SR.CreatedDateTime BETWEEN @rFromDate AND @rToDate
			UNION ALL
			   SELECT 
			   SR.Number AS [RequestNo],  
			   SR.CreatedDateTime AS [RequestDate],  
			   SR.RequestedByName AS [RequestedBy], 
			   'Issue'AS [Type], 
			   ISNULL(LM.Title,'') AS [Location], 
			   ISNULL( LM.Id,0) AS DepartmentId,
			   ST.Number AS [TransferNo],
			   'Pending' AS [Status], 
			   SUM(ISNULL(SRD.RequestedQuantity, 0)) - SUM(ISNULL(STD.IssuedQuantity, 0)) AS PendingQty,
			   SR.Id [ReqId]
			  -- ST.Id [TransferId]
		   FROM  
				sProcurement.tStockIssueRequest SR
					INNER JOIN sProcurement.tStockIssueRequestDetail SRD
					ON SR.Id = SRD.StockIssueRequestId
					LEFT JOIN sProcurement.tStockIssue ST
					ON ST.StockIssueRequestId = SR.id
					LEFT JOIN sProcurement.tStockIssueDetail STD
					ON ST.Id = STD.StockIssueId
					LEFT JOIN sSetup.tDepartmentMaster LM 
					ON SR.ToDepartmentId = LM.Id
					WHERE 
					--SR.OrgGroupId = @rOrgGroupId AND
					 SR.FromStoreLocationId =  @rStoreLocationId
						 AND (SR.ToDepartmentId= @rToDepartmentId OR @rToDepartmentId =0 )
					GROUP BY 
						SR.Number, SR.CreatedDateTime, SR.RequestedByName, LM.Title,LM.Id, ST.Number, SR.Id, ST.Id
					HAVING 
						SUM(ISNULL(SRD.RequestedQuantity, 0)) - SUM(ISNULL(STD.IssuedQuantity, 0)) > 0
						AND SR.CreatedDateTime BETWEEN @rFromDate AND @rToDate
						Order by SR.Number
		END			
	END
	
	
IF @rStatus = 'Completed'
BEGIN
	IF @rType = 'Tran'
		BEGIN
		   SELECT 
			   SR.Number AS [RequestNo],  
			   SR.CreatedDateTime AS [RequestDate],  
			   SR.RequestedByName AS [RequestedBy], 
			   'Tran'AS [Type], 
			   LM.Title AS [Location],
			   0 AS DepartmentId,
			   ST.Number AS [TransferNo],
			   'Completed' AS [Status], 
			   SUM(ISNULL(SRD.RequestedQuantity, 0)) - SUM(ISNULL(STD.TransferredQuantity, 0)) AS [PendingQty], 
			   SR.Id [ReqId]
			   --ST.Id [TransferId]		   
		   FROM
				sProcurement.tStockTransferRequest SR
					INNER JOIN sProcurement.tStockTransferRequestDetail SRD
					ON SR.Id = SRD.StockTransferRequestId
					INNER JOIN sProcurement.tStockTransfer ST
					ON ST.StockTransferRequestId = SR.id
					INNER JOIN sProcurement.tStockTransferDetail STD
					ON ST.Id = STD.StockTransferId
					INNER JOIN sIp.tStoreLocationMaster LM 
					ON SR.ToStoreLocationId = LM.Id
					WHERE 
					--SR.OrgGroupId = @rOrgGroupId AND 
					SR.FromStoreLocationId =  @rStoreLocationId
					GROUP BY 
						SR.Number, SR.CreatedDateTime, SR.RequestedByName, LM.Title, ST.Number, SR.Id, ST.Id 
					HAVING 
						SUM(ISNULL(SRD.RequestedQuantity, 0)) - SUM(ISNULL(STD.TransferredQuantity, 0)) <= 0
						AND SR.CreatedDateTime BETWEEN @rFromDate AND @rToDate
						Order by  SR.Id,SR.Number
		END
	IF @rType = 'Issue'
		BEGIN
		   SELECT 
			   SR.Number AS [RequestNo],  
			   SR.CreatedDateTime AS [RequestDate],  
			   SR.RequestedByName AS [RequestedBy], 
			   'Issue'AS [Type], 
			   ISNULL(LM.Title,'') AS [Location], 
			   0 AS DepartmentId,
			   ST.Number AS [TransferNo],
			   'Completed' AS [Status], 
			   SUM(ISNULL(SRD.RequestedQuantity, 0)) - SUM(ISNULL(STD.IssuedQuantity, 0)) AS PendingQty, 
			   SR.Id [ReqId]
			   --ST.Id [TransferId]
		   FROM  
				sProcurement.tStockIssueRequest SR
					INNER JOIN sProcurement.tStockIssueRequestDetail SRD
					ON SR.Id = SRD.StockIssueRequestId
					INNER JOIN sProcurement.tStockIssue ST
					ON ST.StockIssueRequestId = SR.id
					INNER JOIN sProcurement.tStockIssueDetail STD
					ON ST.Id = STD.StockIssueId
					LEFT JOIN sSetup.tDepartmentMaster LM 
					ON SR.ToDepartmentId = LM.Id
					WHERE 
					--SR.OrgGroupId = @rOrgGroupId AND
					 SR.FromStoreLocationId =  @rStoreLocationId 
						 AND (SR.ToDepartmentId= @rToDepartmentId OR @rToDepartmentId =0 )
					GROUP BY 
						SR.Number, SR.CreatedDateTime, SR.RequestedByName, LM.Title, ST.Number, SR.Id, ST.Id 
					HAVING 
						SUM(ISNULL(SRD.RequestedQuantity, 0)) - SUM(ISNULL(STD.IssuedQuantity, 0)) <= 0
						AND SR.CreatedDateTime BETWEEN @rFromDate AND @rToDate
						Order by  SR.Id,SR.Number
		END
	IF @rType = 'All'
		BEGIN
		SELECT 
			   SR.Number AS [RequestNo],  
			   SR.CreatedDateTime AS [RequestDate],  
			   SR.RequestedByName AS [RequestedBy], 
			   'Tran'AS [Type], 
			   LM.Title AS [Location], 
			   0 AS DepartmentId,
			   ST.Number AS [TransferNo],
			   'Completed' AS [Status],
			   SUM(ISNULL(SRD.RequestedQuantity, 0)) - SUM(ISNULL(STD.TransferredQuantity, 0)) AS PendingQty,
			   SR.Id [ReqId]
			   --ST.Id [TransferId]
			   FROM  
					sProcurement.tStockTransferRequest SR
						INNER JOIN sProcurement.tStockTransferRequestDetail SRD
						ON SR.Id = SRD.StockTransferRequestId
						INNER JOIN sProcurement.tStockTransfer ST
						ON ST.StockTransferRequestId = SR.id
						INNER JOIN sProcurement.tStockTransferDetail STD
						ON ST.Id = STD.StockTransferId
						INNER JOIN sIp.tStoreLocationMaster LM 
						ON SR.ToStoreLocationId = LM.Id
						WHERE 
						--SR.OrgGroupId = @rOrgGroupId AND 
						SR.FromStoreLocationId =  @rStoreLocationId  
						GROUP BY 
							SR.Number, SR.CreatedDateTime, SR.RequestedByName, LM.Title, ST.Number, SR.Id, ST.Id
						HAVING 
							SUM(ISNULL(SRD.RequestedQuantity, 0)) - SUM(ISNULL(STD.TransferredQuantity, 0)) <= 0
							AND SR.CreatedDateTime BETWEEN @rFromDate AND @rToDate
			UNION ALL
			   SELECT 
			   SR.Number AS [RequestNo],  
			   SR.CreatedDateTime AS [RequestDate],  
			   SR.RequestedByName AS [RequestedBy], 
			   'Issue'AS [Type], 
			   ISNULL(LM.Title,'') AS [Location], 
			   ISNULL( LM.Id,0) AS DepartmentId,
			   ST.Number AS [TransferNo],
			   'Completed' AS [Status], 
			   SUM(ISNULL(SRD.RequestedQuantity, 0)) - SUM(ISNULL(STD.IssuedQuantity, 0)) AS PendingQty,
			   SR.Id [ReqId]
			  -- ST.Id [TransferId]
		   FROM  
				sProcurement.tStockIssueRequest SR
					INNER JOIN sProcurement.tStockIssueRequestDetail SRD
					ON SR.Id = SRD.StockIssueRequestId
					INNER JOIN sProcurement.tStockIssue ST
					ON ST.StockIssueRequestId = SR.id
					INNER JOIN sProcurement.tStockIssueDetail STD
					ON ST.Id = STD.StockIssueId
					LEFT JOIN sSetup.tDepartmentMaster LM 					
					ON SR.ToDepartmentId = LM.Id
					WHERE 
					--SR.OrgGroupId = @rOrgGroupId AND 
					SR.FromStoreLocationId =  @rStoreLocationId
					GROUP BY 
						SR.Number, SR.CreatedDateTime, SR.RequestedByName, LM.Title,LM.Id, ST.Number, SR.Id, ST.Id
					HAVING 
						SUM(ISNULL(SRD.RequestedQuantity, 0)) - SUM(ISNULL(STD.IssuedQuantity, 0)) <= 0
						AND SR.CreatedDateTime BETWEEN @rFromDate AND @rToDate
						Order by  SR.Id,SR.Number
		END			
	END
	
IF @rStatus = 'All'
BEGIN
	IF @rType = 'Tran'
		BEGIN
		   SELECT 
			   SR.Number AS [RequestNo],  
			   SR.CreatedDateTime AS [RequestDate],  
			   SR.RequestedByName AS [RequestedBy], 
			   'Tran'AS [Type], 
			   LM.Title AS [Location],
			   0 AS DepartmentId,
			   ST.Number AS [TransferNo],
			   'Pending' AS [Status], 
			   SUM(ISNULL(SRD.RequestedQuantity, 0)) - SUM(ISNULL(STD.TransferredQuantity, 0)) AS [PendingQty],
			   SR.Id [ReqId]
			   --ST.Id [TransferId]		   
		   FROM  
				sProcurement.tStockTransferRequest SR
					INNER JOIN sProcurement.tStockTransferRequestDetail SRD
					ON SR.Id = SRD.StockTransferRequestId
					LEFT OUTER JOIN sProcurement.tStockTransfer ST
					ON ST.StockTransferRequestId = SR.id
					LEFT JOIN sProcurement.tStockTransferDetail STD
					ON ST.Id = STD.StockTransferId
					INNER JOIN sIp.tStoreLocationMaster LM 
					ON SR.ToStoreLocationId = LM.Id
						WHERE 
						--SR.OrgGroupId = @rOrgGroupId AND 
						SR.FromStoreLocationId =  @rStoreLocationId 
					GROUP BY 
						SR.Number, SR.CreatedDateTime, SR.RequestedByName, LM.Title, ST.Number, SR.Id, ST.Id 
					HAVING 
						SUM(ISNULL(SRD.RequestedQuantity, 0)) - SUM(ISNULL(STD.TransferredQuantity, 0)) > 0
						AND SR.CreatedDateTime BETWEEN @rFromDate AND @rToDate		
		UNION ALL
		SELECT 
			   SR.Number AS [RequestNo],  
			   SR.CreatedDateTime AS [RequestDate],  
			   SR.RequestedByName AS [RequestedBy], 
			   'Tran'AS [Type], 
			   LM.Title AS [Location],
			   0 AS DepartmentId,
			   ST.Number AS [TransferNo],
			   'Completed' AS [Status], 
			   SUM(ISNULL(SRD.RequestedQuantity, 0)) - SUM(ISNULL(STD.TransferredQuantity, 0)) AS [PendingQty], 
			   SR.Id [ReqId]
			   --ST.Id [TransferId]		   
		   FROM
				sProcurement.tStockTransferRequest SR
					INNER JOIN sProcurement.tStockTransferRequestDetail SRD
					ON SR.Id = SRD.StockTransferRequestId
					INNER JOIN sProcurement.tStockTransfer ST
					ON ST.StockTransferRequestId = SR.id
					INNER JOIN sProcurement.tStockTransferDetail STD
					ON ST.Id = STD.StockTransferId
					INNER JOIN sIp.tStoreLocationMaster LM 
					ON SR.ToStoreLocationId = LM.Id
						WHERE 
						--SR.OrgGroupId = @rOrgGroupId AND 
						SR.FromStoreLocationId =  @rStoreLocationId
					GROUP BY 
						SR.Number, SR.CreatedDateTime, SR.RequestedByName, LM.Title, ST.Number, SR.Id, ST.Id 
					HAVING 
						SUM(ISNULL(SRD.RequestedQuantity, 0)) - SUM(ISNULL(STD.TransferredQuantity, 0)) <= 0
						AND SR.CreatedDateTime BETWEEN @rFromDate AND @rToDate
						Order by  SR.Id,SR.Number
		END
	IF @rType = 'Issue'
		BEGIN
		   SELECT 
			   SR.Number AS [RequestNo],  
			   SR.CreatedDateTime AS [RequestDate],  
			   SR.RequestedByName AS [RequestedBy], 
			   'Issue'AS [Type], 
			   ISNULL(LM.Title,'') AS [Location], 
			   ISNULL( LM.Id,0) AS DepartmentId,
			   ST.Number AS [TransferNo],
			   'Pending' AS [Status], 
			   SUM(ISNULL(SRD.RequestedQuantity, 0)) - SUM(ISNULL(STD.IssuedQuantity, 0)) AS PendingQty, 
			   SR.Id [ReqId]
			   --ST.Id [TransferId]
		   FROM  
				sProcurement.tStockIssueRequest SR
					INNER JOIN sProcurement.tStockIssueRequestDetail SRD
					ON SR.Id = SRD.StockIssueRequestId
					LEFT OUTER JOIN sProcurement.tStockIssue ST
					ON ST.StockIssueRequestId = SR.id
					LEFT JOIN sProcurement.tStockIssueDetail STD
					ON ST.Id = STD.StockIssueId
					LEFT JOIN sSetup.tDepartmentMaster LM 
					ON SR.ToDepartmentId = LM.Id
						WHERE 
						--SR.OrgGroupId = @rOrgGroupId AND 
						SR.FromStoreLocationId =  @rStoreLocationId 
						 AND (SR.ToDepartmentId= @rToDepartmentId OR @rToDepartmentId =0 )
					GROUP BY 
						SR.Number, SR.CreatedDateTime, SR.RequestedByName, LM.Title,LM.Id, ST.Number, SR.Id, ST.Id 
					HAVING 
						SUM(ISNULL(SRD.RequestedQuantity, 0)) - SUM(ISNULL(STD.IssuedQuantity, 0)) > 0
						AND SR.CreatedDateTime BETWEEN @rFromDate AND @rToDate
			UNION ALL
			
			SELECT 
			   SR.Number AS [RequestNo],  
			   SR.CreatedDateTime AS [RequestDate],  
			   SR.RequestedByName AS [RequestedBy], 
			   'Issue'AS [Type], 
			   ISNULL(LM.Title,'') AS [Location],
			   ISNULL( LM.Id,0) AS DepartmentId, 
			   ST.Number AS [TransferNo],
			   'Completed' AS [Status], 
			   SUM(ISNULL(SRD.RequestedQuantity, 0)) - SUM(ISNULL(STD.IssuedQuantity, 0)) AS PendingQty, 
			   SR.Id [ReqId]
			   --ST.Id [TransferId]
		   FROM  
				sProcurement.tStockIssueRequest SR
					INNER JOIN sProcurement.tStockIssueRequestDetail SRD
					ON SR.Id = SRD.StockIssueRequestId
					INNER JOIN sProcurement.tStockIssue ST
					ON ST.StockIssueRequestId = SR.id
					INNER JOIN sProcurement.tStockIssueDetail STD
					ON ST.Id = STD.StockIssueId
					LEFT JOIN sSetup.tDepartmentMaster LM 
					ON SR.ToDepartmentId = LM.Id
						WHERE 
						--SR.OrgGroupId = @rOrgGroupId AND 
						SR.FromStoreLocationId =  @rStoreLocationId
						 AND (SR.ToDepartmentId= @rToDepartmentId OR @rToDepartmentId =0)
					GROUP BY 
						SR.Number, SR.CreatedDateTime, SR.RequestedByName, LM.Title,LM.Id, ST.Number, SR.Id, ST.Id 
					HAVING 
						SUM(ISNULL(SRD.RequestedQuantity, 0)) - SUM(ISNULL(STD.IssuedQuantity, 0)) <= 0
						AND SR.CreatedDateTime BETWEEN @rFromDate AND @rToDate
						Order by  SR.Id,SR.Number
		END
		IF @rType = 'All'
		BEGIN
		SELECT 
			   SR.Number AS [RequestNo],  
			   SR.CreatedDateTime AS [RequestDate],  
			   SR.RequestedByName AS [RequestedBy], 
			   'Tran'AS [Type], 
			   LM.Title AS [Location],
			   0 AS DepartmentId, 
			   ST.Number AS [TransferNo],
			   'Pending' AS [Status],
			   SUM(ISNULL(SRD.RequestedQuantity, 0)) - SUM(ISNULL(STD.TransferredQuantity, 0)) AS PendingQty,
			   SR.Id [ReqId]
			   --ST.Id [TransferId]
			   FROM  
					sProcurement.tStockTransferRequest SR
						INNER JOIN sProcurement.tStockTransferRequestDetail SRD
						ON SR.Id = SRD.StockTransferRequestId
						LEFT OUTER JOIN sProcurement.tStockTransfer ST
						ON ST.StockTransferRequestId = SR.id
						LEFT JOIN sProcurement.tStockTransferDetail STD
						ON ST.Id = STD.StockTransferId
						INNER JOIN sIp.tStoreLocationMaster LM 
						ON SR.ToStoreLocationId = LM.Id
							WHERE 
							--SR.OrgGroupId = @rOrgGroupId AND 
							SR.FromStoreLocationId =  @rStoreLocationId
						GROUP BY 
							SR.Number, SR.CreatedDateTime, SR.RequestedByName, LM.Title, ST.Number, SR.Id, ST.Id
						HAVING 
							SUM(ISNULL(SRD.RequestedQuantity, 0)) - SUM(ISNULL(STD.TransferredQuantity, 0)) > 0
							AND SR.CreatedDateTime BETWEEN @rFromDate AND @rToDate
			UNION ALL
			   SELECT 
			   SR.Number AS [RequestNo],  
			   SR.CreatedDateTime AS [RequestDate],  
			   SR.RequestedByName AS [RequestedBy], 
			   'Issue'AS [Type], 
			   ISNULL(LM.Title,'') AS [Location], 
			   ISNULL( LM.Id,0) AS DepartmentId,
			   ST.Number AS [TransferNo],
			   'Pending' AS [Status], 
			   SUM(ISNULL(SRD.RequestedQuantity, 0)) - SUM(ISNULL(STD.IssuedQuantity, 0)) AS PendingQty,
			   SR.Id [ReqId]
			  -- ST.Id [TransferId]
		   FROM  
				sProcurement.tStockIssueRequest SR
					INNER JOIN sProcurement.tStockIssueRequestDetail SRD
					ON SR.Id = SRD.StockIssueRequestId
					LEFT JOIN sProcurement.tStockIssue ST
					ON ST.StockIssueRequestId = SR.id
					LEFT JOIN sProcurement.tStockIssueDetail STD
					ON ST.Id = STD.StockIssueId
					LEFT JOIN sSetup.tDepartmentMaster LM 
					ON SR.ToDepartmentId = LM.Id
						WHERE 
						--SR.OrgGroupId = @rOrgGroupId AND 
						SR.FromStoreLocationId =  @rStoreLocationId 
						 AND (SR.ToDepartmentId= @rToDepartmentId OR @rToDepartmentId =0 )
					GROUP BY 
						SR.Number, SR.CreatedDateTime, SR.RequestedByName, LM.Title,LM.Id, ST.Number, SR.Id, ST.Id
					HAVING 
						SUM(ISNULL(SRD.RequestedQuantity, 0)) - SUM(ISNULL(STD.IssuedQuantity, 0)) > 0
						AND SR.CreatedDateTime BETWEEN @rFromDate AND @rToDate
			UNION ALL
			SELECT 
			   SR.Number AS [RequestNo],  
			   SR.CreatedDateTime AS [RequestDate],  
			   SR.RequestedByName AS [RequestedBy], 
			   'Tran'AS [Type], 
			   LM.Title AS [Location], 
			   0 AS DepartmentId,
			   ST.Number AS [TransferNo],
			   'Completed' AS [Status],
			   SUM(ISNULL(SRD.RequestedQuantity, 0)) - SUM(ISNULL(STD.TransferredQuantity, 0)) AS PendingQty,
			   SR.Id [ReqId]
			   --ST.Id [TransferId]
			   FROM  
					sProcurement.tStockTransferRequest SR
						INNER JOIN sProcurement.tStockTransferRequestDetail SRD
						ON SR.Id = SRD.StockTransferRequestId
						INNER JOIN sProcurement.tStockTransfer ST
						ON ST.StockTransferRequestId = SR.id
						INNER JOIN sProcurement.tStockTransferDetail STD
						ON ST.Id = STD.StockTransferId
						INNER JOIN sIp.tStoreLocationMaster LM 
						ON SR.ToStoreLocationId = LM.Id
							WHERE 
							--SR.OrgGroupId = @rOrgGroupId AND 
							SR.FromStoreLocationId =  @rStoreLocationId
						GROUP BY 
							SR.Number, SR.CreatedDateTime, SR.RequestedByName, LM.Title, ST.Number, SR.Id, ST.Id
						HAVING 
							SUM(ISNULL(SRD.RequestedQuantity, 0)) - SUM(ISNULL(STD.TransferredQuantity, 0)) <= 0
							AND SR.CreatedDateTime BETWEEN @rFromDate AND @rToDate
			UNION ALL
			   SELECT 
			   SR.Number AS [RequestNo],  
			   SR.CreatedDateTime AS [RequestDate],  
			   SR.RequestedByName AS [RequestedBy], 
			   'Issue'AS [Type], 
			   ISNULL(LM.Title,'') AS [Location], 
			   ISNULL( LM.Id,0) AS DepartmentId,
			   ST.Number AS [TransferNo],
			   'Completed' AS [Status], 
			   SUM(ISNULL(SRD.RequestedQuantity, 0)) - SUM(ISNULL(STD.IssuedQuantity, 0)) AS PendingQty,
			   SR.Id [ReqId]
			  -- ST.Id [TransferId]
		   FROM  
				sProcurement.tStockIssueRequest SR
					INNER JOIN sProcurement.tStockIssueRequestDetail SRD
					ON SR.Id = SRD.StockIssueRequestId
					INNER JOIN sProcurement.tStockIssue ST
					ON ST.StockIssueRequestId = SR.id
					INNER JOIN sProcurement.tStockIssueDetail STD
					ON ST.Id = STD.StockIssueId
					LEFT JOIN sSetup.tDepartmentMaster LM 
					ON SR.ToDepartmentId = LM.Id
						WHERE 
						--SR.OrgGroupId = @rOrgGroupId AND 
						SR.FromStoreLocationId =  @rStoreLocationId
						 AND (SR.ToDepartmentId= @rToDepartmentId OR @rToDepartmentId =0 )
					GROUP BY 
						SR.Number, SR.CreatedDateTime, SR.RequestedByName, LM.Title,LM.Id, ST.Number, SR.Id, ST.Id
					HAVING 
						SUM(ISNULL(SRD.RequestedQuantity, 0)) - SUM(ISNULL(STD.IssuedQuantity, 0)) <= 0
						AND SR.CreatedDateTime BETWEEN @rFromDate AND @rToDate
						Order by  SR.Id,SR.Number
		END		
		END
END
GO
PRINT N'Altering [sStudent].[pStudentVerificationGet]...';


GO
ALTER PROCEDURE [sStudent].[pStudentVerificationGet]
	 
	@rClassId int=0,
	@rDivisionId int=0,
	@rRollNo int=0,
	@rOrgId int,
	--@rNumber bigint,
	@rCode nvarchar(20) = '',
	@rStatusId smallint=0,
	@rFirstName nvarchar(100)='',
	@rLastName nvarchar(100)='',
	@rBatchId int = 0,
	@rOrgGroupBatchId int = 0,
	@rDepartmentId int,
	@rOrgGroupId smallint,
	@rToRollNo int=0,
	@rFromCode nvarchar(20)='',
	@rToCode nvarchar(20)='',
	@rSpecificCode nvarchar(max)='',	
	@rOrderByTypeId int  = 0
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON			 

BEGIN 	 

	BEGIN
		SET @rCode= sCommon.fSearchStringGet(@rCode)
		SET @rFirstName = sCommon.fSearchStringGet(@rFirstName)
		SET @rLastName = sCommon.fSearchStringGet(@rLastName)
	END
 
	SELECT 
			SA.AcademicId,
			SA.StudentId,
			SA.ClassId,
			Sa.MiddleName,
			ISNULL(SA.AdmissionDate,'')As AdmissionDate,
			SA.PreviousSchool,
			ISNULL(SA.DateOfBirth,'') As DateOfBirth,
			SA.BirthPlace,
			SA.Gender,
			SA.FamilyCast,
			SA.CastCatagory AS CasteCategory,
			SA.MotherTongue,
			SA.Nationality,
			Sa.FatherName,
			SA.FatherContactNo,
			SA.Mothername,
			SA.MotherContactNo,
			SA.PresentStreetOne,
			SA.PresentStreetTwo,
			SA.PresentStreetThree,
			ISNULL(SA.StudentContactNo,'')As StudentContactNo,
			SA.UIDNumber,
			SA.AdhaarNumber,
			SA.BankBranch,
			SA.BankAccountNumber,
			SA.BankName,
			SA.BankIFSCCode,
			SA.DepartmentId,
			SA.FirstName,
			SA.LastName,
			SA.Name,
			SA.Code,
			SA.ADMISSIONStandardId, 
			SA.DivisionId,
			SA.DivisionName,
			ISNULL(SA.Number,0) AS Number,
			SA.RollNo,
			SA.StatusId,
			--SA.StatusName,
			SA.OrgId,
			--SA.Age,
			ISNULL(SA.AdmissionCategoryId,0) AS AdmissionCategoryId,
			SA.Religion,
			SA.StudentEmail,
			SA.Name,
			(select  Title  from sSetup.tClassMaster where OrgId=@rOrgId AND id=SA.ADMISSIONStandardId  ) As AdmissionStandard,
			SA.ClassName,
			SA.BirthState,
			SA.BirthCountry,
			SA.BirthTaluka,
			SA.BirthDistrict,
			SA.BankAccountHolderName
  FROM 
            sStudent.vStudentVerification SA  
  WHERE 
			((SA.ClassId=@rClassId)OR(@rClassId=0))
			AND((SA.DivisionId=@rDivisionId)OR(@rDivisionId=0))
			AND((SA.Code like @rCode) OR (ISNULL(@rCode,'') = '')) 
			AND((SA.Code >= @rFromCode) AND (SA.Code <= @rToCode) OR (ISNULL(@rFromCode,'') = '' OR ISNULL(@rToCode,'') = '')) 
			AND(SA.Code IN (SELECT CONVERT(nvarchar,item) from sCommon.fnSplit(@rSpecificCode,',')) OR ISNULL(@rSpecificCode,'') = '') 
			AND((SA.FirstName like @rFirstName) OR (ISNULL(@rFirstName,'') = '')) 
			AND((SA.LastName like @rLastName) OR (ISNULL(@rLastName,'') = '')) 
			AND((SA.StatusId=@rStatusId)OR(@rStatusId=0))	
			AND(SA.OrgId=@rOrgId OR @rOrgId = 0)
			AND (OrgGroupBatchId = @rOrgGroupBatchId	or @rOrgGroupBatchId = 0)	
			AND(SA.BatchId=@rBatchId or @rBatchId = 0)
			AND(SA.DepartmentId=@rDepartmentId or @rDepartmentId = 0)
			and ((sa.RollNO>=@rRollNO)OR(@rRollNo=0))
			and ((sa.RollNO<=@rToRollNo)OR(@rToRollNo=0))
			--AND((SA.Number=@rNumber)OR(@rNumber=0))	

--ORDER BY SA.ClassId,SA.DivisionId,SA.RollNo

ORDER by CASE WHEN @rOrderByTypeId = 1 then SA.FirstName 
			  WHEN @rOrderByTypeId = 2 then SA.LastName END, 
		CASE 
			  WHEN @rOrderByTypeId = 3 then SA.RollNo
			  WHEN @rOrderByTypeId = 4 then (CASE WHEN ISNUMERIC(SA.Code) = 1 THEN CAST(SA.Code AS bigINT)  ELSE 99999999999999999999  END) END,
		CASE WHEN @rOrderByTypeId = 5 then SA.AdmissionDate END  
			  ,SA.ClassId, SA.DivisionId,SA.RollNo
 
END
GO
PRINT N'Creating [sAssessment].[pExamSettingAdd]...';


GO

CREATE PROCEDURE [sAssessment].[pExamSettingAdd]
	(
		--@rExamSettingXml nvarchar(MAX),
		--@rOrgId int

		@rExamSettingXml nvarchar(max),
		@rExamSettingTypeId int,
		@rCreatedUserId bigint
	)
AS

SET NOCOUNT ON

BEGIN
SET @rExamSettingXml=REPLACE(@rExamSettingXml,'&','AND')
DECLARE @lInterrorCode INT,
			@intDoc INT
DECLARE @lNextNumber BIGINT			
BEGIN TRY
BEGIN TRANSACTION	
	EXECUTE @lInterrorCode = sp_xml_preparedocument @intDoc OUTPUT, @rExamSettingXml
	
	IF(@rExamSettingTypeId = 1)
	BEGIN
		UPDATE sAssessment.tExamMaster
		SET 
			IsProcessResult = E.IsProcessResult,
			IsNegativeMarks = E.IsNegativeMarks,
			IsLockForEdit = E.IsLockForEdit,
			IsPublished = E.IsPublished,
			IsPublishExamSchedule = E.IsPublishExamSchedule,
			UpdatedUserId = @rCreatedUserId,
			UpdatedDateTime = sCommon.fGetDate()
		FROM (
		SELECT
			ExamId,
			IsProcessResult,
			IsNegativeMarks,
			IsLockForEdit,
			IsPublished,
			IsPublishExamSchedule
			FROM OPENXML (@intDoc, '/Table/ExamSetting', 1)
		WITH
		(
			ExamId bigint,
			IsProcessResult bit ,
			IsNegativeMarks bit ,
			IsLockForEdit bit,
			IsPublished bit,
			IsPublishExamSchedule bit
		))E 
		Where sAssessment.tExamMaster.Id = E.ExamId
	END
	
	ELSE IF(@rExamSettingTypeId = 2)
	BEGIN
		UPDATE sAssessment.tExamMaster
		SET 
			IsGrade = E.IsGrade,
			IsPercentile = E.IsPercentile,
			IsRankNo = E.IsRankNo,
			IsGenerateRankNo = E.IsGenerateRankNo,
			IsPercentage = E.IsPercentage,
			IsRemovePercentageForFail = E.IsFailPercentageZero,
			IsSubjectPercentile = E.IsSubjectPercentile,
			IsResultStatus = E.IsDisplayResultStatus,
			IsAllExamPassRequired = E.IsAllExamPassRequired,
			IsExcludeAbsentTotal = E.IsExcludeAbsentTotal,
			UpdatedUserId = @rCreatedUserId,
			UpdatedDateTime = sCommon.fGetDate()
		FROM (
		SELECT
			ExamId,
			IsGrade,
			IsPercentile,
			IsRankNo,
			IsGenerateRankNo,
			IsPercentage,
			IsFailPercentageZero,
			IsSubjectPercentile,
			IsDisplayResultStatus,
			IsAllExamPassRequired,
			IsExcludeAbsentTotal
			FROM OPENXML (@intDoc, '/Table/ExamSetting', 1)
		WITH
		(
			ExamId bigint,
			IsGrade bit,
			IsPercentile bit,
			IsRankNo bit,
			IsGenerateRankNo bit,
			IsPercentage bit,
			IsFailPercentageZero bit,
			IsSubjectPercentile bit,
			IsDisplayResultStatus bit,
			IsAllExamPassRequired bit,
			IsExcludeAbsentTotal bit
		))E 
		Where sAssessment.tExamMaster.Id = E.ExamId
	END
	
	ELSE IF(@rExamSettingTypeId = 3)
	BEGIN
		UPDATE sAssessment.tExamMaster
			SET 
				IsDisplayPhoto = E.IsDisplayPhoto,
				IsDisplaySchoolName = E.IsDisplaySchoolName,
				IsDisplayBirthDate = E.IsDisplayBirthDate,
				IsDisplayParentName = E.IsDisplayParentName,
				IsDisplayHeightWeight = E.IsDisplayHeightWeight,
				IsDisplayGradeString = E.IsDisplayGradeString,
				IsDisplayTotalMark = E.IsDisplayTotalMark,
				IsDisplayResultIndicator = E.IsDisplayResultIndicator,
				IsDisplayHighestDivisionMark = E.IsDisplayHighestDivisionMark,
				IsDisplayHighestDivisionGrade = E.IsDisplayHighestDivisionGrade,
				IsDisplayTeacherSign = E.IsDisplayTeacherSign,
				IsDisplayPrincipalSign = E.IsDisplayPrincipalSign,
				IsDisplayActivityGrade = E.IsDisplayActivityGrade,
				UpdatedUserId = @rCreatedUserId,
				UpdatedDateTime = sCommon.fGetDate()
			FROM (
			SELECT
				ExamId,
				IsDisplayPhoto ,
				IsDisplaySchoolName ,
				IsDisplayBirthDate ,
				IsDisplayParentName ,
				IsDisplayHeightWeight ,
				IsDisplayGradeString ,
				IsDisplayTotalMark ,
				IsDisplayResultIndicator ,
				IsDisplayHighestDivisionMark ,
				IsDisplayHighestDivisionGrade ,
				IsDisplayTeacherSign ,
				IsDisplayPrincipalSign ,
				IsDisplayActivityGrade 
				FROM OPENXML (@intDoc, '/Table/ExamSetting', 1)
			WITH
			(
				ExamId bigint,
				IsDisplayPhoto bit,
				IsDisplaySchoolName bit,
				IsDisplayBirthDate bit,
				IsDisplayParentName bit,
				IsDisplayHeightWeight bit,
				IsDisplayGradeString bit,
				IsDisplayTotalMark bit,
				IsDisplayResultIndicator bit,
				IsDisplayHighestDivisionMark bit,
				IsDisplayHighestDivisionGrade bit,
				IsDisplayTeacherSign bit,
				IsDisplayPrincipalSign bit,
				IsDisplayActivityGrade bit
			))E 
			Where sAssessment.tExamMaster.Id = E.ExamId
	END
		
	ELSE
	BEGIN
		UPDATE sAssessment.tExamMaster
			SET 
				IsIncludeCoScholastic = E.IsIncludeCoScholastic,
				IsCoScholasticGradeIndicator = E.IsCoScholasticGradeIndicator,
				IsCoScholasticGradeDesIndicator = E.IsCoScholasticGradeDesIndicator,
				IsCoScholasticGrade = E.IsCoScholasticGrade,
				UpdatedUserId = @rCreatedUserId,
				UpdatedDateTime = sCommon.fGetDate()
			FROM (
			SELECT
				ExamId,
				IsIncludeCoScholastic ,
				IsCoScholasticGradeIndicator ,
				IsCoScholasticGradeDesIndicator ,
				IsCoScholasticGrade 
				FROM OPENXML (@intDoc, '/Table/ExamSetting', 1)
			WITH
			(
				ExamId bigint,
				IsIncludeCoScholastic bit,
				IsCoScholasticGradeIndicator bit,
				IsCoScholasticGradeDesIndicator bit,
				IsCoScholasticGrade bit
			))E 
			Where sAssessment.tExamMaster.Id = E.ExamId

	END

	EXEC sp_xml_removedocument @intDoc
	COMMIT TRANSACTION
	SELECT 1
	END TRY
	BEGIN CATCH
	ROLLBACK TRANSACTION
	SELECT -1
	END CATCH

END
GO
PRINT N'Creating [sFee].[pLateFeeRuleMasterAdd]...';


GO
CREATE PROCEDURE [sFee].[pLateFeeRuleMasterAdd]
	    @rOrgId int,
        @rId int,
       -- @rCode nvarchar(20),
        @rTitle nvarchar(100),
		@rFeeRule nvarchar(100),
        @rIsObsolete bit
       
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	IF(@rId = 0)	
	BEGIN
		--IF EXISTS (SELECT Id FROM sFee.tLateFeeRuleMaster WHERE Code=@rCode AND OrgGroupBatchId=@rOrgGroupBatchId AND ReceiptBookId=@rReceiptBookId)
		--	BEGIN
		--	SELECT -101 as Result
		--	RETURN
		--END 
	
		IF EXISTS (SELECT Id FROM sFee.tLateFeeRuleMaster WHERE Title=@rTitle AND OrgId=@rOrgId)
			BEGIN
			SELECT -102 as Result
			RETURN
		END 

			IF EXISTS (SELECT Id FROM sFee.tLateFeeRuleMaster WHERE FeeRule=@rFeeRule AND OrgId=@rOrgId)
			BEGIN
			SELECT -103 as Result
			RETURN
		END 
	END
	ELSE
	BEGIN
		--IF EXISTS (SELECT Id FROM sFee.LateFeeRuleMaster WHERE  Code=@rCode AND OrgGroupBatchId=@rOrgGroupBatchId AND ReceiptBookId=@rReceiptBookId AND Id<>@rId)
		--BEGIN
		--	SELECT -101 as Result
		--	RETURN
		--END	
		IF EXISTS (SELECT Id FROM sFee.tLateFeeRuleMaster WHERE  Title=@rTitle AND OrgId=@rOrgId AND Id<>@rId)
		BEGIN
			SELECT -102 as Result
			RETURN
		END 

		IF EXISTS (SELECT Id FROM sFee.tLateFeeRuleMaster WHERE FeeRule=@rFeeRule AND OrgId=@rOrgId AND Id<>@rId)
			BEGIN
			SELECT -103 as Result
			RETURN
       END
	END
	
	
	 BEGIN TRANSACTION	
	 DECLARE @lNextNumber BIGINT 

	IF(@rId = 0)	
	BEGIN
		
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sFee.tLateFeeRuleMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	
	INSERT INTO sFee.tLateFeeRuleMaster
		(
			OrgId,
			Id,
			--Code,
			Title,
			FeeRule,
			IsObsolete	
		)
	VALUES
		(
		    @rOrgId,
			@lNextNumber,
			--@rCode,
			@rTitle,
			@rFeeRule,
			@rIsObsolete
			
		)
		    SELECT 1 AS Result
	END	 

ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE  sFee.tLateFeeRuleMaster
			--Code=@rCode,
			SET Title=@rTitle,
		    	FeeRule=@rFeeRule,
			IsObsolete=@rIsObsolete
	      WHERE Id = @rId
	      SELECT 11 AS Result
	 END  	
	--if not exists(Select 1 from sSystem.tPortalSync where OrgGroupId=@rOrgGroupId)
	--BEGIN
	--	INsert Into sSystem.tPortalSync
	--	(
	--		OrgGroupId,
	--		FeeChange
	--	)
	--	Values
	--	(
	--		@rOrgGroupId,1
	--	)
	--END
	--ELse
	--BEGIN
	--	Update sSystem.tPortalSync
	--	Set
	--		FeeChange=1
	--	Where OrgGroupId=@rOrgGroupId
	
	--END
	COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result 
	END CATCH	
		
END
GO
PRINT N'Creating [sFee].[pLateFeeRuleMasterGet]...';


GO
Create PROCEDURE [sFee].[pLateFeeRuleMasterGet]
	 
	 @rOrgId int,
	 @rId int,
	 --@rCode nvarchar(20),
	 @rTitle nvarchar(100),
	 @rFeeRule nvarchar(200)
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
	
	BEGIN
			--SET @rCode = sCommon.fSearchStringGet(@rCode)
			SET @rTitle = sCommon.fSearchStringGet(@rTitle)
	END
	
	SELECT 
			Id,
			--CGM.Code,
			Title,
			IsObsolete,
			OrgId,
			ISNULL(FeeRule,'') AS FeeRule
			
	FROM 
			sFee.tLateFeeRuleMaster 		
	WHERE 
			(OrgId = @rOrgId)
			AND	((Id = @rId) OR (@rId = 0))
			--AND ((CGM.Code like @rCode) OR (ISNULL(@rCode,'') = ''))
			AND ((Title like @rTitle) OR (ISNULL(@rTitle,'') = ''))
			
		
END
GO
PRINT N'Creating [sHrm].[pEmployeeAllBAtchDocumentSubmitGet]...';


GO
CREATE PROCEDURE [sHrm].[pEmployeeAllBAtchDocumentSubmitGet]
	 
        @rEmployeeId bigint,
		@rOrgId int
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
 
	BEGIN
			SELECT Isnull(D.Id,0) AS DocumentId,ISNULL(D.DocumentName,'') AS DocumentName,
			CASE WHEN  S.SubmitDocumentMasterId Is null And UD.DocumentId is null THEN 'False' ELSE 'True'END AS IsCheck
			, ISNULL(UD.DocumentName,'')  As FileName,
			isnull(Ud.OrgGroupBatchId,0) AS OrgGroupBatchId,ISNULL(S.IsMigrate,0) as IsMigrate
		 	FROM sCommon.tSubmitDocumentMaster D
			LEFT Join [sHrm].[tEmployeeDocument]  S ON S.SubmitDocumentMasterId=D.id AND S.EmployeeId=@rEmployeeId
			Left Join [sCommon].[tUploadDocument] UD On UD.DocumentId=S.SubmitDocumentMasterId AND UserSourceTypeId=95 AND UserSourceId=S.EmployeeId AND ( UD.UploadFunctionalityId=13)
			WHERE OrgId=@rOrgId AND SubmitDocumentFunctionalityId='2'
END
GO
PRINT N'Creating [sHrm].[pEmployeeDocumentAllBatchDepartmentWiseGet]...';


GO

Create PROCEDURE [sHrm].[pEmployeeDocumentAllBatchDepartmentWiseGet]

	@rOrgId smallint,
	@rCode nvarchar(20) = '',
	@rFirstName nvarchar(100)='',
	@rLastName nvarchar(100)='',
	@rStatusId int = 0,
	@rDepartmentId int = 0,
	@rUserId bigint=0,
    @rMultiCode nvarchar(max)='',
	@rDocumentId int=0

AS
SET NOCOUNT ON

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

		SELECT 
				EC.EmployeeId AS Id,
				EC.Code AS Code,
				ISNULL(EC.EmployeeName, '') AS Name,
				ISNULL(SM.Id,0) AS StatusId,
				ISNULL(SM.Title,'') AS Status,
				EC.DepartmentId,
				EC.DepartmentName,
				OM.DisplayTitle,
				OM.Id As OrgId,
				ISNULL([sHrm].[fEmployeeDocumentAllBatchDepartmentwiseget](@rDocumentId,EC.Id),'') AS DocumentName

		FROM 
				sHrm.vEmployeeCommunication EC
			INNER JOIN sCommon.tStatusMaster SM ON SM.Id = EC.StatusId AND SM.StatusTypeId = 4
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = EC.OrgId
			INNER JOIN sSecurity.tUserAccess U ON U.SourceId = EC.DepartmentId AND U.SourceTypeId=2017
		WHERE 
				((EC.OrgId = @rOrgId) OR (@rOrgId=0))
			AND ((EC.Code Like @rCode + '%') OR (ISNULL(@rCode,'') = ''))
			AND ((EC.FirstName Like @rFirstName  + '%') OR (@rFirstName = ''))	 			 
			AND ((EC.LastName Like @rLastName + '%')OR(@rLastName = ''))
			AND ((EC.DepartmentId = @rDepartmentId) OR (@rDepartmentId = 0))	
			AND ((EC.StatusId = @rStatusId) OR (@rStatusId = 0))	
			AND U.UserId = @rUserId
			AND (ISNULL(EC.Code,0) IN( SELECT cast(item as nvarchar(20)) FROM  sCommon.fnsplit(@rMultiCode,',')) OR ISNULL(@rMultiCode,'')='')
			
			ORDER BY EC.Number
	END TRY
	BEGIN CATCH
		SELECT -1 As Result,ERROR_LINE(),ERROR_MESSAGE()
	END CATCH
END
GO
PRINT N'Creating [sHrm].[pEmployeeStudentDocumentMigrationAdd]...';


GO
CREATE PROCEDURE [sHrm].[pEmployeeStudentDocumentMigrationAdd]
        @rUserSourceId bigint,
		@rUserSourceTypeId smallint,
		@DocumentId int,
		@DocumentName nvarchar(150)
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 	
 
	BEGIN TRY
	
	 BEGIN TRANSACTION	
	 
		if(@rUserSourceTypeId=95)
		Begin
		INSERT INTO sHrm.tEmployeeDocument
		(
			EmployeeId, 
			SubmitDocumentMasterId,
			DocumentName,
			IsMigrate
		)
		VALUES   (@rUserSourceId,@DocumentId,@DocumentName,1)  
		END
		if(@rUserSourceTypeId=2003)
		BEGIN
		INSERT INTO sStudent.tStudentDocument
			(
				StudentId, 
				SubmitDocumentMasterId,
				DocumentName,
				IsMigrate
			)
			VALUES   (@rUserSourceId,@DocumentId,@DocumentName,1)   
		END 
	SELECT 1 AS Result
	
	COMMIT TRANSACTION
	
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH
		
END
GO
PRINT N'Creating [sStudent].[pStudentAllBatchDocumentSubmitGet]...';


GO

CREATE PROCEDURE [sStudent].[pStudentAllBatchDocumentSubmitGet]
	 
        @rStudentId bigint,
		@rOrgId int
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
 
	BEGIN
			SELECT DISTINCT Isnull(D.Id,0) AS DocumentId,ISNULL(D.DocumentName,'') AS DocumentName,
			CASE WHEN  S.SubmitDocumentMasterId Is null and UD.DocumentId is null THEN 'False' ELSE 'True'END AS IsCheck,
			 ISNULL(UD.DocumentName,'') As FileName,
			isnull(Ud.OrgGroupBatchId,0) AS OrgGroupBatchId,ISNULL(S.IsMigrate,0) as IsMigrate
		 	FROM sCommon.tSubmitDocumentMaster D
			INNER JOIN sCommon.tSubmitDocumentScope DS ON DS.SubmitDocumentId = D.Id
			INNER JOIN sStudent.tAcademic A ON A.ClassId = DS.SourceId AND A.StudentId = @rStudentId
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId AND BM.IsActive = 1
			LEFT Join sStudent.tStudentDocument  S ON S.SubmitDocumentMasterId=D.id AND S.StudentId=@rStudentId
			Left Join [sCommon].[tUploadDocument] UD On UD.DocumentId=D.id AND UD.UploadFunctionalityId=11 AND UserSourceTypeId=2003 AND UserSourceId=S.StudentId AND UserSourceId=@rStudentId
			WHERE D.OrgId=@rOrgId AND SubmitDocumentFunctionalityId='1'

			UNION 

			SELECT DISTINCT Isnull(D.Id,0) AS DocumentId,ISNULL(D.DocumentName,'') AS DocumentName,
			CASE WHEN  S.SubmitDocumentMasterId Is null and UD.DocumentId is null THEN 'False' ELSE 'True'END AS IsCheck,
			 ISNULL(UD.DocumentName,'') As FileName,
			isnull(Ud.OrgGroupBatchId,0) AS OrgGroupBatchId,ISNULL(S.IsMigrate,0) as IsMigrate
		 	FROM sCommon.tSubmitDocumentMaster D
			LEFT JOIN sCommon.tSubmitDocumentScope DS ON DS.SubmitDocumentId = D.Id AND DS.SubmitDocumentId is null
			LEFT JOIN sStudent.tAcademic A ON A.ClassId = DS.SourceId AND A.StudentId = @rStudentId
			LEFT JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId AND BM.IsActive = 1
			LEFT Join sStudent.tStudentDocument  S ON S.SubmitDocumentMasterId=D.id AND S.StudentId=@rStudentId
			Left Join [sCommon].[tUploadDocument] UD On UD.DocumentId=D.id AND UD.UploadFunctionalityId=11 AND UserSourceTypeId=2003 AND UserSourceId=S.StudentId AND UserSourceId=@rStudentId
			WHERE D.OrgId=@rOrgId AND SubmitDocumentFunctionalityId='1' --AND DS.SubmitDocumentId is null


END
GO

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

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

GO


GO
PRINT N'Altering [sFee].[tFeeSetup]...';


GO
ALTER TABLE [sFee].[tFeeSetup]
    ADD [LateFeeRuleId] INT NULL;


GO
PRINT N'Altering [sStudent].[AuditStudentAdditional]...';


GO
ALTER TRIGGER [sStudent].[AuditStudentAdditional] 
    ON [sStudent].[tStudentadditional]
    AFTER INSERT,DELETE,UPDATE
AS 
BEGIN
	SET NOCOUNT ON;
	IF (SELECT COUNT(*) FROM deleted) > 0 
	BEGIN
		DECLARE @AuditMessage XML
		----set valut to all xml from deleted table
		SET @AuditMessage = (SELECT 
		                          StudentId,	
		                          ISNULL(BankAccountNumber,'') AS BankAccountNumber,	
		                          ISNULL(BankName,'') AS BankName,	
		                          ISNULL(BankBranch,'') AS BankBranch,	
		                          ISNULL(BankIFSCCode,'') AS BankIFSCCode,	
		                          ISNULL(Class9BoardRegistrationNumber,'') AS Class9BoardRegistrationNumber,	
		                          ISNULL(Class11BoardRegistrationNumber,'') AS Class11BoardRegistrationNumber,	
		                          ISNULL(PassportNumber,'') AS PassportNumber,	
		                          ISNULL(PassportType,'') AS PassportType,	
		                          ISNULL(PassportCountryCode,'') AS PassportCountryCode,	
		                          ISNULL(PassportIssueDate,'') AS PassportIssueDate,	
		                          ISNULL(PassportExpiryDate,'') AS PassportExpiryDate	
		                          
		                      FROM deleted FOR XML AUTO) 
	     
		DECLARE @SourceId bigint;
		DECLARE @CreateUserId bigint;
		DECLARE @CreateDateTime DateTime;      
		SET @SourceId=(SELECT @AuditMessage.value('(/deleted/@StudentId)[1]', 'bigint') As SourceId)
		SET @CreateUserId=(SELECT @AuditMessage.value('(/deleted/@CreatedUserId)[1]', 'bigint') As CreatedUserId)
		--SET @CreateDateTime=(SELECT @AuditMessage.value('(/deleted/@CreateDateTime)[1]', 'DateTime') As CreateDateTime)
		
		INSERT INTO sAudit.HistoryLog(ScreenName, AuditEntry,SourceTypeId, SourceId,CreatedUserId,CreatedDateTime) 
		VALUES ('StudentAdditional', @AuditMessage,2003,ISNULL(@SourceId,0),ISNULL(@CreateUserId,0),GETDATE())   
		
		             
	END
END
GO
PRINT N'Creating [sStudent].[AuditStudentOther]...';


GO
CREATE TRIGGER [sStudent].[AuditStudentOther] 
    ON [sStudent].[tStudentOther]
    AFTER INSERT,DELETE,UPDATE
AS 
BEGIN
	SET NOCOUNT ON;
	IF (SELECT COUNT(*) FROM deleted) > 0 
	BEGIN
		DECLARE @AuditMessage XML
		----set valut to all xml from deleted table
		SET @AuditMessage = (SELECT
		                         StudentId,
		                         ISNULL(UIDNumber,0) AS UIDNumber,
		                         ISNULL(CAST( CONVERT(VARCHAR,DateOfBirth,121) AS varchar(100)),'') AS DateOfBirth,
		                         ISNULL(BirthDateInWord,'') AS BirthDateInWord,
		                         ISNULL(TransportModeId,0) AS TransportModeId,
		                         ISNULL(GenderId,0) AS GenderId,
		                         ISNULL(BloodGroupId,0) AS BloodGroupId,
		                         ISNULL(BirthPlace,'') AS BirthPlace,
		                         ISNULL(BirthTaluka,'') AS BirthTaluka,
								 ISNULL(BirthDistrict,'') AS BirthDistrict,
								 ISNULL(FamilyCast,'') AS FamilyCast,
								 ISNULL(FamilySubCast,'') AS FamilySubCast,
								 ISNULL(CastCategoryId,0) AS CastCategoryId,
								 ISNULL(ReligionId,0) AS ReligionId,
								 ISNULL(HouseId,0) AS HouseId,
								 ISNULL(MotherTongueId,0) AS MotherTongueId,
								 ISNULL(NationalityId,0) AS NationalityId,
								 ISNULL(Hobby,'') AS Hobby,
		                         CreatedUserId,
		                         ISNULL(CAST( CONVERT(VARCHAR, CreatedDateTime, 121) AS varchar(100)),'') AS CreatedDateTime,
		                         ISNULL(UpdatedUserId,'') AS UpdatedUserId,
		                         ISNULL(CAST( CONVERT(VARCHAR, UpdatedDateTime, 121) AS varchar(100)),'') AS UpdatedDateTime,
		                         ISNULL(ReferenceRemark,'') AS ReferenceRemark,
		                         ISNULL(AdhaarNumber,'') AS AdhaarNumber,
		                         ISNULL(MotherTongue,'') AS MotherTongue,
		                         ISNULL(QuotaId,0) AS QuotaId,
		                         ISNULL(BirthState, '') AS BirthState,
		                         ISNULL(BirthCountry, '') AS BirthCountry,
		                         ISNULL(TribeId,0) AS TribeId

		                    FROM deleted FOR XML AUTO) 
	     
		DECLARE @SourceId bigint;
		DECLARE @CreateUserId bigint;
		DECLARE @CreateDateTime DateTime;      
		SET @SourceId=(SELECT @AuditMessage.value('(/deleted/@StudentId)[1]', 'bigint') As SourceId)
		SET @CreateUserId=(SELECT @AuditMessage.value('(/deleted/@CreatedUserId)[1]', 'bigint') As CreatedUserId)
		--SET @CreateDateTime=(SELECT @AuditMessage.value('(/deleted/@CreateDateTime)[1]', 'DateTime') As CreateDateTime)
		
		INSERT INTO sAudit.HistoryLog(ScreenName, AuditEntry,SourceTypeId, SourceId,CreatedUserId,CreatedDateTime) 
		VALUES ('StudentOther', @AuditMessage,2003,ISNULL(@SourceId,0),ISNULL(@CreateUserId,0),GETDATE())   
		
		             
	END
END
GO
PRINT N'Refreshing [sFee].[vReceiptBook]...';


GO
EXECUTE sp_refreshview N'sFee.vReceiptBook';


GO
PRINT N'Refreshing [sFee].[vFeeSetup]...';


GO
EXECUTE sp_refreshview N'sFee.vFeeSetup';


GO
PRINT N'Refreshing [sFee].[vOptionalFeeHeadSetup]...';


GO
EXECUTE sp_refreshview N'sFee.vOptionalFeeHeadSetup';


GO
PRINT N'Refreshing [sFee].[vOptionalFeeSetup]...';


GO
EXECUTE sp_refreshview N'sFee.vOptionalFeeSetup';


GO
PRINT N'Refreshing [sFee].[vReceiptBookBatch]...';


GO
EXECUTE sp_refreshview N'sFee.vReceiptBookBatch';

GO

IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[sHrm].[fEmployeeDocumentAllBatchDepartmentwiseget]') AND type IN (N'FN') )
 
 DROP FUNCTION [sHrm].[fEmployeeDocumentAllBatchDepartmentwiseget] ;

GO

CREATE FUNCTION [sHrm].[fEmployeeDocumentAllBatchDepartmentwiseget] (@rDocumentId int,@rEmployeeId bigint)
RETURNS [nvarchar](max) WITH EXECUTE AS CALLER
AS 
BEGIN

 DECLARE @lDepartmentId int
 DECLARE @lEmployeeId bigint

 SELECT @lDepartmentId = DepartmentId,@lEmployeeId = EmployeeId FROM sHrm.vEmployeeCommunication WHERE Id = @rEmployeeId
      DECLARE @rDocumentName Nvarchar(max)
      BEGIN
		SELECT @rDocumentName = ISNULL(STUFF(
			 (SELECT DISTINCT ',' + DocumentName FROM (SELECT DISTINCT SDM.DocumentName +'-OGB-'+cast(UD.OrgGroupBatchId as nvarchar) as DocumentName
			  FROM sCommon.tSubmitDocumentMaster SDM
			  INNER JOIN  sHrm.tEmployeeDocument ED ON SDM.Id=ED.SubmitDocumentMasterId
			  INNER JOIN sCommon.tSubmitDocumentScope DS ON DS.SubmitDocumentId=SDM.Id AND DS.SourceId = @lDepartmentId
			  Inner Join [sCommon].[tUploadDocument] UD On UD.DocumentId=SDM.Id AND UserSourceTypeId=95 AND UserSourceId=@lEmployeeId AND ( UD.UploadFunctionalityId=13)
			  where ED.EmployeeId=@lEmployeeId AND SDM.SubmitDocumentFunctionalityId = 2 AND ((SDM.Id=@rDocumentId)OR(@rDocumentId=0))

			  UNION ALL

			  SELECT DISTINCT SDM.DocumentName  +'-OGB-'+cast(UD.OrgGroupBatchId as nvarchar) as DocumentName
			  FROM sCommon.tSubmitDocumentMaster SDM
			  INNER JOIN  sHrm.tEmployeeDocument ED ON SDM.Id=ED.SubmitDocumentMasterId
			  LEFT JOIN sCommon.tSubmitDocumentScope DS ON DS.SubmitDocumentId=SDM.Id
			  Left Join [sCommon].[tUploadDocument] UD On UD.DocumentId=SDM.Id AND UserSourceTypeId=95 AND UserSourceId=@lEmployeeId AND ( UD.UploadFunctionalityId=13)
			  where ED.EmployeeId=@lEmployeeId AND SDM.SubmitDocumentFunctionalityId = 2 AND UD.DocumentName is not null   AND ((SDM.Id=@rDocumentId)OR(@rDocumentId=0)))
			  AS DocumentName
			  FOR XML PATH (''))
			  , 1, 1, ''),'')             
                                    
      END

     
      RETURN @rDocumentName
END

GO


IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[sStudent].[fStudentDocumentAllBatchClasswiseget]') AND type IN (N'FN') )
 
 DROP FUNCTION [sStudent].[fStudentDocumentAllBatchClasswiseget] ;

GO

CREATE FUNCTION [sStudent].[fStudentDocumentAllBatchClasswiseget] (@rDocumentId int,@rAcademicId bigint)
RETURNS [nvarchar](max) WITH EXECUTE AS CALLER
AS 
BEGIN

 DECLARE @lClassId int
 DECLARE @lStudentId bigint

 SELECT @lClassId = ClassId,@lStudentId = StudentId FROM sStudent.vStudentAcademic WHERE AcademicId = @rAcademicId
      DECLARE @rDocumentName Nvarchar(max)
      BEGIN
		SELECT @rDocumentName = ISNULL(STUFF(
			 (SELECT DISTINCT ',' + DocumentName FROM (SELECT DISTINCT SDM.DocumentName  +'-OGB-'+cast(UD.OrgGroupBatchId as nvarchar) as DocumentName
			  FROM sCommon.tSubmitDocumentMaster SDM
			  INNER JOIN  sStudent.tStudentDocument SD ON SDM.Id=SD.SubmitDocumentMasterId
			  INNER JOIN sCommon.tSubmitDocumentScope DS ON DS.SubmitDocumentId=SDM.Id AND DS.SourceId = @lClassId
			   Inner Join [sCommon].[tUploadDocument] UD On UD.DocumentId=SDM.Id AND UserSourceTypeId=2003 AND UserSourceId=@lStudentId AND ( UD.UploadFunctionalityId=11)
			  where SD.StudentId=@lStudentId AND SDM.SubmitDocumentFunctionalityId = 1 AND ((SDM.Id=@rDocumentId)OR(@rDocumentId=0))

			  UNION ALL

			  SELECT DISTINCT SDM.DocumentName +'-OGB-'+cast(UD.OrgGroupBatchId as nvarchar) as DocumentName
			  FROM sCommon.tSubmitDocumentMaster SDM
			  INNER JOIN  sStudent.tStudentDocument SD ON SDM.Id=SD.SubmitDocumentMasterId
			  LEFT JOIN sCommon.tSubmitDocumentScope DS ON DS.SubmitDocumentId=SDM.Id
			   Left Join [sCommon].[tUploadDocument] UD On UD.DocumentId=SDM.Id AND UserSourceTypeId=2003 AND UserSourceId=@lStudentId AND ( UD.UploadFunctionalityId=11)
			  where SD.StudentId=@lStudentId AND SDM.SubmitDocumentFunctionalityId = 1  AND ((SDM.Id=@rDocumentId)OR(@rDocumentId=0)))
			  AS DocumentName
			  FOR XML PATH (''))
			  , 1, 1, ''),'')             
                                    
      END

     
      RETURN @rDocumentName
END

GO


ALTER FUNCTION [sCommon].[fnSplit](@sInputList [nvarchar](max), @sDelimiter [nvarchar](100) = ',')
RETURNS @List TABLE (
	[item] [nvarchar](1000) NULL
) WITH EXECUTE AS CALLER
AS 
BEGIN
DECLARE @sItem NVARCHAR(max)
WHILE CHARINDEX(@sDelimiter,@sInputList,0) <> 0
 BEGIN
 SELECT
  @sItem=RTRIM(LTRIM(SUBSTRING(@sInputList,1,CHARINDEX(@sDelimiter,@sInputList,0)-1))),
  @sInputList=RTRIM(LTRIM(SUBSTRING(@sInputList,CHARINDEX(@sDelimiter,@sInputList,0)+LEN(@sDelimiter),LEN(@sInputList))))
 
 IF LEN(@sItem) > 0
  INSERT INTO @List SELECT @sItem
 END

IF LEN(@sInputList) > 0
 INSERT INTO @List SELECT @sInputList -- Put the last item in
RETURN
END
GO
PRINT N'Altering [sAssessment].[vGeneralExamColumnName]...';


GO


IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[sHrm].[pEmployeeAllBAtchDocumentSubmitGet]') AND type IN (N'P') )
BEGIN
	DROP PROCEDURE [sHrm].[pEmployeeAllBAtchDocumentSubmitGet]
END
GO

CREATE PROCEDURE [sHrm].[pEmployeeAllBAtchDocumentSubmitGet]
	 
        @rEmployeeId bigint,
		@rOrgId int
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
 
	BEGIN
			SELECT Isnull(D.Id,0) AS DocumentId,ISNULL(D.DocumentName,'') AS DocumentName,
			CASE WHEN   UD.DocumentId is null THEN 'False' ELSE 'True'END AS IsCheck
			, ISNULL(UD.DocumentName,'')  As FileName,
			isnull(Ud.OrgGroupBatchId,0) AS OrgGroupBatchId,ISNULL(S.IsMigrate,0) as IsMigrate
		 	FROM sCommon.tSubmitDocumentMaster D
			LEFT Join [sHrm].[tEmployeeDocument]  S ON S.SubmitDocumentMasterId=D.id AND S.EmployeeId=@rEmployeeId
			Left Join [sCommon].[tUploadDocument] UD On UD.DocumentId=D.id AND UserSourceTypeId=95 AND UserSourceId=@rEmployeeId AND ( UD.UploadFunctionalityId=13)
			WHERE OrgId=@rOrgId AND SubmitDocumentFunctionalityId='2'
END
GO


IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[sHrm].[pEmployeeDocumentAllBatchDepartmentWiseGet]') AND type IN (N'P') )
BEGIN
	DROP PROCEDURE [sHrm].[pEmployeeDocumentAllBatchDepartmentWiseGet]
END
GO

CREATE PROCEDURE [sHrm].[pEmployeeDocumentAllBatchDepartmentWiseGet]

	@rOrgId smallint,
	@rCode nvarchar(20) = '',
	@rFirstName nvarchar(100)='',
	@rLastName nvarchar(100)='',
	@rStatusId int = 0,
	@rDepartmentId int = 0,
	@rUserId bigint=0,
    @rMultiCode nvarchar(max)='',
	@rDocumentId int=0

AS
SET NOCOUNT ON

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

		SELECT 
				EC.EmployeeId AS Id,
				EC.Code AS Code,
				ISNULL(EC.EmployeeName, '') AS Name,
				ISNULL(SM.Id,0) AS StatusId,
				ISNULL(SM.Title,'') AS Status,
				EC.DepartmentId,
				EC.DepartmentName,
				OM.DisplayTitle,
				OM.Id As OrgId,
				ISNULL([sHrm].[fEmployeeDocumentAllBatchDepartmentwiseget](@rDocumentId,EC.Id),'') AS DocumentName


		FROM 
				sHrm.vEmployeeCommunication EC
			INNER JOIN sCommon.tStatusMaster SM ON SM.Id = EC.StatusId AND SM.StatusTypeId = 4
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = EC.OrgId
			INNER JOIN sSecurity.tUserAccess U ON U.SourceId = EC.DepartmentId AND U.SourceTypeId=2017
		WHERE 
				((EC.OrgId = @rOrgId) OR (@rOrgId=0))
			AND ((EC.Code Like @rCode + '%') OR (ISNULL(@rCode,'') = ''))
			AND ((EC.FirstName Like @rFirstName  + '%') OR (@rFirstName = ''))	 			 
			AND ((EC.LastName Like @rLastName + '%')OR(@rLastName = ''))
			AND ((EC.DepartmentId = @rDepartmentId) OR (@rDepartmentId = 0))	
			AND ((EC.StatusId = @rStatusId) OR (@rStatusId = 0))	
			AND U.UserId = @rUserId
			AND (ISNULL(EC.Code,0) IN( SELECT cast(item as nvarchar(20)) FROM  sCommon.fnsplit(@rMultiCode,',')) OR ISNULL(@rMultiCode,'')='')
			
			ORDER BY EC.Number
	END TRY
	BEGIN CATCH
		SELECT -1 As Result,ERROR_LINE(),ERROR_MESSAGE()
	END CATCH
END
GO


IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[sHrm].[pEmployeeStudentDocumentMigrationAdd]') AND type IN (N'P') )
BEGIN
	DROP PROCEDURE [sHrm].[pEmployeeStudentDocumentMigrationAdd]
END
GO

CREATE PROCEDURE [sHrm].[pEmployeeStudentDocumentMigrationAdd]
        @rUserSourceId bigint,
		@rUserSourceTypeId smallint,
		@DocumentId int,
		@DocumentName nvarchar(150)
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 	
 
	BEGIN TRY
	
	 BEGIN TRANSACTION	
	 
		if(@rUserSourceTypeId=95)
		Begin
		INSERT INTO sHrm.tEmployeeDocument
		(
			EmployeeId, 
			SubmitDocumentMasterId,
			DocumentName,
			IsMigrate
		)
		VALUES   (@rUserSourceId,@DocumentId,@DocumentName,1)  
		END
		if(@rUserSourceTypeId=2003)
		BEGIN
		INSERT INTO sStudent.tStudentDocument
			(
				StudentId, 
				SubmitDocumentMasterId,
				DocumentName,
				IsMigrate
			)
			VALUES   (@rUserSourceId,@DocumentId,@DocumentName,1)   
		END 
	SELECT 1 AS Result
	
	COMMIT TRANSACTION
	
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH
		
END

GO


IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[sStudent].[pStudentAllBatchDocumentSubmitGet]') AND type IN (N'P') )
BEGIN
	DROP PROCEDURE [sStudent].[pStudentAllBatchDocumentSubmitGet]
END
GO

CREATE PROCEDURE [sStudent].[pStudentAllBatchDocumentSubmitGet]
	 
        @rStudentId bigint,
		@rOrgId int
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
 
	BEGIN
			SELECT DISTINCT Isnull(D.Id,0) AS DocumentId,ISNULL(D.DocumentName,'') AS DocumentName,
			CASE WHEN   UD.DocumentId is null THEN 'False' ELSE 'True'END AS IsCheck,
			 ISNULL(UD.DocumentName,'') As FileName,
			isnull(Ud.OrgGroupBatchId,0) AS OrgGroupBatchId,ISNULL(S.IsMigrate,0) as IsMigrate,
			Isnull(cast(UD.DocumentSize as nvarchar),'') AS DocumentSize
		 	FROM sCommon.tSubmitDocumentMaster D
			INNER JOIN sCommon.tSubmitDocumentScope DS ON DS.SubmitDocumentId = D.Id
			INNER JOIN sStudent.tAcademic A ON A.ClassId = DS.SourceId AND A.StudentId = @rStudentId
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId AND BM.IsActive = 1
			LEFT Join sStudent.tStudentDocument  S ON S.SubmitDocumentMasterId=D.id AND S.StudentId=@rStudentId
			Left Join [sCommon].[tUploadDocument] UD On UD.DocumentId=D.id AND UD.UploadFunctionalityId=11 AND UserSourceTypeId=2003  AND UserSourceId=@rStudentId
			WHERE D.OrgId=@rOrgId AND SubmitDocumentFunctionalityId='1'

			UNION 

			SELECT DISTINCT Isnull(D.Id,0) AS DocumentId,ISNULL(D.DocumentName,'') AS DocumentName,
			CASE WHEN  UD.DocumentId is null THEN 'False' ELSE 'True'END AS IsCheck,
			 ISNULL(UD.DocumentName,'') As FileName,
			isnull(Ud.OrgGroupBatchId,0) AS OrgGroupBatchId,ISNULL(S.IsMigrate,0) as IsMigrate,
			Isnull(cast(UD.DocumentSize as nvarchar),'') AS DocumentSize
		 	FROM sCommon.tSubmitDocumentMaster D
			LEFT JOIN sCommon.tSubmitDocumentScope DS ON DS.SubmitDocumentId = D.Id AND DS.SubmitDocumentId is null
			LEFT JOIN sStudent.tAcademic A ON A.ClassId = DS.SourceId AND A.StudentId = @rStudentId 
			LEFT JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId AND BM.IsActive = 1
			LEFT Join sStudent.tStudentDocument  S ON S.SubmitDocumentMasterId=D.id AND S.StudentId=@rStudentId
			Left Join [sCommon].[tUploadDocument] UD On UD.DocumentId=D.id AND UD.UploadFunctionalityId=11 AND UserSourceTypeId=2003  AND UserSourceId=@rStudentId
			WHERE D.OrgId=@rOrgId AND SubmitDocumentFunctionalityId='1' AND A.ClassId is not null--AND DS.SubmitDocumentId is null 


END

GO

IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[sStudent].[pStudentDocumentAllBatchClassWiseGet]') AND type IN (N'P') )
BEGIN
	DROP PROCEDURE [sStudent].[pStudentDocumentAllBatchClassWiseGet]
END
GO



CREATE PROCEDURE [sStudent].[pStudentDocumentAllBatchClassWiseGet]
	@rClassId int=0,
	@rDivisionId int=0,
	@rRollNo int=NULL,
	@rOrgId int,
	@rCode nvarchar(20),
	@rStatusId smallint=0,
	@rFirstName nvarchar(100)='',
	@rLastName nvarchar(100)='',
	@rBatchId int,
    @rSUId nvarchar(50)='',
    @rUserId bigint=0,
    @rMultiCode nvarchar(max)='',
	@rDocumentId int=0,
	@rOrderByTypeId int=0	--add
	
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	 
		BEGIN
			SET @rCode= sCommon.fSearchStringGet(@rCode)
			SET @rFirstName = sCommon.fSearchStringGet(@rFirstName)
			SET @rLastName = sCommon.fSearchStringGet(@rLastName)
		END
	IF(@rRollNo IS NULL)
	BEGIN
	SELECT 
			SA.AcademicId,
			SA.StudentId,
			SA.FirstName,
			SA.LastName,
			SA.Name,
			SA.Code,
			SA.ClassId,
			SA.ClassName,
			SA.DivisionId,
			SA.DivisionName,
			ISNULL(SA.Number,0) AS Number,
			SA.RollNo,
			SA.StatusId,
			SA.StatusName,
			SA.OrgId,
			SA.SUId,
			--SD.DocumentName
			--ISNULL(STUFF(
			-- (SELECT DISTINCT ',' + SDM.DocumentName
			--  FROM sCommon.tSubmitDocumentMaster SDM
			--  INNER JOIN  sStudent.tStudentDocument SD ON SDM.Id=SD.SubmitDocumentMasterId
			--  INNER JOIN sCommon.tSubmitDocumentScope DS ON DS.SubmitDocumentId=SDM.Id AND DS.SourceId = @rClassId
			--  where SD.StudentId=SA.StudentId AND SDM.SubmitDocumentFunctionalityId = 1 AND ((SDM.Id=@rDocumentId)OR(@rDocumentId=0))
			--  FOR XML PATH (''))
			--  , 1, 1, ''),'')  AS DocumentName,
			  ISNULL(sStudent.fStudentDocumentAllBatchClasswiseget(@rDocumentId,SA.AcademicId),'') AS DocumentName
			
  FROM 
          sStudent.vStudentAcademic SA
		  --LEFT JOIN sStudent.tStudentDocument SD ON SD.StudentId=SA.StudentId
		  INNER JOIN sSecurity.tUserAccess U ON U.SourceId = SA.DivisionId AND U.SourceTypeId=2005
             
  WHERE 
 
		((SA.ClassId=@rClassId)OR(@rClassId=0))
		AND((SA.DivisionId=@rDivisionId)OR(@rDivisionId=0))
		AND((SA.Code like @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)
		AND(SA.BatchId=@rBatchId)
		AND((SA.SUID = @rSUId) OR (ISNULL(@rSUId,'') = '')) 
		--AND((SA.Number=@rNumber)OR(@rNumber=0))	
		AND U.UserId = @rUserId
		AND (ISNULL(SA.Code,0) IN( SELECT cast(item as nvarchar(20)) FROM  sCommon.fnsplit(@rMultiCode,',')) OR @rMultiCode='')
ORDER BY CASE WHEN @rOrderByTypeId = 1 THEN SA.RollNo END,		--add case
		 CASE WHEN @rOrderByTypeId = 2 THEN (CASE ISNUMERIC(SA.Code) WHEN 1 THEN REPLICATE(0, 100 - LEN(SA.Code)) + SA.Code ELSE SA.Code END) END,	--add case
		 SA.ClassId,SA.DivisionId,SA.RollNo
END
ELSE
BEGIN
	SELECT 
			SA.AcademicId,
			SA.StudentId,
			SA.FirstName,
			SA.LastName,
			SA.Name,
			SA.Code,
			SA.ClassId,
			SA.ClassName,
			SA.DivisionId,
			SA.DivisionName,
			SA.Number,
			SA.RollNo,
			SA.StatusId,
			SA.StatusName,
			SA.OrgId,
			SA.SUId,
			--SD.DocumentName
			 ISNULL(sStudent.fStudentDocumentAllBatchClasswiseget(@rDocumentId,SA.AcademicId),'') AS DocumentName
			
			
  FROM 
          sStudent.vStudentAcademic SA
		  --LEFT JOIN sStudent.tStudentDocument SD ON SD.StudentId=SA.StudentId
          INNER JOIN sSecurity.tUserAccess U ON U.SourceId = SA.DivisionId AND U.SourceTypeId=2005
  WHERE 
 
		((SA.ClassId=@rClassId)OR(@rClassId=0))
		AND((SA.DivisionId=@rDivisionId)OR(@rDivisionId=0))
		AND((SA.Code like @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)
		AND(SA.BatchId=@rBatchId)
		AND((SA.SUID = @rSUId) OR (ISNULL(@rSUId,'') = '')) 
		AND U.UserId = @rUserId
		AND (ISNULL(SA.Code,0) IN( SELECT cast(item as nvarchar(20)) FROM  sCommon.fnsplit(@rMultiCode,',')) OR @rMultiCode='')
		--AND((SA.Number=@rNumber)OR(@rNumber=0))	

ORDER BY CASE WHEN @rOrderByTypeId = 1 THEN SA.RollNo END,		--add case
		 CASE WHEN @rOrderByTypeId = 2 THEN (CASE ISNUMERIC(SA.Code) WHEN 1 THEN REPLICATE(0, 100 - LEN(SA.Code)) + SA.Code ELSE SA.Code END) END,	--add case
		 SA.ClassId,SA.DivisionId,SA.RollNo
END
  
	
END

GO

PRINT N'Altering [sCommon].[fnSplit]...';


GO



 
/******************************************************************************  
 Purpose          : To get Batch Wise  Class
 Created date     : 21 Nov 2013
 Author           : Kundan Patel 
 Copyright©       : Copyright © Sapphire Software Solutions
 ******************************************************************************/  
ALTER VIEW [sAssessment].[vGeneralExamColumnName]  
  
AS  
  
SELECT 	
		 --SA.AcademicId,	  
		 --SA.ClassId,
		 --SA.DivisionId,
		 SA.RollNo,
		 --SA.OrgId,
		 --SA.BatchId,
		 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,
		 R.TotalMarks,
		 R.TotalObtain,
		 R.ResultStatus,
		 R.ResultGrade,
		 R.ResultGradePoint,
		 R.RankNumber,
		 R.Percentage,
		 R.Percentile,
		 R.ResultRemark,
		 R.OtherRemark1,
		 ESGM.Code AS ExamCode,
		 ESGM.Title AS ExamName,
		 --EM.Id AS Id,
	     U.DisplayTitle AS CreatedUserName,
	     SR.ExamSeatNo,
	     SR.TotalDays,
	     SR.PresentDays,
	     SR.StudentHeight,
	     SR.StudentWeight,
	     SR.ResultRemark1,
	     SR.ResultRemark2,
	     SR.MyGoal,
	     SR.MyStrength,
	     SR.MyInterestHobby,
	     SR.Achievements,
	     SR.AreaOfInterest,
	     SR.Responsibility,
	     SR.DentalHygiene,
	     SR.VisionLeft,
	     SR.VisionRight,
	     SR.MyActivity,
	     SR.ClassTeacherRemark,
	     SR.HouseRemark,
	     SR.ResultRemark3,
	     SR.GeneralRemark,
		 CCM.Code As CastCategory,
		 SF.FatherName,
		 SF.MotherName,
	     ACM.Title AS FeeCategory,
		 HM.Title AS House,
		 SO.DateOfBirth
	     
	  	  	   
FROM 
		sStudent.vStudentAcademic SA
	INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=SA.OrgId
	INNER JOIN sSetup.tBatchMaster BM ON BM.Id=SA.BatchId
	INNER JOIN sAssessment.tResult R ON R.AcademicId=SA.AcademicId
	INNER JOIN sAssessment.tExamMaster EM ON EM.Id=R.ExamId
	INNER JOIN sSecurity.tUser U ON U.Id=R.UpdatedUserId
	INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId
	LEFT JOIN sAssessment.tStudentRemark SR ON SR.AcademicId=SA.AcademicId
	LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId=SA.StudentId
	LEFT JOIN sCommon.tCastCategoryMaster CCM ON CCM.Id=SO.CastCategoryId
	LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId = SA.StudentId
	LEFT JOIN sStudent.tAdmissionCategoryMaster ACM ON SA.AdmissionCategoryId = ACM.Id
	LEFT JOIN sActivity.tHouseMaster HM ON SO.HouseId = HM.Id
GO
PRINT N'Altering [sAssessment].[vGeneralExamCustomSearch]...';


GO
/******************************************************************************  
 Purpose          : To get Batch Wise  Class
 Created date     : 21 Nov 2013
 Author           : Kundan Patel 
 Copyright©       : Copyright © Sapphire Software Solutions
 ******************************************************************************/  
ALTER VIEW [sAssessment].[vGeneralExamCustomSearch]  
  
AS  
  
SELECT 	
		 SA.AcademicId,	  
		 SA.ClassId,
		 SA.DivisionId,
		 SA.RollNo,
		 SA.OrgId,
		 SA.BatchId,
		 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,
		 R.Id AS ResultId,
		 R.ExamId AS ExamId,
		 R.TotalMarks,
		 R.TotalObtain,
		 R.ResultStatus,
		 R.ResultGrade,
		 R.ResultGradePoint,
		 R.RankNumber,
		 R.Percentage,
		 R.Percentile,
		 R.ResultRemark,
		 R.OtherRemark1,
		 ESGM.Code AS ExamCode,
		 ESGM.Title AS ExamName,
	     U.Id AS CreatedUserId,
	     U.DisplayTitle AS CreatedUserName,
	     EM.ExamSubGroupId,
	     SR.ExamSeatNo,
	     SR.TotalDays,
	     SR.PresentDays,
	     SR.StudentHeight,
	     SR.StudentWeight,
	     SR.ResultRemark1,
	     SR.ResultRemark2,
	     SR.MyGoal,
	     SR.MyInterestHobby,
	     SR.MyStrength,
	     SR.Achievements,
	     SR.AreaOfInterest,
	     SR.Responsibility,
	  	 SR.DentalHygiene,
	  	 SR.VisionLeft,
	  	 SR.VisionRight  ,
	  	  CM.DepartmentId,
	  	  SR. MyActivity,
	  	  SR.ClassTeacherRemark,
	  	  SR.HouseRemark,
	  	  SR.ResultRemark3,
	  	  SR.GeneralRemark,
		  CCM.Id As CastCategoryId,
		  CCM.Code As CastCategory,

		  SF.FatherName,
		  SF.MotherName,
	      ACM.Title AS FeeCategory,
		  HM.Title AS House,
		  CONVERT(VARCHAR(10), SO.DateOfBirth, 103) AS DateOfBirth
		  --SM.Id AS SubjectId,
		  --SM.Title AS SubjectTitle   
FROM 
		sStudent.vStudentAcademic SA
	 INNER JOIN sSetup.tClassMaster  CM ON CM.Id= SA.ClassId
	 --Add By Vishkha
	 --INNER Join sSetup.tClassSubject CS ON CS.ClassId=CM.Id
	 --INNER JOIN sSetup.tSubjectMaster SM on CS.SubjectId=SM.Id AND SM.OrgId = SA.OrgId
	
	INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=SA.OrgId
	INNER JOIN sSetup.tBatchMaster BM ON BM.Id=SA.BatchId
	INNER JOIN sAssessment.tResult R ON R.AcademicId=SA.AcademicId
	INNER JOIN sAssessment.tExamMaster EM ON EM.Id=R.ExamId
	LEFT JOIN sSecurity.tUser U ON U.Id=R.UpdatedUserId
	INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId
	LEFT JOIN sAssessment.tStudentRemark SR ON SR.AcademicId = SA.AcademicId AND SR.ExamId = EM.Id
	LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId=SA.StudentId
	LEFT JOIN sCommon.tCastCategoryMaster CCM ON CCM.Id=SO.CastCategoryId

	LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId = SA.StudentId
	LEFT JOIN sStudent.tAdmissionCategoryMaster ACM ON SA.AdmissionCategoryId = ACM.Id
	LEFT JOIN sActivity.tHouseMaster HM ON SO.HouseId = HM.Id
GO
PRINT N'Altering [sStudent].[vStudentAllDetail]...';


GO
ALTER VIEW [sStudent].[vStudentAllDetail]  
  
AS  
  
SELECT 
	  A.Id AS AcademicId,	  
	  A.ClassId,
	  A.DivisionId,
	  A.RollNo,
	  A.OrgId,
	  A.BatchId,
	  SM.Id AS StudentId,
	  SM.Code,
	  SM.Number,
	  SM.FirstName,
	  SM.MiddleName,
	  SM.LastName,
	  [sStudent].[fStudentNameGet](SM.FirstName , SM.MiddleName, SM.LastName,OM.StudentNameFormatId ) AS Name,
	  CM.DisplayTitle+' / '+DM.DisplayTitle AS ClassDivision,
	  SM.StatusId,
	  CM.DisplayTitle AS ClassName,
	  DM.DisplayTitle AS DivisionName,
	  STM.Title AS StatusName,
	  SA.LCProgress,
	  SA.LCConduct,
	  SA.LeftDate,
	  SA.PreviousSchool,
	  SA.LeftReason,
	  SA.InactiveDate,
	  SA.AdmissionDate,
	  AdmissionStandard=(SELECT Title FROM SSetup.tClassMaster WHERE Id=SA.AdmissionStandardId),
	  LeftStandard=(SELECT Title FROM SSetup.tClassMaster WHERE Id=SA.LeftStandardId),
	  SA.LCNumber,
	  SA.LCDate,
	  RM.Title AS Religion,
	  SO.FamilyCast,
	  SO.FamilySubCast,
	  SO.BirthPlace,
	  SO.BirthTaluka,
	  SO.BirthDistrict,
	  ISNULL(SO.DateOfBirth,'0001/01/01') AS DateOfBirth,
	  SO.BirthDateInWord,
	  (SI.StudentPhoto) AS StudentPhoto,
	  (SI.FatherPhoto) AS FatherPhoto,
	  (SI.MotherPhoto) AS MotherPhoto,
	  (SI.RelativePhoto) AS RelativePhoto,
	  BGM.Title AS BloodGroup,
	  ISNULL(SC.PermanentStreetOne,'')+' '+ISNULL(SC.PresentStreetTwo,'')+' '+ISNULL(SC.PresentStreetThree,'')+' '+ISNULL(SC.PresentCity,'')+' '+ISNULL(SC.PresentState,'')+' '+ISNULL(SC.PresentZipCode,'') AS PresentAddress,
	  GM.Id AS GenderId,
	  ISNULL(GM.Title,'') AS Gender,
	  ISNULL(SC.StudentContactNo,'') AS ContactNo,
	  BM.Title AS Batch,
	  ISNULL(ACM.Title,'') AS AdmissionCategory,
	  SO.HouseId,
	  ISNULL(SC.PresentStreetone,'') AS PresentStreetone,
	  ISNULL(SC.PresentStreetTwo,'') AS PresentStreetTwo,
	  ISNULL(SC.PresentStreetThree,'') AS PresentStreetThree,
	  ISNULL(SC.PresentCity,'-') AS PresentCity,
	  ISNULL(SC.PresentState,'-') As PresentState,
	  ISNULL(SC.PresentZipCode,'-') as PresentZipCode,
	  ISNULL(SC.PresentCountry,'-') AS PresentCountry,
	  ISNULL(SC.PresentContactNo,'-') as PresentContactNo,
	  ISNULL(SC.ParentEmail,'-') AS ParentEmail,
	  ISNULL(SC.ParentContactNo,'-') AS ParentContactNo,
	  ISNULL(SC.StudentContactNo,'-') AS StudentContactNo,
	  DM.OrderIndex AS DivisionOrder,
	  SM.RegistrationNumber,
	  BM.IsActive AS IsActiveBatch,
	  CM.DepartmentId,
	  DEM.Title as DepartmentName,
	  BM.OrgGroupBatchId ,
	  ISNULL(SO.UIDNumber,'' ) AS UIDNumber,
	  ISNULL(SO.AdhaarNumber,'') AS AdhaarNumber,
	  ISNULL(SM.SUId,'') AS SUId,
	  ISNUll(SA.IsTransfer,0)AS IsTransfer,
	  ISNULL(SA.TransferFrom,'') AS TransferFrom,
	  ISNULL(SA.CertificateName,'') AS CertificateName,
	  ISNUll(SA.IsTFWS,0)AS IsTFWS,
	  ISNUll(SA.IsCertificateHolder,0)AS IsCertificateHolder,
	  ISNULL(SC.EmergencyStreetOne,'') AS EmergencyStreetOne,
	  ISNULL(SC.EmergencyStreetTwo,'') AS EmergencyStreetTwo,
	  ISNULL(SC.EmergencyStreetThree,'') AS EmergencyStreetThree,
	  ISNULL(SC.EmergencyCountry,'') AS EmergencyCountry,
	  ISNULL(SC.EmergencyState,'') As EmergencyState,
	  ISNULL(SC.EmergencyCity,'') AS EmergencyCity,
	  ISNULL(SC.EmergencyZipCode,'') as EmergencyZipCode,
	  ISNULL(SC.EmergencyContactNo,'') AS EmergencyContactNo,
	  ISNULL(CM.StreamId,0) AS StreamId,
	  Isnull(SO.CastCategoryId,0) AS CastCategoryId,
	  Isnull(SO.NationalityId,0) AS NationalityId,
	  ISNULL(SO.MotherTongue,'') As MotherTongue,
	  Isnull(SO.BirthState,'') AS BirthState,
	  ISNULL(SO.BirthCountry,'') As BirthCountry,
	  ISNULL(SC.PermanentStreetOne,'') AS  PermanentStreetOne ,
	  ISNULL(SC.PermanentStreetTwo,'')  AS  PermanentStreetTwo,
	  ISNULL(SC.PermanentStreetThree,'') AS PermanentStreetThree,
	  ISNULL(SC.PermanentCity,'') AS PermanentCity,
	  ISNULL(SC.PermanentState,'') AS PermanentState,
	  ISNULL(SC.PermanentCountry,'') AS PermanentCountry,
	  ISNULL(SC.PermanentZipCode,'') AS PermanentZipCode,
	  ISNULL(SC.PermanentContactNo,'') AS PermanentContactNo,
	  ISNULL(Sc.StudentEmail,'') AS StudentEmail,
	  ISNULL(SC.PresentDistanceFromSchool,0) AS PresentDistanceFromSchool,
	  ISNULL(NM.Nationality,'') AS Nationality,
	  ISNULL(SA.PreviousStandard,'')AS PreviousStandard,
	  A.ClassStatusId,
	  STM1.Title AS ClassStatusName,
	  ISNULL(WhatsAppContactNo, '-') AS WhatsAppContactNo,
	  SO.ReferenceRemark

  FROM 
  
	sStudent.tAcademic A
	INNER JOIN sStudent.tStudentMaster SM ON A.StudentId=SM.Id	
	INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId
	INNER JOIN sSetup.tDepartmentMaster DEM on DEM.Id=CM.DepartmentId
	INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId
	INNER JOIN sStudent.tStatusMaster STM ON STM.Id=SM.StatusId
	LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId=A.StudentId
	LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId=A.StudentId
	LEFT JOIN sStudent.tStudentAdmission SA ON SA.StudentId=A.StudentId
	LEFT JOIN sCommon.tReligionMaster RM ON RM.Id=SO.ReligionId
	LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId=A.StudentId
	LEFT JOIN 	sCommon.tBloodGroupMaster BGM ON BGM.Id=SO.BloodGroupId
	INNER JOIN sSetup.tBatchMaster BM ON BM.Id=A.BatchId
	LEFT JOIN sCommon.tGenderMaster GM ON GM.Id=SO.GenderId
	LEFT JOIN sStudent.tAdmissionCategoryMaster ACM ON ACM.Id=A.AdmissionCategoryId
	INNER JOIN sSetup.tOrganizationMaster OM ON SM.OrgId = OM.Id
	LEFT JOIN sCommon.tCountryMaster NM ON Nm.Id=SO.NationalityId
	INNER JOIN sStudent.tStatusMaster STM1 ON STM1.Id=A.ClassStatusId
GO



GO
PRINT N'Altering [sAcademic].[pLessonPlanGet]...';


GO

ALTER PROCEDURE [sAcademic].[pLessonPlanGet]

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

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

			--sAcademic.tLessonPlan LP
			--INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id=LP.EmployeeId
			--INNER JOIN sAcademic.tTopicMaster TM ON TM.Id=LP.TopicId
			--INNER JOIN sAcademic.vTeacherSubjectDivision vTSD ON vTSD.DivisionId = LP.DivisionId
			--AND vTSD.ClassId = TM.ClassId 
			--AND vTSD.SubjectId = TM.SubjectId 
			--AND vTSD.EmployeeId = LP.EmployeeId
			--INNER JOIN sSetup.tClassMaster CM ON CM.Id = vTSD.ClassId
	WHERE 
		((LP.BatchId = @rBatchId) OR (@rBatchId = 0))
		 AND ((LP.EmployeeId = @rEmployeeId) OR (@rEmployeeId=0))
		AND ((LP.Id = @rId) OR (@rId = 0))
		AND ((TM.ClassId = @rClassId) OR (@rClassId = 0))
		AND ((LP.DivisionId = @rDivisionId) OR (@rDivisionId = 0))
		AND ((TM.SubjectId = @rSubjectId) OR (@rSubjectId = 0))
		AND ((@rStatus = 2) OR (LP.IsCompleted=@rIsCompleted))
		AND ((CM.DepartmentId = @rDepartmentid) OR (@rDepartmentid=0))
		--AND (LP.StartDate>=@rFromDate OR ISNULL(@rFromDate,'')='')
		--AND (LP.StartDate<=@rToDate OR ISNULL(@rToDate,'')='')
	    AND ((LP.StartDate >= @rFromDate OR ISNULL(@rFromDate,'')='' )AND (LP.StartDate <= @rToDate OR ISNULL(@rToDate,'')='')
		OR (LP.EndDate >= @rFromDate OR ISNULL(@rFromDate,'')='' )AND (LP.EndDate <= @rToDate OR ISNULL(@rToDate,'')='')
		)

		AND (LP.CreatedUserId=@rCreatedUserId OR ISNULL(@rCreatedUserId,'')='')
		AND ISNULL(EM.IsOtherUser,0) = 0
	ORDER BY
		LP.id 
	END
END
GO
PRINT N'Altering [sAlert].[pAssignedToEmployeeQueryGet]...';


GO
 
ALTER PROCEDURE [sAlert].[pAssignedToEmployeeQueryGet]
	 	 
	 	 @rQueryId bigint,	 	 
	 	 @rSubject nvarchar(100),
	 	 @rTemplate nvarchar(max)--,
	 	 --@rFromSourceTypeId smallint
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	DECLARE @AssignedTo bigint;
	DECLARE @AssignedToEmailId varchar(100);
	
		   SELECT 
		     QM.Id AS QueryId,
		     (ISNULL(EM.CompanyEmail,'')) AS EmailId,		    
		     ISNULL(EM.MobileNumber,'') AS MobileNo,
		     replace(replace(@rTemplate,'[Name]',EM.EmployeeName),'[QueryNo]',QM.number) AS MsgText,
		     @rSubject AS Subject,
			 95 AS ReceiverSourceTypeId,
			 EM.EmployeeId AS ReceiverSourceId,
			 OM.Id AS OrgId,
			 OM.OrgGroupId,
			 95 AS SourceTypeId,
			 EM.EmployeeId AS SourceId  ,
			 EM.EmployeeName AS Name,
			 QM.number AS QueryNo,
			 ISNULL(EC.WhatsAppContactNo,'') AS WhatsAppContactNo
		     
	       FROM 
			sCommunication.tQuery QM
			INNER JOIN sHrm.vEmployeeCommonDetail EM ON QM.AssignedToEmployeeId=EM.EmployeeId 
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = EM.OrgId
			LEFT JOIN sHrm.tEmployeeCommunications EC ON EC.EmployeeId = EM.EmployeeId
	      WHERE
		    QM.Id = @rQueryId 
		
END
GO
PRINT N'Altering [sAlert].[pLeaveHierarchyListingGet]...';


GO

ALTER PROCEDURE [sAlert].[pLeaveHierarchyListingGet]
	
	 	 @rLeaveId bigint,
		 @rOrgId int,
		 @rEmployeeId bigint,
		 @rStatusId int,
	 	 @rTemplate nvarchar(max),
		 @rSubject nvarchar(100)=''
		 --@rHierarchyLevelCount int

	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

DECLARE @lLeaveCount int,@lEmployeeId bigint, @lLeaveFromDate date, @lLeaveToDate date, @lLeaveReason nvarchar(200),
@lLeaveStatus nvarchar(100),@lEmployeeName nvarchar(100),@lActionByEmployeeName nvarchar(200), @lHierarchyLevelCount int
	
	SELECT @lLeaveCount = COUNT(AutoId) FROM [sHrm].[tLeaveHierarchyLevel] WHERE LeaveId = @rLeaveId
	
	SELECT @lHierarchyLevelCount = ItemValue From sConfig.tConfigurationSetup WHERE ConfigurationId = 485 AND SourceId = @rOrgId
	--SELECT @lLeaveCount,@lHierarchyLevelCount
IF(@lHierarchyLevelCount > 1)
BEGIN
	SELECT 
	 @lLeaveFromDate = FromDate,
	 @lLeaveToDate = ToDate,
	 @lLeaveReason = LeaveReason,
	 @lLeaveStatus = (CASE WHEN @rStatusId = 549 THEN 'Pending' 
						   WHEN @rStatusId = 550 THEN 'Approved'
						   ELSE 'Rejected' END),
	@lEmployeeName = ECD.EmployeeName
	from sHrm.tLeave L 
	INNER JOIN sHrm.vEmployeeCommonDetail ECD  ON L.EmployeeId = ECD.EmployeeId
	 WHERE L.Id = @rLeaveId 
	 --AND L.OrgId = @rOrgId

	 --Select @lEmployeeId

	IF(@lHierarchyLevelCount <> @lLeaveCount)
	BEGIN
		SELECT @lEmployeeId = EmployeeManagerId from sHrm.tEmployeeJobDetail WHERE EmployeeId = @rEmployeeId 
		--AND OrgId = @rOrgId
		SELECT @lActionByEmployeeName = EmployeeName from sHrm.vEmployeeCommonDetail WHERE EmployeeId = @rEmployeeId 
		--AND OrgId = @rOrgId 

		--Select @lEmployeeId , @lActionByEmployeeName
	END

	ELSE
	--on last approval send alert to employee (Who enter leave)
	BEGIN
	Select @lEmployeeId = EmployeeId from sHrm.tLeave WHERE Id = @rLeaveId 
	--AND OrgId = @rOrgId
	SELECT @lActionByEmployeeName = EmployeeName from sHrm.vEmployeeCommonDetail WHERE EmployeeId = @rEmployeeId 
	--AND OrgId = @rOrgId 
	END

	print @lEmployeeId
	print @lEmployeeName
Select 
		EM.Id AS EmployeeId,
		EM.Code,
		ECD.EmployeeName,
		EC.MobileNumber AS MobileNo,	
		EC.CompanyEmail AS EmailId,
		replace (
		replace (
		replace (
		replace (
		replace (
		replace(@rTemplate,'[EmployeeName]',ISNULL(@lEmployeeName,'')),
		'[LeaveFromDate]',ISNULL(@lLeaveFromDate,'')),
		'[LeaveToDate]',ISNULL(@lLeaveToDate,'')),
		'[LeaveReason]',ISNULL(@lLeaveReason,'')),
		'[LeaveStatus]',ISNULL(@lLeaveStatus,'')),
		'[ActionByEmployeeName]',ISNULL(@lActionByEmployeeName,''))
			AS MsgText,
		@rSubject AS Subject,		
		95 AS SourceTypeId,
		EM.Id AS SourceId,
		95 AS ReceiverSourceTypeId,
		EM.Id AS ReceiverSourceId,
		ISNULL(EC.WhatsAppContactNo,'') AS WhatsAppContactNo,
		ECD.EmployeeName AS Name,
		EM.OrgId,
		OM.OrgGroupId

FROM 
		sHrm.tEmployeeMaster EM
		INNER JOIN sHrm.vEmployeeCommonDetail ECD ON EM.Id = ECD.EmployeeId
		LEFT JOIN sHrm.tEmployeeCommunications EC ON EC.EmployeeId = EM.Id
		INNER JOIN sSetup.tOrganizationMaster OM ON EM.OrgId = OM.Id	

		WHERE 
		EM.Id = @lEmployeeId 
		--AND EM.OrgId = @rOrgId

END
END
GO
PRINT N'Altering [sAlert].[pNewQueryDetailsGet]...';


GO
 
 
ALTER PROCEDURE [sAlert].[pNewQueryDetailsGet]
	 	 
	 	 @rQueryId bigint,	 	 
	 	 @rSubject nvarchar(100),
	 	 @rTemplate nvarchar(max),
	 	 @rFromSourceTypeId smallint,
		 @rOrgId int,
		 @rQueryFrom nvarchar(200)
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	DECLARE @AssignedTo bigint;
	DECLARE @AssignedToEmailId varchar(100);
	
	IF(@rQueryFrom = 'Query')
	BEGIN
	IF(@rFromSourceTypeId=2003)
		BEGIN
		   
	       --SET @AssignedTo=(SELECT AssignedToEmployeeId FROM sCommunication.tQuery QM WHERE QM.Id = @rQueryId AND QM.FromSourceTypeId=@rFromSourceTypeId)
	       --SET @AssignedToEmailId=(select CompanyEmail From sHrm.vEmployeeCommonDetail where EmployeeId=@AssignedTo)
	       
	       
		   SELECT 
			 QM.Id AS QueryId,
		     (ISNULL(SC.ParentEmail,'')) AS EmailId,
		    -- 'mohit.patel@vidyalayaschoolsoftware.com' AS EmailId,
		     ISNULL(SC.ParentContactNo,'') AS MobileNo,
		     replace(replace(@rTemplate,'[Name]',SC.Name),'[QueryNo]',QM.number) AS MsgText,
		     @rSubject AS Subject,
			 2003 AS ReceiverSourceTypeId,
			 SC.StudentId AS ReceiverSourceId,
			 OM.Id AS OrgId,
			 OM.OrgGroupId,
			 2003 AS SourceTypeId,
			 SC.StudentId AS SourceId  ,
			 SC.Name AS Name,
			 QM.number AS QueryNo,
			 SC.WhatsAppContactNo
			
	       FROM 
			sCommunication.tQuery QM
			INNER JOIN [sStudent].[vStudentCommunication] SC ON QM.FromSourceId=SC.StudentId
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SC.BatchId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SC.OrgId
			
		
	      WHERE
		    QM.Id = @rQueryId AND FromSourceTypeId=@rFromSourceTypeId AND BM.IsActive=1 AND SC.IsBlockAllAlert=0
		END
   
    IF(@rFromSourceTypeId=95)
		BEGIN
		
		   SELECT 
		     QM.Id AS QueryId,
		     (ISNULL(EM.CompanyEmail,'')) AS EmailId,		    
		     ISNULL(EM.MobileNumber,'') AS MobileNo,
		     replace(replace(@rTemplate,'[Name]',EM.EmployeeName),'[QueryNo]',QM.number) AS MsgText,
		     @rSubject AS Subject,
		     95 AS ReceiverSourceTypeId,
			 EM.EmployeeId AS ReceiverSourceId,
			 OM.Id AS OrgId,
			 OM.OrgGroupId,
			 95 AS SourceTypeId,
			 EM.EmployeeId AS SourceId,
			 ISNULL(EC.WhatsAppContactNo,'') AS WhatsAppContactNo
		     
	       FROM 
			sCommunication.tQuery QM
			INNER JOIN sHrm.vEmployeeCommonDetail EM ON QM.FromSourceId=EM.EmployeeId 
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = EM.OrgId
			LEFT JOIN sHrm.tEmployeeCommunications EC ON EC.EmployeeId = EM.EmployeeId
		
	      WHERE
		    QM.Id = @rQueryId AND FromSourceTypeId=@rFromSourceTypeId
		
		END
		
	IF(@rFromSourceTypeId=96)
	 	BEGIN
		
		   SELECT 
		     QM.Id AS QueryId,
		     (ISNULL(EM.CompanyEmail,'')) AS EmailId,		    
		     ISNULL(EM.MobileNumber,'') AS MobileNo,
		     replace(replace(@rTemplate,'[Name]',EM.EmployeeName),'[QueryNo]',QM.number) AS MsgText,
		     @rSubject AS Subject,
		     96 AS ReceiverSourceTypeId,
			 EM.EmployeeId AS ReceiverSourceId,
			 OM.Id AS OrgId,
			 OM.OrgGroupId,
			 96 AS SourceTypeId,
			 EM.EmployeeId AS SourceId,
			 ISNULL(EC.WhatsAppContactNo,'') AS WhatsAppContactNo
		     
	       FROM 
			sCommunication.tQuery QM
			INNER JOIN sHrm.vEmployeeCommonDetail EM ON QM.AssignedToEmployeeId=EM.EmployeeId 
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = EM.OrgId
			LEFT JOIN sHrm.tEmployeeCommunications EC ON EC.EmployeeId = EM.EmployeeId
		
	      WHERE
		    QM.Id = @rQueryId 
		
		END
	END
	--Alert from My Query
	ELSE
	BEGIN
		SELECT 
		     QM.Id AS QueryId,
		     ISNULL(EM.CompanyEmail,'') AS EmailId,		    
		     ISNULL(EM.MobileNumber,'') AS MobileNo,
			 replace(replace(@rTemplate,'[Name]',EM.EmployeeName),'[QueryNo]',QM.number) AS MsgText,
		     @rSubject AS Subject,
			 95 AS ReceiverSourceTypeId,
			 EM.EmployeeId AS ReceiverSourceId,
			 QM.OrgGroupId,
			 @rOrgId AS OrgId,
			 EM.EmployeeId AS SourceId,
			 95 AS SourceTypeId,
			 ISNULL(EC.WhatsAppContactNo,'') AS WhatsAppContactNo
		     
	       FROM 
			sCommunication.tQuery QM
			INNER JOIN sCommunication.tQueryCategoryMaster QCM ON QCM.Id = QM.QueryCategoryId
			INNER JOIN sCommunication.tQueryCategoryAssignedTo QCA ON QCA.QueryCategoryId = QCM.Id
			INNER JOIN sHrm.vEmployeeCommonDetail EM ON EM.EmployeeId = QCA.SourceId
			LEFT JOIN sHrm.tEmployeeCommunications EC ON EC.EmployeeId = EM.EmployeeId
		
	      WHERE
		    QM.Id = @rQueryId 
	END
		
END
GO
PRINT N'Altering [sAlert].[pQueryCommentGet]...';


GO
 
ALTER PROCEDURE [sAlert].[pQueryCommentGet]
	 	 
		 @rOrgId int,
	 	 @rQueryId bigint,	 	 
	 	 @rSubject nvarchar(100),
		 @rRemark nvarchar(1000),
	 	 @rTemplate nvarchar(max),
	 	 @rFromSourceTypeId smallint,
		 @rQueryFrom varchar(100)
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	IF(@rQueryFrom = 'QueryList')
	BEGIN
	   SELECT 
			 QM.Id AS QueryId,
		     ISNULL(EM.CompanyEmail,'') AS EmailId,		    
		     ISNULL(EM.MobileNumber,'') AS MobileNo,
		    replace (	
		      replace (	
				 replace (
				         replace(
				                  --@rTemplate,'[User]',EM.EmployeeName),
								   @rTemplate,'[User]',
								   CASE WHEN @rFromSourceTypeId = 2003 THEN 'Student' 
								   WHEN @rFromSourceTypeId = 95 THEN 'Employee' 
								   ELSE 'Admin' END),
								  '[Comment]',@rRemark),
								  --'[Time]',QM.CreatedDateTime),
								  '[Time]',GetDate()),
								  '[Query]',QM.Title) 
				            AS MsgText,
		     
		     @rSubject AS Subject,
			 95 AS ReceiverSourceTypeId,
			 EM.EmployeeId AS ReceiverSourceId,
			 QM.OrgGroupId,
			 @rOrgId AS OrgId,
			 EM.EmployeeId AS SourceId,
			 95 AS SourceTypeId
		     
	       FROM 
			sCommunication.tQuery QM
			INNER JOIN sCommunication.tQueryCategoryMaster QCM ON QCM.Id = QM.QueryCategoryId
			INNER JOIN sCommunication.tQueryCategoryAssignedTo QCA ON QCA.QueryCategoryId = QCM.Id
			INNER JOIN sHrm.vEmployeeCommonDetail EM ON EM.EmployeeId = QCA.SourceId
		
	      WHERE
		    QM.Id = @rQueryId 
	END
	ELSE
	BEGIN
	IF(@rFromSourceTypeId=2003)
		BEGIN
	
		 SELECT 
			QM.Id AS QueryId,
		    ISNULL(SC.ParentEmail,'') AS EmailId,
			ISNULL(SC.ParentContactNo,'') AS MobileNo,
			replace (	
				replace (
				    replace (
				         replace(
				                  --@rTemplate,'[User]',SC.Name),
								  @rTemplate,'[User]','Student'),
								   '[Comment]',@rRemark),
								   --'[Time]',QM.CreatedDateTime),
								   '[Time]',GetDate()),
								 '[Query]',QM.Title) 
				            AS MsgText,
		     
		       @rSubject AS Subject,
			   2003 AS ReceiverSourceTypeId,
			   SC.StudentId AS ReceiverSourceId  ,
			   SC.Name AS Name,
			   (CASE WHEN QM.StatusId = 209 THEN 'Open' WHEN QM.StatusId = 210 THEN 'Closed' WHEN QM.StatusId = 709 THEN 'Hold' ELSE '' END) [Status],
				QM.number AS QueryNo,
				SC.WhatsAppContactNo,
				QM.OrgGroupId,
				@rOrgId AS OrgId,
				SC.StudentId AS SourceId,
				2003 AS SourceTypeId
	       FROM 
			sCommunication.tQuery QM
			INNER JOIN [sStudent].[vStudentCommunication] SC ON QM.FromSourceId=SC.StudentId
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SC.BatchId

	      WHERE
		    QM.Id = @rQueryId AND BM.IsActive=1 
		
		END
   
   IF(@rFromSourceTypeId=95)
		BEGIN
			SELECT 
			QM.Id AS QueryId,
		    ISNULL(EM.CompanyEmail,'') AS EmailId,		    
		    ISNULL(EM.MobileNumber,'') AS MobileNo,
		    replace (	
		      replace (	
				 replace (
				         replace(
				                  --@rTemplate,'[User]',EM.EmployeeName),
								   @rTemplate,'[User]','Employee'),
								  '[Comment]',@rRemark),
								  --'[Time]',QM.CreatedDateTime),
								  '[Time]',GetDate()),
								  '[Query]',QM.Title) 
				            AS MsgText,
		     
		     @rSubject AS Subject,
			 95 AS ReceiverSourceTypeId,
			 EM.EmployeeId AS ReceiverSourceId,
			 QM.OrgGroupId ,
			 @rOrgId AS OrgId ,
			 EM.EmployeeId AS SourceId,
			 95 AS SourceTypeId
		     
	       FROM 
			sCommunication.tQuery QM
			INNER JOIN sHrm.vEmployeeCommonDetail EM ON QM.FromSourceId=EM.EmployeeId
		
	      WHERE
		    QM.Id = @rQueryId 

		END
	END
	
		
END
GO
PRINT N'Altering [sAlert].[pQueryStatusGet]...';


GO
 
ALTER PROCEDURE [sAlert].[pQueryStatusGet]
	 	 
		 @rOrgId int,
	 	 @rQueryId bigint,	 	 
	 	 @rSubject nvarchar(100),
	 	 @rTemplate nvarchar(max),
	 	 @rFromSourceTypeId smallint
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	IF(@rFromSourceTypeId=2003)
		BEGIN
	
		 SELECT 
			QM.Id AS QueryId,
		    ISNULL(SC.ParentEmail,'') AS EmailId,
			ISNULL(SC.ParentContactNo,'') AS MobileNo,
			replace (	
				replace (
				    replace (
				         replace(
						  replace(
									@rTemplate,'[Number]',QM.Number),
									'[Query Category]',QCM.Title),
								    '[Title]',QM.Title),
								    '[Name]',SC.Name) ,
								    '[Status]',(CASE WHEN QM.StatusId = 209 THEN 'Open' WHEN QM.StatusId = 210 THEN 'Closed' ELSE '' END))
								 
				            AS MsgText,
		     
		       @rSubject AS Subject,
			   2003 AS ReceiverSourceTypeId,
			   SC.StudentId AS ReceiverSourceId,
			   QM.OrgGroupId,
			   @rOrgId AS OrgId, 
			   2003 AS SourceTypeId,
			   SC.StudentId AS SourceId
	       FROM 
			sCommunication.tQuery QM
			INNER JOIN sCommunication.tQueryCategoryMaster QCM ON QCM.Id = QM.QueryCategoryId
			INNER JOIN sStudent.vStudentCommunication SC ON QM.FromSourceId=SC.StudentId
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SC.BatchId

	      WHERE
		    QM.Id = @rQueryId AND BM.IsActive=1 
		
		END
   
   IF(@rFromSourceTypeId=95)
		BEGIN
			SELECT 
			QM.Id AS QueryId,
		    ISNULL(EM.CompanyEmail,'') AS EmailId,		    
		    ISNULL(EM.MobileNumber,'') AS MobileNo,
		   replace (	
				replace (
				    replace (
				         replace(
						  replace(
									@rTemplate,'[Number]',QM.Number),
									'[Query Category]',QCM.Title),
								    '[Title]',QM.Title),
								    '[Name]',EM.EmployeeName) ,
								    '[Status]',(CASE WHEN QM.StatusId = 209 THEN 'Open' WHEN QM.StatusId = 210 THEN 'Closed' ELSE '' END))
								 
				            AS MsgText,
		     
		     @rSubject AS Subject,
			 95 AS ReceiverSourceTypeId,
			 EM.EmployeeId AS ReceiverSourceId,
			 QM.OrgGroupId,
			 @rOrgId AS OrgId, 
			 95 AS SourceTypeId,
			 EM.EmployeeId AS SourceId 
		     
	       FROM 
			sCommunication.tQuery QM
			INNER JOIN sHrm.vEmployeeCommonDetail EM ON QM.FromSourceId=EM.EmployeeId
			INNER JOIN sCommunication.tQueryCategoryMaster QCM ON QCM.Id = QM.QueryCategoryId
		
	      WHERE
		    QM.Id = @rQueryId 

		END
	--END
	
		
END
GO
PRINT N'Altering [sAlert].[pViewQueryGet]...';


GO
 
ALTER PROCEDURE [sAlert].[pViewQueryGet]
	 	 
	 	 @rQueryId bigint,	 	 
	 	 @rSubject nvarchar(100),
	 	 @rTemplate nvarchar(max),
	 	 @rFromSourceTypeId smallint
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	
	IF(@rFromSourceTypeId=2003)
		BEGIN
		   SELECT 
		     QM.Id AS QueryId,
		     ISNULL(SC.ParentEmail,'') AS EmailId,
		       --'mohit.patel@vidyalayaschoolsoftware.com' AS EmailId,
				ISNULL(SC.ParentContactNo,'') AS MobileNo,
			replace (	
				 replace (
				         replace(
				                  @rTemplate,'[Name]',SC.Name),'[Status]',
							CASE WHEN QM.StatusId = 209 THEN 'Open' 
								 WHEN QM.StatusId = 210 THEN 'Closed' 
								 WHEN QM.StatusId = 709 THEN 'Hold' ELSE '' END),
								 '[QueryNo]',QM.number) 
				            AS MsgText,
		     
		       @rSubject AS Subject,
			   2003 AS ReceiverSourceTypeId,
			   SC.StudentId AS ReceiverSourceId  ,
			   SC.Name AS Name,
			   (CASE WHEN QM.StatusId = 209 THEN 'Open' WHEN QM.StatusId = 210 THEN 'Closed' WHEN QM.StatusId = 709 THEN 'Hold' ELSE '' END) [Status],
				QM.number AS QueryNo,
				SC.WhatsAppContactNo
	       FROM 
			sCommunication.tQuery QM
			INNER JOIN [sStudent].[vStudentCommunication] SC ON QM.FromSourceId=SC.StudentId
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SC.BatchId
			
		
	      WHERE
		    QM.Id = @rQueryId AND FromSourceTypeId=@rFromSourceTypeId AND BM.IsActive=1 AND SC.IsBlockAllAlert=0
		END
   
   IF(@rFromSourceTypeId=95)
		BEGIN
		
		   SELECT
			 QM.Id AS QueryId, 
		     ISNULL(EM.CompanyEmail,'') AS EmailId,		    
		     ISNULL(EM.MobileNumber,'') AS MobileNo,
		     
		     replace (	
				 replace (
				         replace(
				                  @rTemplate,'[Name]',EM.EmployeeName),'[Status]',
							CASE WHEN QM.StatusId = 209 THEN 'Open' 
								 WHEN QM.StatusId = 210 THEN 'Closed' 
								 WHEN QM.StatusId = 709 THEN 'Hold' ELSE '' END),
								 '[QueryNo]',QM.number) 
				            AS MsgText,
		     
		     @rSubject AS Subject,
			 95 AS ReceiverSourceTypeId,
			 EM.EmployeeId AS ReceiverSourceId  
		     
	       FROM 
			sCommunication.tQuery QM
			INNER JOIN sHrm.vEmployeeCommonDetail EM ON QM.FromSourceId=EM.EmployeeId 
		
	      WHERE
		    QM.Id = @rQueryId AND FromSourceTypeId=@rFromSourceTypeId
		
		END
	
		
END
GO
PRINT N'Altering [sAssessment].[pExamSettingAdd]...';


GO

ALTER PROCEDURE [sAssessment].[pExamSettingAdd]
	(
		--@rExamSettingXml nvarchar(MAX),
		--@rOrgId int

		@rExamSettingXml nvarchar(max),
		@rExamSettingTypeId int,
		@rCreatedUserId bigint
	)
AS

SET NOCOUNT ON

BEGIN
SET @rExamSettingXml=REPLACE(@rExamSettingXml,'&','AND')
DECLARE @lInterrorCode INT,
			@intDoc INT
DECLARE @lNextNumber BIGINT			
BEGIN TRY
BEGIN TRANSACTION	
	EXECUTE @lInterrorCode = sp_xml_preparedocument @intDoc OUTPUT, @rExamSettingXml
	
	IF(@rExamSettingTypeId = 1)
	BEGIN
		UPDATE sAssessment.tExamMaster
		SET 
			--IsProcessResult = E.IsProcessResult,
			IsNegativeMarks = E.IsNegativeMarks,
			IsLockForEdit = E.IsLockForEdit,
			IsPublished = E.IsPublished,
			IsPublishExamSchedule = E.IsPublishExamSchedule,
			UpdatedUserId = @rCreatedUserId,
			UpdatedDateTime = sCommon.fGetDate()
		FROM (
		SELECT
			ExamId,
			IsProcessResult,
			IsNegativeMarks,
			IsLockForEdit,
			IsPublished,
			IsPublishExamSchedule
			FROM OPENXML (@intDoc, '/Table/ExamSetting', 1)
		WITH
		(
			ExamId bigint,
			IsProcessResult bit ,
			IsNegativeMarks bit ,
			IsLockForEdit bit,
			IsPublished bit,
			IsPublishExamSchedule bit
		))E 
		Where sAssessment.tExamMaster.Id = E.ExamId
	END
	
	ELSE IF(@rExamSettingTypeId = 2)
	BEGIN
		UPDATE sAssessment.tExamMaster
		SET 
			IsGrade = E.IsGrade,
			IsPercentile = E.IsPercentile,
			IsRankNo = E.IsRankNo,
			IsGenerateRankNo = E.IsGenerateRankNo,
			IsPercentage = E.IsPercentage,
			IsRemovePercentageForFail = E.IsFailPercentageZero,
			IsSubjectPercentile = E.IsSubjectPercentile,
			IsResultStatus = E.IsDisplayResultStatus,
			IsAllExamPassRequired = E.IsAllExamPassRequired,
			IsExcludeAbsentTotal = E.IsExcludeAbsentTotal,
			UpdatedUserId = @rCreatedUserId,
			UpdatedDateTime = sCommon.fGetDate()
		FROM (
		SELECT
			ExamId,
			IsGrade,
			IsPercentile,
			IsRankNo,
			IsGenerateRankNo,
			IsPercentage,
			IsFailPercentageZero,
			IsSubjectPercentile,
			IsDisplayResultStatus,
			IsAllExamPassRequired,
			IsExcludeAbsentTotal
			FROM OPENXML (@intDoc, '/Table/ExamSetting', 1)
		WITH
		(
			ExamId bigint,
			IsGrade bit,
			IsPercentile bit,
			IsRankNo bit,
			IsGenerateRankNo bit,
			IsPercentage bit,
			IsFailPercentageZero bit,
			IsSubjectPercentile bit,
			IsDisplayResultStatus bit,
			IsAllExamPassRequired bit,
			IsExcludeAbsentTotal bit
		))E 
		Where sAssessment.tExamMaster.Id = E.ExamId
	END
	
	ELSE IF(@rExamSettingTypeId = 3)
	BEGIN
		UPDATE sAssessment.tExamMaster
			SET 
				IsDisplayPhoto = E.IsDisplayPhoto,
				IsDisplaySchoolName = E.IsDisplaySchoolName,
				IsDisplayBirthDate = E.IsDisplayBirthDate,
				IsDisplayParentName = E.IsDisplayParentName,
				IsDisplayHeightWeight = E.IsDisplayHeightWeight,
				IsDisplayGradeString = E.IsDisplayGradeString,
				IsDisplayTotalMark = E.IsDisplayTotalMark,
				IsDisplayResultIndicator = E.IsDisplayResultIndicator,
				IsDisplayHighestDivisionMark = E.IsDisplayHighestDivisionMark,
				IsDisplayHighestDivisionGrade = E.IsDisplayHighestDivisionGrade,
				IsDisplayTeacherSign = E.IsDisplayTeacherSign,
				IsDisplayPrincipalSign = E.IsDisplayPrincipalSign,
				IsDisplayActivityGrade = E.IsDisplayActivityGrade,
				UpdatedUserId = @rCreatedUserId,
				UpdatedDateTime = sCommon.fGetDate()
			FROM (
			SELECT
				ExamId,
				IsDisplayPhoto ,
				IsDisplaySchoolName ,
				IsDisplayBirthDate ,
				IsDisplayParentName ,
				IsDisplayHeightWeight ,
				IsDisplayGradeString ,
				IsDisplayTotalMark ,
				IsDisplayResultIndicator ,
				IsDisplayHighestDivisionMark ,
				IsDisplayHighestDivisionGrade ,
				IsDisplayTeacherSign ,
				IsDisplayPrincipalSign ,
				IsDisplayActivityGrade 
				FROM OPENXML (@intDoc, '/Table/ExamSetting', 1)
			WITH
			(
				ExamId bigint,
				IsDisplayPhoto bit,
				IsDisplaySchoolName bit,
				IsDisplayBirthDate bit,
				IsDisplayParentName bit,
				IsDisplayHeightWeight bit,
				IsDisplayGradeString bit,
				IsDisplayTotalMark bit,
				IsDisplayResultIndicator bit,
				IsDisplayHighestDivisionMark bit,
				IsDisplayHighestDivisionGrade bit,
				IsDisplayTeacherSign bit,
				IsDisplayPrincipalSign bit,
				IsDisplayActivityGrade bit
			))E 
			Where sAssessment.tExamMaster.Id = E.ExamId
	END
		
	ELSE
	BEGIN
		UPDATE sAssessment.tExamMaster
			SET 
				IsIncludeCoScholastic = E.IsIncludeCoScholastic,
				IsCoScholasticGradeIndicator = E.IsCoScholasticGradeIndicator,
				IsCoScholasticGradeDesIndicator = E.IsCoScholasticGradeDesIndicator,
				IsCoScholasticGrade = E.IsCoScholasticGrade,
				UpdatedUserId = @rCreatedUserId,
				UpdatedDateTime = sCommon.fGetDate(),
				CoScholasticScopeId = 1
			FROM (
			SELECT
				ExamId,
				IsIncludeCoScholastic ,
				IsCoScholasticGradeIndicator ,
				IsCoScholasticGradeDesIndicator ,
				IsCoScholasticGrade 
				FROM OPENXML (@intDoc, '/Table/ExamSetting', 1)
			WITH
			(
				ExamId bigint,
				IsIncludeCoScholastic bit,
				IsCoScholasticGradeIndicator bit,
				IsCoScholasticGradeDesIndicator bit,
				IsCoScholasticGrade bit
			))E 
			Where sAssessment.tExamMaster.Id = E.ExamId

	END

	EXEC sp_xml_removedocument @intDoc
	COMMIT TRANSACTION
	SELECT 1
	END TRY
	BEGIN CATCH
	ROLLBACK TRANSACTION
	SELECT -1
	END CATCH

END
GO
PRINT N'Altering [sAssessment].[pExamSettingGet]...';


GO

 
ALTER PROCEDURE [sAssessment].[pExamSettingGet]
	 @rExamId int,
	 @rClassId int,
	 @rExamSettingTypeId int
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 	
DECLARE @lExamIds nvarchar(max)	
CREATE TABLE #AllExams
(
ExamIds int
)
INSERT INTO #AllExams
SELECT EM.Id FROM [sAssessment].[tExamMaster] EM 
		WHERE EM.Id =@rExamId  AND EM.CLassId = @rClassId


INSERT INTO #AllExams
SELECT EM.Id 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 =@rExamId  AND EM.CLassId = @rClassId


INSERT INTO #AllExams
SELECT EM.Id 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

		--SELECT * FROM #AllExams

SELECT @lExamIds = STUFF((SELECT ','+ CONVERT(varchar,ExamIds)
                FROM #AllExams
              -- WHERE t.prodtype = 'XYZ'
             FOR XML PATH('')), 1, 1, '')

--SELECT @lExamIds

IF(@rExamSettingTypeId = 1)
BEGIN
SELECT 


			EM.Id,
			EM.BatchId,
			ESGM.Code,
			ESGM.Title AS Name,
			--ISNULL(IsProcessResult,0) AS IsProcessResult,
			ISNULL(IsNegativeMarks,0) AS IsNegativeMarks,
			ISNULL(IsLockForEdit,0) AS IsLockForEdit,
			ISNULL(IsPublished,0) AS IsPublished,
			ISNULL(IsPublishExamSchedule,0) As IsPublishExamSchedule

   FROM 
			sAssessment.tExamMaster EM
			INNER JOIN sAssessment.tExamSubGroupMaster	ESGM ON ESGM.Id = EM.ExamSubGroupId
			INNER JOIN sAssessment.tExamGroupMaster EGM ON EGM.Id=ESGM.ExamGroupId
			INNER JOIN sSetup.tClassMaster CM on CM.Id=EM.ClassId
   WHERE      
			(ISNULL(EM.Id,0) IN( SELECT cast(item as nvarchar(500)) FROM  sCommon.fnsplit(@lExamIds,',')) OR @lExamIds='') 
            AND EM.ClassId=@rClassId AND EM.IsProcessResult = 1
			order by ESGM.Title
END

ELSE IF(@rExamSettingTypeId = 2)		 
BEGIN
	SELECT 
			EM.Id,
			EM.BatchId,
			ESGM.Code,
			ESGM.Title AS Name,
			EM.IsGrade,
			EM.IsPercentile,
			EM.IsRankNo,
			ISNULL(EM.IsGenerateRankNo,0)As IsGenerateRankNo,
			ISNULL(EM.IsPercentage,0) AS IsPercentage,
			ISNULL(Em.IsRemovePercentageForFail,0) AS IsFailPercentageZero,
			ISNULL(EM.IsSubjectPercentile,0) AS IsSubjectPercentile,
			ISNULL(IsResultStatus,0) AS IsDisplayResultStatus,
			ISNULL(IsAllExamPassRequired,0) As IsAllExamPassRequired,
			ISNULL(IsExcludeAbsentTotal,0) AS IsExcludeAbsentTotal


   FROM 
			sAssessment.tExamMaster EM
			INNER JOIN sAssessment.tExamSubGroupMaster	ESGM ON ESGM.Id = EM.ExamSubGroupId
			INNER JOIN sAssessment.tExamGroupMaster EGM ON EGM.Id=ESGM.ExamGroupId
			INNER JOIN sSetup.tClassMaster CM on CM.Id=EM.ClassId
			--INNER Join sSetup.tClassSubject CS ON EM.ClassId=CS.ClassId				
			--INNER JOIN sSetup.tSubjectMaster SM on   CS.SubjectId=SM.Id					
			--LEFT JOIN sAssessment.tExamDetail ED ON ED.ClassSubjectId = CS.Id AND ED.ExamId=EM.Id
			--LEFT Join sAssessment.tGradeSetMaster GSM ON GSM.Id = ED.GradeSetId
  WHERE      
			(ISNULL(EM.Id,0) IN( SELECT cast(item as nvarchar(500)) FROM  sCommon.fnsplit(@lExamIds,',')) OR @lExamIds='') 
            AND EM.ClassId=@rClassId AND EM.IsProcessResult = 1
			order by ESGM.Title

END
ELSE IF(@rExamSettingTypeId = 3)		 
BEGIN
	SELECT 
			EM.Id,
			EM.BatchId,
			ESGM.Code,
			ESGM.Title AS Name,
			ISNULL(IsDisplayPhoto,0) AS IsDisplayPhoto,
			ISNULL(IsDisplaySchoolName,0) AS IsDisplaySchoolName,
			ISNULL(IsDisplayBirthDate,0) AS IsDisplayBirthDate,
			ISNULL(IsDisplayParentName,0) AS IsDisplayParentName,
			ISNULL(IsDisplayHeightWeight,0) AS IsDisplayHeightWeight,
			ISNULL(IsDisplayGradeString,0) AS IsDisplayGradeString,
			ISNULL(EM.IsDisplayTotalMark,0) AS IsDisplayTotalMark,
			ISNULL(EM.IsDisplayResultIndicator,0) AS IsDisplayResultIndicator,
			ISNULL(IsDisplayHighestDivisionMark,0) AS IsDisplayHighestDivisionMark,
			ISNULL(Convert(bit,IsDisplayHighestDivisionGrade),0) AS IsDisplayHighestDivisionGrade,
			ISNULL(IsDisplayTeacherSign,0) AS IsDisplayTeacherSign,
			ISNULL(IsDisplayPrincipalSign,0) AS IsDisplayPrincipalSign,
			ISNULL(IsDisplayActivityGrade,0) AS IsDisplayActivityGrade
			
   FROM 
			sAssessment.tExamMaster EM
			INNER JOIN sAssessment.tExamSubGroupMaster	ESGM ON ESGM.Id = EM.ExamSubGroupId
			INNER JOIN sAssessment.tExamGroupMaster EGM ON EGM.Id=ESGM.ExamGroupId
			INNER JOIN sSetup.tClassMaster CM on CM.Id=EM.ClassId
			--INNER Join sSetup.tClassSubject CS ON EM.ClassId=CS.ClassId				
			--INNER JOIN sSetup.tSubjectMaster SM on   CS.SubjectId=SM.Id					
			--LEFT JOIN sAssessment.tExamDetail ED ON ED.ClassSubjectId = CS.Id AND ED.ExamId=EM.Id
			--LEFT Join sAssessment.tGradeSetMaster GSM ON GSM.Id = ED.GradeSetId
   WHERE      
			(ISNULL(EM.Id,0) IN( SELECT cast(item as nvarchar(500)) FROM  sCommon.fnsplit(@lExamIds,',')) OR @lExamIds='') 
            AND EM.ClassId=@rClassId AND EM.IsProcessResult = 1
			order by ESGM.Title

END
ELSE
BEGIN
SELECT 
			EM.Id,
			EM.BatchId,
			ESGM.Code,
			ESGM.Title AS Name,
			ISNULL(IsIncludeCoScholastic,0) AS IsIncludeCoScholastic,
			ISNULL(IsCoScholasticGradeIndicator,0) AS IsCoScholasticGradeIndicator,
			ISNULL(IsCoScholasticGradeDesIndicator,0) AS IsCoScholasticGradeDesIndicator,
			ISNULL(IsCoScholasticGrade,0) AS IsCoScholasticGrade
   FROM 
			sAssessment.tExamMaster EM
			INNER JOIN sAssessment.tExamSubGroupMaster	ESGM ON ESGM.Id = EM.ExamSubGroupId
			INNER JOIN sAssessment.tExamGroupMaster EGM ON EGM.Id=ESGM.ExamGroupId
			INNER JOIN sSetup.tClassMaster CM on CM.Id=EM.ClassId
			--INNER Join sSetup.tClassSubject CS ON EM.ClassId=CS.ClassId				
			--INNER JOIN sSetup.tSubjectMaster SM on   CS.SubjectId=SM.Id					
			--LEFT JOIN sAssessment.tExamDetail ED ON ED.ClassSubjectId = CS.Id AND ED.ExamId=EM.Id
			--LEFT Join sAssessment.tGradeSetMaster GSM ON GSM.Id = ED.GradeSetId
   WHERE      
			(ISNULL(EM.Id,0) IN( SELECT cast(item as nvarchar(500)) FROM  sCommon.fnsplit(@lExamIds,',')) OR @lExamIds='') 
            AND EM.ClassId=@rClassId AND EM.IsProcessResult = 1
			order by ESGM.Title
END

DROP TABLE #AllExams
		
END
GO
PRINT N'Altering [sCertificate].[pLeavingBulkGet]...';


GO
ALTER PROCEDURE [sCertificate].[pLeavingBulkGet]
	 
	 @rClassID int,
	 @rDivisionId int,
	 @rOrgId int,
	 @rBatchId int,
	 @rOrderBy int = 0,
	 @rStatusId smallint=0
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	
	SELECT 
			SA.AcademicId,
			ISNULL(SA.RollNo,0) AS RollNo,
			SA.Code,
			SA.Name,
			ISNULL(L.Id,0) AS Id,
			ISNULL(L.LCNumber,0) AS LCNumber,
			ISNULL(L.LCDate,'') AS LCDate,
			ISNULL(L.LCRemark,'')AS LCRemark,
			ISNULL(L.LastExamName,'')AS LastExamName,
			ISNULL(L.LastExamResult,'')AS LastExamResult,
			ISNULL(L.RepeatDetail,'')AS RepeatDetail,
			--ISNULL(L.SubjectStudied,'')AS SubjectStudied,
			ISNULL(L.PromoteToClass,'')AS PromoteToClass,
			ISNULL(L.ExtraCurricularActivities,'')As ExtraCurricularActivities,
			ISNULL(L.NCCScoutDetail,'')AS NCCScoutDetail,
			ISNULL(L.TermsInInstitute,'')As TermsInInstitute,
			ISNULL(L.FeeDetail,'')AS FeeDetail,
			ISNULL(L.FeeConcessionDetail,'')AS FeeConcessionDetail,
			ISNULL(AD.TotalDaysAnnual,0)AS TotalDays,
			ISNULL(AD.PresentDaysAnnual,0)AS PresentDays,
			ISNULL(StuA.ProofOfDOB,'')AS ProofOfDOB,
			CASE WHEN EXISTS(SELECT 1 FROM sSetup.tSubjectMaster S  INNER JOIN sSetup.tClassSubject CS ON  S.Id = CS.SubjectId AND CS.ClassId=@rClassId	
								WHERE S.OrgId=@rOrgId AND CS.IsOptional=0) THEN
			reverse(STUFF(reverse(isnull([sCommon].[fXMLTagsReplaceReverse](STUFF((SELECT ',' + S.Title from sSetup.tSubjectMaster S  
						   INNER JOIN sSetup.tClassSubject CS ON  S.Id = CS.SubjectId AND CS.ClassId=@rClassId	
						   WHERE S.OrgId=@rOrgId AND CS.IsOptional=0 FOR XML PATH('')), 1, 1, '')),'') +',' +
			isnull([sCommon].[fXMLTagsReplaceReverse](STUFF((SELECT ',' + S.Title FROM sAssessment.tOptionalSubject OS 
						   INNER JOIN sSetup.tClassSubject CS ON CS.Id = OS.ClassSubjectId 
						   INNER JOIN sSetup.tSubjectMaster S ON  S.Id = CS.SubjectId 
						   WHERE OS.AcademicId = SA.AcademicId FOR XML PATH('')), 1, 1, '')),'') 
						   ), 1, 1, '')) 
						   
			ELSE

			STUFF(reverse(reverse(isnull([sCommon].[fXMLTagsReplaceReverse](STUFF((SELECT ',' + S.Title from sSetup.tSubjectMaster S  
						   INNER JOIN sSetup.tClassSubject CS ON  S.Id = CS.SubjectId AND CS.ClassId=@rClassId	
						   WHERE S.OrgId=@rOrgId AND CS.IsOptional=0 FOR XML PATH('')), 1, 1, '')),'') +',' +
			isnull([sCommon].[fXMLTagsReplaceReverse](STUFF((SELECT ',' + S.Title FROM sAssessment.tOptionalSubject OS 
						   INNER JOIN sSetup.tClassSubject CS ON CS.Id = OS.ClassSubjectId 
						   INNER JOIN sSetup.tSubjectMaster S ON  S.Id = CS.SubjectId 
						   WHERE OS.AcademicId = SA.AcademicId FOR XML PATH('')), 1, 1, '')),'') 
						   )), 1, 1, '') END AS SubjectStudied,
			(SA.ClassName +'-'+SA.DivisionName)AS ClassDivision


			
			
  FROM 
			[sStudent].[vStudentAcademic]  SA 
			LEFT OUTER JOIN sCertificate.tLeaving L ON L.AcademicId=SA.AcademicId
			LEFT JOIN sStudent.tAcademicDetail AD ON SA.AcademicId=AD.AcademicId
			LEFT JOIN sStudent.tStudentAdmission StuA ON StuA.StudentId = SA.StudentId
  WHERE 
			(SA.ClassId=@rClassId OR @rClassId=0)
			AND (SA.DivisionId=@rDivisionId OR @rDivisionId=0)
			AND SA.BatchId=@rBatchId
			AND SA.OrgID=@rOrgId 
			AND L.Id IS NULL
			AND((SA.StatusId=@rStatusId)OR(@rStatusId=0))
			order by
			CASE @rOrderBy WHEN 2 THEN (CASE ISNUMERIC(SA.Code) WHEN 1 THEN REPLICATE(0 , 100 - LEN(SA.Code)) + SA.Code ELSE SA.Code  END) END,
			CASE @rOrderBy WHEN 1 THEN SA.RollNo END,
			CASE @rOrderBy WHEN 0 THEN SA.RollNo END
END
GO
PRINT N'Altering [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
	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 [sCommunication].[pFeedbackAnswerTypeMasterAdd]...';


GO
ALTER PROCEDURE [sCommunication].[pFeedbackAnswerTypeMasterAdd]
	 
	 	@rOrgGroupId smallint,
        @rId bigint=0,
        @rCode nvarchar(200),
        @rTitle nvarchar(200),
        @rIsObsolete bit,
		@rCreatedUserId bigint,
		@rFeedBackAnswerGroupMasterId int
		
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	 DECLARE @lNextNumber BIGINT 

 
	
	
	IF(@rId = 0)	
	BEGIN
		
			if exists(Select 1 from sCommunication.tFeedbackAnswerTypeMaster where Code=@rCode AND ORggroupId=@rOrgGroupId)
	BEGIn
		Select -101 As Result
		Return
	END
	
	If exists(Select 1 from sCommunication.tFeedbackAnswerTypeMaster where Title =@rTitle AND ORggroupId=@rOrgGroupId)
	BEGIN
		Select -102 As Result
		Return
	END
	EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sCommunication.tFeedbackAnswerTypeMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	INSERT INTO sCommunication.tFeedbackAnswerTypeMaster
		(
			Id,
			Code,
			Title,
			IsObsolete,
			OrgGroupId,
			CreatedUserId,
			CreatedDateTime,
			FeedBackAnswerGroupMasterId
		)
	VALUES
		(
			@lNextNumber,
			@rCode,
			@rTitle,
			@rIsObsolete,
			@rOrgGroupId,
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rFeedBackAnswerGroupMasterId
		)
		    SELECT @lNextNumber AS Result
	END	 

ELSE
	 BEGIN
	 
	 if exists(Select 1 from sCommunication.tFeedbackAnswerTypeMaster where Code=@rCode AND ORggroupId=@rOrgGroupId AND Id<>@rId)
	BEGIn
		Select -101 As Result
		Return
	END
	
	If exists(Select 1 from sCommunication.tFeedbackAnswerTypeMaster where Title =@rTitle AND ORggroupId=@rOrgGroupId AND Id<>@rId)
	BEGIN
		Select -102 As Result
		Return
	END
	
	 --SET @lNextNumber = @rId
	    UPDATE  sCommunication.tFeedbackAnswerTypeMaster
	    SET
			Code=@rCode,
			Title=@rTitle,
			OrgGroupId=@rOrgGroupId,
			UpdatedUserId=@rCreatedUserId,
			UpdatedDateTime=sCommon.fGetDate() ,
			FeedBackAnswerGroupMasterId=@rFeedBackAnswerGroupMasterId,
			IsObsolete = @rIsObsolete
	      
	      WHERE Id = @rId
	      SELECT @rId AS Result
	 END  	

	
	END TRY
	
	BEGIN CATCH 
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Altering [sFee].[pDepositBalanceAdd]...';


GO
ALTER PROCEDURE [sFee].[pDepositBalanceAdd]
	 
	@rDepositHeadId int,
	@rClassId int,
	@rBalanceAmount decimal(12,2)
	--@rNegativeBalance decimal(12,2) = 0
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
		---- FOR DELETE 
		--IF(@rIsDeleted=1)
		--BEGIN
		--	DELETE FROM sScholarship.tScholarshipStudentPaid WHERE ScholarshipReceiveId=@rScholarshipReceiveId AND AcademicId=@rAcademicId
		--			SELECT @rScholarshipReceiveId AS Result
		--END	
BEGIN	
BEGIN TRY
BEGIN TRANSACTION	

		---- DATE VALIDATION
		
		--	IF NOT EXISTS (SELECT 1 FROM sScholarship.tScholarshipStudentPaid WHERE AcademicId=@rAcademicId AND ScholarshipReceiveId=@rScholarshipReceiveId)
		--	BEGIN
		--		IF EXISTS (SELECT 1 FROM sScholarship.tScholarshipReceive WHERE ReceiveDate > @rPaidDate )
		--		BEGIN
		--			SELECT -101 AS Result
		--			RETURN
		--		END
		--	END 
		--	ELSE
		--	BEGIN
		--		IF EXISTS	(SELECT 1 FROM sScholarship.tScholarshipStudentPaid SSP INNER JOIN sScholarship.tScholarshipReceive SR ON SR.Id = SSP.ScholarshipReceiveId
		--						AND ScholarshipReceiveId=@rScholarshipReceiveId  AND SR.ReceiveDate > @rPaidDate)
		--		BEGIN
		--			SELECT -101 as Result
		--			RETURN
		--		END 
		--	END 
			
		--	-- AMOUNT VALIDATIEON
			
		--	IF EXISTS (SELECT 1 FROM sScholarship.tScholarshipStudentPaid WHERE AcademicId=@rAcademicId AND ScholarshipReceiveId = @rScholarshipReceiveId)
		--	BEGIN
		--		If EXISTS
		--			(SELECT 1 FROM sScholarship.tScholarshipReceive SR
		--			WHERE SR.Id = @rScholarshipReceiveId AND SR.TotalAmount 
		--			< (SELECT  ISNULL(SUM(SSP.PaidAmount),0) + @rPaidAmount - (SELECT ISNULL(PaidAmount,0) FROM sScholarship.tScholarshipStudentPaid 
		--			WHERE AcademicId=@rAcademicId AND ScholarshipReceiveId = @rScholarshipReceiveId) 
		--			AS TotalPaidAmount FROM sScholarship.tScholarshipStudentPaid SSP 
		--			WHERE ScholarshipReceiveId = @rScholarshipReceiveId)) 				
		--			BEGIN
		--				SELECT -102 as Result
		--				RETURN
		--			END 
		--		END
		--	ELSE
		--		BEGIN
		--			If EXISTS
		--			(SELECT SR.TotalAmount FROM sScholarship.tScholarshipReceive SR WHERE SR.Id = @rScholarshipReceiveId AND SR.TotalAmount 
		--			 < (SELECT  ISNULL(SUM(SSP.PaidAmount),0) + @rPaidAmount AS TotalPaidAmount FROM sScholarship.tScholarshipStudentPaid SSP 
		--				WHERE ScholarshipReceiveId = @rScholarshipReceiveId)) 				
		--			BEGIN
		--				SELECT -102 as Result
		--				RETURN
		--			END 
		--		END			
			
 IF NOT EXISTS (SELECT 1 FROM sFee.tDepositBalance WHERE DepositHeadId=@rDepositHeadId AND ClassId=@rClassId)	
   BEGIN
		INSERT INTO sFee.tDepositBalance
			(
				DepositHeadId,
				ClassId,
				BalanceAmount
				--NegativeBalance
			)
		VALUES
			(
				@rDepositHeadId,
				@rClassId,
				@rBalanceAmount
				--@rNegativeBalance
			)   
	END	 
ELSE
     BEGIN
     
	    UPDATE sFee.tDepositBalance
	    SET
			  BalanceAmount=@rBalanceAmount
			  --NegativeBalance = @rNegativeBalance
	    WHERE DepositHeadId=@rDepositHeadId AND ClassId=@rClassId
	    
	 END  
		SELECT @rDepositHeadId AS Result
	
	COMMIT TRANSACTION
		
END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
	
	END	
END
GO
PRINT N'Altering [sFee].[pDepositBalanceGet]...';


GO

ALTER PROCEDURE [sFee].[pDepositBalanceGet]
          
           @rDepositHeadId int,
           @rBatchId int
AS
SET NOCOUNT ON
BEGIN
SELECT   
		ISNULL(vBC.ClassId,0) AS ClassId,
        ISNULL(vBC.ClassName,'') AS ClassName,
        ISNULL(DB.DepositHeadId,0) AS DepositHeadId,
        ISNULL(DB.BalanceAmount,0.00)AS BalanceAmount
		--ISNULL(DB.NegativeBalance,0.00)AS NegativeBalance
  FROM 		
	  	sSetup.vBatchClass vBC
		LEFT JOIN sFee.tDepositBalance DB ON DB.ClassId =vBC.ClassId AND (DB.DepositHeadId=@rDepositHeadId OR @rDepositHeadId=0)
  WHERE 
		vBC.BatchId=@rBatchId
		order by vBC.OrderIndex
END
GO
PRINT N'Altering [sFee].[pFeeExportDetailsGet]...';


GO
ALTER PROCEDURE [sFee].[pFeeExportDetailsGet]    
      
  @rOrgGroupBatchId int,    
  @rAdmissionCategoryId int,    
  @rClassId int,    
  @rDivisionId int,    
  @rIdNo nvarchar(20)='',    
  @rFirstName nvarchar(100)='',    
  @rFromReceiptNumber int=0,    
  @rToReceiptNumber int=0,    
  @rReceiptBookId int=0,    
  @rSourceTypeId int=0,    
  @rPayTypeId int,    
  @rChequeNo nvarchar(40)='',    
  @rFromDate date,    
  @rToDate date,    
  @rIsObsolete bit,    
  @rOrgId smallint,    
  @rBatchId int,    
  @rOrgGroupId smallint,    
  @rCreatedUserName nvarchar(100),    
  @rCreatedUserId bigint,    
  @rDepartmentId int=0,    
  @rFromChequeDate date='',    
  @rToChequeDate date='',    
  @rSUId nvarchar(50) = '',    
  @rLastName nvarchar(100) = '',  
  @rPayTypeIds nvarchar(max) = '',
  @rBankName nvarchar(100)='',
  @rCancelStatusId int = 0
      
 WITH EXECUTE AS CALLER    
AS    
SET NOCOUNT ON    
        
    BEGIN    
		SET @rFirstName = sCommon.fSearchStringGet(@rFirstName)    
		SET @rLastName = sCommon.fSearchStringGet(@rLastName)    
		SET @rCreatedUserName = sCommon.fSearchStringGet(@rCreatedUserName)   
		SET @rBankName = sCommon.fSearchStringGet(@rBankName)    
    END 
	
BEGIN       

CREATE Table #FeeReceiptDetail
		(
		StatusId bigint,
		ReceiptId bigint,
		FeeCode nvarchar(100),
		FeeAmount decimal(12,2),
		Organization nvarchar(max),
		Batch nvarchar(100),
		BatchId bigint,
		Code nvarchar(20),
		ClassDiv nvarchar(200),
		Name nvarchar(300),
		ReceiptNumber nvarchar(200),
		ReceiptDate Date,
		ReceiptAmount decimal(12,2),
		PayType nvarchar(300),
		ChequeNo nvarchar(40),
		Remark nvarchar(max),
		ChequeDate nvarchar(50),
		InvoiceNumber int,
		ReceiptCreatedDateTime datetime,
		BankName nvarchar(200),
		ReceiptBookName nvarchar(100),
		TotalReceiptAmount decimal(12,2),
		DiscountAmount decimal(12,2),
		VariableAmount decimal(12,2),
		ExemptionAmount decimal(12,2),
		AdditionalAmount decimal(12,2),
		NotApplicableAmount decimal(12,2),
		SUId nvarchar(50)
		
		)


INSERT INTO #FeeReceiptDetail
 SELECT 
    A.StatusId,    
	R.Id AS ReceiptId,
	FM.Code,
	RD.Amount,
	OM.DisplayTitle AS Organization,  
	BM.Title AS Batch,
	BM.Id AS BatchId,
	A.Code AS Code, 
	CM.Title +' - '+ DM.Title AS ClassDiv,
	A.Name,    
	R.ReceiptNumber,   
	R.ReceiptDate,     
	ISNULL(R.ReceiptAmount,0)AS ReceiptAmount,
	PTM.Title AS PayType,    
	CASE WHEN ISNULL(R.ChequeNo,'') != '' THEN R.ChequeNo ELSE CONVERT(nvarchar(20),R.PaymentTransactionId) END AS ChequeNo,    
	R.Remark,
	CONVERT(VARCHAR(10), R.ChequeDate, 103)AS ChequeDate, 
	--ISNULL(CAST(R.ChequeDate AS Date),'') AS ChequeDate, 
	ISNULL(FI.InvoiceNumber,0) AS InvoiceNumber,    
	R.CreatedDateTime AS ReceiptCreatedDateTime,
	R.BankName,    
	RBM.Title AS ReceiptBook,    
    ISNULL(R.TotalReceiptAmount,0)AS TotalReceiptAmount,    
    ISNULL(R.DiscountAmount,0)AS DiscountAmount,
	FA.VariableAmount,
	FA.DiscountAmount AS ExemptionAmount,
	FA.AdditionalAmount,
	FA.NotApplicableAmount,
	ISNULL(A.SUId,'') As SUId
	
  
  FROM     
  
     sFee.tReceipt R    
  INNER JOIN sStudent.vStudentAcademic A    
   ON A.AcademicId=R.SourceId AND (A.AdmissionCategoryId=@rAdmissionCategoryId OR @rAdmissionCategoryId=0)   
   
  INNER JOIN  sSetup.tClassMaster CM ON CM.Id = A.ClassId     
  INNER JOIN  sSetup.tDivisionMaster DM ON DM.Id = A.DivisionId     
  INNER JOIN sCommon.tSourceTypeMaster STM    
   ON STM.Id=R.SourceTypeId    
  INNER JOIN sFinanceCommon.tPayTypeMaster PTM    
   ON PTM.Id=R.PayTypeId    
  INNER JOIN sFee.tReceiptBookMaster RBM    
   ON RBM.Id=R.ReceiptBookId    
  INNER JOIN sSetup.tOrganizationMaster OM    
   ON OM.Id=A.OrgId    
    AND OM.OrgGroupId=@rOrgGroupId    
  INNER JOIN sSetup.tBatchMaster BM    
   ON BM.Id=R.BatchId     
   AND BM.OrgGroupBatchId=@rOrgGroupBatchId    
  LEFT JOIN sSecurity.tUser U ON U.Id=R.CreatedUserId    
  INNER JOIN sFee.vUserReceiptBook URB ON URB.Id=RBM.Id AND URB.UserId=@rCreatedUserId    
  LEFT JOIN sFee.tFeeInvoice FI ON FI.Id = R.FeeInvoiceId    
  
  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
  LEFT JOIN sFee.tFeeAllocation FA ON FA.FeeSetupId=FS.Id AND FA.SourceId=A.AcademicId
  
WHERE     
 ((A.Code like @rIdNo) OR (ISNULL(@rIdNo,'')=''))    
 AND (R.SourceTypeId=2001)    
 AND ((A.FirstName like @rFirstName) OR(ISNULL(@rFirstName,'')=''))    
 AND ((R.ReceiptNumber>=@rFromReceiptNumber)OR(@rFromReceiptNumber=0))    
 AND ((R.ReceiptNumber<=@rToReceiptNumber)OR(@rToReceiptNumber=0))    
 AND ((R.ReceiptBookId=@rReceiptBookId)OR(@rReceiptBookId=0))    
 AND ((R.PayTypeId=@rPayTypeId)OR(@rPayTypeId=0))    
 AND ((ISNULL(R.PayTypeId,0) IN ( SELECT cast(item as int) FROM  sCommon.fnsplit(@rPayTypeIds,','))) OR (ISNULL(@rPayTypeIds,'')=''))
 AND ((R.ChequeNo like @rChequeNo) OR(ISNULL(@rChequeNo,'')=''))    
 AND ((STM.Id=@rSourceTypeId)OR(@rSourceTypeId=0))    
 AND ((R.ReceiptDate>=@rFromDate)OR(ISNULL(@rFromDate,'')=''))    
 AND ((R.ReceiptDate<=@rToDate)OR(ISNULL(@rToDate,'')=''))    
 AND (R.IsObsolete=@rIsObsolete)    
 AND ((A.OrgId=@rOrgId) OR (@rOrgId=0))    
 AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))    
 AND ((ISNULL(U.DisplayTitle,'') like @rCreatedUserName) OR (ISNULL(@rCreatedUserName,'')=''))    
 AND ((CM.DepartmentId = @rDepartmentId) OR (@rDepartmentId=0))    
 AND ((A.ClassId=@rClassId) OR (@rClassId=0))     
 AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId=0))    
 AND ((R.ChequeDate>=@rFromChequeDate)OR(ISNULL(@rFromChequeDate,'')=''))    
 AND ((R.ChequeDate<=@rToChequeDate)OR(ISNULL(@rToChequeDate,'')=''))    
 AND ((A.SUId like @rSUId) OR (ISNULL(@rSUId,'')=''))    
 AND ((A.LastName like @rLastName) OR (ISNULL(@rLastName,'')=''))  
 AND ((R.BankName like @rBankName) OR(ISNULL(@rBankName,'')=''))    
 AND ((R.CancelStatusId = @rCancelStatusId) OR(@rCancelStatusId=0)) ----Added By Dhruv for Issue No.11130    
 ORDER BY R.ReceiptNumber DESC   
 
 --Select * from #FeeReceiptDetail
 DECLARE @cols AS NVARCHAR(MAX),@query  AS NVARCHAR(MAX)

    SELECT @cols = STUFF((SELECT  DISTINCT ',' + QUOTENAME(ID.FeeCode)
                       FROM #FeeReceiptDetail ID FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'),1,1,'')   
 
    SELECT @query = 
    'SELECT  
			P.*,
            ID.VariableAmount,
            ID.ExemptionAmount,
            ID.AdditionalAmount,
            ID.NotApplicableAmount ,
			ID.DiscountAmount
     FROM
    (SELECT  
	
		ReceiptId ,
		Organization ,
		Batch ,
		Code ,
		ClassDiv ,
		Name ,
		ReceiptNumber ,
		ReceiptDate ,
		ReceiptAmount ,
		Remark,
		PayType ,
		ChequeNo ,
		ChequeDate, 
		BankName ,
		ReceiptBookName ,
		InvoiceNumber,    
		ReceiptCreatedDateTime,
		TotalReceiptAmount ,
		FeeCode, 
        FeeAmount,
		SUId
		    		
    FROM #FeeReceiptDetail)X
    PIVOT 
    (
         SUM(FeeAmount) 
         FOR [FeeCode] IN (' +  @cols + ')
    ) P
    LEFT JOIN
	(
		SELECT
		    ReceiptId,
			SUM(VariableAmount) AS VariableAmount,
			SUM(ExemptionAmount) AS ExemptionAmount,
			SUM(AdditionalAmount) AS AdditionalAmount,
			SUM(NotApplicableAmount) AS NotApplicableAmount,
			(DiscountAmount) AS DiscountAmount
		FROM  
			#FeeReceiptDetail
			GROUP BY ReceiptId,DiscountAmount
    ) ID ON ID.ReceiptId = P.ReceiptId
	Order By P.ReceiptNumber DESC
    '
	EXECUTE(@query) 
END
GO
PRINT N'Altering [sFee].[pFeeSetupAdd]...';


GO
ALTER PROCEDURE [sFee].[pFeeSetupAdd]
	 
		@rId int,
        @rClassId int,
        @rAdmissionCategoryId int,
        @rBatchId int,
        @rFeeId int,
        @rIsOptional bit,
        @rIsVariable bit,
        @rAmount decimal(12,2),
        @rStartDate date,
        @rEndDate date,
        @rReceiptBookId int,
        @rCreatedUserId bigint,
		@rUpdatedUserId bigint,
		@rOrgId int,
		@rCheck bit,
		@rIsServiceTax bit,
		@rCollectionGroupId int = 0,
		@rOrgGroupId int=0,
		@rFeeDuration nvarchar(100) ='',
		@rLevelAmount decimal(12,2)=0,
		@rLateFeeRuleId int = 0

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	DECLARE @lFeeSetupId int=0
	
	 IF(@rCheck=1 AND @rId>0)
	 BEGIN
	 
	 IF(@rIsOptional = 1 AND @rIsVariable = 1)
	 BEGIN
		  SELECT 0 as Result
		  RETURN
	 END
	 ELSE
	 BEGIN
			IF EXists( SELECT * FROM (
			SELECT AcademicId,	   
					(SELECT ISNULL(SUM(RD.Amount),0)  
					FROM sFee.tReceipt R INNER JOIN sFee.tReceiptDetail RD
					ON	RD.ReceiptId = R.Id
					AND RD.FeeSetupId = @rId
					WHERE R.SourceId = VA.AcademicId AND R.IsObsolete = 0) PaidAmount,		      
					(SELECT ISNULL(VariableAmount,0)-ISNULL(DiscountAmount,0) +
					IsNULL(AdditionalAmount,0) - ISNULL(NotApplicableAmount,0)  
					FROM  sFee.tFeeAllocation A		  
					WHERE A.SourceId = VA.AcademicId AND A.FeeSetupId = @rId  ) AllocationAmount
					--,
					--(SELECT Amount FROM sFee.tFeeSetup S WHERE S.Id = @rId 
					----S.ClassId = VA.AcademicId
					----AND S.AdmissionCategoryId = VA.AdmissionCategoryId
					--) AS FeeSetupAmount	   
			FROM sStudent.vStudentAcademic VA	   
			WHERE ClassId = @rClassId AND AdmissionCategoryId = @rAdmissionCategoryId AND VA.BatchId = @rBatchId
			   ) ST WHERE (@rAmount + ISNULL(ST.AllocationAmount,0) - ISNULL(ST.PaidAmount,0) < 0))
			   
			   select @rId as Result
			   ELSE
			   SELECT 0 as Result
			   RETURN
	 END
	 
		   
		   
		  --WHERE ST.Amount + AllocationAmount - PaidAmount > 0
		  
	 
	 
		    
		  
	 
		      
	 -- SELECT @lFeeSetupId=R.FeeSetupId FROM
	 -- sFee.tFeeSetup FS
		--LEFT JOIN
		--(
		--    SELECT ISNULL(SUM(RD.Amount),0) AS PaidAmount,
		--    RD.FeeSetupId,FA.VariableAmount,FA.AdditionalAmount,FA.DiscountAmount,FA.NotApplicableAmount 
		--    FROM
		--    sFee.tReceipt R INNER JOIN sFee.tReceiptDetail RD ON	RD.ReceiptId = R.Id
		--     LEFT JOIN sFee.tFeeAllocation FA ON FA.FeeSetupId=RD.FeeSetupId AND FA.SourceId=R.SourceId 
		--     AND FA.SourceTypeId=R.SourceTypeId	
		--	WHERE						
		--	 R.IsObsolete = 0 
		--	 GROUP BY RD.FeeSetupId,R.SourceId,R.SourceTypeId,FA.VariableAmount,FA.AdditionalAmount,
		--	 FA.DiscountAmount,FA.NotApplicableAmount
		
		--) R ON R.FeeSetupId = FS.Id 
		--where ISNULL(R.FeeSetupId,0)=@rId 
		--AND (@rAmount +  ISNULL(R.VariableAmount,0) + ISNULL(R.AdditionalAmount,0.00) -  ISNULL(R.DiscountAmount,0)-ISNULL(R.NotApplicableAmount,0) -ISNULL(R.PaidAmount,0))<0
		--BEGIN
		


--	select @lFeeSetupId as Result
		--	RETURN
		--END
		
	END
	 
 IF(@rId = 0)	
BEGIN
	
	DECLARE @lNextNumber BIGINT     
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sFee.tFeeSetup', 0, 1, 1,@outNextNumber = @lNextNumber output

	INSERT INTO sFee.tFeeSetup
		(
		   Id,
           ClassId,
           AdmissionCategoryId,
           BatchId,
           FeeId,
           IsOptional,
           IsVariable,
           Amount,
           StartDate,
           EndDate,
           ReceiptBookId,
           CreatedUserId,
           CreatedDateTime,
           IsServiceTax,
           CollectionGroupId,
           FeeDuration,
           LevelAmount,
		   LateFeeRuleId
        )
	VALUES
		(
			@lNextNumber,
			@rClassId,
			@rAdmissionCategoryId,
            @rBatchId,
            @rFeeId,
            @rIsOptional,
            @rIsVariable,
            @rAmount,
            @rStartDate,
            @rEndDate,
            @rReceiptBookId,
            @rCreatedUserId,
			sCommon.fGetDate(),
			@rIsServiceTax,
			@rCollectionGroupId,
			@rFeeDuration,
			@rLevelAmount,
			@rLateFeeRuleId
		)

		SELECT 1 AS Result
	END	 
	 ELSE
	 BEGIN
	 
	 SET @lNextNumber = @rId
	    UPDATE  sFee.tFeeSetup
	    SET
			 --ClassId=@rClassId,
			 --AdmissionCategoryId=@rAdmissionCategoryId,
    --         BatchId=@rBatchId,
             IsOptional=@rIsOptional,
             IsVariable=@rIsVariable,
             Amount=@rAmount,
             StartDate=@rStartDate,
             EndDate=@rEndDate,
             ReceiptBookId=@rReceiptBookId,
             UpdatedUserId=@rUpdatedUserId,
			 UpdatedDateTime=sCommon.fGetDate(),
			 IsServiceTax=@rIsServiceTax,
			 CollectionGroupId=@rCollectionGroupId,
			 FeeDuration=@rFeeDuration,
			 LevelAmount=@rLevelAmount,
			 LateFeeRuleId=@rLateFeeRuleId
	      WHERE (Id = @rId)
	       --AND (FeeId=@rFeeId) 

	      SELECT 11 AS Result   
	 END  
	
	If Not Exists(Select 1 from sSystem.tPortalSync where OrgGroupId=@rOrgGRoupId)
	BEGIN
		Insert INto sSystem.tPortalSync 
		(
			OrgGRoupId,
			FeeChange
		)
		Values
		(
			@rOrgGRoupId,
			1
		)
	END
	Else
	BEGIN
		Update sSystem.tPortalSync 
		Set
			FeeChange=1
		Where OrgGroupId=@rOrgGroupId
		
	END

	EXEC [sFee].[pFeeProcessGenerate] @rOrgId,@rBatchId,@rClassId,NULL,NULL,@rCreatedUserId,@lNextNumber

	END TRY
	
	BEGIN CATCH 
		
		SELECT -1 AS Result
	END CATCH
END
GO
PRINT N'Altering [sFee].[pFeeSetupFeeWiseGet]...';


GO
ALTER PROCEDURE [sFee].[pFeeSetupFeeWiseGet]
    @rAdmissionCategoryId int,
	@rBatchId int,
	@rOrgGroupId int,
	@rFeeId int
           
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
BEGIN 
	SELECT 
		ISNULL(FS.Id,0)AS Id,
		ISNULL(CM.Id,0)AS ClassId,
		ISNULL(CM.Title,'') AS ClassName,
		ISNULL(FS.AdmissionCategoryId,0) AS AdmissionCategoryId,
		ISNULL(FS.BatchId,0)AS BatchId,
		ISNULL(FS.IsOptional,0)AS IsOptional,
		ISNULL(FS.IsVariable,0)AS IsVariable,
		ISNULL(FS.Amount,0)AS Amount,
		ISNULL(FS.StartDate,'0001-01-01 00:00:00.00')AS StartDate,
		ISNULL(FS.EndDate,'0001-01-01 00:00:00.00')AS EndDate,
		ISNULL(FS.ReceiptBookId,0) AS ReceiptBookId,
		CASE WHEN (SELECT COUNT(*) FROM sFee.tReceiptDetail WHERE FeeSetupId=FS.Id) <= 0 THEN 'True' ELSE 'False' END AS IsReceiptBookChange,
		ISNULL(FS.IsServiceTax,0)AS IsServiceTax,
		ISNULL(FS.CollectionGroupId,0) AS CollectionGroupId,
		ISNULL(FS.FeeDuration,'')  AS FeeDuration,
		ISNULL(FS.LevelAmount,0) AS LevelAmount,
		ISNULL(FS.LateFeeRuleId, 0) AS LateFeeRuleId
  FROM 
		sSetup.tClassMaster CM
		INNER JOIN sSetup.tBatchClass BC ON BC.ClassId = CM.Id AND BC.BatchId = @rBatchId
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = CM.OrgId
		LEFT JOIN sFee.tFeeSetup FS ON CM.Id=FS.ClassId 
		AND (FS.FeeId=@rFeeId OR @rFeeId= 0) 
		AND (FS.AdmissionCategoryId=@rAdmissionCategoryId OR @rAdmissionCategoryId= 0) 
		AND (FS.BatchId=@rBatchId)
		LEFT JOIN sFee.tReceiptBookMaster RBM ON RBM.Id=FS.ReceiptBookId
WHERE 
		OM.OrgGroupId=@rOrgGroupId
		ORDER BY FS.StartDate,CM.OrderIndex
END
GO
PRINT N'Altering [sFee].[pFeeSetupGet]...';


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


GO


ALTER PROCEDURE [sFee].[pRptFeeFolioGet]
		
		@rBuilder1 nvarchar(max)='',
		@rBuilder2 nvarchar(max)='',
		@rReportId int=0,
		@rIsFilter bit=0,
	    @rIsDisplayOrgGroup bit=0,
	    @rIsFeeInvoiceHeadwise bit=0,
		@rOrgGroupBatchId int=0,
		@rCommonBatch nvarchar(100)='',
		@rReceiptBookId int=0,
		@rOrgId int=0,
		@rBatchId int=0,
		@rDepartmentId int=0,
		@rAdmissionCategoryId int=0,
		@rClassId int=0,
		@rDivisionId int=0,
		@rStatusId int=0,
		@rFromRollNo int=0,
	    @rToRollNo int=0,
	    @rCode nvarchar(20)='',
	    @rCollectionGroupId int=0,
	    @rFeeHeadId nvarchar(max) = '',
	    @rFirstName nvarchar(100)='',
	    @rFromInvoiceNumber int=0,
		@rToInvoiceNumber int=0,
		@rCreatedUserName nvarchar(100)='',
		@rFeeInvoiceIds nvarchar(max)='',
		@rFilterId int=0,
		@rOrgIds nvarchar(max) = '' , 
		@rParentContactNo nvarchar(20) = '',
		@rClassStatusId int=0
	    
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			
	BEGIN
			SET @rFirstName = sCommon.fSearchStringGet(@rFirstName)
			SET @rCreatedUserName = sCommon.fSearchStringGet(@rCreatedUserName)
	END		
			 
BEGIN

SELECT 
		@rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,
		@rIsFilter AS IsFilter,
		@rIsDisplayOrgGroup AS IsDisplayOrgGroup,
		@rIsFeeInvoiceHeadwise AS IsFeeInvoiceHeadwise,
		SA.AcademicId,
		SA.Name,
		SA.ClassId,
		SA.ClassName,
		SA.DivisionId,
		SA.DivisionName,
		SA.DivisionOrder,
		SA.RollNo,
		SA.Code,
		SA.DepartmentId,
		SA.DepartmentName,
		FM.Id AS FeeId,
		FM.Title AS FeeName,
		FM.OrderIndex AS FeeOrderIndex,
		FHM.Id AS FeeHeadId,
		FHM.Title AS FeeHeadName,
		FHM.OrderIndex AS FeeHeadOrderIndex,
		RBM.Id AS ReceiptBookId,
		RBM.Title AS ReceiptBookName,
		RBM.BankName,
		RBM.BankAccountNumber,
		RBM.OrderIndex AS ReceiptBookOrderIndex,
		FID.Amount AS FeeAmount,
		CGM.Id AS CollectionGroupId,
		CGM.Title AS CollectionGroupName,
		CGM.OrderIndex AS CollectionGroupOrderIndex,
		CGM.FooterRemark1 AS FooterRemark1,
		CGM.FooterRemark2 AS FooterRemark2,
		CGM.FeePeriod AS FeePeriod,
		SA.BatchName,
		CGM.StartDate,
		CGM.EndDate,
		CGM.Remark,
		RBM.FullTitle,
		RBM.Address1,
		RBM.Address2,
		--(CASE WHEN ROW_NUMBER() OVER (PARTITION BY OM.Id ORDER BY OM.Id) = 1 THEN OM.OrgLogo ELSE NULL END) AS OrgLogo,
		OM.OrgLogo,
		SC.ParentContactNo,
		ISNULL(RBM.IsOnPrePrinted,0) AS IsOnPrePrinted,
		ISNULL(RBM.IsSupressLogo,0) AS IsSupressLogo,
		OGM.Title AS OrgGroupName,
		sFinanceCommon.fDefaultCurrencyTitleGet(OM.OrgGroupId) AS CurrencyTitle,
		ISNULL(SO.GenderId,0) AS GenderId,
		sFinanceCommon.fDefaultCurrencyCodeGet(OM.OrgGroupId) AS CurrencyCode,
		FI.InvoiceNumber,
 
		CASE WHEN FAL.DiscountAmount=0 THEN  null
		 ELSE FAL.DiscountAmount END AS ExemptionAmount,
		 RBM.GroupTitle,
		 SA.Suid,
		ISnull(CGM.IsDisplayCashDetailInFolio,0) AS IsDisplayCashDetailInFolio,
       ISnull(CGM.IsOnPrePrinted,0) AS IsOnPrePrintedHeader,
		
       
       CASE
				 WHEN RBM.IsOnPrePrinted=1       
				 THEN 2
				 ELSE  ISNULL(RBM.FeeInvoiceHeaderDisplayId,1)
				END AS FeeInvoiceHeaderDisplayId,
       RBM.FeeInvoiceHeader,
       isnull(rt.pickuppoint,'') as Pickuppoint,
        isnull(rt.Droppoint,'') as Droppoint,
        SA.MiddleName AS FatherName,
		ISNULL(SF.FatherName,'') AS FatherNameFamily,
		ISNULL(SF.MotherName,'') AS MotherName,
		FI.InvoiceDate  ,
		ISNULL(SA.LastName,'') As LastName    
  FROM 
		sFee.tFeeInvoiceDetail FID 
		INNER JOIN sFee.tFeeInvoice FI ON FI.Id = FID.FeeInvoiceId
		INNER JOIN sFee.tFeeSetup FS ON FS.Id = FID.FeeSetupId		
		INNER JOIN sStudent.vStudentAcademic SA ON FI.SourceTypeId = 2001 AND FI.SourceId = SA.AcademicId AND FI.BatchId=SA.BatchId AND FI.OrgGroupBatchId = SA.OrgGroupBatchId
		INNER JOIN sFee.tFeeMaster FM ON FM.Id = FS.FeeId
		INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id = FM.FeeHeadId
		INNER JOIN sFee.tReceiptBookMaster RBM ON RBM.Id = FS.ReceiptBookId
		INNER JOIN sSetup.tOrgGroupMaster OGM ON OGM.Id = RBM.OrgGroupId
		LEFT JOIN sFee.tCollectionGroupMaster CGM ON CGM.Id = FS.CollectionGroupId AND SA.OrgGroupBatchId = CGM.OrgGroupBatchId
		LEFT JOIN sSetup.tOrganizationMaster OM ON OM.Id=SA.OrgId
		LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId = SA.StudentId
		LEFT JOIN sSecurity.tUser U ON U.Id=FI.CreatedUserId
		LEFT JOIN sFee.tFeeAllocation FAL  ON FAL.FeeSetupId  = FS.Id AND FAL.SourceId = FI.SourceId 
		 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,BM.Title as pickuppoint,BM1.Title as droppoint 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))
    Left JOIN sTransport.tBusRouteDestinationMaster BM1 ON BM1.Id=AT.DropDestinationId
    LEFT JOIN sTransport.tBusRouteMaster B1 ON B1.Id=BM1.BusRouteId AND  AT.SourceTypeId=2003 AND ((B1.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))
    ) RT
    ON RT.SourceId = SA.StudentId AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) 
	Left JOIN sStudent.tStudentCommunication SC  ON SC.StudentId = SA.StudentId
	LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId = SA.StudentId
WHERE 
		(SA.OrgGroupBatchId = @rOrgGroupBatchId)
		AND ((SA.OrgId=@rOrgId) OR (@rOrgId=0))	
		AND ((SA.BatchId=@rBatchId) OR (@rBatchId=0))	
		AND	((SA.AdmissionCategoryId = @rAdmissionCategoryId) OR (@rAdmissionCategoryId = 0))
		AND ((SA.ClassId = @rClassId) OR (@rClassId = 0))
		AND ((SA.DivisionId = @rDivisionId) OR (@rDivisionId = 0))	
		AND ((SA.StatusId=@rStatusId) OR (@rStatusId=0))
		AND ((SA.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
		AND ((SA.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
		AND ((SA.RollNo <= @rToRollNo) OR (@rToRollNo=0))
		AND ((SA.Code=@rCode) OR (@rCode=''))
		AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
		AND	((FS.ReceiptBookId = @rReceiptBookId) OR (@rReceiptBookId = 0))
		AND	((FS.CollectionGroupId = @rCollectionGroupId) OR (@rCollectionGroupId = 0))
		AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
		AND ((SA.FirstName like @rFirstName) OR(ISNULL(@rFirstName,'')=''))
		AND ((FI.InvoiceNumber>=@rFromInvoiceNumber)OR(@rFromInvoiceNumber=0))
		AND ((FI.InvoiceNumber<=@rToInvoiceNumber)OR(@rToInvoiceNumber=0))
		AND ((ISNULL(U.LoginTitle,'') like @rCreatedUserName) OR (ISNULL(@rCreatedUserName,'')=''))
		AND (ISNULL(FI.Id,0) IN( SELECT cast(item as bigint) FROM  sCommon.fnsplit(@rFeeInvoiceIds,','))OR @rFeeInvoiceIds='')
		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 ((SC.ParentContactNo= @rParentContactNo) OR (ISNULL(@rParentContactNo,'')=''))
		AND ((SA.ClassStatusId=@rClassStatusId) OR (@rClassStatusId=0))

END
GO
PRINT N'Altering [sFrontOffice].[pStudentGatePassAdd]...';


GO

ALTER PROCEDURE [sFrontOffice].[pStudentGatePassAdd]
	
	@rOrgId int, 
	@rId int,
	@rAcademicId bigint,
	@rRelationshipId tinyint,
	@rRelation nvarchar(50),
	@rVisitorName nvarchar(100),
	@rVisitorMobile nvarchar(50),
	@rReasonOfGatePass nvarchar(200),
	@rVisitorPhoto varbinary(max),
	@rGatePassDate date,
	@rReturnGatePassDate date,
	@rGatePassTime datetime,
	@rReturnGatePassTime datetime,
	@rEntryModeStatusId smallint,
	@rCreatedUserId bigint,
	@rRemark nvarchar(200)='',
	@rGatePassNo bigint = 0
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	BEGIN TRANSACTION	
IF(@rId = 0)	
BEGIN
	DECLARE @lNextNumber INT     
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sFrontOffice.tStudentGatePass', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	INSERT INTO sFrontOffice.tStudentGatePass
		(
			OrgId,
			Id,
			AcademicId,
			RelationshipId,
			Relation,
			VisitorName,
			VisitorMobile,
			ReasonOfGatePass,
			VisitorPhoto,
			GatePassDate,
			ReturnGatePassDate,
			GatePassTime,
			ReturnGatePassTime,
			EntryModeStatusId,
			CreatedUserId,
			CreatedDateTime,
			Remark,
			GatePassNo
		)
	VALUES
		(
			@rOrgId,
			@lNextNumber,
			@rAcademicId,
			@rRelationshipId,
			@rRelation,
			@rVisitorName,
			@rVisitorMobile,
			@rReasonOfGatePass,
			@rVisitorPhoto,
			@rGatePassDate,
			Null,
			@rGatePassTime,
			Null,
			@rEntryModeStatusId,
			@rCreatedUserId,
			sCommon.fGetDate()	,
			@rRemark,
			@rGatePassNo
		)
		             
END	 
	 ELSE
BEGIN
	SET @lNextNumber = @rId
	UPDATE  sFrontOffice.tStudentGatePass
	SET
		RelationshipId=@rRelationshipId,
		Relation=@rRelation,
		VisitorName=@rVisitorName,
		VisitorMobile=@rVisitorMobile,
		ReasonOfGatePass=@rReasonOfGatePass,
		VisitorPhoto=@rVisitorPhoto,
		GatePassDate=@rGatePassDate,
		ReturnGatePassDate=@rReturnGatePassDate,
		GatePassTime=@rGatePassTime,
		ReturnGatePassTime=@rReturnGatePassTime,
		EntryModeStatusId=@rEntryModeStatusId,
		Remark=@rRemark

	WHERE Id = @rId 	   
END  
	
	SELECT @lNextNumber AS Result
	
	COMMIT TRANSACTION
	
	END TRY
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
END
GO
PRINT N'Altering [sHostel].[pAttendanceRegisterGet]...';


GO
ALTER PROCEDURE [sHostel].[pAttendanceRegisterGet]
	 	 
	 	 @rRoomId int,
		 @rAttendanceDate date,
		 @rHostelId int,
		 @rHostelAttendanceTypeId int,
		 @rOrgGroupBatchId int,
		 @rBuildingId int = 0

	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	IF EXISTS(SELECT 1 FROM sHostel.tAttendanceRegister ATR INNER JOIN sHostel.tAssignRoom AR ON AR.SourceId = ATR.StudentId AND AR.SourceTypeId=2003
	            INNER JOIN sHostel.tRoomMaster RM ON RM.Id = AR.RoomId
				WHERE ATR.AttendanceDate=@rAttendanceDate AND ATR.OrgGroupBatchId=@rOrgGroupBatchId AND ATR.HostelAttendanceTypeId=@rHostelAttendanceTypeId
				 AND AR.RoomId = @rRoomId AND RM.BuildingId = @rBuildingId )
	BEGIN
		SELECT 
			AR.SourceId AS StudentId,
			VA.Code,
			VA.Name,
			VA.SUId,
			ISNULL(ATR.IsPresent,'true') as IsPresent,
			ISNULL(ATR.AbsentReasonId,0) as AbsentReasonId,
			CASE WHEN ATR.CreatedUserId IS NULL THEN 'false' ELSE 'true' END AS IsDeleted,
			(SI.StudentPhoto) AS StudentPhoto,
			ISNULL(ATR.HostelAttendanceTypeId,0) AS HostelAttendanceTypeId
			
  FROM 
           sStudent.vStudentAcademic VA 
            INNER JOIN sHostel.tAssignRoom AR ON VA.StudentId = AR.SourceId AND AR.SourceTypeId=2003
            LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId=VA.StudentId
            INNER JOIN sHostel.tRoomMaster RM ON RM.Id = AR.RoomId
            INNER JOIN sHostel.tAttendanceRegister ATR ON ATR.StudentId=VA.StudentId 			
			AND (ATR.AttendanceDate=@rAttendanceDate) AND (ATR.OrgGroupBatchId=@rOrgGroupBatchId)
			AND isnull(ATR.HostelAttendanceTypeId,0)=@rHostelAttendanceTypeId
			LEFT JOIN sHostel.tHostelAdmission HA ON HA.SourceId =  AR.SourceId  AND HA.SourceTypeId=2003
								  
  WHERE 
      RM.HostelId = @rHostelId
	  AND ((AR.RoomId=@rRoomId) OR (@rRoomId=0))
	   AND VA.OrgGroupBatchId=@rOrgGroupBatchId
	   AND AR.OrgGroupBatchId=@rOrgGroupBatchId
	   AND ((RM.BuildingId = @rBuildingId) OR (@rBuildingId=0))
	   AND (HA.AllocateDate <= @rAttendanceDate)
  ORDER BY VA.Code
	END
	ELSE
		BEGIN
		SELECT 
				AR.SourceId AS StudentId,
				VA.Code,
				VA.Name,
				VA.SUId,
				ISNULL(ATR.IsPresent,'true') as IsPresent,
				ISNULL(ATR.AbsentReasonId,0) as AbsentReasonId,
				CASE WHEN ATR.CreatedUserId IS NULL THEN 'false' ELSE 'true' END AS IsDeleted,
				(SI.StudentPhoto) AS StudentPhoto,
				ISNULL(ATR.HostelAttendanceTypeId,0) AS HostelAttendanceTypeId
			
	  FROM 
			   sStudent.vStudentAcademic VA 
				INNER JOIN sHostel.tAssignRoom AR ON VA.StudentId = AR.SourceId AND AR.SourceTypeId=2003
				LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId=VA.StudentId
				INNER JOIN sHostel.tRoomMaster RM ON RM.Id = AR.RoomId
				LEFT JOIN sHostel.tAttendanceRegister ATR ON ATR.StudentId=VA.StudentId 			
				AND (ATR.AttendanceDate=@rAttendanceDate) AND (ATR.OrgGroupBatchId=@rOrgGroupBatchId)
				AND isnull(ATR.HostelAttendanceTypeId,0)=@rHostelAttendanceTypeId			
				LEFT JOIN sHostel.tHostelAdmission HA ON HA.SourceId =  AR.SourceId  AND HA.SourceTypeId=2003
		  
	  WHERE 
		  RM.HostelId = @rHostelId
		  AND ((AR.RoomId=@rRoomId) OR (@rRoomId=0))
		   AND VA.OrgGroupBatchId=@rOrgGroupBatchId
		   AND AR.OrgGroupBatchId=@rOrgGroupBatchId
		   AND ((RM.BuildingId = @rBuildingId) OR (@rBuildingId=0))
		   AND (HA.AllocateDate <= @rAttendanceDate)
	  ORDER BY VA.Code
	  END

	 --Select * from sHostel.tAttendanceRegister where Hostelattendancetypeid = 991100003 AND Attendancedate = '2022-12-28 00:00:00'
GO
PRINT N'Altering [sHrm].[pEmployeeAllBAtchDocumentSubmitGet]...';


GO

ALTER PROCEDURE [sHrm].[pEmployeeAllBAtchDocumentSubmitGet]
	 
        @rEmployeeId bigint,
		@rOrgId int
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
 
	BEGIN
			SELECT Isnull(D.Id,0) AS DocumentId,ISNULL(D.DocumentName,'') AS DocumentName,
			CASE WHEN   UD.DocumentId is null THEN 'False' ELSE 'True'END AS IsCheck
			, ISNULL(UD.DocumentName,'')  As FileName,
			isnull(Ud.OrgGroupBatchId,0) AS OrgGroupBatchId,ISNULL(S.IsMigrate,0) as IsMigrate
		 	FROM sCommon.tSubmitDocumentMaster D
			LEFT Join [sHrm].[tEmployeeDocument]  S ON S.SubmitDocumentMasterId=D.id AND S.EmployeeId=@rEmployeeId
			Left Join [sCommon].[tUploadDocument] UD On UD.DocumentId=D.id AND UserSourceTypeId=95 AND UserSourceId=@rEmployeeId AND ( UD.UploadFunctionalityId=13)
			WHERE OrgId=@rOrgId AND SubmitDocumentFunctionalityId='2'
END
GO
PRINT N'Altering [sHrm].[pEmployeeTravelAdd]...';


GO
ALTER PROCEDURE [sHrm].[pEmployeeTravelAdd]
        @rOrgId int,
        @rId bigint,
        @rEmployeeId bigint,
        @rReportDate date,
        @rTravelFromDate date,
        @rTravelToDate date,
        @rTravelPeriodId tinyint,       
        @rTravelReason nvarchar(200),
        @rTravelRemark nvarchar(200),
        @rNoOfDays decimal(5,2),
        @rFromTime datetime=null,
		@rToTime datetime=null,
        @rBatchId int,
       
        @rCreatedUserId bigint,
        @rStatusId int,
		@rStatusReason nvarchar(100) = ''
       
AS
SET NOCOUNT ON

BEGIN


      DECLARE @1Days int
	BEGIN TRY
	
	BEGIN TRANSACTION

	DECLARE @lNextNumber bigint
	 
    IF (@rId = 0)
     BEGIN
       
       IF(@rTravelPeriodId = 2) --For Half Leave	  	
       SELECT @1Days = SUM(NoOfDays) from sHrm.tEmployeeTravel where EmployeeId = @rEmployeeId AND OrgId = @rOrgId AND TravelFromDate = @rTravelFromDate
       ELSE
         SET @1Days = 1
     		
	   IF NOT EXISTS(SELECT 1 FROM sHrm.tEmployeeTravel WHERE EmployeeId = @rEmployeeId 
	   AND(( TravelFromDate  BETWEEN @rTravelFromDate AND @rTravelToDate) OR (TravelToDate BETWEEN @rTravelFromDate AND @rTravelToDate)
	   OR (@rTravelFromDate  BETWEEN TravelFromDate AND TravelToDate) OR (@rTravelToDate BETWEEN TravelFromDate AND TravelToDate)) AND OrgId = @rOrgId AND BatchId = @rBatchId AND StatusId!=643)OR @1Days != 1 
	   BEGIN
	    EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sHrm.tEmployeeTravel', 0, 1, 1,@outNextNumber = @lNextNumber output	
	    
		  INSERT INTO sHrm.tEmployeeTravel
           (
            [Id]
           ,[EmployeeId]
           ,[ReportDate]
           ,TravelFromDate
           ,TravelToDate
           ,TravelPeriodId       
           ,TravelReason
           ,TravelRemark
           ,NoOfDays
            ,[FromTime]
           ,[ToTime]
           ,[OrgId] 
            ,[CreatedUserId]
           ,[CreatedDateTime]
           ,[UpdatedUserId]
           ,[UpdatedDateTime] 
           ,BatchId                              
           ,[StatusId]
		   ,StatusReason
           )
     VALUES
           (
            @lNextNumber
           ,@rEmployeeId 
           ,@rReportDate 
           ,@rTravelFromDate
           ,@rTravelToDate 
           ,@rTravelPeriodId          
           ,@rTravelReason 
           ,@rTravelRemark
           ,@rNoOfDays
           ,@rFromTime
           ,@rToTime  
           ,@rOrgId 
           ,@rCreatedUserId 
           ,sCommon.fGetDate()
           ,@rCreatedUserId 
           ,sCommon.fGetDate()
           ,@rBatchId                      
           ,@rStatusId       
           ,@rStatusReason
           )
            SELECT 1 AS Result
            END
          ELSE
            SET @lNextNumber = -101            
          END
	ELSE
	BEGIN
	SET @lNextNumber = @rId
		UPDATE sHrm.tEmployeeTravel
		SET 	 
		   [EmployeeId]= @rEmployeeId 
		  ,[ReportDate]= @rReportDate 
		  ,[TravelFromDate]= @rTravelFromDate
		  ,TravelToDate= @rTravelToDate
		  ,[TravelPeriodId]= @rTravelPeriodId
		 
		  ,TravelReason= @rTravelReason
		  ,TravelRemark=@rTravelRemark
		  ,NoOfDays = @rNoOfDays
		  ,[OrgId]= @rOrgId        
		  ,[UpdatedUserId]= @rCreatedUserId
		  ,[UpdatedDateTime]= sCommon.fGetDate()
		  ,[FromTime] = @rFromTime
          ,[ToTime] = @rToTime
		  ,StatusReason = @rStatusReason    
		WHERE Id = @rId
		 SELECT 11 AS Result
	 END 
	   SELECT @lNextNumber AS Result	   
	   COMMIT TRANSACTION
	   		
	END TRY	
	BEGIN CATCH
		ROLLBACK TRANSACTION
		SELECT -1 AS RESULT
	END CATCH
END
GO
PRINT N'Altering [sHrm].[pGetDropDowns]...';


GO

 

ALTER proc [sHrm].[pGetDropDowns]
@rOrgId int,
@rUserId bigint,
@rOrgGroupId int = 1101,
@rPayrollYearId int = null
as
begin
	declare @lStatusRes varchar(max)='',@lColumnRes varchar(max)='',@lReportList varchar(max)=''
	declare @lOrganizationRes nvarchar(max) = '',@lPayRollYear varchar(max) = '',@lPayrollColumn varchar(max) = ''
	declare @lPayrollReportList varchar(max) = '', @lSavedReport nvarchar(max)='', @lSavedReport1 nvarchar(max)=''
	declare @lCustomtagdrop nvarchar(max)=''
	
	select @lOrganizationRes = @lOrganizationRes + '<option value="0"> -- ALL -- </option>'
	select @lOrganizationRes = @lOrganizationRes + '<option ' + case when Id = @rOrgId then 'selected="selected"' else '' end + ' value="' + convert(varchar,Id) + '">' + DisplayTitle + '</option>'
	from sSetup.vUserOrganization where IsObsolete = 0 AND OrgGroupId = isnull(@rOrgGroupId,0) and UserId = @rUserId
	order by OrderIndex
	
	select @lPayRollYear = @lPayRollYear + '<option value="0"> -- Select -- </option>'
	select top 1 @lPayRollYear = @lPayRollYear + '<option value="' + convert(varchar,YearNumber) + '">' + convert(varchar,YearNumber) + '</option>'
	from sPayroll.fMonthYearForPayrollGet(@rPayrollYearId)
	
	select @lStatusRes = @lStatusRes + '<option value="0"> -- ALL -- </option>'
	select @lStatusRes = @lStatusRes + '<option value="7">Active</option>'
	select @lStatusRes = @lStatusRes + '<option value="9">Left</option>'
	select @lStatusRes = @lStatusRes + '<option value="8">Suspended</option>'
	select @lStatusRes = @lStatusRes + '<option value="10">Unknown</option>'
	select @lStatusRes = @lStatusRes + '<option value="738">Retired</option>'
	
	select @lColumnRes = @lColumnRes + '<option value="' + COLUMN_NAME + '">' + COLUMN_NAME + '</option>'
	from INFORMATION_SCHEMA.COLUMNS where TABLE_SCHEMA='sHrm' AND TABLE_NAME='vEmployeeColumnName'
	
	select @lPayrollColumn = @lPayrollColumn + '<option value="' + COLUMN_NAME + '">' + COLUMN_NAME + '</option>'
	from INFORMATION_SCHEMA.COLUMNS where TABLE_SCHEMA='sPayroll' AND TABLE_NAME='vPayrollColumnName'
	
	select @lReportList = @lReportList + '<tr><td style="width:100px; word-wrap:break-word;">' + SCS.Title + '</td>
	<td style="width:700px; word-wrap:break-word;">' + SCS.ColumnName + '</td>
	<td style="width:50px; word-wrap:break-word;"><a onclick="ViewReport(' + convert(varchar(20),SCS.Id) + ',''' + convert(varchar(20),SCS.Title) + ''',''' + convert(varchar(max),SCS.ColumnName) +''');">View</a></td>
	<td style="width:100px; word-wrap:break-word;">' + U.DisplayTitle + '</td>	
	<td style="width:50px; word-wrap:break-word;"><a onclick="DeleteReport(' + convert(varchar,SCS.Id) + ');"><img src="/Images/Del.png"></i></a></td></tr>'
	from sHrm.tEmployeeCustomSearch SCS
	LEFT JOIN sSetup.tOrganizationMaster OM ON OM.Id = SCS.OrgId AND OM.OrgGroupId = @rOrgGroupId
	LEFT JOIN sSecurity.tUser U ON U.Id=SCS.CreatedUserId
	WHERE (SCS.CreatedUserId = @rUserId OR SCS.IsCommon = 1  OR SCS.IsCommonForOrg = 1)
	
	select @lPayrollReportList = @lPayrollReportList + '<tr><td style="width:100px; word-wrap:break-word;">' + SCS.Title + '</td>
	<td style="width:700px; word-wrap:break-word;">' + SCS.ColumnName + '</td>
	<td style="width:50px; word-wrap:break-word;"></td>
	<td style="width:100px; word-wrap:break-word;">' + U.DisplayTitle + '</td>	
	<td style="width:50px; word-wrap:break-word;"><a onclick="DeleteReport(' + convert(varchar,SCS.Id) + ');"><img src="/Images/Del.png"></i></a></td></tr>'
	from sPayroll.tPayrollCustomSearch SCS
	INNER JOIN sSecurity.tUser U ON U.Id=SCS.CreatedUserId
	WHERE (SCS.CreatedUserId = @rUserId OR SCS.IsCommon = 1)
	AND SCS.OrgId = @rOrgId
	
	select @lSavedReport = @lSavedReport + '<option value="0"> -- Select -- </option>'
	select @lSavedReport =  @lSavedReport + '<option value="' + convert(varchar,ECS.Id)+ '">' + ECS.Title + '</option>'
	from sHrm.tEmployeeCustomSearch  ECS
	LEFT JOIN sSetup.tOrganizationMaster OM ON OM.Id = ECS.OrgId AND OM.OrgGroupId = @rOrgGroupId
	WHERE (ECS.CreatedUserId = @rUserId OR ECS.IsCommon = 1 OR ECS.IsCommonForOrg = 1)

	select @lSavedReport1 = @lSavedReport1 + '<option value="0"> -- Select -- </option>'
	select @lSavedReport1 =  @lSavedReport1 + '<option value="' + convert(varchar,PCS.Id)+ '">' + PCS.Title + '</option>'
	from sPayroll.tPayrollCustomSearch  PCS
	LEFT JOIN sSetup.tOrganizationMaster OM ON OM.Id = PCS.OrgId AND OM.OrgGroupId = @rOrgGroupId
	WHERE (PCS.CreatedUserId = @rUserId OR PCS.IsCommon = 1 OR PCS.IsCommonForOrg = 1)
	

	select @lCustomtagdrop  = @lCustomtagdrop  + '<option value="' +convert(varchar,Id)+ '">' + Title + '</option>'
	from sHrm.tCustomTagMaster where IsObsolete =0  and OrgGroupId = @rOrgGroupId

	DECLARE @lAvailableEmployeeColumns nvarchar(max)=''
	 DECLARE @lAvailableEmployeeCustomRes nvarchar(max)=''
	 Declare @Title as nvarchar(max)


	   SET @lAvailableEmployeeColumns=   STUFF((SELECT ',' + QUOTENAME(PP.FieldTitle,'[]'), '' AS FieldTitle, '' AS SalaryMonth
						from sHrm.tEmployeeCustomFieldMaster PP WHERE PP.IsObsolete=0 AND PP.OrgGroupId =@rOrgGroupId
				FOR XML PATH(''), TYPE
				).value('.', 'NVARCHAR(MAX)') 
			,1,1,'')
	        
		DECLARE @lEmployeeCustomFields TABLE
		(
		  Title nvarchar(max)
		)
		 INSERT INTO  @lEmployeeCustomFields      
		select Item AS Title from sCommon.fnSplit(@lAvailableEmployeeColumns , ',')

	        
		select @lAvailableEmployeeCustomRes = @lAvailableEmployeeCustomRes +'<option class=EmployeeCustom value="|' + Title + '||">|' + Title + '||</option>'
		from @lEmployeeCustomFields

		
	
	select @lStatusRes as StatusRes,@lColumnRes as AvailableRes,@lReportList as ReportList,
	@lOrganizationRes as OrganizationRes,@lPayRollYear as PayRollYear,@lPayrollColumn as PayrollColumn,
	@lPayrollReportList as PayrollReportList, @lSavedReport AS SavedReportList,@lCustomtagdrop AS customtaghklist,@lAvailableEmployeeCustomRes as AvailableEmployeeCustomRes
	
end
GO
PRINT N'Altering [sHrm].[pLeaveHierarchyLevelUpdate]...';


GO


ALTER PROCEDURE [sHrm].[pLeaveHierarchyLevelUpdate]
        @rLeaveHierarchyLevelId bigint,   
		@rStatusId int,
		@rHierarchyLevelCount int,
        @rLeaveId bigint,
        @rRemark nvarchar(500),
        @rEmployeeId bigint,
		@rOrgId int
       
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
	
	BEGIN TRANSACTION

	BEGIN
	DECLARE @lActionByEmployeeId bigint
	SELECT @lActionByEmployeeId = EmployeeManagerId from [sHrm].[tEmployeeJobDetail] WHere EmployeeId = @rEmployeeId 
	--AND OrgId = @rOrgId

	UPDATE [sHrm].[tLeaveHierarchyLevel] SET StatusId = @rStatusId , Remark = @rRemark WHERE AutoId = @rLeaveHierarchyLevelId

	DECLARE @lLeaveCount int
	SELECT @lLeaveCount = COUNT(AutoId) FROM [sHrm].[tLeaveHierarchyLevel] WHERE LeaveId = @rLeaveId

	IF(@rStatusId = 550)
	BEGIN
		IF(@rHierarchyLevelCount <> @lLeaveCount)
		BEGIN
			 --IF (@rStatusId = 550)
			 --BEGIN
				INSERT INTO [sHrm].[tLeaveHierarchyLevel]
					   (LeaveId
					   ,StatusId
					   ,Remark
					   ,ActionByEmployeeId
					   ,ActionDatetime)
				 VALUES
					   (@rLeaveId
					   ,549
					   ,''
					   ,@lActionByEmployeeId
					   ,sCommon.fGetDate())

						SELECT 0 AS Result 
			 --END
		END
		ELSE
		BEGIN
			 UPDATE [sHrm].[tLeave] SET StatusId = @rStatusId Where Id = @rLeaveId
			 
			 SELECT @rStatusId AS Result 
			
		END
	END
	ELSE
	BEGIN
		UPDATE [sHrm].[tLeave] SET StatusId = @rStatusId Where Id = @rLeaveId
			--IF(@rHierarchyLevelCount = @lLeaveCount)
			--BEGIN
				DELETE FROM [sHrm].[tLeaveHierarchyLevel] Where LeaveId = @rLeaveId AND ActionByEmployeeId = @lActionByEmployeeId
			--END
		SELECT @rStatusId AS Result 
	END
	
	END 	   
	COMMIT TRANSACTION
	END TRY	
	BEGIN CATCH
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH
END
GO
PRINT N'Altering [sPayroll].[pRptEmployeeSalaryDetail]...';


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

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

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


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

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


GO
ALTER PROCEDURE [sSecurity].[pAppPermissionGet]
	@rOrgGroupId [int],
	@rUserId [bigint]
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
IF EXISTS (SELECT 1 FROM sSecurity.tPermissionUser WHERE UserId=@rUserId AND OrgGroupId=@rOrgGroupId)

	BEGIN
	
		SELECT		
			TP.TaskId AS TaskID,
			CAST(MAX(TP.C) AS BIT) AS [Create],
			CAST(MAX(TP.R) AS BIT) AS [Read],
			CAST(MAX(TP.U) AS BIT) AS [Update],
			CAST(MAX(TP.D) AS BIT) AS [Delete],
			CAST(MAX(TP.S) AS BIT) AS [Search],
			CAST(MAX(TP.P) AS BIT) AS [Print],
			CAST(MAX(TP.X) AS BIT) AS [Execute]
		FROM
		(
			SELECT 	
				P.TaskId					AS	TaskID,
				(Permission & 1) 		AS	C, --[Create],
				(Permission & 2)/2		AS	R, --[Read],
				(Permission & 4)/4		AS	U, --[Update],
				(Permission & 8)/8		AS	D, --[Delete],
				(Permission & 16)/16 	AS	S, --[Search],
				(Permission & 32)/32 	AS	P, --[Print],
				(Permission & 64)/64 	AS	X --[Execute]
			FROM sSecurity.tPermissionUser P
			INNER JOIN sSecurity.tOrganizationTask T ON P.TaskId = T.TaskId And T.OrgGroupId = @rOrgGroupId
			INNER JOIN sSecurity.tTask T1 ON T1.Id=P.TaskId 
			INNER JOIN sSecurity.tModulePermission MP ON MP.ModuleId=T1.ModuleId AND MP.OrgGroupId=@rOrgGroupId
			WHERE
			P.OrgGroupId = @rOrgGroupId 
			AND T1.Id in(
			20075, -- Student Register
			20086, -- Circular
			20094, -- Assignment
			20107, -- Query Queue
			20126, -- Behaviour Entry
			20171, -- Assign Task
			20184, -- Add Photo
			20538, -- Leave Listing
			20561, -- Classwork
			20983, -- My Leave
			30032, -- Subjectwise Attendance
			30502, -- Consolidate - Receipt Details
			30501, -- Consolidate - Fee Status
			30505, -- Consolidate - Student Attendance
			30504, -- Consolidate - Assessment
			30508, -- Consolidate - Task - Attendance
			30507, -- Consolidate - Admission form
			30506, -- Consolidate - Staff
			30536, -- My Expense
			30546, -- Student Alert
			30547, -- Employee Alert
			30550, -- Student Birthdays
			30551, -- Employee Birthdays
			30560, -- Lead Master Admin Permission
			30572, -- Add Lead Permission
			30573, -- Consolidate - Admission Inquiry 
			20089, -- New Query
			30607, -- Consolidate - Task - CW/HW
			30621, -- Consolidate - Fee Collection
			30630, -- Payment Transaction Update
			30621, -- Consolidate - Fee Collection
			20555, -- Lesson Plan
			30635, -- Division Wise -  Photo
			30662, -- Data Search
			30663, -- ClassWork - Home Work Dash Board Search
			30664, -- ClassWork HomeWork Queue
			30678, -- Assignment Queue
			30585, -- Circular Queue
			30687, -- Is Allow SMS Alert
			30688, -- Is Allow Email Alert
			30689, -- Is Allow Notification Alert
			30222, -- Circular Admin
			30540, -- Summarise - Security Dashboard
			30541, -- Summarise - Library Dashboard
			30542, -- Summarise - Transport Dashboard
			30703, -- Summarise - Employee Summary
			30706, -- Summarise - Student Summary
			30766, -- Consolidate Pending Fee
			30768, -- Religionwise Strength Dashboard
			30769, -- Exam Schedule Dashboard 
			20097, -- View Query
			30249, -- Classwork/Homework
			30788, -- Online Learning - Teacher
			30792, -- Online Learning Admin View
			30786, --Online Learning 
			30787, --Online learning Student View
			30815, --Consolidate - Fee Status
			30813, --My Chat - OnlineLearning
			30862,  --Manage Mobile Account
			30900,  -- Close Query
			30927,  -- Classwork Homework Queue Search All
			30930,   -- Consolidate - Admission Inquiry Summary,
			30933,   -- Biometric Punch
			20284,   --Visitor Gate Pass
			30646,   -- Mark Entry From App 
			30944,   -- Circular - Data Search
			30945,   -- Assignment Data Search
			30946,   -- Lesson Data Search
			30947,   -- CW/HW Data Search
			30951,   -- Visitor Log Listing
			30861,   -- Consolidate - Student Subject Attendance
			30505,    -- Consolidate - Student Attendance
			30983,    -- Consolidate - Fee Details Status
			20080,   -- AdmissionInquiry
			30994,   -- AttendanceFollowup
			20556,   -- HostelStudentGatePass
			20934,   -- CS Exam Mark Entry Bulk
			20710,   -- CS Exam Grade Entry Bulk
			20478,   -- CS Exam Indicator Entry Bulk
			20749,   -- Activity Mark Entry Bulk
			20745,   -- Activity Grade Score Bulk
			20746,   -- Activity Indicator Score Bulk
			31007,   -- Is Mark Entry View
			31008,  -- Is CS Entry View
			31009,  -- Is Activity Entry View
			20556,  -- Hostel Student Gate Pass
			31005,	-- My Digital Form
			20183, -- View Photo
			30580, -- Employee Attendance Summary
			20056, -- Event Schedule
			31033, --My Proxy
			20687, --  Employee Attendance
			31043 --  Pending Fee
			,30943 -- My Approval Request
			,30739 -- Behaviour Entry User Wise
			,31048 -- Add Gallery
			,31175 -- View Gallery
			,31179 -- Leave Hierarchy Listing
			,30331 -- My Exam Schedule
			,31182 -- My Admit Card
			,30600 -- MIS Consolidate DashBoard
			,31193 -- Consolidate - Admission Inquiry And Admission Form
			,31194 -- Consolidate - Staff Count
			,31195 -- Consolidate - Charge Receipt
			,31244 -- Lesson Plan Complete
			,20776 -- Front office --Student Gate Pass
			)
		) TP 
		GROUP BY TP.TaskId
	END
ELSE
	BEGIN
	
		SELECT		
			TP.TaskId AS TaskID,
			CAST(MAX(TP.C) AS BIT) AS [Create],
			CAST(MAX(TP.R) AS BIT) AS [Read],
			CAST(MAX(TP.U) AS BIT) AS [Update],
			CAST(MAX(TP.D) AS BIT) AS [Delete],
			CAST(MAX(TP.S) AS BIT) AS [Search],
			CAST(MAX(TP.P) AS BIT) AS [Print],
			CAST(MAX(TP.X) AS BIT) AS [Execute]
		FROM
		(
			SELECT 	
				P.TaskId					AS	TaskID,
				(Permission & 1) 		AS	C, --[Create],
				(Permission & 2)/2		AS	R, --[Read],
				(Permission & 4)/4		AS	U, --[Update],
				(Permission & 8)/8		AS	D, --[Delete],
				(Permission & 16)/16 	AS	S, --[Search],
				(Permission & 32)/32 	AS	P, --[Print],
				(Permission & 64)/64 	AS	X --[Execute]
			FROM sSecurity.tPermission P
			INNER JOIN sSecurity.tOrganizationTask T ON P.TaskId = T.TaskId And T.OrgGroupId = @rOrgGroupId
			INNER JOIN sSecurity.tTask T1 ON T1.Id=P.TaskId 
			INNER JOIN sSecurity.tModulePermission MP ON MP.ModuleId=T1.ModuleId AND MP.OrgGroupId=@rOrgGroupId
			INNER JOIN (SELECT RoleId FROM sSecurity.tUserRole WHERE IsObsolete = 0 AND UserId = @rUserId) R
			ON R.RoleId = P.RoleId 
			WHERE
			P.OrgGroupId = @rOrgGroupId 
			AND T1.Id in(
			20075, -- Student Register
			20086, -- Circular
			20094, -- Assignment
			20107, -- Query Queue
			20126, -- Behaviour Entry
			20171, -- Assign Task
			20184, -- Add Photo
			20538, -- Leave Listing
			20561, -- Classwork
			20983, -- My Leave
			30032, -- Subjectwise Attendance
			30502, -- Consolidate - Receipt Details
			30501, -- Consolidate - Fee Status
			30505, -- Consolidate - Student Attendance
			30504, -- Consolidate - Assessment
			30508, -- Consolidate - Task - Attendance
			30507, -- Consolidate - Admission form
			30506, -- Consolidate - Staff
			30536, -- My Expense
			30546, -- Student Alert
			30547, -- Employee Alert
			30550, -- Student Birthdays
			30551, -- Employee Birthdays
			30560, -- Lead Master Admin Permission
			30572, -- Add Lead Permission
			30573, -- Consolidate - Admission Inquiry 
			20089, -- New Query
			30607, -- Consolidate - Task - CW/HW
			30621, -- Consolidate - Fee Collection
			30630, -- Payment Transaction Update
			30621, -- Consolidate - Fee Collection
			20555, -- Lesson Plan
			30635, -- Division Wise -  Photo
			30662, -- Data Search
			30663, -- ClassWork - Home Work Dash Board Search
			30664, -- ClassWork HomeWork Queue
			30678, -- Assignment Queue
			30585, -- Circular Queue
			30687, -- Is Allow SMS Alert
			30688, -- Is Allow Email Alert
			30689, -- Is Allow Notification Alert
			30222, -- Circular Admin
			30540, -- Summarise - Security Dashboard
			30541, -- Summarise - Library Dashboard
			30542, -- Summarise - Transport Dashboard
			30703, -- Summarise - Employee Summary
			30706, -- Summarise - Student Summary
			30766, -- Consolidate Pending Fee
			30768, -- Religionwise Strength Dashboard
			30769, -- Exam Schedule Dashboard
			20097, -- View Query
			30249,  -- Classwork/Homework
			30788, -- Online Learning - Teacher
			30792, -- Online Learning Admin View
			30786 , --Online Learning 
			30787,  --Online learning Student View
			30815,  --Consolidate - Fee Status
			30813,  --My Chat - OnlineLearning
			30862,  --Manage Mobile Account
			30900,  -- Close Query
			30927,  -- Classwork Homework Queue Search All
			30930,  -- Consolidate - Admission Inquiry Summary
			30933,   -- Biometric Punch
			20284,   --Visitor Gate Pass
			30646,   -- Mark Entry From App
			30944,   -- Circular - Data Search
			30945,   -- Assignment Data Search
			30946,   -- Lesson Data Search
			30947,   -- CW/HW Data Search
			30951,    -- Visitor Log Listing
			30861,   -- Consolidate - Student Subject Attendance
			30505,    -- Consolidate - Student Attendance			
			30983,    -- Consolidate - Fee Details Status
			20080,   -- AdmissionInquiry
			30994,   -- AttendanceFollowup
			20556,    -- HostelStudentGatePass
			20934,   -- CS Exam Mark Entry Bulk
			20710,   -- CS Exam Grade Entry Bulk
			20478,   -- CS Exam Indicator Entry Bulk
			20749,   -- Activity Mark Entry Bulk
			20745,   -- Activity Grade Score Bulk
			20746,   -- Activity Indicator Score Bulk
			31007,   -- Is Mark Entry View
			31008,  -- Is CS Entry View
			31009,   -- Is Activity Entry View
			20556,   -- Hostel Student Gate Pass
			31005,	-- My Digital Form
			20183, -- View Photo
			30580, -- Employee Attendance Summary
			20056, -- Event Schedule
			31033, --My Proxy
			20687, --  Employee Attendance
			31043 --  Pending Fee
			,30943 -- My Approval Request
			,30739 -- Behaviour Entry User Wise
			,31048 -- Add Gallery
			,31175 -- View Gallery
			,31179 -- Leave Hierarchy Listing
			,30331 -- My Exam Schedule
			,31182 -- My Admit Card
			,30600 -- MIS Consolidate DashBoard
			,31193 -- Consolidate - Admission Inquiry And Admission Form
			,31194 -- Consolidate - Staff Count
			,31195 -- Consolidate - Charge Receipt
			,31244 -- Lesson Plan Complete
			,20776 -- Front office --Student Gate Pass
			) 
		) TP 
		GROUP BY TP.TaskId
	END
END
GO
PRINT N'Altering [sSecurity].[pScreenGroupDataListGet]...';


GO
ALTER PROCEDURE [sSecurity].[pScreenGroupDataListGet]

	@rUserId [bigint]

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

DECLARE @lOrgGroupId bigint , @lConfigValue nvarchar(10) = ''

IF EXISTS (SELECT OM.OrgGroupId FROM sSecurity.tUser U INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = U.OrgId WHERE U.Id = @rUserId)
BEGIN
	SELECT @lOrgGroupId = OM.OrgGroupId FROM sSecurity.tUser U INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = U.OrgId WHERE U.Id = @rUserId
		
	SELECT @lConfigValue = ISNULL(CS.ItemValue,'False') FROM sConfig.tConfigurationMaster CM LEFT JOIN sConfig.tConfigurationSetup CS ON CM.Id=CS.Configurationid AND CS.SourceId= @lOrgGroupId AND CS.SourceTypeId=2010 WHERE CM.Id = 327

		IF(@lConfigValue = 'True')
		BEGIN
		     IF EXISTS (SELECT 1 FROM sSecurity.tPermissionUser WHERE UserId=@rUserId AND OrgGroupId=@lOrgGroupId)
				BEGIN
					SELECT S.Id AS Id,LEFT(S.Title,32) AS Title 
					From sSecurity.tScreen S 
					INNER JOIN sSecurity.tPermissionUser P ON P.TaskId=S.TaskId 
					INNER JOIN sSecurity.tTask T ON T.ID = p.TaskId 
					INNER JOIN sSecurity.tOrganizationTask OT ON T.Id = OT.TaskId AND OT.OrgGroupId = P.OrgGroupId 
					INNER JOIN sSecurity.tModulePermission MP ON MP.ModuleId=T.ModuleId AND MP.OrgGroupId=@lOrgGroupId
					WHERE (P.Permission & 2) =2 AND P.OrgGroupId = @lOrgGroupId AND T.IsObsolete = 0 AND P.UserId=@rUserId
					AND T.Id IN (20085,20086,30401,30222,20762,20091,20184,20183,20054,20621,20056,20199,
					30228,20693,20692,20241,20563,20561,30249,20622,143,9072,144,20249,20223,20270,20246,20001,20002,20003,20004,20007,20285,20323,20616,20055,
					139,20175,20176,141,142,20158, 30499,20309,20021,20312,20269,30299,10187,20716,20268,20968,20216,20215,20962,20080,31002,31005,31015,30580,31023,31033,31038,31043,31048,31175,31188,20776)
				END
			ELSE
				BEGIN
					SELECT S.Id AS Id,LEFT(S.Title,32) AS Title 
					From sSecurity.tScreen S 
					INNER JOIN sSecurity.tPermission P ON P.TaskId=S.TaskId 
					INNER JOIN sSecurity.tUserRole U ON U.RoleId=P.RoleId 
					INNER JOIN sSecurity.tTask T ON T.ID = p.TaskId 
					INNER JOIN sSecurity.tOrganizationTask OT ON T.Id = OT.TaskId AND OT.OrgGroupId = P.OrgGroupId 
					WHERE (P.Permission & 2) =2 AND U.IsObsolete=0 AND T.IsObsolete = 0 AND U.UserId=@rUserId
					AND T.Id IN (20085,20086,30401,30222,20762,20091,20184,20183,20054,20621,20056,20199,
					30228,20693,20692,20241,20563,20561,30249,20622,143,9072,144,20249,20223,20270,20246,20001,20002,20003,20004,20007,20285,20323,20616,20055,
					139,20175,20176,141,142,20158, 30499,20309,20021,20312,20269,30299,10187,20716,20268,20968,20216,20215,20962,20080,31002,31005,31015,30580,310235,31033,31038,31043,31048,31175,31179,30331,31182,31188,20776)
				END
		END
		ELSE
		BEGIN
			  IF EXISTS (SELECT 1 FROM sSecurity.tPermissionUser WHERE UserId=@rUserId AND OrgGroupId=@lOrgGroupId)
				BEGIN
					SELECT S.Id AS Id,LEFT(S.Title,32) AS Title 
					From sSecurity.tScreen S 
					INNER JOIN sSecurity.tPermissionUser P ON P.TaskId=S.TaskId 
					INNER JOIN sSecurity.tTask T ON T.ID = p.TaskId 
					INNER JOIN sSecurity.tOrganizationTask OT ON T.Id = OT.TaskId AND OT.OrgGroupId = P.OrgGroupId 
					INNER JOIN sSecurity.tModulePermission MP ON MP.ModuleId=T.ModuleId AND MP.OrgGroupId=@lOrgGroupId
					WHERE (P.Permission & 2) =2 AND P.OrgGroupId = @lOrgGroupId AND T.IsObsolete = 0 AND P.UserId=@rUserId
				END
			  ELSE
				BEGIN
					SELECT S.Id AS Id,LEFT(S.Title,32) AS Title 
					From sSecurity.tScreen S 
					INNER JOIN sSecurity.tPermission P ON P.TaskId=S.TaskId 
					INNER JOIN sSecurity.tUserRole U ON U.RoleId=P.RoleId 
					INNER JOIN sSecurity.tTask T ON T.ID = p.TaskId 
					INNER JOIN sSecurity.tOrganizationTask OT ON T.Id = OT.TaskId AND OT.OrgGroupId = P.OrgGroupId 
					WHERE (P.Permission & 2) =2 AND U.IsObsolete=0 AND T.IsObsolete = 0 AND U.UserId=@rUserId
				END
		END
END

END
GO
PRINT N'Altering [sStudent].[pChangeClassGet]...';


GO
ALTER PROCEDURE [sStudent].[pChangeClassGet]
	 
	 @rClassID int,
	 @rDivisionId int,
	 @rStrIDNo nvarchar(500),
	 @rOrgId int,
	 @rBatchId int,
	 @rOrderBy int=0
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 

		DECLARE @ListofIDs TABLE(IDs nvarchar(20), ID INT IDENTITY(1,1));
		INSERT INTO @ListofIDs

		select q2.value from
		(SELECT cast('<x>'+replace(@rStrIDNo,',','</x><x>')+'</x>' as xml) as thexml)q1 CROSS APPLY
		(SELECT x.value('.','nvarchar(20)') as value FROM thexml.nodes('x') as f(x))q2
		
		
	 --IF(@rIsSearch=1)
		--BEGIN
			--SET @rGRNo = sCommon.fSearchStringGet(@rGRNo)
			--SET @rLastName = sCommon.fSearchStringGet(@rLastName)
			--SET @rFirstName = sCommon.fSearchStringGet(@rFirstName)
		--END
	
	SELECT 
			SN.AcademicId,
			--A.StudentId,
			--SO.GenderId,
			SN.ClassId,
			SN.DivisionId,
			SN.RollNo AS RollNo,
			SN.FirstName,
			SN.MiddleName,
			SN.LastName,
			SN.FirstName + ' ' + SN.MiddleName + ' ' + SN.LastName AS Name,
			--SN.Number AS GRNo
			SN.Code
      
  FROM 
			[sStudent].[vStudentName] SN
           --sStudent.tAcademic A
           --INNER JOIN sStudent.tStudentMaster SM ON SM.Id=A.StudentId 
           ----INNER JOIN sStudent.tStudentOther SO ON SO.StudentId=A.StudentId  
  WHERE 
				(SN.ClassId=@rClassId OR @rClassId=0)
			AND (SN.DivisionId=@rDivisionId OR @rDivisionId=0)
			AND ((SN.Code IN(SELECT IDs FROM @ListofIDs)) OR (ISNULL(@rStrIDNo,'') = ''))
			AND SN.OrgID=@rOrgId 
			AND SN.BatchID=@rBatchId

	ORDER BY CASE WHEN @rOrderBy=1 THEN (CASE ISNUMERIC(SN.Code) WHEN 1 THEN REPLICATE(0 , 100 - LEN(SN.Code)) + SN.Code ELSE SN.Code  END) END,
			 CASE WHEN @rOrderBy=2 THEN SN.LastName
				  WHEN @rOrderBy=3 THEN SN.FirstName END,
			 CASE WHEN @rOrderBy=4 THEN SN.RollNo END
END
GO
PRINT N'Altering [sStudent].[pHistoryLogGet]...';


GO
ALTER PROCEDURE [sStudent].[pHistoryLogGet]
				
		   --@rClassId int,
           @rSourceTypeId int,
		   @rScreenName varchar(100),
		   @rSourceCode BigInt
           
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
BEGIN 
	
	BEGIN
	        --Declare @PrefixSearch varchar(50)
	       
	      -- SELECT (Id) AS StudentId FROM sStudent.tStudentMaster where Code=@rSourceCode
	
			SELECT
			    --Name = CASE 
			    --  WHEN HL.SourceTypeId = 2003 THEN (SELECT (FirstName+' '+ MiddleName +' '+ LastName) As Name FROM sStudent.tStudentMaster WHERE Id=HL.SourceId)
			    --  WHEN HL.SourceTypeId = 95 THEN (SELECT (FirstName+' '+ MiddleName +' '+ LastName) As Name FROM sHrm.tEmployeeMaster WHERE Id=HL.SourceId)			     			     
			    --END			   
			    --,
			    AuditEntry--,
			    --(SELECT CODE FROM sStudent.tStatusMaster where Id=(SELECT AuditEntry.value('(/deleted/@StatusId)[1]', 'bigint'))) AS Status			    
			   FROM 
			      sAudit.HistoryLog HL					
			   WHERE 
			      HL.SourceTypeId=@rSourceTypeId and HL.ScreenName=@rScreenName	
			     --AND (AuditEntry.value('(/deleted/@Code)[1]', 'varchar(20)') = @rSourceCode OR @rSourceCode = '') 
			     --AND
			     --(((@rScreenName = 'StudentMaster' AND (AuditEntry.value('(/deleted/@Id)[1]','bigint') = @rSourceCode) OR @rSourceCode = 0))
			     --OR
        --          ((AuditEntry.value('(/deleted/@StudentId)[1]', 'varchar(20)') = @rSourceCode OR @rSourceCode = ''))
        --          )
			    AND
			     (((@rScreenName = 'StudentMaster' AND (AuditEntry.exist('(/deleted/@Id[.=sql:variable("@rSourceCode")])')=1)))
			     OR
                  ((AuditEntry.exist('(/deleted/@StudentId[.=sql:variable("@rSourceCode")])')=1))
                  )
			     
			   Order by CreatedDateTime DESC  
			     
			    
	 END
	
END

--select *from sStudent.tStudentMaster where Id=1101000003514
--select *from sHrm.tEmployeeMaster

--2003
--95
GO
PRINT N'Altering [sStudent].[pRptStudentStrengthDivisionWiseGet]...';


GO

 
ALTER PROCEDURE [sStudent].[pRptStudentStrengthDivisionWiseGet]
	 
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 @rOrgId smallint,
	 @rBatchId int,
	 @rClassId int,
	 @rDivisionId int,
	 @rDepartmentId int,
	 @rStudentCode varchar(20)='',
	 @rReportId int=0,
	 @rOrggroupBatchID int=0
	 ,@rAsOnDate Date =''
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
  DECLARE @lCount Int
	SELECT 
	
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			CM.DisplayTitle AS Class,
			DM.DisplayTitle AS Division,
			A.ClassId,
			A.DivisionId,
			CM.DisplayTitle+' - '+DM.DisplayTitle AS ClassDivision,
			DM.OrderIndex AS DivisionOrder,
			Cm.OrderINdex AS ClassOrderIndex  ,
		    ISNUll(AR.SourceId,0) AS HostelStudent,
			ISNUll(RT.SourceId,0) AS TransportStudent,
			A.StudentId 
			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 sHostel.tAssignRoom AR ON AR.SourceId=A.StudentId AND AR.SourceTypeId=2003 
			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 = A.StudentId
			INNER JOIN sSetup.tBatchClass BC ON BC.ClassID =  CM.Id and BC.BatchId= @rBatchId
    
	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
		AND ((SM.Code=@rStudentCode) OR (@rStudentCode=''))
		AND ((CM.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
		--AND ((SA.LeftDate > @rAsOnDate) OR (SA.LeftDate Is null AND SM.StatusId = 1))
		
	   END
GO
PRINT N'Altering [sStudent].[pStudentAllBatchDocumentSubmitGet]...';


GO

ALTER PROCEDURE [sStudent].[pStudentAllBatchDocumentSubmitGet]
	 
        @rStudentId bigint,
		@rOrgId int
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
 
	BEGIN
			SELECT DISTINCT Isnull(D.Id,0) AS DocumentId,ISNULL(D.DocumentName,'') AS DocumentName,
			CASE WHEN   UD.DocumentId is null THEN 'False' ELSE 'True'END AS IsCheck,
			 ISNULL(UD.DocumentName,'') As FileName,
			isnull(Ud.OrgGroupBatchId,0) AS OrgGroupBatchId,ISNULL(S.IsMigrate,0) as IsMigrate,
			Isnull(cast(UD.DocumentSize as nvarchar),'') AS DocumentSize
		 	FROM sCommon.tSubmitDocumentMaster D
			INNER JOIN sCommon.tSubmitDocumentScope DS ON DS.SubmitDocumentId = D.Id
			INNER JOIN sStudent.tAcademic A ON A.ClassId = DS.SourceId AND A.StudentId = @rStudentId
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId AND BM.IsActive = 1
			LEFT Join sStudent.tStudentDocument  S ON S.SubmitDocumentMasterId=D.id AND S.StudentId=@rStudentId
			Left Join [sCommon].[tUploadDocument] UD On UD.DocumentId=D.id AND UD.UploadFunctionalityId=11 AND UserSourceTypeId=2003  AND UserSourceId=@rStudentId
			WHERE D.OrgId=@rOrgId AND SubmitDocumentFunctionalityId='1'

			UNION 

			SELECT DISTINCT Isnull(D.Id,0) AS DocumentId,ISNULL(D.DocumentName,'') AS DocumentName,
			CASE WHEN  UD.DocumentId is null THEN 'False' ELSE 'True'END AS IsCheck,
			 ISNULL(UD.DocumentName,'') As FileName,
			isnull(Ud.OrgGroupBatchId,0) AS OrgGroupBatchId,ISNULL(S.IsMigrate,0) as IsMigrate,
			Isnull(cast(UD.DocumentSize as nvarchar),'') AS DocumentSize
		 	FROM sCommon.tSubmitDocumentMaster D
			LEFT JOIN sCommon.tSubmitDocumentScope DS ON DS.SubmitDocumentId = D.Id AND DS.SubmitDocumentId is null
			LEFT JOIN sStudent.tAcademic A ON A.ClassId = DS.SourceId AND A.StudentId = @rStudentId 
			LEFT JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId AND BM.IsActive = 1
			LEFT Join sStudent.tStudentDocument  S ON S.SubmitDocumentMasterId=D.id AND S.StudentId=@rStudentId
			Left Join [sCommon].[tUploadDocument] UD On UD.DocumentId=D.id AND UD.UploadFunctionalityId=11 AND UserSourceTypeId=2003  AND UserSourceId=@rStudentId
			WHERE D.OrgId=@rOrgId AND SubmitDocumentFunctionalityId='1' AND A.ClassId is not null--AND DS.SubmitDocumentId is null 


END
GO
PRINT N'Altering [sStudent].[pStudentCustomFieldsUpdateGet]...';


GO

ALTER PROCEDURE [sStudent].[pStudentCustomFieldsUpdateGet]
	 		
	 @rOrgId int,
	 @rClassId int,
	 @rDivisionId int,
	 @rBatchId int,	
	 @rStatusId int,	 
	 @rSubCategoryId int,
	 @rIsBlank bit
	 
AS
SET NOCOUNT ON

BEGIN
		DECLARE @lDataTypeId nvarchar(1)
		SELECT @lDataTypeId=FieldTypeId FROM sStudent.tStudentCustomFieldMaster WHERE Id=@rSubCategoryId
		
		 Declare @Sql nvarchar(max)
		 Declare @Sql1 nvarchar(max)
		 
		 --IF(@lDataTypeId=3)   --For Free Text and Numeric
		 --BEGIN
		 
		     SET @Sql = 'select *from (Select Row_Number() OVER (PARTITION BY SA.StudentID ORDER BY CASE WHEN SCF.FieldTypeId IS NOT NULL THEN SCF.FieldTypeId END Desc) as RowNumber, SA.StudentId,SA.AcademicId,SA.Code,SA.Name,SA.ClassName+'' - ''+SA.DivisionName AS ClassDivision,SA.RollNo,SA.Number,
		            CASE WHEN SCF.FieldTypeId=3 OR SCF.FieldTypeId=4 THEN
					ISNULL(SC.FieldData,'''') 
					WHEN SCF.FieldTypeId=2 THEN
					ISNULL(SC.FieldData,''0'')
					WHEN SCF.FieldTypeId=1 THEN
					ISNULL(SC.FieldData,''False'') 				
					END AS SubCategory
			FROM 
		       sStudent.vStudentAcademic SA
		         LEFT JOIN sStudent.tStudentCustomFieldData SC ON SC.StudentId=SA.StudentId
		         LEFT JOIN sStudent.tStudentCustomFieldMaster SCF ON SCF.Id=SC.StudentCustomFieldId AND SCF.FieldTypeId='''+@lDataTypeId+'''  AND SCF.Id= '''+CAST(@rSubCategoryId AS nvarchar(15))+''' AND SCF.IsObsolete=0 
		         
		    Where SA.OrgId='+CAST(@rOrgId AS nvarchar(15))
			+'AND (SA.ClassId='+CAST(@rClassId AS nvarchar(15))+ 'OR '+CAST(@rClassId AS nvarchar(15))+'=0)
			AND (SA.DivisionId='+CAST(@rDivisionId AS nvarchar(15))+ 'OR '+CAST(@rDivisionId AS nvarchar(15))+'=0)
			AND (SA.StatusId='+ CAST(@rStatusId AS nvarchar(15)) +' OR '+CAST(@rStatusId AS nvarchar(15))+'=0)
			AND (SA.BatchId='+CAST(@rBatchId AS nvarchar(15))+')
			AND 
			('+CAST(@rIsBlank AS nvarchar(1))+'=0 
				OR (SCF.FieldTypeId=3 AND ISNULL(SC.FieldData,'''')='''')
				OR (SCF.FieldTypeId=4 AND ISNULL(SC.FieldData,'''')='''')
				OR (SCF.FieldTypeId=2 AND ISNULL(SC.FieldData,''0'')=''0'')
				OR (SCF.FieldTypeId=1 AND ISNULL(SC.FieldData,''False'')=''False'') 
			)
			) AS a where RowNumber =1
			'
			    
		 		
		  print @Sql		
		   		
			EXECUTE  sp_executesql @Sql		
	   
END
GO
PRINT N'Altering [sStudent].[pStudentCustomSearchGet]...';


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

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

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

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

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

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


GO
ALTER PROCEDURE [sStudent].[pStudentDetailUpdateGet]
	 
	 @rCategoryId int,
	 @rSubCategory nvarchar(100),
	 @rOrgId int,
	 @rClassId int,
	 @rDivisionId int,
	 @rBatchId int,
	 --@rIsBlank bit,
	 @rStatusId int,
	 @rOrderBy int,
	 @rFromCode nvarchar(20)='',
	 @rToCode nvarchar(20)='',
	  @rMultiCode nvarchar(max)=''
	 
AS
SET NOCOUNT ON

BEGIN
	 	DECLARE @lDataTypeId nvarchar(1)
		SELECT @lDataTypeId=DataTypeId FROM sCommon.tUpdateFieldMaster WHERE Field=@rSubCategory
		 
		 
		 IF @rCategoryId=1 
		 BEGIN-- Communication
			IF @rSubCategory ='Present Address'
			BEGIN
				if @rOrderBY=1
				BEGIN
				Select  SA.StudentId,SA.AcademicId,SA.Name,SA.ClassName+' - '+SA.DivisionName AS ClassDivision,SA.RollNo,SA.Code,
						PresentStreetOne,
						PresentStreetTwo,
						PresentStreetThree,
						PresentCountry,
						PresentState,
						PresentCity,
						PresentZipCode,
						PresentContactNo
				FROM 
				sStudent.vStudentAcademic SA
				LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId=SA.StudentId
				Where SA.OrgId=@rOrgId
				AND ((SA.ClassId=@rClassId) OR (@rClassId =0))
				AND ((SA.DivisionId=@rDivisionId) OR  (@rDivisionId=0))
				AND ((SA.StatusId= @rStatusId ) OR  (@rStatusId  =0))
				AND ((SA.BatchId= @rBatchId )) 
				AND((SA.Code >= @rFromCode) OR (ISNULL(@rFromCode,'') = ''))  
			    AND((SA.Code <= @rToCode) OR (ISNULL(@rToCode,'') = '')) 
			    AND (ISNULL(SA.Code,0) IN( SELECT cast(item as nvarchar(20)) FROM  sCommon.fnsplit(@rMultiCode,',')) OR @rMultiCode='')
				
				ORder BY SA.RollNo
				END
				Else
				BEGIN
					Select  SA.StudentId,SA.AcademicId,SA.Name,SA.ClassName+' - '+SA.DivisionName AS ClassDivision,SA.RollNo,SA.Code,
						PresentStreetOne,
						PresentStreetTwo,
						PresentStreetThree,
						PresentCountry,
						PresentState,
						PresentCity,
						PresentZipCode,
						PresentContactNo
				FROM 
				sStudent.vStudentAcademic SA
				LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId=SA.StudentId
				Where SA.OrgId=@rOrgId
				AND ((SA.ClassId=@rClassId) OR (@rClassId =0))
				AND ((SA.DivisionId=@rDivisionId) OR  (@rDivisionId=0))
				AND ((SA.StatusId= @rStatusId ) OR  (@rStatusId  =0))
				AND ((SA.BatchId= @rBatchId )) 
				AND((SA.Code >= @rFromCode) OR (ISNULL(@rFromCode,'') = ''))  
			    AND((SA.Code <= @rToCode) OR (ISNULL(@rToCode,'') = '')) 
			    AND (ISNULL(SA.Code,0) IN( SELECT cast(item as nvarchar(20)) FROM  sCommon.fnsplit(@rMultiCode,',')) OR @rMultiCode='')
				
				ORder BY CASE ISNUMERIC(SA.Code) WHEN 1 THEN REPLICATE(0 , 100 - LEN(SA.Code)) + SA.Code ELSE SA.Code  END		--add
				END	
			END
			IF @rSubCategory ='Permanent Address'
			BEGIN
				if @rOrderBY=1
				BEGIN
				Select  SA.StudentId,SA.AcademicId,SA.Name,SA.ClassName+' - '+SA.DivisionName AS ClassDivision,SA.RollNo,SA.Code,
						PermanentStreetOne As PresentStreetOne,
						PermanentStreetTwo AS PresentStreetTwo,
						PermanentStreetThree AS PresentStreetThree,
						PermanentCountry AS PresentCountry,
						PermanentState AS PresentState,
						PermanentCity As PresentCity,
						PermanentZipCode As PresentZipCode,
						PermanentContactNo AS PresentContactNo
				FROM 
				sStudent.vStudentAcademic SA
				LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId=SA.StudentId
				Where SA.OrgId=@rOrgId
				AND ((SA.ClassId=@rClassId) OR (@rClassId =0))
				AND ((SA.DivisionId=@rDivisionId) OR  (@rDivisionId=0))
				AND ((SA.StatusId= @rStatusId ) OR  (@rStatusId  =0))
				AND ((SA.BatchId= @rBatchId )) 
				AND((SA.Code >= @rFromCode) OR (ISNULL(@rFromCode,'') = ''))  
			    AND((SA.Code <= @rToCode) OR (ISNULL(@rToCode,'') = '')) 
				AND (ISNULL(SA.Code,0) IN( SELECT cast(item as nvarchar(20)) FROM  sCommon.fnsplit(@rMultiCode,',')) OR @rMultiCode='')
				
				Order by Sa.RollNo
				END
				ELSE
				BEGIN
					Select  SA.StudentId,SA.AcademicId,SA.Name,SA.ClassName+' - '+SA.DivisionName AS ClassDivision,SA.RollNo,SA.Code,
						PermanentStreetOne As PresentStreetOne,
						PermanentStreetTwo AS PresentStreetTwo,
						PermanentStreetThree AS PresentStreetThree,
						PermanentCountry AS PresentCountry,
						PermanentState AS PresentState,
						PermanentCity As PresentCity,
						PermanentZipCode As PresentZipCode,
						PermanentContactNo AS PresentContactNo
				FROM 
				sStudent.vStudentAcademic SA
				LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId=SA.StudentId
				Where SA.OrgId=@rOrgId
				AND ((SA.ClassId=@rClassId) OR (@rClassId =0))
				AND ((SA.DivisionId=@rDivisionId) OR  (@rDivisionId=0))
				AND ((SA.StatusId= @rStatusId ) OR  (@rStatusId  =0))
				AND ((SA.BatchId= @rBatchId ))
				AND((SA.Code >= @rFromCode) OR (ISNULL(@rFromCode,'') = ''))  
			    AND((SA.Code <= @rToCode) OR (ISNULL(@rToCode,'') = '')) 
				 AND (ISNULL(SA.Code,0) IN( SELECT cast(item as nvarchar(20)) FROM  sCommon.fnsplit(@rMultiCode,',')) OR @rMultiCode='')
				 
				Order By CASE ISNUMERIC(SA.Code) WHEN 1 THEN REPLICATE(0 , 100 - LEN(SA.Code)) + SA.Code ELSE SA.Code  END		--add
				END
			END
			IF @rSubCategory ='Emergency Address'
			BEGIN
				if @rOrderBY=1
				BEGIN
				Select  SA.StudentId,SA.AcademicId,SA.Name,SA.ClassName+' - '+SA.DivisionName AS ClassDivision,SA.RollNo,SA.Code,
						EmergencyStreetOne AS PresentStreetOne,
						EmergencyStreetTwo As PresentStreetTwo, 
						EmergencyStreetThree As PresentStreetThree,
						EmergencyCountry As PresentCountry,
						EmergencyState As PresentState,
						EmergencyCity AS PresentCity,
						EmergencyZipCode As PresentZipCode,
						EmergencyContactNo  AS PresentContactNo
				FROM 
				sStudent.vStudentAcademic SA
				LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId=SA.StudentId
				Where SA.OrgId=@rOrgId
				AND ((SA.ClassId=@rClassId) OR (@rClassId =0))
				AND ((SA.DivisionId=@rDivisionId) OR  (@rDivisionId=0))
				AND ((SA.StatusId= @rStatusId ) OR  (@rStatusId  =0))
				AND ((SA.BatchId= @rBatchId )) 
				AND((SA.Code >= @rFromCode) OR (ISNULL(@rFromCode,'') = ''))  
			    AND((SA.Code <= @rToCode) OR (ISNULL(@rToCode,'') = '')) 
				AND (ISNULL(SA.Code,0) IN( SELECT cast(item as nvarchar(20)) FROM  sCommon.fnsplit(@rMultiCode,',')) OR @rMultiCode='')
				
				Order BY SA.RollNo
				END
				Else
				BEGIN
					Select  SA.StudentId,SA.AcademicId,SA.Name,SA.ClassName+' - '+SA.DivisionName AS ClassDivision,SA.RollNo,SA.Code,
						EmergencyStreetOne AS PresentStreetOne,
						EmergencyStreetTwo As PresentStreetTwo, 
						EmergencyStreetThree As PresentStreetThree,
						EmergencyCountry As PresentCountry,
						EmergencyState As PresentState,
						EmergencyCity AS PresentCity,
						EmergencyZipCode As PresentZipCode,
						EmergencyContactNo  AS PresentContactNo
				FROM 
				sStudent.vStudentAcademic SA
				LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId=SA.StudentId
				Where SA.OrgId=@rOrgId
				AND ((SA.ClassId=@rClassId) OR (@rClassId =0))
				AND ((SA.DivisionId=@rDivisionId) OR  (@rDivisionId=0))
				AND ((SA.StatusId= @rStatusId ) OR  (@rStatusId  =0))
				AND ((SA.BatchId= @rBatchId )) 
				AND((SA.Code >= @rFromCode) OR (ISNULL(@rFromCode,'') = ''))  
			    AND((SA.Code <= @rToCode) OR (ISNULL(@rToCode,'') = '')) 
				AND (ISNULL(SA.Code,0) IN( SELECT cast(item as nvarchar(20)) FROM  sCommon.fnsplit(@rMultiCode,',')) OR @rMultiCode='')
				
				Order By CASE ISNUMERIC(SA.Code) WHEN 1 THEN REPLICATE(0 , 100 - LEN(SA.Code)) + SA.Code ELSE SA.Code  END		--add
				END
			END
		END
		IF @rCategoryId= 4 
		BEGIN --Family
			IF @rSubCategory ='Father'
				BEGIN
				if @rOrderBY=1
				BEGIN
					Select  SA.StudentId,SA.AcademicId,SA.Name,SA.ClassName+' - '+SA.DivisionName AS ClassDivision,SA.RollNo,SA.Code,
							FatherName,FatherDateOfBirth,FatherOccupation,FatherQualification,FatherContactNo,FatherMail,
							FatherOfficeAddress,FatherIncome,FatherOfficeContactNo
					FROM 
					sStudent.vStudentAcademic SA
					LEFT JOIN sStudent.tStudentFamily SC ON SC.StudentId=SA.StudentId
					Where SA.OrgId=@rOrgId
				AND ((SA.ClassId=@rClassId) OR (@rClassId =0))
				AND ((SA.DivisionId=@rDivisionId) OR  (@rDivisionId=0))
				AND ((SA.StatusId= @rStatusId ) OR  (@rStatusId  =0))
				AND ((SA.BatchId= @rBatchId )) 
				AND((SA.Code >= @rFromCode) OR (ISNULL(@rFromCode,'') = ''))  
			    AND((SA.Code <= @rToCode) OR (ISNULL(@rToCode,'') = '')) 
				
				ORder BY SA.RollNo
				END
				Else
				BEGIN
					Select  SA.StudentId,SA.AcademicId,SA.Name,SA.ClassName+' - '+SA.DivisionName AS ClassDivision,SA.RollNo,SA.Code,
							FatherName,FatherDateOfBirth,FatherOccupation,FatherQualification,FatherContactNo,FatherMail,
							FatherOfficeAddress,FatherIncome,FatherOfficeContactNo
					FROM 
					sStudent.vStudentAcademic SA
					LEFT JOIN sStudent.tStudentFamily SC ON SC.StudentId=SA.StudentId
					Where SA.OrgId=@rOrgId
				AND ((SA.ClassId=@rClassId) OR (@rClassId =0))
				AND ((SA.DivisionId=@rDivisionId) OR  (@rDivisionId=0))
				AND ((SA.StatusId= @rStatusId ) OR  (@rStatusId  =0))
				AND ((SA.BatchId= @rBatchId )) 
				AND((SA.Code >= @rFromCode) OR (ISNULL(@rFromCode,'') = ''))  
			    AND((SA.Code <= @rToCode) OR (ISNULL(@rToCode,'') = '')) 
				
				Order By CASE ISNUMERIC(SA.Code) WHEN 1 THEN REPLICATE(0 , 100 - LEN(SA.Code)) + SA.Code ELSE SA.Code  END		--add
				END
			END
			IF @rSubCategory ='Mother'
				BEGIN
				if @rOrderBY=1
				BEGIN
					Select  SA.StudentId,SA.AcademicId,SA.Name,SA.ClassName+' - '+SA.DivisionName AS ClassDivision,SA.RollNo,SA.Code,
							MotherName,MotherDateOfBirth,MotherOccupation,MotherQualification,MotherContactNo,MotherMail,
							MotherOfficeAddress,MotherIncome,MotherOfficeContactNo
					FROM 
					sStudent.vStudentAcademic SA
					LEFT JOIN sStudent.tStudentFamily SC ON SC.StudentId=SA.StudentId
					Where SA.OrgId=@rOrgId
					AND ((SA.ClassId=@rClassId) OR (@rClassId =0))
				AND ((SA.DivisionId=@rDivisionId) OR  (@rDivisionId=0))
				AND ((SA.StatusId= @rStatusId ) OR  (@rStatusId  =0))
				AND ((SA.BatchId= @rBatchId )) 
				AND((SA.Code >= @rFromCode) OR (ISNULL(@rFromCode,'') = ''))  
			    AND((SA.Code <= @rToCode) OR (ISNULL(@rToCode,'') = '')) 
				
				Order By SA.ROllNO
				END
				Else
				BEGIN
					Select  SA.StudentId,SA.AcademicId,SA.Name,SA.ClassName+' - '+SA.DivisionName AS ClassDivision,SA.RollNo,SA.Code,
							MotherName,MotherDateOfBirth,MotherOccupation,MotherQualification,MotherContactNo,MotherMail,
							MotherOfficeAddress,MotherIncome,MotherOfficeContactNo
					FROM 
					sStudent.vStudentAcademic SA
					LEFT JOIN sStudent.tStudentFamily SC ON SC.StudentId=SA.StudentId
					Where SA.OrgId=@rOrgId
					AND ((SA.ClassId=@rClassId) OR (@rClassId =0))
				AND ((SA.DivisionId=@rDivisionId) OR  (@rDivisionId=0))
				AND ((SA.StatusId= @rStatusId ) OR  (@rStatusId  =0))
				AND ((SA.BatchId= @rBatchId )) 
				AND((SA.Code >= @rFromCode) OR (ISNULL(@rFromCode,'') = ''))  
			    AND((SA.Code <= @rToCode) OR (ISNULL(@rToCode,'') = '')) 
				
				Order By CASE ISNUMERIC(SA.Code) WHEN 1 THEN REPLICATE(0 , 100 - LEN(SA.Code)) + SA.Code ELSE SA.Code  END		--add
				END
			END
			IF @rSubCategory ='Relative'
				BEGIN
				if @rOrderBY=1
				BEGIN
					Select  SA.StudentId,SA.AcademicId,SA.Name,SA.ClassName+' - '+SA.DivisionName AS ClassDivision,SA.RollNo,SA.Code,
							RelativeName,RelativeDateOfBirth,RelativeOccupation,RelativeQualification,RelativeContactNo,RelativeMail,
							RelativeOfficeAddress,RelativeIncome,RelationshipName
					FROM 
					sStudent.vStudentAcademic SA
					LEFT JOIN sStudent.tStudentFamily SC ON SC.StudentId=SA.StudentId
					Where SA.OrgId=@rOrgId
					AND ((SA.ClassId=@rClassId) OR (@rClassId =0))
				AND ((SA.DivisionId=@rDivisionId) OR  (@rDivisionId=0))
				AND ((SA.StatusId= @rStatusId ) OR  (@rStatusId  =0))
				AND ((SA.BatchId= @rBatchId )) 
				AND((SA.Code >= @rFromCode) OR (ISNULL(@rFromCode,'') = ''))  
			    AND((SA.Code <= @rToCode) OR (ISNULL(@rToCode,'') = '')) 
				
				Order By SA.ROllNo
				END
				Else
				BEGIN
					Select  SA.StudentId,SA.AcademicId,SA.Name,SA.ClassName+' - '+SA.DivisionName AS ClassDivision,SA.RollNo,SA.Code,
							RelativeName,RelativeDateOfBirth,RelativeOccupation,RelativeQualification,RelativeContactNo,RelativeMail,
							RelativeOfficeAddress,RelativeIncome,RelationshipName
					FROM 
					sStudent.vStudentAcademic SA
					LEFT JOIN sStudent.tStudentFamily SC ON SC.StudentId=SA.StudentId
					Where SA.OrgId=@rOrgId
					AND ((SA.ClassId=@rClassId) OR (@rClassId =0))
				AND ((SA.DivisionId=@rDivisionId) OR  (@rDivisionId=0))
				AND ((SA.StatusId= @rStatusId ) OR  (@rStatusId  =0))
				AND ((SA.BatchId= @rBatchId )) 
				AND((SA.Code >= @rFromCode) OR (ISNULL(@rFromCode,'') = ''))  
			    AND((SA.Code <= @rToCode) OR (ISNULL(@rToCode,'') = '')) 
			    
				Order By CASE ISNUMERIC(SA.Code) WHEN 1 THEN REPLICATE(0 , 100 - LEN(SA.Code)) + SA.Code ELSE SA.Code  END		--add
				END
			END
			
		END			
		IF @rCategoryId= 10 
		BEGIN
			IF @rSubCategory ='Academic'
			BEGIN
			
				if @rOrderBY=1
				 BEGIN
					 Select 
						SA.StudentId,SA.Code,SA.FirstName,SA.MiddleName,SA.LastName,SA.ClassName,SA.ClassId,SA.DivisionID,
						SA.DivisionName,convert(date,SO.DateOfBirth) As DateOfBirth,AD.AdmissionDate,AD.AdmissionStandardId,SA.Name,Sa.RollNo,SO.GenderId
					From  
						 sStudent.vStudentAcademic SA
						INNER JOIN sStudent.tStudentOther SO 
									ON SO.StudentId=SA.StudentId
						LEFT JOIN sStudent.tStudentAdmission AD
									ON AD.StudentID = SA.StudentId  
					Where SA.OrgId=@rOrgId
						AND ((SA.ClassId=@rClassId) OR (@rClassId =0))
					AND ((SA.DivisionId=@rDivisionId) OR  (@rDivisionId=0))
					AND ((SA.StatusId= @rStatusId ) OR  (@rStatusId  =0))
					AND ((SA.BatchId= @rBatchId )) 
					AND((SA.Code >= @rFromCode) OR (ISNULL(@rFromCode,'') = ''))  
			        AND((SA.Code <= @rToCode) OR (ISNULL(@rToCode,'') = '')) 
			        
					Order by RollNo
				END
				else
				BEGIN
				Select 
						SA.StudentId,SA.Code,SA.FirstName,SA.MiddleName,SA.LastName,SA.ClassName,SA.ClassId,SA.DivisionID,
						SA.DivisionName,convert(date,SO.DateOfBirth) DateOfBirth,AD.AdmissionDate,AD.AdmissionStandardId,SA.Name,Sa.RollNo,SO.GenderId
					From  
						 sStudent.vStudentAcademic SA
						INNER JOIN sStudent.tStudentOther SO 
									ON SO.StudentId=SA.StudentId
						LEFT JOIN sStudent.tStudentAdmission AD
									ON AD.StudentID = SA.StudentId  
					Where SA.OrgId=@rOrgId
						AND ((SA.ClassId=@rClassId) OR (@rClassId =0))
					AND ((SA.DivisionId=@rDivisionId) OR  (@rDivisionId=0))
					AND ((SA.StatusId= @rStatusId ) OR  (@rStatusId  =0))
					AND ((SA.BatchId= @rBatchId ))
					AND((SA.Code >= @rFromCode) OR (ISNULL(@rFromCode,'') = ''))  
			        AND((SA.Code <= @rToCode) OR (ISNULL(@rToCode,'') = '')) 
					 
					Order by CASE ISNUMERIC(SA.Code) WHEN 1 THEN REPLICATE(0 , 100 - LEN(SA.Code)) + SA.Code ELSE SA.Code  END		--add
				END
			END
			
			IF @rSubCategory ='Main Group'
			BEGIN
				if @rOrderBY=1
				 BEGIN
					 Select 
						SA.StudentId,SA.Code,SA.FirstName,SA.MiddleName,SA.LastName,SA.ClassName,SA.ClassId,SA.DivisionID,
						SA.DivisionName,AD.Id,ISNULl(AD.Code,'') AS groupCode,ISNULl(AD.Title,'') AS Title,SA.Name,Sa.RollNo 
					From  
						 sStudent.vStudentAcademic SA
						
						LEFT JOIN sStudent.tStudentGroupMaster AD
									ON AD.Id = SA.StudentGroupId  
					Where SA.OrgId=@rOrgId
						AND ((SA.ClassId=@rClassId) OR (@rClassId =0))
					AND ((SA.DivisionId=@rDivisionId) OR  (@rDivisionId=0))
					AND ((SA.StatusId= @rStatusId ) OR  (@rStatusId  =0))
					AND ((SA.BatchId= @rBatchId )) 
					AND((SA.Code >= @rFromCode) OR (ISNULL(@rFromCode,'') = ''))  
			        AND((SA.Code <= @rToCode) OR (ISNULL(@rToCode,'') = '')) 
					
					Order by RollNo
				END
				else
				BEGIN
				Select 
						SA.StudentId,SA.Code,SA.FirstName,SA.MiddleName,SA.LastName,SA.ClassName,SA.ClassId,SA.DivisionID,
						SA.DivisionName,AD.Id,ISNULl(AD.Code,'') AS groupCode,ISNULl(AD.Title,'') As Title,SA.Name,Sa.RollNo 
					From  
						 sStudent.vStudentAcademic SA
						
						LEFT JOIN sStudent.tStudentGroupMaster AD
									ON AD.Id = SA.StudentGroupId  
					Where SA.OrgId=@rOrgId
						AND ((SA.ClassId=@rClassId) OR (@rClassId =0))
					AND ((SA.DivisionId=@rDivisionId) OR  (@rDivisionId=0))
					AND ((SA.StatusId= @rStatusId ) OR  (@rStatusId  =0))
					AND ((SA.BatchId= @rBatchId )) 
					AND((SA.Code >= @rFromCode) OR (ISNULL(@rFromCode,'') = ''))  
			        AND((SA.Code <= @rToCode) OR (ISNULL(@rToCode,'') = '')) 
					
					Order by CASE ISNUMERIC(SA.Code) WHEN 1 THEN REPLICATE(0 , 100 - LEN(SA.Code)) + SA.Code ELSE SA.Code  END		--add
				END
			END
			
			IF @rSubCategory ='Other Group'
			BEGIN
				if @rOrderBY=1
				 BEGIN
					 Select 
						SA.StudentId,SA.Code,SA.FirstName,SA.MiddleName,SA.LastName,SA.ClassName,SA.ClassId,SA.DivisionID,
						SA.DivisionName,AD.Id,ISNULl(AD.Code,'') As groupCode,ISNULl(AD.Title,'') AS Title,SA.Name,Sa.RollNo 
					From  
						 sStudent.vStudentAcademic SA
						
						LEFT JOIN sStudent.tStudentOtherGroupMaster AD
									ON AD.Id = SA.StudentOtherGroupId  
					Where SA.OrgId=@rOrgId
						AND ((SA.ClassId=@rClassId) OR (@rClassId =0))
					AND ((SA.DivisionId=@rDivisionId) OR  (@rDivisionId=0))
					AND ((SA.StatusId= @rStatusId ) OR  (@rStatusId  =0))
					AND ((SA.BatchId= @rBatchId )) 
					AND((SA.Code >= @rFromCode) OR (ISNULL(@rFromCode,'') = ''))  
			        AND((SA.Code <= @rToCode) OR (ISNULL(@rToCode,'') = '')) 
					
					Order by RollNo
				END
				else
				BEGIN
				Select 
						SA.StudentId,SA.Code,SA.FirstName,SA.MiddleName,SA.LastName,SA.ClassName,SA.ClassId,SA.DivisionID,
						SA.DivisionName,Ad.Id,ISNULl(AD.Code,'') As groupCode,ISNULl(AD.Title,'') As Title,SA.Name,Sa.RollNo 
					From  
						 sStudent.vStudentAcademic SA
						
						LEFT JOIN sStudent.tStudentOtherGroupMaster AD
									ON AD.Id = SA.StudentOtherGroupId  
					Where SA.OrgId=@rOrgId
						AND ((SA.ClassId=@rClassId) OR (@rClassId =0))
					AND ((SA.DivisionId=@rDivisionId) OR  (@rDivisionId=0))
					AND ((SA.StatusId= @rStatusId ) OR  (@rStatusId  =0))
					AND ((SA.BatchId= @rBatchId )) 
					AND((SA.Code >= @rFromCode) OR (ISNULL(@rFromCode,'') = ''))  
			        AND((SA.Code <= @rToCode) OR (ISNULL(@rToCode,'') = '')) 
					
					Order by CASE ISNUMERIC(SA.Code) WHEN 1 THEN REPLICATE(0 , 100 - LEN(SA.Code)) + SA.Code ELSE SA.Code  END		--add
				END
			END
			
			IF @rSubCategory ='Demographic'
			BEGIN
				if @rOrderBY=1
				 BEGIN
					 Select 
						SA.StudentId,SA.Code,SA.Name,Sa.RollNo,SO.ReligionId,SO.FamilyCast,SO.FamilySubCast,SO.CastCategoryId,SO.NationalityId
					From  
						 sStudent.vStudentAcademic SA
						LEFT JOIN sStudent.tStudentOther SO 
									ON SO.StudentId=SA.StudentId
					Where SA.OrgId=@rOrgId
						AND ((SA.ClassId=@rClassId) OR (@rClassId =0))
					AND ((SA.DivisionId=@rDivisionId) OR  (@rDivisionId=0))
					AND ((SA.StatusId= @rStatusId ) OR  (@rStatusId  =0))
					AND ((SA.BatchId= @rBatchId )) 
					AND((SA.Code >= @rFromCode) OR (ISNULL(@rFromCode,'') = ''))  
			        AND((SA.Code <= @rToCode) OR (ISNULL(@rToCode,'') = '')) 
					
					Order by RollNo
				END
				else
				BEGIN
				Select 
						SA.StudentId,SA.Code,SA.Name,Sa.RollNo,SO.ReligionId,SO.FamilyCast,SO.FamilySubCast,SO.CastCategoryId,SO.NationalityId
					From  
						 sStudent.vStudentAcademic SA
						LEFT JOIN sStudent.tStudentOther SO 
									ON SO.StudentId=SA.StudentId
					Where SA.OrgId=@rOrgId
						AND ((SA.ClassId=@rClassId) OR (@rClassId =0))
					AND ((SA.DivisionId=@rDivisionId) OR  (@rDivisionId=0))
					AND ((SA.StatusId= @rStatusId ) OR  (@rStatusId  =0))
					AND ((SA.BatchId= @rBatchId )) 
					AND((SA.Code >= @rFromCode) OR (ISNULL(@rFromCode,'') = ''))  
			        AND((SA.Code <= @rToCode) OR (ISNULL(@rToCode,'') = '')) 
					
					
					Order by CASE ISNUMERIC(SA.Code) WHEN 1 THEN REPLICATE(0 , 100 - LEN(SA.Code)) + SA.Code ELSE SA.Code  END		--add
				END
			END
			
		END
	 
		   
END
GO
PRINT N'Altering [sStudent].[pStudentDocumentClassWiseGet]...';


GO
ALTER PROCEDURE [sStudent].[pStudentDocumentClassWiseGet]
	@rClassId int=0,
	@rDivisionId int=0,
	@rRollNo int=NULL,
	@rOrgId int,
	@rCode nvarchar(20),
	@rStatusId smallint=0,
	@rFirstName nvarchar(100)='',
	@rLastName nvarchar(100)='',
	@rBatchId int,
    @rSUId nvarchar(50)='',
    @rUserId bigint=0,
    @rMultiCode nvarchar(max)='',
	@rDocumentId int=0,
	@rOrderByTypeId int=0
	
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	 
		BEGIN
			SET @rCode= sCommon.fSearchStringGet(@rCode)
			SET @rFirstName = sCommon.fSearchStringGet(@rFirstName)
			SET @rLastName = sCommon.fSearchStringGet(@rLastName)
		END
	IF(@rRollNo IS NULL)
	BEGIN
	SELECT 
			SA.AcademicId,
			SA.StudentId,
			SA.FirstName,
			SA.LastName,
			SA.Name,
			SA.Code,
			SA.ClassId,
			SA.ClassName,
			SA.DivisionId,
			SA.DivisionName,
			ISNULL(SA.Number,0) AS Number,
			SA.RollNo,
			SA.StatusId,
			SA.StatusName,
			SA.OrgId,
			SA.SUId,
			--SD.DocumentName
			--ISNULL(STUFF(
			-- (SELECT DISTINCT ',' + SDM.DocumentName
			--  FROM sCommon.tSubmitDocumentMaster SDM
			--  INNER JOIN  sStudent.tStudentDocument SD ON SDM.Id=SD.SubmitDocumentMasterId
			--  INNER JOIN sCommon.tSubmitDocumentScope DS ON DS.SubmitDocumentId=SDM.Id AND DS.SourceId = @rClassId
			--  where SD.StudentId=SA.StudentId AND SDM.SubmitDocumentFunctionalityId = 1 AND ((SDM.Id=@rDocumentId)OR(@rDocumentId=0))
			--  FOR XML PATH (''))
			--  , 1, 1, ''),'')  AS DocumentName,
			  ISNULL(sStudent.fStudentDocumentClasswiseget(@rDocumentId,SA.AcademicId),'') AS DocumentName
			
  FROM 
          sStudent.vStudentAcademic SA
		  --LEFT JOIN sStudent.tStudentDocument SD ON SD.StudentId=SA.StudentId
		  INNER JOIN sSecurity.tUserAccess U ON U.SourceId = SA.DivisionId AND U.SourceTypeId=2005
             
  WHERE 
 
		((SA.ClassId=@rClassId)OR(@rClassId=0))
		AND((SA.DivisionId=@rDivisionId)OR(@rDivisionId=0))
		AND((SA.Code like @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)
		AND(SA.BatchId=@rBatchId)
		AND((SA.SUID = @rSUId) OR (ISNULL(@rSUId,'') = '')) 
		--AND((SA.Number=@rNumber)OR(@rNumber=0))	
		AND U.UserId = @rUserId
		AND (ISNULL(SA.Code,0) IN( SELECT cast(item as nvarchar(20)) FROM  sCommon.fnsplit(@rMultiCode,',')) OR @rMultiCode='')
ORDER BY CASE WHEN @rOrderByTypeId = 1 then SA.RollNo END,
		 CASE WHEN @rOrderByTypeId = 2 then (CASE ISNUMERIC(SA.Code) WHEN 1 THEN REPLICATE(0 , 100 - LEN(SA.Code)) + SA.Code ELSE SA.Code  END) END,
			SA.ClassId,SA.DivisionId,SA.RollNo
END
ELSE
BEGIN
	SELECT 
			SA.AcademicId,
			SA.StudentId,
			SA.FirstName,
			SA.LastName,
			SA.Name,
			SA.Code,
			SA.ClassId,
			SA.ClassName,
			SA.DivisionId,
			SA.DivisionName,
			SA.Number,
			SA.RollNo,
			SA.StatusId,
			SA.StatusName,
			SA.OrgId,
			SA.SUId,
			--SD.DocumentName
			ISNULL(sStudent.fStudentDocumentClasswiseget(@rDocumentId,SA.AcademicId),'') AS DocumentName
			
			
  FROM 
          sStudent.vStudentAcademic SA
		  --LEFT JOIN sStudent.tStudentDocument SD ON SD.StudentId=SA.StudentId
          INNER JOIN sSecurity.tUserAccess U ON U.SourceId = SA.DivisionId AND U.SourceTypeId=2005
  WHERE 
 
		((SA.ClassId=@rClassId)OR(@rClassId=0))
		AND((SA.DivisionId=@rDivisionId)OR(@rDivisionId=0))
		AND((SA.Code like @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)
		AND(SA.BatchId=@rBatchId)
		AND((SA.SUID = @rSUId) OR (ISNULL(@rSUId,'') = '')) 
		AND U.UserId = @rUserId
		AND (ISNULL(SA.Code,0) IN( SELECT cast(item as nvarchar(20)) FROM  sCommon.fnsplit(@rMultiCode,',')) OR @rMultiCode='')
		--AND((SA.Number=@rNumber)OR(@rNumber=0))	

ORDER BY CASE WHEN @rOrderByTypeId = 1 then SA.RollNo END,
		 CASE WHEN @rOrderByTypeId = 2 then (CASE ISNUMERIC(SA.Code) WHEN 1 THEN REPLICATE(0 , 100 - LEN(SA.Code)) + SA.Code ELSE SA.Code  END) END,
		 SA.ClassId,SA.DivisionId,SA.RollNo
END
  
	
END
GO
PRINT N'Altering [sStudent].[pStudentFullProfileGet]...';


GO

ALTER PROCEDURE [sStudent].[pStudentFullProfileGet]
	 
	 @rBatchId int,
	 @rStudentId bigint,
	 @rReportId int=0,
	 @rOrgId int,
	 @rStrCode nvarchar(max)='',
	 @rClassId int=0,
	 @rDivisionId int=0,
	 @rFromRollNo int=0,
	 @rToRollNo int=0,
	 @rStatusId int=0,
	 @rClassStatusId int=0,
	 @rDateOfBirth int=0,
	 @rDepartmentId int=0,
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='',
	 @rOrgGroupBatchId int,
	 @rFromAdmissionDate date = '',
	 @rToAdmissionDate date = ''
	 
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
	
	DECLARE @lAcademicId bigint
	SELECT @lAcademicId = Id from sStudent.tAcademic Where StudentId = @rStudentId AND BatchId = @rBatchId
	
	SELECT 
			--Academic
			@rBuilder1 As Builder1,
			SA.StudentId AS Id,
			--SA.FirstName + ' ' + ISNULL(SA.MiddleName,'') + ' ' + 	SA.LastName AS StudentName,
			SA.Name AS StudentName,
			SA.FirstName as FirstName,
			SA.MiddleName as MiddleName,
			SA.LastName as LastName,
			SA.Batch AS AcademicYear,
			ISNULL(SA.Code,' - ') AS Code,
			SA.ClassDivision AS ClassDiv,			
			SA.RollNo,
			ISNULL(SM.Title,'-') AS House,
			--Other
			CASE WHEN @rReportId=0 THEN ISNULL(SA.DateOfBirth,'0001/01/01')  
			WHEN @rReportId=1 THEN  SA.DateOfBirth END  AS DateOfBirth,
			ISNULL(SA.BirthTaluka,'') AS BirthTaluka,
			ISNULL(SA.BirthPlace,'') AS BirthPlace,	
			ISNULL(SA.BirthDistrict,'') AS BirthDistrict,
			ISNULL(SA.BirthDateInWord,'') AS BirthDateInWord,                           
			ISNULL(SA.Gender,'') AS Gender,
			ISNULL(SA.Religion,'') AS Religion,
			--Admission			
			ISNULL(SA.AdmissionStandard,'') AS AdmissionStandard,
			--ISNULL(SA.AdmissionDate,'0001/01/01') AS AdmissionDate,
			CASE WHEN @rReportId=0 THEN ISNULL(SA.AdmissionDate,'0001/01/01')
			WHEN @rReportId=1 THEN  SA.AdmissionDate END AS AdmissionDate,
	
			ISNULL(SA.PreviousSchool,'') AS PreviousSchool,
			ISNULL(SA.AdmissionCategory,'') AS StudentAdmissionCategory,
			CASE WHEN @rReportId=0 THEN ISNULL(SA.LeftDate,'0001/01/01')
			WHEN @rReportId=1 THEN  SA.LeftDate END AS LeftDate,
						 
			ISNULL(SA.LeftStandard,'') AS LeftStandard,
			--ISNULL(SA.InactiveDate,'0001/01/01') AS InactiveDate,
			CASE WHEN @rReportId=0 THEN ISNULL(SA.InactiveDate,'0001/01/01')
			WHEN @rReportId=1 THEN  SA.InactiveDate END AS InactiveDate,		
			ISNULL(SA.LCNumber,'') AS LCNumber,
			--ISNULL(SA.LCDate,'0001/01/01') AS LCDate,
			 CASE WHEN @rReportId=0 THEN ISNULL(SA.LCDate,'0001/01/01')
			WHEN @rReportId=1 THEN  SA.LCDate END AS LCDate,
			--Communication
			ISNULL(SA.PresentStreetone,'') + ' ' + ISNULL(SA.PresentStreetTwo,'') + ' ' + ISNULL(SA.PresentStreetThree,'') AS PresentAddress,
			ISNULL(SA.PresentCity,'') AS PresentCity,
			ISNULL(SA.PresentState,'') AS PresentState,
			ISNULL(SA.PresentCountry,'') AS PresentCountry,
			ISNULL(SA.PresentZipCode,'') AS PresentZipCode,
			ISNULL(SA.PresentContactNo,'') AS PresentContactNo,
			
			ISNULL(SA.EmergencyStreetOne,'') + ' ' + ISNULL(SA.EmergencyStreetTwo,'') + ' ' + ISNULL(SA.EmergencyStreetThree,'') AS EmergencyAddress,
			ISNULL(SA.EmergencyCity,'') AS EmergencyCity,
			ISNULL(SA.EmergencyState,'') AS EmergencyState,
			ISNULL(SA.EmergencyCountry,'') AS EmergencyCountry,
			ISNULL(SA.EmergencyZipCode,'') AS EmergencyZipCode,
			ISNULL(SA.EmergencyContactNo,'') AS EmergencyContactNo,
			
			ISNULL(SA.PermanentStreetOne,'') + ' ' + ISNULL(SA.PermanentStreetTwo,'') + ' ' + ISNULL(SA.PermanentStreetThree,'') AS PermanentAddress,
			ISNULL(SA.PermanentCity,'') AS PermanentCity,
			ISNULL(SA.PermanentState,'') AS PermanentState,
			ISNULL(SA.PermanentCountry,'') AS PermanentCountry,
			ISNULL(SA.PermanentZipCode,'') AS PermanentZipCode,
			ISNULL(SA.PermanentContactNo,'') AS PermanentContactNo,
			
			--Parent Information
			ISNULL(SF.FatherName,'') AS FatherName,
			ISNULL(SF.FatherOccupation,'') AS FatherOccupation,
			ISNULL(SF.FatherQualification,'') AS FatherQualification,
			ISNULL(SF.FatherContactNo,'') AS FatherContactNo,
			ISNULL(SF.FatherMail,'') AS FatherMail,
			ISNULL(SF.FatherOfficeAddress,'') AS FatherOfficeAddress,
			ISNULL(SF.FatherDesignation,'') AS FatherDesignation,
			ISNULL(SF.FatherOrganization,'') AS FatherOrganization,
			ISNULL(SF.FatherIncome,'') AS FatherIncome,

			ISNULL(SF.MotherName,'') AS MotherName,
			ISNULL(SF.MotherOccupation,'') AS MotherOccupation,
			ISNULL(SF.MotherQualification,'') AS MotherQualification,
			ISNULL(SF.MotherContactNo,'') AS MotherContactNo,
			ISNULL(SF.MotherMail,'') AS MotherMail,
			ISNULL(SF.MotherOfficeAddress,'') AS MotherOfficeAddress,
			ISNULL(SF.MotherDesignation,'') AS MotherDesignation,
			ISNULL(SF.MotherOrganization,'') AS MotherOrganization,
			ISNULL(SF.MotherIncome,'') AS MotherIncome,

			ISNULL(SF.RelationshipName,'') AS RelationShip,
			ISNULL(SF.RelativeName,'') AS RelativeName,
			ISNULL(SF.RelativeOccupation,'') AS RelativeOccupation,
			ISNULL(SF.RelativeQualification,'') AS RelativeQualification,
			ISNULL(SF.RelativeContactNo,'') AS RelativeContactNo,
			ISNULL(SF.RelativeMail,'') AS RelativeMail,
			ISNULL(SF.RelativeOfficeAddress,'') AS RelativeOfficeAddress,
			ISNULL(SF.RelativeDesignation,'') AS RelativeDesignation,
			ISNULL(SF.RelativeOrganization,'') AS RelativeOrganization,
			ISNULL(SF.RelativeIncome,'') AS RelativeIncome,
			
			--Health Information
			ISNULL(SA.BloodGroup,'') AS BloodGroup,
			ISNULL(SH.IdentificationMark1,'')+' '+ISNULL(SH.IdentificationMark2,'') as IdentificationMark,
			
			ISNULL(SH.FamilyDoctorName,'') AS FamilyDoctorName,
			ISNULL(SH.FamilyDoctorContactNo,'') AS FamilyDoctorContactNo,
			
			ISNULL(SH.IsPysicalDeformity,0) AS IsPysicalDeformity,
			ISNULL(SH.PysicalDeformityRemark,'') AS PysicalDeformityRemark,
			ISNULL(SH.IsMajorIllness,0) AS IsMajorIllness,
			ISNULL(SH.MajorIllnessRemark,'') As MajorIllnessRemark,
			ISNULL(SH.IsAllergy,0) AS IsAllergy,
			ISNULL(SH.AllergyRemark,'') As AllergyRemark,
			ISNULL(SH.IsPastHistory,0) As IsPastHistory ,
			ISNULL(SH.PastHistoryRemark,'') As PastHistoryRemark,
			--Hostel
			ISNULL(RM.Title,'') AS RoomNo,			
			ISNULL(HM.Title,'') AS Hostel,
			ISNULL(EMW.FirstName,'')+' '+ISNULL(EMW.LastName,'') AS WardenName,
			ISNULL(ECW.PhoneNoCompany,'') As WardenPhoneNo,
			ISNULL(ECW.ExtensionNo,'') AS WardenExtNo,
			ISNULL(ECW.MobileNumber,'') AS WardenMobileNo,
			ISNULL(EMA.FirstName,'')+' '+ISNULL(EMA.LastName,'') AS AssignedRoomBy,	
			ISNULL(ECA.PhoneNoCompany,'') AS AssignedRoomByPhoneNo,
			ISNULL(ECA.ExtensionNo,'') AS AssignedRoomByExtNo,
			ISNULL(ECA.MobileNumber,'') AS AssignedRoomByMobileNo,
			--Notification Details
			ISNULL(SA.ParentEmail,'') AS ParentEmail,
			ISNULL(SA.ParentContactNo,'') As ParentContactNo,
			ISNULL(SA.StudentEmail,'') AS StudentEmail,
			ISNULL(SA.StudentContactNo,'') AS StudentContactNo,
					
	   	    --ISNULL(SA.StudentPhoto, CONVERT(VARBINARY(MAX), 0))AS StudentPhoto,
	   	   -- ISNULL(SA.FatherPhoto, CONVERT(VARBINARY(MAX), 0)) AS FatherPhoto,
	   	   -- ISNULL(SA.MotherPhoto, CONVERT(VARBINARY(MAX), 0)) AS MotherPhoto,
	   	    --ISNULL(SA.RelativePhoto, CONVERT(VARBINARY(MAX), 0)) AS RelativePhoto,
	   	   CASE WHEN @rReportId=0
			THEN ISNULL(SA.StudentPhoto, CONVERT(VARBINARY(MAX), 0))
			WHEN @rReportId=1
			THEN ISNULL(SA.StudentPhoto, CONVERT(VARBINARY(MAX), ''))
			END AS StudentPhoto,
			
			CASE WHEN @rReportId=0
			THEN ISNULL(SA.MotherPhoto, CONVERT(VARBINARY(MAX), 0))
			WHEN @rReportId=1
			THEN ISNULL(SA.MotherPhoto, CONVERT(VARBINARY(MAX), ''))
			END AS MotherPhoto,
			
			CASE WHEN @rReportId=0
			THEN ISNULL(SA.FatherPhoto, CONVERT(VARBINARY(MAX), 0))
			WHEN @rReportId=1
			THEN ISNULL(SA.FatherPhoto, CONVERT(VARBINARY(MAX), ''))
			END AS FatherPhoto,
			
			CASE WHEN @rReportId=0
			THEN ISNULL(SA.RelativePhoto, CONVERT(VARBINARY(MAX), 0))
			WHEN @rReportId=1
			THEN ISNULL(SA.RelativePhoto, CONVERT(VARBINARY(MAX), ''))
			END AS RelativePhoto,
		   -- Transport Details
		    A.VehicleName AS VehicleName,
		    A.VehicleRegistrationNumber AS VehicleRegistrationNumber,
		    A.TypeOfVehicle AS TypeOfVehicle,
		    ISNULL(A.BusRoute,'') AS BusRoute,
		    A.DriverName,
		    A.DriverMobileNo,
		    A.ConductorName,
		    A.ConductorMobileNo,
		    ISNULL(A.BusRouteDestination,'') AS BusRouteDestination,
		    
		    A.DropVehicleName AS DropVehicleName,
		    A.DropVehicleRegistrationNumber AS DropVehicleRegistrationNumber,
		    A.DropTypeOfVehicle AS DropTypeOfVehicle,
		    ISNULL(A.DropRoute,'') AS DropRoute,
		    A.DropRouteDriverName AS DropRouteDriverName,
		    A.DropRouteDriverMobileNo AS DropRouteDriverMobileNo,
		    A.DropRouteConductorName AS DropRouteConductorName,
		    A.DropRouteConductorMobileNo AS DropRouteConductorMobileNo,
		    ISNULL(A.DropDestination,'') AS DropDestination,
		    
		    --ClassTeacher Details
		    ISNULL(EMT.Id,0) AS TeacherId,
		    EMT.FirstName+' '+EMT.MiddleName+' '+EMT.LastName AS TeacherFullName,
		    EDM.Title AS TeacherDesignation,
		    EPD.Qualification AS TeacherQualification,
		    ISNULL(EI.EmployeePhoto, CONVERT(VARBINARY(MAX), 0)) AS TeacherPhoto,
		    ISNULL(DF.IsDisplayFamilyDetail,0) AS IsDisplayFamilyDetail,
		    ISNULL(DF.IsDisplaySiblingDetail,0) AS IsDisplaySiblingDetail,
		    ISNULL(DF.IsDisplayPassportDetail,0) AS IsDisplayPassportDetail,
		    ISNULL(DF.IsDisplayBankDetail,0) AS IsDisplayBankDetail,
		    ISNULL(DF.IsDisplayCBSEREGDetail,0) AS IsDisplayCBSEREGDetail,
		    ISNULL(DF.IsDisplayCollegeDetail,0) AS IsDisplayCollegeDetail,
		    ISNULL(DF.IsDisplayGOVREGNoDetail,0) AS IsDisplayGOVREGNoDetail,
		    ISNULL(DF.IsDisplayHealthDetail,0) AS IsDisplayHealthDetail,
		    ISNULL(DF.IsDisplayTransportDetail,0) AS IsDisplayTransportDetail,
		    ISNULL(DF.IsDisplayHostelDetail,0) AS IsDisplayHostelDetail,
		    ISNULL(DF.IsDisplayClubDetail,0) AS IsDisplayClubDetail,
		    
		    ISNULL(DF.IsDisplaySSCResultDDetail,0) AS IsDisplaySSCResultDDetail,
		    ISNULL(DF.IsDisplayHSCResultDetail,0) AS IsDisplayHSCResultDetail,
		    ISNULL(DF.IsDisplayJeeDetail,0) AS IsDisplayJeeDetail,
		    ISNULL(DF.IsDisplayDiplomaDetail,0) AS IsDisplayDiplomaDetail,
			ISNULL(DF.IsDisplayClassTeacherDetail,0) AS IsDisplayClassTeacherDetail,
		    --Sibling Detail
		    isnull(SS.SiblingName1,'') AS SiblingName1,
	        ISNULL (SS.SiblingInstitue1,'') AS SiblingInstitue1,
	        ISNULL(SS.SiblingClass1,'')AS SiblingClass1,
	        ISNULL(SS.SiblingAge1,'')AS SiblingAge1,
	        ISNULL(SS.SiblingRelation1,'')AS SiblingRelation1,
	        isnull(SS.SiblingName2,'') AS SiblingName2,
	        ISNULL(SS.SiblingInstitue2,'')AS SiblingInstitue2,
	        ISNULL(SS.SiblingClass2,'')AS SiblingClass2,
	        ISNULL(SS.SiblingAge2,'') AS SiblingAge2,
	        ISNULL(SS.SiblingRelation2,'')AS SiblingRelation2,
	        isnull(SS.SiblingName3,'') AS SiblingName3,
	        ISNULL( SS.SiblingInstitue3,'')AS SiblingInstitue3,
	        ISNULL(SS.SiblingClass3,'')AS SiblingClass3,
	        ISNULL(SS.SiblingAge3,'')AS SiblingAge3,
	        ISNULL(SS.SiblingRelation3,'')AS SiblingRelation3,
	        ISNULL(SAD.BankAccountNumber,'')AS BankAccountNumber,
	        ISNULL(SAD.BankName,'')AS BankName,
	        ISNULL(SAD.BankBranch,'') AS BankBranch,
	        ISNULL(SAD.BankIFSCCode,'')AS BankIFSCCode,
	        ISNULL(SAD.Class9BoardRegistrationNumber,'') AS Class9BoardRegistrationNumber,
	        ISNULL(SAD.Class11BoardRegistrationNumber,'')AS Class11BoardRegistrationNumber,
	        ISNULL(SAD.PassportNumber,'')AS PassportNumber, 
	        ISNULL(SAD.PassportType,'') AS PassportType,
	       ISNULL( SAD.PassportCountryCode,'') AS PassportCountryCode,
	        CASE WHEN @rReportId=0 THEN ISNULL(SAD.PassportIssueDate,'0001/01/01')
			WHEN @rReportId=1 THEN  SAD.PassportIssueDate END AS PassportIssueDate,
			CASE WHEN @rReportId=0 THEN ISNULL(SAD.PassportExpiryDate,'0001/01/01')
			WHEN @rReportId=1 THEN  SAD.PassportExpiryDate END AS PassportExpiryDate,
	        ISNULL(SA.UIDNumber,'')AS UIDNumber,
	        ISNULL(SA.AdhaarNumber,'') AS AdhaarNumber,
	       ISNull(SA.StatusId,0) AS StatusId,
	       ISNUll(SA.IsTransfer,0)AS IsTransfer,
	       ISNULL(SA.TransferFrom,'') AS TransferFrom,
	       ISNULL(SA.CertificateName,'') AS CertificateName,
	       ISNUll(SA.IsTFWS,0)AS IsTFWS,
	       ISNUll(SA.IsCertificateHolder,0)AS IsCertificateHolder,
	       ISNULL(CD.SSCBoard,'') AS SSCBoard,
	       ISNULL(CD.SSCSchool,'') AS SSCSchool,
	       ISNULL(CD.SSCPassingYear,'') AS SSCPassingYear,
	       ISNULL(CD.SSCObtainMarks,0) AS SSCObtainMarks,
	       ISNULL(CD.SSCOutOfMarks,0) AS SSCOutOfMarks,
	       ISNULL(CD.SSCPercentage,0) AS SSCPercentage,
	       ISNULL(CD.SSCMathMarks,0) AS SSCMathMarks,
	       ISNULL(CD.SSCMathOutOfMarks,0) AS SSCMathOutOfMarks,
	       ISNULL(CD.SSCPercentile,0) AS SSCPercentile,
	       ISNULL(CD.SSCGrade,0) AS SSCGrade,
	       ISNULL(CD.HSCBoard,'') AS HSCBoard,
	       ISNULL(CD.HSCSchool,'') AS HSCSchool,
	       ISNULL(CD.HSCPassingYear,0) AS HSCPassingYear,
	       ISNULL(CD.HSCObtainMarks,0) AS HSCObtainMarks,
	       ISNULL(CD.HSCOutOfMarks,0) AS HSCOutOfMarks,
	       ISNULL(CD.HSCPercentage,0) AS HSCPercentage,
	       ISNULL(CD.HSCPhysicsMarks,0) AS HSCPhysicsMarks,
	       ISNULL(CD.HSCPhysicsOutOfMarks,0) AS HSCPhysicsOutOfMarks,
	       ISNULL(CD.HSCChemistryMarks,0) AS HSCChemistryMarks,
	       ISNULL(CD.HSCChemistryOutOfMarks,0) AS HSCChemistryOutOfMarks,
	       ISNULL(CD.HSCMathMarks,0) AS HSCMathMarks,
	       ISNULL(CD.HSCMathOutOfMarks,0) AS HSCMathOutOfMarks,
	       ISNULL(CD.HSCBiologyMarks,0) AS HSCBiologyMarks,
	       ISNULL(CD.HSCBiologyOutOfMarks,0) AS HSCBiologyOutOfMarks,
	       ISNULL(CD.PCMMarks,0) AS PCMMarks,
	       ISNULL(CD.PCBMarks,0) AS PCBMarks,
	       ISNULL(CD.JEERollNo,'') AS JEERollNo,
	       ISNULL(CD.JEEMeritNo,'') AS JEEMeritNo,
	       ISNULL(CD.JEEMeritMarks,0) AS JEEMeritMarks,
	       ISNULL(CD.JEEOutOfMarks,0) AS JEEOutOfMarks,
	       ISNULL(CD.DiplomaBoard,'') AS DiplomaBoard,
	       ISNULL(CD.DiplomaCollege,'') AS DiplomaCollege,
	       ISNULL(CD.DiplomaPassingYear,'') AS DiplomaPassingYear,
	       ISNULL(CD.DiplomaObtainMarks,0) AS DiplomaObtainMarks,
	       ISNULL(CD.DiplomaOutOfMarks,0) AS DiplomaOutOfMarks,
	       ISNULL(CD.DiplomaPercentage,0) AS DiplomaPercentage,
	       ISNULL(CD.ApplicationNo,'') AS ApplicationNo,
	       ISNULL(CD.AdmissionRound,0) AS AdmissionRound,
	       ISNULL(CD.MaritalStatusId,0) AS MaritalStatusId,
	       ISNULL(MS.Title,'') AS MaritalStatus,
	       ISNULL(ACD.RepeatCount,1)AS RepeatCount,
	       ISNULL(SA.MotherTongue,'') As MotherTongue,
	       ISNULL(SA.FamilyCast,'') AS FamilyCast,
	      ISNULL(CM.Nationality,'') AS Nationality,
	       ISNULL(CT.Title,'') AS CasteCategory,
	       ISnull(SA.ClassName,'') AS ClassName ,
	       ISnull( SA.DivisionName,'') AS DivisionName,
	      ISNULL( SF.IsFatherExStudent,0) AS IsFatherExStudent,
	       ISnull(SF.FatherPassOutYear,'') AS FatherPassOutYear,
	       Isnull(SF.IsMotherExStudent,0) AS IsMotherExStudent,
	       Isnull(SF.MotherPassOutYear,'') AS MotherPassOutYear,
	       ISNULL(SF.IsRelativeExStudent,0) AS IsRelativeExStudent,
	       ISNULL(SF.RelativePassOutYear,'') AS RelativePassOutYear,
	       ISNULL(Sa.PresentDistanceFromSchool,0) AS PresentDistanceFromSchool,
	        SA.StudentId,
	        SA.ClassId,
	        SA.DivisionId,
	        SA.BirthState,
	        SA.BirthCountry,
	         ISNULL(SA.PreviousStandard,'')AS PreviousStandard
	        ,ISNULL(CGG.Title,'') AS CustomGroup
			,ISNULL(SGM.Title,'') As StudentGroup
			,ISNULL(SOGM.Title,'') As StudentOtherGroup
			,ISNULL([sStudent].[fAssignedClubGet](@lAcademicId),'') AS ClubName
			,ISNULL([sStudent].[fAssignedCustomTagGet](@lAcademicId),'') AS CustomTag 
	        ,SA.ClassStatusId
	        ,SA.ClassStatusName
	        ,PDCM.Title As PhysicalDisabilityCategory
			,ISNULL(SAM.PreviousLCNumber,'') AS PreviousLCNumber
			,ISNULL(SAM.PreviousLCDate,'') AS PreviousLCDate,
			ISNULL(SAM.AdmissionNumber,'') AS  AdmissionNumber,
			ISNULL(SAM.AdmissionFormNumber,'') AS  AdmissionFormNumber,
			SA.SUId,
	       --[sHostel].[fHostelWardenGet](HM.Id) As WardenName
		   MS.Title AS MaritalStatus,
		   SA.FamilySubCast,
		   SA.ReferenceRemark 

  FROM 
           sStudent.vStudentAllDetail SA
          -- LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId = SA.StudentId
           LEFT JOIN sStudent.tStudentHealth SH ON SA.StudentId=SH.StudentId
           LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId = SA.StudentId 
          -- LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId = SA.StudentId
           LEFT JOIN sActivity.tHouseMaster SM ON SM.ID = SA.HouseId
           LEFT JOIN sHostel.tAssignRoom AR ON AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003  AND ((AR.OrgGroupBatchId=@rOrgGroupBatchId) OR(@rOrgGroupBatchId=0))
           LEFT JOIN sHostel.tRoomMaster RM ON RM.Id=AR.RoomId
           LEFT JOIN sCommon.tPhysicalDisabilityCategoryMaster PDCM ON PDCM.Id = SH.PhysicalDisabilityCategoryId
           LEFT JOIN sHostel.tHostelMaster HM ON HM.Id=RM.HostelId   
            LEFT JOIN
            (
		   SELECT 
		   employeeId, 
		   HostelId,   
		   ROW_NUMBER() OVER (PARTITION BY HostelId ORDER By HostelId ) as ROWNo 		   
		 
		   FROM sHostel.tHostelwarden 
            )  HW ON HW.HostelId=HM.Id AND RowNo = 1       
           --LEFT JOIN sHostel.tHostelWarden HW ON HW.HostelId=HM.Id
           LEFT JOIN sHrm.tEmployeeMaster EMW ON HW.EmployeeId=EMW.Id AND  ISNULL(EMW.IsOtherUser,0) = 0
           LEFT JOIN sHrm.tEmployeeMaster EMA ON RM.AssignedEmployeeId=EMA.Id AND  ISNULL(EMA.IsOtherUser,0) = 0
           LEFT JOIN sHrm.tEmployeeCommunications ECW ON EMW.Id=ECW.EmployeeId 
           LEFT JOIN sHrm.tEmployeeCommunications ECA ON  EMA.Id=ECA.EmployeeId
           LEFT JOIN 
           ( SElect AR1.SourceId,
           VM.Title AS VehicleName,
		    VM.RegistrationNumber AS VehicleRegistrationNumber,
		    TV.Title AS TypeOfVehicle,
		    ISNULL(BRM.Title,'') AS BusRoute,
		    BRM.DriverName,
		    BRM.DriverMobileNo,
		    BRM.ConductorName,
		    BRM.ConductorMobileNo,
		    ISNULL(BRDM.Title,'') AS BusRouteDestination,
		    VM.Title AS DropVehicleName,
		    VM.RegistrationNumber AS DropVehicleRegistrationNumber,
		    TV1.Title AS DropTypeOfVehicle,
		    ISNULL(BRM1.Title,'') AS DropRoute,
		    BRM1.DriverName AS DropRouteDriverName,
		    BRM1.DriverMobileNo AS DropRouteDriverMobileNo,
		    BRM1.ConductorName AS DropRouteConductorName,
		    BRM1.ConductorMobileNo AS DropRouteConductorMobileNo,
		    ISNULL(BRDM1.Title,'') AS DropDestination
		      FROM
             sTransport.tAssignRoute AR1   
           INNER JOIN sTransport.tBusRouteDestinationMaster BRDM ON BRDM.Id=AR1.PickupDestinationId AND AR1.SourceTypeId=2003
           INNER JOIN sTransport.tBusRouteMaster BRM ON BRM.Id=BRDM.BusRouteId AND ((BRM.OrgGroupBatchId=@rOrgGroupBatchId) OR(@rOrgGroupBatchId=0))
           LEFT JOIN sTransport.tVehicleMaster VM ON VM.Id=BRM.VehicleId
           LEFT JOIN sTransport.tVehicleTypeMaster TV ON TV.Id = VM.VehicleTypeId
           LEFT JOIN sTransport.tBusRouteDestinationMaster BRDM1 ON BRDM1.Id=AR1.DropDestinationId
           LEFT JOIN sTransport.tBusRouteMaster BRM1 ON BRM1.Id=BRDM1.BusRouteId AND ((BRM1.OrgGroupBatchId=@rOrgGroupBatchId) OR(@rOrgGroupBatchId=0))
           LEFT JOIN sTransport.tVehicleMaster VM1 ON VM1.Id=BRM1.VehicleId
           LEFT JOIN sTransport.tVehicleTypeMaster TV1 ON TV1.Id = VM1.VehicleTypeId) A ON A.SourceId=SA.StudentId
           LEFT JOIN sSetup.tDivisionMaster DM ON  DM.Id=SA.DivisionId
           LEFT JOIN sHrm.tEmployeeMaster EMT ON EMT.Id=DM.InchargeEmployeeId AND  ISNULL(EMT.IsOtherUser,0) = 0
           LEFT JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EMT.Id
           LEFT JOIN sHrm.tEmployeeDesignationMaster EDM ON EDM.Id=EJD.EmployeeDesignationId
           LEFT JOIN sHrm.tEmployeePersonalDetail EPD ON EPD.EmployeeId=EMT.Id
           LEFT JOIN sHrm.tEmployeeImages EI ON EI.EmployeeId=EMT.Id
           LEFT JOIN sStudent.tStudentSibling  SS ON SS.StudentId=SA.StudentId 
           LEFT JOIN sStudent.tStudentAdditional  SAD ON SAD.StudentId=SA.StudentId 
           LEFT JOIN sStudent.tCollegeDetail  CD ON CD.StudentId=SA.StudentId 
           LEFT JOIN sStudent.tAcademicDetail  ACD ON ACD.AcademicId=SA.AcademicId 
           LEFT JOIN sCommon.tMaritalStatusMaster  MS ON MS.Id=CD.MaritalStatusId
           LEFT JOIN sConfig.fDisplayFieldGet(@rOrgId) AS DF ON DF.OrgId=SA.OrgId
           LEFT JOIN sCommon.tCastCategoryMaster CT ON CT.Id = SA.CastCategoryId
           LEFT JOIN sCommon.tCountryMaster CM ON CM.Id=SA.NationalityId
           INNER JOIN sSetup.tBatchClass BC ON BC.ClassID =  SA.ClassID and BC.BatchId= @rBatchId
           LEFT JOIN sCommunication.tCustomGroupMember CGM ON CGM.SourceId = SA.StudentId AND CGM.SourceTypeId = 2003
           LEFT JOIN sCommunication.tCustomGroup CGG ON CGG.Id = CGM.CustomGroupId
           LEFT JOIN sStudent.tStudentMaster SMM ON SMM.Id = SA.StudentId
           LEFT JOIN sStudent.tStudentGroupMaster SGM ON SGM.Id = SMM.StudentGroupId
           LEFT JOIN sStudent.tStudentOtherGroupMaster SOGM ON SOGM.Id = SMM.StudentOtherGroupId
		   LEFT JOIN sStudent.tStudentAdmission SAM ON SAM.StudentId = SA.StudentId
  WHERE 
			((SA.StudentId=@rStudentId)OR(@rStudentId=0))
			AND((SA.BatchId=@rBatchId) OR(@rBatchId=0))
			AND (ISNULL(SA.Code,0) IN( SELECT cast(item as nvarchar(20)) FROM  sCommon.fnsplit(@rStrCode,',')) OR @rStrCode='') 
			AND ((SA.ClassId=@rClassId) OR (@rClassId=0))
			AND ((SA.DivisionId=@rDivisionId) OR (@rDivisionId=0))
			AND ((SA.StudentId=@rStudentId) OR (@rStudentId=0))
			AND ((SA.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
			AND ((SA.RollNo <= @rToRollNo) OR (@rToRollNo=0))
			AND ((SA.StatusId=@rStatusId)OR(@rStatusId=0))
			AND ((SA.ClassStatusId=@rClassStatusId)OR(@rClassStatusId=0))
			AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
			AND ((SA.OrgGroupBatchId=@rOrgGroupBatchId) OR(@rOrgGroupBatchId=0))
			AND ((SA.AdmissionDate >= @rFromAdmissionDate) OR (ISNULL(@rFromAdmissionDate,'') = ''))
			AND ((SA.AdmissionDate <= @rToAdmissionDate) OR (ISNULL(@rToAdmissionDate,'') = ''))
			--AND(SA.OrgId=@rOrgId)
			
END
GO
PRINT N'Altering [sStudent].[pStudentGenerateReport]...';


GO

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

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

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


GO
ALTER PROCEDURE [sStudent].[pStudentVerificationGet]
	 
	@rClassId int=0,
	@rDivisionId int=0,
	@rRollNo int=0,
	@rOrgId int,
	--@rNumber bigint,
	@rCode nvarchar(20) = '',
	@rStatusId smallint=0,
	@rFirstName nvarchar(100)='',
	@rLastName nvarchar(100)='',
	@rBatchId int = 0,
	@rOrgGroupBatchId int = 0,
	@rDepartmentId int,
	@rOrgGroupId smallint,
	@rToRollNo int=0,
	@rFromCode nvarchar(20)='',
	@rToCode nvarchar(20)='',
	@rSpecificCode nvarchar(max)='',	
	@rOrderByTypeId int  = 0
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON			 

BEGIN 	 

	BEGIN
		SET @rCode= sCommon.fSearchStringGet(@rCode)
		SET @rFirstName = sCommon.fSearchStringGet(@rFirstName)
		SET @rLastName = sCommon.fSearchStringGet(@rLastName)
	END
 
	SELECT 
			SA.AcademicId,
			SA.StudentId,
			SA.ClassId,
			Sa.MiddleName,
			ISNULL(SA.AdmissionDate,'')As AdmissionDate,
			SA.PreviousSchool,
			ISNULL(SA.DateOfBirth,'') As DateOfBirth,
			SA.BirthPlace,
			SA.Gender,
			SA.FamilyCast,
			SA.CastCatagory AS CasteCategory,
			SA.MotherTongue,
			SA.Nationality,
			Sa.FatherName,
			SA.FatherContactNo,
			SA.Mothername,
			SA.MotherContactNo,
			SA.PresentStreetOne,
			SA.PresentStreetTwo,
			SA.PresentStreetThree,
			ISNULL(SA.StudentContactNo,'')As StudentContactNo,
			SA.UIDNumber,
			SA.AdhaarNumber,
			SA.BankBranch,
			SA.BankAccountNumber,
			SA.BankName,
			SA.BankIFSCCode,
			SA.DepartmentId,
			SA.FirstName,
			SA.LastName,
			SA.Name,
			SA.Code,
			SA.ADMISSIONStandardId, 
			SA.DivisionId,
			SA.DivisionName,
			ISNULL(SA.Number,0) AS Number,
			SA.RollNo,
			SA.StatusId,
			--SA.StatusName,
			SA.OrgId,
			--SA.Age,
			ISNULL(SA.AdmissionCategoryId,0) AS AdmissionCategoryId,
			SA.Religion,
			SA.StudentEmail,
			SA.Name,
			(select  Title  from sSetup.tClassMaster where OrgId=@rOrgId AND id=SA.ADMISSIONStandardId  ) As AdmissionStandard,
			SA.ClassName,
			SA.BirthState,
			SA.BirthCountry,
			SA.BirthTaluka,
			SA.BirthDistrict,
			SA.BankAccountHolderName
  FROM 
            sStudent.vStudentVerification SA  
  WHERE 
			((SA.ClassId=@rClassId)OR(@rClassId=0))
			AND((SA.DivisionId=@rDivisionId)OR(@rDivisionId=0))
			AND((SA.Code like @rCode) OR (ISNULL(@rCode,'') = '')) 
			AND((SA.Code >= @rFromCode) AND (SA.Code <= @rToCode) OR (ISNULL(@rFromCode,'') = '' OR ISNULL(@rToCode,'') = '')) 
			AND(SA.Code IN (SELECT CONVERT(nvarchar,item) from sCommon.fnSplit(@rSpecificCode,',')) OR ISNULL(@rSpecificCode,'') = '') 
			AND((SA.FirstName like @rFirstName) OR (ISNULL(@rFirstName,'') = '')) 
			AND((SA.LastName like @rLastName) OR (ISNULL(@rLastName,'') = '')) 
			AND((SA.StatusId=@rStatusId)OR(@rStatusId=0))	
			AND(SA.OrgId=@rOrgId OR @rOrgId = 0)
			AND (OrgGroupBatchId = @rOrgGroupBatchId	or @rOrgGroupBatchId = 0)	
			AND(SA.BatchId=@rBatchId or @rBatchId = 0)
			AND(SA.DepartmentId=@rDepartmentId or @rDepartmentId = 0)
			and ((sa.RollNO>=@rRollNO)OR(@rRollNo=0))
			and ((sa.RollNO<=@rToRollNo)OR(@rToRollNo=0))
			--AND((SA.Number=@rNumber)OR(@rNumber=0))	

--ORDER BY SA.ClassId,SA.DivisionId,SA.RollNo

ORDER by CASE WHEN @rOrderByTypeId = 1 then SA.FirstName 
			  WHEN @rOrderByTypeId = 2 then SA.LastName
			  WHEN @rOrderByTypeId = 4 then (CASE IsNumeric (SA.Code) WHEN 1 THEN Replicate (0, 100 - Len (SA.Code)) + SA.Code  ELSE SA.Code  END) END,		--add
		CASE WHEN @rOrderByTypeId = 3 then SA.RollNo END,
		CASE WHEN @rOrderByTypeId = 5 then SA.AdmissionDate END  
			  ,SA.ClassId, SA.DivisionId,SA.RollNo
 
END
GO
PRINT N'Altering [sStudent].[pSUIDGenerationGet]...';


GO
ALTER PROCEDURE [sStudent].[pSUIDGenerationGet]
	 
	 @rOrgGroupId smallint,
	 @rOrgId smallint,
	 @rDepartmentId int,
	 @rClassID int,
	 @rDivisionId int,
	 @rRecordStatusId smallint,
	 @rBatchId int=0,
	 @rOrderByTypeId smallint = 0
	 

	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
	SELECT 
			vSA.StudentId,
			vSA.OrgId,
			vSA.OrganizationName,
			VSA.DepartmentName,
			vSA.ClassName+' - '+vSA.DivisionName AS ClassDivisionName,
			vSA.RollNo,
			vSA.Code,
			ISNULL(vSA.SUId,'') AS SUID,
			vSA.Name,
			SA.AdmissionDate,
			GM.Title As Gender,
			(Select CM.Title from sSetup.tClassMaster CM WHere CM.Id=SA.AdmissionStandardId) AS AdmissionStandard,
			vSA.FirstName,
			vSA.LastName,
			SA.AdmissionDate,
			vSA.ClassID,
			vSA.AcademicId,
			vSA.DivisionId
			
	FROM 
			sStudent.vStudentAcademic vSA
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = vSA.OrgId
			INNER JOIN sStudent.tStudentAdmission SA ON SA.StudentId=vSA.StudentId
			INNER JOIN sStudent.tStudentOther SO ON So.StudentId=vSa.StudentId
			INNER JOIN sCommon.tGenderMaster GM ON Gm.Id=SO.GenderID
	WHERE 
			(OM.OrgGroupId = @rOrgGroupId)
			AND (vSA.OrgId=@rOrgId)
			AND (vSA.BatchId=@rBatchId)
			AND ((vSA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
			AND ((vSA.ClassId=@rClassId) OR (@rClassId=0))
			AND ((vSA.DivisionId=@rDivisionId) OR (@rDivisionId=0))
			AND ((vSA.RecordStatusId=@rRecordStatusId) OR (@rRecordStatusId=0))
			--ORDER BY OM.OrderIndex,vSA.DivisionOrder,vSA.RollNo

	ORDER by CASE WHEN @rOrderByTypeId = 1 then vSA.FirstName
				  WHEN @rOrderByTypeId = 2 then vSA.LastName
				  WHEN @rOrderByTypeId = 4 then (CASE ISNUMERIC(vSA.Code) WHEN 1 THEN REPLICATE(0 , 100 - LEN(vSA.Code)) + vSA.Code ELSE vSA.Code  END) END,	--add inner case
		CASE WHEN @rOrderByTypeId = 3 then vSA.RollNo END,
		CASE WHEN @rOrderByTypeId = 5 then SA.AdmissionDate END
			  ,OM.OrderIndex,vSA.DivisionOrder,vSA.RollNo
END
GO
PRINT N'Altering [sStudent].[pUploadStudentPhotoClassWise]...';


GO
ALTER PROCEDURE [sStudent].[pUploadStudentPhotoClassWise]
	@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,
    @rSUId nvarchar(50)='',
    @rUserId bigint=0,
    @rMultiCode nvarchar(max)='',
	@rOrderByTypeId int=0
	
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	 
		BEGIN
			SET @rCode= sCommon.fSearchStringGet(@rCode)
			SET @rFirstName = sCommon.fSearchStringGet(@rFirstName)
			SET @rLastName = sCommon.fSearchStringGet(@rLastName)
		END
	IF(@rRollNo IS NULL)
	BEGIN
	SELECT 
			SA.AcademicId,
			SA.StudentId,
			SA.FirstName,
			SA.LastName,
			SA.Name,
			SA.Code,
			SA.ClassId,
			SA.ClassName,
			SA.DivisionId,
			SA.DivisionName,
			ISNULL(SA.Number,0) AS Number,
			SA.RollNo,
			SA.StatusId,
			SA.StatusName,
			SA.OrgId,
			SA.SUId,
			ISNULL(SI.StudentPhoto, CONVERT(VARBINARY(MAX), 0)) AS StudentPhoto,
			ISNULL(SI.FatherPhoto, CONVERT(VARBINARY(MAX), 0)) AS FatherPhoto,
			ISNULL(SI.MotherPhoto, CONVERT(VARBINARY(MAX), 0)) AS MotherPhoto,
			ISNULL(SI.RelativePhoto, CONVERT(VARBINARY(MAX), 0)) AS RelativePhoto,
			ISNULL(SI.QRCode, CONVERT(VARBINARY(MAX),0)) AS QRCode
			
			
  FROM 
          sStudent.vStudentAcademic SA
       LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId=SA.StudentId
       INNER JOIN sSecurity.tUserAccess U ON U.SourceId = SA.DivisionId AND U.SourceTypeId=2005
             
  WHERE 
 
		((SA.ClassId=@rClassId)OR(@rClassId=0))
		AND((SA.DivisionId=@rDivisionId)OR(@rDivisionId=0))
		AND((SA.Code like @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)
		AND(SA.BatchId=@rBatchId)
		AND((SA.SUID = @rSUId) OR (ISNULL(@rSUId,'') = '')) 
		--AND((SA.Number=@rNumber)OR(@rNumber=0))	
		AND U.UserId = @rUserId
		AND (ISNULL(SA.Code,0) IN( SELECT cast(item as nvarchar(20)) FROM  sCommon.fnsplit(@rMultiCode,',')) OR @rMultiCode='')
ORDER BY CASE WHEN @rOrderByTypeId = 1 then SA.RollNo END,
		 CASE WHEN @rOrderByTypeId = 2 then (CASE ISNUMERIC(SA.Code) WHEN 1 THEN REPLICATE(0, 100 - LEN(SA.Code)) + SA.Code ELSE SA.Code END) END,
		 SA.ClassId,SA.DivisionId,SA.RollNo
END
ELSE
BEGIN
	SELECT 
			SA.AcademicId,
			SA.StudentId,
			SA.FirstName,
			SA.LastName,
			SA.Name,
			SA.Code,
			SA.ClassId,
			SA.ClassName,
			SA.DivisionId,
			SA.DivisionName,
			SA.Number,
			SA.RollNo,
			SA.StatusId,
			SA.StatusName,
			SA.OrgId,
			SA.SUId,
			ISNULL(SI.StudentPhoto, CONVERT(VARBINARY(MAX), 0)) AS StudentPhoto,
			ISNULL(SI.FatherPhoto, CONVERT(VARBINARY(MAX), 0)) AS FatherPhoto,
			ISNULL(SI.MotherPhoto, CONVERT(VARBINARY(MAX), 0)) AS MotherPhoto,
			ISNULL(SI.RelativePhoto, CONVERT(VARBINARY(MAX), 0)) AS RelativePhoto,
			ISNULL(SI.QRCode, CONVERT(VARBINARY(MAX),0)) AS QRCode
			
  FROM 
          sStudent.vStudentAcademic SA
       LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId=SA.StudentId
       INNER JOIN sSecurity.tUserAccess U ON U.SourceId = SA.DivisionId AND U.SourceTypeId=2005
  WHERE 
 
		((SA.ClassId=@rClassId)OR(@rClassId=0))
		AND((SA.DivisionId=@rDivisionId)OR(@rDivisionId=0))
		AND((SA.Code like @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)
		AND(SA.BatchId=@rBatchId)
		AND((SA.SUID = @rSUId) OR (ISNULL(@rSUId,'') = '')) 
		AND U.UserId = @rUserId
		AND (ISNULL(SA.Code,0) IN( SELECT cast(item as nvarchar(20)) FROM  sCommon.fnsplit(@rMultiCode,',')) OR @rMultiCode='')
		--AND((SA.Number=@rNumber)OR(@rNumber=0))	

ORDER BY CASE WHEN @rOrderByTypeId = 1 then SA.RollNo END,
		 CASE WHEN @rOrderByTypeId = 2 then (CASE ISNUMERIC(SA.Code) WHEN 1 THEN REPLICATE(0, 100 - LEN(SA.Code)) + SA.Code ELSE SA.Code END) END,
		 SA.ClassId,SA.DivisionId,SA.RollNo
END
  
	
END
GO
PRINT N'Altering [sTally].[pReceiptPostingGet]...';


GO

ALTER PROCEDURE [sTally].[pReceiptPostingGet]

	 @rOrgGroupBatchId int,
	 @rReceiptBookId int,
	 @rReceiptDate Date,
	 @rToReceiptDate Date,
	 @rPayTypeId int = 0,
	 @rCustomNarration nvarchar(max)='',
	 @rIsCustomNarration bit=0
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
	
	DECLARE @lTallyPostingType nVarchar(100)
	DECLARE @lOrgGroupId INT
	
	SELECT @lOrgGroupId = OrgGroupId from sSetup.tOrgGroupBatchMaster Where Id=@rOrgGroupBatchId
	
	SELECT @lTallyPostingType = CASE WHEN CS.ItemValue IS NULL THEN C.ItemValue ELSE CS.ItemValue END 
		FROM sConfig.tConfigurationMaster C
        INNER JOIN sConfig.tConfigurationLevelMaster CM ON CM.Id = C.ConfigurationLevelId
        LEFT JOIN sConfig.tConfigurationSetup CS ON CS.ConfigurationId = C.Id AND CS.SOURCEID= @lOrgGroupId
        WHERE  C.ItemKey = 'Tally.PostingType'
        
		
        IF @lTallyPostingType = 'FeeHeadWise' 
        BEGIN
			   SELECT	ReceiptDate,
						ISNULL(FHM.Title,'') AS FeeName,
						PM.Title AS PayType,
						Sum(FRD.Amount) AS Amount,
						Case when @rIsCustomNarration=1 then STUFF((SELECT distinct ','  +Replace(replace(
																					Replace(
																					replace(
																					Replace(
																					replace(
																					Replace(
																					replace(
																					Replace(
																					replace(
																					Replace(
																					replace(
																					Replace(
																					replace(
																					Replace(
																					replace(
																					replace(
																					@rCustomNarration,'[Class]',isnull(SM1.ClassName,'')
																					),'[Division]',Isnull(SM1.DivisionName,'')
																					),'[StudentsName]',isnull(SM1.Name,'')
																					), '[RollNumber]',isnull(convert(nvarchar(200),SM1.RollNo),'0')
																					),'[Batch]',isnull(SM1.BatchName,'')
																					), '[ReceiptNumber]', isnull(Convert(nvarchar(100),FR1.ReceiptNumber),'')
																					), '[ReceiptDate]',isnull(Convert(nvarchar(100),FR1.ReceiptDate),'')
																					), '[ReceiptAmount]',isnull(Convert(nvarchar(100),FR1.ReceiptAmount),'')
																					), '[ChequeNo]',isnull(Convert(nvarchar(100),FR1.ChequeNo),'')
																					),'[BankName]',isnull(FR1.BankName,'')
																					),'[FeeName]',isnull(FM1.Title,'')
																					), '[FeeAmount]',isnull(Convert(nvarchar(100),Sum(FRD.Amount)),'0.00')
																					),'[FeeHeadName]',ISNULL(FHM.Title,'')
																					), '[FeeHeadAmount]',isnull(Convert(nvarchar(100),Sum(FRD.Amount)),'0.00')
																					), '[CollectionGroupName]',isNull(CGM1.Title,'')
																					),'[ReceiptFromNumber]',isnull(Convert(nvarchar(10),(Select Min(ReceiptNumber) from sFee.tReceipt where   FR.ReceiptDate =ReceiptDate)),'')
																					), '[ReceiptToNumber]',isnull(Convert(nvarchar(10),(Select Max(ReceiptNumber) from sFee.tReceipt Where FR.ReceiptDate = ReceiptDate)),''))
						from sFee.tReceipt FR1  INNER JOIN sFee.tReceiptDetail FRD1 ON FR1.Id = FRD1.ReceiptId
						INNER JOIN sFee.tFeeSetup FS1 ON FS1.Id = FRD1.FeeSetupId 
						INNER JOIN sStudent.vStudentAcademic SM1 ON SM1.ACademicId = FR1.SourceID AND SM1.OrgGRoupBatchId = FR1.OrgGRoupBatchId 						
						INNER JOIN sFee.tFeeMaster FM1 ON FM1.Id = FS1.FeeId --AND FRD.ReceiptId=FRD1.ReceiptId
						LEFT JOIN sFee.tCollectionGroupMaster CGM1 ON CGM1.Id = FS1.CollectionGroupId
						INNER JOIN sFee.tFeeHeadMaster FHM1 ON FHM1.Id = FM1.FeeHeadId AND FHM1.Id=FHM.Id where  FR.ReceiptDate=FR1.ReceiptDate FOR XML PATH('')),1,1,'') else
						 'Receipt generated for Batch : ' + (Select Title from sSetup.tOrgGroupBatchMaster Where Id= @rOrgGroupBatchId) +
						' Receipt Date : ' +  Convert(nvarchar(10),ReceiptDate) + ' and Receipt Number From ' + Convert(nvarchar(10),(Select Min(ReceiptNumber) from sFee.tReceipt where   FR.ReceiptDate =ReceiptDate AND IsObsolete = 0 )) + ' -  ' + 
						Convert(nvarchar(10),(Select Max(ReceiptNumber) from sFee.tReceipt Where FR.ReceiptDate = ReceiptDate AND IsObsolete = 0)) end as Narration,						
						FR.PayTypeId AS PayTypeId, 
						FHM.Id AS FeeId,
						0 AS ReceiptId
				FROM sFee.tReceipt FR 
					INNER JOIN sFee.tReceiptDetail FRD ON FR.Id = FRD.ReceiptId
					INNER JOIN sFee.tFeeSetup FS ON FS.Id = FRD.FeeSetupId
					INNER JOIN sFee.tFeeMaster FM ON FM.Id = FS.FeeId
					INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id = FM.FeeHeadId
					INNER JOIN sFinanceCommon.tPayTypeMaster PM ON PM.Id = FR.PayTypeId
					WHERE	FR.ReceiptBookId = @rReceiptBookId 
							AND FR.IsObsolete = 0 
							AND FR.OrgGroupBatchId = @rOrgGroupBatchId
							AND FR.ReceiptDate >= @rReceiptDate AND FR.ReceiptDate <= @rToReceiptDate
							AND (FR.PayTypeId = @rPayTypeId OR @rPayTypeId = 0)
				group by ReceiptDate,FHM.Title,PM.Title,FHM.Id,FR.PayTypeId
				Order By ReceiptDate Desc
			END				
       ELSE IF @lTallyPostingType = 'FeeHeadWiseCustom' 
        BEGIN
			   SELECT	ReceiptDate,
						FR.Id AS FeeName,
						PM.Title AS PayType,
						Sum(FRD.Amount) AS Amount,
						Case when @rIsCustomNarration=1 then  STUFF((SELECT distinct ','  +Replace(replace(
																					Replace(
																					replace(
																					Replace(
																					replace(
																					Replace(
																					replace(
																					Replace(
																					replace(
																					Replace(
																					replace(
																					Replace(
																					replace(
																					Replace(
																					replace(
																					replace(
																					@rCustomNarration,'[Class]',isnull(SM1.ClassName,'')
																					),'[Division]',Isnull(SM1.DivisionName,'')
																					),'[StudentsName]',isnull(SM1.Name,'')
																					), '[RollNumber]',isnull(convert(nvarchar(200),SM1.RollNo),'0')
																					),'[Batch]',isnull(SM1.BatchName,'')
																					), '[ReceiptNumber]', isnull(Convert(nvarchar(100),FR1.ReceiptNumber),'')
																					), '[ReceiptDate]',isnull(Convert(nvarchar(100),FR1.ReceiptDate),'')
																					), '[ReceiptAmount]',isnull(Convert(nvarchar(100),FR1.ReceiptAmount),'')
																					), '[ChequeNo]',isnull(Convert(nvarchar(100),FR1.ChequeNo),'')
																					),'[BankName]',isnull(FR1.BankName,'')
																					),'[FeeName]',isnull(FM1.Title,'')
																					), '[FeeAmount]',isnull(Convert(nvarchar(100),Sum(FRD.Amount)),'0.00')
																					),'[FeeHeadName]',ISNULL(FHM1.Title,'')
																					), '[FeeHeadAmount]',isnull(Convert(nvarchar(100),Sum(FRD.Amount)),'0.00')
																					), '[CollectionGroupName]',isNull(CGM1.Title,'')
																					),'[ReceiptFromNumber]',isnull(Convert(nvarchar(10),(Select Min(ReceiptNumber) from sFee.tReceipt where   FR.ReceiptDate =ReceiptDate AND IsObsolete = 0)),'')
																					), '[ReceiptToNumber]',isnull(Convert(nvarchar(10),(Select Max(ReceiptNumber) from sFee.tReceipt Where FR.ReceiptDate = ReceiptDate AND IsObsolete = 0)),''))
						from sFee.tReceipt FR1  INNER JOIN sFee.tReceiptDetail FRD1 ON FR1.Id = FRD1.ReceiptId
						INNER JOIN sFee.tFeeSetup FS1 ON FS1.Id = FRD1.FeeSetupId 
						INNER JOIN sStudent.vStudentAcademic SM1 ON SM1.ACademicId = FR1.SourceID AND SM1.OrgGRoupBatchId = FR1.OrgGRoupBatchId 						
						INNER JOIN sFee.tFeeMaster FM1 ON FM1.Id = FS1.FeeId --AND FRD.ReceiptId=FRD1.ReceiptId
						LEFT JOIN sFee.tCollectionGroupMaster CGM1 ON CGM1.Id = FS1.CollectionGroupId
						INNER JOIN sFee.tFeeHeadMaster FHM1 ON FHM1.Id = FM1.FeeHeadId  where   FR.ReceiptDate=FR1.ReceiptDate AND FR.Id=FR1.Id AND FR1.IsObsolete = 0  FOR XML PATH('')),1,1,'') else
						SM.Name + '(' + ClassName + ':' + DivisionName + ') ' + ' # Cheque No. :' + ISNULL(FR.ChequeNo,'') + ' BankName :' + ISNULL(FR.BankName,'') end as Narration,						
						FR.PayTypeId AS PayTypeId, 
						0 AS FeeId,
						FR.Id AS ReceiptId
				FROM sFee.tReceipt FR 
					INNER JOIN sFee.tReceiptDetail FRD ON FR.Id = FRD.ReceiptId
					INNER JOIN sStudent.vStudentAcademic SM ON SM.ACademicId = FR.SourceID AND SM.OrgGRoupBatchId = FR.OrgGRoupBatchId 
					INNER JOIN sFee.tFeeSetup FS ON FS.Id = FRD.FeeSetupId
					INNER JOIN sFee.tFeeMaster FM ON FM.Id = FS.FeeId
					INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id = FM.FeeHeadId
					INNER JOIN sFinanceCommon.tPayTypeMaster PM ON PM.Id = FR.PayTypeId
					INNER JOIN sSetup.tOrganizationMaster OM ON  OM.Id=SM.OrgId
					LEFT JOIN sSetup.tOrgSubGroupMaster OSM ON OSM.id=OM.OrgSubGroupId

					WHERE	FR.ReceiptBookId= @rReceiptBookId 
							AND FR.IsObsolete = 0 
							AND FR.OrgGroupBatchId = @rOrgGroupBatchId
							AND FR.ReceiptDate >= @rReceiptDate AND FR.ReceiptDate <= @rToReceiptDate
							AND (FR.PayTypeId = @rPayTypeId OR @rPayTypeId = 0)
				group by ReceiptDate,PM.Title,FR.PayTypeId,FR.Id,SM.Name + '(' + ClassName + ':' + DivisionName + ') ' + ' # Cheque No. :' + ISNULL(FR.ChequeNo,'') + ' BankName :' + ISNULL(FR.BankName,'')
				Order By FR.Id,ReceiptDate Desc
			END	

       ELSE IF @lTallyPostingType = 'OrgMainGroupWise' 
        BEGIN
			   SELECT	ReceiptDate,
						SM.AcademicId AS FeeName,
						PM.Title AS PayType,
						Sum(FRD.Amount) AS Amount,
						Case when @rIsCustomNarration=1 then  STUFF((SELECT distinct ','  +Replace(replace(
																					Replace(
																					replace(
																					Replace(
																					replace(
																					Replace(
																					replace(
																					Replace(
																					replace(
																					Replace(
																					replace(
																					Replace(
																					replace(
																					Replace(
																					replace(
																					replace(
																					@rCustomNarration,'[Class]',isnull(SM1.ClassName,'')
																					),'[Division]',Isnull(SM1.DivisionName,'')
																					),'[StudentsName]',isnull(SM1.Name,'')
																					), '[RollNumber]',isnull(convert(nvarchar(200),SM1.RollNo),'0')
																					),'[Batch]',isnull(SM1.BatchName,'')
																					), '[ReceiptNumber]', isnull(Convert(nvarchar(100),FR1.ReceiptNumber),'')
																					), '[ReceiptDate]',isnull(Convert(nvarchar(100),FR1.ReceiptDate),'')
																					), '[ReceiptAmount]',isnull(Convert(nvarchar(100),FR1.ReceiptAmount),'')
																					), '[ChequeNo]',isnull(Convert(nvarchar(100),FR1.ChequeNo),'')
																					),'[BankName]',isnull(FR1.BankName,'')
																					),'[FeeName]',isnull(FM1.Title,'')
																					), '[FeeAmount]',isnull(Convert(nvarchar(100),Sum(FRD.Amount)),'0.00')
																					),'[FeeHeadName]',ISNULL(FHM1.Title,'')
																					), '[FeeHeadAmount]',isnull(Convert(nvarchar(100),Sum(FRD.Amount)),'0.00')
																					), '[CollectionGroupName]',isNull(CGM1.Title,'')
																					),'[ReceiptFromNumber]',isnull(Convert(nvarchar(10),FR1.ReceiptNumber),'')
																					), '[ReceiptToNumber]',isnull(Convert(nvarchar(10),FR1.ReceiptNumber),''))
						from sFee.tReceipt FR1  INNER JOIN sFee.tReceiptDetail FRD1 ON FR1.Id = FRD1.ReceiptId
						INNER JOIN sFee.tFeeSetup FS1 ON FS1.Id = FRD1.FeeSetupId 
						INNER JOIN sStudent.vStudentAcademic SM1 ON SM1.ACademicId = FR1.SourceID AND SM1.OrgGRoupBatchId = FR1.OrgGRoupBatchId 						
						INNER JOIN sFee.tFeeMaster FM1 ON FM1.Id = FS1.FeeId --AND FRD.ReceiptId=FRD1.ReceiptId
						LEFT JOIN sFee.tCollectionGroupMaster CGM1 ON CGM1.Id = FS1.CollectionGroupId
						INNER JOIN sFinanceCommon.tPayTypeMaster PM1 ON PM1.Id = FR1.PayTypeId
						INNER JOIN sFee.tFeeHeadMaster FHM1 ON FHM1.Id = FM1.FeeHeadId  where  FR.ReceiptDate=FR1.ReceiptDate AND PM.Title=PM1.Title AND SM.AcademicId=SM1.AcademicId AND  FR.PayTypeId=FR1.PayTypeId AND FR1.IsObsolete = 0  FOR XML PATH('')),1,1,'') else
						SM.Name + '(' + ClassName + ':' + DivisionName + ') ' + ' # Cheque No. :' + ISNULL(FR.ChequeNo,'') + ' BankName :' + ISNULL(FR.BankName,'') end as Narration,						
						FR.PayTypeId AS PayTypeId, 
						FR.Id AS FeeId,
						SM.AcademicId AS ReceiptId
				FROM sFee.tReceipt FR 
					INNER JOIN sFee.tReceiptDetail FRD ON FR.Id = FRD.ReceiptId
					INNER JOIN sStudent.vStudentAcademic SM ON SM.ACademicId = FR.SourceID AND SM.OrgGRoupBatchId = FR.OrgGRoupBatchId 
					INNER JOIN sFee.tFeeSetup FS ON FS.Id = FRD.FeeSetupId
					INNER JOIN sFee.tFeeMaster FM ON FM.Id = FS.FeeId
					INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id = FM.FeeHeadId
					INNER JOIN sFinanceCommon.tPayTypeMaster PM ON PM.Id = FR.PayTypeId
					INNER JOIN sSEtup.tOrganizationMaster OM ON OM.OrgSubGRoupID =  @rReceiptBookId AND OM.ID = SM.OrgId					
					WHERE	FR.IsObsolete = 0 
							AND FR.OrgGroupBatchId = @rOrgGroupBatchId
							AND FR.ReceiptDate >= @rReceiptDate AND FR.ReceiptDate <= @rToReceiptDate
							AND FR.PayTypeID = 2
							AND (FR.PayTypeId = @rPayTypeId OR @rPayTypeId = 0)
				group by ReceiptDate,PM.Title,SM.AcademicId ,FR.PayTypeId,FR.Id,SM.Name + '(' + ClassName + ':' + DivisionName + ') ' + ' # Cheque No. :' + ISNULL(FR.ChequeNo,'') + ' BankName :' + ISNULL(FR.BankName,'')
				Order By FR.Id,ReceiptDate Desc
			END	
	ELSE IF @lTallyPostingType = 'ReceiptWise' 
			BEGIN	
				SELECT	ReceiptDate,						
						ISNULL(SLM.LedgerName,'') AS FeeName,
						PM.Title AS PayType,						
						FR.ReceiptAmount AS Amount,
						Case when @rIsCustomNarration=1 then  STUFF((SELECT distinct ','+  +Replace(
																					replace(
																					Replace(
																					replace(
																					Replace(
																					replace(
																					Replace(
																					replace(
																					Replace(
																					replace(
																					Replace(
																					replace(
																					Replace(
																					replace(
																					Replace(
																					replace(
																					replace(
																					@rCustomNarration,'[Class]',isnull(SM1.ClassName,'')
																					),'[Division]',Isnull(SM1.DivisionName,'')
																					),'[StudentsName]',isnull(SM1.Name,'')
																					), '[RollNumber]',isnull(convert(nvarchar(200),SM1.RollNo),'0')
																					),'[Batch]',isnull(SM1.BatchName,'')
																					), '[ReceiptNumber]', isnull(Convert(nvarchar(100),FR1.ReceiptNumber),'')
																					), '[ReceiptDate]',isnull(Convert(nvarchar(100),FR1.ReceiptDate),'')
																					), '[ReceiptAmount]',isnull(Convert(nvarchar(100),FR1.ReceiptAmount),'')
																					), '[ChequeNo]',isnull(Convert(nvarchar(100),FR1.ChequeNo),'')
																					),'[BankName]',isnull(FR1.BankName,'')
																					),'[FeeName]',isnull(FM1.Title,'')
																					), '[FeeAmount]',isnull(Convert(nvarchar(100),Sum(FRD.Amount)),'0.00')
																					),'[FeeHeadName]',ISNULL(FHM1.Title,'')
																					), '[FeeHeadAmount]',isnull(Convert(nvarchar(100),Sum(FRD.Amount)),'0.00')
																					), '[CollectionGroupName]',isNull(CGM1.Title,'')
																					),'[ReceiptFromNumber]',isnull(Convert(nvarchar(10),FR1.ReceiptNumber),'')
																					), '[ReceiptToNumber]',isnull(Convert(nvarchar(10),FR1.ReceiptNumber),''))
						from sFee.tReceipt FR1  INNER JOIN sFee.tReceiptDetail FRD1 ON FR1.Id = FRD1.ReceiptId
						INNER JOIN sFee.tFeeSetup FS1 ON FS1.Id = FRD1.FeeSetupId 
						INNER JOIN sStudent.vStudentAcademic SM1 ON SM1.ACademicId = FR1.SourceID AND SM1.OrgGRoupBatchId = FR1.OrgGRoupBatchId 						
						INNER JOIN sFee.tFeeMaster FM1 ON FM1.Id = FS1.FeeId --AND FRD.ReceiptId=FRD1.ReceiptId
						LEFT JOIN sFee.tCollectionGroupMaster CGM1 ON CGM1.Id = FS1.CollectionGroupId
						INNER JOIN sFinanceCommon.tPayTypeMaster PM1 ON PM1.Id = FR1.PayTypeId
						INNER JOIN sFee.tFeeHeadMaster FHM1 ON FHM1.Id = FM1.FeeHeadId
						LEFT JOIN sTally.tStudentLedgerMapping SLM1 ON SLM1.StudentId = SM1.StudentId AND SLM1.ReceiptBookid = FR1.ReceiptBookId AND SLM.LedgerName=SLM1.LedgerName where  FR1.ReceiptDate=FR.ReceiptDate   AND FR1.PayTypeId=FR.PayTypeId AND  A.StudentId=SM1.StudentId AND FR.ReceiptAmount=FR1.ReceiptAmount AND FR1.IsObsolete = 0  FOR XML PATH('')),1,1,'') else
						case When FR.PayTypeId = 1 then
						'Std-' + ClassName + ':' + DivisionName + ' RollNo :' + convert(nvarchar(20),RollNo) + ' ' + BatchName + '-->' +
						STUFF((SELECT ','  + convert(nvarchar(20),isnull(FRD1.Amount,'')) + '-' + isnull(FM1.Title ,'') 
						from sFee.tReceipt FR1  INNER JOIN sFee.tReceiptDetail FRD1 ON FR1.Id = FRD1.ReceiptId
						INNER JOIN sFee.tFeeSetup FS1 ON FS1.Id = FRD1.FeeSetupId 						
						INNER JOIN sFee.tFeeMaster FM1 ON FM1.Id = FS1.FeeId AND FRD.ReceiptId=FRD1.ReceiptId  FOR XML PATH('')),1,1,'') 
						when FR.PayTypeId <> 1 then 
						'Std-' + ClassName + ':' + DivisionName + ' RollNo :' + convert(nvarchar(20),RollNo) + ' ' + BatchName + '-->' +
						STUFF((SELECT ','  + convert(nvarchar(20),isnull(FRD1.Amount,'')) + '-' + isnull(FM1.Title ,'') 
						from sFee.tReceipt FR1  INNER JOIN sFee.tReceiptDetail FRD1 ON FR1.Id = FRD1.ReceiptId
						INNER JOIN sFee.tFeeSetup FS1 ON FS1.Id = FRD1.FeeSetupId 						
						INNER JOIN sFee.tFeeMaster FM1 ON FM1.Id = FS1.FeeId AND FRD.ReceiptId=FRD1.ReceiptId  FOR XML PATH('')),1,1,'') + '  Cheque No. :' + ISNULL(FR.ChequeNo,'') + ' BankName :' + ISNULL(FR.BankName,'')  ENd
						end AS Narration,
						--A.Name+', '+ClassName + '-' + DivisionName+', '+A.OrganizationName+', ('+BatchName+')'
						--AS Narration,					
						FR.PayTypeId AS PayTypeId,									
						A.StudentId AS FeeId,
						FRD.ReceiptId					 
				FROM sFee.tReceipt FR 
					INNER JOIN sFee.tReceiptDetail FRD ON FR.Id = FRD.ReceiptId
					INNER JOIN sFee.tFeeSetup FS ON FS.Id = FRD.FeeSetupId
					INNER JOIN sFee.tFeeMaster FM ON FM.Id = FS.FeeId
					INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id = FM.FeeHeadId
					INNER JOIN sFinanceCommon.tPayTypeMaster PM ON PM.Id = FR.PayTypeId
					INNER JOIN sStudent.vStudentAcademic A ON A.AcademicId = FR.SourceId AND A.OrgGRoupBatchId = FR.OrgGRoupBatchId
					LEFT JOIN sTally.tStudentLedgerMapping SLM ON SLM.StudentId = A.StudentId AND SLM.ReceiptBookid = FR.ReceiptBookId
					WHERE							
							FR.ReceiptBookId = @rReceiptBookId 
							AND FR.IsObsolete = 0 
							AND FR.OrgGroupBatchId = @rOrgGroupBatchId
							AND FR.ReceiptDate >= @rReceiptDate	And FR.ReceiptDate <= @rToReceiptDate
							AND (FR.PayTypeId = @rPayTypeId OR @rPayTypeId = 0)
				group by 
				ReceiptDate,PM.Title,
				SLM.LedgerName,FR.PayTypeId,A.StudentId,
				FRD.ReceiptId,Isnull(FR.ChequeNo,''),ISNull(FR.BankName,''),
				--A.Name+', '+ClassName + '-' + DivisionName+', '+A.OrganizationName+', ('+BatchName+')',
				'Std-' + ClassName + ':' + DivisionName + ' RollNo :' + convert(nvarchar(20),RollNo) + ' ' + BatchName,
				FR.ReceiptAmount			
				Order By ReceiptDate desc
			END		
			
	ELSE IF @lTallyPostingType = 'FeeHeadAndReceiptBookWise' 
			BEGIN	
				SELECT	ReceiptDate,						
						ISNULL(SLM.LedgerName,'') AS FeeName,
						PM.Title AS PayType,						
						FR.ReceiptAmount AS Amount,
						Case when @rIsCustomNarration=1 then STUFF((SELECT distinct ','  +Replace(replace(
																					Replace(
																					replace(
																					Replace(
																					replace(
																					Replace(
																					replace(
																					Replace(
																					replace(
																					Replace(
																					replace(
																					Replace(
																					replace(
																					Replace(
																					replace(
																					replace(
																					@rCustomNarration,'[Class]',isnull(SM1.ClassName,'')
																					),'[Division]',Isnull(SM1.DivisionName,'')
																					),'[StudentsName]',isnull(SM1.Name,'')
																					), '[RollNumber]',isnull(convert(nvarchar(200),SM1.RollNo),'0')
																					),'[Batch]',isnull(SM1.BatchName,'')
																					), '[ReceiptNumber]', isnull(Convert(nvarchar(100),FR1.ReceiptNumber),'')
																					), '[ReceiptDate]',isnull(Convert(nvarchar(100),FR1.ReceiptDate),'')
																					), '[ReceiptAmount]',isnull(Convert(nvarchar(100),FR1.ReceiptAmount),'')
																					), '[ChequeNo]',isnull(Convert(nvarchar(100),FR1.ChequeNo),'')
																					),'[BankName]',isnull(FR1.BankName,'')
																					),'[FeeName]',isnull(FM1.Title,'')
																					), '[FeeAmount]',isnull(Convert(nvarchar(100),Sum(FRD.Amount)),'0.00')
																					),'[FeeHeadName]',ISNULL(FHM1.Title,'')
																					), '[FeeHeadAmount]',isnull(Convert(nvarchar(100),Sum(FRD.Amount)),'0.00')
																					), '[CollectionGroupName]',isNull(CGM1.Title,'')
																					),'[ReceiptFromNumber]',isnull(Convert(nvarchar(10),FR1.ReceiptNumber),'')
																					), '[ReceiptToNumber]',isnull(Convert(nvarchar(10),FR1.ReceiptNumber),''))
						from sFee.tReceipt FR1  INNER JOIN sFee.tReceiptDetail FRD1 ON FR1.Id = FRD1.ReceiptId
						INNER JOIN sFee.tFeeSetup FS1 ON FS1.Id = FRD1.FeeSetupId 
						INNER JOIN sStudent.vStudentAcademic SM1 ON SM1.ACademicId = FR1.SourceID AND SM1.OrgGRoupBatchId = FR1.OrgGRoupBatchId 						
						INNER JOIN sFee.tFeeMaster FM1 ON FM1.Id = FS1.FeeId --AND FRD.ReceiptId=FRD1.ReceiptId
						LEFT JOIN sFee.tCollectionGroupMaster CGM1 ON CGM1.Id = FS1.CollectionGroupId
						INNER JOIN sFinanceCommon.tPayTypeMaster PM1 ON PM1.Id = FR1.PayTypeId
						INNER JOIN sFee.tFeeHeadMaster FHM1 ON FHM1.Id = FM1.FeeHeadId 
						LEFT JOIN sTally.tStudentLedgerMapping SLM1 ON SLM1.StudentId = SM1.StudentId AND SLM1.ReceiptBookid = FR1.ReceiptBookId AND SLM.LedgerName=SLM1.LedgerName where  FR1.ReceiptDate=FR.ReceiptDate AND PM1.Title=PM.Title  AND FR1.PayTypeId=FR.PayTypeId AND A.StudentId=SM1.StudentId AND FR.ReceiptAmount=FR1.ReceiptAmount AND FR1.IsObsolete = 0  FOR XML PATH('')),1,1,'') else
						case When FR.PayTypeId = 1 then
						'Receiptno-'  + CONVERT(nvarchar,isnull(FR.ReceiptNumber,'')) + 
						STUFF((SELECT ','  + convert(nvarchar(20),isnull(FM1.title,'')) 
						from sFee.tReceipt FR1  INNER JOIN sFee.tReceiptDetail FRD1 ON FR1.Id = FRD1.ReceiptId And FRD1.ReceiptId = FRD.ReceiptId 
						INNER JOIN sFee.tFeeSetup FS1 ON FS1.Id = FRD1.FeeSetupId 						
						INNER JOIN sFee.tFeeMaster FM1 ON FM1.Id = FS1.FeeId AND FRD.ReceiptId=FRD1.ReceiptId  FOR XML PATH('')),1,1,'') 
						when FR.PayTypeId <> 1 then 
						'Receiptno-'  +  CONVERT(nvarchar,isnull(FR.ReceiptNumber,'')) +
						STUFF((SELECT ','  + convert(nvarchar(20),isnull(FM1.title,'')) 
						from sFee.tReceipt FR1  INNER JOIN sFee.tReceiptDetail FRD1 ON FR1.Id = FRD1.ReceiptId And FRD1.ReceiptId = FRD.ReceiptId 
						INNER JOIN sFee.tFeeSetup FS1 ON FS1.Id = FRD1.FeeSetupId 						
						INNER JOIN sFee.tFeeMaster FM1 ON FM1.Id = FS1.FeeId AND FRD.ReceiptId=FRD1.ReceiptId  FOR XML PATH('')),1,1,'') 
						+ '  Cheque No. :' + ISNULL(FR.ChequeNo,'') + ' BankName :' + ISNULL(FR.BankName,'')  ENd
						end AS Narration,
						FR.PayTypeId AS PayTypeId,									
						A.StudentId AS FeeId,
						FRD.ReceiptId		
									 
				FROM sFee.tReceipt FR 
					INNER JOIN sFee.tReceiptDetail FRD ON FR.Id = FRD.ReceiptId
					INNER JOIN sFee.tFeeSetup FS ON FS.Id = FRD.FeeSetupId
					INNER JOIN sFee.tFeeMaster FM ON FM.Id = FS.FeeId
					INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id = FM.FeeHeadId
					INNER JOIN sFinanceCommon.tPayTypeMaster PM ON PM.Id = FR.PayTypeId
					INNER JOIN sStudent.vStudentAcademic A ON A.AcademicId = FR.SourceId AND A.OrgGRoupBatchId = FR.OrgGRoupBatchId
					LEFT JOIN sTally.tStudentLedgerMapping SLM ON SLM.StudentId = A.StudentId AND SLM.ReceiptBookid = FR.ReceiptBookId
					WHERE							
							FR.ReceiptBookId = @rReceiptBookId 
							AND FR.IsObsolete = 0 
							AND FR.OrgGroupBatchId = @rOrgGroupBatchId
							AND FR.ReceiptDate >= @rReceiptDate	And FR.ReceiptDate <= @rToReceiptDate
							AND (FR.PayTypeId = @rPayTypeId OR @rPayTypeId = 0)
				group by 
				ReceiptDate,PM.Title,
				SLM.LedgerName,FR.PayTypeId,A.StudentId,
				FRD.ReceiptId,
				Isnull(FR.ChequeNo,''),ISNull(FR.BankName,''),
				'Std-' + ClassName + ':' + DivisionName + ' RollNo :' + convert(nvarchar(20),RollNo) + ' ' + BatchName,FR.ReceiptAmount,FR.ReceiptNumber
				--,FHM.Title
				
				Order By ReceiptDate desc	
			END	
	ELSE IF @lTallyPostingType = 'FeeHeadWiseReceipt_AllDetail' 
        BEGIN
			   SELECT	ReceiptDate,
						FR.Id AS FeeName,
						PM.Title AS PayType,
						Sum(FRD.Amount) AS Amount,
						Case when @rIsCustomNarration=1 then  STUFF((SELECT  distinct ','  +Replace(replace(
																					Replace(
																					replace(
																					Replace(
																					replace(
																					Replace(
																					replace(
																					Replace(
																					replace(
																					Replace(
																					replace(
																					Replace(
																					replace(
																					Replace(
																					replace(
																					replace(
																					replace(
																					replace(
																					@rCustomNarration,'[Class]',isnull(SM1.ClassName,'')
																					),'[Division]',Isnull(SM1.DivisionName,'')
																					),'[StudentsName]',isnull(SM1.Name,'')
																					), '[RollNumber]',isnull(convert(nvarchar(200),SM1.RollNo),'0')
																					),'[Batch]',isnull(SM1.BatchName,'')
																					), '[ReceiptNumber]', isnull(Convert(nvarchar(100),FR1.ReceiptNumber),'')
																					), '[ReceiptDate]',isnull(Convert(nvarchar(100),FR1.ReceiptDate),'')
																					), '[ReceiptAmount]',isnull(Convert(nvarchar(100),FR1.ReceiptAmount),'')
																					),'Cheque No. :[ChequeNo]',case when FR1.PayTypeId = 1 then '' else 'Cheque No. :[ChequeNo]' end
																					), '[ChequeNo]',isnull(Convert(nvarchar(100),FR1.ChequeNo),'')
																					),'BankName :[BankName]',case when FR1.PayTypeId = 1 then '' else 'BankName :[BankName]' end
																					),'[BankName]',isnull(FR1.BankName,'')
																					),'[FeeName]',isnull(FM1.Title,'')
																					), '[FeeAmount]',isnull(Convert(nvarchar(100),Sum(FRD.Amount)),'0.00')
																					),'[FeeHeadName]',ISNULL(FHM1.Title,'')
																					), '[FeeHeadAmount]',isnull(Convert(nvarchar(100),Sum(FRD.Amount)),'0.00')
																					), '[CollectionGroupName]',isNull(CGM1.Title,'')
																					),'[ReceiptFromNumber]',isnull(Convert(nvarchar(10),(Select Min(ReceiptNumber) from sFee.tReceipt where   FR.ReceiptDate =ReceiptDate AND IsObsolete = 0)),'')
																					), '[ReceiptToNumber]',isnull(Convert(nvarchar(10),(Select Max(ReceiptNumber) from sFee.tReceipt Where FR.ReceiptDate = ReceiptDate AND IsObsolete = 0)),''))
						from sFee.tReceipt FR1  INNER JOIN sFee.tReceiptDetail FRD1 ON FR1.Id = FRD1.ReceiptId
						INNER JOIN sFee.tFeeSetup FS1 ON FS1.Id = FRD1.FeeSetupId 
						INNER JOIN sStudent.vStudentAcademic SM1 ON SM1.ACademicId = FR1.SourceID AND SM1.OrgGRoupBatchId = FR1.OrgGRoupBatchId 						
						INNER JOIN sFee.tFeeMaster FM1 ON FM1.Id = FS1.FeeId --AND FRD.ReceiptId=FRD1.ReceiptId
						LEFT JOIN sFee.tCollectionGroupMaster CGM1 ON CGM1.Id = FS1.CollectionGroupId
						INNER JOIN sFee.tFeeHeadMaster FHM1 ON FHM1.Id = FM1.FeeHeadId  where   FR.ReceiptDate=FR1.ReceiptDate AND FR.Id=FR1.Id AND FR1.IsObsolete = 0  FOR XML PATH('')),1,1,'') else
						case When FR.PayTypeId = 1 then
						'ReceiptNo-'  + CONVERT(nvarchar,isnull(FR.ReceiptNumber,'')) + '('+BatchName+')'
						when FR.PayTypeId <> 1 then 
						'Receiptno-'  +  CONVERT(nvarchar,isnull(FR.ReceiptNumber,'')) + '('+BatchName+')'
						+ '  Cheque No. :' + ISNULL(FR.ChequeNo,'') + ' BankName :' + ISNULL(FR.BankName,'')  ENd 
						END as Narration,						
						FR.PayTypeId AS PayTypeId, 
						FR.Id  AS FeeId,
						FR.Id AS ReceiptId
				FROM sFee.tReceipt FR 
					INNER JOIN sFee.tReceiptDetail FRD ON FR.Id = FRD.ReceiptId
					INNER JOIN sStudent.vStudentAcademic SM ON SM.ACademicId = FR.SourceID AND SM.OrgGRoupBatchId = FR.OrgGRoupBatchId 
					INNER JOIN sFee.tFeeSetup FS ON FS.Id = FRD.FeeSetupId
					INNER JOIN sFee.tFeeMaster FM ON FM.Id = FS.FeeId
					INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id = FM.FeeHeadId
					INNER JOIN sFinanceCommon.tPayTypeMaster PM ON PM.Id = FR.PayTypeId
					INNER JOIN sSetup.tOrganizationMaster OM ON  OM.Id=SM.OrgId
					LEFT JOIN sSetup.tOrgSubGroupMaster OSM ON OSM.id=OM.OrgSubGroupId

					WHERE	FR.ReceiptBookId= @rReceiptBookId 
							AND FR.IsObsolete = 0 
							AND FR.OrgGroupBatchId = @rOrgGroupBatchId
							AND FR.ReceiptDate >= @rReceiptDate AND FR.ReceiptDate <= @rToReceiptDate
							AND (FR.PayTypeId = @rPayTypeId OR @rPayTypeId = 0)
				group by ReceiptDate,PM.Title,FR.PayTypeId,FR.Id,isnull(FR.ReceiptNumber,'') , BatchName,ISNULL(FR.BankName,''),ISNULL(FR.ChequeNo,'')
				Order By FR.Id,ReceiptDate Desc
			END			
			
END
GO
PRINT N'Creating [sFee].[pRptDepositStatusStudentWise]...';


GO
CREATE PROCEDURE [sFee].[pRptDepositStatusStudentWise]

	@rBuilder1 nvarchar(max)='',
	@rBuilder2 nvarchar(max)='',
	@rOrgId int =0,
	@rBatchId int =0,
	@rDepositHeadId int =0,
	@rDepartmentId int=0,
	@rClassId int=0,
	@rDivisionId int =0,
	@rCode nvarchar(20) = ''

AS
BEGIN
	SELECT DISTINCT 
		A.StudentId,
		A.AcademicId,
		A.Code,
		A.Name,
		A.OrganizationName,
		A.OrgId,
		A.ClassDivisionName,
		ISNULL(A.TotalAmount,0) AS TotalAmount,
		A.MobileNo,
		ISNULL(A.UsedAmount,0) AS UsedAmount,
		ISNULL(A.RefundAmount,0) AS RefundAmount,
		(ISNULL(A.TotalAmount,0) - ISNULL(A.UsedAmount,0) - ISNULL(A.RefundAmount,0)) AS BalanceAmount

	FROM
		(SELECT
			VA.StudentId,
			VA.AcademicId,
			VA.Code,
			VA.Name,
			VA.OrganizationName,
			VA.OrgId,
			VA.ClassName+' - '+VA.DivisionName AS ClassDivisionName,
			SC.ParentContactNo AS MobileNo,
			VA.BatchId,

			(SELECT SUM(DA1.Amount)
			 FROM sStudent.vStudentAcademic VA1
				LEFT JOIN sFee.tDepositAdd DA1 ON VA1.AcademicId = DA1.AcademicId
			 WHERE VA1.StudentId=VA.StudentId AND (DA1.DepositHeadId=@rDepositHeadId OR @rDepositHeadId=0)) AS TotalAmount,

			(SELECT SUM(DAJ1.Amount)
			 FROM sStudent.vStudentAcademic VA2
				LEFT JOIN sFee.tDepositAdjustment DAJ1 ON VA2.AcademicId = DAJ1.AcademicId
			 WHERE VA2.StudentId=VA.StudentId AND (DAJ1.DepositHeadId=@rDepositHeadId OR @rDepositHeadId=0)) AS UsedAmount,

			(SELECT SUM(DR1.RefundAmount)
			 FROM sStudent.vStudentAcademic VA3
				LEFT JOIN sFee.tDepositRefund DR1 ON VA3.AcademicId = DR1.AcademicId
			 WHERE VA3.StudentId=VA.StudentId AND (DR1.DepositHeadId=@rDepositHeadId OR @rDepositHeadId=0)) AS RefundAmount

		FROM sStudent.vStudentAcademic VA
			LEFT JOIN sFee.tDepositAdd DA ON VA.AcademicId = DA.AcademicId
			INNER JOIN sStudent.vStudentCommunication SC ON SC.StudentId = VA.StudentId
			LEFT JOIN sFee.tDepositAdjustment DAJ ON VA.AcademicId = DAJ.AcademicId
			LEFT JOIN sFee.tDepositRefund DR ON VA.AcademicId = DR.AcademicId
			
		WHERE (VA.OrgId=@rOrgId OR @rOrgId=0)
				AND VA.StatusId =1
				AND (VA.DepartmentId=@rDepartmentId OR @rDepartmentId=0)
				AND ((VA.ClassId = @rClassId)OR(@rClassId=0))
				AND ((VA.DivisionId = @rDivisionId)OR(@rDivisionId=0))
				AND ((VA.Code=@rCode) OR (ISNULL(@rCode,'')=''))
		)A
	WHERE (A.BatchId=@rBatchId OR @rBatchId=0) AND (A.TotalAmount IS NOT NULL OR A.UsedAmount IS NOT NULL OR A.RefundAmount IS NOT NULL)
END
GO
PRINT N'Creating [sStudent].[pStudentDocumentAllBatchClassWiseGet]...';


GO

IF EXISTS (SELECT * FROM dbo.sysobjects 
WHERE id = OBJECT_ID('[sStudent].[pStudentDocumentAllBatchClassWiseGet]'))
BEGIN
    DROP PROCEDURE [sStudent].[pStudentDocumentAllBatchClassWiseGet]
END

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [sStudent].[pStudentDocumentAllBatchClassWiseGet]
	@rClassId int=0,
	@rDivisionId int=0,
	@rRollNo int=NULL,
	@rOrgId int,
	@rCode nvarchar(20),
	@rStatusId smallint=0,
	@rFirstName nvarchar(100)='',
	@rLastName nvarchar(100)='',
	@rBatchId int,
    @rSUId nvarchar(50)='',
    @rUserId bigint=0,
    @rMultiCode nvarchar(max)='',
	@rDocumentId int=0,
	@rOrderByTypeId int=0	--add
	
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	 
		BEGIN
			SET @rCode= sCommon.fSearchStringGet(@rCode)
			SET @rFirstName = sCommon.fSearchStringGet(@rFirstName)
			SET @rLastName = sCommon.fSearchStringGet(@rLastName)
		END
	IF(@rRollNo IS NULL)
	BEGIN
	SELECT 
			SA.AcademicId,
			SA.StudentId,
			SA.FirstName,
			SA.LastName,
			SA.Name,
			SA.Code,
			SA.ClassId,
			SA.ClassName,
			SA.DivisionId,
			SA.DivisionName,
			ISNULL(SA.Number,0) AS Number,
			SA.RollNo,
			SA.StatusId,
			SA.StatusName,
			SA.OrgId,
			SA.SUId,
			--SD.DocumentName
			--ISNULL(STUFF(
			-- (SELECT DISTINCT ',' + SDM.DocumentName
			--  FROM sCommon.tSubmitDocumentMaster SDM
			--  INNER JOIN  sStudent.tStudentDocument SD ON SDM.Id=SD.SubmitDocumentMasterId
			--  INNER JOIN sCommon.tSubmitDocumentScope DS ON DS.SubmitDocumentId=SDM.Id AND DS.SourceId = @rClassId
			--  where SD.StudentId=SA.StudentId AND SDM.SubmitDocumentFunctionalityId = 1 AND ((SDM.Id=@rDocumentId)OR(@rDocumentId=0))
			--  FOR XML PATH (''))
			--  , 1, 1, ''),'')  AS DocumentName,
			  ISNULL(sStudent.fStudentDocumentAllBatchClasswiseget(@rDocumentId,SA.AcademicId),'') AS DocumentName
			
  FROM 
          sStudent.vStudentAcademic SA
		  --LEFT JOIN sStudent.tStudentDocument SD ON SD.StudentId=SA.StudentId
		  INNER JOIN sSecurity.tUserAccess U ON U.SourceId = SA.DivisionId AND U.SourceTypeId=2005
             
  WHERE 
 
		((SA.ClassId=@rClassId)OR(@rClassId=0))
		AND((SA.DivisionId=@rDivisionId)OR(@rDivisionId=0))
		AND((SA.Code like @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)
		AND(SA.BatchId=@rBatchId)
		AND((SA.SUID = @rSUId) OR (ISNULL(@rSUId,'') = '')) 
		--AND((SA.Number=@rNumber)OR(@rNumber=0))	
		AND U.UserId = @rUserId
		AND (ISNULL(SA.Code,0) IN( SELECT cast(item as nvarchar(20)) FROM  sCommon.fnsplit(@rMultiCode,',')) OR @rMultiCode='')
ORDER BY CASE WHEN @rOrderByTypeId = 1 THEN SA.RollNo END,		--add case
		 CASE WHEN @rOrderByTypeId = 2 THEN (CASE ISNUMERIC(SA.Code) WHEN 1 THEN REPLICATE(0, 100 - LEN(SA.Code)) + SA.Code ELSE SA.Code END) END,	--add case
		 SA.ClassId,SA.DivisionId,SA.RollNo
END
ELSE
BEGIN
	SELECT 
			SA.AcademicId,
			SA.StudentId,
			SA.FirstName,
			SA.LastName,
			SA.Name,
			SA.Code,
			SA.ClassId,
			SA.ClassName,
			SA.DivisionId,
			SA.DivisionName,
			SA.Number,
			SA.RollNo,
			SA.StatusId,
			SA.StatusName,
			SA.OrgId,
			SA.SUId,
			--SD.DocumentName
			 ISNULL(sStudent.fStudentDocumentAllBatchClasswiseget(@rDocumentId,SA.AcademicId),'') AS DocumentName
			
			
  FROM 
          sStudent.vStudentAcademic SA
		  --LEFT JOIN sStudent.tStudentDocument SD ON SD.StudentId=SA.StudentId
          INNER JOIN sSecurity.tUserAccess U ON U.SourceId = SA.DivisionId AND U.SourceTypeId=2005
  WHERE 
 
		((SA.ClassId=@rClassId)OR(@rClassId=0))
		AND((SA.DivisionId=@rDivisionId)OR(@rDivisionId=0))
		AND((SA.Code like @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)
		AND(SA.BatchId=@rBatchId)
		AND((SA.SUID = @rSUId) OR (ISNULL(@rSUId,'') = '')) 
		AND U.UserId = @rUserId
		AND (ISNULL(SA.Code,0) IN( SELECT cast(item as nvarchar(20)) FROM  sCommon.fnsplit(@rMultiCode,',')) OR @rMultiCode='')
		--AND((SA.Number=@rNumber)OR(@rNumber=0))	

ORDER BY CASE WHEN @rOrderByTypeId = 1 THEN SA.RollNo END,		--add case
		 CASE WHEN @rOrderByTypeId = 2 THEN (CASE ISNUMERIC(SA.Code) WHEN 1 THEN REPLICATE(0, 100 - LEN(SA.Code)) + SA.Code ELSE SA.Code END) END,	--add case
		 SA.ClassId,SA.DivisionId,SA.RollNo
END
  
	
END
GO
PRINT N'Creating [sTimetable].[pAssignDivisionDelete]...';


GO

Create PROCEDURE [sTimetable].[pAssignDivisionDelete]
	 
		@rDivisionId int,
		@rTimeTableSchemaId int
		
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 



	BEGIN TRY
		BEGIN TRANSACTION	

		IF EXISTS (SELECT 1 FROM  [sTimetable].[tProxySetting]  WHERE  DivisionId =@rDivisionId  AND TimeTableSchemaId =@rTimeTableSchemaId )
		BEGIN
			SELECT -101 AS RESULT
		END
		else IF EXISTS (SELECT 1 FROM  [sTimetable].[tTimeTableTime]  WHERE  DivisionId =@rDivisionId  AND TimeTableSchemaId =@rTimeTableSchemaId )
		BEGIN
			SELECT -102 AS RESULT
		END
		else IF EXISTS (SELECT 1 FROM  [sTimetable].[tTimeTable]  WHERE  DivisionId =@rDivisionId  AND TimeTableSchemaId =@rTimeTableSchemaId )
		BEGIN
			SELECT -103 AS RESULT
		END
		else IF EXISTS (SELECT 1 FROM  [sTimetable].[tTeacherWorkLoad]  WHERE  DivisionId =@rDivisionId  AND TimeTableSchemaId =@rTimeTableSchemaId )
		BEGIN
			SELECT -104 AS RESULT
		END
		else IF EXISTS (SELECT 1 FROM  [sTimetable].[tDivisionWorkLoad]  WHERE  DivisionId =@rDivisionId  AND TimeTableSchemaId =@rTimeTableSchemaId )
		BEGIN
			SELECT -105 AS RESULT
		END

		else IF EXISTS (SELECT 1 FROM  [sTimetable].[tTimeSetup]  WHERE  ClassId =@rDivisionId  AND TimeTableSchemaId =@rTimeTableSchemaId )
		BEGIN
			SELECT -106 AS RESULT
		END
		else IF EXISTS (SELECT 1 FROM  [sTimetable].[tDivisionTimeOff]  WHERE  DivisionId =@rDivisionId  AND TimeTableSchemaId =@rTimeTableSchemaId )
		BEGIN
			SELECT -107 AS RESULT
		END	
		
		ELSE 
		BEGIN
			Delete from sTimetable.tAssignDivision Where DivisionId =@rDivisionId  AND TimeTableSchemaId =@rTimeTableSchemaId 
			SELECT 1 AS Result
		END		
		COMMIT TRANSACTION	
	END TRY
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH			
END
GO


GO

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

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


GO
/*
Table [sHrm].[tTempEmployee13] is being dropped.  Deployment will halt if the table contains data.
*/

IF EXISTS (select top 1 1 from [sHrm].[tTempEmployee13])
    RAISERROR (N'Rows were detected. The schema update is terminating because data loss might occur.', 16, 127) WITH NOWAIT

GO
/*
Table [sStudent].[tTempStudent11] is being dropped.  Deployment will halt if the table contains data.
*/

IF EXISTS (select top 1 1 from [sStudent].[tTempStudent11])
    RAISERROR (N'Rows were detected. The schema update is terminating because data loss might occur.', 16, 127) WITH NOWAIT

GO
/*
Table [sStudent].[tTempStudent14] is being dropped.  Deployment will halt if the table contains data.
*/

IF EXISTS (select top 1 1 from [sStudent].[tTempStudent14])
    RAISERROR (N'Rows were detected. The schema update is terminating because data loss might occur.', 16, 127) WITH NOWAIT

GO
PRINT N'Dropping Index [sAcademic].[tOnlineLearningView].[UK_tOnlineLearningView]...';


GO
DROP INDEX [UK_tOnlineLearningView]
    ON [sAcademic].[tOnlineLearningView];


GO
PRINT N'Dropping Index [sSetup].[tDivisionInchargeEmployee].[UK_tDivisionInchargeEmployee]...';


GO
DROP INDEX [UK_tDivisionInchargeEmployee]
    ON [sSetup].[tDivisionInchargeEmployee];


GO
PRINT N'Dropping Primary Key [sAccounting].[PK_tLedgerGroupMaster]...';


GO
ALTER TABLE [sAccounting].[tLedgerGroupMaster] DROP CONSTRAINT [PK_tLedgerGroupMaster];


GO
PRINT N'Dropping Primary Key [sAccounting].[PK_tLedgerMaster]...';


GO
ALTER TABLE [sAccounting].[tLedgerMaster] DROP CONSTRAINT [PK_tLedgerMaster];


GO
PRINT N'Dropping Primary Key [sSecurity].[PK_tScreenHelp]...';


GO
ALTER TABLE [sSecurity].[tScreenHelp] DROP CONSTRAINT [PK_tScreenHelp];


GO
PRINT N'Dropping Table [sHrm].[tTempEmployee13]...';


GO
DROP TABLE [sHrm].[tTempEmployee13];


GO
PRINT N'Dropping Table [sStudent].[tTempStudent11]...';


GO
DROP TABLE [sStudent].[tTempStudent11];


GO
PRINT N'Dropping Table [sStudent].[tTempStudent14]...';


GO
DROP TABLE [sStudent].[tTempStudent14];


GO
PRINT N'Dropping Procedure [sAcademic].[pEmployeeClassworkHomeworkQueueGet]...';


GO
DROP PROCEDURE [sAcademic].[pEmployeeClassworkHomeworkQueueGet];


GO
PRINT N'Dropping Procedure [sAdmission].[pOnlineRegistrationCriteriaFormGet]...';


GO
DROP PROCEDURE [sAdmission].[pOnlineRegistrationCriteriaFormGet];


GO
PRINT N'Dropping Procedure [sAlert].[pWebDeviceTokenGet]...';


GO
DROP PROCEDURE [sAlert].[pWebDeviceTokenGet];


GO
PRINT N'Dropping Procedure [sCommunication].[pCloneCircularAdd]...';


GO
DROP PROCEDURE [sCommunication].[pCloneCircularAdd];


GO
PRINT N'Dropping Procedure [sFee].[pRptFeePendingDetailListGet_TestPerformance]...';


GO
DROP PROCEDURE [sFee].[pRptFeePendingDetailListGet_TestPerformance];


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


GO
ALTER TABLE [sFee].[tDepositBalance]
    ADD [NegativeBalance] DECIMAL (12, 2) NULL;


GO
PRINT N'Altering View [sHrm].[vEmployeeColumnName]...';


GO
ALTER VIEW [sHrm].[vEmployeeColumnName]  
  
AS  
  
SELECT 	
		--EM.OrgId
		--,EM.Id AS EmployeeId
		OM.Title AS Organization
		,EM.Code
		,EM.FirstName
		,EM.MiddleName
		,EM.LastName
		,ISNULL(EM.FirstName, '') + ' ' + ISNULL(EM.MiddleName, '') + ' ' + ISNULL(EM.LastName, '') AS Name
		--,EM.StatusId
		,SM.Title AS StatusName
		--,EM.IsObsolete
		--,EJD.Id AS EmployeeJobDetailId
		--,EJD.EmployeeDesignationId
		,EDM.Title AS EmployeeDesignation
		--,EJD.OrganizationDepartmentId
		,ODM.Title AS OrganizationDepartment
		,EJD.DateOfJoining
		--,EJD.EPFNumber
		--,EJD.ESINumber
		--,EJD.EmployeeTypeId
		,ETM.Title AS EmployeeType
		,EGM.Title AS EmployeeGroup
		,EJD.DateOfleaving
		,EJD.ReasonOfleaving
		,EJD.Subjects
		--,ELM.StreetOne
		--,ELM.StreetTwo
		--,ELM.StreetThree
		--,ELM.CityName
		--,ELM.StateName
		--,ELM.CountryName
		--,ELM.ZipCode
		--,ELM.PhoneNo
		--,ELM.FaxNo
		--,ELM.NameOfOccupier
		--,ELM.AddressOfOccupier
		--,ELM.SmallAddress1
		--,ELM.SmallAddress2
		--,ELM.RegistrationNumber
		--,ELM.LicenceNumber
		--,ELM.EsicNumber
		--,ELM.EsicAddress1
		--,ELM.EsicAddress2
		--,ELM.NatureOfIndustry
		--,ELM.ByProduct
		--,ELM.DangerousOperation
		--,ELM.NatureOfTest
		--,ELM.NatureOfTestNonHazardous
		--,ELM.RowMaterialUsed
		--,ELM.HazardousProcess
		--,ELM.Cmo
		--,ELM.NicNumber
		--,ELM.CountryId
		--,ELM.StateId
		--,EPD.Id AS EmployeePersonalDetailId
		,EPD.UIDNumber
		,EPD.DateOfBirth
		,EPD.Qualification
		,EPD.FamilyCast
		,CCM.Title AS CastCategory
		--,EPD.GenderId
		,GM.Title AS Gender
		--,EPD.ReligionId
		,RM.Title AS Religion
		--,EPD.MaritalStatusId
		,MSM.Title AS MaritalStatus
		,EPD.IdentificationMark1
		--,EPD.BloodGroupId
		,BGM.Title AS BloodGroup,
		EC.MobileNumber,
		EC.PersonalEmail
		,EC.CompanyEmail
		,EC.PhoneNoCompany
		,EC.ExtensionNo
		,EC.PresentStreetOne
		,Ec.PresentStreetTwo
		,Ec.PresentStreetThree
		,Ec.PresentCountry
		,Ec.PresentState
		,Ec.PresentCity
		,Ec.PresentZipCode
		,Ec.PresentContactNo
		,Ec.PermanentStreetOne
		,Ec.PermanentStreetTwo
		,Ec.PermanentStreetThree
		,Ec.PermanentCountry
		,Ec.PermanentState
		,Ec.PermanentCity
		,Ec.PermanentZipCode
		,Ec.PermanentContactNo
		,Ec.EmergencyStreetOne
		,Ec.EmergencyStreetTwo
		,Ec.EmergencyStreetThree
		,Ec.EmergencyCountry
		,Ec.EmergencyState
		,Ec.EmergencyCity
		,Ec.EmergencyZipCode
		,Ec.EmergencyContactNo
		,ES.EPFNumber
		,ES.ESINumber
		,ES.AccountNumber
		,ES.BankName
		,ES.Branch
		,ES.IFSCNumber
		,ES.PanNumber
		,ES.BasicPay
		,ES.IncrementDate
		,ES.EPFJoinDate
		,ISNULL(ES.Payscale,'') AS Payscale
		,ISNULL(EPD.AdhaarNumber,'') AS AdhaarNumber
		,ISNULL(ES.RetirementDate,'') AS RetirementDate
		,EM.Number
		,ISNULL(EJD.ProbationUptoDate,'') As ProbationUptoDate
		,ISNULL(EJD.AhdocUptoDate,'') As AhdocUptoDate
		,ISNULL(EJD.PermanentDate,'') As PermanentDate
		,ISNULL(EJD.DateOfResignation,'') As DateOfResignation
		,STUFF( (SELECT DISTINCT ',' + CTM.Title FROM sHrm.tEmployeeCustomTag ECT INNER JOIN sHrm.tCustomTagMaster CTM ON ECT.CustomTagId=CTM.Id 
							WHERE ECT.EmployeeId = EM.Id FOR XML PATH ('')), 1, 1, '')  AS CustomTag
		,ES.AccountHolderName
		,ISNULL(EC.WhatsAppContactNo,'') AS WhatsAppContactNo
		,EM.PunchId AS PunchId
		,ISNULL(ShiftName,'') AS ShiftName
		,STUFF(
			COALESCE(',' + NULLIF(EC.PresentStreetOne, ''), '')  + 
			COALESCE(',' + NULLIF(EC.PresentStreetTwo, ''), '') +
			COALESCE(',' + NULLIF(EC.PresentStreetThree, ''), '') +
			COALESCE(',' + NULLIF(EC.PresentCountry, ''), '') +
			COALESCE(',' + NULLIF(EC.PresentState, ''), '') +
			COALESCE(',' + NULLIF(EC.PresentCity, ''), '') +
			COALESCE(',' + NULLIF(EC.PresentZipCode, ''), '') +
			COALESCE(',' + NULLIF(EC.PresentContactNo, ''), ''),
			1, 1, '') AS PresentAddress
FROM sHrm.tEmployeeMaster EM
		INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id
		--LEFT JOIN sHrm.tEmployeeJobTitleMaster EJTM ON EJTM.Id=EJD.EmployeeJobTitleId
		LEFT JOIN sHrm.tEmployeeDesignationMaster EDM ON EDM.Id=EJD.EmployeeDesignationId
		INNER JOIN sSetup.tDepartmentMaster ODM ON ODM.Id = EJD.OrganizationDepartmentId
		INNER JOIN sHrm.tEmployeePersonalDetail EPD ON EPD.EmployeeId = EM.Id
		LEFT JOIN sCommon.tCastCategoryMaster CCM ON CCM.Id = EPD.CastCategoryId
		LEFT JOIN sCommon.tGenderMaster GM ON GM.Id=EPD.GenderId
		LEFT JOIN sCommon.tReligionMaster RM ON RM.Id=EPD.ReligionId
		LEFT JOIN sCommon.tMaritalStatusMaster MSM ON MSM.Id=EPD.MaritalStatusId
		LEFT JOIN sCommon.tBloodGroupMaster BGM ON BGM.Id=EPD.BloodGroupId
		--LEFT JOIN sHrm.tQualificationMaster QM ON QM.Id=EPD.HigestQualificationId
		INNER JOIN sHrm.tEmployeeTypeMaster ETM ON ETM.Id = EJD.EmployeeTypeId
		INNER JOIN sCommon.tStatusMaster SM ON SM.Id = EM.StatusId AND SM.StatusTypeId = 4
		LEFT JOIN sHrm.tEmployeeCommunications EC ON EC.EmployeeId = EM.Id
		LEFT JOIN sHrm.tEmployeeStatutoryAndOther ES ON ES.EmployeeId = EM.Id
		LEFT JOIN sHrm.tEmployeeGroupMaster EGM ON EGM.Id = EJD.EmployeeGroupId
		INNER JOIN sSetup.tOrganizationMaster OM ON EM.OrgId = OM.Id
		left JOIn [sBiometric].[tShiftMasterCloud] SMC ON SMC.ShiftCode=EM.ShiftId
GO
PRINT N'Altering View [sHrm].[vEmployeeCustomSearch]...';


GO
ALTER VIEW [sHrm].[vEmployeeCustomSearch]
AS
SELECT        
		EM.OrgID,
		OM.DisplayTitle AS Organization, 
		EM.Id AS EmployeeId, 
		EM.Code, 
		EM.FirstName, 
		EM.MiddleName, 
		EM.LastName, 
		ISNULL(EM.FirstName, '') + ' ' + ISNULL(EM.MiddleName, '') + ' ' + ISNULL(EM.LastName, '') AS Name, 
		EM.StatusId, 
		SM.Title AS StatusName, 
		EM.IsObsolete, 
		0 AS EmployeeJobDetail, 
		EJD.EmployeeDesignationId, 
		EDM.Title AS EmployeeDesignation, 
		EJD.OrganizationDepartmentId, 
		ODM.Title AS OrganizationDepartment, 
		CONVERT(VARCHAR(10), EJD.DateOfJoining, 111) AS DateOfJoining, 
		EJD.EmployeeTypeId, 
		ETM.Title AS EmployeeType, 
		EGM.Title AS EmployeeGroup, 
		CONVERT(VARCHAR(10), EJD.DateOfleaving, 111) AS DateOfleaving, 
		EJD.ReasonOfleaving, 
		EJD.Subjects, 
		0 AS EmployeePersonalDetailId, 
		EPD.UIDNumber, 
		CONVERT(VARCHAR(10), EPD.DateOfBirth, 111) AS DateOfBirth, 
		EPD.GenderId, 
		GM.Title AS Gender, 
		EPD.ReligionId, 
		RM.Title AS Religion, 
		EPD.MaritalStatusId, 
		MSM.Title AS MaritalStatus, 
		EPD.IdentificationMark1, 
		EPD.BloodGroupId, 
		BGM.Title AS BloodGroup, 
		EPD.Qualification, 
		EPD.FamilyCast, 
		CCM.Title AS CastCategory, 
		EJD.EmployeeGroupId, 
		EC.MobileNumber, 
		EC.PersonalEmail, 
		EC.CompanyEmail, 
		EC.PhoneNoCompany, 
		EC.ExtensionNo, 
		EC.PresentStreetOne, 
		EC.PresentStreetTwo, 
		EC.PresentStreetThree, 
		EC.PresentCountry, 
		EC.PresentState, 
		EC.PresentCity, 
		EC.PresentZipCode, 
		EC.PresentContactNo, 
		EC.PermanentStreetOne, 
		EC.PermanentStreetTwo, 
		EC.PermanentStreetThree, 
		EC.PermanentCountry, 
		EC.PermanentState, 
		EC.PermanentCity, 
		EC.PermanentZipCode, 
		EC.PermanentContactNo, 
		EC.EmergencyStreetOne, 
		EC.EmergencyStreetTwo, 
		EC.EmergencyStreetThree, 
		EC.EmergencyCountry, 
		EC.EmergencyState, 
		EC.EmergencyCity, 
		EC.EmergencyZipCode, 
		EC.EmergencyContactNo, 
		ES.EPFNumber, 
		ES.ESINumber, 
		ES.AccountNumber, 
		ES.BankName, 
		ES.Branch, 
		ES.IFSCNumber, 
		ES.PanNumber, 
		ES.BasicPay, 
		CONVERT(VARCHAR(10), ES.IncrementDate, 111) AS IncrementDate, 
		CONVERT(VARCHAR(10), ES.EPFJoinDate, 111) AS EPFJoinDate, 
		ISNULL(ES.Payscale, '') AS Payscale, 
		ISNULL(EPD.AdhaarNumber, '') AS AdhaarNumber, 
		ISNULL(CONVERT(VARCHAR(50), ES.RetirementDate, 103), '') AS RetirementDate, 
		ISNULL(EM.Number, 0) AS Number, 
		CONVERT(VARCHAR(10), EJD.ProbationUptoDate, 111) AS ProbationUptoDate, 
		CONVERT(VARCHAR(10), EJD.AhdocUptoDate, 111) AS AhdocUptoDate, 
		CONVERT(VARCHAR(10), EJD.PermanentDate, 111) AS PermanentDate, 
		CONVERT(VARCHAR(10), EJD.DateOfResignation, 111) AS DateOfResignation, 
		EM.IsOtherUser,
		(SELECT STUFF((
			SELECT DISTINCT ',' + CTM.Title 
			FROM sHrm.tEmployeeCustomTag ECT 
				INNER JOIN sHrm.tCustomTagMaster CTM ON ECT.CustomTagId=CTM.Id 
			WHERE ECT.EmployeeId = EM.Id FOR XML PATH ('')), 1, 1, '')  AS CustomTag 
		FROM sHrm.tEmployeeMaster EM1 
		WHERE EM1.Id = EM.Id 
		GROUP BY EM1.Id) AS CustomTag,
		OM.OrgGroupId,
		ES.AccountHolderName,
		ISNULL(EC.WhatsAppContactNo,'') AS WhatsAppContactNo,
		EM.PunchId AS PunchId,
		ISNULL(ShiftName,'') AS ShiftName,
		STUFF(
			COALESCE(',' + NULLIF(EC.PresentStreetOne, ''), '')  + 
			COALESCE(',' + NULLIF(EC.PresentStreetTwo, ''), '') +
			COALESCE(',' + NULLIF(EC.PresentStreetThree, ''), '') +
			COALESCE(',' + NULLIF(EC.PresentCountry, ''), '') +
			COALESCE(',' + NULLIF(EC.PresentState, ''), '') +
			COALESCE(',' + NULLIF(EC.PresentCity, ''), '') +
			COALESCE(',' + NULLIF(EC.PresentZipCode, ''), '') +
			COALESCE(',' + NULLIF(EC.PresentContactNo, ''), ''),
			1, 1, '') AS PresentAddress

FROM	sHrm.tEmployeeMaster AS EM 
			INNER JOIN sHrm.tEmployeeJobDetail AS EJD ON EJD.EmployeeId = EM.Id 
			LEFT OUTER JOIN sHrm.tEmployeeDesignationMaster AS EDM ON EDM.Id = EJD.EmployeeDesignationId 
			INNER JOIN sSetup.tDepartmentMaster AS ODM ON ODM.Id = EJD.OrganizationDepartmentId 
			INNER JOIN sHrm.tEmployeePersonalDetail AS EPD ON EPD.EmployeeId = EM.Id 
			LEFT OUTER JOIN sCommon.tCastCategoryMaster AS CCM ON CCM.Id = EPD.CastCategoryId 
			LEFT OUTER JOIN sCommon.tGenderMaster AS GM ON GM.Id = EPD.GenderId 
			LEFT OUTER JOIN sCommon.tReligionMaster AS RM ON RM.Id = EPD.ReligionId 
			LEFT OUTER JOIN sCommon.tMaritalStatusMaster AS MSM ON MSM.Id = EPD.MaritalStatusId 
			LEFT OUTER JOIN sCommon.tBloodGroupMaster AS BGM ON BGM.Id = EPD.BloodGroupId 
			INNER JOIN sHrm.tEmployeeTypeMaster AS ETM ON ETM.Id = EJD.EmployeeTypeId 
			INNER JOIN sCommon.tStatusMaster AS SM ON SM.Id = EM.StatusId AND SM.StatusTypeId = 4 
			LEFT OUTER JOIN sHrm.tEmployeeCommunications AS EC ON EC.EmployeeId = EM.Id 
			LEFT OUTER JOIN sHrm.tEmployeeStatutoryAndOther AS ES ON ES.EmployeeId = EM.Id 
			LEFT OUTER JOIN sHrm.tEmployeeGroupMaster AS EGM ON EGM.Id = EJD.EmployeeGroupId 
			INNER JOIN sSetup.tOrganizationMaster AS OM ON EM.OrgID = OM.Id
			left JOIn [sBiometric].[tShiftMasterCloud] SMC ON SMC.ShiftCode=EM.ShiftId
GO
PRINT N'Altering Procedure [sFee].[pDepositBalanceAdd]...';


GO
ALTER PROCEDURE [sFee].[pDepositBalanceAdd]
	 
	@rDepositHeadId int,
	@rClassId int,
	@rBalanceAmount decimal(12,2),
	@rNegativeBalance decimal(12,2) = 0
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
		---- FOR DELETE 
		--IF(@rIsDeleted=1)
		--BEGIN
		--	DELETE FROM sScholarship.tScholarshipStudentPaid WHERE ScholarshipReceiveId=@rScholarshipReceiveId AND AcademicId=@rAcademicId
		--			SELECT @rScholarshipReceiveId AS Result
		--END	
BEGIN	
BEGIN TRY
BEGIN TRANSACTION	

		---- DATE VALIDATION
		
		--	IF NOT EXISTS (SELECT 1 FROM sScholarship.tScholarshipStudentPaid WHERE AcademicId=@rAcademicId AND ScholarshipReceiveId=@rScholarshipReceiveId)
		--	BEGIN
		--		IF EXISTS (SELECT 1 FROM sScholarship.tScholarshipReceive WHERE ReceiveDate > @rPaidDate )
		--		BEGIN
		--			SELECT -101 AS Result
		--			RETURN
		--		END
		--	END 
		--	ELSE
		--	BEGIN
		--		IF EXISTS	(SELECT 1 FROM sScholarship.tScholarshipStudentPaid SSP INNER JOIN sScholarship.tScholarshipReceive SR ON SR.Id = SSP.ScholarshipReceiveId
		--						AND ScholarshipReceiveId=@rScholarshipReceiveId  AND SR.ReceiveDate > @rPaidDate)
		--		BEGIN
		--			SELECT -101 as Result
		--			RETURN
		--		END 
		--	END 
			
		--	-- AMOUNT VALIDATIEON
			
		--	IF EXISTS (SELECT 1 FROM sScholarship.tScholarshipStudentPaid WHERE AcademicId=@rAcademicId AND ScholarshipReceiveId = @rScholarshipReceiveId)
		--	BEGIN
		--		If EXISTS
		--			(SELECT 1 FROM sScholarship.tScholarshipReceive SR
		--			WHERE SR.Id = @rScholarshipReceiveId AND SR.TotalAmount 
		--			< (SELECT  ISNULL(SUM(SSP.PaidAmount),0) + @rPaidAmount - (SELECT ISNULL(PaidAmount,0) FROM sScholarship.tScholarshipStudentPaid 
		--			WHERE AcademicId=@rAcademicId AND ScholarshipReceiveId = @rScholarshipReceiveId) 
		--			AS TotalPaidAmount FROM sScholarship.tScholarshipStudentPaid SSP 
		--			WHERE ScholarshipReceiveId = @rScholarshipReceiveId)) 				
		--			BEGIN
		--				SELECT -102 as Result
		--				RETURN
		--			END 
		--		END
		--	ELSE
		--		BEGIN
		--			If EXISTS
		--			(SELECT SR.TotalAmount FROM sScholarship.tScholarshipReceive SR WHERE SR.Id = @rScholarshipReceiveId AND SR.TotalAmount 
		--			 < (SELECT  ISNULL(SUM(SSP.PaidAmount),0) + @rPaidAmount AS TotalPaidAmount FROM sScholarship.tScholarshipStudentPaid SSP 
		--				WHERE ScholarshipReceiveId = @rScholarshipReceiveId)) 				
		--			BEGIN
		--				SELECT -102 as Result
		--				RETURN
		--			END 
		--		END			
			
 IF NOT EXISTS (SELECT 1 FROM sFee.tDepositBalance WHERE DepositHeadId=@rDepositHeadId AND ClassId=@rClassId)	
   BEGIN
		INSERT INTO sFee.tDepositBalance
			(
				DepositHeadId,
				ClassId,
				BalanceAmount,
				NegativeBalance
			)
		VALUES
			(
				@rDepositHeadId,
				@rClassId,
				@rBalanceAmount,
				@rNegativeBalance
			)   
	END	 
ELSE
     BEGIN
     
	    UPDATE sFee.tDepositBalance
	    SET
			  BalanceAmount=@rBalanceAmount,
			  NegativeBalance = @rNegativeBalance
	    WHERE DepositHeadId=@rDepositHeadId AND ClassId=@rClassId
	    
	 END  
		SELECT @rDepositHeadId AS Result
	
	COMMIT TRANSACTION
		
END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
	
	END	
END
GO
PRINT N'Altering Procedure [sFee].[pDepositBalanceGet]...';


GO

ALTER PROCEDURE [sFee].[pDepositBalanceGet]
          
           @rDepositHeadId int,
           @rBatchId int
AS
SET NOCOUNT ON
BEGIN
SELECT   
		ISNULL(vBC.ClassId,0) AS ClassId,
        ISNULL(vBC.ClassName,'') AS ClassName,
        ISNULL(DB.DepositHeadId,0) AS DepositHeadId,
        ISNULL(DB.BalanceAmount,0.00)AS BalanceAmount,
		ISNULL(DB.NegativeBalance,0.00)AS NegativeBalance
  FROM 		
	  	sSetup.vBatchClass vBC
		LEFT JOIN sFee.tDepositBalance DB ON DB.ClassId =vBC.ClassId AND (DB.DepositHeadId=@rDepositHeadId OR @rDepositHeadId=0)
  WHERE 
		vBC.BatchId=@rBatchId
		order by vBC.OrderIndex
END
GO
PRINT N'Altering Procedure [sFee].[pRptDepositBalanceGet]...';


GO

ALTER PROCEDURE [sFee].[pRptDepositBalanceGet]
          
           @rOrgId smallint,
           @rDepositHeadId int,
           @rBatchId 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
SELECT   
		ISNULL(vBC.ClassId,0) AS ClassId,
        ISNULL(vBC.ClassName,'') AS ClassName,
        ISNULL(DB.DepositHeadId,0) AS DepositHeadId,
        ISNULL(DHM.Title,'') AS DepositHeadName,
        ISNULL(DB.BalanceAmount,0.00)AS BalanceAmount,
        ISNULL(OM.Id,0) AS OrgId,
        ISNULL(OM.DisplayTitle,'') AS OrganizationName,
		@lIDConfigValue AS ItemValue,
		ISNULL(DB.NegativeBalance,0.00)AS NegativeBalance
  FROM 		
	  	sSetup.vBatchClass vBC
		LEFT JOIN sFee.tDepositBalance DB ON DB.ClassId =vBC.ClassId AND (DB.DepositHeadId=@rDepositHeadId OR @rDepositHeadId=0)
		INNER JOIN sFee.tDepositHeadMaster DHM ON DHM.Id=DB.DepositHeadId
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=@rOrgId
  WHERE 
		vBC.BatchId=@rBatchId
		AND (DB.DepositHeadId=@rDepositHeadId OR @rDepositHeadId=0)
		AND (Om.Id=@rOrgId OR @rOrgId=0)

		order by vBC.OrderIndex
END
GO
PRINT N'Altering Procedure [sAssessment].[pCopyExamAdd]...';


GO

ALTER PROCEDURE [sAssessment].[pCopyExamAdd]
	 
	      @rFromBatchId int,
	      @rClassId int,
	      @rOrgId int,
	      @rToBatchId int
		  	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	 
	 BEGIN TRANSACTION	
	 
	 
	DECLARE @lNextNumber BIGINT,@lExamdetailNextNumber BIGINT,@lExamCombineNextNumber bigint,@lCombineNextNumber bigint
	Declare @lCount int,@lExamDetailCount int,@lExamCombineCount int,@lCombineCount int ,
	@lClass nvarchar(50)
	 
	
		
	if exists (Select 1  from sAssessment.tExamMaster  WHere BatchId = @rToBatchId And ((ClassID=@rClassId) OR (@rClassId=0)))
	BEGIN
		Select @lClass=CM.Title from sAssessment.tExamMaster EM INNER JOIN sSetup.tClassMaster CM ON CM.Id= EM.ClassID Where EM.BatchId = @rToBatchId AND ((EM.ClassID=@rClassId) OR (@rClassId=0))
		Select 1 as REsult,@lClass As Class
		COMMIT TRANSACTION		
	
		Return
		
	END


	Select @lCount = Count(Id) from sAssessment.tExamMaster where BatchId = @rFromBatchId AND ((ClassId = @rClassId) OR (@rClassId=0))
	  EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sAssessment.tExamMaster', 0, 1, 1,@outNextNumber = @lNextNumber output

	
	Insert into sAssessment.tExamMaster
	( 
		Id,BatchId,ExamSubGroupId,ClassId,IsRankNo,IsGrade,IsPercentile,IsPercentage,IsSubjectPercentile,
		GradeSetId,RankSetId,LevelSetId,UpdatedUserId,UpdatedDateTime,IsProcessResult,IsMarksInDecimal,
		IsNegativeMarks,IsIncludeCoScholastic,IsOnPrePrinted,ReportId,DisplayTitle,Remark1,Remark2,
		Remark3,IsDisplayPhoto,FooterAdjustment,IsDisplayBirthDate,IsLockForEdit,
		IsDisplaySchoolName,DetailAdjustment,IsDisplayHeightWeight,IsDisplayAttendance,TermScopeId,
		IsResultStatus,ExamMaximum,IsDisplayGradeString,IsIncludeGradeSubject,GradeSubjectGradeSetId,
		IsIncludeSubExam,IsCoScholasticGrade,IsCoScholasticGradeIndicator,
		IsCoScholasticGradeDesIndicator,IsCoScholasticCombine,OldExamId,IsPublished,IsDisplayHighestDivisionMark,
		IsDisplayHighestDivisionGrade,IsDisplayParentName,CoScholasticScopeId,SubjectGroupPerPage,
		IsDisplayTeacherSign,IsDisplayPrincipalSign,PercentileScopeId,CoScholasticGradeSetId,IsExcludeAbsentTotal,
		CoScholasticTitle,IsDisplayMonthlyAttendance,IsDisplayImageHeader,DecimalFormat,IsDisplayTotalMark,
		IsDisplayResultIndicator,IsRemovePercentageForFail,Remark1Caption,Remark2Caption,Remark3Caption,
		TeacherSignCaption,PrincipalSignCaption,ParentSignCaption,IsSubjectWeightage,OldImportExamId,IsDisplayActivityGrade,IsAllExamPassRequired,HeaderAdjustment,IsPublishExamSchedule,LinkExamId,OverallPercentageForGrace,MinimumGracePercetage,GraceMaxMark,KrupaMaxMark,IsApplySiddhiKrupa,IsDisplayGraph,IsGenerateRankNo
	)
	 Select  
		@lNextNumber + ROW_NUMBER() OVER(ORDER BY Id) ,@rToBatchId,ExamSubGroupId,@rClassId,IsRankNo,IsGrade,IsPercentile,IsPercentage,
		IsSubjectPercentile,GradeSetId,RankSetId,LevelSetId,UpdatedUserId,sCommon.fGetDate(),IsProcessResult,
		IsMarksInDecimal,IsNegativeMarks,IsIncludeCoScholastic,IsOnPrePrinted,ReportId,DisplayTitle,Remark1,
		Remark2,Remark3,IsDisplayPhoto,FooterAdjustment,IsDisplayBirthDate,IsLockForEdit,
		IsDisplaySchoolName,DetailAdjustment,IsDisplayHeightWeight,IsDisplayAttendance,TermScopeId,
		IsResultStatus,ExamMaximum,IsDisplayGradeString,IsIncludeGradeSubject,GradeSubjectGradeSetId,
		IsIncludeSubExam,IsCoScholasticGrade,IsCoScholasticGradeIndicator,
		IsCoScholasticGradeDesIndicator,IsCoScholasticCombine,OldExamId,IsPublished,IsDisplayHighestDivisionMark,
		IsDisplayHighestDivisionGrade,IsDisplayParentName,CoScholasticScopeId,SubjectGroupPerPage,IsDisplayTeacherSign,
		IsDisplayPrincipalSign,PercentileScopeId,CoScholasticGradeSetId,IsExcludeAbsentTotal,CoScholasticTitle,
		IsDisplayMonthlyAttendance,IsDisplayImageHeader,DecimalFormat,IsDisplayTotalMark,IsDisplayResultIndicator,
		IsRemovePercentageForFail,Remark1Caption,Remark2Caption,Remark3Caption,TeacherSignCaption,
		PrincipalSignCaption,ParentSignCaption,IsSubjectWeightage,Id,IsDisplayActivityGrade,IsAllExamPassRequired,HeaderAdjustment,IsPublishExamSchedule,LinkExamId,OverallPercentageForGrace,MinimumGracePercetage,GraceMaxMark,KrupaMaxMark,IsApplySiddhiKrupa,IsDisplayGraph,IsGenerateRankNo
	from sAssessment.tExamMaster Where BatchId = @rFromBatchId AND ((ClassId = @rClassId) OR (@rClassId=0))
	
	 SET @lNextNumber  = @lCount + @lNextNumber 
	  EXECUTE sCommon.pTableRowIdModify @rOrgId, @rTableTitle = 'sAssessment.tExamMaster', @rCurrentNumber = @lNextNumber 

	
	
	
	select @lExamDetailCount =count (Ed.id) from sAssessment.tExamDetail Ed INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId Where ((Em.ClassId=@rClassId) OR (@rClassID=0)) and Em.batchId=@rFromBatchId
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sAssessment.tExamDetail', 0, 1, 1,@outNextNumber = @lExamdetailNextNumber output

	
	--Delete EC from sAssessment.tExamDetail EC INNER JOIN sAssessment.tExamMaster EM ON EM.Id=EC.ExamID where ((Em.ClassId = @rClassId) OR (@rClassID=0)) AND EM.BatchId=@rToBatchID
	--Add TobatchId in SubQuery because it get multiple records of batch 
	Insert into sAssessment.tExamDetail
	( 
		Id,ExamId,ClassSubjectId,Maximum,Minimum,IsIncludeInTotal,IsDisplayInMarksheet,IsShowSubjectGrade,DisplayOrder,GradeSetId,ExamDate,ExamTime,ExamTopic,UpdatedUserId,UpdatedDateTime,NoOfQuestion,IsShowSubjectMark
	)  
	Select
		@lExamdetailNextNumber+ ROW_NUMBER() OVER(ORDER BY ClassSubjectId),
		ExamId = (SELECT Id FROM sAssessment.tExamMaster E1 WHERE E1.OldImportExamId = Ed.ExamId and E1.ClassId=@rClassId AND E1.BatchId = @rToBatchId)
		,ClassSubjectId,Maximum,Minimum,IsIncludeInTotal,IsDisplayInMarksheet,IsShowSubjectGrade,DisplayOrder,ED.GradeSetId,ExamDate,ExamTime,ExamTopic,ED.UpdatedUserId,sCommon.fGetDate(),NoOfQuestion,IsShowSubjectMark
	from sAssessment.tExamDetail Ed INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
	Where ((Em.ClassId=@rClassId) OR (@rClassID=0)) and Em.batchId=@rFromBatchId
	
	SET @lExamdetailNextNumber  = @lExamDetailCount + @lExamdetailNextNumber 
	EXECUTE sCommon.pTableRowIdModify @rOrgId, @rTableTitle = 'sAssessment.tExamDetail', @rCurrentNumber = @lExamdetailNextNumber 
	
	Select  @lExamCombineCount = count(EC.id) from sAssessment.tExamCombine Ec INNER JOIN sAssessment.tExamMaster EM ON EM.Id= EC.ExamId
	WHere ((Em.ClassId =@rClassId) OR (@rClassID=0)) ANd BatchId =@rFromBatchId
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sAssessment.tExamCombine', 0, 1, 1,@outNextNumber = @lExamCombineNextNumber output
	
	--Delete EC from sAssessment.tExamCombine EC INNER JOIN sAssessment.tExamMaster EM ON EM.Id= EC.ExamId Where Em.batchId=@rToBatchId AND ((Em.ClassId=@rClassID) OR (@rClassID=0))  
	--Add TobatchId in SubQuery because it get multiple records of batch
	Insert into sAssessment.tExamCombine
	(
		Id,ExamId,SubExamId,weightage,ExamOrder,CreatedUserId,CreatedDateTime,UpdatedUserId,UpdatedDateTime
	)
	Select
		@lExamCombineNextNumber+ROW_NUMBER() OVER(ORDER BY ExamId),ExamId = (Select Id from sAssessment.tExamMaster E1 where E1.OldImportExamId = Ec.ExamId  and E1.ClassId=@rClassId AND E1.BatchId = @rToBatchId),
		SubExamId = (Select Id from sAssessment.tExamMaster E1 where E1.OldImportExamId = Ec.SubExamId and E1.ClassId=@rClassId AND E1.BatchId = @rToBatchId),weightage,ExamOrder,EC.CreatedUserId,SCommon.fGetdate(),EC.UpdatedUserId,sCommon.fGetDate()
	From sAssessment.tExamCombine EC INNER JOIN sAssessment.tExamMaster EM on EM.Id =EC.ExamId where EM.BatchId=@rFromBatchId and ((EM.ClassId=@rClassId) OR (@rClassID=0))
	
	SET @lExamCombineNextNumber  = @lExamCombineCount + @lExamCombineNextNumber 
	EXECUTE sCommon.pTableRowIdModify @rOrgId, @rTableTitle = 'sAssessment.tExamCombine', @rCurrentNumber = @lExamCombineNextNumber 

	--Add TobatchId in SubQuery because it get multiple records of batch
	--DElete EC From sAssessment.tExamCombineSubject EC INNER JOIN sAssessment.tExamMaster  EM ON EM.Id=EC.ExamId WHere ((Em.ClassID =@rClassId) OR (@rClassId=0)) AND EM.BatchId=@rToBatchId
	Insert into sAssessment.tExamCombineSubject
	(
		ExamId,SubExamId,ClassSubjectId,SubjectWeightage
	)
	Select 
		ExamId = (Select Id from sAssessment.tExamMaster E1  Where E1.OldImportExamId = Ec.ExamId AND E1.BatchId = @rToBatchId),
		
		SubExamId =(select Id from sAssessment.tExamMaster E1 Where  E1.OldImportExamId= ec.SubExamId AND E1.BatchId = @rToBatchId),
		ClassSubjectId,SubjectWeightage
	from sAssessment.tExamCombineSubject EC INNER JOIN sAssessment.tExamMaster EM ON EM.Id= EC.ExamId where ((EM.ClassId =@rClassId) OR (@rClassId=0)) and Em.BatchID=@rFromBatchId
	
	select 11 as result
COMMIT TRANSACTION		
	 
END
GO
PRINT N'Altering Procedure [sAssessment].[pExamSettingAdd]...';


GO

ALTER PROCEDURE [sAssessment].[pExamSettingAdd]
	(
		--@rExamSettingXml nvarchar(MAX),
		--@rOrgId int

		@rExamSettingXml nvarchar(max),
		@rExamSettingTypeId int,
		@rCreatedUserId bigint
	)
AS

SET NOCOUNT ON

BEGIN
SET @rExamSettingXml=REPLACE(@rExamSettingXml,'&','AND')
DECLARE @lInterrorCode INT,
			@intDoc INT
DECLARE @lNextNumber BIGINT			
BEGIN TRY
BEGIN TRANSACTION	
	EXECUTE @lInterrorCode = sp_xml_preparedocument @intDoc OUTPUT, @rExamSettingXml
	
	IF(@rExamSettingTypeId = 1)
	BEGIN
		UPDATE sAssessment.tExamMaster
		SET 
			--IsProcessResult = E.IsProcessResult,
			IsNegativeMarks = E.IsNegativeMarks,
			IsLockForEdit = E.IsLockForEdit,
			IsPublished = E.IsPublished,
			IsPublishExamSchedule = E.IsPublishExamSchedule,
			ReportId = CASE WHEN E.IsPublished = 1 THEN 20438 ELSE 0 END,
			--(CASE WHEN E.IsPublished = 1 THEN ReportId = 20438 ELSE '' END),
			UpdatedUserId = @rCreatedUserId,
			UpdatedDateTime = sCommon.fGetDate()
		FROM (
		SELECT
			ExamId,
			IsProcessResult,
			IsNegativeMarks,
			IsLockForEdit,
			IsPublished,
			IsPublishExamSchedule
			FROM OPENXML (@intDoc, '/Table/ExamSetting', 1)
		WITH
		(
			ExamId bigint,
			IsProcessResult bit ,
			IsNegativeMarks bit ,
			IsLockForEdit bit,
			IsPublished bit,
			IsPublishExamSchedule bit
		))E 
		Where sAssessment.tExamMaster.Id = E.ExamId
	END
	
	ELSE IF(@rExamSettingTypeId = 2)
	BEGIN
		UPDATE sAssessment.tExamMaster
		SET 
			IsGrade = E.IsGrade,
			IsPercentile = E.IsPercentile,
			IsRankNo = E.IsRankNo,
			IsGenerateRankNo = E.IsGenerateRankNo,
			IsPercentage = E.IsPercentage,
			IsRemovePercentageForFail = E.IsFailPercentageZero,
			IsSubjectPercentile = E.IsSubjectPercentile,
			IsResultStatus = E.IsDisplayResultStatus,
			IsAllExamPassRequired = E.IsAllExamPassRequired,
			IsExcludeAbsentTotal = E.IsExcludeAbsentTotal,
			UpdatedUserId = @rCreatedUserId,
			UpdatedDateTime = sCommon.fGetDate()
		FROM (
		SELECT
			ExamId,
			IsGrade,
			IsPercentile,
			IsRankNo,
			IsGenerateRankNo,
			IsPercentage,
			IsFailPercentageZero,
			IsSubjectPercentile,
			IsDisplayResultStatus,
			IsAllExamPassRequired,
			IsExcludeAbsentTotal
			FROM OPENXML (@intDoc, '/Table/ExamSetting', 1)
		WITH
		(
			ExamId bigint,
			IsGrade bit,
			IsPercentile bit,
			IsRankNo bit,
			IsGenerateRankNo bit,
			IsPercentage bit,
			IsFailPercentageZero bit,
			IsSubjectPercentile bit,
			IsDisplayResultStatus bit,
			IsAllExamPassRequired bit,
			IsExcludeAbsentTotal bit
		))E 
		Where sAssessment.tExamMaster.Id = E.ExamId
	END
	
	ELSE IF(@rExamSettingTypeId = 3)
	BEGIN
		UPDATE sAssessment.tExamMaster
			SET 
				IsDisplayPhoto = E.IsDisplayPhoto,
				IsDisplaySchoolName = E.IsDisplaySchoolName,
				IsDisplayBirthDate = E.IsDisplayBirthDate,
				IsDisplayParentName = E.IsDisplayParentName,
				IsDisplayHeightWeight = E.IsDisplayHeightWeight,
				IsDisplayGradeString = E.IsDisplayGradeString,
				IsDisplayTotalMark = E.IsDisplayTotalMark,
				IsDisplayResultIndicator = E.IsDisplayResultIndicator,
				IsDisplayHighestDivisionMark = E.IsDisplayHighestDivisionMark,
				IsDisplayHighestDivisionGrade = E.IsDisplayHighestDivisionGrade,
				IsDisplayTeacherSign = E.IsDisplayTeacherSign,
				IsDisplayPrincipalSign = E.IsDisplayPrincipalSign,
				IsDisplayActivityGrade = E.IsDisplayActivityGrade,
				UpdatedUserId = @rCreatedUserId,
				UpdatedDateTime = sCommon.fGetDate()
			FROM (
			SELECT
				ExamId,
				IsDisplayPhoto ,
				IsDisplaySchoolName ,
				IsDisplayBirthDate ,
				IsDisplayParentName ,
				IsDisplayHeightWeight ,
				IsDisplayGradeString ,
				IsDisplayTotalMark ,
				IsDisplayResultIndicator ,
				IsDisplayHighestDivisionMark ,
				IsDisplayHighestDivisionGrade ,
				IsDisplayTeacherSign ,
				IsDisplayPrincipalSign ,
				IsDisplayActivityGrade 
				FROM OPENXML (@intDoc, '/Table/ExamSetting', 1)
			WITH
			(
				ExamId bigint,
				IsDisplayPhoto bit,
				IsDisplaySchoolName bit,
				IsDisplayBirthDate bit,
				IsDisplayParentName bit,
				IsDisplayHeightWeight bit,
				IsDisplayGradeString bit,
				IsDisplayTotalMark bit,
				IsDisplayResultIndicator bit,
				IsDisplayHighestDivisionMark bit,
				IsDisplayHighestDivisionGrade bit,
				IsDisplayTeacherSign bit,
				IsDisplayPrincipalSign bit,
				IsDisplayActivityGrade bit
			))E 
			Where sAssessment.tExamMaster.Id = E.ExamId
	END
		
	ELSE
	BEGIN
		UPDATE sAssessment.tExamMaster
			SET 
				IsIncludeCoScholastic = E.IsIncludeCoScholastic,
				IsCoScholasticGradeIndicator = E.IsCoScholasticGradeIndicator,
				IsCoScholasticGradeDesIndicator = E.IsCoScholasticGradeDesIndicator,
				IsCoScholasticGrade = E.IsCoScholasticGrade,
				UpdatedUserId = @rCreatedUserId,
				UpdatedDateTime = sCommon.fGetDate(),
				CoScholasticScopeId = 1
			FROM (
			SELECT
				ExamId,
				IsIncludeCoScholastic ,
				IsCoScholasticGradeIndicator ,
				IsCoScholasticGradeDesIndicator ,
				IsCoScholasticGrade 
				FROM OPENXML (@intDoc, '/Table/ExamSetting', 1)
			WITH
			(
				ExamId bigint,
				IsIncludeCoScholastic bit,
				IsCoScholasticGradeIndicator bit,
				IsCoScholasticGradeDesIndicator bit,
				IsCoScholasticGrade bit
			))E 
			Where sAssessment.tExamMaster.Id = E.ExamId

	END

	EXEC sp_xml_removedocument @intDoc
	COMMIT TRANSACTION
	SELECT 1
	END TRY
	BEGIN CATCH
	ROLLBACK TRANSACTION
	SELECT -1
	END CATCH

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


GO

ALTER PROCEDURE [sAssessment].[pRptExamAdmitcard]
	  
	  @rBatchId int,
	  @rClassId int,
	  @rDivisionId int,
	 -- @rExamId int=0,
	  @rExamSubGroupId int=0,
	  @rCode nvarchar(20),
	  @rFromRollNo int,
	  @rToRollNo int,
	  @rDepartmentId int,
	  @rSubjectId int=0,
	  @rStatusId int=0,
	  @rClassStatusId int=0
	  
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON 
BEGIN 	
	SELECT 		
	       	ESGM.Title AS ExamName,
	       	ISNULL(ED.DisplayOrder,0) as DisplayOrder,
	        ISNULL(ED.ExamDate,sCommon.fGetDate()) as ExamDate,
	        ISNULL(ED.ExamTime,'') as ExamTime,
	        V.SubjectName AS SubjectName,
	        CM.DisplayTitle+' / '+DM.DisplayTitle AS ClassDivision,
	         CM.DisplayTitle AS ClassName,
	         CM.Id As ClassId,
	         DM.Id AS DiVisionId,
	        V.ClassSubjectId AS ClassSubjectId,
	        SA.Name,
	        SA.RollNo,
	        SA.Code,
	        SF.FatherName,
	        So.DateOfBirth,
	        GM.Title AS Gender,
	        EM.Remark1,
	        EM.Remark2,
	        EM.Remark3,
	        SA.AcademicId,
	        SI.StudentPhoto,
	        SF.MotherName,
	        SR. ExamCenter,
	        SR.ExamSeatNo,
	        V.SubjectCode AS SubjectCode,
		
	         
		(CASE EM.IsDisplayImageHeader WHEN 1 THEN
			OI.CertificateHeaderA4 
			ELSE NULL END)AS  MarksheetHeaderA4 ,
			ISNULL(EM.IsDisplayImageHeader,0) AS IsImageHeader,
			EM.IsOnPrePrinted ,
	        --EM.Id As ExamId,
			EM.IsDisplayPhoto,
			SR.ExamBlock,
			EI.EmployeeSign,
			EM.TeacherSignCaption,
			EM.PrincipalSignCaption,
			EM.ParentSignCaption,
			ISNULL(EM.DisplayTitle,'') AS DisplayTitle ,
			ISNULL(ED.ExamTopic,'') AS ExamTopic,
			ISNULL(ED.ExamLanguage,'') AS ExamLanguage,
			ISNULL(SA.OrganizationName,'') AS OrganizationName,
			ISNULL(SA.SUId,'') AS SUId ,
			EM.IsDisplayPrincipalSign AS IsDisplayPrincipalSign,
			ISNULL(SO.UIDNumber,'') AS UId ,
			CSM.Title As CasteCategory ,
		    ISNULL(SO.AdhaarNumber,'') AS AdhaarNumber

			FROM
			sStudent.vStudentAcademic SA 
			INNER JOIN sSetup.tClassMaster CM ON SA.ClassId=CM.Id 
			INNER JOIN sSetup.tDivisionMaster DM ON DM.ClassId=CM.Id AND SA.DivisionId=DM.Id
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id  ANd Em.BatchId=SA.BatchId 
			INNER JOIN sAssessment.tExamSubGroupMaster	ESGM ON ESGM.Id = EM.ExamSubGroupId
			INNER JOIN sAssessment.tExamGroupMaster EGM ON EGM.Id=ESGM.ExamGroupId
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			LEFT JOIN sSetup.vClassSubject V ON V.ClassSubjectId = Ed.ClassSubjectId  
			LEFT JOIN sAssessment.tOptionalSubject OS on OS.AcademicId=SA.AcademicId and OS.ClassSubjectId=V.ClassSubjectId
			LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId=SA.StudentId  
			LEFT JOIN sStudent.tStudentOther SO ON So.StudentId=SA.StudentId  
			LEFT JOIN sCommon.tGenderMaster GM ON GM.Id=So.GenderId   
			LEFT JOIN  sStudent.tStudentImages SI ON SI.StudentId=SA.StudentId 
			LEFT JOIN sAssessment.tStudentRemark SR ON SR.ExamId=EM.Id AND SR.AcademicId=SA.AcademicId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=SA.OrgId
			LEFT JOIN sSetup.tOrgImages OI ON OI.Orgid = OM.Id
			LEFT JOIN sHrm.tEmployeeImages EI ON EI.EmployeeId = DM.InchargeEmployeeId
			LEFT JOIN sCommon.tCastCategoryMaster CSM ON CSM.Id=SO.CastCategoryId
	WHERE 
			SA.BatchId = @rBatchId 
		 AND (SA.ClassId=@rClassId OR @rClassId=0) 
		 AND (SA.DivisionId=@rDivisionId OR @rDivisionId=0)
		 AND ((SA.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
		 AND ((SA.RollNo <= @rToRollNo) OR (@rToRollNo=0))
		 AND ((ESGM.Id = @rExamSubGroupId) OR (@rExamSubGroupId = 0))	
	     AND ((SA.Code=@rCode) OR (@rCode=''))
	     AND (SA.DepartmentId=@rDepartmentId OR @rDepartmentId=0) 
	     AND (V.SubjectId=@rSubjectId OR @rSubjectId=0) 
	    AND ((V.IsOptional = 1 AND  isnull(OS.AcademicId,0) <> 0) OR (V.IsOptional = 0))
		AND ((SA.StatusId=@rStatusId) OR (@rStatusId = 0))
		AND (SA.ClassStatusId=@rClassStatusId OR @rClassStatusId=0)
	
	Order by ED.ExamDate
END
GO
PRINT N'Altering Procedure [sAssessment].[pRptResultListGet]...';


GO
ALTER PROCEDURE [sAssessment].[pRptResultListGet]
	 
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 --@rOrgId smallint,
	 @rBatchId int,
	 @rClassId int,
	 @rDivisionId int,
	 @rExamId int=0,
	 @rExamSubGroupId int=0,
	 @rCode nvarchar(20)='',
	 @rFromRollNo int=0,
	 @rToRollNo int=0,
	 @rFromRank int=0,
	 @rToRank int=0,
	 @rGrade nvarchar(20)='',
	 @rAcademicId bigint=0,
	 @rFromPercentage decimal(5,2)=0,
	 @rToPercentage decimal(5,2)=0,
	 @rDepartmentid int=0,
	 @rStatus int =1,
	 @rGenderId int,
	 @rClassStatusId int=0,
	 @rResultStatus nvarchar(20)='',
	 @rMultiCode nvarchar(max)='',
	 @rOrderBy int = 0
	
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 

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

	SELECT 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			Convert(nvarchar(20),A.Id) AS   AcademicIdText,	
			CONVERT (nvarchar(20),@rExamId) AS ExamIdText,
			CONVERT (nvarchar(20),EM.GradeSetId) AS GradeSetIdText,
			CONVERT (nvarchar(20),@rBatchId) AS BatchIdText,
			CONVERT(nvarchar(20),ISNULL(EM.IsDisplayMonthlyAttendance,0))AS IsDisplayMonthlyAttendanceText,
			ESGM.Title AS Exam,
			SM.Code,
			[sStudent].[fStudentNameGet](SM.FirstName , SM.MiddleName, SM.LastName,OM.StudentNameFormatId ) AS Name,
			A.RollNo,
			R.AcademicId,
			CM.DisplayTitle+'/'+DM.DisplayTitle AS Class,
			DM.DisplayTitle AS Division,
			DM.Id AS DivisionId,
			DM.OrderIndex AS DivisinOrderIndex,
			R.TotalMarks,
			R.TotalObtain,
			R.Percentage,
			R.RankNumber,
			R.ResultGrade,
			EM.IsMarksInDecimal,
			(CASE EM.IsDisplayPhoto WHEN 1 THEN
				SI.StudentPhoto
				ELSE NULL END)AS StudentPhoto,
			EM.DisplayTitle,
			OM.SmallAddress1,
			R.ResultRemark,
			R.OtherRemark1,
			EM.Remark1,
			EM.Remark2,
			EM.Remark3,
			SR.ResultRemark2,
			EM.GradeSetId,
			R.ResultStatus,
			SR.ResultRemark1,
			REPLICATE(',',EM.FooterAdjustment) AS FooterAdjustmentText,
			(CASE EM.IsDisplayTeacherSign WHEN 1 THEN
				EI.EmployeeSign
				ELSE NULL END ) AS EmployeeSign,
			EM.IsDisplayPrincipalSign,
			EM.IsDisplayTeacherSign,
			EM.IsOnPrePrinted,
			EM.IsDisplayPhoto,
			ISNULL(SR.PresentDays,0)AS PresentDays,			
			ISNULL(SR.TotalDays,0)AS TotalDays,
			EM.DecimalFormat,
			CM.Id AS ClassId,
			@rOrderBy AS OrderBy,
			CONVERT(bit,@DecimalConfigId) AS IsDecimal
      
	FROM 
			sAssessment.tExamMaster EM
			INNER JOIN sAssessment.tResult R ON EM.Id=R.ExamId			
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId 
			INNER JOIN sStudent.tAcademic A ON R.AcademicId=A.Id
			 
			INNER JOIN sStudent.tStudentMaster SM ON A.StudentId=SM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=A.OrgId
			INNER JOIN sSetup.tClassMaster CM ON CM.Id=EM.ClassId
			INNER JOIN sSetup.tDivisionMaster DM ON A.DivisionId=DM.Id
			LEFT JOIN sHrm.tEmployeeImages EI ON EI.EmployeeId = DM.InchargeEmployeeId
			LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId=SM.Id
			LEFT JOIN sAssessment.tStudentRemark SR ON SR.AcademicId=A.Id AND SR.ExamId = EM.Id
			LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId=A.StudentId
			
			 
	WHERE 
			
		      EM.BatchId = @rBatchId 
		AND (EM.ClassId=@rClassId OR @rClassId=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 ((ESGM.Id=@rExamSubGroupId )	OR (@rExamSubGroupId = 0))
		AND ((EM.Id=@rExamId )	OR (@rExamId = 0))
		AND ((SM.Code=@rCode) OR (@rCode=''))
		AND ((A.Id =@rAcademicId) OR (@rAcademicId=0))
		
		AND ((R.Percentage >=@rFromPercentage) OR (@rFromPercentage=0))
		AND ((R.Percentage <=@rToPercentage) OR (@rToPercentage=0))
		AND ((CM.DepartmentId = @rDepartmentId) OR (@rDepartmentId=0))
		ANd ((SM.StatusId= @rStatus) OR (@rStatus = 0))
		AND ((SO.GenderId=@rGenderId) OR (@rGenderId=0))
		AND (A.ClassStatusId=@rClassStatusId OR @rClassStatusId=0)
		AND ((R.ResultStatus=@rResultStatus) OR (@rResultStatus=''))
		AND (ISNULL(SM.Code,0) IN( SELECT cast(item as nvarchar(20)) FROM  sCommon.fnsplit(@rMultiCode,',')) OR @rMultiCode='')

		ORDER BY 
			CASE @rOrderBy WHEN 0 THEN SM.Code END , 
			CASE @rOrderBy WHEN 1 THEN R.RankNumber END , 
			CASE @rOrderBy WHEN 2 THEN A.RollNo END, 
			CASE @rOrderBy WHEN 3 THEN SM.FirstName END,
			CASE @rOrderBy WHEN 4 THEN R.TotalObtain END
			
END
GO
PRINT N'Altering Procedure [sAssessment].[pRptResultSheetOnlyCoScholasticCombineGet]...';


GO
ALTER PROCEDURE [sAssessment].[pRptResultSheetOnlyCoScholasticCombineGet]
	 
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 @rSubjectId int,
	 @rBatchId int,
	 @rClassId int,
	 @rDivisionId int,
	 @rExamId int,
	 @rCode nvarchar(20),
	 @rFromRollNo int,
	 @rToRollNo int,
	 @rFromRank int=0,
	 @rToRank int=0,
	 @rGrade nvarchar(20),
	 @rStatusId int,
	 @rClassStatusId int=0,
	 @rMultiCode nvarchar(max)=''
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
 
 --select * from  dbo.tTempCoScholasticCombine
 
DECLARE @GradeString nvarchar(1000),
@GradeSetId int, 
@Exam1 int,
@Exam2 int

SELECT @Exam1 = SubExamId From sAssessment.tExamCombine WHERE ExamId = @rExamId AND ExamOrder = 1
SELECT @Exam2 = SubExamId From sAssessment.tExamCombine WHERE ExamId = @rExamId AND ExamOrder = 2
SELECT @GradeSetId = GradesetId FROM sAssessment.tExamMaster WHERE Id = @rExamId
SELECT @GradeString = [sAssessment].[fGradeStringGet](@GradeSetId)  

DECLARE @lOrgId int=0
SELECT @lOrgId=OrgId FROM sSetup.tBatchMaster WHERE Id=@rBatchId
DECLARE @DecimalConfidId nvarchar(20)=''
SELECT @DecimalConfidId =ItemValue From sConfig.tConfigurationSetup WHERE ConfigurationId = 496 AND SourceTypeId = 1016 AND SourceId = @lOrgId
 
 	CREATE TABLE #TempExam 
	(
		AcademicId bigint,
		ExamId int,
		CCECSId int,
		CCECSGroupId int,
		CoSubject nvarchar(150),
		CoSubjectGroup nvarchar(150),
		CoSubjectOrderIndex int,
		CoSubjectGroupOrderIndex int,
		Grade1 nvarchar(10) NULL,
		GradeIndicator1 nvarchar(50) NULL,
		DescriptiveIndicator1 nvarchar(200) NULL,
		Grade2 nvarchar(10) NULL,
		GradeIndicator2 nvarchar(50) NULL,
		DescriptiveIndicator2 nvarchar(200) NULL
	 )
	 
 

 INSERT INTO  #TempExam 
	(
	AcademicId,
	ExamId,
	CCECSId,
	CCECSGroupId,
	CoSubject,
	CoSubjectGroup,
	CoSubjectOrderIndex,
	CoSubjectGroupOrderIndex
	
	)
 SELECT A.Id,@rExamId,CS.Id,CS.CCECAGroupId,CS.Title,csg.Title,CS.OrderIndex,CSG.OrderIndex 
 FROM sStudent.tAcademic A INNER JOIN
 sAssessment.tCCECSClass C ON A.ClassId = C.ClassId  
 INNER JOIN sAssessment.tCCECSMaster CS ON C.CCECSGroupId = cs.CCECAGroupId
 INNER JOIN sAssessment.tCCECSGroupMaster CSG ON CS.CCECAGroupId = CSG.Id 
 WHERE DivisionId = @rDivisionId
 AND A.BatchId = @rBatchId
 
UPDATE
    TE
SET
    TE.Grade1 = ES.Grade,
    TE.GradeIndicator1 = ES.GradeIndicator,
    TE.DescriptiveIndicator1 = ES.DescriptiveIndicator
FROM
    #TempExam TE
    INNER JOIN sAssessment.tCCECSExamScore ES
    ON TE.AcademicId = ES.AcademicId AND   
    TE.CCECSId = ES.CCECSId
    AND ES.ExamId = @Exam1
    
  UPDATE
    TE
SET
    TE.Grade2 = ES.Grade,
    TE.GradeIndicator2 = ES.GradeIndicator,
    TE.DescriptiveIndicator2 = ES.DescriptiveIndicator
FROM
    #TempExam TE
    INNER JOIN sAssessment.tCCECSExamScore ES
    ON TE.AcademicId = ES.AcademicId AND   
    TE.CCECSId = ES.CCECSId
    AND ES.ExamId = @Exam2

	SELECT 
			ESGM.Title AS Exam,
			StuM.Code,
			StuM.FirstName+' '+StuM.MiddleName+' '+StuM.LastName AS Name,
			A.RollNo,
			TE.AcademicId,			 
			ISNULL(R.ResultStatus,'') AS ResultStatus,
			CM.DisplayTitle AS Class,
			DM.DisplayTitle AS Division,
			ISNULL(R.TotalMarks,0) AS TotalMarks ,
			ISNULL(R.TotalObtain,0) AS TotalObtain,
			ISNULL(R.Percentage,0) AS Percentage,
			ISNULL(R.RankNumber,0) AS RankNumber,
			ISNULL(R.ResultGrade,'') AS ResultGrade,
			ISNULL(R.Percentile,0) AS Percentile,		 
			ISNULL(R.Id ,0) AS ResultId, 
			EM.IsMarksInDecimal,
			--SM.OrderIndex AS SubjectCode,	 
			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,
			@GradeString AS GradeString,
			EM.IsDisplayGradeString,
			TE.CoSubject,
			TE.CoSubjectGroup,
			TE.CoSubjectGroupOrderIndex,
			TE.CoSubjectOrderIndex,
			TE.Grade1,
			TE.GradeIndicator1,
			TE.DescriptiveIndicator1,
			TE.Grade2,
			TE.GradeIndicator2,
			TE.DescriptiveIndicator2,
			SF.FatherName,
			SF.MotherName,
			EM.IsDisplayPrincipalSign,
			Em.IsDisplayTeacherSign,
			(CASE EM.IsDisplayTeacherSign WHEN 1 THEN
			EI.EmployeeSign
			ELSE NULL END ) AS EmployeeSign,
			SR.StudentHeight,
			ISNULL(SR.TotalDays,0)AS TotalDays,
			ISNULL(SR.PresentDays,0)AS PresentDays,
			SR.StudentWeight,
			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,
			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,
			SR.ResultRemark3,
			SR.ResultRemark1,
			Sr.ResultRemark2,
			(CASE EM.IsDisplayImageHeader WHEN 1 THEN
			OI.CertificateHeaderA4 
			ELSE NULL END)AS  MarksheetHeaderA4,
			ISNULL(EM.IsDisplayImageHeader,0) AS IsImageHeader,
			CONVERT(bit, @DecimalConfidId) AS IsDecimal
	FROM 
			#TempExam TE INNER JOIN 	 
			sAssessment.tExamMaster EM ON EM.Id=TE.ExamId 		 
			INNER JOIN sStudent.tAcademic A ON A.Id=TE.AcademicId
			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 sStudent.tStudentImages SI ON SI.StudentId=StuM.Id
			LEFT JOIN sAssessment.tStudentRemark SR ON A.Id = SR.AcademicId AND EM.Id = SR.ExamId
			LEFT JOIN sStudent.tStudentFamily SF ON SF.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.tEmployeeImages EI ON EI.EmployeeId = Dm.InchargeEmployeeId
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id = EM.EXAMSUBGROUPID			 
			LEFT JOIN sAssessment.tResult R	ON TE.AcademicId = R.AcademicId AND TE.ExamId = R.ExamId
			LEFT JOIN 	sCommon.tBloodGroupMaster BGM ON BGM.Id=So.BloodGroupId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=A.OrgId
			LEFT JOIN sSetup.tOrgImages OI ON OI.Orgid = OM.Id
	WHERE 
			EM.BatchId = @rBatchId 
			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 (TE.ExamId = @rExamId)
			AND ((StuM.Code=@rCode) OR (@rCode=''))		
			AND ((StuM.StatusId=@rStatusId)OR(@rStatusId=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 A.RollNo,TE.CoSubjectGroupOrderIndex,TE.CoSubjectOrderIndex 
			--AND A.id = 1005000000007



		--SELECT 
		--	'' AS Exam,
		--	'' AS Code,
		--	'' AS Name,
		--	0 AS RollNo,
		--	CONVERT(bigint,0) AS AcademicId,			 
		--	'' AS ResultStatus,
		--	'' AS Class,
		--	'' AS Division,
		--	CONVERT(decimal ,0) AS TotalMarks ,
		--	CONVERT(decimal ,0) AS TotalObtain,
		--	CONVERT(decimal ,0) AS Percentage,
		--	0 AS RankNumber,
		--	'' AS ResultGrade,
		--	CONVERT(decimal ,0) AS Percentile,		 
		--	CONVERT(bigint ,0) AS ResultId, 
		--	CONVERT(bit ,0)IsMarksInDecimal,
		--	--SM.OrderIndex AS SubjectCode,	 
		--	'' AS Remark1,
		--	'' AS Remark2,
		--	'' AS Remark3,
		--	'' AS DisplayTitle,
		--	CONVERT(bit ,0) AS IsRankNo, 
		--	CONVERT(bit ,0) AS IsGrade,
		--	CONVERT(bit ,0) AS IsPercentile,
		--	CONVERT(bit ,0) AS IsPercentage,
		--	CONVERT(bit ,0) AS IsSubjectPercentile,
		--	CONVERT(bit ,0) AS IsProcessResult,
			 
		--	CONVERT(bit ,0) AS IsNegativeMarks,
		--	CONVERT(bit ,0) AS IsIncludeCoScholastic,
		--	CONVERT(bit ,0) AS IsOnPrePrinted,
		--	CONVERT(bit ,0) AS IsDisplayPhoto,
		--	CONVERT(bit ,0) AS IsDisplayBirthDate,
		--	CONVERT(bit ,0) AS IsLockForEdit,
		--	CONVERT(bit ,0) AS IsDisplaySchoolName,			
		--	CONVERT(bit ,0) AS IsDisplayAttendance,
		--	CONVERT(bit ,0) AS IsDisplayHeightWeight,
		--	CONVERT(bit ,0) AS IsResultStatus,
		--	'' AS FooterAdjustmentText,
		--	'' AS DetailAdjustmentText,
		--	0 AS FooterAdjustment,
		--	0 AS DetailAdjustment,
		--	'' AS ResultRemark,
		--	CONVERT(date , null) AS DateOfBirth,
		--	CONVERT(decimal ,0) AS HeightTerm1,
		--	CONVERT(decimal ,0) AS WeightTerm1,
		--	CONVERT(decimal ,0) AS HeightTerm2,
		--	CONVERT(decimal ,0) AS WeightTerm2,
		--	CONVERT(decimal ,0) AS HeightAnnual,
		--	CONVERT(decimal ,0) AS WeightAnnual,
		--	0 AS PresentDaysTerm1,
		--	0 AS PresentDaysTerm2,
		--	0 AS PresentDaysAnnual,
		--	0 AS TotalDaysTerm1,
		--	0 AS TotalDaysTerm2,
		--	0 AS TotalDaysAnnual,
		--	CONVERT(tinyint ,0) AS TermScopeId,
		--	CONVERT(varbinary ,0) AS StudentPhoto,
		--	'' AS GradeString,
		--	CONVERT(bit ,0) AS IsDisplayGradeString,
		--	'' AS CoSubject,
		--	'' AS CoSubjectGroup,
		--	0 AS CoSubjectGroupOrderIndex,
		--	0 AS CoSubjectOrderIndex,
		--	'' AS Grade1,
		--	'' AS GradeIndicator1,
		--	'' AS DescriptiveIndicator1,
		--	'' AS Grade2,
		--	'' AS GradeIndicator2,
		--	'' AS DescriptiveIndicator2,
		--	'' AS FatherName,
		--	'' AS MotherName,
		--	CONVERT(bit ,0) AS IsDisplayPrincipalSign,
		--	CONVERT(bit ,0) AS IsDisplayTeacherSign,
		--	CONVERT(varbinary ,0) AS EmployeeSign ,
		--	CONVERT(decimal ,0) AS StudentHeight,
		--	CONVERT(decimal ,0) AS TotalDays,
		--	CONVERT(decimal ,0) AS PresentDays,
		--	CONVERT(decimal ,0) AS StudentWeight,
		--	'' AS MyGoal,
		--	'' AS AreaOfInterest,
		--	'' AS Responsibility,
		--	'' AS MyInterestHobby,
		--	'' AS MyStrength,
		--	'' AS Achievements,
		--	'' AS DentalHygiene,
		--	'' AS VisionLeft,
		--	'' AS VisionRight,
		--	'' AS TeacherSignCaption,
		--	'' AS PrincipalSignCaption,
		--	'' As ParentSignCaption,
		--	'' As ImprovementArea,
		--	'' AS ProgressArea,
		--	'' As GeneralRemark,
		--	'' AS MyActivity,
		--	'' As ClassTeacherRemark,
		--	'' As HouseRemark,
		--	'' AS BloodGroup,
		--	'' AS ResultRemark3,
		--	'' AS ResultRemark1,
		--	'' AS ResultRemark2,
		--	CONVERT(varbinary ,0) AS MarksheetHeaderA4,
		--	CONVERT(bit ,0) AS IsImageHeader,
		--	CONVERT(bit , 0) AS IsDecimal


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


GO
 


ALTER PROCEDURE [sAssessment].[pRptResultSheetOnlyCoScholasticTermwiseGet]
	 
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 @rSubjectId int,
	 @rBatchId int,
	 @rClassId int,
	 @rDivisionId int,
	 @rExamId int,
	 @rCode nvarchar(20),
	 @rFromRollNo int,
	 @rToRollNo int,
	 @rFromRank int=0,
	 @rToRank int=0,
	 @rGrade nvarchar(20),
	 @rStatusId int,
	 @rClassStatusId int=0,
	 @rMultiCode nvarchar(max)=''
	 
	
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 

DECLARE @GradeString nvarchar(1000),
@GradeSetId int
 
SELECT @GradeSetId = GradesetId FROM sAssessment.tExamMaster WHERE Id = @rExamId
SELECT @GradeString = [sAssessment].[fGradeStringGet](@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

	SELECT 
			ESGM.Title AS Exam,
			StuM.Code,
			StuM.FirstName+' '+StuM.MiddleName+' '+StuM.LastName AS Name,
			A.RollNo,
			CCEEM.AcademicId,
			--RD.Obtain,
			ISNULL(R.ResultStatus,'') AS ResultStatus,
			CM.DisplayTitle AS Class,
			DM.DisplayTitle AS Division,
			ISNULL(R.TotalMarks,0) AS TotalMarks,
			ISNULL(R.TotalObtain,0) AS TotalObtain,
			ISNULL(R.Percentage,0) AS Percentage,
			ISNULL(R.RankNumber,0) AS RankNumber,
			ISNULL(R.ResultGrade,0) AS ResultGrade,
			ISNULL(R.Percentile,0) AS Percentile,
			--SM.Title AS ClassSubject,
			--RD.Id AS ResultDetailId,
			ISNULL(R.Id,0) AS ResultId,
			--CS.Id AS SubjectId,
			--ED.Maximum,
			--RD.SubjectGrade,
			EM.IsMarksInDecimal,
			--SM.OrderIndex AS SubjectCode,
			--SM.Code AS SubjectCode,
			--SM.OrderIndex AS SubjectOrderIndex,
			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,
			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,
			@GradeString AS GradeString,
			CCEEM.Grade,
			CCEEM.GradeIndicator,
			CCEEM.DescriptiveIndicator,
			CCEM.Title AS CoSubject,
			CCEM.OrderIndex AS CoOrderIndex,
			CCEGM.Title AS CoSubjectGroup,
			CCEGM.OrderIndex AS CoOrderIndexGroup,
			EM.IsDisplayPrincipalSign,
			Em.IsDisplayTeacherSign,
			(CASE 	EM.IsDisplayTeacherSign WHEN 1 THEN
				EI.EmployeeSign
			ELSE NULL END)AS EmployeeSign,
			SR.StudentHeight,
			ISNULL(SR.TotalDays,0)AS TotalDays,
			ISNULL(SR.PresentDays,0)AS PresentDays,
			SR.StudentWeight,
			EM.IsCoScholasticGrade,
			EM.IsCoScholasticGradeIndicator,
			EM.IsCoScholasticGradeDesIndicator,
				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,
		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.VisionLeft,'') AS VisionLeft,
		ISNULL(SR.VisionRight,'') AS VisionRight,
		SR.ResultRemark1,
		SR.ResultRemark2,
		EM.IsDisplayGradeString,
		(CASE EM.IsDisplayImageHeader WHEN 1 THEN
			OI.CertificateHeaderA4 
			ELSE NULL END)AS  MarksheetHeaderA4,
			ISNULL(EM.IsDisplayImageHeader,0) AS IsImageHeader,

		sAssessment.fGetGradepoint(CCEEM.Grade) AS GradePoint,
		SF.FatherName,
		SF.MotherName,
		EM.IsDisplayParentName,
		CONVERT(bit,@lDecimalConfig) AS IsDecimal
	FROM 
			 
			 
			sAssessment.tCCECSExamScore CCEEM INNER JOIN   
			--INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId
			  sAssessment.tExamMaster EM ON EM.Id=CCEEM.ExamId AND CCEEM.ExamId=@rExamId
			--INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			--INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=CS.SubjectId		
			INNER JOIN sStudent.tAcademic A ON A.Id=CCEEM.AcademicId
			LEFT JOIN sStudent.tAcademicDetail AD ON AD.AcademicId=A.Id
			INNER JOIN sAssessment.tCCECSMaster CCEM ON CCEM.Id=CCEEM.CCECSId
			INNER JOIN sAssessment.tCCECSGroupMaster CCEGM ON CCEGM.Id= CCEM.CCECAGroupId	
			INNER JOIN sStudent.tStudentMaster StuM ON StuM.Id=A.StudentId
			
			LEFT JOIN sAssessment.tStudentRemark SR ON A.Id = SR.AcademicId AND EM.Id = SR.ExamId
			LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId = StuM.Id
		   INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=A.OrgId
			LEFT JOIN sSetup.tOrgImages OI ON OI.Orgid = OM.Id
			LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId=A.StudentId
			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.tEmployeeImages EI ON EI.EmployeeId = Dm.InchargeEmployeeId
			
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id = EM.EXAMSUBGROUPID
			LEFT JOIN sAssessment.tResult R ON R.AcademicId = CCEEM.AcademicId AND R.ExamId = CCEEM.ExamId
			LEFT JOIN 	sCommon.tBloodGroupMaster BGM ON BGM.Id=So.BloodGroupId
	WHERE 
			
		EM.BatchId = @rBatchId 
		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 (CCEEM.ExamId = @rExamId)
		AND ((StuM.Code=@rCode) OR (@rCode=''))		
		AND ((StuM.StatusId=@rStatusId)OR(@rStatusId=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 A.RollNo--,CS.OrderIndex 
		--AND A.id = 1005000000007
END
GO
PRINT N'Altering Procedure [sAssessment].[pRptResultSheetStandardWithAnalysisGet]...';


GO
ALTER  PROCEDURE [sAssessment].[pRptResultSheetStandardWithAnalysisGet]
	 
	 @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),
@GradeSetId int 
 
SELECT @GradeSetId = GradesetId FROM sAssessment.tExamMaster WHERE Id = @rExamId
SELECT @GradeString = [sAssessment].[fGradeStringGet](@GradeSetId) 

DECLARE @lOrgId int=0
SELECT @lOrgId=OrgId FROM sSetup.tBatchMaster WHERE Id=@rBatchId
Declare @DecimalConfigId nvarchar(20)=''
SELECT @DecimalConfigId =ItemValue From sConfig.tConfigurationSetup WHERE ConfigurationId = 496 AND SourceTypeId = 1016 AND SourceId = @lOrgId
 
	SELECT 
			--Convert(nvarchar(20),A.Id) AS AcademicIdText,
			--Convert(nvarchar(20),@rExamId) AS ExamIdText,
			RAD.SubjectHighestClassMark,
			RAD.SubjectHighestDivisionMark,
			RAD.SubjectAverageClassMark,
			RAD.SubjectAverageDivisionMark,
			RAD.SubjectHighestClassGrade,
			RAD.SubjectHighestDivisionGrade,
			RAD.ClassSubjectId,
			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,
			--SM.OrderIndex AS SubjectCode,
			
			--CS.OrderIndex AS SubjectOrderIndex,
			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,
			SR.StudentHeight,
			SR.StudentWeight,		
			ISNULL(SR.PresentDays,0)AS PresentDays,			
			ISNULL(SR.TotalDays,0)AS TotalDays,
			SR.ResultRemark1,
			SR.ResultRemark2,						 
			EM.TermScopeId,
			(CASE EM.IsDisplayPhoto WHEN 1 THEN
				SI.StudentPhoto
				ELSE NULL END)AS StudentPhoto,
			RD.IsPresent,
			@GradeString 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,
			RAN.HighestClassMark,
			RAN.HighestDivisionMark AS DivisionHighestMark,
			RAn.HighestClassGrade,
			RAN.HighestDivisionGrade AS DivisionHighestGrade,
			RAN.AverageClassMark,
			RAn.AverageDivisionMark,
			RAN.DivisionPercentile,
			RAN.ClassPercentile 
			,RAN.TotalStudentClass,
			RAN.TotalStudentDivision,
		 
			RA.ClassRank,
			RA.DivisionRank,
			RD.Remark,
			RA.PassedSubject,
			RA.FailedSubject,
			EMP.Id AS EmployeeId,
			--TSD.EmployeeId,
			EMP.FirstName + ' ' +EMP.MiddleName +' ' +Emp.LastName AS EmployeeName,
			(CASE EM.IsDisplayTeacherSign WHEN 1 THEN
				EI.EmployeeSign
				ELSE NULL END ) AS EmployeeSign,
			EM.IsDisplayPrincipalSign,
			EM.IsDisplayTeacherSign,
			EM.DecimalFormat,
			SR.ResultRemark3,
			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,
			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, 
			ISNULL(EM.IsDisplayImageHeader,0) AS IsImageHeader,
			--(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 ,
			CONVERT(bit,@DecimalConfigId) AS IsDecimal
	FROM 
			 sAssessment.tResultDetail RD
			 INNER JOIN sAssessment.tResult R ON R.Id = RD.ResultId
			 INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId
			 INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId			
			 INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			  INNER JOIN sStudent.tAcademic A ON A.Id=R.AcademicId
			 INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId
			 LEFT JOIN sHrm.tEmployeeImages EI ON EI.EmployeeId = DM .InchargeEmployeeId
			 INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=CS.SubjectId		
			 --Left Join sAcademic.tTeacherSubjectDivision TSD ON TSD.SubjectId = SM.Id AND Tsd.DivisionId=A.DivisionId
			 --AND TSD.EmployeeId = EI.EmployeeId
			 LEFT JOIN sHrm.tEmployeeMaster EMP ON EMP.Id=EI.EmployeeId 
			
			  
			  LEFT JOin sAssessment.tResultAnalysis RA ON RA.AcademicId = A.Id AND RA.ExamId = EM.Id
			  LEFT JOIN sAssessment.tResultAnalysisDivisionDetail RAD ON RAD.ClassSubjectId = CS.Id AND RAD.DivisionId = A.DivisionId AND RAD.ExamId = Em.Id
			  LEFT JOIN sAssessment.tResultAnalysisDivision RAN ON RAN.DivisionId = A.DivisionId AND RAN.ExamId = EM.Id
			   
			  
		      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 sStudent.tStudentImages SI ON SI.StudentId=StuM.Id
			  INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId
			
			  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
			  LEFT JOIN 	sCommon.tBloodGroupMaster BGM ON BGM.Id=So.BloodGroupId
				 
	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,CS.OrderIndex 
			--AND A.id = 1005000000007
END
GO
PRINT N'Altering Procedure [sAssessment].[pRptResultSheetSubjectAcivityMultiExamGet]...';


GO
ALTER PROCEDURE [sAssessment].[pRptResultSheetSubjectAcivityMultiExamGet]
	 
	 @rBuilder1 nvarchar(max)='',
	 @rSubjectId int = 0,
	 @rBatchId int=0,
	 @rClass int=0,
	 @rDivisionId int=0,
	 @rExamId int,
	 @rCode nvarchar(20)='',
	 @rFromRollNo int=0,
	 @rToRollNo int=0,
	 @rFromRank int=0,
	 @rToRank int=0,
	 @rGrade nvarchar(20)='',
	 @rResultId bigint=0,
	 @rStatusId int=0,
	 @rAcademicId bigint=0,
	 @rOrgId int=0,
	 @rMultiCode nvarchar(max)=''

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
 begin
 	

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

Declare @lDecimalConfig nvarchar(20)=''
SELECT @lDecimalConfig =ItemValue From sConfig.tConfigurationSetup WHERE ConfigurationId = 496 AND SourceTypeId = 1016 AND SourceId = @rOrgId
 
--#TempAllExam
	CREATE TABLE #TempAllExam
	(
		AcademicIdText nvarchar(20),
		ExamIdText nvarchar(20),
		CoScholasticScopeIdText nvarchar(20),
		
		AcademicId bigint,
		ExamName Nvarchar(150),
		StudCode NVarchar(20),
		StudentName Nvarchar(150),
		RollNo int,
		
		ResultStatus Nvarchar(50),	
		
		ClassName NVarchar(100),
				
		Division NVarchar(100),
		TotalMark decimal(8,2),
		TotalObtain decimal(8,2),
		Percentage decimal(8,2),
		RankNumber int,
		ResultGrade NVarchar(50),
		
		--MaximumMark1 decimal(8,2),		
		SubjectGrade1 NVarchar(50),
		--Obtain1 decimal(8,2),
		--ExamMaximum1 decimal(8,2),
		IsPresent1 bit,
						
		MaximumMark2 decimal(8,2),	
		SubjectGrade2 NVarchar(50),
		Obtain2 decimal(8,2),
		ExamMaximum2 decimal(8,2),
		IsPresent2 bit,
				
		MaximumMark3 decimal(8,2),
		SubjectGrade3 NVarchar(50),
		Obtain3 decimal(8,2),
		ExamMaximum3 decimal(8,2),
		IsPresent3 bit,		
		
		MaximumMark4 decimal(8,2),	
		SubjectGrade4 NVarchar(50),
		Obtain4 decimal(8,2),
		ExamMaximum4 decimal(8,2),
		IsPresent4 bit,	
				
		MaximumMark5 decimal(8,2),		
		SubjectGrade5 NVarchar(50),
		Obtain5 decimal(8,2),
		ExamMaximum5 decimal(8,2),
		IsPresent5 bit,	
				
		MaximumMark6 decimal(8,2),		
		SubjectGrade6 NVarchar(50),
		Obtain6 decimal(8,2),
		ExamMaximum6 decimal(8,2),
		IsPresent6 bit,	
		
		MaximumMark7 decimal(8,2),		
		SubjectGrade7 NVarchar(50),
		Obtain7 decimal(8,2),
		ExamMaximum7 decimal(8,2),
		IsPresent7 bit,	
		
		MaximumMark8 decimal(8,2),	
		SubjectGrade8 NVarchar(50),
		Obtain8 decimal(8,2),
		ExamMaximum8 decimal(8,2),
		IsPresent8 bit,	
		
		SubjectGradeTerm1 NVarchar(50),
		SubjectGradeTerm2 NVarchar(50),
		IsMarksInDecimal bit,
		column_visible bit,
		--Obtain decimal(5,2),
		Percentile decimal(5,2),
		--ClassSubject nvarchar(100),
		ResultDetailId bigint,
		ResultId bigint,	
		Remark1 nvarchar(1000),
		
		Remark2 nvarchar(300),
		Remark3 nvarchar(300),
		DisplayTitle nvarchar(150),		
		IsRankNo bit, 
		IsGrade bit,
		IsPercentile bit,
		IsPercentage bit,
		IsSubjectPercentile bit,
		IsProcessResult bit,
		IsNegativeMarks bit,
		IsIncludeCoScholastic bit,
		IsOnPrePrinted bit,
		IsDisplayPhoto bit,
		IsDisplayBirthDate bit,
		IsLockForEdit bit,
		IsDisplaySchoolName bit,			
		IsDisplayAttendance bit,
		IsDisplayHeightWeight bit,
		IsResultStatus bit,
		FooterAdjustmentText nvarchar(max),
		DetailAdjustmentText nvarchar(max),
		FooterAdjustment smallint,
		DetailAdjustment smallint,
		ResultRemark nvarchar(200),
		DateOfBirth date,
		HeightTerm1 decimal(5,2),
		WeightTerm1 decimal(5,2),
		HeightTerm2 decimal(5,2),
		WeightTerm2 decimal(5,2),
		HeightAnnual decimal(5,2),
		WeightAnnual decimal(5,2),
		PresentDaysTerm1 smallint,
		PresentDaysTerm2 smallint,
		PresentDaysAnnual smallint,
		TotalDaysTerm1 smallint,
		TotalDaysTerm2 smallint,
		TotalDaysAnnual smallint,
		TotalMarkTerm1 decimal(8,2),
		TotalObtainTerm1 decimal(8,2),
		PercentageTerm1 decimal(8,2),
		RankNumberTerm1 int,
		ResultGradeTerm1 NVarchar(50),
		PercentileTerm1 decimal(8,2),
		ResultStatusTerm1 Nvarchar(20),		   
		TotalMarkTerm2 decimal(8,2),
		TotalObtainTerm2 decimal(8,2),
		PercentageTerm2 decimal(8,2),
		RankNumberTerm2 int,
		ResultGradeTerm2 NVarchar(50),
		PercentileTerm2 decimal(8,2),
		ResultStatusTerm2 Nvarchar(20), 
		TermScopeId tinyint,		 
		StudentPhoto varbinary(max),
		GradeString nvarchar(1000),
		IsDisplayGradeString bit,		 
		IsDisplayInMarksheet bit,
		IsShowSubjectGrade bit,
		IsIncludeInTotal bit,
		ClassSubjectID int,
		SubjectId int,
		--Maximum decimal(5,2),
		SubjectOrderIndex smallint,
		SubjectGrade NVarchar(50),
		SubjectName NVarchar(150),
		SubjectCode Nvarchar(50),	
		SubjectMinimum decimal(8,2),		
		SubjectMaximum decimal(8,2),
		SubjectObtain  decimal(8,2),
		
		Exam1Name Nvarchar(150),		
		TotalMarks1 decimal(8,2),		
		TotalObtain1 decimal(8,2),
		Percentage1 decimal(8,2),
		RankNumber1 int,
		ResultGrade1 NVarchar(50),
		Percentile1 decimal(8,2),
		ResultStatus1 Nvarchar(20),
		
		SubActivityGrade1 nvarchar(50),
		ActivityGrade1 nvarchar(50),
		
		Exam2Name nvarchar(150),	
		TotalMarks2 decimal(8,2),
		TotalObtain2 decimal(8,2),
		Percentage2 decimal(8,2),
		RankNumber2 int,
		ResultGrade2 NVarchar(50),
		Percentile2 decimal(8,2),
		ResultStatus2 Nvarchar(20),
		
		SubActivityGrade2 nvarchar(50),
		ActivityGrade2 nvarchar(50),
		
		Exam3Name nvarchar(150),	
		TotalMarks3 decimal(8,2),
		TotalObtain3 decimal(8,2),
		Percentage3 decimal(8,2),
		RankNumber3 int,
		ResultGrade3 NVarchar(50),
		Percentile3 decimal(8,2),		
		ResultStatus3 Nvarchar(20),
		
		SubActivityGrade3 nvarchar(50),
		ActivityGrade3 nvarchar(50),
		
		Exam4Name nvarchar(150),	
		TotalMarks4 decimal(8,2),
		TotalObtain4 decimal(8,2),
		Percentage4 decimal(8,2),
		RankNumber4 int,
		ResultGrade4 NVarchar(50),
		Percentile4 decimal(8,2),
		ResultStatus4 Nvarchar(20),
		
		SubActivityGrade4 nvarchar(50),
		ActivityGrade4 nvarchar(50),
		
		Exam5Name nvarchar(150),		
		TotalMarks5 decimal(8,2),
		TotalObtain5 decimal(8,2),
		Percentage5 decimal(8,2),
		RankNumber5 int,
		ResultGrade5 NVarchar(50),
		Percentile5 decimal(8,2),
		ResultStatus5 Nvarchar(20),
		
		SubActivityGrade5 nvarchar(50),
		ActivityGrade5 nvarchar(50),
		
		Exam6Name nvarchar(150),	
		TotalMarks6 decimal(8,2),
		TotalObtain6 decimal(8,2),
		Percentage6 decimal(8,2),
		RankNumber6 int,
		ResultGrade6 NVarchar(50),
		Percentile6 decimal(8,2),
		ResultStatus6 Nvarchar(20),
		
		SubActivityGrade6 nvarchar(50),
		ActivityGrade6 nvarchar(50),
		
		Exam7Name nvarchar(150),		
		TotalMarks7 decimal(8,2),
		TotalObtain7 decimal(8,2),
		Percentage7 decimal(8,2),
		RankNumber7 int,
		ResultGrade7 NVarchar(50),
		Percentile7 decimal(8,2),
		ResultStatus7 Nvarchar(20),
		
		--SubActivityGrade7 nvarchar(10),
		
		Exam8Name nvarchar(150),
		TotalMarks8 decimal(8,2),
		TotalObtain8 decimal(8,2),
		Percentage8 decimal(8,2),
		RankNumber8 int,
		ResultGrade8 NVarchar(50),
		Percentile8 decimal(8,2),
		ResultStatus8 Nvarchar(20),
		ResultRemark1 nvarchar(200),
		ResultRemark2 nvarchar(200),
		TotalDays decimal(6, 2),
		PresentDays decimal(6, 2),
		StudentHeight decimal(6,2),
		StudentWeight decimal(6,2),
		ExamSeatNo nvarchar(20),
		ExamId int,
		IsDisplayParentName bit,
		
		FatherName nvarchar(100),
		MotherName nvarchar(100),
		IsShowSubjectMark bit, 
		IsOptionalSubject bit,
		CoScholasticScopeId tinyint,
		IsDisplayPrincipalSign bit,
		IsDisplayTeacherSign bit,
		EmployeeSign varbinary(max),
		
		ActivityName nvarchar(200),
		SubActivityName nvarchar(200),
		SubActivityId int,
		ActivityId Int,
		 SubActivityGrade nvarchar(50),
		 ActivityGrade nvarchar(50),
		SubActivityGradeIndicator nvarchar(50),
		SubActivityDescriptiveIndicator nvarchar(200),
		SubjectActivityOrderIndex Smallint,
		SubActivityOrderIndex smallint,
		ColumnSubjectCount SmallInt,
		MarksheetHeaderA4 varbinary(max),
		IsImageHeader bit,
		Height1 decimal(6,2),
		Height2 decimal(6,2),
		Height3 decimal(6,2),
		Height4 decimal(6,2),
		Height5 decimal(6,2),
		Height6 decimal(6,2),
		Weight1 decimal(6,2),
		Weight2 decimal(6,2),
		Weight3 decimal(6,2),
		Weight4 decimal(6,2),
		Weight5 decimal(6,2),
		Weight6 decimal(6,2),
		TotalDays1 decimal(6, 2),
		PresentDays1 decimal(6, 2),
		TotalDays2 decimal(6, 2),
		PresentDays2 decimal(6, 2),
		TotalDays3 decimal(6, 2),
		PresentDays3 decimal(6, 2),
		TotalDays4 decimal(6, 2),
		PresentDays4 decimal(6, 2),
		TotalDays5 decimal(6, 2),
		PresentDays5 decimal(6, 2),
		TotalDays6 decimal(6, 2),
		PresentDays6 decimal(6, 2),
		MyActivity1 nvarchar(200),
		MyActivity2 nvarchar(200),
		MyActivity3 nvarchar(200),
		MyActivity4 nvarchar(200),
		MyActivity5 nvarchar(200),
		MyActivity6 nvarchar(200),
		GeneralRemark1 nvarchar(200),
		GeneralRemark2 nvarchar(200),
		GeneralRemark3 nvarchar(200),
		GeneralRemark4 nvarchar(200),
		GeneralRemark5 nvarchar(200),
		GeneralRemark6 nvarchar(200),
		PresentAddress nvarchar(500) ,
		MobileNo nvarchar(50),
		House nvarchar(100),
		 
		AttendanceTerm1 decimal(6, 2) ,
		AttendanceTerm2 decimal(6, 2),
		WorkingDaysTerm1 decimal(6, 2),
		WorkingDaysTerm2 decimal(6, 2),
		
		BloodGroup nvarchar(20),
		GradeSetIdText nvarchar(50),
		IsDisplayMonthlyAttendanceText nvarchar(20),
		DentalHygiene nvarchar(200),
		VisionLeft nvarchar(50),
		VisionRight nvarchar(50),
		TeacherSignCaption nvarchar(100),
		PrincipalSignCaption nvarchar(100),
		ParentSignCaption nvarchar(100),
		ParentEmail nvarchar(500),
		MyGoal nvarchar(200),
		MyStrength nvarchar(200),
		MyInterestHobby nvarchar(200),
		AreaOfInterest nvarchar(200),
		Responsibility nvarchar(200),
		Achievements nvarchar(1000),
		ImprovementArea nvarchar(200),
		ProgressArea nvarchar(200),
		MyActivity nvarchar(200),
		ClassTeacherRemark nvarchar(1000),
		ClassTeacherName Nvarchar(100),
		HouseRemark nvarchar(1000),
		GeneralRemark nvarchar(1000),
		FatherContactNo nvarchar(50),
		MotherContactNo nvarchar(50),
		FatherMail nvarchar(max),
		MotherMail nvarchar(max),
		IsDecimal bit,
		Name nvarchar(150)
	)	
	
	 --print 'temp created'    	
	INSERT INTO  #TempAllExam 
	(
	AcademicIdText,
	ExamIdText,
	CoScholasticScopeIdText,
	
	AcademicId,
	ExamName,
	StudCode,
	StudentName,
	RollNo,
	ResultStatus,
	ClassName,
	Division,
	TotalMark,
	TotalObtain,
	Percentage,
	RankNumber,
	ResultGrade,
	IsMarksInDecimal,
	column_visible,
	--Obtain,
	Percentile,
	--ClassSubject,
	ResultDetailId,
	ResultId,

	Remark1,
	Remark2,
    Remark3,
	DisplayTitle,
	IsRankNo, 
	IsGrade,
	IsPercentile,
	IsPercentage,
	IsSubjectPercentile,
	IsProcessResult,
	IsNegativeMarks,
	IsIncludeCoScholastic,
	IsOnPrePrinted,
	IsDisplayPhoto,
	IsDisplayBirthDate,
	IsLockForEdit,
	IsDisplaySchoolName,			
	IsDisplayAttendance,
	IsDisplayHeightWeight,
	IsResultStatus,
	FooterAdjustmentText,
	DetailAdjustmentText,
	FooterAdjustment,
	DetailAdjustment,
	ResultRemark,
	DateOfBirth,
	HeightTerm1,
	WeightTerm1,
	HeightTerm2,
	WeightTerm2,
	HeightAnnual,
	WeightAnnual,
	PresentDaysTerm1,
	PresentDaysTerm2,
	PresentDaysAnnual,
	TotalDaysTerm1,
	TotalDaysTerm2,
	TotalDaysAnnual,
	TermScopeId,
	StudentPhoto,
	GradeString,
	IsDisplayGradeString,	 
	IsDisplayInMarksheet,
	IsShowSubjectGrade,
	IsIncludeInTotal,
	ClassSubjectID,
	SubjectId,
	--Maximum,
	SubjectOrderIndex,
	SubjectGrade,
	SubjectName,
	SubjectCode,
	SubjectMinimum,
	SubjectMaximum,
	SubjectObtain,
	ResultRemark1,
	ResultRemark2,
	TotalDays,
	PresentDays,
	StudentHeight,
	StudentWeight,
	ExamSeatNo,
	ExamId,
	IsDisplayParentName,
	FatherName,
	MotherName,
	IsShowSubjectMark,
	IsOptionalSubject,
	CoScholasticScopeId,
	IsDisplayPrincipalSign,
	IsDisplayTeacherSign,
	EmployeeSign,
	SubActivityGrade,
	ActivityGrade,
	ActivityName,
	SubActivityName,
	SubActivityId,
	ActivityId,
	SubActivityGradeIndicator,
	SubActivityDescriptiveIndicator,
	SubjectActivityOrderIndex,
	SubActivityOrderIndex,
	ColumnSubjectCount,
	MarksheetHeaderA4,
	IsImageHeader,
	PresentAddress,
 	MobileNo,
	House,
	AttendanceTerm1   ,
	AttendanceTerm2  ,
	WorkingDaysTerm1  ,
	WorkingDaysTerm2  ,
	BloodGroup,
	GradeSetIdText,
	IsDisplayMonthlyAttendanceText,
	DentalHygiene,
	VisionLeft,
	VisionRight,
	TeacherSignCaption,
	PrincipalSignCaption,ParentSignCaption,
	ParentEmail,
	MyGoal ,
	MyStrength ,
	MyInterestHobby ,
	AreaOfInterest ,
	Responsibility ,
	Achievements ,
	ImprovementArea ,
	ProgressArea ,
	MyActivity ,
	ClassTeacherRemark ,
	ClassTeacherName ,
	HouseRemark ,
	GeneralRemark ,
	FatherContactNo ,
	MotherContactNo ,
	FatherMail,
	MotherMail,
	IsDecimal,
	Name
	)
	
	SELECT 
		Convert(nvarchar(20),A.Id),
		Convert(nvarchar(20),@rExamId),
		Convert(nvarchar(20),EM.CoScholasticScopeId),
		A.Id,
		ISNULL(ESGM.Title,'') AS EXAMNAME,
		StuM.Code AS StudCode,
		StuM.FirstName+' '+StuM.MiddleName+' '+StuM.LastName AS StudentName,
		A.RollNo,
		R.ResultStatus,
		CM.DisplayTitle AS ClassName,
		DM.DisplayTitle AS Division,
		R.TotalMarks AS TotalMark,
		R.TotalObtain,
		R.Percentage,
		R.RankNumber,
		R.ResultGrade,


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

		ISNULL(EM.Remark1,'') AS Remark1,
		ISNULL(EM.Remark2,'') AS Remark2,
		ISNULL(EM.Remark3,'') AS Remark3,
		EM.DisplayTitle,
		EM.IsRankNo, 
		EM.IsGrade,
		EM.IsPercentile,
		EM.IsPercentage,
		EM.IsSubjectPercentile,
		EM.IsProcessResult,
		EM.IsNegativeMarks,
		EM.IsIncludeCoScholastic,
		EM.IsOnPrePrinted,
		EM.IsDisplayPhoto,
		EM.IsDisplayBirthDate,
		EM.IsLockForEdit,
		EM.IsDisplaySchoolName,			
		EM.IsDisplayAttendance,
		EM.IsDisplayHeightWeight,
		EM.IsResultStatus,
		REPLICATE(',',EM.FooterAdjustment) AS FooterAdjustmentText,
		REPLICATE(',',EM.DetailAdjustment) AS DetailAdjustmentText,
		EM.FooterAdjustment,
		EM.DetailAdjustment,
		ISNULL(R.ResultRemark,'') AS ResultRemark,
		SO.DateOfBirth,
		AD.HeightTerm1,
		AD.WeightTerm1,
		AD.HeightTerm2,
		AD.WeightTerm2,
		AD.HeightAnnual,
		AD.WeightAnnual,
		AD.PresentDaysTerm1,
		AD.PresentDaysTerm2,
		AD.PresentDaysAnnual,
		AD.TotalDaysTerm1,
		AD.TotalDaysTerm2,
		AD.TotalDaysAnnual,
		EM.TermScopeId,
		CASE WHEN EM.IsDisplayPhoto = 1 THEN SI.StudentPhoto ELSE NULL END AS StudentPhoto,
		CASE @GradeStringRemark WHEN '' THEN @GradeString ELSE @GradeStringRemark END AS GradeString,
		EM.IsDisplayGradeString,
		ED.IsDisplayInMarksheet,
		ED.IsShowSubjectGrade,
		ED.IsIncludeInTotal,
	    SAM.ClassSubjectId,
		CS.SubjectId AS SubjectId,
		--ED.Maximum,
		(CASE ISNULL(ED.DisplayOrder,0)
		WHEN 0 THEN CS.OrderIndex
		ELSE ED.DisplayOrder END) AS SubjectOrderIndex,
		
		--SM.OrderIndex AS SubjectOrderIndex,
		RD.SubjectGrade,
		SM.Title AS SubjectName,
		ISNULL(SM.Code,'') AS SubjectCode,
		ED.Minimum,
		ED.Maximum,
		RD.Obtain,
		SR.ResultRemark1,
		SR.ResultRemark2,
		ISNULL(SR.TotalDays,0)AS TotalDays,
		ISNULL(SR.PresentDays,0)AS PresentDays,
		SR.StudentHeight,
		SR.StudentWeight,
		SR.ExamSeatNo,
		@rExamId,
		EM.IsDisplayParentName,
		SF.FatherName,
		SF.MotherName,
		ED.IsShowSubjectMark,
		--EMP.FirstName
		(CASE ISNULL(OS.AcademicId,0)
		WHEN 0 THEN 0
		ELSE 1 END) AS IsOptionalSubject,
		EM.CoScholasticScopeId,
		EM.IsDisplayPrincipalSign,
		Em.IsDisplayTeacherSign,
		(CASE Em.IsDisplayTeacherSign WHEN 1 THEN
			EI.EmployeeSign
			ELSE NULL END ) AS EmployeeSign,
		SSA.Grade AS SubActivityGrade,
		ISNULL(SAS.Grade,'') AS ActivityGrade,
		SAM.Title AS ActivityName,
		SSAM.Title AS SubActivityName,
		SSA.SubjectSubActivityId AS SubActivityId,
		SAM.Id AS ActivityId,
		SSA.GradeIndicator AS SubActivityGradeIndicator,
		SSA.DescriptiveIndicator AS SubActivityDescriptiveIndicator,
		SAM.OrderIndex AS SubjectActivityOrderIndex,
		SSAM.OrderIndex AS SubActivityOrderIndex,
		CASE WHEN CS.OrderIndex % 2 = 0 THEN 2 
				ELSE 1 END   AS   ColumnSubjectCount,
		(CASE EM.IsDisplayImageHeader WHEN 1 THEN
			OI.MarksheetHeaderA4
			ELSE NULL END)AS  MarksheetHeaderA4,
		ISNULL(EM.IsDisplayImageHeader,0) AS IsImageHeader	,
		ISNULL(SC.PresentStreetONe,'')+' '+ISNULL(SC.PresentStreetTwo,'')+' '+ISNULL(SC.PresentStreetThree,'')+' '+ISNULL(SC.PresentCity,'')+' '+ISNULL(SC.PresentState,'') AS PresentAddress,
		 SC.ParentContactNo,
		ISNULL(HM.Title,'') AS House,
		ISNULL(CCER.AttendanceTerm1,0) AS AttendanceTerm1,
		ISNULL(CCER.AttendanceTerm2,0) AS AttendanceTerm2,
		ISNULL(CCER.WorkingDaysTerm1,0) AS WorkingDaysTerm1,
		ISNULL(CCER.WorkingDaysTerm2,0) AS WorkingDaysTerm2,
		ISNULL(BGM.Title,'') AS BloodGroup,
		CONVERT (nvarchar(50),EM.GradeSetId) AS GradeSetIdText,
		Convert(nvarchar(20),ISNULL(EM.IsDisplayMonthlyAttendance,0)) AS IsDisplayMonthlyAttendanceText,
		ISNULL(SR.DentalHygiene,'') AS DentalHygiene,
		ISNULL(SR.VisionLeft,'') AS VisionLeft,
		ISNULL(SR.VisionRight,'') AS VisionRight,
		--CASE WHEN EM.IsDisplayTeacherSign = 1 THEN EM.TeacherSignCaption ELSE NULL END AS TeacherSignCaption,
		--CASE WHEN EM.IsDisplayPrincipalSign = 1 THEN EM.PrincipalSignCaption ELSE NULL END AS PrincipalSignCaption,
		ISNULL(EM.TeacherSignCaption,'') AS TeacherSignCaption,
		ISNULL(EM.PrincipalSignCaption,'') AS PrincipalSignCaption,
		ISNULL(ParentSignCaption,'') AS ParentSignCaption,
		SC.ParentEmail As ParentEmail,
		ISNULL(SR.MyGoal,'') AS MyGoal,
		ISNULL(SR.MyStrength,'') AS MyStrength,
		ISNULL(SR.MyInterestHobby,'') AS MyInterestHobby,
		ISNULL(SR.AreaOfInterest,'') AS AreaOfInterest,
		ISNULL(SR.Responsibility,'') AS Responsibility,
		ISNULL(SR.Achievements,'') AS Achievements,
		ISNULL(SR.ImprovementArea,'') As ImprovementArea,
		ISNULL(SR.ProgressArea,'') AS ProgressArea,
		ISNULL(SR.MyActivity,'') AS MyActivity,
		ISNULL(SR.ClassTeacherRemark,'') As ClassTeacherRemark,
		EMP.FirstName + ' ' + EMP.LastName AS ClassTeacherName,
		ISNULL(SR.HouseRemark,'') As HouseRemark,
		ISNULL(SR.GeneralRemark,'') As GeneralRemark,
		SF.FatherContactNo,
		SF.MotherContactNo,
		SF.FatherMail,
		SF.MotherMail,
		CONVERT(bit,@lDecimalConfig) AS IsDecimal,
		[sStudent].[fStudentNameGet](stum.FirstName , StuM.MiddleName, StuM.LastName,OM.StudentNameFormatId ) AS Name
	FROM 
		sAssessment.tCCESubjectSubActivityExamScore SSA
		INNER JOIN sAssessment.tCCESubjectSubActivityMaster SSAM ON SSAM.Id = SSA.SubjectSubActivityId
		INNER JOIN sAssessment.tCCESubjectActivityMaster SAM ON SAM.Id = SSAM.SubjectActivityId
		LEFT JOIN sAssessment.tCCESubjectActivityExamScore SAS ON SAS.SubjectActivityId= SAM.Id AND SSA.AcademicId = SAS.AcademicId AND SSA.ExamId = SAS.ExamId
		INNER JOIN sSetup.tClassSubject CS ON CS.Id=SAM.ClassSubjectId	
		INNER JOIN sAssessment.tExamMaster EM ON EM.Id=SSA.ExamId
		INNER JOIN sAssessment.tExamDetail ED ON EM.Id=ED.ExamId AND ED.ClassSubjectId = SAM.ClassSubjectId
		--INNER JOIN sSetup.tClassSubject CS ON CS.Id=SAM.ClassSubjectId
		INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=CS.SubjectId					 
    	INNER JOIN sStudent.tAcademic  A ON   SSA.AcademicId = A.Id
		LEFT JOIN sAssessment.tCCEResult CCER    ON  CCER.AcademicId=A.Id
		INNER JOIN sStudent.tStudentMaster StuM ON StuM.Id=A.StudentId
		INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId
		INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId
		LEFT JOIN sHrm.tEmployeeMaster EMP ON EMP.Id = DM.InchargeEmployeeId
		LEFT JOIN sHrm.tEmployeeImages EI ON EI.EmployeeId = Dm.InchargeEmployeeId
		INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id = EM.EXAMSUBGROUPID
		LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId=StuM.Id
		LEFT JOIN sCommon.tBloodGroupMaster BGM ON BGM.Id=SO.BloodGroupId
		LEFT JOIN sStudent.tAcademicDetail AD ON AD.AcademicId=A.Id
		LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId=StuM.Id
		LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId = StuM.Id
		LEFT JOIN sAssessment.tOptionalSubject OS ON OS.AcademicId = A.Id AND OS.ClassSubjectId = ED.ClassSubjectId  
		LEFT JOIN sAssessment.tResult R ON R.AcademicId = SSA.AcademicId AND R.ExamId = SSA.ExamId
		LEFT JOIN sAssessment.tResultDetail RD  ON R.Id = RD.ResultId AND ED.ID = RD.ExamDetailId 
		LEFT JOIN sAssessment.tStudentRemark SR ON A.Id = SR.AcademicId AND EM.Id = SR.ExamId
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = StuM.OrgId
		LEFT JOIN sSetup.tOrgImages OI ON OI.OrgId = OM.Id
		LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId =Stum.ID
		LEFT JOIN sActivity.tHouseMaster HM ON HM.Id=SO.HouseId
		--LEFT JOIN sAcademic.tTeacherSubjectDivision TSD ON TSD.SubjectId=SM.Id AND TSD.DivisionId = A.DivisionId
		--LEFT JOIN sHrm.tEmployeeMaster EMP ON TSD.EmployeeId = EMP.Id
	
	 WHERE
		SSA.ExamId = @rExamId 
		AND ((A.DivisionId =  @rDivisionId) OR (@rDivisionId=0))
		AND ((A.ClassId =  @rClass) OR (@rClass=0))		 
		AND ((A.BatchId =  @rBatchId) OR (@rBatchId=0))
		AND ((A.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
		AND ((A.RollNo <= @rToRollNo) OR (@rToRollNo=0))
		--AND ((R.RankNumber >= @rFromRank) OR (@rFromRank=0))
		--AND ((R.RankNumber <= @rToRank) OR (@rToRank=0))
		--AND ((R.ResultGrade = @rGrade) OR (@rGrade=''))
		AND ((StuM.Code=@rCode) OR (@rCode=''))	
		--AND ((R.Id = @rResultId) OR (@rResultId = 0))	
		--AND ((StuM.StatusId=@rStatusId)OR(@rStatusId=0))
		AND((A.Id=@rAcademicId)OR (@rAcademicId=0))
		--AND ((CS.SubjectId=@rSubjectId) OR(@rSubjectId=0) ) 
		 AND (ISNULL(StuM.Code,0) IN( SELECT cast(item as nvarchar(20)) FROM  sCommon.fnsplit(@rMultiCode,',')) OR @rMultiCode='')
	 
	Order By ED.DisplayOrder
 
	
 --print 'temp insert'
  --SET @IsIncludeSubExam = 1
	create TABLE #tempcombineExam
	(	Id int IDENTITY,
		ExamID int )

	IF (@IsIncludeSubExam = 0)
	BEGIN	
	INSERT INTO #tempcombineExam (ExamID) 
	SELECT SUBEXAMID FROM sAssessment.tExamCombine WHERE ExamId  = @rExamId Order By ExamOrder ASC
 	END
 	ELSE
 	BEGIN
 	-- if we want to display result for both the term with all exam select this option
 	INSERT INTO #tempcombineExam (ExamID) 
	SELECT C.SUBEXAMID FROM sAssessment.tExamCombine C
	INNER JOIN (SELECT SUBEXAMID,ExamOrder FROM sAssessment.tExamCombine WHERE ExamId  = @rExamId) E
	ON C.SubExamId = E.SubExamId
	ORDER BY E.ExamOrder,C.ExamOrder
	END
	 
	--ON 
	
	-- Order By ExamOrder ASC
	--WHERE ExamId in (SELECT SUBEXAMID FROM sAssessment.tExamCombine WHERE ExamId  = @rExamId Order By ExamOrder ASC)
	
	DECLARE @lCount int,@query  AS NVARCHAR(MAX),@lSubExamId int,@lCount1 int  
	Select @lCount = MAX(Id) from #tempcombineExam	
	DECLARE @ExamTitle nvarchar(150)
	while (@lCount > 0)
	begin
		select @lSubExamId = ExamID from #tempcombineExam Where Id = @lCount
		--select @ExamTitle = Title from sAssessment.tExamMaster Where Id = @lSubExamId	
		
		set @query ='update T SET
					
					 IsPresent' + convert(nvarchar(15),@lCount)+'=RD.IsPresent,					
					 SubjectGrade' + convert(nvarchar(15),@lCount)+ '=RD.SubjectGrade,
					 Exam' + convert(nvarchar(15),@lCount)+ 'Name=ESGM.Title,
					 Height' + convert(nvarchar(15),@lCount)+ '=SR.StudentHeight,
					 Weight' + convert(nvarchar(15),@lCount)+ '=SR.StudentWeight,				
					 TotalDays'+convert(nvarchar(15),@lCount)+'=SR.TotalDays,
					 PresentDays'+convert(nvarchar(15),@lCount)+'=SR.PresentDays,
					 MyActivity'+convert(nvarchar(15),@lCount)+'=SR.MyActivity,
					 GeneralRemark'+convert(nvarchar(15),@lCount)+'=SR.GeneralRemark 
					 									
					 From
						 
						 sAssessment.tResult R 
						INNER JOIN  sAssessment.tResultDetail RD ON RD.ResultId = R.Id						
						INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
						INNER JOIN sAssessment.tExamSubgroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId					
						INNER JOIN 	#TempAllExam  T ON T.ClassSubjectID = ED.ClassSubjectId And T.AcademicId = R.AcademicId	
						LEFT JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND T.AcademicId = SR.AcademicId 							
						WHERE EM.Id =' + convert(nvarchar(15), @lSubExamId)  
						
	
	 execute(@query)
 
	 set @query ='update T SET
					
					 
					 SubActivityGrade' + convert(nvarchar(15),@lCount)+ '=SSA.Grade	
					 						
					 From
						sAssessment.tCCESubjectSubActivityExamScore SSA				
						inner JOIN 	#TempAllExam  T ON T.SubActivityId = SSA.SubjectSubActivityId And T.AcademicId = SSA.AcademicId	 					
						WHERE SSA.ExamId =' + convert(nvarchar(15), @lSubExamId)  
						
	
 --PRINT(@QUERY)	
   EXECUTE(@query)
 
  set @query ='update T SET
					
					  ActivityGrade' + convert(nvarchar(15),@lCount)+ '=SAS.Grade	
					 						
					 From
						sAssessment.tCCESubjectActivityExamScore SAS				
						inner JOIN 	#TempAllExam  T ON T.ActivityId = SAS.SubjectActivityId And T.AcademicId = SAS.AcademicId	 					
						WHERE SAS.ExamId =' + convert(nvarchar(15), @lSubExamId)  
						
	
 --PRINT(@QUERY)	
   EXECUTE(@query)
	-- set @query ='update T SET
					
	--				 Height' + convert(nvarchar(15),@lCount)+ '=SR.StudentHeight,
	--				 Weight' + convert(nvarchar(15),@lCount)+ '=SR.StudentWeight,				
	--				 TotalDays'+convert(nvarchar(15),@lCount)+'=SR.TotalDays,
	--				 PresentDays'+convert(nvarchar(15),@lCount)+'=SR.PresentDays,
	--				 MyActivity'+convert(nvarchar(15),@lCount)+'=SR.MyActivity,
	--				 GeneralRemark'+convert(nvarchar(15),@lCount)+'=SR.GeneralRemark
	--				 From
	--					sAssessment.tCCESubjectSubActivityExamScore SSA
						
	--					inner JOIN sAssessment.tCCESubjectSubActivityMaster SSAM ON SSAM.Id = SSA.SubjectSubActivityId
	--					inner JOIN sAssessment.tCCESubjectActivityMaster SAM ON SAM.Id = SSAM.SubjectActivityId
	--					INNER JOIN sAssessment.tExamMaster EM ON EM.Id=SSA.ExamId
	--					inner JOIN 	#TempAllExam  T ON T.SubActivityId = SSA.SubjectSubActivityId And T.AcademicId = SSA.AcademicId	
	--					LEFT JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND T.AcademicId = SR.AcademicId 					
	--					WHERE EM.Id =' + convert(nvarchar(15), @lSubExamId)  
						
	
 ----PRINT(@QUERY)	
 --  EXECUTE(@query)
	
						
		/*	set @query ='update T set 
				    TotalMarks' + convert(nvarchar(15),@lCount)+ '=R.TotalMarks,
					TotalObtain' + convert(nvarchar(15),@lCount)+ '=R.TotalObtain,
					Percentage' + convert(nvarchar(15),@lCount)+ '=R.Percentage,
					RankNumber' + convert(nvarchar(15),@lCount)+'=R.RankNumber,
					ResultGrade' + convert(nvarchar(15),@lCount)+'=R.ResultGrade,
					Percentile' + convert(nvarchar(15),@lCount)+'=R.Percentile,
					ResultStatus' + convert(nvarchar(15),@lCount)+'=R.ResultStatus,
					Exam' + convert(nvarchar(15),@lCount)+ 'Name=ESGM.Title,
					ExamMaximum' + convert(nvarchar(15),@lCount)+'=EM.ExamMaximum
					 From						
						sAssessment.tResult R						
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id=R.ExamId
						INNER JOIN sAssessment.tExamSubgroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId					
						INNER JOIN 	#TempAllExam  T ON  T.AcademicId = R.AcademicId						
						WHERE EM.Id =' + convert(nvarchar(15), @lSubExamId)  
						
	execute(@query)*/
		
		
	set @lCount = @lCount -1
	end
	SELECT @rBuilder1 , T.*
	FROM #TempAllExam T
	
	
		
	drop table #tempcombineExam
	Drop table #TempAllExam

	--Select 
	-- '' As AcademicIdText,
	--	'' As ExamIdText,
	--	'' As CoScholasticScopeIdText ,
		
	--	CONVERT(bigint , 0) As AcademicId,
	--	'' As ExamName,
	--	'' As StudCode,
	--	'' As StudentName ,
	--	0 As RollNo,
	--	'' As ResultStatus ,	
	--	'' As ClassName ,		
	--	'' As Division ,
	--	CONVERT(decimal , 0) As TotalMark ,
	--	CONVERT(decimal , 0) As TotalObtain,
	--	CONVERT(decimal , 0) As Percentage ,
	--	0 As RankNumber ,
	--	'' As ResultGrade ,
		
	--	--MaximumMark1 decimal(8,2),		
	--	'' As SubjectGrade1 ,
	--	--Obtain1 decimal(8,2),
	--	--ExamMaximum1 decimal(8,2),
	--	CONVERT(bit , 0) As IsPresent1,
						
	--	CONVERT(decimal , 0) As MaximumMark2 ,	
	--	'' As SubjectGrade2 ,
	--	CONVERT(decimal , 0) As Obtain2 ,
	--	CONVERT(decimal , 0) As ExamMaximum2 ,
	--	CONVERT(bit , 0) As IsPresent2,
				
	--	CONVERT(decimal , 0) As MaximumMark3 ,
	--	'' As SubjectGrade3 ,
	--	CONVERT(decimal , 0) As Obtain3 ,
	--	CONVERT(decimal , 0) As ExamMaximum3 ,
	--	CONVERT(bit , 0) As IsPresent3 ,		
		
	--	CONVERT(decimal , 0) As MaximumMark4 ,	
	--	'' As SubjectGrade4 ,
	--	CONVERT(decimal , 0) As Obtain4 ,
	--	CONVERT(decimal , 0) As ExamMaximum4 ,
	--	CONVERT(bit , 0) As IsPresent4 ,	
				
	--	CONVERT(decimal , 0) As MaximumMark5 ,		
	--	'' As SubjectGrade5 ,
	--	CONVERT(decimal , 0) As Obtain5 ,
	--	CONVERT(decimal , 0) As ExamMaximum5 ,
	--	CONVERT(bit , 0) As IsPresent5 ,	
				
	--	CONVERT(decimal , 0) As MaximumMark6 ,		
	--	'' As SubjectGrade6,
	--	CONVERT(decimal , 0) As Obtain6 ,
	--	CONVERT(decimal , 0) As ExamMaximum6 ,
	--	CONVERT(bit , 0) As IsPresent6 ,	
		
	--	CONVERT(decimal , 0) As MaximumMark7 ,		
	--	'' As SubjectGrade7,
	--	CONVERT(decimal , 0) As Obtain7 ,
	--	CONVERT(decimal , 0) As ExamMaximum7 ,
	--	CONVERT(bit , 0) As IsPresent7 ,	
	
	--	CONVERT(decimal , 0) As MaximumMark8 ,	
	--	'' As SubjectGrade8,
	--	CONVERT(decimal , 0) As Obtain8 ,
	--	CONVERT(decimal , 0) As ExamMaximum8 ,
	--	CONVERT(bit , 0) As IsPresent8 ,	
		
	--	'' As SubjectGradeTerm1,
	--	'' As SubjectGradeTerm2 ,
	--	CONVERT(bit , 0) As IsMarksInDecimal ,
	--	CONVERT(bit , 0) As column_visible ,
	--	--Obtain decimal(5,2),
	--	CONVERT(decimal , 0) As Percentile,
	--	--ClassSubject nvarchar(100),
	--	CONVERT(bigint , 0) As ResultDetailId ,
	--	CONVERT(bigint , 0) As ResultId ,	
	--	'' As Remark1 ,
	--	'' As Remark2 ,
	--	'' As Remark3 ,
	--	'' As DisplayTitle ,		
	--	CONVERT(bit , 0) As IsRankNo , 
	--	CONVERT(bit , 0) As IsGrade ,
	--	CONVERT(bit , 0) As IsPercentile ,
	--	CONVERT(bit , 0) As IsPercentage ,
	--	CONVERT(bit , 0) As IsSubjectPercentile ,
	--	CONVERT(bit , 0) As IsProcessResult ,
	--	CONVERT(bit , 0) As IsNegativeMarks ,
	--	CONVERT(bit , 0) As IsIncludeCoScholastic ,
	--	CONVERT(bit,0) As IsOnPrePrinted ,
	--	CONVERT(bit , 0) As IsDisplayPhoto ,
	--	CONVERT(bit , 0) As IsDisplayBirthDate ,
	--	CONVERT(bit , 0) As IsLockForEdit ,
	--	CONVERT(bit , 0) As IsDisplaySchoolName ,			
	--	CONVERT(bit , 0) As IsDisplayAttendance ,
	--	CONVERT(bit , 0) As IsDisplayHeightWeight ,
	--	CONVERT(bit , 0) As IsResultStatus ,
	--	'' As FooterAdjustmentText ,
	--	'' As DetailAdjustmentText ,
	--	0 As FooterAdjustment ,
	--	0 As DetailAdjustment ,
	--	'' As ResultRemark ,
	--	CONVERT(Date , null) As DateOfBirth ,
	--	CONVERT(decimal , 0) As HeightTerm1 ,
	--	CONVERT(decimal , 0) As WeightTerm1 ,
	--	CONVERT(decimal , 0) As HeightTerm2,
	--	CONVERT(decimal , 0) As WeightTerm2 ,
	--	CONVERT(decimal , 0) As HeightAnnual ,
	--	CONVERT(decimal , 0) As WeightAnnual ,
	--	0 As PresentDaysTerm1,
	--	0 As PresentDaysTerm2 ,
	--	0 As PresentDaysAnnual ,
	--	0 As TotalDaysTerm1 ,
	--	0 As TotalDaysTerm2 ,
	--	0 As TotalDaysAnnual ,
	--	CONVERT(decimal , 0) As TotalMarkTerm1 ,
	--	CONVERT(decimal , 0) As TotalObtainTerm1 ,
	--	CONVERT(decimal , 0) As PercentageTerm1,
	--	0 As RankNumberTerm1 ,
	--	'' As ResultGradeTerm1,
	--	CONVERT(decimal , 0) As PercentileTerm1 ,
	--	'' As ResultStatusTerm1,		   
	--	CONVERT(decimal , 0) As TotalMarkTerm2 ,
	--	CONVERT(decimal , 0) As TotalObtainTerm2 ,
	--	CONVERT(decimal , 0) As PercentageTerm2 ,
	--	0 As RankNumberTerm2 ,
	--	'' As ResultGradeTerm2 ,
	--	CONVERT(decimal , 0) As PercentileTerm2 ,
	--	'' As ResultStatusTerm2 , 
	--	CONVERT(tinyInt , 0) As TermScopeId ,		 
	--	Convert (varbinary(max) , '') As StudentPhoto ,
	--	'' As GradeString,
	--	CONVERT(bit , 0) As IsDisplayGradeString ,		 
	--	CONVERT(bit , 0) As IsDisplayInMarksheet ,
	--	CONVERT(bit , 0) As IsShowSubjectGrade ,
	--	CONVERT(bit , 0) As IsIncludeInTotal ,
	--	0 As ClassSubjectID ,
	--	0 As SubjectId ,
	--	--Maximum decimal(5,2),
	--	0 As SubjectOrderIndex ,
	--	'' As SubjectGrade ,
	--	'' As SubjectName ,
	--	'' As SubjectCode ,	
	--	CONVERT(decimal , 0) As SubjectMinimum ,		
	--	CONVERT(decimal , 0) As SubjectMaximum ,
	--	CONVERT(decimal , 0) As SubjectObtain ,
		
	--	'' As Exam1Name ,		
	--	CONVERT(decimal , 0) As TotalMarks1 ,		
	--	CONVERT(decimal , 0) As TotalObtain1 ,
	--	CONVERT(decimal , 0) As Percentage1 ,
	--	0 As RankNumber1 ,
	--	'' As ResultGrade1,
	--	CONVERT(decimal , 0) As Percentile1 ,
	--	'' As ResultStatus1 ,
		
	--	'' As SubActivityGrade1,
	--	'' As ActivityGrade1,
		
	--	'' As Exam2Name ,	
	--	CONVERT(decimal , 0) As TotalMarks2 ,
	--	CONVERT(decimal , 0) As TotalObtain2 ,
	--	CONVERT(decimal , 0) As Percentage2 ,
	--	0 As RankNumber2 ,
	--	'' As ResultGrade2 ,
	--	CONVERT(decimal , 0) As Percentile2 ,
	--	'' As ResultStatus2 ,
		
	--	'' As SubActivityGrade2,
	--	'' As ActivityGrade2 ,
		
	--	'' As Exam3Name ,	
	--	CONVERT(decimal , 0) As TotalMarks3 ,
	--	CONVERT(decimal , 0) As TotalObtain3 ,
	--	CONVERT(decimal , 0) As Percentage3 ,
	--	0 As RankNumber3 ,
	--	'' As ResultGrade3 ,
	--	CONVERT(decimal , 0) As Percentile3 ,		
	--	'' As ResultStatus3,
		
	--	'' As SubActivityGrade3 ,
	--	'' As ActivityGrade3 ,
		
	--	'' As Exam4Name ,	
	--	CONVERT(decimal , 0) As TotalMarks4 ,
	--	CONVERT(decimal , 0) As TotalObtain4,
	--	CONVERT(decimal , 0) As Percentage4 ,
	--	0 As RankNumber4 ,
	--	'' As ResultGrade4 ,
	--	CONVERT(decimal , 0) As Percentile4 ,
	--	'' As ResultStatus4 ,
		
	--	'' As SubActivityGrade4,
	--	'' As ActivityGrade4 ,
		
	--	'' As Exam5Name ,		
	--	CONVERT(decimal , 0) As TotalMarks5 ,
	--	CONVERT(decimal , 0) As TotalObtain5 ,
	--	CONVERT(decimal , 0) As Percentage5 ,
	--	0 As RankNumber5 ,
	--	'' As ResultGrade5 ,
	--	CONVERT(decimal , 0) As Percentile5 ,
	--	'' As ResultStatus5 ,
		
	--	'' As SubActivityGrade5 ,
	--	'' As ActivityGrade5 ,
		
	--	'' As Exam6Name ,	
	--	CONVERT(decimal , 0) As TotalMarks6 ,
	--	CONVERT(decimal , 0) As TotalObtain6,
	--	CONVERT(decimal , 0) As Percentage6 ,
	--	0 As RankNumber6 ,
	--	'' As ResultGrade6 ,
	--	CONVERT(decimal , 0) As Percentile6 ,
	--	'' As ResultStatus6 ,
		
	--	'' As SubActivityGrade6 ,
	--	'' As ActivityGrade6 ,
		
	--	'' As Exam7Name ,		
	--	CONVERT(decimal , 0) As TotalMarks7 ,
	--	CONVERT(decimal , 0) As TotalObtain7,
	--	CONVERT(decimal , 0) As Percentage7 ,
	--	0 As RankNumber7 ,
	--	'' As ResultGrade7,
	--	CONVERT(decimal , 0) As Percentile7 ,
	--	'' As ResultStatus7 ,
		
	--	--SubActivityGrade7 nvarchar(10),
		
	--	'' As Exam8Name,
	--	CONVERT(decimal , 0) As TotalMarks8 ,
	--	CONVERT(decimal , 0) As TotalObtain8 ,
	--	CONVERT(decimal , 0) As Percentage8,
	--	0 As RankNumber8 ,
	--	'' As ResultGrade8 ,
	--	CONVERT(decimal , 0) As Percentile8,
	--	'' As ResultStatus8,
	--	'' As ResultRemark1 ,
	--	'' As ResultRemark2,
	--	CONVERT(decimal , 0) As TotalDays ,
	--	CONVERT(decimal , 0) As PresentDays ,
	--	CONVERT(decimal , 0) As StudentHeight,
	--	CONVERT(decimal , 0) As StudentWeight ,
	--	'' As ExamSeatNo ,
	--	0 As ExamId ,
	--	CONVERT(bit , 0) As IsDisplayParentName ,
	--	'' As FatherName ,
	--	'' As MotherName ,
	--	CONVERT(bit , 0) As IsShowSubjectMark , 
	--	CONVERT(bit , 0) As IsOptionalSubject ,
	--	CONVERT(tinyInt , 0) As CoScholasticScopeId ,
	--	CONVERT(bit , 0) As IsDisplayPrincipalSign ,
	--	CONVERT(bit , 0) As IsDisplayTeacherSign ,
	--	Convert (varbinary(max) , '') As EmployeeSign,
		
	--	'' As ActivityName ,
	--	'' As SubActivityName ,
	--	0 As SubActivityId ,
	--	0 As ActivityId ,
	--	 '' As SubActivityGrade,
	--	 '' As ActivityGrade ,
	--	'' As SubActivityGradeIndicator ,
	--	'' As SubActivityDescriptiveIndicator,
	--	0 As SubjectActivityOrderIndex ,
	--	0 As SubActivityOrderIndex ,
	--	0 As ColumnSubjectCount ,
	--	Convert (varbinary(max) , '') As MarksheetHeaderA4 ,
	--	CONVERT(bit,0) As IsImageHeader ,
	--	CONVERT(decimal , 0) As Height1 ,
	--	CONVERT(decimal , 0) As Height2 ,
	--	CONVERT(decimal , 0) As Height3,
	--	CONVERT(decimal , 0) As Height4 ,
	--	CONVERT(decimal , 0) As Height5,
	--	CONVERT(decimal , 0) As Height6 ,
	--	CONVERT(decimal , 0) As Weight1 ,
	--	CONVERT(decimal , 0) As Weight2 ,
	--	CONVERT(decimal , 0) As Weight3 ,
	--	CONVERT(decimal , 0) As Weight4,
	--	CONVERT(decimal , 0) As Weight5 ,
	--	CONVERT(decimal , 0) As Weight6 ,
	--	CONVERT(decimal , 0) As TotalDays1 ,
	--	CONVERT(decimal , 0) As PresentDays1 ,
	--	CONVERT(decimal , 0) As TotalDays2 ,
	--	CONVERT(decimal , 0) As PresentDays2 ,
	--	CONVERT(decimal , 0) As TotalDays3 ,
	--	CONVERT(decimal , 0) As PresentDays3 ,
	--	CONVERT(decimal , 0) As TotalDays4 ,
	--	CONVERT(decimal , 0) As PresentDays4 ,
	--	CONVERT(decimal , 0) As TotalDays5 ,
	--	CONVERT(decimal , 0) As PresentDays5 ,
	--	CONVERT(decimal , 0) As TotalDays6 ,
	--	CONVERT(decimal , 0) As PresentDays6 ,
	--	'' As MyActivity1,
	--	'' As MyActivity2 ,
	--	'' As MyActivity3,
	--	'' As MyActivity4 ,
	--	'' As MyActivity5,
	--	'' As MyActivity6,
	--	'' As GeneralRemark1,
	--	'' As GeneralRemark2 ,
	--	'' As GeneralRemark3 ,
	--	'' As GeneralRemark4,
	--	'' As GeneralRemark5,
	--	'' As GeneralRemark6,
	--	'' As PresentAddress ,
	--	'' As  MobileNo,
	--	'' As House ,
		 
	--	CONVERT(decimal , 0) As AttendanceTerm1  ,
	--	CONVERT(decimal , 0) As AttendanceTerm2 ,
	--	CONVERT(decimal , 0) As WorkingDaysTerm1 ,
	--	CONVERT(decimal , 0) As WorkingDaysTerm2 ,
	--	  '' As BloodGroup ,
	--	  '' As GradeSetIdText ,
	--	  '' As IsDisplayMonthlyAttendanceText ,
	--	  '' As DentalHygiene ,
	--	'' As VisionLeft ,
	--	'' As VisionRight ,
	--	'' As TeacherSignCaption ,
	--	'' As PrincipalSignCaption ,
	--	'' As ParentSignCaption ,
	--	'' As ParentEmail ,
	--  '' AS MyGoal,
	--	'' AS MyStrength,
	--	'' AS MyInterestHobby,
	--	'' AS AreaOfInterest,
	--	'' AS Responsibility,
	--	'' AS Achievements,
	--	'' As ImprovementArea,
	--	'' AS ProgressArea,
	--	'' AS MyActivity,
	--	'' As ClassTeacherRemark,
	--	'' AS ClassTeacherName,
	--	'' As HouseRemark,
	--	'' As GeneralRemark,
	--	'' AS FatherContactNo,
	--	'' AS MotherContactNo,
	--	'' AS FatherMail,
	--	'' AS MotherMail,
	--  CONVERT(bit , 0) As IsDecimal,
	--  '' As Name

	--END


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


GO


ALTER PROCEDURE [sAssessment].[pRptResultWithAllSubjectListGet]
	 
   	@rBuilder1 nvarchar(max)='',
	@rBuilder2 nvarchar(max)='', 
	@rSubjectId int=0,
	@rBatchId int,
	@rClassId int,
	@rDivisionId int,	
	@rExamId int=0,
	@rExamSubGroupId int=0,
	@rCode nvarchar(20),
	@rFromRollNo int,
	@rToRollNo int,
	@rFromRank int,
	@rToRank int,
	@rGrade nvarchar(20),
	@rStatusId int = 0,
	@rFromPercentage decimal(5,2)=0,
	@rToPercentage decimal(5,2)=0,
	@rResultStatus nvarchar(20)='',
	@rDepartmentId int=0,
	@rClassStatusId int=0,
	@rFilterId int=0 
	
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 

	SELECT 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			ESGM.Title AS Exam,
			StuM.Code,
		    [sStudent].[fStudentNameGet](StuM.FirstName , StuM.MiddleName, StuM.LastName,OM.StudentNameFormatId ) AS Name,
			A.RollNo,
			R.AcademicId,
			RD.Obtain,
			R.ResultStatus,
			CM.DisplayTitle AS Class,
			Cm.Id AS ClassId,
			DM.DisplayTitle AS Division,
			DM.Id AS DivisionId,
			DM.OrderIndex AS DivisinOrderIndex,
			R.TotalMarks,
			R.TotalObtain,
			R.Percentage,
			R.RankNumber,
			R.ResultGrade,
			SM.Title AS ClassSubject,
			RD.Id AS ResultDetailId,
			R.Id AS ResultId,
			CS.Id AS SubjectId,
			ED.Maximum,
			RD.SubjectGrade, 
			EM.IsMarksInDecimal,
			SM.Code AS SubjectCode,
			ED.DisplayOrder AS SubjectOrderIndex,
			CM.OrderIndex AS ClassOrderIndex,
			RD.IsPresent,
			EM.IsGrade,
			EM.IsPercentage,
			EM.IsResultStatus,
			EM.IsRankNo ,
			ED.Minimum,
			RD.GraceMark,
			EM.DecimalFormat,
			CS.IsOptional,
			(EmpM.FirstName + ' ' +EmpM.LastName ) AS InchargeEmployeeName
      
	FROM 
	
	sStudent.tAcademic A 
	INNER JOIN sAssessment.tResult R ON A.Id=R.AcademicId    
	INNER JOIN sStudent.tStudentMaster StuM ON StuM.Id=A.StudentId
	INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId
	INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId
	INNER JOIN sSetup.tOrganizationMaster OM ON StuM.OrgId = OM.Id
	INNER JOIN sAssessment.tExamMaster EM ON EM.Id=R.ExamId AND	((EM.Id=@rExamId )	OR (@rExamId = 0))AND EM.BatchId = @rBatchId	
	INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId AND ((ESGM.Id = @rExamSubGroupId) OR (@rExamSubGroupId = 0))
	INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId = EM.Id
	INNER JOIN sSetup.tClassSubject CS ON Cs.Id = Ed.ClassSubjectId
	INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=CS.SubjectId	
	LEFT JOIN sAssessment.tResultDetail RD ON ED.Id=RD.ExamDetailId 
		AND ((SM.Id=@rSubjectId) OR (RD.ExamDetailId=@rSubjectId) OR (@rSubjectId=0)) 
		AND R.Id = RD.ResultId
	LEFT JOIN sHrm.tEmployeeMaster EmpM ON EmpM.Id = DM.InchargeEmployeeId AND EmpM.StatusId = 7
	INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId
	LEFT JOIN sHostel.tAssignRoom AR ON  AR.SourceId=StuM.Id AND AR.SourceTypeId=2003 AND BM.OrgGroupBatchId = AR.OrgGroupBatchId
	LEFT JOIN
	(SELECT AT.SourceId,B.OrgGroupBatchId FROM sTransport.tAssignRoute AT 
    INNER JOIN sTransport.tBusRouteDestinationMaster BRD ON BRD.Id=AT.PickupDestinationId 
    INNER JOIN sTransport.tBusRouteMaster B ON B.Id=BRD.BusRouteId AND  AT.SourceTypeId=2003 ) RT
    ON RT.SourceId = StuM.Id AND RT.OrgGroupBatchId = BM.OrgGroupBatchId
	
			
	WHERE 
	     
	   --(CS.ClassId=@rClassId OR @rClassId=0) 
		 EM.BatchId = @rBatchId 
		AND (A.ClassId=@rClassId OR @rClassId=0) 
		--AND((SM.Id=@rSubjectId) OR (RD.ExamDetailId=@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 ((ESGM.Id = @rExamSubGroupId) OR (@rExamSubGroupId = 0))		
		AND ((EM.Id=@rExamId )	OR (@rExamId = 0))		
		AND ((StuM.Code=@rCode) OR (@rCode=''))
		AND ((StuM.StatusId=@rStatusId)OR(@rStatusId=0))	
		AND ((R.Percentage>=@rFromPercentage) OR (@rFromPercentage=0))
		AND ((R.Percentage<=@rToPercentage) OR(@rToPercentage=0))	
		AND ((R.ResultStatus=@rResultStatus) OR (@rResultStatus=''))
		AND ((CM.DepartmentId = @rDepartmentId) OR (@rDepartmentId=0))
	    AND	A.BatchId = @rBatchId 
		AND (A.ClassStatusId=@rClassStatusId OR @rClassStatusId=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)))
		) 
		order by A.RollNo,CS.OrderIndex 

		
END
GO
PRINT N'Altering Procedure [sAttendance].[pAttenanceRegisterGet]...';


GO

ALTER PROCEDURE [sAttendance].[pAttenanceRegisterGet]
     @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 @rAttendanceTypeId smallint,
	 @rOrgId int,
	 @rForMonth smallint,
	 @rForYear smallint,
	 @rClassId int=0,
	 @rDivisionId int=0,
	 @rBatchId int = 0,
	 @rStudentCode nvarchar(20)='',
	 @rDepartmentId int = 0,
	 @rAcademicId bigint = 0,
	 @PageIndex int=0,
	 @rStatus int=0,
	 @rFromStudentCode nvarchar(20)='',
	 @rToStudentCode nvarchar(20)='',
	 @rOrderBy int=0
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

--Select * from sAttendance.tTempAttendance

DECLARE @lFirstDate Date
	DECLARE @lResult nvarchar(max)
	DECLARE @li int 
	SET @li=1
	SET @lFirstDate = CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'/'+CONVERT(NVARCHAR(2),@rForMonth)+'/01'))	
	
DECLARE @lOrgId  int
--DECLARE @lSchoolRemark1  nvarchar(500)
--DECLARE @lSchoolRemark2  nvarchar(500)
--DECLARE @lSchoolRemark3  nvarchar(500)
DECLARE @lSchoolRequiredSignature  nvarchar(500)

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=1 where RGM.Id=1
 
-- select @lSchoolRequiredSignature as sig
 	Declare @Days int 
 	select @Days=sCommon.fGetDaysInMonth(@rForMonth,@rForYear)
BEGIN 
	 CREATE Table #AttendanceRegistertempTable
(
	TID int identity(1,1),
	ClassDivisionTitle Nvarchar(500),
	Code nvarchar(500),
	RollNo int,
	AcademicId bigint,
	Name nvarchar(500),
	AttendanceTypeId int,
	ForYear int,
	ForMonth int,
	ForMonthInWord nvarchar(500),
	ClassId int,
	DivisionId int,
	ClassName nvarchar(500),
	DivisionName nvarchar(500),
	IsPresent bit,
	DayPart int,
	LeftDate date,
	ClassOrderIndex int,
	DivisionOrderIndex int,
	FooterSignature nvarchar(500),
	StatusId int,
	AttendanceDate date,
	AttendanceTagId int ,
	EmployeeName nvarchar(500),
	DateOfBirth date,
	Religion nvarchar(500),
	MotherName nvarchar(500),
	FamilyCast nvarchar(100),
	Gender tinyint,
	CastCategory nvarchar(50)

)
Insert INTO #AttendanceRegistertempTable
(	
	ClassDivisionTitle,
	Code ,
	RollNo,
	AcademicId,
	Name,
	AttendanceTypeId,
	ForYear,
	ForMonth,
	ForMonthInWord,
	ClassId,
	DivisionId,
	ClassName,
	DivisionName,
	IsPresent,
	DayPart,
	LeftDate,
	ClassOrderIndex,
	DivisionOrderIndex,
	FooterSignature,
	StatusId,
	AttendanceDate,
	AttendanceTagId,
	EmployeeName,
	DateOfBirth,
	Religion,
	MotherName,
	FamilyCast,
	Gender,
	CastCategory
)
Select	    
	ISNULL(SA.ClassName + '-' + SA.DivisionName,'') AS ClassDivisionTitle,
	SA.Code,
	SA.RollNo,
	SA.AcademicId,
	SA.Name,
	SR.AttendanceTypeId ,
	YEAR(SR.AttendanceDate) AS ForYear,
	MONTH(SR.AttendanceDate) AS ForMonth,
	DATENAME(month, SR.AttendanceDate) AS ForMonthInWord,
	SA.ClassId,
	SA.DivisionId,
	SA.ClassName,Sa.DivisionName,
  
	--(CASE SR.IsPresent WHEN 1 THEN 'P' 
	--	WHEN 0 THEN 'A'
	--ELSE  ' ' END )AS  IsPresent,		
	SR.IsPresent,
	 day(SR.AttendanceDate) AS DayPart,
	 
	 A.LeftDate,
	 CM.OrderIndex AS ClassOrderIndex,
	 DM.OrderIndex As DivisionOrderIndex,
	@lSchoolRequiredSignature AS FooterSignature,
	 SA.StatusId,
	 SR.AttendanceDate As AttendanceDate,
	 SR.AttendanceTagId,
	 EM.FirstName+' ' + EM.LastName AS EmployeeName,
	 SO.DateOfBirth,
	 RE.Title As Religion,
	 Sf.MotherName,
	 SO.FamilyCast,
	 --,
	 --SR.IsPresent
	 SO.GenderId,
	 ISNULL(CCM.Title,'') AS CastCategory
	 
    from
            sStudent.vStudentAcademic SA 
            INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=SA.AcademicId 
            INNER JOIN sStudent.tStudentAdmission A ON SA.StudentId = A.StudentId
            INNER JOIN sSetup.tClassMaster CM ON CM.Id = SA.ClassId
            INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = CM.OrgId
            INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=SA.DivisionId
            LEFT JOIN sHrm.tEmployeeMaster EM ON EM.Id = DM.InchargeEmployeeId 
            INNER JOIN sStudent.tStudentOther SO ON SO.StudentId=SA.StudentId
			LEFT JOIN  sStudent.tStudentFamily SF ON Sf.StudentId=Sa.StudentID
            LEFT JOIN sCommon.tReligionMaster RE On RE.Id=SO.ReligionId
			LEFT JOIN sCommon.tCastCategoryMaster CCM ON CCM.Id=SO.CastCategoryId
            
             WHERE  
	        ((SR.AttendanceTypeId=@rAttendanceTypeId) OR (@rAttendanceTypeId= 0))
	         AND ((SA.OrgId=@rOrgId) OR (@rOrgId= 0))
	          AND ((SA.BatchId=@rBatchId) OR (@rBatchId= 0))
	          AND ((YEAR(SR.AttendanceDate)=@rForYear) OR (@rForYear= 0))
	          AND ((MONTH(SR.AttendanceDate)=@rForMonth) OR (@rForMonth= 0))
	           AND ((SA.ClassId=@rClassId) OR (@rClassId= 0))
	           AND ((SA.Code=@rStudentCode) OR (@rStudentCode=''))
	           AND ((SA.AcademicId=@rAcademicId) OR (@rAcademicId=0))	           
				AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
	           AND ((SA.DivisionId=@rDivisionId) OR (@rDivisionId= 0))
	           AND ((SA.StatusId=@rStatus)OR (@rStatus=0))
	           AND ((SA.Code >= @rFromStudentCode) OR (ISNULL(@rFromStudentCode,'')=''))
	           AND ((SA.Code <= @rToStudentCode) OR (ISNULL(@rToStudentCode,'')=''))
	           AND  ISNULL(EM.IsOtherUser,0) = 0 
				
CREATE TABLE #TempDaysTempTable
(
 DayPart int,
 Value nvarchar(20)
 )
WHILE @li<=@Days
BEGIN
INSERT INTO #TempDaysTempTable
(
	DayPart ,
   Value
)

SELECT 
@li AS DayPart,
 [sAttendance].[fWeekHOffGet](@rForYear,@rForMonth,@li,@rBatchId,@rClassId,@rDivisionId,'',@rOrgId) 
SET @li = @li + 1
END

 

SELECT  
			@lFirstDate AS LastDate,
			LeftDate,
            @rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			PivotTable.AcademicId,
			ClassDivisionTitle,isnull(Code,'') as Code,isnull(RollNo,0) as RollNo,
			isnull(Name,'') as Name,isnull(AttendanceTypeId,0) as AttendanceTypeId,ForYear,
			ForMonth,ClassId,ClassName,DivisionId,
			DivisionName,
			ForMonthInWord,
			(ISNULL(TC.TCount,0) - ISNULL(AC.ACount,0)) AS PresentCount,
			ISNULL(ABU.AUCount,0) AS AbsentUpto,
			ISNULL(TC.TCount,0) AS AttendanceCount,
		    ISNULL(AC.ACount,0) As  AbsentCount,
		    ISNULL(PC.PCount,0) As  PresentUpto,	    
		    
		    ClassOrderIndex,
		    DivisionOrderIndex,
		    FooterSignature,
			(ISNULL(TotalPresent,0) + ISNULL(TC.TCount,0)) AS TotalPresent,
			 
			  [sAttendance].[fWeekHOffGet](@rForYear ,@rForMonth ,1 ,@rBatchId ,@rClassId,@rDivisionId , isnull([1],''),@rOrgId )  AS P1,
			[sAttendance].[fWeekHOffGet](@rForYear ,@rForMonth ,2 ,@rBatchId ,@rClassId,@rDivisionId , isnull([2],''),@rOrgId )  AS P2,
			[sAttendance].[fWeekHOffGet](@rForYear ,@rForMonth ,3 ,@rBatchId ,@rClassId,@rDivisionId , isnull([3],''),@rOrgId )  AS P3,
			[sAttendance].[fWeekHOffGet](@rForYear ,@rForMonth ,4 ,@rBatchId ,@rClassId,@rDivisionId , isnull([4],''),@rOrgId )  AS P4,
			[sAttendance].[fWeekHOffGet](@rForYear ,@rForMonth ,5 ,@rBatchId ,@rClassId,@rDivisionId , isnull([5],''),@rOrgId )  AS P5,
			[sAttendance].[fWeekHOffGet](@rForYear ,@rForMonth ,6 ,@rBatchId ,@rClassId,@rDivisionId , isnull([6],''),@rOrgId ) AS P6,
			[sAttendance].[fWeekHOffGet](@rForYear ,@rForMonth ,7 ,@rBatchId ,@rClassId,@rDivisionId , isnull([7],''),@rOrgId ) AS P7,
			[sAttendance].[fWeekHOffGet](@rForYear ,@rForMonth ,8 ,@rBatchId ,@rClassId,@rDivisionId , isnull([8],''),@rOrgId ) AS P8,
			[sAttendance].[fWeekHOffGet](@rForYear ,@rForMonth ,9 ,@rBatchId ,@rClassId,@rDivisionId , isnull([9],''),@rOrgId ) AS P9,
			[sAttendance].[fWeekHOffGet](@rForYear ,@rForMonth ,10 ,@rBatchId ,@rClassId,@rDivisionId , isnull([10],''),@rOrgId ) AS P10,
			[sAttendance].[fWeekHOffGet](@rForYear ,@rForMonth ,11 ,@rBatchId ,@rClassId,@rDivisionId , isnull([11],''),@rOrgId ) AS P11,
			[sAttendance].[fWeekHOffGet](@rForYear ,@rForMonth ,12 ,@rBatchId ,@rClassId,@rDivisionId , isnull([12],''),@rOrgId ) AS P12,
			[sAttendance].[fWeekHOffGet](@rForYear ,@rForMonth ,13 ,@rBatchId ,@rClassId,@rDivisionId , isnull([13],''),@rOrgId ) AS P13,
			[sAttendance].[fWeekHOffGet](@rForYear ,@rForMonth ,14 ,@rBatchId ,@rClassId,@rDivisionId , isnull([14],''),@rOrgId ) AS P14,
			[sAttendance].[fWeekHOffGet](@rForYear ,@rForMonth ,15 ,@rBatchId ,@rClassId,@rDivisionId , isnull([15],''),@rOrgId ) AS P15,
			[sAttendance].[fWeekHOffGet](@rForYear ,@rForMonth ,16 ,@rBatchId ,@rClassId,@rDivisionId , isnull([16],''),@rOrgId ) AS P16,
			[sAttendance].[fWeekHOffGet](@rForYear ,@rForMonth ,17 ,@rBatchId ,@rClassId,@rDivisionId , isnull([17],''),@rOrgId ) AS P17,
			[sAttendance].[fWeekHOffGet](@rForYear ,@rForMonth ,18 ,@rBatchId ,@rClassId,@rDivisionId , isnull([18],''),@rOrgId ) AS P18,
			[sAttendance].[fWeekHOffGet](@rForYear ,@rForMonth ,19 ,@rBatchId ,@rClassId,@rDivisionId , isnull([19],''),@rOrgId ) AS P19,
			[sAttendance].[fWeekHOffGet](@rForYear ,@rForMonth ,20 ,@rBatchId ,@rClassId,@rDivisionId , isnull([20],''),@rOrgId ) AS P20,
			[sAttendance].[fWeekHOffGet](@rForYear ,@rForMonth ,21 ,@rBatchId ,@rClassId,@rDivisionId , isnull([21],''),@rOrgId ) AS P21,
			[sAttendance].[fWeekHOffGet](@rForYear ,@rForMonth ,22 ,@rBatchId ,@rClassId,@rDivisionId , isnull([22],''),@rOrgId ) AS P22,
			[sAttendance].[fWeekHOffGet](@rForYear ,@rForMonth ,23 ,@rBatchId ,@rClassId,@rDivisionId , isnull([23],''),@rOrgId ) AS P23,
			[sAttendance].[fWeekHOffGet](@rForYear ,@rForMonth ,24 ,@rBatchId ,@rClassId,@rDivisionId , isnull([24],''),@rOrgId ) AS P24,
			[sAttendance].[fWeekHOffGet](@rForYear ,@rForMonth ,25 ,@rBatchId ,@rClassId,@rDivisionId , isnull([25],''),@rOrgId ) AS P25,
			[sAttendance].[fWeekHOffGet](@rForYear ,@rForMonth ,26 ,@rBatchId ,@rClassId,@rDivisionId , isnull([26],''),@rOrgId ) AS P26,
			[sAttendance].[fWeekHOffGet](@rForYear ,@rForMonth ,27 ,@rBatchId ,@rClassId,@rDivisionId , isnull([27],''),@rOrgId ) AS P27,
			[sAttendance].[fWeekHOffGet](@rForYear ,@rForMonth ,28 ,@rBatchId ,@rClassId,@rDivisionId , isnull([28],''),@rOrgId ) AS P28,
			CASE WHEN @Days>=29 THEN  [sAttendance].[fWeekHOffGet](@rForYear ,@rForMonth ,29 ,@rBatchId,@rClassId ,@rDivisionId , isnull([29],''),@rOrgId ) end AS P29,
			CASE WHEN @Days>=30 THEN [sAttendance].[fWeekHOffGet](@rForYear ,@rForMonth ,30 ,@rBatchId ,@rClassId,@rDivisionId , isnull([30],''),@rOrgId ) end AS P30,
			CASE WHEN @Days>=31 THEN [sAttendance].[fWeekHOffGet](@rForYear ,@rForMonth ,31 ,@rBatchId ,@rClassId,@rDivisionId , isnull([31],''),@rOrgId )  end AS P31,
			
	 	--	 isnull([1],'') AS P1,
			--isnull([2],'') AS P2,
			--isnull([3],'') AS P3,
			--isnull([4],'') AS P4,
			--isnull([5],'') AS P5,
			--isnull([6],'') AS P6,
			--isnull([7],'') AS P7,
			--isnull([8],'') AS P8,
			--isnull([9],'') AS P9,
			--isnull([10],'') AS P10,
			--isnull([11],'') AS P11,
			--isnull([12],'') AS P12,
			--isnull([13],'') AS P13,
			--isnull([14],'') AS P14,
			--isnull([15],'') AS P15,
			--isnull([16],'') AS P16,
			--isnull([17],'') AS P17,
			--isnull([18],'') AS P18,
			--isnull([19],'') AS P19,
			--isnull([20],'') AS P20,
			--isnull([21],'') AS P21,
			--isnull([22],'') AS P22,
			--isnull([23],'') AS P23,
			--isnull([24],'') AS P24,
			--isnull([25],'') AS P25,
			--isnull([26],'') AS P26,
			--isnull([27],'') AS P27,
			--isnull([28],'') AS P28,
			--isnull([29],'') AS P29,
			--isnull([30],'') AS P30,
			--isnull([31],'') AS P31, 
			 EmployeeName ,
 
             sCommon.fGetDaysInMonth ( @rForMonth,@rForYear) AS DaysInMonth,
              DateOfBirth,Religion,MotherName,FamilyCast,Gender,
			  CastCategory
--,
--AttendanceTagId

 
FROM
(
	Select --TID, 
		ISNULL(ClassName + '-' + DivisionName,'') AS ClassDivisionTitle,
		Code,
		RollNo,
		AcademicId,
		Name,
		AttendanceTypeId ,
		YEAR(ST.AttendanceDate) AS ForYear,
		MONTH(ST.AttendanceDate) AS ForMonth,
		DATENAME(month, ST.AttendanceDate) AS ForMonthInWord,
		ClassId,
		DivisionId,
		ClassName,
		DivisionName,
		(
			CASE  WHEN IsPresent = 1 AND ST.AttendanceTagId = 1 THEN 'LC' 
				  WHEN IsPresent = 1 AND ST.AttendanceTagId = 2 THEN 'EL' 
				  WHEN IsPresent = 1 AND ST.AttendanceTagId = 3 THEN 'N' 
				  WHEN IsPresent = 1 AND ST.AttendanceTagId = 4 THEN 'G' 
			      WHEN IsPresent = 1  THEN 'P' 
				  WHEN IsPresent = 0 THEN 'A'
				  ELSE  DT.Value END 
		)AS  IsPresent,		
		day(ST.AttendanceDate) AS DayPart,
		LeftDate
		,
		ClassOrderIndex,
		DivisionOrderIndex,
		FooterSignature,EmployeeName,
		DateOfBirth,Religion,MotherName,FamilyCast,Gender,
		CastCategory
      -- DO NOT ADD ANY FIELD HERE WITHOUT PERMISSION OF RAJENDRA
	 FROM 
		#AttendanceRegistertempTable ST 
		INNER JOIN #TempDaysTempTable DT ON DT.DayPart = ST.DayPart
	 WHERE
		((LeftDate >= @lFirstDate) OR ISNULL(LeftDate,'') = '')
) AS SourceTable 
 
	           
	        
PIVOT
(	
MIN(IsPresent)
FOR DayPart IN ([0], [1], [2], [3], [4],[5],[6],[7],[8],[9],[10],[11],[12],[13],[14],[15],[16],[17],[18],[19],[20],[21],[22],[23],[24],[25],[26],[27],[28],[29],[30],[31])
) AS PivotTable
	LEFT JOIN
	(
		Select  AcademicId AS AcademicId, COUNT(1) AS TCount 
		   FROM  
				#AttendanceRegistertempTable
		    
			GROUP BY  AcademicId
    ) TC ON TC.AcademicId = PivotTable.AcademicId
    
	LEFT JOIN
	(
		Select AcademicId AS AcademicId, COUNT(1) AS ACount 
		   FROM  #AttendanceRegistertempTable
		    WHERE   IsPresent = 0	 		
            
			GROUP BY  AcademicId
    ) AC ON AC.AcademicId = PivotTable.AcademicId
	LEFT JOIN
	(SELECT A.Id AS AcademicId, COUNT(1) AS PCount  FROM sAttendance.tStudentRegister SR 
			INNER JOIN sStudent.tAcademic A ON SR.AcademicId = A.Id 
		   INNER JOIN sStudent.tStudentMaster SA ON A.StudentId = SA.Id
		   INNER JOIN sSetup.tClassMaster CM ON A.ClassId = CM.Id
			WHERE  
			 SR.AttendanceDate < (convert(date,CONVERT(nvarchar(10), @rForYear)+ '/' +  CONVERT(nvarchar(10), @rForMonth) + '/' + '01' ))
			AND SR.IsPresent = 1	    		
            --AND (SA.StatusId = 1)
	        AND ((SR.AttendanceTypeId=@rAttendanceTypeId) OR (@rAttendanceTypeId= 0))
	        AND ((SA.OrgId=@rOrgId) OR (@rOrgId= 0))
	        AND ((A.BatchId=@rBatchId) OR (@rBatchId= 0))	          
	        AND ((A.ClassId=@rClassId) OR (@rClassId= 0))
	        AND ((SA.Code=@rStudentCode) OR (@rStudentCode=''))
	        AND ((A.Id=@rAcademicId) OR (@rAcademicId=0))	           
			AND ((CM.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))				
	        AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId= 0))
	        AND ((SA.Code>=@rFromStudentCode) OR (ISNULL(@rFromStudentCode,'')=''))
	        AND ((SA.Code<=@rToStudentCode) OR (ISNULL(@rToStudentCode,'')=''))

			GROUP BY A.Id
    ) PC ON PC.AcademicId = PivotTable.AcademicId
		LEFT JOIN
	(SELECT A.Id AS AcademicId, COUNT(1) AS AUCount  FROM sAttendance.tStudentRegister SR 
			INNER JOIN sStudent.tAcademic A ON SR.AcademicId = A.Id 
		   INNER JOIN sStudent.tStudentMaster SA ON A.StudentId = SA.Id
		   INNER JOIN sSetup.tClassMaster CM ON A.ClassId = CM.Id
			WHERE  
			 SR.AttendanceDate < (convert(date,CONVERT(nvarchar(10), @rForYear)+ '/' +  CONVERT(nvarchar(10), @rForMonth) + '/' + '01' ))
			AND SR.IsPresent = 0	    		
            --AND (SA.StatusId = 1)
	        AND ((SR.AttendanceTypeId=@rAttendanceTypeId) OR (@rAttendanceTypeId= 0))
	        AND ((SA.OrgId=@rOrgId) OR (@rOrgId= 0))
	        AND ((A.BatchId=@rBatchId) OR (@rBatchId= 0))	          
	        AND ((A.ClassId=@rClassId) OR (@rClassId= 0))
	        AND ((SA.Code=@rStudentCode) OR (@rStudentCode=''))
	        AND ((A.Id=@rAcademicId) OR (@rAcademicId=0))	           
			AND ((CM.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))				
	        AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId= 0))
	        AND ((SA.Code>=@rFromStudentCode) OR (ISNULL(@rFromStudentCode,'')=''))
	        AND ((SA.Code<=@rToStudentCode) OR (ISNULL(@rToStudentCode,'')=''))

			GROUP BY A.Id
    ) ABU ON ABU.AcademicId = PivotTable.AcademicId
	LEFT JOIN
	(SELECT A.Id AS AcademicId, COUNT(1) AS TotalPresent  FROM sAttendance.tStudentRegister SR 
			INNER JOIN sStudent.tAcademic A ON SR.AcademicId = A.Id 
		   INNER JOIN sStudent.tStudentMaster SA ON A.StudentId = SA.Id
		   INNER JOIN sSetup.tClassMaster CM ON A.ClassId = CM.Id
			WHERE  
			SR.AttendanceDate < (convert(date,CONVERT(nvarchar(10), @rForYear)+ '/' +  CONVERT(nvarchar(10), @rForMonth) + '/' + '01' ))
	        AND
	        ((SR.AttendanceTypeId=@rAttendanceTypeId) OR (@rAttendanceTypeId= 0))
	        AND ((SA.OrgId=@rOrgId) OR (@rOrgId= 0))
	        AND ((A.BatchId=@rBatchId) OR (@rBatchId= 0))	          
	        AND ((A.ClassId=@rClassId) OR (@rClassId= 0))
	        AND ((SA.Code=@rStudentCode) OR (@rStudentCode=''))
	        AND ((A.Id=@rAcademicId) OR (@rAcademicId=0))	           
			AND ((CM.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))				
	        AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId= 0))
	        AND ((SA.Code>=@rFromStudentCode) OR (ISNULL(@rFromStudentCode,'')=''))
	        AND ((SA.Code<=@rToStudentCode) OR (ISNULL(@rToStudentCode,'')=''))

			GROUP BY A.Id
    ) AA ON AA.AcademicId = PivotTable.AcademicId
 
    --ORDER BY CASE When @rOrderBy = 0 then RollNo
	   --           When @rOrderBy = 1 then Code
				
			 -- End

 ORDER BY CASE WHEN @rOrderBy = 0 then RollNo END,
		  CASE WHEN @rOrderBy = 1 then (CASE ISNUMERIC(Code) WHEN 1 THEN REPLICATE(0 , 100 - LEN(Code)) + Code ELSE Code  END)
		  END
 

select * from #TempDaysTempTable
 				
drop table #AttendanceRegistertempTable	  
drop table #TempDaysTempTable
	


	--SELECT  
	--		Convert(date,'') AS LastDate,
	--		Convert(date,'') AS LeftDate,
 --           '' AS Builder1,
	--		'' AS Builder2,
	--		Convert(bigint,0) AS AcademicId,
	--		'' AS ClassDivisionTitle,
	--		'' AS Code,
	--		0 as RollNo,
	--		'' AS Name,
	--		0 as AttendanceTypeId,
	--		0 as ForYear,
	--		0 as ForMonth,
	--		0 as ClassId,
	--		'' as ClassName,
	--		0 as DivisionId,
	--		'' as DivisionName,
	--		'' as ForMonthInWord,
	--		0 AS PresentCount,
	--		0 AS AbsentUpto,
	--		0 AS AttendanceCount,
	--	    0 As  AbsentCount,
	--	    0 As  PresentUpto,
	--	    0 as ClassOrderIndex,
	--	    0 as DivisionOrderIndex,
	--	    '' as FooterSignature,
	--		0 AS TotalPresent,
	--		'' AS P1,
	--		'' AS P2,
	--		'' AS P3,
	--		'' AS P4,
	--		'' AS P5,
	--		'' AS P6,
	--		'' AS P7,
	--		'' AS P8,
	--		'' AS P9,
	--		'' AS P10,
	--		'' AS P11,
	--		'' AS P12,
	--		'' AS P13,
	--		'' AS P14,
	--		'' AS P15,
	--		'' AS P16,
	--		'' AS P17,
	--		'' AS P18,
	--		'' AS P19,
	--		'' AS P20,
	--		'' AS P21,
	--		'' AS P22,
	--		'' AS P23,
	--		'' AS P24,
	--		'' AS P25,
	--		'' AS P26,
	--		'' AS P27,
	--		'' AS P28,
	--		'' AS P29,
	--		'' AS P30,
	--		'' AS P31,
	--		'' as EmployeeName ,
 --           0 AS DaysInMonth,
	--		Convert(date,'') AS DateOfBirth,
	--		'' as Religion,
	--		'' as MotherName,
	--		'' as FamilyCast,
	--		0 as Gender,
	--		'' as CastCategory



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


GO
ALTER PROCEDURE [sCertificate].[pPrintTemplateStudentListGet]

	 @rDepartmentId int,
	 @rClassId int,
	 @rDivisionId int,
	 @rStudentCode nvarchar(max),
	 @rBatchId int,
	 @rStatusId int = 0,
	 @rAdmissionCategoryId int= 0,		--add
	 @rCastCategoryId int = 0			--add
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
	
	SELECT 
			A.Id AS AcademicId,
		    DivM.Id AS DivisionId,
		    DivM.DisplayTitle AS DivisionName,
		    CM.Id AS ClassId,
		    CM.DisplayTitle AS ClassName,
		    CM.DisplayTitle+'-'+DivM.DisplayTitle AS ClassDivisionName,
		    DM.Id AS DepartmentId,
		    DM.DisplayTitle AS DepartmentName,
		    SM.FirstName+' '+SM.LastName AS StudentName,
		    SM.Code,
		    A.RollNo,
			A.AdmissionCategoryId,		--add
			SO.CastCategoryId			--add
	FROM 
			sStudent.tAcademic A
			RIGHT JOIN sStudent.tStudentMaster SM ON SM.Id=A.StudentId
			INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId
			INNER JOIN sSetup.tDivisionMaster DivM ON DivM.Id=A.DivisionId
			INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id = CM.DepartmentId
			LEFT JOIN	sStudent.tStudentOther SO ON SO.StudentId = A.StudentId		--add
	WHERE 
		(A.BatchId = @rBatchId)	
		AND ((DM.Id = @rDepartmentId) OR (@rDepartmentId = 0))
		AND ((CM.Id = @rClassId) OR (@rClassId = 0))
		AND ((DivM.Id = @rDivisionId) OR (@rDivisionId = 0))
		AND (ISNULL(SM.Code,0) IN( SELECT cast(item as nvarchar(20)) FROM  sCommon.fnsplit(@rStudentCode,',')) OR @rStudentCode='') 
		AND ((SM.StatusId = @rStatusId) OR (@rStatusId = 0))
		AND ((A.AdmissionCategoryId=@rAdmissionCategoryId)OR(@rAdmissionCategoryId=0))		--add
		AND ((SO.CastCategoryId=@rCastCategoryId)OR(@rCastCategoryId=0))					--add
		Order by DivM.OrderIndex,SM.Number
END
GO
PRINT N'Altering Procedure [sCommunication].[pQueryQueueGet]...';


GO

 
ALTER PROCEDURE [sCommunication].[pQueryQueueGet]
	 
	 @rQueryCategoryId int = 0,
	 --@rCreatedUserId bigint,
	 @rOrgGroupBatchId int,
	 @rOrgGroupId smallint,
	 @rQueryId bigint,
	 @rUserSourceId bigint,
	 @rMyList bit,
	 @rStatusId int = 0,
	 @rSourceId bigint = 0,
	 @rSubjectId int = 0,
	 @rFromDate date ='',
	 @rToDate date =''
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
		
BEGIN 
IF(@rMyList=0)
BEGIN
	SELECT 
			QCM.Id AS QueryCategoryId,
			ISNULL(QCM.Title,'') AS QueryCategoryMaster,
			QM.Title,
			QM.Remark,
			QM.CreatedDateTime,
			QM.StatusId,
			ISNULL(sm.Title,'') AS StatusMaster,
			QM.Id AS QueryId,
			QM.IsUserView,
			QM.IsAssigneeView,
			ODM.Title AS Department,
			U.DisplayTitle AS SourceName, 
			U.SourceTypeId, 
			'Employee' AS SourceType,
			QM.CreatedUserId AS QueryCreatedUserId,
			OM.DisplayTitle AS OrgName,
			EM.Code AS Code,
			(SELECT TOP 1 U.DisplayTitle AS SourceName FROM sCommunication.tQueryComment QC INNER JOIN sSecurity.tUser U ON U.Id=QC.CreatedUserId WHERE QC.QueryId=QM.Id AND  QM.CreatedUserId != QC.CreatedUserId ORDER BY QC.CreatedDateTime DESC) AS AnswerUserName,
			(SELECT TOP 1 CONVERT(NVARCHAR,QC.CreatedDateTime,103) AS SourceName FROM sCommunication.tQueryComment QC INNER JOIN sSecurity.tUser U ON U.Id=QC.CreatedUserId WHERE QC.QueryId=QM.Id AND QM.CreatedUserId != QC.CreatedUserId ORDER BY QC.CreatedDateTime DESC) AS AnswerUserDate,
			(CASE WHEN QM.StatusId=210 then  U.DisplayTitle ELSE '' END) AS UserName
	FROM 
			sCommunication.tQuery QM
		INNER JOIN sCommunication.tQueryCategoryMaster QCM ON QM.QueryCategoryId=QCM.Id
        INNER JOIN sCommon.tStatusMaster SM ON SM.Id=QM.StatusId
        INNER JOIN sSecurity.tUser U ON U.Id=QM.CreatedUserId
        INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id = U.SourceId AND U.SourceTypeId = 95
        INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = U.SourceId AND U.SourceTypeId = 95
        INNER JOIN sSetup.tDepartmentMaster ODM ON EJD.OrganizationDepartmentId=ODM.Id  
        INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = ODM.OrgId
        
	WHERE 
  
			((QCM.Id = @rQueryCategoryId) OR (@rQueryCategoryId = 0))
		AND ((QM.Id = @rQueryId) OR (@rQueryId = 0)) 
		AND (QCM.OrgGroupId = @rOrgGroupId) 
		AND (QM.OrgGroupBatchId = @rOrgGroupBatchId)
	    AND ((QM.StatusId=@rStatusId) OR (@rStatusId=0))
	    AND ((EJD.EmployeeId=@rSourceId) OR (@rSourceId=0))
		AND ((CAST(QM.CreatedDateTime AS DATE) >= CAST(@rFromDate AS DATE)) OR (ISNULL(CAST(@rFromDate AS DATE),'')=''))
		AND ((CAST(QM.CreatedDateTime AS DATE) <= CAST(@rToDate AS DATE)) OR (ISNULL(CAST(@rToDate AS DATE),'')=''))
		AND ISNULL(EM.IsOtherUser,0) = 0
	UNION 

	SELECT 
			QCM.Id AS QueryCategoryId,
			ISNULL(QCM.Title,'') AS QueryCategoryMaster,
			QM.Title,
			QM.Remark,
			QM.CreatedDateTime,
			QM.StatusId,
			ISNULL(sm.Title,'') AS StatusMaster,
			QM.Id AS QueryId,
			QM.IsUserView,
			QM.IsAssigneeView,
			SA.ClassName + ' ' + SA.DivisionName  AS Department,
			U.DisplayTitle AS SourceName,
			U.SourceTypeId,
			'Student' AS SourceType,
			QM.CreatedUserId AS QueryCreatedUserId,
			OM.DisplayTitle AS OrgName,
			SA.Code,
			(SELECT TOP 1 U.DisplayTitle AS SourceName FROM sCommunication.tQueryComment QC INNER JOIN sSecurity.tUser U ON U.Id=QC.CreatedUserId WHERE QC.QueryId=QM.Id AND  QM.CreatedUserId != QC.CreatedUserId ORDER BY QC.CreatedDateTime DESC) AS AnswerUserName,
			(SELECT TOP 1 CONVERT(NVARCHAR,QC.CreatedDateTime,103) AS SourceName FROM sCommunication.tQueryComment QC INNER JOIN sSecurity.tUser U ON U.Id=QC.CreatedUserId WHERE QC.QueryId=QM.Id AND QM.CreatedUserId != QC.CreatedUserId ORDER BY QC.CreatedDateTime DESC) AS AnswerUserDate,
			(CASE WHEN QM.StatusId=210 then  U.DisplayTitle ELSE '' END) AS UserName
			
	FROM 
			sCommunication.tQuery QM
        INNER JOIN sCommunication.tQueryCategoryMaster QCM ON QM.QueryCategoryId=QCM.Id
        INNER JOIN sCommon.tStatusMaster SM ON SM.Id=QM.StatusId
        INNER JOIN sSecurity.tUser U ON U.Id=QM.CreatedUserId
        INNER JOIN sStudent.vStudentAcademic SA ON SA.StudentId = U.SourceId AND U.SourceTypeId = 2003 AND SA.OrgGroupBatchId = @rOrgGroupBatchId AND SA.IsActiveBatch = 1
        INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SA.OrgId
	WHERE 
			((QCM.Id = @rQueryCategoryId) OR (@rQueryCategoryId = 0))
		AND ((QM.Id = @rQueryId) OR (@rQueryId = 0)) 
		AND (QCM.OrgGroupId=@rOrgGroupId)  
		AND (QM.OrgGroupBatchId=@rOrgGroupBatchId)
		AND ((QM.StatusId=@rStatusId) OR (@rStatusId=0))
		AND ((SA.StudentId=@rSourceId) OR (@rSourceId=0))
		AND ((CAST(QM.CreatedDateTime AS DATE) >= CAST(@rFromDate AS DATE)) OR (ISNULL(CAST(@rFromDate AS DATE),'')=''))
		AND ((CAST(QM.CreatedDateTime AS DATE) <= CAST(@rToDate AS DATE)) OR (ISNULL(CAST(@rToDate AS DATE),'')=''))
		
		
	
		UNION
		SELECT 
			QCM.Id AS QueryCategoryId,
			ISNULL(QCM.Title,'') AS QueryCategoryMaster,
			QM.Title,
			QM.Remark,
			QM.CreatedDateTime,
			QM.StatusId,
			ISNULL(sm.Title,'') AS StatusMaster,
			QM.Id AS QueryId,
			QM.IsUserView,
			QM.IsAssigneeView,
			SA.ClassName + ' ' + SA.DivisionName  AS Department,
			U.DisplayTitle AS SourceName,
			U.SourceTypeId,
			'Student' AS SourceType,
			QM.CreatedUserId AS QueryCreatedUserId,
			OM.DisplayTitle AS OrgName,
			SA.Code,
			(SELECT TOP 1 U.DisplayTitle AS SourceName FROM sCommunication.tQueryComment QC INNER JOIN sSecurity.tUser U ON U.Id=QC.CreatedUserId WHERE QC.QueryId=QM.Id AND  QM.CreatedUserId != QC.CreatedUserId ORDER BY QC.CreatedDateTime DESC) AS AnswerUserName,
			(SELECT TOP 1 CONVERT(NVARCHAR,QC.CreatedDateTime,103) AS SourceName FROM sCommunication.tQueryComment QC INNER JOIN sSecurity.tUser U ON U.Id=QC.CreatedUserId WHERE QC.QueryId=QM.Id AND QM.CreatedUserId != QC.CreatedUserId ORDER BY QC.CreatedDateTime DESC) AS AnswerUserDate,
			(CASE WHEN QM.StatusId=210 then  U.DisplayTitle ELSE '' END) AS UserName
	FROM 
		sCommunication.tQuery QM
        INNER JOIN sCommunication.tQueryCategoryMaster QCM ON QM.QueryCategoryId=QCM.Id
        INNER JOIN sCommon.tStatusMaster SM ON SM.Id=QM.StatusId
        INNER JOIN sSecurity.tUser U ON U.Id=QM.CreatedUserId
        INNER JOIN sStudent.vStudentAcademic SA ON SA.StudentId = U.SourceId AND SA.IsActiveBatch = 1 --AND U.SourceTypeId = 2003 AND SA.OrgGroupBatchId = 120100101 
        INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SA.OrgId
	WHERE 
	       ((QCM.Id = @rQueryCategoryId) OR (@rQueryCategoryId = 0))
			AND ((QM.Id = @rQueryId) OR (@rQueryId = 0)) 
			AND (QCM.OrgGroupId=@rOrgGroupId)  
			AND (QM.OrgGroupBatchId=@rOrgGroupBatchId)
			--AND QueryCategoryId IN (select QueryCategoryId FROM sCommunication.tQueryCategoryAssignedTo where  RIGHT(SourceId,2) = 25 AND SourceTypeId = 2015)
			AND ((QM.StatusId=@rStatusId) OR (@rStatusId=0))
			AND ((SA.StudentId=@rSourceId) OR (@rSourceId=0))
			AND ((QM.FromSourceId=@rUserSourceId) OR (@rUserSourceId=0)) and QM.FromSourceTypeId=2003 and QM.OrgGroupBatchId=@rOrgGroupBatchId
			AND ((CAST(QM.CreatedDateTime AS DATE) >= CAST(@rFromDate AS DATE)) OR (ISNULL(CAST(@rFromDate AS DATE),'')=''))
		    AND ((CAST(QM.CreatedDateTime AS DATE) <= CAST(@rToDate AS DATE)) OR (ISNULL(CAST(@rToDate AS DATE),'')=''))
		
		UNION
		
		
		SELECT 
			QCM.Id AS QueryCategoryId,
			ISNULL(QCM.Title,'') AS QueryCategoryMaster,
			QM.Title,
			QM.Remark,
			QM.CreatedDateTime,
			QM.StatusId,
			ISNULL(sm.Title,'') AS StatusMaster,
			QM.Id AS QueryId,
			QM.IsUserView,
			QM.IsAssigneeView,
			ODM.Title AS Department,
			U.DisplayTitle AS SourceName, 
			U.SourceTypeId, 
			'Employee' AS SourceType,
			QM.CreatedUserId AS QueryCreatedUserId,
			OM.DisplayTitle AS OrgName,
			EM.Code,
			(SELECT TOP 1 U.DisplayTitle AS SourceName FROM sCommunication.tQueryComment QC INNER JOIN sSecurity.tUser U ON U.Id=QC.CreatedUserId WHERE QC.QueryId=QM.Id AND  QM.CreatedUserId != QC.CreatedUserId ORDER BY QC.CreatedDateTime DESC) AS AnswerUserName,
			(SELECT TOP 1 CONVERT(NVARCHAR,QC.CreatedDateTime,103) AS SourceName FROM sCommunication.tQueryComment QC INNER JOIN sSecurity.tUser U ON U.Id=QC.CreatedUserId WHERE QC.QueryId=QM.Id AND QM.CreatedUserId != QC.CreatedUserId ORDER BY QC.CreatedDateTime DESC) AS AnswerUserDate,
			(CASE WHEN QM.StatusId=210 then  U.DisplayTitle ELSE '' END) AS UserName
	FROM 
			sCommunication.tQuery QM
		INNER JOIN sCommunication.tQueryCategoryMaster QCM ON QM.QueryCategoryId=QCM.Id
        INNER JOIN sCommon.tStatusMaster SM ON SM.Id=QM.StatusId
        INNER JOIN sSecurity.tUser U ON U.Id=QM.CreatedUserId  
        INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id = QM.AssignedToEmployeeId 
        INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id
        INNER JOIN sSetup.tDepartmentMaster ODM ON EJD.OrganizationDepartmentId=ODM.Id 
        INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = EM.OrgId
	
	 WHERE 
	 
	 ((QCM.Id = @rQueryCategoryId) OR (@rQueryCategoryId = 0))
	 AND ((QM.Id = @rQueryId) OR (@rQueryId = 0)) 
	 AND (QCM.OrgGroupId=@rOrgGroupId)  
	 AND (QM.OrgGroupBatchId=@rOrgGroupBatchId)
	 AND ((QM.StatusId=@rStatusId) OR (@rStatusId=0))
	 
	 AND ((QM.AssignedToEmployeeId=@rUserSourceId) OR (@rUserSourceId=0))
	 AND ISNULL(EM.IsOtherUser,0) = 0
	 AND ((CAST(QM.CreatedDateTime AS DATE) >= CAST(@rFromDate AS DATE)) OR (ISNULL(CAST(@rFromDate AS DATE),'')=''))
	 AND ((CAST(QM.CreatedDateTime AS DATE) <= CAST(@rToDate AS DATE)) OR (ISNULL(CAST(@rToDate AS DATE),'')=''))
	 ORDER BY QM.CreatedDateTime DESC
	 --and QM.FromSourceTypeId=95
		
		
END
ELSE IF(@rMyList=1)
BEGIN

	SELECT 
			QCM.Id AS QueryCategoryId,
			ISNULL(QCM.Title,'') AS QueryCategoryMaster,
			QM.Title,
			QM.Remark,
			QM.CreatedDateTime,
			QM.StatusId,
			ISNULL(sm.Title,'') AS StatusMaster,
			QM.Id AS QueryId,
			QM.IsUserView,
			QM.IsAssigneeView,
			ODM.Title AS Department,
			U.DisplayTitle AS SourceName, 
			U.SourceTypeId, 
			'Employee' AS SourceType,
			QM.CreatedUserId AS QueryCreatedUserId,
			OM.DisplayTitle AS OrgName,
			EM.Code,
			(SELECT TOP 1 U.DisplayTitle AS SourceName FROM sCommunication.tQueryComment QC INNER JOIN sSecurity.tUser U ON U.Id=QC.CreatedUserId WHERE QC.QueryId=QM.Id AND  QM.CreatedUserId != QC.CreatedUserId ORDER BY QC.CreatedDateTime DESC) AS AnswerUserName,
			(SELECT TOP 1 CONVERT(NVARCHAR,QC.CreatedDateTime,103) AS SourceName FROM sCommunication.tQueryComment QC INNER JOIN sSecurity.tUser U ON U.Id=QC.CreatedUserId WHERE QC.QueryId=QM.Id AND QM.CreatedUserId != QC.CreatedUserId ORDER BY QC.CreatedDateTime DESC) AS AnswerUserDate,
			(CASE WHEN QM.StatusId=210 then  U.DisplayTitle ELSE '' END) AS UserName
	FROM 
			sCommunication.tQuery QM
		INNER JOIN sCommunication.tQueryCategoryMaster QCM ON QM.QueryCategoryId=QCM.Id
        INNER JOIN sCommon.tStatusMaster SM ON SM.Id=QM.StatusId
        INNER JOIN sSecurity.tUser U ON U.Id=QM.CreatedUserId
        INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id = U.SourceId AND U.SourceTypeId = 95
        INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = U.SourceId AND U.SourceTypeId = 95
        INNER JOIN sSetup.tDepartmentMaster ODM ON EJD.OrganizationDepartmentId=ODM.Id 
        INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = ODM.OrgId
	WHERE 
			((QCM.Id = @rQueryCategoryId) OR (@rQueryCategoryId = 0))
		AND ((QM.Id = @rQueryId) OR (@rQueryId = 0)) 
		AND (QCM.OrgGroupId = @rOrgGroupId)
		AND (QM.OrgGroupBatchId = @rOrgGroupBatchId)
	    --AND QueryCategoryId IN (select QueryCategoryId FROM sCommunication.tQueryCategoryAssignedTo where  SourceId = @rUserSourceId)
	    AND ((QM.StatusId=@rStatusId) OR (@rStatusId=0))
	    AND (( EJD.EmployeeId=@rUserSourceId) OR (@rUserSourceId=0))
		AND ((CAST(QM.CreatedDateTime AS DATE) >= CAST(@rFromDate AS DATE)) OR (ISNULL(CAST(@rFromDate AS DATE),'')=''))
		AND ((CAST(QM.CreatedDateTime AS DATE) <= CAST(@rToDate AS DATE)) OR (ISNULL(CAST(@rToDate AS DATE),'')=''))
		AND ISNULL(EM.IsOtherUser,0) = 0
	UNION 

	SELECT 
			QCM.Id AS QueryCategoryId,
			ISNULL(QCM.Title,'') AS QueryCategoryMaster,
			QM.Title,
			QM.Remark,
			QM.CreatedDateTime,
			QM.StatusId,
			ISNULL(sm.Title,'') AS StatusMaster,
			QM.Id AS QueryId,
			QM.IsUserView,
			QM.IsAssigneeView,
			SA.ClassName + ' ' + SA.DivisionName  AS Department,
			U.DisplayTitle AS SourceName,
			U.SourceTypeId,
			'Student' AS SourceType,
			QM.CreatedUserId AS QueryCreatedUserId,
			OM.DisplayTitle AS OrgName,
			SA.Code,
			(SELECT TOP 1 U.DisplayTitle AS SourceName FROM sCommunication.tQueryComment QC INNER JOIN sSecurity.tUser U ON U.Id=QC.CreatedUserId WHERE QC.QueryId=QM.Id AND  QM.CreatedUserId != QC.CreatedUserId ORDER BY QC.CreatedDateTime DESC) AS AnswerUserName,
			(SELECT TOP 1 CONVERT(NVARCHAR,QC.CreatedDateTime,103) AS SourceName FROM sCommunication.tQueryComment QC INNER JOIN sSecurity.tUser U ON U.Id=QC.CreatedUserId WHERE QC.QueryId=QM.Id AND QM.CreatedUserId != QC.CreatedUserId ORDER BY QC.CreatedDateTime DESC) AS AnswerUserDate,
			(CASE WHEN QM.StatusId=210 then  U.DisplayTitle ELSE '' END) AS UserName
	FROM 
		sCommunication.tQuery QM
        INNER JOIN sCommunication.tQueryCategoryMaster QCM ON QM.QueryCategoryId=QCM.Id
        INNER JOIN sCommon.tStatusMaster SM ON SM.Id=QM.StatusId
        INNER JOIN sSecurity.tUser U ON U.Id=QM.CreatedUserId
        INNER JOIN sStudent.vStudentAcademic SA ON SA.StudentId = U.SourceId AND U.SourceTypeId = 2003 AND SA.OrgGroupBatchId = @rOrgGroupBatchId AND SA.IsActiveBatch = 1
        INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SA.OrgId
	WHERE 
			((QCM.Id = @rQueryCategoryId) OR (@rQueryCategoryId = 0))
		AND ((QM.Id = @rQueryId) OR (@rQueryId = 0)) 
		AND (QCM.OrgGroupId=@rOrgGroupId)  
		AND (QM.OrgGroupBatchId=@rOrgGroupBatchId)
		AND QueryCategoryId IN (select QueryCategoryId FROM sCommunication.tQueryCategoryAssignedTo where  SourceId = @rUserSourceId AND SourceTypeId <> 2015)
		AND ((QM.StatusId=@rStatusId) OR (@rStatusId=0))
		AND ((SA.StudentId=@rSourceId) OR (@rSourceId=0))
		AND ((CAST(QM.CreatedDateTime AS DATE) >= CAST(@rFromDate AS DATE)) OR (ISNULL(CAST(@rFromDate AS DATE),'')=''))
		AND ((CAST(QM.CreatedDateTime AS DATE) <= CAST(@rToDate AS DATE)) OR (ISNULL(CAST(@rToDate AS DATE),'')=''))
	UNION 

	SELECT 
			QCM.Id AS QueryCategoryId,
			ISNULL(QCM.Title,'') AS QueryCategoryMaster,
			QM.Title,
			QM.Remark,
			QM.CreatedDateTime,
			QM.StatusId,
			ISNULL(sm.Title,'') AS StatusMaster,
			QM.Id AS QueryId,
			QM.IsUserView,
			QM.IsAssigneeView,
			SA.ClassName + ' ' + SA.DivisionName  AS Department,
			U.DisplayTitle AS SourceName,
			U.SourceTypeId,
			'Student' AS SourceType,
			QM.CreatedUserId AS QueryCreatedUserId,
			OM.DisplayTitle AS OrgName,
			SA.Code,
			(SELECT TOP 1 U.DisplayTitle AS SourceName FROM sCommunication.tQueryComment QC INNER JOIN sSecurity.tUser U ON U.Id=QC.CreatedUserId WHERE QC.QueryId=QM.Id AND  QM.CreatedUserId != QC.CreatedUserId ORDER BY QC.CreatedDateTime DESC) AS AnswerUserName,
			(SELECT TOP 1 CONVERT(NVARCHAR,QC.CreatedDateTime,103) AS SourceName FROM sCommunication.tQueryComment QC INNER JOIN sSecurity.tUser U ON U.Id=QC.CreatedUserId WHERE QC.QueryId=QM.Id AND QM.CreatedUserId != QC.CreatedUserId ORDER BY QC.CreatedDateTime DESC) AS AnswerUserDate,
			(CASE WHEN QM.StatusId=210 then  U.DisplayTitle ELSE '' END) AS UserName
	FROM 
		sCommunication.tQuery QM
        INNER JOIN sCommunication.tQueryCategoryMaster QCM ON QM.QueryCategoryId=QCM.Id
        INNER JOIN sCommon.tStatusMaster SM ON SM.Id=QM.StatusId
        INNER JOIN sSecurity.tUser U ON U.Id=QM.CreatedUserId
        INNER JOIN sStudent.vStudentAcademic SA ON SA.StudentId = U.SourceId AND U.SourceTypeId = 2003 AND SA.OrgGroupBatchId = @rOrgGroupBatchId AND SA.IsActiveBatch = 1
					AND SA.DivisionId IN (SELECT Id FROM sSetup.tDivisionMaster WHERE InchargeEmployeeId=@rUserSourceId)
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SA.OrgId			
	WHERE 
			((QCM.Id = @rQueryCategoryId) OR (@rQueryCategoryId = 0))
		AND ((QM.Id = @rQueryId) OR (@rQueryId = 0)) 
		AND (QCM.OrgGroupId=@rOrgGroupId)  
		AND (QM.OrgGroupBatchId=@rOrgGroupBatchId)
		AND QueryCategoryId IN (select QueryCategoryId FROM sCommunication.tQueryCategoryAssignedTo where  RIGHT(SourceId,2) = 24 AND SourceTypeId = 2015)
		AND ((QM.StatusId=@rStatusId) OR (@rStatusId=0))
		AND ((SA.StudentId=@rSourceId) OR (@rSourceId=0))
		AND ((CAST(QM.CreatedDateTime AS DATE) >= CAST(@rFromDate AS DATE)) OR (ISNULL(CAST(@rFromDate AS DATE),'')=''))
		AND ((CAST(QM.CreatedDateTime AS DATE) <= CAST(@rToDate AS DATE)) OR (ISNULL(CAST(@rToDate AS DATE),'')=''))
	UNION 

	SELECT 
			QCM.Id AS QueryCategoryId,
			ISNULL(QCM.Title,'') AS QueryCategoryMaster,
			QM.Title,
			QM.Remark,
			QM.CreatedDateTime,
			QM.StatusId,
			ISNULL(sm.Title,'') AS StatusMaster,
			QM.Id AS QueryId,
			QM.IsUserView,
			QM.IsAssigneeView,
			SA.ClassName + ' ' + SA.DivisionName  AS Department,
			U.DisplayTitle AS SourceName,
			U.SourceTypeId,
			'Student' AS SourceType,
			QM.CreatedUserId AS QueryCreatedUserId,
			OM.DisplayTitle AS OrgName,
			SA.Code,
			(SELECT TOP 1 U.DisplayTitle AS SourceName FROM sCommunication.tQueryComment QC INNER JOIN sSecurity.tUser U ON U.Id=QC.CreatedUserId WHERE QC.QueryId=QM.Id AND  QM.CreatedUserId != QC.CreatedUserId ORDER BY QC.CreatedDateTime DESC) AS AnswerUserName,
			(SELECT TOP 1 CONVERT(NVARCHAR,QC.CreatedDateTime,103) AS SourceName FROM sCommunication.tQueryComment QC INNER JOIN sSecurity.tUser U ON U.Id=QC.CreatedUserId WHERE QC.QueryId=QM.Id AND QM.CreatedUserId != QC.CreatedUserId ORDER BY QC.CreatedDateTime DESC) AS AnswerUserDate,
			(CASE WHEN QM.StatusId=210 then  U.DisplayTitle ELSE '' END) AS UserName
	FROM 
		sCommunication.tQuery QM
        INNER JOIN sCommunication.tQueryCategoryMaster QCM ON QM.QueryCategoryId=QCM.Id
        INNER JOIN sCommon.tStatusMaster SM ON SM.Id=QM.StatusId
        INNER JOIN sSecurity.tUser U ON U.Id=QM.CreatedUserId
        INNER JOIN sStudent.vStudentAcademic SA ON SA.StudentId = U.SourceId AND U.SourceTypeId = 2003 AND SA.OrgGroupBatchId = @rOrgGroupBatchId AND SA.IsActiveBatch = 1
        INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SA.OrgId
	WHERE 
			((QCM.Id = @rQueryCategoryId) OR (@rQueryCategoryId = 0))
		AND ((QM.Id = @rQueryId) OR (@rQueryId = 0)) 
		AND (QCM.OrgGroupId=@rOrgGroupId)  
		AND (QM.OrgGroupBatchId=@rOrgGroupBatchId)
		AND QueryCategoryId IN (select QueryCategoryId FROM sCommunication.tQueryCategoryAssignedTo where  RIGHT(SourceId,2) = 25 AND SourceTypeId = 2015)
		AND ((QM.StatusId=@rStatusId) OR (@rStatusId=0))
		AND ((SA.StudentId=@rSourceId) OR (@rSourceId=0))
		AND ((CAST(QM.CreatedDateTime AS DATE) >= CAST(@rFromDate AS DATE)) OR (ISNULL(CAST(@rFromDate AS DATE),'')=''))
		AND ((CAST(QM.CreatedDateTime AS DATE) <= CAST(@rToDate AS DATE)) OR (ISNULL(CAST(@rToDate AS DATE),'')=''))
		
		
		UNION 

	SELECT 
			QCM.Id AS QueryCategoryId,
			ISNULL(QCM.Title,'') AS QueryCategoryMaster,
			QM.Title,
			QM.Remark,
			QM.CreatedDateTime,
			QM.StatusId,
			ISNULL(sm.Title,'') AS StatusMaster,
			QM.Id AS QueryId,
			QM.IsUserView,
			QM.IsAssigneeView,
			SA.ClassName + ' ' + SA.DivisionName  AS Department,
			U.DisplayTitle AS SourceName,
			U.SourceTypeId,
			'Student' AS SourceType,
			QM.CreatedUserId AS QueryCreatedUserId,
			OM.DisplayTitle AS OrgName,
			SA.Code,
			(SELECT TOP 1 U.DisplayTitle AS SourceName FROM sCommunication.tQueryComment QC INNER JOIN sSecurity.tUser U ON U.Id=QC.CreatedUserId WHERE QC.QueryId=QM.Id AND  QM.CreatedUserId != QC.CreatedUserId ORDER BY QC.CreatedDateTime DESC) AS AnswerUserName,
			(SELECT TOP 1 CONVERT(NVARCHAR,QC.CreatedDateTime,103) AS SourceName FROM sCommunication.tQueryComment QC INNER JOIN sSecurity.tUser U ON U.Id=QC.CreatedUserId WHERE QC.QueryId=QM.Id AND QM.CreatedUserId != QC.CreatedUserId ORDER BY QC.CreatedDateTime DESC) AS AnswerUserDate,
			(CASE WHEN QM.StatusId=210 then  U.DisplayTitle ELSE '' END) AS UserName
	FROM 
		sCommunication.tQuery QM
        INNER JOIN sCommunication.tQueryCategoryMaster QCM ON QM.QueryCategoryId=QCM.Id
        INNER JOIN sCommon.tStatusMaster SM ON SM.Id=QM.StatusId
        INNER JOIN sSecurity.tUser U ON U.Id=QM.CreatedUserId
        INNER JOIN sStudent.vStudentAcademic SA ON SA.StudentId = U.SourceId AND SA.IsActiveBatch = 1 --AND U.SourceTypeId = 2003 AND SA.OrgGroupBatchId = 120100101 
        INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SA.OrgId
	WHERE 
	       ((QCM.Id = @rQueryCategoryId) OR (@rQueryCategoryId = 0))
			AND ((QM.Id = @rQueryId) OR (@rQueryId = 0)) 
			AND (QCM.OrgGroupId=@rOrgGroupId)  
			AND (QM.OrgGroupBatchId=@rOrgGroupBatchId)
			--AND QueryCategoryId IN (select QueryCategoryId FROM sCommunication.tQueryCategoryAssignedTo where  RIGHT(SourceId,2) = 25 AND SourceTypeId = 2015)
			AND ((QM.StatusId=@rStatusId) OR (@rStatusId=0))
			AND ((SA.StudentId=@rSourceId) OR (@rSourceId=0))
			AND ((QM.FromSourceId=@rUserSourceId) OR (@rUserSourceId=0)) and QM.FromSourceTypeId=2003 and QM.OrgGroupBatchId=@rOrgGroupBatchId
			AND ((CAST(QM.CreatedDateTime AS DATE) >= CAST(@rFromDate AS DATE)) OR (ISNULL(CAST(@rFromDate AS DATE),'')=''))
		    AND ((CAST(QM.CreatedDateTime AS DATE) <= CAST(@rToDate AS DATE)) OR (ISNULL(CAST(@rToDate AS DATE),'')=''))
		
   UNION
    
    
    
    
    
    SELECT 
			QCM.Id AS QueryCategoryId,
			ISNULL(QCM.Title,'') AS QueryCategoryMaster,
			QM.Title,
			QM.Remark,
			QM.CreatedDateTime,
			QM.StatusId,
			ISNULL(sm.Title,'') AS StatusMaster,
			QM.Id AS QueryId,
			QM.IsUserView,
			QM.IsAssigneeView,
			SA.ClassName + ' ' + SA.DivisionName  AS Department,
			U.DisplayTitle AS SourceName, 
			U.SourceTypeId, 
			'Employee' AS SourceType,
			QM.CreatedUserId AS QueryCreatedUserId,
			OM.DisplayTitle AS OrgName,
			SA.Code,
			(SELECT TOP 1 U.DisplayTitle AS SourceName FROM sCommunication.tQueryComment QC INNER JOIN sSecurity.tUser U ON U.Id=QC.CreatedUserId WHERE QC.QueryId=QM.Id AND  QM.CreatedUserId != QC.CreatedUserId ORDER BY QC.CreatedDateTime DESC) AS AnswerUserName,
			(SELECT TOP 1 CONVERT(NVARCHAR,QC.CreatedDateTime,103) AS SourceName FROM sCommunication.tQueryComment QC INNER JOIN sSecurity.tUser U ON U.Id=QC.CreatedUserId WHERE QC.QueryId=QM.Id AND QM.CreatedUserId != QC.CreatedUserId ORDER BY QC.CreatedDateTime DESC) AS AnswerUserDate,
			(CASE WHEN QM.StatusId=210 then  U.DisplayTitle ELSE '' END) AS UserName
			
	FROM 
		sCommunication.tQuery QM
        INNER JOIN sCommunication.tQueryCategoryMaster QCM ON QM.QueryCategoryId=QCM.Id
        INNER JOIN sCommon.tStatusMaster SM ON SM.Id=QM.StatusId
        INNER JOIN sSecurity.tUser U ON U.Id=QM.CreatedUserId AND U.SourceTypeId = 95
        INNER JOIN sStudent.vStudentAcademic SA ON SA.StudentId = U.SourceId AND U.SourceTypeId = 2003 AND SA.OrgGroupBatchId = @rOrgGroupBatchId AND SA.IsActiveBatch = 1
        INNER JOIN sAcademic.tTeacherSubjectDivision TSD ON TSD.DivisionId = SA.DivisionId AND (( TSD.EmployeeId = @rUserSourceId) OR (@rUserSourceId=0)) AND QM.SubjectId= TSD.SubjectId                  
        INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SA.OrgId
        
  WHERE 
	       ((QCM.Id = @rQueryCategoryId) OR (@rQueryCategoryId = 0))
			AND ((QM.Id = @rQueryId) OR (@rQueryId = 0)) 
			AND (QM.OrgGroupId=@rOrgGroupId)  
			AND (QM.OrgGroupBatchId=@rOrgGroupBatchId)
			--AND QueryCategoryId IN (select QueryCategoryId FROM sCommunication.tQueryCategoryAssignedTo where  RIGHT(SourceId,2) = 25 AND SourceTypeId = 2015)
			AND ((QM.StatusId=@rStatusId) OR (@rStatusId=0))
			AND ((SA.StudentId=@rSourceId) OR (@rSourceId=0))
			AND ((TSD.SubjectId=@rSubjectId) OR (@rSubjectId=0))
			--AND ((QM.FromSourceId=@rUserSourceId) OR (@rUserSourceId=0)) and QM.FromSourceTypeId=2003 and QM.OrgGroupBatchId=@rOrgGroupBatchId      
			AND ((CAST(QM.CreatedDateTime AS DATE) >= CAST(@rFromDate AS DATE)) OR (ISNULL(CAST(@rFromDate AS DATE),'')=''))
		    AND ((CAST(QM.CreatedDateTime AS DATE) <= CAST(@rToDate AS DATE)) OR (ISNULL(CAST(@rToDate AS DATE),'')=''))
	 
	 UNION
    
    SELECT 
			QCM.Id AS QueryCategoryId,
			ISNULL(QCM.Title,'') AS QueryCategoryMaster,
			QM.Title,
			QM.Remark,
			QM.CreatedDateTime,
			QM.StatusId,
			ISNULL(sm.Title,'') AS StatusMaster,
			QM.Id AS QueryId,
			QM.IsUserView,
			QM.IsAssigneeView,
			ODM.Title AS Department,
			U.DisplayTitle AS SourceName, 
			U.SourceTypeId, 
			'Employee' AS SourceType,
			QM.CreatedUserId AS QueryCreatedUserId,
			OM.DisplayTitle AS OrgName,
			EM.Code,
			(SELECT TOP 1 U.DisplayTitle AS SourceName FROM sCommunication.tQueryComment QC INNER JOIN sSecurity.tUser U ON U.Id=QC.CreatedUserId WHERE QC.QueryId=QM.Id AND  QM.CreatedUserId != QC.CreatedUserId ORDER BY QC.CreatedDateTime DESC) AS AnswerUserName,
			(SELECT TOP 1 CONVERT(NVARCHAR,QC.CreatedDateTime,103) AS SourceName FROM sCommunication.tQueryComment QC INNER JOIN sSecurity.tUser U ON U.Id=QC.CreatedUserId WHERE QC.QueryId=QM.Id AND QM.CreatedUserId != QC.CreatedUserId ORDER BY QC.CreatedDateTime DESC) AS AnswerUserDate,
			(CASE WHEN QM.StatusId=210 then  U.DisplayTitle ELSE '' END) AS UserName
	FROM 	
		
		sCommunication.tQuery QM
		INNER JOIN sCommunication.tQueryCategoryMaster QCM ON QM.QueryCategoryId=QCM.Id
        INNER JOIN sCommon.tStatusMaster SM ON SM.Id=QM.StatusId
        INNER JOIN sSecurity.tUser U ON U.Id=QM.CreatedUserId  
        INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id = QM.AssignedToEmployeeId 
        INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id
        INNER JOIN sSetup.tDepartmentMaster ODM ON EJD.OrganizationDepartmentId=ODM.Id 
        INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = EM.OrgId
	
	 WHERE 
	 
	 ((QCM.Id = @rQueryCategoryId) OR (@rQueryCategoryId = 0))
	 AND ((QM.Id = @rQueryId) OR (@rQueryId = 0)) 
	 AND (QCM.OrgGroupId=@rOrgGroupId)  
	 AND (QM.OrgGroupBatchId=@rOrgGroupBatchId)
	 AND ((QM.StatusId=@rStatusId) OR (@rStatusId=0))
	 AND ((QM.AssignedToEmployeeId=@rUserSourceId) OR (@rUserSourceId=0))
	 AND ISNULL(EM.IsOtherUser,0) = 0
	 AND ((CAST(QM.CreatedDateTime AS DATE) >= CAST(@rFromDate AS DATE)) OR (ISNULL(CAST(@rFromDate AS DATE),'')=''))
	 AND ((CAST(QM.CreatedDateTime AS DATE) <= CAST(@rToDate AS DATE)) OR (ISNULL(CAST(@rToDate AS DATE),'')=''))
	 ORDER BY QM.CreatedDateTime DESC	
	 
	 
	 
	 
	 
	 
	 
		
END
END


--SELECT Q.CreatedUserId FROM sCommunication.tQueryCategoryMaster QCM INNER JOIN sCommunication.tQuery Q ON Q.QueryCategoryId = QCM.Id
GO
PRINT N'Altering Procedure [sFee].[pFeeExportDetailsGet]...';


GO

ALTER PROCEDURE [sFee].[pFeeExportDetailsGet]    
      
  @rOrgGroupBatchId int,    
  @rAdmissionCategoryId int,    
  @rClassId int,    
  @rDivisionId int,    
  @rIdNo nvarchar(20)='',    
  @rFirstName nvarchar(100)='',    
  @rFromReceiptNumber int=0,    
  @rToReceiptNumber int=0,    
  @rReceiptBookId int=0,    
  @rSourceTypeId int=0,    
  @rPayTypeId int,    
  @rChequeNo nvarchar(40)='',    
  @rFromDate date,    
  @rToDate date,    
  @rIsObsolete bit,    
  @rOrgId smallint,    
  @rBatchId int,    
  @rOrgGroupId smallint,    
  @rCreatedUserName nvarchar(100),    
  @rCreatedUserId bigint,    
  @rDepartmentId int=0,    
  @rFromChequeDate date='',    
  @rToChequeDate date='',    
  @rSUId nvarchar(50) = '',    
  @rLastName nvarchar(100) = '',  
  @rPayTypeIds nvarchar(max) = '',
  @rBankName nvarchar(100)='',
  @rCancelStatusId int = 0
      
 WITH EXECUTE AS CALLER    
AS    
SET NOCOUNT ON    
        
    BEGIN    
		SET @rFirstName = sCommon.fSearchStringGet(@rFirstName)    
		SET @rLastName = sCommon.fSearchStringGet(@rLastName)    
		SET @rCreatedUserName = sCommon.fSearchStringGet(@rCreatedUserName)   
		SET @rBankName = sCommon.fSearchStringGet(@rBankName)    
    END 
	
BEGIN       

CREATE Table #FeeReceiptDetail
		(
		StatusId bigint,
		ReceiptId bigint,
		FeeCode nvarchar(100),
		FeeAmount decimal(12,2),
		Organization nvarchar(max),
		Batch nvarchar(100),
		BatchId bigint,
		Code nvarchar(20),
		ClassDiv nvarchar(200),
		Name nvarchar(300),
		ReceiptNumber nvarchar(200),
		ReceiptDate Date,
		ReceiptAmount decimal(12,2),
		PayType nvarchar(300),
		ChequeNo nvarchar(40),
		Remark nvarchar(max),
		ChequeDate nvarchar(50),
		InvoiceNumber int,
		ReceiptCreatedDateTime datetime,
		BankName nvarchar(200),
		ReceiptBookName nvarchar(100),
		TotalReceiptAmount decimal(12,2),
		DiscountAmount decimal(12,2),
		VariableAmount decimal(12,2),
		ExemptionAmount decimal(12,2),
		AdditionalAmount decimal(12,2),
		NotApplicableAmount decimal(12,2),
		SUId nvarchar(50)
		
		)


INSERT INTO #FeeReceiptDetail
 SELECT 
    A.StatusId,    
	R.Id AS ReceiptId,
	FM.Code,
	RD.Amount,
	OM.DisplayTitle AS Organization,  
	BM.Title AS Batch,
	BM.Id AS BatchId,
	A.Code AS Code, 
	CM.Title +' - '+ DM.Title AS ClassDiv,
	A.Name,    
	R.ReceiptNumber,   
	R.ReceiptDate,     
	ISNULL(R.ReceiptAmount,0)AS ReceiptAmount,
	PTM.Title AS PayType,    
	CASE WHEN ISNULL(R.ChequeNo,'') != '' THEN R.ChequeNo ELSE CONVERT(nvarchar(20),R.PaymentTransactionId) END AS ChequeNo,    
	R.Remark,
	CONVERT(VARCHAR(10), R.ChequeDate, 103)AS ChequeDate, 
	--ISNULL(CAST(R.ChequeDate AS Date),'') AS ChequeDate, 
	ISNULL(FI.InvoiceNumber,0) AS InvoiceNumber,    
	R.CreatedDateTime AS ReceiptCreatedDateTime,
	R.BankName,    
	RBM.Title AS ReceiptBook,    
    ISNULL(R.TotalReceiptAmount,0)AS TotalReceiptAmount,    
    ISNULL(R.DiscountAmount,0)AS DiscountAmount,
	FA.VariableAmount,
	FA.DiscountAmount AS ExemptionAmount,
	FA.AdditionalAmount,
	FA.NotApplicableAmount,
	ISNULL(A.SUId,'') As SUId
	
  
  FROM     
  
     sFee.tReceipt R    
  INNER JOIN sStudent.vStudentAcademic A    
   ON A.AcademicId=R.SourceId AND (A.AdmissionCategoryId=@rAdmissionCategoryId OR @rAdmissionCategoryId=0)   
   
  INNER JOIN  sSetup.tClassMaster CM ON CM.Id = A.ClassId     
  INNER JOIN  sSetup.tDivisionMaster DM ON DM.Id = A.DivisionId     
  INNER JOIN sCommon.tSourceTypeMaster STM    
   ON STM.Id=R.SourceTypeId    
  INNER JOIN sFinanceCommon.tPayTypeMaster PTM    
   ON PTM.Id=R.PayTypeId    
  INNER JOIN sFee.tReceiptBookMaster RBM    
   ON RBM.Id=R.ReceiptBookId    
  INNER JOIN sSetup.tOrganizationMaster OM    
   ON OM.Id=A.OrgId    
    AND OM.OrgGroupId=@rOrgGroupId    
  INNER JOIN sSetup.tBatchMaster BM    
   ON BM.Id=R.BatchId     
   AND BM.OrgGroupBatchId=@rOrgGroupBatchId    
  LEFT JOIN sSecurity.tUser U ON U.Id=R.CreatedUserId    
  INNER JOIN sFee.vUserReceiptBook URB ON URB.Id=RBM.Id AND URB.UserId=@rCreatedUserId    
  LEFT JOIN sFee.tFeeInvoice FI ON FI.Id = R.FeeInvoiceId    
  
  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
  LEFT JOIN sFee.tFeeAllocation FA ON FA.FeeSetupId=FS.Id AND FA.SourceId=A.AcademicId
  
WHERE     
 ((A.Code like @rIdNo) OR (ISNULL(@rIdNo,'')=''))    
 AND (R.SourceTypeId=2001)    
 AND ((A.FirstName like @rFirstName) OR(ISNULL(@rFirstName,'')=''))    
 AND ((R.ReceiptNumber>=@rFromReceiptNumber)OR(@rFromReceiptNumber=0))    
 AND ((R.ReceiptNumber<=@rToReceiptNumber)OR(@rToReceiptNumber=0))    
 AND ((R.ReceiptBookId=@rReceiptBookId)OR(@rReceiptBookId=0))    
 AND ((R.PayTypeId=@rPayTypeId)OR(@rPayTypeId=0))    
 AND ((ISNULL(R.PayTypeId,0) IN ( SELECT cast(item as int) FROM  sCommon.fnsplit(@rPayTypeIds,','))) OR (ISNULL(@rPayTypeIds,'')=''))
 AND ((R.ChequeNo like @rChequeNo) OR(ISNULL(@rChequeNo,'')=''))    
 AND ((STM.Id=@rSourceTypeId)OR(@rSourceTypeId=0))    
 AND ((R.ReceiptDate>=@rFromDate)OR(ISNULL(@rFromDate,'')=''))    
 AND ((R.ReceiptDate<=@rToDate)OR(ISNULL(@rToDate,'')=''))    
 AND (R.IsObsolete=@rIsObsolete)    
 AND ((A.OrgId=@rOrgId) OR (@rOrgId=0))    
 AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))    
 AND ((ISNULL(U.DisplayTitle,'') like @rCreatedUserName) OR (ISNULL(@rCreatedUserName,'')=''))    
 AND ((CM.DepartmentId = @rDepartmentId) OR (@rDepartmentId=0))    
 AND ((A.ClassId=@rClassId) OR (@rClassId=0))     
 AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId=0))    
 AND ((R.ChequeDate>=@rFromChequeDate)OR(ISNULL(@rFromChequeDate,'')=''))    
 AND ((R.ChequeDate<=@rToChequeDate)OR(ISNULL(@rToChequeDate,'')=''))    
 AND ((A.SUId like @rSUId) OR (ISNULL(@rSUId,'')=''))    
 AND ((A.LastName like @rLastName) OR (ISNULL(@rLastName,'')=''))  
 AND ((R.BankName like @rBankName) OR(ISNULL(@rBankName,'')=''))    
 AND ((R.CancelStatusId = @rCancelStatusId) OR(@rCancelStatusId=0)) ----Added By Dhruv for Issue No.11130    
 ORDER BY R.ReceiptNumber DESC   
 
 --Select * from #FeeReceiptDetail
 DECLARE @cols AS NVARCHAR(MAX),@query  AS NVARCHAR(MAX)

    SELECT @cols = STUFF((SELECT  DISTINCT ',' + QUOTENAME(ID.FeeCode)
                       FROM #FeeReceiptDetail ID FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'),1,1,'')   
 
    SELECT @query = 
    'SELECT  
			P.*,
            ID.VariableAmount,
            ID.ExemptionAmount,
            ID.AdditionalAmount,
            ID.NotApplicableAmount ,
			ID.DiscountAmount
     FROM
    (SELECT  
	
		ReceiptId ,
		Organization ,
		Batch ,
		Code ,
		SUId,
		ClassDiv ,
		Name ,
		ReceiptNumber ,
		ReceiptDate ,
		ReceiptAmount ,
		Remark,
		PayType ,
		ChequeNo ,
		ChequeDate, 
		BankName ,
		ReceiptBookName ,
		InvoiceNumber,    
		ReceiptCreatedDateTime,
		TotalReceiptAmount ,
		FeeCode, 
        FeeAmount
				    		
    FROM #FeeReceiptDetail)X
    PIVOT 
    (
         SUM(FeeAmount) 
         FOR [FeeCode] IN (' +  @cols + ')
    ) P
    LEFT JOIN
	(
		SELECT
		    ReceiptId,
			SUM(VariableAmount) AS VariableAmount,
			SUM(ExemptionAmount) AS ExemptionAmount,
			SUM(AdditionalAmount) AS AdditionalAmount,
			SUM(NotApplicableAmount) AS NotApplicableAmount,
			(DiscountAmount) AS DiscountAmount
		FROM  
			#FeeReceiptDetail
			GROUP BY ReceiptId,DiscountAmount
    ) ID ON ID.ReceiptId = P.ReceiptId
	Order By P.ReceiptNumber DESC
    '
	EXECUTE(@query) 
END
GO
PRINT N'Altering Procedure [sFee].[pPendingFeeDashboardGet]...';


GO

ALTER PROCEDURE [sFee].[pPendingFeeDashboardGet]

		@rOrgGroupBatchId int = 0,
		@rCommonOrgGroupBatchId int = 0,
		@rType int,
		@rFilterType nvarchar(Max),
		@rFeeType nvarchar(Max),
		@rStudentStatus int = 0,
		@rUptoDate date = '',
		@rDepartmentId int=0,
	    @rOrgId int,
		@rReceiptBookId int,
		@rOrgGroupId int = 0

	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

SELECT @rOrgGroupBatchId = Id FROM sSetup.tOrgGroupBatchMaster WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND OrgGroupId = @rOrgGroupId

IF (@rType = 1)
 BEGIN
IF(@rFilterType = 'Organizationwise')		
	BEGIN 
	 IF(@rFeeType = 'FeeHeadwise')
	 BEGIN
		--SELECT
		--	SA.OrgId,
		--	O.Title AS OrgName,
		--	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,
		--	FHM.Id AS FeeHeadId,
		--	FHM.Title AS FeeHeadName,
		--	FHM.OrderIndex
		--FROM
		--	sStudent.vStudentAcademic SA
		--	INNER JOIN sSetup.tOrganizationMaster O ON SA.OrgId = O.Id
		--	INNER JOIN 
		--	(
		--		SELECT 
		--			ISNULL(FS1.Amount,0)AS Amount,
		--			FM.Title AS FeeName,
		--			FM.FeeHeadId,
		--			SA1.Id As AcademicId,
		--			FS1.Id,
		--			FS1.StartDate
 	--			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 sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
		--		WHERE 
		--			BM.OrgGroupBatchId = @rOrgGroupBatchId
		--			AND (FS1.IsOptional=0)
		--			-- IsInContext
		--			AND BM.IsInContext = 1
		--		UNION ALL
		--		SELECT 
		--			ISNULL(FS1.Amount,0)AS Amount,
		--			FM.Title AS FeeName,
		--			FM.FeeHeadId,
		--			SA1.AcademicId As AcademicId,
		--			FS1.Id,
		--			FS1.StartDate
		--		FROM sFee.tFeeSetup FS1
		--		INNER JOIN sFee.tFeeOptional FO ON FO.FeeSetupId=FS1.Id
		--		INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
		--		INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=FO.SourceId 
		--		AND SA1.BatchId = FS1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId AND SA1.ClassId = FS1.ClassId
		--		INNER JOIN sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
		--		WHERE
		--				SA1.OrgGroupBatchId = @rOrgGroupBatchId
		--				AND (FS1.IsOptional=1)
		--				-- IsInContext
		--				AND BM.IsInContext = 1
		--		) FS ON FS.AcademicId=SA.AcademicId
		--		LEFT JOIN sFee.tFeeAllocation FA ON FA.FeeSetupId=FS.Id AND FA.SourceId=SA.AcademicId
		--		LEFT JOIN
		--		(
		--			SELECT 
		--			    ISNULL(SUM(RD.Amount),0) AS PaidAmount,RD.FeeSetupId ,R.SourceId
		--			FROM
		--				sFee.tReceipt R 
		--				INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id 
		--				INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id
		--				INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id
		--				INNER JOIN sStudent.tAcademic SA1 ON SA1.Id=R.SourceId
		--				INNER JOIN sSetup.tBatchMaster BM ON BM.Id=SA1.BatchId			
		--			WHERE		
		--				(R.SourceTypeId = 2001)
		--				AND (R.IsObsolete = 0) 
		--				AND ((BM.OrgGroupBatchId = @rOrgGroupBatchId))
		--				AND (R.OrgGroupBatchId = @rOrgGroupBatchId)
		--				AND (R.ReceiptDate <= @rUptoDate) 
		--				-- IsInContext
		--				AND BM.IsInContext = 1 
		--				GROUP BY FeeSetupId,R.SourceId
		--		) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
		--		INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id = FS.FeeHeadId	
		--		INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId
		--	WHERE
		--	  SA.OrgGroupBatchId = @rOrgGroupBatchId
		--	  AND (SA.StatusId = @rStudentStatus OR @rStudentStatus=0)
		--	  AND ((FS.StartDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
		--	  -- IsInContext
		--	  AND BM.IsInContext = 1
		--	GROUP BY SA.OrgId,O.Title,FHM.Id,FHM.Title,FHM.OrderIndex
		--	ORDER BY OrgId,FHM.OrderIndex

		CREATE TABLE #FeeHeadwisetmp
		(
		Amount decimal (12,2),
		FeeName nvarchar(100),
		FeeHeadId int,
		AcademicId bigint,
		Id int,
		StartDate date
		--ReceiptBookId int 
		)

		INSERT INTO #FeeHeadwisetmp
		SELECT 
					ISNULL(FS1.Amount,0)AS Amount,
					FM.Title AS FeeName,
					FM.FeeHeadId,
					SA1.Id As AcademicId,
					FS1.Id,
					FS1.StartDate
 				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 sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
				WHERE 
					BM.OrgGroupBatchId = @rOrgGroupBatchId
					AND (FS1.IsOptional=0)
					-- IsInContext
					AND BM.IsInContext = 1
				UNION ALL
				SELECT 
					ISNULL(FS1.Amount,0)AS Amount,
					FM.Title AS FeeName,
					FM.FeeHeadId,
					SA1.AcademicId As AcademicId,
					FS1.Id,
					FS1.StartDate
				FROM sFee.tFeeSetup FS1
				INNER JOIN sFee.tFeeOptional FO ON FO.FeeSetupId=FS1.Id
				INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
				INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=FO.SourceId 
				AND SA1.BatchId = FS1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId AND SA1.ClassId = FS1.ClassId
				INNER JOIN sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
				WHERE
						SA1.OrgGroupBatchId = @rOrgGroupBatchId
						AND (FS1.IsOptional=1)
						-- IsInContext
						AND BM.IsInContext = 1

		SELECT
			SA.OrgId,
			O.Title AS OrgName,
			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,
			FHM.Id AS FeeHeadId,
			FHM.Title AS FeeHeadName,
			FHM.OrderIndex
		FROM
			sStudent.vStudentAcademic SA
			INNER JOIN sSetup.tOrganizationMaster O ON SA.OrgId = O.Id
			INNER JOIN #FeeHeadwisetmp 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.tAcademic SA1 ON SA1.Id=R.SourceId
						INNER JOIN sSetup.tBatchMaster BM ON BM.Id=SA1.BatchId			
					WHERE		
						(R.SourceTypeId = 2001)
						AND (R.IsObsolete = 0) 
						AND ((BM.OrgGroupBatchId = @rOrgGroupBatchId))
						AND (R.OrgGroupBatchId = @rOrgGroupBatchId)
						AND (R.ReceiptDate <= @rUptoDate) 
						-- IsInContext
						AND BM.IsInContext = 1 
						GROUP BY FeeSetupId,R.SourceId
				) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
				INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id = FS.FeeHeadId	
				INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId
			WHERE
			  SA.OrgGroupBatchId = @rOrgGroupBatchId
			  AND (SA.StatusId = @rStudentStatus OR @rStudentStatus=0)
			  AND ((FS.StartDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
			  -- IsInContext
			  AND BM.IsInContext = 1
			GROUP BY SA.OrgId,O.Title,FHM.Id,FHM.Title,FHM.OrderIndex
			ORDER BY OrgId,FHM.OrderIndex

		DROP TABLE #FeeHeadwisetmp
	 END
	 ELSE IF(@rFeeType = 'FeeMasterwise')
	 BEGIN
		CREATE TABLE #FeeMasterwisetmp
		(
			FeeId int,
			Amount decimal (12,2),
			FeeName nvarchar(100),
			FeeHeadId int,
			AcademicId bigint,
			Id int,
			StartDate date,
			OrderIndex int
		)
	 
	 INSERT INTO #FeeMasterwisetmp
		 SELECT 
			FS1.FeeId,
			ISNULL(FS1.Amount,0)AS Amount,
			FM.Title AS FeeName,
			FM.FeeHeadId,
			SA1.Id As AcademicId,
			FS1.Id,
			FS1.StartDate,
			FM.OrderIndex
 		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 sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
		WHERE 
			BM.OrgGroupBatchId = @rOrgGroupBatchId
			AND (FS1.IsOptional=0)
			-- IsInContext
			AND BM.IsInContext = 1
		UNION ALL
		SELECT 
			FS1.FeeId,
			ISNULL(FS1.Amount,0)AS Amount,
			FM.Title AS FeeName,
			FM.FeeHeadId,
			SA1.AcademicId As AcademicId,
			FS1.Id,
			FS1.StartDate,
			FM.OrderIndex
		FROM sFee.tFeeSetup FS1
		INNER JOIN sFee.tFeeOptional FO ON FO.FeeSetupId=FS1.Id
		INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
		INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=FO.SourceId 
		AND SA1.BatchId = FS1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId AND SA1.ClassId = FS1.ClassId
		INNER JOIN sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
		WHERE
				SA1.OrgGroupBatchId = @rOrgGroupBatchId
				AND (FS1.IsOptional=1)
				-- IsInContext
				AND BM.IsInContext = 1

	 SELECT
			SA.OrgId,
			O.Title AS OrgName,
			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,
			FS.FeeId,
			FS.FeeName,
			FS.OrderIndex
		FROM
			sStudent.vStudentAcademic SA
				INNER JOIN sSetup.tOrganizationMaster O ON SA.OrgId = O.Id
				INNER JOIN #FeeMasterwisetmp 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.tAcademic SA1 ON SA1.Id=R.SourceId
						INNER JOIN sSetup.tBatchMaster BM ON BM.Id=SA1.BatchId			
					WHERE		
						(R.SourceTypeId = 2001)
						AND (R.IsObsolete = 0) 
						AND ((BM.OrgGroupBatchId = @rOrgGroupBatchId))
						AND (R.OrgGroupBatchId = @rOrgGroupBatchId)
						AND (R.ReceiptDate <= @rUptoDate) 
						-- IsInContext
						AND BM.IsInContext = 1 
						GROUP BY FeeSetupId,R.SourceId
				) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
				INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id = FS.FeeHeadId	
				INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId
			WHERE
				SA.OrgGroupBatchId = @rOrgGroupBatchId
				AND (SA.StatusId = @rStudentStatus OR @rStudentStatus=0)
				AND ((FS.StartDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
				-- IsInContext
				AND BM.IsInContext = 1
			GROUP BY SA.OrgId,O.Title,FS.FeeId,FS.FeeName,FS.OrderIndex
			ORDER BY OrgId,FS.FeeId
	 DROP TABLE #FeeMasterwisetmp
	 END
	 ELSE IF(@rFeeType = 'CollectionGroupwise')
	 BEGIN
		CREATE TABLE #CollectionGroupwisetmp
		(
			FeeId int,
			Amount decimal (12,2),
			FeeName nvarchar(100),
			FeeHeadId int,
			AcademicId bigint,
			Id int,
			StartDate date,
			CollectionGroupId int
		)
	 INSERT INTO #CollectionGroupwisetmp
	 SELECT 
			FS1.FeeId,
			ISNULL(FS1.Amount,0)AS Amount,
			FM.Title AS FeeName,
			FM.FeeHeadId,
			SA1.Id As AcademicId,
			FS1.Id,
			FS1.StartDate,
			FS1.CollectionGroupId
 		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 sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
		WHERE 
			BM.OrgGroupBatchId = @rOrgGroupBatchId
			AND (FS1.IsOptional=0)
			-- IsInContext
			AND BM.IsInContext = 1
		UNION ALL
		SELECT 
			FS1.FeeId,
			ISNULL(FS1.Amount,0)AS Amount,
			FM.Title AS FeeName,
			FM.FeeHeadId,
			SA1.AcademicId As AcademicId,
			FS1.Id,
			FS1.StartDate,
			FS1.CollectionGroupId
		FROM sFee.tFeeSetup FS1
		INNER JOIN sFee.tFeeOptional FO ON FO.FeeSetupId=FS1.Id
		INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
		INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=FO.SourceId 
		AND SA1.BatchId = FS1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId AND SA1.ClassId = FS1.ClassId
		INNER JOIN sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
		WHERE
				SA1.OrgGroupBatchId = @rOrgGroupBatchId
				AND (FS1.IsOptional=1)
				-- IsInContext
				AND BM.IsInContext = 1

	 SELECT
			SA.OrgId,
			O.Title AS OrgName,
			SUM(ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00))AS PendingAmount,
			ISNULL(CGM.Id,0) AS CollectionGroupId,
			ISNULL(CGM.Title,'') AS CollectionGroupName,
			ISNULL(CGM.OrderIndex,0) AS OrderIndex
		FROM
			sStudent.vStudentAcademic SA
			INNER JOIN sSetup.tOrganizationMaster O ON SA.OrgId = O.Id
			INNER JOIN #CollectionGroupwisetmp 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.tAcademic SA1 ON SA1.Id=R.SourceId
						INNER JOIN sSetup.tBatchMaster BM ON BM.Id=SA1.BatchId			
					WHERE		
						(R.SourceTypeId = 2001)
						AND (R.IsObsolete = 0) 
						AND ((BM.OrgGroupBatchId = @rOrgGroupBatchId))
						AND (R.OrgGroupBatchId = @rOrgGroupBatchId)
						AND (R.ReceiptDate <= @rUptoDate) 
						-- IsInContext
						AND BM.IsInContext = 1 
						GROUP BY FeeSetupId,R.SourceId
				) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
				LEFT JOIN sFee.tCollectionGroupMaster CGM ON FS.CollectionGroupId=CGM.Id
				INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId
			WHERE
			  SA.OrgGroupBatchId = @rOrgGroupBatchId
			  AND (SA.StatusId = @rStudentStatus OR @rStudentStatus=0)
			  AND ((FS.StartDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
			  -- IsInContext
			  AND BM.IsInContext = 1
			GROUP BY SA.OrgId,O.Title,CGM.Id,CGM.Title,CGM.OrderIndex
			ORDER BY OrgId,CGM.Id

	 DROP TABLE #CollectionGroupwisetmp
	 END
	END
ELSE IF(@rFilterType = 'Departmentwise')
	BEGIN
	 IF(@rFeeType = 'FeeHeadwise')
	 BEGIN
		IF OBJECT_ID('tempdb..#tmpDepartFeeHeadWise') IS NOT NULL DROP TABLE #tmpDepartFeeHeadWise
		CREATE TABLE #tmpDepartFeeHeadWise
		(
		Amount decimal (12,2),
		FeeName nvarchar(100),
		FeeHeadId int,
		AcademicId bigint,
		Id int,
		StartDate date
		)

		Insert Into #tmpDepartFeeHeadWise
		SELECT 
					ISNULL(FS1.Amount,0)AS Amount,
					FM.Title AS FeeName,
					FM.FeeHeadId,
					SA1.Id As AcademicId,
					FS1.Id,
					FS1.StartDate
 				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 sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
				WHERE 
					BM.OrgGroupBatchId = @rOrgGroupBatchId
					AND (FS1.IsOptional=0)
					-- IsInContext
					AND BM.IsInContext = 1
				UNION ALL
				SELECT 
					ISNULL(FS1.Amount,0)AS Amount,
					FM.Title AS FeeName,
					FM.FeeHeadId,
					SA1.AcademicId As AcademicId,
					FS1.Id,
					FS1.StartDate
				FROM sFee.tFeeSetup FS1
				INNER JOIN sFee.tFeeOptional FO ON FO.FeeSetupId=FS1.Id
				INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
				INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=FO.SourceId 
				AND SA1.BatchId = FS1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId AND SA1.ClassId = FS1.ClassId
				INNER JOIN sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
				WHERE
						SA1.OrgGroupBatchId = @rOrgGroupBatchId
						AND (FS1.IsOptional=1)
						-- IsInContext
						AND BM.IsInContext = 1

		SELECT
			SA.DepartmentId,
		    SA.DepartmentName,
			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,
			FHM.Id AS FeeHeadId,
			FHM.Title AS FeeHeadName,
			FHM.OrderIndex
		FROM
			sStudent.vStudentAcademic SA
				INNER JOIN sSetup.tOrganizationMaster O ON SA.OrgId = O.Id
				INNER JOIN  #tmpDepartFeeHeadWise 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.tAcademic SA1 ON SA1.Id=R.SourceId
						INNER JOIN sSetup.tBatchMaster BM ON BM.Id=SA1.BatchId			
					WHERE		
						(R.SourceTypeId = 2001)
						AND (R.IsObsolete = 0) 
						AND ((BM.OrgGroupBatchId = @rOrgGroupBatchId))
						AND (R.OrgGroupBatchId = @rOrgGroupBatchId)
						AND (R.ReceiptDate <= @rUptoDate)
						-- IsInContext
						AND BM.IsInContext = 1  
						GROUP BY FeeSetupId,R.SourceId
				) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
				INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id = FS.FeeHeadId	
				INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId
			WHERE
			  SA.OrgGroupBatchId = @rOrgGroupBatchId
			  AND (SA.StatusId = @rStudentStatus OR @rStudentStatus=0)
			  AND ((FS.StartDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
			  -- IsInContext
			  AND BM.IsInContext = 1 
			GROUP BY SA.DepartmentId,SA.DepartmentName,FHM.Id,FHM.Title,FHM.OrderIndex
			ORDER BY DepartmentId,FHM.Id
	 END
	 ELSE IF(@rFeeType = 'FeeMasterwise')
	 BEGIN

		IF OBJECT_ID('tempdb..#tmpDepartFeeMasterwise') IS NOT NULL DROP TABLE #tmpDepartFeeMasterwise
		CREATE TABLE #tmpDepartFeeMasterwise
		(
		FeeId int,
		Amount decimal (12,2),
		FeeName nvarchar(100),
		FeeHeadId int,
		AcademicId bigint,
		Id int,
		StartDate date,
		OrderIndex int
		)

		Insert Into #tmpDepartFeeMasterwise
		SELECT 
					FS1.FeeId,
					ISNULL(FS1.Amount,0)AS Amount,
					FM.Title AS FeeName,
					FM.FeeHeadId,
					SA1.Id As AcademicId,
					FS1.Id,
					FS1.StartDate,
					FM.OrderIndex
 				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 sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
				WHERE 
					BM.OrgGroupBatchId = @rOrgGroupBatchId
					AND (FS1.IsOptional=0)
					-- IsInContext
					AND BM.IsInContext = 1
				UNION ALL
				SELECT 
					FS1.FeeId,
					ISNULL(FS1.Amount,0)AS Amount,
					FM.Title AS FeeName,
					FM.FeeHeadId,
					SA1.AcademicId As AcademicId,
					FS1.Id,
					FS1.StartDate,
					FM.OrderIndex
				FROM sFee.tFeeSetup FS1
				INNER JOIN sFee.tFeeOptional FO ON FO.FeeSetupId=FS1.Id
				INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
				INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=FO.SourceId 
				AND SA1.BatchId = FS1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId AND SA1.ClassId = FS1.ClassId
				INNER JOIN sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
				WHERE
						SA1.OrgGroupBatchId = @rOrgGroupBatchId
						AND (FS1.IsOptional=1)
						-- IsInContext
						AND BM.IsInContext = 1


		SELECT
			SA.DepartmentId,
		    SA.DepartmentName,
			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,
			FS.FeeId,
			FS.FeeName,
			FS.OrderIndex
		FROM
			sStudent.vStudentAcademic SA
				INNER JOIN sSetup.tOrganizationMaster O ON SA.OrgId = O.Id
				INNER JOIN #tmpDepartFeeMasterwise 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.tAcademic SA1 ON SA1.Id=R.SourceId
						INNER JOIN sSetup.tBatchMaster BM ON BM.Id=SA1.BatchId			
					WHERE		
						(R.SourceTypeId = 2001)
						AND (R.IsObsolete = 0) 
						AND ((BM.OrgGroupBatchId = @rOrgGroupBatchId))
						AND (R.OrgGroupBatchId = @rOrgGroupBatchId)
						AND (R.ReceiptDate <= @rUptoDate)  
						-- IsInContext
						AND BM.IsInContext = 1
						GROUP BY FeeSetupId,R.SourceId
				) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
				INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id = FS.FeeHeadId	
				INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId
			WHERE
			  SA.OrgGroupBatchId = @rOrgGroupBatchId
			  AND (SA.StatusId = @rStudentStatus OR @rStudentStatus=0)
			  AND ((FS.StartDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
			  -- IsInContext
			  AND BM.IsInContext = 1
			GROUP BY SA.DepartmentId,SA.DepartmentName,FS.FeeId,FS.FeeName,FS.OrderIndex
			ORDER BY DepartmentId,FS.FeeId
	 END
	 ELSE IF(@rFeeType = 'CollectionGroupwise')
	 BEGIN
		IF OBJECT_ID('tempdb..#tmpDepartCollectionGroupwise') IS NOT NULL DROP TABLE #tmpDepartCollectionGroupwise
		CREATE TABLE #tmpDepartCollectionGroupwise
		(
		FeeId int,
		Amount decimal (12,2),
		FeeName nvarchar(100),
		FeeHeadId int,
		AcademicId bigint,
		Id int,
		StartDate date,
		CollectionGroupId int
		)

		INSERT INTO #tmpDepartCollectionGroupwise
		SELECT 
					FS1.FeeId,
					ISNULL(FS1.Amount,0)AS Amount,
					FM.Title AS FeeName,
					FM.FeeHeadId,
					SA1.Id As AcademicId,
					FS1.Id,
					FS1.StartDate,
					FS1.CollectionGroupId
 				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 sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
				WHERE 
					BM.OrgGroupBatchId = @rOrgGroupBatchId
					AND (FS1.IsOptional=0)
					-- IsInContext
					AND BM.IsInContext = 1
				UNION ALL
				SELECT 
					FS1.FeeId,
					ISNULL(FS1.Amount,0)AS Amount,
					FM.Title AS FeeName,
					FM.FeeHeadId,
					SA1.AcademicId As AcademicId,
					FS1.Id,
					FS1.StartDate,
					FS1.CollectionGroupId
				FROM sFee.tFeeSetup FS1
				INNER JOIN sFee.tFeeOptional FO ON FO.FeeSetupId=FS1.Id
				INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
				INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=FO.SourceId 
				AND SA1.BatchId = FS1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId AND SA1.ClassId = FS1.ClassId
				INNER JOIN sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
				WHERE
						SA1.OrgGroupBatchId = @rOrgGroupBatchId
						AND (FS1.IsOptional=1)
						-- IsInContext
						AND BM.IsInContext = 1


		SELECT
			SA.DepartmentId,
		    SA.DepartmentName,
			SUM(ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00))AS PendingAmount,
			ISNULL(CGM.Id,0) AS CollectionGroupId,
			ISNULL(CGM.Title,'') AS CollectionGroupName,
			ISNULL(CGM.OrderIndex,0) AS OrderIndex
		FROM
			sStudent.vStudentAcademic SA
				INNER JOIN sSetup.tOrganizationMaster O ON SA.OrgId = O.Id
				INNER JOIN #tmpDepartCollectionGroupwise 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.tAcademic SA1 ON SA1.Id=R.SourceId
						INNER JOIN sSetup.tBatchMaster BM ON BM.Id=SA1.BatchId			
					WHERE		
						(R.SourceTypeId = 2001)
						AND (R.IsObsolete = 0) 
						AND ((BM.OrgGroupBatchId = @rOrgGroupBatchId))
						AND (R.OrgGroupBatchId = @rOrgGroupBatchId)
						AND (R.ReceiptDate <= @rUptoDate)  
						-- IsInContext
						AND BM.IsInContext = 1
						GROUP BY FeeSetupId,R.SourceId
				) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
				LEFT JOIN sFee.tCollectionGroupMaster CGM ON FS.CollectionGroupId=CGM.Id
				INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId
			WHERE
			  SA.OrgGroupBatchId = @rOrgGroupBatchId
			  AND (SA.StatusId = @rStudentStatus OR @rStudentStatus=0)
			  AND ((FS.StartDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
			  -- IsInContext
			  AND BM.IsInContext = 1
			GROUP BY SA.DepartmentId,SA.DepartmentName,CGM.Id,CGM.Title,CGM.OrderIndex
			ORDER BY DepartmentId,CGM.Id
	 END
	END
ELSE IF(@rFilterType = 'ReceiptBookwise')
	BEGIN
	IF(@rFeeType = 'FeeHeadwise')
	BEGIN
		-- For Timeout issue
		CREATE TABLE #tmp
		(
		Amount decimal (12,2),
		FeeName nvarchar(100),
		FeeHeadId int,
		AcademicId bigint,
		Id int,
		StartDate date,
		ReceiptBookId int 
		)

		INSERT INTO #tmp
		SELECT 
			ISNULL(FS1.Amount,0)AS Amount,
			FM.Title AS FeeName,
			FM.FeeHeadId,
			SA1.Id As AcademicId,
			FS1.Id,
			FS1.StartDate,
			FS1.ReceiptBookId
 		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 sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
		WHERE 
			BM.OrgGroupBatchId = @rOrgGroupBatchId
			AND (FS1.IsOptional=0)
			-- IsInContext
			AND BM.IsInContext = 1
		UNION ALL
		SELECT 
			ISNULL(FS1.Amount,0)AS Amount,
			FM.Title AS FeeName,
			FM.FeeHeadId,
			SA1.AcademicId As AcademicId,
			FS1.Id,
			FS1.StartDate,
			FS1.ReceiptBookId
		FROM sFee.tFeeSetup FS1
		INNER JOIN sFee.tFeeOptional FO ON FO.FeeSetupId=FS1.Id
		INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
		INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=FO.SourceId 
		AND SA1.BatchId = FS1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId AND SA1.ClassId = FS1.ClassId
		INNER JOIN sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
		WHERE
				SA1.OrgGroupBatchId = @rOrgGroupBatchId
				AND (FS1.IsOptional=1)
				-- IsInContext
				AND BM.IsInContext = 1



	 SELECT
			FS.ReceiptBookId,
		    ISNULL(RBM.Title,'') AS ReceiptBookTitle,
			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,
			FHM.Id AS FeeHeadId,
			FHM.Title AS FeeHeadName,
			FHM.OrderIndex
		FROM
			sStudent.tAcademic SA
			INNER JOIN [sStudent].[tStudentMaster] SM ON SA.StudentId = SM.Id 
			INNER JOIN [sSetup].[tBatchMaster] BM ON SA.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster O ON SA.OrgId = O.Id
			--INNER JOIN 
			--(
				--SELECT 
				--	ISNULL(FS1.Amount,0)AS Amount,
				--	FM.Title AS FeeName,
				--	FM.FeeHeadId,
				--	SA1.Id As AcademicId,
				--	FS1.Id,
				--	FS1.StartDate,
				--	FS1.ReceiptBookId
 			--	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 sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
				--WHERE 
				--	BM.OrgGroupBatchId = @rOrgGroupBatchId
				--	AND (FS1.IsOptional=0)
				--	-- IsInContext
				--	AND BM.IsInContext = 1
				--UNION ALL
				--SELECT 
				--	ISNULL(FS1.Amount,0)AS Amount,
				--	FM.Title AS FeeName,
				--	FM.FeeHeadId,
				--	SA1.AcademicId As AcademicId,
				--	FS1.Id,
				--	FS1.StartDate,
				--	FS1.ReceiptBookId
				--FROM sFee.tFeeSetup FS1
				--INNER JOIN sFee.tFeeOptional FO ON FO.FeeSetupId=FS1.Id
				--INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
				--INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=FO.SourceId 
				--AND SA1.BatchId = FS1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId AND SA1.ClassId = FS1.ClassId
				--INNER JOIN sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
				--WHERE
				--		SA1.OrgGroupBatchId = @rOrgGroupBatchId
				--		AND (FS1.IsOptional=1)
				--		-- IsInContext
				--		AND BM.IsInContext = 1
				--) 
				INNER JOIN #tmp FS ON FS.AcademicId=SA.Id
				LEFT JOIN sFee.tFeeAllocation FA ON FA.FeeSetupId=FS.Id AND FA.SourceId=SA.Id
				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.tAcademic SA1 ON SA1.Id=R.SourceId
						INNER JOIN sSetup.tBatchMaster BM ON BM.Id=SA1.BatchId			
					WHERE		
						(R.SourceTypeId = 2001)
						AND (R.IsObsolete = 0) 
						AND ((BM.OrgGroupBatchId = @rOrgGroupBatchId))
						AND (R.OrgGroupBatchId = @rOrgGroupBatchId)
						AND (R.ReceiptDate <= @rUptoDate)  
						-- IsInContext
						AND BM.IsInContext = 1
						GROUP BY FeeSetupId,R.SourceId
				) R ON R.FeeSetupId = FS.Id AND SA.Id = R.SourceId
				INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id = FS.FeeHeadId	
				INNER JOIN sFee.tReceiptBookMaster RBM ON FS.ReceiptBookId=RBM.Id
			WHERE
			  BM.OrgGroupBatchId = @rOrgGroupBatchId
			  AND (SM.StatusId = @rStudentStatus OR @rStudentStatus=0)
			  AND ((FS.StartDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
			  -- IsInContext
			  AND BM.IsInContext = 1
			GROUP BY FS.ReceiptBookId,RBM.Title,FHM.Id,FHM.Title,FHM.OrderIndex
			ORDER BY ReceiptBookId,FHM.Id

		DROP TABLE #tmp
	 END
	ELSE IF(@rFeeType = 'FeeMasterwise')
	BEGIN

		IF OBJECT_ID('tempdb..#tmpReceiptFeeMasterwise') IS NOT NULL DROP TABLE #tmpReceiptFeeMasterwise
		CREATE TABLE #tmpReceiptFeeMasterwise
		(
		FeeId int,
		Amount decimal (12,2),
		FeeName nvarchar(100),
		FeeHeadId int,
		AcademicId bigint,
		Id int,
		StartDate date,
		ReceiptBookId int,
		OrderIndex int
		)

		INSERT INTO  #tmpReceiptFeeMasterwise
		SELECT 
					FS1.FeeId,
					ISNULL(FS1.Amount,0)AS Amount,
					FM.Title AS FeeName,
					FM.FeeHeadId,
					SA1.Id As AcademicId,
					FS1.Id,
					FS1.StartDate,
					FS1.ReceiptBookId,
					FM.OrderIndex
 				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 sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
				WHERE 
					BM.OrgGroupBatchId = @rOrgGroupBatchId
					AND (FS1.IsOptional=0)
					-- IsInContext
					AND BM.IsInContext = 1
				UNION ALL
				SELECT 
					FS1.FeeId,
					ISNULL(FS1.Amount,0)AS Amount,
					FM.Title AS FeeName,
					FM.FeeHeadId,
					SA1.AcademicId As AcademicId,
					FS1.Id,
					FS1.StartDate,
					FS1.ReceiptBookId,
					FM.OrderIndex
				FROM sFee.tFeeSetup FS1
				INNER JOIN sFee.tFeeOptional FO ON FO.FeeSetupId=FS1.Id
				INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
				INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=FO.SourceId 
				AND SA1.BatchId = FS1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId AND SA1.ClassId = FS1.ClassId
				INNER JOIN sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
				WHERE
						SA1.OrgGroupBatchId = @rOrgGroupBatchId
						AND (FS1.IsOptional=1)
						-- IsInContext
						AND BM.IsInContext = 1

		SELECT
			FS.ReceiptBookId,
		    ISNULL(RBM.Title,'') AS ReceiptBookTitle,
			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,
			FS.FeeId,
			FS.FeeName,
			FS.OrderIndex
		FROM
			sStudent.vStudentAcademic SA
				INNER JOIN sSetup.tOrganizationMaster O ON SA.OrgId = O.Id
				INNER JOIN #tmpReceiptFeeMasterwise 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.tAcademic SA1 ON SA1.Id=R.SourceId
						INNER JOIN sSetup.tBatchMaster BM ON BM.Id=SA1.BatchId			
					WHERE		
						(R.SourceTypeId = 2001)
						AND (R.IsObsolete = 0) 
						AND ((BM.OrgGroupBatchId = @rOrgGroupBatchId))
						AND (R.OrgGroupBatchId = @rOrgGroupBatchId)
						AND (R.ReceiptDate <= @rUptoDate) 
						-- IsInContext
						AND BM.IsInContext = 1 
						GROUP BY FeeSetupId,R.SourceId
				) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
				INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id = FS.FeeHeadId	
				INNER JOIN sFee.tReceiptBookMaster RBM ON FS.ReceiptBookId=RBM.Id
				INNER JOIN sSetup.tBatchMaster BM ON SA.BatchId = BM.Id
			WHERE
			  SA.OrgGroupBatchId = @rOrgGroupBatchId
			  AND (SA.StatusId = @rStudentStatus OR @rStudentStatus=0)
			  AND ((FS.StartDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
			  -- IsInContext
			  AND BM.IsInContext = 1
			GROUP BY FS.ReceiptBookId,RBM.Title,FS.FeeId,FS.FeeName,FS.OrderIndex
			ORDER BY ReceiptBookId,FS.FeeId
	END
	ELSE IF(@rFeeType = 'CollectionGroupwise')
	BEGIN

		IF OBJECT_ID('tempdb..#tmpReceiptCollectionGroupwise') IS NOT NULL DROP TABLE #tmpReceiptCollectionGroupwise
		CREATE TABLE #tmpReceiptCollectionGroupwise
		(
		FeeId int,
		Amount decimal (12,2),
		FeeName nvarchar(100),
		FeeHeadId int,
		AcademicId bigint,
		Id int,
		StartDate date,
		CollectionGroupId int,
		ReceiptBookId int
		)

		INSERT INTO #tmpReceiptCollectionGroupwise
		SELECT 
					FS1.FeeId,
					ISNULL(FS1.Amount,0)AS Amount,
					FM.Title AS FeeName,
					FM.FeeHeadId,
					SA1.Id As AcademicId,
					FS1.Id,
					FS1.StartDate,
					FS1.CollectionGroupId,
					FS1.ReceiptBookId
 				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 sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
				WHERE 
					BM.OrgGroupBatchId = @rOrgGroupBatchId
					AND (FS1.IsOptional=0)
					-- IsInContext
					AND BM.IsInContext = 1
				UNION ALL
				SELECT 
					FS1.FeeId,
					ISNULL(FS1.Amount,0)AS Amount,
					FM.Title AS FeeName,
					FM.FeeHeadId,
					SA1.AcademicId As AcademicId,
					FS1.Id,
					FS1.StartDate,
					FS1.CollectionGroupId,
					FS1.ReceiptBookId
				FROM sFee.tFeeSetup FS1
				INNER JOIN sFee.tFeeOptional FO ON FO.FeeSetupId=FS1.Id
				INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
				INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=FO.SourceId 
				AND SA1.BatchId = FS1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId AND SA1.ClassId = FS1.ClassId
				INNER JOIN sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
				WHERE
						SA1.OrgGroupBatchId = @rOrgGroupBatchId
						AND (FS1.IsOptional=1)
						-- IsInContext
						AND BM.IsInContext = 1

		SELECT
			FS.ReceiptBookId,
		    ISNULL(RBM.Title,'') AS ReceiptBookTitle,
			SUM(ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00))AS PendingAmount,
			ISNULL(CGM.Id,0) AS CollectionGroupId,
			ISNULL(CGM.Title,'') AS CollectionGroupName,
			ISNULL(CGM.OrderIndex,0) AS OrderIndex
		FROM
			sStudent.vStudentAcademic SA
				INNER JOIN sSetup.tOrganizationMaster O ON SA.OrgId = O.Id
				INNER JOIN #tmpReceiptCollectionGroupwise 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.tAcademic SA1 ON SA1.Id=R.SourceId
						INNER JOIN sSetup.tBatchMaster BM ON BM.Id=SA1.BatchId			
					WHERE		
						(R.SourceTypeId = 2001)
						AND (R.IsObsolete = 0) 
						AND ((BM.OrgGroupBatchId = @rOrgGroupBatchId))
						AND (R.OrgGroupBatchId = @rOrgGroupBatchId)
						AND (R.ReceiptDate <= @rUptoDate)  
						-- IsInContext
						AND BM.IsInContext = 1
						GROUP BY FeeSetupId,R.SourceId
				) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
				LEFT JOIN sFee.tCollectionGroupMaster CGM ON FS.CollectionGroupId=CGM.Id
				INNER JOIN sFee.tReceiptBookMaster RBM ON FS.ReceiptBookId=RBM.Id
				INNER JOIN sSetup.tBatchMaster BM ON SA.BatchId = BM.Id
			WHERE
			  SA.OrgGroupBatchId = @rOrgGroupBatchId
			  AND (SA.StatusId = @rStudentStatus OR @rStudentStatus=0)
			  AND ((FS.StartDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
			  -- IsInContext
			  AND BM.IsInContext = 1
			GROUP BY FS.ReceiptBookId,RBM.Title,CGM.Id,CGM.Title,CGM.OrderIndex
			--ORDER BY ReceiptBookId,CGM.Id
			ORDER BY CGM.OrderIndex
	END
	END 
  END
ELSE IF(@rType = 2)
		BEGIN

			IF OBJECT_ID('tempdb..#tmptbl') IS NOT NULL DROP TABLE #tmptbl
			CREATE TABLE #tmptbl
			(
				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,
				FeeOrderIndex int
			)
			INSERT INTO #tmptbl 
			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,
							FS1.CollectionGroupId,
							FM.OrderIndex AS FeeOrderIndex			 
						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 sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
						WHERE 
							BM.OrgGroupBatchId = @rOrgGroupBatchId
							AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
							AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
							AND (FS1.IsOptional=0)
							-- IsInContext
							AND BM.IsInContext = 1
						UNION ALL
				
						SELECT 
							FS1.FeeId,
							FS1.Id,
							ISNULL(FS1.IsOptional,0)AS IsOptional,
							ISNULL(FS1.IsVariable,0)AS IsVariable,
							ISNULL(FS1.Amount,0)AS Amount,
							ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
							ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
							FS1.BatchId,
							ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
							SA1.AcademicId,
							FM.Title AS FeeName,
							FM.FeeHeadId,
							FS1.CollectionGroupId,
							FM.OrderIndex AS FeeOrderIndex			 			 
						FROM sFee.tFeeSetup FS1
						INNER JOIN sFee.tFeeOptional FO ON FO.FeeSetupId=FS1.Id
						INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
						INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=FO.SourceId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
						INNER JOIN sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
						WHERE
							SA1.OrgGroupBatchId = @rOrgGroupBatchId
							AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
							AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
							AND (FS1.IsOptional=1)
							-- IsInContext
							AND BM.IsInContext = 1
	
				SELECT 
					SA.OrgId,
					SA.OrganizationName as OrgName,
					SA.ClassId,
					SA.ClassName,
					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 #tmptbl  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.tAcademic SA1 ON SA1.Id=R.SourceId
							INNER JOIN sSetup.tBatchMaster BM ON BM.Id=SA1.BatchId			
							 
						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
							-- IsInContext
							AND BM.IsInContext = 1
							GROUP BY FeeSetupId,R.SourceId
					) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
					 INNER JOIN sSetup.tOrganizationMaster O ON	
					 SA.OrgId = O.Id
					 INNER JOIN sFee.tReceiptBookMaster RBM 
						ON FS.ReceiptBookId=RBM.Id
					 LEFT JOIN sFee.tCollectionGroupMaster CGM
						ON FS.CollectionGroupId=CGM.Id	
					 LEFT JOIN sStudent.tStudentCommunication SC 
						ON SC.StudentId = SA.StudentId
					 LEFT JOIN sStudent.tStudentOther SO 
						ON SO.StudentId = SA.StudentId
					 INNER JOIN sFee.tFeeHeadMaster FHM
						ON FHM.Id = FS.FeeHeadId
					INNER JOIN sSetup.tBatchMaster BM ON SA.BatchId = BM.Id	
				  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))  
				WHERE	
				 SA.OrgGroupBatchId = @rOrgGroupBatchId
                 AND (SA.StatusId = @rStudentStatus OR @rStudentStatus=0)
                 AND ((FS.StartDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
				 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)			
				 -- IsInContext
				 AND BM.IsInContext = 1
				GROUP BY 
						SA.ClassId,SA.ClassName,SA.OrgId,SA.OrganizationName
				Order By
						SA.ClassId
		END
END
GO
PRINT N'Altering Procedure [sFee].[pReceiptAddValidate]...';


GO
 
ALTER PROCEDURE [sFee].[pReceiptAddValidate]
 
		 @rAcademicId bigint,
		 @rFeeSetupIds nvarchar(max) = '',
		 @rReceiptDetailXml [nvarchar](max),
		 @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	


	
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
  SELECT @rIsCreated = 0
 END 
 
 	EXEC sp_xml_removedocument @loDoc
END
GO
PRINT N'Altering Procedure [sHostel].[pAttendanceRegisterGet]...';


GO
ALTER PROCEDURE [sHostel].[pAttendanceRegisterGet]
	 	 
	 	 @rRoomId int,
		 @rAttendanceDate date,
		 @rHostelId int,
		 @rHostelAttendanceTypeId int,
		 @rOrgGroupBatchId int,
		 @rBuildingId int = 0

	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	IF EXISTS(SELECT 1 FROM sHostel.tAttendanceRegister ATR INNER JOIN sHostel.tAssignRoom AR ON AR.SourceId = ATR.StudentId AND AR.SourceTypeId=2003
	            INNER JOIN sHostel.tRoomMaster RM ON RM.Id = AR.RoomId
				WHERE ATR.AttendanceDate=@rAttendanceDate AND ATR.OrgGroupBatchId=@rOrgGroupBatchId AND ATR.HostelAttendanceTypeId=@rHostelAttendanceTypeId
				 AND AR.RoomId = @rRoomId AND RM.BuildingId = @rBuildingId )
	BEGIN
		SELECT 
			AR.SourceId AS StudentId,
			VA.Code,
			VA.Name,
			VA.SUId,
			ISNULL(ATR.IsPresent,'true') as IsPresent,
			ISNULL(ATR.AbsentReasonId,0) as AbsentReasonId,
			CASE WHEN ATR.CreatedUserId IS NULL THEN 'false' ELSE 'true' END AS IsDeleted,
			(SI.StudentPhoto) AS StudentPhoto,
			ISNULL(ATR.HostelAttendanceTypeId,0) AS HostelAttendanceTypeId
			
  FROM 
           sStudent.vStudentAcademic VA 
            INNER JOIN sHostel.tAssignRoom AR ON VA.StudentId = AR.SourceId AND AR.SourceTypeId=2003
            LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId=VA.StudentId
            INNER JOIN sHostel.tRoomMaster RM ON RM.Id = AR.RoomId
            INNER JOIN sHostel.tAttendanceRegister ATR ON ATR.StudentId=VA.StudentId 			
			AND (ATR.AttendanceDate=@rAttendanceDate) AND (ATR.OrgGroupBatchId=@rOrgGroupBatchId)
			AND isnull(ATR.HostelAttendanceTypeId,0)=@rHostelAttendanceTypeId
			INNER JOIN sHostel.tHostelAdmission HA ON HA.SourceId =  AR.SourceId  AND HA.SourceTypeId=2003 AND HA.OrgGroupBatchId = AR.OrgGroupBatchId
								  
  WHERE 
      RM.HostelId = @rHostelId
	  AND ((AR.RoomId=@rRoomId) OR (@rRoomId=0))
	   AND VA.OrgGroupBatchId=@rOrgGroupBatchId
	   AND AR.OrgGroupBatchId=@rOrgGroupBatchId
	   AND ((RM.BuildingId = @rBuildingId) OR (@rBuildingId=0))
	   AND (HA.AllocateDate <= @rAttendanceDate)
  ORDER BY VA.Code
	END
	ELSE
		BEGIN
		SELECT 
				AR.SourceId AS StudentId,
				VA.Code,
				VA.Name,
				VA.SUId,
				ISNULL(ATR.IsPresent,'true') as IsPresent,
				ISNULL(ATR.AbsentReasonId,0) as AbsentReasonId,
				CASE WHEN ATR.CreatedUserId IS NULL THEN 'false' ELSE 'true' END AS IsDeleted,
				(SI.StudentPhoto) AS StudentPhoto,
				ISNULL(ATR.HostelAttendanceTypeId,0) AS HostelAttendanceTypeId
			
	  FROM 
			   sStudent.vStudentAcademic VA 
				INNER JOIN sHostel.tAssignRoom AR ON VA.StudentId = AR.SourceId AND AR.SourceTypeId=2003
				LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId=VA.StudentId
				INNER JOIN sHostel.tRoomMaster RM ON RM.Id = AR.RoomId
				LEFT JOIN sHostel.tAttendanceRegister ATR ON ATR.StudentId=VA.StudentId 			
				AND (ATR.AttendanceDate=@rAttendanceDate) AND (ATR.OrgGroupBatchId=@rOrgGroupBatchId)
				AND isnull(ATR.HostelAttendanceTypeId,0)=@rHostelAttendanceTypeId			
				INNER JOIN sHostel.tHostelAdmission HA ON HA.SourceId =  AR.SourceId  AND HA.SourceTypeId=2003 AND HA.OrgGroupBatchId = AR.OrgGroupBatchId
		  
	  WHERE 
		  RM.HostelId = @rHostelId
		  AND ((AR.RoomId=@rRoomId) OR (@rRoomId=0))
		   AND VA.OrgGroupBatchId=@rOrgGroupBatchId
		   AND AR.OrgGroupBatchId=@rOrgGroupBatchId
		   AND ((RM.BuildingId = @rBuildingId) OR (@rBuildingId=0))
		   AND (HA.AllocateDate <= @rAttendanceDate)
	  ORDER BY VA.Code
	  END

	 --Select * from sHostel.tAttendanceRegister where Hostelattendancetypeid = 991100003 AND Attendancedate = '2022-12-28 00:00:00'
GO
PRINT N'Altering Procedure [sHrm].[pEmployeeCustomSearchGet]...';


GO
 
ALTER PROCEDURE [sHrm].[pEmployeeCustomSearchGet]
(
	@rPageIndex int = null,
	@rOrgId smallint,
	@rOrderBy nvarchar(max) = 'Number',
	@rCode [nvarchar](20) = '',
	@rFirstName [nvarchar](50) = '',	
	@rLastName[nvarchar](50) = '',
	@rEmployeeTypeId[nvarchar](50) = '',
	@rStatusId[nvarchar](50) = '',
	@rOrganizationDepartmentId[nvarchar](50) = '',
	@rReligionId[nvarchar](50) = '',
	@rMaritalStatusId[nvarchar](50) = '',
	@rQualification[nvarchar](50) = '',
	@rGenderId[nvarchar](50) = '',
	@rEmployeeDesignationId[nvarchar](50) = '',
	@rBloodGroupId[nvarchar](50) = '',
	@rEmployeeGroupId[nvarchar](50)='',
	@rDOBFromDate Date = '0001-01-01',
	@rDOBToDate Date = '9999-12-31',
	@rDOJFromDate Date = '0001-01-01',
	@rDOJToDate Date = '9999-12-31',
	@rLeftFromDate Date = '0001-01-01',
	@rLeftToDate Date = '9999-12-31',
	@rProbationUptoDate Date ,
	@rAhdocUptoDate Date ,
	@rPermanentDate Date ,
	@rDropDownStatusId int,
	
	@rNumber int = null,
	@rCustomTagId nvarchar(max) = '',
	@rDateOfResignation Date = '',
	@rIsOtherUser int=0,
	@rOrgGroupId int
 )
AS
SET NOCOUNT ON
BEGIN
	DECLARE @Sql nvarchar(MAX)
	
	if @rDOBToDate = '9999-12-31'
	begin
		select @rDOBToDate = null
	end
	
	if @rLeftToDate = '9999-12-31'
	begin
		select @rLeftToDate = null
	end
	
	 IF  EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME ='tTempEMP')
	 BEGIN		
		DROP Table sHrm.tTempEMP
	 END

	SET @rCode = sCommon.fSearchStringGet(@rCode)
	SET @rFirstName = sCommon.fSearchStringGet(@rFirstName)
	SET @rLastName = sCommon.fSearchStringGet(@rLastName)
	SET @rQualification = sCommon.fSearchStringGet(@rQualification)
	

	IF (@rCustomTagId <> '')
	BEGIN
		SELECT DISTINCT EM.Id AS EmployeeId1	
		INTO sHrm.tTempEMP
		FROM sHrm.tEmployeeMaster EM
		INNER JOIN sHrm.tEmployeeCustomTag ECT ON ECT.EmployeeId=EM.Id AND ISNULL(EM.IsOtherUser,0) = @rIsOtherUser 
		INNER JOIN sSetup.tOrganizationMaster OM ON EM.OrgId = OM.Id
		WHERE ((EM.OrgId = @rOrgId) OR (@rOrgId = 0)) AND OM.OrgGroupId = @rOrgGroupId AND ISNULL(EM.IsOtherUser,0) = 0 AND (ISNULL(ECT.CustomTagId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rCustomTagId,','))OR @rCustomTagId='')
	END
	ELSE
	BEGIN
		SELECT DISTINCT NULL AS EmployeeId1
		INTO sHrm.tTempEMP
	END



	SELECT * into sHrm.tTempEmployee1
	FROM sHrm.vEmployeeCustomSearch ECS 
	INNER JOIN sHrm.tTempEMP T2 ON ECS.EmployeeId = T2.EmployeeId1 OR @rCustomTagId = ''
	WHERE ((ECS.OrgId = @rOrgId) OR (@rOrgId = 0))
	AND ECS.OrgGroupId = @rOrgGroupId
	AND ((ECS.Code Like @rCode + '%') OR (@rCode = ''))
	AND ((ECS.FirstName Like @rFirstName  + '%') OR (@rFirstName = ''))
	AND ((ECS.LastName Like @rLastName + '%')OR(@rLastName = ''))
	AND ((ISNULL(ECS.Qualification,'') Like @rQualification + '%')OR(@rQualification = ''))
	AND ((ECS.DateOfBirth >= @rDOBFromDate) OR (ISNULL(@rDOBFromDate,'') = ''))
	AND ((ECS.DateOfBirth <= @rDOBToDate) OR (ISNULL(@rDOBToDate,'') = ''))
	AND ((ECS.DateOfJoining >= @rDOJFromDate) OR (ISNULL(@rDOJFromDate,'') = ''))
	AND ((ECS.DateOfJoining <= @rDOJToDate) OR (ISNULL(@rDOJToDate,'') = ''))
	AND ((ECS.DateOfleaving >= @rLeftFromDate) OR (ISNULL(@rLeftFromDate,'') = ''))
	AND ((ECS.DateOfleaving <= @rLeftToDate) OR (ISNULL(@rLeftToDate,'') = ''))
	AND (ISNULL(ECS.OrganizationDepartmentId,0) IN( SELECT cast(item as int) FROM sCommon.fnsplit(@rOrganizationDepartmentId,','))OR @rOrganizationDepartmentId='')
	AND (ISNULL(ECS.StatusId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rStatusId,','))OR @rStatusId='')
	AND (ISNULL(ECS.EmployeeTypeId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rEmployeeTypeId,','))OR @rEmployeeTypeId='')
	AND (ISNULL(ECS.EmployeeDesignationId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rEmployeeDesignationId,','))OR @rEmployeeDesignationId='')
	AND (ISNULL(ECS.EmployeeGroupId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rEmployeeGroupId,','))OR @rEmployeeGroupId='')
	AND (ISNULL(ECS.BloodGroupId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rBloodGroupId,','))OR @rBloodGroupId='')
	AND (ISNULL(ECS.ReligionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rReligionId,','))OR @rReligionId='')
	AND (ISNULL(ECS.MaritalStatusId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rMaritalStatusId,','))OR @rMaritalStatusId='')
	AND (ISNULL(ECS.GenderId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rGenderId,','))OR @rGenderId='')
	AND ((ECS.StatusId = @rDropDownStatusId) OR (@rDropDownStatusId=0))
	AND ((ECS.Number = @rNumber) OR (ISNULL(@rNumber,0) = 0))
	AND ((ECS.ProbationUptoDate = @rProbationUptoDate) OR (ISNULL(@rProbationUptoDate,'')=''))
	AND ((ECS.AhdocUptoDate = @rAhdocUptoDate) OR (ISNULL(@rAhdocUptoDate,'')=''))
	AND ((ECS.PermanentDate = @rPermanentDate) OR (ISNULL(@rPermanentDate,'')=''))
	AND ((ECS.DateofResignation = @rDateOfResignation) OR (ISNULL(@rDateOfResignation,'')=''))
	--AND ISNULL(ECS.IsOtherUser,0) = 0
	AND ISNULL(ECS.IsOtherUser,0) = @rIsOtherUser
	ORDER BY ECS.Number
	
	SET @rOrderBy=Replace(@rOrderBy,'Number','Number')
	Print @rOrderBy
	SET @sql='SELECT EmployeeId,Code AS Code,Name,EmployeeType,OrganizationDepartment AS OrganizationDepartment,
	StatusName FROM sHrm.tTempEmployee1 ORDER BY '+@rOrderBy
	exec(@Sql)
	
	create table #EMPLOYEETEMP
	(
		tid int identity(1,1),t_EmployeeId bigint
	)
	select @Sql = 'insert into #EMPLOYEETEMP
	SELECT EmployeeId FROM sHrm.tTempEmployee1 ORDER BY ' + @rOrderBy
	
	exec (@Sql)
	
	select @rPageIndex = case when isnull(@rPageIndex,0) = 0 then 1 else @rPageIndex end
	declare @lTotalRecords int,@lPageSize int = 10,@lResult nvarchar(max) = '',@lPaging varchar(max) = ''
	
	select @lTotalRecords = COUNT(*) FROM #EMPLOYEETEMP
	select @lPaging = @lPaging + dbo.fnc_SearchPagingFormat(@rPageIndex, @lTotalRecords, @lPageSize)
	
	select @lResult = @lResult + '<tr><td><a style="cursor:pointer;" onclick="SelectEmp(' + convert(varchar,EmployeeId) + ',''' + isnull(Code,'') + ''')">Select</a></td>
	<td>' + isnull(Organization,'') + '</td><td>' + isnull(OrganizationDepartment,'') + '</td><td>' + isnull(Code,'') + '</td><td>' + isnull(Name,'') + '</td><td>' + isnull(EmployeeType,'') + '</td>
	<td>' + isnull(StatusName,'') + '</td></tr>'	
	from sHrm.tTempEmployee1,#EMPLOYEETEMP
	where t_EmployeeId = EmployeeId and tid between ((@lPageSize * (@rPageIndex - 1)) + 1) AND (@lPageSize * @rPageIndex)
	order by tid
	
	select @lResult as EmpList,@lPaging as Paging,@lTotalRecords as TotalRecords
	
	DROP TABLE #EMPLOYEETEMP
	DROP Table sHrm.tTempEmployee1
	DROP Table sHrm.tTempEMP
END
GO
PRINT N'Altering Procedure [sHrm].[pEmployeeDocumentAdd]...';


GO

ALTER PROCEDURE [sHrm].[pEmployeeDocumentAdd]
	 
        @rEmployeeId bigint,
		@rDocumenetXml [nvarchar](max)
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
DECLARE @loDoc INT
EXEC sp_xml_preparedocument @loDoc OUTPUT, @rDocumenetXml
BEGIN 	
 
	BEGIN TRY
	
	 BEGIN TRANSACTION	
	 
		DELETE FROM [sHrm].[tEmployeeDocument] WHERE EmployeeId=@rEmployeeId
	
		INSERT INTO sHrm.tEmployeeDocument
		(
			EmployeeId, 
			SubmitDocumentMasterId,
			DocumentName,
			IsMigrate
		)
		SELECT
		   @rEmployeeId,
		   SubmitDocumentMasterId,
		   DocumentName,
		   isnull(IsMigrate,0)
		FROM OPENXML (@loDoc, '/Table/SubmitDocument', 1)
		WITH ( 
				SubmitDocumentMasterId int,
				DocumentName nvarchar(150),
				IsMigrate bit
			  ) 
	
	SELECT 1 AS Result
	
	COMMIT TRANSACTION
	
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH
		
END
GO
PRINT N'Altering Procedure [sHrm].[pEmploymentCertificateAdd]...';


GO
ALTER PROCEDURE [sHrm].[pEmploymentCertificateAdd]
			@rId bigint
	       ,@rEmployeeId bigint
	       ,@rNumber int
	       ,@rCertificateDate date
	       ,@rCreatedUserId bigint
	       ,@rOrgId int
	       ,@rRemark nvarchar(200)
	       ,@rDesignationId int
	       ,@rCertificateReason nvarchar(200)
           	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY	
	 BEGIN TRANSACTION	
	 
		IF(@rNumber = 0)	
		BEGIN
			SELECT @rNumber = ISNULL(MAX(Number),0) + 1 FROM sHrm.tCertificateEmployment WHERE OrgId=@rOrgId
		END	
			
		IF(@rId = 0)	
		BEGIN
			IF EXISTS(SELECT 1 FROM sHrm.tCertificateEmployment WHERE Number=@rNumber AND OrgId=@rOrgId)
			BEGIN
				SELECT -103 AS Result
				RETURN
			END
		END

	  DECLARE @lNextNumber BIGINT
	  IF(@rId = 0)	
		BEGIN
			EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sHrm.tCertificateEmployment', 0, 1, 1,@outNextNumber = @lNextNumber output
				INSERT INTO sHrm.tCertificateEmployment
				(
					Id
				   ,EmployeeId
				   ,Number
				   ,CertificateDate
				   ,OrgId
				   ,CreatedUserId
				   ,CreatedDateTime,
				   Remark,
				   EmployeeDesignationId,
				   CertificateReason
				)
				VALUES
				(	@lNextNumber
				   ,@rEmployeeId
				   ,@rNumber
				   ,@rCertificateDate
				   ,@rOrgId
				   ,@rCreatedUserId
				   ,sCommon.fGetDate()
				   ,@rRemark
				   ,@rDesignationId
				   ,@rCertificateReason
				)
		END
		
		ELSE
		
		BEGIN
			SET @lNextNumber = @rId
				UPDATE  sHrm.tCertificateEmployment
				SET
					EmployeeId=@rEmployeeId,
					CertificateDate=@rCertificateDate,
					UpdatedUserId=@rCreatedUserId,
					UpdatedDateTime=sCommon.fGetDate(),
					Remark=@rRemark,
					EmployeeDesignationId=@rDesignationId,
					CertificateReason=@rCertificateReason
					
				WHERE Id = @rId
		 END  	
		
		SELECT @lNextNumber AS Result
	
	COMMIT TRANSACTION
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
	
END
GO
PRINT N'Altering Procedure [sHrm].[pGetCheckBoxLists]...';


GO
ALTER proc [sHrm].[pGetCheckBoxLists]
@rFlag int,
@rOrgId int,
@rOrgGroupId int
as
begin
	declare @lResult varchar(max)=''

	if @rFlag = 0
	begin
		declare @ddlStatusMaster varchar(max)='<option value="0">-- ALL --</option>'
		declare @ddlReligionMaster varchar(max)='<option value="0">-- ALL --</option>'
		declare @ddlMaritalStatusMaster varchar(max)='<option value="0">-- ALL --</option>'
		declare @ddlGenderMaster varchar(max)='<option value="0">-- ALL --</option>'
		declare @ddlEmployeeDesignationMaster varchar(max)='<option value="0">-- ALL --</option>'
		declare @ddlEmployeeTypeMaster varchar(max)='<option value="0">-- ALL --</option>'
		declare @ddlEmployeeGroupMaster varchar(max)='<option value="0">-- ALL --</option>'
		declare @ddlBloodGroupMaster varchar(max)='<option value="0">-- ALL --</option>'
		declare @ddlDepartmentMaster varchar(max)='<option value="0">-- ALL --</option>'	
		declare @ddlEmployeeGradeMaster varchar(max)='<option value="0">-- ALL --</option>'

		select @ddlStatusMaster = @ddlStatusMaster + '<option value="' + convert(varchar,Id) +'">' + Title + '</option>'
		from sCommon.tStatusMaster where StatusTypeId = 4
		select @ddlReligionMaster = @ddlReligionMaster + '<option value="' + convert(varchar,Id) +'">' + Title + '</option>'
		from sCommon.tReligionMaster where IsObsolete = 0 AND OrgGroupId = @rOrgGroupId									  
		select @ddlMaritalStatusMaster = @ddlMaritalStatusMaster + '<option value="' + convert(varchar,Id) +'">' + Title + '</option>'
		from sCommon.tMaritalStatusMaster where IsObsolete = 0															   
		select @ddlGenderMaster = @ddlGenderMaster + '<option value="' + convert(varchar,Id) +'">' + Title + '</option>'
		from sCommon.tGenderMaster where IsObsolete = 0																	  
		select @ddlEmployeeDesignationMaster = @ddlEmployeeDesignationMaster + '<option value="' + convert(varchar,Id) +'">' + Title + '</option>'
		from sHrm.tEmployeeDesignationMaster where IsObsolete = 0 AND OrgId = @rOrgId									   
		select @ddlEmployeeTypeMaster = @ddlEmployeeTypeMaster + '<option value="' + convert(varchar,Id) +'">' + Title + '</option>'
		from sHrm.tEmployeeTypeMaster where IsObsolete = 0 AND OrgId = @rOrgId											  
		select @ddlEmployeeGroupMaster = @ddlEmployeeGroupMaster + '<option value="' + convert(varchar,Id) +'">' + Title + '</option>'
		from sHrm.tEmployeeGroupMaster WHERE IsObsolete = 0																   
		select @ddlBloodGroupMaster = @ddlBloodGroupMaster + '<option value="' + convert(varchar,Id) +'">' + Title + '</option>'
		from sCommon.tBloodGroupMaster where IsObsolete = 0															   
		select @ddlDepartmentMaster = @ddlDepartmentMaster + '<option value="' + convert(varchar,Id) +'">' + Title + '</option>'
		from sSetup.tDepartmentMaster where IsObsolete = 0 AND OrgId = @rOrgId											   
		select @ddlEmployeeGradeMaster = @ddlEmployeeGradeMaster + '<option value="' + convert(varchar,Id) +'">' + Title + '</option>'
		from sHrm.tEmployeeGradeMaster where IsObsolete = 0 AND OrgId = @rOrgId
		select @ddlStatusMaster as StatusMaster,@ddlReligionMaster as ReligionMaster,@ddlMaritalStatusMaster as MaritalStatusMaster,@ddlGenderMaster as GenderMaster,
		@ddlEmployeeDesignationMaster as EmployeeDesignationMaster,@ddlEmployeeTypeMaster as EmployeeTypeMaster,@ddlEmployeeGroupMaster as EmployeeGroupMaster,
		@ddlBloodGroupMaster as BloodGroupMaster,@ddlDepartmentMaster as DepartmentMaster,@ddlEmployeeGradeMaster as EmployeeGradeMaster
	end
	else if @rFlag = 1
	begin
		select @lResult = @lResult + '&nbsp;&nbsp;<input type="checkbox" attrid="' + convert(varchar,Id) + '" />&nbsp;' + Title + '<br />'
		from sCommon.tStatusMaster where StatusTypeId = 4
	end
	else if @rFlag = 2
	begin
		select @lResult = @lResult + '&nbsp;&nbsp;<input type="checkbox" attrid="' + convert(varchar,Id) + '" />&nbsp;' + Title + '<br />'
		from sCommon.tReligionMaster where IsObsolete = 0 AND OrgGroupId = @rOrgGroupId
	end
	else if @rFlag = 3
	begin
		select @lResult = @lResult + '&nbsp;&nbsp;<input type="checkbox" attrid="' + convert(varchar,Id) + '" />&nbsp;' + Title + '<br />'
		from sCommon.tMaritalStatusMaster where IsObsolete = 0
	end
	else if @rFlag = 4
	begin
		select @lResult = @lResult + '&nbsp;&nbsp;<input type="checkbox" attrid="' + convert(varchar,Id) + '" />&nbsp;' + Title + '<br />'
		from sCommon.tGenderMaster where IsObsolete = 0
	end
	else if @rFlag = 5
	begin
		select @lResult = @lResult + '&nbsp;&nbsp;<input type="checkbox" attrid="' + convert(varchar,Id) + '" />&nbsp;' + Title + '<br />'
		from sHrm.tEmployeeDesignationMaster where IsObsolete = 0 AND OrgId = @rOrgId
	end
	else if @rFlag = 6
	begin
		select @lResult = @lResult + '&nbsp;&nbsp;<input type="checkbox" attrid="' + convert(varchar,Id) + '" />&nbsp;' + Title + '<br />'
		from sHrm.tEmployeeTypeMaster where IsObsolete = 0 AND OrgId = @rOrgId
	end
	else if @rFlag = 7
	begin
		select @lResult = @lResult + '&nbsp;&nbsp;<input type="checkbox" attrid="' + convert(varchar,Id) + '" />&nbsp;' + Title + '<br />'
		from sHrm.tEmployeeGroupMaster WHERE IsObsolete = 0
	end
	else if @rFlag = 8
	begin
		select @lResult = @lResult + '&nbsp;&nbsp;<input type="checkbox" attrid="' + convert(varchar,Id) + '" />&nbsp;' + Title + '<br />'
		from sCommon.tBloodGroupMaster where IsObsolete = 0
	end
	else if @rFlag = 9
	begin
		select @lResult = @lResult + '&nbsp;&nbsp;<input type="checkbox" attrid="' + convert(varchar,Id) + '" />&nbsp;' + Title + '<br />'
		from sSetup.tDepartmentMaster where IsObsolete = 0 AND OrgId = @rOrgId
	end
	
	else if @rFlag = 10
	begin
		select @lResult = @lResult + '&nbsp;&nbsp;<input type="checkbox" attrid="' + convert(varchar,Id) + '" />&nbsp;' + Title + '<br />'
		from sHrm.tEmployeeGradeMaster where IsObsolete = 0 AND OrgId = @rOrgId
	end
	
	select @lResult as Result
end
GO
PRINT N'Altering Procedure [sHrm].[pLeaveBalanceLogGet]...';


GO
ALTER PROCEDURE [sHrm].[pLeaveBalanceLogGet]
	 @rCode nvarchar(20),
	 @rName nvarchar(100),
	 @rLeaveTypeId int,
	 @rLeaveTransactionId tinyint,
	 @rFromDate date,
	 @rToDate date,
	 @rBatchId int	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	
	BEGIN
		SET @rName = sCommon.fSearchStringGet(@rName)
	END
	
	SELECT 
			ECD.Code,
			ECD.EmployeeName,
			ECD.DepartmentName,
			LBL.CreatedDateTime AS LogDate,
			--LBL.TransactionLeave AS TransactionLeave,			
			case when LeaveTransactionId=2 then ISNULL(LBL.TransactionLeave,0) else CONVERT(decimal(16,2), ISNULL(LBL.BalanceLeave,0)) + CONVERT(decimal(16,2), ISNULL(LBL.TransactionLeave,0)) end as TransactionLeave,		
			ISNULL(LBL.BalanceLeave,0) AS BalanceLeave,			
			case when LeaveTransactionId=2 then ISNULL(LBL.TransactionLeave,0)-ISNULL(LBL.BalanceLeave,0) 
			else (CONVERT(decimal(16,2), ISNULL(LBL.BalanceLeave,0)) + CONVERT(decimal(16,2), ISNULL(LBL.TransactionLeave,0)))-ISNULL(LBL.BalanceLeave,0) end as TransactionCount,
			LBL.BatchId,
			LBL.Remark,
			LBL.LeaveTypeId,
			LTM.Title AS LeaveTypeName,		
			LT.Title  +' ('+ CONVERT(Nvarchar(max), ISNULL(LBL.BalanceLeave,0)) +' To '+CONVERT(Nvarchar(max), ISNULL(LBL.TransactionLeave,0))+')' As LeaveTransactionType,
			ISNULL(LB.BalanceLeave,0) AS UpdatedBalance
	FROM
			sHrm.tLeaveBalanceLog LBL
			INNER JOIN sHrm.tLeaveTypeMaster LTM ON LTM.Id = LBL.LeaveTypeId AND LTM.IsLWP=0
			INNER JOIN sHrm.vEmployeeCommonDetail ECD ON LBL.EmployeeId = ECD.EmployeeId
			INNER JOIN sHrm.tLeaveTransactionMaster LT ON LT.Id=LBL.LeaveTransactionId 
			LEFT JOIN sHrm.tLeaveBalance LB ON LB.EmployeeId = LBL.EmployeeId AND LB.LeaveTypeId = LBL.LeaveTypeId AND  LB.BatchId =  LBL.BatchId 
	WHERE 
		(LBL.BatchId = @rBatchId)
		AND ((CONVERT(DATE, LBL.CreatedDateTime)>=@rFromDate) OR (ISNULL(@rFromDate,'')=''))
		AND ((CONVERT(DATE, LBL.CreatedDateTime)<=@rToDate) OR (ISNULL(@rToDate,'')=''))
		AND ((LBL.LeaveTypeId=@rLeaveTypeId) OR (@rLeaveTypeId=0))
		AND ((ECD.Code=@rCode) OR (ISNULL(@rCode,'')=''))
		AND ((ECD.EmployeeName like @rName) OR (ISNULL(@rName,'')=''))
		AND ((LBL.LeaveTransactionId = @rLeaveTransactionId) OR (@rLeaveTransactionId = 0))
		AND LT.IsObsolete=0
		AND ISNULL(ECD.IsOtherUser,0)=0		
	ORDER BY LBL.CreatedDateTime DESC
END
GO
PRINT N'Altering Procedure [sHrm].[pRptEmployeeIcardGet]...';


GO

ALTER PROCEDURE [sHrm].[pRptEmployeeIcardGet]
	@rBuilder1 nvarchar(max)='',
	@rBuilder2 nvarchar(max)='',
	@rReportId smallint,
	@rOrgId smallint,
	@rStrEmployeeId nvarchar(max),
	@rEmployeeTypeId [int],
	@rDepartmentId [int]= 0,
	@rGradeId [int]= 0,
	@rDesignationId [int]= 0,
	@rGenderId [int]= 0,		
	@rEmployeeId [bigint]= 0,
	@rAgeFrom nvarchar(10),
	@rAgeTo nvarchar(10),
	@rEmployeeCode nvarchar(50)='',
	@rEmployeeGroupId smallint,
	@rEmployeeStatusId smallint,
	@rIsShowBarcode bit=0,
	@rStrCode nvarchar(max)='',
	@rBatchName nvarchar(100) = ''
	
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
	SELECT		
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			ECD.EmployeeId,
	        ECD.Code,	      	
			ECD.EmployeeName, 	 								 
			ECD.DepartmentId,  			
			ECD.DepartmentName,
		    ECD.MobileNumber,
		    ECD.EmployeeDesignation,
		    ECD.PhoneNoCompany,
		    ECD.BloodGroup,
		    ECD.DateOfBirth,
			EI.EmployeePhoto,
		    OM.Title AS OrgName,
		    OM.PrincipalSignature,
			ISNULL(ICO.ICardOrgTitle,'') AS ICardOrgTitle,
			ISNULL(ICO.ICardAddress1,'') AS ICardAddress1,
			ISNULL(ICO.ICardAddress2,'') AS ICardAddress2,
			ISNULL(ICO.ICardAddress3,'') AS ICardAddress3,	
		    OM.OrgLogo AS ICardLogo,
			ICO.ICardBackground,	
			ICO.ICardBackBackground,						
			ISNULL(ICO.LabelColor,'Black') AS LabelColor,
			ISNULL(ICO.DetailColor,'Black') AS DetailColor,
			ISNULL(ICO.HeaderColor,'Black') AS HeaderColor,
			ISNULL(EC.PresentStreetOne,'') AS PresentStreetOne,
			ISNULL(EC.PresentStreetTwo,'') AS PresentStreetTwo,
			ISNULL(EC.PresentStreetThree,'') AS PresentStreetThree,
			ISNULL(EC.PresentCity,'') AS PresentCity,
			ISNULL(EC.PresentState,'') AS PresentState,
			ISNULL(EC.PresentCountry,'') AS PresentCountry,
			ISNULL(EC.PresentZipCode,'') AS PresentZipCode,
			ECD.DateofJoining,
			EI.EmployeeSign,
			@rIsShowBarcode As IsShowBarcode,
			ISNULL(EC.EmergencyStreetOne,'') AS EmergencyStreetOne,
			ISNULL(EC.EmergencyStreetTwo,'') AS EmergencyStreetTwo,
			ISNULL(EC.EmergencyStreetThree,'') AS EmergencyStreetThree,
			ISNULL(EC.EmergencyCity,'') AS EmergencyCity,
			ISNULL(EC.EmergencyState,'') AS EmergencyState,
			ISNULL(EC.EmergencyCountry,'') AS EmergencyCountry,
			ISNULL(EC.EmergencyZipCode,'') AS EmergencyZipCode,
			ISNULL(PanNumber,'') AS PanNumber,
			EC.EmergencyContactNo AS EmergencyContactNo,
			EPD.Qualification AS Qualification,
			--ISNULL(EM.MiddleName,'')AS FatherName,
			ISNULL(ECD.MiddleName,'')AS FatherName,
			ECD.GenderTitle,
			ISNULL(ECD.FirstName,'')AS FirstName,
			ISNULL(ECD.LastName,'')AS SurName,
			(CASE WHEN RelationshipId = 2 THEN EFD.MobileNo ELSE '' END )AS FatherContactNo,
			ISNULL(@rBatchName,'') AS BatchName,
			ISNULL(EC.PresentContactNo,'') AS PresentContactNo
		FROM 
			sHrm.vEmployeeCommonDetail ECD
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=ECD.OrgID
			LEFT JOIN sHrm.tEmployeeImages EI ON EI.EmployeeId=ECD.EmployeeId
			LEFT JOIN sHrm.tEmployeeICardOrg ICO ON ECD.OrgId = ICO.OrgId
			LEFT JOIN sHrm.tEmployeeCommunications EC ON ECD.EmployeeId = EC.EmployeeId
			LEFT JOIN sHrm.tEmployeeStatutoryAndOther EO ON EO.EmployeeId = ECD.EmployeeId
			LEFT JOIN sHrm.tEmployeePersonalDetail EPD ON EPD.EmployeeId = EO.EmployeeId
			LEFT JOIN sHrm.tEmployeeFamilyDetails EFD on ECD.EmployeeId=EFD.EmployeeId 
			--LEFT JOIN sCommon.tRelationshipMaster RM on EFD.RelationshipId=RM.Id AND RM.Id=2
			--LEFT JOIN sHrm.tEmployeeMaster EM on EM.Id = ECD.EmployeeId
			
		WHERE
		((ECD.Code LIKE @rEmployeeCode)OR @rEmployeeCode = '' )
	   AND (ISNULL(ECD.EmployeeId,0) NOT IN( SELECT cast(item as bigint) FROM  sCommon.fnsplit(@rStrEmployeeId,',')) OR @rStrEmployeeId='') 
	   AND (ISNULL(ECD.Code,'') IN( SELECT cast(item as nvarchar(20)) FROM  sCommon.fnsplit(@rStrCode,',')) OR @rStrCode='')   
	   AND (ECD.EmployeeTypeId = @rEmployeeTypeId OR @rEmployeeTypeId = 0)
	   AND (ECD.OrganizationDepartmentId = @rDepartmentId OR @rDepartmentId = 0)
	   AND (ECD.EmployeeStatusId = @rEmployeeStatusId OR @rEmployeeStatusId = 0)
	   AND (ECD.EmployeeGroupId=@rEmployeeGroupId OR @rEmployeeGroupId=0)
	   AND (ECD.EmployeeGradeId = @rGradeId OR @rGradeId = 0)
	   AND (ECD.EmployeeDesignationId = @rDesignationId OR @rDesignationId = 0)	 	   
	   AND (ECD.GenderId = @rGenderId OR @rGenderId = 0)  	    
	   AND (ECD.EmployeeId = @rEmployeeId OR @rEmployeeId = 0)	   
	   --AND ((DATEDIFF(yy,ECD.DateOfBirth,GETDATE()) <= @rAgeTo) OR (ISNULL(@rAgeTo,0)=0))
	   --AND ((DATEDIFF(yy,ECD.DateOfBirth,GETDATE()) >= @rAgeFrom)OR (ISNULL(@rAgeFrom,0)=0))
	   AND  ECD.OrgId = @rOrgId
	   AND ISNULL(ECD.IsOtherUser,0)=0
	  
END
GO
PRINT N'Altering Procedure [sStudent].[pRptStudentInformationFormGet]...';


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

	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

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


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

BEGIN 

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


GO
ALTER PROCEDURE [sStudent].[pRptStudentStrengthDivisionWiseGet]
	 
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 @rOrgId smallint,
	 @rBatchId int,
	 @rClassId int,
	 @rDivisionId int,
	 @rDepartmentId int,
	 @rStudentCode varchar(20)='',
	 @rReportId int=0,
	 @rOrggroupBatchID int=0,
	 @rAsOnDate Date ='',
    @rStatusId int=0

	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
  DECLARE @lCount Int
	SELECT 
	
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			CM.DisplayTitle AS Class,
			DM.DisplayTitle AS Division,
			A.ClassId,
			A.DivisionId,
			CM.DisplayTitle+' - '+DM.DisplayTitle AS ClassDivision,
			DM.OrderIndex AS DivisionOrder,
			Cm.OrderINdex AS ClassOrderIndex  ,
		    ISNUll(AR.SourceId,0) AS HostelStudent,
			ISNUll(RT.SourceId,0) AS TransportStudent,
			A.StudentId 
			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 sHostel.tAssignRoom AR ON AR.SourceId=A.StudentId AND AR.SourceTypeId=2003 
			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 = A.StudentId
			INNER JOIN sSetup.tBatchClass BC ON BC.ClassID =  CM.Id and BC.BatchId= @rBatchId
    
	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
		AND ((SM.Code=@rStudentCode) OR (@rStudentCode=''))
		AND ((CM.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
		--start by megha - mentis 0026391
		--AND ((SA.LeftDate > @rAsOnDate) OR (SA.LeftDate Is null AND SM.StatusId = 1))
		AND ((SA.LeftDate > @rAsOnDate) OR (SA.LeftDate Is null))
	    AND ((SM.StatusId=@rStatusId)OR(@rStatusId=0))
		--end
	   END
GO
PRINT N'Altering Procedure [sStudent].[pStudentDocumentAdd]...';


GO

ALTER PROCEDURE [sStudent].[pStudentDocumentAdd]
	 
        @rStudentId bigint,
		@rDocumenetXml [nvarchar](max)
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
DECLARE @loDoc INT
EXEC sp_xml_preparedocument @loDoc OUTPUT, @rDocumenetXml
BEGIN 	
 
	BEGIN TRY
	
	 BEGIN TRANSACTION	
	 
		DELETE FROM sStudent.tStudentDocument WHERE StudentId=@rStudentId
	
		INSERT INTO sStudent.tStudentDocument
		(
			StudentId, 
			SubmitDocumentMasterId,
			DocumentName,
			IsMigrate
		)
		SELECT
		   @rStudentId,
		   SubmitDocumentMasterId,
		   DocumentName,
		   ISNULL(IsMigrate,0)
		FROM OPENXML (@loDoc, '/Table/SubmitDocument', 1)
		WITH ( 
				SubmitDocumentMasterId int,
				DocumentName nvarchar(150),
				IsMigrate bit
			  ) 
	
	SELECT 1 AS Result
	
	COMMIT TRANSACTION
	
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH
		
END
GO
PRINT N'Altering Procedure [sTimetable].[pRptDivisionTimeTableGet]...';


GO
ALTER PROCEDURE [sTimetable].[pRptDivisionTimeTableGet]

	  --@rBuilder1 nvarchar(max)='',
	  --@rBuilder2 nvarchar(max)='', 
	  @rBatchId int,
	  @rClassId int,
	  @rDivisionId int,
	  @rEmployeeId bigint,
	  @rTimeTableSchemaId int,
	  @rReportId int=0,
	  @rDate Date='',
	  @rOrgId int=0
	  
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON 

BEGIN   
  IF(@rReportId=10166) -- Teacherwise
  BEGIN
  SELECT

	A.TimeTableID,
	A.DivisionName,
	
	A.EmployeeId,
	A.SubjectId,
	
	CASE WHEN A.EmployeeId=-1 THEN '###' WHEN A.EmployeeId=-2 THEN '***' ELSE A.EmployeeName END  AS EmployeeName,
	CASE WHEN A.SubjectId=-1 THEN '###' WHEN A.SubjectId=-2 THEN '***' ELSE A.Subject END  AS Subject,
	--A.Subject,
	A.DivisionId,
	ISNULL(L.Title,'') AS DayName,
	ISNULL(L.DayId,0) AS DayId,
	ISNULL(L.LectureNumber,'') AS LactureNumber,
	--ISNULL(A.DayName,'') AS DayName,
	--ISNULL(A.DayId,0) AS DayId,
	--ISNULL(A.LactureNumber,'') AS LactureNumber,
	A.DayLacture,
	A.ClassId,
	A.ClassDivisionName,
	A.DivisionOrderIndex,
	A.Code,
	A.TimeTableDetail,
	0 As IsPresent,
	'' As WeekOffs,
	CASE WHEN EXISTS (SELECT 1 FROM sTimetable.tTimeTableSchema TS INNER JOIN sTimetable.tTimeTable TT ON TT.TimeTableSchemaId = TS.Id WHERE TS.IsDisplayPeriodTime = 1 AND TS.Id = @rTimeTableSchemaId) THEN A.FromTime ELSE '' END As FromTime,
	CASE WHEN EXISTS (SELECT 1 FROM sTimetable.tTimeTableSchema TS INNER JOIN sTimetable.tTimeTable TT ON TT.TimeTableSchemaId = TS.Id WHERE TS.IsDisplayPeriodTime = 1 AND TS.Id = @rTimeTableSchemaId) THEN A.ToTime ELSE '' END As ToTime,
	ISNULL(IsDiplayPeriodTime,0) As IsDiplayPeriodTime,
	'' as DivisionIncharge,
	IsBreak,
	IsBreakBefore,
	EmployeeSubject,
	 ClassSubject,
	'' AS EmployeeSNSubject,
	ISNULL(Convert(smallint,(select Isnull(max(cast(IsBreak as smallint)),0)*2+ISNULL(max(cast(IsBreakBefore as smallint)),0)*1
			From sTimetable.tTimeTableTime
			where TimeTableSchemaId=@rTimeTableSchemaId AND LectureNumber=A.LactureNumber
			Group by TimeTableSchemaId,LectureNumber)),0) AS HideBreak

  FROM
(
	SELECT 
	--@rBuilder1 AS Builder1,
	--@rBuilder2 AS Builder2,	 
	TT.Id AS TimeTableID,
	ISNULL(DV.Title,'') AS DivisionName,
	ISNULL(EmployeeId,0) AS EmployeeId,
	ISNULL(SubjectId,0) AS SubjectId,

	ISNULL(Em.FirstName +'  '+Em.LastName,'')  AS EmployeeName,
	--ISNULL(Em.FirstName,'')  AS EmployeeName,  
	ISNULL(SM.Title,'') AS Subject,
	ISNULL(TT.DivisionId,0) AS DivisionId,
	ISNULL(DM.Title,'') AS DayName,
	ISNULL(TT.DayId,0) AS DayId,
	ISNULL(TT.LectureNumber,'') AS LactureNumber,
	ISNULL(DM.Title,'') +'-'+ISNULL(convert(nvarchar(4),TT.LectureNumber),'') AS DayLacture,
	ISNULL(DV.ClassId,0) AS ClassId,
	ISNULL(CM.DisplayTitle,'')+'-'+ISNULL(DV.Title,'') as ClassDivisionName,
	ISNULL(DV.OrderIndex,0) As DivisionOrderIndex,
	ISNULL(SM.Code,'') AS Code,
	--'' AS TimeTableDetail,
	--(ISNULL(CM.DisplayTitle,'')+'-'+ISNULL(DV.Title,'') + ISNULL(SM.Title,'')) AS TimeTableDetail
	ISNULL([sTimetable].[fTimeTableDivisionGet](TT.TimeTableSchemaId,TT.Id,TT.EmployeeId,TT.DayId,TT.LectureNumber,0),'') AS TimeTableDetail,
	ISNULL(TTM.FromTime,0) As FromTime,
	ISNULL(TTM.ToTime,0) As ToTime,
	ISNULL(TS.IsDisplayPeriodTime,0) As IsDiplayPeriodTime,

	--GetBreak
	CASE WHEN 
	(SELECT ISNULL(IsBreak,0) FROM sTimetable.tTimeTableTime WHERE TimeTableSchemaId = TT.TimeTableSchemaId 
	AND DayId = TT.DayId AND DivisionId = TT.DivisionId AND LectureNumber = TT.LectureNumber AND IsBreak = 1) = 1 
	THEN (SELECT ISNULL(IsBreak,0) FROM sTimetable.tTimeTableTime WHERE TimeTableSchemaId = TT.TimeTableSchemaId 
	AND DayId = TT.DayId AND DivisionId = TT.DivisionId AND LectureNumber = TT.LectureNumber AND IsBreak = 1)
	ELSE ISNULL(TT.IsBreak,0) END AS IsBreak,

	--GetBreakBefore
	CASE WHEN 
	(SELECT ISNULL(IsBreakBefore,0) FROM sTimetable.tTimeTableTime WHERE TimeTableSchemaId = TT.TimeTableSchemaId 
	AND DayId = TT.DayId AND DivisionId = TT.DivisionId AND LectureNumber = TT.LectureNumber AND IsBreakBefore = 1) = 1 
	THEN (SELECT ISNULL(IsBreakBefore,0) FROM sTimetable.tTimeTableTime WHERE TimeTableSchemaId = TT.TimeTableSchemaId 
	AND DayId = TT.DayId AND DivisionId = TT.DivisionId AND LectureNumber = TT.LectureNumber AND IsBreakBefore = 1)
	ELSE ISNULL(TT.IsBreakBefore,0) END AS IsBreakBefore,
	
	STUFF((
			SELECT ', ' +  ISNULL(ISNULL(Em1.FirstName +'  '+Em1.LastName,'') +' - '+SM1.Title,'')
			FROM sTimetable.tTimeTable T1 
			inner join sHrm.tEmployeeMaster EM1 on EM1.Id=T1.EmployeeId
			INNER JOIN sSetup.tSubjectMaster SM1 ON SM1.Id=T1.SubjectId
			where T1.DivisionId=TT.DivisionId 
			AND TT.LectureNumber=T1.LectureNumber 
			AND TT.DayId=T1.DayId and TT.TimeTableSchemaId=T1.TimeTableSchemaId  
			--AND timetableid in ()
			FOR XML PATH('')
			), 1, 1, '') EmployeeSubject,
	[sCommon].[fXMLTagsReplaceReverse](STUFF((
		SELECT ',<br>' +  ISNULL(VBCD1.ClassDivisionName +' - '+SM1.Title,'')
				FROM sTimetable.tTimeTable T1 
				INNER JOIN sSetup.tSubjectMaster SM1 ON SM1.Id=T1.SubjectId
					INNER JOIN sSetup.vClassDivision VBCD1 ON VBCD1.DivisionId=T1.DivisionId
				where T1.EmployeeId=TT.EmployeeId 
				AND TT.LectureNumber=T1.LectureNumber 
				AND TT.DayId=T1.DayId and TT.TimeTableSchemaId=T1.TimeTableSchemaId  
				--AND timetableid in ()
				FOR XML PATH('')
				), 1, 11, ''))  ClassSubject

	FROM 
	sTimetable.tTimeTable TT	
	INNER JOIN sSetup.tSubjectMaster SM ON SM.Id = TT.SubjectId 
	LEFT JOIN sHrm.tEmployeeMaster Em ON Em.Id = TT.EmployeeId
	LEFT JOIN sCommon.tDayMaster DM ON DM.Id = TT.DayId
	LEFT JOIN sSetup.tDivisionMaster DV ON DV.Id = TT.DivisionId
	LEFT JOIN sSetup.tClassMaster CM ON CM.Id = DV.ClassId
	LEFT JOIN sTimetable.tTimeTableTime TTM ON TTM.TimeTableSchemaId=TT.TimeTableSchemaId AND TTM.DayId = DM.Id AND TTM.DivisionId = TT.DivisionId AND TTM.LectureNumber = TT.LectureNumber
	INNER JOIN sTimetable.tTimeTableSchema TS ON TS.Id = TT.TimeTableSchemaId
	WHERE (ClassId = @rClassId OR @rClassId=0)
	  AND (TT.DivisionId = @rDivisionId OR @rDivisionId=0)	
	  AND (TT.EmployeeId=@rEmployeeId OR @rEmployeeId=0)
	  AND TT.TimeTableSchemaId=@rTimeTableSchemaId
	  AND TT.EmployeeId <> 0
	  
	  UNION ALL
	  
	  
	  
	  	SELECT 
	--@rBuilder1 AS Builder1,
	--@rBuilder2 AS Builder2,	 
	TT.Id AS TimeTableID,
	ISNULL(DV.Title,'') AS DivisionName,
	ISNULL(TTD.EmployeeId,0) AS EmployeeId,
	ISNULL(TTD.SubjectId,0) AS SubjectId,

	ISNULL(Em.FirstName +'  '+Em.LastName,'')  AS EmployeeName,
	--ISNULL(Em.FirstName,'')  AS EmployeeName,  
	ISNULL(SM.Title,'') AS Subject,
	ISNULL(TT.DivisionId,0) AS DivisionId,
	ISNULL(DM.Title,'') AS DayName,
	ISNULL(TT.DayId,0) AS DayId,
	ISNULL(TT.LectureNumber,'') AS LactureNumber,
	ISNULL(DM.Title,'') +'-'+ISNULL(convert(nvarchar(4),TT.LectureNumber),'') AS DayLacture,
	ISNULL(DV.ClassId,0) AS ClassId,
	ISNULL(CM.DisplayTitle,'')+'-'+ISNULL(DV.Title,'') as ClassDivisionName,
	ISNULL(DV.OrderIndex,0) As DivisionOrderIndex,
	ISNULL(SM.Code,'') AS Code,
	--(ISNULL(CM.DisplayTitle,'')+'-'+ISNULL(DV.Title,'') + ISNULL(SM.Title,'')) AS TimeTableDetail
	'' AS TimeTableDetail,
	ISNULL(TTM.FromTime,0) As FromTime,
	ISNULL(TTM.ToTime,0) As ToTime,
	ISNULL(TS.IsDisplayPeriodTime,0) As IsDiplayPeriodTime,
	0 AS IsBreak,
	0 AS IsBreakBefore,
	STUFF((
			SELECT ', ' +  ISNULL(ISNULL(Em1.FirstName +'  '+Em1.LastName,'') +' - '+SM1.Title,'')
			FROM sTimetable.tTimeTable T1 
			inner join sHrm.tEmployeeMaster EM1 on EM1.Id=T1.EmployeeId
			INNER JOIN sSetup.tSubjectMaster SM1 ON SM1.Id=T1.SubjectId
			where T1.DivisionId=TT.DivisionId 
			AND TT.LectureNumber=T1.LectureNumber 
			AND TT.DayId=T1.DayId and TT.TimeTableSchemaId=T1.TimeTableSchemaId  
			--AND timetableid in ()
			FOR XML PATH('')
			), 1, 1, '') EmployeeSubject ,
	[sCommon].[fXMLTagsReplaceReverse](STUFF((
		SELECT ',<br>' +  ISNULL(VBCD1.ClassDivisionName +' - '+SM1.Title,'')
				FROM sTimetable.tTimeTable T1 
				INNER JOIN sSetup.tSubjectMaster SM1 ON SM1.Id=T1.SubjectId
					INNER JOIN sSetup.vClassDivision VBCD1 ON VBCD1.DivisionId=T1.DivisionId
				where T1.EmployeeId=TT.EmployeeId 
				AND TT.LectureNumber=T1.LectureNumber 
				AND TT.DayId=T1.DayId and TT.TimeTableSchemaId=T1.TimeTableSchemaId  
				--AND timetableid in ()
				FOR XML PATH('')
				), 1, 11, ''))  ClassSubject

	FROM 
	sTimetable.tTimeTable TT
	INNER JOIN 	sTimetable.tTimeTableDetail TTD ON TTD.TimetableId = TT.Id
	INNER JOIN sSetup.tSubjectMaster SM ON SM.Id = TTD.SubjectId 
	INNER JOIN sHrm.tEmployeeMaster Em ON Em.Id = TTD.EmployeeId
	LEFT JOIN sCommon.tDayMaster DM ON DM.Id = TT.DayId
	LEFT JOIN sSetup.tDivisionMaster DV ON DV.Id = TT.DivisionId
	LEFT JOIN sSetup.tClassMaster CM ON CM.Id = DV.ClassId
	LEFT JOIN sTimetable.tTimeTableTime TTM ON TTM.TimeTableSchemaId=TT.TimeTableSchemaId AND TTM.DayId = DM.Id AND TTM.DivisionId = TT.DivisionId AND TTM.LectureNumber = TT.LectureNumber
	INNER JOIN sTimetable.tTimeTableSchema TS ON TS.Id = TT.TimeTableSchemaId 

	WHERE (ClassId = @rClassId OR @rClassId=0)
	  AND (TT.DivisionId = @rDivisionId OR @rDivisionId=0)	
	  AND (TTD.EmployeeId=@rEmployeeId OR @rEmployeeId=0)
	  AND TT.TimeTableSchemaId=@rTimeTableSchemaId
	 
	  
	  --ORDER BY DV.OrderIndex
	  )
	  A
			INNER JOIN (SELECT DISTINCT DayId,LectureNumber,DM.title  FROM sTimetable.tTimeTable
			INNER JOIN sCommon.tDayMaster DM ON DM.Id = DayId
			WHERE TimeTableSchemaId=@rTimeTableSchemaId  ) L
			ON A.LactureNumber = L.LectureNumber AND A.DayId = L.DayId

	END
ELSE IF(@rReportId = 30661) --- Absent Teacher Divisionwise
  BEGIN
	  SELECT

	A.TimeTableID,
	A.DivisionName,
	
	A.EmployeeId,
	A.SubjectId,
	
	CASE WHEN A.EmployeeId=-1 THEN '###' WHEN A.EmployeeId=-2 THEN '***' ELSE A.EmployeeName END  AS EmployeeName,
	CASE WHEN A.SubjectId=-1 THEN '###' WHEN A.SubjectId=-2 THEN '***' ELSE A.Subject END  AS Subject,
	--A.Subject,
	A.DivisionId,
	ISNULL(L.Title,'') AS DayName,
	ISNULL(L.DayId,0) AS DayId,
	ISNULL(L.LectureNumber,'') AS LactureNumber,
	--ISNULL(A.DayName,'') AS DayName,
	--ISNULL(A.DayId,0) AS DayId,
	--ISNULL(A.LactureNumber,'') AS LactureNumber,
	A.DayLacture,
	A.ClassId,
	ISNULL(A.ClassDivisionName,'')AS ClassDivisionName,
	A.DivisionOrderIndex,
	A.Code,
	A.TimeTableDetail,
	A.IsPresent,
	'' As WeekOffs,
	0 As FromTime,
	0 As ToTime,
	'' as DivisionIncharge,
	A.EmployeeSubject,
	'' as ClassSubject
  FROM
(
	SELECT 
	--@rBuilder1 AS Builder1,
	--@rBuilder2 AS Builder2,	 
	TT.Id AS TimeTableID,
	ISNULL(DV.Title,'') AS DivisionName,
	ISNULL(EAR.EmployeeId,0) AS EmployeeId,
	ISNULL(SubjectId,0) AS SubjectId,

	[sHrm].[fEmployeeNameGet](ISNULL(Em.FirstName,'') , ISNULL(Em.MiddleName,''), ISNULL(Em.LastName,''),ISNULL(OM.EmployeeNameFormatId,1)) AS EmployeeName,
	--ISNULL(Em.FirstName +'  '+Em.LastName,'')  AS EmployeeName,
	--ISNULL(Em.FirstName,'')  AS EmployeeName,  
	ISNULL(SM.Title,'') AS Subject,
	ISNULL(TT.DivisionId,0) AS DivisionId,
	ISNULL(DM.Title,'') AS DayName,
	ISNULL(TT.DayId,0) AS DayId,
	ISNULL(TT.LectureNumber,'') AS LactureNumber,
	ISNULL(DM.Title,'') +'-'+ISNULL(convert(nvarchar(4),TT.LectureNumber),'') AS DayLacture,
	ISNULL(DV.ClassId,0) AS ClassId,
	ISNULL(CM.DisplayTitle,'')+'-'+ISNULL(DV.Title,'') as ClassDivisionName,
	ISNULL(DV.OrderIndex,0) As DivisionOrderIndex,
	ISNULL(SM.Code,'') AS Code,
	'' AS TimeTableDetail,
	ISNULL(EAR.IsPresent,0) AS IsPresent,
	[sCommon].[fXMLTagsReplaceReverse](STUFF((
			SELECT ',<br>' + case when ISNULL(EAR1.IsPresent,0)=0 then   ISNULL(ISNULL([sHrm].[fEmployeeNameGet](ISNULL(Em1.FirstName,'') , ISNULL(Em1.MiddleName,''), ISNULL(Em1.LastName,''),ISNULL(OM1.EmployeeNameFormatId,1)),'') +' <br><b> '+SM1.Title+'</b>','') else '' end
			FROM sTimetable.tTimeTable T1 
			Left join sHrm.tEmployeeMaster EM1 on EM1.Id=T1.EmployeeId
			left JOIN sSetup.tSubjectMaster SM1 ON SM1.Id=T1.SubjectId
			LEFT JOIN sSetup.tOrganizationMaster OM1 ON OM1.Id = Em1.OrgID
			RIGHT JOIN sHrm.tEmployeeAttendanceRegister EAR1 ON EAR1.EmployeeId = Em1.Id
			where T1.DivisionId=TT.DivisionId 
			AND T1.LectureNumber=TT.LectureNumber 
			AND T1.DayId=TT.DayId and T1.TimeTableSchemaId=TT.TimeTableSchemaId  
			AND (EAR1.AttendanceDate = @rDate OR @rDate = '')
			AND (T1.DayId = (DATEPART(weekday,@rDate)) OR @rDate = '') 
			--AND timetableid in ()
			FOR XML PATH('')
			), 1, 11, '')) EmployeeSubject
	--(ISNULL(CM.DisplayTitle,'')+'-'+ISNULL(DV.Title,'') + ISNULL(SM.Title,'')) AS TimeTableDetail
	--ISNULL([sTimetable].[fTimeTableDivisionGet](TT.TimeTableSchemaId,TT.Id,TT.EmployeeId,TT.DayId,TT.LectureNumber),'') AS TimeTableDetail
	FROM 
	sTimetable.tTimeTable TT	 
	LEFT JOIN sSetup.tSubjectMaster SM ON SM.Id = TT.SubjectId 
	LEFT JOIN sHrm.tEmployeeMaster Em ON Em.Id = TT.EmployeeId
	LEFT JOIN sCommon.tDayMaster DM ON DM.Id = TT.DayId
	LEFT JOIN sSetup.tDivisionMaster DV ON DV.Id = TT.DivisionId
	LEFT JOIN sSetup.tClassMaster CM ON CM.Id = DV.ClassId
	LEFT JOIN sSetup.tOrganizationMaster OM ON OM.Id = Em.OrgID
	RIGHT JOIN sHrm.tEmployeeAttendanceRegister EAR ON EAR.EmployeeId = Em.Id

	WHERE (ClassId = @rClassId OR @rClassId=0)
	  AND (TT.DivisionId = @rDivisionId OR @rDivisionId=0)	
	  AND (TT.EmployeeId=@rEmployeeId OR @rEmployeeId=0)
	  AND TT.TimeTableSchemaId=@rTimeTableSchemaId
	  AND (EAR.AttendanceDate = @rDate OR @rDate = '')
	  AND (TT.DayId = (DATEPART(weekday,@rDate)) OR @rDate = '')

	  UNION ALL
	  
	  
	  
	  	SELECT 
	--@rBuilder1 AS Builder1,
	--@rBuilder2 AS Builder2,	 
	TT.Id AS TimeTableID,
	ISNULL(DV.Title,'') AS DivisionName,
	ISNULL(TTD.EmployeeId,0) AS EmployeeId,
	ISNULL(TTD.SubjectId,0) AS SubjectId,

	[sHrm].[fEmployeeNameGet](ISNULL(Em.FirstName,'') , ISNULL(Em.MiddleName,''), ISNULL(Em.LastName,''),ISNULL(OM.EmployeeNameFormatId,1)) AS EmployeeName,
	--ISNULL(Em.FirstName +'  '+Em.LastName,'')  AS EmployeeName,
	--ISNULL(Em.FirstName,'')  AS EmployeeName,  
	ISNULL(SM.Title,'') AS Subject,
	ISNULL(TT.DivisionId,0) AS DivisionId,
	ISNULL(DM.Title,'') AS DayName,
	ISNULL(TT.DayId,0) AS DayId,
	ISNULL(TT.LectureNumber,'') AS LactureNumber,
	ISNULL(DM.Title,'') +'-'+ISNULL(convert(nvarchar(4),TT.LectureNumber),'') AS DayLacture,
	ISNULL(DV.ClassId,0) AS ClassId,
	ISNULL(CM.DisplayTitle,'')+'-'+ISNULL(DV.Title,'') as ClassDivisionName,
	ISNULL(DV.OrderIndex,0) As DivisionOrderIndex,
	ISNULL(SM.Code,'') AS Code,
	--(ISNULL(CM.DisplayTitle,'')+'-'+ISNULL(DV.Title,'') + ISNULL(SM.Title,'')) AS TimeTableDetail
	ISNULL([sTimetable].[fTimeTableDivisionGet](TT.TimeTableSchemaId,TT.Id,TTD.EmployeeId,TT.DayId,TT.LectureNumber,0),'') AS TimeTableDetail,
	ISNULL(EAR.IsPresent,'') As IsPresent,
	[sCommon].[fXMLTagsReplaceReverse](STUFF((
			SELECT   ',<br>' +case when ISNULL(EAR1.IsPresent,0)=0 then ISNULL(ISNULL([sHrm].[fEmployeeNameGet](ISNULL(Em1.FirstName,'') , ISNULL(Em1.MiddleName,''), ISNULL(Em1.LastName,''),ISNULL(OM1.EmployeeNameFormatId,1)),'') +' <br><b> '+SM1.Title+'</b>','') else '' end
			FROM sTimetable.tTimeTable T1 
			inner join sHrm.tEmployeeMaster EM1 on EM1.Id=T1.EmployeeId
			INNER JOIN sSetup.tSubjectMaster SM1 ON SM1.Id=T1.SubjectId
			LEFT JOIN sSetup.tOrganizationMaster OM1 ON OM1.Id = Em1.OrgID
			LEFT JOIN sHrm.tEmployeeAttendanceRegister EAR1 ON EAR1.EmployeeId = Em1.Id
			where T1.DivisionId=TT.DivisionId 
			AND T1.LectureNumber=TT.LectureNumber 
			AND T1.DayId=TT.DayId and T1.TimeTableSchemaId=TT.TimeTableSchemaId  
			AND (EAR1.AttendanceDate = @rDate OR @rDate = '')
			AND (T1.DayId = (DATEPART(weekday,@rDate)) OR @rDate = '') 
			--AND timetableid in ()
			FOR XML PATH('')
			), 1, 11, '')) EmployeeSubject
	FROM 
	sTimetable.tTimeTable TT
	INNER JOIN 	sTimetable.tTimeTableDetail TTD ON TTD.TimetableId = TT.Id
	INNER JOIN sSetup.tSubjectMaster SM ON SM.Id = TTD.SubjectId 
	INNER JOIN sHrm.tEmployeeMaster Em ON Em.Id = TTD.EmployeeId
	LEFT JOIN sCommon.tDayMaster DM ON DM.Id = TT.DayId
	LEFT JOIN sSetup.tDivisionMaster DV ON DV.Id = TT.DivisionId
	LEFT JOIN sSetup.tClassMaster CM ON CM.Id = DV.ClassId
	LEFT JOIN sSetup.tOrganizationMaster OM ON OM.Id = Em.OrgID
	LEFT JOIN sHrm.tEmployeeAttendanceRegister EAR ON EAR.EmployeeId = Em.Id

	WHERE (ClassId = @rClassId OR @rClassId=0)
	  AND (TT.DivisionId = @rDivisionId OR @rDivisionId=0)	
	  AND (TTD.EmployeeId=@rEmployeeId OR @rEmployeeId=0)
	  AND TT.TimeTableSchemaId=@rTimeTableSchemaId
	  AND (EAR.AttendanceDate = @rDate OR @rDate = '')
	  AND (TT.DayId = (DATEPART(weekday,@rDate)) OR @rDate = '') 
	  
	  --ORDER BY DV.OrderIndex
	  )
	  A
			INNER JOIN (SELECT DISTINCT DayId,LectureNumber,DM.title  FROM sTimetable.tTimeTable
			INNER JOIN sCommon.tDayMaster DM ON DM.Id = DayId
			
			WHERE TimeTableSchemaId=@rTimeTableSchemaId ) L
			ON A.LactureNumber = L.LectureNumber AND A.DayId = L.DayId

	END
ELSE IF(@rReportId = 30925) --TeacherTimeTable_2
   BEGIN
   SELECT

	A.TimeTableID,
	A.DivisionName,
	A.EmployeeId,
	A.SubjectId,
	CASE WHEN A.EmployeeId=-1 THEN '###' WHEN A.EmployeeId=-2 THEN '***' ELSE A.EmployeeName END As EmployeeName,
	CASE WHEN A.SubjectId=-1 THEN '###' WHEN A.SubjectId=-2 THEN '***' ELSE A.Subject END  AS Subject,
	--A.Subject,
	A.DivisionId,
	--ISNULL(L.Title,'') AS DayName,
	--ISNULL(L.DayId,0) AS DayId,
	--ISNULL(L.LectureNumber,'') AS LactureNumber,
	ISNULL(A.DayName,'') AS DayName,
	ISNULL(A.DayId,0) AS DayId,
	ISNULL(A.LactureNumber,'') AS LactureNumber,
	A.DayLacture,
	A.ClassId,
	A.ClassDivisionName,
	A.DivisionOrderIndex,
	A.Code,
	[sTimetable].[fTimeTableDetailGet](A.TimeTableID,1) AS TimeTableDetail,
	0 AS IsPresent,
	A.WeekOffs,
	CASE WHEN EXISTS (SELECT 1 FROM sTimetable.tTimeTableSchema TS INNER JOIN sTimetable.tTimeTable TT ON TT.TimeTableSchemaId = TS.Id WHERE TS.IsDisplayPeriodTime = 1 AND TS.Id = @rTimeTableSchemaId) THEN A.FromTime ELSE '' END As FromTime,
	CASE WHEN EXISTS (SELECT 1 FROM sTimetable.tTimeTableSchema TS INNER JOIN sTimetable.tTimeTable TT ON TT.TimeTableSchemaId = TS.Id WHERE TS.IsDisplayPeriodTime = 1 AND TS.Id = @rTimeTableSchemaId) THEN A.ToTime ELSE '' END As ToTime,
	ISNULL(IsDiplayPeriodTime,0) As IsDiplayPeriodTime,
	DivisionIncharge,
	'' AS EmployeeSubject,
	ClassSubject
FROM
(
	SELECT 
	--@rBuilder1 AS Builder1,
	--@rBuilder2 AS Builder2,	 
	TT.Id AS TimeTableID,
	ISNULL(DV.Title,'') AS DivisionName,
	ISNULL(TT.EmployeeId,0) AS EmployeeId,
	ISNULL(SubjectId,0) AS SubjectId,
	[sHrm].[fEmployeeNameGet](ISNULL(EM.FirstName,'') , ISNULL(EM.MiddleName,''), ISNULL(EM.LastName,''),ISNULL(OM.EmployeeNameFormatId,1)) AS EmployeeName,
	--ISNULL(EM.LastName+' '+EM.FirstName,'')  AS EmployeeName,
	ISNULL(SM.Title,'') AS Subject,
	ISNULL(TT.DivisionId,0) AS DivisionId,
	ISNULL(DM.Title,'') AS DayName,
	ISNULL(TT.DayId,0) AS DayId,
	ISNULL(TT.LectureNumber,'') AS LactureNumber,
	ISNULL(DM.Title,'') +'-'+ISNULL(convert(nvarchar(4),TT.LectureNumber),'') AS DayLacture,
	ISNULL(DV.ClassId,0) AS ClassId,
	ISNULL(CM.DisplayTitle,'')+'-'+ISNULL(DV.Title,'') as ClassDivisionName,
	ISNULL(DV.OrderIndex,0) As DivisionOrderIndex,
	ISNULL(SM.Code,'') AS Code,
	ISNULL(TTS.WeekOffs,'') As WeekOffs,
	ISNULL(TTM.FromTime,'') As FromTime,
	ISNULL(TTM.ToTime,'') As ToTime,
	ISNULL(TS.IsDisplayPeriodTime,0) As IsDiplayPeriodTime,
	(SELECT ISNULL(EM.FirstName+' '+EM.LastName,'') FROM sHrm.tEmployeeMaster EM INNER JOIN sSetup.tDivisionMaster DIE ON DIE.InchargeEmployeeId = EM.Id  WHERE DIE.Id = DV.Id) as DivisionIncharge,
	[sCommon].[fXMLTagsReplaceReverse](STUFF((
		SELECT ',<br>' +  ISNULL(VBCD1.ClassDivisionName +'<br><b>'+SM1.Title+'</b>','')
				FROM sTimetable.tTimeTable T1 
				INNER JOIN sSetup.tSubjectMaster SM1 ON SM1.Id=T1.SubjectId
					INNER JOIN sSetup.vClassDivision VBCD1 ON VBCD1.DivisionId=T1.DivisionId
				where T1.EmployeeId=TT.EmployeeId 
				AND TT.LectureNumber=T1.LectureNumber 
				AND TT.DayId=T1.DayId and TT.TimeTableSchemaId=T1.TimeTableSchemaId  
				--AND timetableid in ()
				FOR XML PATH('')
				), 1, 11, ''))  ClassSubject
	FROM 
	sTimetable.tTimeTable TT  
	LEFT JOIN sSetup.tSubjectMaster SM ON SM.Id = TT.SubjectId 
	INNER JOIN sHrm.tEmployeeMaster Em ON Em.Id = TT.EmployeeId
	LEFT JOIN sCommon.tDayMaster DM ON DM.Id = TT.DayId
	LEFT JOIN sSetup.tDivisionMaster DV ON DV.Id = TT.DivisionId
	LEFT JOIN sSetup.tClassMaster CM ON CM.Id = DV.ClassId
	LEFT JOIN sTimetable.tTimeTableSchema TTS ON TTS.Id = TT.TimeTableSchemaId
	LEFT JOIN sTimetable.tTimeTableTime TTM ON TTM.TimeTableSchemaId=TT.TimeTableSchemaId AND TTM.DayId = DM.Id AND TTM.DivisionId = TT.DivisionId AND TTM.LectureNumber = TT.LectureNumber AND TTM.IsBreak = 0
	INNER JOIN sTimetable.tTimeTableSchema TS ON TS.Id = TT.TimeTableSchemaId 
	INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = DV.OrgId
	WHERE (ClassId = @rClassId OR @rClassId=0)
	  AND (TT.DivisionId = @rDivisionId OR @rDivisionId=0)	
	  AND (TT.EmployeeId=@rEmployeeId OR @rEmployeeId=0)
	  AND TT.TimeTableSchemaId=@rTimeTableSchemaId
	  AND (TT.DayId = (DATEPART(weekday,@rDate)) OR @rDate = '')
	  AND (OM.Id = @rOrgId OR @rOrgId = 0)
	  --AND (Em.OrgId = @rOrgId OR @rOrgId = 0)
	  )
	  A  ORDER BY A.EmployeeName, A.DivisionOrderIndex,A.DayId, A.LactureNumber
   END
 ELSE
 BEGIN
	SELECT

	A.TimeTableID,
	A.DivisionName,
	A.EmployeeId,
	A.SubjectId,
	CASE WHEN A.EmployeeId=-1 THEN '###' WHEN A.EmployeeId=-2 THEN '***' ELSE A.EmployeeName END As EmployeeName,
	CASE WHEN A.SubjectId=-1 THEN '###' WHEN A.SubjectId=-2 THEN '***' ELSE A.Subject END  AS Subject,
	--A.Subject,
	A.DivisionId,
	--ISNULL(L.Title,'') AS DayName,
	--ISNULL(L.DayId,0) AS DayId,
	--ISNULL(L.LectureNumber,'') AS LactureNumber,
	ISNULL(A.DayName,'') AS DayName,
	ISNULL(A.DayId,0) AS DayId,
	ISNULL(A.LactureNumber,'') AS LactureNumber,
	A.DayLacture,
	A.ClassId,
	A.ClassDivisionName,
	A.DivisionOrderIndex,
	A.Code,
	[sTimetable].[fTimeTableDetailGet](A.TimeTableID,1) AS TimeTableDetail,
	0 AS IsPresent,
	A.WeekOffs,
	CASE WHEN EXISTS (SELECT 1 FROM sTimetable.tTimeTableSchema TS INNER JOIN sTimetable.tTimeTable TT ON TT.TimeTableSchemaId = TS.Id WHERE TS.IsDisplayPeriodTime = 1 AND TS.Id = @rTimeTableSchemaId) THEN A.FromTime ELSE '' END As FromTime,
	CASE WHEN EXISTS (SELECT 1 FROM sTimetable.tTimeTableSchema TS INNER JOIN sTimetable.tTimeTable TT ON TT.TimeTableSchemaId = TS.Id WHERE TS.IsDisplayPeriodTime = 1 AND TS.Id = @rTimeTableSchemaId) THEN A.ToTime ELSE '' END As ToTime,
	ISNULL(IsDiplayPeriodTime,0) As IsDiplayPeriodTime,
	DivisionIncharge,
	IsBreak,
	IsBreakBefore,
	EmployeeSubject,
	ClassSubject,
	EmployeeSNSubject,
	ISNULL(Convert(smallint,(select Isnull(max(cast(IsBreak as smallint)),0)*2+ISNULL(max(cast(IsBreakBefore as smallint)),0)*1
			From sTimetable.tTimeTableTime
			where TimeTableSchemaId=@rTimeTableSchemaId AND LectureNumber=A.LactureNumber
			Group by TimeTableSchemaId,LectureNumber)),0) AS HideBreak
FROM
(
	SELECT 
	--@rBuilder1 AS Builder1,
	--@rBuilder2 AS Builder2,	 
	TT.Id AS TimeTableID,
	ISNULL(DV.Title,'') AS DivisionName,
	ISNULL(TT.EmployeeId,0) AS EmployeeId,
	ISNULL(SubjectId,0) AS SubjectId,
	[sHrm].[fEmployeeNameGet](ISNULL(Em.FirstName,'') , ISNULL(Em.MiddleName,''), ISNULL(Em.LastName,''),ISNULL(OM.EmployeeNameFormatId,1)) AS EmployeeName,
	--ISNULL(EM.LastName+' '+EM.FirstName,'')  AS EmployeeName,
	ISNULL(SM.Title,'') AS Subject,
	ISNULL(TT.DivisionId,0) AS DivisionId,
	ISNULL(DM.Title,'') AS DayName,
	ISNULL(TT.DayId,0) AS DayId,
	ISNULL(TT.LectureNumber,'') AS LactureNumber,
	ISNULL(DM.Title,'') +'-'+ISNULL(convert(nvarchar(4),TT.LectureNumber),'') AS DayLacture,
	ISNULL(DV.ClassId,0) AS ClassId,
	ISNULL(CM.DisplayTitle,'')+'-'+ISNULL(DV.Title,'') as ClassDivisionName,
	ISNULL(DV.OrderIndex,0) As DivisionOrderIndex,
	ISNULL(SM.Code,'') AS Code,
	ISNULL(TTS.WeekOffs,'') As WeekOffs,
	ISNULL(TTM.FromTime,'') As FromTime,
	ISNULL(TTM.ToTime,'') As ToTime,
	ISNULL(TS.IsDisplayPeriodTime,0) As IsDiplayPeriodTime,
	(SELECT ISNULL(EM.FirstName+' '+EM.LastName,'') FROM sHrm.tEmployeeMaster EM INNER JOIN sSetup.tDivisionMaster DIE ON DIE.InchargeEmployeeId = EM.Id  WHERE DIE.Id = DV.Id) as DivisionIncharge,

	--GetBreak
	CASE WHEN 
	(SELECT ISNULL(IsBreak,0) FROM sTimetable.tTimeTableTime WHERE TimeTableSchemaId = TT.TimeTableSchemaId 
	AND DayId = TT.DayId AND DivisionId = TT.DivisionId AND LectureNumber = TT.LectureNumber AND IsBreak = 1) = 1 
	THEN (SELECT ISNULL(IsBreak,0) FROM sTimetable.tTimeTableTime WHERE TimeTableSchemaId = TT.TimeTableSchemaId 
	AND DayId = TT.DayId AND DivisionId = TT.DivisionId AND LectureNumber = TT.LectureNumber AND IsBreak = 1)
	ELSE ISNULL(TT.IsBreak,0) END AS IsBreak,

	--GetBreakBefore
	CASE WHEN 
	(SELECT ISNULL(IsBreakBefore,0) FROM sTimetable.tTimeTableTime WHERE TimeTableSchemaId = TT.TimeTableSchemaId 
	AND DayId = TT.DayId AND DivisionId = TT.DivisionId AND LectureNumber = TT.LectureNumber AND IsBreakBefore = 1) = 1 
	THEN (SELECT ISNULL(IsBreakBefore,0) FROM sTimetable.tTimeTableTime WHERE TimeTableSchemaId = TT.TimeTableSchemaId 
	AND DayId = TT.DayId AND DivisionId = TT.DivisionId AND LectureNumber = TT.LectureNumber AND IsBreakBefore = 1)
	ELSE ISNULL(TT.IsBreakBefore,0) END AS IsBreakBefore,
	[sCommon].[fXMLTagsReplaceReverse](STUFF((
			SELECT ',<br>' +  ISNULL(ISNULL([sHrm].[fEmployeeNameGet](ISNULL(Em1.FirstName,'') , ISNULL(Em1.MiddleName,''), ISNULL(Em1.LastName,''),ISNULL(OM1.EmployeeNameFormatId,1)) ,'') +' - '+SM1.Title,'')
			FROM sTimetable.tTimeTable T1 
			inner join sHrm.tEmployeeMaster EM1 on EM1.Id=T1.EmployeeId
			INNER JOIN sSetup.tSubjectMaster SM1 ON SM1.Id=T1.SubjectId
			LEFT JOIN sSetup.tOrganizationMaster OM1 ON OM1.Id = Em1.OrgID
			where T1.DivisionId=TT.DivisionId 
			AND T1.LectureNumber=TT.LectureNumber 
			AND T1.DayId=TT.DayId and T1.TimeTableSchemaId=TT.TimeTableSchemaId  
			--AND timetableid in ()
			FOR XML PATH('')
			), 1, 11, ''))  EmployeeSubject,
	[sCommon].[fXMLTagsReplaceReverse](STUFF((
		SELECT ',<br>' +  ISNULL(VBCD1.ClassDivisionName+'<br><b>' +SM1.Code+'</b>','')
				FROM sTimetable.tTimeTable T1 
				INNER JOIN sSetup.tSubjectMaster SM1 ON SM1.Id=T1.SubjectId
					INNER JOIN sSetup.vClassDivision VBCD1 ON VBCD1.DivisionId=T1.DivisionId
				where T1.EmployeeId=TT.EmployeeId 
				AND TT.LectureNumber=T1.LectureNumber 
				AND TT.DayId=T1.DayId and TT.TimeTableSchemaId=T1.TimeTableSchemaId  
				--AND timetableid in ()
				FOR XML PATH('')
				), 1, 11, '')) ClassSubject,
	STUFF((
			SELECT ', ' +  ISNULL(ISNULL(Em1.ShortName,'') +' - '+SM1.Title,'')
			FROM sTimetable.tTimeTable T1 
			inner join sHrm.tEmployeeMaster EM1 on EM1.Id=T1.EmployeeId
			INNER JOIN sSetup.tSubjectMaster SM1 ON SM1.Id=T1.SubjectId
			where T1.DivisionId=TT.DivisionId 
			AND TT.LectureNumber=T1.LectureNumber 
			AND TT.DayId=T1.DayId and TT.TimeTableSchemaId=T1.TimeTableSchemaId  
			--AND timetableid in ()
			FOR XML PATH('')
			), 1, 1, '') EmployeeSNSubject

	FROM 
	sTimetable.tTimeTable TT  
	LEFT JOIN sSetup.tSubjectMaster SM ON SM.Id = TT.SubjectId 
	LEFT JOIN sHrm.tEmployeeMaster Em ON Em.Id = TT.EmployeeId
	LEFT JOIN sCommon.tDayMaster DM ON DM.Id = TT.DayId
	LEFT JOIN sSetup.tDivisionMaster DV ON DV.Id = TT.DivisionId
	LEFT JOIN sSetup.tClassMaster CM ON CM.Id = DV.ClassId
	LEFT JOIN sTimetable.tTimeTableSchema TTS ON TTS.Id = TT.TimeTableSchemaId
	LEFT JOIN sTimetable.tTimeTableTime TTM ON TTM.TimeTableSchemaId=TT.TimeTableSchemaId AND TTM.DayId = DM.Id AND TTM.DivisionId = TT.DivisionId AND TTM.LectureNumber = TT.LectureNumber AND TTM.IsBreak = 0	
	INNER JOIN sTimetable.tTimeTableSchema TS ON TS.Id = TT.TimeTableSchemaId 
	INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = DV.OrgId
	WHERE (ClassId = @rClassId OR @rClassId=0)
	  AND (TT.DivisionId = @rDivisionId OR @rDivisionId=0)	
	  AND (TT.EmployeeId=@rEmployeeId OR @rEmployeeId=0)
	  AND TT.TimeTableSchemaId=@rTimeTableSchemaId
	  AND (TT.DayId = (DATEPART(weekday,@rDate)) OR @rDate = '')
	  AND (OM.Id = @rOrgId OR @rOrgId = 0)
	  AND TT.EmployeeId <> 0
	  )
	  A  ORDER BY A.EmployeeName, A.DivisionOrderIndex,A.DayId, A.LactureNumber
		END
END
GO
PRINT N'Altering Procedure [sTool].[pUpgradeVersion]...';


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

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

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


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

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



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

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

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

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

-- update tablerowid master data from excel to table

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

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

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



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




exec [sTool].[pTableRowIdCurrentNumberSet] @rOrgGroupId

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


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

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


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


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

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

--static entry in tVisitorTypeMaster

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

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

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

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

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

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

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

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


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

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

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


			
			
END


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

END


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

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

END

UPDATE sSystem.tDatabaseInfo SET ApplicationId = 1

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

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

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

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

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

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

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

-- for SysSuperAdmin update password
UPDATE sSecurity.tUser SET LoginPassword='0ca5MKWkfJN5DAbg5Rp+fg==' WHERE Id = sCommon.fGetBigIntIdForOrg(1,@rOrgGroupId)
UPDATE sSecurity.tUser SET LoginPassword='0ca5MKWkfJN5DAbg5Rp+fg==' WHERE Id = 1

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

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


GO



CREATE PROCEDURE [sFee].[pRptPendingFee100PercentGet]

 @rOrgId int = 0,
 @rBatchId int = 0,
 @rOrgGroupBatchId int = 0,
 @rClassId int = 0,
 @rDivisionId int = 0,
 @rReceiptBookId int = 0,
 @rDepartmentId int = 0,
 @rCommonBatch nvarchar(100) = '',
 @rAdmissionCategoryId int = 0,
 @rClassStatusId int = 0,
 @rIsDisplayOrgGroup bit=0,
 @rIsFilter bit=0,
 @rBuilder1 nvarchar(max) = '',
 @rBuilder2 nvarchar(max) = ''
	
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
	IF object_id('tempdb..#tTable') IS NOT NULL
	BEGIN
		DROP TABLE #tTable
	END
CREATE TABLE #tTable(
	AcademicId BIGINT NOT NULL,
	AdmissionCategoryId int,
	ReceiptBookId int
)
INSERT INTO #tTable
	SELECT SA.AcademicId, FS.AdmissionCategoryId, FS.ReceiptBookId
	FROM sFee.tFeeSetup FS
	INNER JOIN sStudent.vStudentAcademic SA ON SA.ClassId=FS.ClassId AND FS.BatchId = SA.BatchId AND SA.AdmissionCategoryId = FS.AdmissionCategoryId
	--INNER JOIN sSetup.tBatchMaster BM ON FS.BatchId = BM.Id 
	AND (SA.OrgGroupBatchId = @rOrgGroupBatchId OR @rOrgGroupBatchId = 0)
	WHERE 
	((SA.OrgId = @rOrgId)OR(@rOrgId = 0)) 
	AND ((SA.BatchId = @rBatchId) OR (@rBatchId = 0))
	AND (SA.BatchName = @rCommonBatch OR @rCommonBatch = '') 
	AND (SA.DepartmentId = @rDepartmentId OR @rDepartmentId = 0)
	AND (SA.ClassStatusId = @rClassStatusId OR @rClassStatusId = 0)
	AND (SA.ClassId = @rClassId OR @rClassId = 0)
	AND (SA.DivisionId = @rDivisionId OR @rDivisionId = 0)
	AND (FS.ReceiptBookId = @rReceiptBookId OR @rReceiptBookId = 0)
	AND (FS.AdmissionCategoryId = @rAdmissionCategoryId OR @rAdmissionCategoryId = 0)
	GROUP BY FS.ClassId,SA.AcademicId,FS.AdmissionCategoryId, FS.ReceiptBookId


SELECT F.AcademicId, F.RollNo, F.Name, F.Code, F.ClassName , F.DivisionName , @rIsFilter AS IsFilter ,
	 @rIsDisplayOrgGroup AS IsDisplayOrgGroup, F.ClassOrderIndex, F.DivisionOrder AS DivisionOrderIndex,
	 @rBuilder1 AS Builder1, @rBuilder2 AS Builder2
	FROM
		(

		SELECT 
			SA.AcademicId, SA.RollNo,SA.Name,SA.Code, ISNULL(T.AcademicId,0) AS Pending, ISNULL(PS.AcademicId,0) AS [Partial]
			,SA.ClassName , SA.DivisionName , SA.ClassOrderIndex , SA.DivisionOrder
			,(
				SELECT (SUM(FS1.Amount)+Sum(FA1.VariableAmount)+ SUM(FA1.AdditionalAmount)) - (SUM(FA1.DiscountAmount)+ SUM(FA1.NotApplicableAmount)) 
				FROM sFee.tFeeAllocation FA1
				INNER JOIN sFee.tFeeSetup FS1 ON FS1.BatchId = SA.BatchId AND FS1.ClassId = SA.ClassId AND FS1.AdmissionCategoryId = SA.AdmissionCategoryId AND FA1.FeeSetupId = FS1.Id
				WHERE FA1.SourceId = SA.AcademicId 
					AND (FS1.AdmissionCategoryId = @rAdmissionCategoryId OR @rAdmissionCategoryId = 0)
					AND (FS1.ReceiptBookId = @rReceiptBookId OR @rReceiptBookId = 0)
			) AS IsFeePayAmount
		FROM sStudent.vStudentAcademic SA 
		INNER JOIN #tTable FS  on  FS.AcademicId = SA.AcademicId
		LEFT JOIN(
			SELECT COUNT(R.Id)as PaidCount,R.SourceId AS AcademicId--, SA.Code,SA.Name 
			FROM sFee.tReceipt R
			--INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.SourceId 
			WHERE R.SourceTypeId = 2001 --AND((SA.OrgId = @rOrgId) OR (@rOrgId = 0))
			AND ((R.BatchId = @rBatchId) OR (@rBatchId = 0)) AND (R.IsObsolete = 0)
			AND (R.ReceiptBookId = @rReceiptBookId OR @rReceiptBookId = 0) 
			GROUP BY R.SourceId--, SA.Code,SA.Name
			)T ON T.AcademicId = SA.AcademicId
		LEFT JOIN 
			(
				SELECT 
					SA1.AcademicId 
				FROM sFee.tFeeSetup FS1
				INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				LEFT JOIN sFee.tFeeAllocation FA ON FA.FeeSetupId=FS1.Id AND FA.SourceId=SA1.AcademicId
				LEFT JOIN 
					(
					SELECT 
						SUM(RD.Amount) as Amount,R.SourceId,FS.Id AS FeeSetupId
					FROM sFee.tReceiptDetail RD
					INNER JOIN sFee.tReceipt R ON RD.ReceiptId = R.Id
					INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id
					WHERE R.SourceTypeId = 2001
					AND (R.IsObsolete = 0) 
					AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
					AND (R.ReceiptBookId = @rReceiptBookId OR @rReceiptBookId = 0)
					Group By R.SourceId,FS.Id
					) R ON R.SourceId = SA1.AcademicId AND R.FeeSetupId = FS1.Id
				INNER JOIN 
					(
					SELECT Distinct SourceId 
					FROM sFee.tReceipt 
					) RE ON RE.SourceId = SA1.AcademicId
				WHERE 
					((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
					AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
					AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
					AND SA1.StatusId =1
					AND FS1.IsOptional = 0
					AND ISNULL(FS1.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.Amount,0.00) > 0
					AND (FS1.AdmissionCategoryId = @rAdmissionCategoryId OR @rAdmissionCategoryId = 0)
					AND (FS1.ReceiptBookId = @rReceiptBookId OR @rReceiptBookId = 0)
							
				UNION 

				SELECT 
					SA1.AcademicId 
				FROM sFee.tFeeSetup FS1
				INNER JOIN sFee.tFeeOptional FO ON FO.FeeSetupId=FS1.Id 
				INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId AND SA1.AcademicId=FO.SourceId
				LEFT JOIN sFee.tFeeAllocation FA ON FA.FeeSetupId=FS1.Id AND FA.SourceId=SA1.AcademicId
				LEFT JOIN 
				(
					SELECT SUM(RD.Amount) as Amount,R.SourceId,FS.Id AS FeeSetupId
					FROM sFee.tReceiptDetail RD
					INNER JOIN sFee.tReceipt R ON RD.ReceiptId = R.Id
					INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id
					WHERE R.SourceTypeId = 2001
					AND (R.IsObsolete = 0) 
					AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
					AND (R.ReceiptBookId = @rReceiptBookId OR @rReceiptBookId = 0)
					Group By R.SourceId,FS.Id
					) R ON R.SourceId = SA1.AcademicId AND R.FeeSetupId = FS1.Id
				INNER JOIN 
				(
					SELECT Distinct SourceId 
					FROM sFee.tReceipt 
				) RE ON RE.SourceId = SA1.AcademicId
				WHERE 
					((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
					AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
					AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
					AND SA1.StatusId =1
					AND FS1.IsOptional = 1
					AND ISNULL(FS1.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.Amount,0.00) > 0
					AND (FS1.AdmissionCategoryId = @rAdmissionCategoryId OR @rAdmissionCategoryId = 0)
					AND (FS1.ReceiptBookId = @rReceiptBookId OR @rReceiptBookId = 0)

			) PS ON PS.AcademicId=SA.AcademicId

		WHERE 
			
		((SA.OrgId = @rOrgId)OR(@rOrgId = 0)) 
		AND SA.StatusId =1
		AND ((SA.BatchId = @rBatchId) OR (@rBatchId = 0))
		AND (SA.BatchName = @rCommonBatch OR @rCommonBatch = '') 
		AND (SA.DepartmentId = @rDepartmentId OR @rDepartmentId = 0)
		AND (SA.ClassStatusId = @rClassStatusId OR @rClassStatusId = 0)
		AND (SA.ClassId = @rClassId OR @rClassId = 0)
		AND (SA.DivisionId = @rDivisionId OR @rDivisionId = 0)
		AND (FS.ReceiptBookId = @rReceiptBookId OR @rReceiptBookId = 0)
		AND (FS.AdmissionCategoryId = @rAdmissionCategoryId OR @rAdmissionCategoryId = 0)	
		) AS F 
		
	WHERE ISNULL(F.IsFeePayAmount,1) <> 0 AND F.Pending = 0 AND F.Partial = 0


	--For Dataset Drag and Drop
	--SELECT
	--CONVERT(BigInt,0) AS AcademicId,
	--0 AS RollNo,
	--'' AS Name,
	--'' AS Code,
	--'' AS ClassName,
	--'' AS DivisionName,
	--CONVERT(bit,0) AS IsFilter,
	--CONVERT(bit,0) AS IsDisplayOrgGroup,
	--0 AS ClassOrderIndex,
	--0 AS DivisionOrderIndex,
	--'' AS Builder1,
	--'' AS Builder2

END
GO
PRINT N'Creating Procedure [sStudent].[pRptStudentLCVerificationGet]...';


GO
CREATE PROCEDURE [sStudent].[pRptStudentLCVerificationGet]
	 
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 @rDepartmentId int=0,
	 @rClassId int=0,
	 @rDivisionId int=0,
     @rStrCode nvarchar(20)='',
	 @rStatusId int=0,
	 @rClassStatusId int=0,
	 @rExamId int = 0

	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
	
	SELECT 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			L.Id,		
			SM.Code,
			L.AcademicId,
			SM.FirstName,SM.MiddleName,SM.LastName,
			[sStudent].[fStudentNameGet](SM.FirstName , SM.MiddleName, SM.LastName,OM.StudentNameFormatId ) AS Name,
			ISNULL(SF.FatherName,'') As FatherName,
			ISNULL(SF.MotherName,'') As MotherName,
			ISNULL(CTM.Nationality,'') AS Nationality,		
			ISNULL(RM.Title,'') AS Religion,
			ISNULL(so.BirthPlace,'') AS BirthPlace,
			ISNULL(SO.BirthTaluka,'') AS BirthTaluka,
			ISNULL(SO.BirthDistrict,'') AS BirthDistrict,
			SO.DateOfBirth,
			ISNULL(SO.BirthDateInWord,'') AS 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,
		
			SM.StatusId,
			--L.LastExamName AS Result,
			--L.LastExamResult AS FailOrPass,
			--L.SubjectStudied AS SubjectNAme,
		--	L.RepeatDetail as PromotedorNot,
			
			--L.PromoteToClass  AS PromotedToClass,
			--L.FeeDetail AS LastFeesPaid,
		     --	L.FeeConcessionDetail AS AnyConcession,
           --L.NCCScoutDetail  AS NCCScoutDetail,
		--	L.ExtraCurricularActivities AS GamesPlayed,
			OM.OrgLogo,
			OM.Title AS OrgTitle,
			OM.StreetOne+' '+OM.StreetTwo+' '+OM.StreetThree AS OrgAddress,
			OM.PhoneNo,
			vSA.RollNo,
			DM.OrderIndex AS DivisionOrder,
			OM.SmallAddress1,
			OM.SmallAddress2,
			OM.RegistrationDetail,			
			vSA.ClassName AS ClassName,
			vSA.DivisionName AS DivisionName,
			
			isnull(MainCastCategoryId,0) AS CastCategoryId,
			--ISNULL(L.ToCollege,'') AS ToCollege ,
			--ISNULL(L.ToCollegeAddress,'')AS ToCollegeAddress,
		--	ISNULL(OM.University,'')AS University,
			
		
			--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
			
			,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,
	    	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
	FROM 
			sCertificate.tLeaving L
			INNER JOIN sStudent.vStudentAcademic vSA ON vSA.AcademicId=L.AcademicId
			
			LEFT JOIN sStudent.tStudentAdmission SA ON SA.StudentId=vSA.StudentId
			INNER JOIN sStudent.tStudentMaster SM ON SM.Id=vSA.StudentId			
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=vSA.OrgId 
			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 sSetup.tClassMaster CM ON CM.Id=SA.AdmissionStandardId
			INNER JOIN sSetup.tDivisionMaster DM ON vSA.DivisionId = DM.Id  
			INNER JOIN sSetup.tClassMaster CMS ON CMS.Id= DM.ClassId 
			LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId=vSA.StudentId
			LEFT JOIN sCommon.tCountryMaster CTM ON CTM.Id=SO.NationalityId
			LEFT JOIN sStudent.tAcademicDetail AD ON AD.AcademicId=vSA.AcademicId
			
			LEFT JOIN sSetup.tOrgImages OI ON OI.OrgId = OM.Id
			LEFT JOIN sCommon.tCastCategoryMaster CSM ON CSM.Id=SO.CastCategoryId
			
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id=vSA.BatchId 
		
			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
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId=vSA.ClassId
            INNER JOIN sAssessment.tResult R ON R.ExamId = EM.Id
	Where		
	           ((vSA.DepartmentId=@rDepartmentId) OR(@rDepartmentId=0))
	       AND ((vSA.ClassId=@rClassId) OR(@rClassId=0))
	  
	       AND ((vSA.DivisionId=@rDivisionId) OR (@rDivisionId=0))	
		   AND ((vSA.Code = @rStrCode) OR (ISNULL(@rStrCode,'') = ''))
           AND ((vSA.StatusId=@rStatusId)OR(@rStatusId=0))
		   AND ((vSA.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0)) 
		   AND ((R.ExamId = @rExamId) OR (@rExamId=0))
				
END
GO
PRINT N'Creating Extended Property [sFrontOffice].[tEmployeeGatePass].[StatusId].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'Pending Approve Reject', @level0type = N'SCHEMA', @level0name = N'sFrontOffice', @level1type = N'TABLE', @level1name = N'tEmployeeGatePass', @level2type = N'COLUMN', @level2name = N'StatusId';


GO
PRINT N'Creating Extended Property [sFrontOffice].[tEmployeeGatePass].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'', @level0type = N'SCHEMA', @level0name = N'sFrontOffice', @level1type = N'TABLE', @level1name = N'tEmployeeGatePass';


GO
PRINT N'Creating Extended Property [sFrontOffice].[tVisitorLog].[StatusId].[MS_Description]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_Description', @value = N'Pending Approve Reject', @level0type = N'SCHEMA', @level0name = N'sFrontOffice', @level1type = N'TABLE', @level1name = N'tVisitorLog', @level2type = N'COLUMN', @level2name = N'StatusId';


GO
PRINT N'Creating Extended Property [sHrm].[vExtEmployee].[MS_DiagramPane1]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_DiagramPane1', @value = N'[0E232FF0-B466-11cf-A24F-00AA00A3EFFF, 1.00]
Begin DesignProperties = 
   Begin PaneConfigurations = 
      Begin PaneConfiguration = 0
         NumPanes = 4
         Configuration = "(H (1[40] 4[20] 2[20] 3) )"
      End
      Begin PaneConfiguration = 1
         NumPanes = 3
         Configuration = "(H (1 [50] 4 [25] 3))"
      End
      Begin PaneConfiguration = 2
         NumPanes = 3
         Configuration = "(H (1 [50] 2 [25] 3))"
      End
      Begin PaneConfiguration = 3
         NumPanes = 3
         Configuration = "(H (4 [30] 2 [40] 3))"
      End
      Begin PaneConfiguration = 4
         NumPanes = 2
         Configuration = "(H (1 [56] 3))"
      End
      Begin PaneConfiguration = 5
         NumPanes = 2
         Configuration = "(H (2 [66] 3))"
      End
      Begin PaneConfiguration = 6
         NumPanes = 2
         Configuration = "(H (4 [50] 3))"
      End
      Begin PaneConfiguration = 7
         NumPanes = 1
         Configuration = "(V (3))"
      End
      Begin PaneConfiguration = 8
         NumPanes = 3
         Configuration = "(H (1[56] 4[18] 2) )"
      End
      Begin PaneConfiguration = 9
         NumPanes = 2
         Configuration = "(H (1 [75] 4))"
      End
      Begin PaneConfiguration = 10
         NumPanes = 2
         Configuration = "(H (1[66] 2) )"
      End
      Begin PaneConfiguration = 11
         NumPanes = 2
         Configuration = "(H (4 [60] 2))"
      End
      Begin PaneConfiguration = 12
         NumPanes = 1
         Configuration = "(H (1) )"
      End
      Begin PaneConfiguration = 13
         NumPanes = 1
         Configuration = "(V (4))"
      End
      Begin PaneConfiguration = 14
         NumPanes = 1
         Configuration = "(V (2))"
      End
      ActivePaneConfig = 0
   End
   Begin DiagramPane = 
      Begin Origin = 
         Top = -307
         Left = 0
      End
      Begin Tables = 
         Begin Table = "EM"
            Begin Extent = 
               Top = 6
               Left = 38
               Bottom = 136
               Right = 241
            End
            DisplayFlags = 280
            TopColumn = 0
         End
         Begin Table = "EJD"
            Begin Extent = 
               Top = 138
               Left = 38
               Bottom = 268
               Right = 268
            End
            DisplayFlags = 280
            TopColumn = 0
         End
      End
   End
   Begin SQLPane = 
   End
   Begin DataPane = 
      Begin ParameterDefaults = ""
      End
   End
   Begin CriteriaPane = 
      Begin ColumnWidths = 11
         Column = 1440
         Alias = 900
         Table = 1170
         Output = 720
         Append = 1400
         NewValue = 1170
         SortType = 1350
         SortOrder = 1410
         GroupBy = 1350
         Filter = 1350
         Or = 1350
         Or = 1350
         Or = 1350
      End
   End
End
', @level0type = N'SCHEMA', @level0name = N'sHrm', @level1type = N'VIEW', @level1name = N'vExtEmployee';


GO
PRINT N'Creating Extended Property [sHrm].[vExtEmployee].[MS_DiagramPaneCount]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_DiagramPaneCount', @value = 1, @level0type = N'SCHEMA', @level0name = N'sHrm', @level1type = N'VIEW', @level1name = N'vExtEmployee';


GO
PRINT N'Creating Extended Property [sStudent].[vStudentAcademic].[MS_DiagramPane1]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_DiagramPane1', @value = N'[0E232FF0-B466-11cf-A24F-00AA00A3EFFF, 1.00]
Begin DesignProperties = 
   Begin PaneConfigurations = 
      Begin PaneConfiguration = 0
         NumPanes = 4
         Configuration = "(H (1[15] 4[47] 2[21] 3) )"
      End
      Begin PaneConfiguration = 1
         NumPanes = 3
         Configuration = "(H (1 [50] 4 [25] 3))"
      End
      Begin PaneConfiguration = 2
         NumPanes = 3
         Configuration = "(H (1 [50] 2 [25] 3))"
      End
      Begin PaneConfiguration = 3
         NumPanes = 3
         Configuration = "(H (4 [30] 2 [40] 3))"
      End
      Begin PaneConfiguration = 4
         NumPanes = 2
         Configuration = "(H (1 [56] 3))"
      End
      Begin PaneConfiguration = 5
         NumPanes = 2
         Configuration = "(H (2 [66] 3))"
      End
      Begin PaneConfiguration = 6
         NumPanes = 2
         Configuration = "(H (4 [50] 3))"
      End
      Begin PaneConfiguration = 7
         NumPanes = 1
         Configuration = "(V (3))"
      End
      Begin PaneConfiguration = 8
         NumPanes = 3
         Configuration = "(H (1[56] 4[18] 2) )"
      End
      Begin PaneConfiguration = 9
         NumPanes = 2
         Configuration = "(H (1 [75] 4))"
      End
      Begin PaneConfiguration = 10
         NumPanes = 2
         Configuration = "(H (1[66] 2) )"
      End
      Begin PaneConfiguration = 11
         NumPanes = 2
         Configuration = "(H (4 [60] 2))"
      End
      Begin PaneConfiguration = 12
         NumPanes = 1
         Configuration = "(H (1) )"
      End
      Begin PaneConfiguration = 13
         NumPanes = 1
         Configuration = "(V (4))"
      End
      Begin PaneConfiguration = 14
         NumPanes = 1
         Configuration = "(V (2))"
      End
      ActivePaneConfig = 0
   End
   Begin DiagramPane = 
      Begin Origin = 
         Top = 0
         Left = 0
      End
      Begin Tables = 
         Begin Table = "A"
            Begin Extent = 
               Top = 6
               Left = 38
               Bottom = 136
               Right = 241
            End
            DisplayFlags = 280
            TopColumn = 0
         End
         Begin Table = "SM"
            Begin Extent = 
               Top = 138
               Left = 38
               Bottom = 268
               Right = 241
            End
            DisplayFlags = 280
            TopColumn = 0
         End
         Begin Table = "CM"
            Begin Extent = 
               Top = 6
               Left = 279
               Bottom = 136
               Right = 466
            End
            DisplayFlags = 280
            TopColumn = 0
         End
         Begin Table = "DM"
            Begin Extent = 
               Top = 270
               Left = 38
               Bottom = 400
               Right = 250
            End
            DisplayFlags = 280
            TopColumn = 0
         End
         Begin Table = "BM"
            Begin Extent = 
               Top = 138
               Left = 279
               Bottom = 268
               Right = 473
            End
            DisplayFlags = 280
            TopColumn = 0
         End
         Begin Table = "STM"
            Begin Extent = 
               Top = 270
               Left = 288
               Bottom = 400
               Right = 458
            End
            DisplayFlags = 280
            TopColumn = 0
         End
         Begin Table = "DeptM"
            Begin Extent = 
               Top = 402
               Left = 38
               Bottom = 532
               Right = 222
            End
            DisplayFlags = 280
            TopColumn = 0
     ', @level0type = N'SCHEMA', @level0name = N'sStudent', @level1type = N'VIEW', @level1name = N'vStudentAcademic';


GO
PRINT N'Creating Extended Property [sStudent].[vStudentAcademic].[MS_DiagramPane2]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_DiagramPane2', @value = N'    End
         Begin Table = "OM"
            Begin Extent = 
               Top = 534
               Left = 38
               Bottom = 664
               Right = 297
            End
            DisplayFlags = 280
            TopColumn = 0
         End
         Begin Table = "STM1"
            Begin Extent = 
               Top = 402
               Left = 260
               Bottom = 532
               Right = 430
            End
            DisplayFlags = 280
            TopColumn = 0
         End
         Begin Table = "SO"
            Begin Extent = 
               Top = 666
               Left = 38
               Bottom = 796
               Right = 222
            End
            DisplayFlags = 280
            TopColumn = 0
         End
      End
   End
   Begin SQLPane = 
   End
   Begin DataPane = 
      Begin ParameterDefaults = ""
      End
   End
   Begin CriteriaPane = 
      Begin ColumnWidths = 11
         Column = 9180
         Alias = 5055
         Table = 1170
         Output = 720
         Append = 1400
         NewValue = 1170
         SortType = 1350
         SortOrder = 1410
         GroupBy = 1350
         Filter = 1350
         Or = 1350
         Or = 1350
         Or = 1350
      End
   End
End
', @level0type = N'SCHEMA', @level0name = N'sStudent', @level1type = N'VIEW', @level1name = N'vStudentAcademic';


GO
PRINT N'Creating Extended Property [sStudent].[vStudentAcademic].[MS_DiagramPaneCount]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_DiagramPaneCount', @value = 2, @level0type = N'SCHEMA', @level0name = N'sStudent', @level1type = N'VIEW', @level1name = N'vStudentAcademic';


GO
PRINT N'Refreshing Procedure [sCommon].[pOrganizationSetupRemove]...';


GO
EXECUTE sp_refreshsqlmodule N'[sCommon].[pOrganizationSetupRemove]';


GO
PRINT N'Refreshing Procedure [sFee].[pDepositBalanceDelete]...';


GO
EXECUTE sp_refreshsqlmodule N'[sFee].[pDepositBalanceDelete]';


GO
PRINT N'Refreshing Procedure [sFee].[pDepositHeadMasterDelete]...';


GO
EXECUTE sp_refreshsqlmodule N'[sFee].[pDepositHeadMasterDelete]';


GO
PRINT N'Refreshing Procedure [sFee].[pFeeReceiptImportValidate]...';


GO
EXECUTE sp_refreshsqlmodule N'[sFee].[pFeeReceiptImportValidate]';


GO
PRINT N'Refreshing Procedure [sFee].[pGSTReceiptAdd]...';


GO
EXECUTE sp_refreshsqlmodule N'[sFee].[pGSTReceiptAdd]';


GO
PRINT N'Refreshing Procedure [sFee].[pReceiptAdd]...';


GO
EXECUTE sp_refreshsqlmodule N'[sFee].[pReceiptAdd]';


GO
PRINT N'Refreshing Procedure [sHrm].[pEmployeeGenerateReport]...';


GO
EXECUTE sp_refreshsqlmodule N'[sHrm].[pEmployeeGenerateReport]';


GO
PRINT N'Refreshing Procedure [sStudent].[pStudentCustomSearchGet]...';


GO
EXECUTE sp_refreshsqlmodule N'[sStudent].[pStudentCustomSearchGet]';


GO
PRINT N'Refreshing Procedure [sStudent].[pStudentGenerateReport]...';


GO
EXECUTE sp_refreshsqlmodule N'[sStudent].[pStudentGenerateReport]';


GO
PRINT N'Update complete.';


GO


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



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

PRINT N'Altering Table [sIp].[tStoreLocationMaster]...';


GO
ALTER TABLE [sIp].[tStoreLocationMaster]
    ADD [DepositHeadId]        INT      NULL,
        [DepositExpenseTypeId] INT      NULL,
        [ReportId]             SMALLINT NULL;


GO
PRINT N'Altering Table [sProcurement].[tStockIssue]...';


GO
ALTER TABLE [sProcurement].[tStockIssue]
    ADD [PayTypeId]     TINYINT        NULL,
        [ReceiptNumber] INT            NULL,
        [BankName]      NVARCHAR (200) NULL,
        [ChequeNo]      NVARCHAR (40)  NULL,
        [ChequeDate]    DATE           NULL;


GO
PRINT N'Creating Table [sAlert].[tAlertQueueLog]...';


GO
CREATE TABLE [sAlert].[tAlertQueueLog] (
    [AutoId]          BIGINT         IDENTITY (1, 1) NOT NULL,
    [MessageDate]     DATETIME       NOT NULL,
    [QueueMessage]    NVARCHAR (MAX) NOT NULL,
    [EventId]         INT            NOT NULL,
    [AlertModeId]     TINYINT        NOT NULL,
    [OrgId]           SMALLINT       NOT NULL,
    [CreatedUserId]   BIGINT         NOT NULL,
    [CreatedDateTime] DATETIME       NOT NULL
);


GO
PRINT N'Creating Table [sProcurement].[tStockKitDetail]...';


GO
CREATE TABLE [sProcurement].[tStockKitDetail] (
    [StockKitId]  INT             NOT NULL,
    [StockItemId] INT             NOT NULL,
    [Quantity]    DECIMAL (12, 2) NOT NULL
);


GO
PRINT N'Creating Table [sProcurement].[tStockKitIssueDetail]...';


GO
CREATE TABLE [sProcurement].[tStockKitIssueDetail] (
    [StockIssueId] BIGINT NOT NULL,
    [StockKitId]   INT    NOT NULL
);


GO
PRINT N'Creating Table [sProcurement].[tStockKitMaster]...';


GO
CREATE TABLE [sProcurement].[tStockKitMaster] (
    [OrgGroupId]      SMALLINT       NOT NULL,
    [Id]              INT            NOT NULL,
    [Number]          INT            NOT NULL,
    [Code]            NVARCHAR (20)  NOT NULL,
    [Title]           NVARCHAR (100) NOT NULL,
    [CreatedUserId]   BIGINT         NOT NULL,
    [CreatedDateTime] DATETIME       NOT NULL,
    [OrderIndex]      SMALLINT       NOT NULL,
    [IsObsolete]      BIT            NOT NULL,
    [UpdatedUserId]   BIGINT         NULL,
    [UpdatedDateTime] DATETIME       NULL,
    [StoreLocationId] INT            NOT NULL
);


GO


GO
ALTER PROCEDURE [sIp].[pStoreLocationMasterModify]
	@rId [int],
	@rTitle [nvarchar](100),
	@rIsObsolete [bit],
	@rUpdatedUserId [bigint],
	@rCode [nvarchar](100),	
	@rOrgGroupId int,
	@rIsBatchwiseTracking bit = 0,
	@rDepositHeadId int=0,
	@rDepositExpenseTypeId int=0,
	@rReportId smallint=0


WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
IF NOT EXISTS (SELECT 1 FROM sIP.tStoreLocationMaster WHERE UPPER(Title) = UPPER(@rTitle) AND Id  <> @rId AND OrgGroupId = @rOrgGroupId)
BEGIN

	 UPDATE sIP.tStoreLocationMaster
		SET 
			Title = @rTitle,
			IsObsolete = @rIsObsolete,
			UpdatedUserId = @rUpdatedUserId,
			UpdatedDateTime = sCommon.fGetDate(),
		    Code = @rCode,
		    IsBatchwiseTracking = @rIsBatchwiseTracking,
			DepositHeadId=@rDepositHeadId,
			DepositExpenseTypeId=@rDepositExpenseTypeId,
			ReportId=@rReportId
			
	  WHERE Id = @rId AND OrgGroupId = @rOrgGroupId
	  
	  
SELECT 1 AS RESULT
END

ELSE

 BEGIN
	 SELECT -100 AS RESULT
 END
 
END
GO
PRINT N'Altering Procedure [sIp].[pStoreLocationMasterAdd]...';


GO
ALTER PROCEDURE [sIp].[pStoreLocationMasterAdd]
	@rTitle [nvarchar](100),
	@rCreatedUserId [bigint],
	@rIsObsolete [bit],
	@rCode [nvarchar](100),
	@rOrgGroupId int,
	@rIsBatchwiseTracking bit = 0,
	@rDepositHeadId int=0,
	@rDepositExpenseTypeId int=0,
	@rReportId smallint=0
 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN

IF NOT EXISTS (SELECT 1 FROM sIp.tStoreLocationMaster WHERE UPPER(Title) = UPPER(@rTitle)  AND OrgGroupId = @rOrgGroupId )


BEGIN

	DECLARE @StockItemId INT
	DECLARE @lCount INT 
	DECLARE @rStockBatchId INT
	DECLARE @lNextNumber INT
	--EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sIp.tStoreLocationMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
	EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sIp.tStoreLocationMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
	

	INSERT INTO sIp.tStoreLocationMaster
		(
			Id,
			Title,
			CreatedUserId,
			CreatedDateTime,
			IsObsolete,
			UpdatedUserId,
			UpdatedDateTime,
			Code,
			LocationId, 
			OrgGroupId,
		 	IsBatchwiseTracking,
			DepositHeadId,
			DepositExpenseTypeId,
			ReportId
		)
	VALUES
		(
			@lNextNumber,
			@rTitle,
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rIsObsolete,
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rCode,
			@lNextNumber,
			@rOrgGroupId,
			@rIsBatchwiseTracking,
			@rDepositHeadId,
			@rDepositExpenseTypeId,
			@rReportId
			 
		)
		
	  INSERT INTO sSecurity.tUserAccess
           (
           SourceTypeId
           ,SourceId
           ,[UserId]
           
           )
		   SELECT 
		   1014
		   ,@lNextNumber
		   ,@rCreatedUserId		
		
--CREATE TABLE #tmpStockItemMaster
--(
--	Id bigint identity,
--	StockItemId int
--)	 
		 
--INSERT INTO #tmpStockItemMaster
--SELECT Id FROM sIP.tStockItemMaster WHERE LocationId = @rLocationId

--SELECT @lCount =  COUNT(Id) FROM #tmpStockItemMaster

--WHILE @lCount > 0 
-- 	BEGIN

-- 		SELECT  @StockItemId = StockItemId 
-- 	   FROM #tmpStockItemMaster WHERE Id = @lCount	
	
-- 	EXECUTE sProcurement.pStockBatchAdd @rOrgGroupId,@lNextNumber,@StockItemId,null,null,0,@rCreatedUserId ,  @rStockBatchId
--		SET @lCount = @lCount - 1
--	END	
 	
	--EXECUTE	sIp.pStockItemPurchaseUomAdd @rOrgId,@lNextNumber,@rIssueStockUomId,1,0,@rCreatedUserId	
	----EXEC [sIp].[pItemStandardPriceLogAdd] @rOrgId,@lNextNumber, @rStandardPrice, @rCreatedUserId
 --   SELECT @lNextNumber AS RESULT
    
    
 --END
		
	SELECT 1 AS RESULT
END
ELSE
 BEGIN
 SELECT -100 AS RESULT
 END
END
GO
PRINT N'Altering Procedure [sIp].[pStoreLocationMasterGet]...';


GO
ALTER PROCEDURE [sIp].[pStoreLocationMasterGet]
	@rId [int] = 0,
	@rTitle [nvarchar](20) = '',
	@rCode [nvarchar](100) = '',
	@rLocationId [int] = 0,
	@rOrgGroupId int,
	@rIsWildCardSearch [bit] = 1

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN

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


	 SELECT SLM.Id,
			SLM.Title,
			SLM.CreatedUserId,
			SLM.CreatedDateTime,
			SLM.IsObsolete,
			SLM.UpdatedUserId,
			SLM.UpdatedDateTime,
			SLM.Code,		
			SLM.OrgGroupId,
			OM.Title AS OrgGroupName,
			SLM.Title AS StoreLocationName,
			ISNULL(SLM.IsBatchwiseTracking,0) AS IsBatchwiseTracking,
			Isnull(SLM.DepositHeadId,0) as DepositHeadId,
			Isnull(SLM.DepositExpenseTypeId,0) as DepositExpenseTypeId,
			Isnull(SLM.ReportId,0) as ReportId

	   FROM sIp.tStoreLocationMaster SLM 	   
	   INNER JOIN sSetup.tOrgGroupMaster OM ON OM.Id=SLM.OrgGroupId
	  WHERE ((SLM.Id = @rId) OR (@rId = 0))
	   AND ((SLM.Title LIKE @rTitle) OR (ISNULL(@rTitle, '') = ''))
	   AND ((SLM.Code LIKE @rCode) OR (ISNULL(@rCode, '') = ''))	  
	   AND  (SLM.OrgGroupId = @rOrgGroupId)  
	   --AND SLM.IsObsolete = 0
END



/****** Object:  StoredProcedure [sExamination].[pIssueReturnDataGet]    Script Date: 06/15/2013 16:42:58 ******/
SET ANSI_NULLS ON
GO
PRINT N'Altering Procedure [sProcurement].[pStockIssueStudentAdd_New]...';


GO
/******************************************************************************
	Purpose          : To add records to sProcurement.tStockIssue table
	Created date     : 09 Jan 2012
	Author           : System Generated
	Copyright©       : Copyright © Sapphire Software
	Last Change Desc : Added @rStockIssueRequestId field
	Test script      : EXECUTE sProcurement.pStockIssueAdd @rNumber = '', @rStockIssueRequestId = 0, @rIssuedByName = '', @rToOrganizationDepartmentId = 0, @rFromStoreLocationId = 0, @rRemark = '', @rCreatedUserId = 0, @rDetail = ''
*******************************************************************************/
ALTER PROCEDURE [sProcurement].[pStockIssueStudentAdd_New]
(
	@rOrgGroupId [int],
	@rNumber						nvarchar(20) = '',
	@rStockIssueRequestId			int=0, 
	@rIssuedByName					nvarchar(100) = '',
	@rToOrganizationDepartmentId	int,
	@rFromStoreLocationId			int,
	@rFirstAidId					int,
	@rCreatedUserId					bigint,
	@rDetail						Nvarchar(Max)='',
	@rOrgId int,
	@rLocationId int,
	@rIssuedToName nvarchar(50)='',
	@rIssueToSourceTypeId int,
	@rIssueToSourceId bigint,
	@rIssueDate datetime = null,
    @rCreatedOnDate datetime = null ,
	@rPayTypeId tinyint=null,
	@rReceiptNumber int=null,
	@rBankName  nvarchar(200)=null,
	@rChequeNo  nvarchar(40)=null,
	@rChequeDate Date=null
)
AS

SET NOCOUNT ON

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

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

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

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



If @rFirstAidId < 0 
SET @rFirstAidId =  NULL

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


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

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

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

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


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


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


GO

ALTER PROCEDURE [sProcurement].[pStockIssSearch_Get]
	@rOrgGroupId int,
	@rNumber [nvarchar](20) = '',
	@rFromDate date='',
	@rToDate date='',
	@rStoreLocationId int=0,
	@rAcademicId bigint=0,
	@rId int=0,
	@rPayTypeId int=0
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN	  
SELECT		
SI.Id AS  StockId,SI.Number,isnull(SI.StockIssueRequestId,0) as StockIssueRequestId,
SI.IssuedByName,SI.CreatedDateTime AS IssuedDate,
IssueToSourceId

FROM sProcurement.tStockIssue SI
 
 
WHERE ((SI.Number like '%' + @rNumber + '%') OR (@rNumber = '*'))
AND  SI.OrgGroupId = @rOrgGroupId
AND (isnull(PayTypeId,14)=@rPayTypeId OR isnull(@rPayTypeId,0)=0)
AND (( Convert(Date,SI.CreatedDateTime)>= @rFromDate ) OR (ISNULL(@rFromDate,'')=''))
AND (( Convert(Date,SI.CreatedDateTime)<= @rToDate ) OR (ISNULL(@rToDate,'')=''))
AND SI.FromStoreLocationId=@rStoreLocationId 
AND ((SI.IssueToSourceId =@rAcademicId) OR (@rAcademicId=0))
AND SI.IssueToSourceTypeId = 2001
Order by SI.CreatedDateTime desc
END
GO
PRINT N'Altering Procedure [sAlert].[pAbsentStudentGet]...';


GO
ALTER PROCEDURE [sAlert].[pAbsentStudentGet]

	 	 @rBatchId int,
	 	 @rClassId int,
	 	 @rDivisionId int,
	 	 @rOrgId int,
	 	 @rTemplate nvarchar(max),
	 	 @rAttendanceTypeId tinyint,
	 	 @rSubjectId int,
	 	 @rFromDate date,
	 	 @rToDate date,
	 	 @rIsPresent bit,
	 	 @rMailSubject nvarchar(500)=''

	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

--SET @rToDate = dateadd(d,1,@rToDate)

	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,
			CASE WHEN @rIsPresent=0 THEN
			replace (replace (replace (						--add replace
			replace(replace(replace(@rTemplate,'[Name]',SC.Name),
			'[Class]',SC.ClassName),
			'[Division]',SC.DivisionName),
			'[AbsentDates]',Convert(Varchar,SR.AttendanceDate,105)),	--add convert
			'[AbsentReason]',ISNULL(AR.Title,'')),
			'[RollNo]',ISNULL(SC.RollNo,0))								--add
			ELSE
			replace(replace(											--add replace
			replace(replace(replace(@rTemplate,'[Name]',SC.Name),
			'[Class]',SC.ClassName),
			'[Division]',SC.DivisionName),
			'[PresentDates]',Convert(Varchar,SR.AttendanceDate,105)),	--add Convert
			'[RollNo]',ISNULL(SC.RollNo,0))								--add
			END
			 AS MsgText,
			@rMailSubject AS Subject,
			SC.AcademicId AS SourceId,
			2001 AS SourceTypeId,
			SC.OrgId,
			SC.OrgGroupId,
			SC.AcademicId AS ReceiverSourceId,
			2001 AS ReceiverSourceTypeId,
			SC.ClassName AS Class,
			SC.DivisionName AS Division,
			SR.AttendanceDate AS AbsentDates,
			ISNULL(AR.Title,'') AS AbsentReason,
			SR.AttendanceDate AS PresentDates,
			SC.WhatsAppContactNo

	From
		sStudent.vStudentCommunication SC
	INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=SC.AcademicId
	LEFT JOIN sAttendance.tAbsentReasonMaster AR ON SR.AbsentReasonId = AR.Id

	WHERE
			((SC.ClassId=@rClassId) OR (@rClassId=0))
		AND ((SC.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		AND (SC.OrgId=@rOrgId)
		AND (SC.BatchId=@rBatchId)
		AND (SC.StatusId=1)
		AND ((SR.AttendanceTypeId=@rAttendanceTypeId) OR (@rAttendanceTypeId=0))
			AND ((SR.SubjectId=@rSubjectId) OR (@rSubjectId=0))
			AND ((SR.AttendanceDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
			AND ((SR.AttendanceDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
			AND (SR.IsPresent = @rIsPresent)
		AND	SC.AcademicId NOT IN (SELECT AcademicId FROM sAttendance.tStudentLeaveRequest WHERE LeaveFromDate = @rFromDate AND LeaveToDate=@rToDate)
		AND SC.IsBlockAttendanceAlert=0 AND SC.IsBlockAllAlert=0
   ORDER BY SC.ClassOrderIndex,SC.DivisionOrderIndex,SC.Rollno
END
GO
PRINT N'Altering Procedure [sAssessment].[pMarkEntryConvertForDifferentSubject]...';


GO

ALTER PROCEDURE [sAssessment].[pMarkEntryConvertForDifferentSubject]  
	 	
	 
	@rClassId int, 
	@rDivisionId int,
	@rSourceExamDetailIdList nvarchar(500),
	@rOrgId smallint,
	@rBatchId int,
	@rDestinationExamDetailId  int=0,
	@rBasedOnPresent int = 0 	
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

DECLARE @loDoc INT,@lIsMarksInDecimal bit
Declare @lDecimalFormat nvarchar(10)
select @lDecimalFormat = DecimalFormat from sAssessment.tExamMaster where Id =(Select ExamId  from sAssessment.tExamDetail WHere Id = @rDestinationExamDetailId)
select @lIsMarksInDecimal = IsMarksInDecimal from sAssessment.tExamMaster where Id= (Select ExamId  from sAssessment.tExamDetail WHere Id = @rDestinationExamDetailId)
BEGIN
	 
	 BEGIN	
	 
	 
	--select @lDecimalFormat = DecimalFormat from sAssessment.tExamMaster where Id =@rExamId;
	 
	CREATE Table #MarkEntrySubjectWise_CTE ( AcademicId  bigint,  SourceObtain decimal(5,2),SourceMaximum decimal(5,2),IsPresent int)
 
-- Define the CTE query.
	INSERT INTO #MarkEntrySubjectWise_CTE 
	(
		AcademicId,
	 
		SourceObtain,
		SourceMaximum,
		IsPresent
		--ClassSubjectId
	)
	
   Select 			
		
		R.AcademicId,	
		 	 
		SUM(RD.Obtain)AS SourceObtain,
		SUM(ED.Maximum) AS SourceMaximum,
		(CASE WHEN @rBasedOnPresent = 0 THEN MIN(CONVERT(INT,RD.IsPresent)) ELSE MAX(CONVERT(INT,RD.IsPresent)) END)AS IsPresent
		--ED.ClassSubjectId		
	 
	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.tExamMaster EM ON EM.Id = R.ExamId
			INNER JOIN sAssessment.tExamDetail ED ON RD.ExamDetailId=ED.Id AND ED.ExamId = EM.Id			 			 			  			 			 
			 Where
			 A.ClassId = @rClassId AND A.BatchId=@rbatchId 
			 AND ED.Id IN (SELECT  cast(item as int) AS ExamDetailID FROM  sCommon.fnsplit( REPLACE(REPLACE(@rSourceExamDetailIdList,'(',''),')','') ,','))  
			Group By R.AcademicId 
		 
		--Select * from #MarkEntrySubjectWise_CTE 


	DECLARE @lNextNumber BIGINT 
	DECLARE @lResultId BIGINT
	DECLARE @lCount INT
	DECLARE @lMarkInDecimal bit
	Declare @lExamId BigInt
	DECLARE @Query nvarchar(max)
	DECLARE @lMaxId Bigint
	Declare @lHigh1 decimal(5,2),@lHigh2 decimal(5,2)
	Declare @lCountMark int,@lSum_Highest decimal(5,2),@lSum decimal(5,2)
	Declare @lMaximum decimal(5,2)
	Select @lMaximum = Maximum from sAssessment.tExamDetail where Id = @rDestinationExamDetailId

	DECLARE @lDestinationExamId bigint
	SELECT @lDestinationExamId = ExamId FROM sAssessment.tExamDetail WHERE Id = @rDestinationExamDetailId

	IF NOT EXISTS (SELECT 1 FROM sAssessment.tResult R INNER JOIN sStudent.tAcademic A ON A.Id = R.AcademicId AND A.BatchId=@rBatchId
				AND R.ExamId=@lDestinationExamId AND A.ClassId=@rClassId AND (A.DivisionId=@rDivisionId OR @rDivisionId=0))		
	BEGIN
		 
		EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sAssessment.tResult', 0, 1, 1,@outNextNumber = @lNextNumber output	
		
		INSERT INTO sAssessment.tResult (Id,ExamId,AcademicId,TotalMarks,TotalObtain,ResultStatus,ResultGrade,ResultGradePoint,
		RankNumber,Percentage,Percentile,ResultRemark,OtherRemark1,UpdatedUserId,UpdatedDateTime) 
		
		SELECT @lNextNumber + ROW_NUMBER() OVER(ORDER BY A.AcademicId) AS Id,@lDestinationExamId,A.AcademicId,0,0,'','',0,0,0,0,'','',1,sCommon.fGetDate()
		From sStudent.vStudentAcademic A
		Where A.ClassId=@rClassId AND (A.DivisionId=@rDivisionId OR @rDivisionId=0) AND A.StatusId=1 AND A.BatchId=@rBatchId
		
		SELECT @lCount = COUNT(1) FROM sStudent.vStudentAcademic WHERE ClassId=@rClassId AND (DivisionId=@rDivisionId OR @rDivisionId =0) AND BatchId=@rBatchId
		SET @lNextNumber  = @lCount + @lNextNumber 
		
		EXECUTE sCommon.pTableRowIdModify @rOrgId, @rTableTitle = 'sAssessment.tResult', @rCurrentNumber = @lNextNumber
			
	END

	IF EXISTS (SELECT 1 FROM sAssessment.tResultDetail RD 
    INNER JOIN sAssessment.tResult R ON R.Id=RD.ResultId AND R.ExamId=@lDestinationExamId
    INNER JOIN sStudent.vStudentAcademic A ON A.AcademicId=R.AcademicId AND A.ClassId = @rClassId AND A.BatchId=@rBatchId
    AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId = 0))
	AND (RD.ExamDetailId = @rDestinationExamDetailId OR @rDestinationExamDetailId = 0)
    )
    BEGIN	
	
	  UPDATE RD SET RD.OBTAIN  =
								(CASE WHEN  (@lIsMarksInDecimal = 1 AND @lDecimalFormat='0.0') THEN
									Round((MC.SourceObtain * ED.Maximum)/MC.SourceMaximum,1) 
								WHEN ( @lIsMarksInDecimal = 1 AND @lDecimalFormat='0.00' ) THEN
									CONVERT(Decimal(5,2),(MC.SourceObtain * ED.Maximum)/MC.SourceMaximum) 
								ELSE			  
									ROUND((MC.SourceObtain * ED.Maximum)/MC.SourceMaximum,0)
								END),RD.IsPresent=MC.IsPresent
	  
	  FROM	  
			sAssessment.tResultDetail RD 
			INNER JOIN sAssessment.tResult R ON RD.ResultId = R.Id 
			INNER JOIN sAssessment.tExamDetail  ED ON RD.ExamDetailId = ED.Id
			INNER JOIN #MarkEntrySubjectWise_CTE MC ON R.AcademicId = MC.AcademicId 
			AND RD.ExamDetailId = @rDestinationExamDetailId 
				
	Select 11 AS Result
	END
	ELSE
	BEGIN

		EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sAssessment.tResultDetail', 0, 1, 1,@outNextNumber = @lNextNumber output

			INSERT INTO sAssessment.tResultDetail
							 (Id,ResultId,ExamDetailId,IsPresent,Obtain) 
						SELECT
							@lNextNumber  + ROW_number()OVER(Order by R.AcademicId) AS Id,
							R.Id as ResultId,
							@rDestinationExamDetailId AS ExamDetailId,
							--ED1.Id AS ExamDetailId,
							A.IsPresent AS IsPresent,
							--A.Obtain 
							((ED1.Maximum * A.SourceObtain) / A.SourceMaximum) AS Obtain
							from 
					  	 sAssessment.tResult R 
					  	INNER JOIN sAssessment.tExamMaster EM ON EM.Id = R.ExamId
					    INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId = R.AcademicId  
						INNER JOIN sAssessment.tExamDetail ED1 ON ED1.ExamId = EM.Id 
						INNER JOIN( 
									SELECT   AcademicId,SourceObtain,SourceMaximum,IsPresent
									FROM #MarkEntrySubjectWise_CTE 
									--group by   AcademicId,
									----ClassSubjectId,
									--SourceObtain,SourceMaximum,IsPresent
								)A   ON R.AcademicId= A.AcademicId  
								--AND A.ClassSubjectId = ED1.ClassSubjectId						
				 		 
						 WHERE SA.ClassId = @rClassId AND  ((SA.DIVISIONID= @rDivisionId ) OR (@rDivisionId = 0))
						AND R.ExamId = @lDestinationExamId AND ED1.Id = @rDestinationExamDetailId
									
		SELECT @lMaxId=MAx(RD.Id)   FROM sAssessment.tResultDetail RD
		INNER JOIN sAssessment.tResult R On R.Id = RD.ResultId
		INNER JOIN sAssessment.tExamMaster EM ON EM.Id =R.ExamId
		INNER JOIN sSetup.tBatchMaster BM ON BM.ID = EM.BatchId 
		WHERE BM.OrgId = @rOrgId
		  
		EXECUTE sCommon.pTableRowIdModify @rOrgId, @rTableTitle = 'sAssessment.tResultDetail', @rCurrentNumber = @lMaxId 
		 Select 1 As Result
	END
END

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


GO

ALTER PROCEDURE [sAssessment].[pMarkEntryConvertForSubject]  
	 	
	 
	@rClassId int, 
	@rDivisionId int,
	@rSourceExamDetailIdList nvarchar(500),
	@rOrgId smallint,
	@rBatchId int,
	@rDestinationExamDetailId  int=0 ,
	@rBasedOnPresent int = 0 	

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

DECLARE @loDoc INT,@lIsMarksInDecimal bit
Declare @lDecimalFormat nvarchar(10)
select @lDecimalFormat = DecimalFormat from sAssessment.tExamMaster where Id =(Select ExamId  from sAssessment.tExamDetail WHere Id = @rDestinationExamDetailId)
select @lIsMarksInDecimal = IsMarksInDecimal from sAssessment.tExamMaster where Id= (Select ExamId  from sAssessment.tExamDetail WHere Id = @rDestinationExamDetailId)
BEGIN
	 
	 BEGIN	
	 
	 
	--select @lDecimalFormat = DecimalFormat from sAssessment.tExamMaster where Id =@rExamId;
	 
	CREATE Table #MarkEntrySubjectWise_CTE ( AcademicId  bigint, ClassSubjectId int,SourceObtain decimal(5,2),SourceMaximum decimal(5,2),IsPresent int)
 
-- Define the CTE query.
	INSERT INTO #MarkEntrySubjectWise_CTE 
	(
		AcademicId,
		ClassSubjectId,
		SourceObtain,
		SourceMaximum,
		IsPresent
	)
	
   Select 			
		
		R.AcademicId,	
		ED.ClassSubjectId,	 
		SUM(RD.Obtain)AS SourceObtain,
		SUM(ED.Maximum) AS SourceMaximum,
		(CASE WHEN @rBasedOnPresent = 0 THEN MIN(CONVERT(INT,RD.IsPresent)) ELSE MAX(CONVERT(INT,RD.IsPresent)) END)AS IsPresent
	 
	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.tExamMaster EM ON EM.Id = R.ExamId
			INNER JOIN sAssessment.tExamDetail ED ON RD.ExamDetailId=ED.Id AND ED.ExamId = EM.Id			 			 			  			 			 
			 Where
			 A.ClassId = @rClassId AND A.BatchId=@rbatchId 
			 AND ED.Id IN (SELECT  cast(item as int) AS ExamDetailID FROM  sCommon.fnsplit( REPLACE(REPLACE(@rSourceExamDetailIdList,'(',''),')','') ,','))  
			Group By R.AcademicId,ED.ClassSubjectId 
		 
		--Select * from #MarkEntrySubjectWise_CTE 
	--Select ExamId  from sAssessment.tExamDetail WHere Id = @rDestinationExamDetailId

	 DECLARE @lNextNumber BIGINT 
	 DECLARE @lResultId BIGINT
	 DECLARE @lCount INT
	 DECLARE @lMarkInDecimal bit
	 Declare @lExamId BigInt
	 DECLARE @Query nvarchar(max)
	 DECLARE @lMaxId Bigint
	 Declare @lHigh1 decimal(5,2),@lHigh2 decimal(5,2)
	 Declare @lCountMark int,@lSum_Highest decimal(5,2),@lSum decimal(5,2)
	 Declare @lMaximum decimal(5,2)
	 Select @lMaximum = Maximum from sAssessment.tExamDetail where Id = @rDestinationExamDetailId

	 DECLARE @lDestinationExamId bigint
	 SELECT @lDestinationExamId = ExamId FROM sAssessment.tExamDetail WHERE Id = @rDestinationExamDetailId

	  IF NOT EXISTS (SELECT 1 FROM sAssessment.tResult R INNER JOIN sStudent.tAcademic A ON A.Id = R.AcademicId AND A.BatchId=@rBatchId
				AND R.ExamId=@lDestinationExamId AND A.ClassId=@rClassId AND (A.DivisionId=@rDivisionId OR @rDivisionId=0))		
	BEGIN
		 
		EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sAssessment.tResult', 0, 1, 1,@outNextNumber = @lNextNumber output	
		
		INSERT INTO sAssessment.tResult (Id,ExamId,AcademicId,TotalMarks,TotalObtain,ResultStatus,ResultGrade,ResultGradePoint,
		RankNumber,Percentage,Percentile,ResultRemark,OtherRemark1,UpdatedUserId,UpdatedDateTime) 
		
		SELECT @lNextNumber + ROW_NUMBER() OVER(ORDER BY A.AcademicId) AS Id,@lDestinationExamId,A.AcademicId,0,0,'','',0,0,0,0,'','',1,sCommon.fGetDate()
		From sStudent.vStudentAcademic A
		Where A.ClassId=@rClassId AND (A.DivisionId=@rDivisionId OR @rDivisionId=0) AND A.StatusId=1 AND A.BatchId=@rBatchId
		
		SELECT @lCount = COUNT(1) FROM sStudent.vStudentAcademic WHERE ClassId=@rClassId AND (DivisionId=@rDivisionId OR @rDivisionId =0) AND BatchId=@rBatchId
		SET @lNextNumber  = @lCount + @lNextNumber 
		
		EXECUTE sCommon.pTableRowIdModify @rOrgId, @rTableTitle = 'sAssessment.tResult', @rCurrentNumber = @lNextNumber
			
	END

	IF EXISTS (SELECT 1 FROM sAssessment.tResultDetail RD 
    INNER JOIN sAssessment.tResult R ON R.Id=RD.ResultId AND R.ExamId=@lDestinationExamId
    INNER JOIN sStudent.vStudentAcademic A ON A.AcademicId=R.AcademicId AND A.ClassId = @rClassId AND A.BatchId=@rBatchId
    AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId = 0))
	AND (RD.ExamDetailId = @rDestinationExamDetailId OR @rDestinationExamDetailId = 0)
    )
    BEGIN
	  UPDATE RD SET RD.OBTAIN  =
								(CASE WHEN  (@lIsMarksInDecimal = 1 AND @lDecimalFormat='0.0') THEN
									Round((MC.SourceObtain * ED.Maximum)/MC.SourceMaximum,1) 
								WHEN ( @lIsMarksInDecimal = 1 AND @lDecimalFormat='0.00' ) THEN
									CONVERT(Decimal(5,2),(MC.SourceObtain * ED.Maximum)/MC.SourceMaximum) 
								ELSE			  
									ROUND((MC.SourceObtain * ED.Maximum)/MC.SourceMaximum,0)
								END),RD.IsPresent=MC.IsPresent
	  
	   --Convert(Decimal(5,2),(MC.SourceObtain * ED.Maximum)/MC.SourceMaximum)
	  FROM	  
			sAssessment.tResultDetail RD 
			INNER JOIN sAssessment.tResult R ON RD.ResultId = R.Id 
			INNER JOIN sAssessment.tExamDetail  ED ON RD.ExamDetailId = ED.Id
			INNER JOIN #MarkEntrySubjectWise_CTE MC ON R.AcademicId = MC.AcademicId AND ED.ClassSubjectId = MC.ClassSubjectId
			AND RD.ExamDetailId = @rDestinationExamDetailId 
	 
	
	Select 11 AS Result
   END
    ELSE
	BEGIN
		EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sAssessment.tResultDetail', 0, 1, 1,@outNextNumber = @lNextNumber output
		
		INSERT INTO sAssessment.tResultDetail
							 (Id,ResultId,ExamDetailId,IsPresent,Obtain) 
						SELECT  
							@lNextNumber  + ROW_number()OVER(Order by R.Id) AS Id,
							 
							R.Id as ResultId,
							@rDestinationExamDetailId AS ExamDetailId,
							A.IsPresent AS IsPresent,
							--A.Obtain 
							((ED1.maximum * A.Obtain) / A.Maximum) AS Obtain
							from 
					  	 sAssessment.tResult R 
					  	INNER JOIN sAssessment.tExamMaster EM ON EM.Id = R.ExamId
					    INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId = R.AcademicId  
						INNER JOIN sAssessment.tExamDetail ED1 ON ED1.ExamId = EM.Id 
						INNER JOIN( 
									SELECT   AcademicId,ClassSubjectId,SourceObtain AS Obtain,SourceMaximum AS Maximum,IsPresent
									FROM #MarkEntrySubjectWise_CTE 
									--GROUP BY  AcademicId,ClassSubjectId,SourceObtain,SourceMaximum,IsPresent
								)A   ON R.AcademicId= A.AcademicId  AND A.ClassSubjectId = ED1.ClassSubjectId						
				 		 
						 WHERE SA.ClassId = @rClassId AND  ((SA.DIVISIONID= @rDivisionId ) OR (@rDivisionId = 0))
						 AND R.ExamId = @lDestinationExamId AND ED1.Id = @rDestinationExamDetailId
									
		SELECT @lMaxId=MAX(RD.Id)   FROM sAssessment.tResultDetail RD
		INNER JOIN sAssessment.tResult R On R.Id = RD.ResultId
		INNER JOIN sAssessment.tExamMaster EM ON EM.Id =R.ExamId
		INNER JOIN sSetup.tBatchMaster BM ON BM.ID = EM.BatchId 
		WHERE BM.OrgId = @rOrgId
		  
		EXECUTE sCommon.pTableRowIdModify @rOrgId, @rTableTitle = 'sAssessment.tResultDetail', @rCurrentNumber = @lMaxId 
		 Select 1 As Result
		 
   END

   DROP TABLE #MarkEntrySubjectWise_CTE
END

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


GO

ALTER PROCEDURE [sAssessment].[pRptExamAdmitcard]
	  
	  @rBatchId int,
	  @rClassId int,
	  @rDivisionId int,
	 -- @rExamId int=0,
	  @rExamSubGroupId int=0,
	  @rCode nvarchar(20),
	  @rFromRollNo int,
	  @rToRollNo int,
	  @rDepartmentId int,
	  @rSubjectId int=0,
	  @rStatusId int=0,
	  @rClassStatusId int=0
	  
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON 
BEGIN 	
	SELECT 		
	       	ESGM.Title AS ExamName,
	       	ISNULL(ED.DisplayOrder,0) as DisplayOrder,
	        ISNULL(ED.ExamDate,sCommon.fGetDate()) as ExamDate,
	        ISNULL(ED.ExamTime,'') as ExamTime,
	        V.SubjectName AS SubjectName,
	        CM.DisplayTitle+' / '+DM.DisplayTitle AS ClassDivision,
	         CM.DisplayTitle AS ClassName,
	         CM.Id As ClassId,
	         DM.Id AS DiVisionId,
	        V.ClassSubjectId AS ClassSubjectId,
	        SA.Name,
	        SA.RollNo,
	        SA.Code,
	        SF.FatherName,
	        So.DateOfBirth,
	        GM.Title AS Gender,
	        EM.Remark1,
	        EM.Remark2,
	        EM.Remark3,
	        SA.AcademicId,
	        SI.StudentPhoto,
	        SF.MotherName,
	        SR. ExamCenter,
	        SR.ExamSeatNo,
	        V.SubjectCode AS SubjectCode,
		
	         
		(CASE EM.IsDisplayImageHeader WHEN 1 THEN
			OI.CertificateHeaderA4 
			ELSE NULL END)AS  MarksheetHeaderA4 ,
			ISNULL(EM.IsDisplayImageHeader,0) AS IsImageHeader,
			EM.IsOnPrePrinted ,
	        --EM.Id As ExamId,
			EM.IsDisplayPhoto,
			SR.ExamBlock,
			EI.EmployeeSign,
			EM.TeacherSignCaption,
			EM.PrincipalSignCaption,
			EM.ParentSignCaption,
			ISNULL(EM.DisplayTitle,'') AS DisplayTitle ,
			ISNULL(ED.ExamTopic,'') AS ExamTopic,
			ISNULL(ED.ExamLanguage,'') AS ExamLanguage,
			ISNULL(SA.OrganizationName,'') AS OrganizationName,
			ISNULL(SA.SUId,'') AS SUId ,
			EM.IsDisplayPrincipalSign AS IsDisplayPrincipalSign,
			ISNULL(SO.UIDNumber,'') AS UId ,
			CSM.Title As CasteCategory ,
		    ISNULL(SO.AdhaarNumber,'') AS AdhaarNumber,
			ISNULL(SO.FamilySubCast,'') AS FamilySubCast

			FROM
			sStudent.vStudentAcademic SA 
			INNER JOIN sSetup.tClassMaster CM ON SA.ClassId=CM.Id 
			INNER JOIN sSetup.tDivisionMaster DM ON DM.ClassId=CM.Id AND SA.DivisionId=DM.Id
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id  ANd Em.BatchId=SA.BatchId 
			INNER JOIN sAssessment.tExamSubGroupMaster	ESGM ON ESGM.Id = EM.ExamSubGroupId
			INNER JOIN sAssessment.tExamGroupMaster EGM ON EGM.Id=ESGM.ExamGroupId
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			LEFT JOIN sSetup.vClassSubject V ON V.ClassSubjectId = Ed.ClassSubjectId  
			LEFT JOIN sAssessment.tOptionalSubject OS on OS.AcademicId=SA.AcademicId and OS.ClassSubjectId=V.ClassSubjectId
			LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId=SA.StudentId  
			LEFT JOIN sStudent.tStudentOther SO ON So.StudentId=SA.StudentId  
			LEFT JOIN sCommon.tGenderMaster GM ON GM.Id=So.GenderId   
			LEFT JOIN  sStudent.tStudentImages SI ON SI.StudentId=SA.StudentId 
			LEFT JOIN sAssessment.tStudentRemark SR ON SR.ExamId=EM.Id AND SR.AcademicId=SA.AcademicId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=SA.OrgId
			LEFT JOIN sSetup.tOrgImages OI ON OI.Orgid = OM.Id
			LEFT JOIN sHrm.tEmployeeImages EI ON EI.EmployeeId = DM.InchargeEmployeeId
			LEFT JOIN sCommon.tCastCategoryMaster CSM ON CSM.Id=SO.CastCategoryId
	WHERE 
			SA.BatchId = @rBatchId 
		 AND (SA.ClassId=@rClassId OR @rClassId=0) 
		 AND (SA.DivisionId=@rDivisionId OR @rDivisionId=0)
		 AND ((SA.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
		 AND ((SA.RollNo <= @rToRollNo) OR (@rToRollNo=0))
		 AND ((ESGM.Id = @rExamSubGroupId) OR (@rExamSubGroupId = 0))	
	     AND ((SA.Code=@rCode) OR (@rCode=''))
	     AND (SA.DepartmentId=@rDepartmentId OR @rDepartmentId=0) 
	     AND (V.SubjectId=@rSubjectId OR @rSubjectId=0) 
	    AND ((V.IsOptional = 1 AND  isnull(OS.AcademicId,0) <> 0) OR (V.IsOptional = 0))
		AND ((SA.StatusId=@rStatusId) OR (@rStatusId = 0))
		AND (SA.ClassStatusId=@rClassStatusId OR @rClassStatusId=0)
	
	Order by ED.ExamDate
END
GO
PRINT N'Altering Procedure [sAudit].[pActivityLogGet]...';


GO


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

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


GO
 
ALTER PROCEDURE [sFee].[pApplicablePayTypeGet]
	   @rOrgGroupId int
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;

    -- Insert statements for procedure here
	SELECT  FPT.Id as PayTypeId,
			FPT.Title as PayType,
			CASE WHEN APT.PayTypeId Is Null THEN 'False' ELSE 'True' END AS IsObsolete
		
  FROM sFinanceCommon.tPayTypeMaster FPT
	LEFT JOIN sFee.tApplicablePayType APT ON APT.PayTypeId=FPT.Id AND OrgGroupId=@rOrgGroupId
	Where FPT.Id not in (12,13,14)
END
GO
PRINT N'Altering Procedure [sFee].[pFeeCollectionConsolidatedDashboardGet]...';


GO
ALTER PROCEDURE [sFee].[pFeeCollectionConsolidatedDashboardGet]

     @rOrgGroupId smallint=0,
     @rTypeId int=0,
     @rType nvarchar(20)='',
     @rCommonOrgGroupBatchId int=0,
	 @rFromDate date =null,
	 @rToDate date = null,
	 @rReceiptBookId int =0,
	 @rUserId bigint=0,
	 @rOrgId int =0,
	 @rCommonFeeId int =0
	 
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
--If @rFromDate= NULL Set @rFromDate = ''
--  If @rToDate =NULL Set @rToDate = ''
 DECLARE @cols NVARCHAR(MAX),@query  NVARCHAR(MAX),@cols1 NVARCHAR(MAX), @cols2 NVARCHAR(MAX); 
	---Fee Collection Wise  
			IF(@rTypeId=1)
				BEGIN
					SET @cols = STUFF((SELECT ',' +  QUOTENAME(PTM.Title )
					FROM sFinanceCommon.tPayTypeMaster PTM
					--INNER JOIN  sFee.tReceipt R  ON PTM.Id=R.PayTypeId
					--INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.SourceId 
					GROUP BY PTM.Title
					FOR XML PATH(''), TYPE
					).value('.', 'NVARCHAR(MAX)') 
					,1,1,'')

					SET @cols1 = STUFF((SELECT ', SUM(ISNULL(' + QUOTENAME(PTM.Title) + ', ''0'')) ' + QUOTENAME(PTM.Title) 
					FROM sFinanceCommon.tPayTypeMaster PTM
					--INNER JOIN  sFee.tReceipt R  ON PTM.Id=R.PayTypeId
					--INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.SourceId 
					GROUP BY PTM.Title
					FOR XML PATH(''), TYPE
					).value('.', 'NVARCHAR(MAX)') 
					,1,1,'')					

					SET @cols2 = STUFF((SELECT '+ SUM(ISNULL(' + QUOTENAME(PTM.Title) + ', ''0'')) ' 
					FROM sFinanceCommon.tPayTypeMaster PTM
					GROUP BY PTM.Title
					FOR XML PATH(''), TYPE
					).value('.', 'NVARCHAR(MAX)') 
					,1,1,'')	

					set @query = 'SELECT OrgGroupId,OrgGroupName,' + @cols2 + ' AS Total, ' + @cols1 + ' from 
					(
					SELECT  OMM.Id AS OrgGroupId ,OMM.Title AS OrgGroupName,SUM(R.ReceiptAmount) AS Total,PTM.Title AS PayTypeName, COALESCE(SUM(R.ReceiptAmount),0) AS ReceiptAmount FROM sFee.tReceipt R
					INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.SourceId 
					INNER JOIN  sFinanceCommon.tPayTypeMaster PTM  ON PTM.Id=R.PayTypeId
					INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SA.OrgId
					INNER JOIN sSetup.tOrgGroupMaster OMM ON OMM.Id = OM.OrgGroupId 
					INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=SA.OrgGroupBatchId
					INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
					INNER JOIN sSetup.tBatchMaster BM ON SA.BatchId = BM.Id
					WHERE  COGBM.Id='+CONVERT(nvarchar(20),@rCommonOrgGroupBatchId)+' AND R.SourceTypeId = 2001 
					AND((OMM.Id='+CONVERT(nvarchar(20),@rOrgGroupId)+') OR ('+CONVERT(nvarchar(20),@rOrgGroupId)+'=0))
					AND (( convert(DATE, R.ReceiptDate,102) >= '''+CONVERT(nvarchar(20),@rFromDate)+''') OR ('''+CONVERT(nvarchar(20),@rFromDate)+'''=''1900-01-01''))
					AND (( convert(DATE, R.ReceiptDate,102) <= '''+CONVERT(nvarchar(20),@rToDate)+''') OR ('''+CONVERT(nvarchar(20),@rToDate)+'''=''1900-01-01''))
					AND R.IsObsolete = 0
					And ISNULL(OMM.IsObsolete,0) = 0
					AND BM.IsInContext = 1 
					GROUP BY OMM.Title,OMM.Id,PTM.Title
					) x
					pivot 
					(
					Sum(ReceiptAmount) 
					for PayTypeName in (' + @cols + ')
					) p GROUP BY OrgGroupId,OrgGroupName  ORDER BY OrgGroupId'
					--print(@query)
					execute(@query)
				END
			ELSE IF( @rTypeId=11)
				BEGIN
					SET @cols = STUFF((SELECT ',' +  QUOTENAME(PTM.Title )
					FROM sFinanceCommon.tPayTypeMaster PTM
					--INNER JOIN  sFee.tReceipt R  ON PTM.Id=R.PayTypeId
					--INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.SourceId 
					GROUP BY PTM.Title
					FOR XML PATH(''), TYPE
					).value('.', 'NVARCHAR(MAX)') 
					,1,1,'')

					SET @cols1 = STUFF((SELECT ', SUM(ISNULL(' + QUOTENAME(PTM.Title) + ', ''0'')) ' + QUOTENAME(PTM.Title) 
					FROM sFinanceCommon.tPayTypeMaster PTM
					--INNER JOIN  sFee.tReceipt R  ON PTM.Id=R.PayTypeId
					--INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.SourceId 
					GROUP BY PTM.Title
					FOR XML PATH(''), TYPE
					).value('.', 'NVARCHAR(MAX)') 
					,1,1,'')

					SET @cols2 = STUFF((SELECT '+ SUM(ISNULL(' + QUOTENAME(PTM.Title) + ', ''0'')) ' 
					FROM sFinanceCommon.tPayTypeMaster PTM
					GROUP BY PTM.Title
					FOR XML PATH(''), TYPE
					).value('.', 'NVARCHAR(MAX)') 
					,1,1,'')

					set @query = 'SELECT ReceiptBookId,ReceiptBook,'+@cols2+' AS Total, ' + @cols1 + ' from 
					(
					SELECT RBM.Id AS ReceiptBookId,RBM.Title AS ReceiptBook,SUM(R.ReceiptAmount) AS Total,PTM.Title AS PayTypeName, COALESCE(SUM(R.ReceiptAmount),0) AS ReceiptAmount FROM sFee.tReceipt R
					INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.SourceId 
					INNER JOIN sFinanceCommon.tPayTypeMaster PTM ON PTM.Id=R.PayTypeId
					INNER JOIN sFee.tReceiptBookMaster RBM ON RBM.Id=R.ReceiptBookId
					INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SA.OrgId
					INNER JOIN sSetup.tOrgGroupMaster OMM ON OMM.Id = OM.OrgGroupId 
					INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=SA.OrgGroupBatchId
					INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
					INNER JOIN sSetup.tBatchMaster BM ON SA.BatchId = BM.Id
					WHERE  COGBM.Id='+CONVERT(nvarchar(20),@rCommonOrgGroupBatchId)+' AND R.SourceTypeId = 2001 
					AND((OMM.Id='+CONVERT(nvarchar(20),@rOrgGroupId)+') OR ('+CONVERT(nvarchar(20),@rOrgGroupId)+'=0))
					AND (( convert(DATE, R.ReceiptDate,102) >= '''+CONVERT(nvarchar(20),@rFromDate)+''') OR ('''+CONVERT(nvarchar(20),@rFromDate)+'''=''1900-01-01''))
					AND (( convert(DATE, R.ReceiptDate,102) <= '''+CONVERT(nvarchar(20),@rToDate)+''') OR ('''+CONVERT(nvarchar(20),@rToDate)+'''=''1900-01-01''))
					AND R.IsObsolete = 0
					And ISNULL(OMM.IsObsolete,0) = 0
					AND BM.IsInContext = 1
					GROUP BY RBM.Title,RBM.Id,PTM.Title
					) x
					pivot 
					(
					Sum(ReceiptAmount) 
					for PayTypeName in (' + @cols + ')
					) p GROUP BY ReceiptBookId,ReceiptBook ORDER BY ReceiptBookId'					
					--print(@query)
					execute(@query)
				 END
			ELSE IF( @rTypeId=12)
				BEGIN
						SET @cols = STUFF((SELECT ',' +  QUOTENAME(PTM.Title )
					FROM sFinanceCommon.tPayTypeMaster PTM
					--INNER JOIN  sFee.tReceipt R  ON PTM.Id=R.PayTypeId
					--INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.SourceId 
					GROUP BY PTM.Title
					FOR XML PATH(''), TYPE
					).value('.', 'NVARCHAR(MAX)') 
					,1,1,'')

					SET @cols1 = STUFF((SELECT ', SUM(ISNULL(' + QUOTENAME(PTM.Title) + ', ''0'')) ' + QUOTENAME(PTM.Title) 
					FROM sFinanceCommon.tPayTypeMaster PTM
					--INNER JOIN  sFee.tReceipt R  ON PTM.Id=R.PayTypeId
					--INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.SourceId 
					GROUP BY PTM.Title
					FOR XML PATH(''), TYPE
					).value('.', 'NVARCHAR(MAX)') 
					,1,1,'')

					SET @cols2 = STUFF((SELECT '+ SUM(ISNULL(' + QUOTENAME(PTM.Title) + ', ''0'')) '
					FROM sFinanceCommon.tPayTypeMaster PTM
					GROUP BY PTM.Title
					FOR XML PATH(''), TYPE
					).value('.', 'NVARCHAR(MAX)') 
					,1,1,'')

					set @query = 'SELECT UserId,UserName,SourceTypeId,' + @cols2 + ' AS Total, ' + @cols1 + ' from 
					(
					SELECT  U.Id As UserId,U.DisplayTitle AS UserName,ISNULL(U.SourceTypeId,0) AS SourceTypeId,SUM(R.ReceiptAmount) AS Total,PTM.Title AS PayTypeName, COALESCE(SUM(R.ReceiptAmount),0) AS ReceiptAmount FROM sFee.tReceipt R
					INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.SourceId 
					INNER JOIN sFinanceCommon.tPayTypeMaster PTM ON PTM.Id=R.PayTypeId
					INNER JOIN sFee.tReceiptBookMaster RBM ON RBM.Id=R.ReceiptBookId
					INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SA.OrgId
					INNER JOIN sSetup.tOrgGroupMaster OMM ON OMM.Id = OM.OrgGroupId 
					INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=SA.OrgGroupBatchId
					INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
					INNER JOIN sSetup.tBatchMaster BM ON SA.BatchId = BM.Id
					LEFT JOIN sSecurity.tUser U ON U.Id=R.CreatedUserId
					WHERE  COGBM.Id='+CONVERT(nvarchar(20),@rCommonOrgGroupBatchId)+' AND R.SourceTypeId = 2001 
					AND((OMM.Id='+CONVERT(nvarchar(20),@rOrgGroupId)+') OR ('+CONVERT(nvarchar(20),@rOrgGroupId)+'=0))
					AND (( convert(DATE, R.ReceiptDate,102) >= '''+CONVERT(nvarchar(20),@rFromDate)+''') OR ('''+CONVERT(nvarchar(20),@rFromDate)+'''=''1900-01-01''))
					AND (( convert(DATE, R.ReceiptDate,102) <= '''+CONVERT(nvarchar(20),@rToDate)+''') OR ('''+CONVERT(nvarchar(20),@rToDate)+'''=''1900-01-01''))
					AND BM.IsInContext = 1
					GROUP BY U.id,U.DisplayTitle,PTM.Title,U.SourceTypeId
					) x
					pivot 
					(
					Sum(ReceiptAmount) 
					for PayTypeName in (' + @cols + ')
					) p GROUP BY UserId,UserName,SourceTypeId ORDER BY UserId'
					print(@query)
					execute(@query)
				END
			ELSE IF (@rTypeId=13)
				BEGIN
					SET @cols = STUFF((SELECT ',' +  QUOTENAME(PTM.Title )
					FROM sFinanceCommon.tPayTypeMaster PTM
					--INNER JOIN  sFee.tReceipt R  ON PTM.Id=R.PayTypeId
					--INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.SourceId 
					GROUP BY PTM.Title
					FOR XML PATH(''), TYPE
					).value('.', 'NVARCHAR(MAX)') 
					,1,1,'')

					SET @cols1 = STUFF((SELECT ', SUM(ISNULL(' + QUOTENAME(PTM.Title) + ', ''0'')) ' + QUOTENAME(PTM.Title) 
					FROM sFinanceCommon.tPayTypeMaster PTM
					--INNER JOIN  sFee.tReceipt R  ON PTM.Id=R.PayTypeId
					--INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.SourceId 
					GROUP BY PTM.Title
					FOR XML PATH(''), TYPE
					).value('.', 'NVARCHAR(MAX)') 
					,1,1,'')

					SET @cols2 = STUFF((SELECT '+ SUM(ISNULL(' + QUOTENAME(PTM.Title) + ', ''0'')) '
					FROM sFinanceCommon.tPayTypeMaster PTM
					GROUP BY PTM.Title
					FOR XML PATH(''), TYPE
					).value('.', 'NVARCHAR(MAX)') 
					,1,1,'')

					set @query = 'SELECT OrgGroupId,OrgGroupName,' + @cols2 + ' AS Total, ' + @cols1 + ' from 
					(
					SELECT  OM.Id AS OrgGroupId ,OM.DisplayTitle AS OrgGroupName,SUM(R.ReceiptAmount) AS Total,PTM.Title AS PayTypeName, COALESCE(SUM(R.ReceiptAmount),0) AS ReceiptAmount FROM sFee.tReceipt R
					INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.SourceId 
					INNER JOIN sFinanceCommon.tPayTypeMaster PTM ON PTM.Id=R.PayTypeId
					INNER JOIN sFee.tReceiptBookMaster RBM ON RBM.Id=R.ReceiptBookId
					INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SA.OrgId
					INNER JOIN sSetup.tOrgGroupMaster OMM ON OMM.Id = OM.OrgGroupId 
					INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=SA.OrgGroupBatchId
					INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
					INNER JOIN sSetup.tBatchMaster BM ON SA.BatchId = BM.Id
					WHERE  COGBM.Id='+CONVERT(nvarchar(20),@rCommonOrgGroupBatchId)+' AND R.SourceTypeId = 2001 
					AND((OMM.Id='+CONVERT(nvarchar(20),@rOrgGroupId)+') OR ('+CONVERT(nvarchar(20),@rOrgGroupId)+'=0))
					AND (( convert(DATE, R.ReceiptDate,102) >= '''+CONVERT(nvarchar(20),@rFromDate)+''') OR ('''+CONVERT(nvarchar(20),@rFromDate)+'''=''1900-01-01''))
					AND (( convert(DATE, R.ReceiptDate,102) <= '''+CONVERT(nvarchar(20),@rToDate)+''') OR ('''+CONVERT(nvarchar(20),@rToDate)+'''=''1900-01-01''))
					AND BM.IsInContext = 1
					GROUP BY OM.DisplayTitle,OM.Id,PTM.Title
					) x
					pivot 
					(
					Sum(ReceiptAmount) 
					for PayTypeName in (' + @cols + ')
					) p GROUP BY OrgGroupId,OrgGroupName ORDER BY OrgGroupId '
					print(@query)
					execute(@query)
				END
			ELSE IF (@rTypeId=14)
				BEGIN
					SET @cols = STUFF((SELECT ',' +  QUOTENAME(PTM.Title )
					FROM sFinanceCommon.tPayTypeMaster PTM
					--INNER JOIN  sFee.tReceipt R  ON PTM.Id=R.PayTypeId
					--INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.SourceId 
					GROUP BY PTM.Title
					FOR XML PATH(''), TYPE
					).value('.', 'NVARCHAR(MAX)') 
					,1,1,'')

					SET @cols1 = STUFF((SELECT ', SUM(ISNULL(' + QUOTENAME(PTM.Title) + ', ''0'')) ' + QUOTENAME(PTM.Title) 
					FROM sFinanceCommon.tPayTypeMaster PTM
					--INNER JOIN  sFee.tReceipt R  ON PTM.Id=R.PayTypeId
					--INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.SourceId 
					GROUP BY PTM.Title
					FOR XML PATH(''), TYPE
					).value('.', 'NVARCHAR(MAX)') 
					,1,1,'')

					SET @cols2 = STUFF((SELECT '+ SUM(ISNULL(' + QUOTENAME(PTM.Title) + ', ''0'')) '
					FROM sFinanceCommon.tPayTypeMaster PTM
					GROUP BY PTM.Title
					FOR XML PATH(''), TYPE
					).value('.', 'NVARCHAR(MAX)') 
					,1,1,'')

					set @query = 'SELECT FeeHeadId,FeeHead,' + @cols2 + ' AS Total, ' + @cols1 + ' from 
					(
					SELECT  FHM.Id AS FeeHeadId,FHM.Title AS FeeHead,SUM(RD.Amount) AS total,PTM.Title AS PayTypeName,ISNULL(SUM(RD.Amount),0) AS ReceiptAmount FROM sFee.tReceipt R
					INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.SourceId 
					INNER JOIN sFee.tReceiptDetail RD ON R.Id = RD.ReceiptId
					INNER JOIN sFinanceCommon.tPayTypeMaster PTM ON PTM.Id=R.PayTypeId
					INNER JOIN sFee.tReceiptBookMaster RBM ON RBM.Id=R.ReceiptBookId
					INNER JOIN sFee.tFeeSetup FS ON FS.Id = RD.FeeSetupId
					INNER JOIN sFee.tFeeMaster FM ON FM.Id = FS.FeeId
					INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FM.FeeHeadId
					INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SA.OrgId
					INNER JOIN sSetup.tOrgGroupMaster OMM ON OMM.Id = OM.OrgGroupId 
					INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=SA.OrgGroupBatchId
					INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
					INNER JOIN sSetup.tBatchMaster BM ON SA.BatchId = BM.Id
					WHERE  COGBM.Id='+CONVERT(nvarchar(20),@rCommonOrgGroupBatchId)+' AND R.SourceTypeId = 2001 
					AND((OMM.Id='+CONVERT(nvarchar(20),@rOrgGroupId)+') OR ('+CONVERT(nvarchar(20),@rOrgGroupId)+'=0))
					AND (( convert(DATE, R.ReceiptDate,102) >= '''+CONVERT(nvarchar(20),@rFromDate)+''') OR ('''+CONVERT(nvarchar(20),@rFromDate)+'''=''1900-01-01''))
					AND (( convert(DATE, R.ReceiptDate,102) <= '''+CONVERT(nvarchar(20),@rToDate)+''') OR ('''+CONVERT(nvarchar(20),@rToDate)+'''=''1900-01-01''))
					AND BM.IsInContext = 1
					GROUP BY FHM.Id,FHM.Title,PTM.Id,PTM.Title
					) x
					pivot 
					(
					Sum(ReceiptAmount) 
					for PayTypeName in (' + @cols + ')
					) p GROUP BY FeeHeadId,FeeHead ORDER BY FeeHeadId'
					
					execute(@query)
				END
			ELSE IF (@rTypeId=15)
				BEGIN
					SET @cols = STUFF((SELECT ',' +  QUOTENAME(PTM.Title )
					FROM sFinanceCommon.tPayTypeMaster PTM
					--INNER JOIN  sFee.tReceipt R  ON PTM.Id=R.PayTypeId
					--INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.SourceId 
					GROUP BY PTM.Title
					FOR XML PATH(''), TYPE
					).value('.', 'NVARCHAR(MAX)') 
					,1,1,'')

					SET @cols1 = STUFF((SELECT ', SUM(ISNULL(' + QUOTENAME(PTM.Title) + ', ''0'')) ' + QUOTENAME(PTM.Title) 
					FROM sFinanceCommon.tPayTypeMaster PTM
					--INNER JOIN  sFee.tReceipt R  ON PTM.Id=R.PayTypeId
					--INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.SourceId 
					GROUP BY PTM.Title
					FOR XML PATH(''), TYPE
					).value('.', 'NVARCHAR(MAX)') 
					,1,1,'')

					SET @cols2 = STUFF((SELECT '+ SUM(ISNULL(' + QUOTENAME(PTM.Title) + ', ''0'')) '
					FROM sFinanceCommon.tPayTypeMaster PTM
					GROUP BY PTM.Title
					FOR XML PATH(''), TYPE
					).value('.', 'NVARCHAR(MAX)') 
					,1,1,'')

					set @query = 'SELECT FeeHeadId,FeeMaster,' + @cols2 + ' AS Total, ' + @cols1 + ' from 
					(
					SELECT FM.Id AS FeeHeadId,FM.Title AS FeeMaster,SUM(RD.Amount) AS total,PTM.Title AS PayTypeName,ISNULL(SUM(RD.Amount),0) AS ReceiptAmount FROM sFee.tReceipt R
						INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.SourceId 
						INNER JOIN sFee.tReceiptDetail RD ON R.Id = RD.ReceiptId
						INNER JOIN sFinanceCommon.tPayTypeMaster PTM ON PTM.Id=R.PayTypeId
						INNER JOIN sFee.tReceiptBookMaster RBM ON RBM.Id=R.ReceiptBookId
						INNER JOIN sFee.tFeeSetup FS ON FS.Id = RD.FeeSetupId
						INNER JOIN sFee.tFeeMaster FM ON FM.Id = FS.FeeId
						INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FM.FeeHeadId
						INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SA.OrgId
						INNER JOIN sSetup.tOrgGroupMaster OMM ON OMM.Id = OM.OrgGroupId 
						INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=SA.OrgGroupBatchId
						INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
						INNER JOIN sSetup.tBatchMaster BM ON SA.BatchId = BM.Id
						WHERE  COGBM.Id='+CONVERT(nvarchar(20),@rCommonOrgGroupBatchId)+' AND R.SourceTypeId = 2001 
						AND((OMM.Id='+CONVERT(nvarchar(20),@rOrgGroupId)+') OR ('+CONVERT(nvarchar(20),@rOrgGroupId)+'=0))
						AND (( convert(DATE, R.ReceiptDate,102) >= '''+CONVERT(nvarchar(20),@rFromDate)+''') OR ('''+CONVERT(nvarchar(20),@rFromDate)+'''=''1900-01-01''))
						AND (( convert(DATE, R.ReceiptDate,102) <= '''+CONVERT(nvarchar(20),@rToDate)+''') OR ('''+CONVERT(nvarchar(20),@rToDate)+'''=''1900-01-01''))
						AND BM.IsInContext = 1
						GROUP BY FM.Id,FM.Title,PTM.Id,PTM.Title
					) x
					pivot 
					(
					Sum(ReceiptAmount) 
					for PayTypeName in (' + @cols + ')
					) p GROUP BY FeeHeadId,FeeMaster  ORDER BY FeeHeadId'
					execute(@query)
				END

			ELSE IF(@rTypeId =21)
				BEGIN
				IF NOT EXISTS(SELECT 1 FROM sFee.tApplicablePayType WHERE OrgGroupId = @rOrgGroupId)
				BEGIN
					SELECT  R.ReceiptNumber AS ReceiptNumber,R.ReceiptDate AS ReceiptDate,SA.Code AS Code, SA.Name AS Name,R.ReceiptAmount AS Amount
					FROM sFee.tReceipt R
					INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.SourceId 
					INNER JOIN sFinanceCommon.tPayTypeMaster PTM ON PTM.Id=R.PayTypeId
					INNER JOIN sFee.tReceiptBookMaster RBM ON RBM.Id=R.ReceiptBookId
					INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SA.OrgId
					INNER JOIN sSetup.tOrgGroupMaster OMM ON OMM.Id = OM.OrgGroupId 
					INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=SA.OrgGroupBatchId
					INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
					INNER JOIN sSetup.tBatchMaster BM ON SA.BatchId = BM.Id
					WHERE  COGBM.Id= @rCommonOrgGroupBatchId  AND R.SourceTypeId = 2001 					 
					AND((OMM.Id=@rOrgGroupId) OR (@rOrgGroupId=0))
					AND ((R.ReceiptBookId =@rReceiptBookId )OR(@rReceiptBookId=0))
					AND (( convert(DATE, R.ReceiptDate,102) >= @rFromDate) OR (@rFromDate=''))
					AND (( convert(DATE, R.ReceiptDate,102) <= @rToDate) OR (@rToDate=''))
					AND R.IsObsolete = 0
					And ISNULL(OMM.IsObsolete,0) = 0
					AND BM.IsInContext = 1
					ORDER BY R.ReceiptNumber -- Added By Foram - 02/08/2023 - Mantis Issue: 0026499
				END
				ELSE
				BEGIN
				SELECT  R.ReceiptNumber AS ReceiptNumber,R.ReceiptDate AS ReceiptDate,SA.Code AS Code, SA.Name AS Name,R.ReceiptAmount AS Amount
					FROM sFee.tReceipt R
					INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.SourceId 
					INNER JOIN sFee.tApplicablePayType PTM ON PTM.PayTypeId=R.PayTypeId
					INNER JOIN sFee.tReceiptBookMaster RBM ON RBM.Id=R.ReceiptBookId
					INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SA.OrgId
					INNER JOIN sSetup.tOrgGroupMaster OMM ON OMM.Id = OM.OrgGroupId 
					INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=SA.OrgGroupBatchId
					INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
					INNER JOIN sSetup.tBatchMaster BM ON SA.BatchId = BM.Id
					WHERE  COGBM.Id= @rCommonOrgGroupBatchId  AND R.SourceTypeId = 2001 					 
					AND((OMM.Id=@rOrgGroupId) OR (@rOrgGroupId=0))
					AND ((R.ReceiptBookId =@rReceiptBookId )OR(@rReceiptBookId=0))
					AND (( convert(DATE, R.ReceiptDate,102) >= @rFromDate) OR (@rFromDate=''))
					AND (( convert(DATE, R.ReceiptDate,102) <= @rToDate) OR (@rToDate=''))
					AND R.IsObsolete = 0
					And ISNULL(OMM.IsObsolete,0) = 0
					AND BM.IsInContext = 1
					ORDER BY R.ReceiptNumber -- Added By Foram - 02/08/2023 - Mantis Issue: 0026499
				END
				END
			ELSE IF(@rTypeId =22)
				BEGIN
				IF NOT EXISTS(SELECT 1 FROM sFee.tApplicablePayType WHERE OrgGroupId = @rOrgGroupId)
				BEGIN
					SELECT  R.ReceiptNumber AS ReceiptNumber,R.ReceiptDate AS ReceiptDate,SA.Code AS Code, SA.Name AS Name,R.ReceiptAmount AS Amount
					FROM sFee.tReceipt R
					INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.SourceId 
					INNER JOIN sFinanceCommon.tPayTypeMaster PTM ON PTM.Id=R.PayTypeId
					INNER JOIN sFee.tReceiptBookMaster RBM ON RBM.Id=R.ReceiptBookId
					INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SA.OrgId
					INNER JOIN sSetup.tOrgGroupMaster OMM ON OMM.Id = OM.OrgGroupId 
					INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=SA.OrgGroupBatchId
					INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
					LEFT JOIN sSecurity.tUser U ON U.Id=R.CreatedUserId
					INNER JOIN sSetup.tBatchMaster BM ON SA.BatchId = BM.Id
					WHERE  COGBM.Id= @rCommonOrgGroupBatchId  AND R.SourceTypeId = 2001 					 
					AND((OMM.Id=@rOrgGroupId) OR (@rOrgGroupId=0))
					--AND ((U.Id =@rUserId )OR(@rUserId=0))
					AND ((U.Id = CASE WHEN @rUserId = 2003 THEN 0 ELSE @rUserId END)OR(CASE WHEN @rUserId = 2003 THEN 0 ELSE @rUserId END=0))
					AND ((U.SourceTypeId = CASE WHEN @rUserId = 2003 THEN 2003 ELSE 0 END)OR(CASE WHEN @rUserId = 2003 THEN 2003 ELSE 0 END=0))
					AND (( convert(DATE, R.ReceiptDate,102) >= @rFromDate) OR (@rFromDate=''))
					AND (( convert(DATE, R.ReceiptDate,102) <= @rToDate) OR (@rToDate=''))
					AND BM.IsInContext = 1
				END
				ELSE
				BEGIN
					SELECT  R.ReceiptNumber AS ReceiptNumber,R.ReceiptDate AS ReceiptDate,SA.Code AS Code, SA.Name AS Name,R.ReceiptAmount AS Amount
					FROM sFee.tReceipt R
					INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.SourceId 
					INNER JOIN sFee.tApplicablePayType PTM ON PTM.PayTypeId=R.PayTypeId
					INNER JOIN sFee.tReceiptBookMaster RBM ON RBM.Id=R.ReceiptBookId
					INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SA.OrgId
					INNER JOIN sSetup.tOrgGroupMaster OMM ON OMM.Id = OM.OrgGroupId 
					INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=SA.OrgGroupBatchId
					INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
					LEFT JOIN sSecurity.tUser U ON U.Id=R.CreatedUserId
					INNER JOIN sSetup.tBatchMaster BM ON SA.BatchId = BM.Id
					WHERE  COGBM.Id= @rCommonOrgGroupBatchId  AND R.SourceTypeId = 2001 					 
					AND((OMM.Id=@rOrgGroupId) OR (@rOrgGroupId=0))
					--AND ((U.Id =@rUserId )OR(@rUserId=0))
					AND ((U.Id = CASE WHEN @rUserId = 2003 THEN 0 ELSE @rUserId END)OR(CASE WHEN @rUserId = 2003 THEN 0 ELSE @rUserId END=0))
					AND ((U.SourceTypeId = CASE WHEN @rUserId = 2003 THEN 2003 ELSE 0 END)OR(CASE WHEN @rUserId = 2003 THEN 2003 ELSE 0 END=0))
					AND (( convert(DATE, R.ReceiptDate,102) >= @rFromDate) OR (@rFromDate=''))
					AND (( convert(DATE, R.ReceiptDate,102) <= @rToDate) OR (@rToDate=''))
					AND BM.IsInContext = 1
				END
				END
			ELSE IF(@rTypeId =23)
				BEGIN
				IF NOT EXISTS(SELECT 1 FROM sFee.tApplicablePayType WHERE OrgGroupId = @rOrgGroupId)
				BEGIN
					SELECT  R.ReceiptNumber AS ReceiptNumber,R.ReceiptDate AS ReceiptDate,SA.Code AS Code, SA.Name AS Name,R.ReceiptAmount AS Amount
					FROM sFee.tReceipt R
					INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.SourceId 
					INNER JOIN sFinanceCommon.tPayTypeMaster PTM ON PTM.Id=R.PayTypeId
					INNER JOIN sFee.tReceiptBookMaster RBM ON RBM.Id=R.ReceiptBookId
					INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SA.OrgId
					INNER JOIN sSetup.tOrgGroupMaster OMM ON OMM.Id = OM.OrgGroupId 
					INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=SA.OrgGroupBatchId
					INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
					INNER JOIN sSetup.tBatchMaster BM ON SA.BatchId = BM.Id
					WHERE  COGBM.Id= @rCommonOrgGroupBatchId  AND R.SourceTypeId = 2001 					 
					AND((OMM.Id=@rOrgGroupId) OR (@rOrgGroupId=0))
					AND ((OM.Id =@rOrgId )OR(@rOrgId=0))
					AND (( convert(DATE, R.ReceiptDate,102) >= @rFromDate) OR (@rFromDate=''))
					AND (( convert(DATE, R.ReceiptDate,102) <= @rToDate) OR (@rToDate=''))
					AND BM.IsInContext = 1
				END
				ELSE
				BEGIN
					SELECT  R.ReceiptNumber AS ReceiptNumber,R.ReceiptDate AS ReceiptDate,SA.Code AS Code, SA.Name AS Name,R.ReceiptAmount AS Amount
					FROM sFee.tReceipt R
					INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.SourceId 
					INNER JOIN sFee.tApplicablePayType PTM ON PTM.PayTypeId=R.PayTypeId
					INNER JOIN sFee.tReceiptBookMaster RBM ON RBM.Id=R.ReceiptBookId
					INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SA.OrgId
					INNER JOIN sSetup.tOrgGroupMaster OMM ON OMM.Id = OM.OrgGroupId 
					INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=SA.OrgGroupBatchId
					INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
					INNER JOIN sSetup.tBatchMaster BM ON SA.BatchId = BM.Id
					WHERE  COGBM.Id= @rCommonOrgGroupBatchId  AND R.SourceTypeId = 2001 					 
					AND((OMM.Id=@rOrgGroupId) OR (@rOrgGroupId=0))
					AND ((OM.Id =@rOrgId )OR(@rOrgId=0))
					AND (( convert(DATE, R.ReceiptDate,102) >= @rFromDate) OR (@rFromDate=''))
					AND (( convert(DATE, R.ReceiptDate,102) <= @rToDate) OR (@rToDate=''))
					AND BM.IsInContext = 1
				END
				END
			ELSE IF(@rTypeId =24)
				BEGIN
				IF NOT EXISTS(SELECT 1 FROM sFee.tApplicablePayType WHERE OrgGroupId = @rOrgGroupId)
				BEGIN
					SELECT  R.ReceiptNumber AS ReceiptNumber,R.ReceiptDate AS ReceiptDate,SA.Code AS Code, SA.Name AS Name,SUM(RD.Amount) AS Amount
					FROM sFee.tReceipt R
					INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.SourceId 
					INNER JOIN sFee.tReceiptDetail RD ON R.Id = RD.ReceiptId
					INNER JOIN sFinanceCommon.tPayTypeMaster PTM ON PTM.Id=R.PayTypeId
					INNER JOIN sFee.tReceiptBookMaster RBM ON RBM.Id=R.ReceiptBookId
					INNER JOIN sFee.tFeeSetup FS ON FS.Id = RD.FeeSetupId
					INNER JOIN sFee.tFeeMaster FM ON FM.Id = FS.FeeId
					INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FM.FeeHeadId
					INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SA.OrgId
					INNER JOIN sSetup.tOrgGroupMaster OMM ON OMM.Id = OM.OrgGroupId 
					INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=SA.OrgGroupBatchId
					INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
					INNER JOIN sSetup.tBatchMaster BM ON SA.BatchId = BM.Id
					WHERE  COGBM.Id= @rCommonOrgGroupBatchId  AND R.SourceTypeId = 2001 					 
					AND((OMM.Id=@rOrgGroupId) OR (@rOrgGroupId=0))
					AND ((FHM.Id =@rCommonFeeId)OR(@rCommonFeeId=0))
					AND (( convert(DATE, R.ReceiptDate,102) >= @rFromDate) OR (@rFromDate=''))
					AND (( convert(DATE, R.ReceiptDate,102) <= @rToDate) OR (@rToDate=''))
					AND BM.IsInContext = 1
					GROUP BY  R.ReceiptNumber,R.ReceiptDate,SA.Code, SA.Name 
				END
				ELSE
				BEGIN
					SELECT  R.ReceiptNumber AS ReceiptNumber,R.ReceiptDate AS ReceiptDate,SA.Code AS Code, SA.Name AS Name,SUM(RD.Amount) AS Amount
					FROM sFee.tReceipt R
					INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.SourceId 
					INNER JOIN sFee.tReceiptDetail RD ON R.Id = RD.ReceiptId
					INNER JOIN sFee.tApplicablePayType PTM ON PTM.PayTypeId=R.PayTypeId
					INNER JOIN sFee.tReceiptBookMaster RBM ON RBM.Id=R.ReceiptBookId
					INNER JOIN sFee.tFeeSetup FS ON FS.Id = RD.FeeSetupId
					INNER JOIN sFee.tFeeMaster FM ON FM.Id = FS.FeeId
					INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FM.FeeHeadId
					INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SA.OrgId
					INNER JOIN sSetup.tOrgGroupMaster OMM ON OMM.Id = OM.OrgGroupId 
					INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=SA.OrgGroupBatchId
					INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
					INNER JOIN sSetup.tBatchMaster BM ON SA.BatchId = BM.Id
					WHERE  COGBM.Id= @rCommonOrgGroupBatchId  AND R.SourceTypeId = 2001 					 
					AND((OMM.Id=@rOrgGroupId) OR (@rOrgGroupId=0))
					AND ((FHM.Id =@rCommonFeeId)OR(@rCommonFeeId=0))
					AND (( convert(DATE, R.ReceiptDate,102) >= @rFromDate) OR (@rFromDate=''))
					AND (( convert(DATE, R.ReceiptDate,102) <= @rToDate) OR (@rToDate=''))
					GROUP BY  R.ReceiptNumber,R.ReceiptDate,SA.Code, SA.Name
				END
				END
			ELSE IF(@rTypeId =25)
				BEGIN
				IF NOT EXISTS(SELECT 1 FROM sFee.tApplicablePayType WHERE OrgGroupId = @rOrgGroupId)
				BEGIN
					SELECT  R.ReceiptNumber AS ReceiptNumber,R.ReceiptDate AS ReceiptDate,SA.Code AS Code, SA.Name AS Name,SUM(RD.Amount) AS Amount
					FROM sFee.tReceipt R
					INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.SourceId 
					INNER JOIN sFee.tReceiptDetail RD ON R.Id = RD.ReceiptId
					INNER JOIN sFinanceCommon.tPayTypeMaster PTM ON PTM.Id=R.PayTypeId
					INNER JOIN sFee.tReceiptBookMaster RBM ON RBM.Id=R.ReceiptBookId
					INNER JOIN sFee.tFeeSetup FS ON FS.Id = RD.FeeSetupId
					INNER JOIN sFee.tFeeMaster FM ON FM.Id = FS.FeeId
					INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FM.FeeHeadId
					INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SA.OrgId
					INNER JOIN sSetup.tOrgGroupMaster OMM ON OMM.Id = OM.OrgGroupId 
					INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=SA.OrgGroupBatchId
					INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
					INNER JOIN sSetup.tBatchMaster BM ON SA.BatchId = BM.Id
					WHERE  
					COGBM.Id=@rCommonOrgGroupBatchId
					AND R.SourceTypeId = 2001 					 
					AND((OMM.Id=@rOrgGroupId) OR (@rOrgGroupId=0))
					AND ((FM.Id =@rCommonFeeId)OR(@rCommonFeeId=0))
					AND (( convert(DATE, R.ReceiptDate,102) >= @rFromDate) OR (@rFromDate=''))
					AND (( convert(DATE, R.ReceiptDate,102) <= @rToDate) OR (@rToDate=''))
					AND BM.IsInContext = 1
					GROUP BY  R.ReceiptNumber,R.ReceiptDate,SA.Code, SA.Name 
				END
				ELSE
				BEGIN
					SELECT  R.ReceiptNumber AS ReceiptNumber,R.ReceiptDate AS ReceiptDate,SA.Code AS Code, SA.Name AS Name,SUM(RD.Amount) AS Amount
					FROM sFee.tReceipt R
					INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.SourceId 
					INNER JOIN sFee.tReceiptDetail RD ON R.Id = RD.ReceiptId
					INNER JOIN sFee.tApplicablePayType PTM ON PTM.PayTypeId=R.PayTypeId
					INNER JOIN sFee.tReceiptBookMaster RBM ON RBM.Id=R.ReceiptBookId
					INNER JOIN sFee.tFeeSetup FS ON FS.Id = RD.FeeSetupId
					INNER JOIN sFee.tFeeMaster FM ON FM.Id = FS.FeeId
					INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FM.FeeHeadId
					INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SA.OrgId
					INNER JOIN sSetup.tOrgGroupMaster OMM ON OMM.Id = OM.OrgGroupId 
					INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=SA.OrgGroupBatchId
					INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
					INNER JOIN sSetup.tBatchMaster BM ON SA.BatchId = BM.Id
					WHERE  
					COGBM.Id=@rCommonOrgGroupBatchId
					AND R.SourceTypeId = 2001 					 
					AND((OMM.Id=@rOrgGroupId) OR (@rOrgGroupId=0))
					AND ((FM.Id =@rCommonFeeId)OR(@rCommonFeeId=0))
					AND (( convert(DATE, R.ReceiptDate,102) >= @rFromDate) OR (@rFromDate=''))
					AND (( convert(DATE, R.ReceiptDate,102) <= @rToDate) OR (@rToDate=''))
					AND BM.IsInContext = 1
					GROUP BY  R.ReceiptNumber,R.ReceiptDate,SA.Code, SA.Name
				END
				END
		
	
END
GO
PRINT N'Altering Procedure [sFee].[pFeeSetupApply]...';


GO
 ALTER PROCEDURE [sFee].[pFeeSetupApply]
	 
		   @rOrgId int,
           @rFromClassId int,
           @rFromAdmissionCategoryId int,
           @rFromBatchId int,
           @rToClassId int,
           @rToAdmissionCategoryId int,
           @rToBatchId int,       
           @rCreatedUserId bigint

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
		BEGIN TRANSACTION
	
	DECLARE @lNextNumber INT  
	DECLARE @lCountSetup INT
	DECLARE @lNextSetupNumber INT
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sFee.tFeeSetup', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	INSERT INTO sFee.tFeeSetup
				SELECT @lNextNumber + ROW_NUMBER() OVER(ORDER BY Id) AS Id,
				@rToClassId,
				@rToAdmissionCategoryId,
				@rToBatchId,
				FeeId,
				IsVariable,
				IsOptional,
				Amount,
				StartDate,
				EndDate,
				ReceiptBookId,
				@rCreatedUserId,
				sCommon.fGetDate(),
				NULL,
				NULL,
				IsServiceTax,
				CollectionGroupId,
				FeeDuration,
				0,
				LevelAmount,
				LateFeeRuleId
				
				FROM sFee.tFeeSetup
				WHERE ClassId = @rFromClassId AND AdmissionCategoryId = @rFromAdmissionCategoryId
				AND BatchId = @rFromBatchId
				
				SELECT @lCountSetup = COUNT(Id)	FROM sFee.tFeeSetup
					WHERE ClassId = @rFromClassId 
					AND AdmissionCategoryId = @rFromAdmissionCategoryId
					AND BatchId = @rFromBatchId
					
				SET @lNextSetupNumber  = ISNULL(@lNextNumber,0) + ISNULL( @lCountSetup ,0)		
					
				EXECUTE sCommon.pTableRowIdModify @rOrgId, @rTableTitle = 'sFee.tFeeSetup', @rCurrentNumber = @lNextSetupNumber 		
				
				SELECT 1 AS Result
				
			COMMIT TRANSACTION			
		END TRY
		
		BEGIN CATCH 
			ROLLBACK TRANSACTION
				SELECT -1 AS Result
		END CATCH
END
GO
PRINT N'Altering Procedure [sFee].[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
	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
			 
 	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
	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,'') = ''))
    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
--END
GO
PRINT N'Altering Procedure [sLibrary].[pRptAccessionRegisterGet]...';


GO

ALTER PROCEDURE [sLibrary].[pRptAccessionRegisterGet]
	 
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='',
	 @rBookSupplier nvarchar(200),
	 @rBookPublisher nvarchar(200),
	 @rBookLanguage nvarchar(200),
	 @rBookTag nvarchar(200),
	 @rBookCustomTag nvarchar(200),
	 @rLibraryId int,
	 @rAccessionNo nvarchar(50)='',
	 @rClassificationNo nvarchar(50)='',
	 @rBookGroup1Id int,
	 @rBookGroup2Id int,
	 @rBookSubjectDrop nvarchar(200)='',
	 @rBookSubjectText nvarchar(200)='',
	 @rFromPurchaseDate date='',
	 @rToPurchaseDate date=''
           
AS
SET NOCOUNT ON
BEGIN
	BEGIN	  
		SET @rBookSupplier = sCommon.fSearchStringGet(@rBookSupplier)
		SET @rBookPublisher = sCommon.fSearchStringGet(@rBookPublisher)
		SET @rBookLanguage = sCommon.fSearchStringGet(@rBookLanguage)
		SET @rBookTag = sCommon.fSearchStringGet(@rBookTag)
		SET @rBookCustomTag = sCommon.fSearchStringGet(@rBookCustomTag)
		SET @rAccessionNo = sCommon.fSearchStringGet(@rAccessionNo)
		SET @rClassificationNo = sCommon.fSearchStringGet(@rClassificationNo)
		SET @rBookSubjectText = sCommon.fSearchStringGet(@rBookSubjectText)
	END
	SELECT   
		@rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,
		BM.Id AS BookId,
		BM.Code AS BookCode,
		BM.Title AS BookName,
		BM.Author,
		BM.Publisher,
		BM.ClassificationNo,
		BM.BookSubject,
		BM.AccessionNo,
		BM.Edition,
		BM.NoOfPages,
		BM.BookLanguage,
		BM.Supplier,
		BM.PurchaseDate,
		BM.Price,
		BM.ISBNNumber,
		BM.Location,
		BM.BookRemark,
		LM.ReportOrgTitle,
		LM.SmallAddress1,
		LM.SmallAddress2
	FROM  
		sLibrary.tBookMaster BM 
		LEFT JOIN sLibrary.tLibraryMaster LM ON LM.Id=BM.LibraryId
	WHERE 
		BM.LibraryId=@rLibraryId
		AND ((BM.Supplier like @rBookSupplier) OR (@rBookSupplier=''))
		AND ((BM.Publisher like @rBookPublisher) OR (@rBookPublisher=''))
		AND ((BM.BookLanguage like @rBookLanguage) OR (@rBookLanguage=''))
		AND ((BM.BookTag like @rBookTag) OR (@rBookTag=''))
		AND ((BM.BookCustomTag like @rBookCustomTag) OR (@rBookCustomTag=''))
		AND ((BM.AccessionNo like @rAccessionNo) OR (@rAccessionNo=''))
		AND ((BM.ClassificationNo like @rClassificationNo) OR (@rClassificationNo=''))
		AND ((BM.BookGroup1Id = @rBookGroup1Id) OR (@rBookGroup1Id=0))
		AND ((BM.BookGroup2Id = @rBookGroup2Id) OR (@rBookGroup2Id=0))
		AND ((BM.BookSubject = @rBookSubjectDrop) OR (@rBookSubjectDrop=''))
		AND ((BM.BookSubject like @rBookSubjectText) OR (@rBookSubjectText=''))
		AND ((BM.PurchaseDate >= @rFromPurchaseDate) OR (ISNULL(@rFromPurchaseDate,'') = ''))
		AND ((BM.PurchaseDate <= @rToPurchaseDate) OR (ISNULL(@rToPurchaseDate,'') =''))
END
GO
PRINT N'Altering Procedure [sLibrary].[pRptBookListGet]...';


GO
 
ALTER PROCEDURE [sLibrary].[pRptBookListGet]
	 
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='',
	 @rBookSupplier nvarchar(200),
	 @rBookPublisher nvarchar(200),
	 @rBookSubjectText nvarchar(200),
	 @rBookLanguage nvarchar(200),
	 @rBookTag nvarchar(200),
	 @rBookCustomTag nvarchar(200),
	 @rLibraryId int,
	 @rBookDepartment nvarchar(150)='',
	 @rIsDetail bit=0,
	 @rFromPurchaseDate date='',
	 @rToPurchaseDate date='',
	 @rBookGroup1Id int,
	 @rBookGroup2Id int,
	 --@rOrgGroupId int,
	 @rFromCode nvarchar(25) ='',
	 @rToCode nvarchar(25) ='',
	 @rSpecificCode nvarchar(max) ='',
	 @rBookSubjectDrop nvarchar(500)='',
	 @rFromDate date ='',
	 @rToDate date =''
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
		
BEGIN 
	--DECLARE @rFromCodeInt INT, @rToCodeInt INT
	--DECLARE @BookConfig NVARCHAR, @rFromCodeString NVARCHAR, @rToCodeString NVARCHAR
	--SELECT @BookConfig = ItemValue From sConfig.tConfigurationSetup	WHERE ConfigurationId = 260 AND SourceId = @rOrgGroupId
	
	--SET @rFromCodeInt = Convert(Int,ISNULL(@rFromCode,0))
	--SET @rToCodeInt = Convert(Int,ISNULL(@rToCode,0))
	--SET @rFromCodeString = Convert(nvarchar,ISNULL(@rFromCode,''))
	--SET @rToCodeString = Convert(nvarchar,ISNULL(@rToCode,''))
	
	DECLARE @ListofBookCodes TABLE(Code nvarchar(25), ID INT IDENTITY(1,1));
		INSERT INTO @ListofBookCodes
	
	select q2.value from
		(SELECT cast('<x>'+replace(@rSpecificCode,',','</x><x>')+'</x>' as xml) as thexml)q1 CROSS APPLY
		(SELECT x.value('.','nvarchar(max)') as value FROM thexml.nodes('x') as f(x))q2
		

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

	SELECT 
		@rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,
		BM.Code,
		BM.Title As BookTitle,
		BM.Publisher,BM.Supplier,
		BM.BookSubject,
		BM.Code AS BookCode,
		BM.BookLanguage,
		BM.BookCustomTag,
		BM.BookCustomTag,
		BM.Location,
		BM.ISBNNumber,
		LM.ReportOrgTitle,
        LM.SmallAddress1,
        LM.SmallAddress2,
        CASE WHEN BM.BookDepartment is null THEN 'Blank'
            WHEN BM.BookDepartment='' THEN 'Blank'  ELSE BM.BookDepartment END AS  BookDepartment,
        BM.NoOfCopies,
        @rIsDetail AS IsDetail,
        LM.Code AS LibraryCode,	       
         LM.Title AS LibraryTitle,
        BM.AccessionNo AS AccessionNo
		
	FROM 
		sLibrary.tBookMaster BM
		LEFT JOIN sLibrary.tLibraryMaster LM ON LM.Id=BM.LibraryId
	WHERE 
		BM.LibraryId=@rLibraryId
		AND ((BM.Supplier like @rBookSupplier) OR (@rBookSupplier=''))
		AND ((BM.Publisher like @rBookPublisher) OR (@rBookPublisher=''))
		AND ((BM.BookSubject like @rBookSubjectText) OR (@rBookSubjectText=''))
		AND ((BM.BookSubject = @rBookSubjectDrop) OR (@rBookSubjectDrop=''))
		AND ((BM.BookLanguage like @rBookLanguage) OR (@rBookLanguage=''))
		AND ((BM.BookTag like @rBookTag) OR (@rBookTag=''))
		AND ((BM.BookCustomTag like @rBookCustomTag) OR (@rBookCustomTag=''))
		AND ((BM.BookDepartment like @rBookDepartment) OR (@rBookDepartment=''))
		AND ((BM.PurchaseDate >= @rFromPurchaseDate) OR (ISNULL(@rFromPurchaseDate,'') = ''))
		AND ((BM.PurchaseDate <= @rToPurchaseDate) OR (ISNULL(@rToPurchaseDate,'') =''))
		AND ((BM.BookGroup1Id = @rBookGroup1Id) OR (@rBookGroup1Id=0))
		AND ((BM.BookGroup2Id = @rBookGroup2Id) OR (@rBookGroup2Id=0))
		AND ((Convert(nvarchar(25),ISNULL(BM.Code,'')) >= @rFromCode) OR (ISNULL(@rFromCode,'') = ''))
		AND ((Convert(nvarchar(25),ISNULL(BM.Code,'')) <= @rToCode) OR (ISNULL(@rToCode,'') = ''))
		AND ((BM.Code IN(SELECT Code FROM @ListofBookCodes)) OR (ISNULL(@rSpecificCode,'') = ''))
		--AND CASE WHEN @BookConfig = 'True' THEN BM.Code >= @rFromCodeString ELSE BM.Code > @rFromCodeInt END AS BM.Code
		--AND CASE WHEN @BookConfig = 'True' THEN BM.Code <= @rToCodeString ELSE BM.Code > @rToCodeInt END AS BM.Code
		AND ((BM.BookEntryDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
		AND ((BM.BookEntryDate <= @rToDate) OR (ISNULL(@rToDate,'') = ''))
		ORDER BY
		CASE WHEN BM.Code like '%[0-9]%' 
		 THEN Replicate('0', 100 - Len(BM.Code)) + BM.Code
		 ELSE BM.Code  END
		--ORDER BY CONVERT(INT, BM.Code)
		
	END
GO
PRINT N'Altering Procedure [sSecurity].[pPendingLoginStudentdGet]...';


GO
 
ALTER PROCEDURE [sSecurity].[pPendingLoginStudentdGet]
	
	@rOrgId smallint,
	@rBatchId int,
	@rIsPendingLogin bit,
	@rIsCreatedLogin bit,
	@rClassId int = 0,
	@rDivisionId int = 0,
	@rNotRegister bit = 0,
	@rRollNos nvarchar(max) = NULL,
	@rMultiCode nvarchar(max)=''

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	SELECT 
	-- TOP 100
			ISNULL(U.Id,0) AS Id,
			SC.StudentId,
			SC.Code,
			SC.Name,
			SC.ClassName + '-' + SC.DivisionName AS ClassName,
			SC.RollNo,
			ISNULL(SC.ParentContactNo,'') AS MobileNo,
			ISNULL(SC.ParentEmail,'') AS EmailId,
			U.LoginTitle AS UserName,
			U.LoginPassword,
			SC.SUId,
			SM.Title AS Status,
			(CASE WHEN A.UserId IS NULL THEN 'Not Register' ELSE 'Register' END) AS UserRegisterStatus,
			ISNULL(SC.WhatsAppContactNo,'') AS WhatsAppContactNo
	FROM 
			sStudent.vStudentCommunication SC
			LEFT JOIN sSecurity.tUser U ON U.SourceId = SC.StudentId AND U.SourceTypeId=2003
			INNER JOIN sStudent.tStatusMaster SM ON SM.Id = SC.StatusId 
			LEFT JOIN 
			(
				SELECT DISTINCT UserId FROM sCommunication.tRegisteredUsers
			) AS A ON A.UserId = U.Id
	WHERE 
			((U.LoginPassWord is Null AND @rIsPendingLogin=1) OR (U.LoginPassWord is NOT Null AND @rIsCreatedLogin=1))
			 AND	(SC.OrgId = @rOrgId)
			 AND	(SC.BatchId = @rBatchId) 
			 AND	((SC.ClassId = @rClassId) OR(@rClassId=0))
			 AND	((SC.DivisionId = @rDivisionId) OR(@rDivisionId=0))
			 AND SC.StatusId = 1
			 AND ((A.UserId IS NULL AND @rNotRegister = 1) OR (@rNotRegister = 0))
			 AND (ISNULL(SC.RollNo,0) IN( SELECT cast(item as Int) FROM  sCommon.fnsplit(@rRollNos,',')) OR @rRollNos IS NULL)
			 AND (ISNULL(SC.Code,0) IN( SELECT cast(item as nvarchar(20)) FROM  sCommon.fnsplit(@rMultiCode,',')) OR @rMultiCode='')
	Order By SC.DivisionOrderIndex,SC.RollNo
	
END
GO
PRINT N'Altering Procedure [sStudent].[pRptStudentLCVerificationGet]...';


GO
ALTER PROCEDURE [sStudent].[pRptStudentLCVerificationGet]
	 
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 @rDepartmentId int=0,
	 @rClassId int=0,
	 @rDivisionId int=0,
     @rStrCode nvarchar(20)='',
	 @rStatusId int=0,
	 @rClassStatusId int=0,
	 @rExamId int = 0
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
	
	SELECT 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			L.Id,		
			vSA.Code,
			L.AcademicId,
			vSA.FirstName,vSA.MiddleName,vSA.LastName,
			[sStudent].[fStudentNameGet](vSA.FirstName , vSA.MiddleName, vSA.LastName,OM.StudentNameFormatId ) AS Name,
			ISNULL(SF.FatherName,'') As FatherName,
			ISNULL(SF.MotherName,'') As MotherName,
			--ISNULL(CTM.Nationality,'') AS Nationality,		
			--ISNULL(RM.Title,'') AS Religion,
			ISNULL(so.BirthPlace,'') AS BirthPlace,
			ISNULL(SO.BirthTaluka,'') AS BirthTaluka,
			ISNULL(SO.BirthDistrict,'') AS BirthDistrict,
			SO.DateOfBirth,
			ISNULL(SO.BirthDateInWord,'') AS BirthDateInWord,
			L.LCNumber,
			L.LeftDate,
			L.LCReason,
			L.LCProgress,
			L.LCConduct,
			L.LCRemark,
			L.LCDate,
			L.LCBookNumber,
			ISNULL(SO.FamilySubCast,'') AS SubCaste,
			ISNULL(SO.FamilyCast,'') AS Caste,
		    vSA.StatusId,		
		 	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,			
			vSA.ClassName AS ClassName,
			vSA.DivisionName AS DivisionName,	
			isnull(MainCastCategoryId,0) AS CastCategoryId,
			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,
			SO.UIDNumber,
			--SA.PreviousStandard 
			L.LCCopy
			,vSA.BatchName AS BatchName,
		    ISNULL(SA.AdmissionNumber,'') AS AdmissionNumber,
			SO.UIDNumber,	
			ISNULL(OM.ReportOrgGroupTitle,'') AS ReportOrgGroupTitle,
			OM.ReportOrgTitle,	
    		ISNULL(CMS.ClassNameInWord,'') AS ClassNameInWord,
			vSA.ClassId AS ClassId,
	    	--EI.EmployeeSign,
		    OM.PrincipalSignature,
			ISNULL(R.Percentage,0) As Percentage,
			ISNULL(SCM.Title,0) AS LeftStandard
	FROM 
			sCertificate.tLeaving L
			INNER JOIN sStudent.vStudentAcademic vSA ON vSA.AcademicId=L.AcademicId	
			LEFT JOIN sStudent.tStudentAdmission SA ON SA.StudentId=vSA.StudentId			
			INNER JOIN 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 sSetup.tClassMaster CM ON CM.Id=SA.AdmissionStandardId
			INNER JOIN sSetup.tDivisionMaster DM ON vSA.DivisionId = DM.Id  
			INNER JOIN sSetup.tClassMaster CMS ON CMS.Id= DM.ClassId 
			LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId=vSA.StudentId
			--LEFT JOIN sCommon.tCountryMaster CTM ON CTM.Id=SO.NationalityId
			--LEFT JOIN sStudent.tAcademicDetail AD ON AD.AcademicId=vSA.AcademicId	
			--LEFT JOIN sSetup.tOrgImages OI ON OI.OrgId = OM.Id
			LEFT JOIN sCommon.tCastCategoryMaster CSM ON CSM.Id=SO.CastCategoryId
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id=vSA.BatchId 
			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=vSA.StudentId
			--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
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId=vSA.ClassId
            INNER JOIN sAssessment.tResult R ON R.ExamId = EM.Id AND vSA.AcademicId = R.AcademicId
			LEFT JOIN sSetup.tClassMaster SCM ON SCM.Id = SA.LeftStandardId
	Where		
	           ((vSA.DepartmentId=@rDepartmentId) OR(@rDepartmentId=0))
	       AND ((vSA.ClassId=@rClassId) OR(@rClassId=0))	  
	       AND ((vSA.DivisionId=@rDivisionId) OR (@rDivisionId=0))	
		   --AND ((vSA.Code = @rStrCode) OR (ISNULL(@rStrCode,'') = ''))
		   AND (ISNULL(vSA.Code,0) IN( SELECT cast(item as nvarchar(20)) FROM  sCommon.fnsplit(@rStrCode,',')) OR @rStrCode='')
           AND ((vSA.StatusId=@rStatusId)OR(@rStatusId=0))
		   AND ((vSA.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0)) 
		   AND ((R.ExamId = @rExamId) OR (@rExamId=0))				
END
GO
PRINT N'Altering Procedure [sStudent].[pStudentDocumentSubmitGet]...';


GO

ALTER PROCEDURE [sStudent].[pStudentDocumentSubmitGet]
	 
        @rStudentId bigint,
		@rOrgId int
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
 
	BEGIN
			SELECT DISTINCT Isnull(D.Id,0) AS DocumentId,ISNULL(D.DocumentName,'') AS DocumentName,
			CASE WHEN  S.SubmitDocumentMasterId Is null THEN 'False' ELSE 'True'END AS IsCheck,
			ISNULL(S.DocumentName,'') AS FileName
		 	FROM sCommon.tSubmitDocumentMaster D
			INNER JOIN sCommon.tSubmitDocumentScope DS ON DS.SubmitDocumentId = D.Id
			INNER JOIN sStudent.tAcademic A ON A.ClassId = DS.SourceId AND A.StudentId = @rStudentId
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId AND BM.IsActive = 1
			LEFT Join sStudent.tStudentDocument  S ON S.SubmitDocumentMasterId=D.id AND S.StudentId=@rStudentId
			WHERE D.OrgId=@rOrgId AND SubmitDocumentFunctionalityId='1'

			UNION 

			SELECT DISTINCT Isnull(D.Id,0) AS DocumentId,ISNULL(D.DocumentName,'') AS DocumentName,
			CASE WHEN  S.SubmitDocumentMasterId Is null THEN 'False' ELSE 'True'END AS IsCheck,
			ISNULL(S.DocumentName,'') AS FileName
		 	FROM sCommon.tSubmitDocumentMaster D
			LEFT JOIN sCommon.tSubmitDocumentScope DS ON DS.SubmitDocumentId = D.Id AND DS.SubmitDocumentId is null
			LEFT JOIN sStudent.tAcademic A ON A.ClassId = DS.SourceId AND A.StudentId = @rStudentId
			LEFT JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId AND BM.IsActive = 1
			LEFT Join sStudent.tStudentDocument  S ON S.SubmitDocumentMasterId=D.id AND S.StudentId=@rStudentId
			WHERE D.OrgId=@rOrgId AND SubmitDocumentFunctionalityId='1' AND A.ClassId is not null --AND DS.SubmitDocumentId is null


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


GO
ALTER PROCEDURE [sStudent].[pSUIDGenerationGet]
	 
	 @rOrgGroupId smallint,
	 @rOrgId smallint,
	 @rDepartmentId int,
	 @rClassID int,
	 @rDivisionId int,
	 @rRecordStatusId smallint,
	 @rBatchId int=0,
	 @rOrderByTypeId smallint = 0	 

	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
	SELECT 
		vSA.StudentId,
		vSA.OrgId,
		vSA.OrganizationName,
		VSA.DepartmentName,
		vSA.ClassName+' - '+vSA.DivisionName AS ClassDivisionName,
		vSA.RollNo,
		vSA.Code,
		ISNULL(vSA.SUId,'') AS SUID,
		vSA.Name,
		SA.AdmissionDate,
		GM.Title As Gender,
		(Select CM.Title from sSetup.tClassMaster CM WHere CM.Id=SA.AdmissionStandardId) AS AdmissionStandard,
		vSA.FirstName,
		vSA.LastName,
		SA.AdmissionDate,
		vSA.ClassID,
		vSA.AcademicId,
		vSA.DivisionId,
		vSA.Number
			
	FROM 
		sStudent.vStudentAcademic vSA
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = vSA.OrgId
		INNER JOIN sStudent.tStudentAdmission SA ON SA.StudentId=vSA.StudentId
		INNER JOIN sStudent.tStudentOther SO ON So.StudentId=vSa.StudentId
		INNER JOIN sCommon.tGenderMaster GM ON Gm.Id=SO.GenderID
	WHERE 
		(OM.OrgGroupId = @rOrgGroupId)
		AND (vSA.OrgId=@rOrgId)
		AND (vSA.BatchId=@rBatchId)
		AND ((vSA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
		AND ((vSA.ClassId=@rClassId) OR (@rClassId=0))
		AND ((vSA.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		AND ((vSA.RecordStatusId=@rRecordStatusId) OR (@rRecordStatusId=0))
	--ORDER BY OM.OrderIndex,vSA.DivisionOrder,vSA.RollNo
	ORDER by CASE WHEN @rOrderByTypeId = 1 then vSA.FirstName
				  WHEN @rOrderByTypeId = 2 then vSA.LastName
				  WHEN @rOrderByTypeId = 4 then (CASE ISNUMERIC(vSA.Code) WHEN 1 THEN REPLICATE(0 , 100 - LEN(vSA.Code)) + vSA.Code ELSE vSA.Code  END) END,	--add inner case
		CASE WHEN @rOrderByTypeId = 3 then vSA.RollNo END,
		CASE WHEN @rOrderByTypeId = 5 then SA.AdmissionDate END
			  ,OM.OrderIndex,vSA.DivisionOrder,vSA.RollNo
END
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 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
PRINT N'Altering Procedure [sWorkflow].[pWorkflowQueuesGet]...';


GO

 
ALTER  PROCEDURE [sWorkflow].[pWorkflowQueuesGet]
			 @rWorkflowFunctionalityId bigint=0,
			 @rFromDate date=null,
			 @rToDate date=null,
			 @rStatusId int=0,
			 @rCode nvarchar(20) ='',
			 @rDepartmentId int=0,
			 @rUserId bigint ,
			 @rApprovalRequestId int = 0
			 

	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
Declare @lRoleId int
Select @lRoleId = RoleId from [sSecurity].[tUserRole] Where UserId = @rUserId
--Select @lRoleId
SELECT
	AA.Id AS ApprovalActionId,
	ADM.Id AS DepartmentId,
	WFM.Title AS WorkFlowName,
	WFM.Id AS WorkFlowId,
	AR.Id AS ApprovalRequestId,
	ADM.Title AS DepartmentTitle,
	CONVERT(DATE,AR.CreatedDateTime, 103) AS CreatedDateTime,
	AR.ParticipantSourceTypeId AS ParticipantSourceTypeId,
	CASE WHEN ParticipantSourceTypeId= 2001 THEN SA.AcademicId WHEN ParticipantSourceTypeId= 95 THEN EM.Id END AS SourceId,
	CASE WHEN ParticipantSourceTypeId= 2001 THEN SA.Code WHEN ParticipantSourceTypeId= 95 THEN EM.Code END AS Code ,
	CASE WHEN ParticipantSourceTypeId= 2001 THEN SA.Name WHEN ParticipantSourceTypeId= 95 THEN EM.FirstName +' '+ EM.MiddleName +' ' +EM.LastName END AS Name ,
	AR.Remark AS Remark,
	(CASE ISNULL(asm.Id,'') WHEN '' THEN 3 ELSE asm.Id END) AS statusId,
	(CASE ISNULL(asm.title,'') WHEN '' THEN 'Pending' ELSE asm.title END) AS status,
	ISNULL(AA.ActionRemark, '') AS ActionRemark
			
		
from sWorkflow.tApprovalRequest AR
INNER JOIN sWorkflow.tFunctionalityApprovingDepartment FAD  ON AR.WorkflowFunctionalityId = FAD.WorkflowFunctionalityId 
INNER JOIN sWorkflow.tApprovingDepartmentMaster ADM ON FAD.ApprovingDepartmentId = ADM.Id
INNER JOIN sWorkflow.tFunctionalityApprovingAuthority FAA ON ADM.Id = FAA.FunctionalityApprovingDepartmentId AND AR.WorkflowFunctionalityId = FAA.WorkflowFunctionalityId
INNER JOIN sSecurity.tRole R ON R.Id = FAA.AuthoritySourceId AND FAA.AuthoritySourceTypeId = 2015
LEFT JOIN sWorkflow.tApprovalAction AA ON AA.ApprovalRequestId = AR.Id AND AA.ApprovingDepartmentId = ADM.ID
LEFT JOIN sWorkflow.tActionStatusMaster ASM ON ASM.Id = AA.ActionStatusId
INNER JOIN sWorkflow.tWorkflowFunctionalityMaster WFM ON AR.WorkflowFunctionalityId = WFM.Id
LEFT JOIN  sStudent.vStudentAcademic  SA ON SA.AcademicId = AR.ParticipantSourceId
LEFT JOIN  sHrm.tEmployeeMaster  EM ON EM.Id = AR.ParticipantSourceId
WHERE R.Id = @lRoleId
AND ((WFM.Id = @rWorkflowFunctionalityId) OR (@rWorkflowFunctionalityId =0)) 
AND ((Convert(Date,AR.CreatedDateTime)>= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
AND ((Convert(Date,AR.CreatedDateTime) <= @rToDate) OR (ISNULL(@rToDate,'') = ''))
AND((ASM.Id = @rStatusId) OR (@rStatusId =0))
AND (((SA.Code = @rCode) OR (@rCode ='')) OR ((EM.Code = @rCode) OR (@rCode = '')))
AND((ADM.Id = @rDepartmentId) OR (@rDepartmentId =0))
AND  ISNULL(EM.IsOtherUser,0) = 0
AND ((AR.Id = @rApprovalRequestId) OR (@rApprovalRequestId = 0))

UNION

SELECT
	AA.Id AS ApprovalActionId,
	ADM.Id AS DepartmentId,
	WFM.Title AS WorkFlowName,
	WFM.Id AS WorkFlowId,
	AR.Id AS ApprovalRequestId,
	ADM.Title AS DepartmentTitle,
	CONVERT(DATE,AR.CreatedDateTime, 103) AS CreatedDateTime,
	AR.ParticipantSourceTypeId AS ParticipantSourceTypeId,
	CASE WHEN ParticipantSourceTypeId= 2001 THEN SA.AcademicId WHEN ParticipantSourceTypeId= 95 THEN EM.Id END AS SourceId,
	CASE WHEN ParticipantSourceTypeId= 2001 THEN SA.Code WHEN ParticipantSourceTypeId= 95 THEN EM.Code END AS Code ,
	CASE WHEN ParticipantSourceTypeId= 2001 THEN SA.Name WHEN ParticipantSourceTypeId= 95 THEN EM.FirstName +' '+ EM.MiddleName +' ' +EM.LastName END AS Name ,
	AR.Remark AS Remark,
	(CASE ISNULL(asm.Id,'') WHEN '' THEN 3 ELSE asm.Id END) AS statusId,
	(CASE ISNULL(asm.title,'') WHEN '' THEN 'Pending' ELSE asm.title END) AS status,
	ISNULL(AA.ActionRemark, '') AS ActionRemark
			
		
from sWorkflow.tApprovalRequest AR
INNER JOIN sWorkflow.tFunctionalityApprovingDepartment FAD  ON AR.WorkflowFunctionalityId = FAD.WorkflowFunctionalityId 
INNER JOIN sWorkflow.tApprovingDepartmentMaster ADM ON FAD.ApprovingDepartmentId = ADM.Id
INNER JOIN sWorkflow.tFunctionalityApprovingAuthority FAA ON ADM.Id = FAA.FunctionalityApprovingDepartmentId AND AR.WorkflowFunctionalityId = FAA.WorkflowFunctionalityId
INNER JOIN sSecurity.tUser U ON U.Id = FAA.AuthoritySourceId AND FAA.AuthoritySourceTypeId = 1019
LEFT JOIN sWorkflow.tApprovalAction AA ON AA.ApprovalRequestId = AR.Id AND AA.ApprovingDepartmentId = ADM.ID
LEFT JOIN sWorkflow.tActionStatusMaster ASM ON ASM.Id = AA.ActionStatusId
INNER JOIN sWorkflow.tWorkflowFunctionalityMaster WFM ON AR.WorkflowFunctionalityId = WFM.Id
LEFT JOIN  sStudent.vStudentAcademic  SA ON SA.AcademicId = AR.ParticipantSourceId
LEFT JOIN  sHrm.tEmployeeMaster  EM ON EM.Id = AR.ParticipantSourceId
WHERE U.Id = @rUserId
AND ((WFM.Id = @rWorkflowFunctionalityId) OR (@rWorkflowFunctionalityId =0)) 
AND ((Convert(Date,AR.CreatedDateTime)>= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
AND ((Convert(Date,AR.CreatedDateTime) <= @rToDate) OR (ISNULL(@rToDate,'') = ''))
AND((ASM.Id = @rStatusId) OR (@rStatusId =0))
AND (((SA.Code = @rCode) OR (@rCode ='')) OR ((EM.Code = @rCode) OR (@rCode ='')))
AND((ADM.Id = @rDepartmentId) OR (@rDepartmentId =0))
AND  ISNULL(EM.IsOtherUser,0) = 0
AND ((AR.Id = @rApprovalRequestId) OR (@rApprovalRequestId = 0))

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


GO
CREATE PROCEDURE sAlert.pAlertQueueLogAdd
	@rId bigint = 0,
	@rMessageDate datetime = null,
	@rQueueMessage nvarchar(max) = '',
	@rEventId int = 0,
	@rAlertModeId tinyint = 0,
	@rOrgId smallint = 0,
	@rCreatedUserId bigint = 0

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	BEGIN TRANSACTION	
		IF(@rId = 0)	
		BEGIN
			INSERT INTO [sAlert].[tAlertQueueLog]
				([MessageDate]
			   ,[QueueMessage]
			   ,[EventId]
			   ,[AlertModeId]
			   ,[OrgId]
			   ,[CreatedUserId]
			   ,[CreatedDateTime])
		   VALUES
				(@rMessageDate
			   ,@rQueueMessage
			   ,@rEventId
			   ,@rAlertModeId
			   ,@rOrgId
			   ,@rCreatedUserId
			   ,sCommon.fGetDate())

			SELECT @@IDENTITY AS Result
		END
		ELSE
		BEGIN
			UPDATE [sAlert].[tAlertQueueLog] SET [QueueMessage] = @rQueueMessage WHERE AutoId = @rId

			SELECT @rId AS Result
		END
	COMMIT TRANSACTION
    END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
END
GO
PRINT N'Creating Procedure [sAlert].[pTransportAttendanceListGet]...';


GO


CREATE PROCEDURE [sAlert].[pTransportAttendanceListGet]	 
	@rBusRouteId int,
	@rRouteMode nvarchar(5),
	@rOrgGroupBatchId int,
	@rOrgGroupId int,
	@rAttendanceDate date,
	@rTemplate nvarchar(max),
	@rMailSubject nvarchar(500),
	@rIsPresent bit = 0,
	@rStudentIds nvarchar(max)
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

DECLARE @lTransportMode nvarchar(10)
IF(UPPER(@rRouteMode) = 'IN')
    SET @lTransportMode = 'Pickup'
ELSE
    SET @lTransportMode = 'Drop'

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,
		CASE WHEN @rIsPresent = 0 THEN --for absent
		REPLACE (REPLACE (			
		REPLACE(REPLACE(REPLACE(@rTemplate,'[Name]',SC.Name),
		'[Class]',SC.ClassName),
		'[Division]',SC.DivisionName),
		'[AbsentDates]',ATR.AttendanceDate),
		'[TransportMode]',@lTransportMode)
		ELSE --for present
		REPLACE(REPLACE (					
		REPLACE(REPLACE(REPLACE(@rTemplate,'[Name]',SC.Name),
		'[Class]',SC.ClassName),
		'[Division]',SC.DivisionName),
		'[PresentDates]',ATR.AttendanceDate),
		'[TransportMode]',@lTransportMode)			
		END
			AS MsgText,
		@rMailSubject AS Subject,
		SC.AcademicId AS SourceId,
		2001 AS SourceTypeId,
		SC.OrgId,
		SC.OrgGroupId,
		SC.AcademicId AS ReceiverSourceId,
		2001 AS ReceiverSourceTypeId,
		SC.ClassName AS Class,
		SC.DivisionName AS Division,
		SC.WhatsAppContactNo
	FROM 
		sStudent.vStudentCommunication SC
		INNER JOIN sTransport.tAssignRoute  AR ON SC.StudentId = AR.SourceId AND AR.SourceTypeId=2003
		INNER JOIN sTransport.tBusRouteDestinationMaster BRDM 
		ON (BRDM.Id = AR.PickupDestinationId AND UPPER(@rRouteMode)='IN')OR(BRDM.Id = AR.DropDestinationId AND UPPER(@rRouteMode)='OUT')
		INNER JOIN sTransport.tBusRouteMaster BR ON BR.Id=BRDM.BusRouteId
		LEFT JOIN sTransport.tAttendanceRegister ATR ON ATR.SourceId=SC.StudentId 
			
	WHERE 
		BRDM.BusRouteId = @rBusRouteId
		AND BR.OrgGroupBatchId=@rOrgGroupBatchId
		AND SC.OrgGroupBatchId=@rOrgGroupBatchId 
		AND BR.OrgGroupId=@rOrgGroupId
		AND ATR.AttendanceDate=@rAttendanceDate
		AND (
        (@rRouteMode = 'IN' AND  ISNULL(ATR.IsPresentPickup, 0) = @rIsPresent) OR
        (@rRouteMode = 'OUT' AND  ISNULL(ATR.IsPresentDrop, 0) = @rIsPresent)
		)
		AND SC.IsActiveBatch = 1
        AND SC.StatusId = 1
		AND SC.StudentId IN( SELECT cast(item as bigint) FROM  sCommon.fnsplit(@rStudentIds,','))

	ORDER BY SC.ClassOrderIndex,SC.DivisionOrderIndex,SC.RollNo
END
GO
PRINT N'Creating Procedure [sCommunication].[pPollListTaskPermissionwiseGet]...';


GO
CREATE PROCEDURE sCommunication.pPollListTaskPermissionwiseGet
	 @rId bigint = 0,
	 @rOrgGroupBatchId int,
	 @rCreatedUserId bigint,
	 @rSourceTypeId smallint,
	 @rCreatedDateTime datetime=''

	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
	SELECT 
	
			P.Id as PollId,
			P.Title AS PollTitle,
			P.Remark AS PollRemark,
			P.IsOwnAnswer,
			P.IsOpen,
			P.CreatedDateTime AS PollCreatedDateTime,
			ISNULL(PR.CreatedUserId,0) AS PollResultUserId,
			(SELECT  ISNULL(Count(1),0) FROM sCommunication.tPollResult PR WHERE PR.PollId=P.Id) AS TotalPollVote,
			(SELECT U.DisplayTitle FROM sSecurity.tUser U WHERE U.Id = P.CreatedUserId) AS DisplayTitle			
  FROM 
            sCommunication.tPoll P			
            LEFT JOIN sCommunication.tPollResult PR ON P.Id = PR.PollId AND  PR.CreatedUserId = @rCreatedUserId
  WHERE 
  
      ((P.Id = @rId) OR (@rId = 0))
    AND ((P.CreatedUserId = @rCreatedUserId) OR (@rCreatedUserId = 0))
	AND ((P.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
	AND ((convert(date,P.CreatedDateTime)=CONVERT(date,@rCreatedDateTime)) OR (ISNull(@rCreatedDateTime,'')=''))

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


GO

CREATE PROCEDURE [sFee].[pRptReceiptSummaryUserPayTypeWiseDetailsGet]  
	@rReportId int=0,
	@rReceiptBookId int=0,
	@rAdmissionCategoryId int=0,
	@rClassId int=0,
	@rDivisionId int=0,
	@rFromDate date='',
	@rToDate date='',
	@rFromReceiptNo int=0,
	@rToReceiptNo int=0,  
	@rBatchId int = 0,
	@rUserId bigint=0,
	@rBuilder1 nvarchar(max)=0,
	@rBuilder2 nvarchar(max)=0,
	@rIsDetail bit=0,
	@rIsCancel bit=0,
	@rOrgId int = 0,
	@rOrgGroupBatchId int = 0,
	@rStatusId int=0,
	@rPaytypeId int=0,
	@rCommonBatch nvarchar(100)='',
	@rDepartmentId int=0,
	@rFromRollNo int=0,
	@rToRollNo int=0,
	@rCode nvarchar(20)='',
	@rIsFilter bit=1,
	@rIsHeader bit=0,
	@rCreatedUserName nvarchar(100)='',
	@rFeeHeadId nvarchar(max) = '',
	@rIsDisplayOrgGroup bit=0,
	@rIsDiscount bit = 0,
	@rFeeId nvarchar(max) = '',
	@rFilterId int=1,
	@rCustomGroupId smallint = 0,
	@rOrgGroupId int=0,
	@rFeeStatusId int=0,
    @rBankName nvarchar(100)='',
    @rOrgIds nvarchar(max) = '',
    @rBankNames nvarchar(max) = '',
	@rFromChequeClearDate Date = '',
	@rToChequeClearDate Date = '' ,
	@rClassStatusId int=0 ,
	@rPayTypeIds nvarchar(max) = '',
	@rUserAcessUserId bigint = 0,
	@rReceiptBookIds nvarchar(max) = ''

 WITH EXECUTE AS CALLER  
AS  
SET NOCOUNT ON  
      
BEGIN   
   SELECT   
		@rBuilder1 AS Builder1,  
		@rBuilder2 AS Builder2,  
		@rIsDetail AS IsDetail,  
		R.IsObsolete AS IsCancel,   
		@rIsFilter As IsFilter,  
		@rIsHeader As IsHeader,  
		@rIsDisplayOrgGroup AS IsDisplayOrgGroup,  
		R.Id AS ReceiptId,  
		R.ReceiptNumber,  
		SA.ClassId,  
		--SA.ClassName,  
		SA.DivisionId,  
		--SA.DivisionName,  
		SA.ClassName+' - '+SA.DivisionName AS ClassDivision,  
		SA.RollNo,  
		SA.Code,  
		SA.Name,  
		ISNULL(PTM.Title,'') AS PayType,    
		CASE WHEN ISNULL(R.ChequeNo,'') != '' THEN R.ChequeNo ELSE CONVERT(nvarchar(20),R.PaymentTransactionId) END AS ChequeNo,
		ISNULL(R.BankName,'') AS BankName,  
		R.ReceiptAmount,  
		R.ReceiptDate,  
		--CASE  WHEN @rReportId = 30611 AND R.ChequeClearDate IS NOT NULL THEN R.ChequeClearDate ELSE R.ReceiptDate END AS ReceiptDate,  
		R.CreatedUserId,  
		ISNULL(U.LoginTitle,'') AS UserName,  
		ISNULL(RBM.Title,'') AS ReceiptBookTitle,  
		ISNULL(RBM.BankName,'') AS ReceiptBookBank,  
		ISNULL(RBM.BankAccountNumber,'') AS BankAccountNumber,  
		ISNULL(R.ReceiptBookId,'0') As ReceiptBookId,  
		ISNULL((CASE @rReportId WHEN 20461 THEN [sFee].[fReceiptFeeDetailGet](R.Id)  --Need to check
		ELSE '' END),'') AS FeeDetail,  
		R.Remark,  
		R.DiscountAmount,  
		ISNULL(RBM.OrderIndex,0) AS ReceiptBookOrderIndex,  
		SA.OrgId,  
		SA.OrganizationName,  
		ISNULL(R.AmountAfterDiscount,0) AS AmountAfterDiscount,  
		ISNULL(R.CGSTPercentage,0) AS CGSTPercentage,  
		ISNULL(R.SGSTPercentage,0) AS SGSTPercentage,  
		ISNULL(R.CGSTAmount,0) AS CGSTAmount,  
		ISNULL(R.SGSTAmount,0) AS SGSTAmount,  
		@rCustomGroupId AS CustomGroupId,  
		SA.OrgGroupBatchId AS BatchId,  
		SA.BatchName,  
		R.ChequeDate,  
		R.ChequeClearDate ,
		SA.GenderId,
		ISNULL(FM.Id,0) AS FeeId,
		FM.Code AS FeeCode,  
		ISNULL(FM.Title,'') AS FeeTitle,
		FM.OrderIndex AS FeeOrderIndex,
		R.CancelStatusRemark AS CancelRemark,
		FM.FeeHeadId,
		FHM.Title AS FeeHeadName,
		RD.Amount AS DetailAmount
	FROM   
		   sFee.tReceipt R  
		  INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id   
		  INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id  
		  INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id
		  INNER JOIN sFee.tFeeHeadMaster FHM ON FM.FeeHeadId = FHM.Id  

		  INNER JOIN sStudent.vStudentAcademic SA  
		   ON SA.AcademicId=R.SourceId AND ((SA.OrgId=@rOrgId) OR (@rOrgId=0)) 

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

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


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


GO
CREATE PROCEDURE [sHrm].[pRptEmployeeAvailableLeaveWithPay]

		@rBuilder1 nvarchar(max)='',
		@rBuilder2 nvarchar(max)='',
		@rDepartmentId int,
		@rEmployeeGradeId int,
		@rEmployeeStatusId int=0,
		@rEmployeeCode nvarchar (200),
		@rEmployeeName nvarchar(200),
		@rBatchId int,
		@rOrgId int,
		@rLeaveTypeIds nvarchar(50) = '',
		@rEmployeeId int=0

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

	SELECT
		@rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,
		EM.Code AS EmployeeCode,
		EM.EmployeeName,
		EM.EmployeeId,
		EM.DepartmentName,
		EM.EmployeeGrade,
		ESO.BasicPay,
		LTM.Id AS LeaveTypeId,
		LTM.Title AS LeaveType,
		(SELECT	(ISNULL(LB.BalanceLeave,0) - ISNULL(SUM(NoOfLeave),0)) AS AvailableBalance
		 FROM sHrm.tLeaveBalance LB
			  LEFT JOIN sHrm.tLeave L ON LB.EmployeeId=L.EmployeeId AND LB.BatchId = L.BatchId AND LB.LeaveTypeId = L.LeaveTypeId AND L.StatusId = 550
		 WHERE LB.BatchId = @rBatchId AND LB.EmployeeId=EM.EmployeeId AND LB.LeaveTypeId=LTM.Id
		 GROUP BY LB.BalanceLeave) AS AvailableBalance
	FROM
		sHrm.vEmployeeCommonDetail EM
		LEFT JOIN sHrm.tEmployeeStatutoryAndOther ESO ON ESO.EmployeeId=EM.EmployeeId
		LEFT JOIN sHrm.tLeaveTypeMaster LTM ON LTM.OrgId=EM.OrgId AND LTM.IsObsolete = 0 AND IsLWP=0
	WHERE
		EM.OrgID = @rOrgId
		AND ((EM.EmployeeGradeId=@rEmployeeGradeId) OR (@rEmployeeGradeId=0))
		AND ((EM.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
		AND ((EM.Code like @rEmployeeCode) OR (@rEmployeeCode=''))
		AND ((EM.EmployeeName like @rEmployeeName) OR (@rEmployeeName=''))
		AND ((EM.EmployeeId=@rEmployeeId) OR (@rEmployeeId=0))
		AND ((EM.EmployeeStatusId=@rEmployeeStatusId) OR (@rEmployeeStatusId=0))
		AND ((EM.DepartmentId= @rDepartmentId ) OR (@rDepartmentId= 0 ))
		AND (ISNULL(LTM.Id,0) IN (SELECT cast(item as int) FROM sCommon.fnsplit(@rLeaveTypeIds,',')) OR ISNULL(@rLeaveTypeIds, '')='')
	ORDER BY EM.Code

END
GO
PRINT N'Creating Procedure [sProcurement].[pRptStockIssueStudentReceipt]...';


GO

 
CREATE PROCEDURE [sProcurement].[pRptStockIssueStudentReceipt]
 
	@rId int = 0,
	@rStoreLocationId int = 0,
	@rMainGroupId int=0,
	@rSubGroupId int=0,
	@rItemCode nvarchar(50)='',
	@rItemName nvarchar(50)='',
	@rOrgGroupId int=0,
	@rBuilder1 nvarchar(max)='',
	@rBuilder2 nvarchar(max)='',
	@rReportId int=0,
	@rStockItemCategoryId int=0,
	@rFromDate date='',
	@rTodate date='',
	@rToDepartmentId int =0,
	@rNumber nvarchar(10)='',
	@rAcademicId bigint = 0,
	@rOrgId smallint = 0,
	@rBatchId int = 0
	
WITH EXECUTE AS CALLER
AS
BEGIN
	
	SET NOCOUNT ON;
	SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED
	Declare @lIDConfigValue nvarchar(50)=''
	DECLARE @lCurrencyCode nvarchar(20) = ''
	DECLARE @lCurrencyTitle nvarchar(100) = ''
	SELECT @lIDConfigValue =ItemValue From sConfig.tConfigurationSetup
	WHERE ConfigurationId = 236 AND SourceId = @rOrgGroupId
	SELECT  @lCurrencyCode = [sFinanceCommon].[fDefaultCurrencyCodeGet](@rOrgGroupId) 
	SELECT  @lCurrencyTitle = [sFinanceCommon].[fDefaultCurrencyTitleGet](@rOrgGroupId) 
       SELECT  
			@rBuilder1 AS Builder1,
			SIM.Code AS ItemNumber,
			SIM.Title AS ItemName,		
			SI.IssuedByName,	
			SI.Number, 	
			SI.CreatedDateTime AS IssuedDate,
			ID.IssuedQuantity,
			ID.RequestedQuantity,
			SM.FirstName +' '+SM.MiddleName As StudentName,
			Sm.Code AS StudentCode,
			SG.Code AS ItemSubGroup,
			SG.Id AS ItemSubGroupId,
			OM.DisplayTitle,
			BM.Title AS BatchTitle,
			CM.Title +'-'+ DM.TItle As Class,
			(SELECT ISNULL(SUM(AvailableQuantity),0) FROM sProcurement.tStockBatch SB 
		    WHERE SB.StockItemId = SIM.Id 
		    AND ((SB.StorelocationId = @rStoreLocationId) OR (@rStoreLocationId = 0))
			) AS Quantity ,
			A.OrgId,
			A.BatchId,
			ISNULL(CAST(SIP.WeightedAverageCost AS DECIMAL(18, 2)), '0') AS WeightedAverageCost,
			@lIDConfigValue AS IdNoLabel,
			((ISNULL(CAST(SIP.WeightedAverageCost AS DECIMAL(18, 2)), '0')) * (ID.IssuedQuantity)) AS Amount,

			(sFinanceCommon.fNumberToWordsWithDecimal(
			((ISNULL(CAST(SIP.WeightedAverageCost AS DECIMAL(18, 2)), '0')) * (ID.IssuedQuantity)),1,2,SI.OrgGroupId)
			) AS AmountInWords,
			ISNULL(SI.PayTypeId,0) as PayTypeId,
			 ISNULL(PTM.Title,'Not Charged') AS PayType,
			ISNULL(SI.ReceiptNumber,0) as ReceiptNumber,
			ISNULL(SI.BankName,'') as BankName,
			ISNULL(SI.ChequeNo,'') as ChequeNo,
			ISNULL(SI.ChequeDate,'') as ChequeDate,
			@lCurrencyCode AS CurrencyCode,
			@lCurrencyTitle AS CurrencyTitle

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


SET ANSI_NULLS ON
GO
PRINT N'Creating Procedure [sProcurement].[pStockIssueDepositAdjustmentAdd]...';


GO

Create PROCEDURE [sProcurement].[pStockIssueDepositAdjustmentAdd]
	
	@rId bigint, 
	@rAdjustmentId bigint,
	@rDepositHeadId int,
	@rAmount decimal(12,2),
	@rAdjustmentDate date,
	@rRemark nvarchar(200),
	@rCreatedUserId bigint,
	@rOrgGroupId smallint,
	@rAcademicId bigint,
	@rFeeDepositExpenseTypeId int,
	@rOrgGroupBatchId int,
	@rReferenceSourceId bigint
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

DECLARE @lStudentId bigint

BEGIN	
BEGIN TRY
BEGIN TRANSACTION	
 DECLARE @rAdjustmentNumber Int
 Select @rAdjustmentNumber=(MAX(AdjustmentNumber) +1) from sFee.tDepositAdjustment
DECLARE @lNextNumber bigint 
IF NOT EXISTS(Select Id From sFee.tDepositAdjustment Where ReferenceSourceId=@rReferenceSourceId)
BEGIN
EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sFee.tDepositAdjustment', 0, 1, 1,@outNextNumber = @lNextNumber output 
	INSERT INTO sFee.tDepositAdjustment
		(
		Id,
		DepositHeadId,
		Amount,
		AdjustmentDate,
		Remark,
		CreatedUserId,
		CreatedDateTime,
		AcademicId,
		FeeDepositExpenseTypeId,
		AdjustmentNumber,
		OrgGroupBatchId,
		ReferenceSourceTypeId,
		ReferenceSourceId
		)
	VALUES
		(
		@lNextNumber,
		@rDepositHeadId,
		@rAmount,
		@rAdjustmentDate,
		@rRemark,
		@rCreatedUserId,
		sCommon.fGetDate(),
		@rAcademicId,
		@rFeeDepositExpenseTypeId,
		@rAdjustmentNumber,
		@rOrgGroupBatchId,
		2039 ,
		@rReferenceSourceId 
		) 
		SELECT @lNextNumber  AS Result   
	END	
ELSE
    BEGIN
    --SET @lNextNumber = @rId
	    UPDATE sFee.tDepositAdjustment
	    SET
	    DepositHeadId=@rDepositHeadId,
		Amount=@rAmount,
		AdjustmentDate=@rAdjustmentDate,
		Remark=@rRemark,
		UpdatedUserId=@rCreatedUserId,
	    UpdatedDateTime=sCommon.fGetDate(),
	    AcademicId=@rAcademicId,
	    FeeDepositExpenseTypeId=@rFeeDepositExpenseTypeId,
		AdjustmentNumber=@rAdjustmentNumber,
		OrgGroupBatchId=@rOrgGroupBatchId,
		ReferenceSourceTypeId=2039,
		ReferenceSourceId=@rReferenceSourceId
	    WHERE ReferenceSourceId = @rAdjustmentId 
	    SELECT 11 AS Result
	 END  
	COMMIT TRANSACTION
		
END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
	
END
GO
PRINT N'Creating Procedure [sProcurement].[pStockKitDetailAdd]...';


GO

 CREATE PROCEDURE [sProcurement].[pStockKitDetailAdd]
	@rStockKitId [int],
	@rStockKitDeatilXml [nvarchar](max)
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	DECLARE @loIdoc INT
	DECLARE @lStockKitDetailCurrentId INT
	DECLARE @lCount INT
	DECLARE @lNextNumber int
		
	EXEC sp_xml_preparedocument @loIdoc OUTPUT, @rStockKitDeatilXml
	CREATE TABLE #TempStockKitDetail (StockKitId INT,StockItemId int,Quantity DECIMAL(22, 6));

	BEGIN TRY
	BEGIN TRANSACTION
		INSERT INTO #TempStockKitDetail (StockKitId,StockItemId,Quantity)
		SELECT  
			StockKitId,
			StockItemId,
			Quantity
		FROM OPENXML (@loIdoc, '/StockKit/StockKitDetail', 1)
			WITH ( 
					StockKitId INT, 
					StockItemId INT,
					Quantity DECIMAL(22, 6)
				  )

		DELETE SKD  
		From sProcurement.tStockKitDetail SKD
		Left JOIN #TempStockKitDetail Temp On SKD.StockKitId=Temp.StockKitId AND TEMP.StockItemId=SKD.StockItemId 
		 Where Temp.StockKitId is null AND SKD.StockKitId =@rStockKitId


		UPDATE SKD
		Set SKD.Quantity=Temp.Quantity
		From sProcurement.tStockKitDetail SKD
		Inner Join #TempStockKitDetail Temp  ON Temp.StockKitId=SKD.StockKitId  AND TEMP.StockItemId=SKD.StockItemId 


		INSERT INTO sProcurement.tStockKitDetail
			(
				StockKitId,
				StockItemId,
				Quantity
			)
		SELECT  
			@rStockKitId,
			Temp.StockItemId,
			Temp.Quantity
		FROM #TempStockKitDetail Temp
		Left JOIN sProcurement.tStockKitDetail SKD On SKD.StockKitId=Temp.StockKitId AND TEMP.StockItemId=SKD.StockItemId 
		Where SKD.StockKitId is null

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

END
GO
PRINT N'Creating Procedure [sProcurement].[pStockKitDetailGet]...';


GO
CREATE PROCEDURE [sProcurement].[pStockKitDetailGet]
	
	 @rStockKitId int = 0,
	 @rStockItemId int=0,
	 @rOrgGroupId int=0,
	 @rStoreLocationId int=0,
	 @rStockKitTitle nvarchar(100)='',
	 @rStockKitCode nvarchar(20)=''
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	SET @rStockKitCode = sCommon.fSearchStringGet(@rStockKitCode)
	SET @rStockKitTitle = sCommon.fSearchStringGet(@rStockKitTitle)
END	 

BEGIN 

	SELECT 
	
	SKD.StockKitId AS StockKitId, 
	SKD.StockItemId AS StockItemId,
	SKD.Quantity AS Quantity,
	ESIM.Code AS StockItemCode,
	ESIM.Title AS StockItemName,
	ISUBM.Title AS ItemSubGroup,
	ESIM.ItemSubGroupId as ItemSubGroupId

     
  FROM sProcurement.tStockKitDetail SKD
  INNER JOIN sProcurement.tStockKitMaster SKM ON SKM.Id=SKD.StockKitId
  Inner Join sIp.vExtStockItemMaster ESIM ON ESIM.Id=SKD.StockItemId  
  Inner Join  [sIp].[tItemSubGroupMaster] ISUBM ON ESIM.ItemSubGroupId=ISUBM.Id
             
  WHERE 
	  (SKM.OrgGroupId = @rOrgGroupId or @rOrgGroupId=0)	
	  AND SKM.StoreLocationId=@rStoreLocationId
      AND ((SKM.Id = @rStockKitId) OR (@rStockKitId = 0))
      AND ((SKM.Code like @rStockKitCode) OR (ISNULL(@rStockKitCode,'') = ''))    
      AND ((SKM.Title like @rStockKitCode) OR (ISNULL(@rStockKitCode,'') = ''))  
	  AND (ESIM.Id =@rStockItemId or @rStockItemId=0)
END
GO
PRINT N'Creating Procedure [sProcurement].[pStockKitIssueDetailAdd]...';


GO
create PROCEDURE [sProcurement].[pStockKitIssueDetailAdd]
	@rStockKitIssueDeatilXml [nvarchar](max)
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
BEGIN TRY
	BEGIN TRANSACTION
	DECLARE @loDoc INT
		
	EXEC sp_xml_preparedocument @loDoc OUTPUT, @rStockKitIssueDeatilXml
		INSERT INTO [sProcurement].[tStockKitIssueDetail]
				   ([StockIssueId]
				   ,[StockKitId])
		SELECT
			StockIssueId,
			StockKitId
		FROM OPENXML (@loDoc, '/Table/StockKitDetail', 1)
		WITH ( 
				StockIssueId int,
				StockKitId int
			  ) 



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



END
GO
PRINT N'Creating Procedure [sProcurement].[pStockKitMasterAdd]...';


GO


CREATE PROCEDURE [sProcurement].[pStockKitMasterAdd]
	 
	@rOrgGroupId int,	
	@rId int,
	@rNumber int,
	@rCode nvarchar(20),
	@rTitle nvarchar(100),
	@rCreatedUserId bigint,
	@rOrderIndex smallint,
	@rIsObsolete bit,
	@rStoreLocationId int,
	@rStockKitDeatilXml [nvarchar](max)=''
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	-- For New Entry
	print 1
	IF(@rId = 0)
		BEGIN
			If Exists(select Id from sProcurement.tStockKitMaster where Code=@rCode AND OrgGroupId= @rOrgGroupId AND StoreLocationId=@rStoreLocationId)
			BEGIN
				select -101 as Result
				RETURN
			END 
			If Exists(select Id from sProcurement.tStockKitMaster where Number=@rNumber AND OrgGroupId= @rOrgGroupId AND StoreLocationId=@rStoreLocationId)
			BEGIN
				select -102 as Result
				RETURN
			END
			If Exists(select Id from sProcurement.tStockKitMaster where OrderIndex=@rOrderIndex AND OrgGroupId= @rOrgGroupId AND StoreLocationId=@rStoreLocationId)
			BEGIN
				select -103 as Result
				RETURN
			END
		 
	 
		END
	-- For Update Entry	
	ELSE
		BEGIN
			If  Exists(select Id from sProcurement.tStockKitMaster where Code=@rCode AND Id<>@rId AND OrgGroupId=@rOrgGroupId AND StoreLocationId=@rStoreLocationId)
			Begin
				select -101 as Result
				RETURN
			End
			If  Exists(select Id from sProcurement.tStockKitMaster where Number=@rNumber AND Id<>@rId AND OrgGroupId=@rOrgGroupId AND StoreLocationId=@rStoreLocationId )
			Begin
				select -102 as Result
				RETURN
			End
			If  Exists(select Id from sProcurement.tStockKitMaster where OrderIndex=@rOrderIndex AND Id<>@rId AND OrgGroupId=@rOrgGroupId AND StoreLocationId=@rStoreLocationId )
			Begin
				select -103 as Result
				RETURN
			End
		END
BEGIN TRY
BEGIN TRANSACTION	
	IF(@rId = 0)	
	 BEGIN
		DECLARE @lNextNumber INT     
		EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sProcurement.tStockKitMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
		print @lNextNumber
		INSERT INTO  sProcurement.tStockKitMaster
			(
				 OrgGroupId,
				 Id,
				 Number,
				 Code,
				 Title,
				 CreatedUserId,
				 CreatedDateTime,
				 OrderIndex,
				 IsObsolete,
				 StoreLocationId
			)
		VALUES
			(
				@rOrgGroupId,
				@lNextNumber,
				@rNumber,
				@rCode,
				@rTitle,
				@rCreatedUserId,
				sCommon.fGetDate(),
				@rOrderIndex,
				@rIsObsolete,
				@rStoreLocationId
			)
			EXECUTE [sProcurement].[pStockKitDetailAdd]  @rStockKitId = @lNextNumber,@rStockKitDeatilXml=@rStockKitDeatilXml
			SELECT 1 AS Result       
	END	 
	ELSE
	BEGIN
		 SET @lNextNumber = @rId
			UPDATE sProcurement.tStockKitMaster
			SET
				 Number=@rNumber,
				 Code=@rCode,
				 Title=@rTitle,
				 OrderIndex=@rOrderIndex,
				 IsObsolete=@rIsObsolete,
				 UpdatedUserId=@rCreatedUserId,
				 UpdatedDateTime=sCommon.fGetDate(),
				 StoreLocationId=@rStoreLocationId
	      
			  WHERE Id = @rId 	
			 EXECUTE [sProcurement].[pStockKitDetailAdd]  @rStockKitId = @lNextNumber,@rStockKitDeatilXml=@rStockKitDeatilXml
			  SELECT 11 AS Result    
	END  
	COMMIT TRANSACTION
		
END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Creating Procedure [sProcurement].[pStockKitMasterGet]...';


GO

CREATE PROCEDURE [sProcurement].[pStockKitMasterGet]
	
	 @rId int = 0,
	 @rTitle nvarchar(100)='',
	 @rCode nvarchar(20)='',
	 @rOrgGroupId int,
	 @rStoreLocationId int
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

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

BEGIN 

	SELECT 
	
	CTM.Id, 
	CTM.Code,
	CTM.Number,
	CTM.Title,
	CTM.IsObsolete,
	CTM.OrderIndex,
	OrgGroupId,
	CreatedUserId,
	StoreLocationId,
	CreatedDateTime
     
  FROM sProcurement.tStockKitMaster CTM         
             
  WHERE 
	  CTM.OrgGroupId = @rOrgGroupId		
	  AND StoreLocationId=@rStoreLocationId
      AND ((CTM.Id = @rId) OR (@rId = 0))
      AND ((CTM.Code like @rCode) OR (ISNULL(@rCode,'') = ''))    
      AND ((CTM.Title like @rTitle) OR (ISNULL(@rTitle,'') = '')) 
	  Order By CTM.OrderIndex DESC 
	  
	EXECUTE [sProcurement].[pStockKitDetailGet]   @rStockKitId=@rId,@rOrgGroupId =@rOrgGroupId,@rStoreLocationId=@rStoreLocationId,@rStockKitTitle=@rTitle,@rStockKitCode=@rCode
	  
END
GO

PRINT N'Update complete.';


GO

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



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




GO
PRINT N'Altering Table [sAcademic].[tOnlineMeetingAccount]...';


GO
ALTER TABLE [sAcademic].[tOnlineMeetingAccount] ALTER COLUMN [JWTToken] NVARCHAR (MAX) NULL;


GO
ALTER TABLE [sAcademic].[tOnlineMeetingAccount]
    ADD [OAuthAccountId]    NVARCHAR (MAX) NULL,
        [OAuthClientId]     NVARCHAR (MAX) NULL,
        [OAuthClientSecret] NVARCHAR (MAX) NULL;


GO
PRINT N'Altering Table [sAcademic].[tOnlineMeetingSettings]...';


GO
ALTER TABLE [sAcademic].[tOnlineMeetingSettings] ALTER COLUMN [JWTToken] NVARCHAR (MAX) NULL;


GO
ALTER TABLE [sAcademic].[tOnlineMeetingSettings]
    ADD [OAuthAccountId]    NVARCHAR (MAX) NULL,
        [OAuthClientId]     NVARCHAR (MAX) NULL,
        [OAuthClientSecret] NVARCHAR (MAX) NULL;


GO
PRINT N'Altering Table [sBiometric].[tShiftMasterCloud]...';


GO
ALTER TABLE [sBiometric].[tShiftMasterCloud]
    ADD [IsStopInTimeAlertTime] BIT      NULL,
        [StopInTimeAlertTime]   DATETIME NULL;


GO
PRINT N'Altering Table [sCanteen].[tCanteenIssue]...';


GO
ALTER TABLE [sCanteen].[tCanteenIssue]
    ADD [PayTypeId]  TINYINT        NULL,
        [ChequeNo]   NVARCHAR (40)  NULL,
        [BankName]   NVARCHAR (200) NULL,
        [ChequeDate] DATE           NULL;


GO
PRINT N'Altering Table [sLibrary].[tNewspaperLog]...';


GO
ALTER TABLE [sLibrary].[tNewspaperLog]
    ADD [NewspaperAmount] DECIMAL (12, 2) NULL;


GO
PRINT N'Altering Table [sSetup].[tOrgGroupMaster]...';


GO
ALTER TABLE [sSetup].[tOrgGroupMaster]
    ADD [ChannelPartner] NVARCHAR (200) NULL,
        [BrandConfig]    NVARCHAR (MAX) NULL;


GO
PRINT N'Creating Table [sAudit].[tStockOperationLog]...';


GO
CREATE TABLE [sAudit].[tStockOperationLog] (
    [AutoId]          BIGINT         IDENTITY (1, 1) NOT NULL,
    [ScreenId]        SMALLINT       NOT NULL,
    [OperationId]     SMALLINT       NOT NULL,
    [SourceTypeId]    SMALLINT       NOT NULL,
    [SourceId]        BIGINT         NOT NULL,
    [OperationRemark] NVARCHAR (MAX) NOT NULL,
    [CreatedUserId]   BIGINT         NOT NULL,
    [CreatedDateTime] DATETIME       NOT NULL,
    CONSTRAINT [PK_tStockOperationLog] PRIMARY KEY CLUSTERED ([AutoId] ASC)
);


GO

PRINT N'Altering Procedure [sAcademic].[pMeetingAccountAdd]...';


GO

 
ALTER PROCEDURE [sAcademic].[pMeetingAccountAdd]
	 
        @rId bigint = 0,
		@rEmployeeId bigint=0,
		@rMeetingProviderId int,
		@rAccountName nvarchar(200)='',
		@rAccountEmail nvarchar(200)='',
		@rAccountPassword nvarchar(200)='',
		@rAPIKey nvarchar(100)='',
		@rAPISecret nvarchar(100)='',
		@rWebAPIKey nvarchar(100)='',
		@rWebAPISecret nvarchar(100)='',
		@rCreatedUserId bigint,
		@rOrgGroupId Smallint,
		@rJWTToken nvarchar(MAX)='',
		@rIsObsolete  bit =0,
		@rOAuthAccountId nvarchar(max)='',
		@rOAuthClientId nvarchar(max)='',
		@rOAuthClientSecret nvarchar(max)=''

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

	BEGIN TRY
	 
	 BEGIN TRANSACTION	
	 DECLARE @lNextNumber BIGINT 
	IF EXISTS(SELECT 1 FROM sAcademic.tOnlineMeetingAccount WHERE AccountName = @rAccountName AND Id != @rId AND OrgGroupId = @rOrgGroupId)
		BEGIN
			SELECT -202 As Result
		END	
	ELSE
	BEGIN
	IF(@rId = 0)	
	BEGIN
		
	 
	EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sAcademic.tOnlineMeetingAccount', 0, 1, 1,@outNextNumber = @lNextNumber output
	--Print @lNextNumber

	INSERT INTO sAcademic.tOnlineMeetingAccount
		(
			Id
           ,MeetingProviderId
           ,EmployeeId
           ,AccountName
           ,AccountEmailId
           ,AccountPassword
           ,APIKey
           ,APISecret
           ,WebAPIKey
           ,WebAPISecret
           ,CreatedUserId
           ,CreatedDateTime
		   ,OrgGroupId
		   ,JWTToken
		   ,IsObsolete
		   ,OAuthAccountId
		   ,OAuthClientId
		   ,OAuthClientSecret
		)
	VALUES
		(
			@lNextNumber,
			@rMeetingProviderId,
			@rEmployeeId,
			@rAccountName,
			@rAccountEmail,
			@rAccountPassword,
			@rAPIKey,
			@rAPISecret,
			@rWebAPIKey,
			@rWebAPISecret,
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rOrgGroupId,
			@rJWTToken,
			@rIsObsolete,
			@rOAuthAccountId,
		    @rOAuthClientId,
		    @rOAuthClientSecret
		)
		    SELECT @lNextNumber AS Result
	END	 
	ELSE
	 BEGIN
	 SET @lNextNumber = @rId

	    UPDATE sAcademic.tOnlineMeetingAccount
	    SET
        	Id = @rId 
           ,EmployeeId = @rEmployeeId
           ,AccountName = @rAccountName
           ,AccountEmailId = @rAccountEmail
           ,AccountPassword = @rAccountPassword
           ,APIKey = @rAPIKey
           ,APISecret = @rAPISecret
		   ,WebAPIKey = @rWebAPIKey
           ,WebAPISecret = @rWebAPISecret
		   ,UpdatedUserId = @rCreatedUserId
		   ,UpdatedDateTime = sCommon.fGetDate()
		   ,OrgGroupId = @rOrgGroupId
		   ,JWTToken = @rJWTToken
		   ,IsObsolete = @rIsObsolete
		   ,OAuthAccountId = @rOAuthAccountId
		   ,OAuthClientId = @rOAuthClientId
		   ,OAuthClientSecret = @rOAuthClientSecret
	     WHERE Id = @rId
	      
		DECLARE @tOnlineLearningAccount TABLE  
		(  
		Id INT IDENTITY(1, 1),  
		OnlineLearningId BIGINT
		)   

		INSERT INTO @tOnlineLearningAccount
		SELECT Id
		FROM 
		 sAcademic.tOnlineLearning 
		WHERE MeetingAccountId = @rId AND IsCompleted = 0
		
		DECLARE @lCount int=1
		WHILE(@lCount <= (SELECT count(*) FROM @tOnlineLearningAccount))                
		BEGIN
			UPDATE sAcademic.tOnlineMeetingSettings 
			SET 
			AccountEmailId = OMA.AccountEmailId
		   ,AccountPassword = OMA.AccountPassword
		   ,APIKey = OMA.APIKey
		   ,APISecret = OMA.APISecret
		   ,WebAPIKey = OMA.WebAPIKey
		   ,WebAPISecret = OMA.WebAPISecret
		   ,MeetingProviderId = OMA.MeetingProviderId
		   ,JWTToken = OMA.JWTToken
		   ,OAuthAccountId = @rOAuthAccountId
		   ,OAuthClientId = @rOAuthClientId
		   ,OAuthClientSecret = @rOAuthClientSecret
		   FROM
			sAcademic.tOnlineMeetingAccount OMA
		   WHERE 
			OnlineLearningId = (SELECT OnlineLearningId FROM @tOnlineLearningAccount WHERE Id = @lCount)
			AND OMA.Id = @rId

			SET @lCount = @lCount + 1
		END
	      SELECT -100 AS Result
		--COMMIT TRANSACTION
	 END  	
	END
	COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Altering Procedure [sAcademic].[pMeetingAccountGet]...';


GO
 
 
ALTER PROCEDURE [sAcademic].[pMeetingAccountGet]

	 @rId bigint = 0,
	 @rTitle nvarchar(100) ='',
	 @rEmployeeId bigint = 0,
	 @rOrgGroupId smallint,
	 @rMeetingProviderId int = 0
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	if(@rId = 0)
	BEGIN 
	
	SELECT 
			OMA.Id,
			OMA.AccountName,
			OMA.AccountEmailId,
			ISNULL(EM.EmployeeName,'') as EmployeeName,
			DM.Title as MeetingProvider,
			OMA.WebAPIKey,
			OMA.WebAPISecret,
			ISNULL(OMA.IsObsolete,0) as IsObsolete,
			ISNULL(OMA.OAuthAccountId,'')AS OAuthAccountId,
			ISNULL(OMA.OAuthClientId,'') AS OAuthClientId,
			ISNULL(OMA.OAuthClientSecret,'') AS OAuthClientSecret
	  FROM 
			sAcademic.tOnlineMeetingAccount OMA
			LEFT JOIN sHrm.vExtEmployee EM ON EM.EmployeeId = OMA.EmployeeId 
			INNER JOIN sCommon.tDataMaster DM ON OMA.MeetingProviderId = DM.Id AND DM.DataTypeId = 8
	  WHERE 
  
				((OMA.AccountName like @rTitle) OR (ISNULL(@rTitle,'') = ''))
				AND OMA.OrgGroupId = @rOrgGroupId
				AND ((OMA.MeetingProviderId = @rMeetingProviderId) OR (ISNULL(@rMeetingProviderId,0) = 0))
	 
	END
	ELSE
	BEGIN
		SELECT 
			OMA.Id,
			OMA.EmployeeId as EmployeeId,
			EM.EmployeeCode as EmployeeCode,
			OMA.AccountName as AccountName,
			OMA.AccountEmailId as AccountEmailId,
			OMA.AccountPassword as AccountPassword,
			OMA.APIKey as APIKey,
			OMA.APISecret as APISecret,
			OMA.WebAPIKey as WebAPIKey,
			OMA.WebAPISecret as WebAPISecret,
			OMA.MeetingProviderId as MeetingProviderId,
			DM.Title as MeetingProvider,
			OMA.JWTToken as JWTToken,
			ISNULL(OMA.IsObsolete,0) as IsObsolete,
			ISNULL(OMA.OAuthAccountId,'')AS OAuthAccountId,
			ISNULL(OMA.OAuthClientId,'') AS OAuthClientId,
			ISNULL(OMA.OAuthClientSecret,'') AS OAuthClientSecret
	  FROM 
			sAcademic.tOnlineMeetingAccount OMA
			INNER JOIN sCommon.tDataMaster DM ON OMA.MeetingProviderId = DM.Id AND DM.DataTypeId = 8
			LEFT JOIN sHrm.vExtEmployee EM ON EM.EmployeeId = OMA.EmployeeId
	  WHERE 
			(OMA.Id = @rId) AND OMA.OrgGroupId = @rOrgGroupId
			AND ((OMA.MeetingProviderId = @rMeetingProviderId) OR (ISNULL(@rMeetingProviderId,0) = 0))
	END
END
GO
PRINT N'Altering Procedure [sAcademic].[pOnlineLearningAdd]...';


GO
 
ALTER PROCEDURE [sAcademic].[pOnlineLearningAdd]
	 
        @rId bigint = 0,
		@rLearningTypeId int,
		@rClassId int = 0,
        @rSubjectId int,
		@rTopicId int = 0,
		@rTeacherId bigint,
		@rStartDate date,
		@rEndDate date,
		@rStartTime datetime,
		@rEndTime datetime,
		@rTitle nvarchar(100) = '',
		@rDescription nvarchar(max) = '',
		@rLecturePath nvarchar(max) = '',
		@rIsDisplayMeetingId bit =0,
		@rMeetingId nvarchar(50) = '',
		@rMeetingPass nvarchar(50) = '',
		@rIsTrackAttendance bit =0,
		@rIsAssignment bit=0,
		@rIsResource bit=0,
		@rIsRefrence bit=0,
		@rIsCompleted bit = 0,
		@rIsMeetingStarted bit = 0,
		@rCreatedUserId bigint,
		@rBatchId int,
		@rOrgId int,
		@rTempOnlineLearningId nvarchar(100) = 0,
		@rIsSubmitAssignment bit=0,
		@rIsTakeTest bit=0,
		@rTestId int=0,
		@rIsOnParticipantVideo bit=0,
		@rIsOnParticipantAudio bit=0,
		@rIsOnHostVideo bit=0,
		@rIsOnHostAudio bit=0,
		@rIsOnParticipantScreenShare bit=0,
		@rIsOnHostscreenShare bit=0,
		@rMeetingAccountId int = 0,
		@rReferenceId bigint = 0,
		@rIsMeetingCreated bit=0,
		@rAssignmentRemark nvarchar(500) = '',
		@rIsTrackAssignmentView bit = 0,
		@rCoTeacherEmployeeId1 bigint =0,
		@rCoTeacherEmployeeId2 bigint =0,
		@rSubmissionEndDate DateTime = '',
		@rIsRecording bit = 0
			
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	 
	 BEGIN TRANSACTION	
	 DECLARE @lNextNumber BIGINT 

	 DECLARE @lAccountEmailId NVARCHAR(200),@lAccountPassword NVARCHAR(200),@lAPIKey NVARCHAR(100),@lAPISecret NVARCHAR(100),@lWebAPIKey NVARCHAR(100),
	         @lWebAPISecret NVARCHAR(100),@lMeetingProviderId NVARCHAR(100),@lJWTToken NVARCHAR(MAX),@lOAuthAccountId NVARCHAR(MAX), @lOAuthClientId NVARCHAR(MAX),@lOAuthClientSecret NVARCHAR(MAX)

	SELECT @lAccountEmailId = AccountEmailId,@lAccountPassword = AccountPassword,@lAPIKey = APIKey,@lAPISecret = APISecret,@lWebAPIKey = WebAPIKey,@lWebAPISecret = WebAPISecret,@lMeetingProviderId = MeetingProviderId,
	@lJWTToken = JWTToken, @lOAuthAccountId = OAuthAccountId , @lOAuthClientId = OAuthClientId , @lOAuthClientSecret = OAuthClientSecret
	    FROM sAcademic.tOnlineMeetingAccount
		WHERE Id = @rMeetingAccountId

	IF(@rId = 0)	
	BEGIN
		
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sAcademic.tOnlineLearning', 0, 1, 1,@outNextNumber = @lNextNumber output
	Print @lNextNumber
	INSERT INTO sAcademic.tOnlineLearning
		(
			Id
           ,BatchId
           ,StartDate
           ,StartTime
           ,EndDate
           ,EndTime
           ,ClassId
           ,SubjectId
           ,TeacherEmployeeId
           ,Title
           ,Description
           ,LearningTypeId
           ,IsTrackAttendance
           ,TopicId
           ,LecturePath
           ,IsDisplayMeetingId
           ,MeetingId
           ,MeetingPassword
           ,IsAssignment
           ,IsReference
           ,IsResource
           ,IsCompleted
           ,IsMeetingStarted
           ,CreatedUserId
           ,CreatedDateTime
		   ,IsSubmitAssignment
		   ,IsTakeTest
		   ,TestId
		   ,MeetingAccountId
		   ,IsMeetingCreated
		   ,AssignmentRemark
		   ,IsTrackAssignmentView
		   ,CoTeacherEmployeeId1
		   ,CoTeacherEmployeeId2
		   ,AssignmentSubmissionEndDate
		   ,IsRecording
		)
	VALUES
		(
			@lNextNumber,
			@rBatchId,
			@rStartDate,
			@rStartTime,
			@rEndDate, 
			@rEndTime,
			@rClassId,
			@rSubjectId,
			@rTeacherId,
			@rTitle,
			@rDescription,
			@rLearningTypeId,
			@rIsTrackAttendance,
			@rTopicId,
			@rLecturePath,
			@rIsDisplayMeetingId,
			@rMeetingId,
			@rMeetingPass,
			@rIsAssignment,
			@rIsRefrence,
			@rIsResource,
			@rIsCompleted,
			@rIsMeetingStarted,
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rIsSubmitAssignment,
			@rIsTakeTest,
			@rTestId,
			@rMeetingAccountId,
			@rIsMeetingCreated,
			@rAssignmentRemark,
			@rIsTrackAssignmentView,
			@rCoTeacherEmployeeId1,
			@rCoTeacherEmployeeId2,
			@rSubmissionEndDate,
			@rIsRecording
		)
		    
		IF(@rLearningTypeId = 2)
		BEGIN
		INSERT INTO sAcademic.tOnlineMeetingSettings
		(
			OnlineLearningId,
			IsOnParticipantVideo,
			IsOnParticipantAudio,
			IsOnHostVideo,
			IsOnHostAudio,
			IsOnParticipantScreenShare,
			IsOnHostscreenShare,
			AccountEmailId,
			AccountPassword,
			APIKey,
			APISecret,
			WebAPIKey,
			WebAPISecret,
			MeetingProviderId,
			JWTToken,
			OAuthAccountId,
			OAuthClientId,
			OAuthClientSecret
		)
		VALUES
		(
			@lNextNumber,
			@rIsOnParticipantVideo,
			@rIsOnParticipantAudio,
			@rIsOnHostVideo ,
			@rIsOnHostAudio ,
			@rIsOnParticipantScreenShare,
			@rIsOnHostscreenShare,
			@lAccountEmailId,
			@lAccountPassword,
			@lAPIKey,
			@lAPISecret,
			@lWebAPIKey,
			@lWebAPISecret,
			@lMeetingProviderId,
			@lJWTToken,
			@lOAuthAccountId,
			@lOAuthClientId,
			@lOAuthClientSecret
		)
		END
		IF(@rReferenceId = 0)
		BEGIN
		   IF EXISTS (SELECT 1 FROM sAcademic.tTempOnlineLearningScope WHERE TempOnlineLearningId = @rTempOnlineLearningId)
		   BEGIN
		   print 2
				IF EXISTS(SELECT 1 FROM sAcademic.tOnlineLearningScope WHERE Convert(NVARCHAR(MAX),OnlineLearningId) = @rTempOnlineLearningId)
				BEGIN
					DELETE FROM sAcademic.tOnlineLearningScope WHERE OnlineLearningId = @rTempOnlineLearningId
				END
				INSERT INTO sAcademic.tOnlineLearningScope
				SELECT @lNextNumber,SourceTypeId,SourceId
				FROM sAcademic.tTempOnlineLearningScope 
				WHERE TempOnlineLearningId = @rTempOnlineLearningId
		
				DELETE FROM sAcademic.tTempOnlineLearningScope WHERE TempOnlineLearningId = @rTempOnlineLearningId
			--COMMIT TRANSACTION 
			END     
		END
		ELSE
		BEGIN 
		   IF EXISTS (SELECT 1 FROM sAcademic.tOnlineLearningScope WHERE OnlineLearningId = @rReferenceId)
		   BEGIN
				INSERT INTO sAcademic.tOnlineLearningScope
				SELECT @lNextNumber,SourceTypeId,SourceId
				FROM sAcademic.tOnlineLearningScope 
				WHERE OnlineLearningId = @rReferenceId
		
			--COMMIT TRANSACTION 
			END    
		END
		SELECT @lNextNumber AS Result   
	END	 

ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE sAcademic.tOnlineLearning
	    SET
			 
           StartDate = @rStartDate
           ,StartTime = @rStartTime
           ,EndDate = @rEndDate
           ,EndTime = @rEndTime
           ,ClassId = @rClassId
           ,SubjectId = @rSubjectId
           ,TeacherEmployeeId = @rTeacherId
           ,Title = @rTitle
           ,Description = @rDescription
           ,LearningTypeId = @rLearningTypeId
           ,IsTrackAttendance = @rIsTrackAttendance
           ,TopicId = @rTopicId
           ,LecturePath = @rLecturePath
           ,IsDisplayMeetingId = @rIsDisplayMeetingId
           ,MeetingId = @rMeetingId
           ,MeetingPassword = @rMeetingPass
           ,IsAssignment = @rIsAssignment
           ,IsReference = @rIsRefrence
           ,IsResource = @rIsResource
           ,IsCompleted = @rIsCompleted
		   ,UpdatedUserId=@rCreatedUserId
		   ,UpdatedDateTime=sCommon.fGetDate()
		   ,IsSubmitAssignment=@rIsSubmitAssignment
		   ,IsTakeTest=@rIsTakeTest
		   ,TestId=@rTestId
		   ,MeetingAccountId = @rMeetingAccountId
		   ,IsMeetingCreated = @rIsMeetingCreated
		   ,AssignmentRemark = @rAssignmentRemark
		   ,IsTrackAssignmentView = @rIsTrackAssignmentView
		   ,CoTeacherEmployeeId1 = @rCoTeacherEmployeeId1
		   ,CoTeacherEmployeeId2 = @rCoTeacherEmployeeId2
		   ,AssignmentSubmissionEndDate = @rSubmissionEndDate
		   ,IsRecording = @rIsRecording
	      WHERE Id = @rId
	      
		  IF(@rLearningTypeId = 2)
		  BEGIN
		  IF EXISTS (SELECT 1 FROM sAcademic.tOnlineMeetingSettings WHERE OnlineLearningId = @rId)
		  BEGIN
	      UPDATE sAcademic.tOnlineMeetingSettings
		  SET
			IsOnParticipantVideo = @rIsOnParticipantVideo,
			IsOnParticipantAudio = @rIsOnParticipantAudio,
			IsOnHostVideo = @rIsOnHostVideo,
			IsOnHostAudio = @rIsOnHostAudio,
			IsOnParticipantScreenShare = @rIsOnParticipantScreenShare,
			IsOnHostscreenShare = @rIsOnHostscreenShare,
			AccountEmailId = @lAccountEmailId,
			AccountPassword = @lAccountPassword,
			APIKey = @lAPIKey,
			APISecret = @lAPISecret,
			WebAPIKey = @lWebAPIKey,
			WebAPISecret = @lWebAPISecret,
			MeetingProviderId = @lMeetingProviderId,
			JWTToken = @lJWTToken,
			OAuthAccountId = @lOAuthAccountId,
			OAuthClientId = @lOAuthClientId,
			OAuthClientSecret = @lOAuthClientSecret
		  WHERE OnlineLearningId = @rId
	      END
		  ELSE
		  BEGIN
			INSERT INTO sAcademic.tOnlineMeetingSettings
			(
				OnlineLearningId,
				IsOnParticipantVideo,
				IsOnParticipantAudio,
				IsOnHostVideo,
				IsOnHostAudio,
				IsOnParticipantScreenShare,
				IsOnHostscreenShare,
				AccountEmailId,
				AccountPassword,
				APIKey,
				APISecret,
				WebAPIKey,
				WebAPISecret,
				MeetingProviderId,
				JWTToken,
				OAuthAccountId,
				OAuthClientId,
				OAuthClientSecret
			)
			VALUES
			(
				@rId,
				@rIsOnParticipantVideo,
				@rIsOnParticipantAudio,
				@rIsOnHostVideo ,
				@rIsOnHostAudio ,
				@rIsOnParticipantScreenShare,
				@rIsOnHostscreenShare,
				@lAccountEmailId,
				@lAccountPassword,
				@lAPIKey,
				@lAPISecret,
				@lWebAPIKey,
				@lWebAPISecret,
				@lMeetingProviderId,
				@lJWTToken,
				@lOAuthAccountId,
				@lOAuthClientId,
				@lOAuthClientSecret
			)
		  END
		  END
		  IF EXISTS (SELECT 1 FROM sAcademic.tTempOnlineLearningScope WHERE TempOnlineLearningId = @rTempOnlineLearningId)
		   BEGIN
				IF EXISTS(SELECT 1 FROM sAcademic.tOnlineLearningScope WHERE OnlineLearningId = @rTempOnlineLearningId)
				BEGIN
					DELETE FROM sAcademic.tOnlineLearningScope WHERE OnlineLearningId = @rTempOnlineLearningId
				END
				INSERT INTO sAcademic.tOnlineLearningScope
				SELECT @lNextNumber,SourceTypeId,SourceId
				FROM sAcademic.tTempOnlineLearningScope 
				WHERE TempOnlineLearningId = @rTempOnlineLearningId
		
				DELETE FROM sAcademic.tTempOnlineLearningScope WHERE TempOnlineLearningId = @rTempOnlineLearningId
			--COMMIT TRANSACTION 
			END  
	      SELECT 1 AS Result
	
		--COMMIT TRANSACTION
	 END  	

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


GO
 
ALTER PROCEDURE [sAcademic].[pOnlineLearningMobilelectureAdd]
	 
        @rId bigint = 0,
		@rLearningTypeId int,
		@rClassId int = 0,
        @rSubjectId int,
		@rTopicId int = 0,
		@rTeacherId bigint,
		@rStartDate date,
		@rEndDate date,
		@rStartTime datetime,
		@rEndTime datetime,
		@rTitle nvarchar(100) = '',
		@rDescription nvarchar(max) = '',
		@rLecturePath nvarchar(max) = '',
		@rIsDisplayMeetingId bit =0,
		@rMeetingId nvarchar(50) = '',
		@rMeetingPass nvarchar(50) = '',
		@rIsTrackAttendance bit =0,
		@rIsAssignment bit=0,
		@rIsResource bit=0,
		@rIsRefrence bit=0,
		@rIsCompleted bit = 0,
		@rIsMeetingStarted bit = 0,
		@rCreatedUserId bigint,
		@rBatchId int,
		@rOrgId int,
		--@rTempOnlineLearningId nvarchar(100) = 0,
		@rIsSubmitAssignment bit=0,
		@rIsTakeTest bit=0,
		@rTestId int=0,
		@rIsOnParticipantVideo bit=0,
		@rIsOnParticipantAudio bit=0,
		@rIsOnHostVideo bit=0,
		@rIsOnHostAudio bit=0,
		@rIsOnParticipantScreenShare bit=0,
		@rIsOnHostscreenShare bit=0,
		@rMeetingAccountId int = 0,
		@rReferenceId bigint = 0,
		@rIsMeetingCreated bit=0,
		@rAssignmentRemark nvarchar(500) = '',
		@rIsTrackAssignmentView bit = 0,
		@rCoTeacherEmployeeId1 bigint =0,
		@rCoTeacherEmployeeId2 bigint =0,
		--@rAssignToXML nvarchar(Max) = ''
		@rSubmissionEndDate DateTime = '',
		@rIsRecording bit = 0
			
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	 
	 BEGIN TRANSACTION	
	 DECLARE @lNextNumber BIGINT 

	 DECLARE @lAccountEmailId NVARCHAR(200),@lAccountPassword NVARCHAR(200),@lAPIKey NVARCHAR(100),@lAPISecret NVARCHAR(100),@lWebAPIKey NVARCHAR(100),
	         @lWebAPISecret NVARCHAR(100),@lMeetingProviderId NVARCHAR(100),@lJWTToken NVARCHAR(MAX),@lOAuthAccountId NVARCHAR(MAX) ,@lOAuthClientId NVARCHAR(MAX),@lOAuthClientSecret NVARCHAR(MAX)

	SELECT @lAccountEmailId = AccountEmailId,@lAccountPassword = AccountPassword,@lAPIKey = APIKey,@lAPISecret = APISecret,@lWebAPIKey = WebAPIKey,@lWebAPISecret = WebAPISecret,@lMeetingProviderId = MeetingProviderId
	,@lJWTToken = JWTToken , @lOAuthAccountId = OAuthAccountId , @lOAuthClientId = OAuthClientId, @lOAuthClientSecret = OAuthClientSecret
	    FROM sAcademic.tOnlineMeetingAccount
		WHERE Id = @rMeetingAccountId



	IF(@rId = 0)	
	BEGIN
		
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sAcademic.tOnlineLearning', 0, 1, 1,@outNextNumber = @lNextNumber output
	Print @lNextNumber
	
	INSERT INTO sAcademic.tOnlineLearning
		(
			Id
           ,BatchId
           ,StartDate
           ,StartTime
           ,EndDate
           ,EndTime
           ,ClassId
           ,SubjectId
           ,TeacherEmployeeId
           ,Title
           ,Description
           ,LearningTypeId
           ,IsTrackAttendance
           ,TopicId
           ,LecturePath
           ,IsDisplayMeetingId
           ,MeetingId
           ,MeetingPassword
           ,IsAssignment
           ,IsReference
           ,IsResource
           ,IsCompleted
           ,IsMeetingStarted
           ,CreatedUserId
           ,CreatedDateTime
		   ,IsSubmitAssignment
		   ,IsTakeTest
		   ,TestId
		   ,MeetingAccountId
		   ,IsMeetingCreated
		   ,AssignmentRemark
		   ,IsTrackAssignmentView
		   ,CoTeacherEmployeeId1
		   ,CoTeacherEmployeeId2
		   ,AssignmentSubmissionEndDate
		   ,IsRecording
		)
	VALUES
		(
			@lNextNumber,
			@rBatchId,
			@rStartDate,
			@rStartTime,
			@rEndDate, 
			@rEndTime,
			@rClassId,
			@rSubjectId,
			@rTeacherId,
			@rTitle,
			@rDescription,
			@rLearningTypeId,
			@rIsTrackAttendance,
			@rTopicId,
			@rLecturePath,
			@rIsDisplayMeetingId,
			@rMeetingId,
			@rMeetingPass,
			@rIsAssignment,
			@rIsRefrence,
			@rIsResource,
			@rIsCompleted,
			@rIsMeetingStarted,
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rIsSubmitAssignment,
			@rIsTakeTest,
			@rTestId,
			@rMeetingAccountId,
			@rIsMeetingCreated,
			@rAssignmentRemark,
			@rIsTrackAssignmentView,
			@rCoTeacherEmployeeId1,
			@rCoTeacherEmployeeId2,
			@rSubmissionEndDate,
			@rIsRecording
		)
		    
		IF(@rLearningTypeId = 2)
		BEGIN
		INSERT INTO sAcademic.tOnlineMeetingSettings
		(
			OnlineLearningId,
			IsOnParticipantVideo,
			IsOnParticipantAudio,
			IsOnHostVideo,
			IsOnHostAudio,
			IsOnParticipantScreenShare,
			IsOnHostscreenShare,
			AccountEmailId,
			AccountPassword,
			APIKey,
			APISecret,
			WebAPIKey,
			WebAPISecret,
			MeetingProviderId,
			JWTToken,
			OAuthAccountId,
			OAuthClientId,
			OAuthClientSecret
		)
		VALUES
		(
			@lNextNumber,
			@rIsOnParticipantVideo,
			@rIsOnParticipantAudio,
			@rIsOnHostVideo ,
			@rIsOnHostAudio ,
			@rIsOnParticipantScreenShare,
			@rIsOnHostscreenShare,
			@lAccountEmailId,
			@lAccountPassword,
			@lAPIKey,
			@lAPISecret,
			@lWebAPIKey,
			@lWebAPISecret,
			@lMeetingProviderId,
			@lJWTToken,
			@lOAuthAccountId,
			@lOAuthClientId,
			@lOAuthClientSecret
		)
		END
		
		--COMMIT TRANSACTION 
		SELECT @lNextNumber AS Result   
	END	 

ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE sAcademic.tOnlineLearning
	    SET
			 
           StartDate = @rStartDate
           ,StartTime = @rStartTime
           ,EndDate = @rEndDate
           ,EndTime = @rEndTime
           ,ClassId = @rClassId
           ,SubjectId = @rSubjectId
           ,TeacherEmployeeId = @rTeacherId
           ,Title = @rTitle
           ,Description = @rDescription
           ,LearningTypeId = @rLearningTypeId
           ,IsTrackAttendance = @rIsTrackAttendance
           ,TopicId = @rTopicId
           ,LecturePath = @rLecturePath
           ,IsDisplayMeetingId = @rIsDisplayMeetingId
           ,MeetingId = @rMeetingId
           ,MeetingPassword = @rMeetingPass
           ,IsAssignment = @rIsAssignment
           ,IsReference = @rIsRefrence
           ,IsResource = @rIsResource
           ,IsCompleted = @rIsCompleted
		   ,UpdatedUserId=@rCreatedUserId
		   ,UpdatedDateTime=sCommon.fGetDate()
		   ,IsSubmitAssignment=@rIsSubmitAssignment
		   ,IsTakeTest=@rIsTakeTest
		   ,TestId=@rTestId
		   ,MeetingAccountId = @rMeetingAccountId
		   ,IsMeetingCreated = @rIsMeetingCreated
		   ,AssignmentRemark = @rAssignmentRemark
		   ,IsTrackAssignmentView = @rIsTrackAssignmentView
		   ,CoTeacherEmployeeId1 = @rCoTeacherEmployeeId1
		   ,CoTeacherEmployeeId2 = @rCoTeacherEmployeeId2
		   ,AssignmentSubmissionEndDate = @rSubmissionEndDate
		   ,IsRecording = @rIsRecording
	      WHERE Id = @rId
	      
		  IF(@rLearningTypeId = 2)
		  BEGIN
		  IF EXISTS (SELECT 1 FROM sAcademic.tOnlineMeetingSettings WHERE OnlineLearningId = @rId)
		  BEGIN
	      UPDATE sAcademic.tOnlineMeetingSettings
		  SET
			IsOnParticipantVideo = @rIsOnParticipantVideo,
			IsOnParticipantAudio = @rIsOnParticipantAudio,
			IsOnHostVideo = @rIsOnHostVideo,
			IsOnHostAudio = @rIsOnHostAudio,
			IsOnParticipantScreenShare = @rIsOnParticipantScreenShare,
			IsOnHostscreenShare = @rIsOnHostscreenShare,
			AccountEmailId = @lAccountEmailId,
			AccountPassword = @lAccountPassword,
			APIKey = @lAPIKey,
			APISecret = @lAPISecret,
			WebAPIKey = @lWebAPIKey,
			WebAPISecret = @lWebAPISecret,
			MeetingProviderId = @lMeetingProviderId,
			JWTToken = @lJWTToken,
			OAuthAccountId = @lOAuthAccountId,
			OAuthClientId = @lOAuthClientId,
			OAuthClientSecret = @lOAuthClientSecret
		  WHERE OnlineLearningId = @rId
	      END
		  ELSE
		  BEGIN
			INSERT INTO sAcademic.tOnlineMeetingSettings
			(
				OnlineLearningId,
				IsOnParticipantVideo,
				IsOnParticipantAudio,
				IsOnHostVideo,
				IsOnHostAudio,
				IsOnParticipantScreenShare,
				IsOnHostscreenShare,
				AccountEmailId,
				AccountPassword,
				APIKey,
				APISecret,
				WebAPIKey,
				WebAPISecret,
				MeetingProviderId,
				JWTToken,
				OAuthAccountId,
				OAuthClientId,
				OAuthClientSecret
			)
			VALUES
			(
				@rId,
				@rIsOnParticipantVideo,
				@rIsOnParticipantAudio,
				@rIsOnHostVideo ,
				@rIsOnHostAudio ,
				@rIsOnParticipantScreenShare,
				@rIsOnHostscreenShare,
				@lAccountEmailId,
				@lAccountPassword,
				@lAPIKey,
				@lAPISecret,
				@lWebAPIKey,
				@lWebAPISecret,
				@lMeetingProviderId,
				@lJWTToken,
				@lOAuthAccountId,
				@lOAuthClientId,
				@lOAuthClientSecret
			)
		  END
		  END

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


GO
 

ALTER PROCEDURE [sAcademic].[pOnlineLearningScheduleCopy]
	 
        @rId bigint,
		@rAssignToStartDate DateTime,
		@rAssignToEndDate DateTime,
		@rCreatedUserId bigint,
		@rOrgId int
			
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	 
	 BEGIN TRANSACTION	

	 DECLARE @lNextNumber BIGINT 

	 EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sAcademic.tOnlineLearning', 0, 1, 1,@outNextNumber = @lNextNumber output
	 Print @lNextNumber
	 
	 INSERT INTO sAcademic.tOnlineLearning
		(
			Id
           ,BatchId
           ,StartDate
           ,StartTime
           ,EndDate
           ,EndTime
           ,ClassId
           ,SubjectId
           ,TeacherEmployeeId
           ,Title
           ,Description
           ,LearningTypeId
           ,IsTrackAttendance
           ,TopicId
           ,LecturePath
           ,IsDisplayMeetingId
           ,MeetingId
           ,MeetingPassword
		   ,IsCompleted
           ,CreatedUserId
           ,CreatedDateTime
		   ,MeetingAccountId
		   ,CoTeacherEmployeeId1
		   ,CoTeacherEmployeeId2
		)
	 SELECT 
			@lNextNumber,
			OL.BatchId,
			@rAssignToStartDate,
			OL.StartTime,
			@rAssignToEndDate, 
			OL.EndTime,
			OL.ClassId,
			OL.SubjectId,
			OL.TeacherEmployeeId,
			OL.Title,
			OL.Description,
			OL.LearningTypeId,
			OL.IsTrackAttendance,
			OL.TopicId,
			OL.LecturePath,
			OL.IsDisplayMeetingId,
			'',
			'',
			0,
			@rCreatedUserId,
			sCommon.fGetDate(),
			OL.MeetingAccountId,
			OL.CoTeacherEmployeeId1,
			OL.CoTeacherEmployeeId2
	  FROM sAcademic.tOnlineLearning OL WHERE Id = @rId

	  INSERT INTO sAcademic.tOnlineMeetingSettings
		(
			OnlineLearningId,
			IsOnParticipantVideo,
			IsOnParticipantAudio,
			IsOnHostVideo,
			IsOnHostAudio,
			IsOnParticipantScreenShare,
			IsOnHostscreenShare,
			AccountEmailId,
			AccountPassword,
			APIKey,
			APISecret,
			WebAPIKey,
			WebAPISecret,
			MeetingProviderId,
			JWTToken,
			OAuthAccountId,
			OAuthClientId,
			OAuthClientSecret
		)
		SELECT
			@lNextNumber,
			OMS.IsOnParticipantVideo,
			OMS.IsOnParticipantAudio,
			OMS.IsOnHostVideo ,
			OMS.IsOnHostAudio ,
			OMS.IsOnParticipantScreenShare,
			OMS.IsOnHostscreenShare,
			OMS.AccountEmailId,
			OMS.AccountPassword,
			OMS.APIKey,
			OMS.APISecret,
			OMS.WebAPIKey,
			OMS.WebAPISecret,
			OMS.MeetingProviderId,
			OMS.JWTToken,
			OMS.OAuthAccountId,
			OMS.OAuthClientId,
			OMS.OAuthClientSecret
		FROM 
		sAcademic.tOnlineMeetingSettings OMS
		WHERE OnlineLearningId = @rId

		 IF EXISTS (SELECT 1 FROM sAcademic.tOnlineLearningScope WHERE OnlineLearningId = @rId)
		   BEGIN
				INSERT INTO sAcademic.tOnlineLearningScope
				SELECT @lNextNumber,SourceTypeId,SourceId
				FROM sAcademic.tOnlineLearningScope 
				WHERE OnlineLearningId = @rId
		
			END    

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


GO

 
ALTER PROCEDURE [sBiometric].[pShiftMasterCloudAdd]
@rShiftCode int = 0,
@rShiftName nvarchar(50),
@rStartTime DateTime = null,
@rEndTime DateTime = null,
@rGraceBefore int = 0,
@rGraceAfter int = 0,
@rShiftDur nvarchar(16) = NULL,
@rMinHrsHalfDay  nvarchar(16) = null,
@rMinHrsFullDay nvarchar(16) = null,
@rAlterGraceTime int = 0,
@IsOutTimeAlertTime bit = 0,
@OutTimeAlertTime DateTime = null,
@rOrgGroupId int = 0,
@rLastOutAlertBasedOnId int=1,
@rIsStopInTimeAlertTime bit=0,
@rStopInTimeAlertTime DateTime=null

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
	IF(@rShiftcode = 0)	
		BEGIN
			If Exists(select ShiftCode from sBiometric.tShiftMasterCloud where ShiftName=@rShiftName and OrgGroupId = @rOrgGroupId)
				BEGIN
				select -103 as Result
				RETURN
			END 
		END
	ELSE
		BEGIN
			If  Exists(select ShiftCode from sBiometric.tShiftMasterCloud where ShiftName=@rShiftName AND Shiftcode<>@rShiftcode and OrgGroupId = @rOrgGroupId)
			Begin
				select -103 as Result
				RETURN
			End
		END	
	
	 BEGIN TRANSACTION	
	 DECLARE @lNextNumber BIGINT 
	 IF EXISTS (SELECT 1 FROM sBiometric.tShiftMasterCloud)
	 BEGIN
		SELECT @lNextNumber = Max(ISNULL(ShiftCode,0)) + 1 FROM sBiometric.tShiftMasterCloud
	 END
	 ELSE
	 BEGIN
		SET @lNextNumber = 1
	 END
	 
	IF(@rShiftcode = 0)	
	BEGIN
	Insert into sBiometric.tShiftMasterCloud 
     (ShiftCode
     , ShiftName
     , StartTime
     , EndTime
     , GraceBefore
     , GraceAfter
     , ShiftDur
     , MinHrsHalfDay
     , MinHrsFullDay    
     , AlterGraceTime
     , IsOutTimeAlertTime
     , OutTimeAlertTime
     , OrgGroupId
	 ,LastOutAlertBasedOnId
	 ,IsStopInTimeAlertTime
	 ,StopInTimeAlertTime)
     Values
     (@lNextNumber
     ,@rShiftName
     ,@rStartTime
     ,@rEndTime
     ,@rGraceBefore
     ,@rGraceAfter
     ,@rShiftDur
     ,@rMinHrsHalfDay
     ,@rMinHrsFullDay
     ,@rAlterGraceTime
     ,@IsOutTimeAlertTime
     ,@OutTimeAlertTime
     ,@rOrgGroupId
     ,@rLastOutAlertBasedOnId
	 ,@rIsStopInTimeAlertTime 
	 ,@rStopInTimeAlertTime 
	 )
     
     SELECT @lNextNumber AS Result
	
		--COMMIT TRANSACTION         
	END	 

ELSE
	 BEGIN
	    UPDATE sBiometric.tShiftMasterCloud
	    SET
			ShiftName=@rShiftName,
			StartTime=@rStartTime,
			EndTime=@rEndTime,
			GraceBefore=@rGraceBefore,
			shiftDur=@rShiftDur,
			MinHrsHalfDay=@rMinHrsHalfDay,
			MinHrsFullDay=@rMinHrsFullDay,
			AlterGraceTime=@rAlterGraceTime,
		    IsOutTimeAlertTime = @IsOutTimeAlertTime,
			OutTimeAlertTime = @OutTimeAlertTime,
			LastOutAlertBasedOnId=@rLastOutAlertBasedOnId,
			IsStopInTimeAlertTime=@rIsStopInTimeAlertTime,
			StopInTimeAlertTime=@rStopInTimeAlertTime
		
	      WHERE ShiftCode = @rShiftcode and OrgGroupId = @rOrgGroupId
	      
	      SELECT @lNextNumber AS Result
	
		--COMMIT TRANSACTION
	 END  	

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


GO

ALTER PROCEDURE [sBiometric].[pShiftMasterCloudGet]
@rShiftCode int = 0,
@rShiftName nvarchar(50) = '',
@rOrgGroupId int = 0

AS
BEGIN

	select [ShiftCode]
      ,[ShiftName]
      ,[StartTime]
      ,[EndTime]
      ,[GraceBefore]
      ,[GraceAfter]
      ,[ShiftDur]
      ,[MinHrsHalfDay]
      ,[MinHrsFullDay]
      ,[RecessDur]
      ,[AlterGraceTime]
      ,[SMSScheduleTime]
      ,[ShiftGroupCode]
      ,[IsOutTimeAlertTime]
      ,[OutTimeAlertTime]
      ,[OrgGroupId]
      ,isnull([LastOutAlertBasedOnId],1) as LastOutAlertBasedOnId
	  ,Isnull(IsStopInTimeAlertTime,0) as IsStopInTimeAlertTime
	 ,StopInTimeAlertTime 
	   from sBiometric.tShiftMasterCloud
	where 
	((ShiftCode = @rShiftCode) OR (@rShiftCode=0))     
	AND ((ShiftName = @rShiftName) OR (@rShiftName=''))     
	AND ((OrgGroupId = @rOrgGroupId) OR (@rOrgGroupId=0))     
END
GO
PRINT N'Altering Procedure [sCanteen].[pCanteenIssueAdd]...';


GO
ALTER PROCEDURE [sCanteen].[pCanteenIssueAdd]
	  
	  
        @rId bigint,
        @rCanteenId int,
		@rSourceTypeId smallint,
		@rSourceId bigint,
		@rIssueDate date,
		@rTotalAmount decimal(12,2),
		@rOrgGroupId int,
		@rCreatedUserId bigint,
		@rOtherName nvarchar(100),
		@rCanteenIssueXml nvarchar(max),
		@rStudentDailySpendLimit decimal(12,2)=0,
		--@rIdOut [bigint] OUTPUT
		--add by dhruvik for 25772 mantis issue
		@rPayTypeId tinyint,		--add
		@rChequeNo nvarchar(40),	--add
		@rBankName nvarchar(200),	--add
		@rChequeDate date			--add
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

	BEGIN TRY
	
	--IF(@rId = 0)	
	--BEGIN
		
	--	If Exists(select 1 from sCanteen.tCanteenIssue where CanteenId=@rCanteenId AND Id=@rId)
	--		BEGIN
	--		select -103 as Result
	--		RETURN
	--	END 
	--END
	--ELSE
	--BEGIN
		
	--	If  Exists(select 1 from sCanteen.tCanteenIssue where CanteenId=@rCanteenId AND Id<>@rId)
	--	Begin
	--		select -103 as Result
	--		RETURN
	--	End

	--END
	IF (@rSourceTypeId=2003 AND @rStudentDailySpendLimit > 0 AND @rId = 0)
	BEGIN
	DECLARE @lSpendAmount Decimal(12,2)
	SELECT @lSpendAmount = ISNUll(SUM(TotalAmount),0) from sCanteen.tCanteenIssue where CanteenId=@rCanteenId AND SourceId=@rSourceId AND @rSourceTypeId=2003 AND IssueDate = @rIssueDate
	
	if (@lSpendAmount + @rTotalAmount > @rStudentDailySpendLimit )
	BEGIN
	SELECT -101 as Result 
	RETURN
	END
	END
	
	BEGIN TRANSACTION	
	
	 DECLARE @lNextNumber bigint

		IF(@rId = 0)	
	BEGIN
	EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sCanteen.tCanteenIssue', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	INSERT INTO sCanteen.tCanteenIssue
		(
			CanteenId,
			Id,	
			SourceTypeId,
			SourceId,
			IssueDate,
			TotalAmount,
			CreatedUserId,
			CreatedDateTime,
			OtherName,
			--add by dhruvik for 25772 mantis issue
			PayTypeId,		--add
			ChequeNo,		--add
			BankName,		--add
			ChequeDate		--add
			
		)
	VALUES
		(
		    @rCanteenId,
			@lNextNumber,
			@rSourceTypeId,
			@rSourceId,
			@rIssueDate,
			@rTotalAmount,
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rOtherName,
			--add by dhruvik for 25772 mantis issue
			@rPayTypeId,		--add
			@rChequeNo,			--add
			@rBankName,			--add
			@rChequeDate		--add
		)
		
		--SELECT 1 AS Result
		  SELECT @lNextNumber AS Result
		 END 
	ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE  sCanteen.tCanteenIssue
	    SET
			TotalAmount=@rTotalAmount,
			--add by dhruvik for 25772 mantis issue
			PayTypeId=@rPayTypeId,		--add
			ChequeNo=@rChequeNo,		--add
			BankName=@rBankName,		--add
			ChequeDate=@rChequeDate		--add
	      
	      WHERE Id = @rId
	      SELECT 11 AS Result
	 END  	
		
	EXEC [sCanteen].[pCanteenIssueDetailAdd] @lNextNumber,@rCanteenIssueXml
	
	
	COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
	
END
GO
PRINT N'Altering Procedure [sCanteen].[pCanteenIssueMasterGet]...';


GO
ALTER PROCEDURE [sCanteen].[pCanteenIssueMasterGet]
	
	@rId bigint = 0,
	@rCanteenId int ,
	@rFromDate date,
	@rToDate date,
	@rSUID nvarchar(50)=''

	--@rCode nvarchar(max)
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	 SELECT 
	        CI.Id,
			CI.CanteenId,
			CI.SourceTypeId,
			CI.SourceId,
			CI.IssueDate,
			CI.TotalAmount,
			CI.CreatedDateTime,
			(CASE WHEN CI.SourceTypeId=2003 THEN  isnull(SMast.Code,'')
			WHEN  CI.SourceTypeId=95  THEN isnull(EM.Code, '') ElSE ''
			 END) AS Code,
			 (CASE WHEN CI.SourceTypeId=2003 THEN  isnull(SMast.Name,'')
			WHEN  CI.SourceTypeId=95  THEN isnull(EM.FirstName +' ' + EM.MiddleName + ' ' + EM.LastName ,'') ElSE CI.OtherName
			 END) AS Name,
			 ISNULL(CI.OtherName,'') AS OtherName,
			 (CASE WHEN CI.SourceTypeId=2003 THEN  isnull(SMast.OrgId,'')
			WHEN  CI.SourceTypeId=95  THEN isnull(EM.OrgId, '') ElSE ''
			 END) AS OrgId,
			  (CASE WHEN CI.SourceTypeId=2003 THEN  isnull(SMast.SUId,'')
			 ElSE ''
			 END) AS SUId,
			 --add by dhruvik for 25772 mantis issue
			 ISNULL(CI.PayTypeId,0) as PayTypeId,			--add
			 ISNULL(CI.ChequeNo,'') as ChequeNo,			--add
			 ISNULL(CI.BankName,'') as BankName,			--add
			 ISNULL(CI.ChequeDate,'') as ChequeDate			--add
		
	   FROM sCanteen.tCanteenIssue CI
	   LEFT JOIN  sStudent.vStudentLastAcademic SMast ON SMast.StudentId = CI.SourceId AND CI.SourceTypeId = 2003  
       LEFT JOIN sHrm.tEmployeeMaster EM ON EM.Id = CI.SourceId AND CI.SourceTypeId = 95
     
      
	  
	  WHERE ((CI.Id = @rId) OR (@rId = 0))
		  AND CI.CanteenId = @rCanteenId
		  AND ((CI.IssueDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
		 AND ((CI.IssueDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
		 AND ((SMast.SUID = @rSUID) OR (ISNULL(@rSUID,'')=''))
	 --  AND ((CI.IssueDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
	 AND ISNULL(EM.IsOtherUser,0) = 0 
order by CI.IssueDate desc
	  --EXEC [sCanteen].[pCanteenIssueDetailGet] @rId,@rCanteenId
END
GO
PRINT N'Altering Procedure [sLibrary].[pNewspaperLogAdd]...';


GO


ALTER PROCEDURE [sLibrary].[pNewspaperLogAdd]
	
	@rId int,
	@rNewspaperId Int,
	@rNewsPaperDate DateTime,
	@rNoOfCopy Smallint,
	@rLibraryId int,
	@rCreatedUserId bigint,
	@rNewspaperAmount decimal(12,2)
		
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

IF(@rId = 0)
    BEGIN
    
	INSERT INTO [sLibrary].[tNewspaperLog]
           ([NewspaperId]
           ,[NewspaperDate]
           ,[NoOfCopy]
           ,[CreatedUserId]
           ,[CreatedDateTime]
		   ,[NewspaperAmount])
     VALUES
           (@rNewspaperId
           ,@rNewspaperDate
           ,@rNoOfCopy
           ,@rCreatedUserId
           ,sCommon.fGetDate(),
		   @rNewspaperAmount)
	SELECT 1 AS Result
	End
	ELSE 
	BEGIN
	 
	UPDATE [sLibrary].[tNewspaperLog]
		SET [NewspaperId] = @rNewspaperId
		  ,[NewspaperDate] = @rNewspaperDate
		  ,[NoOfCopy] = @rNoOfCopy
		  ,[NewspaperAmount] = @rNewspaperAmount
	WHERE  AutoId = @rId
		 SELECT 11 AS Result
	END
end
GO
PRINT N'Altering Procedure [sLibrary].[pNewspaperLogGet]...';


GO

ALTER PROCEDURE [sLibrary].[pNewspaperLogGet]
	 @rId bigint = 0,
	 @rNewspaperId int,
	 @rFromNewspaperDate Date,
	 @rToNewspaperDate Date,
	 @rLibraryId int

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	
		SELECT NL.AutoId AS Id
		  ,NM.Title AS NewsPaperName
		  ,NM.Id AS NewsPaperId
		  ,NM.Language AS NewsPaperLanguage
		  ,NM.LibraryId AS LibraryId
		  ,LM.Title AS LibraryName
		  ,isnull(NM.NewsTypeId,0) AS NewsTypeId
		  ,NM.CreatedUserId AS CreatedUserId
		  ,NM.CreatedDateTime AS CreatedDateTime
		  ,NL.NewsPaperDate AS NewsPaperDate
		  ,NL.NoOfCopy AS NoOfCopy,
		   isnull(NL.NewspaperAmount,0) AS NewspaperAmount
		 
		  
	  FROM [sLibrary].[tNewspaperLog] NL 
	  inner Join [sLibrary].[tNewspaperMaster] NM On NL.NewspaperId=NM.Id
	  inner join [sLibrary].[tLibraryMaster] LM ON LM.Id=NM.LibraryId
	  where 
	  (LM.Id=@rLibraryId)
		AND ((NL.AutoId=@rId) OR (@rId=0))
		AND ((NL.NewspaperId=@rNewspaperId) OR (@rNewspaperId=0))
		AND (NL.NewspaperDate>=@rFromNewspaperDate OR ISNULL(@rFromNewspaperDate,'')='')
		AND (NL.NewspaperDate<=@rToNewspaperDate OR ISNULL(@rToNewspaperDate,'')='')
		--AND ((NM.CreatedUserId=@rCreatedUserId) OR (@rCreatedUserId=0))
	--order By NL.NewsPaperDate
END
GO
PRINT N'Altering Procedure [sSetup].[pOrgGroupMasterAdd]...';


GO
ALTER PROCEDURE [sSetup].[pOrgGroupMasterAdd]
	 
	@rId int,
	@rCode nvarchar(20),
	@rTitle nvarchar(100),
	@rCRMLicenceNo int,
	@rPunchLine nvarchar(200),
	@rOrgGroupBatchName nvarchar(20),
	@rFromDate date,
	@rToDate date,
	@rIsWindowSupport bit=0,
	@rIsSync bit = 0,
	@rChannelPartner nvarchar(200),		--add for 26991 mantis
	@rBrandConfig nvarchar(max)			--add for 26991 mantis
	
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	 
	IF(@rId=0)
		BEGIN
		IF EXISTS(SELECT 1 FROM sSetup.tOrgGroupMaster WHERE Code=@rCode)
		BEGIN
			SELECT -100 AS Result
			RETURN
		END
	END
	
	BEGIN TRANSACTION	
		IF(@rId=0)
		BEGIN
		
			DECLARE @lOrgGroupId smallint
			DECLARE @lOrgGroupBatchId int
			SET @lOrgGroupId=@rCode
			DECLARE @lCreatedUserId Int
			SET @lCreatedUserId = 1
			DECLARE @lCreatedDateTime DATETIME
			SET @lCreatedDateTime =  sCommon.fGetDate()
			
	
			
			INSERT INTO sSetup.tOrgGroupMaster
			(
				Id,
				Code,
				Title,
				PunchLine,
				CRMLicenceNo,
				IsWindowSupport,
				ChannelPartner,				--add for 26991 mantis
				BrandConfig					--add for 26991 mantis
			)
			VALUES
			(
				@rCode,
				@rCode,
				@rTitle,
				@rPunchLine,
				@rCRMLicenceNo,
				@rIsWindowSupport,
				@rChannelPartner,			--add for 26991 mantis
				@rBrandConfig				--add for 26991 mantis
			)
			
	 IF ( @rIsSync = 0)
 BEGIN
			
			SELECT @lOrgGroupBatchId=ISNULL(MIN(Id),(Convert(nvarchar(10),Convert(nvarchar(10),@lOrgGroupId))+'00000')+1) 
			FROM sSetup.tOrgGroupBatchMaster WHERE OrgGroupId=@lOrgGroupId
			
					 INSERT INTO [sSetup].[tOrgGroupBatchMaster]
					   ([Id]
					   ,[Code]
					   ,[Title]
					   ,[OrgGroupId]
					   ,[IsHistory]
					   ,[IsActive]
					   ,[IsObsolete]
					   ,[OrderIndex]
					   ,[FromDate]
					   ,[ToDate]
					   ,[CreatedUserId]
					   ,[CreatedDateTime]
					   ,[UpdatedUserId]
					   ,[UpdatedDateTime])
			     
				  SELECT @lOrgGroupBatchId
					   ,@rOrgGroupBatchName
					   ,@rOrgGroupBatchName
					   ,@lOrgGroupId
					   ,0
					   ,1
					   ,0
					   ,1
					   ,@rFromDate
					   ,@rToDate
					  ,@lCreatedUserId
					  ,@lCreatedDateTime
					  ,@lCreatedUserId
					  ,@lCreatedDateTime
 END
			
			 INSERT INTO [sSecurity].[tRole]
				   ([Id]
				   ,[Title]
				   ,[Remark]
				   ,[IsObsolete]
				   ,[CreatedUserId]
				   ,[CreatedDateTime]
				   ,[UpdatedUserId]
				   ,[UpdatedDateTime]
				   ,[IsSystem]
				   ,[OrgGroupId])
			SELECT
				   sCommon.fGetIntIdForOrg(Id,@lOrgGroupId)
				  ,[Title]
				  ,[Remark]
				  ,[IsObsolete]
				  ,@lCreatedUserId
				  ,@lCreatedDateTime
				  ,@lCreatedUserId
				  ,@lCreatedDateTime
				  ,[IsSystem]
				  ,@lOrgGroupId
			  FROM [sSecurity].[tRole] WHere OrgGroupId=1          

			INSERT INTO [sFinanceCommon].[tStockUomMaster]
					   ([Id]
					   ,[Code]
					   ,[Title]
					   ,[IsObsolete]
					   ,[CreatedUserId]
					   ,[CreatedDateTime]
					   ,[UpdatedUserId]
					   ,[UpdatedDateTime]
					   ,[OrgGroupId])
				 SELECT
						 sCommon.fGetIntIdForOrg(6,@lOrgGroupId)
						,'Nos'
						,'Nos'
						,0
						,@lCreatedUserId
						,@lCreatedDateTime
						,@lCreatedUserId
						,@lCreatedDateTime
						,@lOrgGroupId
				 --FROM [sFinanceCommon].[tStockUomMaster] WHERE OrgGroupId=1
	
	
	
				INSERT INTO [sStudent].[tAdmissionCategoryMaster]
					   ([Id]
					   ,[Code]
					   ,[Title]
					   ,[IsObsolete]
					   ,[CreatedUserId]
					   ,[CreatedDateTime]
					   ,[UpdatedUserId]
					   ,[UpdatedDateTime]
					   ,[OrgGroupId])
				 SELECT
						 sCommon.fGetIntIdForOrg(1,@lOrgGroupId)
						,'General'
						,'General'
						,0
						,@lCreatedUserId
						,@lCreatedDateTime
						,@lCreatedUserId
						,@lCreatedDateTime
						,@lOrgGroupId
				 --FROM [sStudent].[tAdmissionCategoryMaster]
				 -- WHERE OrgGroupId=1

				
				
				INSERT INTO [sCommon].[tTableRowId]
					   ([OrgId]
					   ,[TableTitle]
					   ,[CurrentNumber]
					   ,[Seed]
					   ,[Increment])
				SELECT
					   @lOrgGroupId
					  ,[TableTitle]
					  
					  ,CASE 
				  WHEN IdDataType = 'int' THEN sCommon.fGetIntIdForOrg(ISNULL(CurrentNumber,0),@lOrgGroupId) 
				  WHEN IdDataType = 'bigint' THEN sCommon.fGetbigIntIdForOrg(ISNULL(CurrentNumber,0),@lOrgGroupId )
					END 
					
					  ,CASE 
				  WHEN IdDataType = 'int' THEN sCommon.fGetIntIdForOrg(ISNULL(CurrentNumber,0),@lOrgGroupId) 
				  WHEN IdDataType = 'bigint' THEN sCommon.fGetbigIntIdForOrg(ISNULL(CurrentNumber,0),@lOrgGroupId )
					END  
					   ,1
				  FROM [sCommon].[tTableRowIdMaster] where 
				  (tableType = 'Non Static' or tableType = '100Static' )
				  AND iddatatype <> '' AND IdScope = 'OrgGroup'

				
			--		INSERT INTO [sCommon].[tTableRowId]
			--           ([OrgId]
			--           ,[TableTitle]
			--           ,[CurrentNumber]
			--           ,[Seed]
			--           ,[Increment])
			--SELECT
			--		   0
			--		  ,[TableTitle]		  
			--		  ,CurrentNumber		
			--		  ,CurrentNumber
			--		  ,1
			--	  FROM [sCommon].[tTableRowIdMaster] where 
			--	  (tableType =   '100StaticCommon') 
			--	  AND IdScope = 'OrgGroup' 
			
			
			
				INSERT INTO sCommunication.tCircularTypeMaster
					   ([Id]
					   ,[Code]
					   ,[Title]
					   ,[IsObsolete]
					   ,[CreatedUserId]
					   ,[CreatedDateTime]
					   ,[UpdatedUserId]
					   ,[UpdatedDateTime]
					   ,[OrgGroupId]
					   ,HighlightColor)
				 SELECT
						 sCommon.fGetIntIdForOrg(1,@lOrgGroupId)
						,'Circular'
						,'Circular'
						,0
						,@lCreatedUserId
						,@lCreatedDateTime
						,@lCreatedUserId
						,@lCreatedDateTime
						,@lOrgGroupId
						,'#0000CC'
						
				INSERT INTO sCommunication.tCircularTypeMaster
					   ([Id]
					   ,[Code]
					   ,[Title]
					   ,[IsObsolete]
					   ,[CreatedUserId]
					   ,[CreatedDateTime]
					   ,[UpdatedUserId]
					   ,[UpdatedDateTime]
					   ,[OrgGroupId]
					   ,HighlightColor)
				 SELECT
						 sCommon.fGetIntIdForOrg(2,@lOrgGroupId)
						,'Alert'
						,'Alert'
						,0
						,@lCreatedUserId
						,@lCreatedDateTime
						,@lCreatedUserId
						,@lCreatedDateTime
						,@lOrgGroupId
						,'#006600'



			INSERT INTO sCommon.tReligionMaster
					   ([Id]
					   ,[Code]
					   ,[Title]
					   ,[IsObsolete]
					   ,[CreatedUserId]
					   ,[CreatedDateTime]
					   ,[UpdatedUserId]
					   ,[UpdatedDateTime]
					   ,[OrgGroupId]
					    )
				 SELECT						
						sCommon.fGetIntIdForOrg(ID,@lOrgGroupId)
					   ,[Code]
					   ,[Title]
					   ,[IsObsolete]
					   ,[CreatedUserId]
					   ,[CreatedDateTime]
					   ,[UpdatedUserId]
					   ,[UpdatedDateTime]
					   ,@lOrgGroupId
					   FROM sCommon.tReligionMaster WHERE OrgGroupId = 1
						

			INSERT INTO [sFrontOffice].[tVisitorTypeMaster]
					   (
						[Id]
					   ,[Code]
					   ,[Title]
					   ,[IsObsolete]
					   ,[CreatedUserId]
					   ,[CreatedDateTime]
					   ,[UpdatedUserId]
					   ,[UpdatedDateTime]
					   ,[OrgGroupId]
					   )
				 SELECT
					  
					   sCommon.fGetIntIdForOrg(ID,@lOrgGroupId)
					   ,[Code]
					   ,[Title]
					   ,[IsObsolete]
					   ,[CreatedUserId]
					   ,[CreatedDateTime]
					   ,[UpdatedUserId]
					   ,[UpdatedDateTime]
					   ,@lOrgGroupId
					   FROM [sFrontOffice].[tVisitorTypeMaster] WHERE OrgGroupId = 1
					   
					   
 			
				INSERT INTO sAdmission.tInquiryStatusMaster
					   ([Id]
					   ,[Code]
					   ,[Title]
					   ,[IsObsolete]
					   ,[CreatedUserId]
					   ,[CreatedDateTime]
					   ,[UpdatedUserId]
					   ,[UpdatedDateTime]
					   ,[OrgGroupId]
					   ,StatusId
					   )

				 SELECT
						 sCommon.fGetIntIdForOrg(Id,@lOrgGroupId)
						,Title
						,Title
						,0
						,1
						,sCommon.fGetDate()
						,NULL
						,NULL
						,@lOrgGroupId
						,Id	
						FROM sCommon.tStatusMaster SM
						where statustypeId = 104

				UPDATE ISM  
						SET ISM.HighlightColor = ISM1.HighlightColor ,
							ISM.InquiryMainStatusId = ISM1.InquiryMainStatusId
						FROM sAdmission.tInquiryStatusMaster ISM  
						INNER JOIN sAdmission.tInquiryStatusMaster ISM1 ON ISM.StatusId = ISM1.StatusId AND ISM1.OrgGroupId = 1
						INNER JOIN sCommon.tStatusMaster SM ON SM.Id = ISM1.StatusId 
						where SM.statustypeId = 104 AND ISM.OrgGroupId = @lOrgGroupId
						
				 Insert Into sCommunication.tFeedbackAnswerTypeMaster
				(
						Id,
						Code,
						Title,
						IsObsolete,
						OrgGroupId,
						CreatedUserId,
						CreatedDateTime,
						UpdatedUserId,
						UpdatedDateTime,
						FeedBackAnswerGroupMasterId
				)
				Values
				(
						sCommon.fGetIntIdForOrg(1,@lOrgGroupId),
						'Numeric',
						'Numeric',
						0,
						@lOrgGroupId,
						@lCreatedUserId,
						@lCreatedDateTime,
						NULL,
						NULL,
						2
				)
						
				Insert Into sCommunication.tFeedbackAnswerTypeMaster
				(
						Id,
						Code,
						Title,
						IsObsolete,
						OrgGroupId,
						CreatedUserId,
						CreatedDateTime,
						UpdatedUserId,
						UpdatedDateTime,
						FeedBackAnswerGroupMasterId
				)
				Values
				(
						sCommon.fGetIntIdForOrg(2,@lOrgGroupId),
						'Free Text',
						'Free Text',
						0,
						@lOrgGroupId,
						@lCreatedUserId,
						@lCreatedDateTime,
						NULL,
						NULL,
						3
				)
						
	DECLARE @lMaxId int
	SET @lMaxId = sCommon.fGetIntIdForOrg(213,@lOrgGroupId)					
	EXECUTE sCommon.pTableRowIdModify @lOrgGroupId, @rTableTitle = 'sAdmission.tInquiryStatusMaster', @rCurrentNumber = @lMaxId
						
 
					   
		END
		ELSE
		BEGIN
			UPDATE sSetup.tOrgGroupMaster
			SET
				Title=@rTitle,
				PunchLine=@rPunchLine,
				CRMLicenceNo=@rCRMLicenceNo,
				IsWindowSupport=@rIsWindowSupport,
				ChannelPartner=@rChannelPartner,				--add for 26991 mantis
				BrandConfig=@rBrandConfig						--add for 26991 mantis
				
			  WHERE Id = @rId 
	    END
	      
	  
	  
	  
	  IF NOT EXISTS(SELECT 1 FROM sCommon.tCastCategoryMaster WHERE OrgGroupId = @rCode)
BEGIN				
				INSERT INTO sCommon.tCastCategoryMaster
					   ([Id]
					   ,[Number]
					   ,[Code]
					   ,[Title]
					   ,[IsObsolete]
					   ,[CreatedUserId]
					   ,[CreatedDateTime]
					   ,[UpdatedUserId]
					   ,[UpdatedDateTime]
					   ,[OrgGroupId]
					   , MainCastCategoryId 
					   ,OrderIndex)
				 SELECT
						 sCommon.fGetIntIdForOrg(Id,@rCode)
						,Id	
						,Code
						,Title
						,0
						,1
						,sCommon.fGetDate()
						,1
						,sCommon.fGetDate()
						,@rCode
						,Id
						,Id						
						FROM sCommon.tMainCastCategoryMaster
						 
						
	DECLARE @lMaxCatId int
	SET @lMaxCatId = sCommon.fGetIntIdForOrg(100,@rCode)					
	EXECUTE sCommon.pTableRowIdModify @rCode, @rTableTitle = 'sCommon.tCastCategoryMaster', @rCurrentNumber = @lMaxCatId


			
			
END
	   

IF NOT EXISTS(SELECT 1 FROM sSetup.tBatchGroupMaster WHERE OrgGroupId = @rCode)
BEGIN				
				INSERT INTO sSetup.tBatchGroupMaster
					   ([Id]
					   ,[Number]
					   ,[Code]
					   ,[Title]					  
					   ,[CreatedUserId]
					   ,[CreatedDateTime]
					   ,[UpdatedUserId]
					   ,[UpdatedDateTime]
					   ,[OrgGroupId]					   
					   ,OrderIndex)
				 SELECT
						 sCommon.fGetIntIdForOrg(1,@rCode)
						,1	
						,'Common'
						,'Common'					
						,1
						,sCommon.fGetDate()
						,1
						,sCommon.fGetDate()
						,@rCode						 
						,1						
						 
						 
END						
	 


			
			

	      
	      SELECT @rCode AS Result	
		COMMIT TRANSACTION
		
		--  exec  [sCommon].[pOrganizationSetupAdd] @rId
		
	 
		
END
GO
PRINT N'Altering Procedure [sSetup].[pOrgGroupMasterGet]...';


GO
ALTER PROCEDURE [sSetup].[pOrgGroupMasterGet]
	 
	 @rId int,
	 @rTitle nvarchar(100),
	 @rCode nvarchar(20),
	 @rStatus nvarchar(5)
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
	BEGIN
		SET @rTitle = sCommon.fSearchStringGet(@rTitle)
		SET @rCode = sCommon.fSearchStringGet(@rCode)
		
		DECLARE @lIsObsolete bit = 0
			If(@rStatus='1')
		SET @lIsObsolete = 0
	else If(@rStatus='2')
		SET @lIsObsolete = 1
		--SET @rStatus = sCommon.fSearchStringGet(@rStatus)
	END
	SELECT 
		OB.Id,
		OB.Code,
		OB.Title,
		OB.CRMLicenceNo,
		ISNULL(OB.PunchLine,'') AS PunchLine,
		ISNULL(OB.IsWindowSupport,0) AS IsWindowSupport,
		ISNULL(OB.IsObsolete,0) AS IsObsolete,
		ISNULL(OB.ChannelPartner,'') AS ChannelPartner,			--add for 26991 mantis
		ISNULL(OB.BrandConfig,'') AS BrandConfig				--add for 26991 mantis
		
  FROM 
        sSetup.tOrgGroupMaster OB
  WHERE 
		((OB.Id=@rId) OR (@rId=0))
	AND (OB.Id!=1)
	AND ((OB.Code like @rCode) OR (ISNULL(@rCode,'')='')) 
	AND ((OB.Title like @rTitle) OR (ISNULL(@rTitle,'')='')) 
	AND ((ISNULL(OB.IsObsolete,0) = @lIsObsolete)OR( @rStatus=0))	
	--AND((ISNULL(OB.IsObsolete,0)=@rStatus))
END
GO
PRINT N'Altering Procedure [sAlert].[pIssueBookAllGet]...';


GO
ALTER PROCEDURE [sAlert].[pIssueBookAllGet]
	 
	 @rSourceTypeId smallint,
	 @rFromDate date,
	 @rToDate date,
	 @rOrgId smallint,
	 @rBatchId int,
	 @rDepartmentId int = 0,
	 @rClassId int = 0,
	 @rDivisionId int = 0,
	 @rTemplate nvarchar(max),	 	
	 @rMailSubject nvarchar(max)=''
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			
BEGIN 	
		SELECT distinct
			SC.OrgGroupId,
			SC.OrgId,
			SC.AcademicId,
			SC.Code,
			SC.Name AS Name,
			SC.ParentContactNo AS MobileNo,	
			SC.ParentEmail AS EmailId,
			SC.WhatsAppContactNo,
			replace (
			replace (
			replace(@rTemplate,'[Name]',SC.Name),			
			'[BookCode - BookName - IssueDate]',(SELECT STUFF ((SELECT distinct ',' +' ' + BM1.Code +' - '+BM1.Title+' - '+ CONVERT(nvarchar(100), BL1.LogDate, 103)
					From sLibrary.tBookLog BL1
					INNER JOIN sLibrary.tBookMaster BM1 ON BM1.Id=BL1.ResourceSourceId
					INNER JOIN sStudent.vStudentCommunication SC1 ON SC1.StudentId = BL1.ReaderSourceId AND SC1.BatchId = BL1.BatchId  AND BL1.ReaderSourceTypeId=2003
					INNER JOIN sSetup.tBatchMaster BMM1 ON BMM1.Id = BL1.BatchId 
					INNER JOIN sSetup.tOrganizationMaster OM1 ON OM1.Id = BL1.OrgId
					INNER JOIN sLibrary.tLibraryMaster LM1 ON LM.Id=BL1.LibraryId
					WHERE
							(BL1.ReaderSourceTypeId=@rSourceTypeId OR @rSourceTypeId=0)
						AND ((BL1.LogDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
						AND ((BL1.LogDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
						AND (BL1.OrgId = @rOrgId)
						AND (BL1.BatchId = @rBatchId)
						AND (BL1.ReaderSourceTypeId != 0)
						AND ((SC1.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
						AND ((SC1.ClassId=@rClassId) OR (@rClassId=0))
						AND ((SC1.DivisionId=@rDivisionId) OR (@rDivisionId=0))
						--AND BL1.IsCurrentStatus=1 
						AND BL1.StatusId = 523
						AND BL1.ReaderSourceId=BL.ReaderSourceId	
						AND (SC.StatusId=1) AND SC.IsBlockAllAlert=0	
                    FOR XML PATH('')),1,1,''))),
			'[LibraryName]',LM.Title)
			 AS Template,
			replace (
			replace (
			replace(@rTemplate,'[Name]',SC.Name),			
			'[BookCode - BookName - IssueDate]',(SELECT STUFF ((SELECT distinct ',' +' ' + BM1.Code +' - '+BM1.Title+' - '+ CONVERT(nvarchar(100), BL1.LogDate, 103)
					From sLibrary.tBookLog BL1
					INNER JOIN sLibrary.tBookMaster BM1 ON BM1.Id=BL1.ResourceSourceId AND BL1.ReaderSourceTypeId=2003
					AND BL1.ReaderSourceId=BL.ReaderSourceId  AND BL1.ReaderSourceId = SC.StudentId AND BL1.BatchId =SC.BatchId  
					AND BMM.Id = BL1.BatchId  AND BL1.OrgId = OM.Id AND  BL1.LibraryId =LM.Id
					AND (SC.StatusId=1) AND SC.IsBlockAllAlert=0
					AND BL1.StatusId = 523
					--AND BL1.IsCurrentStatus=1 		
                    FOR XML PATH('')),1,1,'') )),
			'[LibraryName]',LM.Title)
			 AS MsgText,
			'2003' AS SourceTypeId,
			SC.StudentId AS SourceId,
			@rMailSubject AS Subject,
			2003 AS ReceiverSourceTypeId,
			SC.StudentId AS ReceiverSourceId,
			LM.Title AS LibraryName
	From 
		sLibrary.tBookLog BL
		INNER JOIN sLibrary.tBookMaster BM ON BM.Id=BL.ResourceSourceId
		INNER JOIN sStudent.vStudentCommunication SC ON SC.StudentId = BL.ReaderSourceId AND SC.BatchId = BL.BatchId  AND BL.ReaderSourceTypeId=2003
		INNER JOIN sSetup.tBatchMaster BMM ON BMM.Id = BL.BatchId 
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = BL.OrgId
		INNER JOIN sCommon.tStatusMaster SM ON SM.Id=BL.StatusId
		INNER JOIN sLibrary.tLibraryMaster LM ON LM.Id=BL.LibraryId
	WHERE
		(BL.ReaderSourceTypeId=@rSourceTypeId OR @rSourceTypeId=0)
		AND ((BL.LogDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
		AND ((BL.LogDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
				AND (BL.OrgId = @rOrgId OR @rOrgId=0)
		AND (BL.BatchId = @rBatchId OR @rBatchId = 0)
		AND (BL.ReaderSourceTypeId != 0)
		AND ((SC.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
		AND ((SC.ClassId=@rClassId) OR (@rClassId=0))
		AND ((SC.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		AND (SC.StatusId=1) AND SC.IsBlockAllAlert=0	
		AND BL.StatusId = 523
		--AND BL.IsCurrentStatus=1 

	UNION 

	SELECT distinct
			OM.OrgGroupId,
			EC.OrgId,
			EC.EmployeeId As AcademicId,
			EC.Code,
			EC.EmployeeName AS Name,
			EC.MobileNumber AS MobileNo,	
			EC.CompanyEmail AS EmailId,
			EC.WhatsAppContactNo,
			replace (
			replace (
			replace(@rTemplate,'[Name]',EC.EmployeeName),			
			'[BookCode - BookName - IssueDate]',(SELECT STUFF ((SELECT distinct ',' +' ' + BM1.Code +' - '+BM1.Title+' - '+ CONVERT(nvarchar(100), BL1.LogDate, 103)
						From sLibrary.tBookLog BL1
							INNER JOIN sLibrary.tBookMaster BM1 ON BM1.Id=BL1.ResourceSourceId AND BL1.ReaderSourceTypeId=95
							AND BL1.ReaderSourceId=BL.ReaderSourceId  AND BL1.ReaderSourceId = EC.EmployeeId 
							AND BL1.OrgId = OM.Id AND  BL1.LibraryId =LM.Id AND ODM.Id = EC.DepartmentId
							AND ISNULL(EC.IsOtherUser,0) = 0  AND EC.StatusId = 7
							--AND BL1.IsCurrentStatus=1
							AND BL1.StatusId = 523
                    FOR XML PATH('')),1,1,'') )),
			'[LibraryName]',LM.Title)
			 AS Template,
			replace (
			replace (
			replace(@rTemplate,'[Name]',EC.EmployeeName),			
			'[BookCode - BookName - IssueDate]',(SELECT STUFF ((SELECT distinct ',' +' ' + BM1.Code +' - '+BM1.Title+' - '+ CONVERT(nvarchar(100), BL1.LogDate, 103)
						From sLibrary.tBookLog BL1
							INNER JOIN sLibrary.tBookMaster BM1 ON BM1.Id=BL1.ResourceSourceId AND BL1.ReaderSourceTypeId=95
							AND BL1.ReaderSourceId=BL.ReaderSourceId  AND BL1.ReaderSourceId = EC.EmployeeId 
							AND BL1.OrgId = OM.Id AND  BL1.LibraryId =LM.Id AND ODM.Id = EC.DepartmentId
							AND ISNULL(EC.IsOtherUser,0) = 0  AND EC.StatusId = 7
							AND BL1.StatusId = 523
							--AND BL1.IsCurrentStatus=1	
                    FOR XML PATH('')),1,1,'') )),
			'[LibraryName]',LM.Title)
			 AS MsgText,
			'95' AS SourceTypeId,
			EC.EmployeeId AS SourceId,
			@rMailSubject AS Subject,
			95 AS ReceiverSourceTypeId,
			EC.EmployeeId AS ReceiverSourceId,
			LM.Title AS LibraryName
	         
	FROM 
		sLibrary.tBookLog BL
		INNER JOIN sLibrary.tBookMaster BM ON BM.Id=BL.ResourceSourceId
		INNER JOIN sHrm.vEmployeeCommunication EC ON EC.EmployeeId=BL.ReaderSourceId AND BL.ReaderSourceTypeId=95 
		INNER JOIN sSetup.tDepartmentMaster ODM ON ODM.Id = EC.DepartmentId
		INNER JOIN [sSetup].[tOrganizationMaster] OM ON OM.Id = EC.OrgId
		INNER JOIN sCommon.tStatusMaster SM ON SM.Id=BL.StatusId
		INNER JOIN sLibrary.tLibraryMaster LM ON LM.Id=BL.LibraryId

	WHERE 

		 (BL.OrgId = @rOrgId OR @rOrgId=0)
		AND (BL.BatchId = @rBatchId OR @rBatchId = 0)
		AND ((EC.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
		AND ((BL.LogDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
		AND ((BL.LogDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
		AND (BL.ReaderSourceTypeId=@rSourceTypeId OR @rSourceTypeId=0)
		AND ISNULL(EC.IsOtherUser,0) = 0  AND EC.StatusId = 7	
		AND BL.StatusId = 523
		--AND BL.IsCurrentStatus=1 
		 
END
GO
PRINT N'Altering Procedure [sAlert].[pNotificationLogAdd]...';


GO
ALTER PROCEDURE [sAlert].[pNotificationLogAdd]
	
	@rXML nvarchar(max),
	@rOrgGroupId smallint
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	
BEGIN
BEGIN TRY
	
	BEGIN TRANSACTION
	 
	SET @rXML=REPLACE(@rXML,'&','AND')
	DECLARE @lCount INT
	DECLARE @lInterrorCode INT,
			@intDoc INT
	EXECUTE @lInterrorCode = sp_xml_preparedocument @intDoc OUTPUT, @rXML
	
	DECLARE @lNextNumber BIGINT  
	DECLARE @lFromNextNumber BIGINT  
	
	EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sAlert.tNotificationLog', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	SET @lFromNextNumber=@lNextNumber-1
	
	INSERT INTO sAlert.tNotificationLog
		(
			Id,
			OSTypeId,
			SourceTypeId,
			SourceId,
			EventId,
			DocumentId,
			MessageTitle,
			NotificationMessage,
			APIResponse,
			StatusCode,
			CreatedUserId,
			CreatedDateTime,
			IsViewed
		)
	SELECT
			@lFromNextNumber + ROW_NUMBER() OVER(ORDER BY SourceId),
			OSTypeId,
			SourceTypeId,
			SourceId,
			EventId,
			DocumentId,
			MessageTitle,
			NotificationMessage,
			APIResponse,
			StatusCode,
			CreatedUserId,
			sCommon.fGetDate(),
			(CASE WHEN OSTypeId = 3 THEN 0 ELSE NULL END)IsViewed
			
	FROM OPENXML (@intDoc, '/Table/NotificationLog', 1)
	WITH
	(
			OSTypeId tinyint 'OSTypeId',
			SourceTypeId smallint 'SourceTypeId',
			SourceId bigint 'SourceId',
			EventId int 'EventId',
			DocumentId bigint 'DocumentId',
			MessageTitle nvarchar(200) 'MessageTitle',
			NotificationMessage nvarchar(max) 'NotificationMessage',
			APIResponse nvarchar(500) 'APIResponse',
			StatusCode nvarchar(50) 'StatusCode',
			CreatedUserId bigint 'CreatedUserId'
	)
	
		SELECT @lCount = COUNT(1) FROM OPENXML (@intDoc, '/Table/NotificationLog', 1)
			WITH (SourceId bigint)
				 
		SET @lNextNumber  = @lCount + @lFromNextNumber 
		
		EXECUTE sCommon.pTableRowIdModify @rOrgGroupId, @rTableTitle = 'sAlert.tNotificationLog', @rCurrentNumber = @lNextNumber 
		
		EXEC sp_xml_removedocument @intDoc
		
		SELECT 1 AS Result,@lFromNextNumber+1 AS FromId,@lNextNumber AS ToId
		
		COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH
END
GO
PRINT N'Altering Procedure [sAlert].[pStudentBiometricFirstInTimeGet]...';


GO

ALTER PROCEDURE [sAlert].[pStudentBiometricFirstInTimeGet]
	@rTemplate nvarchar(max)='',
	@rSubject nvarchar(100)='',
	@rOrgId int,
	@rIntervalTime int

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY	
		BEGIN TRANSACTION 
		declare @lDateTimeNow datetime=[sCommon].[fGetDate]()
			if object_id('tempdb..#tTable') is not null
			BEGIN
				DROP TABLE #tTable
			END
			CREATE TABLE #tTable(
					SourceId bigint NOT NULL,
					In_Out_Time [datetime] NOT NULL,
					SourceTypeId int NOT NULL,
					CreatedDateTime [datetime] NOT NULL,
				)
			insert into #tTable
			select CDT.SourceId,min(CDT.In_Out_Time),CDT.SourceTypeId,min(CDT.CreatedDateTime) 
			from [sBiometric].[tCloudTransactionData] CDT
			inner join sBiometric.tShiftMasterCloud SMC ON SMC.ShiftCode=CDT.ShiftCode
			WHERE CDT.Attn_Dt=CONVERT(date,@lDateTimeNow)  AND CDT.SourceTypeId=2003
				AND (SMC.IsStopInTimeAlertTime=0 OR (SMC.IsStopInTimeAlertTime=1 
				AND CAST(SMC.StopInTimeAlertTime as Time)>=CAST(DATEADD(minute,(@rIntervalTime),[sCommon].[fGetDate]()) AS Time)
				AND  CAST(SMC.StopInTimeAlertTime as Time)>=CAST(CDT.In_Out_Time AS Time)))
			 Group by CDT.SourceId,CDT.SourceTypeId
	
			--select * from #tTable
			SELECT 
				SC.ParentContactNo AS MobileNo,	
				SC.ParentEmail AS EmailId,
				replace (
				replace (
				replace (
				replace(@rTemplate,'[StudentName]',SC.Name),
				'[TimeStamp]',ISNULL(Convert(varchar,temp.In_Out_Time,108),'')),
				'[PresentTime]',ISNULL(Convert(varchar,temp.In_Out_Time,108),'')),
				'[PresentDate]',ISNULL(Convert(varchar,[sCommon].[fGetDate](),103),''))
				 AS MsgText,
				@rSubject AS Subject,
				2003 AS ReceiverSourceTypeId,
				SC.StudentId AS ReceiverSourceId,
				SC.Name AS StudentName,
				SC.Code AS Code,
				ISNULL(SC.WhatsAppContactNo,'') AS WhatsAppContactNo,
				2003 AS SourceTypeId,
				SC.StudentId AS SourceId,
				SC.OrgId,
				OM.OrgGroupId,
				ISNULL(Convert(varchar,temp.In_Out_Time,108),'') as Time,
				OM.DisplayTitle AS OrganizationTitle


			FROM 
				#tTable temp
				Inner join sStudent.vStudentCommunication SC ON temp.SourceId=SC.StudentId AND SC.IsActiveBatch=1
				INNER JOIN sSetup.tOrganizationMaster OM ON SC.OrgID = OM.Id
			WHERE
				temp.CreatedDateTime >= DATEADD(minute,-(@rIntervalTime),@lDateTimeNow)
				AND SC.OrgID =@rOrgId
				AND SC.StatusId = 1
			DROP TABLE #tTable
		COMMIT TRANSACTION
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH

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


GO
ALTER PROCEDURE [sAssessment].[pStudentwiseOptionalSubjectListGet]
                  
    @rDivisionId bigint,
    @rClassId bigint,
    @rSubjectId bigint ,
    @rBatchId int,
    @rBuilder1 nvarchar(max)='',
	@rBuilder2 nvarchar(max)='',
	@rClassStatusId int=0,
	@rStatusId int=1,
    @rViewMode smallint = 0,  -- 0 for Vertical and 1 for Horizontal
	@rSubjects nvarchar(max)=''
AS
SET NOCOUNT ON

BEGIN

	IF(@rViewMode = 1)
	BEGIN
		SELECT
			SA.AcademicId,
			CS.Id as ClassSubjectId,
			SA.Name as StudentName,
			CS.SubjectId, 
			SA.Code,
			SA.RollNo,
			SA.DivisionId,
			SA.ClassName,
			SA.DivisionName
			INTO #TempTable 
			FROM
			(
					SELECT * FROM sStudent.vStudentAcademic 
					where (DivisionId = @rDivisionId OR @rDivisionId = 0)  AND BatchId = @rBatchId
					AND (ClassStatusId = @rClassStatusId OR @rClassStatusId = 0) 
					AND (StatusId = @rStatusId OR @rStatusId = 0)) SA  
					CROSS JOIN
					(select * FROM sSetup.tClassSubject B   
					WHERE  B.IsOptional = 1 AND (B.ClassId = @rClassId OR @rClassId = 0)  
					AND  (B.Id = @rSubjectId OR @rSubjectId = 0) 
			) AS CS

		SELECT DISTINCT
			SS.AcademicId,
			Stuff ((select ',' + Convert(nvarchar(20),OS.ClassSubjectId) FROM sAssessment.tOptionalSubject OS WHERE AcademicId = SS.AcademicId FOR XML PATH('') ),1,1,'') AS ClassSubjectId,
			SS.StudentName,
			SS.Code,
			SS.RollNo,
			@rBuilder1 AS ClassName,
			@rBuilder2 AS DivisionName,
			SS.DivisionId,
			SS.ClassName AS ClsName,
			SS.DivisionName AS DivName,
			@rSubjects
			FROM
			#TempTable AS SS
			INNER JOIN sSetup.tSubjectMaster SM ON SS.SubjectId = SM.Id 
			LEFT JOIN sAssessment.tOptionalSubject OS ON OS.AcademicId = SS.AcademicId AND OS.ClassSubjectId = SS.ClassSubjectId

			DROP TABLE #TempTable
	END
	ELSE
	BEGIN
		SELECT 
		SS.AcademicId,
		SS.ClassSubjectId,
		SS.StudentName,
		SS.SubjectId,
		SM.Code as SubjectName,
		SS.Code,
		SS.RollNo,
		@rBuilder1 AS ClassName,
		@rBuilder2 AS DivisionName,
		SS.DivisionId,
		SS.ClassName AS ClsName,
		SS.DivisionName AS DivName,
		CASE WHEN isnull(OS.ClassSubjectId,0) <> 0 THEN 'true' ELSE 'false' END AS Selected
		FROM
		(SELECT
		SA.AcademicId,
		CS.Id as ClassSubjectId,
		SA.Name as StudentName,
		CS.SubjectId, 
		SA.Code,
		SA.RollNo,
		SA.DivisionId,
		SA.ClassName,
		SA.DivisionName
		FROM
		 (select * FROM sStudent.vStudentAcademic where (DivisionId=@rDivisionId OR @rDivisionId = 0)  AND BatchId=@rBatchId AND (ClassStatusId=@rClassStatusId OR @rClassStatusId=0) AND (StatusId=@rStatusId OR @rStatusId=0))SA  
		 CROSS JOIN    (select * FROM sSetup.tClassSubject B   WHERE  B.IsOptional = 1 AND (B.ClassId = @rClassId OR @rClassId = 0)  AND  (B.Id= @rSubjectID OR @rSubjectId= 0) 
		) AS CS 
		 ) AS SS
		 INNER JOIN sSetup.tSubjectMaster SM ON SS.SubjectId = SM.Id 
		 LEFT JOIN sAssessment.tOptionalSubject OS ON OS.AcademicId = SS.AcademicId AND OS.ClassSubjectId = SS.ClassSubjectId

		ORDER BY SS.RollNo,SM.OrderIndex
	   END
END
GO
PRINT N'Altering Procedure [sAttendance].[pStudentLeaveRequestGet]...';


GO
ALTER PROCEDURE [sAttendance].[pStudentLeaveRequestGet] 
	 
	 	@rAcademicId bigint,
        @rLeaveFromDate date='',
        @rLeaveToDate date='' ,
        @rOrgID int=0,
        @rBatchId int=0
		
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	 
	Select
		SL.AcademicId,
		ISNULL(SL.LeaveFromDate,'')AS LeaveFromDate,
		ISNULL(SL.LeaveToDate,'')AS LeaveToDate,
		SL.LeaveReason,
		SM.Code As IdNo,
		SM.FirstName+' ' +SM.MiddleName+' ' +SM.LastName As Name,
		ISNULL(SL.StatusId,0) AS StatusId,  
      ISNULL(S.Title,'Pending') AS StatusName,  
      ISNULL(SL.StatusReason,'') AS  StatusReason
		
	from sAttendance.tStudentLeaveRequest SL
	INNER JOIN sStudent.tAcademic A ON A.Id=SL.AcademicId
	INNER JOIN sStudent.tStudentMaster SM ON SM.Id=A.StudentId
	LEFT JOIN sCommon.tStatusMaster S ON S.Id = SL.StatusId 
	Where ((AcademicId=@rAcademicId) OR (@rAcademicId=0))
	AND ((LeaveFromDate >= @rLeaveFromDate) OR (ISNULL(@rLeaveFromDate,'')=''))
	AND ((LeaveToDate <= @rLeaveToDate) OR (ISNULL(@rLeaveToDate,'')=''))
	AND ((SM.OrgId=@rOrgID)OR(@rOrgID=0))
	AND ((A.BatchId=@rBatchId)OR(@rBatchId=0))
	
END
GO
PRINT N'Altering Procedure [sAttendance].[pStudentRegisterXMLAdd]...';


GO
ALTER PROCEDURE [sAttendance].[pStudentRegisterXMLAdd]
	(
		@rXmlDoc nvarchar(MAX)
	)
AS

SET NOCOUNT ON

BEGIN
SET @rXmlDoc=REPLACE(@rXmlDoc,'&','AND')
DECLARE @lInterrorCode INT,
			@intDoc INT
BEGIN TRY
BEGIN TRANSACTION	
	EXECUTE @lInterrorCode = sp_xml_preparedocument @intDoc OUTPUT, @rXmlDoc	
	-----------------------
	DELETE SA FROM sAttendance.tStudentRegister SA INNER JOIN 
	(SELECT AcademicId,AttendanceDate FROM OPENXML (@intDoc, '/Table/StudentAttendace', 1)
	WITH
	(		
		AcademicId BigINT '@Id',
		AttendanceDate DateTime '@AttendanceDate'
	))A ON  SA.AcademicId = A.AcademicId AND SA.AttendanceDate=A.AttendanceDate AND SA.AttendanceTypeId = 1
		
	
	INSERT INTO sAttendance.tStudentRegister
	(
		AcademicId,
		AttendanceDate,
		IsPresent,
		AttendanceTypeId,
		CreatedUserId,
		CreatedDateTime	
	)
	SELECT
		AcademicId,
		AttendanceDate,
		IsPresent,
		1,
		3,		--they want Admin in created user id so put 3 insted of 1 because 1 stands for SysSuperAdmin and 3 stands for Admin. Mantis id 26812
		sCommon.fGetDate()	
		
	FROM OPENXML (@intDoc, '/Table/StudentAttendace', 1)
	WITH
	(		
		AcademicId BigINT '@Id',
		AttendanceDate DateTime '@AttendanceDate',
		IsPresent Smallint '@Present'
	)A
	
	
	EXEC sp_xml_removedocument @intDoc
	COMMIT TRANSACTION
	SELECT 1
	END TRY
	BEGIN CATCH
	SELECT -1
	END CATCH

END
GO
PRINT N'Altering Procedure [sAttendance].[pUpdateResultAttendance]...';


GO

ALTER PROCEDURE [sAttendance].[pUpdateResultAttendance]
	 	 
		 @rClassId int=0,
		 @rDivisionId int=0,
		 @rStudentCode nvarchar(20)='',	
	 	 @rAttendanceTypeId tinyint=1,	 	 
		 @rFromAttendanceDate date='',
		 @rToAttendanceDate date='',
	 	 @rBatchId int,
	 	 @rOrgId int,
	 	 @rExamId int,
	 	 @rExamSubGroupId int=0
	  
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
 
 

BEGIN 
 
		
	CREATE TABLE #tResultAttendance
	 (
	 ExamId int,  
	 AcademicId  bigint,	 
	 PresentCount int,
	 AbsentCount int 
	 )

   INSERT INTO #tResultAttendance
   (ExamId,AcademicId,PresentCount,AbsentCount)
   	SELECT
   	EM.Id, 
   	SA.Id,
	   ISNULL((SELECT count(AcademicId) FROM sAttendance.tStudentRegister SR	 
		WHERE		 
		 SR.AttendanceDate >= @rFromAttendanceDate
		AND SR.AttendanceDate <= @rToAttendanceDate
		AND 
		SR.AcademicId = SA.Id
		AND SR.IsPresent = 1
		AND SR.AttendanceTypeId = @rAttendanceTypeId				
		) ,0)
		 AS PresentCount
		 , 
	   ISNULL((SELECT count(AcademicId) FROM sAttendance.tStudentRegister SR	 
		WHERE		 
		 SR.AttendanceDate >= @rFromAttendanceDate
		AND SR.AttendanceDate <= @rToAttendanceDate		
		AND 
		SR.IsPresent = 0
		AND SR.AttendanceTypeId = @rAttendanceTypeId
		AND SR.AcademicId = SA.Id		
		),0)
		 AS AbsentCount 		
  FROM 
		 sStudent.tAcademic SA 
		 INNER JOIN sStudent.tStudentMaster SM ON SM.Id=SA.StudentId
		 INNER JOIN sAssessment.tExamMaster EM ON SA.BatchId = EM.BatchId 
		 AND SA.ClassId = EM.ClassId
		 AND EM.ExamSubGroupId = 	@rExamSubGroupId
		 AND EM.BatchId = @rBatchId	 
		 INNER JOIN sAssessment.tExamStatus ES ON ES.ExamId = EM.Id AND ES.DivisionId = SA.DivisionId 
         WHERE
   --       ((SM.Code=@rStudentCode) OR (@rStudentCode=''))         
		 --AND 
		 ((SA.ClassId=@rClassId) OR (@rClassId=0))
	     AND ((SA.DivisionId=@rDivisionId) OR (@rDivisionId=0)) 
         AND (SA.OrgId = @rOrgId)
         AND (SA.BatchId = @rBatchId)
		 --AND ES.StatusId <> 504 -- commented by sarangi if result is generated then attendance not Updated - mantisid - 0026854
        
  
 -- Select * from #tResultAttendance
    INSERT INTO sAssessment.tStudentRemark
    (ExamId,AcademicId,PresentDays,TotalDays)
    SELECT RA.ExamId,RA.AcademicId,CONVERT(decimal(6, 2),PresentCount),CONVERT(decimal(6, 2),AbsentCount) + CONVERT(decimal(6, 2),PresentCount)
    --,SR.AcademicId,SR.ExamId
    FROM #tResultAttendance RA LEFT JOIN sAssessment.tStudentRemark SR
    ON RA.AcademicId = SR.AcademicId AND RA.ExamId = SR.ExamId
    WHERE SR.AcademicId IS NULL   AND SR.ExamId IS NULL
    
   
    
    UPDATE SR
    SET PresentDays = CONVERT(decimal(6, 2),RA.PresentCount),
         TotalDays = CONVERT(decimal(6, 2),RA.PresentCount) + CONVERT(decimal(6, 2),RA.AbsentCount)
    FROM sAssessment.tStudentRemark SR INNER JOIN
    #tResultAttendance RA 
    ON  SR.ExamId = RA.ExamId AND SR.AcademicId = RA.AcademicId
    --INNER JOIN sAssessment.tExamMaster EM ON EM.Id = SR.ExamId
    --WHERE EM.ExamSubGroupId = @rExamSubGroupId
 
 --Select * from sAssessment.tStudentRemark Order by UpdatedDateTime desc
 SELECT 1 AS RESULT
END
GO
PRINT N'Altering Procedure [sAudit].[pActivityLogGet]...';


GO


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

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


GO
ALTER PROCEDURE [sCertificate].[pLeavingBulkGet]
	 
	 @rClassID int,
	 @rDivisionId int,
	 @rOrgId int,
	 @rBatchId int,
	 @rStatusId smallint=0
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	
	SELECT 
			SA.AcademicId,
			ISNULL(SA.RollNo,0) AS RollNo,
			SA.Code,
			SA.Name,
			SA.Number,
			ISNULL(L.Id,0) AS Id,
			ISNULL(L.LCNumber,0) AS LCNumber,
			ISNULL(L.LCDate,'') AS LCDate,
			ISNULL(L.LCRemark,'')AS LCRemark,
			ISNULL(L.LastExamName,'')AS LastExamName,
			ISNULL(L.LastExamResult,'')AS LastExamResult,
			ISNULL(L.RepeatDetail,'')AS RepeatDetail,
			--ISNULL(L.SubjectStudied,'')AS SubjectStudied,
			ISNULL(L.PromoteToClass,'')AS PromoteToClass,
			ISNULL(L.ExtraCurricularActivities,'')As ExtraCurricularActivities,
			ISNULL(L.NCCScoutDetail,'')AS NCCScoutDetail,
			ISNULL(L.TermsInInstitute,'')As TermsInInstitute,
			ISNULL(L.FeeDetail,'')AS FeeDetail,
			ISNULL(L.FeeConcessionDetail,'')AS FeeConcessionDetail,
			ISNULL(AD.TotalDaysAnnual,0)AS TotalDays,
			ISNULL(AD.PresentDaysAnnual,0)AS PresentDays,
			ISNULL(StuA.ProofOfDOB,'')AS ProofOfDOB,
			CASE WHEN EXISTS(SELECT 1 FROM sSetup.tSubjectMaster S  INNER JOIN sSetup.tClassSubject CS ON  S.Id = CS.SubjectId AND CS.ClassId=@rClassId	
								WHERE S.OrgId=@rOrgId AND CS.IsOptional=0) THEN
			reverse(STUFF(reverse(isnull([sCommon].[fXMLTagsReplaceReverse](STUFF((SELECT ',' + S.Title from sSetup.tSubjectMaster S  
						   INNER JOIN sSetup.tClassSubject CS ON  S.Id = CS.SubjectId AND CS.ClassId=@rClassId	
						   WHERE S.OrgId=@rOrgId AND CS.IsOptional=0 FOR XML PATH('')), 1, 1, '')),'') +',' +
			isnull([sCommon].[fXMLTagsReplaceReverse](STUFF((SELECT ',' + S.Title FROM sAssessment.tOptionalSubject OS 
						   INNER JOIN sSetup.tClassSubject CS ON CS.Id = OS.ClassSubjectId 
						   INNER JOIN sSetup.tSubjectMaster S ON  S.Id = CS.SubjectId 
						   WHERE OS.AcademicId = SA.AcademicId FOR XML PATH('')), 1, 1, '')),'') 
						   ), 1, 1, '')) 
						   
			ELSE

			STUFF(reverse(reverse(isnull([sCommon].[fXMLTagsReplaceReverse](STUFF((SELECT ',' + S.Title from sSetup.tSubjectMaster S  
						   INNER JOIN sSetup.tClassSubject CS ON  S.Id = CS.SubjectId AND CS.ClassId=@rClassId	
						   WHERE S.OrgId=@rOrgId AND CS.IsOptional=0 FOR XML PATH('')), 1, 1, '')),'') +',' +
			isnull([sCommon].[fXMLTagsReplaceReverse](STUFF((SELECT ',' + S.Title FROM sAssessment.tOptionalSubject OS 
						   INNER JOIN sSetup.tClassSubject CS ON CS.Id = OS.ClassSubjectId 
						   INNER JOIN sSetup.tSubjectMaster S ON  S.Id = CS.SubjectId 
						   WHERE OS.AcademicId = SA.AcademicId FOR XML PATH('')), 1, 1, '')),'') 
						   )), 1, 1, '') END AS SubjectStudied,
			(SA.ClassName +'-'+SA.DivisionName)AS ClassDivision


			
			
  FROM 
			[sStudent].[vStudentAcademic]  SA 
			LEFT OUTER JOIN sCertificate.tLeaving L ON L.AcademicId=SA.AcademicId
			LEFT JOIN sStudent.tAcademicDetail AD ON SA.AcademicId=AD.AcademicId
			LEFT JOIN sStudent.tStudentAdmission StuA ON StuA.StudentId = SA.StudentId
  WHERE 
			(SA.ClassId=@rClassId OR @rClassId=0)
			AND (SA.DivisionId=@rDivisionId OR @rDivisionId=0)
			AND SA.BatchId=@rBatchId
			AND SA.OrgID=@rOrgId 
			AND L.Id IS NULL
			AND((SA.StatusId=@rStatusId)OR(@rStatusId=0))
			--order by
			--CASE @rOrderBy WHEN 2 THEN (CASE ISNUMERIC(SA.Code) WHEN 1 THEN REPLICATE(0 , 100 - LEN(SA.Code)) + SA.Code ELSE SA.Code  END) END,
			--CASE @rOrderBy WHEN 1 THEN SA.RollNo END,
			--CASE @rOrderBy WHEN 0 THEN SA.RollNo END
END
GO
PRINT N'Altering Procedure [sCommunication].[pMyBookGet]...';


GO
ALTER PROCEDURE [sCommunication].[pMyBookGet]
	 
	 @rReaderSourceTypeId smallint,
	 @rReaderSourceId bigint,
	 @rBatchId int,
	 @rStatusId int=0,
	 @rLibraryId int=0
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 



	select 
		BL.Id AS BookLogId,
		BM.Title AS BookTitle,
		BL.LogDate AS IssueDate,
		--BL.IsCurrentStatus AS IsReturnPending,
		BL.StatusId AS StatusId,
		CASE WHEN SM.Title = 'Available' THEN 'Return' ELSE SM.Title END AS StatusName,
		--due to status not display properly
		--(CASE WHEN (ISNULL(BL.ReturnDate,'')!='' OR BL.BookActionStatusId=1) THEN 'Return'
		--	 WHEN BL.BookActionStatusId=2 THEN 'Release'
		--	 ELSE SM.Title END) AS StatusName,
		CASE WHEN BL.IsCurrentStatus = 1 THEN 'Pending' ELSE 'Return' END AS IsReturnPending,
		BL.DueDate,
		BL.LibraryId ,
		ISNULL(BM.Author,'')AS Author
	--CASE WHEN BL.IsCurrentStatus = 0 THEN BL.DueDate ELSE '' END AS DueDate

	  from 
		  sLibrary.tBookLog BL 
		  INNER JOIN sLibrary.tBookMaster BM
		  ON BL.ResourceSourceId = BM.Id AND BL.ResourceSourceTypeId = 2009  
		  LEFT JOIN sCommon.tStatusMaster SM ON SM.Id = BL.StatusId AND SM.statusTypeId = 106
	  WHERE 
		  --BL.statusId = 523
		  BL.ReaderSourceId = @rReaderSourceId
		  AND BL.ReaderSourceTypeId = @rReaderSourceTypeId
		  AND (BL.StatusId = @rStatusId OR @rStatusId=0)
		  AND (BL.LibraryId= @rLibraryId OR @rLibraryId=0)
		  AND (SM.Id!=521 OR ISNULL(BL.BookActionStatusId,0)!=0)
		  AND (BL.BatchId = @rBatchId OR @rBatchId = 0)
	  
	  ORDER BY BL.LogDate DESC,BL.CreatedDateTime DESC

END
GO
PRINT N'Altering Procedure [sHrm].[pRptEmployeeAvailableLeaveWithPay]...';


GO
ALTER PROCEDURE [sHrm].[pRptEmployeeAvailableLeaveWithPay]

		@rBuilder1 nvarchar(max)='',
		@rBuilder2 nvarchar(max)='',
		@rDepartmentId int,
		@rEmployeeGradeId int,
		@rEmployeeStatusId int=0,
		@rEmployeeCode nvarchar (200),
		@rEmployeeName nvarchar(200),
		@rBatchId int,
		@rOrgId int,
		@rLeaveTypeIds nvarchar(50) = '',
		@rEmployeeId bigint=0

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

	SELECT
		@rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,
		EM.Code AS EmployeeCode,
		EM.EmployeeName,
		EM.EmployeeId,
		EM.DepartmentName,
		EM.EmployeeGrade,
		ISNULL(ESO.BasicPay,0) AS BasicPay,
		LTM.Id AS LeaveTypeId,
		LTM.Title AS LeaveType,
		(SELECT	(ISNULL(LB.BalanceLeave,0) - ISNULL(SUM(NoOfLeave),0)) AS AvailableBalance
		 FROM sHrm.tLeaveBalance LB
			  LEFT JOIN sHrm.tLeave L ON LB.EmployeeId=L.EmployeeId AND LB.BatchId = L.BatchId AND LB.LeaveTypeId = L.LeaveTypeId AND L.StatusId = 550
		 WHERE LB.BatchId = @rBatchId AND LB.EmployeeId=EM.EmployeeId AND LB.LeaveTypeId=LTM.Id
		 GROUP BY LB.BalanceLeave) AS AvailableBalance
	FROM
		sHrm.vEmployeeCommonDetail EM
		LEFT JOIN sHrm.tEmployeeStatutoryAndOther ESO ON ESO.EmployeeId=EM.EmployeeId
		LEFT JOIN sHrm.tLeaveTypeMaster LTM ON LTM.OrgId=EM.OrgId AND LTM.IsObsolete = 0 AND IsLWP=0
	WHERE
		EM.OrgID = @rOrgId
		AND ((EM.EmployeeGradeId=@rEmployeeGradeId) OR (@rEmployeeGradeId=0))
		AND ((EM.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
		AND ((EM.Code like @rEmployeeCode) OR (@rEmployeeCode=''))
		AND ((EM.EmployeeName like @rEmployeeName) OR (@rEmployeeName=''))
		AND ((EM.EmployeeId=@rEmployeeId) OR (@rEmployeeId=0))
		AND ((EM.EmployeeStatusId=@rEmployeeStatusId) OR (@rEmployeeStatusId=0))
		AND ((EM.DepartmentId= @rDepartmentId ) OR (@rDepartmentId= 0 ))
		AND (ISNULL(LTM.Id,0) IN (SELECT cast(item as int) FROM sCommon.fnsplit(@rLeaveTypeIds,',')) OR ISNULL(@rLeaveTypeIds, '')='')
	ORDER BY EM.Code

END
GO
PRINT N'Altering Procedure [sHrm].[pRptEmployeeIcardGet]...';


GO

ALTER PROCEDURE [sHrm].[pRptEmployeeIcardGet]
	@rBuilder1 nvarchar(max)='',
	@rBuilder2 nvarchar(max)='',
	@rReportId smallint,
	@rOrgId smallint,
	@rStrEmployeeId nvarchar(max),
	@rEmployeeTypeId [int],
	@rDepartmentId [int]= 0,
	@rGradeId [int]= 0,
	@rDesignationId [int]= 0,
	@rGenderId [int]= 0,		
	@rEmployeeId [bigint]= 0,
	@rAgeFrom nvarchar(10),
	@rAgeTo nvarchar(10),
	@rEmployeeCode nvarchar(50)='',
	@rEmployeeGroupId smallint,
	@rEmployeeStatusId smallint,
	@rIsShowBarcode bit=0,
	@rStrCode nvarchar(max)='',
	@rBatchName nvarchar(100) = ''
	
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
	SELECT		
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			ECD.EmployeeId,
	        ECD.Code,	      	
			ECD.EmployeeName, 	 								 
			ECD.DepartmentId,  			
			ECD.DepartmentName,
		    ECD.MobileNumber,
		    ECD.EmployeeDesignation,
		    ECD.PhoneNoCompany,
		    ECD.BloodGroup,
		    ECD.DateOfBirth,
			EI.EmployeePhoto,
		    OM.Title AS OrgName,
		    OM.PrincipalSignature,
			ISNULL(ICO.ICardOrgTitle,'') AS ICardOrgTitle,
			ISNULL(ICO.ICardAddress1,'') AS ICardAddress1,
			ISNULL(ICO.ICardAddress2,'') AS ICardAddress2,
			ISNULL(ICO.ICardAddress3,'') AS ICardAddress3,	
		    OM.OrgLogo AS ICardLogo,
			ICO.ICardBackground,	
			ICO.ICardBackBackground,						
			ISNULL(ICO.LabelColor,'Black') AS LabelColor,
			ISNULL(ICO.DetailColor,'Black') AS DetailColor,
			ISNULL(ICO.HeaderColor,'Black') AS HeaderColor,
			ISNULL(EC.PresentStreetOne,'') AS PresentStreetOne,
			ISNULL(EC.PresentStreetTwo,'') AS PresentStreetTwo,
			ISNULL(EC.PresentStreetThree,'') AS PresentStreetThree,
			ISNULL(EC.PresentCity,'') AS PresentCity,
			ISNULL(EC.PresentState,'') AS PresentState,
			ISNULL(EC.PresentCountry,'') AS PresentCountry,
			ISNULL(EC.PresentZipCode,'') AS PresentZipCode,
			ECD.DateofJoining,
			EI.EmployeeSign,
			@rIsShowBarcode As IsShowBarcode,
			ISNULL(EC.EmergencyStreetOne,'') AS EmergencyStreetOne,
			ISNULL(EC.EmergencyStreetTwo,'') AS EmergencyStreetTwo,
			ISNULL(EC.EmergencyStreetThree,'') AS EmergencyStreetThree,
			ISNULL(EC.EmergencyCity,'') AS EmergencyCity,
			ISNULL(EC.EmergencyState,'') AS EmergencyState,
			ISNULL(EC.EmergencyCountry,'') AS EmergencyCountry,
			ISNULL(EC.EmergencyZipCode,'') AS EmergencyZipCode,
			ISNULL(PanNumber,'') AS PanNumber,
			EC.EmergencyContactNo AS EmergencyContactNo,
			EPD.Qualification AS Qualification,
			--ISNULL(EM.MiddleName,'')AS FatherName,
			ISNULL(ECD.MiddleName,'')AS FatherName,
			ECD.GenderTitle,
			ISNULL(ECD.FirstName,'')AS FirstName,
			ISNULL(ECD.LastName,'')AS SurName,
			(CASE WHEN RelationshipId = 2 THEN EFD.MobileNo ELSE '' END )AS FatherContactNo,
			ISNULL(@rBatchName,'') AS BatchName,
			ISNULL(EC.PresentContactNo,'') AS PresentContactNo
		FROM 
			sHrm.vEmployeeCommonDetail ECD
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=ECD.OrgID
			LEFT JOIN sHrm.tEmployeeImages EI ON EI.EmployeeId=ECD.EmployeeId
			LEFT JOIN sHrm.tEmployeeICardOrg ICO ON ECD.OrgId = ICO.OrgId
			LEFT JOIN sHrm.tEmployeeCommunications EC ON ECD.EmployeeId = EC.EmployeeId
			LEFT JOIN sHrm.tEmployeeStatutoryAndOther EO ON EO.EmployeeId = ECD.EmployeeId
			LEFT JOIN sHrm.tEmployeePersonalDetail EPD ON EPD.EmployeeId = EO.EmployeeId
			LEFT JOIN sHrm.tEmployeeFamilyDetails EFD on ECD.EmployeeId=EFD.EmployeeId AND EFD.RelationshipId = 2
			--LEFT JOIN sCommon.tRelationshipMaster RM on EFD.RelationshipId=RM.Id AND RM.Id=2
			--LEFT JOIN sHrm.tEmployeeMaster EM on EM.Id = ECD.EmployeeId
			
		WHERE
		((ECD.Code LIKE @rEmployeeCode)OR @rEmployeeCode = '' )
	   AND (ISNULL(ECD.EmployeeId,0) NOT IN( SELECT cast(item as bigint) FROM  sCommon.fnsplit(@rStrEmployeeId,',')) OR @rStrEmployeeId='') 
	   AND (ISNULL(ECD.Code,'') IN( SELECT cast(item as nvarchar(20)) FROM  sCommon.fnsplit(@rStrCode,',')) OR @rStrCode='')   
	   AND (ECD.EmployeeTypeId = @rEmployeeTypeId OR @rEmployeeTypeId = 0)
	   AND (ECD.OrganizationDepartmentId = @rDepartmentId OR @rDepartmentId = 0)
	   AND (ECD.EmployeeStatusId = @rEmployeeStatusId OR @rEmployeeStatusId = 0)
	   AND (ECD.EmployeeGroupId=@rEmployeeGroupId OR @rEmployeeGroupId=0)
	   AND (ECD.EmployeeGradeId = @rGradeId OR @rGradeId = 0)
	   AND (ECD.EmployeeDesignationId = @rDesignationId OR @rDesignationId = 0)	 	   
	   AND (ECD.GenderId = @rGenderId OR @rGenderId = 0)  	    
	   AND (ECD.EmployeeId = @rEmployeeId OR @rEmployeeId = 0)	   
	   --AND ((DATEDIFF(yy,ECD.DateOfBirth,GETDATE()) <= @rAgeTo) OR (ISNULL(@rAgeTo,0)=0))
	   --AND ((DATEDIFF(yy,ECD.DateOfBirth,GETDATE()) >= @rAgeFrom)OR (ISNULL(@rAgeFrom,0)=0))
	   AND  ECD.OrgId = @rOrgId
	   AND ISNULL(ECD.IsOtherUser,0)=0
	  
END
GO
PRINT N'Altering Procedure [sLibrary].[pReaderBookLogListGet]...';


GO

ALTER PROCEDURE [sLibrary].[pReaderBookLogListGet]
	 @rReaderSourceTypeId smallint=0,
	 @rReaderSourceId bigint,
	 @rOrgId smallint,
	 @rBatchId int,
	 @rLibraryId int
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 	
If(@rReaderSourceTypeId=2003)
BEGIN
	SELECT 
			BL.Id AS BookLogId,
			BM.Code AS ResourceCode,
			BM.Title AS ResourceName,
			BL.LogDate,
			BL.DueDate,
			IS1.NoOfBookIssuable,
			BL.StatusId,
			BM.Id As BookId
	FROM 
			sLibrary.tBookLog BL
			INNER JOIN sLibrary.tBookMaster BM ON BM.Id=BL.ResourceSourceId
			INNER JOIN sStudent.vStudentLastAcademic SA ON SA.StudentId=BL.ReaderSourceId 
			INNER JOIN sLibrary.tIssueSetting IS1 ON IS1.SourceId=SA.ClassId AND IS1.SourceTypeId=2005 AND IS1.LibraryId=@rLibraryId
	WHERE 
			((BL.ReaderSourceTypeId=@rReaderSourceTypeId) OR (@rReaderSourceTypeId=0))
		AND (BL.ReaderSourceId=@rReaderSourceId)
		AND BL.IsCurrentStatus=1
		AND ((BL.StatusId=522) OR (BL.StatusId=523))
		--AND (BL.OrgId=@rOrgId)
		--AND (BL.BatchId=@rBatchId)
		-- because of pAssignBooksBulkReturnGet sp (due date and Book Code not display) - done by sarangi - mantisid - 0026852
		AND (SA.OrgId=@rOrgId)
		AND (SA.BatchId=@rBatchId)
		--AND  SA.IsActiveBatch = 1
		AND (BL.LibraryId=@rLibraryId)
END
ELSE If(@rReaderSourceTypeId=95)
BEGIN
	SELECT 
			BL.Id AS BookLogId,
			BM.Code AS ResourceCode,
			BM.Title AS ResourceName,
			BL.LogDate,
			BL.DueDate,
			IS1.NoOfBookIssuable,
			BL.StatusId,
			BM.Id As BookId   
	FROM 
			sLibrary.tBookLog BL
			INNER JOIN sLibrary.tBookMaster BM ON BM.Id=BL.ResourceSourceId
			INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id=BL.ReaderSourceId	
			INNER JOIN sHrm.tEmployeeJobDetail EJD ON EM.Id = EJD.EmployeeId
			INNER JOIN sSetup.tDepartmentMaster ODM ON ODM.Id = EJD.OrganizationDepartmentId
			INNER JOIN sLibrary.tIssueSetting IS1 ON IS1.SourceId=ODM.Id AND IS1.SourceTypeId=2004 AND IS1.LibraryId=@rLibraryId
	WHERE 
			((BL.ReaderSourceTypeId=@rReaderSourceTypeId) OR (@rReaderSourceTypeId=0))
		AND (BL.ReaderSourceId=@rReaderSourceId)
		AND BL.IsCurrentStatus=1
		AND ((BL.StatusId=522) OR (BL.StatusId=523))
		-- because of pAssignBooksBulkReturnGet sp (due date and Book Code not display) - done by sarangi - mantisid - 0026852
		--AND (BL.OrgId=@rOrgId)
		AND (EM.OrgId=@rOrgId)
		AND (BL.BatchId=@rBatchId)
		AND (BL.LibraryId=@rLibraryId)
		AND ISNULL(EM.IsOtherUser,0) = 0
END
END
GO
PRINT N'Altering Procedure [sProcurement].[pRptStockIssueStudentReceipt]...';


GO

 
ALTER PROCEDURE [sProcurement].[pRptStockIssueStudentReceipt]
 
	@rId int = 0,
	@rStoreLocationId int = 0,
	@rMainGroupId int=0,
	@rSubGroupId int=0,
	@rItemCode nvarchar(50)='',
	@rItemName nvarchar(50)='',
	@rOrgGroupId int=0,
	@rBuilder1 nvarchar(max)='',
	@rBuilder2 nvarchar(max)='',
	@rReportId int=0,
	@rStockItemCategoryId int=0,
	@rFromDate date='',
	@rTodate date='',
	@rToDepartmentId int =0,
	@rNumber nvarchar(10)='',
	@rAcademicId bigint = 0,
	@rOrgId smallint = 0,
	@rBatchId int = 0
	
WITH EXECUTE AS CALLER
AS
BEGIN
	
	SET NOCOUNT ON;
	SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED
	Declare @lIDConfigValue nvarchar(50)=''
	DECLARE @lCurrencyCode nvarchar(20) = ''
	DECLARE @lCurrencyTitle nvarchar(100) = ''
	SELECT @lIDConfigValue =ItemValue From sConfig.tConfigurationSetup
	WHERE ConfigurationId = 236 AND SourceId = @rOrgGroupId
	SELECT  @lCurrencyCode = [sFinanceCommon].[fDefaultCurrencyCodeGet](@rOrgGroupId) 
	SELECT  @lCurrencyTitle = [sFinanceCommon].[fDefaultCurrencyTitleGet](@rOrgGroupId) 
       SELECT  
			@rBuilder1 AS Builder1,
			SIM.Code AS ItemNumber,
			SIM.Title AS ItemName,		
			SI.IssuedByName,	
			SI.Number, 	
			SI.CreatedDateTime AS IssuedDate,
			ID.IssuedQuantity,
			ID.RequestedQuantity,
			SM.FirstName +' '+SM.MiddleName As StudentName,
			Sm.Code AS StudentCode,
			SG.Code AS ItemSubGroup,
			SG.Id AS ItemSubGroupId,
			OM.DisplayTitle,
			BM.Title AS BatchTitle,
			CM.Title +'-'+ DM.TItle As Class,
			(SELECT ISNULL(SUM(AvailableQuantity),0) FROM sProcurement.tStockBatch SB 
		    WHERE SB.StockItemId = SIM.Id 
		    AND ((SB.StorelocationId = @rStoreLocationId) OR (@rStoreLocationId = 0))
			) AS Quantity ,
			A.OrgId,
			A.BatchId,
			ISNULL(CAST(SIP.WeightedAverageCost AS DECIMAL(18, 2)), '0') AS WeightedAverageCost,
			@lIDConfigValue AS IdNoLabel,
			((ISNULL(CAST(SIP.WeightedAverageCost AS DECIMAL(18, 2)), '0')) * (ID.IssuedQuantity)) AS Amount,
			replace(
			(sFinanceCommon.fNumberToWordsWithDecimal(
			((ISNULL(CAST(SIP.WeightedAverageCost AS DECIMAL(18, 2)), '0')) * (ID.IssuedQuantity)),1,2,SI.OrgGroupId)
			),'Rupees Rupees',[sFinanceCommon].[fDefaultCurrencyMinorTitleGet](OM.OrgGroupId)) AS AmountInWords,
			ISNULL(SI.PayTypeId,0) as PayTypeId,
			 ISNULL(PTM.Title,'Not Charged') AS PayType,
			ISNULL(SI.ReceiptNumber,0) as ReceiptNumber,
			ISNULL(SI.BankName,'') as BankName,
			ISNULL(SI.ChequeNo,'') as ChequeNo,
			ISNULL(SI.ChequeDate,'') as ChequeDate,
			@lCurrencyCode AS CurrencyCode,
			@lCurrencyTitle AS CurrencyTitle

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


SET ANSI_NULLS ON
GO
PRINT N'Altering Procedure [sSecurity].[pPendingLoginStudentdGet]...';


GO

ALTER PROCEDURE [sSecurity].[pPendingLoginStudentdGet]
	
	@rOrgId smallint,
	@rBatchId int,
	@rIsPendingLogin bit,
	@rIsCreatedLogin bit,
	@rClassId int = 0,
	@rDivisionId int = 0,
	@rNotRegister bit = 0
	--@rRollNos nvarchar(max) = NULL,
	--@rMultiCode nvarchar(max)=''

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	SELECT 
	-- TOP 100
			ISNULL(U.Id,0) AS Id,
			SC.StudentId,
			SC.Code,
			SC.Name,
			SC.ClassName + '-' + SC.DivisionName AS ClassName,
			SC.RollNo,
			ISNULL(SC.ParentContactNo,'') AS MobileNo,
			ISNULL(SC.ParentEmail,'') AS EmailId,
			U.LoginTitle AS UserName,
			U.LoginPassword,
			SC.SUId,
			SM.Title AS Status,
			(CASE WHEN A.UserId IS NULL THEN 'Not Register' ELSE 'Register' END) AS UserRegisterStatus,
			ISNULL(SC.WhatsAppContactNo,'') AS WhatsAppContactNo
	FROM 
			sStudent.vStudentCommunication SC
			LEFT JOIN sSecurity.tUser U ON U.SourceId = SC.StudentId AND U.SourceTypeId=2003
			INNER JOIN sStudent.tStatusMaster SM ON SM.Id = SC.StatusId 
			LEFT JOIN 
			(
				SELECT DISTINCT UserId FROM sCommunication.tRegisteredUsers
			) AS A ON A.UserId = U.Id
	WHERE 
			((U.LoginPassWord is Null AND @rIsPendingLogin=1) OR (U.LoginPassWord is NOT Null AND @rIsCreatedLogin=1))
			 AND	(SC.OrgId = @rOrgId)
			 AND	(SC.BatchId = @rBatchId) 
			 AND	((SC.ClassId = @rClassId) OR(@rClassId=0))
			 AND	((SC.DivisionId = @rDivisionId) OR(@rDivisionId=0))
			 AND SC.StatusId = 1
			 AND ((A.UserId IS NULL AND @rNotRegister = 1) OR (@rNotRegister = 0))
			 --AND (ISNULL(SC.RollNo,0) IN( SELECT cast(item as Int) FROM  sCommon.fnsplit(@rRollNos,',')) OR @rRollNos IS NULL)
			 --AND (ISNULL(SC.Code,0) IN( SELECT cast(item as nvarchar(20)) FROM  sCommon.fnsplit(@rMultiCode,',')) OR @rMultiCode='')
	Order By SC.DivisionOrderIndex,SC.RollNo
	
END
GO
PRINT N'Altering Procedure [sStudent].[pChangeClassGet]...';


GO
ALTER PROCEDURE [sStudent].[pChangeClassGet]
	 
	 @rClassID int,
	 @rDivisionId int,
	 @rStrIDNo nvarchar(500),
	 @rOrgId int,
	 @rBatchId int
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 

		DECLARE @ListofIDs TABLE(IDs nvarchar(20), ID INT IDENTITY(1,1));
		INSERT INTO @ListofIDs

		select q2.value from
		(SELECT cast('<x>'+replace(@rStrIDNo,',','</x><x>')+'</x>' as xml) as thexml)q1 CROSS APPLY
		(SELECT x.value('.','nvarchar(20)') as value FROM thexml.nodes('x') as f(x))q2
		
		
	 --IF(@rIsSearch=1)
		--BEGIN
			--SET @rGRNo = sCommon.fSearchStringGet(@rGRNo)
			--SET @rLastName = sCommon.fSearchStringGet(@rLastName)
			--SET @rFirstName = sCommon.fSearchStringGet(@rFirstName)
		--END
	
	SELECT 
			SN.AcademicId,
			--A.StudentId,
			--SO.GenderId,
			SN.ClassId,
			SN.DivisionId,
			SN.RollNo AS RollNo,
			SN.FirstName,
			SN.MiddleName,
			SN.LastName,
			SN.FirstName + ' ' + SN.MiddleName + ' ' + SN.LastName AS Name,
			SN.Number,
			SN.Code
      
  FROM 
			[sStudent].[vStudentName] SN
           --sStudent.tAcademic A
           --INNER JOIN sStudent.tStudentMaster SM ON SM.Id=A.StudentId 
           ----INNER JOIN sStudent.tStudentOther SO ON SO.StudentId=A.StudentId  
  WHERE 
				(SN.ClassId=@rClassId OR @rClassId=0)
			AND (SN.DivisionId=@rDivisionId OR @rDivisionId=0)
			AND ((SN.Code IN(SELECT IDs FROM @ListofIDs)) OR (ISNULL(@rStrIDNo,'') = ''))
			AND SN.OrgID=@rOrgId 
			AND SN.BatchID=@rBatchId

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


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

BEGIN 

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


GO
ALTER PROCEDURE [sStudent].[pStudentDetailUpdateGet]
	 
	 @rCategoryId int,
	 @rSubCategory nvarchar(100),
	 @rOrgId int,
	 @rClassId int,
	 @rDivisionId int,
	 @rBatchId int,
	 --@rIsBlank bit,
	 @rStatusId int,
	 @rOrderBy int,
	 @rFromCode nvarchar(20)='',
	 @rToCode nvarchar(20)='',
	  @rMultiCode nvarchar(max)=''
	 
AS
SET NOCOUNT ON

BEGIN
	 	DECLARE @lDataTypeId nvarchar(1)
		SELECT @lDataTypeId=DataTypeId FROM sCommon.tUpdateFieldMaster WHERE Field=@rSubCategory
		 
		 
		 IF @rCategoryId=1 
		 BEGIN-- Communication
			IF @rSubCategory ='Present Address'
			BEGIN
				if @rOrderBY=1
				BEGIN
				Select  SA.StudentId,SA.AcademicId,SA.Name,SA.ClassName+' - '+SA.DivisionName AS ClassDivision,SA.RollNo,SA.Code,SA.Number,
						PresentStreetOne,
						PresentStreetTwo,
						PresentStreetThree,
						PresentCountry,
						PresentState,
						PresentCity,
						PresentZipCode,
						PresentContactNo
				FROM 
				sStudent.vStudentAcademic SA
				LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId=SA.StudentId
				Where SA.OrgId=@rOrgId
				AND ((SA.ClassId=@rClassId) OR (@rClassId =0))
				AND ((SA.DivisionId=@rDivisionId) OR  (@rDivisionId=0))
				AND ((SA.StatusId= @rStatusId ) OR  (@rStatusId  =0))
				AND ((SA.BatchId= @rBatchId )) 
				AND((SA.Code >= @rFromCode) OR (ISNULL(@rFromCode,'') = ''))  
			    AND((SA.Code <= @rToCode) OR (ISNULL(@rToCode,'') = '')) 
			    AND (ISNULL(SA.Code,0) IN( SELECT cast(item as nvarchar(20)) FROM  sCommon.fnsplit(@rMultiCode,',')) OR @rMultiCode='')
				
				ORder BY SA.RollNo
				END
				Else
				BEGIN
					Select  SA.StudentId,SA.AcademicId,SA.Name,SA.ClassName+' - '+SA.DivisionName AS ClassDivision,SA.RollNo,SA.Code,SA.Number,
						PresentStreetOne,
						PresentStreetTwo,
						PresentStreetThree,
						PresentCountry,
						PresentState,
						PresentCity,
						PresentZipCode,
						PresentContactNo
				FROM 
				sStudent.vStudentAcademic SA
				LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId=SA.StudentId
				Where SA.OrgId=@rOrgId
				AND ((SA.ClassId=@rClassId) OR (@rClassId =0))
				AND ((SA.DivisionId=@rDivisionId) OR  (@rDivisionId=0))
				AND ((SA.StatusId= @rStatusId ) OR  (@rStatusId  =0))
				AND ((SA.BatchId= @rBatchId )) 
				AND((SA.Code >= @rFromCode) OR (ISNULL(@rFromCode,'') = ''))  
			    AND((SA.Code <= @rToCode) OR (ISNULL(@rToCode,'') = '')) 
			    AND (ISNULL(SA.Code,0) IN( SELECT cast(item as nvarchar(20)) FROM  sCommon.fnsplit(@rMultiCode,',')) OR @rMultiCode='')
				
				ORder BY SA.Number		--add
				END	
			END
			IF @rSubCategory ='Permanent Address'
			BEGIN
				if @rOrderBY=1
				BEGIN
				Select  SA.StudentId,SA.AcademicId,SA.Name,SA.ClassName+' - '+SA.DivisionName AS ClassDivision,SA.RollNo,SA.Code,SA.Number,
						PermanentStreetOne As PresentStreetOne,
						PermanentStreetTwo AS PresentStreetTwo,
						PermanentStreetThree AS PresentStreetThree,
						PermanentCountry AS PresentCountry,
						PermanentState AS PresentState,
						PermanentCity As PresentCity,
						PermanentZipCode As PresentZipCode,
						PermanentContactNo AS PresentContactNo
				FROM 
				sStudent.vStudentAcademic SA
				LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId=SA.StudentId
				Where SA.OrgId=@rOrgId
				AND ((SA.ClassId=@rClassId) OR (@rClassId =0))
				AND ((SA.DivisionId=@rDivisionId) OR  (@rDivisionId=0))
				AND ((SA.StatusId= @rStatusId ) OR  (@rStatusId  =0))
				AND ((SA.BatchId= @rBatchId )) 
				AND((SA.Code >= @rFromCode) OR (ISNULL(@rFromCode,'') = ''))  
			    AND((SA.Code <= @rToCode) OR (ISNULL(@rToCode,'') = '')) 
				AND (ISNULL(SA.Code,0) IN( SELECT cast(item as nvarchar(20)) FROM  sCommon.fnsplit(@rMultiCode,',')) OR @rMultiCode='')
				
				Order by Sa.RollNo
				END
				ELSE
				BEGIN
					Select  SA.StudentId,SA.AcademicId,SA.Name,SA.ClassName+' - '+SA.DivisionName AS ClassDivision,SA.RollNo,SA.Code,SA.Number,
						PermanentStreetOne As PresentStreetOne,
						PermanentStreetTwo AS PresentStreetTwo,
						PermanentStreetThree AS PresentStreetThree,
						PermanentCountry AS PresentCountry,
						PermanentState AS PresentState,
						PermanentCity As PresentCity,
						PermanentZipCode As PresentZipCode,
						PermanentContactNo AS PresentContactNo
				FROM 
				sStudent.vStudentAcademic SA
				LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId=SA.StudentId
				Where SA.OrgId=@rOrgId
				AND ((SA.ClassId=@rClassId) OR (@rClassId =0))
				AND ((SA.DivisionId=@rDivisionId) OR  (@rDivisionId=0))
				AND ((SA.StatusId= @rStatusId ) OR  (@rStatusId  =0))
				AND ((SA.BatchId= @rBatchId ))
				AND((SA.Code >= @rFromCode) OR (ISNULL(@rFromCode,'') = ''))  
			    AND((SA.Code <= @rToCode) OR (ISNULL(@rToCode,'') = '')) 
				 AND (ISNULL(SA.Code,0) IN( SELECT cast(item as nvarchar(20)) FROM  sCommon.fnsplit(@rMultiCode,',')) OR @rMultiCode='')
				 
				Order By SA.Number		--add
				END
			END
			IF @rSubCategory ='Emergency Address'
			BEGIN
				if @rOrderBY=1
				BEGIN
				Select  SA.StudentId,SA.AcademicId,SA.Name,SA.ClassName+' - '+SA.DivisionName AS ClassDivision,SA.RollNo,SA.Code,SA.Number,
						EmergencyStreetOne AS PresentStreetOne,
						EmergencyStreetTwo As PresentStreetTwo, 
						EmergencyStreetThree As PresentStreetThree,
						EmergencyCountry As PresentCountry,
						EmergencyState As PresentState,
						EmergencyCity AS PresentCity,
						EmergencyZipCode As PresentZipCode,
						EmergencyContactNo  AS PresentContactNo
				FROM 
				sStudent.vStudentAcademic SA
				LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId=SA.StudentId
				Where SA.OrgId=@rOrgId
				AND ((SA.ClassId=@rClassId) OR (@rClassId =0))
				AND ((SA.DivisionId=@rDivisionId) OR  (@rDivisionId=0))
				AND ((SA.StatusId= @rStatusId ) OR  (@rStatusId  =0))
				AND ((SA.BatchId= @rBatchId )) 
				AND((SA.Code >= @rFromCode) OR (ISNULL(@rFromCode,'') = ''))  
			    AND((SA.Code <= @rToCode) OR (ISNULL(@rToCode,'') = '')) 
				AND (ISNULL(SA.Code,0) IN( SELECT cast(item as nvarchar(20)) FROM  sCommon.fnsplit(@rMultiCode,',')) OR @rMultiCode='')
				
				Order BY SA.RollNo
				END
				Else
				BEGIN
					Select  SA.StudentId,SA.AcademicId,SA.Name,SA.ClassName+' - '+SA.DivisionName AS ClassDivision,SA.RollNo,SA.Code,SA.Number,
						EmergencyStreetOne AS PresentStreetOne,
						EmergencyStreetTwo As PresentStreetTwo, 
						EmergencyStreetThree As PresentStreetThree,
						EmergencyCountry As PresentCountry,
						EmergencyState As PresentState,
						EmergencyCity AS PresentCity,
						EmergencyZipCode As PresentZipCode,
						EmergencyContactNo  AS PresentContactNo
				FROM 
				sStudent.vStudentAcademic SA
				LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId=SA.StudentId
				Where SA.OrgId=@rOrgId
				AND ((SA.ClassId=@rClassId) OR (@rClassId =0))
				AND ((SA.DivisionId=@rDivisionId) OR  (@rDivisionId=0))
				AND ((SA.StatusId= @rStatusId ) OR  (@rStatusId  =0))
				AND ((SA.BatchId= @rBatchId )) 
				AND((SA.Code >= @rFromCode) OR (ISNULL(@rFromCode,'') = ''))  
			    AND((SA.Code <= @rToCode) OR (ISNULL(@rToCode,'') = '')) 
				AND (ISNULL(SA.Code,0) IN( SELECT cast(item as nvarchar(20)) FROM  sCommon.fnsplit(@rMultiCode,',')) OR @rMultiCode='')
				
				Order By SA.Number		--add
				END
			END
		END
		IF @rCategoryId= 4 
		BEGIN --Family
			IF @rSubCategory ='Father'
				BEGIN
				if @rOrderBY=1
				BEGIN
					Select  SA.StudentId,SA.AcademicId,SA.Name,SA.ClassName+' - '+SA.DivisionName AS ClassDivision,SA.RollNo,SA.Code,SA.Number,
							FatherName,FatherDateOfBirth,FatherOccupation,FatherQualification,FatherContactNo,FatherMail,
							FatherOfficeAddress,FatherIncome,FatherOfficeContactNo
					FROM 
					sStudent.vStudentAcademic SA
					LEFT JOIN sStudent.tStudentFamily SC ON SC.StudentId=SA.StudentId
					Where SA.OrgId=@rOrgId
				AND ((SA.ClassId=@rClassId) OR (@rClassId =0))
				AND ((SA.DivisionId=@rDivisionId) OR  (@rDivisionId=0))
				AND ((SA.StatusId= @rStatusId ) OR  (@rStatusId  =0))
				AND ((SA.BatchId= @rBatchId )) 
				AND((SA.Code >= @rFromCode) OR (ISNULL(@rFromCode,'') = ''))  
			    AND((SA.Code <= @rToCode) OR (ISNULL(@rToCode,'') = '')) 
				
				ORder BY SA.RollNo
				END
				Else
				BEGIN
					Select  SA.StudentId,SA.AcademicId,SA.Name,SA.ClassName+' - '+SA.DivisionName AS ClassDivision,SA.RollNo,SA.Code,SA.Number,
							FatherName,FatherDateOfBirth,FatherOccupation,FatherQualification,FatherContactNo,FatherMail,
							FatherOfficeAddress,FatherIncome,FatherOfficeContactNo
					FROM 
					sStudent.vStudentAcademic SA
					LEFT JOIN sStudent.tStudentFamily SC ON SC.StudentId=SA.StudentId
					Where SA.OrgId=@rOrgId
				AND ((SA.ClassId=@rClassId) OR (@rClassId =0))
				AND ((SA.DivisionId=@rDivisionId) OR  (@rDivisionId=0))
				AND ((SA.StatusId= @rStatusId ) OR  (@rStatusId  =0))
				AND ((SA.BatchId= @rBatchId )) 
				AND((SA.Code >= @rFromCode) OR (ISNULL(@rFromCode,'') = ''))  
			    AND((SA.Code <= @rToCode) OR (ISNULL(@rToCode,'') = '')) 
				
				Order By SA.Number	--add
				END
			END
			IF @rSubCategory ='Mother'
				BEGIN
				if @rOrderBY=1
				BEGIN
					Select  SA.StudentId,SA.AcademicId,SA.Name,SA.ClassName+' - '+SA.DivisionName AS ClassDivision,SA.RollNo,SA.Code,SA.Number,
							MotherName,MotherDateOfBirth,MotherOccupation,MotherQualification,MotherContactNo,MotherMail,
							MotherOfficeAddress,MotherIncome,MotherOfficeContactNo
					FROM 
					sStudent.vStudentAcademic SA
					LEFT JOIN sStudent.tStudentFamily SC ON SC.StudentId=SA.StudentId
					Where SA.OrgId=@rOrgId
					AND ((SA.ClassId=@rClassId) OR (@rClassId =0))
				AND ((SA.DivisionId=@rDivisionId) OR  (@rDivisionId=0))
				AND ((SA.StatusId= @rStatusId ) OR  (@rStatusId  =0))
				AND ((SA.BatchId= @rBatchId )) 
				AND((SA.Code >= @rFromCode) OR (ISNULL(@rFromCode,'') = ''))  
			    AND((SA.Code <= @rToCode) OR (ISNULL(@rToCode,'') = '')) 
				
				Order By SA.ROllNO
				END
				Else
				BEGIN
					Select  SA.StudentId,SA.AcademicId,SA.Name,SA.ClassName+' - '+SA.DivisionName AS ClassDivision,SA.RollNo,SA.Code,SA.Number,
							MotherName,MotherDateOfBirth,MotherOccupation,MotherQualification,MotherContactNo,MotherMail,
							MotherOfficeAddress,MotherIncome,MotherOfficeContactNo
					FROM 
					sStudent.vStudentAcademic SA
					LEFT JOIN sStudent.tStudentFamily SC ON SC.StudentId=SA.StudentId
					Where SA.OrgId=@rOrgId
					AND ((SA.ClassId=@rClassId) OR (@rClassId =0))
				AND ((SA.DivisionId=@rDivisionId) OR  (@rDivisionId=0))
				AND ((SA.StatusId= @rStatusId ) OR  (@rStatusId  =0))
				AND ((SA.BatchId= @rBatchId )) 
				AND((SA.Code >= @rFromCode) OR (ISNULL(@rFromCode,'') = ''))  
			    AND((SA.Code <= @rToCode) OR (ISNULL(@rToCode,'') = '')) 
				
				Order By SA.Number	--add
				END
			END
			IF @rSubCategory ='Relative'
				BEGIN
				if @rOrderBY=1
				BEGIN
					Select  SA.StudentId,SA.AcademicId,SA.Name,SA.ClassName+' - '+SA.DivisionName AS ClassDivision,SA.RollNo,SA.Code,SA.Number,
							RelativeName,RelativeDateOfBirth,RelativeOccupation,RelativeQualification,RelativeContactNo,RelativeMail,
							RelativeOfficeAddress,RelativeIncome,RelationshipName
					FROM 
					sStudent.vStudentAcademic SA
					LEFT JOIN sStudent.tStudentFamily SC ON SC.StudentId=SA.StudentId
					Where SA.OrgId=@rOrgId
					AND ((SA.ClassId=@rClassId) OR (@rClassId =0))
				AND ((SA.DivisionId=@rDivisionId) OR  (@rDivisionId=0))
				AND ((SA.StatusId= @rStatusId ) OR  (@rStatusId  =0))
				AND ((SA.BatchId= @rBatchId )) 
				AND((SA.Code >= @rFromCode) OR (ISNULL(@rFromCode,'') = ''))  
			    AND((SA.Code <= @rToCode) OR (ISNULL(@rToCode,'') = '')) 
				
				Order By SA.ROllNo
				END
				Else
				BEGIN
					Select  SA.StudentId,SA.AcademicId,SA.Name,SA.ClassName+' - '+SA.DivisionName AS ClassDivision,SA.RollNo,SA.Code,SA.Number,
							RelativeName,RelativeDateOfBirth,RelativeOccupation,RelativeQualification,RelativeContactNo,RelativeMail,
							RelativeOfficeAddress,RelativeIncome,RelationshipName
					FROM 
					sStudent.vStudentAcademic SA
					LEFT JOIN sStudent.tStudentFamily SC ON SC.StudentId=SA.StudentId
					Where SA.OrgId=@rOrgId
					AND ((SA.ClassId=@rClassId) OR (@rClassId =0))
				AND ((SA.DivisionId=@rDivisionId) OR  (@rDivisionId=0))
				AND ((SA.StatusId= @rStatusId ) OR  (@rStatusId  =0))
				AND ((SA.BatchId= @rBatchId )) 
				AND((SA.Code >= @rFromCode) OR (ISNULL(@rFromCode,'') = ''))  
			    AND((SA.Code <= @rToCode) OR (ISNULL(@rToCode,'') = '')) 
			    
				Order By SA.Number		--add
				END
			END
			
		END			
		IF @rCategoryId= 10 
		BEGIN
			IF @rSubCategory ='Academic'
			BEGIN
			
				if @rOrderBY=1
				 BEGIN
					 Select 
						SA.StudentId,SA.Code,SA.FirstName,SA.MiddleName,SA.LastName,SA.ClassName,SA.ClassId,SA.DivisionID,SA.Number,
						SA.DivisionName,convert(date,SO.DateOfBirth) As DateOfBirth,AD.AdmissionDate,AD.AdmissionStandardId,SA.Name,Sa.RollNo,SO.GenderId
					From  
						 sStudent.vStudentAcademic SA
						INNER JOIN sStudent.tStudentOther SO 
									ON SO.StudentId=SA.StudentId
						LEFT JOIN sStudent.tStudentAdmission AD
									ON AD.StudentID = SA.StudentId  
					Where SA.OrgId=@rOrgId
						AND ((SA.ClassId=@rClassId) OR (@rClassId =0))
					AND ((SA.DivisionId=@rDivisionId) OR  (@rDivisionId=0))
					AND ((SA.StatusId= @rStatusId ) OR  (@rStatusId  =0))
					AND ((SA.BatchId= @rBatchId )) 
					AND((SA.Code >= @rFromCode) OR (ISNULL(@rFromCode,'') = ''))  
			        AND((SA.Code <= @rToCode) OR (ISNULL(@rToCode,'') = '')) 
			        
					Order by RollNo
				END
				else
				BEGIN
				Select 
						SA.StudentId,SA.Code,SA.FirstName,SA.MiddleName,SA.LastName,SA.ClassName,SA.ClassId,SA.DivisionID,SA.Number,
						SA.DivisionName,convert(date,SO.DateOfBirth) DateOfBirth,AD.AdmissionDate,AD.AdmissionStandardId,SA.Name,Sa.RollNo,SO.GenderId
					From  
						 sStudent.vStudentAcademic SA
						INNER JOIN sStudent.tStudentOther SO 
									ON SO.StudentId=SA.StudentId
						LEFT JOIN sStudent.tStudentAdmission AD
									ON AD.StudentID = SA.StudentId  
					Where SA.OrgId=@rOrgId
						AND ((SA.ClassId=@rClassId) OR (@rClassId =0))
					AND ((SA.DivisionId=@rDivisionId) OR  (@rDivisionId=0))
					AND ((SA.StatusId= @rStatusId ) OR  (@rStatusId  =0))
					AND ((SA.BatchId= @rBatchId ))
					AND((SA.Code >= @rFromCode) OR (ISNULL(@rFromCode,'') = ''))  
			        AND((SA.Code <= @rToCode) OR (ISNULL(@rToCode,'') = '')) 
					 
					Order by SA.Number--add
				END
			END
			
			IF @rSubCategory ='Main Group'
			BEGIN
				if @rOrderBY=1
				 BEGIN
					 Select 
						SA.StudentId,SA.Code,SA.FirstName,SA.MiddleName,SA.LastName,SA.ClassName,SA.ClassId,SA.DivisionID,SA.Number,
						SA.DivisionName,AD.Id,ISNULl(AD.Code,'') AS groupCode,ISNULl(AD.Title,'') AS Title,SA.Name,Sa.RollNo 
					From  
						 sStudent.vStudentAcademic SA
						
						LEFT JOIN sStudent.tStudentGroupMaster AD
									ON AD.Id = SA.StudentGroupId  
					Where SA.OrgId=@rOrgId
						AND ((SA.ClassId=@rClassId) OR (@rClassId =0))
					AND ((SA.DivisionId=@rDivisionId) OR  (@rDivisionId=0))
					AND ((SA.StatusId= @rStatusId ) OR  (@rStatusId  =0))
					AND ((SA.BatchId= @rBatchId )) 
					AND((SA.Code >= @rFromCode) OR (ISNULL(@rFromCode,'') = ''))  
			        AND((SA.Code <= @rToCode) OR (ISNULL(@rToCode,'') = '')) 
					
					Order by RollNo
				END
				else
				BEGIN
				Select 
						SA.StudentId,SA.Code,SA.FirstName,SA.MiddleName,SA.LastName,SA.ClassName,SA.ClassId,SA.DivisionID,SA.Number,
						SA.DivisionName,AD.Id,ISNULl(AD.Code,'') AS groupCode,ISNULl(AD.Title,'') As Title,SA.Name,Sa.RollNo 
					From  
						 sStudent.vStudentAcademic SA
						
						LEFT JOIN sStudent.tStudentGroupMaster AD
									ON AD.Id = SA.StudentGroupId  
					Where SA.OrgId=@rOrgId
						AND ((SA.ClassId=@rClassId) OR (@rClassId =0))
					AND ((SA.DivisionId=@rDivisionId) OR  (@rDivisionId=0))
					AND ((SA.StatusId= @rStatusId ) OR  (@rStatusId  =0))
					AND ((SA.BatchId= @rBatchId )) 
					AND((SA.Code >= @rFromCode) OR (ISNULL(@rFromCode,'') = ''))  
			        AND((SA.Code <= @rToCode) OR (ISNULL(@rToCode,'') = '')) 
					
					Order by SA.Number		--add
				END
			END
			
			IF @rSubCategory ='Other Group'
			BEGIN
				if @rOrderBY=1
				 BEGIN
					 Select 
						SA.StudentId,SA.Code,SA.FirstName,SA.MiddleName,SA.LastName,SA.ClassName,SA.ClassId,SA.DivisionID,SA.Number,
						SA.DivisionName,AD.Id,ISNULl(AD.Code,'') As groupCode,ISNULl(AD.Title,'') AS Title,SA.Name,Sa.RollNo 
					From  
						 sStudent.vStudentAcademic SA
						
						LEFT JOIN sStudent.tStudentOtherGroupMaster AD
									ON AD.Id = SA.StudentOtherGroupId  
					Where SA.OrgId=@rOrgId
						AND ((SA.ClassId=@rClassId) OR (@rClassId =0))
					AND ((SA.DivisionId=@rDivisionId) OR  (@rDivisionId=0))
					AND ((SA.StatusId= @rStatusId ) OR  (@rStatusId  =0))
					AND ((SA.BatchId= @rBatchId )) 
					AND((SA.Code >= @rFromCode) OR (ISNULL(@rFromCode,'') = ''))  
			        AND((SA.Code <= @rToCode) OR (ISNULL(@rToCode,'') = '')) 
					
					Order by RollNo
				END
				else
				BEGIN
				Select 
						SA.StudentId,SA.Code,SA.FirstName,SA.MiddleName,SA.LastName,SA.ClassName,SA.ClassId,SA.DivisionID,SA.Number,
						SA.DivisionName,Ad.Id,ISNULl(AD.Code,'') As groupCode,ISNULl(AD.Title,'') As Title,SA.Name,Sa.RollNo 
					From  
						 sStudent.vStudentAcademic SA
						
						LEFT JOIN sStudent.tStudentOtherGroupMaster AD
									ON AD.Id = SA.StudentOtherGroupId  
					Where SA.OrgId=@rOrgId
						AND ((SA.ClassId=@rClassId) OR (@rClassId =0))
					AND ((SA.DivisionId=@rDivisionId) OR  (@rDivisionId=0))
					AND ((SA.StatusId= @rStatusId ) OR  (@rStatusId  =0))
					AND ((SA.BatchId= @rBatchId )) 
					AND((SA.Code >= @rFromCode) OR (ISNULL(@rFromCode,'') = ''))  
			        AND((SA.Code <= @rToCode) OR (ISNULL(@rToCode,'') = '')) 
					
					Order by SA.Number	--add
				END
			END
			
			IF @rSubCategory ='Demographic'
			BEGIN
				if @rOrderBY=1
				 BEGIN
					 Select 
						SA.StudentId,SA.Code,SA.Name,Sa.RollNo,SO.ReligionId,SO.FamilyCast,SO.FamilySubCast,SO.CastCategoryId,SO.NationalityId,SA.Number
					From  
						 sStudent.vStudentAcademic SA
						LEFT JOIN sStudent.tStudentOther SO 
									ON SO.StudentId=SA.StudentId
					Where SA.OrgId=@rOrgId
						AND ((SA.ClassId=@rClassId) OR (@rClassId =0))
					AND ((SA.DivisionId=@rDivisionId) OR  (@rDivisionId=0))
					AND ((SA.StatusId= @rStatusId ) OR  (@rStatusId  =0))
					AND ((SA.BatchId= @rBatchId )) 
					AND((SA.Code >= @rFromCode) OR (ISNULL(@rFromCode,'') = ''))  
			        AND((SA.Code <= @rToCode) OR (ISNULL(@rToCode,'') = '')) 
					
					Order by RollNo
				END
				else
				BEGIN
				Select 
						SA.StudentId,SA.Code,SA.Name,Sa.RollNo,SO.ReligionId,SO.FamilyCast,SO.FamilySubCast,SO.CastCategoryId,SO.NationalityId,SA.Number
					From  
						 sStudent.vStudentAcademic SA
						LEFT JOIN sStudent.tStudentOther SO 
									ON SO.StudentId=SA.StudentId
					Where SA.OrgId=@rOrgId
						AND ((SA.ClassId=@rClassId) OR (@rClassId =0))
					AND ((SA.DivisionId=@rDivisionId) OR  (@rDivisionId=0))
					AND ((SA.StatusId= @rStatusId ) OR  (@rStatusId  =0))
					AND ((SA.BatchId= @rBatchId )) 
					AND((SA.Code >= @rFromCode) OR (ISNULL(@rFromCode,'') = ''))  
			        AND((SA.Code <= @rToCode) OR (ISNULL(@rToCode,'') = '')) 
					
					
					Order by SA.Number		--add
				END
			END
			
		END
	 
		   
END
GO
PRINT N'Altering Procedure [sStudent].[pStudentDocumentClassWiseGet]...';


GO
ALTER PROCEDURE [sStudent].[pStudentDocumentClassWiseGet]
	@rClassId int=0,
	@rDivisionId int=0,
	@rRollNo int=NULL,
	@rOrgId int,
	@rCode nvarchar(20),
	@rStatusId smallint=0,
	@rFirstName nvarchar(100)='',
	@rLastName nvarchar(100)='',
	@rBatchId int,
    @rSUId nvarchar(50)='',
    @rUserId bigint=0,
    @rMultiCode nvarchar(max)='',
	@rDocumentId int=0
	
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	 
		BEGIN
			SET @rCode= sCommon.fSearchStringGet(@rCode)
			SET @rFirstName = sCommon.fSearchStringGet(@rFirstName)
			SET @rLastName = sCommon.fSearchStringGet(@rLastName)
		END
	IF(@rRollNo IS NULL)
	BEGIN
	SELECT 
			SA.AcademicId,
			SA.StudentId,
			SA.FirstName,
			SA.LastName,
			SA.Name,
			SA.Code,
			SA.ClassId,
			SA.ClassName,
			SA.DivisionId,
			SA.DivisionName,
			ISNULL(SA.Number,0) AS Number,
			SA.RollNo,
			SA.StatusId,
			SA.StatusName,
			SA.OrgId,
			SA.SUId,
			--SD.DocumentName
			--ISNULL(STUFF(
			-- (SELECT DISTINCT ',' + SDM.DocumentName
			--  FROM sCommon.tSubmitDocumentMaster SDM
			--  INNER JOIN  sStudent.tStudentDocument SD ON SDM.Id=SD.SubmitDocumentMasterId
			--  INNER JOIN sCommon.tSubmitDocumentScope DS ON DS.SubmitDocumentId=SDM.Id AND DS.SourceId = @rClassId
			--  where SD.StudentId=SA.StudentId AND SDM.SubmitDocumentFunctionalityId = 1 AND ((SDM.Id=@rDocumentId)OR(@rDocumentId=0))
			--  FOR XML PATH (''))
			--  , 1, 1, ''),'')  AS DocumentName,
			  ISNULL(sStudent.fStudentDocumentClasswiseget(@rDocumentId,SA.AcademicId),'') AS DocumentName
			
  FROM 
          sStudent.vStudentAcademic SA
		  --LEFT JOIN sStudent.tStudentDocument SD ON SD.StudentId=SA.StudentId
		  INNER JOIN sSecurity.tUserAccess U ON U.SourceId = SA.DivisionId AND U.SourceTypeId=2005
             
  WHERE 
 
		((SA.ClassId=@rClassId)OR(@rClassId=0))
		AND((SA.DivisionId=@rDivisionId)OR(@rDivisionId=0))
		AND((SA.Code like @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)
		AND(SA.BatchId=@rBatchId)
		AND((SA.SUID = @rSUId) OR (ISNULL(@rSUId,'') = '')) 
		--AND((SA.Number=@rNumber)OR(@rNumber=0))	
		AND U.UserId = @rUserId
		AND (ISNULL(SA.Code,0) IN( SELECT cast(item as nvarchar(20)) FROM  sCommon.fnsplit(@rMultiCode,',')) OR @rMultiCode='')
--ORDER BY CASE WHEN @rOrderByTypeId = 1 then SA.RollNo END,
--		 CASE WHEN @rOrderByTypeId = 2 then (CASE ISNUMERIC(SA.Code) WHEN 1 THEN REPLICATE(0 , 100 - LEN(SA.Code)) + SA.Code ELSE SA.Code  END) END,
			ORDER BY SA.ClassId,SA.DivisionId,SA.RollNo
END
ELSE
BEGIN
	SELECT 
			SA.AcademicId,
			SA.StudentId,
			SA.FirstName,
			SA.LastName,
			SA.Name,
			SA.Code,
			SA.ClassId,
			SA.ClassName,
			SA.DivisionId,
			SA.DivisionName,
			SA.Number,
			SA.RollNo,
			SA.StatusId,
			SA.StatusName,
			SA.OrgId,
			SA.SUId,
			--SD.DocumentName
			ISNULL(sStudent.fStudentDocumentClasswiseget(@rDocumentId,SA.AcademicId),'') AS DocumentName
			
			
  FROM 
          sStudent.vStudentAcademic SA
		  --LEFT JOIN sStudent.tStudentDocument SD ON SD.StudentId=SA.StudentId
          INNER JOIN sSecurity.tUserAccess U ON U.SourceId = SA.DivisionId AND U.SourceTypeId=2005
  WHERE 
 
		((SA.ClassId=@rClassId)OR(@rClassId=0))
		AND((SA.DivisionId=@rDivisionId)OR(@rDivisionId=0))
		AND((SA.Code like @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)
		AND(SA.BatchId=@rBatchId)
		AND((SA.SUID = @rSUId) OR (ISNULL(@rSUId,'') = '')) 
		AND U.UserId = @rUserId
		AND (ISNULL(SA.Code,0) IN( SELECT cast(item as nvarchar(20)) FROM  sCommon.fnsplit(@rMultiCode,',')) OR @rMultiCode='')
		--AND((SA.Number=@rNumber)OR(@rNumber=0))	

--ORDER BY CASE WHEN @rOrderByTypeId = 1 then SA.RollNo END,
--		 CASE WHEN @rOrderByTypeId = 2 then (CASE ISNUMERIC(SA.Code) WHEN 1 THEN REPLICATE(0 , 100 - LEN(SA.Code)) + SA.Code ELSE SA.Code  END) END,
		 ORDER BY SA.ClassId,SA.DivisionId,SA.RollNo
END
  
	
END
GO
PRINT N'Altering Procedure [sStudent].[pStudentVerificationGet]...';


GO
ALTER PROCEDURE [sStudent].[pStudentVerificationGet]
	 
	@rClassId int=0,
	@rDivisionId int=0,
	@rRollNo int=0,
	@rOrgId int,
	--@rNumber bigint,
	@rCode nvarchar(20) = '',
	@rStatusId smallint=0,
	@rFirstName nvarchar(100)='',
	@rLastName nvarchar(100)='',
	@rBatchId int = 0,
	@rOrgGroupBatchId int = 0,
	@rDepartmentId int,
	@rOrgGroupId smallint,
	@rToRollNo int=0,
	@rFromCode nvarchar(20)='',
	@rToCode nvarchar(20)='',
	@rSpecificCode nvarchar(max)=''
	
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON			 

BEGIN 	 

	BEGIN
		SET @rCode= sCommon.fSearchStringGet(@rCode)
		SET @rFirstName = sCommon.fSearchStringGet(@rFirstName)
		SET @rLastName = sCommon.fSearchStringGet(@rLastName)
	END
 
	SELECT 
			SA.AcademicId,
			SA.StudentId,
			SA.ClassId,
			Sa.MiddleName,
			ISNULL(SA.AdmissionDate,'')As AdmissionDate,
			SA.PreviousSchool,
			ISNULL(SA.DateOfBirth,'') As DateOfBirth,
			SA.BirthPlace,
			SA.Gender,
			SA.FamilyCast,
			SA.CastCatagory AS CasteCategory,
			SA.MotherTongue,
			SA.Nationality,
			Sa.FatherName,
			SA.FatherContactNo,
			SA.Mothername,
			SA.MotherContactNo,
			SA.PresentStreetOne,
			SA.PresentStreetTwo,
			SA.PresentStreetThree,
			ISNULL(SA.StudentContactNo,'')As StudentContactNo,
			SA.UIDNumber,
			SA.AdhaarNumber,
			SA.BankBranch,
			SA.BankAccountNumber,
			SA.BankName,
			SA.BankIFSCCode,
			SA.DepartmentId,
			SA.FirstName,
			SA.LastName,
			SA.Name,
			SA.Code,
			SA.ADMISSIONStandardId, 
			SA.DivisionId,
			SA.DivisionName,
			ISNULL(SA.Number,0) AS Number,
			SA.RollNo,
			SA.StatusId,
			--SA.StatusName,
			SA.OrgId,
			--SA.Age,
			ISNULL(SA.AdmissionCategoryId,0) AS AdmissionCategoryId,
			SA.Religion,
			SA.StudentEmail,
			SA.Name,
			(select  Title  from sSetup.tClassMaster where OrgId=@rOrgId AND id=SA.ADMISSIONStandardId  ) As AdmissionStandard,
			SA.ClassName,
			SA.BirthState,
			SA.BirthCountry,
			SA.BirthTaluka,
			SA.BirthDistrict,
			SA.BankAccountHolderName
  FROM 
            sStudent.vStudentVerification SA  
  WHERE 
			((SA.ClassId=@rClassId)OR(@rClassId=0))
			AND((SA.DivisionId=@rDivisionId)OR(@rDivisionId=0))
			AND((SA.Code like @rCode) OR (ISNULL(@rCode,'') = '')) 
			AND((SA.Code >= @rFromCode) AND (SA.Code <= @rToCode) OR (ISNULL(@rFromCode,'') = '' OR ISNULL(@rToCode,'') = '')) 
			AND(SA.Code IN (SELECT CONVERT(nvarchar,item) from sCommon.fnSplit(@rSpecificCode,',')) OR ISNULL(@rSpecificCode,'') = '') 
			AND((SA.FirstName like @rFirstName) OR (ISNULL(@rFirstName,'') = '')) 
			AND((SA.LastName like @rLastName) OR (ISNULL(@rLastName,'') = '')) 
			AND((SA.StatusId=@rStatusId)OR(@rStatusId=0))	
			AND(SA.OrgId=@rOrgId OR @rOrgId = 0)
			AND (OrgGroupBatchId = @rOrgGroupBatchId	or @rOrgGroupBatchId = 0)	
			AND(SA.BatchId=@rBatchId or @rBatchId = 0)
			AND(SA.DepartmentId=@rDepartmentId or @rDepartmentId = 0)
			and ((sa.RollNO>=@rRollNO)OR(@rRollNo=0))
			and ((sa.RollNO<=@rToRollNo)OR(@rToRollNo=0))
			--AND((SA.Number=@rNumber)OR(@rNumber=0))	

			ORDER BY SA.ClassId,SA.DivisionId,SA.RollNo

--ORDER by CASE WHEN @rOrderByTypeId = 1 then SA.FirstName 
--			  WHEN @rOrderByTypeId = 2 then SA.LastName
--			  WHEN @rOrderByTypeId = 4 then (CASE IsNumeric (SA.Code) WHEN 1 THEN Replicate (0, 100 - Len (SA.Code)) + SA.Code  ELSE SA.Code  END) END,		--add
--		CASE WHEN @rOrderByTypeId = 3 then SA.RollNo END,
--		CASE WHEN @rOrderByTypeId = 5 then SA.AdmissionDate END  
--			  ,SA.ClassId, SA.DivisionId,SA.RollNo
 
END
GO
PRINT N'Altering Procedure [sStudent].[pSUIDGenerationGet]...';


GO
ALTER PROCEDURE [sStudent].[pSUIDGenerationGet]
	 
	 @rOrgGroupId smallint,
	 @rOrgId smallint,
	 @rDepartmentId int,
	 @rClassID int,
	 @rDivisionId int,
	 @rRecordStatusId smallint,
	 @rBatchId int=0,
	 @rOrderByTypeId smallint = 0	 

	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
	SELECT 
		vSA.StudentId,
		vSA.OrgId,
		vSA.OrganizationName,
		VSA.DepartmentName,
		vSA.ClassName+' - '+vSA.DivisionName AS ClassDivisionName,
		vSA.RollNo,
		vSA.Code,
		ISNULL(vSA.SUId,'') AS SUID,
		vSA.Name,
		SA.AdmissionDate,
		GM.Title As Gender,
		(Select CM.Title from sSetup.tClassMaster CM WHere CM.Id=SA.AdmissionStandardId) AS AdmissionStandard,
		vSA.FirstName,
		vSA.LastName,
		SA.AdmissionDate,
		vSA.ClassID,
		vSA.AcademicId,
		vSA.DivisionId,
		vSA.Number
			
	FROM 
		sStudent.vStudentAcademic vSA
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = vSA.OrgId
		INNER JOIN sStudent.tStudentAdmission SA ON SA.StudentId=vSA.StudentId
		INNER JOIN sStudent.tStudentOther SO ON So.StudentId=vSa.StudentId
		INNER JOIN sCommon.tGenderMaster GM ON Gm.Id=SO.GenderID
	WHERE 
		(OM.OrgGroupId = @rOrgGroupId)
		AND (vSA.OrgId=@rOrgId)
		AND (vSA.BatchId=@rBatchId)
		AND ((vSA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
		AND ((vSA.ClassId=@rClassId) OR (@rClassId=0))
		AND ((vSA.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		AND ((vSA.RecordStatusId=@rRecordStatusId) OR (@rRecordStatusId=0))
	ORDER BY OM.OrderIndex,vSA.DivisionOrder,vSA.RollNo
	--ORDER by CASE WHEN @rOrderByTypeId = 1 then vSA.FirstName
	--			  WHEN @rOrderByTypeId = 2 then vSA.LastName
	--			  WHEN @rOrderByTypeId = 4 then (CASE ISNUMERIC(vSA.Code) WHEN 1 THEN REPLICATE(0 , 100 - LEN(vSA.Code)) + vSA.Code ELSE vSA.Code  END) END,	--add inner case
	--	CASE WHEN @rOrderByTypeId = 3 then vSA.RollNo END,
	--	CASE WHEN @rOrderByTypeId = 5 then SA.AdmissionDate END
	--		  ,OM.OrderIndex,vSA.DivisionOrder,vSA.RollNo
END
GO
PRINT N'Altering Procedure [sTool].[pDeleteStaticData]...';


GO
 
ALTER PROCEDURE [sTool].[pDeleteStaticData]
 
	 
AS
SET NOCOUNT ON
BEGIN 
 

DELETE FROM sAlert.tEventMaster
DELETE FROM sCommon.tAutoCompleteMaster
DELETE FROM sCommon.tCommonMaster
DELETE FROM sCommon.tDepends
DELETE FROM sCommon.tModuleMaster
DELETE FROM sCommon.tPrefixFunctionality
DELETE FROM sCommon.tRefferedTableForObsoleteCheck
DELETE FROM sCommon.tRefferedTableWithoutForeignKey
DELETE FROM sCommon.tReport
DELETE FROM sCommon.tReportFormatGroupMaster
DELETE FROM sCommon.tReportGroupMaster
DELETE FROM sCommon.tSourceScreenMaster
DELETE FROM sCommon.tSourceTypeMaster
DELETE FROM sCommon.tStatusMaster
DELETE FROM sCommon.tStatusTypeMaster
DELETE FROM sCommon.tTableRowIdMaster
DELETE FROM sCommon.tUpdateFieldMaster
DELETE FROM sCommon.tValidationType
DELETE FROM sConfig.tColorLegendMaster
DELETE FROM sConfig.tConfigurationMaster
DELETE FROM sConfig.tConfigurationValue
DELETE FROM sSecurity.tMenu
DELETE FROM sSecurity.tResourceTypeMaster
DELETE FROM sSecurity.tScreen
DELETE FROM sSecurity.tScreenGroupMaster
DELETE FROM sSecurity.tScreenTypeMaster
DELETE FROM sSecurity.tTask
DELETE FROM sSystem.tTable
DELETE FROM sTool.tObjects
DELETE FROM sCommon.tReportTypeMaster


DELETE FROM sSetup.tAffiliationClassGroup
DELETE FROM sSetup.tAffiliationTypeMaster
DELETE FROM sSetup.tAffiliationMaster	
DELETE FROM sSetup.tStreamMaster

-- temp insert
DELETE FROM sAttendance.tAttendanceForMaster
DELETE FROM sEExam.tEntryModeMaster
DELETE FROM sSetup.tTermScopeMaster	 
 
DELETE FROM sConfig.tConfigurationLevelMaster

DELETE FROM sAdmission.tInquiryModeMaster

DELETE FROM sFee.tFeeMainGroupMaster

DELETE FROM sPayroll.tPayElementDefault

DELETE FROM sSecurity.tScreenGroupMapping
DELETE FROM sAssessment.tCCEExamMaster
DELETE FROM sSetup.tTermPatternMaster


DELETE FROM sAdmission.tAdmissionStatusMaster
DELETE FROM sAssessment.tCCERptGroup
DELETE FROM sHrm.tEmployeeICardTemplate
DELETE FROM sSecurity.tDashletMaster
DELETE FROM sStudent.tICardTemplate
DELETE FROM sSystem.tCustomQuery

DELETE FROM sCommon.tRangeGroupMaster

DELETE FROM sHostel.tLogStatusMaster

DELETE FROM sSetup.tStudentNameFormatMaster

DELETE FROM sCommon.tMainCastCategoryMaster

DELETE FROM sOp.tFunctionalityMaster
DELETE FROM sOp.tPaymentGatewayMaster

DELETE FROM sOp.tPayTypeMaster
DELETE FROM sOp.tTransactionStatusMaster
--DELETE FROM sPayroll.tForm16B
DELETE FROM sStudent.tBatchStatusMaster
DELETE FROM [sFinanceCommon].[tPayTypeMaster]

DELETE FROM sAttendance.tAttendanceTagMaster
DELETE FROM sCommon.tLiveWithMaster
DELETE FROM sConfig.tDisplayFieldMaster

DELETE FROM sActivity.tEventMainTypeMaster
DELETE FROM sAlert.tOSType

DELETE FROM sCommon.tCalculationTypeMaster
DELETE FROM sFee.tApplayAsMaster
DELETE FROM sSecurity.tScreenDependency
DELETE FROM sStudent.tSUIdFieldMaster

DELETE FROM [sAlert].[tAlertModeMaster]
DELETE FROM sCommon.tReportRemarkGroupMaster
DELETE FROM sStudent.tEnrollmentStatusMaster
DELETE FROM [sSetup].[tClassGroupMaster]

DELETE FROM sCommon.tTemplateSourceMaster
DELETE FROM sErp.tCustomerStatusMaster
DELETE FROM sErp.tInstallationTypeMaster
DELETE FROM sRecruitment.tRecruitmentStatusMaster

DELETE FROM sAssessment.tStaticCCECSMaster
DELETE FROM sAssessment.tStaticCCECSGroupMaster

DELETE FROM siTax.tStaticIncomeTaxGroup
DELETE FROM siTax.tStaticIncomeTaxSubGroup

DELETE FROM sCommon.tImportFieldMaster
DELETE FROM sCRM.tHostingTypeMaster
DELETE FROM sHrm.tMainLeaveTypeMaster

DELETE FROM sAppraisal.tConductIndicatorMaster
DELETE FROM sHrm.tTravelPeriodMaster
DELETE FROM sLoan.tInsterestTypeMaster

DELETE FROM sAppraisal.tBHRatingStatus
DELETE FROM sAppraisal.tConductIndicatorMaster
DELETE FROM sAppraisal.tKPAMeasureMaster
DELETE FROM sAppraisal.tKPATypeMaster
DELETE FROM sAppraisal.tRatingStatus
DELETE FROM sCommon.tHeaderDisplayMaster
DELETE FROM sCommon.tModuleGroupMaster
DELETE FROM sHrm.tLeaveTransactionMaster
DELETE FROM sCommon.tCheckFrequencyMaster

DELETE FROM sErp.tLeadAffiliationMaster
DELETE FROM sErp.tLeadSourceMaster
DELETE FROM sErp.tLeadStatusMaster

DELETE FROM sSystem.tStaticVersion

DELETE FROM sCommunication.tFeedBackAnswerGroupMaster

DELETE FROM sCommon.tSubmitDocumentFunctionalityMaster
DELETE FROM sSetup.tMandatoryFeild
DELETE FROM sSetup.tMandatoryFeildFunctionalityMaster

DELETE FROM sSystem.tTimeZone
DELETE FROM sTool.tTestCaseTypeMaster

DELETE FROM sAlumni.tEmployeementType

DELETE FROM sErp.tCampusTypeMaster

DELETE FROM sAlert.tMailTypeMaster
DELETE FROM sAlert.tSMSVendorMaster
DELETE FROM sCommon.tWeekOffRules

DELETE FROM sSecurity.tScreenHelp
DELETE FROM sSystem.tSettingInfo

DELETE FROM sProcurement.tOtherLocationSourceTypeMaster

DELETE FROM sCommon.tFieldTypeMaster
DELETE FROM sErp.tLeadInfrastructureMaster

DELETE FROM sHostel.tHostelEventMainTypeMaster

DELETE FROM sCertificate.tCertificateTypeMaster	
DELETE FROM sWorkflow.tActionStatusMaster
DELETE FROM sWorkflow.tApprovingDepartmentMaster
DELETE FROM sWorkflow.tWorkflowFunctionalityMaster

DELETE FROM sAcademic.tHomeworkCheckStatusMaster
DELETE FROM sAssessment.tExamTypeMaster

DELETE FROM sErp.tMarketingActivityMaster
DELETE FROM sErp.tMarketingSubActivityMaster
DELETE FROM sSetup.tCommonOrgGroupBatchMaster
DELETE FROM sWorkflow.tWorkflowFunctionalityMaster

DELETE FROM sAudit.tOperationMaster

DELETE FROM sAdmission.tInquiryMainStatusMaster
DELETE FROM sCertificate.tPrintTemplateFunctionalityMaster
DELETE FROM sErp.tTripLogStatusMaster

DELETE FROM sErp.tFollowupTypeMaster
DELETE FROM sErp.tSupportCategoryMaster
DELETE FROM sErp.tSupportPriorityMaster
DELETE FROM sErp.tSupportTicketStatusMaster


DELETE FROM sErp.tPlugInMaster
DELETE FROM sErp.tTagMaster

DELETE FROM sErp.tIssueTypeMaster

DELETE FROM sErp.tScreenFunctionalityMaster

DELETE FROM sHrm.tChangeTypeMaster


DELETE FROM sCommon.tDataMaster
DELETE FROM sCommon.tDataTypeMaster

DELETE FROM siTax.tStaticIncomeTaxSubSubGroup

DELETE FROM sCommunication.tStudentDocumentTypeMaster

DELETE FROM sCommon.tUploadFunctionalityMaster
DELETE FROM sCommunication.tEmployeeDocumentTypeMaster

DELETE FROM sErp.tCustomerMessageTypeMaster

DELETE FROM sActivity.tActivityMainTypeMaster
DELETE FROM sSecurity.tTraceabilityMaster
DELETE FROM sSecurity.tTraceabilityTrack

DELETE FROM sSecurity.tScreenScopeDetails
DELETE FROM sBiometric.tEmployeeConfigurationMaster
DELETE FROM sSetup.tEmployeeNameFormatMaster
DELETE FROM sStudent.tOnlineRegistrationDisplayFieldMaster

DELETE FROM sSetup.tFormTypeMaster
DELETE FROM sSetup.tFormButtonMaster

DELETE FROM sSecurity.tSysSuperScreen
DELETE FROM sAppraisal.tKPAStatus

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


GO
CREATE PROCEDURE sAlert.pAlertStatusUpdate
	 
	@rOrgId int
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN	
BEGIN TRY
BEGIN TRANSACTION	
 
    BEGIN 
		IF OBJECT_ID('tempdb..#TempAlertLog') IS NOT NULL DROP TABLE #TempAlertLog
		IF OBJECT_ID('tempdb..#TempNotificationLog') IS NOT NULL DROP TABLE #TempNotificationLog

		IF EXISTS(SELECT name FROM master.dbo.sysdatabases WHERE name = 'NVQueue')
		BEGIN

			CREATE TABLE #TempAlertLog
			(
				Id bigint IDENTITY,
				AlertLogId bigint,
				AlertModeId tinyint
			)
		
			INSERT INTO #TempAlertLog SELECT Id, AlertModeId FROM [sAlert].[tAlertLog] WHERE StatusId = 0
		
			DECLARE @lCount int = (SELECT COUNT(Id) FROM #TempAlertLog)

			IF (@lCount > 0)
			BEGIN
				WHILE(@lCount > 0)
				BEGIN
					DECLARE @lId bigint = (SELECT AlertLogId FROM #TempAlertLog WHERE Id = @lCount)
					DECLARE @lAlertModeId int = (SELECT AlertModeId FROM #TempAlertLog WHERE Id = @lCount)

					IF EXISTS(SELECT 1 FROM [NVqueue].[dbo].[QueueDetailLog] WHERE AlertLogId = @lId) 
					BEGIN 
						DECLARE @lResponse int=0,@lResponseText nvarchar(100)=0
						
						SELECT @lResponse = CASE WHEN ISNULL(IsError, 0) = 1 THEN -1 ELSE ISNULL(IsSuccess, 0) END 
						FROM [NVqueue].[dbo].[QueueDetailLog] WHERE AlertLogId = @lId AND @lAlertModeId IN (1, 4)
						
						UPDATE [sAlert].[tAlertLog] SET StatusId = @lResponse WHERE Id = @lId AND AlertModeId IN (1, 4)


						SELECT 
							@lResponse = CASE WHEN ISNULL(IsError, 0) = 1 THEN -1 ELSE ISNULL(IsSuccess, 0) END,
							@lResponseText = ISNULL(Response, '')
						FROM [NVqueue].[dbo].[QueueDetailLog] 
						WHERE AlertLogId = @lId AND @lAlertModeId = 2
						
						UPDATE [sAlert].[tAlertLog] 
						SET StatusId = CASE WHEN @lResponse = -1 THEN -1 ELSE (SELECT Id FROM sAlert.tSMSStatusMaster WHERE Code = @lResponseText) END
						WHERE Id = @lId AND AlertModeId = 2
					END

					SET @lCount = @lCount - 1
				END
			END

			CREATE TABLE #TempNotificationLog
			(
				Id bigint IDENTITY,
				AlertLogId bigint
			)
		
			INSERT INTO #TempNotificationLog SELECT Id FROM [sAlert].[tNotificationLog] WHERE ISNULL(APIResponse, '') = ''
		
			DECLARE @lCount1 int = (SELECT COUNT(Id) FROM #TempNotificationLog)

			IF (@lCount1 > 0)
			BEGIN
				WHILE(@lCount1 > 0)
				BEGIN
					DECLARE @lId1 bigint = (SELECT AlertLogId FROM #TempNotificationLog WHERE Id = @lCount1)
					IF EXISTS(SELECT 1 FROM [NVqueue].[dbo].[QueueDetailLog] WHERE AlertLogId = @lId1) 
					BEGIN 
						DECLARE @lAPIResponse nvarchar(500) = ''
						SELECT @lAPIResponse = ISNULL(Response, '') 
						FROM [NVqueue].[dbo].[QueueDetailLog] WHERE AlertLogId = @lId1 AND IsSuccess = 1

						UPDATE [sAlert].[tNotificationLog] SET APIResponse = @lAPIResponse WHERE Id = @lId1 
					END
					SET @lCount1 = @lCount1 - 1
				END
			END
		END

		DROP TABLE #TempAlertLog
		DROP TABLE #TempNotificationLog		 
		SELECT 1 As Result
	END  
	
	COMMIT TRANSACTION
	
END TRY
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
END
GO
PRINT N'Creating Procedure [sAssessment].[pRptResultListConsolidatedMarkRangeWiseGet]...';


GO
CREATE PROCEDURE [sAssessment].[pRptResultListConsolidatedMarkRangeWiseGet]
	 
	 @rBuilder1 nvarchar(max)='', 
	 @rBuilder2 nvarchar(max)='', 
	 @rBatchId int = 0,
	 @rClassId int=0,
	 @rDivisionId int=0,
	 @rExamId int,
	 @rCode nvarchar(20)='',
	 @rFromRollNo int,
	 @rToRollNo int,
	 --@rFromRank int=0,
	 --@rToRank int=0,
	 --@rGrade nvarchar(20)='',
	 --@rResultId bigint=0,
	 @rStatusId int=0,
	 @rAcademicId bigint=0,
	 @rFilterId int=0,
	 @rOrgGroupBatchId int=0,
	 @rClassStatusId int=0
	 		 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN

SELECT 
	@rBuilder1 AS Builder1,
	@rBuilder2 AS Builder2,
	ESGM.Title AS ExamName,
	TSD.EmployeeId,
	EmpM.FirstName,
	EmpM.MiddleName,
	EmpM.LastName,
	EmpM.FirstName + ' ' + EmpM.MiddleName + ' ' + EmpM.LastName AS EmployeeName,
	EmpM.Code AS EmployeeCode,
	SM.Id AS SubjectId,
	SM.Code AS SubjectCode,
	SM.Title AS SubjectName,
	DM.Id AS DivisionId,
	DM.DisplayTitle AS DivisionName,
	DM.OrderIndex AS DivisionOrder,
	CM.Id AS ClassId,
	CM.DisplayTitle AS ClassName,
	CM.OrderIndex AS ClassOrder,
	(CM.DisplayTitle + ' - ' + DM.DisplayTitle) AS ClassDivision,
	A.Id As AcademicId,
	EM.Id AS ExamId,
	RD.Obtain AS SubjectObtain,
	ED.Maximum AS SubjectMaximum,
	CONVERT(Int,ROUND((ISNULL(RD.Obtain, 0) * 100) / ED.Maximum, 0)) AS SubjectPercentage,
	RD.SubjectGrade,
	BM.Title AS BatchName

	FROM 
		sAssessment.tResultDetail RD
		INNER JOIN sAssessment.tResult R ON R.Id = RD.ResultId
		INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId
		INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId		
		INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id = EM.EXAMSUBGROUPID
		INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
		INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=CS.SubjectId					 
		INNER JOIN sStudent.tAcademic A ON A.Id=R.AcademicId	
		INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId		
		INNER JOIN sStudent.tStudentMaster StuM ON StuM.Id=A.StudentId			
		INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId
		INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId			
		--INNER JOIN sSetup.tOrganizationMaster OM ON StuM.OrgId = OM.Id			
		INNER JOIN sAcademic.tTeacherSubjectDivision TSD ON SM.Id = TSD.SubjectId AND DM.Id = TSD.DivisionId
		INNER JOIN sHrm.tEmployeeMaster EmpM ON TSD.EmployeeId = EmpM.Id 			
		LEFT JOIN sHostel.tAssignRoom ARO ON  ARO.SourceId=StuM.Id AND ARO.SourceTypeId=2003 AND ((BM.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  AND ((ARO.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0) AND (BM.OrgGroupBatchId = ARO.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 
			
	WHERE EM.Id = @rExamId
		AND ((EM.BatchId = @rBatchId) OR  (@rBatchId = 0))
		AND ((A.ClassId=@rClassId) OR (@rClassId=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 ((StuM.Code=@rCode) OR (@rCode=''))
		--AND ((R.Id = @rResultId) OR (@rResultId = 0))
		AND ((StuM.StatusId=@rStatusId)OR(@rStatusId=0))
		
		 AND (
	 (@rFilterId = 0) -- All
     OR (@rFilterId = 2 AND isnull(ARO.SourceId,0)!=0) -- Hostel
     OR (@rFilterId = 3 AND isnull(RT.SourceId,0)!=0) -- Transport
     OR ((@rFilterId =1) AND ((isnull(ARO.SourceId,0)=0) AND (isnull(RT.SourceId,0)=0)))
    ) 
	AND ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0))
END
GO
PRINT N'Creating Procedure [sAssessment].[pRptResultListConsolidatedWithMarks2Get]...';


GO

CREATE PROCEDURE [sAssessment].[pRptResultListConsolidatedWithMarks2Get]
	 
	 @rBuilder1 nvarchar(max)='', 
	 @rBuilder2 nvarchar(max)='', 
	 @rBatchId int = 0,
	 @rClassId int=0,
	 @rDivisionId int=0,
	 @rExamId int,
	 @rCode nvarchar(20)='',
	 @rFromRollNo int,
	 @rToRollNo int,
	 @rFromRank int=0,
	 @rToRank int=0,
	 @rGrade nvarchar(20)='',
	 @rResultId bigint=0,
	 @rStatusId int=0,
	 @rAcademicId bigint=0,
	 @rFilterId int=0,
	 @rOrgGroupBatchId int=0,
	 @rClassStatusId int=0
	 
	
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	--Select
	--	'' AS AcademicIdText,
	--	'' AS ExamIdText,
	--	'' AS IsDisplayMonthlyAttendanceText,
	--	'' AS AnnualExam,
	--	'' AS Builder1,
	--	'' Code,
	--	'' AS Name,
	--	0 AS RollNo,
	--	Convert(BigInt,0) AcademicId,			
	--	'' ResultStatus,
	--	'' AS Class,
	--	'' AS Division,
	--	Convert(Decimal,0) TermTotalMark,
	--	Convert(Decimal,0) TermTotalObtain,
	--	0 AS TermRankNumber,
	--	Convert(Decimal,0) TermPercentage,
	--	'' AS TermGrade,
	--	Convert(Decimal,0) TermPercentile,			
	--	Convert(BigInt,0) ResultDetailId,		
	--	Convert(Bit,0) IsDisplayInMarksheet,
	--	Convert(Bit,0) IsShowSubjectGrade,
	--	Convert(Bit,0) IsIncludeInTotal,
	--	Convert(Decimal,0) AS SubjectObtain,
	--	Convert(Decimal,0) AS SubjectMinimum,
	--	Convert(Decimal,0) AS SubjectMaximum,			
	--	'' AS SubjectCode,
	--	'' AS SubjectName,
	--	0 AS SubjectOrderIndex,
	--	Convert(BigInt,0) AS ResultId,
	--	0 AS SubjectId,			 	
	--	Convert(Bit,0) IsMarksInDecimal,
			
	--	'' AS Remark1,
	--	'' AS Remark2,
	--	'' AS Remark3,
	--	'' AS DisplayTitle,
	--	Convert(Bit,0) IsRankNo, 
	--	Convert(Bit,0) IsGrade,
	--	Convert(Bit,0) IsPercentile,
	--	Convert(Bit,0) IsPercentage,
	--	Convert(Bit,0) IsSubjectPercentile,
	--	Convert(Bit,0) IsProcessResult,			 
	--	Convert(Bit,0) IsNegativeMarks,
	--	Convert(Bit,0) IsIncludeCoScholastic,
	--	Convert(Bit,0) IsOnPrePrinted,
	--	Convert(Bit,0) IsDisplayPhoto,
	--	Convert(Bit,0) IsDisplayBirthDate,
	--	Convert(Bit,0) IsLockForEdit,
	--	Convert(Bit,0) IsDisplaySchoolName,			
	--	Convert(Bit,0) IsDisplayAttendance,
	--	Convert(Bit,0) IsDisplayHeightWeight,
	--	Convert(Bit,0) IsResultStatus,
	--	'' AS FooterAdjustmentText,
	--	'' AS DetailAdjustmentText,
	--	0 AS FooterAdjustment,
	--	0 AS DetailAdjustment,		 		 
	--	0 AS TermScopeId,		 
	--	Convert(Bit,0) IsPresent,
	--	'' AS GradeString,
	--	Convert(Bit,0) IsDisplayGradeString,
	--	convert(Decimal,0) HighestDivisionMark,
	--	''  AS HighestDivisionGrade,			
	--	'' SmallAddress1,
	--	Convert(Bit,0) IsDisplayParentName,			 
	--	Convert(Bit,0) AS IsShowSubjectMark,			
	--	Convert(Bit,0) IsDisplayTeacherSign,
	--	Convert(Bit,0) IsDisplayPrincipalSign,		 
	--	Convert(Bit,0) AS IsDisplayMonthlyAttendance,			 
	--	Convert(Bit,0) AS IsImageHeader,			 
	--	0 AS ExamOrderIndex,
	--	0 AS AnnualExamId,
	--	'' AS DecimalFormat,
	--	0 TermExamId,
	--	'' AS ExamName, 			 
	--	'' AS FatherName,
	--	'' AS MotherName,
	--	CONVERT(bit,0) AS IsAbsentRemark,
	--	'' AS AbsentRemark
	

 
DECLARE @GradeString nvarchar(1000),
@GradeSetId int 
 
SELECT @GradeSetId = GradesetId FROM sAssessment.tExamMaster WHERE Id = @rExamId
SELECT @GradeString = [sAssessment].[fGradeStringGet](@GradeSetId)  

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

CREATE TABLE #TempExam
( 
	ExamOrderIndex int,
	TermExamId int,
	AnnualExamId int, 
	Exam nvarchar(50) 
)


INSERT INTO #TempExam
(
	 ExamOrderIndex,
	 TermExamId,
	 AnnualExamId,
	 Exam 	
)
 
SELECT EC.ExamOrder,
EM.Id AS TermExamId,
@rExamId AS AnnualExamId,
ESGM.Code AS Exam
  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 =@rExamId  AND (EM.ClassId=@rClassId) AND EM.BatchId =@rBatchId
	
	SELECT 
			Convert(nvarchar(20),A.Id) AS AcademicIdText,
			Convert(nvarchar(20),@rExamId) AS AnnualExamIdText,
			Convert(nvarchar(20),ISNULL(EM.IsDisplayMonthlyAttendance,0)) AS IsDisplayMonthlyAttendanceText,
			ESGM.Title AS AnnualExam,
			 @rBuilder1 AS Builder1,
			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 AS TermTotalMark,
			R.TotalObtain AS TermTotalObtain,
			R.RankNumber AS TermRankNumber,
			R.Percentage AS TermPercentage,
			R.ResultGrade AS TermGrade,
			R.Percentile AS TermPercentile,			
			RD.Id AS ResultDetailId,		
			ED.IsDisplayInMarksheet,
			ED.IsShowSubjectGrade,
			ED.IsIncludeInTotal,
			RD.Obtain AS SubjectObtain,
			ED.Minimum AS SubjectMinimum,
			ED.Maximum AS SubjectMaximum,			
			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.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,		 		 
			EM.TermScopeId,		 
			RD.IsPresent,
			@GradeString 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,			 
			ISNULL(ED.IsShowSubjectMark,1) AS IsShowSubjectMark,			
			EM.IsDisplayTeacherSign,
			Em.IsDisplayPrincipalSign,		 
			ISNULL(EM.IsDisplayMonthlyAttendance,0) AS IsDisplayMonthlyAttendance,			 
			ISNULL(EM.IsDisplayImageHeader,0) AS IsImageHeader,			 
			EC.ExamOrderIndex,
			EC.AnnualExamId ,
			EM.DecimalFormat,
			EC.TermExamId,
			EC.Exam AS ExamName, 						 
			SF.FatherName,
			SF.MotherName,
			CONVERT(bit,@lAbsentRemarkConfig) AS IsAbsentRemark,
			RD.AbsentRemark
						
	FROM 
			sAssessment.tResultDetail RD
			INNER JOIN sAssessment.tResult R ON R.Id = RD.ResultId
			INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId
			INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId		
			INNER JOIN #TempExam EC ON EC.TermExamId = EM.Id 	
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=CS.SubjectId					 
			INNER JOIN sStudent.tAcademic A ON A.Id=R.AcademicId	
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId		
			INNER JOIN sStudent.tStudentMaster StuM ON StuM.Id=A.StudentId			
			INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId
			INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId			
			INNER JOIN sSetup.tOrganizationMaster OM ON StuM.OrgId = OM.Id			
						
			LEFT JOIN sHostel.tAssignRoom ARO ON  ARO.SourceId=StuM.Id AND ARO.SourceTypeId=2003 AND ((BM.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  AND ((ARO.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0) AND (BM.OrgGroupBatchId = ARO.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 sAssessment.tStudentRemark SR ON R.AcademicId = SR.AcademicId AND  SR.ExamId=EC.AnnualExamId
			LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId = StuM.Id
			
	WHERE 
			
		((EM.BatchId = @rBatchId) OR  (@rBatchId = 0))
		AND ((A.ClassId=@rClassId) OR (@rClassId=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 ((StuM.Code=@rCode) OR (@rCode=''))
		AND ((R.Id = @rResultId) OR (@rResultId = 0))
		AND ((StuM.StatusId=@rStatusId)OR(@rStatusId=0))
		
		 AND (
	 (@rFilterId = 0) -- All
     OR (@rFilterId = 2 AND isnull(ARO.SourceId,0)!=0) -- Hostel
     OR (@rFilterId = 3 AND isnull(RT.SourceId,0)!=0) -- Transport
     OR ((@rFilterId =1) AND ((isnull(ARO.SourceId,0)=0) AND (isnull(RT.SourceId,0)=0)))
    ) 
	AND ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0))
		
	 drop table #TempExam
	 
END
GO
PRINT N'Creating Procedure [sAttendance].[pRptStudentwiseAbsentDaysDetailsGet]...';


GO

Create PROCEDURE [sAttendance].[pRptStudentwiseAbsentDaysDetailsGet]
	 
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 @rOrgId smallint,
	 @rBatchId int,
	 @rClassId int,
	 @rDivisionId int,
	 @rAttendanceTypeId tinyint,
	 @rSubjectId int,
	 @rFromDate date,
	 @rToDate date,
	 @rStudentCode nvarchar(20),
	 @rDepartmentId int
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
 
	SELECT 
			DISTINCT(SA.AcademicId),
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			SA.ClassId,
			SA.DivisionId,
			SA.ClassName,
			SA.DivisionName,
			SA.ClassName+' - '+SA.DivisionName AS ClassDivision,
			SA.Code,
			SA.RollNo,			
			SA.Name,			
			sAttendance.fAttendanceGet(SA.AcademicId,@rAttendanceTypeId,@rSubjectId,@rFromDate,@rToDate) AS AttendanceDate,
			AbsentCount=(SELECT COUNT(1) FROM sAttendance.tStudentRegister SR1 
				WHERE SR1.AcademicId=SA.AcademicId 
				AND ((SR1.AttendanceTypeId=@rAttendanceTypeId) OR (@rAttendanceTypeId=0))
				AND ((SR1.SubjectId=@rSubjectId) OR (@rSubjectId=0))
				AND ((SR1.AttendanceDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
				AND ((SR1.AttendanceDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
				AND SR1.IsPresent=0),
		   SA.DivisionOrder,
		   SC.ParentContactNo
	FROM 
			sStudent.vStudentAcademic SA
		INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=SA.AcademicId
		INNER JOIN sStudent.tStudentCommunication SC ON SC.StudentId=SA.StudentId
	WHERE 
			(SA.OrgId=@rOrgId)
		AND	(SA.BatchId = @rBatchId) 
		AND ((SA.ClassId=@rClassId) OR (@rClassId=0))
		AND ((SA.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		AND ((SR.AttendanceTypeId=@rAttendanceTypeId) OR (@rAttendanceTypeId=0))
		AND ((SR.SubjectId=@rSubjectId) OR (@rSubjectId=0))
		AND ((SR.AttendanceDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
		AND ((SR.AttendanceDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
		AND (SR.IsPresent = 0)
		AND (SA.StatusId != 3)
		AND ((SA.Code=@rStudentCode) OR (@rStudentCode=''))
		AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
		GROUP BY SA.AcademicId,SA.ClassId,SA.DivisionId,SA.ClassName,SA.DivisionName,SA.Code,SA.RollNo,SA.Name,SA.DivisionOrder,SC.ParentContactNo
END
GO
PRINT N'Creating Procedure [sAudit].[pStockOperationLogAdd]...';


GO
CREATE PROCEDURE [sAudit].[pStockOperationLogAdd]
	
	@rScreenId int,
	@rSourceId int,
	@rSourceTypeId smallint,
	@rOperationId tinyint,
	@rOperationRemark nvarchar(max),
	@rCreatedUserId bigint,
	@rCreatedDateTime datetime
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	
	INSERT INTO sAudit.tStockOperationLog
		(
			ScreenId,
			OperationId,
			SourceTypeId,			
			SourceId,
			OperationRemark,
			CreatedUserId,
			CreatedDateTime
		)
	VALUES
		(
			@rScreenId,
			@rOperationId,
			@rSourceTypeId,
			@rSourceId,
			@rOperationRemark,
			@rCreatedUserId,
			@rCreatedDateTime
		)
		
END
GO
PRINT N'Creating Procedure [sAudit].[pStockOperationLogGet]...';


GO
CREATE PROCEDURE [sAudit].[pStockOperationLogGet]
	
	@rScreenId int,
	@rItemCode nvarchar(max),
	@rFromDate date,
	@rToDate date
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	SET @rItemCode = sCommon.fSearchStringGet(@rItemCode)
	Select 
		OL.OperationRemark,
		U.DisplayTitle AS UserName,
		OL.CreatedDateTime,
		SIM.Code,
		SLM.Title
	From
		sAudit.tStockOperationLog OL
		--not used in this issue 26757 but added because in future want logs in other stock screens.
		--INNER JOIN sAudit.tOperationMaster OM ON OM.Id = OL.OperationId
		INNER JOIN sSecurity.tUser U ON U.Id = OL.CreatedUserId
		INNER JOIN sIp.tStockItemMaster SIM ON SIM.Id=OL.SourceId
		INNER JOIN sIp.tStoreLocationMaster SLM ON SLM.Id=SIM.StoreLocationId
	Where
		((OL.ScreenId = @rScreenId) OR (@rScreenId = 0)) 
		AND ((SIM.Code like @rItemCode) OR (ISNULL(@rItemCode,'')=''))
		AND (CONVERT(Date,OL.CreatedDateTime) >= @rFromDate)
		AND (CONVERT(Date,OL.CreatedDateTime) <= @rToDate)
	ORDER BY
		OL.CreatedDateTime DESC
END
GO
PRINT N'Creating Procedure [sFee].[pRptFeeCertificateWithAllFeeDetailsGet]...';


GO

CREATE PROCEDURE [sFee].[pRptFeeCertificateWithAllFeeDetailsGet]  
  
	@rAdmissionCategoryId int,  
	@rClassId int,  
	@rDivisionId int,   
	@rBatchId int,    
	@rBuilder1 nvarchar(max),  
	@rBuilder2 nvarchar(max),   
	@rOrgId int,  
	@rOrgGroupBatchId int,  
	@rStatusId int,  
	@rCommonBatch nvarchar(100),  
	@rDepartmentId int,  
	@rFromRollNo int,  
    @rToRollNo int,  
    @rCode nvarchar(20),  
    @rIsDetail bit=0,  
	@rIsFilter bit,  
	@rIsHeader bit,  
	@rFeeHeadId nvarchar(max) = '',  
	@rIsDisplayOrgGroup bit=0,  
	@rFeeId nvarchar(max) = '',  
	@rFilterId int=0,
	@rOrgIds nvarchar(max) = '',
	@rClassStatusId int=0	  
  
WITH EXECUTE AS CALLER  
AS  
SET NOCOUNT ON  
BEGIN       
BEGIN
	CREATE TABLE #FeeSetup (
		FeeId INT,
		Id INT,
		Amount DECIMAL(12, 2),
		ClassId INT,
		AdmissionCategoryId INT,
		AcademicId BIGINT,
		BatchId INT
	);
	
	INSERT INTO #FeeSetup (FeeId, Id, Amount, ClassId, AdmissionCategoryId, AcademicId, BatchId)
		SELECT 
			FS1.FeeId,
			FS1.Id,
			ISNULL(FS1.Amount, 0) AS Amount,
			FS1.ClassId,
			FS1.AdmissionCategoryId,
			0 AS AcademicId,
			FS1.BatchId
		FROM sFee.tFeeSetup FS1
		WHERE FS1.BatchId = @rBatchId AND IsOptional = 0 AND (FS1.AdmissionCategoryId=@rAdmissionCategoryId OR @rAdmissionCategoryId=0)
		UNION ALL
		SELECT 
			FS1.FeeId,
			FS1.Id,
			ISNULL(FS1.Amount, 0) AS Amount,
			FS1.ClassId,
			FS1.AdmissionCategoryId,
			FO.SourceId AS AcademicId,
			FS1.BatchId
		FROM sFee.tFeeSetup FS1
		INNER JOIN sFee.tFeeOptional FO ON FO.FeeSetupId = FS1.Id AND FO.SourceTypeId = 2001
		WHERE FS1.BatchId = @rBatchId AND IsOptional = 1 AND (FS1.AdmissionCategoryId=@rAdmissionCategoryId OR @rAdmissionCategoryId=0);

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

	INSERT INTO #ReceiptAmount (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 		
		WHERE R.SourceTypeId = 2001 AND R.IsObsolete = 0 AND R.BatchId = @rBatchId
		GROUP BY R.SourceId, FeeSetupId;

END	  
BEGIN
	SELECT   
		@rBuilder1 AS Builder1,  
		@rBuilder2 AS Builder2,   
		@rIsDetail AS IsDetail,  
		@rIsFilter As IsFilter,  
		@rIsHeader As IsHeader,  
		@rIsDisplayOrgGroup AS IsDisplayOrgGroup,   
		SA.ClassId,  
		SA.ClassName,
		SA.ClassOrderIndex,  
		SA.DivisionId,  
		SA.DivisionName,
		SA.DivisionOrder AS DivisionOrderIndex,
		SA.ClassName+' - '+SA.DivisionName AS ClassDivision,  
		SA.RollNo,  
		SA.AcademicId,  
		SA.FirstName,  
		SA.MiddleName,  
		SA.LastName,  
		SA.Code,  
		SA.Name,
		SA.OrgId, 
		ISNULL(SA.SUID,'') AS SUID,
		ISNULL(SA.BatchName,'') BatchName,
		ISNULL(SA.GenderId,0) AS GenderId,
		DM.Id AS DepartmentId,  
		DM.Title AS DepartmentName,  
		ISNULL(DM.OrderIndex,0) as DepartmentOrderIndex,   
		ISNULL(FM.Id,0) AS FeeId,  
		ISNULL(FM.Title,'') AS Fee,
		FM.Code AS FeeCode,  
		FM.OrderIndex AS FeeOrderIndex,
		ISNULL(FM.FeeHeadId,0) AS FeeHeadId,  
		ISNULL(FHM.Title,'') AS FeeHead,  
		ISNULL(FHM.Code,'') AS FeeHeadCode,  
		ISNULL(FHM.OrderIndex,0) AS FeeHeadOrderIndex,  	   
		ISNULL(R.PaidAmount,0.00) 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(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00) AS TotalAmount

	FROM 
		sStudent.vStudentAcademic SA
		INNER JOIN #FeeSetup FS ON SA.ClassId = FS.ClassId AND SA.BatchId = FS.BatchId AND (SA.AcademicId = FS.AcademicId OR FS.AcademicId = 0)
		LEFT JOIN #ReceiptAmount R ON SA.AcademicId = R.SourceId AND R.FeeSetupId = FS.Id	 
		INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS.FeeId  
		INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FM.FeeHeadId   
		INNER JOIN sSetup.tDepartmentMaster DM ON SA.DepartmentId=DM.Id  
		INNER JOIN sSetup.tOrganizationMaster O ON O.Id=sa.OrgId   
		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.tFeeAllocation FA ON FA.FeeSetupId=FS.Id AND FA.SourceId=SA.AcademicId
	WHERE    
		((SA.AdmissionCategoryId = @rAdmissionCategoryId) OR (@rAdmissionCategoryId = 0))  
		AND ((SA.ClassId = @rClassId) OR (@rClassId = 0))  
		AND ((SA.DivisionId = @rDivisionId) OR (@rDivisionId = 0))    
		AND (SA.OrgGroupBatchId = @rOrgGroupBatchId)  
		AND ((SA.OrgId=@rOrgId) OR (@rOrgId=0))        
		AND (SA.StatusId = @rStatusId OR @rStatusId=0)  
		AND ((SA.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))  
		AND ((SA.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))  
		AND ((SA.RollNo <= @rToRollNo) OR (@rToRollNo=0))  
		AND ((SA.Code=@rCode) OR (@rCode=''))  
		AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))    
		AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')  
		AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')   
		AND (  
		(@rFilterId = 0) -- All  
			OR (@rFilterId = 2 AND isnull(AR.SourceId,0)!=0) -- Hostel  
			OR (@rFilterId = 3 AND isnull(RT.SourceId,0)!=0) -- Transport  
			OR ((@rFilterId =1) AND ((isnull(AR.SourceId,0)=0) AND (isnull(RT.SourceId,0)=0)))  
		)  
		AND (ISNULL(SA.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')
  		AND ((SA.ClassStatusId=@rClassStatusId) OR (@rClassStatusId=0))  
	ORDER By SA.ClassId,SA.AcademicId
END

DROP TABLE #ReceiptAmount
DROP TABLE #FeeSetup

--BEGIN -- For DataSet Drag & Drop
--	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,
--	0 AS ClassId,
--	'' AS ClassName,
--	0 AS ClassOrderIndex,
--	0 AS DivisionId,
--	'' AS DivisionName,
--  0 AS DivisionOrderIndex,
--	'' AS ClassDivision,
--	0 AS RollNo,
--	CONVERT(BigInt,0) AS AcademicId,
--	'' AS FirstName,
--	'' AS MiddleName,
--	'' AS LastName,
--	'' AS Code,
--	'' AS Name,
--	0 AS OrgId,
--	'' AS SUID,
--	'' AS BatchName,
--	0 AS GenderId,
--	0 AS DepartmentId,
--	'' AS DepartmentName,
--	0 AS DepartmentOrderIndex,
--	0 AS FeeId,
--	'' AS Fee,
--	'' AS FeeCode,
--	0 AS FeeOrderIndex,
--	0 AS FeeHeadId,
--	'' AS FeeHead,
--	'' AS FeeHeadCode,
--	0 AS FeeHeadOrderIndex,
--	CONVERT(DECIMAL,0) AS PaidAmount,
--	CONVERT(DECIMAL,0) AS PendingAmount,
--	CONVERT(DECIMAL,0) AS TotalAmount
--END

END
GO
PRINT N'Creating Procedure [sHrm].[pEmployeeReplacementDeleteAndTransfer]...';


GO
CREATE PROCEDURE [sHrm].[pEmployeeReplacementDeleteAndTransfer]
	 
        @rExistingEmployeeId BIGINT,
		@rNewEmployeeId BIGINT,
		@rId NVARCHAR(500)
	

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	IF OBJECT_ID('tempdb..#tmpSplitTable') IS NOT NULL DROP TABLE #tmpSplitTable

	CREATE Table #tmpSplitTable
	(
		Id NVARCHAR(150)
	)

	INSERT INTO #tmpSplitTable
	SELECT CAST(item AS NVARCHAR(20)) AS Id FROM  sCommon.fnsplit(@rId,',')

	IF EXISTS (SELECT 1 from #tmpSplitTable WHERE Id ='Assign Teacher')
	BEGIN
		INSERT INTO sTimetable.tAssignTeacher
		Select TimeTableSchemaId, @rNewEmployeeId from sTimetable.tAssignTeacher WHERE EmployeeId = @rExistingEmployeeId

		delete from sTimetable.tAssignTeacher where EmployeeId = @rExistingEmployeeId
	END

	IF EXISTS (SELECT 1 from #tmpSplitTable WHERE Id ='Teacher Subject Division')
	BEGIN
		INSERT INTO sAcademic.tTeacherSubject
		Select @rNewEmployeeId,SubjectId from sAcademic.tTeacherSubject where EmployeeId  = @rExistingEmployeeId

		delete from sAcademic.tTeacherSubject where EmployeeId = @rExistingEmployeeId

		Insert into sAcademic.tTeacherSubjectDivision 
		select @rNewEmployeeId, SubjectId, DivisionId,SubjectCordinatorEmployeeId from sAcademic.tTeacherSubjectDivision  
		where EmployeeId = @rExistingEmployeeId

		delete from sAcademic.tTeacherSubjectDivision where EmployeeId = @rExistingEmployeeId
	END

	IF EXISTS (SELECT 1 from #tmpSplitTable WHERE Id ='Time Table')
	BEGIN
		Update sTimetable.tTimeTable
		Set EmployeeId = @rNewEmployeeId from sTimetable.tTimeTable where EmployeeId  = @rExistingEmployeeId
	END

	IF EXISTS (SELECT 1 from #tmpSplitTable WHERE Id ='Lesson Plan')
	BEGIN
		Update sAcademic.tLessonPlan
		Set EmployeeId = @rNewEmployeeId from sAcademic.tLessonPlan where EmployeeId  = @rExistingEmployeeId
	END

	IF EXISTS (SELECT 1 from #tmpSplitTable WHERE Id ='Teacher work load')
	BEGIN
		INSERT INTO sTimetable.tTeacherWorkLoad
		Select @rNewEmployeeId,BatchId,DivisionId,SubjectId,NoOfLecture,CreatedUserId,CreatedDateTime,TimeTableSchemaId
		,LectureLength from sTimetable.tTeacherWorkLoad where EmployeeId  = @rExistingEmployeeId

		delete from sTimetable.tTeacherWorkLoad where EmployeeId = @rExistingEmployeeId
	END

	IF EXISTS (SELECT 1 from #tmpSplitTable WHERE Id ='User Access')
	BEGIN
		declare @lExistingUserId bigint= (select Id from sSecurity.tUser where SourceId = @rExistingEmployeeId AND SourceTypeId = 95)
		declare @lNewUserId bigint= (select Id from sSecurity.tUser where SourceId = @rNewEmployeeId AND SourceTypeId = 95)
		Insert into sSecurity.tUserOrganization 
		select OrgId, @lNewUserId from sSecurity.tUserOrganization WHERE UserId=@lExistingUserId

		delete from sSecurity.tUserOrganization  WHERE UserId=@lExistingUserId

		INSERT INTO sSecurity.tUserAccess
		SELECT SourceTypeId, SourceId, @lNewUserId FROM sSecurity.tUserAccess WHERE UserId=@lExistingUserId

		delete from sSecurity.tUserAccess  WHERE UserId=@lExistingUserId
	END

	Drop Table #tmpSplitTable
END
GO
PRINT N'Creating Procedure [sHrm].[pEmployeeReplacementGet]...';


GO
CREATE PROCEDURE [sHrm].[pEmployeeReplacementGet]
	 
        @rEmployeeId bigint
	

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	Declare @lTeacherSubjectId bigint = 0 , @lTeacherDivisionId bigint = 0
	IF OBJECT_ID('tempdb..#tmpTable') IS NOT NULL DROP TABLE #tmpTable
	CREATE Table #tmpTable 
	(
		Id bigint IDENTITY,
		Title nvarchar(50)
	)

	IF EXISTS(select top 1 1 from sTimetable.tAssignTeacher where EmployeeId = @rEmployeeId)
	BEGIN
		Insert INTO #tmpTable Values
		(
			'Assign Teacher'
		)
	END


	set @lTeacherSubjectId = (select top 1 1 from sAcademic.tTeacherSubject where EmployeeId = @rEmployeeId)
	SET @lTeacherDivisionId = (select top 1 1 from sAcademic.tTeacherSubjectDivision where EmployeeId = @rEmployeeId)
	IF ((@lTeacherSubjectId = 1) OR (@lTeacherDivisionId = 1))
	BEGIN
		Insert INTO #tmpTable Values
		(
			'Teacher Subject Division'
		)
	END

	IF EXISTS (select top 1 1 from sTimetable.tTimeTable where EmployeeId = @rEmployeeId)
	BEGIN
		Insert INTO #tmpTable Values
		(
			'Time Table'
		)
	END

	IF EXISTS (select top 1 1 from sTimetable.tTeacherWorkLoad where EmployeeId = @rEmployeeId)
	BEGIN
		Insert INTO #tmpTable Values
		(
			'Teacher Work Load'
		)
	END

	IF EXISTS (select top 1 1 from sAcademic.tLessonPlan where EmployeeId = @rEmployeeId)
	BEGIN
		Insert INTO #tmpTable Values
		(
			'Lesson Plan'
		)
	END

	declare @lUserId bigint= (select top 1 1 from sSecurity.tUser where SourceId = @rEmployeeId AND SourceTypeId = 95)
	declare @lUserOrganizationId int ,@lUserAccessId int
	SET @lUserOrganizationId = (SELECT Top 1 1 FROM sSecurity.tUserOrganization WHERE UserId=@lUserId)
	SET @lUserAccessId= (SELECT top 1 1 FROM sSecurity.tUserAccess WHERE UserId=@lUserId)
	IF ((@lUserOrganizationId = 1) OR (@lUserAccessId = 1))
	BEGIN
		Insert INTO #tmpTable Values
		(
			'User Access'
		)
	END

	select * from #tmpTable

	Drop Table #tmpTable
END
GO
PRINT N'Creating Procedure [sHrm].[pEmployeeReplacementTransfer]...';


GO
CREATE PROCEDURE [sHrm].[pEmployeeReplacementTransfer]
	 
        @rExistingEmployeeId BIGINT,
		@rNewEmployeeId BIGINT,
		@rId NVARCHAR(max),
		@rOrgId int
	

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	IF OBJECT_ID('tempdb..#tmpSplitTable') IS NOT NULL DROP TABLE #tmpSplitTable

	CREATE Table #tmpSplitTable
	(
		Id NVARCHAR(max)
	)
	INSERT INTO #tmpSplitTable
	SELECT CAST(item AS NVARCHAR(max)) AS Id FROM  sCommon.fnsplit(@rId,',')

	IF EXISTS (SELECT 1 from #tmpSplitTable WHERE Id ='Assign Teacher')
	BEGIN
		INSERT INTO sTimetable.tAssignTeacher
		Select TimeTableSchemaId, @rNewEmployeeId from sTimetable.tAssignTeacher WHERE EmployeeId = @rExistingEmployeeId
	END

	IF EXISTS (SELECT 1 from #tmpSplitTable WHERE Id ='Teacher Subject Division')
	BEGIN
		INSERT INTO sAcademic.tTeacherSubject
		Select @rNewEmployeeId,SubjectId from sAcademic.tTeacherSubject where EmployeeId  = @rExistingEmployeeId

		Insert into sAcademic.tTeacherSubjectDivision 
		select @rNewEmployeeId, SubjectId, DivisionId,SubjectCordinatorEmployeeId from sAcademic.tTeacherSubjectDivision  where EmployeeId = @rExistingEmployeeId
	END

	IF EXISTS (SELECT 1 from #tmpSplitTable WHERE Id ='Teacher work load')
	BEGIN
		INSERT INTO sTimetable.tTeacherWorkLoad
		Select @rNewEmployeeId,BatchId,DivisionId,SubjectId,NoOfLecture,CreatedUserId,CreatedDateTime,TimeTableSchemaId
		,LectureLength from sTimetable.tTeacherWorkLoad where EmployeeId  = @rExistingEmployeeId

	END

	IF EXISTS (SELECT 1 from #tmpSplitTable WHERE Id ='User Access')
	BEGIN
		declare @lExistingUserId bigint= (select Id from sSecurity.tUser where SourceId = @rExistingEmployeeId AND SourceTypeId = 95)
		declare @lNewUserId bigint= (select Id from sSecurity.tUser where SourceId = @rNewEmployeeId AND SourceTypeId = 95)
		Insert into sSecurity.tUserOrganization 
		select OrgId, @lNewUserId from sSecurity.tUserOrganization WHERE UserId=@lExistingUserId

		INSERT INTO sSecurity.tUserAccess
		SELECT SourceTypeId, SourceId, @lNewUserId FROM sSecurity.tUserAccess WHERE UserId=@lExistingUserId
	END

	IF EXISTS (SELECT 1 from #tmpSplitTable WHERE Id ='Lesson Plan')
	BEGIN
		declare @lCount int,@lNextNumber BIGINT ,@lId int
		Create table #tmpLessonPlan
		(
			Id bigint IDENTITY,
			TopicId int,
			DivisionId int, 
			NoOfPeriodRequired smallint,
			Objective nvarchar(1000),
			IndicativeHomework nvarchar(200),
			Summary nvarchar(200),
			StartDate date,
			EndDate date,
			IsCompleted bit,
			EmployeeId bigint,
			BatchId int,
			CreatedUserId bigint,
			OrgId smallint,
			LearningExperience nvarchar(1000),
			ToolsAndTechniques nvarchar(500),
			EssentialMaterial nvarchar(500),
			AssessmentQuestion	nvarchar(1000),	
			TeacherExample	nvarchar(1000),
			GuidedPractice	nvarchar(1000),
			IndependentPractice	nvarchar(1000),
			SubTopic nvarchar(1000),
			Session nvarchar(100) 
		)

		insert into #tmpLessonPlan
		select * from sAcademic.tLessonPlan where EmployeeId  = @rExistingEmployeeId

		Set @lCount = (Select Count(Id) from #tmpLessonPlan)
		WHILE @lCount > 0
		BEGIN
			EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sAcademic.tLessonPlan', 0, 1, 1,@outNextNumber = @lNextNumber output

			Set @lId = (Select Id from #tmpLessonPlan where Id = @lCount)

			INSERT INTO sAcademic.tLessonPlan
			select @lNextNumber, TopicId,DivisionId,NoOfPeriodRequired,Objective,IndicativeHomework,Summary,StartDate,EndDate,IsCompleted
			,@rNewEmployeeId,BatchId,CreatedUserId,CreatedDateTime,LearningExperience,ToolsAndTechniques,EssentialMaterial,AssessmentQuestion,
			TeacherExample,GuidedPractice,IndependentPractice,SubTopic ,[Session] ,TrainingMethod ,PeriodCount,Remark
			from #tmpLessonPlan  where Id  = @lId
			
			set @lCount = @lCount-1
		END

		drop table #tmpLessonPlan
	END

	IF EXISTS (SELECT 1 from #tmpSplitTable WHERE Id ='Time Table')
	BEGIN
		declare @lCount1 int,@lNextNumber1 BIGINT ,@lId1 int

		Create Table #tmpTimeTable 
		(
				[Id] int identity
			   ,[TimeTableSchemaId] int
			   ,[EmployeeId] bigint
			   ,[DivisionId] int
			   ,[SubjectId] int
			   ,[DayId] smallint
			   ,[LectureNumber] smallint
			   ,[LockNo] bigint
			   ,[LockColour] varchar(50)
		)

		insert into #tmpTimeTable
		select [TimeTableSchemaId],@rNewEmployeeId,[DivisionId],[SubjectId],[DayId],[LectureNumber],[LockNo],[LockColour]
		from sTimetable.tTimeTable  where EmployeeId  = @rExistingEmployeeId

		Set @lCount1 = (Select Count(Id) from #tmpTimeTable)

		WHILE @lCount1 > 0
		BEGIN
			EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sTimetable.tTimeTable', 0, 1, 1,@outNextNumber = @lNextNumber1 output

			Set @lId1 = (Select Id from #tmpTimeTable where Id = @lCount1)

			INSERT INTO sTimetable.tTimeTable
			select @lNextNumber1,[TimeTableSchemaId],EmployeeId,[DivisionId],[SubjectId],[DayId],[LectureNumber],[LockNo],[LockColour]
			from #tmpTimeTable  where Id = @lId1
			set @lCount1 = @lCount1 -  1
		END

		drop table #tmpTimeTable
	END
	Drop Table #tmpSplitTable
END
GO
PRINT N'Creating Procedure [sStudent].[pAlphaNumericOrder]...';


GO
CREATE PROCEDURE sStudent.pAlphaNumericOrder
	 
	 @rOrgId smallint = 0

	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

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

	CREATE TABLE #tmpStudent
	(
		Id bigint IDENTITY,
		Code nvarchar(20),
		OrgId smallint,
		StudentId bigint
	)
	
	INSERT INTO #tmpStudent
	SELECT Code,OrgId, Id  As StudentId from sStudent.tStudentMaster
	where (OrgId = @rOrgId OR @rOrgId = 0)
	ORDER BY CASE IsNumeric (Code) WHEN 1 THEN Replicate (0, 100 - Len (Code)) + Code  ELSE Code  END

	Update SM SET SM.Number = T.Id
	from #tmpStudent T INNER JOIN sStudent.tStudentMaster SM ON SM.Id = T.StudentId AND SM.Code = T.Code AND SM.OrgId = T.OrgId
	where (SM.OrgId = @rOrgId OR @rOrgId = 0)

	Drop Table #tmpStudent
END
GO
PRINT N'Creating Procedure [sStudent].[pRptStudentBMIListGet]...';


GO
CREATE PROCEDURE [sStudent].[pRptStudentBMIListGet]
	@rBuilder1 nvarchar(max)='',
	@rBuilder2 nvarchar(max)='',
	@rOrgId smallint=0,
	@rBatchId int=0,
	@rDepartmentId int=0,
	@rStrCode nvarchar(max)='',
	@rClassId int=0,
	@rDivisionId int=0,
	@rStudentId bigint=0,
	@rStatusId int=0,
	@rClassStatusId int=0,
	@rFromRollNo int=0,
	@rToRollNo int=0,
	@rHouseGroupId int=0


	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON


BEGIN

	SELECT
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			SA.AcademicId,
			SA.StudentId,
			SA.Code,
			SA.RollNo AS RollNo,
			SA.Name,
			SA.ClassId,
			SA.ClassName,
			SA.DivisionId,
			SA.DivisionName,
			SA.StatusName,
			SA.DivisionOrder,
			SA.Number AS StudentNumber,
			ISNULL(HM.Title,'') AS HouseName,
			SA.ClassStatusName,
			ISNULL(AD.HeightAnnual,0) AS Height,
			ISNULL(AD.WeightAnnual,0) AS Weight,
			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

	FROM
		 	sStudent.vStudentAcademic SA
			LEFT JOIN sStudent.tStudentOther SO ON SA.StudentId = SO.StudentId
		 	LEFT JOIN sActivity.tHouseMaster HM ON SO.HouseId = HM.Id
		 	INNER JOIN sSetup.tBatchClass BC ON BC.ClassID =  SA.ClassId and BC.BatchId= @rBatchId
			LEFT JOIN sStudent.tAcademicDetail AD ON AD.AcademicId=SA.AcademicId

	WHERE
			SA.OrgId=@rOrgId
		AND	SA.BatchId = @rBatchId
		AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
		AND (ISNULL(SA.Code,0) IN( SELECT cast(item as nvarchar(20)) FROM  sCommon.fnsplit(@rStrCode,',')) OR @rStrCode='')
		AND ((SA.ClassId=@rClassId) OR (@rClassId=0))
		AND ((SA.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		AND ((SA.StudentId=@rStudentId) OR (@rStudentId=0))
		AND ((SA.StatusId=@rStatusId)OR(@rStatusId=0))
		AND ((SA.ClassStatusId=@rClassStatusId)OR(@rClassStatusId=0))
		AND ((SA.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
		AND ((SA.RollNo <= @rToRollNo) OR (@rToRollNo=0))
		AND ((SO.HouseId=@rHouseGroupId)OR(@rHouseGroupId=0))

END
GO

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



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

/*
Deployment script for NetVidyalayaVersionBlank

This code was generated by a tool.
Changes to this file may cause incorrect behavior and will be lost if
the code is regenerated.
*/

GO
SET ANSI_NULLS, ANSI_PADDING, ANSI_WARNINGS, ARITHABORT, CONCAT_NULL_YIELDS_NULL, QUOTED_IDENTIFIER ON;
GO
ALTER FUNCTION [sHrm].[fAttendanceWithApproveLeaveGet](@rEmployeeId bigint, @rForYear smallint,@rForMonth smallint,@rDay smallint,@rBatchId int,@rDepartmentId int,@rOrgId int,@rAttendanceDate nvarchar(20), @rDateOfJoining date,@rDateOfLeaving date,@rStatus nvarchar(10))
RETURNS [nvarchar](50) WITH EXECUTE AS CALLER
AS 
BEGIN	

DECLARE @lWeekOff nvarchar(20)
Declare @WeekNumber int,@EmpSecondWeekOffRule int,@EmpFirstWeekOffRule int
DECLARE @lDate datetime,@lWeekDay1 nvarchar(20),@lWeekDay2  nvarchar(20)
DECLARE @lCOUNT int 
DECLARE @lEmployeeFirstWeekOffDayId int
DECLARE @lEmployeeSEcondWeekOffDayId int
DECLARE @lEmployeeFirstWeekOffRuleId int
DECLARE @lEmployeeSecondWeekOffRuleId int



SET @lDate = CONVERT(nvarchar(10), @rForYear)+ '-' +  CONVERT(nvarchar(10), @rForMonth) + '-' + CONVERT(nvarchar(10), @rDay)
SET @lWeekOff = [sAssessment].[fGetdayNumber](@lDate)
Set @WeekNumber = datediff(week, dateadd(week, datediff(week, 0, dateadd(month, datediff(month, 0, @lDate), 0)), 0), @lDate - 1) + 1

SET @lEmployeeFirstWeekOffDayId= (SELECT EmployeeFirstWeekOffDayId FROM sSetup.tOrganizationMaster  WHERE Id = @rOrgId) 
SET @lEmployeeSEcondWeekOffDayId= (SELECT EmployeeSEcondWeekOffDayId FROM sSetup.tOrganizationMaster  WHERE Id = @rOrgId) 
SET @lEmployeeFirstWeekOffRuleId= (SELECT EmployeeFirstWeekOffRuleId FROM sSetup.tOrganizationMaster  WHERE Id = @rOrgId) 
SET @lEmployeeSecondWeekOffRuleId= (SELECT EmployeeSecondWeekOffRuleId FROM sSetup.tOrganizationMaster  WHERE Id = @rOrgId) 



IF ((@lEmployeeFirstWeekOffDayId !=0 AND @lEmployeeFirstWeekOffRuleId !=0 ) OR (@lEmployeeSEcondWeekOffDayId != 0 AND @lEmployeeSecondWeekOffRuleId!=0))
	BEGIN
	SELECT @lWeekDay1 = EmployeeFirstWeekOffDayId,@lWeekDay2 = EmployeeSEcondWeekOffDayId,@EmpFirstWeekOffRule = EmployeeFirstWeekOffRuleId,@EmpSecondWeekOffRule = EmployeeSecondWeekOffRuleId  FROM sSetup.tOrganizationMaster  WHERE Id = @rOrgId 
	END 
	
	ELSE
	
	BEGIN
	SELECT @lWeekDay1 = FirstWeekOffDayId, @lWeekDay2 = SecondWeekOff,@EmpFirstWeekOffRule = FristWeekOffRuleId,@EmpSecondWeekOffRule = SEcondWeekOffRuleId FROM sActivity.tWeekOffSetting  WHERE SourceId = @rEmployeeId AND SourceTypeId=95
		
	END


if @EmpFirstWeekOffRule = 1 
	BEGIN		
		if(@lWeekOff = @lWeekDay1)
			BEGIN	
				if(@rDateOfJoining  > @rAttendanceDate)
				BEGIN 
					 Set @rStatus = 'NA'
				END
				ELSE
				BEGIN
					 Set @rStatus = 'W'
				END	
				
				if(@rStatus !='W')	
				BEGIN	
					if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=1)
					BEGIN 
						SET @rStatus = 'P'
					END
						if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=0)
					BEGIN 						
						SET @rStatus = 'A'
					END
				END

					IF EXISTS(SELECT 1 from  sHrm.tLeave where   @rAttendanceDate BETWEEN FromDate AND ToDate AND  OrgId = @rOrgId AND EmployeeId = @rEmployeeId AND BatchId =@rBatchId) 
					 BEGIN
							if(@rStatus !='W')	
							BEGIN
								SET @rStatus = (Select Distinct case when l.LeavePeriodId=1 then LTM.Code else 'HD-'+LTM.Code end from sHrm.tLeaveTypeMaster LTM INNER JOIN sHrm.tLeave l On LTM.Id= l.LeaveTypeId AND l.StatusId=550 where  (@lDate BETWEEN L.FromDate AND L.ToDate ) AND L.OrgId = @rOrgid AND L.EmployeeId = @rEmployeeId AND L.BatchId =@rBatchid)
							END
							BEGIN
								SET @rStatus = (Select Distinct  'W-'+LTM.Code from sHrm.tLeaveTypeMaster LTM INNER JOIN sHrm.tLeave l On LTM.Id= l.LeaveTypeId AND l.StatusId=550 where  (@lDate BETWEEN L.FromDate AND L.ToDate ) AND L.OrgId = @rOrgid AND L.EmployeeId = @rEmployeeId AND L.BatchId =@rBatchid)
							END
							IF(@rStatus IS NULL)
							BEGIN
								IF Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=1)
								BEGIN 
									SET @rStatus = 'P'
									RETURN @rStatus
								END
								IF Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=0)
								BEGIN 						
									SET @rStatus = 'A'
									RETURN @rStatus
								END
							END
							ELSE
							BEGIN
								RETURN @rStatus
							END																
					 END
					IF   EXISTS(SELECT 1 FROM sActivity.tEventSchedule ES INNER JOIN  sActivity.tEventAssign EA ON EA.EventScheduleId=ES.Id
						INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id=EA.SourceId 
						WHERE ES.BatchId = @rBatchId AND ((SourceId=@rDepartmentId) OR (@rDepartmentId=0)) 
						AND SourceTypeId in (2004, 3,95)
						AND (@lDate BETWEEN ES.FromDate AND ES.ToDate) AND ES.IsHoliday=1)  
					 BEGIN
						 SET @rStatus = 'H'	
						 RETURN @rStatus		
					 END
					END
				
			 END
	Else if @EmpFirstWeekOffRule = 2 
	BEGIN
		   
		IF @WeekNumber = 2 or @WeekNumber = 4 
		BEGIN
			
			if(@lWeekOff = @lWeekDay1)
			BEGIN
				--Set @rStatus = 'W'
				if(@rDateOfJoining  > @rAttendanceDate)
				BEGIN 
					 Set @rStatus = 'NA'
				END
				ELSE
				BEGIN
					 Set @rStatus = 'W'
				END	
				
							
				if(@rStatus !='W')	
				BEGIN
					if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=1)
					BEGIN 
						SET @rStatus = 'P'
					END
						if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=0)
					BEGIN 
						SET @rStatus = 'A'
					END
				END
					IF EXISTS(SELECT 1 from  sHrm.tLeave where   @rAttendanceDate BETWEEN FromDate AND ToDate AND  OrgId = @rOrgId AND EmployeeId = @rEmployeeId AND BatchId =@rBatchId) 
					BEGIN
						if(@rStatus !='W')	
						BEGIN
							SET @rStatus = (Select Distinct case when l.LeavePeriodId=1 then LTM.Code else 'HD-'+LTM.Code end from sHrm.tLeaveTypeMaster LTM INNER JOIN sHrm.tLeave l On LTM.Id= l.LeaveTypeId AND l.StatusId=550 where  (@lDate BETWEEN L.FromDate AND L.ToDate ) AND L.OrgId = @rOrgid AND L.EmployeeId = @rEmployeeId AND L.BatchId =@rBatchid)
						END
						BEGIN
							SET @rStatus = (Select Distinct  'W-'+LTM.Code from sHrm.tLeaveTypeMaster LTM INNER JOIN sHrm.tLeave l On LTM.Id= l.LeaveTypeId AND l.StatusId=550 where  (@lDate BETWEEN L.FromDate AND L.ToDate ) AND L.OrgId = @rOrgid AND L.EmployeeId = @rEmployeeId AND L.BatchId =@rBatchid)
						END
							
						IF(@rStatus IS NULL)
						BEGIN
							IF Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=1)
							BEGIN 
								SET @rStatus = 'P'
								RETURN @rStatus
							END
							IF Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=0)
							BEGIN 						
								SET @rStatus = 'A'
								RETURN @rStatus
							END
						END
						ELSE
						BEGIN
							RETURN @rStatus
						END																
					 END
						IF   EXISTS(SELECT 1 FROM sActivity.tEventSchedule ES INNER JOIN  sActivity.tEventAssign EA ON EA.EventScheduleId=ES.Id
						INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id=EA.SourceId WHERE ES.BatchId = @rBatchId AND ((SourceId=@rDepartmentId) OR (@rDepartmentId=0)) 
						AND SourceTypeId in (2004, 3,95)
						AND (@lDate BETWEEN ES.FromDate AND ES.ToDate) AND ES.IsHoliday=1)  
		        BEGIN
			         SET @rStatus = 'H'	
					RETURN @rStatus		
		        END
		     END
		END
	END
	else if @EmpFirstWeekOffRule = 3
	BEGIN
		   
		if @WeekNumber = 1 or @WeekNumber = 3 
		BEGIN
			if(@lWeekOff = @lWeekDay1)
			BEGIN
				--Set @rStatus = 'W'	
				if(@rDateOfJoining  > @rAttendanceDate)
				BEGIN 
					 Set @rStatus = 'NA'
				END
				ELSE
				BEGIN
					 Set @rStatus = 'W'
				END
				if(@rStatus !='W')	
				BEGIN
				
					if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=1)
					BEGIN 
						SET @rStatus = 'P'
					END
						if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=0)
					BEGIN 
						SET @rStatus = 'A'
					END
				END
					IF EXISTS(SELECT 1 from  sHrm.tLeave where   @rAttendanceDate BETWEEN FromDate AND ToDate AND  OrgId = @rOrgId AND EmployeeId = @rEmployeeId AND BatchId =@rBatchId) 
					 BEGIN
							if(@rStatus !='W')	
							BEGIN
								SET @rStatus = (Select Distinct case when l.LeavePeriodId=1 then LTM.Code else 'HD-'+LTM.Code end from sHrm.tLeaveTypeMaster LTM INNER JOIN sHrm.tLeave l On LTM.Id= l.LeaveTypeId AND l.StatusId=550 where  (@lDate BETWEEN L.FromDate AND L.ToDate ) AND L.OrgId = @rOrgid AND L.EmployeeId = @rEmployeeId AND L.BatchId =@rBatchid)
							END
							BEGIN
								SET @rStatus = (Select Distinct  'W-'+LTM.Code from sHrm.tLeaveTypeMaster LTM INNER JOIN sHrm.tLeave l On LTM.Id= l.LeaveTypeId AND l.StatusId=550 where  (@lDate BETWEEN L.FromDate AND L.ToDate ) AND L.OrgId = @rOrgid AND L.EmployeeId = @rEmployeeId AND L.BatchId =@rBatchid)
							END
							
							IF(@rStatus IS NULL)
							BEGIN
								IF Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=1)
								BEGIN 
									SET @rStatus = 'P'
									RETURN @rStatus
								END
								IF Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=0)
								BEGIN 						
									SET @rStatus = 'A'
									RETURN @rStatus
								END
							END
							ELSE
							BEGIN
								RETURN @rStatus
							END																
					 END
					IF   EXISTS(SELECT 1 FROM sActivity.tEventSchedule ES INNER JOIN  sActivity.tEventAssign EA ON EA.EventScheduleId=ES.Id
						INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id=EA.SourceId WHERE ES.BatchId = @rBatchId AND ((SourceId=@rDepartmentId) OR (@rDepartmentId=0)) 
						AND SourceTypeId in (2004, 3,95)
						AND (@lDate BETWEEN ES.FromDate AND ES.ToDate) AND ES.IsHoliday=1)  
				BEGIN
					SET @rStatus = 'H'	
					RETURN @rStatus	
				END
			END
		 END
	END
	else if @EmpFirstWeekOffRule = 4
	BEGIN
		   
		if @WeekNumber = 1 or @WeekNumber = 3 or @WeekNumber = 5
		BEGIN
			if(@lWeekOff = @lWeekDay1)
			BEGIN
				--Set @rStatus = 'W'	
				if(@rDateOfJoining  > @rAttendanceDate)
				BEGIN 
					 Set @rStatus = 'NA'
				END
				ELSE
				BEGIN
					 Set @rStatus = 'W'
				END
				
				if(@rStatus !='W')	
				BEGIN
					if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=1)
					BEGIN 
						SET @rStatus = 'P'
					END
						if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=0)
					BEGIN 
						SET @rStatus = 'A'
					END
				END
					IF EXISTS(SELECT 1 from  sHrm.tLeave where   @rAttendanceDate BETWEEN FromDate AND ToDate AND  OrgId = @rOrgId AND EmployeeId = @rEmployeeId AND BatchId =@rBatchId) 
					 BEGIN
							if(@rStatus !='W')	
							BEGIN
								SET @rStatus = (Select Distinct case when l.LeavePeriodId=1 then LTM.Code else 'HD-'+LTM.Code end from sHrm.tLeaveTypeMaster LTM INNER JOIN sHrm.tLeave l On LTM.Id= l.LeaveTypeId AND l.StatusId=550 where  (@lDate BETWEEN L.FromDate AND L.ToDate ) AND L.OrgId = @rOrgid AND L.EmployeeId = @rEmployeeId AND L.BatchId =@rBatchid)
							END
							BEGIN
								SET @rStatus = (Select Distinct  'W-'+LTM.Code from sHrm.tLeaveTypeMaster LTM INNER JOIN sHrm.tLeave l On LTM.Id= l.LeaveTypeId AND l.StatusId=550 where  (@lDate BETWEEN L.FromDate AND L.ToDate ) AND L.OrgId = @rOrgid AND L.EmployeeId = @rEmployeeId AND L.BatchId =@rBatchid)
							END
							IF(@rStatus IS NULL)
							BEGIN
								IF Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=1)
								BEGIN 
									SET @rStatus = 'P'
									RETURN @rStatus
								END
								IF Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=0)
								BEGIN 						
									SET @rStatus = 'A'
									RETURN @rStatus
								END
							END
							ELSE
							BEGIN
								RETURN @rStatus
							END																
					 END
					IF   EXISTS(SELECT 1 FROM sActivity.tEventSchedule ES INNER JOIN  sActivity.tEventAssign EA ON EA.EventScheduleId=ES.Id
						INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id=EA.SourceId WHERE ES.BatchId = @rBatchId AND ((SourceId=@rDepartmentId) OR (@rDepartmentId=0)) 
						AND SourceTypeId in (2004, 3,95)
						AND (@lDate BETWEEN ES.FromDate AND ES.ToDate) AND ES.IsHoliday=1)  
				BEGIN
					SET @rStatus = 'H'	
					RETURN @rStatus	
				END
			END
			 
		END
		 
	END
	else if @EmpFirstWeekOffRule = 5
	BEGIN
		   
		if @WeekNumber = 2 or @WeekNumber = 3 
		BEGIN
			if(@lWeekOff = @lWeekDay1)
			BEGIN
				--Set @rStatus = 'W'	
				if(@rDateOfJoining  > @rAttendanceDate)
				BEGIN 
					 Set @rStatus = 'NA'
				END
				ELSE
				BEGIN
					 Set @rStatus = 'W'
				END
				if(@rStatus !='W')	
				BEGIN
					if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=1)
					BEGIN 
						SET @rStatus = 'P'
					END
						if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=0)
					BEGIN 
						SET @rStatus = 'A'
					END
				END
					IF EXISTS(SELECT 1 from  sHrm.tLeave where   @rAttendanceDate BETWEEN FromDate AND ToDate AND  OrgId = @rOrgId AND EmployeeId = @rEmployeeId AND BatchId =@rBatchId) 
					 BEGIN
							if(@rStatus !='W')	
							BEGIN
								SET @rStatus = (Select Distinct case when l.LeavePeriodId=1 then LTM.Code else 'HD-'+LTM.Code end from sHrm.tLeaveTypeMaster LTM INNER JOIN sHrm.tLeave l On LTM.Id= l.LeaveTypeId AND l.StatusId=550 where  (@lDate BETWEEN L.FromDate AND L.ToDate ) AND L.OrgId = @rOrgid AND L.EmployeeId = @rEmployeeId AND L.BatchId =@rBatchid)
							END
							BEGIN
								SET @rStatus = (Select Distinct  'W-'+LTM.Code from sHrm.tLeaveTypeMaster LTM INNER JOIN sHrm.tLeave l On LTM.Id= l.LeaveTypeId AND l.StatusId=550 where  (@lDate BETWEEN L.FromDate AND L.ToDate ) AND L.OrgId = @rOrgid AND L.EmployeeId = @rEmployeeId AND L.BatchId =@rBatchid)
							END
							IF(@rStatus IS NULL)
							BEGIN
								IF Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=1)
								BEGIN 
									SET @rStatus = 'P'
									RETURN @rStatus
								END
								IF Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=0)
								BEGIN 						
									SET @rStatus = 'A'
									RETURN @rStatus
								END
							END
							ELSE
							BEGIN
								RETURN @rStatus
							END																
					 END
					IF   EXISTS(SELECT 1 FROM sActivity.tEventSchedule ES INNER JOIN  sActivity.tEventAssign EA ON EA.EventScheduleId=ES.Id
						INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id=EA.SourceId WHERE ES.BatchId = @rBatchId AND ((SourceId=@rDepartmentId) OR (@rDepartmentId=0)) 
						AND SourceTypeId in (2004, 3,95)
						AND (@lDate BETWEEN ES.FromDate AND ES.ToDate) AND ES.IsHoliday=1)  
				BEGIN
					SET @rStatus = 'H'	
					RETURN @rStatus	
				END
			END
			 
		END
		 
	END
	else if @EmpFirstWeekOffRule = 6
	BEGIN
		   
		if @WeekNumber = 1 
		BEGIN
			if(@lWeekOff = @lWeekDay1)
			BEGIN
				--Set @rStatus = 'W'	
				if(@rDateOfJoining  > @rAttendanceDate)
				BEGIN 
					 Set @rStatus = 'NA'
				END
				ELSE
				BEGIN
					 Set @rStatus = 'W'
				END
				
				if(@rStatus !='W')	
				BEGIN
					if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=1)
					BEGIN 
						SET @rStatus = 'P'
					END
						if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=0)
					BEGIN 
						SET @rStatus = 'A'
					END
				END
					IF EXISTS(SELECT 1 from  sHrm.tLeave where   @rAttendanceDate BETWEEN FromDate AND ToDate AND  OrgId = @rOrgId AND EmployeeId = @rEmployeeId AND BatchId =@rBatchId) 
					 BEGIN
							if(@rStatus !='W')	
							BEGIN
								SET @rStatus = (Select Distinct case when l.LeavePeriodId=1 then LTM.Code else 'HD-'+LTM.Code end from sHrm.tLeaveTypeMaster LTM INNER JOIN sHrm.tLeave l On LTM.Id= l.LeaveTypeId AND l.StatusId=550 where  (@lDate BETWEEN L.FromDate AND L.ToDate ) AND L.OrgId = @rOrgid AND L.EmployeeId = @rEmployeeId AND L.BatchId =@rBatchid)
							END
							BEGIN
								SET @rStatus = (Select Distinct  'W-'+LTM.Code from sHrm.tLeaveTypeMaster LTM INNER JOIN sHrm.tLeave l On LTM.Id= l.LeaveTypeId AND l.StatusId=550 where  (@lDate BETWEEN L.FromDate AND L.ToDate ) AND L.OrgId = @rOrgid AND L.EmployeeId = @rEmployeeId AND L.BatchId =@rBatchid)
							END
							IF(@rStatus IS NULL)
							BEGIN
								IF Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=1)
								BEGIN 
									SET @rStatus = 'P'
									RETURN @rStatus
								END
								IF Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=0)
								BEGIN 						
									SET @rStatus = 'A'
									RETURN @rStatus
								END
							END
							ELSE
							BEGIN
								RETURN @rStatus
							END																
					 END
					IF   EXISTS(SELECT 1 FROM sActivity.tEventSchedule ES INNER JOIN  sActivity.tEventAssign EA ON EA.EventScheduleId=ES.Id
						INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id=EA.SourceId WHERE ES.BatchId = @rBatchId AND ((SourceId=@rDepartmentId) OR (@rDepartmentId=0)) 
						AND SourceTypeId in (2004, 3,95)
						AND (@lDate BETWEEN ES.FromDate AND ES.ToDate) AND ES.IsHoliday=1)  
				BEGIN
					SET @rStatus = 'H'	
					RETURN @rStatus	
				END
			END
			 
		END
		 
	END
	else if @EmpFirstWeekOffRule = 7
	BEGIN
		   
		if @WeekNumber = 2 
		BEGIN
			if(@lWeekOff = @lWeekDay1)
			BEGIN
				--Set @rStatus = 'W'	
				if(@rDateOfJoining  > @rAttendanceDate)
				BEGIN 
					 Set @rStatus = 'NA'
				END
				ELSE
				BEGIN
					 Set @rStatus = 'W'
				END
				
				if(@rStatus !='W')	
				BEGIN
					if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=1)
					BEGIN 
						SET @rStatus = 'P'
					END
						if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=0)
					BEGIN 
						SET @rStatus = 'A'
					END
				END
					IF EXISTS(SELECT 1 from  sHrm.tLeave where   @rAttendanceDate BETWEEN FromDate AND ToDate AND  OrgId = @rOrgId AND EmployeeId = @rEmployeeId AND BatchId =@rBatchId) 
					 BEGIN
							if(@rStatus !='W')	
							BEGIN
								SET @rStatus = (Select Distinct case when l.LeavePeriodId=1 then LTM.Code else 'HD-'+LTM.Code end from sHrm.tLeaveTypeMaster LTM INNER JOIN sHrm.tLeave l On LTM.Id= l.LeaveTypeId AND l.StatusId=550 where  (@lDate BETWEEN L.FromDate AND L.ToDate ) AND L.OrgId = @rOrgid AND L.EmployeeId = @rEmployeeId AND L.BatchId =@rBatchid)
							END
							BEGIN
								SET @rStatus = (Select Distinct  'W-'+LTM.Code from sHrm.tLeaveTypeMaster LTM INNER JOIN sHrm.tLeave l On LTM.Id= l.LeaveTypeId AND l.StatusId=550 where  (@lDate BETWEEN L.FromDate AND L.ToDate ) AND L.OrgId = @rOrgid AND L.EmployeeId = @rEmployeeId AND L.BatchId =@rBatchid)
							END
							IF(@rStatus IS NULL)
							BEGIN
								IF Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=1)
								BEGIN 
									SET @rStatus = 'P'
									RETURN @rStatus
								END
								IF Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=0)
								BEGIN 						
									SET @rStatus = 'A'
									RETURN @rStatus
								END
							END
							ELSE
							BEGIN
								RETURN @rStatus
							END																
					 END
					IF   EXISTS(SELECT 1 FROM sActivity.tEventSchedule ES INNER JOIN  sActivity.tEventAssign EA ON EA.EventScheduleId=ES.Id
						INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id=EA.SourceId WHERE ES.BatchId = @rBatchId AND ((SourceId=@rDepartmentId) OR (@rDepartmentId=0)) 
						AND SourceTypeId in (2004, 3,95)
						AND (@lDate BETWEEN ES.FromDate AND ES.ToDate) AND ES.IsHoliday=1)  
				BEGIN
					SET @rStatus = 'H'	
					RETURN @rStatus	
				END
			END
			 
		END
		 
	END
	else if @EmpFirstWeekOffRule = 8
	BEGIN
		   
		if @WeekNumber = 3 
		BEGIN
			if(@lWeekOff = @lWeekDay1)
			BEGIN
				--Set @rStatus = 'W'	
				if(@rDateOfJoining  > @rAttendanceDate)
				BEGIN 
					 Set @rStatus = 'NA'
				END
				ELSE
				BEGIN
					 Set @rStatus = 'W'
				END
				
				if(@rStatus !='W')	
				BEGIN
					if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=1)
					BEGIN 
						SET @rStatus = 'P'
					END
						if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=0)
					BEGIN 
						SET @rStatus = 'A'
					END
				END
					IF EXISTS(SELECT 1 from  sHrm.tLeave where   @rAttendanceDate BETWEEN FromDate AND ToDate AND  OrgId = @rOrgId AND EmployeeId = @rEmployeeId AND BatchId =@rBatchId) 
					 BEGIN
							if(@rStatus !='W')	
							BEGIN
								SET @rStatus = (Select Distinct case when l.LeavePeriodId=1 then LTM.Code else 'HD-'+LTM.Code end from sHrm.tLeaveTypeMaster LTM INNER JOIN sHrm.tLeave l On LTM.Id= l.LeaveTypeId AND l.StatusId=550 where  (@lDate BETWEEN L.FromDate AND L.ToDate ) AND L.OrgId = @rOrgid AND L.EmployeeId = @rEmployeeId AND L.BatchId =@rBatchid)
							END
							BEGIN
								SET @rStatus = (Select Distinct  'W-'+LTM.Code from sHrm.tLeaveTypeMaster LTM INNER JOIN sHrm.tLeave l On LTM.Id= l.LeaveTypeId AND l.StatusId=550 where  (@lDate BETWEEN L.FromDate AND L.ToDate ) AND L.OrgId = @rOrgid AND L.EmployeeId = @rEmployeeId AND L.BatchId =@rBatchid)
							END
							IF(@rStatus IS NULL)
							BEGIN
								IF Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=1)
								BEGIN 
									SET @rStatus = 'P'
									RETURN @rStatus
								END
								IF Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=0)
								BEGIN 						
									SET @rStatus = 'A'
									RETURN @rStatus
								END
							END
							ELSE
							BEGIN
								RETURN @rStatus
							END																
					 END
					IF   EXISTS(SELECT 1 FROM sActivity.tEventSchedule ES INNER JOIN  sActivity.tEventAssign EA ON EA.EventScheduleId=ES.Id
						INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id=EA.SourceId WHERE ES.BatchId = @rBatchId AND ((SourceId=@rDepartmentId) OR (@rDepartmentId=0)) 
						AND SourceTypeId in (2004, 3,95)
						AND (@lDate BETWEEN ES.FromDate AND ES.ToDate) AND ES.IsHoliday=1)  
				BEGIN
					SET @rStatus = 'H'	
					RETURN @rStatus	
				END
			END
			 
		END
		 
	END
	else if @EmpFirstWeekOffRule = 9
	BEGIN
		   
		if @WeekNumber = 4 
		BEGIN
			if(@lWeekOff = @lWeekDay1)
			BEGIN
				--Set @rStatus = 'W'	
				if(@rDateOfJoining  > @rAttendanceDate)
				BEGIN 
					 Set @rStatus = 'NA'
				END
				ELSE
				BEGIN
					 Set @rStatus = 'W'
				END
				
				if(@rStatus !='W')	
				BEGIN
					if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=1)
					BEGIN 
						SET @rStatus = 'P'
					END
						if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=0)
					BEGIN 
						SET @rStatus = 'A'
					END
				END
					IF EXISTS(SELECT 1 from  sHrm.tLeave where   @rAttendanceDate BETWEEN FromDate AND ToDate AND  OrgId = @rOrgId AND EmployeeId = @rEmployeeId AND BatchId =@rBatchId) 
					 BEGIN
							if(@rStatus !='W')	
							BEGIN
								SET @rStatus = (Select Distinct case when l.LeavePeriodId=1 then LTM.Code else 'HD-'+LTM.Code end from sHrm.tLeaveTypeMaster LTM INNER JOIN sHrm.tLeave l On LTM.Id= l.LeaveTypeId AND l.StatusId=550 where  (@lDate BETWEEN L.FromDate AND L.ToDate ) AND L.OrgId = @rOrgid AND L.EmployeeId = @rEmployeeId AND L.BatchId =@rBatchid)
							END
							BEGIN
								SET @rStatus = (Select Distinct  'W-'+LTM.Code from sHrm.tLeaveTypeMaster LTM INNER JOIN sHrm.tLeave l On LTM.Id= l.LeaveTypeId AND l.StatusId=550 where  (@lDate BETWEEN L.FromDate AND L.ToDate ) AND L.OrgId = @rOrgid AND L.EmployeeId = @rEmployeeId AND L.BatchId =@rBatchid)
							END
							IF(@rStatus IS NULL)
							BEGIN
								IF Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=1)
								BEGIN 
									SET @rStatus = 'P'
									RETURN @rStatus
								END
								IF Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=0)
								BEGIN 						
									SET @rStatus = 'A'
									RETURN @rStatus
								END
							END
							ELSE
							BEGIN
								RETURN @rStatus
							END																
					 END
					IF   EXISTS(SELECT 1 FROM sActivity.tEventSchedule ES INNER JOIN  sActivity.tEventAssign EA ON EA.EventScheduleId=ES.Id
						INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id=EA.SourceId WHERE ES.BatchId = @rBatchId AND ((SourceId=@rDepartmentId) OR (@rDepartmentId=0)) 
						AND SourceTypeId in (2004, 3,95)
						AND (@lDate BETWEEN ES.FromDate AND ES.ToDate) AND ES.IsHoliday=1)  
				BEGIN
					SET @rStatus = 'H'	
					RETURN @rStatus	
				END
			END
			 
		END
		 
	END
	  if @EmpSecondWeekOffRule = 1 
	BEGIN	 
		 if(@lWeekOff = @lWeekDay2)
			BEGIN
				--Set @rStatus = 'W'
				if(@rDateOfJoining  > @rAttendanceDate)
				BEGIN 
					 Set @rStatus = 'NA'
				END
				ELSE
				BEGIN
					 Set @rStatus = 'W'
				END	
				if(@rStatus !='W')	
				BEGIN	
					if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=1)
					BEGIN 
						SET @rStatus = 'P'
					END
						if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=0)
					BEGIN 						
						SET @rStatus = 'A'
					END
				END

					IF EXISTS(SELECT 1 from  sHrm.tLeave where   @rAttendanceDate BETWEEN FromDate AND ToDate AND  OrgId = @rOrgId AND EmployeeId = @rEmployeeId AND BatchId =@rBatchId) 
					 BEGIN
							if(@rStatus !='W')	
							BEGIN
								SET @rStatus = (Select Distinct case when l.LeavePeriodId=1 then LTM.Code else 'HD-'+LTM.Code end from sHrm.tLeaveTypeMaster LTM INNER JOIN sHrm.tLeave l On LTM.Id= l.LeaveTypeId AND l.StatusId=550 where  (@lDate BETWEEN L.FromDate AND L.ToDate ) AND L.OrgId = @rOrgid AND L.EmployeeId = @rEmployeeId AND L.BatchId =@rBatchid)
							END
							BEGIN
								SET @rStatus = (Select Distinct  'W-'+LTM.Code from sHrm.tLeaveTypeMaster LTM INNER JOIN sHrm.tLeave l On LTM.Id= l.LeaveTypeId AND l.StatusId=550 where  (@lDate BETWEEN L.FromDate AND L.ToDate ) AND L.OrgId = @rOrgid AND L.EmployeeId = @rEmployeeId AND L.BatchId =@rBatchid)
							END
							IF(@rStatus IS NULL)
							BEGIN
								IF Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=1)
								BEGIN 
									SET @rStatus = 'P'
									RETURN @rStatus
								END
								IF Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=0)
								BEGIN 						
									SET @rStatus = 'A'
									RETURN @rStatus
								END
							END
							ELSE
							BEGIN
								RETURN @rStatus
							END																
					 END
					IF   EXISTS(SELECT 1 FROM sActivity.tEventSchedule ES INNER JOIN  sActivity.tEventAssign EA ON EA.EventScheduleId=ES.Id
						INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id=EA.SourceId 
						WHERE ES.BatchId = @rBatchId AND ((SourceId=@rDepartmentId) OR (@rDepartmentId=0)) 
						AND SourceTypeId in (2004, 3,95)
						AND (@lDate BETWEEN ES.FromDate AND ES.ToDate) AND ES.IsHoliday=1)  
					 BEGIN
						 SET @rStatus = 'H'	
						 RETURN @rStatus		
					 END			
			END
		 
	END
	Else if @EmpSecondWeekOffRule = 2 
	BEGIN
	 
		IF @WeekNumber = 2 or @WeekNumber = 4 
		BEGIN
			if(@lWeekOff = @lWeekDay2)
			BEGIN
				--Set @rStatus = 'W'
				if(@rDateOfJoining  > @rAttendanceDate)
				BEGIN 
					 Set @rStatus = 'NA'
				END
				ELSE
				BEGIN
					 Set @rStatus = 'W'
				END
				if(@rStatus !='W')	
				BEGIN
					if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=1)
					BEGIN 
						SET @rStatus = 'P'
					END
					if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=0)
					BEGIN 
						SET @rStatus = 'A'
					END
				END
					IF EXISTS(SELECT 1 from  sHrm.tLeave where   @rAttendanceDate BETWEEN FromDate AND ToDate AND  OrgId = @rOrgId AND EmployeeId = @rEmployeeId AND BatchId =@rBatchId) 
					 BEGIN
							if(@rStatus !='W')	
							BEGIN
								SET @rStatus = (Select Distinct case when l.LeavePeriodId=1 then LTM.Code else 'HD-'+LTM.Code end from sHrm.tLeaveTypeMaster LTM INNER JOIN sHrm.tLeave l On LTM.Id= l.LeaveTypeId AND l.StatusId=550 where  (@lDate BETWEEN L.FromDate AND L.ToDate ) AND L.OrgId = @rOrgid AND L.EmployeeId = @rEmployeeId AND L.BatchId =@rBatchid)
							END
							ELSE
							BEGIN
								SET @rStatus = (Select Distinct  'W-'+LTM.Code from sHrm.tLeaveTypeMaster LTM INNER JOIN sHrm.tLeave l On LTM.Id= l.LeaveTypeId AND l.StatusId=550 where  (@lDate BETWEEN L.FromDate AND L.ToDate ) AND L.OrgId = @rOrgid AND L.EmployeeId = @rEmployeeId AND L.BatchId =@rBatchid)
							END

							IF(@rStatus IS NULL)
							BEGIN
								IF Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=1)
								BEGIN 
									SET @rStatus = 'P'
									RETURN @rStatus
								END
								IF Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=0)
								BEGIN 						
									SET @rStatus = 'A'
									RETURN @rStatus
								END
							END
							ELSE
							BEGIN
								RETURN @rStatus
							END																
					 END
					
					IF   EXISTS(SELECT 1 FROM sActivity.tEventSchedule ES INNER JOIN  sActivity.tEventAssign EA ON EA.EventScheduleId=ES.Id
						INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id=EA.SourceId WHERE ES.BatchId = @rBatchId AND ((SourceId=@rDepartmentId) OR (@rDepartmentId=0)) 
						AND SourceTypeId in (2004, 3,95)
						AND (@lDate BETWEEN ES.FromDate AND ES.ToDate) AND ES.IsHoliday=1)  
				BEGIN
					SET @rStatus = 'H'	
					RETURN @rStatus	
				END
				
			END
			 
		END
		 
	END
	else if @EmpSecondWeekOffRule = 3
	BEGIN
		if @WeekNumber = 1 or @WeekNumber = 3 
		BEGIN
			if(@lWeekOff = @lWeekDay2)
			BEGIN
				--Set @rStatus = 'W'
				if(@rDateOfJoining  > @rAttendanceDate)
				BEGIN 
					 Set @rStatus = 'NA'
				END
				ELSE
				BEGIN
					 Set @rStatus = 'W'
				END	
			
			
				IF(@rStatus !='W')	
				BEGIN
					if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=1)
					BEGIN 
						SET @rStatus = 'P'
					END
					 if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=0)
					BEGIN 
						SET @rStatus = 'A'
					END
				END
					IF EXISTS(SELECT 1 from  sHrm.tLeave where   @rAttendanceDate BETWEEN FromDate AND ToDate AND  OrgId = @rOrgId AND EmployeeId = @rEmployeeId AND BatchId =@rBatchId) 
					 BEGIN
							IF(@rStatus !='W')	
							BEGIN
								SET @rStatus = (Select Distinct case when l.LeavePeriodId=1 then LTM.Code else 'HD-'+LTM.Code end from sHrm.tLeaveTypeMaster LTM INNER JOIN sHrm.tLeave l On LTM.Id= l.LeaveTypeId AND l.StatusId=550 where  (@lDate BETWEEN L.FromDate AND L.ToDate ) AND L.OrgId = @rOrgid AND L.EmployeeId = @rEmployeeId AND L.BatchId =@rBatchid)
							END
							ELSE
							BEGIN
								SET @rStatus = (Select Distinct  'W-'+LTM.Code from sHrm.tLeaveTypeMaster LTM INNER JOIN sHrm.tLeave l On LTM.Id= l.LeaveTypeId AND l.StatusId=550 where  (@lDate BETWEEN L.FromDate AND L.ToDate ) AND L.OrgId = @rOrgid AND L.EmployeeId = @rEmployeeId AND L.BatchId =@rBatchid)
							END
							IF(@rStatus IS NULL)
							BEGIN
								IF Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=1)
								BEGIN 
									SET @rStatus = 'P'
									RETURN @rStatus
								END
								IF Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=0)
								BEGIN 						
									SET @rStatus = 'A'
									RETURN @rStatus
								END
							END
							ELSE
							BEGIN
								RETURN @rStatus
							END																
					 END
					
					IF   EXISTS(SELECT 1 FROM sActivity.tEventSchedule ES INNER JOIN  sActivity.tEventAssign EA ON EA.EventScheduleId=ES.Id
						INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id=EA.SourceId WHERE ES.BatchId = @rBatchId AND ((SourceId=@rDepartmentId) OR (@rDepartmentId=0)) 
						AND SourceTypeId in (2004, 3)
						AND (@lDate BETWEEN ES.FromDate AND ES.ToDate) AND ES.IsHoliday=1)  
				BEGIN
					SET @rStatus = 'H'	
					RETURN @rStatus	
				END
				
			END
			 
		END
		 
	END
	else if @EmpSecondWeekOffRule = 4
	BEGIN
		 
		if @WeekNumber = 1 or @WeekNumber = 3 or @WeekNumber = 5
		BEGIN
			if(@lWeekOff = @lWeekDay2)
			BEGIN
				--Set @rStatus = 'W'
				if(@rDateOfJoining  > @rAttendanceDate)
				BEGIN 
					 Set @rStatus = 'NA'
				END
				ELSE
				BEGIN
					 Set @rStatus = 'W'
				END			
				IF(@rStatus !='W')	
				BEGIN
					if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=1)
					BEGIN 
						SET @rStatus = 'P'
					END
					 if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=0)
					BEGIN 
						SET @rStatus = 'A'
					END
				END
					IF EXISTS(SELECT 1 from  sHrm.tLeave where   @rAttendanceDate BETWEEN FromDate AND ToDate AND  OrgId = @rOrgId AND EmployeeId = @rEmployeeId AND BatchId =@rBatchId) 
					 BEGIN
							IF(@rStatus !='W')	
							BEGIN
								SET @rStatus = (Select Distinct case when l.LeavePeriodId=1 then LTM.Code else 'HD-'+LTM.Code end from sHrm.tLeaveTypeMaster LTM INNER JOIN sHrm.tLeave l On LTM.Id= l.LeaveTypeId AND l.StatusId=550 where  (@lDate BETWEEN L.FromDate AND L.ToDate ) AND L.OrgId = @rOrgid AND L.EmployeeId = @rEmployeeId AND L.BatchId =@rBatchid)
							END
							BEGIN
								SET @rStatus = (Select Distinct  'W-'+LTM.Code from sHrm.tLeaveTypeMaster LTM INNER JOIN sHrm.tLeave l On LTM.Id= l.LeaveTypeId AND l.StatusId=550 where  (@lDate BETWEEN L.FromDate AND L.ToDate ) AND L.OrgId = @rOrgid AND L.EmployeeId = @rEmployeeId AND L.BatchId =@rBatchid)
							END
							IF(@rStatus IS NULL)
							BEGIN
								IF Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=1)
								BEGIN 
									SET @rStatus = 'P'
									RETURN @rStatus
								END
								IF Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=0)
								BEGIN 						
									SET @rStatus = 'A'
									RETURN @rStatus
								END
							END
							ELSE
							BEGIN
								RETURN @rStatus
							END																
					 END
					IF   EXISTS(SELECT 1 FROM sActivity.tEventSchedule ES INNER JOIN  sActivity.tEventAssign EA ON EA.EventScheduleId=ES.Id
						INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id=EA.SourceId WHERE ES.BatchId = @rBatchId AND ((SourceId=@rDepartmentId) OR (@rDepartmentId=0)) 
						AND SourceTypeId in (2004, 3)
						AND (@lDate BETWEEN ES.FromDate AND ES.ToDate) AND ES.IsHoliday=1)  
				BEGIN
					SET @rStatus = 'H'	
					RETURN @rStatus	
				END
			END
		END
		
	END
	else if @EmpSecondWeekOffRule = 5
	BEGIN
		 
		if @WeekNumber = 2 or @WeekNumber = 3 
		BEGIN
			if(@lWeekOff = @lWeekDay2)
			BEGIN
				--Set @rStatus = 'W'
				if(@rDateOfJoining  > @rAttendanceDate)
				BEGIN 
					 Set @rStatus = 'NA'
				END
				ELSE
				BEGIN
					 Set @rStatus = 'W'
				END			
				IF(@rStatus !='W')	
				BEGIN
					if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=1)
					BEGIN 
						SET @rStatus = 'P'
					END
					 if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=0)
					BEGIN 
						SET @rStatus = 'A'
					END
				END
					IF EXISTS(SELECT 1 from  sHrm.tLeave where   @rAttendanceDate BETWEEN FromDate AND ToDate AND  OrgId = @rOrgId AND EmployeeId = @rEmployeeId AND BatchId =@rBatchId) 
					 BEGIN
							IF(@rStatus !='W')	
							BEGIN
								SET @rStatus = (Select Distinct case when l.LeavePeriodId=1 then LTM.Code else 'HD-'+LTM.Code end from sHrm.tLeaveTypeMaster LTM INNER JOIN sHrm.tLeave l On LTM.Id= l.LeaveTypeId AND l.StatusId=550 where  (@lDate BETWEEN L.FromDate AND L.ToDate ) AND L.OrgId = @rOrgid AND L.EmployeeId = @rEmployeeId AND L.BatchId =@rBatchid)
							END
							BEGIN
								SET @rStatus = (Select Distinct  'W-'+LTM.Code from sHrm.tLeaveTypeMaster LTM INNER JOIN sHrm.tLeave l On LTM.Id= l.LeaveTypeId AND l.StatusId=550 where  (@lDate BETWEEN L.FromDate AND L.ToDate ) AND L.OrgId = @rOrgid AND L.EmployeeId = @rEmployeeId AND L.BatchId =@rBatchid)
							END
							IF(@rStatus IS NULL)
							BEGIN
								IF Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=1)
								BEGIN 
									SET @rStatus = 'P'
									RETURN @rStatus
								END
								IF Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=0)
								BEGIN 						
									SET @rStatus = 'A'
									RETURN @rStatus
								END
							END
							ELSE
							BEGIN
								RETURN @rStatus
							END																
					 END
					IF   EXISTS(SELECT 1 FROM sActivity.tEventSchedule ES INNER JOIN  sActivity.tEventAssign EA ON EA.EventScheduleId=ES.Id
						INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id=EA.SourceId WHERE ES.BatchId = @rBatchId AND ((SourceId=@rDepartmentId) OR (@rDepartmentId=0)) 
						AND SourceTypeId in (2004, 3)
						AND (@lDate BETWEEN ES.FromDate AND ES.ToDate) AND ES.IsHoliday=1)  
				BEGIN
					SET @rStatus = 'H'	
					RETURN @rStatus	
				END
			END
		END
		
	END
	else if @EmpSecondWeekOffRule = 6
	BEGIN
		 
		if @WeekNumber = 1 
		BEGIN
			if(@lWeekOff = @lWeekDay2)
			BEGIN
				--Set @rStatus = 'W'
				if(@rDateOfJoining  > @rAttendanceDate)
				BEGIN 
					 Set @rStatus = 'NA'
				END
				ELSE
				BEGIN
					 Set @rStatus = 'W'
				END			
				IF(@rStatus !='W')	
				BEGIN
					if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=1)
					BEGIN 
						SET @rStatus = 'P'
					END
					 if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=0)
					BEGIN 
						SET @rStatus = 'A'
					END
				END
					IF EXISTS(SELECT 1 from  sHrm.tLeave where   @rAttendanceDate BETWEEN FromDate AND ToDate AND  OrgId = @rOrgId AND EmployeeId = @rEmployeeId AND BatchId =@rBatchId) 
					 BEGIN
							IF(@rStatus !='W')	
							BEGIN
								SET @rStatus = (Select Distinct case when l.LeavePeriodId=1 then LTM.Code else 'HD-'+LTM.Code end from sHrm.tLeaveTypeMaster LTM INNER JOIN sHrm.tLeave l On LTM.Id= l.LeaveTypeId AND l.StatusId=550 where  (@lDate BETWEEN L.FromDate AND L.ToDate ) AND L.OrgId = @rOrgid AND L.EmployeeId = @rEmployeeId AND L.BatchId =@rBatchid)
							END
							BEGIN
								SET @rStatus = (Select Distinct  'W-'+LTM.Code from sHrm.tLeaveTypeMaster LTM INNER JOIN sHrm.tLeave l On LTM.Id= l.LeaveTypeId AND l.StatusId=550 where  (@lDate BETWEEN L.FromDate AND L.ToDate ) AND L.OrgId = @rOrgid AND L.EmployeeId = @rEmployeeId AND L.BatchId =@rBatchid)
							END
							IF(@rStatus IS NULL)
							BEGIN
								IF Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=1)
								BEGIN 
									SET @rStatus = 'P'
									RETURN @rStatus
								END
								IF Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=0)
								BEGIN 						
									SET @rStatus = 'A'
									RETURN @rStatus
								END
							END
							ELSE
							BEGIN
								RETURN @rStatus
							END																
					 END
					IF   EXISTS(SELECT 1 FROM sActivity.tEventSchedule ES INNER JOIN  sActivity.tEventAssign EA ON EA.EventScheduleId=ES.Id
						INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id=EA.SourceId WHERE ES.BatchId = @rBatchId AND ((SourceId=@rDepartmentId) OR (@rDepartmentId=0)) 
						AND SourceTypeId in (2004, 3)
						AND (@lDate BETWEEN ES.FromDate AND ES.ToDate) AND ES.IsHoliday=1)  
				BEGIN
					SET @rStatus = 'H'	
					RETURN @rStatus	
				END
			END
		END
		
	END
	else if @EmpSecondWeekOffRule = 7
	BEGIN
		 
		if @WeekNumber =2
		BEGIN
			if(@lWeekOff = @lWeekDay2)
			BEGIN
				--Set @rStatus = 'W'
				if(@rDateOfJoining  > @rAttendanceDate)
				BEGIN 
					 Set @rStatus = 'NA'
				END
				ELSE
				BEGIN
					 Set @rStatus = 'W'
				END			
				IF(@rStatus !='W')	
				BEGIN
					if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=1)
					BEGIN 
						SET @rStatus = 'P'
					END
					 if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=0)
					BEGIN 
						SET @rStatus = 'A'
					END
				END
					IF EXISTS(SELECT 1 from  sHrm.tLeave where   @rAttendanceDate BETWEEN FromDate AND ToDate AND  OrgId = @rOrgId AND EmployeeId = @rEmployeeId AND BatchId =@rBatchId) 
					 BEGIN
							IF(@rStatus !='W')	
							BEGIN
								SET @rStatus = (Select Distinct case when l.LeavePeriodId=1 then LTM.Code else 'HD-'+LTM.Code end from sHrm.tLeaveTypeMaster LTM INNER JOIN sHrm.tLeave l On LTM.Id= l.LeaveTypeId AND l.StatusId=550 where  (@lDate BETWEEN L.FromDate AND L.ToDate ) AND L.OrgId = @rOrgid AND L.EmployeeId = @rEmployeeId AND L.BatchId =@rBatchid)
							END
							BEGIN
								SET @rStatus = (Select Distinct  'W-'+LTM.Code from sHrm.tLeaveTypeMaster LTM INNER JOIN sHrm.tLeave l On LTM.Id= l.LeaveTypeId AND l.StatusId=550 where  (@lDate BETWEEN L.FromDate AND L.ToDate ) AND L.OrgId = @rOrgid AND L.EmployeeId = @rEmployeeId AND L.BatchId =@rBatchid)
							END
							IF(@rStatus IS NULL)
							BEGIN
								IF Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=1)
								BEGIN 
									SET @rStatus = 'P'
									RETURN @rStatus
								END
								IF Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=0)
								BEGIN 						
									SET @rStatus = 'A'
									RETURN @rStatus
								END
							END
							ELSE
							BEGIN
								RETURN @rStatus
							END																
					 END
					IF   EXISTS(SELECT 1 FROM sActivity.tEventSchedule ES INNER JOIN  sActivity.tEventAssign EA ON EA.EventScheduleId=ES.Id
						INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id=EA.SourceId WHERE ES.BatchId = @rBatchId AND ((SourceId=@rDepartmentId) OR (@rDepartmentId=0)) 
						AND SourceTypeId in (2004, 3)
						AND (@lDate BETWEEN ES.FromDate AND ES.ToDate) AND ES.IsHoliday=1)  
				BEGIN
					SET @rStatus = 'H'	
					RETURN @rStatus	
				END
			END
		END
		
	END
	else if @EmpSecondWeekOffRule = 8
	BEGIN
		 
		if  @WeekNumber = 3 
		BEGIN
			if(@lWeekOff = @lWeekDay2)
			BEGIN
				--Set @rStatus = 'W'
				if(@rDateOfJoining  > @rAttendanceDate)
				BEGIN 
					 Set @rStatus = 'NA'
				END
				ELSE
				BEGIN
					 Set @rStatus = 'W'
				END			
				IF(@rStatus !='W')	
				BEGIN
					if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=1)
					BEGIN 
						SET @rStatus = 'P'
					END
					 if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=0)
					BEGIN 
						SET @rStatus = 'A'
					END
				END
					IF EXISTS(SELECT 1 from  sHrm.tLeave where   @rAttendanceDate BETWEEN FromDate AND ToDate AND  OrgId = @rOrgId AND EmployeeId = @rEmployeeId AND BatchId =@rBatchId) 
					 BEGIN
							IF(@rStatus !='W')	
							BEGIN
								SET @rStatus = (Select Distinct case when l.LeavePeriodId=1 then LTM.Code else 'HD-'+LTM.Code end from sHrm.tLeaveTypeMaster LTM INNER JOIN sHrm.tLeave l On LTM.Id= l.LeaveTypeId AND l.StatusId=550 where  (@lDate BETWEEN L.FromDate AND L.ToDate ) AND L.OrgId = @rOrgid AND L.EmployeeId = @rEmployeeId AND L.BatchId =@rBatchid)
							END
							BEGIN
								SET @rStatus = (Select Distinct  'W-'+LTM.Code from sHrm.tLeaveTypeMaster LTM INNER JOIN sHrm.tLeave l On LTM.Id= l.LeaveTypeId AND l.StatusId=550 where  (@lDate BETWEEN L.FromDate AND L.ToDate ) AND L.OrgId = @rOrgid AND L.EmployeeId = @rEmployeeId AND L.BatchId =@rBatchid)
							END
							IF(@rStatus IS NULL)
							BEGIN
								IF Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=1)
								BEGIN 
									SET @rStatus = 'P'
									RETURN @rStatus
								END
								IF Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=0)
								BEGIN 						
									SET @rStatus = 'A'
									RETURN @rStatus
								END
							END
							ELSE
							BEGIN
								RETURN @rStatus
							END																
					 END
					IF   EXISTS(SELECT 1 FROM sActivity.tEventSchedule ES INNER JOIN  sActivity.tEventAssign EA ON EA.EventScheduleId=ES.Id
						INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id=EA.SourceId WHERE ES.BatchId = @rBatchId AND ((SourceId=@rDepartmentId) OR (@rDepartmentId=0)) 
						AND SourceTypeId in (2004, 3)
						AND (@lDate BETWEEN ES.FromDate AND ES.ToDate) AND ES.IsHoliday=1)  
				BEGIN
					SET @rStatus = 'H'	
					RETURN @rStatus	
				END
			END
		END
		
	END
	else if @EmpSecondWeekOffRule = 9
	BEGIN
		 
		if @WeekNumber = 4
		BEGIN
			if(@lWeekOff = @lWeekDay2)
			BEGIN
				--Set @rStatus = 'W'
				if(@rDateOfJoining  > @rAttendanceDate)
				BEGIN 
					 Set @rStatus = 'NA'
				END
				ELSE
				BEGIN
					 Set @rStatus = 'W'
				END			
				IF(@rStatus !='W')	
				BEGIN
					if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=1)
					BEGIN 
						SET @rStatus = 'P'
					END
					 if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=0)
					BEGIN 
						SET @rStatus = 'A'
					END
				END
					IF EXISTS(SELECT 1 from  sHrm.tLeave where   @rAttendanceDate BETWEEN FromDate AND ToDate AND  OrgId = @rOrgId AND EmployeeId = @rEmployeeId AND BatchId =@rBatchId) 
					 BEGIN
							IF(@rStatus !='W')	
							BEGIN
								SET @rStatus = (Select Distinct case when l.LeavePeriodId=1 then LTM.Code else 'HD-'+LTM.Code end from sHrm.tLeaveTypeMaster LTM INNER JOIN sHrm.tLeave l On LTM.Id= l.LeaveTypeId AND l.StatusId=550 where  (@lDate BETWEEN L.FromDate AND L.ToDate ) AND L.OrgId = @rOrgid AND L.EmployeeId = @rEmployeeId AND L.BatchId =@rBatchid)
							END
							BEGIN
								SET @rStatus = (Select Distinct  'W-'+LTM.Code from sHrm.tLeaveTypeMaster LTM INNER JOIN sHrm.tLeave l On LTM.Id= l.LeaveTypeId AND l.StatusId=550 where  (@lDate BETWEEN L.FromDate AND L.ToDate ) AND L.OrgId = @rOrgid AND L.EmployeeId = @rEmployeeId AND L.BatchId =@rBatchid)
							END
							IF(@rStatus IS NULL)
							BEGIN
								IF Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=1)
								BEGIN 
									SET @rStatus = 'P'
									RETURN @rStatus
								END
								IF Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=0)
								BEGIN 						
									SET @rStatus = 'A'
									RETURN @rStatus
								END
							END
							ELSE
							BEGIN
								RETURN @rStatus
							END																
					 END
					IF   EXISTS(SELECT 1 FROM sActivity.tEventSchedule ES INNER JOIN  sActivity.tEventAssign EA ON EA.EventScheduleId=ES.Id
						INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id=EA.SourceId WHERE ES.BatchId = @rBatchId AND ((SourceId=@rDepartmentId) OR (@rDepartmentId=0)) 
						AND SourceTypeId in (2004, 3)
						AND (@lDate BETWEEN ES.FromDate AND ES.ToDate) AND ES.IsHoliday=1)  
				BEGIN
					SET @rStatus = 'H'	
					RETURN @rStatus	
				END
			END
		END
		
	END
 
IF EXISTS(SELECT 1 from  sHrm.tLeave where   @rAttendanceDate BETWEEN FromDate AND ToDate AND  OrgId = @rOrgId AND EmployeeId = @rEmployeeId AND BatchId =@rBatchId) 
BEGIN
	SET @rStatus = (Select Distinct case when l.LeavePeriodId=1 then LTM.Code else 'HD-'+LTM.Code end from sHrm.tLeaveTypeMaster LTM INNER JOIN sHrm.tLeave l On LTM.Id= l.LeaveTypeId AND l.StatusId=550 where  (@lDate BETWEEN L.FromDate AND L.ToDate ) AND L.OrgId = @rOrgid AND L.EmployeeId = @rEmployeeId AND L.BatchId =@rBatchid)
	IF(@rStatus IS NULL)
	BEGIN
		IF Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=1)
		BEGIN 
			SET @rStatus = 'P'
			RETURN @rStatus
		END
		IF Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=0)
		BEGIN 						
			SET @rStatus = 'A'
			RETURN @rStatus
		END
	END
	ELSE
	BEGIN
		RETURN @rStatus
	END																
END
--It Take only department assign Holiday maitisid--27362 Nimesh
--IF   EXISTS(SELECT 1 FROM sActivity.tEventSchedule ES INNER JOIN  sActivity.tEventAssign EA ON EA.EventScheduleId=ES.Id
--INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id=EA.SourceId 
--WHERE ES.BatchId = @rBatchId AND ((SourceId=@rDepartmentId) OR (@rDepartmentId=0)) 
--AND SourceTypeId in (2004, 3,95)
--AND (@lDate BETWEEN ES.FromDate AND ES.ToDate) AND ES.IsHoliday=1)  
--BEGIN
--	SET @rStatus = 'H'	
--	RETURN @rStatus		
--END

--It Take assign Holiday acording to SourcetypeId
IF   EXISTS(SELECT 1 FROM sActivity.tEventSchedule ES INNER JOIN  sActivity.tEventAssign EA ON EA.EventScheduleId=ES.Id
WHERE ES.BatchId = @rBatchId
	AND (((SourceId=@rEmployeeId OR @rEmployeeId=0) AND SourceTypeId in (95)) OR ((SourceId=@rDepartmentId OR @rDepartmentId=0) AND SourceTypeId in (2004, 3)))
	-- AND ((SourceId=@rEmployeeId) OR (@rEmployeeId=0)) 
	--AND SourceTypeId in (95)
	AND (@lDate BETWEEN ES.FromDate AND ES.ToDate) AND ES.IsHoliday=1)  
BEGIN
	SET @rStatus = 'H'	
	RETURN @rStatus	
END



 if(@rDateOfJoining IS NOT NULL AND @rDateOfLeaving IS NOT NULL)
	Set @ldate = @rAttendanceDate	
	if ISDATE(@ldate)=1	
	BEGIN
	
		if(@rDateOfJoining  > @rAttendanceDate)
		BEGIN
			SET @rStatus = 'NA'			
			RETURN @rStatus
		END
		IF(@rDateOfLeaving<>'')
		BEGIN
			if(@rDateOfLeaving <= @rAttendanceDate)
			BEGIN
				SET @rStatus='L'
				RETURN @rStatus
			END
		END
	END
	IF(@rStatus Is NULL)
	 SET @rStatus = ''
	RETURN @rStatus
	END
GO
PRINT N'Creating Function [sCommon].[f_GetCamelCase]...';


GO
CREATE FUNCTION sCommon.f_GetCamelCase(@str as varchar(1000))
RETURNS VARCHAR(1000) WITH EXECUTE AS CALLER
AS
BEGIN
DECLARE @bitval bit;
DECLARE @result varchar(1000);
DECLARE @i int;
DECLARE @j char(1);
SELECT @bitval = 1, @i=1, @result = '';
WHILE (@i <= len(@str))
SELECT @j= substring(@str,@i,1),
@result = @result + case when @bitval=1 then UPPER(@j) else LOWER(@j) end,
@bitval = case when @j like '[a-zA-Z]' then 0 else 1 end,
@i = @i +1
RETURN @result
END
GO
PRINT N'Altering Procedure [dbo].[pEmployeeMasterGet]...';


GO
 
 
ALTER PROCEDURE [dbo].[pEmployeeMasterGet]
@rOrgId int = 0,
 @rBuilder1 nvarchar(max)='',
 @rBuilder2 nvarchar(max)='',
 @rEmployeeStatusId int=0,
 @rEmployeeId bigint = 0,
 @rOrgGroupId int = 0	 
AS

BEGIN

declare @lBiometricDeviceMode nVarchar(100)
SELECT @lBiometricDeviceMode = CASE WHEN CS.ItemValue IS NULL THEN C.ItemValue ELSE CS.ItemValue END 
		FROM sConfig.tConfigurationMaster C
        INNER JOIN sConfig.tConfigurationLevelMaster CM ON CM.Id = C.ConfigurationLevelId
        LEFT JOIN sConfig.tConfigurationSetup CS ON CS.ConfigurationId = C.Id AND CS.SOURCEID= @rOrgGroupId
        WHERE  C.ItemKey = 'Biometric.BiometricDeviceMode'

if(@lBiometricDeviceMode='Offline')
Begin
	UPDATE sHrm.tEmployeeMaster SET PunchId = NULL
	--IF EXISTS (SELECT EM.PunchId FROM sHrm.tEmployeeMaster EM INNER JOIN sBiometric.BioDetailMapping BM ON BM.EmpID = EM.Id WHERE EM.PunchId is null)
	--BEGIN
	UPDATE EM
	SET
		PunchId = BM.EmpPunchID
	FROM
	    sHrm.tEmployeeMaster EM
		INNER JOIN sBiometric.BioDetailMapping AS BM
		ON BM.EmpID = EM.Id
		WHERE PunchId is null
	--END
End


	select EM.*,isnull(EM.FirstName,'') +' '+ isnull(EM.MiddleName,'') as 'FullName',
	(SELECT Title FROM sSetup.tOrganizationMaster WHERE Id = OrgID) AS OrganizationTitle
 from sHrm.tEmployeeMaster EM
 INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = EM.OrgID
	where PunchId is not null
	and (EM.OrgID = @rOrgId OR @rOrgId = 0)
	AND (EM.StatusId = @rEmployeeStatusId) OR (ISNULL(@rEmployeeStatusId,0)=0) 
	AND ISNULL(EM.IsOtherUser,0) = 0
	and (OM.OrgGroupId = @rOrgGroupId)
END
GO
PRINT N'Altering Procedure [sAcademic].[pTopicMasterAdd]...';


GO


ALTER PROCEDURE [sAcademic].[pTopicMasterAdd]
	 
        @rId int,
        @rNumber smallint,
        @rTitle nvarchar(100),
        @rSubjectId int,
        @rClassId int,
        @rOrgId smallint,
        @rCreatedUserId bigint
		--@rIsObsolete bit
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	IF(@rId = 0)	
	BEGIN
		If Exists(select Id from sAcademic.tTopicMaster where Title=@rTitle AND OrgId=@rOrgId AND ClassId=@rClassId AND SubjectId=@rSubjectId)
			BEGIN
			select -102 as Result
			RETURN
		END 
	
		If Exists(select Id from sAcademic.tTopicMaster where Number=@rNumber AND OrgId=@rOrgId AND ClassId=@rClassId AND SubjectId=@rSubjectId)
			BEGIN
			select -103 as Result
			RETURN
		END 
	END
	ELSE
	BEGIN
		If  Exists(select Id from sAcademic.tTopicMaster where Title=@rTitle AND OrgId=@rOrgId AND ClassId=@rClassId AND SubjectId=@rSubjectId AND Id<>@rId)
		Begin
			select -102 as Result
			RETURN
		End
		If  Exists(select Id from sAcademic.tTopicMaster where Number=@rNumber AND OrgId=@rOrgId AND ClassId=@rClassId AND SubjectId=@rSubjectId AND Id<>@rId)
		Begin
			select -103 as Result
			RETURN
		End

	END
	
	
	
	 BEGIN TRANSACTION	
	 DECLARE @lNextNumber BIGINT 

	IF(@rId = 0)	
	BEGIN
		
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sAcademic.tTopicMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	INSERT INTO sAcademic.tTopicMaster
		(
			Id,
			Number,
			Title,
			SubjectId,
			ClassId,
			OrgId,
			CreatedUserId,
			CreatedDateTime
			----added by megha for 0024270
			--IsObsolete
		)
	VALUES
		(
			@lNextNumber,
			@rNumber,
			@rTitle,
			@rSubjectId,
			@rClassId,
			@rOrgId,
			@rCreatedUserId,
			sCommon.fGetDate()
			--@rIsObsolete
		)
		    SELECT 1 AS Result
	END	 

ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE  sAcademic.tTopicMaster
	    SET
			Number=@rNumber,
			Title=@rTitle,
			SubjectId=@rSubjectId,
			ClassId=@rClassId,
			OrgId=@rOrgId,
			UpdatedUserId=@rCreatedUserId,
			UpdatedDateTime=sCommon.fGetDate()
			--IsObsolete = @rIsObsolete
	      
	      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 [sAcademic].[pTopicMasterGet]...';


GO
ALTER PROCEDURE [sAcademic].[pTopicMasterGet]

	 @rId int,
	 @rOrgId smallint,
	 @rClassId int,
	 @rSubjectId int,
	 @rEmployeeId bigint,
	 @rSourceTypeId smallint = 0
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
	IF(@rSourceTypeId = 0)
	BEGIN
		SELECT 
				DISTINCT TM.Id,
				TM.Number,
				TM.Title,
				TM.OrgId,
				TM.ClassId,
				TM.SubjectId,
				TM.CreatedUserId,
				TM.CreatedDateTime,
				CM.DisplayTitle AS ClassName,
				SM.Title AS SubjectName,
				CM.OrderIndex,
				SM.OrderIndex
				--added by megha for 0024270
				--ISNULL(TM.IsObsolete,0) AS IsObsolete
		FROM 
				sAcademic.tTopicMaster TM
				INNER JOIN sSetup.tClassMaster CM ON CM.Id = TM.ClassId
				INNER JOIN sSetup.tSubjectMaster SM ON SM.Id = TM.SubjectId
				LEFT JOIN sAcademic.vTeacherSubjectDivision vTSD ON vTSD.ClassId = TM.ClassId 			
				--AND vTSD.SubjectId = TM.SubjectId 
				AND vTSD.EmployeeId = @rEmployeeId
		WHERE 
			(TM.OrgId=@rOrgId)
			AND ((TM.Id = @rId) OR (@rId = 0))
			AND ((TM.ClassId = @rClassId) OR (@rClassId = 0))
			AND ((TM.SubjectId = @rSubjectId) OR (@rSubjectId = 0))
			--AND ((vTSD.EmployeeId = @rEmployeeId) OR (vTSD.EmployeeId = 0))
			--ORDER BY CM.OrderIndex
		ORDER BY CM.OrderIndex,SM.OrderIndex,TM.Number ASC
	END
	ELSE IF (@rSourceTypeId = 95)
	BEGIN
		SELECT 
				DISTINCT TM.Id,
				TM.Number,
				TM.Title,
				TM.OrgId,
				TM.ClassId,
				TM.SubjectId,
				TM.CreatedUserId,
				TM.CreatedDateTime,
				CM.DisplayTitle AS ClassName,
				SM.Title AS SubjectName,
				CM.OrderIndex,
				SM.OrderIndex
				--ISNULL(TM.IsObsolete,0) AS IsObsolete
		FROM 
				sAcademic.tTopicMaster TM
				INNER JOIN sSetup.tClassMaster CM ON CM.Id = TM.ClassId
				INNER JOIN sSetup.tSubjectMaster SM ON SM.Id = TM.SubjectId
				INNER JOIN sAcademic.vTeacherSubjectDivision vTSD ON vTSD.ClassId = TM.ClassId AND vTSD.SubjectId = TM.SubjectId 
				AND vTSD.EmployeeId = @rEmployeeId
		WHERE 
			(TM.OrgId=@rOrgId)
			AND ((TM.Id = @rId) OR (@rId = 0))
			AND ((TM.ClassId = @rClassId) OR (@rClassId = 0))
			AND ((TM.SubjectId = @rSubjectId) OR (@rSubjectId = 0))
		ORDER BY CM.OrderIndex,SM.OrderIndex,TM.Number ASC
	END
END
GO
PRINT N'Altering Procedure [sAlert].[pEmployeeBiometricAbsentTimeGet]...';


GO


ALTER PROCEDURE [sAlert].[pEmployeeBiometricAbsentTimeGet]
	@rOrgId int,
	@rOrgGroupId int,
	@rTemplate nvarchar(max),
	@rSubject nvarchar(100),
	@rIntervalTime int=0,
	@rToDateTime dateTime=null,
	@rFromDateTime DateTime=null
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY	
		BEGIN TRANSACTION 
			declare  @lBatchID INT
			SELECT @lBatchID = Id from sSetup.tBatchMaster Where OrgId = @rOrgId AND IsActive = 1
			if object_id('tempdb..#tShift') is not null
			BEGIN
				DROP TABLE #tShift
			END
			CREATE TABLE #tShift(
					ShiftCode int NOT NULL
				)

			insert #tShift
			Select 
				ShiftCode
			FROM sBiometric.tShiftMasterCloud
			where  ((OrgGroupId = @rOrgGroupId) OR (@rOrgGroupId=0))  
			--AND IsOutTimeAlertTime=1
			--AND CAST(DATEADD(MINUTE,AlterGraceTime,StartTime) AS Time)<=cast([sCommon].[fGetDate]() as Time)
			--AND CAST(DATEADD(MINUTE,AlterGraceTime,StartTime) AS Time)>=cast(DATEADD(MINUTE,-@rIntervalTime,[sCommon].[fGetDate]()) as Time)
			AND CAST(DATEADD(MINUTE,AlterGraceTime,StartTime) AS Time)<=cast(@rToDateTime as Time)
			AND CAST(DATEADD(MINUTE,AlterGraceTime,StartTime) AS Time)>=cast(@rFromDateTime as Time)

			--select * from #tShift
			declare @lcount int=(SELECT COUNT(ShiftCode) FROM #tShift)

			if object_id('tempdb..#tTable') is not null
			BEGIN
				DROP TABLE #tTable
			END
			CREATE TABLE #tTable(
						SourceId bigint NOT NULL,
						In_Out_Time [datetime] NOT NULL,
						SourceTypeId int NOT NULL
					)

			if(@lcount>0)
			BEGIN
				insert into #tTable
				select SourceId,MIN(In_Out_Time),SourceTypeId
				from [sBiometric].[tCloudTransactionData] CDT
				inner join #tShift tempShift ON tempShift.ShiftCode=CDT.ShiftCode 
				WHERE Attn_Dt=CONVERT(date,[sCommon].[fGetDate]())  AND SourceTypeId=95 Group by SourceId,SourceTypeId
			END
			
			
			--select * from #tTable
			select EM.MobileNumber AS MobileNo,	
					EM.CompanyEmail AS EmailId,
					replace (
					replace(@rTemplate,'[EmployeeName]',EM.EmployeeName),
					'[AbsentDate]',ISNULL(Convert(varchar,[sCommon].[fGetDate](),103),''))
					 AS MsgText,
					@rSubject AS Subject,
					95 AS ReceiverSourceTypeId,
					EM.EmployeeId AS ReceiverSourceId,
					EM.EmployeeName AS EmployeeName,
					EM.Code AS Code,
					ISNULL(EC.WhatsAppContactNo,'') AS WhatsAppContactNo,
					95 AS SourceTypeId,
					EM.EmployeeId AS SourceId,
					EM.OrgId,
					OM.DisplayTitle AS OrganizationTitle
				FROM  
					sHrm.vEmployeeCommonDetail EM 
					Inner Join  [sHrm].[tEmployeeMaster] E on EM.EmployeeId=E.Id
					INNER JOIN #tShift tempshift ON tempshift.ShiftCode=E.ShiftId
					LEFT JOIN #tTable temp ON  temp.SourceId=EM.EmployeeId
					LEFT JOIN sHrm.tEmployeeCommunications EC ON EC.EmployeeId = EM.EmployeeId
					LEFT JOIN sSetup.tOrganizationMaster OM ON EM.OrgID = OM.Id
				where 
				EM.OrgID =@rOrgId
				AND temp.In_Out_Time is null
				AND ( [sHrm].[fWeekHOffGetBio](EM.EmployeeId , YEAR([sCommon].[fGetDate]()) ,MONTH([sCommon].[fGetDate]()) ,DAY([sCommon].[fGetDate]()),@lBatchID ,OrganizationDepartmentId ,@rOrgId )<>'W')
				AND ( [sHrm].[fWeekHOffGetBio](EM.EmployeeId , YEAR([sCommon].[fGetDate]()) ,MONTH([sCommon].[fGetDate]()) ,DAY([sCommon].[fGetDate]()),@lBatchID ,OrganizationDepartmentId ,@rOrgId )<> 'H')
			DROP TABLE #tTable
			DROP TABLE #tShift
		COMMIT TRANSACTION
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH
END
GO
PRINT N'Altering Procedure [sAlert].[pEmployeeBiometricFirstInTimeGet]...';


GO

ALTER PROCEDURE [sAlert].[pEmployeeBiometricFirstInTimeGet]
	 	 @rTemplate nvarchar(max)='',
		@rSubject nvarchar(100)='',
		@rOrgId int,
		@rIntervalTime int=0,
	@rToDateTime dateTime,
	@rFromDateTime DateTime
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY	
		BEGIN TRANSACTION 
			if object_id('tempdb..#tTable') is not null
			BEGIN
				DROP TABLE #tTable
			END
			CREATE TABLE #tTable(
					SourceId bigint NOT NULL,
					In_Out_Time [datetime] NOT NULL,
					SourceTypeId int NOT NULL,
					CreatedDateTime [datetime] NOT NULL,
				)
			insert into #tTable
			select SourceId,min(In_Out_Time),SourceTypeId,min(CreatedDateTime) 
			from [sBiometric].[tCloudTransactionData] 
			WHERE Attn_Dt=CONVERT(date,[sCommon].[fGetDate]()) AND SourceTypeId=95 Group by SourceId,SourceTypeId
	
			--select * from #tTable

			SELECT 
				EM.MobileNumber AS MobileNo,	
				EM.CompanyEmail AS EmailId,
				replace (
				replace (
				replace (
				replace(@rTemplate,'[EmployeeName]',EM.EmployeeName),
				'[TimeStamp]',ISNULL(Convert(varchar,temp.In_Out_Time,108),'')),
				'[PresentTime]',ISNULL(Convert(varchar,temp.In_Out_Time,108),'')),
				'[PresentDate]',ISNULL(Convert(varchar,[sCommon].[fGetDate](),103),''))
				 AS MsgText,
				@rSubject AS Subject,
				95 AS ReceiverSourceTypeId,
				EM.EmployeeId AS ReceiverSourceId,
				EM.EmployeeName AS EmployeeName,
				EM.Code AS Code,
				ISNULL(EC.WhatsAppContactNo,'') AS WhatsAppContactNo,
				95 AS SourceTypeId,
				EM.EmployeeId AS SourceId,
				EM.OrgId,
				OM.OrgGroupId,
				ISNULL(Convert(varchar,temp.In_Out_Time,108),'') as Time,
				OM.DisplayTitle AS OrganizationTitle
			FROM 
				#tTable temp
				Inner join sHrm.vEmployeeCommonDetail EM ON temp.SourceId=EM.EmployeeId
				LEFT JOIN sHrm.tEmployeeCommunications EC ON EC.EmployeeId = EM.EmployeeId
				INNER JOIN sSetup.tOrganizationMaster OM ON EM.OrgID = OM.Id
			WHERE
				--temp.CreatedDateTime >= DATEADD(minute,-(@rIntervalTime),[sCommon].[fGetDate]())
				temp.CreatedDateTime < @rToDateTime
				AND temp.CreatedDateTime >= @rFromDateTime
				AND EM.OrgID =@rOrgId

			DROP TABLE #tTable
		COMMIT TRANSACTION
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH


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


GO

ALTER PROCEDURE [sAlert].[pEmployeeBiometricLastOutTimeGet]
	@rTemplate nvarchar(max)='',
	@rSubject nvarchar(100)='',
	@rOrgId int,
	@rOrgGroupId int,
	@rIntervalTime int=0,
	@rToDateTime dateTime=null,
	@rFromDateTime DateTime=null
 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY	
		BEGIN TRANSACTION 
			if object_id('tempdb..#tShift') is not null
			BEGIN
				DROP TABLE #tShift
			END
			CREATE TABLE #tShift(
					ShiftCode int NOT NULL,
					OutTimeAlertTime time not NUll
				)
			insert #tShift
			Select 
				ShiftCode, 
				CAST(OutTimeAlertTime AS Time)
				--case When DATEDIFF(MINUTE,CAST(OutTimeAlertTime AS Time),cast([sCommon].[fGetDate]() as Time)) < @rIntervalTime then DATEDIFF(MINUTE,CAST(OutTimeAlertTime AS Time),cast([sCommon].[fGetDate]() as Time)) else @rIntervalTime end 
			  FROM sBiometric.tShiftMasterCloud
			where  ((OrgGroupId = @rOrgGroupId) OR (@rOrgGroupId=0))  
			AND IsOutTimeAlertTime=1
			--AND CAST(OutTimeAlertTime AS Time)<=cast([sCommon].[fGetDate]() as Time)
			--AND CAST(OutTimeAlertTime AS Time) > CAST(DATEADD(minute,-(@rIntervalTime),[sCommon].[fGetDate]()) AS Time)
			AND CAST(OutTimeAlertTime AS Time)<=cast(@rFromDateTime as Time)
			AND CAST(OutTimeAlertTime AS Time) > CAST(@rToDateTime AS Time)

			declare @lcount int=(SELECT COUNT(ShiftCode) FROM #tShift)
	 
			--select * from #tShift
			if object_id('tempdb..#tTable') is not null
			BEGIN
				DROP TABLE #tTable
			END
			CREATE TABLE #tTable(
						SourceId bigint NOT NULL,
						In_Out_Time [datetime] NOT NULL,
						SourceTypeId int NOT NULL,
						OutTimeAlertTime time NOT NULL,
						CreatedDateTime [datetime] NOT NULL
					)
			if(@lcount>0)
			BEGIN
				insert into #tTable
				select SourceId,MAX(In_Out_Time),SourceTypeId,tempShift.OutTimeAlertTime,Max(CreatedDateTime) 
				from [sBiometric].[tCloudTransactionData] CDT 
				inner join #tShift tempShift ON tempShift.ShiftCode=CDT.ShiftCode
				WHERE Attn_Dt=CONVERT(date,[sCommon].[fGetDate]())  AND SourceTypeId=95 Group by SourceId,SourceTypeId,tempShift.OutTimeAlertTime
			END

			--select * from #tTable

			SELECT 
				EM.MobileNumber AS MobileNo,	
				EM.CompanyEmail AS EmailId,
				replace (
				replace(@rTemplate,'[EmployeeName]',EM.EmployeeName),
				'[TimeStamp]',ISNULL(Convert(varchar,temp.In_Out_Time,108),''))
				 AS MsgText,
				@rSubject AS Subject,
				95 AS ReceiverSourceTypeId,
				EM.EmployeeId AS ReceiverSourceId,
				EM.EmployeeName AS EmployeeName,
				ISNULL(EC.WhatsAppContactNo,'') AS WhatsAppContactNo,
				95 AS SourceTypeId,
				EM.EmployeeId AS SourceId,
				EM.OrgId,
				OM.OrgGroupId,
				OM.DisplayTitle AS OrganizationTitle
			FROM 
				#tTable temp
				Inner join sHrm.vEmployeeCommonDetail EM ON temp.SourceId=EM.EmployeeId
				LEFT JOIN sHrm.tEmployeeCommunications EC ON EC.EmployeeId = EM.EmployeeId
				INNER JOIN sSetup.tOrganizationMaster OM ON EM.OrgID = OM.Id
			WHERE
				temp.OutTimeAlertTime <= CAST([sCommon].[fGetDate]() AS Time)
				AND temp.OutTimeAlertTime > CAST(DATEADD(minute,-(@rIntervalTime),[sCommon].[fGetDate]()) AS Time)
				AND EM.OrgID =@rOrgId

			DROP TABLE #tTable
			DROP TABLE #tShift
		COMMIT TRANSACTION
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH
END
GO
PRINT N'Altering Procedure [sAlert].[pStudentBiometricAbsentTimeGet]...';


GO


ALTER PROCEDURE [sAlert].[pStudentBiometricAbsentTimeGet]
	 @rOrgId int,
	@rOrgGroupId int,
	@rTemplate nvarchar(max),
	@rSubject nvarchar(100)='',
	@rIntervalTime int=0,
	@rToDateTime dateTime=null,
	@rFromDateTime DateTime=null

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY	
		BEGIN TRANSACTION 
		declare  @lBatchID INT
		SELECT @lBatchID = Id from sSetup.tBatchMaster Where OrgId = @rOrgId AND IsActive = 1
			
			if object_id('tempdb..#tShift') is not null
			BEGIN
				DROP TABLE #tShift
			END
			CREATE TABLE #tShift(
					ShiftCode int NOT NULL
				)

			insert #tShift
			Select 
				ShiftCode
			FROM sBiometric.tShiftMasterCloud
			where  ((OrgGroupId = @rOrgGroupId) OR (@rOrgGroupId=0))  
			--AND IsOutTimeAlertTime=1
			--AND CAST(DATEADD(MINUTE,AlterGraceTime,StartTime) AS Time)<cast([sCommon].[fGetDate]() as Time)
			--AND CAST(DATEADD(MINUTE,AlterGraceTime,StartTime) AS Time)>=cast(DATEADD(MINUTE,-@rIntervalTime,[sCommon].[fGetDate]()) as Time)
			AND CAST(DATEADD(MINUTE,AlterGraceTime,StartTime) AS Time)<cast(@rToDateTime as Time)
			AND CAST(DATEADD(MINUTE,AlterGraceTime,StartTime) AS Time)>=cast(@rFromDateTime as Time)

			--select * from #tShift
			declare @lcount int=(SELECT COUNT(ShiftCode) FROM #tShift)

			if object_id('tempdb..#tTable') is not null
			BEGIN
				DROP TABLE #tTable
			END
			CREATE TABLE #tTable(
						SourceId bigint NOT NULL,
						In_Out_Time [datetime] NOT NULL,
						SourceTypeId int NOT NULL
					)

			if(@lcount>0)
			BEGIN
				insert into #tTable
				select SourceId,MIN(In_Out_Time),SourceTypeId
				from [sBiometric].[tCloudTransactionData] CDT
				inner join #tShift tempShift ON tempShift.ShiftCode=CDT.ShiftCode 
				WHERE Attn_Dt=CONVERT(date,[sCommon].[fGetDate]())  AND SourceTypeId=2003 Group by SourceId,SourceTypeId
			END
			
			
			--select * from #tTable
			select SC.ParentContactNo AS MobileNo,	
					SC.ParentEmail AS EmailId,
					replace (
					replace(@rTemplate,'[StudentName]',SC.Name),
					'[AbsentDate]',ISNULL(Convert(varchar,[sCommon].[fGetDate](),103),''))
					 AS MsgText,
					@rSubject AS Subject,
					2003 AS ReceiverSourceTypeId,
					SC.StudentId AS ReceiverSourceId,
					SC.Name AS StudentName,
					SC.Code,
					ISNULL(SC.WhatsAppContactNo,'') AS WhatsAppContactNo,
					2003 AS SourceTypeId,
					SC.StudentId AS SourceId,
					SC.OrgId,
					OM.OrgGroupId,
					OM.DisplayTitle AS OrganizationTitle
				FROM  
					sStudent.vStudentCommunication SC 
					Inner Join  [sStudent].[tStudentMaster] SM on SM.Id=SC.StudentId
					INNER JOIN sSetup.tOrganizationMaster OM ON SC.OrgID = OM.Id
					INNER JOIN #tShift tempshift ON tempshift.ShiftCode=SM.ShiftId
					LEFT JOIN #tTable temp ON  temp.SourceId=SC.StudentId 
				where 
					SC.OrgID =@rOrgId
					AND SC.IsActiveBatch=1
					AND SC.StatusId = 1
					AND temp.In_Out_Time is null
					AND ([sAttendance].[fWeekHOffGet](YEAR([sCommon].[fGetDate]()) ,MONTH([sCommon].[fGetDate]()) ,DAY([sCommon].[fGetDate]()),SC.BatchId,SC.ClassId,SC.DivisionId, '',@rOrgId)<>'W')
					AND ([sAttendance].[fWeekHOffGet](YEAR([sCommon].[fGetDate]()) ,MONTH([sCommon].[fGetDate]()) ,DAY([sCommon].[fGetDate]()),SC.BatchId,SC.ClassId,SC.DivisionId, '',@rOrgId)<>'H')

			DROP TABLE #tTable
			DROP TABLE #tShift
		COMMIT TRANSACTION
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH
END
GO
PRINT N'Altering Procedure [sAlert].[pStudentBiometricFirstInTimeGet]...';


GO

ALTER PROCEDURE [sAlert].[pStudentBiometricFirstInTimeGet]
	@rTemplate nvarchar(max)='',
	@rSubject nvarchar(100)='',
	@rOrgId int,
	@rIntervalTime int=0,
	@rToDateTime dateTime,
	@rFromDateTime DateTime

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY	
		BEGIN TRANSACTION 
		declare @lDateTimeNow datetime=[sCommon].[fGetDate]()
		declare @lLastStudentFirstInAlertSendTime datetime
		
			if object_id('tempdb..#tTable') is not null
			BEGIN
				DROP TABLE #tTable
			END
			CREATE TABLE #tTable(
					SourceId bigint NOT NULL,
					In_Out_Time [datetime] NOT NULL,
					SourceTypeId int NOT NULL,
					CreatedDateTime [datetime] NOT NULL,
				)
			insert into #tTable
			select CDT.SourceId,min(CDT.In_Out_Time),CDT.SourceTypeId,min(CDT.CreatedDateTime) 
			from [sBiometric].[tCloudTransactionData] CDT
			inner join sBiometric.tShiftMasterCloud SMC ON SMC.ShiftCode=CDT.ShiftCode
			WHERE CDT.Attn_Dt=CONVERT(date,@lDateTimeNow)  AND CDT.SourceTypeId=2003
				AND (isnull(SMC.IsStopInTimeAlertTime,0)=0 OR (SMC.IsStopInTimeAlertTime=1 
				AND CAST(SMC.StopInTimeAlertTime as Time)>=CAST(@rToDateTime AS Time)
				AND  CAST(SMC.StopInTimeAlertTime as Time)>=CAST(CDT.In_Out_Time AS Time)))
			 Group by CDT.SourceId,CDT.SourceTypeId
	
			--select * from #tTable
			SELECT 
				SC.ParentContactNo AS MobileNo,	
				SC.ParentEmail AS EmailId,
				replace (
				replace (
				replace (
				replace(@rTemplate,'[StudentName]',SC.Name),
				'[TimeStamp]',ISNULL(Convert(varchar,temp.In_Out_Time,108),'')),
				'[PresentTime]',ISNULL(Convert(varchar,temp.In_Out_Time,108),'')),
				'[PresentDate]',ISNULL(Convert(varchar,[sCommon].[fGetDate](),103),''))
				 AS MsgText,
				@rSubject AS Subject,
				2003 AS ReceiverSourceTypeId,
				SC.StudentId AS ReceiverSourceId,
				SC.Name AS StudentName,
				SC.Code AS Code,
				ISNULL(SC.WhatsAppContactNo,'') AS WhatsAppContactNo,
				2003 AS SourceTypeId,
				SC.StudentId AS SourceId,
				SC.OrgId,
				OM.OrgGroupId,
				ISNULL(Convert(varchar,temp.In_Out_Time,108),'') as Time,
				OM.DisplayTitle AS OrganizationTitle


			FROM 
				#tTable temp
				Inner join sStudent.vStudentCommunication SC ON temp.SourceId=SC.StudentId AND SC.IsActiveBatch=1
				INNER JOIN sSetup.tOrganizationMaster OM ON SC.OrgID = OM.Id
			WHERE
			    --temp.CreatedDateTime >= DATEADD(minute,-(@rIntervalTime),@lDateTimeNow)
				temp.CreatedDateTime < @rToDateTime
				AND temp.CreatedDateTime >= @rFromDateTime
				AND SC.OrgID =@rOrgId
				AND SC.StatusId = 1


			DROP TABLE #tTable
		COMMIT TRANSACTION
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH

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


GO


ALTER PROCEDURE [sAlert].[pStudentBiometricLastOutTimeGet]
	@rTemplate nvarchar(max)='',
	@rSubject nvarchar(100)='',
	@rOrgId int,
	@rOrgGroupId int,
	@rIntervalTime int=0,
	@rToDateTime dateTime,
	@rFromDateTime DateTime
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY	
		BEGIN TRANSACTION 
			if object_id('tempdb..#tShift') is not null
			BEGIN
				DROP TABLE #tShift
			END
			CREATE TABLE #tShift(
					ShiftCode int NOT NULL,
					OutTimeAlertTime time not NUll,
					LastOutAlertBasedOnId int not NUll
				)

			insert #tShift
			Select 
				ShiftCode,
				 case when LastOutAlertBasedOnId=3 THEN 
				 --case When DATEDIFF(MINUTE,CAST(EndTime AS Time),cast([sCommon].[fGetDate]() as Time)) < @rIntervalTime THEN CAST(DATEADD(minute,-(GraceBefore),EndTime) AS Time) else  CAST(DATEADD(minute,-(@rIntervalTime),[sCommon].[fGetDate]()) AS Time) end 
				 case When DATEDIFF(MINUTE,CAST(EndTime AS Time),cast(@rToDateTime as Time)) < @rIntervalTime THEN CAST(DATEADD(minute,-(GraceBefore),EndTime) AS Time) else  CAST(@rFromDateTime AS Time) end 
				 else  CAST(OutTimeAlertTime AS Time) end,
				 isnull(LastOutAlertBasedOnId,1)
				--case When DATEDIFF(MINUTE,CAST(@rIntervalTime AS Time),cast([sCommon].[fGetDate]() as Time)) < @rIntervalTime then DATEDIFF(MINUTE,CAST(OutTimeAlertTime AS Time),cast([sCommon].[fGetDate]() as Time)) else @rIntervalTime end 
			FROM sBiometric.tShiftMasterCloud
			where  ((OrgGroupId = @rOrgGroupId) OR (@rOrgGroupId=0))  
			AND IsOutTimeAlertTime=1
			AND (
			 ( (LastOutAlertBasedOnId=1 OR LastOutAlertBasedOnId=2) AND CAST(OutTimeAlertTime AS Time)<cast(@rToDateTime as Time)
			AND CAST(OutTimeAlertTime AS Time) > CAST(@rFromDateTime AS Time)) 
			OR 
			(LastOutAlertBasedOnId=3 AND CAST(DATEADD(minute,-@rIntervalTime,EndTime) AS Time)<cast(@rToDateTime as Time)
			AND CAST(OutTimeAlertTime AS Time) > CAST(@rFromDateTime AS Time))
			)
			--AND (
			-- ( (LastOutAlertBasedOnId=1 OR LastOutAlertBasedOnId=2) AND CAST(OutTimeAlertTime AS Time)<cast([sCommon].[fGetDate]() as Time)
			--AND CAST(OutTimeAlertTime AS Time) > CAST(DATEADD(minute,-(@rIntervalTime),[sCommon].[fGetDate]()) AS Time)) 
			--OR 
			--(LastOutAlertBasedOnId=3 AND CAST(DATEADD(minute,-@rIntervalTime,EndTime) AS Time)<cast([sCommon].[fGetDate]() as Time)
			--AND CAST(OutTimeAlertTime AS Time) > CAST(DATEADD(minute,-(@rIntervalTime),[sCommon].[fGetDate]()) AS Time))
			--)

			--select * from #tShift
			declare @lcount int=(SELECT COUNT(ShiftCode) FROM #tShift)

			if object_id('tempdb..#tTable') is not null
			BEGIN
				DROP TABLE #tTable
			END
			CREATE TABLE #tTable(
				SourceId bigint NOT NULL,
				In_Out_Time [datetime] NOT NULL,
				SourceTypeId int NOT NULL,
				OutTimeAlertTime time NOT NULL,
				CreatedDateTime [datetime] NOT NULL,
				LastOutAlertBasedOnId int NOT NULL,
				ShiftCode int NOT NULL
			)
			if(@lcount>0)
			BEGIN
				insert into #tTable
				select SourceId,MAX(In_Out_Time),SourceTypeId,tempShift.OutTimeAlertTime,Max(CreatedDateTime),tempShift.LastOutAlertBasedOnId,CDT.ShiftCode
				from [sBiometric].[tCloudTransactionData] CDT 
				inner join #tShift tempShift ON tempShift.ShiftCode=CDT.ShiftCode
				WHERE Attn_Dt=CONVERT(date,[sCommon].[fGetDate]())  AND SourceTypeId=2003 Group by SourceId,SourceTypeId,tempShift.OutTimeAlertTime,tempShift.LastOutAlertBasedOnId,CDT.ShiftCode
			End
			--select * from #tTable

			SELECT 
				SC.ParentContactNo AS MobileNo,	
				SC.ParentEmail AS EmailId,
				replace (
				replace(@rTemplate,'[StudentName]',SC.Name),
				'[TimeStamp]',ISNULL(Convert(varchar,temp.In_Out_Time,108),''))
				 AS MsgText,
				@rSubject AS Subject,
				2003 AS ReceiverSourceTypeId,
				SC.StudentId AS ReceiverSourceId,
				SC.Name AS StudentName,
				SC.Code,
				ISNULL(SC.WhatsAppContactNo,'') AS WhatsAppContactNo,
				2003 AS SourceTypeId,
				SC.StudentId AS SourceId,
				SC.OrgId,
				OM.OrgGroupId,
				OM.DisplayTitle AS OrganizationTitle


			FROM 
				#tTable temp
				Inner Join sBiometric.tShiftMasterCloud SMC on SMC.ShiftCode=temp.ShiftCode
				Inner join sStudent.vStudentCommunication SC ON temp.SourceId=SC.StudentId AND SC.IsActiveBatch=1
				INNER JOIN sSetup.tOrganizationMaster OM ON SC.OrgID = OM.Id
			WHERE
			((temp.LastOutAlertBasedOnId=1 ) AND temp.OutTimeAlertTime <= CAST(@rToDateTime AS Time)
				AND temp.OutTimeAlertTime > CAST(@rFromDateTime AS Time)
				
				OR( temp.LastOutAlertBasedOnId=2 AND CAST(DATEADD(minute,-(SMC.GraceBefore),SMC.EndTime) AS Time) <= CAST(temp.In_Out_Time  AS Time)
				AND CAST(temp.In_Out_Time AS Time) < CAST(@rToDateTime AS Time)
				)
				OR 
				(  
					(temp.LastOutAlertBasedOnId=3 
					AND (CAST(temp.In_Out_Time  AS Time)  >= CAST(temp.OutTimeAlertTime AS Time) 
					AND CAST(temp.In_Out_Time  AS Time)  <= CAST([sCommon].[fGetDate]() AS Time)))
					))

				--((temp.LastOutAlertBasedOnId=1 ) AND temp.OutTimeAlertTime <= CAST([sCommon].[fGetDate]() AS Time)
				--AND temp.OutTimeAlertTime > CAST(DATEADD(minute,-(@rIntervalTime),[sCommon].[fGetDate]()) AS Time)
				
				--OR( temp.LastOutAlertBasedOnId=2 AND CAST(DATEADD(minute,-(SMC.GraceBefore),SMC.EndTime) AS Time) <= CAST(temp.In_Out_Time  AS Time)
				--AND CAST(temp.In_Out_Time AS Time) < CAST([sCommon].[fGetDate]() AS Time)
				--)
				--OR 
				--(  
				--	(temp.LastOutAlertBasedOnId=3 
				--	AND (CAST(temp.In_Out_Time  AS Time)  >= CAST(temp.OutTimeAlertTime AS Time) 
				--	AND CAST(temp.In_Out_Time  AS Time)  <= CAST([sCommon].[fGetDate]() AS Time)))
				--	))
				AND SC.OrgID =@rOrgId
				AND SC.StatusId = 1

			DROP TABLE #tTable
			DROP TABLE #tShift
		COMMIT TRANSACTION
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH
END
GO
PRINT N'Altering Procedure [sAssessment].[pMarkEntryGet]...';


GO
ALTER PROCEDURE [sAssessment].[pMarkEntryGet]
	 @rClassId int,
	 @rDivisionId int,
	 @rExamId int,
	 @rExamDetailId int,
	 @rBatchId int,
	 @rIsWithPhoto bit=0
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 		

if(@rIsWithPhoto=1)
BEGIN
SELECT 
	
	 EM.ClassId
	,DM.Id AS DivisionId
	,EM.Id AS ExamId
	,ED.ClassSubjectId AS ClassSubjectId
	,ISNULL(RD.Id,0) AS ResultDetailId
	,ISNULL(R.Id,0) AS ResultId  
	,SA.AcademicId
	,SA.Name AS StudentName
	,SA.Code 
	,SA.RollNo
	,CASE WHEN ISNULL(EM.IsMarksInDecimal,0) = 1 THEN ISNULL(RD.Obtain,0) ELSE ROUND(ISNULL(RD.Obtain,0),0) END  AS Obtain
	--,ISNULL(RD.Obtain,0) AS Obtain
	,ISNULL(RD.IsPresent,'true') as IsPresent
	,ED.Id AS ExamDetailId
	,ED.Maximum AS MaximumMark
	,ISNULL(EM.IsMarksInDecimal,0) AS IsMarkInDecimal
	,ISNULL(EM.IsNegativeMarks,0) AS IsNegativeMarks,
	ISNULL(SI.StudentPhoto, CONVERT(VARBINARY(MAX), 0)) AS StudentPhoto,
	ISNULL(ED.ExamTopic,'') as ExamTopic,
	0 AS PresentTotal,
	0 AS TotalCount,
	ISNULL(RD.AbsentRemark,'') AS AbsentRemark

from sStudent.vStudentAcademic SA 
	LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId = SA.StudentId
	INNER JOIN sSetup.tClassMaster CM ON SA.ClassId=CM.Id 
	INNER JOIN sSetup.tDivisionMaster DM ON DM.ClassId=CM.Id AND SA.DivisionId=DM.Id
	INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id  
	LEFT JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=SA.AcademicId
	INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
	LEFT JOIN sSetup.vClassSubject V ON V.ClassSubjectId = Ed.ClassSubjectId  
	LEFT JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
	LEFT JOIN sAssessment.tOptionalSubject o on o.AcademicId=SA.AcademicId and o.ClassSubjectId=V.ClassSubjectId

Where  (DM.Id=@rDivisionId OR @rDivisionId = 0)
	   AND (EM.ClassId = @rClassId OR @rClassId = 0)  
	   AND (ED.Id=@rExamDetailId OR @rExamDetailId = 0 )
	   AND (EM.Id=@rExamId OR @rExamId = 0)
	   AND SA.StatusId=1 AND SA.BatchId=@rBatchId
	   AND ((V.IsOptional = 1 AND    isnull(o.AcademicId,0) <> 0) OR (V.IsOptional = 0))	  
	Order By SA.RollNo
END
ELse
BEGIN
	SELECT 
	
	 EM.ClassId
	,DM.Id AS DivisionId
	,EM.Id AS ExamId
	,ED.ClassSubjectId AS ClassSubjectId
	,ISNULL(RD.Id,0) AS ResultDetailId
	,ISNULL(R.Id,0) AS ResultId  
	,SA.AcademicId
	,SA.Name AS StudentName
	,SA.Code 
	,SA.RollNo
	,CASE WHEN ISNULL(EM.IsMarksInDecimal,0) = 1 THEN ISNULL(RD.Obtain,0) ELSE ROUND(ISNULL(RD.Obtain,0),0) END  AS Obtain
	--,ISNULL(RD.Obtain,0) AS Obtain
	,ISNULL(RD.IsPresent,'true') as IsPresent
	,ED.Id AS ExamDetailId
	,ED.Maximum AS MaximumMark
	,ISNULL(EM.IsMarksInDecimal,0) AS IsMarkInDecimal
	,ISNULL(EM.IsNegativeMarks,0) AS IsNegativeMarks,
	CONVERT(VARBINARY(MAX), 0) AS  StudentPhoto,
	ISNULL(ED.ExamTopic,'') as ExamTopic,
	0 AS PresentTotal,
	0 AS TotalCount,
	ISNULL(RD.AbsentRemark,'') AS AbsentRemark
from sStudent.vStudentAcademic SA 
	--LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId = SA.StudentId
	INNER JOIN sSetup.tClassMaster CM ON SA.ClassId=CM.Id 
	INNER JOIN sSetup.tDivisionMaster DM ON DM.ClassId=CM.Id AND SA.DivisionId=DM.Id
	INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id  
	LEFT JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=SA.AcademicId
	INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
	LEFT JOIN sSetup.vClassSubject V ON V.ClassSubjectId = Ed.ClassSubjectId  
	LEFT JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
	LEFT JOIN sAssessment.tOptionalSubject o on o.AcademicId=SA.AcademicId and o.ClassSubjectId=V.ClassSubjectId

Where  (DM.Id=@rDivisionId OR @rDivisionId = 0)
	   AND (EM.ClassId = @rClassId OR @rClassId = 0)  
	   AND (ED.Id=@rExamDetailId OR @rExamDetailId = 0 )
	   AND (EM.Id=@rExamId OR @rExamId = 0)
	   AND SA.StatusId=1 AND SA.BatchId=@rBatchId
	   AND ((V.IsOptional = 1 AND    isnull(o.AcademicId,0) <> 0) OR (V.IsOptional = 0))	  
Order By SA.RollNo
END

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


GO

ALTER PROCEDURE [sAssessment].[pRptResultListConsolidatedMarkRangeWiseGet]
	 
	 @rBuilder1 nvarchar(max)='', 
	 @rBuilder2 nvarchar(max)='', 
	 @rBatchId int = 0,
	 @rClassId int=0,
	 @rDivisionId int=0,
	 @rExamSubGroupId int, 
	 @rCode nvarchar(20)='',
	 @rFromRollNo int,
	 @rToRollNo int,
	 @rStatusId int=0,
	 @rFilterId int=0,
	 @rOrgGroupBatchId int=0,
	 @rClassStatusId int=0,
	 @rDepartmentId int=0
	 		 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN

SELECT 
	@rBuilder1 AS Builder1,
	@rBuilder2 AS Builder2,
	ESGM.Title AS ExamName,
	TSD.EmployeeId,
	EmpM.FirstName,
	EmpM.MiddleName,
	EmpM.LastName,
	EmpM.FirstName + ' ' + EmpM.MiddleName + ' ' + EmpM.LastName AS EmployeeName,
	EmpM.Code AS EmployeeCode,
	SM.Id AS SubjectId,
	SM.Code AS SubjectCode,
	SM.Title AS SubjectName,
	DM.Id AS DivisionId,
	DM.DisplayTitle AS DivisionName,
	DM.OrderIndex AS DivisionOrder,
	CM.Id AS ClassId,
	CM.DisplayTitle AS ClassName,
	CM.OrderIndex AS ClassOrder,
	(CM.DisplayTitle + ' - ' + DM.DisplayTitle) AS ClassDivision,
	A.Id As AcademicId,
	EM.Id AS ExamId,
	RD.Obtain AS SubjectObtain,
	ED.Maximum AS SubjectMaximum,
	CONVERT(Int,ROUND((ISNULL(RD.Obtain, 0) * 100) / ED.Maximum, 0)) AS SubjectPercentage,
	RD.SubjectGrade,
	BM.Title AS BatchName

	FROM 
		sAssessment.tResultDetail RD
		INNER JOIN sAssessment.tResult R ON R.Id = RD.ResultId
		INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId
		INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId 		
		INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId
		INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
		INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=CS.SubjectId					 
		INNER JOIN sStudent.tAcademic A ON A.Id=R.AcademicId	
		INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId		
		INNER JOIN sStudent.tStudentMaster StuM ON StuM.Id=A.StudentId			
		INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId
		INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId			
		--INNER JOIN sSetup.tOrganizationMaster OM ON StuM.OrgId = OM.Id			
		INNER JOIN sAcademic.tTeacherSubjectDivision TSD ON SM.Id = TSD.SubjectId AND DM.Id = TSD.DivisionId
		INNER JOIN sHrm.tEmployeeMaster EmpM ON TSD.EmployeeId = EmpM.Id AND EmpM.StatusId = 7			
		LEFT JOIN sHostel.tAssignRoom ARO ON  ARO.SourceId=StuM.Id AND ARO.SourceTypeId=2003 AND ((BM.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  AND ((ARO.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0) AND (BM.OrgGroupBatchId = ARO.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 
			
	WHERE ESGM.Id = @rExamSubGroupId
		AND ((EM.BatchId = @rBatchId) OR  (@rBatchId = 0))
		AND ((A.ClassId=@rClassId) OR (@rClassId=0)) 
		AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		AND ((A.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
		AND ((A.RollNo <= @rToRollNo) OR (@rToRollNo=0))
		AND ((StuM.Code=@rCode) OR (@rCode=''))
		AND ((StuM.StatusId = @rStatusId) OR (@rStatusId = 0))
		AND ((CM.DepartmentId = @rDepartmentId) OR (@rDepartmentId = 0))		
		AND (
			(@rFilterId = 0) -- All
			OR (@rFilterId = 2 AND isnull(ARO.SourceId,0)!=0) -- Hostel
			OR (@rFilterId = 3 AND isnull(RT.SourceId,0)!=0) -- Transport
			OR ((@rFilterId =1) AND ((isnull(ARO.SourceId,0)=0) AND (isnull(RT.SourceId,0)=0)))
			) 
		AND ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0))
END
GO
PRINT N'Altering Procedure [sAssessment].[pRptResultListConsolidatedWithMarks2Get]...';


GO

ALTER PROCEDURE [sAssessment].[pRptResultListConsolidatedWithMarks2Get]
	 
	 @rBuilder1 nvarchar(max)='', 
	 @rBuilder2 nvarchar(max)='', 
	 @rBatchId int = 0,
	 @rClassId int=0,
	 @rDivisionId int=0,
	 @rExamId int,
	 @rCode nvarchar(20)='',
	 @rFromRollNo int,
	 @rToRollNo int,
	 @rStatusId int=0,
	 @rFilterId int=0,
	 @rOrgGroupBatchId int=0,
	 @rClassStatusId int=0,
	 @rDepartmentId int=0
	 
	
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	--Select
	--	'' AS AcademicIdText,
	--	'' AS ExamIdText,
	--	0 AS AnnualExamId,
	--	'' AS AnnualExam,
	--	'' AS Builder1,
	--	'' Code,
	--	'' AS Name,
	--	0 AS RollNo,
	--	Convert(BigInt,0) AcademicId,			
	--	'' ResultStatus,
	--	'' AS Class,
	--	'' AS Division,
	--	Convert(Decimal,0) TermTotalMark,
	--	Convert(Decimal,0) TermTotalObtain,
	--	0 AS TermRankNumber,
	--	Convert(Decimal,0) TermPercentage,
	--	'' AS TermGrade,
	--	Convert(Decimal,0) TermPercentile,			
	--	Convert(BigInt,0) ResultDetailId,		
	--	Convert(Bit,0) IsDisplayInMarksheet,
	--	Convert(Bit,0) IsShowSubjectGrade,
	--	Convert(Bit,0) IsIncludeInTotal,
	--	Convert(Decimal,0) AS SubjectObtain,
	--	Convert(Decimal,0) AS SubjectMinimum,
	--	Convert(Decimal,0) AS SubjectMaximum,			
	--	'' AS SubjectCode,
	--	'' AS SubjectName,
	--	0 AS SubjectOrderIndex,
	--	Convert(BigInt,0) AS ResultId,
	--	0 AS SubjectId,			 	
	--	Convert(Bit,0) IsMarksInDecimal,
			
	--	'' AS Remark1,
	--	'' AS Remark2,
	--	'' AS Remark3,
	--	'' AS DisplayTitle,
	--	Convert(Bit,0) IsRankNo, 
	--	Convert(Bit,0) IsGrade,
	--	Convert(Bit,0) IsPercentile,
	--	Convert(Bit,0) IsPercentage,
	--	Convert(Bit,0) IsSubjectPercentile,
	--	Convert(Bit,0) IsProcessResult,			 
	--	Convert(Bit,0) IsNegativeMarks,
	--	Convert(Bit,0) IsIncludeCoScholastic,
	--	Convert(Bit,0) IsOnPrePrinted,
	--	Convert(Bit,0) IsDisplayPhoto,
	--	Convert(Bit,0) IsDisplayBirthDate,
	--	Convert(Bit,0) IsLockForEdit,
	--	Convert(Bit,0) IsDisplaySchoolName,			
	--	Convert(Bit,0) IsDisplayAttendance,
	--	Convert(Bit,0) IsDisplayHeightWeight,
	--	Convert(Bit,0) IsResultStatus,
	--	'' AS FooterAdjustmentText,
	--	'' AS DetailAdjustmentText,
	--	0 AS FooterAdjustment,
	--	0 AS DetailAdjustment,		 		 
	--	0 AS TermScopeId,		 
	--	Convert(Bit,0) IsPresent,
	--	Convert(Bit,0) IsDisplayGradeString,			
	--	'' SmallAddress1,
	--	Convert(Bit,0) IsDisplayParentName,			 
	--	Convert(Bit,0) AS IsShowSubjectMark,			
	--	Convert(Bit,0) IsDisplayTeacherSign,
	--	Convert(Bit,0) IsDisplayPrincipalSign,		 			 
	--	Convert(Bit,0) AS IsImageHeader,			 
	--	0 AS ExamOrderIndex,
	--	'' AS DecimalFormat,
	--	0 TermExamId,
	--	'' AS ExamName, 			 
	--	'' AS FatherName,
	--	'' AS MotherName
	
 
 DECLARE @lAnnualExam Nvarchar(100) 
 SELECT @lAnnualExam = ESGM.Title FROM [sAssessment].[tExamMaster] EM 
	INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.ID = EM.ExamSubGroupId 
	WHERE EM.ClassId=@rClassId AND EM.BatchId =@rBatchId AND EM.Id = @rExamId

CREATE TABLE #TempExam
( 
	ExamOrderIndex int,
	TermExamId int,
	AnnualExamId int, 
	Exam nvarchar(100) 
)

INSERT INTO #TempExam
(
	 ExamOrderIndex,
	 TermExamId,
	 AnnualExamId,
	 Exam 	
)
 
SELECT EC.ExamOrder,
EM.Id AS TermExamId,
@rExamId AS AnnualExamId,
ESGM.Title AS Exam
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 =@rExamId  AND (EM.ClassId=@rClassId) AND EM.BatchId =@rBatchId
	
	SELECT 
			Convert(nvarchar(20),A.Id) AS AcademicIdText,
			Convert(nvarchar(20),@rExamId) AS AnnualExamIdText,
			EC.AnnualExamId,
			@lAnnualExam AS AnnualExam,
			 @rBuilder1 AS Builder1,
			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 AS TermTotalMark,
			R.TotalObtain AS TermTotalObtain,
			R.RankNumber AS TermRankNumber,
			R.Percentage AS TermPercentage,
			R.ResultGrade AS TermGrade,
			R.Percentile AS TermPercentile,			
			RD.Id AS ResultDetailId,		
			ED.IsDisplayInMarksheet,
			ED.IsShowSubjectGrade,
			ED.IsIncludeInTotal,
			RD.Obtain AS SubjectObtain,
			ED.Minimum AS SubjectMinimum,
			ED.Maximum AS SubjectMaximum,			
			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.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,		 		 
			EM.TermScopeId,		 
			RD.IsPresent,
			EM.IsDisplayGradeString,	
			OM.SmallAddress1,
			EM.IsDisplayParentName,			 
			ISNULL(ED.IsShowSubjectMark,1) AS IsShowSubjectMark,			
			EM.IsDisplayTeacherSign,
			Em.IsDisplayPrincipalSign,		 		 
			ISNULL(EM.IsDisplayImageHeader,0) AS IsImageHeader,			 
			EC.ExamOrderIndex,
			EM.DecimalFormat,
			EC.TermExamId,
			EC.Exam AS ExamName, 						 
			SF.FatherName,
			SF.MotherName
						
	FROM 
			sAssessment.tResultDetail RD
			INNER JOIN sAssessment.tResult R ON R.Id = RD.ResultId
			INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId
			INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId		
			INNER JOIN #TempExam EC ON EC.TermExamId = EM.Id 	
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=CS.SubjectId					 
			INNER JOIN sStudent.tAcademic A ON A.Id=R.AcademicId	
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId		
			INNER JOIN sStudent.tStudentMaster StuM ON StuM.Id=A.StudentId			
			INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId
			INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId			
			INNER JOIN sSetup.tOrganizationMaster OM ON StuM.OrgId = OM.Id			
						
			LEFT JOIN sHostel.tAssignRoom ARO ON  ARO.SourceId=StuM.Id AND ARO.SourceTypeId=2003 AND ((BM.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  AND ((ARO.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0) AND (BM.OrgGroupBatchId = ARO.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 sAssessment.tStudentRemark SR ON R.AcademicId = SR.AcademicId AND  SR.ExamId=EC.AnnualExamId
			LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId = StuM.Id
			
	WHERE 
			
		((EM.BatchId = @rBatchId) OR  (@rBatchId = 0))
		AND ((A.ClassId=@rClassId) OR (@rClassId=0)) 
		AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		AND ((A.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
		AND ((A.RollNo <= @rToRollNo) OR (@rToRollNo=0))
		AND ((StuM.Code=@rCode) OR (@rCode=''))
		AND ((StuM.StatusId=@rStatusId)OR(@rStatusId=0))
		AND ((CM.DepartmentId = @rDepartmentId) OR (@rDepartmentId = 0)) 
		AND (
			(@rFilterId = 0) -- All
			OR (@rFilterId = 2 AND isnull(ARO.SourceId,0)!=0) -- Hostel
			OR (@rFilterId = 3 AND isnull(RT.SourceId,0)!=0) -- Transport
			OR ((@rFilterId =1) AND ((isnull(ARO.SourceId,0)=0) AND (isnull(RT.SourceId,0)=0)))
			) 
		AND ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0))
		
	 drop table #TempExam
	 
END
GO
PRINT N'Altering Procedure [sAssessment].[pRptSubjectActivityExamDetailGet]...';


GO
ALTER PROCEDURE [sAssessment].[pRptSubjectActivityExamDetailGet]
	 
		@rOrgId int=0,
		@rExamId int=0,
		@rClass int=0,
		@rDivisionId int=0,
		@rBatchId int=0,
		@rBuilder1 nvarchar(max)='',
		@rAcademicId bigint=0,
		@rCode nvarchar(20)='',
		@rFromRollNo int=0,
		@rToRollNo int=0,
		@rMultiCode nvarchar(max)=''
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON 
BEGIN 	 

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

Declare @DecimalConfid nvarchar(20)=''
SELECT @DecimalConfid =ItemValue From sConfig.tConfigurationSetup WHERE ConfigurationId = 496 AND SourceTypeId = 1016 AND SourceId = @rOrgId

	SELECT 			 
			Convert(nvarchar(20),SA.Id) AS AcademicIdText,	
			CONVERT (nvarchar(20),@rExamId) AS ExamIdText, 
			@rBuilder1 AS Builder1,
			SA.Id AS AcademicId,
			SA.RollNo,
			StuM.Number,
			AIS.Grade,
			SAM.Title AS SubjectActivityTitle,
			SSA.Title AS SubjectSubActivityTitle,
			SAM.Id AS ActivityId,
			SSA.Id AS SubjectSubActivityId,
			SAM.OrderIndex AS ActivityOrderIndex,
			SSA.OrderIndex AS SubjectSubActivityOrderIndex ,
			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,
			EM.IsDisplayGradeString,
			EM.IsDisplayParentName,
			[sStudent].[fStudentNameGet](StuM.FirstName , ISNULL(StuM.MiddleName,'') , StuM.LastName,OM.StudentNameFormatId ) AS Name,
			SO.DateOfBirth,
			CMM.Title AS ClassName,
			StuM.code,
			SF.FatherName,
			SF.MotherName,
			SAM.ClassSubjectId ,
			SM.Title AS SubjectName,
			SM.OrderIndex AS SubjectOrderIndex,
			CMM.DisplayTitle AS Class,
			DM.DisplayTitle AS Division,
			CASE WHEN EM.IsDisplayPhoto = 1 THEN SI.StudentPhoto ELSE NULL END AS StudentPhoto, 
			ISNULL(AIS.DescriptiveIndicator,'') AS DescriptiveIndicator,
			CASE WHEN CS.OrderIndex % 2 = 0 THEN 2 
			ELSE 1 END AS ColumnSubjectCount,
			CS.OrderIndex,
			EM.SubjectGroupPerPage,
			AIS.GradeIndicator,
			EM.IsCoScholasticGradeIndicator,
			CASE WHEN EM.IsDisplayTeacherSign = 1 THEN EI.EmployeeSign ELSE NULL END AS EmployeeSign,
			Em.IsDisplayPrincipalSign,
			EM.IsDisplayTeacherSign,
			EM.IsCoScholasticGradeDesIndicator,
			EM.IsCoScholasticGrade,
			Em.IsDisplayParentName,
			(CASE EM.IsDisplayImageHeader WHEN 1 THEN 
			OI.MarksheetHeaderA4 
			ELSE 
			NULL END) AS MarksheetHeaderA4,
			ISNULL(EM.IsDisplayImageHeader,0) AS IsImageHeader,
			RD.Remark,
			
			HM.Title AS House,
			BM.Title AS BAtch ,
			[sAttendance].[fSubjectTeacherGet](SA.DivisionId,SM.ID) AS TEacherName,
			ED.IsShowSubjectGrade,
			CASE @GradeStringRemark WHEN '' THEN @GradeString  ELSE @GradeStringRemark END AS GradeString,
			--@GradeString AS GradeString,
			Convert(nvarchar(20),ISNULL(Em.IsDisplayMonthlyAttendance,0)) As IsDisplayMonthlyAttendanceText,
			TeacherSignCaption,
			EM.PrincipalSignCaption,
			ParentSignCaption,
			--CASE WHEN EM.IsDisplayTeacherSign = 1 THEN EM.TeacherSignCaption ELSE NULL END AS TeacherSignCaption,
			--CASE WHEN EM.IsDisplayPrincipalSign = 1 THEN EM.PrincipalSignCaption ELSE NULL END AS PrincipalSignCaption,
			SR.ResultRemark1,
			SR.ResultRemark2,	
			SR.ResultRemark3,
			SR.ClassTeacherRemark,
			SR.HouseRemark,
			ISNULL(SR.PresentDays,0)AS PresentDays,			
			ISNULL(SR.TotalDays,0)AS TotalDays,
			SR.StudentHeight,
			SR.StudentWeight,
			
			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,
			ISNULL(SR.ImprovementArea,'') As ImprovementArea,
			ISNULL(SR.ProgressArea,'') AS ProgressArea,
			ISNULL(SR.GeneralRemark,'') As GeneralRemark,
			ISNULL(SR.MyActivity,'') AS MyActivity,
			ISNULL(SF.FatherContactNo,'') AS FatherContactNo,
			ISNULL(SF.MotherContactNo,'') AS MotherContactNo,
			ISNULL(SF.FatherMail,'') AS FatherMail,
			ISNULL(SF.MotherMail,'') AS MotherMail,
			ISNULL(SC.PresentStreetONe,'')+' '+ISNULL(SC.PresentStreetTwo,'')+' '+ISNULL(SC.PresentStreetThree,'')+' '+ISNULL(SC.PresentCity,'')+' '+ISNULL(SC.PresentState,'') AS PresentAddress,
			DivisionId,
			SM.ID,
			( EmpM.FirstName + ' ' +EmpM.LastName ) AS InchargeEmployeeName,
			ISNULL(SC.ParentContactNo,'') AS ParentContactNo,
			CONVERT(bit,@DecimalConfid) AS IsDecimal,
			AIS.Marks

	 FROM 
			sAssessment.tCCESubjectSubActivityExamScore AIS 
			INNER JOIN sAssessment.tCCESubjectSubActivityMaster SSA ON AIS.SubjectSubActivityId = SSA.Id 
			INNER JOIN	sAssessment.tCCESubjectActivityMaster SAM  ON SAM.Id = SSA.SubjectActivityId			
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=SAM.ClassSubjectId		
			INNER JOIN sStudent.tAcademic SA ON SA.Id = AIS.AcademicId 
			INNER JOIN sStudent.tStudentMaster StuM ON StuM.Id=SA.StudentId
			INNER JOIN sAssessment.tExamMaster EM ON EM.Id=AIS.ExamId
			INNER JOIN sAssessment.tExamDetail ED ON EM.Id=ED.ExamId AND ED.ClassSubjectId = CS.Id 		 			 
			INNER JOIN sAssessment.tResult AR ON AR.ExamId = AIS.ExamId AND AIS.AcademicId = AR.AcademicId
			INNER JOIN sAssessment.tResultDetail ARD ON ARD.ResultId = AR.Id AND ARD.ExamDetailId = ED.Id
			LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId=SA.StudentId
			LEFT JOIN sActivity.tHouseMaster HM ON HM.Id=SO.HouseId
			LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId=SA.StudentId	
			INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=CS.SubjectId
			INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=SA.divisionId	
			INNER JOIN sSetup.tClassMaster CMM ON CMM.Id=DM.ClassId 
			LEFT JOIN sHrm.tEmployeeMaster EmpM 
				ON EmpM.Id = DM.InchargeEmployeeId AND EmpM.IsObsolete = 0
			LEFT JOIN sHrm.tEmployeeImages EI ON EI.EmployeeId = Dm.InchargeEmployeeId
			--LEFT JOIN sAcademic.tTeacherSubjectDivision TSD ON TSD.DivisionId = DM.Id AND TSD.SubjectId = SM.Id 
			--LEFT JOIN sHrm.tEmployeeMaster EMP ON EMP.Id = TSD.EmployeeId
			LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId = SA.StudentId
			LEFT JOIN sAssessment.tStudentRemark SR ON SA.Id = SR.AcademicId	AND EM.Id = SR.ExamId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = Stum.OrgId
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id= SA.BatchID
			LEFT JOIN sSetup.tOrgImages OI ON OI.OrgId = Om.Id
			LEFT JOIN sAssessment.tResultDetailOther RD ON RD.AcademicId = SA.Id AND EM.ID=RD.ExamId AND CS.Id=RD.ClassSubjectID 
			LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId =StuM.ID
	    --LEFT JOIN @lAcademicId A ON A.AcademicId = SA.AcademicId AND A.ClassSubjectId = ED.ClassSubjectId
			----------------------------------------------------------------------------
			--sAssessment.tCCESubjectActivityMaster SAM 	
			--INNER JOIN sAssessment.tCCESubjectSubActivityMaster SSA ON SAM.Id=SSA.SubjectActivityId 
			--INNER JOIN sAssessment.vCCEExamClassSubject CS ON CS.ClassSubjectId=SAM.ClassSubjectId
			--INNER JOIN sSetup.tClassMaster CMM ON CMM.Id=CS.ClassId 
			--INNER JOIN sStudent.vStudentAcademic SA ON SA.ClassId = CS.ClassId 
			--INNER JOIN sStudent.tStudentMaster StuM ON StuM.Id=SA.StudentId			 
			--LEFT JOIN sAssessment.tCCESubjectSubActivityExamScore AIS ON AIS.AcademicId =SA.AcademicId AND AIS.SubjectSubActivityId= SSA.Id 	
			--LEFT JOIN sAssessment.tExamMaster EM ON EM.Id=AIS.ExamId
			--LEFT JOIN sAssessment.tExamDetail ED ON EM.Id=ED.ExamId	AND ED.ClassSubjectId = CS.ClassSubjectId 		 
			--LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId=SA.StudentId
			--LEFT JOIN sActivity.tHouseMaster HM ON HM.Id=SO.HouseId
			--LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId=SA.StudentId	
			--INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=CS.SubjectId	
			--INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=SA.divisionId
			--LEFT JOIN sHrm.tEmployeeImages EI ON EI.EmployeeId = Dm.InchargeEmployeeId
			--LEFT JOIN sAcademic.tTeacherSubjectDivision TSD ON TSD.DivisionId = DM.Id AND TSD.SubjectId = SM.Id 
			--LEFT JOIN sHrm.tEmployeeMaster EMP ON EMP.Id = TSD.EmployeeId
			--LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId = SA.StudentId
			--LEFT JOIN sAssessment.tStudentRemark SR ON SA.AcademicId = SR.AcademicId	AND EM.Id = SR.ExamId
			--INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = Stum.OrgId
			--INNER JOIN sSetup.tBatchMaster BM ON BM.Id= SA.BatchID
			--LEFT JOIN sSetup.tOrgImages OI ON OI.OrgId = Om.Id
			--LEFT JOIN sAssessment.tResultDetailOther RD ON RD.AcademicId = SA.AcademicId AND EM.ID=RD.ExamId AND CS.ClassSubjectId=RD.ClassSubjectID 
		WHERE
			((SA.Id=@rAcademicId) OR(@rAcademicId=0))
			AND ((CS.ClassId=@rClass) OR (@rClass=0))
			And ((SA.DivisionId =@rDivisionId) or(@rDivisionId=0))	
			And ((SA.BatchId =@rBatchId) OR (@rBatchId=0))
			and ((SA.OrgId=@rOrgId) OR (@rOrgId=0))
			And AIS.ExamId=@rExamId
			AND ((STum.Code = @rCode) OR(@rCode=''))
			AND ((SA.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
			AND ((SA.RollNo <= @rToRollNo) OR (@rToRollNo=0))
			AND StuM.StatusId = 1
			AND (ISNULL(STum.Code,0) IN( SELECT cast(item as nvarchar(20)) FROM  sCommon.fnsplit(@rMultiCode,',')) OR @rMultiCode='')
			AND SAM.IsObsolete = 0
		ORDER BY 
			SA.RollNo ASC,
			SAM.OrderIndex ASC,
			SSA.OrderIndex ASC;
END
GO
PRINT N'Altering Procedure [sAssessment].[pRptSubjectActivityExamDetailWithTermGradeGet]...';


GO
ALTER PROCEDURE [sAssessment].[pRptSubjectActivityExamDetailWithTermGradeGet]
	 
		@rOrgId int=0,
		@rExamId int=0,
		@rClass int=0,
		@rDivisionId int=0,
		@rBatchId int=0,
		@rBuilder1 nvarchar(max)='',
		@rAcademicId bigint=0,
		@rCode nvarchar(20)='',
		@rFromRollNo int=0,
		@rToRollNo int=0,
		@rMultiCode nvarchar(max)=''
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON 
BEGIN 	 
Declare @GradeString nvarchar(500),@GradeSetId int
SELECT @GradeSetId = GradesetId FROM sAssessment.tExamMaster WHERE Id = @rExamId
SELECT @GradeString = [sAssessment].[fGradeStringGet](@GradeSetId)

Declare @DecimalConfid nvarchar(20)=''
SELECT @DecimalConfid =ItemValue From sConfig.tConfigurationSetup WHERE ConfigurationId = 496 AND SourceTypeId = 1016 AND SourceId = @rOrgId


--Declare @rIsDisplayStudentPhoto bit, @rIsDisplayTeacherSign bit, @rIsDisplayPrincipalSign bit, @rIsDisplayImageHeader bit
--SELECT @rIsDisplayStudentPhoto = ISNULL(IsDisplayPhoto,0), @rIsDisplayTeacherSign = ISNULL(IsDisplayTeacherSign,0),
--	   @rIsDisplayPrincipalSign = ISNULL(IsDisplayPrincipalSign,0),@rIsDisplayImageHeader = ISNULL(IsDisplayImageHeader,0)
--	   From sAssessment.tExamMaster Where Id = @rExamId
	   
		--DECLARE @lAcademicId TABLE (AcademicId bigint, ClassSubjectId int, Term1Grade nvarchar(20), Term2Grade nvarchar(20), AnnualGrade nvarchar(20),
		--Term1PresentDays Int, Term1TotalDays Int, Term2PresentDays Int, Term2TotalDays Int)
		
		--INSERT INTO @lAcademicId (AcademicId, ClassSubjectId)
		--(
		--	SELECT 			 
		--		SA.AcademicId,
		--		CS.ClassSubjectId
		--	FROM 
		--		sStudent.vStudentAcademic SA
		--		INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = SA.ClassId
		--		INNER JOIN sAssessment.tExamDetail ED ON EM.Id = ED.ExamId
		--		INNER JOIN sAssessment.vCCEExamClassSubject CS ON CS.ClassSubjectId = ED.ClassSubjectId 
		--		--INNER JOIN sSetup.tSubjectMaster SM ON SM.Id = CS.SubjectId
		--	WHERE
		--		((SA.AcademicId=@rAcademicId) OR(@rAcademicId=0))
		--		AND ((CS.ClassId=@rClass) OR (@rClass=0))
		--		And ((SA.DivisionId =@rDivisionId) or(@rDivisionId=0))	
		--		And ((SA.BatchId =@rBatchId) OR (@rBatchId=0))
		--		And ((EM.Id = @rExamId) OR (@rExamId = 0))
		--		and ((SA.OrgId=@rOrgId) OR (@rOrgId=0))
		--		AND ((SA.Code = @rCode) OR(@rCode=''))
		--		AND ((SA.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
		--		AND ((SA.RollNo <= @rToRollNo) OR (@rToRollNo=0))
		--		AND SA.StatusId = 1
		--)
		
		--Declare @FirstTermExamId AS INT,@SecondTermExamId AS INT, @Term1PresentDays AS INT, @Term1TotalDays AS INT,
		--@Term2PresentDays AS INT, @Term2TotalDays AS INT
		
		--Select @FirstTermExamId=SubExamId  from sAssessment.tExamCombine Where ExamId = @rExamId AND ExamOrder = 1
		
		--Select @SecondTermExamId=SubExamId from sAssessment.tExamCombine Where ExamId = @rExamId AND ExamOrder = 2
		
		
	
		--UPDATE @lAcademicId 
		--SET Term1Grade = ARD.SubjectGrade
		--FROM @lAcademicId A
		--INNER JOIN sAssessment.tResult AR ON AR.ExamId = @FirstTermExamId AND AR.AcademicId = A.AcademicId
		--INNER JOIN sAssessment.tResultDetail ARD ON ARD.ResultId = AR.Id 
		--INNER JOIN sAssessment.tExamDetail ED ON ED.Id = ARD.ExamDetailId AND ED.ClassSubjectId = A.ClassSubjectId
	    
		--UPDATE @lAcademicId 
		--SET Term2Grade = ARD.SubjectGrade
		--FROM @lAcademicId A
		--INNER JOIN sAssessment.tResult AR ON AR.ExamId = @SecondTermExamId AND AR.AcademicId = A.AcademicId
		--INNER JOIN sAssessment.tResultDetail ARD ON ARD.ResultId = AR.Id 
		--INNER JOIN sAssessment.tExamDetail ED ON ED.Id = ARD.ExamDetailId AND ED.ClassSubjectId = A.ClassSubjectId
		
		--UPDATE @lAcademicId 
		--SET AnnualGrade = ARD.SubjectGrade
		--FROM @lAcademicId A
		--INNER JOIN sAssessment.tResult AR ON AR.ExamId = @rExamId AND AR.AcademicId = A.AcademicId
		--INNER JOIN sAssessment.tResultDetail ARD ON ARD.ResultId = AR.Id 
		--INNER JOIN sAssessment.tExamDetail ED ON ED.Id = ARD.ExamDetailId AND ED.ClassSubjectId = A.ClassSubjectId
		
		--UPDATE @lAcademicId 
		--SET Term1PresentDays = SR.PresentDays
		--FROM @lAcademicId A
		--INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = @FirstTermExamId AND SR.AcademicId = A.AcademicId
		
		--UPDATE @lAcademicId 
		--SET Term1TotalDays = SR.TotalDays
		--FROM @lAcademicId A
		--INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = @FirstTermExamId AND SR.AcademicId = A.AcademicId
		
	 --   UPDATE @lAcademicId 
		--SET Term2PresentDays = SR.PresentDays
		--FROM @lAcademicId A
		--INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = @SecondTermExamId AND SR.AcademicId = A.AcademicId
		
		--UPDATE @lAcademicId 
		--SET Term2TotalDays = SR.TotalDays
		--FROM @lAcademicId A
		--INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = @SecondTermExamId AND SR.AcademicId = A.AcademicId
	    
	    --Select * from @lAcademicId
	    
	    SELECT 			 
			Convert(nvarchar(20),SA.Id) AS AcademicIdText,	
			CONVERT (nvarchar(20),@rExamId) AS ExamIdText, 
			@rBuilder1 AS Builder1,
			SA.Id AS AcademicId,
			SA.RollNo,
			StuM.Number,
			AIS.Grade,
			SAM.Title AS SubjectActivityTitle,
			SSA.Title AS SubjectSubActivityTitle,
			SAM.Id AS ActivityId,
			SSA.Id AS SubjectSubActivityId,
			SAM.OrderIndex AS ActivityOrderIndex,
			SSA.OrderIndex AS SubjectSubActivityOrderIndex ,
			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,
			EM.IsDisplayGradeString,
			EM.IsDisplayParentName,
			StuM.FirstName + ' ' +StuM.MiddleName +' ' +StuM.LastName AS Name,
			SO.DateOfBirth,
			CMM.Title AS ClassName,
			StuM.code,
			ISNULL(SR.PresentDays,0)AS PresentDays,			
			ISNULL(SR.TotalDays,0)AS TotalDays,
			SR.StudentHeight,
			SR.StudentWeight,
			SF.FatherName,
			SF.MotherName,
			SAM.ClassSubjectId ,
			SM.Title AS SubjectName,
			SM.OrderIndex AS SubjectOrderIndex,
			CMM.DisplayTitle AS Class,
			DM.DisplayTitle AS Division,
			SR.ResultRemark1,
			SR.ResultRemark2,						 
			CASE WHEN EM.IsDisplayPhoto = 1 THEN SI.StudentPhoto ELSE NULL END AS StudentPhoto, 
			ISNULL(AIS.DescriptiveIndicator,'') AS DescriptiveIndicator,
			CASE WHEN CS.OrderIndex % 2 = 0 THEN 2 
			ELSE 1 END AS ColumnSubjectCount,
			CS.OrderIndex,
			EM.SubjectGroupPerPage,
			AIS.GradeIndicator,
			EM.IsCoScholasticGradeIndicator,
			(CASE Em.IsDisplayTeacherSign WHEN 1 THEN
			EI.EmployeeSign
			ELSE NULL END ) AS EmployeeSign,
			Em.IsDisplayPrincipalSign,
			EM.IsDisplayTeacherSign,
			EM.IsCoScholasticGradeDesIndicator,
			EM.IsCoScholasticGrade,
			Em.IsDisplayParentName,
			(CASE EM.IsDisplayImageHeader WHEN 1 THEN
			OI.CertificateHeaderA4 
			ELSE NULL END)AS MarksheetHeaderA4,
			ISNULL(EM.IsDisplayImageHeader,0) AS IsImageHeader,
			RD.Remark,
			SR.ClassTeacherRemark,
			SR.HouseRemark,
			HM.Title AS House,
			BM.Title AS BAtch ,
			[sAttendance].[fSubjectTeacherGet](SA.DivisionId,SM.ID) AS TEacherName,
			ED.IsShowSubjectGrade,
			@GradeString AS GradeString,
			Convert(nvarchar(20),ISNULL(Em.IsDisplayMonthlyAttendance,0)) As IsDisplayMonthlyAttendanceText,
			--CASE WHEN EM.IsDisplayTeacherSign = 1 THEN EM.TeacherSignCaption ELSE NULL END AS TeacherSignCaption,
			--CASE WHEN EM.IsDisplayPrincipalSign = 1 THEN EM.PrincipalSignCaption ELSE NULL END AS PrincipalSignCaption,
			ISNULL(EM.TeacherSignCaption,'') AS TeacherSignCaption,
		    ISNULL(EM.PrincipalSignCaption,'') AS PrincipalSignCaption,
			ParentSignCaption,
			SR.ResultRemark3,
			ARD.SubjectGrade,
			ISNULL(SR.GeneralRemark,'') As GeneralRemark,
			(CASE  When EM.CoordinatorEmployeeId IS NOT NULL AND EM.CoordinatorEmployeeId !=0 then EICoordinator.EmployeeSign ELSE NULL END) AS CoordinatorEmployeeSign,
			ISNULL(C.ParentContactNo,'') AS ParentContactNo,
			ISNULL(C.StudentContactNo,'') AS StudentContactNo,
			(C.PresentStreetOne+' '+C.PresentStreetTwo+' '+C.PresentStreetThree+' '+C.PresentCountry+' '+C.PresentState+' '+C.PresentCity+' '+C.PresentZipCode) AS Address1,
			CONVERT(bit,@DecimalConfid) AS IsDecimal,
			--added by megha for 0027299
			AR.ResultGrade As OverallGrade

			
			--A.Term1Grade,
			--A.Term2Grade,
			--A.AnnualGrade,
			--A.Term1PresentDays,
			--A.Term1TotalDays,
			--A.Term2PresentDays,
			--A.Term2TotalDays			
			
		FROM 
			sAssessment.tCCESubjectSubActivityExamScore AIS 
			INNER JOIN sAssessment.tCCESubjectSubActivityMaster SSA ON AIS.SubjectSubActivityId = SSA.Id 
			INNER JOIN	sAssessment.tCCESubjectActivityMaster SAM  ON SAM.Id = SSA.SubjectActivityId			
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=SAM.ClassSubjectId		
			INNER JOIN sStudent.tAcademic SA ON SA.Id = AIS.AcademicId 
			INNER JOIN sStudent.tStudentMaster StuM ON StuM.Id=SA.StudentId
			INNER JOIN sAssessment.tExamMaster EM ON EM.Id=AIS.ExamId
			INNER JOIN sAssessment.tExamDetail ED ON EM.Id=ED.ExamId AND ED.ClassSubjectId = CS.Id 		 			 
			INNER JOIN sAssessment.tResult AR ON AR.ExamId = AIS.ExamId AND AIS.AcademicId = AR.AcademicId
			INNER JOIN sAssessment.tResultDetail ARD ON ARD.ResultId = AR.Id AND ARD.ExamDetailId = ED.Id
			LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId=SA.StudentId
			LEFT JOIN sActivity.tHouseMaster HM ON HM.Id=SO.HouseId
			LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId=SA.StudentId	
			INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=CS.SubjectId
			INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=SA.divisionId	
			INNER JOIN sSetup.tClassMaster CMM ON CMM.Id=DM.ClassId 
			
			LEFT JOIN sHrm.tEmployeeImages EI ON EI.EmployeeId = Dm.InchargeEmployeeId
			--LEFT JOIN sAcademic.tTeacherSubjectDivision TSD ON TSD.DivisionId = DM.Id AND TSD.SubjectId = SM.Id 
			--LEFT JOIN sHrm.tEmployeeMaster EMP ON EMP.Id = TSD.EmployeeId
			LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId = SA.StudentId
			LEFT JOIN sAssessment.tStudentRemark SR ON SA.Id = SR.AcademicId	AND EM.Id = SR.ExamId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = Stum.OrgId
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id= SA.BatchID
			LEFT JOIN sSetup.tOrgImages OI ON OI.OrgId = Om.Id
			LEFT JOIN sAssessment.tResultDetailOther RD ON RD.AcademicId = SA.Id AND EM.ID=RD.ExamId AND CS.Id=RD.ClassSubjectID 
			LEFT JOIN sHrm.tEmployeeImages EICoordinator ON EICoordinator.EmployeeId = EM.CoordinatorEmployeeId	
			--LEFT JOIN @lAcademicId A ON A.AcademicId = SA.AcademicId AND A.ClassSubjectId = ED.ClassSubjectId
			LEFT JOIN sStudent.tStudentCommunication C ON C.StudentId = SA.StudentId
			
		WHERE
			((SA.Id=@rAcademicId) OR(@rAcademicId=0))
			AND ((CS.ClassId=@rClass) OR (@rClass=0))
			And ((SA.DivisionId =@rDivisionId) or(@rDivisionId=0))	
			And ((SA.BatchId =@rBatchId) OR (@rBatchId=0))
			and ((SA.OrgId=@rOrgId) OR (@rOrgId=0))
			And AIS.ExamId=@rExamId
			AND ((STum.Code = @rCode) OR(@rCode=''))
			AND ((SA.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
			AND ((SA.RollNo <= @rToRollNo) OR (@rToRollNo=0))
			AND StuM.StatusId = 1
			AND (ISNULL(StuM.Code,0) IN( SELECT cast(item as nvarchar(20)) FROM  sCommon.fnsplit(@rMultiCode,',')) OR @rMultiCode='')
		--ORDER BY 
		--	SA.RollNo ASC,
		--	SAM.OrderIndex ASC,
		--	SSA.OrderIndex ASC;
			
END
GO
PRINT N'Altering Procedure [sAssessment].[pStudentwiseOptionalSubjectListGet]...';


GO

ALTER PROCEDURE [sAssessment].[pStudentwiseOptionalSubjectListGet]
                  
    @rDivisionId bigint,
    @rClassId bigint,
    @rSubjectId bigint ,
    @rBatchId int,
    @rBuilder1 nvarchar(max)='',
	@rBuilder2 nvarchar(max)='',
	@rClassStatusId int=0,
	@rStatusId int=1,
    @rViewMode smallint = 0,  -- 0 for Vertical and 1 for Horizontal
	@rSubjects nvarchar(max)=''
AS
SET NOCOUNT ON

BEGIN

	IF(@rViewMode = 1)
	BEGIN
		SELECT
			SA.AcademicId,
			CS.Id as ClassSubjectId,
			SA.Name as StudentName,
			CS.SubjectId, 
			SA.Code,
			SA.RollNo,
			SA.DivisionId,
			SA.ClassName,
			SA.DivisionName
			INTO #TempTable 
			FROM
			(
					SELECT * FROM sStudent.vStudentAcademic 
					where (DivisionId = @rDivisionId OR @rDivisionId = 0)  AND BatchId = @rBatchId
					AND (ClassStatusId = @rClassStatusId OR @rClassStatusId = 0) 
					AND (StatusId = @rStatusId OR @rStatusId = 0)) SA  
					CROSS JOIN
					(select * FROM sSetup.tClassSubject B   
					WHERE  B.IsOptional = 1 AND (B.ClassId = @rClassId OR @rClassId = 0)  
					AND  (B.Id = @rSubjectId OR @rSubjectId = 0) 
			) AS CS

		SELECT DISTINCT
			SS.AcademicId,
			Stuff ((select ',' + Convert(nvarchar(20),OS.ClassSubjectId) FROM sAssessment.tOptionalSubject OS WHERE AcademicId = SS.AcademicId FOR XML PATH('') ),1,1,'') AS ClassSubjectId,
			SS.StudentName,
			SS.Code,
			SS.RollNo,
			@rBuilder1 AS ClassName,
			@rBuilder2 AS DivisionName,
			SS.DivisionId,
			SS.ClassName AS ClsName,
			SS.DivisionName AS DivName,
			@rSubjects
			FROM
			#TempTable AS SS
			INNER JOIN sSetup.tSubjectMaster SM ON SS.SubjectId = SM.Id 
			LEFT JOIN sAssessment.tOptionalSubject OS ON OS.AcademicId = SS.AcademicId AND OS.ClassSubjectId = SS.ClassSubjectId
			ORDER BY SS.RollNo
			DROP TABLE #TempTable
	END
	ELSE
	BEGIN
		SELECT 
		SS.AcademicId,
		SS.ClassSubjectId,
		SS.StudentName,
		SS.SubjectId,
		SM.Code as SubjectName,
		SS.Code,
		SS.RollNo,
		@rBuilder1 AS ClassName,
		@rBuilder2 AS DivisionName,
		SS.DivisionId,
		SS.ClassName AS ClsName,
		SS.DivisionName AS DivName,
		CASE WHEN isnull(OS.ClassSubjectId,0) <> 0 THEN 'true' ELSE 'false' END AS Selected
		FROM
		(SELECT
		SA.AcademicId,
		CS.Id as ClassSubjectId,
		SA.Name as StudentName,
		CS.SubjectId, 
		SA.Code,
		SA.RollNo,
		SA.DivisionId,
		SA.ClassName,
		SA.DivisionName
		FROM
		 (select * FROM sStudent.vStudentAcademic where (DivisionId=@rDivisionId OR @rDivisionId = 0)  AND BatchId=@rBatchId AND (ClassStatusId=@rClassStatusId OR @rClassStatusId=0) AND (StatusId=@rStatusId OR @rStatusId=0))SA  
		 CROSS JOIN    (select * FROM sSetup.tClassSubject B   WHERE  B.IsOptional = 1 AND (B.ClassId = @rClassId OR @rClassId = 0)  AND  (B.Id= @rSubjectID OR @rSubjectId= 0) 
		) AS CS 
		 ) AS SS
		 INNER JOIN sSetup.tSubjectMaster SM ON SS.SubjectId = SM.Id 
		 LEFT JOIN sAssessment.tOptionalSubject OS ON OS.AcademicId = SS.AcademicId AND OS.ClassSubjectId = SS.ClassSubjectId

		ORDER BY SS.RollNo,SM.OrderIndex
	   END
END
GO
PRINT N'Altering Procedure [sAttendance].[pRptStudentwiseAbsentDaysDetailsGet]...';


GO

ALTER PROCEDURE [sAttendance].[pRptStudentwiseAbsentDaysDetailsGet]	
 
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 @rOrgId smallint,
	 @rBatchId int,
	 @rDepartmentId int,
	 @rClassId int,
	 @rDivisionId int,
	 @rAttendanceTypeId tinyint,
	 @rFromDate date,
	 @rToDate date,
	 @rStudentCode nvarchar(20),
	 @rSubjectId int

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	BEGIN 
 
 

	SELECT 
		DISTINCT(SA.AcademicId),
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			SA.ClassId,
			SA.DivisionId,
			SA.ClassName,
			SA.DivisionName,
			SA.ClassName+' - '+SA.DivisionName AS ClassDivision,
			SA.Code,
			SA.RollNo,			
			SA.Name,			
			sAttendance.fAttendanceGet(SA.AcademicId,@rAttendanceTypeId,@rSubjectId,@rFromDate,@rToDate) AS AttendanceDate,
		    SA.DivisionOrder,
		    SC.ParentContactNo,
		     (SELECT COUNT(1) FROM sAttendance.tStudentRegister SR1 
				WHERE SR1.AcademicId=SA.AcademicId 
				AND ((SR1.AttendanceTypeId=@rAttendanceTypeId) OR (@rAttendanceTypeId=0))
				AND ((SR1.SubjectId=@rSubjectId) OR (@rSubjectId=0))
				AND ((SR1.AttendanceDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
				AND ((SR1.AttendanceDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
				AND SR1.IsPresent=0) AS AbsentCount,
		     (SELECT COUNT(1) FROM sAttendance.tStudentRegister SR1 
				WHERE SR1.AcademicId=SA.AcademicId 
				AND ((SR1.AttendanceTypeId=@rAttendanceTypeId) OR (@rAttendanceTypeId=0))
				AND ((SR1.SubjectId=@rSubjectId) OR (@rSubjectId=0))
				AND ((SR1.AttendanceDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
				AND ((SR1.AttendanceDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
				AND SR1.IsPresent=1) AS PresentCount,
			(SELECT COUNT(1) FROM sAttendance.tStudentRegister SR1 
				WHERE SR1.AcademicId=SA.AcademicId 
				AND ((SR1.AttendanceTypeId=@rAttendanceTypeId) OR (@rAttendanceTypeId=0))
				AND ((SR1.SubjectId=@rSubjectId) OR (@rSubjectId=0))
				AND ((SR1.AttendanceDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
				AND ((SR1.AttendanceDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))) AS TotalWorkingDays
				 
	FROM 
			sStudent.vStudentAcademic SA
		INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=SA.AcademicId
		INNER JOIN sStudent.tStudentCommunication SC ON SC.StudentId=SA.StudentId
	WHERE 
			(SA.OrgId=@rOrgId)
		AND	(SA.BatchId = @rBatchId) 
		AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
		AND ((SA.ClassId=@rClassId) OR (@rClassId=0))
		AND ((SA.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		AND ((SR.AttendanceTypeId=@rAttendanceTypeId) OR (@rAttendanceTypeId=0))
		AND ((SR.AttendanceDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
		AND ((SR.AttendanceDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
		AND ((SA.Code=@rStudentCode) OR (@rStudentCode=''))
		--AND (SR.IsPresent = 0)
		AND (SA.StatusId != 3)
		AND ((SR.SubjectId=@rSubjectId) OR (@rSubjectId=0))
		GROUP BY SA.AcademicId,SA.ClassId,SA.DivisionId,SA.ClassName,SA.DivisionName,SA.Code,SA.RollNo,SA.Name,SA.DivisionOrder,SC.ParentContactNo
END
GO
PRINT N'Altering Procedure [sAttendance].[pStudentAttendaceDashboardGet]...';


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

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

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

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

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

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

--Organization wise Attendance

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

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

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

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

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

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

      END
   
ELSE IF @rTypeId=24     
      BEGIN

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

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

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

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

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

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

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


GO

ALTER PROCEDURE [sAttendance].[pUpdateResultAttendance]
	 	 
		 @rClassId int=0,
		 @rDivisionId int=0,
		 @rStudentCode nvarchar(20)='',	
	 	 @rAttendanceTypeId tinyint=1,	 	 
		 @rFromAttendanceDate date='',
		 @rToAttendanceDate date='',
	 	 @rBatchId int,
	 	 @rOrgId int,
	 	 @rExamId int,
	 	 @rExamSubGroupId int=0
	  
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
 
 

BEGIN 
 
		
	CREATE TABLE #tResultAttendance
	 (
	 ExamId int,  
	 AcademicId  bigint,	 
	 PresentCount int,
	 AbsentCount int 
	 )

   INSERT INTO #tResultAttendance
   (ExamId,AcademicId,PresentCount,AbsentCount)
   	SELECT
   	EM.Id, 
   	SA.Id,
	   ISNULL((SELECT count(AcademicId) FROM sAttendance.tStudentRegister SR	 
		WHERE		 
		 SR.AttendanceDate >= @rFromAttendanceDate
		AND SR.AttendanceDate <= @rToAttendanceDate
		AND 
		SR.AcademicId = SA.Id
		AND SR.IsPresent = 1
		AND SR.AttendanceTypeId = @rAttendanceTypeId				
		) ,0)
		 AS PresentCount
		 , 
	   ISNULL((SELECT count(AcademicId) FROM sAttendance.tStudentRegister SR	 
		WHERE		 
		 SR.AttendanceDate >= @rFromAttendanceDate
		AND SR.AttendanceDate <= @rToAttendanceDate		
		AND 
		SR.IsPresent = 0
		AND SR.AttendanceTypeId = @rAttendanceTypeId
		AND SR.AcademicId = SA.Id		
		),0)
		 AS AbsentCount 		
  FROM 
		 sStudent.tAcademic SA 
		 INNER JOIN sStudent.tStudentMaster SM ON SM.Id=SA.StudentId
		 INNER JOIN sAssessment.tExamMaster EM ON SA.BatchId = EM.BatchId 
		 AND SA.ClassId = EM.ClassId
		 AND EM.ExamSubGroupId = 	@rExamSubGroupId
		 AND EM.BatchId = @rBatchId	 
		 --INNER JOIN sAssessment.tExamStatus ES ON ES.ExamId = EM.Id AND ES.DivisionId = SA.DivisionId -- commented by sarangi if new exam then attendance not Updated - mantisid - 0026854
         WHERE
   --       ((SM.Code=@rStudentCode) OR (@rStudentCode=''))         
		 --AND 
		 ((SA.ClassId=@rClassId) OR (@rClassId=0))
	     AND ((SA.DivisionId=@rDivisionId) OR (@rDivisionId=0)) 
         AND (SA.OrgId = @rOrgId)
         AND (SA.BatchId = @rBatchId)
		 --AND ES.StatusId <> 504 -- commented by sarangi if result is generated then attendance not Updated - mantisid - 0026854
        
  
 -- Select * from #tResultAttendance
    INSERT INTO sAssessment.tStudentRemark
    (ExamId,AcademicId,PresentDays,TotalDays)
    SELECT RA.ExamId,RA.AcademicId,CONVERT(decimal(6, 2),PresentCount),CONVERT(decimal(6, 2),AbsentCount) + CONVERT(decimal(6, 2),PresentCount)
    --,SR.AcademicId,SR.ExamId
    FROM #tResultAttendance RA LEFT JOIN sAssessment.tStudentRemark SR
    ON RA.AcademicId = SR.AcademicId AND RA.ExamId = SR.ExamId
    WHERE SR.AcademicId IS NULL   AND SR.ExamId IS NULL
    
   
    
    UPDATE SR
    SET PresentDays = CONVERT(decimal(6, 2),RA.PresentCount),
         TotalDays = CONVERT(decimal(6, 2),RA.PresentCount) + CONVERT(decimal(6, 2),RA.AbsentCount)
    FROM sAssessment.tStudentRemark SR INNER JOIN
    #tResultAttendance RA 
    ON  SR.ExamId = RA.ExamId AND SR.AcademicId = RA.AcademicId
    --INNER JOIN sAssessment.tExamMaster EM ON EM.Id = SR.ExamId
    --WHERE EM.ExamSubGroupId = @rExamSubGroupId
 
 --Select * from sAssessment.tStudentRemark Order by UpdatedDateTime desc
 SELECT 1 AS RESULT
END
GO
PRINT N'Altering Procedure [sAttendance].[pYearlyRegisterGet]...';


GO
ALTER PROCEDURE [sAttendance].[pYearlyRegisterGet]

	 
	 @rAcademicId bigint=0,
	 @rClassId int=0,
	 @rDivisionId int=0,
	 @rBatchId int=0,
	 @rAttendanceTypeId tinyint=1,
	 @rStatus int=0,
	 @rDepartmentId int=0,
	 @rStudentCode nvarchar(20) = '',
	 @rBuilder1 nvarchar(max)='',		--add for mantis 27006
	 @rBuilder2 nvarchar(max)=''		--add for mantis 27006
	 
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
DECLARE @Month1 nvarchar(20),@Month2 nvarchar(20),@Month3 nvarchar(20),
        @Month4 nvarchar(20),@Month5 nvarchar(20),@Month6 nvarchar(20),
		@Month7 nvarchar(20),@Month8 nvarchar(20),@Month9 nvarchar(20),
		@Month10 nvarchar(20),@Month11 nvarchar(20),@Month12 nvarchar(20)
	 
	 Select @Month1 = Month1 FROM sAttendance.tYearlyRegister WHERE Month1 IS NOT NULL
	 Select @Month2 = Month2 FROM sAttendance.tYearlyRegister WHERE Month2 IS NOT NULL
	 Select @Month3 = Month3 FROM sAttendance.tYearlyRegister WHERE Month3 IS NOT NULL
	 Select @Month4 = Month4 FROM sAttendance.tYearlyRegister WHERE Month4 IS NOT NULL
	 Select @Month5 = Month5 FROM sAttendance.tYearlyRegister WHERE Month5 IS NOT NULL
	 Select @Month6 = Month6 FROM sAttendance.tYearlyRegister WHERE Month6 IS NOT NULL
	 Select @Month7 = Month7 FROM sAttendance.tYearlyRegister WHERE Month7 IS NOT NULL
	 Select @Month8 = Month8 FROM sAttendance.tYearlyRegister WHERE Month8 IS NOT NULL
	 Select @Month9 = Month9 FROM sAttendance.tYearlyRegister WHERE Month9 IS NOT NULL
	 Select @Month10 = Month10 FROM sAttendance.tYearlyRegister WHERE Month10 IS NOT NULL
	 Select @Month11 = Month11 FROM sAttendance.tYearlyRegister WHERE Month11 IS NOT NULL
	 Select @Month12 = Month12 FROM sAttendance.tYearlyRegister WHERE Month12 IS NOT NULL
        
SELECT 
	A.Id AS AcademicId,
	A.RollNo,
	SM.Code,
	ISNULL(YR.AvergeAttendance,0) AS AvergeAttendance,
	YR.TotalDays,
	YR.PresentDays,
	
	ISNULL(YR.Month1,@Month1) AS Month1,
	ISNULL(YR.PresentDays1,0) AS PresentDays1,
	ISNULL(YR.TotalDays1,0) AS TotalDays1,
	
	ISNULL(YR.Month2,@Month2) AS Month2,
	ISNULL(YR.PresentDays2,0) AS PresentDays2,
	ISNULL(YR.TotalDays2,0) AS TotalDays2,
	
	ISNULL(YR.Month3,@Month3) AS Month3,
	ISNULL(YR.PresentDays3,0) AS PresentDays3,
	ISNULL(YR.TotalDays3,0) AS TotalDays3,
	
	ISNULL(YR.Month4,@Month4) AS Month4,
	ISNULL(YR.PresentDays4,0) AS PresentDays4,
	ISNULL(YR.TotalDays4,0) AS TotalDays4,
	
	ISNULL(YR.Month5,@Month5) AS Month5,
	ISNULL(YR.PresentDays5,0) AS PresentDays5,
	ISNULL(YR.TotalDays5,0) AS TotalDays5,
	
	ISNULL(YR.Month6,@Month6) AS Month6,
	ISNULL(YR.PresentDays6,0) AS PresentDays6,
	ISNULL(YR.TotalDays6,0) AS TotalDays6,
	
	ISNULL(YR.Month7,@Month7) AS Month7,
	ISNULL(YR.PresentDays7,0) AS PresentDays7,
	ISNULL(YR.TotalDays7,0) AS TotalDays7,
	
	ISNULL(YR.Month8,@Month8) AS Month8,
	ISNULL(YR.PresentDays8,0) AS PresentDays8,
	ISNULL(YR.TotalDays8,0) AS TotalDays8,
	
	ISNULL(YR.Month9,@Month9) AS Month9,
	ISNULL(YR.PresentDays9,0) AS PresentDays9,
	ISNULL(YR.TotalDays9,0) AS TotalDays9,
	
	ISNULL(YR.Month10,@Month10) AS Month10,
	ISNULL(YR.PresentDays10,0) AS PresentDays10,
	ISNULL(YR.TotalDays10,0) AS TotalDays10,
	
	ISNULL(YR.Month11,@Month11) AS Month11,
	ISNULL(YR.PresentDays11,0) AS PresentDays11,
	ISNULL(YR.TotalDays11,0) AS TotalDays11,
	
	ISNULL(YR.Month12,@Month12) AS Month12,
	ISNULL(YR.PresentDays12,0) AS PresentDays12,
	ISNULL(YR.TotalDays12,0) AS TotalDays12,
	
	SM.FirstName + ' ' + ' '+ SM.MiddleName+ ' ' + SM.LastName As Name,	
	SM.StatusID,
	SO.UIDNumber,
	SO.AdhaarNumber,
	A.ClassId AS ClassId,
	A.DivisionId AS DivisionId,
	(SELECT Title FROM sSetup.tClassMaster WHERE Id = A.ClassId) AS ClassTitle,
	(SELECT OrderIndex FROM sSetup.tClassMaster WHERE Id = A.ClassId) AS ClassOrderIndex,
	(SELECT Title FROM sSetup.tDivisionMaster WHERE Id = A.DivisionId) AS DivisionTitle,
	(SELECT OrderIndex FROM sSetup.tDivisionMaster WHERE Id = A.DivisionId) AS DivisionOrderIndex,
	--CM.Title AS ClassTitle,
	--DM.Title AS DivisionTitle,
	--CM.OrderIndex AS ClassOrderIndex,
	--DM.OrderIndex AS DivisionOrderIndex
	[sStudent].[fStudentNameGet](SM.FirstName , SM.MiddleName, SM.LastName,OM.StudentNameFormatId ) AS NameAsPerOrgWise,
	@rBuilder1 AS Builder1,				--add for mantis 27006
	@rBuilder2 AS Builder2				--add for mantis 27006
from
	sAttendance.tYearlyRegister YR
	INNER JOIN sStudent.tAcademic A ON A.Id=YR.AcademicId
	INNER JOIN sStudent.tStudentMaster SM ON SM.Id=A.StudentId 	
	INNER JOIN sStudent.tStudentOther SO ON SO.StudentId = A.StudentId
	INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=A.OrgId
	--INNER JOIN sSetup.tClassMaster CM ON A.ClassId = CM.Id
	--INNER JOIN sSetup.tDivisionMaster DM ON A.DivisionId = A.DivisionId
where 


	((YR.AcademicId=@rAcademicId) OR (@rAcademicId=0))
	AND(A.BatchId=@rBatchId)
	AND((A.ClassId=@rClassId) OR (@rClassId=0))
	AND((A.DivisionId=@rDivisionId) OR (@rDivisionId=0))
	AND ((SM.StatusId=@rStatus) OR (@rStatus=0))
	AND ((SM.Code=@rStudentCode) OR (@rStudentCode=''))
	order by A.RollNo 
 
	 END
GO
PRINT N'Altering Procedure [sAttendance].[pYearlyRegisterUpdate]...';


GO
 

ALTER PROCEDURE [sAttendance].[pYearlyRegisterUpdate]

     @rOrgId int,
	 @rBatchId int
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 

	DECLARE @lQuery AS nvarchar(max)
	
	DELETE YR FROM sAttendance.tYearlyRegister  YR INNER JOIN
	sStudent.tAcademic A ON YR.AcademicId = A.Id
	WHERE A.BatchId = @rBatchId
 
 	INSERT INTO sAttendance.tYearlyRegister(AcademicId) 
	SELECT Id FROM sStudent.tAcademic WHERE BatchId = @rBatchId
	
	
		CREATE TABLE #tempClass
	(	Id int IDENTITY,
		ClassId int  
	)
	
	INSERT INTO #tempClass (ClassId) 
	SELECT  ID FROM sSetup.tClassMaster  WHERE OrgId = @rOrgId
	
	
	DECLARE @lClassCount int,@lClassId int
	DECLARE @lClassCounter int 
	SET @lClassCounter = 0
	
	Select @lClassCount = MAX(Id) from #tempClass
	
 	while (@lClassCounter <= @lClassCount)
	BEGIN
	
	SELECT @lClassId = ClassId FROM #tempClass WHERe Id = @lClassCounter
	
	
 	CREATE TABLE #tempMonthlySetup
	(	Id int IDENTITY,
		ForMonth int,
		ForYear int,
		ClassId int
	)
	
	INSERT INTO #tempMonthlySetup (ForMonth,ForYear,ClassId) 
	SELECT MS.ForMonth, MS.ForYear,MS.ClassId FROM 
	sSetup.fMonthYearForBatchGET(@rBatchId) AS MY
	LEFT JOIN sAttendance.tMonthlySetup MS ON MS.BatchId=MY.BatchId AND (MS.ClassId=@lClassId) AND MS.ForMonth = MY.MonthNumber AND MS.ForYear = MY.YearNumber WHERE MY.BatchId=@rBatchId
 
	
	DECLARE @lCount int
	
	DECLARE @lCounter int,@lForMonth int,@lForYear int
	Select @lCount = MAX(Id) from #tempMonthlySetup
	
	 SET @lCounter = 1
	 IF (@lCount > 12) 
	 SET @lCount =12
	while (@lCounter <= @lCount)
	BEGIN
	 
	SELECT @lForMonth = ForMonth ,@lForYear = ForYear FROM #tempMonthlySetup WHERe Id = @lCounter
	
	



SET @lQuery = 'UPDATE YR    
    SET Month' +   convert(nvarchar(15),@lCounter)+  ' = MM.Code,
    TotalDays' +   convert(nvarchar(15),@lCounter)+  ' = MR.TotalCount,
    PresentDays' +   convert(nvarchar(15),@lCounter)+  ' = MR.PresentCount 
    from sAttendance.tYearlyRegister YR
    INNER JOIN sAttendance.tMonthlyRegister MR
    ON YR.AcademicId = MR.AcademicId
    AND MR.ForMonth = '  + convert(nvarchar(15),@lForMonth)  + ' AND MR.ForYear = ' + convert(nvarchar(15),@lForYear)  +
    ' INNER JOIN sCommon.tMonthMaster MM ON MM.Id = MR.ForMonth
    INNER JOIN sStudent.tAcademic A ON A.Id = MR.AcademicId 
    AND A.BatchId = ' +  convert(nvarchar(15),@rBatchId)  + ' AND A.ClassId = ' + convert(nvarchar(15),@lClassId) 
    

    
print @lQuery
execute(@lQuery)
	
	--IF 	(@lCounter = 1)
	--BEGIN
 
	--UPDATE YR    
 --   SET Month1  = MM.Title,TotalDays1 = MR.TotalCount,PresentDays1 = MR.PresentCount 
 --   from sAttendance.tYearlyRegister YR
 --   INNER JOIN sAttendance.tMonthlyRegister MR
 --   ON YR.AcademicId = MR.AcademicId
 --   AND MR.ForMonth = @lForMonth AND MR.ForYear = @lForYear
 --   INNER JOIN sCommon.tMonthMaster MM ON MM.Id = MR.ForMonth
 --   INNER JOIN sStudent.tAcademic A ON A.Id = MR.AcademicId 
 --   AND A.BatchId = @rBatchId AND A.ClassId = @lClassId
    
	--END
	--ELSE IF (@lCounter = 2)
	--BEGIN

	--UPDATE YR    
 --   SET Month2  = MM.Title,TotalDays2 = MR.TotalCount,PresentDays2 = MR.PresentCount 
 --   from sAttendance.tYearlyRegister YR
 --   INNER JOIN sAttendance.tMonthlyRegister MR
 --   ON YR.AcademicId = MR.AcademicId
 --   AND MR.ForMonth = @lForMonth ANd MR.ForYear = @lForYear
 --   INNER JOIN sCommon.tMonthMaster MM ON MM.Id = MR.ForMonth
 --   INNER JOIN sStudent.tAcademic A ON A.Id = MR.AcademicId 
 --   AND A.BatchId = @rBatchId AND A.ClassId = @lClassId
    
	--END
 
		SET @lCounter = @lCounter + 1
	END
	DROP TABLE #tempMonthlySetup
	SET @lClassCounter = @lClassCounter + 1
	END 

    UPDATE YR 
    SET TotalDays = (ISNULL(TotalDays1,0) + ISNULL(TotalDays2,0) + ISNULL(TotalDays3,0) + ISNULL(TotalDays4,0) + ISNULL(TotalDays5,0) + ISNULL(TotalDays6,0)
					+ ISNULL(TotalDays7,0) + ISNULL(TotalDays8,0) + ISNULL(TotalDays9,0) + ISNULL(TotalDays10,0) + ISNULL(TotalDays11,0) + ISNULL(TotalDays12,0)),
		PresentDays = ((ISNULL(PresentDays1,0) + ISNULL(PresentDays2,0) + ISNULL(PresentDays3,0) + ISNULL(PresentDays4,0) + ISNULL(PresentDays5,0) + ISNULL(PresentDays6,0)
					+ ISNULL(PresentDays7,0) + ISNULL(PresentDays8,0) + ISNULL(PresentDays9,0) + ISNULL(PresentDays10,0) + ISNULL(PresentDays11,0) + ISNULL(PresentDays12,0)))		
     FROM sAttendance.tYearlyRegister AS YR
    INNER JOIN sStudent.tAcademic A ON YR.AcademicId = A.Id
    WHERE  A.BatchId = @rBatchId
 
    UPDATE  YR
    
    SET YR.AvergeAttendance = (round(CAST(YR.PresentDays AS float)  / CAST(YR.TotalDays AS float),2)) * 100 
    FROM sAttendance.tYearlyRegister AS YR
    INNER JOIN sStudent.tAcademic A ON YR.AcademicId = A.Id	
    WHERE YR.TotalDays <> 0 AND A.BatchId = @rBatchId
    	 
	 DROP TABLE #tempClass
 
	
END
GO
PRINT N'Altering Procedure [sCertificate].[pRptBonafiedCertificateWithPreviousDetail]...';


GO

ALTER PROCEDURE [sCertificate].[pRptBonafiedCertificateWithPreviousDetail]

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

DECLARE @lIsOnPrePrinted bit = 0
DECLARE @lIsDisplayImageHeader bit=0
--added by megha for 0027170
DECLARE @lIsDisplayReligion bit=0
DECLARE @lIsShowPhoto bit = 0

DECLARE @lConfigValue nvarchar(50)

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 = 124 AND SourceTypeId = 1016 AND SourceId = @rOrgId
	
	IF (@lConfigValue IS NULL) OR (@lConfigValue = 'False')
	SET @lIsShowPhoto = 0
	ELSE
	SET @lIsShowPhoto = 1
--DECLARE @rStudentId bigint = 0
--SET @rStudentId = (SELECT Id FROM sStudent.tStudentMaster WHERE Code = @rCode)

	SELECT 	
			@rBuilder1 AS Builder1,
		    @rBuilder2 AS Builder2,
			B.Id,
			B.Number,
			B.AcademicId,
			SM.Code,
			   [sStudent].[fStudentNameGet](SM.FirstName , SM.MiddleName, SM.LastName,OM.StudentNameFormatId ) AS Name,
			CM.DisplayTitle+' - '+DM.DisplayTitle AS Class,
			BM.Title AS Batch,
			SM.FirstName,
			SM.MiddleName,
			SM.LastName,
			SO.DateOfBirth,
			ISNULL(SO.BirthDateInWord,'') AS DOBInWords,
			ISNULL(SO.BirthPlace,'') AS BirthPlace,
			ISNULL(SO.BirthTaluka,'') AS Taluka,
			ISNULL(SO.BirthDistrict,'')	AS District,		
			B.BonafideDate,
			ISNULL(SO.FamilyCast,'') AS Caste,
			ISNULL(SO.FamilySubCast,'') AS SubCaste,
			ISNULL(OM.CityName,'') AS City,
			ISNULL(OM.StateName,'') AS CityState,
			SO.GenderId,
			OM.OrgLogo,
			OM.Title AS OrgTitle,
			SM.StatusId,
			A.RollNo,
			DM.OrderIndex AS DivisionOrder,
			OM.ReportOrgTitle,
			OM.RegistrationDetail,
			ISNULL(RM.Title,'') AS ReligionName,
			B.Remark AS ReceiptNo,
			SA.AdmissionDate,
			DP.Title AS DepartmentName,
			REPLICATE(',',OM.LetterHeadMargin)    AS LetterHeadMargin,
			CT.Title AS Category,
			CM.DisplayTitle AS ClassName,
			OM.PrincipalSignature,
			DM.DisplayTitle AS Divisionname, 
			CM1.Title AS AdmissionStandard,
			ISNULL(OM.ReportOrgGroupTitle,'') AS ReportOrgGroupTitle,
			OM.ReportOrgTitle,
			SM.Id AS StudentId,
			SA.LeftDate AS LeftDate,
			OI.CertificateHeaderA4Portrait AS CertificateHeaderA4,
			@lIsOnPrePrinted AS IsOnPrePrinted,
			@lIsDisplayImageHeader AS IsDisplayImageHeader,
			OM.SmallAddress1,
			OM.SmallAddress2,
			@lIsDisplayReligion AS IsDisplayReligion
	FROM 
			sStudent.tAcademic A
			
			
			LEFT JOIN sCertificate.tBonafide B ON B.AcademicId = A.Id 
			INNER JOIN sStudent.tStudentMaster SM ON SM.Id=A.StudentId
			LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId=A.StudentId
			LEFT JOIN sSetup.tDivisionMaster DM ON A.DivisionId = DM.Id  
			LEFT JOIN sSetup.tClassMaster CM ON CM.Id= A.ClassId
			LEFT JOIN sSetup.tBatchMaster BM ON BM.Id=A.BatchId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=A.OrgId
			LEFT JOIN sSetup.tOrgImages OI ON OI.OrgId = OM.Id
			LEFT JOIN sCommon.tReligionMaster RM ON SO.ReligionId=RM.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 
	WHERE 
			A.OrgId=@rOrgId
			AND ((SM.FirstName = @rName) OR (ISNULL(@rName,'') = ''))
			--AND ((B.Number=@rNumber) OR (@rNumber=''))
			AND ((B.Number >= @rFromNo) OR (@rFromNo=''))  
			AND ((B.Number <= @rToNo) OR (@rToNo=''))
			AND ((B.BonafideDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
			AND ((B.BonafideDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
			AND ((SM.Code = @rCode) OR (ISNULL(@rCode,'')=''))
			AND ((A.ClassId=@rClassId) OR (@rClassId=0))
			AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId=0))
			ORDER BY B.BonafideDate DESC
	END
GO
PRINT N'Altering Procedure [sFee].[pConsolidateFeeStatusDashboardGet]...';


GO
 
ALTER PROCEDURE [sFee].[pConsolidateFeeStatusDashboardGet]
	@rType int =0,
	@rCommonOrgGroupBatchId int=0,
	@rOrgGroupId smallint=0,
	@rReceiptBookId int =0,
	@rOrgId int  =0,
	@rFeeHeadId int =0,
	@rFeeId int =0
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 

IF (@rType = 1)
	BEGIN
		SELECT * 
		INTO #TempFeeSetupData
		FROM 
		(
			SELECT 
				FS1.FeeId,
				FS1.Id,
				ISNULL(FS1.Amount,0)AS Amount,
				ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
				FM.Title AS FeeName,
				SA1.AcademicId,
				FM.FeeHeadId
			FROM sFee.tFeeSetup FS1
			INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
			INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
			WHERE FS1.IsOptional=0

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

		SELECT 
			RBM.Id AS ReceiptBookId,
			RBM.Title AS ReceiptBook,
			SUM(ISNULL(R.PaidAmount,0)) AS PaidAmount,
			SUM(ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00))AS PendingAmount,
			SUM(ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)) AS Total,
			RBM.OrderIndex
		FROM 
			sStudent.vStudentAcademic SA
			INNER JOIN sStudent.tStudentAdmission tSA ON tSA.StudentId = SA.StudentId
			INNER JOIN #TempFeeSetupData FS ON FS.AcademicId=SA.AcademicId
			LEFT JOIN sFee.tFeeAllocation FA ON FA.FeeSetupId=FS.Id AND FA.SourceId=SA.AcademicId
			LEFT JOIN
			(
				SELECT ISNULL(SUM(RD.Amount),0) AS PaidAmount,RD.FeeSetupId ,R.SourceId
				FROM
					sFee.tReceipt R 
					INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id 
					INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id
					INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id
					INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=R.SourceId 
					INNER JOIN sStudent.tStudentAdmission tSA ON tSA.StudentId = SA1.StudentId
					INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SA1.OrgId
					INNER JOIN sSetup.tOrgGroupMaster OMM ON OMM.Id = OM.OrgGroupId 
					INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=SA1.OrgGroupBatchId
					INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
				WHERE		
					(R.SourceTypeId = 2001) AND (R.IsObsolete = 0) 
					AND COGBM.Id = @rCommonOrgGroupBatchId
					AND((OMM.Id = @rOrgGroupId) OR (@rOrgGroupId = 0))
				GROUP BY FeeSetupId,R.SourceId
			) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
			LEFT JOIN sHostel.tAssignRoom AR ON  AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003  
			LEFT JOIN (
				SELECT AT.SourceId FROM sTransport.tAssignRoute AT 
				INNER JOIN sTransport.tBusRouteDestinationMaster BM ON BM.Id=AT.PickupDestinationId
				INNER JOIN sTransport.tBusRouteMaster B ON B.Id=BM.BusRouteId AND  AT.SourceTypeId=2003
				INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=B.OrgGroupBatchId
				INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
				WHERE COGBM.Id = @rCommonOrgGroupBatchId
			) RT ON RT.SourceId = SA.StudentId 
			INNER JOIN sSetup.tOrganizationMaster O ON SA.OrgId = O.Id
			INNER JOIN sFee.tReceiptBookMaster RBM ON FS.ReceiptBookId=RBM.Id
			INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FS.FeeHeadId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SA.OrgId
			INNER JOIN sSetup.tOrgGroupMaster OMM ON OMM.Id = OM.OrgGroupId 
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=SA.OrgGroupBatchId
			INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
		WHERE  
			COGBM.Id = @rCommonOrgGroupBatchId
			AND((OMM.Id = @rOrgGroupId) OR (@rOrgGroupId = 0))
		GROUP BY RBM.Title,RBM.Id,RBM.OrderIndex
		Order By RBM.OrderIndex, RBM.Id

		DROP TABLE #TempFeeSetupData
	END
ELSE IF (@rType = 11)
	BEGIN
		SELECT 
			ISNULL(SA.AcademicId,0) AS SourceId,
			ISNULL(SA.ClassName,'') AS ClassName,
			ISNULL(SA.DivisionId,0) AS DivisionId,
			ISNULL(SA.DivisionName,'') AS DivisionName,
			ISNULL(SA.ClassName+'-'+SA.DivisionName,'') AS ClassDivision,
			ISNULL(SA.Code,'') As Code,
			ISNULL(SA.Name,'') AS Name,
			ISNULL(SC.ParentContactNo,'') AS ParentContactNo,
			SUM(ISNULL(R.PaidAmount,0)) AS PaidAmount,
			SA.ClassOrderIndex,  
			SA.DivisionOrder,
			SA.RollNo 
		FROM 
			sStudent.vStudentAcademic SA
			INNER JOIN sStudent.tStudentAdmission tSA ON tSA.StudentId = SA.StudentId
			LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId = SA.StudentId
			INNER JOIN 
			(
				SELECT 
					FS1.FeeId,
					FS1.Id,
					ISNULL(FS1.Amount,0)AS Amount,
					ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
					FM.Title AS FeeName,
					SA1.AcademicId,
					FM.FeeHeadId
				FROM sFee.tFeeSetup FS1
				INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
		
				WHERE 
					(FS1.IsOptional=0)

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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


GO


ALTER PROCEDURE [sFee].[pFeeExportDetailsGet]    
      
  @rOrgGroupBatchId int,    
  @rAdmissionCategoryId int,    
  @rClassId int,    
  @rDivisionId int,    
  @rIdNo nvarchar(20)='',    
  @rFirstName nvarchar(100)='',    
  @rFromReceiptNumber int=0,    
  @rToReceiptNumber int=0,    
  @rReceiptBookId int=0,    
  @rSourceTypeId int=0,    
  @rPayTypeId int,    
  @rChequeNo nvarchar(40)='',    
  @rFromDate date,    
  @rToDate date,    
  @rIsObsolete bit,    
  @rOrgId smallint,    
  @rBatchId int,    
  @rOrgGroupId smallint,    
  @rCreatedUserName nvarchar(100),    
  @rCreatedUserId bigint,    
  @rDepartmentId int=0,    
  @rFromChequeDate date='',    
  @rToChequeDate date='',    
  @rSUId nvarchar(50) = '',    
  @rLastName nvarchar(100) = '',  
  @rPayTypeIds nvarchar(max) = '',
  @rBankName nvarchar(100)='',
  @rCancelStatusId int = 0
      
 WITH EXECUTE AS CALLER    
AS    
SET NOCOUNT ON    
        
    BEGIN    
		SET @rFirstName = sCommon.fSearchStringGet(@rFirstName)    
		SET @rLastName = sCommon.fSearchStringGet(@rLastName)    
		SET @rCreatedUserName = sCommon.fSearchStringGet(@rCreatedUserName)   
		SET @rBankName = sCommon.fSearchStringGet(@rBankName)    
    END 
	
BEGIN       

CREATE Table #FeeReceiptDetail
		(
		StatusId bigint,
		ReceiptId bigint,
		FeeCode nvarchar(100),
		FeeAmount decimal(12,2),
		Organization nvarchar(max),
		Batch nvarchar(100),
		BatchId bigint,
		Code nvarchar(20),
		ClassDiv nvarchar(200),
		Name nvarchar(300),
		ReceiptNumber nvarchar(200),
		ReceiptDate nvarchar(50),
		ReceiptAmount decimal(12,2),
		PayType nvarchar(300),
		ChequeNo nvarchar(40),
		Remark nvarchar(max),
		ChequeDate nvarchar(50),
		InvoiceNumber int,
		ReceiptCreatedDateTime datetime,
		BankName nvarchar(200),
		ReceiptBookName nvarchar(100),
		TotalReceiptAmount decimal(12,2),
		DiscountAmount decimal(12,2),
		VariableAmount decimal(12,2),
		ExemptionAmount decimal(12,2),
		AdditionalAmount decimal(12,2),
		NotApplicableAmount decimal(12,2),
		SUId nvarchar(50)
		
		)


INSERT INTO #FeeReceiptDetail
 SELECT 
    A.StatusId,    
	R.Id AS ReceiptId,
	FM.Code,
	RD.Amount,
	OM.DisplayTitle AS Organization,  
	BM.Title AS Batch,
	BM.Id AS BatchId,
	A.Code AS Code, 
	CM.Title +' - '+ DM.Title AS ClassDiv,
	A.Name,    
	R.ReceiptNumber,   
	--change by megha for mentis 0027171 start
	--R.ReceiptDate,   
	CONVERT(VARCHAR(10), R.ReceiptDate, 103) AS ReceiptDate, 
   --end
	ISNULL(R.ReceiptAmount,0)AS ReceiptAmount,
	PTM.Title AS PayType,    
	CASE WHEN ISNULL(R.ChequeNo,'') != '' THEN R.ChequeNo ELSE CONVERT(nvarchar(20),R.PaymentTransactionId) END AS ChequeNo,    
	R.Remark,
	CONVERT(VARCHAR(10), R.ChequeDate, 103)AS ChequeDate, 
	--ISNULL(CAST(R.ChequeDate AS Date),'') AS ChequeDate, 
	ISNULL(FI.InvoiceNumber,0) AS InvoiceNumber,    
	R.CreatedDateTime AS ReceiptCreatedDateTime,
	R.BankName,    
	RBM.Title AS ReceiptBook,    
    ISNULL(R.TotalReceiptAmount,0)AS TotalReceiptAmount,    
    ISNULL(R.DiscountAmount,0)AS DiscountAmount,
	FA.VariableAmount,
	FA.DiscountAmount AS ExemptionAmount,
	FA.AdditionalAmount,
	FA.NotApplicableAmount,
	ISNULL(A.SUId,'') As SUId
	
  
  FROM     
  
     sFee.tReceipt R    
  INNER JOIN sStudent.vStudentAcademic A    
   ON A.AcademicId=R.SourceId AND (A.AdmissionCategoryId=@rAdmissionCategoryId OR @rAdmissionCategoryId=0)   
   
  INNER JOIN  sSetup.tClassMaster CM ON CM.Id = A.ClassId     
  INNER JOIN  sSetup.tDivisionMaster DM ON DM.Id = A.DivisionId     
  INNER JOIN sCommon.tSourceTypeMaster STM    
   ON STM.Id=R.SourceTypeId    
  INNER JOIN sFinanceCommon.tPayTypeMaster PTM    
   ON PTM.Id=R.PayTypeId    
  INNER JOIN sFee.tReceiptBookMaster RBM    
   ON RBM.Id=R.ReceiptBookId    
  INNER JOIN sSetup.tOrganizationMaster OM    
   ON OM.Id=A.OrgId    
    AND OM.OrgGroupId=@rOrgGroupId    
  INNER JOIN sSetup.tBatchMaster BM    
   ON BM.Id=R.BatchId     
   AND BM.OrgGroupBatchId=@rOrgGroupBatchId    
  LEFT JOIN sSecurity.tUser U ON U.Id=R.CreatedUserId    
  INNER JOIN sFee.vUserReceiptBook URB ON URB.Id=RBM.Id AND URB.UserId=@rCreatedUserId    
  LEFT JOIN sFee.tFeeInvoice FI ON FI.Id = R.FeeInvoiceId    
  
  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
  LEFT JOIN sFee.tFeeAllocation FA ON FA.FeeSetupId=FS.Id AND FA.SourceId=A.AcademicId
  
WHERE     
 ((A.Code like @rIdNo) OR (ISNULL(@rIdNo,'')=''))    
 AND (R.SourceTypeId=2001)    
 AND ((A.FirstName like @rFirstName) OR(ISNULL(@rFirstName,'')=''))    
 AND ((R.ReceiptNumber>=@rFromReceiptNumber)OR(@rFromReceiptNumber=0))    
 AND ((R.ReceiptNumber<=@rToReceiptNumber)OR(@rToReceiptNumber=0))    
 AND ((R.ReceiptBookId=@rReceiptBookId)OR(@rReceiptBookId=0))    
 AND ((R.PayTypeId=@rPayTypeId)OR(@rPayTypeId=0))    
 AND ((ISNULL(R.PayTypeId,0) IN ( SELECT cast(item as int) FROM  sCommon.fnsplit(@rPayTypeIds,','))) OR (ISNULL(@rPayTypeIds,'')=''))
 AND ((R.ChequeNo like @rChequeNo) OR(ISNULL(@rChequeNo,'')=''))    
 AND ((STM.Id=@rSourceTypeId)OR(@rSourceTypeId=0))    
 AND ((R.ReceiptDate>=@rFromDate)OR(ISNULL(@rFromDate,'')=''))    
 AND ((R.ReceiptDate<=@rToDate)OR(ISNULL(@rToDate,'')=''))    
 AND (R.IsObsolete=@rIsObsolete)    
 AND ((A.OrgId=@rOrgId) OR (@rOrgId=0))    
 AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))    
 AND ((ISNULL(U.DisplayTitle,'') like @rCreatedUserName) OR (ISNULL(@rCreatedUserName,'')=''))    
 AND ((CM.DepartmentId = @rDepartmentId) OR (@rDepartmentId=0))    
 AND ((A.ClassId=@rClassId) OR (@rClassId=0))     
 AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId=0))    
 AND ((R.ChequeDate>=@rFromChequeDate)OR(ISNULL(@rFromChequeDate,'')=''))    
 AND ((R.ChequeDate<=@rToChequeDate)OR(ISNULL(@rToChequeDate,'')=''))    
 AND ((A.SUId like @rSUId) OR (ISNULL(@rSUId,'')=''))    
 AND ((A.LastName like @rLastName) OR (ISNULL(@rLastName,'')=''))  
 AND ((R.BankName like @rBankName) OR(ISNULL(@rBankName,'')=''))    
 AND ((R.CancelStatusId = @rCancelStatusId) OR(@rCancelStatusId=0)) ----Added By Dhruv for Issue No.11130    
 ORDER BY R.ReceiptNumber DESC   
 
 --Select * from #FeeReceiptDetail
 DECLARE @cols AS NVARCHAR(MAX),@query  AS NVARCHAR(MAX)

    SELECT @cols = STUFF((SELECT  DISTINCT ',' + QUOTENAME(ID.FeeCode)
                       FROM #FeeReceiptDetail ID FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'),1,1,'')   
 
    SELECT @query = 
    'SELECT  
			P.*,
            ID.VariableAmount,
            ID.ExemptionAmount,
            ID.AdditionalAmount,
            ID.NotApplicableAmount ,
			ID.DiscountAmount
     FROM
    (SELECT  
	
		ReceiptId ,
		Organization ,
		Batch ,
		Code ,
		SUId,
		ClassDiv ,
		Name ,
		ReceiptNumber ,
		ReceiptDate ,
		ReceiptAmount ,
		Remark,
		PayType ,
		ChequeNo ,
		ChequeDate, 
		BankName ,
		ReceiptBookName ,
		InvoiceNumber,    
		ReceiptCreatedDateTime,
		TotalReceiptAmount ,
		FeeCode, 
        FeeAmount
				    		
    FROM #FeeReceiptDetail)X
    PIVOT 
    (
         SUM(FeeAmount) 
         FOR [FeeCode] IN (' +  @cols + ')
    ) P
    LEFT JOIN
	(
		SELECT
		    ReceiptId,
			SUM(VariableAmount) AS VariableAmount,
			SUM(ExemptionAmount) AS ExemptionAmount,
			SUM(AdditionalAmount) AS AdditionalAmount,
			SUM(NotApplicableAmount) AS NotApplicableAmount,
			(DiscountAmount) AS DiscountAmount
		FROM  
			#FeeReceiptDetail
			GROUP BY ReceiptId,DiscountAmount
    ) ID ON ID.ReceiptId = P.ReceiptId
	Order By P.ReceiptNumber DESC
    '
	EXECUTE(@query) 
END
GO
PRINT N'Altering Procedure [sFee].[pFeeSummaryDashboard]...';


GO
ALTER PROCEDURE [sFee].[pFeeSummaryDashboard]
	@rType nvarchar(20)='',
	@rOrgId int =0,
	@rBatchId int=0,
	@rDepartmentId int =0
	--@rLibraryId int =0
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON			 
BEGIN 

	--DECLARE @lAdmissionCategoryId int =  0
	--SET @lAdmissionCategoryId = [sCommon].[fGetIntIdForOrg](1,@rOrgId)
	
	if object_id('tempdb..#tTable') is not null
			BEGIN
				DROP TABLE #tTable
			END
		Create table #tTable(
			AcademicId bigint not null
		)
		Insert into #tTable
			select SA.AcademicId 
			FROM sFee.tFeeSetup FS
			INNER JOIN sStudent.vStudentAcademic SA ON SA.ClassId=FS.ClassId AND FS.BatchId = SA.BatchId AND SA.AdmissionCategoryId = FS.AdmissionCategoryId
			where ((SA.OrgId=@rOrgId)OR(@rOrgId=0)) AND ((SA.BatchId=@rBatchId) OR (@rBatchId=0))AND SA.StatusId =1
			-- AND SA.AdmissionCategoryId=@lAdmissionCategoryId
			group by FS.ClassId,SA.AcademicId 

		--Create Table #ttemptable1
		--	(
		--		AcademicId bigint,
		--		PaidAmount int,
		--		PendingAmount int
		--	)
		--	Insert into #ttemptable1
		--	(
		--		AcademicId,
		--		PaidAmount,
		--		PendingAmount
		--	)
		--	Select SA.AcademicId , SUM(SF.PaidAmount) AS PaidAmount , SUM(SF.PendingAmount) AS PendingAmount
		--	From sStudent.vStudentAcademic SA 
		--	Inner Join sFee.tStudentFee SF ON SA.AcademicId=SF.AcademicId
		--	where SA.OrgId=9911 AND SA.BatchId=991100104
		--	Group by SA.AcademicId


	IF(@rType = 'FeeList')
		BEGIN

		CREATE TABLE #tmp
		(
			AcademicId bigint,
			Amount decimal(12,2),
			VariableAmount decimal(12,2),
			AdditionalAmount decimal(12,2),
			DiscountAmount decimal(12,2),
			NotApplicableAmount decimal(12,2)
		)
		INSERT INTO #tmp
			Select SA.AcademicId  AS AcademicId 
			, SUM(FS1.Amount) AS Amount , Sum(FA1.VariableAmount) AS VariableAmount, SUM(FA1.AdditionalAmount)AS AdditionalAmount,SUM(FA1.DiscountAmount)AS DiscountAmount,
			SUM(FA1.NotApplicableAmount)AS NotApplicableAmount
			From sStudent.vStudentAcademic SA

			--Changes for pending fee minus count for mantis Id :0027388
			--LEFT JOIN sFee.tFeeAllocation FA1 ON FA1.SourceId = SA.AcademicId
			--LEFT JOIN sFee.tFeeSetup FS1 ON FA1.FeeSetupId = FS1.Id AND FS1.BatchId = SA.BatchId AND FS1.ClassId = SA.ClassId AND FS1.AdmissionCategoryId = SA.AdmissionCategoryId
			LEFT JOIN sFee.tFeeSetup FS1 ON FS1.BatchId = SA.BatchId  AND FS1.ClassId = SA.ClassId AND FS1.AdmissionCategoryId = SA.AdmissionCategoryId
			LEFT JOIN sFee.tFeeAllocation FA1 ON FA1.SourceId = SA.AcademicId AND FS1.Id = FA1.FeeSetupId
			INNER JOIN #tTable tmp1 ON tmp1.AcademicId = SA.AcademicId
		
			Where
			((SA.OrgId=@rOrgId)OR(@rOrgId=0)) AND ((SA.BatchId=@rBatchId) OR (@rBatchId=0))AND SA.StatusId =1
			group by FS1.ClassId,SA.AcademicId 

			SELECT COUNT(SA.AcademicId)AS TotalCount,COUNT(T.PaidCount) AS PaidCount,(COUNT(tmp.AcademicId)-COUNT(T.PaidCount))AS UnPaidCount
			, COUNT(PS.AcademicId) AS PartialCount
			FROM sStudent.vStudentAcademic SA 
			LEFT JOIN #tmp tmp ON SA.AcademicId = tmp.AcademicId 
			AND ISNULL(((ISNULL(Amount,0) + ISNULL(VariableAmount,0)+ ISNULL(0,AdditionalAmount)) - (DiscountAmount + NotApplicableAmount)),1) <> 0 
			INNER JOIN sStudent.tAdmissionCategoryMaster ACM ON SA.AdmissionCategoryId = ACM.Id
			Inner Join #tTable FS  on  FS.AcademicId=SA.AcademicId
			LEFT JOIN(
			SELECT COUNT(R.Id)as PaidCount,SA.AcademicId AS AcademicId FROM sFee.tReceipt R
			INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.SourceId 
			WHERE R.SourceTypeId = 2001 AND((SA.OrgId=@rOrgId) OR (@rOrgId=0))
			AND ((R.BatchId=@rBatchId) OR (@rBatchId=0)) AND (R.IsObsolete = 0) 
			GROUP BY SA.AcademicId
			)T ON T.AcademicId = SA.AcademicId 

			LEFT JOIN 
			(
				SELECT 
					SA1.AcademicId 
				FROM sFee.tFeeSetup FS1
				INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				LEFT JOIN sFee.tFeeAllocation FA ON FA.FeeSetupId=FS1.Id AND FA.SourceId=SA1.AcademicId
				LEFT JOIN 
				(
				SELECT SUM(RD.Amount) as Amount,R.SourceId,FS.Id AS FeeSetupId
				FROM sFee.tReceiptDetail RD
				INNER JOIN sFee.tReceipt R ON RD.ReceiptId = R.Id
				INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id
				WHERE R.SourceTypeId = 2001
				AND (R.IsObsolete = 0) 
				AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
				Group By R.SourceId,FS.Id
				) R ON R.SourceId = SA1.AcademicId AND R.FeeSetupId = FS1.Id
				INNER JOIN 
				(
				SELECT Distinct SourceId 
				FROM sFee.tReceipt 
				) RE ON RE.SourceId = SA1.AcademicId
				WHERE 
					((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
					AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
					AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
					AND SA1.StatusId =1
					AND FS1.IsOptional = 0
					AND ISNULL(FS1.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.Amount,0.00) > 0
					
				UNION 

				SELECT 
					SA1.AcademicId 
				FROM sFee.tFeeSetup FS1
				INNER JOIN sFee.tFeeOptional FO ON FO.FeeSetupId=FS1.Id 
				INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId AND SA1.AcademicId=FO.SourceId
				LEFT JOIN sFee.tFeeAllocation FA ON FA.FeeSetupId=FS1.Id AND FA.SourceId=SA1.AcademicId
				LEFT JOIN 
				(
				SELECT SUM(RD.Amount) as Amount,R.SourceId,FS.Id AS FeeSetupId
				FROM sFee.tReceiptDetail RD
				INNER JOIN sFee.tReceipt R ON RD.ReceiptId = R.Id
				INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id
				WHERE R.SourceTypeId = 2001
				AND (R.IsObsolete = 0) 
				AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
				Group By R.SourceId,FS.Id
				) R ON R.SourceId = SA1.AcademicId AND R.FeeSetupId = FS1.Id
				INNER JOIN 
				(
				SELECT Distinct SourceId 
				FROM sFee.tReceipt 
				) RE ON RE.SourceId = SA1.AcademicId
				WHERE 
					((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
					AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
					AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
					AND SA1.StatusId =1
					AND FS1.IsOptional = 1
					AND ISNULL(FS1.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.Amount,0.00) > 0
					
			) PS ON PS.AcademicId=SA.AcademicId

			WHERE ((SA.OrgId=@rOrgId) OR (@rOrgId=0))
			AND SA.StatusId =1
			AND ((SA.BatchId=@rBatchId) OR (@rBatchId=0))
			--AND ACM.Code Like '%General%' 
			--AND ACM.ID = @lAdmissionCategoryId 
			AND ACM.IsObsolete = 0	
			DROP TABLE  #tmp
		END
	ELSE IF(@rType = 'FeeGraph')
		BEGIN
		
		CREATE TABLE #tmpData
		(
			AcademicId bigint,
			Amount decimal(12,2),
			VariableAmount decimal(12,2),
			AdditionalAmount decimal(12,2),
			DiscountAmount decimal(12,2),
			NotApplicableAmount decimal(12,2)
		)
		INSERT INTO #tmpData
			Select SA.AcademicId  AS AcademicId 
			, SUM(FS1.Amount) AS Amount , Sum(FA1.VariableAmount) AS VariableAmount, SUM(FA1.AdditionalAmount)AS AdditionalAmount,SUM(FA1.DiscountAmount)AS DiscountAmount,
			SUM(FA1.NotApplicableAmount)AS NotApplicableAmount
			From sStudent.vStudentAcademic SA

			--Changes for pending fee minus count for mantis Id :0027388
			--LEFT JOIN sFee.tFeeAllocation FA1 ON FA1.SourceId = SA.AcademicId
			--LEFT JOIN sFee.tFeeSetup FS1 ON FA1.FeeSetupId = FS1.Id AND FS1.BatchId = SA.BatchId AND FS1.ClassId = SA.ClassId AND FS1.AdmissionCategoryId = SA.AdmissionCategoryId
			LEFT JOIN sFee.tFeeSetup FS1 ON FS1.BatchId = SA.BatchId  AND FS1.ClassId = SA.ClassId AND FS1.AdmissionCategoryId = SA.AdmissionCategoryId
			LEFT JOIN sFee.tFeeAllocation FA1 ON FA1.SourceId = SA.AcademicId AND FS1.Id = FA1.FeeSetupId
			INNER JOIN #tTable tmp1 ON tmp1.AcademicId = SA.AcademicId
		
			Where
			((SA.OrgId=@rOrgId)OR(@rOrgId=0)) AND ((SA.BatchId=@rBatchId) OR (@rBatchId=0))AND SA.StatusId =1
			group by FS1.ClassId,SA.AcademicId 


		SELECT CM.Id,CM.Title,ISNULL(T.TotalCount,0)AS TotalCount,COUNT(T1.PaidCount) AS PaidCount,(COUNT(tmpData.AcademicId)-COUNT(T1.PaidCount))AS UnPaidCount,CM.OrderIndex
			FROM sStudent.vStudentAcademic SA
			LEFT JOIN #tmpData tmpData ON SA.AcademicId = tmpData.AcademicId 
			AND ISNULL(((ISNULL(Amount,0) + ISNULL(VariableAmount,0)+ ISNULL(0,AdditionalAmount)) - (DiscountAmount + NotApplicableAmount)),1) <> 0 
			INNER JOIN sStudent.tAdmissionCategoryMaster ACM ON SA.AdmissionCategoryId = ACM.Id
			LEFT JOIN sSetup.tClassMaster CM ON  CM.Id = SA.ClassId
			LEFT JOIN 
			(SELECT COUNT(SA1.AcademicId) AS TotalCount,SA1.ClassId AS ClassId FROM sStudent.vStudentAcademic SA1
			INNER JOIN sStudent.tAdmissionCategoryMaster ACM1 ON SA1.AdmissionCategoryId = ACM1.Id
			Inner Join #tTable temp on SA1.AcademicId=temp.AcademicId
			WHERE ((SA1.OrgId=@rOrgId)OR(@rOrgId=0)) AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))AND SA1.StatusId =1
			--AND ACM1.Code Like '%General%' AND ACM1.IsObsolete = 0	
			--AND ACM1.ID = @lAdmissionCategoryId 
			AND ACM1.IsObsolete = 0
			GROUP BY ClassId
			)T ON T.ClassId = CM.Id	
			LEFT JOIN(
			SELECT COUNT(SA.AcademicId)as PaidCount,SA.AcademicId AS AcademicId,SA.ClassId AS ClassId FROM sFee.tReceipt R
			INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.SourceId 
			INNER JOIN sStudent.tAdmissionCategoryMaster ACM ON SA.AdmissionCategoryId = ACM.Id
			LEFT JOIN sSetup.tClassMaster CM ON  CM.Id = SA.ClassId
			WHERE R.SourceTypeId = 2001 AND((SA.OrgId=@rOrgId) OR (@rOrgId=0))AND SA.StatusId =1
			--AND ACM.Code Like '%General%' AND ACM.IsObsolete = 0
			--AND ACM.ID = @lAdmissionCategoryId 
			AND ACM.IsObsolete = 0		
			AND ((R.BatchId=@rBatchId) OR (@rBatchId=0)) AND (R.IsObsolete = 0) 
			GROUP BY SA.AcademicId,SA.ClassId
			)T1 ON T1.AcademicId = SA.AcademicId  AND CM.Id = SA.ClassId
			WHERE ((CM.OrgId =@rOrgId)OR(@rOrgId=0))
			AND SA.StatusId =1
			--AND ACM.ID = @lAdmissionCategoryId 
			AND ACM.IsObsolete = 0
			--AND ACM.Code Like '%General%' AND ACM.IsObsolete = 0	
			GROUP BY CM.Title, CM.Id,T.TotalCount,CM.OrderIndex
			ORDER BY CM.OrderIndex

			DROP TABLE #tmpData
		
		END
	ELSE IF (@rType = 'FeeListDetails')
		BEGIN
		SELECT F.RollNo,F.Name,F.Code,F.Pending,F.[Partial],F.[Status],F.ClassDivision
		FROM
		(

		SELECT SA.RollNo,SA.Name,SA.Code, ISNULL(T.AcademicId,0) AS Pending, ISNULL(PS.AcademicId,0) AS [Partial],'' AS [Status]
			,SA.ClassName+'/'+SA.DivisionName AS ClassDivision,
			(
				Select (SUM(FS1.Amount)+Sum(FA1.VariableAmount)+ SUM(FA1.AdditionalAmount)) - (SUM(FA1.DiscountAmount)+ SUM(FA1.NotApplicableAmount)) 
				From sFee.tFeeAllocation FA1
				INNER JOIN sFee.tFeeSetup FS1 ON FS1.BatchId = SA.BatchId AND FS1.ClassId = SA.ClassId AND FS1.AdmissionCategoryId = SA.AdmissionCategoryId AND FA1.FeeSetupId = FS1.Id
				Where FA1.SourceId = SA.AcademicId 
			) AS IsFeePayAmount
			--,ISNULL(FS1.PaidAmount,0) AS PaidAmount ,ISNULL(FS1.PendingAmount,0)AS PendingAmount
			FROM sStudent.vStudentAcademic SA 
			Inner Join #tTable FS  on  FS.AcademicId=SA.AcademicId
			--LEFT Join #ttemptable1 FS1 ON FS1.AcademicId=SA.AcademicId
			LEFT JOIN(
			SELECT COUNT(R.Id)as PaidCount,SA.AcademicId AS AcademicId, SA.Code,SA.Name FROM sFee.tReceipt R
			INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.SourceId 
			WHERE R.SourceTypeId = 2001 AND((SA.OrgId=@rOrgId) OR (@rOrgId=0))
			AND ((R.BatchId=@rBatchId) OR (@rBatchId=0)) AND (R.IsObsolete = 0) 
			GROUP BY SA.AcademicId, SA.Code,SA.Name
			)T ON T.AcademicId = SA.AcademicId
			LEFT JOIN 
			(
				SELECT 
					SA1.AcademicId 
				FROM sFee.tFeeSetup FS1
				INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				LEFT JOIN sFee.tFeeAllocation FA ON FA.FeeSetupId=FS1.Id AND FA.SourceId=SA1.AcademicId
				LEFT JOIN 
				(
				SELECT SUM(RD.Amount) as Amount,R.SourceId,FS.Id AS FeeSetupId
				FROM sFee.tReceiptDetail RD
				INNER JOIN sFee.tReceipt R ON RD.ReceiptId = R.Id
				INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id
				WHERE R.SourceTypeId = 2001
				AND (R.IsObsolete = 0) 
				AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
				Group By R.SourceId,FS.Id
				) R ON R.SourceId = SA1.AcademicId AND R.FeeSetupId = FS1.Id
				INNER JOIN 
				(
				SELECT Distinct SourceId 
				FROM sFee.tReceipt 
				) RE ON RE.SourceId = SA1.AcademicId
				WHERE 
					((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
					AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
					AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
					AND SA1.StatusId =1
					AND FS1.IsOptional = 0
					AND ISNULL(FS1.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.Amount,0.00) > 0
					
				UNION 

				SELECT 
					SA1.AcademicId 
				FROM sFee.tFeeSetup FS1
				INNER JOIN sFee.tFeeOptional FO ON FO.FeeSetupId=FS1.Id 
				INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId AND SA1.AcademicId=FO.SourceId
				LEFT JOIN sFee.tFeeAllocation FA ON FA.FeeSetupId=FS1.Id AND FA.SourceId=SA1.AcademicId
				LEFT JOIN 
				(
				SELECT SUM(RD.Amount) as Amount,R.SourceId,FS.Id AS FeeSetupId
				FROM sFee.tReceiptDetail RD
				INNER JOIN sFee.tReceipt R ON RD.ReceiptId = R.Id
				INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id
				WHERE R.SourceTypeId = 2001
				AND (R.IsObsolete = 0) 
				AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
				Group By R.SourceId,FS.Id
				) R ON R.SourceId = SA1.AcademicId AND R.FeeSetupId = FS1.Id
				INNER JOIN 
				(
				SELECT Distinct SourceId 
				FROM sFee.tReceipt 
				) RE ON RE.SourceId = SA1.AcademicId
				WHERE 
					((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
					AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
					AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
					AND SA1.StatusId =1
					AND FS1.IsOptional = 1
					AND ISNULL(FS1.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.Amount,0.00) > 0
					
			) PS ON PS.AcademicId=SA.AcademicId


			WHERE ((SA.OrgId=@rOrgId) OR (@rOrgId=0))
			AND SA.StatusId =1
			AND ((SA.BatchId=@rBatchId) OR (@rBatchId=0))	 			
			) AS F 
			WHERE ISNULL(F.IsFeePayAmount,1) <> 0
		END

	ELSE IF(@rType='FeeCollection')
		BEGIN
			SELECT Isnull(Sum(R.ReceiptAmount),0.00) as TodayCollection 
			FROM sFee.tReceipt R
				INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.SourceId 
			WHERE R.SourceTypeId = 2001 AND((SA.OrgId=@rOrgId) OR (@rOrgId=0))
				AND ((R.BatchId=@rBatchId) OR (@rBatchId=0)) AND (R.IsObsolete = 0) 
				AND ((SA.OrgId=@rOrgId) OR (@rOrgId=0))
				AND SA.StatusId =1
				AND ((SA.BatchId=@rBatchId) OR (@rBatchId=0))
				AND (R.ReceiptDate=CAST(GETDATE() as DATE))

			SELECT ISNULL(Sum(R.ReceiptAmount),0.00) as MonthlyCollection 
			FROM sFee.tReceipt R
				INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.SourceId 
			WHERE R.SourceTypeId = 2001 AND((SA.OrgId=@rOrgId) OR (@rOrgId=0))
				AND ((R.BatchId=@rBatchId) OR (@rBatchId=0)) AND (R.IsObsolete = 0) 
				AND ((SA.OrgId=@rOrgId) OR (@rOrgId=0))
				AND SA.StatusId =1
				AND ((SA.BatchId=@rBatchId) OR (@rBatchId=0))
				AND (R.ReceiptDate>=CAST(DATEADD(DD,-(DAY(GETDATE() -1)), GETDATE()) as DATE) AND R.ReceiptDate<=CAST(DATEADD(DD,-(DAY(GETDATE())), DATEADD(MM, 1, GETDATE())) as DATE))

			SELECT Isnull(Sum(R.ReceiptAmount),0.00) as UptodateCollection 
			FROM sFee.tReceipt R
				INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.SourceId 
			WHERE R.SourceTypeId = 2001 AND((SA.OrgId=@rOrgId) OR (@rOrgId=0))
				AND ((R.BatchId=@rBatchId) OR (@rBatchId=0)) AND (R.IsObsolete = 0) 
				AND ((SA.OrgId=@rOrgId) OR (@rOrgId=0))
				AND SA.StatusId =1
				AND ((SA.BatchId=@rBatchId) OR (@rBatchId=0))
				AND (R.ReceiptDate<=CAST(GETDATE() as DATE))
		END
		--Drop Table #ttemptable1
		Drop Table #tTable
END
GO
PRINT N'Altering Procedure [sFrontOffice].[pStudentGatePassGet]...';


GO
ALTER PROCEDURE [sFrontOffice].[pStudentGatePassGet]
          
           @rId int,
           @rOrgId int=0,
           @rFromGatePassDate datetime='',
           @rToGatePassDate datetime='',
           @rEntryModeStatusId smallint=0,
           @rCode nvarchar(20)='',
           @rIsPrintView bit=0,
           @rOrgGroupId int=0,
           @rUserId bigint= 0,
		   @rDepartmentId int=0,
		   @rClassId int=0,
		   @rDivisionId int=0
AS
SET NOCOUNT ON
BEGIN
		Declare @GatePassConfig nvarchar(20)=''
		SELECT @GatePassConfig =ItemValue From sConfig.tConfigurationSetup WHERE ConfigurationId = 241 AND SourceId = @rOrgGroupId
		
		SELECT  
			SGP.Id,
			vSA.Code,
			vSA.FirstName+' '+vSA.MiddleName+' '+vSA.LastName AS Name,
			VSA.ClassName+' - '+VSA.DivisionName AS Class,
			SGP.AcademicId,
			ISNULL(SGP.RelationshipId,0) AS RelationshipId,
			RM.Title AS Relationship,
			SGP.Relation,
			SGP.VisitorName,
			ISNULL(SGP.VisitorMobile,0) As VisitorMobile,
			SGP.ReasonOfGatePass,
			(CASE  WHEN @rIsPrintView=1 THEN 
				SGP.VisitorPhoto		
			ELSE ISNULL(SGP.VisitorPhoto, CONVERT(VARBINARY(MAX), 0)) END) AS VisitorPhoto,
			--ISNULL(SGP.VisitorPhoto, CONVERT(VARBINARY(MAX), 0)) AS VisitorPhoto,
			ISNULL(SGP.GatePassDate,'') As GatePassDate,
			ISNULL(SGP.ReturnGatePassDate,'') As ReturnGatePassDate,
			ISNULL(SGP.GatePassTime,'') As GatePassTime,
			ISNULL(SGP.ReturnGatePassTime,'') As ReturnGatePassTime,
			ISNULL(SGP.EntryModeStatusId,0) AS EntryModeStatusId,
			ISNULL(SM.Title,'')  AS EntryModeStatus,
			OM.Id AS OrgId,
			OM.OrgLogo,
			OM.DisplayTitle AS Organization,
			(CASE  WHEN @rIsPrintView=1 THEN 
				SI.StudentPhoto		
			ELSE ISNULL(SI.StudentPhoto, CONVERT(VARBINARY(MAX), 0)) END) AS StudentPhoto,
			
			(CASE  WHEN @rIsPrintView=1 THEN 
				SI.FatherPhoto		
			ELSE ISNULL(SI.FatherPhoto, CONVERT(VARBINARY(MAX), 0)) END) AS FatherPhoto,
			
			(CASE  WHEN @rIsPrintView=1 THEN 
				SI.MotherPhoto		
			ELSE ISNULL(SI.MotherPhoto, CONVERT(VARBINARY(MAX), 0)) END) AS MotherPhoto,
			
			(CASE  WHEN @rIsPrintView=1 THEN 
				SI.RelativePhoto		
			ELSE ISNULL(SI.RelativePhoto, CONVERT(VARBINARY(MAX), 0)) END) AS RelativePhoto,
			
			--ISNULL(SI.StudentPhoto, CONVERT(VARBINARY(MAX), 0)) AS StudentPhoto,
			ISNULL(U.DisplayTitle,'') AS UserName,
			vSA.SUId,
			Remark,
			@GatePassConfig AS ConfigValue,
				
			SF.FatherContactNo,
			SF.MotherContactNo,
			SF.RelativeContactNo,
			SF.FatherName,
			SF.MotherName,
			SF.RelativeName,
			ISNULL(SGP.GatePassNo,0)AS GatePassNo,
		    --added by megha for 0027081
			CONVERT(VARCHAR, ISNULL(SGP.GatePassTime,''), 100) AS GatePassTime_12hours,
			(CASE WHEN @GatePassConfig='Image' THEN					--Add For 27089 mantis
				OI.CertificateHeaderA4
				ELSE NULL END) AS CertificateHeaderA4
		FROM
		    sStudent.vStudentAcademic vSA
			INNER JOIN sFrontOffice.tStudentGatePass SGP ON SGP.AcademicId = vSA.AcademicId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=vSA.OrgId
			INNER JOIN sCommon.tRelationshipMaster RM ON RM.Id=SGP.RelationshipId
			INNER JOIN sCommon.tStatusMaster SM ON SM.Id=SGP.EntryModeStatusId
			INNER JOIN sSecurity.tUserOrganization UO ON UO.OrgId = SGP.OrgId AND UO.UserId = @rUserId
			LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId=vSA.StudentId
			LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId = SI.StudentId
			LEFT JOIN sSecurity.tUser U	ON U.Id=SGP.CreatedUserId
			LEFT JOIN sSetup.tOrgImages OI ON OI.OrgId = vSA.OrgId			--Add For 27089 mantis
			
		WHERE 
		  ((SGP.Id=@rId) OR (@rId=0))
			AND ((SGP.OrgId=@rOrgId) OR (@rOrgId=0))
			AND ((SGP.GatePassDate>=@rFromGatePassDate) OR (ISNULL(@rFromGatePassDate,'')=''))
			AND ((SGP.GatePassDate<=@rToGatePassDate) OR (ISNULL(@rToGatePassDate,'')=''))
			AND ((SGP.EntryModeStatusId=@rEntryModeStatusId) OR (@rEntryModeStatusId=0))
			AND ((vSA.Code=@rCode) OR (ISNULL(@rCode,'')=''))
			AND (OM.OrgGroupId=@rOrgGroupId)
			AND ((vSA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
			AND ((vSA.ClassId=@rClassId) OR (@rClassId=0))
			AND ((vSA.DivisionId=@rDivisionId) OR (@rDivisionId=0))
			--AND vSA.IsActiveBatch=1
			ORDER BY SGP.GatePassDate,SGP.GatePassTime DESC
			
END
GO
PRINT N'Altering Procedure [sHrm].[pEmployeeReplacementDeleteAndTransfer]...';


GO
ALTER PROCEDURE [sHrm].[pEmployeeReplacementDeleteAndTransfer]
	 
        @rExistingEmployeeId BIGINT,
		@rNewEmployeeId BIGINT,
		@rId NVARCHAR(500)
	

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	IF OBJECT_ID('tempdb..#tmpSplitTable') IS NOT NULL DROP TABLE #tmpSplitTable

	CREATE Table #tmpSplitTable
	(
		Id NVARCHAR(150)
	)

	INSERT INTO #tmpSplitTable
	SELECT CAST(item AS NVARCHAR(150)) AS Id FROM  sCommon.fnsplit(@rId,',')
	
	IF EXISTS (SELECT 1 from #tmpSplitTable WHERE Id ='Assign Teacher')
	BEGIN
		IF NOT EXISTS(select top 1 1 from sTimetable.tAssignTeacher where EmployeeId = @rNewEmployeeId)
		begin
			INSERT INTO sTimetable.tAssignTeacher
			Select TimeTableSchemaId, @rNewEmployeeId from sTimetable.tAssignTeacher WHERE EmployeeId = @rExistingEmployeeId
			delete from sTimetable.tAssignTeacher where EmployeeId = @rExistingEmployeeId
		end		
	END

	IF EXISTS (SELECT 1 from #tmpSplitTable WHERE Id ='Teacher Subject Division')
	BEGIN
		INSERT INTO sAcademic.tTeacherSubject
		Select @rNewEmployeeId,SubjectId from sAcademic.tTeacherSubject where EmployeeId = @rExistingEmployeeId 
		and SubjectId NOT IN (select SubjectId from sAcademic.tTeacherSubjectDivision  where EmployeeId = @rNewEmployeeId)
		
		delete from sAcademic.tTeacherSubject where EmployeeId = @rExistingEmployeeId
		
		Insert into sAcademic.tTeacherSubjectDivision 
		select @rNewEmployeeId, SubjectId, DivisionId,SubjectCordinatorEmployeeId 
		from sAcademic.tTeacherSubjectDivision 
		where SubjectId NOT IN (select SubjectId from sAcademic.tTeacherSubjectDivision  where EmployeeId = @rNewEmployeeId)
		AND EmployeeId = @rExistingEmployeeId
		
		delete from sAcademic.tTeacherSubjectDivision where EmployeeId = @rExistingEmployeeId
		
	END

	IF EXISTS (SELECT 1 from #tmpSplitTable WHERE Id ='Time Table')
	BEGIN
		Update sTimetable.tTimeTable
		Set EmployeeId = @rNewEmployeeId from sTimetable.tTimeTable where EmployeeId  = @rExistingEmployeeId
		
		UPDATE sTimetable.tTeacherWorkLoad SET EmployeeId = @rNewEmployeeId WHERE EmployeeId = @rExistingEmployeeId 
	END
	
	IF EXISTS (SELECT 1 from #tmpSplitTable WHERE Id ='User Access')
	BEGIN
		declare @lExistingUserId bigint= (select Id from sSecurity.tUser where SourceId = @rExistingEmployeeId AND SourceTypeId = 95)
		declare @lNewUserId bigint= (select Id from sSecurity.tUser where SourceId = @rNewEmployeeId AND SourceTypeId = 95)

		IF (@lNewUserId IS NULL)
		BEGIN
			Return
		END
		ELSE
		BEGIN
		Insert into sSecurity.tUserOrganization 
		select OrgId, @lNewUserId from sSecurity.tUserOrganization WHERE UserId=@lExistingUserId
		AND OrgId NOT in (select OrgId from sSecurity.tUserOrganization WHERE UserId=@lNewUserId)

		delete from sSecurity.tUserOrganization  WHERE UserId=@lExistingUserId

		INSERT INTO sSecurity.tUserAccess
		SELECT SourceTypeId, SourceId, @lNewUserId FROM sSecurity.tUserAccess WHERE UserId=@lExistingUserId
		AND SourceId not in (select SourceId from  sSecurity.tUserAccess WHERE UserId=@lNewUserId)

		delete from sSecurity.tUserAccess  WHERE UserId=@lExistingUserId
		END
	END

	IF EXISTS (SELECT 1 from #tmpSplitTable WHERE Id ='Class Teacher')
	BEGIN
		Update sSetup.tDivisionMaster SET InchargeEmployeeId = @rNewEmployeeId where  InchargeEmployeeId = @rExistingEmployeeId
	END

	Drop Table #tmpSplitTable
END
GO
PRINT N'Altering Procedure [sHrm].[pEmployeeReplacementGet]...';


GO
ALTER PROCEDURE [sHrm].[pEmployeeReplacementGet]
	 
        @rEmployeeId bigint
	

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	Declare @lTeacherSubjectId bigint = 0 , @lTeacherDivisionId bigint = 0
	IF OBJECT_ID('tempdb..#tmpTable') IS NOT NULL DROP TABLE #tmpTable
	CREATE Table #tmpTable 
	(
		Id bigint IDENTITY,
		Title nvarchar(50)
	)

	IF EXISTS(select top 1 1 from sTimetable.tAssignTeacher where EmployeeId = @rEmployeeId)
	BEGIN
		Insert INTO #tmpTable Values
		(
			'Assign Teacher'
		)
	END


	set @lTeacherSubjectId = (select top 1 1 from sAcademic.tTeacherSubject where EmployeeId = @rEmployeeId)
	SET @lTeacherDivisionId = (select top 1 1 from sAcademic.tTeacherSubjectDivision where EmployeeId = @rEmployeeId)
	IF ((@lTeacherSubjectId = 1) OR (@lTeacherDivisionId = 1))
	BEGIN
		Insert INTO #tmpTable Values
		(
			'Teacher Subject Division'
		)
	END

	IF EXISTS (select top 1 1 from sTimetable.tTimeTable where EmployeeId = @rEmployeeId)
	BEGIN
		Insert INTO #tmpTable Values
		(
			'Time Table'
		)
	END

	--IF EXISTS (select top 1 1 from sTimetable.tTeacherWorkLoad where EmployeeId = @rEmployeeId)
	--BEGIN
	--	Insert INTO #tmpTable Values
	--	(
	--		'Teacher Work Load'
	--	)
	--END
	
	declare @lUserId bigint= (select top 1 Id from sSecurity.tUser where SourceId = @rEmployeeId AND SourceTypeId = 95)
	declare @lUserOrganizationId int ,@lUserAccessId int
	SET @lUserOrganizationId = (SELECT Top 1 1 FROM sSecurity.tUserOrganization WHERE UserId=@lUserId)
	SET @lUserAccessId= (SELECT top 1 1 FROM sSecurity.tUserAccess WHERE UserId=@lUserId)
	IF ((@lUserOrganizationId = 1) OR (@lUserAccessId = 1))
	BEGIN
		Insert INTO #tmpTable Values
		(
			'User Access'
		)
	END

	IF EXISTS (select top 1 1 from sSetup.tDivisionMaster where InchargeEmployeeId = @rEmployeeId)
	BEGIN
		Insert INTO #tmpTable Values
		(
			'Class Teacher'
		)
	END

	select * from #tmpTable

	Drop Table #tmpTable
END
GO
PRINT N'Altering Procedure [sHrm].[pEmployeeReplacementTransfer]...';


GO
ALTER PROCEDURE [sHrm].[pEmployeeReplacementTransfer]
	 
        @rExistingEmployeeId BIGINT,
		@rNewEmployeeId BIGINT,
		@rId NVARCHAR(max),
		@rOrgId int
	

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	IF OBJECT_ID('tempdb..#tmpSplitTable') IS NOT NULL DROP TABLE #tmpSplitTable

	CREATE Table #tmpSplitTable
	(
		Id NVARCHAR(max)
	)
	INSERT INTO #tmpSplitTable
	SELECT CAST(item AS NVARCHAR(max)) AS Id FROM  sCommon.fnsplit(@rId,',')

	IF EXISTS (SELECT 1 from #tmpSplitTable WHERE Id ='Assign Teacher')
	BEGIN
		IF NOT EXISTS(select top 1 1 from sTimetable.tAssignTeacher where EmployeeId = @rNewEmployeeId)
		begin
			INSERT INTO sTimetable.tAssignTeacher
			Select TimeTableSchemaId, @rNewEmployeeId from sTimetable.tAssignTeacher WHERE EmployeeId = @rExistingEmployeeId
		end
	END

	IF EXISTS (SELECT 1 from #tmpSplitTable WHERE Id ='Teacher Subject Division')
	BEGIN
		
		INSERT INTO sAcademic.tTeacherSubject
		Select @rNewEmployeeId,SubjectId from sAcademic.tTeacherSubject where EmployeeId = @rExistingEmployeeId 
		and SubjectId NOT IN (select SubjectId from sAcademic.tTeacherSubjectDivision  where EmployeeId = @rNewEmployeeId)
		
		Insert into sAcademic.tTeacherSubjectDivision 
		select @rNewEmployeeId, SubjectId, DivisionId,SubjectCordinatorEmployeeId 
		from sAcademic.tTeacherSubjectDivision 
		where SubjectId NOT IN (select SubjectId from sAcademic.tTeacherSubjectDivision  where EmployeeId = @rNewEmployeeId)
		AND EmployeeId = @rExistingEmployeeId
		
	END
	
	IF EXISTS (SELECT 1 from #tmpSplitTable WHERE Id ='User Access')
	BEGIN
		declare @lExistingUserId bigint= (select Id from sSecurity.tUser where SourceId = @rExistingEmployeeId AND SourceTypeId = 95)
		declare @lNewUserId bigint= (select Id from sSecurity.tUser where SourceId = @rNewEmployeeId AND SourceTypeId = 95)
		IF (@lNewUserId IS NULL)
		BEGIN
			Return
		END
		ELSE
		BEGIN
			Insert into sSecurity.tUserOrganization 
			select OrgId, @lNewUserId from sSecurity.tUserOrganization WHERE UserId=@lExistingUserId
			AND OrgId NOT in (select OrgId from sSecurity.tUserOrganization WHERE UserId=@lNewUserId)

			INSERT INTO sSecurity.tUserAccess
			SELECT SourceTypeId, SourceId, @lNewUserId FROM sSecurity.tUserAccess WHERE UserId=@lExistingUserId
			AND SourceId not in (select SourceId from  sSecurity.tUserAccess WHERE UserId=@lNewUserId)
		END
	END
	
	IF EXISTS (SELECT 1 from #tmpSplitTable WHERE Id ='Time Table')
	BEGIN

		UPDATE sTimetable.tTimeTable 
		SET EmployeeId = @rNewEmployeeId 
		WHERE EmployeeId = @rExistingEmployeeId 

		UPDATE sTimetable.tTeacherWorkLoad 
		SET EmployeeId = @rNewEmployeeId WHERE EmployeeId = @rExistingEmployeeId 
	END

	IF EXISTS (SELECT 1 from #tmpSplitTable WHERE Id ='Class Teacher')
	BEGIN
		Update sSetup.tDivisionMaster SET InchargeEmployeeId = @rNewEmployeeId where  InchargeEmployeeId = @rExistingEmployeeId
	END

	Drop Table #tmpSplitTable
END
GO
PRINT N'Altering Procedure [sHrm].[pLeaveListingModify]...';


GO

ALTER PROCEDURE [sHrm].[pLeaveListingModify]
           
        @rId bigint,
        @rEmployeeId bigint,
        @rBatchId int,
        @rOrgId int,
        @rStatusId int,
        @rLeaveRemark nvarchar(200), 
        @rActionByEmployeeId bigint,
        @rUpdatedUserId bigint = 0
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
	
	BEGIN TRANSACTION

	BEGIN
		UPDATE sHrm.tLeave
		SET 	 
		  [StatusId]=@rStatusId,
          [LeaveRemark]=@rLeaveRemark,
          [ActionByEmployeeId]=@rActionByEmployeeId,
          [UpdatedUserId]=@rUpdatedUserId                  
		WHERE EmployeeId = @rEmployeeId AND Id=@rId
		
		--DECLARE @lLeaveTypeId int = 0
		--DECLARE @lBalanceLeave decimal(8,2) = 0
		--DECLARE @lAddBalance decimal(5,2) = 0
		--DECLARE @lStatusId int = 0
		
		--SELECT @lLeaveTypeId=LeaveTypeId , @lAddBalance=NoOfLeave, @lStatusId = StatusId FROM sHrm.tLeave WHERE EmployeeId = @rEmployeeId AND Id=@rId
		
		--SELECT @lBalanceLeave=BalanceLeave FROM sHrm.tLeaveBalance WHERE EmployeeId = @rEmployeeId AND LeaveTypeId=@lLeaveTypeId AND BatchId = @rBatchId
		
		--IF(@rStatusId=550) -- Approved
		--BEGIN
		--	-- Add Leave Balance Log
		--	INSERT INTO sHrm.tLeaveBalanceLog 
		--	SELECT @rEmployeeId,@lLeaveTypeId,@lBalanceLeave+@lAddBalance,4,@lAddBalance,
		--	'Add Leave - Approved',@rBatchId,0,sCommon.fGetDate()	 
		--END
		--ELSE
		--BEGIN
		--		IF(@lStatusId=551)
		--		BEGIN
		--			 -- Add Leave Balance Log
		--			INSERT INTO sHrm.tLeaveBalanceLog 
		--			SELECT @rEmployeeId,@lLeaveTypeId,@lBalanceLeave-@lAddBalance,4,@lAddBalance,
		--			'Add Leave - Rejected',@rBatchId,0,sCommon.fGetDate()
		--		END
		--END
		-- Update Leave in EmployeeRegister when leave is Approved from LeaveListing Screen (only in Approved) - mantisid - 0027169
		IF(@rStatusId = 550)
		BEGIN
			CREATE TABLE #tmp
			(
				Id int IDENTITY,
				LeaveDate DATE
			)

			DECLARE	@StartDate DATE, @EndDate DATE , @lEmployeeId bigint
			SELECT @StartDate = FromDate FROM sHrm.tLeave WHERE Id = @rId 
			SELECT @EndDate = ToDate FROM sHrm.tLeave WHERE Id = @rId
			SELECT @lEmployeeId = EmployeeId FROM sHrm.tLeave WHERE Id = @rId;
			
			WITH ListDates(AllDates) AS 
			(    
				SELECT @StartDate AS DATE
				UNION ALL
				SELECT DATEADD(DAY,1,AllDates)
				FROM ListDates 
				WHERE AllDates < @EndDate)

			INSERT INTO #tmp
			SELECT AllDates
			FROM ListDates

			--Select * from #tmp
			DECLARE @lCount int,@lId int,@lLeaveDate Date , @lLeaveTypeId int, @lLeavePeriodId int
			SELECT @lCount=COUNT(Id) FROM #tmp
			SELECT Top 1 @lId=Id FROM #tmp
			
			WHILE @lId <= @lCount
			BEGIN
				SELECT @lLeaveDate=LeaveDate FROM #tmp WHERE Id=@lId
				SELECT @lLeaveTypeId = LeaveTypeId , @lLeavePeriodId = LeavePeriodId FROM sHrm.tLeave WHERE Id = @rId


				IF EXISTS(SELECT 1 FROM sHrm.tEmployeeAttendanceRegister WHERE EmployeeId = @lEmployeeId AND AttendanceDate = @lLeaveDate AND BatchId = @rBatchId)
				BEGIN
				--Print 111
				--	SELECT 0 ,@lLeaveTypeId, @lLeavePeriodId FROM sHrm.tEmployeeAttendanceRegister 
				--		WHERE AttendanceDate = @lLeaveDate AND EmployeeId = @lEmployeeId AND BatchId = @rBatchId

					UPDATE sHrm.tEmployeeAttendanceRegister SET IsPresent = 0 ,LeaveTypeId = @lLeaveTypeId, LeavePeriodId = @lLeavePeriodId
					WHERE AttendanceDate = @lLeaveDate AND EmployeeId = @lEmployeeId AND BatchId = @rBatchId
				END
				--ELSE
				--BEGIN
			
				--INSERT INTO sHrm.tEmployeeAttendanceRegister
				--   (EmployeeId
				--   ,[AttendanceDate]
				--   ,[IsPresent]
				--   ,[AbsentReasonId]
				--   ,[UpdatedUserId]
				--   ,[UpdatedDateTime]
				--   ,[BatchId]
				--   ,[AttendanceTagId]
				--   ,[LeaveTypeId]
				--   ,[LeavePeriodId])
				-- VALUES
				--	   (@lEmployeeId
				--	   ,@lLeaveDate
				--	   ,0
				--	   ,0
				--	   ,1
				--	   ,GetDate()
				--	   ,@rBatchId
				--	   ,NULL
				--	   ,@lLeaveTypeId
				--	   ,@lLeavePeriodId
				--	   )
				
				--END

				SET @lId=@lId+1
			END
			DROP TABLE #tmp
			
		END
		
	 END 
	   SELECT @rId AS Result	   
	   COMMIT TRANSACTION
	END TRY	
	BEGIN CATCH
		ROLLBACK TRANSACTION
		SELECT -1 AS RESULT
	END CATCH
END
GO
PRINT N'Altering Procedure [sHrm].[pRptEmployeeAttendanceRegisterGet]...';


GO


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

BEGIN 

DECLARE @li int 
SET @li=1
Declare @ldate datetime,@lDays int
declare @Days int
Declare @Firstdate datetime
Declare @Lastdate datetime

		
Set @ldate= CONVERT(nvarchar(10), @rForYear)+ '-' +  CONVERT(nvarchar(10), @rForMonth) + '-' + CONVERT(nvarchar(10), 01)
Select @lDays=day(dateadd(mm,DateDiff(mm, -1, @ldate),0) -1) 
select @Days=sCommon.fGetDaysInMonth(@rForMonth,@rForYear)
		
set @Firstdate=CONVERT(nvarchar(10), @rForYear)+ '-' +  CONVERT(nvarchar(10), @rForMonth) + '-' + CONVERT(nvarchar(10), 01)
set @Lastdate=CONVERT(nvarchar(10), @rForYear)+ '-' +  CONVERT(nvarchar(10), @rForMonth) + '-' + CONVERT(nvarchar(10), @Days)
		
CREATE Table #EmployeeAttendanceRegistertempTable
(
	 
	EmployeeCode nvarchar(50),
	EmployeeId bigint,
	EmployeeName nvarchar(100),
	ForYear int,
	ForMonth int,
	ForMonthInWord nvarchar(100),
	DepartmentId int,
	DepartmentName nvarchar(50),
	IsPresent bit,
	DayPart int,
	AttendanceDate date,
	DateOfJoining date,
	DateOfLeaving  date,
	AttendanceTagId int ,
	Number int ,
	IsOtherUser smallint,
	EmployeeGrade nvarchar(500),
	Code nvarchar(200),
	LeaveCount decimal(12,2)
 
)
Insert INTO #EmployeeAttendanceRegistertempTable
(	
	EmployeeCode ,
	EmployeeId ,
	EmployeeName,
	ForYear ,
	ForMonth,
	ForMonthInWord,
	DepartmentId ,
	DepartmentName ,
	IsPresent ,
	DayPart ,
	AttendanceDate ,
	DateOfJoining ,
	DateOfLeaving ,
	AttendanceTagId,
	Number,
	IsOtherUser,
	EmployeeGrade,
	Code,
	LeaveCount
)
SELECT  
		EM.Code AS EmployeeCode,
		EM.EmployeeId AS EmployeeId,
		EM.EmployeeName,
		YEAR(EAR.AttendanceDate) AS ForYear,
		MONTH(EAR.AttendanceDate) AS ForMonth,
		DATENAME(month, EAR.AttendanceDate) AS ForMonthInWord,
		EM.DepartmentId,
		EM.DepartmentName,
		EAR.IsPresent,
		day(EAR.AttendanceDate) AS DayPart,
		EAR.AttendanceDate,
		--ISNULL(CONVERT(VARCHAR(50),EM.DateOfJoining,103),'') AS DateOfJoining,
		EJD.DateOfJoining,
		EJD.DateOfLeaving,
		--ISNULL(CONVERT(VARCHAR(50),EM.DateOfLeaving,103),'') AS DateOfLeaving,
			EAR.AttendancetagId,
		EM.Number,
		EM.IsOtherUser,
		EM.EmployeeGrade,
		LTM.Code,
		(SELECT ISNULL(SUM(CONVERT(decimal(12,2),  '.'+PARSENAME(NoOfLeave,1))),0) FROM sHrm.tLeave WHERE LeaveTypeId = LTM.Id AND FromDate BETWEEN @FirstDate AND @LastDate AND StatusId!=551 AND OrgId = @rOrgId AND BatchId = @rBatchId AND EmployeeId = EM.EmployeeId) AS LeaveCount

	FROM 

		sHrm.vEmployeeCommonDetail EM 
		INNER JOIN sHrm.tEmployeeMaster E ON E.Id = EM.EmployeeId
		INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.EmployeeId
		INNER JOIN sHrm.tWorkingDays WD ON  EM.EmployeeGradeId = WD.EmployeeGradeId
		AND WD.ForMonth=@rForMonth AND WD.ForYear=@rForYear AND WD.BatchId = @rBatchId
		LEFT JOIN sHrm.tEmployeeAttendanceRegister EAR ON EAR.EmployeeId = EM.EmployeeId AND (EAR.BatchId = @rBatchId)
		AND MONTH(EAR.AttendanceDate)=@rForMonth AND YEAR(EAR.AttendanceDate)=@rForYear
		INNER JOIN sHrm.tLeaveTypeMaster LTM ON E.OrgID=LTM.OrgId AND LTM.IsObsolete=0	
	WHERE 
			EM.OrgID = @rOrgId 
    		AND ((EM.EmployeeGradeId=@rEmployeeGradeId) OR (@rEmployeeGradeId=0))
    		AND ((EM.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
    		AND ((EM.Code like @rEmployeeCode) OR (@rEmployeeCode=''))
    		AND ((EM.EmployeeName like @rEmployeeName) OR (@rEmployeeName=''))
    		AND ((EM.EmployeeId=@rEmployeeId) OR (@rEmployeeId=0))
    		AND ((EM.EmployeeStatusId=@rStatusId) OR (@rStatusId=0))
    		AND ((EM.EmployeeStatusId=@rEmployeeStatusId) OR (@rEmployeeStatusId=0))
    		AND (EM.DateOfJoining<= @Lastdate OR ISNULL(EM.DateOfJoining,'')='')
    		AND (EM.DateOfleaving>= @Firstdate OR ISNULL(EM.DateOfleaving,'')='')
			AND EM.IsOtherUser = 0
			AND (EM.Number >= @rFromNumber OR @rFromNumber IS NULL) AND (EM.Number <= @rToNumber OR @rToNumber IS NULL)
			ORDER BY EM.Number

--Select * from #EmployeeAttendanceRegistertempTable
CREATE TABLE #TempDaysTempTable
(
 DayPart int
 )
WHILE @li<=@Days

BEGIN

INSERT INTO #TempDaysTempTable
(
	DayPart 
)

SELECT 
@li AS DayPart
SET @li = @li + 1

END

		
			SELECT 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2, 
			Number,
			isnull(EmployeeCode,'') as EmployeeCode,
			PivotTable.EmployeeId,
			isnull(EmployeeName,'') as EmployeeName,   
			DepartmentName,
			EmployeeGrade,      
		   	sCommon.fGetDaysInMonth (@rForMonth,@rForYear) AS TotalDays,
			[sHrm].[fAttendanceWithApproveLeaveGet](PivotTable.EmployeeId,@rForYear,@rForMonth,'01',@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-01')),DateOfJoining,DateOfLeaving,[1]) AS P1,
			[sHrm].[fAttendanceWithApproveLeaveGet](PivotTable.EmployeeId,@rForYear,@rForMonth,'02',@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-02')),DateOfJoining,DateOfLeaving,[2]) AS P2,
			[sHrm].[fAttendanceWithApproveLeaveGet](PivotTable.EmployeeId,@rForYear,@rForMonth,'03',@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-03')),DateOfJoining,DateOfLeaving,[3]) AS P3,
			[sHrm].[fAttendanceWithApproveLeaveGet](PivotTable.EmployeeId,@rForYear,@rForMonth,'04',@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-04')),DateOfJoining,DateOfLeaving,[4])  AS P4,
			[sHrm].[fAttendanceWithApproveLeaveGet](PivotTable.EmployeeId,@rForYear,@rForMonth,'05',@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-05')),DateOfJoining,DateOfLeaving,[5]) AS P5,
			[sHrm].[fAttendanceWithApproveLeaveGet](PivotTable.EmployeeId,@rForYear,@rForMonth,'06',@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-06')),DateOfJoining,DateOfLeaving,[6]) AS P6,
			[sHrm].[fAttendanceWithApproveLeaveGet](PivotTable.EmployeeId,@rForYear,@rForMonth,'07',@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-07')),DateOfJoining,DateOfLeaving,[7])  AS P7,
			[sHrm].[fAttendanceWithApproveLeaveGet](PivotTable.EmployeeId,@rForYear,@rForMonth,'08',@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-08')),DateOfJoining,DateOfLeaving,[8]) As P8,
			[sHrm].[fAttendanceWithApproveLeaveGet](PivotTable.EmployeeId,@rForYear,@rForMonth,'09',@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-09')),DateOfJoining,DateOfLeaving,[9]) AS P9,
			[sHrm].[fAttendanceWithApproveLeaveGet](PivotTable.EmployeeId,@rForYear,@rForMonth,'10',@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-10')),DateOfJoining,DateOfLeaving,[10]) AS P10,
			[sHrm].[fAttendanceWithApproveLeaveGet](PivotTable.EmployeeId,@rForYear,@rForMonth,'11',@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-11')),DateOfJoining,DateOfLeaving,[11]) AS P11,
			[sHrm].[fAttendanceWithApproveLeaveGet](PivotTable.EmployeeId,@rForYear,@rForMonth,'12',@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-12')),DateOfJoining,DateOfLeaving,[12]) AS P12,
			[sHrm].[fAttendanceWithApproveLeaveGet](PivotTable.EmployeeId,@rForYear,@rForMonth,'13',@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-13')),DateOfJoining,DateOfLeaving,[13]) AS P13,
			[sHrm].[fAttendanceWithApproveLeaveGet](PivotTable.EmployeeId,@rForYear,@rForMonth,'14',@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-14')),DateOfJoining,DateOfLeaving,[14]) AS P14,
			[sHrm].[fAttendanceWithApproveLeaveGet](PivotTable.EmployeeId,@rForYear,@rForMonth,'15',@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-15')),DateOfJoining,DateOfLeaving,[15]) AS P15,
			[sHrm].[fAttendanceWithApproveLeaveGet](PivotTable.EmployeeId,@rForYear,@rForMonth,'16',@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-16')),DateOfJoining,DateOfLeaving,[16])  AS P16,
			[sHrm].[fAttendanceWithApproveLeaveGet](PivotTable.EmployeeId,@rForYear,@rForMonth,'17',@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-17')),DateOfJoining,DateOfLeaving,[17]) AS P17,
			[sHrm].[fAttendanceWithApproveLeaveGet](PivotTable.EmployeeId,@rForYear,@rForMonth,'18',@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-18')),DateOfJoining,DateOfLeaving,[18])  AS P18,
			[sHrm].[fAttendanceWithApproveLeaveGet](PivotTable.EmployeeId,@rForYear,@rForMonth,'19',@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-19')),DateOfJoining,DateOfLeaving,[19])  AS P19,
			[sHrm].[fAttendanceWithApproveLeaveGet](PivotTable.EmployeeId,@rForYear,@rForMonth,'20',@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-20')),DateOfJoining,DateOfLeaving,[20])  AS P20,
			[sHrm].[fAttendanceWithApproveLeaveGet](PivotTable.EmployeeId,@rForYear,@rForMonth,'21',@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-21')),DateOfJoining,DateOfLeaving,[21]) AS P21,
			[sHrm].[fAttendanceWithApproveLeaveGet](PivotTable.EmployeeId,@rForYear,@rForMonth,'22',@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-22')),DateOfJoining,DateOfLeaving,[22]) AS P22,
			[sHrm].[fAttendanceWithApproveLeaveGet](PivotTable.EmployeeId,@rForYear,@rForMonth,'23',@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-23')),DateOfJoining,DateOfLeaving,[23]) AS P23,
			[sHrm].[fAttendanceWithApproveLeaveGet](PivotTable.EmployeeId,@rForYear,@rForMonth,'24',@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-24')),DateOfJoining,DateOfLeaving,[24]) AS P24,
			[sHrm].[fAttendanceWithApproveLeaveGet](PivotTable.EmployeeId,@rForYear,@rForMonth,'25',@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-25')),DateOfJoining,DateOfLeaving,[25]) AS P25,
			[sHrm].[fAttendanceWithApproveLeaveGet](PivotTable.EmployeeId,@rForYear,@rForMonth,'26',@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-26')),DateOfJoining,DateOfLeaving,[26]) AS P26,
			[sHrm].[fAttendanceWithApproveLeaveGet](PivotTable.EmployeeId,@rForYear,@rForMonth,'27',@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-27')),DateOfJoining,DateOfLeaving,[27]) AS P27,
			[sHrm].[fAttendanceWithApproveLeaveGet](PivotTable.EmployeeId,@rForYear,@rForMonth,'28',@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-28')),DateOfJoining,DateOfLeaving,[28]) AS P28,
			CASE WHEN @Days>=29 THEN[sHrm].[fAttendanceWithApproveLeaveGet](PivotTable.EmployeeId,@rForYear,@rForMonth,'29',@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-29')),DateOfJoining,DateOfLeaving,[29]) end AS P29,
			CASE WHEN @Days>=30 THEN[sHrm].[fAttendanceWithApproveLeaveGet](PivotTable.EmployeeId,@rForYear,@rForMonth,'30',@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-30')),DateOfJoining,DateOfLeaving,[30])end AS P30,
			CASE WHEN @Days>=31 THEN[sHrm].[fAttendanceWithApproveLeaveGet](PivotTable.EmployeeId,@rForYear,@rForMonth,'31',@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-31')),DateOfJoining,DateOfLeaving,[31])end AS P31,
			Code,
			LeaveCount			
			
			FROM
(
	Select  
		EmployeeCode,
		EmployeeId,
		EmployeeName,
		YEAR(ST.AttendanceDate) AS ForYear,
		MONTH(ST.AttendanceDate) AS ForMonth,
		DATENAME(month, ST.AttendanceDate) AS ForMonthInWord,
		DepartmentId,
		DepartmentName,
		(
			CASE 
				  WHEN IsPresent = 1 AND ST.AttendanceTagId = 1 THEN 'LA' 
				  WHEN IsPresent = 1 AND ST.AttendanceTagId = 2 THEN 'ED' 
			      WHEN IsPresent = 1  THEN 'P' 
				  WHEN IsPresent = 0 THEN 'A'
				END 
		)AS  IsPresent,		
		day(ST.AttendanceDate) AS DayPart,
		DateOfLeaving,		 
		DateOfJoining,
		Number,
		EmployeeGrade,
		Code,
		LeaveCount	
	 FROM 
		#EmployeeAttendanceRegistertempTable ST 
		LEFT JOIN #TempDaysTempTable DT ON DT.DayPart = ST.DayPart
	 WHERE 
		  ((DateOfLeaving >= @FirstDate) OR ISNULL(DateOfLeaving,'') = '')
		  AND IsOtherUser = 0
	   -- WHERE 
	   -- ForYear=@rForYear AND ForMonth=@rForMonth
) AS SourceTable 
	           
	        
PIVOT
(	
MIN(IsPresent)
FOR DayPart IN ([0], [1], [2], [3], [4],[5],[6],[7],[8],[9],[10],[11],[12],[13],[14],[15],[16],[17],[18],[19],[20],[21],[22],[23],[24],[25],[26],[27],[28],[29],[30],[31])
) AS PivotTable
	LEFT JOIN
	(
		Select  EmployeeId AS EmployeeId, COUNT(1) AS TCount 
		   FROM  
				#EmployeeAttendanceRegistertempTable
				WHERE AttendanceDate < (convert(date,CONVERT(nvarchar(10), @rForYear)+ '/' +  CONVERT(nvarchar(10), @rForMonth) + '/' + '01' ))
		     GROUP BY  EmployeeId 
    ) TC ON TC.EmployeeId = PivotTable.EmployeeId 
	LEFT JOIN
	(
		Select EmployeeId AS EmployeeId, COUNT(1) AS ACount 
		   FROM  #EmployeeAttendanceRegistertempTable
		    WHERE   IsPresent = 0	 	 
		      AND AttendanceDate < (convert(date,CONVERT(nvarchar(10), @rForYear)+ '/' +  CONVERT(nvarchar(10), @rForMonth) + '/' + '01' ))
			GROUP BY  EmployeeId
    ) AC ON AC.EmployeeId = PivotTable.EmployeeId
	LEFT JOIN
	(
		SELECT EJD.EmployeeId, COUNT(1) AS PCount  FROM 
		
		sHrm.vEmployeeCommonDetail EM 
		INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.EmployeeId
		INNER JOIN sHrm.tWorkingDays WD ON  EM.EmployeeGradeId = WD.EmployeeGradeId
		AND WD.ForMonth=@rForMonth AND WD.ForYear=@rForYear AND WD.BatchId = @rBatchId
		LEFT JOIN sHrm.tEmployeeAttendanceRegister EAR ON EAR.EmployeeId = EM.EmployeeId AND (EAR.BatchId = @rBatchId)
		AND MONTH(EAR.AttendanceDate)=@rForMonth AND YEAR(EAR.AttendanceDate)=@rForYear
	   
			WHERE   
	
	    ((EM.OrgId=@rOrgId) OR (@rOrgId= 0))
	       AND ((EM.DepartmentId = @rDepartmentId)OR (@rDepartmentId=0))
	       AND ((EAR.BatchId=@rBatchId) OR (@rBatchId= 0))
	       AND EAR.AttendanceDate < (convert(date,CONVERT(nvarchar(10), @rForYear)+ '/' +  CONVERT(nvarchar(10), @rForMonth) + '/' + '01' ))
		   AND EM.IsOtherUser = 0
	 GROUP BY EJD.EmployeeId 
    ) PC ON PC.EmployeeId = PivotTable.EmployeeId
		
	Order By PivotTable.Number	
			--FROM
			--sHrm.vEmployeeCommonDetail EM
			--INNER JOIN sHrm.tEmployeeMaster E ON E.Id = EM.EmployeeId				
			--INNER JOIN sHrm.tLeaveTypeMaster LTM ON E.OrgID=LTM.OrgId						
			
   -- 		WHERE 
   -- 		EM.OrgID = @rOrgId 
   -- 		AND ((EM.EmployeeGradeId=@rEmployeeGradeId) OR (@rEmployeeGradeId=0))
   -- 		AND ((EM.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
   -- 		AND ((EM.Code like @rEmployeeCode) OR (@rEmployeeCode=''))
   -- 		AND ((EM.EmployeeName like @rEmployeeName) OR (@rEmployeeName=''))
   -- 		AND ((EM.EmployeeId=@rEmployeeId) OR (@rEmployeeId=0))
   -- 		AND ((EM.EmployeeStatusId=@rStatusId) OR (@rStatusId=0))
   -- 		AND ((EM.EmployeeStatusId=@rEmployeeStatusId) OR (@rEmployeeStatusId=0))
   -- 		AND (EM.DateOfJoining<= @Lastdate OR ISNULL(EM.DateOfJoining,'')='')
   -- 		AND (EM.DateOfleaving>= @Firstdate OR ISNULL(EM.DateOfleaving,'')='')
   -- 		--AND ((ISNULL(EM.DateOfJoining,''))<=CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-'+CONVERT(NVARCHAR(2),IN(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31)))))			
			--AND EM.IsOtherUser = 0
			--AND E.Number>=@rFromNumber AND E.Number<=@rToNumber

		--	SELECT [Builder1]
  --    ,[Builder2]
	 -- ,[Number]
  --    ,[EmployeeCode]
  --    ,[EmployeeId]
  --    ,[EmployeeName]
  --    ,[DepartmentName]
  --    ,[EmployeeGrade]
  --    ,[TotalDays]
  --    ,[P1]
  --    ,[P2]
  --    ,[P3]
  --    ,[P4]
  --    ,[P5]
  --    ,[P6]
  --    ,[P7]
  --    ,[P8]
  --    ,[P9]
  --    ,[P10]
  --    ,[P11]
  --    ,[P12]
  --    ,[P13]
  --    ,[P14]
  --    ,[P15]
  --    ,[P16]
  --    ,[P17]
  --    ,[P18]
  --    ,[P19]
  --    ,[P20]
  --    ,[P21]
  --    ,[P22]
  --    ,[P23]
  --    ,[P24]
  --    ,[P25]
  --    ,[P26]
  --    ,[P27]
  --    ,[P28]
  --    ,[P29]
  --    ,[P30]
  --    ,[P31]
  --    ,[Code]
  --    ,[LeaveCount]
  --FROM [sHrm].[tTempEmployeeAttendanceRegister]
drop table #EmployeeAttendanceRegistertempTable	  
drop table #TempDaysTempTable
END
GO
PRINT N'Altering Procedure [sHrm].[pRptEmployeeIcardGet]...';


GO


ALTER PROCEDURE [sHrm].[pRptEmployeeIcardGet]
	@rBuilder1 nvarchar(max)='',
	@rBuilder2 nvarchar(max)='',
	@rReportId smallint,
	@rOrgId smallint,
	@rStrEmployeeId nvarchar(max),
	@rEmployeeTypeId [int],
	@rDepartmentId [int]= 0,
	@rGradeId [int]= 0,
	@rDesignationId [int]= 0,
	@rGenderId [int]= 0,		
	@rEmployeeId [bigint]= 0,
	@rAgeFrom nvarchar(10),
	@rAgeTo nvarchar(10),
	@rEmployeeCode nvarchar(50)='',
	@rEmployeeGroupId smallint,
	@rEmployeeStatusId smallint,
	@rIsShowBarcode bit=0,
	@rStrCode nvarchar(max)='',
	@rBatchName nvarchar(100) = ''
	
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
	SELECT		
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			ECD.EmployeeId,
	        ECD.Code,	      	
			ECD.EmployeeName, 	 								 
			ECD.DepartmentId,  			
			ECD.DepartmentName,
		    ECD.MobileNumber,
		    ECD.EmployeeDesignation,
		    ECD.PhoneNoCompany,
		    ECD.BloodGroup,
		    ECD.DateOfBirth,
			EI.EmployeePhoto,
		    OM.Title AS OrgName,
		    OM.PrincipalSignature,
			ISNULL(ICO.ICardOrgTitle,'') AS ICardOrgTitle,
			ISNULL(ICO.ICardAddress1,'') AS ICardAddress1,
			ISNULL(ICO.ICardAddress2,'') AS ICardAddress2,
			ISNULL(ICO.ICardAddress3,'') AS ICardAddress3,	
		    OM.OrgLogo AS ICardLogo,
			ICO.ICardBackground,	
			ICO.ICardBackBackground,						
			ISNULL(ICO.LabelColor,'Black') AS LabelColor,
			ISNULL(ICO.DetailColor,'Black') AS DetailColor,
			ISNULL(ICO.HeaderColor,'Black') AS HeaderColor,
			ISNULL(EC.PresentStreetOne,'') AS PresentStreetOne,
			ISNULL(EC.PresentStreetTwo,'') AS PresentStreetTwo,
			ISNULL(EC.PresentStreetThree,'') AS PresentStreetThree,
			ISNULL(EC.PresentCity,'') AS PresentCity,
			ISNULL(EC.PresentState,'') AS PresentState,
			ISNULL(EC.PresentCountry,'') AS PresentCountry,
			ISNULL(EC.PresentZipCode,'') AS PresentZipCode,
			ECD.DateofJoining,
			EI.EmployeeSign,
			@rIsShowBarcode As IsShowBarcode,
			ISNULL(EC.EmergencyStreetOne,'') AS EmergencyStreetOne,
			ISNULL(EC.EmergencyStreetTwo,'') AS EmergencyStreetTwo,
			ISNULL(EC.EmergencyStreetThree,'') AS EmergencyStreetThree,
			ISNULL(EC.EmergencyCity,'') AS EmergencyCity,
			ISNULL(EC.EmergencyState,'') AS EmergencyState,
			ISNULL(EC.EmergencyCountry,'') AS EmergencyCountry,
			ISNULL(EC.EmergencyZipCode,'') AS EmergencyZipCode,
			ISNULL(PanNumber,'') AS PanNumber,
			EC.EmergencyContactNo AS EmergencyContactNo,
			EPD.Qualification AS Qualification,
			--ISNULL(EM.MiddleName,'')AS FatherName,
			ISNULL(ECD.MiddleName,'')AS FatherName,
			ECD.GenderTitle,
			ISNULL(ECD.FirstName,'')AS FirstName,
			ISNULL(ECD.LastName,'')AS SurName,
			(CASE WHEN RelationshipId = 2 THEN EFD.MobileNo ELSE '' END )AS FatherContactNo,
			ISNULL(@rBatchName,'') AS BatchName,
			ISNULL(EC.PresentContactNo,'') AS PresentContactNo,
			--added by megha for 0027070
			ISNULL(ECD.CompanyEmail,'')AS CompanyEmail,
			ISNULL(EC.PersonalEmail,'')AS PersonalEmail,
			ISNULL(ECD.EmployeeGrade,'')AS EmployeeGrade

		FROM 
			sHrm.vEmployeeCommonDetail ECD
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=ECD.OrgID
			LEFT JOIN sHrm.tEmployeeImages EI ON EI.EmployeeId=ECD.EmployeeId
			LEFT JOIN sHrm.tEmployeeICardOrg ICO ON ECD.OrgId = ICO.OrgId
			LEFT JOIN sHrm.tEmployeeCommunications EC ON ECD.EmployeeId = EC.EmployeeId
			LEFT JOIN sHrm.tEmployeeStatutoryAndOther EO ON EO.EmployeeId = ECD.EmployeeId
			LEFT JOIN sHrm.tEmployeePersonalDetail EPD ON EPD.EmployeeId = EO.EmployeeId
			LEFT JOIN sHrm.tEmployeeFamilyDetails EFD on ECD.EmployeeId=EFD.EmployeeId AND EFD.RelationshipId = 2
			--LEFT JOIN sCommon.tRelationshipMaster RM on EFD.RelationshipId=RM.Id AND RM.Id=2
			--LEFT JOIN sHrm.tEmployeeMaster EM on EM.Id = ECD.EmployeeId
			
		WHERE
		((ECD.Code LIKE @rEmployeeCode)OR @rEmployeeCode = '' )
	   AND (ISNULL(ECD.EmployeeId,0) NOT IN( SELECT cast(item as bigint) FROM  sCommon.fnsplit(@rStrEmployeeId,',')) OR @rStrEmployeeId='') 
	   AND (ISNULL(ECD.Code,'') IN( SELECT cast(item as nvarchar(20)) FROM  sCommon.fnsplit(@rStrCode,',')) OR @rStrCode='')   
	   AND (ECD.EmployeeTypeId = @rEmployeeTypeId OR @rEmployeeTypeId = 0)
	   AND (ECD.OrganizationDepartmentId = @rDepartmentId OR @rDepartmentId = 0)
	   AND (ECD.EmployeeStatusId = @rEmployeeStatusId OR @rEmployeeStatusId = 0)
	   AND (ECD.EmployeeGroupId=@rEmployeeGroupId OR @rEmployeeGroupId=0)
	   AND (ECD.EmployeeGradeId = @rGradeId OR @rGradeId = 0)
	   AND (ECD.EmployeeDesignationId = @rDesignationId OR @rDesignationId = 0)	 	   
	   AND (ECD.GenderId = @rGenderId OR @rGenderId = 0)  	    
	   AND (ECD.EmployeeId = @rEmployeeId OR @rEmployeeId = 0)	   
	   --AND ((DATEDIFF(yy,ECD.DateOfBirth,GETDATE()) <= @rAgeTo) OR (ISNULL(@rAgeTo,0)=0))
	   --AND ((DATEDIFF(yy,ECD.DateOfBirth,GETDATE()) >= @rAgeFrom)OR (ISNULL(@rAgeFrom,0)=0))
	   AND  ECD.OrgId = @rOrgId
	   AND ISNULL(ECD.IsOtherUser,0)=0
	  
END
GO
PRINT N'Altering Procedure [sPayroll].[pPayElementAdd]...';


GO

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

BEGIN

	BEGIN TRY
	BEGIN TRANSACTION  
	DECLARE @lNextNumber BIGINT

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


GO

ALTER PROCEDURE [sSecurity].[pPendingLoginStudentdGet]
	
	@rOrgId smallint,
	@rBatchId int,
	@rIsPendingLogin bit,
	@rIsCreatedLogin bit,
	@rClassId int = 0,
	@rDivisionId int = 0,
	@rNotRegister bit = 0

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	SELECT 
	-- TOP 100
			ISNULL(U.Id,0) AS Id,
			SC.StudentId,
			SC.Code,
			SC.Name,
			SC.ClassName + '-' + SC.DivisionName AS ClassName,
			SC.RollNo,
			ISNULL(SC.ParentContactNo,'') AS MobileNo,
			ISNULL(SC.ParentEmail,'') AS EmailId,
			U.LoginTitle AS UserName,
			U.LoginPassword,
			SC.SUId,
			SM.Title AS Status,
			(CASE WHEN A.UserId IS NULL THEN 'Not Register' ELSE 'Register' END) AS UserRegisterStatus,
			ISNULL(SC.WhatsAppContactNo,'') AS WhatsAppContactNo,
			SC.Number
	FROM 
			sStudent.vStudentCommunication SC
			LEFT JOIN sSecurity.tUser U ON U.SourceId = SC.StudentId AND U.SourceTypeId=2003
			INNER JOIN sStudent.tStatusMaster SM ON SM.Id = SC.StatusId 
			LEFT JOIN 
			(
				SELECT DISTINCT UserId FROM sCommunication.tRegisteredUsers
			) AS A ON A.UserId = U.Id
	WHERE 
			((U.LoginPassWord is Null AND @rIsPendingLogin=1) OR (U.LoginPassWord is NOT Null AND @rIsCreatedLogin=1))
			 AND	(SC.OrgId = @rOrgId)
			 AND	(SC.BatchId = @rBatchId) 
			 AND	((SC.ClassId = @rClassId) OR(@rClassId=0))
			 AND	((SC.DivisionId = @rDivisionId) OR(@rDivisionId=0))
			 AND SC.StatusId = 1
			 AND ((A.UserId IS NULL AND @rNotRegister = 1) OR (@rNotRegister = 0))
	Order By SC.DivisionOrderIndex,SC.RollNo
	
END
GO
PRINT N'Altering Procedure [sSecurity].[pVerifyOTP]...';


GO
ALTER PROCEDURE [sSecurity].[pVerifyOTP]

	@rUserMobileNumber nvarchar(50)='',
	@rOrgId int=0,
	@rOTP nvarchar(10)='',
	@rUserId bigint=0
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON;
BEGIN
	
	DECLARE @rUserSourceId bigint=0
	
	DECLARE @newpwd VARCHAR(100)
	DECLARE @LoginTitle nvarchar(100)
	DECLARE @LoginPassword nvarchar(200)
	
	SELECT @rUserSourceId = SU.SourceId 
	FROM sSecurity.tUser SU WHERE OrgId = @rOrgId AND SourceTypeId = 2003 AND Id = @rUserId
	print @rUserSourceId
	IF EXISTS (SELECT 1 FROM sSecurity.tUser WHERE Id = @rUserId and TempPasswordCode = @rOTP)
	BEGIN
		IF EXISTS(SELECT 1 FROM sSecurity.tUser WHERE Id = @rUserId  and TempPasswordCode = @rOTP and DATEDIFF(SECOND,OTPExpiryDate,GETDATE()) <0)
		BEGIN
			SELECT @LoginTitle= LoginTitle  , @LoginPassword = LoginPassword FROM sSecurity.tUser Where ID = @rUserId and TempPasswordCode=@rOTP
			UPDATE sSecurity.tUser SET TempPasswordCode = NULL	WHERE Id = @rUserId  and TempPasswordCode = @rOTP		
			SELECT 1 AS Result ,'OTP Matched' AS [Message],@LoginTitle As UserName , @LoginPassword As 'Password'
			RETURN
		END
		ELSE
		BEGIN
			SELECT -101 AS Result ,'OTP Expired' AS [Message],@rUserId AS UserId
			RETURN
		END
	END
	ELSE
	BEGIN
		SELECT -102 AS Result ,'OTP does not match' AS [Message],@rUserId AS UserId
		RETURN
	END
END
GO
PRINT N'Altering Procedure [sStudent].[pDigitalFormMasterAdd]...';


GO
 
ALTER PROCEDURE [sStudent].[pDigitalFormMasterAdd]
	 
        @rId bigint = 0,
		@rCode nvarchar(100), 
		@rTitle nvarchar(100),
		@rIsObsolete bit =0,
		@rCreatedUserId bigint,
		@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, 'sStudent.tDigitalForm', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	INSERT INTO sStudent.tDigitalForm
		(
			Id
		   ,Code
		   ,Title
		   ,OrgId
		   ,IsObsolete
		   ,CreatedUserId
           ,CreatedDateTime
		)
	VALUES
		(
			@lNextNumber,
			@rCode,
			@rTitle,
			@rOrgId,
			@rIsObsolete,
			@rCreatedUserId,
			sCommon.fGetDate()
		)

	 
		    SELECT @lNextNumber AS Result
	END	 

ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE sStudent.tDigitalForm
	    SET
			 
        	 Id = @lNextNumber
		   ,Code = @rCode
		   ,Title = @rTitle
		   ,OrgId = @rOrgId
		   ,IsObsolete = @rIsObsolete
		   ,UpdatedUserId = @rCreatedUserId
           ,UpdatedDateTime = sCommon.fGetDate()

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


GO

ALTER PROCEDURE [sStudent].[pRptStudentLCVerificationGet]
	 
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 @rDepartmentId int=0,
	 @rClassId int=0,
	 @rDivisionId int=0,
     @rStrCode nvarchar(20)='',
	 @rStatusId int=0,
	 @rClassStatusId int=0,
	 @rExamId int = 0
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
	
	
	IF(@rExamId!=0)
	 BEGIN
	 SELECT 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			L.Id,		
			vSA.Code,
			L.AcademicId,
			vSA.FirstName,vSA.MiddleName,vSA.LastName,
			[sStudent].[fStudentNameGet](vSA.FirstName , vSA.MiddleName, vSA.LastName,OM.StudentNameFormatId ) AS Name,
			ISNULL(SF.FatherName,'') As FatherName,
			ISNULL(SF.MotherName,'') As MotherName,
			ISNULL(so.BirthPlace,'') AS BirthPlace,
			ISNULL(SO.BirthTaluka,'') AS BirthTaluka,
			ISNULL(SO.BirthDistrict,'') AS BirthDistrict,
			SO.DateOfBirth,
			ISNULL(SO.BirthDateInWord,'') AS BirthDateInWord,
			L.LCNumber,
			L.LeftDate,
			L.LCReason,
			L.LCProgress,
			L.LCConduct,
			L.LCRemark,
			L.LCDate,
			L.LCBookNumber,
			ISNULL(SO.FamilySubCast,'') AS SubCaste,
			ISNULL(SO.FamilyCast,'') AS Caste,
		    vSA.StatusId,		
		 	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,			
			vSA.ClassName AS ClassName,
			vSA.DivisionName AS DivisionName,	
			isnull(MainCastCategoryId,0) AS CastCategoryId,
			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,
			SO.UIDNumber,
			L.LCCopy
			,vSA.BatchName AS BatchName,
		    ISNULL(SA.AdmissionNumber,'') AS AdmissionNumber,
			SO.UIDNumber,	
			ISNULL(OM.ReportOrgGroupTitle,'') AS ReportOrgGroupTitle,
			OM.ReportOrgTitle,	
    		ISNULL(CMS.ClassNameInWord,'') AS ClassNameInWord,
			vSA.ClassId AS ClassId,
		    OM.PrincipalSignature,
			ISNULL(R.Percentage,0) As Percentage,
			ISNULL(SCM.Title,'') AS LeftStandard
	FROM 
			sCertificate.tLeaving L
			INNER JOIN sStudent.vStudentAcademic vSA ON vSA.AcademicId=L.AcademicId	
			LEFT JOIN sStudent.tStudentAdmission SA ON SA.StudentId=vSA.StudentId			
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=vSA.OrgId 
			LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId=vSA.StudentId 		
			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.tCastCategoryMaster CSM ON CSM.Id=SO.CastCategoryId
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id=vSA.BatchId 
			LEFT JOIN sStudent.tStudentAdditional SD ON SD.StudentId=vSA.StudentId
			LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId=vSA.StudentId
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId=vSA.ClassId
            LEFT JOIN sAssessment.tResult R ON R.ExamId = EM.Id AND vSA.AcademicId = R.AcademicId
			LEFT JOIN sSetup.tClassMaster SCM ON SCM.Id = SA.LeftStandardId
	Where		
	           ((vSA.DepartmentId=@rDepartmentId) OR(@rDepartmentId=0))
	       AND ((vSA.ClassId=@rClassId) OR(@rClassId=0))	  
	       AND ((vSA.DivisionId=@rDivisionId) OR (@rDivisionId=0))	
		   AND (ISNULL(vSA.Code,0) IN( SELECT cast(item as nvarchar(20)) FROM  sCommon.fnsplit(@rStrCode,',')) OR @rStrCode='')
           AND ((vSA.StatusId=@rStatusId)OR(@rStatusId=0))
		   AND ((vSA.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0)) 
		   AND ((EM.Id = @rExamId) OR (@rExamId=0))	
    END		
	
	ELSE 
	  BEGIN
	     SELECT
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			L.Id,		
			vSA.Code,
			L.AcademicId,
			vSA.FirstName,vSA.MiddleName,vSA.LastName,
			[sStudent].[fStudentNameGet](vSA.FirstName , vSA.MiddleName, vSA.LastName,OM.StudentNameFormatId ) AS Name,
			ISNULL(SF.FatherName,'') As FatherName,
			ISNULL(SF.MotherName,'') As MotherName,
			ISNULL(so.BirthPlace,'') AS BirthPlace,
			ISNULL(SO.BirthTaluka,'') AS BirthTaluka,
			ISNULL(SO.BirthDistrict,'') AS BirthDistrict,
			SO.DateOfBirth,
			ISNULL(SO.BirthDateInWord,'') AS BirthDateInWord,
			L.LCNumber,
			L.LeftDate,
			L.LCReason,
			L.LCProgress,
			L.LCConduct,
			L.LCRemark,
			L.LCDate,
			L.LCBookNumber,
			ISNULL(SO.FamilySubCast,'') AS SubCaste,
			ISNULL(SO.FamilyCast,'') AS Caste,
		    vSA.StatusId,		
		 	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,			
			vSA.ClassName AS ClassName,
			vSA.DivisionName AS DivisionName,	
			isnull(MainCastCategoryId,0) AS CastCategoryId,
			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,
			SO.UIDNumber,
			L.LCCopy
			,vSA.BatchName AS BatchName,
		    ISNULL(SA.AdmissionNumber,'') AS AdmissionNumber,
			SO.UIDNumber,	
			ISNULL(OM.ReportOrgGroupTitle,'') AS ReportOrgGroupTitle,
			OM.ReportOrgTitle,	
    		ISNULL(CMS.ClassNameInWord,'') AS ClassNameInWord,
			vSA.ClassId AS ClassId,
		    OM.PrincipalSignature,
			0 As Percentage,
			ISNULL(SCM.Title,'') AS LeftStandard
	FROM 
			sCertificate.tLeaving L
			INNER JOIN sStudent.vStudentAcademic vSA ON vSA.AcademicId=L.AcademicId	
			LEFT JOIN sStudent.tStudentAdmission SA ON SA.StudentId=vSA.StudentId			
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=vSA.OrgId 
			LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId=vSA.StudentId 
			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.tCastCategoryMaster CSM ON CSM.Id=SO.CastCategoryId
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id=vSA.BatchId 
			LEFT JOIN sStudent.tStudentAdditional SD ON SD.StudentId=vSA.StudentId
			LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId=vSA.StudentId
			LEFT JOIN sSetup.tClassMaster SCM ON SCM.Id = SA.LeftStandardId
	Where		
	           ((vSA.DepartmentId=@rDepartmentId) OR(@rDepartmentId=0))
	       AND ((vSA.ClassId=@rClassId) OR(@rClassId=0))	  
	       AND ((vSA.DivisionId=@rDivisionId) OR (@rDivisionId=0))	
		   AND (ISNULL(vSA.Code,0) IN( SELECT cast(item as nvarchar(20)) FROM  sCommon.fnsplit(@rStrCode,',')) OR @rStrCode='')
           AND ((vSA.StatusId=@rStatusId)OR(@rStatusId=0))
		   AND ((vSA.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0)) 
	  END 			
END
GO
PRINT N'Altering Procedure [sStudent].[pStudentViewProfileGet]...';


GO
ALTER PROCEDURE [sStudent].[pStudentViewProfileGet]
	 
	 @rBatchId int,
	 @rAcademicId bigint,
	 @rReportId int=0,
	 @rOrgId int,
	 @rOrgGroupBatchId int
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
	
	SELECT 
			SA.StudentId AS Id,
			SA.SUId,
			SA.FirstName + ' ' + ISNULL(SA.MiddleName,'') + ' ' + 	SA.LastName AS StudentName,
			ISnull(SA.Batch,'') AS AcademicYear,
			ISNULL(SA.Code,' ') AS Code,
			SA.ClassDivision AS ClassDiv,			
			Isnull(SA.RollNo,'') AS RollNo,
			convert(varchar,ISNULL(SA.DateOfBirth,'0001/01/01'),103) AS DateOfBirth,
			ISNULL(SM.Title,'-') AS House,
			ISNULL(SA.BirthTaluka,'') AS BirthTaluka,
			ISNULL(SA.BirthPlace,'') AS BirthPlace,	
			ISNULL(SA.BirthDistrict,'') AS BirthDistrict,
			ISNULL(SA.BirthDateInWord,'') AS BirthDateInWord,                           
			ISNULL(SA.Gender,'') AS Gender,
			ISNULL(SA.Religion,'') AS Religion,
			ISNULL(SA.AdmissionStandard,'') AS AdmissionStandard,
			convert(varchar,ISNULL(SA.AdmissionDate,'0001/01/01'),103) AS AdmissionDate,
			ISNULL(SA.PreviousSchool,'') AS PreviousSchool,
			ISNULL(SA.AdmissionCategory,'') AS StudentAdmissionCategory,
            convert(varchar,ISNULL(SA.LeftDate,'0001/01/01'),103) AS LeftDate,
			ISNULL(SA.LeftStandard,'') AS LeftStandard,
			convert(varchar,ISNULL(SA.InactiveDate,'01/01/0001'),103) AS InactiveDate,
			ISNULL(SA.LCNumber,'') AS LCNumber,
			convert(varchar,ISNULL(SA.LCDate,'01/01/0001'),103) AS LCDate,
			ISNULL(SA.PresentStreetone,'') + ' ' + ISNULL(SA.PresentStreetTwo,'') + ' ' + ISNULL(SA.PresentStreetThree,'') AS PresentAddress,
			ISNULL(SA.PresentCity,'') AS PresentCity,
			ISNULL(SA.PresentState,'') AS PresentState,
			ISNULL(SA.PresentCountry,'') AS PresentCountry,
			ISNULL(SA.PresentZipCode,'') AS PresentZipCode,
			ISNULL(SA.PresentContactNo,'') AS PresentContactNo,
			ISNULL(SA.EmergencyStreetOne,'') + ' ' + ISNULL(SA.EmergencyStreetTwo,'') + ' ' + ISNULL(SA.EmergencyStreetThree,'') AS EmergencyAddress,
			ISNULL(SA.EmergencyCity,'') AS EmergencyCity,
			ISNULL(SA.EmergencyState,'') AS EmergencyState,
			ISNULL(SA.EmergencyCountry,'') AS EmergencyCountry,
			ISNULL(SA.EmergencyZipCode,'') AS EmergencyZipCode,
			ISNULL(SA.EmergencyContactNo,'') AS EmergencyContactNo,
			ISNULL(SA.PermanentStreetOne,'') + ' ' + ISNULL(SA.PermanentStreetTwo,'') + ' ' + ISNULL(SA.PermanentStreetThree,'') AS PermanentAddress,
			ISNULL(SA.PermanentCity,'') AS PermanentCity,
			ISNULL(SA.PermanentState,'') AS PermanentState,
			ISNULL(SA.PermanentCountry,'') AS PermanentCountry,
			ISNULL(SA.PermanentZipCode,'') AS PermanentZipCode,
			ISNULL(SA.PermanentContactNo,'') AS PermanentContactNo,
			ISNULL(SF.FatherName,'') AS FatherName,
			ISNULL(SF.FatherOccupation,'') AS FatherOccupation,
			ISNULL(SF.FatherQualification,'') AS FatherQualification,
			ISNULL(SF.FatherContactNo,'') AS FatherContactNo,
			ISNULL(SF.FatherMail,'') AS FatherMail,
			ISNULL(SF.FatherOfficeAddress,'') AS FatherOfficeAddress,
			ISNULL(SF.FatherDesignation,'') AS FatherDesignation,
			ISNULL(SF.FatherOrganization,'') AS FatherOrganization,
			ISNULL(SF.MotherName,'') AS MotherName,
			ISNULL(SF.MotherOccupation,'') AS MotherOccupation,
			ISNULL(SF.MotherQualification,'') AS MotherQualification,
			ISNULL(SF.MotherContactNo,'') AS MotherContactNo,
			ISNULL(SF.MotherMail,'') AS MotherMail,
			ISNULL(SF.MotherOfficeAddress,'') AS MotherOfficeAddress,
			ISNULL(SF.MotherDesignation,'') AS MotherDesignation,
			ISNULL(SF.MotherOrganization,'') AS MotherOrganization,
			ISNULL(SF.RelationshipName,'') AS RelationShip,
			ISNULL(SF.RelativeName,'') AS RelativeName,
			ISNULL(SF.RelativeOccupation,'') AS RelativeOccupation,
			ISNULL(SF.RelativeQualification,'') AS RelativeQualification,
			ISNULL(SF.RelativeContactNo,'') AS RelativeContactNo,
			ISNULL(SF.RelativeMail,'') AS RelativeMail,
			ISNULL(SF.RelativeOfficeAddress,'') AS RelativeOfficeAddress,
			ISNULL(SF.RelativeDesignation,'') AS RelativeDesignation,
			ISNULL(SF.RelativeOrganization,'') AS RelativeOrganization,
			ISNULL(SA.BloodGroup,'') AS BloodGroup,
			ISNULL(SH.IdentificationMark1,'')+' '+ISNULL(SH.IdentificationMark2,'') as IdentificationMark,
			ISNULL(SH.FamilyDoctorName,'') AS FamilyDoctorName,
			ISNULL(SH.FamilyDoctorContactNo,'') AS FamilyDoctorContactNo,
			case When isnull(SH.IsPysicalDeformity,0)=0 then 'NO' Else 'Yes' End As IsPysicalDeformity,
			SH.PysicalDeformityRemark ,
			case When isnull(SH.IsMajorIllness,0)=0 then 'NO' Else 'Yes' End As IsMajorIllness,
			ISNULL(SH.MajorIllnessRemark,'') As MajorIllnessRemark,
			 case When isnull(SH.IsAllergy,0)=0 then 'NO' Else 'Yes' End As IsAllergy,
			ISNULL(SH.AllergyRemark,'') As AllergyRemark,
			 case When isnull(SH.IsPastHistory,0)=0 then 'NO' Else 'Yes' End As IsPastHistory,
			ISNULL(SH.PastHistoryRemark,'') As PastHistoryRemark,
			ISNULL(RM.Title,'') AS RoomNo,			
			ISNULL(HM.Title,'') AS Hostel,
			ISNULL(EMW.FirstName,'')+' '+ISNULL(EMW.LastName,'') AS WardenName,
			ISNULL(ECW.PhoneNoCompany,'') As WardenPhoneNo,
			ISNULL(ECW.ExtensionNo,'') AS WardenExtNo,
			ISNULL(ECW.MobileNumber,'') AS WardenMobileNo,
			ISNULL(EMA.FirstName,'')+' '+ISNULL(EMA.LastName,'') AS AssignedRoomBy,	
			ISNULL(ECA.PhoneNoCompany,'') AS AssignedRoomByPhoneNo,
			ISNULL(ECA.ExtensionNo,'') AS AssignedRoomByExtNo,
			ISNULL(ECA.MobileNumber,'') AS AssignedRoomByMobileNo,
			--Notification Details
			ISNULL(SA.ParentEmail,'') AS ParentEmail,
			ISNULL(SA.ParentContactNo,'') As ParentContactNo,
			ISNULL(SA.WhatsAppContactNo,'') As WhatsAppContactNo,
			ISNULL(SA.StudentEmail,'') AS StudentEmail,
			ISNULL(SA.StudentContactNo,'') AS StudentContactNo,
		    ISnull( A.VehicleName,'') AS VehicleName,
		    ISNULL( A.VehicleRegistrationNumber,'') AS VehicleRegistrationNumber,
		    ISNULL(A.TypeOfVehicle ,'') AS TypeOfVehicle ,
		    ISNULL(A.BusRoute,'') AS BusRoute,
		    ISNULL( A.DriverName,'') AS DriverName,
		    ISNULL(A.DriverMobileNo,'') AS DriverMobileNo,
		    ISNULL( A.ConductorName,'') AS ConductorName,
		    ISNULL( A.ConductorMobileNo,'') AS ConductorMobileNo ,
		    ISNULL(A.BusRouteDestination,'') AS BusRouteDestination,
		    isnull(A.DropVehicleName,'') AS DropVehicleName,
		    isnull(A.DropVehicleRegistrationNumber,'') AS DropVehicleRegistrationNumber,
		    isnull(A.DropTypeOfVehicle,'') AS DropTypeOfVehicle,
		    ISNULL(A.DropRoute,'') AS DropRoute,
		    isnull( A.DriverName,'') AS DropRouteDriverName,
		    isnull(A.DriverMobileNo,'') AS DropRouteDriverMobileNo,
		    isnull(A.ConductorName,'') AS DropRouteConductorName,
		    isnull(A.ConductorMobileNo,'') AS DropRouteConductorMobileNo,
		    ISNULL(A.DropDestination,'') AS DropDestination,
		    --ISNULL( EMT.FirstName+' '+EMT.MiddleName+' '+EMT.LastName,'') AS TeacherFullName,
		    --isnull( EDM.Title,'') AS TeacherDesignation,
		    --ISNULL( EPD.Qualification,'') AS TeacherQualification,
		    ISNULL(DF.IsDisplayFamilyDetail,0) AS IsDisplayFamilyDetail,
		    ISNULL(DF.IsDisplaySiblingDetail,0) AS IsDisplaySiblingDetail,
		    ISNULL(DF.IsDisplayPassportDetail,0) AS IsDisplayPassportDetail,
		    ISNULL(DF.IsDisplayBankDetail,0) AS IsDisplayBankDetail,
		    ISNULL(DF.IsDisplayCBSEREGDetail,0) AS IsDisplayCBSEREGDetail,
		    ISNULL(DF.IsDisplayCollegeDetail,0) AS IsDisplayCollegeDetail,
		    ISNULL(DF.IsDisplayGOVREGNoDetail,0) AS IsDisplayGOVREGNoDetail,
		    ISNULL(DF.IsDisplayHealthDetail,0) AS IsDisplayHealthDetail,
		    ISNULL(DF.IsDisplayTransportDetail,0) AS IsDisplayTransportDetail,
		    ISNULL(DF.IsDisplayHostelDetail,0) AS IsDisplayHostelDetail,
		    ISNULL(DF.IsDisplayClubDetail,0) AS IsDisplayClubDetail,
		    
		    ISNULL(DF.IsDisplaySSCResultDDetail,0) AS IsDisplaySSCResultDDetail,
		    ISNULL(DF.IsDisplayHSCResultDetail,0) AS IsDisplayHSCResultDetail,
		    ISNULL(DF.IsDisplayJeeDetail,0) AS IsDisplayJeeDetail,
		    ISNULL(DF.IsDisplayDiplomaDetail,0) AS IsDisplayDiplomaDetail,
		
		    isnull(SS.SiblingName1,'') AS SiblingName1,
	        ISNULL (SS.SiblingInstitue1,'') AS SiblingInstitue1,
	        ISNULL(SS.SiblingClass1,'')AS SiblingClass1,
	        ISNULL(SS.SiblingAge1,'')AS SiblingAge1,
	        ISNULL(SS.SiblingRelation1,'')AS SiblingRelation1,
	        isnull(SS.SiblingName2,'') AS SiblingName2,
	        ISNULL(SS.SiblingInstitue2,'')AS SiblingInstitue2,
	        ISNULL(SS.SiblingClass2,'')AS SiblingClass2,
	        ISNULL(SS.SiblingAge2,'') AS SiblingAge2,
	        ISNULL(SS.SiblingRelation2,'')AS SiblingRelation2,
	        isnull(SS.SiblingName3,'') AS SiblingName3,
	        ISNULL( SS.SiblingInstitue3,'')AS SiblingInstitue3,
	        ISNULL(SS.SiblingClass3,'')AS SiblingClass3,
	        ISNULL(SS.SiblingAge3,'')AS SiblingAge3,
	        ISNULL(SS.SiblingRelation3,'')AS SiblingRelation3,
	        ISNULL(SAD.BankAccountNumber,'')AS BankAccountNumber,
	        ISNULL(SAD.BankName,'')AS BankName,
	        ISNULL(SAD.BankBranch,'') AS BankBranch,
	        ISNULL(SAD.BankIFSCCode,'')AS BankIFSCCode,
	        ISNULL(SAD.Class9BoardRegistrationNumber,'') AS Class9BoardRegistrationNumber,
	        ISNULL(SAD.Class11BoardRegistrationNumber,'')AS Class11BoardRegistrationNumber,
	        ISNULL(SAD.PassportNumber,'')AS PassportNumber, 
	        ISNULL(SAD.PassportType,'') AS PassportType,
	        ISNULL( SAD.PassportCountryCode,'') AS PassportCountryCode,
	       	convert(varchar,ISNULL(SAD.PassportExpiryDate,'01/01/0001'),103) AS PassportExpiryDate,
	       	convert(varchar,ISNULL(SAD.PassportIssueDate,'01/01/0001'),103) AS PassportIssueDate,
	        ISNULL(SA.UIDNumber,'')AS UIDNumber,
	        ISNULL(SA.AdhaarNumber,'') AS AdhaarNumber,
	        case When isnull(SA.IsTransfer,0)=0 then 'No' Else 'Yes' End As IsTransfer,
	        ISNULL(SA.TransferFrom,'') AS TransferFrom,
	        ISNULL(SA.CertificateName,'') AS CertificateName,
	        case When isnull(SA.IsTFWS,0)=0 then 'No' Else 'Yes 'End As IsTFWS,
	        case When isnull(SA.IsCertificateHolder,0)=0 then 'No' Else 'Yes' End As IsCertificateHolder,
	        ISNULL(CD.SSCBoard,'') AS SSCBoard,
	        ISNULL(CD.SSCSchool,'') AS SSCSchool,
	        ISNULL(CD.SSCPassingYear,'') AS SSCPassingYear,
	        ISNULL(CD.SSCObtainMarks,0) AS SSCObtainMarks,
	        ISNULL(CD.SSCOutOfMarks,0) AS SSCOutOfMarks,
	        ISNULL(CD.SSCMathMarks,0) AS SSCMathMarks,
	        ISNULL(CD.SSCMathOutOfMarks,0) AS SSCMathOutOfMarks,
	        ISNULL(CD.SSCPercentage,0) AS SSCPercentage,
	        ISNULL(CD.HSCBoard,'') AS HSCBoard,
	        ISNULL(CD.HSCSchool,'') AS HSCSchool,
	        ISNULL(CD.HSCPassingYear,0) AS HSCPassingYear,
	        ISNULL(CD.HSCObtainMarks,0) AS HSCObtainMarks,
	        ISNULL(CD.HSCOutOfMarks,0) AS HSCOutOfMarks,
	        ISNULL(CD.HSCPercentage,0) AS HSCPercentage,
	        ISNULL(CD.HSCPhysicsMarks,0) AS HSCPhysicsMarks,
	        ISNULL(CD.HSCPhysicsOutOfMarks,0) AS HSCPhysicsOutOfMarks,
	        ISNULL(CD.HSCChemistryMarks,0) AS HSCChemistryMarks,
	        ISNULL(CD.HSCChemistryOutOfMarks,0) AS HSCChemistryOutOfMarks,
	        ISNULL(CD.HSCMathMarks,0) AS HSCMathMarks,
	        ISNULL(CD.HSCMathOutOfMarks,0) AS HSCMathOutOfMarks,
	        ISNULL(CD.HSCBiologyMarks,0) AS HSCBiologyMarks,
	        ISNULL(CD.HSCBiologyOutOfMarks,0) AS HSCBiologyOutOfMarks,
	        ISNULL(CD.PCMMarks,0) AS PCMMarks,
	        ISNULL(CD.PCBMarks,0) AS PCBMarks,
	        ISNULL(CD.JEERollNo,'') AS JEERollNo,
	        ISNULL(CD.JEEMeritNo,'') AS JEEMeritNo,
	        ISNULL(CD.JEEMeritMarks,0) AS JEEMeritMarks,
	        ISNULL(CD.JEEOutOfMarks,0) AS JEEOutOfMarks,
	        ISNULL(CD.DiplomaBoard,'') AS DiplomaBoard,
	        ISNULL(CD.DiplomaCollege,'') AS DiplomaCollege,
	        ISNULL(CD.DiplomaPassingYear,'') AS DiplomaPassingYear,
	        ISNULL(CD.DiplomaObtainMarks,0) AS DiplomaObtainMarks,
	        ISNULL(CD.DiplomaOutOfMarks,0) AS DiplomaOutOfMarks,
	        ISNULL(CD.DiplomaPercentage,0) AS DiplomaPercentage,
	        ISNULL(CD.ApplicationNo,'') AS ApplicationNo,
	        ISNULL(CD.AdmissionRound,0) AS AdmissionRound,
            ISNULL(MS.Title,'') AS MaritalStatus,
	        ISNULL(ACD.RepeatCount,1)AS RepeatCount,
	        ISNULL(SA.MotherTongue,'') As MotherTongue,
	        ISNULL(SA.FamilyCast,'') AS FamilyCast,
			ISNULL(SA.FamilySubCast,'') AS FamilySubCast,
	        ISNULL(CM.Nationality,'') AS Nationality,
            ISNULL(CT.Title,'') AS CasteCategory,
            --StudentPhoto = case when SA.StudentPhoto is null then '' else SA.StudentPhoto end,
	        StudentPhoto=(SELECT CAST(SA.StudentPhoto as varbinary(max)) FOR XML PATH(''), BINARY BASE64) ,
			--TeacherPhoto=(SELECT CAST(EI.EmployeePhoto as varbinary(max)) FOR XML PATH(''), BINARY BASE64) ,
			FatherPhoto=(SELECT CAST(SA.FatherPhoto as varbinary(max)) FOR XML PATH(''), BINARY BASE64) ,
			MotherPhoto=(SELECT CAST(SA.MotherPhoto as varbinary(max)) FOR XML PATH(''), BINARY BASE64) ,
			RelativePhoto=(SELECT CAST(SA.RelativePhoto as varbinary(max)) FOR XML PATH(''), BINARY BASE64) ,
			ISNULL(SA.PreviousStandard,'')AS PreviousStandard
			,CGG.Title AS CustomGroup
			,SGM.Title As StudentGroup
			,SOGM.Title As StudentOtherGroup
			,ISNULL([sStudent].[fAssignedClubGet](@rAcademicId),'') AS ClubName
			,ISNULL([sStudent].[fAssignedCustomTagGet](@rAcademicId),'') AS CustomTag,
			ISNULL(SA.StudentPhoto, CONVERT(VARBINARY(MAX), 0))AS StudentImage,
		   DID.TeacherFullName,
		   DID.TeacherDesignation,
		   DID.TeacherQualification,
		   TeacherPhoto=(SELECT CAST(DID.TeacherPhoto as varbinary(max)) FOR XML PATH(''), BINARY BASE64)
  FROM 
           sStudent.vStudentAllDetail SA
           --LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId = SA.StudentId
           LEFT JOIN sStudent.tStudentHealth SH ON SA.StudentId=SH.StudentId
           LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId = SA.StudentId 
           --LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId = SA.StudentId
           LEFT JOIN sActivity.tHouseMaster SM ON SM.ID = SA.HouseId
           LEFT JOIN sHostel.tAssignRoom AR ON AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003  AND ((AR.OrgGroupBatchId=@rOrgGroupBatchId) OR(@rOrgGroupBatchId=0))
           LEFT JOIN sHostel.tRoomMaster RM ON RM.Id=AR.RoomId
           LEFT JOIN sHostel.tHostelMaster HM ON HM.Id=RM.HostelId 
           LEFT JOIN
           (
		   SELECT 
		   employeeId, 
		   HostelId,   
		   ROW_NUMBER() OVER (PARTITION BY HostelId ORDER By HostelId ) as ROWNo 
		   FROM sHostel.tHostelwarden 
            )  HW ON HW.HostelId=HM.Id AND RowNo = 1       
           --LEFT JOIN sHostel.tHostelWarden HW ON HW.HostelId=HM.Id
           LEFT JOIN sHrm.tEmployeeMaster EMW ON HW.EmployeeId=EMW.Id AND  ISNULL(EMW.IsOtherUser,0) = 0
           LEFT JOIN sHrm.tEmployeeMaster EMA ON RM.AssignedEmployeeId=EMA.Id AND  ISNULL(EMA.IsOtherUser,0) = 0
           LEFT JOIN sHrm.tEmployeeCommunications ECW ON EMW.Id=ECW.EmployeeId 
           LEFT JOIN sHrm.tEmployeeCommunications ECA ON  EMA.Id=ECA.EmployeeId
           LEFT JOIN 
           (SELECT AR1.SourceId ,
           ISnull( VM.Title,'') AS VehicleName,
		   ISNULL( VM.RegistrationNumber,'') AS VehicleRegistrationNumber,
		   ISNULL(TV.Title ,'') AS TypeOfVehicle ,
		   ISNULL(BRM.Title,'') AS BusRoute,
		   ISNULL( BRM.DriverName,'') AS DriverName,
		   ISNULL(BRM.DriverMobileNo,'') AS DriverMobileNo,
		   ISNULL( BRM.ConductorName,'') AS ConductorName,
		   ISNULL( BRM.ConductorMobileNo,'') AS ConductorMobileNo ,
		   ISNULL(BRDM.Title,'') AS BusRouteDestination,
		   isnull(VM.Title,'') AS DropVehicleName,
		   isnull(VM.RegistrationNumber,'') AS DropVehicleRegistrationNumber,
		   isnull(TV1.Title,'') AS DropTypeOfVehicle,
		   ISNULL(BRM1.Title,'') AS DropRoute,
		   isnull( BRM1.DriverName,'') AS DropRouteDriverName,
		   isnull(BRM1.DriverMobileNo,'') AS DropRouteDriverMobileNo,
		   isnull(BRM1.ConductorName,'') AS DropRouteConductorName,
		   isnull(BRM1.ConductorMobileNo,'') AS DropRouteConductorMobileNo,
		   ISNULL(BRDM1.Title,'') AS DropDestination

		   FROM sTransport.tAssignRoute AR1 
           INNER JOIN sTransport.tBusRouteDestinationMaster BRDM ON BRDM.Id=AR1.PickupDestinationId AND AR1.SourceTypeId=2003
           INNER JOIN sTransport.tBusRouteMaster BRM ON BRM.Id=BRDM.BusRouteId  AND ((BRM.OrgGroupBatchId=@rOrgGroupBatchId) OR(@rOrgGroupBatchId=0))
           LEFT JOIN sTransport.tVehicleMaster VM ON VM.Id=BRM.VehicleId
           LEFT JOIN sTransport.tVehicleTypeMaster TV ON TV.Id = VM.VehicleTypeId
           LEFT JOIN sTransport.tBusRouteDestinationMaster BRDM1 ON BRDM1.Id=AR1.DropDestinationId
           LEFT JOIN sTransport.tBusRouteMaster BRM1 ON BRM1.Id=BRDM1.BusRouteId AND ((BRM1.OrgGroupBatchId=@rOrgGroupBatchId) OR(@rOrgGroupBatchId=0))
           LEFT JOIN sTransport.tVehicleMaster VM1 ON VM1.Id=BRM1.VehicleId
           LEFT JOIN sTransport.tVehicleTypeMaster TV1 ON TV1.Id = VM1.VehicleTypeId)A ON A.SourceId=SA.StudentId
           --LEFT JOIN sSetup.tDivisionMaster DM ON  DM.Id=SA.DivisionId
           --LEFT JOIN sHrm.tEmployeeMaster EMT ON EMT.Id=DM.InchargeEmployeeId AND  ISNULL(EMT.IsOtherUser,0) = 0
           --LEFT JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EMT.Id
           --LEFT JOIN sHrm.tEmployeeDesignationMaster EDM ON EDM.Id=EJD.EmployeeDesignationId
           --LEFT JOIN sHrm.tEmployeePersonalDetail EPD ON EPD.EmployeeId=EMT.Id
           --LEFT JOIN sHrm.tEmployeeImages EI ON EI.EmployeeId=EMT.Id
		   LEFT JOIN (SELECT * FROM [sStudent].[fDivisionInchargeDetailsGet](@rAcademicId, @rBatchId)) DID ON SA.DivisionId = DID.DivisionId
           LEFT JOIN sStudent.tStudentSibling  SS ON SS.StudentId=SA.StudentId 
           LEFT JOIN sStudent.tStudentAdditional  SAD ON SAD.StudentId=SA.StudentId 
           LEFT JOIN sStudent.tCollegeDetail  CD ON CD.StudentId=SA.StudentId 
           LEFT JOIN sStudent.tAcademicDetail  ACD ON ACD.AcademicId=SA.AcademicId 
           LEFT JOIN sCommon.tMaritalStatusMaster  MS ON MS.Id=CD.MaritalStatusId
           LEFT JOIN sConfig.fDisplayFieldGet(@rOrgId) AS DF ON DF.OrgId=SA.OrgId
           LEFT JOIN sCommon.tCastCategoryMaster CT ON CT.Id = SA.CastCategoryId
           LEFT JOIN sCommon.tCountryMaster CM ON CM.Id=SA.NationalityId
           LEFT JOIN sCommunication.tCustomGroupMember CGM ON CGM.SourceId = SA.AcademicId AND CGM.SourceTypeId = 2001
           LEFT JOIN sCommunication.tCustomGroup CGG ON CGG.Id = CGM.CustomGroupId
           LEFT JOIN sStudent.tStudentMaster SMM ON SMM.Id = SA.StudentId
           LEFT JOIN sStudent.tStudentGroupMaster SGM ON SGM.Id = SMM.StudentGroupId
           LEFT JOIN sStudent.tStudentOtherGroupMaster SOGM ON SOGM.Id = SMM.StudentOtherGroupId
  WHERE 
		   ((SA.AcademicId=@rAcademicId)OR(@rAcademicId=0))
		   AND(SA.BatchId=@rBatchId)
		
END
GO
PRINT N'Creating Procedure [sAccounting].[pRptProfitAndLossGet]...';


GO
CREATE 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 @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,'',''
		
	CREATE TABLE #TempExpenseGroup
	(
	   Id INT IDENTITY(1,1),
	   ExpenseGroupId int,
	   ExpenseGroup nvarchar(200),
	   ExpenseLedger nvarchar(200),
	   Expense decimal(22,2),
	   OpeningBalance decimal(22,2),
	   TransactionBalance 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,
	   TransactionBalance 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 TransactionBalance
	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 TransactionBalance
	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,
	        Income,
	        ISNULL(ExpenseGroupId,0) AS ExpenseGroupId,
	        ISNULL(ExpenseGroup,'') AS ExpenseGroup,
	        ISNULL(ExpenseLedger,'') AS ExpenseLedger,
			ISNULL(OpeningBalance,0) AS OpeningBalance,	          
			ISNULL(Expense,0.00) AS Expense,
			ISNULL(TransactionBalance,0.00) AS TransactionBalance
		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,
	        ISNULL(Income,0) AS Income,
	        ISNULL(ExpenseGroupId,0) AS ExpenseGroupId,
	        ExpenseGroup AS ExpenseGroup,
	        ExpenseLedger,
			OpeningBalance,
			Expense,
			ISNULL(TransactionBalance,0.00) AS TransactionBalance
	    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 TransactionBalance
	    
END
GO
PRINT N'Creating Procedure [sAlert].[pAbsentEmployeeGet]...';


GO
CREATE PROCEDURE sAlert.pAbsentEmployeeGet

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

	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

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

	From
		sHrm.vEmployeeCommunication EC
	INNER JOIN sHrm.tEmployeeAttendanceRegister EAR  ON EAR.EmployeeId = EC.EmployeeId
	INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = EC.OrgId
	LEFT JOIN sAttendance.tAbsentReasonMaster AR ON EAR.AbsentReasonId = AR.Id

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

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


GO


CREATE PROCEDURE [sAlert].[pEventEmployeeAttendanceGet]

	 	 --@rEventScheduleId int,
		 @rEventName nvarchar(max),
	 	 @rEmployeeId bigint,
		 @rFromDate Date,
		 @rToDate Date,
		 --@rAttendanceType nvarchar(max),
		 @rIsPresent bit,
	 	 @rTemplate nvarchar(max),
	 	 @rMailSubject nvarchar(500)=''

	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

	Select
			EC.EmployeeId,
			EC.Code,
			EC.EmployeeName,
			ISNULL(EC.MobileNumber,'') AS MobileNo,
			ISNULL(EC.CompanyEmail,'') AS EmailId,
			REPLACE (
			REPLACE (
			REPLACE (
			REPLACE (
			REPLACE(@rTemplate,'[EventName]',@rEventName),
			'[EmployeeName]',EC.EmployeeName),
			'[Code]',EC.Code), 
			'[Date]',convert(varchar, @rFromDate, 103)  + '-' + convert(varchar, @rToDate, 103)),
			'[Type]',
			' Present : ' + CASE WHEN @rIsPresent = 1 THEN 'YES' ELSE 'NO' END) 
			AS MsgText,
			@rMailSubject AS Subject,
			EC.EmployeeId AS SourceId,
			95 AS SourceTypeId,
			EC.OrgId,
			OM.OrgGroupId,
			EC.EmployeeId AS ReceiverSourceId,
			95 AS ReceiverSourceTypeId,
			EC.WhatsAppContactNo

	From
		sHrm.vEmployeeCommunication EC
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = EC.OrgId
		
		WHERE 
		EC.EmployeeId = @rEmployeeId
		AND EC.StatusId = 7

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


GO


CREATE PROCEDURE [sAlert].[pEventStudentAttendanceGet]

	 	 --@rEventScheduleId int,
		 @rEventName nvarchar(max),
	 	 @rAcademicId bigint,
		 @rFromDate Date,
		 @rToDate Date,
		 @rAttendanceType nvarchar(max),
		 @rIsStudentPresent bit,
		 @rIsFatherPresent bit,
		 @rIsMotherPresent bit,
		 @rIsGuardianPresent bit,
	 	 @rTemplate nvarchar(max),
	 	 @rMailSubject nvarchar(500)=''

	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

	Select
			SC.AcademicId,
			SC.Code,
			SC.Name,
			SC.ParentContactNo AS MobileNo,
			SC.ParentEmail AS EmailId,
			REPLACE (
			REPLACE (
			REPLACE (
			REPLACE (
			REPLACE (
			REPLACE(@rTemplate,'[EventName]',@rEventName),
			'[StudentName]',vSA.Name),
			'[Code]',vSA.Code), 
			'[Date]',convert(varchar, @rFromDate, 103)  + '-' + convert(varchar, @rToDate, 103)),
			'[AttendanceType]',@rAttendanceType),
			'[Type]',
			' Student Present : ' + CASE WHEN @rIsStudentPresent = 1 THEN 'YES' ELSE 'NO' END + 
			', Father Present : ' + CASE WHEN @rIsFatherPresent = 1 THEN 'YES' ELSE 'NO' END + 
			', Mother Present : ' + CASE WHEN @rIsMotherPresent = 1 THEN 'YES' ELSE 'NO' END + 
			', Guardian Present : ' + CASE WHEN @rIsGuardianPresent = 1 THEN 'YES' ELSE 'NO' END) 
			AS MsgText,
			@rMailSubject AS Subject,
			SC.AcademicId AS SourceId,
			2001 AS SourceTypeId,
			SC.OrgId,
			SC.OrgGroupId,
			SC.AcademicId AS ReceiverSourceId,
			2001 AS ReceiverSourceTypeId,
			SC.WhatsAppContactNo

	From
	
		--sActivity.tEventSchedule ES
		--INNER JOIN sActivity.tEventAttendance EA ON ES.Id = EA.EventScheduleId
		sStudent.vStudentAcademic vSA 
		INNER JOIN sStudent.vStudentCommunication SC ON SC.AcademicId = vSA.AcademicId
		WHERE 
		vSA.AcademicId = @rAcademicId
		AND SC.IsBlockAllAlert=0
		AND (SC.StatusId=1)

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


GO
 
CREATE PROCEDURE [sAlert].[pStudentLeaveGet]
	 	 
	 	 @rAcademicId bigint,
	 	 @rTemplate nvarchar(max),
	 	 @rMailSubject nvarchar(500)='',
	 	 @rLeaveFromDate Date,
		 @rLeaveToDate Date

	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	
	SELECT 
			EC.MobileNumber AS MobileNo,	
			EC.CompanyEmail AS EmailId,
			SA.AcademicId,
			SA.Code,
			SA.Name,
			REPLACE (
			REPLACE (
			REPLACE (
			REPLACE(@rTemplate,'[Name]',SA.Name),
			'[FromDate]',SLR.LeaveFromDate),
			'[ToDate]',SLR.LeaveToDate), 
			'[LeaveReason]',SLR.LeaveReason) AS MsgText,
			@rMailSubject AS Subject,
			95 AS ReceiverSourceTypeId,
			EM.Id AS ReceiverSourceId,
			ISNULL(EC.WhatsAppContactNo,'') AS WhatsAppContactNo,
			95 AS SourceTypeId,
			EM.Id AS SourceId,
			EM.OrgId,
			OM.OrgGroupId
		
	From 
		sStudent.vStudentAcademic SA
		--INNER JOIN sStudent.vStudentCommunication SC ON SA.AcademicId = SC.AcademicId
		INNER JOIN sAttendance.tStudentLeaveRequest SLR ON SA.AcademicId = SLR.AcademicId
		--INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SA.OrgId
		--INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId
		--INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id = SC.DepartmentId
		LEFT JOIN sHrm.tEmployeeMaster EM ON SA.InchargeEmployeeId = EM.Id	
		LEFT JOIN sHrm.tEmployeeCommunications EC ON EC.EmployeeId = EM.Id
		INNER JOIN sSetup.tOrganizationMaster OM ON EM.OrgId = OM.Id
	WHERE
	
	SA.AcademicId = @rAcademicId
	AND SLR.LeaveFromDate = @rLeaveFromDate 
	AND SLR.LeaveToDate = @rLeaveToDate
	AND EM.IsObsolete = 0 AND ISNULL(EM.IsOtherUser,0) = 0 AND EM.StatusId = 7

END
GO
PRINT N'Creating Procedure [sAssessment].[pRptProgressCardSubjectWiseDetailsGet]...';


GO

CREATE PROCEDURE [sAssessment].[pRptProgressCardSubjectWiseDetailsGet]
	 
	 @rBuilder1 nvarchar(max)='', 
	 @rBuilder2 nvarchar(max)='', 
	 @rBatchId int = 0,
	 @rClassId int=0,
	 @rDivisionId int=0,
	 @rExamId int,
	 @rCode nvarchar(20)='',
	 @rFromRollNo int,
	 @rToRollNo int,
	 @rStatusId int=0,
	 @rClassStatusId int=0
	 
	
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	--Select
	--	'' AS Builder1,
	--	'' AS Builder2,
	--	'' AS AcademicIdText,
	--	'' Code,
	--	'' AS Name,
	--		0 AS RollNo,
	--	Convert(BigInt,0) AcademicId,			
	--	'' ResultStatus,
	--	'' AS Class,
	--	'' AS Division,
	--  0 AS ExamId,
	--	'' AS ExamName,
	--  Convert(Date,null) AS ExamDate,
	--		Convert(Decimal,0) TotalMark,
	--	Convert(Decimal,0) TotalObtain,
	--	0 AS RankNumber,
	--	Convert(Decimal,0) Percentage,
	--	'' AS ResultGrade,
	--	Convert(Decimal,0) Percentile,
	--	Convert(BigInt,0) ResultDetailId,		
	--	Convert(Bit,0) IsDisplayInMarksheet,
	--	Convert(Bit,0) IsShowSubjectGrade,
	--	Convert(Bit,0) IsIncludeInTotal,
	--	Convert(Decimal,0) AS SubjectObtain,
	--  '' AS SubjectGrade,
	--	Convert(Decimal,0) AS SubjectMinimum,
	--	Convert(Decimal,0) AS SubjectMaximum,
	--		'' AS SubjectCode,
	--	'' AS SubjectName,
	--	0 AS SubjectOrderIndex,
	--	Convert(BigInt,0) AS ResultId,
	--	0 AS SubjectId,			 	
	--	Convert(Bit,0) IsMarksInDecimal,		
	--	'' AS Remark1,
	--	'' AS Remark2,
	--	'' AS Remark3,
	--	'' AS DisplayTitle,
	--	Convert(Bit,0) IsRankNo, 
	--	Convert(Bit,0) IsGrade,
	--	Convert(Bit,0) IsPercentile,
	--	Convert(Bit,0) IsPercentage,
	--	Convert(Bit,0) IsSubjectPercentile,
	--	Convert(Bit,0) IsProcessResult,			 
	--	Convert(Bit,0) IsNegativeMarks,
	--	Convert(Bit,0) IsIncludeCoScholastic,
	--	Convert(Bit,0) IsOnPrePrinted,
	--	Convert(Bit,0) IsDisplayPhoto,
	--	Convert(Bit,0) IsDisplayBirthDate,
	--	Convert(Bit,0) IsLockForEdit,
	--	Convert(Bit,0) IsDisplaySchoolName,			
	--	Convert(Bit,0) IsDisplayAttendance,
	--	Convert(Bit,0) IsDisplayHeightWeight,
	--	Convert(Bit,0) IsResultStatus,
	--  '' AS IsDisplayMonthlyAttendanceText,
	--  Convert(Bit,0) IsDisplayMonthlyAttendance,
	--	'' AS FooterAdjustmentText,
	--	'' AS DetailAdjustmentText,
	--	0 AS FooterAdjustment,
	--	0 AS DetailAdjustment,		 		 		 
	--	Convert(Bit,0) IsPresent,			
	--	'' SmallAddress1,
	--	Convert(Bit,0) IsDisplayParentName,				
	--	Convert(Bit,0) AS IsShowSubjectMark,			
	--	Convert(Bit,0) IsDisplayTeacherSign,
	--	Convert(Bit,0) IsDisplayPrincipalSign,		 			 
	--	Convert(Bit,0) AS IsImageHeader,			 
	--	'' AS DecimalFormat,	 			 
	--	'' AS FatherName,
	--	'' AS MotherName,
	--  0 AS SubjectCount
	

CREATE TABLE #TempExam
(
    Id int IDENTITY(1,1) PRIMARY KEY,
    ExamId int,
    Exam nvarchar(100)
)

INSERT INTO #TempExam
(
	 ExamId,
	 Exam 	
)

SELECT 
@rExamId AS ExamId,
ESGM.Title AS Exam
FROM [sAssessment].[tExamMaster] EM 
INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.ID = EM.ExamSubGroupId 
WHERE EM.ClassId=@rClassId AND EM.BatchId =@rBatchId AND EM.Id = @rExamId

UNION ALL

SELECT 
EM.Id AS ExamId,
ESGM.Code AS Exam
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 =@rExamId  AND (EM.ClassId=@rClassId) AND EM.BatchId =@rBatchId

UNION ALL 

SELECT
EM.Id AS ExamId,
ESGM.Title AS Exam
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)  AND (EM.ClassId=@rClassId) AND EM.BatchId =@rBatchId

DECLARE @lSubjectCount int 
SELECT @lSubjectCount = MAX(SubCount)
FROM (
    SELECT COUNT(ED.Id) AS SubCount
    FROM sAssessment.tExamDetail ED
    INNER JOIN #TempExam TE ON TE.ExamId = ED.ExamId
    GROUP BY TE.ExamId
) AS Subquery;

--select * from #TempExam
	
	SELECT 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			Convert(nvarchar(20),A.Id) AS AcademicIdText,
			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,
			EC.ExamId,
			EC.Exam AS ExamName,
			ED.ExamDate,
			R.TotalMarks AS TotalMark,
			R.TotalObtain,
			R.RankNumber,
			R.Percentage,
			R.ResultGrade,
			R.Percentile,			
			RD.Id AS ResultDetailId,		
			ED.IsDisplayInMarksheet,
			ED.IsShowSubjectGrade,
			ED.IsIncludeInTotal,
			RD.Obtain AS SubjectObtain,
			RD.SubjectGrade,
			ED.Minimum AS SubjectMinimum,
			ED.Maximum AS SubjectMaximum,			
			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.IsNegativeMarks,
			EM.IsIncludeCoScholastic,
			EM.IsOnPrePrinted,
			EM.IsDisplayPhoto,
			EM.IsDisplayBirthDate,
			EM.IsLockForEdit,
			EM.IsDisplaySchoolName,			
			EM.IsDisplayAttendance,
			EM.IsDisplayHeightWeight,
			EM.IsResultStatus,
			Convert(nvarchar(20),ISNULL(EM.IsDisplayMonthlyAttendance,0)) AS IsDisplayMonthlyAttendanceText,
			ISNULL(EM.IsDisplayMonthlyAttendance,0) AS IsDisplayMonthlyAttendance,
			REPLICATE(',',EM.FooterAdjustment) AS FooterAdjustmentText,
			REPLICATE(',',EM.DetailAdjustment) AS DetailAdjustmentText,
			EM.FooterAdjustment,
			EM.DetailAdjustment,		 		 		 
			RD.IsPresent,	
			OM.SmallAddress1,
			EM.IsDisplayParentName,			 
			ISNULL(ED.IsShowSubjectMark,1) AS IsShowSubjectMark,			
			EM.IsDisplayTeacherSign,
			Em.IsDisplayPrincipalSign,		 		 
			ISNULL(EM.IsDisplayImageHeader,0) AS IsImageHeader,			 
			EM.DecimalFormat,						 
			SF.FatherName,
			SF.MotherName,
			@lSubjectCount AS SubjectCount
						
	FROM 
			sAssessment.tResultDetail RD
			INNER JOIN sAssessment.tResult R ON R.Id = RD.ResultId
			INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId
			INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId		
			INNER JOIN #TempExam EC ON EC.ExamId = EM.Id 	
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=CS.SubjectId					 
			INNER JOIN sStudent.tAcademic A ON A.Id=R.AcademicId	
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId		
			INNER JOIN sStudent.tStudentMaster StuM ON StuM.Id=A.StudentId			
			INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId
			INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId			
			INNER JOIN sSetup.tOrganizationMaster OM ON StuM.OrgId = OM.Id			
			LEFT JOIN sAssessment.tStudentRemark SR ON R.AcademicId = SR.AcademicId AND  SR.ExamId=EC.ExamId
			LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId = StuM.Id
			
	WHERE 
			
		((EM.BatchId = @rBatchId) OR  (@rBatchId = 0))
		AND ((A.ClassId=@rClassId) OR (@rClassId=0)) 
		AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		AND ((A.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
		AND ((A.RollNo <= @rToRollNo) OR (@rToRollNo=0))
		AND ((StuM.Code=@rCode) OR (@rCode=''))
		AND ((StuM.StatusId=@rStatusId)OR(@rStatusId=0))
		AND ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0))

	ORDER BY A.RollNo , EC.Id
		
	 DROP TABLE #TempExam
	 
END
GO
PRINT N'Creating Procedure [sSecurity].[pVerifyMobileNumberForEmployeeOTP]...';


GO
CREATE PROCEDURE sSecurity.pVerifyMobileNumberForEmployeeOTP

	@rOrgId int = 0,
	@rMobileNumber nvarchar(50), 
	@rEmployeeId bigint

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	DECLARE @lCount int = 0
	DECLARE @lUserId bigint = 0,@lId Bigint = 0
	DECLARE @newpwd VARCHAR(100) 

	SELECT @lCount = COUNT(EC.EmployeeId), @lId = EC.EmployeeId
	FROM sHrm.tEmployeeCommunications EC 
	INNER JOIN sHrm.tEmployeeMaster EM ON EC.EmployeeId = EM.Id 
	INNER JOIN sSecurity.tUser U ON U.SourceId = EC.EmployeeId AND U.SourceTypeId=95
	WHERE EC.MobileNumber = @rMobileNumber AND EM.OrgId=@rOrgId  AND EC.EmployeeId = @rEmployeeId
	GROUP BY EC.EmployeeId
	
	--print @lId
	IF(@lCount > 0)
	BEGIN
	
		EXEC [sSecurity].[pNumericOTPGenerate] @len=6, @min=48, @range=9, @exclude='', @output=@newpwd OUT
		UPDATE sSecurity.tUser 
		SET	TempPasswordCode=@newpwd,CreatedDateTime=sCommon.fGetDate(),OTPExpiryDate=DATEADD(SECOND,120,GETDATE())				
		WHERE SourceId = @lId AND OrgId = @rOrgId AND SourceTypeId = 95
		
		SELECT 1 AS Result,'' AS [Message], TempPasswordCode AS OTP,Id AS UserId FROM sSecurity.tUser 
		WHERE SourceId = @lId AND OrgId = @rOrgId AND SourceTypeId = 95

	END

	ELSE
	BEGIN 
		SELECT -102 AS Result,'Mobile number is wrong' AS [Message],'' AS OTP
	END
END
GO
PRINT N'Creating Procedure [sStudent].[pRptStudentPastLCVerificationGet]...';


GO


CREATE PROCEDURE [sStudent].[pRptStudentPastLCVerificationGet]
	 
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 @rDepartmentId int=0,
	 @rClassId int=0,
	 @rDivisionId int=0,
     @rStrCode nvarchar(20)='',
	 @rStatusId int=0,
	 @rClassStatusId int=0,
	 @rPreviousSchool nvarchar(200)=''

	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
 BEGIN

	     SELECT
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,	
			OM.OrgLogo,
			OM.Title AS OrgTitle,
			OM.StreetOne+' '+OM.StreetTwo+' '+OM.StreetThree AS OrgAddress,
			OM.SmallAddress1,
			OM.SmallAddress2,
			OM.RegistrationDetail,
            vSA.ClassId AS ClassId,
			CM.OrderIndex AS ClassOrderIndex,
			vSA.ClassId AS DivisionId,	
			DM.OrderIndex AS DivisionOrderIndex,		
			vSA.ClassName AS ClassName,
			vSA.DivisionName AS DivisionName,
			ISNULL(OM.ReportOrgGroupTitle,'') AS ReportOrgGroupTitle,
			OM.ReportOrgTitle,		
			vSA.AcademicId,
			vSA.Code,
			ISNULL(SA.AdmissionNumber,'') As OldGRNo,
            vSA.FirstName,vSA.MiddleName,vSA.LastName,
			[sStudent].[fStudentNameGet](vSA.FirstName , vSA.MiddleName, vSA.LastName,OM.StudentNameFormatId ) AS Name,
			ISNULL(SO.DateOfBirth,'') AS DateOfBirth,
			ISNULL(SO.BirthDateInWord,'') AS BirthDateInWord,
			ISNULL(SA.PreviousStandard,'') AS PreviousStandard,
			ISNULL(SA.LeftDate,'') AS LeftDate,
			ISNULL(SO.BirthPlace,'') AS BirthPlace,
			ISNULL(SA.PreviousLCNumber,'') AS PreviousLCNumber,
			ISNULL(SA.PreviousLCDate,'') AS PreviousLCDate,
			ISNULL(SA.PreviousLCResult,'') AS PreviousLCResult,
			ISNULL(SO.FamilySubCast,'') AS SubCaste,
			ISNULL(SO.FamilyCast,'') AS Caste,
			isnull(MainCastCategoryId,0) AS CastCategoryId,
			ISNULL(SA.AdmissionNumber,'') AS AdmissionNumber
			 
			--SA.PreviousSchool

	FROM 
		    sStudent.vStudentAcademic vSA 	
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=vSA.OrgId 
			LEFT JOIN sStudent.tStudentAdmission SA ON SA.StudentId=vSA.StudentId
			INNER JOIN sSetup.tClassMaster CM ON CM.Id=SA.AdmissionStandardId
			INNER JOIN sSetup.tDivisionMaster DM ON vSA.DivisionId = DM.Id  
		    LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId=vSA.StudentId 
			LEFT JOIN sCommon.tCastCategoryMaster CSM ON CSM.Id=SO.CastCategoryId		
	Where		
	           ((vSA.DepartmentId=@rDepartmentId) OR(@rDepartmentId=0))
	       AND ((vSA.ClassId=@rClassId) OR(@rClassId=0))	  
	       AND ((vSA.DivisionId=@rDivisionId) OR (@rDivisionId=0))	
		   AND (ISNULL(vSA.Code,0) IN( SELECT cast(item as nvarchar(20)) FROM  sCommon.fnsplit(@rStrCode,',')) OR @rStrCode='')
           AND ((vSA.StatusId=@rStatusId)OR(@rStatusId=0))
		   AND ((vSA.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0)) 
		   --AND (ISNULL(SA.PreviousSchool,'') IN( SELECT item FROM  sCommon.fnsplit(@rPreviousSchool,','))OR @rPreviousSchool='')	
		    AND ((SA.PreviousSchool =  @rPreviousSchool) OR (@rPreviousSchool='')) 
END
GO


PRINT N'Update complete.';


GO



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



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


Drop FUNCTION [sFee].[fPendingFeeNamesGet]
GO
Drop TYPE [dbo].[TempPendingFee]
GO
CREATE TYPE [dbo].[TempPendingFee] AS TABLE (
    [AcademicId]         BIGINT          NULL,
    [RollNo]             INT             NULL,
    [Name]               NVARCHAR (200)  NULL,
    [Code]               NVARCHAR (20)   NULL,
    [ClassId]            INT             NULL,
    [DivisionId]         INT             NULL,
    [ClassName]          NVARCHAR (100)  NULL,
    [DivisionName]       NVARCHAR (100)  NULL,
    [ClassDivision]      NVARCHAR (200)  NULL,
    [FeeSetupId]         INT             NULL,
    [IsVariable]         INT             NULL,
    [Amount]             DECIMAL (12, 2) NULL,
    [StartDate]          DATE            NULL,
    [EndDate]            DATE            NULL,
    [FAAmount]           DECIMAL (12, 2) NULL,
    [DiscountAmount]     DECIMAL (12, 2) NULL,
    [AdditionalAmount]   DECIMAL (12, 2) NULL,
    [PaidAmount]         DECIMAL (12, 2) NULL,
    [PendingAmount]      DECIMAL (12, 2) NULL,
    [Remark]             NVARCHAR (200)  NULL,
    [ReceiptBookId]      INT             NULL,
    [FeeName]            NVARCHAR (100)  NULL,
    [FeeCode]            NVARCHAR (100)  NULL,
    [OrgId]              INT             NULL,
    [OrgName]            NVARCHAR (200)  NULL,
    [OrgOrderIndex]      INT             NULL,
    [ReceiptBookTitle]   NVARCHAR (200)  NULL,
    [ReceiptOrderIndex]  INT             NULL,
    [BatchId]            INT             NULL,
    [BatchName]          NVARCHAR (100)  NULL,
    [Pickup]             NVARCHAR (100)  NULL,
    [DRoppoint]          NVARCHAR (100)  NULL,
    [PresentContactNo]   NVARCHAR (20)   NULL,
    [SUID]               NVARCHAR (50)   NULL,
    [ClassOrderIndex]    INT             NULL,
    [DivisionOrderIndex] INT             NULL,
    [FeeOrderIndex]      INT             NULL,
    [FatherContactNo]    NVARCHAR (50)   NULL,
    [MotherContactNo]    NVARCHAR (50)   NULL);


GO
PRINT N'Altering Table [sAcademic].[tClasswork]...';


GO
ALTER TABLE [sAcademic].[tClasswork] ALTER COLUMN [Homework] NVARCHAR (MAX) NULL;


GO
PRINT N'Altering Table [sAcademic].[tTopicMaster]...';


GO
ALTER TABLE [sAcademic].[tTopicMaster]
    ADD [IsObsolete] BIT NULL;


GO
PRINT N'Starting rebuilding table [sBiometric].[tCloudTransactionData]...';


GO
BEGIN TRANSACTION;

SET TRANSACTION ISOLATION LEVEL SERIALIZABLE;

SET XACT_ABORT ON;

CREATE TABLE [sBiometric].[tmp_ms_xx_tCloudTransactionData] (
    [AutoId]          BIGINT        IDENTITY (1, 1) NOT NULL,
    [SourceId]        BIGINT        NOT NULL,
    [In_Out_Time]     DATETIME      NOT NULL,
    [ShiftCode]       INT           NOT NULL,
    [Attn_Dt]         DATE          NOT NULL,
    [Mode]            NVARCHAR (10) NOT NULL,
    [CreatedDateTime] DATETIME      NOT NULL,
    [DeviceIP]        NVARCHAR (20) NOT NULL,
    [EntryMode]       TINYINT       NOT NULL,
    [PunchId]         NVARCHAR (50) NULL,
    [TransactionId]   BIGINT        NOT NULL,
    [SourceTypeId]    SMALLINT      NULL,
    [IsProcessed]     BIT           NULL
);

IF EXISTS (SELECT TOP 1 1 
           FROM   [sBiometric].[tCloudTransactionData])
    BEGIN
        INSERT INTO [sBiometric].[tmp_ms_xx_tCloudTransactionData] ([SourceId], [In_Out_Time], [ShiftCode], [Attn_Dt], [Mode], [CreatedDateTime], [DeviceIP], [EntryMode], [PunchId], [TransactionId], [SourceTypeId], [IsProcessed])
        SELECT [SourceId],
               [In_Out_Time],
               [ShiftCode],
               [Attn_Dt],
               [Mode],
               [CreatedDateTime],
               [DeviceIP],
               [EntryMode],
               [PunchId],
               [TransactionId],
               [SourceTypeId],
               [IsProcessed]
        FROM   [sBiometric].[tCloudTransactionData];
    END

DROP TABLE [sBiometric].[tCloudTransactionData];

EXECUTE sp_rename N'[sBiometric].[tmp_ms_xx_tCloudTransactionData]', N'tCloudTransactionData';

COMMIT TRANSACTION;

SET TRANSACTION ISOLATION LEVEL READ COMMITTED;


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


GO
ALTER TABLE [sCommunication].[tRegisteredUsers]
    ADD [DeviceDetail] NVARCHAR (MAX) NULL;


GO
PRINT N'Creating Table [sActivity].[tEmployeeHealthTrack]...';


GO
CREATE TABLE [sActivity].[tEmployeeHealthTrack] (
    [Id]                  BIGINT         NOT NULL,
    [EmployeeId]          BIGINT         NOT NULL,
    [HealthCheckupTypeId] TINYINT        NOT NULL,
    [CheckupFromDate]     DATE           NOT NULL,
    [CheckupToDate]       DATE           NOT NULL,
    [ChiefComplain]       NVARCHAR (100) NOT NULL,
    [Diagnosis]           NVARCHAR (100) NOT NULL,
    [ActionTaken]         NVARCHAR (100) NOT NULL,
    [Remark]              NVARCHAR (200) NULL,
    [ExaminedBy]          NVARCHAR (100) NULL,
    [CreatedUserId]       BIGINT         NOT NULL,
    [CreatedDateTime]     DATETIME       NOT NULL,
    [UpdatedUserId]       BIGINT         NULL,
    [UpdatedDateTime]     DATETIME       NULL,
    [InTime]              TIME (7)       NULL,
    [OutTime]             TIME (7)       NULL,
    CONSTRAINT [PK_tEmployeeHealthTrack] PRIMARY KEY CLUSTERED ([Id] ASC)
);


GO
PRINT N'Creating Table [sActivity].[tHealthCheckupEmployee]...';


GO
CREATE TABLE [sActivity].[tHealthCheckupEmployee] (
    [HealthCheckupId]  INT            NOT NULL,
    [EmployeeId]       BIGINT         NOT NULL,
    [HeightInCm]       DECIMAL (6, 2) NULL,
    [WeightInKg]       DECIMAL (6, 2) NULL,
    [Dental]           NVARCHAR (150) NULL,
    [Nails]            NVARCHAR (150) NULL,
    [Hair]             NVARCHAR (150) NULL,
    [Skin]             NVARCHAR (150) NULL,
    [Ear]              NVARCHAR (150) NULL,
    [Nose]             NVARCHAR (150) NULL,
    [Throat]           NVARCHAR (150) NULL,
    [Respiratory]      NVARCHAR (150) NULL,
    [Cardiovascular]   NVARCHAR (150) NULL,
    [Nervous]          NVARCHAR (150) NULL,
    [Eye]              NVARCHAR (150) NULL,
    [Other]            NVARCHAR (150) NULL,
    [ImportantFinding] NVARCHAR (150) NULL,
    [Remarks]          NVARCHAR (150) NULL,
    [FollowupDetail]   NVARCHAR (150) NULL,
    [StatusId]         SMALLINT       NOT NULL,
    [BloodGroupId]     TINYINT        NULL
);


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


GO
CREATE TABLE [sAssessment].[tTempAllExamWithAllTerm] (
    [AcademicIdText]                 NVARCHAR (20)   NULL,
    [ExamIdText]                     NVARCHAR (20)   NULL,
    [CoScholasticScopeIdText]        NVARCHAR (20)   NULL,
    [IsDisplayMonthlyAttendanceText] NVARCHAR (20)   NULL,
    [ClassIdText]                    NVARCHAR (50)   NULL,
    [AcademicId]                     BIGINT          NULL,
    [ExamName]                       NVARCHAR (150)  NULL,
    [StudCode]                       NVARCHAR (20)   NULL,
    [StudentName]                    NVARCHAR (150)  NULL,
    [RollNo]                         INT             NULL,
    [ResultStatus]                   NVARCHAR (20)   NULL,
    [ClassName]                      NVARCHAR (50)   NULL,
    [Division]                       NVARCHAR (50)   NULL,
    [TotalMark]                      DECIMAL (8, 2)  NULL,
    [TotalObtain]                    DECIMAL (8, 2)  NULL,
    [Percentage]                     DECIMAL (8, 2)  NULL,
    [RankNumber]                     INT             NULL,
    [ResultGrade]                    NVARCHAR (50)   NULL,
    [MaximumMark1]                   DECIMAL (8, 2)  NULL,
    [SubjectGrade1]                  NVARCHAR (50)   NULL,
    [Obtain1]                        DECIMAL (8, 2)  NULL,
    [ExamMaximum1]                   DECIMAL (8, 2)  NULL,
    [IsPresent1]                     BIT             NULL,
    [MaximumMark2]                   DECIMAL (8, 2)  NULL,
    [SubjectGrade2]                  NVARCHAR (50)   NULL,
    [Obtain2]                        DECIMAL (8, 2)  NULL,
    [ExamMaximum2]                   DECIMAL (8, 2)  NULL,
    [IsPresent2]                     BIT             NULL,
    [MaximumMark3]                   DECIMAL (8, 2)  NULL,
    [SubjectGrade3]                  NVARCHAR (50)   NULL,
    [Obtain3]                        DECIMAL (8, 2)  NULL,
    [ExamMaximum3]                   DECIMAL (8, 2)  NULL,
    [IsPresent3]                     BIT             NULL,
    [MaximumMark4]                   DECIMAL (8, 2)  NULL,
    [SubjectGrade4]                  NVARCHAR (50)   NULL,
    [Obtain4]                        DECIMAL (8, 2)  NULL,
    [ExamMaximum4]                   DECIMAL (8, 2)  NULL,
    [IsPresent4]                     BIT             NULL,
    [MaximumMark5]                   DECIMAL (8, 2)  NULL,
    [SubjectGrade5]                  NVARCHAR (50)   NULL,
    [Obtain5]                        DECIMAL (8, 2)  NULL,
    [ExamMaximum5]                   DECIMAL (8, 2)  NULL,
    [IsPresent5]                     BIT             NULL,
    [MaximumMark6]                   DECIMAL (8, 2)  NULL,
    [SubjectGrade6]                  NVARCHAR (50)   NULL,
    [Obtain6]                        DECIMAL (8, 2)  NULL,
    [ExamMaximum6]                   DECIMAL (8, 2)  NULL,
    [IsPresent6]                     BIT             NULL,
    [MaximumMark7]                   DECIMAL (8, 2)  NULL,
    [SubjectGrade7]                  NVARCHAR (50)   NULL,
    [Obtain7]                        DECIMAL (8, 2)  NULL,
    [ExamMaximum7]                   DECIMAL (8, 2)  NULL,
    [IsPresent7]                     BIT             NULL,
    [MaximumMark8]                   DECIMAL (8, 2)  NULL,
    [SubjectGrade8]                  NVARCHAR (50)   NULL,
    [Obtain8]                        DECIMAL (8, 2)  NULL,
    [ExamMaximum8]                   DECIMAL (8, 2)  NULL,
    [IsPresent8]                     BIT             NULL,
    [MaximumMark9]                   DECIMAL (8, 2)  NULL,
    [SubjectGrade9]                  NVARCHAR (50)   NULL,
    [Obtain9]                        DECIMAL (8, 2)  NULL,
    [ExamMaximum9]                   DECIMAL (8, 2)  NULL,
    [IsPresent9]                     BIT             NULL,
    [MaximumMark10]                  DECIMAL (8, 2)  NULL,
    [SubjectGrade10]                 NVARCHAR (50)   NULL,
    [Obtain10]                       DECIMAL (8, 2)  NULL,
    [ExamMaximum10]                  DECIMAL (8, 2)  NULL,
    [IsPresent10]                    BIT             NULL,
    [MaximumMark11]                  DECIMAL (8, 2)  NULL,
    [SubjectGrade11]                 NVARCHAR (50)   NULL,
    [Obtain11]                       DECIMAL (8, 2)  NULL,
    [ExamMaximum11]                  DECIMAL (8, 2)  NULL,
    [IsPresent11]                    BIT             NULL,
    [MaximumMark12]                  DECIMAL (8, 2)  NULL,
    [SubjectGrade12]                 NVARCHAR (50)   NULL,
    [Obtain12]                       DECIMAL (8, 2)  NULL,
    [ExamMaximum12]                  DECIMAL (8, 2)  NULL,
    [IsPresent12]                    BIT             NULL,
    [MaximumMark13]                  DECIMAL (8, 2)  NULL,
    [SubjectGrade13]                 NVARCHAR (50)   NULL,
    [Obtain13]                       DECIMAL (8, 2)  NULL,
    [ExamMaximum13]                  DECIMAL (8, 2)  NULL,
    [IsPresent13]                    BIT             NULL,
    [SubjectGradeTerm1]              NVARCHAR (50)   NULL,
    [SubjectGradeTerm2]              NVARCHAR (50)   NULL,
    [SubjectGradeTerm3]              NVARCHAR (50)   NULL,
    [SubjectGradeTerm4]              NVARCHAR (50)   NULL,
    [IsMarksInDecimal]               BIT             NULL,
    [column_visible]                 BIT             NULL,
    [Percentile]                     DECIMAL (5, 2)  NULL,
    [ResultDetailId]                 BIGINT          NULL,
    [ResultId]                       BIGINT          NULL,
    [Remark1]                        NVARCHAR (1000) NULL,
    [Remark2]                        NVARCHAR (1000) NULL,
    [Remark3]                        NVARCHAR (1000) NULL,
    [DisplayTitle]                   NVARCHAR (150)  NULL,
    [IsRankNo]                       BIT             NULL,
    [IsGrade]                        BIT             NULL,
    [IsPercentile]                   BIT             NULL,
    [IsPercentage]                   BIT             NULL,
    [IsSubjectPercentile]            BIT             NULL,
    [IsProcessResult]                BIT             NULL,
    [IsNegativeMarks]                BIT             NULL,
    [IsIncludeCoScholastic]          BIT             NULL,
    [IsOnPrePrinted]                 BIT             NULL,
    [IsDisplayPhoto]                 BIT             NULL,
    [IsDisplayBirthDate]             BIT             NULL,
    [IsLockForEdit]                  BIT             NULL,
    [IsDisplaySchoolName]            BIT             NULL,
    [IsDisplayAttendance]            BIT             NULL,
    [IsDisplayHeightWeight]          BIT             NULL,
    [IsResultStatus]                 BIT             NULL,
    [FooterAdjustmentText]           NVARCHAR (MAX)  NULL,
    [DetailAdjustmentText]           NVARCHAR (MAX)  NULL,
    [FooterAdjustment]               SMALLINT        NULL,
    [DetailAdjustment]               SMALLINT        NULL,
    [ResultRemark]                   NVARCHAR (200)  NULL,
    [DateOfBirth]                    DATE            NULL,
    [HeightTerm1]                    DECIMAL (5, 2)  NULL,
    [WeightTerm1]                    DECIMAL (5, 2)  NULL,
    [HeightTerm2]                    DECIMAL (5, 2)  NULL,
    [WeightTerm2]                    DECIMAL (5, 2)  NULL,
    [HeightAnnual]                   DECIMAL (5, 2)  NULL,
    [WeightAnnual]                   DECIMAL (5, 2)  NULL,
    [PresentDaysTerm1]               SMALLINT        NULL,
    [PresentDaysTerm2]               SMALLINT        NULL,
    [PresentDaysAnnual]              SMALLINT        NULL,
    [TotalDaysTerm1]                 SMALLINT        NULL,
    [TotalDaysTerm2]                 SMALLINT        NULL,
    [TotalDaysAnnual]                SMALLINT        NULL,
    [TotalMarkTerm1]                 DECIMAL (8, 2)  NULL,
    [TotalObtainTerm1]               DECIMAL (8, 2)  NULL,
    [PercentageTerm1]                DECIMAL (8, 2)  NULL,
    [RankNumberTerm1]                INT             NULL,
    [ResultGradeTerm1]               NVARCHAR (50)   NULL,
    [PercentileTerm1]                DECIMAL (8, 2)  NULL,
    [ResultStatusTerm1]              NVARCHAR (20)   NULL,
    [TotalMarkTerm2]                 DECIMAL (8, 2)  NULL,
    [TotalObtainTerm2]               DECIMAL (8, 2)  NULL,
    [PercentageTerm2]                DECIMAL (8, 2)  NULL,
    [RankNumberTerm2]                INT             NULL,
    [ResultGradeTerm2]               NVARCHAR (50)   NULL,
    [PercentileTerm2]                DECIMAL (8, 2)  NULL,
    [ResultStatusTerm2]              NVARCHAR (20)   NULL,
    [TotalMarkTerm3]                 DECIMAL (8, 2)  NULL,
    [TotalObtainTerm3]               DECIMAL (8, 2)  NULL,
    [PercentageTerm3]                DECIMAL (8, 2)  NULL,
    [RankNumberTerm3]                INT             NULL,
    [ResultGradeTerm3]               NVARCHAR (50)   NULL,
    [PercentileTerm3]                DECIMAL (8, 2)  NULL,
    [ResultStatusTerm3]              NVARCHAR (20)   NULL,
    [TotalMarkTerm4]                 DECIMAL (8, 2)  NULL,
    [TotalObtainTerm4]               DECIMAL (8, 2)  NULL,
    [PercentageTerm4]                DECIMAL (8, 2)  NULL,
    [RankNumberTerm4]                INT             NULL,
    [ResultGradeTerm4]               NVARCHAR (50)   NULL,
    [PercentileTerm4]                DECIMAL (8, 2)  NULL,
    [ResultStatusTerm4]              NVARCHAR (20)   NULL,
    [TermScopeId]                    TINYINT         NULL,
    [StudentPhoto]                   VARBINARY (MAX) NULL,
    [GradeString]                    NVARCHAR (1000) NULL,
    [IsDisplayGradeString]           BIT             NULL,
    [IsDisplayInMarksheet]           BIT             NULL,
    [IsShowSubjectGrade]             BIT             NULL,
    [IsIncludeInTotal]               BIT             NULL,
    [ClassSubjectID]                 INT             NULL,
    [SubjectId]                      INT             NULL,
    [SubjectOrderIndex]              SMALLINT        NULL,
    [SubjectGrade]                   NVARCHAR (50)   NULL,
    [SubjectName]                    NVARCHAR (150)  NULL,
    [SubjectCode]                    NVARCHAR (50)   NULL,
    [SubjectMinimum]                 DECIMAL (8, 2)  NULL,
    [SubjectMaximum]                 DECIMAL (8, 2)  NULL,
    [SubjectObtain]                  DECIMAL (8, 2)  NULL,
    [Exam1Name]                      NVARCHAR (150)  NULL,
    [TotalMarks1]                    DECIMAL (8, 2)  NULL,
    [TotalObtain1]                   DECIMAL (8, 2)  NULL,
    [Percentage1]                    DECIMAL (8, 2)  NULL,
    [RankNumber1]                    INT             NULL,
    [ResultGrade1]                   NVARCHAR (50)   NULL,
    [Percentile1]                    DECIMAL (8, 2)  NULL,
    [ResultStatus1]                  NVARCHAR (20)   NULL,
    [Exam1CombineExamName]           NVARCHAR (150)  NULL,
    [Exam2Name]                      NVARCHAR (150)  NULL,
    [TotalMarks2]                    DECIMAL (8, 2)  NULL,
    [TotalObtain2]                   DECIMAL (8, 2)  NULL,
    [Percentage2]                    DECIMAL (8, 2)  NULL,
    [RankNumber2]                    INT             NULL,
    [ResultGrade2]                   NVARCHAR (50)   NULL,
    [Percentile2]                    DECIMAL (8, 2)  NULL,
    [ResultStatus2]                  NVARCHAR (20)   NULL,
    [Exam2CombineExamName]           NVARCHAR (150)  NULL,
    [Exam3Name]                      NVARCHAR (150)  NULL,
    [TotalMarks3]                    DECIMAL (8, 2)  NULL,
    [TotalObtain3]                   DECIMAL (8, 2)  NULL,
    [Percentage3]                    DECIMAL (8, 2)  NULL,
    [RankNumber3]                    INT             NULL,
    [ResultGrade3]                   NVARCHAR (50)   NULL,
    [Percentile3]                    DECIMAL (8, 2)  NULL,
    [ResultStatus3]                  NVARCHAR (20)   NULL,
    [Exam3CombineExamName]           NVARCHAR (150)  NULL,
    [Exam4Name]                      NVARCHAR (150)  NULL,
    [TotalMarks4]                    DECIMAL (8, 2)  NULL,
    [TotalObtain4]                   DECIMAL (8, 2)  NULL,
    [Percentage4]                    DECIMAL (8, 2)  NULL,
    [RankNumber4]                    INT             NULL,
    [ResultGrade4]                   NVARCHAR (50)   NULL,
    [Percentile4]                    DECIMAL (8, 2)  NULL,
    [ResultStatus4]                  NVARCHAR (20)   NULL,
    [Exam4CombineExamName]           NVARCHAR (150)  NULL,
    [Exam5Name]                      NVARCHAR (150)  NULL,
    [TotalMarks5]                    DECIMAL (8, 2)  NULL,
    [TotalObtain5]                   DECIMAL (8, 2)  NULL,
    [Percentage5]                    DECIMAL (8, 2)  NULL,
    [RankNumber5]                    INT             NULL,
    [ResultGrade5]                   NVARCHAR (50)   NULL,
    [Percentile5]                    DECIMAL (8, 2)  NULL,
    [ResultStatus5]                  NVARCHAR (20)   NULL,
    [Exam5CombineExamName]           NVARCHAR (150)  NULL,
    [Exam6Name]                      NVARCHAR (150)  NULL,
    [TotalMarks6]                    DECIMAL (8, 2)  NULL,
    [TotalObtain6]                   DECIMAL (8, 2)  NULL,
    [Percentage6]                    DECIMAL (8, 2)  NULL,
    [RankNumber6]                    INT             NULL,
    [ResultGrade6]                   NVARCHAR (50)   NULL,
    [Percentile6]                    DECIMAL (8, 2)  NULL,
    [ResultStatus6]                  NVARCHAR (20)   NULL,
    [Exam6CombineExamName]           NVARCHAR (150)  NULL,
    [Exam7Name]                      NVARCHAR (150)  NULL,
    [TotalMarks7]                    DECIMAL (8, 2)  NULL,
    [TotalObtain7]                   DECIMAL (8, 2)  NULL,
    [Percentage7]                    DECIMAL (8, 2)  NULL,
    [RankNumber7]                    INT             NULL,
    [ResultGrade7]                   NVARCHAR (50)   NULL,
    [Percentile7]                    DECIMAL (8, 2)  NULL,
    [ResultStatus7]                  NVARCHAR (20)   NULL,
    [Exam7CombineExamName]           NVARCHAR (150)  NULL,
    [Exam8Name]                      NVARCHAR (150)  NULL,
    [TotalMarks8]                    DECIMAL (8, 2)  NULL,
    [TotalObtain8]                   DECIMAL (8, 2)  NULL,
    [Percentage8]                    DECIMAL (8, 2)  NULL,
    [RankNumber8]                    INT             NULL,
    [ResultGrade8]                   NVARCHAR (50)   NULL,
    [Percentile8]                    DECIMAL (8, 2)  NULL,
    [ResultStatus8]                  NVARCHAR (20)   NULL,
    [Exam8CombineExamName]           NVARCHAR (150)  NULL,
    [Exam9Name]                      NVARCHAR (150)  NULL,
    [TotalMarks9]                    DECIMAL (8, 2)  NULL,
    [TotalObtain9]                   DECIMAL (8, 2)  NULL,
    [Percentage9]                    DECIMAL (8, 2)  NULL,
    [RankNumber9]                    INT             NULL,
    [ResultGrade9]                   NVARCHAR (50)   NULL,
    [Percentile9]                    DECIMAL (8, 2)  NULL,
    [ResultStatus9]                  NVARCHAR (20)   NULL,
    [Exam9CombineExamName]           NVARCHAR (150)  NULL,
    [Exam10Name]                     NVARCHAR (150)  NULL,
    [TotalMarks10]                   DECIMAL (8, 2)  NULL,
    [TotalObtain10]                  DECIMAL (8, 2)  NULL,
    [Percentage10]                   DECIMAL (8, 2)  NULL,
    [RankNumber10]                   INT             NULL,
    [ResultGrade10]                  NVARCHAR (50)   NULL,
    [Percentile10]                   DECIMAL (8, 2)  NULL,
    [ResultStatus10]                 NVARCHAR (20)   NULL,
    [Exam10CombineExamName]          NVARCHAR (150)  NULL,
    [Exam11Name]                     NVARCHAR (150)  NULL,
    [TotalMarks11]                   DECIMAL (8, 2)  NULL,
    [TotalObtain11]                  DECIMAL (8, 2)  NULL,
    [Percentage11]                   DECIMAL (8, 2)  NULL,
    [RankNumber11]                   INT             NULL,
    [ResultGrade11]                  NVARCHAR (50)   NULL,
    [Percentile11]                   DECIMAL (8, 2)  NULL,
    [ResultStatus11]                 NVARCHAR (20)   NULL,
    [Exam11CombineExamName]          NVARCHAR (150)  NULL,
    [Exam12Name]                     NVARCHAR (150)  NULL,
    [TotalMarks12]                   DECIMAL (8, 2)  NULL,
    [TotalObtain12]                  DECIMAL (8, 2)  NULL,
    [Percentage12]                   DECIMAL (8, 2)  NULL,
    [RankNumber12]                   INT             NULL,
    [ResultGrade12]                  NVARCHAR (50)   NULL,
    [Percentile12]                   DECIMAL (8, 2)  NULL,
    [ResultStatus12]                 NVARCHAR (20)   NULL,
    [Exam12CombineExamName]          NVARCHAR (150)  NULL,
    [Exam13Name]                     NVARCHAR (150)  NULL,
    [TotalMarks13]                   DECIMAL (8, 2)  NULL,
    [TotalObtain13]                  DECIMAL (8, 2)  NULL,
    [Percentage13]                   DECIMAL (8, 2)  NULL,
    [RankNumber13]                   INT             NULL,
    [ResultGrade13]                  NVARCHAR (50)   NULL,
    [Percentile13]                   DECIMAL (8, 2)  NULL,
    [ResultStatus13]                 NVARCHAR (20)   NULL,
    [Exam13CombineExamName]          NVARCHAR (150)  NULL,
    [ResultRemark1]                  NVARCHAR (200)  NULL,
    [ResultRemark2]                  NVARCHAR (200)  NULL,
    [TotalDays]                      DECIMAL (6, 2)  NULL,
    [PresentDays]                    DECIMAL (6, 2)  NULL,
    [StudentHeight]                  DECIMAL (6, 2)  NULL,
    [StudentWeight]                  DECIMAL (6, 2)  NULL,
    [ExamSeatNo]                     NVARCHAR (20)   NULL,
    [ExamId]                         INT             NULL,
    [ExamCode]                       NVARCHAR (20)   NULL,
    [Exam1Code]                      NVARCHAR (20)   NULL,
    [Exam2Code]                      NVARCHAR (20)   NULL,
    [Exam3Code]                      NVARCHAR (20)   NULL,
    [Exam4Code]                      NVARCHAR (20)   NULL,
    [Exam5Code]                      NVARCHAR (20)   NULL,
    [Exam6Code]                      NVARCHAR (20)   NULL,
    [Exam7Code]                      NVARCHAR (20)   NULL,
    [Exam8Code]                      NVARCHAR (20)   NULL,
    [Exam9Code]                      NVARCHAR (20)   NULL,
    [Exam10Code]                     NVARCHAR (20)   NULL,
    [Exam11Code]                     NVARCHAR (20)   NULL,
    [Exam12Code]                     NVARCHAR (20)   NULL,
    [Exam13Code]                     NVARCHAR (20)   NULL,
    [IsDisplayParentName]            BIT             NULL,
    [FatherName]                     NVARCHAR (100)  NULL,
    [MotherName]                     NVARCHAR (100)  NULL,
    [IsShowSubjectMark]              BIT             NULL,
    [IsOptionalSubject]              BIT             NULL,
    [CoScholasticScopeId]            TINYINT         NULL,
    [IsDisplayPrincipalSign]         BIT             NULL,
    [IsDisplayTeacherSign]           BIT             NULL,
    [EmployeeSign]                   VARBINARY (MAX) NULL,
    [Batch]                          NVARCHAR (100)  NULL,
    [ExamNameTerm1]                  NVARCHAR (100)  NULL,
    [ExamNameTerm2]                  NVARCHAR (100)  NULL,
    [ExamNameTerm3]                  NVARCHAR (100)  NULL,
    [ExamNameTerm4]                  NVARCHAR (100)  NULL,
    [ClassTeacherName]               NVARCHAR (100)  NULL,
    [FirstName]                      NVARCHAR (50)   NULL,
    [LastName]                       NVARCHAR (50)   NULL,
    [IsDisplayMonthlyAttendance]     BIT             NULL,
    [MarksheetHeaderA4]              VARBINARY (MAX) NULL,
    [IsImageHeader]                  BIT             NULL,
    [MyGoal]                         NVARCHAR (200)  NULL,
    [AreaOfInterest]                 NVARCHAR (200)  NULL,
    [Responsibility]                 NVARCHAR (200)  NULL,
    [MyInterestHobby]                NVARCHAR (200)  NULL,
    [MyStrength]                     NVARCHAR (200)  NULL,
    [Achievements]                   NVARCHAR (1000) NULL,
    [DentalHygiene]                  NVARCHAR (200)  NULL,
    [VisionLeft]                     NVARCHAR (50)   NULL,
    [VisionRight]                    NVARCHAR (50)   NULL,
    [IsDetail]                       BIT             NULL,
    [SubjectGroupId]                 INT             NULL,
    [SubjectGroupTitle]              NVARCHAR (50)   NULL,
    [SubjectGroupCode]               NVARCHAR (50)   NULL,
    [DecimalFormat]                  NVARCHAR (10)   NULL,
    [SubjectRemark]                  NVARCHAR (1000) NULL,
    [GraceMark]                      DECIMAL (5, 2)  NULL,
    [KrupaMark]                      DECIMAL (5, 2)  NULL,
    [GradeStringHtml]                NVARCHAR (500)  NULL,
    [ResultRemark3]                  NVARCHAR (200)  NULL,
    [IsDisplayTotalMark]             BIT             NULL,
    [SubjectObtainTerm1]             DECIMAL (8, 2)  NULL,
    [SubjectObtainTerm2]             DECIMAL (8, 2)  NULL,
    [SubjectObtainTerm3]             DECIMAL (8, 2)  NULL,
    [SubjectObtainTerm4]             DECIMAL (8, 2)  NULL,
    [SubjectMaxTerm1]                DECIMAL (8, 2)  NULL,
    [SubjectMaxTerm2]                DECIMAL (8, 2)  NULL,
    [SubjectMaxTerm3]                DECIMAL (8, 2)  NULL,
    [SubjectMaxTerm4]                DECIMAL (8, 2)  NULL,
    [ContactNo]                      NVARCHAR (50)   NULL,
    [PresentAddress]                 NVARCHAR (MAX)  NULL,
    [TeacherSignCaption]             NVARCHAR (100)  NULL,
    [PrincipalSignCaption]           NVARCHAR (100)  NULL,
    [ParentSignCaption]              NVARCHAR (100)  NULL,
    [ImprovementArea]                NVARCHAR (200)  NULL,
    [ProgressArea]                   NVARCHAR (200)  NULL,
    [GeneralRemark]                  NVARCHAR (1000) NULL,
    [MyActivity]                     NVARCHAR (200)  NULL,
    [ClassTeacherRemark]             NVARCHAR (1000) NULL,
    [HouseRemark]                    NVARCHAR (1000) NULL,
    [BloodGroup]                     NVARCHAR (100)  NULL,
    [TotalDays1]                     DECIMAL (6, 2)  NULL,
    [PresentDays1]                   DECIMAL (6, 2)  NULL,
    [TotalDays2]                     DECIMAL (6, 2)  NULL,
    [PresentDays2]                   DECIMAL (6, 2)  NULL,
    [TotalDays3]                     DECIMAL (6, 2)  NULL,
    [PresentDays3]                   DECIMAL (6, 2)  NULL,
    [TotalDays4]                     DECIMAL (6, 2)  NULL,
    [PresentDays4]                   DECIMAL (6, 2)  NULL,
    [TotalDays5]                     DECIMAL (6, 2)  NULL,
    [PresentDays5]                   DECIMAL (6, 2)  NULL,
    [TotalDays6]                     DECIMAL (6, 2)  NULL,
    [PresentDays6]                   DECIMAL (6, 2)  NULL,
    [TotalDays7]                     DECIMAL (6, 2)  NULL,
    [PresentDays7]                   DECIMAL (6, 2)  NULL,
    [TotalDays8]                     DECIMAL (6, 2)  NULL,
    [PresentDays8]                   DECIMAL (6, 2)  NULL,
    [TotalDays9]                     DECIMAL (6, 2)  NULL,
    [PresentDays9]                   DECIMAL (6, 2)  NULL,
    [TotalDays10]                    DECIMAL (6, 2)  NULL,
    [PresentDays10]                  DECIMAL (6, 2)  NULL,
    [TotalDays11]                    DECIMAL (6, 2)  NULL,
    [PresentDays11]                  DECIMAL (6, 2)  NULL,
    [TotalDays12]                    DECIMAL (6, 2)  NULL,
    [PresentDays12]                  DECIMAL (6, 2)  NULL,
    [TotalDays13]                    DECIMAL (6, 2)  NULL,
    [PresentDays13]                  DECIMAL (6, 2)  NULL,
    [BatchIdText]                    NVARCHAR (20)   NULL,
    [IsShowWithDetail]               BIT             NULL,
    [IsPresent]                      BIT             NULL,
    [GradeTitle]                     NVARCHAR (50)   NULL,
    [SubjectHighestDivisionGrade]    NVARCHAR (50)   NULL,
    [SubjectHighestDivisionMark]     DECIMAL (5, 2)  NULL,
    [AchievementsTerm1]              NVARCHAR (1000) NULL,
    [AchievementsTerm2]              NVARCHAR (1000) NULL,
    [GeneralRemarkTerm1]             NVARCHAR (200)  NULL,
    [GeneralRemarkTerm2]             NVARCHAR (200)  NULL,
    [ResultRemark1Term1]             NVARCHAR (200)  NULL,
    [ResultRemark2Term1]             NVARCHAR (200)  NULL,
    [ResultRemark1Term2]             NVARCHAR (200)  NULL,
    [ResultRemark2Term2]             NVARCHAR (200)  NULL,
    [SR_HeightTerm1]                 DECIMAL (5, 2)  NULL,
    [SR_WeightTerm1]                 DECIMAL (5, 2)  NULL,
    [SR_HeightTerm2]                 DECIMAL (5, 2)  NULL,
    [SR_WeightTerm2]                 DECIMAL (5, 2)  NULL,
    [SR_PresentDaysTerm1]            DECIMAL (6, 2)  NULL,
    [SR_PresentDaysTerm2]            DECIMAL (6, 2)  NULL,
    [SR_TotalDaysTerm1]              DECIMAL (6, 2)  NULL,
    [SR_TotalDaysTerm2]              DECIMAL (6, 2)  NULL,
    [HouseId]                        INT             NULL,
    [HouseName]                      NVARCHAR (100)  NULL,
    [AdhaarNumber]                   NVARCHAR (100)  NULL,
    [UIdNumber]                      NVARCHAR (100)  NULL,
    [FatherContactNo]                NVARCHAR (50)   NULL,
    [MotherContactNo]                NVARCHAR (50)   NULL,
    [FatherMail]                     NVARCHAR (MAX)  NULL,
    [MotherMail]                     NVARCHAR (MAX)  NULL,
    [Gender]                         NVARCHAR (100)  NULL,
    [CoordinatorEmployeeSign]        VARBINARY (MAX) NULL,
    [StudentAddress]                 NVARCHAR (MAX)  NULL,
    [SUId]                           NVARCHAR (50)   NULL,
    [HighestDivisionMark]            DECIMAL (5, 2)  NULL,
    [HighestDivisionGrade]           NVARCHAR (50)   NULL,
    [StreamTitle]                    NVARCHAR (50)   NULL,
    [AdmissionNo]                    NVARCHAR (50)   NULL,
    [AdmissionDate]                  DATE            NULL,
    [MiddleName]                     NVARCHAR (50)   NULL,
    [FatherOccupation]               NVARCHAR (50)   NULL,
    [ResultSheetAdditionalTitle]     NVARCHAR (100)  NULL,
    [IsDecimal]                      BIT             NULL,
    [IsAbsentRemark]                 BIT             NULL,
    [FinalAbsentRemark]              NVARCHAR (100)  NULL,
    [AbsentRemark1]                  NVARCHAR (100)  NULL,
    [AbsentRemark2]                  NVARCHAR (100)  NULL,
    [AbsentRemark3]                  NVARCHAR (100)  NULL,
    [AbsentRemark4]                  NVARCHAR (100)  NULL,
    [AbsentRemark5]                  NVARCHAR (100)  NULL,
    [AbsentRemark6]                  NVARCHAR (100)  NULL,
    [AbsentRemark7]                  NVARCHAR (100)  NULL,
    [AbsentRemark8]                  NVARCHAR (100)  NULL,
    [AbsentRemark9]                  NVARCHAR (100)  NULL,
    [AbsentRemark10]                 NVARCHAR (100)  NULL,
    [AbsentRemark11]                 NVARCHAR (100)  NULL,
    [AbsentRemark12]                 NVARCHAR (100)  NULL,
    [AbsentRemark13]                 NVARCHAR (100)  NULL,
    [ExamMaximumTerm1]               DECIMAL (6, 2)  NULL,
    [ExamMaximumTerm2]               DECIMAL (6, 2)  NULL,
    [ExamMaximumTerm3]               DECIMAL (6, 2)  NULL,
    [ExamMaximumTerm4]               DECIMAL (6, 2)  NULL
);


GO
PRINT N'Creating Table [sAttendance].[tPeriodNoMaster]...';


GO
CREATE TABLE [sAttendance].[tPeriodNoMaster] (
    [Id]         SMALLINT      NOT NULL,
    [Title]      NVARCHAR (10) NOT NULL,
    [IsObsolete] BIT           NOT NULL
);


GO
PRINT N'Creating Table [sBiometric].[tTempBiometricAlertData]...';


GO
CREATE TABLE [sBiometric].[tTempBiometricAlertData] (
    [AutoId]                 BIGINT           IDENTITY (1, 1) NOT NULL,
    [MobileNo]               NVARCHAR (50)    NULL,
    [EmailId]                NVARCHAR (50)    NULL,
    [MsgText]                NVARCHAR (MAX)   NULL,
    [Subject]                NVARCHAR (100)   NULL,
    [ReceiverSourceTypeId]   INT              NULL,
    [ReceiverSourceId]       BIGINT           NULL,
    [StudentName]            NVARCHAR (300)   NULL,
    [Code]                   NVARCHAR (20)    NULL,
    [WhatsAppContactNo]      NVARCHAR (20)    NULL,
    [SourceTypeId]           INT              NULL,
    [SourceId]               BIGINT           NULL,
    [OrgId]                  SMALLINT         NULL,
    [OrgGroupId]             SMALLINT         NULL,
    [Time]                   TIME (7)         NULL,
    [OrganizationTitle]      NVARCHAR (100)   NULL,
    [CloudTransactionDataId] BIGINT           NULL,
    [SchedularFromDateTime]  DATETIME         NULL,
    [SchedularToDateTime]    DATETIME         NULL,
    [CreatedDateTime]        DATETIME         NULL,
    [AlertId]                INT              NULL,
    [AlertUniqueId]          UNIQUEIDENTIFIER NULL
);


GO
PRINT N'Creating Default Constraint unnamed constraint on [sAssessment].[tTempAllExamWithAllTerm]...';


GO
ALTER TABLE [sAssessment].[tTempAllExamWithAllTerm]
    ADD DEFAULT ((0)) FOR [Obtain9];


GO
PRINT N'Creating Default Constraint unnamed constraint on [sAssessment].[tTempAllExamWithAllTerm]...';


GO
ALTER TABLE [sAssessment].[tTempAllExamWithAllTerm]
    ADD DEFAULT ((0)) FOR [Obtain4];


GO
PRINT N'Creating Default Constraint unnamed constraint on [sAssessment].[tTempAllExamWithAllTerm]...';


GO
ALTER TABLE [sAssessment].[tTempAllExamWithAllTerm]
    ADD DEFAULT ((0)) FOR [Obtain10];


GO
PRINT N'Creating Default Constraint unnamed constraint on [sAssessment].[tTempAllExamWithAllTerm]...';


GO
ALTER TABLE [sAssessment].[tTempAllExamWithAllTerm]
    ADD DEFAULT ((0)) FOR [Obtain7];


GO
PRINT N'Creating Default Constraint unnamed constraint on [sAssessment].[tTempAllExamWithAllTerm]...';


GO
ALTER TABLE [sAssessment].[tTempAllExamWithAllTerm]
    ADD DEFAULT ((0)) FOR [Obtain1];


GO
PRINT N'Creating Default Constraint unnamed constraint on [sAssessment].[tTempAllExamWithAllTerm]...';


GO
ALTER TABLE [sAssessment].[tTempAllExamWithAllTerm]
    ADD DEFAULT ((0)) FOR [Obtain2];


GO
PRINT N'Creating Default Constraint unnamed constraint on [sAssessment].[tTempAllExamWithAllTerm]...';


GO
ALTER TABLE [sAssessment].[tTempAllExamWithAllTerm]
    ADD DEFAULT ((0)) FOR [Obtain12];


GO
PRINT N'Creating Default Constraint unnamed constraint on [sAssessment].[tTempAllExamWithAllTerm]...';


GO
ALTER TABLE [sAssessment].[tTempAllExamWithAllTerm]
    ADD DEFAULT ((0)) FOR [Obtain13];


GO
PRINT N'Creating Default Constraint unnamed constraint on [sAssessment].[tTempAllExamWithAllTerm]...';


GO
ALTER TABLE [sAssessment].[tTempAllExamWithAllTerm]
    ADD DEFAULT ((0)) FOR [Obtain8];


GO
PRINT N'Creating Default Constraint unnamed constraint on [sAssessment].[tTempAllExamWithAllTerm]...';


GO
ALTER TABLE [sAssessment].[tTempAllExamWithAllTerm]
    ADD DEFAULT ((0)) FOR [Obtain3];


GO
PRINT N'Creating Default Constraint unnamed constraint on [sAssessment].[tTempAllExamWithAllTerm]...';


GO
ALTER TABLE [sAssessment].[tTempAllExamWithAllTerm]
    ADD DEFAULT ((0)) FOR [Obtain5];


GO
PRINT N'Creating Default Constraint unnamed constraint on [sAssessment].[tTempAllExamWithAllTerm]...';


GO
ALTER TABLE [sAssessment].[tTempAllExamWithAllTerm]
    ADD DEFAULT ((0)) FOR [Obtain6];


GO
PRINT N'Creating Default Constraint unnamed constraint on [sAssessment].[tTempAllExamWithAllTerm]...';


GO
ALTER TABLE [sAssessment].[tTempAllExamWithAllTerm]
    ADD DEFAULT ((0)) FOR [Obtain11];


GO
PRINT N'Creating Function [sFee].[fPendingFeeNamesGet]...';



GO
   CREATE FUNCTION [sFee].[fPendingFeeNamesGet](@rAcademicId bigint,@rReceiptBookId bigint
,@Fee TempPendingFee readonly
)
RETURNS nvarchar(2000) WITH EXECUTE AS CALLER
AS 
BEGIN

DECLARE @rFeeDetail nvarchar(2000)
SELECT 
			@rFeeDetail=COALESCE(@rFeeDetail+',','') +  F.FeeCode
			 FROM
			 @Fee F			  
			 WHERE AcademicId = @rAcademicId  
			 AND ReceiptBookId = @rReceiptBookId
			 Order By F.FeeOrderIndex
		
    RETURN ISNULL(@rFeeDetail,'') 
 
END
GO
PRINT N'Altering Procedure [sAcademic].[pClassworkAdd]...';


GO

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

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

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


GO

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

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

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


GO


ALTER PROCEDURE [sAcademic].[pClassworkHomeworkQueueGet]

	 @rId bigint=0,	 
	 @rSubjectId int=0,
	 @rClassId int=0,
	 @rEmployeeId bigint=0,
	 @rDivisionid int=0,
	 @rFromDate datetime='',
     @rToDate datetime='',
     @rOrgId int=0,
     --@rBatchId int
     @rOrgGroupBatchId int=0,
    @rUserId bigint =0,
	@rStatusId int=0
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON


DECLARE @rSourceId bigint
DECLARE @rSourceTypeId int

set @rSourceId = ( SELECT SourceId FROM sSecurity.tUser where Id=@rUserId)
set @rSourceTypeId = ( SELECT ISNULL(SourceTypeId,0) FROM sSecurity.tUser where Id=@rUserId)


BEGIN 


	--if(@rId = 0)
		--BEGIN

			if(@rSourceTypeId = 95)
				BEGIN

				CREATE TABLE #TempData
				( 
					Id bigint,
					EmployeeId bigint,
					ClassId int,
					DivisionId int,
					SubjectId int,
					ClassWorkDate Date,
					Classwork nvarchar(max),
					Homework nvarchar(max),
					ClassworkStatusId int,
					HomeWorkStatusId int,
					HomeWorkEndDate date,
					CreatedDateTime datetime,
					BatchId bigint,
					Batch nvarchar(100),
					SubjectName nvarchar(100),
					TeacherName nvarchar(200),
					ClassName nvarchar(100),
					DivisionName nvarchar(100),
					OrgId int,
					Organization nvarchar(200),
					UniqueId nvarchar(500),
					StatusId int,
					SubjectCordinatorEmployeeId bigint,
					Status nvarchar(200),
					IsSubmitHomework bit
				)
				INSERT INTO #TempData  
					SELECT 
					AC.Id,
					AC.EmployeeId,
					AC.ClassId,
					AC.DivisionId,
					AC.SubjectId,
					AC.ClassWorkDate,
					AC.Classwork,
					AC.Homework,
					ISNULL(ClassworkStatusId,1) AS ClassworkStatusId,
					ISNULL(HomeWorkStatusId,1) AS HomeWorkStatusId,
					--AC.HomeWorkEndDate,
					ISNULL(AC.HomeWorkEndDate,'') AS HomeWorkEndDate,
					AC.CreatedDateTime,
					AC.BatchId,
					BM.Title AS Batch,
					ISNULL(vTSD.SubjectName,'') as SubjectName,
					ISNULL(EM.FirstName + ' ' + EM.LastName,'') AS TeacherName,
					ISNULL(vTSD.ClassTitle,'') AS ClassName,
					ISNULL(vTSD.DivisionTitle,'') AS DivisionName,
					BM.OrgId,
					OM.DisplayTitle AS Organization,
					REPLACE(CONVERT(VARCHAR(20), AC.ClassWorkDate, 103),'/','') +'_'+ CONVERT(nvarchar(10),AC.DivisionId) +'_'+CONVERT(nvarchar(10),AC.SubjectId) AS UniqueId,
					ISNULL(AC.StatusId,549) AS StatusId,vTSD.SubjectCordinatorEmployeeId,
					CASE WHEN ISNULL(AC.StatusId,549) = 549 then 'Pending' WHEN AC.StatusId=550 then 'Approve' ELSE  'Reject' END  AS Status,
					ISNULL(AC.IsSubmitHomework,0) AS IsSubmitHomework
			FROM 
					sAcademic.tClasswork AC
					INNER JOIN sAcademic.vTeacherSubjectDivision vTSD ON vTSD.SubjectId = AC.SubjectId AND vTSD.DivisionId = AC.DivisionId AND vTSD.ClassId=AC.ClassId
					INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = vTSD.OrgId
					INNER JOIN sSetup.tOrgGroupMaster OGM ON OGM.Id = OM.OrgGroupId
					INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.OrgGroupId = OGM.Id
					INNER JOIN sHrm.tEmployeeMaster EM ON  AC.EmployeeId = EM.Id AND vTSD.EmployeeId = AC.EmployeeId
					--INNER JOIN sHrm.tEmployeeMaster EM ON  AC.EmployeeId = EM.Id 
					INNER JOIN sHrm.tEmployeeJobdetail EJD ON EJD.EmployeeId = EM.Id
					INNER JOIN sSetup.tBatchMaster BM On BM.Id= AC.BatchId AND BM.OrgGroupBatchId = OGBM.Id
					INNER JOIN sSecurity.tUserOrganization U ON U.OrgId = OM.Id 
			WHERE 
					--((AC.BatchId = @rBatchId) OR (@rBatchId = 0))
					((AC.Id = @rId) OR (@rId = 0))
					AND ((AC.EmployeeId= @rEmployeeId) OR (@rEmployeeId = 0))
					AND	((AC.ClassId = @rClassId) OR (@rClassId = 0))
					AND	((vTSD.OrgId = @rOrgId) OR (@rOrgId = 0))
					AND ((AC.SubjectId =@rSubjectId) OR (@rSubjectId=0))
					AND ((AC.DivisionId =@rDivisionId) OR (@rDivisionId=0))
					--AND (AC.ClassWorkDate>=@rFromDate OR ISNULL(@rFromDate,'')='')
					--AND (AC.ClassWorkDate<=@rToDate OR ISNULL(@rToDate,'')='')
					AND (OGBM.Id = @rOrgGroupBatchId) 
					AND ((U.UserId = @rUserId)OR(@rUserId=0))
					AND ((ISNULL(AC.StatusId,549) = @rStatusId) OR (@rStatusId=0)) 
					AND ((ISNULL(vTSD.SubjectCordinatorEmployeeId,0) = @rSourceId) or (@rSourceId=0))
					AND ISNULL(EM.IsOtherUser,0) = 0 
			order by 
					AC.HomeWorkEndDate DESC
						
				if (EXISTS (select 1 from #TempData))
				BEGIN
				
					Select * FROM #TempData tmp
					WHERE (tmp.ClassWorkDate>=@rFromDate OR ISNULL(@rFromDate,'')='')
					AND (tmp.ClassWorkDate<=@rToDate OR ISNULL(@rToDate,'')='')
				END
				ELSE
				BEGIN
					SELECT 
			AC.Id,
			AC.EmployeeId,
			AC.ClassId,
			AC.DivisionId,
			AC.SubjectId,
			AC.ClassWorkDate,
			AC.Classwork,
			AC.Homework,
			ISNULL(ClassworkStatusId,1) AS ClassworkStatusId,
			ISNULL(HomeWorkStatusId,1) AS HomeWorkStatusId,
			--AC.HomeWorkEndDate,
			ISNULL(AC.HomeWorkEndDate,'') AS HomeWorkEndDate,
			AC.CreatedDateTime,
			AC.BatchId,
			BM.Title AS Batch,
		    ISNULL(vTSD.SubjectName,'') as SubjectName,
		    ISNULL(EM.FirstName + ' ' + EM.LastName,'') AS TeacherName,
		    ISNULL(vTSD.ClassTitle,'') AS ClassName,
		    ISNULL(vTSD.DivisionTitle,'') AS DivisionName,
		    BM.OrgId,
		    OM.DisplayTitle AS Organization,
		    REPLACE(CONVERT(VARCHAR(20), AC.ClassWorkDate, 103),'/','') +'_'+ CONVERT(nvarchar(10),AC.DivisionId) +'_'+CONVERT(nvarchar(10),AC.SubjectId) AS UniqueId,
			ISNULL(AC.StatusId,549) AS StatusId,vTSD.SubjectCordinatorEmployeeId,
			CASE WHEN ISNULL(AC.StatusId,549) = 549 then 'Pending' WHEN AC.StatusId=550 then 'Approve' ELSE  'Reject' END  AS Status,
			ISNULL(AC.IsSubmitHomework,0) AS IsSubmitHomework
	FROM 
			sAcademic.tClasswork AC
			INNER JOIN sAcademic.vTeacherSubjectDivision vTSD ON vTSD.SubjectId = AC.SubjectId AND vTSD.DivisionId = AC.DivisionId AND vTSD.ClassId=AC.ClassId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = vTSD.OrgId
			INNER JOIN sSetup.tOrgGroupMaster OGM ON OGM.Id = OM.OrgGroupId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.OrgGroupId = OGM.Id
			INNER JOIN sHrm.tEmployeeMaster EM ON  AC.EmployeeId = EM.Id AND vTSD.EmployeeId = AC.EmployeeId
			--INNER JOIN sHrm.tEmployeeMaster EM ON  AC.EmployeeId = EM.Id 
			INNER JOIN sHrm.tEmployeeJobdetail EJD ON EJD.EmployeeId = EM.Id
			INNER JOIN sSetup.tBatchMaster BM On BM.Id= AC.BatchId AND BM.OrgGroupBatchId = OGBM.Id
			INNER JOIN sSecurity.tUserOrganization U ON U.OrgId = OM.Id 
	WHERE 
	        --((AC.BatchId = @rBatchId) OR (@rBatchId = 0))
			((AC.Id = @rId) OR (@rId = 0))
			AND ((AC.EmployeeId= @rEmployeeId) OR (@rEmployeeId = 0))
			AND	((AC.ClassId = @rClassId) OR (@rClassId = 0))
			AND	((vTSD.OrgId = @rOrgId) OR (@rOrgId = 0))
			AND ((AC.SubjectId =@rSubjectId) OR (@rSubjectId=0))
			AND ((AC.DivisionId =@rDivisionId) OR (@rDivisionId=0))
			AND (AC.ClassWorkDate>=@rFromDate OR ISNULL(@rFromDate,'')='')
			AND (AC.ClassWorkDate<=@rToDate OR ISNULL(@rToDate,'')='')
			AND (OGBM.Id = @rOrgGroupBatchId) 
			AND ((U.UserId = @rUserId)OR(@rUserId=0))
			AND ((ISNULL(AC.StatusId,549) = @rStatusId) OR (@rStatusId=0)) 
			AND ((ISNULL(vTSD.EmployeeId,0) = @rSourceId) or (@rSourceId=0))
			AND ISNULL(EM.IsOtherUser,0) = 0 
	order by 
			AC.HomeWorkEndDate DESC
				END

									
				DROP TABLE #TempData
				END

			ELSE IF (@rUserId = 0)
			BEGIN
			SELECT 
			AC.Id,
			AC.EmployeeId,
			AC.ClassId,
			AC.DivisionId,
			AC.SubjectId,
			AC.ClassWorkDate,
			AC.Classwork,
			AC.Homework,
			ISNULL(ClassworkStatusId,1) AS ClassworkStatusId,
			ISNULL(HomeWorkStatusId,1) AS HomeWorkStatusId,
			--AC.HomeWorkEndDate,
			ISNULL(AC.HomeWorkEndDate,'') AS HomeWorkEndDate,

			AC.CreatedDateTime,
			AC.BatchId,
			BM.Title AS Batch,
		    ISNULL(vTSD.SubjectName,'') as SubjectName,
		    ISNULL(EM.FirstName + ' ' + EM.LastName,'') AS TeacherName,
		    ISNULL(vTSD.ClassTitle,'') AS ClassName,
		    ISNULL(vTSD.DivisionTitle,'') AS DivisionName,
		    BM.OrgId,
		    OM.DisplayTitle AS Organization,
		    REPLACE(CONVERT(VARCHAR(20), AC.ClassWorkDate, 103),'/','') +'_'+ CONVERT(nvarchar(10),AC.DivisionId) +'_'+CONVERT(nvarchar(10),AC.SubjectId) AS UniqueId,
			ISNULL(AC.StatusId,549) AS StatusId,vTSD.SubjectCordinatorEmployeeId,
			CASE WHEN ISNULL(AC.StatusId,549) = 549 then 'Pending' WHEN AC.StatusId=550 then 'Approve' ELSE  'Reject' END  AS Status,
			ISNULL(AC.IsSubmitHomework,0) AS IsSubmitHomework
	FROM 
			sAcademic.tClasswork AC
			INNER JOIN sAcademic.vTeacherSubjectDivision vTSD ON vTSD.SubjectId = AC.SubjectId AND vTSD.DivisionId = AC.DivisionId AND vTSD.ClassId=AC.ClassId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = vTSD.OrgId
			INNER JOIN sSetup.tOrgGroupMaster OGM ON OGM.Id = OM.OrgGroupId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.OrgGroupId = OGM.Id
			INNER JOIN sHrm.tEmployeeMaster EM ON  AC.EmployeeId = EM.Id AND vTSD.EmployeeId = AC.EmployeeId
			--INNER JOIN sHrm.tEmployeeMaster EM ON  AC.EmployeeId = EM.Id 
			--INNER JOIN sHrm.tEmployeeJobdetail EJD ON EJD.EmployeeId = EM.Id
			INNER JOIN sSetup.tBatchMaster BM On BM.Id= AC.BatchId AND BM.OrgGroupBatchId = OGBM.Id
			--INNER JOIN sSecurity.tUserOrganization U ON U.OrgId = OM.Id 
	WHERE 
	        --((AC.BatchId = @rBatchId) OR (@rBatchId = 0))
			((AC.Id = @rId) OR (@rId = 0))
			AND ((AC.EmployeeId= @rEmployeeId) OR (@rEmployeeId = 0))
			AND	((AC.ClassId = @rClassId) OR (@rClassId = 0))
			AND	((vTSD.OrgId = @rOrgId) OR (@rOrgId = 0))
			AND ((AC.SubjectId =@rSubjectId) OR (@rSubjectId=0))
			AND ((AC.DivisionId =@rDivisionId) OR (@rDivisionId=0))
			AND (AC.ClassWorkDate>=@rFromDate OR ISNULL(@rFromDate,'')='')
			AND (AC.ClassWorkDate<=@rToDate OR ISNULL(@rToDate,'')='')
			AND (OGBM.Id = @rOrgGroupBatchId) 
			--AND ((U.UserId = @rUserId)OR(@rUserId=0))
			AND ((ISNULL(AC.StatusId,549) = @rStatusId) OR (@rStatusId=0)) 
			AND ISNULL(EM.IsOtherUser,0) = 0 
	order by 
			AC.HomeWorkEndDate DESC
			END

			ELSE
				BEGIN
					SELECT 
			AC.Id,
			AC.EmployeeId,
			AC.ClassId,
			AC.DivisionId,
			AC.SubjectId,
			AC.ClassWorkDate,
			AC.Classwork,
			AC.Homework,
			ISNULL(ClassworkStatusId,1) AS ClassworkStatusId,
			ISNULL(HomeWorkStatusId,1) AS HomeWorkStatusId,
			--AC.HomeWorkEndDate,
			ISNULL(AC.HomeWorkEndDate,'') AS HomeWorkEndDate,

			AC.CreatedDateTime,
			AC.BatchId,
			BM.Title AS Batch,
		    ISNULL(vTSD.SubjectName,'') as SubjectName,
		    ISNULL(EM.FirstName + ' ' + EM.LastName,'') AS TeacherName,
		    ISNULL(vTSD.ClassTitle,'') AS ClassName,
		    ISNULL(vTSD.DivisionTitle,'') AS DivisionName,
		    BM.OrgId,
		    OM.DisplayTitle AS Organization,
		    REPLACE(CONVERT(VARCHAR(20), AC.ClassWorkDate, 103),'/','') +'_'+ CONVERT(nvarchar(10),AC.DivisionId) +'_'+CONVERT(nvarchar(10),AC.SubjectId) AS UniqueId,
			ISNULL(AC.StatusId,549) AS StatusId,vTSD.SubjectCordinatorEmployeeId,
			CASE WHEN ISNULL(AC.StatusId,549) = 549 then 'Pending' WHEN AC.StatusId=550 then 'Approve' ELSE  'Reject' END  AS Status,
			ISNULL(AC.IsSubmitHomework,0) AS IsSubmitHomework
	FROM 
			sAcademic.tClasswork AC
			INNER JOIN sAcademic.vTeacherSubjectDivision vTSD ON vTSD.SubjectId = AC.SubjectId AND vTSD.DivisionId = AC.DivisionId AND vTSD.ClassId=AC.ClassId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = vTSD.OrgId
			INNER JOIN sSetup.tOrgGroupMaster OGM ON OGM.Id = OM.OrgGroupId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.OrgGroupId = OGM.Id
			INNER JOIN sHrm.tEmployeeMaster EM ON  AC.EmployeeId = EM.Id AND vTSD.EmployeeId = AC.EmployeeId
			--INNER JOIN sHrm.tEmployeeMaster EM ON  AC.EmployeeId = EM.Id 
			--INNER JOIN sHrm.tEmployeeJobdetail EJD ON EJD.EmployeeId = EM.Id
			INNER JOIN sSetup.tBatchMaster BM On BM.Id= AC.BatchId AND BM.OrgGroupBatchId = OGBM.Id
			INNER JOIN sSecurity.tUserOrganization U ON U.OrgId = OM.Id 
	WHERE 
	        --((AC.BatchId = @rBatchId) OR (@rBatchId = 0))
			((AC.Id = @rId) OR (@rId = 0))
			AND ((AC.EmployeeId= @rEmployeeId) OR (@rEmployeeId = 0))
			AND	((AC.ClassId = @rClassId) OR (@rClassId = 0))
			AND	((vTSD.OrgId = @rOrgId) OR (@rOrgId = 0))
			AND ((AC.SubjectId =@rSubjectId) OR (@rSubjectId=0))
			AND ((AC.DivisionId =@rDivisionId) OR (@rDivisionId=0))
			AND (AC.ClassWorkDate>=@rFromDate OR ISNULL(@rFromDate,'')='')
			AND (AC.ClassWorkDate<=@rToDate OR ISNULL(@rToDate,'')='')
			AND (OGBM.Id = @rOrgGroupBatchId) 
			AND ((U.UserId = @rUserId)OR(@rUserId=0))
			AND ((ISNULL(AC.StatusId,549) = @rStatusId) OR (@rStatusId=0)) 
			AND ISNULL(EM.IsOtherUser,0) = 0 
	order by 
			AC.HomeWorkEndDate DESC
				END

		--END 
	--ELSE
	--	BEGIN
	--	SELECT 
	--		AC.Id,
	--		AC.EmployeeId,
	--		AC.ClassId,
	--		AC.DivisionId,
	--		AC.SubjectId,
	--		AC.ClassWorkDate,
	--		AC.Classwork,
	--		AC.Homework,
	--		ISNULL(ClassworkStatusId,1) AS ClassworkStatusId,
	--		ISNULL(HomeWorkStatusId,1) AS HomeWorkStatusId,
	--		--AC.HomeWorkEndDate,
	--		ISNULL(AC.HomeWorkEndDate,'') AS HomeWorkEndDate,
	--		AC.CreatedDateTime,
	--		AC.BatchId,
	--		BM.Title AS Batch,
	--	    ISNULL(vTSD.SubjectName,'') as SubjectName,
	--	    ISNULL(EM.FirstName + ' ' + EM.LastName,'') AS TeacherName,
	--	    ISNULL(vTSD.ClassTitle,'') AS ClassName,
	--	    ISNULL(vTSD.DivisionTitle,'') AS DivisionName,
	--	    BM.OrgId,
	--	    OM.DisplayTitle AS Organization,
	--	    REPLACE(CONVERT(VARCHAR(20), AC.ClassWorkDate, 103),'/','') +'_'+ CONVERT(nvarchar(10),AC.DivisionId) +'_'+CONVERT(nvarchar(10),AC.SubjectId) AS UniqueId
			
	--FROM 
	--		sAcademic.tClasswork AC
	--		INNER JOIN sAcademic.vTeacherSubjectDivision vTSD ON vTSD.SubjectId = AC.SubjectId AND vTSD.DivisionId = AC.DivisionId AND vTSD.ClassId=AC.ClassId
	--		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = vTSD.OrgId
	--		INNER JOIN sSetup.tOrgGroupMaster OGM ON OGM.Id = OM.OrgGroupId
	--		INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.OrgGroupId = OGM.Id
	--		INNER JOIN sHrm.tEmployeeMaster EM ON  AC.EmployeeId = EM.Id AND vTSD.EmployeeId = AC.EmployeeId
	--		INNER JOIN sHrm.tEmployeeJobdetail EJD ON EJD.EmployeeId = EM.Id
	--		INNER JOIN sSetup.tBatchMaster BM On BM.Id= AC.BatchId AND BM.OrgGroupBatchId = OGBM.Id
	--		INNER JOIN sSecurity.tUserOrganization U ON U.OrgId = OM.Id 
	--WHERE 
	--        --((AC.BatchId = @rBatchId) OR (@rBatchId = 0))
	--		((AC.Id = @rId) OR (@rId = 0))
	--		AND ((AC.EmployeeId= @rEmployeeId) OR (@rEmployeeId = 0))
	--		AND	((AC.ClassId = @rClassId) OR (@rClassId = 0))
	--		AND	((vTSD.OrgId = @rOrgId) OR (@rOrgId = 0))
	--		AND ((AC.SubjectId =@rSubjectId) OR (@rSubjectId=0))
	--		AND ((AC.DivisionId =@rDivisionId) OR (@rDivisionId=0))
	--		AND (AC.ClassWorkDate>=@rFromDate OR ISNULL(@rFromDate,'')='')
	--		AND (AC.ClassWorkDate<=@rToDate OR ISNULL(@rToDate,'')='')
	--		AND (OGBM.Id = @rOrgGroupBatchId) 
	--		AND ((U.UserId = @rUserId)OR(@rUserId=0))
	--		GROUP BY AC.Id,
	--		AC.EmployeeId,
	--		AC.ClassId,
	--		AC.DivisionId,
	--		AC.SubjectId,
	--		AC.ClassWorkDate,
	--		AC.Classwork,
	--		AC.Homework,
	--		ClassworkStatusId,
	--		HomeWorkStatusId,
	--		--AC.HomeWorkEndDate,
	--		AC.HomeWorkEndDate,
	--		AC.CreatedDateTime,
	--		AC.BatchId,
	--		BM.Title,
	--	  vTSD.SubjectName,
	--	    EM.FirstName,  EM.LastName,
	--	    vTSD.ClassTitle,
	--	   vTSD.DivisionTitle,
	--	    BM.OrgId,
	--	    OM.DisplayTitle,
	--	     AC.ClassWorkDate, AC.DivisionId,AC.SubjectId
	--order by 
	--		AC.HomeWorkEndDate DESC
	--	END
	
END
GO
PRINT N'Altering Procedure [sAcademic].[pTopicMasterAdd]...';


GO


ALTER PROCEDURE [sAcademic].[pTopicMasterAdd]
	 
        @rId int,
        @rNumber smallint,
        @rTitle nvarchar(100),
        @rSubjectId int,
        @rClassId int,
        @rOrgId smallint,
        @rCreatedUserId bigint,
		@rIsObsolete bit
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	IF(@rId = 0)	
	BEGIN
		If Exists(select Id from sAcademic.tTopicMaster where Title=@rTitle AND OrgId=@rOrgId AND ClassId=@rClassId AND SubjectId=@rSubjectId)
			BEGIN
			select -102 as Result
			RETURN
		END 
	
		If Exists(select Id from sAcademic.tTopicMaster where Number=@rNumber AND OrgId=@rOrgId AND ClassId=@rClassId AND SubjectId=@rSubjectId)
			BEGIN
			select -103 as Result
			RETURN
		END 
	END
	ELSE
	BEGIN
		If  Exists(select Id from sAcademic.tTopicMaster where Title=@rTitle AND OrgId=@rOrgId AND ClassId=@rClassId AND SubjectId=@rSubjectId AND Id<>@rId)
		Begin
			select -102 as Result
			RETURN
		End
		If  Exists(select Id from sAcademic.tTopicMaster where Number=@rNumber AND OrgId=@rOrgId AND ClassId=@rClassId AND SubjectId=@rSubjectId AND Id<>@rId)
		Begin
			select -103 as Result
			RETURN
		End

	END
	
	
	
	 BEGIN TRANSACTION	
	 DECLARE @lNextNumber BIGINT 

	IF(@rId = 0)	
	BEGIN
		
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sAcademic.tTopicMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	INSERT INTO sAcademic.tTopicMaster
		(
			Id,
			Number,
			Title,
			SubjectId,
			ClassId,
			OrgId,
			CreatedUserId,
			CreatedDateTime,
			----added by megha for 0024270
			IsObsolete
		)
	VALUES
		(
			@lNextNumber,
			@rNumber,
			@rTitle,
			@rSubjectId,
			@rClassId,
			@rOrgId,
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rIsObsolete
		)
		    SELECT 1 AS Result
	END	 

ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE  sAcademic.tTopicMaster
	    SET
			Number=@rNumber,
			Title=@rTitle,
			SubjectId=@rSubjectId,
			ClassId=@rClassId,
			OrgId=@rOrgId,
			UpdatedUserId=@rCreatedUserId,
			UpdatedDateTime=sCommon.fGetDate(),
			IsObsolete = @rIsObsolete
	      
	      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 [sAcademic].[pTopicMasterGet]...';


GO

ALTER PROCEDURE [sAcademic].[pTopicMasterGet]

	 @rId int,
	 @rOrgId smallint,
	 @rClassId int,
	 @rSubjectId int,
	 @rEmployeeId bigint,
	 @rSourceTypeId smallint = 0
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
	IF(@rSourceTypeId = 0)
	BEGIN
		SELECT 
				DISTINCT TM.Id,
				TM.Number,
				TM.Title,
				TM.OrgId,
				TM.ClassId,
				TM.SubjectId,
				TM.CreatedUserId,
				TM.CreatedDateTime,
				CM.DisplayTitle AS ClassName,
				SM.Title AS SubjectName,
				CM.OrderIndex,
				SM.OrderIndex,
				--added by megha for 0024270
				ISNULL(TM.IsObsolete,0) AS IsObsolete,
				'' As StatusMessage
		FROM 
				sAcademic.tTopicMaster TM
				INNER JOIN sSetup.tClassMaster CM ON CM.Id = TM.ClassId
				INNER JOIN sSetup.tSubjectMaster SM ON SM.Id = TM.SubjectId
				LEFT JOIN sAcademic.vTeacherSubjectDivision vTSD ON vTSD.ClassId = TM.ClassId 			
				--AND vTSD.SubjectId = TM.SubjectId 
				AND vTSD.EmployeeId = @rEmployeeId
		WHERE 
			(TM.OrgId=@rOrgId)
			AND ((TM.Id = @rId) OR (@rId = 0))
			AND ((TM.ClassId = @rClassId) OR (@rClassId = 0))
			AND ((TM.SubjectId = @rSubjectId) OR (@rSubjectId = 0))
			--AND ((vTSD.EmployeeId = @rEmployeeId) OR (vTSD.EmployeeId = 0))
			--ORDER BY CM.OrderIndex
		ORDER BY CM.OrderIndex,SM.OrderIndex,TM.Number ASC
	END
	ELSE IF (@rSourceTypeId = 95)
	BEGIN
		SELECT 
				DISTINCT TM.Id,
				TM.Number,
				TM.Title,
				TM.OrgId,
				TM.ClassId,
				TM.SubjectId,
				TM.CreatedUserId,
				TM.CreatedDateTime,
				CM.DisplayTitle AS ClassName,
				SM.Title AS SubjectName,
				CM.OrderIndex,
				SM.OrderIndex,
				ISNULL(TM.IsObsolete,0) AS IsObsolete,
				'' As StatusMessage
		FROM 
				sAcademic.tTopicMaster TM
				INNER JOIN sSetup.tClassMaster CM ON CM.Id = TM.ClassId
				INNER JOIN sSetup.tSubjectMaster SM ON SM.Id = TM.SubjectId
				INNER JOIN sAcademic.vTeacherSubjectDivision vTSD ON vTSD.ClassId = TM.ClassId AND vTSD.SubjectId = TM.SubjectId 
				AND vTSD.EmployeeId = @rEmployeeId
		WHERE 
			(TM.OrgId=@rOrgId)
			AND ((TM.Id = @rId) OR (@rId = 0))
			AND ((TM.ClassId = @rClassId) OR (@rClassId = 0))
			AND ((TM.SubjectId = @rSubjectId) OR (@rSubjectId = 0))
		ORDER BY CM.OrderIndex,SM.OrderIndex,TM.Number ASC
	END
END
GO
PRINT N'Altering Procedure [sAlert].[pEmployeeBiometricLastOutTimeGet]...';


GO

ALTER PROCEDURE [sAlert].[pEmployeeBiometricLastOutTimeGet]
	@rTemplate nvarchar(max)='',
	@rSubject nvarchar(100)='',
	@rOrgId int,
	@rOrgGroupId int,
	@rIntervalTime int=0,
	@rToDateTime dateTime=null,
	@rFromDateTime DateTime=null
 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY	
		BEGIN TRANSACTION 
			if object_id('tempdb..#tShift') is not null
			BEGIN
				DROP TABLE #tShift
			END
			CREATE TABLE #tShift(
					ShiftCode int NOT NULL,
					OutTimeAlertTime time not NUll
				)
			insert #tShift
			Select 
				ShiftCode, 
				CAST(OutTimeAlertTime AS Time)
				--case When DATEDIFF(MINUTE,CAST(OutTimeAlertTime AS Time),cast([sCommon].[fGetDate]() as Time)) < @rIntervalTime then DATEDIFF(MINUTE,CAST(OutTimeAlertTime AS Time),cast([sCommon].[fGetDate]() as Time)) else @rIntervalTime end 
			  FROM sBiometric.tShiftMasterCloud
			where  ((OrgGroupId = @rOrgGroupId) OR (@rOrgGroupId=0))  
			AND IsOutTimeAlertTime=1
			--AND CAST(OutTimeAlertTime AS Time)<=cast([sCommon].[fGetDate]() as Time)
			--AND CAST(OutTimeAlertTime AS Time) > CAST(DATEADD(minute,-(@rIntervalTime),[sCommon].[fGetDate]()) AS Time)
			AND CAST(OutTimeAlertTime AS Time)<cast(@rToDateTime as Time)
			AND CAST(OutTimeAlertTime AS Time) >= CAST(@rFromDateTime AS Time)

			declare @lcount int=(SELECT COUNT(ShiftCode) FROM #tShift)
	 
			--select * from #tShift
			if object_id('tempdb..#tTable') is not null
			BEGIN
				DROP TABLE #tTable
			END
			CREATE TABLE #tTable(
						SourceId bigint NOT NULL,
						In_Out_Time [datetime] NOT NULL,
						SourceTypeId int NOT NULL,
						OutTimeAlertTime time NOT NULL,
						CreatedDateTime [datetime] NOT NULL
					)
			if(@lcount>0)
			BEGIN
				insert into #tTable
				select SourceId,MAX(In_Out_Time),SourceTypeId,tempShift.OutTimeAlertTime,Max(CreatedDateTime) 
				from [sBiometric].[tCloudTransactionData] CDT 
				inner join #tShift tempShift ON tempShift.ShiftCode=CDT.ShiftCode
				WHERE Attn_Dt=CONVERT(date,[sCommon].[fGetDate]())  AND SourceTypeId=95 Group by SourceId,SourceTypeId,tempShift.OutTimeAlertTime
			END

			--select * from #tTable

			SELECT 
				EM.MobileNumber AS MobileNo,	
				EM.CompanyEmail AS EmailId,
				replace (
				replace(@rTemplate,'[EmployeeName]',EM.EmployeeName),
				'[TimeStamp]',ISNULL(Convert(varchar,temp.In_Out_Time,108),''))
				 AS MsgText,
				@rSubject AS Subject,
				95 AS ReceiverSourceTypeId,
				EM.EmployeeId AS ReceiverSourceId,
				EM.EmployeeName AS EmployeeName,
				ISNULL(EC.WhatsAppContactNo,'') AS WhatsAppContactNo,
				95 AS SourceTypeId,
				EM.EmployeeId AS SourceId,
				EM.OrgId,
				OM.OrgGroupId,
				OM.DisplayTitle AS OrganizationTitle
			FROM 
				#tTable temp
				Inner join sHrm.vEmployeeCommonDetail EM ON temp.SourceId=EM.EmployeeId
				LEFT JOIN sHrm.tEmployeeCommunications EC ON EC.EmployeeId = EM.EmployeeId
				INNER JOIN sSetup.tOrganizationMaster OM ON EM.OrgID = OM.Id
			WHERE
				--temp.OutTimeAlertTime <= CAST([sCommon].[fGetDate]() AS Time)
				--AND temp.OutTimeAlertTime > CAST(DATEADD(minute,-(@rIntervalTime),[sCommon].[fGetDate]()) AS Time)
				temp.OutTimeAlertTime < cast(@rToDateTime as Time)
				AND temp.OutTimeAlertTime >= Cast(@rFromDateTime As Time)
				AND EM.OrgID =@rOrgId

			DROP TABLE #tTable
			DROP TABLE #tShift
		COMMIT TRANSACTION
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH
END
GO
PRINT N'Altering Procedure [sAlert].[pStudentBiometricLastOutTimeGet]...';


GO


ALTER PROCEDURE [sAlert].[pStudentBiometricLastOutTimeGet]
	@rTemplate nvarchar(max)='',
	@rSubject nvarchar(100)='',
	@rOrgId int,
	@rOrgGroupId int,
	@rIntervalTime int=0,
	@rToDateTime dateTime,
	@rFromDateTime DateTime
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY	
		BEGIN TRANSACTION 
			if object_id('tempdb..#tShift') is not null
			BEGIN
				DROP TABLE #tShift
			END
			CREATE TABLE #tShift(
					ShiftCode int NOT NULL,
					OutTimeAlertTime time not NUll,
					LastOutAlertBasedOnId int not NUll
				)

			insert #tShift
			Select 
				ShiftCode,
				 case when LastOutAlertBasedOnId=3 THEN 
				 --case When DATEDIFF(MINUTE,CAST(EndTime AS Time),cast([sCommon].[fGetDate]() as Time)) < @rIntervalTime THEN CAST(DATEADD(minute,-(GraceBefore),EndTime) AS Time) else  CAST(DATEADD(minute,-(@rIntervalTime),[sCommon].[fGetDate]()) AS Time) end 
				 case When DATEDIFF(MINUTE,CAST(EndTime AS Time),cast(@rToDateTime as Time)) < DATEDIFF(MINUTE,CAST(@rFromDateTime AS Time),cast(@rToDateTime as Time))  THEN CAST(DATEADD(minute,-(GraceBefore),EndTime) AS Time) else  CAST(@rFromDateTime AS Time) end 
				 else  CAST(OutTimeAlertTime AS Time) end,
				 isnull(LastOutAlertBasedOnId,1)
				--case When DATEDIFF(MINUTE,CAST(@rIntervalTime AS Time),cast([sCommon].[fGetDate]() as Time)) < @rIntervalTime then DATEDIFF(MINUTE,CAST(OutTimeAlertTime AS Time),cast([sCommon].[fGetDate]() as Time)) else @rIntervalTime end 
			FROM sBiometric.tShiftMasterCloud
			where  ((OrgGroupId = @rOrgGroupId) OR (@rOrgGroupId=0))  
			AND IsOutTimeAlertTime=1
			AND (
			 ( (LastOutAlertBasedOnId=1 OR LastOutAlertBasedOnId=2) AND CAST(OutTimeAlertTime AS Time)<cast(@rToDateTime as Time)
			AND CAST(OutTimeAlertTime AS Time) > CAST(@rFromDateTime AS Time)) 
			OR 
			(LastOutAlertBasedOnId=3 AND CAST(DATEADD(minute,-@rIntervalTime,EndTime) AS Time)<cast(@rToDateTime as Time)
			AND CAST(OutTimeAlertTime AS Time) > CAST(@rFromDateTime AS Time))
			)
			--AND (
			-- ( (LastOutAlertBasedOnId=1 OR LastOutAlertBasedOnId=2) AND CAST(OutTimeAlertTime AS Time)<cast([sCommon].[fGetDate]() as Time)
			--AND CAST(OutTimeAlertTime AS Time) > CAST(DATEADD(minute,-(@rIntervalTime),[sCommon].[fGetDate]()) AS Time)) 
			--OR 
			--(LastOutAlertBasedOnId=3 AND CAST(DATEADD(minute,-@rIntervalTime,EndTime) AS Time)<cast([sCommon].[fGetDate]() as Time)
			--AND CAST(OutTimeAlertTime AS Time) > CAST(DATEADD(minute,-(@rIntervalTime),[sCommon].[fGetDate]()) AS Time))
			--)

			--select * from #tShift
			declare @lcount int=(SELECT COUNT(ShiftCode) FROM #tShift)

			if object_id('tempdb..#tTable') is not null
			BEGIN
				DROP TABLE #tTable
			END
			CREATE TABLE #tTable(
				SourceId bigint NOT NULL,
				In_Out_Time [datetime] NOT NULL,
				SourceTypeId int NOT NULL,
				OutTimeAlertTime time NOT NULL,
				CreatedDateTime [datetime] NOT NULL,
				LastOutAlertBasedOnId int NOT NULL,
				ShiftCode int NOT NULL
			)
			if(@lcount>0)
			BEGIN
				insert into #tTable
				select SourceId,MAX(In_Out_Time),SourceTypeId,tempShift.OutTimeAlertTime,Max(CreatedDateTime),tempShift.LastOutAlertBasedOnId,CDT.ShiftCode
				from [sBiometric].[tCloudTransactionData] CDT 
				inner join #tShift tempShift ON tempShift.ShiftCode=CDT.ShiftCode
				WHERE Attn_Dt=CONVERT(date,[sCommon].[fGetDate]())  AND SourceTypeId=2003 Group by SourceId,SourceTypeId,tempShift.OutTimeAlertTime,tempShift.LastOutAlertBasedOnId,CDT.ShiftCode
			End
			--select * from #tTable

			SELECT 
				SC.ParentContactNo AS MobileNo,	
				SC.ParentEmail AS EmailId,
				replace (
				replace(@rTemplate,'[StudentName]',SC.Name),
				'[TimeStamp]',ISNULL(Convert(varchar,temp.In_Out_Time,108),''))
				 AS MsgText,
				@rSubject AS Subject,
				2003 AS ReceiverSourceTypeId,
				SC.StudentId AS ReceiverSourceId,
				SC.Name AS StudentName,
				SC.Code,
				ISNULL(SC.WhatsAppContactNo,'') AS WhatsAppContactNo,
				2003 AS SourceTypeId,
				SC.StudentId AS SourceId,
				SC.OrgId,
				OM.OrgGroupId,
				OM.DisplayTitle AS OrganizationTitle


			FROM 
				#tTable temp
				Inner Join sBiometric.tShiftMasterCloud SMC on SMC.ShiftCode=temp.ShiftCode
				Inner join sStudent.vStudentCommunication SC ON temp.SourceId=SC.StudentId AND SC.IsActiveBatch=1
				INNER JOIN sSetup.tOrganizationMaster OM ON SC.OrgID = OM.Id
			WHERE
			((temp.LastOutAlertBasedOnId=1 ) AND temp.OutTimeAlertTime <= CAST(@rToDateTime AS Time)
				AND temp.OutTimeAlertTime > CAST(@rFromDateTime AS Time)
				
				OR( temp.LastOutAlertBasedOnId=2 AND CAST(DATEADD(minute,-(SMC.GraceBefore),SMC.EndTime) AS Time) <= CAST(temp.In_Out_Time  AS Time)
				AND CAST(temp.In_Out_Time AS Time) < CAST(@rToDateTime AS Time)
				)
				OR 
				(  
					(temp.LastOutAlertBasedOnId=3 
					AND (CAST(temp.In_Out_Time  AS Time)  >= CAST(temp.OutTimeAlertTime AS Time) 
					AND CAST(temp.In_Out_Time  AS Time)  <= CAST([sCommon].[fGetDate]() AS Time)))
					))

				--((temp.LastOutAlertBasedOnId=1 ) AND temp.OutTimeAlertTime <= CAST([sCommon].[fGetDate]() AS Time)
				--AND temp.OutTimeAlertTime > CAST(DATEADD(minute,-(@rIntervalTime),[sCommon].[fGetDate]()) AS Time)
				
				--OR( temp.LastOutAlertBasedOnId=2 AND CAST(DATEADD(minute,-(SMC.GraceBefore),SMC.EndTime) AS Time) <= CAST(temp.In_Out_Time  AS Time)
				--AND CAST(temp.In_Out_Time AS Time) < CAST([sCommon].[fGetDate]() AS Time)
				--)
				--OR 
				--(  
				--	(temp.LastOutAlertBasedOnId=3 
				--	AND (CAST(temp.In_Out_Time  AS Time)  >= CAST(temp.OutTimeAlertTime AS Time) 
				--	AND CAST(temp.In_Out_Time  AS Time)  <= CAST([sCommon].[fGetDate]() AS Time)))
				--	))
				AND SC.OrgID =@rOrgId
				AND SC.StatusId = 1

			DROP TABLE #tTable
			DROP TABLE #tShift
		COMMIT TRANSACTION
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH
END
GO
PRINT N'Altering Procedure [sAlert].[pStudentBiometricFirstInTimeGet]...';


GO

ALTER PROCEDURE [sAlert].[pStudentBiometricFirstInTimeGet]
	@rTemplate nvarchar(max)='',
	@rSubject nvarchar(100)='',
	@rOrgId int,
	@rIntervalTime int=0,
	@rToDateTime dateTime,
	@rFromDateTime DateTime

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY	
		BEGIN TRANSACTION 
		declare @lDateTimeNow datetime=[sCommon].[fGetDate]()
		declare @lLastStudentFirstInAlertSendTime datetime
		
			if object_id('tempdb..#tTable') is not null
			BEGIN
				DROP TABLE #tTable
			END
			CREATE TABLE #tTable(
					SourceId bigint NOT NULL,
					In_Out_Time [datetime] NOT NULL,
					SourceTypeId int NOT NULL,
					CreatedDateTime [datetime] NOT NULL,
					AutoId bigint not null,

				)
			insert into #tTable
			select CDT.SourceId,min(CDT.In_Out_Time),CDT.SourceTypeId,min(CDT.CreatedDateTime),min(CDT.Autoid)
			from [sBiometric].[tCloudTransactionData] CDT
			inner join sBiometric.tShiftMasterCloud SMC ON SMC.ShiftCode=CDT.ShiftCode
			WHERE CDT.Attn_Dt=CONVERT(date,@lDateTimeNow)  AND CDT.SourceTypeId=2003
				AND (isnull(SMC.IsStopInTimeAlertTime,0)=0 OR (SMC.IsStopInTimeAlertTime=1 
				AND CAST(SMC.StopInTimeAlertTime as Time)>=CAST(@rFromDateTime AS Time)
				AND  CAST(SMC.StopInTimeAlertTime as Time)>=CAST(CDT.In_Out_Time AS Time)))
			 Group by CDT.SourceId,CDT.SourceTypeId
	
			--select * from #tTable
			
			DECLARE @AlertUniqueId uniqueidentifier = NEWID();
			
			Insert Into sBiometric.tTempBiometricAlertData
			SELECT 
				SC.ParentContactNo AS MobileNo,	
				SC.ParentEmail AS EmailId,
				replace (
				replace (
				replace (
				replace(@rTemplate,'[StudentName]',SC.Name),
				'[TimeStamp]',ISNULL(Convert(varchar,temp.In_Out_Time,108),'')),
				'[PresentTime]',ISNULL(Convert(varchar,temp.In_Out_Time,108),'')),
				'[PresentDate]',ISNULL(Convert(varchar,[sCommon].[fGetDate](),103),''))
				 AS MsgText,
				@rSubject AS Subject,
				2003 AS ReceiverSourceTypeId,
				SC.StudentId AS ReceiverSourceId,
				SC.Name AS StudentName,
				SC.Code AS Code,
				ISNULL(SC.WhatsAppContactNo,'') AS WhatsAppContactNo,
				2003 AS SourceTypeId,
				SC.StudentId AS SourceId,
				SC.OrgId,
				OM.OrgGroupId,
				ISNULL(Convert(varchar,temp.In_Out_Time,108),'') as Time,
				OM.DisplayTitle AS OrganizationTitle,
				temp.AutoId,
				@rFromDateTime,
				@rToDateTime,
				sCommon.fGetDate(),
				129,
				@AlertUniqueId
			FROM 
				#tTable temp
				Inner join sStudent.vStudentCommunication SC ON temp.SourceId=SC.StudentId AND SC.IsActiveBatch=1
				INNER JOIN sSetup.tOrganizationMaster OM ON SC.OrgID = OM.Id
			WHERE
				temp.CreatedDateTime < @rToDateTime
				AND temp.CreatedDateTime >= @rFromDateTime
				AND SC.OrgID =@rOrgId
				AND SC.StatusId = 1

			SELECT 
				MobileNo AS MobileNo,	
				EmailId AS EmailId,
				MsgText AS MsgText,
				Subject AS Subject,
				2003 AS ReceiverSourceTypeId,
				ReceiverSourceId AS ReceiverSourceId,
				StudentName AS StudentName,
				Code AS Code,
				WhatsAppContactNo AS WhatsAppContactNo,
				2003 AS SourceTypeId,
				SourceId AS SourceId,
				OrgId,
				OrgGroupId,
				 Time,
				 OrganizationTitle
			FROM 
				sBiometric.tTempBiometricAlertData
			WHERE
			   AlertUniqueId=@AlertUniqueId


			DROP TABLE #tTable
		COMMIT TRANSACTION
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH

END
GO
PRINT N'Altering Procedure [sBiometric].[pMonthTransProcess]...';


GO
 

--ALTER PROCEDURE [sBiometric].[pMonthTransProcess]

--AS
--SET NOCOUNT ON

--BEGIN
--	CREATE TABLE #tTable(
--	Id bigint identity,
--	[SourceId] [bigint] NOT NULL,
--	[In_Out_Time] [datetime] NOT NULL,
--	[ShiftCode] [int] NOT NULL,
--	[Attn_Dt] [date] NOT NULL,
--	[Mode] [nvarchar](10) NOT NULL,
--	[CreatedDateTime] [datetime] NOT NULL,
--	[DeviceIP] [nvarchar](20) NOT NULL,
--	[EntryMode] [tinyint] NOT NULL,
--	[PunchId] [nvarchar](50) NOT NULL,
--	[TransactionId] [bigint] NOT NULL,
--	[SourceTypeId] [smallint] NULL,
--	[IsProcessed] [bit] NULL
--)

--DECLARE @lPrevAttn_Dt date = ''
--DECLARE @lPrevSourceId bigint = 0
--DECLARE @lPrevSourceTypeId smallint = 0

--IF(DAY(sCommon.fGetDate()) > 10)
--BEGIN
--	INSERT INTO #tTable
--	SELECT [SourceId],[In_Out_Time],[ShiftCode],[Attn_Dt] ,[Mode],[CreatedDateTime],[DeviceIP],[EntryMode],[PunchId],[TransactionId],[SourceTypeId],[IsProcessed] 
--	FROM [sBiometric].[tCloudTransactionData] WHERE MONTH(Attn_Dt) = MONTH(sCommon.fGetDate()) AND YEAR(Attn_Dt) = YEAR(sCommon.fGetDate()) AND IsProcessed = 0
--END
--ELSE
--BEGIN
--	INSERT INTO #tTable
--	SELECT [SourceId],[In_Out_Time],[ShiftCode],[Attn_Dt] ,[Mode],[CreatedDateTime],[DeviceIP],[EntryMode],[PunchId],[TransactionId],[SourceTypeId],[IsProcessed] 
--	 FROM [sBiometric].[tCloudTransactionData] WHERE YEAR(Attn_Dt) = YEAR(sCommon.fGetDate()) AND MONTH(Attn_Dt) IN (MONTH(sCommon.fGetDate()),MONTH(sCommon.fGetDate() - 1)) AND IsProcessed = 0
--END

--	SELECT * FROM #tTable
--	DECLARE @lCount int = 1
--	DECLARE @lTotal int = (SELECT COUNT(Id) FROM #tTable)
--	WHILE @lCount <= @lTotal
--	BEGIN
--		DECLARE @lQuery nvarchar(max) = ''	
--		DECLARE @lAttn_Dt date = (SELECT Attn_Dt FROM #tTable WHERE Id = @lCount)
--		DECLARE @lSourceId bigint = (SELECT SourceId FROM #tTable WHERE Id = @lCount)
--		DECLARE @lSourceTypeId smallint = (SELECT SourceTypeId FROM #tTable WHERE Id = @lCount)
--		DECLARE @lTransactionId bigint = (SELECT TransactionId FROM #tTable WHERE Id = @lCount)

--		IF(@lPrevAttn_Dt = @lAttn_Dt AND @lPrevSourceId = @lSourceId AND @lPrevSourceTypeId = @lSourceTypeId)
--		BEGIN
--			print('same employee')
--			UPDATE sBiometric.tCloudTransactionData SET IsProcessed = 1 WHERE TransactionId = @lTransactionId
--		END
--		ELSE
--		BEGIN
--			DECLARE @lCode int = (SELECT ISNULL(MAX(EmpCode),0) + 1 FROM sBiometric.tMonthTrans)
--			IF EXISTS (SELECT 1 FROM sBiometric.tMonthTrans WHERE EmployeeId = @lSourceId AND SourceTypeId = @lSourceTypeId)
--			BEGIN
--				SET @lCode = (SELECT TOP 1 EmpCode FROM sBiometric.tMonthTrans WHERE EmployeeId = @lSourceId AND SourceTypeId = @lSourceTypeId)
--			END					
--			DECLARE @lShift varchar(25) = (SELECT ShiftName FROM sBiometric.tShiftMasterCloud WHERE ShiftCode IN (SELECT ShiftCode FROM #tTable WHERE Id = @lCount))
--			DECLARE @lShiftStartTime datetime = (SELECT StartTime FROM sBiometric.tShiftMasterCloud WHERE ShiftCode IN (SELECT ShiftCode FROM #tTable WHERE Id = @lCount))
--			DECLARE @lShiftEndTime datetime = (SELECT EndTime FROM sBiometric.tShiftMasterCloud WHERE ShiftCode IN (SELECT ShiftCode FROM #tTable WHERE Id = @lCount))
--			DECLARE @lMinHoursHalfDay time = CAST(CAST((SELECT MinHrsHalfDay FROM sBiometric.tShiftMasterCloud WHERE ShiftCode IN (SELECT ShiftCode FROM #tTable WHERE Id = @lCount)) AS nvarchar) AS time)
--			DECLARE @lMinHoursFullDay time = CAST(CAST((SELECT MinHrsFullDay FROM sBiometric.tShiftMasterCloud WHERE ShiftCode IN (SELECT ShiftCode FROM #tTable WHERE Id = @lCount)) AS nvarchar) AS time)
--			DECLARE @lIn time = CONVERT(time,(SELECT MIN(In_Out_Time) FROM sBiometric.tCloudTransactionData WHERE Attn_Dt = @lAttn_Dt AND SourceId = @lSourceId AND SourceTypeId = @lSourceTypeId))
--			DECLARE @lOut time = CASE WHEN (SELECT COUNT(In_Out_Time) FROM sBiometric.tCloudTransactionData WHERE Attn_Dt = @lAttn_Dt AND SourceId = @lSourceId AND SourceTypeId = @lSourceTypeId) > 1 THEN CONVERT(time,(SELECT MAX(In_Out_Time) FROM #tTable WHERE Attn_Dt = @lAttn_Dt AND SourceId = @lSourceId AND SourceTypeId = @lSourceTypeId))
--									ELSE '00:00' END

--			DECLARE @lTotalTime varchar(10) = CASE WHEN @lOut <> '00:00' THEN (SELECT CONVERT(varchar(10), DATEADD(minute, DATEDIFF(minute, @lIn, @lOut), 0), 114))	
--												ELSE '00:00' END

--			DECLARE @lEarlyBy varchar(10) = '00:00'
--			DECLARE @lLateBy varchar(10) = '00:00'
--			DECLARE @lOverTime varchar(10) = ''
--			DECLARE @lStatus varchar(10) = ''

--			--Add by Nimesh MantisId:0027752
--			--Start
--			IF(DATEDIFF(minute, @lShiftStartTime,@lIn) > 0 AND @lIn<>'00:00')
--			BEGIN
--				--SET @lLateBy = '00:00'
--				SET @lLateBy = (SELECT CONVERT(varchar(10), DATEADD(minute, DATEDIFF(minute, @lShiftStartTime, @lIn), 0), 114))
--			END
--			IF(DATEDIFF(minute,@lShiftEndTime, @lOut) < 0 AND @lOut<> '00:00')
--			BEGIN
--				--SET @lEarlyBy = '00:00'
--				SET @lEarlyBy = (SELECT CONVERT(varchar(10), DATEADD(minute, DATEDIFF(minute, @lOut, @lShiftEndTime), 0), 114))
--			END
--			--End

--			IF(DATEDIFF(minute, @lShiftEndTime,@lOut) < 0)
--			BEGIN
--				SET @lOverTime = '00:00'
--			END
--			ELSE
--			BEGIN
--				SET @lOverTime  = CASE WHEN @lOut <> '00:00' THEN (SELECT CONVERT(varchar(10), DATEADD(minute, DATEDIFF(minute, @lShiftEndTime, @lOut), 0), 114))
--												ELSE '00:00' END
--			END			

--			IF(CAST(@lTotalTime AS TIME) >= @lMinHoursFullDay)
--			BEGIN
--				SET @lStatus = 'P'
--			END
--			IF(CAST(@lTotalTime AS TIME) >= @lMinHoursHalfDay AND CAST(@lTotalTime AS TIME) < @lMinHoursFullDay)
--			BEGIN
--				SET @lStatus = 'HD'
--			END
--			IF(CAST(@lTotalTime AS TIME) < @lMinHoursHalfDay)
--			BEGIN
--				SET @lStatus = 'LH'
--			END
--			IF (@lOut = '00:00' AND @lIn <> '00:00')
--			BEGIN
--				SET @lStatus = 'E'
--			END		
			
--			 --Uncomment this for testing purposes
--			--PRINT('In Time: ' + CONVERT(VARCHAR(5),@lIn,108))
--			--PRINT('Out Time: ' + CONVERT(VARCHAR(5),@lOut,108))
--			--PRINT('Total Time : ' + CONVERT(VARCHAR(5),@lTotalTime,108))
--			--PRINT('Overtime : ' + CONVERT(VARCHAR(5),@lOverTime,108))
--			--PRINT('Min Hours Half Day : ' + CONVERT(VARCHAR(5),@lMinHoursHalfDay,108))
--			--PRINT('Min Hours Full Day : ' + CONVERT(VARCHAR(5),@lMinHoursFullDay,108))
--			--PRINT('EarlyBy : ' + CONVERT(VARCHAR(5),@lEarlyBy,108))
--			--PRINT('LateBy : ' + CONVERT(VARCHAR(5),@lLateBy,108))
--			--PRINT('Status : ' + CONVERT(VARCHAR(5),@lStatus,108))
--			--BREAK


--			DECLARE @lDay nvarchar(10) = (SELECT DAY(IN_Out_Time) FROM #tTable WHERE Id = @lCount)
--			SET @lDay = (SELECT CASE WHEN @lDay BETWEEN 0 AND 9 THEN RIGHT('0' + CAST(@lDay AS VARCHAR(2)), 2) ELSE CAST(@lDay AS NVARCHAR(10)) END)
--			DECLARE @lMonthTransAttn_DtTemp datetime = (select cast((cast(YEAR(@lAttn_Dt) as varchar(255)) + '-' + cast(MONTH(@lAttn_Dt) as varchar(255)) + '-' + '01') as datetime))

--			DECLARE @lMonthTransAttn_Dt varchar(20) = convert(varchar(20), @lMonthTransAttn_DtTemp, 20)
--			PRINT(@lMonthTransAttn_Dt)

--			IF NOT EXISTS(SELECT 1 FROM sBiometric.tMonthTrans WHERE EmployeeId = @lSourceId AND SourceTypeId = @lSourceTypeId AND Attn_Dt = @lMonthTransAttn_Dt)
--			BEGIN
--				--Insert 
--				INSERT INTO sBiometric.tMonthTrans(EmpCode,EmployeeId,Attn_Dt,
--				D01,D02,D03,D04,D05,D06,D07,D08,D09,D10,D11,D12,D13,D14,D15,D16,D17,D18,D19,D20,D21,D22,D23,D24,D25,D26,D27,D28,D29,D30,D31,
--				D01_IN,D02_IN,D03_IN,D04_IN,D05_IN,D06_IN,D07_IN,D08_IN,D09_IN,D10_IN,D11_IN,D12_IN,D13_IN,D14_IN,D15_IN,D16_IN,D17_IN,D18_IN,D19_IN,D20_IN,D21_IN,D22_IN,D23_IN,D24_IN,D25_IN,D26_IN,D27_IN,D28_IN,D29_IN,D30_IN,D31_IN,
--				D01_OUT,D02_OUT,D03_OUT,D04_OUT,D05_OUT,D06_OUT,D07_OUT,D08_OUT,D09_OUT,D10_OUT,D11_OUT,D12_OUT,D13_OUT,D14_OUT,D15_OUT,D16_OUT,D17_OUT,D18_OUT,D19_OUT,D20_OUT,D21_OUT,D22_OUT,D23_OUT,D24_OUT,D25_OUT,D26_OUT,D27_OUT,D28_OUT,D29_OUT,D30_OUT,D31_OUT,
--				D01_O,D02_O,D03_O,D04_O,D05_O,D06_O,D07_O,D08_O,D09_O,D10_O,D11_O,D12_O,D13_O,D14_O,D15_O,D16_O,D17_O,D18_O,D19_O,D20_O,D21_O,D22_O,D23_O,D24_O,D25_O,D26_O,D27_O,D28_O,D29_O,D30_O,D31_O,
--				D01_L,D02_L,D03_L,D04_L,D05_L,D06_L,D07_L,D08_L,D09_L,D10_L,D11_L,D12_L,D13_L,D14_L,D15_L,D16_L,D17_L,D18_L,D19_L,D20_L,D21_L,D22_L,D23_L,D24_L,D25_L,D26_L,D27_L,D28_L,D29_L,D30_L,D31_L,
--				D01_T,D02_T,D03_T,D04_T,D05_T,D06_T,D07_T,D08_T,D09_T,D10_T,D11_T,D12_T,D13_T,D14_T,D15_T,D16_T,D17_T,D18_T,D19_T,D20_T,D21_T,D22_T,D23_T,D24_T,D25_T,D26_T,D27_T,D28_T,D29_T,D30_T,D31_T,
--				D01_S,D02_S,D03_S,D04_S,D05_S,D06_S,D07_S,D08_S,D09_S,D10_S,D11_S,D12_S,D13_S,D14_S,D15_S,D16_S,D17_S,D18_S,D19_S,D20_S,D21_S,D22_S,D23_S,D24_S,D25_S,D26_S,D27_S,D28_S,D29_S,D30_S,D31_S,
--				D01_E,D02_E,D03_E,D04_E,D05_E,D06_E,D07_E,D08_E,D09_E,D10_E,D11_E,D12_E,D13_E,D14_E,D15_E,D16_E,D17_E,D18_E,D19_E,D20_E,D21_E,D22_E,D23_E,D24_E,D25_E,D26_E,D27_E,D28_E,D29_E,D30_E,D31_E,
--				[Tot_Attn],[Tot_Abs],[Tot_WeekOFF],[Tot_Holiday],[TotalHour],[Tot_HD],[Tot_Early],[Tot_Late],[Tot_OT],[Tot_OD],[Tot_Leave],[Count_Late],[Count_Early],[Count_OT],Tot_CL,Tot_SL,Tot_EL,Tot_SP,Tot_C,Tot_PL,Tot_ML,SourceTypeId
--				) 
--				VALUES(@lCode,@lSourceId,@lMonthTransAttn_Dt,
--				'XX','XX','XX','XX','XX','XX','XX','XX','XX','XX','XX','XX','XX','XX','XX','XX','XX','XX','XX','XX','XX','XX','XX','XX','XX','XX','XX','XX','XX','XX','XX',
--				'00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00',
--				'00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00',
--				'00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00',
--				'00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00',
--				'00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00',
--				'XX','XX','XX','XX','XX','XX','XX','XX','XX','XX','XX','XX','XX','XX','XX','XX','XX','XX','XX','XX','XX','XX','XX','XX','XX','XX','XX','XX','XX','XX','XX',
--				'00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00',
--				0,0,0,0,'',0,'','','',0,0,0,0,0,0,0,0,0,0,0,0,@lSourceTypeId)
--			END
--			 --Update
--			SET @lQuery = 'UPDATE sBiometric.tMonthTrans
--			SET D'+CAST(@lDay AS VARCHAR)+'_IN = '''+CONVERT(VARCHAR(5),@lIn,108)+''',
--			D'+CAST(@lDay AS VARCHAR)+'_OUT = '''+CONVERT(VARCHAR(5),@lOut,108)+''',
--			D'+CAST(@lDay AS VARCHAR)+'_E = '''+CONVERT(VARCHAR(5),@lEarlyBy,108)+''',
--			D'+CAST(@lDay AS VARCHAR)+'_L = '''+CONVERT(VARCHAR(5),@lLateBy,108)+''',
--			D'+CAST(@lDay AS VARCHAR)+'_O = '''+CONVERT(VARCHAR(5),@lOverTime,108)+''',
--			D'+CAST(@lDay AS VARCHAR)+'_T = '''+CONVERT(VARCHAR(5),@lTotalTime,108)+''',
--			D'+CAST(@lDay AS VARCHAR)+' = '''+CONVERT(VARCHAR(5),@lStatus,108)+''',
--			D'+CAST(@lDay AS VARCHAR)+'_S = '''+CAST(@lShift AS VARCHAR)+'''
--			WHERE EmployeeId = '+CAST(@lSourceId AS VARCHAR) + ' AND Attn_Dt = ''' + CAST(@lMonthTransAttn_Dt AS VARCHAR) + ''' AND SourceTypeId = '+CAST(@lSourceTypeId AS VARCHAR)

--			PRINT ('Query : '+ @lQuery)

--			EXEC (@lQuery)			
			
			 
--			CREATE TABLE #tSummary (PresentStatus varchar(10), PresentStatusCount int)
--			INSERT INTO #tSummary
--			SELECT [Status],COUNT(*)
--			AS [Count] FROM (
--				SELECT D01,D02,D03,D04,D05,D06,D07,D08,D09,D10,D11,D12,D13,D14,D15,D16,D17,D18,D19,D20,D21,D22,D23,D24,D25,D26,D27,D28,D29,D30,D31
--				FROM sBiometric.tMonthTrans WHERE EmployeeId = @lSourceId AND CAST(Attn_Dt AS DATE) = @lMonthTransAttn_Dt AND SourceTypeId = @lSourceTypeId ) as Temp
--				UNPIVOT
--				(
--					[Status]   
--				   for [Dd] in (D01,D02,D03,D04,D05,D06,D07,D08,D09,D10,D11,D12,D13,D14,D15,D16,D17,D18,D19,D20,D21,D22,D23,D24,D25,D26,D27,D28,D29,D30,D31)
--				) as [unpivoted] 	
--				GROUP BY
--					[Status]
--				HAVING 
--					COUNT(*) > 0
			
--			--SELECT * FROM #tSummary
--			--BREAK

--			DECLARE @lTotal_HalfDay int = (SELECT ISNULL(SUM(PresentStatusCount),0) FROM #tSummary WHERE PresentStatus IN ('HD'))
--			DECLARE @lTotal_Present float = (SELECT ISNULL(SUM(PresentStatusCount),0) FROM #tSummary WHERE PresentStatus IN ('P')) + @lTotal_HalfDay*0.5
--			DECLARE @lTotal_Absent float = (SELECT ISNULL(SUM(PresentStatusCount),0) FROM #tSummary WHERE PresentStatus IN ('A','XX','LH')) + @lTotal_HalfDay*0.5
--			DECLARE @lTotal_WeekOff int = (SELECT ISNULL(SUM(PresentStatusCount),0) FROM #tSummary WHERE PresentStatus IN ('W','PW'))
--			DECLARE @lTotal_Holiday int = (SELECT ISNULL(SUM(PresentStatusCount),0) FROM #tSummary WHERE PresentStatus IN ('H','PH'))

--			DECLARE @lTotal_Hours varchar(50) = (SELECT CAST(t.time_sum/3600 AS VARCHAR(10)) + ':'
--													 + CAST(t.time_sum%3600/60 AS VARCHAR(10)) 
--												FROM
--												(
--													SELECT SUM(DATEDIFF(S, '00:00', [Status])) AS time_sum FROM (
--													SELECT D01_T,D02_T,D03_T,D04_T,D05_T,D06_T,D07_T,D08_T,D09_T,D10_T,D11_T,D12_T,D13_T,D14_T,D15_T,D16_T,D17_T,D18_T,D19_T,D20_T,D21_T,D22_T,D23_T,D24_T,D25_T,D26_T,D27_T,D28_T,D29_T,D30_T,D31_T				
--													FROM sBiometric.tMonthTrans WHERE EmployeeId = @lSourceId AND CAST(Attn_Dt AS DATE) = @lMonthTransAttn_Dt AND SourceTypeId = @lSourceTypeId) as Temp
--													UNPIVOT
--													(
--														[Status]   
--														for [Dd] in (D01_T,D02_T,D03_T,D04_T,D05_T,D06_T,D07_T,D08_T,D09_T,D10_T,D11_T,D12_T,D13_T,D14_T,D15_T,D16_T,D17_T,D18_T,D19_T,D20_T,D21_T,D22_T,D23_T,D24_T,D25_T,D26_T,D27_T,D28_T,D29_T,D30_T,D31_T)
--													) as [unpivoted]				
--												) t)

--			DECLARE @lTotal_Early varchar(50) = (SELECT CAST(t.time_sum/3600 AS VARCHAR(10)) + ':'
--													 + CAST(t.time_sum%3600/60 AS VARCHAR(10)) 
--												FROM
--												(
--													SELECT SUM(DATEDIFF(S, '00:00', [Status])) AS time_sum FROM (
--													SELECT D01_E,D02_E,D03_E,D04_E,D05_E,D06_E,D07_E,D08_E,D09_E,D10_E,D11_E,D12_E,D13_E,D14_E,D15_E,D16_E,D17_E,D18_E,D19_E,D20_E,D21_E,D22_E,D23_E,D24_E,D25_E,D26_E,D27_E,D28_E,D29_E,D30_E,D31_E				
--													FROM sBiometric.tMonthTrans WHERE EmployeeId = @lSourceId AND CAST(Attn_Dt AS DATE) = @lMonthTransAttn_Dt AND SourceTypeId = @lSourceTypeId) as Temp
--													UNPIVOT
--													(
--														[Status]   
--														for [Dd] in (D01_E,D02_E,D03_E,D04_E,D05_E,D06_E,D07_E,D08_E,D09_E,D10_E,D11_E,D12_E,D13_E,D14_E,D15_E,D16_E,D17_E,D18_E,D19_E,D20_E,D21_E,D22_E,D23_E,D24_E,D25_E,D26_E,D27_E,D28_E,D29_E,D30_E,D31_E)
--													) as [unpivoted]				
--												) t)

--			DECLARE @lTotal_Late varchar(50) = (SELECT CAST(t.time_sum/3600 AS VARCHAR(10)) + ':'
--													 + CAST(t.time_sum%3600/60 AS VARCHAR(10)) 
--												FROM
--												(
--													SELECT SUM(DATEDIFF(S, '00:00', [Status])) AS time_sum FROM (
--													SELECT D01_L,D02_L,D03_L,D04_L,D05_L,D06_L,D07_L,D08_L,D09_L,D10_L,D11_L,D12_L,D13_L,D14_L,D15_L,D16_L,D17_L,D18_L,D19_L,D20_L,D21_L,D22_L,D23_L,D24_L,D25_L,D26_L,D27_L,D28_L,D29_L,D30_L,D31_L				
--													FROM sBiometric.tMonthTrans WHERE EmployeeId = @lSourceId AND CAST(Attn_Dt AS DATE) = @lMonthTransAttn_Dt AND SourceTypeId = @lSourceTypeId) as Temp
--													UNPIVOT
--													(
--														[Status]   
--														for [Dd] in (D01_L,D02_L,D03_L,D04_L,D05_L,D06_L,D07_L,D08_L,D09_L,D10_L,D11_L,D12_L,D13_L,D14_L,D15_L,D16_L,D17_L,D18_L,D19_L,D20_L,D21_L,D22_L,D23_L,D24_L,D25_L,D26_L,D27_L,D28_L,D29_L,D30_L,D31_L)
--													) as [unpivoted]				
--												) t)

--			DECLARE @lTotal_OverTime varchar(50) = (SELECT CAST(t.time_sum/3600 AS VARCHAR(10)) + ':'
--													 + CAST(t.time_sum%3600/60 AS VARCHAR(10)) 
--												FROM
--												(
--													SELECT SUM(DATEDIFF(S, '00:00', [Status])) AS time_sum FROM (
--													SELECT D01_O,D02_O,D03_O,D04_O,D05_O,D06_O,D07_O,D08_O,D09_O,D10_O,D11_O,D12_O,D13_O,D14_O,D15_O,D16_O,D17_O,D18_O,D19_O,D20_O,D21_O,D22_O,D23_O,D24_O,D25_O,D26_O,D27_O,D28_O,D29_O,D30_O,D31_O				
--													FROM sBiometric.tMonthTrans WHERE EmployeeId = @lSourceId AND CAST(Attn_Dt AS DATE) = @lMonthTransAttn_Dt AND SourceTypeId = @lSourceTypeId) as Temp
--													UNPIVOT
--													(
--														[Status]   
--														for [Dd] in (D01_O,D02_O,D03_O,D04_O,D05_O,D06_O,D07_O,D08_O,D09_O,D10_O,D11_O,D12_O,D13_O,D14_O,D15_O,D16_O,D17_O,D18_O,D19_O,D20_O,D21_O,D22_O,D23_O,D24_O,D25_O,D26_O,D27_O,D28_O,D29_O,D30_O,D31_O)
--													) as [unpivoted]				
--												) t)

--			UPDATE sBiometric.tMonthTrans SET [Tot_Attn] = @lTotal_Present,[Tot_Abs] = @lTotal_Absent,[Tot_WeekOFF] = @lTotal_WeekOff,
--			[Tot_Holiday] = @lTotal_Holiday,[TotalHour] = @lTotal_Hours,[Tot_HD] = @lTotal_HalfDay,[Tot_Early] = @lTotal_Early,[Tot_Late] = @lTotal_Late,
--			[Tot_OT] = @lTotal_OverTime
--			WHERE EmployeeId = @lSourceId AND CAST(Attn_Dt AS DATE) = @lMonthTransAttn_Dt AND SourceTypeId = @lSourceTypeId			
			
--			UPDATE sBiometric.tCloudTransactionData SET IsProcessed = 1 WHERE TransactionId = @lTransactionId

--			DROP TABLE #tSummary

--		END
			
--		SET @lPrevAttn_Dt = @lAttn_Dt
--		SET @lPrevSourceId = @lSourceId
--		SET @lPrevSourceTypeId = @lSourceTypeId
		

--		SET @lCount = @lCount + 1
--	END
--END
--GO
PRINT N'Altering Procedure [sCommunication].[pMyUpdateGet]...';


GO


--------------------
ALTER PROCEDURE [sCommunication].[pMyUpdateGet]  
@rOrgId int,    
@rBatchId int,  
@rOrgGroupBatchId int,  
@rUserId bigint,  
@rUserSourceId bigint,  
@rUserSourceTypeId int,  
@rSyncedAssignmentId bigint,  
@rSyncedCircularId bigint,  
@rSyncedPollId bigint,  
@rSyncedQueryCommentId bigint,  
@rSyncedNewsId bigint,  
@rSyncedBlogId bigint,  
@rSyncedBehaviourId bigint,  
@rSyncedActivityId bigint,  
@rSyncedResultId bigint,  
@rSyncedAssignTaskId bigint,  
@rSyncedPhotoCategoryId int,  
@rVersionNumber nvarchar(Max)='',  
@rDeviceToken nvarchar(200)='',  
@rOSTypeId smallint = 0,
@rAppVersion nvarchar(20)='',
@rAppName nvarchar(100)=''

 WITH EXECUTE AS CALLER  
AS  
SET NOCOUNT ON  
      
BEGIN   
 DECLARE @lAcademicId bigint,  
  @lScopeSourceId int,  
  @lScopeSourceTypeId int,  
  @lStudentId bigint,  
  @lClassId int,  
  @lDivisionId int,  
  @lOrgId int,  
  @lDepartmentId int,  
  @lAssignmentStatus bit=0,  
  @lCircularStatus bit=0,  
  @lPollStatus bit=0,  
  @lQueryStatus bit=0,  
  @lBlogStatus bit=0,  
  @lNewsStatus bit=0,  
  @lBehaviourStatus bit=0,  
  @lActivityStatus bit=0,  
  @lResultStatus bit=0,  
  @lAssignTaskStatus bit=0,  
  @lPhotoCategoryStatus bit=0,  
  @lIsActive bit=0,  
  @lIsOptimizeAppImageUpload bit=0  
  
IF( @rUserSourceTypeId = 2003)   
BEGIN  
  SELECT @lAcademicId = A.Id,@lStudentId = A.StudentId,@lClassId = A.ClassId, @lDivisionId = A.DivisionId, @lOrgId= A.OrgId, @lDepartmentId=CM.DepartmentId  
  FROM sStudent.tAcademic A INNER JOIN sSetup.tBatchMaster BM  
 ON A.BatchId = BM.Id AND BM.IsActive = 1   
 INNER JOIN sSetup.tClassMaster CM ON CM.Id = A.ClassId  
 WHERE StudentId = @rUserSourceId AND BM.OrgGroupBatchId = @rOrgGroupBatchId  
--SELECT @lAcademicId = Id, @lScopeSourceId = DivisionId FROM sStudent.tAcademic WHERE StudentId = @rUserSourceId AND BatchId = @rBatchId  
SET @lScopeSourceId = @lDivisionId  
SET @lScopeSourceTypeId = 2005  
END  
ELSE  
BEGIN  
 SELECT @lDepartmentId=EJD.OrganizationDepartmentId,@lOrgId = EM.OrgId  FROM sHrm.tEmployeeMaster EM INNER JOIN sHrm.tEmployeeJobDetail EJD  
    ON EJD.EmployeeId = EM.Id WHERE EM.Id=@rUserSourceId AND ISNULL(EM.IsOtherUser,0) = 0  
--SELECT @lScopeSourceId = OrganizationDepartmentId FROM sHrm.tEmployeeJobDetail WHERE EmployeeId = @rUserSourceId  
SET @lScopeSourceId = @lDepartmentId  
SET @lScopeSourceTypeId = 2004  
END  
--IF EXISTS(SELECT 1 FROM sCommunication.tAssignmentScope ASO INNER JOIN  sCommunication.tAssignment A  
-- ON A.Id = ASO.AssignmentId  
--WHERE ASO.AssignmentId > @rSyncedAssignmentId AND ASO.SourceTypeId = @lScopeSourceTypeId AND ASO.SourceId = @lScopeSourceId AND A.BatchId=@rBatchId)  
--SET @lAssignmentStatus = 1  
  
  
--IF( @rUserSourceTypeId = 2003)   
--BEGIN  
  
--    IF EXISTS(SELECT 1 FROM sCommunication.tCircular C INNER JOIN (SELECT CS.CircularId FROM sCommunication.tCircularScope CS WHERE  
--      ((CS.SourceTypeId = 2021 AND CS.SourceId =@lOrgId)   
--      OR (CS.SourceTypeId = 2004 AND CS.SourceId =@lDepartmentId)  
--      OR (CS.SourceTypeId = 2016 AND CS.SourceId =@lClassId)  
--      OR (CS.SourceTypeId = 2005 AND CS.SourceId =@lDivisionId)  
--      OR (CS.SourceTypeId = 2003 AND CS.SourceId =@lStudentId)  
--      OR (CS.SourceTypeId = 2001 AND CS.SourceId =@lAcademicId)  
--      )  
--       AND (CS.CircularId > @rSyncedCircularId OR @rSyncedCircularId = 0)) D ON D.CircularId= C.Id  
--      --INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=C.OrgGroupBatchId AND OGBM.Id=@rOrgGroupBatchId  
--        WHERE ( c.Id > @rSyncedCircularId OR @rSyncedCircularId = 0)  
--        AND C.AssigneeId IN (1,2) AND C.OrgGroupBatchId=@rOrgGroupBatchId)   
--      SET @lCircularStatus = 1  
  
--END   
--ELSE  
--BEGIN  
-- IF EXISTS(SELECT 1 FROM sCommunication.tCircular C INNER JOIN (SELECT CS.CircularId FROM sCommunication.tCircularScope CS  
--       WHERE ((CS.SourceTypeId = 2021 AND CS.SourceId =@lOrgId) OR (CS.SourceTypeId = 2004 AND CS.SourceId =@lDepartmentId))  
--       AND (CS.CircularId > @rSyncedCircularId OR @rSyncedCircularId = 0)) D ON D.CircularId= C.Id  
--       --INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=C.OrgGroupBatchId AND OGBM.Id=@rOrgGroupBatchId  
--       WHERE ( c.Id > @rSyncedCircularId OR @rSyncedCircularId = 0)  
--       AND C.AssigneeId IN (1,3) AND C.OrgGroupBatchId=@rOrgGroupBatchId)   
--     SET @lCircularStatus = 1         
  
--END  
--IF EXISTS(SELECT 1 FROM sCommunication.tCircularScope WHERE  CircularId > @rSyncedCircularId AND SourceTypeId = @lScopeSourceTypeId AND SourceId = @lScopeSourceId)  
--SET @lCircularStatus = 1  
  
--IF EXISTS(SELECT 1 FROM sCommunication.tPoll P INNER JOIN sCommunication.tPollMember PM ON P.Id=PM.PollId  
-- WHERE PM.PollId > @rSyncedPollId AND PM.SourceTypeId = @lScopeSourceTypeId AND PM.SourceId = @lScopeSourceId AND P.OrgGroupBatchId=@rOrgGroupBatchId)  
--SET @lPollStatus = 1  
  
--IF EXISTS(SELECT 1 FROM sCommunication.tBlogScope BS INNER JOIN sCommunication.tBlog B  
--ON B.Id = BS.BlogId  
--WHERE B.IsPublish = 1 AND BS.BlogId > @rSyncedBlogId AND BS.SourceTypeId = 2021 AND BS.SourceId = @rOrgId AND B.OrgGroupBatchId = @rOrgGroupBatchId)  
--SET @lBlogStatus = 1  
  
--IF EXISTS(SELECT 1 FROM  sCommunication.tNews N INNER JOIN sCommunication.tNewsScope NS ON N.Id=NS.NewsId   
--   WHERE NS.NewsId > @rSyncedNewsId AND NS.SourceTypeId = 2021 AND NS.SourceId = @rOrgId AND N.OrgGroupBatchId = @rOrgGroupBatchId)  
--SET @lNewsStatus = 1  
  
--IF EXISTS(SELECT 1 FROM sCommunication.tNewsScope WHERE NewsId > @rSyncedNewsId AND SourceTypeId = @rOrgId AND SourceId = 1016)  
--SET @lNewsStatus = 1  
  
--IF EXISTS(SELECT 1 FROM sCommunication.tUploadResult WHERE Id > @rSyncedResultId AND DivisionId = @lScopeSourceId AND BatchId=@rBatchId AND IsObsolete=0 )  
--SET @lResultStatus = 1  
  
--IF EXISTS(SELECT 1 FROM    
--sCommunication.tPhotoCategoryMaster PCM  
--INNER JOIN sCommunication.tPhotoCategoryScope PCO   
--ON PCM.Id=PCO.PhotoCategoryId WHERE PCM.Id > @rSyncedPhotoCategoryId AND LEFT(PCO.ScopeSourceId,4) = @rOrgId  AND PCM.IsObsolete=0 )  
--SET @lPhotoCategoryStatus = 1  
  
  
--IF EXISTS(SELECT 1 FROM sCommunication.tAssignTask WHERE  Id > @rSyncedAssignTaskId AND AssignedToSourceTypeId = @rUserSourceTypeId   
--AND AssignedToSourceId = @rUserSourceId AND IsCompleted=0 AND IsClosed=0 AND OrgId=@rOrgId)  
--SET @lAssignTaskStatus = 1  
  
  
--IF EXISTS(SELECT 1 FROM  sActivity.tActivity A INNER JOIN sActivity.tActivityParticipant AP ON A.Id=AP.ActivityId  
-- WHERE AP.ActivityId > @rSyncedActivityId AND AP.SourceTypeId = @rUserSourceTypeId AND AP.SourceId = @rUserSourceId AND A.BatchId=@rBatchId)  
--SET @lActivityStatus = 1  
  
--IF EXISTS(SELECT 1 FROM sCommunication.tBehaviour WHERE Id > @rSyncedBehaviourId AND AcademicId = @lAcademicId )  
--SET @lBehaviourStatus = 1  
  
--IF EXISTS(SELECT 1 FROM sCommunication.tQuery Q INNER JOIN sCommunication.tQueryComment QC ON Q.Id=QC.QueryId  
--WHERE Q.CreatedUserId=@rUserId AND Q.IsUserView=0 AND QC.Id>@rSyncedQueryCommentId AND QC.CreatedUserId <> @rUserSourceId AND Q.OrgGroupBatchId=@rOrgGroupBatchId)  
--SET @lQueryStatus = 1  
   
IF(@rUserSourceTypeId = 2003)  
BEGIN   
 DECLARE @lStatusId1 smallint=0  
  SELECT @lStatusId1 = StatusId FROM sStudent.tStudentMaster SM WHERE Id = @rUserSourceId  
 IF(@lStatusId1=1)  
 BEGIN   
  SET @lIsActive = 1  
 END ELSE  
 BEGIN  
  SET @lIsActive = 0  
 END  
END  
ELSE IF(@rUserSourceTypeId = 95)  
BEGIN   
 DECLARE @lStatusId2 smallint=0  
 SELECT @lStatusId2 = StatusId FROM sHrm.tEmployeeMaster EM WHERE Id = @rUserSourceId --AND ISNULL(EM.IsOtherUser,0) = 0  
 IF(@lStatusId2=7)  
 BEGIN   
  SET @lIsActive = 1  
 END ELSE  
 BEGIN  
  SET @lIsActive = 0  
 END  
END  
ELSE IF(@rUserSourceTypeId = 1)  
BEGIN   
 DECLARE @IsObsolete smallint=0 
 SELECT @IsObsolete=ISNULL(IsObsolete,0) FROM sSecurity.tUser WHERE Id = @rUserId  
 IF(@IsObsolete=0)  
 BEGIN   
  SET @lIsActive = 1  
 END   
 ELSE  
 BEGIN  
  SET @lIsActive = 0  
 END  
END  
  
IF(@lIsActive=1)  
BEGIN  
 DECLARE @lIsObsolete bit=0  
 SELECT @lIsObsolete=ISNULL(IsObsolete,0) FROM sSecurity.tUser WHERE Id = @rUserId  
  
 IF(@lIsObsolete=0)  
  SET @lIsActive = 1  
 ELSE  
  SET @lIsActive = 0  
END  
  
  
DECLARE @lOrgGroupId int=0  
SELECT @lOrgGroupId=OrgGroupId FROM sSetup.tOrganizationMaster WHERE Id =@rOrgId  
DECLARE @lOptimizeAppImageUpload nvarchar(50)  
SELECT @lOptimizeAppImageUpload = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 247 AND SourceTypeId = 2010 AND SourceId = @lOrgGroupId  
IF (@lOptimizeAppImageUpload IS NULL) OR (@lOptimizeAppImageUpload = 'False')  
 SET @lIsOptimizeAppImageUpload = 0  
ELSE  
 SET @lIsOptimizeAppImageUpload = 1   
   
DECLARE @lAlertRemark nvarchar(2000) = ''  
   
--IF(@rVersionNumber IS NULl OR @rVersionNumber='')  
--BEGIN  
-- DECLARE @lUserName nvarchar(100)=''  
-- DECLARE @lUserPassword nvarchar(100)=''  
-- DECLARE @lBatch nvarchar(100)=''  
-- SELECT @lBatch = Title  FROM sSetup.tBatchMaster WHERE Id = @rBatchId  
   
-- SELECT @lUserName=UserName,@lUserPassword=UserPassword FROM sSecurity.tTempUser WHERE UserId = @rUserId  
-- SET @lAlertRemark = 'Plese install the new app from this location (https://play.google.com/store/apps/details?id=com.vidyalaya.pinnacleschoolgandhinagarnew) Uninstall the old app. Login in new app with  
--       Registration Number : '+LEFT(@rOrgGroupBatchId,4) +'  
--       User Name : '+@lUserName+'  
--       Password : '+@lUserPassword+'  
--       Batch :' + @lBatch  
--END  
--ELSE   
BEGIN  
 SELECT @lAlertRemark=AlertRemark FROM sSetup.tOrgGroupConfiguration WHERE OrgGroupId = @lOrgGroupId  
END  
  
DECLARE @lMobileAppModuleAutoSyncToken nvarchar(50)  
SELECT @lMobileAppModuleAutoSyncToken = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 317 AND SourceTypeId = 2010 AND SourceId = @lOrgGroupId  
  
  
DECLARE @lIsStopApplicationAccess bit=0  
DECLARE @lStudentCustomAlert nvarchar(1000)=''  
IF(@rUserSourceTypeId=2003)  
SELECT @lIsStopApplicationAccess = ISNULL(IsStopApplicationAccess,0) ,@lStudentCustomAlert= ISNULL(StudentCustomAlert,'') FROM sStudent.tStudentCommunication WHERE StudentId = @rUserSourceId  
  
  
IF(LEN(@rDeviceToken) > 0)  
BEGIN   
 DECLARE @lDeviceToken nvarchar(200)=''  
 SELECT @lDeviceToken = DeviceToken FROM sCommunication.tRegisteredUsers WHERE OrgId=@rOrgId AND UserId=@rUserId AND UserSourceId=@rUserSourceId AND UserSourceTypeId = @rUserSourceTypeId AND OSTypeId = @rOSTypeId  
  
 DECLARE @lConfigValue nvarchar(50)=''  
 SELECT @lConfigValue = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 374 AND SourceTypeId = 2010 AND SourceId = @lOrgGroupId  
  
 IF @lConfigValue IS NULL   
 SET @lConfigValue = 'False'  
  
 IF @lConfigValue = 'True'  
 BEGIN  
 IF(@lDeviceToken!=@rDeviceToken)  
  SET @lIsActive=0  
 END  
 
 SET @lDeviceToken = (SELECT DeviceToken FROM sCommunication.tRegisteredUsers WHERE OrgId=@rOrgId AND UserId=@rUserId AND UserSourceId=@rUserSourceId AND UserSourceTypeId = @rUserSourceTypeId AND DeviceToken=@rDeviceToken)  	
 IF(@lDeviceToken IS NULL OR @lDeviceToken='' OR ISNULL(@lDeviceToken,'') = '')  
  SET @lIsActive=0  
END  
  
DECLARE @lActiceClassBatchId NVARCHAR(MAX) = '',@lBatchClassId int  
   
IF(@rUserSourceTypeId = 2003)  
BEGIN   
 SELECT @lBatchClassId = A.ClassId  
 FROM sStudent.tAcademic A INNER JOIN sSetup.tBatchMaster BM ON A.BatchId = BM.Id  
 INNER JOIN sSetup.tClassMaster CM ON CM.Id = A.ClassId  
 WHERE StudentId = @rUserSourceId AND BM.OrgGroupBatchId = @rOrgGroupBatchId  
  
 IF EXISTS(SELECT BatchId FROM [sSetup].[tBatchClass] BC INNER JOIN sSetup.tBatchMaster BM ON BM.Id = BC.BatchId WHERE ClassId = @lBatchClassId AND IsBatchClassActive = 1 AND BM.IsActive = 1)  
 BEGIN  
  SELECT @lActiceClassBatchId = CONVERT(NVARCHAR,BC.BatchId)+','+ BM.Title FROM [sSetup].[tBatchClass] BC INNER JOIN sSetup.tBatchMaster BM ON BM.Id = BC.BatchId WHERE BC.ClassId = @lBatchClassId AND BC.IsBatchClassActive = 1 AND BM.IsActive = 1  
 END  
 ELSE  
 BEGIN  
  SELECT @lActiceClassBatchId = CONVERT(NVARCHAR,Id) +','+ Title FROM sSetup.tBatchMaster WHERE Id = @rBatchId  
 END  
END  
ELSE IF(@rUserSourceTypeId = 95)  
BEGIN  
 SELECT @lActiceClassBatchId = CONVERT(NVARCHAR,Id) +','+ Title FROM sSetup.tBatchMaster WHERE Id = @rBatchId  
END  


IF(LEN(ISNULL(@rAppVersion,'')) > 0 AND LEN(ISNULL(@rAppVersion,'')) > 0)
BEGIN
	UPDATE sCommunication.tRegisteredUsers
	SET
		AppVersion = @rAppVersion,
		AppName = @rAppName,
		UpdatedDateTime = sCommon.fGetDate(),
		DeviceDetail = @rVersionNumber
	WHERE 
		DeviceToken = @rDeviceToken 
		AND OsTypeId = @rOSTypeId
		AND OrgId=@rOrgId AND UserId=@rUserId 
		AND UserSourceId=@rUserSourceId AND UserSourceTypeId = @rUserSourceTypeId
END
CREATE TABLE #Module (  
Id int,  
Title nvarchar(2000),  
IsNew bit )  
INSERT INTO #Module VALUES (1,'IsActiveCheck',CONVERT(bit,@lIsActive))  
INSERT INTO #Module VALUES (2,'IsOptimizeAppImageUpload',@lIsOptimizeAppImageUpload)  
INSERT INTO #Module VALUES (3,ISNULL(@lAlertRemark,''),1)  
INSERT INTO #Module VALUES (4,ISNULL(@lMobileAppModuleAutoSyncToken,0),1)  
INSERT INTO #Module VALUES (5,'Is Stop Application Access',@lIsStopApplicationAccess)  
INSERT INTO #Module VALUES (6,@lStudentCustomAlert,1)  
INSERT INTO #Module VALUES (20085,'Circular',0)  
INSERT INTO #Module VALUES (20088,'Query',0)  
INSERT INTO #Module VALUES (20099,'Blog',0)  
INSERT INTO #Module VALUES (20104,'News',0)  
INSERT INTO #Module VALUES (20172,'AssignTask',0)  
INSERT INTO #Module VALUES (20183,'Gallery',0)  
INSERT INTO #Module VALUES (20204,'Poll',0)  
INSERT INTO #Module VALUES (20093,'Assignment',0)  
INSERT INTO #Module VALUES (20209,'Activity',0)  
INSERT INTO #Module VALUES (20130,'Behaviour',0)  
INSERT INTO #Module VALUES (20180,'Result',0)  
INSERT INTO #Module VALUES (7,@lActiceClassBatchId,1)  
   
SELECT * FROM #Module  
   
--SELECT @lAssignmentStatus AS Assignment,@lCircularStatus AS Circular,@lPollStatus AS Poll,@lQueryStatus AS Query,  
--@lBlogStatus AS Blog,@lNewsStatus AS News,@lBehaviourStatus AS Behaviour,  
--@lActivityStatus AS Activity,@lResultStatus AS Result,@lAssignTaskStatus AS AssignTask,@lPhotoCategoryStatus AS Gallery  
  
END
GO
PRINT N'Altering Procedure [sFee].[pRptTransportFeePendingWithFeeNameGet]...';


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


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

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

			SELECT
			P.OrgId,			 
			P.ReceiptBookId,
			P.AcademicId,
			P.DivisionId,
			P.ClassDivision,P.RollNo, P.Name,P.Code,ReceiptBookTitle,OrgName,
			SUM(P.PendingAmount) AS PendingAmount, 
			[sFee].[fPendingFeeNamesGet](P.AcademicId,ReceiptBookId,	@p) AS PendingFeeName,
			P.ReceiptOrderIndex,
			BR.Id AS BusRouteId,
			BR.Title AS BusRoute,
			BD.Title AS BusDestination,
			isnull(SC.ParentContactNo,'') AS ParentContactNo,
			P.SUID,
			P.ClassOrderIndex,
			P.DivisionOrderIndex,
			'' AS FatherContactNo,
		    '' AS MotherContactNo
			
			FROM @p P INNER JOIN sStudent.vStudentAcademic VA ON p.AcademicId=VA.AcademicId
			INNER JOIN sTransport.tAssignRoute AR oN VA.StudentId = AR.SourceId AND SourceTypeId = 2003
			INNER JOIN sTransport.tBusRouteDestinationMaster BD ON BD.Id = AR.PickupDestinationId 
			INNER JOIN sTransport.tBusRouteMaster BR ON BR.Id = BD.BusRouteId 
			AND BR.OrgGroupBatchId = @rOrgGroupBatchId
			LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId =  VA.StudentId
			GROUP By P.ReceiptBookId,P.OrgId,P.AcademicId,P.DivisionId,
			P.ClassDivision,P.RollNo, P.Name,P.Code,
			P.ReceiptBookTitle,P.OrgName,P.ReceiptOrderIndex,BR.Title,BD.Title,BR.Id,SC.ParentContactNo	,P.SUID,P.ClassOrderIndex,P.DivisionOrderIndex
			ORDER BY P.AcademicId
 
END
GO
PRINT N'Altering Procedure [sFee].[pRptFeePendingAllBatchGet]...';


GO
ALTER PROCEDURE [sFee].[pRptFeePendingAllBatchGet]
		@rReportId int=0,
		@rReceiptBookId int=0,
		@rAdmissionCategoryId int=0,
		@rClassId int=0,
		@rDivisionId int=0,
		@rUptoDate date='',
		@rBatchId int='',
		@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) = '',
		@rFeeHeadId nvarchar(max) = '',
		@rIsDisplayOrgGroup bit=0,
		@rFeeId nvarchar(max) = '',
		@rFilterId  int=0,
		@rOrgGroupId int = 0,
		@rOrgIds nvarchar(max) = '',
		@rReportType int=1,    
	    @rClassStatusId int=0,
		@rClassIds nvarchar(max) = '',
		@rDivisionIds nvarchar(max) = ''

	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
BEGIN 	
	
	DECLARE @p as TempPendingFee

	IF(@rReportType=1)
	BEGIN
	
		INSERT INTO  @p 
	 
	SELECT 
	
		SA.AcademicId,
		SA.RollNo,
		SA.Name,
		SA.Code,
		SA.ClassId,
		SA.DivisionId,
		SA.ClassName,
		SA.DivisionName,
		SA.ClassName+' - '+SA.DivisionName AS ClassDivision,
		FS.Id AS FeeSetupId,		
		ISNULL(FS.IsVariable,0)AS IsVariable,
		ISNULL(FS.Amount,0)AS Amount,
		ISNULL(FS.StartDate,'1900-01-01')AS StartDate,
		ISNULL(FS.EndDate,'1900-01-01')AS EndDate,
		ISNULL(FA.VariableAmount,0.00)AS FAAmount,
		ISNULL(FA.DiscountAmount,0.00)AS DiscountAmount,
		ISNULL(FA.AdditionalAmount,0.00)AS AdditionalAmount,
		ISNULL(R.PaidAmount,0) AS PaidAmount,
		ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00)AS PendingAmount,
		ISNULL(FA.Remark,'') AS Remark,
		FS.ReceiptBookId,
		FS.FeeName,
		FS.FeeCode,
		SA.OrgId,
		O.Title AS OrgName,
		O.OrderIndex AS OrgOrderIndex,
		ISNULL(RBM.Title,'') AS ReceiptBookTitle,
		ISNULL(RBM.OrderIndex,0) AS ReceiptOrderIndex,
		SA.BatchId,
		BM.Title AS BatchName,
	    RT.Pickup  AS Pickup,
		RT.DRoppoint As DRoppoint,
		SC.PresentContactNo,
		ISNULL(SA.SUID,'') AS SUID,
		SA.ClassOrderIndex,
		SA.DivisionOrder,
		FS.OrderIndex,
		--change by megha for 0027384
	    '' AS FatherContactNo,
		'' AS MotherContactNo
  FROM 
  
			 sStudent.vStudentAcademic SA
			 Left join [sStudent].[tStudentCommunication] SC ON SC.studentId=SA.studentId
			
		INNER JOIN 
		(
			SELECT 
				FS1.FeeId,
				FS1.Id,
				ISNULL(FS1.IsOptional,0)AS IsOptional,
				ISNULL(FS1.IsVariable,0)AS IsVariable,
				ISNULL(FS1.Amount,0)AS Amount,
				ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
				ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
				FS1.BatchId,
				ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
				SA1.AcademicId,
				FM.Title AS FeeName,
				FM.Code AS FeeCode,
				FM.OrderIndex
			FROM sFee.tFeeSetup FS1
			INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId 
				AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId				
				AND ((SA1.ClassId=@rClassId) OR (@rClassId=0)) 
				AND (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
			WHERE 
				(CAST(LEFT(SA1.OrgGroupBatchId, 4) AS int) = @rOrgGroupId OR @rOrgGroupId=0)
			    AND ((SA1.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
				AND	((FS1.ClassId=@rClassId) OR (@rClassId=0))
				AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
				AND (FS1.IsOptional=0)
				AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
				AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND (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 ((SA1.Code=@rCode) OR (@rCode=''))
				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.AcademicId,
				FM.Title AS FeeName,
				FM.Code AS FeeCode,
				FM.OrderIndex
			FROM sFee.tFeeSetup FS1
		INNER JOIN sFee.tFeeOptional FO
			ON FO.FeeSetupId=FS1.Id
	    INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
		INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=FO.SourceId AND SA1.BatchId = FS1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
		AND SA1.ClassId = 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))
		WHERE
				(CAST(LEFT(SA1.OrgGroupBatchId, 4) AS int) = @rOrgGroupId OR @rOrgGroupId=0)
		        AND ((SA1.OrgGroupBatchId = @rOrgGroupBatchId)  OR (@rOrgGroupBatchId=0))
				AND ((FS1.ClassId=@rClassId) OR (@rClassId=0))
				AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
				AND (FS1.IsOptional=1)
				AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
				AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND (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 ((SA1.Code=@rCode) OR (@rCode=''))
				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='')
		) 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
				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='')
			WHERE	
				(CAST(LEFT(SA1.OrgGroupBatchId, 4) AS int) = @rOrgGroupId OR @rOrgGroupId=0)
				AND (R.SourceTypeId = 2001)
				AND ((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND (R.IsObsolete = 0) 
				AND ((SA1.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
				AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))
				AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
				AND (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 ((SA1.Code=@rCode) OR (@rCode=''))
		
				GROUP BY FeeSetupId,R.SourceId
		) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
		 INNER JOIN sSetup.tOrganizationMaster O ON
		 SA.OrgId = O.Id
		 INNER JOIN sFee.tReceiptBookMaster RBM 
			ON FS.ReceiptBookId=RBM.Id
		 INNER JOIN sSetup.tBatchMaster BM 
			ON BM.Id=SA.BatchId	
      LEFT JOIN sHostel.tAssignRoom AR ON  AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003 AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  AND ((AR.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0) AND (SA.OrgGroupBatchId = AR.OrgGroupBatchId)) 
        LEFT JOIN
	(SELECT AT.SourceId ,B.OrgGroupBatchId,B.Title As Pickup,B1.Title As DRoppoint 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))
	Left JOIN sTransport.tBusRouteDestinationMaster BM1 ON BM1.Id=AT.DropDestinationId
    LEFT JOIN sTransport.tBusRouteMaster B1 ON B1.Id=BM1.BusRouteId AND  AT.SourceTypeId=2003 AND ((B1.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))
 ) RT
    ON RT.SourceId = SA.StudentId 
    AND ((SA.OrgGroupBatchId = RT.OrgGroupBatchId))
    AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) 
	WHERE	
			(CAST(LEFT(SA.OrgGroupBatchId, 4) AS int) = @rOrgGroupId OR @rOrgGroupId=0)
			AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
			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 ((SA.ClassStatusId=@rClassStatusId) OR (@rClassStatusId=0))	   
			Order by SA.RollNo
 
		SELECT
			@rBuilder1 AS Builder1,
			@rIsDisplayOrgGroup AS IsDisplayOrgGroup,
			OrgId,			 
			ReceiptBookId,
			AcademicId,
			DivisionId,
			ClassDivision,
			RollNo, 
			Name,
			Code,
			ReceiptBookTitle,
			OrgName,
			SUM(PendingAmount) AS PendingAmount, 
			[sFee].[fPendingFeeNamesGet](AcademicId,ReceiptBookId,	@p) AS PendingFeeName,
			ReceiptOrderIndex,
			BatchId,
			BatchName,
		    Pickup,
			DRoppoint,
			PresentContactNo,
			SUID,
			ClassOrderIndex,
			DivisionOrderIndex,
			'' AS FatherContactNo,
		    '' AS MotherContactNo
			FROM @p 
			
			GROUP By 
			OrgId,AcademicId,ReceiptBookId,DivisionId,BatchId,
			ClassDivision,RollNo, Name,Code,ReceiptBookTitle,OrgName,ReceiptOrderIndex,BatchName,Pickup,DRoppoint,PresentContactNo,SUID,ClassOrderIndex,DivisionOrderIndex,FatherContactNo,MotherContactNo
			ORDER BY AcademicId Desc
	END
	ELSE
	BEGIN
	
	INSERT INTO  @p 
	SELECT 
	
		SA.AcademicId,
		SA.RollNo,
		SA.Name,
		SA.Code,
		SA.ClassId,
		SA.DivisionId,
		SA.ClassName,
		SA.DivisionName,
		SA.ClassName+' - '+SA.DivisionName AS ClassDivision,
		FS.Id AS FeeSetupId,		
		ISNULL(FS.IsVariable,0)AS IsVariable,
		ISNULL(FAS.FeeAmount,0)AS Amount,
		ISNULL(FS.StartDate,'1900-01-01')AS StartDate,
		ISNULL(FS.EndDate,'1900-01-01')AS EndDate,
		ISNULL(FAS.VariableAmount,0.00)AS FAAmount,
		ISNULL(FAS.DiscountAmount,0.00)AS DiscountAmount,
		ISNULL(FAS.AdditionalAmount,0.00)AS AdditionalAmount,
		ISNULL(FAS.PaidAmount,0) AS PaidAmount,
		ISNULL(FAS.ToPayAmount,0) AS PendingAmount,
		--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(FAS.Remark,'') AS Remark,
		FS.ReceiptBookId,
		--FS.FeeName,
		FM.Title AS FeeName, 
		FM.Code AS FeeCode,
		--FS.FeeCode,
		SA.OrgId,
		O.Title AS OrgName,
		O.OrderIndex AS OrgOrderIndex,
		ISNULL(RBM.Title,'') AS ReceiptBookTitle,
		ISNULL(RBM.OrderIndex,0) AS ReceiptOrderIndex,
		SA.BatchId,
		BM.Title AS BatchName,
	    RT.Pickup  AS Pickup,
		RT.DRoppoint As DRoppoint,
		SC.PresentContactNo,
		ISNULL(SA.SUID,'') AS SUID,
		SA.ClassOrderIndex,
		SA.DivisionOrder,
		FM.OrderIndex,
		'' AS FatherContactNo,
		'' AS MotherContactNo
  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 sStudent.tStudentCommunication SC	ON SC.StudentId = SA.StudentId 
		INNER JOIN sSetup.tBatchMaster BM ON BM.Id=SA.BatchId	
        LEFT JOIN sHostel.tAssignRoom AR ON  AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003 AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  AND ((AR.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0) AND (SA.OrgGroupBatchId = AR.OrgGroupBatchId)) 
        LEFT JOIN
		(SELECT AT.SourceId ,B.OrgGroupBatchId,B.Title As Pickup,B1.Title As DRoppoint 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))
	    Left JOIN sTransport.tBusRouteDestinationMaster BM1 ON BM1.Id=AT.DropDestinationId
        LEFT JOIN sTransport.tBusRouteMaster B1 ON B1.Id=BM1.BusRouteId AND  AT.SourceTypeId=2003 AND ((B1.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))
        ) RT
        ON RT.SourceId = SA.StudentId 
        AND ((SA.OrgGroupBatchId = RT.OrgGroupBatchId))
        AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) 
	   
	    WHERE	
			(CAST(LEFT(SA.OrgGroupBatchId, 4) AS int) = @rOrgGroupId OR @rOrgGroupId=0)
			AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
			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) !=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(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(SA.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')  
		   AND ((SA.ClassStatusId=@rClassStatusId) OR (@rClassStatusId=0))  
			Order by SA.RollNo

			
				SELECT
			@rBuilder1 AS Builder1,
			@rIsDisplayOrgGroup AS IsDisplayOrgGroup,
			OrgId,			 
			ReceiptBookId,
			AcademicId,
			DivisionId,
			ClassDivision,
			RollNo, 
			Name,
			Code,
			ReceiptBookTitle,
			OrgName,
			SUM(PendingAmount) AS PendingAmount, 
			[sFee].[fPendingFeeNamesGet](AcademicId,ReceiptBookId,	@p) AS PendingFeeName,
			ReceiptOrderIndex,
			BatchId,
			BatchName,
		    Pickup,
			DRoppoint,
			PresentContactNo,
			SUID,
			ClassOrderIndex,
			DivisionOrderIndex,
			'' AS FatherContactNo,
		    '' AS MotherContactNo
			FROM @p 
			
			GROUP By 
			OrgId,AcademicId,ReceiptBookId,DivisionId,BatchId,
			ClassDivision,RollNo, Name,Code,ReceiptBookTitle,OrgName,ReceiptOrderIndex,BatchName,Pickup,DRoppoint,PresentContactNo,SUID,ClassOrderIndex,
			DivisionOrderIndex
			
			ORDER BY AcademicId
	END
END
GO
PRINT N'Altering Procedure [sFee].[pRptFeePendingWithFeeNameGet]...';


GO

 
ALTER PROCEDURE [sFee].[pRptFeePendingWithFeeNameGet]
		@rReportId int=0,
		@rReceiptBookId int,
		@rAdmissionCategoryId int,
		@rClassId int,
		@rDivisionId int,
		@rUptoDate date,
		@rBatchId int,
		@rUserId bigint,
		@rBuilder1 nvarchar(max),
		@rBuilder2 nvarchar(max),
		@rIsDetail bit,
		@rOrgId int,
		@rOrgGroupBatchId int,
		@rStatusId int,
		@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) = '' ,
		@rReportType int=1,
		@rClassStatusId int=0,
		@rClassIds nvarchar(max) = '',
		@rDivisionIds nvarchar(max) = '',
		@rFromAmount decimal = 0.00,
		@rToAmount decimal = 0.00
	    
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
BEGIN 	

	IF(@rReportType=1)

		BEGIN

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

 
	--CREATE TYPE  TempPendingFee AS TABLE
	--(
	--AcademicId bigint
	--,
	--RollNo int,
	--Name nvarchar(200),
	--Code nvarchar(20),
	--ClassId int,
	--DivisionId int,
	--ClassName nvarchar(100),
	--DivisionName nvarchar(100),
	--ClassDivision nvarchar(100),
	--FeeSetupId int,
	--IsVariable int,
	--Amount Decimal(12,2),
	--StartDate date,
	--EndDate date,
	--FAAmount Decimal(12,2),
	--DiscountAmount Decimal(12,2),
	--AdditionalAmount Decimal(12,2),
	--PaidAmount Decimal(12,2),
	--PendingAmount Decimal(12,2),
	--Remark nvarchar(200),
	--ReceiptBookId int,
	--FeeName nvarchar(100),
	--FeeCode nvarchar(100),
	--OrgId int,
	--OrgName nvarchar(200),
	--OrgOrderIndex int,
	--ReceiptBookTitle nvarchar(200),
	--ReceiptOrderIndex int	
	--)
	
	DECLARE @p as TempPendingFee
	INSERT INTO  @p 
	 
	SELECT 
		--@rBuilder1 AS Builder1,
		--@rBuilder2 AS Builder2,
		--@rIsDetail AS IsDetail,
		--@rIsFilter As IsFilter,
		--@rIsHeader As IsHeader,
		SA.AcademicId		,
		SA.RollNo,
		SA.Name,
		SA.Code,
		SA.ClassId,
		SA.DivisionId,
		SA.ClassName,
		SA.DivisionName,
		SA.ClassName+' - '+SA.DivisionName AS ClassDivision,
		FS.Id AS FeeSetupId,		
		ISNULL(FS.IsVariable,0)AS IsVariable,
		ISNULL(FS.Amount,0)AS Amount,
		ISNULL(FS.StartDate,'1900-01-01')AS StartDate,
		ISNULL(FS.EndDate,'1900-01-01')AS EndDate,
		ISNULL(FA.VariableAmount,0.00)AS FAAmount,
		ISNULL(FA.DiscountAmount,0.00)AS DiscountAmount,
		ISNULL(FA.AdditionalAmount,0.00)AS AdditionalAmount,
		ISNULL(R.PaidAmount,0) AS PaidAmount,
		ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00)AS PendingAmount,
		ISNULL(FA.Remark,'') AS Remark,
		FS.ReceiptBookId,
		FS.FeeName,
		FS.FeeCode,
		SA.OrgId,
		O.Title AS OrgName,
		O.OrderIndex AS OrgOrderIndex,
		ISNULL(RBM.Title,'') AS ReceiptBookTitle,
		ISNULL(RBM.OrderIndex,0) AS ReceiptOrderIndex,
		0 AS BatchId,
		'' AS BatchName,
		ISNULL(SC.ParentContactNo,'') AS ParentContactNo,
		ISNULL(SC.StudentContactNo,'') AS StudentContactNo,
		'',
		ISNULL(SA.SUID,'') AS SUID,
		SA.ClassOrderIndex,
		SA.DivisionOrder,
		FS.FeeOrderIndex,
		--change by megha for 0027384
	    ISNULL(SF.FatherContactNo,'')AS FatherContactNo,
		ISNULL(SF.MotherContactNo,'')AS MotherContactNo
			
  FROM 
  
			 sStudent.vStudentAcademic SA
		INNER JOIN 
		(
			SELECT 
				FS1.FeeId,
				FS1.Id,
				ISNULL(FS1.IsOptional,0)AS IsOptional,
				ISNULL(FS1.IsVariable,0)AS IsVariable,
				ISNULL(FS1.Amount,0)AS Amount,
				ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
				ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
				FS1.BatchId,
				ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
				SA1.AcademicId,
				FM.Title AS FeeName,
				FM.Code AS FeeCode,
				FM.OrderIndex AS FeeOrderIndex
			FROM sFee.tFeeSetup FS1
			INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId 
				AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				AND ((SA1.ClassId=@rClassId) OR (@rClassId=0)) 
				AND (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
			WHERE 
			     (SA1.OrgGroupBatchId = @rOrgGroupBatchId)
				AND	((FS1.ClassId=@rClassId) OR (@rClassId=0))
				AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
				AND (FS1.IsOptional=0)
				AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
				AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND (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(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.AcademicId,
				FM.Title AS FeeName,
				FM.Code AS FeeCode,
				FM.OrderIndex AS FeeOrderIndex
			FROM sFee.tFeeSetup FS1
		INNER JOIN sFee.tFeeOptional FO
			ON FO.FeeSetupId=FS1.Id
	    INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
		INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=FO.SourceId 
			AND SA1.BatchId = FS1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId AND SA1.ClassId = FS1.ClassId 
			AND ((SA1.ClassId=@rClassId) OR (@rClassId=0)) AND ((SA1.DivisionId=@rDivisionId) OR (@rDivisionId=0)) 
			AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
			AND (ISNULL(SA1.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='')
		WHERE
		       (SA1.OrgGroupBatchId = @rOrgGroupBatchId)
				AND ((FS1.ClassId=@rClassId) OR (@rClassId=0))
				AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
				AND (FS1.IsOptional=1)
				AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
				AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND (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(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='')
		) 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				
				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 (SA1.DivisionId=@rDivisionId OR @rDivisionId=0)
				AND (ISNULL(SA1.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='')
			WHERE		
				(R.SourceTypeId = 2001)
				AND ((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND (R.IsObsolete = 0) 
				AND ((SA1.OrgGroupBatchId = @rOrgGroupBatchId)  )
				AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))
				AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
				AND (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) 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 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)) 
		    --change by megha for 0027384
			LEFT JOIN sStudent.tStudentFamily SF ON SF.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 ((SA.ClassStatusId=@rClassStatusId) OR (@rClassStatusId=0))  
			Order by SA.RollNo

	SELECT
			@rBuilder1 as Builder1,
			@rIsDisplayOrgGroup AS IsDisplayOrgGroup,
			(CASE WHEN @rIsReceiptBookGroup = 0 THEN 0
			 WHEN @rIsReceiptBookGroup = 1 THEN	ReceiptBookId
			 END) AS ReceiptBookId,	
			(CASE WHEN @rIsReceiptBookGroup = 0 THEN 'ALL'
			 WHEN @rIsReceiptBookGroup = 1 THEN	ReceiptBookTitle
			 END) AS ReceiptBookTitle,
			(CASE WHEN @rIsReceiptBookGroup = 0 THEN 0
			 WHEN @rIsReceiptBookGroup = 1 THEN	ReceiptOrderIndex
			 END) AS ReceiptOrderIndex,	 
			
			OrgId,			 
			--ReceiptBookId,
			AcademicId,
			DivisionId,
			ClassDivision,RollNo, Name,Code,
			--ReceiptBookTitle,
			OrgName,
			SUM(PendingAmount) AS PendingAmount, 
			[sFee].[fPendingFeeNamesGet](AcademicId,ReceiptBookId,	@p) AS PendingFeeName,
			Pickup AS ParentContactNo,
			DRoppoint AS StudentContactNo,
			SUID,
			ClassOrderIndex,
			DivisionOrderIndex,
			FeeOrderIndex,
			--ReceiptOrderIndex,
			FatherContactNo,
		    MotherContactNo
			FROM @p 
			GROUP By ReceiptBookId,OrgId,AcademicId,DivisionId,
			ClassDivision,RollNo, Name,Code,
			ReceiptBookTitle,OrgName,ReceiptOrderIndex,Pickup,DRoppoint,SUID,ClassOrderIndex,
			DivisionOrderIndex,
			FeeOrderIndex,FatherContactNo,MotherContactNo
			HAVING
			((SUM(PendingAmount) >= @rFromAmount) OR (@rFromAmount=0.00))
			AND (( SUM(PendingAmount)<= @rToAmount) OR (@rToAmount=0.00))
			ORDER BY AcademicId

END

	ELSE
		BEGIN

	INSERT INTO  @p
SELECT 

		SA.AcademicId,
		SA.RollNo,
		SA.Name,
		SA.Code,
		SA.ClassId,
		SA.DivisionId,
		SA.ClassName,
		SA.DivisionName,
		SA.ClassName+' - '+SA.DivisionName AS ClassDivision,
		FS.Id AS FeeSetupId,		
		ISNULL(FS.IsVariable,0)AS IsVariable,
		ISNULL(FS.Amount,0)AS Amount,
		ISNULL(FS.StartDate,'1900-01-01')AS StartDate,
		ISNULL(FS.EndDate,'1900-01-01')AS EndDate,
		ISNULL(FAS.VariableAmount,0.00)AS FAAmount,
		ISNULL(FAS.DiscountAmount,0.00)AS DiscountAmount,
		ISNULL(FAS.AdditionalAmount,0.00)AS AdditionalAmount,
		ISNULL(FAS.PaidAmount,0) AS PaidAmount,
		ISNULL(FAS.ToPayAmount,0) AS PendingAmount,
		--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(FAS.Remark,'') AS Remark,
		FS.ReceiptBookId,
		--FS.FeeName,
		--FS.FeeCode,
		FM.Title AS FeeName, 
		FM.Code AS FeeCode,
		SA.OrgId,
		O.Title AS OrgName,
		O.OrderIndex AS OrgOrderIndex,
		ISNULL(RBM.Title,'') AS ReceiptBookTitle,
		ISNULL(RBM.OrderIndex,0) AS ReceiptOrderIndex,
		0 AS BatchId,
		'' AS BatchName,
		ISNULL(SC.ParentContactNo,'') AS ParentContactNo,
		ISNULL(SC.StudentContactNo,'') AS StudentContactNo,
		'',
		ISNULL(SA.SUID,'') AS SUID,
		SA.ClassOrderIndex,
		SA.DivisionOrder,
		FM.OrderIndex AS FeeOrderIndex,
	    ISNULL(SF.FatherContactNo,'')AS FatherContactNo,
		ISNULL(SF.MotherContactNo,'') AS MotherContactNo
  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=SF.FeeSetupId AND FA.SourceId=SA.AcademicId
		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 sStudent.tStudentCommunication SC ON SC.StudentId = SA.StudentId 
		LEFT JOIN sStudent.tStudentFamily SF ON SF.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) !=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 (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 ((SA.ClassStatusId=@rClassStatusId) OR (@rClassStatusId=0))
			Order by   SA.RollNo
			--FM.OrderIndex 
			

	SELECT
			@rBuilder1 as Builder1,
			@rIsDisplayOrgGroup AS IsDisplayOrgGroup,
			(CASE WHEN @rIsReceiptBookGroup = 0 THEN 0
			 WHEN @rIsReceiptBookGroup = 1 THEN	ReceiptBookId
			 END) AS ReceiptBookId,	
			(CASE WHEN @rIsReceiptBookGroup = 0 THEN 'ALL'
			 WHEN @rIsReceiptBookGroup = 1 THEN	ReceiptBookTitle
			 END) AS ReceiptBookTitle,
			(CASE WHEN @rIsReceiptBookGroup = 0 THEN 0
			 WHEN @rIsReceiptBookGroup = 1 THEN	ReceiptOrderIndex
			 END) AS ReceiptOrderIndex,	 
			
			OrgId,			 
			--ReceiptBookId,
			AcademicId,
			DivisionId,
			ClassDivision,RollNo, Name,Code,
			--ReceiptBookTitle,
			OrgName,
			SUM(PendingAmount) AS PendingAmount, 
			[sFee].[fPendingFeeNamesGet](AcademicId,ReceiptBookId,	@p) AS PendingFeeName,
			Pickup AS ParentContactNo,
			DRoppoint AS StudentContactNo,
			SUID,
			ClassOrderIndex,
			DivisionOrderIndex,
			--ReceiptOrderIndex,
			FeeOrderIndex,
			FatherContactNo,
		    MotherContactNo
			FROM @p 
			GROUP By ReceiptBookId,OrgId,AcademicId,DivisionId,
			ClassDivision,RollNo, Name,Code,
			ReceiptBookTitle,OrgName,ReceiptOrderIndex,Pickup,DRoppoint,SUID,ClassOrderIndex,
			DivisionOrderIndex,FeeOrderIndex,FatherContactNo,MotherContactNo
			HAVING
			((SUM(PendingAmount) >= @rFromAmount) OR (@rFromAmount=0.00))
			AND (( SUM(PendingAmount)<= @rToAmount) OR (@rToAmount=0.00))
			ORDER BY AcademicId

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


GO

 
ALTER PROCEDURE [sFee].[pUpdatePendingAsNAGet]
	 
		@rOrgGroupBatchId int=0,
		@rOrgId int=0,
		@rBatchId int=0,	 
		@rFromLeftDate Date=NULL,
		@rToLeftDate Date=NULL,
	    @rStatusId int=3

	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 	
	
	DECLARE @p AS TempPendingFee
	
	INSERT INTO @p 
	SELECT 
		SA.AcademicId,
		SA.RollNo,
		SA.Name,
		SA.Code,
		SA.ClassId,
		SA.DivisionId,
		SA.ClassName,
		SA.DivisionName,
		SA.ClassName+' - '+SA.DivisionName AS ClassDivision,
		FS.Id AS FeeSetupId,		
		ISNULL(FS.IsVariable,0)AS IsVariable,
		ISNULL(FS.Amount,0)AS Amount,
		ISNULL(FS.StartDate,'1900-01-01')AS StartDate,
		ISNULL(FS.EndDate,'1900-01-01')AS EndDate,
		ISNULL(FA.VariableAmount,0.00)AS FAAmount,
		ISNULL(FA.DiscountAmount,0.00)AS DiscountAmount,
		ISNULL(FA.AdditionalAmount,0.00)AS AdditionalAmount,
		ISNULL(R.PaidAmount,0) AS PaidAmount,
		ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00)AS PendingAmount,
		ISNULL(FA.Remark,'') AS Remark,
		FS.ReceiptBookId,
		FS.FeeName,
		FS.FeeCode,
		SA.OrgId,
		O.Title AS OrgName,
		O.OrderIndex AS OrgOrderIndex,
		ISNULL(RBM.Title,'') AS ReceiptBookTitle,
		ISNULL(RBM.OrderIndex,0) AS ReceiptOrderIndex,
		SA.BatchId,
		BM.Title AS BatchName,
		'',
		'',
		'',
		ISNULL(SA.SUID,'') AS SUID,
		SA.ClassOrderIndex,
		SA.DivisionOrder,
		FS.OrderIndex,
		'' AS FatherContactNo,
		'' AS MotherContactNo
  FROM 
		sStudent.vStudentAcademic SA
		INNER JOIN 
		(
			SELECT 
				FS1.FeeId,
				FS1.Id,
				ISNULL(FS1.IsOptional,0)AS IsOptional,
				ISNULL(FS1.IsVariable,0)AS IsVariable,
				ISNULL(FS1.Amount,0)AS Amount,
				ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
				ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
				FS1.BatchId,
				ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
				SA1.AcademicId,
				FM.Title AS FeeName,
				FM.Code AS FeeCode,
				FM.OrderIndex
			FROM 
				sFee.tFeeSetup FS1
				INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId 
				AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId				
				INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
			WHERE 
			    ((SA1.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
				AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND (FS1.IsOptional=0)
				AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND SA1.StatusId = @rStatusId
				
			UNION ALL
				
			SELECT 
				FS1.FeeId,
				FS1.Id,
				ISNULL(FS1.IsOptional,0)AS IsOptional,
				ISNULL(FS1.IsVariable,0)AS IsVariable,
				ISNULL(FS1.Amount,0)AS Amount,
				ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
				ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
				FS1.BatchId,
				ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
				SA1.AcademicId,
				FM.Title AS FeeName,
				FM.Code AS FeeCode,
				FM.OrderIndex
			FROM 
				sFee.tFeeSetup FS1
				INNER JOIN sFee.tFeeOptional FO ON FO.FeeSetupId=FS1.Id
				INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
				INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=FO.SourceId AND SA1.BatchId = FS1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
			WHERE
		        ((SA1.OrgGroupBatchId = @rOrgGroupBatchId)  OR (@rOrgGroupBatchId=0))
				AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND (FS1.IsOptional=1)
				AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND SA1.StatusId = @rStatusId
				
		) 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 = @rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
				AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
				AND SA1.StatusId = @rStatusId
				GROUP BY FeeSetupId,R.SourceId
		) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
		 INNER JOIN sSetup.tOrganizationMaster O ON SA.OrgId = O.Id
		 INNER JOIN sFee.tReceiptBookMaster RBM ON FS.ReceiptBookId=RBM.Id
		 INNER JOIN sSetup.tBatchMaster BM ON BM.Id=SA.BatchId	
		 LEFT JOIN sHostel.tAssignRoom AR ON  AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003 AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  AND ((AR.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0) AND (SA.OrgGroupBatchId = AR.OrgGroupBatchId)) 
         LEFT JOIN
		(
			SELECT 
				AT.SourceId,
				B.OrgGroupBatchId 
			FROM 
				sTransport.tAssignRoute AT 
				INNER JOIN sTransport.tBusRouteDestinationMaster BM ON BM.Id=AT.PickupDestinationId
				INNER JOIN sTransport.tBusRouteMaster B ON B.Id=BM.BusRouteId AND  AT.SourceTypeId=2003 AND ((B.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))
		) RT ON RT.SourceId = SA.StudentId 
		AND ((SA.OrgGroupBatchId = RT.OrgGroupBatchId))
		AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) 
	WHERE	
			((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
			AND ((SA.BatchId=@rBatchId) OR (@rBatchId=0)) 
			AND (ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00) -ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00) != 0)			
			AND SA.	StatusId = @rStatusId
			
			ORDER BY SA.RollNo
	 
			SELECT
				Temp.OrgId,			 
				Temp.ReceiptBookId,
				Temp.AcademicId,
				Temp.DivisionId,
				ClassDivision,
				Temp.RollNo, 
				Name,
				Temp.Code,
				ReceiptBookTitle,
				OrgName,
				SUM(PendingAmount) AS PendingAmount, 
				[sFee].[fPendingFeeNamesGet](Temp.AcademicId,Temp.ReceiptBookId,	@p) AS PendingFeeName,
				ReceiptOrderIndex,
				Temp.BatchId,
				BatchName,
				'' AS SUId,
				SA.LeftDate,
				Temp.ClassOrderIndex,
				Temp.DivisionOrderIndex,
				'' AS FatherContactNo,
		        '' AS  MotherContactNo
			FROM @p Temp
				INNER JOIN sStudent.tAcademic A ON A.Id =  Temp.AcademicId
				INNER JOIN sStudent.tStudentMaster SM ON SM.Id = A.StudentId AND SM.StatusId = @rStatusId
				INNER JOIN sStudent.tStudentAdmission SA ON SA.StudentId = A.StudentId
			WHERE 
			    ( (@rStatusId = 3 AND ((SA.LeftDate >= @rFromLeftDate) OR (ISNULL(@rFromLeftDate,'') = ''))
				  AND ((SA.LeftDate <= @rToLeftDate) OR (ISNULL(@rToLeftDate,'') = '')) )
				OR (@rStatusId = 2 AND ((SA.InActiveDate >= @rFromLeftDate) OR (ISNULL(@rFromLeftDate,'') = ''))
				  AND ((SA.InActiveDate <= @rToLeftDate) OR (ISNULL(@rToLeftDate,'') = '')) )
				)
				AND SM.StatusId = @rStatusId
				GROUP BY 
				Temp.OrgId,Temp.AcademicId,Temp.ReceiptBookId,Temp.DivisionId,Temp.BatchId,
				ClassDivision,Temp.RollNo, Name,Temp.Code,ReceiptBookTitle,
				OrgName,ReceiptOrderIndex,BatchName,SA.LeftDate,Temp.ClassOrderIndex,
				Temp.DivisionOrderIndex
				ORDER BY Temp.AcademicId
END
GO
PRINT N'Altering Procedure [sFee].[pFeePendingListGet]...';


GO

ALTER PROCEDURE [sFee].[pFeePendingListGet]
		
		@rOrgGroupBatchId int=0,
		@rAdmissionCategoryId int=0,
		@rClassId int=0,
		@rDivisionId int=0,
		@rCode nvarchar(20)='',
		@rFirstName nvarchar(100)='',
		@rLastName nvarchar(100) = '',
		@rReceiptBookId int=0,
		@rOrgId int=0,
		@rBatchId int=0,
		@rDepartmentId int=0,
		@rSUId nvarchar(50) = '',
		@rUptoDate date='',
		@rFromNextFollowupDate date='',
		@rToNextFollowupDate date=''
		
		
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
		BEGIN
			SET @rFirstName = sCommon.fSearchStringGet(@rFirstName)
			SET @rLastName = sCommon.fSearchStringGet(@rLastName)
		END		 
BEGIN 	
	
	DECLARE @p AS TempPendingFee
	
	INSERT INTO @p 
	SELECT 
		SA.AcademicId,
		SA.RollNo,
		SA.Name,
		SA.Code,
		SA.ClassId,
		SA.DivisionId,
		SA.ClassName,
		SA.DivisionName,
		SA.ClassName+' - '+SA.DivisionName AS ClassDivision,
		FS.Id AS FeeSetupId,		
		ISNULL(FS.IsVariable,0)AS IsVariable,
		ISNULL(FS.Amount,0)AS Amount,
		ISNULL(FS.StartDate,'1900-01-01')AS StartDate,
		ISNULL(FS.EndDate,'1900-01-01')AS EndDate,
		ISNULL(FA.VariableAmount,0.00)AS FAAmount,
		ISNULL(FA.DiscountAmount,0.00)AS DiscountAmount,
		ISNULL(FA.AdditionalAmount,0.00)AS AdditionalAmount,
		ISNULL(R.PaidAmount,0) AS PaidAmount,
		ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00)AS PendingAmount,
		ISNULL(FA.Remark,'') AS Remark,
		FS.ReceiptBookId,
		FS.FeeName,
		FS.FeeCode,
		SA.OrgId,
		O.Title AS OrgName,
		O.OrderIndex AS OrgOrderIndex,
		ISNULL(RBM.Title,'') AS ReceiptBookTitle,
		ISNULL(RBM.OrderIndex,0) AS ReceiptOrderIndex,
		SA.BatchId,
		BM.Title AS BatchName,
		'',
		'',
		'',
		ISNULL(SA.SUID,'') AS SUID,
		SA.ClassOrderIndex,
		SA.DivisionOrder,
		FS.OrderIndex,
		--change by megha for 0027384
	    '' AS FatherContactNo,
		'' AS MotherContactNo

  FROM 
		sStudent.vStudentAcademic SA
		INNER JOIN 
		(
			SELECT 
				FS1.FeeId,
				FS1.Id,
				ISNULL(FS1.IsOptional,0)AS IsOptional,
				ISNULL(FS1.IsVariable,0)AS IsVariable,
				ISNULL(FS1.Amount,0)AS Amount,
				ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
				ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
				FS1.BatchId,
				ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
				SA1.AcademicId,
				FM.Title AS FeeName,
				FM.Code AS FeeCode,
				FM.OrderIndex
			FROM 
				sFee.tFeeSetup FS1
				INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId 
				AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId				
				AND ((SA1.ClassId=@rClassId) OR (@rClassId=0)) AND ((SA1.DivisionId=@rDivisionId) OR (@rDivisionId=0))
				AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
			WHERE 
			    ((SA1.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
				AND	((FS1.ClassId=@rClassId) OR (@rClassId=0))
				AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
				AND (FS1.IsOptional=0)
				AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
				
			UNION ALL
				
			SELECT 
				FS1.FeeId,
				FS1.Id,
				ISNULL(FS1.IsOptional,0)AS IsOptional,
				ISNULL(FS1.IsVariable,0)AS IsVariable,
				ISNULL(FS1.Amount,0)AS Amount,
				ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
				ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
				FS1.BatchId,
				ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
				SA1.AcademicId,
				FM.Title AS FeeName,
				FM.Code AS FeeCode,
				FM.OrderIndex
			FROM 
				sFee.tFeeSetup FS1
				INNER JOIN sFee.tFeeOptional FO ON FO.FeeSetupId=FS1.Id
				INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
				INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=FO.SourceId AND SA1.BatchId = FS1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				AND ((SA1.ClassId=@rClassId) OR (@rClassId=0)) AND ((SA1.DivisionId=@rDivisionId) OR (@rDivisionId=0))
				AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
			WHERE
		        ((SA1.OrgGroupBatchId = @rOrgGroupBatchId)  OR (@rOrgGroupBatchId=0))
				AND ((FS1.ClassId=@rClassId) OR (@rClassId=0))
				AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
				AND (FS1.IsOptional=1)
				AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
		) FS ON FS.AcademicId=SA.AcademicId
		LEFT JOIN sFee.tFeeAllocation FA ON FA.FeeSetupId=FS.Id AND FA.SourceId=SA.AcademicId
		LEFT JOIN
		(
		    SELECT 
					ISNULL(SUM(RD.Amount),0) AS PaidAmount,RD.FeeSetupId ,R.SourceId
		    FROM
				sFee.tReceipt R 
				INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id 
				INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id
				INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id
				INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=R.SourceId				
				AND (SA1.ClassId=@rClassId OR @rClassId=0) AND ((SA1.DivisionId=@rDivisionId) OR (@rDivisionId=0))
				AND (SA1.DivisionId=@rDivisionId OR @rDivisionId=0)
				
			WHERE		
				(R.SourceTypeId = 2001)
				AND ((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND (R.IsObsolete = 0) 
				AND ((SA1.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
				AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
				GROUP BY FeeSetupId,R.SourceId
		) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
		 INNER JOIN sSetup.tOrganizationMaster O ON SA.OrgId = O.Id
		 INNER JOIN sFee.tReceiptBookMaster RBM ON FS.ReceiptBookId=RBM.Id
		 INNER JOIN sSetup.tBatchMaster BM ON BM.Id=SA.BatchId	
		 LEFT JOIN sHostel.tAssignRoom AR ON  AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003 AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  AND ((AR.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0) AND (SA.OrgGroupBatchId = AR.OrgGroupBatchId)) 
         LEFT JOIN
		(
			SELECT 
				AT.SourceId,
				B.OrgGroupBatchId 
			FROM 
				sTransport.tAssignRoute AT 
				INNER JOIN sTransport.tBusRouteDestinationMaster BM ON BM.Id=AT.PickupDestinationId
				INNER JOIN sTransport.tBusRouteMaster B ON B.Id=BM.BusRouteId AND  AT.SourceTypeId=2003 AND ((B.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))
		) RT ON RT.SourceId = SA.StudentId 
		AND ((SA.OrgGroupBatchId = RT.OrgGroupBatchId))
		AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) 
	WHERE	
			((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
			AND ((SA.BatchId=@rBatchId) OR (@rBatchId=0)) 
			AND ((SA.Code=@rCode) OR (@rCode=''))
			AND ((SA.Code=@rSUId) OR (@rSUId=''))
			AND ((SA.FirstName like @rFirstName) OR(ISNULL(@rFirstName,'')=''))
			AND ((SA.LastName like @rLastName) OR (ISNULL(@rLastName,'')=''))
			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 SA.	StatusId = 1
			AND ((FS.StartDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
			
			ORDER BY SA.RollNo
 
			SELECT
				Temp.OrgId,			 
				Temp.ReceiptBookId,
				Temp.AcademicId,
				Temp.DivisionId,
				Temp.ClassDivision,
				Temp.RollNo, 
				Temp.Name,
				Temp.Code,
				Temp.ReceiptBookTitle,
				Temp.OrgName,
				SUM(Temp.PendingAmount) AS PendingAmount, 
				[sFee].[fPendingFeeNamesGet](Temp.AcademicId,Temp.ReceiptBookId,	@p) AS PendingFeeName,
				Temp.ReceiptOrderIndex,
				Temp.BatchId,
				Temp.BatchName,
				SA.SUId AS SUId,
				FF.NextFollowupDate,
				ISNULL(SC.IsStopApplicationAccess,0) as IsStopApplicationAccess,
				ISNULL(SC.StudentCustomAlert,'') as StudentCustomAlert,
				ISNULL(SC.ParentContactNo,'')AS ParentContactNo,
				ISNULL(SC.StudentContactNo,'')AS StudentContactNo,
				ISNULL(SC.WhatsAppContactNo,'')AS WhatsAppContactNo,
				Temp.ClassOrderIndex,
				Temp.DivisionOrderIndex,
				'' AS FatherContactNo,
		        '' AS MotherContactNo
			FROM @p Temp
			LEFT JOIN 
			(
				SELECT AcademicId,ReceiptBookId,NextFollowupDate 
				FROM 
				(
				SELECT AcademicId,ReceiptBookId,NextFollowupDate, 
				ROW_NUMBER() OVER(PARTITION BY AcademicId,ReceiptBookId ORDER BY NextFollowupDate DESC) AS RowNumber
				FROM sFee.tFeeFollowup FF 
				) AS T
				WHERE RowNumber = 1 
			) FF ON FF.AcademicId = Temp.AcademicId AND FF.ReceiptBookId = Temp.ReceiptBookId
			INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId = Temp.AcademicId AND SA.OrgId = Temp.OrgId
			LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId = SA.StudentId 
			--change by megha for 0027384
			LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId = SA.StudentId 
		WHERE 
			((FF.NextFollowupDate >= @rFromNextFollowupDate) OR (ISNULL(@rFromNextFollowupDate,'') = ''))
			AND ((FF.NextFollowupDate <= @rToNextFollowupDate) OR (ISNULL(@rToNextFollowupDate,'') = ''))
		GROUP BY 
			Temp.OrgId,Temp.AcademicId,Temp.ReceiptBookId,Temp.DivisionId,Temp.BatchId,
			Temp.ClassDivision,Temp.RollNo, Temp.Name,Temp.Code,Temp.ReceiptBookTitle,
			Temp.OrgName,Temp.ReceiptOrderIndex,Temp.BatchName,FF.NextFollowupDate,
			SC.IsStopApplicationAccess,SC.StudentCustomAlert,SC.ParentContactNo,SC.StudentContactNo,SC.WhatsAppContactNo,SA.SUId,Temp.ClassOrderIndex,
			Temp.DivisionOrderIndex
			ORDER BY Temp.AcademicId
END
GO
PRINT N'Altering Procedure [sFee].[pStudentFeeDetailGet]...';


GO
 
ALTER PROCEDURE [sFee].[pStudentFeeDetailGet]
	 
	   @rBusRouteId int,
	   @rOrgGroupId smallint, 
	   @rOrgGroupBatchId int
		
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
		
BEGIN 

DECLARE @p as TempPendingFee
	
	INSERT INTO  @p 
	 
	SELECT 
		SA.AcademicId,
		SA.RollNo,
		SA.Name,
		SA.Code,
		SA.ClassId,
		SA.DivisionId,
		SA.ClassName,
		SA.DivisionName,
		SA.ClassName+' - '+SA.DivisionName AS ClassDivision,
		FS.Id AS FeeSetupId,		
		ISNULL(FS.IsVariable,0)AS IsVariable,
		ISNULL(FS.Amount,0)AS Amount,
		ISNULL(FS.StartDate,'1900-01-01')AS StartDate,
		ISNULL(FS.EndDate,'1900-01-01')AS EndDate,
		ISNULL(FA.VariableAmount,0.00)AS FAAmount,
		ISNULL(FA.DiscountAmount,0.00)AS DiscountAmount,
		ISNULL(FA.AdditionalAmount,0.00)AS AdditionalAmount,
		ISNULL(R.PaidAmount,0) AS PaidAmount,
		ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00)AS PendingAmount,
		ISNULL(FA.Remark,'') AS Remark,
		FS.ReceiptBookId,
		FS.FeeName,
		FS.FeeCode,
		SA.OrgId,
		O.Title AS OrgName,
		O.OrderIndex AS OrgOrderIndex,
		ISNULL(RBM.Title,'') AS ReceiptBookTitle,
		ISNULL(RBM.OrderIndex,0) AS ReceiptOrderIndex,
		0 AS BatchId,
		'' AS BatchName, 
		'' AS Pickup,
		'' AS DRoppoint,
		'' AS PresentContactNo,
		ISNULL(SA.SUID,'') AS SUID,
		SA.ClassOrderIndex,
		SA.DivisionOrder,
		FS.FeeOrderIndex,
		'' AS FatherContactNo,
		'' AS MotherContactNo	
  FROM 
        sStudent.vStudentAcademic SA
		INNER JOIN 
		(
			SELECT 
				FS1.FeeId,
				FS1.Id,
				ISNULL(FS1.IsOptional,0)AS IsOptional,
				ISNULL(FS1.IsVariable,0)AS IsVariable,
				ISNULL(FS1.Amount,0)AS Amount,
				ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
				ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
				FS1.BatchId,
				ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
				SA1.AcademicId,
				FM.Title AS FeeName,
				FM.Code AS FeeCode,
				SA1.StudentId AS StudentId,
				FM.OrderIndex AS FeeOrderIndex
			FROM sFee.tFeeSetup FS1
				INNER JOIN sFee.tFeeOptional FO ON FO.FeeSetupId=FS1.Id
				INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
				INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=FO.SourceId AND SA1.BatchId = FS1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId AND SA1.ClassId = FS1.ClassId
				INNER JOIN sFee.tFeeHeadMaster FH ON FH.Id = FM.FeeHeadId AND FH.Number = 1001
				INNER JOIN sTransport.tAssignRoute AR oN SA1.StudentId = AR.SourceId AND AR.SourceTypeId = 2003
				INNER JOIN sTransport.tBusRouteDestinationMaster BRDM ON BRDM.Id = AR.PickupDestinationId
				INNER JOIN sTransport.tBusRouteMaster BRM ON BRDM.BusRouteId = BRM.Id
		WHERE
		       (SA1.OrgGroupBatchId = @rOrgGroupBatchId)
				AND (FS1.IsOptional=1)
				AND ((BRDM.BusRouteId=@rBusRouteId) OR (@rBusRouteId=0))
				AND (BRM.OrgGroupBatchId = @rOrgGroupBatchId)
				
		) FS ON FS.AcademicId=SA.AcademicId
		LEFT JOIN sFee.tFeeAllocation FA
			ON FA.FeeSetupId=FS.Id AND FA.SourceId=SA.AcademicId
		LEFT JOIN
		(
		    SELECT 
					ISNULL(SUM(RD.Amount),0) AS PaidAmount,RD.FeeSetupId ,R.SourceId
		    FROM
				sFee.tReceipt R 
				INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id
				INNER JOIN sFee.tFeeSetup FS ON FS.Id = RD.FeeSetupId 
				INNER JOIN sfEe.tFeeMaster FM ON FM.Id = FS.FeeId 
				INNER JOIN sFee.tFeeHeadMaster FH ON FM.FeeHeadId = FH.Id AND FH.Number = 1001
				INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=R.SourceId				
				INNER JOIN sTransport.tAssignRoute AR oN SA1.StudentId = AR.SourceId AND AR.SourceTypeId = 2003
				INNER JOIN sTransport.tBusRouteDestinationMaster BRDM ON BRDM.Id = AR.PickupDestinationId
				INNER JOIN sTransport.tBusRouteMaster BRM ON BRDM.BusRouteId = BRM.Id
				
			WHERE		
				(R.SourceTypeId = 2001)
				AND (R.IsObsolete = 0) 
				AND ((SA1.OrgGroupBatchId = @rOrgGroupBatchId)  )
				AND ((BRDM.BusRouteId=@rBusRouteId) OR (@rBusRouteId=0))
				AND (BRM.OrgGroupBatchId = @rOrgGroupBatchId)
			GROUP BY FeeSetupId,R.SourceId
		) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
		 INNER JOIN sSetup.tOrganizationMaster O ON SA.OrgId = O.Id
		 INNER JOIN sFee.tReceiptBookMaster RBM ON FS.ReceiptBookId=RBM.Id
		 INNER JOIN sTransport.tAssignRoute AR ON  SA.StudentId = AR.SourceId AND AR.SourceTypeId = 2003	
		 INNER JOIN sTransport.tBusRouteDestinationMaster BRDM ON BRDM.Id = AR.PickupDestinationId
	     INNER JOIN sTransport.tBusRouteMaster BRM ON BRDM.BusRouteId = BRM.Id
		
	WHERE	
			(SA.OrgGroupBatchId = @rOrgGroupBatchId)
			AND (SA.StatusId = 1)
			AND ((BRDM.BusRouteId=@rBusRouteId) OR (@rBusRouteId=0))
			AND (BRM.OrgGroupBatchId = @rOrgGroupBatchId)
    Order by SA.DivisionOrder

			SELECT 
				 CM.DisplayTitle + '-' + DM.DisplayTitle AS ClassDivision,
			 	 SA.StudentId AS StudentId, 
			 	 SA.Code AS StudentCode,
				 0x AS StudentPhoto, 
				 SA.FirstName + ' ' + SA.LastName AS StudentName, 
				 BRDM.Title AS Destination,
				 ISNULL(P.PendingAmount,0.00) AS PendingAmount ,
				 ISNULL(P.FeeName,'')AS FeeName,
				 '' AS FatherContactNo,
		         '' AS MotherContactNo
			FROM 
				 sTransport.tAssignRoute AR 
				 INNER JOIN sStudent.vStudentAcademic SA ON SA.StudentId = AR.SourceId
		         INNER JOIN sTransport.tBusRouteDestinationMaster BRDM ON BRDM.Id = AR.PickupDestinationId 
		         INNER JOIN sTransport.tBusRouteMaster BRM ON BRM.Id = BRDM.BusRouteId 
		         INNER JOIN sSetup.tClassMaster CM ON CM.Id = SA.ClassId 
		         INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = SA.DivisionId 
                 LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId = SA.StudentId 
				 LEFT JOIN @p P ON P.AcademicId = SA.AcademicId
            WHERE 
                 BRM.Id = @rBusRouteId 
                 AND BRM.OrgGroupId = @rOrgGroupId 
                 AND BRM.OrgGroupBatchId = @rOrgGroupBatchId
                 AND SA.IsActiveBatch = 1
                 AND SA.StatusId = 1
            ORDER BY 
				 BRDM.OrderIndex,DM.OrderIndex
END
GO
PRINT N'Altering Procedure [sAcademic].[pImportLessonPlan]...';


GO
ALTER PROCEDURE [sAcademic].[pImportLessonPlan]
       
    @rOrgId int,
	@rXmldoc [nvarchar](max),
	@rBatchId int,
	@rCreatedUserId bigint 	  
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

	DECLARE @lCount int,@intDoc INT,@lInterrorCode INT,@loXML XML,
			@lDivisionId int,
			@lTopicId int,
			@lNoOfPeriodRequired smallint,
			@lObjective nvarchar(1000),
			@lIndicativeHomework nvarchar(1000),
			@lSummary nvarchar(1000),
			@lStartDate date,
			@lEndDate date,
			@lIsCompleted bit,
			@lEmployeeId bigint,
			@lBatchId int,
			@lCreatedUserId bigint,
			@lCreatedDateTime datetime,
			@lUpdatedUserId bigint,
			@lUpdatedDateTime datetime,
			@lLearningExperience nvarchar(1000),
			@lToolsAndTechniques nvarchar(500),
			@lEssentialMaterial nvarchar(500),
			@lAssessmentQuestion nvarchar(1000),
			@lTeacherExample nvarchar(1000),
			@lGuidedPractice nvarchar(1000),
			@lIndependentPractice nvarchar(1000),
			@lSubTopic nvarchar(1000) ,
			@lSession nvarchar(100) ,
			@lTrainingMethod  nvarchar(100) ,
			@lPeriodCount int

	SET @loXML = CAST(@rXmldoc AS XML)
	
	
	CREATE TABLE #tTable1 (
	Id int IDENTITY,
	DivisionId int,
	TopicId int,
	NoOfPeriodRequired smallint,
	Objective nvarchar(1000),
	IndicativeHomework nvarchar(1000),
	Summary nvarchar(1000),
	StartDate date,
	EndDate date,
	IsCompleted bit,
	EmployeeId bigint,
	BatchId int,
	CreatedUserId bigint,
	CreatedDateTime datetime,
	UpdatedUserId bigint,
	UpdatedDateTime datetime,
	LearningExperience nvarchar(1000),
	ToolsAndTechniques nvarchar(500),
	EssentialMaterial nvarchar(500),
	AssessmentQuestion nvarchar(1000),
	TeacherExample nvarchar(1000),
	GuidedPractice nvarchar(1000),
	IndependentPractice nvarchar(1000),
	SubTopic nvarchar(1000),
	Session nvarchar(100) ,
	TrainingMethod  nvarchar(100) ,
	PeriodCount int)
	 
	INSERT INTO #tTable1(
			DivisionId
           ,TopicId
           ,NoOfPeriodRequired
           ,Objective
           ,IndicativeHomework
           ,Summary
           ,StartDate
           ,EndDate
           ,IsCompleted
           ,EmployeeId
		   ,BatchId
		   ,CreatedUserId
           ,LearningExperience
           ,ToolsAndTechniques
           ,EssentialMaterial
           ,AssessmentQuestion
           ,TeacherExample
           ,GuidedPractice
           ,IndependentPractice
           ,SubTopic
		   ,Session 
		   ,TrainingMethod
		   ,PeriodCount)
	SELECT
		 T.c.value('@DivisionId','int') AS DivisionId,
		 T.c.value('@TopicId','int') AS TopicId,
		 T.c.value('@PerioNo','smallint') AS NoOfPeriodRequired,
		 T.c.value('@Objective','nvarchar(1000)') AS Objective,
		 T.c.value('@IndicativeHomework','nvarchar(1000)') AS IndicativeHomework,
		 T.c.value('@Summary','nvarchar(1000)') AS Summary,
		 T.c.value('@StartDate','Date') AS StartDate,
		 T.c.value('@EndDate','Date') AS EndDate,
		 T.c.value('@Completed','bit') AS IsCompleted,
		 T.c.value('@EmployeeId','bigint') AS EmployeeId,
		 @rBatchId,
		 T.c.value('@CreatedUserId','bigint') AS CreatedUserId,
		 T.c.value('@LearningExperience','nvarchar(1000)') AS LearningExperience,
		 T.c.value('@ToolsAndTechniques','nvarchar(500)') AS ToolsAndTechniques,
		 T.c.value('@EssentialMaterial','nvarchar(500)') AS EssentialMaterial,
		 T.c.value('@AssessmentQuestion','nvarchar(1000)') AS AssessmentQuestion,
		 T.c.value('@TeacherExample','nvarchar(1000)') AS TeacherExample,
		 T.c.value('@GuidedPractice','nvarchar(1000)') AS GuidedPractice,
		 T.c.value('@IndependentPractice','nvarchar(1000)') AS IndependentPractice,
		 T.c.value('@SubTopic','nvarchar(1000)') AS SubTopic,
		 T.c.value('@Session','nvarchar(100)') AS Session ,
		 T.c.value('@TrainingMethod','nvarchar(100)') AS TrainingMethod,
		 T.c.value('@PeriodCount','int') AS PeriodCount

	FROM @loXML.nodes('/Table/ImportLessonPlan')T(c)
	
		SELECT @lCount =  COUNT(Id) FROM #tTable1
	
		WHILE @lCount > 0 

		BEGIN				
	   
			SELECT	
				@lDivisionId = DivisionId,
				@lTopicId = TopicId,
				@lNoOfPeriodRequired = NoOfPeriodRequired,
				@lObjective = Objective,
				@lIndicativeHomework = IndicativeHomework,
				@lSummary = Summary,
				@lStartDate = StartDate,
				@lEndDate = EndDate,
				@lIsCompleted = IsCompleted,
				@lEmployeeId = EmployeeId,
				@lBatchId = BatchId,
				@lCreatedUserId = CreatedUserId,
				@lLearningExperience = LearningExperience,
				@lToolsAndTechniques = ToolsAndTechniques,
				@lEssentialMaterial = EssentialMaterial,
				@lAssessmentQuestion = AssessmentQuestion,
				@lTeacherExample = TeacherExample,
				@lGuidedPractice = GuidedPractice,
				@lIndependentPractice = IndependentPractice,
				@lSubTopic = SubTopic ,
				@lSession = Session ,
			    @lTrainingMethod  = TrainingMethod ,
			    @lPeriodCount = PeriodCount 
			FROM #tTable1 WHERE Id = @lCount 

			IF EXISTS(SELECT Id FROM sAcademic.tLessonPlan WHERE DivisionId=@lDivisionId AND TopicId = @lTopicId AND StartDate = @lStartDate AND EndDate = @lEndDate)
			BEGIN
				Declare @lTopicName nvarchar(500), @lDivisionName nvarchar(100)
				SET  @lTopicName =(select Title from sAcademic.tTopicMaster where Id =@lTopicId)
				SET  @lDivisionName =(select Title from sSetup.tDivisionMaster Where Id =@lDivisionId)

				SELECT -101 AS Result, 'Lesson Plan Already Exists for for Division - '+@lDivisionName+', Topic - '+@lTopicName+', Start Date - '+Convert(nvarchar(10), @lStartDate, 103)+', End Date - '+Convert(nvarchar(10), @lEndDate, 103)+'' AS Message
				RETURN
			END 

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

			INSERT INTO sAcademic.tLessonPlan
				(
					Id,
					TopicId,
					DivisionId,
					NoOfPeriodRequired,
					Objective,
					IndicativeHomework,
					Summary,
					StartDate,
					EndDate,
					IsCompleted,
					EmployeeId,
					BatchId,
					CreatedUserId,
					CreatedDateTime,
					LearningExperience,
					ToolsAndTechniques,
					EssentialMaterial,
					AssessmentQuestion,
					TeacherExample,
					GuidedPractice,
					IndependentPractice,
					SubTopic ,
					Session ,
					TrainingMethod ,
					PeriodCount
				)
			VALUES
				(
					@lNextNumber,
					@lTopicId,
					@lDivisionId,
					ISNULL(@lNoOfPeriodRequired,0),
					ISNULL(@lObjective,''),
					ISNULL(@lIndicativeHomework,''),
					ISNULL(@lSummary,''),
					@lStartDate,
					@lEndDate,
					@lIsCompleted,
					@lEmployeeId,
					@lBatchId,
					@lCreatedUserId,
					sCommon.fGetDate(),
					ISNULL(@lLearningExperience,''),
					ISNULL(@lToolsAndTechniques,''),
					ISNULL(@lEssentialMaterial,''),
					ISNULL(@lAssessmentQuestion,''),
					ISNULL(@lTeacherExample,''),
					ISNULL(@lGuidedPractice,''),
					ISNULL(@lIndependentPractice,''),
					ISNULL(@lSubTopic,''),
					ISNULL(@lSession,''),
					ISNULL(@lTrainingMethod,''),
					ISNULL(@lPeriodCount,0)
				)
				
			SET @lCount = @lCount - 1
			SELECT 1 AS Result 		

		 END
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 @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,
	        ClosingBalance,
	        Income,
	        ISNULL(ExpenseGroupId,0) AS ExpenseGroupId,
	        ISNULL(ExpenseGroup,'') AS ExpenseGroup,
	        ISNULL(ExpenseLedger,'') AS ExpenseLedger,
			ISNULL(OpeningBalance,0) AS OpeningBalance,	          
			ISNULL(Expense,0.00) AS Expense,
			ISNULL(IG.IncomeTransactionBalance,0.00) AS IncomeTransactionBalance,
			ISNULL(EG.ExpenseTransactionBalance,0.00) 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,
	        ISNULL(ClosingBalance,0) AS ClosingBalance,
	        ISNULL(Income,0) AS Income,
	        ISNULL(ExpenseGroupId,0) AS ExpenseGroupId,
	        ExpenseGroup AS ExpenseGroup,
	        ExpenseLedger,
			OpeningBalance,
			Expense,
			ISNULL(EG.ExpenseTransactionBalance,0.00) AS ExpenseTransactionBalance,
			ISNULL(IG.IncomeTransactionBalance,0.00) 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 [sAlert].[pEventEmployeeAttendanceGet]...';


GO


ALTER PROCEDURE [sAlert].[pEventEmployeeAttendanceGet]

	 	 --@rEventScheduleId int,
		 @rEventName nvarchar(max),
	 	 --@rEmployeeId bigint,
		 @rFromDate Date,
		 @rToDate Date,
		 --@rAttendanceType nvarchar(max),
		 @rIsPresent bit,
	 	 @rTemplate nvarchar(max),
	 	 @rMailSubject nvarchar(500)='',
		 @rEventAttendanceXml nvarchar(max)

	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
DECLARE @loDoc INT
EXEC sp_xml_preparedocument @loDoc OUTPUT, @rEventAttendanceXml
BEGIN
	CREATE TABLE #EventAttendanctemp  
	(
		EmployeeId bigint,
		IsPresent bit
	)
	INSERT INTO #EventAttendanctemp
	(
		EmployeeId ,
		IsPresent 
	)
	SELECT *
			FROM OPENXML (@loDoc, '/Table/EventAttendance', 1)
			WITH
			(						
				SourceId bigint,
				IsSelfPresent bit
			)
	Select
			EC.EmployeeId,
			EC.Code,
			EC.EmployeeName,
			ISNULL(EC.MobileNumber,'') AS MobileNo,
			ISNULL(EC.CompanyEmail,'') AS EmailId,
			REPLACE (
			REPLACE (
			REPLACE (
			REPLACE (
			REPLACE(@rTemplate,'[EventName]',@rEventName),
			'[EmployeeName]',EC.EmployeeName),
			'[Code]',EC.Code), 
			'[Date]',convert(varchar, @rFromDate, 103)  + '-' + convert(varchar, @rToDate, 103)),
			'[Type]',
			' Present : ' + CASE WHEN tmp.IsPresent = 1 THEN 'YES' ELSE 'NO' END) 
			AS MsgText,
			@rMailSubject AS Subject,
			EC.EmployeeId AS SourceId,
			95 AS SourceTypeId,
			EC.OrgId,
			OM.OrgGroupId,
			EC.EmployeeId AS ReceiverSourceId,
			95 AS ReceiverSourceTypeId,
			EC.WhatsAppContactNo

	From
		sHrm.vEmployeeCommunication EC
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = EC.OrgId
		INNER JOIN #EventAttendanctemp tmp ON EC.EmployeeId = tmp.EmployeeId
		WHERE 
		--EC.EmployeeId = @rEmployeeId
		EC.StatusId = 7

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


GO


ALTER PROCEDURE [sAlert].[pEventStudentAttendanceGet]

	 	 --@rEventScheduleId int,
		 @rEventName nvarchar(max),
	 	 --@rAcademicId bigint,
		 @rFromDate Date,
		 @rToDate Date,
		 @rAttendanceType nvarchar(max),
		 --@rIsStudentPresent bit,
		 --@rIsFatherPresent bit,
		 --@rIsMotherPresent bit,
		 --@rIsGuardianPresent bit,
	 	 @rTemplate nvarchar(max),
	 	 @rMailSubject nvarchar(500)='',
		 @rEventAttendanceXml nvarchar(max)

	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
DECLARE @loDoc INT
EXEC sp_xml_preparedocument @loDoc OUTPUT, @rEventAttendanceXml
BEGIN
	CREATE TABLE #EventAttendanctemp  
	(
		AcademicId bigint,
		IsStudentPresent bit,
		IsFatherPresent bit,
		IsMotherPresent bit,
		IsGuardianPresent bit
	)
	INSERT INTO #EventAttendanctemp
	(
		AcademicId ,
		IsStudentPresent ,
		IsFatherPresent ,
		IsMotherPresent ,
		IsGuardianPresent 
	)
	SELECT *
			FROM OPENXML (@loDoc, '/Table/EventAttendance', 1)
			WITH
			(						
				SourceId bigint,
				IsSelfPresent bit,
				IsFatherPresent bit,
				IsMotherPresent bit,
				IsGuardianPresent bit
			)

	Select
			SC.AcademicId,
			SC.Code,
			SC.Name,
			SC.ParentContactNo AS MobileNo,
			SC.ParentEmail AS EmailId,
			REPLACE (
			REPLACE (
			REPLACE (
			REPLACE (
			REPLACE (
			REPLACE(@rTemplate,'[EventName]',@rEventName),
			'[StudentName]',vSA.Name),
			'[Code]',vSA.Code), 
			'[Date]',convert(varchar, @rFromDate, 103)  + '-' + convert(varchar, @rToDate, 103)),
			'[AttendanceType]',@rAttendanceType),
			'[Type]',
			' Student Present : ' + CASE WHEN tmp.IsStudentPresent = 1 THEN 'YES' ELSE 'NO' END + 
			', Father Present : ' + CASE WHEN tmp.IsFatherPresent = 1 THEN 'YES' ELSE 'NO' END + 
			', Mother Present : ' + CASE WHEN tmp.IsMotherPresent = 1 THEN 'YES' ELSE 'NO' END + 
			', Guardian Present : ' + CASE WHEN tmp.IsGuardianPresent = 1 THEN 'YES' ELSE 'NO' END) 
			AS MsgText,
			@rMailSubject AS Subject,
			SC.AcademicId AS SourceId,
			2001 AS SourceTypeId,
			SC.OrgId,
			SC.OrgGroupId,
			SC.AcademicId AS ReceiverSourceId,
			2001 AS ReceiverSourceTypeId,
			SC.WhatsAppContactNo

	From
	
		--sActivity.tEventSchedule ES
		--INNER JOIN sActivity.tEventAttendance EA ON ES.Id = EA.EventScheduleId
		sStudent.vStudentAcademic vSA 
		INNER JOIN sStudent.vStudentCommunication SC ON SC.AcademicId = vSA.AcademicId
		INNER JOIN #EventAttendanctemp tmp ON vSA.AcademicId =  tmp.AcademicId
		WHERE 
		--vSA.AcademicId = @rAcademicId
		SC.IsBlockAllAlert=0
		AND (SC.StatusId=1)

	DROP TABLE #EventAttendanctemp

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


GO
ALTER PROCEDURE [sAssessment].[pRptBatchWiseResultGradeGet]
	  @rCode nvarchar(20)='',
	  @rOrgId int=0,
	  @rClassId int=0,
	  @rDivisionId int=0,
	  @rBatchId int=0,
	  @rTotalDaysPresentDays int=0,
	  @rStudentHeightWeight int=0
	  	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 

	DECLARE @quer varchar(max)=''
	DECLARE @lOrgId int,@lCode nvarchar(20),@lClassId int,@lDivisionId int,@lBatchId int
	DECLARE @lClassGroupId int
	
  		SET @lOrgId=ISNULL(@rOrgId,0)
  		SET @lBatchId=ISNULL(@rBatchId,0)
  		SET @lClassId=ISNULL(@rClassId,0)
  		SET @lDivisionId=ISNULL(@rDivisionId,0)
  	    SET @lCode=ISNULL(@rCode,'')
		  	    
    DELETE FROM sAssessment.tAllBatchResultGrade 
	SELECT @quer = 'INSERT INTO sAssessment.tAllBatchResultGrade 
  	(
	SubjectId,StudentId
	)
	 SELECT 
			 DISTINCT SM.Id AS Subject,STM.Id AS StudentID FROM
              sStudent.tStudentMaster STM
			  INNER JOIN sStudent.tAcademic AD ON STM.Id = AD.StudentId 
			  INNER JOIN sSetup.tClassMaster CM ON CM.Id=AD.ClassId
			  INNER JOIn sSetup.tClassSubject CS ON CS.ClassId=CM.Id
			  INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=CS.SubjectId 
			  AND SM.OrgId=' + convert(varchar,@lOrgId) + '
			  INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=SM.Id 
  	          WHERE STM.OrgId=' + convert(varchar,@lOrgId) + '
  			  AND AB.OrgId =' + convert(varchar,@lOrgId) + '
  			  AND ((STM.Code = ''' + @lCode + ''') OR (''' + @lCode + ''' = ''''))
  			  AND ((AD.ClassId = ''' + convert(varchar,@lClassId) + ''') OR (' + convert(varchar,@lClassId) + ' = 0))
  			  AND ((AD.DivisionId = ''' + convert(varchar,@lDivisionId) + ''') OR (' + convert(varchar,@lDivisionId) + ' = 0))
  			  AND  AD.BatchId='+Convert(varchar,@lBatchId)+''
  			--SELECT  @quer
  	     EXEC (@quer)
  	     
 -- Add New Field :  Height, Weight
 If( @rStudentHeightWeight = 1)
 BEGIN
	select @quer = 'INSERT INTO sAssessment.tAllBatchResultGrade 
  		(
		SubjectId,StudentId
		)
		 SELECT 
			 -1,STM.Id AS StudentID FROM
              sStudent.tStudentMaster STM
			  INNER JOIN sStudent.tAcademic AD ON STM.Id = AD.StudentId			   
			  AND STM.OrgId=' + convert(varchar,@lOrgId) + '			  
  	          WHERE STM.OrgId=' + convert(varchar,@lOrgId) + '  			  
  			  AND ((STM.Code = ''' + @lCode + ''') OR (''' + @lCode + ''' = ''''))
  			  AND ((AD.ClassId = ''' + convert(varchar,@lClassId) + ''') OR (' + convert(varchar,@lClassId) + ' = 0))
  			  AND ((AD.DivisionId = ''' + convert(varchar,@lDivisionId) + ''') OR (' + convert(varchar,@lDivisionId) + ' = 0))
  			  AND  AD.BatchId='+Convert(varchar,@lBatchId)+''  			
  	   EXEC (@quer)
  	   
  	select @quer = 'INSERT INTO sAssessment.tAllBatchResultGrade 
  		(
		SubjectId,StudentId
		)
		 SELECT 
			 -2,STM.Id AS StudentID FROM
              sStudent.tStudentMaster STM
			  INNER JOIN sStudent.tAcademic AD ON STM.Id = AD.StudentId			   
			  AND STM.OrgId=' + convert(varchar,@lOrgId) + '			  
  	          WHERE STM.OrgId=' + convert(varchar,@lOrgId) + '  			  
  			  AND ((STM.Code = ''' + @lCode + ''') OR (''' + @lCode + ''' = ''''))
  			  AND ((AD.ClassId = ''' + convert(varchar,@lClassId) + ''') OR (' + convert(varchar,@lClassId) + ' = 0))
  			  AND ((AD.DivisionId = ''' + convert(varchar,@lDivisionId) + ''') OR (' + convert(varchar,@lDivisionId) + ' = 0))
  			  AND  AD.BatchId='+Convert(varchar,@lBatchId)+''  			
  	   EXEC (@quer)
END
 
If( @rTotalDaysPresentDays = 1)
BEGIN   
  	select @quer = 'INSERT INTO sAssessment.tAllBatchResultGrade 
  		(
		SubjectId,StudentId
		)
		 SELECT 
			 -3,STM.Id AS StudentID FROM
              sStudent.tStudentMaster STM
			  INNER JOIN sStudent.tAcademic AD ON STM.Id = AD.StudentId			   
			  AND STM.OrgId=' + convert(varchar,@lOrgId) + '			  
  	          WHERE STM.OrgId=' + convert(varchar,@lOrgId) + '  			 
  			  AND ((STM.Code = ''' + @lCode + ''') OR (''' + @lCode + ''' = ''''))
  			  AND ((AD.ClassId = ''' + convert(varchar,@lClassId) + ''') OR (' + convert(varchar,@lClassId) + ' = 0))
  			  AND ((AD.DivisionId = ''' + convert(varchar,@lDivisionId) + ''') OR (' + convert(varchar,@lDivisionId) + ' = 0))
  			  AND  AD.BatchId='+Convert(varchar,@lBatchId)+''  			
  	   EXEC (@quer)
  	   
  	select @quer = 'INSERT INTO sAssessment.tAllBatchResultGrade 
  		(
		SubjectId,StudentId
		)
		 SELECT 
			 -4,STM.Id AS StudentID FROM
              sStudent.tStudentMaster STM
			  INNER JOIN sStudent.tAcademic AD ON STM.Id = AD.StudentId			   
			  AND STM.OrgId=' + convert(varchar,@lOrgId) + '			 
  	          WHERE STM.OrgId=' + convert(varchar,@lOrgId) + '  			  
  			  AND ((STM.Code = ''' + @lCode + ''') OR (''' + @lCode + ''' = ''''))
  			  AND ((AD.ClassId = ''' + convert(varchar,@lClassId) + ''') OR (' + convert(varchar,@lClassId) + ' = 0))
  			  AND ((AD.DivisionId = ''' + convert(varchar,@lDivisionId) + ''') OR (' + convert(varchar,@lDivisionId) + ' = 0))
  			  AND  AD.BatchId='+Convert(varchar,@lBatchId)+''  			
  	   EXEC (@quer)
END  	   
-- Ends here 
  	     
	    DEClare @query varchar(max)
	    DEClare @query1 varchar(max)

  		select @query=  ' UPDATE  AR  SET PG = RD.SubjectGrade FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=101 AND  ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
		exec (@query)
		 	
		select @query=  ' UPDATE  AR  SET Nursary = RD.SubjectGrade FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=102 AND  ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
		exec (@query)
		 	
		select @query=  ' UPDATE  AR  SET SrKg = RD.SubjectGrade FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=104 AND  ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
		exec (@query)
		
		select @query=  ' UPDATE  AR  SET JrKg = RD.SubjectGrade FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=103 AND  ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
		exec (@query)
		 	
        select @query=  ' UPDATE  AR  SET First = RD.SubjectGrade FROM 
			sAssessment.tAllBatchResultGrade  AR
	 		INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId 
			WHERE CGM.ClassGroupId=1 AND  ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
		exec (@query)
		 
        select @query=  ' UPDATE  AR  SET Second = RD.SubjectGrade FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=2 AND ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
		exec (@query)
		 	
		 
	    select @query=  ' UPDATE  AR  SET Third = RD.SubjectGrade FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=3 AND ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
		exec (@query)
		  
	    select @query=  ' UPDATE  AR  SET Fourth = RD.SubjectGrade FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=4 AND  ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) +''
		exec (@query)
		 
        select @query=  ' UPDATE  AR  SET Fifth = RD.SubjectGrade FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=5 AND  ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
		exec (@query)
		 	
        select @query=  ' UPDATE  AR  SET Sixth = RD.SubjectGrade FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=6 AND  ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
		exec (@query)
		 	
        select @query=  ' UPDATE  AR  SET Seventh = RD.SubjectGrade FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=7 AND ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
		exec (@query)
		 
	    select @query=  ' UPDATE  AR  SET Eighth = RD.SubjectGrade FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=8 AND  ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
		exec (@query)
		 	
	    select @query=  ' UPDATE  AR  SET Ninth = RD.SubjectGrade FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=9 AND ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
		exec (@query)
		 	
       select @query=  ' UPDATE  AR  SET Tenth = RD.SubjectGrade FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=10 AND ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
	   exec (@query)
		 	
	   select @query=  ' UPDATE  AR  SET Eleventh = RD.SubjectGrade FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=11 AND  ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
	   exec (@query)
		 
	   select @query=  ' UPDATE  AR  SET Twelfth = RD.SubjectGrade FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=12 AND ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
	   exec (@query)
			
	   select @query=  ' UPDATE  AR  SET PG1 = RD.SubjectGrade FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=101 AND  ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
	   exec (@query)
		 	
	   select @query=  ' UPDATE  AR  SET Nursary1 = RD.SubjectGrade FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=102 AND  ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
	   exec (@query)
	
	   select @query=  ' UPDATE  AR  SET SrKg1 = RD.SubjectGrade FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=104 AND  ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
	   exec (@query)
	   
	   select @query=  ' UPDATE  AR  SET JrKg1 = RD.SubjectGrade FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=103 AND  ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
	   exec (@query)
		 
       select @query=  ' UPDATE  AR  SET First1 = RD.SubjectGrade FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId 
			WHERE CGM.ClassGroupId=1 AND  ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
	   exec (@query)
		
       select @query=  ' UPDATE  AR  SET Second1 = RD.SubjectGrade FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=2 AND ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
	   exec (@query)
		 	
	   select @query=  ' UPDATE  AR  SET Third1 = RD.SubjectGrade FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=3 AND ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
	   exec (@query)
		  
	   select @query=  ' UPDATE  AR  SET Fourth1 = RD.SubjectGrade FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=4 AND  ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
	   exec (@query)
		 	
       select @query=  ' UPDATE  AR  SET Fifth1 = RD.SubjectGrade FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=5 AND  ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
	   exec (@query)
		 
       select @query=  ' UPDATE  AR  SET Sixth1 = RD.SubjectGrade FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=6 AND  ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
	   exec (@query)
		 	
       select @query=  ' UPDATE  AR  SET Seventh1 = RD.SubjectGrade FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=7 AND ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
	   exec (@query)
		 	
	   select @query=  ' UPDATE  AR  SET Eighth1 = RD.SubjectGrade FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=8 AND  ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
	   exec (@query)
		 
	   select @query=  ' UPDATE  AR  SET Ninth1 = RD.SubjectGrade FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=9 AND ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
	   exec (@query)
		 
       select @query=  ' UPDATE  AR  SET Tenth1 = RD.SubjectGrade FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=10 AND ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
	   exec (@query)
		 	
		 	
	   select @query=  ' UPDATE  AR  SET Eleventh1 = RD.SubjectGrade FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=11 AND  ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
	   exec (@query)
		 	
	   select @query=  ' UPDATE  AR  SET Twelfth1 = RD.SubjectGrade FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=12 AND ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
	   exec (@query)
		 
	   select @query=  ' UPDATE  AR  SET PG2 = RD.SubjectGrade FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=101 AND  ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
	   exec (@query)
	   
	   select @query=  ' UPDATE  AR  SET Nursary2 = RD.SubjectGrade FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=102 AND  ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
	   exec (@query)
	   
	   select @query=  ' UPDATE  AR  SET SrKg2 = RD.SubjectGrade FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=104 AND  ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
	   exec (@query)
	   
	   select @query=  ' UPDATE  AR  SET JrKg2 = RD.SubjectGrade FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=103 AND  ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) +''
	  exec (@query)
		 
      select @query=  ' UPDATE  AR  SET First2 = RD.SubjectGrade FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId 
			WHERE CGM.ClassGroupId=1 AND  ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
	 exec (@query)
		 
		
	  select @query=  ' UPDATE  AR  SET Second2 = RD.SubjectGrade FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=2 AND ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
	  exec (@query)
		 	
	  select @query=  ' UPDATE  AR  SET Third2 = RD.SubjectGrade FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=3 AND ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
	  exec (@query)
		   	
	  select @query=  ' UPDATE  AR  SET Fourth2 = RD.SubjectGrade FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=4 AND  ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
	  exec (@query)
		 	
	  select @query=  ' UPDATE  AR  SET Fifth2 = RD.SubjectGrade FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=5 AND  ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
	  exec (@query)
		 	
	  select @query=  ' UPDATE  AR  SET Sixth2 = RD.SubjectGrade FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=6 AND  ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
	   exec (@query)
			
	   select @query=  ' UPDATE  AR  SET Seventh2 = RD.SubjectGrade FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=7 AND ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
	   exec (@query)
		 		
	   select @query=  ' UPDATE  AR  SET Eighth2 = RD.SubjectGrade FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=8 AND  ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
	   exec (@query)
		 	
	   select @query=  ' UPDATE  AR  SET Ninth2 = RD.SubjectGrade FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=9 AND ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
	   exec (@query)
		 		
	   select @query=  ' UPDATE  AR  SET Tenth2 = RD.SubjectGrade FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=10 AND ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
	   exec (@query)
		 	
	   select @query=  ' UPDATE  AR  SET Eleventh2 = RD.SubjectGrade FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=11 AND  ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
	   exec (@query)
		 	
	   select @query=  ' UPDATE  AR  SET Twelfth2 = RD.SubjectGrade FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=12 AND ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
	   exec (@query)
	
---- Start Here Height, Weight, TotalDays, PresentDays Value Update

 DECLARE @Updatequery varchar(max)
	
  ---Sub Exam 1 Starts
 If( @rStudentHeightWeight = 1)
 BEGIN
	select @Updatequery=  ' UPDATE  AR  SET PG = SR.StudentHeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=101 AND  ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = -1 
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET PG = SR.StudentWeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=101 AND  ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = -2
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
END

If( @rTotalDaysPresentDays = 1)
BEGIN  
   select @Updatequery=  ' UPDATE  AR  SET PG = SR.TotalDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=101 AND  ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = -3
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET PG = SR.PresentDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=101 AND  ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = -4
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''
   exec (@Updatequery)
END  

If( @rStudentHeightWeight = 1)
BEGIN
	select @Updatequery=  ' UPDATE  AR  SET Nursary = SR.StudentHeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=102 AND  ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = -1 
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET Nursary = SR.StudentWeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=102 AND  ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = -2
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''
   exec (@Updatequery)
END

If( @rTotalDaysPresentDays = 1)
BEGIN 
   select @Updatequery=  ' UPDATE  AR  SET Nursary = SR.TotalDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=102 AND  ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = -3
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET Nursary = SR.PresentDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=102 AND  ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = -4
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
END

If( @rStudentHeightWeight = 1)
BEGIN
   select @Updatequery=  ' UPDATE  AR  SET JrKg = SR.StudentHeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=103 AND  ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = -1 
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET JrKg = SR.StudentWeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=103 AND  ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = -2
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''
   exec (@Updatequery)
END  

If( @rTotalDaysPresentDays = 1)
BEGIN  
   select @Updatequery=  ' UPDATE  AR  SET JrKg = SR.TotalDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=103 AND  ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = -3
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET JrKg = SR.PresentDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=103 AND  ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = -4
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''
   exec (@Updatequery)
END

If( @rStudentHeightWeight = 1)
BEGIN  
    select @Updatequery=  ' UPDATE  AR  SET SrKg = SR.StudentHeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=104 AND  ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = -1 
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET SrKg = SR.StudentWeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=104 AND  ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = -2
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
END

If( @rTotalDaysPresentDays = 1)
BEGIN    
   select @Updatequery=  ' UPDATE  AR  SET SrKg = SR.TotalDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=104 AND  ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = -3
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET SrKg = SR.PresentDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=104 AND  ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = -4
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
END

If( @rStudentHeightWeight = 1)
BEGIN   
       select @Updatequery=  ' UPDATE  AR  SET First = SR.StudentHeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=1 AND  ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = -1 
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET First = SR.StudentWeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=1 AND  ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = -2
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
END

If( @rTotalDaysPresentDays = 1)
BEGIN  
   select @Updatequery=  ' UPDATE  AR  SET First = SR.TotalDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=1 AND  ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = -3
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET First = SR.PresentDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=1 AND  ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = -4
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
END

If( @rStudentHeightWeight = 1)
BEGIN   
        select @Updatequery=  ' UPDATE  AR  SET Second = SR.StudentHeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=2 AND  ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = -1 
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET Second = SR.StudentWeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=2 AND  ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = -2
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''
   exec (@Updatequery)
END

If( @rTotalDaysPresentDays = 1)
BEGIN   
   select @Updatequery=  ' UPDATE  AR  SET Second = SR.TotalDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=2 AND  ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = -3
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET Second = SR.PresentDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=2 AND  ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = -4
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
END

If( @rStudentHeightWeight = 1)
BEGIN   
   select @Updatequery=  ' UPDATE  AR  SET Third = SR.StudentHeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=3 AND  ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = -1 
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET Third = SR.StudentWeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=3 AND  ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = -2
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
END

If( @rTotalDaysPresentDays = 1)
BEGIN  
   select @Updatequery=  ' UPDATE  AR  SET Third = SR.TotalDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=3 AND  ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = -3
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET Third = SR.PresentDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=3 AND  ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = -4
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
END

If( @rStudentHeightWeight = 1)
BEGIN  
   select @Updatequery=  ' UPDATE  AR  SET Fourth = SR.StudentHeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=4 AND  ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = -1 
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET Fourth = SR.StudentWeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=4 AND  ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = -2
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
END

If( @rTotalDaysPresentDays = 1)
BEGIN    
   select @Updatequery=  ' UPDATE  AR  SET Fourth = SR.TotalDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=4 AND  ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = -3
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET Fourth = SR.PresentDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=4 AND  ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = -4
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''
   exec (@Updatequery)
END

If( @rStudentHeightWeight = 1)
BEGIN   
     select @Updatequery=  ' UPDATE  AR  SET Fifth = SR.StudentHeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=5 AND  ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = -1 
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET Fifth = SR.StudentWeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=5 AND  ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = -2
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
END

If( @rTotalDaysPresentDays = 1)
BEGIN   
   select @Updatequery=  ' UPDATE  AR  SET Fifth = SR.TotalDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=5 AND  ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = -3
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET Fifth = SR.PresentDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=5 AND  ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = -4
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
END

If( @rStudentHeightWeight = 1)
BEGIN  
     select @Updatequery=  ' UPDATE  AR  SET Sixth = SR.StudentHeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=6 AND  ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = -1 
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET Sixth = SR.StudentWeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=6 AND  ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = -2
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
END

If( @rTotalDaysPresentDays = 1)
BEGIN  
   select @Updatequery=  ' UPDATE  AR  SET Sixth = SR.TotalDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=6 AND  ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = -3
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET Sixth = SR.PresentDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=6 AND  ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = -4
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
END

If( @rStudentHeightWeight = 1)
BEGIN  
    select @Updatequery=  ' UPDATE  AR  SET Seventh = SR.StudentHeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=7 AND  ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = -1 
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET Seventh = SR.StudentWeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=7 AND  ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = -2
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
END

If( @rTotalDaysPresentDays = 1)
BEGIN     
   select @Updatequery=  ' UPDATE  AR  SET Seventh = SR.TotalDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=7 AND  ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = -3
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET Seventh = SR.PresentDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=7 AND  ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = -4
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
END

If( @rStudentHeightWeight = 1)
BEGIN   
   select @Updatequery=  ' UPDATE  AR  SET Eighth = SR.StudentHeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=8 AND  ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = -1 
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET Eighth = SR.StudentWeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=8 AND  ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = -2
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
END

If( @rTotalDaysPresentDays = 1)
BEGIN 
   select @Updatequery=  ' UPDATE  AR  SET Eighth = SR.TotalDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=8 AND  ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = -3
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET Eighth = SR.PresentDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=8 AND  ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = -4
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
END

If( @rStudentHeightWeight = 1)
BEGIN   
    select @Updatequery=  ' UPDATE  AR  SET Ninth = SR.StudentHeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=9 AND  ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = -1 
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET Ninth = SR.StudentWeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=9 AND  ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = -2
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''
   exec (@Updatequery)
END

If( @rTotalDaysPresentDays = 1)
BEGIN    
   select @Updatequery=  ' UPDATE  AR  SET Ninth = SR.TotalDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=9 AND  ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = -3
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET Ninth = SR.PresentDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=9 AND  ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = -4
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
END

If( @rStudentHeightWeight = 1)
BEGIN 
   select @Updatequery=  ' UPDATE  AR  SET Tenth = SR.StudentHeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=10 AND  ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = -1 
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET Tenth = SR.StudentWeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=10 AND  ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = -2
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
END

If( @rTotalDaysPresentDays = 1)
BEGIN    
   select @Updatequery=  ' UPDATE  AR  SET Tenth = SR.TotalDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=10 AND  ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = -3
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET Tenth = SR.PresentDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=10 AND  ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = -4
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
END

If( @rStudentHeightWeight = 1)
BEGIN   
   select @Updatequery=  ' UPDATE  AR  SET Eleventh = SR.StudentHeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=11 AND  ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = -1 
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET Eleventh = SR.StudentWeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=11 AND  ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = -2
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
END

If( @rTotalDaysPresentDays = 1)
BEGIN    
   select @Updatequery=  ' UPDATE  AR  SET Eleventh = SR.TotalDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=11 AND  ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = -3
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET Eleventh = SR.PresentDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=11 AND  ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = -4
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
END

If( @rStudentHeightWeight = 1)
BEGIN
   select @Updatequery=  ' UPDATE  AR  SET Twelfth = SR.StudentHeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=12 AND  ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = -1 
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET Twelfth = SR.StudentWeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=12 AND  ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = -2
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
END

If( @rTotalDaysPresentDays = 1)
BEGIN  
   select @Updatequery=  ' UPDATE  AR  SET Twelfth = SR.TotalDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=12 AND  ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = -3
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET Twelfth = SR.PresentDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=12 AND  ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = -4
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
END   
  ---Sub Exam 1 Ends   
  ---Sub Exam 2 Starts

If( @rStudentHeightWeight = 1)
BEGIN   
   	select @Updatequery=  ' UPDATE  AR  SET PG1 = SR.StudentHeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=101 AND  ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = -1 
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET PG1 = SR.StudentWeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=101 AND  ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = -2
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
END

If( @rTotalDaysPresentDays = 1)
BEGIN   
   select @Updatequery=  ' UPDATE  AR  SET PG1 = SR.TotalDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=101 AND  ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = -3
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET PG1 = SR.PresentDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=101 AND  ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = -4
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
END   

If( @rStudentHeightWeight = 1)
BEGIN   
	select @Updatequery=  ' UPDATE  AR  SET Nursary1 = SR.StudentHeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=102 AND  ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = -1 
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET Nursary1 = SR.StudentWeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=102 AND  ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = -2
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
END

If( @rTotalDaysPresentDays = 1)
BEGIN     
   select @Updatequery=  ' UPDATE  AR  SET Nursary1 = SR.TotalDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=102 AND  ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = -3
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET Nursary1 = SR.PresentDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=102 AND  ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = -4
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
	exec (@Updatequery)
END

If( @rStudentHeightWeight = 1)
BEGIN
   select @Updatequery=  ' UPDATE  AR  SET JrKg1 = SR.StudentHeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=103 AND  ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = -1 
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET JrKg1 = SR.StudentWeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=103 AND  ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = -2
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
END

If( @rTotalDaysPresentDays = 1)
BEGIN 
   select @Updatequery=  ' UPDATE  AR  SET JrKg1 = SR.TotalDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=103 AND  ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = -3
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET JrKg1 = SR.PresentDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=103 AND  ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = -4
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
END

If( @rStudentHeightWeight = 1)
BEGIN
   select @Updatequery=  ' UPDATE  AR  SET SrKg1 = SR.StudentHeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=104 AND  ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = -1 
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET SrKg1 = SR.StudentWeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=104 AND  ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = -2
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
END

If( @rTotalDaysPresentDays = 1)
BEGIN   
   select @Updatequery=  ' UPDATE  AR  SET SrKg1 = SR.TotalDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=104 AND  ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = -3
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET SrKg1 = SR.PresentDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=104 AND  ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = -4
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
END

If( @rStudentHeightWeight = 1)
BEGIN   
    select @Updatequery=  ' UPDATE  AR  SET First1 = SR.StudentHeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=1 AND  ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = -1 
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET First1 = SR.StudentWeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=1 AND  ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = -2
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
END

If( @rTotalDaysPresentDays = 1)
BEGIN    
   select @Updatequery=  ' UPDATE  AR  SET First1 = SR.TotalDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=1 AND  ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = -3
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET First1 = SR.PresentDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=1 AND  ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = -4
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''
   exec (@Updatequery)
END

If( @rStudentHeightWeight = 1)
BEGIN
    select @Updatequery=  ' UPDATE  AR  SET Second1 = SR.StudentHeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=2 AND  ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = -1 
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET Second1 = SR.StudentWeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=2 AND  ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = -2
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
END

If( @rTotalDaysPresentDays = 1)
BEGIN
   select @Updatequery=  ' UPDATE  AR  SET Second1 = SR.TotalDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=2 AND  ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = -3
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET Second1 = SR.PresentDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=2 AND  ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = -4
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
END

If( @rStudentHeightWeight = 1)
BEGIN
   select @Updatequery=  ' UPDATE  AR  SET Third1 = SR.StudentHeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=3 AND  ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = -1 
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET Third1 = SR.StudentWeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=3 AND  ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = -2
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
END

If( @rTotalDaysPresentDays = 1)
BEGIN
   select @Updatequery=  ' UPDATE  AR  SET Third1 = SR.TotalDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=3 AND  ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = -3
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET Third1 = SR.PresentDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=3 AND  ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = -4
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
END

If( @rStudentHeightWeight = 1)
BEGIN
   select @Updatequery=  ' UPDATE  AR  SET Fourth1 = SR.StudentHeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=4 AND  ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = -1 
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET Fourth1 = SR.StudentWeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=4 AND  ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = -2
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
END

If( @rTotalDaysPresentDays = 1)
BEGIN 
   select @Updatequery=  ' UPDATE  AR  SET Fourth1 = SR.TotalDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=4 AND  ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = -3
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET Fourth1 = SR.PresentDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=4 AND  ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = -4
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
END

If( @rStudentHeightWeight = 1)
BEGIN   
     select @Updatequery=  ' UPDATE  AR  SET Fifth1 = SR.StudentHeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=5 AND  ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = -1 
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET Fifth1 = SR.StudentWeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=5 AND  ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = -2
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
END

If( @rTotalDaysPresentDays = 1)
BEGIN  
   select @Updatequery=  ' UPDATE  AR  SET Fifth1 = SR.TotalDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=5 AND  ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = -3
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET Fifth1 = SR.PresentDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=5 AND  ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = -4
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
END

If( @rStudentHeightWeight = 1)
BEGIN
   select @Updatequery=  ' UPDATE  AR  SET Sixth1 = SR.StudentHeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=6 AND  ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = -1 
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET Sixth1 = SR.StudentWeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=6 AND  ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = -2
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
END

If( @rTotalDaysPresentDays = 1)
BEGIN
   select @Updatequery=  ' UPDATE  AR  SET Sixth1 = SR.TotalDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=6 AND  ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = -3
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET Sixth1 = SR.PresentDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=6 AND  ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = -4
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
END

If( @rStudentHeightWeight = 1)
BEGIN
    select @Updatequery=  ' UPDATE  AR  SET Seventh1 = SR.StudentHeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=7 AND  ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = -1 
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET Seventh1 = SR.StudentWeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=7 AND  ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = -2
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
END

If( @rTotalDaysPresentDays = 1)
BEGIN
   select @Updatequery=  ' UPDATE  AR  SET Seventh1 = SR.TotalDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=7 AND  ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = -3
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET Seventh1 = SR.PresentDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=7 AND  ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = -4
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
END

If( @rStudentHeightWeight = 1)
BEGIN
   select @Updatequery=  ' UPDATE  AR  SET Eighth1 = SR.StudentHeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=8 AND  ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = -1 
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET Eighth1 = SR.StudentWeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=8 AND  ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = -2
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
END

If( @rTotalDaysPresentDays = 1)
BEGIN  
   select @Updatequery=  ' UPDATE  AR  SET Eighth1 = SR.TotalDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=8 AND  ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = -3
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET Eighth1 = SR.PresentDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=8 AND  ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = -4
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
END

If( @rStudentHeightWeight = 1)
BEGIN 
    select @Updatequery=  ' UPDATE  AR  SET Ninth1 = SR.StudentHeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=9 AND  ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = -1 
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET Ninth1 = SR.StudentWeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=9 AND  ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = -2
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
END

If( @rTotalDaysPresentDays = 1)
BEGIN    
   select @Updatequery=  ' UPDATE  AR  SET Ninth1 = SR.TotalDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=9 AND  ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = -3
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET Ninth1 = SR.PresentDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=9 AND  ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = -4
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
END

If( @rStudentHeightWeight = 1)
BEGIN   
   select @Updatequery=  ' UPDATE  AR  SET Tenth1 = SR.StudentHeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=10 AND  ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = -1 
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET Tenth1 = SR.StudentWeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=10 AND  ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = -2
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
END

If( @rTotalDaysPresentDays = 1)
BEGIN    
   select @Updatequery=  ' UPDATE  AR  SET Tenth1 = SR.TotalDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=10 AND  ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = -3
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET Tenth1 = SR.PresentDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=10 AND  ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = -4
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
END

If( @rStudentHeightWeight = 1)
BEGIN   
   select @Updatequery=  ' UPDATE  AR  SET Eleventh1 = SR.StudentHeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=11 AND  ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = -1 
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET Eleventh1 = SR.StudentWeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=11 AND  ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = -2
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
END

If( @rTotalDaysPresentDays = 1)
BEGIN    
   select @Updatequery=  ' UPDATE  AR  SET Eleventh1 = SR.TotalDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=11 AND  ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = -3
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET Eleventh1 = SR.PresentDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=11 AND  ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = -4
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
END

If( @rStudentHeightWeight = 1)
BEGIN   
    select @Updatequery=  ' UPDATE  AR  SET Twelfth1 = SR.StudentHeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=12 AND  ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = -1 
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET Twelfth1 = SR.StudentWeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=12 AND  ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = -2
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
END

If( @rTotalDaysPresentDays = 1)
BEGIN     
   select @Updatequery=  ' UPDATE  AR  SET Twelfth1 = SR.TotalDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=12 AND  ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = -3
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET Twelfth1 = SR.PresentDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=12 AND  ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = -4
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
END   
  ---Sub Exam 2 Ends   
  ---Sub Exam 3 Starts

If( @rStudentHeightWeight = 1)
BEGIN   
   select @Updatequery=  ' UPDATE  AR  SET PG2 = SR.StudentHeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=101 AND  ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = -1 
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET PG2 = SR.StudentWeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=101 AND  ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = -2
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
END

If( @rTotalDaysPresentDays = 1)
BEGIN   
   select @Updatequery=  ' UPDATE  AR  SET PG2 = SR.TotalDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=101 AND  ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = -3
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET PG2 = SR.PresentDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=101 AND  ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = -4
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''
   exec (@Updatequery)
END

If( @rStudentHeightWeight = 1)
BEGIN
	select @Updatequery=  ' UPDATE  AR  SET Nursary2 = SR.StudentHeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=102 AND  ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = -1 
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET Nursary2 = SR.StudentWeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=102 AND  ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = -2
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
END

If( @rTotalDaysPresentDays = 1)
BEGIN   
   select @Updatequery=  ' UPDATE  AR  SET Nursary2 = SR.TotalDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=102 AND  ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = -3
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET Nursary2 = SR.PresentDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=102 AND  ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = -4
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''
   exec (@Updatequery)
END

If( @rStudentHeightWeight = 1)
BEGIN   
   select @Updatequery=  ' UPDATE  AR  SET JrKg2 = SR.StudentHeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=103 AND  ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = -1 
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET JrKg2 = SR.StudentWeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=103 AND  ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = -2
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
END

If( @rTotalDaysPresentDays = 1)
BEGIN    
   select @Updatequery=  ' UPDATE  AR  SET JrKg2 = SR.TotalDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=103 AND  ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = -3
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET JrKg2 = SR.PresentDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=103 AND  ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = -4
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
END

If( @rStudentHeightWeight = 1)
BEGIN   
    select @Updatequery=  ' UPDATE  AR  SET SrKg2 = SR.StudentHeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=104 AND  ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = -1 
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET SrKg2 = SR.StudentWeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=104 AND  ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = -2
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
END

If( @rTotalDaysPresentDays = 1)
BEGIN    
   select @Updatequery=  ' UPDATE  AR  SET SrKg2 = SR.TotalDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=104 AND  ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = -3
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET SrKg2 = SR.PresentDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=104 AND  ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = -4
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
END

If( @rStudentHeightWeight = 1)
BEGIN   
       select @Updatequery=  ' UPDATE  AR  SET First2 = SR.StudentHeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=1 AND  ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = -1 
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET First2 = SR.StudentWeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=1 AND  ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = -2
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
END

If( @rTotalDaysPresentDays = 1)
BEGIN    
   select @Updatequery=  ' UPDATE  AR  SET First2 = SR.TotalDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=1 AND  ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = -3
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET First2 = SR.PresentDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=1 AND  ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = -4
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
END
   
If( @rStudentHeightWeight = 1)
BEGIN
     select @Updatequery=  ' UPDATE  AR  SET Second2 = SR.StudentHeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=2 AND  ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = -1 
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET Second2 = SR.StudentWeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=2 AND  ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = -2
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
END

If( @rTotalDaysPresentDays = 1)
BEGIN    
   select @Updatequery=  ' UPDATE  AR  SET Second2 = SR.TotalDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=2 AND  ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = -3
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET Second2 = SR.PresentDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=2 AND  ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = -4
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
END

If( @rStudentHeightWeight = 1)
BEGIN   
   select @Updatequery=  ' UPDATE  AR  SET Third2 = SR.StudentHeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=3 AND  ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = -1 
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET Third2 = SR.StudentWeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=3 AND  ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = -2
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
END

If( @rTotalDaysPresentDays = 1)
BEGIN    
   select @Updatequery=  ' UPDATE  AR  SET Third2 = SR.TotalDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=3 AND  ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = -3
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET Third2 = SR.PresentDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=3 AND  ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = -4
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
END

If( @rStudentHeightWeight = 1)
BEGIN   
   select @Updatequery=  ' UPDATE  AR  SET Fourth2 = SR.StudentHeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=4 AND  ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = -1 
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET Fourth2 = SR.StudentWeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=4 AND  ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = -2
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
END

If( @rTotalDaysPresentDays = 1)
BEGIN   
   select @Updatequery=  ' UPDATE  AR  SET Fourth2 = SR.TotalDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=4 AND  ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = -3
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET Fourth2 = SR.PresentDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=4 AND  ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = -4
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
END

If( @rStudentHeightWeight = 1)
BEGIN   
   select @Updatequery=  ' UPDATE  AR  SET Fifth2 = SR.StudentHeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=5 AND  ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = -1 
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET Fifth2 = SR.StudentWeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=5 AND  ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = -2
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
END

If( @rTotalDaysPresentDays = 1)
BEGIN   
   select @Updatequery=  ' UPDATE  AR  SET Fifth2 = SR.TotalDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=5 AND  ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = -3
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET Fifth2 = SR.PresentDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=5 AND  ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = -4
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
END

If( @rStudentHeightWeight = 1)
BEGIN   
   select @Updatequery=  ' UPDATE  AR  SET Sixth2 = SR.StudentHeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=6 AND  ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = -1 
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET Sixth2 = SR.StudentWeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=6 AND  ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = -2
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
END

If( @rTotalDaysPresentDays = 1)
BEGIN    
   select @Updatequery=  ' UPDATE  AR  SET Sixth2 = SR.TotalDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=6 AND  ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = -3
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET Sixth2 = SR.PresentDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=6 AND  ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = -4
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
END

If( @rStudentHeightWeight = 1)
BEGIN   
    select @Updatequery=  ' UPDATE  AR  SET Seventh2 = SR.StudentHeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=7 AND  ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = -1 
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET Seventh2 = SR.StudentWeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=7 AND  ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = -2
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
END

If( @rTotalDaysPresentDays = 1)
BEGIN    
   select @Updatequery=  ' UPDATE  AR  SET Seventh2 = SR.TotalDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=7 AND  ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = -3
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET Seventh2 = SR.PresentDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=7 AND  ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = -4
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
END

If( @rStudentHeightWeight = 1)
BEGIN   
   select @Updatequery=  ' UPDATE  AR  SET Eighth2 = SR.StudentHeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=8 AND  ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = -1 
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET Eighth2 = SR.StudentWeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=8 AND  ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = -2
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
END

If( @rTotalDaysPresentDays = 1)
BEGIN   
   select @Updatequery=  ' UPDATE  AR  SET Eighth2 = SR.TotalDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=8 AND  ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = -3
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET Eighth2 = SR.PresentDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=8 AND  ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = -4
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
END

If( @rStudentHeightWeight = 1)
BEGIN   
    select @Updatequery=  ' UPDATE  AR  SET Ninth2 = SR.StudentHeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=9 AND  ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = -1 
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET Ninth2 = SR.StudentWeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=9 AND  ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = -2
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
END

If( @rTotalDaysPresentDays = 1)
BEGIN   
   select @Updatequery=  ' UPDATE  AR  SET Ninth2 = SR.TotalDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=9 AND  ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = -3
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET Ninth2 = SR.PresentDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=9 AND  ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = -4
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
END

If( @rStudentHeightWeight = 1)
BEGIN   
   select @Updatequery=  ' UPDATE  AR  SET Tenth2 = SR.StudentHeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=10 AND  ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = -1 
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET Tenth2 = SR.StudentWeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=10 AND  ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = -2
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
END

If( @rTotalDaysPresentDays = 1)
BEGIN    
   select @Updatequery=  ' UPDATE  AR  SET Tenth2 = SR.TotalDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=10 AND  ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = -3
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET Tenth2 = SR.PresentDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=10 AND  ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = -4
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
END

If( @rStudentHeightWeight = 1)
BEGIN   
   select @Updatequery=  ' UPDATE  AR  SET Eleventh2 = SR.StudentHeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=11 AND  ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = -1 
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET Eleventh2 = SR.StudentWeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=11 AND  ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = -2
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
END

If( @rTotalDaysPresentDays = 1)
BEGIN   
   select @Updatequery=  ' UPDATE  AR  SET Eleventh2 = SR.TotalDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=11 AND  ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = -3
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET Eleventh2 = SR.PresentDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=11 AND  ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = -4
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
END

If( @rStudentHeightWeight = 1)
BEGIN   
   select @Updatequery=  ' UPDATE  AR  SET Twelfth2 = SR.StudentHeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=12 AND  ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = -1 
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET Twelfth2 = SR.StudentWeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=12 AND  ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = -2
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
END

If( @rTotalDaysPresentDays = 1)
BEGIN   
   select @Updatequery=  ' UPDATE  AR  SET Twelfth2 = SR.TotalDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=12 AND  ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = -3
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET Twelfth2 = SR.PresentDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=12 AND  ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = -4
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
END
END  
   -- Sub Exam 3 Ends   
 --   End Here Height, Weight, TotalDays, PresentDays Update 

 --add for 27332 mantis start
	CREATE TABLE #TempAllBatchClassGroup
	(
		ClassGroupId int,
		ClassGroupName nvarchar(50),
		IsObsolete bit
	)
	INSERT INTO #TempAllBatchClassGroup
	SELECT CM.Id AS ClassGroupId ,
		CM.Title AS ClassGroupName,
		CASE  WHEN BG.ClassGroupId IS null THEN 0 Else 1 END AS IsObsolete
	FROM sSetup.tClassGroupMaster CM
		LEFT JOIN  sAssessment.tAllBatchClassGroup BG  ON CM.Id=BG.ClassGroupId AND BG.OrgId=@rOrgId
	WHERE CM.Id In (103,101,102,104,1,2,3,4,5,6,7,8,9,10,11,12)

	DECLARE @lIsObsoletePG bit, @lIsObsoleteNursary bit, @lIsObsoleteJrKg bit, @lIsObsoleteSrKg bit, @lIsObsoleteFirst bit, @lIsObsoleteSecond bit, @lIsObsoleteThird bit, @lIsObsoleteFourth bit, @lIsObsoleteFifth bit, @lIsObsoleteSixth bit, @lIsObsoleteSeventh bit, @lIsObsoleteEighth bit, @lIsObsoleteNinth bit, @lIsObsoleteTenth bit, @lIsObsoleteEleventh bit, @lIsObsoleteTwelfth bit

	SELECT @lIsObsoletePG = IsObsolete from #TempAllBatchClassGroup WHERE ClassGroupId = 101
	SELECT @lIsObsoleteNursary = IsObsolete from #TempAllBatchClassGroup WHERE ClassGroupId = 102
	SELECT @lIsObsoleteJrKg = IsObsolete from #TempAllBatchClassGroup WHERE ClassGroupId = 103
	SELECT @lIsObsoleteSrKg = IsObsolete from #TempAllBatchClassGroup WHERE ClassGroupId = 104
	SELECT @lIsObsoleteFirst = IsObsolete from #TempAllBatchClassGroup WHERE ClassGroupId = 1
	SELECT @lIsObsoleteSecond = IsObsolete from #TempAllBatchClassGroup WHERE ClassGroupId = 2
	SELECT @lIsObsoleteThird = IsObsolete from #TempAllBatchClassGroup WHERE ClassGroupId = 3
	SELECT @lIsObsoleteFourth = IsObsolete from #TempAllBatchClassGroup WHERE ClassGroupId = 4
	SELECT @lIsObsoleteFifth = IsObsolete from #TempAllBatchClassGroup WHERE ClassGroupId = 5
	SELECT @lIsObsoleteSixth = IsObsolete from #TempAllBatchClassGroup WHERE ClassGroupId = 6
	SELECT @lIsObsoleteSeventh = IsObsolete from #TempAllBatchClassGroup WHERE ClassGroupId = 7
	SELECT @lIsObsoleteEighth = IsObsolete from #TempAllBatchClassGroup WHERE ClassGroupId = 8
	SELECT @lIsObsoleteNinth = IsObsolete from #TempAllBatchClassGroup WHERE ClassGroupId = 9
	SELECT @lIsObsoleteTenth = IsObsolete from #TempAllBatchClassGroup WHERE ClassGroupId = 10
	SELECT @lIsObsoleteEleventh = IsObsolete from #TempAllBatchClassGroup WHERE ClassGroupId = 11
	SELECT @lIsObsoleteTwelfth = IsObsolete from #TempAllBatchClassGroup WHERE ClassGroupId = 12
--27332 mantis end

	If( @rTotalDaysPresentDays = 1 AND @rStudentHeightWeight = 1)	
	BEGIN
	   select @query='SELECT AR.StudentId,
			Case When AR.SubjectId > 0 then SM.Id 
			When AR.SubjectId = -1 then 999999991 
		 	When AR.SubjectId = -2 then 999999992 
		 	When AR.SubjectId = -3 then 999999993
		 	When AR.SubjectId = -4 then 999999994 end AS SubjectId,
			Isnull(PG,'''') AS PG,Isnull(Nursary,'''') AS Nursary,Isnull(SrKg,'''') AS SrKg , Isnull(JrKg,'''') AS JrKg,Isnull(First,'''') AS FirstAnnual,
		 	Isnull(Second,'''') AS Second, Isnull(Third,'''') As  Third, Isnull(Fourth,'''') AS Fourth,Isnull(Fifth,'''') AS Fifth, Isnull(Sixth,'''') AS Sixth, Isnull(Seventh,'''') AS Seventh, Isnull(Eighth,'''') AS Eighth, Isnull(Ninth,'''') AS Ninth, 
		 	Isnull(Tenth,'''') As Tenth, Isnull(Eleventh,'''') As Eleventh, Isnull(Twelfth,'''') As Twelfth ,
		 	Isnull(PG1,'''') AS PG1,Isnull(Nursary1,'''') AS Nursary1,Isnull(SrKg1,'''') AS SrKg1 , Isnull(JrKg1,'''') AS JrKg1,Isnull(First1,'''') AS First1,
		 	Isnull(Second1,'''') AS Second1, Isnull(Third1,'''') As  Third1, Isnull(Fourth1,'''') AS Fourth1,Isnull(Fifth1,'''') AS Fifth1, Isnull(Sixth1,'''') AS Sixth1, Isnull(Seventh1,'''') AS Seventh1, Isnull(Eighth1,'''') AS Eighth1, Isnull(Ninth1,'''') AS Ninth1, 
		 	Isnull(Tenth1,'''') As Tenth1, Isnull(Eleventh1,'''') As Eleventh1, Isnull(Twelfth1,'''') As Twelfth1,
		 	Isnull(PG2,'''') AS PG2,Isnull(Nursary2,'''') AS Nursary2,Isnull(SrKg2,'''') AS SrKg2 , Isnull(JrKg2,'''') AS JrKg2,Isnull(First2,'''') AS First2,
		 	Isnull(Second2,'''') AS Second2, Isnull(Third2,'''') As  Third2, Isnull(Fourth2,'''') AS Fourth2,Isnull(Fifth2,'''') AS Fifth2, Isnull(Sixth2,'''') AS Sixth2, Isnull(Seventh2,'''') AS Seventh2, Isnull(Eighth2,'''') AS Eighth2, Isnull(Ninth2,'''') AS Ninth2, 
		 	Isnull(Tenth2,'''') As Tenth2, Isnull(Eleventh2,'''') As Eleventh2, Isnull(Twelfth2,'''') As Twelfth2
		 	,Case When AR.SubjectId > 0 then SM.Code 
		 	When AR.SubjectId = -1 then ''HEIGHT'' 
		 	When AR.SubjectId = -2 then ''WEIGHT'' 
		 	When AR.SubjectId = -3 then ''TOTAL DAYS'' 
		 	When AR.SubjectId = -4 then ''PRESENT DAYS''		 	
		 	end As SubjectCode,A.Code,A.Name,A.BatchName,A.BatchId,SM.OrderIndex,A.RollNo,
			'+convert(varchar,@lIsObsoletePG)+' AS IsObsoletePG, ' + convert(varchar,@lIsObsoleteNursary) + ' AS IsObsoleteNursary, 
			' + convert(varchar,@lIsObsoleteJrKg) + ' AS IsObsoleteJrKg, ' + convert(varchar,@lIsObsoleteSrKg) + ' AS IsObsoleteSrKg,
			' + convert(varchar,@lIsObsoleteFirst) + ' AS IsObsoleteFirst, ' + convert(varchar,@lIsObsoleteSecond) + ' AS IsObsoleteSecond, 
			' + convert(varchar,@lIsObsoleteThird) + ' AS IsObsoleteThird, ' + convert(varchar,@lIsObsoleteFourth) + ' AS IsObsoleteFourth,
			' + convert(varchar,@lIsObsoleteFifth) + ' AS IsObsoleteFifth, ' + convert(varchar,@lIsObsoleteSixth) + ' AS IsObsoleteSixth, 
			' + convert(varchar,@lIsObsoleteSeventh) + ' AS IsObsoleteSeventh, ' + convert(varchar,@lIsObsoleteEighth) + ' AS IsObsoleteEighth,
			' + convert(varchar,@lIsObsoleteNinth) + ' AS IsObsoleteNinth, ' + convert(varchar,@lIsObsoleteTenth) + ' AS IsObsoleteTenth, 
			' + convert(varchar,@lIsObsoleteEleventh) + ' AS IsObsoleteEleventh, ' + convert(varchar,@lIsObsoleteTwelfth) + ' AS IsObsoleteTwelfth 	
		    FROM sStudent.vStudentLastAcademic A  
		    INNER JOIN  sAssessment.tAllBatchResultGrade AR ON  AR.StudentId=A.StudentId 
	        LEFT JOIN sSetup.tSubjectMaster SM ON SM.Id=AR.SubjectId 
		    WHERE A.OrgId=' + convert(varchar,@lOrgId) + ''
		execute (@query)	
	END
	
	If( @rStudentHeightWeight = 1)	
	BEGIN
	   select @query='SELECT AR.StudentId,
			Case When AR.SubjectId > 0 then SM.Id 
			When AR.SubjectId = -1 then 999999991 
		 	When AR.SubjectId = -2 then 999999992 end AS SubjectId,		 	
			Isnull(PG,'''') AS PG,Isnull(Nursary,'''') AS Nursary,Isnull(SrKg,'''') AS SrKg , Isnull(JrKg,'''') AS JrKg,Isnull(First,'''') AS FirstAnnual,
		 	Isnull(Second,'''') AS Second, Isnull(Third,'''') As  Third, Isnull(Fourth,'''') AS Fourth,Isnull(Fifth,'''') AS Fifth, Isnull(Sixth,'''') AS Sixth, Isnull(Seventh,'''') AS Seventh, Isnull(Eighth,'''') AS Eighth, Isnull(Ninth,'''') AS Ninth, 
		 	Isnull(Tenth,'''') As Tenth, Isnull(Eleventh,'''') As Eleventh, Isnull(Twelfth,'''') As Twelfth ,
		 	Isnull(PG1,'''') AS PG1,Isnull(Nursary1,'''') AS Nursary1,Isnull(SrKg1,'''') AS SrKg1 , Isnull(JrKg1,'''') AS JrKg1,Isnull(First1,'''') AS First1,
		 	Isnull(Second1,'''') AS Second1, Isnull(Third1,'''') As  Third1, Isnull(Fourth1,'''') AS Fourth1,Isnull(Fifth1,'''') AS Fifth1, Isnull(Sixth1,'''') AS Sixth1, Isnull(Seventh1,'''') AS Seventh1, Isnull(Eighth1,'''') AS Eighth1, Isnull(Ninth1,'''') AS Ninth1, 
		 	Isnull(Tenth1,'''') As Tenth1, Isnull(Eleventh1,'''') As Eleventh1, Isnull(Twelfth1,'''') As Twelfth1,
		 	Isnull(PG2,'''') AS PG2,Isnull(Nursary2,'''') AS Nursary2,Isnull(SrKg2,'''') AS SrKg2 , Isnull(JrKg2,'''') AS JrKg2,Isnull(First2,'''') AS First2,
		 	Isnull(Second2,'''') AS Second2, Isnull(Third2,'''') As  Third2, Isnull(Fourth2,'''') AS Fourth2,Isnull(Fifth2,'''') AS Fifth2, Isnull(Sixth2,'''') AS Sixth2, Isnull(Seventh2,'''') AS Seventh2, Isnull(Eighth2,'''') AS Eighth2, Isnull(Ninth2,'''') AS Ninth2, 
		 	Isnull(Tenth2,'''') As Tenth2, Isnull(Eleventh2,'''') As Eleventh2, Isnull(Twelfth2,'''') As Twelfth2
		 	,Case When AR.SubjectId > 0 then SM.Code 
		 	When AR.SubjectId = -1 then ''HEIGHT'' 
		 	When AR.SubjectId = -2 then ''WEIGHT'' 
		 	end As SubjectCode,A.Code,A.Name,A.BatchName,A.BatchId,SM.OrderIndex,A.RollNo,
			'+convert(varchar,@lIsObsoletePG)+' AS IsObsoletePG, ' + convert(varchar,@lIsObsoleteNursary) + ' AS IsObsoleteNursary, 
			' + convert(varchar,@lIsObsoleteJrKg) + ' AS IsObsoleteJrKg, ' + convert(varchar,@lIsObsoleteSrKg) + ' AS IsObsoleteSrKg,
			' + convert(varchar,@lIsObsoleteFirst) + ' AS IsObsoleteFirst, ' + convert(varchar,@lIsObsoleteSecond) + ' AS IsObsoleteSecond, 
			' + convert(varchar,@lIsObsoleteThird) + ' AS IsObsoleteThird, ' + convert(varchar,@lIsObsoleteFourth) + ' AS IsObsoleteFourth,
			' + convert(varchar,@lIsObsoleteFifth) + ' AS IsObsoleteFifth, ' + convert(varchar,@lIsObsoleteSixth) + ' AS IsObsoleteSixth, 
			' + convert(varchar,@lIsObsoleteSeventh) + ' AS IsObsoleteSeventh, ' + convert(varchar,@lIsObsoleteEighth) + ' AS IsObsoleteEighth,
			' + convert(varchar,@lIsObsoleteNinth) + ' AS IsObsoleteNinth, ' + convert(varchar,@lIsObsoleteTenth) + ' AS IsObsoleteTenth, 
			' + convert(varchar,@lIsObsoleteEleventh) + ' AS IsObsoleteEleventh, ' + convert(varchar,@lIsObsoleteTwelfth) + ' AS IsObsoleteTwelfth 	
		    FROM sStudent.vStudentLastAcademic A  
		    INNER JOIN  sAssessment.tAllBatchResultGrade AR ON  AR.StudentId=A.StudentId 
	        LEFT JOIN sSetup.tSubjectMaster SM ON SM.Id=AR.SubjectId 
		    WHERE A.OrgId=' + convert(varchar,@lOrgId) + ''
	   execute (@query)	
	END
	
	IF( @rTotalDaysPresentDays = 1)	
	BEGIN
       select @query='SELECT AR.StudentId,
			Case When AR.SubjectId > 0 then SM.Id
		 	When AR.SubjectId = -3 then 999999993
		 	When AR.SubjectId = -4 then 999999994 end AS SubjectId,
			Isnull(PG,'''') AS PG,Isnull(Nursary,'''') AS Nursary,Isnull(SrKg,'''') AS SrKg , Isnull(JrKg,'''') AS JrKg,Isnull(First,'''') AS FirstAnnual,
		 	Isnull(Second,'''') AS Second, Isnull(Third,'''') As  Third, Isnull(Fourth,'''') AS Fourth,Isnull(Fifth,'''') AS Fifth, Isnull(Sixth,'''') AS Sixth, Isnull(Seventh,'''') AS Seventh, Isnull(Eighth,'''') AS Eighth, Isnull(Ninth,'''') AS Ninth, 
		 	Isnull(Tenth,'''') As Tenth, Isnull(Eleventh,'''') As Eleventh, Isnull(Twelfth,'''') As Twelfth ,
		 	Isnull(PG1,'''') AS PG1,Isnull(Nursary1,'''') AS Nursary1,Isnull(SrKg1,'''') AS SrKg1 , Isnull(JrKg1,'''') AS JrKg1,Isnull(First1,'''') AS First1,
		 	Isnull(Second1,'''') AS Second1, Isnull(Third1,'''') As  Third1, Isnull(Fourth1,'''') AS Fourth1,Isnull(Fifth1,'''') AS Fifth1, Isnull(Sixth1,'''') AS Sixth1, Isnull(Seventh1,'''') AS Seventh1, Isnull(Eighth1,'''') AS Eighth1, Isnull(Ninth1,'''') AS Ninth1, 
		 	Isnull(Tenth1,'''') As Tenth1, Isnull(Eleventh1,'''') As Eleventh1, Isnull(Twelfth1,'''') As Twelfth1,
		 	Isnull(PG2,'''') AS PG2,Isnull(Nursary2,'''') AS Nursary2,Isnull(SrKg2,'''') AS SrKg2 , Isnull(JrKg2,'''') AS JrKg2,Isnull(First2,'''') AS First2,
		 	Isnull(Second2,'''') AS Second2, Isnull(Third2,'''') As  Third2, Isnull(Fourth2,'''') AS Fourth2,Isnull(Fifth2,'''') AS Fifth2, Isnull(Sixth2,'''') AS Sixth2, Isnull(Seventh2,'''') AS Seventh2, Isnull(Eighth2,'''') AS Eighth2, Isnull(Ninth2,'''') AS Ninth2, 
		 	Isnull(Tenth2,'''') As Tenth2, Isnull(Eleventh2,'''') As Eleventh2, Isnull(Twelfth2,'''') As Twelfth2
		 	,Case When AR.SubjectId > 0 then SM.Code
		 	When AR.SubjectId = -3 then ''TOTAL DAYS'' 
		 	When AR.SubjectId = -4 then ''PRESENT DAYS''
		 	end As SubjectCode,A.Code,A.Name,A.BatchName,A.BatchId,SM.OrderIndex,A.RollNo,
			'+convert(varchar,@lIsObsoletePG)+' AS IsObsoletePG, ' + convert(varchar,@lIsObsoleteNursary) + ' AS IsObsoleteNursary, 
			' + convert(varchar,@lIsObsoleteJrKg) + ' AS IsObsoleteJrKg, ' + convert(varchar,@lIsObsoleteSrKg) + ' AS IsObsoleteSrKg,
			' + convert(varchar,@lIsObsoleteFirst) + ' AS IsObsoleteFirst, ' + convert(varchar,@lIsObsoleteSecond) + ' AS IsObsoleteSecond, 
			' + convert(varchar,@lIsObsoleteThird) + ' AS IsObsoleteThird, ' + convert(varchar,@lIsObsoleteFourth) + ' AS IsObsoleteFourth,
			' + convert(varchar,@lIsObsoleteFifth) + ' AS IsObsoleteFifth, ' + convert(varchar,@lIsObsoleteSixth) + ' AS IsObsoleteSixth, 
			' + convert(varchar,@lIsObsoleteSeventh) + ' AS IsObsoleteSeventh, ' + convert(varchar,@lIsObsoleteEighth) + ' AS IsObsoleteEighth,
			' + convert(varchar,@lIsObsoleteNinth) + ' AS IsObsoleteNinth, ' + convert(varchar,@lIsObsoleteTenth) + ' AS IsObsoleteTenth, 
			' + convert(varchar,@lIsObsoleteEleventh) + ' AS IsObsoleteEleventh, ' + convert(varchar,@lIsObsoleteTwelfth) + ' AS IsObsoleteTwelfth 	
		    FROM sStudent.vStudentLastAcademic A  
		    INNER JOIN  sAssessment.tAllBatchResultGrade AR ON  AR.StudentId=A.StudentId 
	        LEFT JOIN sSetup.tSubjectMaster SM ON SM.Id=AR.SubjectId 
		    WHERE A.OrgId=' + convert(varchar,@lOrgId) + ''
		execute (@query)	
	END
	
	ELSE
	BEGIN	
	   select @query='SELECT AR.StudentId,SM.Id AS SubjectId,Isnull(PG,'''') AS PG,Isnull(Nursary,'''') AS Nursary,Isnull(SrKg,'''') AS SrKg , Isnull(JrKg,'''') AS JrKg,Isnull(First,'''') AS FirstAnnual,
		 	Isnull(Second,'''') AS Second, Isnull(Third,'''') As  Third, Isnull(Fourth,'''') AS Fourth,Isnull(Fifth,'''') AS Fifth, Isnull(Sixth,'''') AS Sixth, Isnull(Seventh,'''') AS Seventh, Isnull(Eighth,'''') AS Eighth, Isnull(Ninth,'''') AS Ninth, 
		 	Isnull(Tenth,'''') As Tenth, Isnull(Eleventh,'''') As Eleventh, Isnull(Twelfth,'''') As Twelfth ,
		 	Isnull(PG1,'''') AS PG1,Isnull(Nursary1,'''') AS Nursary1,Isnull(SrKg1,'''') AS SrKg1 , Isnull(JrKg1,'''') AS JrKg1,Isnull(First1,'''') AS First1,
		 	Isnull(Second1,'''') AS Second1, Isnull(Third1,'''') As  Third1, Isnull(Fourth1,'''') AS Fourth1,Isnull(Fifth1,'''') AS Fifth1, Isnull(Sixth1,'''') AS Sixth1, Isnull(Seventh1,'''') AS Seventh1, Isnull(Eighth1,'''') AS Eighth1, Isnull(Ninth1,'''') AS Ninth1, 
		 	Isnull(Tenth1,'''') As Tenth1, Isnull(Eleventh1,'''') As Eleventh1, Isnull(Twelfth1,'''') As Twelfth1,
		 	Isnull(PG2,'''') AS PG2,Isnull(Nursary2,'''') AS Nursary2,Isnull(SrKg2,'''') AS SrKg2 , Isnull(JrKg2,'''') AS JrKg2,Isnull(First2,'''') AS First2,
		 	Isnull(Second2,'''') AS Second2, Isnull(Third2,'''') As  Third2, Isnull(Fourth2,'''') AS Fourth2,Isnull(Fifth2,'''') AS Fifth2, Isnull(Sixth2,'''') AS Sixth2, Isnull(Seventh2,'''') AS Seventh2, Isnull(Eighth2,'''') AS Eighth2, Isnull(Ninth2,'''') AS Ninth2, 
		 	Isnull(Tenth2,'''') As Tenth2, Isnull(Eleventh2,'''') As Eleventh2, Isnull(Twelfth2,'''') As Twelfth2
		 	,SM.Code As SubjectCode,A.Code,A.Name,A.BatchName,A.BatchId,SM.OrderIndex,A.RollNo,
			'+convert(varchar,@lIsObsoletePG)+' AS IsObsoletePG, ' + convert(varchar,@lIsObsoleteNursary) + ' AS IsObsoleteNursary, 
			' + convert(varchar,@lIsObsoleteJrKg) + ' AS IsObsoleteJrKg, ' + convert(varchar,@lIsObsoleteSrKg) + ' AS IsObsoleteSrKg,
			' + convert(varchar,@lIsObsoleteFirst) + ' AS IsObsoleteFirst, ' + convert(varchar,@lIsObsoleteSecond) + ' AS IsObsoleteSecond, 
			' + convert(varchar,@lIsObsoleteThird) + ' AS IsObsoleteThird, ' + convert(varchar,@lIsObsoleteFourth) + ' AS IsObsoleteFourth,
			' + convert(varchar,@lIsObsoleteFifth) + ' AS IsObsoleteFifth, ' + convert(varchar,@lIsObsoleteSixth) + ' AS IsObsoleteSixth, 
			' + convert(varchar,@lIsObsoleteSeventh) + ' AS IsObsoleteSeventh, ' + convert(varchar,@lIsObsoleteEighth) + ' AS IsObsoleteEighth,
			' + convert(varchar,@lIsObsoleteNinth) + ' AS IsObsoleteNinth, ' + convert(varchar,@lIsObsoleteTenth) + ' AS IsObsoleteTenth, 
			' + convert(varchar,@lIsObsoleteEleventh) + ' AS IsObsoleteEleventh, ' + convert(varchar,@lIsObsoleteTwelfth) + ' AS IsObsoleteTwelfth 	
		    FROM sStudent.vStudentLastAcademic A  
		    INNER JOIN sAssessment.tAllBatchResultGrade AR ON  AR.StudentId=A.StudentId 
	        LEFT JOIN sSetup.tSubjectMaster SM ON SM.Id=AR.SubjectId 
		    WHERE A.OrgId=' + convert(varchar,@lOrgId) + ''	
	    execute (@query)
		print @query

		DROP TABLE #TempAllBatchClassGroup

	--SELECT
	--	CONVERT(BIGINT, 0) AS StudentId,
	--	0 AS SubjectId,
	--	CONVERT(NVARCHAR(10),'') AS PG,
	--	CONVERT(NVARCHAR(10),'') AS Nursary,
	--	CONVERT(NVARCHAR(10),'') AS SrKg,
	--	CONVERT(NVARCHAR(10),'') AS JrKg,
	--	CONVERT(NVARCHAR(10),'') AS FirstAnnual,
	--	CONVERT(NVARCHAR(10),'') AS Second, 
	--	CONVERT(NVARCHAR(10),'') As  Third, 
	--	CONVERT(NVARCHAR(10),'') AS Fourth,
	--	CONVERT(NVARCHAR(10),'') AS Fifth, 
	--	CONVERT(NVARCHAR(10),'') AS Sixth, 
	--	CONVERT(NVARCHAR(10),'') AS Seventh, 
	--	CONVERT(NVARCHAR(10),'') AS Eighth, 
	--	CONVERT(NVARCHAR(10),'') AS Ninth, 
	--	CONVERT(NVARCHAR(10),'') As Tenth, 
	--	CONVERT(NVARCHAR(10),'') As Eleventh, 
	--	CONVERT(NVARCHAR(10),'') As Twelfth ,
	--	CONVERT(NVARCHAR(10),'') AS PG1,
	--	CONVERT(NVARCHAR(10),'') AS Nursary1,
	--	CONVERT(NVARCHAR(10),'') AS SrKg1 , 
	--	CONVERT(NVARCHAR(10),'') AS JrKg1,
	--	CONVERT(NVARCHAR(10),'') AS First1,
	--	CONVERT(NVARCHAR(10),'') AS Second1, 
	--	CONVERT(NVARCHAR(10),'') As  Third1, 
	--	CONVERT(NVARCHAR(10),'') AS Fourth1,
	--	CONVERT(NVARCHAR(10),'') AS Fifth1, 
	--	CONVERT(NVARCHAR(10),'') AS Sixth1, 
	--	CONVERT(NVARCHAR(10),'') AS Seventh1, 
	--	CONVERT(NVARCHAR(10),'') AS Eighth1, 
	--	CONVERT(NVARCHAR(10),'') AS Ninth1, 
	--	CONVERT(NVARCHAR(10),'') As Tenth1, 
	--	CONVERT(NVARCHAR(10),'') As Eleventh1, 
	--	CONVERT(NVARCHAR(10),'') As Twelfth1,
	--	CONVERT(NVARCHAR(10),'') AS PG2,
	--	CONVERT(NVARCHAR(10),'') AS Nursary2,
	--	CONVERT(NVARCHAR(10),'') AS SrKg2 , 
	--	CONVERT(NVARCHAR(10),'') AS JrKg2,
	--	CONVERT(NVARCHAR(10),'') AS First2,
	--	CONVERT(NVARCHAR(10),'') AS Second2, 
	--	CONVERT(NVARCHAR(10),'') As  Third2, 
	--	CONVERT(NVARCHAR(10),'') AS Fourth2,
	--	CONVERT(NVARCHAR(10),'') AS Fifth2, 
	--	CONVERT(NVARCHAR(10),'') AS Sixth2, 
	--	CONVERT(NVARCHAR(10),'') AS Seventh2, 
	--	CONVERT(NVARCHAR(10),'') AS Eighth2, 
	--	CONVERT(NVARCHAR(10),'') AS Ninth2, 
	--	CONVERT(NVARCHAR(10),'') As Tenth2, 
	--	CONVERT(NVARCHAR(10),'') As Eleventh2, 
	--	CONVERT(NVARCHAR(10),'') As Twelfth2,
	--	CONVERT(NVARCHAR(20),'') AS SubjectCode,
	--	CONVERT(NVARCHAR(20),'') as Code,
	--	CONVERT(NVARCHAR(300),'') as Name,
	--	CONVERT(NVARCHAR(100),'') as BatchName,
	--	0 as BatchId,
	--	CONVERT(SMALLINT,0) AS OrderIndex,
	--	0 AS RollNo,
	--	CONVERT(BIT,0) AS IsObsoletePG,
	--	CONVERT(BIT,0) AS IsObsoleteNursary,
	--	CONVERT(BIT,0) AS IsObsoleteJrKg,
	--	CONVERT(BIT,0) AS IsObsoleteSrKg,
	--	CONVERT(BIT,0) AS IsObsoleteFirst,
	--	CONVERT(BIT,0) AS IsObsoleteSecond,
	--	CONVERT(BIT,0) AS IsObsoleteThird,
	--	CONVERT(BIT,0) AS IsObsoleteFourth,
	--	CONVERT(BIT,0) AS IsObsoleteFifth,
	--	CONVERT(BIT,0) AS IsObsoleteSixth,
	--	CONVERT(BIT,0) AS IsObsoleteSeventh,
	--	CONVERT(BIT,0) AS IsObsoleteEighth,
	--	CONVERT(BIT,0) AS IsObsoleteNinth,
	--	CONVERT(BIT,0) AS IsObsoleteTenth,
	--	CONVERT(BIT,0) AS IsObsoleteEleventh,
	--	CONVERT(BIT,0) AS IsObsoleteTwelfth
		
END
GO
PRINT N'Altering Procedure [sAssessment].[pRptProgressCardGet]...';


GO

ALTER PROCEDURE [sAssessment].[pRptProgressCardGet]	 	 
	 @rClassId int,
	 @rBatchId int,
	 @rDivisionId int,	 
	 @rClassSubjectIdStr nvarchar(max),
	 @rExamGroupIdStr nvarchar(max),
	 @rFromDate Date='',
	 @rToDate Date='',
	 @rFromRollNo int=0,
	 @rToRollNo int=0,
	 @rAcadedmidId bigint=0
	
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 

 --Select * from dbo.TempTableForProgress
	--SELECT 
	--	Convert(BigInt,0) AS AcademicId,
	--	Convert(date,'') AS ExamDate,
	--	Convert(Decimal,0) AS Maximum,
	--	Convert(Decimal,0) AS Obtain,
	--	Convert(Decimal,0) AS Percentage,
	--	'' AS ExamTopic,
	--	'' AS SubjectName,
	--	'' AS ExamGroup,
	--	Convert(varbinary,0) AS StudentPhoto,
	--	'' AS ClassName,
	--	'' AS DivisionName,
	--	'' AS StudentName,
	--	0 AS RollNo,
	--    Convert(bit,0) AS IsMarksInDecimal,
	--	'' AS Year,
	--	'' AS MonthFrom,
	--	'' AS MonthTo,
	--	'' AS Code,
	--	'' AS EXAMNAME,
	--	'' AS ResultStatus,
	--	Convert(bit,0) As IsPresent

		

	CREATE TABLE #tempProgressCard
	(
		Id int Identity,
		AcademicId Bigint,
		ClassSubjectId bigint,
		ExamDate Date,
		Obtain Decimal(6,2),
		Maximum Decimal(6,2),
		Percentage Decimal(6,2),
		ExamId int,
		IsPresent bit
		
	)
 
 DECLARE @query  AS NVARCHAR(MAX)
 set @query = 'INSERT INTO #tempProgressCard 
 SELECT	R.AcademicId,ED.ClassSubjectId,ED.ExamDate ,SUM(RD.Obtain) AS Obtain,SUM(ED.Maximum) AS Maximum,
 (SUM(RD.Obtain)/SUM(ED.Maximum))*100 AS PERCENTAGE,ED.ExamId,RD.IsPresent
FROM sAssessment.tExamMaster EM INNER JOIN sAssessment.tResult R ON R.ExamId = EM.Id
INNER JOIN sAssessment.tResultDetail RD ON RD.ResultId = R.Id
INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId = EM.Id AND ED.Id = RD.ExamDetailId
INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId
INNER JOIN sAssessment.tExamGroupMaster EGM ON EGM.Id = ESGM.ExamGroupId
INNER JOIN sStudent.tAcademic AM ON AM.Id = R.AcademicId
WHERE EM.ClassId =' + CONVERT(NVARCHAR,@rClassId) + '
 

AND AM.DivisionId = ' + CONVERT(NVARCHAR(500),@rDivisionId) + '
AND EGM.Id IN (' + CONVERT(NVARCHAR(500),@rExamGroupIdStr) + ')
AND ED.ClassSubjectId IN (' + CONVERT(NVARCHAR(500),@rClassSubjectIdStr) + ')
AND ED.EXAMDATE >= ''' + CONVERT(NVARCHAR,@rFromDate) +
''' AND ED.EXAMDATE <= ''' + CONVERT(NVARCHAR,@rToDate) +
''' AND ((AM.RollNo >= '''+ CONVERT(NVARCHAR(10),@rFromRollNo)+''') OR (' + CONVERT(NVARCHAR(10),@rFromRollNo)+'='''+ CONVERT(NVARCHAR(10),0) + ''')) 
AND ((AM.RollNo <= '''+ CONVERT(NVARCHAR(10),@rToRollNo) + ''' ) OR (' + CONVERT(NVARCHAR(10),@rToRollNo)+'='''+ CONVERT(NVARCHAR(10),0) + ''')) 
AND ((AM.Id = '''+ CONVERT(NVARCHAR(20),@rAcadedmidId) + ''' ) OR (' + CONVERT(NVARCHAR(20),@rAcadedmidId)+'='''+ CONVERT(NVARCHAR(20),0) + ''')) 
GROUP BY R.AcademicId,ED.ClassSubjectId,ED.ExamDate,ED.ExamId,RD.IsPresent'
-- Remove RD.IsPresent = 1 Condition from @query (As requirement Absent and present students data should be visibled) Mantis :0027445
 --print @query
execute(@query)

-- To maintain Group Footer length add in report row	
--select 1, '.' + replicate('`', 600)  + '.'   font size 1

SELECT
T.AcademicId,
T.ExamDate,
T.Maximum,T.Obtain,T.Percentage,
CASE WHEN ED.ExamTopic = '0' THEN '' ELSE ED.ExamTopic  END AS ExamTopic,
CS.SubjectName AS SubjectName,
EGM.Title AS ExamGroup,
SF.StudentPhoto as StudentPhoto , 
SF.ClassName,
SF.DivisionName,
SF.Name AS StudentName,SF.RollNo, 
EM.IsMarksInDecimal,
SF.Code,
sCommon.fGetMonthName(DatePart(MM,@rFromDate)) AS MonthFrom,
sCommon.fGetMonthName(DatePart(MM,@rToDate)) AS MonthTo,
BM.Title AS Year,
ISNULL(ESGM.Title,'') AS EXAMNAME ,
(Select ResultStatus FROM sAssessment.tResult Where AcademicId = T.AcademicId AND  ExamId = EM.Id)AS ResultStatus,
T.IsPresent



FROM #tempProgressCard T 
INNER JOIN sAssessment.tExamMaster EM on EM.Id=T.ExamId
INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId = T.ExamId AND EM.Id=ED.ExamId AND T.ExamDate = ED.ExamDate
INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id = EM.EXAMSUBGROUPID
INNER JOIN sAssessment.tExamGroupMaster EGM ON EGM.Id = ESGM.ExamGroupId
--INNER JOIN sAssessment.tExamCombine EC ON EC.SubExamId=EM.Id
INNER JOIN sSetup.vClassSubject CS ON CS.ClassSubjectId = ED.ClassSubjectId AND CS.ClassSubjectId=T.ClassSubjectId 
INNER JOIN sStudent.vStudentFull SF ON SF.AcademicId	= T.AcademicId AND SF.StatusId=1
INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SF.BatchId
Order By SF.RollNo,CS.OrderIndex,T.ExamDate Desc



DROP TABLE #tempProgressCard

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


GO


ALTER PROCEDURE [sAssessment].[pRptProgressCardSubjectWiseDetailsGet]
	 
	 @rBuilder1 nvarchar(max)='', 
	 @rBuilder2 nvarchar(max)='', 
	 @rBatchId int = 0,
	 @rClassId int=0,
	 @rDivisionId int=0,
	 @rExamId int,
	 @rCode nvarchar(20)='',
	 @rFromRollNo int,
	 @rToRollNo int,
	 @rStatusId int=0,
	 @rClassStatusId int=0
	 
	
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	--Select
	--	'' AS Builder1,
	--	'' AS Builder2,
	--	'' AS AcademicIdText,
	--	'' Code,
	--	'' AS Name,
	--		0 AS RollNo,
	--	Convert(BigInt,0) AcademicId,			
	--	'' ResultStatus,
	--	'' AS Class,
	--	'' AS Division,
	--  0 AS ExamId,
	--	'' AS ExamName,
	--  Convert(Date,null) AS ExamDate,
	--		Convert(Decimal,0) TotalMark,
	--	Convert(Decimal,0) TotalObtain,
	--	0 AS RankNumber,
	--	Convert(Decimal,0) Percentage,
	--	'' AS ResultGrade,
	--	Convert(Decimal,0) Percentile,
	--	Convert(BigInt,0) ResultDetailId,		
	--	Convert(Bit,0) IsDisplayInMarksheet,
	--	Convert(Bit,0) IsShowSubjectGrade,
	--	Convert(Bit,0) IsIncludeInTotal,
	--	Convert(Decimal,0) AS SubjectObtain,
	--  '' AS SubjectGrade,
	--	Convert(Decimal,0) AS SubjectMinimum,
	--	Convert(Decimal,0) AS SubjectMaximum,
	--		'' AS SubjectCode,
	--	'' AS SubjectName,
	--	0 AS SubjectOrderIndex,
	--	Convert(BigInt,0) AS ResultId,
	--	0 AS SubjectId,			 	
	--	Convert(Bit,0) IsMarksInDecimal,		
	--	'' AS Remark1,
	--	'' AS Remark2,
	--	'' AS Remark3,
	--	'' AS DisplayTitle,
	--	Convert(Bit,0) IsRankNo, 
	--	Convert(Bit,0) IsGrade,
	--	Convert(Bit,0) IsPercentile,
	--	Convert(Bit,0) IsPercentage,
	--	Convert(Bit,0) IsSubjectPercentile,
	--	Convert(Bit,0) IsProcessResult,			 
	--	Convert(Bit,0) IsNegativeMarks,
	--	Convert(Bit,0) IsIncludeCoScholastic,
	--	Convert(Bit,0) IsOnPrePrinted,
	--	Convert(Bit,0) IsDisplayPhoto,
	--	Convert(Bit,0) IsDisplayBirthDate,
	--	Convert(Bit,0) IsLockForEdit,
	--	Convert(Bit,0) IsDisplaySchoolName,			
	--	Convert(Bit,0) IsDisplayAttendance,
	--	Convert(Bit,0) IsDisplayHeightWeight,
	--	Convert(Bit,0) IsResultStatus,
	--  '' AS IsDisplayMonthlyAttendanceText,
	--  Convert(Bit,0) IsDisplayMonthlyAttendance,
	--	'' AS FooterAdjustmentText,
	--	'' AS DetailAdjustmentText,
	--	0 AS FooterAdjustment,
	--	0 AS DetailAdjustment,		 		 		 
	--	Convert(Bit,0) IsPresent,			
	--	'' SmallAddress1,
	--	Convert(Bit,0) IsDisplayParentName,				
	--	Convert(Bit,0) AS IsShowSubjectMark,			
	--	Convert(Bit,0) IsDisplayTeacherSign,
	--	Convert(Bit,0) IsDisplayPrincipalSign,		 			 
	--	Convert(Bit,0) AS IsImageHeader,			 
	--	'' AS DecimalFormat,	 			 
	--	'' AS FatherName,
	--	'' AS MotherName,
	--  0 AS SubjectCount
	

CREATE TABLE #TempExam
(
    Id int IDENTITY(1,1) PRIMARY KEY,
    ExamId int,
    Exam nvarchar(100)
)

INSERT INTO #TempExam
(
	 ExamId,
	 Exam 	
)

SELECT 
@rExamId AS ExamId,
ESGM.Title AS Exam
FROM [sAssessment].[tExamMaster] EM 
INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.ID = EM.ExamSubGroupId 
WHERE EM.ClassId=@rClassId AND EM.BatchId =@rBatchId AND EM.Id = @rExamId

UNION ALL

SELECT 
EM.Id AS ExamId,
ESGM.Code AS Exam
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 =@rExamId  AND (EM.ClassId=@rClassId) AND EM.BatchId =@rBatchId

UNION ALL 

SELECT
EM.Id AS ExamId,
ESGM.Title AS Exam
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)  AND (EM.ClassId=@rClassId) AND EM.BatchId =@rBatchId

CREATE TABLE #TempSubjectCount(
ExamId int,
AcademicId BigInt,
SubjectCount int
)
INSERT INTO #TempSubjectCount(ExamId, AcademicId, SubjectCount)
    SELECT R.ExamId, R.AcademicId, COUNT(RD.Id) AS SubjectCount
    FROM sAssessment.tResultDetail RD
	INNER JOIN sAssessment.tResult R ON R.Id = RD.ResultId
    INNER JOIN #TempExam TE ON TE.ExamId = R.ExamId
    GROUP BY R.ExamId,R.AcademicId

--select * from #TempExam
	
	SELECT 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			Convert(nvarchar(20),A.Id) AS AcademicIdText,
			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,
			EC.ExamId,
			EC.Exam AS ExamName,
			ED.ExamDate,
			R.TotalMarks AS TotalMark,
			R.TotalObtain,
			R.RankNumber,
			R.Percentage,
			R.ResultGrade,
			R.Percentile,			
			RD.Id AS ResultDetailId,		
			ED.IsDisplayInMarksheet,
			ED.IsShowSubjectGrade,
			ED.IsIncludeInTotal,
			RD.Obtain AS SubjectObtain,
			RD.SubjectGrade,
			ED.Minimum AS SubjectMinimum,
			ED.Maximum AS SubjectMaximum,			
			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.IsNegativeMarks,
			EM.IsIncludeCoScholastic,
			EM.IsOnPrePrinted,
			EM.IsDisplayPhoto,
			EM.IsDisplayBirthDate,
			EM.IsLockForEdit,
			EM.IsDisplaySchoolName,			
			EM.IsDisplayAttendance,
			EM.IsDisplayHeightWeight,
			EM.IsResultStatus,
			Convert(nvarchar(20),ISNULL(EM.IsDisplayMonthlyAttendance,0)) AS IsDisplayMonthlyAttendanceText,
			ISNULL(EM.IsDisplayMonthlyAttendance,0) AS IsDisplayMonthlyAttendance,
			REPLICATE(',',EM.FooterAdjustment) AS FooterAdjustmentText,
			REPLICATE(',',EM.DetailAdjustment) AS DetailAdjustmentText,
			EM.FooterAdjustment,
			EM.DetailAdjustment,		 		 		 
			RD.IsPresent,	
			OM.SmallAddress1,
			EM.IsDisplayParentName,			 
			ISNULL(ED.IsShowSubjectMark,1) AS IsShowSubjectMark,			
			EM.IsDisplayTeacherSign,
			Em.IsDisplayPrincipalSign,		 		 
			ISNULL(EM.IsDisplayImageHeader,0) AS IsImageHeader,			 
			EM.DecimalFormat,						 
			SF.FatherName,
			SF.MotherName,
			TSC.SubjectCount AS SubjectCount
						
	FROM 
			sAssessment.tResultDetail RD
			INNER JOIN sAssessment.tResult R ON R.Id = RD.ResultId
			INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId
			INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId		
			INNER JOIN #TempExam EC ON EC.ExamId = EM.Id 	
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=CS.SubjectId					 
			INNER JOIN sStudent.tAcademic A ON A.Id=R.AcademicId	
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId		
			INNER JOIN sStudent.tStudentMaster StuM ON StuM.Id=A.StudentId			
			INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId
			INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId			
			INNER JOIN sSetup.tOrganizationMaster OM ON StuM.OrgId = OM.Id			
			LEFT JOIN sAssessment.tStudentRemark SR ON R.AcademicId = SR.AcademicId AND  SR.ExamId=EC.ExamId
			LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId = StuM.Id
			INNER JOIN #TempSubjectCount TSC ON TSC.ExamId = EM.Id  AND TSC.AcademicId = A.Id 
			
	WHERE 
			
		((EM.BatchId = @rBatchId) OR  (@rBatchId = 0))
		AND ((A.ClassId=@rClassId) OR (@rClassId=0)) 
		AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		AND ((A.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
		AND ((A.RollNo <= @rToRollNo) OR (@rToRollNo=0))
		AND ((StuM.Code=@rCode) OR (@rCode=''))
		AND ((StuM.StatusId=@rStatusId)OR(@rStatusId=0))
		AND ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0))

	ORDER BY A.RollNo , EC.Id
		
	 DROP TABLE #TempExam
	 DROP TABLE #TempSubjectCount
	 
END
GO
PRINT N'Altering Procedure [sAssessment].[pRptResultSheetStandardMultiMaxExamGet]...';


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

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
 begin
 
  
DECLARE @GradeString nvarchar(1000)
DECLARE @GradeStringRemark nvarchar(500),
@GradeSetId int , @IsIncludeSubExam bit,@GradeStringHtml nvarchar(500)
SELECT @GradeSetId = GradesetId,
	   @IsIncludeSubExam = ISNULL(IsIncludeSubExam,0)  FROM sAssessment.tExamMaster WHERE Id = @rExamId
SELECT @GradeString = [sAssessment].[fGradeStringGet](@GradeSetId)

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

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

--#TempAllExam
	CREATE TABLE #TempAllExam
	(
		AcademicIdText nvarchar(20),
		ExamIdText nvarchar(20),
		CoScholasticScopeIdText nvarchar(20),
		IsDisplayMonthlyAttendanceText nvarchar(20),
		ClassIdText nvarchar(50),
		AcademicId bigint,
		ExamName Nvarchar(150),
		StudCode NVarchar(20),
		StudentName Nvarchar(150),
		RollNo int,
		ResultStatus Nvarchar(20),	
		ClassName NVarchar(50),		
		Division NVarchar(50),
		TotalMark decimal(8,2),
		TotalObtain decimal(8,2),
		Percentage decimal(8,2),
		RankNumber int,
		ResultGrade NVarchar(50),
		
		MaximumMark1 decimal(8,2),		
		SubjectGrade1 NVarchar(50),
		Obtain1 decimal(8,2),
		ExamMaximum1 decimal(8,2),
		ObtainedMaximum1 decimal(8,2),
		IsPresent1 bit,
						
		MaximumMark2 decimal(8,2),	
		SubjectGrade2 NVarchar(50),
		Obtain2 decimal(8,2),
		ExamMaximum2 decimal(8,2),
		ObtainedMaximum2 decimal(8,2),
		IsPresent2 bit,
				
		MaximumMark3 decimal(8,2),
		SubjectGrade3 NVarchar(50),
		Obtain3 decimal(8,2),
		ExamMaximum3 decimal(8,2),
		ObtainedMaximum3 decimal(8,2),
		IsPresent3 bit,		
		
		MaximumMark4 decimal(8,2),	
		SubjectGrade4 NVarchar(50),
		Obtain4 decimal(8,2),
		ExamMaximum4 decimal(8,2),
		ObtainedMaximum4 decimal(8,2),
		IsPresent4 bit,	
				
		MaximumMark5 decimal(8,2),		
		SubjectGrade5 NVarchar(50),
		Obtain5 decimal(8,2),
		ExamMaximum5 decimal(8,2),
		IsPresent5 bit,	
				
		MaximumMark6 decimal(8,2),		
		SubjectGrade6 NVarchar(50),
		Obtain6 decimal(8,2),
		ExamMaximum6 decimal(8,2),
		IsPresent6 bit,	
		
		MaximumMark7 decimal(8,2),		
		SubjectGrade7 NVarchar(50),
		Obtain7 decimal(8,2),
		ExamMaximum7 decimal(8,2),
		IsPresent7 bit,	
		
		MaximumMark8 decimal(8,2),	
		SubjectGrade8 NVarchar(50),
		Obtain8 decimal(8,2),
		ExamMaximum8 decimal(8,2),
		IsPresent8 bit,	
		
		MaximumMark9 decimal(8,2),		
		SubjectGrade9 NVarchar(50),
		Obtain9 decimal(8,2),
		ExamMaximum9 decimal(8,2),
		IsPresent9 bit,	
		
		
		MaximumMark10 decimal(8,2),		
		SubjectGrade10 NVarchar(50),
		Obtain10 decimal(8,2),
		ExamMaximum10 decimal(8,2),
		IsPresent10 bit,	
		
		MaximumMark11 decimal(8,2),		
		SubjectGrade11 NVarchar(50),
		Obtain11 decimal(8,2),
		ExamMaximum11 decimal(8,2),
		IsPresent11 bit,
		
		MaximumMark12 decimal(8,2),		
		SubjectGrade12 NVarchar(50),
		Obtain12 decimal(8,2),
		ExamMaximum12 decimal(8,2),
		IsPresent12 bit,		
		 
		 
		SubjectGradeTerm1 NVarchar(50),
		SubjectGradeTerm2 NVarchar(50),
		SubjectGradeTerm3 NVarchar(50),
		IsMarksInDecimal bit,
		column_visible bit,
		Percentile decimal(5,2),
		ResultDetailId bigint,
		ResultId bigint,	
		Remark1 nvarchar(1000),
		Remark2 nvarchar(300),
		Remark3 nvarchar(300),
		DisplayTitle nvarchar(150),		
		IsRankNo bit, 
		IsGrade bit,
		IsPercentile bit,
		IsPercentage bit,
		IsSubjectPercentile bit,
		IsProcessResult bit,
		IsNegativeMarks bit,
		IsIncludeCoScholastic bit,
		IsOnPrePrinted bit,
		IsDisplayPhoto bit,
		IsDisplayBirthDate bit,
		IsLockForEdit bit,
		IsDisplaySchoolName bit,			
		IsDisplayAttendance bit,
		IsDisplayHeightWeight bit,
		IsResultStatus bit,
		FooterAdjustmentText nvarchar(max),
		DetailAdjustmentText nvarchar(max),
		FooterAdjustment smallint,
		DetailAdjustment smallint,
		ResultRemark nvarchar(200),
		DateOfBirth date,
		HeightTerm1 decimal(5,2),
		WeightTerm1 decimal(5,2),
		HeightTerm2 decimal(5,2),
		WeightTerm2 decimal(5,2),
		HeightAnnual decimal(5,2),
		WeightAnnual decimal(5,2),
		PresentDaysTerm1 smallint,
		PresentDaysTerm2 smallint,
		PresentDaysAnnual smallint,
		TotalDaysTerm1 smallint,
		TotalDaysTerm2 smallint,
		TotalDaysAnnual smallint,
		TotalMarkTerm1 decimal(8,2),
		TotalObtainTerm1 decimal(8,2),
		PercentageTerm1 decimal(8,2),
		RankNumberTerm1 int,
		ResultGradeTerm1 NVarchar(50),
		PercentileTerm1 decimal(8,2),
		ResultStatusTerm1 Nvarchar(20),		   
		TotalMarkTerm2 decimal(8,2),
		TotalObtainTerm2 decimal(8,2),
		PercentageTerm2 decimal(8,2),
		RankNumberTerm2 int,
		ResultGradeTerm2 NVarchar(50),
		PercentileTerm2 decimal(8,2),
		ResultStatusTerm2 Nvarchar(20), 
		TotalMarkTerm3 		decimal(8,2),
		TotalObtainTerm3 decimal(8,2),
		PercentageTerm3 decimal(8,2),
		RankNumberTerm3 int,
		ResultGradeTerm3 NVarchar(50),
		PercentileTerm3 decimal(8,2),
		ResultStatusTerm3 Nvarchar(20), 
		
		TermScopeId tinyint,		 
		StudentPhoto varbinary(max),
		GradeString nvarchar(1000),
		IsDisplayGradeString bit,		 
		IsDisplayInMarksheet bit,
		IsShowSubjectGrade bit,
		IsIncludeInTotal bit,
		ClassSubjectID int,
		SubjectId int,
		SubjectOrderIndex smallint,
		SubjectGrade NVarchar(50),
		SubjectName NVarchar(150),
		SubjectCode Nvarchar(50),	
		SubjectMinimum decimal(8,2),		
		SubjectMaximum decimal(8,2),
		SubjectObtain  decimal(8,2),
		
		Exam1Name Nvarchar(150),		
		TotalMarks1 decimal(8,2),		
		TotalObtain1 decimal(8,2),
		Percentage1 decimal(8,2),
		RankNumber1 int,
		ResultGrade1 NVarchar(50),
		Percentile1 decimal(8,2),
		ResultStatus1 Nvarchar(20),
		
		Exam2Name nvarchar(150),	
		TotalMarks2 decimal(8,2),
		TotalObtain2 decimal(8,2),
		Percentage2 decimal(8,2),
		RankNumber2 int,
		ResultGrade2 NVarchar(50),
		Percentile2 decimal(8,2),
		ResultStatus2 Nvarchar(20),
		
		Exam3Name nvarchar(150),	
		TotalMarks3 decimal(8,2),
		TotalObtain3 decimal(8,2),
		Percentage3 decimal(8,2),
		RankNumber3 int,
		ResultGrade3 NVarchar(50),
		Percentile3 decimal(8,2),		
		ResultStatus3 Nvarchar(20),
		
		Exam4Name nvarchar(150),	
		TotalMarks4 decimal(8,2),
		TotalObtain4 decimal(8,2),
		Percentage4 decimal(8,2),
		RankNumber4 int,
		ResultGrade4 NVarchar(50),
		Percentile4 decimal(8,2),
		ResultStatus4 Nvarchar(20),
		
		Exam5Name nvarchar(150),		
		TotalMarks5 decimal(8,2),
		TotalObtain5 decimal(8,2),
		Percentage5 decimal(8,2),
		RankNumber5 int,
		ResultGrade5 NVarchar(50),
		Percentile5 decimal(8,2),
		ResultStatus5 Nvarchar(20),
		
		Exam6Name nvarchar(150),	
		TotalMarks6 decimal(8,2),
		TotalObtain6 decimal(8,2),
		Percentage6 decimal(8,2),
		RankNumber6 int,
		ResultGrade6 NVarchar(50),
		Percentile6 decimal(8,2),
		ResultStatus6 Nvarchar(20),
		
		Exam7Name nvarchar(150),		
		TotalMarks7 decimal(8,2),
		TotalObtain7 decimal(8,2),
		Percentage7 decimal(8,2),
		RankNumber7 int,
		ResultGrade7 NVarchar(50),
		Percentile7 decimal(8,2),
		ResultStatus7 Nvarchar(20),
		
		Exam8Name nvarchar(150),
		TotalMarks8 decimal(8,2),
		TotalObtain8 decimal(8,2),
		Percentage8 decimal(8,2),
		RankNumber8 int,
		ResultGrade8 NVarchar(50),
		Percentile8 decimal(8,2),
		ResultStatus8 Nvarchar(20),
		
		
		Exam9Name nvarchar(150),	
		TotalMarks9 decimal(8,2),
		TotalObtain9 decimal(8,2),
		Percentage9 decimal(8,2),
		RankNumber9 int,
		ResultGrade9 NVarchar(50),
		Percentile9 decimal(8,2),
		ResultStatus9 Nvarchar(20),
		
		Exam10Name nvarchar(150),	
		TotalMarks10 decimal(8,2),
		TotalObtain10 decimal(8,2),
		Percentage10 decimal(8,2),
		RankNumber10 int,
		ResultGrade10 NVarchar(50),
		Percentile10 decimal(8,2),
		ResultStatus10 Nvarchar(20),
		
		Exam11Name nvarchar(150),	
		TotalMarks11 decimal(8,2),
		TotalObtain11 decimal(8,2),
		Percentage11 decimal(8,2),
		RankNumber11 int,
		ResultGrade11 NVarchar(50),
		Percentile11 decimal(8,2),
		ResultStatus11 Nvarchar(20),
		
		
		Exam12Name nvarchar(150),	
		TotalMarks12 decimal(8,2),
		TotalObtain12 decimal(8,2),
		Percentage12 decimal(8,2),
		RankNumber12 int,
		ResultGrade12 NVarchar(50),
		Percentile12 decimal(8,2),
		ResultStatus12 Nvarchar(20),
		
		ResultRemark1 nvarchar(200),
		ResultRemark2 nvarchar(200),
		
		TotalDays decimal(6,2),
		PresentDays decimal(6,2),
		StudentHeight decimal(6,2),
		StudentWeight decimal(6,2),
		ExamSeatNo nvarchar(20),
		ExamId int,
		
		ExamCode nvarchar(20),
		Exam1Code nvarchar(20),
		Exam2Code nvarchar(20),
		Exam3Code nvarchar(20),
		Exam4Code nvarchar(20),
		Exam5Code nvarchar(20),
		Exam6Code Nvarchar(20),
		Exam7Code Nvarchar(20),
		Exam8Code nvarchar(20),
		Exam9Code nvarchar(20),
		Exam10Code nvarchar(20),
		Exam11Code nvarchar(20),
		Exam12Code nvarchar(20),
		
		IsDisplayParentName bit,
		FatherName nvarchar(100),
		MotherName nvarchar(100),
		IsShowSubjectMark bit, 
		IsOptionalSubject bit,
		CoScholasticScopeId tinyint,
		IsDisplayPrincipalSign bit,
		IsDisplayTeacherSign bit,
		EmployeeSign varbinary(max),
		Batch nvarchar(100),
		ExamNameTerm1 NVarchar(100),
		ExamNameTerm2 NVarchar(100) ,
		ExamNameTerm3 NVarchar(100),
		ClassTeacherName Nvarchar(100),
		FirstName nvarchar(50),
		LastName nvarchar(50),
		IsDisplayMonthlyAttendance bit,
		MarksheetHeaderA4 varbinary(max),
		IsImageHeader bit,
		MyGoal nvarchar(200),
		AreaOfInterest nvarchar(200),
		Responsibility nvarchar(200),
		MyInterestHobby nvarchar(200),
		MyStrength nvarchar(200),
		Achievements nvarchar(200),
		DentalHygiene nvarchar(200),
		VisionLeft nvarchar(50),
		VisionRight nvarchar(50), 
		IsDetail bit,
		SubjectGroupId int,
		SubjectGroupTitle nvarchar(50),
		SubjectGroupCode nvarchar(50),
		DecimalFormat nvarchar(10),
		SubjectRemark nvarchar(1000),
		GraceMark decimal(5,2),
		GradeStringHtml nvarchar(500),
		ResultRemark3 nvarchar(200),
		IsDisplayTotalMark bit,
		SubjectObtainTerm1 decimal(8,2),	
		SubjectObtainTerm2 decimal(8,2),
		SubjectObtainTerm3  decimal(8,2),
		SubjectMaxTerm1 decimal(8,2),
		SubjectMaxTerm2 decimal(8,2),
		SubjectMaxTerm3 decimal(8,2),
		ContactNo nvarchar(20),
		PresentAddress nvarchar(max),
		TeacherSignCaption nvarchar(100),
		PrincipalSignCaption nvarchar(100),
		ParentSignCaption nvarchar(100),
		ImprovementArea nvarchar(200),
		ProgressArea nvarchar(200),
		GeneralRemark nvarchar(200),
		MyActivity nvarchar(200),
		ClassTeacherRemark nvarchar(1000),
		 
		HouseRemark nvarchar(1000),
		BloodGroup Nvarchar(100),
		TotalDays1 decimal(6,2),
		PresentDays1 decimal(6,2),
		TotalDays2 decimal(6,2),
		PresentDays2 decimal(6,2),
		TotalDays3 decimal(6,2),
		PresentDays3 decimal(6,2),
		TotalDays4 decimal(6,2),
		PresentDays4 decimal(6,2),
		TotalDays5 decimal(6,2),
		PresentDays5 decimal(6,2),
		TotalDays6 decimal(6,2),
		PresentDays6 decimal(6,2),
		TotalDays7 decimal(6,2),
		PresentDays7 decimal(6,2), 
		TotalDays8 decimal(6,2),
		PresentDays8 decimal(6,2),
		TotalDays9 decimal(6,2),
		PresentDays9 decimal(6,2),
		TotalDays10 decimal(6,2),
		PresentDays10 decimal(6,2),
		TotalDays11 decimal(6,2),
		PresentDays11 decimal(6,2),
		TotalDays12 decimal(6,2),
		PresentDays12 decimal(6,2),
		BatchIdText nvarchar(20),
		IsShowWithDetail bit,
		IsPresent bit,
		GradeTitle nvarchar(50),
		SubjectHighestDivisionGrade nvarchar(50),
		SubjectHighestDivisionMark decimal(5, 2),
		HouseId int,
		HouseName nvarchar(100),
		IsDecimal bit
	)	
	 
	INSERT INTO  #TempAllExam 
	(
	AcademicIdText,
	ExamIdText,
	CoScholasticScopeIdText,
	IsDisplayMonthlyAttendanceText,
	ClassIdText,
	AcademicId,
	ExamName,
	StudCode,
	StudentName,
	RollNo,
	ResultStatus,
	ClassName,
	Division,
	TotalMark,
	TotalObtain,
	Percentage,
	RankNumber,
	ResultGrade,
	IsMarksInDecimal,
	column_visible,
	Percentile,
	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,
	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,
	GradeStringHtml,
	ResultRemark3,
	IsDisplayTotalMark,
	ContactNo,
	PresentAddress,
	TeacherSignCaption,
	PrincipalSignCaption,
	ParentSignCaption,
	ImprovementArea,
	ProgressArea,
	GeneralRemark,
	MyActivity,
	ClassTeacherRemark,
	
	HouseRemark,
	BloodGroup,
	BatchIdText,
    IsShowWithDetail,
    IsPresent,
    GradeTitle,
	
	 SubjectHighestDivisionGrade,
	 SubjectHighestDivisionMark,
	 HouseName,
	 HouseId,
	 IsDecimal
	)
	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,
		R.Percentile,
		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,
		(CASE ISNULL(ED.DisplayOrder,0)
		WHEN 0 THEN CS.OrderIndex
		ELSE ED.DisplayOrder END) 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,
		(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,
		@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),
		@rIsShowWithDetail AS IsShowWithDetail,
		IsPresent,
		GradeTitle ,
		RAD.SubjectHighestDivisionGrade,
		RAD.SubjectHighestDivisionMark ,
		HM.Title As HouseName,HM.Id as HouseId,
		CONVERT(bit,@lDecimalConfig) AS IsDecimal
FROM 
	sAssessment.tResultDetail RD
	INNER JOIN sAssessment.tResult R ON R.Id = RD.ResultId
	INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId
	INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId		
	INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
	INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=CS.SubjectId	
	LEFT JOIN sSetup.tSubjectGroupMaster SG ON SG.Id = Sm.SubjectGroupId				 
	INNER JOIN sStudent.tAcademic A ON A.Id=R.AcademicId
	INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=A.OrgId
	LEFT JOIN sSetup.tOrgImages OI ON OI.Orgid = OM.Id
	INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId
	INNER JOIN sStudent.tStudentMaster StuM ON StuM.Id=A.StudentId
	INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId
	INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId
	LEFT JOIN sHrm.tEmployeeImages EI ON EI.EmployeeId = Dm.InchargeEmployeeId
	LEFT JOIN sHrm.tEmployeeMaster EMP ON EMP.Id = DM.InchargeEmployeeId
	INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id = EM.EXAMSUBGROUPID
	LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId=StuM.Id
	Left JOIN 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
			  
	
	WHERE
		R.ExamId = @rExamId 
		AND ((A.DivisionId =  @rDivisionId) OR (@rDivisionId=0))
		AND ((A.ClassId =  @rClassId) OR (@rClassId=0))		 
		AND ((A.BatchId =  @rBatchId) OR (@rBatchId=0))
		AND ((A.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
		AND ((A.RollNo <= @rToRollNo) OR (@rToRollNo=0))
		AND ((R.RankNumber >= @rFromRank) OR (@rFromRank=0))
		AND ((R.RankNumber <= @rToRank) OR (@rToRank=0))
		AND ((R.ResultGrade = @rGrade) OR (@rGrade=''))
		AND ((StuM.Code=@rCode) OR (@rCode=''))	
		AND ((R.Id = @rResultId) OR (@rResultId = 0))	
		AND ((StuM.StatusId=@rStatusId)OR(@rStatusId=0))
		AND((A.Id=@rAcademicId)OR (@rAcademicId=0))
		AND ((CS.SubjectId=@rSubjectId) OR(@rSubjectId=0) ) 
		AND ((R.Percentage>=@rFromPercentage) OR (@rFromPercentage=0))
		AND ((R.Percentage<=@rToPercentage) OR (@rToPercentage=0))
		 AND ((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 ED.DisplayOrder
 
	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
 	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
	
	DECLARE @lCount int,@query  AS NVARCHAR(MAX),@lSubExamId int,@lCount1 int
  
	Select @lCount = MAX(Id) from #tempcombineExam
	DECLARE @ExamTitle nvarchar(150)
	while (@lCount > 0)
	begin
		
		select @lSubExamId = ExamID from #tempcombineExam Where Id = @lCount
		if(@lCount <= 4)
		BEGIN
			set @query ='update T SET
						 MaximumMark' + convert(nvarchar(15),@lCount)+ '=ED.Maximum,
						 Obtain' + convert(nvarchar(15),@lCount)+'=RD.Obtain,
						 IsPresent' + convert(nvarchar(15),@lCount)+'=RD.IsPresent,
					
						 ObtainedMaximum' + convert(nvarchar(15),@lCount)+ '= CASE WHEN EM.IsDisplayHighestDivisionMark = 1
									THEN [sAssessment].[fGetHighestDivisionMark](A.DivisionId ,RD.ExamDetailId)
									ELSE 0  END,
						 				
						 SubjectGrade' + convert(nvarchar(15),@lCount)+ '=RD.SubjectGrade,
						 TotalDays'+convert(nvarchar(15),@lCount)+'=SR.TotalDays,
						 PresentDays'+convert(nvarchar(15),@lCount)+'=SR.PresentDays										
						 From
							sAssessment.tResultDetail RD
							INNER JOIN sAssessment.tResult R ON R.Id = RD.ResultId
							INNER JOIN sStudent.tAcademic A ON A.Id=R.AcademicId
							INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId
							INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
							INNER JOIN sAssessment.tExamSubgroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId
							INNER JOIN 	#TempAllExam  T ON T.ClassSubjectID = ED.ClassSubjectId And T.AcademicId = R.AcademicId	
							LEFT JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND T.AcademicId = SR.AcademicId 									
							WHERE EM.Id =' + convert(nvarchar(15), @lSubExamId) 
			
			execute(@query)
			
		END
		
		ELSE
		
		BEGIN
			set @query ='update T SET
						 MaximumMark' + convert(nvarchar(15),@lCount)+ '=ED.Maximum,
						 Obtain' + convert(nvarchar(15),@lCount)+'=RD.Obtain,
						 IsPresent' + convert(nvarchar(15),@lCount)+'=RD.IsPresent,	
						 SubjectGrade' + convert(nvarchar(15),@lCount)+ '=RD.SubjectGrade,
						 TotalDays'+convert(nvarchar(15),@lCount)+'=SR.TotalDays,
						 PresentDays'+convert(nvarchar(15),@lCount)+'=SR.PresentDays
						 										
						 From
							sAssessment.tResultDetail RD
							INNER JOIN sAssessment.tResult R ON R.Id = RD.ResultId
							INNER JOIN sStudent.tAcademic A ON A.Id=R.AcademicId
							INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId
							INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
							INNER JOIN sAssessment.tExamSubgroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId					
							INNER JOIN 	#TempAllExam  T ON T.ClassSubjectID = ED.ClassSubjectId And T.AcademicId = R.AcademicId	
							LEFT JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND T.AcademicId = SR.AcademicId 									
							WHERE EM.Id =' + convert(nvarchar(15), @lSubExamId)  
			
					
			execute(@query)
			
		END
						
			set @query ='update T set 
				    TotalMarks' + convert(nvarchar(15),@lCount)+ '=R.TotalMarks,
					TotalObtain' + convert(nvarchar(15),@lCount)+ '=R.TotalObtain,
					Percentage' + convert(nvarchar(15),@lCount)+ '=R.Percentage,
					RankNumber' + convert(nvarchar(15),@lCount)+'=R.RankNumber,
					ResultGrade' + convert(nvarchar(15),@lCount)+'=R.ResultGrade,
					Percentile' + convert(nvarchar(15),@lCount)+'=R.Percentile,
					ResultStatus' + convert(nvarchar(15),@lCount)+'=R.ResultStatus,
					Exam' + convert(nvarchar(15),@lCount)+ 'Name=ESGM.Title,
					Exam' + convert(nvarchar(15),@lCount)+ 'Code=ESGM.Code,
					ExamMaximum' + convert(nvarchar(15),@lCount)+'=ISNULL(EM.ExamMaximum,0)
					 From						
						sAssessment.tResult R						
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id=R.ExamId
						INNER JOIN sAssessment.tExamSubgroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId					
						INNER JOIN 	#TempAllExam  T ON  T.AcademicId = R.AcademicId						
						WHERE EM.Id =' + convert(nvarchar(15), @lSubExamId)  
						
		execute(@query)
		
		
	set @lCount = @lCount -1
	end
	

	IF (@IsIncludeSubExam = 1)
	BEGIN	
		select @lSubExamId = SubExamId from sAssessment.tExamCombine  Where ExamId  = @rExamId AND ExamOrder = 1
		
			set @query ='update T set					 
					SubjectGradeTerm1=RD.SubjectGrade,
					SubjectObtainTerm1 = RD.Obtain,
					 SubjectMaxTerm1 = ED.Maximum
							 
					 From
						 sAssessment.tResultDetail RD
						INNER JOIN  sAssessment.tResult R ON R.Id = RD.ResultId
						INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
						INNER JOIN sAssessment.tExamSubgroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId					
						INNER JOIN 	#TempAllExam  T ON T.ClassSubjectID = ED.ClassSubjectId And T.AcademicId = R.AcademicId						
						WHERE EM.Id =' + convert(nvarchar(15), @lSubExamId)  
		
				execute(@query)
				
		set @query ='update T set					 
					 
					TotalMarkTerm1 = R.TotalMarks,
					TotalObtainTerm1=R.TotalObtain,
					PercentageTerm1=R.Percentage,
					RankNumberTerm1=R.RankNumber,
					ResultGradeTerm1=R.ResultGrade,
					PercentileTerm1 = R.Percentile,
					ResultStatusTerm1 = R.ResultStatus,
					ExamNameTerm1 = ESGM.Code					 
					 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 = 2
		set @query ='update T set					 
					SubjectGradeTerm2=RD.SubjectGrade,
					SubjectObtainTerm2 = RD.Obtain,
					SubjectMaxTerm2= ED.Maximum				 
					 From
						sAssessment.tResultDetail RD
						INNER JOIN sAssessment.tResult R ON R.Id = RD.ResultId
						INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
						INNER JOIN sAssessment.tExamSubgroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId					
						INNER JOIN 	#TempAllExam  T ON T.ClassSubjectID = ED.ClassSubjectId And T.AcademicId = R.AcademicId						
						WHERE EM.Id =' + convert(nvarchar(15), @lSubExamId)  
		execute(@query)
		
		
				set @query ='update T set
 
					TotalMarkTerm2 = R.TotalMarks,
					TotalObtainTerm2=R.TotalObtain,
					PercentageTerm2=R.Percentage,
					RankNumberTerm2=R.RankNumber,
					ResultGradeTerm2=R.ResultGrade,
					PercentileTerm2 = R.Percentile,
					ResultStatusTerm2 = R.ResultStatus,
					ExamNameTerm2 = ESGM.Code			
					 From						 
					   sAssessment.tResult R  				 
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id=R.ExamId
						INNER JOIN sAssessment.tExamSubgroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId					
						INNER JOIN 	#TempAllExam  T ON  T.AcademicId = R.AcademicId						
						WHERE EM.Id =' + convert(nvarchar(15), @lSubExamId)  
		execute(@query)
		
		select @lSubExamId = SubExamId from sAssessment.tExamCombine  Where ExamId  = @rExamId AND ExamOrder = 3
		set @query ='update T set					 
					SubjectGradeTerm3=RD.SubjectGrade,
					SubjectObtainTerm3 = RD.Obtain,
					SubjectMaxTerm3= ED.Maximum				 
					 From
						sAssessment.tResultDetail RD
						INNER JOIN sAssessment.tResult R ON R.Id = RD.ResultId
						INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
						INNER JOIN sAssessment.tExamSubgroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId					
						INNER JOIN 	#TempAllExam  T ON T.ClassSubjectID = ED.ClassSubjectId And T.AcademicId = R.AcademicId						
						WHERE EM.Id =' + convert(nvarchar(15), @lSubExamId)  
		execute(@query)
		set @query ='update T set
 
					TotalMarkTerm3 = R.TotalMarks,
					TotalObtainTerm3=R.TotalObtain,
					PercentageTerm3=R.Percentage,
					RankNumberTerm3=R.RankNumber,
					ResultGradeTerm3=R.ResultGrade,
					PercentileTerm3 = R.Percentile,
					ResultStatusTerm3 = R.ResultStatus,
					ExamNameTerm3 = ESGM.Code			
					 From						 
					   sAssessment.tResult R  				 
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id=R.ExamId
						INNER JOIN sAssessment.tExamSubgroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId					
						INNER JOIN 	#TempAllExam  T ON  T.AcademicId = R.AcademicId						
						WHERE EM.Id =' + convert(nvarchar(15), @lSubExamId)  
		execute(@query)
	END
	
	-- For Getting Highest Mark in Class in 2nd and 3rd Exam in One Field
	
	CREATE TABLE #HighestMarkTerm2Term3
	(
		SubjectId int,
		Term2Term3ClassHighestMarkSum decimal(8,2)
	)
	INSERT INTO #HighestMarkTerm2Term3 
	(
		SubjectId,
		Term2Term3ClassHighestMarkSum
	)
	SELECT 
		CS.SubjectId,		 
		MAX(RD.Obtain) AS Term2Term3ClassHighestMarkSum
	FROM
	sAssessment.tResultDetail RD INNER JOIN sAssessment.tResult R ON RD.ResultId = R.Id
	 INNER JOIN sAssessment.tExamDetail ED ON RD.ExamDetailId = ED.Id
	INNER JOIN sAssessment.tExamMaster EM ON ED.ExamId = EM.Id
	INNER JOIN  sSetup.tClassSubject CS  ON ED.ClassSubjectId = CS.Id
	INNER JOIN sStudent.tAcademic A ON R.AcademicId = A.Id
	WHERE
	A.BatchId = @rBatchId
	AND EM.BatchId =  @rBatchId
	AND	((A.ClassId = @rClassId) OR (@rClassId = 0)) 
		AND ((A.DivisionId = @rDivisionId) OR (@rDivisionId = 0)) 
		--AND ((CS.Id = @rSubjectId) OR (@rSubjectId = 0))
		AND ((EM.Id = @rExamId) OR (@rExamId = 0))
		AND ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0))
		group by CS.SubjectId,A.DivisionId 
		
	
	
	
	
	SELECT 
		  @rBuilder1,@rBuilder2, T.*,H.Term2Term3ClassHighestMarkSum
	FROM 
	      #TempAllExam T
		  INNER JOIN #HighestMarkTerm2Term3 H ON H.SubjectId = T.SubjectId
	
	
	Drop table #tempcombineExam
	
	Drop table #TempAllExam
	
	Drop table #HighestMarkTerm2Term3
	
	END
	
	
	--SELECT @rBuilder1,@rBuilder2,T.* FROM sAssessment.tTempAllExam T
 -- end
GO
PRINT N'Altering Procedure [sAssessment].[pRptResultWithAllSubjectListGet]...';


GO


ALTER PROCEDURE [sAssessment].[pRptResultWithAllSubjectListGet]
	 
   	@rBuilder1 nvarchar(max)='',
	@rBuilder2 nvarchar(max)='', 
	@rSubjectId int=0,
	@rBatchId int,
	@rClassId int,
	@rDivisionId int,	
	@rExamId int=0,
	@rExamSubGroupId int=0,
	@rCode nvarchar(20),
	@rFromRollNo int,
	@rToRollNo int,
	@rFromRank int,
	@rToRank int,
	@rGrade nvarchar(20),
	@rStatusId int = 0,
	@rFromPercentage decimal(5,2)=0,
	@rToPercentage decimal(5,2)=0,
	@rResultStatus nvarchar(20)='',
	@rDepartmentId int=0,
	@rClassStatusId int=0,
	@rFilterId int=0 
	
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 

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


	SELECT 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			ESGM.Title AS Exam,
			StuM.Code,
		    [sStudent].[fStudentNameGet](StuM.FirstName , StuM.MiddleName, StuM.LastName,OM.StudentNameFormatId ) AS Name,
			A.RollNo,
			R.AcademicId,
			RD.Obtain,
			R.ResultStatus,
			CM.DisplayTitle AS Class,
			Cm.Id AS ClassId,
			DM.DisplayTitle AS Division,
			DM.Id AS DivisionId,
			DM.OrderIndex AS DivisinOrderIndex,
			R.TotalMarks,
			R.TotalObtain,
			R.Percentage,
			R.RankNumber,
			R.ResultGrade,
			SM.Title AS ClassSubject,
			RD.Id AS ResultDetailId,
			R.Id AS ResultId,
			CS.Id AS SubjectId,
			ED.Maximum,
			RD.SubjectGrade, 
			EM.IsMarksInDecimal,
			SM.Code AS SubjectCode,
			ED.DisplayOrder AS SubjectOrderIndex,
			CM.OrderIndex AS ClassOrderIndex,
			RD.IsPresent,
			EM.IsGrade,
			EM.IsPercentage,
			EM.IsResultStatus,
			EM.IsRankNo ,
			ED.Minimum,
			RD.GraceMark,
			EM.DecimalFormat,
			CS.IsOptional,
			(EmpM.FirstName + ' ' +EmpM.LastName ) AS InchargeEmployeeName,
			CONVERT(bit,@lAbsentRemarkConfig) AS IsAbsentRemark,
			ISNULL(RD.AbsentRemark,'') AS AbsentRemark
      
	FROM 
	
	sStudent.tAcademic A 
	INNER JOIN sAssessment.tResult R ON A.Id=R.AcademicId    
	INNER JOIN sStudent.tStudentMaster StuM ON StuM.Id=A.StudentId
	INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId
	INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId
	INNER JOIN sSetup.tOrganizationMaster OM ON StuM.OrgId = OM.Id
	INNER JOIN sAssessment.tExamMaster EM ON EM.Id=R.ExamId AND	((EM.Id=@rExamId )	OR (@rExamId = 0))AND EM.BatchId = @rBatchId	
	INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId AND ((ESGM.Id = @rExamSubGroupId) OR (@rExamSubGroupId = 0))
	INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId = EM.Id
	INNER JOIN sSetup.tClassSubject CS ON Cs.Id = Ed.ClassSubjectId
	INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=CS.SubjectId	
	LEFT JOIN sAssessment.tResultDetail RD ON ED.Id=RD.ExamDetailId 
		AND ((SM.Id=@rSubjectId) OR (RD.ExamDetailId=@rSubjectId) OR (@rSubjectId=0)) 
		AND R.Id = RD.ResultId
	LEFT JOIN sHrm.tEmployeeMaster EmpM ON EmpM.Id = DM.InchargeEmployeeId AND EmpM.StatusId = 7
	INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId
	LEFT JOIN sHostel.tAssignRoom AR ON  AR.SourceId=StuM.Id AND AR.SourceTypeId=2003 AND BM.OrgGroupBatchId = AR.OrgGroupBatchId
	LEFT JOIN
	(SELECT AT.SourceId,B.OrgGroupBatchId FROM sTransport.tAssignRoute AT 
    INNER JOIN sTransport.tBusRouteDestinationMaster BRD ON BRD.Id=AT.PickupDestinationId 
    INNER JOIN sTransport.tBusRouteMaster B ON B.Id=BRD.BusRouteId AND  AT.SourceTypeId=2003 ) RT
    ON RT.SourceId = StuM.Id AND RT.OrgGroupBatchId = BM.OrgGroupBatchId
	
			
	WHERE 
	     
	   --(CS.ClassId=@rClassId OR @rClassId=0) 
		 EM.BatchId = @rBatchId 
		AND (A.ClassId=@rClassId OR @rClassId=0) 
		--AND((SM.Id=@rSubjectId) OR (RD.ExamDetailId=@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 ((ESGM.Id = @rExamSubGroupId) OR (@rExamSubGroupId = 0))		
		AND ((EM.Id=@rExamId )	OR (@rExamId = 0))		
		AND ((StuM.Code=@rCode) OR (@rCode=''))
		AND ((StuM.StatusId=@rStatusId)OR(@rStatusId=0))	
		AND ((R.Percentage>=@rFromPercentage) OR (@rFromPercentage=0))
		AND ((R.Percentage<=@rToPercentage) OR(@rToPercentage=0))	
		AND ((R.ResultStatus=@rResultStatus) OR (@rResultStatus=''))
		AND ((CM.DepartmentId = @rDepartmentId) OR (@rDepartmentId=0))
	    AND	A.BatchId = @rBatchId 
		AND (A.ClassStatusId=@rClassStatusId OR @rClassStatusId=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)))
		) 
		order by A.RollNo,CS.OrderIndex 

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


GO
ALTER PROCEDURE [sAssessment].[pRptSubjectActivityExamDetailGet]
	 
		@rOrgId int=0,
		@rExamId int=0,
		@rClass int=0,
		@rDivisionId int=0,
		@rBatchId int=0,
		@rBuilder1 nvarchar(max)='',
		@rAcademicId bigint=0,
		@rCode nvarchar(20)='',
		@rFromRollNo int=0,
		@rToRollNo int=0,
		@rMultiCode nvarchar(max)=''
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON 
BEGIN 	 

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

Declare @DecimalConfid nvarchar(20)=''
SELECT @DecimalConfid =ItemValue From sConfig.tConfigurationSetup WHERE ConfigurationId = 496 AND SourceTypeId = 1016 AND SourceId = @rOrgId

	SELECT 			 
			Convert(nvarchar(20),SA.Id) AS AcademicIdText,	
			CONVERT (nvarchar(20),@rExamId) AS ExamIdText, 
			@rBuilder1 AS Builder1,
			SA.Id AS AcademicId,
			SA.RollNo,
			StuM.Number,
			AIS.Grade,
			SAM.Title AS SubjectActivityTitle,
			SSA.Title AS SubjectSubActivityTitle,
			SAM.Id AS ActivityId,
			SSA.Id AS SubjectSubActivityId,
			SAM.OrderIndex AS ActivityOrderIndex,
			SSA.OrderIndex AS SubjectSubActivityOrderIndex ,
			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,
			EM.IsDisplayGradeString,
			EM.IsDisplayParentName,
			[sStudent].[fStudentNameGet](StuM.FirstName , ISNULL(StuM.MiddleName,'') , StuM.LastName,OM.StudentNameFormatId ) AS Name,
			SO.DateOfBirth,
			CMM.Title AS ClassName,
			StuM.code,
			SF.FatherName,
			SF.MotherName,
			SAM.ClassSubjectId ,
			SM.Title AS SubjectName,
			SM.OrderIndex AS SubjectOrderIndex,
			CMM.DisplayTitle AS Class,
			DM.DisplayTitle AS Division,
			CASE WHEN EM.IsDisplayPhoto = 1 THEN SI.StudentPhoto ELSE NULL END AS StudentPhoto, 
			ISNULL(AIS.DescriptiveIndicator,'') AS DescriptiveIndicator,
			CASE WHEN CS.OrderIndex % 2 = 0 THEN 2 
			ELSE 1 END AS ColumnSubjectCount,
			CS.OrderIndex,
			EM.SubjectGroupPerPage,
			AIS.GradeIndicator,
			EM.IsCoScholasticGradeIndicator,
			CASE WHEN EM.IsDisplayTeacherSign = 1 THEN EI.EmployeeSign ELSE NULL END AS EmployeeSign,
			Em.IsDisplayPrincipalSign,
			EM.IsDisplayTeacherSign,
			EM.IsCoScholasticGradeDesIndicator,
			EM.IsCoScholasticGrade,
			Em.IsDisplayParentName,
			(CASE EM.IsDisplayImageHeader WHEN 1 THEN 
			OI.MarksheetHeaderA4 
			ELSE 
			NULL END) AS MarksheetHeaderA4,
			ISNULL(EM.IsDisplayImageHeader,0) AS IsImageHeader,
			RD.Remark,
			
			HM.Title AS House,
			BM.Title AS BAtch ,
			[sAttendance].[fSubjectTeacherGet](SA.DivisionId,SM.ID) AS TEacherName,
			ED.IsShowSubjectGrade,
			CASE @GradeStringRemark WHEN '' THEN @GradeString  ELSE @GradeStringRemark END AS GradeString,
			--@GradeString AS GradeString,
			Convert(nvarchar(20),ISNULL(Em.IsDisplayMonthlyAttendance,0)) As IsDisplayMonthlyAttendanceText,
			TeacherSignCaption,
			EM.PrincipalSignCaption,
			ParentSignCaption,
			--CASE WHEN EM.IsDisplayTeacherSign = 1 THEN EM.TeacherSignCaption ELSE NULL END AS TeacherSignCaption,
			--CASE WHEN EM.IsDisplayPrincipalSign = 1 THEN EM.PrincipalSignCaption ELSE NULL END AS PrincipalSignCaption,
			SR.ResultRemark1,
			SR.ResultRemark2,	
			SR.ResultRemark3,
			SR.ClassTeacherRemark,
			SR.HouseRemark,
			ISNULL(SR.PresentDays,0)AS PresentDays,			
			ISNULL(SR.TotalDays,0)AS TotalDays,
			SR.StudentHeight,
			SR.StudentWeight,
			
			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,
			ISNULL(SR.ImprovementArea,'') As ImprovementArea,
			ISNULL(SR.ProgressArea,'') AS ProgressArea,
			ISNULL(SR.GeneralRemark,'') As GeneralRemark,
			ISNULL(SR.MyActivity,'') AS MyActivity,
			ISNULL(SF.FatherContactNo,'') AS FatherContactNo,
			ISNULL(SF.MotherContactNo,'') AS MotherContactNo,
			ISNULL(SF.FatherMail,'') AS FatherMail,
			ISNULL(SF.MotherMail,'') AS MotherMail,
			ISNULL(SC.PresentStreetONe,'')+' '+ISNULL(SC.PresentStreetTwo,'')+' '+ISNULL(SC.PresentStreetThree,'')+' '+ISNULL(SC.PresentCity,'')+' '+ISNULL(SC.PresentState,'') AS PresentAddress,
			DivisionId,
			SM.ID,
			( EmpM.FirstName + ' ' +EmpM.LastName ) AS InchargeEmployeeName,
			ISNULL(SC.ParentContactNo,'') AS ParentContactNo,
			CONVERT(bit,@DecimalConfid) AS IsDecimal,
			AIS.Marks,
			SR.ExamSeatNo AS ExamSeatNo					--add for 27710 mantis

	 FROM 
			sAssessment.tCCESubjectSubActivityExamScore AIS 
			INNER JOIN sAssessment.tCCESubjectSubActivityMaster SSA ON AIS.SubjectSubActivityId = SSA.Id 
			INNER JOIN	sAssessment.tCCESubjectActivityMaster SAM  ON SAM.Id = SSA.SubjectActivityId			
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=SAM.ClassSubjectId		
			INNER JOIN sStudent.tAcademic SA ON SA.Id = AIS.AcademicId 
			INNER JOIN sStudent.tStudentMaster StuM ON StuM.Id=SA.StudentId
			INNER JOIN sAssessment.tExamMaster EM ON EM.Id=AIS.ExamId
			INNER JOIN sAssessment.tExamDetail ED ON EM.Id=ED.ExamId AND ED.ClassSubjectId = CS.Id 		 			 
			INNER JOIN sAssessment.tResult AR ON AR.ExamId = AIS.ExamId AND AIS.AcademicId = AR.AcademicId
			INNER JOIN sAssessment.tResultDetail ARD ON ARD.ResultId = AR.Id AND ARD.ExamDetailId = ED.Id
			LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId=SA.StudentId
			LEFT JOIN sActivity.tHouseMaster HM ON HM.Id=SO.HouseId
			LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId=SA.StudentId	
			INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=CS.SubjectId
			INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=SA.divisionId	
			INNER JOIN sSetup.tClassMaster CMM ON CMM.Id=DM.ClassId 
			LEFT JOIN sHrm.tEmployeeMaster EmpM 
				ON EmpM.Id = DM.InchargeEmployeeId AND EmpM.IsObsolete = 0
			LEFT JOIN sHrm.tEmployeeImages EI ON EI.EmployeeId = Dm.InchargeEmployeeId
			--LEFT JOIN sAcademic.tTeacherSubjectDivision TSD ON TSD.DivisionId = DM.Id AND TSD.SubjectId = SM.Id 
			--LEFT JOIN sHrm.tEmployeeMaster EMP ON EMP.Id = TSD.EmployeeId
			LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId = SA.StudentId
			LEFT JOIN sAssessment.tStudentRemark SR ON SA.Id = SR.AcademicId	AND EM.Id = SR.ExamId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = Stum.OrgId
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id= SA.BatchID
			LEFT JOIN sSetup.tOrgImages OI ON OI.OrgId = Om.Id
			LEFT JOIN sAssessment.tResultDetailOther RD ON RD.AcademicId = SA.Id AND EM.ID=RD.ExamId AND CS.Id=RD.ClassSubjectID 
			LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId =StuM.ID
	    --LEFT JOIN @lAcademicId A ON A.AcademicId = SA.AcademicId AND A.ClassSubjectId = ED.ClassSubjectId
			----------------------------------------------------------------------------
			--sAssessment.tCCESubjectActivityMaster SAM 	
			--INNER JOIN sAssessment.tCCESubjectSubActivityMaster SSA ON SAM.Id=SSA.SubjectActivityId 
			--INNER JOIN sAssessment.vCCEExamClassSubject CS ON CS.ClassSubjectId=SAM.ClassSubjectId
			--INNER JOIN sSetup.tClassMaster CMM ON CMM.Id=CS.ClassId 
			--INNER JOIN sStudent.vStudentAcademic SA ON SA.ClassId = CS.ClassId 
			--INNER JOIN sStudent.tStudentMaster StuM ON StuM.Id=SA.StudentId			 
			--LEFT JOIN sAssessment.tCCESubjectSubActivityExamScore AIS ON AIS.AcademicId =SA.AcademicId AND AIS.SubjectSubActivityId= SSA.Id 	
			--LEFT JOIN sAssessment.tExamMaster EM ON EM.Id=AIS.ExamId
			--LEFT JOIN sAssessment.tExamDetail ED ON EM.Id=ED.ExamId	AND ED.ClassSubjectId = CS.ClassSubjectId 		 
			--LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId=SA.StudentId
			--LEFT JOIN sActivity.tHouseMaster HM ON HM.Id=SO.HouseId
			--LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId=SA.StudentId	
			--INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=CS.SubjectId	
			--INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=SA.divisionId
			--LEFT JOIN sHrm.tEmployeeImages EI ON EI.EmployeeId = Dm.InchargeEmployeeId
			--LEFT JOIN sAcademic.tTeacherSubjectDivision TSD ON TSD.DivisionId = DM.Id AND TSD.SubjectId = SM.Id 
			--LEFT JOIN sHrm.tEmployeeMaster EMP ON EMP.Id = TSD.EmployeeId
			--LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId = SA.StudentId
			--LEFT JOIN sAssessment.tStudentRemark SR ON SA.AcademicId = SR.AcademicId	AND EM.Id = SR.ExamId
			--INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = Stum.OrgId
			--INNER JOIN sSetup.tBatchMaster BM ON BM.Id= SA.BatchID
			--LEFT JOIN sSetup.tOrgImages OI ON OI.OrgId = Om.Id
			--LEFT JOIN sAssessment.tResultDetailOther RD ON RD.AcademicId = SA.AcademicId AND EM.ID=RD.ExamId AND CS.ClassSubjectId=RD.ClassSubjectID 
		WHERE
			((SA.Id=@rAcademicId) OR(@rAcademicId=0))
			AND ((CS.ClassId=@rClass) OR (@rClass=0))
			And ((SA.DivisionId =@rDivisionId) or(@rDivisionId=0))	
			And ((SA.BatchId =@rBatchId) OR (@rBatchId=0))
			and ((SA.OrgId=@rOrgId) OR (@rOrgId=0))
			And AIS.ExamId=@rExamId
			AND ((STum.Code = @rCode) OR(@rCode=''))
			AND ((SA.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
			AND ((SA.RollNo <= @rToRollNo) OR (@rToRollNo=0))
			AND StuM.StatusId = 1
			AND (ISNULL(STum.Code,0) IN( SELECT cast(item as nvarchar(20)) FROM  sCommon.fnsplit(@rMultiCode,',')) OR @rMultiCode='')
			AND SAM.IsObsolete = 0
		ORDER BY 
			SA.RollNo ASC,
			SAM.OrderIndex ASC,
			SSA.OrderIndex ASC;
END
GO
PRINT N'Altering Procedure [sAttendance].[pSubjectwiseAttendanceGet]...';


GO
 

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

	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 

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


GO
ALTER PROCEDURE [sBiometric].[pRptTimeSheetListGet]
  @rBuilder1 nvarchar(max)='',
  @rBuilder2 nvarchar(max)='',
  @rEmployeeId bigint=0,  
  @rFromDate DateTime,  
  @rToDate DateTime,  
  @rTimeSheetStatus nvarchar(10) = '0',  
  @rOrgId int = 0  ,
  @rOrgGroupId int,
  @rEmployeeStatusId int = 0,
  @rOrganizationDepartmentId int=0,
  @rOrgGroupDepartmentId int = 0,
  @rGradeId nvarchar(max)= '0'

WITH EXECUTE AS CALLER  
AS  
SET NOCOUNT ON  
BEGIN 

CREATE TABLE #TempMonthTrans  
 (  
 Id int,  
 EmployeeId bigint,   
 Attn_Date DateTime,  
 PresentStatus nvarchar(15),  
 FirstIn nvarchar(20),  
 LastOut nvarchar(20),  
 OverTime nvarchar(20),  
 LateBy nvarchar(20),  
 Duration nvarchar(20),   
 EarlyBy nvarchar(20),
 ShiftName nvarchar(25)  
 )  
    Declare @ldate datetime,@lDays int
		declare @Days int
		Declare @Firstdate datetime
		Declare @Lastdate datetime
		DECLARE @lBatchID int
		DECLARE @lForYear nvarchar(20),@lForMonth nvarchar(20)
		Set @lForYear = Year(@rFromDate)
		
		Set @lForMonth = Month(@rFromDate)
		
		Set @ldate= CONVERT(nvarchar(20), @lForYear)+ '-' +  CONVERT(nvarchar(20), @lForMonth) + '-' + CONVERT(nvarchar(20), 01)
		Select @lDays=day(dateadd(mm,DateDiff(mm, -1, @ldate),0) -1) 
		select @Days=sCommon.fGetDaysInMonth(@lForMonth,@lForYear)
		
		set @Firstdate=CONVERT(nvarchar(20), @lForYear)+ '-' +  CONVERT(nvarchar(20), @lForMonth) + '-' + CONVERT(nvarchar(20), 01)
		set @Lastdate=CONVERT(nvarchar(20), @lForYear)+ '-' +  CONVERT(nvarchar(20), @lForMonth) + '-' + CONVERT(nvarchar(20), @Days)

 INSERT INTO #TempMonthTrans 
  select *
   from [sBiometric].[fBiometricTempMonthTransGet](@rOrgId ,@rOrganizationDepartmentId ,@rFromDate,@rToDate,@rEmployeeId)  
 

		
	 SELECT 
		@rBuilder1 AS Builder1,
		@rBuilder2 as Builder2,
		TM.Id,
		TM.EmployeeId,
		TM.Attn_Date,
		OGD.Title AS [OrganizationGroupDepartment],
		TM.PresentStatus as PresentStatus,
		TM.FirstIn,
		TM.LastOut,
		TM.OverTime,
		TM.LateBy,
		TM.Duration,
		TM.EarlyBy,
		TM.ShiftName,
		 MT.Tot_Attn,
		 EM.FirstName + ' ' + EM.LastName As ShortName,
		 EM.Code as EmpCode ,   
		[sBiometric].[fEmployeeLeaveTypeGet] (TM.ATTN_DATE,TM.EmployeeId) AS LeaveStatus ,  
		ISNULL(ELS.Id,0) AS EmployeeLateStatusId, 
		ISNULL(SM.Id,0) AS StatusId,  
		ISNULL(SM.Title,'') AS Status ,
		 OM.Id AS OrgId,
		OM.Title AS OrganizationTitle  
	 FROM #TempMonthTrans TM   
	 INNER JOIN sBiometric.tMonthTrans MT ON MT.EmployeeId=TM.EmployeeId AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0)  
	 INNER JOIN sHRM.tEmployeeMaster EM ON EM.Id=TM.EmployeeId  
	 LEFT JOIN sBiometric.tEmployeeLateStatus ELS ON ELS.EmployeeId = TM.EmployeeId AND CONVERT(date,TM.Attn_Date) = CONVERT(date,ELS.LateDate)  
	 LEFT JOIN sCommon.tStatusMaster SM ON SM.Id = ELS.StatusId  
	 INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id AND (TM.ATTN_DATE >= ISNULL(cast(rtrim(YEAR(EJD.DateOfJoining) *10000+ Month(EJD.DateOfJoining) *100+ 01) as datetime),'1900/01/01'))
	 INNER JOIN sSetup.tDepartmentMaster ODM ON EJD.OrganizationDepartmentId = ODM.Id 
	 LEFT JOIN sCommon.tOrgGroupDepartmentMaster OGD ON  EJD.OrgGroupDepartmentId=OGD.Id
	 INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = EM.OrgId
	 WHERE   
	 TM.ATTN_DATE >= @rFromDate AND TM.ATTN_DATE <=@rToDate    
	 AND (TM.EmployeeId = @rEmployeeId OR @rEmployeeId = 0)   
	 AND MT.Attn_dt=cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime)
	 AND (( @rTimeSheetStatus = '1' AND (TM.Duration < '09:30')) OR ( @rTimeSheetStatus != '1' AND ((PresentStatus = @rTimeSheetStatus OR @rTimeSheetStatus='0'))))
	 AND (EM.OrgId = @rOrgId OR @rOrgId = 0)
	 AND (OM.OrgGroupId = @rOrgGroupId)
	 AND ((EM.StatusId = @rEmployeeStatusId) OR (@rEmployeeStatusId = 0))
	 AND((EJD.OrganizationDepartmentId=@rOrganizationDepartmentId) OR (@rOrganizationDepartmentId=0))
	 AND ((EJD.OrgGroupDepartmentId = @rOrgGroupDepartmentId) OR (@rOrgGroupDepartmentId=0)) 
	 AND  ISNULL(EM.IsOtherUser,0) = 0
	 AND (EJD.DateOfJoining<= @Lastdate OR ISNULL(EJD.DateOfJoining,'')='')
	 AND (EJD.DateOfleaving>= @Firstdate OR ISNULL(EJD.DateOfleaving,'')='')
	 AND (EmployeeGradeId in ( SELECT cast(item as int) FROM  sCommon.fnsplit(@rGradeId,',')) OR @rGradeId=0) 
	 Order By TM.EmployeeId,TM.Attn_Date

 --SELECT  @rBuilder1 AS Builder1,
	--@rBuilder2 as Builder2,
	--0 as Id,
	--CAST(0 AS bigint) AS EmployeeId,
	--CAST('1999-01-01 00:00:00' AS datetime) as Attn_Date,
	--'' AS OldPresentStatus,
	--'' AS [OrganizationGroupDepartment],
	--'' as PresentStatus,
	--'' as FirstIn,
	--'' AS LastOut,
	--'' as OverTime,
	--'' as LateBy,
	--'' as Duration,
	--'' as EarlyBy,
	--'' as ShiftName, 
	--'' As ShortName,
	--'' as EmpCode ,
	--'' AS LeaveStatus , 
	--'' AS LeavePendingStatus, 
	--'' AS EmployeeTravel,
	--0 AS EmployeeLateStatusId, 
	--0 AS StatusId, 
	--'' AS Status,
	--0 AS OrgId,
 --  '' AS OrganizationTitle  

 end
GO
PRINT N'Altering Procedure [sCommunication].[pAssignmentGet]...';


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

BEGIN 
	 IF @rIsSearch = 1
		BEGIN
			SET @rTitle = sCommon.fSearchStringGet(@rTitle)
		END
	
	SELECT 
			DISTINCT
			A.Id as AssignmentId,
			A.SubjectId,
			SM.Title as SubjectName,
			A.Title,
			A.Remark,
			A.StartDate,
			A.EndDate,
			U.DisplayTitle as CreatedUserName,
			ISNULL(IsAssignmentDocumentUpload,0) AS IsAssignmentDocumentUpload
			--ISNULL(AV.Remark,'') AS ViewRemark
		    
  FROM 
   --         sCommunication.tAssignment A
			--INNER JOIN [sCommunication].[tAssignmentScope] CAS on A.Id = CAS.AssignmentId
   --         INNER JOIN sSecurity.tUser U ON U.Id=A.CreatedUserId
   --         INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=A.SubjectId
			--INNER JOIN [sSetup].[tClassSubject] CS on CS.SubjectId = SM.Id	
			--LEFT JOIN [sSetup].[tDivisionMaster] DM on DM.Id = CAS.SourceId and CS.ClassId = Dm.classId 
			--LEFT JOIN sCommunication.tAssignmentView AV ON A.Id = AV.AssignmentId
			 sCommunication.tAssignment A
			INNER JOIN [sCommunication].[tAssignmentScope] CAS on A.Id = CAS.AssignmentId
            INNER JOIN sSecurity.tUser U ON U.Id=A.CreatedUserId
            INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=A.SubjectId
			LEFT JOIN [sSetup].[tDivisionMaster] DM on DM.Id = CAS.SourceId AND CAS.SourceTypeId = 2005
			--LEFT JOIN sCommunication.tAssignmentView AV ON A.Id = AV.AssignmentId  -- Comment for duplicate data in mobile side for MantisId: 0027677
  WHERE 
  
      ((A.Id = @rId) OR (@rId = 0))
    AND ((A.SubjectId = @rSubjectId) OR (@rSubjectId = 0))
	AND ((A.Title like @rTitle) OR (ISNULL(@rTitle,'') = ''))
	AND ((A.StartDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
	AND ((A.StartDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
	AND ((A.CreatedUserId = @rCreatedUserId) OR (@rCreatedUserId = 0))
	AND A.BatchId=@rBatchId
END
GO
PRINT N'Altering Procedure [sFee].[pChargeAccountMappingGet]...';


GO
ALTER PROCEDURE [sFee].[pChargeAccountMappingGet]
				
		   @rBuilder1 nvarchar(max)='',
		   @rBuilder2 nvarchar(max)='', 
		 
           --@rChargeCategoryId int,
		   --@rBatchId int,
		   @rOrgGroupId int, 
		   @rChargeCategoryId int,
		   @rPayTypeId int=0			--add for 27383 mantis
		   
           
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
BEGIN 
	SELECT  
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			 ISNULL(CM.Id,0)AS ChargeId,
			ISNULL(AM.ChargeId,0)AS AMChargeId,
			--ISNULL(FS.ClassId,0)AS ClassId,
			 
			ISNULL(CM.ChargeCategoryId,0) AS ChargeCategoryId,
			--ISNULL(CR.BatchId,0)AS BatchId,
			 
			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,
			ISNULL(RB.TItle,'') AS ReceiptBookTitle,
			ISNULL(RB.Id,0) AS ReceiptBookId ,
			CM.Title AS ChargeTitle
  FROM 
		  sFee.tChargeMaster CM
		  inner join  sFee.tChargeCategoryMaster CCM ON CCM.Id = CM.ChargeCategoryId AND CM.ChargeCategoryId=@rChargeCategoryId
		 --INNER JOIN sFee.tChargeReceiptDetail CE ON CE.ChargeId = CM.Id AND CM.ChargeCategoryId=@rChargeCategoryId
		 --INNER JOIN sFee.tChargeReceipt CR ON CR.Id=CE.ChargeReceiptId
		INNER JOIN  sFee.tChargeReceiptBookMaster RB ON CCM.ChargeReceiptBookId = RB.Id
		Cross JOIN sFinanceCommon.tPayTypeMaster PTM
		LEFT JOIN sFee.tChargeAccountMapping AM ON AM.ChargeId=CM.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 
		CM.OrgGroupId=@rOrgGroupId
		AND ((PTM.Id=@rPayTypeId) or (@rPayTypeId=0))		--add for 27383 mantis

ORDER BY  PTM.Id

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


GO
ALTER PROCEDURE [sFee].[pConsolidateFeeStatusDashboardGet]
	@rType int =0,
	@rCommonOrgGroupBatchId int=0,
	@rOrgGroupId smallint=0,
	@rReceiptBookId int =0,
	@rOrgId int  =0,
	@rFeeHeadId int =0,
	@rFeeId int =0
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
	
	IF OBJECT_ID('tempdb..#TempFeeSetupData') IS NOT NULL DROP TABLE #TempFeeSetupData
	
	SELECT * 
	INTO #TempFeeSetupData
	FROM 
	(
		SELECT 
			FS1.FeeId,
			FS1.Id,
			ISNULL(FS1.Amount,0)AS Amount,
			ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
			FM.Title AS FeeName,
			FM.Id AS FeeMasterId,
			SA1.AcademicId,
			FM.FeeHeadId,
			FM.OrderIndex
		FROM sFee.tFeeSetup FS1
		INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
		INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
		WHERE FS1.IsOptional=0

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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


GO
ALTER PROCEDURE [sFee].[pFeeImportAdd]
	
	@rClassId int=0,
	@rFromBatchId int,
	@rToBatchId int,
	@rOrgId int,
	@rCreatedUserId bigint,
	@rAddMonthInDate int = 0,
	@rOrgGroupId int =0
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
BEGIN TRY 

	IF EXISTS (SELECT 1 FROM sFee.tFeeSetup WHERE BatchId = @rToBatchId AND ((ClassId = @rClassId) OR (@rClassId=0)))
	BEGIN
		SELECT -101 AS RESULT
		RETURN
	END
	
	BEGIN TRANSACTION
	Declare @lCount int
	DECLARE @lNextNumber INT
	-- Fee Setup Temp Table
	CREATE TABLE #TempFeeMaster(
	[AutoId] int identity,
	[Id] [int] NOT NULL,
	[ClassId] [int] NULL,
	[AdmissionCategoryId] [int] NULL,
	[BatchId] [int] NOT NULL,
	[FeeId] [int] NOT NULL,
	[IsVariable] [bit] NOT NULL,
	[IsOptional] [bit] NULL,
	[Amount] [decimal](12, 2) NOT NULL,
	[StartDate] [date] NOT NULL,
	[EndDate] [date] NOT NULL,
	[ReceiptBookId] [int] NULL,
	[CreatedUserId] [bigint] NOT NULL,
	[CreatedDateTime] [datetime] NOT NULL,
	[UpdatedUserId] [bigint] NULL,
	[UpdatedDateTime] [datetime] NULL,
	[IsServiceTax] [bit] NULL,
	[CollectionGroupId] [int] NULL,
	[FeeDuration] [nvarchar](100),
	[OldFeeSetupId]	[int],		
	[LevelAmount] [decimal](12,2),
	[LateFeeRuleId] [int]
	)
	-- End Create Table
	
	INSERT INTO #TempFeeMaster SELECT * FROM sFee.tFeeSetup WHERE BatchId=@rFromBatchId AND ((ClassId = @rClassId) OR (@rClassId=0))
	
	Select @lCount = COUNT(Id) From #TempFeeMaster
	
	While (@lCount > 0)
	BEGIN
		-- Collection Group Entry
		
		DECLARE @lOrgGroupBatchId int =0
		DECLARE @lCollectionGroupId int=0 
		DECLARE @lReceiptBookId int=0
		DECLARE @lCode nvarchar(20)=''
		DECLARE @lTitle nvarchar(100)=''
		
		SELECT @lReceiptBookId=ReceiptBookId,@lCollectionGroupId=CollectionGroupId FROM #TempFeeMaster WHERE AutoId = @lCount
		SELECT @lOrgGroupBatchId=OrgGroupBatchId FROM sSetup.tBatchMaster WHERE Id = @rToBatchId
		SELECT @lCode=Code,@lTitle=Title FROM sFee.tCollectionGroupMaster WHERE Id = @lCollectionGroupId
		
		IF NOT EXISTS (SELECT 1 FROM sFee.tCollectionGroupMaster WHERE Code=@lCode AND Title=@lTitle AND OrgGroupBatchId=@lOrgGroupBatchId AND ReceiptBookId=@lReceiptBookId)
		BEGIN
			DECLARE @lNumber int=0
			DECLARE @lOrderIndex smallint=0 
			SELECT @lOrderIndex=MAX(OrderIndex) FROM sFee.tCollectionGroupMaster WHERE OrgGroupBatchId = @lOrgGroupBatchId
			EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sFee.tCollectionGroupMaster', 0, 1, 1,@outNextNumber = @lNumber output
			INSERT INTO sFee.tCollectionGroupMaster
			SELECT 
				@lOrgGroupBatchId,@lNumber,Code,Title,DATEADD(MONTH,@rAddMonthInDate,StartDate),DATEADD(MONTH,@rAddMonthInDate,EndDate),
				Remark,IsObsolete,@lOrderIndex,ReceiptBookId,FooterRemark1,FooterRemark2,FeePeriod,IsDisplayCashDetailInFolio,ReportId,IsOnPrePrinted
			FROM sFee.tCollectionGroupMaster Where Id = @lCollectionGroupId
		END 
		
		SELECT @lCollectionGroupId=Id FROM sFee.tCollectionGroupMaster WHERE Code = @lCode AND Title=@lTitle AND OrgGroupBatchId=@lOrgGroupBatchId AND ReceiptBookId=@lReceiptBookId
		
		-- END Collection Group Entry
		
		-- Fee Setup Entry
		
		EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sFee.tFeeSetup', 0, 1, 1,@outNextNumber = @lNextNumber output
		INSERT INTO sFee.tFeeSetup 
		SELECT 
				@lNextNumber,ClassId,AdmissionCategoryId,@rToBatchId,FeeId,ISNULL(IsVariable,0),ISNULL(IsOptional,0),Amount,
				DATEADD(MONTH,@rAddMonthInDate,StartDate),DATEADD(MONTH,@rAddMonthInDate,EndDate),ReceiptBookId,@rCreatedUserId,sCommon.fGetDate(),NULL,NULL,IsServiceTax,@lCollectionGroupId,FeeDuration,Id,LevelAmount,LateFeeRuleId
		FROM #TempFeeMaster Where AutoId = @lCount
		
		-- END Fee Setup Entry
		Set @lCount = @lCount -1
	END

	Drop Table #TempFeeMaster 
	SELECT 1 AS Result
	COMMIT TRANSACTION
END TRY

BEGIN CATCH 
Drop Table #TempFeeMaster 
		ROLLBACK TRANSACTION
		
		SELECT -1 AS Result
END CATCH	
END
GO
PRINT N'Altering Procedure [sFee].[pPendingFeeDashboardGet]...';


GO
ALTER PROCEDURE [sFee].[pPendingFeeDashboardGet]

		@rOrgGroupBatchId int = 0,
		@rCommonOrgGroupBatchId int = 0,
		@rType int,
		@rFilterType nvarchar(Max),
		@rFeeType nvarchar(Max),
		@rStudentStatus int = 0,
		@rUptoDate date = '',
		@rDepartmentId int=0,
	    @rOrgId int,
		@rReceiptBookId int,
		@rOrgGroupId int = 0

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

SELECT @rOrgGroupBatchId = Id FROM sSetup.tOrgGroupBatchMaster WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND OrgGroupId = @rOrgGroupId

IF (@rType = 1)
 BEGIN
IF(@rFilterType = 'Organizationwise')		
	BEGIN 
	 IF(@rFeeType = 'FeeHeadwise')
	 BEGIN
		--SELECT
		--	SA.OrgId,
		--	O.Title AS OrgName,
		--	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,
		--	FHM.Id AS FeeHeadId,
		--	FHM.Title AS FeeHeadName,
		--	FHM.OrderIndex
		--FROM
		--	sStudent.vStudentAcademic SA
		--	INNER JOIN sSetup.tOrganizationMaster O ON SA.OrgId = O.Id
		--	INNER JOIN 
		--	(
		--		SELECT 
		--			ISNULL(FS1.Amount,0)AS Amount,
		--			FM.Title AS FeeName,
		--			FM.FeeHeadId,
		--			SA1.Id As AcademicId,
		--			FS1.Id,
		--			FS1.StartDate
 	--			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 sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
		--		WHERE 
		--			BM.OrgGroupBatchId = @rOrgGroupBatchId
		--			AND (FS1.IsOptional=0)
		--			-- IsInContext
		--			AND BM.IsInContext = 1
		--		UNION ALL
		--		SELECT 
		--			ISNULL(FS1.Amount,0)AS Amount,
		--			FM.Title AS FeeName,
		--			FM.FeeHeadId,
		--			SA1.AcademicId As AcademicId,
		--			FS1.Id,
		--			FS1.StartDate
		--		FROM sFee.tFeeSetup FS1
		--		INNER JOIN sFee.tFeeOptional FO ON FO.FeeSetupId=FS1.Id
		--		INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
		--		INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=FO.SourceId 
		--		AND SA1.BatchId = FS1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId AND SA1.ClassId = FS1.ClassId
		--		INNER JOIN sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
		--		WHERE
		--				SA1.OrgGroupBatchId = @rOrgGroupBatchId
		--				AND (FS1.IsOptional=1)
		--				-- IsInContext
		--				AND BM.IsInContext = 1
		--		) FS ON FS.AcademicId=SA.AcademicId
		--		LEFT JOIN sFee.tFeeAllocation FA ON FA.FeeSetupId=FS.Id AND FA.SourceId=SA.AcademicId
		--		LEFT JOIN
		--		(
		--			SELECT 
		--			    ISNULL(SUM(RD.Amount),0) AS PaidAmount,RD.FeeSetupId ,R.SourceId
		--			FROM
		--				sFee.tReceipt R 
		--				INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id 
		--				INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id
		--				INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id
		--				INNER JOIN sStudent.tAcademic SA1 ON SA1.Id=R.SourceId
		--				INNER JOIN sSetup.tBatchMaster BM ON BM.Id=SA1.BatchId			
		--			WHERE		
		--				(R.SourceTypeId = 2001)
		--				AND (R.IsObsolete = 0) 
		--				AND ((BM.OrgGroupBatchId = @rOrgGroupBatchId))
		--				AND (R.OrgGroupBatchId = @rOrgGroupBatchId)
		--				AND (R.ReceiptDate <= @rUptoDate) 
		--				-- IsInContext
		--				AND BM.IsInContext = 1 
		--				GROUP BY FeeSetupId,R.SourceId
		--		) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
		--		INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id = FS.FeeHeadId	
		--		INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId
		--	WHERE
		--	  SA.OrgGroupBatchId = @rOrgGroupBatchId
		--	  AND (SA.StatusId = @rStudentStatus OR @rStudentStatus=0)
		--	  AND ((FS.StartDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
		--	  -- IsInContext
		--	  AND BM.IsInContext = 1
		--	GROUP BY SA.OrgId,O.Title,FHM.Id,FHM.Title,FHM.OrderIndex
		--	ORDER BY OrgId,FHM.OrderIndex

		CREATE TABLE #FeeHeadwisetmp
		(
		Amount decimal (12,2),
		FeeName nvarchar(100),
		FeeHeadId int,
		AcademicId bigint,
		Id int,
		StartDate date
		--ReceiptBookId int 
		)

		INSERT INTO #FeeHeadwisetmp
		SELECT 
					ISNULL(FS1.Amount,0)AS Amount,
					FM.Title AS FeeName,
					FM.FeeHeadId,
					SA1.Id As AcademicId,
					FS1.Id,
					FS1.StartDate
 				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 sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
				WHERE 
					BM.OrgGroupBatchId = @rOrgGroupBatchId
					AND (FS1.IsOptional=0)
					-- IsInContext
					AND BM.IsInContext = 1
				UNION ALL
				SELECT 
					ISNULL(FS1.Amount,0)AS Amount,
					FM.Title AS FeeName,
					FM.FeeHeadId,
					SA1.AcademicId As AcademicId,
					FS1.Id,
					FS1.StartDate
				FROM sFee.tFeeSetup FS1
				INNER JOIN sFee.tFeeOptional FO ON FO.FeeSetupId=FS1.Id
				INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
				INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=FO.SourceId 
				AND SA1.BatchId = FS1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId AND SA1.ClassId = FS1.ClassId
				INNER JOIN sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
				WHERE
						SA1.OrgGroupBatchId = @rOrgGroupBatchId
						AND (FS1.IsOptional=1)
						-- IsInContext
						AND BM.IsInContext = 1

		SELECT
			SA.OrgId,
			O.Title AS OrgName,
			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,
			FHM.Id AS FeeHeadId,
			FHM.Title AS FeeHeadName,
			FHM.OrderIndex
		FROM
			sStudent.vStudentAcademic SA
			INNER JOIN sSetup.tOrganizationMaster O ON SA.OrgId = O.Id
			INNER JOIN #FeeHeadwisetmp 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.tAcademic SA1 ON SA1.Id=R.SourceId
					INNER JOIN sSetup.tBatchMaster BM ON BM.Id=SA1.BatchId			
				WHERE		
					(R.SourceTypeId = 2001)
					AND (R.IsObsolete = 0) 
					AND ((BM.OrgGroupBatchId = @rOrgGroupBatchId))
					AND (R.OrgGroupBatchId = @rOrgGroupBatchId)
					AND (R.ReceiptDate <= @rUptoDate) 
					-- IsInContext
					AND BM.IsInContext = 1 
					GROUP BY FeeSetupId,R.SourceId
			) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
			INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id = FS.FeeHeadId	
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId
			WHERE
			  SA.OrgGroupBatchId = @rOrgGroupBatchId
			  AND (SA.StatusId = @rStudentStatus OR @rStudentStatus=0)
			  AND ((FS.StartDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
			  -- IsInContext
			  AND BM.IsInContext = 1
			GROUP BY SA.OrgId,O.Title,FHM.Id,FHM.Title,FHM.OrderIndex,O.OrderIndex
			ORDER BY O.OrderIndex,OrgId,FHM.OrderIndex

		DROP TABLE #FeeHeadwisetmp
	 END
	 ELSE IF(@rFeeType = 'FeeMasterwise')
	 BEGIN
		CREATE TABLE #FeeMasterwisetmp
		(
			FeeId int,
			Amount decimal (12,2),
			FeeName nvarchar(100),
			FeeHeadId int,
			AcademicId bigint,
			Id int,
			StartDate date,
			OrderIndex int
		)
	 
	 INSERT INTO #FeeMasterwisetmp
		 SELECT 
			FS1.FeeId,
			ISNULL(FS1.Amount,0)AS Amount,
			FM.Title AS FeeName,
			FM.FeeHeadId,
			SA1.Id As AcademicId,
			FS1.Id,
			FS1.StartDate,
			FM.OrderIndex
 		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 sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
		WHERE 
			BM.OrgGroupBatchId = @rOrgGroupBatchId
			AND (FS1.IsOptional=0)
			-- IsInContext
			AND BM.IsInContext = 1
		UNION ALL
		SELECT 
			FS1.FeeId,
			ISNULL(FS1.Amount,0)AS Amount,
			FM.Title AS FeeName,
			FM.FeeHeadId,
			SA1.AcademicId As AcademicId,
			FS1.Id,
			FS1.StartDate,
			FM.OrderIndex
		FROM sFee.tFeeSetup FS1
		INNER JOIN sFee.tFeeOptional FO ON FO.FeeSetupId=FS1.Id
		INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
		INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=FO.SourceId 
		AND SA1.BatchId = FS1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId AND SA1.ClassId = FS1.ClassId
		INNER JOIN sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
		WHERE
				SA1.OrgGroupBatchId = @rOrgGroupBatchId
				AND (FS1.IsOptional=1)
				-- IsInContext
				AND BM.IsInContext = 1

	 SELECT
			SA.OrgId,
			O.Title AS OrgName,
			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,
			FS.FeeId,
			FS.FeeName,
			FS.OrderIndex
		FROM
			sStudent.vStudentAcademic SA
				INNER JOIN sSetup.tOrganizationMaster O ON SA.OrgId = O.Id
				INNER JOIN #FeeMasterwisetmp 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.tAcademic SA1 ON SA1.Id=R.SourceId
						INNER JOIN sSetup.tBatchMaster BM ON BM.Id=SA1.BatchId			
					WHERE		
						(R.SourceTypeId = 2001)
						AND (R.IsObsolete = 0) 
						AND ((BM.OrgGroupBatchId = @rOrgGroupBatchId))
						AND (R.OrgGroupBatchId = @rOrgGroupBatchId)
						AND (R.ReceiptDate <= @rUptoDate) 
						-- IsInContext
						AND BM.IsInContext = 1 
						GROUP BY FeeSetupId,R.SourceId
				) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
				INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id = FS.FeeHeadId	
				INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId
			WHERE
				SA.OrgGroupBatchId = @rOrgGroupBatchId
				AND (SA.StatusId = @rStudentStatus OR @rStudentStatus=0)
				AND ((FS.StartDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
				-- IsInContext
				AND BM.IsInContext = 1
			GROUP BY SA.OrgId,O.Title,FS.FeeId,FS.FeeName,FS.OrderIndex,O.OrderIndex
			ORDER BY O.OrderIndex,OrgId,FS.FeeId
	 DROP TABLE #FeeMasterwisetmp
	 END
	 ELSE IF(@rFeeType = 'CollectionGroupwise')
	 BEGIN
		CREATE TABLE #CollectionGroupwisetmp
		(
			FeeId int,
			Amount decimal (12,2),
			FeeName nvarchar(100),
			FeeHeadId int,
			AcademicId bigint,
			Id int,
			StartDate date,
			CollectionGroupId int
		)
	 INSERT INTO #CollectionGroupwisetmp
	 SELECT 
			FS1.FeeId,
			ISNULL(FS1.Amount,0)AS Amount,
			FM.Title AS FeeName,
			FM.FeeHeadId,
			SA1.Id As AcademicId,
			FS1.Id,
			FS1.StartDate,
			FS1.CollectionGroupId
 		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 sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
		WHERE 
			BM.OrgGroupBatchId = @rOrgGroupBatchId
			AND (FS1.IsOptional=0)
			-- IsInContext
			AND BM.IsInContext = 1
		UNION ALL
		SELECT 
			FS1.FeeId,
			ISNULL(FS1.Amount,0)AS Amount,
			FM.Title AS FeeName,
			FM.FeeHeadId,
			SA1.AcademicId As AcademicId,
			FS1.Id,
			FS1.StartDate,
			FS1.CollectionGroupId
		FROM sFee.tFeeSetup FS1
		INNER JOIN sFee.tFeeOptional FO ON FO.FeeSetupId=FS1.Id
		INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
		INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=FO.SourceId 
		AND SA1.BatchId = FS1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId AND SA1.ClassId = FS1.ClassId
		INNER JOIN sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
		WHERE
				SA1.OrgGroupBatchId = @rOrgGroupBatchId
				AND (FS1.IsOptional=1)
				-- IsInContext
				AND BM.IsInContext = 1

	 SELECT
			SA.OrgId,
			O.Title AS OrgName,
			SUM(ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00))AS PendingAmount,
			ISNULL(CGM.Id,0) AS CollectionGroupId,
			ISNULL(CGM.Title,'') AS CollectionGroupName,
			ISNULL(CGM.OrderIndex,0) AS OrderIndex
		FROM
			sStudent.vStudentAcademic SA
			INNER JOIN sSetup.tOrganizationMaster O ON SA.OrgId = O.Id
			INNER JOIN #CollectionGroupwisetmp 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.tAcademic SA1 ON SA1.Id=R.SourceId
						INNER JOIN sSetup.tBatchMaster BM ON BM.Id=SA1.BatchId			
					WHERE		
						(R.SourceTypeId = 2001)
						AND (R.IsObsolete = 0) 
						AND ((BM.OrgGroupBatchId = @rOrgGroupBatchId))
						AND (R.OrgGroupBatchId = @rOrgGroupBatchId)
						AND (R.ReceiptDate <= @rUptoDate) 
						-- IsInContext
						AND BM.IsInContext = 1 
						GROUP BY FeeSetupId,R.SourceId
				) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
				LEFT JOIN sFee.tCollectionGroupMaster CGM ON FS.CollectionGroupId=CGM.Id
				INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId
			WHERE
			  SA.OrgGroupBatchId = @rOrgGroupBatchId
			  AND (SA.StatusId = @rStudentStatus OR @rStudentStatus=0)
			  AND ((FS.StartDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
			  -- IsInContext
			  AND BM.IsInContext = 1
			GROUP BY SA.OrgId,O.Title,CGM.Id,CGM.Title,CGM.OrderIndex,O.OrderIndex
			ORDER BY O.OrderIndex,OrgId,CGM.Id

	 DROP TABLE #CollectionGroupwisetmp
	 END
	END
ELSE IF(@rFilterType = 'Departmentwise')
	BEGIN
	 IF(@rFeeType = 'FeeHeadwise')
	 BEGIN
		IF OBJECT_ID('tempdb..#tmpDepartFeeHeadWise') IS NOT NULL DROP TABLE #tmpDepartFeeHeadWise
		CREATE TABLE #tmpDepartFeeHeadWise
		(
		Amount decimal (12,2),
		FeeName nvarchar(100),
		FeeHeadId int,
		AcademicId bigint,
		Id int,
		StartDate date
		)

		Insert Into #tmpDepartFeeHeadWise
		SELECT 
					ISNULL(FS1.Amount,0)AS Amount,
					FM.Title AS FeeName,
					FM.FeeHeadId,
					SA1.Id As AcademicId,
					FS1.Id,
					FS1.StartDate
 				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 sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
				WHERE 
					BM.OrgGroupBatchId = @rOrgGroupBatchId
					AND (FS1.IsOptional=0)
					-- IsInContext
					AND BM.IsInContext = 1
				UNION ALL
				SELECT 
					ISNULL(FS1.Amount,0)AS Amount,
					FM.Title AS FeeName,
					FM.FeeHeadId,
					SA1.AcademicId As AcademicId,
					FS1.Id,
					FS1.StartDate
				FROM sFee.tFeeSetup FS1
				INNER JOIN sFee.tFeeOptional FO ON FO.FeeSetupId=FS1.Id
				INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
				INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=FO.SourceId 
				AND SA1.BatchId = FS1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId AND SA1.ClassId = FS1.ClassId
				INNER JOIN sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
				WHERE
						SA1.OrgGroupBatchId = @rOrgGroupBatchId
						AND (FS1.IsOptional=1)
						-- IsInContext
						AND BM.IsInContext = 1

		SELECT
			SA.DepartmentId,
		    SA.DepartmentName,
			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,
			FHM.Id AS FeeHeadId,
			FHM.Title AS FeeHeadName,
			FHM.OrderIndex
		FROM
			sStudent.vStudentAcademic SA
		INNER JOIN sSetup.tOrganizationMaster O ON SA.OrgId = O.Id
		INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id = SA.DepartmentId
		INNER JOIN #tmpDepartFeeHeadWise 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.tAcademic SA1 ON SA1.Id=R.SourceId
				INNER JOIN sSetup.tBatchMaster BM ON BM.Id=SA1.BatchId			
			WHERE		
				(R.SourceTypeId = 2001)
				AND (R.IsObsolete = 0) 
				AND ((BM.OrgGroupBatchId = @rOrgGroupBatchId))
				AND (R.OrgGroupBatchId = @rOrgGroupBatchId)
				AND (R.ReceiptDate <= @rUptoDate)
				-- IsInContext
				AND BM.IsInContext = 1  
				GROUP BY FeeSetupId,R.SourceId
		) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
		INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id = FS.FeeHeadId	
		INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId
		WHERE
			  SA.OrgGroupBatchId = @rOrgGroupBatchId
			  AND (SA.StatusId = @rStudentStatus OR @rStudentStatus=0)
			  AND ((FS.StartDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
			  -- IsInContext
			  AND BM.IsInContext = 1 
		GROUP BY SA.DepartmentId,SA.DepartmentName,FHM.Id,FHM.Title,FHM.OrderIndex,DM.OrderIndex
		ORDER BY DM.OrderIndex,DepartmentId,FHM.Id
	 END
	 ELSE IF(@rFeeType = 'FeeMasterwise')
	 BEGIN

		IF OBJECT_ID('tempdb..#tmpDepartFeeMasterwise') IS NOT NULL DROP TABLE #tmpDepartFeeMasterwise
		CREATE TABLE #tmpDepartFeeMasterwise
		(
		FeeId int,
		Amount decimal (12,2),
		FeeName nvarchar(100),
		FeeHeadId int,
		AcademicId bigint,
		Id int,
		StartDate date,
		OrderIndex int
		)

		Insert Into #tmpDepartFeeMasterwise
		SELECT 
					FS1.FeeId,
					ISNULL(FS1.Amount,0)AS Amount,
					FM.Title AS FeeName,
					FM.FeeHeadId,
					SA1.Id As AcademicId,
					FS1.Id,
					FS1.StartDate,
					FM.OrderIndex
 				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 sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
				WHERE 
					BM.OrgGroupBatchId = @rOrgGroupBatchId
					AND (FS1.IsOptional=0)
					-- IsInContext
					AND BM.IsInContext = 1
				UNION ALL
				SELECT 
					FS1.FeeId,
					ISNULL(FS1.Amount,0)AS Amount,
					FM.Title AS FeeName,
					FM.FeeHeadId,
					SA1.AcademicId As AcademicId,
					FS1.Id,
					FS1.StartDate,
					FM.OrderIndex
				FROM sFee.tFeeSetup FS1
				INNER JOIN sFee.tFeeOptional FO ON FO.FeeSetupId=FS1.Id
				INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
				INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=FO.SourceId 
				AND SA1.BatchId = FS1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId AND SA1.ClassId = FS1.ClassId
				INNER JOIN sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
				WHERE
						SA1.OrgGroupBatchId = @rOrgGroupBatchId
						AND (FS1.IsOptional=1)
						-- IsInContext
						AND BM.IsInContext = 1


		SELECT
			SA.DepartmentId,
		    SA.DepartmentName,
			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,
			FS.FeeId,
			FS.FeeName,
			FS.OrderIndex
		FROM
			sStudent.vStudentAcademic SA
				INNER JOIN sSetup.tOrganizationMaster O ON SA.OrgId = O.Id
				INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id = SA.DepartmentId
				INNER JOIN #tmpDepartFeeMasterwise 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.tAcademic SA1 ON SA1.Id=R.SourceId
						INNER JOIN sSetup.tBatchMaster BM ON BM.Id=SA1.BatchId			
					WHERE		
						(R.SourceTypeId = 2001)
						AND (R.IsObsolete = 0) 
						AND ((BM.OrgGroupBatchId = @rOrgGroupBatchId))
						AND (R.OrgGroupBatchId = @rOrgGroupBatchId)
						AND (R.ReceiptDate <= @rUptoDate)  
						-- IsInContext
						AND BM.IsInContext = 1
						GROUP BY FeeSetupId,R.SourceId
				) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
				INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id = FS.FeeHeadId	
				INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId
			WHERE
			  SA.OrgGroupBatchId = @rOrgGroupBatchId
			  AND (SA.StatusId = @rStudentStatus OR @rStudentStatus=0)
			  AND ((FS.StartDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
			  -- IsInContext
			  AND BM.IsInContext = 1
			GROUP BY SA.DepartmentId,SA.DepartmentName,FS.FeeId,FS.FeeName,FS.OrderIndex,DM.OrderIndex
			ORDER BY DM.OrderIndex,DepartmentId,FS.FeeId
	 END
	 ELSE IF(@rFeeType = 'CollectionGroupwise')
	 BEGIN
		IF OBJECT_ID('tempdb..#tmpDepartCollectionGroupwise') IS NOT NULL DROP TABLE #tmpDepartCollectionGroupwise
		CREATE TABLE #tmpDepartCollectionGroupwise
		(
		FeeId int,
		Amount decimal (12,2),
		FeeName nvarchar(100),
		FeeHeadId int,
		AcademicId bigint,
		Id int,
		StartDate date,
		CollectionGroupId int
		)

		INSERT INTO #tmpDepartCollectionGroupwise
		SELECT 
					FS1.FeeId,
					ISNULL(FS1.Amount,0)AS Amount,
					FM.Title AS FeeName,
					FM.FeeHeadId,
					SA1.Id As AcademicId,
					FS1.Id,
					FS1.StartDate,
					FS1.CollectionGroupId
 				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 sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
				WHERE 
					BM.OrgGroupBatchId = @rOrgGroupBatchId
					AND (FS1.IsOptional=0)
					-- IsInContext
					AND BM.IsInContext = 1
				UNION ALL
				SELECT 
					FS1.FeeId,
					ISNULL(FS1.Amount,0)AS Amount,
					FM.Title AS FeeName,
					FM.FeeHeadId,
					SA1.AcademicId As AcademicId,
					FS1.Id,
					FS1.StartDate,
					FS1.CollectionGroupId
				FROM sFee.tFeeSetup FS1
				INNER JOIN sFee.tFeeOptional FO ON FO.FeeSetupId=FS1.Id
				INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
				INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=FO.SourceId 
				AND SA1.BatchId = FS1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId AND SA1.ClassId = FS1.ClassId
				INNER JOIN sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
				WHERE
						SA1.OrgGroupBatchId = @rOrgGroupBatchId
						AND (FS1.IsOptional=1)
						-- IsInContext
						AND BM.IsInContext = 1


		SELECT
			SA.DepartmentId,
		    SA.DepartmentName,
			SUM(ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00))AS PendingAmount,
			ISNULL(CGM.Id,0) AS CollectionGroupId,
			ISNULL(CGM.Title,'') AS CollectionGroupName,
			ISNULL(CGM.OrderIndex,0) AS OrderIndex
		FROM
			sStudent.vStudentAcademic SA
				INNER JOIN sSetup.tOrganizationMaster O ON SA.OrgId = O.Id
				INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id = SA.DepartmentId
				INNER JOIN #tmpDepartCollectionGroupwise 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.tAcademic SA1 ON SA1.Id=R.SourceId
						INNER JOIN sSetup.tBatchMaster BM ON BM.Id=SA1.BatchId			
					WHERE		
						(R.SourceTypeId = 2001)
						AND (R.IsObsolete = 0) 
						AND ((BM.OrgGroupBatchId = @rOrgGroupBatchId))
						AND (R.OrgGroupBatchId = @rOrgGroupBatchId)
						AND (R.ReceiptDate <= @rUptoDate)  
						-- IsInContext
						AND BM.IsInContext = 1
						GROUP BY FeeSetupId,R.SourceId
				) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
				LEFT JOIN sFee.tCollectionGroupMaster CGM ON FS.CollectionGroupId=CGM.Id
				INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId
			WHERE
			  SA.OrgGroupBatchId = @rOrgGroupBatchId
			  AND (SA.StatusId = @rStudentStatus OR @rStudentStatus=0)
			  AND ((FS.StartDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
			  -- IsInContext
			  AND BM.IsInContext = 1
			GROUP BY SA.DepartmentId,SA.DepartmentName,CGM.Id,CGM.Title,CGM.OrderIndex,DM.OrderIndex
			ORDER BY DM.OrderIndex,DepartmentId,CGM.Id
	 END
	END
ELSE IF(@rFilterType = 'ReceiptBookwise')
	BEGIN
	IF(@rFeeType = 'FeeHeadwise')
	BEGIN
		-- For Timeout issue
		CREATE TABLE #tmp
		(
		Amount decimal (12,2),
		FeeName nvarchar(100),
		FeeHeadId int,
		AcademicId bigint,
		Id int,
		StartDate date,
		ReceiptBookId int 
		)

		INSERT INTO #tmp
		SELECT 
			ISNULL(FS1.Amount,0)AS Amount,
			FM.Title AS FeeName,
			FM.FeeHeadId,
			SA1.Id As AcademicId,
			FS1.Id,
			FS1.StartDate,
			FS1.ReceiptBookId
 		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 sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
		WHERE 
			BM.OrgGroupBatchId = @rOrgGroupBatchId
			AND (FS1.IsOptional=0)
			-- IsInContext
			AND BM.IsInContext = 1
		UNION ALL
		SELECT 
			ISNULL(FS1.Amount,0)AS Amount,
			FM.Title AS FeeName,
			FM.FeeHeadId,
			SA1.AcademicId As AcademicId,
			FS1.Id,
			FS1.StartDate,
			FS1.ReceiptBookId
		FROM sFee.tFeeSetup FS1
		INNER JOIN sFee.tFeeOptional FO ON FO.FeeSetupId=FS1.Id
		INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
		INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=FO.SourceId 
		AND SA1.BatchId = FS1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId AND SA1.ClassId = FS1.ClassId
		INNER JOIN sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
		WHERE
				SA1.OrgGroupBatchId = @rOrgGroupBatchId
				AND (FS1.IsOptional=1)
				-- IsInContext
				AND BM.IsInContext = 1



	 SELECT
			FS.ReceiptBookId,
		    ISNULL(RBM.Title,'') AS ReceiptBookTitle,
			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,
			FHM.Id AS FeeHeadId,
			FHM.Title AS FeeHeadName,
			FHM.OrderIndex
		FROM
			sStudent.tAcademic SA
			INNER JOIN [sStudent].[tStudentMaster] SM ON SA.StudentId = SM.Id 
			INNER JOIN [sSetup].[tBatchMaster] BM ON SA.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster O ON SA.OrgId = O.Id
			--INNER JOIN 
			--(
				--SELECT 
				--	ISNULL(FS1.Amount,0)AS Amount,
				--	FM.Title AS FeeName,
				--	FM.FeeHeadId,
				--	SA1.Id As AcademicId,
				--	FS1.Id,
				--	FS1.StartDate,
				--	FS1.ReceiptBookId
 			--	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 sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
				--WHERE 
				--	BM.OrgGroupBatchId = @rOrgGroupBatchId
				--	AND (FS1.IsOptional=0)
				--	-- IsInContext
				--	AND BM.IsInContext = 1
				--UNION ALL
				--SELECT 
				--	ISNULL(FS1.Amount,0)AS Amount,
				--	FM.Title AS FeeName,
				--	FM.FeeHeadId,
				--	SA1.AcademicId As AcademicId,
				--	FS1.Id,
				--	FS1.StartDate,
				--	FS1.ReceiptBookId
				--FROM sFee.tFeeSetup FS1
				--INNER JOIN sFee.tFeeOptional FO ON FO.FeeSetupId=FS1.Id
				--INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
				--INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=FO.SourceId 
				--AND SA1.BatchId = FS1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId AND SA1.ClassId = FS1.ClassId
				--INNER JOIN sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
				--WHERE
				--		SA1.OrgGroupBatchId = @rOrgGroupBatchId
				--		AND (FS1.IsOptional=1)
				--		-- IsInContext
				--		AND BM.IsInContext = 1
				--) 
				INNER JOIN #tmp FS ON FS.AcademicId=SA.Id
				LEFT JOIN sFee.tFeeAllocation FA ON FA.FeeSetupId=FS.Id AND FA.SourceId=SA.Id
				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.tAcademic SA1 ON SA1.Id=R.SourceId
						INNER JOIN sSetup.tBatchMaster BM ON BM.Id=SA1.BatchId			
					WHERE		
						(R.SourceTypeId = 2001)
						AND (R.IsObsolete = 0) 
						AND ((BM.OrgGroupBatchId = @rOrgGroupBatchId))
						AND (R.OrgGroupBatchId = @rOrgGroupBatchId)
						AND (R.ReceiptDate <= @rUptoDate)  
						-- IsInContext
						AND BM.IsInContext = 1
						GROUP BY FeeSetupId,R.SourceId
				) R ON R.FeeSetupId = FS.Id AND SA.Id = R.SourceId
				INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id = FS.FeeHeadId	
				INNER JOIN sFee.tReceiptBookMaster RBM ON FS.ReceiptBookId=RBM.Id
			WHERE
			  BM.OrgGroupBatchId = @rOrgGroupBatchId
			  AND (SM.StatusId = @rStudentStatus OR @rStudentStatus=0)
			  AND ((FS.StartDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
			  -- IsInContext
			  AND BM.IsInContext = 1
			GROUP BY FS.ReceiptBookId,RBM.Title,FHM.Id,FHM.Title,FHM.OrderIndex,RBM.OrderIndex
			ORDER BY RBM.OrderIndex,ReceiptBookId,FHM.Id

		DROP TABLE #tmp
	 END
	ELSE IF(@rFeeType = 'FeeMasterwise')
	BEGIN

		IF OBJECT_ID('tempdb..#tmpReceiptFeeMasterwise') IS NOT NULL DROP TABLE #tmpReceiptFeeMasterwise
		CREATE TABLE #tmpReceiptFeeMasterwise
		(
		FeeId int,
		Amount decimal (12,2),
		FeeName nvarchar(100),
		FeeHeadId int,
		AcademicId bigint,
		Id int,
		StartDate date,
		ReceiptBookId int,
		OrderIndex int
		)

		INSERT INTO  #tmpReceiptFeeMasterwise
		SELECT 
					FS1.FeeId,
					ISNULL(FS1.Amount,0)AS Amount,
					FM.Title AS FeeName,
					FM.FeeHeadId,
					SA1.Id As AcademicId,
					FS1.Id,
					FS1.StartDate,
					FS1.ReceiptBookId,
					FM.OrderIndex
 				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 sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
				WHERE 
					BM.OrgGroupBatchId = @rOrgGroupBatchId
					AND (FS1.IsOptional=0)
					-- IsInContext
					AND BM.IsInContext = 1
				UNION ALL
				SELECT 
					FS1.FeeId,
					ISNULL(FS1.Amount,0)AS Amount,
					FM.Title AS FeeName,
					FM.FeeHeadId,
					SA1.AcademicId As AcademicId,
					FS1.Id,
					FS1.StartDate,
					FS1.ReceiptBookId,
					FM.OrderIndex
				FROM sFee.tFeeSetup FS1
				INNER JOIN sFee.tFeeOptional FO ON FO.FeeSetupId=FS1.Id
				INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
				INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=FO.SourceId 
				AND SA1.BatchId = FS1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId AND SA1.ClassId = FS1.ClassId
				INNER JOIN sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
				WHERE
						SA1.OrgGroupBatchId = @rOrgGroupBatchId
						AND (FS1.IsOptional=1)
						-- IsInContext
						AND BM.IsInContext = 1

		SELECT
			FS.ReceiptBookId,
		    ISNULL(RBM.Title,'') AS ReceiptBookTitle,
			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,
			FS.FeeId,
			FS.FeeName,
			FS.OrderIndex
		FROM
			sStudent.vStudentAcademic SA
				INNER JOIN sSetup.tOrganizationMaster O ON SA.OrgId = O.Id
				INNER JOIN #tmpReceiptFeeMasterwise 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.tAcademic SA1 ON SA1.Id=R.SourceId
						INNER JOIN sSetup.tBatchMaster BM ON BM.Id=SA1.BatchId			
					WHERE		
						(R.SourceTypeId = 2001)
						AND (R.IsObsolete = 0) 
						AND ((BM.OrgGroupBatchId = @rOrgGroupBatchId))
						AND (R.OrgGroupBatchId = @rOrgGroupBatchId)
						AND (R.ReceiptDate <= @rUptoDate) 
						-- IsInContext
						AND BM.IsInContext = 1 
						GROUP BY FeeSetupId,R.SourceId
				) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
				INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id = FS.FeeHeadId	
				INNER JOIN sFee.tReceiptBookMaster RBM ON FS.ReceiptBookId=RBM.Id
				INNER JOIN sSetup.tBatchMaster BM ON SA.BatchId = BM.Id
			WHERE
			  SA.OrgGroupBatchId = @rOrgGroupBatchId
			  AND (SA.StatusId = @rStudentStatus OR @rStudentStatus=0)
			  AND ((FS.StartDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
			  -- IsInContext
			  AND BM.IsInContext = 1
			GROUP BY FS.ReceiptBookId,RBM.Title,FS.FeeId,FS.FeeName,FS.OrderIndex,RBM.OrderIndex
			ORDER BY RBM.OrderIndex,ReceiptBookId,FS.FeeId
	END
	ELSE IF(@rFeeType = 'CollectionGroupwise')
	BEGIN

		IF OBJECT_ID('tempdb..#tmpReceiptCollectionGroupwise') IS NOT NULL DROP TABLE #tmpReceiptCollectionGroupwise
		CREATE TABLE #tmpReceiptCollectionGroupwise
		(
		FeeId int,
		Amount decimal (12,2),
		FeeName nvarchar(100),
		FeeHeadId int,
		AcademicId bigint,
		Id int,
		StartDate date,
		CollectionGroupId int,
		ReceiptBookId int
		)

		INSERT INTO #tmpReceiptCollectionGroupwise
		SELECT 
					FS1.FeeId,
					ISNULL(FS1.Amount,0)AS Amount,
					FM.Title AS FeeName,
					FM.FeeHeadId,
					SA1.Id As AcademicId,
					FS1.Id,
					FS1.StartDate,
					FS1.CollectionGroupId,
					FS1.ReceiptBookId
 				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 sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
				WHERE 
					BM.OrgGroupBatchId = @rOrgGroupBatchId
					AND (FS1.IsOptional=0)
					-- IsInContext
					AND BM.IsInContext = 1
				UNION ALL
				SELECT 
					FS1.FeeId,
					ISNULL(FS1.Amount,0)AS Amount,
					FM.Title AS FeeName,
					FM.FeeHeadId,
					SA1.AcademicId As AcademicId,
					FS1.Id,
					FS1.StartDate,
					FS1.CollectionGroupId,
					FS1.ReceiptBookId
				FROM sFee.tFeeSetup FS1
				INNER JOIN sFee.tFeeOptional FO ON FO.FeeSetupId=FS1.Id
				INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
				INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=FO.SourceId 
				AND SA1.BatchId = FS1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId AND SA1.ClassId = FS1.ClassId
				INNER JOIN sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
				WHERE
						SA1.OrgGroupBatchId = @rOrgGroupBatchId
						AND (FS1.IsOptional=1)
						-- IsInContext
						AND BM.IsInContext = 1

		SELECT
			FS.ReceiptBookId,
		    ISNULL(RBM.Title,'') AS ReceiptBookTitle,
			SUM(ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00))AS PendingAmount,
			ISNULL(CGM.Id,0) AS CollectionGroupId,
			ISNULL(CGM.Title,'') AS CollectionGroupName,
			ISNULL(CGM.OrderIndex,0) AS OrderIndex
		FROM
			sStudent.vStudentAcademic SA
				INNER JOIN sSetup.tOrganizationMaster O ON SA.OrgId = O.Id
				INNER JOIN #tmpReceiptCollectionGroupwise 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.tAcademic SA1 ON SA1.Id=R.SourceId
						INNER JOIN sSetup.tBatchMaster BM ON BM.Id=SA1.BatchId			
					WHERE		
						(R.SourceTypeId = 2001)
						AND (R.IsObsolete = 0) 
						AND ((BM.OrgGroupBatchId = @rOrgGroupBatchId))
						AND (R.OrgGroupBatchId = @rOrgGroupBatchId)
						AND (R.ReceiptDate <= @rUptoDate)  
						-- IsInContext
						AND BM.IsInContext = 1
						GROUP BY FeeSetupId,R.SourceId
				) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
				LEFT JOIN sFee.tCollectionGroupMaster CGM ON FS.CollectionGroupId=CGM.Id
				INNER JOIN sFee.tReceiptBookMaster RBM ON FS.ReceiptBookId=RBM.Id
				INNER JOIN sSetup.tBatchMaster BM ON SA.BatchId = BM.Id
			WHERE
			  SA.OrgGroupBatchId = @rOrgGroupBatchId
			  AND (SA.StatusId = @rStudentStatus OR @rStudentStatus=0)
			  AND ((FS.StartDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
			  -- IsInContext
			  AND BM.IsInContext = 1
			GROUP BY FS.ReceiptBookId,RBM.Title,CGM.Id,CGM.Title,CGM.OrderIndex,RBM.OrderIndex
			--ORDER BY ReceiptBookId,CGM.Id
			ORDER BY RBM.OrderIndex,CGM.OrderIndex
	END
	END 
  END
ELSE IF(@rType = 2)
		BEGIN

			IF OBJECT_ID('tempdb..#tmptbl') IS NOT NULL DROP TABLE #tmptbl
			CREATE TABLE #tmptbl
			(
				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,
				FeeOrderIndex int
			)
			INSERT INTO #tmptbl 
			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,
							FS1.CollectionGroupId,
							FM.OrderIndex AS FeeOrderIndex			 
						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 sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
						WHERE 
							BM.OrgGroupBatchId = @rOrgGroupBatchId
							AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
							AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
							AND (FS1.IsOptional=0)
							-- IsInContext
							AND BM.IsInContext = 1
						UNION ALL
				
						SELECT 
							FS1.FeeId,
							FS1.Id,
							ISNULL(FS1.IsOptional,0)AS IsOptional,
							ISNULL(FS1.IsVariable,0)AS IsVariable,
							ISNULL(FS1.Amount,0)AS Amount,
							ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
							ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
							FS1.BatchId,
							ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
							SA1.AcademicId,
							FM.Title AS FeeName,
							FM.FeeHeadId,
							FS1.CollectionGroupId,
							FM.OrderIndex AS FeeOrderIndex			 			 
						FROM sFee.tFeeSetup FS1
						INNER JOIN sFee.tFeeOptional FO ON FO.FeeSetupId=FS1.Id
						INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
						INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=FO.SourceId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
						INNER JOIN sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
						WHERE
							SA1.OrgGroupBatchId = @rOrgGroupBatchId
							AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
							AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
							AND (FS1.IsOptional=1)
							-- IsInContext
							AND BM.IsInContext = 1
	
				SELECT 
					SA.OrgId,
					SA.OrganizationName as OrgName,
					SA.ClassId,
					SA.ClassName,
					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 #tmptbl  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.tAcademic SA1 ON SA1.Id=R.SourceId
							INNER JOIN sSetup.tBatchMaster BM ON BM.Id=SA1.BatchId			
							 
						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
							-- IsInContext
							AND BM.IsInContext = 1
							GROUP BY FeeSetupId,R.SourceId
					) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
					 INNER JOIN sSetup.tOrganizationMaster O ON	
					 SA.OrgId = O.Id
					 INNER JOIN sFee.tReceiptBookMaster RBM 
						ON FS.ReceiptBookId=RBM.Id
					 LEFT JOIN sFee.tCollectionGroupMaster CGM
						ON FS.CollectionGroupId=CGM.Id	
					 LEFT JOIN sStudent.tStudentCommunication SC 
						ON SC.StudentId = SA.StudentId
					 LEFT JOIN sStudent.tStudentOther SO 
						ON SO.StudentId = SA.StudentId
					 INNER JOIN sFee.tFeeHeadMaster FHM
						ON FHM.Id = FS.FeeHeadId
					INNER JOIN sSetup.tBatchMaster BM ON SA.BatchId = BM.Id	
				  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))  
				WHERE	
				 SA.OrgGroupBatchId = @rOrgGroupBatchId
                 AND (SA.StatusId = @rStudentStatus OR @rStudentStatus=0)
                 AND ((FS.StartDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
				 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)			
				 -- IsInContext
				 AND BM.IsInContext = 1
				GROUP BY 
						SA.ClassId,SA.ClassName,SA.OrgId,SA.OrganizationName
				Order By
						SA.ClassId
		END
END
GO
PRINT N'Altering Procedure [sHrm].[pEmployeeReplacementGet]...';


GO
ALTER PROCEDURE [sHrm].[pEmployeeReplacementGet]
	 
        @rEmployeeId bigint
	

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	Declare @lTeacherSubjectId bigint = 0 , @lTeacherDivisionId bigint = 0
	IF OBJECT_ID('tempdb..#tmpTable') IS NOT NULL DROP TABLE #tmpTable
	CREATE Table #tmpTable 
	(
		Id bigint IDENTITY,
		Title nvarchar(50)
	)

	IF EXISTS(select top 1 1 from sTimetable.tAssignTeacher where EmployeeId = @rEmployeeId)
	BEGIN
		Insert INTO #tmpTable Values
		(
			'Assign Teacher'
		)
	END


	set @lTeacherSubjectId = (select top 1 1 from sAcademic.tTeacherSubject where EmployeeId = @rEmployeeId)
	SET @lTeacherDivisionId = (select top 1 1 from sAcademic.tTeacherSubjectDivision where EmployeeId = @rEmployeeId)
	IF ((@lTeacherSubjectId = 1) OR (@lTeacherDivisionId = 1))
	BEGIN
		Insert INTO #tmpTable Values
		(
			'Teacher Subject Division'
		)
	END

	IF EXISTS (select top 1 1 from sTimetable.tTimeTable where EmployeeId = @rEmployeeId)
	BEGIN
		Insert INTO #tmpTable Values
		(
			'Time Table'
		)
	END
		
	declare @lUserId bigint= (select top 1 Id from sSecurity.tUser where SourceId = @rEmployeeId AND SourceTypeId = 95)
	declare @lUserOrganizationId int ,@lUserAccessId int
	SET @lUserOrganizationId = (SELECT Top 1 1 FROM sSecurity.tUserOrganization WHERE UserId=@lUserId)
	SET @lUserAccessId= (SELECT top 1 1 FROM sSecurity.tUserAccess WHERE UserId=@lUserId)
	IF ((@lUserOrganizationId = 1) OR (@lUserAccessId = 1))
	BEGIN
		Insert INTO #tmpTable Values
		(
			'User Access'
		)
	END

	IF EXISTS (select top 1 1 from sSetup.tDivisionMaster where InchargeEmployeeId = @rEmployeeId)
	BEGIN
		Insert INTO #tmpTable Values
		(
			'Class Teacher'
		)
	END	

	--IF EXISTS (select top 1 1 from sAcademic.tLessonPlan where EmployeeId = @rEmployeeId)
	--BEGIN
	--	Insert INTO #tmpTable Values
	--	(
	--		'Lesson Plan'
	--	)
	--END

	select * from #tmpTable --order by Title

	Drop Table #tmpTable
END
GO
PRINT N'Altering Procedure [sHrm].[pImportEmployees_Update_Dynamicly]...';


GO
ALTER proc [sHrm].[pImportEmployees_Update_Dynamicly] 
@rOrgId int,
@rCreatedUserId bigint,
@rCode varchar(200) = '',
@rShortName varchar(200) = '',
@rFirstName varchar(200) = '',
@rMiddleName varchar(200) = '',
@rLastName varchar(200) = '',
@rGender varchar(50) = '',
@rEmpType varchar(100) = '',
@rEmpGroup varchar(100) = '',
@rEmpGrade varchar(100) = '',
@rDepartment varchar(150) = '',
@rDesignation varchar(150) = '',
@rQualification varchar(150) = '',
@rDOB datetime = '',
@rDateOfJoining datetime = '',
@rReligion varchar(150) = '',
@rCompayPhoneNo varchar(15) = '',
@rExtensionNo varchar(15)='',
@rCompayMailId varchar(100)='',
@rPersonalEmailid varchar(100)='',
@rMobileNo varchar(50)='',
@rPresentStreetOne varchar(200)='',
@rPresentStreetTwo varchar(200)='',
@rPresentStreetThree varchar(200)='',
@rPresentCity varchar(100)='',
@rPresentZipCode varchar(15)='',
@rPresentState varchar(100)='',
@rPresentCountry varchar(100)='',
@rPresentContactNo varchar(50)='',
@rCastCategory varchar(50)='',
@rFamilyCast varchar(100)='',
@rAccountNumber varchar(100)='',
@rBankName varchar(100)='',
@rBranch varchar(100)=0,
@rEPFNumber varchar(100)=0,
@rPanNumber  varchar(100)='',
@rAdhaarNumber varchar(100)='',
@rValidate varchar(250)='' ,
@rOrgGroupId int,
@rIdentificationMark1  varchar(200)='',
@rUIDNumber varchar(50)='',
@rDateOfLeaving datetime = '',
@rReason varchar(200)='',
@rBloodGroup varchar(50)='',
@rNumber Bigint,
@rProbationUptoDate date = '',
@rAhdocUptoDate date = '',
@rPermanentDate date = '',
@rDateOfResignation date = '',
@rWhatsAppContactNo nvarchar(20) = ''

as
begin	

	IF(@rDateOfLeaving='') 
	SET @rDateOfLeaving = NULL
	IF(@rDOB='') 
	SET @rDOB = NULL
	IF(@rDateOfJoining='') 
	SET @rDateOfJoining = NULL
	IF(@rProbationUptoDate='')
	SET @rProbationUptoDate = NULL
	IF(@rAhdocUptoDate='')
	SET @rAhdocUptoDate = NULL
	IF(@rPermanentDate='')
	SET @rPermanentDate = NULL
	IF(@rDateOfResignation='')
	SET @rDateOfResignation = NULL
	
	declare @EmpId bigint = 0
	select @EmpId = Id from sHrm.tEmployeeMaster where Code = @rCode and OrgID = @rOrgId AND ISNULL(IsOtherUser,0) = 0
	select @EmpId = isnull(@EmpId,0)
	
	declare @genderid int,@emptypeid int,@cmpanyid int,@departmenttid int,@designationid int, 
	 @employeegradeid int,@empgroupid int,@religionId int,@castcatagoryId int,@bloodgroupid int
	 
	
	select @rGender = case when upper(@rGender) = 'M' then 'Male'
	when  upper(@rGender) = 'MALE' then 'Male'
	when upper(@rGender) ='FEMALE' then 'Female'
	when upper(@rGender) = 'F' then 'Female' when upper(@rGender) = 'N' then 'Not Known' else 'Not Known' end
	 
	select @genderid = isnull(Id,0) from sCommon.tGenderMaster where Title = @rGender
	
	select @emptypeid = isnull(Id,0) from sHrm.tEmployeeTypeMaster where Title = @rEmpType and OrgId = @rOrgId
 
	select @empgroupid = isnull(Id,0) from sHrm.tEmployeeGroupMaster where Title = @rEmpGroup
	
	select @employeegradeid = isnull(Id,0) from sHrm.tEmployeeGradeMaster where Title = @rEmpGrade and OrgId = @rOrgId
	 
	 select @departmenttid = isnull(Id,0) from sSetup.tDepartmentMaster where Title = @rDepartment and OrgId = @rOrgId
	 
	  select @bloodgroupid = isnull(Id,0) from sCommon.tBloodGroupMaster where Title = @rBloodGroup 
	
	if (isnull(@rDesignation,'') <> '')
	select @designationid =  isnull(Id,0) from sHrm.tEmployeeDesignationMaster where Title = @rDesignation and OrgId = @rOrgId
	else
	select @designationid = 0
	
	 if (isnull(@rReligion,'') <> '')
			select @religionId =  isnull(Id,0) from sCommon.tReligionMaster where Title = @rReligion and OrgGroupId = @rOrgGroupId
	else
			select @religionId = 0
	
	 if (isnull(@rCastCategory,'') <> '')
	 select @castcatagoryId =  isnull(Id,0) from sCommon.tCastCategoryMaster where Title = @rCastCategory and OrgGroupId = @rOrgGroupId
	 else
	select @castcatagoryId = 0
			
	select @genderid = isnull(@genderid,0),@emptypeid = isnull(@emptypeid,0),@empgroupid = isnull(@empgroupid,0),
	@employeegradeid = isnull(@employeegradeid,0),@departmenttid = isnull(@departmenttid,0),@designationid = isnull(@designationid,0),
	@religionId = isnull(@religionId,0),@castcatagoryId = isnull(@castcatagoryId,0) 
	
	declare @lNextNumber bigint,@Title varchar(100)=''
	
	if @rEmpGroup = ''
	begin
		
		if exists (select 1 from sHrm.tEmployeeGroupMaster where  Title = @Title)
		begin
			select @empgroupid = Id from sHrm.tEmployeeGroupMaster where Title = @Title
		end
		
	end
	
	 
	
	if @rEmpType = ''
	begin		
		
		if exists (select 1 from sHrm.tEmployeeTypeMaster where OrgId = @rOrgId and Title = @Title)
		begin
			select @emptypeid = Id from sHrm.tEmployeeTypeMaster where OrgId = @rOrgId and Title = @Title
		end
	end
	
	 
	if @rEmpGrade = ''
	begin
		 
		if exists(select 1 from sHrm.tEmployeeGradeMaster where OrgId = @rOrgId and Title = @Title)
		begin
			select @employeegradeid = Id from sHrm.tEmployeeGradeMaster where OrgId = @rOrgId and Title = @Title
		end
	end
	
	
	if @rDepartment = ''
	begin		
		 
		if exists (select * from sSetup.tDepartmentMaster  where Title = @Title and OrgId = @rOrgId)
		begin
			select @departmenttid = Id from sSetup.tDepartmentMaster  where Title = @Title and OrgId = @rOrgId
		end
	end
		

	if @rDesignation = ''
	begin
		select @Title = Title from sHrm.tEmployeeDesignationMaster where Id = 1
		if exists (select * from sHrm.tEmployeeDesignationMaster where Title = @Title and OrgId = @rOrgId)
		begin
			select @designationid = Id from sHrm.tEmployeeDesignationMaster where Title = @Title and OrgId = @rOrgId			
		end
	end
	 
	 if @rCastCategory = ''
	begin
		
		if exists (select 1 from sCommon.tCastCategoryMaster where  Title = @Title and OrgGroupId=@rOrgGroupId)
		begin
			select @castcatagoryId = Id from sCommon.tCastCategoryMaster where Title = @Title and OrgGroupId=@rOrgGroupId
		end
		
	end
	
	 
	 if @rReligion = ''
	begin
		
		if exists (select 1 from sCommon.tReligionMaster where  Title = @Title and OrgGroupId=@rOrgGroupId)
		begin
			select @religionId = Id from sCommon.tReligionMaster where Title = @Title and OrgGroupId=@rOrgGroupId
		end
		
	end
	
	if @rShortName <> ''
	select @rShortName = [sSetup].[fPortalXMLTagsReplaceReverse](@rShortName)
	if @rFirstName <> ''
	select @rFirstName = [sSetup].[fPortalXMLTagsReplaceReverse](@rFirstName)
	if @rMiddleName <> ''
	select @rMiddleName = [sSetup].[fPortalXMLTagsReplaceReverse](@rMiddleName)
	if @rLastName <> ''
	select @rLastName = [sSetup].[fPortalXMLTagsReplaceReverse](@rLastName)
	if @rCompayPhoneNo <> ''
	select @rCompayPhoneNo = [sSetup].[fPortalXMLTagsReplaceReverse](@rCompayPhoneNo)
	if @rExtensionNo <> ''
	select @rExtensionNo = [sSetup].[fPortalXMLTagsReplaceReverse](@rExtensionNo)
	if @rCompayMailId <> ''
	select @rCompayMailId = [sSetup].[fPortalXMLTagsReplaceReverse](@rCompayMailId)
	if @rPersonalEmailid <> ''
	select @rPersonalEmailid = [sSetup].[fPortalXMLTagsReplaceReverse](@rPersonalEmailid)
	if @rMobileNo <> ''
	select @rMobileNo = [sSetup].[fPortalXMLTagsReplaceReverse](@rMobileNo)
	if @rPresentStreetOne <> ''
	select @rPresentStreetOne = [sSetup].[fPortalXMLTagsReplaceReverse](@rPresentStreetOne)
	if @rPresentStreetTwo <> ''
	select @rPresentStreetTwo = [sSetup].[fPortalXMLTagsReplaceReverse](@rPresentStreetTwo)
	if @rPresentStreetThree <> ''
	select @rPresentStreetThree = [sSetup].[fPortalXMLTagsReplaceReverse](@rPresentStreetThree)
	if @rPresentCity <> ''
	select @rPresentCity = [sSetup].[fPortalXMLTagsReplaceReverse](@rPresentCity)
	if @rPresentZipCode <> ''
	select @rPresentZipCode = [sSetup].[fPortalXMLTagsReplaceReverse](@rPresentZipCode)
	if @rPresentState <> ''
	select @rPresentState = [sSetup].[fPortalXMLTagsReplaceReverse](@rPresentState)
	if @rPresentCountry <> ''
	select @rPresentCountry = [sSetup].[fPortalXMLTagsReplaceReverse](@rPresentCountry)
	if @rPresentContactNo <> ''
	select @rPresentContactNo = [sSetup].[fPortalXMLTagsReplaceReverse](@rPresentContactNo)
	if @rFamilyCast <> ''
	select @rFamilyCast = [sSetup].[fPortalXMLTagsReplaceReverse](@rFamilyCast)
	if @rAccountNumber <> ''
	select @rAccountNumber = [sSetup].[fPortalXMLTagsReplaceReverse](@rAccountNumber)
	if @rBankName <> ''
	select @rBankName = [sSetup].[fPortalXMLTagsReplaceReverse](@rBankName)
	if @rBranch <> ''
	select @rBranch = [sSetup].[fPortalXMLTagsReplaceReverse](@rBranch)
	if @rEPFNumber<> ''
	select @rEPFNumber = [sSetup].[fPortalXMLTagsReplaceReverse](@rEPFNumber)
	if @rPanNumber <> ''
	select @rPanNumber = [sSetup].[fPortalXMLTagsReplaceReverse](@rPanNumber)
	if @rAdhaarNumber <> ''
	select @rAdhaarNumber = [sSetup].[fPortalXMLTagsReplaceReverse](@rAdhaarNumber)
	if @rWhatsAppContactNo <> ''
	select @rWhatsAppContactNo = [sSetup].[fPortalXMLTagsReplaceReverse](@rWhatsAppContactNo)
	  
	 
	begin

		UPDATE sHrm.tEmployeeMaster 
		SET 
		ShortName = case when isnull(@rShortName,'') <> '' then @rShortName else ShortName end
		,FirstName = case when isnull(@rFirstName,'') <> '' then @rFirstName else FirstName end
		,MiddleName   = case when isnull(@rMiddleName,'') <> '' then @rMiddleName else MiddleName end
		,LastName     = case when isnull(@rLastName,'') <> '' then @rLastName else LastName end
		--,StatusId     = case when isnull(@statusid,0) <> 0 then @statusid else StatusId end
		,IsObsolete   = case when isnull(IsObsolete,'') <> '' then IsObsolete else IsObsolete end
		,UpdatedUserId = @rCreatedUserId
		,UpdatedDateTime = sCommon.fGetDate()
		,Number = @rNumber
		WHERE Id = @EmpId and OrgId = @rOrgId AND ISNULL(IsOtherUser,0) = 0

		  
		UPDATE sHrm.tEmployeeJobDetail
		SET 
			EmployeeDesignationId = case when isnull(@designationid,0) <> 0 then @designationid else EmployeeDesignationId end,	 
			OrganizationDepartmentId = case when isnull(@departmenttid,0) <> 0 then @departmenttid else OrganizationDepartmentId end,
			DateOfJoining =	case when isnull(@rDateOfJoining,'') <> '' then @rDateOfJoining else DateOfJoining end,
			UpdatedUserId = @rCreatedUserId,
			UpdatedDateTime = sCommon.fGetDate(),
			EmployeeTypeId = case when isnull(@emptypeid,0) <> 0 then @emptypeid else EmployeeTypeId end,
			EmployeeGroupId = case when isnull(@empgroupid,0) <> 0 then @empgroupid else EmployeeGroupid end,
			EmployeeGradeId = case when isnull(@employeegradeid,0) <> 0 then @employeegradeid else EmployeeGradeId  end ,
			DateOfleaving =  case when isnull(@rDateOfLeaving,'') <> '' then @rDateOfLeaving else DateOfleaving end,
			ReasonOfleaving = case when isnull(@rReason,'') <> '' then @rReason else ReasonOfleaving end,
			ProbationUptoDate = @rProbationUptoDate,
			AhdocUptoDate = @rAhdocUptoDate,
			PermanentDate = @rPermanentDate,
			DateOfResignation = @rDateOfResignation
			  
	  WHERE EmployeeId = @EmpId and OrgId = @rOrgId
	  
		Update sHrm.tEmployeePersonalDetail 
		set  
		GenderId = case when isnull(@genderid,0) <> 0 then @genderid else GenderId  end,
		ReligionId =  case when isnull(@religionId,0) <> 0 then @religionId else ReligionId  end,
		Qualification =  case when isnull(@rQualification,'') <> '' then @rQualification else Qualification  end,
		BloodGroupId =  case when isnull(@bloodgroupid,0) <> 0 then @bloodgroupid else BloodGroupId  end,
		DateOfBirth =  case when isnull(@rDOB,0) <> 0 then @rDOB else DateOfBirth  end,
		IdentificationMark1 =  case when isnull(@rIdentificationMark1,0) <> 0 then @rIdentificationMark1 else IdentificationMark1  end,
		UIDNumber =  case when isnull(@rUIDNumber,0) <> 0 then @rUIDNumber else UIDNumber  end,
		UpdatedUserId = @rCreatedUserId,
		UpdatedDateTime = sCommon.fGetDate(),
		FamilyCast =case when isnull(@rFamilyCast,'') <> '' then @rFamilyCast else FamilyCast  end,
		AdhaarNumber =case when isnull(@rAdhaarNumber,'') <> '' then @rAdhaarNumber else AdhaarNumber  end,
		CastCategoryId =case when isnull(@castcatagoryId,0) <> 0 then @castcatagoryId else FamilyCast  end
		where EmployeeId = @EmpId and OrgId = @rOrgId
		
  		UPDATE [sHrm].[tEmployeeCommunications]
		SET 
	      
		   [PresentStreetOne] = case when isnull(@rPresentStreetOne,'') <> '' then @rPresentStreetOne else [PresentStreetOne] end 
		  ,[PresentStreetTwo] =  case when isnull(@rPresentStreetTwo,'') <> '' then @rPresentStreetTwo else [PresentStreetTwo] end 
		  ,[PresentStreetThree] = case when isnull(@rPresentStreetThree,'') <> '' then @rPresentStreetThree else [PresentStreetThree] end 
		  ,[PresentCountry] = case when isnull(@rPresentCountry,'') <> '' then @rPresentCountry else [PresentCountry] end 
		  ,[PresentState] =  case when isnull(@rPresentState,'') <> '' then @rPresentState else [PresentState] end 
		  ,[PresentCity] =  case when isnull(@rPresentCity,'') <> '' then @rPresentCity else [PresentCity] end 
		  ,[EmergencyContactNo] = case when isnull(@rMobileNo,'') <> '' then @rMobileNo else [EmergencyContactNo] end 
		  ,[PhoneNoCompany] = case when isnull(@rCompayPhoneNo,'') <> '' then @rCompayPhoneNo else [PhoneNoCompany] end 
		  ,[ExtensionNo] = case when isnull(@rExtensionNo,'') <> '' then @rExtensionNo else [ExtensionNo] end  
		  ,[CompanyEmail] =  case when isnull(@rCompayMailId,'') <> '' then @rCompayMailId else [CompanyEmail]  end   
		  ,[PersonalEmail] =  case when isnull(@rPersonalEmailid,'') <> '' then @rPersonalEmailid else [PersonalEmail]  end   
		  ,[MobileNumber] =  case when isnull(@rMobileNo,'') <> '' then @rMobileNo else [MobileNumber]  end      
		  ,[UpdatedUserId] = @rCreatedUserId
		  ,[UpdatedDateTime] =  sCommon.fGetDate() 
		  ,[WhatsAppContactNo] =  case when isnull(@rWhatsAppContactNo,'') <> '' then @rWhatsAppContactNo else [WhatsAppContactNo]  end    
		WHERE EmployeeId = @EmpId
			
	end	
end
GO
PRINT N'Altering Procedure [sLibrary].[pBookListGet]...';


GO
ALTER PROCEDURE [sLibrary].[pBookListGet]
	
	 @rName nvarchar(500),
	 @rResourceTypeId int,
	 @rStatusId smallint,
	 @rLibraryId int
	 	
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
--DECLARE @lpaging
BEGIN 


	  --BEGIN
			--SET @rCode = sCommon.fSearchStringGet(@rCode)
			SET @rName = sCommon.fSearchStringGet(@rName)
					
	  --END
	 declare @quer varchar(max)=''
	declare @lOrgId int,@lName nvarchar(200),@lResourceTypeId int,@lStatusId smallint,@lLibraryId int

	
	select 
	@lName = isnull(@rName,''),
	@lResourceTypeId = isnull(@rResourceTypeId,0),@lStatusId = isnull(@rStatusId,0),@lLibraryId = isnull(@rLibraryId,0)

	 
	SELECT @quer='SELECT BM.Code,
	BM.Title,
	ISNULL(BM.Publisher,'''')AS Publisher,
	ISNULL(BM.Supplier,'''')AS Supplier,
	ISNULL(BM.Author,'''')AS Author,
	ISNULL(BM.BookSubject,'''') AS BookSubject,
	ISNULL(BM.BookLanguage,'''') AS BookLanguage,
	ISNULL(BM.Location,'''') AS Location,
	ISNULL(BM.Edition,'''')AS Edition,
	ISNULL(BM.ISBNNumber,'''') AS ISBNNumber,
	ISNULL(BM.Price,0) AS Price,
	ISNULL(BM.Currency,'''') AS Currency,
	ISNULL(BM.BookTag,'''')AS BookTag,
	ISNULL(BM.BookCustomTag,'''') AS BookCustomTag,
	ISNULL(BM.BookDepartment,'''') AS BookDepartment,
	ISNULL(BM.ClassNumber,'''') AS ClassNumber,
	ISNULL(BM.BookVolume,1) AS BookVolume,
	ISNULL(BM.NoOfCopies,1) AS NoOfCopies,
	SM.Title AS StatusName,
	BM.Id,
	ISNULL(AGM.Id,0)AS BookAgeGroupId,
	ISNULL(RTM.Id,0) AS ResourceTypeId,
	BM.CreatedUserId,
	BM.CreatedDateTime,
	ISNULL(BM.UpdatedUserId,0) AS UpdatedUserId,
	ISNULL(BM.UpdatedDateTime,'''') AS UpdatedDateTime,
	BM.LibraryId,
	SM.Id AS StatusId,
	BM.ClassificationNo,
	BM.AccessionNo,
	ISNUll(BM.NoOfPages,0) AS NoOfPages,
	 ISNULL(BM.PurchaseDate,''0001/01/01'') AS PurchaseDate,
    ISNUll(BM.BookRemark,'''') AS BookRemark,
    ISNULL(BM.BillNumber,'''') AS BillNumber,
    BM.YearOfPublication,
    ISNULL(BM.BookEntryDate,''0001/01/01'') AS BookEntryDate,
    ISNULL(BM.BookGroup1Id,0) AS BookGroup1Id,
    ISNULL(BM.BookGroup2Id,0) AS BookGroup2Id,
	ISNULL(BL.ReaderSourceId,0)AS ReaderSourceId
 
	FROM 
         sLibrary.tBookMaster BM
         LEFT JOIN sLibrary.tBookAgeGroupMaster AGM ON BM.BookAgeGroupId=AGM.Id
         INNER JOIN sLibrary.tResourceTypeMaster RTM ON BM.ResourceTypeId=RTM.Id
         INNER JOIN sLibrary.tBookLog BL ON BL.ResourceSourceId = BM.Id AND IsCurrentStatus=1
         INNER JOIN sCommon.tStatusMaster SM ON SM.Id=BL.StatusId 
         
         WHERE  
	 ((BM.Publisher like ''' + @lName + ''') OR (''' + @lName + ''' = '''')
	 OR (BM.Title like ''' + @lName + ''') OR (''' + @lName + ''' = '''')
	 OR (BM.Code like ''' + @lName + ''') OR (''' + @lName + ''' = '''')
	 OR (BM.Author like ''' + @lName + ''') OR (''' + @lName + ''' = '''') 
	 OR (BM.BookSubject like ''' + @lName + ''') OR (''' + @lName + ''' = ''''))
	AND ((BM.ResourceTypeId = ' + convert(varchar,@lResourceTypeId) + ') OR (' + convert(varchar,@lResourceTypeId) + ' = 0))
	AND ((BL.StatusId = ' + convert(varchar,@lStatusId) + ') OR (' + convert(varchar,@lStatusId) + '=0))
	AND BM.LibraryId = ' + convert(varchar,@lLibraryId)
	
	print(@quer);
	exec (@quer)

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


GO
 
ALTER PROCEDURE [sProcurement].[pRptStockAdjustmentRegisterGet]
  @rBuilder1 nvarchar(max)='',
	@rBuilder2 nvarchar(max)='',
	@rReportId int,
	@rStoreLocationId int,
	@rMainGroupId int,
	@rSubGroupId int,
	@rStockItemCategoryId int,
	@rItemCode nvarchar(100),
	@rItemName nvarchar(100),
	@rOrgGroupId int,
	@rFromDate date = '',
	@rToDate date = '',
	@rDetail bit =0
	
WITH EXECUTE AS CALLER
AS
BEGIN
   SELECT  
				SIM.Code AS ItemCode,
				SIM.Title AS ItemName,		
				SI.Number AS Billno, 	
				SI.CreatedDateTime AS IssuedDate,
				ID.SystemQuantity,
				ID.PhysicalQuantity,
				 
				SB.ExpiryDate,
				--SB.Price AS Amount,
				SB.Number As BatchNumber,
				SI.Id,
				@rDetail AS Detail,
				@rBuilder1 As Builder1,
				@rBuilder2 AS Builder2,
				SIM.IsObsolete
				
		FROM  sProcurement.tStockAdjustment SI		
		INNER JOIN sProcurement.tStockAdjustmentDetail ID ON SI.Id = ID.StockAdjustmentId 
		INNER JOIN sIp.tStockItemMaster SIM ON ID.StockItemId  = SIM.Id 
	    LEFT JOIN sProcurement.tStockBatch SB ON SB.Id = ID.StockBatchId
	    
	    INNER JOIN sIp.tItemSubGroupMaster ISGM ON ISGM.Id=SIM.ItemSubGroupId
		INNER JOIN sIp.tItemMainGroupMaster IMGM ON IMGM.Id=ISGM.ItemMainGroupId
		LEFT JOIN sIp.tStockItemCategoryMaster SICM ON SICM.Id=SIM.StockItemCategoryId	
		 
		  WHERE	     
	     --SIM.IsObsolete=0
		  (SB.StoreLocationId= @rStoreLocationId)
		AND (IMGM.Id = @rMainGroupId OR @rMainGroupId=0)
		AND (ISGM.Id = @rSubGroupId OR @rSubGroupId=0)
		AND (SICM.Id = @rStockItemCategoryId OR @rStockItemCategoryId = 0)
		AND (SIM.Code = @rItemCode OR @rItemCode = '')
		AND (SIM.Title = @rItemName OR @rItemName = '')
		AND ((CAST(SI.CreatedDateTime AS DATE) >= CAST(@rFromDate AS DATE)) OR (ISNULL(@rFromDate,'') = '')) 
		AND ((CAST(SI.CreatedDateTime AS DATE) <= CAST(@rToDate AS DATE)) OR (ISNULL(@rToDate,'') = '') )
		AND (SB.OrgGroupId = @rOrgGroupId)
		 
    Order  by SIM.Title	
END
GO
PRINT N'Altering Procedure [sSecurity].[pMenuGet]...';


GO
 
 -- exec [sSecurity].[pMenuGet] 9911000000003
ALTER PROCEDURE [sSecurity].[pMenuGet]
	@rUserId [bigint],
	@rMenuId int = 0,
	@rResourceTypeId int= 0 
 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN


IF EXISTS(SELECT 1 FROM sSecurity.tPermissionUser WHERE UserId = @rUserId)
BEGIN

	SELECT
		MenuID,
		ModuleId,
		ParentMenuID,
		MenuTitle,	 
		ScreenTitle,		 
		PageURL,
		ScreenId,
		Permission,
		OrderNumber,	 
		TaskId,		
	    PageURL  AS PagePath,
	    IconPath
	   
	FROM
   (SELECT Menu.Id AS MenuID, 
		ISNULL(Menu.ParentMenuID, 0) AS ParentMenuID, 
		Menu.Title AS MenuTitle,		 
		ISNULL(Screen.Title, '') AS ScreenTitle,			 
		ISNULL(Screen.Page, '') AS PageURL,
		ISNULL(Screen.ScreenGroupId,0) AS ScreenGroupId,
		ISNULL(Menu.ScreenId, 0) AS ScreenId,
		ISNULL(PermissionValue, 0) AS Permission,
		ISNULL(OrderNumber, 0) AS OrderNumber,
		ISNULL(Screen.TaskId,0) AS TaskId,
		ISNULL(Screen.IconPath,'') As IconPath, 
		ISNULL(T.ResourceTypeId,0) AS ResourceTypeId,
		ISNULL(T.ModuleId,0) AS ModuleId
	  
		 
	FROM sSecurity.tMenu Menu	
	LEFT OUTER JOIN sSecurity.tScreen Screen
		ON Menu.ScreenId = Screen.Id		
	LEFT OUTER JOIN ( 
					SELECT 
						TaskId, 
						SUM(Permission & 2) PermissionValue			   
					FROM 
						sSecurity.tPermissionUser P
						INNER JOIN sSecurity.tTask T ON T.Id = P.TaskId
						--INNER JOIN sSecuirty.tOrganizationTask OT ON OT.TaskId = T.Id AND OT.OrgGroupId = P.OrgGroupId 
						INNER JOIN sSecurity.tModulePermission MP ON MP.ModuleId = T.ModuleId AND MP.OrgGroupId = P.OrgGroupId
					WHERE
						T.IsObsolete = 0 AND P.UserId = @rUserId
					GROUP BY 
						TaskId) TBL2
					ON 
						Screen.TaskId = TBL2.TaskId 
						 LEFT OUTER JOIN sSecurity.tTask  T ON T.Id =  Screen.TaskId AND ResourceTypeId = @rResourceTypeId
						
					WHERE 
					(Menu.IsObsolete = 0)  --For ScreenGroupId Master Page
					AND	ISNULL(Screen.IsObsolete, 0) = 0) 
				    MenuTable  
					--INNER JOIN sSecurity.tTask  T ON T.Id =  MenuTable.TaskId 
	WHERE 
		MenuTable.ScreenId = 0 OR MenuTable.Permission >= 2	
		AND 
		((MenuTable.ResourceTypeId = @rResourceTypeId) OR (@rResourceTypeId = 0))
		AND ((MenuTable.MenuID = @rMenuID)OR(@rMenuID = 0))
	 		
	ORDER BY 
		ParentMenuID
END
ELSE 
BEGIN
	SELECT
		MenuID,
		ModuleId,
		ParentMenuID,
		MenuTitle,	 
		ScreenTitle,		 
		PageURL,
		ScreenId,
		Permission,
		OrderNumber,	 
		TaskId,		
	  PageURL  AS PagePath,
	  IconPath
	   
	FROM
   (SELECT Menu.Id AS MenuID, 
		ISNULL(Menu.ParentMenuID, 0) AS ParentMenuID, 
		Menu.Title AS MenuTitle,		 
		ISNULL(Screen.Title, '') AS ScreenTitle,			 
		ISNULL(Screen.Page, '') AS PageURL,
		ISNULL(Screen.ScreenGroupId,0) AS ScreenGroupId,
		ISNULL(Menu.ScreenId, 0) AS ScreenId,
		ISNULL(PermissionValue, 0) AS Permission,
		ISNULL(OrderNumber, 0) AS OrderNumber,
		ISNULL(Screen.TaskId,0) AS TaskId,
		ISNULL(Screen.IconPath,'') As IconPath, 
		ISNULL(T.ResourceTypeId,0) AS ResourceTypeId,
		ISNULL(T.ModuleId,0) AS ModuleId
	  
		 
	FROM sSecurity.tMenu Menu	
	LEFT OUTER JOIN sSecurity.tScreen Screen
		ON Menu.ScreenId = Screen.Id		
	LEFT OUTER JOIN ( 
					SELECT 
						TaskId, 
						SUM(Permission & 2) PermissionValue			   
					FROM 
						sSecurity.tPermission P
						INNER JOIN sSecurity.tTask T ON T.Id = P.TaskId
						--INNER JOIN sSecuirty.tOrganizationTask OT ON OT.TaskId = T.Id AND OT.OrgGroupId = P.OrgGroupId 
						INNER JOIN sSecurity.tModulePermission MP ON MP.ModuleId = T.ModuleId AND MP.OrgGroupId = P.OrgGroupId
						INNER JOIN
						(
						SELECT RoleId FROM sSecurity.tUserRole UR WHERE  UserId = @rUserId AND IsObsolete = 0
						) B ON B.RoleId = P.RoleId
					WHERE
						T.IsObsolete = 0
					GROUP BY 
						TaskId) TBL2
					ON 
						Screen.TaskId = TBL2.TaskId 
						 LEFT OUTER JOIN sSecurity.tTask  T ON T.Id =  Screen.TaskId AND ResourceTypeId = @rResourceTypeId
						
					WHERE 
					(Menu.IsObsolete = 0)  --For ScreenGroupId Master Page
					AND	ISNULL(Screen.IsObsolete, 0) = 0) 
				    MenuTable  
					--INNER JOIN sSecurity.tTask  T ON T.Id =  MenuTable.TaskId 
	WHERE 
		MenuTable.ScreenId = 0 OR MenuTable.Permission >= 2	
		AND 
		((MenuTable.ResourceTypeId = @rResourceTypeId) OR (@rResourceTypeId = 0))
		AND ((MenuTable.MenuID = @rMenuID)OR(@rMenuID = 0))
	 		
	ORDER BY 
		ParentMenuID

   --SELECT DISTINCT Menu.Id AS MenuID, 
	--		ISNULL(Menu.ParentMenuID, 0) AS ParentMenuID, 
	--		Menu.Title AS MenuTitle, 
	--		Menu.TitleResourceKeyId AS MenuResourceKey, 
	--		Screen.Title AS ScreenTitle,
	--		Screen.TitleResourceKeyId AS ScreenResourceKey,
	--		Screen.Page AS PageURL
	--FROM sSecurity.tMenu Menu
	--LEFT OUTER JOIN sSecurity.tScreen Screen
	--	ON Menu.ScreenId = Screen.Id
	--LEFT OUTER JOIN sSecurity.tPermission Permission
	--	ON Screen.TaskId = Permission.TaskId
	--WHERE	Menu.IsObsolete = 0 AND
	--		Screen.IsObsolete = 0 AND
	--		Permission.RoleId IN (SELECT RoleId FROM sSecurity.tUserRole WHERE UserId = @rUserId) AND
	--		(Permission.Permission & 2) = 2
	--ORDER BY ParentMenuID
END
	
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) = ''
	 
	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
		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='')
END

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


GO

ALTER PROCEDURE [sStudent].[pRptStudentLCVerificationGet]
	 
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 @rOrgId int,
	 @rBatchId int,
	 @rDepartmentId int=0,
	 @rClassId int=0,
	 @rDivisionId int=0,
     @rStrCode nvarchar(20)='',
	 @rStatusId int=0,
	 @rClassStatusId int=0,
	 @rExamId int = 0
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
	
	
	IF(@rExamId!=0)
	 BEGIN
	 SELECT 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			L.Id,		
			vSA.Code,
			L.AcademicId,
			vSA.FirstName,vSA.MiddleName,vSA.LastName,
			[sStudent].[fStudentNameGet](vSA.FirstName , vSA.MiddleName, vSA.LastName,OM.StudentNameFormatId ) AS Name,
			ISNULL(SF.FatherName,'') As FatherName,
			ISNULL(SF.MotherName,'') As MotherName,
			ISNULL(so.BirthPlace,'') AS BirthPlace,
			ISNULL(SO.BirthTaluka,'') AS BirthTaluka,
			ISNULL(SO.BirthDistrict,'') AS BirthDistrict,
			SO.DateOfBirth,
			ISNULL(SO.BirthDateInWord,'') AS BirthDateInWord,
			L.LCNumber,
			L.LeftDate,
			L.LCReason,
			L.LCProgress,
			L.LCConduct,
			L.LCRemark,
			L.LCDate,
			L.LCBookNumber,
			ISNULL(SO.FamilySubCast,'') AS SubCaste,
			ISNULL(SO.FamilyCast,'') AS Caste,
		    vSA.StatusId,		
		 	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,			
			vSA.ClassName AS ClassName,
			vSA.DivisionName AS DivisionName,	
			isnull(MainCastCategoryId,0) AS CastCategoryId,
			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,
			SO.UIDNumber,
			L.LCCopy
			,vSA.BatchName AS BatchName,
		    ISNULL(SA.AdmissionNumber,'') AS AdmissionNumber,
			SO.UIDNumber,	
			ISNULL(OM.ReportOrgGroupTitle,'') AS ReportOrgGroupTitle,
			OM.ReportOrgTitle,	
    		ISNULL(CMS.ClassNameInWord,'') AS ClassNameInWord,
			vSA.ClassId AS ClassId,
		    OM.PrincipalSignature,
			ISNULL(R.Percentage,0) As Percentage,
			ISNULL(SCM.Title,'') AS LeftStandard
	FROM 
			sCertificate.tLeaving L
			INNER JOIN sStudent.vStudentAcademic vSA ON vSA.AcademicId=L.AcademicId	
			LEFT JOIN sStudent.tStudentAdmission SA ON SA.StudentId=vSA.StudentId			
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=vSA.OrgId 
			LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId=vSA.StudentId 		
			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.tCastCategoryMaster CSM ON CSM.Id=SO.CastCategoryId
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id=vSA.BatchId 
			LEFT JOIN sStudent.tStudentAdditional SD ON SD.StudentId=vSA.StudentId
			LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId=vSA.StudentId
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId=vSA.ClassId
            LEFT JOIN sAssessment.tResult R ON R.ExamId = EM.Id AND vSA.AcademicId = R.AcademicId
			LEFT JOIN sSetup.tClassMaster SCM ON SCM.Id = SA.LeftStandardId
	Where		  ((vSA.OrgId=@rOrgId) OR (@rOrgId=0))
	       AND ((vSA.BatchId=@rBatchId) OR (@rBatchId=0))
	       AND ((vSA.DepartmentId=@rDepartmentId) OR(@rDepartmentId=0))
	       AND ((vSA.ClassId=@rClassId) OR(@rClassId=0))	  
	       AND ((vSA.DivisionId=@rDivisionId) OR (@rDivisionId=0))	
		   AND (ISNULL(vSA.Code,0) IN( SELECT cast(item as nvarchar(20)) FROM  sCommon.fnsplit(@rStrCode,',')) OR @rStrCode='')
           AND ((vSA.StatusId=@rStatusId)OR(@rStatusId=0))
		   AND ((vSA.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0)) 
		   AND ((EM.Id = @rExamId) OR (@rExamId=0))	
    END		
	
	ELSE 
	  BEGIN
	     SELECT
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			L.Id,		
			vSA.Code,
			L.AcademicId,
			vSA.FirstName,vSA.MiddleName,vSA.LastName,
			[sStudent].[fStudentNameGet](vSA.FirstName , vSA.MiddleName, vSA.LastName,OM.StudentNameFormatId ) AS Name,
			ISNULL(SF.FatherName,'') As FatherName,
			ISNULL(SF.MotherName,'') As MotherName,
			ISNULL(so.BirthPlace,'') AS BirthPlace,
			ISNULL(SO.BirthTaluka,'') AS BirthTaluka,
			ISNULL(SO.BirthDistrict,'') AS BirthDistrict,
			SO.DateOfBirth,
			ISNULL(SO.BirthDateInWord,'') AS BirthDateInWord,
			L.LCNumber,
			L.LeftDate,
			L.LCReason,
			L.LCProgress,
			L.LCConduct,
			L.LCRemark,
			L.LCDate,
			L.LCBookNumber,
			ISNULL(SO.FamilySubCast,'') AS SubCaste,
			ISNULL(SO.FamilyCast,'') AS Caste,
		    vSA.StatusId,		
		 	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,			
			vSA.ClassName AS ClassName,
			vSA.DivisionName AS DivisionName,	
			isnull(MainCastCategoryId,0) AS CastCategoryId,
			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,
			SO.UIDNumber,
			L.LCCopy
			,vSA.BatchName AS BatchName,
		    ISNULL(SA.AdmissionNumber,'') AS AdmissionNumber,
			SO.UIDNumber,	
			ISNULL(OM.ReportOrgGroupTitle,'') AS ReportOrgGroupTitle,
			OM.ReportOrgTitle,	
    		ISNULL(CMS.ClassNameInWord,'') AS ClassNameInWord,
			vSA.ClassId AS ClassId,
		    OM.PrincipalSignature,
			0 As Percentage,
			ISNULL(SCM.Title,'') AS LeftStandard
	FROM 
			sCertificate.tLeaving L
			INNER JOIN sStudent.vStudentAcademic vSA ON vSA.AcademicId=L.AcademicId	
			LEFT JOIN sStudent.tStudentAdmission SA ON SA.StudentId=vSA.StudentId			
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=vSA.OrgId 
			LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId=vSA.StudentId 
			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.tCastCategoryMaster CSM ON CSM.Id=SO.CastCategoryId
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id=vSA.BatchId 
			LEFT JOIN sStudent.tStudentAdditional SD ON SD.StudentId=vSA.StudentId
			LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId=vSA.StudentId
			LEFT JOIN sSetup.tClassMaster SCM ON SCM.Id = SA.LeftStandardId
	Where		
	            ((vSA.OrgId=@rOrgId) OR (@rOrgId=0))
	       AND ((vSA.BatchId=@rBatchId) OR (@rBatchId=0))
	       AND ((vSA.DepartmentId=@rDepartmentId) OR(@rDepartmentId=0))
	       AND ((vSA.ClassId=@rClassId) OR(@rClassId=0))	  
	       AND ((vSA.DivisionId=@rDivisionId) OR (@rDivisionId=0))	
		   AND (ISNULL(vSA.Code,0) IN( SELECT cast(item as nvarchar(20)) FROM  sCommon.fnsplit(@rStrCode,',')) OR @rStrCode='')
           AND ((vSA.StatusId=@rStatusId)OR(@rStatusId=0))
		   AND ((vSA.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0)) 
	  END 			
END
GO
PRINT N'Altering Procedure [sStudent].[pRptStudentPastLCVerificationGet]...';


GO

ALTER PROCEDURE [sStudent].[pRptStudentPastLCVerificationGet]
	 
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='',
	 @rOrgId int,
	 @rBatchId int,
	 @rDepartmentId int=0,
	 @rClassId int=0,
	 @rDivisionId int=0,
     @rStrCode nvarchar(20)='',
	 @rStatusId int=0,
	 @rClassStatusId int=0,
	 @rPreviousSchool nvarchar(200)=''

	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
 BEGIN

	     SELECT
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,	
			OM.OrgLogo,
			OM.Title AS OrgTitle,
			OM.StreetOne+' '+OM.StreetTwo+' '+OM.StreetThree AS OrgAddress,
			OM.SmallAddress1,
			OM.SmallAddress2,
			OM.RegistrationDetail,
            vSA.ClassId AS ClassId,
			CM.OrderIndex AS ClassOrderIndex,
			vSA.ClassId AS DivisionId,	
			DM.OrderIndex AS DivisionOrderIndex,		
			vSA.ClassName AS ClassName,
			vSA.DivisionName AS DivisionName,
			ISNULL(OM.ReportOrgGroupTitle,'') AS ReportOrgGroupTitle,
			OM.ReportOrgTitle,		
			vSA.AcademicId,
			vSA.Code,
			ISNULL(SA.AdmissionNumber,'') As OldGRNo,
            vSA.FirstName,vSA.MiddleName,vSA.LastName,
			[sStudent].[fStudentNameGet](vSA.FirstName , vSA.MiddleName, vSA.LastName,OM.StudentNameFormatId ) AS Name,
			ISNULL(SO.DateOfBirth,'') AS DateOfBirth,
			ISNULL(SO.BirthDateInWord,'') AS BirthDateInWord,
			ISNULL(SA.PreviousStandard,'') AS PreviousStandard,
			ISNULL(SA.LeftDate,'') AS LeftDate,
			ISNULL(SO.BirthPlace,'') AS BirthPlace,
			ISNULL(SA.PreviousLCNumber,'') AS PreviousLCNumber,
			ISNULL(SA.PreviousLCDate,'') AS PreviousLCDate,
			ISNULL(SA.PreviousLCResult,'') AS PreviousLCResult,
			ISNULL(SO.FamilySubCast,'') AS SubCaste,
			ISNULL(SO.FamilyCast,'') AS Caste,
			isnull(MainCastCategoryId,0) AS CastCategoryId,
			ISNULL(SA.AdmissionNumber,'') AS AdmissionNumber
			 
			--SA.PreviousSchool

	FROM 
		    sStudent.vStudentAcademic vSA 	
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=vSA.OrgId 
			LEFT JOIN sStudent.tStudentAdmission SA ON SA.StudentId=vSA.StudentId
			INNER JOIN sSetup.tClassMaster CM ON CM.Id=SA.AdmissionStandardId
			INNER JOIN sSetup.tDivisionMaster DM ON vSA.DivisionId = DM.Id  
		    LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId=vSA.StudentId 
			LEFT JOIN sCommon.tCastCategoryMaster CSM ON CSM.Id=SO.CastCategoryId		
	Where		
	           ((vSA.OrgId=@rOrgId) OR (@rOrgId=0))
	       AND ((vSA.BatchId=@rBatchId) OR (@rBatchId=0))
	       AND ((vSA.DepartmentId=@rDepartmentId) OR(@rDepartmentId=0))
	       AND ((vSA.ClassId=@rClassId) OR(@rClassId=0))	  
	       AND ((vSA.DivisionId=@rDivisionId) OR (@rDivisionId=0))	
		   AND (ISNULL(vSA.Code,0) IN( SELECT cast(item as nvarchar(20)) FROM  sCommon.fnsplit(@rStrCode,',')) OR @rStrCode='')
           AND ((vSA.StatusId=@rStatusId)OR(@rStatusId=0))
		   AND ((vSA.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0)) 
		   --AND (ISNULL(SA.PreviousSchool,'') IN( SELECT item FROM  sCommon.fnsplit(@rPreviousSchool,','))OR @rPreviousSchool='')	
		    AND ((SA.PreviousSchool =  @rPreviousSchool) OR (@rPreviousSchool='')) 
END
GO
PRINT N'Altering Procedure [sStudent].[pStudentMasterGet]...';


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

BEGIN 

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


GO
ALTER PROCEDURE [sStudent].[pStudentOtherAdd]
	 
		   @rStudentId bigint,
           @rUIDNumber nvarchar(50),
           @rDateOfBirth date,
           @rGenderId tinyint,
           @rReligionId int,     
           @rBloodGroupId tinyint,
           @rBirthPlace nvarchar(150),
           @rBirthTaluka nvarchar(150),
           @rBirthDistrict nvarchar(150),
           @rBirthdateInWord nvarchar(150),     
           @rFamilyCast nvarchar(100),
           @rFamilySubCast nvarchar(100),
           @rCastCategoryId int,
           @rTransportModeId int,
           --@rPickupBusRouteDestinationId int,
           --@rDropBusRouteDestinationId int,
           --@rBusRouteId int,
           --@rPickuppointId int,
           @rHouseId int,
           @rMotherTongueId int,
           @rNationalityId int,
           @rHobby nvarchar(50),           
           --@rFeeCategoryId int,      
           --@rResideModeId int,
           @rCreatedUserId bigint,
           @rUpdatedUserId bigint,
           @rReferenceRemark nvarchar(100) = '',
           @rAdhaarNumber nvarchar(20) = '',
           @rMotherTongue nvarchar(100) = '',
           @rQuotaId int =0,
           @rbirthState nvarchar(100)='',
           @rBirthCountry nvarchar(100)='',
		   @rBatchId int = 0,
		   @rTribeId int = 0
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	IF NOT EXISTS(SELECT 1 FROM sStudent.tStudentOther WHERE StudentId = @rStudentId)
	 BEGIN
	 --commented by dhruvik for 27466 mantis
	  --  IF(ISNULL(@rUIDNumber,'')!='')		
		 -- BEGIN
			--IF EXISTS(SELECT 1 FROM sStudent.tStudentOther SO INNER JOIN sStudent.tStudentMaster SM ON SM.Id = SO.StudentId WHERE SM.OrgId = LEFT(@rBatchId,4) AND UIDNumber=@rUIDNumber AND StudentId NOT IN (SELECT ReferenceSourceId FROM sStudent.tStudentMaster))
			--BEGIN
			--	SELECT -101 AS Result
			--	RETURN
			--END 
		 -- END
		 
		 IF(ISNULL(@rAdhaarNumber,'')!='')		 		 
		  BEGIN

			IF EXISTS(SELECT 1 FROM sStudent.tStudentOther SO INNER JOIN sStudent.tStudentMaster SM ON SM.Id = SO.StudentId WHERE SM.OrgId = LEFT(@rBatchId,4) AND  AdhaarNumber=@rAdhaarNumber AND StudentId NOT IN (SELECT ReferenceSourceId FROM sStudent.tStudentMaster))
				BEGIN
					SELECT -102 AS Result
					RETURN
				END 
		  END
		  
	 END
	 
	 ELSE
	 
	  
	  
	  BEGIN
	  --commented by dhruvik for 27466 mantis
		 --IF(ISNULL(@rUIDNumber,'')!='')		
		 -- BEGIN
			--IF EXISTS(SELECT 1 FROM sStudent.tStudentOther SO INNER JOIN sStudent.tStudentMaster SM ON SM.Id = SO.StudentId WHERE SM.OrgId = LEFT(@rBatchId,4) AND UIDNumber=@rUIDNumber AND StudentId <> @rStudentId AND StudentId NOT IN (SELECT ReferenceSourceId FROM sStudent.tStudentMaster))
			--BEGIN
			--	SELECT -101 AS Result
			--	RETURN
			--END 
		 -- END
		  
		 IF(ISNULL(@rAdhaarNumber,'')!='')	
		  BEGIN
			IF EXISTS(SELECT 1 FROM sStudent.tStudentOther SO INNER JOIN sStudent.tStudentMaster SM ON SM.Id = SO.StudentId WHERE SM.OrgId = LEFT(@rBatchId,4) AND AdhaarNumber=@rAdhaarNumber AND StudentId <> @rStudentId AND StudentId NOT IN (SELECT ReferenceSourceId FROM sStudent.tStudentMaster))
				BEGIN
					SELECT -102 AS Result
					RETURN
				END 
		  END
		  
	 END
	  
	 BEGIN TRANSACTION
	 
IF NOT EXISTS(SELECT * FROM sStudent.tStudentOther WHERE StudentId = @rStudentId)
BEGIN

	--DECLARE @lNextNumber BIGINT     
	--EXECUTE sCommon.pTableRowIdGet 0, 'sStudent.tStudentCommunication', 0, 1, 1,@outNextNumber = @lNextNumber output

	INSERT INTO sStudent.tStudentOther
		(
		   StudentId,
           UIDNumber,
           DateOfBirth,
           GenderId,
           ReligionId,
           BloodGroupId,
           BirthPlace,
           BirthTaluka,
           BirthDistrict,
           BirthdateInWord,
      
           FamilyCast,
           FamilySubCast,
           CastCategoryId,
           TransportModeId,
           --PickupBusRouteDestinationId,
           --DropBusRouteDestinationId,
           --BusRouteId,
           --PickuppointId,
           HouseId,
           MotherTongueId,
           NationalityId,
           Hobby,
           ReferenceRemark,
           --FeeCategoryId,
         
           --ResideModeId,
           CreatedUserId,
           CreatedDateTime,
           AdhaarNumber,
           MotherTongue,
           QuotaId,
           BirthState,
           BirthCountry,
		   TribeId
		)
	VALUES
		(
		   @rStudentId,
           @rUIDNumber,
           @rDateOfBirth,
           @rGenderId,
           @rReligionId,
           @rBloodGroupId,
           @rBirthPlace,
           @rBirthTaluka,
           @rBirthDistrict,
           @rBirthdateInWord,
       
           @rFamilyCast,
           @rFamilySubCast,
           @rCastCategoryId,
           @rTransportModeId,
           --@rPickupBusRouteDestinationId,
           --@rDropBusRouteDestinationId,
           --@rBusRouteId,
           --@rPickuppointId,
           @rHouseId,
           @rMotherTongueId,
           @rNationalityId,
           @rHobby,
           @rReferenceRemark,
           --@rFeeCategoryId,
        
           --@rResideModeId,
           @rCreatedUserId,
           sCommon.fGetDate(),
           @rAdhaarNumber,
           @rMotherTongue,
           @rQuotaId,
           @rbirthState,
           @rBirthCountry,
           @rTribeId
		)
		SELECT 1 AS Result             
END	
 
ELSE

BEGIN
	 --SET @lNextNumber = @rStudentId
	    UPDATE  sStudent.tStudentOther
	    SET
			  StudentId = @rStudentId, 
			  UIDNumber = @rUIDNumber, 
			  DateOfBirth = @rDateOfBirth, 
			  GenderId = @rGenderId,
			  ReligionId = @rReligionId, 
		 
			  BloodGroupId = @rBloodGroupId, 
			  BirthPlace = @rBirthPlace, 
			  BirthTaluka = @rBirthTaluka,
			  BirthDistrict = @rBirthDistrict,
			  BirthdateInWord = @rBirthdateInWord, 
		 
			  FamilyCast = @rFamilyCast, 
			  FamilySubCast = @rFamilySubCast, 
			  CastCategoryId = @rCastCategoryId, 
			  TransportModeId = @rTransportModeId,
			  --PickupBusRouteDestinationId=@rPickupBusRouteDestinationId,
			  --DropBusRouteDestinationId=@rDropBusRouteDestinationId,
			  --BusRouteId = @rBusRouteId,
			  --PickuppointId = @rPickuppointId, 
			  HouseId = @rHouseId, 
			  MotherTongueId=@rMotherTongueId,
			  NationalityId=@rNationalityId,
			  Hobby=@rHobby,
			  ReferenceRemark=@rReferenceRemark,
			  --FeeCategoryId = @rFeeCategoryId,
	 
			  --ResideModeId = @rResideModeId,
			  UpdatedUserId = @rUpdatedUserId, 
			  UpdatedDateTime =sCommon.fGetDate(),
			  AdhaarNumber=@rAdhaarNumber,
			  MotherTongue=@rMotherTongue,
			  QuotaId = @rQuotaId,
			  BirthState =@rbirthState,
			  BirthCountry =@rBirthCountry,
			  TribeId = @rTribeId
	      WHERE StudentId = @rStudentId 
	       
END  
		SELECT 11 AS Result
	
--DECLARE @lAcademicId bigint = 0
--SELECT @lAcademicId = ISNULL(Id,0) from sStudent.tAcademic Where StudentId = @rStudentId AND BatchId = @rBatchId

--If (@lAcademicId != 0)
--BEGIN
--	IF NOT EXISTS(Select 1 from sStudent.tAcademicStudentOther Where AcademicId = @lAcademicId)
--	BEGIN
--		INSERT INTO sStudent.tAcademicStudentOther
--		(
--		   AcademicId,
--           UIDNumber,
--           DateOfBirth,
--           GenderId,
--           ReligionId,
--           BloodGroupId,
--           BirthPlace,
--           BirthTaluka,
--           BirthDistrict,
--           BirthdateInWord,
--           FamilyCast,
--           FamilySubCast,
--           CastCategoryId,
--           TransportModeId,
--           HouseId,
--           MotherTongueId,
--           NationalityId,
--           Hobby,
--           ReferenceRemark,
--           CreatedUserId,
--           CreatedDateTime,
--           AdhaarNumber,
--           MotherTongue,
--           QuotaId,
--           BirthState,
--           BirthCountry
--		)
--		VALUES
--		(
--		   @lAcademicId,
--           @rUIDNumber,
--           @rDateOfBirth,
--           @rGenderId,
--           @rReligionId,
--           @rBloodGroupId,
--           @rBirthPlace,
--           @rBirthTaluka,
--           @rBirthDistrict,
--           @rBirthdateInWord,
--           @rFamilyCast,
--           @rFamilySubCast,
--           @rCastCategoryId,
--           @rTransportModeId,
--           @rHouseId,
--           @rMotherTongueId,
--           @rNationalityId,
--           @rHobby,
--           @rReferenceRemark,
--           @rCreatedUserId,
--           sCommon.fGetDate(),
--           @rAdhaarNumber,
--           @rMotherTongue,
--           @rQuotaId,
--           @rbirthState,
--           @rBirthCountry
--		)
--	END
--	ELSE
--	BEGIN
--		UPDATE  sStudent.tAcademicStudentOther
--	    SET
--		   AcademicId = @lAcademicId, 
--		   UIDNumber = @rUIDNumber, 
--		   DateOfBirth = @rDateOfBirth, 
--		   GenderId = @rGenderId,
--		   ReligionId = @rReligionId, 
--		   BloodGroupId = @rBloodGroupId, 
--		   BirthPlace = @rBirthPlace, 
--		   BirthTaluka = @rBirthTaluka,
--		   BirthDistrict = @rBirthDistrict,
--		   BirthdateInWord = @rBirthdateInWord, 
--		   FamilyCast = @rFamilyCast, 
--		   FamilySubCast = @rFamilySubCast, 
--		   CastCategoryId = @rCastCategoryId, 
--		   TransportModeId = @rTransportModeId,
--		   HouseId = @rHouseId, 
--		   MotherTongueId=@rMotherTongueId,
--		   NationalityId=@rNationalityId,
--		   Hobby=@rHobby,
--		   ReferenceRemark=@rReferenceRemark,
--		   UpdatedUserId = @rUpdatedUserId, 
--		   UpdatedDateTime =sCommon.fGetDate(),
--		   AdhaarNumber=@rAdhaarNumber,
--		   MotherTongue=@rMotherTongue,
--		   QuotaId = @rQuotaId,
--		   BirthState =@rbirthState,
--		   BirthCountry =@rBirthCountry
--	     WHERE AcademicId = @lAcademicId 
--	END
	
--END
	
		COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Altering Procedure [sStudent].[pValidateImportStudent]...';


GO
ALTER PROCEDURE [sStudent].[pValidateImportStudent]

	@rOrgGroupId int,
    @rOrgId int,
	@rXmldoc [nvarchar](max),
	@rOperation int=0,   --1 For Insert,2 For Update
	@rBatchId int=0
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
DECLARE @lSUIdActivate nvarchar(50)=''
DECLARE @lIsSurnameAndFatherNameMandatory nvarchar(50)=''
DECLARE @lIsActivateUniqueId bit = 0
DECLARE @lOrgGroupId int = 0
DECLARE @lIsStudentUIDNumberUnique nvarchar(50)=''		--add
SELECT @lOrgGroupId=OrgGroupId FROM sSetup.tOrganizationMaster WHERE Id = @rOrgId
SELECT @lSUIdActivate = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 167 AND SourceTypeId = 2010 AND SourceId = @lOrgGroupId
SELECT @lIsSurnameAndFatherNameMandatory =  ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 415 AND SourceTypeId = 2010 AND SourceId = @lOrgGroupId	
SELECT @lIsStudentUIDNumberUnique = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 534 AND SourceTypeId = 2010 AND SourceId = @lOrgGroupId		--add
IF (@lSUIdActivate = '') OR (@lSUIdActivate = 'False')
	SET @lIsActivateUniqueId = 0
ELSE
	SET @lIsActivateUniqueId = 1	

DECLARE @lCount INT
DECLARE @lInterrorCode INT,
		@intDoc INT,
        @lCode nvarchar(50),
        @lClass nvarchar(100),
        @lDivision nvarchar(100),        
        @lRegistrationNumber nvarchar(20),  
        @lAdmissionDate nvarchar(15),        
        @lDOB nvarchar(15),             
        @1ReturnCode int = 1,
        @1ExistStudentCode nvarchar(max) = '',
        @1NotExistStudentCode nvarchar(max) = '',
        @1ExistStudentRegistrationNumber nvarchar(max) = '',
        @1ValidAdmissionDate nvarchar(max) = '',
        @1ValidDOB nvarchar(max) = '',
        @1DuplicateStudentCode nvarchar(max) = '',
        @1DuplicateStudentRegistrationNumber nvarchar(max) = '',
        @lSUId nvarchar(50),
        @1ExistStudentSUId nvarchar(max) = '',
        @1DuplicateStudentSUId nvarchar(max) = '',
        @lLeftDate nvarchar(15),
        @lLCDate nvarchar(15),
        @1ValidLeftDate nvarchar(max) = '',
        @1ValidLCDate nvarchar(max) = '',
        @lStatusId smallint,
        
        @lAdhaarNumber nvarchar(50),  
        @1DuplicateAdhaarNumber nvarchar(max) = '',
        
        @lUIDNumber nvarchar(50),  
        @1DuplicateUIDNumber nvarchar(max) = '',
        
        @1StudentId BIGINT = 0
       
EXECUTE @lInterrorCode = sp_xml_preparedocument @intDoc OUTPUT, @rXmlDoc
 
CREATE TABLE #tTable1 
 (
		Id bigint identity,
        Code nvarchar(50),
        RegistrationNumber nvarchar(20),
        FirstName nvarchar(100),
		MiddleName nvarchar(100),
        LastName nvarchar(100),
		Class nvarchar(100),
		Division nvarchar(100),
		AdmissionStandard nvarchar(100),
		AdmissionDate nvarchar(15),
        DOB nvarchar(15),
        Gender nvarchar(10),
        --AdmissionCategory nvarchar(100),
		Religion nvarchar(100),
		CastCategory nvarchar(100),
        SUId nvarchar(50),
        LeftDate nvarchar(15),
        LCDate nvarchar(15),
        LeftStandard nvarchar(100),
        StatusId smallint,
        AdhaarNumber varchar(100),
        UIDNumber varchar(100)
        --Id1 bigint NULL,
        --departmentId int NULL
 
  )
  INSERT INTO #tTable1
	(
	    Code,
	    RegistrationNumber, 
	    FirstName,
		MiddleName,
	    LastName,
	    Class,
	    Division,
	    AdmissionStandard,
	    AdmissionDate,
	    DOB,
	    Gender,
	    --AdmissionCategory,
	    Religion,
	    CastCategory,
	    SUId,
	    LeftDate,
        LCDate,
        LeftStandard,
        StatusId,
        AdhaarNumber,
        UIDNumber
    ) 
   SELECT
        Code,
	    RegistrationNumber, 
	    sSetup.fPortalXMLTagsReplaceReverse(FirstName) AS FirstName,
		sSetup.fPortalXMLTagsReplaceReverse(MiddleName) AS MiddleName,
	    sSetup.fPortalXMLTagsReplaceReverse(LastName) AS LastName,
	    Class,
	    Division,
	    AdmissionStandard,
	    AdmissionDate,
	    DOB,
	    Gender,
	    --AdmissionCategory,
	    sSetup.fPortalXMLTagsReplaceReverse(Religion) AS Religion,
	    sSetup.fPortalXMLTagsReplaceReverse(CastCategory) AS CastCategory,
	    SUId,
	    LeftDate,
        LCDate,
        LeftStandard,
        StatusId,
        AdhaarNumber,
        UIDNumber
   
   FROM OPENXML (@intDoc, '/Table/ImportStudent', 1)
   With
   (
        Code nvarchar(50) '@Code',
        RegistrationNumber nvarchar(20) '@RegistrationNumber',
        FirstName nvarchar(100) '@FirstName',
		MiddleName nvarchar(100) '@MiddleName',
        LastName nvarchar(100) '@LastName',
		Class nvarchar(100) '@Class',
		Division nvarchar(100) '@Division',
		AdmissionStandard nvarchar(100) '@AdmissionStandard',
		AdmissionDate nvarchar(15) '@AdmissionDate',
		DOB nvarchar(15) '@DOB',
		Gender nvarchar(10) '@Gender',
		--AdmissionCategory nvarchar(100) '@AdmissionCategory',
		Religion nvarchar(100) '@Religion',
		CastCategory nvarchar(100) '@CastCategory',
		SUId nvarchar(50) '@SUId',
		LeftDate nvarchar(15) '@LeftDate',
		LCDate nvarchar(15) '@LCDate',
		LeftStandard nvarchar(100) '@LeftStandard',
		StatusId smallint '@StatusId',
		AdhaarNumber varchar(100) '@AdhaarNumber',
		UIDNumber varchar(100) '@UIDNumber'
   )   
EXEC sp_xml_removedocument @intDoc
		
SELECT @lCount =  COUNT(Id) FROM #tTable1

WHILE @lCount > 0 
  BEGIN
  
       SELECT         
         
         @lCode = Code, 
         @lRegistrationNumber = RegistrationNumber,
         @lAdmissionDate = AdmissionDate,
         @lDOB=DOB,
         @lSUId = SUId,
         @lLeftDate = LeftDate,
         @lLCDate = LCDate,
         @lStatusId = StatusId,
         @lAdhaarNumber = AdhaarNumber,
         @lUIDNumber = UIDNumber
        FROM #tTable1 WHERE Id = @lCount 

IF(@rOperation=2)
   BEGIN   
     IF Exists(SELECT Id FROM sStudent.tStudentMaster WHERE Code COLLATE DATABASE_DEFAULT = @lCode COLLATE DATABASE_DEFAULT AND OrgId = @rOrgId)    
      SET @1StudentId = (SELECT Id FROM sStudent.tStudentMaster WHERE Code COLLATE DATABASE_DEFAULT = @lCode COLLATE DATABASE_DEFAULT AND OrgId = @rOrgId)
     ELSE
       SET @1NotExistStudentCode = @1NotExistStudentCode + @lCode + ','    
       print @1NotExistStudentCode
   END     
       
        
IF(@rOperation=1 OR @rOperation=0)     
 BEGIN    
    IF Exists ((select 1 from sStudent.tStudentMaster where Code COLLATE DATABASE_DEFAULT = @lCode COLLATE DATABASE_DEFAULT AND OrgId = @rOrgId))         
          BEGIN
  			    SET @1ExistStudentCode = @1ExistStudentCode + @lCode + ','
	       END	  
	IF Exists ((select 1 from sStudent.tStudentMaster SM INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SM.OrgId where SM.SUId COLLATE DATABASE_DEFAULT = @lSUId COLLATE DATABASE_DEFAULT AND OM.OrgGroupId = @rOrgGroupId))         
          BEGIN
  			    SET @1ExistStudentSUId = @1ExistStudentSUId + @lSUId + ','
	       END	         
	IF Exists ((select 1 from sStudent.tStudentMaster where RegistrationNumber COLLATE DATABASE_DEFAULT = @lRegistrationNumber COLLATE DATABASE_DEFAULT AND OrgId = @rOrgId))         
          BEGIN
				IF(ISNULL(@lRegistrationNumber,'')!='')
				BEGIN
  					SET @1ExistStudentRegistrationNumber = @1ExistStudentRegistrationNumber + CAST(@lRegistrationNumber as varchar(max)) + ','
				END
	       END
	IF Exists ((select * from sStudent.tStudentOther SO INNER JOIN sStudent.tStudentMaster SM ON SM.Id = SO.StudentId INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SM.OrgId where SO.AdhaarNumber COLLATE DATABASE_DEFAULT = @lAdhaarNumber COLLATE DATABASE_DEFAULT))         
          BEGIN
          
                IF(ISNULL(@lAdhaarNumber,'')!='')
                BEGIN
  			        SET @1DuplicateAdhaarNumber = @1DuplicateAdhaarNumber + @lAdhaarNumber + ','
  			    END
	       END	
	     
	IF Exists ((select * from sStudent.tStudentOther SO INNER JOIN sStudent.tStudentMaster SM ON SM.Id = SO.StudentId INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SM.OrgId where SO.UIDNumber COLLATE DATABASE_DEFAULT = @lUIDNumber COLLATE DATABASE_DEFAULT))         
	BEGIN
		IF(@lIsStudentUIDNumberUnique='True')	--add
		BEGIN
			IF(ISNULL(@lUIDNumber,'')!='')
			BEGIN
                
  				SET @1DuplicateUIDNumber = @1DuplicateUIDNumber + @lUIDNumber + ',' 
  			                 
			END 
		END
	END	
END


ELSE

BEGIN    

    IF Exists ((select 1 from sStudent.tStudentMaster where Code COLLATE DATABASE_DEFAULT = @lCode COLLATE DATABASE_DEFAULT AND OrgId = @rOrgId AND Id<>@1StudentId))         
          BEGIN
  			    SET @1ExistStudentCode = @1ExistStudentCode + @lCode + ','
	       END	  
	IF Exists ((select 1 from sStudent.tStudentMaster SM INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SM.OrgId where SM.SUId COLLATE DATABASE_DEFAULT = @lSUId COLLATE DATABASE_DEFAULT AND OM.OrgGroupId = @rOrgGroupId AND SM.Id<>@1StudentId))         
          BEGIN
  			    SET @1ExistStudentSUId = @1ExistStudentSUId + @lSUId + ','
	       END	         
	IF Exists ((select 1 from sStudent.tStudentMaster where RegistrationNumber COLLATE DATABASE_DEFAULT = @lRegistrationNumber COLLATE DATABASE_DEFAULT AND OrgId = @rOrgId AND Id<>@1StudentId))         
          BEGIN
				IF(ISNULL(@lRegistrationNumber,'')!='')
				BEGIN
  					SET @1ExistStudentRegistrationNumber = @1ExistStudentRegistrationNumber + CAST(@lRegistrationNumber as varchar(max)) + ','
				END
	       END
	IF Exists ((select * from sStudent.tStudentOther SO INNER JOIN sStudent.tStudentMaster SM ON SM.Id = SO.StudentId INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SM.OrgId where SO.AdhaarNumber COLLATE DATABASE_DEFAULT = @lAdhaarNumber COLLATE DATABASE_DEFAULT AND SM.Id<>@1StudentId))         
          BEGIN
          
                IF(ISNULL(@lAdhaarNumber,'')!='')
                BEGIN
  			        SET @1DuplicateAdhaarNumber = @1DuplicateAdhaarNumber + @lAdhaarNumber + ','
  			    END
	       END	
	     
	IF Exists ((select * from sStudent.tStudentOther SO INNER JOIN sStudent.tStudentMaster SM ON SM.Id = SO.StudentId INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SM.OrgId where SO.UIDNumber COLLATE DATABASE_DEFAULT = @lUIDNumber COLLATE DATABASE_DEFAULT AND SM.Id<>@1StudentId))         
	BEGIN
		IF(@lIsStudentUIDNumberUnique='True')		--add
		BEGIN  
			IF(ISNULL(@lUIDNumber,'')!='')
			BEGIN
                
  				SET @1DuplicateUIDNumber = @1DuplicateUIDNumber + @lUIDNumber + ',' 
  			                 
			END 
		END   
	END	
END       
	       
	
	IF(ISDATE(@lAdmissionDate) = 0 AND @lAdmissionDate!='')
	BEGIN
		SET @1ValidAdmissionDate=@1ValidAdmissionDate + @lCode + '-' + @lAdmissionDate+','
	END
	IF(ISDATE(@lDOB) = 0 AND @lDOB!='')
	BEGIN
		SET @1ValidDOB=@1ValidDOB + @lCode + '-' + @lDOB+','
	END
	
	IF(ISDATE(@lLeftDate) = 0 AND @lLeftDate!='')
	BEGIN
		SET @1ValidLeftDate=@1ValidLeftDate + @lCode + '-' + @lLeftDate+','
	END
	
	IF(ISDATE(@lLCDate) = 0 AND @lLCDate!='')
	BEGIN
		SET @1ValidLCDate=@1ValidLCDate + @lCode + '-' + @lLCDate+','
	END
	
     SET @lCount = @lCount - 1	
   END	
   
   SELECT @lCount =  COUNT(Id) FROM #tTable1
 
	WHILE @lCount > 0 
		BEGIN
			SELECT         
         
			 @lClass = Class, 
			 @lDivision = Division
     
			FROM #tTable1 WHERE Id = @lCount
			    
		 --IF(@rOperation=1)
		 BEGIN	
			IF NOT EXISTS (SELECT 1 FROM sSetup.tDivisionMaster DM 
					INNER JOIN sSetup.tClassMaster CM ON CM.Id=DM.ClassId 
						WHERE CM.Title COLLATE DATABASE_DEFAULT =@lClass COLLATE DATABASE_DEFAULT AND DM.Title COLLATE DATABASE_DEFAULT =@lDivision COLLATE DATABASE_DEFAULT AND DM.OrgId=@rOrgId)	
			BEGIN
				
				SELECT 'Enter proper value for Division ' + @lClass + ' ' + @lDivision AS StudentCode
				RETURN
			END
		  END	
			SET @lCount = @lCount - 1	
		END
   	      If(@rOperation=2)
   	      BEGIN
   			  DECLARE @lExistingClassId int
   			  DECLARE @lExcelClassId int
   			  SET @lExistingClassId=(SELECT ClassId From sStudent.tAcademic WHERE StudentId=@1StudentId AND BatchId=@rBatchId)
	   		
   			  SET @lExcelClassId=(select Id from sSetup.tClassMaster where Title=@lClass and OrgId=@rOrgId)
	   		  
   			  IF(@lExcelClassId<>@lExistingClassId)
   		       BEGIN
				  SELECT 'Class Id not match/update.' AS StudentCode
			   END
   			
   	      END
              	      
   	      
   	      
   	    
			IF EXISTS(SELECT 1 fROM #tTable1 WHERE Code IS NULL OR Code COLLATE DATABASE_DEFAULT ='' COLLATE DATABASE_DEFAULT)
			BEGIN
				SELECT 'ID No Should not be empty' AS StudentCode
			END
		
		--ELSE IF EXISTS(SELECT 1 fROM #tTable1 WHERE Number IS NULL OR Number='')
		--BEGIN
		--	SELECT 'Number Should not be empty' AS StudentCode
		--END
		--ELSE IF EXISTS(SELECT 1 FROM #tTable1 WHERE LastName IS NULL OR LastName COLLATE DATABASE_DEFAULT ='' COLLATE DATABASE_DEFAULT)
		--BEGIN
		--	SELECT 'Surname Should not be empty' AS StudentCode
		--END
		ELSE IF EXISTS(SELECT 1 fROM #tTable1 WHERE FirstName IS NULL OR FirstName COLLATE DATABASE_DEFAULT='' COLLATE DATABASE_DEFAULT)
		BEGIN
			SELECT 'First Name Should not be empty' AS StudentCode
		END
		ELSE IF EXISTS(SELECT 1 fROM #tTable1 WHERE Class IS NULL OR Class COLLATE DATABASE_DEFAULT ='' COLLATE DATABASE_DEFAULT) AND (@rOperation=1)
		BEGIN
			SELECT 'Class Should not be empty' AS StudentCode
		END
		ELSE IF EXISTS(SELECT 1 fROM #tTable1 WHERE Division IS NULL OR Division COLLATE DATABASE_DEFAULT ='' COLLATE DATABASE_DEFAULT) AND (@rOperation=1)
		BEGIN
			SELECT 'Division Should not be empty' AS StudentCode
		END
		--ELSE IF EXISTS(SELECT 1 fROM #tTable1 WHERE AdmissionStandard IS NULL OR AdmissionStandard='')
		--BEGIN
		--	SELECT 'Admission Standard Should not be empty' AS StudentCode
		--END
		ELSE IF EXISTS(SELECT 1 fROM #tTable1 WHERE Gender IS NULL OR Gender='')
		BEGIN
			SELECT 'Gender Should not be empty' AS StudentCode
		END
		--ELSE IF EXISTS(SELECT 1 fROM #tTable1 WHERE AdmissionCategory IS NULL OR AdmissionCategory='')
		--BEGIN
		--	SELECT 'Admission Category Should not be empty' AS StudentCode
		--END
		ELSE IF EXISTS(SELECT 1 fROM #tTable1 WHERE AdmissionDate IS NULL OR AdmissionDate COLLATE DATABASE_DEFAULT='' COLLATE DATABASE_DEFAULT) AND (@rOperation=1)
		BEGIN
			SELECT 'Admission Date Should not be empty or check the date format' AS StudentCode
		END
		ELSE IF EXISTS(SELECT 1 fROM #tTable1 WHERE Class COLLATE DATABASE_DEFAULT NOT IN(SELECT Title FROM sSetup.tClassMaster WHERE OrgId=@rOrgId)) AND (@rOperation=1)
		BEGIN
			SELECT 'Enter proper value for Class as per Institute Setup > Class Master' AS StudentCode
		END				
		ELSE IF EXISTS(SELECT 1 fROM #tTable1 WHERE AdmissionStandard  COLLATE DATABASE_DEFAULT !='' COLLATE DATABASE_DEFAULT AND AdmissionStandard COLLATE DATABASE_DEFAULT NOT IN(SELECT Title FROM sSetup.tClassMaster WHERE OrgId=@rOrgId)) AND (@rOperation=1)
		BEGIN
			SELECT 'Enter proper value for Admission Class as per Admin Tool > Institute Setup > Class Master' AS StudentCode
		END
		ELSE IF EXISTS(SELECT 1 fROM #tTable1 WHERE Religion COLLATE DATABASE_DEFAULT !='' COLLATE DATABASE_DEFAULT AND Religion COLLATE DATABASE_DEFAULT NOT IN(SELECT Title FROM sCommon.tReligionMaster WHERE OrgGroupId=@rOrgGroupId))
		BEGIN
			SELECT 'Enter proper value / Check spelling for Religion per Admin Tool > Master > Religion Master' AS StudentCode
		END
		ELSE IF EXISTS(SELECT 1 fROM #tTable1 WHERE Gender COLLATE DATABASE_DEFAULT !='' COLLATE DATABASE_DEFAULT AND Gender COLLATE DATABASE_DEFAULT NOT IN(SELECT Title FROM sCommon.tGenderMaster))
		BEGIN
			SELECT 'Enter proper value / Check spelling for gender ( Male / Female )' AS StudentCode
		END
		ELSE IF EXISTS(SELECT 1 fROM #tTable1 WHERE CastCategory COLLATE DATABASE_DEFAULT !='' COLLATE DATABASE_DEFAULT AND CastCategory COLLATE DATABASE_DEFAULT NOT IN(SELECT Title FROM sCommon.tCastCategoryMaster))
		BEGIN
			SELECT 'Enter proper value for Cast Category (OBC,SC,ST,GENERAL)' AS StudentCode
		END
		ELSE IF EXISTS(SELECT 1 fROM #tTable1 WHERE (LeftDate IS NULL OR LeftDate COLLATE DATABASE_DEFAULT ='' COLLATE DATABASE_DEFAULT AND LeftStandard COLLATE DATABASE_DEFAULT !='' COLLATE DATABASE_DEFAULT) AND @lStatusId<>1) AND (@rOperation=1)
		BEGIN
			SELECT 'Left Date Should not be empty or check the date format' AS StudentCode
		END
		ELSE IF EXISTS(SELECT 1 fROM #tTable1 WHERE (LCDate IS NULL OR LCDate COLLATE DATABASE_DEFAULT ='' COLLATE DATABASE_DEFAULT AND LeftStandard COLLATE DATABASE_DEFAULT !='' COLLATE DATABASE_DEFAULT) AND @lStatusId<>1)
		BEGIN
			SELECT 'LC Date Should not be empty or check the date format' AS StudentCode
		END
	
		--ELSE IF EXISTS(SELECT 1 fROM #tTable1 WHERE  LeftStandard COLLATE DATABASE_DEFAULT NOT IN(SELECT Title FROM sSetup.tClassMaster WHERE OrgId=@rOrgId) AND @lLeftDate!='')
		--BEGIN
		--	SELECT 'Enter proper value for Left Standard as per Institute Setup > Class Master' AS StudentCode
		--END	
		--ELSE IF EXISTS(SELECT 1 fROM #tTable1 WHERE LeftDate IS NULL OR LeftDate COLLATE DATABASE_DEFAULT ='' COLLATE DATABASE_DEFAULT AND LeftStandard COLLATE DATABASE_DEFAULT !='' COLLATE DATABASE_DEFAULT)
		--BEGIN
		--	SELECT 'LeftDate Should not be empty or check the date format' AS StudentCode
		--END
		ELSE
		BEGIN
	
		IF (@1NotExistStudentCode IS NOT NULL AND @1NotExistStudentCode COLLATE DATABASE_DEFAULT != '' COLLATE DATABASE_DEFAULT)
		BEGIN
		
			SET @1NotExistStudentCode = 'Not Exist Code ' + @1NotExistStudentCode
			Select @1NotExistStudentCode AS StudentCode
		END		
		
		
		SELECT @1DuplicateStudentCode=COALESCE(@1DuplicateStudentCode ,'') + Code + ',' FROM #tTable1 GROUP BY Code HAVING ( COUNT(Code) > 1 )	
		
	   
			
		SELECT @1DuplicateStudentSUId=COALESCE(@1DuplicateStudentSUId ,'') + SUId + ',' FROM #tTable1 GROUP BY SUId HAVING ( COUNT(SUId) > 1 )	
			IF(@1DuplicateStudentSUId IS NOT NULL AND @1DuplicateStudentSUId != '' AND @lIsActivateUniqueId=1)
				BEGIN
				
					SET @1DuplicateStudentSUId = 'Duplicate SUId ' + @1DuplicateStudentSUId
					SELECT @1DuplicateStudentSUId AS StudentCode
				END
			ELSE IF(@1DuplicateStudentCode IS NOT NULL AND @1DuplicateStudentCode COLLATE DATABASE_DEFAULT != '' COLLATE DATABASE_DEFAULT)
				BEGIN
				  
					SET @1DuplicateStudentCode = 'Duplicate Code ' + @1DuplicateStudentCode
					
					SELECT @1DuplicateStudentCode AS StudentCode
				END
			ELSE			
				BEGIN
				SELECT @1DuplicateStudentRegistrationNumber=COALESCE(@1DuplicateStudentRegistrationNumber ,'') + CONVERT(VARCHAR(20),RegistrationNumber) + ',' FROM #tTable1 GROUP BY RegistrationNumber HAVING ( COUNT(RegistrationNumber) > 1 AND ISNULL(RegistrationNumber,'')!='')	
				IF(@1DuplicateStudentRegistrationNumber IS NOT NULL AND @1DuplicateStudentRegistrationNumber  COLLATE DATABASE_DEFAULT != '' COLLATE DATABASE_DEFAULT)
				BEGIN
					SET @1DuplicateStudentRegistrationNumber = 'Duplicate Registration Number ' + @1DuplicateStudentRegistrationNumber
					SELECT @1DuplicateStudentRegistrationNumber AS StudentCode
				END
		
		ELSE IF (@1DuplicateAdhaarNumber IS NOT NULL AND @1DuplicateAdhaarNumber COLLATE DATABASE_DEFAULT != '' COLLATE DATABASE_DEFAULT)
		BEGIN
		  
			SET @1DuplicateAdhaarNumber = 'Exist Adhaar Number ' + @1DuplicateAdhaarNumber
			Select @1DuplicateAdhaarNumber AS StudentCode
		END
		
		
		ELSE IF (@1DuplicateUIDNumber IS NOT NULL AND @1DuplicateUIDNumber COLLATE DATABASE_DEFAULT != '' COLLATE DATABASE_DEFAULT AND @lIsStudentUIDNumberUnique='True') --add
		BEGIN
			SET @1DuplicateUIDNumber = 'Exist UID Number ' + @1DuplicateUIDNumber
			Select @1DuplicateUIDNumber AS StudentCode
		END
		
		
		ELSE IF((@1ExistStudentSUId IS NULL OR @1ExistStudentSUId = '' OR @lIsActivateUniqueId=0) AND (@1ExistStudentCode IS NULL OR @1ExistStudentCode = '') AND (@1ExistStudentRegistrationNumber IS NULL OR @1ExistStudentRegistrationNumber = '')
		AND (@1ValidAdmissionDate IS NULL OR @1ValidAdmissionDate = '') AND (@1ValidDOB IS NULL OR @1ValidDOB = ''))
		BEGIN
		
			SELECT '' AS StudentCode
		END
		ELSE IF (@1ExistStudentSUId IS NOT NULL AND @1ExistStudentSUId != '' AND @lIsActivateUniqueId=1)
		BEGIN
			SET @1ExistStudentSUId = 'Exist SUId ' + @1ExistStudentSUId
			Select @1ExistStudentSUId AS StudentCode
		END
		
		
		
		
		ELSE IF (@1ExistStudentCode IS NOT NULL AND @1ExistStudentCode COLLATE DATABASE_DEFAULT != '' COLLATE DATABASE_DEFAULT)
		BEGIN
			SET @1ExistStudentCode = 'Exist Code ' + @1ExistStudentCode
			Select @1ExistStudentCode AS StudentCode
		END
		
		ELSE IF (@1ExistStudentRegistrationNumber IS NOT NULL AND @1ExistStudentRegistrationNumber COLLATE DATABASE_DEFAULT != '' COLLATE DATABASE_DEFAULT)
		BEGIN
			SET @1ExistStudentRegistrationNumber = 'Exist Registration Number ' + @1ExistStudentRegistrationNumber
			Select @1ExistStudentRegistrationNumber AS StudentCode
		END
		ELSE IF (@1ValidAdmissionDate IS NOT NULL AND @1ValidAdmissionDate != '')
		BEGIN
			SET @1ValidAdmissionDate = 'Wrong Admission Date ' + @1ValidAdmissionDate
			Select @1ValidAdmissionDate AS StudentCode
		END
		ELSE IF (@1ValidDOB IS NOT NULL AND @1ValidDOB != '')
		BEGIN
			SET @1ValidDOB = 'Wrong DOB ' + @1ValidDOB
			Select @1ValidDOB AS StudentCode
		END
		ELSE IF (@1ValidLeftDate IS NOT NULL AND @1ValidLeftDate != '' AND @lLCDate!='')
		BEGIN
			SET @1ValidLeftDate = 'Wrong LeftDate ' + @1ValidLeftDate
			Select @1ValidLeftDate AS StudentCode
		END
		ELSE IF (@1ValidLCDate IS NOT NULL AND @1ValidLCDate != '' AND @lLCDate!='')
		BEGIN
			SET @1ValidLCDate = 'Wrong LCDate ' + @1ValidLCDate
			Select @1ValidLCDate AS StudentCode
		END
		
		ELSE IF (@lIsSurnameAndFatherNameMandatory = 'True' )
		BEGIN
			IF EXISTS(SELECT 1 fROM #tTable1 WHERE MiddleName IS NULL OR MiddleName COLLATE DATABASE_DEFAULT='' COLLATE DATABASE_DEFAULT)
			BEGIN
				SELECT 'FatherName Should not be empty' AS StudentCode
			END
			IF EXISTS(SELECT 1 fROM #tTable1 WHERE LastName IS NULL OR LastName COLLATE DATABASE_DEFAULT='' COLLATE DATABASE_DEFAULT)
			BEGIN
				SELECT 'Surname Should not be empty' AS StudentCode
			END
			ELSE 
			BEGIN
				SELECT '' AS StudentCode
			END
						
		END



		END
		END
END
GO
PRINT N'Altering Procedure [sTally].[pReceiptPostingGet]...';


GO

ALTER PROCEDURE [sTally].[pReceiptPostingGet]

	 @rOrgGroupBatchId int,
	 @rReceiptBookId int,
	 @rReceiptDate Date,
	 @rToReceiptDate Date,
	 @rPayTypeId int = 0,
	 @rCustomNarration nvarchar(max)='',
	 @rIsCustomNarration bit=0
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
	
	DECLARE @lTallyPostingType nVarchar(100)
	DECLARE @lOrgGroupId INT
	
	SELECT @lOrgGroupId = OrgGroupId from sSetup.tOrgGroupBatchMaster Where Id=@rOrgGroupBatchId
	
	SELECT @lTallyPostingType = CASE WHEN CS.ItemValue IS NULL THEN C.ItemValue ELSE CS.ItemValue END 
		FROM sConfig.tConfigurationMaster C
        INNER JOIN sConfig.tConfigurationLevelMaster CM ON CM.Id = C.ConfigurationLevelId
        LEFT JOIN sConfig.tConfigurationSetup CS ON CS.ConfigurationId = C.Id AND CS.SOURCEID= @lOrgGroupId
        WHERE  C.ItemKey = 'Tally.PostingType'
        
		
        IF @lTallyPostingType = 'FeeHeadWise' 
        BEGIN
			   SELECT	ReceiptDate,
						ISNULL(FHM.Title,'') AS FeeName,
						PM.Title AS PayType,
						Sum(FRD.Amount) AS Amount,
						Case when @rIsCustomNarration=1 then STUFF((SELECT distinct ','  +Replace(replace(
																					Replace(
																					replace(
																					Replace(
																					replace(
																					Replace(
																					replace(
																					Replace(
																					replace(
																					Replace(
																					replace(
																					Replace(
																					replace(
																					Replace(
																					replace(
																					replace(
																					@rCustomNarration,'[Class]',isnull(SM1.ClassName,'')
																					),'[Division]',Isnull(SM1.DivisionName,'')
																					),'[StudentsName]',isnull(SM1.Name,'')
																					), '[RollNumber]',isnull(convert(nvarchar(200),SM1.RollNo),'0')
																					),'[Batch]',isnull(SM1.BatchName,'')
																					), '[ReceiptNumber]', isnull(Convert(nvarchar(100),FR1.ReceiptNumber),'')
																					), '[ReceiptDate]',isnull(Convert(nvarchar(100),FR1.ReceiptDate),'')
																					), '[ReceiptAmount]',isnull(Convert(nvarchar(100),FR1.ReceiptAmount),'')
																					), '[ChequeNo]',isnull(Convert(nvarchar(100),FR1.ChequeNo),'')
																					),'[BankName]',isnull(FR1.BankName,'')
																					),'[FeeName]',isnull(FM1.Title,'')
																					), '[FeeAmount]',isnull(Convert(nvarchar(100),Sum(FRD.Amount)),'0.00')
																					),'[FeeHeadName]',ISNULL(FHM.Title,'')
																					), '[FeeHeadAmount]',isnull(Convert(nvarchar(100),Sum(FRD.Amount)),'0.00')
																					), '[CollectionGroupName]',isNull(CGM1.Title,'')
																					),'[ReceiptFromNumber]',isnull(Convert(nvarchar(10),(Select Min(ReceiptNumber) from sFee.tReceipt where   FR.ReceiptDate =ReceiptDate)),'')
																					), '[ReceiptToNumber]',isnull(Convert(nvarchar(10),(Select Max(ReceiptNumber) from sFee.tReceipt Where FR.ReceiptDate = ReceiptDate)),''))
						from sFee.tReceipt FR1  INNER JOIN sFee.tReceiptDetail FRD1 ON FR1.Id = FRD1.ReceiptId
						INNER JOIN sFee.tFeeSetup FS1 ON FS1.Id = FRD1.FeeSetupId 
						INNER JOIN sStudent.vStudentAcademic SM1 ON SM1.ACademicId = FR1.SourceID AND SM1.OrgGRoupBatchId = FR1.OrgGRoupBatchId 						
						INNER JOIN sFee.tFeeMaster FM1 ON FM1.Id = FS1.FeeId --AND FRD.ReceiptId=FRD1.ReceiptId
						LEFT JOIN sFee.tCollectionGroupMaster CGM1 ON CGM1.Id = FS1.CollectionGroupId
						INNER JOIN sFee.tFeeHeadMaster FHM1 ON FHM1.Id = FM1.FeeHeadId AND FHM1.Id=FHM.Id where  FR.ReceiptDate=FR1.ReceiptDate FOR XML PATH('')),1,1,'') else
						 'Receipt generated for Batch : ' + (Select Title from sSetup.tOrgGroupBatchMaster Where Id= @rOrgGroupBatchId) +
						' Receipt Date : ' +  Convert(nvarchar(10),ReceiptDate) + ' and Receipt Number From ' + Convert(nvarchar(10),(Select Min(ReceiptNumber) from sFee.tReceipt where   FR.ReceiptDate =ReceiptDate AND IsObsolete = 0 )) + ' -  ' + 
						Convert(nvarchar(10),(Select Max(ReceiptNumber) from sFee.tReceipt Where FR.ReceiptDate = ReceiptDate AND IsObsolete = 0)) end as Narration,						
						FR.PayTypeId AS PayTypeId, 
						FHM.Id AS FeeId,
						0 AS ReceiptId
				FROM sFee.tReceipt FR 
					INNER JOIN sFee.tReceiptDetail FRD ON FR.Id = FRD.ReceiptId
					INNER JOIN sFee.tFeeSetup FS ON FS.Id = FRD.FeeSetupId
					INNER JOIN sFee.tFeeMaster FM ON FM.Id = FS.FeeId
					INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id = FM.FeeHeadId
					INNER JOIN sFinanceCommon.tPayTypeMaster PM ON PM.Id = FR.PayTypeId
					WHERE	FR.ReceiptBookId = @rReceiptBookId 
							AND FR.IsObsolete = 0 
							AND FR.OrgGroupBatchId = @rOrgGroupBatchId
							AND FR.ReceiptDate >= @rReceiptDate AND FR.ReceiptDate <= @rToReceiptDate
							AND (FR.PayTypeId = @rPayTypeId OR @rPayTypeId = 0)
				group by ReceiptDate,FHM.Title,PM.Title,FHM.Id,FR.PayTypeId
				Order By ReceiptDate Desc
			END				
       ELSE IF @lTallyPostingType = 'FeeHeadWiseCustom' 
        BEGIN
			   SELECT	ReceiptDate,
						FR.Id AS FeeName,
						PM.Title AS PayType,
						Sum(FRD.Amount) AS Amount,
						Case when @rIsCustomNarration=1 then  STUFF((SELECT distinct ','  +Replace(replace(
																					Replace(
																					replace(
																					Replace(
																					replace(
																					Replace(
																					replace(
																					Replace(
																					replace(
																					Replace(
																					replace(
																					Replace(
																					replace(
																					Replace(
																					replace(
																					replace(
																					@rCustomNarration,'[Class]',isnull(SM1.ClassName,'')
																					),'[Division]',Isnull(SM1.DivisionName,'')
																					),'[StudentsName]',isnull(SM1.Name,'')
																					), '[RollNumber]',isnull(convert(nvarchar(200),SM1.RollNo),'0')
																					),'[Batch]',isnull(SM1.BatchName,'')
																					), '[ReceiptNumber]', isnull(Convert(nvarchar(100),FR1.ReceiptNumber),'')
																					), '[ReceiptDate]',isnull(Convert(nvarchar(100),FR1.ReceiptDate),'')
																					), '[ReceiptAmount]',isnull(Convert(nvarchar(100),FR1.ReceiptAmount),'')
																					), '[ChequeNo]',isnull(Convert(nvarchar(100),FR1.ChequeNo),'')
																					),'[BankName]',isnull(FR1.BankName,'')
																					),'[FeeName]',isnull(FM1.Title,'')
																					), '[FeeAmount]',isnull(Convert(nvarchar(100),Sum(FRD.Amount)),'0.00')
																					),'[FeeHeadName]',ISNULL(FHM1.Title,'')
																					), '[FeeHeadAmount]',isnull(Convert(nvarchar(100),Sum(FRD.Amount)),'0.00')
																					), '[CollectionGroupName]',isNull(CGM1.Title,'')
																					),'[ReceiptFromNumber]',isnull(Convert(nvarchar(10),(Select Min(ReceiptNumber) from sFee.tReceipt where   FR.ReceiptDate =ReceiptDate AND IsObsolete = 0)),'')
																					), '[ReceiptToNumber]',isnull(Convert(nvarchar(10),(Select Max(ReceiptNumber) from sFee.tReceipt Where FR.ReceiptDate = ReceiptDate AND IsObsolete = 0)),''))
						from sFee.tReceipt FR1  INNER JOIN sFee.tReceiptDetail FRD1 ON FR1.Id = FRD1.ReceiptId
						INNER JOIN sFee.tFeeSetup FS1 ON FS1.Id = FRD1.FeeSetupId 
						INNER JOIN sStudent.vStudentAcademic SM1 ON SM1.ACademicId = FR1.SourceID AND SM1.OrgGRoupBatchId = FR1.OrgGRoupBatchId 						
						INNER JOIN sFee.tFeeMaster FM1 ON FM1.Id = FS1.FeeId --AND FRD.ReceiptId=FRD1.ReceiptId
						LEFT JOIN sFee.tCollectionGroupMaster CGM1 ON CGM1.Id = FS1.CollectionGroupId
						INNER JOIN sFee.tFeeHeadMaster FHM1 ON FHM1.Id = FM1.FeeHeadId  where   FR.ReceiptDate=FR1.ReceiptDate AND FR.Id=FR1.Id AND FR1.IsObsolete = 0  FOR XML PATH('')),1,1,'') else
						SM.Name + '(' + ClassName + ':' + DivisionName + ') ' + ' # Cheque No. :' + ISNULL(FR.ChequeNo,'') + ' BankName :' + ISNULL(FR.BankName,'') end as Narration,						
						FR.PayTypeId AS PayTypeId, 
						0 AS FeeId,
						FR.Id AS ReceiptId
				FROM sFee.tReceipt FR 
					INNER JOIN sFee.tReceiptDetail FRD ON FR.Id = FRD.ReceiptId
					INNER JOIN sStudent.vStudentAcademic SM ON SM.ACademicId = FR.SourceID AND SM.OrgGRoupBatchId = FR.OrgGRoupBatchId 
					INNER JOIN sFee.tFeeSetup FS ON FS.Id = FRD.FeeSetupId
					INNER JOIN sFee.tFeeMaster FM ON FM.Id = FS.FeeId
					INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id = FM.FeeHeadId
					INNER JOIN sFinanceCommon.tPayTypeMaster PM ON PM.Id = FR.PayTypeId
					INNER JOIN sSetup.tOrganizationMaster OM ON  OM.Id=SM.OrgId
					LEFT JOIN sSetup.tOrgSubGroupMaster OSM ON OSM.id=OM.OrgSubGroupId

					WHERE	FR.ReceiptBookId= @rReceiptBookId 
							AND FR.IsObsolete = 0 
							AND FR.OrgGroupBatchId = @rOrgGroupBatchId
							AND FR.ReceiptDate >= @rReceiptDate AND FR.ReceiptDate <= @rToReceiptDate
							AND (FR.PayTypeId = @rPayTypeId OR @rPayTypeId = 0)
				group by ReceiptDate,PM.Title,FR.PayTypeId,FR.Id,SM.Name + '(' + ClassName + ':' + DivisionName + ') ' + ' # Cheque No. :' + ISNULL(FR.ChequeNo,'') + ' BankName :' + ISNULL(FR.BankName,'')
				Order By FR.Id,ReceiptDate Desc
			END	

       ELSE IF @lTallyPostingType = 'OrgMainGroupWise' 
        BEGIN
			   SELECT	ReceiptDate,
						SM.AcademicId AS FeeName,
						PM.Title AS PayType,
						Sum(FRD.Amount) AS Amount,
						Case when @rIsCustomNarration=1 then  STUFF((SELECT distinct ','  +Replace(replace(
																					Replace(
																					replace(
																					Replace(
																					replace(
																					Replace(
																					replace(
																					Replace(
																					replace(
																					Replace(
																					replace(
																					Replace(
																					replace(
																					Replace(
																					replace(
																					replace(
																					@rCustomNarration,'[Class]',isnull(SM1.ClassName,'')
																					),'[Division]',Isnull(SM1.DivisionName,'')
																					),'[StudentsName]',isnull(SM1.Name,'')
																					), '[RollNumber]',isnull(convert(nvarchar(200),SM1.RollNo),'0')
																					),'[Batch]',isnull(SM1.BatchName,'')
																					), '[ReceiptNumber]', isnull(Convert(nvarchar(100),FR1.ReceiptNumber),'')
																					), '[ReceiptDate]',isnull(Convert(nvarchar(100),FR1.ReceiptDate),'')
																					), '[ReceiptAmount]',isnull(Convert(nvarchar(100),FR1.ReceiptAmount),'')
																					), '[ChequeNo]',isnull(Convert(nvarchar(100),FR1.ChequeNo),'')
																					),'[BankName]',isnull(FR1.BankName,'')
																					),'[FeeName]',isnull(FM1.Title,'')
																					), '[FeeAmount]',isnull(Convert(nvarchar(100),Sum(FRD.Amount)),'0.00')
																					),'[FeeHeadName]',ISNULL(FHM1.Title,'')
																					), '[FeeHeadAmount]',isnull(Convert(nvarchar(100),Sum(FRD.Amount)),'0.00')
																					), '[CollectionGroupName]',isNull(CGM1.Title,'')
																					),'[ReceiptFromNumber]',isnull(Convert(nvarchar(10),FR1.ReceiptNumber),'')
																					), '[ReceiptToNumber]',isnull(Convert(nvarchar(10),FR1.ReceiptNumber),''))
						from sFee.tReceipt FR1  INNER JOIN sFee.tReceiptDetail FRD1 ON FR1.Id = FRD1.ReceiptId
						INNER JOIN sFee.tFeeSetup FS1 ON FS1.Id = FRD1.FeeSetupId 
						INNER JOIN sStudent.vStudentAcademic SM1 ON SM1.ACademicId = FR1.SourceID AND SM1.OrgGRoupBatchId = FR1.OrgGRoupBatchId 						
						INNER JOIN sFee.tFeeMaster FM1 ON FM1.Id = FS1.FeeId --AND FRD.ReceiptId=FRD1.ReceiptId
						LEFT JOIN sFee.tCollectionGroupMaster CGM1 ON CGM1.Id = FS1.CollectionGroupId
						INNER JOIN sFinanceCommon.tPayTypeMaster PM1 ON PM1.Id = FR1.PayTypeId
						INNER JOIN sFee.tFeeHeadMaster FHM1 ON FHM1.Id = FM1.FeeHeadId  where  FR.ReceiptDate=FR1.ReceiptDate AND PM.Title=PM1.Title AND SM.AcademicId=SM1.AcademicId AND  FR.PayTypeId=FR1.PayTypeId AND FR1.IsObsolete = 0  FOR XML PATH('')),1,1,'') else
						SM.Name + '(' + ClassName + ':' + DivisionName + ') ' + ' # Cheque No. :' + ISNULL(FR.ChequeNo,'') + ' BankName :' + ISNULL(FR.BankName,'') end as Narration,						
						FR.PayTypeId AS PayTypeId, 
						FR.Id AS FeeId,
						SM.AcademicId AS ReceiptId
				FROM sFee.tReceipt FR 
					INNER JOIN sFee.tReceiptDetail FRD ON FR.Id = FRD.ReceiptId
					INNER JOIN sStudent.vStudentAcademic SM ON SM.ACademicId = FR.SourceID AND SM.OrgGRoupBatchId = FR.OrgGRoupBatchId 
					INNER JOIN sFee.tFeeSetup FS ON FS.Id = FRD.FeeSetupId
					INNER JOIN sFee.tFeeMaster FM ON FM.Id = FS.FeeId
					INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id = FM.FeeHeadId
					INNER JOIN sFinanceCommon.tPayTypeMaster PM ON PM.Id = FR.PayTypeId
					INNER JOIN sSEtup.tOrganizationMaster OM ON OM.OrgSubGRoupID =  @rReceiptBookId AND OM.ID = SM.OrgId					
					WHERE	FR.IsObsolete = 0 
							AND FR.OrgGroupBatchId = @rOrgGroupBatchId
							AND FR.ReceiptDate >= @rReceiptDate AND FR.ReceiptDate <= @rToReceiptDate
							AND FR.PayTypeID = 2
							AND (FR.PayTypeId = @rPayTypeId OR @rPayTypeId = 0)
				group by ReceiptDate,PM.Title,SM.AcademicId ,FR.PayTypeId,FR.Id,SM.Name + '(' + ClassName + ':' + DivisionName + ') ' + ' # Cheque No. :' + ISNULL(FR.ChequeNo,'') + ' BankName :' + ISNULL(FR.BankName,'')
				Order By FR.Id,ReceiptDate Desc
			END	
	ELSE IF @lTallyPostingType = 'ReceiptWise' 
			BEGIN	
				SELECT	ReceiptDate,						
						ISNULL(SLM.LedgerName,'') AS FeeName,
						PM.Title AS PayType,						
						FR.ReceiptAmount AS Amount,
						Case when @rIsCustomNarration=1 then  STUFF((SELECT distinct ','+  +Replace(
																					replace(
																					Replace(
																					replace(
																					Replace(
																					replace(
																					Replace(
																					replace(
																					Replace(
																					replace(
																					Replace(
																					replace(
																					Replace(
																					replace(
																					Replace(
																					replace(
																					replace(
																					@rCustomNarration,'[Class]',isnull(SM1.ClassName,'')
																					),'[Division]',Isnull(SM1.DivisionName,'')
																					),'[StudentsName]',isnull(SM1.Name,'')
																					), '[RollNumber]',isnull(convert(nvarchar(200),SM1.RollNo),'0')
																					),'[Batch]',isnull(SM1.BatchName,'')
																					), '[ReceiptNumber]', isnull(Convert(nvarchar(100),FR1.ReceiptNumber),'')
																					), '[ReceiptDate]',isnull(Convert(nvarchar(100),FR1.ReceiptDate),'')
																					), '[ReceiptAmount]',isnull(Convert(nvarchar(100),FR1.ReceiptAmount),'')
																					), '[ChequeNo]',isnull(Convert(nvarchar(100),FR1.ChequeNo),'')
																					),'[BankName]',isnull(FR1.BankName,'')
																					),'[FeeName]',isnull(FM1.Title,'')
																					), '[FeeAmount]',isnull(Convert(nvarchar(100),Sum(FRD.Amount)),'0.00')
																					),'[FeeHeadName]',ISNULL(FHM1.Title,'')
																					), '[FeeHeadAmount]',isnull(Convert(nvarchar(100),Sum(FRD.Amount)),'0.00')
																					), '[CollectionGroupName]',isNull(CGM1.Title,'')
																					),'[ReceiptFromNumber]',isnull(Convert(nvarchar(10),FR1.ReceiptNumber),'')
																					), '[ReceiptToNumber]',isnull(Convert(nvarchar(10),FR1.ReceiptNumber),''))
						from sFee.tReceipt FR1  INNER JOIN sFee.tReceiptDetail FRD1 ON FR1.Id = FRD1.ReceiptId
						INNER JOIN sFee.tFeeSetup FS1 ON FS1.Id = FRD1.FeeSetupId 
						INNER JOIN sStudent.vStudentAcademic SM1 ON SM1.ACademicId = FR1.SourceID AND SM1.OrgGRoupBatchId = FR1.OrgGRoupBatchId 						
						INNER JOIN sFee.tFeeMaster FM1 ON FM1.Id = FS1.FeeId --AND FRD.ReceiptId=FRD1.ReceiptId
						LEFT JOIN sFee.tCollectionGroupMaster CGM1 ON CGM1.Id = FS1.CollectionGroupId
						INNER JOIN sFinanceCommon.tPayTypeMaster PM1 ON PM1.Id = FR1.PayTypeId
						INNER JOIN sFee.tFeeHeadMaster FHM1 ON FHM1.Id = FM1.FeeHeadId
						LEFT JOIN sTally.tStudentLedgerMapping SLM1 ON SLM1.StudentId = SM1.StudentId AND SLM1.ReceiptBookid = FR1.ReceiptBookId AND SLM.LedgerName=SLM1.LedgerName where  FR1.ReceiptDate=FR.ReceiptDate   AND FR1.PayTypeId=FR.PayTypeId AND  A.StudentId=SM1.
StudentId AND FR.ReceiptAmount=FR1.ReceiptAmount AND FR1.IsObsolete = 0  FOR XML PATH('')),1,1,'') else
						case When FR.PayTypeId = 1 then
						'Std-' + ClassName + ':' + DivisionName + ' RollNo :' + convert(nvarchar(20),RollNo) + ' ' + BatchName + '-->' +
						STUFF((SELECT ','  + convert(nvarchar(20),isnull(FRD1.Amount,'')) + '-' + isnull(FM1.Title ,'') 
						from sFee.tReceipt FR1  INNER JOIN sFee.tReceiptDetail FRD1 ON FR1.Id = FRD1.ReceiptId
						INNER JOIN sFee.tFeeSetup FS1 ON FS1.Id = FRD1.FeeSetupId 						
						INNER JOIN sFee.tFeeMaster FM1 ON FM1.Id = FS1.FeeId AND FRD.ReceiptId=FRD1.ReceiptId  FOR XML PATH('')),1,1,'') 
						when FR.PayTypeId <> 1 then 
						'Std-' + ClassName + ':' + DivisionName + ' RollNo :' + convert(nvarchar(20),RollNo) + ' ' + BatchName + '-->' +
						STUFF((SELECT ','  + convert(nvarchar(20),isnull(FRD1.Amount,'')) + '-' + isnull(FM1.Title ,'') 
						from sFee.tReceipt FR1  INNER JOIN sFee.tReceiptDetail FRD1 ON FR1.Id = FRD1.ReceiptId
						INNER JOIN sFee.tFeeSetup FS1 ON FS1.Id = FRD1.FeeSetupId 						
						INNER JOIN sFee.tFeeMaster FM1 ON FM1.Id = FS1.FeeId AND FRD.ReceiptId=FRD1.ReceiptId  FOR XML PATH('')),1,1,'') + '  Cheque No. :' + ISNULL(FR.ChequeNo,'') + ' BankName :' + ISNULL(FR.BankName,'')  ENd
						end AS Narration,
						--A.Name+', '+ClassName + '-' + DivisionName+', '+A.OrganizationName+', ('+BatchName+')'
						--AS Narration,					
						FR.PayTypeId AS PayTypeId,									
						A.StudentId AS FeeId,
						FRD.ReceiptId					 
				FROM sFee.tReceipt FR 
					INNER JOIN sFee.tReceiptDetail FRD ON FR.Id = FRD.ReceiptId
					INNER JOIN sFee.tFeeSetup FS ON FS.Id = FRD.FeeSetupId
					INNER JOIN sFee.tFeeMaster FM ON FM.Id = FS.FeeId
					INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id = FM.FeeHeadId
					INNER JOIN sFinanceCommon.tPayTypeMaster PM ON PM.Id = FR.PayTypeId
					INNER JOIN sStudent.vStudentAcademic A ON A.AcademicId = FR.SourceId AND A.OrgGRoupBatchId = FR.OrgGRoupBatchId
					LEFT JOIN sTally.tStudentLedgerMapping SLM ON SLM.StudentId = A.StudentId AND SLM.ReceiptBookid = FR.ReceiptBookId
					WHERE							
							FR.ReceiptBookId = @rReceiptBookId 
							AND FR.IsObsolete = 0 
							AND FR.OrgGroupBatchId = @rOrgGroupBatchId
							AND FR.ReceiptDate >= @rReceiptDate	And FR.ReceiptDate <= @rToReceiptDate
							AND (FR.PayTypeId = @rPayTypeId OR @rPayTypeId = 0)
				group by 
				ReceiptDate,PM.Title,
				SLM.LedgerName,FR.PayTypeId,A.StudentId,
				FRD.ReceiptId,Isnull(FR.ChequeNo,''),ISNull(FR.BankName,''),
				--A.Name+', '+ClassName + '-' + DivisionName+', '+A.OrganizationName+', ('+BatchName+')',
				'Std-' + ClassName + ':' + DivisionName + ' RollNo :' + convert(nvarchar(20),RollNo) + ' ' + BatchName,
				FR.ReceiptAmount			
				Order By ReceiptDate desc
			END		
			
	ELSE IF @lTallyPostingType = 'FeeHeadAndReceiptBookWise' 
			BEGIN	
				SELECT	ReceiptDate,						
						ISNULL(FHM.Title,'') AS FeeName,
						PM.Title AS PayType,						
						Sum(FRD.Amount) AS Amount,
						Case when @rIsCustomNarration=1 then STUFF((SELECT distinct ','  +Replace(replace(
																					Replace(
																					replace(
																					Replace(
																					replace(
																					Replace(
																					replace(
																					Replace(
																					replace(
																					Replace(
																					replace(
																					Replace(
																					replace(
																					Replace(
																					replace(
																					replace(
																					@rCustomNarration,'[Class]',isnull(SM1.ClassName,'')
																					),'[Division]',Isnull(SM1.DivisionName,'')
																					),'[StudentsName]',isnull(SM1.Name,'')
																					), '[RollNumber]',isnull(convert(nvarchar(200),SM1.RollNo),'0')
																					),'[Batch]',isnull(SM1.BatchName,'')
																					), '[ReceiptNumber]', isnull(Convert(nvarchar(100),FR1.ReceiptNumber),'')
																					), '[ReceiptDate]',isnull(Convert(nvarchar(100),FR1.ReceiptDate),'')
																					), '[ReceiptAmount]',isnull(Convert(nvarchar(100),FR1.ReceiptAmount),'')
																					), '[ChequeNo]',isnull(Convert(nvarchar(100),FR1.ChequeNo),'')
																					),'[BankName]',isnull(FR1.BankName,'')
																					),'[FeeName]',isnull(FM1.Title,'')
																					), '[FeeAmount]',isnull(Convert(nvarchar(100),Sum(FRD.Amount)),'0.00')
																					),'[FeeHeadName]',ISNULL(FHM1.Title,'')
																					), '[FeeHeadAmount]',isnull(Convert(nvarchar(100),Sum(FRD.Amount)),'0.00')
																					), '[CollectionGroupName]',isNull(CGM1.Title,'')
																					),'[ReceiptFromNumber]',isnull(Convert(nvarchar(10),FR1.ReceiptNumber),'')
																					), '[ReceiptToNumber]',isnull(Convert(nvarchar(10),FR1.ReceiptNumber),''))
						from sFee.tReceipt FR1  INNER JOIN sFee.tReceiptDetail FRD1 ON FR1.Id = FRD1.ReceiptId
						INNER JOIN sFee.tFeeSetup FS1 ON FS1.Id = FRD1.FeeSetupId 
						INNER JOIN sStudent.vStudentAcademic SM1 ON SM1.ACademicId = FR1.SourceID AND SM1.OrgGRoupBatchId = FR1.OrgGRoupBatchId 						
						INNER JOIN sFee.tFeeMaster FM1 ON FM1.Id = FS1.FeeId --AND FRD.ReceiptId=FRD1.ReceiptId
						LEFT JOIN sFee.tCollectionGroupMaster CGM1 ON CGM1.Id = FS1.CollectionGroupId
						INNER JOIN sFinanceCommon.tPayTypeMaster PM1 ON PM1.Id = FR1.PayTypeId
						INNER JOIN sFee.tFeeHeadMaster FHM1 ON FHM1.Id = FM1.FeeHeadId 
						LEFT JOIN sTally.tStudentLedgerMapping SLM1 ON SLM1.StudentId = SM1.StudentId AND SLM1.ReceiptBookid = FR1.ReceiptBookId where  FR1.ReceiptDate=FR.ReceiptDate AND PM1.Title=PM.Title  AND FR1.PayTypeId=FR.PayTypeId AND FR1.IsObsolete = 0  FOR XML PATH('')),1,1,'') else
						case When FR.PayTypeId = 1 then
						'Receiptno-'  + CONVERT(nvarchar,isnull(FR.ReceiptNumber,'')) + 
						STUFF((SELECT ','  + convert(nvarchar(20),isnull(FM1.title,'')) 
						from sFee.tReceipt FR1  INNER JOIN sFee.tReceiptDetail FRD1 ON FR1.Id = FRD1.ReceiptId And FRD1.ReceiptId = FRD.ReceiptId 
						INNER JOIN sFee.tFeeSetup FS1 ON FS1.Id = FRD1.FeeSetupId 						
						INNER JOIN sFee.tFeeMaster FM1 ON FM1.Id = FS1.FeeId AND FRD.ReceiptId=FRD1.ReceiptId  FOR XML PATH('')),1,1,'') 
						when FR.PayTypeId <> 1 then 
						'Receiptno-'  +  CONVERT(nvarchar,isnull(FR.ReceiptNumber,'')) +
						STUFF((SELECT ','  + convert(nvarchar(20),isnull(FM1.title,'')) 
						from sFee.tReceipt FR1  INNER JOIN sFee.tReceiptDetail FRD1 ON FR1.Id = FRD1.ReceiptId And FRD1.ReceiptId = FRD.ReceiptId 
						INNER JOIN sFee.tFeeSetup FS1 ON FS1.Id = FRD1.FeeSetupId 						
						INNER JOIN sFee.tFeeMaster FM1 ON FM1.Id = FS1.FeeId AND FRD.ReceiptId=FRD1.ReceiptId  FOR XML PATH('')),1,1,'') 
						+ '  Cheque No. :' + ISNULL(FR.ChequeNo,'') + ' BankName :' + ISNULL(FR.BankName,'')  ENd
						end AS Narration,
						FR.PayTypeId AS PayTypeId,									
						FHM.Id AS FeeId,
						0 AS ReceiptId	
									 
				FROM sFee.tReceipt FR 
					INNER JOIN sFee.tReceiptDetail FRD ON FR.Id = FRD.ReceiptId
					INNER JOIN sFee.tFeeSetup FS ON FS.Id = FRD.FeeSetupId
					INNER JOIN sFee.tFeeMaster FM ON FM.Id = FS.FeeId
					INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id = FM.FeeHeadId
					INNER JOIN sFinanceCommon.tPayTypeMaster PM ON PM.Id = FR.PayTypeId
					WHERE							
							FR.ReceiptBookId = @rReceiptBookId 
							AND FR.IsObsolete = 0 
							AND FR.OrgGroupBatchId = @rOrgGroupBatchId
							AND FR.ReceiptDate >= @rReceiptDate	And FR.ReceiptDate <= @rToReceiptDate
							AND (FR.PayTypeId = @rPayTypeId OR @rPayTypeId = 0)
				group by PM.Title,FRD.ReceiptId,FR.BankName,FR.ChequeNo,FM.Title,
				ReceiptDate, FHM.Title,PM.Title,FHM.Id,
				FR.PayTypeId,FR.ReceiptNumber,FRD.ReceiptId,
				Isnull(FR.ChequeNo,''),ISNull(FR.BankName,''),FM.Title
				--,FHM.Title
				
				Order By ReceiptDate desc	
			END	
	ELSE IF @lTallyPostingType = 'FeeHeadWiseReceipt_AllDetail' 
        BEGIN
			   SELECT	ReceiptDate,
						FR.Id AS FeeName,
						PM.Title AS PayType,
						Sum(FRD.Amount) AS Amount,
						Case when @rIsCustomNarration=1 then  STUFF((SELECT  distinct ','  +Replace(replace(
																					Replace(
																					replace(
																					Replace(
																					replace(
																					Replace(
																					replace(
																					Replace(
																					replace(
																					Replace(
																					replace(
																					Replace(
																					replace(
																					Replace(
																					replace(
																					replace(
																					replace(
																					replace(
																					@rCustomNarration,'[Class]',isnull(SM1.ClassName,'')
																					),'[Division]',Isnull(SM1.DivisionName,'')
																					),'[StudentsName]',isnull(SM1.Name,'')
																					), '[RollNumber]',isnull(convert(nvarchar(200),SM1.RollNo),'0')
																					),'[Batch]',isnull(SM1.BatchName,'')
																					), '[ReceiptNumber]', isnull(Convert(nvarchar(100),FR1.ReceiptNumber),'')
																					), '[ReceiptDate]',isnull(Convert(nvarchar(100),FR1.ReceiptDate),'')
																					), '[ReceiptAmount]',isnull(Convert(nvarchar(100),FR1.ReceiptAmount),'')
																					),'Cheque No. :[ChequeNo]',case when FR1.PayTypeId = 1 then '' else 'Cheque No. :[ChequeNo]' end
																					), '[ChequeNo]',isnull(Convert(nvarchar(100),FR1.ChequeNo),'')
																					),'BankName :[BankName]',case when FR1.PayTypeId = 1 then '' else 'BankName :[BankName]' end
																					),'[BankName]',isnull(FR1.BankName,'')
																					),'[FeeName]',isnull(FM1.Title,'')
																					), '[FeeAmount]',isnull(Convert(nvarchar(100),Sum(FRD.Amount)),'0.00')
																					),'[FeeHeadName]',ISNULL(FHM1.Title,'')
																					), '[FeeHeadAmount]',isnull(Convert(nvarchar(100),Sum(FRD.Amount)),'0.00')
																					), '[CollectionGroupName]',isNull(CGM1.Title,'')
																					),'[ReceiptFromNumber]',isnull(Convert(nvarchar(10),(Select Min(ReceiptNumber) from sFee.tReceipt where   FR.ReceiptDate =ReceiptDate AND IsObsolete = 0)),'')
																					), '[ReceiptToNumber]',isnull(Convert(nvarchar(10),(Select Max(ReceiptNumber) from sFee.tReceipt Where FR.ReceiptDate = ReceiptDate AND IsObsolete = 0)),''))
						from sFee.tReceipt FR1  INNER JOIN sFee.tReceiptDetail FRD1 ON FR1.Id = FRD1.ReceiptId
						INNER JOIN sFee.tFeeSetup FS1 ON FS1.Id = FRD1.FeeSetupId 
						INNER JOIN sStudent.vStudentAcademic SM1 ON SM1.ACademicId = FR1.SourceID AND SM1.OrgGRoupBatchId = FR1.OrgGRoupBatchId 						
						INNER JOIN sFee.tFeeMaster FM1 ON FM1.Id = FS1.FeeId --AND FRD.ReceiptId=FRD1.ReceiptId
						LEFT JOIN sFee.tCollectionGroupMaster CGM1 ON CGM1.Id = FS1.CollectionGroupId
						INNER JOIN sFee.tFeeHeadMaster FHM1 ON FHM1.Id = FM1.FeeHeadId  where   FR.ReceiptDate=FR1.ReceiptDate AND FR.Id=FR1.Id AND FR1.IsObsolete = 0  FOR XML PATH('')),1,1,'') else
						case When FR.PayTypeId = 1 then
						'ReceiptNo-'  + CONVERT(nvarchar,isnull(FR.ReceiptNumber,'')) + '('+BatchName+')'
						when FR.PayTypeId <> 1 then 
						'Receiptno-'  +  CONVERT(nvarchar,isnull(FR.ReceiptNumber,'')) + '('+BatchName+')'
						+ '  Cheque No. :' + ISNULL(FR.ChequeNo,'') + ' BankName :' + ISNULL(FR.BankName,'')  ENd 
						END as Narration,						
						FR.PayTypeId AS PayTypeId, 
						FR.Id  AS FeeId,
						FR.Id AS ReceiptId
				FROM sFee.tReceipt FR 
					INNER JOIN sFee.tReceiptDetail FRD ON FR.Id = FRD.ReceiptId
					INNER JOIN sStudent.vStudentAcademic SM ON SM.ACademicId = FR.SourceID AND SM.OrgGRoupBatchId = FR.OrgGRoupBatchId 
					INNER JOIN sFee.tFeeSetup FS ON FS.Id = FRD.FeeSetupId
					INNER JOIN sFee.tFeeMaster FM ON FM.Id = FS.FeeId
					INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id = FM.FeeHeadId
					INNER JOIN sFinanceCommon.tPayTypeMaster PM ON PM.Id = FR.PayTypeId
					INNER JOIN sSetup.tOrganizationMaster OM ON  OM.Id=SM.OrgId
					LEFT JOIN sSetup.tOrgSubGroupMaster OSM ON OSM.id=OM.OrgSubGroupId

					WHERE	FR.ReceiptBookId= @rReceiptBookId 
							AND FR.IsObsolete = 0 
							AND FR.OrgGroupBatchId = @rOrgGroupBatchId
							AND FR.ReceiptDate >= @rReceiptDate AND FR.ReceiptDate <= @rToReceiptDate
							AND (FR.PayTypeId = @rPayTypeId OR @rPayTypeId = 0)
				group by ReceiptDate,PM.Title,FR.PayTypeId,FR.Id,isnull(FR.ReceiptNumber,'') , BatchName,ISNULL(FR.BankName,''),ISNULL(FR.ChequeNo,'')
				Order By FR.Id,ReceiptDate Desc
			END			
			
END
GO
PRINT N'Altering Procedure [sTally].[pReceiptTallyPostingAdd]...';


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

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

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

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


GO
 
ALTER PROCEDURE [sTimetable].[pImportTimeTableSetup]
	 
	@rToTimeTableSchemaId int,
	@rFromTimeTableSchemaId int
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	
BEGIN

	 
	 -- Division Work Load  	   
	 IF NOT EXISTS(SELECT 1 FROM sTimetable.tDivisionWorkLoad WHERE TimeTableSchemaID=@rFromTimeTableSchemaId) 	--- Exists --> Not Exists Put By Dhruv For Issue No. 0011093
	 BEGIN   	    
	    SELECT -101 AS Result
	    RETURN;
	 END
	 
	 -- Teacher Work Load 
	 IF NOT EXISTS(SELECT 1 FROM sTimetable.tTeacherWorkLoad WHERE TimeTableSchemaID=@rFromTimeTableSchemaId) 	   
	 BEGIN
	    SELECT -102 AS Result
	    RETURN;
	 END
	 
	 -- Time Setup
	 IF NOT EXISTS(SELECT 1 FROM sTimetable.tTimeSetup WHERE TimeTableSchemaID=@rFromTimeTableSchemaId) 
	 BEGIN	   
	    SELECT -103 AS Result
	    RETURN;
	 END
	 -- Time Table
	 IF NOT EXISTS(SELECT 1 FROM sTimetable.tTimeTable WHERE TimeTableSchemaID=@rFromTimeTableSchemaId) 	
	 BEGIN   
	    SELECT -104 AS Result
	    RETURN;
	 END
	 
	BEGIN TRY	
	BEGIN TRANSACTION 

	DECLARE @lOrgGroupId int=0, @lOrgGroupBatchId int=0	
	SELECT @lOrgGroupBatchId=OrgGroupBatchId FROM sTimetable.tTimeTableSchema WHERE Id = @rToTimeTableSchemaId
	SELECT @lOrgGroupId=OrgGroupId FROM sSetup.tOrgGroupBatchMaster WHERE Id = @lOrgGroupBatchId

	-- Division Work Load
	DELETE FROM sTimetable.tDivisionWorkLoad where TimeTableSchemaId = @rToTimeTableSchemaId 
	INSERT INTO sTimetable.tDivisionWorkLoad
	(BatchId,DivisionId,SubjectId,NoOfLecture,CreatedUserId,CreatedDateTime,TimeTableSchemaId)
	SELECT [sTimeTable].[fNextBatchIdGet](BatchId,@lOrgGroupBatchId),DivisionId,SubjectId,NoOfLecture,CreatedUserId,[sCommon].[fGetDate](),@rToTimeTableSchemaId 
	FROM sTimetable.tDivisionWorkLoad 
	WHERE TimeTableSchemaId = @rFromTimeTableSchemaId
	
	
	-- Teacher Work Load	
	DELETE FROM sTimetable.tTeacherWorkLoad WHERE TimeTableSchemaId=@rToTimeTableSchemaId
	INSERT INTO sTimetable.tTeacherWorkLoad(BatchId,EmployeeId,DivisionId,SubjectId,NoOfLecture,CreatedUserId,CreatedDateTime,TimeTableSchemaId)
	SELECT [sTimeTable].[fNextBatchIdGet](BatchId,@lOrgGroupBatchId),EmployeeId,DivisionId,SubjectId,NoOfLecture,CreatedUserId,[sCommon].[fGetDate](),@rToTimeTableSchemaId 
	FROM sTimetable.tTeacherWorkLoad 
	WHERE TimeTableSchemaId = @rFromTimeTableSchemaId
	
	
	-- Time Setup
	DELETE FROM sTimetable.tTimeSetup WHERE TimeTableSchemaId = @rToTimeTableSchemaId
	
	INSERT INTO sTimetable.tTimeSetup
	(ClassId,DayId,NoOfPeriod,BatchId,TimeTableSchemaId)
	SELECT 
	ClassId,DayId,NoOfPeriod,ISNULL([sTimeTable].[fNextBatchIdGet](BatchId,@lOrgGroupBatchId),''),@rToTimeTableSchemaId 
	FROM sTimetable.tTimeSetup WHERE Timetableschemaid = @rFromTimeTableSchemaId
	
	
	CREATE TABLE #TempTimeTable
	(
		[AutoId] int identity,
		[Id] [int] NOT NULL,
		[TimeTableSchemaId] [int] NOT NULL,
		[EmployeeId] [bigint] NOT NULL,
		[DivisionId] [int] NOT NULL,
		[SubjectId] [int] NOT NULL,
		[DayId] [tinyint] NOT NULL,
		[LectureNumber] [tinyint] NOT NULL,
		[LockNo] [bigint] NULL,
		[LockColour] [varchar](50) NULL,
		[SchoolRoomId] [int] NULL,
		[IsBreak] [bit] NULL,
		[IsMergeDivision] [bit] NULL,
		[IsBreakBefore] [bit] NULL
	)
	
	INSERT INTO #TempTimeTable SELECT * FROM sTimetable.tTimeTable WHERE Timetableschemaid = @rFromTimeTableSchemaId
	
	DECLARE @lCount int
	SELECT @lCount = COUNT(Id) FROM #TempTimeTable
	
	DELETE TD FROM sTimetable.tTimeTable T 	INNER JOIN sTimetable.tTimeTableDetail TD ON T.Id = TD.TimeTableId WHERE T.TimeTableSchemaId = @rToTimeTableSchemaId
	DELETE FROM sTimetable.tTimeTable WHERE TimeTableSchemaId = @rToTimeTableSchemaId
	
	WHILE (@lCount > 0)
	BEGIN
		DECLARE @lNextNumber BIGINT
		EXECUTE sCommon.pTableRowIdGet @lOrgGroupId, 'sTimetable.tTimeTable', 0, 1, 1,@outNextNumber = @lNextNumber output 
		DECLARE @lTimeTableId int =0
		SELECT @lTimeTableId=Id FROM #TempTimeTable WHERE AutoId = @lCount
		
		-- Time Table
		INSERT INTO sTimetable.tTimeTable
		(Id,TimeTableSchemaId,EmployeeId,DivisionId,SubjectId,DayId,LectureNumber,LockNo,LockColour,SchoolRoomId,IsBreak,IsMergeDivision,IsBreakBefore)
		SELECT 
		@lNextNumber,@rToTimeTableSchemaId,EmployeeId,DivisionId,SubjectId,DayId,LectureNumber,LockNo,LockColour,SchoolRoomId,IsBreak,IsMergeDivision,IsBreakBefore
		FROM #TempTimeTable  WHERE AutoId = @lCount
	
		DECLARE @lTimeTableDetailId int
		SELECT @lTimeTableDetailId=TimetableId FROM sTimetable.tTimeTableDetail WHERE TimetableId=@lTimeTableId
		
		-- Time Table Detail
		IF(@lTimeTableDetailId IS NOT NULL)
		BEGIN
			INSERT INTO sTimetable.tTimeTableDetail
			(TimetableId,EmployeeId,SubjectId,SchoolRoomId)
			SELECT 
			@lNextNumber,EmployeeId,SubjectId,SchoolRoomId
			FROM sTimetable.tTimeTableDetail WHERE TimetableId = @lCount
		END
		
		SET @lCount = @lCount -1
	END

	--Add By Nimesh Mantis:0027685
	--Start
	DELETE FROM sTimetable.tTimeTableTime WHERE TimeTableSchemaId = @rToTimeTableSchemaId
	INSERT INTO sTimetable.tTimeTableTime ([TimeTableSchemaId],[DivisionId],[DayId],[LectureNumber],[FromTime] ,[ToTime],[IsBreak],[IsBreakBefore])
	SELECT @rToTimeTableSchemaId,[DivisionId],[DayId],[LectureNumber],[FromTime],[ToTime],[IsBreak],[IsBreakBefore] FROM [sTimetable].[tTimeTableTime] where  Timetableschemaid = @rFromTimeTableSchemaId
	--End
	SELECT 1 AS Result
	
	 COMMIT TRANSACTION
	 END TRY
	
	 BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	 END CATCH	
END
GO
PRINT N'Altering Procedure [sTool].[pDeleteStaticData]...';


GO
 
ALTER PROCEDURE [sTool].[pDeleteStaticData]
 
	 
AS
SET NOCOUNT ON
BEGIN 
 

DELETE FROM sAlert.tEventMaster
DELETE FROM sCommon.tAutoCompleteMaster
DELETE FROM sCommon.tCommonMaster
DELETE FROM sCommon.tDepends
DELETE FROM sCommon.tModuleMaster
DELETE FROM sCommon.tPrefixFunctionality
DELETE FROM sCommon.tRefferedTableForObsoleteCheck
DELETE FROM sCommon.tRefferedTableWithoutForeignKey
DELETE FROM sCommon.tReport
DELETE FROM sCommon.tReportFormatGroupMaster
DELETE FROM sCommon.tReportGroupMaster
DELETE FROM sCommon.tSourceScreenMaster
DELETE FROM sCommon.tSourceTypeMaster
DELETE FROM sCommon.tStatusMaster
DELETE FROM sCommon.tStatusTypeMaster
DELETE FROM sCommon.tTableRowIdMaster
DELETE FROM sCommon.tUpdateFieldMaster
DELETE FROM sCommon.tValidationType
DELETE FROM sConfig.tColorLegendMaster
DELETE FROM sConfig.tConfigurationMaster
DELETE FROM sConfig.tConfigurationValue
DELETE FROM sSecurity.tMenu
DELETE FROM sSecurity.tResourceTypeMaster
DELETE FROM sSecurity.tScreen
DELETE FROM sSecurity.tScreenGroupMaster
DELETE FROM sSecurity.tScreenTypeMaster
DELETE FROM sSecurity.tTask
DELETE FROM sSystem.tTable
DELETE FROM sTool.tObjects
DELETE FROM sCommon.tReportTypeMaster


DELETE FROM sSetup.tAffiliationClassGroup
DELETE FROM sSetup.tAffiliationTypeMaster
DELETE FROM sSetup.tAffiliationMaster	
DELETE FROM sSetup.tStreamMaster

-- temp insert
DELETE FROM sAttendance.tAttendanceForMaster
DELETE FROM sEExam.tEntryModeMaster
DELETE FROM sSetup.tTermScopeMaster	 
 
DELETE FROM sConfig.tConfigurationLevelMaster

DELETE FROM sAdmission.tInquiryModeMaster

DELETE FROM sFee.tFeeMainGroupMaster

DELETE FROM sPayroll.tPayElementDefault

DELETE FROM sSecurity.tScreenGroupMapping
DELETE FROM sAssessment.tCCEExamMaster
DELETE FROM sSetup.tTermPatternMaster


DELETE FROM sAdmission.tAdmissionStatusMaster
DELETE FROM sAssessment.tCCERptGroup
DELETE FROM sHrm.tEmployeeICardTemplate
DELETE FROM sSecurity.tDashletMaster
DELETE FROM sStudent.tICardTemplate
DELETE FROM sSystem.tCustomQuery

DELETE FROM sCommon.tRangeGroupMaster

DELETE FROM sHostel.tLogStatusMaster

DELETE FROM sSetup.tStudentNameFormatMaster

DELETE FROM sCommon.tMainCastCategoryMaster

DELETE FROM sOp.tFunctionalityMaster
DELETE FROM sOp.tPaymentGatewayMaster

DELETE FROM sOp.tPayTypeMaster
DELETE FROM sOp.tTransactionStatusMaster
--DELETE FROM sPayroll.tForm16B
DELETE FROM sStudent.tBatchStatusMaster
DELETE FROM [sFinanceCommon].[tPayTypeMaster]

DELETE FROM sAttendance.tAttendanceTagMaster
DELETE FROM sCommon.tLiveWithMaster
DELETE FROM sConfig.tDisplayFieldMaster

DELETE FROM sActivity.tEventMainTypeMaster
DELETE FROM sAlert.tOSType

DELETE FROM sCommon.tCalculationTypeMaster
DELETE FROM sFee.tApplayAsMaster
DELETE FROM sSecurity.tScreenDependency
DELETE FROM sStudent.tSUIdFieldMaster

DELETE FROM [sAlert].[tAlertModeMaster]
DELETE FROM sCommon.tReportRemarkGroupMaster
DELETE FROM sStudent.tEnrollmentStatusMaster
DELETE FROM [sSetup].[tClassGroupMaster]

DELETE FROM sCommon.tTemplateSourceMaster
DELETE FROM sErp.tCustomerStatusMaster
DELETE FROM sErp.tInstallationTypeMaster
DELETE FROM sRecruitment.tRecruitmentStatusMaster

DELETE FROM sAssessment.tStaticCCECSMaster
DELETE FROM sAssessment.tStaticCCECSGroupMaster

DELETE FROM siTax.tStaticIncomeTaxGroup
DELETE FROM siTax.tStaticIncomeTaxSubGroup

DELETE FROM sCommon.tImportFieldMaster
DELETE FROM sCRM.tHostingTypeMaster
DELETE FROM sHrm.tMainLeaveTypeMaster

DELETE FROM sAppraisal.tConductIndicatorMaster
DELETE FROM sHrm.tTravelPeriodMaster
DELETE FROM sLoan.tInsterestTypeMaster

DELETE FROM sAppraisal.tBHRatingStatus
DELETE FROM sAppraisal.tConductIndicatorMaster
DELETE FROM sAppraisal.tKPAMeasureMaster
DELETE FROM sAppraisal.tKPATypeMaster
DELETE FROM sAppraisal.tRatingStatus
DELETE FROM sCommon.tHeaderDisplayMaster
DELETE FROM sCommon.tModuleGroupMaster
DELETE FROM sHrm.tLeaveTransactionMaster
DELETE FROM sCommon.tCheckFrequencyMaster

DELETE FROM sErp.tLeadAffiliationMaster
DELETE FROM sErp.tLeadSourceMaster
DELETE FROM sErp.tLeadStatusMaster

DELETE FROM sSystem.tStaticVersion

DELETE FROM sCommunication.tFeedBackAnswerGroupMaster

DELETE FROM sCommon.tSubmitDocumentFunctionalityMaster
DELETE FROM sSetup.tMandatoryFeild
DELETE FROM sSetup.tMandatoryFeildFunctionalityMaster

DELETE FROM sSystem.tTimeZone
DELETE FROM sTool.tTestCaseTypeMaster

DELETE FROM sAlumni.tEmployeementType

DELETE FROM sErp.tCampusTypeMaster

DELETE FROM sAlert.tMailTypeMaster
DELETE FROM sAlert.tSMSVendorMaster
DELETE FROM sCommon.tWeekOffRules

DELETE FROM sSecurity.tScreenHelp
DELETE FROM sSystem.tSettingInfo

DELETE FROM sProcurement.tOtherLocationSourceTypeMaster

DELETE FROM sCommon.tFieldTypeMaster
DELETE FROM sErp.tLeadInfrastructureMaster

DELETE FROM sHostel.tHostelEventMainTypeMaster

DELETE FROM sCertificate.tCertificateTypeMaster	
DELETE FROM sWorkflow.tActionStatusMaster
DELETE FROM sWorkflow.tApprovingDepartmentMaster
DELETE FROM sWorkflow.tWorkflowFunctionalityMaster

DELETE FROM sAcademic.tHomeworkCheckStatusMaster
DELETE FROM sAssessment.tExamTypeMaster

DELETE FROM sErp.tMarketingActivityMaster
DELETE FROM sErp.tMarketingSubActivityMaster
DELETE FROM sSetup.tCommonOrgGroupBatchMaster
DELETE FROM sWorkflow.tWorkflowFunctionalityMaster

DELETE FROM sAudit.tOperationMaster

DELETE FROM sAdmission.tInquiryMainStatusMaster
DELETE FROM sCertificate.tPrintTemplateFunctionalityMaster
DELETE FROM sErp.tTripLogStatusMaster

DELETE FROM sErp.tFollowupTypeMaster
DELETE FROM sErp.tSupportCategoryMaster
DELETE FROM sErp.tSupportPriorityMaster
DELETE FROM sErp.tSupportTicketStatusMaster


DELETE FROM sErp.tPlugInMaster
DELETE FROM sErp.tTagMaster

DELETE FROM sErp.tIssueTypeMaster

DELETE FROM sErp.tScreenFunctionalityMaster

DELETE FROM sHrm.tChangeTypeMaster


DELETE FROM sCommon.tDataMaster
DELETE FROM sCommon.tDataTypeMaster

DELETE FROM siTax.tStaticIncomeTaxSubSubGroup

DELETE FROM sCommunication.tStudentDocumentTypeMaster

DELETE FROM sCommon.tUploadFunctionalityMaster
DELETE FROM sCommunication.tEmployeeDocumentTypeMaster

DELETE FROM sErp.tCustomerMessageTypeMaster

DELETE FROM sActivity.tActivityMainTypeMaster
DELETE FROM sSecurity.tTraceabilityMaster
DELETE FROM sSecurity.tTraceabilityTrack

DELETE FROM sSecurity.tScreenScopeDetails
DELETE FROM sBiometric.tEmployeeConfigurationMaster
DELETE FROM sSetup.tEmployeeNameFormatMaster
DELETE FROM sStudent.tOnlineRegistrationDisplayFieldMaster

DELETE FROM sSetup.tFormTypeMaster
DELETE FROM sSetup.tFormButtonMaster

DELETE FROM sSecurity.tSysSuperScreen
DELETE FROM sAppraisal.tKPAStatus
DELETE FROM sAttendance.tPeriodNoMaster

END
GO
PRINT N'Altering Procedure [sTool].[pUpgradeVersion]...';


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

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

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


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

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



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

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

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

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

-- update tablerowid master data from excel to table

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

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

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



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




exec [sTool].[pTableRowIdCurrentNumberSet] @rOrgGroupId

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


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

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


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


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

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

--static entry in tVisitorTypeMaster

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

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

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

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

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

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

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

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


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

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

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


			
			
END


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

END


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

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

END

UPDATE sSystem.tDatabaseInfo SET ApplicationId = 1

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

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

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

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

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

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

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

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

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

END
GO
PRINT N'Altering Procedure [sTransport].[pRptRoutewiseStudentListGet]...';


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

		UNION ALL 

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


GO
CREATE PROCEDURE [sActivity].[pEmployeeHealthCheckupEntryGet]
	            
           @rHealthCheckupId int,
           @rStatusId int=0,
           @rBatchId int,
           @rDepartmentId int          
	
WITH EXECUTE AS CALLER	
AS
SET NOCOUNT ON
BEGIN
	 BEGIN TRY 
	 BEGIN TRANSACTION	
	   
	SELECT      
		ISNULL([HealthCheckupId],0) AS HealthCheckupId
		,ISNULL([HeightInCm],0) AS HeightInCm 
		,ISNULL([WeightInKg],0) AS WeightInKg
		,ISNULL([Dental],'') AS Dental
		,ISNULL([Nails],'') AS Nails
		,ISNULL([Hair],'') AS Hair
		,ISNULL([Skin],'') AS Skin
		,ISNULL([Ear],'') AS Ear
		,ISNULL([Nose],'') AS Nose
		,ISNULL([Throat],'') AS Throat
		,ISNULL([Respiratory],'') AS Respiratory
		,ISNULL([Cardiovascular],'') AS Cardiovascular
		,ISNULL([Nervous],'') AS Nervous
		,ISNULL([Eye],'') AS Eye
		,ISNULL([Other],'') AS Other
		,ISNULL([ImportantFinding],'') AS ImportantFinding
		,ISNULL([Remarks],'') AS Remarks
		,ISNULL([FollowupDetail],'') AS FollowupDetail
		,ISNULL(HT.[StatusId],0) AS StatusId
		,EC.EmployeeId AS EmployeeId
		,EC.EmployeeName AS EmployeeName
		,EC.Code AS EmployeeCode
		,EC.DepartmentId
		,EC.DepartmentName AS DepartmentName
		,EC.MobileNumber As MobileNumber
		,ISNULL(HT.BloodGroupId,0)AS BloodGroupId
			  
	FROM	sHrm.vEmployeeCommunication EC
		LEFT JOIN [sActivity].[tHealthCheckupEmployee] HT ON EC.EmployeeId = HT.EmployeeId	
    	--INNER JOIN sCommon.tStatusMaster SMM ON SMM.Id = HT.StatusId	    		
  
	WHERE  (EC.StatusId = @rStatusId OR @rStatusId = 0)
		-- AND (HC.BatchId = @rBatchId OR @rBatchId = 0)
		 ANd (EC.DepartmentId = @rDepartmentId OR @rDepartmentId = 0)
			
	ORDER BY EC.Code ASC
      
	COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Creating Procedure [sActivity].[pEmployeeHealthTrackAdd]...';


GO

CREATE PROCEDURE [sActivity].[pEmployeeHealthTrackAdd]
			
			@rId bigint
           ,@rEmployeeId bigint
           ,@rHealthCheckupTypeId int
           ,@rCheckupFromDate date
           ,@rCheckupToDate date
           ,@rChiefComplain nvarchar(100)
           ,@rDiagnosis nvarchar(100)
           ,@rActionTaken nvarchar(100)
           ,@rRemark nvarchar(200)
           ,@rExaminedBy nvarchar(100)
           ,@rCreatedUserId bigint
           ,@rOrgId int
		   ,@rGatePassInTime datetime
		   ,@rGatePassOutTime datetime
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
  
	
	 BEGIN TRANSACTION	
	DECLARE @lNextNumber BIGINT 

	IF(@rId = 0)	
	BEGIN
		
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sActivity.tEmployeeHealthTrack', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	INSERT INTO [sActivity].[tEmployeeHealthTrack]
           (
            [Id]
           ,[EmployeeId]
           ,[HealthCheckupTypeId]
           ,[CheckupFromDate]
           ,[CheckupToDate]
           ,[ChiefComplain]
           ,[Diagnosis]
           ,[ActionTaken]
           ,[Remark]
           ,[ExaminedBy]
           ,[CreatedUserId]
           ,[CreatedDateTime]
           ,[UpdatedUserId]
           ,[UpdatedDateTime]
		   ,[InTime]
		   ,[OutTime]
           )
     VALUES
           (
            @lNextNumber
           ,@rEmployeeId
           ,@rHealthCheckupTypeId
           ,@rCheckupFromDate
           ,@rCheckupToDate
           ,@rChiefComplain
           ,@rDiagnosis
           ,@rActionTaken
           ,@rRemark
           ,@rExaminedBy
           ,@rCreatedUserId
           ,sCommon.fGetDate()
           ,@rCreatedUserId
           ,sCommon.fGetDate()
		   ,@rGatePassInTime
		   ,@rGatePassOutTime
           )
                                 
		   SELECT @lNextNumber AS Result	
	END	 

ELSE
	 BEGIN 
	      SET @lNextNumber = @rId
	     
	      UPDATE  [sActivity].[tEmployeeHealthTrack]
			   SET  
				   [HealthCheckupTypeId] = @rHealthCheckupTypeId 
				  ,[CheckupFromDate] = @rCheckupFromDate 
				  ,[CheckupToDate] = @rCheckupToDate 
				  ,[ChiefComplain] = @rChiefComplain 
				  ,[Diagnosis] = @rDiagnosis 
				  ,[ActionTaken] = @rActionTaken 
				  ,[Remark] = @rRemark 
				  ,[ExaminedBy] = @rExaminedBy			 
				  ,[UpdatedUserId] = @rCreatedUserId 
				  ,[UpdatedDateTime] = sCommon.fGetDate()
				  ,[InTime] = @rGatePassInTime
				  ,[OutTime] = @rGatePassOutTime
	   
	      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'Creating Procedure [sActivity].[pEmployeeHealthTrackGet]...';


GO
CREATE PROCEDURE [sActivity].[pEmployeeHealthTrackGet]
	 
		   @rBuilder1 nvarchar(max)='',
		   @rBuilder2 nvarchar(max)='',     
           @rId bigint,
           @rEmployeeId bigint,
           @rHealthCheckUpTypeId int,
           @rCheckupFromDate date,
           @rCheckupToDate date,
           @rBatchId int,
		   @rDepartmentId int=0 
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	 BEGIN TRY 
	 BEGIN TRANSACTION	
	   
   SELECT 
   
           @rBuilder1 AS Builder1,
		   @rBuilder2 AS Builder2,
		   HT.[Id]
		  ,HT.EmployeeId
		  ,[HealthCheckupTypeId]
		  ,[CheckupFromDate]
		  ,[CheckupToDate]
		  ,[ChiefComplain]
		  ,[Diagnosis]
		  ,[ActionTaken]
		  ,[Remark]
		  ,[ExaminedBy]
		  ,EC.Code AS EmployeeCode
		  ,EC.EmployeeName AS EmployeeName
		  ,EC.DepartmentId
		  ,EC.DepartmentName
		  ,CTM.Title AS HealthCheckupType
		  ,ISNULL(HT.InTime,'') AS InTime
		  ,ISNULL(HT.OutTime,'') AS OutTime
       
	FROM  [sActivity].[tEmployeeHealthTrack]  HT 
		INNER JOIN sHrm.vEmployeeCommunication EC ON EC.EmployeeId = HT.EmployeeId	
		INNER JOIN sActivity.tHealthCheckUpTypeMaster CTM ON CTM.Id = HT.HealthCheckupTypeId
  
	WHERE   (HT.Id = @rId OR @rId = 0)	   	 	
		AND (HT.EmployeeId = @rEmployeeId OR @rEmployeeId =  0)
		AND (HealthCheckupTypeId = @rHealthCheckUpTypeId OR @rHealthCheckUpTypeId = 0)
		AND (CheckupFromDate >= @rCheckupFromDate OR ISNULL(@rCheckupFromDate,'') = '')
		AND (CheckupFromDate <= @rCheckupToDate OR ISNULL(@rCheckupToDate,'') = '')
		--AND BatchId = @rBatchId 
		AND (EC.DepartmentId=@rDepartmentId OR @rDepartmentId=0)
		
		order by HT.CheckupFromDate Asc
      
	COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Creating Procedure [sActivity].[pHealthCheckupEmployeeAdd]...';


GO

CREATE PROCEDURE [sActivity].[pHealthCheckupEmployeeAdd]
			
			@rHealthCheckupId int
           ,@rEmployeeId bigint
           ,@rHeightInCm decimal(6,2)
           ,@rWeightInKg decimal(6,2)
           ,@rDental nvarchar(150)
           ,@rNails nvarchar(150)
           ,@rHair nvarchar(150)
           ,@rSkin nvarchar(150)
           ,@rEar nvarchar(150)
           ,@rNose nvarchar(150)
           ,@rThroat nvarchar(150)
           ,@rRespiratory nvarchar(150)
           ,@rCardiovascular nvarchar(150)
           ,@rNervous nvarchar(150)
           ,@rEye nvarchar(150)
           ,@rOther nvarchar(150)
           ,@rImortantFinding nvarchar(150)
           ,@rRemark nvarchar(150)
           ,@rFollowupDetail nvarchar(150)
           ,@rStatusId smallint  
           ,@rOrgId int       
           ,@rBloodGroupId int

	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY 
	
	 BEGIN TRANSACTION	 
 
	IF NOT EXISTS (Select 1 FROM sActivity.tHealthCheckupEmployee Where HealthCheckupId = @rHealthCheckupId AND EmployeeId = @rEmployeeId)
	BEGIN
	INSERT INTO  sActivity.tHealthCheckupEmployee
           ([HealthCheckupId]
           ,[EmployeeId]
           ,[HeightInCm]
           ,[WeightInKg]
           ,[Dental]
           ,[Nails]
           ,[Hair]
           ,[Skin]
           ,[Ear]
           ,[Nose]
           ,[Throat]
           ,[Respiratory]
           ,[Cardiovascular]
           ,[Nervous]
           ,[Eye]
           ,[Other]
           ,[ImportantFinding]
           ,[Remarks]
           ,[FollowupDetail]
           ,[StatusId]
		   ,[BloodGroupId])
     VALUES
           (
            @rHealthCheckupId
           ,@rEmployeeId
           ,@rHeightInCm 
           ,@rWeightInKg 
           ,@rDental 
           ,@rNails 
           ,@rHair 
           ,@rSkin 
           ,@rEar 
           ,@rNose 
           ,@rThroat 
           ,@rRespiratory 
           ,@rCardiovascular 
           ,@rNervous 
           ,@rEye 
           ,@rOther 
           ,@rImortantFinding 
           ,@rRemark
           ,@rFollowupDetail 
           ,@rStatusId 
		   ,@rBloodGroupId
           )
                                 
		   SELECT @rHealthCheckupId AS Result	
		   --COMMIT TRANSACTION         
	END	 

ELSE
	 BEGIN  
	      UPDATE [sActivity].[tHealthCheckupEmployee]
			   SET [HealthCheckupId] = @rHealthCheckupId
				  ,[EmployeeId] = @rEmployeeId
				  ,[HeightInCm] = @rHeightInCm
				  ,[WeightInKg] = @rWeightInKg 
				  ,[Dental] = @rDental 
				  ,[Nails] = @rNails 
				  ,[Hair] = @rHair 
				  ,[Skin] = @rSkin 
				  ,[Ear] = @rEar 
				  ,[Nose] = @rNose 
				  ,[Throat] = @rThroat 
				  ,[Respiratory] = @rRespiratory  
				  ,[Cardiovascular] = @rCardiovascular 
				  ,[Nervous] = @rNervous 
				  ,[Eye] = @rEye 
				  ,[Other] = @rOther 
				  ,[ImportantFinding] = @rImortantFinding 
				  ,[Remarks] = @rRemark
				  ,[FollowupDetail] = @rFollowupDetail 
				  ,[StatusId] = @rStatusId 
				  ,[BloodGroupId] = @rBloodGroupId
				 Where HealthCheckupId = @rHealthCheckupId AND EmployeeId = @rEmployeeId
	      
	       SELECT @rHealthCheckupId AS Result      		  
	 END   

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


GO
CREATE PROCEDURE [sActivity].[pHealthCheckupEmployeeGet]
	        
	       @rBuilder1 nvarchar(max)='',
		   @rBuilder2 nvarchar(max)='',     
           @rEmployeeId bigint,
           @rHealthCheckupId int,
           @rStatusId int,
           @rBatchId int,
           @rFromDate date = null,
           @rToDate date = null,
           @rDepartmentId int          
	
WITH EXECUTE AS CALLER	
AS
SET NOCOUNT ON
BEGIN
	 BEGIN TRY 
	 BEGIN TRANSACTION	
	   
  SELECT      
			  @rBuilder1 AS Builder1
			  ,@rBuilder2 AS Builder2
			  ,[HealthCheckupId]     
	          ,HT.EmployeeId 
			  ,ISNULL([HeightInCm],0) AS HeightInCm 
			  ,ISNULL([WeightInKg],0) AS WeightInKg
			  ,[Dental]
			  ,[Nails]
			  ,[Hair]
			  ,[Skin]
			  ,[Ear]
			  ,[Nose]
			  ,[Throat]
			  ,[Respiratory]
			  ,[Cardiovascular]
			  ,[Nervous]
			  ,[Eye]
			  ,[Other]
			  ,[ImportantFinding]
			  ,[Remarks]
			  ,[FollowupDetail]
			  ,HT.[StatusId]	
			  ,EC.EmployeeId AS EmployeeId
			  ,EC.EmployeeName AS EmployeeName
			  ,EC.Code AS EmployeeCode
			  ,EC.DepartmentId
			  ,EC.DepartmentName AS DepartmentName
			  ,ISNULL(EPD.GenderId,0) AS GenderId
			  ,EC.MobileNumber As MobileNumber
			  ,BGM.Title AS BloodGroup
			  ,SMM.Title AS Status
			  ,HC.Title AS HealthCheckup
			  ,HC.DoctorName
			  ,HC.CheckupDate
			  ,ISNULL(HT.BloodGroupId,0)AS BloodGroupId
			  ,ISNULL(BGM.Title,'') AS BloodGroup
			  
  FROM		[sActivity].[tHealthCheckupEmployee] HT 
			INNER JOIN sHrm.vEmployeeCommunication EC ON EC.EmployeeId = HT.EmployeeId	
    		INNER JOIN sCommon.tStatusMaster SMM ON SMM.Id = HT.StatusId	
    		INNER JOIN sActivity.tHealthCheckup HC ON HC.Id = HT.HealthCheckupId  
    		LEFT JOIN [sHrm].[tEmployeePersonalDetail] EPD ON EPD.EmployeeId = EC.EmployeeId
    		LEFT JOIN sCommon.tBloodGroupMaster BGM ON EPD.BloodGroupId=BGM.Id
    		    		
  
  WHERE  (HT.HealthCheckupId = @rHealthCheckupId OR @rHealthCheckupId = 0)	
	     AND (HT.EmployeeId = @rEmployeeId OR @rEmployeeId =  0)
	     AND (HT.StatusId = @rStatusId OR @rStatusId = 0)
         AND (HC.CheckupDate >= @rFromDate OR ISNULL(@rFromDate,'') = '')
		 AND (HC.CheckupDate <= @rToDate OR ISNULL(@rToDate,'') = '')
		 AND (HC.BatchId = @rBatchId OR @rBatchId = 0)
		 ANd (EC.DepartmentId = @rDepartmentId OR @rDepartmentId = 0)
			
		ORDER BY CheckupDate ASC
      
	COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Creating Procedure [sActivity].[pHealthTrackEmployeeRemove]...';


GO

CREATE PROCEDURE [sActivity].[pHealthTrackEmployeeRemove]
	 
            @rEmployeeId bigint,
            @rHealthCheckUpId int
           
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	 BEGIN TRY 
	 BEGIN TRANSACTION	
	   
         DELETE FROM sActivity.tHealthCheckupEmployee Where HealthCheckupId = @rHealthCheckUpId AND EmployeeId = @rEmployeeId 
		
		SELECT 1 AS Result
	 
      
	COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Creating Procedure [sActivity].[pRptEventSchedule]...';


GO
CREATE PROCEDURE [sActivity].[pRptEventSchedule]

	--@rId int = 0,
	@rTitle nvarchar(100),
	@rFromDate date,
	@rToDate date,
	@rBatchId int,
	--@rIsSearch bit = 1,
	@rEventTypeId int = 0
	--,@rSourceId bigint = 0
	--,@rSourceTypeId smallint = 0
	,@rBuilder1 nvarchar(max) = ''
	,@rBuilder2 nvarchar(max) = ''

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON


BEGIN

	--IF @rIsSearch = 1
	--BEGIN
		SET @rTitle = sCommon.fSearchStringGet(@rTitle)
	--END

	--IF(@rSourceTypeId=2003)
	--BEGIN
	--	SELECT
	--		ES.Id as EventScheduleId,
	--		ES.Title,
	--		ES.FromDate,
	--		ES.ToDate,
	--		ES.Remark,
	--		ES.IsCommonForAll,
	--		ES.IsHoliday,
	--		ES.IsEnrollment,
	--		ISNULL(ES.EventTypeId,0) AS EventTypeId,
	--		ISNULL(EM.Title,'') AS EventType,
	--		EM.HighlightColor,
	--		EM.Title AS EventTypeName,
	--		OM.Id as OrgId,
	--		OM.WeekOffs,
	--		ES.BatchId
	--	FROM
	--		sActivity.tEventSchedule ES
	--		LEFT JOIN sActivity.tEventTypeMaster EM ON EM.Id = ES.EventTypeId
	--		INNER JOIN sSetup.tBatchMaster BM ON BM.Id = ES.BatchId
	--		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = BM.OrgId
	--	WHERE
	--		((ES.Id = @rId) OR (@rId = 0))
	--		AND ((ES.Id IN(SELECT EventScheduleId FROM sActivity.tEventAssign WHERE SourceTypeId=2005 AND
	--				SourceId=(SELECT DivisionId FROM sStudent.vStudentName WHERE StudentId=@rSourceId AND
	--					OrgId= CAST(LEFT(@rBatchId,4) AS int)  AND BatchId=@rBatchId))))
	--		AND ((ES.Title like @rTitle) OR (ISNULL(@rTitle,'') = ''))
	--		AND (((ES.FromDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
	--			AND ((ES.FromDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
	--			OR ((ES.ToDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
	--			AND ((ES.ToDate <= @rToDate) OR (ISNULL(@rToDate,'')='')))
	--		AND ES.BatchId=@rBatchId
	--		AND ((ES.EventTypeId = @rEventTypeId) OR (@rEventTypeId = 0))
	--	ORDER BY ES.FromDate DESC
	--END

	--ELSE IF(@rSourceTypeId=95)
	--BEGIN
	--	SELECT
	--		ES.Id as EventScheduleId,
	--		ES.Title,
	--		ES.FromDate,
	--		ES.ToDate,
	--		ES.Remark,
	--		ES.IsCommonForAll,
	--		ES.IsHoliday,
	--		ES.IsEnrollment,
	--		ISNULL(ES.EventTypeId,0) AS EventTypeId,
	--		ISNULL(EM.Title,'') AS EventType,
	--		EM.HighlightColor,
	--		EM.Title AS EventTypeName,
	--		OM.Id as OrgId,
	--		OM.WeekOffs,
	--		ES.BatchId
	--	FROM
	--		sActivity.tEventSchedule ES
	--		LEFT JOIN sActivity.tEventTypeMaster EM ON EM.Id = ES.EventTypeId
	--		INNER JOIN sSetup.tBatchMaster BM ON BM.Id = ES.BatchId
	--		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = BM.OrgId
	--	WHERE
	--		((ES.Id = @rId) OR (@rId = 0))
	--		AND (ES.Id IN(SELECT EventScheduleId FROM sActivity.tEventAssign WHERE SourceTypeId IN(2004,95) AND
	--				((SourceId=(SELECT OrganizationDepartmentId FROM sHrm.vExtEmployeeJobDetail WHERE EmployeeId=@rSourceId)) OR (SourceId=@rSourceId))))
	--		AND ((ES.Title like @rTitle) OR (ISNULL(@rTitle,'') = ''))
	--		AND (((ES.FromDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
	--			AND ((ES.FromDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
	--			OR ((ES.ToDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
	--			AND ((ES.ToDate <= @rToDate) OR (ISNULL(@rToDate,'')='')))
	--		AND ES.BatchId=@rBatchId
	--		AND (( ES.EventTypeId = @rEventTypeId) OR (@rEventTypeId = 0))
	--	ORDER BY ES.FromDate DESC
	--END

	--ELSE
	--BEGIN
		SELECT
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			ES.Id as EventScheduleId,
			ES.Title,
			ES.FromDate,
			ES.ToDate,
			ES.Remark,
			ES.IsCommonForAll,
			ES.IsHoliday,
			ES.IsEnrollment,
			ISNULL(ES.EventTypeId,0) AS EventTypeId,
			ISNULL(EM.Title,'') AS EventType,
			EM.HighlightColor,
			EM.Title AS EventTypeName,
			OM.Id as OrgId,
			OM.WeekOffs,
			ES.BatchId
		FROM
			sActivity.tEventSchedule ES
			LEFT JOIN sActivity.tEventTypeMaster EM ON EM.Id = ES.EventTypeId
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = ES.BatchId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = BM.OrgId
		WHERE
			--((ES.Id = @rId) OR (@rId = 0)) AND 
			((ES.Title like @rTitle) OR (ISNULL(@rTitle,'') = ''))
			AND ((ES.FromDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
			AND ((ES.FromDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
			AND ES.BatchId=@rBatchId
			AND (( ES.EventTypeId = @rEventTypeId) OR (@rEventTypeId = 0))
		ORDER BY ES.FromDate DESC
	--END
END
GO
PRINT N'Creating Procedure [sActivity].[pRptPTMStudentAttendentListGet]...';


GO
CREATE PROCEDURE [sActivity].[pRptPTMStudentAttendentListGet]

		   	
	       @rBuilder1 nvarchar(max)='',
	       @rBuilder2 nvarchar(max)='', 	
           @rClassId int,
           @rDivisionId int,
           @rOrgId int,
           @rStatusId int,
           @rOrgGroupId int=0
          
AS
SET NOCOUNT ON

BEGIN

SELECT
				@rBuilder1 AS Builder1,
				@rBuilder2 AS Builder2,	
			    2003 AS SourceType,
				vSA.AcademicId AS SourceId,
				vSA.Code,
				vSA.RollNo AS Number,
				vSA.Name AS Name,
				vSA.ClassId,
				vSA.DivisionId,
				vSA.DivisionOrder,
				vSA.ClassName AS ClassName,
				OM.Id AS OrgId,
				OM.DisplayTitle AS OrgName,
				vSA.StudentId,
				CM.DisplayTitle + '-' + DM.DisplayTitle AS ClassDivision, 
				Case When ISNULL(EAT.IsSelfPresent,0)=1 OR ISNULL(EAT.IsFatherPresent,0)=1 OR ISNULL(EAT.IsMotherPresent,0)=1 OR ISNULL(EAT.IsGuardianPresent,0)=1 
				then 1 Else 0 end AS IsPresent,
				ISNULL(EAT.IsSelfPresent,0) AS IsSelfPresent,
				ISNULL(EAT.IsFatherPresent,0) AS IsFatherPresent,
				ISNULL(EAT.IsMotherPresent,0) AS IsMotherPresent,
				ISNULL(EAT.IsGuardianPresent,0) AS IsGuardianPresent,
				ES.Title AS EventName,
				ES.Id as EventId
			FROM 
				sStudent.vStudentAcademic vSA
				INNER JOIN sSetup.tClassMaster CM ON CM.Id = vSA.ClassId
				INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = vSA.DivisionId
				INNER JOIN sActivity.tEventAssign EA ON EA.SourceId=vSA.DivisionId AND EA.SourceTypeId=2005 
				--AND EA.EventScheduleId=@rEventScheduleId
				INNER JOIN sActivity.tEventAttendance EAT ON EAT.EventScheduleId = EA.EventScheduleId 
				AND EAT.SourceId = vSA.AcademicId AND EAT.SourceTypeId = 2001
				INNER JOIN sActivity.tEventSchedule ES ON ES.Id = EAT.EventScheduleId
				INNER JOiN [sActivity].[tEventTypeMaster] ETM ON ES.EventTypeId=ETM.Id 
				inner Join [sActivity].[tEventMainTypeMaster]  EMTM ON ETM.EventMainTypeId=EMTM.Id AND EMTM.id=3
				INNER JOIN sSetup.tOrganizationMaster OM ON vSA.OrgId = OM.Id
				INNER JOIN sSetup.tOrgGroupMaster OGM ON OM.OrgGroupId = OGM.Id

			WHERE
				(vSA.ClassId=@rClassId OR @rClassId=0)
				AND (vSA.DivisionId=@rDivisionId OR @rDivisionId=0)
				AND (vSA.StatusId=@rStatusId OR @rStatusId=0)
				AND (vSA.OrgId=@rOrgId OR @rOrgId=0)
				AND (vSA.IsActiveBatch=1)
				AND (OGM.Id = @rOrgGroupId OR @rOrgGroupId = 0)	
			--ORDER BY vSA.RollNo	
		
		
End
GO
PRINT N'Creating Procedure [sActivity].[pXMLModifyHealthCheckupEmployee]...';


GO

CREATE PROCEDURE [sActivity].[pXMLModifyHealthCheckupEmployee]
	
	@rXmlString [nvarchar](max),
	@rHealthCheckupId int
 
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

		DECLARE @loDoc INT
		EXEC sp_xml_preparedocument @loDoc OUTPUT, @rXmlString
		BEGIN
			UPDATE       HC  		  
			SET          HC.HeightInCm = E.HeightInCm,
			             HC.Dental	    =  E.Dental,
						 HC.Nails	    =  E.Nails,
						 HC.Hair	    =  E.Hair,
						 HC.Skin	    =  E.Skin,
						 HC.Ear	    =  E.Ear,
						 HC.Nose	    =  E.Nose,
						 HC.Throat	    =  E.Throat,
						 HC.Respiratory	    =  E.Respiratory,
						 HC.Cardiovascular	    =  E.Cardiovascular,
						 HC.Nervous	    =  E.Nervous,
						 HC.Eye	    =  E.Eye,
						 HC.Other	    =  E.Other,
						 HC.ImportantFinding	    =  E.ImportantFinding,
						 HC.Remarks	    =  E.Remarks,
						 HC.FollowupDetail	    =  E.FollowupDetail,
						 hc.WeightInKg = E.WeightInKg,
						 Hc.StatusId = E.StatusId,
						 Hc.BloodGroupId=E.BloodGroupId
						 	
			   			
			FROM sActivity.tHealthCheckupEmployee HC				 
			 INNER JOIN					
			    (
					SELECT EmployeeId AS EmployeeId,HealthCheckupId AS HealthCheckupId,HeightInCm AS HeightInCm,WeightInKg AS WeightInKg,
					Dental AS Dental,Nails AS Nails,Hair AS Hair,Skin AS Skin,
					Ear AS Ear,Nose AS Nose,Throat AS Throat,Respiratory AS Respiratory,Cardiovascular AS Cardiovascular
				   ,Nervous AS Nervous,Eye AS Eye,Other AS Other,ImportantFinding AS ImportantFinding,Remarks AS Remarks,
					FollowupDetail AS FollowupDetail,StatusId AS StatusId,BloodGroupId AS BloodGroupId
					FROM
					OPENXML (@loDoc, '/Table/HealthCheckupEmployee', 1)
					WITH    (
							      EmployeeId bigint, 
							      HealthCheckupId int,
							      HeightInCm decimal(6,2)
							     ,WeightInKg decimal(6,2)
							     ,Dental	nvarchar(150)
								 ,Nails	nvarchar(150)
								 ,Hair	nvarchar(150)
								 ,Skin	nvarchar(150)
								 ,Ear	nvarchar(150)
								 ,Nose	nvarchar(150)
								 ,Throat	nvarchar(150)
								 ,Respiratory	nvarchar(150)
								 ,Cardiovascular	nvarchar(150)
								 ,Nervous	nvarchar(150)
								 ,Eye	nvarchar(150)
								 ,Other	nvarchar(150)
								 ,ImportantFinding	nvarchar(150)
								 ,Remarks	nvarchar(150)
								 ,FollowupDetail	nvarchar(150)
								 ,StatusId	int
								 ,BloodGroupId tinyint
			                 )
			          )E ON E.EmployeeId = HC.EmployeeId AND E.HealthCheckupId = HC.HealthCheckupId
				
				Where E.EmployeeId = HC.EmployeeId AND E.HealthCheckupId = HC.HealthCheckupId
	 
	 
	 
	INSERT INTO [sActivity].[tHealthCheckupEmployee]
           (
            [HealthCheckupId]
           ,[EmployeeId]
           ,[HeightInCm]
           ,[WeightInKg]
           ,[Dental]
           ,[Nails]
           ,[Hair]
           ,[Skin]
           ,[Ear]
           ,[Nose]
           ,[Throat]
           ,[Respiratory]
           ,[Cardiovascular]
           ,[Nervous]
           ,[Eye]
           ,[Other]
           ,[ImportantFinding]
           ,[Remarks]
           ,[FollowupDetail]
           ,[StatusId]
		   ,[BloodGroupId]
           )             
			SELECT 
			      HealthCheckupId			      			      
			     ,EmployeeId
			     ,HeightInCm
			     ,WeightInKg
			     ,Dental
			     ,Nails
			     ,Hair
			     ,Skin
			     ,Ear
			     ,Nose
			     ,Throat
			     ,Respiratory
			     ,Cardiovascular
				 ,Nervous
				 ,Eye
				 ,Other
				 ,ImportantFinding
				 ,Remarks				  
				 ,FollowupDetail
				 ,StatusId
				 ,BloodGroupId
					FROM
					OPENXML (@loDoc, '/Table/HealthCheckupEmployee', 1)
					WITH    (
							          HealthCheckupId int '@HealthCheckupId'
								     ,EmployeeId bigint  '@EmployeeId'
									 ,HeightInCm decimal(6,2) '@HeightInCm'
									 ,WeightInKg decimal(6,2) '@WeightInKg'
									 ,Dental	nvarchar(150) '@Dental'
									 ,Nails	nvarchar(150) '@Nails'
									 ,Hair	nvarchar(150) '@Hair'
									 ,Skin	nvarchar(150) '@Skin'
									 ,Ear	nvarchar(150) '@Ear'
									 ,Nose	nvarchar(150) '@Nose'
									 ,Throat	nvarchar(150) '@Throat'
									 ,Respiratory	nvarchar(150) '@Respiratory'
									 ,Cardiovascular	nvarchar(150) '@Cardiovascular'
									 ,Nervous	nvarchar(150) '@Nervous'
									 ,Eye	nvarchar(150) '@Eye'
									 ,Other	nvarchar(150) '@Other'
									 ,ImportantFinding	nvarchar(150) '@ImportantFinding'
									 ,Remarks	nvarchar(150) '@Remarks'
									 ,FollowupDetail	nvarchar(150) '@FollowupDetail'
									 ,StatusId int '@StatusId'
									 ,BloodGroupId tinyint '@BloodGroupId'
 
			                 )A
		       WHERE A.EmployeeId NOT IN (Select EmployeeId FROM sActivity.tHealthCheckupEmployee Where HealthCheckupId = @rHealthCheckupId)
 
	  			 
			 Select 1 As Result 
		END	
END
GO
PRINT N'Creating Procedure [sAdmission].[pRptAdmissionListUserWiseGet]...';


GO
CREATE PROCEDURE [sAdmission].[pRptAdmissionListUserWiseGet]
	
	
	 @rBatchId int,
	 @rClassId int,
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='',
	 @rFromDate date,
	 @rToDate date,
	 @rIsDetail bit =0,
	 @rCreatedUserName nvarchar(100)=''
AS
 SET NOCOUNT ON
			 

BEGIN 
	
	SET @rCreatedUserName = sCommon.fSearchStringGet(@rCreatedUserName)

	SELECT 
		 AF.FormNo,
		 AF.FirstName+' '+AF.MiddleName+' '+AF.LastName AS Name,
		 AF.ForClassId,
		 AF.BatchId,
		 AF.OrgId,
		 AF.City,
		 AF.FamilyCast,
		 CM.Title AS Class,
		 AF.FamilySubCast,
		 AF.CastCategoryId,
		 --for online and offline display same feename
		 AC.FormFeeName AS FeeName,
		 --in online entry display amount from pt  and in offline entry amount display from aff
		 CASE WHEN AF.DataEntryModeId = 561 THEN PT.PayAmount ELSE AFF.FeeAmount END  AS FeeAmount,
		 @rIsDetail AS IsDetail,
		 @rBuilder1 AS Builder1,
		 @rBuilder2 AS Builder2,
		 ISNULL(AF.CreatedDateTime,'') AS CreatedDateTime,
		 ISNULL(U.DisplayTitle,'') AS UserName
	 
	 FROM 
		sAdmission.tAdmissionForm AF	
		INNER JOIN sSetup.tClassMaster CM ON AF.ForClassId=CM.Id
		LEFT JOIN sAdmission.tAdmissionFormFee AFF ON AFF.AdmissionFormId = AF.Id
		LEFT JOIN sAdmission.tAdmissionCriteriaFee ACF ON ACF.Id = AFF.AdmissionCriteriaFeeId
		INNER JOIN sAdmission.tAdmissionCriteria AC ON AC.ClassId=CM.Id AND AC.BatchId = @rBatchId
		LEFT JOIN sOp.tPaymentTransaction PT ON AF.Id = PT.PayerSourceId AND PT.TransactionSourceTypeId = 2027 AND PT.TransactionStatusId IN (2,4)
		LEFT JOIN sSecurity.tUser U ON U.Id=AF.CreatedUserId
	WHERE 	
		AF.BatchId=@rBatchId
		--AND AF.OrgId=@rOrgId
		AND ((AF.ForClassId=@rClassId) OR (@rClassId=0))	
		AND ((CONVERT(DATE,AF.CreatedDateTime) >= @rFromDate) OR (isnull(@rFromDate,'')=''))
	    AND ((CONVERT(DATE,AF.CreatedDateTime) <= @rToDate) OR (isnull(@rToDate,'')=''))
		AND ((ISNULL(U.DisplayTitle,'') like @rCreatedUserName) OR (ISNULL(@rCreatedUserName,'')=''))
	    ORDER BY AF.FormNo
END
GO
PRINT N'Creating Procedure [sAssessment].[pRptGradeAnalysisMainCategoryWise]...';


GO
--created by megha for 0027269
CREATE PROCEDURE [sAssessment].[pRptGradeAnalysisMainCategoryWise]
	 
	 --@rAcademicId bigint=0,
	 @rClassId int=0,
	 @rDivisionId int=0,
	 @rBatchId int =0,
	 @rExamSubGroupId int=0,
	 @rBuilder1 nvarchar(max)='',
	 @rClass nvarchar(MAX)='',
	 @rStatusId int =0,
	 @rClassStatusId int=0
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	 
		
	
	select 
	@rBuilder1 AS Builder1,
 
	
		 count(R.id),
		GM.Title AS Gender,
		R.ResultGrade,
		--ISNULL(CCM.Title,'') AS CastCatagory,
		A.ClassId,
		A.DivisionId,
		CM.Title AS ClassName,
		DM.Title AS DivisionName,
		ISNULL(MCM.Title,'') As MainCastCategory
	 
		 
 from sAssessment.tResult  R
		INNER JOIN sAssessment.tExamMaster EM ON EM.Id=R.ExamId
		INNER JOIN sStudent.tAcademic A ON R.AcademicId = A.Id 
		Inner join sSetup.tClassMaster CM ON CM.Id=A.ClassId
		INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId
		INNER JOIN sStudent.tStudentMaster SM ON SM.Id = A.StudentId 
		INNER JOIN sStudent.tStudentOther SO ON SO.StudentId = A.StudentId 	
		INNER JOIN sCommon.tGenderMaster GM ON GM.Id=SO.GenderId
		LEFT  JOIN sCommon.tCastCategoryMaster CCM ON CCM.Id=SO.CastCategoryId
	    LEFT JOIN sCommon.tMainCastCategoryMaster MCM ON MCM.Id = CCM.MainCastCategoryId

		
	where (A.ClassId=@rClassId OR @rClassId=0)
		AND (A.DivisionID=@rDivisionId Or @rDivisionId=0)
		and A.BatchId=@rBatchId
		and EM.ExamSubGroupId=@rExamSubGroupId
		AND    (ISNULL(A.ClassId,0) IN( SELECT item FROM  sCommon.fnsplit(@rClass,','))OR @rClass='')
		and ((sm.StatusId=@rStatusId) or (@rStatusId=0))
		AND ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0))
		 Group by R.ResultGrade, GM.Title,MCM.Title,A.ClassId,A.DivisionId,CM.Title,DM.Title 
		 
END
GO
PRINT N'Creating Procedure [sAssessment].[pRptResultListCastCategorywiseRangeGet]...';


GO


CREATE PROCEDURE [sAssessment].[pRptResultListCastCategorywiseRangeGet]
	 
	@rBuilder1 nvarchar(max)='', 
	@rBuilder2 nvarchar(max)='', 
	@rBatchId int = 0,
	@rClassId int=0,
	@rDivisionId int=0,
	@rExamId int = 0,
	@rStatusId int=0,
	@rClassStatusId int=0,
	@rCasteCategoryIds nvarchar(max) = '',
	@rFilterId int=0,
	@rOrgGroupBatchId int=0
	 		 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN

SELECT 
	@rBuilder1 AS Builder1,
	@rBuilder2 AS Builder2,
	A.Id AS AcademicId,
	EM.Id AS ExamId,
	ESGM.Title AS ExamName,
	R.Percentage,
	StuO.GenderId,
	ISNULL(CCM.Id,0) AS CasteCategoryId,
	ISNULL(CCM.Title,'') AS CasteCategory

	FROM
	sAssessment.tResult R
	INNER JOIN sStudent.tAcademic A ON A.Id = R.AcademicId
	INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId	
	INNER JOIN sAssessment.tExamMaster EM ON EM.Id=R.ExamId
	INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId
	INNER JOIN sStudent.tStudentMaster StuM ON StuM.Id=A.StudentId
	LEFT JOIN sStudent.tStudentOther StuO ON StuO.StudentId = StuM.Id
	LEFT JOIN sCommon.tCastCategoryMaster CCM ON CCM.Id = StuO.CastCategoryId
	LEFT JOIN sHostel.tAssignRoom ARO ON  ARO.SourceId=StuM.Id AND ARO.SourceTypeId=2003 AND ((BM.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  AND ((ARO.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0) AND (BM.OrgGroupBatchId = ARO.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 

	WHERE
	EM.Id = @rExamId 
	AND (EM.BatchId = @rBatchId OR  @rBatchId = 0)
	AND (A.ClassId=@rClassId OR @rClassId=0) 
	AND (A.DivisionId=@rDivisionId OR @rDivisionId=0)
	AND (ISNULL(CCM.Id,0) IN(SELECT cast(item as int) FROM  sCommon.fnsplit(@rCasteCategoryIds,','))OR @rCasteCategoryIds='')
	AND ((StuM.StatusId=@rStatusId)OR(@rStatusId=0))
	AND ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0))
	AND (
			(@rFilterId = 0) -- All
			OR (@rFilterId = 2 AND isnull(ARO.SourceId,0)!=0) -- Hostel
			OR (@rFilterId = 3 AND isnull(RT.SourceId,0)!=0) -- Transport
			OR ((@rFilterId =1) AND ((isnull(ARO.SourceId,0)=0) AND (isnull(RT.SourceId,0)=0)))
			) 
END
GO
PRINT N'Creating Procedure [sAssessment].[pRptResultSheetStandardMultiExamWithAllTermGet]...';


GO

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

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

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

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

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

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

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

		Exam13Name nvarchar(150),	
		TotalMarks13 decimal(8,2),
		TotalObtain13 decimal(8,2),
		Percentage13 decimal(8,2),
		RankNumber13 int,
		ResultGrade13 NVarchar(50),
		Percentile13 decimal(8,2),
		ResultStatus13 Nvarchar(20),
		Exam13CombineExamName Nvarchar(150),
		
		ResultRemark1 nvarchar(200),
		ResultRemark2 nvarchar(200),
		
		TotalDays decimal(6,2),
		PresentDays decimal(6,2),
		StudentHeight decimal(6,2),
		StudentWeight decimal(6,2),
		ExamSeatNo nvarchar(20),
		ExamId int,
		
		ExamCode nvarchar(20),
		Exam1Code nvarchar(20),
		Exam2Code nvarchar(20),
		Exam3Code nvarchar(20),
		Exam4Code nvarchar(20),
		Exam5Code nvarchar(20),
		Exam6Code Nvarchar(20),
		Exam7Code Nvarchar(20),
		Exam8Code nvarchar(20),
		Exam9Code nvarchar(20),
		Exam10Code nvarchar(20),
		Exam11Code nvarchar(20),
		Exam12Code nvarchar(20),
		Exam13Code nvarchar(20),
		
		IsDisplayParentName bit,
		FatherName nvarchar(100),
		MotherName nvarchar(100),
		IsShowSubjectMark bit, 
		IsOptionalSubject bit,
		CoScholasticScopeId tinyint,
		IsDisplayPrincipalSign bit,
		IsDisplayTeacherSign bit,
		EmployeeSign varbinary(max),
		Batch nvarchar(100),
		ExamNameTerm1 NVarchar(100),
		ExamNameTerm2 NVarchar(100) ,
		ExamNameTerm3 NVarchar(100),
		ExamNameTerm4 NVarchar(100),
		ClassTeacherName Nvarchar(100),
		FirstName nvarchar(50),
		LastName nvarchar(50),
		IsDisplayMonthlyAttendance bit,
		MarksheetHeaderA4 varbinary(max),
		IsImageHeader bit,
		MyGoal nvarchar(200),
		AreaOfInterest nvarchar(200),
		Responsibility nvarchar(200),
		MyInterestHobby nvarchar(200),
		MyStrength nvarchar(200),
		Achievements nvarchar(1000),
		
		DentalHygiene nvarchar(200),
		VisionLeft nvarchar(50),
		VisionRight nvarchar(50), 
		IsDetail bit,
		SubjectGroupId int,
		SubjectGroupTitle nvarchar(50),
		SubjectGroupCode nvarchar(50),
		DecimalFormat nvarchar(10),
		SubjectRemark nvarchar(1000),
		GraceMark decimal(5,2),
		KrupaMark decimal(5,2),
		GradeStringHtml nvarchar(500),
		ResultRemark3 nvarchar(200),
		IsDisplayTotalMark bit,
		SubjectObtainTerm1 decimal(8,2),	
		SubjectObtainTerm2 decimal(8,2),
		SubjectObtainTerm3  decimal(8,2),
		SubjectObtainTerm4  decimal(8,2),
		SubjectMaxTerm1 decimal(8,2),
		SubjectMaxTerm2 decimal(8,2),
		SubjectMaxTerm3 decimal(8,2),
		SubjectMaxTerm4 decimal(8,2),
		ContactNo nvarchar(50),
		PresentAddress nvarchar(max),
		TeacherSignCaption nvarchar(100),
		PrincipalSignCaption nvarchar(100),
		ParentSignCaption nvarchar(100),
		ImprovementArea nvarchar(200),
		ProgressArea nvarchar(200),
		GeneralRemark nvarchar(1000),
		MyActivity nvarchar(200),
		ClassTeacherRemark nvarchar(1000),
		 
		HouseRemark nvarchar(1000),
		BloodGroup Nvarchar(100),
		TotalDays1 decimal(6,2),
		PresentDays1 decimal(6,2),
		TotalDays2 decimal(6,2),
		PresentDays2 decimal(6,2),
		TotalDays3 decimal(6,2),
		PresentDays3 decimal(6,2),
		TotalDays4 decimal(6,2),
		PresentDays4 decimal(6,2),
		TotalDays5 decimal(6,2),
		PresentDays5 decimal(6,2),
		TotalDays6 decimal(6,2),
		PresentDays6 decimal(6,2),
		TotalDays7 decimal(6,2),
		PresentDays7 decimal(6,2), 
		TotalDays8 decimal(6,2),
		PresentDays8 decimal(6,2),
		TotalDays9 decimal(6,2),
		PresentDays9 decimal(6,2),
		TotalDays10 decimal(6,2),
		PresentDays10 decimal(6,2),
		TotalDays11 decimal(6,2),
		PresentDays11 decimal(6,2),
		TotalDays12 decimal(6,2),
		PresentDays12 decimal(6,2),
		TotalDays13 decimal(6,2),
		PresentDays13 decimal(6,2),
		BatchIdText nvarchar(20),
		IsShowWithDetail bit,
		IsPresent bit,
		GradeTitle nvarchar(50),
		SubjectHighestDivisionGrade nvarchar(50),
		SubjectHighestDivisionMark decimal(5, 2),
		
		AchievementsTerm1 nvarchar(1000),
		AchievementsTerm2 nvarchar(1000),
		GeneralRemarkTerm1 nvarchar(200),
		GeneralRemarkTerm2 nvarchar(200),
		ResultRemark1Term1 nvarchar(200),
		ResultRemark2Term1 nvarchar(200),
		ResultRemark1Term2 nvarchar(200),
		ResultRemark2Term2 nvarchar(200),
		SR_HeightTerm1 decimal(5,2),
		SR_WeightTerm1 decimal(5,2),
		SR_HeightTerm2 decimal(5,2),
		SR_WeightTerm2 decimal(5,2),
		SR_PresentDaysTerm1 decimal(6,2),
		SR_PresentDaysTerm2 decimal(6,2),
		SR_TotalDaysTerm1 decimal(6,2),
		SR_TotalDaysTerm2 decimal(6,2),
		HouseId int,
		HouseName nvarchar(100),
		AdhaarNumber nvarchar(100),
		UIdNumber nvarchar(100),
		FatherContactNo nvarchar(50),
		MotherContactNo nvarchar(50),
		FatherMail nvarchar(max),
		MotherMail nvarchar(max),
		Gender nvarchar(100),
		CoordinatorEmployeeSign varbinary(max),
		StudentAddress nvarchar(max),
		SUId nvarchar(50),
		HighestDivisionMark decimal(5, 2),
		HighestDivisionGrade nvarchar(50),
		StreamTitle nvarchar(50),
		AdmissionNo nvarchar(50),
		AdmissionDate Date,
		MiddleName nvarchar(50) ,
		FatherOccupation nvarchar(50),
		ResultSheetAdditionalTitle nvarchar(100),
		IsDecimal bit,
		IsAbsentRemark bit,
		FinalAbsentRemark nvarchar(100),
		AbsentRemark1 nvarchar(100),
		AbsentRemark2 nvarchar(100),
		AbsentRemark3 nvarchar(100),
		AbsentRemark4 nvarchar(100),
		AbsentRemark5 nvarchar(100),
		AbsentRemark6 nvarchar(100),
		AbsentRemark7 nvarchar(100),
		AbsentRemark8 nvarchar(100),
		AbsentRemark9 nvarchar(100),
		AbsentRemark10 nvarchar(100),
		AbsentRemark11 nvarchar(100),
		AbsentRemark12 nvarchar(100),
		AbsentRemark13 nvarchar(100),
		ExamMaximumTerm1 decimal(6,2),
		ExamMaximumTerm2 decimal(6,2),
		ExamMaximumTerm3 decimal(6,2),
		ExamMaximumTerm4 decimal(6,2)

		)	
	 --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
	)
	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
				
FROM 
	sAssessment.tResultDetail RD
	INNER JOIN sAssessment.tResult R ON R.Id = RD.ResultId
	INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId AND R.ExamId = ED.ExamId
	INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId		
	INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
	INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=CS.SubjectId	
	LEFT JOIN sSetup.tSubjectGroupMaster SG ON SG.Id = Sm.SubjectGroupId				 
	INNER JOIN sStudent.tAcademic A ON A.Id=R.AcademicId
	INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=A.OrgId
	LEFT JOIN sSetup.tOrgImages OI ON OI.Orgid = OM.Id
	INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId
	INNER JOIN sStudent.tStudentMaster StuM ON StuM.Id=A.StudentId
	INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId
	INNER JOIN sSetup.tStreamMaster StM ON CM.StreamId = Stm.Id
	INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId
	LEFT JOIN sHrm.tEmployeeImages EI ON EI.EmployeeId = Dm.InchargeEmployeeId
	LEFT JOIN sHrm.tEmployeeMaster EMP ON EMP.Id = DM.InchargeEmployeeId AND  ISNULL(EMP.IsOtherUser,0) = 0
	INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id = EM.EXAMSUBGROUPID
	LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId=StuM.Id
	Left JOIN sActivity.tHouseMaster HM ON SO.HouseId = HM.Id
	LEFT JOIN sStudent.tAcademicDetail AD ON AD.AcademicId=A.Id
	LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId=StuM.Id
	LEFT JOIN sAssessment.tStudentRemark SR ON R.AcademicId = SR.AcademicId AND R.ExamId = SR.ExamId
	LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId = StuM.Id
	LEFT JOIN sAssessment.tOptionalSubject OS ON OS.AcademicId = R.AcademicId AND OS.ClassSubjectId = ED.ClassSubjectId  AND ED.ExamId = R.ExamId
	LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId=A.StudentId
	LEFT JOIN 	sCommon.tBloodGroupMaster BGM ON BGM.Id=So.BloodGroupId
	LEFT JOIN sAssessment.tGradeSetDetail GS ON GS.GradeSetId=ED.GradeSetId AND ED.GradeSetId = @GradeSetId and RD.SubjectGrade = GS.GradeCode
	LEFT JOIN sAssessment.tResultAnalysisDivisionDetail RAD ON RAD.ClassSubjectId = CS.Id AND RAD.DivisionId = A.DivisionId AND RAD.ExamId = Em.Id
	
	LEFT JOIN sHostel.tAssignRoom AR ON  AR.SourceId=StuM.Id AND AR.SourceTypeId=2003 AND ((BM.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  AND ((AR.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0) AND (BM.OrgGroupBatchId = AR.OrgGroupBatchId)) 
    LEFT JOIN
	(SELECT AT.SourceId,B.OrgGroupBatchId FROM sTransport.tAssignRoute AT 
    INNER JOIN sTransport.tBusRouteDestinationMaster BM ON BM.Id=AT.PickupDestinationId 
    INNER JOIN sTransport.tBusRouteMaster B ON B.Id=BM.BusRouteId AND  AT.SourceTypeId=2003 AND ((B.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))) RT
    ON RT.SourceId = StuM.Id 
	LEFT JOIN sHrm.tEmployeeImages EICoordinator ON EICoordinator.EmployeeId = EM.CoordinatorEmployeeId		  
	--LEFT JOIN sAcademic.tTeacherSubjectDivision TSD ON TSD.SubjectId=SM.Id AND TSD.DivisionId = A.DivisionId
	--LEFT JOIN sHrm.tEmployeeMaster EMP ON TSD.EmployeeId = EMP.Id
	LEFT JOIN sStudent.tStudentAdmission StuA ON StuM.Id = StuA.StudentId
	
	 WHERE
		R.ExamId = @rExamId 
		AND ((A.DivisionId =  @rDivisionId) OR (@rDivisionId=0))
		AND ((A.ClassId =  @rClassId) OR (@rClassId=0))		 
		AND ((A.BatchId =  @rBatchId) OR (@rBatchId=0))
		AND ((A.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
		AND ((A.RollNo <= @rToRollNo) OR (@rToRollNo=0))
		AND ((R.RankNumber >= @rFromRank) OR (@rFromRank=0))
		AND ((R.RankNumber <= @rToRank) OR (@rToRank=0))
		AND ((R.ResultGrade = @rGrade) OR (@rGrade=''))
		AND ((StuM.Code=@rCode) OR (@rCode=''))	
		AND ((R.Id = @rResultId) OR (@rResultId = 0))	
		AND ((StuM.StatusId=@rStatusId)OR(@rStatusId=0))
		AND((A.Id=@rAcademicId)OR (@rAcademicId=0))
		AND ((CS.SubjectId=@rSubjectId) OR(@rSubjectId=0) ) 
		AND ((R.TotalObtain>=@rFromObtain) OR (@rFromObtain=0))
		AND ((R.TotalObtain<=@rToObtain) OR (@rToObtain=0))
		AND ((R.Percentage>=@rFromPercentage) OR (@rFromPercentage=0))
		AND ((R.Percentage<=@rToPercentage) OR (@rToPercentage=0))
		
		 AND (
	 (@rFilterId = 0) -- All
     OR (@rFilterId = 2 AND isnull(AR.SourceId,0)!=0) -- Hostel
     OR (@rFilterId = 3 AND isnull(RT.SourceId,0)!=0) -- Transport
     OR ((@rFilterId =1) AND ((isnull(AR.SourceId,0)=0) AND (isnull(RT.SourceId,0)=0)))
    )
	AND ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0)) 
	AND (ISNULL(StuM.Code,0) IN( SELECT cast(item as nvarchar(20)) FROM  sCommon.fnsplit(@rMultiCode,',')) OR @rMultiCode='')
	    
	Order By ED.DisplayOrder

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

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

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

		--for 4 Term
		select @lSubExamId = SubExamId from sAssessment.tExamCombine  Where ExamId  = @rExamId AND ExamOrder = 4
		--select @ExamTitle = Title from sAssessment.tExamMaster Where Id = @lSubExamId	
		set @query ='update T set					 
					SubjectGradeTerm4=RD.SubjectGrade,
					SubjectObtainTerm4 = RD.Obtain,
					SubjectMaxTerm4= ED.Maximum
									 
					From
					sAssessment.tResultDetail RD
					INNER JOIN sAssessment.tResult R ON R.Id = RD.ResultId
					INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId AND R.ExamId = ED.ExamId
					INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
					LEFT JOIN sAssessment.tStudentRemark SR ON SR.AcademicId = R.AcademicId AND SR.ExamId = EM.Id
					INNER JOIN sAssessment.tExamSubgroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId					
					INNER JOIN 	#TempAllExam  T ON T.ClassSubjectID = ED.ClassSubjectId And T.AcademicId = R.AcademicId						
					WHERE EM.Id =' + convert(nvarchar(15), @lSubExamId)  
		execute(@query)
		
		
				set @query ='update T set
 
					TotalMarkTerm4 = R.TotalMarks,
					TotalObtainTerm4 =R.TotalObtain,
					PercentageTerm4 =R.Percentage,
					RankNumberTerm4 =R.RankNumber,
					ResultGradeTerm4 =R.ResultGrade,
					PercentileTerm4  = R.Percentile,
					ResultStatusTerm4  = R.ResultStatus,
					ExamNameTerm4 = ESGM.Code,
					ExamMaximumTerm4 = EM.ExamMaximum			
					 From						 
					   sAssessment.tResult R  				 
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id=R.ExamId
						INNER JOIN sAssessment.tExamSubgroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId					
						INNER JOIN 	#TempAllExam  T ON  T.AcademicId = R.AcademicId						
						WHERE EM.Id =' + convert(nvarchar(15), @lSubExamId)  
		execute(@query)
	END
	
	
	
	
	
	--WHILE (@lCount1 <= 6)
	--BEGIN
	--	set @query ='ALTER TABLE #TempAllExam DROP COLUMN MaximumMark' + convert(nvarchar(15),@lCount1)
	--	execute(@query)
	--	set @query ='ALTER TABLE #TempAllExam DROP COLUMN Exam' + convert(nvarchar(150),@lCount1)+ 'Name'
	--	execute(@query)
	--	set @query ='ALTER TABLE #TempAllExam DROP COLUMN SubjectGrade' + convert(nvarchar(150),@lCount1)
	--	execute(@query)		
	--	set @query ='ALTER TABLE #TempAllExam DROP COLUMN Obtain' + convert(nvarchar(15),@lCount1)
	--	execute(@query)
	--	set @query ='ALTER TABLE #TempAllExam DROP COLUMN ExamMaximum' + convert(nvarchar(15),@lCount1)
	--	execute(@query)
	--	SET @lCount1 = @lCount1 + 1
	--END
	
	SELECT @rBuilder1,@rBuilder2, T.*
	FROM #TempAllExam T
	
	--INNER JOIN SSETUP.TCLASSSUBJECT CS ON CS.ID = T.CLASSSUBJECTID
	--WHERE
	--	((T.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
	--	AND ((T.RollNo <= @rToRollNo) OR (@rToRollNo=0))
	--	AND ((T.RankNumber >= @rFromRank) OR (@rFromRank=0))
	--	AND ((T.RankNumber <= @rToRank) OR (@rToRank=0))
	--	AND ((T.ResultGrade = @rGrade) OR (@rGrade=''))
	--	AND ((T.StudCode=@rCode) OR (@rCode=''))		
		--order by T.RollNo,CS.ORDERINDEX
	--SELECT * FROM #TempAllExam	
	drop table #tempcombineExam
	Drop table #TempAllExam
	
	--Select
	--	'' As Builder1,
	--	'' As Builder2,
	--    '' As AcademicIdText,
	--	'' As ExamIdText,
	--	'' As CoScholasticScopeIdText ,
	--	'' As IsDisplayMonthlyAttendanceText,
	--    '' AS ClassIdText,
	--	0 As AcademicId,
	--	'' As ExamName,
	--	'' As StudCode,
	--	'' As StudentName ,
	--	0 As RollNo,
	--	'' As ResultStatus ,	
	--	'' As ClassName ,		
	--	'' As Division ,
	--	0 As TotalMark ,
	--	0 As TotalObtain,
	--	0 As Percentage ,
	--	0 As RankNumber ,
	--	'' As ResultGrade ,
 --       '' As IsMarksInDecimal,
 --             0 As column_visible,

 --             0 As Percentile ,

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

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

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

 --       '' AS ExamCode,

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

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

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

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

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

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


GO
CREATE PROCEDURE [sTimetable].[pApplyEmployee]
    @rTimeTableSchemaId INT,
	@rDivisionId1 INT,
	@rDivisionId2 INT,
	@rCreatedUserId BIGINT
	

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
--First sp
--BEGIN
--	DECLARE @lClassId1 INT,
--			@lClassId2 INT,
--			@lRowCount INT = 1,
--			@lTotalRows INT,
--			@lSubjectId INT,
--			@lNoOfLecture1 TINYINT,
--			@lNoOfLecture2 TINYINT,
--			@lNoOfLecture3 TINYINT,
--			@lLectureLength TINYINT,
--			@lBatchId INT,
--			@lEmployeeId BIGINT

--	SELECT @lClassId1=ClassId FROM sSetup.tDivisionMaster WHERE Id=@rDivisionId1
--	SELECT @lClassId2=ClassId FROM sSetup.tDivisionMaster WHERE Id=@rDivisionId2

--	CREATE TABLE #TempData
--	(
--		SubjectId INT
--	)

--	INSERT INTO #TempData (SubjectId)
--	SELECT CS2.SubjectId
--	FROM sSetup.tClassSubject CS1 
--		INNER JOIN sSetup.tClassSubject CS2 ON CS1.SubjectId = CS2.SubjectId
--		INNER JOIN sTimetable.tTeacherWorkLoad TWL1 ON TWL1.SubjectId=CS2.SubjectId
--	WHERE CS1.ClassId = @lClassId1 
--		AND CS2.ClassId = @lClassId2
--		AND TWL1.TimeTableSchemaId=@rTimeTableSchemaId
--		AND TWL1.DivisionId=@rDivisionId1

--	SELECT @lTotalRows = COUNT(*) FROM #TempData

--	WHILE @lRowCount <= @lTotalRows
--	BEGIN
--		-- Fetch data from the temporary table one by one
--		SELECT TOP 1 @lSubjectId = SubjectId
--		FROM #TempData
--		WHERE SubjectId IN (SELECT TOP (@lRowCount) SubjectId FROM #TempData ORDER BY SubjectId DESC) ORDER BY SubjectId;

--		--Check Lecture
--		SELECT @lNoOfLecture1=NoOfLecture FROM sTimetable.tDivisionWorkLoad WHERE TimeTableSchemaId=@rTimeTableSchemaId AND DivisionId=@rDivisionId1 AND SubjectId=@lSubjectId
--		SELECT @lNoOfLecture2=NoOfLecture FROM sTimetable.tDivisionWorkLoad WHERE TimeTableSchemaId=@rTimeTableSchemaId AND DivisionId=@rDivisionId2 AND SubjectId=@lSubjectId
--		SELECT @lNoOfLecture3=SUM(NoOfLecture) FROM sTimetable.tTeacherWorkLoad WHERE TimeTableSchemaId=@rTimeTableSchemaId AND DivisionId=@rDivisionId2 AND SubjectId=@lSubjectId GROUP BY SubjectId

--		IF(@lNoOfLecture1!=@lNoOfLecture2)
--		BEGIN
--			SELECT -101 AS Result
--		END

--		ELSE IF (@lNoOfLecture3>=@lNoOfLecture2)
--		BEGIN
--			SELECT -102 AS Result
--		END

--		ELSE
--		BEGIN
--			-- Fetch the corresponding data from sTimetable.tTeacherWorkLoad
--			SELECT TOP 1
--				@lBatchId = BatchId,
--				@lEmployeeId = EmployeeId,
--				@lLectureLength = LectureLength
--			FROM sTimetable.tTeacherWorkLoad
--			WHERE DivisionId = @rDivisionId1 
--				AND TimeTableSchemaId = @rTimeTableSchemaId
--				AND SubjectId = @lSubjectId;

--			-- Insert data one by one into the main table
--			INSERT INTO sTimetable.tTeacherWorkLoad 
--			(
--				BatchId,
--				EmployeeId,
--				DivisionId,
--				SubjectId,
--				NoOfLecture,
--				CreatedUserId,
--				CreatedDateTime,
--				TimeTableSchemaId,
--				LectureLength
--			)
--			VALUES 
--			(
--				@lBatchId,
--				@lEmployeeId,
--				@rDivisionId2,  -- Your DivisionId value
--				@lSubjectId, -- Value from the subquery
--				@lNoOfLecture2,
--				@rCreatedUserId,
--				[sCommon].[fGetDate](),
--				@rTimeTableSchemaId,
--				@lLectureLength
--			);
--			SELECT 1 AS Result
--		END

--		-- Increment the row count
--		SET @lRowCount = @lRowCount + 1;
--	END

--	-- Drop the temporary table
--	DROP TABLE #TempData;
--END

--Second sp
--BEGIN
--	DECLARE @lClassId1 INT,
--			@lClassId2 INT
--	SELECT @lClassId1=ClassId FROM sSetup.tDivisionMaster WHERE Id=@rDivisionId1
--	SELECT @lClassId2=ClassId FROM sSetup.tDivisionMaster WHERE Id=@rDivisionId2
--	INSERT INTO sTimetable.tTeacherWorkLoad 
--	(
--		BatchId,
--		EmployeeId,
--		DivisionId,
--		SubjectId,
--		NoOfLecture,
--		CreatedUserId,
--		CreatedDateTime,
--		TimeTableSchemaId,
--		LectureLength
--	)
--	SELECT	TWL1.BatchId , 
--			TWL1.EmployeeId, 
--			@rDivisionId2,
--			TWL1.SubjectId,
--			TWL1.NoOfLecture,
--			@rCreatedUserId,
--			[sCommon].[fGetDate](), 
--			TWL1.TimeTableSchemaId,
--			TWL1.LectureLength
--	FROM sSetup.tClassSubject CS1
--	--FROM sTimetable.tTeacherWorkLoad TWL1
--	INNER JOIN sSetup.tClassSubject CS2 ON CS1.SubjectId = CS2.SubjectId
--	INNER JOIN sTimetable.tTeacherWorkLoad TWL1 ON TWL1.SubjectId=CS2.SubjectId
--	WHERE CS1.ClassId = @lClassId1
--		AND CS2.ClassId = @lClassId2
--		AND TWL1.TimeTableSchemaId=@rTimeTableSchemaId
--		AND TWL1.DivisionId=@rDivisionId1

--SELECT 1 AS Result
--END


--Third sp
BEGIN
	if exists(select Employeeid from sTimetable.tTeacherWorkLoad  where DivisionId=@rDivisionId2 AND TimeTableSchemaId=@rTimeTableSchemaId)
	BEGIN
		Select -101 As Result
	END

	ELSE
	BEGIN
		DECLARE @lClassId1 INT,
				@lClassId2 INT
		SELECT @lClassId1=ClassId FROM sSetup.tDivisionMaster WHERE Id=@rDivisionId1
		SELECT @lClassId2=ClassId FROM sSetup.tDivisionMaster WHERE Id=@rDivisionId2

		INSERT INTO sTimetable.tTeacherWorkLoad
		(
			BatchId,
			EmployeeId,
			DivisionId,
			SubjectId,
			NoOfLecture,
			CreatedUserId,
			CreatedDateTime,
			TimeTableSchemaId,
			LectureLength
		)
		SELECT	TWL1.BatchId
				,TWL1.EmployeeId
				,@rDivisionId2
				,TWL1.SubjectId
				,TWL1.NoOfLecture
				,@rCreatedUserId
				,[sCommon].[fGetDate]()
				,@rTimeTableSchemaId
				,TWL1.LectureLength
		FROM sSetup.tClassSubject CS1 
			INNER JOIN sSetup.tClassSubject CS2 ON CS2.SubjectId = CS1.SubjectId
			INNER JOIN sTimetable.tTeacherWorkLoad TWL1 ON TWL1.SubjectId=CS2.SubjectId
			INNER JOIN sTimetable.tDivisionWorkLoad DWL1 ON DWL1.SubjectId=CS2.SubjectId AND DWL1.DivisionId=TWL1.DivisionId AND DWL1.TimeTableSchemaId=TWL1.TimeTableSchemaId
			INNER JOIN sTimetable.tDivisionWorkLoad DWL2 ON DWL2.SubjectId=CS2.SubjectId AND DWL2.DivisionId=@rDivisionId2 AND DWL2.NoOfLecture=DWL1.NoOfLecture AND DWL2.TimeTableSchemaId=TWL1.TimeTableSchemaId
		WHERE CS1.ClassId = @lClassId1 
			AND CS2.ClassId = @lClassId2
			AND TWL1.TimeTableSchemaId=@rTimeTableSchemaId
			AND TWL1.DivisionId=@rDivisionId1

		SELECT 1 AS Result
	END
END
GO





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



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




GO
CREATE SCHEMA [sEMeeting]
    AUTHORIZATION [dbo];


GO
PRINT N'Creating Schema [sPurchase]...';


GO
CREATE SCHEMA [sPurchase]
    AUTHORIZATION [DEVuser];


GO
PRINT N'Creating Schema [sWf]...';


GO
CREATE SCHEMA [sWf]
    AUTHORIZATION [DEVuser];


GO
PRINT N'Creating User-Defined Table Type [sEMeeting].[OnlineMeetingResourceDetailType]...';


GO
CREATE TYPE [sEMeeting].[OnlineMeetingResourceDetailType] AS TABLE (
    [AutoId]          BIGINT          NOT NULL,
    [OnlineMeetingId] BIGINT          NOT NULL,
    [ResourceTypeId]  SMALLINT        NOT NULL,
    [ResourcePath]    NVARCHAR (2000) NOT NULL,
    [IsObsolete]      BIT             NULL,
    [CreatedUserId]   BIGINT          NOT NULL,
    [CreatedDateTime] DATETIME        NOT NULL,
    [UpdatedUserId]   BIGINT          NULL,
    [UpdatedDateTime] DATETIME        NULL);


GO
PRINT N'Creating User-Defined Table Type [sEMeeting].[OnlineMeetingScopeDetailType]...';


GO
CREATE TYPE [sEMeeting].[OnlineMeetingScopeDetailType] AS TABLE (
    [AutoId]            BIGINT   NULL,
    [OnlineMeetingId]   BIGINT   NOT NULL,
    [ScopeSourceTypeId] SMALLINT NOT NULL,
    [ScopeSourceId]     BIGINT   NOT NULL,
    [IsObsolete]        BIT      NULL,
    [CreatedUserId]     BIGINT   NOT NULL,
    [CreatedDateTime]   DATETIME NOT NULL,
    [UpdatedUserId]     BIGINT   NULL,
    [UpdatedDateTime]   DATETIME NULL);


GO
PRINT N'Creating User-Defined Table Type [sEMeeting].[OnlineMeetingReferenceDetailType]...';


GO
CREATE TYPE [sEMeeting].[OnlineMeetingReferenceDetailType] AS TABLE (
    [AutoId]          BIGINT          NOT NULL,
    [OnlineMeetingId] BIGINT          NOT NULL,
    [ReferencePath]   NVARCHAR (1000) NOT NULL);


GO
PRINT N'Creating User-Defined Table Type [sPurchase].[PurchaseOrderDetailType]...';


GO
CREATE TYPE [sPurchase].[PurchaseOrderDetailType] AS TABLE (
    [Id]                      BIGINT          NOT NULL,
    [OrgGroupId]              SMALLINT        NOT NULL,
    [PurchaseOrderId]         BIGINT          NOT NULL,
    [PurchaseRequestDetailId] BIGINT          NOT NULL,
    [StockItemId]             BIGINT          NOT NULL,
    [TotalQty]                DECIMAL (12, 2) NOT NULL,
    [Remark]                  NVARCHAR (300)  NULL);


GO
PRINT N'Creating User-Defined Table Type [sPurchase].[PurchaseRequestDetailType]...';


GO
CREATE TYPE [sPurchase].[PurchaseRequestDetailType] AS TABLE (
    [Id]                BIGINT          NOT NULL,
    [OrgGroupId]        SMALLINT        NOT NULL,
    [PurchaseRequestId] BIGINT          NOT NULL,
    [StockItemId]       BIGINT          NOT NULL,
    [RequestedQty]      DECIMAL (12, 2) NOT NULL,
    [Remark]            NVARCHAR (300)  NULL);


GO
PRINT N'Creating User-Defined Table Type [sPurchase].[QualityCheckDetailType]...';


GO
CREATE TYPE [sPurchase].[QualityCheckDetailType] AS TABLE (
    [Id]                        BIGINT          NOT NULL,
    [OrgGroupId]                SMALLINT        NOT NULL,
    [QualityCheckId]            BIGINT          NOT NULL,
    [GoodsReceivedNoteDetailId] BIGINT          NOT NULL,
    [UnitTypeId]                BIGINT          NOT NULL,
    [CategoryId]                BIGINT          NOT NULL,
    [SubCategoryId]             BIGINT          NOT NULL,
    [StockItemId]               BIGINT          NOT NULL,
    [POQty]                     DECIMAL (12, 2) NOT NULL,
    [ReceivedQty]               DECIMAL (12, 2) NOT NULL,
    [AcceptedQty]               DECIMAL (12, 2) NOT NULL,
    [RejectedQty]               DECIMAL (12, 2) NOT NULL,
    [ReasonForRejection]        NVARCHAR (300)  NULL);


GO
PRINT N'Creating User-Defined Table Type [sPurchase].[SalesReturnDetailType]...';


GO
CREATE TYPE [sPurchase].[SalesReturnDetailType] AS TABLE (
    [Id]                        BIGINT          NOT NULL,
    [OrgGroupId]                SMALLINT        NOT NULL,
    [SalesReturnId]             BIGINT          NOT NULL,
    [GoodsReceivedNoteDetailId] BIGINT          NOT NULL,
    [UnitTypeId]                BIGINT          NOT NULL,
    [CategoryId]                BIGINT          NOT NULL,
    [SubCategoryId]             BIGINT          NOT NULL,
    [StockItemId]               BIGINT          NOT NULL,
    [POQty]                     DECIMAL (12, 2) NOT NULL,
    [ReceivedQty]               DECIMAL (12, 2) NOT NULL,
    [RejectedQty]               DECIMAL (12, 2) NOT NULL,
    [CreditNoteIssueDate]       DATETIME        NULL,
    [ReasonForRejection]        NVARCHAR (300)  NULL);


GO
PRINT N'Creating User-Defined Table Type [sPurchase].[QuotationRequestDetailType]...';


GO
CREATE TYPE [sPurchase].[QuotationRequestDetailType] AS TABLE (
    [Id]                      BIGINT          NOT NULL,
    [OrgGroupId]              SMALLINT        NOT NULL,
    [QuotationRequestId]      BIGINT          NOT NULL,
    [PurchaseRequestDetailId] BIGINT          NOT NULL,
    [StockItemId]             BIGINT          NOT NULL,
    [RequestedQty]            DECIMAL (12, 2) NOT NULL,
    [Remark]                  NVARCHAR (300)  NULL,
    [TargetPrice]             DECIMAL (12, 2) NOT NULL);


GO
PRINT N'Creating User-Defined Table Type [sPurchase].[InvoiceGenerateDetailType]...';


GO
CREATE TYPE [sPurchase].[InvoiceGenerateDetailType] AS TABLE (
    [Id]                        BIGINT          NOT NULL,
    [OrgGroupId]                SMALLINT        NOT NULL,
    [InvoiceGenerateId]         BIGINT          NOT NULL,
    [GoodsReceivedNoteDetailId] BIGINT          NOT NULL,
    [UnitTypeId]                BIGINT          NOT NULL,
    [CategoryId]                BIGINT          NOT NULL,
    [SubCategoryId]             BIGINT          NOT NULL,
    [StockItemId]               BIGINT          NOT NULL,
    [POQty]                     DECIMAL (12, 2) NOT NULL,
    [ReceivedQty]               DECIMAL (12, 2) NOT NULL,
    [AcceptedQty]               DECIMAL (12, 2) NOT NULL,
    [RejectedQty]               DECIMAL (12, 2) NOT NULL,
    [ReasonForRejection]        NVARCHAR (300)  NULL);


GO
PRINT N'Creating User-Defined Table Type [sPurchase].[GoodsReceivedNoteDetailType]...';


GO
CREATE TYPE [sPurchase].[GoodsReceivedNoteDetailType] AS TABLE (
    [Id]                      BIGINT          NOT NULL,
    [OrgGroupId]              SMALLINT        NOT NULL,
    [GoodsReceivedNoteId]     BIGINT          NOT NULL,
    [PurchaseRequestDetailId] BIGINT          NOT NULL,
    [UnitTypeId]              BIGINT          NOT NULL,
    [CategoryId]              BIGINT          NOT NULL,
    [SubCategoryId]           BIGINT          NOT NULL,
    [StockItemId]             BIGINT          NOT NULL,
    [POQty]                   DECIMAL (12, 2) NOT NULL,
    [ReceivedQty]             DECIMAL (12, 2) NOT NULL,
    [PreviousGRNQty]          DECIMAL (12, 2) NOT NULL,
    [UnitPrice]               DECIMAL (12, 2) NOT NULL,
    [Remark]                  NVARCHAR (300)  NULL);


GO
PRINT N'Starting rebuilding table [sAlert].[tAlertQueueLog]...';


GO
BEGIN TRANSACTION;

SET TRANSACTION ISOLATION LEVEL SERIALIZABLE;

SET XACT_ABORT ON;

CREATE TABLE [sAlert].[tmp_ms_xx_tAlertQueueLog] (
    [AutoId]          BIGINT         NOT NULL,
    [MessageDate]     DATETIME       NOT NULL,
    [QueueMessage]    NVARCHAR (MAX) NOT NULL,
    [EventId]         INT            NOT NULL,
    [AlertModeId]     TINYINT        NOT NULL,
    [OrgId]           SMALLINT       NOT NULL,
    [CreatedUserId]   BIGINT         NOT NULL,
    [CreatedDateTime] DATETIME       NOT NULL,
    CONSTRAINT [tmp_ms_xx_constraint_PK_tAlertQueueLog1] PRIMARY KEY CLUSTERED ([AutoId] ASC)
);

IF EXISTS (SELECT TOP 1 1 
           FROM   [sAlert].[tAlertQueueLog])
    BEGIN
        INSERT INTO [sAlert].[tmp_ms_xx_tAlertQueueLog] ([AutoId], [MessageDate], [QueueMessage], [EventId], [AlertModeId], [OrgId], [CreatedUserId], [CreatedDateTime])
        SELECT   [AutoId],
                 [MessageDate],
                 [QueueMessage],
                 [EventId],
                 [AlertModeId],
                 [OrgId],
                 [CreatedUserId],
                 [CreatedDateTime]
        FROM     [sAlert].[tAlertQueueLog]
        ORDER BY [AutoId] ASC;
    END

DROP TABLE [sAlert].[tAlertQueueLog];

EXECUTE sp_rename N'[sAlert].[tmp_ms_xx_tAlertQueueLog]', N'tAlertQueueLog';

EXECUTE sp_rename N'[sAlert].[tmp_ms_xx_constraint_PK_tAlertQueueLog1]', N'PK_tAlertQueueLog', N'OBJECT';

COMMIT TRANSACTION;

SET TRANSACTION ISOLATION LEVEL READ COMMITTED;


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


GO
ALTER TABLE [sStudent].[tStudentAdmission]
    ADD [PreviousLeftDate] DATE NULL;


GO
PRINT N'Creating Table [sEMeeting].[tOnlineMeetingAttendance]...';


GO
CREATE TABLE [sEMeeting].[tOnlineMeetingAttendance] (
    [AutoId]                  BIGINT   IDENTITY (1, 1) NOT NULL,
    [OnlineLearningId]        BIGINT   NOT NULL,
    [ParticipantSourceTypeId] SMALLINT NOT NULL,
    [ParticipantSourceId]     BIGINT   NOT NULL,
    [IsPresent]               BIT      NULL,
    [FirstInDateTime]         DATETIME NOT NULL,
    [LastOutDateTime]         DATETIME NULL,
    [IsLoggedIn]              BIT      NULL,
    CONSTRAINT [PK_tOnlineMeetingAttendance] PRIMARY KEY CLUSTERED ([AutoId] ASC)
);


GO
PRINT N'Creating Table [sEMeeting].[tOnlineMeetingReference]...';


GO
CREATE TABLE [sEMeeting].[tOnlineMeetingReference] (
    [AutoId]          BIGINT          IDENTITY (1, 1) NOT NULL,
    [OnlineMeetingId] BIGINT          NOT NULL,
    [ReferencePath]   NVARCHAR (1000) NOT NULL,
    CONSTRAINT [PK_tOnlineMeetingReference] PRIMARY KEY CLUSTERED ([AutoId] ASC)
);


GO
PRINT N'Creating Table [sEMeeting].[tOnlineMeetingSettings]...';


GO
CREATE TABLE [sEMeeting].[tOnlineMeetingSettings] (
    [OnlineMeetingId]            BIGINT         NOT NULL,
    [IsOnParticipantVideo]       BIT            NULL,
    [IsOnParticipantAudio]       BIT            NULL,
    [IsOnHostVideo]              BIT            NULL,
    [IsOnHostAudio]              BIT            NULL,
    [IsOnParticipantScreenShare] BIT            NULL,
    [IsOnHostscreenShare]        BIT            NULL,
    [AccountEmailId]             NVARCHAR (200) NULL,
    [AccountPassword]            NVARCHAR (200) NULL,
    [APIKey]                     NVARCHAR (100) NULL,
    [APISecret]                  NVARCHAR (100) NULL,
    [WebAPIKey]                  NVARCHAR (100) NULL,
    [WebAPISecret]               NVARCHAR (100) NULL,
    [MeetingProviderId]          SMALLINT       NULL,
    [JWTToken]                   NVARCHAR (MAX) NULL,
    [OAuthAccountId]             NVARCHAR (MAX) NULL,
    [OAuthClientId]              NVARCHAR (MAX) NULL,
    [OAuthClientSecret]          NVARCHAR (MAX) NULL,
    CONSTRAINT [PK_tOnlineMeetingSettings] PRIMARY KEY CLUSTERED ([OnlineMeetingId] ASC)
);


GO
PRINT N'Creating Table [sEMeeting].[tMeetingTypeMaster]...';


GO
CREATE TABLE [sEMeeting].[tMeetingTypeMaster] (
    [AutoId]          SMALLINT      IDENTITY (1, 1) NOT NULL,
    [OrgGroupId]      SMALLINT      NOT NULL,
    [Name]            NVARCHAR (50) NOT NULL,
    [IsObsolete]      BIT           NULL,
    [CreatedUserId]   BIGINT        NOT NULL,
    [CreatedDateTime] DATETIME      NOT NULL,
    [UpdatedUserId]   BIGINT        NULL,
    [UpdatedDateTime] DATETIME      NULL,
    CONSTRAINT [PK_tMeetingTypeMaster] PRIMARY KEY CLUSTERED ([AutoId] ASC)
);


GO
PRINT N'Creating Table [sEMeeting].[tOnlineMeeting]...';


GO
CREATE TABLE [sEMeeting].[tOnlineMeeting] (
    [Id]                 BIGINT          NOT NULL,
    [OrgGroupId]         SMALLINT        NOT NULL,
    [MeetingTypeId]      SMALLINT        NOT NULL,
    [StartDate]          DATE            NOT NULL,
    [StartTime]          TIME (7)        NOT NULL,
    [EndDate]            DATE            NOT NULL,
    [EndTime]            TIME (7)        NOT NULL,
    [HostEmployeeId]     BIGINT          NOT NULL,
    [Title]              NVARCHAR (200)  NULL,
    [Description]        NVARCHAR (1000) NULL,
    [IsDisplayMeetingId] BIT             NOT NULL,
    [MeetingId]          NVARCHAR (100)  NULL,
    [MeetingPassword]    NVARCHAR (100)  NULL,
    [IsReference]        BIT             NULL,
    [IsResource]         BIT             NULL,
    [IsCompleted]        SMALLINT        NULL,
    [IsMeetingStarted]   BIT             NULL,
    [MeetingAccountId]   INT             NULL,
    [IsMeetingCreated]   BIT             NULL,
    [IsObsolete]         BIT             NULL,
    [CreatedUserId]      BIGINT          NOT NULL,
    [CreatedDateTime]    DATETIME        NOT NULL,
    [UpdatedUserId]      BIGINT          NULL,
    [UpdatedDateTime]    DATETIME        NULL,
    CONSTRAINT [PK_tOnlineMeeting] PRIMARY KEY CLUSTERED ([Id] ASC)
);


GO
PRINT N'Creating Table [sEMeeting].[tOnlineMeetingScope]...';


GO
CREATE TABLE [sEMeeting].[tOnlineMeetingScope] (
    [AutoId]            BIGINT   IDENTITY (1, 1) NOT NULL,
    [OnlineMeetingId]   BIGINT   NOT NULL,
    [ScopeSourceTypeId] SMALLINT NOT NULL,
    [ScopeSourceId]     BIGINT   NOT NULL,
    [IsObsolete]        BIT      NULL,
    [CreatedUserId]     BIGINT   NOT NULL,
    [CreatedDateTime]   DATETIME NOT NULL,
    [UpdatedUserId]     BIGINT   NULL,
    [UpdatedDateTime]   DATETIME NULL,
    CONSTRAINT [PK_tOnlineMeetingScope] PRIMARY KEY CLUSTERED ([AutoId] ASC)
);


GO
PRINT N'Creating Table [sEMeeting].[tOnlineMeetingResource]...';


GO
CREATE TABLE [sEMeeting].[tOnlineMeetingResource] (
    [AutoId]          BIGINT          IDENTITY (1, 1) NOT NULL,
    [OnlineMeetingId] BIGINT          NOT NULL,
    [ResourceTypeId]  SMALLINT        NOT NULL,
    [ResourcePath]    NVARCHAR (2000) NOT NULL,
    [IsObsolete]      BIT             NULL,
    [CreatedUserId]   BIGINT          NOT NULL,
    [CreatedDateTime] DATETIME        NOT NULL,
    [UpdatedUserId]   BIGINT          NULL,
    [UpdatedDateTime] DATETIME        NULL,
    CONSTRAINT [PK_tOnlineMeetingResource] PRIMARY KEY CLUSTERED ([AutoId] ASC)
);


GO
PRINT N'Creating Table [sPurchase].[tQualityCheckDetail]...';


GO
CREATE TABLE [sPurchase].[tQualityCheckDetail] (
    [Id]                        BIGINT          NOT NULL,
    [OrgGroupId]                SMALLINT        NOT NULL,
    [QualityCheckId]            BIGINT          NOT NULL,
    [GoodsReceivedNoteDetailId] BIGINT          NULL,
    [UnitTypeId]                BIGINT          NOT NULL,
    [CategoryId]                BIGINT          NOT NULL,
    [SubCategoryId]             BIGINT          NULL,
    [StockItemId]               BIGINT          NOT NULL,
    [POQty]                     DECIMAL (12, 2) NOT NULL,
    [ReceivedQty]               DECIMAL (12, 2) NOT NULL,
    [AcceptedQty]               DECIMAL (12, 2) NOT NULL,
    [RejectedQty]               DECIMAL (12, 2) NULL,
    [ReasonForRejection]        NVARCHAR (300)  NULL,
    [CreatedUserId]             BIGINT          NULL,
    [CreatedDateTime]           DATETIME        NOT NULL,
    [UpdatedUserId]             BIGINT          NULL,
    [UpdatedDateTime]           DATETIME        NULL,
    CONSTRAINT [PK_sPurchase]].[tQualityCheckDetails] PRIMARY KEY CLUSTERED ([Id] ASC)
);


GO
PRINT N'Creating Table [sPurchase].[tGoodsReceivedNote]...';


GO
CREATE TABLE [sPurchase].[tGoodsReceivedNote] (
    [Id]                 BIGINT          NOT NULL,
    [OrgGroupId]         SMALLINT        NOT NULL,
    [LocationId]         INT             NOT NULL,
    [IsObsolete]         BIT             NULL,
    [PurchaseRequestId]  BIGINT          NOT NULL,
    [PurchaseOrderId]    BIGINT          NOT NULL,
    [DepartmentBranchId] INT             NOT NULL,
    [VendorId]           INT             NOT NULL,
    [RequestedBy]        NVARCHAR (100)  NOT NULL,
    [BillToAddress]      NVARCHAR (1000) NOT NULL,
    [GRNNumber]          NVARCHAR (20)   NOT NULL,
    [StatusId]           SMALLINT        NOT NULL,
    [PODueDate]          DATETIME        NOT NULL,
    [CreatedUserId]      BIGINT          NULL,
    [CreatedDateTime]    DATETIME        NOT NULL,
    [UpdatedUserId]      BIGINT          NULL,
    [UpdatedDateTime]    DATETIME        NULL,
    [DeletedDateTime]    DATETIME        NULL,
    CONSTRAINT [PK_sPurchase]].[tGoodsReceivedNote] PRIMARY KEY CLUSTERED ([Id] ASC)
);


GO
PRINT N'Creating Table [sPurchase].[tPurchaseOrder]...';


GO
CREATE TABLE [sPurchase].[tPurchaseOrder] (
    [Id]                BIGINT          NOT NULL,
    [OrgGroupId]        SMALLINT        NOT NULL,
    [LocationId]        INT             NOT NULL,
    [IsObsolete]        BIT             NULL,
    [PurchaseRequestId] BIGINT          NOT NULL,
    [RequestedBy]       NVARCHAR (100)  NOT NULL,
    [PODate]            DATETIME        NOT NULL,
    [RefNumber]         NVARCHAR (20)   NOT NULL,
    [StatusId]          SMALLINT        NOT NULL,
    [VendorId]          INT             NOT NULL,
    [BillToAddress]     NVARCHAR (1000) NOT NULL,
    [ShipToAddress]     NVARCHAR (1000) NOT NULL,
    [RequiredBy]        DATETIME        NOT NULL,
    [CreatedUserId]     BIGINT          NULL,
    [CreatedDateTime]   DATETIME        NOT NULL,
    [UpdatedUserId]     BIGINT          NULL,
    [UpdatedDateTime]   DATETIME        NULL,
    [DeletedDateTime]   DATETIME        NULL,
    CONSTRAINT [PK_sPurchase]].[tPurchaseOrder] PRIMARY KEY CLUSTERED ([Id] ASC)
);


GO
PRINT N'Creating Table [sPurchase].[tPurchaseRequest]...';


GO
CREATE TABLE [sPurchase].[tPurchaseRequest] (
    [Id]              BIGINT         NOT NULL,
    [OrgGroupId]      SMALLINT       NOT NULL,
    [BranchId]        INT            NULL,
    [LocationId]      INT            NOT NULL,
    [IsObsolete]      BIT            NULL,
    [Number]          NVARCHAR (20)  NOT NULL,
    [RequestDate]     DATETIME       NULL,
    [ResourceId]      BIGINT         NULL,
    [RequestedBy]     NVARCHAR (100) NOT NULL,
    [StatusId]        SMALLINT       NULL,
    [VendorId]        INT            NULL,
    [RequiredBy]      DATETIME       NULL,
    [CreatedUserId]   BIGINT         NULL,
    [CreatedDateTime] DATETIME       NOT NULL,
    [UpdatedUserId]   BIGINT         NULL,
    [UpdatedDateTime] DATETIME       NULL,
    [DeletedDateTime] DATETIME       NULL,
    CONSTRAINT [PK_sPurchase]].[tPurchaseRequest] PRIMARY KEY CLUSTERED ([Id] ASC)
);


GO
PRINT N'Creating Table [sPurchase].[tQuotationRequest]...';


GO
CREATE TABLE [sPurchase].[tQuotationRequest] (
    [Id]                BIGINT         NOT NULL,
    [OrgGroupId]        SMALLINT       NOT NULL,
    [BranchId]          INT            NULL,
    [LocationId]        INT            NOT NULL,
    [PurchaseRequestId] BIGINT         NOT NULL,
    [IsObsolete]        BIT            NULL,
    [Number]            NVARCHAR (20)  NOT NULL,
    [Name]              NVARCHAR (100) NULL,
    [RFQDate]           DATETIME       NOT NULL,
    [Description]       NVARCHAR (300) NULL,
    [StartDate]         DATETIME       NULL,
    [EndDate]           DATETIME       NULL,
    [BidOpen]           NVARCHAR (50)  NULL,
    [BidClose]          NVARCHAR (50)  NULL,
    [PersonContact]     BIGINT         NULL,
    [Email]             NVARCHAR (50)  NULL,
    [SendToVendor]      BIT            NULL,
    [StatusId]          SMALLINT       NOT NULL,
    [VendorId]          INT            NULL,
    [CreatedUserId]     BIGINT         NOT NULL,
    [CreatedDateTime]   DATETIME       NULL,
    [UpdatedUserId]     BIGINT         NULL,
    [UpdatedDateTime]   DATETIME       NULL,
    [DeletedDateTime]   DATETIME       NULL,
    CONSTRAINT [PK_sPurchase]].[tQuotationRequest] PRIMARY KEY CLUSTERED ([Id] ASC)
);


GO
PRINT N'Creating Table [sPurchase].[tQualityCheck]...';


GO
CREATE TABLE [sPurchase].[tQualityCheck] (
    [Id]                  BIGINT         NOT NULL,
    [OrgGroupId]          SMALLINT       NOT NULL,
    [LocationId]          INT            NOT NULL,
    [IsObsolete]          BIT            NULL,
    [GoodsReceivedNoteId] BIGINT         NULL,
    [PurchaseOrderId]     BIGINT         NULL,
    [RequestedBy]         NVARCHAR (100) NOT NULL,
    [QCNumber]            NVARCHAR (20)  NOT NULL,
    [StatusId]            SMALLINT       NOT NULL,
    [CreatedUserId]       BIGINT         NULL,
    [CreatedDateTime]     DATETIME       NOT NULL,
    [UpdatedUserId]       BIGINT         NULL,
    [UpdatedDateTime]     DATETIME       NULL,
    [DeletedDateTime]     DATETIME       NULL,
    CONSTRAINT [PK_sPurchase]].[tQualityCheck] PRIMARY KEY CLUSTERED ([Id] ASC)
);


GO
PRINT N'Creating Table [sPurchase].[tInvoiceGenerate]...';


GO
CREATE TABLE [sPurchase].[tInvoiceGenerate] (
    [Id]                  BIGINT          NOT NULL,
    [OrgGroupId]          SMALLINT        NOT NULL,
    [LocationId]          INT             NOT NULL,
    [IsObsolete]          BIT             NULL,
    [InvoiceGenerateId]   BIGINT          NOT NULL,
    [GoodsReceivedNoteID] BIGINT          NOT NULL,
    [VendorId]            INT             NOT NULL,
    [INVNumber]           NVARCHAR (20)   NOT NULL,
    [RequestedBy]         NVARCHAR (100)  NOT NULL,
    [StatusId]            SMALLINT        NOT NULL,
    [InvoiceDate]         DATETIME        NOT NULL,
    [InvoiceDueDate]      DATETIME        NOT NULL,
    [BillToAddress]       NVARCHAR (1000) NOT NULL,
    [ShipToAddress]       NVARCHAR (1000) NOT NULL,
    [Remarks]             NVARCHAR (500)  NOT NULL,
    [CreatedUserId]       BIGINT          NULL,
    [CreatedDateTime]     DATETIME        NOT NULL,
    [UpdatedUserId]       BIGINT          NULL,
    [UpdatedDateTime]     DATETIME        NULL,
    [DeletedDateTime]     DATETIME        NULL,
    CONSTRAINT [PK_sPurchase]].[tInvoiceGenerate] PRIMARY KEY CLUSTERED ([Id] ASC)
);


GO
PRINT N'Creating Table [sPurchase].[tInvoiceGenerateDetail]...';


GO
CREATE TABLE [sPurchase].[tInvoiceGenerateDetail] (
    [Id]                        BIGINT          NOT NULL,
    [OrgGroupId]                SMALLINT        NOT NULL,
    [InvoiceGenerateId]         BIGINT          NOT NULL,
    [GoodsReceivedNoteDetailId] BIGINT          NOT NULL,
    [UnitTypeId]                BIGINT          NOT NULL,
    [CategoryId]                BIGINT          NOT NULL,
    [SubCategoryId]             BIGINT          NOT NULL,
    [StockItemId]               BIGINT          NOT NULL,
    [POQty]                     DECIMAL (12, 2) NOT NULL,
    [ReceivedQty]               DECIMAL (12, 2) NOT NULL,
    [AcceptedQty]               DECIMAL (12, 2) NOT NULL,
    [RejectedQty]               DECIMAL (12, 2) NOT NULL,
    [ReasonForRejection]        NVARCHAR (300)  NULL,
    [UnitPrice]                 DECIMAL (12, 2) NOT NULL,
    [Remark]                    NVARCHAR (300)  NULL,
    [CreatedUserId]             BIGINT          NULL,
    [CreatedDateTime]           DATETIME        NOT NULL,
    [UpdatedUserId]             BIGINT          NULL,
    [UpdatedDateTime]           DATETIME        NULL,
    CONSTRAINT [PK_sPurchase]].[tInvoiceGenerateDetails] PRIMARY KEY CLUSTERED ([Id] ASC)
);


GO
PRINT N'Creating Table [sPurchase].[tSalesReturn]...';


GO
CREATE TABLE [sPurchase].[tSalesReturn] (
    [Id]                  BIGINT         NOT NULL,
    [OrgGroupId]          SMALLINT       NOT NULL,
    [LocationId]          INT            NOT NULL,
    [IsObsolete]          BIT            NULL,
    [GoodsReceivedNoteId] BIGINT         NULL,
    [PurchaseOrderId]     BIGINT         NULL,
    [RequestedBy]         NVARCHAR (100) NOT NULL,
    [SRNumber]            NVARCHAR (20)  NOT NULL,
    [StatusId]            SMALLINT       NOT NULL,
    [CreatedUserId]       BIGINT         NULL,
    [CreatedDateTime]     DATETIME       NOT NULL,
    [UpdatedUserId]       BIGINT         NULL,
    [UpdatedDateTime]     DATETIME       NULL,
    [DeletedDateTime]     DATETIME       NULL,
    CONSTRAINT [PK_sPurchase]].[tSalesReturn] PRIMARY KEY CLUSTERED ([Id] ASC)
);


GO
PRINT N'Creating Table [sPurchase].[tPurchaseLog]...';


GO
CREATE TABLE [sPurchase].[tPurchaseLog] (
    [Id]              BIGINT             IDENTITY (1, 1) NOT NULL,
    [Message]         NVARCHAR (MAX)     NULL,
    [MessageTemplate] NVARCHAR (MAX)     NULL,
    [Level]           NVARCHAR (MAX)     NULL,
    [TimeStamp]       DATETIMEOFFSET (7) NOT NULL,
    [Exception]       NVARCHAR (MAX)     NULL,
    [Properties]      NVARCHAR (MAX)     NULL,
    CONSTRAINT [PK_PurchaseLog] PRIMARY KEY CLUSTERED ([Id] ASC)
);


GO
PRINT N'Creating Table [sPurchase].[tSalesReturnDetail]...';


GO
CREATE TABLE [sPurchase].[tSalesReturnDetail] (
    [Id]                        BIGINT          NOT NULL,
    [OrgGroupId]                SMALLINT        NOT NULL,
    [SalesReturnId]             BIGINT          NOT NULL,
    [GoodsReceivedNoteDetailId] BIGINT          NULL,
    [UnitTypeId]                BIGINT          NOT NULL,
    [CategoryId]                BIGINT          NOT NULL,
    [SubCategoryId]             BIGINT          NULL,
    [StockItemId]               BIGINT          NOT NULL,
    [POQty]                     DECIMAL (12, 2) NOT NULL,
    [ReceivedQty]               DECIMAL (12, 2) NOT NULL,
    [RejectedQty]               DECIMAL (12, 2) NULL,
    [CreditNoteIssueDate]       DATETIME        NULL,
    [ReasonForRejection]        NVARCHAR (300)  NULL,
    [CreatedUserId]             BIGINT          NULL,
    [CreatedDateTime]           DATETIME        NOT NULL,
    [UpdatedUserId]             BIGINT          NULL,
    [UpdatedDateTime]           DATETIME        NULL,
    CONSTRAINT [PK_sPurchase]].[tSalesReturnDetails] PRIMARY KEY CLUSTERED ([Id] ASC)
);


GO
PRINT N'Creating Table [sPurchase].[tQuotationRequestDetail]...';


GO
CREATE TABLE [sPurchase].[tQuotationRequestDetail] (
    [Id]                      BIGINT          NOT NULL,
    [OrgGroupId]              SMALLINT        NOT NULL,
    [QuotationRequestId]      BIGINT          NOT NULL,
    [PurchaseRequestDetailId] BIGINT          NOT NULL,
    [StockItemId]             BIGINT          NOT NULL,
    [RequestedQty]            DECIMAL (12, 2) NOT NULL,
    [Remark]                  NVARCHAR (300)  NULL,
    [TargetPrice]             DECIMAL (12, 2) NOT NULL,
    [CreatedUserId]           BIGINT          NOT NULL,
    [CreatedDateTime]         DATETIME        NULL,
    [UpdatedUserId]           BIGINT          NULL,
    [UpdatedDateTime]         DATETIME        NULL,
    CONSTRAINT [PK_sPurchase]].[tQuotationRequestDetails] PRIMARY KEY CLUSTERED ([Id] ASC)
);


GO
PRINT N'Creating Table [sPurchase].[tPurchaseRequestDetail]...';


GO
CREATE TABLE [sPurchase].[tPurchaseRequestDetail] (
    [Id]                BIGINT          NOT NULL,
    [OrgGroupId]        SMALLINT        NOT NULL,
    [PurchaseRequestId] BIGINT          NOT NULL,
    [StockItemId]       BIGINT          NOT NULL,
    [RequestedQty]      DECIMAL (12, 2) NOT NULL,
    [Remark]            NVARCHAR (300)  NULL,
    [CreatedUserId]     BIGINT          NULL,
    [CreatedDateTime]   DATETIME        NULL,
    [UpdatedUserId]     BIGINT          NULL,
    [UpdatedDateTime]   DATETIME        NULL,
    CONSTRAINT [PK_sPurchase]].[tPurchaseRequestDetails] PRIMARY KEY CLUSTERED ([Id] ASC)
);


GO
PRINT N'Creating Table [sPurchase].[tPurchaseOrderDetail]...';


GO
CREATE TABLE [sPurchase].[tPurchaseOrderDetail] (
    [Id]                      BIGINT          NOT NULL,
    [OrgGroupId]              SMALLINT        NOT NULL,
    [PurchaseOrderId]         BIGINT          NOT NULL,
    [PurchaseRequestDetailId] BIGINT          NOT NULL,
    [StockItemId]             BIGINT          NOT NULL,
    [TotalQty]                DECIMAL (12, 2) NOT NULL,
    [Remark]                  NVARCHAR (300)  NULL,
    [CreatedUserId]           BIGINT          NULL,
    [CreatedDateTime]         DATETIME        NOT NULL,
    [UpdatedUserId]           BIGINT          NULL,
    [UpdatedDateTime]         DATETIME        NULL,
    CONSTRAINT [PK_sPurchase]].[tPurchaseOrderDetails] PRIMARY KEY CLUSTERED ([Id] ASC)
);


GO
PRINT N'Creating Table [sPurchase].[tGoodsReceivedNoteDetail]...';


GO
CREATE TABLE [sPurchase].[tGoodsReceivedNoteDetail] (
    [Id]                      BIGINT          NOT NULL,
    [OrgGroupId]              SMALLINT        NOT NULL,
    [GoodsReceivedNoteId]     BIGINT          NOT NULL,
    [PurchaseRequestDetailId] BIGINT          NOT NULL,
    [UnitTypeId]              BIGINT          NOT NULL,
    [CategoryId]              BIGINT          NOT NULL,
    [SubCategoryId]           BIGINT          NOT NULL,
    [StockItemId]             BIGINT          NOT NULL,
    [POQty]                   DECIMAL (12, 2) NOT NULL,
    [ReceivedQty]             DECIMAL (12, 2) NOT NULL,
    [PreviousGRNQty]          DECIMAL (12, 2) NOT NULL,
    [UnitPrice]               DECIMAL (12, 2) NOT NULL,
    [Remark]                  NVARCHAR (300)  NULL,
    [CreatedUserId]           BIGINT          NULL,
    [CreatedDateTime]         DATETIME        NOT NULL,
    [UpdatedUserId]           BIGINT          NULL,
    [UpdatedDateTime]         DATETIME        NULL,
    CONSTRAINT [PK_sPurchase]].[tGoodsReceivedNoteDetails] PRIMARY KEY CLUSTERED ([Id] ASC)
);


GO
PRINT N'Creating Table [sWf].[tWfApprovalActionLog]...';


GO
CREATE TABLE [sWf].[tWfApprovalActionLog] (
    [AutoId]             INT             IDENTITY (1, 1) NOT NULL,
    [WfApprovalActionId] BIGINT          NOT NULL,
    [ActionByEmployeeId] BIGINT          NOT NULL,
    [StatusId]           SMALLINT        NOT NULL,
    [IsSequancial]       BIT             NULL,
    [ActionRemark]       NVARCHAR (1000) NULL,
    [CreatedUserId]      BIGINT          NOT NULL,
    [CreatedDateTime]    DATETIME        NOT NULL,
    CONSTRAINT [PK_tWfApprovalActionLog] PRIMARY KEY CLUSTERED ([AutoId] ASC)
);


GO
PRINT N'Creating Table [sWf].[tWfHierarchyLevel]...';


GO
CREATE TABLE [sWf].[tWfHierarchyLevel] (
    [AutoId]             BIGINT         IDENTITY (1, 1) NOT NULL,
    [WfApprovalActionId] BIGINT         NOT NULL,
    [StatusId]           SMALLINT       NOT NULL,
    [Remark]             NVARCHAR (500) NULL,
    [ActionByEmployeeId] BIGINT         NOT NULL,
    [ActionDatetime]     DATETIME       NULL,
    CONSTRAINT [PK_tWfHierarchyLevel] PRIMARY KEY CLUSTERED ([AutoId] ASC)
);


GO
PRINT N'Creating Table [sWf].[tWfTypeMaster]...';


GO
CREATE TABLE [sWf].[tWfTypeMaster] (
    [Id]         SMALLINT       NOT NULL,
    [Code]       NVARCHAR (100) NOT NULL,
    [Title]      NVARCHAR (100) NOT NULL,
    [IsObsolete] BIT            NOT NULL,
    CONSTRAINT [PK_tWfTypeMaster_1] PRIMARY KEY CLUSTERED ([Id] ASC)
);


GO
PRINT N'Creating Table [sWf].[tWfStatusMaster]...';


GO
CREATE TABLE [sWf].[tWfStatusMaster] (
    [Id]         SMALLINT       NOT NULL,
    [Code]       NVARCHAR (100) NOT NULL,
    [Title]      NVARCHAR (100) NOT NULL,
    [IsObsolete] BIT            NOT NULL,
    CONSTRAINT [PK_tWfStatusMaster_1] PRIMARY KEY CLUSTERED ([Id] ASC)
);


GO
PRINT N'Creating Table [sWf].[tWfFunctionalityMaster]...';


GO
CREATE TABLE [sWf].[tWfFunctionalityMaster] (
    [Id]         SMALLINT       NOT NULL,
    [Code]       NVARCHAR (100) NOT NULL,
    [Title]      NVARCHAR (100) NOT NULL,
    [IsObsolete] BIT            NOT NULL,
    CONSTRAINT [PK_tWfFunctionalityMaster_1] PRIMARY KEY CLUSTERED ([Id] ASC)
);


GO
PRINT N'Creating Table [sWf].[tWfApprovalAction]...';


GO
CREATE TABLE [sWf].[tWfApprovalAction] (
    [Id]                BIGINT         NOT NULL,
    [OrgGroupId]        SMALLINT       NOT NULL,
    [ActionEmployeeId]  BIGINT         NOT NULL,
    [ActionStatusId]    TINYINT        NOT NULL,
    [ActionRemark]      NVARCHAR (500) NOT NULL,
    [WfFunctionalityId] SMALLINT       NOT NULL,
    [DocSourceTypeId]   SMALLINT       NOT NULL,
    [DocSourceId]       BIGINT         NOT NULL,
    [CreatedUserId]     BIGINT         NULL,
    [CreatedDateTime]   DATETIME       NOT NULL,
    [UpdatedUserId]     BIGINT         NULL,
    [UpdatedDateTime]   DATETIME       NULL,
    CONSTRAINT [PK_tWfApprovalAction] PRIMARY KEY CLUSTERED ([Id] ASC)
);


GO
PRINT N'Creating Table [sWf].[tWfApprovingAuthority]...';


GO
CREATE TABLE [sWf].[tWfApprovingAuthority] (
    [AutoId]                INT      IDENTITY (1, 1) NOT NULL,
    [AuthoritySourceTypeId] SMALLINT NOT NULL,
    [AuthoritySourceId]     BIGINT   NOT NULL,
    [OrgId]                 SMALLINT NOT NULL,
    [WfFunctionalityId]     SMALLINT NULL,
    CONSTRAINT [PK_tWfApprovingAuthority_1] PRIMARY KEY CLUSTERED ([AutoId] ASC)
);


GO
PRINT N'Creating Table [sWf].[tWfSetup]...';


GO
CREATE TABLE [sWf].[tWfSetup] (
    [AutoId]            SMALLINT IDENTITY (1, 1) NOT NULL,
    [WfTypeMasterId]    SMALLINT NOT NULL,
    [WfLevel]           SMALLINT NOT NULL,
    [OrgGroupId]        SMALLINT NOT NULL,
    [WfFunctionalityId] SMALLINT NOT NULL,
    [IsObsolete]        BIT      NOT NULL,
    CONSTRAINT [PK_tWfSetup_1] PRIMARY KEY CLUSTERED ([AutoId] ASC)
);


GO
PRINT N'Creating Table [sBiometric].[tCloudTransactionDataHistory]...';


GO
CREATE TABLE [sBiometric].[tCloudTransactionDataHistory] (
    [AutoId]          BIGINT        NOT NULL,
    [SourceId]        BIGINT        NOT NULL,
    [In_Out_Time]     DATETIME      NOT NULL,
    [ShiftCode]       INT           NOT NULL,
    [Attn_Dt]         DATE          NOT NULL,
    [Mode]            NVARCHAR (10) NOT NULL,
    [CreatedDateTime] DATETIME      NOT NULL,
    [DeviceIP]        NVARCHAR (20) NOT NULL,
    [EntryMode]       TINYINT       NOT NULL,
    [PunchId]         NVARCHAR (50) NULL,
    [TransactionId]   BIGINT        NOT NULL,
    [SourceTypeId]    SMALLINT      NULL,
    [IsProcessed]     BIT           NULL
);


GO
PRINT N'Creating Table [sBiometric].[tCloudTransactionRawDataHistory]...';


GO
CREATE TABLE [sBiometric].[tCloudTransactionRawDataHistory] (
    [TransactionId]       BIGINT        NOT NULL,
    [PunchId]             NVARCHAR (50) NULL,
    [TransactionDateTime] DATETIME      NOT NULL,
    [DeviceIP]            NVARCHAR (20) NOT NULL,
    [Mode]                NVARCHAR (10) NOT NULL,
    [CreatedDateTime]     DATETIME      NOT NULL
);


GO
PRINT N'Creating Table [sCommunication].[tCircularConsent]...';


GO
CREATE TABLE [sCommunication].[tCircularConsent] (
    [Id]                  BIGINT         IDENTITY (1, 1) NOT NULL,
    [CircularId]          BIGINT         NOT NULL,
    [QuestionDescription] NVARCHAR (MAX) NOT NULL,
    [AnsFieldTypeId]      INT            NOT NULL,
    [AnsFieldList]        NVARCHAR (MAX) NOT NULL,
    CONSTRAINT [PK_tCircularConsentQuestion] PRIMARY KEY CLUSTERED ([Id] ASC)
);


GO
PRINT N'Creating Table [sCommunication].[tCircularConsentResult]...';


GO
CREATE TABLE [sCommunication].[tCircularConsentResult] (
    [Id]                 BIGINT         IDENTITY (1, 1) NOT NULL,
    [SourceId]           BIGINT         NOT NULL,
    [CircularConsentId]  BIGINT         NOT NULL,
    [CircularConsentAns] NVARCHAR (MAX) NOT NULL,
    CONSTRAINT [PK_tCircularConsentResult] PRIMARY KEY CLUSTERED ([Id] ASC)
);


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


GO
CREATE TABLE [sFee].[tTempReceipt] (
    [Id]                   BIGINT          NOT NULL,
    [SourceTypeId]         SMALLINT        NULL,
    [SourceId]             BIGINT          NULL,
    [ReceiptNumber]        INT             NOT NULL,
    [ReceiptDate]          DATE            NOT NULL,
    [ReceiptAmount]        DECIMAL (12, 2) NULL,
    [PayTypeId]            TINYINT         NOT NULL,
    [ChequeNo]             NVARCHAR (40)   NULL,
    [BankName]             NVARCHAR (200)  NULL,
    [ReceiptBookId]        INT             NOT NULL,
    [Remark]               NVARCHAR (200)  NULL,
    [IsObsolete]           BIT             NOT NULL,
    [BatchId]              INT             NULL,
    [OrgGroupBatchId]      INT             NULL,
    [CreatedUserId]        BIGINT          NOT NULL,
    [CreatedDateTime]      DATETIME        NOT NULL,
    [TotalReceiptAmount]   DECIMAL (12, 2) NULL,
    [DiscountAmount]       DECIMAL (12, 2) NULL,
    [IsChequeCleared]      BIT             NULL,
    [ChequeClearDate]      DATE            NULL,
    [ChequeDate]           DATE            NULL,
    [FeeInvoiceId]         BIGINT          NULL,
    [CollectionGroupId]    INT             NULL,
    [AmountAfterDiscount]  DECIMAL (12, 2) NULL,
    [CGSTPercentage]       DECIMAL (5, 2)  NULL,
    [SGSTPercentage]       DECIMAL (5, 2)  NULL,
    [CGSTAmount]           DECIMAL (12, 2) NULL,
    [SGSTAmount]           DECIMAL (12, 2) NULL,
    [DepositedLedgerId]    INT             NULL,
    [PaymentTransactionId] BIGINT          NULL,
    [ReceiptPrintGroupId]  NVARCHAR (100)  NULL,
    [CancelStatusId]       SMALLINT        NULL,
    [CancelStatusRemark]   NVARCHAR (500)  NULL,
    [IsDiscountCoupon]     BIT             NULL,
    [FirmReceiptBookId]    INT             NULL
);


GO
PRINT N'Creating Index [sBiometric].[tCloudTransactionData].[CloudTransactionData_Autoid_TransactionId]...';


GO
CREATE NONCLUSTERED INDEX [CloudTransactionData_Autoid_TransactionId]
    ON [sBiometric].[tCloudTransactionData]([AutoId] ASC, [TransactionId] ASC);


GO
PRINT N'Creating Default Constraint [sEMeeting].[DF_tMeetingTypeMaster_IsObsolete]...';


GO
ALTER TABLE [sEMeeting].[tMeetingTypeMaster]
    ADD CONSTRAINT [DF_tMeetingTypeMaster_IsObsolete] DEFAULT ((0)) FOR [IsObsolete];


GO
PRINT N'Creating Default Constraint [sEMeeting].[DF_tOnlineMeeting_IsObsolete]...';


GO
ALTER TABLE [sEMeeting].[tOnlineMeeting]
    ADD CONSTRAINT [DF_tOnlineMeeting_IsObsolete] DEFAULT ((0)) FOR [IsObsolete];


GO
PRINT N'Creating Default Constraint [sEMeeting].[DF_tOnlineMeetingScope_IsObsolete]...';


GO
ALTER TABLE [sEMeeting].[tOnlineMeetingScope]
    ADD CONSTRAINT [DF_tOnlineMeetingScope_IsObsolete] DEFAULT ((0)) FOR [IsObsolete];


GO
PRINT N'Creating Default Constraint [sEMeeting].[DF_tOnlineMeetingResource_IsObsolete]...';


GO
ALTER TABLE [sEMeeting].[tOnlineMeetingResource]
    ADD CONSTRAINT [DF_tOnlineMeetingResource_IsObsolete] DEFAULT ((0)) FOR [IsObsolete];


GO
PRINT N'Creating Default Constraint unnamed constraint on [sPurchase].[tGoodsReceivedNote]...';


GO
ALTER TABLE [sPurchase].[tGoodsReceivedNote]
    ADD DEFAULT ((0)) FOR [IsObsolete];


GO
PRINT N'Creating Default Constraint unnamed constraint on [sPurchase].[tPurchaseOrder]...';


GO
ALTER TABLE [sPurchase].[tPurchaseOrder]
    ADD DEFAULT ((0)) FOR [IsObsolete];


GO
PRINT N'Creating Default Constraint unnamed constraint on [sPurchase].[tPurchaseRequest]...';


GO
ALTER TABLE [sPurchase].[tPurchaseRequest]
    ADD DEFAULT ((0)) FOR [IsObsolete];


GO
PRINT N'Creating Default Constraint unnamed constraint on [sPurchase].[tQuotationRequest]...';


GO
ALTER TABLE [sPurchase].[tQuotationRequest]
    ADD DEFAULT ((0)) FOR [IsObsolete];


GO
PRINT N'Creating Default Constraint unnamed constraint on [sPurchase].[tQualityCheck]...';


GO
ALTER TABLE [sPurchase].[tQualityCheck]
    ADD DEFAULT ((0)) FOR [IsObsolete];


GO
PRINT N'Creating Default Constraint unnamed constraint on [sPurchase].[tInvoiceGenerate]...';


GO
ALTER TABLE [sPurchase].[tInvoiceGenerate]
    ADD DEFAULT ((0)) FOR [IsObsolete];


GO
PRINT N'Creating Default Constraint unnamed constraint on [sPurchase].[tSalesReturn]...';


GO
ALTER TABLE [sPurchase].[tSalesReturn]
    ADD DEFAULT ((0)) FOR [IsObsolete];


GO
PRINT N'Creating Default Constraint unnamed constraint on [sWf].[tWfApprovalActionLog]...';


GO
ALTER TABLE [sWf].[tWfApprovalActionLog]
    ADD DEFAULT ((0)) FOR [IsSequancial];




GO
EXECUTE sp_refreshsqlmodule N'[sCertificate].[vPrintTemplateBonafideCertificate]';


GO
EXECUTE sp_refreshsqlmodule N'[sCertificate].[vPrintTemplateCharacterCertificate]';



GO
EXECUTE sp_refreshsqlmodule N'[sCertificate].[vPrintTemplateFirstTrialCertificate]';


GO
EXECUTE sp_refreshsqlmodule N'[sCertificate].[vPrintTemplateLeavingCertificate]';



GO
EXECUTE sp_refreshsqlmodule N'[sCertificate].[vPrintTemplateStudentBasicDetails]';



GO
EXECUTE sp_refreshsqlmodule N'[sCertificate].[vPrintTemplateStudentDetail]';



GO
EXECUTE sp_refreshsqlmodule N'[sCertificate].[vPrintTemplateTransferCertificate]';




GO
EXECUTE sp_refreshsqlmodule N'[sStudent].[vStudentAllDetail]';




GO
EXECUTE sp_refreshsqlmodule N'[sStudent].[vStudentColumnName]';



GO
EXECUTE sp_refreshsqlmodule N'[sStudent].[vStudentCustomSearch]';



GO
EXECUTE sp_refreshsqlmodule N'[sStudent].[vStudentDetails]';



GO
EXECUTE sp_refreshsqlmodule N'[sStudent].[vStudentVerification]';



GO

CREATE FUNCTION [sAssessment].[fSubjectWiseGradeGet](@rAcademicId bigint,@rExamId int,@rActivityId int,@rClassSubjectId int,@rBatchId int,@rClassId int)
RETURNS nvarchar(100) WITH EXECUTE AS CALLER
AS 
BEGIN
	DECLARE @lGrade nvarchar(100)=''
  
	DECLARE @lMarks decimal(5,2), @lScore decimal(5,2),@lGradeSetId int, @lTotalActivityCount int , @lSubjectMaximum decimal(5,2)

	SELECT @lMarks = SUM(AIS.Marks) from sAssessment.tCCESubjectSubActivityExamScore AIS
		INNER JOIN sAssessment.tCCESubjectSubActivityMaster SSA ON AIS.SubjectSubActivityId = SSA.Id
		INNER JOIN	sAssessment.tCCESubjectActivityMaster SAM  ON SAM.Id = SSA.SubjectActivityId
		WHERE AIS.AcademicId = @rAcademicId AND AIS.ExamId = @rExamId AND SAM.Id = @rActivityId

	SELECT @lTotalActivityCount = COUNT(1) from sAssessment.tCCESubjectSubActivityExamScore AIS
		INNER JOIN sAssessment.tCCESubjectSubActivityMaster SSA ON AIS.SubjectSubActivityId = SSA.Id
		INNER JOIN	sAssessment.tCCESubjectActivityMaster SAM  ON SAM.Id = SSA.SubjectActivityId
		WHERE AIS.AcademicId = @rAcademicId AND AIS.ExamId = @rExamId AND SAM.Id = @rActivityId

	SELECT @lSubjectMaximum = ED.Maximum from [sAssessment].[tExamDetail] ED
		INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
		WHERE ED.ExamId = @rExamId AND ED.ClassSubjectId = @rClassSubjectId AND EM.BatchId = @rBatchId AND EM.ClassId = @rClassId

	SELECT @lGradeSetId = ED.GradeSetId from [sAssessment].[tExamDetail] ED
		INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
		WHERE ExamId = @rExamId AND ClassSubjectId = @rClassSubjectId AND EM.BatchId = @rBatchId AND EM.ClassId = @rClassId
	
	SET @lScore = (@lMarks * 100) / (@lSubjectMaximum * @lTotalActivityCount)

	SELECT TOP 1 @lGrade = GradeCode
		FROM sAssessment.tGradeSetDetail
		WHERE MinimumScore <= @lScore AND GradesetId = @lGradeSetId
		ORDER BY MinimumScore DESC
	


	return  @lGrade
END
GO
PRINT N'Altering Procedure [sAlert].[pAlertQueueLogAdd]...';


GO
ALTER PROCEDURE [sAlert].[pAlertQueueLogAdd]
	@rId bigint = 0,
	@rMessageDate datetime = null,
	@rQueueMessage nvarchar(max) = '',
	@rEventId int = 0,
	@rAlertModeId tinyint = 0,
	@rOrgId smallint = 0,
	@rCreatedUserId bigint = 0

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	BEGIN TRANSACTION	
		IF(@rId = 0)	
		BEGIN
			DECLARE @lNextNumber BIGINT  
			EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sAlert.tAlertQueueLog', 0, 1, 1,@outNextNumber = @lNextNumber output

			INSERT INTO [sAlert].[tAlertQueueLog]
				([AutoId]
				,[MessageDate]
			    ,[QueueMessage]
			    ,[EventId]
			    ,[AlertModeId]
			    ,[OrgId]
			    ,[CreatedUserId]
			    ,[CreatedDateTime])
		   VALUES
				(@lNextNumber
				,@rMessageDate
			    ,@rQueueMessage
			    ,@rEventId
			    ,@rAlertModeId
			    ,@rOrgId
			    ,@rCreatedUserId
			    ,sCommon.fGetDate())

			SELECT @@IDENTITY AS Result
		END
		ELSE
		BEGIN
			UPDATE [sAlert].[tAlertQueueLog] SET [QueueMessage] = @rQueueMessage WHERE AutoId = @rId

			SELECT @rId AS Result
		END
	COMMIT TRANSACTION
    END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
END
GO
PRINT N'Altering Procedure [sCertificate].[pRptCharacterCertificateGet]...';


GO
ALTER PROCEDURE [sCertificate].[pRptCharacterCertificateGet]
	 
	 @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)=''
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
DECLARE @lIsOnPrePrinted bit = 0

DECLARE @lConfigValue nvarchar(50)

DECLARE @lIsDisplayImageHeader bit=0
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 = 180 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 = 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,
			C.Id,
			C.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,
			CM.DisplayTitle AS ClassOnly,
			BM.Title AS Batch,
			SO.DateOfBirth,
			ISNULL(SO.BirthDateInWord,'') AS DOBInWords,
			ISNULL(SO.BirthPlace,'') AS BirthPlace,
			ISNULL(SO.BirthTaluka,'') AS Taluka,
			ISNULL(SO.BirthDistrict,'')	AS District,		
			C.characterDate,
			C.Number,
			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 OrgName,
			OM.StateName+' '+OM.StreetTwo+' '+OM.StreetThree AS OrgAddress,
			OM.PhoneNo,
			SM.StatusId,
			A.RollNo,
			DM.OrderIndex AS DivisionOrder,
			OM.ReportOrgTitle,
			OM.SmallAddress1,
			OM.SmallAddress2,
			OM.RegistrationDetail,
			@lIsOnPrePrinted AS IsOnPrePrinted,
			@lIsDisplayImageHeader AS IsDisplayImageHeader,
			--OI.CertificateHeaderA4  ,
			SA.AdmissionDate,
			SF.FatherName,
			SF.MotherName,
			@lIDConfigValue AS ItemValue,
			OI.CertificateHeaderA4Portrait AS CertificateHeaderA4,
			A.Id,
			SA.LeftDate AS LCDate,
			C.Remark AS Remark,
			ISNULL(EI.EmployeeSign,0x) AS EmployeeSign,
			ISNULL(OM.PrincipalSignature,0x) AS PrincipalSignature,
			SM.FirstName,
			SM.LastName,
			SM.MiddleName,
			SM.SUId As SUID,
			DM.DisplayTitle AS DivisionOnly,
			@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,
			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
	FROM 
			sCertificate.tCharacter C
			INNER JOIN sStudent.tAcademic A ON C.AcademicId=A.Id
			LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId=A.StudentId
			INNER JOIN sStudent.tStudentMaster SM ON SM.Id=A.StudentId
			INNER JOIN sStudent.tStudentOther SO ON SO.StudentId=A.StudentId
			INNER JOIN sSetup.tDivisionMaster DM ON A.DivisionId = DM.Id  
			INNER JOIN sSetup.tClassMaster CM ON CM.Id= DM.ClassId
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id=A.BatchId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=A.OrgId
			LEFT JOIN sSetup.tOrgImages OI ON OI.OrgId = OM.Id
			LEFT JOIN sStudent.tStudentAdmission SA ON SA.StudentId=A.StudentId
			LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId=A.StudentId
			LEFT JOIN sHrm.tEmployeeImages EI ON EI.EmployeeId = DM.InchargeEmployeeId
			LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId = A.StudentId			--add for 27638 mantis
	WHERE  
			A.OrgId=@rOrgId
		AND	A.BatchId = @rBatchId 
		AND ((A.ClassId=@rClassId) OR (@rClassId=0))
		AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		AND ((SM.Code = @rCode) OR (ISNULL(@rCode,'') = ''))
		AND ((SM.FirstName = @rName) OR (ISNULL(@rName,'') = ''))
		AND ((C.Number=@rNumber) OR (@rNumber=''))
		AND ((C.Number >= @rFromNo) OR (@rFromNo=''))
		AND ((C.Number <= @rToNo) OR (@rToNo=''))
		AND ((C.characterDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
		AND ((C.characterDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
		--Group By C.AcademicId,C.Number,SM.Code,SM.FirstName,SM.LastName,SM.MiddleName,CM.DisplayTitle,BM.Title,SO.DateOfBirth,SO.BirthDateInWord,
		--SO.BirthPlace,SO.BirthTaluka,SO.BirthDistrict,C.characterDate,OM.CityName,OM.StateName,SO.FamilyCast,SO.FamilySubCast,SO.GenderId,SI.StudentPhoto,SM.StatusId,OM.OrgLogo,OM.Title,
		--OM.StreetOne,OM.StreetThree,OM.StreetTwo,OM.PhoneNo
	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
	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].[pRptFirstTrialCertificateGet]...';


GO
ALTER PROCEDURE [sCertificate].[pRptFirstTrialCertificateGet]
	 
	 @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)=''
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
DECLARE @lIsOnPrePrinted bit = 0

DECLARE @lIsDisplayImageHeader bit = 0

DECLARE @lConfigValue nvarchar(50)
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 = 179 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 = 158 AND SourceTypeId = 1016 AND SourceId = @rOrgId
	
	--IF (@lConfigValue IS NULL) OR (@lConfigValue = 'False')
	--SET @lIsDisplayImageHeader = 0
	--ELSE
	--SET @lIsDisplayImageHeader = 1	
	
	--add for 28093 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 28093 mantis end

	SELECT
			@rBuilder1 AS Builder1,
		    @rBuilder2 AS Builder2,
			FT.Id,
			FT.Number,
			FT.AcademicId,
			FT.FirstTrialDate,
			FT.ExamCentre,
			FT.ExamYear,
			FT.SeatNo,
			FT.Trial,
			SM.Code,
			--SM.FirstName+' '+SM.MiddleName+' '+SM.LastName AS Name,
			[sStudent].[fStudentNameGet](SM.FirstName , SM.MiddleName, SM.LastName,OM.StudentNameFormatId ) AS Name,
			SM.LastName as Surname,
			SO.GenderId,
			ISNULL(OM.CityName,'') AS City,
			ISNULL(OM.StateName,'') AS CityState,
			SM.StatusId,
			OM.OrgLogo,
			OM.Title AS OrgTitle,
			OM.StreetOne+' '+OM.StreetTwo+' '+OM.StreetThree AS OrgAddress,
			OM.PhoneNo,
			A.RollNo,
			DM.OrderIndex AS DivisionOrder,
			OM.ReportOrgTitle,
			OM.SmallAddress1,
			OM.SmallAddress2,
			OM.RegistrationDetail,
			@lIsOnPrePrinted AS IsOnPrePrinted,
			CM.DisplayTitle+' - '+DM.DisplayTitle AS Class,
			CM.DisplayTitle  AS ClassName,
			@lIsDisplayImageHeader AS IsDisplayImageHeader,
			--OI.CertificateHeaderA4  ,
			(CASE WHEN CGM.Title='10' THEN  'SSC'
			WHEN  CGM.Title='12'  THEN 'HSC'  ElSE CGM.Title + ' '+'std'
			 END) AS Exam,
			 FT.Remark AS Remark,
			 ISNULL(SF.FatherName,'') As FatherName,
			 ISNULL(SF.MotherName,'') As MotherName,
			 SA.AdmissionDate,
			 SO.BirthDateInWord ,
			 SO.DateOfBirth,
			 SI.StudentPhoto,
			 @lIDConfigValue AS ItemValue,
			 SM.SUID ,
			 STM.Title as StreamName,
			 ISNULL(OM.ReportOrgGroupTitle,'') AS ReportOrgGroupTitle,
			 OM.ReportOrgTitle,
			--(CASE WHEN OI.CertificateHeaderA4Portrait IS NULL THEN
			--OI.CertificateHeaderA4
			--ELSE OI.CertificateHeaderA4Portrait END ) AS CertificateHeader
			OI.CertificateHeaderA4Portrait AS CertificateHeaderA4,
			BM.Title AS Batch,
			ISNULL(SA.LeftDate,'') AS LeftDate,
			ISNULL(EI.EmployeeSign,0x) AS EmployeeSign,
			ISNULL(OM.PrincipalSignature,0x) AS PrincipalSignature,
			EI.EmployeeId,
			SC.PresentStreetOne AS PresentStreetOne,		--add for 28093 mantis start
			SC.PresentStreetTwo AS PresentStreetTwo,
			SC.PresentStreetThree AS PresentStreetThree,
			SC.PresentCountry AS PresentCountry,
			SC.PresentState AS PresentState,
			SC.PresentCity AS PresentCity,
			SC.PresentZipCode AS PresentZipCode,
			SC.PresentContactNo AS PresentContactNo,
			@lIsShowPhoto AS IsShowPhoto,
			CAST((CASE WHEN SI.QRCode IS NULL THEN 0 ELSE 1 END) AS bit) AS IsDisplayQRCode,
			ISNULL(SI.QRCode,'') AS QRCode					--add for 28093 mantis end

	FROM
			sCertificate.tFirstTrial FT
			INNER JOIN sStudent.tAcademic A ON FT.AcademicId=A.Id
			LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId=A.StudentId
			INNER JOIN sStudent.tStudentMaster SM ON SM.Id=A.StudentId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=A.OrgId
			INNER JOIN sStudent.tStudentOther SO ON SO.StudentId=A.StudentId
			INNER JOIN sSetup.tDivisionMaster DM ON A.DivisionId = DM.Id
			INNER JOIN sSetup.tClassMaster CM ON CM.Id= DM.ClassId
			INNER JOIN  sSetup.tStreamMaster STM ON STM.Id= CM.StreamId
			Left JOIN sSetup.tOrgImages OI ON OI.OrgId = OM.Id
			LEFT JOIN sSetup.tClassGroupMaster CGM ON CGM.Id = CM.ClassGroupId
			LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId=A.StudentId
			LEFT JOIN sStudent.tStudentAdmission SA ON SA.StudentId=A.StudentId
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id=A.BatchId
			LEFT JOIN sHrm.tEmployeeImages EI ON EI.EmployeeId = DM.InchargeEmployeeId
			LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId=SM.Id			--add for 28093 mantis
			
	WHERE
			A.OrgId=@rOrgId
			AND	A.BatchId = @rBatchId
			AND ((A.ClassId=@rClassId) OR (@rClassId=0))
			AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId=0))
			AND ((SM.Code = @rCode) OR (ISNULL(@rCode,'') = ''))
			AND ((SM.FirstName = @rName) OR (ISNULL(@rName,'') = ''))
			AND ((FT.FirstTrialDate>=@rFromDate) OR (ISNULL(@rFromDate,'')=''))
			AND ((FT.FirstTrialDate<=@rToDate) OR (ISNULL(@rToDate,'')=''))
			AND ((FT.Number=@rNumber) OR (@rNumber=''))
			AND ((FT.Number >= @rFromNo) OR (@rFromNo=''))
			AND ((FT.Number <= @rToNo) OR (@rToNo=''))
			--Group By FT.AcademicId,SM.Code,SM.FirstName,SM.LastName,SM.MiddleName,FT.SeatNo,FT.Trial,SM.Code,SM.FirstName,OM.StateName,SO.GenderId,
			--OM.CityName,OM.StateName,FT.FirstTrialDate,FT.ExamCentre,FT.ExamYear,SM.MiddleName,SM.LastName,OM.CityName,SM.StatusId
			--,OM.OrgLogo,OM.PhoneNo,OM.Title,OM.StreetOne,OM.StreetTwo,OM.StreetThree
	END
GO
PRINT N'Altering Procedure [sStudent].[pRptStudentPastLCVerificationGet]...';


GO
ALTER PROCEDURE [sStudent].[pRptStudentPastLCVerificationGet]
	 
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='',
	 @rOrgId int,
	 @rBatchId int,
	 @rDepartmentId int=0,
	 @rClassId int=0,
	 @rDivisionId int=0,
     @rStrCode nvarchar(20)='',
	 @rStatusId int=0,
	 @rClassStatusId int=0,
	 @rPreviousSchool nvarchar(200)=''

	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
 BEGIN

	     SELECT
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,	
			OM.OrgLogo,
			OM.Title AS OrgTitle,
			OM.StreetOne+' '+OM.StreetTwo+' '+OM.StreetThree AS OrgAddress,
			OM.SmallAddress1,
			OM.SmallAddress2,
			OM.RegistrationDetail,
            vSA.ClassId AS ClassId,
			CM.OrderIndex AS ClassOrderIndex,
			vSA.ClassId AS DivisionId,	
			DM.OrderIndex AS DivisionOrderIndex,		
			vSA.ClassName AS ClassName,
			vSA.DivisionName AS DivisionName,
			ISNULL(OM.ReportOrgGroupTitle,'') AS ReportOrgGroupTitle,
			OM.ReportOrgTitle,		
			vSA.AcademicId,
			vSA.Code,
			ISNULL(SA.AdmissionNumber,'') As OldGRNo,
            vSA.FirstName,vSA.MiddleName,vSA.LastName,
			[sStudent].[fStudentNameGet](vSA.FirstName , vSA.MiddleName, vSA.LastName,OM.StudentNameFormatId ) AS Name,
			ISNULL(SO.DateOfBirth,'') AS DateOfBirth,
			ISNULL(SO.BirthDateInWord,'') AS BirthDateInWord,
			ISNULL(SA.PreviousStandard,'') AS PreviousStandard,
			ISNULL(SA.LeftDate,'') AS LeftDate,
			ISNULL(SO.BirthPlace,'') AS BirthPlace,
			ISNULL(SA.PreviousLCNumber,'') AS PreviousLCNumber,
			ISNULL(SA.PreviousLCDate,'') AS PreviousLCDate,
			ISNULL(SA.PreviousLCResult,'') AS PreviousLCResult,
			ISNULL(SO.FamilySubCast,'') AS SubCaste,
			ISNULL(SO.FamilyCast,'') AS Caste,
			isnull(MainCastCategoryId,0) AS CastCategoryId,
			ISNULL(SA.AdmissionNumber,'') AS AdmissionNumber,
			ISNULL(SA.PreviousLeftDate,'') AS PreviousLeftDate,		--add for 27789 mantis
			(CASE WHEN @rPreviousSchool='' THEN 'All'
				ELSE SA.PreviousSchool END) AS PreviousSchool		--add for 28188 mantis
			--SA.PreviousSchool

	FROM 
		    sStudent.vStudentAcademic vSA 	
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=vSA.OrgId 
			LEFT JOIN sStudent.tStudentAdmission SA ON SA.StudentId=vSA.StudentId
			INNER JOIN sSetup.tClassMaster CM ON CM.Id=SA.AdmissionStandardId
			INNER JOIN sSetup.tDivisionMaster DM ON vSA.DivisionId = DM.Id  
		    LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId=vSA.StudentId 
			LEFT JOIN sCommon.tCastCategoryMaster CSM ON CSM.Id=SO.CastCategoryId		
	Where		
	           ((vSA.OrgId=@rOrgId) OR (@rOrgId=0))
	       AND ((vSA.BatchId=@rBatchId) OR (@rBatchId=0))
	       AND ((vSA.DepartmentId=@rDepartmentId) OR(@rDepartmentId=0))
	       AND ((vSA.ClassId=@rClassId) OR(@rClassId=0))	  
	       AND ((vSA.DivisionId=@rDivisionId) OR (@rDivisionId=0))	
		   AND (ISNULL(vSA.Code,0) IN( SELECT cast(item as nvarchar(20)) FROM  sCommon.fnsplit(@rStrCode,',')) OR @rStrCode='')
           AND ((vSA.StatusId=@rStatusId)OR(@rStatusId=0))
		   AND ((vSA.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0)) 
		   --AND (ISNULL(SA.PreviousSchool,'') IN( SELECT item FROM  sCommon.fnsplit(@rPreviousSchool,','))OR @rPreviousSchool='')	
		    AND ((SA.PreviousSchool =  @rPreviousSchool) OR (@rPreviousSchool='')) 
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,
			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
	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
	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 [sCommon].[pOrganizationSetupRemove]...';


GO
 
ALTER PROCEDURE [sCommon].[pOrganizationSetupRemove]
	 
	 @rOrgId bigint
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
  --  BEGIN TRY
	
	 --BEGIN TRANSACTION
	 
	 --EXEC sp_msforeachtable "ALTER TABLE ? NOCHECK CONSTRAINT all"
    
DELETE FROM sAccounting.tExpense WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sAccounting.tExpenseGroupMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sAccounting.tReimbursement WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sAccounting.tReimbursementDetail WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sAccounting.tReimbursementTypeMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sActivity.tActivity WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sActivity.tActivityParticipant WHERE CAST(LEFT(ActivityId, 4) AS INT) = @rOrgId
DELETE FROM sActivity.tAssignClub WHERE CAST(LEFT(ClubId, 4) AS INT) = @rOrgId
DELETE FROM sActivity.tEventAssign WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sActivity.tEventEnrollment WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sActivity.tEventSchedule WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sActivity.tHealthCheckup WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sActivity.tHealthCheckupAssign WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sActivity.tHealthCheckupDetail WHERE CAST(LEFT(HealthCheckupId, 4) AS INT) = @rOrgId
DELETE FROM sActivity.tHealthCheckupParameter WHERE CAST(LEFT(HealthCheckupId, 4) AS INT) = @rOrgId
DELETE FROM sActivity.tHealthCheckupStudent WHERE CAST(LEFT(HealthCheckupId, 4) AS INT) = @rOrgId
DELETE FROM sActivity.tHealthParameterGroupMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sActivity.tHealthParameterList WHERE CAST(LEFT(HealthParameterId, 4) AS INT) = @rOrgId
DELETE FROM sActivity.tHealthParameterMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sActivity.tHealthTrack WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sActivity.tHouseMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sActivity.tPlacement WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sActivity.tPlacementInvite WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sActivity.tStudentImmunizationStatus WHERE CAST(LEFT(ImmunizationChartId, 4) AS INT) = @rOrgId
DELETE FROM sAdmission.tAdmissionForm WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sAdmission.tAdmissionFormIssue WHERE OrgId = @rOrgId
DELETE FROM sAdmission.tAdmissionInquiry WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sAlert.tAlertConfiguration WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sAlert.tAlertLog WHERE OrgId = @rOrgId
DELETE FROM sAlert.tAlertQueue WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sAlert.tAlertQueueDetail WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sAlert.tCustomTemplateMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sAlert.tDepartmentRecipient WHERE CAST(LEFT(DepartmentId, 4) AS INT) = @rOrgId
DELETE FROM sAlert.tEmailConfiguration WHERE CAST(LEFT(OrgId, 4) AS SMALLINT) = @rOrgId
DELETE FROM sAlert.tEventTemplate WHERE CAST(LEFT(OrgId, 4) AS SMALLINT) = @rOrgId
DELETE FROM sAlert.tExternalRecipientMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sAlert.tSMSConfiguration WHERE CAST(LEFT(OrgId, 4) AS SMALLINT) = @rOrgId
DELETE FROM sAlert.tTemplateMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sAssessment.tCCECSClass WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sAssessment.tCCECSGroupMaster WHERE OrgId = @rOrgId
DELETE FROM sAssessment.tCCECSIndicatorGrade WHERE CAST(LEFT(CCECSId, 4) AS INT) = @rOrgId
DELETE FROM sAssessment.tCCECSIndicatorMaster WHERE OrgId = @rOrgId
DELETE FROM sAssessment.tCCECSMaster WHERE OrgId = @rOrgId
DELETE FROM sAssessment.tCCECSScore WHERE CAST(LEFT(CCECSId, 4) AS INT) = @rOrgId
DELETE FROM sAssessment.tCCEExamMapping WHERE CAST(LEFT(BatchId, 4) AS INT) = @rOrgId
DELETE FROM sAssessment.tCCEExamSetting WHERE CAST(LEFT(ClassId, 4) AS INT) = @rOrgId
DELETE FROM sAssessment.tCCEFAGroupMaster WHERE OrgId = @rOrgId
DELETE FROM sAssessment.tCCEFAIndicatorMaster WHERE OrgId = @rOrgId
DELETE FROM sAssessment.tCCEFAMaster WHERE OrgId = @rOrgId
DELETE FROM sAssessment.tCCEFAScore WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sAssessment.tCCEFASubject WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sAssessment.tCCEResult WHERE AcademicId = @rOrgId
DELETE FROM sAssessment.tCCEResultDetail WHERE AcademicId = @rOrgId
DELETE FROM sAssessment.tExamCombine WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sAssessment.tExamDetail WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sAssessment.tExamGroupMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sAssessment.tExamMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sAssessment.tExamStatus WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sAssessment.tExamsubgroupmaster WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sAssessment.tGeneralExamCustomSearch WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sAssessment.tGradeSetDetail WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sAssessment.tGradeSetMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sAssessment.tLevelSetDetail WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sAssessment.tLevelSetMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sAssessment.tOptionalSubject WHERE CAST(LEFT(AcademicId, 4) AS BIGINT) = @rOrgId
DELETE FROM sAssessment.tRankSetDetail WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sAssessment.tRankSetMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sAssessment.tResult WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sAssessment.tResultDetail WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sAssetManagement.tAssetAdjustment WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sAssetManagement.tAssetAdjustmentDetail WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sAssetManagement.tAssetAudit WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sAssetManagement.tAssetAuditDetail WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sAssetManagement.tAssetMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sAssetManagement.tDepartmentLocation WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sAssetManagement.tMaintenence WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sAssetManagement.tMovement WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sAssetManagement.tMovementDetail WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sAssetManagement.tRecordManualEvent WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sAttendance.tApplicableAttendanceType WHERE OrgId = @rOrgId
DELETE FROM sAttendance.tMonthlyRegister WHERE CAST(LEFT(AcademicId, 4) AS BIGINT) = @rOrgId
DELETE FROM sAttendance.tMonthlySetup WHERE CAST(LEFT(ClassId, 4) AS INT) = @rOrgId
DELETE FROM sAttendance.tStudentRegister WHERE CAST(LEFT(AcademicId, 4) AS BIGINT) = @rOrgId
DELETE FROM sAttendance.tStudentSetup WHERE CAST(LEFT(AcademicId, 4) AS BIGINT) = @rOrgId
DELETE FROM sAttendance.tSubjectBatch WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sAttendance.tSubjectBatchStudent WHERE CAST(LEFT(AcademicId, 4) AS BIGINT) = @rOrgId
DELETE FROM sAudit.tAudit WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sAudit.tAuditLog WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sAudit.tAuditLogTransaction WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sAudit.tAuditTable WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sAudit.tAuditTableField WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sAudit.tAuditTransaction WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sBi.tAction WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sBi.tActionStatusMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sBi.tActionTypeMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sBi.tAudit WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sBi.tAuditLocation WHERE CAST(LEFT(AuditId, 4) AS BIGINT) = @rOrgId
DELETE FROM sBi.tAuditReasonMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sBi.tAuditStatusMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sBi.tAuditTypeMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sBi.tDocument WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sBi.tDocumentTypeMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sBi.tFinding WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sBi.tFindingTypeMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sBi.tInspection WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sBi.tQuestionAnswerMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sBi.tQuestionAnswerTypeMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sBi.tQuestionMainGroupMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sBi.tQuestionMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sBi.tQuestionnairesMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sBi.tQuestionResponse WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sBi.tQuestionSubGroupMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sBi.tSeverityMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sBiometric.tPunchMaster WHERE CAST(LEFT(OrgId, 4) AS SMALLINT) = @rOrgId
DELETE FROM sCertificate.tBonafide WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sCertificate.tCharacter WHERE OrgId = @rOrgId
DELETE FROM sCertificate.tFirstTrial WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sCertificate.tLeaving WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sCommon.tAgeGroupMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sCommon.tClinicMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId


DELETE FROM sCommon.tDurationMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sCommon.tExceptions WHERE CAST(LEFT(OrgId, 4) AS SMALLINT) = @rOrgId
DELETE FROM sCommon.tFileUpload WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sCommon.tFirstAidMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sCommon.tFunctionMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sCommon.tLocationMaster WHERE OrgId = @rOrgId
DELETE FROM sCommon.tOrganizationDepartmentMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sCommon.tPrefixSetup WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sCommon.tPublicHolidayMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sCommon.tPublicHolidayTypeMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sCommon.tReasonMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sCommon.tReportFormatGroupOrg WHERE OrgId = @rOrgId
 
DELETE FROM sCommunication.tAssignment WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sCommunication.tAssignmentScope WHERE CAST(LEFT(AssignmentId, 4) AS BIGINT) = @rOrgId
DELETE FROM sCommunication.tAssignmentView WHERE CAST(LEFT(AssignmentId, 4) AS BIGINT) = @rOrgId
DELETE FROM sCommunication.tAssignTask WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sCommunication.tBehaviour WHERE CAST(LEFT(AcademicId, 4) AS BIGINT) = @rOrgId
DELETE FROM sCommunication.tDiscussion WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sCommunication.tDiscussionComment WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sCommunication.tDiscussionGroup WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sCommunication.tDiscussionGroupMember WHERE CAST(LEFT(DiscussionGroupId, 4) AS BIGINT) = @rOrgId
DELETE FROM sCommunication.tPhotoCategoryOrg WHERE OrgId = @rOrgId
DELETE FROM sCommunication.tQueryCategoryOrg WHERE OrgId = @rOrgId
DELETE FROM sCommunication.tUploadBookLog WHERE CAST(LEFT(BookLogId, 4) AS BIGINT) = @rOrgId
DELETE FROM sCommunication.tUploadResult WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sConfig.tColorLegendDetail WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sConfig.tConfigurationSetup WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId AND SourceTypeId <> 2010
DELETE FROM sConfig.tCultureConfiguration WHERE OrgId = @rOrgId
DELETE FROM sConfig.tImport WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sConfig.tLocalDeviceSetting WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sConfig.tMachineMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sConfig.tMachinePrinterMapping WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sConfig.tPrinterMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sEExam.tTestAssign WHERE CAST(LEFT(TestId, 4) AS int) = @rOrgId
DELETE FROM sEExam.tTestMaster WHERE OrgId = @rOrgId
DELETE FROM sEExam.tTestParticipant WHERE CAST(LEFT(TestId, 4) AS BIGINT) = @rOrgId
DELETE FROM sEExam.tTestParticipantAnswer WHERE CAST(LEFT(TestId, 4) AS INT) = @rOrgId
DELETE FROM sEExam.tTestQuestion WHERE CAST(LEFT(TestId, 4) AS INT) = @rOrgId
DELETE FROM sFee.tChargeReceipt WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sFee.tChargeReceiptDetail WHERE CAST(LEFT(ChargeReceiptId, 4) AS BIGINT) = @rOrgId
DELETE FROM sFee.tFeeAllocation WHERE CAST(LEFT(SourceId, 4) AS BIGINT) = @rOrgId
DELETE FROM sFee.tFeeCustomSearch WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sFee.tFeeOptional WHERE CAST(LEFT(SourceId, 4) AS BIGINT) = @rOrgId
DELETE FROM sFee.tFeeSetup WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sFee.tReceipt WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sFee.tReceiptDetail WHERE CAST(LEFT(ReceiptId, 4) AS BIGINT) = @rOrgId
DELETE FROM sFixedAsset.tCategoryMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sFixedAsset.tLocationMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sFrontOffice.tVisitorLog WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sGSEB.tActivityIndicatorScore WHERE CAST(LEFT(ActivityId, 4) AS INT) = @rOrgId
DELETE FROM sGSEB.tAnusuchiB WHERE CAST(LEFT(AcademicId, 4) AS BIGINT) = @rOrgId
DELETE FROM sGSEB.tClassActivity WHERE CAST(LEFT(ActivityId, 4) AS INT) = @rOrgId
DELETE FROM sGSEB.tExamSetting WHERE CAST(LEFT(ClassId, 4) AS INT) = @rOrgId
DELETE FROM sGSEB.tGSEBExamMapping WHERE CAST(LEFT(BatchId, 4) AS INT) = @rOrgId
DELETE FROM sGSEB.tHetuMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sGSEB.tAnusuchiB WHERE CAST(LEFT(AcademicId, 4) AS BIGINT) = @rOrgId
DELETE FROM sGSEB.tResult WHERE CAST(LEFT(AcademicId, 4) AS BIGINT) = @rOrgId
DELETE FROM sGSEB.tResultDetail WHERE CAST(LEFT(AcademicId, 4) AS BIGINT) = @rOrgId
DELETE FROM sGSEB.tResultDetailOptional WHERE CAST(LEFT(AcademicId, 4) AS BIGINT) = @rOrgId
DELETE FROM sGSEB.tSubjectIndicatorMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sHostel.tAssignRoom WHERE CAST(LEFT(RoomId, 4) AS INT) = @rOrgId
DELETE FROM sHostel.tHostelWarden WHERE CAST(LEFT(HostelId, 4) AS INT) = @rOrgId
DELETE FROM sHrm.tEmployeeAttendance WHERE CAST(LEFT(EmployeeId, 4) AS BIGINT) = @rOrgId
DELETE FROM sHrm.tEmployeeCommunications WHERE CAST(LEFT(EmployeeId, 4) AS BIGINT) = @rOrgId
DELETE FROM sHrm.tEmployeeCustomSearch WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sHrm.tEmployeeDesignationMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sHrm.tEmployeeFamilyDetails WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sHrm.tEmployeeGradeMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sHrm.tEmployeeImages WHERE CAST(LEFT(EmployeeId, 4) AS BIGINT) = @rOrgId
DELETE FROM sHrm.tEmployeeJobDetail WHERE CAST(LEFT(EmployeeId, 4) AS BIGINT) = @rOrgId
DELETE FROM sHrm.tEmployeeMaster WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sHrm.tEmployeePersonalDetail WHERE CAST(LEFT(EmployeeId, 4) AS BIGINT) = @rOrgId
DELETE FROM sHrm.tEmployeePreviousEmployment WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sHrm.tEmployeeStatutoryAndOther WHERE CAST(LEFT(EmployeeId, 4) AS BIGINT) = @rOrgId
DELETE FROM sHrm.tEmployeeTypeMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sHrm.tGuestMaster WHERE OrgId = @rOrgId
DELETE FROM sHrm.tLeave WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sHrm.tLeaveTypeGradeSettings WHERE CAST(LEFT(OrgId, 4) AS SMALLINT) = @rOrgId
DELETE FROM sHrm.tLeaveTypeMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sHrm.tWorkingDays WHERE CAST(LEFT(BatchId, 4) AS INT) = @rOrgId
DELETE FROM sIp.tBinMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sIp.tItemStandardPriceLog WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sIp.tStockItemBin WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sIp.tStockItemPlanning WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sIp.tStockItemPurchaseUom WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sIp.tWeightedAverageCostLog WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sLibrary.tAssignOrganization WHERE OrgId = @rOrgId
DELETE FROM sLibrary.tBookLog WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sLibrary.tBookLogPenalty WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sLibrary.tBooksForClass WHERE CAST(LEFT(ClassId, 4) AS INT) = @rOrgId
DELETE FROM sLibrary.tIssueSetting WHERE CAST(LEFT(SourceId, 4) AS BIGINT) = @rOrgId
DELETE FROM sOmr.tAnswerKeySetup WHERE CAST(LEFT(ExamDetailId, 4) AS INT) = @rOrgId
DELETE FROM sOmr.tExamSetup WHERE CAST(LEFT(ExamDetailId, 4) AS INT) = @rOrgId
DELETE FROM sOmr.tScanHistory WHERE CAST(LEFT(AcademicId, 4) AS BIGINT) = @rOrgId
DELETE FROM sOmr.tSetting WHERE CAST(LEFT(OrgId, 4) AS SMALLINT) = @rOrgId
DELETE FROM sOmr.tSheetCallibration WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sOmr.tTempAnsKeyAnalysis WHERE CAST(LEFT(ExamDetailId, 4) AS INT) = @rOrgId
DELETE FROM sOrderEntry.tIssueReturn WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sOrderEntry.tIssueReturnDetail WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sOrderEntry.tOrderEntry WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sOrderEntry.tOrderEntryBatch WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sOrderEntry.tServiceItemTypeMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sProcurement.tFirstAidEmoloyee WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sProcurement.tFirstAidEmployeeDetail WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sProcurement.tFirstAidInspection WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sProcurement.tFirstAidInspectionDetail WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sProcurement.tGoodsReceiptNote WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sProcurement.tGoodsReceiptNoteBatch WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sProcurement.tGoodsReceiptNoteDetail WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sProcurement.tGoodsReceiptNoteReturn WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sProcurement.tGoodsReceiptNoteReturnBatch WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sProcurement.tGoodsReceiptNoteReturnDetail WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sProcurement.tPurchaseOrder WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sProcurement.tPurchaseOrderDetail WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sProcurement.tStockAdjustment WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sProcurement.tStockAdjustmentBatch WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sProcurement.tStockAdjustmentDetail WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sProcurement.tStockAudit WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sProcurement.tStockAuditDetail WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sProcurement.tStockBatch WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sProcurement.tStockFreezeAdjustment WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sProcurement.tStockFreezeAdjustmentDetail WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sProcurement.tStockInward WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sProcurement.tStockInwardBatch WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sProcurement.tStockInwardDetail WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sProcurement.tStockInwardRequest WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sProcurement.tStockInwardRequestDetail WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sProcurement.tStockInwardReturn WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sProcurement.tStockInwardReturnBatch WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sProcurement.tStockIssue WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sProcurement.tStockIssueBatch WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sProcurement.tStockIssueDetail WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sProcurement.tStockIssueRequest WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sProcurement.tStockIssueRequestDetail WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sProcurement.tStockItemFreeze WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sProcurement.tStockTransfer WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sProcurement.tStockTransferBatch WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sProcurement.tStockTransferDetail WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sProcurement.tStockTransferRequest WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sProcurement.tStockTransferRequestDetail WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sProcurement.tStockVerification WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sProcurement.tStockVerificationApproval WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sSecurity.tConfiguration WHERE CAST(LEFT(OrgId, 4) AS SMALLINT) = @rOrgId
DELETE FROM sSecurity.tDivisionPermission WHERE CAST(LEFT(UserId, 4) AS BIGINT) = @rOrgId
DELETE FROM sSecurity.tLdapUser WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sSecurity.tUser WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sSecurity.tUserAccess  WHERE CAST(LEFT(UserId, 4) AS int) = @rOrgId
DELETE FROM sSecurity.tUserFavoriteScreen WHERE CAST(LEFT(UserId, 4) AS BIGINT) = @rOrgId
DELETE FROM sSecurity.tUserLocation WHERE CAST(LEFT(StoreLocationId, 4) AS INT) = @rOrgId
DELETE FROM sSecurity.tUserLog WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sSecurity.tUserOrganization WHERE CAST(LEFT(OrgId, 4) AS SMALLINT) = @rOrgId
DELETE FROM sSecurity.tUserPreference WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sSecurity.tUserProfile WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sSecurity.tUserRole WHERE CAST(LEFT(UserId, 4) AS INT) = @rOrgId
DELETE FROM sSetup.tBatchClass WHERE CAST(LEFT(ClassId, 4) AS INT) = @rOrgId
DELETE FROM sSetup.tBatchMaster WHERE OrgId = @rOrgId
DELETE FROM sSetup.tClassMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sSetup.tClassSubject WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sSetup.tDepartmentMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sSetup.tDivisionMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
 
DELETE FROM sSetup.tReportConfiguration WHERE OrgId = @rOrgId
DELETE FROM sSetup.tReportSetting WHERE CAST(LEFT(OrgId, 4) AS SMALLINT) = @rOrgId
DELETE FROM sSetup.tSubjectMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sSetup.tTermMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sStudent.tAcademic WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sStudent.tAcademicDetail WHERE CAST(LEFT(AcademicId, 4) AS BIGINT) = @rOrgId
DELETE FROM sStudent.tStudentAdmission WHERE CAST(LEFT(StudentId, 4) AS BIGINT) = @rOrgId
DELETE FROM sStudent.tStudentCommunication WHERE CAST(LEFT(StudentId, 4) AS BIGINT) = @rOrgId
DELETE FROM sStudent.tStudentCustomSearch WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sStudent.tStudentFamily WHERE CAST(LEFT(StudentId, 4) AS BIGINT) = @rOrgId
DELETE FROM sStudent.tStudentHealth WHERE CAST(LEFT(StudentId, 4) AS BIGINT) = @rOrgId
DELETE FROM sStudent.tStudentImages WHERE CAST(LEFT(StudentId, 4) AS BIGINT) = @rOrgId
DELETE FROM sStudent.tStudentMaster WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sStudent.tStudentOther WHERE CAST(LEFT(StudentId, 4) AS BIGINT) = @rOrgId
DELETE FROM sSupport.tContactMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sSupport.tContactTypeMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sSupport.tImageMaster WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sSupport.tImageTypeMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sSupport.tLinkMaster WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sSupport.tVideoMaster WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sSupport.tVideoTypeMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sTax.tTaxRateSetup WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sTimetable.tDivisionWorkLoad WHERE CAST(LEFT(DivisionId, 4) AS INT) = @rOrgId
DELETE FROM sTimetable.tProxySetting WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sTimetable.tTeacherWorkLoad WHERE CAST(LEFT(DivisionId, 4) AS INT) = @rOrgId
DELETE FROM sTimetable.tTimeSetup WHERE CAST(LEFT(BatchId, 4) AS INT) = @rOrgId
DELETE FROM sTimetable.tTimeTable WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sTimetable.tTimeTableSchema WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sTransport.tAssignRoute WHERE CAST(LEFT(SourceId, 4) AS BIGINT) = @rOrgId
DELETE FROM sAssessment.tCCECSExamScore WHERE CAST(LEFT(ExamId, 4) AS INT) = @rOrgId
DELETE FROM sAssessment.tCCEFAExamScore WHERE CAST(LEFT(ExamId, 4) AS INT) = @rOrgId
DELETE FROM sAssessment.tExamCombineTerm WHERE CAST(LEFT(ExamId, 4) AS INT) = @rOrgId
DELETE FROM sAssessment.tGradeSujbectExamScore WHERE CAST(LEFT(ExamId, 4) AS INT) = @rOrgId
DELETE FROM sAssessment.tStudentRemark WHERE CAST(LEFT(ExamId, 4) AS INT) = @rOrgId
DELETE FROM sAssessment.tSubjectIndicatorMaster WHERE OrgId = @rOrgId
DELETE FROM sAssessment.tTempAllExam
DELETE FROM sAssessment.tTempCoScholasticExam

DELETE FROM sFee.tAccountMapping WHERE CAST(LEFT(FeeSetupId, 4) AS INT) = @rOrgId
DELETE FROM sFee.tDepositAdd WHERE CAST(LEFT(StudentId, 4) AS BIGINT) = @rOrgId
DELETE FROM sFee.tDepositAdjustment WHERE CAST(LEFT(StudentId, 4) AS BIGINT) = @rOrgId
DELETE FROM sFee.tDepositBalance WHERE CAST(LEFT(ClassId, 4) AS INT) = @rOrgId
DELETE FROM sFee.tDepositRefund WHERE CAST(LEFT(StudentId, 4) AS BIGINT) = @rOrgId
DELETE FROM sScholarship.tScholarshipEligibleStudent WHERE CAST(LEFT(AcademicId, 4) AS BIGINT) = @rOrgId
DELETE FROM sScholarship.tScholarshipMaster WHERE CAST(LEFT(BatchId, 4) AS BIGINT) = @rOrgId
DELETE FROM sScholarship.tScholarshipReceive WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sScholarship.tScholarshipStudentPaid WHERE CAST(LEFT(AcademicId, 4) AS BIGINT) = @rOrgId
DELETE FROM sSetup.tYearChangeDivisionMapping WHERE CAST(LEFT(OldDivisionId, 4) AS INT) = @rOrgId
DELETE FROM sAcademic.tClasswork WHERE CAST(LEFT(BatchId, 4) AS INT) = @rOrgId
DELETE FROM sAcademic.tLessonPlan WHERE CAST(LEFT(BatchId, 4) AS INT) = @rOrgId
DELETE FROM sAcademic.tLessonPlanResource WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sAcademic.tTopicMaster WHERE OrgId = @rOrgId
DELETE FROM sCertificate.tPrintTemplate WHERE OrgId = @rOrgId
DELETE FROM sCertificate.tPrintTemplateStudent WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sHostel.tStudentGatePass WHERE CAST(LEFT(StudentId, 4) AS INT) = @rOrgId
DELETE FROM sFee.tFeeHeadOrgwise WHERE OrgId = @rOrgId
DELETE FROM sFee.tReceiptBookOrgwise WHERE OrgId = @rOrgId

DELETE FROM sAcademic.tTeacherSubject WHERE CAST(LEFT(EmployeeId, 4) AS INT) = @rOrgId
DELETE FROM sAcademic.tTeacherSubjectDivision WHERE CAST(LEFT(EmployeeId, 4) AS INT) = @rOrgId
DELETE FROM sAdmission.tAdmissionCriteriaMaster WHERE OrgId = @rOrgId
--DELETE FROM sAdmission.tAdmissionCriteriaStudent WHERE CAST(LEFT(AdmissionSetupId, 4) AS INT) = @rOrgId
DELETE FROM sAdmission.tAdmissionFormSelected WHERE CAST(LEFT(AdmissionFormId, 4) AS INT) = @rOrgId
DELETE FROM sAdmission.tAdmissionSetup WHERE CAST(LEFT(BatchId, 4) AS INT) = @rOrgId
DELETE FROM sAttendance.tFilterCriteria WHERE OrgId = @rOrgId
DELETE FROM sAttendance.tFilterCriteriaDetail WHERE CAST(LEFT(FilterCriteriaId, 4) AS INT) = @rOrgId
DELETE FROM sAttendance.tYearlyRegister WHERE CAST(LEFT(AcademicId, 4) AS INT) = @rOrgId
DELETE FROM sFee.tWinfeeDetail WHERE CAST(LEFT(AcademicId, 4) AS INT) = @rOrgId
DELETE FROM sHrm.tEmployeeAttendanceRegister WHERE CAST(LEFT(EmployeeId, 4) AS INT) = @rOrgId
DELETE FROM sHrm.tEmployeeICardOrg WHERE OrgId = @rOrgId
DELETE FROM sSecurity.tUserDashlet WHERE CAST(LEFT(UserId, 4) AS INT) = @rOrgId
DELETE FROM sStudent.tICardOrg WHERE OrgId = @rOrgId

DELETE FROM sAdmission.tAdmissionSetupStudent WHERE CAST(LEFT(AdmissionSetupId, 4) AS INT) = @rOrgId
DELETE FROM sAssessment.tCCECSForClass WHERE CAST(LEFT(ClassId, 4) AS INT) = @rOrgId
DELETE FROM sAudit.tActivityLog WHERE CAST(LEFT(OrgId, 4) AS INT)  = @rOrgId
DELETE FROM sAudit.tReceiptDelete WHERE BatchId = @rOrgId
DELETE FROM sAudit.tReceiptDetailDelete WHERE CAST(LEFT(ReceiptId, 4) AS INT) = @rOrgId

DELETE FROM sCommunication.tViewResult WHERE CAST(LEFT(AcademicId, 4) AS INT) = @rOrgId
DELETE FROM sCommunication.tViewResultDetail WHERE CAST(LEFT(ExamId, 4) AS INT) = @rOrgId
DELETE FROM sSetup.tOrgInfo WHERE OrgId = @rOrgId

DELETE FROM sStudent.tStudentCustomTag WHERE CAST(LEFT(StudentId, 4) AS INT) = @rOrgId

DELETE FROM sTimetable.tAssignOrg WHERE OrgId = @rOrgId

DELETE FROM sAdmission.tAdmissionCriteria WHERE CAST(LEFT(BatchId, 4) AS INT) = @rOrgId
DELETE FROM sAdmission.tAdmissionFormFamilyDetail WHERE CAST(LEFT(AdmissionFormId, 4) AS BIGINT) = @rOrgId
DELETE FROM sAdmission.tAdmissionFormParentAcademic WHERE CAST(LEFT(AdmissionFormId, 4) AS BIGINT) = @rOrgId
DELETE FROM sAdmission.tAdmissionFormReference WHERE CAST(LEFT(AdmissionFormId, 4) AS BIGINT) = @rOrgId
DELETE FROM sAdmission.tAdmissionFormSibling WHERE CAST(LEFT(AdmissionFormId, 4) AS BIGINT) = @rOrgId
DELETE FROM sAdmission.tAdmissionFormStudentAcademic WHERE CAST(LEFT(AdmissionFormId, 4) AS BIGINT) = @rOrgId
DELETE FROM sAssessment.tCCESubjectActivityMaster WHERE OrgId = @rOrgId
DELETE FROM sAssessment.tCCESubjectSubActivityExamScore WHERE CAST(LEFT(ExamId, 4) AS BIGINT) = @rOrgId
DELETE FROM sAssessment.tCCESubjectSubActivityMaster WHERE OrgId = @rOrgId
DELETE FROM sAssessment.tResultAnalysis WHERE CAST(LEFT(ExamId, 4) AS BIGINT) = @rOrgId
DELETE FROM sAssessment.tResultAnalysisDetail WHERE CAST(LEFT(ExamId, 4) AS BIGINT) = @rOrgId
DELETE FROM sCommon.tReportOrg WHERE ScopeSourceId = @rOrgId AND ScopeSourceTypeId = 2021
DELETE FROM sAssessment.tCCESubjectSubActivityIndicatorMaster WHERE  OrgId = @rOrgId
DELETE FROM sAssessment.tResultAnalysisDivision WHERE CAST(LEFT(ExamId, 4) AS BIGINT) = @rOrgId
DELETE FROM sAssessment.tResultAnalysisDivisionDetail WHERE CAST(LEFT(ExamId, 4) AS BIGINT) = @rOrgId
DELETE FROM sFrontOffice.tStudentGatePass WHERE OrgId = @rOrgId
DELETE FROM sGoogle.tOrgCalander WHERE OrgId = @rOrgId
DELETE FROM sGoogle.tOrgDrive WHERE OrgId = @rOrgId
DELETE FROM sGoogle.tOrgYouTube WHERE OrgId = @rOrgId
DELETE FROM sHrm.tLeaveBalance WHERE CAST(LEFT(BatchId, 4) AS BIGINT) = @rOrgId
DELETE FROM sHrm.tLeaveBalanceAdd WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sTimetable.tAssignTeacher WHERE CAST(LEFT(EmployeeId, 4) AS BIGINT) = @rOrgId
DELETE FROM sTimetable.tDivision WHERE CAST(LEFT(OrgId, 4) AS INT) = @rOrgId
DELETE FROM sTimetable.tSubject WHERE CAST(LEFT(OrgId, 4) AS INT) = @rOrgId
DELETE FROM sTimetable.tSubjectTimeOff WHERE CAST(LEFT(SubjectId, 4) AS INT) = @rOrgId
DELETE FROM sTimetable.tTeacher WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sHrm.tEmployeeQualification WHERE OrgId = @rOrgId
DELETE FROM sSecurity.tUserDashboardNotification WHERE CAST(LEFT(UserId, 4) AS BIGINT) = @rOrgId
DELETE FROM sTransport.tAssignTransportOrg WHERE OrgId = @rOrgId

--DELETE FROM sFee.tOnlinePayment WHERE  CAST(LEFT(BatchId, 4) AS INT) = @rOrgId
--DELETE FROM sFee.tOnlinePaymentDetail WHERE  CAST(LEFT(OnlinePaymentId, 4) AS BIGINT) = @rOrgId
DELETE FROM sFee.tReceiptRefund WHERE  CAST(LEFT(BatchId, 4) AS INT) = @rOrgId
DELETE FROM sFee.tReceiptRefundDetail WHERE  CAST(LEFT(ReceiptRefundId, 4) AS BIGINT) = @rOrgId
DELETE FROM sIp.tUniformIssue WHERE  CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sIp.tUniformIssue WHERE  CAST(LEFT(AcademicId, 4) AS BIGINT) = @rOrgId
DELETE FROM sIp.tUniformItemForClass WHERE  CAST(LEFT(ClassId, 4) AS INT) = @rOrgId
DELETE FROM sIp.tUniformOrder WHERE  CAST(LEFT(AcademicId, 4) AS BIGINT) = @rOrgId
DELETE FROM sIp.tUniformOrderDetail WHERE  CAST(LEFT(UniformOrderId, 4) AS BIGINT) = @rOrgId
 
DELETE FROM sFee.tFeeInvoice WHERE CAST(LEFT(BatchId, 4) AS INT) = @rOrgId
DELETE FROM sFee.tFeeInvoiceDetail WHERE CAST(LEFT(FeeInvoiceId, 4) AS INT) = @rOrgId
DELETE FROM sFee.tOnlineFee WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sFee.tOnlineFeeDetail WHERE CAST(LEFT(OnlineFeeId, 4) AS INT) = @rOrgId
DELETE FROM sHrm.tCertificateEmployment WHERE CAST(LEFT(EmployeeId, 4) AS INT) = @rOrgId
DELETE FROM sOp.tPaymentTransaction WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sSetup.tOrgImages WHERE OrgId = @rOrgId
DELETE FROM sStudent.tStudentadditional WHERE CAST(LEFT(StudentId, 4) AS INT) = @rOrgId
DELETE FROM sStudent.tStudentBatchStatus WHERE CAST(LEFT(AcademicId, 4) AS INT) = @rOrgId

DELETE FROM sCommon.tPrefixConfig WHERE OrgId = @rOrgId
DELETE FROM sConfig.tDisplayFieldOrg WHERE OrgId = @rOrgId
DELETE FROM sHrm.tCertificateExperience WHERE OrgId = @rOrgId
DELETE FROM sHrm.tCertificateRelieving WHERE OrgId = @rOrgId
DELETE FROM sRFID.tAttendance WHERE OrgId = @rOrgId
DELETE FROM sRFID.tRegistration WHERE CAST(LEFT(RegistrtionId, 4) AS INT) = @rOrgId
DELETE FROM sSetup.tBatchClassLecture WHERE CAST(LEFT(BatchId, 4) AS INT) = @rOrgId
DELETE FROM sStudent.tStudentSibling WHERE CAST(LEFT(StudentId, 4) AS INT) = @rOrgId
DELETE FROM sStudent.tTranscriptAssessment WHERE CAST(LEFT(AcademicId, 4) AS INT) = @rOrgId
DELETE FROM sTally.tStudentLedgerMapping WHERE CAST(LEFT(StudentId, 4) AS INT) = @rOrgId

/* -- Date : 13/06/2016 -- */
DELETE FROM sActivity.tEventAttendance WHERE CAST(LEFT(SourceId, 4) AS INT) = @rOrgId
DELETE FROM sCanteen.tAssignOrganization WHERE OrgId = @rOrgId
DELETE FROM sCommunication.tRegisteredUsers WHERE OrgId = @rOrgId
DELETE FROM sStudent.tCollegeDetail WHERE CAST(LEFT(StudentId, 4) AS INT) = @rOrgId

-- 15.7.2016
DELETE FROM sFrontOffice.tInwardRegister WHERE OrgId = @rOrgId
DELETE FROM sFrontOffice.tOutwardRegister WHERE OrgId = @rOrgId
DELETE FROM sSetup.tSubjectGroupMaster WHERE OrgId = @rOrgId

/* -- Date : 12/08/2016 -- */
DELETE FROM sAssessment.tExamCombineSubject WHERE CAST(LEFT(ExamId, 4) AS INT) = @rOrgId
DELETE FROM sAssessment.tResultDetailOther WHERE CAST(LEFT(ExamId, 4) AS INT) = @rOrgId
DELETE FROM sSetup.tDivisionInchargeEmployee WHERE CAST(LEFT(DivisionId, 4) AS INT) = @rOrgId
DELETE FROM sStudent.tEnrollmentStatusOrg WHERE OrgId = @rOrgId
DELETE FROM sStudent.tEnrollmentStatusStudent WHERE CAST(LEFT(AcademicId, 4) AS INT) = @rOrgId
DELETE FROM sStudent.tLinkSibling WHERE CAST(LEFT(StudentId, 4) AS INT) = @rOrgId

/* -- Date : 17/09/2016 -- */

DELETE FROM sAssessment.tTempAllExamSubjectActivity WHERE CAST(LEFT(AcademicId, 4) AS INT) = @rOrgId
DELETE FROM sAttendance.tTempAttendance WHERE CAST(LEFT(AcademicId, 4) AS INT) = @rOrgId

/* -- Date : 05/10/2016 -- */

DELETE FROM sAdmission.tAdmissionInquiryFollowup WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
--DELETE FROM sAssessment.tStaticCCECSGroupMaster WHERE OrgId = @rOrgId
--DELETE FROM sAssessment.tStaticCCECSMaster WHERE OrgId = @rOrgId

/* -- Date : 20/10/2016 -- */

DELETE FROM sAssessment.tOptionalCCECS WHERE CAST(LEFT(AcademicId, 4) AS BIGINT) = @rOrgId

/* -- Date : 24/11/2016 -- */
DELETE FROM sBiometric.tMonthTrans WHERE CAST(LEFT(EmployeeId, 4) AS BIGINT) = @rOrgId

/* -- Date : 23/12/2016 -- */
DELETE FROM sAdmission.tAdmissionFormReceipt WHERE CAST(LEFT(BatchId, 4) AS INT) = @rOrgId
DELETE FROM sAssessment.tCCEExamStatus WHERE CAST(LEFT(BatchId, 4) AS INT) = @rOrgId
DELETE FROM sAttendance.tAttendanceGroup WHERE CAST(LEFT(BatchId, 4) AS INT) = @rOrgId
DELETE FROM sAttendance.tAttendanceGroupStudent WHERE CAST(LEFT(AcademicId, 4) AS BIGINT) = @rOrgId
DELETE FROM sFee.tAccountPosting WHERE CAST(LEFT(AccountId, 4) AS INT) = @rOrgId
DELETE FROM sHrm.tLeaveBalanceAddRequest WHERE CAST(LEFT(BatchId, 4) AS INT) = @rOrgId

/* -- Date : 14/02/2017 -- */

DELETE FROM sCRM.tChannelPartnerMaster WHERE OrgId = @rOrgId
DELETE FROM sCRM.tInstituteGroupMaster WHERE OrgId = @rOrgId
DELETE FROM sCRM.tInstituteMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sSetup.tOrganizationOtherDetail WHERE OrgId = @rOrgId

DELETE FROM sAppraisal.tConduct WHERE CAST(LEFT(BatchId, 4) AS INT) = @rOrgId
DELETE FROM sAssessment.tAllBatchClassGroup WHERE OrgId= @rOrgId
DELETE FROM sAssessment.tAllBatchResult WHERE CAST(LEFT(StudentId, 4) AS BIGINT) = @rOrgId
DELETE FROM sAssessment.tAllBatchSubject WHERE OrgId= @rOrgId
DELETE FROM sHrm.tEmployeeTravel WHERE OrgId= @rOrgId


DELETE FROM sLoan.tLoanDetail WHERE OrgId= @rOrgId
DELETE FROM sLoan.tLoanEMI WHERE CAST(LEFT(LoanDetailId, 4) AS BIGINT) = @rOrgId
DELETE FROM sLoan.tLoanPayrollMapping WHERE OrgId= @rOrgId
DELETE FROM sLoan.tLoanTypeMaster WHERE OrgId= @rOrgId
DELETE FROM sPayroll.tPayrollCustomSearch WHERE OrgId= @rOrgId
DELETE FROM sErp.tChannelMaster WHERE OrgId = @rOrgId

DELETE FROM sAccounting.tExpenseDetail WHERE CAST(LEFT(ExpenseId, 4) AS int) = @rOrgId
DELETE FROM sAccounting.tExpenseSubGroupMaster WHERE OrgId= @rOrgId
DELETE FROM sAppraisal.tAppraisalTypeMaster WHERE CAST(LEFT(BatchId, 4) AS int) = @rOrgId
DELETE FROM sAppraisal.tBusinessHeadsRatingStatus WHERE CAST(LEFT(AppraisalTypeId, 4) AS int) = @rOrgId
DELETE FROM sAppraisal.tKPAEmployee WHERE CAST(LEFT(BatchId, 4) AS int) = @rOrgId
DELETE FROM sAppraisal.tKPAEmployeeDetail WHERE CAST(LEFT(KPAEmployeeId, 4) AS bigint) = @rOrgId
DELETE FROM sAppraisal.tKPAEmployeeRating WHERE CAST(LEFT(KPAEmployeeId, 4) AS bigint) = @rOrgId
DELETE FROM sAppraisal.tKPAEmployeeRatingDetail WHERE CAST(LEFT(KPAEmployeeRatingId, 4) AS bigint) = @rOrgId
DELETE FROM sPoliciesForms.tFolderFile WHERE OrgId = @rOrgId
DELETE FROM sPoliciesForms.tFolderFilePermission WHERE CAST(LEFT(FolderFileId, 4) AS int) = @rOrgId


DELETE FROM sFee.tFeeMainGroupOptionalFee WHERE OrgId = @rOrgId
DELETE FROM sFee.tFeeStructureDetail WHERE CAST(LEFT(FeeStructureId, 4) AS int) = @rOrgId
DELETE FROM sFee.tFeeStructureMaster WHERE OrgId = @rOrgId
DELETE FROM sFrontOffice.tEmployeeGatePass WHERE OrgId = @rOrgId
DELETE FROM sHostel.tHostelStudentGatePass WHERE CAST(LEFT(StudentId, 4) AS bigint) = @rOrgId
DELETE FROM sHrm.tLeaveBalanceLog WHERE CAST(LEFT(EmployeeId, 4) AS bigint) = @rOrgId
DELETE FROM sTransport.tAttendanceRegister WHERE CAST(LEFT(SourceId, 4) AS bigint) = @rOrgId

DELETE FROM sAssessment.tCCESubjectActivityExamScore WHERE CAST(LEFT(AcademicId, 4) AS bigint) = @rOrgId
DELETE FROM sAssessment.tTempAll_Exam WHERE CAST(LEFT(AcademicId, 4) AS bigint) = @rOrgId
DELETE FROM sCanteen.tAttendanceForBreak WHERE CAST(LEFT(SourceId, 4) AS bigint) = @rOrgId
DELETE FROM sCanteen.tRegisterForBreak WHERE CAST(LEFT(SourceId, 4) AS bigint) = @rOrgId
DELETE FROM sCertificate.tTransfer WHERE OrgId = @rOrgId
DELETE FROM sCanteen.tRegisterForBreak WHERE CAST(LEFT(SourceId, 4) AS bigint) = @rOrgId

DELETE FROM sErp.tLeadFollowup WHERE CAST(LEFT(LeadId, 4) AS int) = @rOrgId
DELETE FROM sErp.tLeadMaster WHERE OrgId = @rOrgId


DELETE FROM sAdmission.tAdmissionHSCDetail WHERE CAST(LEFT(AdmissionFormId, 4) AS bigint) = @rOrgId
DELETE FROM sBiometric.tEmployeeCheckIn WHERE CAST(LEFT(EmployeeId, 4) AS bigint) = @rOrgId

DELETE FROM sBiometric.tEmployeeLateStatus WHERE CAST(LEFT(EmployeeId, 4) AS bigint) = @rOrgId

DELETE FROM sCommon.tSubmitDocumentMaster WHERE OrgId = @rOrgId
DELETE FROM sStudent.tStudentDocument WHERE CAST(LEFT(SubmitDocumentMasterId, 4) AS int) = @rOrgId
DELETE FROM sTimetable.tAnnualSubjectWorkLoad WHERE CAST(LEFT(BatchId, 4) AS int) = @rOrgId

DELETE FROM sFee.tReceiptDeleted WHERE CAST(LEFT(BatchId, 4) AS int) = @rOrgId
DELETE FROM sFee.tReceiptDetailDeleted WHERE CAST(LEFT(ReceiptId, 4) AS bigint) = @rOrgId

DELETE FROM sAttendance.tStudentLeaveRequest WHERE CAST(LEFT(AcademicId, 4) AS bigint) = @rOrgId
DELETE FROM sInfrastructure.tResourceMaster WHERE CAST(LEFT(Id, 4) AS int) = @rOrgId
DELETE FROM sInfrastructure.tResourceRequest WHERE CAST(LEFT(Id, 4) AS bigint) = @rOrgId

DELETE FROM sAlumni.tRegistration WHERE OrgId = @rOrgId
DELETE FROM sBiometric.tMonthlyStatusUpdate WHERE CAST(LEFT(EmployeeId, 4) AS bigint) = @rOrgId
DELETE FROM sErp.tDSR WHERE OrgId = @rOrgId
DELETE FROM sErp.tDSRWorkTypeMaster WHERE OrgId = @rOrgId
DELETE FROM sErp.tProjectMaster WHERE OrgId = @rOrgId
DELETE FROM sFee.tFeeFollowup WHERE CAST(LEFT(AcademicId, 4) AS bigint) = @rOrgId
 
DELETE FROM sActivity.tWeekOffSetting WHERE CAST(LEFT(SourceId, 4) AS bigint) = @rOrgId
DELETE FROM sAssessment.tAllBatchResultCoScholestic WHERE CAST(LEFT(StudentId, 4) AS bigint) = @rOrgId
DELETE FROM sHrm.tEmployeeDocument WHERE CAST(LEFT(EmployeeId, 4) AS bigint) = @rOrgId
DELETE FROM sStudent.tChangeIdLog WHERE CAST(LEFT(StudentId, 4) AS bigint) = @rOrgId
DELETE FROM sAlert.tAssociateRecipient WHERE CAST(LEFT(ForUserId, 4) AS bigint) = @rOrgId

DELETE FROM sAcademic.tPreLessonPlan WHERE CAST(LEFT(BatchId, 4) AS int) = @rOrgId
DELETE FROM sAssessment.tAllBatchResultGrade WHERE CAST(LEFT(StudentId, 4) AS bigint) = @rOrgId

DELETE FROM sVts.tvtsClassMaster WHERE CAST(LEFT(ClassId, 4) AS int) = @rOrgId
DELETE FROM sVts.tvtsOrganizationMaster WHERE OrgId = @rOrgId
DELETE FROM sVts.tvtsStudent WHERE CAST(LEFT(StudentId, 4) AS bigint) = @rOrgId
DELETE FROM sErp.tLeadChannelPartnerMaster WHERE  OrgId = @rOrgId


DELETE FROM sAlumni.tStudentMapping WHERE CAST(LEFT(StudentId, 4) AS bigint) = @rOrgId
DELETE FROM sErp.tUserFeedback WHERE CAST(LEFT(UserId, 4) AS bigint) = @rOrgId
DELETE FROM sFee.tFeeExpense WHERE CAST(LEFT(AcademicId, 4) AS bigint) = @rOrgId


DELETE FROM sAdmission.tAdmissionCriteriaForm WHERE CAST(LEFT(BatchId, 4) AS int) = @rOrgId
DELETE FROM sAdmission.tAdmissionFormField WHERE CAST(LEFT(AdmissionFormId, 4) AS bigint) = @rOrgId
DELETE FROM sAssessment.tGradeSetClassSubjectDetail WHERE CAST(LEFT(Id, 4) AS int) = @rOrgId
DELETE FROM sAssessment.tGradeSetClassSubjectMaster WHERE OrgId = @rOrgId
DELETE FROM sBiometric.BioDetailMapping WHERE OrgId = @rOrgId
DELETE FROM sBiometric.tLog WHERE OrgId = @rOrgId

DELETE FROM sCertificate.tOtherCertificate WHERE OrgId = @rOrgId
DELETE FROM sWorkflow.tApprovalAction WHERE CAST(LEFT(ActionUserId, 4) AS bigint) = @rOrgId
DELETE FROM sWorkflow.tApprovalRequest WHERE CAST(LEFT(BatchId, 4) AS int) = @rOrgId
DELETE FROM sWorkflow.tFunctionalityApprovingAuthority WHERE OrgId = @rOrgId
DELETE FROM sWorkflow.tFunctionalityApprovingDepartment WHERE OrgId = @rOrgId

DELETE FROM sBiometric.tProcess WHERE CAST(LEFT(SourceId, 4) AS bigint) = @rOrgId
DELETE FROM sAssessment.tConfiguration WHERE OrgId = @rOrgId

DELETE FROM sAcademic.tHomeworkCheck WHERE CAST(LEFT(AcademicId, 4) AS bigint) = @rOrgId

DELETE FROM sAdmission.tAdmissionCriteriaFee WHERE CAST(LEFT(BatchId, 4) AS int) = @rOrgId
DELETE FROM sAdmission.tAdmissionFormFee WHERE CAST(LEFT(AdmissionFormId, 4) AS bigint) = @rOrgId


DELETE FROM sFee.tFeeOpening WHERE CAST(LEFT(AcademicId, 4) AS bigint) = @rOrgId
DELETE FROM sTransport.tChangeRouteLog WHERE CAST(LEFT(SourceId, 4) AS bigint) = @rOrgId

DELETE FROM sAcademic.tClassworkConfig WHERE OrgId = @rOrgId
DELETE FROM sBiometric.tPunchData WHERE CAST(LEFT(StudentID, 4) AS bigint) = @rOrgId
DELETE FROM sErp.tCallLog WHERE CAST(LEFT(EmployeeId, 4) AS bigint) = @rOrgId
DELETE FROM sErp.tMarketingActivityPlan WHERE CAST(LEFT(EmployeeId, 4) AS bigint) = @rOrgId
--DELETE FROM tMarketingActivityStatus WHERE CAST(LEFT(EmployeeId, 4) AS bigint) = @rOrgId
DELETE FROM sErp.tTripLog WHERE CAST(LEFT(EmployeeId, 4) AS bigint) = @rOrgId


DELETE FROM sAudit.HistoryLog WHERE CAST(LEFT(SourceId, 4) AS bigint) = @rOrgId
DELETE FROM sAudit.tOperationLog WHERE CAST(LEFT(SourceId, 4) AS int) = @rOrgId

--DELETE FROM sErp.tCustomerTicket WHERE OrgId= @rOrgId
DELETE FROM sPayroll.tPayProcessEmployeeRemark WHERE CAST(LEFT(EmployeeId, 4) AS int) = @rOrgId


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

DELETE FROM sSetup.tOrganizationMaster WHERE Id = @rOrgId
DELETE FROM sCommon.tTableRowId WHERE OrgId = @rOrgId


DELETE FROM sAlert.tAlertLogHistory WHERE OrgId= @rOrgId
DELETE FROM sAlert.tNotificationLogHistory WHERE CAST(LEFT(CreatedUserId, 4) AS bigint) = @rOrgId
DELETE FROM sHrm.tBatchEmployeeCommunications WHERE CAST(LEFT(EmployeeId, 4) AS bigint) = @rOrgId
DELETE FROM sHrm.tBatchEmployeeFamilyDetails WHERE CAST(LEFT(EmployeeId, 4) AS bigint) = @rOrgId
DELETE FROM sHrm.tBatchEmployeeJobDetail WHERE OrgId= @rOrgId
DELETE FROM sHrm.tBatchEmployeeMaster WHERE OrgId= @rOrgId
DELETE FROM sHrm.tBatchEmployeePersonalDetail WHERE OrgId= @rOrgId
DELETE FROM sHrm.tBatchEmployeeStatutoryAndOther WHERE CAST(LEFT(EmployeeId, 4) AS bigint) = @rOrgId
DELETE FROM sSecurity.tUserLogHistory WHERE OrgId= @rOrgId
DELETE FROM sStudent.tAcademicStudent WHERE CAST(LEFT(AcademicId, 4) AS bigint) = @rOrgId
DELETE FROM sStudent.tAcademicStudentAdditional WHERE CAST(LEFT(AcademicId, 4) AS bigint) = @rOrgId
DELETE FROM sStudent.tAcademicStudentCommunication WHERE CAST(LEFT(AcademicId, 4) AS bigint) = @rOrgId
DELETE FROM sStudent.tAcademicStudentFamily WHERE CAST(LEFT(AcademicId, 4) AS bigint) = @rOrgId
DELETE FROM sStudent.tAcademicStudentHealth WHERE CAST(LEFT(AcademicId, 4) AS bigint) = @rOrgId
DELETE FROM sStudent.tAcademicStudentOther WHERE CAST(LEFT(AcademicId, 4) AS bigint) = @rOrgId
DELETE FROM sStudent.tStudentCustomFieldData WHERE CAST(LEFT(StudentId, 4) AS bigint) = @rOrgId
DELETE FROM sStudent.tStudentMasterDelete WHERE OrgId= @rOrgId

DELETE FROM sAudit.ChangeLog WHERE CAST(LEFT(SourceId, 4) AS bigint) = @rOrgId
DELETE FROM sHrm.tCertificateIncrement WHERE OrgId= @rOrgId
DELETE FROM sAudit.ChangeLog WHERE CAST(LEFT(ScreenId, 4) AS bigint) = @rOrgId

DELETE FROM sAcademic.tClassworkView WHERE CAST(LEFT(AcademicId, 4) AS bigint) = @rOrgId
DELETE FROM sBiometric.tPunchCount WHERE CAST(LEFT(SourceId, 4) AS bigint) = @rOrgId

DELETE FROM sFrontOffice.tOTPLog WHERE CAST(LEFT(CreatedUserId, 4) AS bigint) = @rOrgId
DELETE FROM sHrm.tLeaveDeduction WHERE CAST(LEFT(EmployeeId, 4) AS bigint) = @rOrgId


DELETE FROM sAdmission.tAdmissionCriteriaDocument WHERE CAST(LEFT(BatchId, 4) AS int) = @rOrgId
DELETE FROM sAdmission.tAdmissionStudentDocument WHERE CAST(LEFT(AdmissionFormId, 4) AS bigint) = @rOrgId
DELETE FROM sTimetable.tTimeTableTime WHERE CAST(LEFT(DivisionId, 4) AS int) = @rOrgId
DELETE FROM sHrm.tEmployeeWorkingDays WHERE CAST(LEFT(BatchId, 4) AS int) = @rOrgId

DELETE FROM sErp.tContactBookMaster WHERE OrgId= @rOrgId
DELETE FROM sErp.tEmployeeERPDetail WHERE CAST(LEFT(EmployeeId, 4) AS bigint) = @rOrgId
DELETE FROM sFrontOffice.tLostFoundRegisterScope WHERE CAST(LEFT(SourceId, 4) AS int) = @rOrgId
DELETE FROM sHrm.tEmployeeChangeHistory WHERE CAST(LEFT(EmployeeId, 4) AS bigint) = @rOrgId
DELETE FROM sCommon.tReportTemplate WHERE OrgId= @rOrgId
DELETE FROM sTransport.tBusRouteAssignedTo WHERE CAST(LEFT(SourceId, 4) AS bigint) = @rOrgId
DELETE FROM sWorkflow.tStudentDataChange WHERE CAST(LEFT(SourceId, 4) AS bigint) = @rOrgId

DELETE FROM sAcademic.tOnlineLearning WHERE CAST(LEFT(BatchId, 4) AS int) = @rOrgId
DELETE FROM sAcademic.tOnlineLearningAssignment WHERE CAST(LEFT(OnlineLearningId, 4) AS bigint) = @rOrgId
DELETE FROM sAcademic.tOnlineLearningAssignmentSubmit WHERE CAST(LEFT(OnlineLearningId, 4) AS bigint) = @rOrgId
DELETE FROM sAcademic.tOnlineLearningAttendance WHERE CAST(LEFT(OnlineLearningId, 4) AS bigint) = @rOrgId
DELETE FROM sAcademic.tOnlineLearningAttendanceLog WHERE CAST(LEFT(OnlineLearningId, 4) AS bigint) = @rOrgId
DELETE FROM sAcademic.tOnlineLearningReference WHERE CAST(LEFT(OnlineLearningId, 4) AS bigint) = @rOrgId
DELETE FROM sAcademic.tOnlineLearningResource WHERE CAST(LEFT(OnlineLearningId, 4) AS bigint) = @rOrgId
DELETE FROM sAcademic.tOnlineLearningScope WHERE CAST(LEFT(OnlineLearningId, 4) AS bigint) = @rOrgId
DELETE FROM sAcademic.tTempOnlineLearningScope WHERE CAST(LEFT(SourceId, 4) AS bigint) = @rOrgId
DELETE FROM sCommunication.tChat WHERE CAST(LEFT(FromSourceId, 4) AS bigint) = @rOrgId
DELETE FROM sCommunication.tTempChatGroupScope WHERE CAST(LEFT(MemberSourceId, 4) AS bigint) = @rOrgId


DELETE FROM sAcademic.tOnlineMeetingSettings WHERE CAST(LEFT(OnlineLearningId, 4) AS bigint) = @rOrgId
DELETE FROM sStudent.tDigitalForm WHERE OrgId= @rOrgId
DELETE FROM sStudent.tDigitalFormScope WHERE CAST(LEFT(DigitalFormId, 4) AS int) = @rOrgId
DELETE FROM sStudent.tDigitalFormField WHERE CAST(LEFT(DigitalFormId, 4) AS int) = @rOrgId
DELETE FROM sStudent.tDigitalFormStudent WHERE CAST(LEFT(DigitalFormId, 4) AS int) = @rOrgId

DELETE FROM sAcademic.tOnlineLearningView WHERE CAST(LEFT(AcademicId, 4) AS bigint) = @rOrgId

DELETE FROM sOp.tPaymentTransactionHistory WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sFee.tOnlineFeeHistory WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sFee.tOnlineFeeDetailHistory WHERE CAST(LEFT(OnlineFeeId, 4) AS INT) = @rOrgId
DELETE FROM sCommunication.tStudentDocumentUpload WHERE CAST(LEFT(BatchId, 4) AS INT) = @rOrgId

DELETE FROM sFee.tFeeAllocationHistory WHERE CAST(LEFT(SourceId, 4) AS bigint) = @rOrgId

DELETE FROM sCommon.tUploadDocument WHERE CAST(LEFT(CreatedUserId, 4) AS bigint) = @rOrgId

DELETE FROM sFee.tFeeAllocationStudent WHERE CAST(LEFT(AcademicId, 4) AS bigint) = @rOrgId
DELETE FROM sFee.tFeeClassBatchStatus WHERE CAST(LEFT(BatchId, 4) AS int) = @rOrgId
DELETE FROM sHrm.tEmployeeBatch WHERE CAST(LEFT([EmployeeId], 4) AS bigint) = @rOrgId
DELETE FROM sCommunication.tEmployeeDocumentUpload WHERE OrgId = @rOrgId

DELETE FROM [sHrm].[tEmployeeCustomFieldData] WHERE CAST(LEFT([EmployeeId], 4) AS bigint) = @rOrgId

DELETE FROM [sCommunication].[tDailyThoughtAssign] WHERE OrgId= @rOrgId
DELETE FROM [sFee].[tEMandate] WHERE CAST(LEFT(Id, 4) AS bigint) = @rOrgId

DELETE FROM [sAdmission].[tAdmissionInquiryCriteria] WHERE CAST(LEFT([ClassId], 4) AS int) = @rOrgId
DELETE FROM [sCommon].[tSubmitDocumentScope] WHERE CAST(LEFT([SubmitDocumentId], 4) AS int) = @rOrgId

DELETE FROM sAcademic.tOnlineLearningRecording WHERE CAST(LEFT([OnlineLearningId], 4) AS bigint) = @rOrgId

DELETE FROM [sCommon].[tUserToken] WHERE CAST(LEFT([UserId], 4) AS bigint) = @rOrgId

DELETE FROM [sBiometric].[tEmployeeConfiguration] WHERE CAST(LEFT([EmployeeId], 4) AS bigint) = @rOrgId
DELETE FROM sAlert.tWhatsAppConfiguration WHERE OrgId= @rOrgId
DELETE FROM sFee.tDepositSetup WHERE CAST(LEFT([StudentId], 4) AS bigint) = @rOrgId
DELETE FROM [sAlert].[tWhatsAppLog] WHERE CAST(LEFT([SourceId], 4) AS bigint) = @rOrgId

DELETE FROM sAcademic.tOnlineLearningHistoryLog WHERE CAST(LEFT([BatchId], 4) AS int) = @rOrgId

DELETE FROM [sAlert].[tAlertTrack] WHERE OrgId = @rOrgId
DELETE FROM sTally.tJVPosting WHERE CAST(LEFT([StudentId], 4) AS bigint) = @rOrgId

DELETE FROM [sHrm].[tLeavePeriod] WHERE OrgId = @rOrgId
DELETE FROM [sRecruitment].[tAssignOrganization] WHERE OrgId = @rOrgId

DELETE FROM sAdmission.tAdmissionCustomSearch WHERE OrgId = @rOrgId

DELETE FROM[sCommunication].[tTempQueryCategoryScope] WHERE CAST(LEFT([SourceId], 4) AS bigint) = @rOrgId


DELETE FROM [sStudent].[tOnlineRegistrationStudentAdmission] WHERE CAST(LEFT([StudentId], 4) AS bigint) = @rOrgId
DELETE FROM [sStudent].[tOnlineRegistrationStudentCommunication] WHERE CAST(LEFT([StudentId], 4) AS bigint) = @rOrgId
DELETE FROM [sStudent].[tOnlineRegistrationStudentCustomFieldData] WHERE CAST(LEFT([StudentId], 4) AS bigint) = @rOrgId
DELETE FROM [sStudent].[tOnlineRegistrationStudentDocument] WHERE CAST(LEFT([StudentId], 4) AS bigint) = @rOrgId
DELETE FROM [sStudent].[tOnlineRegistrationStudentFamily] WHERE CAST(LEFT([StudentId], 4) AS bigint) = @rOrgId
DELETE FROM [sStudent].[tOnlineRegistrationStudentImages] WHERE CAST(LEFT([StudentId], 4) AS bigint) = @rOrgId
DELETE FROM [sStudent].[tOnlineRegistrationStudentOther] WHERE CAST(LEFT([StudentId], 4) AS bigint) = @rOrgId
DELETE FROM [sStudent].[tOnlineRegistrationCollegeDetail] WHERE CAST(LEFT([StudentId], 4) AS bigint) = @rOrgId
DELETE FROM [sStudent].[tOnlineRegistrationDisplayField]  WHERE CAST(LEFT([BatchId], 4) AS int) = @rOrgId
DELETE FROM [sStudent].[tOnlineRegistrationCriteriaDocument]  WHERE CAST(LEFT([BatchId], 4) AS int) = @rOrgId
DELETE FROM [sStudent].[tOnlineRegistrationCriteriaForm]  WHERE CAST(LEFT([BatchId], 4) AS int) = @rOrgId
DELETE FROM [sStudent].[tOnlineRegistrationStudentMaster] WHERE OrgId = @rOrgId

DELETE FROM [sBiometric].[tShiftAllocationCloud] WHERE CAST(LEFT([SourceId], 4) AS bigint) = @rOrgId
DELETE FROM [sBiometric].[tCloudTransactionData] WHERE CAST(LEFT([SourceId], 4) AS bigint) = @rOrgId

DELETE FROM [sTransport].[tAssignRouteLog] WHERE CAST(LEFT([SourceId], 4) AS bigint) = @rOrgId
DELETE FROM [sAttendance].[tAttendanceFollowup] WHERE CAST(LEFT([AcademicId], 4) AS bigint) = @rOrgId

DELETE FROM sAssessment.tAssessmentLabelSetup WHERE OrgId = @rOrgId
DELETE FROM [sAssessment].[tStudentExamRemark] WHERE CAST(LEFT([AcademicId], 4) AS bigint) = @rOrgId
DELETE FROM [sBiometric].[tDeviceMasterCloud] WHERE OrgId = @rOrgId

DELETE FROM [sHrm].[tDigitalForm] WHERE OrgId = @rOrgId
DELETE FROM [sHrm].[tDigitalFormField] WHERE CAST(LEFT([DigitalFormId], 4) AS int) = @rOrgId
DELETE FROM [sHrm].[tDigitalFormScope] WHERE CAST(LEFT([DigitalFormId], 4) AS int) = @rOrgId
DELETE FROM [sHrm].[tDigitalFormEmployee] WHERE CAST(LEFT([DigitalFormId], 4) AS int) = @rOrgId
DELETE FROM [sAdmission].[tAdmissionOptionalSubject] WHERE CAST(LEFT([AdmissionFormId], 4) AS bigint) = @rOrgId
DELETE FROM [sStudent].[tOnlineRegistrationStudentOptionalSubject] WHERE CAST(LEFT([OnlineRegistrationStudentId], 4) AS bigint) = @rOrgId
DELETE FROM [sStudent].[tOnlineRegistrationCriteria] WHERE CAST(LEFT([BatchId], 4) AS int) = @rOrgId
DELETE FROM [sStudent].[tOnlineRegistrationCriteriaOptionalSubject] WHERE CAST(LEFT([BatchId], 4) AS int) = @rOrgId
DELETE FROM [sAdmission].[tAdmissionCriteriaOptionalSubject] WHERE CAST(LEFT([BatchId], 4) AS int) = @rOrgId

DELETE FROM [sAlert].[tAlertTrackHistory] WHERE OrgId = @rOrgId
DELETE FROM [sActivity].[tEventInchargeAssign] WHERE CAST(LEFT([SourceId], 4) AS bigint) = @rOrgId
DELETE FROM [sLibrary].[tNewspaperLog] WHERE CAST(LEFT([NewspaperId], 4) AS int) = @rOrgId
DELETE FROM sSetup.tClassContentSetup WHERE CAST(LEFT([ClassId], 4) AS int) = @rOrgId

DELETE FROM[sHrm].[tCertificateJoining] WHERE [OrgId] = @rOrgId
DELETE FROM[sCommunication].[tTempMultiPhotoCategoryScope] WHERE CAST(LEFT([SourceId], 4) AS bigint) = @rOrgId

DELETE FROM[sStudent].[tDigitalFormStudentStatus] WHERE CAST(LEFT([AcademicId], 4) AS bigint) = @rOrgId
DELETE FROM[sHrm].[tDigitalFormEmployeeStatus] WHERE CAST(LEFT([EmployeeId], 4) AS bigint) = @rOrgId
DELETE FROM[sHrm].[tLeaveHierarchyLevel] WHERE CAST(LEFT([LeaveId], 4) AS bigint) = @rOrgId

DELETE FROM [sAudit].[tChargeDeleted] WHERE [OrgId] = @rOrgId
DELETE FROM [sAudit].[tChargeDetailDelete] WHERE CAST(LEFT([ChargeReceiptId], 4) AS bigint) = @rOrgId

DELETE FROM sFee.tLateFeeRuleMaster WHERE OrgId = @rOrgId
DELETE FROM sAlert.tAlertQueueLog WHERE OrgId = @rOrgId



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

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


GO

ALTER PROCEDURE [sStudent].[pRptStudentStrengthDaywiseGet]
	 
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 @rOrgId smallint,
	 @rBatchId int,
	 @rClassId int,
	 @rDivisionId int,
	 @rReportId int=0,
	 @rDepartmentId int,
	
	-- @rStatus bit,
	 --@rOrgGroupBatchId int,
	-- @rStatusClass bit,
	 @rMonth nvarchar(10)='',
	 @rYear nvarchar(10)=''
  
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 


DECLARE @lMonthDays int

SELECT @lMonthDays = sCommon.fGetDaysInMonth(@rMonth,@rYear)
	SELECT 
			@lMonthDays AS MonthDays,
			Dept.Id AS DepartmentId,
			@rBuilder1 AS Builder1,
		    
		    (
			select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND ((YEAR(SR.AttendanceDate)=@rYear) OR (@rYear= 0))
	        AND ((MONTH(SR.AttendanceDate)=@rMonth) OR (@rMonth= 0))
	        AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id AND SR.AttendanceTypeId =1
			)
			AS BT,
			
			(
			select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND ((YEAR(SR.AttendanceDate)=@rYear) OR (@rYear= 0))
	        AND ((MONTH(SR.AttendanceDate)=@rMonth) OR (@rMonth= 0))
	        AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id AND SR.AttendanceTypeId =1
			)
			AS GT,		
			
			(
			select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '01' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=1 AND SR.AttendanceTypeId =1
			)
			 AS PB1,
			
			(
			select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '01' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=1	AND SR.AttendanceTypeId=1
			)
			 AS PG1,
			(
			select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate= (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '01' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=0	AND SR.AttendanceTypeId=1
			)AS ABB1,
			(
			select count(A.Id) FROM  sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '01' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=0	AND SR.AttendanceTypeId=1
			) AS ABG1,
			(
			select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.LeftDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '01' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id
			) AS LB1,
			(
			select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.LeftDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '01' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id
			) AS LG1,
			(
			select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.AdmissionDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '01' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id
			) AS NAB1,
			(
			select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.AdmissionDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '01' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id 
			) AS NAG1,
			
			(
			select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '02' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=1 AND SR.AttendanceTypeId=1
			) AS PB2,
			(
			select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '02' )) AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=1 AND SR.AttendanceTypeId=1
			) AS PG2,
			(
			select count(A.Id) FROM  sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '02' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=0 AND SR.AttendanceTypeId=1
			) AS ABB2,
			(
			select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '02' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=0 AND SR.AttendanceTypeId=1
			) AS ABG2,
			(
			select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.LeftDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '02' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id
			) AS LB2,
			(
			select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.LeftDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '02' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id
			) AS LG2,
			(
			select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.AdmissionDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '02' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id
			) AS NAB2,
			(
			select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId			
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.AdmissionDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '02' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id
			) AS NAG2,
			
			(
			select count(A.Id) FROM  sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '03' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id AND  SR.IsPresent=1 AND  SR.AttendanceTypeId=1
			) AS PB3,
			(
			select count(A.Id) FROM  sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '03' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=1 AND SR.AttendanceTypeId=1
			) AS PG3,
			(
			select count(A.Id) FROM  sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '03' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=0 AND SR.AttendanceTypeId=1
			) AS ABB3,
			(
			select count(A.Id) FROM  sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '03' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=0 AND SR.AttendanceTypeId=1
			) AS ABG3,
			(
			select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.LeftDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '03' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id
			) AS LB3,
			(
			select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.LeftDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '03' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id
			) AS LG3,
			(
			select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId			 
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.AdmissionDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '03' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id
			) AS NAB3,
			(
			select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId			 
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.AdmissionDate =(convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '03' )) AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id
			) AS NAG3,
			
			(select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '04' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=1 AND SR.AttendanceTypeId =1
			) AS PB4,
			(select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '04' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=1	AND SR.AttendanceTypeId=1
			) AS PG4,
			(select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate= (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '04' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=0	AND SR.AttendanceTypeId=1
			) AS ABB4,
			(select count(A.Id) FROM  sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '04' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=0	AND SR.AttendanceTypeId=1
			) AS ABG4,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.LeftDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '04' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id
			) AS LB4,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.LeftDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '04' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id
			) AS LG4,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.AdmissionDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '04' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id
			) AS NAB4,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.AdmissionDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '04' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id
			) AS NAG4,
			
			(select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '05' )) AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=1 AND SR.AttendanceTypeId =1
			) AS PB5,
			(select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '05' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=1	AND SR.AttendanceTypeId=1
			) AS PG5,
			(select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate= (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '05' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=0	AND SR.AttendanceTypeId=1
			) AS ABB5,
			(select count(A.Id) FROM  sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '05' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=0	AND SR.AttendanceTypeId=1
			) AS ABG5,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.LeftDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '05' )) AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id
			) AS LB5,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.LeftDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '05' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id
			) AS LG5,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.AdmissionDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '05' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id
			) AS NAB5,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.AdmissionDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '05' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id 
			) AS NAG5,
			
			(select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '06' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=1 AND SR.AttendanceTypeId =1
			) AS PB6,
			(select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '06' )) AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=1	AND SR.AttendanceTypeId=1
			) AS PG6,
			(select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate= (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '06' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=0	AND SR.AttendanceTypeId=1
			) AS ABB6,
			(select count(A.Id) FROM  sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '06' )) AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=0	AND SR.AttendanceTypeId=1
			) AS ABG6,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.LeftDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '06' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id
			) AS LB6,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.LeftDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '06' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id
			) AS LG6,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.AdmissionDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '06' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id
			) AS NAB6,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.AdmissionDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '06' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id 
			) AS NAG6,
			
			(select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '07' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=1 AND SR.AttendanceTypeId =1
			) AS PB7,
			(select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '07' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=1	AND SR.AttendanceTypeId=1
			) AS PG7,
			(select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate= (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '07' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=0	AND SR.AttendanceTypeId=1
			) AS ABB7,
			(select count(A.Id) FROM  sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '07' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=0	AND SR.AttendanceTypeId=1
			) AS ABG7,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.LeftDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '07' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id
			) AS LB7,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.LeftDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '07' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id
			) AS LG7,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.AdmissionDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '07' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id
			) AS NAB7,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.AdmissionDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '07' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id 
			) AS NAG7,
			
			(select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '08' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=1 AND SR.AttendanceTypeId =1
			) AS PB8,
			(select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '08' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=1	AND SR.AttendanceTypeId=1
			) AS PG8,
			(select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate= (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '08' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=0	AND SR.AttendanceTypeId=1
			) AS ABB8,
			(select count(A.Id) FROM  sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '08' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=0	AND SR.AttendanceTypeId=1
			) AS ABG8,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.LeftDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '08' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id
			) AS LB8,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.LeftDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '08' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id
			) AS LG8,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.AdmissionDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '08' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id
			) AS NAB8,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.AdmissionDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '08' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id 
			) AS NAG8,
			
			(select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '09' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=1 AND SR.AttendanceTypeId =1
			) AS PB9,
			(select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '09' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=1	AND SR.AttendanceTypeId=1
			) AS PG9,
			(select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate= (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '09' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=0	AND SR.AttendanceTypeId=1) AS ABB9,
			(select count(A.Id) FROM  sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '09' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=0	AND SR.AttendanceTypeId=1
			) AS ABG9,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.LeftDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '09' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id
			) AS LB9,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.LeftDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '09' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id) AS LG9,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.AdmissionDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '09' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id
			) AS NAB9,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.AdmissionDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '09' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id 
			) AS NAG9,
			
			(select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '10' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=1 AND SR.AttendanceTypeId =1
			) AS PB10,
			(select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '10' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=1	AND SR.AttendanceTypeId=1
			) AS PG10,
			(select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate= (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '10' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=0	AND SR.AttendanceTypeId=1
			) AS ABB10,
			(select count(A.Id) FROM  sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '10' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=0	AND SR.AttendanceTypeId=1
			) AS ABG10,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.LeftDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '10' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id
			) AS LB10,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.LeftDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '10' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id
			) AS LG10,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.AdmissionDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '10' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id
			) AS NAB10,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.AdmissionDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '10' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id 
			) AS NAG10,
			
			(select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '11' )) AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=1 AND SR.AttendanceTypeId =1
			) AS PB11,
			(select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '11' )) AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=1	AND SR.AttendanceTypeId=1
			) AS PG11,
			(select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate= (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '11' )) AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=0	AND SR.AttendanceTypeId=1
			) AS ABB11,
			(select count(A.Id) FROM  sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '11' )) AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=0	AND SR.AttendanceTypeId=1
			) AS ABG11,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.LeftDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '11' )) AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id
			) AS LB11,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.LeftDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '11' )) AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id
			) AS LG11,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.AdmissionDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '11' )) AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id
			) AS NAB11,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.AdmissionDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '11' )) AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id 
			) AS NAG11,
			
			(select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '12' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=1 AND SR.AttendanceTypeId =1
			) AS PB12,
			(select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '12' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=1	AND SR.AttendanceTypeId=1
			) AS PG12,
			(select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate= (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '12' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=0	AND SR.AttendanceTypeId=1
			) AS ABB12,
			(select count(A.Id) FROM  sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '12' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=0	AND SR.AttendanceTypeId=1
			) AS ABG12,
			(	select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.LeftDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '12' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id
			) AS LB12,
			(	select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.LeftDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '12' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id
			) AS LG12,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.AdmissionDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '12' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id
			) AS NAB12,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.AdmissionDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '12' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id 
			) AS NAG12,
			
			(select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '13' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=1 AND SR.AttendanceTypeId =1
			) AS PB13,
			(select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '13' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=1	AND SR.AttendanceTypeId=1
			) AS PG13,
			(select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate= (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '13' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=0	AND SR.AttendanceTypeId=1
			) AS ABB13,
			(select count(A.Id) FROM  sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '13' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=0	AND SR.AttendanceTypeId=1
			) AS ABG13,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.LeftDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '13' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id
			) AS LB13,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.LeftDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '13' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id
			) AS LG13,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.AdmissionDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '13' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id
			) AS NAB13,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.AdmissionDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '13' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id 
			) AS NAG13,
			
			(select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '14' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=1 AND SR.AttendanceTypeId =1
			) AS PB14,
			(select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '14' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=1	AND SR.AttendanceTypeId=1
			) AS PG14,
			(select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate= (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '14' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=0	AND SR.AttendanceTypeId=1
			) AS ABB14,
			(select count(A.Id) FROM  sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '14' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=0	AND SR.AttendanceTypeId=1
			) AS ABG14,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.LeftDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '14' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id
			) AS LB14,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.LeftDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '14' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id
			) AS LG14,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.AdmissionDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '14' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id
			) AS NAB14,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.AdmissionDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '14' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id 
			) AS NAG14,
			
			(select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '15' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=1 AND SR.AttendanceTypeId =1
			) AS PB15,
			(select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '15' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=1	AND SR.AttendanceTypeId=1
			) AS PG15,
			(select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate= (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '15' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=0	AND SR.AttendanceTypeId=1
			) AS ABB15,
			(select count(A.Id) FROM  sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '15' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=0	AND SR.AttendanceTypeId=1
			) AS ABG15,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.LeftDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '15' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id
			) AS LB15,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.LeftDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '15' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id) AS LG15,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.AdmissionDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '15' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id
			) AS NAB15,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.AdmissionDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '15' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id
			) AS NAG15,
			
			(select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '16' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=1 AND SR.AttendanceTypeId =1
			) AS PB16,
			(select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '16' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=1	AND SR.AttendanceTypeId=1
			) AS PG16,
			(select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate= (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '16' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=0	AND SR.AttendanceTypeId=1
			) AS ABB16,
			(select count(A.Id) FROM  sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '16' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=0	AND SR.AttendanceTypeId=1
			) AS ABG16,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.LeftDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '16' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id
			) AS LB16,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.LeftDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '16' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id
			) AS LG16,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.AdmissionDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '16' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id
			) AS NAB16,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.AdmissionDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '16' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id 
			) AS NAG16,
			
			(select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '17' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=1 AND SR.AttendanceTypeId =1
			) AS PB17,
			(select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '17' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=1	AND SR.AttendanceTypeId=1
			) AS PG17,
			(select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate= (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '17' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=0	AND SR.AttendanceTypeId=1
			) AS ABB17,
			(select count(A.Id) FROM  sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '17' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=0	AND SR.AttendanceTypeId=1
			) AS ABG17,
			(	select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.LeftDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '17' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id
			) AS LB17,
			(	select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.LeftDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '17' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id) AS LG17,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.AdmissionDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '17' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id
			) AS NAB17,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.AdmissionDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '17' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id 
			) AS NAG17,
			
			(select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '18' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=1 AND SR.AttendanceTypeId =1
			) AS PB18,
			(select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '18' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=1	AND SR.AttendanceTypeId=1
			) AS PG18,
			(select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate= (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '18' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=0	AND SR.AttendanceTypeId=1
			) AS ABB18,
			(select count(A.Id) FROM  sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '18' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=0	AND SR.AttendanceTypeId=1
			) AS ABG18,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.LeftDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '18' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id
			) AS LB18,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.LeftDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '18' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id
			) AS LG18,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.AdmissionDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '18' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id
			) AS NAB18,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.AdmissionDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '18' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id 
			) AS NAG18,
			
			(select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '19' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=1 AND SR.AttendanceTypeId =1
			) AS PB19,
			(select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '19' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=1	AND SR.AttendanceTypeId=1
			) AS PG19,
			(	select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate= (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '19' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=0	AND SR.AttendanceTypeId=1
			) AS ABB19,
			(select count(A.Id) FROM  sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '19' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=0	AND SR.AttendanceTypeId=1
			) AS ABG19,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.LeftDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '19' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id
			) AS LB19,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.LeftDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '19' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id) AS LG19,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.AdmissionDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '19' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id
			) AS NAB19,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.AdmissionDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '19' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id 
			) AS NAG19,
			
			(select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '20' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=1 AND SR.AttendanceTypeId =1
			) AS PB20,
			(select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '20' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=1	AND SR.AttendanceTypeId=1
			) AS PG20,
			(select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate= (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '20' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=0	AND SR.AttendanceTypeId=1
			) AS ABB20,
			(select count(A.Id) FROM  sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '20' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=0	AND SR.AttendanceTypeId=1
			) AS ABG20,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.LeftDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '20' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id
			) AS LB20,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.LeftDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '20' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id
			) AS LG20,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.AdmissionDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '20' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id
			) AS NAB20,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.AdmissionDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '20' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id 
			) AS NAG20,
			
			(select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '21' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=1 AND SR.AttendanceTypeId =1
			) AS PB21,
			(select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '21' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=1	AND SR.AttendanceTypeId=1
			) AS PG21,
			(select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate= (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '21' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=0	AND SR.AttendanceTypeId=1
			) AS ABB21,
			(select count(A.Id) FROM  sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '21' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=0	AND SR.AttendanceTypeId=1
			) AS ABG21,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.LeftDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '21' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id
			) AS LB21,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.LeftDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '21' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id
			) AS LG21,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.AdmissionDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '21' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id
			) AS NAB21,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.AdmissionDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '21' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id 
			) AS NAG21,
			
			(select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '22' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=1 AND SR.AttendanceTypeId =1
			) AS PB22,
			(select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '22' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=1	AND SR.AttendanceTypeId=1
			) AS PG22,
			(select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate= (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '22' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=0	AND SR.AttendanceTypeId=1
			) AS ABB22,
			(select count(A.Id) FROM  sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '22' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=0	AND SR.AttendanceTypeId=1
			) AS ABG22,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.LeftDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '22' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id
			) AS LB22,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.LeftDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '22' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id
			) AS LG22,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.AdmissionDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '22' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id
			) AS NAB22,
			(	select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.AdmissionDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '22' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id 
			) AS NAG22,
			
			(select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '23' )) AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=1 AND SR.AttendanceTypeId =1
			) AS PB23,
			(select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '23' )) AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=1	AND SR.AttendanceTypeId=1
			) AS PG23,
			(select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate= (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '23' )) AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=0	AND SR.AttendanceTypeId=1
			) AS ABB23,
			(select count(A.Id) FROM  sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '23' )) AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=0	AND SR.AttendanceTypeId=1
			) AS ABG23,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.LeftDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '23' )) AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id
			) AS LB23,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.LeftDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '23' )) AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id
			) AS LG23,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.AdmissionDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '23' )) AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id
			) AS NAB23,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.AdmissionDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '23' )) AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id 
			) AS NAG23,
			
			(select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '24' )) AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=1 AND SR.AttendanceTypeId =1
			) AS PB24,
			(select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '24' )) AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=1	AND SR.AttendanceTypeId=1
			) AS PG24,
			(select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate= (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '24' )) AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=0	AND SR.AttendanceTypeId=1
			) AS ABB24,
			(select count(A.Id) FROM  sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '24' )) AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=0	AND SR.AttendanceTypeId=1
			) AS ABG24,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.LeftDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '24' )) AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id
			) AS LB24,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.LeftDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '24' )) AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id
			) AS LG24,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.AdmissionDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '24' )) AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id
			) AS NAB24,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.AdmissionDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '24' )) AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id 
			) AS NAG24,
			
			(select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '25' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=1 AND SR.AttendanceTypeId =1
			) AS PB25,
			(select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '25' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=1	AND SR.AttendanceTypeId=1
			) AS PG25,
			(select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate= (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '25' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=0	AND SR.AttendanceTypeId=1
			) AS ABB25,
			(select count(A.Id) FROM  sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '25' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=0	AND SR.AttendanceTypeId=1
			) AS ABG25,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.LeftDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '25' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id
			) AS LB25,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.LeftDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '25' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id
			) AS LG25,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.AdmissionDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '25' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id
			) AS NAB25,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.AdmissionDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '25' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id 
			) AS NAG25,
			
			(select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '26' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=1 AND SR.AttendanceTypeId =1
			) AS PB26,
			(select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '26' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=1	AND SR.AttendanceTypeId=1
			) AS PG26,
			(select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate= (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '26' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=0	AND SR.AttendanceTypeId=1
			) AS ABB26,
			(select count(A.Id) FROM  sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '26' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=0	AND SR.AttendanceTypeId=1
			) AS ABG26,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.LeftDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '26' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id
			) AS LB26,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.LeftDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '26' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id
			) AS LG26,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.AdmissionDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '26' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id
			) AS NAB26,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.AdmissionDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '26' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id 
			) AS NAG26,
			
			(select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '27' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=1 AND SR.AttendanceTypeId =1
			) AS PB27,
			(select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '27' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=1	AND SR.AttendanceTypeId=1
			) AS PG27,
			(select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate= (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '27' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=0	AND SR.AttendanceTypeId=1
			) AS ABB27,
			(select count(A.Id) FROM  sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '27' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=0	AND SR.AttendanceTypeId=1
			) AS ABG27,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.LeftDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '27' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id
			) AS LB27,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.LeftDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '27' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id
			) AS LG27,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.AdmissionDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '27' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id
			) AS NAB27,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.AdmissionDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '27' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id 
			) AS NAG27,
			
			(select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '28' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=1 AND SR.AttendanceTypeId =1
			) AS PB28,
			(select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '28' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=1	AND SR.AttendanceTypeId=1
			) AS PG28,
			(select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate= (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '28' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=0	AND SR.AttendanceTypeId=1
			) AS ABB28,
			(select count(A.Id) FROM  sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '28' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=0	AND SR.AttendanceTypeId=1
			) AS ABG28,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.LeftDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '28' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id
			) AS LB28,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.LeftDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '28' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id
			) AS LG28,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.AdmissionDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '28' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id
			) AS NAB28,
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.AdmissionDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '28' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id 
			) AS NAG28,
			
			CASE 
			WHEN @lMonthDays >= 29 THEN
			(select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '29' )) AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=1 AND SR.AttendanceTypeId =1
			)
			ELSE
			0
			END
			 AS PB29,
			 
			CASE 
			WHEN @lMonthDays >= 29 THEN
			(select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '29' )) AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=1	AND SR.AttendanceTypeId=1
			)
			ELSE
			0
			END AS PG29,
			CASE 
			WHEN @lMonthDays >= 29 THEN
			(select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate= (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '29' )) AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=0	AND SR.AttendanceTypeId=1
			)ELSE
			0
			END AS ABB29,
			CASE 
			WHEN @lMonthDays >= 29 THEN
			(select count(A.Id) FROM  sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '29' )) AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=0	AND SR.AttendanceTypeId=1
			)ELSE
			0
			END AS ABG29,
			CASE 
			WHEN @lMonthDays >= 29 THEN
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.LeftDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '29' )) AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id
			)ELSE
			0
			END  AS LB29,
			CASE 
			WHEN @lMonthDays >= 29 THEN
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.LeftDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '29' )) AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id
			)ELSE
			0
			END   AS LG29,
			CASE 
			WHEN @lMonthDays >= 29 THEN
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.AdmissionDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '29' )) AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id
			)ELSE
			0
			END  AS NAB29,
			CASE 
			WHEN @lMonthDays >= 29 THEN
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.AdmissionDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '29' )) AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id 
			)ELSE
			0
			END  AS NAG29,
			CASE 
			WHEN @lMonthDays >= 30 THEN
			(select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '30' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=1 AND SR.AttendanceTypeId =1
			)ELSE
			0
			END  AS PB30,
			CASE 
			WHEN @lMonthDays >= 30 THEN
			(select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '30' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=1	AND SR.AttendanceTypeId=1
			)ELSE
			0
			END AS PG30,
			CASE 
			WHEN @lMonthDays >= 30 THEN
			(select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate= (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '30' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=0	AND SR.AttendanceTypeId=1
			)ELSE
			0
			END  AS ABB30,
			CASE 
			WHEN @lMonthDays >= 30 THEN
			(select count(A.Id) FROM  sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '30' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=0	AND SR.AttendanceTypeId=1
			)ELSE
			0
			END  AS ABG30,
			CASE 
			WHEN @lMonthDays >= 30 THEN
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.LeftDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '30' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id
			)ELSE
			0
			END  AS LB30,
			CASE 
			WHEN @lMonthDays >= 30 THEN
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.LeftDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '30' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id
			)ELSE
			0
			END  AS LG30,
			CASE 
			WHEN @lMonthDays >= 30 THEN
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.AdmissionDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '30' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id
			)ELSE
			0
			END  AS NAB30,
			CASE 
			WHEN @lMonthDays >= 30 THEN
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SA.AdmissionDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '30' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id 
			)ELSE
			0
			END  AS NAG30,
			
			CASE 
			WHEN @lMonthDays >= 31 THEN
			(select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
			WHERE A.BatchId = @rBatchId  
			AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '31' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=1 AND SR.AttendanceTypeId =1
			)ELSE
			0
			END  AS PB31,
			CASE 
			WHEN @lMonthDays >= 31 THEN
			(select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
			WHERE A.BatchId = @rBatchId  
			AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '31' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=1	AND SR.AttendanceTypeId=1
			)ELSE
			0
			END   AS PG31,
			CASE 
			WHEN @lMonthDays >= 31 THEN
			(select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
			WHERE A.BatchId = @rBatchId  
			AND SR.AttendanceDate= (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '31' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=0	AND SR.AttendanceTypeId=1
			)ELSE
			0
			END  AS ABB31,
			CASE 
			WHEN @lMonthDays >= 31 THEN
			(select count(A.Id) FROM  sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
			WHERE A.BatchId = @rBatchId  
			AND SR.AttendanceDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '31' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id AND SR.IsPresent=0	AND SR.AttendanceTypeId=1
			)ELSE
			0
			END AS ABG31,
			CASE 
			WHEN @lMonthDays >= 31 THEN
			(	select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
			WHERE A.BatchId = @rBatchId  
			AND SA.LeftDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '31' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id
			)ELSE
			0
			END  AS LB31,
			CASE 
			WHEN @lMonthDays >= 31 THEN
			(	select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
			WHERE A.BatchId = @rBatchId  
			AND SA.LeftDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '31' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id
			)ELSE
			0
			END AS LG31,
			CASE 
			WHEN @lMonthDays >= 31 THEN
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
			WHERE A.BatchId = @rBatchId  
			AND SA.AdmissionDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '31' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id
			)ELSE
			0
			END AS NAB31,
			CASE 
			WHEN @lMonthDays >= 31 THEN
			(select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId
			
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=SA.StudentId
			WHERE A.BatchId = @rBatchId  
			AND SA.AdmissionDate = (convert(date,CONVERT(nvarchar(10), @rYear)+ '/' +  CONVERT(nvarchar(10), @rMonth) + '/' + '31' ))  AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id 
			)ELSE
			0
			END AS NAG31,
			--MS.AttendanceCount AS WorkingDays,
			MS.WorkingDays AS WorkingDays,
			Dept.Title AS DepartmentName,
			CM.Id AS ClassId,
			CM.Title AS ClassName,
			DM.Id AS DivId,
			DM.Title AS DivisionName,
			--@rStatus AS StatusCheck,
			--@rStatusClass AS StatusClass
			@rMonth AS StudentMonth,
			@rYear AS StudentYear
			
			FROM 
			
			
			sSetup.tDivisionMaster DM  
			INNER JOIN sSetup.tClassMaster CM ON CM.Id=DM.ClassId
			INNER JOIN sAttendance.tMonthlySetup MS ON CM.Id=MS.ClassId		
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id=MS.BatchId	
			INNER JOIN sSetup.tDepartmentMaster Dept ON Dept.Id=CM.DepartmentId  
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = DM.OrgId
		
			
	WHERE 
		DM.OrgId=@rOrgId
		AND	MS.BatchId = @rBatchId 
		AND ((DM.ClassId=@rClassId) OR (@rClassId=0))
		AND ((DM.Id=@rDivisionId) OR (@rDivisionId=0))
		AND ((Dept.Id=@rDepartmentId) OR (@rDepartmentId=0))
		
		AND ((MS.ForMonth=@rMonth) OR(@rMonth =0)) 
		AND ((MS.ForYear=@rYear) OR (@rYear=0))
		AND DM.IsObsolete = 0
		--AND	BM.OrgGroupBatchId = @rOrgGroupBatchId 
	
	
END
GO
PRINT N'Altering Procedure [sStudent].[pStudentAdmissionAdd]...';


GO
ALTER PROCEDURE [sStudent].[pStudentAdmissionAdd]
	 
		   @rStudentId bigint,
		   @rPreviousSchool nvarchar(200),
           @rPreviousSchoolTypeId int,
           @rPreviousStudentId bigint,
           @rAdmissionFormId bigint,
           @rAdmissionFormNumber nvarchar(20),
           @rAdmissionStandardId int,
           @rAdmissionDate date,
           @rAdmissionYear nvarchar(10),
           @rLeftStandardId int,
           @rLeftDate date,
           @rLeftYear nvarchar(10),
           @rInactiveDate date,
           @rInActiveReason nvarchar(200),
           @rLeftReason nvarchar(200),
           @rLCProgress nvarchar(200),
           @rLCConduct nvarchar(200),
           @rLCBook nvarchar(20),
           @rLCNumber nvarchar(20),
           @rLCDate date,
           @rLCRemark nvarchar(200),
           @rLCCopy tinyint,
           @rLcId bigint,
           @rBatchId int,
           @rCreatedUserId bigint,
           @rUpdatedUserId bigint,
           @rIsGeneral bit,
           
           @rAdmissionNumber nvarchar(50)='',
           @rIsTransfer bit = 0,
           @rTransferFrom nvarchar(150)='',
           @rPassingYear nvarchar(20)='',
           @rIsTFWS bit = 0,
           @rIsCertificateHolder bit = 0,
           @rCertificateName nvarchar(100) = '',
           @rAdmissionQuotaId int =0,
           @rPreviousStandard nvarchar(50)='',
           @rAcademicId bigint = 0,
           @rPreviousLCDate date=null,
           @rPreviousLCNumber nvarchar(100)='',
           @rPreviousLCResult nvarchar(100) ='',
		   @rProofOfDOB nvarchar(200) ='',
		   @rPreviousLeftDate date=null				--add for 27789 mantis

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

BEGIN TRY
BEGIN TRANSACTION	

 


IF(@rIsGeneral=1)	
BEGIN 
	IF NOT EXISTS(SELECT * FROM sStudent.tStudentAdmission WHERE StudentId = @rStudentId)
	BEGIN

	INSERT INTO sStudent.tStudentAdmission
		(
			   StudentId,
			   PreviousSchool,
			   AdmissionStandardId,
			   AdmissionDate,
			   LeftStandardId,
			   LeftDate,
			   InactiveDate,
			   BatchId,
			   CreatedUserId,
			   CreatedDateTime,
			   PreviousStandard,
			   PreviousLCNumber,
			   PreviousLCDate,
			   PreviousLCResult,
			   ProofOfDOB
			   
			   
		)
	VALUES
		(
			   @rStudentId,
			   @rPreviousSchool,
			   @rAdmissionStandardId,
			   @rAdmissionDate,
			   @rLeftStandardId,
			   @rLeftDate,
			   @rInactiveDate,
			   @rBatchId,
			   @rCreatedUserId,
			   sCommon.fGetDate(),
			   @rPreviousStandard,
			   @rPreviousLCNumber,
			   @rPreviousLCDate,
			   @rPreviousLCResult,
			   @rProofOfDOB
		)
		
		
		SELECT 1 AS Result             
	END	 
	 ELSE
	 BEGIN
		UPDATE sStudent.tStudentAdmission
	    SET
			  
			  AdmissionStandardId = @rAdmissionStandardId, 
			  AdmissionDate = @rAdmissionDate, 
			  LeftStandardId = @rLeftStandardId,
			  LeftDate = @rLeftDate, 
			  InactiveDate = @rInactiveDate, 
			  UpdatedUserId = @rUpdatedUserId, 
			  UpdatedDateTime =sCommon.fGetDate()
	
	      WHERE StudentId = @rStudentId 
	      
	  
	 END  
		SELECT 11 AS Result
	END
ELSE
BEGIN
		IF(@rIsGeneral=0)
	    IF NOT EXISTS(SELECT * FROM sStudent.tStudentAdmission WHERE StudentId = @rStudentId)
BEGIN

	INSERT INTO sStudent.tStudentAdmission
		(
			   StudentId,
			   PreviousSchool,
			   PreviousSchoolTypeId,
			   PreviousStudentId,
			   AdmissionFormId,
			   AdmissionFormNumber,
			   AdmissionStandardId,
			   AdmissionDate,
			   AdmissionYear,
			   LeftStandardId,
			   LeftDate,
			   LeftYear,
			   InactiveDate,
			   InActiveReason,
			   LeftReason,
			   LCProgress,
			   LCConduct,
			   LCBook,
			   LCNumber,
			   LCDate,
			   LCRemark,
			   LCCopy,
			   LcId,
			   BatchId,
			   CreatedUserId,
			   CreatedDateTime,
			   
			   AdmissionNumber,
			   IsTransfer,
			   TransferFrom,
			   PassingYear,
			   IsTFWS,
			   IsCertificateHolder,
			   CertificateName,
			   AdmissionQuotaId,
			   PreviousStandard,
			   PreviousLCNumber,
			   PreviousLCDate,
			   PreviousLCResult,
			   ProofOfDOB,
			   PreviousLeftDate				--add for 27789 mantis
		)
	VALUES
		(
			   @rStudentId,
			   @rPreviousSchool,
			   @rPreviousSchoolTypeId,
			   @rPreviousStudentId,
			   @rAdmissionFormId,
			   @rAdmissionFormNumber,
			   @rAdmissionStandardId,
			   @rAdmissionDate,
			   @rAdmissionYear,
			   @rLeftStandardId,
			   @rLeftDate,
			   @rLeftYear,
			   @rInactiveDate,
			   @rInActiveReason,
			   @rLeftReason,
			   @rLCProgress,
			   @rLCConduct,
			   @rLCBook,
			   @rLCNumber,
			   @rLCDate,
			   @rLCRemark,
			   @rLCCopy,
			   @rLcId,
			   @rBatchId,
			   @rCreatedUserId,
			   sCommon.fGetDate(),
			   
			   @rAdmissionNumber,
			   @rIsTransfer,
			   @rTransferFrom,
			   @rPassingYear,
			   @rIsTFWS,
			   @rIsCertificateHolder,
			   @rCertificateName,
			   @rAdmissionQuotaId,
			   @rPreviousStandard,
			   @rPreviousLCNumber,
			   @rPreviousLCDate,
			   @rPreviousLCResult,
			   @rProofOfDOB,
			   @rPreviousLeftDate				--add for 27789 mantis
		)
		SELECT 1 AS Result             
	END	 
	ELSE
	BEGIN
		UPDATE sStudent.tStudentAdmission
	    SET
			  PreviousSchool = @rPreviousSchool,
			  PreviousSchoolTypeId = @rPreviousSchoolTypeId, 
			  PreviousStudentId = @rPreviousStudentId, 
			  AdmissionFormId = @rAdmissionFormId,
			  AdmissionFormNumber = @rAdmissionFormNumber, 
			  AdmissionStandardId = @rAdmissionStandardId, 
			  AdmissionDate = @rAdmissionDate, 
			  AdmissionYear = @rAdmissionYear,
			  LeftStandardId = @rLeftStandardId,
			  LeftDate = @rLeftDate, 
			  LeftYear = @rLeftYear,
			  InactiveDate = @rInactiveDate, 
			  InActiveReason = @rInActiveReason,
			  LeftReason = @rLeftReason, 
			  LCProgress = @rLCProgress,
			  LCConduct = @rLCConduct, 
			  LCBook = @rLCBook, 
			  LCNumber = @rLCNumber,
			  LCDate = @rLCDate, 
			  LCRemark = @rLCRemark, 
			  LCCopy = @rLCCopy, 
			  LcId = @rLcId, 
			  UpdatedUserId = @rUpdatedUserId, 
			  UpdatedDateTime =sCommon.fGetDate(),
			  
			  AdmissionNumber=@rAdmissionNumber,
			  IsTransfer=@rIsTransfer,
		  	  TransferFrom=@rTransferFrom,
			  PassingYear=@rPassingYear,
			  IsTFWS=@rIsTFWS,
			  IsCertificateHolder=@rIsCertificateHolder,
			  CertificateName=@rCertificateName,
			  AdmissionQuotaId=@rAdmissionQuotaId,
			  PreviousStandard=@rPreviousStandard,
			  PreviousLCNumber=@rPreviousLCNumber,
			  PreviousLCDate=@rPreviousLCDate,
			  PreviousLCResult=@rPreviousLCResult,
			  ProofOfDOB=@rProofOfDOB,
			  PreviousLeftDate=@rPreviousLeftDate			--add for 27789 mantis
	      
	      WHERE StudentId = @rStudentId 	 
	      
	END  
	 
		SELECT 11 AS Result
		
	END

		UPDATE A
		SET ClassStatusId = 3
		FROM sStudent.tAcademic A
		INNER JOIN sStudent.tStudentMaster SM ON A.StudentId = SM.Id
		INNER JOIN sStudent.tStudentAdmission SA ON A.StudentId = SA.StudentId AND A.ClassId = SA.LeftStandardId
		WHERE SM.StatusId = 3 AND SM.Id = @rStudentId

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


GO
ALTER PROCEDURE [sStudent].[pStudentAdmissionGet]
	 
	 @rStudentId bigint
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	SELECT 
			  SA.StudentId,
			  SA.PreviousSchool,
			  ISNULL(SA.PreviousSchoolTypeId,0) AS PreviousSchoolTypeId,
			  ISNULL(SA.PreviousStudentId,0) AS PreviousStudentId,
			  ISNULL(SA.AdmissionFormId,0) AS AdmissionFormId,
			  SA.AdmissionFormNumber,
			  ISNULL(SA.AdmissionStandardId,0) AS AdmissionStandardId,
			  ISNULL(SA.AdmissionDate,'0001/01/01') AS AdmissionDate,
			  SA.AdmissionYear,
			  ISNULL(SA.LeftStandardId,0) AS LeftStandardId,
			  ISNULL(SA.LeftDate,'0001/01/01') AS LeftDate,
			  SA.LeftYear,
			  ISNULL(SA.InactiveDate,'0001/01/01') AS InactiveDate,
			  SA.InActiveReason,
			  SA.LeftReason,
			  SA.LCProgress,
			  SA.LCConduct,
			  SA.LCBook,
			  SA.LCNumber,
			  ISNULL(SA.LCDate,'0001/01/01') AS LCDate,
			  SA.LCRemark,
			  ISNULL(SA.LCCopy,0) AS LCCopy,
			  ISNULL(SA.LcId,0) AS LcId,
			  
			  ISNULL(SA.AdmissionNumber,'') AS AdmissionNumber,
			  ISNULL(SA.IsTransfer,0) AS IsTransfer,
			  ISNULL(SA.TransferFrom,'') AS TransferFrom,
			  ISNULL(SA.PassingYear,'') AS PassingYear,
			  ISNULL(SA.IsTFWS,0) AS IsTFWS,
			  ISNULL(SA.IsCertificateHolder,0) AS IsCertificateHolder,
			  ISNULL(SA.CertificateName,'') AS CertificateName,
			  ISNULL(SA.AdmissionQuotaId,0) AS AdmissionQuotaId,
			  ISNULL(SA.PreviousStandard,'') AS PreviousStandard,
			  ISNULL(SA.PreviousLCDate,'') AS PreviousLCDate,
			  ISNULL(SA.PreviousLCNumber,'') AS PreviousLCNumber,
			  ISNULL(SA.PreviousLCResult,'') AS PreviousLCResult,
			  ISNULL(SA.ProofOfDOB,'') AS ProofOfDOB,
			  ISNULL(SA.PreviousLeftDate,'') AS PreviousLeftDate			--add for 27789 mantis

  FROM 
         sStudent.tStudentAdmission SA
  WHERE 
		SA.StudentId = @rStudentId
END
GO
PRINT N'Altering Procedure [sAcademic].[pImportLessonPlan]...';


GO
ALTER PROCEDURE [sAcademic].[pImportLessonPlan]
       
    @rOrgId int,
	@rXmldoc [nvarchar](max),
	@rBatchId int,
	@rCreatedUserId bigint 	  
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

	DECLARE @lCount int,@intDoc INT,@lInterrorCode INT,@loXML XML,
			@lDivisionId int,
			@lTopicId int,
			@lNoOfPeriodRequired smallint,
			@lObjective nvarchar(1000),
			@lIndicativeHomework nvarchar(1000),
			@lSummary nvarchar(1000),
			@lStartDate date,
			@lEndDate date,
			@lIsCompleted bit,
			@lEmployeeId bigint,
			@lBatchId int,
			@lCreatedUserId bigint,
			@lCreatedDateTime datetime,
			@lUpdatedUserId bigint,
			@lUpdatedDateTime datetime,
			@lLearningExperience nvarchar(1000),
			@lToolsAndTechniques nvarchar(500),
			@lEssentialMaterial nvarchar(500),
			@lAssessmentQuestion nvarchar(1000),
			@lTeacherExample nvarchar(1000),
			@lGuidedPractice nvarchar(1000),
			@lIndependentPractice nvarchar(1000),
			@lSubTopic nvarchar(1000) ,
			@lSession nvarchar(100) ,
			@lTrainingMethod  nvarchar(100) ,
			@lPeriodCount int

	SET @loXML = CAST(@rXmldoc AS XML)
	
	
	CREATE TABLE #tTable1 (
	Id int IDENTITY,
	DivisionId int,
	TopicId int,
	NoOfPeriodRequired smallint,
	Objective nvarchar(1000),
	IndicativeHomework nvarchar(1000),
	Summary nvarchar(1000),
	StartDate date,
	EndDate date,
	IsCompleted bit,
	EmployeeId bigint,
	BatchId int,
	CreatedUserId bigint,
	CreatedDateTime datetime,
	UpdatedUserId bigint,
	UpdatedDateTime datetime,
	LearningExperience nvarchar(1000),
	ToolsAndTechniques nvarchar(500),
	EssentialMaterial nvarchar(500),
	AssessmentQuestion nvarchar(1000),
	TeacherExample nvarchar(1000),
	GuidedPractice nvarchar(1000),
	IndependentPractice nvarchar(1000),
	SubTopic nvarchar(1000),
	Session nvarchar(100) ,
	TrainingMethod  nvarchar(100) ,
	PeriodCount int)
	 
	INSERT INTO #tTable1(
			DivisionId
           ,TopicId
           ,NoOfPeriodRequired
           ,Objective
           ,IndicativeHomework
           ,Summary
           ,StartDate
           ,EndDate
           ,IsCompleted
           ,EmployeeId
		   ,BatchId
		   ,CreatedUserId
           ,LearningExperience
           ,ToolsAndTechniques
           ,EssentialMaterial
           ,AssessmentQuestion
           ,TeacherExample
           ,GuidedPractice
           ,IndependentPractice
           ,SubTopic
		   ,Session 
		   ,TrainingMethod
		   ,PeriodCount)
	SELECT
		 T.c.value('@DivisionId','int') AS DivisionId,
		 T.c.value('@TopicId','int') AS TopicId,
		 T.c.value('@PerioNo','smallint') AS NoOfPeriodRequired,
		 T.c.value('@Objective','nvarchar(1000)') AS Objective,
		 T.c.value('@IndicativeHomework','nvarchar(1000)') AS IndicativeHomework,
		 T.c.value('@Summary','nvarchar(1000)') AS Summary,
		 T.c.value('@StartDate','Date') AS StartDate,
		 T.c.value('@EndDate','Date') AS EndDate,
		 T.c.value('@Completed','bit') AS IsCompleted,
		 T.c.value('@EmployeeId','bigint') AS EmployeeId,
		 @rBatchId,
		 T.c.value('@CreatedUserId','bigint') AS CreatedUserId,
		 T.c.value('@LearningExperience','nvarchar(1000)') AS LearningExperience,
		 T.c.value('@ToolsAndTechniques','nvarchar(500)') AS ToolsAndTechniques,
		 T.c.value('@EssentialMaterial','nvarchar(500)') AS EssentialMaterial,
		 T.c.value('@AssessmentQuestion','nvarchar(1000)') AS AssessmentQuestion,
		 T.c.value('@TeacherExample','nvarchar(1000)') AS TeacherExample,
		 T.c.value('@GuidedPractice','nvarchar(1000)') AS GuidedPractice,
		 T.c.value('@IndependentPractice','nvarchar(1000)') AS IndependentPractice,
		 T.c.value('@SubTopic','nvarchar(1000)') AS SubTopic,
		 T.c.value('@Session','nvarchar(100)') AS Session ,
		 T.c.value('@TrainingMethod','nvarchar(100)') AS TrainingMethod,
		 T.c.value('@PeriodCount','int') AS PeriodCount

	FROM @loXML.nodes('/Table/ImportLessonPlan')T(c)
	
		SELECT @lCount =  COUNT(Id) FROM #tTable1
	
		-- Added for mantis: 0025563 By Foram
		DECLARE @lOrgGroupBatchId int=0, @lConfigValue nvarchar(50),@lIsLessonPlanOnSameDayAllow bit=0
		SELECT @lOrgGroupBatchId=OrgGroupBatchId FROM sSetup.tBatchMaster WHERE Id = @rBatchId
		SELECT @lConfigValue = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 537 AND SourceTypeId = 2010 AND SourceId = LEFT(@lOrgGroupBatchId,4)

		IF (@lConfigValue IS NULL) OR (@lConfigValue = 'False')
		BEGIN 
			SET @lIsLessonPlanOnSameDayAllow = 0 
		END
		ELSE
		BEGIN
			SET @lIsLessonPlanOnSameDayAllow = 1
		END
		-- Added for mantis: 0025563 By Foram

		WHILE @lCount > 0 

		BEGIN				
	   
			SELECT	
				@lDivisionId = DivisionId,
				@lTopicId = TopicId,
				@lNoOfPeriodRequired = NoOfPeriodRequired,
				@lObjective = Objective,
				@lIndicativeHomework = IndicativeHomework,
				@lSummary = Summary,
				@lStartDate = StartDate,
				@lEndDate = EndDate,
				@lIsCompleted = IsCompleted,
				@lEmployeeId = EmployeeId,
				@lBatchId = BatchId,
				@lCreatedUserId = CreatedUserId,
				@lLearningExperience = LearningExperience,
				@lToolsAndTechniques = ToolsAndTechniques,
				@lEssentialMaterial = EssentialMaterial,
				@lAssessmentQuestion = AssessmentQuestion,
				@lTeacherExample = TeacherExample,
				@lGuidedPractice = GuidedPractice,
				@lIndependentPractice = IndependentPractice,
				@lSubTopic = SubTopic ,
				@lSession = Session ,
			    @lTrainingMethod  = TrainingMethod ,
			    @lPeriodCount = PeriodCount 
			FROM #tTable1 WHERE Id = @lCount 
			
			IF(@lIsLessonPlanOnSameDayAllow = 0)
			BEGIN
				IF EXISTS(SELECT Id FROM sAcademic.tLessonPlan WHERE DivisionId=@lDivisionId AND TopicId = @lTopicId AND StartDate = @lStartDate AND EndDate = @lEndDate)
				BEGIN
					Declare @lTopicName nvarchar(500), @lDivisionName nvarchar(100)
					SET  @lTopicName =(select Title from sAcademic.tTopicMaster where Id =@lTopicId)
					SET  @lDivisionName =(select Title from sSetup.tDivisionMaster Where Id =@lDivisionId)

					SELECT -101 AS Result, 'Lesson Plan Already Exists for for Division - '+@lDivisionName+', Topic - '+@lTopicName+', Start Date - '+Convert(nvarchar(10), @lStartDate, 103)+', End Date - '+Convert(nvarchar(10), @lEndDate, 103)+'' AS Message
					RETURN
				END 
			END
			DECLARE @lNextNumber BIGINT	
			EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sAcademic.tLessonPlan', 0, 1, 1,@outNextNumber = @lNextNumber output

			INSERT INTO sAcademic.tLessonPlan
				(
					Id,
					TopicId,
					DivisionId,
					NoOfPeriodRequired,
					Objective,
					IndicativeHomework,
					Summary,
					StartDate,
					EndDate,
					IsCompleted,
					EmployeeId,
					BatchId,
					CreatedUserId,
					CreatedDateTime,
					LearningExperience,
					ToolsAndTechniques,
					EssentialMaterial,
					AssessmentQuestion,
					TeacherExample,
					GuidedPractice,
					IndependentPractice,
					SubTopic ,
					Session ,
					TrainingMethod ,
					PeriodCount
				)
			VALUES
				(
					@lNextNumber,
					@lTopicId,
					@lDivisionId,
					ISNULL(@lNoOfPeriodRequired,0),
					ISNULL(@lObjective,''),
					ISNULL(@lIndicativeHomework,''),
					ISNULL(@lSummary,''),
					@lStartDate,
					@lEndDate,
					@lIsCompleted,
					@lEmployeeId,
					@lBatchId,
					@lCreatedUserId,
					sCommon.fGetDate(),
					ISNULL(@lLearningExperience,''),
					ISNULL(@lToolsAndTechniques,''),
					ISNULL(@lEssentialMaterial,''),
					ISNULL(@lAssessmentQuestion,''),
					ISNULL(@lTeacherExample,''),
					ISNULL(@lGuidedPractice,''),
					ISNULL(@lIndependentPractice,''),
					ISNULL(@lSubTopic,''),
					ISNULL(@lSession,''),
					ISNULL(@lTrainingMethod,''),
					ISNULL(@lPeriodCount,0)
				)
				
			SET @lCount = @lCount - 1
			SELECT 1 AS Result 		

		 END
END
GO
PRINT N'Altering Procedure [sAcademic].[pLessonPlanAdd]...';


GO
ALTER PROCEDURE [sAcademic].[pLessonPlanAdd]
	 
        @rId bigint=0,
        @rTopicId int,
        @rDivisionId int, 
        @rNoOfPeriodRequired smallint,
        @rObjective nvarchar(1000),
        @rIndicativeHomework nvarchar(200),
        @rSummary nvarchar(200),
        @rStartDate date='',
        @rEndDate date='',
        @rIsCompleted bit=0,
        @rEmployeeId bigint,
        @rBatchId int,
        @rCreatedUserId bigint,
        @rOrgId smallint,
        @rLearningExperience nvarchar(1000)='',
        @rToolsAndTechniques nvarchar(500)='',
        @rEssentialMaterial nvarchar(500)='',
		@rAssessmentQuestion	nvarchar(1000)='',	
		@rTeacherExample	nvarchar(1000)='',
		@rGuidedPractice	nvarchar(1000)='',
		@rIndependentPractice	nvarchar(1000)	='',
		@rSubTopic nvarchar(1000)='' ,
	    @rSession nvarchar(100)='' ,
		@rTrainingMethod  nvarchar(100)='' ,
		@rPeriodCount int =0,
		@rRemark nvarchar(MAX) = ''
	

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	 
	--IF(@rId = 0)	
	--BEGIN
	--	--If Exists(select Id from sCommunication.tNews where Code=@rCode AND OrgGroupBatchId=@rOrgGroupBatchId)
	--	--	BEGIN
	--	--	select -102 as Result
	--	--	RETURN
	--	--END 
	
	--	If Exists(select Id from sAcademic.tTopicMaster where Number=@rNumber AND OrgId=@rOrgId)
	--		BEGIN
	--		select -103 as Result
	--		RETURN
	--	END 
	--END
	--ELSE
	--BEGIN
	--	--If Exists(select Id from sCommunication.tNews where Code=@rCode AND OrgGroupBatchId=@rOrgGroupBatchId AND Id<>@rId)
	--	--Begin
	--	--	select -102 as Result
	--	--	RETURN
	--	--End
	--	If  Exists(select Id from sAcademic.tTopicMaster where Number=@rNumber AND OrgId=@rOrgId AND Id<>@rId)
	--	Begin
	--		select -103 as Result
	--		RETURN
	--	End

	--END
	
	-- Added for mantis: 0025563 By Foram
	DECLARE @lOrgGroupBatchId int=0, @lConfigValue nvarchar(50),@lIsLessonPlanOnSameDayAllow bit=0
	SELECT @lOrgGroupBatchId=OrgGroupBatchId FROM sSetup.tBatchMaster WHERE Id = @rBatchId
	SELECT @lConfigValue = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 537 AND SourceTypeId = 2010 AND SourceId = LEFT(@lOrgGroupBatchId,4)

	IF (@lConfigValue IS NULL) OR (@lConfigValue = 'False')
	BEGIN 
		SET @lIsLessonPlanOnSameDayAllow = 0 
	END
	ELSE
	BEGIN
		SET @lIsLessonPlanOnSameDayAllow = 1
	END
	-- Added for mantis: 0025563 By Foram

	IF(@lIsLessonPlanOnSameDayAllow = 0)
	BEGIN
		IF(@rId = 0)	
		BEGIN
			IF EXISTS(SELECT Id FROM sAcademic.tLessonPlan WHERE DivisionId=@rDivisionId AND TopicId = @rTopicId AND StartDate = @rStartDate AND EndDate = @rEndDate)
			BEGIN
				SELECT -101 AS Result
				RETURN
			END 
		END
		ELSE
		BEGIN
			IF  EXISTS(SELECT Id FROM sAcademic.tLessonPlan WHERE DivisionId=@rDivisionId AND TopicId = @rTopicId AND StartDate = @rStartDate AND EndDate = @rEndDate AND Id <> @rId)
			BEGIN
				SELECT -101 AS Result
				RETURN
			END
		END
	END

	DECLARE @lNextNumber BIGINT 

	IF(@rId = 0)	
	BEGIN
		
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sAcademic.tLessonPlan', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	INSERT INTO sAcademic.tLessonPlan
		(
			Id,
			TopicId,
			DivisionId,
			NoOfPeriodRequired,
			Objective,
			IndicativeHomework,
			Summary,
			StartDate,
			EndDate,
			IsCompleted,
			EmployeeId,
			BatchId,
			CreatedUserId,
			CreatedDateTime,
			LearningExperience,
			ToolsAndTechniques,
			EssentialMaterial,
			AssessmentQuestion,
			TeacherExample,
			GuidedPractice,
			IndependentPractice,
			SubTopic ,
			[Session] ,
			TrainingMethod ,
			PeriodCount,
			Remark
		)
	VALUES
		(
			@lNextNumber,
			@rTopicId,
			@rDivisionId,
			@rNoOfPeriodRequired,
			@rObjective,
			@rIndicativeHomework,
			@rSummary,
			@rStartDate,
			@rEndDate,
			@rIsCompleted,
			@rEmployeeId,
			@rBatchId,
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rLearningExperience,
			@rToolsAndTechniques,
			@rEssentialMaterial,
			@rAssessmentQuestion,
			@rTeacherExample,
			@rGuidedPractice,
			@rIndependentPractice,
			CASE WHEN @rSubTopic = '-1' Then '' ELSE @rSubTopic END ,
			@rSession ,
		    @rTrainingMethod ,
			@rPeriodCount,
			@rRemark
		)
		    SELECT 1 AS Result , @lNextNumber As Id
	END	 

ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE  sAcademic.tLessonPlan
	    SET
			TopicId=@rTopicId,
			DivisionId=@rDivisionId,
			NoOfPeriodRequired=@rNoOfPeriodRequired,
			Objective=@rObjective,
			IndicativeHomework=@rIndicativeHomework,
			Summary=@rSummary,
			StartDate=@rStartDate,
			EndDate=@rEndDate,
			IsCompleted=@rIsCompleted,
			UpdatedUserId=@rCreatedUserId,
			UpdatedDateTime=sCommon.fGetDate(),
			LearningExperience = @rLearningExperience,
			ToolsAndTechniques = @rToolsAndTechniques,
			EssentialMaterial =@rEssentialMaterial,
			EmployeeId = @rEmployeeId,
			AssessmentQuestion=@rAssessmentQuestion,
			TeacherExample=@rTeacherExample,
			GuidedPractice=@rGuidedPractice,
			IndependentPractice=@rIndependentPractice,
			SubTopic= CASE WHEN @rSubTopic = '-1' Then '' ELSE @rSubTopic END ,
			[Session] = @rSession ,
			TrainingMethod =@rTrainingMethod ,
			PeriodCount =@rPeriodCount,
			Remark=@rRemark
	      WHERE Id = @rId
	      SELECT 11 AS Result, @lNextNumber As Id
	 END  	

END
GO
PRINT N'Altering Procedure [sActivity].[pEmployeeHealthCheckupEntryGet]...';


GO
ALTER PROCEDURE [sActivity].[pEmployeeHealthCheckupEntryGet]
	            
           @rHealthCheckupId int,
           @rStatusId int=0,
           @rBatchId int,
           @rDepartmentId int          
	
WITH EXECUTE AS CALLER	
AS
SET NOCOUNT ON
BEGIN
	 BEGIN TRY 
	 BEGIN TRANSACTION	
	   
	SELECT      
		ISNULL([HealthCheckupId],0) AS HealthCheckupId
		,ISNULL([HeightInCm],0) AS HeightInCm 
		,ISNULL([WeightInKg],0) AS WeightInKg
		,ISNULL([Dental],'') AS Dental
		,ISNULL([Nails],'') AS Nails
		,ISNULL([Hair],'') AS Hair
		,ISNULL([Skin],'') AS Skin
		,ISNULL([Ear],'') AS Ear
		,ISNULL([Nose],'') AS Nose
		,ISNULL([Throat],'') AS Throat
		,ISNULL([Respiratory],'') AS Respiratory
		,ISNULL([Cardiovascular],'') AS Cardiovascular
		,ISNULL([Nervous],'') AS Nervous
		,ISNULL([Eye],'') AS Eye
		,ISNULL([Other],'') AS Other
		,ISNULL([ImportantFinding],'') AS ImportantFinding
		,ISNULL([Remarks],'') AS Remarks
		,ISNULL([FollowupDetail],'') AS FollowupDetail
		,ISNULL(HT.[StatusId],0) AS StatusId
		,EC.EmployeeId AS EmployeeId
		,EC.EmployeeName AS EmployeeName
		,EC.Code AS EmployeeCode
		,EC.DepartmentId
		,EC.DepartmentName AS DepartmentName
		,EC.MobileNumber As MobileNumber
		,ISNULL(HT.BloodGroupId,0)AS BloodGroupId
			  
	FROM	sHrm.vEmployeeCommunication EC
		LEFT JOIN [sActivity].[tHealthCheckupEmployee] HT ON EC.EmployeeId = HT.EmployeeId	AND (HT.HealthCheckupId = @rHealthCheckupId  )
    	--INNER JOIN sCommon.tStatusMaster SMM ON SMM.Id = HT.StatusId	    		
  
	WHERE  (EC.StatusId = @rStatusId OR @rStatusId = 0)
		-- AND (HC.BatchId = @rBatchId OR @rBatchId = 0)
		 ANd (EC.DepartmentId = @rDepartmentId OR @rDepartmentId = 0)
			
	ORDER BY EC.Code ASC
      
	COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Altering Procedure [sActivity].[pHealthCheckupEmployeeGet]...';


GO
ALTER PROCEDURE [sActivity].[pHealthCheckupEmployeeGet]
	        
	       @rBuilder1 nvarchar(max)='',
		   @rBuilder2 nvarchar(max)='',     
           @rEmployeeId bigint,
           @rHealthCheckupId int,
           @rStatusId int,
           @rBatchId int,
           @rFromDate date = null,
           @rToDate date = null,
           @rDepartmentId int,
		   @rOrgId int  = 0         
	
WITH EXECUTE AS CALLER	
AS
SET NOCOUNT ON
BEGIN
	 BEGIN TRY 
	 BEGIN TRANSACTION	
	   
  SELECT      
			  @rBuilder1 AS Builder1
			  ,@rBuilder2 AS Builder2
			  ,[HealthCheckupId]     
	          ,HT.EmployeeId 
			  ,ISNULL([HeightInCm],0) AS HeightInCm 
			  ,ISNULL([WeightInKg],0) AS WeightInKg
			  ,[Dental]
			  ,[Nails]
			  ,[Hair]
			  ,[Skin]
			  ,[Ear]
			  ,[Nose]
			  ,[Throat]
			  ,[Respiratory]
			  ,[Cardiovascular]
			  ,[Nervous]
			  ,[Eye]
			  ,[Other]
			  ,[ImportantFinding]
			  ,[Remarks]
			  ,[FollowupDetail]
			  ,HT.[StatusId]	
			  ,EC.EmployeeId AS EmployeeId
			  ,EC.EmployeeName AS EmployeeName
			  ,EC.Code AS EmployeeCode
			  ,EC.DepartmentId
			  ,EC.DepartmentName AS DepartmentName
			  ,ISNULL(EPD.GenderId,0) AS GenderId
			  ,EC.MobileNumber As MobileNumber
			  ,BGM.Title AS BloodGroup
			  ,SMM.Title AS Status
			  ,HC.Title AS HealthCheckup
			  ,HC.DoctorName
			  ,HC.CheckupDate
			  ,ISNULL(HT.BloodGroupId,0)AS BloodGroupId
			  ,ISNULL(BGM.Title,'') AS BloodGroup
			  
  FROM		[sActivity].[tHealthCheckupEmployee] HT 
			INNER JOIN sHrm.vEmployeeCommunication EC ON EC.EmployeeId = HT.EmployeeId	
    		INNER JOIN sCommon.tStatusMaster SMM ON SMM.Id = HT.StatusId	
    		INNER JOIN sActivity.tHealthCheckup HC ON HC.Id = HT.HealthCheckupId  
    		LEFT JOIN [sHrm].[tEmployeePersonalDetail] EPD ON EPD.EmployeeId = EC.EmployeeId
    		LEFT JOIN sCommon.tBloodGroupMaster BGM ON EPD.BloodGroupId=BGM.Id
    		    		
  
  WHERE  (HT.HealthCheckupId = @rHealthCheckupId OR @rHealthCheckupId = 0)	
	     AND (HT.EmployeeId = @rEmployeeId OR @rEmployeeId =  0)
	     AND (HT.StatusId = @rStatusId OR @rStatusId = 0)
         AND (HC.CheckupDate >= @rFromDate OR ISNULL(@rFromDate,'') = '')
		 AND (HC.CheckupDate <= @rToDate OR ISNULL(@rToDate,'') = '')
		 AND (HC.BatchId = @rBatchId OR @rBatchId = 0)
		 AND (EC.DepartmentId = @rDepartmentId OR @rDepartmentId = 0)
		 AND (EC.OrgId = @rOrgId OR @rOrgId = 0)
			
		ORDER BY CheckupDate ASC
      
	COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Altering Procedure [sActivity].[pMyEventGet]...';


GO
ALTER PROCEDURE [sActivity].[pMyEventGet]
	 
	 @rSourceTypeId smallint,
	 @rSourceId bigint,
	 @rOrgId smallint,
	 @rBatchId int,
	 @rFromDate date='',
	 @rTodate date='',
	 @rEventTypeId int = 0
	 --@rSyncedEventScheduleId int = 0
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	IF(@rSourceTypeId=2003)
	BEGIN
	
	DECLARE @DivisionId int
	
	SELECT @DivisionId = DivisionId  FROM sStudent.tAcademic WHERE StudentId=@rSourceId 
					AND OrgId=@rOrgId AND BatchId=@rBatchId 
	
		SELECT
				ISNULL(EE.Id,0) AS Id,
				ES.Id AS EventScheduleId,
				ES.Title,
				ES.FromDate,
				ES.ToDate,
				ES.IsCommonForAll,
				ES.IsHoliday,
				ES.IsEnrollment,
				ES.CreatedDateTime,
				ES.Remark AS Remark,
				EE.Remark AS EventEnrollmentRemark
		FROM 
			sActivity.tEventSchedule ES
			LEFT JOIN sActivity.tEventEnrollment EE ON EE.EventScheduleId=ES.Id AND EE.SourceId=@rSourceId AND EE.SourceTypeId=2003
		WHERE 
	        
			 ((ES.Id IN(SELECT EventScheduleId FROM sActivity.tEventAssign WHERE SourceTypeId=2005 AND 
				SourceId= @DivisionId )) OR ES.ISCommonForAll = 1)
					
		AND (ES.BatchId=@rBatchId) 
		AND ((Convert(date,ES.FromDate)<=@rFromDate) OR ISNULL(@rFromDate,'')='')
		AND ((Convert(date,ES.Todate)>=@rTodate) OR ISNULL(@rTodate,'')='')
		AND (ES.EventTypeId = @rEventTypeId OR @rEventTypeId = 0)
		--AND (ES.Id > @rSyncedEventScheduleId OR @rSyncedEventScheduleId = 0)
		ORDER BY ES.FromDate DESC
		
		
		
	END
	ELSE
	BEGIN
		SELECT
				ISNULL(EE.Id,0) AS Id,
				ES.Id AS EventScheduleId,
				ES.Title,
				ES.FromDate,
				ES.ToDate,
				ES.IsCommonForAll,
				ES.IsHoliday,
				ES.IsEnrollment,
				ES.CreatedDateTime,
				ES.Remark AS Remark,
				EE.Remark AS EventEnrollmentRemark
		FROM 
				sActivity.tEventSchedule ES
			LEFT JOIN sActivity.tEventEnrollment EE ON EE.EventScheduleId=ES.Id AND EE.SourceId=@rSourceId AND EE.SourceTypeId=95
		WHERE 
	  
			 --(ES.Id IN(SELECT EventScheduleId FROM sActivity.tEventAssign WHERE SourceTypeId=2004 AND 
				--SourceId=(SELECT OrganizationDepartmentId FROM sHrm.vExtEmployeeJobDetail WHERE EmployeeId=@rSourceId))) 

				 (ES.Id IN(SELECT EventScheduleId FROM sActivity.tEventAssign WHERE SourceTypeId in(2004,95) AND 
				((SourceId=(SELECT OrganizationDepartmentId FROM sHrm.vExtEmployeeJobDetail WHERE EmployeeId=@rSourceId)) or
				(SourceId=@rSourceId)))) 

		AND (ES.BatchId=@rBatchId)
	   AND ((Convert(date,ES.FromDate)<=@rFromDate) OR ISNULL(@rFromDate,'')='')
		AND ((Convert(date,ES.Todate)>=@rTodate) OR ISNULL(@rTodate,'')='')
		AND (ES.EventTypeId = @rEventTypeId OR @rEventTypeId = 0)
		--AND (ES.Id > @rSyncedEventScheduleId OR @rSyncedEventScheduleId = 0)
		ORDER BY ES.FromDate DESC
	END
END
GO
PRINT N'Altering Procedure [sAdmission].[pRptAdmissionListUserWiseGet]...';


GO
ALTER PROCEDURE [sAdmission].[pRptAdmissionListUserWiseGet]
	
	
	 @rBatchId int,
	 @rClassId int,
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='',
	 @rFromDate date,
	 @rToDate date,
	 @rIsDetail bit =0,
	 @rCreatedUserName nvarchar(100)=''
AS
 SET NOCOUNT ON
			 

BEGIN 
	
	SET @rCreatedUserName = sCommon.fSearchStringGet(@rCreatedUserName)

	SELECT 
		 AF.FormNo,
		 AF.FirstName+' '+AF.MiddleName+' '+AF.LastName AS Name,
		 AF.ForClassId,
		 AF.BatchId,
		 AF.OrgId,
		 AF.City,
		 AF.FamilyCast,
		 CM.Title AS Class,
		 AF.FamilySubCast,
		 AF.CastCategoryId,
		 --for online and offline display same feename
		 AC.FormFeeName AS FeeName,
		 --in online entry display amount from pt  and in offline entry amount display from aff
		 CASE WHEN AF.DataEntryModeId = 561 THEN PT.PayAmount ELSE AFF.FeeAmount END  AS FeeAmount,
		 @rIsDetail AS IsDetail,
		 @rBuilder1 AS Builder1,
		 @rBuilder2 AS Builder2,
		 ISNULL(AF.CreatedDateTime,'') AS CreatedDateTime,
		 ISNULL(U.DisplayTitle,'') AS UserName
	 
	 FROM 
		sAdmission.tAdmissionForm AF	
		INNER JOIN sSetup.tClassMaster CM ON AF.ForClassId=CM.Id
		LEFT JOIN sAdmission.tAdmissionFormFee AFF ON AFF.AdmissionFormId = AF.Id
		LEFT JOIN sAdmission.tAdmissionCriteriaFee ACF ON ACF.Id = AFF.AdmissionCriteriaFeeId
		INNER JOIN sAdmission.tAdmissionCriteria AC ON AC.ClassId=CM.Id AND AC.BatchId = @rBatchId
		LEFT JOIN sOp.tPaymentTransaction PT ON AF.Id = PT.PayerSourceId AND PT.TransactionSourceTypeId = 2027 AND PT.TransactionStatusId IN (2,4)
		INNER JOIN sSecurity.tUser U ON U.Id=AF.CreatedUserId
	WHERE 	
		AF.BatchId=@rBatchId
		--AND AF.OrgId=@rOrgId
		AND ((AF.ForClassId=@rClassId) OR (@rClassId=0))	
		AND ((CONVERT(DATE,AF.CreatedDateTime) >= @rFromDate) OR (isnull(@rFromDate,'')=''))
	    AND ((CONVERT(DATE,AF.CreatedDateTime) <= @rToDate) OR (isnull(@rToDate,'')=''))
		AND ((ISNULL(U.DisplayTitle,'') like @rCreatedUserName) OR (ISNULL(@rCreatedUserName,'')=''))
	    ORDER BY AF.FormNo
END
GO
PRINT N'Altering Procedure [sAlert].[pClassworkStudentListGet]...';


GO
ALTER PROCEDURE [sAlert].[pClassworkStudentListGet]
	 
		 @rDivisionId bigint,
		 @rOrgId int,
	 	 @rBatchId int,	 	 	 	
	 	 @rTemplate nvarchar(max) 	,
		 @rMailSubject nvarchar(500)='',
		 @rSubjectId bigint,
		 @rClassworkId bigint
		
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	
	Select 
		SC.OrgGroupId,
		SC.OrgId,
		SC.AcademicId,
		SC.Code,
		SC.Name,
		SC.ParentContactNo AS MobileNo,	
		SC.ParentEmail AS EmailId,
		ISNULL(SC.StudentContactNo,'') AS StudentContactNo,
		ISNULL(SC.StudentEmail,'') AS StudentEmail,
		ISNULL(SC.FatherContactNo,'') AS FatherContactNo,
		ISNULL(SC.FatherMail,'') AS FatherMail,
		ISNULL(SC.MotherContactNo,'') AS MotherContactNo,
		ISNULL(SC.MotherMail,'') AS MotherMail,
		--@rTemplate AS MsgText,
		(replace
			(replace
				(replace
					(replace
						(replace(@rTemplate,'[TeacherName]',EM.FirstName +''+EM.MiddleName+''+EM.LastName), 
					'[SubjectName]',SM.Title),
				'[ClassWork]',AC.Classwork), 
			'[HomeWork]',AC.Homework), 
		'[HomeworkEndDate]',AC.HomeWorkEndDate)) AS MsgText,
		'2003' AS SourceTypeId,
		SC.StudentId AS SourceId,
		2003 AS ReceiverSourceTypeId,
		SC.StudentId AS ReceiverSourceId,
		@rMailSubject AS Subject,
		AC.ClassId,
		AC.DivisionId,
		AC.SubjectId,
		EM.FirstName +''+EM.MiddleName+''+EM.LastName AS TeacherName,
		SM.Title AS SubjectName,
		AC.Classwork,
		AC.Homework,
		AC.HomeWorkEndDate,
		SC.WhatsAppContactNo,
		AC.Id AS DocumentId
				
	From 
		sStudent.vStudentCommunication SC
		INNER JOIN sAcademic.tClasswork AC ON AC.ClassId = SC.ClassId AND AC.DivisionId=SC.DivisionId AND AC.BatchId =SC.BatchId
		INNER JOIN sStudent.vStudentAcademic SA  ON SC.AcademicId=SA.AcademicId AND SC.ClassId=SA.ClassId AND SC.DivisionId=SA.DivisionId
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SA.OrgId AND OM.Id=SC.OrgId
		INNER JOIN sSetup.tSubjectMaster SM ON SM.Id = AC.SubjectId
		INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id=AC.EmployeeId
	WHERE (SC.OrgId=@rOrgId)
		AND (SC.BatchId=@rBatchId)
		AND (SC.StatusId=1) AND SC.IsBlockAllAlert=0	
		AND (SC.DivisionId = @rDivisionId)
		AND (AC.SubjectId=@rSubjectId)
		AND AC.Id = @rClassworkId
END
GO
PRINT N'Altering Procedure [sAlert].[pEmployeeBiometricAbsentTimeGet]...';


GO

ALTER PROCEDURE [sAlert].[pEmployeeBiometricAbsentTimeGet]
	@rOrgId int,
	@rOrgGroupId int,
	@rTemplate nvarchar(max),
	@rSubject nvarchar(100),
	@rIntervalTime int=0,
	@rToDateTime dateTime=null,
	@rFromDateTime DateTime=null,
	@rEventId int =135
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY	
		BEGIN TRANSACTION 
			declare  @lBatchID INT
			SELECT @lBatchID = Id from sSetup.tBatchMaster Where OrgId = @rOrgId AND IsActive = 1

			--For Optimization
			declare @lCloudTransactionDataId bigint=0
			set @lCloudTransactionDataId= isnull((select Max(isnull(CloudTransactionDataId,0)) From sBiometric.tTempBiometricAlertData where OrgID =@rOrgId and AlertId=@rEventId and SourceTypeId=95),0)

			declare @lSMSTemplete nvarchar(max)='',@lMailTemplete nvarchar(max)='', @lWhatsappTemplete nvarchar(max)='',@lNotificationTemplete nvarchar(max)=''
			set @lMailTemplete=isnull((select isnull(Template,'') from sAlert.tEventTemplate where EventId=@rEventId AND OrgId=@rOrgId and AlertModeId = 1 and IsAutoSend=1),'')
			set @lSMSTemplete =isnull((select isnull(Template,'') from sAlert.tEventTemplate where EventId=@rEventId AND OrgId=@rOrgId and AlertModeId = 2 and IsAutoSend=1),'')
			set @lNotificationTemplete =isnull((select isnull(Template,'') from sAlert.tEventTemplate where EventId=@rEventId AND OrgId=@rOrgId and AlertModeId = 3 and IsAutoSend=1),'')
			set @lWhatsappTemplete =isnull((select isnull(Template,'') from sAlert.tEventTemplate where EventId=@rEventId AND OrgId=@rOrgId and AlertModeId = 4 and IsAutoSend=1),'')
			--For Optimization

			if object_id('tempdb..#tShift') is not null
			BEGIN
				DROP TABLE #tShift
			END
			CREATE TABLE #tShift(
					ShiftCode int NOT NULL
				)

			insert #tShift
			Select 
				ShiftCode
			FROM sBiometric.tShiftMasterCloud
			where  ((OrgGroupId = @rOrgGroupId) OR (@rOrgGroupId=0))  
			--AND IsOutTimeAlertTime=1
			--AND CAST(DATEADD(MINUTE,AlterGraceTime,StartTime) AS Time)<=cast([sCommon].[fGetDate]() as Time)
			--AND CAST(DATEADD(MINUTE,AlterGraceTime,StartTime) AS Time)>=cast(DATEADD(MINUTE,-@rIntervalTime,[sCommon].[fGetDate]()) as Time)
			AND CAST(DATEADD(MINUTE,AlterGraceTime,StartTime) AS Time)<=cast(@rToDateTime as Time)
			AND CAST(DATEADD(MINUTE,AlterGraceTime,StartTime) AS Time)>=cast(@rFromDateTime as Time)

			--select * from #tShift
			declare @lcount int=(SELECT COUNT(ShiftCode) FROM #tShift)

			if object_id('tempdb..#tTable') is not null
			BEGIN
				DROP TABLE #tTable
			END
			CREATE TABLE #tTable(
						SourceId bigint NOT NULL,
						In_Out_Time [datetime] NOT NULL,
						SourceTypeId int NOT NULL,
						CreatedDateTime [datetime] NOT NULL,--For Optimization
						AutoId bigint not null--For Optimization
					)

			if(@lcount>0)
			BEGIN
				insert into #tTable
				select SourceId,MIN(In_Out_Time),SourceTypeId
				,min(CDT.CreatedDateTime),min(CDT.Autoid) --For Optimization
				from [sBiometric].[tCloudTransactionData] CDT
				inner join #tShift tempShift ON tempShift.ShiftCode=CDT.ShiftCode 
				WHERE Attn_Dt=CONVERT(date,[sCommon].[fGetDate]())  AND SourceTypeId=95 
				--For Optimization
				AND CDT.Autoid>@lCloudTransactionDataId
				AND CDT.SourceId not in (select ReceiverSourceId From sBiometric.tTempBiometricAlertData where  OrgID =@rOrgId and AlertId=@rEventId and SourceTypeId=95 and cast(CreatedDateTime as date)=CONVERT(date,[sCommon].[fGetDate]()))
				--For Optimization
				Group by SourceId,SourceTypeId
			END
			
			--For Optimization
			DECLARE @AlertUniqueId uniqueidentifier = NEWID();
			
			Insert Into sBiometric.tTempBiometricAlertData
			SELECT 
				EM.MobileNumber AS MobileNo,	
				EM.CompanyEmail AS EmailId,
				'' AS MsgText,
				@rSubject AS Subject,
				95 AS ReceiverSourceTypeId,
				EM.EmployeeId AS ReceiverSourceId,
				EM.EmployeeName AS StudentName,
				EM.Code AS Code,
				ISNULL(EC.WhatsAppContactNo,'') AS WhatsAppContactNo,
				95 AS SourceTypeId,
				EM.EmployeeId AS SourceId,
				EM.OrgId,
				OM.OrgGroupId,
				ISNULL(Convert(varchar,temp.In_Out_Time,108),'') as Time,
				OM.DisplayTitle AS OrganizationTitle,
				temp.AutoId,
				@rFromDateTime,
				@rToDateTime,
				sCommon.fGetDate(),
				@rEventId,
				@AlertUniqueId
			FROM 
				sHrm.vEmployeeCommonDetail EM 
				Inner Join  [sHrm].[tEmployeeMaster] E on EM.EmployeeId=E.Id
				INNER JOIN #tShift tempshift ON tempshift.ShiftCode=E.ShiftId
				LEFT JOIN #tTable temp ON  temp.SourceId=EM.EmployeeId
				LEFT JOIN sHrm.tEmployeeCommunications EC ON EC.EmployeeId = EM.EmployeeId
				LEFT JOIN sSetup.tOrganizationMaster OM ON EM.OrgID = OM.Id
			WHERE
				EM.OrgID =@rOrgId
				AND temp.In_Out_Time is null
				AND E.StatusId = 7  -- Added
				AND ([sHrm].[fWeekHOffGetBio](EM.EmployeeId , YEAR([sCommon].[fGetDate]()) ,MONTH([sCommon].[fGetDate]()) ,DAY([sCommon].[fGetDate]()),@lBatchID ,OrganizationDepartmentId ,@rOrgId )<>'W')
				AND ([sHrm].[fWeekHOffGetBio](EM.EmployeeId , YEAR([sCommon].[fGetDate]()) ,MONTH([sCommon].[fGetDate]()) ,DAY([sCommon].[fGetDate]()),@lBatchID ,OrganizationDepartmentId ,@rOrgId )<> 'H')

			
			--select * from #tTable
				select 
					MobileNo,	
					EmailId,
					replace (
					replace(@lSMSTemplete,'[EmployeeName]',StudentName),
					'[AbsentDate]',ISNULL(Convert(varchar,[sCommon].[fGetDate](),103),''))
					 AS SMSText,
					replace (
					replace(@lMailTemplete,'[EmployeeName]',StudentName),
					'[AbsentDate]',ISNULL(Convert(varchar,[sCommon].[fGetDate](),103),''))
					 AS MailText,
					replace (
					replace(@lNotificationTemplete,'[EmployeeName]',StudentName),
					'[AbsentDate]',ISNULL(Convert(varchar,[sCommon].[fGetDate](),103),''))
					 AS NotificationText,
					replace (
					replace(@lWhatsappTemplete,'[EmployeeName]',StudentName),					
					'[AbsentDate]',ISNULL(Convert(varchar,[sCommon].[fGetDate](),103),''))
					 AS WhatsappText,
					Subject,
					ReceiverSourceTypeId,
					ReceiverSourceId,
					StudentName AS EmployeeName,
					Code,
					WhatsAppContactNo,
					SourceTypeId,
					SourceId,
					OrgId,
					OrganizationTitle
				FROM  
					sBiometric.tTempBiometricAlertData
				where 
					AlertUniqueId=@AlertUniqueId
			--For Optimization

			DROP TABLE #tTable
			DROP TABLE #tShift
		COMMIT TRANSACTION
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH
END
GO
PRINT N'Altering Procedure [sAlert].[pEmployeeBiometricFirstInTimeGet]...';


GO

ALTER PROCEDURE [sAlert].[pEmployeeBiometricFirstInTimeGet]
	@rTemplate nvarchar(max)='',
	@rSubject nvarchar(100)='',
	@rOrgId int,
	@rIntervalTime int=0,
	@rToDateTime dateTime,
	@rFromDateTime DateTime,
	@rEventId int=127
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY	
		BEGIN TRANSACTION 

			--For Optimization
			declare @lCloudTransactionDataId bigint=0
			set @lCloudTransactionDataId= isnull((select Max(isnull(CloudTransactionDataId,0)) From sBiometric.tTempBiometricAlertData where OrgID =@rOrgId and AlertId=@rEventId and SourceTypeId=95),0)

			declare @lSMSTemplete nvarchar(max)='',@lMailTemplete nvarchar(max)='', @lWhatsappTemplete nvarchar(max)='',@lNotificationTemplete nvarchar(max)=''
			set @lMailTemplete=isnull((select isnull(Template,'') from sAlert.tEventTemplate where EventId=@rEventId AND OrgId=@rOrgId and AlertModeId = 1 and IsAutoSend=1),'')
			set @lSMSTemplete =isnull((select isnull(Template,'') from sAlert.tEventTemplate where EventId=@rEventId AND OrgId=@rOrgId and AlertModeId = 2 and IsAutoSend=1),'')
			set @lNotificationTemplete =isnull((select isnull(Template,'') from sAlert.tEventTemplate where EventId=@rEventId AND OrgId=@rOrgId and AlertModeId = 3 and IsAutoSend=1),'')
			set @lWhatsappTemplete =isnull((select isnull(Template,'') from sAlert.tEventTemplate where EventId=@rEventId AND OrgId=@rOrgId and AlertModeId = 4 and IsAutoSend=1),'')
			--For Optimization

			if object_id('tempdb..#tTable') is not null
			BEGIN
				DROP TABLE #tTable
			END
			CREATE TABLE #tTable(
					SourceId bigint NOT NULL,
					In_Out_Time [datetime] NOT NULL,
					SourceTypeId int NOT NULL,
					CreatedDateTime [datetime] NOT NULL,
					AutoId bigint not null--For Optimization
				)
			insert into #tTable
			select SourceId,min(In_Out_Time),SourceTypeId,min(CreatedDateTime) 
			,min(Autoid) --For Optimization
			from [sBiometric].[tCloudTransactionData]  
			WHERE Attn_Dt=CONVERT(date,[sCommon].[fGetDate]()) AND SourceTypeId=95 
			--For Optimization
			AND Autoid>@lCloudTransactionDataId
			AND SourceId not in (select ReceiverSourceId From sBiometric.tTempBiometricAlertData where  OrgID =@rOrgId and AlertId=@rEventId and SourceTypeId=95 and cast(CreatedDateTime as date)=CONVERT(date,[sCommon].[fGetDate]()))
			--For Optimization
			Group by SourceId,SourceTypeId
	
			--select * from #tTable
			--For Optimization
			DECLARE @AlertUniqueId uniqueidentifier = NEWID();
			
			Insert Into sBiometric.tTempBiometricAlertData
			SELECT 
				EM.MobileNumber AS MobileNo,	
				EM.CompanyEmail AS EmailId,
				'' AS MsgText,
				@rSubject AS Subject,
				95 AS ReceiverSourceTypeId,
				EM.EmployeeId AS ReceiverSourceId,
				EM.EmployeeName AS StudentName,
				EM.Code AS Code,
				ISNULL(EC.WhatsAppContactNo,'') AS WhatsAppContactNo,
				95 AS SourceTypeId,
				EM.EmployeeId AS SourceId,
				EM.OrgId,
				OM.OrgGroupId,
				ISNULL(Convert(varchar,temp.In_Out_Time,108),'') as Time,
				OM.DisplayTitle AS OrganizationTitle,
				temp.AutoId,
				@rFromDateTime,
				@rToDateTime,
				sCommon.fGetDate(),
				@rEventId,
				@AlertUniqueId
			FROM 
				#tTable temp
				Inner join sHrm.vEmployeeCommonDetail EM ON temp.SourceId=EM.EmployeeId
				LEFT JOIN sHrm.tEmployeeCommunications EC ON EC.EmployeeId = EM.EmployeeId
				INNER JOIN sSetup.tOrganizationMaster OM ON EM.OrgID = OM.Id
			WHERE
				--temp.CreatedDateTime >= DATEADD(minute,-(@rIntervalTime),[sCommon].[fGetDate]())
				temp.CreatedDateTime < @rToDateTime
				AND temp.CreatedDateTime >= @rFromDateTime
				AND EM.OrgID =@rOrgId
				--AND E.EmployeeStatusId = 7  -- Added

			SELECT 
				MobileNo,	
				EmailId,
				replace (
				replace (
				replace (
				replace(@lSMSTemplete,'[EmployeeName]',StudentName),
				'[TimeStamp]',ISNULL(Convert(varchar,Time,108),'')),
				'[PresentTime]',ISNULL(Convert(varchar,Time,108),'')),
				'[PresentDate]',ISNULL(Convert(varchar,[sCommon].[fGetDate](),103),''))
				AS SMSText,
				replace (
				replace (
				replace (
				replace(@lMailTemplete,'[EmployeeName]',StudentName),
				'[TimeStamp]',ISNULL(Convert(varchar,Time,108),'')),
				'[PresentTime]',ISNULL(Convert(varchar,Time,108),'')),
				'[PresentDate]',ISNULL(Convert(varchar,[sCommon].[fGetDate](),103),''))
				AS MailText,
				replace (
				replace (
				replace (
				replace(@lNotificationTemplete,'[EmployeeName]',StudentName),
				'[TimeStamp]',ISNULL(Convert(varchar,Time,108),'')),
				'[PresentTime]',ISNULL(Convert(varchar,Time,108),'')),
				'[PresentDate]',ISNULL(Convert(varchar,[sCommon].[fGetDate](),103),''))
				AS NotificationText,
				replace (
				replace (
				replace (
				replace(@lWhatsappTemplete,'[EmployeeName]',StudentName),
				'[TimeStamp]',ISNULL(Convert(varchar,Time,108),'')),
				'[PresentTime]',ISNULL(Convert(varchar,Time,108),'')),
				'[PresentDate]',ISNULL(Convert(varchar,[sCommon].[fGetDate](),103),''))
				AS WhatsappText,
				Subject,
				ReceiverSourceTypeId,
				ReceiverSourceId,
				StudentName AS EmployeeName,
				Code,
				WhatsAppContactNo,
				SourceTypeId,
				SourceId,
				OrgId,
				OrgGroupId,
				Time,
				OrganizationTitle
			FROM 
				sBiometric.tTempBiometricAlertData
			where 
				AlertUniqueId=@AlertUniqueId

			DROP TABLE #tTable
		COMMIT TRANSACTION
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH


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


GO

ALTER PROCEDURE [sAlert].[pEmployeeBiometricLastOutTimeGet]
	@rTemplate nvarchar(max)='',
	@rSubject nvarchar(100)='',
	@rOrgId int,
	@rOrgGroupId int,
	@rIntervalTime int=0,
	@rToDateTime dateTime=null,
	@rFromDateTime DateTime=null
 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY	
		BEGIN TRANSACTION 
			declare @lCloudTransactionDataId bigint=0
			set @lCloudTransactionDataId= isnull((select Max(isnull(CloudTransactionDataId,0)) From sBiometric.tTempBiometricAlertData where  OrgID =@rOrgId and AlertId=128 and SourceTypeId=95),0)
			declare @lSMSTemplete nvarchar(max)='',@lMailTemplete nvarchar(max)='', @lWhatsappTemplete nvarchar(max)='',@lNotificationTemplete nvarchar(max)=''
			set @lMailTemplete=isnull((select isnull(Template,'') from sAlert.tEventTemplate where EventId=128 AND OrgId=@rOrgId and AlertModeId = 1 and IsAutoSend=1),'')
			set @lSMSTemplete =isnull((select isnull(Template,'') from sAlert.tEventTemplate where EventId=128 AND OrgId=@rOrgId and AlertModeId = 2 and IsAutoSend=1),'')
			set @lNotificationTemplete =isnull((select isnull(Template,'') from sAlert.tEventTemplate where EventId=128 AND OrgId=@rOrgId and AlertModeId = 3 and IsAutoSend=1),'')
			set @lWhatsappTemplete =isnull((select isnull(Template,'') from sAlert.tEventTemplate where EventId=128 AND OrgId=@rOrgId and AlertModeId = 4 and IsAutoSend=1),'')
			set @rSubject=isnull((select isnull(MailSubject,'') from sAlert.tEventTemplate where EventId=128 AND OrgId=@rOrgId and AlertModeId = 1 ),'')
			--declare @lcount int=(SELECT COUNT(ShiftCode) FROM #tShift)
	 
			--select * from #tShift
			if object_id('tempdb..#tTable') is not null
			BEGIN
				DROP TABLE #tTable
			END
			CREATE TABLE #tTable(
						SourceId bigint NOT NULL,
						In_Out_Time [datetime] NOT NULL,
						SourceTypeId int NOT NULL,
						OutTimeAlertTime time NOT NULL,
						CreatedDateTime [datetime] NOT NULL
					)
			--if(@lcount>0)
			BEGIN
				insert into #tTable
				select SourceId,MAX(In_Out_Time),SourceTypeId,cast(SMC.OutTimeAlertTime as time),Max(CreatedDateTime) 
				from [sBiometric].[tCloudTransactionData] CDT 
				INNER JOIN sBiometric.tShiftMasterCloud SMC on SMC.ShiftCode=CDT.ShiftCode
				WHERE Attn_Dt=CONVERT(date,[sCommon].[fGetDate]())  AND SourceTypeId=95 
				Group by SourceId,SourceTypeId,SMC.OutTimeAlertTime
			END

			--select * from #tTable
			DECLARE @AlertUniqueId uniqueidentifier = NEWID();
			Insert Into sBiometric.tTempBiometricAlertData
			SELECT 
				EM.MobileNumber AS MobileNo,	
				EM.CompanyEmail AS EmailId,
				'' AS MsgText,
				@rSubject AS Subject,
				95 AS ReceiverSourceTypeId,
				EM.EmployeeId AS ReceiverSourceId,
				EM.EmployeeName AS StudentName,
				EM.Code AS Code,
				ISNULL(EC.WhatsAppContactNo,'') AS WhatsAppContactNo,
				95 AS SourceTypeId,
				EM.EmployeeId AS SourceId,
				EM.OrgId,
				OM.OrgGroupId,
				ISNULL(Convert(varchar,temp.In_Out_Time,108),'') as Time,
				OM.DisplayTitle AS OrganizationTitle,
				temp.AutoId,
				@rFromDateTime,
				@rToDateTime,
				sCommon.fGetDate(),
				128,
				@AlertUniqueId
			FROM 
				#tTable temp
				Inner join sHrm.vEmployeeCommonDetail EM ON temp.SourceId=EM.EmployeeId
				LEFT JOIN sHrm.tEmployeeCommunications EC ON EC.EmployeeId = EM.EmployeeId
				INNER JOIN sSetup.tOrganizationMaster OM ON EM.OrgID = OM.Id
			WHERE
				
				temp.OutTimeAlertTime < cast(@rToDateTime as Time)
				AND temp.OutTimeAlertTime >= Cast(@rFromDateTime As Time)
				AND EM.OrgID =@rOrgId

			select 
					MobileNo,	
					EmailId,
					replace (
					replace(@lSMSTemplete,'[EmployeeName]',StudentName),
					'[TimeStamp]',ISNULL(Convert(varchar,[sCommon].[fGetDate](),108),''))
					 AS SMSText,
					replace (
					replace(@lMailTemplete,'[EmployeeName]',StudentName),
					'[TimeStamp]',ISNULL(Convert(varchar,[sCommon].[fGetDate](),108),''))
					 AS MailText,
					replace (
					replace(@lNotificationTemplete,'[EmployeeName]',StudentName),
					'[TimeStamp]',ISNULL(Convert(varchar,[sCommon].[fGetDate](),108),''))
					 AS NotificationText,
					replace (
					replace(@lWhatsappTemplete,'[EmployeeName]',StudentName),					
					'[TimeStamp]',ISNULL(Convert(varchar,[sCommon].[fGetDate](),108),''))
					 AS WhatsappText,
					Subject,
					ReceiverSourceTypeId,
					ReceiverSourceId,
					StudentName AS EmployeeName,
					Code,
					WhatsAppContactNo,
					SourceTypeId,
					SourceId,
					OrgId,
					OrgGroupId,
					OrganizationTitle
				FROM  
					sBiometric.tTempBiometricAlertData
				where 
					AlertUniqueId=@AlertUniqueId


			DROP TABLE #tTable
			--DROP TABLE #tShift
		COMMIT TRANSACTION
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH
END
GO
PRINT N'Altering Procedure [sAlert].[pEmployeeBiometricLateTimeGet]...';


GO

ALTER PROCEDURE [sAlert].[pEmployeeBiometricLateTimeGet]
	 	 
	 	 @rOrgId int,
		 @rTemplate nvarchar(max)='',
		@rSubject nvarchar(100)=''
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	DECLARE @lDate date = ''
	SET @lDate = sCommon.fGetDate()

	DECLARE @lDay as nvarchar(3)

	Select @lDay  = RIGHT('00' + CAST(DATEPART(dd,@lDate) AS varchar(2)), 2)

	DECLARE @lColumnName varchar(10) = '',@lShiftColumntName varchar(10) = ''
	SET @lColumnName = 'MT.D' + CAST(@lDay AS VARCHAR) + '_IN'
	SET @lShiftColumntName = 'MT.D' + CAST(@lDay AS VARCHAR) + '_S'

	DECLARE @lGetConfigTime nvarchar(20) = ''
	SELECT @lGetConfigTime =  ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 398 AND SourceId = @rOrgId

			declare @lSMSTemplete nvarchar(max)='',@lMailTemplete nvarchar(max)='', @lWhatsappTemplete nvarchar(max)='',@lNotificationTemplete nvarchar(max)=''
			set @lMailTemplete=isnull((select isnull(Template,'') from sAlert.tEventTemplate where EventId=137 AND OrgId=@rOrgId and AlertModeId = 1 and IsAutoSend=1),'')
			set @lSMSTemplete =isnull((select isnull(Template,'') from sAlert.tEventTemplate where EventId=137 AND OrgId=@rOrgId and AlertModeId = 2 and IsAutoSend=1),'')
			set @lNotificationTemplete =isnull((select isnull(Template,'') from sAlert.tEventTemplate where EventId=137 AND OrgId=@rOrgId and AlertModeId = 3 and IsAutoSend=1),'')
			set @lWhatsappTemplete =isnull((select isnull(Template,'') from sAlert.tEventTemplate where EventId=137 AND OrgId=@rOrgId and AlertModeId = 4 and IsAutoSend=1),'')

	IF(@lGetConfigTime <> '' AND LEN(@lGetConfigTime) > 0)
	BEGIN
	DECLARE @Query NVARCHAR(MAX) = ''
	SET @Query = 'SELECT
					EC.MobileNumber AS MobileNo,	
					EC.CompanyEmail AS EmailId,
					replace (
					replace (
					replace('''+CONVERT(nvarchar(MAX),@rTemplate)+''',''[EmployeeName]'',EC.EmployeeName),
					''[LateTime]'','+@lColumnName+'),
					''[LateDate]'',ISNULL(Convert(varchar,[sCommon].[fGetDate](),103),''''))
					 AS MsgText,
					 replace (
					replace (
					replace('''+CONVERT(nvarchar(MAX),@lSMSTemplete)+''',''[EmployeeName]'',EC.EmployeeName),
					''[LateTime]'','+@lColumnName+'),
					''[LateDate]'',ISNULL(Convert(varchar,[sCommon].[fGetDate](),103),''''))
					 AS SMSText,
					 replace (
					replace (
					replace('''+CONVERT(nvarchar(MAX),@lMailTemplete)+''',''[EmployeeName]'',EC.EmployeeName),
					''[LateTime]'','+@lColumnName+'),
					''[LateDate]'',ISNULL(Convert(varchar,[sCommon].[fGetDate](),103),''''))
					 AS MailText,
					 replace (
					replace (
					replace('''+CONVERT(nvarchar(MAX),@lNotificationTemplete)+''',''[EmployeeName]'',EC.EmployeeName),
					''[LateTime]'','+@lColumnName+'),
					''[LateDate]'',ISNULL(Convert(varchar,[sCommon].[fGetDate](),103),''''))
					 AS NotificationText,
					  replace (
					replace (
					replace('''+CONVERT(nvarchar(MAX),@lWhatsappTemplete)+''',''[EmployeeName]'',EC.EmployeeName),
					''[LateTime]'','+@lColumnName+'),
					''[LateDate]'',ISNULL(Convert(varchar,[sCommon].[fGetDate](),103),''''))
					 AS WhatsappText,
					'''+CONVERT(nvarchar(20),@rSubject)+''' AS Subject,
					95 AS ReceiverSourceTypeId,
					EC.EmployeeId AS ReceiverSourceId,
					EC.EmployeeName AS EmployeeName,
					ISNULL(EC1.WhatsAppContactNo,'''') AS WhatsAppContactNo,
					95 AS SourceTypeId,
					EC.EmployeeId AS SourceId,
					EC.OrgId,
					OM.OrgGroupId,
					EM.Id AS EmployeeId,
					EM.Code,
					ISNULL(EM.FirstName, '''') + '' '' + ISNULL(EM.LastName, '''') AS  EmployeeName,
					 '+@lColumnName+' AS Time,
					OM.DisplayTitle AS OrganizationTitle
		FROM 
				sHrm.tEmployeeMaster EM
				Inner join sHrm.vEmployeeCommonDetail EC ON EM.Id=EC.EmployeeId
				LEFT JOIN sHrm.tEmployeeCommunications EC1 ON EC1.EmployeeId = EC.EmployeeId
				INNER JOIN sBiometric.tMonthTrans MT ON MT.EmployeeId = EM.Id AND MT.SourceTypeId = 95 
				INNER JOIN sSetup.tOrganizationMaster OM ON EM.OrgID = OM.Id
				INNER Join sBiometric.tShiftMasterCloud SM ON SM.ShiftName='+@lShiftColumntName+'
		WHERE
				EM.OrgID = '+CONVERT(nvarchar(20),@rOrgId)+'
				AND MONTH(MT.Attn_dt) = MONTH('''+CONVERT(nvarchar(20),@lDate)+''')
				AND '+@lColumnName+' > DATEADD(minute, SM.GraceAfter,SM.StartTime)
				--AND '+@lColumnName+' > '''+@lGetConfigTime+'''
				AND EM.StatusId = 7	'
		--print (@Query)
		execute (@Query)	
	END

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


GO
ALTER PROCEDURE [sAlert].[pNewQueryDetailsGet]
	 	 
	 	 @rQueryId bigint,	 	 
	 	 @rSubject nvarchar(100),
	 	 @rTemplate nvarchar(max),
	 	 @rFromSourceTypeId smallint,
		 @rOrgId int,
		 @rQueryFrom nvarchar(200)
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	DECLARE @AssignedTo bigint;
	DECLARE @AssignedToEmailId varchar(100);
	
	IF(@rQueryFrom = 'Query')
	BEGIN
	IF(@rFromSourceTypeId=2003)
	BEGIN
		   SELECT 
			 QM.Id AS QueryId,
		     (ISNULL(SC.ParentEmail,'')) AS EmailId,
		    -- 'mohit.patel@vidyalayaschoolsoftware.com' AS EmailId,
		     ISNULL(SC.ParentContactNo,'') AS MobileNo,
		     replace(replace(@rTemplate,'[Name]',SC.Name),'[QueryNo]',QM.number) AS MsgText,
		     @rSubject AS Subject,
			 2003 AS ReceiverSourceTypeId,
			 SC.StudentId AS ReceiverSourceId,
			 OM.Id AS OrgId,
			 OM.OrgGroupId,
			 2003 AS SourceTypeId,
			 SC.StudentId AS SourceId  ,
			 SC.Name AS Name,
			 QM.number AS QueryNo,
			 SC.WhatsAppContactNo,
			 QM.Id AS DocumentId
			
	       FROM 
			sCommunication.tQuery QM
			INNER JOIN [sStudent].[vStudentCommunication] SC ON QM.FromSourceId=SC.StudentId
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SC.BatchId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SC.OrgId
			
		
	      WHERE
		    QM.Id = @rQueryId AND FromSourceTypeId=@rFromSourceTypeId AND BM.IsActive=1 AND SC.IsBlockAllAlert=0
	END
   
    IF(@rFromSourceTypeId=95)
	BEGIN
		
		   SELECT 
		     QM.Id AS QueryId,
		     (ISNULL(EM.CompanyEmail,'')) AS EmailId,		    
		     ISNULL(EM.MobileNumber,'') AS MobileNo,
		     replace(replace(@rTemplate,'[Name]',EM.EmployeeName),'[QueryNo]',QM.number) AS MsgText,
		     @rSubject AS Subject,
		     95 AS ReceiverSourceTypeId,
			 EM.EmployeeId AS ReceiverSourceId,
			 OM.Id AS OrgId,
			 OM.OrgGroupId,
			 95 AS SourceTypeId,
			 EM.EmployeeId AS SourceId,
			 ISNULL(EC.WhatsAppContactNo,'') AS WhatsAppContactNo,
			 QM.Id AS DocumentId
		     
	       FROM 
			sCommunication.tQuery QM
			INNER JOIN sHrm.vEmployeeCommonDetail EM ON QM.FromSourceId=EM.EmployeeId 
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = EM.OrgId
			LEFT JOIN sHrm.tEmployeeCommunications EC ON EC.EmployeeId = EM.EmployeeId
		
	      WHERE
		    QM.Id = @rQueryId AND FromSourceTypeId=@rFromSourceTypeId
		
	END
		
	IF(@rFromSourceTypeId=96)
	BEGIN
		
		   SELECT 
		     QM.Id AS QueryId,
		     (ISNULL(EM.CompanyEmail,'')) AS EmailId,		    
		     ISNULL(EM.MobileNumber,'') AS MobileNo,
		     replace(replace(@rTemplate,'[Name]',EM.EmployeeName),'[QueryNo]',QM.number) AS MsgText,
		     @rSubject AS Subject,
		     96 AS ReceiverSourceTypeId,
			 EM.EmployeeId AS ReceiverSourceId,
			 OM.Id AS OrgId,
			 OM.OrgGroupId,
			 96 AS SourceTypeId,
			 EM.EmployeeId AS SourceId,
			 ISNULL(EC.WhatsAppContactNo,'') AS WhatsAppContactNo,
			 QM.Id AS DocumentId
		     
	       FROM 
			sCommunication.tQuery QM
			INNER JOIN sHrm.vEmployeeCommonDetail EM ON QM.AssignedToEmployeeId=EM.EmployeeId 
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = EM.OrgId
			LEFT JOIN sHrm.tEmployeeCommunications EC ON EC.EmployeeId = EM.EmployeeId
		
	      WHERE
		    QM.Id = @rQueryId 
		
		END
	END
	--Alert from My Query
	ELSE
	BEGIN
		SELECT 
		     QM.Id AS QueryId,
		     ISNULL(EM.CompanyEmail,'') AS EmailId,		    
		     ISNULL(EM.MobileNumber,'') AS MobileNo,
			 replace(replace(@rTemplate,'[Name]',EM.EmployeeName),'[QueryNo]',QM.number) AS MsgText,
		     @rSubject AS Subject,
			 95 AS ReceiverSourceTypeId,
			 EM.EmployeeId AS ReceiverSourceId,
			 QM.OrgGroupId,
			 @rOrgId AS OrgId,
			 EM.EmployeeId AS SourceId,
			 95 AS SourceTypeId,
			 ISNULL(EC.WhatsAppContactNo,'') AS WhatsAppContactNo,
			 QM.Id AS DocumentId
		     
	       FROM 
			sCommunication.tQuery QM
			INNER JOIN sCommunication.tQueryCategoryMaster QCM ON QCM.Id = QM.QueryCategoryId
			INNER JOIN sCommunication.tQueryCategoryAssignedTo QCA ON QCA.QueryCategoryId = QCM.Id
			INNER JOIN sHrm.vEmployeeCommonDetail EM ON EM.EmployeeId = QCA.SourceId
			LEFT JOIN sHrm.tEmployeeCommunications EC ON EC.EmployeeId = EM.EmployeeId
		
	      WHERE
		    QM.Id = @rQueryId 
	END
		
END
GO
PRINT N'Altering Procedure [sAlert].[pQueryCommentGet]...';


GO
 
ALTER PROCEDURE [sAlert].[pQueryCommentGet]
	 	 
		 @rOrgId int,
	 	 @rQueryId bigint,	 	 
	 	 @rSubject nvarchar(100),
		 @rRemark nvarchar(1000),
	 	 @rTemplate nvarchar(max),
	 	 @rFromSourceTypeId smallint,
		 @rQueryFrom varchar(100)
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	IF(@rQueryFrom = 'QueryList')
	BEGIN
	   SELECT 
			 QM.Id AS QueryId,
		     ISNULL(EM.CompanyEmail,'') AS EmailId,		    
		     ISNULL(EM.MobileNumber,'') AS MobileNo,
		    replace (	
		      replace (	
				 replace (
				         replace(
				                  --@rTemplate,'[User]',EM.EmployeeName),
								   @rTemplate,'[User]',
								   CASE WHEN @rFromSourceTypeId = 2003 THEN 'Student' 
								   WHEN @rFromSourceTypeId = 95 THEN 'Employee' 
								   ELSE 'Admin' END),
								  '[Comment]',@rRemark),
								  --'[Time]',QM.CreatedDateTime),
								  '[Time]',GetDate()),
								  '[Query]',QM.Title) 
				            AS MsgText,
		     
		     @rSubject AS Subject,
			 95 AS ReceiverSourceTypeId,
			 EM.EmployeeId AS ReceiverSourceId,
			 QM.OrgGroupId,
			 @rOrgId AS OrgId,
			 EM.EmployeeId AS SourceId,
			 95 AS SourceTypeId,
			 ISNULL(EC.WhatsAppContactNo,'') AS WhatsAppContactNo
		     
	       FROM 
			sCommunication.tQuery QM
			INNER JOIN sCommunication.tQueryCategoryMaster QCM ON QCM.Id = QM.QueryCategoryId
			INNER JOIN sCommunication.tQueryCategoryAssignedTo QCA ON QCA.QueryCategoryId = QCM.Id
			INNER JOIN sHrm.vEmployeeCommonDetail EM ON EM.EmployeeId = QCA.SourceId
			LEFT JOIN sHrm.tEmployeeCommunications EC ON EC.EmployeeId = EM.EmployeeId
	      WHERE
		    QM.Id = @rQueryId 
	END
	ELSE
	BEGIN
	IF(@rFromSourceTypeId=2003)
		BEGIN
	
		 SELECT 
			QM.Id AS QueryId,
		    ISNULL(SC.ParentEmail,'') AS EmailId,
			ISNULL(SC.ParentContactNo,'') AS MobileNo,
			replace (	
				replace (
				    replace (
				         replace(
				                  --@rTemplate,'[User]',SC.Name),
								  @rTemplate,'[User]','Student'),
								   '[Comment]',@rRemark),
								   --'[Time]',QM.CreatedDateTime),
								   '[Time]',GetDate()),
								 '[Query]',QM.Title) 
				            AS MsgText,
		     
		       @rSubject AS Subject,
			   2003 AS ReceiverSourceTypeId,
			   SC.StudentId AS ReceiverSourceId  ,
			   SC.Name AS Name,
			   (CASE WHEN QM.StatusId = 209 THEN 'Open' WHEN QM.StatusId = 210 THEN 'Closed' WHEN QM.StatusId = 709 THEN 'Hold' ELSE '' END) [Status],
				QM.number AS QueryNo,
				SC.WhatsAppContactNo,
				QM.OrgGroupId,
				@rOrgId AS OrgId,
				SC.StudentId AS SourceId,
				2003 AS SourceTypeId
	       FROM 
			sCommunication.tQuery QM
			INNER JOIN [sStudent].[vStudentCommunication] SC ON QM.FromSourceId=SC.StudentId
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SC.BatchId

	      WHERE
		    QM.Id = @rQueryId AND BM.IsActive=1 
		
		END
   
   IF(@rFromSourceTypeId=95)
		BEGIN
			SELECT 
			QM.Id AS QueryId,
		    ISNULL(EM.CompanyEmail,'') AS EmailId,		    
		    ISNULL(EM.MobileNumber,'') AS MobileNo,
		    replace (	
		      replace (	
				 replace (
				         replace(
				                  --@rTemplate,'[User]',EM.EmployeeName),
								   @rTemplate,'[User]','Employee'),
								  '[Comment]',@rRemark),
								  --'[Time]',QM.CreatedDateTime),
								  '[Time]',GetDate()),
								  '[Query]',QM.Title) 
				            AS MsgText,
		     
		     @rSubject AS Subject,
			 95 AS ReceiverSourceTypeId,
			 EM.EmployeeId AS ReceiverSourceId,
			 QM.OrgGroupId ,
			 @rOrgId AS OrgId ,
			 EM.EmployeeId AS SourceId,
			 95 AS SourceTypeId,
			 ISNULL(EC.WhatsAppContactNo,'') AS WhatsAppContactNo
		     
	       FROM 
			sCommunication.tQuery QM
			INNER JOIN sHrm.vEmployeeCommonDetail EM ON QM.FromSourceId=EM.EmployeeId
			LEFT JOIN sHrm.tEmployeeCommunications EC ON EC.EmployeeId = EM.EmployeeId
		
	      WHERE
		    QM.Id = @rQueryId 

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


GO

ALTER PROCEDURE [sAlert].[pStudentBiometricAbsentTimeGet]
	@rOrgId int,
	@rOrgGroupId int,
	@rTemplate nvarchar(max),
	@rSubject nvarchar(100)='',
	@rIntervalTime int=0,
	@rToDateTime dateTime=null,
	@rFromDateTime DateTime=null,
	@rEventId int=136

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY	
		BEGIN TRANSACTION 
			declare  @lBatchID INT
			SELECT @lBatchID = Id from sSetup.tBatchMaster Where OrgId = @rOrgId AND IsActive = 1
			
			--For Optimization
			declare @lCloudTransactionDataId bigint=0
			set @lCloudTransactionDataId= isnull((select Max(isnull(CloudTransactionDataId,0)) From sBiometric.tTempBiometricAlertData where  OrgID =@rOrgId and AlertId=@rEventId and SourceTypeId=2003),0)

			declare @lSMSTemplete nvarchar(max)='',@lMailTemplete nvarchar(max)='', @lWhatsappTemplete nvarchar(max)='',@lNotificationTemplete nvarchar(max)=''
			set @lMailTemplete=isnull((select isnull(Template,'') from sAlert.tEventTemplate where EventId=@rEventId AND OrgId=@rOrgId and AlertModeId = 1 and IsAutoSend=1),'')
			set @lSMSTemplete =isnull((select isnull(Template,'') from sAlert.tEventTemplate where EventId=@rEventId AND OrgId=@rOrgId and AlertModeId = 2 and IsAutoSend=1),'')
			set @lNotificationTemplete =isnull((select isnull(Template,'') from sAlert.tEventTemplate where EventId=@rEventId AND OrgId=@rOrgId and AlertModeId = 3 and IsAutoSend=1),'')
			set @lWhatsappTemplete =isnull((select isnull(Template,'') from sAlert.tEventTemplate where EventId=@rEventId AND OrgId=@rOrgId and AlertModeId = 4 and IsAutoSend=1),'')
			--For Optimization

			if object_id('tempdb..#tShift') is not null
			BEGIN
				DROP TABLE #tShift
			END
			CREATE TABLE #tShift(
					ShiftCode int NOT NULL
				)

			insert #tShift
			Select 
				ShiftCode
			FROM sBiometric.tShiftMasterCloud
			where  ((OrgGroupId = @rOrgGroupId) OR (@rOrgGroupId=0))  
			--AND IsOutTimeAlertTime=1
			--AND CAST(DATEADD(MINUTE,AlterGraceTime,StartTime) AS Time)<cast([sCommon].[fGetDate]() as Time)
			--AND CAST(DATEADD(MINUTE,AlterGraceTime,StartTime) AS Time)>=cast(DATEADD(MINUTE,-@rIntervalTime,[sCommon].[fGetDate]()) as Time)
			AND CAST(DATEADD(MINUTE,AlterGraceTime,StartTime) AS Time)<cast(@rToDateTime as Time)
			AND CAST(DATEADD(MINUTE,AlterGraceTime,StartTime) AS Time)>=cast(@rFromDateTime as Time)

			--select * from #tShift
			declare @lcount int=(SELECT COUNT(ShiftCode) FROM #tShift)

			if object_id('tempdb..#tTable') is not null
			BEGIN
				DROP TABLE #tTable
			END
			CREATE TABLE #tTable(
						SourceId bigint NOT NULL,
						In_Out_Time [datetime] NOT NULL,
						SourceTypeId int NOT NULL,
						CreatedDateTime [datetime] NOT NULL,--For Optimization
						AutoId bigint not null--For Optimization
					)

			if(@lcount>0)
			BEGIN
				insert into #tTable
				select SourceId,MIN(In_Out_Time),SourceTypeId,
				min(CDT.CreatedDateTime),min(CDT.Autoid) --For Optimization
				from [sBiometric].[tCloudTransactionData] CDT with (nolock) 
				inner join #tShift tempShift ON tempShift.ShiftCode=CDT.ShiftCode 
				WHERE Attn_Dt=CONVERT(date,[sCommon].[fGetDate]())  AND SourceTypeId=2003 
				-- For Optimization
				AND CDT.Autoid>@lCloudTransactionDataId
				AND CDT.SourceId not in (select ReceiverSourceId From sBiometric.tTempBiometricAlertData where  OrgID =@rOrgId and AlertId=136 and SourceTypeId=2003 and cast(CreatedDateTime as date)=CONVERT(date,[sCommon].[fGetDate]()))
				-- For Optimization
				Group by SourceId,SourceTypeId
			END

			-- For Optimization
			DECLARE @AlertUniqueId uniqueidentifier = NEWID();
			
			Insert Into sBiometric.tTempBiometricAlertData
			SELECT 
				SC.ParentContactNo AS MobileNo,	
				SC.ParentEmail AS EmailId,
				'' as MsgText,
				@rSubject AS Subject,
				2003 AS ReceiverSourceTypeId,
				SC.StudentId AS ReceiverSourceId,
				SC.Name AS StudentName,
				SC.Code AS Code,
				ISNULL(SC.WhatsAppContactNo,'') AS WhatsAppContactNo,
				2003 AS SourceTypeId,
				SC.StudentId AS SourceId,
				SC.OrgId,
				OM.OrgGroupId,
				ISNULL(Convert(varchar,temp.In_Out_Time,108),'') as Time,
				OM.DisplayTitle AS OrganizationTitle,
				temp.AutoId,
				@rFromDateTime,
				@rToDateTime,
				sCommon.fGetDate(),
				@rEventId,
				@AlertUniqueId
			FROM 
				sStudent.vStudentCommunication SC 
				Inner Join  [sStudent].[tStudentMaster] SM on SM.Id=SC.StudentId
				INNER JOIN sSetup.tOrganizationMaster OM ON SC.OrgID = OM.Id
				INNER JOIN #tShift tempshift ON tempshift.ShiftCode=SM.ShiftId
				LEFT JOIN #tTable temp ON  temp.SourceId=SC.StudentId 
				where 
					SC.OrgID =@rOrgId
					AND SC.IsActiveBatch=1
					AND SC.StatusId = 1
					AND temp.In_Out_Time is null
					AND ([sAttendance].[fWeekHOffGet](YEAR([sCommon].[fGetDate]()) ,MONTH([sCommon].[fGetDate]()) ,DAY([sCommon].[fGetDate]()),SC.BatchId,SC.ClassId,SC.DivisionId, '',@rOrgId)<>'W')
					AND ([sAttendance].[fWeekHOffGet](YEAR([sCommon].[fGetDate]()) ,MONTH([sCommon].[fGetDate]()) ,DAY([sCommon].[fGetDate]()),SC.BatchId,SC.ClassId,SC.DivisionId, '',@rOrgId)<>'H')
		
				select 
					MobileNo,	
					EmailId,
					replace (
					replace(@lSMSTemplete,'[StudentName]',StudentName),
					'[AbsentDate]',ISNULL(Convert(varchar,[sCommon].[fGetDate](),103),''))
					 AS SMSText,
					replace (
					replace(@lMailTemplete,'[StudentName]',StudentName),
					'[AbsentDate]',ISNULL(Convert(varchar,[sCommon].[fGetDate](),103),''))
					 AS MailText,
					replace (
					replace(@lNotificationTemplete,'[StudentName]',StudentName),
					'[AbsentDate]',ISNULL(Convert(varchar,[sCommon].[fGetDate](),103),''))
					 AS NotificationText,
					replace (
					replace(@lWhatsappTemplete,'[StudentName]',StudentName),					
					'[AbsentDate]',ISNULL(Convert(varchar,[sCommon].[fGetDate](),103),''))
					 AS WhatsappText,
					Subject,
					ReceiverSourceTypeId,
					ReceiverSourceId,
					StudentName,
					Code,
					WhatsAppContactNo,
					SourceTypeId,
					SourceId,
					OrgId,
					OrgGroupId,
					OrganizationTitle
				FROM  
					sBiometric.tTempBiometricAlertData
				where 
					AlertUniqueId=@AlertUniqueId
			--For Optimization

			DROP TABLE #tTable
			DROP TABLE #tShift
		COMMIT TRANSACTION
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH
END
GO
PRINT N'Altering Procedure [sAlert].[pStudentBiometricFirstInTimeGet]...';


GO

ALTER PROCEDURE [sAlert].[pStudentBiometricFirstInTimeGet]
	@rTemplate nvarchar(max)='',
	@rSubject nvarchar(100)='',
	@rOrgId int,
	@rIntervalTime int=0,
	@rToDateTime dateTime,
	@rFromDateTime DateTime,
	@rEventId int=129

	

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY	
		BEGIN TRANSACTION 
			declare @lDateTimeNow datetime=[sCommon].[fGetDate]()
			declare @lLastStudentFirstInAlertSendTime datetime

			declare @lCloudTransactionDataId bigint=0
			set @lCloudTransactionDataId= isnull((select Max(isnull(CloudTransactionDataId,0)) From sBiometric.tTempBiometricAlertData where  OrgID =@rOrgId and AlertId=@rEventId and SourceTypeId=2003),0)
			declare @lSMSTemplete nvarchar(max)='',@lMailTemplete nvarchar(max)='', @lWhatsappTemplete nvarchar(max)='',@lNotificationTemplete nvarchar(max)=''
			set @lMailTemplete=isnull((select isnull(Template,'') from sAlert.tEventTemplate where EventId=@rEventId AND OrgId=@rOrgId and AlertModeId = 1 and IsAutoSend=1),'')
			set @lSMSTemplete =isnull((select isnull(Template,'') from sAlert.tEventTemplate where EventId=@rEventId AND OrgId=@rOrgId and AlertModeId = 2 and IsAutoSend=1),'')
			set @lNotificationTemplete =isnull((select isnull(Template,'') from sAlert.tEventTemplate where EventId=@rEventId AND OrgId=@rOrgId and AlertModeId = 3 and IsAutoSend=1),'')
			set @lWhatsappTemplete =isnull((select isnull(Template,'') from sAlert.tEventTemplate where EventId=@rEventId AND OrgId=@rOrgId and AlertModeId = 4 and IsAutoSend=1),'')
			set @rSubject=isnull((select isnull(MailSubject,'') from sAlert.tEventTemplate where EventId=@rEventId AND OrgId=@rOrgId and AlertModeId = 1 ),'')
		
			if object_id('tempdb..#tTable') is not null
			BEGIN
				DROP TABLE #tTable
			END
			CREATE TABLE #tTable(
				SourceId bigint NOT NULL,
				In_Out_Time [datetime] NOT NULL,
				SourceTypeId int NOT NULL,
				CreatedDateTime [datetime] NOT NULL,
				AutoId bigint not null,

			)
			insert into #tTable
			select CDT.SourceId,min(CDT.In_Out_Time),CDT.SourceTypeId,min(CDT.CreatedDateTime),min(CDT.Autoid)
			from [sBiometric].[tCloudTransactionData] CDT with (nolock) 
			inner join sBiometric.tShiftMasterCloud SMC ON SMC.ShiftCode=CDT.ShiftCode
			WHERE CDT.Attn_Dt=CONVERT(date,@lDateTimeNow)  AND CDT.SourceTypeId=2003
				AND (isnull(SMC.IsStopInTimeAlertTime,0)=0 OR (SMC.IsStopInTimeAlertTime=1 
				--AND CAST(SMC.StopInTimeAlertTime as Time)>=CAST(@rFromDateTime AS Time)
				AND  CAST(SMC.StopInTimeAlertTime as Time)>=CAST(CDT.In_Out_Time AS Time))
				
				)
				AND CDT.Autoid>@lCloudTransactionDataId
				AND CDT.SourceId not in (select ReceiverSourceId From sBiometric.tTempBiometricAlertData where  OrgID =@rOrgId and AlertId=@rEventId and SourceTypeId=2003 AND cast(CreatedDateTime as date)=CONVERT(date,@lDateTimeNow))
			 Group by CDT.SourceId,CDT.SourceTypeId
	
			--select * from #tTable 
			print @lCloudTransactionDataId
			DECLARE @AlertUniqueId uniqueidentifier = NEWID();
			
			Insert Into sBiometric.tTempBiometricAlertData
			SELECT 
				SC.ParentContactNo AS MobileNo,	
				SC.ParentEmail AS EmailId,
				'' as MsgText,
				@rSubject AS Subject,
				2003 AS ReceiverSourceTypeId,
				SC.StudentId AS ReceiverSourceId,
				SC.Name AS StudentName,
				SC.Code AS Code,
				ISNULL(SC.WhatsAppContactNo,'') AS WhatsAppContactNo,
				2003 AS SourceTypeId,
				SC.StudentId AS SourceId,
				SC.OrgId,
				OM.OrgGroupId,
				ISNULL(Convert(varchar,temp.In_Out_Time,108),'') as Time,
				OM.DisplayTitle AS OrganizationTitle,
				temp.AutoId,
				@rFromDateTime,
				@rToDateTime,
				sCommon.fGetDate(),
				@rEventId,
				@AlertUniqueId
			FROM 
				#tTable temp
				Inner join sStudent.vStudentCommunication SC ON temp.SourceId=SC.StudentId AND SC.IsActiveBatch=1
				INNER JOIN sSetup.tOrganizationMaster OM ON SC.OrgID = OM.Id
			WHERE
				--temp.CreatedDateTime < @rToDateTime
				--AND temp.CreatedDateTime >= @rFromDateTime
				--AND 
				SC.OrgID =@rOrgId
				AND SC.StatusId = 1

			SELECT 
				MobileNo AS MobileNo,	
				EmailId AS EmailId,
				replace (
				replace (
				replace (
				replace(@lSMSTemplete,'[StudentName]',StudentName),
				'[TimeStamp]',ISNULL(Convert(varchar,Time,108),'')),
				'[PresentTime]',ISNULL(Convert(varchar,Time,108),'')),
				'[PresentDate]',ISNULL(Convert(varchar,[sCommon].[fGetDate](),103),''))
				 AS SMSText,
				 replace (
				replace (
				replace (
				replace(@lMailTemplete,'[StudentName]',StudentName),
				'[TimeStamp]',ISNULL(Convert(varchar,Time,108),'')),
				'[PresentTime]',ISNULL(Convert(varchar,Time,108),'')),
				'[PresentDate]',ISNULL(Convert(varchar,[sCommon].[fGetDate](),103),''))
				 AS MailText,
				  replace (
				replace (
				replace (
				replace(@lNotificationTemplete,'[StudentName]',StudentName),
				'[TimeStamp]',ISNULL(Convert(varchar,Time,108),'')),
				'[PresentTime]',ISNULL(Convert(varchar,Time,108),'')),
				'[PresentDate]',ISNULL(Convert(varchar,[sCommon].[fGetDate](),103),''))
				 AS NotificationText,
				 replace (
				replace (
				replace (
				replace(@lWhatsappTemplete,'[StudentName]',StudentName),
				'[TimeStamp]',ISNULL(Convert(varchar,Time,108),'')),
				'[PresentTime]',ISNULL(Convert(varchar,Time,108),'')),
				'[PresentDate]',ISNULL(Convert(varchar,[sCommon].[fGetDate](),103),''))
				 AS WhatsappText,
				Subject AS Subject,
				2003 AS ReceiverSourceTypeId,
				ReceiverSourceId AS ReceiverSourceId,
				StudentName AS StudentName,
				Code AS Code,
				WhatsAppContactNo AS WhatsAppContactNo,
				2003 AS SourceTypeId,
				SourceId AS SourceId,
				OrgId,
				OrgGroupId,
				 Time,
				 OrganizationTitle
			FROM 
				sBiometric.tTempBiometricAlertData
			WHERE
			   AlertUniqueId=@AlertUniqueId


			DROP TABLE #tTable
		COMMIT TRANSACTION
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH

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


GO

ALTER PROCEDURE [sAlert].[pStudentBiometricLastOutTimeGet]
	@rTemplate nvarchar(max)='',
	@rSubject nvarchar(100)='',
	@rOrgId int,
	@rOrgGroupId int,
	@rIntervalTime int=0,
	@rToDateTime dateTime,
	@rFromDateTime DateTime
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY	
		BEGIN TRANSACTION 
			declare @lCloudTransactionDataId bigint=0
			set @lCloudTransactionDataId= isnull((select Max(isnull(CloudTransactionDataId,0)) From sBiometric.tTempBiometricAlertData where  OrgID =@rOrgId and AlertId=130 and SourceTypeId=2003),0)
			declare @lSMSTemplete nvarchar(max)='',@lMailTemplete nvarchar(max)='', @lWhatsappTemplete nvarchar(max)='',@lNotificationTemplete nvarchar(max)=''
			set @lMailTemplete=isnull((select isnull(Template,'') from sAlert.tEventTemplate where EventId=130 AND OrgId=@rOrgId and AlertModeId = 1 and IsAutoSend=1),'')
			set @lSMSTemplete =isnull((select isnull(Template,'') from sAlert.tEventTemplate where EventId=130 AND OrgId=@rOrgId and AlertModeId = 2 and IsAutoSend=1),'')
			set @lNotificationTemplete =isnull((select isnull(Template,'') from sAlert.tEventTemplate where EventId=130 AND OrgId=@rOrgId and AlertModeId = 3 and IsAutoSend=1),'')
			set @lWhatsappTemplete =isnull((select isnull(Template,'') from sAlert.tEventTemplate where EventId=130 AND OrgId=@rOrgId and AlertModeId = 4 and IsAutoSend=1),'')
			set @rSubject=isnull((select isnull(MailSubject,'') from sAlert.tEventTemplate where EventId=130 AND OrgId=@rOrgId and AlertModeId = 1),'')
			

			if object_id('tempdb..#tTable') is not null
			BEGIN
				DROP TABLE #tTable
			END
			CREATE TABLE #tTable(
				SourceId bigint NOT NULL,
				In_Out_Time [datetime] NOT NULL,
				SourceTypeId int NOT NULL,
				OutTimeAlertTime time NOT NULL,
				CreatedDateTime [datetime] NOT NULL,
				LastOutAlertBasedOnId int NOT NULL,
				ShiftCode int NOT NULL,
				AutoId bigint not null,
			)
			
				insert into #tTable
				select SourceId,MAX(In_Out_Time),SourceTypeId,SMC.OutTimeAlertTime,Max(CreatedDateTime),SMC.LastOutAlertBasedOnId,CDT.ShiftCode,max(CDT.Autoid)
				from [sBiometric].[tCloudTransactionData] CDT with (nolock)  
				--inner join #tShift tempShift ON tempShift.ShiftCode=CDT.ShiftCode
				 INNER JOIN sBiometric.tShiftMasterCloud SMC on SMC.ShiftCode=CDT.ShiftCode
				where  Attn_Dt=CONVERT(date,[sCommon].[fGetDate]())
					AND	((SMC.OrgGroupId = @rOrgGroupId) OR (@rOrgGroupId=0))  
					AND SMC.IsOutTimeAlertTime=1
					AND CDT.SourceTypeId=2003 
					AND (
							(
								(LastOutAlertBasedOnId=1 OR (LastOutAlertBasedOnId=2  and CAST(DATEADD(minute,-(GraceBefore),EndTime) AS Time)<=cast(CDT.In_Out_Time as Time)
								AND CAST(OutTimeAlertTime AS Time) > CAST(CDT.In_Out_Time AS Time)))
								 AND CAST(OutTimeAlertTime AS Time)<cast(@rToDateTime as Time) 
								AND CAST(OutTimeAlertTime AS Time) > CAST(@rFromDateTime AS Time) 
							)
							OR
							(
							LastOutAlertBasedOnId=3 AND CAST(DATEADD(minute,-(GraceBefore),EndTime) AS Time)<=cast(CDT.In_Out_Time as Time)
							AND CAST(OutTimeAlertTime AS Time) > CAST(CDT.In_Out_Time AS Time)
							--AND CDT.Autoid>@lCloudTransactionDataId 
							AND CDT.SourceId not in (select ReceiverSourceId From sBiometric.tTempBiometricAlertData where  OrgID =@rOrgId and AlertId=130 and SourceTypeId=2003 and cast(CreatedDateTime as date)=CONVERT(date,[sCommon].[fGetDate]()))
							)
						)
				Group by SourceId,SourceTypeId,SMC.OutTimeAlertTime,SMC.LastOutAlertBasedOnId,CDT.ShiftCode
				--select * from #tTable

			DECLARE @AlertUniqueId uniqueidentifier = NEWID();
			Insert Into sBiometric.tTempBiometricAlertData
			SELECT 
				SC.ParentContactNo AS MobileNo,	
				SC.ParentEmail AS EmailId,
				'' as MsgText,
				@rSubject AS Subject,
				2003 AS ReceiverSourceTypeId,
				SC.StudentId AS ReceiverSourceId,
				SC.Name AS StudentName,
				SC.Code AS Code,
				ISNULL(SC.WhatsAppContactNo,'') AS WhatsAppContactNo,
				2003 AS SourceTypeId,
				SC.StudentId AS SourceId,
				SC.OrgId,
				OM.OrgGroupId,
				ISNULL(Convert(varchar,temp.In_Out_Time,108),'') as Time,
				OM.DisplayTitle AS OrganizationTitle,
				temp.AutoId,
				@rFromDateTime,
				@rToDateTime,
				sCommon.fGetDate(),
				130,
				@AlertUniqueId
			FROM 
				#tTable temp
				Inner join sStudent.vStudentCommunication SC ON temp.SourceId=SC.StudentId AND SC.IsActiveBatch=1
				INNER JOIN sSetup.tOrganizationMaster OM ON SC.OrgID = OM.Id
			WHERE
				 
				SC.OrgID =@rOrgId
				AND SC.StatusId = 1



			SELECT 
				MobileNo AS MobileNo,	
				EmailId AS EmailId,
				replace (
				replace (
				replace (
				replace(@lSMSTemplete,'[StudentName]',StudentName),
				'[TimeStamp]',ISNULL(Convert(varchar,Time,108),'')),
				'[PresentTime]',ISNULL(Convert(varchar,Time,108),'')),
				'[PresentDate]',ISNULL(Convert(varchar,[sCommon].[fGetDate](),103),''))
				 AS SMSText,
				 replace (
				replace (
				replace (
				replace(@lMailTemplete,'[StudentName]',StudentName),
				'[TimeStamp]',ISNULL(Convert(varchar,Time,108),'')),
				'[PresentTime]',ISNULL(Convert(varchar,Time,108),'')),
				'[PresentDate]',ISNULL(Convert(varchar,[sCommon].[fGetDate](),103),''))
				 AS MailText,
				  replace (
				replace (
				replace (
				replace(@lNotificationTemplete,'[StudentName]',StudentName),
				'[TimeStamp]',ISNULL(Convert(varchar,Time,108),'')),
				'[PresentTime]',ISNULL(Convert(varchar,Time,108),'')),
				'[PresentDate]',ISNULL(Convert(varchar,[sCommon].[fGetDate](),103),''))
				 AS NotificationText,
				 replace (
				replace (
				replace (
				replace(@lWhatsappTemplete,'[StudentName]',StudentName),
				'[TimeStamp]',ISNULL(Convert(varchar,Time,108),'')),
				'[PresentTime]',ISNULL(Convert(varchar,Time,108),'')),
				'[PresentDate]',ISNULL(Convert(varchar,[sCommon].[fGetDate](),103),''))
				 AS WhatsappText,
				Subject AS Subject,
				2003 AS ReceiverSourceTypeId,
				ReceiverSourceId AS ReceiverSourceId,
				StudentName AS StudentName,
				Code AS Code,
				WhatsAppContactNo AS WhatsAppContactNo,
				2003 AS SourceTypeId,
				SourceId AS SourceId,
				OrgId,
				OrgGroupId,
				 Time,
				 OrganizationTitle
			FROM 
				sBiometric.tTempBiometricAlertData
			WHERE
			   AlertUniqueId=@AlertUniqueId

			DROP TABLE #tTable
		COMMIT TRANSACTION
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH
END
GO
PRINT N'Altering Procedure [sAlert].[pStudentBiometricLateTimeGet]...';


GO

ALTER PROCEDURE [sAlert].[pStudentBiometricLateTimeGet]
	 	 
	 	 @rOrgId int,
		@rTemplate nvarchar(max)='',
		@rSubject nvarchar(100)=''
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	DECLARE @lDate date = ''
	SET @lDate = sCommon.fGetDate()

	DECLARE @lDay as nvarchar(3)
	Select @lDay  = RIGHT('00' + CAST(DATEPART(dd,@lDate) AS varchar(2)), 2)

	DECLARE @lColumnName varchar(10) = '',@lShiftColumntName varchar(10) = ''
	SET @lColumnName = 'MT.D' + CAST(@lDay AS VARCHAR) + '_IN'
	SET @lShiftColumntName = 'MT.D' + CAST(@lDay AS VARCHAR) + '_S'

	DECLARE @lGetConfigTime nvarchar(20) = ''
	SELECT @lGetConfigTime =  ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 399 AND SourceId = @rOrgId

	declare @lSMSTemplete nvarchar(max)='',@lMailTemplete nvarchar(max)='', @lWhatsappTemplete nvarchar(max)='',@lNotificationTemplete nvarchar(max)=''
	set @lMailTemplete=isnull((select isnull(Template,'') from sAlert.tEventTemplate where EventId=137 AND OrgId=@rOrgId and AlertModeId = 1 and IsAutoSend=1),'')
	set @lSMSTemplete =isnull((select isnull(Template,'') from sAlert.tEventTemplate where EventId=137 AND OrgId=@rOrgId and AlertModeId = 2 and IsAutoSend=1),'')
	set @lNotificationTemplete =isnull((select isnull(Template,'') from sAlert.tEventTemplate where EventId=137 AND OrgId=@rOrgId and AlertModeId = 3 and IsAutoSend=1),'')
	set @lWhatsappTemplete =isnull((select isnull(Template,'') from sAlert.tEventTemplate where EventId=137 AND OrgId=@rOrgId and AlertModeId = 4 and IsAutoSend=1),'')

	IF(@lGetConfigTime <> '' AND LEN(@lGetConfigTime) > 0)
	BEGIN
	DECLARE @Query NVARCHAR(MAX) = ''
	SET @Query ='SELECT
					SC.ParentContactNo AS MobileNo,	
					SC.ParentEmail AS EmailId,
					replace (
					replace (
					replace('''+CONVERT(nvarchar(MAX),@rTemplate)+''',''[StudentName]'',sStudent.fStudentNameGet(SM.FirstName, SM.MiddleName, SM.LastName,OM.StudentNameFormatId)),
					''[LateTime]'','+@lColumnName+'),
					''[LateDate]'',ISNULL(Convert(varchar,[sCommon].[fGetDate](),103),''''))
					 AS MsgText,
					 replace (
					replace (
					replace('''+CONVERT(nvarchar(MAX),@lSMSTemplete)+''',''[StudentName]'',sStudent.fStudentNameGet(SM.FirstName, SM.MiddleName, SM.LastName,OM.StudentNameFormatId)),
					''[LateTime]'','+@lColumnName+'),
					''[LateDate]'',ISNULL(Convert(varchar,[sCommon].[fGetDate](),103),''''))
					 AS SMSText,
					 replace (
					replace (
					replace('''+CONVERT(nvarchar(MAX),@lMailTemplete)+''',''[StudentName]'',sStudent.fStudentNameGet(SM.FirstName, SM.MiddleName, SM.LastName,OM.StudentNameFormatId)),
					''[LateTime]'','+@lColumnName+'),
					''[LateDate]'',ISNULL(Convert(varchar,[sCommon].[fGetDate](),103),''''))
					 AS MailText,
					 replace (
					replace (
					replace('''+CONVERT(nvarchar(MAX),@lNotificationTemplete)+''',''[StudentName]'',sStudent.fStudentNameGet(SM.FirstName, SM.MiddleName, SM.LastName,OM.StudentNameFormatId)),
					''[LateTime]'','+@lColumnName+'),
					''[LateDate]'',ISNULL(Convert(varchar,[sCommon].[fGetDate](),103),''''))
					 AS NotificationText,
					 replace (
					replace (
					replace('''+CONVERT(nvarchar(MAX),@lWhatsappTemplete)+''',''[StudentName]'',sStudent.fStudentNameGet(SM.FirstName, SM.MiddleName, SM.LastName,OM.StudentNameFormatId)),
					''[LateTime]'','+@lColumnName+'),
					''[LateDate]'',ISNULL(Convert(varchar,[sCommon].[fGetDate](),103),''''))
					 AS WhatsappText,
					'''+CONVERT(nvarchar(20),@rSubject)+''' AS Subject,
					2003 AS ReceiverSourceTypeId,
					SC.StudentId AS ReceiverSourceId,
					sStudent.fStudentNameGet(SM.FirstName, SM.MiddleName, SM.LastName,OM.StudentNameFormatId) AS StudentName,
					ISNULL(SC.WhatsAppContactNo,'''') AS WhatsAppContactNo,
					2003 AS SourceTypeId,
					SC.StudentId AS SourceId,
					SM.OrgId,
					OM.OrgGroupId,
					SM.Id AS StudentId,
					SM.Code,
					sStudent.fStudentNameGet(SM.FirstName, SM.MiddleName, SM.LastName,OM.StudentNameFormatId) AS  StudentName,
					 '+@lColumnName+' AS Time,
					OM.DisplayTitle AS OrganizationTitle	
		FROM 
				sStudent.tStudentMaster SM
				Inner join sStudent.tStudentCommunication SC ON SM.Id=SC.StudentId
				INNER JOIN sSetup.tOrganizationMaster OM ON SM.OrgID = OM.Id
				INNER JOIN sBiometric.tMonthTrans MT ON MT.EmployeeId = SM.Id AND MT.SourceTypeId = 2003
				INNER Join sBiometric.tShiftMasterCloud SMC ON SMC.ShiftName='+@lShiftColumntName+'
		WHERE
				SM.OrgId = '+CONVERT(nvarchar(20),@rOrgId)+'
				AND MONTH(MT.Attn_dt) = MONTH('''+CONVERT(nvarchar(20),@lDate)+''')
				--AND '+@lColumnName+' > '''+@lGetConfigTime+'''
				AND '+@lColumnName+' > DATEADD(minute, SMC.GraceAfter,SMC.StartTime)
				AND SM.StatusId = 1'
				
		--print (@Query)
		execute (@Query)			
	END

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


GO
ALTER PROCEDURE [sAssessment].[pRptCSExamMarkEntryGet]
	  @rClassId bigint,
	  @rDivisionID Bigint,
	  @rExamId int,
	  @rOrgId int,
	  @rBatchId int,
	  --@rCCECSId int,
	  @rFilter int,
	  @rBuilder nvarchar(max)='',
	  @rCCECAGroupId int=0,
	  @rCCECSId int=0
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	
BEGIN 	
SELECT
    @rBuilder AS Builder,
    SA.AcademicId,
    SA.Code,
    SA.Name,
    AM.Title,
    SA.RollNo AS RollNo ,
    CASE WHEN @rFilter=1 THEN ISNULL(AIS.ObtianMark,0) 
    ELSE  ISNULL(AIS.ConvertedMark,0) END AS TotalMark,
	(CASE EM.IsDisplayPhoto WHEN 1 THEN
	SI.StudentPhoto
	ELSE NULL END)AS StudentPhoto,
	EM.IsDisplayPhoto,
	EM.IsOnPrePrinted,
	ISNULL(EM.IsDisplayImageHeader,0) AS IsImageHeader,
	(CASE EM.IsDisplayImageHeader WHEN 1 THEN 
	OI.MarksheetHeaderA4 
	ELSE 
	NULL END) AS MarksheetHeaderA4,
	CCGM.Id AS CCECSGroupId,
	CCGM.Title AS CCECSGroupTitle,
    CA.OrderIndex AS CCECSGroupOrderIndex
    
	FROM sStudent.vStudentAcademic SA
	INNER JOIN sAssessment.tCCECSClass CA ON CA.ClassId = SA.ClassId AND SA.StatusId = 1
	INNER JOIN sAssessment.tCCECSMaster AM ON CA.CCECSGroupId=AM.CCECAGroupId
	 INNER JOIN sAssessment.tCCECSForClass CL ON CL.CCECSID= AM.Id 
	 AND CL.ClassID=@rClassId
	LEFT JOIN sAssessment.tCCECSExamScore AIS ON AIS.AcademicId =SA.AcademicId AND AIS.CCECSId= AM.Id 
	AND AIS.ExamId= @rExamId 
	AND (AIS.CCECSId =@rCCECSId OR @rCCECSId = 0) 
	INNER JOIN sAssessment.tExamMaster EM ON EM.Id = AIS.ExamId
	LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId=SA.StudentId
	INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=SA.OrgId
	LEFT JOIN sSetup.tOrgImages OI ON OI.Orgid = OM.Id
	INNER JOIN sAssessment.tCCECSGroupMaster CCGM ON CCGM.Id = AM.CCECAGroupId AND CCGM.OrgId = SA.OrgId --New Join Mantis : 0027514	
	WHERE 
	SA.ClassId=@rClassId
	And SA.DivisionId = @rDivisionID	
	And SA.BatchId = @rBatchId
	And (AM.CCECAGroupId= @rCCECAGroupId  OR @rCCECAGroupId  = 0 )
	Order by AM.OrderIndex
	END
GO
PRINT N'Altering Procedure [sAssessment].[pRptCSExamScoreGet]...';


GO
ALTER PROCEDURE [sAssessment].[pRptCSExamScoreGet]
	  
	   @rOrgId int
	  ,@rExamId int,
	  @rClassId int,
	  @rDivisionId int,
	  @rBatchId int,
	  @rCCECAGroupId int=0,
	  @rCCEMasterId int=0,
	  @rAcademicId bigint=0,
	  @rBuilder1 nvarchar(max)=''
	  
	  
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 	
BEGIN TRY
			SELECT 		
				--ISNULL(CGM.Title,'') AS CSGroup,
				--ISNULL(CM.Title,'') AS CS,				
				--ISNULL(CC.Grade,'')  AS Grade,
				--ISNULL(CC.GradeIndicator,'') AS Indicator,
				--ISNULL(CC.DescriptiveIndicator,'')  AS DescriptiveIndicator,			
				--ISNULL(SA.AcademicId,0) AS AcademicId,
				--ISNULL(CC.IndicatorIds,'') AS IndicatorIds,
				--CGM.GradeSetId,
				--CM.Id as CMID
				
				 @rBuilder1 AS Builder1,
				 SA.AcademicId,
				 SA.RollNo,
				 SA.Number,
				 SA.Name,
				  
				 ISNULL(AIS.Grade,'') AS Term1Indicator,
				 CCEM.Title AS GroupTitle,
				 AM.Title AS MasterTitle,
				ISNULL(AIS.ConvertedMark,0) AS ConvertedMark,
				ISNULL(AIS.GradeIndicator,'') AS Indicator,
				ISNULL(AIS.DescriptiveIndicator,'')  AS DescriptiveIndicator	,
				CM.Id AS ClassId,
				CM.Title AS ClassTitle,
				DM.Id AS DivisionId,
				DM.Title AS DivisionTitle,
				SA.Code AS Code,
				(SELECT DisplayTitle FROM sAssessment.tExamMaster WHERE Id = @rExamId) AS ExamTitle	,
				(CASE EM.IsDisplayPhoto WHEN 1 THEN
		        SI.StudentPhoto
			    ELSE NULL END)AS StudentPhoto,
				EM.IsDisplayPhoto,
				EM.IsOnPrePrinted,
				ISNULL(EM.IsDisplayImageHeader,0) AS IsImageHeader,
				(CASE EM.IsDisplayImageHeader WHEN 1 THEN 
				OI.MarksheetHeaderA4 
				ELSE 
				NULL END) AS MarksheetHeaderA4,
				ISNULL(AIS.ObtianMark,0) AS ObtianMark
								 
			FROM sStudent.vStudentAcademic SA
				INNER JOIN sAssessment.tCCECSClass CA ON CA.ClassId = SA.ClassId AND SA.StatusId = 1
				INNER JOIN sAssessment.tCCECSMaster AM ON CA.CCECSGroupId=AM.CCECAGroupId
				INNER JOIN sAssessment.tCCECSGroupMaster CCEM ON CCEM.Id=AM.CCECAGroupId
				INNER JOIN sSetup.tClassMaster CM ON CM.Id = SA.ClassId AND SA.OrgId = CM.OrgId
				INNER JOIN sSetup.tDivisionmaster DM ON DM.Id = SA.DivisionId AND SA.OrgId = DM.OrgId
				LEFT JOIN sAssessment.tCCECSExamScore AIS ON AIS.AcademicId =SA.AcademicId AND CCECSId= AM.Id And AIS.ExamId=@rExamId
				INNER JOIN sAssessment.tExamMaster EM ON EM.Id = AIS.ExamId
				LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId=SA.StudentId
				INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=SA.OrgId
				LEFT JOIN sSetup.tOrgImages OI ON OI.Orgid = OM.Id
			WHERE
				 SA.ClassId=@rClassId 
				And SA.DivisionId =@rDivisionID	
				And SA.BatchId =@rBatchId
				AND AIS.ExamId=@rExamId
				and ((AM.CCECAGroupId=@rCCECAGroupId) OR (@rCCECAGroupId=0))
				AND((AM.Id=@rCCEMasterId) OR (@rCCEMasterId=0))	
				and AM.OrgId=@rOrgId
				and ((SA.AcademicId=@rAcademicId) OR (@rAcademicId=0))
						
			--FROM   
			--	sAssessment.tCCECSMaster CM 
			--	INNER JOIN sAssessment.tCCECSGroupMaster CGM ON CGM.Id=CM.CCECAGroupId AND CM.OrgId=@rOrgId
			--	INNER JOIN sAssessment.tCCECSClass CL ON CL.CCECSGroupId = CGM.Id				
			--	INNER JOIN sStudent.vStudentAcademic SA ON   SA.ClassId = CL.ClassId 
			--	LEFT JOIN   sAssessment.tCCECSExamScore CC  ON CC.CCECSID=CM.ID  
			--	AND CC.AcademicId = SA.AcademicId AND ExamId=@rExamId	AND CC.AcademicId = @rAcademicId	
			--	WHERE ((SA.AcademicId = @rAcademicId) OR (@rAcademicId=0))
			--		and SA.ClassId=@rClassId and SA.DivisionId=@rDivisionId
		
			 ORDER BY SA.RollNo
			
END TRY
BEGIN CATCH
	SELECT -1 AS RESULT
END CATCH
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
 
	SELECT 
		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
	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].[pRptSubjectActivityExamMarkGet]...';


GO


ALTER PROCEDURE [sAssessment].[pRptSubjectActivityExamMarkGet]
	  
	   @rOrgId int
	  ,@rExamId int,
	  @rClass int,
	  @rDivisionId int,
	  @rBatchId int,
	  @rActivityId int,
	  @rSubjectSubActivityId int,
	  @rBuilder1 nvarchar(max)
	  
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 	

	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
 
			SELECT 		 
				 @rBuilder1 AS Builder1,
				 SA.AcademicId,
				 SA.RollNo,
				 SA.Number,
				 SA.Name,
				  
				 ISNULL(AIS.Marks,0) AS Marks,
				 
				 SAM.Title AS SubjectActivityTitle,
				 SSA.Title AS SubjectSubActivityTitle,
				 SAM.Id AS ActivityId,
				 SSA.Id AS SubjectSubActivityId,
				 SAM.OrderIndex AS ActivityOrderIndex,
				 SSA.OrderIndex AS SubjectSubActivityOrderIndex,
				 SM.Title AS SubjectName,
				 SAM.ClassSubjectId,
				 ISNULL(AIS.Grade,'') AS Grade,
				 ISNULL(AIS.GradeIndicator,'') AS GradeIndicator,
				 ISNULL(AIS.DescriptiveIndicator,'') AS DescriptiveIndicator,
				 (SELECT EM.FirstName + ' ' + EM.LastName  From sHrm.tEmployeeMaster EM 
				  INNER JOIN sSetup.tDivisionMaster DM ON EM.Id = DM.InchargeEmployeeId Where DM.Id = @rDivisionId) AS ClassTeacher,
				  ISNULL(SR.TotalDays,0)AS TotalDays,
				  ISNULL(SR.PresentDays,0)AS PresentDays,
				  CONVERT(bit,@lDecimalConfig) AS IsDecimal,
				  ISNULL(SR.GeneralRemark,'') AS GeneralRemark,
				  ISNULL(SR.Achievements,'') AS Achievements,
				  ISNULL(SR.ResultRemark1,'') AS ResultRemark1,
				  ISNULL(SR.ResultRemark2,'') AS ResultRemark2,
				  ISNULL(SR.ResultRemark3,'') AS ResultRemark3
					 
			FROM 
			  sAssessment.tCCESubjectActivityMaster SAM 	
			INNER JOIN sAssessment.tCCESubjectSubActivityMaster SSA ON SAM.Id=SSA.SubjectActivityId  
			INNER JOIN sAssessment.vCCEExamClassSubject CS ON CS.ClassSubjectId=SAM.ClassSubjectId		
			INNER JOIN sSetup.tClassMaster CMM ON CMM.Id=CS.ClassId 
			INNER JOIN sStudent.vStudentAcademic SA ON   SA.ClassId = CMM.Id 
			LEFT JOIN sAssessment.tCCESubjectSubActivityExamScore AIS ON AIS.AcademicId =SA.AcademicId AND AIS.SubjectSubActivityId= SSA.Id And AIS.ExamId=@rExamId
			INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=CS.SubjectId
			LEFT JOIN sAssessment.tStudentRemark SR ON SA.AcademicId = SR.AcademicId AND SR.ExamId = @rExamId -- Mantis : 0027635

	    	 WHERE
				 ((SAM.ClassSubjectId=@rClass) OR (@rClass=0))
				And SA.DivisionId =@rDivisionID	
				And SA.BatchId =@rBatchId
				--AND AIS.ExamId=@rExamId
				and ((SSA.SubjectActivityId=@rActivityId) OR (@rActivityId=0))
				AND((SSA.Id=@rSubjectSubActivityId) OR (@rSubjectSubActivityId=0))	
				and SSA.OrgId=@rOrgId
				AND  SA.StatusId = 1		
		 
			 ORDER BY SA.RollNo
			
END
GO
PRINT N'Altering Procedure [sAttendance].[pStudentAttendaceDashboardGet]...';


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

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

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

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

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

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

--Organization wise Attendance

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

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

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

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

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

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

      END
   
ELSE IF @rTypeId=24     
      BEGIN

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

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

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

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

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

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

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


GO
ALTER PROCEDURE [sBiometric].[pCloudTransactionDataAdd]

@rXmlDoc nvarchar(max) = ''

AS
SET NOCOUNT ON

BEGIN
	SET @rXmlDoc=REPLACE(@rXmlDoc,'&','AND')
	DECLARE @lInterrorCode INT,
			@intDoc INT
	BEGIN TRANSACTION					
	EXECUTE @lInterrorCode = sp_xml_preparedocument @intDoc OUTPUT, @rXmlDoc
	CREATE TABLE #tTable(
		TransactionId bigint NOT NULL,
		[PunchId] [nvarchar](50) NOT NULL,
		TransactionDateTime [datetime] NOT NULL,
		[DeviceIP] [nvarchar](20) NOT NULL,
		[Mode] [nvarchar](10) NOT NULL,
		[CreatedDateTime] [datetime] NOT NULL
	)
	INSERT INTO #tTable
	SELECT 
		A.TransactionId,
		A.PunchId,
		A.TransactionDateTime,
		A.DeviceIP,
		A.Mode,
		sCommon.fGetDate()
	FROM OPENXML (@intDoc, '/Table/CloudTransactionData', 1)
	WITH
	(
		TransactionId bigint '@TransactionId',
		PunchId nvarchar(50) '@PunchId',
		TransactionDateTime datetime '@TransactionDateTime',
		DeviceIP nvarchar(20) '@DeviceIP',		
		Mode nvarchar(10) '@Mode'	
	) A	

	INSERT INTO sBiometric.tCloudTransactionRawData
	SELECT 
		A.TransactionId,
		A.PunchId,
		A.TransactionDateTime,
		A.DeviceIP,
		A.Mode,
		A.CreatedDateTime
	From #tTable A 
	Where NOT EXISTS 
		(SELECT 1 FROM  sBiometric.tCloudTransactionRawData CRD where  A.TransactionDateTime=CRD.TransactionDateTime AND A.PunchId=CRD.PunchId AND A.DeviceIP=CRD.DeviceIP)
	
	INSERT INTO [sBiometric].[tCloudTransactionData] with (rowlock)
	--Employee
	SELECT 
		EM.Id,
		CRD.TransactionDateTime,
		CASE WHEN (SELECT 1 FROM sBiometric.tShiftAllocationCloud WHERE (ShiftDay = DATEPART(WEEKDAY, CRD.TransactionDateTime - 1) OR CRD.TransactionDateTime BETWEEN FromShiftDate AND ToShiftDate) AND SourceId = EM.Id AND SourceTypeId = 95) IS NOT NULL THEN 
		(SELECT top 1 ShiftCode FROM sBiometric.tShiftAllocationCloud WHERE (ShiftDay = DATEPART(WEEKDAY, CRD.TransactionDateTime - 1) OR CRD.TransactionDateTime BETWEEN FromShiftDate AND ToShiftDate) AND SourceId = EM.Id AND SourceTypeId = 95 order by fromShiftDate desc)
		ELSE EM.ShiftId END AS ShiftCode,
		CONVERT(DATE,CRD.TransactionDateTime) AS Attn_Dt,
		CASE WHEN (SELECT TOP 1 ISNULL(Mode,'IN') FROM [sBiometric].[tCloudTransactionData] WHERE SourceId = EM.Id AND Attn_Dt = CONVERT(DATE,CRD.TransactionDateTime) ORDER BY In_Out_Time DESC) = 'IN' THEN 'OUT' ELSE 'IN' END AS Mode,
		sCommon.fGetDate(),
		CRD.DeviceIP,
		0,
		CRD.PunchId,
		CRD.TransactionId,
		95,
		0
	FROM 
		sBiometric.tCloudTransactionRawData CRD 		
		INNER JOIN sHrm.tEmployeeMaster EM ON EM.PunchId = CRD.PunchId
	WHERE
		CRD.TransactionId NOT IN (SELECT TransactionId FROM sBiometric.tCloudTransactionData)

	UNION ALL

	--Student
	SELECT 
		SM.Id,
		CRD.TransactionDateTime,
		CASE WHEN (SELECT 1 FROM sBiometric.tShiftAllocationCloud WHERE (ShiftDay = DATEPART(WEEKDAY, CRD.TransactionDateTime - 1) OR CRD.TransactionDateTime BETWEEN FromShiftDate AND ToShiftDate) AND SourceId = SM.Id AND SourceTypeId = 2003) IS NOT NULL THEN 
		(SELECT top 1 ShiftCode FROM sBiometric.tShiftAllocationCloud WHERE (ShiftDay = DATEPART(WEEKDAY, CRD.TransactionDateTime - 1) OR CRD.TransactionDateTime BETWEEN FromShiftDate AND ToShiftDate) AND SourceId = SM.Id AND SourceTypeId = 2003 order by fromShiftDate desc)
		ELSE SM.ShiftId END AS ShiftCode,
		CONVERT(DATE,CRD.TransactionDateTime) AS Attn_Dt,
		CASE WHEN (SELECT TOP 1 ISNULL(Mode,'IN') FROM [sBiometric].[tCloudTransactionData] WHERE SourceId = SM.Id AND Attn_Dt = CONVERT(DATE,CRD.TransactionDateTime) ORDER BY In_Out_Time DESC) = 'IN' THEN 'OUT' ELSE 'IN' END AS Mode,
		sCommon.fGetDate(),
		CRD.DeviceIP,
		0,
		CRD.PunchId,
		CRD.TransactionId,
		2003,
		0
	FROM 
		sBiometric.tCloudTransactionRawData CRD 		
		INNER JOIN sStudent.tStudentMaster SM ON SM.PunchId = CRD.PunchId
	WHERE
		CRD.TransactionId NOT IN (SELECT TransactionId FROM sBiometric.tCloudTransactionData)

	DROP TABLE #tTable
	COMMIT TRANSACTION
	SELECT 1 AS Result
END
GO

 
 
 

PRINT N'Altering Procedure [sBiometric].[pRptEmployeeWiseMonthlySummaryGet]...';


GO

ALTER PROCEDURE [sBiometric].[pRptEmployeeWiseMonthlySummaryGet] 
     @rBuilder1 nvarchar(max)='',
	@rBuilder2 nvarchar(max)='',
	@rOrgId int ,
	@rDeptId int ,
	@rForYear int,
	@rForMonth int,	 
	@rEmployeeStatusId int,
	@rEmployeeId bigint,
	@rOrgGroupId int
WITH EXECUTE AS CALLER  
AS  
SET NOCOUNT ON  
BEGIN   
  
declare @Days int
Declare @lFromDate datetime
Declare @lToDate datetime


CREATE TABLE #TempMonthTrans  
 (  
 Id int ,  
 EmployeeId bigint,   
 Attn_Date DateTime,  
 PresentStatus nvarchar(15),  
 LateBy nvarchar(20),   
 EarlyBy nvarchar(20), 
 ) 
 select @Days=sCommon.fGetDaysInMonth(@rForMonth,@rForYear)
 set @lFromDate=CONVERT(nvarchar(20), @rForYear)+ '-' +  CONVERT(nvarchar(20), @rForMonth) + '-' + CONVERT(nvarchar(20), 01)
		set @lToDate=CONVERT(nvarchar(20), @rForYear)+ '-' +  CONVERT(nvarchar(20), @rForMonth) + '-' + CONVERT(nvarchar(20), @Days)
 --select @lFromDate,@lToDate
  INSERT INTO #TempMonthTrans 
  select Id,EmployeeId ,Attn_Date,PresentStatus ,LateBy, EarlyBy 
   from [sBiometric].[fBiometricTempMonthTransGet](@rOrgId ,@rDeptId ,@lFromDate,@lToDate,@rEmployeeId)

  SELECT
		@rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,
		MT.EmployeeId,
		MT.EmpCode,
		EM.FirstName + ' ' + EM.LastName AS EmployeeName,  
		OM.Id AS OrganizationId,
		OM.DisplayTitle AS OrganizationTitle,
		OM.OrderIndex AS OrganizationOrderIndex,
		EM.Number AS EmployeeNumber,
		DAY(DATEADD(MONTH, @rForMonth, DATEADD(YEAR, @rForYear - 1900, -1))) AS TotalDays,
		MT.Count_Late AS Count_Late,
		isnull(Absent.TotAbsent,0.00) AS TotalAbsentDays,
		isnull(WeekOff.TotWeekOff,0.00) AS TotalWeekOffs,
		isnull(Holidays.TotHoliday,0.00) AS TotalHolidays,
		isnull(Present.TotPresent,0.00) AS TotalPresentDays,
		isnull(HalfDay.TotHalfDay,0.00) AS TotalHalfDays,
		isnull(ErrorCase.TotalErrorCase,0.00) AS TotalErrorCase,
		ISNULL(EA.PaidLeave,0.00)  as PaidLeave,
		Isnull(EA.LWP,0.00)  AS UnPaidLeave,
		IsNull(MT.TotalHour,'00:00') as TotalHour,
		Isnull(MT.Tot_Early,'00:00') as Tot_Early,
		Isnull(MT.Tot_OT,'00:00') as Tot_OT,
		Isnull(MT.Tot_Late,'00:00') as Tot_Late,
		DM.Displaytitle AS DeptName,
		DM.Id As DeptId
	FROM
	sBiometric.tMonthTrans MT
	INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id = MT.EmployeeId AND (SourceTypeId = 95 OR SourceTypeId=0)
	left join [sHrm].[tEmployeeAttendance] EA ON EA.EmployeeId=Mt.EmployeeId AND EA.ForYear=@rForYear AND EA.ForMonth=@rForMonth
	INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = EM.OrgId
	INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id
	LEFT JOIN sSetup.tDepartmentMaster DM ON DM.Id = EJD.OrganizationDepartmentId
	LEFT Join (Select COUNT(*) AS TotPresent,EmployeeId from #TempMonthTrans Where PresentStatus IN ('P','PW','PH') group by EmployeeId) Present ON Present.EmployeeId = MT.employeeID
	LEFT Join (Select COUNT(*) AS TotAbsent,EmployeeId from #TempMonthTrans Where PresentStatus Like 'A' group by EmployeeId) Absent ON Absent.EmployeeId = MT.employeeID
	LEFT Join (Select COUNT(*) AS TotWeekOff,EmployeeId from #TempMonthTrans Where PresentStatus IN ('W','PW','PHW') group by EmployeeId) WeekOff ON WeekOff.EmployeeId = MT.employeeID
	LEFT Join (Select COUNT(*) AS TotHalfDay,EmployeeId from #TempMonthTrans Where PresentStatus Like 'HD' group by EmployeeId) HalfDay ON HalfDay.EmployeeId = MT.employeeID
    LEFT Join (Select COUNT(*) AS TotHoliday,EmployeeId from #TempMonthTrans Where PresentStatus Like 'H' group by EmployeeId) Holidays ON Holidays.EmployeeId = MT.employeeID	
	LEFT Join (Select COUNT(*) AS TotalErrorCase,EmployeeId from #TempMonthTrans Where PresentStatus Like 'E' group by EmployeeId) ErrorCase ON ErrorCase.EmployeeId = MT.employeeID	

	WHERE
	(EM.OrgId = @rOrgId OR @rOrgId = 0)
	--AND YEAR(MT.Attn_Dt) = @rForYear
	--AND (MONTH(MT.Attn_dt) = @rForMonth )
	AND MT.Attn_dt=cast(rtrim(@rForYear *10000+ @rForMonth *100+ 01) as datetime) --Mantis Id : 0028180
	AND (EJD.OrganizationDepartmentId = @rDeptId OR @rDeptId = 0)		 	
	AND (EM.StatusId = @rEmployeeStatusId OR ISNULL(@rEmployeeStatusId,0)=0)
	AND ISNULL(EM.IsOtherUser,0) = 0 
	AND (ISNULL(MT.SourceTypeId,95) = 95 OR MT.SourceTypeId = 0)
	AND (MT.EmployeeId = @rEmployeeId OR @rEmployeeId = 0)
	AND (OM.OrgGroupId = @rOrgGroupId)
	order by MT.EmpCode

	DROP Table #TempMonthTrans	
 --select 
 --@rBuilder1 AS Builder1,
	--	@rBuilder2 AS Builder2,
	--	CAST(0 AS bigint) AS EmployeeId,
	--	0 AS EmpCode,
	--	'' AS EmployeeName,  
	--	0 AS OrganizationId,
	--	'' AS OrganizationTitle,
	--	0 AS OrganizationOrderIndex,
	--	CAST(0 AS bigint) AS EmployeeNumber,
	--	DAY(DATEADD(MONTH, @rForMonth, DATEADD(YEAR, @rForYear - 1900, -1))) AS TotalDays,
	--	0.00 AS Count_Late,
	--	0.00 AS TotalAbsentDays,
	--	0.00 AS TotalWeekOffs,
	--	0.00 AS TotalHolidays,
	--	0.00 AS TotalPresentDays,
	--	0.00 AS TotalHalfDays,
	--	0.00 AS TotalErrorCase,
	--	0.00  as PaidLeave,
	--	0.00  AS UnPaidLeave,
	--	'00:00' as TotalHour,
	--	'00:00' as Tot_Early,
	--	'00:00' as Tot_OT,
	--	'00:00' as Tot_Late,
	--	'' AS DeptName,
	--	0 As DeptId

end
GO
PRINT N'Altering Procedure [sBiometric].[pShiftAllocationCloudAdd]...';


GO

--exec [sBiometric].[pShiftAllocationCloudAdd] @rXmlDoc=''
ALTER PROC [sBiometric].[pShiftAllocationCloudAdd]
	
		@rXmlDoc nvarchar(MAX)
	
AS

SET NOCOUNT ON

BEGIN
SET @rXmlDoc=REPLACE(@rXmlDoc,'&','AND')
DECLARE @lInterrorCode INT,
			@intDoc INT
DECLARE @lNextNumber BIGINT
			
BEGIN TRY
BEGIN TRANSACTION	
	EXECUTE @lInterrorCode = sp_xml_preparedocument @intDoc OUTPUT, @rXmlDoc	
	-----------------------
	CREATE TABLE #tTable  
	(
		SourceId bigint not null
		,SourceTypeId smallint null
		,ShiftCode int null
		,ShiftDay tinyint null		
		,FromShiftDate Datetime null
		,ToShiftDate DateTime null
		,ShiftAllocationId int null
	)

	INSERT INTO #tTable
			   (			    
				SourceId
				,SourceTypeId
				,ShiftCode 
				,ShiftDay 		
				,FromShiftDate 
				,ToShiftDate  
				,ShiftAllocationId 
			   )
	SELECT		
		
		A.SourceId,
		A.SourceTypeId,
		ShiftCode,
		ShiftDay,
		FromShiftDate,
		ToShiftDate,
		ShiftAllocationId
		
	FROM OPENXML (@intDoc, '/Table/ShiftAllocationCloud', 1)
	WITH
	(	
		SourceId bigint '@SourceId'
		,SourceTypeId smallint '@SourceTypeId'
		,ShiftCode int '@ShiftCode'
		,ShiftDay tinyint '@ShiftDay'	
		,FromShiftDate Datetime '@FromShiftDate'
		,ToShiftDate DateTime '@ToShiftDate'
		,ShiftAllocationId int	'@ShiftAllocationId'
	)A 
	select  @intDoc
	INSERT INTO sBiometric.tShiftAllocationCloud
	(
		SourceId,
		SourceTypeId,
		ShiftCode,
		ShiftDay,
		FromShiftDate,
		ToShiftDate
	)
	SELECT
		A.SourceId,
		A.SourceTypeId,
		A.ShiftCode,
		A.ShiftDay,
		A.FromShiftDate,
		A.ToShiftDate				
	FROM #tTable A 
	 WHERE A.SourceId Not in (SELECT SourceId From sBiometric.tShiftAllocationCloud  Where SourceId=A.SourceId  AND SourceTypeId=A.SourceTypeId AND (ShiftDay=A.ShiftDay AND FromShiftDate = A.FromShiftDate))
	 And A.ShiftAllocationId=0
	 --And A.SourceTypeId Not in (SELECT SourceTypeId From sBiometric.tShiftAllocationCloud Where SAC.ShiftDay=A.ShiftDay AND SAC.SourceId=A.SourceId AND SAC.FromShiftDate = A.FromShiftDate)
	
	
	--SELECT * From #tTable
	UPDATE SAC SET SAC.ShiftCode = A.ShiftCode,
				   SAC.ShiftDay=A.ShiftDay,
					SAC.FromShiftDate=A.FromShiftDate,
					SAC.ToShiftDate=A.ToShiftDate
	FROM 
	#tTable A 
	INNER JOIN sBiometric.tShiftAllocationCloud SAC ON SAC.SourceId = A.SourceId AND SAC.SourceTypeId = A.SourceTypeId and SAC.Id=A.ShiftAllocationId
	--WHERE A.Id  in (SELECT SourceId From sBiometric.tShiftAllocationCloud Where ShiftDay=A.ShiftDay AND SourceId=A.SourceId AND FromShiftDate = A.FromShiftDate)
	


	EXEC sp_xml_removedocument @intDoc
	COMMIT TRANSACTION
	SELECT 1
END TRY
	BEGIN CATCH
		SELECT -1
	END CATCH

END
GO
PRINT N'Altering Procedure [sBiometric].[pShiftAllocationCloudGet]...';


GO
 
ALTER PROCEDURE [sBiometric].[pShiftAllocationCloudGet]

@rOrgId int = 0,
@rSourceTypeId smallint = 0,
@rSerchBy int=1 --1 for ByDay, 2 For ByDate
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
IF (@rSourceTypeId=95)
	BEGIN
		SELECT 

			EM.Id AS EmployeeId,
			0 as StudentId,
			'' as StudentCode,
			'' as StudentName,
			EM.Code AS EmployeeCode,
			EM.FirstName + ' ' + EM.LastName AS EmployeeName,
			ISNULL(EM.ShiftId,0) AS CurrentShiftId,
			ISNULL(SA.ShiftCode,0) AS NewShiftId,
			ISNULL(SA.FromShiftDate,'') AS FromShiftDate,
			ISNULL(SA.ToShiftDate,'') AS ToShiftDate,
			ISNULL(SA.ShiftDay,0) AS ShiftDay,
			ISNULL(SA.Id,0) as ShiftAllocationId
		FROM 
			sHrm.tEmployeeMaster EM
			LEFT JOIN sBiometric.tShiftMasterCloud SMC ON SMC.ShiftCode = EM.ShiftId
			Inner JOIN sBiometric.tShiftAllocationCloud SA ON SA.SourceId = EM.Id AND SA.SourceTypeId=95 
				AND ((@rSerchBy=1 And SA.ShiftDay<>0 ) or (@rSerchBy=2 And SA.ShiftDay=0))
		WHERE
			EM.OrgID = @rOrgId AND EM.StatusId=7
		Union All
			SELECT 

			EM.Id AS EmployeeId,
			0 as StudentId,
			'' as StudentCode,
			'' as StudentName,
			EM.Code AS EmployeeCode,
			EM.FirstName + ' ' + EM.LastName AS EmployeeName,
			ISNULL(EM.ShiftId,0) AS CurrentShiftId,
			0 AS NewShiftId,
			'' AS FromShiftDate,
			'' AS ToShiftDate,
			0 AS ShiftDay,
			0 as ShiftAllocationId
		FROM 
			sHrm.tEmployeeMaster EM
			LEFT JOIN sBiometric.tShiftMasterCloud SMC ON SMC.ShiftCode = EM.ShiftId
			
		WHERE
			EM.OrgID = @rOrgId AND EM.StatusId=7

		Order by EmployeeId,ShiftAllocationId
			
	END
ELSE IF(@rSourceTypeId=2003)
	BEGIN
			SELECT 
				SM.Id AS StudentId,
				SM.Code AS StudentCode,
				SM.FirstName + ' ' + SM.LastName AS StudentName,
				ISNULL(SM.ShiftId,0) AS CurrentShiftId,
				ISNULL(SA.ShiftCode,0) AS NewShiftId,
				ISNULL(SA.FromShiftDate,'') AS FromShiftDate,
				ISNULL(SA.ToShiftDate,'') AS ToShiftDate,
				ISNULL(SA.ShiftDay,0) AS ShiftDay,
				0 as EmployeeId,
				'' as EmployeeCode,
				'' as EmployeeName,
				ISNULL(SA.Id,0) as ShiftAllocationId
			FROM 
				sStudent.tStudentMaster SM
				LEFT JOIN sBiometric.tShiftMasterCloud SMC ON SMC.ShiftCode = SM.ShiftId
				Inner JOIN sBiometric.tShiftAllocationCloud SA ON SA.SourceId = SM.Id	AND SA.SourceTypeId=2003
					AND ((@rSerchBy=1 And SA.ShiftDay<>0 ) or (@rSerchBy=2 And SA.ShiftDay=0))
			WHERE
				SM.OrgID = @rOrgId AND SM.StatusId=1
		Union All
			SELECT 
				SM.Id AS StudentId,
				SM.Code AS StudentCode,
				SM.FirstName + ' ' + SM.LastName AS StudentName,
				ISNULL(SM.ShiftId,0) AS CurrentShiftId,
				0 AS NewShiftId,
				'' AS FromShiftDate,
				'' AS ToShiftDate,
				0 AS ShiftDay,
				0 as EmployeeId,
				'' as EmployeeCode,
				'' as EmployeeName,
				0 as ShiftAllocationId
			FROM 
				sStudent.tStudentMaster SM
				LEFT JOIN sBiometric.tShiftMasterCloud SMC ON SMC.ShiftCode = SM.ShiftId
				
			WHERE
				SM.OrgID = @rOrgId AND SM.StatusId=1	
			Order by EmployeeId,ShiftAllocationId
	END
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
		
	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 [sCommunication].[pCircularGet]...';


GO
 
 
ALTER PROCEDURE [sCommunication].[pCircularGet]
	 @rId bigint = 0,
	 @rTitle nvarchar(100),
	 @rFromDate date,
	 @rToDate date,
	 @rOrgGroupBatchId int,
	 @rIsSearch bit = 1,
	 @rAssigneeId tinyint,
	 @rCircularTypeId int,
	 @rCreatedUserId bigint=0
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	 IF @rIsSearch = 1
		BEGIN
			SET @rTitle = sCommon.fSearchStringGet(@rTitle)
		END
	
	SELECT 
	
			C.Id as CircularId,
			C.Title,
			C.Remark,
			C.StartDate,
			U.DisplayTitle as CreatedUserName,
			C.AssigneeId,
			AM.Title AS Assignee,
			CTM.Title AS CircularTypeTitle,
			CTM.HighlightColor,
			C.CircularTypeId,
			C.CreatedUserId,
			C.CreatedDateTime,
			ISNULL(C.StatusId,549) AS StatusId,
			ISNULL(C.PublishDateTime,'') as PublishDateTime,
			--CASE WHEN ISNULL(C.StatusId,549) =549 then 'Pending' WHEN C.StatusId=550 then 'Approve' ELSE 'Reject' END AS Status
			ISNULL(C.IsPublishInFuture,0) as PublishInFuture
			--ISNULL(C.IsConsent,0) AS IsConsent
  FROM 
            sCommunication.tCircular C
            INNER JOIN sSecurity.tUser U ON U.Id=C.CreatedUserId
            INNER JOIN sCommon.tAssigneeMaster AM ON AM.Id=C.AssigneeId
            INNER JOIN sCommunication.tCircularTypeMaster CTM ON CTM.Id = C.CircularTypeId
  WHERE 
  
		((C.Id = @rId) OR (@rId = 0))
	AND ((C.Title like @rTitle) OR (ISNULL(@rTitle,'') = ''))
	AND ((C.StartDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
	AND ((C.StartDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
	AND ((C.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
	AND ((C.AssigneeId IN (1,2,3) AND @rAssigneeId=1)  OR
		 (C.AssigneeId = @rAssigneeId AND @rAssigneeId IN (2,3)) OR
		  @rIsSearch = 0)
     AND (C.CircularTypeId=@rCircularTypeId OR @rIsSearch = 0)
    AND (C.CreatedUserId = @rCreatedUserId OR @rCreatedUserId = 0)
	ORDER BY C.StartDate DESC
END
GO
PRINT N'Altering Procedure [sCommunication].[pMyUpdateGet]...';


GO


--------------------
ALTER PROCEDURE [sCommunication].[pMyUpdateGet]  
@rOrgId int,    
@rBatchId int,  
@rOrgGroupBatchId int,  
@rUserId bigint,  
@rUserSourceId bigint,  
@rUserSourceTypeId int,  
@rSyncedAssignmentId bigint,  
@rSyncedCircularId bigint,  
@rSyncedPollId bigint,  
@rSyncedQueryCommentId bigint,  
@rSyncedNewsId bigint,  
@rSyncedBlogId bigint,  
@rSyncedBehaviourId bigint,  
@rSyncedActivityId bigint,  
@rSyncedResultId bigint,  
@rSyncedAssignTaskId bigint,  
@rSyncedPhotoCategoryId int,  
@rVersionNumber nvarchar(Max)='',  
@rDeviceToken nvarchar(200)='',  
@rOSTypeId smallint = 0,
@rAppVersion nvarchar(20)='',
@rAppName nvarchar(100)=''

 WITH EXECUTE AS CALLER  
AS  
SET NOCOUNT ON  
      
BEGIN   
 DECLARE @lAcademicId bigint,  
  @lScopeSourceId int,  
  @lScopeSourceTypeId int,  
  @lStudentId bigint,  
  @lClassId int,  
  @lDivisionId int,  
  @lOrgId int,  
  @lDepartmentId int,  
  @lAssignmentStatus bit=0,  
  @lCircularStatus bit=0,  
  @lPollStatus bit=0,  
  @lQueryStatus bit=0,  
  @lBlogStatus bit=0,  
  @lNewsStatus bit=0,  
  @lBehaviourStatus bit=0,  
  @lActivityStatus bit=0,  
  @lResultStatus bit=0,  
  @lAssignTaskStatus bit=0,  
  @lPhotoCategoryStatus bit=0,  
  @lIsActive bit=0,  
  @lIsOptimizeAppImageUpload bit=0  
  
IF( @rUserSourceTypeId = 2003)   
BEGIN  
  SELECT @lAcademicId = A.Id,@lStudentId = A.StudentId,@lClassId = A.ClassId, @lDivisionId = A.DivisionId, @lOrgId= A.OrgId, @lDepartmentId=CM.DepartmentId  
  FROM sStudent.tAcademic A INNER JOIN sSetup.tBatchMaster BM  
 ON A.BatchId = BM.Id AND BM.IsActive = 1   
 INNER JOIN sSetup.tClassMaster CM ON CM.Id = A.ClassId  
 WHERE StudentId = @rUserSourceId AND BM.OrgGroupBatchId = @rOrgGroupBatchId  
--SELECT @lAcademicId = Id, @lScopeSourceId = DivisionId FROM sStudent.tAcademic WHERE StudentId = @rUserSourceId AND BatchId = @rBatchId  
SET @lScopeSourceId = @lDivisionId  
SET @lScopeSourceTypeId = 2005  
END  
ELSE  
BEGIN  
 SELECT @lDepartmentId=EJD.OrganizationDepartmentId,@lOrgId = EM.OrgId  FROM sHrm.tEmployeeMaster EM INNER JOIN sHrm.tEmployeeJobDetail EJD  
    ON EJD.EmployeeId = EM.Id WHERE EM.Id=@rUserSourceId AND ISNULL(EM.IsOtherUser,0) = 0  
--SELECT @lScopeSourceId = OrganizationDepartmentId FROM sHrm.tEmployeeJobDetail WHERE EmployeeId = @rUserSourceId  
SET @lScopeSourceId = @lDepartmentId  
SET @lScopeSourceTypeId = 2004  
END  
--IF EXISTS(SELECT 1 FROM sCommunication.tAssignmentScope ASO INNER JOIN  sCommunication.tAssignment A  
-- ON A.Id = ASO.AssignmentId  
--WHERE ASO.AssignmentId > @rSyncedAssignmentId AND ASO.SourceTypeId = @lScopeSourceTypeId AND ASO.SourceId = @lScopeSourceId AND A.BatchId=@rBatchId)  
--SET @lAssignmentStatus = 1  
  
  
--IF( @rUserSourceTypeId = 2003)   
--BEGIN  
  
--    IF EXISTS(SELECT 1 FROM sCommunication.tCircular C INNER JOIN (SELECT CS.CircularId FROM sCommunication.tCircularScope CS WHERE  
--      ((CS.SourceTypeId = 2021 AND CS.SourceId =@lOrgId)   
--      OR (CS.SourceTypeId = 2004 AND CS.SourceId =@lDepartmentId)  
--      OR (CS.SourceTypeId = 2016 AND CS.SourceId =@lClassId)  
--      OR (CS.SourceTypeId = 2005 AND CS.SourceId =@lDivisionId)  
--      OR (CS.SourceTypeId = 2003 AND CS.SourceId =@lStudentId)  
--      OR (CS.SourceTypeId = 2001 AND CS.SourceId =@lAcademicId)  
--      )  
--       AND (CS.CircularId > @rSyncedCircularId OR @rSyncedCircularId = 0)) D ON D.CircularId= C.Id  
--      --INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=C.OrgGroupBatchId AND OGBM.Id=@rOrgGroupBatchId  
--        WHERE ( c.Id > @rSyncedCircularId OR @rSyncedCircularId = 0)  
--        AND C.AssigneeId IN (1,2) AND C.OrgGroupBatchId=@rOrgGroupBatchId)   
--      SET @lCircularStatus = 1  
  
--END   
--ELSE  
--BEGIN  
-- IF EXISTS(SELECT 1 FROM sCommunication.tCircular C INNER JOIN (SELECT CS.CircularId FROM sCommunication.tCircularScope CS  
--       WHERE ((CS.SourceTypeId = 2021 AND CS.SourceId =@lOrgId) OR (CS.SourceTypeId = 2004 AND CS.SourceId =@lDepartmentId))  
--       AND (CS.CircularId > @rSyncedCircularId OR @rSyncedCircularId = 0)) D ON D.CircularId= C.Id  
--       --INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=C.OrgGroupBatchId AND OGBM.Id=@rOrgGroupBatchId  
--       WHERE ( c.Id > @rSyncedCircularId OR @rSyncedCircularId = 0)  
--       AND C.AssigneeId IN (1,3) AND C.OrgGroupBatchId=@rOrgGroupBatchId)   
--     SET @lCircularStatus = 1         
  
--END  
--IF EXISTS(SELECT 1 FROM sCommunication.tCircularScope WHERE  CircularId > @rSyncedCircularId AND SourceTypeId = @lScopeSourceTypeId AND SourceId = @lScopeSourceId)  
--SET @lCircularStatus = 1  
  
--IF EXISTS(SELECT 1 FROM sCommunication.tPoll P INNER JOIN sCommunication.tPollMember PM ON P.Id=PM.PollId  
-- WHERE PM.PollId > @rSyncedPollId AND PM.SourceTypeId = @lScopeSourceTypeId AND PM.SourceId = @lScopeSourceId AND P.OrgGroupBatchId=@rOrgGroupBatchId)  
--SET @lPollStatus = 1  
  
--IF EXISTS(SELECT 1 FROM sCommunication.tBlogScope BS INNER JOIN sCommunication.tBlog B  
--ON B.Id = BS.BlogId  
--WHERE B.IsPublish = 1 AND BS.BlogId > @rSyncedBlogId AND BS.SourceTypeId = 2021 AND BS.SourceId = @rOrgId AND B.OrgGroupBatchId = @rOrgGroupBatchId)  
--SET @lBlogStatus = 1  
  
--IF EXISTS(SELECT 1 FROM  sCommunication.tNews N INNER JOIN sCommunication.tNewsScope NS ON N.Id=NS.NewsId   
--   WHERE NS.NewsId > @rSyncedNewsId AND NS.SourceTypeId = 2021 AND NS.SourceId = @rOrgId AND N.OrgGroupBatchId = @rOrgGroupBatchId)  
--SET @lNewsStatus = 1  
  
--IF EXISTS(SELECT 1 FROM sCommunication.tNewsScope WHERE NewsId > @rSyncedNewsId AND SourceTypeId = @rOrgId AND SourceId = 1016)  
--SET @lNewsStatus = 1  
  
--IF EXISTS(SELECT 1 FROM sCommunication.tUploadResult WHERE Id > @rSyncedResultId AND DivisionId = @lScopeSourceId AND BatchId=@rBatchId AND IsObsolete=0 )  
--SET @lResultStatus = 1  
  
--IF EXISTS(SELECT 1 FROM    
--sCommunication.tPhotoCategoryMaster PCM  
--INNER JOIN sCommunication.tPhotoCategoryScope PCO   
--ON PCM.Id=PCO.PhotoCategoryId WHERE PCM.Id > @rSyncedPhotoCategoryId AND LEFT(PCO.ScopeSourceId,4) = @rOrgId  AND PCM.IsObsolete=0 )  
--SET @lPhotoCategoryStatus = 1  
  
  
--IF EXISTS(SELECT 1 FROM sCommunication.tAssignTask WHERE  Id > @rSyncedAssignTaskId AND AssignedToSourceTypeId = @rUserSourceTypeId   
--AND AssignedToSourceId = @rUserSourceId AND IsCompleted=0 AND IsClosed=0 AND OrgId=@rOrgId)  
--SET @lAssignTaskStatus = 1  
  
  
--IF EXISTS(SELECT 1 FROM  sActivity.tActivity A INNER JOIN sActivity.tActivityParticipant AP ON A.Id=AP.ActivityId  
-- WHERE AP.ActivityId > @rSyncedActivityId AND AP.SourceTypeId = @rUserSourceTypeId AND AP.SourceId = @rUserSourceId AND A.BatchId=@rBatchId)  
--SET @lActivityStatus = 1  
  
--IF EXISTS(SELECT 1 FROM sCommunication.tBehaviour WHERE Id > @rSyncedBehaviourId AND AcademicId = @lAcademicId )  
--SET @lBehaviourStatus = 1  
  
--IF EXISTS(SELECT 1 FROM sCommunication.tQuery Q INNER JOIN sCommunication.tQueryComment QC ON Q.Id=QC.QueryId  
--WHERE Q.CreatedUserId=@rUserId AND Q.IsUserView=0 AND QC.Id>@rSyncedQueryCommentId AND QC.CreatedUserId <> @rUserSourceId AND Q.OrgGroupBatchId=@rOrgGroupBatchId)  
--SET @lQueryStatus = 1  
   
IF(@rUserSourceTypeId = 2003)  
BEGIN   
 DECLARE @lStatusId1 smallint=0  
  SELECT @lStatusId1 = StatusId FROM sStudent.tStudentMaster SM WHERE Id = @rUserSourceId  
 IF(@lStatusId1=1)  
 BEGIN   
  SET @lIsActive = 1  
 END ELSE  
 BEGIN  
  SET @lIsActive = 0  
 END  
END  
ELSE IF(@rUserSourceTypeId = 95)  
BEGIN   
 DECLARE @lStatusId2 smallint=0  
 SELECT @lStatusId2 = StatusId FROM sHrm.tEmployeeMaster EM WHERE Id = @rUserSourceId --AND ISNULL(EM.IsOtherUser,0) = 0  
 IF(@lStatusId2=7)  
 BEGIN   
  SET @lIsActive = 1  
 END ELSE  
 BEGIN  
  SET @lIsActive = 0  
 END  
END  
ELSE IF(@rUserSourceTypeId = 1)  
BEGIN   
 DECLARE @IsObsolete smallint=0 
 SELECT @IsObsolete=ISNULL(IsObsolete,0) FROM sSecurity.tUser WHERE Id = @rUserId  
 IF(@IsObsolete=0)  
 BEGIN   
  SET @lIsActive = 1  
 END   
 ELSE  
 BEGIN  
  SET @lIsActive = 0  
 END  
END  
  
IF(@lIsActive=1)  
BEGIN  
 DECLARE @lIsObsolete bit=0  
 SELECT @lIsObsolete=ISNULL(IsObsolete,0) FROM sSecurity.tUser WHERE Id = @rUserId  
  
 IF(@lIsObsolete=0)  
  SET @lIsActive = 1  
 ELSE  
  SET @lIsActive = 0  
END  
  
  
DECLARE @lOrgGroupId int=0  
SELECT @lOrgGroupId=OrgGroupId FROM sSetup.tOrganizationMaster WHERE Id =@rOrgId  
DECLARE @lOptimizeAppImageUpload nvarchar(50)  
SELECT @lOptimizeAppImageUpload = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 247 AND SourceTypeId = 2010 AND SourceId = @lOrgGroupId  
IF (@lOptimizeAppImageUpload IS NULL) OR (@lOptimizeAppImageUpload = 'False')  
 SET @lIsOptimizeAppImageUpload = 0  
ELSE  
 SET @lIsOptimizeAppImageUpload = 1   
   
DECLARE @lAlertRemark nvarchar(2000) = ''  
   
--IF(@rVersionNumber IS NULl OR @rVersionNumber='')  
--BEGIN  
-- DECLARE @lUserName nvarchar(100)=''  
-- DECLARE @lUserPassword nvarchar(100)=''  
-- DECLARE @lBatch nvarchar(100)=''  
-- SELECT @lBatch = Title  FROM sSetup.tBatchMaster WHERE Id = @rBatchId  
   
-- SELECT @lUserName=UserName,@lUserPassword=UserPassword FROM sSecurity.tTempUser WHERE UserId = @rUserId  
-- SET @lAlertRemark = 'Plese install the new app from this location (https://play.google.com/store/apps/details?id=com.vidyalaya.pinnacleschoolgandhinagarnew) Uninstall the old app. Login in new app with  
--       Registration Number : '+LEFT(@rOrgGroupBatchId,4) +'  
--       User Name : '+@lUserName+'  
--       Password : '+@lUserPassword+'  
--       Batch :' + @lBatch  
--END  
--ELSE   
BEGIN  
 SELECT @lAlertRemark=AlertRemark FROM sSetup.tOrgGroupConfiguration WHERE OrgGroupId = @lOrgGroupId  
END  
  
DECLARE @lMobileAppModuleAutoSyncToken nvarchar(50)  
SELECT @lMobileAppModuleAutoSyncToken = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 317 AND SourceTypeId = 2010 AND SourceId = @lOrgGroupId  
  
  
DECLARE @lIsStopApplicationAccess bit=0  
DECLARE @lStudentCustomAlert nvarchar(1000)=''  
IF(@rUserSourceTypeId=2003)  
SELECT @lIsStopApplicationAccess = ISNULL(IsStopApplicationAccess,0) ,@lStudentCustomAlert= ISNULL(StudentCustomAlert,'') FROM sStudent.tStudentCommunication WHERE StudentId = @rUserSourceId  
  
  
IF(LEN(@rDeviceToken) > 0)  
BEGIN   
 DECLARE @lDeviceToken nvarchar(200)=''  
 SELECT @lDeviceToken = DeviceToken FROM sCommunication.tRegisteredUsers WHERE OrgId=@rOrgId AND UserId=@rUserId AND UserSourceId=@rUserSourceId AND UserSourceTypeId = @rUserSourceTypeId AND OSTypeId = @rOSTypeId  
  
 DECLARE @lConfigValue nvarchar(50)=''  
 SELECT @lConfigValue = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 374 AND SourceTypeId = 2010 AND SourceId = @lOrgGroupId  
  
 IF @lConfigValue IS NULL   
 SET @lConfigValue = 'False'  
  
 IF @lConfigValue = 'True'  
 BEGIN  
 IF(@lDeviceToken!=@rDeviceToken)  
  SET @lIsActive=0  
 END  
 
 SET @lDeviceToken = (SELECT DeviceToken FROM sCommunication.tRegisteredUsers WHERE OrgId=@rOrgId AND UserId=@rUserId AND UserSourceId=@rUserSourceId AND UserSourceTypeId = @rUserSourceTypeId AND DeviceToken=@rDeviceToken)  	
 IF(@lDeviceToken IS NULL OR @lDeviceToken='' OR ISNULL(@lDeviceToken,'') = '')  
  SET @lIsActive=0  
END  
  
DECLARE @lActiceClassBatchId NVARCHAR(MAX) = '',@lBatchClassId int  
   
IF(@rUserSourceTypeId = 2003)  
BEGIN   
 SELECT @lBatchClassId = A.ClassId  
 FROM sStudent.tAcademic A INNER JOIN sSetup.tBatchMaster BM ON A.BatchId = BM.Id  
 INNER JOIN sSetup.tClassMaster CM ON CM.Id = A.ClassId  
 WHERE StudentId = @rUserSourceId AND BM.OrgGroupBatchId = @rOrgGroupBatchId  
  
 IF EXISTS(SELECT BatchId FROM [sSetup].[tBatchClass] BC INNER JOIN sSetup.tBatchMaster BM ON BM.Id = BC.BatchId WHERE ClassId = @lBatchClassId AND IsBatchClassActive = 1 AND BM.IsActive = 1)  
 BEGIN  
  SELECT @lActiceClassBatchId = CONVERT(NVARCHAR,BC.BatchId)+','+ BM.Title FROM [sSetup].[tBatchClass] BC INNER JOIN sSetup.tBatchMaster BM ON BM.Id = BC.BatchId WHERE BC.ClassId = @lBatchClassId AND BC.IsBatchClassActive = 1 AND BM.IsActive = 1  
 END  
 ELSE  
 BEGIN  
  SELECT @lActiceClassBatchId = CONVERT(NVARCHAR,Id) +','+ Title FROM sSetup.tBatchMaster WHERE Id = @rBatchId  
 END  
END  
ELSE IF(@rUserSourceTypeId = 95)  
BEGIN  
 SELECT @lActiceClassBatchId = CONVERT(NVARCHAR,Id) +','+ Title FROM sSetup.tBatchMaster WHERE Id = @rBatchId  
END  


IF(LEN(ISNULL(@rAppVersion,'')) > 0 AND LEN(ISNULL(@rAppVersion,'')) > 0)
BEGIN
	UPDATE sCommunication.tRegisteredUsers
	SET
		AppVersion = @rAppVersion,
		AppName = @rAppName,
		UpdatedDateTime = sCommon.fGetDate(),
		DeviceDetail = @rVersionNumber
	WHERE 
		DeviceToken = @rDeviceToken 
		AND OsTypeId = @rOSTypeId
		AND OrgId=@rOrgId AND UserId=@rUserId 
		AND UserSourceId=@rUserSourceId AND UserSourceTypeId = @rUserSourceTypeId
END
CREATE TABLE #Module (  
Id int,  
Title nvarchar(2000),  
IsNew bit )  
INSERT INTO #Module VALUES (1,'IsActiveCheck',CONVERT(bit,@lIsActive))  
INSERT INTO #Module VALUES (2,'IsOptimizeAppImageUpload',@lIsOptimizeAppImageUpload)  
INSERT INTO #Module VALUES (3,ISNULL(@lAlertRemark,''),1)  
INSERT INTO #Module VALUES (4,ISNULL(@lMobileAppModuleAutoSyncToken,0),1)  
INSERT INTO #Module VALUES (5,'Is Stop Application Access',@lIsStopApplicationAccess)  
INSERT INTO #Module VALUES (6,@lStudentCustomAlert,1)  
INSERT INTO #Module VALUES (20085,'Circular',0)  
INSERT INTO #Module VALUES (20088,'Query',0)  
INSERT INTO #Module VALUES (20099,'Blog',0)  
INSERT INTO #Module VALUES (20104,'News',0)  
INSERT INTO #Module VALUES (20172,'AssignTask',0)  
INSERT INTO #Module VALUES (20183,'Gallery',0)  
INSERT INTO #Module VALUES (20204,'Poll',0)  
INSERT INTO #Module VALUES (20093,'Assignment',0)  
INSERT INTO #Module VALUES (20209,'Activity',0)  
INSERT INTO #Module VALUES (20130,'Behaviour',0)  
INSERT INTO #Module VALUES (20180,'Result',0)  
INSERT INTO #Module VALUES (7,@lActiceClassBatchId,1)  
   
SELECT * FROM #Module  
   
--SELECT @lAssignmentStatus AS Assignment,@lCircularStatus AS Circular,@lPollStatus AS Poll,@lQueryStatus AS Query,  
--@lBlogStatus AS Blog,@lNewsStatus AS News,@lBehaviourStatus AS Behaviour,  
--@lActivityStatus AS Activity,@lResultStatus AS Result,@lAssignTaskStatus AS AssignTask,@lPhotoCategoryStatus AS Gallery  
  
END
GO
PRINT N'Altering Procedure [sCommunication].[pTempCircularAdd]...';


GO
 
ALTER PROCEDURE [sCommunication].[pTempCircularAdd]
	 
        @rId bigint,
		@rTitle nvarchar(200),
		@rRemark nvarchar(max),
		@rStartDate date,
		@rCreatedUserId bigint,
        @rOrgGroupId smallint,
        @rOrgGroupBatchId int,
        @rAssigneeId tinyint,
        @rCircularTypeId int,
        @rTempCircularId nvarchar(100),
		@rPublishDateTime DateTime = '',
		@rPublishInFuture bit = 0
		--@rIsConsent bit = 0
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	
	BEGIN TRY
	BEGIN TRANSACTION	
	DECLARE @lNextNumber BIGINT 

	IF(@rId = 0)	
	BEGIN
		
	EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sCommunication.tCircular', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	 
	DECLARE @lConfigValue nvarchar(50)
	DECLARE @lIsCircularBasedOnApproval bit=0
	SELECT @lConfigValue = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 302 AND SourceTypeId = 2010 AND SourceId = LEFT(@rOrgGroupBatchId,4)

	IF (@lConfigValue IS NULL) OR (@lConfigValue = 'False')
	SET @lIsCircularBasedOnApproval = 0
	ELSE
	SET @lIsCircularBasedOnApproval = 1	
	
	Declare @StatusId smallint
	IF(@lIsCircularBasedOnApproval=0)
	SET @StatusId=550
	ELSE
	SET @StatusId=549
	
	INSERT INTO sCommunication.tCircular
		(
			Id,
			Title,
			Remark,
			StartDate,
			CreatedUserId,
			CreatedDateTime,
			OrgGroupId,
			OrgGroupBatchId,
			AssigneeId,
			CircularTypeId,
			StatusId,
			PublishDateTime,
			IsPublishInFuture
			--IsConsent
		)
	VALUES
		(
			@lNextNumber,
			@rTitle,
			@rRemark,
			@rStartDate,
			@rCreatedUserId,
			sCommon.fGetDate(), 
			@rOrgGroupId,
			@rOrgGroupBatchId,
			@rAssigneeId,
			@rCircularTypeId,
			@StatusId,
			@rPublishDateTime,
			@rPublishInFuture
			--@rIsConsent
		)
		
		SELECT @lNextNumber AS Result  
		    
		INSERT INTO sCommunication.tCircularScope
		SELECT @lNextNumber,SourceTypeId,SourceId,AssigneeToId
		FROM sCommunication.tTempCircularScope 
		WHERE TempCircularId = @rTempCircularId
		
		DELETE FROM sCommunication.tTempCircularScope WHERE TempCircularId = @rTempCircularId
		
		
	END	 

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


GO
ALTER PROCEDURE [sFee].[pCollectionGroupGet]
		
	@rSourceId bigint,
	@rSourceTypeId int=0,
	@rReceiptBookId int=0,
	@rReceiptId bigint=0,
	@rBatchId int,
	@rCollectionGroupId int =0 
		
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
		
BEGIN 	
	DECLARE @lClassId int
	DECLARE @lAdmissionCategoryId int,@lOrgId int,@lOrgGorupId int
	SELECT @lClassId=ClassId,@lAdmissionCategoryId=AdmissionCategoryId,@lOrgId = OrgId FROM sStudent.vStudentAcademic WHERE AcademicId=@rSourceId	
	
	Select @lOrgGorupId = OrgGroupId from sSetup.tOrganizationMaster Where Id = @lOrgId
				
	DECLARE @lConfigValue nvarchar(50)
	--,@lOrgGroupBatchId int
	--SELECT @lOrgGroupBatchId = OrgGroupBatchId FROM [sSetup].[tBatchMaster] WHERE Id = @rBatchId
	SELECT @lConfigValue = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 487 AND SourceTypeId = 2010 AND SourceId = @lOrgGorupId


	IF(@lConfigValue = 'True')
	BEGIN
		SELECT 
			SUM(CG.PayableAmount) AS PendingAmount 
			,CollectionGroupId
			,StartDate
			,EndDate
			,CollectionGroupName
			,ReceiptBookId
			,ReceiptBook
			,CollectionGroupCode -- added for mantis 0026962 by Foram
		FROM
			(SELECT 
				FM.Id AS FeeId,
				FM.Title AS FeeName,
				FS.Id AS FeeSetupId,			 
				FS.ReceiptBookId,
				RBM.Title AS ReceiptBook,
				ISNULL(R.PaidAmount,0) AS PaidAmount,
				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,
				--FM.OrderIndex,
				FS.CollectionGroupId,
				CGM.StartDate,
				CGM.EndDate,
				CGM.Title AS CollectionGroupName,
				CGM.OrderIndex,
				CGM.Code AS CollectionGroupCode -- added for mantis 0026962 by Foram
			FROM 
				sFee.tFeeMaster FM
				INNER JOIN 
				(
					SELECT 
						FS1.FeeId,
						FS1.Id,
						ISNULL(FS1.IsOptional,0)AS IsOptional,
						ISNULL(FS1.IsVariable,0)AS IsVariable,
						ISNULL(FS1.Amount,0)AS Amount,
						ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
						ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
						FS1.BatchId,
						ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
						ISNULL(FS1.CollectionGroupId,0) AS CollectionGroupId
					FROM sFee.tFeeSetup FS1
					WHERE FS1.ClassId=@lClassId AND FS1.BatchId = @rBatchId  
						AND ((FS1.CollectionGroupId=@rCollectionGroupId) OR (@rCollectionGroupId=0))
						AND FS1.AdmissionCategoryId=@lAdmissionCategoryId AND IsOptional=0
				
						UNION ALL
				
					SELECT 
						FS1.FeeId,
						FS1.Id,
						ISNULL(FS1.IsOptional,0)AS IsOptional,
						ISNULL(FS1.IsVariable,0)AS IsVariable,
						ISNULL(FS1.Amount,0)AS Amount,
						ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
						ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
						FS1.BatchId,
						ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
						ISNULL(FS1.CollectionGroupId,0) AS CollectionGroupId
					FROM sFee.tFeeSetup FS1
				INNER JOIN sFee.tFeeOptional FO
					ON FO.FeeSetupId=FS1.Id AND (FO.SourceId=@rSourceId) AND ((FO.SourceTypeId=@rSourceTypeId) OR (@rSourceTypeId=0))
				WHERE
						FS1.ClassId=@lClassId AND FS1.BatchId =@rBatchId AND FS1.AdmissionCategoryId=@lAdmissionCategoryId AND IsOptional=1
						AND ((FS1.CollectionGroupId=@rCollectionGroupId) OR (@rCollectionGroupId=0))
				
				) 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 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 ((FSR.CollectionGroupId=@rCollectionGroupId) OR (@rCollectionGroupId=0))
					AND R.SourceId= @rSourceId
					AND ((R.SourceTypeId=@rSourceTypeId) OR (@rSourceTypeId=0))
					AND R.IsObsolete = 0 			 
					 GROUP BY FeeSetupId
				) R ON R.FeeSetupId = FS.Id 
				LEFT JOIN sFee.tFeeAllocation FA ON FA.FeeSetupId=FS.Id AND (FA.SourceId=@rSourceId) AND ((FA.SourceTypeId=@rSourceTypeId) OR (@rSourceTypeId=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(@rReceiptId=0) OR(@rReceiptId<>0))
				AND(FS.BatchId=@rBatchId)
				AND CAST(sCommon.fGetDate() AS DATE) <= CAST(CGM.EndDate AS DATE)
				AND CGM.IsObsolete = 0
			) AS CG
		GROUP BY CollectionGroupId,StartDate,EndDate,CollectionGroupName,CollectionGroupCode,OrderIndex,ReceiptBookId,ReceiptBook
		ORDER BY CG.StartDate,CG.OrderIndex
	END
	ELSE
	BEGIN
		SELECT 
			SUM(CG.PayableAmount) AS PendingAmount 
			,CollectionGroupId
			,StartDate
			,EndDate
			,CollectionGroupName
			,ReceiptBookId
			,ReceiptBook
			,CollectionGroupCode -- added for mantis 0026962 by Foram
		FROM
			(SELECT 
				FM.Id AS FeeId,
				FM.Title AS FeeName,
				FS.Id AS FeeSetupId,			 
				FS.ReceiptBookId,
				RBM.Title AS ReceiptBook,
				ISNULL(R.PaidAmount,0) AS PaidAmount,
				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,
				--FM.OrderIndex,
				FS.CollectionGroupId,
				CGM.StartDate,
				CGM.EndDate,
				CGM.Title AS CollectionGroupName,
				CGM.OrderIndex,
				CGM.Code AS CollectionGroupCode -- added for mantis 0026962 by Foram
			FROM 
				sFee.tFeeMaster FM
				INNER JOIN 
				(
					SELECT 
						FS1.FeeId,
						FS1.Id,
						ISNULL(FS1.IsOptional,0)AS IsOptional,
						ISNULL(FS1.IsVariable,0)AS IsVariable,
						ISNULL(FS1.Amount,0)AS Amount,
						ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
						ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
						FS1.BatchId,
						ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
						ISNULL(FS1.CollectionGroupId,0) AS CollectionGroupId
					FROM sFee.tFeeSetup FS1
						WHERE FS1.ClassId=@lClassId AND FS1.BatchId = @rBatchId  
						AND ((FS1.CollectionGroupId=@rCollectionGroupId) OR (@rCollectionGroupId=0))
						AND FS1.AdmissionCategoryId=@lAdmissionCategoryId AND IsOptional=0
				
					UNION ALL
				
					SELECT 
						FS1.FeeId,
						FS1.Id,
						ISNULL(FS1.IsOptional,0)AS IsOptional,
						ISNULL(FS1.IsVariable,0)AS IsVariable,
						ISNULL(FS1.Amount,0)AS Amount,
						ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
						ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
						FS1.BatchId,
						ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
						ISNULL(FS1.CollectionGroupId,0) AS CollectionGroupId
					FROM sFee.tFeeSetup FS1
				INNER JOIN sFee.tFeeOptional FO
					ON FO.FeeSetupId=FS1.Id AND (FO.SourceId=@rSourceId) AND ((FO.SourceTypeId=@rSourceTypeId) OR (@rSourceTypeId=0))
				WHERE
						FS1.ClassId=@lClassId AND FS1.BatchId =@rBatchId AND FS1.AdmissionCategoryId=@lAdmissionCategoryId AND IsOptional=1
						AND ((FS1.CollectionGroupId=@rCollectionGroupId) OR (@rCollectionGroupId=0))
				
				) 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 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 ((FSR.CollectionGroupId=@rCollectionGroupId) OR (@rCollectionGroupId=0))
					AND R.SourceId= @rSourceId
					AND ((R.SourceTypeId=@rSourceTypeId) OR (@rSourceTypeId=0))
					AND R.IsObsolete = 0 			 
					 GROUP BY FeeSetupId
		
				) R ON R.FeeSetupId = FS.Id 
				LEFT JOIN sFee.tFeeAllocation FA
					ON FA.FeeSetupId=FS.Id AND 
					(FA.SourceId=@rSourceId) AND ((FA.SourceTypeId=@rSourceTypeId) OR (@rSourceTypeId=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(@rReceiptId=0) OR(@rReceiptId<>0))
				AND(FS.BatchId=@rBatchId)
				AND CGM.IsObsolete = 0
		  ) AS CG
		GROUP BY CollectionGroupId,StartDate,EndDate,CollectionGroupName,CollectionGroupCode,OrderIndex,ReceiptBookId,ReceiptBook
		ORDER BY CG.StartDate,CG.OrderIndex
	END
END
GO
PRINT N'Altering Procedure [sFee].[pFeeSetupFeeWiseRemove]...';


GO
ALTER PROCEDURE [sFee].[pFeeSetupFeeWiseRemove]

	 @rId int,
	 @rFeeId 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 
		-- Removed for mantis : 0028005 By Foram
		--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 FeeId=@rFeeId 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].[pPendingFeeDashboardGet]...';


GO
ALTER PROCEDURE [sFee].[pPendingFeeDashboardGet]

		@rOrgGroupBatchId int = 0,
		@rCommonOrgGroupBatchId int = 0,
		@rType int,
		@rFilterType nvarchar(Max),
		@rFeeType nvarchar(Max),
		@rStudentStatus int = 0,
		@rUptoDate date = '',
		@rDepartmentId int=0,
	    @rOrgId int,
		@rReceiptBookId int,
		@rOrgGroupId int = 0

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

SELECT @rOrgGroupBatchId = Id FROM sSetup.tOrgGroupBatchMaster WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND OrgGroupId = @rOrgGroupId

IF (@rType = 1)
 BEGIN
IF(@rFilterType = 'Organizationwise')		
	BEGIN 
	 IF(@rFeeType = 'FeeHeadwise')
	 BEGIN
		--SELECT
		--	SA.OrgId,
		--	O.Title AS OrgName,
		--	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,
		--	FHM.Id AS FeeHeadId,
		--	FHM.Title AS FeeHeadName,
		--	FHM.OrderIndex
		--FROM
		--	sStudent.vStudentAcademic SA
		--	INNER JOIN sSetup.tOrganizationMaster O ON SA.OrgId = O.Id
		--	INNER JOIN 
		--	(
		--		SELECT 
		--			ISNULL(FS1.Amount,0)AS Amount,
		--			FM.Title AS FeeName,
		--			FM.FeeHeadId,
		--			SA1.Id As AcademicId,
		--			FS1.Id,
		--			FS1.StartDate
 	--			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 sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
		--		WHERE 
		--			BM.OrgGroupBatchId = @rOrgGroupBatchId
		--			AND (FS1.IsOptional=0)
		--			-- IsInContext
		--			AND BM.IsInContext = 1
		--		UNION ALL
		--		SELECT 
		--			ISNULL(FS1.Amount,0)AS Amount,
		--			FM.Title AS FeeName,
		--			FM.FeeHeadId,
		--			SA1.AcademicId As AcademicId,
		--			FS1.Id,
		--			FS1.StartDate
		--		FROM sFee.tFeeSetup FS1
		--		INNER JOIN sFee.tFeeOptional FO ON FO.FeeSetupId=FS1.Id
		--		INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
		--		INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=FO.SourceId 
		--		AND SA1.BatchId = FS1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId AND SA1.ClassId = FS1.ClassId
		--		INNER JOIN sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
		--		WHERE
		--				SA1.OrgGroupBatchId = @rOrgGroupBatchId
		--				AND (FS1.IsOptional=1)
		--				-- IsInContext
		--				AND BM.IsInContext = 1
		--		) FS ON FS.AcademicId=SA.AcademicId
		--		LEFT JOIN sFee.tFeeAllocation FA ON FA.FeeSetupId=FS.Id AND FA.SourceId=SA.AcademicId
		--		LEFT JOIN
		--		(
		--			SELECT 
		--			    ISNULL(SUM(RD.Amount),0) AS PaidAmount,RD.FeeSetupId ,R.SourceId
		--			FROM
		--				sFee.tReceipt R 
		--				INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id 
		--				INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id
		--				INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id
		--				INNER JOIN sStudent.tAcademic SA1 ON SA1.Id=R.SourceId
		--				INNER JOIN sSetup.tBatchMaster BM ON BM.Id=SA1.BatchId			
		--			WHERE		
		--				(R.SourceTypeId = 2001)
		--				AND (R.IsObsolete = 0) 
		--				AND ((BM.OrgGroupBatchId = @rOrgGroupBatchId))
		--				AND (R.OrgGroupBatchId = @rOrgGroupBatchId)
		--				AND (R.ReceiptDate <= @rUptoDate) 
		--				-- IsInContext
		--				AND BM.IsInContext = 1 
		--				GROUP BY FeeSetupId,R.SourceId
		--		) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
		--		INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id = FS.FeeHeadId	
		--		INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId
		--	WHERE
		--	  SA.OrgGroupBatchId = @rOrgGroupBatchId
		--	  AND (SA.StatusId = @rStudentStatus OR @rStudentStatus=0)
		--	  AND ((FS.StartDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
		--	  -- IsInContext
		--	  AND BM.IsInContext = 1
		--	GROUP BY SA.OrgId,O.Title,FHM.Id,FHM.Title,FHM.OrderIndex
		--	ORDER BY OrgId,FHM.OrderIndex

		CREATE TABLE #FeeHeadwisetmp
		(
		Amount decimal (12,2),
		FeeName nvarchar(100),
		FeeHeadId int,
		AcademicId bigint,
		Id int,
		StartDate date
		--ReceiptBookId int 
		)

		INSERT INTO #FeeHeadwisetmp
		SELECT 
					ISNULL(FS1.Amount,0)AS Amount,
					FM.Title AS FeeName,
					FM.FeeHeadId,
					SA1.Id As AcademicId,
					FS1.Id,
					FS1.StartDate
 				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 sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
				WHERE 
					BM.OrgGroupBatchId = @rOrgGroupBatchId
					AND (FS1.IsOptional=0)
					-- IsInContext
					AND BM.IsInContext = 1
				UNION ALL
				SELECT 
					ISNULL(FS1.Amount,0)AS Amount,
					FM.Title AS FeeName,
					FM.FeeHeadId,
					SA1.AcademicId As AcademicId,
					FS1.Id,
					FS1.StartDate
				FROM sFee.tFeeSetup FS1
				INNER JOIN sFee.tFeeOptional FO ON FO.FeeSetupId=FS1.Id
				INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
				INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=FO.SourceId 
				AND SA1.BatchId = FS1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId AND SA1.ClassId = FS1.ClassId
				INNER JOIN sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
				WHERE
						SA1.OrgGroupBatchId = @rOrgGroupBatchId
						AND (FS1.IsOptional=1)
						-- IsInContext
						AND BM.IsInContext = 1

		SELECT
			SA.OrgId,
			O.Title AS OrgName,
			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,
			FHM.Id AS FeeHeadId,
			FHM.Title AS FeeHeadName,
			FHM.OrderIndex,
			ISNULL(O.OrderIndex,0) AS TypeOrderIndex
		FROM
			sStudent.vStudentAcademic SA
			INNER JOIN sSetup.tOrganizationMaster O ON SA.OrgId = O.Id
			INNER JOIN #FeeHeadwisetmp 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.tAcademic SA1 ON SA1.Id=R.SourceId
					INNER JOIN sSetup.tBatchMaster BM ON BM.Id=SA1.BatchId			
				WHERE		
					(R.SourceTypeId = 2001)
					AND (R.IsObsolete = 0) 
					AND ((BM.OrgGroupBatchId = @rOrgGroupBatchId))
					AND (R.OrgGroupBatchId = @rOrgGroupBatchId)
					AND (R.ReceiptDate <= @rUptoDate) 
					-- IsInContext
					AND BM.IsInContext = 1 
					GROUP BY FeeSetupId,R.SourceId
			) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
			INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id = FS.FeeHeadId	
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId
			WHERE
			  SA.OrgGroupBatchId = @rOrgGroupBatchId
			  AND (SA.StatusId = @rStudentStatus OR @rStudentStatus=0)
			  AND ((FS.StartDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
			  -- IsInContext
			  AND BM.IsInContext = 1
			GROUP BY SA.OrgId,O.Title,FHM.Id,FHM.Title,FHM.OrderIndex,O.OrderIndex
			ORDER BY O.OrderIndex,OrgId,FHM.OrderIndex

		DROP TABLE #FeeHeadwisetmp
	 END
	 ELSE IF(@rFeeType = 'FeeMasterwise')
	 BEGIN
		CREATE TABLE #FeeMasterwisetmp
		(
			FeeId int,
			Amount decimal (12,2),
			FeeName nvarchar(100),
			FeeHeadId int,
			AcademicId bigint,
			Id int,
			StartDate date,
			OrderIndex int
		)
	 
	 INSERT INTO #FeeMasterwisetmp
		 SELECT 
			FS1.FeeId,
			ISNULL(FS1.Amount,0)AS Amount,
			FM.Title AS FeeName,
			FM.FeeHeadId,
			SA1.Id As AcademicId,
			FS1.Id,
			FS1.StartDate,
			FM.OrderIndex
 		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 sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
		WHERE 
			BM.OrgGroupBatchId = @rOrgGroupBatchId
			AND (FS1.IsOptional=0)
			-- IsInContext
			AND BM.IsInContext = 1
		UNION ALL
		SELECT 
			FS1.FeeId,
			ISNULL(FS1.Amount,0)AS Amount,
			FM.Title AS FeeName,
			FM.FeeHeadId,
			SA1.AcademicId As AcademicId,
			FS1.Id,
			FS1.StartDate,
			FM.OrderIndex
		FROM sFee.tFeeSetup FS1
		INNER JOIN sFee.tFeeOptional FO ON FO.FeeSetupId=FS1.Id
		INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
		INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=FO.SourceId 
		AND SA1.BatchId = FS1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId AND SA1.ClassId = FS1.ClassId
		INNER JOIN sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
		WHERE
				SA1.OrgGroupBatchId = @rOrgGroupBatchId
				AND (FS1.IsOptional=1)
				-- IsInContext
				AND BM.IsInContext = 1

	 SELECT
			SA.OrgId,
			O.Title AS OrgName,
			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,
			FS.FeeId,
			FS.FeeName,
			FS.OrderIndex,
			ISNULL(O.OrderIndex,0) AS TypeOrderIndex
		FROM
			sStudent.vStudentAcademic SA
				INNER JOIN sSetup.tOrganizationMaster O ON SA.OrgId = O.Id
				INNER JOIN #FeeMasterwisetmp 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.tAcademic SA1 ON SA1.Id=R.SourceId
						INNER JOIN sSetup.tBatchMaster BM ON BM.Id=SA1.BatchId			
					WHERE		
						(R.SourceTypeId = 2001)
						AND (R.IsObsolete = 0) 
						AND ((BM.OrgGroupBatchId = @rOrgGroupBatchId))
						AND (R.OrgGroupBatchId = @rOrgGroupBatchId)
						AND (R.ReceiptDate <= @rUptoDate) 
						-- IsInContext
						AND BM.IsInContext = 1 
						GROUP BY FeeSetupId,R.SourceId
				) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
				INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id = FS.FeeHeadId	
				INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId
			WHERE
				SA.OrgGroupBatchId = @rOrgGroupBatchId
				AND (SA.StatusId = @rStudentStatus OR @rStudentStatus=0)
				AND ((FS.StartDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
				-- IsInContext
				AND BM.IsInContext = 1
			GROUP BY SA.OrgId,O.Title,FS.FeeId,FS.FeeName,FS.OrderIndex,O.OrderIndex
			ORDER BY O.OrderIndex,OrgId,FS.FeeId
	 DROP TABLE #FeeMasterwisetmp
	 END
	 ELSE IF(@rFeeType = 'CollectionGroupwise')
	 BEGIN
		CREATE TABLE #CollectionGroupwisetmp
		(
			FeeId int,
			Amount decimal (12,2),
			FeeName nvarchar(100),
			FeeHeadId int,
			AcademicId bigint,
			Id int,
			StartDate date,
			CollectionGroupId int
		)
	 INSERT INTO #CollectionGroupwisetmp
	 SELECT 
			FS1.FeeId,
			ISNULL(FS1.Amount,0)AS Amount,
			FM.Title AS FeeName,
			FM.FeeHeadId,
			SA1.Id As AcademicId,
			FS1.Id,
			FS1.StartDate,
			FS1.CollectionGroupId
 		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 sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
		WHERE 
			BM.OrgGroupBatchId = @rOrgGroupBatchId
			AND (FS1.IsOptional=0)
			-- IsInContext
			AND BM.IsInContext = 1
		UNION ALL
		SELECT 
			FS1.FeeId,
			ISNULL(FS1.Amount,0)AS Amount,
			FM.Title AS FeeName,
			FM.FeeHeadId,
			SA1.AcademicId As AcademicId,
			FS1.Id,
			FS1.StartDate,
			FS1.CollectionGroupId
		FROM sFee.tFeeSetup FS1
		INNER JOIN sFee.tFeeOptional FO ON FO.FeeSetupId=FS1.Id
		INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
		INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=FO.SourceId 
		AND SA1.BatchId = FS1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId AND SA1.ClassId = FS1.ClassId
		INNER JOIN sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
		WHERE
				SA1.OrgGroupBatchId = @rOrgGroupBatchId
				AND (FS1.IsOptional=1)
				-- IsInContext
				AND BM.IsInContext = 1

	 SELECT
			SA.OrgId,
			O.Title AS OrgName,
			SUM(ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00))AS PendingAmount,
			ISNULL(CGM.Id,0) AS CollectionGroupId,
			ISNULL(CGM.Title,'') AS CollectionGroupName,
			ISNULL(CGM.OrderIndex,0) AS OrderIndex,
			ISNULL(O.OrderIndex,0) AS TypeOrderIndex
		FROM
			sStudent.vStudentAcademic SA
			INNER JOIN sSetup.tOrganizationMaster O ON SA.OrgId = O.Id
			INNER JOIN #CollectionGroupwisetmp 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.tAcademic SA1 ON SA1.Id=R.SourceId
						INNER JOIN sSetup.tBatchMaster BM ON BM.Id=SA1.BatchId			
					WHERE		
						(R.SourceTypeId = 2001)
						AND (R.IsObsolete = 0) 
						AND ((BM.OrgGroupBatchId = @rOrgGroupBatchId))
						AND (R.OrgGroupBatchId = @rOrgGroupBatchId)
						AND (R.ReceiptDate <= @rUptoDate) 
						-- IsInContext
						AND BM.IsInContext = 1 
						GROUP BY FeeSetupId,R.SourceId
				) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
				LEFT JOIN sFee.tCollectionGroupMaster CGM ON FS.CollectionGroupId=CGM.Id
				INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId
			WHERE
			  SA.OrgGroupBatchId = @rOrgGroupBatchId
			  AND (SA.StatusId = @rStudentStatus OR @rStudentStatus=0)
			  AND ((FS.StartDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
			  -- IsInContext
			  AND BM.IsInContext = 1
			GROUP BY SA.OrgId,O.Title,CGM.Id,CGM.Title,CGM.OrderIndex,O.OrderIndex
			ORDER BY O.OrderIndex,OrgId,CGM.Id

	 DROP TABLE #CollectionGroupwisetmp
	 END
	END
ELSE IF(@rFilterType = 'Departmentwise')
	BEGIN
	 IF(@rFeeType = 'FeeHeadwise')
	 BEGIN
		IF OBJECT_ID('tempdb..#tmpDepartFeeHeadWise') IS NOT NULL DROP TABLE #tmpDepartFeeHeadWise
		CREATE TABLE #tmpDepartFeeHeadWise
		(
		Amount decimal (12,2),
		FeeName nvarchar(100),
		FeeHeadId int,
		AcademicId bigint,
		Id int,
		StartDate date
		)

		Insert Into #tmpDepartFeeHeadWise
		SELECT 
					ISNULL(FS1.Amount,0)AS Amount,
					FM.Title AS FeeName,
					FM.FeeHeadId,
					SA1.Id As AcademicId,
					FS1.Id,
					FS1.StartDate
 				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 sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
				WHERE 
					BM.OrgGroupBatchId = @rOrgGroupBatchId
					AND (FS1.IsOptional=0)
					-- IsInContext
					AND BM.IsInContext = 1
				UNION ALL
				SELECT 
					ISNULL(FS1.Amount,0)AS Amount,
					FM.Title AS FeeName,
					FM.FeeHeadId,
					SA1.AcademicId As AcademicId,
					FS1.Id,
					FS1.StartDate
				FROM sFee.tFeeSetup FS1
				INNER JOIN sFee.tFeeOptional FO ON FO.FeeSetupId=FS1.Id
				INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
				INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=FO.SourceId 
				AND SA1.BatchId = FS1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId AND SA1.ClassId = FS1.ClassId
				INNER JOIN sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
				WHERE
						SA1.OrgGroupBatchId = @rOrgGroupBatchId
						AND (FS1.IsOptional=1)
						-- IsInContext
						AND BM.IsInContext = 1

		SELECT
			SA.DepartmentId,
		    SA.DepartmentName,
			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,
			FHM.Id AS FeeHeadId,
			FHM.Title AS FeeHeadName,
			FHM.OrderIndex,
			ISNULL(DM.OrderIndex,0) AS TypeOrderIndex
		FROM
			sStudent.vStudentAcademic SA
		INNER JOIN sSetup.tOrganizationMaster O ON SA.OrgId = O.Id
		INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id = SA.DepartmentId
		INNER JOIN #tmpDepartFeeHeadWise 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.tAcademic SA1 ON SA1.Id=R.SourceId
				INNER JOIN sSetup.tBatchMaster BM ON BM.Id=SA1.BatchId			
			WHERE		
				(R.SourceTypeId = 2001)
				AND (R.IsObsolete = 0) 
				AND ((BM.OrgGroupBatchId = @rOrgGroupBatchId))
				AND (R.OrgGroupBatchId = @rOrgGroupBatchId)
				AND (R.ReceiptDate <= @rUptoDate)
				-- IsInContext
				AND BM.IsInContext = 1  
				GROUP BY FeeSetupId,R.SourceId
		) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
		INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id = FS.FeeHeadId	
		INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId
		WHERE
			  SA.OrgGroupBatchId = @rOrgGroupBatchId
			  AND (SA.StatusId = @rStudentStatus OR @rStudentStatus=0)
			  AND ((FS.StartDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
			  -- IsInContext
			  AND BM.IsInContext = 1 
		GROUP BY SA.DepartmentId,SA.DepartmentName,FHM.Id,FHM.Title,FHM.OrderIndex,DM.OrderIndex
		ORDER BY DM.OrderIndex,DepartmentId,FHM.Id
	 END
	 ELSE IF(@rFeeType = 'FeeMasterwise')
	 BEGIN

		IF OBJECT_ID('tempdb..#tmpDepartFeeMasterwise') IS NOT NULL DROP TABLE #tmpDepartFeeMasterwise
		CREATE TABLE #tmpDepartFeeMasterwise
		(
		FeeId int,
		Amount decimal (12,2),
		FeeName nvarchar(100),
		FeeHeadId int,
		AcademicId bigint,
		Id int,
		StartDate date,
		OrderIndex int
		)

		Insert Into #tmpDepartFeeMasterwise
		SELECT 
					FS1.FeeId,
					ISNULL(FS1.Amount,0)AS Amount,
					FM.Title AS FeeName,
					FM.FeeHeadId,
					SA1.Id As AcademicId,
					FS1.Id,
					FS1.StartDate,
					FM.OrderIndex
 				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 sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
				WHERE 
					BM.OrgGroupBatchId = @rOrgGroupBatchId
					AND (FS1.IsOptional=0)
					-- IsInContext
					AND BM.IsInContext = 1
				UNION ALL
				SELECT 
					FS1.FeeId,
					ISNULL(FS1.Amount,0)AS Amount,
					FM.Title AS FeeName,
					FM.FeeHeadId,
					SA1.AcademicId As AcademicId,
					FS1.Id,
					FS1.StartDate,
					FM.OrderIndex
				FROM sFee.tFeeSetup FS1
				INNER JOIN sFee.tFeeOptional FO ON FO.FeeSetupId=FS1.Id
				INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
				INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=FO.SourceId 
				AND SA1.BatchId = FS1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId AND SA1.ClassId = FS1.ClassId
				INNER JOIN sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
				WHERE
						SA1.OrgGroupBatchId = @rOrgGroupBatchId
						AND (FS1.IsOptional=1)
						-- IsInContext
						AND BM.IsInContext = 1


		SELECT
			SA.DepartmentId,
		    SA.DepartmentName,
			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,
			FS.FeeId,
			FS.FeeName,
			FS.OrderIndex,
			ISNULL(DM.OrderIndex,0) AS TypeOrderIndex
		FROM
			sStudent.vStudentAcademic SA
				INNER JOIN sSetup.tOrganizationMaster O ON SA.OrgId = O.Id
				INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id = SA.DepartmentId
				INNER JOIN #tmpDepartFeeMasterwise 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.tAcademic SA1 ON SA1.Id=R.SourceId
						INNER JOIN sSetup.tBatchMaster BM ON BM.Id=SA1.BatchId			
					WHERE		
						(R.SourceTypeId = 2001)
						AND (R.IsObsolete = 0) 
						AND ((BM.OrgGroupBatchId = @rOrgGroupBatchId))
						AND (R.OrgGroupBatchId = @rOrgGroupBatchId)
						AND (R.ReceiptDate <= @rUptoDate)  
						-- IsInContext
						AND BM.IsInContext = 1
						GROUP BY FeeSetupId,R.SourceId
				) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
				INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id = FS.FeeHeadId	
				INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId
			WHERE
			  SA.OrgGroupBatchId = @rOrgGroupBatchId
			  AND (SA.StatusId = @rStudentStatus OR @rStudentStatus=0)
			  AND ((FS.StartDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
			  -- IsInContext
			  AND BM.IsInContext = 1
			GROUP BY SA.DepartmentId,SA.DepartmentName,FS.FeeId,FS.FeeName,FS.OrderIndex,DM.OrderIndex
			ORDER BY DM.OrderIndex,DepartmentId,FS.FeeId
	 END
	 ELSE IF(@rFeeType = 'CollectionGroupwise')
	 BEGIN
		IF OBJECT_ID('tempdb..#tmpDepartCollectionGroupwise') IS NOT NULL DROP TABLE #tmpDepartCollectionGroupwise
		CREATE TABLE #tmpDepartCollectionGroupwise
		(
		FeeId int,
		Amount decimal (12,2),
		FeeName nvarchar(100),
		FeeHeadId int,
		AcademicId bigint,
		Id int,
		StartDate date,
		CollectionGroupId int
		)

		INSERT INTO #tmpDepartCollectionGroupwise
		SELECT 
					FS1.FeeId,
					ISNULL(FS1.Amount,0)AS Amount,
					FM.Title AS FeeName,
					FM.FeeHeadId,
					SA1.Id As AcademicId,
					FS1.Id,
					FS1.StartDate,
					FS1.CollectionGroupId
 				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 sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
				WHERE 
					BM.OrgGroupBatchId = @rOrgGroupBatchId
					AND (FS1.IsOptional=0)
					-- IsInContext
					AND BM.IsInContext = 1
				UNION ALL
				SELECT 
					FS1.FeeId,
					ISNULL(FS1.Amount,0)AS Amount,
					FM.Title AS FeeName,
					FM.FeeHeadId,
					SA1.AcademicId As AcademicId,
					FS1.Id,
					FS1.StartDate,
					FS1.CollectionGroupId
				FROM sFee.tFeeSetup FS1
				INNER JOIN sFee.tFeeOptional FO ON FO.FeeSetupId=FS1.Id
				INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
				INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=FO.SourceId 
				AND SA1.BatchId = FS1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId AND SA1.ClassId = FS1.ClassId
				INNER JOIN sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
				WHERE
						SA1.OrgGroupBatchId = @rOrgGroupBatchId
						AND (FS1.IsOptional=1)
						-- IsInContext
						AND BM.IsInContext = 1


		SELECT
			SA.DepartmentId,
		    SA.DepartmentName,
			SUM(ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00))AS PendingAmount,
			ISNULL(CGM.Id,0) AS CollectionGroupId,
			ISNULL(CGM.Title,'') AS CollectionGroupName,
			ISNULL(CGM.OrderIndex,0) AS OrderIndex,
			ISNULL(DM.OrderIndex,0) AS TypeOrderIndex
		FROM
			sStudent.vStudentAcademic SA
				INNER JOIN sSetup.tOrganizationMaster O ON SA.OrgId = O.Id
				INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id = SA.DepartmentId
				INNER JOIN #tmpDepartCollectionGroupwise 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.tAcademic SA1 ON SA1.Id=R.SourceId
						INNER JOIN sSetup.tBatchMaster BM ON BM.Id=SA1.BatchId			
					WHERE		
						(R.SourceTypeId = 2001)
						AND (R.IsObsolete = 0) 
						AND ((BM.OrgGroupBatchId = @rOrgGroupBatchId))
						AND (R.OrgGroupBatchId = @rOrgGroupBatchId)
						AND (R.ReceiptDate <= @rUptoDate)  
						-- IsInContext
						AND BM.IsInContext = 1
						GROUP BY FeeSetupId,R.SourceId
				) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
				LEFT JOIN sFee.tCollectionGroupMaster CGM ON FS.CollectionGroupId=CGM.Id
				INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId
			WHERE
			  SA.OrgGroupBatchId = @rOrgGroupBatchId
			  AND (SA.StatusId = @rStudentStatus OR @rStudentStatus=0)
			  AND ((FS.StartDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
			  -- IsInContext
			  AND BM.IsInContext = 1
			GROUP BY SA.DepartmentId,SA.DepartmentName,CGM.Id,CGM.Title,CGM.OrderIndex,DM.OrderIndex
			ORDER BY DM.OrderIndex,DepartmentId,CGM.Id
	 END
	END
ELSE IF(@rFilterType = 'ReceiptBookwise')
	BEGIN
	IF(@rFeeType = 'FeeHeadwise')
	BEGIN
		-- For Timeout issue
		CREATE TABLE #tmp
		(
		Amount decimal (12,2),
		FeeName nvarchar(100),
		FeeHeadId int,
		AcademicId bigint,
		Id int,
		StartDate date,
		ReceiptBookId int 
		)

		INSERT INTO #tmp
		SELECT 
			ISNULL(FS1.Amount,0)AS Amount,
			FM.Title AS FeeName,
			FM.FeeHeadId,
			SA1.Id As AcademicId,
			FS1.Id,
			FS1.StartDate,
			FS1.ReceiptBookId
 		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 sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
		WHERE 
			BM.OrgGroupBatchId = @rOrgGroupBatchId
			AND (FS1.IsOptional=0)
			-- IsInContext
			AND BM.IsInContext = 1
		UNION ALL
		SELECT 
			ISNULL(FS1.Amount,0)AS Amount,
			FM.Title AS FeeName,
			FM.FeeHeadId,
			SA1.AcademicId As AcademicId,
			FS1.Id,
			FS1.StartDate,
			FS1.ReceiptBookId
		FROM sFee.tFeeSetup FS1
		INNER JOIN sFee.tFeeOptional FO ON FO.FeeSetupId=FS1.Id
		INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
		INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=FO.SourceId 
		AND SA1.BatchId = FS1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId AND SA1.ClassId = FS1.ClassId
		INNER JOIN sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
		WHERE
				SA1.OrgGroupBatchId = @rOrgGroupBatchId
				AND (FS1.IsOptional=1)
				-- IsInContext
				AND BM.IsInContext = 1



	 SELECT
			FS.ReceiptBookId,
		    ISNULL(RBM.Title,'') AS ReceiptBookTitle,
			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,
			FHM.Id AS FeeHeadId,
			FHM.Title AS FeeHeadName,
			FHM.OrderIndex,
			ISNULL(RBM.OrderIndex,0) AS TypeOrderIndex
		FROM
			sStudent.tAcademic SA
			INNER JOIN [sStudent].[tStudentMaster] SM ON SA.StudentId = SM.Id 
			INNER JOIN [sSetup].[tBatchMaster] BM ON SA.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster O ON SA.OrgId = O.Id
			--INNER JOIN 
			--(
				--SELECT 
				--	ISNULL(FS1.Amount,0)AS Amount,
				--	FM.Title AS FeeName,
				--	FM.FeeHeadId,
				--	SA1.Id As AcademicId,
				--	FS1.Id,
				--	FS1.StartDate,
				--	FS1.ReceiptBookId
 			--	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 sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
				--WHERE 
				--	BM.OrgGroupBatchId = @rOrgGroupBatchId
				--	AND (FS1.IsOptional=0)
				--	-- IsInContext
				--	AND BM.IsInContext = 1
				--UNION ALL
				--SELECT 
				--	ISNULL(FS1.Amount,0)AS Amount,
				--	FM.Title AS FeeName,
				--	FM.FeeHeadId,
				--	SA1.AcademicId As AcademicId,
				--	FS1.Id,
				--	FS1.StartDate,
				--	FS1.ReceiptBookId
				--FROM sFee.tFeeSetup FS1
				--INNER JOIN sFee.tFeeOptional FO ON FO.FeeSetupId=FS1.Id
				--INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
				--INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=FO.SourceId 
				--AND SA1.BatchId = FS1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId AND SA1.ClassId = FS1.ClassId
				--INNER JOIN sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
				--WHERE
				--		SA1.OrgGroupBatchId = @rOrgGroupBatchId
				--		AND (FS1.IsOptional=1)
				--		-- IsInContext
				--		AND BM.IsInContext = 1
				--) 
				INNER JOIN #tmp FS ON FS.AcademicId=SA.Id
				LEFT JOIN sFee.tFeeAllocation FA ON FA.FeeSetupId=FS.Id AND FA.SourceId=SA.Id
				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.tAcademic SA1 ON SA1.Id=R.SourceId
						INNER JOIN sSetup.tBatchMaster BM ON BM.Id=SA1.BatchId			
					WHERE		
						(R.SourceTypeId = 2001)
						AND (R.IsObsolete = 0) 
						AND ((BM.OrgGroupBatchId = @rOrgGroupBatchId))
						AND (R.OrgGroupBatchId = @rOrgGroupBatchId)
						AND (R.ReceiptDate <= @rUptoDate)  
						-- IsInContext
						AND BM.IsInContext = 1
						GROUP BY FeeSetupId,R.SourceId
				) R ON R.FeeSetupId = FS.Id AND SA.Id = R.SourceId
				INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id = FS.FeeHeadId	
				INNER JOIN sFee.tReceiptBookMaster RBM ON FS.ReceiptBookId=RBM.Id
			WHERE
			  BM.OrgGroupBatchId = @rOrgGroupBatchId
			  AND (SM.StatusId = @rStudentStatus OR @rStudentStatus=0)
			  AND ((FS.StartDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
			  -- IsInContext
			  AND BM.IsInContext = 1
			GROUP BY FS.ReceiptBookId,RBM.Title,FHM.Id,FHM.Title,FHM.OrderIndex,RBM.OrderIndex
			ORDER BY RBM.OrderIndex,ReceiptBookId,FHM.Id

		DROP TABLE #tmp
	 END
	ELSE IF(@rFeeType = 'FeeMasterwise')
	BEGIN

		IF OBJECT_ID('tempdb..#tmpReceiptFeeMasterwise') IS NOT NULL DROP TABLE #tmpReceiptFeeMasterwise
		CREATE TABLE #tmpReceiptFeeMasterwise
		(
		FeeId int,
		Amount decimal (12,2),
		FeeName nvarchar(100),
		FeeHeadId int,
		AcademicId bigint,
		Id int,
		StartDate date,
		ReceiptBookId int,
		OrderIndex int
		)

		INSERT INTO  #tmpReceiptFeeMasterwise
		SELECT 
					FS1.FeeId,
					ISNULL(FS1.Amount,0)AS Amount,
					FM.Title AS FeeName,
					FM.FeeHeadId,
					SA1.Id As AcademicId,
					FS1.Id,
					FS1.StartDate,
					FS1.ReceiptBookId,
					FM.OrderIndex
 				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 sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
				WHERE 
					BM.OrgGroupBatchId = @rOrgGroupBatchId
					AND (FS1.IsOptional=0)
					-- IsInContext
					AND BM.IsInContext = 1
				UNION ALL
				SELECT 
					FS1.FeeId,
					ISNULL(FS1.Amount,0)AS Amount,
					FM.Title AS FeeName,
					FM.FeeHeadId,
					SA1.AcademicId As AcademicId,
					FS1.Id,
					FS1.StartDate,
					FS1.ReceiptBookId,
					FM.OrderIndex
				FROM sFee.tFeeSetup FS1
				INNER JOIN sFee.tFeeOptional FO ON FO.FeeSetupId=FS1.Id
				INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
				INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=FO.SourceId 
				AND SA1.BatchId = FS1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId AND SA1.ClassId = FS1.ClassId
				INNER JOIN sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
				WHERE
						SA1.OrgGroupBatchId = @rOrgGroupBatchId
						AND (FS1.IsOptional=1)
						-- IsInContext
						AND BM.IsInContext = 1

		SELECT
			FS.ReceiptBookId,
		    ISNULL(RBM.Title,'') AS ReceiptBookTitle,
			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,
			FS.FeeId,
			FS.FeeName,
			FS.OrderIndex,
			ISNULL(RBM.OrderIndex,0) AS TypeOrderIndex
		FROM
			sStudent.vStudentAcademic SA
				INNER JOIN sSetup.tOrganizationMaster O ON SA.OrgId = O.Id
				INNER JOIN #tmpReceiptFeeMasterwise 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.tAcademic SA1 ON SA1.Id=R.SourceId
						INNER JOIN sSetup.tBatchMaster BM ON BM.Id=SA1.BatchId			
					WHERE		
						(R.SourceTypeId = 2001)
						AND (R.IsObsolete = 0) 
						AND ((BM.OrgGroupBatchId = @rOrgGroupBatchId))
						AND (R.OrgGroupBatchId = @rOrgGroupBatchId)
						AND (R.ReceiptDate <= @rUptoDate) 
						-- IsInContext
						AND BM.IsInContext = 1 
						GROUP BY FeeSetupId,R.SourceId
				) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
				INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id = FS.FeeHeadId	
				INNER JOIN sFee.tReceiptBookMaster RBM ON FS.ReceiptBookId=RBM.Id
				INNER JOIN sSetup.tBatchMaster BM ON SA.BatchId = BM.Id
			WHERE
			  SA.OrgGroupBatchId = @rOrgGroupBatchId
			  AND (SA.StatusId = @rStudentStatus OR @rStudentStatus=0)
			  AND ((FS.StartDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
			  -- IsInContext
			  AND BM.IsInContext = 1
			GROUP BY FS.ReceiptBookId,RBM.Title,FS.FeeId,FS.FeeName,FS.OrderIndex,RBM.OrderIndex
			ORDER BY RBM.OrderIndex,ReceiptBookId,FS.FeeId
	END
	ELSE IF(@rFeeType = 'CollectionGroupwise')
	BEGIN

		IF OBJECT_ID('tempdb..#tmpReceiptCollectionGroupwise') IS NOT NULL DROP TABLE #tmpReceiptCollectionGroupwise
		CREATE TABLE #tmpReceiptCollectionGroupwise
		(
		FeeId int,
		Amount decimal (12,2),
		FeeName nvarchar(100),
		FeeHeadId int,
		AcademicId bigint,
		Id int,
		StartDate date,
		CollectionGroupId int,
		ReceiptBookId int
		)

		INSERT INTO #tmpReceiptCollectionGroupwise
		SELECT 
					FS1.FeeId,
					ISNULL(FS1.Amount,0)AS Amount,
					FM.Title AS FeeName,
					FM.FeeHeadId,
					SA1.Id As AcademicId,
					FS1.Id,
					FS1.StartDate,
					FS1.CollectionGroupId,
					FS1.ReceiptBookId
 				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 sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
				WHERE 
					BM.OrgGroupBatchId = @rOrgGroupBatchId
					AND (FS1.IsOptional=0)
					-- IsInContext
					AND BM.IsInContext = 1
				UNION ALL
				SELECT 
					FS1.FeeId,
					ISNULL(FS1.Amount,0)AS Amount,
					FM.Title AS FeeName,
					FM.FeeHeadId,
					SA1.AcademicId As AcademicId,
					FS1.Id,
					FS1.StartDate,
					FS1.CollectionGroupId,
					FS1.ReceiptBookId
				FROM sFee.tFeeSetup FS1
				INNER JOIN sFee.tFeeOptional FO ON FO.FeeSetupId=FS1.Id
				INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
				INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=FO.SourceId 
				AND SA1.BatchId = FS1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId AND SA1.ClassId = FS1.ClassId
				INNER JOIN sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
				WHERE
						SA1.OrgGroupBatchId = @rOrgGroupBatchId
						AND (FS1.IsOptional=1)
						-- IsInContext
						AND BM.IsInContext = 1

		SELECT
			FS.ReceiptBookId,
		    ISNULL(RBM.Title,'') AS ReceiptBookTitle,
			SUM(ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00))AS PendingAmount,
			ISNULL(CGM.Id,0) AS CollectionGroupId,
			ISNULL(CGM.Title,'') AS CollectionGroupName,
			ISNULL(CGM.OrderIndex,0) AS OrderIndex,
			ISNULL(RBM.OrderIndex,0) AS TypeOrderIndex
		FROM
			sStudent.vStudentAcademic SA
				INNER JOIN sSetup.tOrganizationMaster O ON SA.OrgId = O.Id
				INNER JOIN #tmpReceiptCollectionGroupwise 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.tAcademic SA1 ON SA1.Id=R.SourceId
						INNER JOIN sSetup.tBatchMaster BM ON BM.Id=SA1.BatchId			
					WHERE		
						(R.SourceTypeId = 2001)
						AND (R.IsObsolete = 0) 
						AND ((BM.OrgGroupBatchId = @rOrgGroupBatchId))
						AND (R.OrgGroupBatchId = @rOrgGroupBatchId)
						AND (R.ReceiptDate <= @rUptoDate)  
						-- IsInContext
						AND BM.IsInContext = 1
						GROUP BY FeeSetupId,R.SourceId
				) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
				LEFT JOIN sFee.tCollectionGroupMaster CGM ON FS.CollectionGroupId=CGM.Id
				INNER JOIN sFee.tReceiptBookMaster RBM ON FS.ReceiptBookId=RBM.Id
				INNER JOIN sSetup.tBatchMaster BM ON SA.BatchId = BM.Id
			WHERE
			  SA.OrgGroupBatchId = @rOrgGroupBatchId
			  AND (SA.StatusId = @rStudentStatus OR @rStudentStatus=0)
			  AND ((FS.StartDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
			  -- IsInContext
			  AND BM.IsInContext = 1
			GROUP BY FS.ReceiptBookId,RBM.Title,CGM.Id,CGM.Title,CGM.OrderIndex,RBM.OrderIndex
			--ORDER BY ReceiptBookId,CGM.Id
			ORDER BY RBM.OrderIndex,CGM.OrderIndex
	END
	END 
  END
ELSE IF(@rType = 2)
		BEGIN

			IF OBJECT_ID('tempdb..#tmptbl') IS NOT NULL DROP TABLE #tmptbl
			CREATE TABLE #tmptbl
			(
				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,
				FeeOrderIndex int
			)
			INSERT INTO #tmptbl 
			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,
							FS1.CollectionGroupId,
							FM.OrderIndex AS FeeOrderIndex			 
						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 sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
						WHERE 
							BM.OrgGroupBatchId = @rOrgGroupBatchId
							AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
							AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
							AND (FS1.IsOptional=0)
							-- IsInContext
							AND BM.IsInContext = 1
						UNION ALL
				
						SELECT 
							FS1.FeeId,
							FS1.Id,
							ISNULL(FS1.IsOptional,0)AS IsOptional,
							ISNULL(FS1.IsVariable,0)AS IsVariable,
							ISNULL(FS1.Amount,0)AS Amount,
							ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
							ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
							FS1.BatchId,
							ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
							SA1.AcademicId,
							FM.Title AS FeeName,
							FM.FeeHeadId,
							FS1.CollectionGroupId,
							FM.OrderIndex AS FeeOrderIndex			 			 
						FROM sFee.tFeeSetup FS1
						INNER JOIN sFee.tFeeOptional FO ON FO.FeeSetupId=FS1.Id
						INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
						INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=FO.SourceId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
						INNER JOIN sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
						WHERE
							SA1.OrgGroupBatchId = @rOrgGroupBatchId
							AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
							AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
							AND (FS1.IsOptional=1)
							-- IsInContext
							AND BM.IsInContext = 1
	
				SELECT 
					SA.OrgId,
					SA.OrganizationName as OrgName,
					SA.ClassId,
					SA.ClassName,
					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 #tmptbl  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.tAcademic SA1 ON SA1.Id=R.SourceId
							INNER JOIN sSetup.tBatchMaster BM ON BM.Id=SA1.BatchId			
							 
						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
							-- IsInContext
							AND BM.IsInContext = 1
							GROUP BY FeeSetupId,R.SourceId
					) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
					 INNER JOIN sSetup.tOrganizationMaster O ON	
					 SA.OrgId = O.Id
					 INNER JOIN sFee.tReceiptBookMaster RBM 
						ON FS.ReceiptBookId=RBM.Id
					 LEFT JOIN sFee.tCollectionGroupMaster CGM
						ON FS.CollectionGroupId=CGM.Id	
					 LEFT JOIN sStudent.tStudentCommunication SC 
						ON SC.StudentId = SA.StudentId
					 LEFT JOIN sStudent.tStudentOther SO 
						ON SO.StudentId = SA.StudentId
					 INNER JOIN sFee.tFeeHeadMaster FHM
						ON FHM.Id = FS.FeeHeadId
					INNER JOIN sSetup.tBatchMaster BM ON SA.BatchId = BM.Id	
				  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))  
				WHERE	
				 SA.OrgGroupBatchId = @rOrgGroupBatchId
                 AND (SA.StatusId = @rStudentStatus OR @rStudentStatus=0)
                 AND ((FS.StartDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
				 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)			
				 -- IsInContext
				 AND BM.IsInContext = 1
				GROUP BY 
						SA.ClassId,SA.ClassName,SA.OrgId,SA.OrganizationName
				Order By
						SA.ClassId
		END
END
GO
PRINT N'Altering Procedure [sFee].[pReceiptAdd]...';


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

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

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

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

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

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

	IF @rChequeDate = '1900-01-01'
		SET @rChequeDate = NULL
	 
	IF(@rReceiptNumber <> 0)
	BEGIN
		IF(@rId = 0)--ID Condition Added by dhruv for issue no.0013266	
		BEGIN
			IF(@lConfigValue='ReceiptBookWise')
			BEGIN
				IF EXISTS(SELECT 1 from sFee.tReceipt where ReceiptNumber=@rReceiptNumber AND ReceiptBookId=@rReceiptBookId AND OrgGroupBatchId = @rOrgGroupBatchId)
				BEGIN
					SELECT -102 AS Result
					RETURN	
				END
			END
			ELSE IF(@lConfigValue='PayTypeWise')
			BEGIN
				IF EXISTS(SELECT 1 from sFee.tReceipt where ReceiptNumber=@rReceiptNumber AND ReceiptBookId=@rReceiptBookId AND  PayTypeId=@rPayTypeId AND OrgGroupBatchId = @rOrgGroupBatchId)
				BEGIN
					SELECT -102 AS Result
					RETURN	
				END
			END
		END
		ELSE
		BEGIN
			IF(@lConfigValue='ReceiptBookWise')
			BEGIN
				IF EXISTS(SELECT 1 from sFee.tReceipt where ReceiptNumber=@rReceiptNumber AND ReceiptBookId=@rReceiptBookId AND OrgGroupBatchId = @rOrgGroupBatchId AND Id != @rId)
				BEGIN
					SELECT -102 AS Result
					RETURN	
				END
			END
			ELSE IF(@lConfigValue='PayTypeWise')
			BEGIN
				IF EXISTS(SELECT 1 from sFee.tReceipt where ReceiptNumber=@rReceiptNumber AND ReceiptBookId=@rReceiptBookId AND  PayTypeId=@rPayTypeId AND OrgGroupBatchId = @rOrgGroupBatchId AND Id != @rId)
				BEGIN
					SELECT -102 AS Result
					RETURN	
				END
			END
		END 
	END
	ELSE
	BEGIN
		SET @rReceiptNumber = sFee.fReceiptNumberGet(@rReceiptBookId,@rOrgGroupBatchId,@rPayTypeId,@lConfigValue)
		Print @rReceiptNumber
	END	
EXECUTE [sFee].[pReceiptAddValidate] @rSourceId,'',@rReceiptDetailXml,@rIsCreated = @lIsCreated OUTPUT
 	IF(@lIsCreated = 1)
 		BEGIN
			SELECT -501 AS Result
			RETURN
		END
 
	 BEGIN TRANSACTION	
 IF(@rId = 0)	
BEGIN

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

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

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

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

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

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

		BEGIN
		UPDATE sFee.tReceipt SET
			ReceiptNumber = @rReceiptNumber,
			ReceiptDate=@rReceiptDate,
			PayTypeId=@rPayTypeId,
			ChequeDate=@rChequeDate,
		    ChequeNo=@rChequeNo,
		    BankName=@rBankName,
		    Remark=@rRemark
		WHERE Id=@rId
		
	SELECT @rId AS RESULT
	END 
	END
	
		COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
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
			 
 	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
	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
--END
GO
PRINT N'Altering Procedure [sHrm].[pEmployeeReplacementDeleteAndTransfer]...';


GO
ALTER PROCEDURE [sHrm].[pEmployeeReplacementDeleteAndTransfer]
	 
        @rExistingEmployeeId BIGINT,
		@rNewEmployeeId BIGINT,
		@rTitle NVARCHAR(500)
	

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	--IF OBJECT_ID('tempdb..#tmpSplitTable') IS NOT NULL DROP TABLE #tmpSplitTable

	--CREATE Table #tmpSplitTable
	--(
	--	Id NVARCHAR(150)
	--)

	--INSERT INTO #tmpSplitTable
	--SELECT CAST(item AS NVARCHAR(150)) AS Id FROM  sCommon.fnsplit(@rId,',')
	
	IF (@rTitle = 'Assign Teacher')
	BEGIN
		IF NOT EXISTS(select top 1 1 from sTimetable.tAssignTeacher where EmployeeId = @rNewEmployeeId)
		begin
			INSERT INTO sTimetable.tAssignTeacher
			Select TimeTableSchemaId, @rNewEmployeeId from sTimetable.tAssignTeacher WHERE EmployeeId = @rExistingEmployeeId
			delete from sTimetable.tAssignTeacher where EmployeeId = @rExistingEmployeeId
		end		
	END

	IF (@rTitle = 'Teacher Subject Division')
	BEGIN
		INSERT INTO sAcademic.tTeacherSubject
		Select @rNewEmployeeId,SubjectId from sAcademic.tTeacherSubject where EmployeeId = @rExistingEmployeeId 
		and SubjectId NOT IN (select SubjectId from sAcademic.tTeacherSubjectDivision  where EmployeeId = @rNewEmployeeId)
		
		delete from sAcademic.tTeacherSubject where EmployeeId = @rExistingEmployeeId
		
		Insert into sAcademic.tTeacherSubjectDivision 
		select @rNewEmployeeId, SubjectId, DivisionId,SubjectCordinatorEmployeeId 
		from sAcademic.tTeacherSubjectDivision 
		where SubjectId NOT IN (select SubjectId from sAcademic.tTeacherSubjectDivision  where EmployeeId = @rNewEmployeeId)
		AND EmployeeId = @rExistingEmployeeId
		
		delete from sAcademic.tTeacherSubjectDivision where EmployeeId = @rExistingEmployeeId		
	END

	IF (@rTitle ='Time Table')
	BEGIN
		Update sTimetable.tTimeTable
		Set EmployeeId = @rNewEmployeeId from sTimetable.tTimeTable where EmployeeId  = @rExistingEmployeeId
		
		UPDATE sTimetable.tTeacherWorkLoad SET EmployeeId = @rNewEmployeeId WHERE EmployeeId = @rExistingEmployeeId 
	END
	
	IF (@rTitle ='User Access')
	BEGIN
		declare @lExistingUserId bigint= (select Id from sSecurity.tUser where SourceId = @rExistingEmployeeId AND SourceTypeId = 95)
		declare @lNewUserId bigint= (select Id from sSecurity.tUser where SourceId = @rNewEmployeeId AND SourceTypeId = 95)

		IF (@lNewUserId IS NULL)
		BEGIN
			Return
		END
		ELSE
		BEGIN
		Insert into sSecurity.tUserOrganization 
		select OrgId, @lNewUserId from sSecurity.tUserOrganization WHERE UserId=@lExistingUserId
		AND OrgId NOT in (select OrgId from sSecurity.tUserOrganization WHERE UserId=@lNewUserId)

		delete from sSecurity.tUserOrganization  WHERE UserId=@lExistingUserId

		INSERT INTO sSecurity.tUserAccess
		SELECT SourceTypeId, SourceId, @lNewUserId FROM sSecurity.tUserAccess WHERE UserId=@lExistingUserId
		AND SourceId not in (select SourceId from  sSecurity.tUserAccess WHERE UserId=@lNewUserId)

		delete from sSecurity.tUserAccess  WHERE UserId=@lExistingUserId
		END
	END

	IF (@rTitle ='Class Teacher')
	BEGIN
		Update sSetup.tDivisionMaster SET InchargeEmployeeId = @rNewEmployeeId where  InchargeEmployeeId = @rExistingEmployeeId
	END

	IF (@rTitle ='Lesson Plan')
	BEGIN
		Update sAcademic.tLessonPlan SET EmployeeId = @rNewEmployeeId where EmployeeId = @rExistingEmployeeId
	END

	--Drop Table #tmpSplitTable
END
GO
PRINT N'Altering Procedure [sHrm].[pEmployeeReplacementGet]...';


GO
ALTER PROCEDURE [sHrm].[pEmployeeReplacementGet]
	 
        @rEmployeeId bigint
	

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	Declare @lTeacherSubjectId bigint = 0 , @lTeacherDivisionId bigint = 0
	IF OBJECT_ID('tempdb..#tmpTable') IS NOT NULL DROP TABLE #tmpTable
	CREATE Table #tmpTable 
	(
		Id bigint IDENTITY,
		Title nvarchar(50)
	)

	IF EXISTS(select top 1 1 from sTimetable.tAssignTeacher where EmployeeId = @rEmployeeId)
	BEGIN
		Insert INTO #tmpTable Values
		(
			'Assign Teacher'
		)
	END


	set @lTeacherSubjectId = (select top 1 1 from sAcademic.tTeacherSubject where EmployeeId = @rEmployeeId)
	SET @lTeacherDivisionId = (select top 1 1 from sAcademic.tTeacherSubjectDivision where EmployeeId = @rEmployeeId)
	IF ((@lTeacherSubjectId = 1) OR (@lTeacherDivisionId = 1))
	BEGIN
		Insert INTO #tmpTable Values
		(
			'Teacher Subject Division'
		)
	END

	IF EXISTS (select top 1 1 from sTimetable.tTimeTable where EmployeeId = @rEmployeeId)
	BEGIN
		Insert INTO #tmpTable Values
		(
			'Time Table'
		)
	END
		
	declare @lUserId bigint= (select top 1 Id from sSecurity.tUser where SourceId = @rEmployeeId AND SourceTypeId = 95)
	declare @lUserOrganizationId int ,@lUserAccessId int
	SET @lUserOrganizationId = (SELECT Top 1 1 FROM sSecurity.tUserOrganization WHERE UserId=@lUserId)
	SET @lUserAccessId= (SELECT top 1 1 FROM sSecurity.tUserAccess WHERE UserId=@lUserId)
	IF ((@lUserOrganizationId = 1) OR (@lUserAccessId = 1))
	BEGIN
		Insert INTO #tmpTable Values
		(
			'User Access'
		)
	END

	IF EXISTS (select top 1 1 from sSetup.tDivisionMaster where InchargeEmployeeId = @rEmployeeId)
	BEGIN
		Insert INTO #tmpTable Values
		(
			'Class Teacher'
		)
	END	

	IF EXISTS (select top 1 1 from sAcademic.tLessonPlan where EmployeeId = @rEmployeeId)
	BEGIN
		Insert INTO #tmpTable Values
		(
			'Lesson Plan'
		)
	END

	select * from #tmpTable order by Title

	Drop Table #tmpTable
END
GO
PRINT N'Altering Procedure [sHrm].[pEmployeeReplacementTransfer]...';


GO
ALTER PROCEDURE [sHrm].[pEmployeeReplacementTransfer]
	 
        @rExistingEmployeeId BIGINT,
		@rNewEmployeeId BIGINT,
		@rTitle NVARCHAR(max),
		@rOrgId int
	

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	--IF OBJECT_ID('tempdb..#tmpSplitTable') IS NOT NULL DROP TABLE #tmpSplitTable

	--CREATE Table #tmpSplitTable
	--(
	--	Id NVARCHAR(max)
	--)

	--INSERT INTO #tmpSplitTable
	--SELECT CAST(item AS NVARCHAR(max)) AS Id FROM  sCommon.fnsplit(@rId,',')

	IF (@rTitle = 'Assign Teacher')
	BEGIN
		IF NOT EXISTS(select top 1 1 from sTimetable.tAssignTeacher where EmployeeId = @rNewEmployeeId)
		begin
			INSERT INTO sTimetable.tAssignTeacher
			Select TimeTableSchemaId, @rNewEmployeeId from sTimetable.tAssignTeacher WHERE EmployeeId = @rExistingEmployeeId
		end
	END

	IF (@rTitle = 'Teacher Subject Division')
	BEGIN
		
		INSERT INTO sAcademic.tTeacherSubject
		Select @rNewEmployeeId,SubjectId from sAcademic.tTeacherSubject where EmployeeId = @rExistingEmployeeId 
		and SubjectId NOT IN (select SubjectId from sAcademic.tTeacherSubjectDivision  where EmployeeId = @rNewEmployeeId)
		
		Insert into sAcademic.tTeacherSubjectDivision 
		select @rNewEmployeeId, SubjectId, DivisionId,SubjectCordinatorEmployeeId 
		from sAcademic.tTeacherSubjectDivision 
		where SubjectId NOT IN (select SubjectId from sAcademic.tTeacherSubjectDivision  where EmployeeId = @rNewEmployeeId)
		AND EmployeeId = @rExistingEmployeeId
		
	END
	
	IF (@rTitle = 'User Access')
	BEGIN
		declare @lExistingUserId bigint= (select Id from sSecurity.tUser where SourceId = @rExistingEmployeeId AND SourceTypeId = 95)
		declare @lNewUserId bigint= (select Id from sSecurity.tUser where SourceId = @rNewEmployeeId AND SourceTypeId = 95)
		IF (@lNewUserId IS NULL)
		BEGIN
			Return
		END
		ELSE
		BEGIN
			Insert into sSecurity.tUserOrganization 
			select OrgId, @lNewUserId from sSecurity.tUserOrganization WHERE UserId=@lExistingUserId
			AND OrgId NOT in (select OrgId from sSecurity.tUserOrganization WHERE UserId=@lNewUserId)

			INSERT INTO sSecurity.tUserAccess
			SELECT SourceTypeId, SourceId, @lNewUserId FROM sSecurity.tUserAccess WHERE UserId=@lExistingUserId
			AND SourceId not in (select SourceId from  sSecurity.tUserAccess WHERE UserId=@lNewUserId)
		END
	END
	
	--IF EXISTS (SELECT 1 from #tmpSplitTable WHERE Id ='Time Table')
	--BEGIN

	--	UPDATE sTimetable.tTimeTable 
	--	SET EmployeeId = @rNewEmployeeId 
	--	WHERE EmployeeId = @rExistingEmployeeId 

	--	UPDATE sTimetable.tTeacherWorkLoad 
	--	SET EmployeeId = @rNewEmployeeId WHERE EmployeeId = @rExistingEmployeeId 
	--END

	--IF EXISTS (SELECT 1 from #tmpSplitTable WHERE Id ='Class Teacher')
	--BEGIN
	--	Update sSetup.tDivisionMaster SET InchargeEmployeeId = @rNewEmployeeId where  InchargeEmployeeId = @rExistingEmployeeId
	--END

	--Drop Table #tmpSplitTable
END
GO
PRINT N'Altering Procedure [sHrm].[pImportEmployees_Update_Dynamicly]...';


GO
ALTER proc [sHrm].[pImportEmployees_Update_Dynamicly] 
@rOrgId int,
@rCreatedUserId bigint,
@rCode varchar(200) = '',
@rShortName varchar(200) = '',
@rFirstName varchar(200) = '',
@rMiddleName varchar(200) = '',
@rLastName varchar(200) = '',
@rGender varchar(50) = '',
@rEmpType varchar(100) = '',
@rEmpGroup varchar(100) = '',
@rEmpGrade varchar(100) = '',
@rDepartment varchar(150) = '',
@rDesignation varchar(150) = '',
@rQualification varchar(150) = '',
@rDOB datetime = '',
@rDateOfJoining datetime = '',
@rReligion varchar(150) = '',
@rCompayPhoneNo varchar(15) = '',
@rExtensionNo varchar(15)='',
@rCompayMailId varchar(100)='',
@rPersonalEmailid varchar(100)='',
@rMobileNo varchar(50)='',
@rPresentStreetOne varchar(200)='',
@rPresentStreetTwo varchar(200)='',
@rPresentStreetThree varchar(200)='',
@rPresentCity varchar(100)='',
@rPresentZipCode varchar(15)='',
@rPresentState varchar(100)='',
@rPresentCountry varchar(100)='',
@rPresentContactNo varchar(50)='',
@rCastCategory varchar(50)='',
@rFamilyCast varchar(100)='',
@rAccountNumber varchar(100)='',
@rBankName varchar(100)='',
@rBranch varchar(100)=0,
@rEPFNumber varchar(100)=0,
@rPanNumber  varchar(100)='',
@rAdhaarNumber varchar(100)='',
@rValidate varchar(250)='' ,
@rOrgGroupId int,
@rIdentificationMark1  varchar(200)='',
@rUIDNumber varchar(50)='',
@rDateOfLeaving datetime = '',
@rReason varchar(200)='',
@rBloodGroup varchar(50)='',
@rNumber Bigint,
@rProbationUptoDate date = '',
@rAhdocUptoDate date = '',
@rPermanentDate date = '',
@rDateOfResignation date = '',
@rWhatsAppContactNo nvarchar(20) = ''

as
begin	

	IF(@rDateOfLeaving='') 
	SET @rDateOfLeaving = NULL
	IF(@rDOB='') 
	SET @rDOB = NULL
	IF(@rDateOfJoining='') 
	SET @rDateOfJoining = NULL
	IF(@rProbationUptoDate='')
	SET @rProbationUptoDate = NULL
	IF(@rAhdocUptoDate='')
	SET @rAhdocUptoDate = NULL
	IF(@rPermanentDate='')
	SET @rPermanentDate = NULL
	IF(@rDateOfResignation='')
	SET @rDateOfResignation = NULL
	
	declare @EmpId bigint = 0
	select @EmpId = Id from sHrm.tEmployeeMaster where Code = @rCode and OrgID = @rOrgId AND ISNULL(IsOtherUser,0) = 0
	select @EmpId = isnull(@EmpId,0)
	
	declare @genderid int,@emptypeid int,@cmpanyid int,@departmenttid int,@designationid int, 
	 @employeegradeid int,@empgroupid int,@religionId int,@castcatagoryId int,@bloodgroupid int
	 
	
	select @rGender = case when upper(@rGender) = 'M' then 'Male'
	when  upper(@rGender) = 'MALE' then 'Male'
	when upper(@rGender) ='FEMALE' then 'Female'
	when upper(@rGender) = 'F' then 'Female' when upper(@rGender) = 'N' then 'Not Known' else 'Not Known' end
	 
	select @genderid = isnull(Id,0) from sCommon.tGenderMaster where Title = @rGender
	
	select @emptypeid = isnull(Id,0) from sHrm.tEmployeeTypeMaster where Title = @rEmpType and OrgId = @rOrgId
 
	select @empgroupid = isnull(Id,0) from sHrm.tEmployeeGroupMaster where Title = @rEmpGroup
	
	select @employeegradeid = isnull(Id,0) from sHrm.tEmployeeGradeMaster where Title = @rEmpGrade and OrgId = @rOrgId
	 
	 select @departmenttid = isnull(Id,0) from sSetup.tDepartmentMaster where Title = @rDepartment and OrgId = @rOrgId
	 
	  select @bloodgroupid = isnull(Id,0) from sCommon.tBloodGroupMaster where Title = @rBloodGroup 
	
	if (isnull(@rDesignation,'') <> '')
	select @designationid =  isnull(Id,0) from sHrm.tEmployeeDesignationMaster where Title = @rDesignation and OrgId = @rOrgId
	else
	select @designationid = 0
	
	 if (isnull(@rReligion,'') <> '')
			select @religionId =  isnull(Id,0) from sCommon.tReligionMaster where Title = @rReligion and OrgGroupId = @rOrgGroupId
	else
			select @religionId = 0
	
	 if (isnull(@rCastCategory,'') <> '')
	 select @castcatagoryId =  isnull(Id,0) from sCommon.tCastCategoryMaster where Title = @rCastCategory and OrgGroupId = @rOrgGroupId
	 else
	select @castcatagoryId = 0
			
	select @genderid = isnull(@genderid,0),@emptypeid = isnull(@emptypeid,0),@empgroupid = isnull(@empgroupid,0),
	@employeegradeid = isnull(@employeegradeid,0),@departmenttid = isnull(@departmenttid,0),@designationid = isnull(@designationid,0),
	@religionId = isnull(@religionId,0),@castcatagoryId = isnull(@castcatagoryId,0) 
	
	declare @lNextNumber bigint,@Title varchar(100)=''
	
	if @rEmpGroup = ''
	begin
		
		if exists (select 1 from sHrm.tEmployeeGroupMaster where  Title = @Title)
		begin
			select @empgroupid = Id from sHrm.tEmployeeGroupMaster where Title = @Title
		end
		
	end
	
	 
	
	if @rEmpType = ''
	begin		
		
		if exists (select 1 from sHrm.tEmployeeTypeMaster where OrgId = @rOrgId and Title = @Title)
		begin
			select @emptypeid = Id from sHrm.tEmployeeTypeMaster where OrgId = @rOrgId and Title = @Title
		end
	end
	
	 
	if @rEmpGrade = ''
	begin
		 
		if exists(select 1 from sHrm.tEmployeeGradeMaster where OrgId = @rOrgId and Title = @Title)
		begin
			select @employeegradeid = Id from sHrm.tEmployeeGradeMaster where OrgId = @rOrgId and Title = @Title
		end
	end
	
	
	if @rDepartment = ''
	begin		
		 
		if exists (select * from sSetup.tDepartmentMaster  where Title = @Title and OrgId = @rOrgId)
		begin
			select @departmenttid = Id from sSetup.tDepartmentMaster  where Title = @Title and OrgId = @rOrgId
		end
	end
		

	if @rDesignation = ''
	begin
		select @Title = Title from sHrm.tEmployeeDesignationMaster where Id = 1
		if exists (select * from sHrm.tEmployeeDesignationMaster where Title = @Title and OrgId = @rOrgId)
		begin
			select @designationid = Id from sHrm.tEmployeeDesignationMaster where Title = @Title and OrgId = @rOrgId			
		end
	end
	 
	 if @rCastCategory = ''
	begin
		
		if exists (select 1 from sCommon.tCastCategoryMaster where  Title = @Title and OrgGroupId=@rOrgGroupId)
		begin
			select @castcatagoryId = Id from sCommon.tCastCategoryMaster where Title = @Title and OrgGroupId=@rOrgGroupId
		end
		
	end
	
	 
	 if @rReligion = ''
	begin
		
		if exists (select 1 from sCommon.tReligionMaster where  Title = @Title and OrgGroupId=@rOrgGroupId)
		begin
			select @religionId = Id from sCommon.tReligionMaster where Title = @Title and OrgGroupId=@rOrgGroupId
		end
		
	end
	
	if @rShortName <> ''
	select @rShortName = [sSetup].[fPortalXMLTagsReplaceReverse](@rShortName)
	if @rFirstName <> ''
	select @rFirstName = [sSetup].[fPortalXMLTagsReplaceReverse](@rFirstName)
	if @rMiddleName <> ''
	select @rMiddleName = [sSetup].[fPortalXMLTagsReplaceReverse](@rMiddleName)
	if @rLastName <> ''
	select @rLastName = [sSetup].[fPortalXMLTagsReplaceReverse](@rLastName)
	if @rCompayPhoneNo <> ''
	select @rCompayPhoneNo = [sSetup].[fPortalXMLTagsReplaceReverse](@rCompayPhoneNo)
	if @rExtensionNo <> ''
	select @rExtensionNo = [sSetup].[fPortalXMLTagsReplaceReverse](@rExtensionNo)
	if @rCompayMailId <> ''
	select @rCompayMailId = [sSetup].[fPortalXMLTagsReplaceReverse](@rCompayMailId)
	if @rPersonalEmailid <> ''
	select @rPersonalEmailid = [sSetup].[fPortalXMLTagsReplaceReverse](@rPersonalEmailid)
	if @rMobileNo <> ''
	select @rMobileNo = [sSetup].[fPortalXMLTagsReplaceReverse](@rMobileNo)
	if @rPresentStreetOne <> ''
	select @rPresentStreetOne = [sSetup].[fPortalXMLTagsReplaceReverse](@rPresentStreetOne)
	if @rPresentStreetTwo <> ''
	select @rPresentStreetTwo = [sSetup].[fPortalXMLTagsReplaceReverse](@rPresentStreetTwo)
	if @rPresentStreetThree <> ''
	select @rPresentStreetThree = [sSetup].[fPortalXMLTagsReplaceReverse](@rPresentStreetThree)
	if @rPresentCity <> ''
	select @rPresentCity = [sSetup].[fPortalXMLTagsReplaceReverse](@rPresentCity)
	if @rPresentZipCode <> ''
	select @rPresentZipCode = [sSetup].[fPortalXMLTagsReplaceReverse](@rPresentZipCode)
	if @rPresentState <> ''
	select @rPresentState = [sSetup].[fPortalXMLTagsReplaceReverse](@rPresentState)
	if @rPresentCountry <> ''
	select @rPresentCountry = [sSetup].[fPortalXMLTagsReplaceReverse](@rPresentCountry)
	if @rPresentContactNo <> ''
	select @rPresentContactNo = [sSetup].[fPortalXMLTagsReplaceReverse](@rPresentContactNo)
	if @rFamilyCast <> ''
	select @rFamilyCast = [sSetup].[fPortalXMLTagsReplaceReverse](@rFamilyCast)
	if @rAccountNumber <> ''
	select @rAccountNumber = [sSetup].[fPortalXMLTagsReplaceReverse](@rAccountNumber)
	if @rBankName <> ''
	select @rBankName = [sSetup].[fPortalXMLTagsReplaceReverse](@rBankName)
	if @rBranch <> ''
	select @rBranch = [sSetup].[fPortalXMLTagsReplaceReverse](@rBranch)
	if @rEPFNumber<> ''
	select @rEPFNumber = [sSetup].[fPortalXMLTagsReplaceReverse](@rEPFNumber)
	if @rPanNumber <> ''
	select @rPanNumber = [sSetup].[fPortalXMLTagsReplaceReverse](@rPanNumber)
	if @rAdhaarNumber <> ''
	select @rAdhaarNumber = [sSetup].[fPortalXMLTagsReplaceReverse](@rAdhaarNumber)
	if @rWhatsAppContactNo <> ''
	select @rWhatsAppContactNo = [sSetup].[fPortalXMLTagsReplaceReverse](@rWhatsAppContactNo)
	  
	 
	begin

		UPDATE sHrm.tEmployeeMaster 
		SET 
		ShortName = case when isnull(@rShortName,'') <> '' then @rShortName else ShortName end
		,FirstName = case when isnull(@rFirstName,'') <> '' then @rFirstName else FirstName end
		,MiddleName   = case when isnull(@rMiddleName,'') <> '' then @rMiddleName else MiddleName end
		,LastName     = case when isnull(@rLastName,'') <> '' then @rLastName else LastName end
		--,StatusId     = case when isnull(@statusid,0) <> 0 then @statusid else StatusId end
		,IsObsolete   = case when isnull(IsObsolete,'') <> '' then IsObsolete else IsObsolete end
		,UpdatedUserId = @rCreatedUserId
		,UpdatedDateTime = sCommon.fGetDate()
		,Number = @rNumber
		WHERE Id = @EmpId and OrgId = @rOrgId AND ISNULL(IsOtherUser,0) = 0

		  
		UPDATE sHrm.tEmployeeJobDetail
		SET 
			EmployeeDesignationId = case when isnull(@designationid,0) <> 0 then @designationid else EmployeeDesignationId end,	 
			OrganizationDepartmentId = case when isnull(@departmenttid,0) <> 0 then @departmenttid else OrganizationDepartmentId end,
			DateOfJoining =	case when isnull(@rDateOfJoining,'') <> '' then @rDateOfJoining else DateOfJoining end,
			UpdatedUserId = @rCreatedUserId,
			UpdatedDateTime = sCommon.fGetDate(),
			EmployeeTypeId = case when isnull(@emptypeid,0) <> 0 then @emptypeid else EmployeeTypeId end,
			EmployeeGroupId = case when isnull(@empgroupid,0) <> 0 then @empgroupid else EmployeeGroupid end,
			EmployeeGradeId = case when isnull(@employeegradeid,0) <> 0 then @employeegradeid else EmployeeGradeId  end ,
			DateOfleaving =  case when isnull(@rDateOfLeaving,'') <> '' then @rDateOfLeaving else DateOfleaving end,
			ReasonOfleaving = case when isnull(@rReason,'') <> '' then @rReason else ReasonOfleaving end,
			ProbationUptoDate = @rProbationUptoDate,
			AhdocUptoDate = @rAhdocUptoDate,
			PermanentDate = @rPermanentDate,
			DateOfResignation = @rDateOfResignation
			  
	  WHERE EmployeeId = @EmpId and OrgId = @rOrgId
	  
		Update sHrm.tEmployeePersonalDetail 
		set  
		GenderId = case when isnull(@genderid,0) <> 0 then @genderid else GenderId  end,
		ReligionId =  case when isnull(@religionId,0) <> 0 then @religionId else ReligionId  end,
		Qualification =  case when isnull(@rQualification,'') <> '' then @rQualification else Qualification  end,
		BloodGroupId =  case when isnull(@bloodgroupid,0) <> 0 then @bloodgroupid else BloodGroupId  end,
		DateOfBirth =  case when isnull(@rDOB,0) <> 0 then @rDOB else DateOfBirth  end,
		IdentificationMark1 =  case when isnull(@rIdentificationMark1,'') <> '' then @rIdentificationMark1 else IdentificationMark1  end,
		UIDNumber =  case when isnull(@rUIDNumber,0) <> 0 then @rUIDNumber else UIDNumber  end,
		UpdatedUserId = @rCreatedUserId,
		UpdatedDateTime = sCommon.fGetDate(),
		FamilyCast =case when isnull(@rFamilyCast,'') <> '' then @rFamilyCast else FamilyCast  end,
		AdhaarNumber =case when isnull(@rAdhaarNumber,'') <> '' then @rAdhaarNumber else AdhaarNumber  end,
		CastCategoryId =case when isnull(@castcatagoryId,0) <> 0 then @castcatagoryId else FamilyCast  end
		where EmployeeId = @EmpId and OrgId = @rOrgId
		
  		UPDATE [sHrm].[tEmployeeCommunications]
		SET 
	      
		   [PresentStreetOne] = case when isnull(@rPresentStreetOne,'') <> '' then @rPresentStreetOne else [PresentStreetOne] end 
		  ,[PresentStreetTwo] =  case when isnull(@rPresentStreetTwo,'') <> '' then @rPresentStreetTwo else [PresentStreetTwo] end 
		  ,[PresentStreetThree] = case when isnull(@rPresentStreetThree,'') <> '' then @rPresentStreetThree else [PresentStreetThree] end 
		  ,[PresentCountry] = case when isnull(@rPresentCountry,'') <> '' then @rPresentCountry else [PresentCountry] end 
		  ,[PresentState] =  case when isnull(@rPresentState,'') <> '' then @rPresentState else [PresentState] end 
		  ,[PresentCity] =  case when isnull(@rPresentCity,'') <> '' then @rPresentCity else [PresentCity] end 
		  ,[EmergencyContactNo] = case when isnull(@rMobileNo,'') <> '' then @rMobileNo else [EmergencyContactNo] end 
		  ,[PhoneNoCompany] = case when isnull(@rCompayPhoneNo,'') <> '' then @rCompayPhoneNo else [PhoneNoCompany] end 
		  ,[ExtensionNo] = case when isnull(@rExtensionNo,'') <> '' then @rExtensionNo else [ExtensionNo] end  
		  ,[CompanyEmail] =  case when isnull(@rCompayMailId,'') <> '' then @rCompayMailId else [CompanyEmail]  end   
		  ,[PersonalEmail] =  case when isnull(@rPersonalEmailid,'') <> '' then @rPersonalEmailid else [PersonalEmail]  end   
		  ,[MobileNumber] =  case when isnull(@rMobileNo,'') <> '' then @rMobileNo else [MobileNumber]  end      
		  ,[UpdatedUserId] = @rCreatedUserId
		  ,[UpdatedDateTime] =  sCommon.fGetDate() 
		  ,[WhatsAppContactNo] =  case when isnull(@rWhatsAppContactNo,'') <> '' then @rWhatsAppContactNo else [WhatsAppContactNo]  end    
		  ,PresentZipCode = case when isnull(@rPresentZipCode,'') <> '' then @rPresentZipCode else PresentZipCode  end    
		  ,PresentContactNo = case when isnull(@rPresentContactNo,'') <> '' then @rPresentContactNo else PresentContactNo  end    
		WHERE EmployeeId = @EmpId

		Update [sHrm].[tEmployeeStatutoryAndOther]
		SET
		AccountNumber = case when isnull(@rAccountNumber,'') <> '' then @rAccountNumber else AccountNumber  end, 
		BankName = case when isnull(@rBankName,'') <> '' then @rBankName else BankName  end,
		Branch = case when isnull(@rBranch,'') <> '' then @rBranch else Branch  end , 
		EPFNumber = case when isnull(@rEPFNumber,'') <> '' then @rEPFNumber else EPFNumber  end,
		PanNumber = case when isnull(@rPanNumber,'') <> '' then @rPanNumber else PanNumber  end
		where EmployeeId = @EmpId 
	end	
end
GO
PRINT N'Altering Procedure [sSecurity].[pVerifyMobileNumberForEmployeeOTP]...';


GO
ALTER PROCEDURE sSecurity.pVerifyMobileNumberForEmployeeOTP

	@rOrgId int = 0,
	@rMobileNumber nvarchar(50), 
	@rEmployeeId bigint

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	DECLARE @lCount int = 0
	DECLARE @lUserId bigint = 0,@lId Bigint = 0
	DECLARE @newpwd VARCHAR(100) 

	SELECT @lCount = COUNT(EC.EmployeeId), @lId = EC.EmployeeId
	FROM sHrm.tEmployeeCommunications EC 
	INNER JOIN sHrm.tEmployeeMaster EM ON EC.EmployeeId = EM.Id 
	INNER JOIN sSecurity.tUser U ON U.SourceId = EC.EmployeeId AND U.SourceTypeId=95
	WHERE EC.MobileNumber = @rMobileNumber AND EM.OrgId=@rOrgId  AND EC.EmployeeId = @rEmployeeId
	GROUP BY EC.EmployeeId
	
	
	IF(@lCount > 0)
	BEGIN
	
		EXEC [sSecurity].[pNumericOTPGenerate] @len=6, @min=48, @range=9, @exclude='', @output=@newpwd OUT
		UPDATE sSecurity.tUser 
		SET	TempPasswordCode=@newpwd,CreatedDateTime=sCommon.fGetDate(),OTPExpiryDate=DATEADD(SECOND,120,GETDATE())				
		WHERE SourceId = @lId AND OrgId = @rOrgId AND SourceTypeId = 95
		
		SELECT 1 AS Result,'' AS [Message], TempPasswordCode AS OTP,Id AS UserId FROM sSecurity.tUser 
		WHERE SourceId = @lId AND OrgId = @rOrgId AND SourceTypeId = 95

	END

	ELSE
	BEGIN 
		SELECT -102 AS Result,'Mobile number is wrong' AS [Message],'' AS OTP, 0 AS UserId
	END
END
GO
PRINT N'Altering Procedure [sSecurity].[pVerifyMobileNumberForOTP]...';


GO
ALTER PROCEDURE [sSecurity].[pVerifyMobileNumberForOTP]

	@rOrgId int = 0,
	@rBatchId int =0,
	@rMobileNumber nvarchar(50), 
	@rAcademicId bigint 

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	DECLARE @lCount int = 0
	DECLARE @lUserId bigint =0
	DECLARE @newpwd VARCHAR(100) 

	SELECT @lCount = COUNT(SC.StudentId) 
	FROM  sStudent.tStudentCommunication SC
	INNER JOIN sStudent.tAcademic A ON A.StudentId = SC.StudentId
	INNER JOIN sSecurity.tUser U ON U.SourceId = SC.StudentId AND U.SourceTypeId=2003
	WHERE SC.ParentContactNo = @rMobileNumber  
	--AND A.BatchId = @rBatchId    -- No Need as per mantis 0027903
	AND A.OrgId=@rOrgId  AND A.Id = @rAcademicId
	GROUP BY SC.StudentId
	
		IF(@lCount > 0)
		BEGIN
		
			SELECT SC.StudentId  INTO #UserId FROM  sStudent.tStudentCommunication SC
			INNER JOIN sStudent.tAcademic A ON A.StudentId = SC.StudentId
			INNER JOIN sSecurity.tUser U ON U.SourceId = SC.StudentId AND U.SourceTypeId=2003
			WHERE SC.ParentContactNo = @rMobileNumber 
			--AND A.BatchId = @rBatchId		-- No Need as per mantis 0027903
			AND A.OrgId=@rOrgId AND A.Id = @rAcademicId
		
			--END
			--SELECT * FROM #UserId
			SELECT @lUserId = StudentId FROM #UserId
			EXEC [sSecurity].[pNumericOTPGenerate] @len=6, @min=48, @range=9, @exclude='', @output=@newpwd OUT
			UPDATE sSecurity.tUser 
			SET	TempPasswordCode=@newpwd,CreatedDateTime=sCommon.fGetDate(),OTPExpiryDate=DATEADD(SECOND,120,GETDATE())				
			WHERE SourceId = @lUserId AND OrgId = @rOrgId AND SourceTypeId = 2003
		
			SELECT 1 AS Result,'' AS [Message], TempPasswordCode AS OTP,Id AS UserId FROM sSecurity.tUser 
			WHERE SourceId = @lUserId AND OrgId = @rOrgId	

			DROP Table #UserId
		END

		ELSE
		BEGIN 
			SELECT -102 AS Result,'Mobile number is wrong' AS [Message],'' AS OTP, 0 AS UserId
		END
		
	
END
GO
PRINT N'Altering Procedure [sStudent].[pDigitalFormChangeListGet]...';


GO

 
ALTER PROCEDURE [sStudent].[pDigitalFormChangeListGet]

	  @rId int=0,
	  @rOrgId smallint=0,
	  @rStudentCode nvarchar(100),
	  @rClassId bigint=0,
	  @rDivisionId bigint=0,
	  @rFormStatusId smallint = 0
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
	 
		SELECT 
			(SELECT MAX(AutoId) FROM sStudent.tDigitalFormStudent WHERE DigitalFormId = DF.Id AND AcademicId = DFS.AcademicId) as Id,
			DF.Id as DigitalFormId,
			DF.Code,
			DF.Title,
			SA.StudentId,
			SA.AcademicId,
			SA.Code as StudentCode,
			SA.Name,
			SA.ClassName+' - '+SA.DivisionName AS ClassDivision,
			SA.RollNo,
			SA.Number,
			ISNULL(DFSS.StatusId, 0) AS DigitalFormStatusId,
			ISNULL(SM.Title, '') AS DigitalFormStatus,
			ISNULL(DFSS.ActionDateTime, '') AS FormActionDateTime,
			(select count(1) from [sStudent].[tDigitalFormStudent] DFS1 
					Left join sCommon.tUpdateFieldMaster UFM On UFM.Id = DFS1.UpdateFieldId
				where DFS1.DigitalFormId = DF.Id and SA.AcademicId = DFS1.AcademicId and DFS1.StatusId=549	
				and ((isnull(SubFunctionalityName,'')<>'StudentImages' AND  isnull(DFS1.OldValue,'')<>isnull(DFS1.NewValue,'') ) OR (isnull(SubFunctionalityName,'')='StudentImages' AND isnull(DFS1.OldValueImage,cast('' as varbinary))<>isnull(DFS1.NewValueImage,cast('' as varbinary))))) PendingCount,
			(select count(1) from [sStudent].[tDigitalFormStudent] DFS1 
					Left join sCommon.tUpdateFieldMaster UFM On UFM.Id = DFS1.UpdateFieldId
				where DFS1.DigitalFormId = DF.Id and SA.AcademicId = DFS1.AcademicId and DFS1.StatusId=550
				and ((isnull(SubFunctionalityName,'')<>'StudentImages' AND  isnull(DFS1.OldValue,'')<>isnull(DFS1.NewValue,'') ) OR (isnull(SubFunctionalityName,'')='StudentImages' AND isnull(DFS1.OldValueImage,cast('' as varbinary))<>isnull(DFS1.NewValueImage,cast('' as varbinary))))
				) ApprovedCount,
			(select count(1) from [sStudent].[tDigitalFormStudent] DFS1 
					Left join sCommon.tUpdateFieldMaster UFM On UFM.Id = DFS1.UpdateFieldId
				where DFS1.DigitalFormId = DF.Id and SA.AcademicId = DFS1.AcademicId and DFS1.StatusId=551
				and ((isnull(SubFunctionalityName,'')<>'StudentImages' AND  isnull(DFS1.OldValue,'')<>isnull(DFS1.NewValue,'') ) OR (isnull(SubFunctionalityName,'')='StudentImages' AND isnull(DFS1.OldValueImage,cast('' as varbinary))<>isnull(DFS1.NewValueImage,cast('' as varbinary))))
			 ) RejectedCount,
			 (select count(1) from [sStudent].[tDigitalFormStudent] DFS1 
					Left join sCommon.tUpdateFieldMaster UFM On UFM.Id = DFS1.UpdateFieldId
				where DFS1.DigitalFormId = DF.Id and SA.AcademicId = DFS1.AcademicId --and DFS1.StatusId=551
				and ((isnull(SubFunctionalityName,'')<>'StudentImages' AND  isnull(DFS1.OldValue,'')=isnull(DFS1.NewValue,'') ) OR (isnull(SubFunctionalityName,'')='StudentImages' AND isnull(DFS1.OldValueImage,cast('' as varbinary))=isnull(DFS1.NewValueImage,cast('' as varbinary))))
			 ) NoChangeCount
		FROM 
			sStudent.tDigitalForm DF
			INNER JOIN (SELECT DigitalFormId,AcademicId FROM sStudent.tDigitalFormStudent GROUP By AcademicId,DigitalFormId) DFS ON DFS.DigitalFormId = DF.Id
			INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId = DFS.AcademicId
			LEFT JOIN [sStudent].[tDigitalFormStudentStatus] DFSS ON DFSS.DigitalFormId = DF.Id AND DFSS.AcademicId = SA.AcademicId
			LEFT JOIN sCommon.tStatusMaster SM ON SM.Id = DFSS.StatusId
		WHERE 
			((DF.OrgId = @rOrgId)OR (@rOrgId=0))
			AND ((DF.Id = @rId) OR (@rId = 0))		
			AND ((SA.Code = @rStudentCode) OR (@rStudentCode=''))
			AND ((SA.ClassId = @rClassId) OR (@rClassId = 0))
			AND ((SA.DivisionId = @rDivisionId) OR (@rDivisionId = 0))
			AND ((SA.OrgId = @rOrgId) OR (@rOrgId = 0))
			AND (DFSS.StatusId = @rFormStatusId OR @rFormStatusId = 0)
	   ORDER BY Id Asc
END
GO
PRINT N'Altering Procedure [sStudent].[pStudentBulkImagesAdd]...';


GO
ALTER PROCEDURE [sStudent].[pStudentBulkImagesAdd]
	 
	@rNumber bigint,
	@rCode nvarchar(20),
	@rStudentPhoto varbinary(max),
	@rOrgId smallint,
	@rPhotoType nvarchar(50),
	@rOriginalStudentPhoto varbinary(max)
	
	
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	DECLARE @lStudentId bigint
	
	SELECT @lStudentId=Id FROM sStudent.tStudentMaster WHERE Code=@rCode AND OrgId=@rOrgId
	
	IF(ISNULL(@lStudentId,'') = '')
	BEGIN
		SELECT 1 AS Result
		RETURN
	END
	
	IF NOT EXISTS(SELECT StudentId FROM sStudent.tStudentImages WHERE StudentId=@lStudentId)
	BEGIN 
	INSERT INTO sStudent.tStudentImages
		(
			StudentId,
			StudentPhoto
		)
	VALUES
		(
			@lStudentId,
			NULL
		)		             
	END	 
	 
	 
	 IF @rPhotoType = 'TempStudentPhotos'
	 BEGIN
	  UPDATE sStudent.tStudentImages  SET StudentPhoto=@rStudentPhoto,OriginalStudentPhoto=@rOriginalStudentPhoto,UpdatedDateTime = sCommon.fGetDate() WHERE StudentId=@lStudentId
	 END 
	 ELSE IF @rPhotoType = 'TempStudentFatherPhotos'
	 BEGIN
	  UPDATE sStudent.tStudentImages  SET FatherPhoto=@rStudentPhoto,OriginalFatherPhoto=@rOriginalStudentPhoto,UpdatedDateTime = sCommon.fGetDate() WHERE StudentId=@lStudentId	 	 
	 END 
	 ELSE IF @rPhotoType = 'TempStudentMotherPhotos' 
	 BEGIN
	  UPDATE sStudent.tStudentImages  SET MotherPhoto=@rStudentPhoto,OriginalMotherPhoto=@rOriginalStudentPhoto,UpdatedDateTime = sCommon.fGetDate() WHERE StudentId=@lStudentId
	 END
	 ELSE IF @rPhotoType = 'TempStudentRelativePhotos' 
	 BEGIN
	 UPDATE sStudent.tStudentImages  SET RelativePhoto=@rStudentPhoto,OriginalRelativePhoto=@rOriginalStudentPhoto,UpdatedDateTime = sCommon.fGetDate() WHERE StudentId=@lStudentId	 
	 END
	 
	 SELECT 1 AS Result
	
	
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Altering Procedure [sTool].[pDeleteStaticData]...';


GO
 
ALTER PROCEDURE [sTool].[pDeleteStaticData]
 
	 
AS
SET NOCOUNT ON
BEGIN 
 

DELETE FROM sAlert.tEventMaster
DELETE FROM sCommon.tAutoCompleteMaster
DELETE FROM sCommon.tCommonMaster
DELETE FROM sCommon.tDepends
DELETE FROM sCommon.tModuleMaster
DELETE FROM sCommon.tPrefixFunctionality
DELETE FROM sCommon.tRefferedTableForObsoleteCheck
DELETE FROM sCommon.tRefferedTableWithoutForeignKey
DELETE FROM sCommon.tReport
DELETE FROM sCommon.tReportFormatGroupMaster
DELETE FROM sCommon.tReportGroupMaster
DELETE FROM sCommon.tSourceScreenMaster
DELETE FROM sCommon.tSourceTypeMaster
DELETE FROM sCommon.tStatusMaster
DELETE FROM sCommon.tStatusTypeMaster
DELETE FROM sCommon.tTableRowIdMaster
DELETE FROM sCommon.tUpdateFieldMaster
DELETE FROM sCommon.tValidationType
DELETE FROM sConfig.tColorLegendMaster
DELETE FROM sConfig.tConfigurationMaster
DELETE FROM sConfig.tConfigurationValue
DELETE FROM sSecurity.tMenu
DELETE FROM sSecurity.tResourceTypeMaster
DELETE FROM sSecurity.tScreen
DELETE FROM sSecurity.tScreenGroupMaster
DELETE FROM sSecurity.tScreenTypeMaster
DELETE FROM sSecurity.tTask
DELETE FROM sSystem.tTable
DELETE FROM sTool.tObjects
DELETE FROM sCommon.tReportTypeMaster


DELETE FROM sSetup.tAffiliationClassGroup
DELETE FROM sSetup.tAffiliationTypeMaster
DELETE FROM sSetup.tAffiliationMaster	
DELETE FROM sSetup.tStreamMaster

-- temp insert
DELETE FROM sAttendance.tAttendanceForMaster
DELETE FROM sEExam.tEntryModeMaster
DELETE FROM sSetup.tTermScopeMaster	 
 
DELETE FROM sConfig.tConfigurationLevelMaster

DELETE FROM sAdmission.tInquiryModeMaster

DELETE FROM sFee.tFeeMainGroupMaster

DELETE FROM sPayroll.tPayElementDefault

DELETE FROM sSecurity.tScreenGroupMapping
DELETE FROM sAssessment.tCCEExamMaster
DELETE FROM sSetup.tTermPatternMaster


DELETE FROM sAdmission.tAdmissionStatusMaster
DELETE FROM sAssessment.tCCERptGroup
DELETE FROM sHrm.tEmployeeICardTemplate
DELETE FROM sSecurity.tDashletMaster
DELETE FROM sStudent.tICardTemplate
DELETE FROM sSystem.tCustomQuery

DELETE FROM sCommon.tRangeGroupMaster

DELETE FROM sHostel.tLogStatusMaster

DELETE FROM sSetup.tStudentNameFormatMaster

DELETE FROM sCommon.tMainCastCategoryMaster

DELETE FROM sOp.tFunctionalityMaster
DELETE FROM sOp.tPaymentGatewayMaster

DELETE FROM sOp.tPayTypeMaster
DELETE FROM sOp.tTransactionStatusMaster
--DELETE FROM sPayroll.tForm16B
DELETE FROM sStudent.tBatchStatusMaster
DELETE FROM [sFinanceCommon].[tPayTypeMaster]

DELETE FROM sAttendance.tAttendanceTagMaster
DELETE FROM sCommon.tLiveWithMaster
DELETE FROM sConfig.tDisplayFieldMaster

DELETE FROM sActivity.tEventMainTypeMaster
DELETE FROM sAlert.tOSType

DELETE FROM sCommon.tCalculationTypeMaster
DELETE FROM sFee.tApplayAsMaster
DELETE FROM sSecurity.tScreenDependency
DELETE FROM sStudent.tSUIdFieldMaster

DELETE FROM [sAlert].[tAlertModeMaster]
DELETE FROM sCommon.tReportRemarkGroupMaster
DELETE FROM sStudent.tEnrollmentStatusMaster
DELETE FROM [sSetup].[tClassGroupMaster]

DELETE FROM sCommon.tTemplateSourceMaster
DELETE FROM sErp.tCustomerStatusMaster
DELETE FROM sErp.tInstallationTypeMaster
DELETE FROM sRecruitment.tRecruitmentStatusMaster

DELETE FROM sAssessment.tStaticCCECSMaster
DELETE FROM sAssessment.tStaticCCECSGroupMaster

DELETE FROM siTax.tStaticIncomeTaxGroup
DELETE FROM siTax.tStaticIncomeTaxSubGroup

DELETE FROM sCommon.tImportFieldMaster
DELETE FROM sCRM.tHostingTypeMaster
DELETE FROM sHrm.tMainLeaveTypeMaster

DELETE FROM sAppraisal.tConductIndicatorMaster
DELETE FROM sHrm.tTravelPeriodMaster
DELETE FROM sLoan.tInsterestTypeMaster

DELETE FROM sAppraisal.tBHRatingStatus
DELETE FROM sAppraisal.tConductIndicatorMaster
DELETE FROM sAppraisal.tKPAMeasureMaster
DELETE FROM sAppraisal.tKPATypeMaster
DELETE FROM sAppraisal.tRatingStatus
DELETE FROM sCommon.tHeaderDisplayMaster
DELETE FROM sCommon.tModuleGroupMaster
DELETE FROM sHrm.tLeaveTransactionMaster
DELETE FROM sCommon.tCheckFrequencyMaster

DELETE FROM sErp.tLeadAffiliationMaster
DELETE FROM sErp.tLeadSourceMaster
DELETE FROM sErp.tLeadStatusMaster

DELETE FROM sSystem.tStaticVersion

DELETE FROM sCommunication.tFeedBackAnswerGroupMaster

DELETE FROM sCommon.tSubmitDocumentFunctionalityMaster
DELETE FROM sSetup.tMandatoryFeild
DELETE FROM sSetup.tMandatoryFeildFunctionalityMaster

DELETE FROM sSystem.tTimeZone
DELETE FROM sTool.tTestCaseTypeMaster

DELETE FROM sAlumni.tEmployeementType

DELETE FROM sErp.tCampusTypeMaster

DELETE FROM sAlert.tMailTypeMaster
DELETE FROM sAlert.tSMSVendorMaster
DELETE FROM sCommon.tWeekOffRules

DELETE FROM sSecurity.tScreenHelp
DELETE FROM sSystem.tSettingInfo

DELETE FROM sProcurement.tOtherLocationSourceTypeMaster

DELETE FROM sCommon.tFieldTypeMaster
DELETE FROM sErp.tLeadInfrastructureMaster

DELETE FROM sHostel.tHostelEventMainTypeMaster

DELETE FROM sCertificate.tCertificateTypeMaster	
DELETE FROM sWorkflow.tActionStatusMaster
DELETE FROM sWorkflow.tApprovingDepartmentMaster
DELETE FROM sWorkflow.tWorkflowFunctionalityMaster

DELETE FROM sAcademic.tHomeworkCheckStatusMaster
DELETE FROM sAssessment.tExamTypeMaster

DELETE FROM sErp.tMarketingActivityMaster
DELETE FROM sErp.tMarketingSubActivityMaster
DELETE FROM sSetup.tCommonOrgGroupBatchMaster
DELETE FROM sWorkflow.tWorkflowFunctionalityMaster

DELETE FROM sAudit.tOperationMaster

DELETE FROM sAdmission.tInquiryMainStatusMaster
DELETE FROM sCertificate.tPrintTemplateFunctionalityMaster
DELETE FROM sErp.tTripLogStatusMaster

DELETE FROM sErp.tFollowupTypeMaster
DELETE FROM sErp.tSupportCategoryMaster
DELETE FROM sErp.tSupportPriorityMaster
DELETE FROM sErp.tSupportTicketStatusMaster


DELETE FROM sErp.tPlugInMaster
DELETE FROM sErp.tTagMaster

DELETE FROM sErp.tIssueTypeMaster

DELETE FROM sErp.tScreenFunctionalityMaster

DELETE FROM sHrm.tChangeTypeMaster


DELETE FROM sCommon.tDataMaster
DELETE FROM sCommon.tDataTypeMaster

DELETE FROM siTax.tStaticIncomeTaxSubSubGroup

DELETE FROM sCommunication.tStudentDocumentTypeMaster

DELETE FROM sCommon.tUploadFunctionalityMaster
DELETE FROM sCommunication.tEmployeeDocumentTypeMaster

DELETE FROM sErp.tCustomerMessageTypeMaster

DELETE FROM sActivity.tActivityMainTypeMaster
DELETE FROM sSecurity.tTraceabilityMaster
DELETE FROM sSecurity.tTraceabilityTrack

DELETE FROM sSecurity.tScreenScopeDetails
DELETE FROM sBiometric.tEmployeeConfigurationMaster
DELETE FROM sSetup.tEmployeeNameFormatMaster
DELETE FROM sStudent.tOnlineRegistrationDisplayFieldMaster

DELETE FROM sSetup.tFormTypeMaster
DELETE FROM sSetup.tFormButtonMaster

DELETE FROM sSecurity.tSysSuperScreen
DELETE FROM sAppraisal.tKPAStatus
--DELETE FROM sAttendance.tPeriodNoMaster

END
GO
PRINT N'Altering Procedure [sTool].[pUpgradeVersion]...';


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

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

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


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

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



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

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

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

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

-- update tablerowid master data from excel to table

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

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

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



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




exec [sTool].[pTableRowIdCurrentNumberSet] @rOrgGroupId

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


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

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


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


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

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

--static entry in tVisitorTypeMaster

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

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

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

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

--PeriodNoMaster Entry

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

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

END

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

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

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

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


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

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

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


			
			
END


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

END


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

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

END

UPDATE sSystem.tDatabaseInfo SET ApplicationId = 1

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

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

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

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

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

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

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

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

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

END
GO
PRINT N'Creating Procedure [sEMeeting].[pMeetingTypeMasterAdd]...';


GO

CREATE PROCEDURE [sEMeeting].[pMeetingTypeMasterAdd]
	@rTitle nvarchar(100),
	@rOrgGroupId smallint,
	@rIsObsolete bit = 0,
	@rCreatedUserId bigint

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

	BEGIN TRY

	BEGIN TRANSACTION	

	BEGIN

	INSERT INTO sEMeeting.tMeetingTypeMaster
	(
		Name,
		OrgGroupId,
		IsObsolete,
		CreatedUserId,
		CreatedDateTime
	)
	VALUES
	(
		@rTitle,
		@rOrgGroupId,
		@rIsObsolete,
		@rCreatedUserId,
		sCommon.fGetDate()
	)

		SELECT 1 AS Result
	END

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


GO

CREATE PROCEDURE [sEMeeting].[pOnlineMeetingScopeAdd]
			@rOnlineMeetingId bigint,
			@rScopeSourceTypeId smallint,
			@rScopeSourceId bigint,
			@rIsObsolete bit = 0,
			@rCreatedUserId bigint
           	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN

	BEGIN TRY

	BEGIN TRANSACTION	

	BEGIN

	If Exists(select OnlineMeetingId from sEMeeting.tOnlineMeetingScope where OnlineMeetingId=@rOnlineMeetingId AND ScopeSourceTypeId=@rScopeSourceTypeId
	AND ScopeSourceId=@rScopeSourceId)
		BEGIN
			SELECT @rScopeSourceId AS Result
			RETURN
		END 
ELSE
			BEGIN
			INSERT INTO sEMeeting.tOnlineMeetingScope
			(
			OnlineMeetingId,
			ScopeSourceTypeId,
			ScopeSourceId,
			IsObsolete,
			CreatedUserId,
			UpdatedUserId,
			CreatedDateTime,
			UpdatedDateTime
			)
			VALUES
			(
			@rOnlineMeetingId,
			@rScopeSourceTypeId,
			@rScopeSourceId,
			@rIsObsolete,
			@rCreatedUserId,
			@rCreatedUserId,
			sCommon.fGetDate(),
			sCommon.fGetDate()
			)
			SELECT 1 AS Result

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


GO

CREATE PROCEDURE [sEMeeting].[pOnlineMeetingScopeGet]
	@rOnlineMeetingId bigint

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

			 SELECT
			 OMS.OnlineMeetingId,
			 OMS.ScopeSourceTypeId,
			 OMS.ScopeSourceId,
			 OM.DisplayTitle AS Source,
			 'Organization' AS SourceType,
			 '' AS RollNo,
             '' AS Code,
             '' AS ClassDepartment,
             OM.DisplayTitle AS OrgName
			FROM sEMeeting.tOnlineMeetingScope OMS
			INNER JOIN sSetup.tOrganizationMaster OM
				ON OMS.ScopeSourceId=OM.Id
			WHERE OMS.OnlineMeetingId=@rOnlineMeetingId AND OMS.ScopeSourceTypeId=2021

			UNION ALL

			SELECT
			 OMS.OnlineMeetingId,
			 OMS.ScopeSourceTypeId,
			 OMS.ScopeSourceId,
			 DM.DisplayTitle AS Source,
			 'Department' AS SourceType,
			 '' AS RollNo,
             '' AS Code,
             DM.Title AS ClassDepartment,
             OM.DisplayTitle AS OrgName
			FROM sEMeeting.tOnlineMeetingScope OMS
			INNER JOIN sSetup.tDepartmentMaster DM
				ON OMS.ScopeSourceId=DM.Id
			INNER JOIN sSetup.tOrganizationMaster OM
				ON DM.OrgId=OM.Id 
			WHERE OMS.OnlineMeetingId=@rOnlineMeetingId AND OMS.ScopeSourceTypeId=2017

			UNION ALL

			SELECT
			 OMS.OnlineMeetingId,
			 OMS.ScopeSourceTypeId,
			 OMS.ScopeSourceId,
			 CM.DisplayTitle AS Source,
			 'Class' AS SourceType,
			 '' AS RollNo,
             '' AS Code,
             DMast.Title AS ClassDepartment,
             OM.DisplayTitle AS OrgName
			FROM sEMeeting.tOnlineMeetingScope OMS
			INNER JOIN  sSetup.tClassMaster CM
				ON OMS.ScopeSourceId=CM.Id
			INNER JOIN sSetup.tDepartmentMaster DMast
				ON CM.DepartmentId =DMast.Id		
			INNER JOIN sSetup.tOrganizationMaster OM
				ON DMast.OrgId=OM.Id
			WHERE OMS.OnlineMeetingId=@rOnlineMeetingId AND OMS.ScopeSourceTypeId=2016

			UNION ALL

			SELECT
			 OMS.OnlineMeetingId,
			 OMS.ScopeSourceTypeId,
			 OMS.ScopeSourceId,
			 DM.Code AS Source,
			 'Division' AS SourceType,
			 '' AS RollNo,
             '' AS Code,
             DMast.Title AS ClassDepartment,
             OM.DisplayTitle AS OrgName
			FROM sEMeeting.tOnlineMeetingScope OMS
			INNER JOIN   sSetup.tDivisionMaster DM
				ON OMS.ScopeSourceId=DM.Id
			INNER JOIN 	sSetup.tClassMaster CM
				ON DM.ClassId=CM.Id	
			INNER JOIN sSetup.tDepartmentMaster DMast
				ON CM.DepartmentId =DMast.Id
			INNER JOIN sSetup.tOrganizationMaster OM
				ON DMast.OrgId=OM.Id	
				WHERE OMS.OnlineMeetingId=@rOnlineMeetingId AND OMS.ScopeSourceTypeId=2005

			UNION ALL
			
			SELECT
			 OMS.OnlineMeetingId,
			 OMS.ScopeSourceTypeId,
			 OMS.ScopeSourceId,
			 [sStudent].[fStudentNameGet](SM.FirstName , SM.MiddleName, SM.LastName,OM.StudentNameFormatId ) AS Source,
			 'Student' AS SourceType,
			 SA.RollNo,
             SA.Code,
             SA.ClassName+' - '+SA.DivisionName AS ClassDepartment,
             OM.DisplayTitle AS OrgName
			FROM sEMeeting.tOnlineMeetingScope OMS
		    INNER JOIN sStudent.tStudentMaster SM
				ON OMS.ScopeSourceId=SM.Id
			INNER JOIN  sStudent.vStudentAcademic SA
				ON OMS.ScopeSourceId=SA.StudentId AND SA.IsActiveBatch=1 AND SA.StatusId=1		
			INNER JOIN sSetup.tOrganizationMaster OM
				ON SM.OrgId = OM.Id
			WHERE OMS.OnlineMeetingId=@rOnlineMeetingId AND OMS.ScopeSourceTypeId=2003
			
			UNION ALL
			
			SELECT
			 OMS.OnlineMeetingId,
			 OMS.ScopeSourceTypeId,
			 OMS.ScopeSourceId,
			 SA.Name AS Source,
			 'Student' AS SourceType,
			 SA.RollNo,
             SA.Code,
             SA.ClassName+' - '+SA.DivisionName AS ClassDepartment,
             OM.DisplayTitle AS OrgName
			FROM sEMeeting.tOnlineMeetingScope OMS
		   	INNER JOIN  sStudent.vStudentAcademic SA
				ON OMS.ScopeSourceId=SA.AcademicId AND SA.IsActiveBatch=1 AND SA.StatusId=1
			INNER JOIN sSetup.tOrganizationMaster OM
				ON SA.OrgId = OM.Id	
			WHERE OMS.OnlineMeetingId=@rOnlineMeetingId AND OMS.ScopeSourceTypeId=2001
			
			UNION ALL
			
			SELECT
			 OMS.OnlineMeetingId,
			 OMS.ScopeSourceTypeId,
			 OMS.ScopeSourceId,
			 vEC.FirstName +' '+ vEC.LastName AS Source,
			 'Employee' AS SourceType,
			 '' AS RollNo,
             vEC.Code,
             vEC.DepartmentName AS ClassDepartment,
             OM.DisplayTitle AS OrgName
			FROM sEMeeting.tOnlineMeetingScope OMS
			INNER JOIN sHrm.vEmployeeCommunication vEC 
				ON OMS.ScopeSourceId=vEC.EmployeeId AND vEC.StatusId=7
			INNER JOIN sSetup.tOrganizationMaster OM
				ON vEC.OrgId = OM.Id	
			WHERE OMS.OnlineMeetingId=@rOnlineMeetingId AND OMS.ScopeSourceTypeId=95

END
GO
PRINT N'Creating Procedure [sEMeeting].[pOnlineMeetingGet]...';


GO
 
CREATE PROCEDURE [sEMeeting].[pOnlineMeetingGet]
	 @rId bigint = 0,
	 @rTitle nvarchar(100) ='',
	 @rFromDate date = '',
	 @rToDate date = '',
	 @rEmployeeId bigint = 0,
	 @rMeetingTypeId smallint = 0,
	 @rIsCompleted int = -1,
	 @rUserId bigint = 0,
	 @rOnlineMeetingAccountId int = 0
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
BEGIN TRY

	if(@rId = 0)
	BEGIN 
	
	SELECT 
			OM.Id,
			EM.FirstName +' '+ EM.LastName as Teacher,
			DM.Title as MeetingType,
			CONVERT(NVARCHAR,OM.StartDate,103)+' '+CONVERT(NVARCHAR(5),OM.StartTime,108) as StartDate,
			CONVERT(NVARCHAR,OM.EndDate,103)+' '+CONVERT(NVARCHAR(5),OM.EndTime,108) as EndDate,
			OM.IsCompleted as Status,
		    ISNULL(OM.Title,'') as Title,
			OM.StartDate AS TeacherStartDate,
			OM.EndDate AS TeacherEndDate
	  FROM 
			sEMeeting.tOnlineMeeting OM
			
			INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id = OM.HostEmployeeId 
			INNER JOIN sCommon.tDataMaster DM ON DM.Id = OM.MeetingTypeId AND DM.DataTypeId = 3
	  WHERE 
  
				((OM.Title like @rTitle) OR (ISNULL(@rTitle,'') = ''))
			AND ((OM.StartDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
			AND ((OM.StartDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
			AND ((OM.HostEmployeeId = @rEmployeeId) OR (@rEmployeeId = 0))
			AND ((OM.MeetingTypeId = @rMeetingTypeId) OR (@rMeetingTypeId = 0))
			AND ((CONVERT(int,OM.IsCompleted)=@rIsCompleted) OR (@rIsCompleted = -1))
			AND OM.IsCompleted <> 721			
	 ORDER BY
			
			OM.StartDate , OM.StartTime asc
			SELECT
			 OMS.OnlineMeetingId,
			 OMS.ScopeSourceTypeId,
			 OMS.ScopeSourceId,
			 OM.DisplayTitle AS Source,
			 'Organization' AS SourceType,
			 '' AS ROllNo,
             '' AS Code,
             '' AS ClassDepartment,
             OM.DisplayTitle AS OrgName
			FROM sEMeeting.tOnlineMeetingScope OMS
			INNER JOIN sSetup.tOrganizationMaster OM
				ON OMS.ScopeSourceId=OM.Id
			WHERE OMS.OnlineMeetingId=@rId AND OMS.ScopeSourceTypeId=2021

			UNION ALL

			SELECT
			 OMS.OnlineMeetingId,
			 OMS.ScopeSourceTypeId,
			 OMS.ScopeSourceId,
			 DM.DisplayTitle AS Source,
			 'Department' AS SourceType,
			 '' AS ROllNo,
             '' AS Code,
             DM.Title AS ClassDepartment,
             OM.DisplayTitle AS OrgName
			FROM sEMeeting.tOnlineMeetingScope OMS
			INNER JOIN sSetup.tDepartmentMaster DM
				ON OMS.ScopeSourceId=DM.Id
			INNER JOIN sSetup.tOrganizationMaster OM
				ON DM.OrgId=OM.Id 
			WHERE OMS.OnlineMeetingId=@rId AND OMS.ScopeSourceTypeId=2017

			UNION ALL

			SELECT
			 OMS.OnlineMeetingId,
			 OMS.ScopeSourceTypeId,
			 OMS.ScopeSourceId,
			 CM.DisplayTitle AS Source,
			 'Class' AS SourceType,
			 '' AS ROllNo,
             '' AS Code,
             DMast.Title AS ClassDepartment,
             OM.DisplayTitle AS OrgName
			FROM sEMeeting.tOnlineMeetingScope OMS
			INNER JOIN  sSetup.tClassMaster CM
				ON OMS.ScopeSourceId=CM.Id
			INNER JOIN sSetup.tDepartmentMaster DMast
				ON CM.DepartmentId =DMast.Id		
			INNER JOIN sSetup.tOrganizationMaster OM
				ON DMast.OrgId=OM.Id
			WHERE OMS.OnlineMeetingId=@rId AND OMS.ScopeSourceTypeId=2016

			UNION ALL

			SELECT
			 OMS.OnlineMeetingId,
			 OMS.ScopeSourceTypeId,
			 OMS.ScopeSourceId,
			 DM.Code AS Source,
			 'Division' AS SourceType,
			 '' AS ROllNo,
             '' AS Code,
             DMast.Title AS ClassDepartment,
             OM.DisplayTitle AS OrgName
			FROM sEMeeting.tOnlineMeetingScope OMS
			INNER JOIN   sSetup.tDivisionMaster DM
				ON OMS.ScopeSourceId=DM.Id
			INNER JOIN 	sSetup.tClassMaster CM
				ON DM.ClassId=CM.Id	
			INNER JOIN sSetup.tDepartmentMaster DMast
				ON CM.DepartmentId =DMast.Id
			INNER JOIN sSetup.tOrganizationMaster OM
				ON DMast.OrgId=OM.Id	
				WHERE OMS.OnlineMeetingId=@rId AND OMS.ScopeSourceTypeId=2005

			UNION ALL
			
			SELECT
			 OMS.OnlineMeetingId,
			 OMS.ScopeSourceTypeId,
			 OMS.ScopeSourceId,
			 [sStudent].[fStudentNameGet](SM.FirstName , SM.MiddleName, SM.LastName,OM.StudentNameFormatId ) AS Source,
			 'Student' AS SourceType,
			 SA.ROllNo,
             SA.Code,
             SA.ClassName+' - '+SA.DivisionName AS ClassDepartment,
             OM.DisplayTitle AS OrgName
			FROM sEMeeting.tOnlineMeetingScope OMS
		    INNER JOIN sStudent.tStudentMaster SM
				ON OMS.ScopeSourceId=SM.Id
			INNER JOIN  sStudent.vStudentAcademic SA
				ON OMS.ScopeSourceId=SA.StudentId AND SA.IsActiveBatch=1 AND SA.StatusId=1		
			INNER JOIN sSetup.tOrganizationMaster OM
				ON SM.OrgId = OM.Id
			WHERE OMS.OnlineMeetingId=@rId AND OMS.ScopeSourceTypeId=2003
			
			UNION ALL
			
			SELECT
			 OMS.OnlineMeetingId,
			 OMS.ScopeSourceTypeId,
			 OMS.ScopeSourceId,
			 SA.Name AS Source,
			 'Student' AS SourceType,
			 SA.ROllNo,
             SA.Code,
             SA.ClassName+' - '+SA.DivisionName AS ClassDepartment,
             OM.DisplayTitle AS OrgName
			FROM sEMeeting.tOnlineMeetingScope OMS
		   	INNER JOIN  sStudent.vStudentAcademic SA
				ON OMS.ScopeSourceId=SA.AcademicId AND SA.IsActiveBatch=1 AND SA.StatusId=1
			INNER JOIN sSetup.tOrganizationMaster OM
				ON SA.OrgId = OM.Id	
			WHERE OMS.OnlineMeetingId=@rId AND OMS.ScopeSourceTypeId=2001
			
			UNION ALL
			
			SELECT
			 OMS.OnlineMeetingId,
			 OMS.ScopeSourceTypeId,
			 OMS.ScopeSourceId,
			 vEC.FirstName +' '+ vEC.LastName AS Source,
			 'Employee' AS SourceType,
			 '' AS ROllNo,
             vEC.Code,
             vEC.DepartmentName AS ClassDepartment,
             OM.DisplayTitle AS OrgName
			FROM sEMeeting.tOnlineMeetingScope OMS
			INNER JOIN sHrm.vEmployeeCommunication vEC 
				ON OMS.ScopeSourceId=vEC.EmployeeId AND vEC.StatusId=7
			INNER JOIN sSetup.tOrganizationMaster OM
				ON vEC.OrgId = OM.Id	
			WHERE OMS.OnlineMeetingId=@rId AND OMS.ScopeSourceTypeId=95
	END
	ELSE
	BEGIN
		SELECT 
			OM.Id,
			EM.EmployeeName as Teacher,
			Em.EmployeeId as TeacherId,
			DM.Title as MeetingType,
			DM.Id as MeetingTypeId,
			CONVERT(NVARCHAR,OM.StartDate) as StartDate,
			CONVERT(NVARCHAR,OM.StartTime,108) as StartTime,
			CONVERT(NVARCHAR,OM.EndDate) as EndDate,
			CONVERT(NVARCHAR,OM.EndTime,108) as EndTime,
			OM.IsCompleted as Status,
			OM.Title as MeetingTitle,
			OM.Description,
			OM.IsDisplayMeetingId,
			OM.MeetingId,
			OM.MeetingPassword,
			ISNULL(OM.IsReference,0) as IsReference,
			ISNULL(OM.IsResource,0) as IsResource,
			ISNULL(OM.IsCompleted,0) as IsCompleted,
			ISNULL(OM.IsMeetingStarted,0) as IsMeetingStarted,
			ISNULL(OMS.IsOnParticipantVideo,0) AS IsOnParticipantVideo,
			ISNULL(OMS.IsOnParticipantAudio,0) AS IsOnParticipantAudio,
			ISNULL(OMS.IsOnHostVideo,0) AS IsOnHostVideo,
			ISNULL(OMS.IsOnHostAudio,0) AS IsOnHostAudio,
			ISNULL(OMS.IsOnParticipantScreenShare,0) AS IsOnParticipantScreenShare,
			ISNULL(OMS.IsOnHostscreenShare,0) AS IsOnHostscreenShare,
			ISNULL(OM.MeetingAccountId,0) AS MeetingAccountId,
			ISNULL(OM.IsMeetingCreated,0) AS IsMeetingCreated,
			
			ISNULL(OMS.MeetingProviderId,0) As MeetingProviderId,



			OM.StartDate AS TeacherStartDate,
			OM.EndDate AS TeacherEndDate
	  FROM 
			sEMeeting.tOnlineMeeting OM
			
			INNER JOIN sHrm.vExtEmployee EM ON EM.EmployeeId = OM.HostEmployeeId 
			INNER JOIN sCommon.tDataMaster DM ON DM.Id = OM.MeetingTypeId AND DM.DataTypeId = 3
			LEFT JOIN sEMeeting.tOnlineMeetingSettings OMS ON OMS.OnlineMeetingId = OM.Id 
	  WHERE 
			(OM.Id = @rId) AND OM.IsCompleted <> 721
	  ORDER BY
			OM.StartDate , OM.StartTime asc
			SELECT
			 OMS.OnlineMeetingId,
			 OMS.ScopeSourceTypeId,
			 OMS.ScopeSourceId,
			 OM.DisplayTitle AS Source,
			 'Organization' AS SourceType,
			 '' AS ROllNo,
             '' AS Code,
             '' AS ClassDepartment,
             OM.DisplayTitle AS OrgName
			FROM sEMeeting.tOnlineMeetingScope OMS
			INNER JOIN sSetup.tOrganizationMaster OM
				ON OMS.ScopeSourceId=OM.Id
			WHERE OMS.OnlineMeetingId=@rId AND OMS.ScopeSourceTypeId=2021

			UNION ALL

			SELECT
			 OMS.OnlineMeetingId,
			 OMS.ScopeSourceTypeId,
			 OMS.ScopeSourceId,
			 DM.DisplayTitle AS Source,
			 'Department' AS SourceType,
			 '' AS ROllNo,
             '' AS Code,
             DM.Title AS ClassDepartment,
             OM.DisplayTitle AS OrgName
			FROM sEMeeting.tOnlineMeetingScope OMS
			INNER JOIN sSetup.tDepartmentMaster DM
				ON OMS.ScopeSourceId=DM.Id
			INNER JOIN sSetup.tOrganizationMaster OM
				ON DM.OrgId=OM.Id 
			WHERE OMS.OnlineMeetingId=@rId AND OMS.ScopeSourceTypeId=2017

			UNION ALL

			SELECT
			 OMS.OnlineMeetingId,
			 OMS.ScopeSourceTypeId,
			 OMS.ScopeSourceId,
			 CM.DisplayTitle AS Source,
			 'Class' AS SourceType,
			 '' AS ROllNo,
             '' AS Code,
             DMast.Title AS ClassDepartment,
             OM.DisplayTitle AS OrgName
			FROM sEMeeting.tOnlineMeetingScope OMS
			INNER JOIN  sSetup.tClassMaster CM
				ON OMS.ScopeSourceId=CM.Id
			INNER JOIN sSetup.tDepartmentMaster DMast
				ON CM.DepartmentId =DMast.Id		
			INNER JOIN sSetup.tOrganizationMaster OM
				ON DMast.OrgId=OM.Id
			WHERE OMS.OnlineMeetingId=@rId AND OMS.ScopeSourceTypeId=2016

			UNION ALL

			SELECT
			 OMS.OnlineMeetingId,
			 OMS.ScopeSourceTypeId,
			 OMS.ScopeSourceId,
			 DM.Code AS Source,
			 'Division' AS SourceType,
			 '' AS ROllNo,
             '' AS Code,
             DMast.Title AS ClassDepartment,
             OM.DisplayTitle AS OrgName
			FROM sEMeeting.tOnlineMeetingScope OMS
			INNER JOIN   sSetup.tDivisionMaster DM
				ON OMS.ScopeSourceId=DM.Id
			INNER JOIN 	sSetup.tClassMaster CM
				ON DM.ClassId=CM.Id	
			INNER JOIN sSetup.tDepartmentMaster DMast
				ON CM.DepartmentId =DMast.Id
			INNER JOIN sSetup.tOrganizationMaster OM
				ON DMast.OrgId=OM.Id	
				WHERE OMS.OnlineMeetingId=@rId AND OMS.ScopeSourceTypeId=2005

			UNION ALL
			
			SELECT
			 OMS.OnlineMeetingId,
			 OMS.ScopeSourceTypeId,
			 OMS.ScopeSourceId,
			 [sStudent].[fStudentNameGet](SM.FirstName , SM.MiddleName, SM.LastName,OM.StudentNameFormatId ) AS Source,
			 'Student' AS SourceType,
			 SA.ROllNo,
             SA.Code,
             SA.ClassName+' - '+SA.DivisionName AS ClassDepartment,
             OM.DisplayTitle AS OrgName
			FROM sEMeeting.tOnlineMeetingScope OMS
		    INNER JOIN sStudent.tStudentMaster SM
				ON OMS.ScopeSourceId=SM.Id
			INNER JOIN  sStudent.vStudentAcademic SA
				ON OMS.ScopeSourceId=SA.StudentId AND SA.IsActiveBatch=1 AND SA.StatusId=1		
			INNER JOIN sSetup.tOrganizationMaster OM
				ON SM.OrgId = OM.Id
			WHERE OMS.OnlineMeetingId=@rId AND OMS.ScopeSourceTypeId=2003
			
			UNION ALL
			
			SELECT
			 OMS.OnlineMeetingId,
			 OMS.ScopeSourceTypeId,
			 OMS.ScopeSourceId,
			 SA.Name AS Source,
			 'Student' AS SourceType,
			 SA.ROllNo,
             SA.Code,
             SA.ClassName+' - '+SA.DivisionName AS ClassDepartment,
             OM.DisplayTitle AS OrgName
			FROM sEMeeting.tOnlineMeetingScope OMS
		   	INNER JOIN  sStudent.vStudentAcademic SA
				ON OMS.ScopeSourceId=SA.AcademicId AND SA.IsActiveBatch=1 AND SA.StatusId=1
			INNER JOIN sSetup.tOrganizationMaster OM
				ON SA.OrgId = OM.Id	
			WHERE OMS.OnlineMeetingId=@rId AND OMS.ScopeSourceTypeId=2001
			
			UNION ALL
			
			SELECT
			 OMS.OnlineMeetingId,
			 OMS.ScopeSourceTypeId,
			 OMS.ScopeSourceId,
			 vEC.FirstName +' '+ vEC.LastName AS Source,
			 'Employee' AS SourceType,
			 '' AS ROllNo,
             vEC.Code,
             vEC.DepartmentName AS ClassDepartment,
             OM.DisplayTitle AS OrgName
			FROM sEMeeting.tOnlineMeetingScope OMS
			INNER JOIN sHrm.vEmployeeCommunication vEC 
				ON OMS.ScopeSourceId=vEC.EmployeeId AND vEC.StatusId=7
			INNER JOIN sSetup.tOrganizationMaster OM
				ON vEC.OrgId = OM.Id	
			WHERE OMS.OnlineMeetingId=@rId AND OMS.ScopeSourceTypeId=95
	END
END TRY
BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
END CATCH
END
GO
PRINT N'Creating Procedure [sEMeeting].[pOnlineMeetingAdd]...';


GO
 
CREATE PROCEDURE [sEMeeting].[pOnlineMeetingAdd]
	 
        @rId bigint = 0,
		@rOrgGroupId smallint,
		@rMeetingTypeId smallint,
		@rHostEmployeeId bigint,
		@rStartDate date,
		@rStartTime datetime,
		@rEndDate date,
		@rEndTime datetime,
		@rTitle nvarchar(100) = '',
		@rDescription nvarchar(max) = '',
		@rIsDisplayMeetingId bit = 0,
		@rMeetingId nvarchar(50) = '',
		@rMeetingPass nvarchar(50) = '',
		@rIsReference bit = 0,
		@rIsResource bit=0,
		@rIsCompleted bit = 0,
		@rIsMeetingStarted bit = 0,
		@rMeetingAccountId int = 0,
		@rIsMeetingCreated bit=0,
		@rIsObsolete bit = 0,
		@rCreatedUserId bigint,
		@rOnlineMeetingScopeList sEMeeting.OnlineMeetingScopeDetailType READONLY,
		@rOnlineMeetingReferenceList sEMeeting.OnlineMeetingReferenceDetailType READONLY
			
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	 
	 BEGIN TRANSACTION	
	 DECLARE @lNextNumber BIGINT 

	 DECLARE @lAccountEmailId NVARCHAR(200),@lAccountPassword NVARCHAR(200),@lAPIKey NVARCHAR(100),@lAPISecret NVARCHAR(100),@lWebAPIKey NVARCHAR(100),
	         @lWebAPISecret NVARCHAR(100),@lMeetingProviderId NVARCHAR(100),@lJWTToken NVARCHAR(MAX),@lOAuthAccountId NVARCHAR(MAX), @lOAuthClientId NVARCHAR(MAX),@lOAuthClientSecret NVARCHAR(MAX)

	SELECT @lAccountEmailId = AccountEmailId,@lAccountPassword = AccountPassword,@lAPIKey = APIKey,@lAPISecret = APISecret,@lWebAPIKey = WebAPIKey,@lWebAPISecret = WebAPISecret,@lMeetingProviderId = MeetingProviderId,
	@lJWTToken = JWTToken, @lOAuthAccountId = OAuthAccountId , @lOAuthClientId = OAuthClientId , @lOAuthClientSecret = OAuthClientSecret
	    FROM sAcademic.tOnlineMeetingAccount
		WHERE Id = @rMeetingAccountId

	IF(@rId = 0)	
	BEGIN
		
	EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sEMeeting.tOnlineMeeting', 0, 1, 1,@outNextNumber = @lNextNumber output
	Print @lNextNumber
	INSERT INTO sEMeeting.tOnlineMeeting
		(
			Id,
			OrgGroupId,
			MeetingTypeId,
			HostEmployeeId,
			StartDate,
			StartTime,
			EndDate,
			EndTime,
			Title,
			Description,
			IsDisplayMeetingId,
			MeetingId,
			MeetingPassword,
			IsReference,
			IsResource,
			IsCompleted,
			IsMeetingStarted,
			MeetingAccountId,
			IsMeetingCreated,
			IsObsolete,
			CreatedUserId,
			CreatedDateTime
		)
	VALUES
		(
			@lNextNumber,
			@rOrgGroupId,
			@rMeetingTypeId,
			@rHostEmployeeId,
			@rStartDate,
			@rStartTime,
			@rEndDate, 
			@rEndTime,
			@rTitle,
			@rDescription,
			@rIsDisplayMeetingId,
			@rMeetingId,
			@rMeetingPass,
			@rIsReference,
			@rIsResource,
			@rIsCompleted,
			@rIsMeetingStarted,
			@rMeetingAccountId,
			@rIsMeetingCreated,
			@rIsObsolete,
			@rCreatedUserId,
			GetUtcDate()
		)
		    
	INSERT INTO sEMeeting.tOnlineMeetingScope
			(
			OnlineMeetingId,
			ScopeSourceTypeId,
			ScopeSourceId,
			IsObsolete,
			CreatedUserId,
			CreatedDateTime
			)
			SELECT 
			@lNextNumber,
			ScopeSourceTypeId,
			ScopeSourceId,
			@rIsObsolete,
			@rCreatedUserId,
			GetUtcDate()
			from @rOnlineMeetingScopeList

	INSERT INTO sEMeeting.tOnlineMeetingReference
	(
	OnlineMeetingId,
	ReferencePath
	)
	SELECT
	@lNextNumber,
	ReferencePath
	from @rOnlineMeetingReferenceList

	END	 

ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE sEMeeting.tOnlineMeeting
	    SET
			 
           Id = @lNextNumber,
		   OrgGroupId = @rOrgGroupId,
		   MeetingTypeId = @rMeetingTypeId,
		   HostEmployeeId = @rHostEmployeeId,
		   StartDate = @rStartDate,
		   StartTime = @rStartTime,
		   EndDate = @rEndDate,
		   EndTime = @rEndTime,
		   Title = @rTitle,
		   Description = @rDescription,
		   IsDisplayMeetingId = @rIsDisplayMeetingId,
		   MeetingId = @rMeetingId,
		   MeetingPassword = @rMeetingPass,
		   IsReference = @rIsReference,
		   IsResource = @rIsResource,
		   IsCompleted = @rIsCompleted,
		   IsMeetingStarted = @rIsMeetingStarted,
		   MeetingAccountId = @rMeetingAccountId,
		   IsMeetingCreated = @rIsMeetingCreated,
		   IsObsolete = @rIsObsolete,
		   UpdatedUserId = @rCreatedUserId,
		   UpdatedDateTime = GetUtcDate()

	      WHERE Id = @rId
		  
		delete from sEMeeting.tOnlineMeetingScope where OnlineMeetingId = @rId

		INSERT INTO sEMeeting.tOnlineMeetingScope
			(
			OnlineMeetingId,
			ScopeSourceTypeId,
			ScopeSourceId,
			IsObsolete,
			UpdatedUserId,
			UpdatedDateTime
			)
			SELECT 
			@rId,
			ScopeSourceTypeId,
			ScopeSourceId,
			@rIsObsolete,
			@rCreatedUserId,
			GetUtcDate()
			from @rOnlineMeetingScopeList
		
		delete from sEMeeting.tOnlineMeetingReference where OnlineMeetingId = @rId

		INSERT INTO sEMeeting.tOnlineMeetingReference
			(
			OnlineMeetingId,
			ReferencePath
			)
			SELECT
			@rId,
			ReferencePath
			from @rOnlineMeetingReferenceList
		
	    SELECT 11 AS Result
	
	 END  	

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


GO

CREATE PROCEDURE [sEMeeting].[pMeetingTypeGet]
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	BEGIN
	BEGIN TRY
		SELECT
		MTM.AutoId AS Id,
		MTM.Name AS Title
		FROM sEMeeting.tMeetingTypeMaster MTM
		WHERE MTM.IsObsolete = 0
	END TRY
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
	END
GO
PRINT N'Creating Procedure [sEMeeting].[pMeetingAccountGet]...';


GO

CREATE PROCEDURE [sEMeeting].[pMeetingAccountGet]
		@rOrgGroupId smallint
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	BEGIN
	BEGIN TRY
		SELECT
		OMA.Id,
		OMA.AccountName AS Title
		FROM sAcademic.tOnlineMeetingAccount OMA
		WHERE OMA.IsObsolete = 0 AND OMA.OrgGroupId =  @rOrgGroupId
	END TRY
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
	END
GO
PRINT N'Creating Procedure [sEMeeting].[pOnlineMeetingTeacherGet]...';


GO

CREATE PROCEDURE [sEMeeting].[pOnlineMeetingTeacherGet]
	 
	 @rSourceId bigint,
	 @rSourceTypeId int,
	 @rOrgGroupId int,
	 @rUserId bigint,
	 @rIsOnlineLearningAdmin bit
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
BEGIN
	BEGIN TRY
	If (@rSourceTypeId = 95)
		BEGIN
		if(@rIsOnlineLearningAdmin = 'true')
			BEGIN
			SELECT EM.EmployeeId as Id, 
			[sHrm].[fEmployeeNameGet](EM.FirstName , EM.MiddleName, EM.LastName,ISNULL(OrgM.EmployeeNameFormatId,1)) AS Title 
			FROM sHrm.vExtEmployee EM 
			INNER JOIN sSetup.vUserOrganization OM ON OM.Id = EM.OrgId INNER JOIN sSetup.tOrganizationMaster OrgM 
			ON OrgM.Id=EM.OrgId 
			WHERE ISNULL(IsOtherUser,0) = 0 AND  StatusId =7  AND EmployeeGroupId = 1 AND OM.OrgGroupId = @rOrgGroupId AND OM.UserId = @rUserId
			ORDER BY Title
			END
		else
			BEGIN
			SELECT EM.EmployeeId as Id, 
			[sHrm].[fEmployeeNameGet](EM.FirstName , EM.MiddleName, EM.LastName,ISNULL(OrgM.EmployeeNameFormatId,1)) AS Title 
			FROM sHrm.vExtEmployee EM 
			INNER JOIN sSetup.tOrganizationMaster OrgM 
			ON OrgM.Id=EM.OrgId 
			WHERE ISNULL(EM.IsOtherUser,0) = 0 AND  EM.StatusId =7  AND EM.EmployeeGroupId = 1 AND  EM.EmployeeId = @rSourceId 
			ORDER BY EmployeeName
			END
		END
	else
		BEGIN
		SELECT EM.EmployeeId as Id,
		[sHrm].[fEmployeeNameGet](EM.FirstName , EM.MiddleName, EM.LastName,ISNULL(OrgM.EmployeeNameFormatId,1)) AS Title 
		FROM sHrm.vExtEmployee EM 
		INNER JOIN sSetup.vUserOrganization OM ON OM.Id = EM.OrgId INNER JOIN sSetup.tOrganizationMaster OrgM 
		ON OrgM.Id=EM.OrgId 
		WHERE ISNULL(IsOtherUser,0) = 0 AND  StatusId =7  AND EmployeeGroupId = 1 AND OM.OrgGroupId = @rOrgGroupId AND OM.UserId = @rUserId 
		ORDER BY EmployeeName
		END
	END TRY

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


GO

 
 
CREATE PROCEDURE [sEMeeting].[pOnlineMeetingTeacherStudentListGet]
	 
	 @rSourceId bigint,
	 @rSourceTypeId int,
	 @rMeetingTypeId int = 0,
	 @rStartDate date = '',
	 @rEndDate date = '',
	 @rIsCompleted int=-1,
	 @rTitle nvarchar(100) ='',
	 @rOrgGroupBatchId int
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
BEGIN 
	 DECLARE @lConfigValue nvarchar(50)=''

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

	 IF @lConfigValue = ''
		SET @lConfigValue = 'False'
	 Print @lConfigValue
	  DECLARE @lAcademicId bigint,@lStudentId bigint,@lClassId int,@lDivisionId int,@lOrgId int,@lDepartmentId int,@lEmployeeId bigint,
	 @lClassName nvarchar(100)


	 SELECT @lAcademicId = A.Id,@lStudentId = A.StudentId,@lClassId = A.ClassId, @lDivisionId = A.DivisionId, @lOrgId= A.OrgId, @lDepartmentId=CM.DepartmentId,
		@lClassName=CM.Title,@lCLassId=CM.Id
     FROM sStudent.tAcademic A INNER JOIN sSetup.tBatchMaster BM ON A.BatchId = BM.Id 
	 INNER JOIN sSetup.tClassMaster CM ON CM.Id = A.ClassId
	 WHERE A.Id = @rSourceId AND BM.OrgGroupBatchId = @rOrgGroupBatchId
	 
	 IF(@lConfigValue = 'True')
  BEGIN
	 If (@rSourceTypeId = 2001)
	 BEGIN
	
	  SELECT 
			OM.Id,
			DM.Title AS MeetingType,
			ISNULL(EM.FirstName,'') +' ' + ISNULL(EM.MiddleName,'') +' ' + ISNULL(EM.LastName ,'') AS Teacher,
			CONVERT(NVARCHAR,OM.StartDate,103)+' '+CONVERT(NVARCHAR(5),OM.StartTime,108) as StartDate,
			CONVERT(NVARCHAR,OM.EndDate,103)+' '+CONVERT(NVARCHAR(5),OM.EndTime,108) as EndDate,
			(CASE WHEN OM.IsCompleted=0 THEN 'Pending' WHEN OM.IsCompleted=1 THEN 'Completed'  WHEN OM.IsCompleted=721 THEN 'Cancel' END) AS Status,
			ISNULL(OM.Title,'') AS Title
			
		FROM 
				sEMeeting.tOnlineMeeting OM
				INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id = OM.HostEmployeeId 
				INNER JOIN sCommon.tDataMaster DM ON DM.Id = OM.MeetingTypeId AND DM.DataTypeId = 3
				INNER JOIN (SELECT OMS.OnlineMeetingId FROM sEMeeting.tOnlineMeetingScope OMS
				WHERE (
				( 
				(OMS.ScopeSourceTypeId = 2021 AND OMS.ScopeSourceId =@lOrgId) 
				OR
				(OMS.ScopeSourceTypeId = 2017 AND OMS.ScopeSourceId =@lDepartmentId) OR
				(OMS.ScopeSourceTypeId = 2016 AND OMS.ScopeSourceId =@lClassId) OR
				(OMS.ScopeSourceTypeId = 2005 AND OMS.ScopeSourceId =@lDivisionId) OR
				(OMS.ScopeSourceTypeId = 2003 AND OMS.ScopeSourceId =@lStudentId) OR
				(OMS.ScopeSourceTypeId = 2001 AND OMS.ScopeSourceId =@lAcademicId)
				 ))
				) D
				ON D.OnlineMeetingId= OM.Id

			WHERE
				((OM.Title like '%' +@rTitle+ '%') OR (ISNULL(@rTitle,'')=''))
				AND ((OM.EndDate >= CASE WHEN OM.MeetingTypeId = 1 THEN CONVERT(varchar,GETDATE(),23) ELSE '1900-01-01' END)) 
				AND ((OM.StartDate <= CASE WHEN OM.MeetingTypeId = 1 THEN CONVERT(varchar,GETDATE(),23) ELSE '9999-01-01' END))
				AND ((OM.StartTime <= CASE WHEN OM.MeetingTypeId = 1 AND OM.StartDate = CONVERT(varchar,GETDATE(),23) THEN CONVERT(varchar,GETDATE(),14) ELSE OM.StartTime END)) 
				AND ((OM.EndTime >= CASE WHEN OM.MeetingTypeId = 1  AND OM.EndDate = CONVERT(varchar,GETDATE(),23)THEN CONVERT(varchar,GETDATE(),14) ELSE OM.EndTime END))
				AND ((OM.StartDate >= @rStartDate) OR (ISNULL(@rStartDate,'')=''))
				AND ((OM.StartDate <= @rEndDate) OR (ISNULL(@rEndDate,'')=''))
				AND ((OM.MeetingTypeId = @rMeetingTypeId)OR (ISNULL(@rMeetingTypeId,0)=0))
				AND ((Convert(int,OM.IsCompleted)=@rIsCompleted) OR (@rIsCompleted = -1))
				AND OM.IsCompleted <> 721
				
				ORDER BY OM.IsCompleted,OM.StartDate,OM.StartTime,OM.EndDate
			END
		
	IF (@rSourceTypeId = 95)
	BEGIN 
		SELECT 
			OM.Id,
			DM.Title AS MeetingType,
			ISNULL(EM.FirstName,'') +' ' + ISNULL(EM.MiddleName,'') +' ' + ISNULL(EM.LastName ,'') AS Teacher,
			CONVERT(NVARCHAR,OM.StartDate,103)+' '+CONVERT(NVARCHAR(5),OM.StartTime,108) as StartDate,
			CONVERT(NVARCHAR,OM.EndDate,103)+' '+CONVERT(NVARCHAR(5),OM.EndTime,108) as EndDate,
			(CASE WHEN OM.IsCompleted=0 THEN 'Pending' WHEN OM.IsCompleted=1 THEN 'Completed'  WHEN OM.IsCompleted=721 THEN 'Cancel' END) AS Status,
			ISNULL(OM.Title,'') As Title,
			OM.StartDate AS TeacherStartDateTime,
			OM.StartDate AS TeacherEndDateTime
			FROM 
				sEMeeting.tOnlineMeeting OM
				INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id = OM.HostEmployeeId
				INNER JOIN sCommon.tDataMaster DM ON DM.Id = OM.MeetingTypeId AND DM.DataTypeId = 3

			WHERE
				((OM.MeetingTypeId = @rMeetingTypeId) OR (@rMeetingTypeId = 0))
				AND ((OM.EndDate >= CASE WHEN OM.MeetingTypeId = 1 THEN CONVERT(varchar,GETDATE(),23) ELSE '1900-01-01' END)) 
				AND ((OM.StartDate <= CASE WHEN OM.MeetingTypeId = 1 THEN CONVERT(varchar,GETDATE(),23) ELSE '9999-01-01' END))
				AND ((OM.StartTime <= CASE WHEN OM.MeetingTypeId = 1 AND OM.StartDate = CONVERT(varchar,GETDATE(),23) THEN CONVERT(varchar,GETDATE(),14) ELSE OM.StartTime END)) 
				AND ((OM.EndTime >= CASE WHEN OM.MeetingTypeId = 1 AND OM.EndDate = CONVERT(varchar,GETDATE(),23) THEN CONVERT(varchar,GETDATE(),14) ELSE OM.EndTime END))
				AND ((OM.StartDate >= @rStartDate) OR (ISNULL(@rStartDate,'')=''))
				AND ((OM.StartDate <= @rEndDate) OR (ISNULL(@rEndDate,'')=''))
				AND (OM.HostEmployeeId = @rSourceId)
				AND ((Convert(int,OM.IsCompleted)=@rIsCompleted) OR (@rIsCompleted = -1))
				AND ((OM.Title like '%' +@rTitle+ '%') OR (ISNULL(@rTitle,'')=''))
				AND OM.IsCompleted <> 721
				ORDER BY OM.IsCompleted,OM.StartDate,OM.StartTime,OM.EndDate
		END
				
		END	
	ELSE IF(@lConfigValue = 'False')
	BEGIN
		If (@rSourceTypeId = 2001)
	 BEGIN
	
	  SELECT 
			OM.Id,
			DM.Title AS MeetingType,
			ISNULL(EM.FirstName,'') +' ' + ISNULL(EM.MiddleName,'') +' ' + ISNULL(EM.LastName ,'') AS Teacher,
			CONVERT(NVARCHAR,OM.StartDate,103)+' '+CONVERT(NVARCHAR(5),OM.StartTime,108) as StartDate,
			CONVERT(NVARCHAR,OM.EndDate,103)+' '+CONVERT(NVARCHAR(5),OM.EndTime,108) as EndDate,
			(CASE WHEN OM.IsCompleted=0 THEN 'Pending' WHEN OM.IsCompleted=1 THEN 'Completed'  WHEN OM.IsCompleted=721 THEN 'Cancel' END) AS Status,
			ISNULL(OM.Title,'') AS Title
		
		FROM 
				sEMeeting.tOnlineMeeting OM
				
				INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id = OM.HostEmployeeId 
				INNER JOIN sCommon.tDataMaster DM ON DM.Id = OM.MeetingTypeId AND DM.DataTypeId = 3
				INNER JOIN (SELECT OMS.OnlineMeetingId FROM sEMeeting.tOnlineMeetingScope OMS
				WHERE (
				( 
				(OMS.ScopeSourceTypeId = 2021 AND OMS.ScopeSourceId =@lOrgId) 
				OR
				(OMS.ScopeSourceTypeId = 2017 AND OMS.ScopeSourceId =@lDepartmentId) OR
				(OMS.ScopeSourceTypeId = 2016 AND OMS.ScopeSourceId =@lClassId) OR
				(OMS.ScopeSourceTypeId = 2005 AND OMS.ScopeSourceId =@lDivisionId) OR
				(OMS.ScopeSourceTypeId = 2003 AND OMS.ScopeSourceId =@lStudentId) OR
				(OMS.ScopeSourceTypeId = 2001 AND OMS.ScopeSourceId =@lAcademicId)
				 ))
				) D
				ON D.OnlineMeetingId= OM.Id

			WHERE
				((OM.Title like '%' +@rTitle+ '%') OR (ISNULL(@rTitle,'')=''))
				AND ((OM.StartDate >= @rStartDate) OR (ISNULL(@rStartDate,'')=''))
				AND ((OM.StartDate <= @rEndDate) OR (ISNULL(@rEndDate,'')=''))
				AND ((OM.MeetingTypeId = @rMeetingTypeId)OR (ISNULL(@rMeetingTypeId,0)=0))
				AND ((Convert(int,OM.IsCompleted)=@rIsCompleted) OR (@rIsCompleted = -1))
				AND OM.IsCompleted <> 721
				
				ORDER BY OM.IsCompleted,OM.StartDate,OM.StartTime,OM.EndDate
			END
		
			IF (@rSourceTypeId = 95)
			BEGIN 
			SELECT 
				OM.Id,
				DM.Title AS MeetingType,
				--EM.EmployeeName AS Teacher,
				CONVERT(NVARCHAR,OM.StartDate,103)+' '+CONVERT(NVARCHAR(5),OM.StartTime,108) as StartDate,
				CONVERT(NVARCHAR,OM.EndDate,103)+' '+CONVERT(NVARCHAR(5),OM.EndTime,108) as EndDate,
				(CASE WHEN OM.IsCompleted=0 THEN 'Pending' WHEN OM.IsCompleted=1 THEN 'Completed'  WHEN OM.IsCompleted=721 THEN 'Cancel' END) AS Status,
				ISNULL(OM.Title,'') As Title,
				OM.StartDate AS TeacherStartDateTime,
			    OM.StartDate AS TeacherEndDateTime
			
				FROM 
					sEMeeting.tOnlineMeeting OM
					INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id = OM.HostEmployeeId
					INNER JOIN sCommon.tDataMaster DM ON DM.Id = OM.MeetingTypeId AND DM.DataTypeId = 3

				WHERE
					((OM.MeetingTypeId = @rMeetingTypeId) OR (@rMeetingTypeId = 0))
					AND ((OM.StartDate >= @rStartDate) OR (ISNULL(@rStartDate,'')=''))
					AND ((OM.StartDate <= @rEndDate) OR (ISNULL(@rEndDate,'')=''))
					AND (OM.HostEmployeeId = @rSourceId)
					AND ((Convert(int,OM.IsCompleted)=@rIsCompleted) OR (@rIsCompleted = -1))
					AND ((OM.Title like '%' +@rTitle+ '%') OR (ISNULL(@rTitle,'')=''))
					AND OM.IsCompleted <> 721
					ORDER BY OM.IsCompleted,OM.StartDate,OM.StartTime,OM.EndDate
			END
	END
END
GO
PRINT N'Creating Procedure [sPurchase].[pPurchaseOrderApprovedGet]...';


GO








CREATE PROCEDURE [sPurchase].[pPurchaseOrderApprovedGet]
	  @rId int
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
		select PO.Id,
			   PO.RefNumber,
			   PO.PurchaseRequestId,
			   PO.RequestedBy,
			   PO.StatusId,
			   PO.VendorId,
			   PO.LocationId,
			   PO.OrgGroupId,
			   PO.PODate,
			   PO.BillToAddress,
			   PO.ShipToAddress,
			   PO.RequiredBy,
			   ISNULL(SM.Title,'') as Status,
			   VM.Code AS VendorCode,
			   VM.Title AS VendorName 
		from   [sPurchase].[tPurchaseOrder] PO(nolock) 
			   Left JOIN sProcurement.tVendorMaster  VM on PO.VendorId = VM.ID 
			   Left Join [sWf].[tWfStatusMaster] SM ON SM.Id = PO.StatusId
		where  PO.Id=@rId AND PO.IsObsolete = 0 AND PO.StatusId = 3

		select POD.Id,
			   POD.PurchaseOrderId,
			   POD.OrgGroupId,
			   POD.PurchaseRequestDetailId,
			   POD.StockItemId,
			   POD.TotalQty,
			   POD.Remark, 
			   SIM.Code				AS StockItemCode,
			   SIM.Title				AS StockItemName,
			   SUMa.Code				AS UOM
		from   [sPurchase].[tPurchaseOrderDetail] POD (nolock)
			   Inner JOIN	sPurchase.tPurchaseOrder PO	ON PO.Id = POD.PurchaseOrderId AND PO.IsObsolete = 0 AND PO.StatusId = 3
			   Inner JOIN	sIp.tStockItemMaster SIM	ON SIM.Id = POD.StockItemId 
			   Inner JOIN  sFinanceCommon.tStockUomMaster SUMa ON SUMa.Id = SIM.IssueStockUomId
		where  PurchaseOrderId=@rId
	END TRY

	BEGIN CATCH
    IF @@TRANCOUNT > 0
        ROLLBACK TRAN --RollBack in case of Error
    
    DECLARE @ErrorMessage NVARCHAR(4000);  
    DECLARE @ErrorSeverity INT;  
    DECLARE @ErrorState INT;  
    SELECT   
       @ErrorMessage = ERROR_MESSAGE(),  
       @ErrorSeverity = ERROR_SEVERITY(),  
       @ErrorState = ERROR_STATE();  
    RAISERROR (@ErrorMessage, @ErrorSeverity, @ErrorState);  
    
	END CATCH

END
GO
PRINT N'Creating Procedure [sPurchase].[pPurchaseOrderApprovedSearchGet]...';


GO





CREATE PROCEDURE [sPurchase].[pPurchaseOrderApprovedSearchGet]

	@rNumber nvarchar(30) = '',
	@rLocationId int,
	@rName nvarchar,
	@rOrgGroupId int

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY


		If @rNumber = NULL SET @rNumber=''
		If @rName = NULL SET @rName=''

	    SELECT		
				PO.Id, 
				PO.RefNumber as Number,
				PO.RequestedBy, 
				PO.LocationId, 
				PO.PODate
		FROM		
				sPurchase.tPurchaseOrder PO (nolock)
		WHERE 
				((PO.RefNumber like @rNumber+'%') OR (@rNumber = ''))
   				AND ((PO.RequestedBy like @rName+'%') OR (@rName = ''))
   				--AND ((SLM.Id = @rStoreLocationId) OR (@rStoreLocationId = 0))
   				AND ((PO.OrgGroupId = @rOrgGroupId) OR (@rOrgGroupId=0))
				AND PO.IsObsolete = 0 and PO.StatusId = 3
	 END TRY

	BEGIN CATCH
    IF @@TRANCOUNT > 0
        ROLLBACK TRAN --RollBack in case of Error
    
    DECLARE @ErrorMessage NVARCHAR(4000);  
    DECLARE @ErrorSeverity INT;  
    DECLARE @ErrorState INT;  
    SELECT   
       @ErrorMessage = ERROR_MESSAGE(),  
       @ErrorSeverity = ERROR_SEVERITY(),  
       @ErrorState = ERROR_STATE();  
    RAISERROR (@ErrorMessage, @ErrorSeverity, @ErrorState);  
    
	END CATCH  		  
END
GO
PRINT N'Creating Procedure [sPurchase].[pPurchaseOrderGet]...';


GO








CREATE PROCEDURE [sPurchase].[pPurchaseOrderGet]
	  @rId int
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
		select PO.Id,
			   PO.RefNumber,
			   PO.PurchaseRequestId,
			   PO.RequestedBy,
			   PO.StatusId,
			   PO.VendorId,
			   PO.LocationId,
			   PO.OrgGroupId,
			   PO.PODate,
			   PO.BillToAddress,
			   PO.ShipToAddress,
			   PO.RequiredBy,
			   ISNULL(SM.Title,'') as Status,
			   VM.Code AS VendorCode,
			   VM.Title AS VendorName 
		from   [sPurchase].[tPurchaseOrder] PO(nolock) 
			   Left JOIN sProcurement.tVendorMaster  VM on PO.VendorId = VM.ID
			   Left Join [sWf].[tWfStatusMaster] SM ON SM.Id = PO.StatusId
		where  PO.Id = @rId AND PO.IsObsolete = 0

		select POD.Id,
			   POD.PurchaseOrderId,
			   POD.PurchaseRequestDetailId,
			   POD.OrgGroupId,
			   POD.StockItemId,
			   POD.TotalQty,
			   POD.Remark, 
			   SIM.Code				AS StockItemCode,
			   SIM.Title				AS StockItemName,
			   SUMa.Code				AS UOM
		from   [sPurchase].[tPurchaseOrderDetail] POD (nolock)
			   Inner JOIN	sPurchase.tPurchaseOrder PO	ON PO.Id = POD.PurchaseOrderId AND PO.IsObsolete = 0
			   Inner JOIN	sIp.tStockItemMaster SIM	ON SIM.Id = POD.StockItemId 
			   Inner JOIN  sFinanceCommon.tStockUomMaster SUMa ON SUMa.Id = SIM.IssueStockUomId
		where  POD.PurchaseOrderId = @rId
	END TRY

	BEGIN CATCH
    IF @@TRANCOUNT > 0
        ROLLBACK TRAN --RollBack in case of Error
    
    DECLARE @ErrorMessage NVARCHAR(4000);  
    DECLARE @ErrorSeverity INT;  
    DECLARE @ErrorState INT;  
    SELECT   
       @ErrorMessage = ERROR_MESSAGE(),  
       @ErrorSeverity = ERROR_SEVERITY(),  
       @ErrorState = ERROR_STATE();  
    RAISERROR (@ErrorMessage, @ErrorSeverity, @ErrorState);  
    
	END CATCH

END
GO
PRINT N'Creating Procedure [sPurchase].[pPurchaseOrderSearchGet]...';


GO



CREATE PROCEDURE [sPurchase].[pPurchaseOrderSearchGet]

	@rNumber nvarchar(30) = '',
	@rLocationId int,
	@rName nvarchar,
	@rOrgGroupId int

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY


		If @rNumber = NULL SET @rNumber=''
		If @rName = NULL SET @rName=''

	    SELECT		
				PO.Id,
				PO.PurchaseRequestId,
				PO.RefNumber as Number,
				PO.RequestedBy, 
				PO.LocationId, 
				PO.PODate
		FROM		
				sPurchase.tPurchaseOrder PO (nolock)
		WHERE 
				((PO.RefNumber like @rNumber+'%') OR (@rNumber = ''))
   				AND ((PO.RequestedBy like @rName+'%') OR (@rName = ''))
   				--AND ((SLM.Id = @rStoreLocationId) OR (@rStoreLocationId = 0))
   				AND ((PO.OrgGroupId = @rOrgGroupId) OR (@rOrgGroupId=0))
				AND PO.IsObsolete = 0
	 END TRY

	BEGIN CATCH
    IF @@TRANCOUNT > 0
        ROLLBACK TRAN --RollBack in case of Error
    
    DECLARE @ErrorMessage NVARCHAR(4000);  
    DECLARE @ErrorSeverity INT;  
    DECLARE @ErrorState INT;  
    SELECT   
       @ErrorMessage = ERROR_MESSAGE(),  
       @ErrorSeverity = ERROR_SEVERITY(),  
       @ErrorState = ERROR_STATE();  
    RAISERROR (@ErrorMessage, @ErrorSeverity, @ErrorState);  
    
	END CATCH  		  
END
GO
PRINT N'Creating Procedure [sPurchase].[pPurchaseRequestApprovedGet]...';


GO







CREATE PROCEDURE [sPurchase].[pPurchaseRequestApprovedGet]
	  @rId int
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
		select PR.Id,
			   PR.Number,
			   PR.RequestedBy,
			   PR.StatusId,
			   PR.VendorId,
			   PR.LocationId,
			   PR.BranchId,
			   PR.OrgGroupId,
			   PR.ResourceId,
			   PR.RequestDate,
			   PR.RequiredBy,
			   ISNULL(SM.Title,'') as Status 
		from   [sPurchase].[tPurchaseRequest] PR (nolock) 
			   Left Join [sWf].[tWfStatusMaster] SM ON SM.Id = PR.StatusId
		where  PR.Id=@rId AND PR.IsObsolete = 0 AND PR.StatusId = 3

		select PRD.Id,
			   PRD.PurchaseRequestId,
			   PRD.OrgGroupId,
			   PRD.StockItemId,
			   PRD.RequestedQty,
			   PRD.Remark, 
			   SIM.Code				AS StockItemCode,
			   SIM.Title				AS StockItemName,
			   SUMa.Code				AS UOM
		from   [sPurchase].[tPurchaseRequestDetail] PRD (nolock)
			   Inner JOIN	sPurchase.tPurchaseRequest PR	ON PR.Id = PRD.PurchaseRequestId AND PR.IsObsolete = 0 AND PR.StatusId = 3
			   Inner JOIN	sIp.tStockItemMaster SIM	ON SIM.Id = PRD.StockItemId 
			   Inner JOIN  sFinanceCommon.tStockUomMaster SUMa ON SUMa.Id = SIM.IssueStockUomId
		where  PurchaseRequestId=@rId
	END TRY

	BEGIN CATCH
    IF @@TRANCOUNT > 0
        ROLLBACK TRAN --RollBack in case of Error
    
    DECLARE @ErrorMessage NVARCHAR(4000);  
    DECLARE @ErrorSeverity INT;  
    DECLARE @ErrorState INT;  
    SELECT   
       @ErrorMessage = ERROR_MESSAGE(),  
       @ErrorSeverity = ERROR_SEVERITY(),  
       @ErrorState = ERROR_STATE();  
    RAISERROR (@ErrorMessage, @ErrorSeverity, @ErrorState);  
    
	END CATCH

END
GO
PRINT N'Creating Procedure [sPurchase].[pPurchaseRequestApprovedSearchGet]...';


GO


CREATE PROCEDURE [sPurchase].[pPurchaseRequestApprovedSearchGet]

	@rNumber nvarchar(30) = '',
	@rLocationId int,
	@rName nvarchar,
	@rOrgGroupId int

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY


		If @rNumber = NULL SET @rNumber=''
		If @rName = NULL SET @rName=''

	    SELECT		
				PR.Id, 
				PR.Number,
				PR.RequestedBy, 
				PR.LocationId, 
				PR.RequestDate
		FROM		
				sPurchase.tPurchaseRequest PR (nolock)
		WHERE 
				((PR.Number like @rNumber+'%') OR (@rNumber = ''))
   				AND ((PR.RequestedBy like @rName+'%') OR (@rName = ''))
   				--AND ((SLM.Id = @rStoreLocationId) OR (@rStoreLocationId = 0))
   				AND ((PR.OrgGroupId = @rOrgGroupId) OR (@rOrgGroupId=0))
				AND PR.IsObsolete = 0 and PR.StatusId = 3
	 END TRY

	BEGIN CATCH
    IF @@TRANCOUNT > 0
        ROLLBACK TRAN --RollBack in case of Error
    
    DECLARE @ErrorMessage NVARCHAR(4000);  
    DECLARE @ErrorSeverity INT;  
    DECLARE @ErrorState INT;  
    SELECT   
       @ErrorMessage = ERROR_MESSAGE(),  
       @ErrorSeverity = ERROR_SEVERITY(),  
       @ErrorState = ERROR_STATE();  
    RAISERROR (@ErrorMessage, @ErrorSeverity, @ErrorState);  
    
	END CATCH  		  
END
GO
PRINT N'Creating Procedure [sPurchase].[pPurchaseRequestGet]...';


GO


CREATE PROCEDURE [sPurchase].[pPurchaseRequestGet]
	  @rId int
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
		select  PR.Id,
				PR.Number,
				PR.RequestedBy,
				PR.StatusId,
				PR.VendorId,
				PR.LocationId,
				PR.BranchId,
				PR.OrgGroupId,
				PR.ResourceId,
				PR.RequestDate,
				PR.RequiredBy,
				ISNULL(SM.Title,'') as Status,
				VM.Code AS VendorCode,
				VM.Title AS VendorName
		from    [sPurchase].[tPurchaseRequest] PR (nolock) 
			    Left Join sProcurement.tVendorMaster  VM on PR.VendorId = VM.ID
				Left Join [sWf].[tWfStatusMaster] SM ON SM.Id = PR.StatusId
		where   PR.Id=@rId AND PR.IsObsolete = 0

		select PRD.Id,
			   PRD.PurchaseRequestId,
			   PRD.OrgGroupId,
			   PRD.StockItemId,
			   PRD.RequestedQty,
			   PRD.Remark, 
			   SIM.Code				AS StockItemCode,
			   SIM.Title				AS StockItemName,
			   SUMa.Code				AS UOM
		from   [sPurchase].[tPurchaseRequestDetail] PRD (nolock)
			   Inner JOIN	sPurchase.tPurchaseRequest PR	ON PR.Id = PRD.PurchaseRequestId AND PR.IsObsolete = 0
			   Inner JOIN	sIp.tStockItemMaster SIM	ON SIM.Id = PRD.StockItemId 
			   Inner JOIN  sFinanceCommon.tStockUomMaster SUMa ON SUMa.Id = SIM.IssueStockUomId
		where  PurchaseRequestId=@rId
	END TRY

	BEGIN CATCH
    IF @@TRANCOUNT > 0
        ROLLBACK TRAN --RollBack in case of Error
    
    DECLARE @ErrorMessage NVARCHAR(4000);  
    DECLARE @ErrorSeverity INT;  
    DECLARE @ErrorState INT;  
    SELECT   
       @ErrorMessage = ERROR_MESSAGE(),  
       @ErrorSeverity = ERROR_SEVERITY(),  
       @ErrorState = ERROR_STATE();  
    RAISERROR (@ErrorMessage, @ErrorSeverity, @ErrorState);  
    
	END CATCH

END
GO
PRINT N'Creating Procedure [sPurchase].[pPurchaseRequestSearchGet]...';


GO


CREATE PROCEDURE [sPurchase].[pPurchaseRequestSearchGet]

	@rNumber nvarchar(30) = '',
	@rLocationId int,
	@rName nvarchar,
	@rOrgGroupId int

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY


		If @rNumber = NULL SET @rNumber=''
		If @rName = NULL SET @rName=''

	    SELECT		
				PR.Id, 
				PR.Number,
				PR.RequestedBy, 
				PR.LocationId, 
				PR.RequestDate
		FROM		
				sPurchase.tPurchaseRequest PR (nolock)
		WHERE 
				((PR.Number like @rNumber+'%') OR (@rNumber = ''))
   				AND ((PR.RequestedBy like @rName+'%') OR (@rName = ''))
   				--AND ((SLM.Id = @rStoreLocationId) OR (@rStoreLocationId = 0))
   				AND ((PR.OrgGroupId = @rOrgGroupId) OR (@rOrgGroupId=0))
				AND PR.IsObsolete = 0
	 END TRY

	BEGIN CATCH
    IF @@TRANCOUNT > 0
        ROLLBACK TRAN --RollBack in case of Error
    
    DECLARE @ErrorMessage NVARCHAR(4000);  
    DECLARE @ErrorSeverity INT;  
    DECLARE @ErrorState INT;  
    SELECT   
       @ErrorMessage = ERROR_MESSAGE(),  
       @ErrorSeverity = ERROR_SEVERITY(),  
       @ErrorState = ERROR_STATE();  
    RAISERROR (@ErrorMessage, @ErrorSeverity, @ErrorState);  
    
	END CATCH  		  
END
GO
PRINT N'Creating Procedure [sPurchase].[pPurchaseVendorMasterGet]...';


GO


CREATE PROCEDURE [sPurchase].[pPurchaseVendorMasterGet]
	@rOrgGroupId [int],
	@rId [int] = 0,
	@rTitle [nvarchar](300) = '',
	--@rIsWildCardSearch [bit] = 1,
	@rCode [nvarchar](20) = '',
	@rVendorCategoryId [int] = 0,
	@rLocationId int=0	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
		 --IF @rIsWildCardSearch = 1
		 --BEGIN
			 SET @rCode = sCommon.fSearchStringGet(@rCode)
		 --END
		     SET @rTitle = sCommon.fSearchStringGet(@rTitle)
		
	     SELECT 
		  
		    VM.Id,
			VM.Code,
			VM.Title,
			VM.IsObsolete,
			VM.CreatedUserId,
			VM.CreatedDateTime,
			VM.UpdatedUserId,
			VM.UpdatedDateTime,
			--VM.Area,
			--VM.City,
			VM.ContactPersonName,
			--VM.Country,
			ISNULL(VM.CreditDays, 0) CreditDays,
			ISNULL(CAST(VM.CreditLimit AS DECIMAL(18, 2)), '0') CreditLimit,
			--VM.CreditLimit,
			VM.Email,
			VM.FaxNumber,			
			VM.PhoneNumberMobile,
			VM.PhoneNumberOffice,			
			--VM.State,
			VM.StreetFour,
			VM.StreetOne,
			VM.StreetThree,
			VM.StreetTwo,			
			VM.VendorCategoryId,
			VM.ZipCode,
			VC.Title VendorCategory,
			VM.State STATETITLE,
			VM.City CITYTITLE,
			VM.Country COUNTRYTITLE,
			VM.Area Area,
			VM.LocationID		
					
	   FROM sProcurement.tVendorMaster  VM (nolock)
	   LEFT JOIN   sProcurement.tVendorCategoryMaster VC
	   ON  VM.VendorCategoryId = VC.Id  
	   --LEFT JOIN  sCommon.tStateMaster SM 
	   --ON VM.StateId = SM.Id 
	   --LEFT JOIN   sCommon.tCityMaster CM 
	   --ON VM.CityId = CM.Id 
	   --LEFT JOIN    sCommon.tAreaMaster AM 
	   --ON VM.AreaId = AM.Id 
	   --LEFT JOIN   sCommon.tCountryMaster CAM
	   --ON VM.CountryId = CAM.Id 		     
	   WHERE ((VM.Id = @rId) OR (@rId = 0))
	   AND	((VM.Code LIKE @rCode) OR (ISNULL(@rCode, '') = ''))
	   AND ((VM.Title LIKE @rTitle) OR (ISNULL(@rTitle, '') = ''))
	   AND ((VM.VendorCategoryId = @rVendorCategoryId) OR (@rVendorCategoryId = 0))
	   AND  VM.OrgGroupId = @rOrgGroupId
	   AND ((VM.LocationId = @rLocationId) OR (@rLocationId = 0))
	   AND VM.IsObsolete = 0
	END TRY

	BEGIN CATCH
    IF @@TRANCOUNT > 0
        ROLLBACK TRAN --RollBack in case of Error
    
    DECLARE @ErrorMessage NVARCHAR(4000);  
    DECLARE @ErrorSeverity INT;  
    DECLARE @ErrorState INT;  
    SELECT   
       @ErrorMessage = ERROR_MESSAGE(),  
       @ErrorSeverity = ERROR_SEVERITY(),  
       @ErrorState = ERROR_STATE();  
    RAISERROR (@ErrorMessage, @ErrorSeverity, @ErrorState);  
    
	END CATCH
END
GO
PRINT N'Creating Procedure [sPurchase].[pQuotationRequestGet]...';


GO


CREATE PROCEDURE [sPurchase].[pQuotationRequestGet]
	  @rId int
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
		select QR.Id,
			   QR.Number,
			   QR.PurchaseRequestId,
			   QR.Name,
			   QR.StatusId,
			   QR.VendorId,
			   QR.LocationId,
			   QR.BranchId,
			   QR.OrgGroupId,
			   QR.RFQDate,
			   QR.Description,
			   QR.StartDate,
			   QR.EndDate,
			   QR.BidOpen,
			   QR.BidClose,
			   QR.PersonContact,
			   QR.Email,
			   QR.SendToVendor,
			   QR.VendorId,
			   ISNULL(SM.Title,'') as Status,
			   VM.Code AS VendorCode,
			   VM.Title AS VendorName
		from   [sPurchase].[tQuotationRequest] QR(nolock) 
			   Left JOIN sProcurement.tVendorMaster  VM on QR.VendorId = VM.ID
			   Left Join [sWf].[tWfStatusMaster] SM ON SM.Id = QR.StatusId
		where  QR.Id=@rId AND QR.IsObsolete = 0

		select QRD.Id,
			   QRD.QuotationRequestId,
			   QRD.PurchaseRequestDetailId,
			   QRD.OrgGroupId,
			   QRD.StockItemId,
			   QRD.RequestedQty,
			   QRD.TargetPrice,
			   QRD.Remark, 
			   SIM.Code				AS StockItemCode,
			   SIM.Title				AS StockItemName,
			   SUMa.Code				AS UOM
		from   [sPurchase].[tQuotationRequestDetail] QRD (nolock)
			   Inner JOIN	sPurchase.tQuotationRequest QR	ON QR.Id = QRD.QuotationRequestId AND QR.IsObsolete = 0
			   Inner JOIN	sIp.tStockItemMaster SIM	ON SIM.Id = QRD.StockItemId 
			   Inner JOIN  sFinanceCommon.tStockUomMaster SUMa ON SUMa.Id = SIM.IssueStockUomId
		where  QRD.QuotationRequestId=@rId
	END TRY

	BEGIN CATCH
    IF @@TRANCOUNT > 0
        ROLLBACK TRAN --RollBack in case of Error
    
    DECLARE @ErrorMessage NVARCHAR(4000);  
    DECLARE @ErrorSeverity INT;  
    DECLARE @ErrorState INT;  
    SELECT   
       @ErrorMessage = ERROR_MESSAGE(),  
       @ErrorSeverity = ERROR_SEVERITY(),  
       @ErrorState = ERROR_STATE();  
    RAISERROR (@ErrorMessage, @ErrorSeverity, @ErrorState);  
    
	END CATCH

END
GO
PRINT N'Creating Procedure [sPurchase].[pQuotationRequestSearchGet]...';


GO


CREATE PROCEDURE [sPurchase].[pQuotationRequestSearchGet]

	@rNumber nvarchar(30) = '',
	@rLocationId int,
	@rName nvarchar,
	@rOrgGroupId int

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY


		If @rNumber = NULL SET @rNumber=''
		If @rName = NULL SET @rName=''

	    SELECT		
				QR.Id, 
				QR.Number,
				QR.Name, 
				QR.LocationId
		FROM		
				sPurchase.tQuotationRequest QR (nolock)
		WHERE 
				((QR.Number like @rNumber+'%') OR (@rNumber = ''))
   				AND ((QR.Name like @rName+'%') OR (@rName = ''))
   				--AND ((SLM.Id = @rStoreLocationId) OR (@rStoreLocationId = 0))
   				AND ((QR.OrgGroupId = @rOrgGroupId) OR (@rOrgGroupId=0))
				AND QR.IsObsolete = 0
	 END TRY

	BEGIN CATCH
    IF @@TRANCOUNT > 0
        ROLLBACK TRAN --RollBack in case of Error
    
    DECLARE @ErrorMessage NVARCHAR(4000);  
    DECLARE @ErrorSeverity INT;  
    DECLARE @ErrorState INT;  
    SELECT   
       @ErrorMessage = ERROR_MESSAGE(),  
       @ErrorSeverity = ERROR_SEVERITY(),  
       @ErrorState = ERROR_STATE();  
    RAISERROR (@ErrorMessage, @ErrorSeverity, @ErrorState);  
    
	END CATCH  		  
END
GO
PRINT N'Creating Procedure [sPurchase].[pGoodsReceivedNoteGet]...';


GO


CREATE PROCEDURE [sPurchase].[pGoodsReceivedNoteGet]
	  @rId int
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
		select  GRN.Id,
				GRN.GRNNumber                               ,
				GRN.OrgGroupId,
				GRN.LocationId,
				GRN.PurchaseRequestId,
				GRN.PurchaseOrderId,
				GRN.DepartmentBranchId,
				GRN.VendorId,
				GRN.RequestedBy,
				GRN.BillToAddress,
				GRN.StatusId,
				GRN.PODueDate,
				ISNULL(SM.Title,'') as Status,
				VM.Title AS VendorName 
		from   [sPurchase].[tGoodsReceivedNote] GRN(nolock) 
			   Left JOIN sProcurement.tVendorMaster  VM on GRN.VendorId = VM.ID
			   Left Join [sWf].[tWfStatusMaster] SM ON SM.Id = GRN.StatusId
		where  GRN.Id=@rId AND GRN.IsObsolete = 0

		select GRND.Id,
			   GRND.GoodsReceivedNoteId,
			   GRND.PurchaseRequestDetailId,
			   GRND.OrgGroupId,
			   GRND.UnitTypeId,
			   GRND.CategoryId,
			   GRND.SubCategoryId,
			   GRND.StockItemId,
			   GRND.POQty,
			   GRND.ReceivedQty,
			   GRND.PreviousGRNQty,
			   GRND.UnitPrice,
			   GRND.Remark, 
			   SIM.Code				AS StockItemCode,
			   SIM.Title				AS StockItemName,
			   SUMa.Code				AS UOM
		from   [sPurchase].[tGoodsReceivedNoteDetail] GRND (nolock)
			   Inner JOIN	sPurchase.tGoodsReceivedNote GRN	ON GRN.Id = GRND.GoodsReceivedNoteId AND GRN.IsObsolete = 0
			   Inner JOIN	sIp.tStockItemMaster SIM	ON SIM.Id = GRND.StockItemId 
			   Inner JOIN  sFinanceCommon.tStockUomMaster SUMa ON SUMa.Id = SIM.IssueStockUomId
		where  GRND.GoodsReceivedNoteId=@rId
	END TRY

	BEGIN CATCH
    IF @@TRANCOUNT > 0
        ROLLBACK TRAN --RollBack in case of Error
    
    DECLARE @ErrorMessage NVARCHAR(4000);  
    DECLARE @ErrorSeverity INT;  
    DECLARE @ErrorState INT;  
    SELECT   
       @ErrorMessage = ERROR_MESSAGE(),  
       @ErrorSeverity = ERROR_SEVERITY(),  
       @ErrorState = ERROR_STATE();  
    RAISERROR (@ErrorMessage, @ErrorSeverity, @ErrorState);  
    
	END CATCH
END
GO
PRINT N'Creating Procedure [sPurchase].[pGoodsReceivedNoteSearchGet]...';


GO


CREATE PROCEDURE [sPurchase].[pGoodsReceivedNoteSearchGet]

	@rNumber nvarchar(30) = '',
	@rLocationId int,
	@rName nvarchar,
	@rOrgGroupId int

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY


		If @rNumber = NULL SET @rNumber=''
		If @rName = NULL SET @rName=''

	    SELECT		
				GRN.Id,
				--GRN.PurchaseRequestId,
				--GRN.PurchaseOrderId,
				--GRN.DepartmentBranchId,
				--GRN.VendorId,
				GRN.GRNNumber as Number,
				GRN.RequestedBy, 
				GRN.LocationId, 
				GRN.PODueDate
		FROM		
				sPurchase.tGoodsReceivedNote GRN (nolock)
		WHERE 
				((GRN.GRNNumber like @rNumber+'%') OR (@rNumber = ''))
   				AND ((GRN.RequestedBy like @rName+'%') OR (@rName = ''))
   				--AND ((SLM.Id = @rStoreLocationId) OR (@rStoreLocationId = 0))
   				AND ((GRN.OrgGroupId = @rOrgGroupId) OR (@rOrgGroupId=0))
				AND GRN.IsObsolete = 0
	 END TRY

	BEGIN CATCH
    IF @@TRANCOUNT > 0
        ROLLBACK TRAN --RollBack in case of Error
    
    DECLARE @ErrorMessage NVARCHAR(4000);  
    DECLARE @ErrorSeverity INT;  
    DECLARE @ErrorState INT;  
    SELECT   
       @ErrorMessage = ERROR_MESSAGE(),  
       @ErrorSeverity = ERROR_SEVERITY(),  
       @ErrorState = ERROR_STATE();  
    RAISERROR (@ErrorMessage, @ErrorSeverity, @ErrorState);  
    
	END CATCH  		  
END
GO
PRINT N'Creating Procedure [sPurchase].[pQuotationRequestDelete]...';


GO



CREATE PROCEDURE [sPurchase].[pQuotationRequestDelete]
		@rId bigint,
		@rStatusId int
 
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
	BEGIN TRANSACTION
		If(@rId > 0)
		Begin
			Update sPurchase.tQuotationRequest
			set 
				StatusId = @rStatusId,
				IsObsolete = 1,		
				DeletedDateTime = GetUtcDate()
			where Id = @rId and IsObsolete = 0

			if exists(select Id From sPurchase.tQuotationRequestDetail where QuotationRequestId = @rId)
			Begin
				delete from sPurchase.tQuotationRequestDetail
				where QuotationRequestId = @rId
			End
			select 1
		End
	COMMIT TRAN -- Transaction Success!	
	END TRY

	BEGIN CATCH
    IF @@TRANCOUNT > 0
        ROLLBACK TRAN --RollBack in case of Error

    
    DECLARE @ErrorMessage NVARCHAR(4000);  
    DECLARE @ErrorSeverity INT;  
    DECLARE @ErrorState INT;  

    SELECT   
       @ErrorMessage = ERROR_MESSAGE(),  
       @ErrorSeverity = ERROR_SEVERITY(),  
       @ErrorState = ERROR_STATE();  

    RAISERROR (@ErrorMessage, @ErrorSeverity, @ErrorState);  
    
	END CATCH
END
GO
PRINT N'Creating Procedure [sPurchase].[pPurchaseRequestDelete]...';


GO



CREATE PROCEDURE [sPurchase].[pPurchaseRequestDelete]
		@rId bigint,
		@rStatusId smallint
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
	BEGIN TRANSACTION
		If(@rId > 0)
		Begin
			Update sPurchase.tPurchaseRequest
			set 
				StatusId = @rStatusId,
				IsObsolete = 1,		
				DeletedDateTime = GetUtcDate()
			where Id = @rId and IsObsolete = 0

			if exists(select Id From sPurchase.tPurchaseRequestDetail where PurchaseRequestId = @rId)
			Begin
				delete from sPurchase.tPurchaseRequestDetail
				where PurchaseRequestId = @rId
			End
			select 1
		End
	COMMIT TRAN -- Transaction Success!	
	END TRY

	BEGIN CATCH
    IF @@TRANCOUNT > 0
        ROLLBACK TRAN --RollBack in case of Error

    
    DECLARE @ErrorMessage NVARCHAR(4000);  
    DECLARE @ErrorSeverity INT;  
    DECLARE @ErrorState INT;  

    SELECT   
       @ErrorMessage = ERROR_MESSAGE(),  
       @ErrorSeverity = ERROR_SEVERITY(),  
       @ErrorState = ERROR_STATE();  

    RAISERROR (@ErrorMessage, @ErrorSeverity, @ErrorState);  
    
	END CATCH
END
GO
PRINT N'Creating Procedure [sPurchase].[pPurchaseOrderDelete]...';


GO


CREATE PROCEDURE [sPurchase].[pPurchaseOrderDelete]
		@rId bigint,
		@rStatusId smallint
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
	BEGIN TRANSACTION
		If(@rId > 0)
		Begin
			Update sPurchase.tPurchaseOrder
			set 
				StatusId = @rStatusId,
				IsObsolete = 1,		
				DeletedDateTime = GetUtcDate()
			where Id = @rId and IsObsolete = 0

			if exists(select Id From sPurchase.tPurchaseOrderDetail where PurchaseOrderId = @rId)
			Begin
				delete from sPurchase.tPurchaseOrderDetail
				where PurchaseOrderId = @rId
			End
			select 1
		End
	COMMIT TRAN -- Transaction Success!	
	END TRY

	BEGIN CATCH
    IF @@TRANCOUNT > 0
        ROLLBACK TRAN --RollBack in case of Error

    
    DECLARE @ErrorMessage NVARCHAR(4000);  
    DECLARE @ErrorSeverity INT;  
    DECLARE @ErrorState INT;  

    SELECT   
       @ErrorMessage = ERROR_MESSAGE(),  
       @ErrorSeverity = ERROR_SEVERITY(),  
       @ErrorState = ERROR_STATE();  

    RAISERROR (@ErrorMessage, @ErrorSeverity, @ErrorState);  
    
	END CATCH
END
GO
PRINT N'Creating Procedure [sPurchase].[pGoodsReceivedNoteDelete]...';


GO



CREATE PROCEDURE [sPurchase].[pGoodsReceivedNoteDelete]
		@rId bigint,
		@rStatusId smallint
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
	BEGIN TRANSACTION
		If(@rId > 0)
		Begin
			Update sPurchase.tGoodsReceivedNote
			set 
				StatusId = @rStatusId,
				IsObsolete = 1,
				DeletedDateTime = GetUtcDate()
			where Id = @rId and IsObsolete = 0

			if exists(select Id From sPurchase.tGoodsReceivedNoteDetail where GoodsReceivedNoteId = @rId)
			Begin
				delete from sPurchase.tGoodsReceivedNoteDetail
				where GoodsReceivedNoteId = @rId
			End
			select 1
		End
	COMMIT TRAN -- Transaction Success!	
	END TRY

	BEGIN CATCH
    IF @@TRANCOUNT > 0
        ROLLBACK TRAN --RollBack in case of Error

    
    DECLARE @ErrorMessage NVARCHAR(4000);  
    DECLARE @ErrorSeverity INT;  
    DECLARE @ErrorState INT;  

    SELECT   
       @ErrorMessage = ERROR_MESSAGE(),  
       @ErrorSeverity = ERROR_SEVERITY(),  
       @ErrorState = ERROR_STATE();  

    RAISERROR (@ErrorMessage, @ErrorSeverity, @ErrorState);  
    
	END CATCH
END
GO
PRINT N'Creating Procedure [sPurchase].[InvoiceGenerateDelete]...';


GO



CREATE PROCEDURE [sPurchase].[InvoiceGenerateDelete]
		@rId bigint,
		@rStatusId smallint
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
	BEGIN TRANSACTION
		If(@rId > 0)
		Begin
			Update sPurchase.tInvoiceGenerate
			set 
				StatusId = @rStatusId,
				IsObsolete = 1,
				DeletedDateTime = GetUtcDate()
			where Id = @rId and IsObsolete = 0

			if exists(select Id From sPurchase.tInvoiceGenerateDetail where InvoiceGenerateId = @rId)
			Begin
				delete from sPurchase.tInvoiceGenerateDetail
				where InvoiceGenerateId = @rId
			End
			select 1
		End
	COMMIT TRAN -- Transaction Success!	
	END TRY

	BEGIN CATCH
    IF @@TRANCOUNT > 0
        ROLLBACK TRAN --RollBack in case of Error

    
    DECLARE @ErrorMessage NVARCHAR(4000);  
    DECLARE @ErrorSeverity INT;  
    DECLARE @ErrorState INT;  

    SELECT   
       @ErrorMessage = ERROR_MESSAGE(),  
       @ErrorSeverity = ERROR_SEVERITY(),  
       @ErrorState = ERROR_STATE();  

    RAISERROR (@ErrorMessage, @ErrorSeverity, @ErrorState);  
    
	END CATCH
END
GO
PRINT N'Creating Procedure [sPurchase].[pInvoiceGenerateSearchGet]...';


GO


CREATE PROCEDURE [sPurchase].[pInvoiceGenerateSearchGet]

	@rNumber nvarchar(30) = '',
	@rLocationId int,
	@rName nvarchar,
	@rOrgGroupId int

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY


		If @rNumber = NULL SET @rNumber=''
		If @rName = NULL SET @rName=''

	    SELECT		
				IG.Id,
				--GRN.PurchaseRequestId,
				--GRN.PurchaseOrderId,
				--GRN.DepartmentBranchId,
				--GRN.VendorId,
				IG.INVNumber as Number,
				IG.RequestedBy, 
				IG.LocationId
		FROM		
				sPurchase.tInvoiceGenerate IG (nolock)
		WHERE 
				((IG.INVNumber like @rNumber+'%') OR (@rNumber = ''))
   				AND ((IG.RequestedBy like @rName+'%') OR (@rName = ''))
   				--AND ((SLM.Id = @rStoreLocationId) OR (@rStoreLocationId = 0))
   				AND ((IG.OrgGroupId = @rOrgGroupId) OR (@rOrgGroupId=0))
				AND IG.IsObsolete = 0
	 END TRY

	BEGIN CATCH
    IF @@TRANCOUNT > 0
        ROLLBACK TRAN --RollBack in case of Error
    
    DECLARE @ErrorMessage NVARCHAR(4000);  
    DECLARE @ErrorSeverity INT;  
    DECLARE @ErrorState INT;  
    SELECT   
       @ErrorMessage = ERROR_MESSAGE(),  
       @ErrorSeverity = ERROR_SEVERITY(),  
       @ErrorState = ERROR_STATE();  
    RAISERROR (@ErrorMessage, @ErrorSeverity, @ErrorState);  
    
	END CATCH  		  
END
GO
PRINT N'Creating Procedure [sPurchase].[pInvoiceGenerateGet]...';


GO


CREATE PROCEDURE [sPurchase].[pInvoiceGenerateGet]
	  @rId int
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
		select  IG.Id,
				IG.INVNumber,
				IG.OrgGroupId,
				IG.LocationId,
				IG.GoodsReceivedNoteId,
				IG.RequestedBy,
				IG.VendorId,
				ISNULL(GRN.GRNNumber,'') as GRNNumber,
				IG.StatusId,
				ISNULL(SM.Title,'') as Status,
				ISNULL(VM.Title,'') AS VendorName,
				ISNULL(VM.Code,'') AS VendorCode
		from   [sPurchase].[tInvoiceGenerate] IG(nolock) 
		Left Join [sPurchase].[tGoodsReceivedNote] GRN ON GRN.Id = IG.GoodsReceivedNoteID
		Left JOIN sProcurement.tVendorMaster  VM on IG.VendorId = VM.ID
		Left Join [sWf].[tWfStatusMaster] SM ON SM.Id = IG.StatusId
		where  IG.Id=@rId AND IG.IsObsolete = 0

		select IGD.Id,
			   IGD.InvoiceGenerateId,
			   IGD.GoodsReceivedNoteDetailId,
			   IGD.OrgGroupId,
			   IGD.UnitTypeId,
			   IGD.CategoryId,
			   IGD.SubCategoryId,
			   IGD.StockItemId,
			   IGD.POQty,
			   IGD.ReceivedQty,
			   IGD.AcceptedQty,
			   IGD.RejectedQty, 
			   SIM.Code				AS StockItemCode,
			   SIM.Title				AS StockItemName,
			   SUMa.Code				AS UOM
		from   [sPurchase].[tInvoiceGenerateDetail] IGD (nolock)
			   Inner JOIN	sPurchase.tInvoiceGenerate IG	ON IG.Id = IGD.InvoiceGenerateId AND IG.IsObsolete = 0
			   Inner JOIN	sIp.tStockItemMaster SIM	ON SIM.Id = IGD.StockItemId 
			   Inner JOIN  sFinanceCommon.tStockUomMaster SUMa ON SUMa.Id = SIM.IssueStockUomId
		where  IGD.InvoiceGenerateId=@rId
	END TRY

	BEGIN CATCH
    IF @@TRANCOUNT > 0
        ROLLBACK TRAN --RollBack in case of Error
    
    DECLARE @ErrorMessage NVARCHAR(4000);  
    DECLARE @ErrorSeverity INT;  
    DECLARE @ErrorState INT;  
    SELECT   
       @ErrorMessage = ERROR_MESSAGE(),  
       @ErrorSeverity = ERROR_SEVERITY(),  
       @ErrorState = ERROR_STATE();  
    RAISERROR (@ErrorMessage, @ErrorSeverity, @ErrorState);  
    
	END CATCH
END
GO
PRINT N'Creating Procedure [sPurchase].[pInvoiceGenerateAdd]...';


GO



CREATE PROCEDURE [sPurchase].[pInvoiceGenerateAdd]
		@rId bigint,
		@rGoodsReceivedNoteId bigint,
		@rVendorId bigint,
		@rRequestedBy nvarchar(100),
		@rOrgGroupId int,
		@rLocationId int,
		@rStatusId smallint,
		@rInvoiceDate datetime,
		@rInvoiceDueDate datetime,
		@rBillToAddress nvarchar(1000),
		@rShipToAddress nvarchar(1000),
		@rRemarks nvarchar(500),	
		@rUserId bigint,
		@rDetailList sPurchase.InvoiceGenerateDetailType READONLY
 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
	BEGIN TRANSACTION

		If(@rId > 0)
		Begin
			Update sPurchase.tInvoiceGenerate
			set 
				StatusId = @rStatusId,
				GoodsReceivedNoteId = @rGoodsReceivedNoteId,
				VendorId = @rVendorId,
				InvoiceDate = @rInvoiceDate,
				InvoiceDueDate = @rInvoiceDueDate,
				BillToAddress = @rBillToAddress,
				ShipToAddress = @rShipToAddress,
				Remarks = @rRemarks,
				UpdatedUserId = @rUserId,		
				UpdatedDateTime = GetUtcDate()
			where Id = @rId and IsObsolete = 0

			delete from sPurchase.tInvoiceGenerateDetail
			where InvoiceGenerateId = @rId

			DECLARE @lNextNumberIGD INT	 
			EXECUTE [sCommon].[pGetIntMaxIdForOrgGroup] @rOrgGroupId, 'sPurchase.tInvoiceGenerateDetail',@lNextNumber = @lNextNumberIGD output
			set @lNextNumberIGD=@lNextNumberIGD-1
			INSERT INTO sPurchase.tInvoiceGenerateDetail
			(
				Id,
				OrgGroupId,
				InvoiceGenerateId,
				GoodsReceivedNoteDetailId,
				UnitTypeId,
				CategoryId,
				SubCategoryId,
				StockItemId,
				POQty,
				ReceivedQty,
				AcceptedQty,
				RejectedQty,
				ReasonForRejection,
				CreatedUserId,
				CreatedDateTime
			)
			select	@lNextNumberIGD+Id,
					OrgGroupId,
					@rId,
					GoodsReceivedNoteDetailId,
					UnitTypeId,
					CategoryId,
					SubCategoryId,
					StockItemId,
					POQty,
					ReceivedQty,
					AcceptedQty,
					RejectedQty,
					ReasonForRejection,
					@rUserId, 
					GETUTCDATE() 
			from @rDetailList
			set @lNextNumberIGD=@lNextNumberIGD+(select Count(Id) from @rDetailList)
			EXECUTE sCommon.pTableRowIdModify @rOrgGroupId, @rTableTitle = 'sPurchase.tInvoiceGenerateDetail', @rCurrentNumber = @lNextNumberIGD
			Select @rId
		End
		Else
		Begin
			DECLARE @lNextNumber INT	 
			EXECUTE [sCommon].[pGetIntMaxIdForOrgGroup] @rOrgGroupId, 'sPurchase.tInvoiceGenerate',@lNextNumber = @lNextNumber output	
			--select @lNextNumber
			--DECLARE @loNextNumber nVarchar(20)
			--EXECUTE sCommon.pPrefixSetupNextNumberGet @rOrgId = @rOrgGroupId, @rPrefixFunctionalityId = 1005,@rStoreLocationId = @rLocationId,
			--@rNextNumber = @loNextNumber OUTPUT

	 		INSERT INTO sPurchase.tInvoiceGenerate
			(
				Id,
				INVNumber,
				GoodsReceivedNoteId,
				VendorId,
				RequestedBy, 
				OrgGroupId,
				LocationId, 			 
				StatusId,
				InvoiceDate,
				InvoiceDueDate,
				BillToAddress,
				ShipToAddress,
				Remarks,
				CreatedUserId,		
				CreatedDateTime
	
			)
			VALUES
			(
				@lNextNumber,
				@lNextNumber,
				@rGoodsReceivedNoteId,
				@rVendorId,
				@rRequestedBy,	 
				@rOrgGroupId,
				@rLocationId, 		 
				@rStatusId,
				@rInvoiceDate,
				@rInvoiceDueDate,
				@rBillToAddress,
				@rShipToAddress,
				@rRemarks,
				@rUserId,		
				GETUTCDATE()
			)
 
			set @rId = @lNextNumber  
			
			DECLARE @lNextNumberIGDD INT	 
			EXECUTE [sCommon].[pGetIntMaxIdForOrgGroup] @rOrgGroupId, 'sPurchase.tInvoiceGenerateDetail',@lNextNumber = @lNextNumberIGDD output	
			set @lNextNumberIGDD=@lNextNumberIGDD-1

	 		INSERT INTO sPurchase.tInvoiceGenerateDetail
			(
				Id,
				OrgGroupId,
				InvoiceGenerateId,
				GoodsReceivedNoteDetailId,
				UnitTypeId,
				CategoryId,
				SubCategoryId,
				StockItemId,
				POQty,
				ReceivedQty,
				AcceptedQty,
				RejectedQty,
				ReasonForRejection,
				CreatedUserId,
				CreatedDateTime
			)
			select	@lNextNumberIGDD+Id,
					OrgGroupId,
					@rId,
					GoodsReceivedNoteDetailId,
					UnitTypeId,
					CategoryId,
					SubCategoryId,
					StockItemId,
					POQty,
					ReceivedQty,
					AcceptedQty,
					RejectedQty,
					ReasonForRejection,
					@rUserId, 
					GETUTCDATE() 
			from @rDetailList
						
			set @lNextNumberIGDD=@lNextNumberIGDD+(select Count(Id) from @rDetailList)
			EXECUTE sCommon.pTableRowIdModify @rOrgGroupId, @rTableTitle = 'sPurchase.tInvoiceGenerateDetail', @rCurrentNumber = @lNextNumberIGDD
			select @rId
		End
	COMMIT TRAN -- Transaction Success!	
	END TRY

	BEGIN CATCH
    IF @@TRANCOUNT > 0
        ROLLBACK TRAN --RollBack in case of Error

    
    DECLARE @ErrorMessage NVARCHAR(4000);  
    DECLARE @ErrorSeverity INT;  
    DECLARE @ErrorState INT;  

    SELECT   
       @ErrorMessage = ERROR_MESSAGE(),  
       @ErrorSeverity = ERROR_SEVERITY(),  
       @ErrorState = ERROR_STATE();  

    RAISERROR (@ErrorMessage, @ErrorSeverity, @ErrorState);  
    
	END CATCH
END
GO
PRINT N'Creating Procedure [sPurchase].[pSalesReturnSearchGet]...';


GO


CREATE PROCEDURE [sPurchase].[pSalesReturnSearchGet]

	@rNumber nvarchar(30) = '',
	@rLocationId int,
	@rName nvarchar,
	@rOrgGroupId int

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY


		If @rNumber = NULL SET @rNumber=''
		If @rName = NULL SET @rName=''

	    SELECT		
				SR.Id,
				SR.SRNumber as Number,
				SR.RequestedBy, 
				SR.LocationId
		FROM		
				sPurchase.tSalesReturn SR (nolock)
		WHERE 
				((SR.SRNumber like @rNumber+'%') OR (@rNumber = ''))
   				AND ((SR.RequestedBy like @rName+'%') OR (@rName = ''))
   				--AND ((SLM.Id = @rStoreLocationId) OR (@rStoreLocationId = 0))
   				AND ((SR.OrgGroupId = @rOrgGroupId) OR (@rOrgGroupId=0))
				AND SR.IsObsolete = 0
	 END TRY

	BEGIN CATCH
    IF @@TRANCOUNT > 0
        ROLLBACK TRAN --RollBack in case of Error
    
    DECLARE @ErrorMessage NVARCHAR(4000);  
    DECLARE @ErrorSeverity INT;  
    DECLARE @ErrorState INT;  
    SELECT   
       @ErrorMessage = ERROR_MESSAGE(),  
       @ErrorSeverity = ERROR_SEVERITY(),  
       @ErrorState = ERROR_STATE();  
    RAISERROR (@ErrorMessage, @ErrorSeverity, @ErrorState);  
    
	END CATCH  		  
END
GO
PRINT N'Creating Procedure [sPurchase].[pSalesReturnGet]...';


GO


CREATE PROCEDURE [sPurchase].[pSalesReturnGet]
	  @rId int
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
		select  SR.Id,
				SR.SRNumber,
				SR.OrgGroupId,
				SR.LocationId,
				SR.GoodsReceivedNoteId,
				SR.PurchaseOrderId,
				SR.RequestedBy,
				ISNULL(GRN.GRNNumber,'') as GRNNumber,
				SR.StatusId,
				ISNULL(SM.Title,'') as Status
		from   [sPurchase].[tSalesReturn] SR(nolock) 
		Left Join [sPurchase].[tGoodsReceivedNote] GRN ON GRN.Id = SR.GoodsReceivedNoteID
		Left Join [sWf].[tWfStatusMaster] SM ON SM.Id = SR.StatusId
		where  SR.Id=@rId AND SR.IsObsolete = 0

		select SRD.Id,
			   SRD.SalesReturnId,
			   SRD.GoodsReceivedNoteDetailId,
			   SRD.OrgGroupId,
			   SRD.UnitTypeId,
			   SRD.CategoryId,
			   SRD.SubCategoryId,
			   SRD.StockItemId,
			   SRD.POQty,
			   SRD.ReceivedQty,
			   SRD.RejectedQty,
			   SRD.CreditNoteIssueDate,
			   SRD.ReasonForRejection, 
			   SIM.Code				AS StockItemCode,
			   SIM.Title				AS StockItemName,
			   SUMa.Code				AS UOM
		from   [sPurchase].[tSalesReturnDetail] SRD (nolock)
			   Inner JOIN	sPurchase.tSalesReturn SR	ON SR.Id = SRD.SalesReturnId AND SR.IsObsolete = 0
			   Inner JOIN	sIp.tStockItemMaster SIM	ON SIM.Id = SRD.StockItemId 
			   Inner JOIN  sFinanceCommon.tStockUomMaster SUMa ON SUMa.Id = SIM.IssueStockUomId
		where  SRD.SalesReturnId=@rId
	END TRY

	BEGIN CATCH
    IF @@TRANCOUNT > 0
        ROLLBACK TRAN --RollBack in case of Error
    
    DECLARE @ErrorMessage NVARCHAR(4000);  
    DECLARE @ErrorSeverity INT;  
    DECLARE @ErrorState INT;  
    SELECT   
       @ErrorMessage = ERROR_MESSAGE(),  
       @ErrorSeverity = ERROR_SEVERITY(),  
       @ErrorState = ERROR_STATE();  
    RAISERROR (@ErrorMessage, @ErrorSeverity, @ErrorState);  
    
	END CATCH
END
GO
PRINT N'Creating Procedure [sPurchase].[pSalesReturnDelete]...';


GO



CREATE PROCEDURE [sPurchase].[pSalesReturnDelete]
		@rId bigint,
		@rStatusId smallint
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
	BEGIN TRANSACTION
		If(@rId > 0)
		Begin
			Update sPurchase.tSalesReturn
			set 
				StatusId = @rStatusId,
				IsObsolete = 1,
				DeletedDateTime = GetUtcDate()
			where Id = @rId and IsObsolete = 0

			if exists(select Id From sPurchase.tSalesReturnDetail where SalesReturnId = @rId)
			Begin
				delete from sPurchase.tSalesReturnDetail
				where SalesReturnId = @rId
			End
			select 1
		End
	COMMIT TRAN -- Transaction Success!	
	END TRY

	BEGIN CATCH
    IF @@TRANCOUNT > 0
        ROLLBACK TRAN --RollBack in case of Error

    
    DECLARE @ErrorMessage NVARCHAR(4000);  
    DECLARE @ErrorSeverity INT;  
    DECLARE @ErrorState INT;  

    SELECT   
       @ErrorMessage = ERROR_MESSAGE(),  
       @ErrorSeverity = ERROR_SEVERITY(),  
       @ErrorState = ERROR_STATE();  

    RAISERROR (@ErrorMessage, @ErrorSeverity, @ErrorState);  
    
	END CATCH
END
GO
PRINT N'Creating Procedure [sPurchase].[pGoodsReceivedNoteSRGet]...';


GO


CREATE PROCEDURE [sPurchase].[pGoodsReceivedNoteSRGet]
	  @rId int,
	  @rQualityCheckId bigint
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
		select  GRN.Id,
				GRN.GRNNumber                               ,
				GRN.OrgGroupId,
				GRN.LocationId,
				GRN.PurchaseRequestId,
				GRN.PurchaseOrderId,
				GRN.DepartmentBranchId,
				GRN.VendorId,
				GRN.RequestedBy,
				GRN.BillToAddress,
				GRN.StatusId,
				GRN.PODueDate,
				ISNULL(SM.Title,'') as Status,
				VM.Title AS VendorName 
		from   [sPurchase].[tGoodsReceivedNote] GRN(nolock) 
			   INNER JOIN sPurchase.tQualityCheck QC on QC.GoodsReceivedNoteId = GRN.Id AND QC.Id = @rQualityCheckId
			   LEFT JOIN  sProcurement.tVendorMaster  VM on GRN.VendorId = VM.ID
			   LEFT Join  sWf.tWfStatusMaster SM ON SM.Id = GRN.StatusId
		where  GRN.Id=@rId AND GRN.IsObsolete = 0

		select GRND.Id,
			   GRND.GoodsReceivedNoteId,
			   GRND.PurchaseRequestDetailId,
			   GRND.OrgGroupId,
			   GRND.UnitTypeId,
			   GRND.CategoryId,
			   GRND.SubCategoryId,
			   GRND.StockItemId,
			   GRND.POQty,
			   GRND.ReceivedQty,
			   GRND.PreviousGRNQty,
			   GRND.UnitPrice,
			   GRND.Remark, 
			   SIM.Code				AS StockItemCode,
			   SIM.Title				AS StockItemName,
			   SUMa.Code				AS UOM
		from   [sPurchase].[tGoodsReceivedNoteDetail] GRND (nolock)
			   INNER JOIN	sPurchase.tGoodsReceivedNote GRN	ON GRN.Id = GRND.GoodsReceivedNoteId AND GRN.IsObsolete = 0
			   INNER JOIN sPurchase.tQualityCheck QC on QC.GoodsReceivedNoteId = GRN.Id AND QC.Id = @rQualityCheckId
			   INNER JOIN   sPurchase.tQualityCheckDetail QCD on QCD.QualityCheckId = QC.Id
			   INNER JOIN	sIp.tStockItemMaster SIM	ON SIM.Id = GRND.StockItemId 
			   INNER JOIN   sFinanceCommon.tStockUomMaster SUMa ON SUMa.Id = SIM.IssueStockUomId
		where  GRND.GoodsReceivedNoteId=@rId AND QCD.RejectedQty > 0
	END TRY

	BEGIN CATCH
    IF @@TRANCOUNT > 0
        ROLLBACK TRAN --RollBack in case of Error
    
    DECLARE @ErrorMessage NVARCHAR(4000);  
    DECLARE @ErrorSeverity INT;  
    DECLARE @ErrorState INT;  
    SELECT   
       @ErrorMessage = ERROR_MESSAGE(),  
       @ErrorSeverity = ERROR_SEVERITY(),  
       @ErrorState = ERROR_STATE();  
    RAISERROR (@ErrorMessage, @ErrorSeverity, @ErrorState);  
    
	END CATCH
END
GO
PRINT N'Creating Procedure [sPurchase].[pGoodsReceivedNoteSearchSRGet]...';


GO


CREATE PROCEDURE [sPurchase].[pGoodsReceivedNoteSearchSRGet]

	@rNumber nvarchar(30) = '',
	@rLocationId int,
	@rName nvarchar,
	@rOrgGroupId int,
	@rQualityCheckId bigint

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY


		If @rNumber = NULL SET @rNumber=''
		If @rName = NULL SET @rName=''

	    SELECT		
				GRN.Id,
				GRN.GRNNumber as Number,
				GRN.RequestedBy, 
				GRN.LocationId, 
				GRN.PODueDate
		FROM		
				sPurchase.tGoodsReceivedNote GRN (nolock)
			    INNER JOIN   sPurchase.tQualityCheck QC on QC.GoodsReceivedNoteId = GRN.Id AND QC.Id = @rQualityCheckId
			    INNER JOIN   sPurchase.tQualityCheckDetail QCD on QCD.QualityCheckId = QC.Id
		WHERE 
				((GRN.GRNNumber like @rNumber+'%') OR (@rNumber = ''))
   				AND ((GRN.RequestedBy like @rName+'%') OR (@rName = ''))
   				--AND ((SLM.Id = @rStoreLocationId) OR (@rStoreLocationId = 0))
   				AND ((GRN.OrgGroupId = @rOrgGroupId) OR (@rOrgGroupId=0))
				AND GRN.IsObsolete = 0 AND QCD.RejectedQty > 0
	 END TRY

	BEGIN CATCH
    IF @@TRANCOUNT > 0
        ROLLBACK TRAN --RollBack in case of Error
    
    DECLARE @ErrorMessage NVARCHAR(4000);  
    DECLARE @ErrorSeverity INT;  
    DECLARE @ErrorState INT;  
    SELECT   
       @ErrorMessage = ERROR_MESSAGE(),  
       @ErrorSeverity = ERROR_SEVERITY(),  
       @ErrorState = ERROR_STATE();  
    RAISERROR (@ErrorMessage, @ErrorSeverity, @ErrorState);  
    
	END CATCH  		  
END
GO
PRINT N'Creating Procedure [sPurchase].[pPurchaseStatusGet]...';


GO






CREATE PROCEDURE [sPurchase].[pPurchaseStatusGet]
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
		select Id,
			   Title
		from   [sWf].[tWfStatusMaster] (nolock) 
		where  IsObsolete = 0
	END TRY

	BEGIN CATCH
    IF @@TRANCOUNT > 0
        ROLLBACK TRAN --RollBack in case of Error
    
    DECLARE @ErrorMessage NVARCHAR(4000);  
    DECLARE @ErrorSeverity INT;  
    DECLARE @ErrorState INT;  
    SELECT   
       @ErrorMessage = ERROR_MESSAGE(),  
       @ErrorSeverity = ERROR_SEVERITY(),  
       @ErrorState = ERROR_STATE();  
    RAISERROR (@ErrorMessage, @ErrorSeverity, @ErrorState);  
    
	END CATCH

END
GO
PRINT N'Creating Procedure [sPurchase].[pQualityCheckDelete]...';


GO



CREATE PROCEDURE [sPurchase].[pQualityCheckDelete]
		@rId bigint,
		@rStatusId smallint
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
	BEGIN TRANSACTION
		If(@rId > 0)
		Begin
			Update sPurchase.tQualityCheck
			set 
				StatusId = @rStatusId,
				IsObsolete = 1,
				DeletedDateTime = GetUtcDate()
			where Id = @rId and IsObsolete = 0

			if exists(select Id From sPurchase.tQualityCheckDetail where QualityCheckId = @rId)
			Begin
				delete from sPurchase.tQualityCheckDetail
				where QualityCheckId = @rId
			End
			select 1
		End
	COMMIT TRAN -- Transaction Success!	
	END TRY

	BEGIN CATCH
    IF @@TRANCOUNT > 0
        ROLLBACK TRAN --RollBack in case of Error

    
    DECLARE @ErrorMessage NVARCHAR(4000);  
    DECLARE @ErrorSeverity INT;  
    DECLARE @ErrorState INT;  

    SELECT   
       @ErrorMessage = ERROR_MESSAGE(),  
       @ErrorSeverity = ERROR_SEVERITY(),  
       @ErrorState = ERROR_STATE();  

    RAISERROR (@ErrorMessage, @ErrorSeverity, @ErrorState);  
    
	END CATCH
END
GO
PRINT N'Creating Procedure [sPurchase].[pQualityCheckSearchGet]...';


GO


CREATE PROCEDURE [sPurchase].[pQualityCheckSearchGet]

	@rNumber nvarchar(30) = '',
	@rLocationId int,
	@rName nvarchar,
	@rOrgGroupId int

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY


		If @rNumber = NULL SET @rNumber=''
		If @rName = NULL SET @rName=''

	    SELECT		
				QC.Id,
				--GRN.PurchaseRequestId,
				--GRN.PurchaseOrderId,
				--GRN.DepartmentBranchId,
				--GRN.VendorId,
				QC.QCNumber as Number,
				QC.RequestedBy, 
				QC.LocationId
		FROM		
				sPurchase.tQualityCheck QC (nolock)
		WHERE 
				((QC.QCNumber like @rNumber+'%') OR (@rNumber = ''))
   				AND ((QC.RequestedBy like @rName+'%') OR (@rName = ''))
   				--AND ((SLM.Id = @rStoreLocationId) OR (@rStoreLocationId = 0))
   				AND ((QC.OrgGroupId = @rOrgGroupId) OR (@rOrgGroupId=0))
				AND QC.IsObsolete = 0
	 END TRY

	BEGIN CATCH
    IF @@TRANCOUNT > 0
        ROLLBACK TRAN --RollBack in case of Error
    
    DECLARE @ErrorMessage NVARCHAR(4000);  
    DECLARE @ErrorSeverity INT;  
    DECLARE @ErrorState INT;  
    SELECT   
       @ErrorMessage = ERROR_MESSAGE(),  
       @ErrorSeverity = ERROR_SEVERITY(),  
       @ErrorState = ERROR_STATE();  
    RAISERROR (@ErrorMessage, @ErrorSeverity, @ErrorState);  
    
	END CATCH  		  
END
GO
PRINT N'Creating Procedure [sPurchase].[pQualityCheckGet]...';


GO


CREATE PROCEDURE [sPurchase].[pQualityCheckGet]
	  @rId int
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
		select  QC.Id,
				QC.QCNumber,
				QC.OrgGroupId,
				QC.LocationId,
				QC.GoodsReceivedNoteId,
				QC.PurchaseOrderId,
				QC.RequestedBy,
				ISNULL(GRN.GRNNumber,'') as GRNNumber,
				QC.StatusId,
				ISNULL(SM.Title,'') as Status
		from   [sPurchase].[tQualityCheck] QC(nolock) 
		Left Join [sPurchase].[tGoodsReceivedNote] GRN ON GRN.Id = QC.GoodsReceivedNoteID
		Left Join [sWf].[tWfStatusMaster] SM ON SM.Id = QC.StatusId
		where  QC.Id=@rId AND QC.IsObsolete = 0

		select QCD.Id,
			   QCD.QualityCheckId,
			   QCD.GoodsReceivedNoteDetailId,
			   QCD.OrgGroupId,
			   QCD.UnitTypeId,
			   QCD.CategoryId,
			   QCD.SubCategoryId,
			   QCD.StockItemId,
			   QCD.POQty,
			   QCD.ReceivedQty,
			   QCD.AcceptedQty,
			   QCD.RejectedQty,
			   QCD.ReasonForRejection, 
			   SIM.Code				AS StockItemCode,
			   SIM.Title				AS StockItemName,
			   SUMa.Code				AS UOM
		from   [sPurchase].[tQualityCheckDetail] QCD (nolock)
			   Inner JOIN	sPurchase.tQualityCheck QC	ON QC.Id = QCD.QualityCheckId AND QC.IsObsolete = 0
			   Inner JOIN	sIp.tStockItemMaster SIM	ON SIM.Id = QCD.StockItemId 
			   Inner JOIN  sFinanceCommon.tStockUomMaster SUMa ON SUMa.Id = SIM.IssueStockUomId
		where  QCD.QualityCheckId=@rId
	END TRY

	BEGIN CATCH
    IF @@TRANCOUNT > 0
        ROLLBACK TRAN --RollBack in case of Error
    
    DECLARE @ErrorMessage NVARCHAR(4000);  
    DECLARE @ErrorSeverity INT;  
    DECLARE @ErrorState INT;  
    SELECT   
       @ErrorMessage = ERROR_MESSAGE(),  
       @ErrorSeverity = ERROR_SEVERITY(),  
       @ErrorState = ERROR_STATE();  
    RAISERROR (@ErrorMessage, @ErrorSeverity, @ErrorState);  
    
	END CATCH
END
GO
PRINT N'Creating Procedure [sPurchase].[pQualityCheckAdd]...';


GO



CREATE PROCEDURE [sPurchase].[pQualityCheckAdd]
		@rId bigint,
		@rGoodsReceivedNoteId bigint,
		@rPurchaseOrderId bigint,
		@rRequestedBy nvarchar(100),
		@rOrgGroupId int,
		@rLocationId int,
		@rStatusId smallint,	
		@rUserId bigint,
		@rDetailList sPurchase.QualityCheckDetailType READONLY
 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
	BEGIN TRANSACTION

		If(@rId > 0)
		Begin
			Update sPurchase.tQualityCheck
			set 
				StatusId = @rStatusId,
				GoodsReceivedNoteId = @rGoodsReceivedNoteId,
				PurchaseOrderId = @rPurchaseOrderId,
				UpdatedUserId = @rUserId,		
				UpdatedDateTime = GetUtcDate()
			where Id = @rId and IsObsolete = 0

			delete from sPurchase.tQualityCheckDetail
			where QualityCheckId = @rId

			DECLARE @lNextNumberQCD INT	 
			EXECUTE [sCommon].[pGetIntMaxIdForOrgGroup] @rOrgGroupId, 'sPurchase.tQualityCheckDetail',@lNextNumber = @lNextNumberQCD output
			set @lNextNumberQCD=@lNextNumberQCD-1
			INSERT INTO sPurchase.tQualityCheckDetail
			(
				Id,
				OrgGroupId,
				QualityCheckId,
				GoodsReceivedNoteDetailId,
				UnitTypeId,
				CategoryId,
				SubCategoryId,
				StockItemId,
				POQty,
				ReceivedQty,
				AcceptedQty,
				RejectedQty,
				ReasonForRejection,
				CreatedUserId,
				CreatedDateTime
			)
			select	@lNextNumberQCD+Id,
					OrgGroupId,
					@rId,
					GoodsReceivedNoteDetailId,
					UnitTypeId,
					CategoryId,
					SubCategoryId,
					StockItemId,
					POQty,
					ReceivedQty,
					AcceptedQty,
					RejectedQty,
					ReasonForRejection,
					@rUserId, 
					GETUTCDATE() 
			from @rDetailList
			set @lNextNumberQCD=@lNextNumberQCD+(select Count(Id) from @rDetailList)
			EXECUTE sCommon.pTableRowIdModify @rOrgGroupId, @rTableTitle = 'sPurchase.tQualityCheckDetail', @rCurrentNumber = @lNextNumberQCD
			Select @rId
		End
		Else
		Begin
			DECLARE @lNextNumber INT	 
			EXECUTE [sCommon].[pGetIntMaxIdForOrgGroup] @rOrgGroupId, 'sPurchase.tQualityCheck',@lNextNumber = @lNextNumber output	
			--select @lNextNumber
			--DECLARE @loNextNumber nVarchar(20)
			--EXECUTE sCommon.pPrefixSetupNextNumberGet @rOrgId = @rOrgGroupId, @rPrefixFunctionalityId = 1005,@rStoreLocationId = @rLocationId,
			--@rNextNumber = @loNextNumber OUTPUT

	 		INSERT INTO sPurchase.tQualityCheck
			(
				Id,
				QCNumber,
				GoodsReceivedNoteId,
				PurchaseOrderId,
				RequestedBy, 
				OrgGroupId,
				LocationId, 			 
				StatusId,
				CreatedUserId,		
				CreatedDateTime
	
			)
			VALUES
			(
				@lNextNumber,
				@lNextNumber,
				@rGoodsReceivedNoteId,
				@rPurchaseOrderId,
				@rRequestedBy,	 
				@rOrgGroupId,
				@rLocationId, 		 
				@rStatusId,
				@rUserId,		
				GETUTCDATE()
			)
 
			set @rId = @lNextNumber  
			
			DECLARE @lNextNumberQCDD INT	 
			EXECUTE [sCommon].[pGetIntMaxIdForOrgGroup] @rOrgGroupId, 'sPurchase.tQualityCheckDetail',@lNextNumber = @lNextNumberQCDD output	
			set @lNextNumberQCDD=@lNextNumberQCDD-1

	 		INSERT INTO sPurchase.tQualityCheckDetail
			(
				Id,
				OrgGroupId,
				QualityCheckId,
				GoodsReceivedNoteDetailId,
				UnitTypeId,
				CategoryId,
				SubCategoryId,
				StockItemId,
				POQty,
				ReceivedQty,
				AcceptedQty,
				RejectedQty,
				ReasonForRejection,
				CreatedUserId,
				CreatedDateTime
			)
			select	@lNextNumberQCDD+Id,
					OrgGroupId,
					@rId,
					GoodsReceivedNoteDetailId,
					UnitTypeId,
					CategoryId,
					SubCategoryId,
					StockItemId,
					POQty,
					ReceivedQty,
					AcceptedQty,
					RejectedQty,
					ReasonForRejection,
					@rUserId, 
					GETUTCDATE() 
			from @rDetailList
						
			set @lNextNumberQCDD=@lNextNumberQCDD+(select Count(Id) from @rDetailList)
			EXECUTE sCommon.pTableRowIdModify @rOrgGroupId, @rTableTitle = 'sPurchase.tQualityCheckDetail', @rCurrentNumber = @lNextNumberQCDD
			select @rId
		End
	COMMIT TRAN -- Transaction Success!	
	END TRY

	BEGIN CATCH
    IF @@TRANCOUNT > 0
        ROLLBACK TRAN --RollBack in case of Error

    
    DECLARE @ErrorMessage NVARCHAR(4000);  
    DECLARE @ErrorSeverity INT;  
    DECLARE @ErrorState INT;  

    SELECT   
       @ErrorMessage = ERROR_MESSAGE(),  
       @ErrorSeverity = ERROR_SEVERITY(),  
       @ErrorState = ERROR_STATE();  

    RAISERROR (@ErrorMessage, @ErrorSeverity, @ErrorState);  
    
	END CATCH
END
GO
PRINT N'Creating Procedure [sWf].[pWfApprovalAdd]...';


GO


CREATE PROCEDURE [sWf].[pWfApprovalAdd]
		@rId	bigint,
	 	@rDocSourceId bigint=0,
	 	@rDocSourceTypeId smallint=0,
        @rActionEmployeeId bigint=0,
		@rActionStatusId smallint=0,
		@rActionRemark nvarchar(500) = '',
		@rIsSequancial bit=0,
		@rWfLevel int=0,
		@rWfFunctionalityId smallint=0,
		@rOrgGroupId smallint
		
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
    BEGIN TRY
	BEGIN TRANSACTION
    Declare @lActionByEmployeeId bigint
	set @lActionByEmployeeId = @rActionEmployeeId

	Declare @StatusId smallint
	set @StatusId = @rActionStatusId

	IF(@rIsSequancial = 1)
	BEGIN
		Declare @HierarchyLevelId bigint
		select @HierarchyLevelId=ISNULL(AutoId,0) from [sWf].[tWfHierarchyLevel] WHERE WfApprovalActionId =@rId AND ActionByEmployeeId=@rActionEmployeeId AND StatusId <> 4
		IF(@HierarchyLevelId > 0)
		Begin
			UPDATE [sWf].[tWfHierarchyLevel] SET StatusId = @StatusId , Remark = @rActionRemark 
			WHERE AutoId = @HierarchyLevelId
		End

		IF(@rActionStatusId <> 4)
		BEGIN
			DECLARE @LogCount int
			SELECT @LogCount = COUNT(AutoId) FROM [sWf].[tWfHierarchyLevel] WHERE WfApprovalActionId = @rId
			
			IF(@rWfLevel <> @LogCount)
			Begin
				IF(@rActionStatusId = 3)
				Begin
					set @StatusId = 2
				End
				
			End
			SELECT @lActionByEmployeeId = EmployeeManagerId from [sHrm].[tEmployeeJobDetail] WHere EmployeeId = @rActionEmployeeId
			AND @lActionByEmployeeId IS NOT NULL
			
		END
	END

	IF(@rId = 0)
	BEGIN
		
		DECLARE @lNextNumber INT	 
		EXECUTE [sCommon].[pGetIntMaxIdForOrgGroup] @rOrgGroupId, 'sWf.tWfApprovalAction',@lNextNumber = @lNextNumber output

		INSERT INTO sWf.tWfApprovalAction
		(
		Id,
		OrgGroupId,
		ActionEmployeeId,
		ActionStatusId,
		ActionRemark,
		DocSourceId,
		DocSourceTypeId,
		WfFunctionalityId,
		CreatedUserId,
		CreatedDateTime
		)
		VALUES
		(
			@lNextNumber,
			@rOrgGroupId,
			@rActionEmployeeId,
			@StatusId,
			@rActionRemark,
			@rDocSourceId,
			@rDocSourceTypeId,
			@rWfFunctionalityId,
			@rActionEmployeeId,
			GETUTCDATE()				
		)
		set @rId=@lNextNumber
		
		INSERT INTO sWf.tWfApprovalActionLog
		(
			WfApprovalActionId,
			ActionByEmployeeId,
			StatusId,
			IsSequancial,
			ActionRemark,
			CreatedUserId,
			CreatedDateTime
		)
		VALUES
		(
			@rId,
			@lActionByEmployeeId,
			@rActionStatusId,
			@rIsSequancial,
			@rActionRemark,
			@rActionEmployeeId,
			GETUTCDATE()				
		)

		IF(@rIsSequancial = 1 AND (@rWfLevel <> @LogCount OR @rWfLevel > 0))
		BEGIN																																																																																																																																																																				IF(@lActionByEmployeeId > 0)
			INSERT INTO [sWf].[tWfHierarchyLevel]
					(WfApprovalActionId
					,StatusId
					,Remark
					,ActionByEmployeeId
					,ActionDatetime)
				VALUES
					(@rId
					,1
					,''
					,@lActionByEmployeeId
					,sCommon.fGetDate())
		END
		SELECT 1 AS Result
	END
	ELSE
	BEGIN
		IF EXISTS(select ID from sWf.tWfApprovalAction WHERE id = @rId AND ActionStatusId not in(3,4) OR @rIsSequancial = 0)
		BEGIN
			UPDATE sWf.tWfApprovalAction
			SET 
			DocSourceId=@rDocSourceId,
			DocSourceTypeId=@rDocSourceTypeId,
			ActionEmployeeId=@rActionEmployeeId,
			ActionStatusId=@StatusId,
			ActionRemark=@rActionRemark,
			UpdatedUserId = @rActionEmployeeId,		
			UpdatedDateTime = GetUtcDate()
			WHERE id = @rId 

			INSERT INTO sWf.tWfApprovalActionLog
			(
				WfApprovalActionId,
				ActionByEmployeeId,
				StatusId,
				IsSequancial,
				ActionRemark,
				CreatedUserId,
				CreatedDateTime
			)
			VALUES
			(
				@rId,
				@lActionByEmployeeId,
				@rActionStatusId,
				@rIsSequancial,
				@rActionRemark,
				@rActionEmployeeId,
				GETUTCDATE()				
			)
			IF(@rIsSequancial = 1 AND @rWfLevel <> @LogCount AND @rActionStatusId <> 4)
			BEGIN																																																																																																																																																																				IF(@lActionByEmployeeId > 0)
				INSERT INTO [sWf].[tWfHierarchyLevel]
						(WfApprovalActionId
						,StatusId
						,Remark
						,ActionByEmployeeId
						,ActionDatetime)
					VALUES
						(@rId
						,1
						,''
						,@lActionByEmployeeId
						,sCommon.fGetDate())
			END
			ELSE
			BEGIN
					SELECT @lActionByEmployeeId = EmployeeManagerId from [sHrm].[tEmployeeJobDetail] WHere EmployeeId = @rActionEmployeeId
					DELETE FROM [sWf].[tWfHierarchyLevel] Where WfApprovalActionId = @rId AND ActionByEmployeeId = @lActionByEmployeeId AND @lActionByEmployeeId IS NOT NULL
			END 
			SELECT 11 AS Result 
		END
	    SELECT 21 AS Result 
	END	
	IF EXISTS(select ID from sWf.tWfApprovalAction WHERE id = @rId AND ActionStatusId in(3,4))
	Begin
		if(@rDocSourceTypeId = 2040)
		Begin
			update sPurchase.tPurchaseRequest 
			set StatusId = @StatusId,
				UpdatedUserId = @rActionEmployeeId,
				UpdatedDateTime = GETUTCDATE()
			where Id = @rDocSourceId 
		END
		else if(@rDocSourceTypeId = 2041)
		Begin
			update sPurchase.tQuotationRequest 
			set StatusId = @StatusId,
				UpdatedUserId = @rActionEmployeeId,
				UpdatedDateTime = GETUTCDATE()
			where Id = @rDocSourceId 
		END
		else if(@rDocSourceTypeId = 2042)
		Begin
			update sPurchase.tPurchaseOrder 
			set StatusId = @StatusId,
				UpdatedUserId = @rActionEmployeeId,
				UpdatedDateTime = GETUTCDATE()
			where Id = @rDocSourceId 
		END
		else if(@rDocSourceTypeId = 2043)
		Begin
			update sPurchase.tGoodsReceivedNote 
			set StatusId = @StatusId,
				UpdatedUserId = @rActionEmployeeId,
				UpdatedDateTime = GETUTCDATE()
			where Id = @rDocSourceId 
		END
		else if(@rDocSourceTypeId = 2044)
		Begin
			update sPurchase.tSalesReturn 
			set StatusId = @StatusId,
				UpdatedUserId = @rActionEmployeeId,
				UpdatedDateTime = GETUTCDATE()
			where Id = @rDocSourceId 
		END
	End
	COMMIT TRAN -- Transaction Success!	
	END TRY

	BEGIN CATCH
    IF @@TRANCOUNT > 0
        ROLLBACK TRAN --RollBack in case of Error

    
    DECLARE @ErrorMessage NVARCHAR(4000);  
    DECLARE @ErrorSeverity INT;  
    DECLARE @ErrorState INT;  

    SELECT   
       @ErrorMessage = ERROR_MESSAGE(),  
       @ErrorSeverity = ERROR_SEVERITY(),  
       @ErrorState = ERROR_STATE();  

    RAISERROR (@ErrorMessage, @ErrorSeverity, @ErrorState);  
    
	END CATCH 
END
GO
PRINT N'Creating Procedure [sWf].[pWfApprovalGet]...';


GO



 
CREATE  PROCEDURE [sWf].[pWfApprovalGet]
			 @rWfFunctionalityId smallint=0,
			 @rFromDate date=null,
			 @rToDate date=null,
			 @rStatusId smallint=0,
			 @rOrgId smallint=0,
			 @rCode nvarchar(20) ='',
			 @rUserId bigint ,
			 @rApprovalRequestId bigint = 0

	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	Declare @lRoleId int
	Select @lRoleId = RoleId from [sSecurity].[tUserRole] Where UserId = @rUserId

	SELECT
		AA.Id AS ApprovalActionId,
		AA.DocSourceId AS DocSourceId,
		AA.DocSourceTypeId AS DocSourceTypeId,
		WFM.Title AS WorkFlowName,
		WFM.Id AS WorkFlowId,
		PR.Id AS ApprovalRequestId,
		CONVERT(DATE,PR.CreatedDateTime, 103) AS CreatedDateTime,
		95 AS ParticipantSourceTypeId,
		EM.Id AS SourceId,
		EM.Code AS Code ,
		EM.FirstName +' '+ EM.MiddleName +' ' +EM.LastName AS Name ,
		--PR.Remark AS Remark,
		(CASE ISNULL(sm.Id,'') WHEN '' THEN 3 ELSE sm.Id END) AS statusId,
		(CASE ISNULL(sm.title,'') WHEN '' THEN 'Pending' ELSE sm.title END) AS status,
		ISNULL(AA.ActionRemark, '') AS ActionRemark
			
		
	from sPurchase.tPurchaseRequest PR
	INNER JOIN sWf.tWfApprovingAuthority FAA ON 1 = FAA.WfFunctionalityId And FAA.OrgId =@rOrgId
	INNER JOIN sSecurity.tRole R ON R.Id = FAA.AuthoritySourceId AND FAA.AuthoritySourceTypeId = 2015
	LEFT JOIN sWf.tWfApprovalAction AA ON AA.DocSourceId = PR.Id AND AA.WfFunctionalityId = FAA.WfFunctionalityId AND AA.DocSourceTypeId = 2040
	LEFT JOIN sWf.tWfStatusMaster SM ON SM.Id = AA.ActionStatusId
	INNER JOIN sWf.tWfFunctionalityMaster WFM ON WFM.Id = FAA.WfFunctionalityId
	LEFT JOIN  sHrm.tEmployeeMaster  EM ON EM.Id = AA.ActionEmployeeId
	
	WHERE R.Id = @lRoleId
	AND ((WFM.Id = @rWfFunctionalityId) OR (@rWfFunctionalityId =0)) 
	AND ((Convert(Date,PR.CreatedDateTime)>= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
	AND ((Convert(Date,PR.CreatedDateTime) <= @rToDate) OR (ISNULL(@rToDate,'') = ''))
	AND((SM.Id = @rStatusId) OR (@rStatusId =0))
	AND ((EM.Code = @rCode) OR (@rCode = ''))
	AND  ISNULL(EM.IsOtherUser,0) = 0
	AND ((PR.Id = @rApprovalRequestId) OR (@rApprovalRequestId = 0))

	UNION

	SELECT
		AA.Id AS ApprovalActionId,
		AA.DocSourceId AS DocSourceId,
		AA.DocSourceTypeId AS DocSourceTypeId,
		WFM.Title AS WorkFlowName,
		WFM.Id AS WorkFlowId,
		PR.Id AS ApprovalRequestId,
		CONVERT(DATE,PR.CreatedDateTime, 103) AS CreatedDateTime,
		95 AS ParticipantSourceTypeId,
		EM.Id AS SourceId,
		EM.Code AS Code ,
		EM.FirstName +' '+ EM.MiddleName +' ' +EM.LastName AS Name ,
		--AR.Remark AS Remark,
		(CASE ISNULL(sm.Id,'') WHEN '' THEN 3 ELSE sm.Id END) AS statusId,
		(CASE ISNULL(sm.title,'') WHEN '' THEN 'Pending' ELSE sm.title END) AS status,
		ISNULL(AA.ActionRemark, '') AS ActionRemark
			
		
	from sPurchase.tPurchaseRequest PR
	INNER JOIN sWf.tWfApprovingAuthority FAA ON 1 = FAA.WfFunctionalityId And FAA.OrgId =@rOrgId
	INNER JOIN sSecurity.tUser U ON U.Id = FAA.AuthoritySourceId AND FAA.AuthoritySourceTypeId = 1019
	LEFT JOIN sWf.tWfApprovalAction AA ON AA.DocSourceId = PR.Id AND AA.WfFunctionalityId = FAA.WfFunctionalityId AND AA.DocSourceTypeId = 2040
	LEFT JOIN sWf.tWfStatusMaster SM ON SM.Id = AA.ActionStatusId
	INNER JOIN sWf.tWfFunctionalityMaster WFM ON WFM.Id = FAA.WfFunctionalityId
	LEFT JOIN  sHrm.tEmployeeMaster  EM ON EM.Id = AA.ActionEmployeeId
	WHERE U.Id = @rUserId
	AND ((WFM.Id = @rWfFunctionalityId) OR (@rWfFunctionalityId =0)) 
	AND ((Convert(Date,PR.CreatedDateTime)>= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
	AND ((Convert(Date,PR.CreatedDateTime) <= @rToDate) OR (ISNULL(@rToDate,'') = ''))
	AND((SM.Id = @rStatusId) OR (@rStatusId =0))
	AND ((EM.Code = @rCode) OR (@rCode =''))
	AND  ISNULL(EM.IsOtherUser,0) = 0
	AND ((PR.Id = @rApprovalRequestId) OR (@rApprovalRequestId = 0))

	UNION

	SELECT
		AA.Id AS ApprovalActionId,
		AA.DocSourceId AS DocSourceId,
		AA.DocSourceTypeId AS DocSourceTypeId,
		WFM.Title AS WorkFlowName,
		WFM.Id AS WorkFlowId,
		PR.Id AS ApprovalRequestId,
		CONVERT(DATE,PR.CreatedDateTime, 103) AS CreatedDateTime,
		95 AS ParticipantSourceTypeId,
		EM.Id AS SourceId,
		EM.Code AS Code ,
		EM.FirstName +' '+ EM.MiddleName +' ' +EM.LastName AS Name ,
		--AR.Remark AS Remark,
		(CASE ISNULL(sm.Id,'') WHEN '' THEN 3 ELSE sm.Id END) AS statusId,
		(CASE ISNULL(sm.title,'') WHEN '' THEN 'Pending' ELSE sm.title END) AS status,
		ISNULL(AA.ActionRemark, '') AS ActionRemark
			
		
	from sPurchase.tPurchaseRequest PR
	INNER JOIN sWf.tWfFunctionalityMaster WFM ON 1 = WFM.Id
	INNER JOIN sWf.tWfApprovalAction AA ON AA.DocSourceId = PR.Id AND AA.WfFunctionalityId = WFM.Id AND AA.DocSourceTypeId = 2040
	INNER JOIN sWf.tWfHierarchyLevel HL ON HL.WfApprovalActionId = AA.Id
	LEFT JOIN sWf.tWfStatusMaster SM ON SM.Id = AA.ActionStatusId
	LEFT JOIN  sHrm.tEmployeeMaster  EM ON EM.Id = AA.ActionEmployeeId
	WHERE HL.ActionByEmployeeId = @rUserId
	AND ((WFM.Id = @rWfFunctionalityId) OR (@rWfFunctionalityId =0)) 
	AND ((Convert(Date,PR.CreatedDateTime)>= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
	AND ((Convert(Date,PR.CreatedDateTime) <= @rToDate) OR (ISNULL(@rToDate,'') = ''))
	AND((SM.Id = @rStatusId) OR (@rStatusId =0))
	AND ((EM.Code = @rCode) OR (@rCode =''))
	AND  ISNULL(EM.IsOtherUser,0) = 0
	AND ((PR.Id = @rApprovalRequestId) OR (@rApprovalRequestId = 0))

	------------------------------------------------------------------------------------------------------------------------------------------------------------------
	UNION
	SELECT
		AA.Id AS ApprovalActionId,
		AA.DocSourceId AS DocSourceId,
		AA.DocSourceTypeId AS DocSourceTypeId,
		WFM.Title AS WorkFlowName,
		WFM.Id AS WorkFlowId,
		QR.Id AS ApprovalRequestId,
		CONVERT(DATE,QR.CreatedDateTime, 103) AS CreatedDateTime,
		95 AS ParticipantSourceTypeId,
		EM.Id AS SourceId,
		EM.Code AS Code ,
		EM.FirstName +' '+ EM.MiddleName +' ' +EM.LastName AS Name ,
		--PR.Remark AS Remark,
		(CASE ISNULL(sm.Id,'') WHEN '' THEN 3 ELSE sm.Id END) AS statusId,
		(CASE ISNULL(sm.title,'') WHEN '' THEN 'Pending' ELSE sm.title END) AS status,
		ISNULL(AA.ActionRemark, '') AS ActionRemark
			
		
	from sPurchase.tQuotationRequest QR
	INNER JOIN sWf.tWfApprovingAuthority FAA ON 2 = FAA.WfFunctionalityId And FAA.OrgId =@rOrgId
	INNER JOIN sSecurity.tRole R ON R.Id = FAA.AuthoritySourceId AND FAA.AuthoritySourceTypeId = 2015
	LEFT JOIN sWf.tWfApprovalAction AA ON AA.DocSourceId = QR.Id AND AA.WfFunctionalityId = FAA.WfFunctionalityId AND AA.DocSourceTypeId = 2041
	LEFT JOIN sWf.tWfStatusMaster SM ON SM.Id = AA.ActionStatusId
	INNER JOIN sWf.tWfFunctionalityMaster WFM ON WFM.Id = FAA.WfFunctionalityId
	LEFT JOIN  sHrm.tEmployeeMaster  EM ON EM.Id = AA.ActionEmployeeId
	
	WHERE R.Id = @lRoleId
	AND ((WFM.Id = @rWfFunctionalityId) OR (@rWfFunctionalityId =0)) 
	AND ((Convert(Date,QR.CreatedDateTime)>= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
	AND ((Convert(Date,QR.CreatedDateTime) <= @rToDate) OR (ISNULL(@rToDate,'') = ''))
	AND((SM.Id = @rStatusId) OR (@rStatusId =0))
	AND ((EM.Code = @rCode) OR (@rCode = ''))
	AND  ISNULL(EM.IsOtherUser,0) = 0
	AND ((QR.Id = @rApprovalRequestId) OR (@rApprovalRequestId = 0))

	UNION

	SELECT
		AA.Id AS ApprovalActionId,
		AA.DocSourceId AS DocSourceId,
		AA.DocSourceTypeId AS DocSourceTypeId,
		WFM.Title AS WorkFlowName,
		WFM.Id AS WorkFlowId,
		QR.Id AS ApprovalRequestId,
		CONVERT(DATE,QR.CreatedDateTime, 103) AS CreatedDateTime,
		95 AS ParticipantSourceTypeId,
		EM.Id AS SourceId,
		EM.Code AS Code ,
		EM.FirstName +' '+ EM.MiddleName +' ' +EM.LastName AS Name ,
		--AR.Remark AS Remark,
		(CASE ISNULL(sm.Id,'') WHEN '' THEN 3 ELSE sm.Id END) AS statusId,
		(CASE ISNULL(sm.title,'') WHEN '' THEN 'Pending' ELSE sm.title END) AS status,
		ISNULL(AA.ActionRemark, '') AS ActionRemark
			
		
	from sPurchase.tQuotationRequest QR
	INNER JOIN sWf.tWfApprovingAuthority FAA ON 2 = FAA.WfFunctionalityId And FAA.OrgId =@rOrgId
	INNER JOIN sSecurity.tUser U ON U.Id = FAA.AuthoritySourceId AND FAA.AuthoritySourceTypeId = 1019
	LEFT JOIN sWf.tWfApprovalAction AA ON AA.DocSourceId = QR.Id AND AA.WfFunctionalityId = FAA.WfFunctionalityId AND AA.DocSourceTypeId = 2041
	LEFT JOIN sWf.tWfStatusMaster SM ON SM.Id = AA.ActionStatusId
	INNER JOIN sWf.tWfFunctionalityMaster WFM ON WFM.Id = FAA.WfFunctionalityId
	LEFT JOIN  sHrm.tEmployeeMaster  EM ON EM.Id = AA.ActionEmployeeId
	WHERE U.Id = @rUserId
	AND ((WFM.Id = @rWfFunctionalityId) OR (@rWfFunctionalityId =0)) 
	AND ((Convert(Date,QR.CreatedDateTime)>= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
	AND ((Convert(Date,QR.CreatedDateTime) <= @rToDate) OR (ISNULL(@rToDate,'') = ''))
	AND((SM.Id = @rStatusId) OR (@rStatusId =0))
	AND ((EM.Code = @rCode) OR (@rCode =''))
	AND  ISNULL(EM.IsOtherUser,0) = 0
	AND ((QR.Id = @rApprovalRequestId) OR (@rApprovalRequestId = 0))

	UNION

	SELECT
		AA.Id AS ApprovalActionId,
		AA.DocSourceId AS DocSourceId,
		AA.DocSourceTypeId AS DocSourceTypeId,
		WFM.Title AS WorkFlowName,
		WFM.Id AS WorkFlowId,
		QR.Id AS ApprovalRequestId,
		CONVERT(DATE,QR.CreatedDateTime, 103) AS CreatedDateTime,
		95 AS ParticipantSourceTypeId,
		EM.Id AS SourceId,
		EM.Code AS Code ,
		EM.FirstName +' '+ EM.MiddleName +' ' +EM.LastName AS Name ,
		--AR.Remark AS Remark,
		(CASE ISNULL(sm.Id,'') WHEN '' THEN 3 ELSE sm.Id END) AS statusId,
		(CASE ISNULL(sm.title,'') WHEN '' THEN 'Pending' ELSE sm.title END) AS status,
		ISNULL(AA.ActionRemark, '') AS ActionRemark
			
		
	from sPurchase.tQuotationRequest QR
	INNER JOIN sWf.tWfFunctionalityMaster WFM ON 2 = WFM.Id
	INNER JOIN sWf.tWfApprovalAction AA ON AA.DocSourceId = QR.Id AND AA.WfFunctionalityId = WFM.Id AND AA.DocSourceTypeId = 2041
	INNER JOIN sWf.tWfHierarchyLevel HL ON HL.WfApprovalActionId = AA.Id
	LEFT JOIN sWf.tWfStatusMaster SM ON SM.Id = AA.ActionStatusId
	LEFT JOIN  sHrm.tEmployeeMaster  EM ON EM.Id = AA.ActionEmployeeId
	WHERE HL.ActionByEmployeeId = @rUserId
	AND ((WFM.Id = @rWfFunctionalityId) OR (@rWfFunctionalityId =0)) 
	AND ((Convert(Date,QR.CreatedDateTime)>= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
	AND ((Convert(Date,QR.CreatedDateTime) <= @rToDate) OR (ISNULL(@rToDate,'') = ''))
	AND((SM.Id = @rStatusId) OR (@rStatusId =0))
	AND ((EM.Code = @rCode) OR (@rCode =''))
	AND  ISNULL(EM.IsOtherUser,0) = 0
	AND ((QR.Id = @rApprovalRequestId) OR (@rApprovalRequestId = 0))
	------------------------------------------------------------------------------------------------------------------------------------------------------------------
	UNION
	SELECT
		AA.Id AS ApprovalActionId,
		AA.DocSourceId AS DocSourceId,
		AA.DocSourceTypeId AS DocSourceTypeId,
		WFM.Title AS WorkFlowName,
		WFM.Id AS WorkFlowId,
		PO.Id AS ApprovalRequestId,
		CONVERT(DATE,PO.CreatedDateTime, 103) AS CreatedDateTime,
		95 AS ParticipantSourceTypeId,
		EM.Id AS SourceId,
		EM.Code AS Code ,
		EM.FirstName +' '+ EM.MiddleName +' ' +EM.LastName AS Name ,
		--PR.Remark AS Remark,
		(CASE ISNULL(sm.Id,'') WHEN '' THEN 3 ELSE sm.Id END) AS statusId,
		(CASE ISNULL(sm.title,'') WHEN '' THEN 'Pending' ELSE sm.title END) AS status,
		ISNULL(AA.ActionRemark, '') AS ActionRemark
			
		
	from sPurchase.tPurchaseOrder PO
	INNER JOIN sWf.tWfApprovingAuthority FAA ON 3 = FAA.WfFunctionalityId And FAA.OrgId =@rOrgId
	INNER JOIN sSecurity.tRole R ON R.Id = FAA.AuthoritySourceId AND FAA.AuthoritySourceTypeId = 2015
	LEFT JOIN sWf.tWfApprovalAction AA ON AA.DocSourceId = PO.Id AND AA.WfFunctionalityId = FAA.WfFunctionalityId AND AA.DocSourceTypeId = 2042
	LEFT JOIN sWf.tWfStatusMaster SM ON SM.Id = AA.ActionStatusId
	INNER JOIN sWf.tWfFunctionalityMaster WFM ON WFM.Id = FAA.WfFunctionalityId
	LEFT JOIN  sHrm.tEmployeeMaster  EM ON EM.Id = AA.ActionEmployeeId
	
	WHERE R.Id = @lRoleId
	AND ((WFM.Id = @rWfFunctionalityId) OR (@rWfFunctionalityId =0)) 
	AND ((Convert(Date,PO.CreatedDateTime)>= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
	AND ((Convert(Date,PO.CreatedDateTime) <= @rToDate) OR (ISNULL(@rToDate,'') = ''))
	AND((SM.Id = @rStatusId) OR (@rStatusId =0))
	AND ((EM.Code = @rCode) OR (@rCode = ''))
	AND  ISNULL(EM.IsOtherUser,0) = 0
	AND ((PO.Id = @rApprovalRequestId) OR (@rApprovalRequestId = 0))

	UNION

	SELECT
		AA.Id AS ApprovalActionId,
		AA.DocSourceId AS DocSourceId,
		AA.DocSourceTypeId AS DocSourceTypeId,
		WFM.Title AS WorkFlowName,
		WFM.Id AS WorkFlowId,
		PO.Id AS ApprovalRequestId,
		CONVERT(DATE,PO.CreatedDateTime, 103) AS CreatedDateTime,
		95 AS ParticipantSourceTypeId,
		EM.Id AS SourceId,
		EM.Code AS Code ,
		EM.FirstName +' '+ EM.MiddleName +' ' +EM.LastName AS Name ,
		--PR.Remark AS Remark,
		(CASE ISNULL(sm.Id,'') WHEN '' THEN 3 ELSE sm.Id END) AS statusId,
		(CASE ISNULL(sm.title,'') WHEN '' THEN 'Pending' ELSE sm.title END) AS status,
		ISNULL(AA.ActionRemark, '') AS ActionRemark
			
		
	from sPurchase.tPurchaseOrder PO
	INNER JOIN sWf.tWfApprovingAuthority FAA ON 3 = FAA.WfFunctionalityId And FAA.OrgId =@rOrgId
	INNER JOIN sSecurity.tUser U ON U.Id = FAA.AuthoritySourceId AND FAA.AuthoritySourceTypeId = 1019
	LEFT JOIN sWf.tWfApprovalAction AA ON AA.DocSourceId = PO.Id AND AA.WfFunctionalityId = FAA.WfFunctionalityId AND AA.DocSourceTypeId = 2042
	LEFT JOIN sWf.tWfStatusMaster SM ON SM.Id = AA.ActionStatusId
	INNER JOIN sWf.tWfFunctionalityMaster WFM ON WFM.Id = FAA.WfFunctionalityId
	LEFT JOIN  sHrm.tEmployeeMaster  EM ON EM.Id = AA.ActionEmployeeId
	WHERE U.Id = @rUserId
	AND ((WFM.Id = @rWfFunctionalityId) OR (@rWfFunctionalityId =0)) 
	AND ((Convert(Date,PO.CreatedDateTime)>= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
	AND ((Convert(Date,PO.CreatedDateTime) <= @rToDate) OR (ISNULL(@rToDate,'') = ''))
	AND((SM.Id = @rStatusId) OR (@rStatusId =0))
	AND ((EM.Code = @rCode) OR (@rCode =''))
	AND  ISNULL(EM.IsOtherUser,0) = 0
	AND ((PO.Id = @rApprovalRequestId) OR (@rApprovalRequestId = 0))

	UNION

	SELECT
		AA.Id AS ApprovalActionId,
		AA.DocSourceId AS DocSourceId,
		AA.DocSourceTypeId AS DocSourceTypeId,
		WFM.Title AS WorkFlowName,
		WFM.Id AS WorkFlowId,
		PO.Id AS ApprovalRequestId,
		CONVERT(DATE,PO.CreatedDateTime, 103) AS CreatedDateTime,
		95 AS ParticipantSourceTypeId,
		EM.Id AS SourceId,
		EM.Code AS Code ,
		EM.FirstName +' '+ EM.MiddleName +' ' +EM.LastName AS Name ,
		--PR.Remark AS Remark,
		(CASE ISNULL(sm.Id,'') WHEN '' THEN 3 ELSE sm.Id END) AS statusId,
		(CASE ISNULL(sm.title,'') WHEN '' THEN 'Pending' ELSE sm.title END) AS status,
		ISNULL(AA.ActionRemark, '') AS ActionRemark
			
		
	from sPurchase.tPurchaseOrder PO
	INNER JOIN sWf.tWfFunctionalityMaster WFM ON 3 = WFM.Id
	INNER JOIN sWf.tWfApprovalAction AA ON AA.DocSourceId = PO.Id AND AA.WfFunctionalityId = WFM.Id AND AA.DocSourceTypeId = 2042
	INNER JOIN sWf.tWfHierarchyLevel HL ON HL.WfApprovalActionId = AA.Id
	LEFT JOIN sWf.tWfStatusMaster SM ON SM.Id = AA.ActionStatusId
	LEFT JOIN  sHrm.tEmployeeMaster  EM ON EM.Id = AA.ActionEmployeeId
	WHERE HL.ActionByEmployeeId = @rUserId
	AND ((WFM.Id = @rWfFunctionalityId) OR (@rWfFunctionalityId =0)) 
	AND ((Convert(Date,PO.CreatedDateTime)>= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
	AND ((Convert(Date,PO.CreatedDateTime) <= @rToDate) OR (ISNULL(@rToDate,'') = ''))
	AND((SM.Id = @rStatusId) OR (@rStatusId =0))
	AND ((EM.Code = @rCode) OR (@rCode =''))
	AND  ISNULL(EM.IsOtherUser,0) = 0
	AND ((PO.Id = @rApprovalRequestId) OR (@rApprovalRequestId = 0))

	------------------------------------------------------------------------------------------------------------------------------------------------------------------
	UNION
	SELECT
		AA.Id AS ApprovalActionId,
		AA.DocSourceId AS DocSourceId,
		AA.DocSourceTypeId AS DocSourceTypeId,
		WFM.Title AS WorkFlowName,
		WFM.Id AS WorkFlowId,
		GRN.Id AS ApprovalRequestId,
		CONVERT(DATE,GRN.CreatedDateTime, 103) AS CreatedDateTime,
		95 AS ParticipantSourceTypeId,
		EM.Id AS SourceId,
		EM.Code AS Code ,
		EM.FirstName +' '+ EM.MiddleName +' ' +EM.LastName AS Name ,
		--PR.Remark AS Remark,
		(CASE ISNULL(sm.Id,'') WHEN '' THEN 3 ELSE sm.Id END) AS statusId,
		(CASE ISNULL(sm.title,'') WHEN '' THEN 'Pending' ELSE sm.title END) AS status,
		ISNULL(AA.ActionRemark, '') AS ActionRemark
			
		
	from sPurchase.tGoodsReceivedNote GRN
	INNER JOIN sWf.tWfApprovingAuthority FAA ON 4 = FAA.WfFunctionalityId And FAA.OrgId =@rOrgId
	INNER JOIN sSecurity.tRole R ON R.Id = FAA.AuthoritySourceId AND FAA.AuthoritySourceTypeId = 2015
	LEFT JOIN sWf.tWfApprovalAction AA ON AA.DocSourceId = GRN.Id AND AA.WfFunctionalityId = FAA.WfFunctionalityId AND AA.DocSourceTypeId = 2043
	LEFT JOIN sWf.tWfStatusMaster SM ON SM.Id = AA.ActionStatusId
	INNER JOIN sWf.tWfFunctionalityMaster WFM ON WFM.Id = FAA.WfFunctionalityId
	LEFT JOIN  sHrm.tEmployeeMaster  EM ON EM.Id = AA.ActionEmployeeId
	
	WHERE R.Id = @lRoleId
	AND ((WFM.Id = @rWfFunctionalityId) OR (@rWfFunctionalityId =0)) 
	AND ((Convert(Date,GRN.CreatedDateTime)>= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
	AND ((Convert(Date,GRN.CreatedDateTime) <= @rToDate) OR (ISNULL(@rToDate,'') = ''))
	AND((SM.Id = @rStatusId) OR (@rStatusId =0))
	AND ((EM.Code = @rCode) OR (@rCode = ''))
	AND  ISNULL(EM.IsOtherUser,0) = 0
	AND ((GRN.Id = @rApprovalRequestId) OR (@rApprovalRequestId = 0))

	UNION

	SELECT
		AA.Id AS ApprovalActionId,
		AA.DocSourceId AS DocSourceId,
		AA.DocSourceTypeId AS DocSourceTypeId,
		WFM.Title AS WorkFlowName,
		WFM.Id AS WorkFlowId,
		GRN.Id AS ApprovalRequestId,
		CONVERT(DATE,GRN.CreatedDateTime, 103) AS CreatedDateTime,
		95 AS ParticipantSourceTypeId,
		EM.Id AS SourceId,
		EM.Code AS Code ,
		EM.FirstName +' '+ EM.MiddleName +' ' +EM.LastName AS Name ,
		--AR.Remark AS Remark,
		(CASE ISNULL(sm.Id,'') WHEN '' THEN 3 ELSE sm.Id END) AS statusId,
		(CASE ISNULL(sm.title,'') WHEN '' THEN 'Pending' ELSE sm.title END) AS status,
		ISNULL(AA.ActionRemark, '') AS ActionRemark
			
		
	from sPurchase.tGoodsReceivedNote GRN
	INNER JOIN sWf.tWfApprovingAuthority FAA ON 4 = FAA.WfFunctionalityId And FAA.OrgId =@rOrgId
	INNER JOIN sSecurity.tUser U ON U.Id = FAA.AuthoritySourceId AND FAA.AuthoritySourceTypeId = 1019
	LEFT JOIN sWf.tWfApprovalAction AA ON AA.DocSourceId = GRN.Id AND AA.WfFunctionalityId = FAA.WfFunctionalityId AND AA.DocSourceTypeId = 2043
	LEFT JOIN sWf.tWfStatusMaster SM ON SM.Id = AA.ActionStatusId
	INNER JOIN sWf.tWfFunctionalityMaster WFM ON WFM.Id = FAA.WfFunctionalityId
	LEFT JOIN  sHrm.tEmployeeMaster  EM ON EM.Id = AA.ActionEmployeeId
	WHERE U.Id = @rUserId
	AND ((WFM.Id = @rWfFunctionalityId) OR (@rWfFunctionalityId =0)) 
	AND ((Convert(Date,GRN.CreatedDateTime)>= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
	AND ((Convert(Date,GRN.CreatedDateTime) <= @rToDate) OR (ISNULL(@rToDate,'') = ''))
	AND((SM.Id = @rStatusId) OR (@rStatusId =0))
	AND ((EM.Code = @rCode) OR (@rCode =''))
	AND  ISNULL(EM.IsOtherUser,0) = 0
	AND ((GRN.Id = @rApprovalRequestId) OR (@rApprovalRequestId = 0))

	UNION

	SELECT
		AA.Id AS ApprovalActionId,
		AA.DocSourceId AS DocSourceId,
		AA.DocSourceTypeId AS DocSourceTypeId,
		WFM.Title AS WorkFlowName,
		WFM.Id AS WorkFlowId,
		GRN.Id AS ApprovalRequestId,
		CONVERT(DATE,GRN.CreatedDateTime, 103) AS CreatedDateTime,
		95 AS ParticipantSourceTypeId,
		EM.Id AS SourceId,
		EM.Code AS Code ,
		EM.FirstName +' '+ EM.MiddleName +' ' +EM.LastName AS Name ,
		--AR.Remark AS Remark,
		(CASE ISNULL(sm.Id,'') WHEN '' THEN 3 ELSE sm.Id END) AS statusId,
		(CASE ISNULL(sm.title,'') WHEN '' THEN 'Pending' ELSE sm.title END) AS status,
		ISNULL(AA.ActionRemark, '') AS ActionRemark
			
		
	from sPurchase.tGoodsReceivedNote GRN
	INNER JOIN sWf.tWfFunctionalityMaster WFM ON 4 = WFM.Id
	INNER JOIN sWf.tWfApprovalAction AA ON AA.DocSourceId = GRN.Id AND AA.WfFunctionalityId = WFM.Id AND AA.DocSourceTypeId = 2043
	INNER JOIN sWf.tWfHierarchyLevel HL ON HL.WfApprovalActionId = AA.Id
	LEFT JOIN sWf.tWfStatusMaster SM ON SM.Id = AA.ActionStatusId
	LEFT JOIN  sHrm.tEmployeeMaster  EM ON EM.Id = AA.ActionEmployeeId
	WHERE HL.ActionByEmployeeId = @rUserId
	AND ((WFM.Id = @rWfFunctionalityId) OR (@rWfFunctionalityId =0)) 
	AND ((Convert(Date,GRN.CreatedDateTime)>= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
	AND ((Convert(Date,GRN.CreatedDateTime) <= @rToDate) OR (ISNULL(@rToDate,'') = ''))
	AND((SM.Id = @rStatusId) OR (@rStatusId =0))
	AND ((EM.Code = @rCode) OR (@rCode =''))
	AND  ISNULL(EM.IsOtherUser,0) = 0
	AND ((GRN.Id = @rApprovalRequestId) OR (@rApprovalRequestId = 0))

	------------------------------------------------------------------------------------------------------------------------------------------------------------------
	UNION
	SELECT
		AA.Id AS ApprovalActionId,
		AA.DocSourceId AS DocSourceId,
		AA.DocSourceTypeId AS DocSourceTypeId,
		WFM.Title AS WorkFlowName,
		WFM.Id AS WorkFlowId,
		SR.Id AS ApprovalRequestId,
		CONVERT(DATE,SR.CreatedDateTime, 103) AS CreatedDateTime,
		95 AS ParticipantSourceTypeId,
		EM.Id AS SourceId,
		EM.Code AS Code ,
		EM.FirstName +' '+ EM.MiddleName +' ' +EM.LastName AS Name ,
		--PR.Remark AS Remark,
		(CASE ISNULL(sm.Id,'') WHEN '' THEN 3 ELSE sm.Id END) AS statusId,
		(CASE ISNULL(sm.title,'') WHEN '' THEN 'Pending' ELSE sm.title END) AS status,
		ISNULL(AA.ActionRemark, '') AS ActionRemark
			
		
	from sPurchase.tSalesReturn SR
	INNER JOIN sWf.tWfApprovingAuthority FAA ON 5 = FAA.WfFunctionalityId And FAA.OrgId =@rOrgId
	INNER JOIN sSecurity.tRole R ON R.Id = FAA.AuthoritySourceId AND FAA.AuthoritySourceTypeId = 2015
	LEFT JOIN sWf.tWfApprovalAction AA ON AA.DocSourceId = SR.Id AND AA.WfFunctionalityId = FAA.WfFunctionalityId AND AA.DocSourceTypeId = 2044
	LEFT JOIN sWf.tWfStatusMaster SM ON SM.Id = AA.ActionStatusId
	INNER JOIN sWf.tWfFunctionalityMaster WFM ON WFM.Id = FAA.WfFunctionalityId
	LEFT JOIN  sHrm.tEmployeeMaster  EM ON EM.Id = AA.ActionEmployeeId
	
	WHERE R.Id = @lRoleId
	AND ((WFM.Id = @rWfFunctionalityId) OR (@rWfFunctionalityId =0)) 
	AND ((Convert(Date,SR.CreatedDateTime)>= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
	AND ((Convert(Date,SR.CreatedDateTime) <= @rToDate) OR (ISNULL(@rToDate,'') = ''))
	AND((SM.Id = @rStatusId) OR (@rStatusId =0))
	AND ((EM.Code = @rCode) OR (@rCode = ''))
	AND  ISNULL(EM.IsOtherUser,0) = 0
	AND ((SR.Id = @rApprovalRequestId) OR (@rApprovalRequestId = 0))

	UNION

	SELECT
		AA.Id AS ApprovalActionId,
		AA.DocSourceId AS DocSourceId,
		AA.DocSourceTypeId AS DocSourceTypeId,
		WFM.Title AS WorkFlowName,
		WFM.Id AS WorkFlowId,
		SR.Id AS ApprovalRequestId,
		CONVERT(DATE,SR.CreatedDateTime, 103) AS CreatedDateTime,
		95 AS ParticipantSourceTypeId,
		EM.Id AS SourceId,
		EM.Code AS Code ,
		EM.FirstName +' '+ EM.MiddleName +' ' +EM.LastName AS Name ,
		--AR.Remark AS Remark,
		(CASE ISNULL(sm.Id,'') WHEN '' THEN 3 ELSE sm.Id END) AS statusId,
		(CASE ISNULL(sm.title,'') WHEN '' THEN 'Pending' ELSE sm.title END) AS status,
		ISNULL(AA.ActionRemark, '') AS ActionRemark
			
		
	from sPurchase.tSalesReturn SR
	INNER JOIN sWf.tWfApprovingAuthority FAA ON 4 = FAA.WfFunctionalityId And FAA.OrgId =@rOrgId
	INNER JOIN sSecurity.tUser U ON U.Id = FAA.AuthoritySourceId AND FAA.AuthoritySourceTypeId = 1019
	LEFT JOIN sWf.tWfApprovalAction AA ON AA.DocSourceId = SR.Id AND AA.WfFunctionalityId = FAA.WfFunctionalityId AND AA.DocSourceTypeId = 2043
	LEFT JOIN sWf.tWfStatusMaster SM ON SM.Id = AA.ActionStatusId
	INNER JOIN sWf.tWfFunctionalityMaster WFM ON WFM.Id = FAA.WfFunctionalityId
	LEFT JOIN  sHrm.tEmployeeMaster  EM ON EM.Id = AA.ActionEmployeeId
	WHERE U.Id = @rUserId
	AND ((WFM.Id = @rWfFunctionalityId) OR (@rWfFunctionalityId =0)) 
	AND ((Convert(Date,SR.CreatedDateTime)>= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
	AND ((Convert(Date,SR.CreatedDateTime) <= @rToDate) OR (ISNULL(@rToDate,'') = ''))
	AND((SM.Id = @rStatusId) OR (@rStatusId =0))
	AND ((EM.Code = @rCode) OR (@rCode =''))
	AND  ISNULL(EM.IsOtherUser,0) = 0
	AND ((SR.Id = @rApprovalRequestId) OR (@rApprovalRequestId = 0))

	UNION

	SELECT
		AA.Id AS ApprovalActionId,
		AA.DocSourceId AS DocSourceId,
		AA.DocSourceTypeId AS DocSourceTypeId,
		WFM.Title AS WorkFlowName,
		WFM.Id AS WorkFlowId,
		SR.Id AS ApprovalRequestId,
		CONVERT(DATE,SR.CreatedDateTime, 103) AS CreatedDateTime,
		95 AS ParticipantSourceTypeId,
		EM.Id AS SourceId,
		EM.Code AS Code ,
		EM.FirstName +' '+ EM.MiddleName +' ' +EM.LastName AS Name ,
		--AR.Remark AS Remark,
		(CASE ISNULL(sm.Id,'') WHEN '' THEN 3 ELSE sm.Id END) AS statusId,
		(CASE ISNULL(sm.title,'') WHEN '' THEN 'Pending' ELSE sm.title END) AS status,
		ISNULL(AA.ActionRemark, '') AS ActionRemark
			
		
	from sPurchase.tSalesReturn SR
	INNER JOIN sWf.tWfFunctionalityMaster WFM ON 5 = WFM.Id
	INNER JOIN sWf.tWfApprovalAction AA ON AA.DocSourceId = SR.Id AND AA.WfFunctionalityId = WFM.Id AND AA.DocSourceTypeId = 2044
	INNER JOIN sWf.tWfHierarchyLevel HL ON HL.WfApprovalActionId = AA.Id
	LEFT JOIN sWf.tWfStatusMaster SM ON SM.Id = AA.ActionStatusId
	LEFT JOIN  sHrm.tEmployeeMaster  EM ON EM.Id = AA.ActionEmployeeId
	WHERE HL.ActionByEmployeeId = @rUserId
	AND ((WFM.Id = @rWfFunctionalityId) OR (@rWfFunctionalityId =0)) 
	AND ((Convert(Date,SR.CreatedDateTime)>= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
	AND ((Convert(Date,SR.CreatedDateTime) <= @rToDate) OR (ISNULL(@rToDate,'') = ''))
	AND((SM.Id = @rStatusId) OR (@rStatusId =0))
	AND ((EM.Code = @rCode) OR (@rCode =''))
	AND  ISNULL(EM.IsOtherUser,0) = 0
	AND ((SR.Id = @rApprovalRequestId) OR (@rApprovalRequestId = 0))
END
GO
PRINT N'Creating Procedure [sWf].[pWfSetupGet]...';


GO


CREATE PROCEDURE [sWf].[pWfSetupGet]
	  @rId smallint,
	  @rOrgGroupId smallint
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
		select WFS.AutoId,
			   WFS.WfTypeMasterId,
			   WFS.WfLevel,
			   WFS.OrgGroupId,
			   WFS.WfFunctionalityId
		from   [sWf].[tWfSetup] WFS(nolock) 
		where  WFS.AutoId = @rId AND WFS.OrgGroupId = @rOrgGroupId AND WFS.IsObsolete = 0
	END TRY

	BEGIN CATCH
    IF @@TRANCOUNT > 0
        ROLLBACK TRAN --RollBack in case of Error
    
    DECLARE @ErrorMessage NVARCHAR(4000);  
    DECLARE @ErrorSeverity INT;  
    DECLARE @ErrorState INT;  
    SELECT   
       @ErrorMessage = ERROR_MESSAGE(),  
       @ErrorSeverity = ERROR_SEVERITY(),  
       @ErrorState = ERROR_STATE();  
    RAISERROR (@ErrorMessage, @ErrorSeverity, @ErrorState);  
    
	END CATCH

END
GO
PRINT N'Creating Procedure [sWf].[pWfSetupAdd]...';


GO



CREATE PROCEDURE [sWf].[pWfSetupAdd]
		@rId [smallint],
		@rWfTypeMasterId [smallint],
		@rLevel [smallint],
		@rOrgGroupId [smallint],
		@rWfFunctionalityId [smallint]
		--,
		--@rIsObsolete [bit]=false
       
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
	BEGIN TRANSACTION
		BEGIN
			IF(@rId = 0)
			BEGIN
				INSERT INTO [sWf].[tWfSetup]
				(
				WfTypeMasterId,
				WfLevel,
				OrgGroupId,
				WfFunctionalityId,
				IsObsolete
				)
				VALUES
				(
				@rWfTypeMasterId,
				@rLevel,
				@rOrgGroupId,
				@rWfFunctionalityId,
				0
				)
				SELECT @rId = Scope_Identity()
			END
			ELSE
			BEGIN
				UPDATE [sWf].[tWfSetup]
				SET 
					WfTypeMasterId = @rWfTypeMasterId,
					WfLevel = @rLevel,
					OrgGroupId = @rOrgGroupId,
					WfFunctionalityId = @rWfFunctionalityId
				WHERE AutoId =@rId
				SELECT @rId
			END
		END
	COMMIT TRANSACTION
	END TRY	
	BEGIN CATCH
		ROLLBACK TRANSACTION
		SELECT -1 AS RESULT
	END CATCH
END
GO
PRINT N'Creating Procedure [sWf].[pWfUserGet]...';


GO


CREATE PROCEDURE [sWf].[pWfUserGet]
	  @rOrgGroupId smallint
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
		select U.Id,
	           U.DisplayTitle 
		from   sSecurity.tUser U (nolock)
		INNER JOIN sSecurity.tUserRole UR ON UR.UserId = U.Id
		INNER JOIN sSecurity.tRole R ON R.Id = UR.RoleId 
		where U.IsObsolete='0' AND UR.IsObsolete='0' AND U.OrgId = @rOrgGroupId
		AND   R.Id <> ([sCommon].[fGetIntIdForOrg](21,@rOrgGroupId)) 
		AND   R.Id <> ([sCommon].[fGetIntIdForOrg](22,@rOrgGroupId))
	END TRY

	BEGIN CATCH
    IF @@TRANCOUNT > 0
        ROLLBACK TRAN --RollBack in case of Error
    
    DECLARE @ErrorMessage NVARCHAR(4000);  
    DECLARE @ErrorSeverity INT;  
    DECLARE @ErrorState INT;  
    SELECT   
       @ErrorMessage = ERROR_MESSAGE(),  
       @ErrorSeverity = ERROR_SEVERITY(),  
       @ErrorState = ERROR_STATE();  
    RAISERROR (@ErrorMessage, @ErrorSeverity, @ErrorState);  
    
	END CATCH

END
GO
PRINT N'Creating Procedure [sWf].[pWfApprovingAuthorityAdd]...';


GO




CREATE PROCEDURE [sWf].[pWfApprovingAuthorityAdd]
		@rId [int],
		@rAuthoritySourceTypeId [smallint],
		@rAuthoritySourceId [bigint],
		@rOrgId [smallint],
		@rWfFunctionalityId [smallint]
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
	BEGIN TRANSACTION
		IF(@rId = 0)
		BEGIN
			INSERT INTO sWf.tWfApprovingAuthority
			(
			AuthoritySourceTypeId,
			AuthoritySourceId,
			OrgId,
			WfFunctionalityId
			)
			VALUES
			(
			@rAuthoritySourceTypeId,
			@rAuthoritySourceId,
			@rOrgId,
			@rWfFunctionalityId
			)
			SELECT @rId = SCOPE_IDENTITY()
		END
		ELSE
		BEGIN
			DELETE FROM sWf.tWfApprovingAuthority
			WHERE OrgId = @rOrgId AND WfFunctionalityId = @rWfFunctionalityId
			AND AuthoritySourceTypeId = @rAuthoritySourceTypeId

			INSERT INTO sWf.tWfApprovingAuthority
			(
			AuthoritySourceTypeId,
			AuthoritySourceId,
			OrgId,
			WfFunctionalityId
			)
			VALUES
			(
			@rAuthoritySourceTypeId,
			@rAuthoritySourceId,
			@rOrgId,
			@rWfFunctionalityId
			)
			SELECT @rId = SCOPE_IDENTITY()
		END
	COMMIT TRANSACTION
	END TRY	
	BEGIN CATCH
		ROLLBACK TRANSACTION
		SELECT -1 AS RESULT
	END CATCH
END
GO
PRINT N'Creating Procedure [sWf].[pWfApprovingAuthorityGet]...';


GO



CREATE PROCEDURE [sWf].[pWfApprovingAuthorityGet]
	  @rOrgId smallint,
	  @rWfFunctionalityId int
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
		select AutoId,
			   AuthoritySourceTypeId,
			   AuthoritySourceId,
			   OrgId,
			   WfFunctionalityId
        from   sWf.tWfApprovingAuthority (nolock)
        where  OrgId = @rOrgId AND WfFunctionalityId = @rWfFunctionalityId  
		ORDER BY WfFunctionalityId
	END TRY

	BEGIN CATCH
    IF @@TRANCOUNT > 0
        ROLLBACK TRAN --RollBack in case of Error
    
    DECLARE @ErrorMessage NVARCHAR(4000);  
    DECLARE @ErrorSeverity INT;  
    DECLARE @ErrorState INT;  
    SELECT   
       @ErrorMessage = ERROR_MESSAGE(),  
       @ErrorSeverity = ERROR_SEVERITY(),  
       @ErrorState = ERROR_STATE();  
    RAISERROR (@ErrorMessage, @ErrorSeverity, @ErrorState);  
    
	END CATCH

END
GO
PRINT N'Creating Procedure [sWf].[pWfRoleGet]...';


GO



CREATE PROCEDURE [sWf].[pWfRoleGet]
	  @rOrgGroupId smallint
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
		select Id,
			   Title 
	    from   sSecurity.tRole (nolock)
		where  IsObsolete='0' AND OrgGroupId = @rOrgGroupId
          AND  Id <> ([sCommon].[fGetIntIdForOrg](21,@rOrgGroupId)) 
		  AND  Id <> ([sCommon].[fGetIntIdForOrg](22,@rOrgGroupId))
	END TRY

	BEGIN CATCH
    IF @@TRANCOUNT > 0
        ROLLBACK TRAN --RollBack in case of Error
    
    DECLARE @ErrorMessage NVARCHAR(4000);  
    DECLARE @ErrorSeverity INT;  
    DECLARE @ErrorState INT;  
    SELECT   
       @ErrorMessage = ERROR_MESSAGE(),  
       @ErrorSeverity = ERROR_SEVERITY(),  
       @ErrorState = ERROR_STATE();  
    RAISERROR (@ErrorMessage, @ErrorSeverity, @ErrorState);  
    
	END CATCH

END
GO
PRINT N'Creating Procedure [sWf].[pWfFunctionalityMasterGet]...';


GO


CREATE PROCEDURE [sWf].[pWfFunctionalityMasterGet]
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
		SELECT Id,
			   Code,
			   Title,
			   IsObsolete
			   --Type
		FROM   sWf.tWfFunctionalityMaster(nolock)
		WHERE  IsObsolete = 0
	END TRY

	BEGIN CATCH
    IF @@TRANCOUNT > 0
        ROLLBACK TRAN --RollBack in case of Error
    
    DECLARE @ErrorMessage NVARCHAR(4000);  
    DECLARE @ErrorSeverity INT;  
    DECLARE @ErrorState INT;  
    SELECT   
       @ErrorMessage = ERROR_MESSAGE(),  
       @ErrorSeverity = ERROR_SEVERITY(),  
       @ErrorState = ERROR_STATE();  
    RAISERROR (@ErrorMessage, @ErrorSeverity, @ErrorState);  
    
	END CATCH

END
GO
PRINT N'Creating Procedure [sWf].[pWfTypeMasterGet]...';


GO


CREATE PROCEDURE [sWf].[pWfTypeMasterGet]
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
		SELECT  Id,
				Code,
				Title,
				IsObsolete
		FROM    sWf.tWfTypeMaster(nolock)
		WHERE   IsObsolete = 0
	END TRY

	BEGIN CATCH
    IF @@TRANCOUNT > 0
        ROLLBACK TRAN --RollBack in case of Error
    
    DECLARE @ErrorMessage NVARCHAR(4000);  
    DECLARE @ErrorSeverity INT;  
    DECLARE @ErrorState INT;  
    SELECT   
       @ErrorMessage = ERROR_MESSAGE(),  
       @ErrorSeverity = ERROR_SEVERITY(),  
       @ErrorState = ERROR_STATE();  
    RAISERROR (@ErrorMessage, @ErrorSeverity, @ErrorState);  
    
	END CATCH

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


GO
CREATE PROCEDURE [sAlert].[pAlertQueueDashboardGet]
	@rOrgGroupId int =0,
	@rFromDate date = '',
	@rToDate date = '',
	@rTypeId smallint = 1

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON			 
BEGIN 
	IF(@rTypeId = 1) -- OrgGroup wise Summary
	BEGIN
		SELECT 
			OGM.Id AS OrgGroupId, 
			OGM.Title AS OrgGroupTitle, 
			COUNT(AQL.AutoId) AS QueueAlertTotal, 
			COUNT(QL.Id) AS ReceivedQueueAlertTotal
		FROM sAlert.tAlertQueueLog AQL
		LEFT JOIN sSetup.tOrganizationMaster OM ON OM.Id = AQL.OrgId
		LEFT JOIN sSetup.tOrgGroupMaster OGM ON OGM.Id = OM.OrgGroupId
		LEFT JOIN NVQueue.dbo.QueueLog QL ON AQL.AutoId = QL.MessageId
		WHERE OGM.Id = @rOrgGroupId OR @rOrgGroupId = 0
			AND (AQL.CreatedDateTime >= @rFromDate OR ISNULL(@rFromDate, '') = '')
			AND (AQL.CreatedDateTime <= @rToDate OR ISNULL(@rToDate, '') = '')
		GROUP BY OGM.Id, OGM.Title
	END
	IF(@rTypeId = 2) -- Organization wise Summary
	BEGIN
		SELECT 
			AQL.OrgId AS OrgId, 
			OM.Title AS OrganizationTitle,
			COUNT(AQL.AutoId) AS QueueAlertTotal, 
			COUNT(QL.Id) AS ReceivedQueueAlertTotal
		FROM sAlert.tAlertQueueLog AQL
		LEFT JOIN sSetup.tOrganizationMaster OM ON OM.Id = AQL.OrgId
		LEFT JOIN sSetup.tOrgGroupMaster OGM ON OGM.Id = OM.OrgGroupId
		LEFT JOIN NVQueue.dbo.QueueLog QL ON AQL.AutoId = QL.MessageId
		WHERE OGM.Id = @rOrgGroupId OR @rOrgGroupId = 0
			AND (AQL.CreatedDateTime >= @rFromDate OR ISNULL(@rFromDate, '') = '')
			AND (AQL.CreatedDateTime <= @rToDate OR ISNULL(@rToDate, '') = '')
		GROUP BY AQL.OrgId, OM.Title
	END
END
GO
PRINT N'Creating Procedure [sAssessment].[pRptLearningOutcomesGet]...';


GO
CREATE PROCEDURE [sAssessment].[pRptLearningOutcomesGet]
	 
	 @rBuilder1 nvarchar(max)='', 
	 @rBuilder2 nvarchar(max)='', 
	 @rBatchId int = 0,
	 @rClassId int=0,
	 @rDivisionId int=0,
	 @rExamSubGroupId int, 
	 --@rCode nvarchar(20)='',
	 @rFromRollNo int,
	 @rToRollNo int,
	 @rStatusId int=0,
	 @rClassStatusId int=0,
	 @rDepartmentId int=0
	 		 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN

SELECT 
	@rBuilder1 AS Builder1,
	@rBuilder2 AS Builder2,
	ESGM.Title AS ExamName,
	--TSD.EmployeeId,
	--EmpM.FirstName,
	--EmpM.MiddleName,
	--EmpM.LastName,
	--EmpM.FirstName + ' ' + EmpM.MiddleName + ' ' + EmpM.LastName AS EmployeeName,
	--EmpM.Code AS EmployeeCode,
	--SM.Id AS SubjectId,
	--SM.Code AS SubjectCode,
	--SM.Title AS SubjectName,
	DM.Id AS DivisionId,
	DM.DisplayTitle AS DivisionName,
	DM.OrderIndex AS DivisionOrder,
	CM.Id AS ClassId,
	CM.DisplayTitle AS ClassName,
	CM.OrderIndex AS ClassOrder,
	(CM.DisplayTitle + ' - ' + DM.DisplayTitle) AS ClassDivision,
	A.Id As AcademicId,
	EM.Id AS ExamId,
	--RD.Obtain AS SubjectObtain,
	--ED.Maximum AS SubjectMaximum,
	--CONVERT(Int,ROUND((ISNULL(RD.Obtain, 0) * 100) / ED.Maximum, 0)) AS SubjectPercentage,
	--RD.SubjectGrade,
	BM.Title AS BatchName,
	Round(R.Percentage,0)AS Percentage

	FROM 
		--sAssessment.tResultDetail RD
		sAssessment.tResult R 
		--INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId
		INNER JOIN sAssessment.tExamMaster EM ON EM.Id=R.ExamId 		
		INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId
		--INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
		--INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=CS.SubjectId					 
		INNER JOIN sStudent.tAcademic A ON A.Id=R.AcademicId	
		INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId		
		INNER JOIN sStudent.tStudentMaster StuM ON StuM.Id=A.StudentId			
		INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId
		INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId			
		--INNER JOIN sSetup.tOrganizationMaster OM ON StuM.OrgId = OM.Id			
		--INNER JOIN sAcademic.tTeacherSubjectDivision TSD ON SM.Id = TSD.SubjectId AND DM.Id = TSD.DivisionId
		--INNER JOIN sHrm.tEmployeeMaster EmpM ON TSD.EmployeeId = EmpM.Id AND EmpM.StatusId = 7			
		--LEFT JOIN sHostel.tAssignRoom ARO ON  ARO.SourceId=StuM.Id AND ARO.SourceTypeId=2003 AND ((BM.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  AND ((ARO.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0) AND (BM.OrgGroupBatchId = ARO.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 
			
	WHERE ESGM.Id = @rExamSubGroupId
		AND ((EM.BatchId = @rBatchId) OR  (@rBatchId = 0))
		AND ((A.ClassId=@rClassId) OR (@rClassId=0)) 
		AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		AND ((A.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
		AND ((A.RollNo <= @rToRollNo) OR (@rToRollNo=0))
		--AND ((StuM.Code=@rCode) OR (@rCode=''))
		AND ((StuM.StatusId = @rStatusId) OR (@rStatusId = 0))
		AND ((CM.DepartmentId = @rDepartmentId) OR (@rDepartmentId = 0))		
		AND ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0))
END
GO
PRINT N'Creating Procedure [sAssessment].[pRptSubjectActivityMaxMarkGradeTwoColumnGet]...';


GO

CREATE PROCEDURE [sAssessment].[pRptSubjectActivityMaxMarkGradeTwoColumnGet]
	 
		@rOrgId int=0,
		@rExamId int=0,
		@rClass int=0,
		@rDivisionId int=0,
		@rBatchId int=0,
		@rBuilder1 nvarchar(max)='',
		@rAcademicId bigint=0,
		@rCode nvarchar(20)='',
		@rFromRollNo int=0,
		@rToRollNo int=0,
		@rMultiCode nvarchar(max)=''
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON 
BEGIN 	 

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

Declare @DecimalConfid nvarchar(20)=''
SELECT @DecimalConfid =ItemValue From sConfig.tConfigurationSetup WHERE ConfigurationId = 496 AND SourceTypeId = 1016 AND SourceId = @rOrgId

	SELECT 			 
			Convert(nvarchar(20),SA.Id) AS AcademicIdText,	
			CONVERT (nvarchar(20),@rExamId) AS ExamIdText, 
			@rBuilder1 AS Builder1,
			SA.Id AS AcademicId,
			SA.RollNo,
			StuM.Number,
			AIS.Grade,
			SAM.Title AS SubjectActivityTitle,
			SSA.Title AS SubjectSubActivityTitle,
			SAM.Id AS ActivityId,
			SSA.Id AS SubjectSubActivityId,
			SAM.OrderIndex AS ActivityOrderIndex,
			SSA.OrderIndex AS SubjectSubActivityOrderIndex ,
			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,
			EM.IsDisplayGradeString,
			EM.IsDisplayParentName,
			[sStudent].[fStudentNameGet](StuM.FirstName , ISNULL(StuM.MiddleName,'') , StuM.LastName,OM.StudentNameFormatId ) AS Name,
			SO.DateOfBirth,
			CMM.Title AS ClassName,
			StuM.code,
			SF.FatherName,
			SF.MotherName,
			SAM.ClassSubjectId ,
			SM.Title AS SubjectName,
			SM.OrderIndex AS SubjectOrderIndex,
			CMM.DisplayTitle AS Class,
			DM.DisplayTitle AS Division,
			CASE WHEN EM.IsDisplayPhoto = 1 THEN SI.StudentPhoto ELSE NULL END AS StudentPhoto, 
			ISNULL(AIS.DescriptiveIndicator,'') AS DescriptiveIndicator,
			CASE WHEN CS.OrderIndex % 2 = 0 THEN 2 
			ELSE 1 END AS ColumnSubjectCount,
			CS.OrderIndex,
			EM.SubjectGroupPerPage,
			AIS.GradeIndicator,
			EM.IsCoScholasticGradeIndicator,
			CASE WHEN EM.IsDisplayTeacherSign = 1 THEN EI.EmployeeSign ELSE NULL END AS EmployeeSign,
			Em.IsDisplayPrincipalSign,
			EM.IsDisplayTeacherSign,
			EM.IsCoScholasticGradeDesIndicator,
			EM.IsCoScholasticGrade,
			Em.IsDisplayParentName,
			(CASE EM.IsDisplayImageHeader WHEN 1 THEN 
			OI.MarksheetHeaderA4 
			ELSE 
			NULL END) AS MarksheetHeaderA4,
			ISNULL(EM.IsDisplayImageHeader,0) AS IsImageHeader,
			RD.Remark,
			
			HM.Title AS House,
			BM.Title AS BAtch ,
			[sAttendance].[fSubjectTeacherGet](SA.DivisionId,SM.ID) AS TEacherName,
			ED.IsShowSubjectGrade,
			CASE @GradeStringRemark WHEN '' THEN @GradeString  ELSE @GradeStringRemark END AS GradeString,
			--@GradeString AS GradeString,
			Convert(nvarchar(20),ISNULL(Em.IsDisplayMonthlyAttendance,0)) As IsDisplayMonthlyAttendanceText,
			TeacherSignCaption,
			EM.PrincipalSignCaption,
			ParentSignCaption,
			--CASE WHEN EM.IsDisplayTeacherSign = 1 THEN EM.TeacherSignCaption ELSE NULL END AS TeacherSignCaption,
			--CASE WHEN EM.IsDisplayPrincipalSign = 1 THEN EM.PrincipalSignCaption ELSE NULL END AS PrincipalSignCaption,
			SR.ResultRemark1,
			SR.ResultRemark2,	
			SR.ResultRemark3,
			SR.ClassTeacherRemark,
			SR.HouseRemark,
			ISNULL(SR.PresentDays,0)AS PresentDays,			
			ISNULL(SR.TotalDays,0)AS TotalDays,
			SR.StudentHeight,
			SR.StudentWeight,
			
			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,
			ISNULL(SR.ImprovementArea,'') As ImprovementArea,
			ISNULL(SR.ProgressArea,'') AS ProgressArea,
			ISNULL(SR.GeneralRemark,'') As GeneralRemark,
			ISNULL(SR.MyActivity,'') AS MyActivity,
			ISNULL(SF.FatherContactNo,'') AS FatherContactNo,
			ISNULL(SF.MotherContactNo,'') AS MotherContactNo,
			ISNULL(SF.FatherMail,'') AS FatherMail,
			ISNULL(SF.MotherMail,'') AS MotherMail,
			ISNULL(SC.PresentStreetONe,'')+' '+ISNULL(SC.PresentStreetTwo,'')+' '+ISNULL(SC.PresentStreetThree,'')+' '+ISNULL(SC.PresentCity,'')+' '+ISNULL(SC.PresentState,'') AS PresentAddress,
			DivisionId,
			SM.ID,
			( EmpM.FirstName + ' ' +EmpM.LastName ) AS InchargeEmployeeName,
			ISNULL(SC.ParentContactNo,'') AS ParentContactNo,
			CONVERT(bit,@DecimalConfid) AS IsDecimal,
			AIS.Marks,
			SR.ExamSeatNo AS ExamSeatNo,					--add for 27710 mantis
			[sAssessment].[fSubjectWiseGradeGet](SA.Id,@rExamId,SAM.Id,SAM.ClassSubjectId,@rBatchId,@rClass) AS SubjectGrade,
			ED.Maximum AS SubjectMaximum

	 FROM 
			sAssessment.tCCESubjectSubActivityExamScore AIS 
			INNER JOIN sAssessment.tCCESubjectSubActivityMaster SSA ON AIS.SubjectSubActivityId = SSA.Id 
			INNER JOIN	sAssessment.tCCESubjectActivityMaster SAM  ON SAM.Id = SSA.SubjectActivityId			
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=SAM.ClassSubjectId		
			INNER JOIN sStudent.tAcademic SA ON SA.Id = AIS.AcademicId 
			INNER JOIN sStudent.tStudentMaster StuM ON StuM.Id=SA.StudentId
			INNER JOIN sAssessment.tExamMaster EM ON EM.Id=AIS.ExamId
			INNER JOIN sAssessment.tExamDetail ED ON EM.Id=ED.ExamId AND ED.ClassSubjectId = CS.Id 		 			 
			INNER JOIN sAssessment.tResult AR ON AR.ExamId = AIS.ExamId AND AIS.AcademicId = AR.AcademicId
			INNER JOIN sAssessment.tResultDetail ARD ON ARD.ResultId = AR.Id AND ARD.ExamDetailId = ED.Id
			LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId=SA.StudentId
			LEFT JOIN sActivity.tHouseMaster HM ON HM.Id=SO.HouseId
			LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId=SA.StudentId	
			INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=CS.SubjectId
			INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=SA.divisionId	
			INNER JOIN sSetup.tClassMaster CMM ON CMM.Id=DM.ClassId 
			LEFT JOIN sHrm.tEmployeeMaster EmpM 
				ON EmpM.Id = DM.InchargeEmployeeId AND EmpM.IsObsolete = 0
			LEFT JOIN sHrm.tEmployeeImages EI ON EI.EmployeeId = Dm.InchargeEmployeeId
			--LEFT JOIN sAcademic.tTeacherSubjectDivision TSD ON TSD.DivisionId = DM.Id AND TSD.SubjectId = SM.Id 
			--LEFT JOIN sHrm.tEmployeeMaster EMP ON EMP.Id = TSD.EmployeeId
			LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId = SA.StudentId
			LEFT JOIN sAssessment.tStudentRemark SR ON SA.Id = SR.AcademicId	AND EM.Id = SR.ExamId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = Stum.OrgId
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id= SA.BatchID
			LEFT JOIN sSetup.tOrgImages OI ON OI.OrgId = Om.Id
			LEFT JOIN sAssessment.tResultDetailOther RD ON RD.AcademicId = SA.Id AND EM.ID=RD.ExamId AND CS.Id=RD.ClassSubjectID 
			LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId =StuM.ID
	    --LEFT JOIN @lAcademicId A ON A.AcademicId = SA.AcademicId AND A.ClassSubjectId = ED.ClassSubjectId
			----------------------------------------------------------------------------
			--sAssessment.tCCESubjectActivityMaster SAM 	
			--INNER JOIN sAssessment.tCCESubjectSubActivityMaster SSA ON SAM.Id=SSA.SubjectActivityId 
			--INNER JOIN sAssessment.vCCEExamClassSubject CS ON CS.ClassSubjectId=SAM.ClassSubjectId
			--INNER JOIN sSetup.tClassMaster CMM ON CMM.Id=CS.ClassId 
			--INNER JOIN sStudent.vStudentAcademic SA ON SA.ClassId = CS.ClassId 
			--INNER JOIN sStudent.tStudentMaster StuM ON StuM.Id=SA.StudentId			 
			--LEFT JOIN sAssessment.tCCESubjectSubActivityExamScore AIS ON AIS.AcademicId =SA.AcademicId AND AIS.SubjectSubActivityId= SSA.Id 	
			--LEFT JOIN sAssessment.tExamMaster EM ON EM.Id=AIS.ExamId
			--LEFT JOIN sAssessment.tExamDetail ED ON EM.Id=ED.ExamId	AND ED.ClassSubjectId = CS.ClassSubjectId 		 
			--LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId=SA.StudentId
			--LEFT JOIN sActivity.tHouseMaster HM ON HM.Id=SO.HouseId
			--LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId=SA.StudentId	
			--INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=CS.SubjectId	
			--INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=SA.divisionId
			--LEFT JOIN sHrm.tEmployeeImages EI ON EI.EmployeeId = Dm.InchargeEmployeeId
			--LEFT JOIN sAcademic.tTeacherSubjectDivision TSD ON TSD.DivisionId = DM.Id AND TSD.SubjectId = SM.Id 
			--LEFT JOIN sHrm.tEmployeeMaster EMP ON EMP.Id = TSD.EmployeeId
			--LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId = SA.StudentId
			--LEFT JOIN sAssessment.tStudentRemark SR ON SA.AcademicId = SR.AcademicId	AND EM.Id = SR.ExamId
			--INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = Stum.OrgId
			--INNER JOIN sSetup.tBatchMaster BM ON BM.Id= SA.BatchID
			--LEFT JOIN sSetup.tOrgImages OI ON OI.OrgId = Om.Id
			--LEFT JOIN sAssessment.tResultDetailOther RD ON RD.AcademicId = SA.AcademicId AND EM.ID=RD.ExamId AND CS.ClassSubjectId=RD.ClassSubjectID 
		WHERE
			((SA.Id=@rAcademicId) OR(@rAcademicId=0))
			AND ((CS.ClassId=@rClass) OR (@rClass=0))
			And ((SA.DivisionId =@rDivisionId) or(@rDivisionId=0))	
			And ((SA.BatchId =@rBatchId) OR (@rBatchId=0))
			and ((SA.OrgId=@rOrgId) OR (@rOrgId=0))
			And AIS.ExamId=@rExamId
			AND ((STum.Code = @rCode) OR(@rCode=''))
			AND ((SA.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
			AND ((SA.RollNo <= @rToRollNo) OR (@rToRollNo=0))
			AND StuM.StatusId = 1
			AND (ISNULL(STum.Code,0) IN( SELECT cast(item as nvarchar(20)) FROM  sCommon.fnsplit(@rMultiCode,',')) OR @rMultiCode='')
			AND SAM.IsObsolete = 0
		ORDER BY 
			SA.RollNo ASC,
			SAM.OrderIndex ASC,
			SSA.OrderIndex ASC;
END
GO
PRINT N'Creating Procedure [sAttendance].[pRptStudentRegisterSubjectWiseGet]...';


GO
 
CREATE PROCEDURE [sAttendance].[pRptStudentRegisterSubjectWiseGet]
	 	 	  
		 @rBuilder1 nvarchar(max)='',
	     @rBuilder2 nvarchar(max)='', 
		 @rOrgId smallint,
		 @rBatchId int,
		 @rClassId int,
		 @rDivisionId int,
		 @rSubjectId int,
		 @rFromDate date,
		 @rToDate date,
		 @rStudentCode nvarchar(20),
		 @rReportId int = 0,
		 @rDepartmentId int,
		 @rPeriodNo int,
		 @rStatusId int=0
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
SET @rToDate = DATEADD (d,1,@rToDate)

	BEGIN
		Select 
		@rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,
		SA.AcademicId,
		SA.Name,
		SA.Code,
		SA.RollNo,
		SA.ClassId,
		SA.ClassName,
		SA.DivisionId,
		SA.DivisionName,
		SA.DivisionOrder,
		R.AttendanceDate,
		ISNULL(SM.Id,0) AS SubjectId,
		ISNULL(SM.Code,'') AS SubjectCode,
		ISNULL(SM.Title,'') AS SubjectName,
		R.IsPresent,
		R.PeriodNo,
		ISNULL((SELECT COUNT(1) FROM sAttendance.tStudentRegister SR WHERE SR.AcademicId = SA.ACademicID 
		AND SR.SubjectId = R.SubjectId		
		AND((SR.AttendanceDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
		AND ((SR.AttendanceDate < @rToDate) OR (ISNULL(@rToDate,'')=''))
		AND (SR.IsPresent = 1)
		AND SR.AttendanceTypeId = 5
		Group BY SR.AcademicId,SR.SubjectId),0) AS TotalPresentCount,
		
		ISNULL((SELECT COUNT(1) FROM sAttendance.tStudentRegister SR WHERE SR.AcademicId = SA.ACademicID 
		AND SR.SubjectId = R.SubjectId		
		AND((SR.AttendanceDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
		AND ((SR.AttendanceDate < @rToDate) OR (ISNULL(@rToDate,'')=''))
		AND (SR.IsPresent = 0)
		AND SR.AttendanceTypeId = 5
		Group BY SR.AcademicId,SR.SubjectId),0) AS TotalAbsentCount

		
	From 
	sAttendance.tStudentRegister R	 
	INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.AcademicId
	INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=R.SubjectId
	WHERE
		((R.SubjectId=@rSubjectId) OR (@rSubjectId=0))
		AND (SA.OrgId=@rOrgId)
		AND	(SA.BatchId = @rBatchId) 
		AND ((SA.ClassId=@rClassId) OR (@rClassId=0))
		AND ((SA.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		AND ((R.AttendanceDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
		AND ((R.AttendanceDate < @rToDate) OR (ISNULL(@rToDate,'')=''))
		AND R.AttendanceTypeId = 5
		AND ((SA.Code=@rStudentCode) OR (@rStudentCode=''))
		AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
		AND ((R.PeriodNo=@rPeriodNo) OR (@rPeriodNo=0))
		AND ((SA.StatusId =@rStatusId ) OR (@rStatusId=0))
	END
END
GO
PRINT N'Creating Procedure [sBiometric].[pRptBiometricAttendanceAnalysisReportGet]...';


GO

CREATE PROCEDURE [sBiometric].[pRptBiometricAttendanceAnalysisReportGet]
	@rBuilder1 nvarchar(max)='',
	@rBuilder2 nvarchar(max)='',
	@rOrgId int,
	@rBatchId int,
	@rEmployeeId bigint,
	@rEmployeeStatusId int,
	@rForYear int,
	@rForMonth int,
	@rDeptId int

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	DECLARE @lMonthDay int=0
	SELECT @lMonthDay=[sCommon].[fGetDaysInMonth] (@rForMonth,@rForYear)
	DECLARE @lFirstDate Date
	DECLARE @lLasteDate Date
	SET @lFirstDate = CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'/'+CONVERT(NVARCHAR(2),@rForMonth)+'/01'))
	SET @lLasteDate = DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,@lFirstDate)+1,0))


	SELECT	ISNULL(@rBuilder1,'') AS Builder1,
			@rBuilder2 AS Builder2,
			MT.EmployeeId AS EmployeeId,
			MT.EmpCode AS EmployeeCode,
			EM.FirstName + ' ' + EM.LastName AS EmployeeName,
			EWD.ForMonth AS Month,
			EWD.ForYear AS Year,
			DAY(DATEADD(MONTH, @rForMonth, DATEADD(YEAR, @rForYear - 1900, -1))) AS TotalDaysInMonth,
			EWD.WeekOffs AS WeekOffs,
			([sHrm].[fEmployeeHolidayGet](EM.Id,0, @rForYear,@rForMonth,@rBatchId,@rOrgId)) AS HoliDays,

			((CASE	WHEN YEAR(EJD.DateOfJoining) = @rForYear AND MONTH(EJD.DateOfJoining) = @rForMonth  
						THEN DATEDIFF(day, EJD.DateOfJoining , @lLasteDate)  + 1 
					WHEN YEAR(EJD.DateOfleaving) = @rForYear AND MONTH(EJD.DateOfleaving) = @rForMonth 
						THEN  DATEDIFF(day, @lFirstDate , EJD.DateOfleaving) + 1
					ELSE @lMonthDay
			END) - ([sHrm].[fEmployeeHolidayGet](EM.Id,0, @rForYear,@rForMonth,@rBatchId,@rOrgId)))  AS WorkingDay,
			CAST(DATEDIFF(S,CAST(MT.Tot_OT as Time),CAST(MT.TotalHour as Time))/3600 AS VARCHAR(10)) + ':'
													 + CAST(DATEDIFF(S,CAST(MT.Tot_OT as Time),CAST(MT.TotalHour as Time))%3600/60 AS VARCHAR(10)) 
			 AS TotalHour,
			MT.Tot_Attn AS TotalAttendance,
			MT.Tot_Abs AS TotalAbsent,
			MT.Tot_WeekOFF AS TotalWeekOff,
			MT.Tot_Holiday AS TotalHoliday,
			MT.Tot_Leave AS TotalLeave,
			MT.Count_OT AS OTCount,
			MT.Tot_OT AS TotalOT,
			MT.Tot_Late AS TotalLate,
			Mt.Tot_Early AS TotalEarly,
			EM.ShiftId AS EmployeeShift

	FROM	sBiometric.tMonthTrans MT
			INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id = MT.EmployeeId
			INNER JOIN sBiometric.tShiftMasterCloud SMC ON SMC.ShiftCode = EM.ShiftId
			INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId= EM.Id
			LEFT JOIN sHrm.tEmployeeWorkingDays EWD ON EWD.EmployeeId=EM.Id AND EWD.ForYear = YEAR(MT.Attn_dt) AND EWD.ForMonth = Month(MT.Attn_dt)
			
	WHERE	(EM.OrgId = @rOrgId OR @rOrgId = 0)
			AND (MT.SourceTypeId = 95 OR MT.SourceTypeId=0)
			AND MT.Attn_dt=cast(rtrim(@rForYear *10000+ @rForMonth *100+ 01) as datetime)

END


--[sActivity].[tWeekOffSetting]

--[sCommon].[tWeekOffRules]

--[sHrm].[fEmployeeHolidayGet]

--SELECT ROUTINE_NAME, ROUTINE_TYPE, SPECIFIC_NAME
--FROM INFORMATION_SCHEMA.ROUTINES
--WHERE ROUTINE_DEFINITION LIKE '%fEmployeeHolidayGet%'
GO
PRINT N'Creating Procedure [sBiometric].[pStudentTimeSheetListGe]...';


GO
create PROCEDURE [sBiometric].[pStudentTimeSheetListGe]
	@rOrgGroupId int,
	@rOrgId int,
	 @rFromDate DateTime,  
  @rToDate DateTime, 
	@rStudentId bigint,
	 @rClassId int,
	@rDivisionId int,
	@rOrgGroupBatchId int=0,
	@rTimeSheetStatus nvarchar(10) = '0',
	@rDepartmentId int=0,
	@rStatusId int=0,
	@rBatchId  int
WITH EXECUTE AS CALLER  
AS  
SET NOCOUNT ON  
BEGIN   

CREATE TABLE #TempMonthTrans (
	Id int Identity,
	EmployeeId bigint,	
	Attn_Date DateTime,
	PresentStatus nvarchar(5),
	FirstIn nvarchar(20),
	LastOut nvarchar(20),
	OverTime nvarchar(20),
	LateBy nvarchar(20),
	Duration nvarchar(20),	
	EarlyBy nvarchar(20)
	
	)

	
	
	INSERT INTO #TempMonthTrans
	
	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 01) as datetime),D01,D01_IN,D01_OUT,D01_O,D01_L,D01_T,D01_E FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rStudentId OR @rStudentId = 0) 
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND ( SourceTypeId =2003)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 02) as datetime),D02,D02_IN,D02_OUT,D02_O,D02_L,D02_T,D02_E FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rStudentId OR @rStudentId = 0)
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND ( SourceTypeId = 2003)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 03) as datetime),D03,D03_IN,D03_OUT,D03_O,D03_L,D03_T,D03_E FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rStudentId OR @rStudentId = 0)
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND ( SourceTypeId =2003)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 04) as datetime),D04,D04_IN,D04_OUT,D04_O,D04_L,D04_T,D04_E FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rStudentId OR @rStudentId = 0)
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND ( SourceTypeId =2003)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 05) as datetime),D05,D05_IN,D05_OUT,D05_O,D05_L,D05_T,D05_E FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rStudentId OR @rStudentId = 0)
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND ( SourceTypeId =2003)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 06) as datetime),D06,D06_IN,D06_OUT,D06_O,D06_L,D06_T,D06_E FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rStudentId OR @rStudentId = 0)
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND ( SourceTypeId =2003)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 07) as datetime),D07,D07_IN,D07_OUT,D07_O,D07_L,D07_T,D07_E FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rStudentId OR @rStudentId = 0)
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND ( SourceTypeId =2003)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 08) as datetime),D08,D08_IN,D08_OUT,D08_O,D08_L,D08_T,D08_E FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rStudentId OR @rStudentId = 0)
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND ( SourceTypeId =2003)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 09) as datetime),D09,D09_IN,D09_OUT,D09_O,D09_L,D09_T,D09_E FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rStudentId OR @rStudentId = 0)
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND ( SourceTypeId =2003)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 10) as datetime),D10,D10_IN,D10_OUT,D10_O,D10_L,D10_T,D10_E FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rStudentId OR @rStudentId = 0)
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND ( SourceTypeId =2003)

	UNION ALL

	SELECT @rStudentId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 11) as datetime),D11,D11_IN,D11_OUT,D11_O,D11_L,D11_T,D11_E FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rStudentId OR @rStudentId = 0)
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND ( SourceTypeId =2003)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 12) as datetime),D12,D12_IN,D12_OUT,D12_O,D12_L,D12_T,D12_E FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rStudentId OR @rStudentId = 0)
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND ( SourceTypeId =2003)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 13) as datetime),D13,D13_IN,D13_OUT,D13_O,D13_L,D13_T,D13_E FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rStudentId OR @rStudentId = 0)
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND ( SourceTypeId =2003)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 14) as datetime),D14,D14_IN,D14_OUT,D14_O,D14_L,D14_T,D14_E FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rStudentId OR @rStudentId = 0)
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND ( SourceTypeId =2003)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 15) as datetime),D15,D15_IN,D15_OUT,D15_O,D15_L,D15_T,D15_E FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rStudentId OR @rStudentId = 0)
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND ( SourceTypeId =2003)

	UNION ALL

	SELECT @rStudentId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 16) as datetime),D16,D16_IN,D16_OUT,D16_O,D16_L,D16_T,D16_E FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rStudentId OR @rStudentId = 0)
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND ( SourceTypeId =2003)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 17) as datetime),D17,D17_IN,D17_OUT,D17_O,D17_L,D17_T,D17_E FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rStudentId OR @rStudentId = 0)
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND ( SourceTypeId =2003)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 18) as datetime),D18,D18_IN,D18_OUT,D18_O,D18_L,D18_T,D18_E FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rStudentId OR @rStudentId = 0)
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND ( SourceTypeId =2003)

	UNION ALL

	SELECT @rStudentId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 19) as datetime),D19,D19_IN,D19_OUT,D19_O,D19_L,D19_T,D19_E FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rStudentId OR @rStudentId = 0)
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND ( SourceTypeId =2003)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 20) as datetime),D20,D20_IN,D20_OUT,D20_O,D20_L,D20_T,D20_E FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rStudentId OR @rStudentId = 0)
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND ( SourceTypeId =2003)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 21) as datetime),D21,D21_IN,D21_OUT,D21_O,D21_L,D21_T,D21_E FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rStudentId OR @rStudentId = 0)
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND ( SourceTypeId =2003)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 22) as datetime),D22,D22_IN,D22_OUT,D22_O,D22_L,D22_T,D22_E FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rStudentId OR @rStudentId = 0)
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND ( SourceTypeId =2003)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 23) as datetime),D23,D23_IN,D23_OUT,D23_O,D23_L,D23_T,D23_E FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rStudentId OR @rStudentId = 0)
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND ( SourceTypeId =2003)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 24) as datetime),D24,D24_IN,D24_OUT,D24_O,D24_L,D24_T,D24_E FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rStudentId OR @rStudentId = 0)
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND ( SourceTypeId =2003)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 25) as datetime),D25,D25_IN,D25_OUT,D25_O,D25_L,D25_T,D25_E FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rStudentId OR @rStudentId = 0)
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND ( SourceTypeId =2003)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 26) as datetime),D26,D26_IN,D26_OUT,D26_O,D26_L,D26_T,D26_E FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rStudentId OR @rStudentId = 0)
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND ( SourceTypeId =2003)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 27) as datetime),D27,D27_IN,D27_OUT,D27_O,D27_L,D27_T,D27_E FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rStudentId OR @rStudentId = 0)
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND ( SourceTypeId =2003)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 28) as datetime),D28,D28_IN,D28_OUT,D28_O,D28_L,D28_T,D28_E FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rStudentId OR @rStudentId = 0)
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND ( SourceTypeId =2003)

	--IF  Month(@rFromDate) <> 2 or (((YEAR(@rFromDate) % 4 = 0 AND YEAR(@rFromDate) % 100 <> 0) OR YEAR(@rFromDate) % 400 = 0 And Month(@rFromDate)  =2)) 
	--BEGIN
		INSERT INTO #TempMonthTrans
		SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 29) as datetime),D29,D29_IN,D29_OUT,D29_O,D29_L,D29_T,D29_E FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rStudentId OR @rStudentId = 0)
		 AND (((Month(@rFromDate) <> 2 or (((YEAR(@rFromDate) % 4 = 0 AND YEAR(@rFromDate) % 100 <> 0) OR YEAR(@rFromDate) % 400 = 0 And Month(@rFromDate)  =2))) AND ATTN_DT = cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime)) 
		OR ((Month(@rToDate) <> 2 or (((YEAR(@rToDate) % 4 = 0 AND YEAR(@rToDate) % 100 <> 0) OR YEAR(@rToDate) % 400 = 0 And Month(@rToDate)  =2))) AND ATTN_DT = cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime))) 
		AND ( SourceTypeId =2003)
	--END
	
	--IF Month(@rFromDate) <> 2
	--BEGIN
	INSERT INTO #TempMonthTrans
	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 30) as datetime),D30,D30_IN,D30_OUT,D30_O,D30_L,D30_T,D30_E FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rStudentId OR @rStudentId = 0)
	AND ((Month(@rFromDate) <> 2 AND ATTN_DT = cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime)) Or (Month(@rToDate) <> 2 AND ATTN_DT = cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)))
	 AND ( SourceTypeId =2003)
	--END
	
	--IF Month(@rFromDate) NOT IN (2,4,6,9,11)
	--BEGIN
	INSERT INTO #TempMonthTrans
	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 31) as datetime),D31,D31_IN,D31_OUT,D31_O,D31_L,D31_T,D31_E FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rStudentId OR @rStudentId = 0)
	AND ((Month(@rFromDate) NOT IN (2,4,6,9,11) AND ATTN_DT = cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime)) OR (Month(@rToDate) NOT IN (2,4,6,9,11) AND ATTN_DT = cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)))
	 AND ( SourceTypeId =2003)
	--END

	Update TM set PresentStatus = CASE When (([sAttendance].[fWeekHOffGet]( YEAR(Attn_Date) ,MONTH(TM.Attn_Date) ,DAY(TM.Attn_Date) ,SA.BatchID,SA.ClassId,SA.DivisionId ,'' ,SA.OrgId )='H') AND (TM.FirstIn !='00:00'))  then 'PH'
		 When (([sAttendance].[fWeekHOffGet]( YEAR(Attn_Date) ,MONTH(TM.Attn_Date) ,DAY(TM.Attn_Date) ,SA.BatchID,SA.ClassId,SA.DivisionId ,'' ,SA.OrgId )='H') AND (TM.FirstIn='00:00')) THEN 'H'  
		 When (([sAttendance].[fWeekHOffGet]( YEAR(Attn_Date) ,MONTH(TM.Attn_Date) ,DAY(TM.Attn_Date) ,SA.BatchID,SA.ClassId,SA.DivisionId ,'' ,SA.OrgId )='W') AND (TM.FirstIn !='00:00'))  then 'PW'
		 When (([sAttendance].[fWeekHOffGet]( YEAR(Attn_Date) ,MONTH(TM.Attn_Date) ,DAY(TM.Attn_Date) ,SA.BatchID,SA.ClassId,SA.DivisionId ,'' ,SA.OrgId )='W') AND (TM.FirstIn ='00:00'))  then 'W'
		 When ((TM.PresentStatus='W')AND ([sAttendance].[fWeekHOffGet]( YEAR(Attn_Date) ,MONTH(TM.Attn_Date) ,DAY(TM.Attn_Date) ,SA.BatchID,SA.ClassId,SA.DivisionId ,'' ,SA.OrgId )!='W') AND (TM.FirstIn !='00:00'))  then 'P'
		 When ((TM.PresentStatus='PW')AND ([sAttendance].[fWeekHOffGet]( YEAR(Attn_Date) ,MONTH(TM.Attn_Date) ,DAY(TM.Attn_Date) ,SA.BatchID,SA.ClassId,SA.DivisionId ,'' ,SA.OrgId )!='W') AND (TM.FirstIn !='00:00'))  then 'P'
		 When ((TM.PresentStatus='W')AND ([sAttendance].[fWeekHOffGet]( YEAR(Attn_Date) ,MONTH(TM.Attn_Date) ,DAY(TM.Attn_Date) ,SA.BatchID,SA.ClassId,SA.DivisionId ,'' ,SA.OrgId )!='W') AND (TM.FirstIn ='00:00'))  then 'A'
		 WHEN ((TM.PresentStatus='W') AND (TM.FirstIn !='00:00')) THEN 'PW' 
		 ELSE TM.PresentStatus END
		From #TempMonthTrans TM
		INNER JOIN sStudent.vStudentAcademic SA  ON SA.StudentId = TM.EmployeeId 


	Select 
		SA.AcademicId AS AcademicId,
		SA.Code AS StudentCode,
		SA.Name AS StudentName,
		ISNULL(SA.RollNo,0) as RollNo,
		(SELECT COUNT(Id) FROM #TempMonthTrans WHERE EmployeeId=MT.EmployeeId AND PresentStatus='A') AS TotalAbsentDays,
		(SELECT COUNT(Id) FROM #TempMonthTrans WHERE EmployeeId=MT.EmployeeId AND PresentStatus='W') AS TotalWeekOffs,
		(SELECT COUNT(Id) FROM #TempMonthTrans WHERE EmployeeId=MT.EmployeeId AND PresentStatus='H') AS TotalHolidays,
		(SELECT COUNT(Id) FROM #TempMonthTrans WHERE EmployeeId=MT.EmployeeId AND (PresentStatus='P' OR PresentStatus='PW')) AS TotalPresentDays,
		(SELECT COUNT(Id) FROM #TempMonthTrans WHERE EmployeeId=MT.EmployeeId AND PresentStatus='HD') AS TotalHalfDays,
		(SELECT COUNT(Id) FROM #TempMonthTrans WHERE EmployeeId=MT.EmployeeId AND PresentStatus='LH') AS TotalLessHours,
		(SELECT COUNT(Id) FROM #TempMonthTrans WHERE EmployeeId=MT.EmployeeId AND PresentStatus='E') AS TotalErrorCase,
		 OM.DisplayTitle AS Organization,
		CM.DisplayTitle AS ClassName,
		CM.Id AS ClassId,
		DM.DisplayTitle AS DivisionName,
		DM.Id AS DivisionId,
		Dept.DisplayTitle AS Department,
		Dept.Id AS DepartmentId,
		CM.Title+'-'+DM.DisplayTitle As ClassDivision,
		Dept.OrderIndex AS OrderIndex,
		DM.OrderIndex AS DivisionOrderIndex,
		SA.OrgId AS OrgId--,
		--DAY(DATEADD(MONTH, @rForMonth, DATEADD(YEAR, @rForYear - 1900, -1))) AS TotalDays
				
		From sBiometric.tMonthTrans MT  
	 INNER JOIN sStudent.vStudentAcademic SA  ON SA.StudentId = MT.EmployeeId AND MT.SourceTypeId=2003 --AND MT.ATTN_DT = cast(rtrim(YEAR(@rAttendanceDate) *10000+ Month(@rAttendanceDate)  *100+ 01) as datetime)
	INNER JOIN sStudent.tStudentAdmission AD ON SA.StudentId = AD.StudentId
	INNER JOIN sSetup.tDivisionMaster DM  ON  SA.DivisionId=DM.Id
	INNER JOIN sSetup.tClassMaster CM ON CM.Id=DM.ClassId
	INNER JOIN sSetup.tDepartmentMaster Dept ON Dept.Id=CM.DepartmentId 
	INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = DM.OrgId
	INNER JOIN sSetup.tBatchClass BC ON BC.ClassId = CM.Id
	INNER JOIN sSetup.tBatchMaster BM ON BC.BatchId = BM.Id  AND BM.OrgGroupBatchId=@rOrgGroupBatchId --AND BM.IsActive=1
	WHERE 
		((SA.ClassId=@rClassId) OR (@rClassId=0))
			AND ((SA.DivisionId=@rDivisionId) OR (@rDivisionId=0))
			AND OM.OrgGroupId=@rOrgGroupId
			AND (SA.OrgId=@rOrgId OR @rOrgId=0)
			AND (SA.OrgGroupBatchId = @rOrgGroupBatchId)
			AND (SA.StudentId=@rStudentId OR @rStudentId=0)
			AND ( (SA.StatusId =  @rStatusId) OR @rStatusId=0)
			AND (AD.LeftDate > @rFromDate OR ISNULL(AD.LeftDate,'')= '')
			AND (AD.AdmissionDate <= @rToDate)
			 AND MT.Attn_dt=cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime)
			 --AND (( @rTimeSheetStatus = '1' AND (TM.Duration < '09:30')) OR ( @rTimeSheetStatus != '1' AND ((PresentStatus = @rTimeSheetStatus OR @rTimeSheetStatus='0'))))
			AND (SA.OrgId = @rOrgId OR @rOrgId = 0)
			 AND((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
	ORDER BY SA.RollNo

	DROP Table #TempMonthTrans	
END
GO
PRINT N'Creating Procedure [sCommunication].[pCircularConsentAdd]...';


GO

CREATE PROCEDURE [sCommunication].[pCircularConsentAdd]
	 
        @rCircularId bigint,
		@rQuestionDescription nvarchar(max),
		@rAnsFieldTypeId int,
		@rAnsFieldList nvarchar(max)
	
		
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	BEGIN TRANSACTION	
	
	INSERT INTO [sCommunication].[tCircularConsent]
		(
			CircularId,
			QuestionDescription,
			AnsFieldTypeId,
			AnsFieldList
		)
	VALUES
		(
			@rCircularId,
			@rQuestionDescription,
			@rAnsFieldTypeId,
			@rAnsFieldList
		)

	 
	 SELECT 1 AS Result

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


GO

CREATE PROCEDURE [sCommunication].[pCircularConsentGet]
	 
        @rCircularId bigint
		
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	
	SELECT
		ISNULL(CC.QuestionDescription,'')AS QuestionDescription,
		ISNULL(CC.AnsFieldTypeId,0)AS AnsFieldTypeId,
		ISNULL(CC.AnsFieldList,'') AS AnsFieldList
	FROM [sCommunication].[tCircularConsent] CC
	WHERE CircularId = @rCircularId
END
GO
PRINT N'Creating Procedure [sHrm].[pEmployeeReplacementDelete]...';


GO
CREATE PROCEDURE [sHrm].[pEmployeeReplacementDelete]
	 
        @rExistingEmployeeId BIGINT,
		@rTitle NVARCHAR(500)
	

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	IF (@rTitle = 'Assign Teacher')
	BEGIN
		delete from sTimetable.tAssignTeacher where EmployeeId = @rExistingEmployeeId
	END

	IF (@rTitle = 'Teacher Subject Division')
	BEGIN
		
		delete from sAcademic.tTeacherSubject where EmployeeId = @rExistingEmployeeId
		
		delete from sAcademic.tTeacherSubjectDivision where EmployeeId = @rExistingEmployeeId		
	END

	IF (@rTitle ='Time Table')
	BEGIN
		Delete sTimetable.tTimeTable where EmployeeId  = @rExistingEmployeeId
		
		DELETE sTimetable.tTeacherWorkLoad  WHERE EmployeeId = @rExistingEmployeeId 
	END
	
	IF (@rTitle ='User Access')
	BEGIN

		declare @lExistingUserId bigint= (select Id from sSecurity.tUser where SourceId = @rExistingEmployeeId AND SourceTypeId = 95)
		
		IF (@lExistingUserId IS NULL)
		BEGIN
			Return
		END
		ELSE
		BEGIN
		
			delete from sSecurity.tUserOrganization  WHERE UserId=@lExistingUserId

			delete from sSecurity.tUserAccess  WHERE UserId=@lExistingUserId
		END
	END

	IF (@rTitle ='Class Teacher')
	BEGIN
		Update sSetup.tDivisionMaster SET InchargeEmployeeId = 0 where  InchargeEmployeeId =  @rExistingEmployeeId
	END

	IF (@rTitle ='Lesson Plan')
	BEGIN
		Delete sAcademic.tLessonPlan where EmployeeId =  @rExistingEmployeeId
	END
END
GO
PRINT N'Creating Procedure [sLibrary].[pRptBookPurchaseListGet]...';


GO

CREATE PROCEDURE [sLibrary].[pRptBookPurchaseListGet]
	 
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='',
	 @rBookSupplier nvarchar(200),
	 @rBookPublisher nvarchar(200),
	 @rBookLanguage nvarchar(200),
	 @rBookTag nvarchar(200),
	 @rBookCustomTag nvarchar(200),
	 @rLibraryId int,
	 @rAccessionNo nvarchar(50)='',
	 @rClassificationNo nvarchar(50)='',
	 @rBookGroup1Id int,
	 @rBookGroup2Id int,
	 @rBookSubjectDrop nvarchar(200)='',
	 @rBookSubjectText nvarchar(200)='',
	 @rFromPurchaseDate date='',
	 @rToPurchaseDate date=''
           
AS
SET NOCOUNT ON
BEGIN
	BEGIN	  
		SET @rBookSupplier = sCommon.fSearchStringGet(@rBookSupplier)
		SET @rBookPublisher = sCommon.fSearchStringGet(@rBookPublisher)
		SET @rBookLanguage = sCommon.fSearchStringGet(@rBookLanguage)
		SET @rBookTag = sCommon.fSearchStringGet(@rBookTag)
		SET @rBookCustomTag = sCommon.fSearchStringGet(@rBookCustomTag)
		SET @rAccessionNo = sCommon.fSearchStringGet(@rAccessionNo)
		SET @rClassificationNo = sCommon.fSearchStringGet(@rClassificationNo)
		SET @rBookSubjectText = sCommon.fSearchStringGet(@rBookSubjectText)
	END
	SELECT   
		@rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,
		BM.Id AS BookId,
		BM.Code AS BookCode,
		BM.Title AS BookName,
		BM.Author,
		BM.Publisher,
		BM.ClassificationNo,
		BM.BookSubject,
		BM.AccessionNo,
		BM.Edition,
		BM.NoOfPages,
		BM.BookLanguage,
		BM.Supplier,
		BM.PurchaseDate,
		BM.Price,
		BM.ISBNNumber,
		BM.Location,
		BM.BookRemark,
		LM.ReportOrgTitle,
		LM.SmallAddress1,
		LM.SmallAddress2,
		BM.NoOfCopies,
		BM.BillNumber,
		BM.Currency,
		BM.BookEntryDate,
		SM.Title AS StatusName
	FROM  
		sLibrary.tBookMaster BM 
		LEFT JOIN sLibrary.tLibraryMaster LM ON LM.Id=BM.LibraryId
		INNER JOIN sLibrary.tBookLog BL ON BL.ResourceSourceId = BM.Id AND IsCurrentStatus=1
        INNER JOIN sCommon.tStatusMaster SM ON SM.Id=BL.StatusId 
	WHERE 
		BM.LibraryId=@rLibraryId
		AND ((BM.Supplier like @rBookSupplier) OR (@rBookSupplier=''))
		AND ((BM.Publisher like @rBookPublisher) OR (@rBookPublisher=''))
		AND ((BM.BookLanguage like @rBookLanguage) OR (@rBookLanguage=''))
		AND ((BM.BookTag like @rBookTag) OR (@rBookTag=''))
		AND ((BM.BookCustomTag like @rBookCustomTag) OR (@rBookCustomTag=''))
		AND ((BM.AccessionNo like @rAccessionNo) OR (@rAccessionNo=''))
		AND ((BM.ClassificationNo like @rClassificationNo) OR (@rClassificationNo=''))
		AND ((BM.BookGroup1Id = @rBookGroup1Id) OR (@rBookGroup1Id=0))
		AND ((BM.BookGroup2Id = @rBookGroup2Id) OR (@rBookGroup2Id=0))
		AND ((BM.BookSubject = @rBookSubjectDrop) OR (@rBookSubjectDrop=''))
		AND ((BM.BookSubject like @rBookSubjectText) OR (@rBookSubjectText=''))
		AND ((BM.PurchaseDate >= @rFromPurchaseDate) OR (ISNULL(@rFromPurchaseDate,'') = ''))
		AND ((BM.PurchaseDate <= @rToPurchaseDate) OR (ISNULL(@rToPurchaseDate,'') =''))
END
GO
PRINT N'Creating Procedure [sPurchase].[pPurchaseRequestAdd]...';


GO




CREATE PROCEDURE [sPurchase].[pPurchaseRequestAdd]
		@rId bigint,
		@rRequestDate datetime,
		@rResourceId int,
		@rRequestedBy nvarchar(100),
		@rOrgGroupId smallint,
		@rBranchId int,
		@rLocationId int,
		@rStatusId smallint,	
		@rVendorId int,
		@rUserId bigint,	
		@rRequiredBy datetime,	
		@rDetailList sPurchase.PurchaseRequestDetailType READONLY
 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
	BEGIN TRANSACTION

		If(@rId > 0)
		Begin
			Update sPurchase.tPurchaseRequest
			set
				--RequestedBy = @rRequestedBy,	 
				StatusId = @rStatusId,
				--VendorId = @rVendorId,
				UpdatedUserId = @rUserId,		
				UpdatedDateTime = GetUtcDate()
			where Id = @rId and IsObsolete = 0

			delete from sPurchase.tPurchaseRequestDetail
			where PurchaseRequestId = @rId

			DECLARE @lNextNumberPRQA INT	 
			EXECUTE [sCommon].[pGetIntMaxIdForOrgGroup] @rOrgGroupId, 'sPurchase.tPurchaseRequestDetail',@lNextNumber = @lNextNumberPRQA output
			set @lNextNumberPRQA=@lNextNumberPRQA-1
			INSERT INTO sPurchase.tPurchaseRequestDetail
			(
				ID,
				OrgGroupId,
				PurchaseRequestId,
				StockItemId,
				RequestedQty,
				Remark,
				CreatedUserId,
				CreatedDateTime
			)
			select	@lNextNumberPRQA+Id,
					OrgGroupId,
					@rId, 
					StockItemId,
					RequestedQty,
					Remark, 
					@rUserId, 
					GETUTCDATE() 
			from @rDetailList
			set @lNextNumberPRQA=@lNextNumberPRQA+(select Count(Id) from @rDetailList)
			EXECUTE sCommon.pTableRowIdModify @rOrgGroupId, @rTableTitle = 'sPurchase.tPurchaseRequestDetail', @rCurrentNumber = @lNextNumberPRQA
			Select @rId
		End
		Else
		Begin
			DECLARE @lNextNumber INT	 
			EXECUTE [sCommon].[pGetIntMaxIdForOrgGroup] @rOrgGroupId, 'sPurchase.tPurchaseRequest',@lNextNumber = @lNextNumber output	
			--select @lNextNumber
			--DECLARE @loNextNumber nVarchar(20)
			--EXECUTE sCommon.pPrefixSetupNextNumberGet @rOrgId = @rOrgGroupId, @rPrefixFunctionalityId = 1005,@rStoreLocationId = @rLocationId,
			--@rNextNumber = @loNextNumber OUTPUT
	 		INSERT INTO sPurchase.tPurchaseRequest
			(
				Id,
				Number,
				RequestDate,
				ResourceId,
				RequestedBy, 
				OrgGroupId,
				BranchId,
				LocationId, 			 
				StatusId,
				VendorId,
				RequiredBy,
				CreatedUserId,		
				CreatedDateTime
	
			)
			VALUES
			(
				@lNextNumber,
				@lNextNumber,
				@rRequestDate,
				@rResourceId,
				@rRequestedBy,	 
				@rOrgGroupId,
				@rBranchId,
				@rLocationId, 		 
				@rStatusId,
				@rVendorId,
				@rRequiredBy,
				@rUserId,		
				GETUTCDATE()
			)
 
			set @rId = @lNextNumber  
			DECLARE @lNextNumberPRQ INT	 
			EXECUTE [sCommon].[pGetIntMaxIdForOrgGroup] @rOrgGroupId, 'sPurchase.tPurchaseRequestDetail',@lNextNumber = @lNextNumberPRQ output	
			set @lNextNumberPRQ=@lNextNumberPRQ-1

	 		INSERT INTO sPurchase.tPurchaseRequestDetail
			(
				Id,
				OrgGroupId,
				PurchaseRequestId,
				StockItemId,
				RequestedQty,
				Remark,
				CreatedUserId,
				CreatedDateTime
			)
			select	@lNextNumberPRQ+Id,
					OrgGroupId,
					@rId, 
					StockItemId,
					RequestedQty,
					Remark, 
					@rUserId, 
					GETUTCDATE() 
			from @rDetailList
			set @lNextNumberPRQ=@lNextNumberPRQ+(select Count(Id) from @rDetailList)
			EXECUTE sCommon.pTableRowIdModify @rOrgGroupId, @rTableTitle = 'sPurchase.tPurchaseRequestDetail', @rCurrentNumber = @lNextNumberPRQ
			
			select @rId

			Declare @typeId smallint=0
			Declare @Level smallint=0
			SELECT @typeId=WfTypeMasterId, @Level=WfLevel FROM sWf.tWfSetup WHERE WfFunctionalityId = 1
			IF(@typeId = 1)--parallel
			BEGIN
				exec [sWf].[pWfApprovalAdd] 0,@rId,2040,@rUserId,1,'',0,0,1,@rOrgGroupId
			END
			ELSE IF(@typeId = 2)--sequencial
			Begin
				exec [sWf].[pWfApprovalAdd] 0,@rId,2040,@rUserId,1,'',1,@Level,1,@rOrgGroupId
			End
			ELSE IF(@typeId = 3)--auto approved
			BEGIN
				exec [sWf].[pWfApprovalAdd] 0,@rId,2040,@rUserId,3,'',0,0,1,@rOrgGroupId
			END
			
		End
	COMMIT TRAN -- Transaction Success!	
	END TRY

	BEGIN CATCH
    IF @@TRANCOUNT > 0
        ROLLBACK TRAN --RollBack in case of Error

    
    DECLARE @ErrorMessage NVARCHAR(4000);  
    DECLARE @ErrorSeverity INT;  
    DECLARE @ErrorState INT;  

    SELECT   
       @ErrorMessage = ERROR_MESSAGE(),  
       @ErrorSeverity = ERROR_SEVERITY(),  
       @ErrorState = ERROR_STATE();  

    RAISERROR (@ErrorMessage, @ErrorSeverity, @ErrorState);  
    
	END CATCH
END
GO
PRINT N'Creating Procedure [sPurchase].[pSalesReturnAdd]...';


GO



CREATE PROCEDURE [sPurchase].[pSalesReturnAdd]
		@rId bigint,
		@rGoodsReceivedNoteId bigint,
		@rPurchaseOrderId bigint,
		@rRequestedBy nvarchar(100),
		@rOrgGroupId int,
		@rLocationId int,
		@rStatusId smallint,	
		@rUserId bigint,
		@rDetailList sPurchase.SalesReturnDetailType READONLY
 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
	BEGIN TRANSACTION

		If(@rId > 0)
		Begin
			Update sPurchase.tSalesReturn
			set 
				StatusId = @rStatusId,
				GoodsReceivedNoteId = @rGoodsReceivedNoteId,
				PurchaseOrderId = @rPurchaseOrderId,
				UpdatedUserId = @rUserId,		
				UpdatedDateTime = GetUtcDate()
			where Id = @rId and IsObsolete = 0

			delete from sPurchase.tSalesReturnDetail
			where SalesReturnId = @rId

			DECLARE @lNextNumberSRD INT	 
			EXECUTE [sCommon].[pGetIntMaxIdForOrgGroup] @rOrgGroupId, 'sPurchase.tSalesReturnDetail',@lNextNumber = @lNextNumberSRD output
			set @lNextNumberSRD=@lNextNumberSRD-1
			INSERT INTO sPurchase.tSalesReturnDetail
			(
				Id,
				OrgGroupId,
				SalesReturnId,
				GoodsReceivedNoteDetailId,
				UnitTypeId,
				CategoryId,
				SubCategoryId,
				StockItemId,
				POQty,
				ReceivedQty,
				RejectedQty,
				CreditNoteIssueDate,
				ReasonForRejection,
				CreatedUserId,
				CreatedDateTime
			)
			select	@lNextNumberSRD+Id,
					OrgGroupId,
					@rId,
					GoodsReceivedNoteDetailId,
					UnitTypeId,
					CategoryId,
					SubCategoryId,
					StockItemId,
					POQty,
					ReceivedQty,
					RejectedQty,
					CreditNoteIssueDate,
					ReasonForRejection,
					@rUserId, 
					GETUTCDATE() 
			from @rDetailList
			set @lNextNumberSRD=@lNextNumberSRD+(select Count(Id) from @rDetailList)
			EXECUTE sCommon.pTableRowIdModify @rOrgGroupId, @rTableTitle = 'sPurchase.tSalesReturnDetail', @rCurrentNumber = @lNextNumberSRD
			Select @rId
		End
		Else
		Begin
			DECLARE @lNextNumber INT	 
			EXECUTE [sCommon].[pGetIntMaxIdForOrgGroup] @rOrgGroupId, 'sPurchase.tSalesReturn',@lNextNumber = @lNextNumber output	
			--select @lNextNumber
			--DECLARE @loNextNumber nVarchar(20)
			--EXECUTE sCommon.pPrefixSetupNextNumberGet @rOrgId = @rOrgGroupId, @rPrefixFunctionalityId = 1005,@rStoreLocationId = @rLocationId,
			--@rNextNumber = @loNextNumber OUTPUT

	 		INSERT INTO sPurchase.tSalesReturn
			(
				Id,
				SRNumber,
				GoodsReceivedNoteId,
				PurchaseOrderId,
				RequestedBy, 
				OrgGroupId,
				LocationId, 			 
				StatusId,
				CreatedUserId,		
				CreatedDateTime
	
			)
			VALUES
			(
				@lNextNumber,
				@lNextNumber,
				@rGoodsReceivedNoteId,
				@rPurchaseOrderId,
				@rRequestedBy,	 
				@rOrgGroupId,
				@rLocationId, 		 
				@rStatusId,
				@rUserId,		
				GETUTCDATE()
			)
 
			set @rId = @lNextNumber  
			
			DECLARE @lNextNumberSRDD INT	 
			EXECUTE [sCommon].[pGetIntMaxIdForOrgGroup] @rOrgGroupId, 'sPurchase.tSalesReturnDetail',@lNextNumber = @lNextNumberSRDD output	
			set @lNextNumberSRDD=@lNextNumberSRDD-1

	 		INSERT INTO sPurchase.tSalesReturnDetail
			(
				Id,
				OrgGroupId,
				SalesReturnId,
				GoodsReceivedNoteDetailId,
				UnitTypeId,
				CategoryId,
				SubCategoryId,
				StockItemId,
				POQty,
				ReceivedQty,
				RejectedQty,
				CreditNoteIssueDate,
				ReasonForRejection,
				CreatedUserId,
				CreatedDateTime
			)
			select	@lNextNumberSRDD+Id,
					OrgGroupId,
					@rId,
					GoodsReceivedNoteDetailId,
					UnitTypeId,
					CategoryId,
					SubCategoryId,
					StockItemId,
					POQty,
					ReceivedQty,
					RejectedQty,
					CreditNoteIssueDate,
					ReasonForRejection,
					@rUserId, 
					GETUTCDATE() 
			from @rDetailList
						
			set @lNextNumberSRDD=@lNextNumberSRDD+(select Count(Id) from @rDetailList)
			EXECUTE sCommon.pTableRowIdModify @rOrgGroupId, @rTableTitle = 'sPurchase.tSalesReturnDetail', @rCurrentNumber = @lNextNumberSRDD
			select @rId

			Declare @typeId smallint=0
			Declare @Level smallint=0
			SELECT @typeId=WfTypeMasterId, @Level=WfLevel FROM sWf.tWfSetup WHERE WfFunctionalityId = 5
			IF(@typeId = 1)--parallel
			BEGIN
				exec [sWf].[pWfApprovalAdd] 0,@rId,2044,@rUserId,1,'',0,0,5,@rOrgGroupId
			END
			ELSE IF(@typeId = 2)--sequencial
			Begin
				exec [sWf].[pWfApprovalAdd] 0,@rId,2044,@rUserId,1,'',1,@Level,5,@rOrgGroupId
			End
			ELSE IF(@typeId = 3)--auto approved
			BEGIN
				exec [sWf].[pWfApprovalAdd] 0,@rId,2044,@rUserId,3,'',0,0,5,@rOrgGroupId
			END
		End
	COMMIT TRAN -- Transaction Success!	
	END TRY

	BEGIN CATCH
    IF @@TRANCOUNT > 0
        ROLLBACK TRAN --RollBack in case of Error

    
    DECLARE @ErrorMessage NVARCHAR(4000);  
    DECLARE @ErrorSeverity INT;  
    DECLARE @ErrorState INT;  

    SELECT   
       @ErrorMessage = ERROR_MESSAGE(),  
       @ErrorSeverity = ERROR_SEVERITY(),  
       @ErrorState = ERROR_STATE();  

    RAISERROR (@ErrorMessage, @ErrorSeverity, @ErrorState);  
    
	END CATCH
END
GO
PRINT N'Creating Procedure [sPurchase].[pQuotationRequestAdd]...';


GO



CREATE PROCEDURE [sPurchase].[pQuotationRequestAdd]
		@rId bigint,
		@rOrgGroupId smallint,
		@rBranchId int,
		@rLocationId int,
		@rPurchaseRequestId bigint,
		@rName varchar(100),
		@rRFQDate datetime,
		@rDescription nvarchar(300),
		@rStartDate datetime,
		@rEndDate datetime,
		@rBidOpen nvarchar(100),
		@rBidClose nvarchar(100),
		@rPersonContact bigint,
		@rEmail nvarchar(100),
		@rSendToVendor bit,
		@rStatusId int,
		@rVendorId int,
		@rUserId bigint,	
		@rDetailList sPurchase.QuotationRequestDetailType READONLY
 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
	BEGIN TRANSACTION
		If(@rId > 0)
		Begin
			Update sPurchase.tQuotationRequest
			set
				OrgGroupId =@rOrgGroupId,
				BranchId =@rBranchId,
				LocationId =@rLocationId,
				PurchaseRequestId =@rPurchaseRequestId,
				Name =@rName,
				RFQDate =@rRFQDate,
				Description =@rDescription,
				StartDate =@rStartDate,
				EndDate =@rEndDate,
				BidOpen =@rBidOpen,
				BidClose =@rBidClose,
				PersonContact =@rPersonContact,
				Email =@rEmail,
				SendToVendor =@rSendToVendor,
				StatusId =@rStatusId,
				VendorId =@rVendorId,
				UpdatedUserId = @rUserId,		
				UpdatedDateTime = GetUtcDate()
			where Id = @rId and IsObsolete = 0

			delete from sPurchase.tQuotationRequestDetail
			where QuotationRequestId = @rId

			DECLARE @lNextNumberQRDA INT	 
			EXECUTE [sCommon].[pGetIntMaxIdForOrgGroup] @rOrgGroupId, 'sPurchase.tQuotationRequestDetail',@lNextNumber = @lNextNumberQRDA output
			SET @lNextNumberQRDA=@lNextNumberQRDA-1
			INSERT INTO sPurchase.tQuotationRequestDetail
			(
				Id,
				OrgGroupId,
				QuotationRequestId,
				PurchaseRequestDetailId,
				StockItemId,
				RequestedQty,
				Remark,
				TargetPrice,
				CreatedUserId,
				CreatedDateTime
			)
			select	@lNextNumberQRDA+Id,
				    OrgGroupId,
					@rId,
					PurchaseRequestDetailId, 
					StockItemId,
					RequestedQty,
					Remark,
					TargetPrice,
					@rUserId, 
					GETUTCDATE() 
			from @rDetailList
			set @lNextNumberQRDA=@lNextNumberQRDA+(select Count(Id) from @rDetailList)
			EXECUTE sCommon.pTableRowIdModify @rOrgGroupId, @rTableTitle = 'sPurchase.tQuotationRequestDetail', @rCurrentNumber = @lNextNumberQRDA
		End
		Else
		Begin
			DECLARE @lNextNumber INT	 
			EXECUTE [sCommon].[pGetIntMaxIdForOrgGroup] @rOrgGroupId, 'sPurchase.tQuotationRequest',@lNextNumber = @lNextNumber output	
			--select @lNextNumber
			--DECLARE @loNextNumber nVarchar(20)
			--EXECUTE sCommon.pPrefixSetupNextNumberGet @rOrgId = @rOrgGroupId, @rPrefixFunctionalityId = 1005,@rStoreLocationId = @rLocationId,
			--@rNextNumber = @loNextNumber OUTPUT

	 		INSERT INTO sPurchase.tQuotationRequest
			(
				Id,
				Number,
				OrgGroupId,
				BranchId,
				LocationId,
				PurchaseRequestId,
				Name,
				RFQDate,
				Description,
				StartDate,
				EndDate,
				BidOpen,
				BidClose,
				PersonContact,
				Email,
				SendToVendor,
				StatusId,
				VendorId,
				CreatedUserId,		
				CreatedDateTime
	
			)
			VALUES
			(
				@lNextNumber,
				@lNextNumber,
				@rOrgGroupId,
				@rBranchId ,
				@rLocationId,
				@rPurchaseRequestId,
				@rName,
				@rRFQDate,
				@rDescription,
				@rStartDate,
				@rEndDate ,
				@rBidOpen ,
				@rBidClose,
				@rPersonContact,
				@rEmail,
				@rSendToVendor,
				@rStatusId,
				@rVendorId ,
				@rUserId,		
				GETUTCDATE()
			)
 
			set @rId = @lNextNumber 

			DECLARE @lNextNumberQRD INT	 
			EXECUTE [sCommon].[pGetIntMaxIdForOrgGroup] @rOrgGroupId, 'sPurchase.tQuotationRequestDetail',@lNextNumber = @lNextNumberQRD output
			SET @lNextNumberQRD=@lNextNumberQRD+1
	 		INSERT INTO sPurchase.tQuotationRequestDetail
			(
				Id,
				OrgGroupId,
				QuotationRequestId,
				PurchaseRequestDetailId,
				StockItemId,
				RequestedQty,
				Remark,
				TargetPrice,
				CreatedUserId,
				CreatedDateTime
			)
			select	@lNextNumberQRD+Id,
				    OrgGroupId,
					@rId,
					PurchaseRequestDetailId, 
					StockItemId,
					RequestedQty,
					Remark,
					TargetPrice,
					@rUserId, 
					GETUTCDATE() 
			from @rDetailList
			set @lNextNumberQRD=@lNextNumberQRD+(select Count(Id) from @rDetailList)
			EXECUTE sCommon.pTableRowIdModify @rOrgGroupId, @rTableTitle = 'sPurchase.tQuotationRequestDetail', @rCurrentNumber = @lNextNumberQRD
			select @rId

			Declare @typeId smallint=0
			Declare @Level smallint=0
			SELECT @typeId=WfTypeMasterId, @Level=WfLevel FROM sWf.tWfSetup WHERE WfFunctionalityId = 2
			IF(@typeId = 1)--parallel
			BEGIN
				exec [sWf].[pWfApprovalAdd] 0,@rId,2041,@rUserId,1,'',0,0,2,@rOrgGroupId
			END
			ELSE IF(@typeId = 2)--sequencial
			Begin
				exec [sWf].[pWfApprovalAdd] 0,@rId,2041,@rUserId,1,'',1,@Level,2,@rOrgGroupId
			End
			ELSE IF(@typeId = 3)--auto approved
			BEGIN
				exec [sWf].[pWfApprovalAdd] 0,@rId,2041,@rUserId,3,'',0,0,2,@rOrgGroupId
			END
		End
	COMMIT TRAN -- Transaction Success!	
	END TRY

	BEGIN CATCH
    IF @@TRANCOUNT > 0
        ROLLBACK TRAN --RollBack in case of Error

    
    DECLARE @ErrorMessage NVARCHAR(4000);  
    DECLARE @ErrorSeverity INT;  
    DECLARE @ErrorState INT;  

    SELECT   
       @ErrorMessage = ERROR_MESSAGE(),  
       @ErrorSeverity = ERROR_SEVERITY(),  
       @ErrorState = ERROR_STATE();  

    RAISERROR (@ErrorMessage, @ErrorSeverity, @ErrorState);  
    
	END CATCH
END
GO
PRINT N'Creating Procedure [sPurchase].[pPurchaseOrderAdd]...';


GO






CREATE PROCEDURE [sPurchase].[pPurchaseOrderAdd]
		@rId bigint,
		@rPurchaseRequestId bigint,
		@rPODate datetime,	
		@rRequestedBy nvarchar(100),
		@rOrgGroupId smallint,
		@rLocationId int,
		@rStatusId smallint,	
		@rVendorId int,
		@rBillToAddress nvarchar(1000),
		@rShipToAddress nvarchar(1000),	
		@rUserId bigint,
		@rRequiredBy datetime,	
		@rDetailList sPurchase.PurchaseOrderDetailType READONLY
 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
	BEGIN TRANSACTION

		If(@rId > 0)
		Begin
			Update sPurchase.tPurchaseOrder
			set 
				StatusId = @rStatusId,
				VendorId = @rVendorId,
				RequiredBy = @rRequiredBy,
				BillToAddress = @rBillToAddress,
				ShipToAddress = @rShipToAddress,
				UpdatedUserId = @rUserId,		
				UpdatedDateTime = GetUtcDate()
			where Id = @rId and IsObsolete = 0

			delete from sPurchase.tPurchaseOrderDetail
			where PurchaseOrderId = @rId

			DECLARE @lNextNumberPOD INT	 
			EXECUTE [sCommon].[pGetIntMaxIdForOrgGroup] @rOrgGroupId, 'sPurchase.tPurchaseOrderDetail',@lNextNumber = @lNextNumberPOD output
			set @lNextNumberPOD=@lNextNumberPOD-1
			INSERT INTO sPurchase.tPurchaseOrderDetail
			(
				Id,
				OrgGroupId,
				PurchaseOrderId,
				PurchaseRequestDetailId,
				StockItemId,
				TotalQty,
				Remark,
				CreatedUserId,
				CreatedDateTime
			)
			select	@lNextNumberPOD+Id,
					OrgGroupId,
					@rId,
					PurchaseRequestDetailId,
					StockItemId,
					TotalQty,
					Remark, 
					@rUserId, 
					GETUTCDATE() 
			from @rDetailList
			set @lNextNumberPOD=@lNextNumberPOD+(select Count(Id) from @rDetailList)
			EXECUTE sCommon.pTableRowIdModify @rOrgGroupId, @rTableTitle = 'sPurchase.tPurchaseOrderDetail', @rCurrentNumber = @lNextNumberPOD
			Select @rId
		End
		Else
		Begin
			DECLARE @lNextNumber INT	 
			EXECUTE [sCommon].[pGetIntMaxIdForOrgGroup] @rOrgGroupId, 'sPurchase.tPurchaseOrder',@lNextNumber = @lNextNumber output	
			--select @lNextNumber
			--DECLARE @loNextNumber nVarchar(20)
			--EXECUTE sCommon.pPrefixSetupNextNumberGet @rOrgId = @rOrgGroupId, @rPrefixFunctionalityId = 1005,@rStoreLocationId = @rLocationId,
			--@rNextNumber = @loNextNumber OUTPUT

	 		INSERT INTO sPurchase.tPurchaseOrder
			(
				Id,
				RefNumber,
				PurchaseRequestId,
				PODate,
				RequestedBy, 
				OrgGroupId,
				LocationId, 			 
				StatusId,
				VendorId,
				RequiredBy,
				BillToAddress,
				ShipToAddress,
				CreatedUserId,		
				CreatedDateTime
	
			)
			VALUES
			(
				@lNextNumber,
				@lNextNumber,
				@rPurchaseRequestId,
				@rPODate,
				@rRequestedBy,	 
				@rOrgGroupId,
				@rLocationId, 		 
				@rStatusId,
				@rVendorId,
				@rRequiredBy,
				@rBillToAddress,
				@rShipToAddress,
				@rUserId,		
				GETUTCDATE()
			)
 
			set @rId = @lNextNumber  
			
			DECLARE @lNextNumberPO INT	 
			EXECUTE [sCommon].[pGetIntMaxIdForOrgGroup] @rOrgGroupId, 'sPurchase.tPurchaseOrderDetail',@lNextNumber = @lNextNumberPO output	
			set @lNextNumberPO=@lNextNumberPO-1

	 		INSERT INTO sPurchase.tPurchaseOrderDetail
			(
				Id,
				OrgGroupId,
				PurchaseOrderId,
				PurchaseRequestDetailId,
				StockItemId,
				TotalQty,
				Remark,
				CreatedUserId,
				CreatedDateTime
			)
			select	@lNextNumberPO+Id,
					OrgGroupId,
					@rId,
					PurchaseRequestDetailId,
					StockItemId,
					TotalQty,
					Remark, 
					@rUserId, 
					GETUTCDATE() 
			from @rDetailList
						
			set @lNextNumberPO=@lNextNumberPO+(select Count(Id) from @rDetailList)
			EXECUTE sCommon.pTableRowIdModify @rOrgGroupId, @rTableTitle = 'sPurchase.tPurchaseOrderDetail', @rCurrentNumber = @lNextNumberPO
			select @rId

			Declare @typeId smallint=0
			Declare @Level smallint=0
			SELECT @typeId=WfTypeMasterId, @Level=WfLevel FROM sWf.tWfSetup WHERE WfFunctionalityId = 3
			IF(@typeId = 1)--parallel
			BEGIN
				exec [sWf].[pWfApprovalAdd] 0,@rId,2042,@rUserId,1,'',0,0,3,@rOrgGroupId
			END
			ELSE IF(@typeId = 2)--sequencial
			Begin
				exec [sWf].[pWfApprovalAdd] 0,@rId,2042,@rUserId,1,'',1,@Level,3,@rOrgGroupId
			End
			ELSE IF(@typeId = 3)--auto approved
			BEGIN
				exec [sWf].[pWfApprovalAdd] 0,@rId,2042,@rUserId,3,'',0,0,3,@rOrgGroupId
			END
		End
	COMMIT TRAN -- Transaction Success!	
	END TRY

	BEGIN CATCH
    IF @@TRANCOUNT > 0
        ROLLBACK TRAN --RollBack in case of Error

    
    DECLARE @ErrorMessage NVARCHAR(4000);  
    DECLARE @ErrorSeverity INT;  
    DECLARE @ErrorState INT;  

    SELECT   
       @ErrorMessage = ERROR_MESSAGE(),  
       @ErrorSeverity = ERROR_SEVERITY(),  
       @ErrorState = ERROR_STATE();  

    RAISERROR (@ErrorMessage, @ErrorSeverity, @ErrorState);  
    
	END CATCH
END
GO
PRINT N'Creating Procedure [sPurchase].[pGoodsReceivedNoteAdd]...';


GO



CREATE PROCEDURE [sPurchase].[pGoodsReceivedNoteAdd]
		@rId bigint,
		@rPurchaseRequestId bigint,
		@rPurchaseOrderId bigint,
		@rDepartmentBranchId int,
		@rVendorId int,
		@rPODueDate datetime,	
		@rRequestedBy nvarchar(100),
		@rOrgGroupId smallint,
		@rLocationId int,
		@rStatusId smallint,	
		@rBillToAddress nvarchar(1000),
		@rUserId bigint,
		@rDetailList sPurchase.GoodsReceivedNoteDetailType READONLY
 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
	BEGIN TRANSACTION

		If(@rId > 0)
		Begin
			Update sPurchase.tGoodsReceivedNote
			set 
				StatusId = @rStatusId,
				PurchaseRequestId = @rPurchaseRequestId,
				PurchaseOrderId = @rPurchaseOrderId,
				DepartmentBranchId = @rDepartmentBranchId,
				VendorId = @rVendorId,
				PODueDate = @rPODueDate,
				BillToAddress = @rBillToAddress,
				UpdatedUserId = @rUserId,		
				UpdatedDateTime = GetUtcDate()
			where Id = @rId and IsObsolete = 0

			delete from sPurchase.tGoodsReceivedNoteDetail
			where GoodsReceivedNoteId = @rId

			DECLARE @lNextNumberGRN INT	 
			EXECUTE [sCommon].[pGetIntMaxIdForOrgGroup] @rOrgGroupId, 'sPurchase.tGoodsReceivedNoteDetail',@lNextNumber = @lNextNumberGRN output
			set @lNextNumberGRN=@lNextNumberGRN-1
			INSERT INTO sPurchase.tGoodsReceivedNoteDetail
			(
				Id,
				OrgGroupId,
				GoodsReceivedNoteId,
				PurchaseRequestDetailId,
				UnitTypeId,
				CategoryId,
				SubCategoryId,
				StockItemId,
				POQty,
				ReceivedQty,
				PreviousGRNQty,
				UnitPrice,
				Remark,
				CreatedUserId,
				CreatedDateTime
			)
			select	@lNextNumberGRN+Id,
					OrgGroupId,
					@rId,
					PurchaseRequestDetailId,
					UnitTypeId,
					CategoryId,
					SubCategoryId,
					StockItemId,
					POQty,
					ReceivedQty,
					PreviousGRNQty,
					UnitPrice,
					Remark,
					@rUserId, 
					GETUTCDATE() 
			from @rDetailList
			set @lNextNumberGRN=@lNextNumberGRN+(select Count(Id) from @rDetailList)
			EXECUTE sCommon.pTableRowIdModify @rOrgGroupId, @rTableTitle = 'sPurchase.tGoodsReceivedNoteDetail', @rCurrentNumber = @lNextNumberGRN
			Select @rId
		End
		Else
		Begin
			DECLARE @lNextNumber INT	 
			EXECUTE [sCommon].[pGetIntMaxIdForOrgGroup] @rOrgGroupId, 'sPurchase.tGoodsReceivedNote',@lNextNumber = @lNextNumber output	
			--select @lNextNumber
			--DECLARE @loNextNumber nVarchar(20)
			--EXECUTE sCommon.pPrefixSetupNextNumberGet @rOrgId = @rOrgGroupId, @rPrefixFunctionalityId = 1005,@rStoreLocationId = @rLocationId,
			--@rNextNumber = @loNextNumber OUTPUT

	 		INSERT INTO sPurchase.tGoodsReceivedNote
			(
				Id,
				GRNNumber,
				PurchaseRequestId,
				PurchaseOrderId,
				DepartmentBranchId,
				PODueDate,
				RequestedBy, 
				OrgGroupId,
				LocationId, 			 
				StatusId,
				VendorId,
				BillToAddress,
				CreatedUserId,		
				CreatedDateTime
	
			)
			VALUES
			(
				@lNextNumber,
				@lNextNumber,
				@rPurchaseRequestId,
				@rPurchaseOrderId,
				@rDepartmentBranchId,
				@rPODueDate,
				@rRequestedBy,	 
				@rOrgGroupId,
				@rLocationId, 		 
				@rStatusId,
				@rVendorId,
				@rBillToAddress,
				@rUserId,		
				GETUTCDATE()
			)
 
			set @rId = @lNextNumber  
			
			DECLARE @lNextNumberGRND INT	 
			EXECUTE [sCommon].[pGetIntMaxIdForOrgGroup] @rOrgGroupId, 'sPurchase.tGoodsReceivedNoteDetail',@lNextNumber = @lNextNumberGRND output	
			set @lNextNumberGRND=@lNextNumberGRND-1

	 		INSERT INTO sPurchase.tGoodsReceivedNoteDetail
			(
				Id,
				OrgGroupId,
				GoodsReceivedNoteId,
				PurchaseRequestDetailId,
				UnitTypeId,
				CategoryId,
				SubCategoryId,
				StockItemId,
				POQty,
				ReceivedQty,
				PreviousGRNQty,
				UnitPrice,
				Remark,
				CreatedUserId,
				CreatedDateTime
			)
			select	@lNextNumberGRND+Id,
					OrgGroupId,
					@rId,
					PurchaseRequestDetailId,
					UnitTypeId,
					CategoryId,
					SubCategoryId,
					StockItemId,
					POQty,
					ReceivedQty,
					PreviousGRNQty,
					UnitPrice,
					Remark,
					@rUserId, 
					GETUTCDATE() 
			from @rDetailList
						
			set @lNextNumberGRND=@lNextNumberGRND+(select Count(Id) from @rDetailList)
			EXECUTE sCommon.pTableRowIdModify @rOrgGroupId, @rTableTitle = 'sPurchase.tGoodsReceivedNoteDetail', @rCurrentNumber = @lNextNumberGRND
			select @rId

			Declare @typeId smallint=0
			Declare @Level smallint=0
			SELECT @typeId=WfTypeMasterId, @Level=WfLevel FROM sWf.tWfSetup WHERE WfFunctionalityId = 4
			IF(@typeId = 1)
			BEGIN
				exec [sWf].[pWfApprovalAdd] 0,@rId,2043,@rUserId,1,'',0,0,4,@rOrgGroupId
			END
			ELSE IF(@typeId = 2)
			Begin
				exec [sWf].[pWfApprovalAdd] 0,@rId,2043,@rUserId,1,'',1,@Level,4,@rOrgGroupId
			End
			ELSE IF(@typeId = 3)
			BEGIN
				exec [sWf].[pWfApprovalAdd] 0,@rId,2043,@rUserId,3,'',0,0,4,@rOrgGroupId
			END
		End
	COMMIT TRAN -- Transaction Success!	
	END TRY

	BEGIN CATCH
    IF @@TRANCOUNT > 0
        ROLLBACK TRAN --RollBack in case of Error

    
    DECLARE @ErrorMessage NVARCHAR(4000);  
    DECLARE @ErrorSeverity INT;  
    DECLARE @ErrorState INT;  

    SELECT   
       @ErrorMessage = ERROR_MESSAGE(),  
       @ErrorSeverity = ERROR_SEVERITY(),  
       @ErrorState = ERROR_STATE();  

    RAISERROR (@ErrorMessage, @ErrorSeverity, @ErrorState);  
    
	END CATCH
END



GO
EXECUTE sp_refreshsqlmodule N'[sStudent].[fDivisionInchargeDetailsGet]';


GO
EXECUTE sp_refreshsqlmodule N'[sCertificate].[pLeavingBulkGet]';



GO
EXECUTE sp_refreshsqlmodule N'[sAttendance].[pMonthlyAttenanceRegisterGet]';


GO
EXECUTE sp_refreshsqlmodule N'[sAssessment].[pRptStudentProfileGet]';


GO
EXECUTE sp_refreshsqlmodule N'[sAttendance].[pStudentAttendanceXMLInsert]';


GO
EXECUTE sp_refreshsqlmodule N'[sStudent].[pIDNoGenerationGet]';


GO
EXECUTE sp_refreshsqlmodule N'[sStudent].[pXMLStudentImportAdd]';


GO
EXECUTE sp_refreshsqlmodule N'[sAssessment].[pRptResultSheetStandardMultiExamGet]';



GO
EXECUTE sp_refreshsqlmodule N'[sAttendance].[pAttenanceRegisterGetNew1]';


GO
EXECUTE sp_refreshsqlmodule N'[sStudent].[pStudentDelete]';



GO
EXECUTE sp_refreshsqlmodule N'[sAssessment].[pRptStudentAnalysisDetailsGet]';


GO
EXECUTE sp_refreshsqlmodule N'[sFee].[pUpdatePendingAsNAGet]';


GO
EXECUTE sp_refreshsqlmodule N'[sAttendance].[pMonthlyAttendaceImportAdd]';



GO
EXECUTE sp_refreshsqlmodule N'[sStudent].[pRptStudentLCVerificationGet]';

GO
EXECUTE sp_refreshsqlmodule N'[sStudent].[pRptCountCategorywiseStudentGet]';



GO
EXECUTE sp_refreshsqlmodule N'[sAdmission].[pAPIAdmissionInquiryDetailGet]';


GO
EXECUTE sp_refreshsqlmodule N'[sAdmission].[pAPIAdmissionInquiryGet]';


GO
EXECUTE sp_refreshsqlmodule N'[sCertificate].[pRptOtherCertificateGet]';



GO
EXECUTE sp_refreshsqlmodule N'[sStudent].[pStudentHistoryAcademicWiseAdd]';


GO
EXECUTE sp_refreshsqlmodule N'[sAssessment].[pRptResultListConsolidateWithSubExamGet]';



GO
EXECUTE sp_refreshsqlmodule N'[sAssessment].[pRptResultSheetStandardMultiExamGet_Old]';


GO
EXECUTE sp_refreshsqlmodule N'[sStudent].[pStudentFullProfileGet]';


GO
EXECUTE sp_refreshsqlmodule N'[sStudent].[pRptStudentRegisterDetailsGet]';


GO
EXECUTE sp_refreshsqlmodule N'[sAttendance].[pAttenanceRegisterGetNew]';



GO
EXECUTE sp_refreshsqlmodule N'[sCanteen].[pRptCanteenIssueSlipGet]';



GO
EXECUTE sp_refreshsqlmodule N'[sBiometric].[pRptMonthlySummaryListDateWiseGet]';

GO
EXECUTE sp_refreshsqlmodule N'[sBiometric].[pRptStudentMonthlySummaryListGet]';


GO
EXECUTE sp_refreshsqlmodule N'[sStudent].[pStudentGenerateReport]';



GO
EXECUTE sp_refreshsqlmodule N'[sCertificate].[pRptBonafiedCertificateWithPreviousDetail]';


GO
EXECUTE sp_refreshsqlmodule N'[sAdmission].[pAdmissionFormGet]';


GO
EXECUTE sp_refreshsqlmodule N'[sAdmission].[pAdmissionInquiryGet]';



GO
EXECUTE sp_refreshsqlmodule N'[sAssessment].[pRptResultSheetStandardMultiExamWithAllTermGet]';


GO
EXECUTE sp_refreshsqlmodule N'[sAdmission].[pAdmissionGenerateReport]';


GO
EXECUTE sp_refreshsqlmodule N'[sAdmission].[pRptAdmissionListWIthMeritMarksGet]';



GO
EXECUTE sp_refreshsqlmodule N'[sAdmission].[pRptAdmissionSummaryGet]';



GO
EXECUTE sp_refreshsqlmodule N'[sAdmission].[pRptPreviousStudentAnalysisGet]';



GO
EXECUTE sp_refreshsqlmodule N'[sAdmission].[pRptStudentNewAdmissionListGet]';



GO
EXECUTE sp_refreshsqlmodule N'[sAlert].[pNewAdmissionGet]';


GO
EXECUTE sp_refreshsqlmodule N'[sAlert].[pStudentAdmissionGet]';



GO
EXECUTE sp_refreshsqlmodule N'[sAttendance].[pAttenanceRegisterGet]';



GO
EXECUTE sp_refreshsqlmodule N'[sAttendance].[pAttenanceRegisterGet_HTML]';



GO
EXECUTE sp_refreshsqlmodule N'[sAttendance].[pAttendanceFollowupDetailGet]';



GO
EXECUTE sp_refreshsqlmodule N'[sAttendance].[pAttendanceFollowupListGet]';



GO
EXECUTE sp_refreshsqlmodule N'[sAttendance].[pRptDailyAttendanceList]';



GO
EXECUTE sp_refreshsqlmodule N'[sAttendance].[pRptMonthlyAttendanceStudentwise]';


GO
EXECUTE sp_refreshsqlmodule N'[sAttendance].[pRptMonthlyStrengthAttendanceSummary]';



GO
EXECUTE sp_refreshsqlmodule N'[sAttendance].[pRptStudentAttendanceLateCountList]';


GO
EXECUTE sp_refreshsqlmodule N'[sAttendance].[pStudentRegisterGet]';



GO
EXECUTE sp_refreshsqlmodule N'[sAttendance].[pStudentRegisterMobileAppGet]';



GO
EXECUTE sp_refreshsqlmodule N'[sAttendance].[pSubjectwiseAttendanceGet]';


GO
EXECUTE sp_refreshsqlmodule N'[sCertificate].[pLeavingAdd]';


GO
EXECUTE sp_refreshsqlmodule N'[sCertificate].[pLeavingBulkAdd]';


GO
EXECUTE sp_refreshsqlmodule N'[sCertificate].[pLeavingGet]';



GO
EXECUTE sp_refreshsqlmodule N'[sCertificate].[pTransferAdd]';


GO
EXECUTE sp_refreshsqlmodule N'[sClient].[pIshaDetailStudentModelGet]';


GO
EXECUTE sp_refreshsqlmodule N'[sEis].[pRptInquiryAdmissionGet]';



GO
EXECUTE sp_refreshsqlmodule N'[sFee].[pAdditionalFeeDashBoardGet]';


GO
EXECUTE sp_refreshsqlmodule N'[sFee].[pConsolidateFeeStatusDashboardGet]';


GO
EXECUTE sp_refreshsqlmodule N'[sFee].[pDepositSetupGet]';



GO
EXECUTE sp_refreshsqlmodule N'[sFee].[pExamptionFeeDashBoardGet]';


GO
EXECUTE sp_refreshsqlmodule N'[sFee].[pNotApplicableFeeDashBoardGet]';



GO
EXECUTE sp_refreshsqlmodule N'[sFee].[pRptFeePendingDetailListOtherGet]';



GO
EXECUTE sp_refreshsqlmodule N'[sFee].[pRptFeeProcessGenerateGet]';



GO
EXECUTE sp_refreshsqlmodule N'[sFee].[pRptFeeProcessSummaryGet]';



GO
EXECUTE sp_refreshsqlmodule N'[sFee].[pRptFeeStatusFeeHeadandBusRouteWiseGet]';



GO
EXECUTE sp_refreshsqlmodule N'[sFee].[pRptFeeStatusStudentAndFeeWiseGet]';


GO
EXECUTE sp_refreshsqlmodule N'[sFee].[pRptFeeStatusStudentWiseDetails]';



GO
EXECUTE sp_refreshsqlmodule N'[sFee].[pRptFeeStatusStudentWisewithDiscountGet]';



GO
EXECUTE sp_refreshsqlmodule N'[sFee].[pRptFeeSummaryGet]';


GO
EXECUTE sp_refreshsqlmodule N'[sFee].[pRptStudentCountStatusGet]';



GO
EXECUTE sp_refreshsqlmodule N'[sFee].[pRptStudentFeeDetailsGet]';



GO
EXECUTE sp_refreshsqlmodule N'[sFee].[pRptStudentLedgerGet]';

GO
EXECUTE sp_refreshsqlmodule N'[sFee].[pRptStudentWiseFeeDetailGet]';


GO
EXECUTE sp_refreshsqlmodule N'[sFee].[pRptSummaryFeeStatusGet]';


GO
EXECUTE sp_refreshsqlmodule N'[sFee].[pRptSummaryPendingFeeGet]';



GO
EXECUTE sp_refreshsqlmodule N'[sFee].[pStudentCountStatusDashBoardGet]';



GO
EXECUTE sp_refreshsqlmodule N'[sHostel].[pRptHostelAttendanceSheetGet]';



GO
EXECUTE sp_refreshsqlmodule N'[sMis].[pRptClassCapacityGet]';


GO
EXECUTE sp_refreshsqlmodule N'[sMis].[pRptInquiryAdmissionGet]';



GO
EXECUTE sp_refreshsqlmodule N'[sMis].[pRptStudentStrengthGet]';



GO
EXECUTE sp_refreshsqlmodule N'[sStudent].[pEnrollmentStatusAdd]';


GO
EXECUTE sp_refreshsqlmodule N'[sStudent].[ppImportStudent_Update_Dynamicly]';



GO
EXECUTE sp_refreshsqlmodule N'[sStudent].[pRptCastCategoryStudentStrengthGet]';



GO
EXECUTE sp_refreshsqlmodule N'[sStudent].[pRptGenderwiseStudentStrengthGet]';



GO
EXECUTE sp_refreshsqlmodule N'[sStudent].[pRptNewAdmissionStrengthSummaryGet]';



GO
EXECUTE sp_refreshsqlmodule N'[sStudent].[pRptRelegionStudentStrengthGet]';



GO
EXECUTE sp_refreshsqlmodule N'[sStudent].[pRptStudentAttendanceSummaryGet]';



GO
EXECUTE sp_refreshsqlmodule N'[sStudent].[pRptStudentDetailListGet]';


GO
EXECUTE sp_refreshsqlmodule N'[sStudent].[pRptStudentListAsOnDateGet]';

GO
EXECUTE sp_refreshsqlmodule N'[sStudent].[pRptStudentListGet]';

GO
EXECUTE sp_refreshsqlmodule N'[sStudent].[pRptStudentRegisterWithAcademicDetailGet]';


GO
EXECUTE sp_refreshsqlmodule N'[sStudent].[pRptStudentStrengthDivisionStatusWiseGet]';



GO
EXECUTE sp_refreshsqlmodule N'[sStudent].[pRptStudentStrengthDivisionWiseGet]';



GO
EXECUTE sp_refreshsqlmodule N'[sStudent].[pRptStudentStrengthGet]';


GO
EXECUTE sp_refreshsqlmodule N'[sStudent].[pRptStudentTenureAndConductCertificateGet]';



GO
EXECUTE sp_refreshsqlmodule N'[sStudent].[pRptTrancriptionCertificateGet]';




GO
EXECUTE sp_refreshsqlmodule N'[sStudent].[pRptVerifyStudentDataListGet]';




GO
EXECUTE sp_refreshsqlmodule N'[sStudent].[pStrengthStatusLEFTWiseGet]';


GO
EXECUTE sp_refreshsqlmodule N'[sStudent].[pStrengthStatusWiseGet]';


GO
EXECUTE sp_refreshsqlmodule N'[sStudent].[pStudentDataListGet]';


GO
EXECUTE sp_refreshsqlmodule N'[sStudent].[pStudentDetailDelete]';


GO
EXECUTE sp_refreshsqlmodule N'[sStudent].[pStudentDetailUpdate]';


GO
EXECUTE sp_refreshsqlmodule N'[sStudent].[pStudentDetailUpdateGet]';


GO
EXECUTE sp_refreshsqlmodule N'[sStudent].[pStudentSummaryDashboard]';



GO
EXECUTE sp_refreshsqlmodule N'[sStudent].[pStudentVerificationUpdate]';


GO
EXECUTE sp_refreshsqlmodule N'[sStudent].[pSUIDGenerationGet]';


GO
EXECUTE sp_refreshsqlmodule N'[sCertificate].[pTemplateFunctionalFieldsGet]';



GO
EXECUTE sp_refreshsqlmodule N'[sAttendance].[pAttendanceDataVerifyGet]';



GO
EXECUTE sp_refreshsqlmodule N'[sStudent].[pRptStudentIcardGet]';


GO
EXECUTE sp_refreshsqlmodule N'[sStudent].[pStudentViewProfileGet]';




GO
EXECUTE sp_refreshsqlmodule N'[sStudent].[pIDRegisterGet]';



GO
EXECUTE sp_refreshsqlmodule N'[sAcademic].[pOnlineLearningAssignmentStudentCountGet]';


GO
EXECUTE sp_refreshsqlmodule N'[sAcademic].[pOnlineLearningAssignmentViewListGet]';


GO
EXECUTE sp_refreshsqlmodule N'[sAlert].[pOnlineLearningAbsentStudentListGet]';



GO
EXECUTE sp_refreshsqlmodule N'[sAlert].[pOnlineLearningLectureAdd]';


GO
EXECUTE sp_refreshsqlmodule N'[sAttendance].[pAbsentStudentDashboardGet]';

GO
EXECUTE sp_refreshsqlmodule N'[sAttendance].[pStudentPresenceDashboardGet]';



GO
EXECUTE sp_refreshsqlmodule N'[sCommon].[pStudentRecord]';


GO
EXECUTE sp_refreshsqlmodule N'[sCommunication].[pChatGroupDetailGet]';


GO
EXECUTE sp_refreshsqlmodule N'[sFee].[pFeeFollowupGet]';


GO
EXECUTE sp_refreshsqlmodule N'[sFee].[pMorePendingfee]';


GO
EXECUTE sp_refreshsqlmodule N'[sHrm].[PAttendanceNotAdd]';



GO
EXECUTE sp_refreshsqlmodule N'[sHrm].[PFee]';


GO
EXECUTE sp_refreshsqlmodule N'[sHrm].[PHomework]';


GO
EXECUTE sp_refreshsqlmodule N'[sHrm].[PNoAbsentEmployee]';



GO
EXECUTE sp_refreshsqlmodule N'[sMis].[pRptStudentBirthdayList]';


GO
EXECUTE sp_refreshsqlmodule N'[sStudent].[pDigitalFormStudentListGet]';



GO
EXECUTE sp_refreshsqlmodule N'[sStudent].[pDigitalFormStudentStatusAdd]';


GO
EXECUTE sp_refreshsqlmodule N'[sStudent].[pDigitalFormSubmittedStudentListGet]';


GO
EXECUTE sp_refreshsqlmodule N'[sStudent].[PNoOfAbsentStudent]';

GO
EXECUTE sp_refreshsqlmodule N'[sStudent].[pRptincopleteFieldGet]';

GO
EXECUTE sp_refreshsqlmodule N'[sStudent].[pRptStudentInformationFormGet]';


GO
EXECUTE sp_refreshsqlmodule N'[sStudent].[pRptStudentInformationFormTestGet]';


GO
EXECUTE sp_refreshsqlmodule N'[sStudent].[pRptStudentRegisterGet]';


GO
EXECUTE sp_refreshsqlmodule N'[sStudent].[pRptStudentRegisterWithAddressGet]';

GO
EXECUTE sp_refreshsqlmodule N'[sStudent].[pRptStudentRegisterWithSUIDAndDemographicDetailGet]';


GO
EXECUTE sp_refreshsqlmodule N'[sStudent].[pStudentDashboardGet]';



GO
EXECUTE sp_refreshsqlmodule N'[sStudent].[pStudentProfileGet]';


GO
EXECUTE sp_refreshsqlmodule N'[sTransport].[pRptBusAttendanceGet]';


GO
EXECUTE sp_refreshsqlmodule N'[sTransport].[pRptStudentAttendanceRegister]';



GO
EXECUTE sp_refreshsqlmodule N'[sTransport].[pRptStudentAttendanceRegisterBlankGet]';


GO
EXECUTE sp_refreshsqlmodule N'[sStudent].[pStudentCustomSearchGet]';


GO
EXECUTE sp_refreshsqlmodule N'[sStudent].[pGetStudentList]';


GO
EXECUTE sp_refreshsqlmodule N'[sStudent].[pStudentVerificationGet]';


GO
EXECUTE sp_refreshsqlmodule N'[sStudent].[pAcademicDelete]';


GO
EXECUTE sp_refreshsqlmodule N'[sSetup].[pOrganizationWiseStudentDelete]';


GO
EXECUTE sp_refreshsqlmodule N'[sStudent].[pImportStudent_New]';



GO
EXECUTE sp_refreshsqlmodule N'[sStudent].[pStudentDetailFormGet]';


GO
EXECUTE sp_refreshsqlmodule N'[sStudent].[pImportStudent]';

GO
EXECUTE sp_refreshsqlmodule N'[sSecurity].[pDashletGet]';


GO





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

