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