

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




IF EXISTS (select top 1 1 from [sPurchase].[tPurchaseReportTemplate])
    RAISERROR (N'Rows were detected. The schema update is terminating because data loss might occur.', 16, 127) WITH NOWAIT

GO
PRINT N'Dropping Table [sPurchase].[tPurchaseReportTemplate]...';


GO
DROP TABLE [sPurchase].[tPurchaseReportTemplate];


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


GO
ALTER TABLE [sFee].[tLateFeeRuleMaster] ALTER COLUMN [FeeRule] NVARCHAR (MAX) NULL;


GO
PRINT N'Altering Table [sPurchase].[tQuotationRequest]...';


GO
ALTER TABLE [sPurchase].[tQuotationRequest] ALTER COLUMN [PersonContact] NVARCHAR (50) NULL;


GO
PRINT N'Creating Table [sBiometric].[tBiometricTypeMaster]...';


GO
CREATE TABLE [sBiometric].[tBiometricTypeMaster] (
    [Status]          NVARCHAR (10) NOT NULL,
    [MainStatusId]    INT           NOT NULL,
    [OrgGroupId]      INT           NOT NULL,
    [CreatedUserId]   BIGINT        NOT NULL,
    [CreatedDateTime] DATETIME      NOT NULL,
    [UpdtaedUserId]   BIGINT        NULL,
    [UpdatedDateTime] DATETIME      NULL
);


GO
PRINT N'Creating Table [sPurchase].[tPurchaseReportTemplateMaster]...';


GO
CREATE TABLE [sPurchase].[tPurchaseReportTemplateMaster] (
    [Id]            BIGINT         IDENTITY (1, 1) NOT NULL,
    [Template]      NVARCHAR (MAX) NOT NULL,
    [CreatedBy]     BIGINT         NOT NULL,
    [CreatedByDate] DATETIME       NULL,
    [IsObsolete]    BIT            NULL,
    [Code]          NVARCHAR (100) NULL,
    CONSTRAINT [PK_PurchaseReportTemplateMaster] PRIMARY KEY CLUSTERED ([Id] ASC)
);


GO
PRINT N'Altering Procedure [sFee].[pLateFeeRuleMasterAdd]...';


GO
ALTER PROCEDURE [sFee].[pLateFeeRuleMasterAdd]
	    @rOrgId int,
        @rId int,
       -- @rCode nvarchar(20),
        @rTitle nvarchar(100),
		@rFeeRule nvarchar(max),
        @rIsObsolete bit
       
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	IF(@rId = 0)	
	BEGIN
		--IF EXISTS (SELECT Id FROM sFee.tLateFeeRuleMaster WHERE Code=@rCode AND OrgGroupBatchId=@rOrgGroupBatchId AND ReceiptBookId=@rReceiptBookId)
		--	BEGIN
		--	SELECT -101 as Result
		--	RETURN
		--END 
	
		IF EXISTS (SELECT Id FROM sFee.tLateFeeRuleMaster WHERE Title=@rTitle AND OrgId=@rOrgId)
			BEGIN
			SELECT -102 as Result
			RETURN
		END 

			IF EXISTS (SELECT Id FROM sFee.tLateFeeRuleMaster WHERE FeeRule=@rFeeRule AND OrgId=@rOrgId)
			BEGIN
			SELECT -103 as Result
			RETURN
		END 
	END
	ELSE
	BEGIN
		--IF EXISTS (SELECT Id FROM sFee.LateFeeRuleMaster WHERE  Code=@rCode AND OrgGroupBatchId=@rOrgGroupBatchId AND ReceiptBookId=@rReceiptBookId AND Id<>@rId)
		--BEGIN
		--	SELECT -101 as Result
		--	RETURN
		--END	
		IF EXISTS (SELECT Id FROM sFee.tLateFeeRuleMaster WHERE  Title=@rTitle AND OrgId=@rOrgId AND Id<>@rId)
		BEGIN
			SELECT -102 as Result
			RETURN
		END 

		IF EXISTS (SELECT Id FROM sFee.tLateFeeRuleMaster WHERE FeeRule=@rFeeRule AND OrgId=@rOrgId AND Id<>@rId)
			BEGIN
			SELECT -103 as Result
			RETURN
       END
	END
	
	
	 BEGIN TRANSACTION	
	 DECLARE @lNextNumber BIGINT 

	IF(@rId = 0)	
	BEGIN
		
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sFee.tLateFeeRuleMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	
	INSERT INTO sFee.tLateFeeRuleMaster
		(
			OrgId,
			Id,
			--Code,
			Title,
			FeeRule,
			IsObsolete	
		)
	VALUES
		(
		    @rOrgId,
			@lNextNumber,
			--@rCode,
			@rTitle,
			@rFeeRule,
			@rIsObsolete
			
		)
		    SELECT 1 AS Result
	END	 

ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE  sFee.tLateFeeRuleMaster
			--Code=@rCode,
			SET Title=@rTitle,
		    	FeeRule=@rFeeRule,
			IsObsolete=@rIsObsolete
	      WHERE Id = @rId
	      SELECT 11 AS Result
	 END  	
	--if not exists(Select 1 from sSystem.tPortalSync where OrgGroupId=@rOrgGroupId)
	--BEGIN
	--	INsert Into sSystem.tPortalSync
	--	(
	--		OrgGroupId,
	--		FeeChange
	--	)
	--	Values
	--	(
	--		@rOrgGroupId,1
	--	)
	--END
	--ELse
	--BEGIN
	--	Update sSystem.tPortalSync
	--	Set
	--		FeeChange=1
	--	Where OrgGroupId=@rOrgGroupId
	
	--END
	COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result 
	END CATCH	
		
END
GO
PRINT N'Altering Procedure [sPurchase].[pPurchaseRequestApprovedGet]...';


GO

--exec [sPurchase].[pPurchaseRequestApprovedGet] 991100002
ALTER PROCEDURE [sPurchase].[pPurchaseRequestApprovedGet]
	  @rId int
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
		select PR.Id,
			   PR.Number,
			   PR.RequestedBy,
			   PR.StatusId,
			   QR.VendorId,
			   PR.LocationId,
			   PR.BranchId,
			   PR.OrgGroupId,
			   PR.ResourceId,
			   PR.RequestDate,
			   PR.RequiredBy,
			   ISNULL(SM.Title,'') AS Status,
			   VM.Code AS VendorCode,
			   VM.Title AS VendorName 
		from   [sPurchase].[tPurchaseRequest] PR (nolock)
			   Left Join [sPurchase].[tQuotationRequest] QR on QR.PurchaseRequestId = PR.Id AND QR.StatusId = 3
			   Left Join [sWf].[tWfStatusMaster] SM ON SM.Id = PR.StatusId
			   Left Join sProcurement.tVendorMaster  VM ON QR.VendorId = VM.ID
		where  PR.Id=@rId AND PR.IsObsolete = 0 AND PR.StatusId = 3 

		select PRD.Id,
			   PRD.PurchaseRequestId,
			   PRD.OrgGroupId,
			   PRD.StockItemId,
			   PRD.RequestedQty,
			   PRD.Remark, 
			   SIM.Code	AS StockItemCode,
			   SCM.Title AS CategoryName,
			   SIM.Title AS StockItemName,
			   SUMa.Code AS UOM
		from   [sPurchase].[tPurchaseRequestDetail] PRD (nolock)
			   Inner JOIN	sPurchase.tPurchaseRequest PR	ON PR.Id = PRD.PurchaseRequestId AND PR.IsObsolete = 0 AND PR.StatusId = 3
			   Inner JOIN	sIp.tStockItemMaster SIM	ON SIM.Id = PRD.StockItemId 
			   LEFT JOIN [sIp].[tStockItemCategoryMaster] SCM ON SCM.Id = SIM.StockItemCategoryId
			   Inner JOIN  sFinanceCommon.tStockUomMaster SUMa ON SUMa.Id = SIM.IssueStockUomId
		where  PurchaseRequestId=@rId
	END TRY

	BEGIN CATCH
    IF @@TRANCOUNT > 0
        ROLLBACK TRAN --RollBack in case of Error
    
    DECLARE @ErrorMessage NVARCHAR(4000);  
    DECLARE @ErrorSeverity INT;  
    DECLARE @ErrorState INT;  
    SELECT   
       @ErrorMessage = ERROR_MESSAGE(),  
       @ErrorSeverity = ERROR_SEVERITY(),  
       @ErrorState = ERROR_STATE();  
    RAISERROR (@ErrorMessage, @ErrorSeverity, @ErrorState);  
    
	END CATCH

END
GO
PRINT N'Altering Procedure [sPurchase].[pPurchaseRequestApprovedSearchGet]...';


GO

--exec [sPurchase].[pPurchaseRequestApprovedSearchGet] '',991100001,'',9911,'2021-01-01','2023-12-11',1,10,null
ALTER PROCEDURE [sPurchase].[pPurchaseRequestApprovedSearchGet]

	@rNumber nvarchar(30) = '',
	@rLocationId int,
	@rName nvarchar = '',
	@rOrgGroupId int,
	@rStartDate DateTime = null,
	@rEndDate DateTime = null,
	@rPageNo int,
	@rPageSize int,
	@rStatusId smallint = 0

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY

		DECLARE @TotalRecords BIGINT;
		-- Get the total number of records
		SELECT @TotalRecords = COUNT(*) FROM sPurchase.tPurchaseRequest PR (nolock)

		WHERE 
				((PR.Number like @rNumber+'%') OR (ISNULL(@rNumber,'') = ''))
   				AND ((PR.RequestedBy like @rName+'%') OR (ISNULL(@rName,'') = ''))
   				--AND ((SLM.Id = @rStoreLocationId) OR (@rStoreLocationId = 0))
   				AND ((PR.OrgGroupId = @rOrgGroupId) OR (@rOrgGroupId=0))
				AND ((PR.StatusId = @rStatusId) OR (ISNULL(@rStatusId,0)=0))
				AND PR.IsObsolete = 0 and PR.StatusId = 3 
				AND ((Cast(PR.CreatedDateTime as Date) >= Cast(@rStartDate as Date)) OR (ISNULL(@rStartDate,'')=''))
				AND((Cast(PR.CreatedDateTime as Date) <= Cast(@rEndDate as Date)) OR (ISNULL(@rEndDate,'')=''))


		Select t.* From (
			Select ROW_NUMBER() Over (
			Order by PR.Id desc  
			) AS 'RowNum',PR.Id, 
				PR.Number,
				PR.RequestedBy, 
				PR.LocationId, 
				PR.RequestDate,
				ISNULL(SM.Title,'') as Status

	    FROM		
				sPurchase.tPurchaseRequest PR (nolock)
				Left Join [sWf].[tWfStatusMaster] SM on PR.StatusId = SM.Id


        WHERE 
				((PR.Number like @rNumber+'%') OR (ISNULL(@rNumber,'') = ''))
   				AND ((PR.RequestedBy like @rName+'%') OR (ISNULL(@rName,'') = ''))
   				--AND ((SLM.Id = @rStoreLocationId) OR (@rStoreLocationId = 0))
   				AND ((PR.OrgGroupId = @rOrgGroupId) OR (@rOrgGroupId=0))
				AND ((PR.StatusId = @rStatusId) OR (ISNULL(@rStatusId,0)=0))
				AND PR.IsObsolete = 0 and PR.StatusId = 3 
				AND ((Cast(PR.CreatedDateTime as Date) >= Cast(@rStartDate as Date)) OR (ISNULL(@rStartDate,'')=''))
				AND((Cast(PR.CreatedDateTime as Date) <= Cast(@rEndDate as Date)) OR (ISNULL(@rEndDate,'')='')))t Where t.RowNum Between
		        ((@rPageNo-1)*@rPageSize +1) AND (@rPageNo*@rpageSize)

        SELECT @TotalRecords as TotalRecords
	 END TRY

	BEGIN CATCH
    IF @@TRANCOUNT > 0
        ROLLBACK TRAN --RollBack in case of Error
    
    DECLARE @ErrorMessage NVARCHAR(4000);  
    DECLARE @ErrorSeverity INT;  
    DECLARE @ErrorState INT;  
    SELECT   
       @ErrorMessage = ERROR_MESSAGE(),  
       @ErrorSeverity = ERROR_SEVERITY(),  
       @ErrorState = ERROR_STATE();  
    RAISERROR (@ErrorMessage, @ErrorSeverity, @ErrorState);  
    
	END CATCH  		  
END
GO
PRINT N'Altering Procedure [sPurchase].[pQuotationRequestSearchGet]...';


GO

--exec [sPurchase].[pQuotationRequestSearchGet] @rLocationId=991100001,@rOrgGroupId=9911,@rStartDate='2023-12-12',@rEndDate='2023-12-13',@rPageNo=1,@rPageSize=10
ALTER PROCEDURE [sPurchase].[pQuotationRequestSearchGet]

	@rNumber nvarchar(30) = '',
	@rLocationId int,
	@rName nvarchar = '',
	@rOrgGroupId smallint,
	@rStartDate DateTime = null,
	@rEndDate DateTime = null,
	@rPageNo int,
	@rPageSize int,
	@rStatusId smallint = 0

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY

        DECLARE @TotalRecords BIGINT;
		-- Get the total number of records
		SELECT @TotalRecords = COUNT(*) FROM sPurchase.tQuotationRequest QR (nolock)

		WHERE 
				((QR.Number like @rNumber+'%') OR (ISNULL(@rNumber,'') = ''))
   				AND ((QR.Name like @rName+'%') OR (ISNULL(@rName,'') = ''))
   				--AND ((SLM.Id = @rStoreLocationId) OR (@rStoreLocationId = 0))
   				AND ((QR.OrgGroupId = @rOrgGroupId) OR (@rOrgGroupId=0))
				AND ((QR.StatusId = @rStatusId) OR (ISNULL(@rStatusId,0)=0))
				AND QR.IsObsolete = 0
				AND ((Cast(QR.CreatedDateTime as Date) >= Cast(@rStartDate as Date)) OR (ISNULL(@rStartDate,'')=''))
				AND((Cast(QR.CreatedDateTime as Date) <= Cast(@rEndDate as Date)) OR (ISNULL(@rEndDate,'')=''))


		Select t.* From (
			Select ROW_NUMBER() Over (
			Order by QR.Id desc  
			) AS 'RowNum',QR.Id, 
				QR.Number,
				QR.Name as RequestedBy,
				QR.LocationId,
				QR.RFQDate,
				ISNULL(SM.Title,'') as Status

        FROM		
				sPurchase.tQuotationRequest QR (nolock)
				Left Join [sWf].[tWfStatusMaster] SM on QR.StatusId = SM.Id

	    
		WHERE 
				((QR.Number like @rNumber+'%') OR (ISNULL(@rNumber,'') = ''))
   				AND ((QR.Name like @rName+'%') OR (ISNULL(@rName,'') = ''))
   				--AND ((SLM.Id = @rStoreLocationId) OR (@rStoreLocationId = 0))
   				AND ((QR.OrgGroupId = @rOrgGroupId) OR (@rOrgGroupId=0))
				AND ((QR.StatusId = @rStatusId) OR (ISNULL(@rStatusId,0)=0))
				AND QR.IsObsolete = 0
				AND ((Cast(QR.CreatedDateTime as Date) >= Cast(@rStartDate as Date)) OR (ISNULL(@rStartDate,'')=''))
				AND((Cast(QR.CreatedDateTime as Date) <= Cast(@rEndDate as Date)) OR (ISNULL(@rEndDate,'')=''))
					)t Where t.RowNum Between
		        ((@rPageNo-1)*@rPageSize +1) AND (@rPageNo*@rpageSize)

        SELECT @TotalRecords as TotalRecords

	 END TRY

	BEGIN CATCH
    IF @@TRANCOUNT > 0
        ROLLBACK TRAN --RollBack in case of Error
    
    DECLARE @ErrorMessage NVARCHAR(4000);  
    DECLARE @ErrorSeverity INT;  
    DECLARE @ErrorState INT;  
    SELECT   
       @ErrorMessage = ERROR_MESSAGE(),  
       @ErrorSeverity = ERROR_SEVERITY(),  
       @ErrorState = ERROR_STATE();  
    RAISERROR (@ErrorMessage, @ErrorSeverity, @ErrorState);  
    
	END CATCH  		  
END
GO
PRINT N'Altering Procedure [sPurchase].[pQuotationVendorGet]...';


GO

 
--exec [sPurchase].[pQuotationVendorGet] 991100010
ALTER PROCEDURE [sPurchase].[pQuotationVendorGet]
	
		 @rQuotationRequestId bigint
		 --,
	 	-- @rTemplate nvarchar(max)
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

	Declare
		@rDescription  AS NVARCHAR(1000),
		@rStartDate AS NVARCHAR(100),
		@rEndDate AS NVARCHAR(100),
		@rBidOpen AS NVARCHAR(100),
		@rBidClose AS NVARCHAR(100),
		@rPersonContact AS NVARCHAR(100),
		@rEmail AS NVARCHAR(100),
		@rRFQDate AS NVARCHAR(100)

	    select  @rDescription = ISNULL(QR.Description,''),
				@rStartDate = ISNULL(QR.StartDate,''),
				@rEndDate = ISNULL(QR.EndDate,''),
				@rBidOpen = ISNULL(QR.BidOpen,''),
				@rBidClose = ISNULL(QR.BidClose,''),
				@rPersonContact = ISNULL(QR.PersonContact,''),
				@rEmail = ISNULL(QR.Email,''),
				@rRFQDate = ISNULL(QR.RFQDate,'')
		from   [sPurchase].[tQuotationRequest] QR(nolock) 
			   Left JOIN sProcurement.tVendorMaster  VM on QR.VendorId = VM.ID
			   Left Join [sWf].[tWfStatusMaster] SM ON SM.Id = QR.StatusId
			   Left Join [sPurchase].[tPurchaseRequest] PR on PR.Id = QR.PurchaseRequestId
		where  QR.Id = @rQuotationRequestId AND QR.IsObsolete = 0

	DECLARE @HTMLTable NVARCHAR(MAX);
	SET @HTMLTable = '';
    SET @HTMLTable = @HTMLTable + '<tr>';
    SET @HTMLTable = @HTMLTable + '<th>StockItemCode</th>';
    SET @HTMLTable = @HTMLTable + '<th>StockItemName</th>';
    SET @HTMLTable = @HTMLTable + '<th>Uom</th>';
    SET @HTMLTable = @HTMLTable + '<th>TotalQty</th>';
    SET @HTMLTable = @HTMLTable + '<th>TargetPrice</th>';
    SET @HTMLTable = @HTMLTable + '<th>Remark</th>';
    SET @HTMLTable = @HTMLTable + '</tr>';

	Select @HTMLTable = @HTMLTable+'<tr><td>'+Cast(SIM.Code as Nvarchar(100))+'</td><td>'
	+SIM.Title+'</td><td>'+SUMa.Code+'</td><td>'+Cast(QRD.RequestedQty as Nvarchar(100))+
	+'</td><td>'+Cast(QRD.TargetPrice as Nvarchar(100))+'</td><td>'+QRD.Remark+'</td></tr>'
	  from   [sPurchase].[tQuotationRequestDetail] QRD (nolock)
		Inner JOIN	sPurchase.tQuotationRequest QR	ON QR.Id = QRD.QuotationRequestId AND QR.IsObsolete = 0
		Inner JOIN	sIp.tStockItemMaster SIM	ON SIM.Id = QRD.StockItemId 
		Inner JOIN  sFinanceCommon.tStockUomMaster SUMa ON SUMa.Id = SIM.IssueStockUomId
		where  QR.Id = @rQuotationRequestId
    --PRINT @HTMLTable;
	declare @txtMessage nvarchar(Max)
    select @txtMessage=REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(Template, 
		'{Description}' , @rDescription),
		'{StartDate}' , @rStartDate),
		'{EndDate}' , @rEndDate),
		'{BidOpen}' , @rBidOpen),
		'{BidClose}' , @rBidClose),
		'{PersonContact}' , @rPersonContact),
		'{Email}' , @rEmail),
		'{RFQDate}' , @rRFQDate),
		'{QuatationDetails}' , @HTMLTable)from sPurchase.tPurchaseReportTemplate where id = 1

		Declare @VendorId bigint
		Select @VendorId = QR.VendorId from sPurchase.tQuotationRequest QR Where QR.Id = @rQuotationRequestId AND QR.IsObsolete = 0
	
	SELECT 
			--A.AcademicId,
			A.Code,
			A.Name,
			A.ParentContactNo AS MobileNo,	
			A.ParentEmail AS EmailId,
			@txtMessage	AS MsgText,
			'' AS Subject,
			 2001 AS ReceiverSourceTypeId,
			 (SELECT Id FROM sSetup.tOrganizationMaster where OrgGroupId=A.OrgGroupId and Id = A.OrgGroupId) AS OrgId,
			 A.OrgGroupId AS OrgGroupId,
			 --A.AcademicId AS ReceiverSourceId,
			 A.Id AS SourceId,
			 2001 AS SourceTypeId,
			 --DM.Title AS MeetingType,
			 --CONVERT(varchar(11),ISNULL(OM.StartDate,'') ,103) AS StartDate,
			 --CONVERT(varchar(11),ISNULL(OM.EndDate,'') ,103) AS EndDate,
			 --EE.EmployeeName AS Teacher,
			 --OM.Title AS Title,
			 A.WhatsAppContactNo
	FROM 
		 [sPurchase].[tQuotationRequestDetail] QRD (nolock)
		Inner JOIN	sPurchase.tQuotationRequest QR	ON QR.Id = QRD.QuotationRequestId AND QR.IsObsolete = 0
		Inner JOIN	sIp.tStockItemMaster SIM	ON SIM.Id = QRD.StockItemId 
		Inner JOIN  sFinanceCommon.tStockUomMaster SUMa ON SUMa.Id = SIM.IssueStockUomId
		INNER JOIN (
			SELECT	VM.Id,
					VM.ContactPersonName as Name,
					VM.Code,
					VM.PhoneNumberOffice as ParentContactNo,
					VM.Email as ParentEmail,
					VM.OrgGroupId,
					VM.PhoneNumberMobile WhatsAppContactNo		
			FROM	sProcurement.tVendorMaster  VM
			LEFT JOIN   sProcurement.tVendorCategoryMaster VC
			ON  VM.VendorCategoryId = VC.Id
			WHERE VM.Id = @VendorId
		) as A ON A.Id = QR.VendorId
		where  QR.Id = @rQuotationRequestId
END
GO
PRINT N'Altering Procedure [sWf].[pWfApprovalAdd]...';


GO


ALTER PROCEDURE [sWf].[pWfApprovalAdd]
		@rId	bigint,
	 	@rDocSourceId bigint=0,
	 	@rDocSourceTypeId smallint=0,
        @rActionEmployeeId bigint=0,
		@rActionStatusId smallint=0,
		@rActionRemark nvarchar(500) = '',
		@rIsSequancial bit=0,
		@rWfLevel int=0,
		@rWfFunctionalityId smallint=0,
		@rOrgGroupId smallint
		
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
    BEGIN TRY
	BEGIN TRANSACTION
    Declare @lActionByEmployeeId bigint
	set @lActionByEmployeeId = @rActionEmployeeId

	Declare @StatusId smallint
	set @StatusId = @rActionStatusId

	IF(@rIsSequancial = 1)
	BEGIN
		Declare @HierarchyLevelId bigint
		select @HierarchyLevelId=ISNULL(AutoId,0) from [sWf].[tWfHierarchyLevel] WHERE WfApprovalActionId =@rId AND ActionByEmployeeId=@rActionEmployeeId AND StatusId <> 4
		IF(@HierarchyLevelId > 0)
		Begin
			UPDATE [sWf].[tWfHierarchyLevel] SET StatusId = @StatusId , Remark = @rActionRemark 
			WHERE AutoId = @HierarchyLevelId
		End

		IF(@rActionStatusId <> 4)
		BEGIN
			DECLARE @LogCount int
			SELECT @LogCount = COUNT(AutoId) FROM [sWf].[tWfHierarchyLevel] WHERE WfApprovalActionId = @rId
			
			IF(@rWfLevel <> @LogCount)
			Begin
				IF(@rActionStatusId = 3)
				Begin
					set @StatusId = 2
				End
				
			End
			SELECT @lActionByEmployeeId = EmployeeManagerId from [sHrm].[tEmployeeJobDetail] WHere EmployeeId = @rActionEmployeeId
			AND @lActionByEmployeeId IS NOT NULL
			
		END
	END

	IF(@rId = 0)
	BEGIN
		
		DECLARE @lNextNumber INT	 
		EXECUTE [sCommon].[pGetIntMaxIdForOrgGroup] @rOrgGroupId, 'sWf.tWfApprovalAction',@lNextNumber = @lNextNumber output

		INSERT INTO sWf.tWfApprovalAction
		(
		Id,
		OrgGroupId,
		ActionEmployeeId,
		ActionStatusId,
		ActionRemark,
		DocSourceId,
		DocSourceTypeId,
		WfFunctionalityId,
		CreatedUserId,
		CreatedDateTime
		)
		VALUES
		(
			@lNextNumber,
			@rOrgGroupId,
			@rActionEmployeeId,
			@StatusId,
			@rActionRemark,
			@rDocSourceId,
			@rDocSourceTypeId,
			@rWfFunctionalityId,
			@rActionEmployeeId,
			GETUTCDATE()				
		)
		set @rId=@lNextNumber
		
		INSERT INTO sWf.tWfApprovalActionLog
		(
			WfApprovalActionId,
			ActionByEmployeeId,
			StatusId,
			IsSequancial,
			ActionRemark,
			CreatedUserId,
			CreatedDateTime
		)
		VALUES
		(
			@rId,
			@lActionByEmployeeId,
			@rActionStatusId,
			@rIsSequancial,
			@rActionRemark,
			@rActionEmployeeId,
			GETUTCDATE()				
		)

		IF(@rIsSequancial = 1 AND (@rWfLevel <> @LogCount OR @rWfLevel > 0))
		BEGIN																																																																																																																																																																				IF(@lActionByEmployeeId > 0)
			INSERT INTO [sWf].[tWfHierarchyLevel]
					(WfApprovalActionId
					,StatusId
					,Remark
					,ActionByEmployeeId
					,ActionDatetime)
				VALUES
					(@rId
					,1
					,''
					,@lActionByEmployeeId
					,sCommon.fGetDate())
		END
		SELECT 1 AS Result
	END
	ELSE
	BEGIN
		--IF EXISTS(select ID from sWf.tWfApprovalAction WHERE id = @rId AND ActionStatusId not in(3,4) OR @rIsSequancial = 0)
		--BEGIN
			UPDATE sWf.tWfApprovalAction
			SET 
			DocSourceId=@rDocSourceId,
			DocSourceTypeId=@rDocSourceTypeId,
			ActionEmployeeId=@rActionEmployeeId,
			ActionStatusId=@StatusId,
			ActionRemark=@rActionRemark,
			UpdatedUserId = @rActionEmployeeId,		
			UpdatedDateTime = GetUtcDate()
			WHERE id = @rId 

			INSERT INTO sWf.tWfApprovalActionLog
			(
				WfApprovalActionId,
				ActionByEmployeeId,
				StatusId,
				IsSequancial,
				ActionRemark,
				CreatedUserId,
				CreatedDateTime
			)
			VALUES
			(
				@rId,
				@lActionByEmployeeId,
				@rActionStatusId,
				@rIsSequancial,
				@rActionRemark,
				@rActionEmployeeId,
				GETUTCDATE()				
			)
			IF(@rIsSequancial = 1)
			Begin
				IF(@rWfLevel <> @LogCount AND @rActionStatusId <> 4)
				BEGIN																																										IF(@lActionByEmployeeId > 0)
					INSERT INTO [sWf].[tWfHierarchyLevel]
							(WfApprovalActionId
							,StatusId
							,Remark
							,ActionByEmployeeId
							,ActionDatetime)
						VALUES
							(@rId
							,1
							,''
							,@lActionByEmployeeId
							,sCommon.fGetDate())
				END
				ELSE
				BEGIN
						SELECT @lActionByEmployeeId = EmployeeManagerId from [sHrm].[tEmployeeJobDetail] WHere EmployeeId = @rActionEmployeeId
						DELETE FROM [sWf].[tWfHierarchyLevel] Where WfApprovalActionId = @rId AND ActionByEmployeeId = @lActionByEmployeeId AND @lActionByEmployeeId IS NOT NULL
				END 
			END
			SELECT 11 AS Result 
		--END
	END	
	IF EXISTS(select ID from sWf.tWfApprovalAction WHERE id = @rId AND ActionStatusId in(3,4))
	Begin
		if(@rDocSourceTypeId = 2040)
		Begin
			update sPurchase.tPurchaseRequest 
			set StatusId = @StatusId,
				UpdatedUserId = @rActionEmployeeId,
				UpdatedDateTime = GETUTCDATE()
			where Id = @rDocSourceId 
		END
		else if(@rDocSourceTypeId = 2041)
		Begin
			update sPurchase.tQuotationRequest 
			set StatusId = @StatusId,
				UpdatedUserId = @rActionEmployeeId,
				UpdatedDateTime = GETUTCDATE()
			where Id = @rDocSourceId 
		END
		else if(@rDocSourceTypeId = 2042)
		Begin
			update sPurchase.tPurchaseOrder 
			set StatusId = @StatusId,
				UpdatedUserId = @rActionEmployeeId,
				UpdatedDateTime = GETUTCDATE()
			where Id = @rDocSourceId 
		END
		else if(@rDocSourceTypeId = 2043)
		Begin
			update sPurchase.tGoodsReceivedNote 
			set StatusId = @StatusId,
				UpdatedUserId = @rActionEmployeeId,
				UpdatedDateTime = GETUTCDATE()
			where Id = @rDocSourceId 
		END
		else if(@rDocSourceTypeId = 2044)
		Begin
			update sPurchase.tSalesReturn 
			set StatusId = @StatusId,
				UpdatedUserId = @rActionEmployeeId,
				UpdatedDateTime = GETUTCDATE()
			where Id = @rDocSourceId 
		END
	End
	COMMIT TRAN -- Transaction Success!	
	END TRY

	BEGIN CATCH
    IF @@TRANCOUNT > 0
        ROLLBACK TRAN --RollBack in case of Error

    
    DECLARE @ErrorMessage NVARCHAR(4000);  
    DECLARE @ErrorSeverity INT;  
    DECLARE @ErrorState INT;  

    SELECT   
       @ErrorMessage = ERROR_MESSAGE(),  
       @ErrorSeverity = ERROR_SEVERITY(),  
       @ErrorState = ERROR_STATE();  

    RAISERROR (@ErrorMessage, @ErrorSeverity, @ErrorState);  
    
	END CATCH 
END
GO
PRINT N'Altering Procedure [sWf].[pWfApprovalGet]...';


GO


--exec [sWf].[pWfApprovalGet] 1,null,null,0,9911,'',9911000000270,0
 
ALTER  PROCEDURE [sWf].[pWfApprovalGet]
			 @rWfFunctionalityId smallint=0,
			 @rFromDate date=null,
			 @rToDate date=null,
			 @rStatusId smallint=0,
			 @rOrgId smallint=0,
			 @rCode nvarchar(20) ='',
			 @rUserId bigint ,
			 @rApprovalRequestId bigint = 0

	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	Declare @lRoleId int
	Select @lRoleId = RoleId from [sSecurity].[tUserRole] Where UserId = @rUserId

	SELECT
		AA.Id AS ApprovalActionId,
		AA.DocSourceId AS DocSourceId,
		AA.DocSourceTypeId AS DocSourceTypeId,
		WFM.Title AS WorkFlowName,
		WFM.Id AS WorkFlowId,
		PR.Id AS ApprovalRequestId,
		CONVERT(DATE,PR.CreatedDateTime, 103) AS CreatedDateTime,
		95 AS ParticipantSourceTypeId,
		EM.Id AS SourceId,
		EM.Code AS Code ,
		EM.FirstName +' '+ EM.MiddleName +' ' +EM.LastName AS Name ,
		--PR.Remark AS Remark,
		(CASE ISNULL(sm.Id,'') WHEN '' THEN 3 ELSE sm.Id END) AS statusId,
		(CASE ISNULL(sm.title,'') WHEN '' THEN 'Pending' ELSE sm.title END) AS status,
		ISNULL(AA.ActionRemark, '') AS ActionRemark
			
		
	from sPurchase.tPurchaseRequest PR
	INNER JOIN sWf.tWfApprovingAuthority FAA ON 1 = FAA.WfFunctionalityId And FAA.OrgId =@rOrgId
	INNER JOIN sSecurity.tRole R ON R.Id = FAA.AuthoritySourceId AND FAA.AuthoritySourceTypeId = 2015
	LEFT JOIN sWf.tWfApprovalAction AA ON AA.DocSourceId = PR.Id AND AA.WfFunctionalityId = FAA.WfFunctionalityId AND AA.DocSourceTypeId = 2040
	LEFT JOIN sWf.tWfStatusMaster SM ON SM.Id = AA.ActionStatusId
	INNER JOIN sWf.tWfFunctionalityMaster WFM ON WFM.Id = FAA.WfFunctionalityId
	LEFT JOIN  sHrm.tEmployeeMaster  EM ON EM.Id = AA.ActionEmployeeId
	
	WHERE R.Id = @lRoleId
	AND ((WFM.Id = @rWfFunctionalityId) OR (@rWfFunctionalityId =0)) 
	AND ((Convert(Date,PR.CreatedDateTime)>= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
	AND ((Convert(Date,PR.CreatedDateTime) <= @rToDate) OR (ISNULL(@rToDate,'') = ''))
	AND((SM.Id = @rStatusId) OR (@rStatusId =0))
	AND ((EM.Code = @rCode) OR (@rCode = ''))
	AND  ISNULL(EM.IsOtherUser,0) = 0
	AND ((PR.Id = @rApprovalRequestId) OR (@rApprovalRequestId = 0))

	UNION

	SELECT
		AA.Id AS ApprovalActionId,
		AA.DocSourceId AS DocSourceId,
		AA.DocSourceTypeId AS DocSourceTypeId,
		WFM.Title AS WorkFlowName,
		WFM.Id AS WorkFlowId,
		PR.Id AS ApprovalRequestId,
		CONVERT(DATE,PR.CreatedDateTime, 103) AS CreatedDateTime,
		95 AS ParticipantSourceTypeId,
		EM.Id AS SourceId,
		EM.Code AS Code ,
		EM.FirstName +' '+ EM.MiddleName +' ' +EM.LastName AS Name ,
		--AR.Remark AS Remark,
		(CASE ISNULL(sm.Id,'') WHEN '' THEN 3 ELSE sm.Id END) AS statusId,
		(CASE ISNULL(sm.title,'') WHEN '' THEN 'Pending' ELSE sm.title END) AS status,
		ISNULL(AA.ActionRemark, '') AS ActionRemark
			
		
	from sPurchase.tPurchaseRequest PR
	INNER JOIN sWf.tWfApprovingAuthority FAA ON 1 = FAA.WfFunctionalityId And FAA.OrgId =@rOrgId
	INNER JOIN sSecurity.tUser U ON U.Id = FAA.AuthoritySourceId AND FAA.AuthoritySourceTypeId = 1019
	LEFT JOIN sWf.tWfApprovalAction AA ON AA.DocSourceId = PR.Id AND AA.WfFunctionalityId = FAA.WfFunctionalityId AND AA.DocSourceTypeId = 2040
	LEFT JOIN sWf.tWfStatusMaster SM ON SM.Id = AA.ActionStatusId
	INNER JOIN sWf.tWfFunctionalityMaster WFM ON WFM.Id = FAA.WfFunctionalityId
	LEFT JOIN  sHrm.tEmployeeMaster  EM ON EM.Id = AA.ActionEmployeeId
	WHERE U.Id = @rUserId
	AND ((WFM.Id = @rWfFunctionalityId) OR (@rWfFunctionalityId =0)) 
	AND ((Convert(Date,PR.CreatedDateTime)>= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
	AND ((Convert(Date,PR.CreatedDateTime) <= @rToDate) OR (ISNULL(@rToDate,'') = ''))
	AND((SM.Id = @rStatusId) OR (@rStatusId =0))
	AND ((EM.Code = @rCode) OR (@rCode =''))
	AND  ISNULL(EM.IsOtherUser,0) = 0
	AND ((PR.Id = @rApprovalRequestId) OR (@rApprovalRequestId = 0))

	UNION

	SELECT
		AA.Id AS ApprovalActionId,
		AA.DocSourceId AS DocSourceId,
		AA.DocSourceTypeId AS DocSourceTypeId,
		WFM.Title AS WorkFlowName,
		WFM.Id AS WorkFlowId,
		PR.Id AS ApprovalRequestId,
		CONVERT(DATE,PR.CreatedDateTime, 103) AS CreatedDateTime,
		95 AS ParticipantSourceTypeId,
		EM.Id AS SourceId,
		EM.Code AS Code ,
		EM.FirstName +' '+ EM.MiddleName +' ' +EM.LastName AS Name ,
		--AR.Remark AS Remark,
		(CASE ISNULL(sm.Id,'') WHEN '' THEN 3 ELSE sm.Id END) AS statusId,
		(CASE ISNULL(sm.title,'') WHEN '' THEN 'Pending' ELSE sm.title END) AS status,
		ISNULL(AA.ActionRemark, '') AS ActionRemark
			
		
	from sPurchase.tPurchaseRequest PR
	INNER JOIN sWf.tWfFunctionalityMaster WFM ON 1 = WFM.Id
	INNER JOIN sWf.tWfApprovalAction AA ON AA.DocSourceId = PR.Id AND AA.WfFunctionalityId = WFM.Id AND AA.DocSourceTypeId = 2040
	INNER JOIN sWf.tWfHierarchyLevel HL ON HL.WfApprovalActionId = AA.Id
	LEFT JOIN sWf.tWfStatusMaster SM ON SM.Id = AA.ActionStatusId
	LEFT JOIN  sHrm.tEmployeeMaster  EM ON EM.Id = AA.ActionEmployeeId
	WHERE HL.ActionByEmployeeId = @rUserId
	AND ((WFM.Id = @rWfFunctionalityId) OR (@rWfFunctionalityId =0)) 
	AND ((Convert(Date,PR.CreatedDateTime)>= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
	AND ((Convert(Date,PR.CreatedDateTime) <= @rToDate) OR (ISNULL(@rToDate,'') = ''))
	AND((SM.Id = @rStatusId) OR (@rStatusId =0))
	AND ((EM.Code = @rCode) OR (@rCode =''))
	AND  ISNULL(EM.IsOtherUser,0) = 0
	AND ((PR.Id = @rApprovalRequestId) OR (@rApprovalRequestId = 0))

	------------------------------------------------------------------------------------------------------------------------------------------------------------------
	UNION
	SELECT
		AA.Id AS ApprovalActionId,
		AA.DocSourceId AS DocSourceId,
		AA.DocSourceTypeId AS DocSourceTypeId,
		WFM.Title AS WorkFlowName,
		WFM.Id AS WorkFlowId,
		QR.Id AS ApprovalRequestId,
		CONVERT(DATE,QR.CreatedDateTime, 103) AS CreatedDateTime,
		95 AS ParticipantSourceTypeId,
		EM.Id AS SourceId,
		EM.Code AS Code ,
		EM.FirstName +' '+ EM.MiddleName +' ' +EM.LastName AS Name ,
		--PR.Remark AS Remark,
		(CASE ISNULL(sm.Id,'') WHEN '' THEN 3 ELSE sm.Id END) AS statusId,
		(CASE ISNULL(sm.title,'') WHEN '' THEN 'Pending' ELSE sm.title END) AS status,
		ISNULL(AA.ActionRemark, '') AS ActionRemark
			
		
	from sPurchase.tQuotationRequest QR
	INNER JOIN sWf.tWfApprovingAuthority FAA ON 2 = FAA.WfFunctionalityId And FAA.OrgId =@rOrgId
	INNER JOIN sSecurity.tRole R ON R.Id = FAA.AuthoritySourceId AND FAA.AuthoritySourceTypeId = 2015
	LEFT JOIN sWf.tWfApprovalAction AA ON AA.DocSourceId = QR.Id AND AA.WfFunctionalityId = FAA.WfFunctionalityId AND AA.DocSourceTypeId = 2041
	LEFT JOIN sWf.tWfStatusMaster SM ON SM.Id = AA.ActionStatusId
	INNER JOIN sWf.tWfFunctionalityMaster WFM ON WFM.Id = FAA.WfFunctionalityId
	LEFT JOIN  sHrm.tEmployeeMaster  EM ON EM.Id = AA.ActionEmployeeId
	
	WHERE R.Id = @lRoleId
	AND ((WFM.Id = @rWfFunctionalityId) OR (@rWfFunctionalityId =0)) 
	AND ((Convert(Date,QR.CreatedDateTime)>= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
	AND ((Convert(Date,QR.CreatedDateTime) <= @rToDate) OR (ISNULL(@rToDate,'') = ''))
	AND((SM.Id = @rStatusId) OR (@rStatusId =0))
	AND ((EM.Code = @rCode) OR (@rCode = ''))
	AND  ISNULL(EM.IsOtherUser,0) = 0
	AND ((QR.Id = @rApprovalRequestId) OR (@rApprovalRequestId = 0))

	UNION

	SELECT
		AA.Id AS ApprovalActionId,
		AA.DocSourceId AS DocSourceId,
		AA.DocSourceTypeId AS DocSourceTypeId,
		WFM.Title AS WorkFlowName,
		WFM.Id AS WorkFlowId,
		QR.Id AS ApprovalRequestId,
		CONVERT(DATE,QR.CreatedDateTime, 103) AS CreatedDateTime,
		95 AS ParticipantSourceTypeId,
		EM.Id AS SourceId,
		EM.Code AS Code ,
		EM.FirstName +' '+ EM.MiddleName +' ' +EM.LastName AS Name ,
		--AR.Remark AS Remark,
		(CASE ISNULL(sm.Id,'') WHEN '' THEN 3 ELSE sm.Id END) AS statusId,
		(CASE ISNULL(sm.title,'') WHEN '' THEN 'Pending' ELSE sm.title END) AS status,
		ISNULL(AA.ActionRemark, '') AS ActionRemark
			
		
	from sPurchase.tQuotationRequest QR
	INNER JOIN sWf.tWfApprovingAuthority FAA ON 2 = FAA.WfFunctionalityId And FAA.OrgId =@rOrgId
	INNER JOIN sSecurity.tUser U ON U.Id = FAA.AuthoritySourceId AND FAA.AuthoritySourceTypeId = 1019
	LEFT JOIN sWf.tWfApprovalAction AA ON AA.DocSourceId = QR.Id AND AA.WfFunctionalityId = FAA.WfFunctionalityId AND AA.DocSourceTypeId = 2041
	LEFT JOIN sWf.tWfStatusMaster SM ON SM.Id = AA.ActionStatusId
	INNER JOIN sWf.tWfFunctionalityMaster WFM ON WFM.Id = FAA.WfFunctionalityId
	LEFT JOIN  sHrm.tEmployeeMaster  EM ON EM.Id = AA.ActionEmployeeId
	WHERE U.Id = @rUserId
	AND ((WFM.Id = @rWfFunctionalityId) OR (@rWfFunctionalityId =0)) 
	AND ((Convert(Date,QR.CreatedDateTime)>= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
	AND ((Convert(Date,QR.CreatedDateTime) <= @rToDate) OR (ISNULL(@rToDate,'') = ''))
	AND((SM.Id = @rStatusId) OR (@rStatusId =0))
	AND ((EM.Code = @rCode) OR (@rCode =''))
	AND  ISNULL(EM.IsOtherUser,0) = 0
	AND ((QR.Id = @rApprovalRequestId) OR (@rApprovalRequestId = 0))

	UNION

	SELECT
		AA.Id AS ApprovalActionId,
		AA.DocSourceId AS DocSourceId,
		AA.DocSourceTypeId AS DocSourceTypeId,
		WFM.Title AS WorkFlowName,
		WFM.Id AS WorkFlowId,
		QR.Id AS ApprovalRequestId,
		CONVERT(DATE,QR.CreatedDateTime, 103) AS CreatedDateTime,
		95 AS ParticipantSourceTypeId,
		EM.Id AS SourceId,
		EM.Code AS Code ,
		EM.FirstName +' '+ EM.MiddleName +' ' +EM.LastName AS Name ,
		--AR.Remark AS Remark,
		(CASE ISNULL(sm.Id,'') WHEN '' THEN 3 ELSE sm.Id END) AS statusId,
		(CASE ISNULL(sm.title,'') WHEN '' THEN 'Pending' ELSE sm.title END) AS status,
		ISNULL(AA.ActionRemark, '') AS ActionRemark
			
		
	from sPurchase.tQuotationRequest QR
	INNER JOIN sWf.tWfFunctionalityMaster WFM ON 2 = WFM.Id
	INNER JOIN sWf.tWfApprovalAction AA ON AA.DocSourceId = QR.Id AND AA.WfFunctionalityId = WFM.Id AND AA.DocSourceTypeId = 2041
	INNER JOIN sWf.tWfHierarchyLevel HL ON HL.WfApprovalActionId = AA.Id
	LEFT JOIN sWf.tWfStatusMaster SM ON SM.Id = AA.ActionStatusId
	LEFT JOIN  sHrm.tEmployeeMaster  EM ON EM.Id = AA.ActionEmployeeId
	WHERE HL.ActionByEmployeeId = @rUserId
	AND ((WFM.Id = @rWfFunctionalityId) OR (@rWfFunctionalityId =0)) 
	AND ((Convert(Date,QR.CreatedDateTime)>= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
	AND ((Convert(Date,QR.CreatedDateTime) <= @rToDate) OR (ISNULL(@rToDate,'') = ''))
	AND((SM.Id = @rStatusId) OR (@rStatusId =0))
	AND ((EM.Code = @rCode) OR (@rCode =''))
	AND  ISNULL(EM.IsOtherUser,0) = 0
	AND ((QR.Id = @rApprovalRequestId) OR (@rApprovalRequestId = 0))
	------------------------------------------------------------------------------------------------------------------------------------------------------------------
	UNION
	SELECT
		AA.Id AS ApprovalActionId,
		AA.DocSourceId AS DocSourceId,
		AA.DocSourceTypeId AS DocSourceTypeId,
		WFM.Title AS WorkFlowName,
		WFM.Id AS WorkFlowId,
		PO.Id AS ApprovalRequestId,
		CONVERT(DATE,PO.CreatedDateTime, 103) AS CreatedDateTime,
		95 AS ParticipantSourceTypeId,
		EM.Id AS SourceId,
		EM.Code AS Code ,
		EM.FirstName +' '+ EM.MiddleName +' ' +EM.LastName AS Name ,
		--PR.Remark AS Remark,
		(CASE ISNULL(sm.Id,'') WHEN '' THEN 3 ELSE sm.Id END) AS statusId,
		(CASE ISNULL(sm.title,'') WHEN '' THEN 'Pending' ELSE sm.title END) AS status,
		ISNULL(AA.ActionRemark, '') AS ActionRemark
			
		
	from sPurchase.tPurchaseOrder PO
	INNER JOIN sWf.tWfApprovingAuthority FAA ON 3 = FAA.WfFunctionalityId And FAA.OrgId =@rOrgId
	INNER JOIN sSecurity.tRole R ON R.Id = FAA.AuthoritySourceId AND FAA.AuthoritySourceTypeId = 2015
	LEFT JOIN sWf.tWfApprovalAction AA ON AA.DocSourceId = PO.Id AND AA.WfFunctionalityId = FAA.WfFunctionalityId AND AA.DocSourceTypeId = 2042
	LEFT JOIN sWf.tWfStatusMaster SM ON SM.Id = AA.ActionStatusId
	INNER JOIN sWf.tWfFunctionalityMaster WFM ON WFM.Id = FAA.WfFunctionalityId
	LEFT JOIN  sHrm.tEmployeeMaster  EM ON EM.Id = AA.ActionEmployeeId
	
	WHERE R.Id = @lRoleId
	AND ((WFM.Id = @rWfFunctionalityId) OR (@rWfFunctionalityId =0)) 
	AND ((Convert(Date,PO.CreatedDateTime)>= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
	AND ((Convert(Date,PO.CreatedDateTime) <= @rToDate) OR (ISNULL(@rToDate,'') = ''))
	AND((SM.Id = @rStatusId) OR (@rStatusId =0))
	AND ((EM.Code = @rCode) OR (@rCode = ''))
	AND  ISNULL(EM.IsOtherUser,0) = 0
	AND ((PO.Id = @rApprovalRequestId) OR (@rApprovalRequestId = 0))

	UNION

	SELECT
		AA.Id AS ApprovalActionId,
		AA.DocSourceId AS DocSourceId,
		AA.DocSourceTypeId AS DocSourceTypeId,
		WFM.Title AS WorkFlowName,
		WFM.Id AS WorkFlowId,
		PO.Id AS ApprovalRequestId,
		CONVERT(DATE,PO.CreatedDateTime, 103) AS CreatedDateTime,
		95 AS ParticipantSourceTypeId,
		EM.Id AS SourceId,
		EM.Code AS Code ,
		EM.FirstName +' '+ EM.MiddleName +' ' +EM.LastName AS Name ,
		--PR.Remark AS Remark,
		(CASE ISNULL(sm.Id,'') WHEN '' THEN 3 ELSE sm.Id END) AS statusId,
		(CASE ISNULL(sm.title,'') WHEN '' THEN 'Pending' ELSE sm.title END) AS status,
		ISNULL(AA.ActionRemark, '') AS ActionRemark
			
		
	from sPurchase.tPurchaseOrder PO
	INNER JOIN sWf.tWfApprovingAuthority FAA ON 3 = FAA.WfFunctionalityId And FAA.OrgId =@rOrgId
	INNER JOIN sSecurity.tUser U ON U.Id = FAA.AuthoritySourceId AND FAA.AuthoritySourceTypeId = 1019
	LEFT JOIN sWf.tWfApprovalAction AA ON AA.DocSourceId = PO.Id AND AA.WfFunctionalityId = FAA.WfFunctionalityId AND AA.DocSourceTypeId = 2042
	LEFT JOIN sWf.tWfStatusMaster SM ON SM.Id = AA.ActionStatusId
	INNER JOIN sWf.tWfFunctionalityMaster WFM ON WFM.Id = FAA.WfFunctionalityId
	LEFT JOIN  sHrm.tEmployeeMaster  EM ON EM.Id = AA.ActionEmployeeId
	WHERE U.Id = @rUserId
	AND ((WFM.Id = @rWfFunctionalityId) OR (@rWfFunctionalityId =0)) 
	AND ((Convert(Date,PO.CreatedDateTime)>= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
	AND ((Convert(Date,PO.CreatedDateTime) <= @rToDate) OR (ISNULL(@rToDate,'') = ''))
	AND((SM.Id = @rStatusId) OR (@rStatusId =0))
	AND ((EM.Code = @rCode) OR (@rCode =''))
	AND  ISNULL(EM.IsOtherUser,0) = 0
	AND ((PO.Id = @rApprovalRequestId) OR (@rApprovalRequestId = 0))

	UNION

	SELECT
		AA.Id AS ApprovalActionId,
		AA.DocSourceId AS DocSourceId,
		AA.DocSourceTypeId AS DocSourceTypeId,
		WFM.Title AS WorkFlowName,
		WFM.Id AS WorkFlowId,
		PO.Id AS ApprovalRequestId,
		CONVERT(DATE,PO.CreatedDateTime, 103) AS CreatedDateTime,
		95 AS ParticipantSourceTypeId,
		EM.Id AS SourceId,
		EM.Code AS Code ,
		EM.FirstName +' '+ EM.MiddleName +' ' +EM.LastName AS Name ,
		--PR.Remark AS Remark,
		(CASE ISNULL(sm.Id,'') WHEN '' THEN 3 ELSE sm.Id END) AS statusId,
		(CASE ISNULL(sm.title,'') WHEN '' THEN 'Pending' ELSE sm.title END) AS status,
		ISNULL(AA.ActionRemark, '') AS ActionRemark
			
		
	from sPurchase.tPurchaseOrder PO
	INNER JOIN sWf.tWfFunctionalityMaster WFM ON 3 = WFM.Id
	INNER JOIN sWf.tWfApprovalAction AA ON AA.DocSourceId = PO.Id AND AA.WfFunctionalityId = WFM.Id AND AA.DocSourceTypeId = 2042
	INNER JOIN sWf.tWfHierarchyLevel HL ON HL.WfApprovalActionId = AA.Id
	LEFT JOIN sWf.tWfStatusMaster SM ON SM.Id = AA.ActionStatusId
	LEFT JOIN  sHrm.tEmployeeMaster  EM ON EM.Id = AA.ActionEmployeeId
	WHERE HL.ActionByEmployeeId = @rUserId
	AND ((WFM.Id = @rWfFunctionalityId) OR (@rWfFunctionalityId =0)) 
	AND ((Convert(Date,PO.CreatedDateTime)>= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
	AND ((Convert(Date,PO.CreatedDateTime) <= @rToDate) OR (ISNULL(@rToDate,'') = ''))
	AND((SM.Id = @rStatusId) OR (@rStatusId =0))
	AND ((EM.Code = @rCode) OR (@rCode =''))
	AND  ISNULL(EM.IsOtherUser,0) = 0
	AND ((PO.Id = @rApprovalRequestId) OR (@rApprovalRequestId = 0))

	------------------------------------------------------------------------------------------------------------------------------------------------------------------
	UNION
	SELECT
		AA.Id AS ApprovalActionId,
		AA.DocSourceId AS DocSourceId,
		AA.DocSourceTypeId AS DocSourceTypeId,
		WFM.Title AS WorkFlowName,
		WFM.Id AS WorkFlowId,
		GRN.Id AS ApprovalRequestId,
		CONVERT(DATE,GRN.CreatedDateTime, 103) AS CreatedDateTime,
		95 AS ParticipantSourceTypeId,
		EM.Id AS SourceId,
		EM.Code AS Code ,
		EM.FirstName +' '+ EM.MiddleName +' ' +EM.LastName AS Name ,
		--PR.Remark AS Remark,
		(CASE ISNULL(sm.Id,'') WHEN '' THEN 3 ELSE sm.Id END) AS statusId,
		(CASE ISNULL(sm.title,'') WHEN '' THEN 'Pending' ELSE sm.title END) AS status,
		ISNULL(AA.ActionRemark, '') AS ActionRemark
			
		
	from sPurchase.tGoodsReceivedNote GRN
	INNER JOIN sWf.tWfApprovingAuthority FAA ON 4 = FAA.WfFunctionalityId And FAA.OrgId =@rOrgId
	INNER JOIN sSecurity.tRole R ON R.Id = FAA.AuthoritySourceId AND FAA.AuthoritySourceTypeId = 2015
	LEFT JOIN sWf.tWfApprovalAction AA ON AA.DocSourceId = GRN.Id AND AA.WfFunctionalityId = FAA.WfFunctionalityId AND AA.DocSourceTypeId = 2043
	LEFT JOIN sWf.tWfStatusMaster SM ON SM.Id = AA.ActionStatusId
	INNER JOIN sWf.tWfFunctionalityMaster WFM ON WFM.Id = FAA.WfFunctionalityId
	LEFT JOIN  sHrm.tEmployeeMaster  EM ON EM.Id = AA.ActionEmployeeId
	
	WHERE R.Id = @lRoleId
	AND ((WFM.Id = @rWfFunctionalityId) OR (@rWfFunctionalityId =0)) 
	AND ((Convert(Date,GRN.CreatedDateTime)>= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
	AND ((Convert(Date,GRN.CreatedDateTime) <= @rToDate) OR (ISNULL(@rToDate,'') = ''))
	AND((SM.Id = @rStatusId) OR (@rStatusId =0))
	AND ((EM.Code = @rCode) OR (@rCode = ''))
	AND  ISNULL(EM.IsOtherUser,0) = 0
	AND ((GRN.Id = @rApprovalRequestId) OR (@rApprovalRequestId = 0))

	UNION

	SELECT
		AA.Id AS ApprovalActionId,
		AA.DocSourceId AS DocSourceId,
		AA.DocSourceTypeId AS DocSourceTypeId,
		WFM.Title AS WorkFlowName,
		WFM.Id AS WorkFlowId,
		GRN.Id AS ApprovalRequestId,
		CONVERT(DATE,GRN.CreatedDateTime, 103) AS CreatedDateTime,
		95 AS ParticipantSourceTypeId,
		EM.Id AS SourceId,
		EM.Code AS Code ,
		EM.FirstName +' '+ EM.MiddleName +' ' +EM.LastName AS Name ,
		--AR.Remark AS Remark,
		(CASE ISNULL(sm.Id,'') WHEN '' THEN 3 ELSE sm.Id END) AS statusId,
		(CASE ISNULL(sm.title,'') WHEN '' THEN 'Pending' ELSE sm.title END) AS status,
		ISNULL(AA.ActionRemark, '') AS ActionRemark
			
		
	from sPurchase.tGoodsReceivedNote GRN
	INNER JOIN sWf.tWfApprovingAuthority FAA ON 4 = FAA.WfFunctionalityId And FAA.OrgId =@rOrgId
	INNER JOIN sSecurity.tUser U ON U.Id = FAA.AuthoritySourceId AND FAA.AuthoritySourceTypeId = 1019
	LEFT JOIN sWf.tWfApprovalAction AA ON AA.DocSourceId = GRN.Id AND AA.WfFunctionalityId = FAA.WfFunctionalityId AND AA.DocSourceTypeId = 2043
	LEFT JOIN sWf.tWfStatusMaster SM ON SM.Id = AA.ActionStatusId
	INNER JOIN sWf.tWfFunctionalityMaster WFM ON WFM.Id = FAA.WfFunctionalityId
	LEFT JOIN  sHrm.tEmployeeMaster  EM ON EM.Id = AA.ActionEmployeeId
	WHERE U.Id = @rUserId
	AND ((WFM.Id = @rWfFunctionalityId) OR (@rWfFunctionalityId =0)) 
	AND ((Convert(Date,GRN.CreatedDateTime)>= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
	AND ((Convert(Date,GRN.CreatedDateTime) <= @rToDate) OR (ISNULL(@rToDate,'') = ''))
	AND((SM.Id = @rStatusId) OR (@rStatusId =0))
	AND ((EM.Code = @rCode) OR (@rCode =''))
	AND  ISNULL(EM.IsOtherUser,0) = 0
	AND ((GRN.Id = @rApprovalRequestId) OR (@rApprovalRequestId = 0))

	UNION

	SELECT
		AA.Id AS ApprovalActionId,
		AA.DocSourceId AS DocSourceId,
		AA.DocSourceTypeId AS DocSourceTypeId,
		WFM.Title AS WorkFlowName,
		WFM.Id AS WorkFlowId,
		GRN.Id AS ApprovalRequestId,
		CONVERT(DATE,GRN.CreatedDateTime, 103) AS CreatedDateTime,
		95 AS ParticipantSourceTypeId,
		EM.Id AS SourceId,
		EM.Code AS Code ,
		EM.FirstName +' '+ EM.MiddleName +' ' +EM.LastName AS Name ,
		--AR.Remark AS Remark,
		(CASE ISNULL(sm.Id,'') WHEN '' THEN 3 ELSE sm.Id END) AS statusId,
		(CASE ISNULL(sm.title,'') WHEN '' THEN 'Pending' ELSE sm.title END) AS status,
		ISNULL(AA.ActionRemark, '') AS ActionRemark
			
		
	from sPurchase.tGoodsReceivedNote GRN
	INNER JOIN sWf.tWfFunctionalityMaster WFM ON 4 = WFM.Id
	INNER JOIN sWf.tWfApprovalAction AA ON AA.DocSourceId = GRN.Id AND AA.WfFunctionalityId = WFM.Id AND AA.DocSourceTypeId = 2043
	INNER JOIN sWf.tWfHierarchyLevel HL ON HL.WfApprovalActionId = AA.Id
	LEFT JOIN sWf.tWfStatusMaster SM ON SM.Id = AA.ActionStatusId
	LEFT JOIN  sHrm.tEmployeeMaster  EM ON EM.Id = AA.ActionEmployeeId
	WHERE HL.ActionByEmployeeId = @rUserId
	AND ((WFM.Id = @rWfFunctionalityId) OR (@rWfFunctionalityId =0)) 
	AND ((Convert(Date,GRN.CreatedDateTime)>= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
	AND ((Convert(Date,GRN.CreatedDateTime) <= @rToDate) OR (ISNULL(@rToDate,'') = ''))
	AND((SM.Id = @rStatusId) OR (@rStatusId =0))
	AND ((EM.Code = @rCode) OR (@rCode =''))
	AND  ISNULL(EM.IsOtherUser,0) = 0
	AND ((GRN.Id = @rApprovalRequestId) OR (@rApprovalRequestId = 0))

	------------------------------------------------------------------------------------------------------------------------------------------------------------------
	UNION
	SELECT
		AA.Id AS ApprovalActionId,
		AA.DocSourceId AS DocSourceId,
		AA.DocSourceTypeId AS DocSourceTypeId,
		WFM.Title AS WorkFlowName,
		WFM.Id AS WorkFlowId,
		SR.Id AS ApprovalRequestId,
		CONVERT(DATE,SR.CreatedDateTime, 103) AS CreatedDateTime,
		95 AS ParticipantSourceTypeId,
		EM.Id AS SourceId,
		EM.Code AS Code ,
		EM.FirstName +' '+ EM.MiddleName +' ' +EM.LastName AS Name ,
		--PR.Remark AS Remark,
		(CASE ISNULL(sm.Id,'') WHEN '' THEN 3 ELSE sm.Id END) AS statusId,
		(CASE ISNULL(sm.title,'') WHEN '' THEN 'Pending' ELSE sm.title END) AS status,
		ISNULL(AA.ActionRemark, '') AS ActionRemark
			
		
	from sPurchase.tSalesReturn SR
	INNER JOIN sWf.tWfApprovingAuthority FAA ON 5 = FAA.WfFunctionalityId And FAA.OrgId =@rOrgId
	INNER JOIN sSecurity.tRole R ON R.Id = FAA.AuthoritySourceId AND FAA.AuthoritySourceTypeId = 2015
	LEFT JOIN sWf.tWfApprovalAction AA ON AA.DocSourceId = SR.Id AND AA.WfFunctionalityId = FAA.WfFunctionalityId AND AA.DocSourceTypeId = 2044
	LEFT JOIN sWf.tWfStatusMaster SM ON SM.Id = AA.ActionStatusId
	INNER JOIN sWf.tWfFunctionalityMaster WFM ON WFM.Id = FAA.WfFunctionalityId
	LEFT JOIN  sHrm.tEmployeeMaster  EM ON EM.Id = AA.ActionEmployeeId
	
	WHERE R.Id = @lRoleId
	AND ((WFM.Id = @rWfFunctionalityId) OR (@rWfFunctionalityId =0)) 
	AND ((Convert(Date,SR.CreatedDateTime)>= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
	AND ((Convert(Date,SR.CreatedDateTime) <= @rToDate) OR (ISNULL(@rToDate,'') = ''))
	AND((SM.Id = @rStatusId) OR (@rStatusId =0))
	AND ((EM.Code = @rCode) OR (@rCode = ''))
	AND  ISNULL(EM.IsOtherUser,0) = 0
	AND ((SR.Id = @rApprovalRequestId) OR (@rApprovalRequestId = 0))

	UNION

	SELECT
		AA.Id AS ApprovalActionId,
		AA.DocSourceId AS DocSourceId,
		AA.DocSourceTypeId AS DocSourceTypeId,
		WFM.Title AS WorkFlowName,
		WFM.Id AS WorkFlowId,
		SR.Id AS ApprovalRequestId,
		CONVERT(DATE,SR.CreatedDateTime, 103) AS CreatedDateTime,
		95 AS ParticipantSourceTypeId,
		EM.Id AS SourceId,
		EM.Code AS Code ,
		EM.FirstName +' '+ EM.MiddleName +' ' +EM.LastName AS Name ,
		--AR.Remark AS Remark,
		(CASE ISNULL(sm.Id,'') WHEN '' THEN 3 ELSE sm.Id END) AS statusId,
		(CASE ISNULL(sm.title,'') WHEN '' THEN 'Pending' ELSE sm.title END) AS status,
		ISNULL(AA.ActionRemark, '') AS ActionRemark
			
		
	from sPurchase.tSalesReturn SR
	INNER JOIN sWf.tWfApprovingAuthority FAA ON 4 = FAA.WfFunctionalityId And FAA.OrgId =@rOrgId
	INNER JOIN sSecurity.tUser U ON U.Id = FAA.AuthoritySourceId AND FAA.AuthoritySourceTypeId = 1019
	LEFT JOIN sWf.tWfApprovalAction AA ON AA.DocSourceId = SR.Id AND AA.WfFunctionalityId = FAA.WfFunctionalityId AND AA.DocSourceTypeId = 2043
	LEFT JOIN sWf.tWfStatusMaster SM ON SM.Id = AA.ActionStatusId
	INNER JOIN sWf.tWfFunctionalityMaster WFM ON WFM.Id = FAA.WfFunctionalityId
	LEFT JOIN  sHrm.tEmployeeMaster  EM ON EM.Id = AA.ActionEmployeeId
	WHERE U.Id = @rUserId
	AND ((WFM.Id = @rWfFunctionalityId) OR (@rWfFunctionalityId =0)) 
	AND ((Convert(Date,SR.CreatedDateTime)>= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
	AND ((Convert(Date,SR.CreatedDateTime) <= @rToDate) OR (ISNULL(@rToDate,'') = ''))
	AND((SM.Id = @rStatusId) OR (@rStatusId =0))
	AND ((EM.Code = @rCode) OR (@rCode =''))
	AND  ISNULL(EM.IsOtherUser,0) = 0
	AND ((SR.Id = @rApprovalRequestId) OR (@rApprovalRequestId = 0))

	UNION

	SELECT
		AA.Id AS ApprovalActionId,
		AA.DocSourceId AS DocSourceId,
		AA.DocSourceTypeId AS DocSourceTypeId,
		WFM.Title AS WorkFlowName,
		WFM.Id AS WorkFlowId,
		SR.Id AS ApprovalRequestId,
		CONVERT(DATE,SR.CreatedDateTime, 103) AS CreatedDateTime,
		95 AS ParticipantSourceTypeId,
		EM.Id AS SourceId,
		EM.Code AS Code ,
		EM.FirstName +' '+ EM.MiddleName +' ' +EM.LastName AS Name ,
		--AR.Remark AS Remark,
		(CASE ISNULL(sm.Id,'') WHEN '' THEN 3 ELSE sm.Id END) AS statusId,
		(CASE ISNULL(sm.title,'') WHEN '' THEN 'Pending' ELSE sm.title END) AS status,
		ISNULL(AA.ActionRemark, '') AS ActionRemark
			
		
	from sPurchase.tSalesReturn SR
	INNER JOIN sWf.tWfFunctionalityMaster WFM ON 5 = WFM.Id
	INNER JOIN sWf.tWfApprovalAction AA ON AA.DocSourceId = SR.Id AND AA.WfFunctionalityId = WFM.Id AND AA.DocSourceTypeId = 2044
	INNER JOIN sWf.tWfHierarchyLevel HL ON HL.WfApprovalActionId = AA.Id
	LEFT JOIN sWf.tWfStatusMaster SM ON SM.Id = AA.ActionStatusId
	LEFT JOIN  sHrm.tEmployeeMaster  EM ON EM.Id = AA.ActionEmployeeId
	WHERE HL.ActionByEmployeeId = @rUserId
	AND ((WFM.Id = @rWfFunctionalityId) OR (@rWfFunctionalityId =0)) 
	AND ((Convert(Date,SR.CreatedDateTime)>= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
	AND ((Convert(Date,SR.CreatedDateTime) <= @rToDate) OR (ISNULL(@rToDate,'') = ''))
	AND((SM.Id = @rStatusId) OR (@rStatusId =0))
	AND ((EM.Code = @rCode) OR (@rCode =''))
	AND  ISNULL(EM.IsOtherUser,0) = 0
	AND ((SR.Id = @rApprovalRequestId) OR (@rApprovalRequestId = 0))
END
GO
PRINT N'Altering Procedure [sPurchase].[pGoodsReceivedNoteAdd]...';


GO


ALTER PROCEDURE [sPurchase].[pGoodsReceivedNoteAdd]
		@rId bigint,
		@rPurchaseRequestId bigint,
		@rPurchaseOrderId bigint,
		@rVendorId int,
		@rPODueDate datetime,	
		@rRequestedBy nvarchar(100),
		@rOrgGroupId smallint,
		@rLocationId int,
		@rStatusId smallint,	
		@rBillToAddress nvarchar(1000),
		@rUserId bigint,
		@rDetailList sPurchase.GoodsReceivedNoteDetailType READONLY
 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
	BEGIN TRANSACTION

		If(@rId > 0)
		Begin
			Update sPurchase.tGoodsReceivedNote
			set 
				StatusId = @rStatusId,
				PurchaseRequestId = @rPurchaseRequestId,
				PurchaseOrderId = @rPurchaseOrderId,
				VendorId = @rVendorId,
				PODueDate = @rPODueDate,
				RequestedBy = @rRequestedBy,
				BillToAddress = @rBillToAddress,
				UpdatedUserId = @rUserId,		
				UpdatedDateTime = GetUtcDate()
			where Id = @rId and IsObsolete = 0

			delete from sPurchase.tGoodsReceivedNoteDetail
			where Id not in(select Id from @rDetailList)
			and GoodsReceivedNoteId = @rId

			update sPurchase.tGoodsReceivedNoteDetail
			set
			OrgGroupId = @rOrgGroupId,
			GoodsReceivedNoteId = @rId,
			PurchaseOrderDetailId = DL.PurchaseOrderDetailId,
			StockItemId = DL.StockItemId,
			POQty = DL.POQty,
			ReceivedQty = DL.ReceivedQty,
			PreviousGRNQty = DL.PreviousGRNQty,
			UnitPrice = DL.UnitPrice,
			Remark = DL.Remark,
			UpdatedUserId = @rUserId,
			UpdatedDateTime = GETUTCDATE()
			from @rDetailList DL
			inner join sPurchase.tGoodsReceivedNoteDetail GRN ON DL.ID = GRN.Id
			where GoodsReceivedNoteId = @rId

			DECLARE @lNextNumberGRN BIGINT	 
			EXECUTE [sCommon].[pGetIntMaxIdForOrgGroup] @rOrgGroupId, 'sPurchase.tGoodsReceivedNoteDetail',@lNextNumber = @lNextNumberGRN output
			set @lNextNumberGRN=@lNextNumberGRN-1
			INSERT INTO sPurchase.tGoodsReceivedNoteDetail
			(
				Id,
				OrgGroupId,
				GoodsReceivedNoteId,
				PurchaseOrderDetailId,
				StockItemId,
				POQty,
				ReceivedQty,
				PreviousGRNQty,
				UnitPrice,
				Remark,
				CreatedUserId,
				CreatedDateTime
			)
			select	@lNextNumberGRN+Id,
					@rOrgGroupId,
					@rId,
					PurchaseOrderDetailId,
					StockItemId,
					POQty,
					ReceivedQty,
					PreviousGRNQty,
					UnitPrice,
					Remark,
					@rUserId, 
					GETUTCDATE() 
			from @rDetailList
			where Id not in(Select DL.Id from @rDetailList DL
			inner join sPurchase.tGoodsReceivedNoteDetail GRN ON DL.ID = GRN.Id
			where GRN.GoodsReceivedNoteId = @rId)

			set @lNextNumberGRN=@lNextNumberGRN+(select Count(Id) from @rDetailList where Id not in(Select DL.Id              from @rDetailList DL
			inner join sPurchase.tGoodsReceivedNoteDetail GRN ON DL.ID = GRN.Id
			where GRN.GoodsReceivedNoteId = @rId))
			EXECUTE sCommon.pTableRowIdModify @rOrgGroupId, @rTableTitle = 'sPurchase.tGoodsReceivedNoteDetail', @rCurrentNumber = @lNextNumberGRN

			Select @rId
		End
		Else
		Begin
			DECLARE @lNextNumber INT	 
			EXECUTE [sCommon].[pGetIntMaxIdForOrgGroup] @rOrgGroupId, 'sPurchase.tGoodsReceivedNote',@lNextNumber = @lNextNumber output	
			--------------select @lNextNumber
			--DECLARE @loNextNumber nVarchar(20)
			--EXECUTE sCommon.pPrefixSetupNextNumberGet @rOrgId = @rOrgGroupId, @rPrefixFunctionalityId = 1005,@rStoreLocationId = @rLocationId,
			--------------@rNextNumber = @loNextNumber OUTPUT

	 		INSERT INTO sPurchase.tGoodsReceivedNote
			(
				Id,
				GRNNumber,
				PurchaseRequestId,
				PurchaseOrderId,
				PODueDate,
				RequestedBy, 
				OrgGroupId,
				LocationId, 			 
				StatusId,
				VendorId,
				BillToAddress,
				CreatedUserId,		
				CreatedDateTime
	
			)
			VALUES
			(
				@lNextNumber,
				@lNextNumber,
				@rPurchaseRequestId,
				@rPurchaseOrderId,
				@rPODueDate,
				@rRequestedBy,	 
				@rOrgGroupId,
				@rLocationId, 		 
				@rStatusId,
				@rVendorId,
				@rBillToAddress,
				@rUserId,		
				GETUTCDATE()
			)
 
			set @rId = @lNextNumber  
			
			DECLARE @lNextNumberGRND BIGINT	 
			EXECUTE [sCommon].[pGetIntMaxIdForOrgGroup] @rOrgGroupId, 'sPurchase.tGoodsReceivedNoteDetail',@lNextNumber = @lNextNumberGRND output	
			set @lNextNumberGRND=@lNextNumberGRND-1

	 		INSERT INTO sPurchase.tGoodsReceivedNoteDetail
			(
				Id,
				OrgGroupId,
				GoodsReceivedNoteId,
				PurchaseOrderDetailId,
				StockItemId,
				POQty,
				ReceivedQty,
				PreviousGRNQty,
				UnitPrice,
				Remark,
				CreatedUserId,
				CreatedDateTime
			)
			select	@lNextNumberGRND+Id,
					@rOrgGroupId,
					@rId,
					PurchaseOrderDetailId,
					StockItemId,
					POQty,
					ReceivedQty,
					PreviousGRNQty,
					UnitPrice,
					Remark,
					@rUserId, 
					GETUTCDATE() 
			from @rDetailList
						
			set @lNextNumberGRND=@lNextNumberGRND+(select Count(Id) from @rDetailList)
			EXECUTE sCommon.pTableRowIdModify @rOrgGroupId, @rTableTitle = 'sPurchase.tGoodsReceivedNoteDetail', @rCurrentNumber = @lNextNumberGRND

			select @rId

			Declare @typeId smallint=0
			Declare @Level smallint=0
			SELECT @typeId=WfTypeMasterId, @Level=WfLevel FROM sWf.tWfSetup WHERE WfFunctionalityId = 4
			IF(@typeId = 1)
			BEGIN
				exec [sWf].[pWfApprovalAdd] 0,@rId,2043,@rUserId,1,'',0,0,4,@rOrgGroupId
			END
			ELSE IF(@typeId = 2)
			Begin
				exec [sWf].[pWfApprovalAdd] 0,@rId,2043,@rUserId,2,'',1,@Level,4,@rOrgGroupId
			End
			ELSE IF(@typeId = 3)
			BEGIN
				exec [sWf].[pWfApprovalAdd] 0,@rId,2043,@rUserId,3,'',0,0,4,@rOrgGroupId
			END
			--select 1;
		End
	COMMIT TRAN -- Transaction Success!	
	END TRY

	BEGIN CATCH
    IF @@TRANCOUNT > 0
        ROLLBACK TRAN --RollBack in case of Error

    
    DECLARE @ErrorMessage NVARCHAR(4000);  
    DECLARE @ErrorSeverity INT;  
    DECLARE @ErrorState INT;  

    SELECT   
       @ErrorMessage = ERROR_MESSAGE(),  
       @ErrorSeverity = ERROR_SEVERITY(),  
       @ErrorState = ERROR_STATE();  

    RAISERROR (@ErrorMessage, @ErrorSeverity, @ErrorState);  
    
	END CATCH
END
GO
PRINT N'Altering Procedure [sPurchase].[pPurchaseOrderAdd]...';


GO







ALTER PROCEDURE [sPurchase].[pPurchaseOrderAdd]
		@rId bigint,
		@rPurchaseRequestId bigint,
		@rPODate datetime,	
		@rRequestedBy nvarchar(100),
		@rOrgGroupId smallint,
		@rLocationId int,
		@rStatusId smallint,	
		@rVendorId int,
		@rBillToAddress nvarchar(1000),
		@rShipToAddress nvarchar(1000),	
		@rUserId bigint,
		@rRequiredBy datetime,
		@rDetailList sPurchase.PurchaseOrderDetailType READONLY
 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
	BEGIN TRANSACTION

		If(@rId > 0)
		Begin
			Update sPurchase.tPurchaseOrder
			set 
				StatusId = @rStatusId,
				RequestedBy = @rRequestedBy,
				VendorId = @rVendorId,
				RequiredBy = @rRequiredBy,
				BillToAddress = @rBillToAddress,
				ShipToAddress = @rShipToAddress,
				UpdatedUserId = @rUserId,		
				UpdatedDateTime = GetUtcDate()
			where Id = @rId and IsObsolete = 0

			delete from sPurchase.tPurchaseOrderDetail
			where Id not in(select Id from @rDetailList)
			and PurchaseOrderId = @rId

			update sPurchase.tPurchaseOrderDetail
			set
			OrgGroupId = @rOrgGroupId,
			PurchaseOrderId = @rId,
			PurchaseRequestDetailId = DL.PurchaseRequestDetailId,
			StockItemId = DL.StockItemId,
			TotalQty = DL.TotalQty,
			Remark = DL.Remark,
			UpdatedUserId = @rUserId,
			UpdatedDateTime = GETUTCDATE()
			from @rDetailList DL
			inner join sPurchase.tPurchaseOrderDetail PO ON DL.ID = PO.Id
			where PurchaseOrderId = @rId

			DECLARE @lNextNumberPOD BIGINT	 
			EXECUTE [sCommon].[pGetIntMaxIdForOrgGroup] @rOrgGroupId, 'sPurchase.tPurchaseOrderDetail',@lNextNumber = @lNextNumberPOD output
			set @lNextNumberPOD=@lNextNumberPOD-1
			INSERT INTO sPurchase.tPurchaseOrderDetail
			(
				Id,
				OrgGroupId,
				PurchaseOrderId,
				PurchaseRequestDetailId,
				StockItemId,
				TotalQty,
				Remark,
				CreatedUserId,
				CreatedDateTime
			)
			select	@lNextNumberPOD+Id,
					@rOrgGroupId,
					@rId,
					PurchaseRequestDetailId,
					StockItemId,
					TotalQty,
					Remark, 
					@rUserId, 
					GETUTCDATE() 
			from @rDetailList
			where Id not in(Select DL.Id from @rDetailList DL
			inner join sPurchase.tPurchaseOrderDetail PO ON DL.ID = PO.Id
			where PO.PurchaseOrderId = @rId)
			set @lNextNumberPOD=@lNextNumberPOD+(select Count(Id) from @rDetailList where Id not in(Select DL.Id from @rDetailList DL
			inner join sPurchase.tPurchaseOrderDetail PO ON DL.ID = PO.Id
			where PO.PurchaseOrderId = @rId))
			EXECUTE sCommon.pTableRowIdModify @rOrgGroupId, @rTableTitle = 'sPurchase.tPurchaseOrderDetail', @rCurrentNumber = @lNextNumberPOD

			Select @rId
		End
		Else
		Begin
			DECLARE @lNextNumber INT	 
			EXECUTE [sCommon].[pGetIntMaxIdForOrgGroup] @rOrgGroupId, 'sPurchase.tPurchaseOrder',@lNextNumber = @lNextNumber output	
			---------------select @lNextNumber
			--DECLARE @loNextNumber nVarchar(20)
			--EXECUTE sCommon.pPrefixSetupNextNumberGet @rOrgId = @rOrgGroupId, @rPrefixFunctionalityId = 1005,@rStoreLocationId = @rLocationId,
			---------------@rNextNumber = @loNextNumber OUTPUT

	 		INSERT INTO sPurchase.tPurchaseOrder
			(
				Id,
				RefNumber,
				PurchaseRequestId,
				PODate,
				RequestedBy, 
				OrgGroupId,
				LocationId, 			 
				StatusId,
				VendorId,
				RequiredBy,
				BillToAddress,
				ShipToAddress,
				CreatedUserId,		
				CreatedDateTime
	
			)
			VALUES
			(
				@lNextNumber,
				@lNextNumber,
				@rPurchaseRequestId,
				@rPODate,
				@rRequestedBy,	 
				@rOrgGroupId,
				@rLocationId, 		 
				@rStatusId,
				@rVendorId,
				@rRequiredBy,
				@rBillToAddress,
				@rShipToAddress,
				@rUserId,		
				GETUTCDATE()
			)
 
			set @rId = @lNextNumber  
			
			DECLARE @lNextNumberPO BIGINT	 
			EXECUTE [sCommon].[pGetIntMaxIdForOrgGroup] @rOrgGroupId, 'sPurchase.tPurchaseOrderDetail',@lNextNumber = @lNextNumberPO output	
			set @lNextNumberPO=@lNextNumberPO-1

	 		INSERT INTO sPurchase.tPurchaseOrderDetail
			(
				Id,
				OrgGroupId,
				PurchaseOrderId,
				PurchaseRequestDetailId,
				StockItemId,
				TotalQty,
				Remark,
				CreatedUserId,
				CreatedDateTime
			)
			select	@lNextNumberPO+Id,
					@rOrgGroupId,
					@rId,
					PurchaseRequestDetailId,
					StockItemId,
					TotalQty,
					Remark, 
					@rUserId, 
					GETUTCDATE() 
			from @rDetailList
						
			set @lNextNumberPO=@lNextNumberPO+(select Count(Id) from @rDetailList)
			EXECUTE sCommon.pTableRowIdModify @rOrgGroupId, @rTableTitle = 'sPurchase.tPurchaseOrderDetail', @rCurrentNumber = @lNextNumberPO

			Select @rId

			Declare @typeId smallint=0
			Declare @Level smallint=0
			SELECT @typeId=WfTypeMasterId, @Level=WfLevel FROM sWf.tWfSetup WHERE WfFunctionalityId = 3
			IF(@typeId = 1)--parallel
			BEGIN
				exec [sWf].[pWfApprovalAdd] 0,@rId,2042,@rUserId,1,'',0,0,3,@rOrgGroupId
			END
			ELSE IF(@typeId = 2)--sequencial
			Begin
				exec [sWf].[pWfApprovalAdd] 0,@rId,2042,@rUserId,2,'',1,@Level,3,@rOrgGroupId
			End
			ELSE IF(@typeId = 3)--auto approved
			BEGIN
				exec [sWf].[pWfApprovalAdd] 0,@rId,2042,@rUserId,3,'',0,0,3,@rOrgGroupId
			END
			--select 1;
		End
	COMMIT TRAN -- Transaction Success!	
	END TRY

	BEGIN CATCH
    IF @@TRANCOUNT > 0
        ROLLBACK TRAN --RollBack in case of Error

    
    DECLARE @ErrorMessage NVARCHAR(4000);  
    DECLARE @ErrorSeverity INT;  
    DECLARE @ErrorState INT;  

    SELECT   
       @ErrorMessage = ERROR_MESSAGE(),  
       @ErrorSeverity = ERROR_SEVERITY(),  
       @ErrorState = ERROR_STATE();  

    RAISERROR (@ErrorMessage, @ErrorSeverity, @ErrorState);  
    
	END CATCH
END
GO
PRINT N'Altering Procedure [sPurchase].[pPurchaseRequestAdd]...';


GO


ALTER PROCEDURE [sPurchase].[pPurchaseRequestAdd]
		@rId bigint,
		@rRequestDate datetime,
		@rResourceId bigint,
		@rRequestedBy nvarchar(100),
		@rOrgGroupId smallint,
		@rBranchId int,
		@rLocationId int,
		@rStatusId smallint,	
		@rVendorId int,
		@rUserId bigint,	
		@rRequiredBy datetime,	
		@rDetailList sPurchase.PurchaseRequestDetailType READONLY

 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
	BEGIN TRANSACTION

		If(@rId > 0)
		Begin
			Update sPurchase.tPurchaseRequest
			set 
				StatusId = @rStatusId,
				UpdatedUserId = @rUserId,		
				UpdatedDateTime = GetUtcDate()
			where Id = @rId and IsObsolete = 0

			delete from sPurchase.tPurchaseRequestDetail
			where Id not in(select Id from @rDetailList)
			and PurchaseRequestId = @rId

			update sPurchase.tPurchaseRequestDetail
			set
			OrgGroupId = @rOrgGroupId,
			PurchaseRequestId = @rId,
			StockItemId = DL.StockItemId,
			RequestedQty = DL.RequestedQty,
			Remark = DL.Remark,
			UpdatedUserId = @rUserId,
			UpdatedDateTime = GETUTCDATE()
			from @rDetailList DL
			inner join sPurchase.tPurchaseRequestDetail PR ON DL.ID = PR.Id
			where PR.PurchaseRequestId = @rId

			DECLARE @lNextNumberPRQA BIGINT	 
			EXECUTE [sCommon].[pGetIntMaxIdForOrgGroup] @rOrgGroupId, 'sPurchase.tPurchaseRequestDetail',@lNextNumber = @lNextNumberPRQA output
			set @lNextNumberPRQA=@lNextNumberPRQA-1
			INSERT INTO sPurchase.tPurchaseRequestDetail
			(
				ID,
				OrgGroupId,
				PurchaseRequestId,
				StockItemId,
				RequestedQty,
				Remark,
				CreatedUserId,
				CreatedDateTime
			)
			select	@lNextNumberPRQA+Id,
					@rOrgGroupId,
					@rId, 
					StockItemId,
					RequestedQty,
					Remark, 
					@rUserId, 
					GETUTCDATE() 
			from @rDetailList
			where Id not in(Select DL.Id from @rDetailList DL
			inner join sPurchase.tPurchaseRequestDetail PR ON DL.ID = PR.Id
			where PR.PurchaseRequestId = @rId)
			set @lNextNumberPRQA=@lNextNumberPRQA+(select Count(Id) from @rDetailList where Id not in(Select DL.Id from @rDetailList DL
			inner join sPurchase.tPurchaseRequestDetail PR ON DL.ID = PR.Id
			where PR.PurchaseRequestId = @rId))
			EXECUTE sCommon.pTableRowIdModify @rOrgGroupId, @rTableTitle = 'sPurchase.tPurchaseRequestDetail', @rCurrentNumber = @lNextNumberPRQA

			Select @rId
		End
		Else
		Begin
			DECLARE @lNextNumber INT	 
			EXECUTE [sCommon].[pGetIntMaxIdForOrgGroup] @rOrgGroupId, 'sPurchase.tPurchaseRequest',@lNextNumber = @lNextNumber output	
			--select @lNextNumber
			--DECLARE @loNextNumber nVarchar(20)
			--EXECUTE sCommon.pPrefixSetupNextNumberGet @rOrgId = @rOrgGroupId, @rPrefixFunctionalityId = 1005,@rStoreLocationId = @rLocationId,
			--@rNextNumber = @loNextNumber OUTPUT
	 		INSERT INTO sPurchase.tPurchaseRequest
			(
				Id,
				Number,
				RequestDate,
				ResourceId,
				RequestedBy, 
				OrgGroupId,
				BranchId,
				LocationId, 			 
				StatusId,
				VendorId,
				RequiredBy,
				CreatedUserId,		
				CreatedDateTime
			)
			VALUES
			(
				@lNextNumber,
				@lNextNumber,
				@rRequestDate,
				@rResourceId,
				@rRequestedBy,	 
				@rOrgGroupId,
				@rBranchId,
				@rLocationId, 		 
				@rStatusId,
				@rVendorId,
				@rRequiredBy,
				@rUserId,		
				GETUTCDATE()
			)
 
			set @rId = @lNextNumber  
			DECLARE @lNextNumberPRQ BIGINT	 
			EXECUTE [sCommon].[pGetIntMaxIdForOrgGroup] @rOrgGroupId, 'sPurchase.tPurchaseRequestDetail',@lNextNumber = @lNextNumberPRQ output	
			set @lNextNumberPRQ=@lNextNumberPRQ-1

	 		INSERT INTO sPurchase.tPurchaseRequestDetail
			(
				Id,
				OrgGroupId,
				PurchaseRequestId,
				StockItemId,
				RequestedQty,
				Remark,
				CreatedUserId,
				CreatedDateTime
			)
			select	@lNextNumberPRQ+Id,
					@rOrgGroupId,
					@rId, 
					StockItemId,
					RequestedQty,
					Remark, 
					@rUserId, 
					GETUTCDATE() 
			from @rDetailList
			set @lNextNumberPRQ=@lNextNumberPRQ+(select Count(Id) from @rDetailList)
			EXECUTE sCommon.pTableRowIdModify @rOrgGroupId, @rTableTitle = 'sPurchase.tPurchaseRequestDetail', @rCurrentNumber = @lNextNumberPRQ

			
			select @rId

			Declare @typeId smallint=0
			Declare @Level smallint=0
			SELECT @typeId=WfTypeMasterId, @Level=WfLevel FROM sWf.tWfSetup WHERE WfFunctionalityId = 1
			IF(@typeId = 1)--parallel
			BEGIN
				exec [sWf].[pWfApprovalAdd] 0,@rId,2040,@rUserId,1,'',0,0,1,@rOrgGroupId
			END
			ELSE IF(@typeId = 2)--sequencial
			Begin
				exec [sWf].[pWfApprovalAdd] 0,@rId,2040,@rUserId,2,'',1,@Level,1,@rOrgGroupId
			End
			ELSE IF(@typeId = 3)--auto approved
			BEGIN
				exec [sWf].[pWfApprovalAdd] 0,@rId,2040,@rUserId,3,'',0,0,1,@rOrgGroupId
			END
			
		End
	COMMIT TRAN -- Transaction Success!	
	END TRY

	BEGIN CATCH
    IF @@TRANCOUNT > 0
        ROLLBACK TRAN --RollBack in case of Error

    
    DECLARE @ErrorMessage NVARCHAR(4000);  
    DECLARE @ErrorSeverity INT;  
    DECLARE @ErrorState INT;  

    SELECT   
       @ErrorMessage = ERROR_MESSAGE(),  
       @ErrorSeverity = ERROR_SEVERITY(),  
       @ErrorState = ERROR_STATE();  

    RAISERROR (@ErrorMessage, @ErrorSeverity, @ErrorState);  
    
	END CATCH
END
GO
PRINT N'Altering Procedure [sPurchase].[pSalesReturnAdd]...';


GO




ALTER PROCEDURE [sPurchase].[pSalesReturnAdd]
		@rId bigint,
		@rGoodsReceivedNoteId bigint,
		@rPurchaseOrderId bigint,
		@rVendorId int,
		@rRequestedBy nvarchar(100),
		@rOrgGroupId smallint,
		@rLocationId int,
		@rStatusId smallint,	
		@rUserId bigint,
		@rDetailList sPurchase.SalesReturnDetailType READONLY
 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
	BEGIN TRANSACTION

		If(@rId > 0)
		Begin
			Update sPurchase.tSalesReturn
			set 
				StatusId = @rStatusId,
				GoodsReceivedNoteId = @rGoodsReceivedNoteId,
				RequestedBy = @rRequestedBy,
				PurchaseOrderId = @rPurchaseOrderId,
				VendorId = @rVendorId,
				UpdatedUserId = @rUserId,		
				UpdatedDateTime = GetUtcDate()
			where Id = @rId and IsObsolete = 0

			delete from sPurchase.tSalesReturnDetail
			where Id not in(select Id from @rDetailList)
			and SalesReturnId = @rId

			update sPurchase.tSalesReturnDetail
			set
			OrgGroupId = @rOrgGroupId,
			SalesReturnId = @rId,
			GoodsReceivedNoteDetailId = DL.GoodsReceivedNoteDetailId,
			StockItemId = DL.StockItemId,
			POQty = DL.POQty,
			ReceivedQty = DL.ReceivedQty,
			RejectedQty = DL.RejectedQty,
			CreditNoteIssueDate = DL.CreditNoteIssueDate,
			ReasonForRejection = DL.ReasonForRejection,
			UpdatedUserId = @rUserId,
			UpdatedDateTime = GETUTCDATE()
			from @rDetailList DL
			inner join sPurchase.tSalesReturnDetail SR ON DL.ID = SR.Id
			where SalesReturnId = @rId

			DECLARE @lNextNumberSRD BIGINT	 
			EXECUTE [sCommon].[pGetIntMaxIdForOrgGroup] @rOrgGroupId, 'sPurchase.tSalesReturnDetail',@lNextNumber = @lNextNumberSRD output
			set @lNextNumberSRD=@lNextNumberSRD-1
			INSERT INTO sPurchase.tSalesReturnDetail
			(
				Id,
				OrgGroupId,
				SalesReturnId,
				GoodsReceivedNoteDetailId,
				StockItemId,
				POQty,
				ReceivedQty,
				RejectedQty,
				CreditNoteIssueDate,
				ReasonForRejection,
				CreatedUserId,
				CreatedDateTime
			)
			select	@lNextNumberSRD+Id,
					@rOrgGroupId,
					@rId,
					GoodsReceivedNoteDetailId,
					StockItemId,
					POQty,
					ReceivedQty,
					RejectedQty,
					CreditNoteIssueDate,
					ReasonForRejection,
					@rUserId, 
					GETUTCDATE() 
			from @rDetailList
			where Id not in(Select DL.Id from @rDetailList DL
			inner join sPurchase.tSalesReturnDetail SR ON DL.ID = SR.Id
			where SR.SalesReturnId = @rId)
			set @lNextNumberSRD=@lNextNumberSRD+(select Count(Id) from @rDetailList where Id not in(Select DL.Id from @rDetailList DL
			inner join sPurchase.tSalesReturnDetail SR ON DL.ID = SR.Id
			where SR.SalesReturnId = @rId))
			EXECUTE sCommon.pTableRowIdModify @rOrgGroupId, @rTableTitle = 'sPurchase.tSalesReturnDetail', @rCurrentNumber = @lNextNumberSRD
			
			select @rId
		End
		Else
		Begin
			DECLARE @lNextNumber INT	 
			EXECUTE [sCommon].[pGetIntMaxIdForOrgGroup] @rOrgGroupId, 'sPurchase.tSalesReturn',@lNextNumber = @lNextNumber output	
			-------------select @lNextNumber
			--DECLARE @loNextNumber nVarchar(20)
			--EXECUTE sCommon.pPrefixSetupNextNumberGet @rOrgId = @rOrgGroupId, @rPrefixFunctionalityId = 1005,@rStoreLocationId = @rLocationId,
			------------@rNextNumber = @loNextNumber OUTPUT

	 		INSERT INTO sPurchase.tSalesReturn
			(
				Id,
				SRNumber,
				GoodsReceivedNoteId,
				PurchaseOrderId,
				VendorId,
				RequestedBy, 
				OrgGroupId,
				LocationId, 			 
				StatusId,
				CreatedUserId,		
				CreatedDateTime
	
			)
			VALUES
			(
				@lNextNumber,
				@lNextNumber,
				@rGoodsReceivedNoteId,
				@rPurchaseOrderId,
				@rVendorId,
				@rRequestedBy,	 
				@rOrgGroupId,
				@rLocationId, 		 
				@rStatusId,
				@rUserId,		
				GETUTCDATE()
			)
 
			set @rId = @lNextNumber  
			
			DECLARE @lNextNumberSRDD BIGINT	 
			EXECUTE [sCommon].[pGetIntMaxIdForOrgGroup] @rOrgGroupId, 'sPurchase.tSalesReturnDetail',@lNextNumber = @lNextNumberSRDD output	
			set @lNextNumberSRDD=@lNextNumberSRDD-1

	 		INSERT INTO sPurchase.tSalesReturnDetail
			(
				Id,
				OrgGroupId,
				SalesReturnId,
				GoodsReceivedNoteDetailId,
				StockItemId,
				POQty,
				ReceivedQty,
				RejectedQty,
				CreditNoteIssueDate,
				ReasonForRejection,
				CreatedUserId,
				CreatedDateTime
			)
			select	@lNextNumberSRDD+Id,
					@rOrgGroupId,
					@rId,
					GoodsReceivedNoteDetailId,
					StockItemId,
					POQty,
					ReceivedQty,
					RejectedQty,
					CreditNoteIssueDate,
					ReasonForRejection,
					@rUserId, 
					GETUTCDATE() 
			from @rDetailList
						
			set @lNextNumberSRDD=@lNextNumberSRDD+(select Count(Id) from @rDetailList)
			EXECUTE sCommon.pTableRowIdModify @rOrgGroupId, @rTableTitle = 'sPurchase.tSalesReturnDetail', @rCurrentNumber = @lNextNumberSRDD
			
			select @rId

			Declare @typeId smallint=0
			Declare @Level smallint=0
			SELECT @typeId=WfTypeMasterId, @Level=WfLevel FROM sWf.tWfSetup WHERE WfFunctionalityId = 5
			IF(@typeId = 1)--parallel
			BEGIN
				exec [sWf].[pWfApprovalAdd] 0,@rId,2044,@rUserId,1,'',0,0,5,@rOrgGroupId
			END
			ELSE IF(@typeId = 2)--sequencial
			Begin
				exec [sWf].[pWfApprovalAdd] 0,@rId,2044,@rUserId,2,'',1,@Level,5,@rOrgGroupId
			End
			ELSE IF(@typeId = 3)--auto approved
			BEGIN
				exec [sWf].[pWfApprovalAdd] 0,@rId,2044,@rUserId,3,'',0,0,5,@rOrgGroupId
			END
			--select 1;
		End
	COMMIT TRAN -- Transaction Success!	
	END TRY

	BEGIN CATCH
    IF @@TRANCOUNT > 0
        ROLLBACK TRAN --RollBack in case of Error

    
    DECLARE @ErrorMessage NVARCHAR(4000);  
    DECLARE @ErrorSeverity INT;  
    DECLARE @ErrorState INT;  

    SELECT   
       @ErrorMessage = ERROR_MESSAGE(),  
       @ErrorSeverity = ERROR_SEVERITY(),  
       @ErrorState = ERROR_STATE();  

    RAISERROR (@ErrorMessage, @ErrorSeverity, @ErrorState);  
    
	END CATCH
END
GO
PRINT N'Altering Procedure [sAdmission].[pAdmissionStudentSetupAdd]...';


GO
ALTER PROCEDURE [sAdmission].[pAdmissionStudentSetupAdd]
		 @rAdmissionFormId bigint
		,@rAdmissionSetupId int
		,@rObtainMark decimal(12,2)  -- Changed decimal to decimal(12,2) for mantis 0029297 By Foram
		
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN	
 
 BEGIN TRANSACTION	
  
	 
	 
		--IF Exists(select ObtainMark from sAdmission.tAdmissionSetupStudent where Code=@rCode AND OrgId=@rOrgId)
		--	BEGIN
		--	select -101 as Result
		--	RETURN
		--END 
	
	
		--DECLARE @lNextNumber BIGINT
		--EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sAdmission.tAdmissionCriteriaMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
	IF NOT Exists(Select ObtainMark from sAdmission.tAdmissionSetupStudent where AdmissionFormId=@rAdmissionFormId AND AdmissionSetupId=@rAdmissionSetupId)
	BEGIN
	
	INSERT INTO sAdmission.tAdmissionSetupStudent
		(
			 AdmissionFormId
			 ,AdmissionSetupId
			 ,ObtainMark
			 
		)
	VALUES
		(
			 
			 @rAdmissionFormId
			,@rAdmissionSetupId
			,@rObtainMark
			 
		)
		     SELECT 103 AS Result
	END	 
		
ELSE
	 
	 BEGIN
	 
	 
	    UPDATE  sAdmission.tAdmissionSetupStudent
	    SET 
			-- AdmissionFormId = @rAdmissionFormId
			--,AdmissionSetupId = @rAdmissionSetupId
			--,
			ObtainMark = @rObtainMark
			 
			
	      WHERE AdmissionFormId = @rAdmissionFormId AND AdmissionSetupId=@rAdmissionSetupId
	
		SELECT 104 AS Result
	END
		COMMIT TRANSACTION
		
	--END TRY
	
	--BEGIN CATCH 
	--	ROLLBACK TRANSACTION
	--	SELECT -1 AS Result
	--END CATCH	
		
END
GO
PRINT N'Altering Procedure [sAlert].[pEmployeeBiometricFirstInTimeGet]...';


GO
ALTER PROCEDURE [sAlert].[pEmployeeBiometricFirstInTimeGet]
	@rTemplate nvarchar(max)='',
	@rSubject nvarchar(100)='',
	@rOrgId int,
	@rIntervalTime int=0,
	@rToDateTime dateTime,
	@rFromDateTime DateTime,
	@rEventId int=127
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY	
		BEGIN TRANSACTION 
			--add for 29368 mantis, add @lDateTimeNow and in @lCloudTransactionDataId add CreatedDateTime filter
			declare @lDateTimeNow datetime=[sCommon].[fGetDate]()

			--For Optimization
			declare @lCloudTransactionDataId bigint=0
			set @lCloudTransactionDataId= isnull((select Max(isnull(CloudTransactionDataId,0)) From sBiometric.tTempBiometricAlertData where OrgID =@rOrgId and AlertId=@rEventId and SourceTypeId=95 AND CAST(CreatedDateTime as date)=CAST(@lDateTimeNow as date)),0)

			declare @lSMSTemplete nvarchar(max)='',@lMailTemplete nvarchar(max)='', @lWhatsappTemplete nvarchar(max)='',@lNotificationTemplete nvarchar(max)=''
			set @lMailTemplete=isnull((select isnull(Template,'') from sAlert.tEventTemplate where EventId=@rEventId AND OrgId=@rOrgId and AlertModeId = 1 and IsAutoSend=1),'')
			set @lSMSTemplete =isnull((select isnull(Template,'') from sAlert.tEventTemplate where EventId=@rEventId AND OrgId=@rOrgId and AlertModeId = 2 and IsAutoSend=1),'')
			set @lNotificationTemplete =isnull((select isnull(Template,'') from sAlert.tEventTemplate where EventId=@rEventId AND OrgId=@rOrgId and AlertModeId = 3 and IsAutoSend=1),'')
			set @lWhatsappTemplete =isnull((select isnull(Template,'') from sAlert.tEventTemplate where EventId=@rEventId AND OrgId=@rOrgId and AlertModeId = 4 and IsAutoSend=1),'')
			set @rSubject=isnull((select isnull(MailSubject,'') from sAlert.tEventTemplate where EventId=@rEventId AND OrgId=@rOrgId and AlertModeId = 1 ),'')
			--For Optimization

			if object_id('tempdb..#tTable') is not null
			BEGIN
				DROP TABLE #tTable
			END
			CREATE TABLE #tTable(
					SourceId bigint NOT NULL,
					In_Out_Time [datetime] NOT NULL,
					SourceTypeId int NOT NULL,
					CreatedDateTime [datetime] NOT NULL,
					AutoId bigint not null--For Optimization
				)
			insert into #tTable
			select SourceId,min(In_Out_Time),SourceTypeId,min(CreatedDateTime) 
			,min(Autoid) --For Optimization
			from [sBiometric].[tCloudTransactionData]  
			WHERE Attn_Dt=CONVERT(date,[sCommon].[fGetDate]()) AND SourceTypeId=95 
			--For Optimization
			AND Autoid>@lCloudTransactionDataId
			AND SourceId not in (select ReceiverSourceId From sBiometric.tTempBiometricAlertData where  OrgID =@rOrgId and AlertId=@rEventId and SourceTypeId=95 and cast(CreatedDateTime as date)=CONVERT(date,[sCommon].[fGetDate]()))
			--For Optimization
			Group by SourceId,SourceTypeId
	
			--select * from #tTable
			--For Optimization
			DECLARE @AlertUniqueId uniqueidentifier = NEWID();
			
			Insert Into sBiometric.tTempBiometricAlertData
			SELECT 
				EM.MobileNumber AS MobileNo,	
				EM.CompanyEmail AS EmailId,
				'' AS MsgText,
				@rSubject AS Subject,
				95 AS ReceiverSourceTypeId,
				EM.EmployeeId AS ReceiverSourceId,
				EM.EmployeeName AS StudentName,
				EM.Code AS Code,
				ISNULL(EC.WhatsAppContactNo,'') AS WhatsAppContactNo,
				95 AS SourceTypeId,
				EM.EmployeeId AS SourceId,
				EM.OrgId,
				OM.OrgGroupId,
				ISNULL(Convert(varchar,temp.In_Out_Time,108),'') as Time,
				OM.DisplayTitle AS OrganizationTitle,
				temp.AutoId,
				@rFromDateTime,
				@rToDateTime,
				sCommon.fGetDate(),
				@rEventId,
				@AlertUniqueId
			FROM 
				#tTable temp
				Inner join sHrm.vEmployeeCommonDetail EM ON temp.SourceId=EM.EmployeeId
				LEFT JOIN sHrm.tEmployeeCommunications EC ON EC.EmployeeId = EM.EmployeeId
				INNER JOIN sSetup.tOrganizationMaster OM ON EM.OrgID = OM.Id
			WHERE
				--temp.CreatedDateTime >= DATEADD(minute,-(@rIntervalTime),[sCommon].[fGetDate]())
				--temp.CreatedDateTime < @rToDateTime
				--AND temp.CreatedDateTime >= @rFromDateTime
				--AND 
				EM.OrgID =@rOrgId
				--AND E.EmployeeStatusId = 7  -- Added

			SELECT 
				MobileNo,	
				EmailId,
				replace (
				replace (
				replace (
				replace(@lSMSTemplete,'[EmployeeName]',StudentName),
				'[TimeStamp]',ISNULL(Convert(varchar,Time,108),'')),
				'[PresentTime]',ISNULL(Convert(varchar,Time,108),'')),
				'[PresentDate]',ISNULL(Convert(varchar,[sCommon].[fGetDate](),103),''))
				AS SMSText,
				replace (
				replace (
				replace (
				replace(@lMailTemplete,'[EmployeeName]',StudentName),
				'[TimeStamp]',ISNULL(Convert(varchar,Time,108),'')),
				'[PresentTime]',ISNULL(Convert(varchar,Time,108),'')),
				'[PresentDate]',ISNULL(Convert(varchar,[sCommon].[fGetDate](),103),''))
				AS MailText,
				replace (
				replace (
				replace (
				replace(@lNotificationTemplete,'[EmployeeName]',StudentName),
				'[TimeStamp]',ISNULL(Convert(varchar,Time,108),'')),
				'[PresentTime]',ISNULL(Convert(varchar,Time,108),'')),
				'[PresentDate]',ISNULL(Convert(varchar,[sCommon].[fGetDate](),103),''))
				AS NotificationText,
				replace (
				replace (
				replace (
				replace(@lWhatsappTemplete,'[EmployeeName]',StudentName),
				'[TimeStamp]',ISNULL(Convert(varchar,Time,108),'')),
				'[PresentTime]',ISNULL(Convert(varchar,Time,108),'')),
				'[PresentDate]',ISNULL(Convert(varchar,[sCommon].[fGetDate](),103),''))
				AS WhatsappText,
				Subject,
				ReceiverSourceTypeId,
				ReceiverSourceId,
				StudentName AS EmployeeName,
				Code,
				WhatsAppContactNo,
				SourceTypeId,
				SourceId,
				OrgId,
				OrgGroupId,
				Time,
				OrganizationTitle
			FROM 
				sBiometric.tTempBiometricAlertData
			where 
				AlertUniqueId=@AlertUniqueId

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


END
GO
PRINT N'Altering Procedure [sAlert].[pEmployeeBiometricLateTimeGet]...';


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

	DECLARE @lDay as nvarchar(3)

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

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

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

			declare @lSMSTemplete nvarchar(max)='',@lMailTemplete nvarchar(max)='', @lWhatsappTemplete nvarchar(max)='',@lNotificationTemplete nvarchar(max)=''
			set @lMailTemplete=isnull((select isnull(Template,'') from sAlert.tEventTemplate where EventId=@rEventId AND OrgId=@rOrgId and AlertModeId = 1 and IsAutoSend=1),'')
			set @lSMSTemplete =isnull((select isnull(Template,'') from sAlert.tEventTemplate where EventId=@rEventId AND OrgId=@rOrgId and AlertModeId = 2 and IsAutoSend=1),'')
			set @lNotificationTemplete =isnull((select isnull(Template,'') from sAlert.tEventTemplate where EventId=@rEventId AND OrgId=@rOrgId and AlertModeId = 3 and IsAutoSend=1),'')
			set @lWhatsappTemplete =isnull((select isnull(Template,'') from sAlert.tEventTemplate where EventId=@rEventId AND OrgId=@rOrgId and AlertModeId = 4 and IsAutoSend=1),'')
			set @rSubject=isnull((select isnull(MailSubject,'') from sAlert.tEventTemplate where EventId=@rEventId AND OrgId=@rOrgId and AlertModeId = 1 ),'')
	--IF(@lGetConfigTime <> '' AND LEN(@lGetConfigTime) > 0)
	--BEGIN
	DECLARE @Query NVARCHAR(MAX) = ''
	print (@Query)
	SET @Query = 'SELECT
					EC.MobileNumber AS MobileNo,	
					EC.CompanyEmail AS EmailId,
					replace (
					replace (
					replace('''+CONVERT(nvarchar(MAX),@rTemplate)+''',''[EmployeeName]'',EC.EmployeeName),
					''[LateTime]'','+@lColumnName+'),
					''[LateDate]'',ISNULL(Convert(varchar,[sCommon].[fGetDate](),103),''''))
					 AS MsgText,
					 replace (
					replace (
					replace('''+CONVERT(nvarchar(MAX),@lSMSTemplete)+''',''[EmployeeName]'',EC.EmployeeName),
					''[LateTime]'','+@lColumnName+'),
					''[LateDate]'',ISNULL(Convert(varchar,[sCommon].[fGetDate](),103),''''))
					 AS SMSText,
					 replace (
					replace (
					replace('''+CONVERT(nvarchar(MAX),@lMailTemplete)+''',''[EmployeeName]'',EC.EmployeeName),
					''[LateTime]'','+@lColumnName+'),
					''[LateDate]'',ISNULL(Convert(varchar,[sCommon].[fGetDate](),103),''''))
					 AS MailText,
					 replace (
					replace (
					replace('''+CONVERT(nvarchar(MAX),@lNotificationTemplete)+''',''[EmployeeName]'',EC.EmployeeName),
					''[LateTime]'','+@lColumnName+'),
					''[LateDate]'',ISNULL(Convert(varchar,[sCommon].[fGetDate](),103),''''))
					 AS NotificationText,
					  replace (
					replace (
					replace('''+CONVERT(nvarchar(MAX),@lWhatsappTemplete)+''',''[EmployeeName]'',EC.EmployeeName),
					''[LateTime]'','+@lColumnName+'),
					''[LateDate]'',ISNULL(Convert(varchar,[sCommon].[fGetDate](),103),''''))
					 AS WhatsappText,
					'''+CONVERT(nvarchar(20),@rSubject)+''' AS Subject,
					95 AS ReceiverSourceTypeId,
					EC.EmployeeId AS ReceiverSourceId,
					EC.EmployeeName AS EmployeeName,
					ISNULL(EC1.WhatsAppContactNo,'''') AS WhatsAppContactNo,
					95 AS SourceTypeId,
					EC.EmployeeId AS SourceId,
					EC.OrgId,
					OM.OrgGroupId,
					EM.Id AS EmployeeId,
					EM.Code,
					ISNULL(EM.FirstName, '''') + '' '' + ISNULL(EM.LastName, '''') AS  EmployeeName,
					 '+@lColumnName+' AS Time,
					OM.DisplayTitle AS OrganizationTitle
		FROM 
				sHrm.tEmployeeMaster EM
				Inner join sHrm.vEmployeeCommonDetail EC ON EM.Id=EC.EmployeeId
				LEFT JOIN sHrm.tEmployeeCommunications EC1 ON EC1.EmployeeId = EC.EmployeeId
				INNER JOIN sBiometric.tMonthTrans MT ON MT.EmployeeId = EM.Id AND MT.SourceTypeId = 95 
				INNER JOIN sSetup.tOrganizationMaster OM ON EM.OrgID = OM.Id
				INNER Join sBiometric.tShiftMasterCloud SM ON SM.ShiftName='+CONVERT(nvarchar(20),@lShiftColumntName)+' And (SM.ShiftCode='+CONVERT(nvarchar(20),@rShiftCode)+' OR '+CONVERT(nvarchar(20),@rShiftCode)+'=0)
		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	
				--add for 29339 mantis
				AND YEAR(MT.Attn_dt) = YEAR('''+CONVERT(nvarchar(20),@lDate)+''')'
		print (@Query)
		execute (@Query)	
	--END

END
GO
PRINT N'Altering Procedure [sAlert].[pIssueBookAllGet]...';


GO
ALTER PROCEDURE [sAlert].[pIssueBookAllGet]
	 
	 @rSourceTypeId smallint,
	 @rFromDate date,
	 @rToDate date,
	 @rOrgId smallint,
	 @rBatchId int,
	 @rDepartmentId int = 0,
	 @rClassId int = 0,
	 @rDivisionId int = 0,
	 @rTemplate nvarchar(max),	 	
	 @rMailSubject nvarchar(max)='',
	 @rIsCurrentStatus bit = 0  --MantisId : 0028808
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			
BEGIN 	
		SELECT distinct
			SC.OrgGroupId,
			SC.OrgId,
			SC.AcademicId,
			SC.Code,
			SC.Name AS Name,
			SC.ParentContactNo AS MobileNo,	
			SC.ParentEmail AS EmailId,
			SC.WhatsAppContactNo,
			replace (
			replace (
			replace(@rTemplate,'[Name]',SC.Name),			
			'[BookCode - BookName - IssueDate]',(SELECT STUFF ((SELECT distinct ',' + CHAR(10) +' ' + BM1.Code +' - '+BM1.Title+' - '+ CONVERT(nvarchar(100), BL1.LogDate, 103)
					From sLibrary.tBookLog BL1
					INNER JOIN sLibrary.tBookMaster BM1 ON BM1.Id=BL1.ResourceSourceId
					INNER JOIN sStudent.vStudentCommunication SC1 ON SC1.StudentId = BL1.ReaderSourceId AND SC1.BatchId = BL1.BatchId  AND BL1.ReaderSourceTypeId=2003
					INNER JOIN sSetup.tBatchMaster BMM1 ON BMM1.Id = BL1.BatchId 
					INNER JOIN sSetup.tOrganizationMaster OM1 ON OM1.Id = BL1.OrgId
					INNER JOIN sLibrary.tLibraryMaster LM1 ON LM.Id=BL1.LibraryId
					WHERE
							(BL1.ReaderSourceTypeId=@rSourceTypeId OR @rSourceTypeId=0)
						AND ((BL1.LogDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
						AND ((BL1.LogDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
						AND (BL1.OrgId = @rOrgId)
						AND (BL1.BatchId = @rBatchId)
						AND (BL1.ReaderSourceTypeId != 0)
						AND ((SC1.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
						AND ((SC1.ClassId=@rClassId) OR (@rClassId=0))
						AND ((SC1.DivisionId=@rDivisionId) OR (@rDivisionId=0))
						AND (BL1.IsCurrentStatus=@rIsCurrentStatus OR @rIsCurrentStatus = 0) --MantisId : 0028808
						AND BL1.StatusId = 523
						AND BL1.ReaderSourceId=BL.ReaderSourceId	
						AND (SC.StatusId=1) AND SC.IsBlockAllAlert=0	
                    FOR XML PATH('')),1,1,''))),
			'[LibraryName]',LM.Title)
			 AS Template,
			replace (
			replace (
			replace(@rTemplate,'[Name]',SC.Name),			
			'[BookCode - BookName - IssueDate]',(SELECT STUFF ((SELECT distinct ',' + CHAR(10) + ' ' + BM1.Code +' - '+BM1.Title+' - '+ CONVERT(nvarchar(100), BL1.LogDate, 103)
					From sLibrary.tBookLog BL1
					INNER JOIN sLibrary.tBookMaster BM1 ON BM1.Id=BL1.ResourceSourceId AND BL1.ReaderSourceTypeId=2003
					AND BL1.ReaderSourceId=BL.ReaderSourceId  AND BL1.ReaderSourceId = SC.StudentId AND BL1.BatchId =SC.BatchId  
					AND BMM.Id = BL1.BatchId  AND BL1.OrgId = OM.Id AND  BL1.LibraryId =LM.Id
					AND (SC.StatusId=1) AND SC.IsBlockAllAlert=0
					AND BL1.StatusId = 523
					AND (BL1.IsCurrentStatus=@rIsCurrentStatus OR @rIsCurrentStatus = 0) --MantisId : 0028808		
                    FOR XML PATH('')),1,1,'') )),
			'[LibraryName]',LM.Title)
			 AS MsgText,
			'2003' AS SourceTypeId,
			SC.StudentId AS SourceId,
			@rMailSubject AS Subject,
			2003 AS ReceiverSourceTypeId,
			SC.StudentId AS ReceiverSourceId,
			LM.Title AS LibraryName
	From 
		sLibrary.tBookLog BL
		INNER JOIN sLibrary.tBookMaster BM ON BM.Id=BL.ResourceSourceId
		INNER JOIN sStudent.vStudentCommunication SC ON SC.StudentId = BL.ReaderSourceId AND SC.BatchId = BL.BatchId  AND BL.ReaderSourceTypeId=2003
		INNER JOIN sSetup.tBatchMaster BMM ON BMM.Id = BL.BatchId 
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = BL.OrgId
		INNER JOIN sCommon.tStatusMaster SM ON SM.Id=BL.StatusId
		INNER JOIN sLibrary.tLibraryMaster LM ON LM.Id=BL.LibraryId
	WHERE
		(BL.ReaderSourceTypeId=@rSourceTypeId OR @rSourceTypeId=0)
		AND ((BL.LogDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
		AND ((BL.LogDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
				AND (BL.OrgId = @rOrgId OR @rOrgId=0)
		AND (BL.BatchId = @rBatchId OR @rBatchId = 0)
		AND (BL.ReaderSourceTypeId != 0)
		AND ((SC.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
		AND ((SC.ClassId=@rClassId) OR (@rClassId=0))
		AND ((SC.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		AND (SC.StatusId=1) AND SC.IsBlockAllAlert=0	
		AND BL.StatusId = 523
		AND (BL.IsCurrentStatus=@rIsCurrentStatus OR @rIsCurrentStatus = 0) --MantisId : 0028808

	UNION 

	SELECT distinct
			OM.OrgGroupId,
			EC.OrgId,
			EC.EmployeeId As AcademicId,
			EC.Code,
			EC.EmployeeName AS Name,
			EC.MobileNumber AS MobileNo,	
			EC.CompanyEmail AS EmailId,
			EC.WhatsAppContactNo,
			replace (
			replace (
			replace(@rTemplate,'[Name]',EC.EmployeeName),			
			'[BookCode - BookName - IssueDate]',(SELECT STUFF ((SELECT distinct ',' + CHAR(10) +' ' + BM1.Code +' - '+BM1.Title+' - '+ CONVERT(nvarchar(100), BL1.LogDate, 103)
						From sLibrary.tBookLog BL1
							INNER JOIN sLibrary.tBookMaster BM1 ON BM1.Id=BL1.ResourceSourceId AND BL1.ReaderSourceTypeId=95
							AND BL1.ReaderSourceId=BL.ReaderSourceId  AND BL1.ReaderSourceId = EC.EmployeeId 
							AND BL1.OrgId = OM.Id AND  BL1.LibraryId =LM.Id AND ODM.Id = EC.DepartmentId
							AND ISNULL(EC.IsOtherUser,0) = 0  AND EC.StatusId = 7
							AND (BL1.IsCurrentStatus=@rIsCurrentStatus OR @rIsCurrentStatus = 0) --MantisId : 0028808
							AND BL1.StatusId = 523
                    FOR XML PATH('')),1,1,'') )),
			'[LibraryName]',LM.Title)
			 AS Template,
			replace (
			replace (
			replace(@rTemplate,'[Name]',EC.EmployeeName),			
			'[BookCode - BookName - IssueDate]',(SELECT STUFF ((SELECT distinct ',' + CHAR(10) + ' ' + BM1.Code +' - '+BM1.Title+' - '+ CONVERT(nvarchar(100), BL1.LogDate, 103)
						From sLibrary.tBookLog BL1
							INNER JOIN sLibrary.tBookMaster BM1 ON BM1.Id=BL1.ResourceSourceId AND BL1.ReaderSourceTypeId=95
							AND BL1.ReaderSourceId=BL.ReaderSourceId  AND BL1.ReaderSourceId = EC.EmployeeId 
							AND BL1.OrgId = OM.Id AND  BL1.LibraryId =LM.Id AND ODM.Id = EC.DepartmentId
							AND ISNULL(EC.IsOtherUser,0) = 0  AND EC.StatusId = 7
							AND BL1.StatusId = 523
							AND (BL1.IsCurrentStatus=@rIsCurrentStatus OR @rIsCurrentStatus = 0) --MantisId : 0028808
                    FOR XML PATH('')),1,1,'') )),
			'[LibraryName]',LM.Title)
			 AS MsgText,
			'95' AS SourceTypeId,
			EC.EmployeeId AS SourceId,
			@rMailSubject AS Subject,
			95 AS ReceiverSourceTypeId,
			EC.EmployeeId AS ReceiverSourceId,
			LM.Title AS LibraryName
	         
	FROM 
		sLibrary.tBookLog BL
		INNER JOIN sLibrary.tBookMaster BM ON BM.Id=BL.ResourceSourceId
		INNER JOIN sHrm.vEmployeeCommunication EC ON EC.EmployeeId=BL.ReaderSourceId AND BL.ReaderSourceTypeId=95 
		INNER JOIN sSetup.tDepartmentMaster ODM ON ODM.Id = EC.DepartmentId
		INNER JOIN [sSetup].[tOrganizationMaster] OM ON OM.Id = EC.OrgId
		INNER JOIN sCommon.tStatusMaster SM ON SM.Id=BL.StatusId
		INNER JOIN sLibrary.tLibraryMaster LM ON LM.Id=BL.LibraryId

	WHERE 

		 (BL.OrgId = @rOrgId OR @rOrgId=0)
		AND (BL.BatchId = @rBatchId OR @rBatchId = 0)
		AND ((EC.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
		AND ((BL.LogDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
		AND ((BL.LogDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
		AND (BL.ReaderSourceTypeId=@rSourceTypeId OR @rSourceTypeId=0)
		AND ISNULL(EC.IsOtherUser,0) = 0  AND EC.StatusId = 7	
		AND BL.StatusId = 523
		AND (BL.IsCurrentStatus=@rIsCurrentStatus OR @rIsCurrentStatus = 0) --MantisId : 0028808
		 
END
GO
PRINT N'Altering Procedure [sAlert].[pSMSLogModify]...';


GO
ALTER PROCEDURE [sAlert].[pSMSLogModify]
	
	@rXML nvarchar(max)
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	
BEGIN
--BEGIN TRY
	
--	BEGIN TRANSACTION
	 
	SET @rXML=REPLACE(@rXML,'&','AND')
	DECLARE @lCount INT
	DECLARE @lInterrorCode INT,
			@intDoc INT
	EXECUTE @lInterrorCode = sp_xml_preparedocument @intDoc OUTPUT, @rXML
	
	UPDATE sAlert.tAlertLog
		SET 
			StatusId = ISNULL(SSM.Id,0),
			ResultMessage = ISNULL(SSM.Title,XmlTable.Code)
		FROM OPENXML (@intDoc, '/Table/SMSLog', 2)
				 WITH ( 
						Id bigint,
						Code nvarchar(20),
						VendorId smallint
					  ) XmlTable
			INNER JOIN sAlert.tAlertLog AL ON AL.Id=XmlTable.Id
			LEFT JOIN sAlert.tSMSStatusMaster SSM ON SSM.Code=XmlTable.Code
	

	EXEC sp_xml_removedocument @intDoc
	
		SELECT 1 AS Result
	
	--	COMMIT TRANSACTION
		
	--END TRY
	
	--BEGIN CATCH 
	--	ROLLBACK TRANSACTION
	--	SELECT -1 AS Result
	--END CATCH
END
GO
PRINT N'Altering Procedure [sAlert].[pStudentBiometricFirstInTimeGet]...';


GO
ALTER PROCEDURE [sAlert].[pStudentBiometricFirstInTimeGet]
	@rTemplate nvarchar(max)='',
	@rSubject nvarchar(100)='',
	@rOrgId int,
	@rIntervalTime int=0,
	@rToDateTime dateTime,
	@rFromDateTime DateTime,
	@rEventId int=129

	

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY	
		BEGIN TRANSACTION 
			declare @lDateTimeNow datetime=[sCommon].[fGetDate]()
			declare @lLastStudentFirstInAlertSendTime datetime

			declare @lCloudTransactionDataId bigint=0
			set @lCloudTransactionDataId= isnull((select Max(isnull(CloudTransactionDataId,0)) From sBiometric.tTempBiometricAlertData where  OrgID =@rOrgId and AlertId=@rEventId and SourceTypeId=2003 AND CAST(CreatedDateTime as date)=CAST(@lDateTimeNow as date)),0)
			declare @lSMSTemplete nvarchar(max)='',@lMailTemplete nvarchar(max)='', @lWhatsappTemplete nvarchar(max)='',@lNotificationTemplete nvarchar(max)=''
			set @lMailTemplete=isnull((select isnull(Template,'') from sAlert.tEventTemplate where EventId=@rEventId AND OrgId=@rOrgId and AlertModeId = 1 and IsAutoSend=1),'')
			set @lSMSTemplete =isnull((select isnull(Template,'') from sAlert.tEventTemplate where EventId=@rEventId AND OrgId=@rOrgId and AlertModeId = 2 and IsAutoSend=1),'')
			set @lNotificationTemplete =isnull((select isnull(Template,'') from sAlert.tEventTemplate where EventId=@rEventId AND OrgId=@rOrgId and AlertModeId = 3 and IsAutoSend=1),'')
			set @lWhatsappTemplete =isnull((select isnull(Template,'') from sAlert.tEventTemplate where EventId=@rEventId AND OrgId=@rOrgId and AlertModeId = 4 and IsAutoSend=1),'')
			set @rSubject=isnull((select isnull(MailSubject,'') from sAlert.tEventTemplate where EventId=@rEventId AND OrgId=@rOrgId and AlertModeId = 1 ),'')
		
			if object_id('tempdb..#tTable') is not null
			BEGIN
				DROP TABLE #tTable
			END
			CREATE TABLE #tTable(
				SourceId bigint NOT NULL,
				In_Out_Time [datetime] NOT NULL,
				SourceTypeId int NOT NULL,
				CreatedDateTime [datetime] NOT NULL,
				AutoId bigint not null,

			)
			insert into #tTable
			select CDT.SourceId,min(CDT.In_Out_Time),CDT.SourceTypeId,min(CDT.CreatedDateTime),min(CDT.Autoid)
			from [sBiometric].[tCloudTransactionData] CDT with (nolock) 
			inner join sBiometric.tShiftMasterCloud SMC ON SMC.ShiftCode=CDT.ShiftCode
			WHERE CDT.Attn_Dt=CONVERT(date,@lDateTimeNow)  AND CDT.SourceTypeId=2003
				AND (isnull(SMC.IsStopInTimeAlertTime,0)=0 OR (SMC.IsStopInTimeAlertTime=1 
				--AND CAST(SMC.StopInTimeAlertTime as Time)>=CAST(@rFromDateTime AS Time)
				AND  CAST(SMC.StopInTimeAlertTime as Time)>=CAST(CDT.In_Out_Time AS Time))
				
				)
				AND CDT.Autoid>@lCloudTransactionDataId
				AND CDT.SourceId not in (select ReceiverSourceId From sBiometric.tTempBiometricAlertData where  OrgID =@rOrgId and AlertId=@rEventId and SourceTypeId=2003 AND cast(CreatedDateTime as date)=CONVERT(date,@lDateTimeNow))
			 Group by CDT.SourceId,CDT.SourceTypeId
	
			--select * from #tTable 
			print @lCloudTransactionDataId
			DECLARE @AlertUniqueId uniqueidentifier = NEWID();
			
			Insert Into sBiometric.tTempBiometricAlertData
			SELECT 
				SC.ParentContactNo AS MobileNo,	
				SC.ParentEmail AS EmailId,
				'' as MsgText,
				@rSubject AS Subject,
				2003 AS ReceiverSourceTypeId,
				SC.StudentId AS ReceiverSourceId,
				SC.Name AS StudentName,
				SC.Code AS Code,
				ISNULL(SC.WhatsAppContactNo,'') AS WhatsAppContactNo,
				2003 AS SourceTypeId,
				SC.StudentId AS SourceId,
				SC.OrgId,
				OM.OrgGroupId,
				ISNULL(Convert(varchar,temp.In_Out_Time,108),'') as Time,
				OM.DisplayTitle AS OrganizationTitle,
				temp.AutoId,
				@rFromDateTime,
				@rToDateTime,
				sCommon.fGetDate(),
				@rEventId,
				@AlertUniqueId
			FROM 
				#tTable temp
				Inner join sStudent.vStudentCommunication SC ON temp.SourceId=SC.StudentId AND SC.IsActiveBatch=1
				INNER JOIN sSetup.tOrganizationMaster OM ON SC.OrgID = OM.Id
			WHERE
				--temp.CreatedDateTime < @rToDateTime
				--AND temp.CreatedDateTime >= @rFromDateTime
				--AND 
				SC.OrgID =@rOrgId
				AND SC.StatusId = 1

			SELECT 
				MobileNo AS MobileNo,	
				EmailId AS EmailId,
				replace (
				replace (
				replace (
				replace(@lSMSTemplete,'[StudentName]',StudentName),
				'[TimeStamp]',ISNULL(Convert(varchar,Time,108),'')),
				'[PresentTime]',ISNULL(Convert(varchar,Time,108),'')),
				'[PresentDate]',ISNULL(Convert(varchar,[sCommon].[fGetDate](),103),''))
				 AS SMSText,
				 replace (
				replace (
				replace (
				replace(@lMailTemplete,'[StudentName]',StudentName),
				'[TimeStamp]',ISNULL(Convert(varchar,Time,108),'')),
				'[PresentTime]',ISNULL(Convert(varchar,Time,108),'')),
				'[PresentDate]',ISNULL(Convert(varchar,[sCommon].[fGetDate](),103),''))
				 AS MailText,
				  replace (
				replace (
				replace (
				replace(@lNotificationTemplete,'[StudentName]',StudentName),
				'[TimeStamp]',ISNULL(Convert(varchar,Time,108),'')),
				'[PresentTime]',ISNULL(Convert(varchar,Time,108),'')),
				'[PresentDate]',ISNULL(Convert(varchar,[sCommon].[fGetDate](),103),''))
				 AS NotificationText,
				 replace (
				replace (
				replace (
				replace(@lWhatsappTemplete,'[StudentName]',StudentName),
				'[TimeStamp]',ISNULL(Convert(varchar,Time,108),'')),
				'[PresentTime]',ISNULL(Convert(varchar,Time,108),'')),
				'[PresentDate]',ISNULL(Convert(varchar,[sCommon].[fGetDate](),103),''))
				 AS WhatsappText,
				Subject AS Subject,
				2003 AS ReceiverSourceTypeId,
				ReceiverSourceId AS ReceiverSourceId,
				StudentName AS StudentName,
				Code AS Code,
				WhatsAppContactNo AS WhatsAppContactNo,
				2003 AS SourceTypeId,
				SourceId AS SourceId,
				OrgId,
				OrgGroupId,
				 Time,
				 OrganizationTitle
			FROM 
				sBiometric.tTempBiometricAlertData
			WHERE
			   AlertUniqueId=@AlertUniqueId


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

END
GO
PRINT N'Altering Procedure [sAlert].[pStudentBiometricLateTimeGet]...';


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

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

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

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

	declare @lSMSTemplete nvarchar(max)='',@lMailTemplete nvarchar(max)='', @lWhatsappTemplete nvarchar(max)='',@lNotificationTemplete nvarchar(max)=''
	set @lMailTemplete=isnull((select isnull(Template,'') from sAlert.tEventTemplate where EventId=@rEventId AND OrgId=@rOrgId and AlertModeId = 1 and IsAutoSend=1),'')
	set @lSMSTemplete =isnull((select isnull(Template,'') from sAlert.tEventTemplate where EventId=@rEventId AND OrgId=@rOrgId and AlertModeId = 2 and IsAutoSend=1),'')
	set @lNotificationTemplete =isnull((select isnull(Template,'') from sAlert.tEventTemplate where EventId=@rEventId AND OrgId=@rOrgId and AlertModeId = 3 and IsAutoSend=1),'')
	set @lWhatsappTemplete =isnull((select isnull(Template,'') from sAlert.tEventTemplate where EventId=@rEventId AND OrgId=@rOrgId and AlertModeId = 4 and IsAutoSend=1),'')
	set @rSubject=isnull((select isnull(MailSubject,'') from sAlert.tEventTemplate where EventId=@rEventId AND OrgId=@rOrgId and AlertModeId = 1 ),'')
	--IF(@lGetConfigTime <> '' AND LEN(@lGetConfigTime) > 0)
	--BEGIN
	DECLARE @Query NVARCHAR(MAX) = ''
	SET @Query ='SELECT
					SC.ParentContactNo AS MobileNo,	
					SC.ParentEmail AS EmailId,
					replace (
					replace (
					replace('''+CONVERT(nvarchar(MAX),@rTemplate)+''',''[StudentName]'',sStudent.fStudentNameGet(SM.FirstName, SM.MiddleName, SM.LastName,OM.StudentNameFormatId)),
					''[LateTime]'','+@lColumnName+'),
					''[LateDate]'',ISNULL(Convert(varchar,[sCommon].[fGetDate](),103),''''))
					 AS MsgText,
					 replace (
					replace (
					replace('''+CONVERT(nvarchar(MAX),@lSMSTemplete)+''',''[StudentName]'',sStudent.fStudentNameGet(SM.FirstName, SM.MiddleName, SM.LastName,OM.StudentNameFormatId)),
					''[LateTime]'','+@lColumnName+'),
					''[LateDate]'',ISNULL(Convert(varchar,[sCommon].[fGetDate](),103),''''))
					 AS SMSText,
					 replace (
					replace (
					replace('''+CONVERT(nvarchar(MAX),@lMailTemplete)+''',''[StudentName]'',sStudent.fStudentNameGet(SM.FirstName, SM.MiddleName, SM.LastName,OM.StudentNameFormatId)),
					''[LateTime]'','+@lColumnName+'),
					''[LateDate]'',ISNULL(Convert(varchar,[sCommon].[fGetDate](),103),''''))
					 AS MailText,
					 replace (
					replace (
					replace('''+CONVERT(nvarchar(MAX),@lNotificationTemplete)+''',''[StudentName]'',sStudent.fStudentNameGet(SM.FirstName, SM.MiddleName, SM.LastName,OM.StudentNameFormatId)),
					''[LateTime]'','+@lColumnName+'),
					''[LateDate]'',ISNULL(Convert(varchar,[sCommon].[fGetDate](),103),''''))
					 AS NotificationText,
					 replace (
					replace (
					replace('''+CONVERT(nvarchar(MAX),@lWhatsappTemplete)+''',''[StudentName]'',sStudent.fStudentNameGet(SM.FirstName, SM.MiddleName, SM.LastName,OM.StudentNameFormatId)),
					''[LateTime]'','+@lColumnName+'),
					''[LateDate]'',ISNULL(Convert(varchar,[sCommon].[fGetDate](),103),''''))
					 AS WhatsappText,
					'''+CONVERT(nvarchar(20),@rSubject)+''' AS Subject,
					2003 AS ReceiverSourceTypeId,
					SC.StudentId AS ReceiverSourceId,
					sStudent.fStudentNameGet(SM.FirstName, SM.MiddleName, SM.LastName,OM.StudentNameFormatId) AS StudentName,
					ISNULL(SC.WhatsAppContactNo,'''') AS WhatsAppContactNo,
					2003 AS SourceTypeId,
					SC.StudentId AS SourceId,
					SM.OrgId,
					OM.OrgGroupId,
					SM.Id AS StudentId,
					SM.Code,
					sStudent.fStudentNameGet(SM.FirstName, SM.MiddleName, SM.LastName,OM.StudentNameFormatId) AS  StudentName,
					 '+@lColumnName+' AS Time,
					OM.DisplayTitle AS OrganizationTitle	
		FROM 
				sStudent.tStudentMaster SM
				Inner join sStudent.tStudentCommunication SC ON SM.Id=SC.StudentId
				INNER JOIN sSetup.tOrganizationMaster OM ON SM.OrgID = OM.Id
				INNER JOIN sBiometric.tMonthTrans MT ON MT.EmployeeId = SM.Id AND MT.SourceTypeId = 2003
				INNER Join sBiometric.tShiftMasterCloud SMC ON SMC.ShiftName='+@lShiftColumntName+' And (SMC.ShiftCode='+CONVERT(nvarchar(20),@rShiftCode)+' OR '+CONVERT(nvarchar(20),@rShiftCode)+'=0)
		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
				--add for 29339 mantis
				AND YEAR(MT.Attn_dt) = YEAR('''+CONVERT(nvarchar(20),@lDate)+''')'
				
		print (@Query)
		execute (@Query)			
	--END

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


GO

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

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

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

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

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

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

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

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

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

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


GO

ALTER PROCEDURE [sAssessment].[pRptGraphicalTeacherEvaluationAnalysis2Get]
	 
	 @rBuilder1 nvarchar(max)='', 
	 @rBuilder2 nvarchar(max)='', 
	 @rBatchId int = 0,
	 @rClassId int=0,
	 @rDivisionId int=0,
	 @rExamSubGroupId int,
	 @rOrgId int=0, 
	 @rGroupByid int=0,
	 @rEmployeeId bigint=0
	 		 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN

SELECT 
	@rBuilder1 AS Builder1,
	@rBuilder2 AS Builder2,
	ESGM.Title AS ExamName,
	TSD.EmployeeId,
	EmpM.Code AS EmployeeCode,
	SM.Id AS SubjectId,
	SM.Code AS SubjectCode,
	SM.Title AS SubjectName,
	SM.OrderIndex AS SubjectOrderIndex,
	CS.Id AS ClassSubjectId,
	DM.Id AS DivisionId,
	DM.DisplayTitle AS DivisionName,
	CM.Id AS ClassId,
	CM.DisplayTitle AS ClassName,
	A.Id As AcademicId,
	EM.Id AS ExamId,
	RD.IsPresent,
	RD.Obtain AS SubjectObtain,
	ED.Maximum AS SubjectMaximum,
	CAST(ROUND((ISNULL(RD.Obtain, 0) * 100.0) / ED.Maximum, 2) AS DECIMAL(5,2)) AS SubjectPercentage,
	CASE WHEN @rGroupByid=1 THEN DM.Id
		WHEN @rGroupByid=2 THEN CM.Id
		WHEN @rGroupByid=3 THEN CM.DepartmentId
	    WHEN @rGroupByid=4 THEN OM.Id
		ELSE 0  END  AS HeadId,
	CASE WHEN @rGroupByid=1 THEN 'Division : ' +CM.DisplayTitle+ ' / '+DM.DisplayTitle   
		WHEN @rGroupByid=2 THEN 'Class : ' + CM.DisplayTitle 
		WHEN @rGroupByid=3 THEN 'Department : ' + DP.Title 
		WHEN @rGroupByid=4 THEN  'Organization : '+OM.Title END  AS HeadName,
	CASE WHEN @rGroupByid=1 THEN DM.OrderIndex
		WHEN @rGroupByid=2 THEN CM.OrderIndex
		WHEN @rGroupByid=3 THEN DP.Id
		WHEN @rGroupByid=4 THEN OM.OrderIndex  END AS OrderIndex,
		ED.DisplayOrder 

	FROM 
		sAssessment.tResultDetail RD
		INNER JOIN sAssessment.tResult R ON R.Id = RD.ResultId
		INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId
		INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId 		
		INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId
		INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
		INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=CS.SubjectId					 
		INNER JOIN sStudent.tAcademic A ON A.Id=R.AcademicId			
		INNER JOIN sStudent.tStudentMaster StuM ON StuM.Id=A.StudentId			
		INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId
		INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId
		INNER JOIN sSetup.tOrganizationMaster OM ON StuM.OrgId = OM.Id
		INNER JOIN sSetup.tDepartmentMaster DP ON DP.Id=CM.DepartmentId						
		INNER JOIN sAcademic.tTeacherSubjectDivision TSD ON SM.Id = TSD.SubjectId AND DM.Id = TSD.DivisionId
		INNER JOIN sHrm.tEmployeeMaster EmpM ON TSD.EmployeeId = EmpM.Id AND EmpM.StatusId = 7			
			
	WHERE ESGM.Id = @rExamSubGroupId
		AND ((EM.BatchId = @rBatchId) OR  (@rBatchId = 0))
		AND ((A.ClassId=@rClassId) OR (@rClassId=0)) 
		AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		AND TSD.EmployeeId=@rEmployeeId
END
GO
PRINT N'Altering Procedure [sAttendance].[pAttendanceFollowupListGet]...';


GO
ALTER PROCEDURE [sAttendance].[pAttendanceFollowupListGet]
	 	 
	 	 @rClassId int,
	 	 @rDivisionId int,
	 	 @rAttendanceTypeId tinyint,
		 @rFromDate date,
		 @rToDate date,
	 	 @rBatchId int,
	 	 @rOrgId int,
		 @rPresentStatus int,
		 @rCode nvarchar(20)
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 

	SELECT
	SA.AcademicId, 
	SA.ClassName +'-' + SA.DivisionName AS ClassDivision,
	SA.Code,
	SA.RollNo,
	SA.Name,
	SC.PresentContactNo,
	SC.PermanentContactNo,
	SC.EmergencyContactNo,
	SC.ParentContactNo,
	SC.StudentContactNo,
	AF.Remark,
	AF.AttendanceTypeId AS AttendanceTypeId,
	AF.FollowupDate,
	AF.IsPresent,
	--(Select ISNULL(AF.Remark,'') FROM sAttendance.tAttendanceFollowup AF WHERE SA.AcademicId = AF.AcademicId AND AF.AttendanceTypeId=1 AND (AF.FollowupDate=@rFollowupDate))AS Remark
	--AF.Remark
	(isnull(SC.PresentStreetOne,'')+' '+isnull(SC.PresentStreetTwo,'')+' '+isnull(SC.PresentStreetThree,'')+' '+isnull(SC.PresentCity,'')+' '+isnull(SC.PresentState,'')+' '+isnull(SC.PresentCountry,'')) as PresentAdress		--Mantis: 28987

	FROM
	sStudent.vStudentAcademic SA
	INNER JOIN sStudent.tStudentAdmission AD ON SA.StudentId = AD.StudentId 
	INNER JOIN sAttendance.tAttendanceFollowup AF ON SA.AcademicId = AF.AcademicId
	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.OrgId = @rOrgId)
		  AND (SA.BatchId = @rBatchId)
		  AND (SA.StatusId NOT IN(2,3))
		  AND ((AF.IsPresent = @rPresentStatus) OR (@rPresentStatus= -1))
		  AND (AF.FollowupDate >= @rFromDate) AND (AF.FollowupDate <= @rToDate)
		  AND ((AF.AttendanceTypeId= @rAttendanceTypeId) OR (@rAttendanceTypeId = 0))
		  AND ((SA.Code=@rCode)OR (ISNULL(@rCode,'')=''))
END
GO
PRINT N'Altering Procedure [sAttendance].[pAttendanceSummaryDashboard]...';


GO
ALTER  PROCEDURE [sAttendance].[pAttendanceSummaryDashboard]
	@rType nvarchar(20)='',
	@rOrgId int =0,
	@rAttendanceDate date ='',
	@rClassId int=0,
	@rDepartmentId int =0,
	@rDivisionId int=0
	--@rLibraryId int =0
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON			 
BEGIN 
	IF(@rType = 'AttendanceList')
		BEGIN
			SELECT COUNT(SR.AcademicId)
					,ISNULL((SELECT COUNT(SR.AcademicId)
						FROM sStudent.tAcademic A 
							INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
							INNER JOIN sSetup.tClassMaster CM ON CM.Id = A.ClassId	 
							 AND SR.AttendanceDate = @rAttendanceDate WHERE SR.IsPresent=1 AND ((A.OrgId=@rOrgId)OR(@rOrgId=0))
							 AND ((CM.Id =@rClassId)OR(@rClassId=0))
							AND((CM.DepartmentId = @rDepartmentId)OR(@rDepartmentId=0))),0) AS PresentCount,
					ISNULL((SELECT COUNT(SR.AcademicId)
					FROM sStudent.tAcademic A 
						INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id AND SR.AttendanceDate = @rAttendanceDate
						INNER JOIN sSetup.tClassMaster CM ON CM.Id = A.ClassId	 
						  WHERE SR.IsPresent=0 AND  ((CM.Id =@rClassId)OR(@rClassId=0)) AND ((A.OrgId=@rOrgId)OR(@rOrgId=0))
							AND((CM.DepartmentId = @rDepartmentId)OR(@rDepartmentId=0)) ),0) AS AbsentCount,
				ISNULL((SELECT COUNT(SR.AcademicId)
				FROM  sStudent.tAcademic A 
				INNER JOIN sAttendance.tStudentLeaveRequest SLR ON SLR.AcademicId=A.Id  AND SLR.LeaveFromDate = @rAttendanceDate AND  SLR.LeaveToDate = @rAttendanceDate
				INNER JOIN sSetup.tClassMaster CM ON CM.Id = A.ClassId	 
				WHERE ((CM.Id =@rClassId)OR(@rClassId=0)) AND ((A.OrgId=@rOrgId)OR(@rOrgId=0))
							AND((CM.DepartmentId = @rDepartmentId)OR(@rDepartmentId=0))),0) AS LeaveCount
				FROM sStudent.tAcademic A 
				INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id  AND SR.AttendanceDate = @rAttendanceDate
				INNER JOIN sSetup.tClassMaster CM ON CM.Id = A.ClassId
			WHERE ((A.OrgId=@rOrgId)OR(@rOrgId=0)) AND ((CM.Id =@rClassId)OR(@rClassId=0))
							AND((CM.DepartmentId = @rDepartmentId)OR(@rDepartmentId=0))
		END
	ELSE IF(@rType = 'ClassWiseAttendance')
		BEGIN 
			SELECT CM.Id,CM.Title,ISNULL(T.PresentCount,0) AS PresentCount ,ISNULL(T1.AbsentCount,0) As AbsentCount,CM.OrderIndex
				FROM sSetup.tClassMaster CM
						LEFT JOIN sStudent.tAcademic A ON CM.Id = A.ClassId	
						LEFT JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id  AND SR.AttendanceDate = @rAttendanceDate
						LEFT JOIN 
							(SELECT COUNT(A.Id) AS PresentCount,A.ClassId FROM sStudent.tAcademic A 
							INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id 
							INNER JOIN sSetup.tClassMaster CM ON CM.Id = A.ClassId
							WHERE SR.IsPresent=1 AND  AttendanceDate = @rAttendanceDate
							GROUP BY A.ClassId 
						)T ON T.ClassId = A.ClassId
						
						LEFT JOIN 
							(SELECT COUNT(A.Id) AS AbsentCount,A.ClassId FROM sStudent.tAcademic A 
							INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id 
							INNER JOIN sSetup.tClassMaster CM ON CM.Id = A.ClassId
							WHERE SR.IsPresent=0 AND  AttendanceDate = @rAttendanceDate
							GROUP BY A.ClassId 
						)T1 ON T1.ClassId = A.ClassId 
						--AND T.ClassId = T1.ClassId
			WHERE ((CM.OrgId=@rOrgId)OR (@rOrgId=0))
			AND ((CM.Id =@rClassId)OR(@rClassId=0))
			AND((CM.DepartmentId = @rDepartmentId)OR(@rDepartmentId=0))
				GROUP BY CM.Title, CM.Id,T.PresentCount,T1.AbsentCount,CM.OrderIndex
				ORDER BY CM.OrderIndex
		END
	
	ELSE
		BEGIN
		--create temp table for 29257 mantis
			CREATE TABLE #tempPresentAbsentCount
					(PresentCount int,
					AbsentCount int,
					ClassId int,
					DivisionId int
					)

			INSERT INTO #tempPresentAbsentCount
					(PresentCount,
					AbsentCount,
					ClassId,
					DivisionId
					)
			SELECT COUNT(CASE WHEN SR.IsPresent=1 THEN 1 END),
					COUNT(CASE WHEN SR.IsPresent=0 THEN 1 END),
					A.ClassId,
					A.DivisionId
			FROM sStudent.tAcademic A
				INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
				INNER JOIN sSetup.tClassMaster CM ON CM.Id = A.ClassId
				INNER JOIN sSetup.tDivisionMaster DM ON DM.ClassId =  CM.Id AND DM.Id = A.DivisionId
			WHERE AttendanceDate = @rAttendanceDate
			GROUP BY A.ClassId,A.DivisionId

			SELECT CM.Id,(CM.Title +' - '+ DM.Title) AS  Title ,ISNULL(T.PresentCount,0) AS PresentCount ,ISNULL(T.AbsentCount,0) As AbsentCount,DM.OrderIndex
			FROM sSetup.tClassMaster CM
				INNER JOIN sSetup.tDivisionMaster DM ON DM.ClassId =  CM.Id
				LEFT JOIN sStudent.tAcademic A  ON CM.Id = A.ClassId AND DM.Id = A.DivisionId
				LEFT JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id  AND SR.AttendanceDate = @rAttendanceDate
				--comment for 29257 mantis and also add new left join for temp table, it will done for query time optimization
				--LEFT JOIN
				--	(SELECT COUNT(A.Id) AS PresentCount,A.ClassId,A.DivisionId FROM sStudent.tAcademic A
				--	INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
				--	INNER JOIN sSetup.tClassMaster CM ON CM.Id = A.ClassId
				--	INNER JOIN sSetup.tDivisionMaster DM ON DM.ClassId =  CM.Id AND DM.Id = A.DivisionId
				--	WHERE SR.IsPresent=1 AND  AttendanceDate = @rAttendanceDate
				--	GROUP BY A.ClassId,A.DivisionId
				--)T ON T.ClassId = A.ClassId AND T.DivisionId = A.DivisionId

				--LEFT JOIN
				--	(SELECT COUNT(A.Id) AS AbsentCount,A.ClassId,A.DivisionId FROM sStudent.tAcademic A
				--	INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
				--	INNER JOIN sSetup.tClassMaster CM ON CM.Id = A.ClassId
				--	INNER JOIN sSetup.tDivisionMaster DM ON DM.ClassId =  CM.Id AND DM.Id = A.DivisionId
				--	WHERE SR.IsPresent=0 AND  AttendanceDate = @rAttendanceDate
				--	GROUP BY A.ClassId,A.DivisionId
				--)T1 ON T1.ClassId = A.ClassId AND T1.DivisionId = A.DivisionId
				----AND T.ClassId = T1.ClassId
				LEFT JOIN #tempPresentAbsentCount T ON T.ClassId = A.ClassId AND T.DivisionId = A.DivisionId
			WHERE ((CM.OrgId=@rOrgId)OR (@rOrgId=0))
				AND ((CM.Id =@rClassId)OR(@rClassId=0))
				AND ((DM.Id =@rDivisionId)OR(@rDivisionId=0))
				AND((CM.DepartmentId = @rDepartmentId)OR(@rDepartmentId=0))
			GROUP BY CM.Title, CM.Id,T.PresentCount,T.AbsentCount,DM.OrderIndex,DM.Title
			ORDER BY DM.OrderIndex

			DROP TABLE #tempPresentAbsentCount
		END
END
GO
PRINT N'Altering Procedure [sAttendance].[pDateWiseAttendanceStrengthGet]...';


GO
ALTER PROCEDURE sAttendance.pDateWiseAttendanceStrengthGet
	@rUserId bigint,
	@rMonth smallint,
	@rYear int,
	@rBatchId int,
	@rOrgId int

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

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

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

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

	SELECT DISTINCT DM.Id AS DivisionId
		,CM.Id AS ClassId
		,OM.DisplayTitle + ' - ' + CM.Title + ' - ' + DM.Title AS ClassDivision
	INTO #TempData
	FROM sSetup.tClassMaster CM
	INNER JOIN sSetup.tDivisionMaster DM ON DM.ClassId = CM.Id
	INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = DM.OrgId
	INNER JOIN sSecurity.tUserAccess U ON U.SourceId = DM.Id
	WHERE U.SourceTypeId = 2005
		AND U.UserId = @rUserId

	DECLARE @li INT, @Days INT, @lOrgGroupBatchId int
	SELECT @lOrgGroupBatchId = (SELECT OrgGroupBatchId FROM sSetup.tBatchMaster WHERE Id = @rBatchId)
	SET @li = 1
	SELECT @Days = sCommon.fGetDaysInMonth(@rMonth, @rYear)

	CREATE TABLE #TempDaysTempTable (
		DayPart INT
		,WHDate DATE
		,Value NVARCHAR(20)
		,ClassId INT
		,DivisionId INT
		,ClassDivision NVARCHAR(200)
	)

	WHILE @li <= @Days
	BEGIN
		INSERT INTO #TempDaysTempTable (
			DayPart
			,WHDate
			,Value
			,ClassId
			,DivisionId
			,ClassDivision
		)
		SELECT @li AS DayPart
			,CONVERT(DATE, (CONVERT(NVARCHAR(4), @rYear) + '/' + CONVERT(NVARCHAR(2), @rMonth) + '/' + CONVERT(NVARCHAR(2), @li)))
			,[sAttendance].[fWeekHOffGet](@rYear, @rMonth, @li, @rBatchId, ClassId, DivisionId, '', @rOrgId) AS STATUS
			,ClassId
			,DivisionId
			,ClassDivision
		FROM #TempData

		SET @li = @li + 1
	END

	CREATE TABLE #TempAttendanceData (
		AttendanceDate DATE
		,StudentCount INT
		,AttendanceType SMALLINT
		,DivisionId INT
	)

	INSERT INTO #TempAttendanceData
	SELECT SR.AttendanceDate
		,COUNT(DISTINCT (SR.AcademicId)) AS Present
		,1 -- For Present
		,T.DivisionId
	FROM sAttendance.tStudentRegister SR
	INNER JOIN sStudent.tAcademic A ON SR.AcademicId = A.Id
	INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId
	INNER JOIN sStudent.tStudentMaster SM ON A.StudentId = SM.Id
	INNER JOIN #TempData T ON T.DivisionId = A.DivisionId
		AND T.ClassId = A.ClassId
	WHERE IsPresent = 1
		AND MONTH(SR.AttendanceDate) = @rMonth
		AND BM.OrgGroupBatchId = @lOrgGroupBatchId
		AND AttendanceTypeId = 1
	GROUP BY SR.AttendanceDate
		,T.DivisionId
		,ClassDivision

	INSERT INTO #TempAttendanceData
	SELECT SR.AttendanceDate
		,COUNT(DISTINCT (SR.AcademicId)) AS Absent
		,2 -- For Absent
		,T.DivisionId
	FROM sAttendance.tStudentRegister SR
	INNER JOIN sStudent.tAcademic A ON SR.AcademicId = A.Id
	INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId
	INNER JOIN sStudent.tStudentMaster SM ON A.StudentId = SM.Id
	INNER JOIN #TempData T ON T.DivisionId = A.DivisionId
		AND T.ClassId = A.ClassId
	WHERE IsPresent = 0
		AND MONTH(SR.AttendanceDate) = @rMonth
		AND BM.OrgGroupBatchId = @lOrgGroupBatchId
		AND AttendanceTypeId = 1
	GROUP BY SR.AttendanceDate
		,T.DivisionId
		,ClassDivision

	-- Class Division List
	SELECT *
	FROM #TempData

	-- Attendance and WeekOff/Holiday Data
	
	SELECT AttendanceDate, SUM(Present) AS Present, SUM(Absent) AS Absent, SUM(Present) + SUM(Absent) AS Total, ISNULL(DivisionId, 0) AS DivisionId, ISNULL(ClassDivision, '') AS ClassDivision, MIN(STATUS) AS STATUS FROM 
	(SELECT AttendanceDate
		,SUM(Present) AS Present
		,SUM(Absent) AS Absent
		--,SUM(Present) + SUM(Absent) AS Total
		,T.DivisionId
		,T.ClassDivision
		,T.Value AS STATUS
	FROM (
		SELECT AttendanceDate
			,CASE 
				WHEN AttendanceType = 1
					THEN SUM(StudentCount)
				ELSE 0
				END AS Present
			,CASE 
				WHEN AttendanceType = 2
					THEN SUM(StudentCount)
				ELSE 0
				END AS Absent
			,DivisionId
		FROM #TempAttendanceData
		GROUP BY AttendanceDate
			,AttendanceType
			,StudentCount
			,DivisionId
		) AS A
	LEFT JOIN #TempDaysTempTable T ON T.WHDate = A.AttendanceDate
		AND T.DivisionId = A.DivisionId
	GROUP BY A.AttendanceDate
		,T.DivisionId
		,T.ClassDivision
		,T.Value

	UNION

	SELECT WHDate AS AttendanceDate
		,0 AS Present
		,0 AS Absent
		--,0 AS Total
		,DivisionId
		,ClassDivision
		,Value AS STATUS
	FROM #TempDaysTempTable
	WHERE ISNULL(Value, '') <> '' ) A 
	GROUP BY AttendanceDate, DivisionId, ClassDivision
END
GO
PRINT N'Altering Procedure [sBiometric].[pBiometricEmployeeAttendanceGet]...';


GO
ALTER PROCEDURE [sBiometric].[pBiometricEmployeeAttendanceGet]
	 	 
	 	 @rDepartmentId int=0,
	 	 @rAttendanceDate date='',
	 	 @rCode nvarchar(20)='',
	 	 @rBatchId int=0,
	 	 @rOrgId int=0,
		 @TimeSheetStatusId nvarchar(10) = '0'
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 

Declare @lQuery nvarchar(Max)
DECLARE @strQuery nvarchar(Max)
DECLARE @lDate date
DECLARE @lDay as nvarchar(3)
DECLARE @lMonth as nvarchar(3)
DECLARE @lYear as nvarchar(4)
  BEGIN
	Select @lDay  = RIGHT('00' + CAST(DATEPART(dd,@rAttendanceDate) AS varchar(2)), 2)
	Select @lMonth = RIGHT('00' + CAST(DATEPART(MM,@rAttendanceDate) AS varchar(2)), 2)
	Select @lYear  = RIGHT('0000' + CAST(DATEPART(yyyy,@rAttendanceDate) AS varchar(4)), 4)
	
	
	
		set @strQuery ='Select EM.EmployeeId,EM.Code AS EmployeeCode,EM.EmployeeName,EM.DepartmentName,
			--change for 28927 mantis, add IsPresent column and add tBiometricTypeMaster table join
			Isnull(EAR.IsPresent,case when T1.D'+convert(nvarchar(15),@lDay)+'=''A'' or BTM.MainStatusId = -1 then ''false''
				when T1.D'+convert(nvarchar(15),@lDay)+'=''P'' then ''true''
				Else cast(ISNULL(BTM.MainStatusId,0) as bit) end) as IsPresent,
			ISNULL(EAR.AbsentReasonId,0) as AbsentReasonId,CASE WHEN EAR.UpdatedUserId IS NULL THEN cast(0 as bit) ELSE cast(1 as bit) END AS IsDeleted,
			ISNULL(EAR.AttendanceTagId,0) AS AttendanceTagId,ISNULL(EAR.LeaveTypeId,0) AS LeaveTypeId,ISNULL(EAR.LeavePeriodId,0) AS LeavePeriodId,
			ISNULL(D'+convert(nvarchar(15),@lDay)+'_IN,''00:00'') AS FirstIn,ISNULL(D'+convert(nvarchar(15),@lDay)+'_Out,''00:00'') AS LastOut,ISNULL(D'+convert(nvarchar(15),@lDay)+'_L,''00:00'') AS LateBy,ISNULL(D'+convert(nvarchar(15),@lDay)+'_E,''00:00'') AS EarlyBy, ISNULL(D'+convert(nvarchar(15),@lDay)+'_T,''00:00'') AS Duration,
			ISNULL(D'+convert(nvarchar(15),@lDay)+',''XX'') AS OldPresentStatus,
			CASE When (([sHrm].[fWeekHOffGetBio](EM.EmployeeId, '+convert(nvarchar(15),@lYear)+' ,'+convert(nvarchar(15),@lMonth)+' ,'+convert(nvarchar(15),@lDay)+' ,'+convert(nvarchar(15), @rBatchId)+' ,DepartmentId ,'+convert(nvarchar(15),@rOrgId)+' )=''H'') AND (ISNULL(D'+convert(nvarchar(15),@lDay)+'_IN,''00:00'') !=''00:00''))  then ''PH''
			 When (([sHrm].[fWeekHOffGetBio](EM.EmployeeId , '+convert(nvarchar(15),@lYear)+' ,'+convert(nvarchar(15),@lMonth)+' ,'+convert(nvarchar(15),@lDay)+' ,'+convert(nvarchar(15), @rBatchId)+' ,DepartmentId ,'+convert(nvarchar(15),@rOrgId)+' )=''H'') AND (ISNULL(D'+convert(nvarchar(15),@lDay)+'_IN,''00:00'')=''00:00'')) THEN ''H''  
			 When (([sHrm].[fWeekHOffGetBio](EM.EmployeeId , '+convert(nvarchar(15),@lYear)+' ,'+convert(nvarchar(15),@lMonth)+' ,'+convert(nvarchar(15),@lDay)+' ,'+convert(nvarchar(15), @rBatchId)+' ,DepartmentId ,'+convert(nvarchar(15),@rOrgId)+' )=''W'') AND (ISNULL(D'+convert(nvarchar(15),@lDay)+'_IN,''00:00'') !=''00:00''))  then ''PW''
			 When (([sHrm].[fWeekHOffGetBio](EM.EmployeeId , '+convert(nvarchar(15),@lYear)+' ,'+convert(nvarchar(15),@lMonth)+' ,'+convert(nvarchar(15),@lDay)+' ,'+convert(nvarchar(15), @rBatchId)+' ,DepartmentId ,'+convert(nvarchar(15),@rOrgId)+' )=''W'') AND (ISNULL(D'+convert(nvarchar(15),@lDay)+'_IN,''00:00'') =''00:00''))  then ''W''
			 When ((ISNULL(D'+convert(nvarchar(15),@lDay)+',''XX'')=''W'')AND ([sHrm].[fWeekHOffGetBio](EM.EmployeeId , '+convert(nvarchar(15),@lYear)+' ,'+convert(nvarchar(15),@lMonth)+' ,'+convert(nvarchar(15),@lDay)+' ,'+convert(nvarchar(15), @rBatchId)+' ,DepartmentId ,'+convert(nvarchar(15),@rOrgId)+' )!=''W'') AND (ISNULL(D'+convert(nvarchar(15),@lDay)+'_IN,''00:00'') !=''00:00''))  then ''P''
			 When ((ISNULL(D'+convert(nvarchar(15),@lDay)+',''XX'')=''PW'')AND ([sHrm].[fWeekHOffGetBio](EM.EmployeeId , '+convert(nvarchar(15),@lYear)+' ,'+convert(nvarchar(15),@lMonth)+' ,'+convert(nvarchar(15),@lDay)+' ,'+convert(nvarchar(15), @rBatchId)+' ,DepartmentId ,'+convert(nvarchar(15),@rOrgId)+' )!=''W'') AND (ISNULL(D'+convert(nvarchar(15),@lDay)+'_IN,''00:00'') !=''00:00''))  then ''P''
			 When ((ISNULL(D'+convert(nvarchar(15),@lDay)+',''XX'')=''W'')AND ([sHrm].[fWeekHOffGetBio](EM.EmployeeId , '+convert(nvarchar(15),@lYear)+' ,'+convert(nvarchar(15),@lMonth)+' ,'+convert(nvarchar(15),@lDay)+' ,'+convert(nvarchar(15), @rBatchId)+' ,DepartmentId ,'+convert(nvarchar(15),@rOrgId)+' )!=''W'') AND (ISNULL(D'+convert(nvarchar(15),@lDay)+'_IN,''00:00'') =''00:00''))  then ''A''
			 WHEN ((ISNULL(D'+convert(nvarchar(15),@lDay)+',''XX'')=''W'') AND (ISNULL(D'+convert(nvarchar(15),@lDay)+'_IN,''00:00'') !=''00:00'')) THEN ''PW''
			 When ((ISNULL(D'+convert(nvarchar(15),@lDay)+',''XX'')=''XX'')AND (Cast('''+convert(nvarchar(15),@rAttendanceDate)+''' as date)<GETDATE()) And (cast(EM.DateOfJoining as date)<= Cast('''+convert(nvarchar(15),@rAttendanceDate)+''' as date) OR ISNULL(EM.DateOfJoining,'''')='''')AND (EM.DateOfleaving>= Cast('''+convert(nvarchar(15),@rAttendanceDate)+''' as date) OR ISNULL(EM.DateOfleaving,'''')='''') AND (ISNULL(D'+convert(nvarchar(15),@lDay)+'_IN,''00:00'') =''00:00''))  then ''A''
			 ELSE
			 ISNULL(D'+convert(nvarchar(15),@lDay)+',''XX'') END as PresentStatus
			 From 
		sHrm.vExtEmployeeMaster EM 
		LEFT JOIN sBiometric.tMonthTrans T1 ON EM.EmployeeId = T1.EmployeeId AND (ISNULL(T1.SourceTypeId,95) = 95 OR SourceTypeId = 0) AND ATTN_DT = cast(rtrim(YEAR(''' + convert(nvarchar(15),@rAttendanceDate) + ''') *10000+ Month(''' + convert(nvarchar(15),@rAttendanceDate) + ''') *100+ 01) as datetime)
		LEFT JOIN sHrm.tEmployeeAttendanceRegister EAR ON EAR.EmployeeId=EM.EmployeeId AND EAR.AttendanceDate ='''+convert(nvarchar(15),@rAttendanceDate)+'''  AND (EAR.BatchId ='+convert(nvarchar(15), @rBatchId)+')
		Left JOIN [sSetup].[tOrganizationMaster] OM ON OM.Id =EM.OrgId
		LEFT JOIN sBiometric.tBiometricTypeMaster BTM ON BTM.OrgGroupId=OM.OrgGroupId AND BTM.Status=REPLACE(T1.D'+convert(nvarchar(15),@lDay)+',''PW'',''PH'')
		WHERE 
			 ((EM.DepartmentId='+convert(nvarchar(15),@rDepartmentId)+') OR ('+convert(nvarchar(15),@rDepartmentId)+'=0))
		  AND ((EM.Code like '''+convert(nvarchar(15),@rCode)+''' ) OR (ISNULL('''+convert(nvarchar(15),@rCode)+''','''')=''''))
		  AND (EM.OrgId = '+convert(nvarchar(15),@rOrgId)+')
		  AND ((EM.DateOfleaving >= '''+convert(nvarchar(15),@rAttendanceDate)+''' ) OR ISNULL(EM.DateOfleaving,'''') = '''')
          AND ((EM.DateOfJoining <='''+convert(nvarchar(15),@rAttendanceDate)+''' ) OR ISNULL(EM.DateOfJoining,'''') = '''') 
		  AND (EM.StatusId = 7)
		  AND (EM.IsOtherUser = 0)
		  AND  (( '''+convert(nvarchar(15),@TimeSheetStatusId)+''' = ''1'' AND (ISNULL(D'+convert(nvarchar(15),@lDay)+'_T,''00:00'') < ''09:30'')) OR ( '''+convert(nvarchar(15),@TimeSheetStatusId)+'''  != ''1'' AND ((ISNULL(D'+convert(nvarchar(15),@lDay)+',''XX'') = '''+convert(nvarchar(15),@TimeSheetStatusId)+'''  OR '''+convert(nvarchar(15),@TimeSheetStatusId)+''' =''0''))))
          ORDER BY EM.Number'
	--print @strQuery
	execute (@strQuery )
	--print @strQuery
  END
END
GO
PRINT N'Altering Procedure [sBiometric].[pShiftMasterDelete]...';


GO
 
ALTER PROCEDURE [sBiometric].[pShiftMasterDelete]
	@rShiftcode int,
	@rOrgGroupId int 
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
----
	BEGIN TRY
	 BEGIN TRANSACTION	
	 
  		IF EXISTS( SELECT 1 FROM sHrm.tEmployeeMaster WHERE ShiftId = @rShiftcode)	
		BEGIN
			SELECT 101 AS RESULT
		END	
		ELSE IF EXISTS( SELECT 1 FROM sStudent.tStudentMaster WHERE ShiftId = @rShiftcode)	
		BEGIN
			SELECT -102 AS RESULT
		END	
		ELSE IF EXISTS( SELECT 1 FROM  sBiometric.tShiftAllocationCloud WHERE ShiftCode = @rShiftcode)	
		BEGIN
			SELECT -103 AS RESULT
		END 
		ELSE
		BEGIN

			DELETE FROM sBiometric.tShiftMasterCloud WHERE ShiftCode = @rShiftcode and OrgGroupId = @rOrgGroupId
			SELECT 1 AS RESULT
		END


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


GO

ALTER PROCEDURE [sBiometric].[pTimeSheetListStudentGet]
	@rOrgId int,
	@rFromDate DateTime,  
    @rToDate DateTime, 
	@rStudentId bigint,
	@rClassId int=0,
	@rDivisionId int=0,
	@rStatusId int=0,
	@rBatchId  int
WITH EXECUTE AS CALLER  
AS  
SET NOCOUNT ON  
BEGIN   

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

	
	
	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 @rStudentId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 11) as datetime),D11,D11_IN,D11_OUT,D11_O,D11_L,D11_T,D11_E,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 @rStudentId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 16) as datetime),D16,D16_IN,D16_OUT,D16_O,D16_L,D16_T,D16_E,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 @rStudentId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 19) as datetime),D19,D19_IN,D19_OUT,D19_O,D19_L,D19_T,D19_E,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

	Update TM set PresentStatus = CASE When (([sAttendance].[fWeekHOffGet]( YEAR(Attn_Date) ,MONTH(TM.Attn_Date) ,DAY(TM.Attn_Date) ,SA.BatchID,SA.ClassId,SA.DivisionId ,'' ,SA.OrgId )='H') AND (TM.FirstIn !='00:00'))  then 'PH'
		 When (([sAttendance].[fWeekHOffGet]( YEAR(Attn_Date) ,MONTH(TM.Attn_Date) ,DAY(TM.Attn_Date) ,SA.BatchID,SA.ClassId,SA.DivisionId ,'' ,SA.OrgId )='H') AND (TM.FirstIn='00:00')) THEN 'H'  
		 When (([sAttendance].[fWeekHOffGet]( YEAR(Attn_Date) ,MONTH(TM.Attn_Date) ,DAY(TM.Attn_Date) ,SA.BatchID,SA.ClassId,SA.DivisionId ,'' ,SA.OrgId )='W') AND (TM.FirstIn !='00:00'))  then 'PW'
		 When (([sAttendance].[fWeekHOffGet]( YEAR(Attn_Date) ,MONTH(TM.Attn_Date) ,DAY(TM.Attn_Date) ,SA.BatchID,SA.ClassId,SA.DivisionId ,'' ,SA.OrgId )='W') AND (TM.FirstIn ='00:00'))  then 'W'
		 When ((TM.PresentStatus='W')AND ([sAttendance].[fWeekHOffGet]( YEAR(Attn_Date) ,MONTH(TM.Attn_Date) ,DAY(TM.Attn_Date) ,SA.BatchID,SA.ClassId,SA.DivisionId ,'' ,SA.OrgId )!='W') AND (TM.FirstIn !='00:00'))  then 'P'
		 When ((TM.PresentStatus='PW')AND ([sAttendance].[fWeekHOffGet]( YEAR(Attn_Date) ,MONTH(TM.Attn_Date) ,DAY(TM.Attn_Date) ,SA.BatchID,SA.ClassId,SA.DivisionId ,'' ,SA.OrgId )!='W') AND (TM.FirstIn !='00:00'))  then 'P'
		 When ((TM.PresentStatus='W')AND ([sAttendance].[fWeekHOffGet]( YEAR(Attn_Date) ,MONTH(TM.Attn_Date) ,DAY(TM.Attn_Date) ,SA.BatchID,SA.ClassId,SA.DivisionId ,'' ,SA.OrgId )!='W') AND (TM.FirstIn ='00:00'))  then 'A'
		 WHEN ((TM.PresentStatus='W') AND (TM.FirstIn !='00:00')) THEN 'PW' 
		 --When ((TM.PresentStatus='XX')AND (Cast(TM.Attn_Date as date)<GETDATE()) And (cast(AD.AdmissionDate as date)<= Cast(TM.Attn_Date as date) OR ISNULL(AD.AdmissionDate,'')='')AND (AD.LeftDate>= Cast(TM.Attn_Date as date) OR ISNULL(AD.LeftDate,'')='') AND (TM.FirstIn ='00:00'))  then 'A'
		 ELSE TM.PresentStatus END
		From #TempMonthTrans TM
		INNER JOIN sStudent.vStudentAcademic SA  ON SA.StudentId = TM.EmployeeId 
		--INNER JOIN sStudent.tStudentAdmission AD ON SA.StudentId = AD.StudentId

--select * from #TempMonthTrans 
	Select 
		SA.AcademicId AS AcademicId,
		SA.StudentId AS StudentId,
		TM.Attn_Date AS  Attn_Date,
		TM.FirstIn,
		TM.LastOut,
		TM.OverTime,
		TM.LateBy,
		TM.Duration,
		TM.EarlyBy,
		TM.ShiftName,
		TM.PresentStatus as PresentStatus,
		SA.Code AS StudentCode,
		SA.Name AS StudentName,
		ISNULL(SA.RollNo,0) as RollNo,
		--(SELECT COUNT(Id) FROM #TempMonthTrans WHERE EmployeeId=MT.EmployeeId AND PresentStatus='A') AS TotalAbsentDays,
		--(SELECT COUNT(Id) FROM #TempMonthTrans WHERE EmployeeId=MT.EmployeeId AND PresentStatus='W') AS TotalWeekOffs,
		--(SELECT COUNT(Id) FROM #TempMonthTrans WHERE EmployeeId=MT.EmployeeId AND PresentStatus='H') AS TotalHolidays,
		--(SELECT COUNT(Id) FROM #TempMonthTrans WHERE EmployeeId=MT.EmployeeId AND (PresentStatus='P' OR PresentStatus='PW')) AS TotalPresentDays,
		--(SELECT COUNT(Id) FROM #TempMonthTrans WHERE EmployeeId=MT.EmployeeId AND PresentStatus='HD') AS TotalHalfDays,
		--(SELECT COUNT(Id) FROM #TempMonthTrans WHERE EmployeeId=MT.EmployeeId AND PresentStatus='LH') AS TotalLessHours,
		--(SELECT COUNT(Id) FROM #TempMonthTrans WHERE EmployeeId=MT.EmployeeId AND PresentStatus='E') AS TotalErrorCase,
		 OM.DisplayTitle AS Organization,
		CM.DisplayTitle AS ClassName,
		CM.Id AS ClassId,
		DM.DisplayTitle AS DivisionName,
		DM.Id AS DivisionId,
		Dept.DisplayTitle AS Department,
		Dept.Id AS DepartmentId,
		CM.Title+'-'+DM.DisplayTitle As ClassDivision,
		Dept.OrderIndex AS OrderIndex,
		DM.OrderIndex AS DivisionOrderIndex,
		SA.OrgId AS OrgId--,
		--DAY(DATEADD(MONTH, @rForMonth, DATEADD(YEAR, @rForYear - 1900, -1))) AS TotalDays
				
		 From #TempMonthTrans TM   
	 INNER JOIN sBiometric.tMonthTrans MT ON MT.EmployeeId=TM.EmployeeId AND SourceTypeId = 2003 
	 INNER JOIN sStudent.vStudentAcademic SA  ON SA.StudentId = MT.EmployeeId AND MT.SourceTypeId=2003 
	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
	
	WHERE 
			SA.OrgId=@rOrgId 
			AND	((SA.ClassId=@rClassId) OR (@rClassId=0))
			AND ((SA.DivisionId=@rDivisionId) OR (@rDivisionId=0))
			AND (SA.StudentId=@rStudentId OR @rStudentId=0)
			AND ( (SA.StatusId =  @rStatusId) OR @rStatusId=0)
			AND (AD.LeftDate > @rFromDate OR ISNULL(AD.LeftDate,'')= '')
			AND (AD.AdmissionDate <= @rToDate)
			AND SA.BatchId = @rBatchId
			 AND MT.Attn_dt=cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime)
			 
	ORDER BY SA.RollNo



	DROP Table #TempMonthTrans	
END
GO
PRINT N'Altering Procedure [sCertificate].[pRptLeavingCertificateGet]...';


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

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

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


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

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


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

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


GO
ALTER PROCEDURE [sCommunication].[pDailyThoughtGet]

	@rOrgId int,
	@rSourceId bigint = 0,
	@rSourceTypeId int = 0

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
	DECLARE @lDay smallint , @lMonth smallint
	DECLARE @lOrgGroupId Int
	DECLARE @lDailyThoughtId nvarchar(100)
	DECLARE @lFinalDailyThoughtId nvarchar(100) = ''

	SET @lDay = DAY(sCommon.fGetDate())
	SET @lMonth = MONTH(sCommon.fGetDate())
	SELECT @lOrgGroupId = OrgGroupId FROM sSetup.tOrganizationMaster WHERE Id = @rOrgId

	IF(@rSourceTypeId = 2001)
	BEGIN
		DECLARE @lClassId int,@lDivisionId int,@lOrgId int

		SELECT @lClassId = A.ClassId, @lDivisionId = A.DivisionId, @lOrgId= A.OrgId
		 FROM sStudent.tAcademic A 
		 WHERE A.Id = @rSourceId  

		 IF EXISTS (SELECT 1 FROM sCommunication.tDailyThoughtAssign WHERE OrgId = @rOrgId AND Day = @lDay AND Month = @lMonth AND SourceTypeId = 2005 AND SourceId = @lDivisionId)
			BEGIN --Check If DailyThought Assign to particular day
				SELECT 
					DTM.Id,
					DTM.Number,
					DTM.Title,
					DTM.Remark,
					DTS.Title As [Subject]
				FROM
					sCommunication.tDailyThoughtAssign DTA
					INNER JOIN sCommunication.tDailyThoughtMaster DTM ON DTM.Id IN (SELECT item FROM [sCommon].[fnSplit](DTA.DailyThoughtId, ','))
					INNER JOIN sCommunication.tDailyThoughtSubjectMaster DTS ON DTM.DailyThoughtSubjectId = DTS.Id
				WHERE
					DTA.OrgId = @rOrgId AND DTA.Day = @lDay AND DTA.Month = @lMonth AND SourceTypeId = 2005 AND SourceId = @lDivisionId

				SELECT @lFinalDailyThoughtId = DailyThoughtId FROM sCommunication.tDailyThoughtAssign WHERE OrgId = @rOrgId AND Day = @lDay AND Month = @lMonth AND SourceTypeId = 2005 AND SourceId = @lDivisionId
			END
		ELSE IF EXISTS (SELECT 1 FROM sCommunication.tDailyThoughtAssign WHERE OrgId = @rOrgId AND Day = @lDay AND Month = @lMonth AND SourceTypeId = 2016 AND SourceId = @lClassId)
			BEGIN --Check If DailyThought Assign to particular day
					SELECT 
						DTM.Id,
						DTM.Number,
						DTM.Title,
						DTM.Remark,
						DTS.Title As [Subject]
					FROM
						sCommunication.tDailyThoughtAssign DTA
						INNER JOIN sCommunication.tDailyThoughtMaster DTM ON DTM.Id IN (SELECT item FROM [sCommon].[fnSplit](DTA.DailyThoughtId, ','))
						INNER JOIN sCommunication.tDailyThoughtSubjectMaster DTS ON DTM.DailyThoughtSubjectId = DTS.Id
					WHERE
						DTA.OrgId = @rOrgId AND DTA.Day = @lDay AND DTA.Month = @lMonth AND SourceTypeId = 2016 AND SourceId = @lClassId

					SELECT @lFinalDailyThoughtId = DailyThoughtId FROM sCommunication.tDailyThoughtAssign WHERE OrgId = @rOrgId AND Day = @lDay AND Month = @lMonth AND SourceTypeId = 2016 AND SourceId = @lClassId
				END
		ELSE IF EXISTS (SELECT 1 FROM sCommunication.tDailyThoughtAssign WHERE OrgId = @rOrgId AND Day = @lDay AND Month = @lMonth AND (SourceTypeId = 2021 AND SourceId = @lOrgId))
			BEGIN --Check If DailyThought Assign to particular day

					SELECT 
						DTM.Id,
						DTM.Number,
						DTM.Title,
						DTM.Remark,
						DTS.Title As [Subject]
					FROM
						sCommunication.tDailyThoughtAssign DTA
						INNER JOIN sCommunication.tDailyThoughtMaster DTM ON DTM.Id IN (SELECT item FROM [sCommon].[fnSplit](DTA.DailyThoughtId, ','))
						INNER JOIN sCommunication.tDailyThoughtSubjectMaster DTS ON DTM.DailyThoughtSubjectId = DTS.Id
					WHERE
						DTA.OrgId = @rOrgId AND DTA.Day = @lDay AND DTA.Month = @lMonth AND (SourceTypeId = 2021 AND SourceId = @lOrgId)

					SELECT @lFinalDailyThoughtId = DailyThoughtId FROM sCommunication.tDailyThoughtAssign WHERE OrgId = @rOrgId AND Day = @lDay AND Month = @lMonth AND (SourceTypeId = 2021 AND SourceId = @lOrgId)
			END
	END
	
	IF(@rSourceTypeId = 95)
	BEGIN
			IF EXISTS (SELECT 1 FROM sCommunication.tDailyThoughtAssign WHERE OrgId = @rOrgId AND Day = @lDay AND Month = @lMonth AND ((SourceTypeId = 2021 AND SourceId = @rOrgId) OR (ISNULL(SourceId,0)=0 AND ISNULL(SourceTypeId,0) = 0)))
			BEGIN --Check If DailyThought Assign to particular day
				SELECT 
					DTM.Id,
					DTM.Number,
					DTM.Title,
					DTM.Remark,
					DTS.Title As [Subject]
				FROM
					sCommunication.tDailyThoughtAssign DTA
					INNER JOIN sCommunication.tDailyThoughtMaster DTM ON DTM.Id IN (SELECT item FROM [sCommon].[fnSplit](DTA.DailyThoughtId, ','))
					INNER JOIN sCommunication.tDailyThoughtSubjectMaster DTS ON DTM.DailyThoughtSubjectId = DTS.Id
				WHERE
					DTA.OrgId = @rOrgId AND DTA.Day = @lDay AND DTA.Month = @lMonth AND ((SourceTypeId = 2021 AND SourceId = @rOrgId) OR (ISNULL(SourceId,0)=0 AND ISNULL(SourceTypeId,0) = 0))

				SELECT @lFinalDailyThoughtId = DailyThoughtId FROM sCommunication.tDailyThoughtAssign WHERE OrgId = @rOrgId AND Day = @lDay AND Month = @lMonth AND ((SourceTypeId = 2021 AND SourceId = @rOrgId) OR (ISNULL(SourceId,0)=0 AND ISNULL(SourceTypeId,0) = 0))



			END
	END
	 
	IF(@lFinalDailyThoughtId = '')
	BEGIN 
		IF EXISTS (SELECT 1 FROM sCommunication.tDailyThoughtAssign WHERE OrgId = @rOrgId AND Day = @lDay AND Month = @lMonth AND ((SourceTypeId = 2021 AND SourceId = @rOrgId) OR (ISNULL(SourceId,0)=0 AND ISNULL(SourceTypeId,0) = 0)))
			BEGIN --Check If DailyThought Assign to particular day
			     
				SELECT 
					DTM.Id,
					DTM.Number,
					DTM.Title,
					DTM.Remark,
					DTS.Title As [Subject]
				FROM
					sCommunication.tDailyThoughtAssign DTA
					INNER JOIN sCommunication.tDailyThoughtMaster DTM ON DTM.Id IN (SELECT item FROM [sCommon].[fnSplit](DTA.DailyThoughtId, ','))
					INNER JOIN sCommunication.tDailyThoughtSubjectMaster DTS ON DTM.DailyThoughtSubjectId = DTS.Id
				WHERE
					DTA.OrgId = @rOrgId AND DTA.Day = @lDay AND DTA.Month = @lMonth AND ((SourceTypeId = 2021 AND SourceId = @rOrgId) OR (ISNULL(SourceId,0)=0 AND ISNULL(SourceTypeId,0) = 0))

				SELECT @lFinalDailyThoughtId = DailyThoughtId FROM sCommunication.tDailyThoughtAssign WHERE OrgId = @rOrgId AND Day = @lDay AND Month = @lMonth AND ((SourceTypeId = 2021 AND SourceId = @rOrgId) OR (ISNULL(SourceId,0)=0 AND ISNULL(SourceTypeId,0) = 0))

			END
		--Added for mantis 0029003: 3rd point by Foram (Reason: If Daily Thought Master is not there then no need it in temp table also)
		--ELSE IF EXISTS (SELECT 1 FROM sCommunication.tDailyThoughtTemp WHERE CONVERT(NVARCHAR,CreatedDateTime,105) = CONVERT(NVARCHAR,sCommon.fGetDate(),105) AND OrgGroupId = @lOrgGroupId)
		--BEGIN --If DailyThought loaded in temp table for particular day 
		--	SELECT 
		--		DTM.Id,
		--		DTM.Number,
		--		DTM.Title,
		--		DTM.Remark,
		--		DTS.Title As [Subject]
		--	FROM
		--		sCommunication.tDailyThoughtTemp DTM 
		--		INNER JOIN sCommunication.tDailyThoughtSubjectMaster DTS ON DTM.DailyThoughtSubjectId = DTS.Id
		--		INNER JOIN sSetup.tOrganizationMaster OM ON OM.OrgGroupId = DTM.OrgGroupId
		--		INNER JOIN sCommunication.tDailyThoughtMaster DM ON DM.Id = DTM.Id   -- Added Join for mantis 0029003: 3rd point by Foram
		--	WHERE
		--		OM.Id = @rOrgId

		--	-- Added for mantis 0029003: 3rd point by Foram (Reason: If Daily Thought Master is not there then no need it in temp table also)
		--	DELETE DTM 
		--	FROM
		--		sCommunication.tDailyThoughtTemp DTM 
		--		INNER JOIN sCommunication.tDailyThoughtSubjectMaster DTS ON DTM.DailyThoughtSubjectId = DTS.Id
		--		INNER JOIN sSetup.tOrganizationMaster OM ON OM.OrgGroupId = DTM.OrgGroupId
		--		LEFT JOIN sCommunication.tDailyThoughtMaster DM ON DM.Id = DTM.Id   -- Added Join for mantis 0029003: 3rd point by Foram
		--	WHERE
		--		OM.Id = @rOrgId AND DM.Id IS NULL

		--END
		--ELSE
		--BEGIN --If DailyThought not Assign to particular day than insert into temp table and select from that
		--	DELETE FROM sCommunication.tDailyThoughtTemp WHERE OrgGroupId = @lOrgGroupId

		--	IF EXISTS (SELECT 1 FROM sCommunication.tDailyThoughtMaster WHERE OrgGroupId = @lOrgGroupId AND IsObsolete = 0 AND IsRead = 0)
		--	BEGIN
				
		--		SELECT Top 1 @lDailyThoughtId = Id FROM sCommunication.tDailyThoughtMaster WHERE OrgGroupId = @lOrgGroupId AND IsObsolete = 0 AND IsRead = 0 ORDER BY CreatedDateTime ASC

		--		INSERT INTO sCommunication.tDailyThoughtTemp 
		--		  (
		--			Id,
		--			DailyThoughtSubjectId,
		--			Title,
		--			Remark,
		--			IsObsolete,
		--			Number,
		--			OrgGroupId,
		--			IsRead,
		--			CreatedUserId,
		--			CreatedDateTime,
		--			UpdatedUserId,
		--			UpdatedDateTime
		--		  )
		--		  SELECT
		--			Id,
		--			DailyThoughtSubjectId,
		--			Title,
		--			Remark,
		--			IsObsolete,
		--			Number,
		--			OrgGroupId,
		--			IsRead,
		--			CreatedUserId,
		--			sCommon.fGetDate(),
		--			UpdatedUserId,
		--			UpdatedDateTime
		--		  FROM 
		--			sCommunication.tDailyThoughtMaster
		--		  WHERE 
		--			Id = @lDailyThoughtId

		--		  UPDATE 
		--			sCommunication.tDailyThoughtMaster 
		--		  SET 
		--			IsRead = 1 
		--		  WHERE 
		--			Id = @lDailyThoughtId

		--		  SELECT 
		--			DTM.Id,
		--			DTM.Number,
		--			DTM.Title,
		--			DTM.Remark,
		--			DTS.Title As [Subject]	
		--		  FROM
		--			sCommunication.tDailyThoughtTemp DTM 
		--			INNER JOIN sCommunication.tDailyThoughtSubjectMaster DTS ON DTM.DailyThoughtSubjectId = DTS.Id
		--		  WHERE
		--			DTM.OrgGroupId = @lOrgGroupId
		--	END
		--	ELSE
		--	BEGIN --If All thought read than change flag IsRead to false in all thought and than assign in temp table
		--			UPDATE sCommunication.tDailyThoughtMaster SET IsRead = 0 WHERE OrgGroupId = @lOrgGroupId
					
		--			IF EXISTS (SELECT 1 FROM sCommunication.tDailyThoughtMaster WHERE OrgGroupId = @lOrgGroupId AND IsObsolete = 0 AND IsRead = 0)
		--			BEGIN
						
		--				SELECT Top 1 @lDailyThoughtId =(Id) FROM sCommunication.tDailyThoughtMaster WHERE OrgGroupId = @lOrgGroupId AND IsObsolete = 0 AND IsRead = 0 ORDER By CreatedDateTime ASC
				
		--				INSERT INTO sCommunication.tDailyThoughtTemp 
		--				  (
		--					Id,
		--					DailyThoughtSubjectId,
		--					Title,
		--					Remark,
		--					IsObsolete,
		--					Number,
		--					OrgGroupId,
		--					IsRead,
		--					CreatedUserId,
		--					CreatedDateTime,
		--					UpdatedUserId,
		--					UpdatedDateTime
		--				  )
		--				  SELECT
		--					Id,
		--					DailyThoughtSubjectId,
		--					Title,
		--					Remark,
		--					IsObsolete,
		--					Number,
		--					OrgGroupId,
		--					IsRead,
		--					CreatedUserId,
		--					sCommon.fGetDate(),
		--					UpdatedUserId,
		--					UpdatedDateTime
		--				  FROM 
		--					sCommunication.tDailyThoughtMaster
		--				  WHERE 
		--					Id = @lDailyThoughtId

		--				  UPDATE 
		--					sCommunication.tDailyThoughtMaster 
		--				  SET 
		--					IsRead = 1 
		--				  WHERE 
		--					Id IN (@lDailyThoughtId)

		--				  SELECT 
		--					DTM.Id,
		--					DTM.Number,
		--					DTM.Title,
		--					DTM.Remark,
		--					DTS.Title As [Subject]
		--				  FROM
		--					sCommunication.tDailyThoughtTemp DTM 
		--					INNER JOIN sCommunication.tDailyThoughtSubjectMaster DTS ON DTM.DailyThoughtSubjectId = DTS.Id
		--				  WHERE
		--					DTM.OrgGroupId = @lOrgGroupId
		--			END
		--	END
		--END
	END
END
GO
PRINT N'Altering Procedure [sEMeeting].[pMeetingTypeMasterAdd]...';


GO

ALTER PROCEDURE [sEMeeting].[pMeetingTypeMasterAdd]
	@rAutoId smallint,
	@rTitle nvarchar(100),
	@rOrgGroupId smallint,
	@rIsObsolete bit = 0,
	@rCreatedUserId bigint,
	@rCode nvarchar(10),
	@rOrderIndex int = 0,
	@rDescription nvarchar(max) 

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

	BEGIN TRY

	BEGIN TRANSACTION	

	BEGIN

	IF (@rAutoId = 0)
	BEGIN
	 
	IF EXISTS (select 1 from sEMeeting.tMeetingTypeMaster where Title = @rTitle and IsObsolete = 0)
		BEGIN
			SELECT -101 as Result
		END
	ELSE IF EXISTS (select 1 from sEMeeting.tMeetingTypeMaster where OrderIndex = @rOrderIndex and IsObsolete = 0)
		BEGIN
			SELECT -102 as Result
		END
	ELSE
	    BEGIN
			INSERT INTO sEMeeting.tMeetingTypeMaster
			(
				Title,
				OrgGroupId,
				IsObsolete,
				CreatedUserId,
				CreatedDateTime,
				Code,
				OrderIndex,
				Description
			)
			VALUES
			(
				@rTitle,
				@rOrgGroupId,
				@rIsObsolete,
				@rCreatedUserId,
				sCommon.fGetDate(),
				@rCode,
				@rOrderIndex,
				@rDescription
			)
				SELECT 1 AS Result
		END
	END
	ELSE
	BEGIN 
		IF EXISTS (SELECT 1 FROM sEMeeting.tMeetingTypeMaster WHERE (AutoId = @rAutoId OR OrderIndex = @rOrderIndex) AND IsObsolete = 0)
		BEGIN
			IF NOT EXISTS (SELECT 1 FROM sEMeeting.tMeetingTypeMaster WHERE AutoId <> @rAutoId AND OrderIndex = @rOrderIndex AND IsObsolete = 0)
			BEGIN
				UPDATE sEMeeting.tMeetingTypeMaster
				SET 
					Title = @rTitle,
					IsObsolete = @rIsObsolete,
					UpdatedUserId = @rCreatedUserId,
					UpdatedDateTime = GETUTCDATE(),
					OrderIndex = @rOrderIndex,
					Code = @rCode,
					Description = @rDescription
				WHERE AutoId = @rAutoId;
				SELECT 11 AS Result;
			END
			ELSE
			BEGIN
				SELECT -102 AS Result;
			END
		END
		ELSE
		BEGIN
			SELECT -102 AS Result;
		END
	END
	END

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


GO
 
ALTER PROCEDURE [sEMeeting].[pMeetingTypeMasterDelete]
	 @rId smallint

	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
BEGIN TRY

	IF EXISTS (SELECT 1 from sEMeeting.tOnlineMeeting where MeetingTypeId = @rId)
	BEGIN
	SELECT -101 As Result
	END
	ELSE
	BEGIN
	IF EXISTS (SELECT 1 from sEMeeting.tMeetingTypeMaster where AutoId = @rId AND IsObsolete = 0)
	BEGIN 
	Update sEMeeting.tMeetingTypeMaster
	SET 
		IsObsolete = 1
	WHERE AutoId = @rId
	SELECT 1 As Result
	END
	END
END TRY
BEGIN CATCH 
		SELECT -1 AS Result
END CATCH
END
GO
PRINT N'Altering Procedure [sEMeeting].[pMeetingTypeMasterDetailGet]...';


GO
 
ALTER PROCEDURE [sEMeeting].[pMeetingTypeMasterDetailGet]
	 @rId smallint = 0,
	 @rTitle nvarchar(20) = ''
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
BEGIN TRY

	If(@rId = 0) 
	BEGIN 
		SELECT AutoId, Title, Code, OrderIndex, Description
			from [sEMeeting].[tMeetingTypeMaster] MTM where IsObsolete = 0 
			AND (MTM.Title LIKE '%' + @rTitle + '%' OR (ISNULL(@rTitle,'') = '') OR @rTitle = '*')
	END
	ELSE
	BEGIN
		SELECT AutoId, Title, Code, OrderIndex, Description
			from [sEMeeting].[tMeetingTypeMaster] where AutoId = @rId AND IsObsolete = 0
	END
END TRY
BEGIN CATCH 
		SELECT -1 AS Result
END CATCH
END
GO
PRINT N'Altering Procedure [sEMeeting].[pMenuGet]...';


GO
-- exec sEMeeting.pMenuGet 9911000000270,0,0,1
-- exec sEMeeting.pMenuGet 9911000000545,0,0,1
ALTER PROCEDURE [sEMeeting].[pMenuGet]
 @rUserId [bigint],    
 @rMenuId int = 0,    
 @rResourceTypeId int= 0,    
 @rIsCoreMenu bit = 0     
      
WITH EXECUTE AS CALLER    
AS    
SET NOCOUNT ON    
    
BEGIN    
 IF(@rIsCoreMenu=0)    
 BEGIN    
 IF EXISTS(SELECT 1 FROM sSecurity.tPermissionUser WHERE UserId = @rUserId)    
  BEGIN    
   SELECT    
    MenuID,    
    ModuleId,    
    ParentMenuID,    
    MenuTitle,      
    ScreenTitle,       
    PageURL,    
    ScreenId,    
    Permission,    
    OrderNumber,      
    TaskId,      
    PageURL  AS PagePath,    
    IconPath    
        
   FROM    
     (SELECT Menu.Id AS MenuID,     
    ISNULL(Menu.ParentMenuID, 0) AS ParentMenuID,     
    Menu.Title AS MenuTitle,       
    ISNULL(Screen.Title, '') AS ScreenTitle,        
    ISNULL(Screen.Page, '') AS PageURL,    
    ISNULL(Screen.ScreenGroupId,0) AS ScreenGroupId,    
    ISNULL(Menu.ScreenId, 0) AS ScreenId,    
    ISNULL(PermissionValue, 0) AS Permission,    
    ISNULL(OrderNumber, 0) AS OrderNumber,    
    ISNULL(Screen.TaskId,0) AS TaskId,    
    ISNULL(Screen.IconPath,'') As IconPath,     
    ISNULL(T.ResourceTypeId,0) AS ResourceTypeId,    
    ISNULL(T.ModuleId,0) AS ModuleId    
       
       
   FROM sSecurity.tMenu Menu     
   LEFT OUTER JOIN sSecurity.tScreen Screen    
    ON Menu.ScreenId = Screen.Id      
   LEFT OUTER JOIN (     
       SELECT     
        TaskId,     
        SUM(Permission & 2) PermissionValue          
       FROM     
        sSecurity.tPermissionUser P    
        INNER JOIN sSecurity.tTask T ON T.Id = P.TaskId    
        --INNER JOIN sSecuirty.tOrganizationTask OT ON OT.TaskId = T.Id AND OT.OrgGroupId = P.OrgGroupId     
        INNER JOIN sSecurity.tModulePermission MP ON MP.ModuleId = T.ModuleId AND MP.OrgGroupId = P.OrgGroupId    
       WHERE    
        T.IsObsolete = 0 AND P.UserId = @rUserId    
       GROUP BY     
        TaskId) TBL2    
       ON     
        Screen.TaskId = TBL2.TaskId     
         LEFT OUTER JOIN sSecurity.tTask  T ON T.Id =  Screen.TaskId AND ResourceTypeId = @rResourceTypeId    
          
       WHERE     
       (Menu.IsObsolete = 0)  --For ScreenGroupId Master Page    
       AND ISNULL(Screen.IsObsolete, 0) = 0)     
       MenuTable      
       --INNER JOIN sSecurity.tTask  T ON T.Id =  MenuTable.TaskId     
   WHERE     
    MenuTable.ScreenId = 0 OR MenuTable.Permission >= 2     
    AND     
    ((MenuTable.ResourceTypeId = @rResourceTypeId) OR (@rResourceTypeId = 0))    
    AND ((MenuTable.MenuID = @rMenuID)OR(@rMenuID = 0))    
        
   ORDER BY     
    ParentMenuID    
  END    
 ELSE     
  BEGIN    
   SELECT    
    MenuID,    
    ModuleId,    
    ParentMenuID,    
    MenuTitle,      
    ScreenTitle,       
    PageURL,    
    ScreenId,    
    Permission,    
    OrderNumber,      
    TaskId,      
     PageURL  AS PagePath,    
     IconPath    
        
   FROM    
     (SELECT Menu.Id AS MenuID,     
    ISNULL(Menu.ParentMenuID, 0) AS ParentMenuID,     
    Menu.Title AS MenuTitle,       
    ISNULL(Screen.Title, '') AS ScreenTitle,        
    ISNULL(Screen.Page, '') AS PageURL,    
    ISNULL(Screen.ScreenGroupId,0) AS ScreenGroupId,    
    ISNULL(Menu.ScreenId, 0) AS ScreenId,    
    ISNULL(PermissionValue, 0) AS Permission,    
    ISNULL(OrderNumber, 0) AS OrderNumber,    
    ISNULL(Screen.TaskId,0) AS TaskId,    
    ISNULL(Screen.IconPath,'') As IconPath,     
    ISNULL(T.ResourceTypeId,0) AS ResourceTypeId,    
    ISNULL(T.ModuleId,0) AS ModuleId    
       
       
   FROM sSecurity.tMenu Menu     
   LEFT OUTER JOIN sSecurity.tScreen Screen    
    ON Menu.ScreenId = Screen.Id      
   LEFT OUTER JOIN (     
       SELECT     
        TaskId,     
        SUM(Permission & 2) PermissionValue          
       FROM     
        sSecurity.tPermission P    
        INNER JOIN sSecurity.tTask T ON T.Id = P.TaskId    
        --INNER JOIN sSecuirty.tOrganizationTask OT ON OT.TaskId = T.Id AND OT.OrgGroupId = P.OrgGroupId     
        INNER JOIN sSecurity.tModulePermission MP ON MP.ModuleId = T.ModuleId AND MP.OrgGroupId = P.OrgGroupId    
        INNER JOIN    
        (    
        SELECT RoleId FROM sSecurity.tUserRole UR WHERE  UserId = @rUserId AND IsObsolete = 0    
        ) B ON B.RoleId = P.RoleId    
       WHERE    
        T.IsObsolete = 0    
       GROUP BY     
        TaskId) TBL2    
       ON     
        Screen.TaskId = TBL2.TaskId     
         LEFT OUTER JOIN sSecurity.tTask  T ON T.Id =  Screen.TaskId AND ResourceTypeId = @rResourceTypeId    
          
       WHERE     
       (Menu.IsObsolete = 0)  --For ScreenGroupId Master Page    
       AND ISNULL(Screen.IsObsolete, 0) = 0 AND TBL2.PermissionValue > 0)     
       MenuTable      
       --INNER JOIN sSecurity.tTask  T ON T.Id =  MenuTable.TaskId     
   WHERE     
    MenuTable.ScreenId = 0 OR MenuTable.Permission >= 2     
    AND     
    ((MenuTable.ResourceTypeId = @rResourceTypeId) OR (@rResourceTypeId = 0))    
    AND ((MenuTable.MenuID = @rMenuID)OR(@rMenuID = 0))    
        
   ORDER BY     
    ParentMenuID    
  END    
 END    
 ELSE    
 BEGIN     
 SELECT    
   MenuID,    
   ModuleId,    
   ParentMenuID,    
   MenuTitle,      
   ScreenTitle,       
   PageURL,    
   ScreenId,    
   Permission,    
   OrderNumber,      
   TaskId,      
   PageURL  AS PagePath,    
   MenuIsObsolete,    
   Icon      
  FROM    
  (    

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

  UNION
  

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

  ) MenuTable      
  WHERE     
  --(MenuTable.ScreenId = 0 OR MenuTable.Permission >= 2)  
  --AND   
  ((MenuTable.ResourceTypeId = @rResourceTypeId) OR (@rResourceTypeId = 0))    
  AND ((MenuTable.MenuID = @rMenuID)OR(@rMenuID = 0))    
  AND MenuIsObsolete = 0    
  AND MenuTable.MenuId IN (19184027,2411)   
  AND ModuleId IN (95,235)
  ORDER BY ParentMenuID  
 END    
END
GO
PRINT N'Altering Procedure [sEMeeting].[pOnlineMeetingAdd]...';


GO
 
ALTER PROCEDURE [sEMeeting].[pOnlineMeetingAdd]
	 
        @rId bigint = 0,
		@rOrgGroupId smallint,
		@rMeetingTypeId smallint,
		@rHostEmployeeId bigint,
		@rStartDate datetime,
		@rStartTime datetime,
		@rEndDate datetime,
		@rEndTime datetime,
		@rTitle nvarchar(100) = '',
		@rDescription nvarchar(max) = '',
		@rIsDisplayMeetingId bit = 0,
		@rMeetingId nvarchar(50) = '',
		@rMeetingPass nvarchar(50) = '',
		@rIsReference bit = 0,
		@rIsResource bit=0,
		@rIsCompleted bit = 0,
		@rIsMeetingStarted bit = 0,
		@rMeetingAccountId int = 0,
		@rIsMeetingCreated bit=0,
		@rIsObsolete bit = 0,
		@rCreatedUserId bigint,
		@rIsOnParticipantVideo bit = 0,
		@rIsOnParticipantAudio bit = 0,
		@rIsOnHostVideo bit = 0,
		@rIsOnHostAudio bit = 0,
		@rIsOnParticipantScreenShare bit = 0,
		@rIsOnHostscreenShare bit = 0,
		@rAssigneeId tinyint,
		@rIsTrackAttendance bit = 0,
		@rOnlineMeetingScopeList sEMeeting.OnlineMeetingScopeDetailType READONLY,
		@rOnlineMeetingReferenceList sEMeeting.OnlineMeetingReferenceDetailType READONLY
			
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	 
	 BEGIN TRANSACTION	
	 DECLARE @lNextNumber BIGINT 

	 DECLARE @lAccountEmailId NVARCHAR(200),@lAccountPassword NVARCHAR(200),@lAPIKey NVARCHAR(100),@lAPISecret NVARCHAR(100),@lWebAPIKey NVARCHAR(100),
	         @lWebAPISecret NVARCHAR(100),@lMeetingProviderId NVARCHAR(100),@lJWTToken NVARCHAR(MAX),@lOAuthAccountId NVARCHAR(MAX), @lOAuthClientId NVARCHAR(MAX),@lOAuthClientSecret NVARCHAR(MAX)

	SELECT @lAccountEmailId = AccountEmailId,@lAccountPassword = AccountPassword,@lAPIKey = APIKey,@lAPISecret = APISecret,@lWebAPIKey = WebAPIKey,@lWebAPISecret = WebAPISecret,@lMeetingProviderId = MeetingProviderId,
	@lJWTToken = JWTToken, @lOAuthAccountId = OAuthAccountId , @lOAuthClientId = OAuthClientId , @lOAuthClientSecret = OAuthClientSecret
	    FROM sAcademic.tOnlineMeetingAccount
		WHERE Id = @rMeetingAccountId

	IF(@rId = 0)	
	BEGIN
		
	EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sEMeeting.tOnlineMeeting', 0, 1, 1,@outNextNumber = @lNextNumber output
	Print @lNextNumber
	INSERT INTO sEMeeting.tOnlineMeeting
		(
			Id,
			OrgGroupId,
			MeetingTypeId,
			HostEmployeeId,
			StartDate,
			StartTime,
			EndDate,
			EndTime,
			Title,
			Description,
			IsDisplayMeetingId,
			MeetingId,
			MeetingPassword,
			IsReference,
			IsResource,
			IsCompleted,
			IsMeetingStarted,
			MeetingAccountId,
			IsMeetingCreated,
			IsObsolete,
			AssigneeId,
			IsTrackAttendance,
			CreatedUserId,
			CreatedDateTime
		)
	VALUES
		(
			@lNextNumber,
			@rOrgGroupId,
			@rMeetingTypeId,
			@rHostEmployeeId,
			@rStartDate,
			@rStartTime,
			@rEndDate, 
			@rEndTime,
			@rTitle,
			@rDescription,
			@rIsDisplayMeetingId,
			@rMeetingId,
			@rMeetingPass,
			@rIsReference,
			@rIsResource,
			@rIsCompleted,
			@rIsMeetingStarted,
			@rMeetingAccountId,
			@rIsMeetingCreated,
			@rIsObsolete,
			@rAssigneeId,
			@rIsTrackAttendance,
			@rCreatedUserId,
			GetUtcDate()
		)
		    
	INSERT INTO sEMeeting.tOnlineMeetingScope
			(
			OnlineMeetingId,
			ScopeSourceTypeId,
			ScopeSourceId,
			IsObsolete,
			AssigneeId,
			CreatedUserId,
			CreatedDateTime
			)
			SELECT 
			@lNextNumber,
			ScopeSourceTypeId,
			ScopeSourceId,
			@rIsObsolete,
			AssigneeId,
			@rCreatedUserId,
			GetUtcDate()
			from @rOnlineMeetingScopeList

	IF (@rIsReference = 'true')
	BEGIN
	INSERT INTO sEMeeting.tOnlineMeetingReference
	(
	OnlineMeetingId,
	ReferencePath
	)
	SELECT
	@lNextNumber,
	ReferencePath
	from @rOnlineMeetingReferenceList
		
	END

	INSERT INTO sEMeeting.tOnlineMeetingSettings
		(
			OnlineMeetingId,
			IsOnParticipantVideo,
			IsOnParticipantAudio,
			IsOnHostVideo,
			IsOnHostAudio,
			IsOnParticipantScreenShare,
			IsOnHostscreenShare,
			AccountEmailId,
			AccountPassword,
			APIKey,
			APISecret,
			WebAPIKey,
			WebAPISecret,
			MeetingProviderId,
			JWTToken,
			OAuthAccountId,
			OAuthClientId,
			OAuthClientSecret
		)
		VALUES
		(
			@lNextNumber,
			@rIsOnParticipantVideo,
			@rIsOnParticipantAudio,
			@rIsOnHostVideo,
			@rIsOnHostAudio,
			@rIsOnParticipantScreenShare,
			@rIsOnHostscreenShare,
			@lAccountEmailId,
			@lAccountPassword,
			@lAPIKey,
			@lAPISecret,
			@lWebAPIKey,
			@lWebAPISecret,
			@lMeetingProviderId,
			@lJWTToken,
			@lOAuthAccountId,
			@lOAuthClientId,
			@lOAuthClientSecret
		)

	SELECT @lNextNumber as Result
	END	 

ELSE
	 BEGIN
	    UPDATE sEMeeting.tOnlineMeeting
	    SET
		   OrgGroupId = @rOrgGroupId,
		   MeetingTypeId = @rMeetingTypeId,
		   HostEmployeeId = @rHostEmployeeId,
		   StartDate = @rStartDate,
		   StartTime = @rStartTime,
		   EndDate = @rEndDate,
		   EndTime = @rEndTime,
		   Title = @rTitle,
		   Description = @rDescription,
		   IsDisplayMeetingId = @rIsDisplayMeetingId,
		   MeetingId = @rMeetingId,
		   MeetingPassword = @rMeetingPass,
		   IsReference = @rIsReference,
		   IsResource = @rIsResource,
		   IsCompleted = @rIsCompleted,
		   IsMeetingStarted = @rIsMeetingStarted,
		   MeetingAccountId = @rMeetingAccountId,
		   IsMeetingCreated = @rIsMeetingCreated,
		   IsObsolete = @rIsObsolete,
		   UpdatedUserId = @rCreatedUserId,
		   UpdatedDateTime = GetUtcDate(),
		   IsTrackAttendance = @rIsTrackAttendance

	      WHERE Id = @rId
		  
		delete from sEMeeting.tOnlineMeetingScope where OnlineMeetingId = @rId

		INSERT INTO sEMeeting.tOnlineMeetingScope
			(
			OnlineMeetingId,
			ScopeSourceTypeId,
			ScopeSourceId,
			IsObsolete,
			CreatedUserId,
			CreatedDateTime,
			AssigneeId
			)
			SELECT 
			@rId,
			ScopeSourceTypeId,
			ScopeSourceId,
			@rIsObsolete,
			@rCreatedUserId,
			GetUtcDate(),
			AssigneeId
			from @rOnlineMeetingScopeList
		
		delete from sEMeeting.tOnlineMeetingReference where OnlineMeetingId = @rId

		IF (@rIsReference = 'true')
		BEGIN
			INSERT INTO sEMeeting.tOnlineMeetingReference
			(
			OnlineMeetingId,
			ReferencePath
			)
			SELECT
			@rId,
			ReferencePath
			from @rOnlineMeetingReferenceList
		END

	    SELECT 11 AS Result
	
	 END  	

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


GO


ALTER PROCEDURE [sEMeeting].[pOnlineMeetingAttendanceGet]
	@rOnlineMeetingId bigint
 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
	
	CREATE TABLE #ScopeSourceTypeId
	(
		Id int IDENTITY,
		ScopeSourceTypeId bigint
	)
	CREATE TABLE #StudentData
	(
	Class nvarchar(200),
	Code nvarchar(200),
	RollNo bigint,
	StudentName nvarchar(200),
	IsPresent nvarchar(100),
	ClassID bigint,
	DivisionId bigint,
	AcademicId bigint,
	IsLoggedIn nvarchar(100),
	FirstInDateTime datetime,
	LastOutDateTime datetime,
	IsPresentAbsent nvarchar(100)
	)

	INSERT INTO #ScopeSourceTypeId
	Select Distinct  ScopeSourceTypeId from [sEMeeting].[tOnlineMeetingScope] Where OnlineMeetingId=@rOnlineMeetingId

DECLARE @lCountScopeSourceTypeId int,@lScopeSourceTypeId int,@lId int

SELECT @lCountScopeSourceTypeId=COUNT(ScopeSourceTypeId) FROM #ScopeSourceTypeId
	SELECT Top 1 @lId=Id FROM #ScopeSourceTypeId

	WHILE @lId <= @lCountScopeSourceTypeId
			BEGIN
			SELECT @lScopeSourceTypeId=ScopeSourceTypeId FROM #ScopeSourceTypeId WHERE Id=@lId
	--AcademicId
	IF(@lScopeSourceTypeId=2003)
	BEGIN
	INSERT INTO #StudentData
	SELECT 
			SA.ClassName+'-'+SA.DivisionName AS Class,
			SA.Code,
			SA.RollNo,
			SA.FirstName +' '+SA.MiddleName +' '+SA.LastName As StudentName ,
			ISNULL((SELECT (CASE WHEN OMA.IsPresent=1 THEN 'P' ELSE 'N' END)  FROM sEMeeting.tOnlineMeetingAttendance OMA 
			WHERE OMA.ParticipantSourceId = SA.AcademicId AND OMA.OnlineMeetingId=@rOnlineMeetingId),'N')AS IsPresent,
			SA.ClassID,
			SA.DivisionId,
			SA.AcademicId,
			ISNULL((SELECT (CASE WHEN OMA.IsLoggedIn=1 THEN 'ON' ELSE 'OFF' END)  FROM sEMeeting.tOnlineMeetingAttendance OMA 
			WHERE OMA.ParticipantSourceId = SA.AcademicId AND  OMA.OnlineMeetingId=@rOnlineMeetingId),'OFF')AS IsLoggedIn,
			ISNULL((SELECT  OMA.FirstInDateTime FROM sEMeeting.tOnlineMeetingAttendance OMA 
			WHERE  OMA.OnlineMeetingId=@rOnlineMeetingId),OM.StartDate)AS FirstInDateTime,
			(SELECT  OMA.LastOutDateTime FROM sEMeeting.tOnlineMeetingAttendance OMA WHERE  OMA.OnlineMeetingId=@rOnlineMeetingId ) as LastOutDateTime,
			ISNULL((SELECT  OMA.IsPresent  FROM sEMeeting.tOnlineMeetingAttendance OMA 
			WHERE  OMA.OnlineMeetingId=@rOnlineMeetingId),0)AS IsPresentAbsent
			
  FROM		sStudent.vStudentAcademic SA
			INNER JOIN sEMeeting.tOnlineMeetingScope OMS ON SA.AcademicId=OMS.ScopeSourceId
			INNER JOIN [sEMeeting].[tOnlineMeeting] OM ON OM.Id=OMS.OnlineMeetingId
			WHERE 
			OMS.OnlineMeetingId=@rOnlineMeetingId
			AND SA.StatusId = 1
			GROUP BY
			SA.StudentId,SA.FirstName ,SA.MiddleName,SA.LastName,
			SA.ClassName,SA.Code,SA.RollNo,SA.RollNo,
			SA.DivisionName,SA.ClassID,
			SA.DivisionId,SA.AcademicId,OM.StartDate
			ORDER BY SA.ClassID,SA.DivisionId,SA.RollNo
	END
	--ClassId
	ELSE IF(@lScopeSourceTypeId=2016)
	BEGIN
	INSERT INTO #StudentData
	SELECT 

			SA.ClassName+'-'+SA.DivisionName AS Class,
			SA.Code,
			SA.RollNo,
			SA.FirstName +' '+SA.MiddleName +' '+SA.LastName As StudentName ,
			ISNULL((SELECT (CASE WHEN OMA.IsPresent=1 THEN 'P' ELSE 'N' END)  FROM sEMeeting.tOnlineMeetingAttendance OMA 
			WHERE  OMA.ParticipantSourceTypeId = SA.AcademicId AND OMA.OnlineMeetingId=@rOnlineMeetingId),'N')AS IsPresent,
			SA.ClassID,
			SA.DivisionId,
			SA.AcademicId,
			ISNULL((SELECT (CASE WHEN OMA.IsLoggedIn=1 THEN 'ON' ELSE 'OFF' END)  FROM sEMeeting.tOnlineMeetingAttendance OMA 
			WHERE  OMA.ParticipantSourceTypeId = SA.AcademicId AND OMA.OnlineMeetingId=@rOnlineMeetingId),'OFF')AS IsLoggedIn,
			ISNULL((SELECT   OMA.FirstInDateTime  FROM sEMeeting.tOnlineMeetingAttendance OMA 
			WHERE  OMA.OnlineMeetingId=@rOnlineMeetingId),OM.StartDate)AS FirstInDateTime,
			(SELECT  OMA.LastOutDateTime FROM sEMeeting.tOnlineMeetingAttendance OMA WHERE  OMA.OnlineMeetingId=@rOnlineMeetingId ) as LastOutDateTime,
			ISNULL((SELECT  OMA.IsPresent  FROM sEMeeting.tOnlineMeetingAttendance OMA 
			WHERE  OMA.OnlineMeetingId=@rOnlineMeetingId),0)AS IsPresentAbsent
			
			
  FROM		sStudent.vStudentAcademic SA
			INNER JOIN sEMeeting.tOnlineMeetingScope OMS ON SA.ClassId=OMS.ScopeSourceId
			INNER JOIN [sEMeeting].[tOnlineMeeting] OM ON OM.Id=OMS.OnlineMeetingId
			WHERE 
			OMS.OnlineMeetingId=@rOnlineMeetingId
			AND SA.StatusId = 1
			GROUP BY 
			SA.StudentId,SA.FirstName ,SA.MiddleName,SA.LastName,
			SA.ClassName,SA.Code,SA.RollNo,SA.RollNo,
			SA.DivisionName,SA.ClassID,
			SA.DivisionId,SA.AcademicId,OM.StartDate
			ORDER BY SA.ClassID,SA.DivisionId,SA.RollNo
	END
	--DeparmentId
	ELSE IF(@lScopeSourceTypeId=2017)
	BEGIN
	INSERT INTO #StudentData
	SELECT 

			SA.ClassName+'-'+SA.DivisionName AS Class,
			SA.Code,
			SA.RollNo,
			SA.FirstName +' '+SA.MiddleName +' '+SA.LastName As StudentName ,
			ISNULL((SELECT (CASE WHEN OMA.IsPresent=1 THEN 'P' ELSE 'N' END)  FROM sEMeeting.tOnlineMeetingAttendance OMA 
			WHERE OMA.ParticipantSourceId = SA.AcademicId AND OMA.OnlineMeetingId=@rOnlineMeetingId),'N')AS IsPresent,
			SA.ClassID,
			SA.DivisionId,
			SA.AcademicId,
			ISNULL((SELECT (CASE WHEN OMA.IsLoggedIn=1 THEN 'ON' ELSE 'OFF' END)  FROM sEMeeting.tOnlineMeetingAttendance OMA 
			WHERE OMA.ParticipantSourceId = SA.AcademicId AND  OMA.OnlineMeetingId=@rOnlineMeetingId),'OFF')AS IsLoggedIn,
			ISNULL((SELECT   OMA.FirstInDateTime  FROM sEMeeting.tOnlineMeetingAttendance OMA 
			WHERE  OMA.OnlineMeetingId=@rOnlineMeetingId),OM.StartDate)AS FirstInDateTime,
			(SELECT  OMA.LastOutDateTime FROM sEMeeting.tOnlineMeetingAttendance OMA WHERE  OMA.OnlineMeetingId=@rOnlineMeetingId ) as LastOutDateTime,
			ISNULL((SELECT  OMA.IsPresent  FROM sEMeeting.tOnlineMeetingAttendance OMA 
			WHERE  OMA.OnlineMeetingId=@rOnlineMeetingId),0)AS IsPresentAbsent
			
			
  FROM		sStudent.vStudentAcademic SA
			INNER JOIN sEMeeting.tOnlineMeetingScope OMS ON SA.DepartmentId=OMS.ScopeSourceId
			INNER JOIN [sEMeeting].[tOnlineMeeting] OM ON OM.Id=OMS.OnlineMeetingId
			WHERE 
			OMS.OnlineMeetingId=@rOnlineMeetingId
			AND SA.StatusId = 1
			GROUP BY 
			SA.StudentId,SA.FirstName ,SA.MiddleName,SA.LastName,
			SA.ClassName,SA.Code,SA.RollNo,SA.RollNo,
			SA.DivisionName,SA.ClassID,
			SA.DivisionId,SA.AcademicId,OM.StartDate
			ORDER BY SA.ClassID,SA.DivisionId,SA.RollNo
	END
	--OrgId
	ELSE IF(@lScopeSourceTypeId=2021)
	BEGIN
	INSERT INTO #StudentData
	SELECT 
			SA.ClassName+'-'+SA.DivisionName AS Class,
			SA.Code,
			SA.RollNo,
			SA.FirstName +' '+SA.MiddleName +' '+SA.LastName As StudentName ,
			ISNULL((SELECT (CASE WHEN OMA.IsPresent=1 THEN 'P' ELSE 'N' END)  FROM sEMeeting.tOnlineMeetingAttendance OMA 
			WHERE OMA.ParticipantSourceId = SA.AcademicId AND  OMA.OnlineMeetingId=@rOnlineMeetingId),'N')AS IsPresent,
			SA.ClassID,
			SA.DivisionId,
			SA.AcademicId,
			ISNULL((SELECT (CASE WHEN OMA.IsLoggedIn=1 THEN 'ON' ELSE 'OFF' END)  FROM sEMeeting.tOnlineMeetingAttendance OMA 
			WHERE OMA.ParticipantSourceId = SA.AcademicId AND OMA.OnlineMeetingId=@rOnlineMeetingId),'OFF')AS IsLoggedIn,
			ISNULL((SELECT   OMA.FirstInDateTime  FROM sEMeeting.tOnlineMeetingAttendance OMA 
			WHERE  OMA.OnlineMeetingId=@rOnlineMeetingId),OM.StartDate)AS FirstInDateTime,
			(SELECT  OMA.LastOutDateTime FROM sEMeeting.tOnlineMeetingAttendance OMA WHERE  OMA.OnlineMeetingId=@rOnlineMeetingId ) as LastOutDateTime,
			ISNULL((SELECT  OMA.IsPresent  FROM sEMeeting.tOnlineMeetingAttendance OMA 
			WHERE  OMA.OnlineMeetingId=@rOnlineMeetingId),0)AS IsPresentAbsent
			
			
  FROM		sStudent.vStudentAcademic SA
			INNER JOIN sEMeeting.tOnlineMeetingScope OMS ON SA.OrgId=OMS.ScopeSourceId
			INNER JOIN [sEMeeting].[tOnlineMeeting] OM ON OM.Id=OMS.OnlineMeetingId
			WHERE 
			OMS.OnlineMeetingId=@rOnlineMeetingId
			AND SA.StatusId = 1
			GROUP BY 
			SA.StudentId,SA.FirstName ,SA.MiddleName,SA.LastName,
			SA.ClassName,SA.Code,SA.RollNo,SA.RollNo,
			SA.DivisionName,SA.ClassID,
			SA.DivisionId,SA.AcademicId,OM.StartDate
			ORDER BY SA.ClassID,SA.DivisionId,SA.RollNo
	END
	--Division
	ELSE IF(@lScopeSourceTypeId=2005)
	BEGIN
	INSERT INTO #StudentData
	SELECT 
			SA.ClassName+'-'+SA.DivisionName AS Class,
			SA.Code,
			SA.RollNo,
			SA.FirstName +' '+SA.MiddleName +' '+SA.LastName As StudentName ,
			ISNULL((SELECT (CASE WHEN OMA.IsPresent=1 THEN 'P' ELSE 'N' END)  FROM sEMeeting.tOnlineMeetingAttendance OMA 
			WHERE OMA.ParticipantSourceId = SA.AcademicId AND OMA.OnlineMeetingId=@rOnlineMeetingId),'N')AS IsPresent,
			SA.ClassID,
			SA.DivisionId,
			SA.AcademicId,
			ISNULL((SELECT (CASE WHEN OMA.IsLoggedIn=1 THEN 'ON' ELSE 'OFF' END)  FROM sEMeeting.tOnlineMeetingAttendance OMA 
			WHERE OMA.ParticipantSourceId = SA.AcademicId AND OMA.OnlineMeetingId=@rOnlineMeetingId),'OFF')AS IsLoggedIn,
			ISNULL((SELECT   OMA.FirstInDateTime  FROM sEMeeting.tOnlineMeetingAttendance OMA 
			WHERE  OMA.OnlineMeetingId=@rOnlineMeetingId),OM.StartDate)AS FirstInDateTime,
			(SELECT  OMA.LastOutDateTime FROM sEMeeting.tOnlineMeetingAttendance OMA WHERE  OMA.OnlineMeetingId=@rOnlineMeetingId ) as LastOutDateTime,
			ISNULL((SELECT  OMA.IsPresent  FROM sEMeeting.tOnlineMeetingAttendance OMA 
			WHERE  OMA.OnlineMeetingId=@rOnlineMeetingId),0)AS IsPresentAbsent
			
			
  FROM		sStudent.vStudentAcademic SA
			INNER JOIN sEMeeting.tOnlineMeetingScope OMS ON SA.DivisionId=OMS.ScopeSourceId
			INNER JOIN [sEMeeting].[tOnlineMeeting] OM ON OM.Id=OMS.OnlineMeetingId 
			WHERE 
			OMS.OnlineMeetingId=@rOnlineMeetingId
			AND SA.StatusId = 1
			GROUP BY 
			SA.StudentId,SA.FirstName ,SA.MiddleName,SA.LastName,
			SA.ClassName,SA.Code,SA.RollNo,SA.RollNo,
			SA.DivisionName,SA.ClassID,
			SA.DivisionId,SA.AcademicId,OM.StartDate
			ORDER BY SA.ClassID,SA.DivisionId,SA.RollNo
	END

	SET @lId=@lId+1
	END
	Select * from #StudentData
	DROP TABLE #ScopeSourceTypeId
	DROP TABLE #StudentData
				
END
GO
PRINT N'Altering Procedure [sEMeeting].[pOnlineMeetingGet]...';


GO
 
ALTER PROCEDURE [sEMeeting].[pOnlineMeetingGet]
	 @rId bigint = 0,
	 @rTitle nvarchar(100) ='',
	 @rFromDate date = '',
	 @rToDate date = '',
	 @rEmployeeId bigint = 0,
	 @rMeetingTypeId smallint = 0,
	 @rIsCompleted int = 0,
	 @rAssigneeId tinyint,
	 @rUserId bigint = 0,
	 @rOnlineMeetingAccountId int = 0
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
BEGIN TRY

	if(@rId = 0)
	BEGIN 
	SELECT 
			OM.Id,
			EM.FirstName +' '+ EM.LastName as Teacher,
			OMT.Title as MeetingType,
			CONVERT(NVARCHAR,OM.StartDate,3)+' '+CONVERT(NVARCHAR(5),OM.StartTime,108) as StartDate,
			CONVERT(NVARCHAR,OM.EndDate,3)+' '+CONVERT(NVARCHAR(5),OM.EndTime,108) as EndDate,
			OM.IsCompleted as StatusId,
		    ISNULL(OM.Title,'') as Title,
			OM.StartDate AS TeacherStartDate,
			OM.EndDate AS TeacherEndDate,
			OM.AssigneeId,
			(SELECT
			  (
			  STUFF((SELECT ',' + a.Code
			  FROM
			  (
			  SELECT Code FROM sEMeeting.tOnlineMeetingScope OMS INNER JOIN sSetup.tClassMaster CM ON OMS.ScopeSourceId = CM.Id Where  OnlineMeetingId = OM.Id AND OMS.ScopeSourceTypeId = 2016
			  UNION ALL
			  SELECT Code FROM sEMeeting.tOnlineMeetingScope OMS INNER JOIN sSetup.tDivisionMaster DM ON OMS.ScopeSourceId = DM.Id Where  OnlineMeetingId = OM.Id AND OMS.ScopeSourceTypeId = 2005
			  UNION ALL
			  SELECT Title FROM sEMeeting.tOnlineMeetingScope OMS INNER JOIN sSetup.tOrganizationMaster DM ON OMS.ScopeSourceId = DM.Id Where  OnlineMeetingId = OM.Id AND OMS.ScopeSourceTypeId = 2021
			  UNION ALL
			  SELECT Code FROM sEMeeting.tOnlineMeetingScope OMS INNER JOIN sSetup.tDepartmentMaster DM ON OMS.ScopeSourceId = DM.Id Where  OnlineMeetingId = OM.Id AND OMS.ScopeSourceTypeId = 2017
			  ) a
			  FOR XML PATH ('')), 1, 1, '') ) ) as Assignee 
	  FROM 
			sEMeeting.tOnlineMeeting OM
			
			INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id = OM.HostEmployeeId 
			INNER JOIN sEMeeting.tMeetingTypeMaster OMT ON OMT.AutoId = OM.MeetingTypeId
			INNER JOIN sCommon.tAssigneeMaster AM ON AM.Id=OM.AssigneeId
	  WHERE 
    (
        (OM.Title LIKE @rTitle OR ISNULL(@rTitle, '') = '')
        AND (
            (OM.StartDate >= @rFromDate OR ISNULL(@rFromDate, '') = '')
            AND (OM.StartDate <= @rToDate OR ISNULL(@rToDate, '') = '')
            OR
            (OM.EndDate >= @rFromDate OR ISNULL(@rFromDate, '') = '')
            AND (OM.EndDate <= @rToDate OR ISNULL(@rToDate, '') = '')
        )
        AND (OM.HostEmployeeId = @rEmployeeId OR @rEmployeeId = 0)
        AND (OM.MeetingTypeId = @rMeetingTypeId OR @rMeetingTypeId = 0)
        AND (OM.MeetingAccountId = @rOnlineMeetingAccountId OR @rOnlineMeetingAccountId = 0)
        AND (
            (OM.IsCompleted IN (549, 550, 551, 0) AND @rIsCompleted = 0)
            OR (OM.IsCompleted = @rIsCompleted AND @rIsCompleted IN (549, 550, 551))
        )
        AND (
            (OM.AssigneeId IN (1, 2, 3) AND @rAssigneeId = 1)
            OR (OM.AssigneeId = @rAssigneeId AND @rAssigneeId IN (2, 3))
        )
    )

ORDER BY
    OM.StartDate, OM.StartTime ASC
	SELECT
			 OMS.OnlineMeetingId,
			 OMS.ScopeSourceTypeId,
			 OMS.ScopeSourceId,
			 OM.DisplayTitle AS Source,
			 'Organization' AS SourceType,
			 '' AS ROllNo,
             '' AS Code,
             '' AS ClassDepartment,
             OM.DisplayTitle AS OrgName,
			 OMS.AssigneeId
			FROM sEMeeting.tOnlineMeetingScope OMS
			INNER JOIN sSetup.tOrganizationMaster OM
				ON OMS.ScopeSourceId=OM.Id
			LEFT JOIN sCommon.tAssigneeMaster AM 
				ON AM.Id = OMS.AssigneeId
			WHERE OMS.OnlineMeetingId=@rId AND OMS.ScopeSourceTypeId=2021

			UNION ALL

			SELECT
			 OMS.OnlineMeetingId,
			 OMS.ScopeSourceTypeId,
			 OMS.ScopeSourceId,
			 DM.DisplayTitle AS Source,
			 'Department' AS SourceType,
			 '' AS ROllNo,
             '' AS Code,
             DM.Title AS ClassDepartment,
             OM.DisplayTitle AS OrgName,
			 OMS.AssigneeId
			FROM sEMeeting.tOnlineMeetingScope OMS
			INNER JOIN sSetup.tDepartmentMaster DM
				ON OMS.ScopeSourceId=DM.Id
			INNER JOIN sSetup.tOrganizationMaster OM
				ON DM.OrgId=OM.Id 
			LEFT JOIN sCommon.tAssigneeMaster AM 
				ON AM.Id = OMS.AssigneeId
			WHERE OMS.OnlineMeetingId=@rId AND OMS.ScopeSourceTypeId=2017

			UNION ALL

			SELECT
			 OMS.OnlineMeetingId,
			 OMS.ScopeSourceTypeId,
			 OMS.ScopeSourceId,
			 CM.DisplayTitle AS Source,
			 'Class' AS SourceType,
			 '' AS ROllNo,
             '' AS Code,
             DMast.Title AS ClassDepartment,
             OM.DisplayTitle AS OrgName,
			 OMS.AssigneeId
			FROM sEMeeting.tOnlineMeetingScope OMS
			INNER JOIN  sSetup.tClassMaster CM
				ON OMS.ScopeSourceId=CM.Id
			INNER JOIN sSetup.tDepartmentMaster DMast
				ON CM.DepartmentId =DMast.Id		
			INNER JOIN sSetup.tOrganizationMaster OM
				ON DMast.OrgId=OM.Id
			LEFT JOIN sCommon.tAssigneeMaster AM 
				ON AM.Id = OMS.AssigneeId
			WHERE OMS.OnlineMeetingId=@rId AND OMS.ScopeSourceTypeId=2016

			UNION ALL

			SELECT
			 OMS.OnlineMeetingId,
			 OMS.ScopeSourceTypeId,
			 OMS.ScopeSourceId,
			 DM.Code AS Source,
			 'Division' AS SourceType,
			 '' AS ROllNo,
             '' AS Code,
             DMast.Title AS ClassDepartment,
             OM.DisplayTitle AS OrgName,
			 OMS.AssigneeId
			FROM sEMeeting.tOnlineMeetingScope OMS
			INNER JOIN   sSetup.tDivisionMaster DM
				ON OMS.ScopeSourceId=DM.Id
			INNER JOIN 	sSetup.tClassMaster CM
				ON DM.ClassId=CM.Id	
			INNER JOIN sSetup.tDepartmentMaster DMast
				ON CM.DepartmentId =DMast.Id
			INNER JOIN sSetup.tOrganizationMaster OM
				ON DMast.OrgId=OM.Id
			LEFT JOIN sCommon.tAssigneeMaster AM 
				ON AM.Id = OMS.AssigneeId
				WHERE OMS.OnlineMeetingId=@rId AND OMS.ScopeSourceTypeId=2005

			UNION ALL
			
			SELECT
			 OMS.OnlineMeetingId,
			 OMS.ScopeSourceTypeId,
			 OMS.ScopeSourceId,
			 [sStudent].[fStudentNameGet](SM.FirstName , SM.MiddleName, SM.LastName,OM.StudentNameFormatId ) AS Source,
			 'Student' AS SourceType,
			 SA.ROllNo,
             SA.Code,
             SA.ClassName+' - '+SA.DivisionName AS ClassDepartment,
             OM.DisplayTitle AS OrgName,
			 OMS.AssigneeId
			FROM sEMeeting.tOnlineMeetingScope OMS
		    INNER JOIN sStudent.tStudentMaster SM
				ON OMS.ScopeSourceId=SM.Id
			INNER JOIN  sStudent.vStudentAcademic SA
				ON OMS.ScopeSourceId=SA.StudentId AND SA.IsActiveBatch=1 AND SA.StatusId=1		
			INNER JOIN sSetup.tOrganizationMaster OM
				ON SM.OrgId = OM.Id
			LEFT JOIN sCommon.tAssigneeMaster AM 
				ON AM.Id = OMS.AssigneeId
			WHERE OMS.OnlineMeetingId=@rId AND OMS.ScopeSourceTypeId=2003
			
			UNION ALL
			
			SELECT
			 OMS.OnlineMeetingId,
			 OMS.ScopeSourceTypeId,
			 OMS.ScopeSourceId,
			 SA.Name AS Source,
			 'Student' AS SourceType,
			 SA.ROllNo,
             SA.Code,
             SA.ClassName+' - '+SA.DivisionName AS ClassDepartment,
             OM.DisplayTitle AS OrgName,
			 OMS.AssigneeId
			FROM sEMeeting.tOnlineMeetingScope OMS
		   	INNER JOIN  sStudent.vStudentAcademic SA
				ON OMS.ScopeSourceId=SA.AcademicId AND SA.IsActiveBatch=1 AND SA.StatusId=1
			INNER JOIN sSetup.tOrganizationMaster OM
				ON SA.OrgId = OM.Id	
			LEFT JOIN sCommon.tAssigneeMaster AM 
				ON AM.Id = OMS.AssigneeId
			WHERE OMS.OnlineMeetingId=@rId AND OMS.ScopeSourceTypeId=2001
			
			UNION ALL
			
			SELECT
			 OMS.OnlineMeetingId,
			 OMS.ScopeSourceTypeId,
			 OMS.ScopeSourceId,
			 vEC.FirstName +' '+ vEC.LastName AS Source,
			 'Employee' AS SourceType,
			 '' AS ROllNo,
             vEC.Code,
             vEC.DepartmentName AS ClassDepartment,
             OM.DisplayTitle AS OrgName,
			 OMS.AssigneeId
			FROM sEMeeting.tOnlineMeetingScope OMS
			INNER JOIN sHrm.vEmployeeCommunication vEC 
				ON OMS.ScopeSourceId=vEC.EmployeeId AND vEC.StatusId=7
			INNER JOIN sSetup.tOrganizationMaster OM
				ON vEC.OrgId = OM.Id	
			LEFT JOIN sCommon.tAssigneeMaster AM 
				ON AM.Id = OMS.AssigneeId
			WHERE OMS.OnlineMeetingId=@rId AND OMS.ScopeSourceTypeId=95
	SELECT
		OnlineMeetingId, 
		ReferencePath 
		from sEMeeting.tOnlineMeetingReference OMR
		where OMR.OnlineMeetingId = @rId
	END
	ELSE
	BEGIN
		SELECT 
			OM.Id,
			EM.EmployeeName as Teacher,
			Em.EmployeeId as TeacherId,
			OMT.Title as MeetingType,
			OMT.AutoId as MeetingTypeId,
			CONVERT(NVARCHAR,OM.StartDate) as StartDate,
			CONVERT(NVARCHAR,OM.StartTime,108) as StartTime,
			CONVERT(NVARCHAR,OM.EndDate) as EndDate,
			CONVERT(NVARCHAR,OM.EndTime,108) as EndTime,
			OM.IsCompleted as StatusId,
			OM.Title as MeetingTitle,
			OM.Description,
			OM.IsDisplayMeetingId,
			OM.MeetingId,
			OM.MeetingPassword,
			ISNULL(OM.IsReference,0) as IsReference,
			ISNULL(OM.IsResource,0) as IsResource,
			ISNULL(OM.IsCompleted,0) as IsCompleted,
			ISNULL(OM.IsMeetingStarted,0) as IsMeetingStarted,
			ISNULL(OMS.IsOnParticipantVideo,0) AS IsOnParticipantVideo,
			ISNULL(OMS.IsOnParticipantAudio,0) AS IsOnParticipantAudio,
			ISNULL(OMS.IsOnHostVideo,0) AS IsOnHostVideo,
			ISNULL(OMS.IsOnHostAudio,0) AS IsOnHostAudio,
			ISNULL(OMS.IsOnParticipantScreenShare,0) AS IsOnParticipantScreenShare,
			ISNULL(OMS.IsOnHostscreenShare,0) AS IsOnHostscreenShare,
			ISNULL(OM.MeetingAccountId,0) AS MeetingAccountId,
			ISNULL(OM.IsMeetingCreated,0) AS IsMeetingCreated,
			ISNULL(OM.IsTrackAttendance,0) AS IsTrackAttendance,
			ISNULL(OMS.MeetingProviderId,0) As MeetingProviderId,
			OM.AssigneeId,
			OM.StartDate AS TeacherStartDate,
			OM.EndDate AS TeacherEndDate
	  FROM 
			sEMeeting.tOnlineMeeting OM
			
			INNER JOIN sHrm.vExtEmployee EM ON EM.EmployeeId = OM.HostEmployeeId 
			INNER JOIN sEMeeting.tMeetingTypeMaster OMT ON OMT.AutoId = OM.MeetingTypeId
			LEFT JOIN sEMeeting.tOnlineMeetingSettings OMS ON OMS.OnlineMeetingId = OM.Id
			INNER JOIN sCommon.tAssigneeMaster AM ON AM.Id=OM.AssigneeId
	  WHERE 
			(OM.Id = @rId)
	  ORDER BY
			OM.StartDate , OM.StartTime asc
		SELECT
			 OMS.OnlineMeetingId,
			 OMS.ScopeSourceTypeId,
			 OMS.ScopeSourceId,
			 OM.DisplayTitle AS Source,
			 'Organization' AS SourceType,
			 '' AS ROllNo,
             '' AS Code,
             '' AS ClassDepartment,
             OM.DisplayTitle AS OrgName,
			 OMS.AssigneeId
			FROM sEMeeting.tOnlineMeetingScope OMS
			INNER JOIN sSetup.tOrganizationMaster OM
				ON OMS.ScopeSourceId=OM.Id
			LEFT JOIN sCommon.tAssigneeMaster AM 
				ON AM.Id = OMS.AssigneeId
			WHERE OMS.OnlineMeetingId=@rId AND OMS.ScopeSourceTypeId=2021

			UNION ALL

			SELECT
			 OMS.OnlineMeetingId,
			 OMS.ScopeSourceTypeId,
			 OMS.ScopeSourceId,
			 DM.DisplayTitle AS Source,
			 'Department' AS SourceType,
			 '' AS ROllNo,
             '' AS Code,
             DM.Title AS ClassDepartment,
             OM.DisplayTitle AS OrgName,
			 OMS.AssigneeId
			FROM sEMeeting.tOnlineMeetingScope OMS
			INNER JOIN sSetup.tDepartmentMaster DM
				ON OMS.ScopeSourceId=DM.Id
			INNER JOIN sSetup.tOrganizationMaster OM
				ON DM.OrgId=OM.Id
			LEFT JOIN sCommon.tAssigneeMaster AM 
				ON AM.Id = OMS.AssigneeId
			WHERE OMS.OnlineMeetingId=@rId AND OMS.ScopeSourceTypeId=2017

			UNION ALL

			SELECT
			 OMS.OnlineMeetingId,
			 OMS.ScopeSourceTypeId,
			 OMS.ScopeSourceId,
			 CM.DisplayTitle AS Source,
			 'Class' AS SourceType,
			 '' AS ROllNo,
             '' AS Code,
             DMast.Title AS ClassDepartment,
             OM.DisplayTitle AS OrgName,
			 OMS.AssigneeId
			FROM sEMeeting.tOnlineMeetingScope OMS
			INNER JOIN  sSetup.tClassMaster CM
				ON OMS.ScopeSourceId=CM.Id
			INNER JOIN sSetup.tDepartmentMaster DMast
				ON CM.DepartmentId =DMast.Id		
			INNER JOIN sSetup.tOrganizationMaster OM
				ON DMast.OrgId=OM.Id
				LEFT JOIN sCommon.tAssigneeMaster AM 
				ON AM.Id = OMS.AssigneeId
			WHERE OMS.OnlineMeetingId=@rId AND OMS.ScopeSourceTypeId=2016

			UNION ALL

			SELECT
			 OMS.OnlineMeetingId,
			 OMS.ScopeSourceTypeId,
			 OMS.ScopeSourceId,
			 DM.Code AS Source,
			 'Division' AS SourceType,
			 '' AS ROllNo,
             '' AS Code,
             DMast.Title AS ClassDepartment,
             OM.DisplayTitle AS OrgName,
			 OMS.AssigneeId
			FROM sEMeeting.tOnlineMeetingScope OMS
			INNER JOIN   sSetup.tDivisionMaster DM
				ON OMS.ScopeSourceId=DM.Id
			INNER JOIN 	sSetup.tClassMaster CM
				ON DM.ClassId=CM.Id	
			INNER JOIN sSetup.tDepartmentMaster DMast
				ON CM.DepartmentId =DMast.Id
			INNER JOIN sSetup.tOrganizationMaster OM
				ON DMast.OrgId=OM.Id	
				LEFT JOIN sCommon.tAssigneeMaster AM 
				ON AM.Id = OMS.AssigneeId
				WHERE OMS.OnlineMeetingId=@rId AND OMS.ScopeSourceTypeId=2005

			UNION ALL
			
			SELECT
			 OMS.OnlineMeetingId,
			 OMS.ScopeSourceTypeId,
			 OMS.ScopeSourceId,
			 [sStudent].[fStudentNameGet](SM.FirstName , SM.MiddleName, SM.LastName,OM.StudentNameFormatId ) AS Source,
			 'Student' AS SourceType,
			 SA.ROllNo,
             SA.Code,
             SA.ClassName+' - '+SA.DivisionName AS ClassDepartment,
             OM.DisplayTitle AS OrgName,
			 OMS.AssigneeId
			FROM sEMeeting.tOnlineMeetingScope OMS
		    INNER JOIN sStudent.tStudentMaster SM
				ON OMS.ScopeSourceId=SM.Id
			INNER JOIN  sStudent.vStudentAcademic SA
				ON OMS.ScopeSourceId=SA.StudentId AND SA.IsActiveBatch=1 AND SA.StatusId=1		
			INNER JOIN sSetup.tOrganizationMaster OM
				ON SM.OrgId = OM.Id
				LEFT JOIN sCommon.tAssigneeMaster AM 
				ON AM.Id = OMS.AssigneeId
			WHERE OMS.OnlineMeetingId=@rId AND OMS.ScopeSourceTypeId=2003
			
			UNION ALL
			
			SELECT
			 OMS.OnlineMeetingId,
			 OMS.ScopeSourceTypeId,
			 OMS.ScopeSourceId,
			 SA.Name AS Source,
			 'Student' AS SourceType,
			 SA.ROllNo,
             SA.Code,
             SA.ClassName+' - '+SA.DivisionName AS ClassDepartment,
             OM.DisplayTitle AS OrgName,
			 OMS.AssigneeId
			FROM sEMeeting.tOnlineMeetingScope OMS
		   	INNER JOIN  sStudent.vStudentAcademic SA
				ON OMS.ScopeSourceId=SA.AcademicId AND SA.IsActiveBatch=1 AND SA.StatusId=1
			INNER JOIN sSetup.tOrganizationMaster OM
				ON SA.OrgId = OM.Id	
				LEFT JOIN sCommon.tAssigneeMaster AM 
				ON AM.Id = OMS.AssigneeId
			WHERE OMS.OnlineMeetingId=@rId AND OMS.ScopeSourceTypeId=2001
			
			UNION ALL
			
			SELECT
			 OMS.OnlineMeetingId,
			 OMS.ScopeSourceTypeId,
			 OMS.ScopeSourceId,
			 vEC.FirstName +' '+ vEC.LastName AS Source,
			 'Employee' AS SourceType,
			 '' AS ROllNo,
             vEC.Code,
             vEC.DepartmentName AS ClassDepartment,
             OM.DisplayTitle AS OrgName,
			 OMS.AssigneeId
			FROM sEMeeting.tOnlineMeetingScope OMS
			INNER JOIN sHrm.vEmployeeCommunication vEC 
				ON OMS.ScopeSourceId=vEC.EmployeeId AND vEC.StatusId=7
			INNER JOIN sSetup.tOrganizationMaster OM
				ON vEC.OrgId = OM.Id	
			LEFT JOIN sCommon.tAssigneeMaster AM 
				ON AM.Id = OMS.AssigneeId
			WHERE OMS.OnlineMeetingId=@rId AND OMS.ScopeSourceTypeId=95
		SELECT
		OnlineMeetingId, 
		ReferencePath 
		from sEMeeting.tOnlineMeetingReference OMR
		where OMR.OnlineMeetingId = @rId
	END
END TRY
BEGIN CATCH 
		SELECT -1 AS Result
END CATCH
END
GO
PRINT N'Altering Procedure [sEMeeting].[pOnlineMeetingOrganizationGet]...';


GO

ALTER PROCEDURE [sEMeeting].[pOnlineMeetingOrganizationGet]
		@rOrgGroupId int,
		@rUserId bigint 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	BEGIN
	BEGIN TRY
		SELECT 
		UO.Id, 
		UO.DisplayTitle AS Title 
		FROM sSetup.vUserOrganization UO
        WHERE IsObsolete = 0 
		AND OrgGroupId = @rOrgGroupId  
		AND UserId = @rUserId
		ORDER BY OrderIndex
	END TRY
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
	END
GO
PRINT N'Altering Procedure [sEMeeting].[pOnlineMeetingTeacherGet]...';


GO

ALTER PROCEDURE [sEMeeting].[pOnlineMeetingTeacherGet]
	 
	 @rSourceId bigint,
	 @rSourceTypeId int,
	 @rOrgGroupId int,
	 @rOrgId int,
	 @rUserId bigint,
	 @rIsOnlineLearningAdmin bit,
	 @rBatchId int
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
BEGIN
	BEGIN TRY
	If (@rSourceTypeId = 95)
		BEGIN
		if(@rIsOnlineLearningAdmin = 1)
			BEGIN
			SELECT EM.EmployeeId as Id, 
			[sHrm].[fEmployeeNameGet](EM.FirstName , EM.MiddleName, EM.LastName,ISNULL(OrgM.EmployeeNameFormatId,1)) AS Title 
			FROM sHrm.vExtEmployee EM 
			INNER JOIN sSetup.vUserOrganization OM ON OM.Id = EM.OrgId INNER JOIN sSetup.tOrganizationMaster OrgM 
			ON OrgM.Id=EM.OrgId 
			WHERE ISNULL(IsOtherUser,0) = 0 AND  StatusId =7  AND EmployeeGroupId = 1 AND OM.OrgGroupId = @rOrgGroupId AND (OM.Id = @rOrgId or @rOrgId = 0) AND OM.UserId = @rUserId
			ORDER BY Title
			END
		else
			BEGIN
			SELECT EM.EmployeeId as Id, 
			[sHrm].[fEmployeeNameGet](EM.FirstName , EM.MiddleName, EM.LastName,ISNULL(OrgM.EmployeeNameFormatId,1)) AS Title 
			FROM sHrm.vExtEmployee EM 
			INNER JOIN sSetup.tOrganizationMaster OrgM 
			ON OrgM.Id=EM.OrgId 
			WHERE ISNULL(EM.IsOtherUser,0) = 0 AND  EM.StatusId =7  AND EM.EmployeeGroupId = 1 AND  EM.EmployeeId = @rSourceId 
			ORDER BY EmployeeName
			END
		END
	else
		BEGIN
		SELECT DISTINCT EM.Id,ISNULL(EM.FirstName,'') +' ' + ISNULL(EM.MiddleName,'') +' ' + ISNULL(EM.LastName ,'') As Title FROM [sHrm].[tEmployeeMaster] EM
		 INNER JOIN [sAcademic].[tOnlineLearning] OL ON OL.TeacherEmployeeId=EM.Id WHERE OL.BatchId = @rBatchId
		END
	END TRY

	BEGIN CATCH 
		SELECT -1 AS Result
	END CATCH
END
GO
PRINT N'Altering Procedure [sEMeeting].[pOnlineMeetingTeacherStudentListGet]...';


GO

 
ALTER PROCEDURE [sEMeeting].[pOnlineMeetingTeacherStudentListGet]
	 @rId bigint = 0,	 
	 @rScopeSourceId bigint,
	 @rScopeSourceTypeId int,
	 @rMeetingTypeId int = 0,
	 @rStartDate date = '',
	 @rEndDate date = '',
	 @rIsCompleted int= 0,
	 @rTitle nvarchar(100) ='',
	 @rOrgGroupBatchId int
		 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 

	if (@rId = 0)
		BEGIN
	  DECLARE @lAcademicId bigint,@lStudentId bigint,@lClassId int,@lDivisionId int,@lOrgId int,@lDepartmentId int,@lEmployeeId bigint,
	 @lClassName nvarchar(100)


	 SELECT @lAcademicId = A.Id,@lStudentId = A.StudentId,@lClassId = A.ClassId, @lDivisionId = A.DivisionId, @lOrgId= A.OrgId, @lDepartmentId=CM.DepartmentId,
		@lClassName=CM.Title,@lCLassId=CM.Id
     FROM sStudent.tAcademic A INNER JOIN sSetup.tBatchMaster BM ON A.BatchId = BM.Id 
	 INNER JOIN sSetup.tClassMaster CM ON CM.Id = A.ClassId
	 WHERE A.Id = @rScopeSourceId 
	 --AND BM.OrgGroupBatchId = @rOrgGroupBatchId

	 If (@rScopeSourceTypeId = 2003)
	 BEGIN
	
	  SELECT 
			OM.Id,
			OMT.Title AS MeetingType,
			OMT.AutoId AS MeetingTypeId,
			ISNULL(EM.FirstName,'') +' ' + ISNULL(EM.MiddleName,'') +' ' + ISNULL(EM.LastName ,'') AS Teacher,
			CONVERT(NVARCHAR,OM.StartDate,3)+' '+CONVERT(NVARCHAR(5),OM.StartTime,108) as StartDate,
			CONVERT(NVARCHAR,OM.EndDate,3)+' '+CONVERT(NVARCHAR(5),OM.EndTime,108) as EndDate,
			(CASE WHEN OM.IsCompleted=0 THEN 'Pending' WHEN OM.IsCompleted=550 THEN 'Completed'  WHEN OM.IsCompleted=551 THEN 'Cancel' END) AS Status,
			ISNULL(OM.Title,'') AS Title
			
		FROM 
				sEMeeting.tOnlineMeeting OM
				INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id = OM.HostEmployeeId 
				--INNER JOIN sCommon.tDataMaster DM ON DM.Id = OM.MeetingTypeId
				INNER JOIN sEMeeting.tMeetingTypeMaster OMT ON OMT.AutoId = OM.MeetingTypeId
				INNER JOIN sEMeeting.tOnlineMeetingScope OMS ON OMS.OnlineMeetingId = OM.Id
				INNER JOIN (SELECT OMS.OnlineMeetingId FROM sEMeeting.tOnlineMeetingScope OMS
				WHERE (
				( 
				(OMS.ScopeSourceTypeId = 2021 AND OMS.ScopeSourceId =@lOrgId AND OMS.AssigneeId = 2) 
				OR
				(OMS.ScopeSourceTypeId = 2017 AND OMS.ScopeSourceId =@lDepartmentId AND OMS.AssigneeId = 2) OR
				(OMS.ScopeSourceTypeId = 2016 AND OMS.ScopeSourceId =@lClassId AND OMS.AssigneeId = 2) OR
				(OMS.ScopeSourceTypeId = 2005 AND OMS.ScopeSourceId =@lDivisionId AND OMS.AssigneeId = 2) OR
				(OMS.ScopeSourceTypeId = 2003 AND OMS.ScopeSourceId =@lAcademicId AND OMS.AssigneeId = 2) OR
				(OMS.ScopeSourceTypeId = 2001 AND OMS.ScopeSourceId =@lAcademicId AND OMS.AssigneeId = 2)
				 ))
				) D
				ON D.OnlineMeetingId= OM.Id

			WHERE
				(
				(OM.Title like '%' +@rTitle+ '%') OR (ISNULL(@rTitle,'')=''))
				AND (
						(OM.StartDate >= @rStartDate OR ISNULL(@rStartDate, '') = '')
						AND (OM.StartDate <= @rEndDate OR ISNULL(@rEndDate, '') = '')
						OR
						(OM.EndDate >= @rStartDate OR ISNULL(@rStartDate, '') = '')
						AND (OM.EndDate <= @rEndDate OR ISNULL(@rEndDate, '') = '')
					)
				AND ((OM.MeetingTypeId = @rMeetingTypeId)OR (ISNULL(@rMeetingTypeId,0)=0))
				AND ((Convert(int,OM.IsCompleted)=@rIsCompleted) OR (@rIsCompleted = 0)
				)
				ORDER BY OM.IsCompleted,OM.StartDate,OM.StartTime,OM.EndDate
			END
		
	IF (@rScopeSourceTypeId = 95)
	BEGIN 
	DECLARE @lOrgId1 int,@lDepartmentId1 int,@lEmployeeId1 bigint
	 SELECT @lOrgId1 = EC.OrgId, @lDepartmentId1 =EC.DepartmentId, @lEmployeeId1 = EC.EmployeeId
     FROM sHrm.vEmployeeCommunication EC
	 WHERE EC.Id = @rScopeSourceId
		SELECT 
			OM.Id,
			OMT.Title AS MeetingType,
			CONVERT(NVARCHAR,OM.StartDate,103)+' '+CONVERT(NVARCHAR(5),OM.StartTime,108) as StartDate,
			CONVERT(NVARCHAR,OM.EndDate,103)+' '+CONVERT(NVARCHAR(5),OM.EndTime,108) as EndDate,
			(CASE WHEN OM.IsCompleted=0 THEN 'Pending' WHEN OM.IsCompleted=550 THEN 'Completed'  WHEN OM.IsCompleted=551 THEN 'Cancel' END) AS Status,
			ISNULL(OM.Title,'') As Title,
			OM.StartDate AS TeacherStartDateTime,
			OM.EndDate AS TeacherEndDateTime
			FROM 
				sEMeeting.tOnlineMeeting OM
				INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id = OM.HostEmployeeId
				INNER JOIN sEMeeting.tMeetingTypeMaster OMT ON OMT.AutoId = OM.MeetingTypeId
				INNER JOIN (SELECT OMS.OnlineMeetingId FROM sEMeeting.tOnlineMeetingScope OMS
				WHERE (
				( 
				(OMS.ScopeSourceTypeId = 2021 AND OMS.ScopeSourceId =@lOrgId1 AND OMS.AssigneeId = 3) 
				OR
				(OMS.ScopeSourceTypeId = 2017 AND OMS.ScopeSourceId =@lDepartmentId1 AND OMS.AssigneeId = 3)
				OR
				(OMS.ScopeSourceTypeId = 95 AND OMS.ScopeSourceId =@lEmployeeId1 AND OMS.AssigneeId = 3)
				 ))
				) D
				ON D.OnlineMeetingId= OM.Id OR (OM.HostEmployeeId = @rScopeSourceId)
			WHERE
			(
			    (OM.MeetingTypeId = @rMeetingTypeId OR @rMeetingTypeId = 0)
			    AND (
			        (OM.StartDate >= @rStartDate OR ISNULL(@rStartDate, '') = '')
			        AND (OM.StartDate <= @rEndDate OR ISNULL(@rEndDate, '') = '')
			        OR
			        (OM.EndDate >= @rStartDate OR ISNULL(@rStartDate, '') = '')
			        AND (OM.EndDate <= @rEndDate OR ISNULL(@rEndDate, '') = '')
			    )
			    AND (Convert(int, OM.IsCompleted) = @rIsCompleted OR @rIsCompleted = 0)
			    AND (OM.Title LIKE '%' + @rTitle + '%' OR ISNULL(@rTitle, '') = '')
			)
			ORDER BY
			    OM.StartDate, OM.StartTime ASC;

		END
		END
	ELSE
	IF (@rScopeSourceTypeId = 2003)
	BEGIN 

	 DECLARE @lAcademicId2 bigint,@lStudentId2 bigint,@lClassId2 int,@lDivisionId2 int,@lOrgId2 int,@lDepartmentId2 int,@lEmployeeId2 bigint,
	 @lClassName2 nvarchar(100)


	 SELECT @lAcademicId = A.Id,@lStudentId = A.StudentId,@lClassId = A.ClassId, @lDivisionId = A.DivisionId, @lOrgId= A.OrgId, @lDepartmentId=CM.DepartmentId,
	 @lClassName=CM.Title,@lCLassId=CM.Id
     FROM sStudent.tAcademic A INNER JOIN sSetup.tBatchMaster BM
	 ON A.BatchId = BM.Id 
	INNER JOIN sSetup.tClassMaster CM ON CM.Id = A.ClassId
 WHERE A.Id = @rScopeSourceId 
 --AND BM.OrgGroupBatchId = @rOrgGroupBatchId



	SELECT
			OM.Id,
			OMT.Title AS MeetingType,
			ISNULL(EM.FirstName,'') +' ' + ISNULL(EM.MiddleName,'') +' ' + ISNULL(EM.LastName ,'')  AS Teacher,
			CONVERT(NVARCHAR,OM.StartDate,103)+' '+CONVERT(NVARCHAR(5),OM.StartTime,108) as StartTime,
			CONVERT(NVARCHAR,OM.EndDate,103)+' '+CONVERT(NVARCHAR(5),OM.EndTime,108) as EndTime,
			(CASE WHEN OM.IsCompleted=0 THEN 'Pending' WHEN OM.IsCompleted=550 THEN 'Completed'  WHEN OM.IsCompleted=551 THEN 'Cancel' END) AS Status,
			OM.MeetingTypeId AS MeetingTypeId,
			OM.IsDisplayMeetingId AS IsDisplayMeetingId,
			OM.MeetingId AS MeetingId,
			OM.MeetingPassword AS MeetingPassword,
			ISNULL(OM.IsMeetingStarted,'') AS IsMeetingStarted,
			OM.IsCompleted AS IsCompleted,
			ISNULL(OM.Description,'')AS Description,
			ISNULL(OM.Title,'') AS Title,
			ISNULL(OM.IsMeetingStarted,'') AS IsMeetingStarted,
			OM.IsMeetingCreated AS IsMeetingCreated,
			OM.IsReference,
			OM.IsResource
          FROM 
				sEMeeting.tOnlineMeeting OM
				
				INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id = OM.HostEmployeeId 
				INNER JOIN sEMeeting.tMeetingTypeMaster OMT ON OMT.AutoId = OM.MeetingTypeId
				INNER JOIN (SELECT OMS.OnlineMeetingId FROM sEMeeting.tOnlineMeetingScope OMS
				WHERE (
				( 
				(OMS.ScopeSourceTypeId = 2021 AND OMS.ScopeSourceId =@lOrgId AND OMS.AssigneeId = 2) 
				OR
				(OMS.ScopeSourceTypeId = 2017 AND OMS.ScopeSourceId =@lDepartmentId AND OMS.AssigneeId = 2) OR
				(OMS.ScopeSourceTypeId = 2016 AND OMS.ScopeSourceId =@lClassId AND OMS.AssigneeId = 2) OR
				(OMS.ScopeSourceTypeId = 2005 AND OMS.ScopeSourceId =@lDivisionId AND OMS.AssigneeId = 2) OR
				(OMS.ScopeSourceTypeId = 2003 AND OMS.ScopeSourceId =@lAcademicId AND OMS.AssigneeId = 2) OR
				(OMS.ScopeSourceTypeId = 2001 AND OMS.ScopeSourceId =@lAcademicId AND OMS.AssigneeId = 2)
				 ))
				) D
				ON D.OnlineMeetingId= OM.Id

            
            WHERE
				 OM.Id = @rId

				ORDER BY OM.IsCompleted,OM.StartDate,OM.EndDate
				SELECT 1 from sEMeeting.tOnlineMeetingScope where OnlineMeetingId = @rId
				SELECT
				OnlineMeetingId, 
				ReferencePath 
				from sEMeeting.tOnlineMeetingReference OMR
				where OMR.OnlineMeetingId = @rId
		END
		
		IF(@rScopeSourceTypeId = 95)
		BEGIN
		SELECT 
			OM.Id,
			OMT.Title AS MeetingType,
			ISNULL(EM.FirstName,'') +' ' + ISNULL(EM.MiddleName,'') +' ' + ISNULL(EM.LastName ,'')  AS Teacher,
			CONVERT(NVARCHAR,OM.StartDate,103)+' '+CONVERT(NVARCHAR(5),OM.StartTime,108) as StartTime,
			CONVERT(NVARCHAR,OM.EndDate,103)+' '+CONVERT(NVARCHAR(5),OM.EndTime,108) as EndTime,
			(CASE WHEN OM.IsCompleted=0 THEN 'Pending' WHEN OM.IsCompleted=550 THEN 'Completed'  WHEN OM.IsCompleted=551 THEN 'Cancel' END) AS Status,
			OM.MeetingTypeId AS MeetingTypeId,
			OM.IsDisplayMeetingId AS IsDisplayMeetingId,
			OM.MeetingId AS MeetingId,
			OM.MeetingPassword AS MeetingPassword,
			OM.IsCompleted AS IsCompleted,
			ISNULL(OM.Title,'') AS Title,
			ISNULL(OM.Description,'')AS Description,
			ISNULL(OM.IsMeetingStarted,'') AS IsMeetingStarted,
			OM.IsMeetingCreated AS IsMeetingCreated,
			OM.IsTrackAttendance AS IsTrackAttendance,
			OM.IsReference,
			OM.IsResource,
			OM.HostEmployeeId
		FROM 
				sEMeeting.tOnlineMeeting OM
				INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id = OM.HostEmployeeId
				INNER JOIN sEMeeting.tMeetingTypeMaster OMT ON OMT.AutoId = OM.MeetingTypeId
				INNER JOIN sEMeeting.tOnlineMeetingScope OMS ON OMS.OnlineMeetingId = OM.Id
		WHERE
			 OM.Id = @rId
			ORDER BY OM.CreatedDateTime
		SELECT
			 OMS.OnlineMeetingId,
			 OMS.ScopeSourceTypeId,
			 OMS.ScopeSourceId,
			 OM.DisplayTitle AS Source,
			 'Organization' AS SourceType,
			 '' AS ROllNo,
             '' AS Code,
             '' AS ClassDepartment,
             OM.DisplayTitle AS OrgName,
			 OMS.AssigneeId
			FROM sEMeeting.tOnlineMeetingScope OMS
			INNER JOIN sSetup.tOrganizationMaster OM
				ON OMS.ScopeSourceId=OM.Id
			LEFT JOIN sCommon.tAssigneeMaster AM 
				ON AM.Id = OMS.AssigneeId
			WHERE OMS.OnlineMeetingId=@rId AND OMS.ScopeSourceTypeId=2021

			UNION ALL

			SELECT
			 OMS.OnlineMeetingId,
			 OMS.ScopeSourceTypeId,
			 OMS.ScopeSourceId,
			 DM.DisplayTitle AS Source,
			 'Department' AS SourceType,
			 '' AS ROllNo,
             '' AS Code,
             DM.Title AS ClassDepartment,
             OM.DisplayTitle AS OrgName,
			 OMS.AssigneeId
			FROM sEMeeting.tOnlineMeetingScope OMS
			INNER JOIN sSetup.tDepartmentMaster DM
				ON OMS.ScopeSourceId=DM.Id
			INNER JOIN sSetup.tOrganizationMaster OM
				ON DM.OrgId=OM.Id
			LEFT JOIN sCommon.tAssigneeMaster AM 
				ON AM.Id = OMS.AssigneeId 
			WHERE OMS.OnlineMeetingId=@rId AND OMS.ScopeSourceTypeId=2017

			UNION ALL

			SELECT
			 OMS.OnlineMeetingId,
			 OMS.ScopeSourceTypeId,
			 OMS.ScopeSourceId,
			 CM.DisplayTitle AS Source,
			 'Class' AS SourceType,
			 '' AS ROllNo,
             '' AS Code,
             DMast.Title AS ClassDepartment,
             OM.DisplayTitle AS OrgName,
			 OMS.AssigneeId
			FROM sEMeeting.tOnlineMeetingScope OMS
			INNER JOIN  sSetup.tClassMaster CM
				ON OMS.ScopeSourceId=CM.Id
			INNER JOIN sSetup.tDepartmentMaster DMast
				ON CM.DepartmentId =DMast.Id		
			INNER JOIN sSetup.tOrganizationMaster OM
				ON DMast.OrgId=OM.Id
			LEFT JOIN sCommon.tAssigneeMaster AM 
				ON AM.Id = OMS.AssigneeId
			WHERE OMS.OnlineMeetingId=@rId AND OMS.ScopeSourceTypeId=2016

			UNION ALL

			SELECT
			 OMS.OnlineMeetingId,
			 OMS.ScopeSourceTypeId,
			 OMS.ScopeSourceId,
			 DM.Code AS Source,
			 'Division' AS SourceType,
			 '' AS ROllNo,
             '' AS Code,
             DMast.Title AS ClassDepartment,
             OM.DisplayTitle AS OrgName,
			 OMS.AssigneeId
			FROM sEMeeting.tOnlineMeetingScope OMS
			INNER JOIN   sSetup.tDivisionMaster DM
				ON OMS.ScopeSourceId=DM.Id
			INNER JOIN 	sSetup.tClassMaster CM
				ON DM.ClassId=CM.Id	
			INNER JOIN sSetup.tDepartmentMaster DMast
				ON CM.DepartmentId =DMast.Id
			INNER JOIN sSetup.tOrganizationMaster OM
				ON DMast.OrgId=OM.Id
			LEFT JOIN sCommon.tAssigneeMaster AM 
				ON AM.Id = OMS.AssigneeId	
				WHERE OMS.OnlineMeetingId=@rId AND OMS.ScopeSourceTypeId=2005

			UNION ALL
			
			SELECT
			 OMS.OnlineMeetingId,
			 OMS.ScopeSourceTypeId,
			 OMS.ScopeSourceId,
			 [sStudent].[fStudentNameGet](SM.FirstName , SM.MiddleName, SM.LastName,OM.StudentNameFormatId ) AS Source,
			 'Student' AS SourceType,
			 SA.ROllNo,
             SA.Code,
             SA.ClassName+' - '+SA.DivisionName AS ClassDepartment,
             OM.DisplayTitle AS OrgName,
			 OMS.AssigneeId
			FROM sEMeeting.tOnlineMeetingScope OMS
		    INNER JOIN sStudent.tStudentMaster SM
				ON OMS.ScopeSourceId=SM.Id
			INNER JOIN  sStudent.vStudentAcademic SA
				ON OMS.ScopeSourceId=SA.StudentId AND SA.IsActiveBatch=1 AND SA.StatusId=1		
			INNER JOIN sSetup.tOrganizationMaster OM
				ON SM.OrgId = OM.Id
			LEFT JOIN sCommon.tAssigneeMaster AM 
				ON AM.Id = OMS.AssigneeId
			WHERE OMS.OnlineMeetingId=@rId AND OMS.ScopeSourceTypeId=2003
			
			UNION ALL
			
			SELECT
			 OMS.OnlineMeetingId,
			 OMS.ScopeSourceTypeId,
			 OMS.ScopeSourceId,
			 SA.Name AS Source,
			 'Student' AS SourceType,
			 SA.ROllNo,
             SA.Code,
             SA.ClassName+' - '+SA.DivisionName AS ClassDepartment,
             OM.DisplayTitle AS OrgName,
			 OMS.AssigneeId
			FROM sEMeeting.tOnlineMeetingScope OMS
		   	INNER JOIN  sStudent.vStudentAcademic SA
				ON OMS.ScopeSourceId=SA.AcademicId AND SA.IsActiveBatch=1 AND SA.StatusId=1
			INNER JOIN sSetup.tOrganizationMaster OM
				ON SA.OrgId = OM.Id
			LEFT JOIN sCommon.tAssigneeMaster AM 
				ON AM.Id = OMS.AssigneeId	
			WHERE OMS.OnlineMeetingId=@rId AND OMS.ScopeSourceTypeId=2001
			
			UNION ALL
			
			SELECT
			 OMS.OnlineMeetingId,
			 OMS.ScopeSourceTypeId,
			 OMS.ScopeSourceId,
			 vEC.FirstName +' '+ vEC.LastName AS Source,
			 'Employee' AS SourceType,
			 '' AS ROllNo,
             vEC.Code,
             vEC.DepartmentName AS ClassDepartment,
             OM.DisplayTitle AS OrgName,
			 OMS.AssigneeId
			FROM sEMeeting.tOnlineMeetingScope OMS
			INNER JOIN sHrm.vEmployeeCommunication vEC 
				ON OMS.ScopeSourceId=vEC.EmployeeId AND vEC.StatusId=7
			INNER JOIN sSetup.tOrganizationMaster OM
				ON vEC.OrgId = OM.Id
			LEFT JOIN sCommon.tAssigneeMaster AM 
				ON AM.Id = OMS.AssigneeId
			WHERE OMS.OnlineMeetingId=@rId AND OMS.ScopeSourceTypeId=95
		SELECT
		OnlineMeetingId, 
		ReferencePath 
		from sEMeeting.tOnlineMeetingReference OMR
		where OMR.OnlineMeetingId = @rId
			END
		
END
GO
PRINT N'Altering Procedure [sFee].[pRptFeeReceiptDetailListGet]...';


GO
ALTER PROCEDURE [sFee].[pRptFeeReceiptDetailListGet]  
  @rReportId int,  
  @rReceiptBookId int,  
  @rAdmissionCategoryId int,  
  @rClassId int,  
  @rDivisionId int,  
  @rFromDate date,  
  @rToDate date,  
  @rFromReceiptNo int,  
  @rToReceiptNo int,  
  @rBatchId int,  
  @rUserId bigint,  
  @rBuilder1 nvarchar(max),  
  @rBuilder2 nvarchar(max),  
  @rIsCancel bit,  
  @rOrgId int,  
  @rOrgGroupBatchId int,  
  @rStatusId int,  
  @rCommonBatch nvarchar(100),  
  @rDepartmentId int,  
  @rFromRollNo int,  
     @rToRollNo int,  
     @rCode nvarchar(20),  
     @rIsDetail bit=0,  
  @rIsFilter bit,  
  @rIsHeader bit,  
  @rCreatedUserName nvarchar(100)='',  
  @rFeeHeadId nvarchar(max) = '',  
  @rIsDisplayOrgGroup bit=0,  
  @rPayTypeId int=0,  
  @rFeeId nvarchar(max) = '',  
  @rFilterId int=0,
  @rOrgIds nvarchar(max) = '',
  @rClassStatusId int=0,
  @rPayTypeIds nvarchar(max) = '' ,
  @rBankName nvarchar(200)='' ,
  @rUserAcessUserId bigint = 0  
  
 WITH EXECUTE AS CALLER  
AS  
SET NOCOUNT ON  
      
BEGIN  
SET @rBankName = sCommon.fSearchStringGet(@rBankName)  
IF(@rReportId=10145)
	BEGIN
	SELECT   
  @rBuilder1 AS Builder1,  
  @rBuilder2 AS Builder2,  
  @rIsCancel AS IsCancel,  
  @rIsDetail AS IsDetail,  
  @rIsFilter As IsFilter,  
  @rIsHeader As IsHeader,  
  @rIsDisplayOrgGroup AS IsDisplayOrgGroup,  
  R.Id AS ReceiptId,  
  R.ReceiptNumber,  
  SA.ClassId,  
  SA.ClassName,  
  SA.DivisionId,  
  SA.DivisionName,  
  SA.ClassName+' - '+SA.DivisionName AS ClassDivision,  
  SA.RollNo,  
  SA.AcademicId,  
  SA.FirstName,  
  SA.MiddleName,  
  SA.LastName,  
  SA.Code,  
  SA.Name,  
  PTM.Title AS PayType,  
  --R.ChequeNo,  
  CASE WHEN ISNULL(R.ChequeNo,'') != '' THEN R.ChequeNo ELSE CONVERT(nvarchar(20),R.PaymentTransactionId) END AS ChequeNo,
  R.BankName,  
  --R.ReceiptAmount,  ,
  CASE WHEN ROW_NUMBER() OVER (PARTITION BY R.Id  ORDER BY R.Id ) =1 THEN R.ReceiptAmount ELSE 0 END AS ReceiptAmount,
  R.ReceiptDate,  
  FM.Title AS FeeDetail,  
  FM.Code AS FeeCode,  
  FM.OrderIndex AS FeeOrderIndex,  
  RD.Amount AS DetailAmount,  
  ISNULL(R.ReceiptBookId,'0') As ReceiptBookId,  
  ISNULL(RBM.Title,'') AS ReceiptBookTitle,  
  ISNULL(RBM.OrderIndex,0) AS ReceiptOrderIndex,  
  ISNULL(FHM.Title,'') AS FeeHead,  
  ISNULL(FHM.Code,'') AS FeeHeadCode,  
  ISNULL(FHM.OrderIndex,0) AS FeeHeadOrderIndex,  
  SA.OrgId,  
  O.DisplayTitle AS OrgName,  
  O.OrderIndex AS OrgOrderIndex,  
  ISNULL(R.Remark,'') AS Remark,  
  DM.Id AS DepartmentId,  
  DM.Title AS DepartmentName,  
  SA.ClassOrderIndex,  
  ISNULL(SO.GenderId,0) AS GenderId,  
  ISNULL(SA.BatchName,'') BatchName,  
  ISNULL(FM.FeeHeadId,0) AS FeeHeadId,  
  sFinanceCommon.fNumberToWordsWithDecimal(ISNULL(R.ReceiptAmount,0.00),1,2,O.OrgGroupId) AS ReceiptAmountInWords,  
  R.ChequeDate,  
  ISNULL(FM.Id,0) AS FeeId,  
  ISNULL(FM.Title,'') AS Fee,  
  ISNULL(SF.FatherName,'' ) AS FatherName,  
  ISNULL(SF.MotherName,'' ) AS MotherName,
  CASE WHEN ROW_NUMBER() OVER (PARTITION BY R.Id  ORDER BY R.Id ) =1 THEN R.DiscountAmount ELSE 0 END AS Discount,
  RD.Amount AS PaidAmount,
  ISNULL(DM.OrderIndex,0) as DepartmentOrderIndex,
  PTM.Id AS PayTypeId,
  ISNULL(SA.SUID,'') AS SUID,
  ISNULL(U.DisplayTitle,'') AS CreatedUser
  ,TBM.FromDate AS FromDate
  ,TBM.ToDate AS ToDate
  FROM   
   sFee.tReceipt R  
  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.tReceiptDetail RD  
   ON RD.ReceiptId=R.Id  
  INNER JOIN sFee.tFeeSetup FS  
   ON FS.Id=RD.FeeSetupId  
  INNER JOIN sFee.tFeeMaster FM  
   ON FM.Id=FS.FeeId  
  INNER JOIN sFee.tFeeHeadMaster FHM  
   ON FHM.Id=FM.FeeHeadId  
  INNER JOIN sFee.tReceiptBookMaster RBM   
   ON RBM.Id=R.ReceiptBookId  
  INNER JOIN sSetup.tDepartmentMaster DM  
   ON SA.DepartmentId=DM.Id  
  INNER JOIN sSetup.tOrganizationMaster O  
   ON O.Id=sa.OrgId 
    --for UserAccess Wise (in ReceiptListFeeHeadHeadwise report)
  INNER JOIN sSecurity.tUserOrganization UO ON UO.OrgId=SA.OrgId AND O.IsObsolete=0 AND UO.UserId=@rUserAcessUserId  
 
  LEFT JOIN sStudent.tStudentOther SO  
   ON SO.StudentId = SA.StudentId  
  LEFT JOIN sStudent.tStudentFamily SF  
   ON SF.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))   
 INNER JOIN sSetup.tBatchMaster TBM ON TBM.Id=R.BatchId AND ((TBM.OrgId=@rOrgId) OR (@rOrgId=0))
 INNER JOIN [sSecurity].[tUser] U ON U.Id=R.CreatedUserId
WHERE   
 R.SourceTypeId = 2001  
 AND ((SA.AdmissionCategoryId = @rAdmissionCategoryId) OR (@rAdmissionCategoryId = 0))  
 AND ((SA.ClassId = @rClassId) OR (@rClassId = 0))  
 AND ((SA.DivisionId = @rDivisionId) OR (@rDivisionId = 0))  
 AND ((R.ReceiptBookId = @rReceiptBookId) OR (@rReceiptBookId = 0))  
 AND ((R.ReceiptNumber >= @rFromReceiptNo) OR (@rFromReceiptNo = 0))  
 AND ((R.ReceiptNumber <= @rToReceiptNo) OR (@rToReceiptNo = 0))  
 AND ((R.ReceiptDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))  
 AND ((R.ReceiptDate <= @rToDate) OR (ISNULL(@rToDate,'') = ''))  
 AND (SA.OrgGroupBatchId = @rOrgGroupBatchId)  
 AND ((SA.OrgId=@rOrgId) OR (@rOrgId=0))  
 AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))  
 AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))  
 AND (R.IsObsolete = @rIsCancel)   
 AND (SA.StatusId = @rStatusId OR @rStatusId=0)  
 AND ((SA.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))  
 AND ((SA.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))  
 AND ((SA.RollNo <= @rToRollNo) OR (@rToRollNo=0))  
 AND ((SA.Code=@rCode) OR (@rCode=''))  
 AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))  
 --AND ((ISNULL(U.LoginTitle,'') like @rCreatedUserName) OR (ISNULL(@rCreatedUserName,'')=''))  
 AND (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 ((R.PayTypeId=@rPayTypeId) OR (@rPayTypeId=0))  
 AND (  
  (@rFilterId = 0) -- All  
     OR (@rFilterId = 2 AND isnull(AR.SourceId,0)!=0) -- Hostel  
     OR (@rFilterId = 3 AND isnull(RT.SourceId,0)!=0) -- Transport  
     OR ((@rFilterId =1) AND ((isnull(AR.SourceId,0)=0) AND (isnull(RT.SourceId,0)=0)))  
   )  
  AND (ISNULL(SA.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')
  	 AND ((SA.ClassStatusId=@rClassStatusId) OR (@rClassStatusId=0))
	AND (ISNULL(R.PayTypeId,0) IN (SELECT cast(item as tinyint) FROM sCommon.fnsplit(@rPayTypeIds,',')) OR @rPayTypeIds='')   
	AND ((UPPER(R.BankName) like UPPER(@rBankName)) OR(ISNULL(@rBankName,'')=''))    
 ORDER BY R.ReceiptNumber  
	END

ELSE
	BEGIN
	SELECT   
  @rBuilder1 AS Builder1,  
  @rBuilder2 AS Builder2,  
  @rIsCancel AS IsCancel,  
  @rIsDetail AS IsDetail,  
  @rIsFilter As IsFilter,  
  @rIsHeader As IsHeader,  
  @rIsDisplayOrgGroup AS IsDisplayOrgGroup,  
  R.Id AS ReceiptId,  
  R.ReceiptNumber,  
  SA.ClassId,  
  SA.ClassName,  
  SA.DivisionId,  
  SA.DivisionName,  
  SA.ClassName+' - '+SA.DivisionName AS ClassDivision,  
  SA.RollNo,  
  SA.AcademicId,  
  SA.FirstName,  
  SA.MiddleName,  
  SA.LastName,  
  SA.Code,  
  SA.Name,  
  PTM.Title AS PayType,  
  --R.ChequeNo,  
  CASE WHEN ISNULL(R.ChequeNo,'') != '' THEN R.ChequeNo ELSE CONVERT(nvarchar(20),R.PaymentTransactionId) END AS ChequeNo,
  R.BankName,  
  --R.ReceiptAmount,  ,
  CASE WHEN ROW_NUMBER() OVER (PARTITION BY R.Id  ORDER BY R.Id ) =1 THEN R.ReceiptAmount ELSE 0 END AS ReceiptAmount,
  R.ReceiptDate,  
  FM.Title AS FeeDetail,  
  FM.Code AS FeeCode,  
  FM.OrderIndex AS FeeOrderIndex,  
  RD.Amount AS DetailAmount,  
  ISNULL(R.ReceiptBookId,'0') As ReceiptBookId,  
  ISNULL(RBM.Title,'') AS ReceiptBookTitle,  
  ISNULL(RBM.OrderIndex,0) AS ReceiptOrderIndex,  
  ISNULL(FHM.Title,'') AS FeeHead,  
  ISNULL(FHM.Code,'') AS FeeHeadCode,  
  ISNULL(FHM.OrderIndex,0) AS FeeHeadOrderIndex,  
  SA.OrgId,  
  O.DisplayTitle AS OrgName,  
  O.OrderIndex AS OrgOrderIndex,  
  ISNULL(R.Remark,'') AS Remark,  
  DM.Id AS DepartmentId,  
  DM.Title AS DepartmentName,  
  SA.ClassOrderIndex,  
  ISNULL(SO.GenderId,0) AS GenderId,  
  ISNULL(SA.BatchName,'') BatchName,  
  ISNULL(FM.FeeHeadId,0) AS FeeHeadId,  
  sFinanceCommon.fNumberToWordsWithDecimal(ISNULL(R.ReceiptAmount,0.00),1,2,O.OrgGroupId) AS ReceiptAmountInWords,  
  R.ChequeDate,  
  ISNULL(FM.Id,0) AS FeeId,  
  ISNULL(FM.Title,'') AS Fee,  
  ISNULL(SF.FatherName,'' ) AS FatherName,  
  ISNULL(SF.MotherName,'' ) AS MotherName,
  CASE WHEN ROW_NUMBER() OVER (PARTITION BY R.Id  ORDER BY R.Id ) =1 THEN R.DiscountAmount ELSE 0 END AS Discount,
  RD.Amount AS PaidAmount,
  ISNULL(DM.OrderIndex,0) as DepartmentOrderIndex,
  PTM.Id AS PayTypeId,
  ISNULL(SA.SUID,'') AS SUID
  ,ISNULL(U.DisplayTitle,'NA') AS CreatedUser
  ,TBM.FromDate AS FromDate
  ,TBM.ToDate AS ToDate
  FROM   
   sFee.tReceipt R  
  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.tReceiptDetail RD  
   ON RD.ReceiptId=R.Id  
  INNER JOIN sFee.tFeeSetup FS  
   ON FS.Id=RD.FeeSetupId  
  INNER JOIN sFee.tFeeMaster FM  
   ON FM.Id=FS.FeeId  
  INNER JOIN sFee.tFeeHeadMaster FHM  
   ON FHM.Id=FM.FeeHeadId  
  INNER JOIN sFee.tReceiptBookMaster RBM   
   ON RBM.Id=R.ReceiptBookId  
  INNER JOIN sSetup.tDepartmentMaster DM  
   ON SA.DepartmentId=DM.Id  
  INNER JOIN sSetup.tOrganizationMaster O  
   ON O.Id=sa.OrgId 
  LEFT JOIN [sSecurity].[tUser] U ON U.Id=R.CreatedUserId -- Change innerjoin to left join for mantis id :0029242
  LEFT JOIN sStudent.tStudentOther SO  
   ON SO.StudentId = SA.StudentId  
  LEFT JOIN sStudent.tStudentFamily SF  
   ON SF.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))  
 INNER JOIN sSetup.tBatchMaster TBM ON TBM.Id=R.BatchId AND ((TBM.OrgId=@rOrgId) OR (@rOrgId=0))
WHERE   
 R.SourceTypeId = 2001  
 AND ((SA.AdmissionCategoryId = @rAdmissionCategoryId) OR (@rAdmissionCategoryId = 0))  
 AND ((SA.ClassId = @rClassId) OR (@rClassId = 0))  
 AND ((SA.DivisionId = @rDivisionId) OR (@rDivisionId = 0))  
 AND ((R.ReceiptBookId = @rReceiptBookId) OR (@rReceiptBookId = 0))  
 AND ((R.ReceiptNumber >= @rFromReceiptNo) OR (@rFromReceiptNo = 0))  
 AND ((R.ReceiptNumber <= @rToReceiptNo) OR (@rToReceiptNo = 0))  
 AND ((R.ReceiptDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))  
 AND ((R.ReceiptDate <= @rToDate) OR (ISNULL(@rToDate,'') = ''))  
 AND (SA.OrgGroupBatchId = @rOrgGroupBatchId)  
 AND ((SA.OrgId=@rOrgId) OR (@rOrgId=0))  
 AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))  
 AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))  
 AND (R.IsObsolete = @rIsCancel)   
 AND (SA.StatusId = @rStatusId OR @rStatusId=0)  
 AND ((SA.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))  
 AND ((SA.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))  
 AND ((SA.RollNo <= @rToRollNo) OR (@rToRollNo=0))  
 AND ((SA.Code=@rCode) OR (@rCode=''))  
 AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))  
 AND ((ISNULL(U.LoginTitle,'') like @rCreatedUserName) OR (ISNULL(@rCreatedUserName,'')=''))  
 AND (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 ((R.PayTypeId=@rPayTypeId) OR (@rPayTypeId=0))  
 AND (  
  (@rFilterId = 0) -- All  
     OR (@rFilterId = 2 AND isnull(AR.SourceId,0)!=0) -- Hostel  
     OR (@rFilterId = 3 AND isnull(RT.SourceId,0)!=0) -- Transport  
     OR ((@rFilterId =1) AND ((isnull(AR.SourceId,0)=0) AND (isnull(RT.SourceId,0)=0)))  
   )  
  AND (ISNULL(SA.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')
  	 AND ((SA.ClassStatusId=@rClassStatusId) OR (@rClassStatusId=0))
	AND (ISNULL(R.PayTypeId,0) IN (SELECT cast(item as tinyint) FROM sCommon.fnsplit(@rPayTypeIds,',')) OR @rPayTypeIds='')   
	AND ((UPPER(R.BankName) like UPPER(@rBankName)) OR(ISNULL(@rBankName,'')=''))    
 ORDER BY R.ReceiptNumber  
	END
 --ORDER BY R.Id 
-- UNION ALL  
   
-- SELECT   
--  R.Id AS ReceiptId,  
--  0 AS ClassId,  
--  --SA.ClassName,  
--  0 AS DivisionId,  
--  --SA.DivisionName,  
--  EM.DepartmentId,  
--  EM.DepartmentName AS ClassDept,  
--  0 AS RollNo,  
--  EM.Code,  
--  EM.EmployeeName,  
--  PTM.Title AS PayType,  
--  R.ReceiptAmount  
     
--  FROM   
--   sFee.tReceipt R  
--  INNER JOIN sCommon.tSourceTypeMaster STM  
--   ON STM.Id=R.SourceTypeId AND R.SourceTypeId = 95  
--  INNER JOIN sHrm.vExtEmployeeMaster EM  
--   ON EM.EmployeeId=R.SourceId  
--  INNER JOIN sFinanceCommon.tPayTypeMaster PTM  
--   ON PTM.Id=R.PayTypeId  
     
--WHERE   
--  ((EM.DepartmentId = @rDepartmentId) OR (@rDepartmentId = 0))  
-- AND ((R.ReceiptNumber >= @rFromReceiptNo) OR (@rFromReceiptNo = 0))  
-- AND ((R.ReceiptNumber <= @rToReceiptNo) OR (@rToReceiptNo = 0))  
-- AND ((R.ReceiptDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))  
-- AND ((R.ReceiptDate <= @rToDate) OR (ISNULL(@rToDate,'') = ''))  
-- AND (R.BatchId = @rBatchId)  
END
GO
PRINT N'Altering Procedure [sFee].[pRptFeeReceiptDetailsGet]...';


GO

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

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

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

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

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

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


GO
ALTER PROCEDURE [sHrm].[pMISEmployeeSummaryDashboardGet]

	@rTypeId int=0,
	@rFilterType nvarchar(50)='',
	@rOrgGroupId smallint=0,
	@rOrgSubGroupId int=0,
	@rOrgId int=0,
	@rStatusId int=0,
	@rGenderId int=0,
	@rEmployeeGroupId int=0
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON			 
BEGIN 
  
------------1
	IF(@rTypeId = 1)
	BEGIN
		IF(@rFilterType = 'Statuswise')--Statuswise (Total/Active)
		BEGIN
			SELECT 
				 OSGM.Id As OrgSubGroupId		
				,OSGM.Title As OrgSubGroupName
				,COUNT(EM.Code) As Total
				,COUNT(AEM.Code) as Active
			FROM
				sSetup.tOrgSubGroupMaster OSGM
				INNER JOIN sSetup.tOrgGroupMaster OGM ON OGM.Id = OSGM.OrgGroupId
				LEFT JOIN sSetup.tOrganizationMaster OM ON OM.OrgSubGroupId = OSGM.Id
			    LEFT JOIN sHrm.tEmployeeMaster EM ON EM.OrgId = OM.Id
				LEFT JOIN (SELECT EM1.Code As Code FROM sHrm.tEmployeeMaster EM1 
				WHERE EM1.StatusId = 7 AND ISNULL(EM1.IsOtherUser,0) = 0  Group By EM1.Code) AEM ON  EM.Code = AEM.Code
			WHERE OGM.Id != 1 AND ISNULL(OGM.IsObsolete,0) = 0 AND OGM.Id = @rOrgGroupId
			Group By OSGM.Id,OSGM.Title
			Order By OrgSubGroupName
		END
		ELSE IF(@rFilterType = 'Genderwise')--Genderwise
		BEGIN
		 SELECT 
				 OSGM.Id As OrgSubGroupId		
				,OSGM.Title As OrgSubGroupName
				,COUNT(Male.Code) as Male
				,COUNT(Female.Code) as Female
				,COUNT(EM.Code) as Total
			FROM
				sSetup.tOrgSubGroupMaster OSGM
				INNER JOIN sSetup.tOrgGroupMaster OGM ON OGM.Id = OSGM.OrgGroupId
				LEFT JOIN sSetup.tOrganizationMaster OM ON OM.OrgSubGroupId = OSGM.Id
				LEFT JOIN sHrm.tEmployeeMaster EM ON EM.OrgId = OM.Id AND EM.StatusId = 7 AND ISNULL(EM.IsOtherUser,0) = 0 
				LEFT JOIN (SELECT EM1.Code As Code FROM sHrm.tEmployeeMaster EM1 
					INNER JOIN sHrm.tEmployeePersonalDetail EPD ON EPD.EmployeeId = EM1.Id
					WHERE EM1.StatusId = 7 AND ISNULL(EM1.IsOtherUser,0) = 0  AND EPD.GenderId = 1 Group By EM1.Code) Male ON  EM.Code = Male.Code
				LEFT JOIN (SELECT EM1.Code As Code FROM sHrm.tEmployeeMaster EM1 
					INNER JOIN sHrm.tEmployeePersonalDetail EPD ON EPD.EmployeeId = EM1.Id
					WHERE EM1.StatusId = 7 AND ISNULL(EM1.IsOtherUser,0) = 0  AND EPD.GenderId = 2 Group By EM1.Code) Female ON  EM.Code = Female.Code
			WHERE ((OGM.Id = @rOrgGroupId) OR (@rOrgGroupId = 0)) AND ISNULL(OGM.IsObsolete,0) = 0
			Group By OSGM.Id,OSGM.Title
			Order By OrgSubGroupName
		END
		ELSE IF(@rFilterType = 'EmployeeGroupwise')--EmployeeGroupwise
		BEGIN
			 SELECT 
				OSGM.Id As OrgSubGroupId		
				,OSGM.Title As OrgSubGroupName
				,COUNT(T1.Code) as Teaching
				,COUNT(T2.Code) as NonTeaching

			FROM 
				sSetup.tOrgSubGroupMaster OSGM
				INNER JOIN sSetup.tOrgGroupMaster OGM ON OGM.Id = OSGM.OrgGroupId
				LEFT JOIN sSetup.tOrganizationMaster OM ON OM.OrgSubGroupId = OSGM.Id
				LEFT JOIN sHrm.tEmployeeMaster EM ON EM.OrgId = OM.Id AND EM.StatusId = 7 AND ISNULL(EM.IsOtherUser,0) = 0 

				LEFT JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id
				LEFT JOIN (SELECT EM1.Code As Code FROM sHrm.tEmployeeMaster EM1 
					INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM1.Id
					WHERE EM1.StatusId = 7 AND ISNULL(EM1.IsOtherUser,0) = 0  AND EJD.EmployeeGroupId=1 Group By EM1.Code) T1 ON  EM.Code = T1.Code
				LEFT JOIN (SELECT EM1.Code As Code FROM sHrm.tEmployeeMaster EM1 
					INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM1.Id
					WHERE EM1.StatusId = 7 AND ISNULL(EM1.IsOtherUser,0) = 0  AND EJD.EmployeeGroupId=2 Group By EM1.Code) T2 ON  EM.Code = T2.Code
				 
			WHERE ((OGM.Id = @rOrgGroupId) OR (@rOrgGroupId = 0))AND ISNULL(OGM.IsObsolete,0) = 0
			Group By OSGM.Id,OSGM.Title
			Order By OrgSubGroupName
		END
	END
-------------11 
	ELSE IF(@rTypeId = 2)
	BEGIN
		IF(@rFilterType = 'Statuswise')--Statuswise (Total/Active)
		BEGIN
		 SELECT 
			 OM.Title As Organization
			,OM.Id As OrgId
			,COUNT(EM.Code) As Total
			,COUNT(AEM.Code) as Active
		FROM 
			sSetup.tOrgGroupMaster OGM
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.OrgGroupId = OGM.Id
			LEFT JOIN sHrm.tEmployeeMaster EM ON EM.OrgId = OM.Id
       		LEFT JOIN (SELECT EM1.Code As Code FROM sHrm.tEmployeeMaster EM1 
			 WHERE EM1.StatusId = 7 AND ISNULL(EM1.IsOtherUser,0) = 0  Group By EM1.Code) AEM ON  EM.Code = AEM.Code
		WHERE ((OM.OrgSubGroupId = @rOrgSubGroupId) OR (@rOrgSubGroupId = 0)) AND EM.IsOtherUser = 0
		Group By OM.Title,OM.Id
		Order By Organization
		END

		ELSE IF(@rFilterType = 'Genderwise')--Genderwise
		BEGIN
			 SELECT 
				 OM.Title As Organization
				,OM.Id As OrgId
				,COUNT(Male.Code) as Male
				,COUNT(Female.Code) as Female
				,COUNT(EM.Code) as Total
			FROM
				sSetup.tOrgGroupMaster OGM
				INNER JOIN sSetup.tOrganizationMaster OM ON OM.OrgGroupId = OGM.Id
				LEFT JOIN sHrm.tEmployeeMaster EM ON EM.OrgId = OM.Id AND EM.StatusId = 7 AND ISNULL(EM.IsOtherUser,0) = 0 
				LEFT JOIN (SELECT EM1.Code As Code FROM sHrm.tEmployeeMaster EM1 
					INNER JOIN sHrm.tEmployeePersonalDetail EPD ON EPD.EmployeeId = EM1.Id
					WHERE EM1.StatusId = 7 AND ISNULL(EM1.IsOtherUser,0) = 0  AND EPD.GenderId = 1 Group By EM1.Code) Male ON  EM.Code = Male.Code
				LEFT JOIN (SELECT EM1.Code As Code FROM sHrm.tEmployeeMaster EM1 
					INNER JOIN sHrm.tEmployeePersonalDetail EPD ON EPD.EmployeeId = EM1.Id
					WHERE EM1.StatusId = 7 AND ISNULL(EM1.IsOtherUser,0) = 0  AND EPD.GenderId = 2 Group By EM1.Code) Female ON  EM.Code = Female.Code
			WHERE ((OM.OrgSubGroupId = @rOrgSubGroupId) OR (@rOrgSubGroupId = 0)) AND ISNULL(OGM.IsObsolete,0) = 0
			Group By OM.Title,OM.Id
			Order By Organization
		END

		ELSE IF(@rFilterType = 'EmployeeGroupwise')--EmployeeGroupwise
		BEGIN
			 SELECT 
				OM.Title As Organization
				,OM.Id As OrgId
				,COUNT(T1.Code) as Teaching
				,COUNT(T2.Code) as NonTeaching

			FROM 
				sSetup.tOrgGroupMaster OGM
				INNER JOIN sSetup.tOrganizationMaster OM ON OM.OrgGroupId = OGM.Id
				LEFT JOIN sHrm.tEmployeeMaster EM ON EM.OrgId = OM.Id AND EM.StatusId = 7 AND ISNULL(EM.IsOtherUser,0) = 0 

				LEFT JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id
				LEFT JOIN (SELECT EM1.Code As Code FROM sHrm.tEmployeeMaster EM1 
					INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM1.Id
					WHERE EM1.StatusId = 7 AND ISNULL(EM1.IsOtherUser,0) = 0  AND EJD.EmployeeGroupId=1 Group By EM1.Code) T1 ON  EM.Code = T1.Code
				LEFT JOIN (SELECT EM1.Code As Code FROM sHrm.tEmployeeMaster EM1 
					INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM1.Id
					WHERE EM1.StatusId = 7 AND ISNULL(EM1.IsOtherUser,0) = 0  AND EJD.EmployeeGroupId=2 Group By EM1.Code) T2 ON  EM.Code = T2.Code
				 
			WHERE ((OM.OrgSubGroupId = @rOrgSubGroupId) OR (@rOrgSubGroupId = 0))AND ISNULL(OGM.IsObsolete,0) = 0
			Group By OM.Title,OM.Id
			Order By Organization
		END
		 
	END
------------------21
	ELSE IF(@rTypeId = 3)
		BEGIN
		IF(@rFilterType = 'Statuswise')--Statuswise (Total/Active)
		BEGIN
			SELECT 
				(EM.Id)EmployeeID,
				(EM.Code)EmployeeCode,
				(EM.FirstName+' '+EM.LastName) AS EmployeeName,
				(EC.MobileNumber) AS ContactNo
			 from  sHrm.tEmployeeMaster EM 
				   INNER JOIN sSetup.tOrganizationMaster OME ON OME.Id = EM.OrgId
				   INNER JOIN sSetup.tOrgGroupMaster OGME ON OGME.Id=OME.OrgGroupId
				   LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
		    WHERE ((EM.OrgId = @rOrgId) OR (@rOrgId = 0))
				And ISNULL(OGME.IsObsolete,0) = 0
				and ((EM.StatusId=@rStatusId) OR (@rStatusId = 0)) AND  ISNULL(EM.IsOtherUser,0) = 0	
		END
		ELSE IF(@rFilterType = 'Genderwise')--Genderwise
		BEGIN
			SELECT 
					(EM.Id)EmployeeID,
					(EM.Code)EmployeeCode,
					(EM.FirstName+' '+EM.LastName) AS EmployeeName,
					(EC.MobileNumber) AS ContactNo
				 from  sHrm.tEmployeeMaster EM 
					   INNER JOIN sSetup.tOrganizationMaster OME ON OME.Id = EM.OrgId
					   INNER JOIN sSetup.tOrgGroupMaster OGME ON OGME.Id=OME.OrgGroupId
					   LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
					   INNER JOIN sHrm.tEmployeePersonalDetail EPD ON EPD.EmployeeId = EM.Id
				WHERE ((EM.OrgId = @rOrgId) OR (@rOrgId = 0))
					And ISNULL(OGME.IsObsolete,0) = 0
					and (EM.StatusId=7) AND  ISNULL(EM.IsOtherUser,0) = 0	
					and EPD.GenderId = @rGenderId
		END
		ELSE IF(@rFilterType = 'EmployeeGroupwise')--EmployeeGroupwise
		BEGIN
			SELECT 
					(EM.Id)EmployeeID,
					(EM.Code)EmployeeCode,
					(EM.FirstName+' '+EM.LastName) AS EmployeeName,
					(EC.MobileNumber) AS ContactNo
				 from  sHrm.tEmployeeMaster EM 
					   INNER JOIN sSetup.tOrganizationMaster OME ON OME.Id = EM.OrgId
					   INNER JOIN sSetup.tOrgGroupMaster OGME ON OGME.Id=OME.OrgGroupId
					   LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
					   INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id
				WHERE ((EM.OrgId = @rOrgId) OR (@rOrgId = 0))
					And ISNULL(OGME.IsObsolete,0) = 0
					and (EM.StatusId=7) AND  ISNULL(EM.IsOtherUser,0) = 0	
					and EJD.EmployeeGroupId = @rEmployeeGroupId
		END
		END
	
END
GO
PRINT N'Altering Procedure [sOp].[pPaymentTransactionUpdate]...';


GO
ALTER PROCEDURE [sOp].[pPaymentTransactionUpdate]
	 
	@rPaymentTransactionId bigint,
	@rMerchantTransactionId nvarchar(50),
	@rBankTransactionId bigint,
	@rBankName nvarchar(100),
	@rPaymentType nvarchar(50),
	@rCardNumber nvarchar(100),
	@rTransactionResponse nvarchar(max)
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN	
BEGIN TRY
BEGIN TRANSACTION	
 
    BEGIN 
	    UPDATE sOp.tPaymentTransaction
	    SET
	    MerchantTransactionId=@rMerchantTransactionId,
	    BankTransactionId=@rBankTransactionId,
	    BankName=@rBankName,
	    PaymentType=@rPaymentType,
	    CardNumber=@rCardNumber,
	    TransactionResponse=@rTransactionResponse
	    WHERE Id = @rPaymentTransactionId 
	    SELECT @rPaymentTransactionId AS Result
	END  
	
	COMMIT TRANSACTION
	
END TRY
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
END
GO
PRINT N'Altering Procedure [sPurchase].[pEventSMSTemplateIdGet]...';


GO

ALTER PROCEDURE [sPurchase].[pEventSMSTemplateIdGet]
		@rOrgId int,
		@rEventId int
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	BEGIN
		BEGIN TRY
			Select SMSTemplateID FROM sAlert.tEventTemplate WHERE EventId = @rEventId AND OrgId=@rOrgId AND AlertModeId = 2
		END TRY
		BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH
	END
GO
PRINT N'Altering Procedure [sPurchase].[pEventTemplateGet]...';


GO

ALTER PROCEDURE [sPurchase].[pEventTemplateGet]
		@rOrgId int
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	BEGIN
		BEGIN TRY
			SELECT EventId,Template FROM sAlert.tEventTemplate WHERE IsAutoSend = 1 AND OrgId =@rOrgId AND EventId = 158
			 --AND AlertModeId in (3)
		END TRY
		BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH
	END
GO
PRINT N'Altering Procedure [sPurchase].[pGetTemplate]...';


GO





--exec [sPurchase].[pGetTemplate] 991100001
ALTER PROCEDURE [sPurchase].[pGetTemplate]
 @rPurchaseOrderId int
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
	DECLARE @HTMLTable NVARCHAR(MAX);

	Declare
	@rRefNumber AS NVARCHAR(20),
	@rPurchaseRequestNumber AS NVARCHAR(20),
	@rRequestedBy AS NVARCHAR(100),
	@rPoDate AS NVARCHAR(100),
	@rStatus AS NVARCHAR(100),
	@rVendorCode AS NVARCHAR(100),
	@rVendorName AS NVARCHAR(300),
	@rRequiredBy AS NVARCHAR(100),
	@rBillToAddress AS NVARCHAR(1000),
	@rShipToAddress AS NVARCHAR(1000)

	    select  @rRefNumber = ISNULL(PO.RefNumber,''),
				@rPurchaseRequestNumber = ISNULL(PR.Number,''),
				@rRequestedBy = ISNULL(PO.RequestedBy,''),
				@rPoDate = ISNULL(PO.PODate,''),
				@rStatus = ISNULL(SM.Title,''),
				@rVendorCode = ISNULL(VM.Code,''),
				@rVendorName = ISNULL(VM.Title,''),
				@rRequiredBy = ISNULL(PO.RequiredBy,''),
				@rBillToAddress = ISNULL(PO.BillToAddress,''),
				@rShipToAddress = ISNULL(PO.ShipToAddress,'')
		from   [sPurchase].[tPurchaseOrder] PO(nolock) 
			   Left JOIN sProcurement.tVendorMaster  VM on PO.VendorId = VM.ID
			   Left Join [sWf].[tWfStatusMaster] SM ON SM.Id = PO.StatusId
			   Left Join [sPurchase].[tPurchaseRequest] PR on PR.Id = PO.PurchaseRequestId
		where  PO.Id = @rPurchaseOrderId AND PO.IsObsolete = 0


    SET @HTMLTable = '';
	if exists(select *  from   [sPurchase].[tPurchaseOrderDetail] POD
			where  POD.PurchaseOrderId = @rPurchaseOrderId)
    Begin
    SET @HTMLTable = @HTMLTable + '<tr>';
    SET @HTMLTable = @HTMLTable + '<th>StockItemCode</th>';
    SET @HTMLTable = @HTMLTable + '<th>StockItemName</th>';
    SET @HTMLTable = @HTMLTable + '<th>Uom</th>';
    SET @HTMLTable = @HTMLTable + '<th>TotalQty</th>';
    SET @HTMLTable = @HTMLTable + '</tr>';

	Select @HTMLTable = @HTMLTable+'<tr><td>'+Cast(SIM.Code as Nvarchar(100))+'</td><td>'
+SIM.Title+'</td><td>'+SUMa.Code+'</td><td>'+Cast(POD.TotalQty as Nvarchar(20))+'</td></tr>'
	  from   [sPurchase].[tPurchaseOrderDetail] POD (nolock)
			   Inner JOIN	sPurchase.tPurchaseOrder PO	ON PO.Id = POD.PurchaseOrderId AND PO.IsObsolete = 0
			   Inner JOIN	sIp.tStockItemMaster SIM	ON SIM.Id = POD.StockItemId 
			   Inner JOIN  sFinanceCommon.tStockUomMaster SUMa ON SUMa.Id = SIM.IssueStockUomId
		where  POD.PurchaseOrderId = @rPurchaseOrderId

	End
select REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(Template, 
		'{RefNumber}' , @rRefNumber),
		'{PurchaseRequestNumber}' , @rPurchaseRequestNumber),
		'{RequestedBy}' , @rRequestedBy),
		'{PoDate}' , @rPoDate),
		'{Status}' , @rStatus),
		'{VendorCode}' , @rVendorCode),
		'{VendorName}' , @rVendorName),
		'{RequiredBy}' , @rRequiredBy),
		'{BillToAddress}' , @rBillToAddress),
		'{ShipToAddress}' , @rShipToAddress),
		'{PurchaseOrderDetails}' , ISNULL(@HTMLTable,''))

		as Template from sPurchase.tPurchaseReportTemplateMaster where Code='PO' AND IsObsolete = 0


	END TRY

	BEGIN CATCH
    IF @@TRANCOUNT > 0
        ROLLBACK TRAN --RollBack in case of Error

    
    DECLARE @ErrorMessage NVARCHAR(4000);  
    DECLARE @ErrorSeverity INT;  
    DECLARE @ErrorState INT;  

    SELECT   
       @ErrorMessage = ERROR_MESSAGE(),  
       @ErrorSeverity = ERROR_SEVERITY(),  
       @ErrorState = ERROR_STATE();  

    RAISERROR (@ErrorMessage, @ErrorSeverity, @ErrorState);  
    
	END CATCH
END
GO
PRINT N'Altering Procedure [sPurchase].[pGoodsReceivedNoteGet]...';


GO

--exec [sPurchase].[pGoodsReceivedNoteGet] 991100002
ALTER PROCEDURE [sPurchase].[pGoodsReceivedNoteGet]
	  @rId int
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
		select  GRN.Id,
				GRN.GRNNumber                               ,
				GRN.OrgGroupId,
				GRN.LocationId,
				GRN.PurchaseRequestId,
				GRN.PurchaseOrderId,
				GRN.VendorId,
				GRN.RequestedBy,
				ISNULL(GRN.BillToAddress, PO.BillToAddress) AS BillToAddress,
				GRN.StatusId,
				GRN.PODueDate,
				ISNULL(SM.Title,'') AS Status,
				VM.Title AS VendorName,
			    PR.Number As PurchaseRequestNumber,
				ISNULL(PO.ShipToAddress,'') AS ShipToAddress,
			    PO.RefNumber AS PurchaseOrderNumber  
		from   [sPurchase].[tGoodsReceivedNote] GRN(nolock) 
			   Left JOIN sProcurement.tVendorMaster  VM on GRN.VendorId = VM.ID
			   Left Join [sWf].[tWfStatusMaster] SM ON SM.Id = GRN.StatusId
			   Left Join [sPurchase].[tPurchaseRequest] PR ON PR.ID = GRN.PurchaseRequestId
			   Left Join [sPurchase].[tPurchaseOrder] PO On PO.Id = GRN.PurchaseOrderId
		where  GRN.Id=@rId AND GRN.IsObsolete = 0

		select GRND.Id,
			   GRND.GoodsReceivedNoteId,
			   GRND.PurchaseOrderDetailId,
			   GRND.OrgGroupId,
			   SUMa.Id AS UnitTypeId,
			   GRND.StockItemId,
			   GRND.POQty,
			   GRND.ReceivedQty,
			   GRND.PreviousGRNQty,
			   GRND.UnitPrice,
			   GRND.Remark, 
			   SIM.Code	AS StockItemCode,
			   SIM.Title AS StockItemName,
			   SUMa.Code AS UOM,
			   SCM.Id as CategoryId,
			   SCM.Title as CategoryName,
			   0 as SubCategoryId
		from   [sPurchase].[tGoodsReceivedNoteDetail] GRND (nolock)
			   Inner JOIN	sPurchase.tGoodsReceivedNote GRN	ON GRN.Id = GRND.GoodsReceivedNoteId AND GRN.IsObsolete = 0
			   Inner JOIN	sIp.tStockItemMaster SIM	ON SIM.Id = GRND.StockItemId 
			   Inner JOIN  sFinanceCommon.tStockUomMaster SUMa ON SUMa.Id = SIM.IssueStockUomId
			   LEFT JOIN [sIp].[tStockItemCategoryMaster] SCM ON SCM.Id = SIM.StockItemCategoryId
		where  GRND.GoodsReceivedNoteId=@rId
	END TRY

	BEGIN CATCH
    IF @@TRANCOUNT > 0
        ROLLBACK TRAN --RollBack in case of Error
    
    DECLARE @ErrorMessage NVARCHAR(4000);  
    DECLARE @ErrorSeverity INT;  
    DECLARE @ErrorState INT;  
    SELECT   
       @ErrorMessage = ERROR_MESSAGE(),  
       @ErrorSeverity = ERROR_SEVERITY(),  
       @ErrorState = ERROR_STATE();  
    RAISERROR (@ErrorMessage, @ErrorSeverity, @ErrorState);  
    
	END CATCH
END
GO
PRINT N'Altering Procedure [sPurchase].[pGoodsReceivedNoteSearchGet]...';


GO

--exec [sPurchase].[pGoodsReceivedNoteSearchGet] null,991100001,null,9911,'2023-01-01','2023-12-01',1,10,null
ALTER PROCEDURE [sPurchase].[pGoodsReceivedNoteSearchGet]

	@rNumber nvarchar(30) = '',
	@rLocationId int,
	@rName nvarchar = '',
	@rOrgGroupId int,
	@rStartDate DateTime = null,
	@rEndDate DateTime = null,
	@rPageNo int,
	@rPageSize int,
	@rStatusId smallint = null

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY


	    DECLARE @TotalRecords BIGINT;
			-- Get the total number of records
		SELECT @TotalRecords = COUNT(*) FROM sPurchase.tGoodsReceivedNote GRN(nolock)



		WHERE 
				((GRN.GRNNumber like @rNumber+'%') OR (ISNULL(@rNumber,'') = ''))
   				AND ((GRN.RequestedBy like @rName+'%') OR (ISNULL(@rName,'') = ''))
   				--AND ((SLM.Id = @rStoreLocationId) OR (@rStoreLocationId = 0))
   				AND ((GRN.OrgGroupId = @rOrgGroupId) OR (@rOrgGroupId=0))
				AND ((GRN.StatusId = @rStatusId) OR (ISNULL(@rStatusId,0)=0))
				AND GRN.IsObsolete = 0
				AND ((Cast(GRN.CreatedDateTime as Date) >= Cast(@rStartDate as Date)) OR (ISNULL(@rStartDate,'')=''))
				AND((Cast(GRN.CreatedDateTime as Date) <= Cast(@rEndDate as Date)) OR (ISNULL(@rEndDate,'')=''))

	    Select t.* From (
			Select ROW_NUMBER() Over (
			Order by GRN.Id desc  
			) AS 'RowNum',GRN.Id,
				GRN.PurchaseRequestId,
				GRN.PurchaseOrderId,
				GRN.VendorId,
				GRN.GRNNumber as Number,
				GRN.RequestedBy, 
				GRN.LocationId, 
				GRN.PODueDate,
				ISNULL(SM.Title,'') as Status,
				VM.Code AS VendorCode,
			    VM.Title AS VendorName,
				PR.Number as PurchaseNumber,
				PO.RefNumber as PurchaseOrderNumber

	    FROM		
				sPurchase.tGoodsReceivedNote GRN (nolock)
				Left Join [sWf].[tWfStatusMaster] SM on GRN.StatusId = SM.Id
				Left JOIN sProcurement.tVendorMaster  VM on GRN.VendorId = VM.ID
				Left Join [sPurchase].[tPurchaseRequest] PR on PR.Id = GRN.PurchaseRequestId
				Left Join [sPurchase].[tPurchaseOrder] PO on PO.Id = GRN.PurchaseOrderId
		WHERE 
				((GRN.GRNNumber like @rNumber+'%') OR (ISNULL(@rNumber,'') = ''))
   				AND ((GRN.RequestedBy like @rName+'%') OR (ISNULL(@rName,'') = ''))
   				--AND ((SLM.Id = @rStoreLocationId) OR (@rStoreLocationId = 0))
   				AND ((GRN.OrgGroupId = @rOrgGroupId) OR (@rOrgGroupId=0))
				AND ((GRN.StatusId = @rStatusId) OR (ISNULL(@rStatusId,0)=0))
				AND GRN.IsObsolete = 0
				AND ((Cast(GRN.CreatedDateTime as Date) >= Cast(@rStartDate as Date)) OR (ISNULL(@rStartDate,'')=''))
				AND((Cast(GRN.CreatedDateTime as Date) <= Cast(@rEndDate as Date)) OR (ISNULL(@rEndDate,'')=''))
					)t Where t.RowNum Between
		((@rPageNo-1)*@rPageSize +1) AND (@rPageNo*@rpageSize)

		SELECT @TotalRecords as TotalRecords

	 END TRY

	BEGIN CATCH
    IF @@TRANCOUNT > 0
        ROLLBACK TRAN --RollBack in case of Error
    
    DECLARE @ErrorMessage NVARCHAR(4000);  
    DECLARE @ErrorSeverity INT;  
    DECLARE @ErrorState INT;  
    SELECT   
       @ErrorMessage = ERROR_MESSAGE(),  
       @ErrorSeverity = ERROR_SEVERITY(),  
       @ErrorState = ERROR_STATE();  
    RAISERROR (@ErrorMessage, @ErrorSeverity, @ErrorState);  
    
	END CATCH  		  
END
GO
PRINT N'Altering Procedure [sPurchase].[pGoodsReceivedNoteSearchSRGet]...';


GO

--exec [sPurchase].[pGoodsReceivedNoteSearchSRGet] null,991100001,null,9911,'2023-12-01','2023-12-18',1,10,null
ALTER PROCEDURE [sPurchase].[pGoodsReceivedNoteSearchSRGet]

	@rNumber nvarchar(30) = '',
	@rLocationId int,
	@rName nvarchar = '',
	@rOrgGroupId int,
	@rStartDate DateTime = null,
	@rEndDate DateTime = null,
	@rPageNo int,
	@rPageSize int,
	@rStatusId smallint = null

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY


		 DECLARE @TotalRecords BIGINT;
		-- Get the total number of records
		SELECT @TotalRecords = COUNT(*) FROM sPurchase.tGoodsReceivedNote GRN (nolock)

		WHERE 
				((GRN.GRNNumber like @rNumber+'%') OR (ISNULL(@rNumber,'') = ''))
   				AND ((GRN.RequestedBy like @rName+'%') OR (ISNULL(@rName,'') = ''))
   				--AND ((SLM.Id = @rStoreLocationId) OR (@rStoreLocationId = 0))
   				AND ((GRN.OrgGroupId = @rOrgGroupId) OR (@rOrgGroupId=0))
				AND ((GRN.StatusId = @rStatusId) OR (ISNULL(@rStatusId,0)=0))
				AND GRN.IsObsolete = 0 
				AND GRN.Id in (select Distinct GRN1.Id from sPurchase.tGoodsReceivedNote GRN1
			    INNER JOIN   sPurchase.tQualityCheck QC on QC.GoodsReceivedNoteId = GRN1.Id
			    INNER JOIN   sPurchase.tQualityCheckDetail QCD on QCD.QualityCheckId = QC.Id AND QCD.RejectedQty > 0)
				AND ((Cast(GRN.CreatedDateTime as Date) >= Cast(@rStartDate as Date)) OR (ISNULL(@rStartDate,'')=''))
				AND((Cast(GRN.CreatedDateTime as Date) <= Cast(@rEndDate as Date)) OR (ISNULL(@rEndDate,'')=''))


		Select t.* From (
			Select ROW_NUMBER() Over (
			Order by GRN.Id desc  
			) AS 'RowNum',GRN.Id,
				GRN.GRNNumber as Number,
				GRN.RequestedBy, 
				GRN.LocationId, 
				GRN.PODueDate,
				ISNULL(SM.Title,'') as Status,
				(select Sum(QCD1.RejectedQty) from sPurchase.tGoodsReceivedNote GRN12
			    INNER JOIN   sPurchase.tQualityCheck QC1 on QC1.GoodsReceivedNoteId = GRN12.Id
			    INNER JOIN   sPurchase.tQualityCheckDetail QCD1 on QCD1.QualityCheckId = QC1.Id AND QCD1.RejectedQty > 0
				where GRN12.Id = GRN.Id) as RejectedQty

        FROM		
				sPurchase.tGoodsReceivedNote GRN (nolock)
				Left Join [sWf].[tWfStatusMaster] SM on GRN.StatusId = SM.Id


	    WHERE 
				((GRN.GRNNumber like @rNumber+'%') OR (ISNULL(@rNumber,'') = ''))
   				AND ((GRN.RequestedBy like @rName+'%') OR (ISNULL(@rName,'') = ''))
   				--AND ((SLM.Id = @rStoreLocationId) OR (@rStoreLocationId = 0))
   				AND ((GRN.OrgGroupId = @rOrgGroupId) OR (@rOrgGroupId=0))
				AND ((GRN.StatusId = @rStatusId) OR (ISNULL(@rStatusId,0)=0))
				AND GRN.IsObsolete = 0 
				AND GRN.Id in (select Distinct GRN1.Id from sPurchase.tGoodsReceivedNote GRN1
			    INNER JOIN   sPurchase.tQualityCheck QC on QC.GoodsReceivedNoteId = GRN1.Id
			    INNER JOIN   sPurchase.tQualityCheckDetail QCD on QCD.QualityCheckId = QC.Id AND QCD.RejectedQty > 0)
				AND ((Cast(GRN.CreatedDateTime as Date) >= Cast(@rStartDate as Date)) OR (ISNULL(@rStartDate,'')=''))
				AND((Cast(GRN.CreatedDateTime as Date) <= Cast(@rEndDate as Date)) OR (ISNULL(@rEndDate,'')=''))
					)t Where t.RowNum Between
		        ((@rPageNo-1)*@rPageSize +1) AND (@rPageNo*@rpageSize)

        SELECT @TotalRecords as TotalRecords

	 END TRY

	BEGIN CATCH
    IF @@TRANCOUNT > 0
        ROLLBACK TRAN --RollBack in case of Error
    
    DECLARE @ErrorMessage NVARCHAR(4000);  
    DECLARE @ErrorSeverity INT;  
    DECLARE @ErrorState INT;  
    SELECT   
       @ErrorMessage = ERROR_MESSAGE(),  
       @ErrorSeverity = ERROR_SEVERITY(),  
       @ErrorState = ERROR_STATE();  
    RAISERROR (@ErrorMessage, @ErrorSeverity, @ErrorState);  
    
	END CATCH  		  
END
GO
PRINT N'Altering Procedure [sPurchase].[pGoodsReceivedNoteSRGet]...';


GO

--exec [sPurchase].[pGoodsReceivedNoteSRGet] 991100002
ALTER PROCEDURE [sPurchase].[pGoodsReceivedNoteSRGet]
	  @rId int
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
		select Distinct GRN.Id as GoodsReceivedNoteId,
				GRN.GRNNumber,
				GRN.OrgGroupId,
				GRN.LocationId,
				GRN.PurchaseRequestId,
				GRN.PurchaseOrderId,
				GRN.VendorId,
				GRN.RequestedBy,
				GRN.BillToAddress,
				GRN.StatusId,
				GRN.PODueDate,
				PO.RefNumber as PurchaseOrderNumber,
				ISNULL(SM.Title,'') as Status,
				VM.Title AS VendorName 
		from   [sPurchase].[tGoodsReceivedNote] GRN(nolock) 
			   INNER JOIN sPurchase.tQualityCheck QC on QC.GoodsReceivedNoteId = GRN.Id
			   INNER JOIN sPurchase.tPurchaseOrder PO on PO.Id = GRN.PurchaseOrderId
			   LEFT JOIN  sProcurement.tVendorMaster  VM on GRN.VendorId = VM.ID
			   LEFT Join  sWf.tWfStatusMaster SM ON SM.Id = GRN.StatusId
		where  GRN.Id=@rId AND GRN.IsObsolete = 0

		select Distinct GRND.Id as GoodsReceivedNoteDetailId,
			   GRND.GoodsReceivedNoteId,
			   GRND.PurchaseOrderDetailId,
			   GRND.OrgGroupId,
			   SUMa.Id AS UnitTypeId,
			   GRND.StockItemId,
			   GRND.POQty,
			   GRND.ReceivedQty,
			   GRND.PreviousGRNQty,
			   GRND.UnitPrice,
			   GRND.Remark, 
			   (select Sum(QCD1.RejectedQty) from sPurchase.tGoodsReceivedNote GRN12
			    INNER JOIN   sPurchase.tQualityCheck QC1 on QC1.GoodsReceivedNoteId = GRN12.Id
			    INNER JOIN   sPurchase.tQualityCheckDetail QCD1 on QCD1.QualityCheckId = QC1.Id AND QCD1.RejectedQty > 0
				where GRN12.Id = GRN.Id) AS RejectedQty,
			   '' AS ReasonForRejection,
			   SIM.Code	AS StockItemCode,
			   SIM.Title AS StockItemName,
			   SUMa.Code AS UOM,
			   SCM.Id as CategoryId,
			   SCM.Title as CategoryName,
			   0 as SubCategoryId
		from   [sPurchase].[tGoodsReceivedNoteDetail] GRND (nolock)
			   INNER JOIN	sPurchase.tGoodsReceivedNote GRN	ON GRN.Id = GRND.GoodsReceivedNoteId AND GRN.IsObsolete = 0
			   INNER JOIN sPurchase.tQualityCheck QC on QC.GoodsReceivedNoteId = GRN.Id
			   INNER JOIN   sPurchase.tQualityCheckDetail QCD on QCD.QualityCheckId = QC.Id AND QCD.GoodsReceivedNoteDetailId = GRND.ID
			   INNER JOIN	sIp.tStockItemMaster SIM	ON SIM.Id = GRND.StockItemId 
			   INNER JOIN   sFinanceCommon.tStockUomMaster SUMa ON SUMa.Id = SIM.IssueStockUomId
			   LEFT JOIN [sIp].[tStockItemCategoryMaster] SCM ON SCM.Id = SIM.StockItemCategoryId
		where  GRND.GoodsReceivedNoteId=@rId AND QCD.RejectedQty > 0
	END TRY

	BEGIN CATCH
    IF @@TRANCOUNT > 0
        ROLLBACK TRAN --RollBack in case of Error
    
    DECLARE @ErrorMessage NVARCHAR(4000);  
    DECLARE @ErrorSeverity INT;  
    DECLARE @ErrorState INT;  
    SELECT   
       @ErrorMessage = ERROR_MESSAGE(),  
       @ErrorSeverity = ERROR_SEVERITY(),  
       @ErrorState = ERROR_STATE();  
    RAISERROR (@ErrorMessage, @ErrorSeverity, @ErrorState);  
    
	END CATCH
END
GO
PRINT N'Altering Procedure [sPurchase].[pInvoiceGenerateAdd]...';


GO



ALTER PROCEDURE [sPurchase].[pInvoiceGenerateAdd]
		@rId bigint,
		@rGoodsReceivedNoteId bigint,
		@rVendorId bigint,
		@rRequestedBy nvarchar(100),
		@rOrgGroupId smallint,
		@rLocationId int,
		@rStatusId smallint,
		@rInvoiceDate datetime,
		@rInvoiceDueDate datetime,
		@rBillToAddress nvarchar(1000),
		@rShipToAddress nvarchar(1000),
		@rRemarks nvarchar(500),	
		@rUserId bigint,
		@rDetailList sPurchase.InvoiceGenerateDetailType READONLY
 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
	BEGIN TRANSACTION

		If(@rId > 0)
		Begin
			Update sPurchase.tInvoiceGenerate
			set 
				StatusId = @rStatusId,
				GoodsReceivedNoteId = @rGoodsReceivedNoteId,
				VendorId = @rVendorId,
				RequestedBy = @rRequestedBy,
				InvoiceDate = @rInvoiceDate,
				InvoiceDueDate = @rInvoiceDueDate,
				BillToAddress = @rBillToAddress,
				ShipToAddress = @rShipToAddress,
				Remarks = @rRemarks,
				UpdatedUserId = @rUserId,		
				UpdatedDateTime = GetUtcDate()
			where Id = @rId and IsObsolete = 0

			delete from sPurchase.tInvoiceGenerateDetail
			where Id not in(select Id from @rDetailList)
			and InvoiceGenerateId = @rId

			update sPurchase.tInvoiceGenerateDetail
			set
			OrgGroupId = @rOrgGroupId,
			InvoiceGenerateId = @rId,
			GoodsReceivedNoteDetailId = DL.GoodsReceivedNoteDetailId,
			StockItemId = DL.StockItemId,
			POQty = DL.POQty,
			ReceivedQty = DL.ReceivedQty,
			AcceptedQty = DL.AcceptedQty,
			RejectedQty = DL.RejectedQty,
			ReasonForRejection = DL.ReasonForRejection,
			UnitPrice = DL.UnitPrice,
			Remark = IG.Remark,
			UpdatedUserId = @rUserId,
			UpdatedDateTime = GETUTCDATE()
			from @rDetailList DL
			inner join sPurchase.tInvoiceGenerateDetail IG ON DL.ID = IG.Id
			where IG.InvoiceGenerateId = @rId

			DECLARE @lNextNumberIGD BIGINT	 
			EXECUTE [sCommon].[pGetIntMaxIdForOrgGroup] @rOrgGroupId, 'sPurchase.tInvoiceGenerateDetail',@lNextNumber = @lNextNumberIGD output
			set @lNextNumberIGD=@lNextNumberIGD-1
			INSERT INTO sPurchase.tInvoiceGenerateDetail
			(
				Id,
				OrgGroupId,
				InvoiceGenerateId,
				GoodsReceivedNoteDetailId,
				StockItemId,
				POQty,
				ReceivedQty,
				AcceptedQty,
				RejectedQty,
				UnitPrice,
				ReasonForRejection,
				CreatedUserId,
				CreatedDateTime
			)
			select	@lNextNumberIGD+Id,
					@rOrgGroupId,
					@rId,
					GoodsReceivedNoteDetailId,
					StockItemId,
					POQty,
					ReceivedQty,
					AcceptedQty,
					RejectedQty,
					UnitPrice,
					ReasonForRejection,
					@rUserId, 
					GETUTCDATE() 
			from @rDetailList
			where Id not in(Select DL.Id from @rDetailList DL
			inner join sPurchase.tInvoiceGenerateDetail IG ON DL.ID = IG.Id
			where IG.InvoiceGenerateId = @rId)
			set @lNextNumberIGD=@lNextNumberIGD+(select Count(Id) from @rDetailList where Id not in(Select DL.Id from @rDetailList DL
			inner join sPurchase.tInvoiceGenerateDetail IG ON DL.ID = IG.Id
			where IG.InvoiceGenerateId = @rId))
			EXECUTE sCommon.pTableRowIdModify @rOrgGroupId, @rTableTitle = 'sPurchase.tInvoiceGenerateDetail', @rCurrentNumber = @lNextNumberIGD
			
			Select @rId
		End
		Else
		Begin
			DECLARE @lNextNumber INT 
			EXECUTE [sCommon].[pGetIntMaxIdForOrgGroup] @rOrgGroupId, 'sPurchase.tInvoiceGenerate',@lNextNumber = @lNextNumber output	
			--select @lNextNumber
			--DECLARE @loNextNumber nVarchar(20)
			--EXECUTE sCommon.pPrefixSetupNextNumberGet @rOrgId = @rOrgGroupId, @rPrefixFunctionalityId = 1005,@rStoreLocationId = @rLocationId,
			--@rNextNumber = @loNextNumber OUTPUT

	 		INSERT INTO sPurchase.tInvoiceGenerate
			(
				Id,
				INVNumber,
				GoodsReceivedNoteId,
				VendorId,
				RequestedBy, 
				OrgGroupId,
				LocationId, 			 
				StatusId,
				InvoiceDate,
				InvoiceDueDate,
				BillToAddress,
				ShipToAddress,
				Remarks,
				CreatedUserId,		
				CreatedDateTime
	
			)
			VALUES
			(
				@lNextNumber,
				@lNextNumber,
				@rGoodsReceivedNoteId,
				@rVendorId,
				@rRequestedBy,	 
				@rOrgGroupId,
				@rLocationId, 		 
				@rStatusId,
				@rInvoiceDate,
				@rInvoiceDueDate,
				@rBillToAddress,
				@rShipToAddress,
				@rRemarks,
				@rUserId,		
				GETUTCDATE()
			)
 
			set @rId = @lNextNumber  
			
			DECLARE @lNextNumberIGDD BIGINT= 10000 + 	(select count (ID) from sPurchase.tInvoiceGenerateDetail)	 
			EXECUTE [sCommon].[pGetIntMaxIdForOrgGroup] @rOrgGroupId, 'sPurchase.tInvoiceGenerateDetail',@lNextNumber = @lNextNumberIGDD output	
			set @lNextNumberIGDD=@lNextNumberIGDD-1

	 		INSERT INTO sPurchase.tInvoiceGenerateDetail
			(
				Id,
				OrgGroupId,
				InvoiceGenerateId,
				GoodsReceivedNoteDetailId,
				StockItemId,
				POQty,
				ReceivedQty,
				AcceptedQty,
				RejectedQty,
				UnitPrice,
				ReasonForRejection,
				CreatedUserId,
				CreatedDateTime
			)
			select	@lNextNumberIGDD+Id,
					@rOrgGroupId,
					@rId,
					GoodsReceivedNoteDetailId,
					StockItemId,
					POQty,
					ReceivedQty,
					AcceptedQty,
					RejectedQty,
					UnitPrice,
					ReasonForRejection,
					@rUserId, 
					GETUTCDATE() 
			from @rDetailList
						
			set @lNextNumberIGDD=@lNextNumberIGDD+(select Count(Id) from @rDetailList)
			EXECUTE sCommon.pTableRowIdModify @rOrgGroupId, @rTableTitle = 'sPurchase.tInvoiceGenerateDetail', @rCurrentNumber = @lNextNumberIGDD
			select @rId
		End
	COMMIT TRAN -- Transaction Success!	
	END TRY

	BEGIN CATCH
    IF @@TRANCOUNT > 0
        ROLLBACK TRAN --RollBack in case of Error

    
    DECLARE @ErrorMessage NVARCHAR(4000);  
    DECLARE @ErrorSeverity INT;  
    DECLARE @ErrorState INT;  

    SELECT   
       @ErrorMessage = ERROR_MESSAGE(),  
       @ErrorSeverity = ERROR_SEVERITY(),  
       @ErrorState = ERROR_STATE();  

    RAISERROR (@ErrorMessage, @ErrorSeverity, @ErrorState);  
    
	END CATCH
END
GO
PRINT N'Altering Procedure [sPurchase].[pInvoiceGenerateSearchGet]...';


GO

--exec [sPurchase].[pInvoiceGenerateSearchGet] '',991100001,'',9911,'2023-01-01','2023-12-01',1,10,null
ALTER PROCEDURE [sPurchase].[pInvoiceGenerateSearchGet]

	@rNumber nvarchar(30) = '',
	@rLocationId int,
	@rName nvarchar = '',
	@rOrgGroupId int,
	@rStartDate DateTime = null,
	@rEndDate DateTime = null,
	@rPageNo int,
	@rPageSize int,
	@rStatusId smallint = 0

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY

		DECLARE @TotalRecords BIGINT;
		-- Get the total number of records
		SELECT @TotalRecords = COUNT(*) FROM sPurchase.tInvoiceGenerate IG (nolock)

		WHERE 
				((IG.INVNumber like @rNumber+'%') OR (ISNULL(@rNumber,'') = ''))
   				AND ((IG.RequestedBy like @rName+'%') OR (ISNULL(@rName,'') = ''))
   				--AND ((SLM.Id = @rStoreLocationId) OR (@rStoreLocationId = 0))
   				AND ((IG.OrgGroupId = @rOrgGroupId) OR (@rOrgGroupId=0))
				AND ((IG.StatusId = @rStatusId) OR (ISNULL(@rStatusId,0)=0))
				AND ((Cast(IG.CreatedDateTime as Date) >= Cast(@rStartDate as Date)) OR (ISNULL(@rStartDate,'')=''))
				AND((Cast(IG.CreatedDateTime as Date) <= Cast(@rEndDate as Date)) OR (ISNULL(@rEndDate,'')=''))
				AND IG.IsObsolete = 0


	    
        Select t.* From (
			Select ROW_NUMBER() Over (
			Order by IG.Id desc  
			) AS 'RowNum',
			    IG.Id,
				IG.INVNumber as Number,
				IG.RequestedBy, 
				IG.LocationId,
				IG.InvoiceDate,
				ISNULL(SM.Title,'') as Status

        FROM		
				sPurchase.tInvoiceGenerate IG (nolock)
				Left Join [sWf].[tWfStatusMaster] SM on IG.StatusId = SM.Id



        WHERE 
				((IG.INVNumber like @rNumber+'%') OR (ISNULL(@rNumber,'') = ''))
   				AND ((IG.RequestedBy like @rName+'%') OR (ISNULL(@rName,'') = ''))
   				--AND ((SLM.Id = @rStoreLocationId) OR (@rStoreLocationId = 0))
   				AND ((IG.OrgGroupId = @rOrgGroupId) OR (@rOrgGroupId=0))
				AND ((IG.StatusId = @rStatusId) OR (ISNULL(@rStatusId,0)=0))
				AND ((Cast(IG.CreatedDateTime as Date) >= Cast(@rStartDate as Date)) OR (ISNULL(@rStartDate,'')=''))
				AND((Cast(IG.CreatedDateTime as Date) <= Cast(@rEndDate as Date)) OR (ISNULL(@rEndDate,'')=''))
				AND IG.IsObsolete = 0
				)t Where t.RowNum Between
		        ((@rPageNo-1)*@rPageSize +1) AND (@rPageNo*@rpageSize)

        SELECT @TotalRecords as TotalRecords
	 END TRY

	BEGIN CATCH
    IF @@TRANCOUNT > 0
        ROLLBACK TRAN --RollBack in case of Error
    
    DECLARE @ErrorMessage NVARCHAR(4000);  
    DECLARE @ErrorSeverity INT;  
    DECLARE @ErrorState INT;  
    SELECT   
       @ErrorMessage = ERROR_MESSAGE(),  
       @ErrorSeverity = ERROR_SEVERITY(),  
       @ErrorState = ERROR_STATE();  
    RAISERROR (@ErrorMessage, @ErrorSeverity, @ErrorState);  
    
	END CATCH  		  
END
GO
PRINT N'Altering Procedure [sPurchase].[pMenuGet_Purchase]...';


GO
--exec [sPurchase].[pMenuGet_Purchase] 9911000000270
ALTER PROCEDURE [sPurchase].[pMenuGet_Purchase]    
 @rUserId [bigint],    
 @rMenuId int = 0,    
 @rResourceTypeId int= 0
 --,    
 --@rIsCoreMenu bit = 0     
      
WITH EXECUTE AS CALLER    
AS    
SET NOCOUNT ON    
    
BEGIN    
 Declare @rIsCoreMenu int=1
 IF(@rIsCoreMenu=0)    
 BEGIN    
 IF EXISTS(SELECT 1 FROM sSecurity.tPermissionUser WHERE UserId = @rUserId)    
  BEGIN    
   SELECT    
    MenuID,    
    ModuleId,    
    ParentMenuID,    
    MenuTitle,      
    ScreenTitle,       
    PageURL,    
    ScreenId,    
    Permission,    
    OrderNumber,      
    TaskId,      
    PageURL  AS PagePath,    
    IconPath    
        
   FROM    
     (SELECT Menu.Id AS MenuID,     
    ISNULL(Menu.ParentMenuID, 0) AS ParentMenuID,     
    Menu.Title AS MenuTitle,       
    ISNULL(Screen.Title, '') AS ScreenTitle,        
    ISNULL(Screen.Page, '') AS PageURL,    
    ISNULL(Screen.ScreenGroupId,0) AS ScreenGroupId,    
    ISNULL(Menu.ScreenId, 0) AS ScreenId,    
    ISNULL(PermissionValue, 0) AS Permission,    
    ISNULL(OrderNumber, 0) AS OrderNumber,    
    ISNULL(Screen.TaskId,0) AS TaskId,    
    ISNULL(Screen.IconPath,'') As IconPath,     
    ISNULL(T.ResourceTypeId,0) AS ResourceTypeId,    
    ISNULL(T.ModuleId,0) AS ModuleId    
       
       
   FROM sSecurity.tMenu Menu     
   LEFT OUTER JOIN sSecurity.tScreen Screen    
    ON Menu.ScreenId = Screen.Id      
   LEFT OUTER JOIN (     
       SELECT     
        TaskId,     
        SUM(Permission & 2) PermissionValue          
       FROM     
        sSecurity.tPermissionUser P    
        INNER JOIN sSecurity.tTask T ON T.Id = P.TaskId    
        --INNER JOIN sSecuirty.tOrganizationTask OT ON OT.TaskId = T.Id AND OT.OrgGroupId = P.OrgGroupId     
        INNER JOIN sSecurity.tModulePermission MP ON MP.ModuleId = T.ModuleId AND MP.OrgGroupId = P.OrgGroupId    
       WHERE    
        T.IsObsolete = 0 AND P.UserId = @rUserId    
       GROUP BY     
        TaskId) TBL2    
       ON     
        Screen.TaskId = TBL2.TaskId     
         LEFT OUTER JOIN sSecurity.tTask  T ON T.Id =  Screen.TaskId AND ResourceTypeId = @rResourceTypeId    
          
       WHERE     
       (Menu.IsObsolete = 0)  --For ScreenGroupId Master Page    
       AND ISNULL(Screen.IsObsolete, 0) = 0)     
       MenuTable      
       --INNER JOIN sSecurity.tTask  T ON T.Id =  MenuTable.TaskId     
   WHERE     
    MenuTable.ScreenId = 0 OR MenuTable.Permission >= 2     
    AND     
    ((MenuTable.ResourceTypeId = @rResourceTypeId) OR (@rResourceTypeId = 0))    
    AND ((MenuTable.MenuID = @rMenuID)OR(@rMenuID = 0))    
        
   ORDER BY     
    ParentMenuID    
  END    
 ELSE     
  BEGIN    
   SELECT    
    MenuID,    
    ModuleId,    
    ParentMenuID,    
    MenuTitle,      
    ScreenTitle,       
    PageURL,    
    ScreenId,    
    Permission,    
    OrderNumber,      
    TaskId,      
     PageURL  AS PagePath,    
     IconPath    
        
   FROM    
     (SELECT Menu.Id AS MenuID,     
    ISNULL(Menu.ParentMenuID, 0) AS ParentMenuID,     
    Menu.Title AS MenuTitle,       
    ISNULL(Screen.Title, '') AS ScreenTitle,        
    ISNULL(Screen.Page, '') AS PageURL,    
    ISNULL(Screen.ScreenGroupId,0) AS ScreenGroupId,    
    ISNULL(Menu.ScreenId, 0) AS ScreenId,    
    ISNULL(PermissionValue, 0) AS Permission,    
    ISNULL(OrderNumber, 0) AS OrderNumber,    
    ISNULL(Screen.TaskId,0) AS TaskId,    
    ISNULL(Screen.IconPath,'') As IconPath,     
    ISNULL(T.ResourceTypeId,0) AS ResourceTypeId,    
    ISNULL(T.ModuleId,0) AS ModuleId    
       
       
   FROM sSecurity.tMenu Menu     
   LEFT OUTER JOIN sSecurity.tScreen Screen    
    ON Menu.ScreenId = Screen.Id      
   LEFT OUTER JOIN (     
       SELECT     
        TaskId,     
        SUM(Permission & 2) PermissionValue          
       FROM     
        sSecurity.tPermission P    
        INNER JOIN sSecurity.tTask T ON T.Id = P.TaskId    
        --INNER JOIN sSecuirty.tOrganizationTask OT ON OT.TaskId = T.Id AND OT.OrgGroupId = P.OrgGroupId     
        INNER JOIN sSecurity.tModulePermission MP ON MP.ModuleId = T.ModuleId AND MP.OrgGroupId = P.OrgGroupId    
        INNER JOIN    
        (    
        SELECT RoleId FROM sSecurity.tUserRole UR WHERE  UserId = @rUserId AND IsObsolete = 0    
        ) B ON B.RoleId = P.RoleId    
       WHERE    
        T.IsObsolete = 0  
       GROUP BY     
        TaskId) TBL2    
       ON     
        Screen.TaskId = TBL2.TaskId     
         LEFT OUTER JOIN sSecurity.tTask  T ON T.Id =  Screen.TaskId AND ResourceTypeId = @rResourceTypeId    
          
       WHERE     
       (Menu.IsObsolete = 0)  --For ScreenGroupId Master Page    
       AND ISNULL(Screen.IsObsolete, 0) = 0)     
       MenuTable      
       --INNER JOIN sSecurity.tTask  T ON T.Id =  MenuTable.TaskId     
   WHERE     
    MenuTable.ScreenId = 0 OR MenuTable.Permission >= 2     
    AND     
    ((MenuTable.ResourceTypeId = @rResourceTypeId) OR (@rResourceTypeId = 0))    
    AND ((MenuTable.MenuID = @rMenuID)OR(@rMenuID = 0))    
        
   ORDER BY     
    ParentMenuID    
  END    
 END    
 ELSE    
 BEGIN     
 SELECT    
   MenuID,    
   ModuleId,    
   ParentMenuID,    
   MenuTitle,      
   ScreenTitle,       
   PageURL,    
   ScreenId,    
   Permission,    
   OrderNumber,      
   TaskId,      
   PageURL  AS PagePath,    
   MenuIsObsolete,    
   Icon     
  FROM    
  (    

SELECT    
   ISNULL(Menu.Id,0) AS MenuID,     
   ISNULL(Menu.ParentMenuID, 0) AS ParentMenuID,     
   ISNULL(Menu.Title,'') AS MenuTitle,       
   ISNULL(Screen.Title, '') AS ScreenTitle,        
   ISNULL(Screen.Page, '') AS PageURL,    
   ISNULL(Screen.ScreenGroupId,0) AS ScreenGroupId,    
   ISNULL(Screen.Id, 0) AS ScreenId,    
   ISNULL(PermissionValue, 0) AS Permission,    
   ISNULL(OrderNumber, 0) AS OrderNumber,    
   ISNULL(Screen.TaskId,0) AS TaskId,    
   ISNULL(T.ResourceTypeId,0) AS ResourceTypeId,    
   ISNULL(T.ModuleId,0) AS ModuleId,    
   ISNULL(Menu.IsObsolete,1) AS MenuIsObsolete,    
   ISNULL(Screen.IconPath,'') AS Icon,
   ISNULL(Screen.OrderIndex,0) As OrderIndex     
  FROM     
  sSecurity.tMenu Menu     
  LEFT OUTER JOIN sSecurity.tScreen Screen ON Menu.ScreenId = Screen.Id        
  LEFT OUTER JOIN     
  (    
  SELECT     
   P.TaskId,     
   SUM(OT.AvailablePermission & 2) PermissionValue          
  FROM     
   sSecurity.tPermission P    
   INNER JOIN sSecurity.tTask T ON T.Id = P.TaskId  AND T.IsObsolete = 0  
   INNER JOIN sSecurity.tModulePermission MP ON MP.ModuleId = T.ModuleId      
   INNER JOIN sCommon.tModuleMaster MM ON MP.ModuleId = MM.Id And  MM.IsObsolete = 0    
   INNER JOIN sSecurity.tOrganizationTask OT ON OT.TaskId = T.Id        
   INNER JOIN (SELECT RoleId FROM sSecurity.tUserRole WHERE  UserId = @rUserId AND IsObsolete = 0) UR ON UR.RoleId = P.RoleId     
  GROUP BY P.TaskId    
  ) TBL2 ON Screen.TaskId = TBL2.TaskId     
  LEFT OUTER JOIN sSecurity.tTask  T ON T.Id =  Screen.TaskId AND ResourceTypeId = @rResourceTypeId    
  WHERE (Menu.IsObsolete = 0)    
  AND ISNULL(Screen.IsObsolete, 0) = 0    
  AND (Menu.Id  in (19184028))   
  --Or ParentMenuID  in (24,2711))     
  --AND (
  ----Menu.Id IN (19184027)  
  ----OR ParentMenuID IN (55)
  --)  

  UNION
  

  SELECT     
  
   ISNULL(Menu.Id, 0) AS MenuID,     
   ISNULL(Menu.Id, 0) AS ParentMenuID,     
   ISNULL(Screen1.Title,'') AS MenuTitle,       
   ISNULL(Screen1.Title, '') AS ScreenTitle,        
   ISNULL(Screen1.Page, '')  AS PageURL,    
   ISNULL(Screen1.ScreenGroupId,0) AS ScreenGroupId,    
   ISNULL(Screen1.Id, 0) AS ScreenId,    
   ISNULL(PermissionValue, 0) AS Permission,    
   ISNULL(OrderNumber, 0) AS OrderNumber,    
   ISNULL(Screen1.TaskId,0) AS TaskId,    
   ISNULL(T.ResourceTypeId,0) AS ResourceTypeId,    
   ISNULL(T.ModuleId,0) AS ModuleId,    
   ISNULL(Menu.IsObsolete,1) AS MenuIsObsolete,    
   ISNULL(Screen1.IconPath,'') AS Icon,
   ISNULL(Screen1.OrderIndex,0) As OrderIndex    
  FROM     
   sSecurity.tMenu Menu     
   LEFT OUTER JOIN sSecurity.tScreen Screen ON Menu.ScreenId = Screen.Id        
   LEFT OUTER JOIN sSecurity.tScreen Screen1 ON Screen1.ScreenGroupId = Screen.ScreenGroupId     
   LEFT OUTER JOIN sSecurity.tTask  T ON T.Id =  Screen1.TaskId    
   LEFT OUTER JOIN (     
  SELECT     
   P.TaskId,     
   SUM(OT.AvailablePermission & 2) PermissionValue          
  FROM     
   sSecurity.tPermission P    
   INNER JOIN sSecurity.tTask T ON T.Id = P.TaskId   AND T.IsObsolete = 0  
   INNER JOIN sSecurity.tModulePermission MP ON MP.ModuleId = T.ModuleId        
   INNER JOIN sCommon.tModuleMaster MM ON MP.ModuleId = MM.Id And  MM.IsObsolete = 0    
   INNER JOIN sSecurity.tOrganizationTask OT ON OT.TaskId = T.Id       
   INNER JOIN (SELECT RoleId FROM sSecurity.tUserRole WHERE  UserId = @rUserId AND IsObsolete = 0) UR ON UR.RoleId = P.RoleId    
            
  GROUP BY P.TaskId    
  ) TBL2 ON Screen1.TaskId = TBL2.TaskId    
  WHERE (Menu.IsObsolete = 0) AND ISNULL(Screen1.IsObsolete, 0) = 0    
  --AND (Menu.ParentMenuID  in (24,2711)   
  --or Menu.Id  in (24,2711))   
  AND TBL2.PermissionValue > 0
  AND Screen1.Id IN (31296,31297,31298,31299,31300,31301,31310,31311,31312)
  ) MenuTable      
  WHERE     
  --(MenuTable.ScreenId = 0 OR MenuTable.Permission >= 2)
  --AND   
  ((MenuTable.ResourceTypeId = @rResourceTypeId) OR (@rResourceTypeId = 0))    
  AND ((MenuTable.MenuID = @rMenuID)OR(@rMenuID = 0))    
  AND MenuIsObsolete = 0    
  AND MenuTable.MenuId IN (19184028)   
  AND ModuleId IN (96)
  ORDER BY MenuTable.OrderIndex, ParentMenuID  
 END   
END
GO
PRINT N'Altering Procedure [sPurchase].[pPurchaseOrderApprovedSearchGet]...';


GO


--exec [sPurchase].[pPurchaseOrderApprovedSearchGet] '',991100001,'',9911,'2023-01-01','2023-12-01',1,10,null
ALTER PROCEDURE [sPurchase].[pPurchaseOrderApprovedSearchGet]

	@rNumber nvarchar(30) = '',
	@rLocationId int,
	@rName nvarchar = '',
	@rOrgGroupId int,
	@rStartDate DateTime = null,
	@rEndDate DateTime = null,
	@rPageNo int,
	@rPageSize int,
	@rStatusId smallint = 0

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY


		DECLARE @TotalRecords BIGINT;
		-- Get the total number of records
		SELECT @TotalRecords = COUNT(*) FROM sPurchase.tPurchaseOrder PO (nolock)

		WHERE 
				((PO.RefNumber like @rNumber+'%') OR (ISNULL(@rNumber,'') = ''))
   				AND ((PO.RequestedBy like @rName+'%') OR (ISNULL(@rName,'') = ''))
   				--AND ((SLM.Id = @rStoreLocationId) OR (@rStoreLocationId = 0))
   				AND ((PO.OrgGroupId = @rOrgGroupId) OR (@rOrgGroupId=0))
				AND ((PO.StatusId = @rStatusId) OR (ISNULL(@rStatusId,0)=0))
				AND PO.IsObsolete = 0 and PO.StatusId = 3
				AND ((Cast(PO.CreatedDateTime as Date) >= Cast(@rStartDate as Date)) OR (ISNULL(@rStartDate,'')=''))
				AND((Cast(PO.CreatedDateTime as Date) <= Cast(@rEndDate as Date)) OR (ISNULL(@rEndDate,'')=''))


	    Select t.* From (
			Select ROW_NUMBER() Over (
			Order by PO.Id desc  
			) AS 'RowNum',
				PO.Id, 
				PO.RefNumber as Number,
				PO.RequestedBy, 
				PO.LocationId, 
				PO.PODate,
				ISNULL(SM.Title,'') as Status
		FROM		
				sPurchase.tPurchaseOrder PO (nolock)
				Left Join [sWf].[tWfStatusMaster] SM on PO.StatusId = SM.Id
		WHERE 
				((PO.RefNumber like @rNumber+'%') OR (ISNULL(@rNumber,'') = ''))
   				AND ((PO.RequestedBy like @rName+'%') OR (ISNULL(@rName,'') = ''))
   				--AND ((SLM.Id = @rStoreLocationId) OR (@rStoreLocationId = 0))
   				AND ((PO.OrgGroupId = @rOrgGroupId) OR (@rOrgGroupId=0))
				AND ((PO.StatusId = @rStatusId) OR (ISNULL(@rStatusId,0)=0))
				AND PO.IsObsolete = 0 and PO.StatusId = 3
				AND ((Cast(PO.CreatedDateTime as Date) >= Cast(@rStartDate as Date)) OR (ISNULL(@rStartDate,'')=''))
				AND((Cast(PO.CreatedDateTime as Date) <= Cast(@rEndDate as Date)) OR (ISNULL(@rEndDate,'')=''))
					)t Where t.RowNum Between
		        ((@rPageNo-1)*@rPageSize +1) AND (@rPageNo*@rpageSize)

        SELECT @TotalRecords as TotalRecords

	 
	 END TRY

	BEGIN CATCH
    IF @@TRANCOUNT > 0
        ROLLBACK TRAN --RollBack in case of Error
    
    DECLARE @ErrorMessage NVARCHAR(4000);  
    DECLARE @ErrorSeverity INT;  
    DECLARE @ErrorState INT;  
    SELECT   
       @ErrorMessage = ERROR_MESSAGE(),  
       @ErrorSeverity = ERROR_SEVERITY(),  
       @ErrorState = ERROR_STATE();  
    RAISERROR (@ErrorMessage, @ErrorSeverity, @ErrorState);  
    
	END CATCH  		  
END
GO
PRINT N'Altering Procedure [sPurchase].[pPurchaseOrderSearchGet]...';


GO



ALTER PROCEDURE [sPurchase].[pPurchaseOrderSearchGet]

	@rNumber nvarchar(30) = '',
	@rLocationId int,
	@rName nvarchar = '',
	@rOrgGroupId int,
	@rStartDate DateTime = null,
	@rEndDate DateTime = null,
	@rPageNo int,
	@rPageSize int,
	@rStatusId smallint = null

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY


		If @rNumber = NULL SET @rNumber=''
		If @rName = NULL SET @rName=''
		If @rStartDate = '' SET @rStartDate=NULL
		If @rEndDate = '' SET @rEndDate=NULL
		If @rStatusId is NULL SET @rStatusId=0

		DECLARE @TotalRecords BIGINT;
		-- Get the total number of records
		SELECT @TotalRecords = COUNT(*) FROM sPurchase.tPurchaseOrder PO (nolock)

		WHERE 
				((PO.RefNumber like @rNumber+'%') OR (@rNumber = ''))
   				AND ((PO.RequestedBy like @rName+'%') OR (@rName = ''))
   				--AND ((SLM.Id = @rStoreLocationId) OR (@rStoreLocationId = 0))
   				AND ((PO.OrgGroupId = @rOrgGroupId) OR (@rOrgGroupId=0))
				AND ((PO.StatusId = @rStatusId) OR (@rStatusId=0))
				AND PO.IsObsolete = 0
				AND ((Cast(PO.CreatedDateTime as Date) >= Cast(@rStartDate as Date)) OR (ISNULL(@rStartDate,'')=''))
				AND((Cast(PO.CreatedDateTime as Date) <= Cast(@rEndDate as Date)) OR (ISNULL(@rEndDate,'')=''))

	    Select t.* From (
			Select ROW_NUMBER() Over (
			Order by PO.Id desc  
			) AS 'RowNum',PO.Id,
				PO.PurchaseRequestId,
				PO.RefNumber as Number,
				PO.RequestedBy, 
				PO.LocationId, 
				PO.PODate,
				ISNULL(SM.Title,'') as Status
				
		 FROM		
				sPurchase.tPurchaseOrder PO (nolock)
				Left Join [sWf].[tWfStatusMaster] SM on PO.StatusId = SM.Id

         
		 WHERE 
				((PO.RefNumber like @rNumber+'%') OR (@rNumber = ''))
   				AND ((PO.RequestedBy like @rName+'%') OR (@rName = ''))
   				--AND ((SLM.Id = @rStoreLocationId) OR (@rStoreLocationId = 0))
   				AND ((PO.OrgGroupId = @rOrgGroupId) OR (@rOrgGroupId=0))
				AND ((PO.StatusId = @rStatusId) OR (@rStatusId=0))
				AND PO.IsObsolete = 0
				AND ((Cast(PO.CreatedDateTime as Date) >= Cast(@rStartDate as Date)) OR (ISNULL(@rStartDate,'')=''))
				AND((Cast(PO.CreatedDateTime as Date) <= Cast(@rEndDate as Date)) OR (ISNULL(@rEndDate,'')=''))
				)t Where t.RowNum Between
		        ((@rPageNo-1)*@rPageSize +1) AND (@rPageNo*@rpageSize)

        SELECT @TotalRecords as TotalRecords
	 END TRY

	BEGIN CATCH
    IF @@TRANCOUNT > 0
        ROLLBACK TRAN --RollBack in case of Error
    
    DECLARE @ErrorMessage NVARCHAR(4000);  
    DECLARE @ErrorSeverity INT;  
    DECLARE @ErrorState INT;  
    SELECT   
       @ErrorMessage = ERROR_MESSAGE(),  
       @ErrorSeverity = ERROR_SEVERITY(),  
       @ErrorState = ERROR_STATE();  
    RAISERROR (@ErrorMessage, @ErrorSeverity, @ErrorState);  
    
	END CATCH  		  
END
GO
PRINT N'Altering Procedure [sPurchase].[pPurchaseRequestGet]...';


GO

--exec [sPurchase].[pPurchaseRequestGet] 991100003
ALTER PROCEDURE [sPurchase].[pPurchaseRequestGet]
	  @rId bigint
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
		select  PR.Id,
				PR.Number,
				PR.RequestedBy,
				PR.StatusId,
				PR.VendorId,
				PR.LocationId,
				PR.BranchId,
				PR.OrgGroupId,
				PR.ResourceId,
				PR.RequestDate,
				PR.RequiredBy,
				ISNULL(SM.Title,'') as Status,
				VM.Code AS VendorCode,
				VM.Title AS VendorName
		from    [sPurchase].[tPurchaseRequest] PR (nolock) 
			    Left Join sProcurement.tVendorMaster  VM on PR.VendorId = VM.ID
				Left Join [sWf].[tWfStatusMaster] SM ON SM.Id = PR.StatusId
		where   PR.Id=@rId AND PR.IsObsolete = 0

		select PRD.Id,
			   PRD.PurchaseRequestId,
			   PRD.OrgGroupId,
			   PRD.StockItemId,
			   PRD.RequestedQty,
			   PRD.Remark, 
			   SIM.Code	AS StockItemCode,
			   SCM.Title AS CategoryName,
			   SIM.Title AS StockItemName,
			   SUMa.Code AS UOM
		from   [sPurchase].[tPurchaseRequestDetail] PRD (nolock)
			   Inner JOIN	sPurchase.tPurchaseRequest PR	ON PR.Id = PRD.PurchaseRequestId AND PR.IsObsolete = 0
			   Inner JOIN	sIp.tStockItemMaster SIM	ON SIM.Id = PRD.StockItemId 
			   LEFT JOIN [sIp].[tStockItemCategoryMaster] SCM ON SCM.Id = SIM.StockItemCategoryId
			   Inner JOIN  sFinanceCommon.tStockUomMaster SUMa ON SUMa.Id = SIM.IssueStockUomId
		where  PurchaseRequestId=@rId

	
	END TRY

	BEGIN CATCH
    IF @@TRANCOUNT > 0
        ROLLBACK TRAN --RollBack in case of Error
    
    DECLARE @ErrorMessage NVARCHAR(4000);  
    DECLARE @ErrorSeverity INT;  
    DECLARE @ErrorState INT;  
    SELECT   
       @ErrorMessage = ERROR_MESSAGE(),  
       @ErrorSeverity = ERROR_SEVERITY(),  
       @ErrorState = ERROR_STATE();  
    RAISERROR (@ErrorMessage, @ErrorSeverity, @ErrorState);  
    
	END CATCH

END
GO
PRINT N'Altering Procedure [sPurchase].[pPurchaseRequestSearchGet]...';


GO

--exec [sPurchase].[pPurchaseRequestSearchGet] null,991100001,null,9911,'2023-12-07','2023-12-08',1,10,null
ALTER PROCEDURE [sPurchase].[pPurchaseRequestSearchGet]

	@rNumber nvarchar(30) = '',
	@rLocationId int,
	@rName nvarchar  = '',
	@rOrgGroupId int,
	@rStartDate DateTime = null,
	@rEndDate DateTime = null,
	@rPageNo int,
	@rPageSize int,
	@rStatusId smallint = 0

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY


		If @rNumber = NULL SET @rNumber=''
		If @rName = NULL SET @rName=''
		If @rStartDate = '' SET @rStartDate=NULL
		If @rEndDate = '' SET @rEndDate=NULL
		If @rStatusId is NULL SET @rStatusId=0

		DECLARE @TotalRecords BIGINT;
		-- Get the total number of records
		SELECT @TotalRecords = COUNT(*) FROM sPurchase.tPurchaseRequest PR (nolock)

		WHERE 
				((PR.Number like @rNumber+'%') OR (ISNULL(@rNumber,'') = ''))
   				AND ((PR.RequestedBy like @rName+'%') OR (ISNULL(@rName,'') = ''))
   				--AND ((SLM.Id = @rStoreLocationId) OR (@rStoreLocationId = 0))
   				AND ((PR.OrgGroupId = @rOrgGroupId) OR (@rOrgGroupId=0))
   				AND ((PR.StatusId = @rStatusId) OR (ISNULL(@rStatusId,0)=0))
				AND PR.IsObsolete = 0
				AND ((Cast(PR.CreatedDateTime as Date) >= Cast(@rStartDate as Date)) OR (ISNULL(@rStartDate,'')=''))
				AND((Cast(PR.CreatedDateTime as Date) <= Cast(@rEndDate as Date)) OR (ISNULL(@rEndDate,'')=''))
			

	    Select t.* From (
			Select ROW_NUMBER() Over (
			Order by PR.Id desc  
			) AS 'RowNum',PR.Id, 
				PR.Number,
				PR.RequestedBy, 
				PR.LocationId, 
				PR.RequestDate,
				ISNULL(SM.Title,'') as Status

        FROM		
				sPurchase.tPurchaseRequest PR (nolock)
				Left Join [sWf].[tWfStatusMaster] SM on PR.StatusId = SM.Id

        WHERE 
				((PR.Number like @rNumber+'%') OR (ISNULL(@rNumber,'') = ''))
   				AND ((PR.RequestedBy like @rName+'%') OR (ISNULL(@rName,'') = ''))
   				--AND ((SLM.Id = @rStoreLocationId) OR (@rStoreLocationId = 0))
   				AND ((PR.OrgGroupId = @rOrgGroupId) OR (@rOrgGroupId=0))
   				AND ((PR.StatusId = @rStatusId) OR (ISNULL(@rStatusId,0)=0))
				AND PR.IsObsolete = 0
				AND ((Cast(PR.CreatedDateTime as Date) >= Cast(@rStartDate as Date)) OR (ISNULL(@rStartDate,'')=''))
				AND((Cast(PR.CreatedDateTime as Date) <= Cast(@rEndDate as Date)) OR (ISNULL(@rEndDate,'')=''))
					)t Where t.RowNum Between
		        ((@rPageNo-1)*@rPageSize +1) AND (@rPageNo*@rpageSize)

        SELECT @TotalRecords as TotalRecords
	 END TRY

	BEGIN CATCH
    IF @@TRANCOUNT > 0
        ROLLBACK TRAN --RollBack in case of Error
    
    DECLARE @ErrorMessage NVARCHAR(4000);  
    DECLARE @ErrorSeverity INT;  
    DECLARE @ErrorState INT;  
    SELECT   
       @ErrorMessage = ERROR_MESSAGE(),  
       @ErrorSeverity = ERROR_SEVERITY(),  
       @ErrorState = ERROR_STATE();  
    RAISERROR (@ErrorMessage, @ErrorSeverity, @ErrorState);  
    
	END CATCH  		  
END
GO
PRINT N'Altering Procedure [sPurchase].[pPurchaseScreenGet]...';


GO
--exec [sPurchase].[pPurchaseScreenGet]
ALTER PROCEDURE [sPurchase].[pPurchaseScreenGet]
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
begin
	BEGIN TRY
		SELECT	
			S.Id			AS ScreenId,
			S.Title		AS ScreenTitle,
			S.TaskId		AS TaskId,	
			S.Page		As PageUrl,
			S.IsObsolete	AS ScreenIsObsolete,	
			S.Title,		
			S.Page,
			SG.Id AS ScreenGroupId,
			ISNULL(SG.Title,'') AS ScreenGroupName
		
		FROM 
			sSecurity.tScreen S (nolock)
		LEFT JOIN sSecurity.tScreenGroupMaster SG ON SG.Id=S.ScreenGroupId
		WHERE 
			S.IsObsolete = 0 and S.ScreenGroupID=254 and S.Id in (31296,31297,31298,31299,31300,31301,31310,31311,31312)
		Order by S.OrderIndex
	END TRY

	BEGIN CATCH
    IF @@TRANCOUNT > 0
        ROLLBACK TRAN --RollBack in case of Error
    
    DECLARE @ErrorMessage NVARCHAR(4000);  
    DECLARE @ErrorSeverity INT;  
    DECLARE @ErrorState INT;  
    SELECT   
       @ErrorMessage = ERROR_MESSAGE(),  
       @ErrorSeverity = ERROR_SEVERITY(),  
       @ErrorState = ERROR_STATE();  
    RAISERROR (@ErrorMessage, @ErrorSeverity, @ErrorState);  
    
	END CATCH
end
GO
PRINT N'Altering Procedure [sPurchase].[pQualityCheckAdd]...';


GO




ALTER PROCEDURE [sPurchase].[pQualityCheckAdd]
		@rId bigint,
		@rGoodsReceivedNoteId bigint,
		@rPurchaseOrderId bigint,
		@rRequestedBy nvarchar(100),
		@rOrgGroupId smallint,
		@rLocationId int,
		@rStatusId smallint,	
		@rUserId bigint,
		@rDetailList sPurchase.QualityCheckDetailType READONLY
 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
	BEGIN TRANSACTION

		If(@rId > 0)
		Begin
			CREATE TABLE #temp_table (
						OrgGroupId SMALLINT,
						LocationId INT,
						StockItemId BIGINT,
						AcceptedQty decimal(12,2),
						Operation nvarchar(20),
						UserId BIGINT
					);

			Insert Into #temp_table
			Select QCD.OrgGroupId,@rLocationId,QCD.StockItemId,
			CASE
			WHEN QCD.AcceptedQty > DL.AcceptedQty THEN QCD.AcceptedQty - DL.AcceptedQty
			ELSE DL.AcceptedQty - QCD.AcceptedQty
			END,
			CASE
			WHEN QCD.AcceptedQty > DL.AcceptedQty THEN '-'
			ELSE '+'
			END,
			@rUserId 
			from sPurchase.tQualityCheckDetail QCD
			Inner Join @rDetailList DL ON DL.StockItemId = QCD.StockItemId and QCD.QualityCheckId = @rId
			where QualityCheckId = @rId



			Update sPurchase.tQualityCheck
			set 
				StatusId = @rStatusId,
				GoodsReceivedNoteId = @rGoodsReceivedNoteId,
				PurchaseOrderId = @rPurchaseOrderId,
				UpdatedUserId = @rUserId,		
				UpdatedDateTime = GetUtcDate()
			where Id = @rId and IsObsolete = 0

			delete from sPurchase.tQualityCheckDetail
			where Id not in(select Id from @rDetailList)
			and QualityCheckId = @rId

			update sPurchase.tQualityCheckDetail
			set
			GoodsReceivedNoteDetailId = DL.GoodsReceivedNoteDetailId,
			StockItemId = DL.StockItemId,
			POQty = DL.POQty,
			ReceivedQty = DL.ReceivedQty,
			AcceptedQty = DL.AcceptedQty,
			RejectedQty = DL.RejectedQty,
			ReasonForRejection = DL.ReasonForRejection,
			UpdatedUserId = @rUserId,
			UpdatedDateTime = GETUTCDATE()
			from @rDetailList DL
			inner join sPurchase.tQualityCheckDetail QC ON DL.ID = QC.Id
			where QC.QualityCheckId = @rId

			DECLARE @lNextNumberQCD BIGINT	 
			EXECUTE [sCommon].[pGetIntMaxIdForOrgGroup] @rOrgGroupId, 'sPurchase.tQualityCheckDetail',@lNextNumber = @lNextNumberQCD output
			set @lNextNumberQCD=@lNextNumberQCD-1
			INSERT INTO sPurchase.tQualityCheckDetail
			(
				Id,
				OrgGroupId,
				QualityCheckId,
				GoodsReceivedNoteDetailId,
				StockItemId,
				POQty,
				ReceivedQty,
				AcceptedQty,
				RejectedQty,
				ReasonForRejection,
				CreatedUserId,
				CreatedDateTime
			)
			select	@lNextNumberQCD+Id,
					@rOrgGroupId,
					@rId,
					GoodsReceivedNoteDetailId,
					StockItemId,
					POQty,
					ReceivedQty,
					AcceptedQty,
					RejectedQty,
					ReasonForRejection,
					@rUserId, 
					GETUTCDATE() 
			from @rDetailList
			where Id not in(Select DL.Id from @rDetailList DL
			inner join sPurchase.tQualityCheckDetail QC ON DL.ID = QC.Id
			where QC.QualityCheckId = @rId)

			set @lNextNumberQCD=@lNextNumberQCD+(select Count(Id) from @rDetailList where Id not in(Select DL.Id from @rDetailList DL
			inner join sPurchase.tQualityCheckDetail QC ON DL.ID = QC.Id
			where QC.QualityCheckId = @rId))
			EXECUTE sCommon.pTableRowIdModify @rOrgGroupId, @rTableTitle = 'sPurchase.tQualityCheckDetail', @rCurrentNumber = @lNextNumberQCD
			
			UPDATE  sProcurement.tStockBatch
				SET  AvailableQuantity = ISNULL(AvailableQuantity,0) + tt.AcceptedQty,
					UpdatedUserId = @rUserId,
					UpdatedDateTime = sCommon.fGetDate()
				FROM sProcurement.tStockBatch SB
				Inner Join #temp_table tt ON SB.Id = tt.StockItemId
				WHERE  
			(SB.StoreLocationId = tt.LocationId OR tt.LocationId = 0) AND
			(SB.StockItemId = tt.StockItemId) AND
			--(Number = @rNumber OR ISNULL(@rNumber, '') = '') AND
			--(ExpiryDate = @rExpiryDate OR ISNULL(@rExpiryDate, '') = '') AND
				SB.OrgGroupId = @rOrgGroupId
				And tt.Operation = '+'

			UPDATE  sProcurement.tStockBatch
				SET  AvailableQuantity = ISNULL(AvailableQuantity,0) - tt.AcceptedQty,
					UpdatedUserId = @rUserId,
					UpdatedDateTime = sCommon.fGetDate()
				FROM sProcurement.tStockBatch SB
				Inner Join #temp_table tt ON SB.Id = tt.StockItemId
				WHERE  
			(SB.StoreLocationId = tt.LocationId OR tt.LocationId = 0) AND
			(SB.StockItemId = tt.StockItemId) AND
			--(Number = @rNumber OR ISNULL(@rNumber, '') = '') AND
			--(ExpiryDate = @rExpiryDate OR ISNULL(@rExpiryDate, '') = '') AND
				SB.OrgGroupId = @rOrgGroupId
				And tt.Operation = '-'


			select @rId
		End
		Else
		Begin
			DECLARE @lNextNumber INT	 
			EXECUTE [sCommon].[pGetIntMaxIdForOrgGroup] @rOrgGroupId, 'sPurchase.tQualityCheck',@lNextNumber = @lNextNumber output	
			---------------select @lNextNumber
			--DECLARE @loNextNumber nVarchar(20)
			--EXECUTE sCommon.pPrefixSetupNextNumberGet @rOrgId = @rOrgGroupId, @rPrefixFunctionalityId = 1005,@rStoreLocationId = @rLocationId,
			---------------@rNextNumber = @loNextNumber OUTPUT

	 		INSERT INTO sPurchase.tQualityCheck
			(
				Id,
				QCNumber,
				GoodsReceivedNoteId,
				PurchaseOrderId,
				RequestedBy, 
				OrgGroupId,
				LocationId, 			 
				StatusId,
				CreatedUserId,		
				CreatedDateTime
	
			)
			VALUES
			(
				@lNextNumber,
				@lNextNumber,
				@rGoodsReceivedNoteId,
				@rPurchaseOrderId,
				@rRequestedBy,	 
				@rOrgGroupId,
				@rLocationId, 		 
				@rStatusId,
				@rUserId,		
				GETUTCDATE()
			)
 
			set @rId = @lNextNumber  
			
			DECLARE @lNextNumberQCDD BIGINT	 
			EXECUTE [sCommon].[pGetIntMaxIdForOrgGroup] @rOrgGroupId, 'sPurchase.tQualityCheckDetail',@lNextNumber = @lNextNumberQCDD output	
			set @lNextNumberQCDD=@lNextNumberQCDD-1

	 		INSERT INTO sPurchase.tQualityCheckDetail
			(
				Id,
				OrgGroupId,
				QualityCheckId,
				GoodsReceivedNoteDetailId,
				StockItemId,
				POQty,
				ReceivedQty,
				AcceptedQty,
				RejectedQty,
				ReasonForRejection,
				CreatedUserId,
				CreatedDateTime
			)
			select	@lNextNumberQCDD+Id,
					@rOrgGroupId,
					@rId,
					GoodsReceivedNoteDetailId,
					StockItemId,
					POQty,
					ReceivedQty,
					AcceptedQty,
					RejectedQty,
					ReasonForRejection,
					@rUserId, 
					GETUTCDATE() 
			from @rDetailList
						
			set @lNextNumberQCDD=@lNextNumberQCDD+(select Count(Id) from @rDetailList)
			EXECUTE sCommon.pTableRowIdModify @rOrgGroupId, @rTableTitle = 'sPurchase.tQualityCheckDetail', @rCurrentNumber = @lNextNumberQCDD

			UPDATE  sProcurement.tStockBatch
				SET  AvailableQuantity = ISNULL(AvailableQuantity,0) + QC.AcceptedQty,
					UpdatedUserId = @rUserId,
					UpdatedDateTime = sCommon.fGetDate()
				FROM sProcurement.tStockBatch SB
				Inner Join sPurchase.tQualityCheckDetail QC ON SB.Id = QC.StockItemId
				WHERE  
			(SB.StoreLocationId = @rLocationId OR @rLocationId = 0) AND
			(SB.StockItemId = QC.StockItemId) AND
			--(Number = @rNumber OR ISNULL(@rNumber, '') = '') AND
			--(ExpiryDate = @rExpiryDate OR ISNULL(@rExpiryDate, '') = '') AND
				SB.OrgGroupId = @rOrgGroupId

			select @rId
			--select 1;
		End
	COMMIT TRAN -- Transaction Success!	
	END TRY

	BEGIN CATCH
    IF @@TRANCOUNT > 0
        ROLLBACK TRAN --RollBack in case of Error

    
    DECLARE @ErrorMessage NVARCHAR(4000);  
    DECLARE @ErrorSeverity INT;  
    DECLARE @ErrorState INT;  

    SELECT   
       @ErrorMessage = ERROR_MESSAGE(),  
       @ErrorSeverity = ERROR_SEVERITY(),  
       @ErrorState = ERROR_STATE();  

    RAISERROR (@ErrorMessage, @ErrorSeverity, @ErrorState);  
    
	END CATCH
END
GO
PRINT N'Altering Procedure [sPurchase].[pQualityCheckSearchGet]...';


GO

--exec [sPurchase].[pQualityCheckSearchGet] null,991100001,null,9911,null,null,1,10,null
ALTER PROCEDURE [sPurchase].[pQualityCheckSearchGet]

	@rNumber nvarchar(30) = '',
	@rLocationId int,
	@rName nvarchar = '',
	@rOrgGroupId int,
	@rStartDate DateTime = null,
	@rEndDate DateTime = null,
	@rPageNo int,
	@rPageSize int,
	@rStatusId smallint = 0

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY


		If @rNumber = NULL SET @rNumber=''
		If @rName = NULL SET @rName=''
		If @rStartDate = '' SET @rStartDate=NULL
		If @rEndDate = '' SET @rEndDate=NULL
		If @rStatusId is NULL SET @rStatusId=0

		DECLARE @TotalRecords BIGINT;
		-- Get the total number of records
		SELECT @TotalRecords = COUNT(*) FROM sPurchase.tQualityCheck QC (nolock)

		WHERE 
				((QC.QCNumber like @rNumber+'%') OR (@rNumber = ''))
   				AND ((QC.RequestedBy like @rName+'%') OR (@rName = ''))
   				--AND ((SLM.Id = @rStoreLocationId) OR (@rStoreLocationId = 0))
   				AND ((QC.OrgGroupId = @rOrgGroupId) OR (@rOrgGroupId=0))
				AND ((QC.StatusId = @rStatusId) OR (@rStatusId=0))
				AND QC.IsObsolete = 0
				AND ((Cast(QC.CreatedDateTime as Date) >= Cast(@rStartDate as Date)) OR (ISNULL(@rStartDate,'')=''))
				AND((Cast(QC.CreatedDateTime as Date) <= Cast(@rEndDate as Date)) OR (ISNULL(@rEndDate,'')=''))

		Select t.* From (
			Select ROW_NUMBER() Over (
			Order by QC.Id desc  
			) AS 'RowNum',QC.Id,
				QC.QCNumber as Number,
				QC.RequestedBy, 
				QC.LocationId,
				ISNULL(SM.Title,'') as Status

        FROM		
				sPurchase.tQualityCheck QC (nolock)
				Left Join [sWf].[tWfStatusMaster] SM on QC.StatusId = SM.Id


	    WHERE 
				((QC.QCNumber like @rNumber+'%') OR (@rNumber = ''))
   				AND ((QC.RequestedBy like @rName+'%') OR (@rName = ''))
   				--AND ((SLM.Id = @rStoreLocationId) OR (@rStoreLocationId = 0))
   				AND ((QC.OrgGroupId = @rOrgGroupId) OR (@rOrgGroupId=0))
				AND ((QC.StatusId = @rStatusId) OR (@rStatusId=0))
				AND QC.IsObsolete = 0
				AND ((Cast(QC.CreatedDateTime as Date) >= Cast(@rStartDate as Date)) OR (ISNULL(@rStartDate,'')=''))
				AND((Cast(QC.CreatedDateTime as Date) <= Cast(@rEndDate as Date)) OR (ISNULL(@rEndDate,'')=''))
					)t Where t.RowNum Between
		        ((@rPageNo-1)*@rPageSize +1) AND (@rPageNo*@rpageSize)

        SELECT @TotalRecords as TotalRecords
	 END TRY

	BEGIN CATCH
    IF @@TRANCOUNT > 0
        ROLLBACK TRAN --RollBack in case of Error
    
    DECLARE @ErrorMessage NVARCHAR(4000);  
    DECLARE @ErrorSeverity INT;  
    DECLARE @ErrorState INT;  
    SELECT   
       @ErrorMessage = ERROR_MESSAGE(),  
       @ErrorSeverity = ERROR_SEVERITY(),  
       @ErrorState = ERROR_STATE();  
    RAISERROR (@ErrorMessage, @ErrorSeverity, @ErrorState);  
    
	END CATCH  		  
END
GO
PRINT N'Altering Procedure [sPurchase].[pSalesReturnGet]...';


GO

--exec [sPurchase].[pSalesReturnGet] 991100001
ALTER PROCEDURE [sPurchase].[pSalesReturnGet]
	  @rId int
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
		select  SR.Id,
				SR.SRNumber,
				SR.OrgGroupId,
				SR.LocationId,
				SR.GoodsReceivedNoteId,
				SR.PurchaseOrderId,
				SR.VendorId,
				SR.RequestedBy,
				ISNULL(GRN.GRNNumber,'') as GRNNumber,
				SR.StatusId,
				ISNULL(SM.Title,'') as Status,
				VM.Title AS VendorName,
				PO.RefNumber as PurchaseOrderNumber
		from   [sPurchase].[tSalesReturn] SR(nolock) 
		Left Join [sPurchase].[tGoodsReceivedNote] GRN ON GRN.Id = SR.GoodsReceivedNoteID
		left JOIN sPurchase.tPurchaseOrder PO on PO.Id = SR.PurchaseOrderId
		Left Join [sWf].[tWfStatusMaster] SM ON SM.Id = SR.StatusId
		LEFT JOIN  sProcurement.tVendorMaster  VM on SR.VendorId = VM.ID
		where  SR.Id=@rId AND SR.IsObsolete = 0

		select SRD.Id,
			   SRD.SalesReturnId,
			   SRD.GoodsReceivedNoteDetailId,
			   SRD.OrgGroupId,
			   SRD.StockItemId,
			   SRD.POQty,
			   SRD.ReceivedQty,
			   SRD.RejectedQty,
			   SUMa.Id AS UnitTypeId,
			   SRD.CreditNoteIssueDate,
			   SRD.ReasonForRejection, 
			   SIM.Code	AS StockItemCode,
			   SIM.Title AS StockItemName,
			   SUMa.Code AS UOM,
			   SCM.Id as CategoryId,
			   SCM.Title as CategoryName,
			   0 as SubCategoryId
		from   [sPurchase].[tSalesReturnDetail] SRD (nolock)
			   Inner JOIN	sPurchase.tSalesReturn SR	ON SR.Id = SRD.SalesReturnId AND SR.IsObsolete = 0
			   Inner JOIN	sIp.tStockItemMaster SIM	ON SIM.Id = SRD.StockItemId 
			   LEFT JOIN [sIp].[tStockItemCategoryMaster] SCM ON SCM.Id = SIM.StockItemCategoryId
			   Inner JOIN  sFinanceCommon.tStockUomMaster SUMa ON SUMa.Id = SIM.IssueStockUomId
		where  SRD.SalesReturnId=@rId

	END TRY

	BEGIN CATCH
    IF @@TRANCOUNT > 0
        ROLLBACK TRAN --RollBack in case of Error
    
    DECLARE @ErrorMessage NVARCHAR(4000);  
    DECLARE @ErrorSeverity INT;  
    DECLARE @ErrorState INT;  
    SELECT   
       @ErrorMessage = ERROR_MESSAGE(),  
       @ErrorSeverity = ERROR_SEVERITY(),  
       @ErrorState = ERROR_STATE();  
    RAISERROR (@ErrorMessage, @ErrorSeverity, @ErrorState);  
    
	END CATCH
END
GO
PRINT N'Altering Procedure [sPurchase].[pSalesReturnSearchGet]...';


GO


ALTER PROCEDURE [sPurchase].[pSalesReturnSearchGet]

	@rNumber nvarchar(30) = '',
	@rLocationId int,
	@rName nvarchar = '',
	@rOrgGroupId int,
	@rStartDate DateTime = null,
	@rEndDate DateTime = null,
    @rPageNo int,
	@rPageSize int,
	@rStatusId smallint = null

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY


		If @rNumber = NULL SET @rNumber=''
		If @rName = NULL SET @rName=''
		If @rStartDate = '' SET @rStartDate=NULL
		If @rEndDate = '' SET @rEndDate=NULL
		If @rStatusId is NULL SET @rStatusId=0

		DECLARE @TotalRecords BIGINT;
		-- Get the total number of records
		SELECT @TotalRecords = COUNT(*) FROM sPurchase.tSalesReturn SR (nolock)
				Left Join [sWf].[tWfStatusMaster] SM on SR.StatusId = SM.Id

        WHERE 
				((SR.SRNumber like @rNumber+'%') OR (@rNumber = ''))
   				AND ((SR.RequestedBy like @rName+'%') OR (@rName = ''))
   				--AND ((SLM.Id = @rStoreLocationId) OR (@rStoreLocationId = 0))
   				AND ((SR.OrgGroupId = @rOrgGroupId) OR (@rOrgGroupId=0))
				AND ((SR.StatusId = @rStatusId) OR (@rStatusId=0))
				AND SR.IsObsolete = 0
				AND ((Cast(SR.CreatedDateTime as Date) >= Cast(@rStartDate as Date)) OR (ISNULL(@rStartDate,'')=''))
				AND((Cast(SR.CreatedDateTime as Date) <= Cast(@rEndDate as Date)) OR (ISNULL(@rEndDate,'')=''))

        Select t.* From (
			Select ROW_NUMBER() Over (
			Order by SR.Id desc  
			) AS 'RowNum',SR.Id,
				SR.SRNumber as Number,
				SR.RequestedBy, 
				SR.LocationId,
				ISNULL(SM.Title,'') as Status

        FROM		
				sPurchase.tSalesReturn SR (nolock)
				Left Join [sWf].[tWfStatusMaster] SM on SR.StatusId = SM.Id

	    WHERE 
				((SR.SRNumber like @rNumber+'%') OR (@rNumber = ''))
   				AND ((SR.RequestedBy like @rName+'%') OR (@rName = ''))
   				--AND ((SLM.Id = @rStoreLocationId) OR (@rStoreLocationId = 0))
   				AND ((SR.OrgGroupId = @rOrgGroupId) OR (@rOrgGroupId=0))
				AND ((SR.StatusId = @rStatusId) OR (@rStatusId=0))
				AND SR.IsObsolete = 0
				AND ((Cast(SR.CreatedDateTime as Date) >= Cast(@rStartDate as Date)) OR (ISNULL(@rStartDate,'')=''))
				AND((Cast(SR.CreatedDateTime as Date) <= Cast(@rEndDate as Date)) OR (ISNULL(@rEndDate,'')=''))
					)t Where t.RowNum Between
		        ((@rPageNo-1)*@rPageSize +1) AND (@rPageNo*@rpageSize)

        SELECT @TotalRecords as TotalRecords
	
	 END TRY

	BEGIN CATCH
    IF @@TRANCOUNT > 0
        ROLLBACK TRAN --RollBack in case of Error
    
    DECLARE @ErrorMessage NVARCHAR(4000);  
    DECLARE @ErrorSeverity INT;  
    DECLARE @ErrorState INT;  
    SELECT   
       @ErrorMessage = ERROR_MESSAGE(),  
       @ErrorSeverity = ERROR_SEVERITY(),  
       @ErrorState = ERROR_STATE();  
    RAISERROR (@ErrorMessage, @ErrorSeverity, @ErrorState);  
    
	END CATCH  		  
END
GO
PRINT N'Altering Procedure [sSecurity].[pAppPermissionGet]...';


GO
ALTER PROCEDURE [sSecurity].[pAppPermissionGet]
	@rOrgGroupId [int],
	@rUserId [bigint]
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
IF EXISTS (SELECT 1 FROM sSecurity.tPermissionUser WHERE UserId=@rUserId AND OrgGroupId=@rOrgGroupId)

	BEGIN
	
		SELECT		
			TP.TaskId AS TaskID,
			CAST(MAX(TP.C) AS BIT) AS [Create],
			CAST(MAX(TP.R) AS BIT) AS [Read],
			CAST(MAX(TP.U) AS BIT) AS [Update],
			CAST(MAX(TP.D) AS BIT) AS [Delete],
			CAST(MAX(TP.S) AS BIT) AS [Search],
			CAST(MAX(TP.P) AS BIT) AS [Print],
			CAST(MAX(TP.X) AS BIT) AS [Execute]
		FROM
		(
			SELECT 	
				P.TaskId					AS	TaskID,
				(Permission & 1) 		AS	C, --[Create],
				(Permission & 2)/2		AS	R, --[Read],
				(Permission & 4)/4		AS	U, --[Update],
				(Permission & 8)/8		AS	D, --[Delete],
				(Permission & 16)/16 	AS	S, --[Search],
				(Permission & 32)/32 	AS	P, --[Print],
				(Permission & 64)/64 	AS	X --[Execute]
			FROM sSecurity.tPermissionUser P
			INNER JOIN sSecurity.tOrganizationTask T ON P.TaskId = T.TaskId And T.OrgGroupId = @rOrgGroupId
			INNER JOIN sSecurity.tTask T1 ON T1.Id=P.TaskId 
			INNER JOIN sSecurity.tModulePermission MP ON MP.ModuleId=T1.ModuleId AND MP.OrgGroupId=@rOrgGroupId
			WHERE
			P.OrgGroupId = @rOrgGroupId 
			AND T1.Id in(
			20075, -- Student Register
			20086, -- Circular
			20094, -- Assignment
			20107, -- Query Queue
			20126, -- Behaviour Entry
			20171, -- Assign Task
			20184, -- Add Photo
			20538, -- Leave Listing
			20561, -- Classwork
			20983, -- My Leave
			30032, -- Subjectwise Attendance
			30502, -- Consolidate - Receipt Details
			30501, -- Consolidate - Fee Status
			30505, -- Consolidate - Student Attendance
			30504, -- Consolidate - Assessment
			30508, -- Consolidate - Task - Attendance
			30507, -- Consolidate - Admission form
			30506, -- Consolidate - Staff
			30536, -- My Expense
			30546, -- Student Alert
			30547, -- Employee Alert
			30550, -- Student Birthdays
			30551, -- Employee Birthdays
			30560, -- Lead Master Admin Permission
			30572, -- Add Lead Permission
			30573, -- Consolidate - Admission Inquiry 
			20089, -- New Query
			30607, -- Consolidate - Task - CW/HW
			30621, -- Consolidate - Fee Collection
			30630, -- Payment Transaction Update
			30621, -- Consolidate - Fee Collection
			20555, -- Lesson Plan
			30635, -- Division Wise -  Photo
			30662, -- Data Search
			30663, -- ClassWork - Home Work Dash Board Search
			30664, -- ClassWork HomeWork Queue
			30678, -- Assignment Queue
			30585, -- Circular Queue
			30687, -- Is Allow SMS Alert
			30688, -- Is Allow Email Alert
			30689, -- Is Allow Notification Alert
			30222, -- Circular Admin
			30540, -- Summarise - Security Dashboard
			30541, -- Summarise - Library Dashboard
			30542, -- Summarise - Transport Dashboard
			30703, -- Summarise - Employee Summary
			30706, -- Summarise - Student Summary
			30766, -- Consolidate Pending Fee
			30768, -- Religionwise Strength Dashboard
			30769, -- Exam Schedule Dashboard 
			20097, -- View Query
			30249, -- Classwork/Homework
			30788, -- Online Learning - Teacher
			30792, -- Online Learning Admin View
			30786, --Online Learning 
			30787, --Online learning Student View
			30815, --Consolidate - Fee Status
			30813, --My Chat - OnlineLearning
			30862,  --Manage Mobile Account
			30900,  -- Close Query
			30927,  -- Classwork Homework Queue Search All
			30930,   -- Consolidate - Admission Inquiry Summary,
			30933,   -- Biometric Punch
			20284,   --Visitor Gate Pass
			30646,   -- Mark Entry From App 
			30944,   -- Circular - Data Search
			30945,   -- Assignment Data Search
			30946,   -- Lesson Data Search
			30947,   -- CW/HW Data Search
			30951,   -- Visitor Log Listing
			30861,   -- Consolidate - Student Subject Attendance
			30505,    -- Consolidate - Student Attendance
			30983,    -- Consolidate - Fee Details Status
			20080,   -- AdmissionInquiry
			30994,   -- AttendanceFollowup
			20556,   -- HostelStudentGatePass
			20934,   -- CS Exam Mark Entry Bulk
			20710,   -- CS Exam Grade Entry Bulk
			20478,   -- CS Exam Indicator Entry Bulk
			20749,   -- Activity Mark Entry Bulk
			20745,   -- Activity Grade Score Bulk
			20746,   -- Activity Indicator Score Bulk
			31007,   -- Is Mark Entry View
			31008,  -- Is CS Entry View
			31009,  -- Is Activity Entry View
			20556,  -- Hostel Student Gate Pass
			31005,	-- My Digital Form
			20183, -- View Photo
			30580, -- Employee Attendance Summary
			20056, -- Event Schedule
			31033, --My Proxy
			20687, --  Employee Attendance
			31043 --  Pending Fee
			,30943 -- My Approval Request
			,30739 -- Behaviour Entry User Wise
			,31048 -- Add Gallery
			,31175 -- View Gallery
			,31179 -- Leave Hierarchy Listing
			,30331 -- My Exam Schedule
			,31182 -- My Admit Card
			,30600 -- MIS Consolidate DashBoard
			,31193 -- Consolidate - Admission Inquiry And Admission Form
			,31194 -- Consolidate - Staff Count
			,31195 -- Consolidate - Charge Receipt
			,31244 -- Lesson Plan Complete
			,20776 -- Front office --Student Gate Pass
			,31305 --Consolidate - Staff Biometric Attendance
			,31314 -- Event Attendance Student Wise
			)
		) TP 
		GROUP BY TP.TaskId
	END
ELSE
	BEGIN
	
		SELECT		
			TP.TaskId AS TaskID,
			CAST(MAX(TP.C) AS BIT) AS [Create],
			CAST(MAX(TP.R) AS BIT) AS [Read],
			CAST(MAX(TP.U) AS BIT) AS [Update],
			CAST(MAX(TP.D) AS BIT) AS [Delete],
			CAST(MAX(TP.S) AS BIT) AS [Search],
			CAST(MAX(TP.P) AS BIT) AS [Print],
			CAST(MAX(TP.X) AS BIT) AS [Execute]
		FROM
		(
			SELECT 	
				P.TaskId					AS	TaskID,
				(Permission & 1) 		AS	C, --[Create],
				(Permission & 2)/2		AS	R, --[Read],
				(Permission & 4)/4		AS	U, --[Update],
				(Permission & 8)/8		AS	D, --[Delete],
				(Permission & 16)/16 	AS	S, --[Search],
				(Permission & 32)/32 	AS	P, --[Print],
				(Permission & 64)/64 	AS	X --[Execute]
			FROM sSecurity.tPermission P
			INNER JOIN sSecurity.tOrganizationTask T ON P.TaskId = T.TaskId And T.OrgGroupId = @rOrgGroupId
			INNER JOIN sSecurity.tTask T1 ON T1.Id=P.TaskId 
			INNER JOIN sSecurity.tModulePermission MP ON MP.ModuleId=T1.ModuleId AND MP.OrgGroupId=@rOrgGroupId
			INNER JOIN (SELECT RoleId FROM sSecurity.tUserRole WHERE IsObsolete = 0 AND UserId = @rUserId) R
			ON R.RoleId = P.RoleId 
			WHERE
			P.OrgGroupId = @rOrgGroupId 
			AND T1.Id in(
			20075, -- Student Register
			20086, -- Circular
			20094, -- Assignment
			20107, -- Query Queue
			20126, -- Behaviour Entry
			20171, -- Assign Task
			20184, -- Add Photo
			20538, -- Leave Listing
			20561, -- Classwork
			20983, -- My Leave
			30032, -- Subjectwise Attendance
			30502, -- Consolidate - Receipt Details
			30501, -- Consolidate - Fee Status
			30505, -- Consolidate - Student Attendance
			30504, -- Consolidate - Assessment
			30508, -- Consolidate - Task - Attendance
			30507, -- Consolidate - Admission form
			30506, -- Consolidate - Staff
			30536, -- My Expense
			30546, -- Student Alert
			30547, -- Employee Alert
			30550, -- Student Birthdays
			30551, -- Employee Birthdays
			30560, -- Lead Master Admin Permission
			30572, -- Add Lead Permission
			30573, -- Consolidate - Admission Inquiry 
			20089, -- New Query
			30607, -- Consolidate - Task - CW/HW
			30621, -- Consolidate - Fee Collection
			30630, -- Payment Transaction Update
			30621, -- Consolidate - Fee Collection
			20555, -- Lesson Plan
			30635, -- Division Wise -  Photo
			30662, -- Data Search
			30663, -- ClassWork - Home Work Dash Board Search
			30664, -- ClassWork HomeWork Queue
			30678, -- Assignment Queue
			30585, -- Circular Queue
			30687, -- Is Allow SMS Alert
			30688, -- Is Allow Email Alert
			30689, -- Is Allow Notification Alert
			30222, -- Circular Admin
			30540, -- Summarise - Security Dashboard
			30541, -- Summarise - Library Dashboard
			30542, -- Summarise - Transport Dashboard
			30703, -- Summarise - Employee Summary
			30706, -- Summarise - Student Summary
			30766, -- Consolidate Pending Fee
			30768, -- Religionwise Strength Dashboard
			30769, -- Exam Schedule Dashboard
			20097, -- View Query
			30249,  -- Classwork/Homework
			30788, -- Online Learning - Teacher
			30792, -- Online Learning Admin View
			30786 , --Online Learning 
			30787,  --Online learning Student View
			30815,  --Consolidate - Fee Status
			30813,  --My Chat - OnlineLearning
			30862,  --Manage Mobile Account
			30900,  -- Close Query
			30927,  -- Classwork Homework Queue Search All
			30930,  -- Consolidate - Admission Inquiry Summary
			30933,   -- Biometric Punch
			20284,   --Visitor Gate Pass
			30646,   -- Mark Entry From App
			30944,   -- Circular - Data Search
			30945,   -- Assignment Data Search
			30946,   -- Lesson Data Search
			30947,   -- CW/HW Data Search
			30951,    -- Visitor Log Listing
			30861,   -- Consolidate - Student Subject Attendance
			30505,    -- Consolidate - Student Attendance			
			30983,    -- Consolidate - Fee Details Status
			20080,   -- AdmissionInquiry
			30994,   -- AttendanceFollowup
			20556,    -- HostelStudentGatePass
			20934,   -- CS Exam Mark Entry Bulk
			20710,   -- CS Exam Grade Entry Bulk
			20478,   -- CS Exam Indicator Entry Bulk
			20749,   -- Activity Mark Entry Bulk
			20745,   -- Activity Grade Score Bulk
			20746,   -- Activity Indicator Score Bulk
			31007,   -- Is Mark Entry View
			31008,  -- Is CS Entry View
			31009,   -- Is Activity Entry View
			20556,   -- Hostel Student Gate Pass
			31005,	-- My Digital Form
			20183, -- View Photo
			30580, -- Employee Attendance Summary
			20056, -- Event Schedule
			31033, --My Proxy
			20687, --  Employee Attendance
			31043 --  Pending Fee
			,30943 -- My Approval Request
			,30739 -- Behaviour Entry User Wise
			,31048 -- Add Gallery
			,31175 -- View Gallery
			,31179 -- Leave Hierarchy Listing
			,30331 -- My Exam Schedule
			,31182 -- My Admit Card
			,30600 -- MIS Consolidate DashBoard
			,31193 -- Consolidate - Admission Inquiry And Admission Form
			,31194 -- Consolidate - Staff Count
			,31195 -- Consolidate - Charge Receipt
			,31244 -- Lesson Plan Complete
			,20776 -- Front office --Student Gate Pass
			,31305 --Consolidate - Staff Biometric Attendance
			,31314 -- Event Attendance Student Wise
			) 
		) TP 
		GROUP BY TP.TaskId
	END
END
GO
PRINT N'Altering Procedure [sSecurity].[pScreenGroupDataListGet]...';


GO
ALTER PROCEDURE [sSecurity].[pScreenGroupDataListGet]

	@rUserId [bigint]

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

DECLARE @lOrgGroupId bigint , @lConfigValue nvarchar(10) = ''

IF EXISTS (SELECT OM.OrgGroupId FROM sSecurity.tUser U INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = U.OrgId WHERE U.Id = @rUserId)
BEGIN
	SELECT @lOrgGroupId = OM.OrgGroupId FROM sSecurity.tUser U INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = U.OrgId WHERE U.Id = @rUserId
		
	SELECT @lConfigValue = ISNULL(CS.ItemValue,'False') FROM sConfig.tConfigurationMaster CM LEFT JOIN sConfig.tConfigurationSetup CS ON CM.Id=CS.Configurationid AND CS.SourceId= @lOrgGroupId AND CS.SourceTypeId=2010 WHERE CM.Id = 327

		IF(@lConfigValue = 'True')
		BEGIN
		     IF EXISTS (SELECT 1 FROM sSecurity.tPermissionUser WHERE UserId=@rUserId AND OrgGroupId=@lOrgGroupId)
				BEGIN
					SELECT S.Id AS Id,LEFT(S.Title,32) AS Title 
					From sSecurity.tScreen S 
					INNER JOIN sSecurity.tPermissionUser P ON P.TaskId=S.TaskId 
					INNER JOIN sSecurity.tTask T ON T.ID = p.TaskId 
					INNER JOIN sSecurity.tOrganizationTask OT ON T.Id = OT.TaskId AND OT.OrgGroupId = P.OrgGroupId 
					INNER JOIN sSecurity.tModulePermission MP ON MP.ModuleId=T.ModuleId AND MP.OrgGroupId=@lOrgGroupId
					WHERE (P.Permission & 2) =2 AND P.OrgGroupId = @lOrgGroupId AND T.IsObsolete = 0 AND P.UserId=@rUserId
					AND T.Id IN (20085,20086,30401,30222,20762,20091,20184,20183,20054,20621,20056,20199,
					30228,20693,20692,20241,20563,20561,30249,20622,143,9072,144,20249,20223,20270,20246,20001,20002,20003,20004,20007,20285,20323,20616,20055,
					139,20175,20176,141,142,20158, 30499,20309,20021,20312,20269,30299,10187,20716,20268,20968,20216,20215,20962,20080,31002,31005,31015,30580,31023,31033,31038,31043,31048,31175,31188,20776)
				END
			ELSE
				BEGIN
					SELECT S.Id AS Id,LEFT(S.Title,32) AS Title 
					From sSecurity.tScreen S 
					INNER JOIN sSecurity.tPermission P ON P.TaskId=S.TaskId 
					INNER JOIN sSecurity.tUserRole U ON U.RoleId=P.RoleId 
					INNER JOIN sSecurity.tTask T ON T.ID = p.TaskId 
					INNER JOIN sSecurity.tOrganizationTask OT ON T.Id = OT.TaskId AND OT.OrgGroupId = P.OrgGroupId 
					WHERE (P.Permission & 2) =2 AND U.IsObsolete=0 AND T.IsObsolete = 0 AND U.UserId=@rUserId
					AND T.Id IN (20085,20086,30401,30222,20762,20091,20184,20183,20054,20621,20056,20199,
					30228,20693,20692,20241,20563,20561,30249,20622,143,9072,144,20249,20223,20270,20246,20001,20002,20003,20004,20007,20285,20323,20616,20055,
					139,20175,20176,141,142,20158, 30499,20309,20021,20312,20269,30299,10187,20716,20268,20968,20216,20215,20962,20080,31002,31005,31015,30580,310235,31033,31038,31043,31048,31175,31179,30331,31182,31188,20776,31314)
				END
		END
		ELSE
		BEGIN
			  IF EXISTS (SELECT 1 FROM sSecurity.tPermissionUser WHERE UserId=@rUserId AND OrgGroupId=@lOrgGroupId)
				BEGIN
					SELECT S.Id AS Id,LEFT(S.Title,32) AS Title 
					From sSecurity.tScreen S 
					INNER JOIN sSecurity.tPermissionUser P ON P.TaskId=S.TaskId 
					INNER JOIN sSecurity.tTask T ON T.ID = p.TaskId 
					INNER JOIN sSecurity.tOrganizationTask OT ON T.Id = OT.TaskId AND OT.OrgGroupId = P.OrgGroupId 
					INNER JOIN sSecurity.tModulePermission MP ON MP.ModuleId=T.ModuleId AND MP.OrgGroupId=@lOrgGroupId
					WHERE (P.Permission & 2) =2 AND P.OrgGroupId = @lOrgGroupId AND T.IsObsolete = 0 AND P.UserId=@rUserId
				END
			  ELSE
				BEGIN
					SELECT S.Id AS Id,LEFT(S.Title,32) AS Title 
					From sSecurity.tScreen S 
					INNER JOIN sSecurity.tPermission P ON P.TaskId=S.TaskId 
					INNER JOIN sSecurity.tUserRole U ON U.RoleId=P.RoleId 
					INNER JOIN sSecurity.tTask T ON T.ID = p.TaskId 
					INNER JOIN sSecurity.tOrganizationTask OT ON T.Id = OT.TaskId AND OT.OrgGroupId = P.OrgGroupId 
					WHERE (P.Permission & 2) =2 AND U.IsObsolete=0 AND T.IsObsolete = 0 AND U.UserId=@rUserId
				END
		END
END

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


GO
ALTER PROCEDURE [sSecurity].[pVerifyEmailIdForOTP]

	@rOrgId int = 0,
	@rBatchId int =0,
	@rEmailId nvarchar(50), 
	@rAcademicId bigint 

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	DECLARE @lCount int = 0 
	DECLARE @lUserId bigint =0
	DECLARE @newpwd VARCHAR(100) 

	SELECT @lCount = COUNT(SC.StudentId) 
	FROM  sStudent.tStudentCommunication SC
	INNER JOIN sStudent.tAcademic A ON A.StudentId = SC.StudentId
	INNER JOIN sSecurity.tUser U ON U.SourceId = SC.StudentId AND U.SourceTypeId=2003
	WHERE SC.ParentEmail = @rEmailId  AND A.BatchId = @rBatchId AND A.OrgId=@rOrgId  AND A.Id = @rAcademicId
	GROUP BY SC.StudentId

	IF(@lCount > 0)
	BEGIN
	
		SELECT SC.StudentId  INTO #UserId FROM  sStudent.tStudentCommunication SC
		INNER JOIN sStudent.tAcademic A ON A.StudentId = SC.StudentId
		INNER JOIN sSecurity.tUser U ON U.SourceId = SC.StudentId AND U.SourceTypeId=2003
		WHERE SC.ParentEmail = @rEmailId AND A.BatchId = @rBatchId AND A.OrgId=@rOrgId AND A.Id = @rAcademicId
		
		SELECT @lUserId = StudentId FROM #UserId
		EXEC [sSecurity].[pNumericOTPGenerate] @len=6, @min=48, @range=9, @exclude='', @output=@newpwd OUT
		UPDATE sSecurity.tUser 
		SET	TempPasswordCode=@newpwd,CreatedDateTime=sCommon.fGetDate(),OTPExpiryDate=DATEADD(SECOND,120,GETDATE())				
		WHERE SourceId = @lUserId AND OrgId = @rOrgId AND SourceTypeId = 2003
		
		SELECT 1 AS Result,'' AS [Message],TempPasswordCode AS OTP,Id AS UserId FROM sSecurity.tUser 
		WHERE SourceId = @lUserId AND OrgId = @rOrgId	

		DROP Table #UserId
	END

	ELSE
	BEGIN 
		SELECT -102 AS Result,'Email Id is wrong' AS [Message],'' AS OTP, 0 AS UserId
	END
END
GO
PRINT N'Altering Procedure [sSetup].[pOrgGroupMasterAdd]...';


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

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

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

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



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

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

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

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


			
			
END
	   

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


			
			

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


GO
ALTER PROCEDURE [sStudent].[pDigitalFormStudentListGet]
	 @rSourceId bigint,
	 @rSourceTypeId int,
	 @rOrgGroupBatchId int,
	 @rOrgId int 
		 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	IF (@rSourceTypeId = 2001)
	BEGIN 
	 
	 DECLARE @lAcademicId bigint,@lStudentId bigint,@lClassId int,@lDivisionId int,@lOrgId int,@lDepartmentId int,@lEmployeeId bigint,
	 @lClassName nvarchar(100)


	 SELECT @lAcademicId = A.Id,@lStudentId = A.StudentId,@lClassId = A.ClassId, @lDivisionId = A.DivisionId, @lOrgId= A.OrgId, @lDepartmentId=CM.DepartmentId,
	 @lClassName=CM.Title,@lCLassId=CM.Id
     FROM sStudent.tAcademic A INNER JOIN sSetup.tBatchMaster BM
	 ON A.BatchId = BM.Id 
	 INNER JOIN sSetup.tClassMaster CM ON CM.Id = A.ClassId
     WHERE A.Id = @rSourceId AND BM.OrgGroupBatchId = @rOrgGroupBatchId

     SELECT 
			 DF.Id,
			 DF.Code,
			 DF.Title,
			 DF.IsObsolete,
			 CONVERT(nvarchar,DF.CreatedDateTime,103) as CreatedDateTime, 
			 CASE WHEN U.SourceTypeId = 95 THEN (SELECT ShortName FROM sHrm.tEmployeeMaster WHERE Id = U.SourceId )
			 WHEN U.SourceTypeId = 2003 THEN (SELECT FirstName+''+LastName as Name FROM sStudent.tAcademic A INNER JOIN sStudent.tStudentMaster SM ON A.StudentId = SM.Id WHERE A.Id = U.SourceId ) ELSE 'Admin' END As CreatedBy,
			 0 as Submitted,
			 0 as NotSubmitted,
			 ISNULL(DFSS.StatusId, 0) AS DigitalFormStatusId,
			 ISNULL(SM.Title, '') AS DigitalFormStatus,
			 ISNULL(DFSS.VerifyDateTime, '') AS FormActionDateTime
     FROM 
		    sStudent.tDigitalForm DF
			INNER JOIN sSecurity.tUser U ON DF.CreatedUserId = U.Id
			INNER JOIN (SELECT DFS.DigitalFormId FROM sStudent.tDigitalFormScope DFS
			WHERE (
			( 
			(DFS.SourceTypeId = 2021 AND DFS.SourceId =@lOrgId) 
			OR
			(DFS.SourceTypeId = 2017 AND DFS.SourceId =@lDepartmentId) OR
			(DFS.SourceTypeId = 2016 AND DFS.SourceId =@lClassId) OR
			(DFS.SourceTypeId = 2005 AND DFS.SourceId =@lDivisionId) OR
			(DFS.SourceTypeId = 2003 AND DFS.SourceId =@lStudentId) OR
			(DFS.SourceTypeId = 2001 AND DFS.SourceId =@lAcademicId)
				))
			) D
			ON D.DigitalFormId= DF.Id
			LEFT JOIN [sStudent].[tDigitalFormStudentStatus] DFSS ON DFSS.DigitalFormId = DF.Id AND DFSS.AcademicId = @lAcademicId
			LEFT JOIN sCommon.tStatusMaster SM ON SM.Id = DFSS.StatusId
	 WHERE
			DF.IsObsolete = 0

		END
	ELSE IF(@rSourceTypeId = 95)
	BEGIN
	SELECT
		DF.Id,
		DF.Code,
		DF.Title,
		DF.IsObsolete,
		CONVERT(nvarchar,DF.CreatedDateTime,103) as CreatedDateTime, 
		CASE WHEN U.SourceTypeId = 95 THEN (SELECT ShortName FROM sHrm.tEmployeeMaster WHERE Id = U.SourceId )
		WHEN U.SourceTypeId = 2003 THEN (SELECT FirstName+''+LastName as Name FROM sStudent.tAcademic A INNER JOIN sStudent.tStudentMaster SM ON A.StudentId = SM.Id WHERE A.Id = U.SourceId ) ELSE 'Admin' END As CreatedBy,
		--(SELECT COUNT(Distinct(AcademicId)) FROM sStudent.tDigitalFormStudent WHERE DigitalFormId = DF.Id) as Submitted,
		--(ISNULL(B.Total,0) - (SELECT COUNT(Distinct(AcademicId)) FROM sStudent.tDigitalFormStudent WHERE DigitalFormId = DF.Id)) as NotSubmitted
		(SELECT SUM(s.Count1) from (SELECT COUNT(Distinct(DFS.AcademicId)) AS Count1
		FROM sStudent.tDigitalFormStudent DFS INNER JOIN  sStudent.vStudentAllDetail A ON A.AcademicId = DFS.AcademicId
		WHERE DigitalFormId = DF.Id AND OrgGroupBatchId = @rOrgGroupBatchId GROUP BY  DFS.AcademicId)AS S) AS Submitted,
		(ISNULL(B.Total,0) - ((SELECT SUM(s.Count1) from (SELECT COUNT(Distinct(DFS.AcademicId)) AS Count1
		FROM sStudent.tDigitalFormStudent DFS INNER JOIN  sStudent.vStudentAllDetail A ON A.AcademicId = DFS.AcademicId
		WHERE DigitalFormId = DF.Id AND OrgGroupBatchId = @rOrgGroupBatchId GROUP BY  DFS.AcademicId)AS S))) as NotSubmitted
	FROM 
		sStudent.tDigitalForm DF
		INNER JOIN sSecurity.tUser U ON DF.CreatedUserId = U.Id
		LEFT JOIN 
		(
			SELECT
			ISNULL(COUNT(A.Code),0) as Total,
			DigitalFormId
			FROM
			(
				SELECT 
				   SD.Code,
				   DFS.DigitalFormId
				FROM 
					sStudent.tDigitalFormScope DFS  
					INNER JOIN sStudent.vStudentAllDetail SD ON SD.StudentId = DFS.SourceId AND SD.OrgGroupBatchId = @rOrgGroupBatchId 
				WHERE 
					SD.StatusId = 1 AND DFS.SourceTypeId = 2003
				UNION ALL	
																			 			  
				SELECT 
					SD.Code,
					DFS.DigitalFormId
				FROM 
					sStudent.tDigitalFormScope DFS 
					INNER JOIN sStudent.vStudentAllDetail SD ON SD.DepartmentId = DFS.SourceId AND SD.OrgGroupBatchId = @rOrgGroupBatchId
				WHERE 
					SD.StatusId = 1 AND  DFS.SourceTypeId = 2017

				UNION ALL		
															 			 				  
				SELECT 
					SD.Code,
					DFS.DigitalFormId 
				FROM 
					sStudent.tDigitalFormScope DFS  
					INNER JOIN sStudent.vStudentAllDetail SD ON SD.ClassId = DFS.SourceId AND SD.OrgGroupBatchId = @rOrgGroupBatchId 
				WHERE 
					SD.StatusId = 1 AND DFS.SourceTypeId = 2016

				UNION ALL	
																 			 				  
				SELECT 
					SD.Code,
					DFS.DigitalFormId
				FROM 
					sStudent.tDigitalFormScope DFS 
					INNER JOIN sStudent.vStudentAllDetail SD ON SD.DivisionId = DFS.SourceId AND SD.OrgGroupBatchId = @rOrgGroupBatchId 
				WHERE 
					SD.StatusId = 1 AND DFS.SourceTypeId = 2005

				UNION ALL		
															 			 				  
				SELECT 
					SD.Code,
					DFS.DigitalFormId
				FROM 
					sStudent.tDigitalFormScope DFS  
					INNER JOIN sStudent.vStudentAllDetail SD ON SD.OrgId = DFS.SourceId AND SD.OrgGroupBatchId = @rOrgGroupBatchId 
				WHERE 
					SD.StatusId = 1 AND DFS.SourceTypeId = 2021
			)A
			GROUP BY DigitalFormId
		)  B ON B.DigitalFormId = DF.Id
	 
	END 
END
GO
PRINT N'Altering Procedure [sStudent].[pDigitalFormSubmittedStudentListGet]...';


GO
ALTER PROCEDURE [sStudent].[pDigitalFormSubmittedStudentListGet]
	  
	 @rOrgGroupBatchId int,
	 @rDigitalFormId int,
	 @rPageIndex int
		 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	DECLARE @lPageSize int = 20	

	IF OBJECT_ID('tempdb..#tDigitalFormTable') IS NOT NULL DROP TABLE #tDigitalFormTable
	CREATE TABLE #tDigitalFormTable  
	(
		Id bigint identity,	
		SourceId Bigint,
		Code nvarchar(20),
		ClassDivision nvarchar(200),
		StudentName nvarchar(300),
		IsSubmitted bit, 
		SubmittedDate nvarchar(100),
		DivisionOrder smallint
	)

	Insert into #tDigitalFormTable
	SELECT
		DISTINCT A.AcademicId as SourceId, 
		A.Code as Code,
		A.ClassName+'-'+A.DivisionName as ClassDivision,
		A.Name as StudentName,
		convert(bit,(SELECT CASE WHEN DFS.AcademicId IS NOT NULL THEN 1 ELSE 0 END as IsSubmitted)) as IsSubmitted,
		ISNULL(CONVERT(NVARCHAR,DFS.CreatedDateTime,103),'') as SubmittedDate,
		A.DivisionOrder
	FROM
		sStudent.tDigitalForm DF		
		INNER JOIN (SELECT 
					   SD.Code,
					   DFS.DigitalFormId,
					   SD.AcademicId,
					   SD.ClassName,
					   SD.DivisionName,
					   SD.Name,
					   SD.DivisionOrder
					FROM 
						sStudent.tDigitalFormScope DFS  
						INNER JOIN sStudent.vStudentAllDetail SD ON SD.StudentId = DFS.SourceId AND SD.OrgGroupBatchId = @rOrgGroupBatchId 
					WHERE 
						SD.StatusId = 1 AND DFS.SourceTypeId = 2003
					UNION ALL	
																			 			  
					SELECT 
						SD.Code,
						DFS.DigitalFormId,
						SD.AcademicId,
						SD.ClassName,
						SD.DivisionName,
						SD.Name,
						SD.DivisionOrder
					FROM 
						sStudent.tDigitalFormScope DFS 
						INNER JOIN sStudent.vStudentAllDetail SD ON SD.DepartmentId = DFS.SourceId AND SD.OrgGroupBatchId = @rOrgGroupBatchId
					WHERE 
						SD.StatusId = 1 AND  DFS.SourceTypeId = 2017

					UNION ALL		
															 			 				  
					SELECT 
						SD.Code,
						DFS.DigitalFormId,
						SD.AcademicId,
						SD.ClassName,
						SD.DivisionName,
						SD.Name,
						SD.DivisionOrder
					FROM 
						sStudent.tDigitalFormScope DFS  
						INNER JOIN sStudent.vStudentAllDetail SD ON SD.ClassId = DFS.SourceId AND SD.OrgGroupBatchId = @rOrgGroupBatchId 
					WHERE 
						SD.StatusId = 1 AND DFS.SourceTypeId = 2016

					UNION ALL	
																 			 				  
					SELECT 
						SD.Code,
						DFS.DigitalFormId,
						SD.AcademicId,
						SD.ClassName,
						SD.DivisionName,
						SD.Name,
						SD.DivisionOrder
					FROM 
						sStudent.tDigitalFormScope DFS 
						INNER JOIN sStudent.vStudentAllDetail SD ON SD.DivisionId = DFS.SourceId AND SD.OrgGroupBatchId = @rOrgGroupBatchId 
					WHERE 
						SD.StatusId = 1 AND DFS.SourceTypeId = 2005

					UNION ALL		
															 			 				  
					SELECT 
						SD.Code,
						DFS.DigitalFormId,
						SD.AcademicId,
						SD.ClassName,
						SD.DivisionName,
						SD.Name,
						SD.DivisionOrder
					FROM 
						sStudent.tDigitalFormScope DFS  
						INNER JOIN sStudent.vStudentAllDetail SD ON SD.OrgId = DFS.SourceId AND SD.OrgGroupBatchId = @rOrgGroupBatchId 
					WHERE 
						SD.StatusId = 1 AND DFS.SourceTypeId = 2021)A ON DF.Id = A.DigitalFormId 
				LEFT JOIN sStudent.tDigitalFormStudent DFS ON DFS.DigitalFormId = DF.Id AND DFS.AcademicId = A.AcademicId
		WHERE
			DF.Id = @rDigitalFormId  
		ORDER BY
		IsSubmitted desc,
		A.DivisionOrder Asc

	Declare @lCount int = (Select Count(Id) from #tDigitalFormTable)
	
	select Id, SourceId, Code, ClassDivision , StudentName, IsSubmitted, SubmittedDate, DivisionOrder,@lCount As TotalRecords
	from #tDigitalFormTable 
	where Id between ((@lPageSize * (@rPageindex-1)) + 1) and (@lPageSize * @rPageindex)

	drop table #tDigitalFormTable
END
GO
PRINT N'Altering Procedure [sStudent].[pMISStudentSummaryDashboardGet]...';


GO
ALTER PROCEDURE [sStudent].[pMISStudentSummaryDashboardGet]
 
 
@rCommonOrgGroupBatchId int = 0,
@rOrgGroupId int = 0,
@rOrgId int = 0,
@rOrgSubGroupId int = 0,
@rDepartmentId int = 0,
@rTypeId int = 0,
@rFilter nvarchar(50)=''


WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON			 
BEGIN 
	IF(@rTypeId = 1)-------------LEVEL 1
	BEGIN
	IF(@rFilter = 'Statuswise')--Statuswise (Total/Active)
		BEGIN
			SELECT 
				OSGM.Id As OrgSubGroupId		
				,OSGM.Title As OrgSubGroupName,
				COUNT(SA.AcademicId) AS Total,
				COUNT(ASA.ActiveStudent) AS Active
			FROM 
				sSetup.tOrgSubGroupMaster OSGM
				INNER JOIN sSetup.tOrgGroupMaster OGM ON OGM.Id = OSGM.OrgGroupId
				LEFT JOIN sSetup.tOrganizationMaster OM ON OM.OrgSubGroupId = OSGM.Id
				INNER JOIN sStudent.vStudentAcademic SA ON  SA.OrgId = OM.Id
				LEFT JOIN (SELECT SA1.AcademicId As ActiveStudent FROM sStudent.vStudentAcademic SA1
				WHERE SA1.StatusId = 1 Group By SA1.AcademicId) ASA ON ASA.ActiveStudent = SA.AcademicId
				INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId 
				INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BM.OrgGroupBatchId
				INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
			WHERE  
				   COGBM.Id=@rCommonOrgGroupBatchId AND ISNULL(OGM.IsObsolete,0) = 0
				   AND OGM.Id = @rOrgGroupId
 			GROUP BY 
				OSGM.Id,OSGM.Title
		END
	ELSE IF(@rFilter = 'Genderwise') ------- Genderwise
		BEGIN
			SELECT 
				OSGM.Id As OrgSubGroupId		
				,OSGM.Title As OrgSubGroupName,
				ISNULL(COUNT(MSA.ActiveStudent),0) AS Male,
				ISNULL(COUNT(FSA.ActiveStudent),0) AS Female
			FROM 
				sSetup.tOrgSubGroupMaster OSGM
				LEFT JOIN sSetup.tOrgGroupMaster OGMR ON OGMR.Id = OSGM.OrgGroupId
				LEFT JOIN sSetup.tOrganizationMaster OM ON OM.OrgSubGroupId = OSGM.Id
				LEFT JOIN sStudent.vStudentAcademic SA ON  SA.OrgId = OM.Id
				LEFT JOIN (SELECT SA1.AcademicId As ActiveStudent FROM sStudent.vStudentAcademic SA1
				INNER JOIN sStudent.tStudentOther SO ON SO.StudentId = SA1.StudentId
				WHERE SA1.StatusId = 1 AND SO.GenderId = 1  Group By SA1.AcademicId) MSA ON MSA.ActiveStudent = SA.AcademicId
				LEFT JOIN (SELECT SA1.AcademicId As ActiveStudent FROM sStudent.vStudentAcademic SA1
				INNER JOIN sStudent.tStudentOther SO ON SO.StudentId = SA1.StudentId
				WHERE SA1.StatusId = 1 AND SO.GenderId = 2  Group By SA1.AcademicId) FSA ON FSA.ActiveStudent = SA.AcademicId
				LEFT JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId 
				LEFT JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BM.OrgGroupBatchId
				LEFT JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
			WHERE   
				COGBM.Id=@rCommonOrgGroupBatchId  AND SA.StatusId = 1 AND ISNULL(OGMR.IsObsolete,0) = 0
				   AND OGMR.Id = @rOrgGroupId
 			GROUP BY 
				OSGM.Id,OSGM.Title
			Order By 
				OrgSubGroupName
		END
	ELSE IF(@rFilter = 'CastCategorywise') ----------- CastCategory
		BEGIN
			SELECT 
				OSGM.Id As OrgSubGroupId		
				,OSGM.Title As OrgSubGroupName,
				ISNULL(CCM.Title,'NA') AS CastCategory,
				COUNT(SA.AcademicId) As Total
			FROM 
				sSetup.tOrgSubGroupMaster OSGM
				LEFT JOIN sSetup.tOrgGroupMaster OGMR ON OGMR.Id = OSGM.OrgGroupId
				LEFT JOIN sSetup.tOrganizationMaster OM ON OM.OrgSubGroupId = OSGM.Id
				LEFT JOIN sStudent.vStudentAcademic SA ON SA.OrgId = OM.Id
				INNER JOIN sStudent.tStudentOther SO ON SO.StudentId = SA.StudentId
				LEFT JOIN sCommon.tCastCategoryMaster CCM ON CCM.Id = SO.CastCategoryId
				LEFT JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId 
				LEFT JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BM.OrgGroupBatchId
				LEFT JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
			WHERE  
				COGBM.Id=@rCommonOrgGroupBatchId AND SA.StatusId = 1 AND ISNULL(OGMR.IsObsolete,0) = 0
				AND OGMR.Id = @rOrgGroupId
 			GROUP BY 
				OSGM.Id,OSGM.Title,CCM.Title
			Order By OrgSubGroupName
		END
	ELSE IF(@rFilter = 'Religionwise') ----------- Religion
		BEGIN
			SELECT 
				OSGM.Id As OrgSubGroupId		
				,OSGM.Title As OrgSubGroupName,
				ISNULL(RM.Title,'NA') AS Religion,
				COUNT(SA.AcademicId) As Total
			FROM 
				sSetup.tOrgSubGroupMaster OSGM
				LEFT JOIN sSetup.tOrgGroupMaster OGMR ON OGMR.Id = OSGM.OrgGroupId
				LEFT JOIN sSetup.tOrganizationMaster OM ON OM.OrgSubGroupId = OSGM.Id
				LEFT JOIN sStudent.vStudentAcademic SA ON SA.OrgId = OM.Id
				INNER JOIN sStudent.tStudentOther SO ON SO.StudentId = SA.StudentId
				LEFT JOIN sCommon.tReligionMaster RM ON RM.Id = SO.ReligionId
				LEFT JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId 
				LEFT JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BM.OrgGroupBatchId
				LEFT JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
			WHERE  
				COGBM.Id=@rCommonOrgGroupBatchId AND SA.StatusId = 1 AND ISNULL(OGMR.IsObsolete,0) = 0
				AND OGMR.Id = @rOrgGroupId
 			GROUP BY 
				OSGM.Id,OSGM.Title,RM.Title
			Order By OrgSubGroupName
		END
	ELSE IF(@rFilter = 'Housewise') ------------ House
		BEGIN
			SELECT 
				OSGM.Id As OrgSubGroupId		
				,OSGM.Title As OrgSubGroupName,
				ISNULL(HM.Title,'NA') AS House,
				COUNT(SA.AcademicId) As Total
			FROM 
				sSetup.tOrgSubGroupMaster OSGM
				LEFT JOIN sSetup.tOrgGroupMaster OGMR ON OGMR.Id = OSGM.OrgGroupId
				LEFT JOIN sSetup.tOrganizationMaster OM ON OM.OrgSubGroupId = OSGM.Id
				LEFT JOIN sStudent.vStudentAcademic SA ON SA.OrgId = OM.Id
				INNER JOIN sStudent.tStudentOther SO ON SO.StudentId = SA.StudentId
				LEFT JOIN sActivity.tHouseMaster HM ON HM.Id = SO.HouseId
				LEFT JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId 
				LEFT JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BM.OrgGroupBatchId
				LEFT JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
			WHERE  
				COGBM.Id=@rCommonOrgGroupBatchId AND SA.StatusId = 1 AND ISNULL(OGMR.IsObsolete,0) = 0
				AND OGMR.Id = @rOrgGroupId
 			GROUP BY 
				OSGM.Id,OSGM.Title,HM.Title
			Order By OSGM.Id
		END
	END
	ELSE IF(@rTypeId = 2)----------LEVEL 2
	BEGIN
		IF(@rFilter = 'Statuswise')--Statuswise (Total/Active)
			BEGIN
				SELECT 
					OM.Id As OrgId,
					OM.Title As Organization,
					COUNT(SA.AcademicId) AS Total,
					COUNT(ASA.ActiveStudent) AS Active
				FROM 
					sSetup.tOrganizationMaster OM
					LEFT JOIN sStudent.vStudentAcademic SA ON SA.OrgId = OM.Id
					LEFT JOIN (SELECT SA1.AcademicId As ActiveStudent FROM sStudent.vStudentAcademic SA1
					WHERE SA1.StatusId = 1 Group By SA1.AcademicId) ASA ON ASA.ActiveStudent = SA.AcademicId
					INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId
					LEFT JOIN sSetup.tOrgGroupMaster OGMR ON OGMR.Id=OM.OrgGroupId 
					INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BM.OrgGroupBatchId
					INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
				WHERE  
					   COGBM.Id=@rCommonOrgGroupBatchId AND ISNULL(OGMR.IsObsolete,0) = 0
					   AND ((OM.OrgSubGroupId = @rOrgSubGroupId) OR (@rOrgSubGroupId = 0))
 				GROUP BY 
					OM.Id,OM.Title
			END
		ELSE IF(@rFilter = 'Genderwise') ------- Genderwise
			BEGIN
				SELECT 
					OM.Id As OrgId,
					OM.Title As Organization,
					ISNULL(COUNT(MSA.ActiveStudent),0) AS Male,
					ISNULL(COUNT(FSA.ActiveStudent),0) AS Female
				FROM 
					sSetup.tOrganizationMaster OM
					LEFT JOIN sStudent.vStudentAcademic SA ON SA.OrgId = OM.Id
					LEFT JOIN (SELECT SA1.AcademicId As ActiveStudent FROM sStudent.vStudentAcademic SA1
					INNER JOIN sStudent.tStudentOther SO ON SO.StudentId = SA1.StudentId
					WHERE SA1.StatusId = 1 AND SO.GenderId = 1  Group By SA1.AcademicId) MSA ON MSA.ActiveStudent = SA.AcademicId
					LEFT JOIN (SELECT SA1.AcademicId As ActiveStudent FROM sStudent.vStudentAcademic SA1
					INNER JOIN sStudent.tStudentOther SO ON SO.StudentId = SA1.StudentId
					WHERE SA1.StatusId = 1 AND SO.GenderId = 2  Group By SA1.AcademicId) FSA ON FSA.ActiveStudent = SA.AcademicId
					LEFT JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId 
					LEFT JOIN sSetup.tOrgGroupMaster OGMR ON OGMR.Id=OM.OrgGroupId 
					LEFT JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BM.OrgGroupBatchId
					LEFT JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
				WHERE   
					COGBM.Id=@rCommonOrgGroupBatchId  AND SA.StatusId = 1 AND ISNULL(OGMR.IsObsolete,0) = 0
					  AND ((OM.OrgSubGroupId = @rOrgSubGroupId) OR (@rOrgSubGroupId = 0))
 				GROUP BY 
					OM.Id,OM.Title
				Order By 
					Organization
			END
		ELSE IF(@rFilter = 'CastCategorywise') ----------- CastCategory
			BEGIN
				SELECT 
					OM.Id As OrgId,
					OM.Title As Organization,
					ISNULL(CCM.Title,'NA') AS CastCategory,
					COUNT(SA.AcademicId) As Total
				FROM 
					sSetup.tOrganizationMaster OM
					LEFT JOIN sStudent.vStudentAcademic SA ON SA.OrgId = OM.Id
					INNER JOIN sStudent.tStudentOther SO ON SO.StudentId = SA.StudentId
					LEFT JOIN sCommon.tCastCategoryMaster CCM ON CCM.Id = SO.CastCategoryId
					LEFT JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId 
					LEFT JOIN sSetup.tOrgGroupMaster OGMR ON OGMR.Id=OM.OrgGroupId 
					LEFT JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BM.OrgGroupBatchId
					LEFT JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
				WHERE  
					COGBM.Id=@rCommonOrgGroupBatchId AND SA.StatusId = 1 AND ISNULL(OGMR.IsObsolete,0) = 0
					AND ((OM.OrgSubGroupId = @rOrgSubGroupId) OR (@rOrgSubGroupId = 0))
 				GROUP BY 
					OM.Id,OM.Title,CCM.Title
				Order By Organization
			END
		ELSE IF(@rFilter = 'Religionwise') ----------- Religion
			BEGIN
				SELECT 
					OM.Id As OrgId,
					OM.Title As Organization,
					ISNULL(RM.Title,'NA') AS Religion,
					COUNT(SA.AcademicId) As Total
				FROM 
					sSetup.tOrganizationMaster OM
					LEFT JOIN sStudent.vStudentAcademic SA ON SA.OrgId = OM.Id
					INNER JOIN sStudent.tStudentOther SO ON SO.StudentId = SA.StudentId
					LEFT JOIN sCommon.tReligionMaster RM ON RM.Id = SO.ReligionId
					LEFT JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId 
					LEFT JOIN sSetup.tOrgGroupMaster OGMR ON OGMR.Id=OM.OrgGroupId 
					LEFT JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BM.OrgGroupBatchId
					LEFT JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
				WHERE  
					COGBM.Id=@rCommonOrgGroupBatchId AND SA.StatusId = 1 AND ISNULL(OGMR.IsObsolete,0) = 0
					AND ((OM.OrgSubGroupId = @rOrgSubGroupId) OR (@rOrgSubGroupId = 0))
 				GROUP BY 
					OM.Id,OM.Title,RM.Title
				Order By Organization
			END
		ELSE IF(@rFilter = 'Housewise') ------------ House
			BEGIN
				SELECT 
					OM.Id As OrgId,
					OM.Title As Organization,
					ISNULL(HM.Title,'NA') AS House,
					COUNT(SA.AcademicId) As Total
				FROM 
					sSetup.tOrganizationMaster OM
					LEFT JOIN sStudent.vStudentAcademic SA ON SA.OrgId = OM.Id
					INNER JOIN sStudent.tStudentOther SO ON SO.StudentId = SA.StudentId
					LEFT JOIN sActivity.tHouseMaster HM ON HM.Id = SO.HouseId
					LEFT JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId 
					LEFT JOIN sSetup.tOrgGroupMaster OGMR ON OGMR.Id=OM.OrgGroupId 
					LEFT JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BM.OrgGroupBatchId
					LEFT JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
				WHERE  
					COGBM.Id=@rCommonOrgGroupBatchId AND SA.StatusId = 1 AND ISNULL(OGMR.IsObsolete,0) = 0
					AND ((OM.OrgSubGroupId = @rOrgSubGroupId) OR (@rOrgSubGroupId = 0))
 				GROUP BY 
					OM.Id,OM.Title,HM.Title
				Order By Organization
			END
	END
	ELSE IF(@rTypeId = 3)----------LEVEL 3
	BEGIN
		IF(@rFilter = 'Statuswise')
		BEGIN
		SELECT 
			DM.Id As DepartmentId,
			DM.Title As Department,
			ISNULL(COUNT(SA.AcademicId),0) AS Total,
			ISNULL(COUNT(ASA.ActiveStudent),0) AS Active
		FROM 
			sSetup.tDepartmentMaster DM
			LEFT JOIN sStudent.vStudentAcademic SA ON SA.DepartmentId = DM.Id
			LEFT JOIN (SELECT SA1.AcademicId As ActiveStudent FROM sStudent.vStudentAcademic SA1
			WHERE SA1.StatusId = 1 Group By SA1.AcademicId) ASA ON ASA.ActiveStudent = SA.AcademicId
			LEFT JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId 
			LEFT JOIN sSetup.tOrganizationMaster OM ON OM.Id = BM.OrgId
			LEFT JOIN sSetup.tOrgGroupMaster OGMR ON OGMR.Id=OM.OrgGroupId
			LEFT JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BM.OrgGroupBatchId
			LEFT JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
		WHERE  
			COGBM.Id=@rCommonOrgGroupBatchId
			AND ((DM.OrgId = @rOrgId) OR (@rOrgId = 0))
 		GROUP BY 
			DM.Title,DM.Id
		Order By DM.Id
		END
		ELSE IF(@rFilter = 'Genderwise') --------------Department/Gender
		BEGIN
			SELECT 
				DM.Id As DepartmentId,
				DM.Title As Department,
				ISNULL(COUNT(MSA.ActiveStudent),0) AS Male,
				ISNULL(COUNT(FSA.ActiveStudent),0) AS Female
			FROM 
				sSetup.tDepartmentMaster DM
				LEFT JOIN sStudent.vStudentAcademic SA ON SA.DepartmentId = DM.Id
				LEFT JOIN (SELECT SA1.AcademicId As ActiveStudent FROM sStudent.vStudentAcademic SA1
				INNER JOIN sStudent.tStudentOther SO ON SO.StudentId = SA1.StudentId
				WHERE SA1.StatusId = 1 AND SO.GenderId = 1  Group By SA1.AcademicId) MSA ON MSA.ActiveStudent = SA.AcademicId
				LEFT JOIN (SELECT SA1.AcademicId As ActiveStudent FROM sStudent.vStudentAcademic SA1
				INNER JOIN sStudent.tStudentOther SO ON SO.StudentId = SA1.StudentId
				WHERE SA1.StatusId = 1 AND SO.GenderId = 2  Group By SA1.AcademicId) FSA ON FSA.ActiveStudent = SA.AcademicId
				LEFT JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId 
				LEFT JOIN sSetup.tOrganizationMaster OM ON OM.Id = BM.OrgId
				LEFT JOIN sSetup.tOrgGroupMaster OGMR ON OGMR.Id=OM.OrgGroupId
				LEFT JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BM.OrgGroupBatchId
				LEFT JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
			WHERE  
				COGBM.Id=@rCommonOrgGroupBatchId AND SA.StatusId = 1
				AND ((DM.OrgId = @rOrgId) OR (@rOrgId = 0))
 			GROUP BY 
				DM.Title,DM.Id
			Order By 
				DM.Id
    	END
		ELSE IF(@rFilter = 'CastCategorywise') --------------Department/CastCategory
		BEGIN
			SELECT 
				DM.Id As DepartmentId,
				DM.Title As Department,
				ISNULL(CCM.Title,'NA') AS CastCategory,
				COUNT(SA.AcademicId) As Total
			FROM 
				sSetup.tDepartmentMaster DM
				LEFT JOIN sStudent.vStudentAcademic SA ON SA.DepartmentId = DM.Id
				INNER JOIN sStudent.tStudentOther SO ON SO.StudentId = SA.StudentId
				LEFT JOIN sCommon.tCastCategoryMaster CCM ON CCM.Id = SO.CastCategoryId
				LEFT JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId 
				LEFT JOIN sSetup.tOrganizationMaster OM ON OM.Id = BM.OrgId
				LEFT JOIN sSetup.tOrgGroupMaster OGMR ON OGMR.Id=OM.OrgGroupId
				LEFT JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BM.OrgGroupBatchId
				LEFT JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
			WHERE  
				COGBM.Id=@rCommonOrgGroupBatchId AND SA.StatusId = 1
				AND ((DM.OrgId = @rOrgId) OR (@rOrgId = 0))
 			GROUP BY 
				DM.Title,DM.Id,CCM.Title
			Order By DM.Id
		END
		ELSE IF(@rFilter = 'Religionwise') --------------Department/Religion
		BEGIN
			SELECT 
				DM.Id As DepartmentId,
				DM.Title As Department,
				ISNULL(RM.Title,'NA') AS Religion,
				COUNT(SA.AcademicId) As Total
			FROM 
				sSetup.tDepartmentMaster DM
				LEFT JOIN sStudent.vStudentAcademic SA ON SA.DepartmentId = DM.Id
				INNER JOIN sStudent.tStudentOther SO ON SO.StudentId = SA.StudentId
				LEFT JOIN sCommon.tReligionMaster RM ON RM.Id = SO.ReligionId
				LEFT JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId 
				LEFT JOIN sSetup.tOrganizationMaster OM ON OM.Id = BM.OrgId
				LEFT JOIN sSetup.tOrgGroupMaster OGMR ON OGMR.Id=OM.OrgGroupId
				LEFT JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BM.OrgGroupBatchId
				LEFT JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
			WHERE  
				COGBM.Id=@rCommonOrgGroupBatchId AND SA.StatusId = 1
				AND ((DM.OrgId = @rOrgId) OR (@rOrgId = 0))
 			GROUP BY 
				DM.Title,DM.Id,RM.Title
			Order By DM.Id
		END
		ELSE IF(@rFilter = 'Housewise') --------------Department/House
		BEGIN
			SELECT 
				DM.Id As DepartmentId,
				DM.Title As Department,
				ISNULL(HM.Title,'NA') AS House,
				COUNT(SA.AcademicId) As Total
			FROM 
				sSetup.tDepartmentMaster DM
				LEFT JOIN sStudent.vStudentAcademic SA ON SA.DepartmentId = DM.Id
				INNER JOIN sStudent.tStudentOther SO ON SO.StudentId = SA.StudentId
				LEFT JOIN sActivity.tHouseMaster HM ON HM.Id = SO.HouseId
				LEFT JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId 
				LEFT JOIN sSetup.tOrganizationMaster OM ON OM.Id = BM.OrgId
				LEFT JOIN sSetup.tOrgGroupMaster OGMR ON OGMR.Id=OM.OrgGroupId
				LEFT JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BM.OrgGroupBatchId
				LEFT JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
			WHERE  
				COGBM.Id=@rCommonOrgGroupBatchId AND SA.StatusId = 1
				AND ((DM.OrgId = @rOrgId) OR (@rOrgId = 0))
 			GROUP BY 
				DM.Title,DM.Id,HM.Title
			Order By DM.Id
		END
	END
	ELSE IF(@rTypeId = 4)----------LEVEL 4
	BEGIN
		IF(@rFilter = 'Statuswise')
		BEGIN
			SELECT 
				CM.Id as ClassId,
				CM.Title As Class,
				COUNT(SA.AcademicId) AS Total,
				COUNT(ASA.ActiveStudent) AS Active
			FROM 
				sSetup.tClassMaster CM
				LEFT JOIN sStudent.vStudentAcademic SA ON SA.ClassId = CM.Id
				LEFT JOIN (SELECT SA1.AcademicId As ActiveStudent FROM sStudent.vStudentAcademic SA1
				WHERE SA1.StatusId = 1 Group By SA1.AcademicId) ASA ON ASA.ActiveStudent = SA.AcademicId
				INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id = SA.DepartmentId
				INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId 
 				INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = BM.OrgId
				INNER JOIN sSetup.tOrgGroupMaster OGMR ON OGMR.Id=OM.OrgGroupId
				INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BM.OrgGroupBatchId
				INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
			WHERE  
				COGBM.Id=@rCommonOrgGroupBatchId AND ((SA.OrgId = @rOrgId) OR (@rOrgId = 0))
				AND ((DM.Id = @rDepartmentId) OR (@rDepartmentId = 0))
 			GROUP BY 
				CM.Title,CM.Id 
			Order By
				CM.Title
		END
		ELSE IF(@rFilter = 'Genderwise')----------------Class/Gender
		BEGIN
			SELECT 
				CM.Id as ClassId,
				CM.Title As Class,
				COUNT(MSA.ActiveStudent) AS Male,
				COUNT(FSA.ActiveStudent) AS Female
			FROM 
				sSetup.tClassMaster CM
				LEFT JOIN sStudent.vStudentAcademic SA ON SA.ClassId = CM.Id
				LEFT JOIN (SELECT SA1.AcademicId As ActiveStudent FROM sStudent.vStudentAcademic SA1
				INNER JOIN sStudent.tStudentOther SO ON SO.StudentId = SA1.StudentId
				WHERE SA1.StatusId = 1 AND SO.GenderId = 1  Group By SA1.AcademicId) MSA ON MSA.ActiveStudent = SA.AcademicId
				LEFT JOIN (SELECT SA1.AcademicId As ActiveStudent FROM sStudent.vStudentAcademic SA1
				INNER JOIN sStudent.tStudentOther SO ON SO.StudentId = SA1.StudentId
				WHERE SA1.StatusId = 1 AND SO.GenderId = 2  Group By SA1.AcademicId) FSA ON FSA.ActiveStudent = SA.AcademicId
				INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id = SA.DepartmentId
				INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId 
 				INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = BM.OrgId
				INNER JOIN sSetup.tOrgGroupMaster OGMR ON OGMR.Id=OM.OrgGroupId
				INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BM.OrgGroupBatchId
				INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
			WHERE  
				 COGBM.Id=@rCommonOrgGroupBatchId AND ((SA.OrgId = @rOrgId) OR (@rOrgId = 0))
				AND ((DM.Id = @rDepartmentId) OR (@rDepartmentId = 0))
 			GROUP BY 
				CM.Title,CM.Id 
			Order By
				CM.Title
		END
		ELSE IF(@rFilter = 'CastCategorywise')---------------------Class/CastCategory
		BEGIN
			SELECT 
				CM.Id as ClassId,
				CM.Title As Class,
				ISNULL(CCM.Title,'NA') AS CastCategory,
				COUNT(SA.AcademicId) As Total
			FROM 
				sSetup.tClassMaster CM
				LEFT JOIN sStudent.vStudentAcademic SA ON SA.ClassId = CM.Id
				INNER JOIN sStudent.tStudentOther SO ON SO.StudentId = SA.StudentId
				LEFT JOIN sCommon.tCastCategoryMaster CCM ON CCM.Id = SO.CastCategoryId
				INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id = SA.DepartmentId
				INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId 
 				INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = BM.OrgId
				INNER JOIN sSetup.tOrgGroupMaster OGMR ON OGMR.Id=OM.OrgGroupId
				INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BM.OrgGroupBatchId
				INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
			WHERE  
				 COGBM.Id=@rCommonOrgGroupBatchId AND ((SA.OrgId = @rOrgId) OR (@rOrgId = 0))
				AND ((DM.Id = @rDepartmentId) OR (@rDepartmentId = 0)) AND SA.StatusId = 1
 			GROUP BY 
				CM.Title,CM.Id,CCM.Title
			Order By
				CM.Title
		END
		ELSE IF(@rFilter = 'Religionwise')---------------------Class/Religion
		BEGIN
			SELECT 
				CM.Id as ClassId,
				CM.Title As Class,
				ISNULL(RM.Title,'NA') AS Religion,
				COUNT(SA.AcademicId) As Total
			FROM 
				sSetup.tClassMaster CM
				LEFT JOIN sStudent.vStudentAcademic SA ON SA.ClassId = CM.Id
				INNER JOIN sStudent.tStudentOther SO ON SO.StudentId = SA.StudentId
				LEFT JOIN sCommon.tReligionMaster RM ON RM.Id = SO.ReligionId
				INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id = SA.DepartmentId
				INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId 
 				INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = BM.OrgId
				INNER JOIN sSetup.tOrgGroupMaster OGMR ON OGMR.Id=OM.OrgGroupId
				INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BM.OrgGroupBatchId
				INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
			WHERE  
				 COGBM.Id=@rCommonOrgGroupBatchId AND ((SA.OrgId = @rOrgId) OR (@rOrgId = 0))
				AND ((DM.Id = @rDepartmentId) OR (@rDepartmentId = 0)) AND SA.StatusId = 1
 			GROUP BY 
				CM.Title,CM.Id,RM.Title
			Order By
				CM.Title
		END
		ELSE IF(@rFilter = 'Housewise')-------------------Class/House
		BEGIN
			SELECT 
				CM.Id as ClassId,
				CM.Title As Class,
				ISNULL(HM.Title,'NA') AS House,
				COUNT(SA.AcademicId) As Total
			FROM 
				sSetup.tClassMaster CM
				LEFT JOIN sStudent.vStudentAcademic SA ON SA.ClassId = CM.Id
				INNER JOIN sStudent.tStudentOther SO ON SO.StudentId = SA.StudentId
				LEFT JOIN sActivity.tHouseMaster HM ON HM.Id = SO.HouseId
				INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id = SA.DepartmentId
				INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId 
 				INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = BM.OrgId
				INNER JOIN sSetup.tOrgGroupMaster OGMR ON OGMR.Id=OM.OrgGroupId
				INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BM.OrgGroupBatchId
				INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
			WHERE  
				 COGBM.Id=@rCommonOrgGroupBatchId AND ((SA.OrgId = @rOrgId) OR (@rOrgId = 0))
				AND ((DM.Id = @rDepartmentId) OR (@rDepartmentId = 0)) AND SA.StatusId = 1
 			GROUP BY 
				CM.Title,CM.Id,HM.Title
			Order By
				CM.Title
		END
	END
END
GO
PRINT N'Altering Procedure [sStudent].[pStudentDetailFormGet]...';


GO
 
ALTER PROCEDURE [sStudent].[pStudentDetailFormGet]
	@rBatchId int = 0,
	@rStudentId bigint = 0,
	@rOrgGroupBatchId int = 0,
	@rOrgId int = 0,
	@Tab nvarchar(20) = '',
	@rAttendanceTypeId smallint = 0,
	@rDepositHeadId int = 0,
	@rAlertModeId smallint = 0,
	@rIsMobileApp bit = 0,
	@rExamId int = 0

	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 

	DECLARE @lSUIdBarcode nvarchar(50)
	DECLARE @lAcademicId bigint = 0, @lClassId int  = 0, @lAdmissionCategoryId int = 0,@lCode nvarchar(20) = '',@lEmail nvarchar(50) = '',@lContactNo nvarchar(50) ='',@lDate datetime = (SELECT sCommon.fGetDate()),@lOrgGroupId int = 0,
	@lDepartmentId int = 0, @lDivisionId int = 0
	SELECT @lAcademicId = Id,@lClassId=ClassId,@lAdmissionCategoryId=AdmissionCategoryId,@lDivisionId = DivisionId from sStudent.tAcademic
	Where StudentId = @rStudentId AND BatchId = @rBatchId
	SELECT @lCode = Code FROM sStudent.tStudentMaster WHERE Id = @rStudentId
	SELECT @lEmail = ParentEmail, @lContactNo = ParentContactNo FROM sStudent.tStudentCommunication WHERE StudentId = @rStudentId
	SELECT @lOrgGroupId = OrgGroupId FROM sSetup.tOrganizationMaster WHERE Id = @rOrgId	
	SELECT @lDepartmentId = DepartmentId FROM sSetup.tClassMaster WHERE Id = @lClassId
	SELECT @lSUIdBarcode = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 168 AND SourceTypeId = 2010 AND SourceId = @lOrgGroupId



	IF(LOWER(@Tab) = 'overview')
	BEGIN
		SELECT
			SA.StudentId AS Id,			
			SA.Name AS StudentName,
			SA.FirstName as FirstName,
			SA.MiddleName as MiddleName,
			SA.LastName as LastName,
			SA.Batch AS AcademicYear,
			ISNULL(SA.Code,' - ') AS Code,
			SA.ClassDivision AS ClassDiv,			
			SA.RollNo,
			ISNULL(SM.Title,'-') AS House,
			--Other
			ISNULL(SA.DateOfBirth,'0001/01/01') AS DateOfBirth,
			ISNULL(SA.BirthTaluka,'') AS BirthTaluka,
			ISNULL(SA.BirthPlace,'') AS BirthPlace,	
			ISNULL(SA.BirthDistrict,'') AS BirthDistrict,
			ISNULL(SA.BirthDateInWord,'') AS BirthDateInWord,                           
			ISNULL(SA.Gender,'') AS Gender,
			SA.GenderId,
			ISNULL(SA.Religion,'') AS Religion,
			--Admission			
			ISNULL(SA.AdmissionStandard,'') AS AdmissionStandard,			
			ISNULL(SA.AdmissionDate,'0001/01/01') AS AdmissionDate,	
			ISNULL(SA.PreviousSchool,'') AS PreviousSchool,
			ISNULL(SA.AdmissionCategory,'') AS StudentAdmissionCategory,
			ISNULL(SA.LeftDate,'0001/01/01') AS LeftDate,						 
			ISNULL(SA.LeftStandard,'') AS LeftStandard,			
			ISNULL(SA.InactiveDate,'0001/01/01') AS InactiveDate,		
			ISNULL(SA.LCNumber,'') AS LCNumber,			
			ISNULL(SA.LCDate,'0001/01/01') AS LCDate,
			--Communication
			ISNULL(SA.PresentStreetone,'') + ' ' + ISNULL(SA.PresentStreetTwo,'') + ' ' + ISNULL(SA.PresentStreetThree,'') AS PresentAddress,
			ISNULL(SA.PresentCity,'') AS PresentCity,
			ISNULL(SA.PresentState,'') AS PresentState,
			ISNULL(SA.PresentCountry,'') AS PresentCountry,
			ISNULL(SA.PresentZipCode,'') AS PresentZipCode,
			ISNULL(SA.PresentContactNo,'') AS PresentContactNo,
			
			ISNULL(SA.EmergencyStreetOne,'') + ' ' + ISNULL(SA.EmergencyStreetTwo,'') + ' ' + ISNULL(SA.EmergencyStreetThree,'') AS EmergencyAddress,
			ISNULL(SA.EmergencyCity,'') AS EmergencyCity,
			ISNULL(SA.EmergencyState,'') AS EmergencyState,
			ISNULL(SA.EmergencyCountry,'') AS EmergencyCountry,
			ISNULL(SA.EmergencyZipCode,'') AS EmergencyZipCode,
			ISNULL(SA.EmergencyContactNo,'') AS EmergencyContactNo,
			
			ISNULL(SA.PermanentStreetOne,'') + ' ' + ISNULL(SA.PermanentStreetTwo,'') + ' ' + ISNULL(SA.PermanentStreetThree,'') AS PermanentAddress,
			ISNULL(SA.PermanentCity,'') AS PermanentCity,
			ISNULL(SA.PermanentState,'') AS PermanentState,
			ISNULL(SA.PermanentCountry,'') AS PermanentCountry,
			ISNULL(SA.PermanentZipCode,'') AS PermanentZipCode,
			ISNULL(SA.PermanentContactNo,'') AS PermanentContactNo,
			
			--Parent Information
			ISNULL(SF.FatherName,'') AS FatherName,
			ISNULL(SF.FatherOccupation,'') AS FatherOccupation,
			ISNULL(SF.FatherQualification,'') AS FatherQualification,
			ISNULL(SF.FatherContactNo,'') AS FatherContactNo,
			ISNULL(SF.FatherMail,'') AS FatherMail,
			ISNULL(SF.FatherOfficeAddress,'') AS FatherOfficeAddress,
			ISNULL(SF.FatherDesignation,'') AS FatherDesignation,
			ISNULL(SF.FatherOrganization,'') AS FatherOrganization,
			ISNULL(SF.FatherIncome,'') AS FatherIncome,

			ISNULL(SF.MotherName,'') AS MotherName,
			ISNULL(SF.MotherOccupation,'') AS MotherOccupation,
			ISNULL(SF.MotherQualification,'') AS MotherQualification,
			ISNULL(SF.MotherContactNo,'') AS MotherContactNo,
			ISNULL(SF.MotherMail,'') AS MotherMail,
			ISNULL(SF.MotherOfficeAddress,'') AS MotherOfficeAddress,
			ISNULL(SF.MotherDesignation,'') AS MotherDesignation,
			ISNULL(SF.MotherOrganization,'') AS MotherOrganization,
			ISNULL(SF.MotherIncome,'') AS MotherIncome,

			ISNULL(SF.RelationshipName,'') AS RelationShip,
			ISNULL(SF.RelativeName,'') AS RelativeName,
			ISNULL(SF.RelativeOccupation,'') AS RelativeOccupation,
			ISNULL(SF.RelativeQualification,'') AS RelativeQualification,
			ISNULL(SF.RelativeContactNo,'') AS RelativeContactNo,
			ISNULL(SF.RelativeMail,'') AS RelativeMail,
			ISNULL(SF.RelativeOfficeAddress,'') AS RelativeOfficeAddress,
			ISNULL(SF.RelativeDesignation,'') AS RelativeDesignation,
			ISNULL(SF.RelativeOrganization,'') AS RelativeOrganization,
			ISNULL(SF.RelativeIncome,'') AS RelativeIncome,
			
			--Health Information
			ISNULL(SA.BloodGroup,'') AS BloodGroup,
			ISNULL(SH.IdentificationMark1,'')+' '+ISNULL(SH.IdentificationMark2,'') as IdentificationMark,
			
			ISNULL(SH.FamilyDoctorName,'') AS FamilyDoctorName,
			ISNULL(SH.FamilyDoctorContactNo,'') AS FamilyDoctorContactNo,
			
			ISNULL(SH.IsPysicalDeformity,0) AS IsPysicalDeformity,
			ISNULL(SH.PysicalDeformityRemark,'') AS PysicalDeformityRemark,
			ISNULL(SH.IsMajorIllness,0) AS IsMajorIllness,
			ISNULL(SH.MajorIllnessRemark,'') As MajorIllnessRemark,
			ISNULL(SH.IsAllergy,0) AS IsAllergy,
			ISNULL(SH.AllergyRemark,'') As AllergyRemark,
			ISNULL(SH.IsPastHistory,0) As IsPastHistory ,
			ISNULL(SH.PastHistoryRemark,'') As PastHistoryRemark,
			--Hostel
			ISNULL(RM.Title,'') AS RoomNo,			
			ISNULL(HM.Title,'') AS Hostel,
			ISNULL(EMW.FirstName,'')+' '+ISNULL(EMW.LastName,'') AS WardenName,
			ISNULL(ECW.PhoneNoCompany,'') As WardenPhoneNo,
			ISNULL(ECW.ExtensionNo,'') AS WardenExtNo,
			ISNULL(ECW.MobileNumber,'') AS WardenMobileNo,
			ISNULL(EMA.FirstName,'')+' '+ISNULL(EMA.LastName,'') AS AssignedRoomBy,	
			ISNULL(ECA.PhoneNoCompany,'') AS AssignedRoomByPhoneNo,
			ISNULL(ECA.ExtensionNo,'') AS AssignedRoomByExtNo,
			ISNULL(ECA.MobileNumber,'') AS AssignedRoomByMobileNo,
			--Notification Details
			ISNULL(SA.ParentEmail,'') AS ParentEmail,
			ISNULL(SA.ParentContactNo,'') As ParentContactNo,
			ISNULL(SA.StudentEmail,'') AS StudentEmail,
			ISNULL(SA.StudentContactNo,'') AS StudentContactNo,

			-- Photos		
	   	    ISNULL(SA.StudentPhoto, CONVERT(VARBINARY(MAX), 0))AS StudentPhoto,
	   	    ISNULL(SA.FatherPhoto, CONVERT(VARBINARY(MAX), 0)) AS FatherPhoto,
	   	    ISNULL(SA.MotherPhoto, CONVERT(VARBINARY(MAX), 0)) AS MotherPhoto,
	   	    ISNULL(SA.RelativePhoto, CONVERT(VARBINARY(MAX), 0)) AS RelativePhoto,
			
		   -- Transport Details
		    A.VehicleName AS VehicleName,
		    A.VehicleRegistrationNumber AS VehicleRegistrationNumber,
		    A.TypeOfVehicle AS TypeOfVehicle,
		    ISNULL(A.BusRoute,'') AS BusRoute,
		    A.DriverName,
		    A.DriverMobileNo,
		    A.ConductorName,
		    A.ConductorMobileNo,
		    ISNULL(A.BusRouteDestination,'') AS BusRouteDestination,		    
		    A.DropVehicleName AS DropVehicleName,
		    A.DropVehicleRegistrationNumber AS DropVehicleRegistrationNumber,
		    A.DropTypeOfVehicle AS DropTypeOfVehicle,
		    ISNULL(A.DropRoute,'') AS DropRoute,
		    A.DropRouteDriverName AS DropRouteDriverName,
		    A.DropRouteDriverMobileNo AS DropRouteDriverMobileNo,
		    A.DropRouteConductorName AS DropRouteConductorName,
		    A.DropRouteConductorMobileNo AS DropRouteConductorMobileNo,
		    ISNULL(A.DropDestination,'') AS DropDestination,
		    
		    --ClassTeacher Details
		    ISNULL(EMT.Id,0) AS TeacherId,
		    EMT.FirstName+' '+EMT.MiddleName+' '+EMT.LastName AS TeacherFullName,
		    EDM.Title AS TeacherDesignation,
		    EPD.Qualification AS TeacherQualification,
			ISNULL(FED.PaidAmount,0) AS FeePaidAmount,
			ISNULL(FED.PendingAmount,0) AS FeePendingAmount,
			ISNULL(FED.PaidAmount,0) + ISNULL(FED.PendingAmount,0) AS FeeTotalAmount,
			(SELECT COUNT(AcademicId) FROM sAttendance.tStudentRegister WHERE AcademicId = @lAcademicId AND IsPresent = 0) AS AbsentCount,
			(SELECT COUNT(AcademicId) FROM sAttendance.tStudentRegister WHERE AcademicId = @lAcademicId AND IsPresent = 1) AS PresentCount,

			--TecherSubjectDivision
			--EM.FirstName + ' ' + EM.LastName AS DivisionTeacherName,
			--SM.Title AS DivisionSubjectName,

			-- Today's Lectures

			ISNULL(STUFF((
			SELECT ',' + OnlineLearningTitle FROM 
			(SELECT OL.Title AS OnlineLearningTitle FROM sAcademic.tOnlineLearning OL INNER JOIN (SELECT OLS.OnlineLearningId FROM sAcademic.tOnlineLearningScope OLS
				WHERE (
				( 
				(OLS.SourceTypeId = 2021 AND OLS.SourceId =SA.OrgId) 
				OR
				(OLS.SourceTypeId = 2017 AND OLS.SourceId =SA.DepartmentId) OR
				(OLS.SourceTypeId = 2016 AND OLS.SourceId =SA.ClassId) OR
				(OLS.SourceTypeId = 2005 AND OLS.SourceId =SA.DivisionId) OR
				(OLS.SourceTypeId = 2003 AND OLS.SourceId =SA.StudentId) OR
				(OLS.SourceTypeId = 2001 AND OLS.SourceId =SA.AcademicId)
				 ))
				) D
				ON D.OnlineLearningId= OL.Id WHERE OL.StartDate >= CAST(sCommon.fGetDate() AS DATE) AND OL.EndDate <= CAST(sCommon.fGetDate() AS DATE)) OL FOR XML PATH('')),1,1,''),'') AS OnlineLearningLectures,

			ISNULL(STUFF((
				SELECT ',' + ExamName + ' (' + CAST([Percentage] AS NVARCHAR(20)) + ')' FROM (
				SELECT AD.Id AS AcademicId,E.[Name] AS ExamName, R.[Percentage] FROM
				sStudent.tAcademic AD 
				INNER JOIN  sAssessment.vExamMaster E ON E.BatchId = AD.BatchId AND E.ClassId = AD.ClassId
				INNER JOIN sSetup.tBatchMaster BM ON E.BatchId = BM.Id 
				INNER JOIN sSetup.tClassMaster CM ON CM.Id=AD.ClassId
				INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=AD.DivisionId
				INNER JOIN sAssessment.tResult R ON AD.Id = R.AcademicId AND R.ExamId = E.Id
 
				 WHERE ((AD.Id=@lAcademicId) OR (@lAcademicId=0))	
					AND IsProcessResult=1 ) E
				FOR XML PATH('')),1,1,''),'') AS ExamPercentage,
				
			(SELECT SUM(Amount) FROM sFee.tDepositAdd WHERE AcademicId = @lAcademicId) AS DepositCreditAmount,
			(SELECT SUM(Amount) FROM sFee.tDepositAdjustment WHERE AcademicId = @lAcademicId) + (SELECT SUM(RefundAmount) FROM sFee.tDepositRefund WHERE AcademicId = @lAcademicId) AS DepositDebitAmount,
			ISNULL(SI.QRCode,0x) AS QRCode,
			CASE WHEN @lSUIdBarcode = 'True' THEN SA.SUId  ELSE SA.Code END AS BarcodeNumber

			FROM 
			sStudent.vStudentAllDetail SA          
           LEFT JOIN sStudent.tStudentHealth SH ON SA.StudentId=SH.StudentId
           LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId = SA.StudentId           
           LEFT JOIN sActivity.tHouseMaster SM ON SM.ID = SA.HouseId
           LEFT JOIN sHostel.tAssignRoom AR ON AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003  AND ((AR.OrgGroupBatchId=@rOrgGroupBatchId) OR(@rOrgGroupBatchId=0))
           LEFT JOIN sHostel.tRoomMaster RM ON RM.Id=AR.RoomId
           LEFT JOIN sCommon.tPhysicalDisabilityCategoryMaster PDCM ON PDCM.Id = SH.PhysicalDisabilityCategoryId
           LEFT JOIN sHostel.tHostelMaster HM ON HM.Id=RM.HostelId  
		   LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId = SA.StudentId
		   --LEFT JOIN sAcademic.tTeacherSubjectDivision TSD ON TSD.DivisionId = SA.DivisionId
		   --LEFT JOIN sSetup.tSubjectMaster SBM ON SBM.Id = TSD.SubjectId
		   --LEFT JOIN sHrm.tEmployeeMaster EM ON EM.Id = TSD.EmployeeId
            LEFT JOIN --HostelDetails
            (
		   SELECT 
		   employeeId, 
		   HostelId,   
		   ROW_NUMBER() OVER (PARTITION BY HostelId ORDER By HostelId ) as ROWNo 		   
		 
		   FROM sHostel.tHostelwarden 
            )  HW ON HW.HostelId=HM.Id AND RowNo = 1           
           LEFT JOIN sHrm.tEmployeeMaster EMW ON HW.EmployeeId=EMW.Id AND  ISNULL(EMW.IsOtherUser,0) = 0
           LEFT JOIN sHrm.tEmployeeMaster EMA ON RM.AssignedEmployeeId=EMA.Id AND  ISNULL(EMA.IsOtherUser,0) = 0
           LEFT JOIN sHrm.tEmployeeCommunications ECW ON EMW.Id=ECW.EmployeeId 
           LEFT JOIN sHrm.tEmployeeCommunications ECA ON  EMA.Id=ECA.EmployeeId
           LEFT JOIN -- Transport Details
           ( SElect AR1.SourceId,
           VM.Title AS VehicleName,
		    VM.RegistrationNumber AS VehicleRegistrationNumber,
		    TV.Title AS TypeOfVehicle,
		    ISNULL(BRM.Title,'') AS BusRoute,
		    BRM.DriverName,
		    BRM.DriverMobileNo,
		    BRM.ConductorName,
		    BRM.ConductorMobileNo,
		    ISNULL(BRDM.Title,'') AS BusRouteDestination,
		    VM.Title AS DropVehicleName,
		    VM.RegistrationNumber AS DropVehicleRegistrationNumber,
		    TV1.Title AS DropTypeOfVehicle,
		    ISNULL(BRM1.Title,'') AS DropRoute,
		    BRM1.DriverName AS DropRouteDriverName,
		    BRM1.DriverMobileNo AS DropRouteDriverMobileNo,
		    BRM1.ConductorName AS DropRouteConductorName,
		    BRM1.ConductorMobileNo AS DropRouteConductorMobileNo,
		    ISNULL(BRDM1.Title,'') AS DropDestination
		      FROM
             sTransport.tAssignRoute AR1   
           INNER JOIN sTransport.tBusRouteDestinationMaster BRDM ON BRDM.Id=AR1.PickupDestinationId AND AR1.SourceTypeId=2003
           INNER JOIN sTransport.tBusRouteMaster BRM ON BRM.Id=BRDM.BusRouteId AND ((BRM.OrgGroupBatchId=@rOrgGroupBatchId) OR(@rOrgGroupBatchId=0))
           LEFT JOIN sTransport.tVehicleMaster VM ON VM.Id=BRM.VehicleId
           LEFT JOIN sTransport.tVehicleTypeMaster TV ON TV.Id = VM.VehicleTypeId
           LEFT JOIN sTransport.tBusRouteDestinationMaster BRDM1 ON BRDM1.Id=AR1.DropDestinationId
           LEFT JOIN sTransport.tBusRouteMaster BRM1 ON BRM1.Id=BRDM1.BusRouteId AND ((BRM1.OrgGroupBatchId=@rOrgGroupBatchId) OR(@rOrgGroupBatchId=0))
           LEFT JOIN sTransport.tVehicleMaster VM1 ON VM1.Id=BRM1.VehicleId
           LEFT JOIN sTransport.tVehicleTypeMaster TV1 ON TV1.Id = VM1.VehicleTypeId) A ON A.SourceId=SA.StudentId
           LEFT JOIN sSetup.tDivisionMaster DM ON  DM.Id=SA.DivisionId
           LEFT JOIN sHrm.tEmployeeMaster EMT ON EMT.Id=DM.InchargeEmployeeId AND  ISNULL(EMT.IsOtherUser,0) = 0
           LEFT JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EMT.Id
           LEFT JOIN sHrm.tEmployeeDesignationMaster EDM ON EDM.Id=EJD.EmployeeDesignationId
           LEFT JOIN sHrm.tEmployeePersonalDetail EPD ON EPD.EmployeeId=EMT.Id
           LEFT JOIN sHrm.tEmployeeImages EI ON EI.EmployeeId=EMT.Id
           LEFT JOIN sStudent.tStudentSibling  SS ON SS.StudentId=SA.StudentId 
           LEFT JOIN sStudent.tStudentAdditional  SAD ON SAD.StudentId=SA.StudentId 
           LEFT JOIN sStudent.tCollegeDetail  CD ON CD.StudentId=SA.StudentId 
           LEFT JOIN sStudent.tAcademicDetail  ACD ON ACD.AcademicId=SA.AcademicId 
           LEFT JOIN sCommon.tMaritalStatusMaster  MS ON MS.Id=CD.MaritalStatusId
           LEFT JOIN sConfig.fDisplayFieldGet(@rOrgId) AS DF ON DF.OrgId=SA.OrgId
           LEFT JOIN sCommon.tCastCategoryMaster CT ON CT.Id = SA.CastCategoryId
           LEFT JOIN sCommon.tCountryMaster CM ON CM.Id=SA.NationalityId
           INNER JOIN sSetup.tBatchClass BC ON BC.ClassID =  SA.ClassID and BC.BatchId= @rBatchId
           LEFT JOIN sCommunication.tCustomGroupMember CGM ON CGM.SourceId = SA.StudentId AND CGM.SourceTypeId = 2003
           LEFT JOIN sCommunication.tCustomGroup CGG ON CGG.Id = CGM.CustomGroupId
           LEFT JOIN sStudent.tStudentMaster SMM ON SMM.Id = SA.StudentId
           LEFT JOIN sStudent.tStudentGroupMaster SGM ON SGM.Id = SMM.StudentGroupId
           LEFT JOIN sStudent.tStudentOtherGroupMaster SOGM ON SOGM.Id = SMM.StudentOtherGroupId
		   LEFT JOIN sStudent.tStudentAdmission SAM ON SAM.StudentId = SA.StudentId
		   LEFT JOIN -- Fee Details
		   (
				SELECT 
			SUM(ISNULL(R.PaidAmount,0)) AS PaidAmount,
			SUM(ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00)) AS PendingAmount,
			FS.BatchId
			  FROM 
						sFee.tFeeMaster FM
					INNER JOIN 
					(
						SELECT 
							FS1.FeeId,
							FS1.Id,
							ISNULL(FS1.IsOptional,0)AS IsOptional,
							ISNULL(FS1.IsVariable,0)AS IsVariable,
							ISNULL(FS1.Amount,0)AS Amount,
							ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
							ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
							FS1.BatchId,
							ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
							ISNULL(FS1.CollectionGroupId,0) AS CollectionGroupId
				 
						FROM sFee.tFeeSetup FS1
			   
							WHERE FS1.ClassId=@lClassId AND FS1.AdmissionCategoryId=@lAdmissionCategoryId AND IsOptional=0
							AND FS1.BatchId = @rBatchId
							UNION ALL
				
						SELECT 
							FS1.FeeId,
							FS1.Id,
							ISNULL(FS1.IsOptional,0)AS IsOptional,
							ISNULL(FS1.IsVariable,0)AS IsVariable,
							ISNULL(FS1.Amount,0)AS Amount,
							ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
							ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
							FS1.BatchId,
							ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
							ISNULL(FS1.CollectionGroupId,0) AS CollectionGroupId 
				 
						FROM sFee.tFeeSetup FS1
			 
					INNER JOIN sFee.tFeeOptional FO
						ON FO.FeeSetupId=FS1.Id AND (FO.SourceId=@lAcademicId) AND(FO.SourceTypeId=2001)
						WHERE
						 FS1.BatchId = @rBatchId
						AND	FS1.ClassId=@lClassId AND FS1.AdmissionCategoryId=@lAdmissionCategoryId AND IsOptional=1
					) FS ON FS.FeeId=FM.Id
					LEFT JOIN sFee.tFeeAllocation FA
						ON FA.FeeSetupId=FS.Id AND (FA.SourceId=@lAcademicId) AND(FA.SourceTypeId=2001)
					LEFT JOIN
					(
						SELECT ISNULL(SUM(RD.Amount),0) AS PaidAmount,RD.FeeSetupId
						FROM
						sFee.tReceipt R INNER JOIN sFee.tReceiptDetail RD ON	RD.ReceiptId = R.Id 		
						WHERE						
						 R.SourceId= @lAcademicId
						AND ((R.SourceTypeId = 2001))
						AND R.IsObsolete = 0 
						AND R.BatchId = @rBatchId
						 GROUP BY FeeSetupId
					) R ON R.FeeSetupId = FS.Id	
			WHERE 
				FS.BatchId=@rBatchId
				GROUP BY FS.BatchId
		   ) FED ON FED.BatchId = SA.BatchId			  		  

  WHERE 
			((SA.StudentId=@rStudentId)OR(@rStudentId=0))
			AND((SA.BatchId=@rBatchId) OR(@rBatchId=0))			
			AND ((SA.StudentId=@rStudentId) OR (@rStudentId=0))			
			AND ((SA.OrgGroupBatchId=@rOrgGroupBatchId) OR(@rOrgGroupBatchId=0))			
			AND ((SA.OrgId=@rOrgId) OR (@rOrgId = 0))
	END
	ELSE IF(LOWER(@Tab) = 'studentdetails')
	BEGIN
		exec sStudent.pStudentFullProfileGet @rBatchId=@rBatchId,@rStudentId=@rStudentId,@rOrgGroupBatchId=@rOrgGroupBatchId,@rOrgId=@rOrgId
	END	
	ELSE IF(LOWER(@Tab) = 'feedetails')
	BEGIN
		IF(@rIsMobileApp = 0)
		BEGIN
			exec [sFee].[pFeeAllocationViewGet] @rSourceId=@lAcademicId,@rSourceTypeId=2001,@rBatchId=@rBatchId
		
			DECLARE @Receiptgrid NVARCHAR(max)=''
			SELECT  @Receiptgrid = @Receiptgrid + '<tr>		
			<td align="left" scope="col">' + ISNULL(RBM.Title,'') + '</td>
			<td style="color:Black;overflow-wrap:anywhere;"><a style="color: #03afc5 !important;" onclick="FeeReceiptEdit(' + convert(nvarchar,R.ReceiptBookId) + ',' + convert(nvarchar,R.PayTypeId) + ',' + convert(nvarchar,R.ReceiptNumber) + ')">' + convert(varchar,isnull(R.ReceiptNumber,'')) + '</a></td>		
			<td align="left" scope="col">' +  convert(varchar,isnull(R.ReceiptDate,'01/01/0001'),103) + '</td>
			<td align="left" scope="col">' +  ISNULL(PTM.Title,'') + '</td>
			<td align="left" scope="col">' +  isnull(R.ChequeNo,'') + '</td>
			<td align="left" scope="col">' + isnull(R.BankName,'') + '</td>
			<td align="left" scope="col">' +  ISNULL([sFee].[fReceiptFeeDetailGet](R.Id),'') + '</td>
			<td align="left" scope="col">' +  convert(varchar,isnull(R.ReceiptAmount,0)) + '</td>
			<td><input type="button" id="' + convert(varchar,R.Id) + '" value="&#xf02f; Print Fee Receipt" onclick="PrintFeeReceipt(this, ' + convert(varchar,R.Id) + ', ' + convert(varchar,RBM.Id) + ');" class="fas btn btn-report " /></td>
			</tr>'	
			
		  FROM 
					sFee.tReceipt R
				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
				LEFT JOIN sSecurity.tUser U
					ON U.Id=R.CreatedUserId
				INNER JOIN sFee.tReceiptBookMaster RBM 
					ON RBM.Id=R.ReceiptBookId
			
		WHERE 
			R.SourceTypeId = 2001
			AND SA.AcademicId=@lAcademicId		
			ORDER BY R.ReceiptNumber
			
			
		select isnull(@Receiptgrid,'') as Receiptgrid

			--exec [sFee].[pFeeReceiptListViewGet] @rAcademicId=@lAcademicId,@rOrgId=@rOrgId
			exec [sFee].[pFeecancelReceiptListviewGet] @rBatchId=@rBatchId,@rOrgId=@rOrgId,@rAcademicId=@lAcademicId		
			exec [sFee].[pRptFeePendingAllBatchGet] @rOrgGroupBatchId=0,@rOrgId=@rOrgId,@rBatchId=0,@rCode=@lCode,@rUserId=0

			--exec [sFee].[pFeeAllocationViewGet] @rSourceId=@lAcademicId,@rSourceTypeId=2001,@rBatchId=@rBatchId
		END
		ELSE
		BEGIN
			exec [sFee].[pFeeAllocationViewGet] @rSourceId=@lAcademicId,@rSourceTypeId=2001,@rBatchId=@rBatchId

			SELECT  
			ISNULL(RBM.Title,'') AS ReceiptBook,
			convert(varchar,isnull(R.ReceiptNumber,'')) AS ReceiptNumber,
			convert(varchar,isnull(R.ReceiptDate,'01/01/0001'),103) AS ReceiptDate,
			ISNULL(PTM.Title,'') AS PayType,
			isnull(R.ChequeNo,'') AS ChequeNo,
			isnull(R.BankName,'') AS BankName,
			ISNULL([sFee].[fReceiptFeeDetailGet](R.Id),'') AS FeeDetail,
			convert(varchar,isnull(R.ReceiptAmount,0)) AS ReceiptAmount						
			  FROM 
						sFee.tReceipt R
					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
					LEFT JOIN sSecurity.tUser U
						ON U.Id=R.CreatedUserId
					INNER JOIN sFee.tReceiptBookMaster RBM 
						ON RBM.Id=R.ReceiptBookId			
			WHERE 
				R.SourceTypeId = 2001
				AND SA.AcademicId=@lAcademicId		
				ORDER BY R.ReceiptNumber


			SELECT convert(varchar,Isnull(R.ReceiptNumber,0)) AS ReceiptNumber,
			convert(varchar,ISNULL(R.ReceiptDate,'01/01/0001'),103) AS ReceiptDate,
			Convert(varchar,ISNULL(R.ReceiptAmount,0)) AS ReceiptAmount,
			ISNULL(PTM.Title,'') AS PayType,
			ISNULL(R.ChequeNo,'') AS ChequeNo,
			ISNULL(R.BankName,'') AS BankName,
			ISNULL(RBM.Title,'') AS ReceiptBook,
			convert(varchar,ISNULL(FI.InvoiceNumber,0)) AS InvoiceNumber,
			 convert(varchar,ISNULL(R.Remark,'')) AS Remark			
		  FROM 
				sFee.tReceipt R
				INNER JOIN sStudent.vStudentAcademic A
					ON A.AcademicId=R.SourceId
				INNER JOIN sFinanceCommon.tPayTypeMaster PTM
				ON PTM.Id=R.PayTypeId
				INNER JOIN sFee.tReceiptBookMaster RBM
					ON RBM.Id=R.ReceiptBookId
				LEFT JOIN sFee.tFeeInvoice FI ON FI.Id = R.FeeInvoiceId
		WHERE 
				R.SourceTypeId=2001 AND R.IsObsolete=1
				AND A.OrgId=@rOrgId AND R.BatchId=@rBatchId
				AND A.AcademicId=@lAcademicId
			   ORDER BY R.ReceiptNumber DESC


            /**** Changes done for mantis : 28925 ****/
		
		SELECT 
			ISNULL(OM.DisplayTitle,'') AS OrganizationName,
			SA.FirstName+' '+SA.LastName as StudentName,
			convert(varchar,Isnull(CR.ReceiptNumber,0)) AS ReceiptNumber,
			convert(varchar,ISNULL(CR.ReceiptDate,'01/01/0001'),103) AS ReceiptDate,
			ISNULL(RBM.Title,'') AS ReceiptBook,
			ISNULL(CCM.Title,'') AS ChargeCategory,
			convert(varchar,ISNULL(SUM(CRD.Amount),0)) AS Amount
			
		    FROM 
            sFee.tChargeReceipt CR
		    INNER JOIN sFee.tChargeReceiptDetail CRD ON CRD.ChargeReceiptId=CR.Id	
		    INNER JOIN sFee.tChargeMaster CM ON CM.Id=CRD.ChargeId
		    INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=CR.SourceId AND CR.SourceTypeId=2001
		    INNER JOIN sFee.tChargeCategoryMaster CCM ON CCM.Id=CM.ChargeCategoryId
		    INNER JOIN sFee.tChargeReceiptBookMaster RBM ON RBM.Id=CR.ChargeReceiptBookId
		    INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=CR.OrgId
		    WHERE 
			CR.SourceTypeId=2001 AND CR.IsObsolete=0
			AND SA.OrgId=@rOrgId AND CR.BatchId=@rBatchId
			AND SA.AcademicId=@lAcademicId
			GROUP BY
            OM.DisplayTitle,
            SA.FirstName,
            SA.LastName,
            CR.ReceiptNumber,
            CR.ReceiptDate,
            RBM.Title,
            CCM.Title
            ORDER BY CR.ReceiptNumber DESC

		SELECT 
		    ISNULL(DHM.Title,'') AS DepositHeadName,
		    ISNULL(vSA.Name,'') AS StudentName, 
		    ISNULL(vSA.Code,'') AS GrNo,
		    vSA.ClassName AS Class,
		    ISNULL(EM.Title,'') As ExpenseType,
		    Convert(varchar,ISNULL(DA.Amount,0)) AS Amount,
		    convert(varchar,ISNULL(DA.AdjustmentDate,'01/01/0001'),103) AS AdjustmentDate
  FROM 		
		sStudent.vStudentAcademic vSA
		INNER JOIN sFee.tDepositAdjustment DA ON DA.AcademicId = vSA.AcademicId
		INNER JOIN sFee.tDepositHeadMaster DHM ON DHM.Id = DA.DepositHeadId
		LEFT JOIN  sFee.tFeeDepositExpenseTypeMaster EM ON EM.Id=DA.FeeDepositExpenseTypeId
  WHERE 				
		vSA.OrgId=@rOrgId AND vSA.BatchId=@rBatchId
		AND vSA.AcademicId=@lAcademicId
		ORDER BY vSA.Name DESC

		SELECT 
		ISNULL(DHM.Title,'') AS DepositHeadName,
		ISNULL(vSA.Name,'') AS StudentName,
		ISNULL(vSA.Code,'') AS GrNo, 
		ISNULL(vSA.ClassName,'') AS Class,
		convert(varchar,(CASE  WHEN ISNULL(DR.RefundAmount,0) <> 0 THEN ISNULL(DR.RefundAmount,0) ELSE
        (SELECT ISNULL(SUM(D.Amount),0) FROM sFee.tDepositAdd D 
        INNER JOIN sFee.tDepositRefund DR1 ON DR1.DepositHeadId=D.DepositHeadId AND DR1.AcademicId=D.AcademicId AND D.AcademicId = DR.AcademicId
        WHERE D.DepositHeadId = DR1.DepositHeadId AND D.AcademicId=DR1.AcademicId )         
		 - (SELECT ISNULL(SUM(DA.Amount),0) AS TotalAmount FROM sFee.tDepositAdjustment DA 
		 INNER JOIN sFee.tDepositRefund DR2 ON DR2.DepositHeadId=DA.DepositHeadId AND DR2.AcademicId=DA.AcademicId AND DA.AcademicId= DR.AcademicId
		 WHERE DA.DepositHeadId = DR2.DepositHeadId AND DA.AcademicId=DR2.AcademicId ) END)) AS RefundAmount,
		 convert(varchar,ISNULL(DR.RefundDate,'01/01/0001'),103) AS RefundDate
		
  FROM 		
		sStudent.vStudentAcademic vSA
		INNER JOIN sFee.tDepositRefund DR ON DR.AcademicId = vSA.AcademicId
		INNER JOIN sFee.tDepositHeadMaster DHM ON DHM.Id = DR.DepositHeadId

  WHERE 				
		vSA.OrgId=@rOrgId AND vSA.BatchId=@rBatchId
		AND vSA.AcademicId=@lAcademicId
		--AND DR.DepositHeadId=@rDepositHeadId
		ORDER BY vSA.Name DESC

		/**** Changes done for mantis : 28925 ****/

		END
	END	
	ELSE IF(LOWER(@Tab) = 'attendance')
	BEGIN
		IF(@rIsMobileApp = 0)
		BEGIN
			IF(@rAttendanceTypeId = 5)
			BEGIN
			exec [sAttendance].[pSubjectRegisterStudentViewGet] @rAcademicId = @lAcademicId,@rBatchId = @rBatchId, @rAttendanceTypeId = @rAttendanceTypeId		
			END
			ELSE 
			BEGIN
			exec [sAttendance].[pMonthlyRegisterStudentviewGet] @rAttendanceTypeId = @rAttendanceTypeId, @rAcademicId = @lAcademicId,@rBatchId = @rBatchId
			END
		END
		ELSE
		BEGIN	
			IF(@rAttendanceTypeId <> 5)
			BEGIN
			SELECT 
				Isnull(MY.MonthTitle,'') AS ForMonth,
				CAST(isnull(MY.YearNumber,0) AS NVARCHAR(20)) AS ForYear,
				CAST(isnull(MR.AttendanceCount,0) AS NVARCHAR(20)) AS AttendanceCount,
				CAST(isnull(MR.PresentCount,0) AS NVARCHAR(20)) AS PresentDays,
				CAST(isnull(MR.AbsentCount,0) AS NVARCHAR(20)) AS AbsentDays,
				CAST(isnull(MR.AveragePresence,0) AS NVARCHAR(20)) AS AveragePresence,
				CAST(isnull(MR.AbsentDays,0) AS NVARCHAR(20)) AS AbsentDate					
			FROM sStudent.vStudentName SN 
			INNER JOIN sSetup.fMonthYearForBatchGET(@rBatchId) AS MY ON MY.BatchId=SN.BatchId AND SN.AcademicId=@lAcademicId 
			INNER JOIN sAttendance.tMonthlyRegister MR ON MR.AcademicId=SN.AcademicId 
				AND MR.AttendanceTypeId=@rAttendanceTypeId
				AND MR.ForMonth=MY.MonthNumber AND MR.ForYear=MY.YearNumber
			WHERE
				SN.AcademicId=@lAcademicId	
			ORDER BY MY.YearNumber,MY.MonthNumber
			END
			ELSE
			BEGIN
			Select 
				isnull(SM.Title,'') AS [Subject],
				(SELECT convert(varchar,ISNULL(count(1),0) )FROM sAttendance.tStudentRegister SR  WHERE  SR.AttendanceTypeId = 5 AND SR.IsPresent = 1 AND SR.AcademicId = SN.AcademicId  AND SR.SubjectId = CS.SubjectId) AS PresentCount,
				(SELECT convert(varchar,ISNULL(count(1),0)) FROM sAttendance.tStudentRegister SR WHERE SR.AttendanceTypeId = 5 AND SR.IsPresent = 0 AND SR.AcademicId = SN.AcademicId AND SR.SubjectId = CS.SubjectId) AS AbsentCount	
				From sStudent.vStudentName SN
				INNER JOIN sSetup.tClassSubject CS
				ON SN.ClassId = CS.ClassId
				INNER JOIN sSetup.tSubjectMaster SM
				ON CS.SubjectId = SM.Id 
				WHERE
					(SN.AcademicId=@lAcademicId)
					AND SN.BatchId = @rBatchId
			END
		END
	END
	ELSE IF(LOWER(@Tab) = 'assessment')
	BEGIN
		IF (@rIsMobileApp = 0) 
		BEGIN
			exec [sAssessment].[pExamListGet] @rAcademicId = @lAcademicId, @rBatchId = @rBatchId
		END
		ELSE
		BEGIN
			SELECT  ISNULL(Cm.DisplayTitle,'')+' - '+isnull(Dm.DisplayTitle,'')+' : '+isnull(E.Name,'') AS ExamName,
			isnull(BM.Title,'') AS [Year],
			convert(varchar,isnull(R.TotalMarks,0)) AS TotalMarks,
			convert(varchar,isnull(R.TotalObtain,'')) AS TotalObtain,
			isnull(R.ResultStatus,'') AS Result,
			isnull(R.ResultGrade,'') AS Grade,
			convert(varchar,isnull(R.RankNumber,0)) AS [Rank],
			convert(varchar,isnull(R.Percentage,0)) AS [Percentage],
			convert(varchar,isnull(R.Percentile,0)) AS Percentile,
			@lAcademicId AS AcademicId,
			convert(varchar,E.Id) AS ExamId
			 From
			 sStudent.tAcademic AD 
			 INNER JOIN  sAssessment.vExamMaster E ON E.BatchId = AD.BatchId AND E.ClassId = AD.ClassId
			 INNER JOIN sSetup.tBatchMaster BM ON E.BatchId = BM.Id 
			 INNER JOIN sSetup.tClassMaster CM ON CM.Id=AD.ClassId
			 INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=AD.DivisionId
			 INNER JOIN sAssessment.tResult R ON AD.Id = R.AcademicId AND R.ExamId = E.Id
 
			 WHERE ((AD.Id=@lAcademicId) OR (@lAcademicId=0))	
			 AND IsProcessResult=1
			 ORDER BY DM.OrderIndex DESC


			 SELECT isnull(ESGM.Title,'') AS ExamName,
			 isnull(SBM.Title,'') AS [Subject],
			convert(varchar,isnull(ED.Maximum,0)) AS Maximum,
			convert(varchar,isnull(ED.Minimum,0)) AS Minimum,
			convert(varchar,isnull(RD.Obtain,0)) As Obtain,
			convert(varchar,isnull(RD.GraceMark,0)) AS GraceMark,
			isnull(RD.Remark,'') AS Remark			
    	
		   FROM sStudent.tAcademic AD
			INNER JOIN sAssessment.tExamMaster EM ON EM.BatchId = AD.BatchId AND EM.ClassId = AD.ClassId
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId = EM.Id
			INNER JOIN sAssessment.tResult R ON AD.Id = R.AcademicId AND R.ExamId = EM.Id
			INNER JOIN sAssessment.tResultDetail RD ON RD.ExamDetailId = ED.Id AND R.Id = RD.ResultId
			INNER JOIN sSetup.tClassSubject CS ON CS.Id = ED.ClassSubjectId
			INNER JOIN sSetup.tSubjectMaster SBM ON SBM.Id = CS.SubjectId
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId
			Where
			((AD.Id=@lAcademicId) OR (@lAcademicId=0))
			AND ((AD.BatchId =  @rBatchId) OR (@rBatchId=0))
		   AND ((EM.Id=@rExamId) OR (@rExamId=0))
		END
	END
	ELSE IF(LOWER(@Tab) = 'certificate')
	BEGIN
		SELECT 'Bonafied' AS CertificateName,CreatedDateTime,Number AS CertificateNumber,Id FROM [sCertificate].[tBonafide] WHERE AcademicId = @lAcademicId AND OrgId = @rOrgId AND BatchId = @rBatchId
		UNION ALL
		SELECT 'Character' AS CertificateName,CreatedDateTime,Number AS CertificateNumber,Id FROM [sCertificate].[tCharacter] WHERE AcademicId = @lAcademicId AND OrgId = @rOrgId AND BatchId = @rBatchId		
		UNION ALL
		SELECT 'Leaving' AS CertificateName,CreatedDateTime,LCNumber AS CertificateNumber,Id FROM [sCertificate].[tLeaving] WHERE AcademicId = @lAcademicId AND OrgId = @rOrgId AND BatchId = @rBatchId
		UNION ALL
		SELECT 'FirstTrial' AS CertificateName,CreatedDateTime,Number AS CertificateNumber,Id FROM [sCertificate].[tFirstTrial] WHERE AcademicId = @lAcademicId AND OrgId = @rOrgId AND BatchId = @rBatchId		
		UNION ALL
		SELECT 'Transfer' AS CertificateName,CreatedDateTime,Number AS CertificateNumber,Id FROM [sCertificate].[tTransfer] WHERE AcademicId = @lAcademicId AND OrgId = @rOrgId AND BatchId = @rBatchId
	END
	ELSE IF(LOWER(@Tab) = 'deposit')
	BEGIN
		exec sFee.pStudentLedgerGet @rAcademicId=@rStudentId,@rDepositHeadId=@rDepositHeadId,@rCode=@lCode,@rSUId=N'',@rOrgId=@rOrgId
	END
	ELSE IF(LOWER(@Tab) = 'alert')
	BEGIN				
		IF(@rIsMobileApp = 1)
		BEGIN
			SELECT 
				'Notification' AS SourceEvent,EM.Title AS EventName,AL.MessageTitle AS AlertSubject,[sCommon].[fXMLTagsReplace](AL.NotificationMessage) as AlertMessage,CONVERT(VARCHAR(10),AL.CreatedDateTime,103) AS CreatedDate,'3' AS AlertModeId			
			FROM
				sAlert.tNotificationLog AL
				INNER JOIN sAlert.tEventMaster EM ON EM.Id=AL.EventId
			WHERE  
				AL.SourceId = @lAcademicId AND AL.SourceTypeId = 2001				

				UNION ALL

			SELECT 
				AL.SourceEvent,EM.Title AS EventName,AL.AlertSubject,[sCommon].[fXMLTagsReplace](AL.AlertMessage) as AlertMessage,CONVERT(VARCHAR(10),AL.CreatedDateTime,103) AS CreatedDate,CAST(AL.AlertModeId AS NVARCHAR(10)) AS AlertModeId
			FROM
				sAlert.tAlertLog AL
				INNER JOIN sAlert.tEventMaster EM ON EM.Id=AL.EventId
			WHERE  
				((AL.ContactId = @lContactNo) OR (AL.ContactId = @lEmail))
				And AL.OrgId=@rOrgId				
		END
		ELSE 
		BEGIN
			IF(@rAlertModeId = 3)
			BEGIN
				exec sAlert.pNotificationViewGet @rSourceId = @lAcademicId, @rSourceTypeId = 2001, @rIsFlag = 1
			END
			ELSE
			BEGIN
				exec [sAlert].[pSMSViewGet] @rMobileNumber = @lContactNo,@rEmail = @lEmail, @rOrgId = @rOrgId, @rIsFlag = 1, @rAlertModeId = @rAlertModeId		
			END
		END
	END
	ELSE IF(LOWER(@Tab) = 'library')
	BEGIN
		IF(@rIsMobileApp = 1)
		BEGIN
			SELECT
				Isnull(LM.Title,'') AS [Library],
				ISNULL(BM.Code,'') AS BookCode,
				isnull(BM.Title,'') AS BookTitle,
				convert(varchar,isnull(BL.LogDate,''),103) AS LogDate,
				convert(varchar,isnull(BL.DueDate,''),103) AS DueDate,
				CASE WHEN SM.Title = 'Available' THEN  'Returned' ELSE ISNULL(SM.Title,'') END AS [Status]		
			FROM 
				sLibrary.tBookLog BL
				INNER JOIN sLibrary.tBookMaster BM ON BM.Id=BL.ResourceSourceId
				INNER JOIN sStudent.vStudentAcademic SA ON SA.StudentId=BL.ReaderSourceId
				INNER JOIN sLibrary.tIssueSetting IS1 ON IS1.SourceId=SA.ClassId AND IS1.SourceTypeId=2005 AND BL.LibraryId = IS1.LibraryId
				INNER JOIN sCommon.tStatusMaster SM ON SM.Id=BL.StatusId AND SM.IsObsolete = 0 AND SM.StatusTypeId=106
				INNER JOIN sLibrary.tLibraryMaster LM ON LM.Id=BL.LibraryId
			WHERE 
				(BL.ReaderSourceTypeId=2003)
				AND BL.IsCurrentStatus=1
				AND ((BL.StatusId=521) OR (BL.StatusId=523))
				AND (BL.OrgId=@rOrgId)
				AND (BL.BatchId=@rBatchId)
				AND SA.AcademicId=@lAcademicId
		END
		ELSE BEGIN
		exec [sLibrary].[pBookLogListViewGet] @rAcademicId = @lAcademicId, @rOrgId = @rOrgId,@rBatchId = @rBatchId
		END
	END
	ELSE IF(LOWER(@Tab) = 'paymentdetails')
	BEGIN
		exec sOp.pPaymentTransactionGet @rId=@lAcademicId,@rFromDate=NULL,@rToDate=@lDate,@rTransactionStatusId=0,@rFunctionalityId=0,
		@rFirstName=NULL,@rOrgGroupId=@lOrgGroupId,@rOrgId=@rOrgId,
		@rBatchId=@rBatchId,@rReceiptBookId=0,@rOSTypeId=0,@rFormNo=0,@rReferenceNo=0,@rPaymentGatewayId=0
	END
	ELSE IF(LOWER(@Tab) = 'onlinelearning')
	BEGIN
	SELECT OL.Title AS OLTitle,  OL.StartTime, OL.EndTime, SM.Title AS [Subject], EM.FirstName + ' ' + Em.LastName AS EmployeeName, DM.Title AS LearningType FROM sAcademic.tOnlineLearningScope OLS
	INNER JOIN sAcademic.tOnlineLearning OL ON OL.Id = OLS.OnlineLearningId
	INNER JOIN sSetup.tSubjectMaster SM ON SM.Id = OL.SubjectId
	INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id = TeacherEmployeeId
	INNER JOIN sCommon.tDataMaster DM ON DM.Id = OL.LearningTypeId AND DM.DataTypeId = 3
	WHERE (
	( 
	(OLS.SourceTypeId = 2021 AND OLS.SourceId = @rOrgId) 
	OR
	(OLS.SourceTypeId = 2017 AND OLS.SourceId = @lDepartmentId) OR
	(OLS.SourceTypeId = 2016 AND OLS.SourceId = @lClassId) OR
	(OLS.SourceTypeId = 2005 AND OLS.SourceId = @lDivisionId) OR
	(OLS.SourceTypeId = 2003 AND OLS.SourceId = @rStudentId) OR
	(OLS.SourceTypeId = 2001 AND OLS.SourceId = @lAcademicId)
		))

	AND OL.StartDate = CAST(sCommon.fGetDate() AS DATE)

	SELECT
		ISNULL((SELECT SUM(AcademicId) FROM sAcademic.tOnlineLearningAttendance WHERE IsPresent = 1 And AcademicId = @lAcademicId),0) AS PresentCount,
		ISNULL((SELECT SUM(AcademicId) FROM sAcademic.tOnlineLearningAttendance WHERE IsPresent = 0 And AcademicId = @lAcademicId),0) AS AbsentCount,
		CAST(ISNULL((((SELECT SUM(AcademicId) FROM sAcademic.tOnlineLearningAttendance WHERE IsPresent = 1 And AcademicId = @lAcademicId) / 
		(SELECT SUM(AcademicId) FROM sAcademic.tOnlineLearningAttendance WHERE IsPresent = 0 And AcademicId = @lAcademicId)) * 100 ),0) AS DECIMAL(10,2)) AS PresentPercentage
	
	END
	ELSE IF(LOWER(@Tab) = 'charge')
	BEGIN
		exec sFee.pChargeReceiptListGet @rSourceTypeId=0,@rGuestName=N'*',@rSourceCode=@lCode,@rFromDate=NULL,@rToDate=NULL,@rReceiptBookId=0,@rChargeCategoryId=0,@rOrgId=@rOrgId,@rBatchId=0,@rOrgGroupBatchId=@rOrgGroupBatchId,@rFromNo=0,@rToNo=0,@rOrgGroupId=@lOrgGroupId
	END
	ELSE IF(LOWER(@Tab) = 'siblingdetails')
	BEGIN
		exec sStudent.pSiblingLinkListGet @rStudentId=@rStudentId
	END
	ELSE IF (LOWER(@Tab) = 'teachersubject')
	BEGIN
		SELECT DISTINCT SM.Title AS SubjectName,
		(SELECT Stuff (( select ',' + Convert(nvarchar(MAX),EM.FirstName + ' ' + EM.LastName)
			FROM 
			sAcademic.tTeacherSubjectDivision TSD1
			INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id = TSD1.EmployeeId AND EM.StatusId = 7
			WHERE 
			TSD1.SubjectId = TSD.SubjectId AND TSD1.DivisionId = @lDivisionId
			  FOR XML PATH('')  
			 ),1,1,'')) TeacherName

		FROM 
		sAcademic.tTeacherSubjectDivision TSD
		INNER JOIN sSetup.tSubjectMaster SM ON SM.Id = TSD.SubjectId
		WHERE TSD.DivisionId = @lDivisionId
	END
	ELSE IF (LOWER(@Tab) = 'activitybehaviour')
	BEGIN		
		SELECT
			convert(varchar,isnull(A.FromDate,''),103) AS FromDate,
			convert(varchar,isnull(A.ToDate,''),103) AS ToDate,
			isnull (A.Title,'') AS Title,
			isnull( A.Remark,'') AS Remark				
		FROM 
			sActivity.tActivity A 
			INNER JOIN sActivity.tActivityTypeMaster ATM ON ATM.Id=A.ActivityTypeId
			INNER JOIN sStudent.vStudentAcademic SA ON SA.StudentId=@rStudentId AND SA.BatchId = @rBatchId
			INNER JOIN sActivity.tActivityParticipant AP ON AP.ActivityId=A.Id AND AP.SourceTypeId=2003
		WHERE 
			AP.SourceTypeId = 2003 AND AP.SourceId = @rStudentId  AND A.BatchId=@rBatchId
					
		SELECT 
			convert(varchar,isnull(B.BehaviourDate,''),103) AS BehaviourDate,
			isnull (BTM.Title,'') AS BehaviourType,
			isnull( B.Title,'') AS BehaviourDetails,
			isnull(B.Remark,'') AS Remark
		FROM 
			sCommunication.tBehaviour B
			 INNER JOIN sCommunication.tBehaviourTypeMaster BTM
			 ON B.BehaviourTypeId=BTM.Id
			 INNER JOIN sStudent.vStudentAcademic SA
			 ON SA.AcademicId=B.AcademicId      
		WHERE 
			SA.OrgGroupBatchId=@rOrgGroupBatchId AND SA.AcademicId=@lAcademicId
	END
END
GO
PRINT N'Altering Procedure [sTimetable].[pDeleteTimeTable]...';


GO
ALTER PROCEDURE [sTimetable].[pDeleteTimeTable]

	  @rSelectScreen nvarchar(100),
	  @rTimeTableSchemaId int

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
---
BEGIN
	IF(@rSelectScreen='Proxy Setting')
	BEGIN
		DELETE FROM sTimetable.tProxySetting WHERE TimeTableSchemaId=@rTimeTableSchemaId
		SELECT 1 AS Result
	END

	ELSE IF(@rSelectScreen='Assign Time Table Time')
	BEGIN
		IF EXISTS(SELECT * FROM sTimetable.tProxySetting WHERE TimeTableSchemaId=@rTimeTableSchemaId)
		BEGIN
			SELECT 101 AS Result
			RETURN;
		END
		DELETE FROM sTimetable.tTimeTableTime WHERE TimeTableSchemaId=@rTimeTableSchemaId
		SELECT 1 AS Result
	END

	ELSE IF(@rSelectScreen='Time Table')
	BEGIN
		IF EXISTS(SELECT * FROM sTimetable.tTimeTableTime WHERE TimeTableSchemaId=@rTimeTableSchemaId)
		BEGIN
			SELECT 102 AS Result
			RETURN;
		END
		DELETE FROM sTimetable.tTimeTable WHERE TimeTableSchemaId=@rTimeTableSchemaId
		SELECT 1 AS Result
	END

	ELSE IF (@rSelectScreen='Teacher Work Load')
	BEGIN
		IF EXISTS(SELECT * FROM sTimetable.tTimeTable WHERE TimeTableSchemaId=@rTimeTableSchemaId)
		BEGIN
			SELECT 103 AS Result
			RETURN;
		END
		DELETE FROM sTimetable.tTeacherWorkLoad WHERE TimeTableSchemaId=@rTimeTableSchemaId
		SELECT 1 AS Result
	END

	ELSE IF (@rSelectScreen='Division Work Load')
	BEGIN
		IF EXISTS(SELECT * FROM sTimetable.tTeacherWorkLoad WHERE TimeTableSchemaId=@rTimeTableSchemaId)
		BEGIN
			SELECT 104 AS Result
			RETURN;
		END
		DELETE FROM sTimetable.tDivisionWorkLoad WHERE TimeTableSchemaId=@rTimeTableSchemaId
		SELECT 1 AS Result
	END

	ELSE IF (@rSelectScreen='Time Setup')
	BEGIN
		IF EXISTS(SELECT * FROM sTimetable.tDivisionWorkLoad WHERE TimeTableSchemaId=@rTimeTableSchemaId)
		BEGIN
			SELECT 105 AS Result
			RETURN;
		END
		DELETE FROM sTimetable.tTimeSetup WHERE TimeTableSchemaId=@rTimeTableSchemaId
		SELECT 1 AS Result
	END
END
GO
PRINT N'Altering Procedure [sTimetable].[pRptDivisionTimeTableGet]...';


GO
ALTER PROCEDURE [sTimetable].[pRptDivisionTimeTableGet]

	  --@rBuilder1 nvarchar(max)='',
	  --@rBuilder2 nvarchar(max)='', 
	  @rBatchId int,
	  @rClassId int,
	  @rDivisionId int,
	  @rEmployeeId bigint,
	  @rTimeTableSchemaId int,
	  @rReportId int=0,
	  @rDate Date='',
	  @rOrgId int=0,
	  @rDisplayWithBreak bit = 1, -- Mantis : 0029066
	  @rDisplayWithTeacher bit = 1 
	  
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON 

BEGIN   
  IF(@rReportId=10166) -- Teacherwise
  BEGIN
  SELECT

	A.TimeTableID,
	A.DivisionName,
	
	A.EmployeeId,
	A.SubjectId,
	
	CASE WHEN A.EmployeeId=-1 THEN '###' WHEN A.EmployeeId=-2 THEN '***' ELSE A.EmployeeName END  AS EmployeeName,
	CASE WHEN A.SubjectId=-1 THEN '###' WHEN A.SubjectId=-2 THEN '***' ELSE A.Subject END  AS Subject,
	--A.Subject,
	A.DivisionId,
	ISNULL(L.Title,'') AS DayName,
	ISNULL(L.DayId,0) AS DayId,
	ISNULL(L.LectureNumber,'') AS LactureNumber,
	--ISNULL(A.DayName,'') AS DayName,
	--ISNULL(A.DayId,0) AS DayId,
	--ISNULL(A.LactureNumber,'') AS LactureNumber,
	A.DayLacture,
	A.ClassId,
	A.ClassDivisionName,
	A.DivisionOrderIndex,
	A.Code,
	A.TimeTableDetail,
	0 As IsPresent,
	'' As WeekOffs,
	CASE WHEN EXISTS (SELECT 1 FROM sTimetable.tTimeTableSchema TS INNER JOIN sTimetable.tTimeTable TT ON TT.TimeTableSchemaId = TS.Id WHERE TS.IsDisplayPeriodTime = 1 AND TS.Id = @rTimeTableSchemaId) THEN A.FromTime ELSE '' END As FromTime,
	CASE WHEN EXISTS (SELECT 1 FROM sTimetable.tTimeTableSchema TS INNER JOIN sTimetable.tTimeTable TT ON TT.TimeTableSchemaId = TS.Id WHERE TS.IsDisplayPeriodTime = 1 AND TS.Id = @rTimeTableSchemaId) THEN A.ToTime ELSE '' END As ToTime,
	ISNULL(IsDiplayPeriodTime,0) As IsDiplayPeriodTime,
	'' as DivisionIncharge,
	IsBreak,
	IsBreakBefore,
	EmployeeSubject,
	 ClassSubject,
	'' AS EmployeeSNSubject,
	ISNULL(Convert(smallint,(select Isnull(max(cast(IsBreak as smallint)),0)*2+ISNULL(max(cast(IsBreakBefore as smallint)),0)*1
			From sTimetable.tTimeTableTime
			where TimeTableSchemaId=@rTimeTableSchemaId AND LectureNumber=A.LactureNumber
			Group by TimeTableSchemaId,LectureNumber)),0) AS HideBreak ,
	'' AS SubjectEmployeeSN,			--add for 27992 mantis
	'' AS SubjectName, --#Start Mantis : 0029066
	Convert(bit,0) AS DisplayWithBreak,
	Convert(bit,0) AS DisplayWithTeacher --#End Mantis : 0029066

  FROM
(
	SELECT 
	--@rBuilder1 AS Builder1,
	--@rBuilder2 AS Builder2,	 
	TT.Id AS TimeTableID,
	ISNULL(DV.Title,'') AS DivisionName,
	ISNULL(EmployeeId,0) AS EmployeeId,
	ISNULL(SubjectId,0) AS SubjectId,

	ISNULL(Em.FirstName +'  '+Em.LastName,'')  AS EmployeeName,
	--ISNULL(Em.FirstName,'')  AS EmployeeName,  
	ISNULL(SM.Title,'') AS Subject,
	ISNULL(TT.DivisionId,0) AS DivisionId,
	ISNULL(DM.Title,'') AS DayName,
	ISNULL(TT.DayId,0) AS DayId,
	ISNULL(TT.LectureNumber,'') AS LactureNumber,
	ISNULL(DM.Title,'') +'-'+ISNULL(convert(nvarchar(4),TT.LectureNumber),'') AS DayLacture,
	ISNULL(DV.ClassId,0) AS ClassId,
	ISNULL(CM.DisplayTitle,'')+'-'+ISNULL(DV.Title,'') as ClassDivisionName,
	ISNULL(DV.OrderIndex,0) As DivisionOrderIndex,
	ISNULL(SM.Code,'') AS Code,
	--'' AS TimeTableDetail,
	--(ISNULL(CM.DisplayTitle,'')+'-'+ISNULL(DV.Title,'') + ISNULL(SM.Title,'')) AS TimeTableDetail
	ISNULL([sTimetable].[fTimeTableDivisionGet](TT.TimeTableSchemaId,TT.Id,TT.EmployeeId,TT.DayId,TT.LectureNumber,0),'') AS TimeTableDetail,
	ISNULL(TTM.FromTime,0) As FromTime,
	ISNULL(TTM.ToTime,0) As ToTime,
	ISNULL(TS.IsDisplayPeriodTime,0) As IsDiplayPeriodTime,

	--GetBreak
	CASE WHEN 
	(SELECT ISNULL(IsBreak,0) FROM sTimetable.tTimeTableTime WHERE TimeTableSchemaId = TT.TimeTableSchemaId 
	AND DayId = TT.DayId AND DivisionId = TT.DivisionId AND LectureNumber = TT.LectureNumber AND IsBreak = 1) = 1 
	THEN (SELECT ISNULL(IsBreak,0) FROM sTimetable.tTimeTableTime WHERE TimeTableSchemaId = TT.TimeTableSchemaId 
	AND DayId = TT.DayId AND DivisionId = TT.DivisionId AND LectureNumber = TT.LectureNumber AND IsBreak = 1)
	ELSE ISNULL(TT.IsBreak,0) END AS IsBreak,

	--GetBreakBefore
	CASE WHEN 
	(SELECT ISNULL(IsBreakBefore,0) FROM sTimetable.tTimeTableTime WHERE TimeTableSchemaId = TT.TimeTableSchemaId 
	AND DayId = TT.DayId AND DivisionId = TT.DivisionId AND LectureNumber = TT.LectureNumber AND IsBreakBefore = 1) = 1 
	THEN (SELECT ISNULL(IsBreakBefore,0) FROM sTimetable.tTimeTableTime WHERE TimeTableSchemaId = TT.TimeTableSchemaId 
	AND DayId = TT.DayId AND DivisionId = TT.DivisionId AND LectureNumber = TT.LectureNumber AND IsBreakBefore = 1)
	ELSE ISNULL(TT.IsBreakBefore,0) END AS IsBreakBefore,
	
	STUFF((
			SELECT ', ' +  ISNULL(ISNULL(Em1.FirstName +'  '+Em1.LastName,'') +' - '+SM1.Title,'')
			FROM sTimetable.tTimeTable T1 
			inner join sHrm.tEmployeeMaster EM1 on EM1.Id=T1.EmployeeId
			INNER JOIN sSetup.tSubjectMaster SM1 ON SM1.Id=T1.SubjectId
			where T1.DivisionId=TT.DivisionId 
			AND TT.LectureNumber=T1.LectureNumber 
			AND TT.DayId=T1.DayId and TT.TimeTableSchemaId=T1.TimeTableSchemaId  
			--AND timetableid in ()
			FOR XML PATH('')
			), 1, 1, '') EmployeeSubject,
	[sCommon].[fXMLTagsReplaceReverse](STUFF((
		SELECT ',<br>' +  ISNULL(VBCD1.ClassDivisionName +' - '+SM1.Title,'')
				FROM sTimetable.tTimeTable T1 
				INNER JOIN sSetup.tSubjectMaster SM1 ON SM1.Id=T1.SubjectId
					INNER JOIN sSetup.vClassDivision VBCD1 ON VBCD1.DivisionId=T1.DivisionId
				where T1.EmployeeId=TT.EmployeeId 
				AND TT.LectureNumber=T1.LectureNumber 
				AND TT.DayId=T1.DayId and TT.TimeTableSchemaId=T1.TimeTableSchemaId  
				--AND timetableid in ()
				FOR XML PATH('')
				), 1, 11, ''))  ClassSubject

	FROM 
	sTimetable.tTimeTable TT	
	INNER JOIN sSetup.tSubjectMaster SM ON SM.Id = TT.SubjectId 
	LEFT JOIN sHrm.tEmployeeMaster Em ON Em.Id = TT.EmployeeId
	LEFT JOIN sCommon.tDayMaster DM ON DM.Id = TT.DayId
	LEFT JOIN sSetup.tDivisionMaster DV ON DV.Id = TT.DivisionId
	LEFT JOIN sSetup.tClassMaster CM ON CM.Id = DV.ClassId
	LEFT JOIN sTimetable.tTimeTableTime TTM ON TTM.TimeTableSchemaId=TT.TimeTableSchemaId AND TTM.DayId = DM.Id AND TTM.DivisionId = TT.DivisionId AND TTM.LectureNumber = TT.LectureNumber
	INNER JOIN sTimetable.tTimeTableSchema TS ON TS.Id = TT.TimeTableSchemaId
	WHERE (ClassId = @rClassId OR @rClassId=0)
	  AND (TT.DivisionId = @rDivisionId OR @rDivisionId=0)	
	  AND (TT.EmployeeId=@rEmployeeId OR @rEmployeeId=0)
	  AND TT.TimeTableSchemaId=@rTimeTableSchemaId
	  AND TT.EmployeeId <> 0
	  
	  UNION ALL
	  
	  
	  
	  	SELECT 
	--@rBuilder1 AS Builder1,
	--@rBuilder2 AS Builder2,	 
	TT.Id AS TimeTableID,
	ISNULL(DV.Title,'') AS DivisionName,
	ISNULL(TTD.EmployeeId,0) AS EmployeeId,
	ISNULL(TTD.SubjectId,0) AS SubjectId,

	ISNULL(Em.FirstName +'  '+Em.LastName,'')  AS EmployeeName,
	--ISNULL(Em.FirstName,'')  AS EmployeeName,  
	ISNULL(SM.Title,'') AS Subject,
	ISNULL(TT.DivisionId,0) AS DivisionId,
	ISNULL(DM.Title,'') AS DayName,
	ISNULL(TT.DayId,0) AS DayId,
	ISNULL(TT.LectureNumber,'') AS LactureNumber,
	ISNULL(DM.Title,'') +'-'+ISNULL(convert(nvarchar(4),TT.LectureNumber),'') AS DayLacture,
	ISNULL(DV.ClassId,0) AS ClassId,
	ISNULL(CM.DisplayTitle,'')+'-'+ISNULL(DV.Title,'') as ClassDivisionName,
	ISNULL(DV.OrderIndex,0) As DivisionOrderIndex,
	ISNULL(SM.Code,'') AS Code,
	--(ISNULL(CM.DisplayTitle,'')+'-'+ISNULL(DV.Title,'') + ISNULL(SM.Title,'')) AS TimeTableDetail
	'' AS TimeTableDetail,
	ISNULL(TTM.FromTime,0) As FromTime,
	ISNULL(TTM.ToTime,0) As ToTime,
	ISNULL(TS.IsDisplayPeriodTime,0) As IsDiplayPeriodTime,
	0 AS IsBreak,
	0 AS IsBreakBefore,
	STUFF((
			SELECT ', ' +  ISNULL(ISNULL(Em1.FirstName +'  '+Em1.LastName,'') +' - '+SM1.Title,'')
			FROM sTimetable.tTimeTable T1 
			inner join sHrm.tEmployeeMaster EM1 on EM1.Id=T1.EmployeeId
			INNER JOIN sSetup.tSubjectMaster SM1 ON SM1.Id=T1.SubjectId
			where T1.DivisionId=TT.DivisionId 
			AND TT.LectureNumber=T1.LectureNumber 
			AND TT.DayId=T1.DayId and TT.TimeTableSchemaId=T1.TimeTableSchemaId  
			--AND timetableid in ()
			FOR XML PATH('')
			), 1, 1, '') EmployeeSubject ,
	[sCommon].[fXMLTagsReplaceReverse](STUFF((
		SELECT ',<br>' +  ISNULL(VBCD1.ClassDivisionName +' - '+SM1.Title,'')
				FROM sTimetable.tTimeTable T1 
				INNER JOIN sSetup.tSubjectMaster SM1 ON SM1.Id=T1.SubjectId
					INNER JOIN sSetup.vClassDivision VBCD1 ON VBCD1.DivisionId=T1.DivisionId
				where T1.EmployeeId=TT.EmployeeId 
				AND TT.LectureNumber=T1.LectureNumber 
				AND TT.DayId=T1.DayId and TT.TimeTableSchemaId=T1.TimeTableSchemaId  
				--AND timetableid in ()
				FOR XML PATH('')
				), 1, 11, ''))  ClassSubject

	FROM 
	sTimetable.tTimeTable TT
	INNER JOIN 	sTimetable.tTimeTableDetail TTD ON TTD.TimetableId = TT.Id
	INNER JOIN sSetup.tSubjectMaster SM ON SM.Id = TTD.SubjectId 
	INNER JOIN sHrm.tEmployeeMaster Em ON Em.Id = TTD.EmployeeId
	LEFT JOIN sCommon.tDayMaster DM ON DM.Id = TT.DayId
	LEFT JOIN sSetup.tDivisionMaster DV ON DV.Id = TT.DivisionId
	LEFT JOIN sSetup.tClassMaster CM ON CM.Id = DV.ClassId
	LEFT JOIN sTimetable.tTimeTableTime TTM ON TTM.TimeTableSchemaId=TT.TimeTableSchemaId AND TTM.DayId = DM.Id AND TTM.DivisionId = TT.DivisionId AND TTM.LectureNumber = TT.LectureNumber
	INNER JOIN sTimetable.tTimeTableSchema TS ON TS.Id = TT.TimeTableSchemaId 

	WHERE (ClassId = @rClassId OR @rClassId=0)
	  AND (TT.DivisionId = @rDivisionId OR @rDivisionId=0)	
	  AND (TTD.EmployeeId=@rEmployeeId OR @rEmployeeId=0)
	  AND TT.TimeTableSchemaId=@rTimeTableSchemaId
	 
	  
	  --ORDER BY DV.OrderIndex
	  )
	  A
			INNER JOIN (SELECT DISTINCT DayId,LectureNumber,DM.title  FROM sTimetable.tTimeTable
			INNER JOIN sCommon.tDayMaster DM ON DM.Id = DayId
			WHERE TimeTableSchemaId=@rTimeTableSchemaId  ) L
			ON A.LactureNumber = L.LectureNumber AND A.DayId = L.DayId

	END
ELSE IF(@rReportId = 30661) --- Absent Teacher Divisionwise
  BEGIN
	  SELECT

	A.TimeTableID,
	A.DivisionName,
	
	A.EmployeeId,
	A.SubjectId,
	
	CASE WHEN A.EmployeeId=-1 THEN '###' WHEN A.EmployeeId=-2 THEN '***' ELSE A.EmployeeName END  AS EmployeeName,
	CASE WHEN A.SubjectId=-1 THEN '###' WHEN A.SubjectId=-2 THEN '***' ELSE A.Subject END  AS Subject,
	--A.Subject,
	A.DivisionId,
	ISNULL(L.Title,'') AS DayName,
	ISNULL(L.DayId,0) AS DayId,
	ISNULL(L.LectureNumber,'') AS LactureNumber,
	--ISNULL(A.DayName,'') AS DayName,
	--ISNULL(A.DayId,0) AS DayId,
	--ISNULL(A.LactureNumber,'') AS LactureNumber,
	A.DayLacture,
	A.ClassId,
	ISNULL(A.ClassDivisionName,'')AS ClassDivisionName,
	A.DivisionOrderIndex,
	A.Code,
	A.TimeTableDetail,
	A.IsPresent,
	'' As WeekOffs,
	0 As FromTime,
	0 As ToTime,
	'' as DivisionIncharge,
	A.EmployeeSubject,
	'' as ClassSubject,
	'' AS SubjectEmployeeSN,		--add for 27992 mantis
	'' AS SubjectName, --#Start Mantis : 0029066
	Convert(bit,0) AS DisplayWithBreak,
	Convert(bit,0) AS DisplayWithTeacher --#End Mantis : 0029066
  FROM
(
	SELECT 
	--@rBuilder1 AS Builder1,
	--@rBuilder2 AS Builder2,	 
	TT.Id AS TimeTableID,
	ISNULL(DV.Title,'') AS DivisionName,
	ISNULL(EAR.EmployeeId,0) AS EmployeeId,
	ISNULL(SubjectId,0) AS SubjectId,

	[sHrm].[fEmployeeNameGet](ISNULL(Em.FirstName,'') , ISNULL(Em.MiddleName,''), ISNULL(Em.LastName,''),ISNULL(OM.EmployeeNameFormatId,1)) AS EmployeeName,
	--ISNULL(Em.FirstName +'  '+Em.LastName,'')  AS EmployeeName,
	--ISNULL(Em.FirstName,'')  AS EmployeeName,  
	ISNULL(SM.Title,'') AS Subject,
	ISNULL(TT.DivisionId,0) AS DivisionId,
	ISNULL(DM.Title,'') AS DayName,
	ISNULL(TT.DayId,0) AS DayId,
	ISNULL(TT.LectureNumber,'') AS LactureNumber,
	ISNULL(DM.Title,'') +'-'+ISNULL(convert(nvarchar(4),TT.LectureNumber),'') AS DayLacture,
	ISNULL(DV.ClassId,0) AS ClassId,
	ISNULL(CM.DisplayTitle,'')+'-'+ISNULL(DV.Title,'') as ClassDivisionName,
	ISNULL(DV.OrderIndex,0) As DivisionOrderIndex,
	ISNULL(SM.Code,'') AS Code,
	'' AS TimeTableDetail,
	ISNULL(EAR.IsPresent,0) AS IsPresent,
	[sCommon].[fXMLTagsReplaceReverse](STUFF((
			SELECT ',<br>' + case when ISNULL(EAR1.IsPresent,0)=0 then   ISNULL(ISNULL([sHrm].[fEmployeeNameGet](ISNULL(Em1.FirstName,'') , ISNULL(Em1.MiddleName,''), ISNULL(Em1.LastName,''),ISNULL(OM1.EmployeeNameFormatId,1)),'') +' <br><b> '+SM1.Title+'</b>','') else '' end
			FROM sTimetable.tTimeTable T1 
			Left join sHrm.tEmployeeMaster EM1 on EM1.Id=T1.EmployeeId
			left JOIN sSetup.tSubjectMaster SM1 ON SM1.Id=T1.SubjectId
			LEFT JOIN sSetup.tOrganizationMaster OM1 ON OM1.Id = Em1.OrgID
			RIGHT JOIN sHrm.tEmployeeAttendanceRegister EAR1 ON EAR1.EmployeeId = Em1.Id
			where T1.DivisionId=TT.DivisionId 
			AND T1.LectureNumber=TT.LectureNumber 
			AND T1.DayId=TT.DayId and T1.TimeTableSchemaId=TT.TimeTableSchemaId  
			AND (EAR1.AttendanceDate = @rDate OR @rDate = '')
			AND (T1.DayId = (DATEPART(weekday,@rDate)) OR @rDate = '') 
			--AND timetableid in ()
			FOR XML PATH('')
			), 1, 11, '')) EmployeeSubject
	--(ISNULL(CM.DisplayTitle,'')+'-'+ISNULL(DV.Title,'') + ISNULL(SM.Title,'')) AS TimeTableDetail
	--ISNULL([sTimetable].[fTimeTableDivisionGet](TT.TimeTableSchemaId,TT.Id,TT.EmployeeId,TT.DayId,TT.LectureNumber),'') AS TimeTableDetail
	FROM 
	sTimetable.tTimeTable TT	 
	LEFT JOIN sSetup.tSubjectMaster SM ON SM.Id = TT.SubjectId 
	LEFT JOIN sHrm.tEmployeeMaster Em ON Em.Id = TT.EmployeeId
	LEFT JOIN sCommon.tDayMaster DM ON DM.Id = TT.DayId
	LEFT JOIN sSetup.tDivisionMaster DV ON DV.Id = TT.DivisionId
	LEFT JOIN sSetup.tClassMaster CM ON CM.Id = DV.ClassId
	LEFT JOIN sSetup.tOrganizationMaster OM ON OM.Id = Em.OrgID
	RIGHT JOIN sHrm.tEmployeeAttendanceRegister EAR ON EAR.EmployeeId = Em.Id

	WHERE (ClassId = @rClassId OR @rClassId=0)
	  AND (TT.DivisionId = @rDivisionId OR @rDivisionId=0)	
	  AND (TT.EmployeeId=@rEmployeeId OR @rEmployeeId=0)
	  AND TT.TimeTableSchemaId=@rTimeTableSchemaId
	  AND (EAR.AttendanceDate = @rDate OR @rDate = '')
	  AND (TT.DayId = (DATEPART(weekday,@rDate)) OR @rDate = '')

	  UNION ALL
	  
	  
	  
	  	SELECT 
	--@rBuilder1 AS Builder1,
	--@rBuilder2 AS Builder2,	 
	TT.Id AS TimeTableID,
	ISNULL(DV.Title,'') AS DivisionName,
	ISNULL(TTD.EmployeeId,0) AS EmployeeId,
	ISNULL(TTD.SubjectId,0) AS SubjectId,

	[sHrm].[fEmployeeNameGet](ISNULL(Em.FirstName,'') , ISNULL(Em.MiddleName,''), ISNULL(Em.LastName,''),ISNULL(OM.EmployeeNameFormatId,1)) AS EmployeeName,
	--ISNULL(Em.FirstName +'  '+Em.LastName,'')  AS EmployeeName,
	--ISNULL(Em.FirstName,'')  AS EmployeeName,  
	ISNULL(SM.Title,'') AS Subject,
	ISNULL(TT.DivisionId,0) AS DivisionId,
	ISNULL(DM.Title,'') AS DayName,
	ISNULL(TT.DayId,0) AS DayId,
	ISNULL(TT.LectureNumber,'') AS LactureNumber,
	ISNULL(DM.Title,'') +'-'+ISNULL(convert(nvarchar(4),TT.LectureNumber),'') AS DayLacture,
	ISNULL(DV.ClassId,0) AS ClassId,
	ISNULL(CM.DisplayTitle,'')+'-'+ISNULL(DV.Title,'') as ClassDivisionName,
	ISNULL(DV.OrderIndex,0) As DivisionOrderIndex,
	ISNULL(SM.Code,'') AS Code,
	--(ISNULL(CM.DisplayTitle,'')+'-'+ISNULL(DV.Title,'') + ISNULL(SM.Title,'')) AS TimeTableDetail
	ISNULL([sTimetable].[fTimeTableDivisionGet](TT.TimeTableSchemaId,TT.Id,TTD.EmployeeId,TT.DayId,TT.LectureNumber,0),'') AS TimeTableDetail,
	ISNULL(EAR.IsPresent,'') As IsPresent,
	[sCommon].[fXMLTagsReplaceReverse](STUFF((
			SELECT   ',<br>' +case when ISNULL(EAR1.IsPresent,0)=0 then ISNULL(ISNULL([sHrm].[fEmployeeNameGet](ISNULL(Em1.FirstName,'') , ISNULL(Em1.MiddleName,''), ISNULL(Em1.LastName,''),ISNULL(OM1.EmployeeNameFormatId,1)),'') +' <br><b> '+SM1.Title+'</b>','') else '' end
			FROM sTimetable.tTimeTable T1 
			inner join sHrm.tEmployeeMaster EM1 on EM1.Id=T1.EmployeeId
			INNER JOIN sSetup.tSubjectMaster SM1 ON SM1.Id=T1.SubjectId
			LEFT JOIN sSetup.tOrganizationMaster OM1 ON OM1.Id = Em1.OrgID
			LEFT JOIN sHrm.tEmployeeAttendanceRegister EAR1 ON EAR1.EmployeeId = Em1.Id
			where T1.DivisionId=TT.DivisionId 
			AND T1.LectureNumber=TT.LectureNumber 
			AND T1.DayId=TT.DayId and T1.TimeTableSchemaId=TT.TimeTableSchemaId  
			AND (EAR1.AttendanceDate = @rDate OR @rDate = '')
			AND (T1.DayId = (DATEPART(weekday,@rDate)) OR @rDate = '') 
			--AND timetableid in ()
			FOR XML PATH('')
			), 1, 11, '')) EmployeeSubject
	FROM 
	sTimetable.tTimeTable TT
	INNER JOIN 	sTimetable.tTimeTableDetail TTD ON TTD.TimetableId = TT.Id
	INNER JOIN sSetup.tSubjectMaster SM ON SM.Id = TTD.SubjectId 
	INNER JOIN sHrm.tEmployeeMaster Em ON Em.Id = TTD.EmployeeId
	LEFT JOIN sCommon.tDayMaster DM ON DM.Id = TT.DayId
	LEFT JOIN sSetup.tDivisionMaster DV ON DV.Id = TT.DivisionId
	LEFT JOIN sSetup.tClassMaster CM ON CM.Id = DV.ClassId
	LEFT JOIN sSetup.tOrganizationMaster OM ON OM.Id = Em.OrgID
	LEFT JOIN sHrm.tEmployeeAttendanceRegister EAR ON EAR.EmployeeId = Em.Id

	WHERE (ClassId = @rClassId OR @rClassId=0)
	  AND (TT.DivisionId = @rDivisionId OR @rDivisionId=0)	
	  AND (TTD.EmployeeId=@rEmployeeId OR @rEmployeeId=0)
	  AND TT.TimeTableSchemaId=@rTimeTableSchemaId
	  AND (EAR.AttendanceDate = @rDate OR @rDate = '')
	  AND (TT.DayId = (DATEPART(weekday,@rDate)) OR @rDate = '') 
	  
	  --ORDER BY DV.OrderIndex
	  )
	  A
			INNER JOIN (SELECT DISTINCT DayId,LectureNumber,DM.title  FROM sTimetable.tTimeTable
			INNER JOIN sCommon.tDayMaster DM ON DM.Id = DayId
			
			WHERE TimeTableSchemaId=@rTimeTableSchemaId ) L
			ON A.LactureNumber = L.LectureNumber AND A.DayId = L.DayId

	END
ELSE IF(@rReportId = 30925) --TeacherTimeTable_2
   BEGIN
   SELECT

	A.TimeTableID,
	A.DivisionName,
	A.EmployeeId,
	A.SubjectId,
	CASE WHEN A.EmployeeId=-1 THEN '###' WHEN A.EmployeeId=-2 THEN '***' ELSE A.EmployeeName END As EmployeeName,
	CASE WHEN A.SubjectId=-1 THEN '###' WHEN A.SubjectId=-2 THEN '***' ELSE A.Subject END  AS Subject,
	--A.Subject,
	A.DivisionId,
	--ISNULL(L.Title,'') AS DayName,
	--ISNULL(L.DayId,0) AS DayId,
	--ISNULL(L.LectureNumber,'') AS LactureNumber,
	ISNULL(A.DayName,'') AS DayName,
	ISNULL(A.DayId,0) AS DayId,
	ISNULL(A.LactureNumber,'') AS LactureNumber,
	A.DayLacture,
	A.ClassId,
	A.ClassDivisionName,
	A.DivisionOrderIndex,
	A.Code,
	[sTimetable].[fTimeTableDetailGet](A.TimeTableID,1) AS TimeTableDetail,
	0 AS IsPresent,
	A.WeekOffs,
	CASE WHEN EXISTS (SELECT 1 FROM sTimetable.tTimeTableSchema TS INNER JOIN sTimetable.tTimeTable TT ON TT.TimeTableSchemaId = TS.Id WHERE TS.IsDisplayPeriodTime = 1 AND TS.Id = @rTimeTableSchemaId) THEN A.FromTime ELSE '' END As FromTime,
	CASE WHEN EXISTS (SELECT 1 FROM sTimetable.tTimeTableSchema TS INNER JOIN sTimetable.tTimeTable TT ON TT.TimeTableSchemaId = TS.Id WHERE TS.IsDisplayPeriodTime = 1 AND TS.Id = @rTimeTableSchemaId) THEN A.ToTime ELSE '' END As ToTime,
	ISNULL(IsDiplayPeriodTime,0) As IsDiplayPeriodTime,
	DivisionIncharge,
	'' AS EmployeeSubject,
	ClassSubject,
	'' AS SubjectEmployeeSN,		--add for 27992 mantis
	'' AS SubjectName, --#Start Mantis : 0029066
	Convert(bit,0) AS DisplayWithBreak,
	Convert(bit,0) AS DisplayWithTeacher --#End Mantis : 0029066
FROM
(
	SELECT 
	--@rBuilder1 AS Builder1,
	--@rBuilder2 AS Builder2,	 
	TT.Id AS TimeTableID,
	ISNULL(DV.Title,'') AS DivisionName,
	ISNULL(TT.EmployeeId,0) AS EmployeeId,
	ISNULL(SubjectId,0) AS SubjectId,
	[sHrm].[fEmployeeNameGet](ISNULL(EM.FirstName,'') , ISNULL(EM.MiddleName,''), ISNULL(EM.LastName,''),ISNULL(OM.EmployeeNameFormatId,1)) AS EmployeeName,
	--ISNULL(EM.LastName+' '+EM.FirstName,'')  AS EmployeeName,
	ISNULL(SM.Title,'') AS Subject,
	ISNULL(TT.DivisionId,0) AS DivisionId,
	ISNULL(DM.Title,'') AS DayName,
	ISNULL(TT.DayId,0) AS DayId,
	ISNULL(TT.LectureNumber,'') AS LactureNumber,
	ISNULL(DM.Title,'') +'-'+ISNULL(convert(nvarchar(4),TT.LectureNumber),'') AS DayLacture,
	ISNULL(DV.ClassId,0) AS ClassId,
	ISNULL(CM.DisplayTitle,'')+'-'+ISNULL(DV.Title,'') as ClassDivisionName,
	ISNULL(DV.OrderIndex,0) As DivisionOrderIndex,
	ISNULL(SM.Code,'') AS Code,
	ISNULL(TTS.WeekOffs,'') As WeekOffs,
	ISNULL(TTM.FromTime,'') As FromTime,
	ISNULL(TTM.ToTime,'') As ToTime,
	ISNULL(TS.IsDisplayPeriodTime,0) As IsDiplayPeriodTime,
	(SELECT ISNULL(EM.FirstName+' '+EM.LastName,'') FROM sHrm.tEmployeeMaster EM INNER JOIN sSetup.tDivisionMaster DIE ON DIE.InchargeEmployeeId = EM.Id  WHERE DIE.Id = DV.Id) as DivisionIncharge,
	[sCommon].[fXMLTagsReplaceReverse](STUFF((
		SELECT ',<br>' +  ISNULL(VBCD1.ClassDivisionName +'<br><b>'+SM1.Title+'</b>','')
				FROM sTimetable.tTimeTable T1 
				INNER JOIN sSetup.tSubjectMaster SM1 ON SM1.Id=T1.SubjectId
					INNER JOIN sSetup.vClassDivision VBCD1 ON VBCD1.DivisionId=T1.DivisionId
				where T1.EmployeeId=TT.EmployeeId 
				AND TT.LectureNumber=T1.LectureNumber 
				AND TT.DayId=T1.DayId and TT.TimeTableSchemaId=T1.TimeTableSchemaId  
				--AND timetableid in ()
				FOR XML PATH('')
				), 1, 11, ''))  ClassSubject
	FROM 
	sTimetable.tTimeTable TT  
	LEFT JOIN sSetup.tSubjectMaster SM ON SM.Id = TT.SubjectId 
	INNER JOIN sHrm.tEmployeeMaster Em ON Em.Id = TT.EmployeeId
	LEFT JOIN sCommon.tDayMaster DM ON DM.Id = TT.DayId
	LEFT JOIN sSetup.tDivisionMaster DV ON DV.Id = TT.DivisionId
	LEFT JOIN sSetup.tClassMaster CM ON CM.Id = DV.ClassId
	LEFT JOIN sTimetable.tTimeTableSchema TTS ON TTS.Id = TT.TimeTableSchemaId
	LEFT JOIN sTimetable.tTimeTableTime TTM ON TTM.TimeTableSchemaId=TT.TimeTableSchemaId AND TTM.DayId = DM.Id AND TTM.DivisionId = TT.DivisionId AND TTM.LectureNumber = TT.LectureNumber AND TTM.IsBreak = 0
	INNER JOIN sTimetable.tTimeTableSchema TS ON TS.Id = TT.TimeTableSchemaId 
	INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = DV.OrgId
	WHERE (ClassId = @rClassId OR @rClassId=0)
	  AND (TT.DivisionId = @rDivisionId OR @rDivisionId=0)	
	  AND (TT.EmployeeId=@rEmployeeId OR @rEmployeeId=0)
	  AND TT.TimeTableSchemaId=@rTimeTableSchemaId
	  AND (TT.DayId = (DATEPART(weekday,@rDate)) OR @rDate = '')
	  AND (OM.Id = @rOrgId OR @rOrgId = 0)
	  --AND (Em.OrgId = @rOrgId OR @rOrgId = 0)
	  )
	  A  ORDER BY A.EmployeeName, A.DivisionOrderIndex,A.DayId, A.LactureNumber
   END
 ELSE
 BEGIN
	SELECT

	A.TimeTableID,
	A.DivisionName,
	A.EmployeeId,
	A.SubjectId,
	CASE WHEN A.EmployeeId=-1 THEN '###' WHEN A.EmployeeId=-2 THEN '***' ELSE A.EmployeeName END As EmployeeName,
	CASE WHEN A.SubjectId=-1 THEN '###' WHEN A.SubjectId=-2 THEN '***' ELSE A.Subject END  AS Subject,
	--A.Subject,
	A.DivisionId,
	--ISNULL(L.Title,'') AS DayName,
	--ISNULL(L.DayId,0) AS DayId,
	--ISNULL(L.LectureNumber,'') AS LactureNumber,
	ISNULL(A.DayName,'') AS DayName,
	ISNULL(A.DayId,0) AS DayId,
	ISNULL(A.LactureNumber,'') AS LactureNumber,
	A.DayLacture,
	A.ClassId,
	A.ClassDivisionName,
	A.DivisionOrderIndex,
	A.Code,
	[sTimetable].[fTimeTableDetailGet](A.TimeTableID,1) AS TimeTableDetail,
	0 AS IsPresent,
	A.WeekOffs,
	CASE WHEN EXISTS (SELECT 1 FROM sTimetable.tTimeTableSchema TS INNER JOIN sTimetable.tTimeTable TT ON TT.TimeTableSchemaId = TS.Id WHERE TS.IsDisplayPeriodTime = 1 AND TS.Id = @rTimeTableSchemaId) THEN A.FromTime ELSE '' END As FromTime,
	CASE WHEN EXISTS (SELECT 1 FROM sTimetable.tTimeTableSchema TS INNER JOIN sTimetable.tTimeTable TT ON TT.TimeTableSchemaId = TS.Id WHERE TS.IsDisplayPeriodTime = 1 AND TS.Id = @rTimeTableSchemaId) THEN A.ToTime ELSE '' END As ToTime,
	ISNULL(IsDiplayPeriodTime,0) As IsDiplayPeriodTime,
	DivisionIncharge,
	IsBreak,
	IsBreakBefore,
	EmployeeSubject,
	ClassSubject,
	EmployeeSNSubject,
	ISNULL(Convert(smallint,(select Isnull(max(cast(IsBreak as smallint)),0)*2+ISNULL(max(cast(IsBreakBefore as smallint)),0)*1
			From sTimetable.tTimeTableTime
			where TimeTableSchemaId=@rTimeTableSchemaId AND LectureNumber=A.LactureNumber
			Group by TimeTableSchemaId,LectureNumber)),0) AS HideBreak,
	A.SubjectEmployeeSN,			--add for 27992 mantis
	A.SubjectName, -- #Start Mantis : 0029066
	@rDisplayWithBreak AS DisplayWithBreak,
	@rDisplayWithTeacher AS DisplayWithTeacher -- #End Mantis : 0029066
FROM
(
	SELECT 
	--@rBuilder1 AS Builder1,
	--@rBuilder2 AS Builder2,	 
	TT.Id AS TimeTableID,
	ISNULL(DV.Title,'') AS DivisionName,
	ISNULL(TT.EmployeeId,0) AS EmployeeId,
	ISNULL(SubjectId,0) AS SubjectId,
	[sHrm].[fEmployeeNameGet](ISNULL(Em.FirstName,'') , ISNULL(Em.MiddleName,''), ISNULL(Em.LastName,''),ISNULL(OM.EmployeeNameFormatId,1)) AS EmployeeName,
	--ISNULL(EM.LastName+' '+EM.FirstName,'')  AS EmployeeName,
	ISNULL(SM.Title,'') AS Subject,
	ISNULL(TT.DivisionId,0) AS DivisionId,
	ISNULL(DM.Title,'') AS DayName,
	ISNULL(TT.DayId,0) AS DayId,
	ISNULL(TT.LectureNumber,'') AS LactureNumber,
	ISNULL(DM.Title,'') +'-'+ISNULL(convert(nvarchar(4),TT.LectureNumber),'') AS DayLacture,
	ISNULL(DV.ClassId,0) AS ClassId,
	ISNULL(CM.DisplayTitle,'')+'-'+ISNULL(DV.Title,'') as ClassDivisionName,
	ISNULL(DV.OrderIndex,0) As DivisionOrderIndex,
	ISNULL(SM.Code,'') AS Code,
	ISNULL(TTS.WeekOffs,'') As WeekOffs,
	ISNULL(TTM.FromTime,'') As FromTime,
	ISNULL(TTM.ToTime,'') As ToTime,
	ISNULL(TS.IsDisplayPeriodTime,0) As IsDiplayPeriodTime,
	(SELECT ISNULL(EM.FirstName+' '+EM.LastName,'') FROM sHrm.tEmployeeMaster EM INNER JOIN sSetup.tDivisionMaster DIE ON DIE.InchargeEmployeeId = EM.Id  WHERE DIE.Id = DV.Id) as DivisionIncharge,

	--GetBreak
	CASE WHEN 
	(SELECT ISNULL(IsBreak,0) FROM sTimetable.tTimeTableTime WHERE TimeTableSchemaId = TT.TimeTableSchemaId 
	AND DayId = TT.DayId AND DivisionId = TT.DivisionId AND LectureNumber = TT.LectureNumber AND IsBreak = 1) = 1 
	THEN (SELECT ISNULL(IsBreak,0) FROM sTimetable.tTimeTableTime WHERE TimeTableSchemaId = TT.TimeTableSchemaId 
	AND DayId = TT.DayId AND DivisionId = TT.DivisionId AND LectureNumber = TT.LectureNumber AND IsBreak = 1)
	ELSE ISNULL(TT.IsBreak,0) END AS IsBreak,

	--GetBreakBefore
	CASE WHEN 
	(SELECT ISNULL(IsBreakBefore,0) FROM sTimetable.tTimeTableTime WHERE TimeTableSchemaId = TT.TimeTableSchemaId 
	AND DayId = TT.DayId AND DivisionId = TT.DivisionId AND LectureNumber = TT.LectureNumber AND IsBreakBefore = 1) = 1 
	THEN (SELECT ISNULL(IsBreakBefore,0) FROM sTimetable.tTimeTableTime WHERE TimeTableSchemaId = TT.TimeTableSchemaId 
	AND DayId = TT.DayId AND DivisionId = TT.DivisionId AND LectureNumber = TT.LectureNumber AND IsBreakBefore = 1)
	ELSE ISNULL(TT.IsBreakBefore,0) END AS IsBreakBefore,
	[sCommon].[fXMLTagsReplaceReverse](STUFF((
			SELECT ',<br>' +  ISNULL(ISNULL([sHrm].[fEmployeeNameGet](ISNULL(Em1.FirstName,'') , ISNULL(Em1.MiddleName,''), ISNULL(Em1.LastName,''),ISNULL(OM1.EmployeeNameFormatId,1)) ,'') +' - '+SM1.Title,'')
			FROM sTimetable.tTimeTable T1 
			inner join sHrm.tEmployeeMaster EM1 on EM1.Id=T1.EmployeeId
			INNER JOIN sSetup.tSubjectMaster SM1 ON SM1.Id=T1.SubjectId
			LEFT JOIN sSetup.tOrganizationMaster OM1 ON OM1.Id = Em1.OrgID
			where T1.DivisionId=TT.DivisionId 
			AND T1.LectureNumber=TT.LectureNumber 
			AND T1.DayId=TT.DayId and T1.TimeTableSchemaId=TT.TimeTableSchemaId  
			--AND timetableid in ()
			FOR XML PATH('')
			), 1, 11, ''))  EmployeeSubject,
	[sCommon].[fXMLTagsReplaceReverse](STUFF((
		SELECT ',<br>' +  ISNULL(VBCD1.ClassDivisionName+'<br><b>' +SM1.Code+'</b>','')
				FROM sTimetable.tTimeTable T1 
				INNER JOIN sSetup.tSubjectMaster SM1 ON SM1.Id=T1.SubjectId
					INNER JOIN sSetup.vClassDivision VBCD1 ON VBCD1.DivisionId=T1.DivisionId
				where T1.EmployeeId=TT.EmployeeId 
				AND TT.LectureNumber=T1.LectureNumber 
				AND TT.DayId=T1.DayId and TT.TimeTableSchemaId=T1.TimeTableSchemaId  
				--AND timetableid in ()
				FOR XML PATH('')
				), 1, 11, '')) ClassSubject,
	STUFF((
			SELECT ', ' +  ISNULL(ISNULL(Em1.ShortName,'') +' - '+SM1.Title,'')
			FROM sTimetable.tTimeTable T1 
			inner join sHrm.tEmployeeMaster EM1 on EM1.Id=T1.EmployeeId
			INNER JOIN sSetup.tSubjectMaster SM1 ON SM1.Id=T1.SubjectId
			where T1.DivisionId=TT.DivisionId 
			AND TT.LectureNumber=T1.LectureNumber 
			AND TT.DayId=T1.DayId and TT.TimeTableSchemaId=T1.TimeTableSchemaId  
			--AND timetableid in ()
			FOR XML PATH('')
			), 1, 1, '') EmployeeSNSubject,

	[sCommon].[fXMLTagsReplaceReverse](STUFF((
			SELECT ', ' +  ISNULL('<b>'+SM1.Title+'</b><br/>'+ISNULL(Em1.ShortName,''),'')
			FROM sTimetable.tTimeTable T1 
			inner join sHrm.tEmployeeMaster EM1 on EM1.Id=T1.EmployeeId
			INNER JOIN sSetup.tSubjectMaster SM1 ON SM1.Id=T1.SubjectId
			where T1.DivisionId=TT.DivisionId 
			AND TT.LectureNumber=T1.LectureNumber 
			AND TT.DayId=T1.DayId and TT.TimeTableSchemaId=T1.TimeTableSchemaId  
			--AND timetableid in ()
			FOR XML PATH('')
			), 1, 1, '')) SubjectEmployeeSN,			--add for 27992 mantis
			[sCommon].[fXMLTagsReplaceReverse](STUFF((
			SELECT ',<br>' +  ISNULL(SM1.Title,'')
			FROM sTimetable.tTimeTable T1 
			inner join sHrm.tEmployeeMaster EM1 on EM1.Id=T1.EmployeeId
			INNER JOIN sSetup.tSubjectMaster SM1 ON SM1.Id=T1.SubjectId
			LEFT JOIN sSetup.tOrganizationMaster OM1 ON OM1.Id = Em1.OrgID
			where T1.DivisionId=TT.DivisionId 
			AND T1.LectureNumber=TT.LectureNumber 
			AND T1.DayId=TT.DayId and T1.TimeTableSchemaId=TT.TimeTableSchemaId  
			--AND timetableid in ()
			FOR XML PATH('')
			), 1, 11, ''))  SubjectName -- #Mantis : 0029066
			

	FROM 
	sTimetable.tTimeTable TT  
	LEFT JOIN sSetup.tSubjectMaster SM ON SM.Id = TT.SubjectId 
	LEFT JOIN sHrm.tEmployeeMaster Em ON Em.Id = TT.EmployeeId
	LEFT JOIN sCommon.tDayMaster DM ON DM.Id = TT.DayId
	LEFT JOIN sSetup.tDivisionMaster DV ON DV.Id = TT.DivisionId
	LEFT JOIN sSetup.tClassMaster CM ON CM.Id = DV.ClassId
	LEFT JOIN sTimetable.tTimeTableSchema TTS ON TTS.Id = TT.TimeTableSchemaId
	LEFT JOIN sTimetable.tTimeTableTime TTM ON TTM.TimeTableSchemaId=TT.TimeTableSchemaId AND TTM.DayId = DM.Id AND TTM.DivisionId = TT.DivisionId AND TTM.LectureNumber = TT.LectureNumber AND TTM.IsBreak = 0	
	INNER JOIN sTimetable.tTimeTableSchema TS ON TS.Id = TT.TimeTableSchemaId 
	INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = DV.OrgId
	WHERE (ClassId = @rClassId OR @rClassId=0)
	  AND (TT.DivisionId = @rDivisionId OR @rDivisionId=0)	
	  AND (TT.EmployeeId=@rEmployeeId OR @rEmployeeId=0)
	  AND TT.TimeTableSchemaId=@rTimeTableSchemaId
	  AND (TT.DayId = (DATEPART(weekday,@rDate)) OR @rDate = '')
	  AND (OM.Id = @rOrgId OR @rOrgId = 0)
	  AND TT.EmployeeId <> 0
	  )
	  A  ORDER BY A.EmployeeName, A.DivisionOrderIndex,A.DayId, A.LactureNumber
		END
END
GO
PRINT N'Altering Procedure [sTimetable].[pTimeTableTimeListGet]...';


GO
ALTER PROCEDURE [sTimetable].[pTimeTableTimeListGet]

		@rBatchId int,
		@rDayIds nvarchar(100)='',
		@rLectureNo smallint,
		@rTimeTableSchemaId int,
		@rOrgId int=0,
		@rDivisionId int=0

	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN

----
	SELECT
		TTT.TimeTableSchemaId AS TimeTableSchemaId,
		TTT.AutoId AS AutoId,
		DV.Title AS DivisionName,
		TTT.DivisionId,
		ISNULL(DM.Title,'') AS DayName,
		ISNULL(TTT.DayId,0) AS DayId,
		ISNULL(TTT.LectureNumber,'') AS LactureNumber,
		ISNULL(DM.Title,'') +'-'+ISNULL(convert(nvarchar(4),TTT.LectureNumber),'') AS DayLacture,
		ISNULL(DV.Code,'') AS ClassDivisionName
		,ISNULL(TTT.FromTime,'') AS FromTime
		,ISNULL(TTT.ToTime,'') AS ToTime

	FROM
		sTimetable.tTimeTableTime TTT
		INNER JOIN sCommon.tDayMaster DM ON DM.Id = TTT.DayId
		INNER JOIN sSetup.tDivisionMaster DV ON DV.Id = TTT.DivisionId

	WHERE
		TTT.TimeTableSchemaId=@rTimeTableSchemaId
		AND (TTT.DayId IN (SELECT CAST(item AS int) FROM  sCommon.fnsplit(@rDayIds,',')) OR (@rDayIds = ''))
		AND ((TTT.LectureNumber = @rLectureNo) OR (@rLectureNo = 0))
		AND ((DV.OrgId=@rOrgId) OR (@rOrgId=0))
		AND ISNULL(TTT.IsBreak,0)=0
		AND ISNULL(TTT.IsBreakBefore,0)=0
		AND ((ISNULL(TTT.DivisionId,0)=@rDivisionId) OR (@rDivisionId=0))
	ORDER BY TTT.LectureNumber
END
GO
PRINT N'Altering Procedure [sWorkflow].[pMyApprovalRequestGet]...';


GO
ALTER  PROCEDURE [sWorkflow].[pMyApprovalRequestGet]
			 @rWorkflowFunctionalityId bigint=0,
			 @rFromDate date=null,
			 @rToDate date=null,
			 @rStatusId int=0,
			 @rCode nvarchar(200) ='',
			 @rUserId bigint = 0,
			 @rUserSourceTypeId int,
			 @rParticipantSourceId bigint = 0,
			 @rApprovalRequestId int = 0
			 

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

	BEGIN
		IF(@rUserSourceTypeId = 2001)
		BEGIN
			SELECT
			WFM.Title AS WorkFlowName,
			WFM.Id AS WorkFlowId,
			AR.Id AS ApprovalRequestId,
			AR.CreatedDateTime AS CreatedDateTime,
			AR.ParticipantSourceTypeId AS ParticipantSourceTypeId,
			CASE WHEN ParticipantSourceTypeId= 2001 THEN ISNULL(SA.AcademicId, 0) WHEN ParticipantSourceTypeId= 95 THEN ISNULL(EM.Id,0) ELSE 0 END AS SourceId,
			CASE WHEN ParticipantSourceTypeId= 2001 THEN SA.Code WHEN ParticipantSourceTypeId= 95 THEN EM.Code END AS Code ,
			CASE WHEN ParticipantSourceTypeId= 2001 THEN SA.Name WHEN ParticipantSourceTypeId= 95 THEN EM.FirstName +' '+ EM.MiddleName +' ' +EM.LastName END AS Name ,
			AR.Remark AS Remark,
			(CASE ISNULL(asm.Id,'') WHEN '' THEN 3 ELSE asm.Id END) AS statusId,
			(case isnull(asm.title,'') when '' then 'Pending' else asm.title end) as status,
			AR.ParticipantSourceId,
			ISNULL(AA.ActionRemark, '') AS ActionRemark
		FROM sWorkflow.tApprovalRequest AR
			INNER JOIN sWorkflow.tWorkflowFunctionalityMaster WFM ON AR.WorkflowFunctionalityId = WFM.Id
			LEFT JOIN  sStudent.vStudentAcademic  SA ON SA.AcademicId = AR.ParticipantSourceId
			LEFT JOIN  sHrm.tEmployeeMaster  EM ON EM.Id = AR.ParticipantSourceId
			LEFT JOIN sWorkflow.tApprovalAction AA ON AA.ApprovalRequestId = AR.Id 
			LEFT JOIN sWorkflow.tActionStatusMaster ASM ON ASM.Id = AA.ActionStatusId 
		WHERE ((WFM.Id = @rWorkflowFunctionalityId) OR (@rWorkflowFunctionalityId =0)) 
			AND ((AR.CreatedDateTime >= '') OR (ISNULL('','') = ''))
			AND ((AR.CreatedDateTime <= '') OR (ISNULL('','') = ''))
			AND((ASM.Id = 0) OR (0 =0))
			AND (((SA.Code = '') OR ('' ='')) OR ((EM.Code = '') OR ('' =0)))
			AND ISNULL(EM.IsOtherUser,0) = 0 
			AND AR.CreatedUserId = @rUserId AND AR.ParticipantSourceTypeId = 2001
			AND ((AR.ParticipantSourceId = @rParticipantSourceId) OR (@rParticipantSourceId = 0))
			AND ((AR.Id = @rApprovalRequestId) OR (@rApprovalRequestId = 0))
			AND ((ISNULL(ASM.Id,3) = @rStatusId) OR (@rStatusId =0))
			AND ((Convert(Date,AR.CreatedDateTime)>= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
            AND ((Convert(Date,AR.CreatedDateTime) <= @rToDate) OR (ISNULL(@rToDate,'') = ''))
		
UNION 

SELECT
			WFM.Title AS WorkFlowName,
			WFM.Id AS WorkFlowId,
			AR.Id AS ApprovalRequestId,
			AR.CreatedDateTime AS CreatedDateTime,
			AR.ParticipantSourceTypeId AS ParticipantSourceTypeId,
			CASE WHEN ParticipantSourceTypeId= 2001 THEN SA.AcademicId WHEN ParticipantSourceTypeId= 95 THEN EM.Id ELSE 0 END AS SourceId,
			CASE WHEN ParticipantSourceTypeId= 2001 THEN SA.Code WHEN ParticipantSourceTypeId= 95 THEN EM.Code END AS Code ,
			CASE WHEN ParticipantSourceTypeId= 2001 THEN SA.Name WHEN ParticipantSourceTypeId= 95 THEN EM.FirstName +' '+ EM.MiddleName +' ' +EM.LastName END AS Name ,
			AR.Remark AS Remark,
			(CASE ISNULL(asm.Id,'') WHEN '' THEN 3 ELSE asm.Id END) AS statusId,
			(case isnull(asm.title,'') when '' then 'Pending' else asm.title end) as status,
			AR.ParticipantSourceId,
			ISNULL(AA.ActionRemark, '') AS ActionRemark
		FROM sWorkflow.tApprovalRequest AR
			INNER JOIN sWorkflow.tWorkflowFunctionalityMaster WFM ON AR.WorkflowFunctionalityId = WFM.Id
			LEFT JOIN  sStudent.vStudentAcademic  SA ON SA.AcademicId = AR.ParticipantSourceId
			LEFT JOIN  sHrm.tEmployeeMaster  EM ON EM.Id = AR.ParticipantSourceId
			LEFT JOIN sWorkflow.tApprovalAction AA ON AA.ApprovalRequestId = AR.Id 
			LEFT JOIN sWorkflow.tActionStatusMaster ASM ON ASM.Id = AA.ActionStatusId 
		WHERE ((WFM.Id = @rWorkflowFunctionalityId) OR (@rWorkflowFunctionalityId =0)) 
			AND ((AR.CreatedDateTime >= '') OR (ISNULL('','') = ''))
			AND ((AR.CreatedDateTime <= '') OR (ISNULL('','') = ''))
			AND((ASM.Id = 0) OR (0 =0))
			AND (((SA.Code = '') OR ('' ='')) OR ((EM.Code = '') OR ('' =0)))
			AND ISNULL(EM.IsOtherUser,0) = 0 
			AND AR.ParticipantSourceTypeId = 2001
			AND ((AR.ParticipantSourceId = @rParticipantSourceId) OR (@rParticipantSourceId = 0))
			AND ((AR.Id = @rApprovalRequestId) OR (@rApprovalRequestId = 0))
			AND ((ISNULL(ASM.Id,3) = @rStatusId) OR (@rStatusId =0))
			AND ((Convert(Date,AR.CreatedDateTime)>= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
            AND ((Convert(Date,AR.CreatedDateTime) <= @rToDate) OR (ISNULL(@rToDate,'') = ''))
		END
		ELSE IF(@rUserSourceTypeId = 95)
		BEGIN
			SELECT
			WFM.Title AS WorkFlowName,
			WFM.Id AS WorkFlowId,
			AR.Id AS ApprovalRequestId,
			AR.CreatedDateTime AS CreatedDateTime,
			AR.ParticipantSourceTypeId AS ParticipantSourceTypeId,
			CASE WHEN ParticipantSourceTypeId= 2001 THEN SA.AcademicId WHEN ParticipantSourceTypeId= 95 THEN EM.Id ELSE 0 END AS SourceId,
			CASE WHEN ParticipantSourceTypeId= 2001 THEN SA.Code WHEN ParticipantSourceTypeId= 95 THEN EM.Code END AS Code ,
			CASE WHEN ParticipantSourceTypeId= 2001 THEN SA.Name WHEN ParticipantSourceTypeId= 95 THEN EM.FirstName +' '+ EM.MiddleName +' ' +EM.LastName END AS Name ,
			AR.Remark AS Remark,
			(CASE ISNULL(asm.Id,'') WHEN '' THEN 3 ELSE asm.Id END) AS statusId,
			(case isnull(asm.title,'') when '' then 'Pending' else asm.title end) as status,
			AR.ParticipantSourceId,
			ISNULL(AA.ActionRemark, '') AS ActionRemark
		FROM sWorkflow.tApprovalRequest AR
			INNER JOIN sWorkflow.tWorkflowFunctionalityMaster WFM ON AR.WorkflowFunctionalityId = WFM.Id
			LEFT JOIN  sStudent.vStudentAcademic  SA ON SA.AcademicId = AR.ParticipantSourceId
			LEFT JOIN  sHrm.tEmployeeMaster  EM ON EM.Id = AR.ParticipantSourceId
			LEFT JOIN sWorkflow.tApprovalAction AA ON AA.ApprovalRequestId = AR.Id 
			LEFT JOIN sWorkflow.tActionStatusMaster ASM ON ASM.Id = AA.ActionStatusId
		WHERE ((WFM.Id = @rWorkflowFunctionalityId) OR (@rWorkflowFunctionalityId=0)) 
			AND ((AR.CreatedDateTime >= '') OR (ISNULL('','') = ''))
			AND ((AR.CreatedDateTime <= '') OR (ISNULL('','') = ''))
			AND((ASM.Id = 0) OR (0 =0))
			AND (((SA.Code = '') OR ('' ='')) OR ((EM.Code = '') OR ('' =0)))
			AND ISNULL(EM.IsOtherUser,0) = 0 
			AND AR.CreatedUserId = @rUserId AND AR.ParticipantSourceTypeId = 95
			AND ((AR.ParticipantSourceId = @rParticipantSourceId) OR (@rParticipantSourceId = 0))
			AND ((AR.Id = @rApprovalRequestId) OR (@rApprovalRequestId = 0))
			AND((ISNULL(ASM.Id,3) = @rStatusId) OR (@rStatusId =0))
			AND ((Convert(Date,AR.CreatedDateTime)>= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
            AND ((Convert(Date,AR.CreatedDateTime) <= @rToDate) OR (ISNULL(@rToDate,'') = ''))
		
UNION 

SELECT
			WFM.Title AS WorkFlowName,
			WFM.Id AS WorkFlowId,
			AR.Id AS ApprovalRequestId,
			AR.CreatedDateTime AS CreatedDateTime,
			AR.ParticipantSourceTypeId AS ParticipantSourceTypeId,
			CASE WHEN ParticipantSourceTypeId= 2001 THEN SA.AcademicId WHEN ParticipantSourceTypeId= 95 THEN EM.Id ELSE 0 END AS SourceId,
			CASE WHEN ParticipantSourceTypeId= 2001 THEN SA.Code WHEN ParticipantSourceTypeId= 95 THEN EM.Code END AS Code ,
			CASE WHEN ParticipantSourceTypeId= 2001 THEN SA.Name WHEN ParticipantSourceTypeId= 95 THEN EM.FirstName +' '+ EM.MiddleName +' ' +EM.LastName END AS Name ,
			AR.Remark AS Remark,
			(CASE ISNULL(asm.Id,'') WHEN '' THEN 3 ELSE asm.Id END) AS statusId,
			(case isnull(asm.title,'') when '' then 'Pending' else asm.title end) as status,
			AR.ParticipantSourceId,
			ISNULL(AA.ActionRemark, '') AS ActionRemark
		FROM sWorkflow.tApprovalRequest AR
			INNER JOIN sWorkflow.tWorkflowFunctionalityMaster WFM ON AR.WorkflowFunctionalityId = WFM.Id
			LEFT JOIN  sStudent.vStudentAcademic  SA ON SA.AcademicId = AR.ParticipantSourceId
			LEFT JOIN  sHrm.tEmployeeMaster  EM ON EM.Id = AR.ParticipantSourceId
			LEFT JOIN sWorkflow.tApprovalAction AA ON AA.ApprovalRequestId = AR.Id 
			LEFT JOIN sWorkflow.tActionStatusMaster ASM ON ASM.Id = AA.ActionStatusId
		WHERE ((WFM.Id = @rWorkflowFunctionalityId) OR (@rWorkflowFunctionalityId =0)) 
			AND ((AR.CreatedDateTime >= '') OR (ISNULL('','') = ''))
			AND ((AR.CreatedDateTime <= '') OR (ISNULL('','') = ''))
			AND((ASM.Id = 0) OR (0 =0))
			AND (((SA.Code = '') OR ('' ='')) OR ((EM.Code = '') OR ('' =0)))
			AND ISNULL(EM.IsOtherUser,0) = 0 
			AND AR.ParticipantSourceTypeId = 95
			AND ((AR.ParticipantSourceId = @rParticipantSourceId) OR (@rParticipantSourceId = 0))
			AND ((AR.Id = @rApprovalRequestId) OR (@rApprovalRequestId = 0))
			AND((ISNULL(ASM.Id,3) = @rStatusId) OR (@rStatusId =0))
		END
		ELSE
		BEGIN
			SELECT
			--U.SourceTypeId,
			WFM.Title AS WorkFlowName,
			WFM.Id AS WorkFlowId,
			AR.Id AS ApprovalRequestId,
			AR.CreatedDateTime AS CreatedDateTime,
			AR.ParticipantSourceTypeId AS ParticipantSourceTypeId,
			CASE WHEN ParticipantSourceTypeId= 2001 THEN SA.AcademicId WHEN ParticipantSourceTypeId= 95 THEN EM.Id ELSE 0 END AS SourceId,
			CASE WHEN ParticipantSourceTypeId= 2001 THEN SA.Code WHEN ParticipantSourceTypeId= 95 THEN EM.Code END AS Code ,
			CASE WHEN ParticipantSourceTypeId= 2001 THEN SA.Name WHEN ParticipantSourceTypeId= 95 THEN EM.FirstName +' '+ EM.MiddleName +' ' +EM.LastName END AS Name ,
			AR.Remark AS Remark,
			(CASE ISNULL(asm.Id,'') WHEN '' THEN 3 ELSE asm.Id END) AS statusId,
			(case isnull(asm.title,'') when '' then 'Pending' else asm.title end) as status,
			AR.ParticipantSourceId,
			ISNULL(AA.ActionRemark, '') AS ActionRemark
		FROM sWorkflow.tApprovalRequest AR
			INNER JOIN sWorkflow.tWorkflowFunctionalityMaster WFM ON AR.WorkflowFunctionalityId = WFM.Id
			LEFT JOIN  sStudent.vStudentAcademic  SA ON SA.AcademicId = AR.ParticipantSourceId
			LEFT JOIN  sHrm.tEmployeeMaster  EM ON EM.Id = AR.ParticipantSourceId
			LEFT JOIN sWorkflow.tApprovalAction AA ON AA.ApprovalRequestId = AR.Id 
			LEFT JOIN sWorkflow.tActionStatusMaster ASM ON ASM.Id = AA.ActionStatusId
			--INNER JOIN [sSecurity].[tUser] U ON AR.CreatedUserId = U.Id
		WHERE 
		--((WFM.Id = 0) OR (0 =0)) 
			((WFM.Id = @rWorkflowFunctionalityId) OR (@rWorkflowFunctionalityId =0)) 
			AND ((AR.CreatedDateTime >= '') OR (ISNULL('','') = ''))
			AND ((AR.CreatedDateTime <= '') OR (ISNULL('','') = ''))
			AND ((ASM.Id = 0) OR (0 =0))
			AND (((SA.Code = '') OR ('' ='')) OR ((EM.Code = '') OR ('' =0)))
			AND ISNULL(EM.IsOtherUser,0) = 0 
			AND((ISNULL(ASM.Id,3) = @rStatusId) OR (@rStatusId =0))
		END
END
GO
PRINT N'Creating Procedure [sActivity].[pEventAttendanceStudentDetailsGet]...';


GO


CREATE PROCEDURE [sActivity].[pEventAttendanceStudentDetailsGet]
	
	 @rUserTypeId int,
	 @rIsPresentAbsent int,
	 @rOrgId int,
	 @rAcademicId bigint

	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 		
	--SET @rUserTypeId = 1 for Student
	--SET @rUserTypeId = 2 for Father
	--SET @rUserTypeId = 3 for Mother
	--SET @rUserTypeId = 4 for Relative

	--SET @rIsPresentAbsent = 1 for All
	--SET @rIsPresentAbsent = 2 for Present
	--SET @rIsPresentAbsent = 3 for Absent


	--for Student
IF(@rUserTypeId = 1 AND @rIsPresentAbsent = 1)
BEGIN
SELECT 
ES.Title AS EventName,
(CASE WHEN EAT.IsSelfPresent = 1 THEN 'PR' ELSE 'AB' END ) AS Status,
ES.FromDate,
ES.ToDate
FROM 
				sStudent.vStudentAcademic vSA
				INNER JOIN sSetup.tClassMaster CM ON CM.Id = vSA.ClassId
				INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = vSA.DivisionId
				INNER JOIN sActivity.tEventAssign EA ON EA.SourceId=vSA.DivisionId AND EA.SourceTypeId=2005 
				--AND EA.EventScheduleId=@rEventScheduleId
				INNER JOIN sActivity.tEventAttendance EAT ON EAT.EventScheduleId = EA.EventScheduleId 
				AND EAT.SourceId = vSA.AcademicId AND EAT.SourceTypeId = 2001
				INNER JOIN sActivity.tEventSchedule ES ON ES.Id = EAT.EventScheduleId
				INNER JOiN [sActivity].[tEventTypeMaster] ETM ON ES.EventTypeId=ETM.Id 
				inner Join [sActivity].[tEventMainTypeMaster]  EMTM ON ETM.EventMainTypeId=EMTM.Id --AND EMTM.id=3
				INNER JOIN sSetup.tOrganizationMaster OM ON vSA.OrgId = OM.Id
				INNER JOIN sSetup.tOrgGroupMaster OGM ON OM.OrgGroupId = OGM.Id

			WHERE
				--(vSA.ClassId=0 OR 0=0)
				--AND (vSA.DivisionId=0 OR 0=0)
				(vSA.StatusId=1)
				AND (vSA.OrgId = @rOrgId OR @rOrgId = 0)
				AND (vSA.IsActiveBatch = 1)
				AND (OGM.Id = @rOrgId OR @rOrgId = 0)
				AND vSA.AcademicId = @rAcademicId	
				AND (EAT.IsSelfPresent = 0 OR EAT.IsSelfPresent = 1)
END

IF(@rUserTypeId = 1 AND @rIsPresentAbsent = 2)
BEGIN
SELECT 
ES.Title AS EventName,
(CASE WHEN EAT.IsSelfPresent = 1 THEN 'PR' ELSE 'AB' END ) AS Status,
ES.FromDate,
ES.ToDate
FROM 
				sStudent.vStudentAcademic vSA
				INNER JOIN sSetup.tClassMaster CM ON CM.Id = vSA.ClassId
				INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = vSA.DivisionId
				INNER JOIN sActivity.tEventAssign EA ON EA.SourceId=vSA.DivisionId AND EA.SourceTypeId=2005 
				--AND EA.EventScheduleId=@rEventScheduleId
				INNER JOIN sActivity.tEventAttendance EAT ON EAT.EventScheduleId = EA.EventScheduleId 
				AND EAT.SourceId = vSA.AcademicId AND EAT.SourceTypeId = 2001
				INNER JOIN sActivity.tEventSchedule ES ON ES.Id = EAT.EventScheduleId
				INNER JOiN [sActivity].[tEventTypeMaster] ETM ON ES.EventTypeId=ETM.Id 
				inner Join [sActivity].[tEventMainTypeMaster]  EMTM ON ETM.EventMainTypeId=EMTM.Id --AND EMTM.id=3
				INNER JOIN sSetup.tOrganizationMaster OM ON vSA.OrgId = OM.Id
				INNER JOIN sSetup.tOrgGroupMaster OGM ON OM.OrgGroupId = OGM.Id

			WHERE
				--(vSA.ClassId=0 OR 0=0)
				--AND (vSA.DivisionId=0 OR 0=0)
				(vSA.StatusId=1)
				AND (vSA.OrgId = @rOrgId OR @rOrgId = 0)
				AND (vSA.IsActiveBatch=1)
				AND (OGM.Id = @rOrgId OR @rOrgId = 0)
				AND vSA.AcademicId = @rAcademicId		
				AND (EAT.IsSelfPresent = 1)
END

IF(@rUserTypeId = 1 AND @rIsPresentAbsent = 3)
BEGIN
SELECT 
ES.Title AS EventName,
(CASE WHEN EAT.IsSelfPresent = 1 THEN 'PR' ELSE 'AB' END ) AS Status,
ES.FromDate,
ES.ToDate
FROM 
				sStudent.vStudentAcademic vSA
				INNER JOIN sSetup.tClassMaster CM ON CM.Id = vSA.ClassId
				INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = vSA.DivisionId
				INNER JOIN sActivity.tEventAssign EA ON EA.SourceId=vSA.DivisionId AND EA.SourceTypeId=2005 
				--AND EA.EventScheduleId=@rEventScheduleId
				INNER JOIN sActivity.tEventAttendance EAT ON EAT.EventScheduleId = EA.EventScheduleId 
				AND EAT.SourceId = vSA.AcademicId AND EAT.SourceTypeId = 2001
				INNER JOIN sActivity.tEventSchedule ES ON ES.Id = EAT.EventScheduleId
				INNER JOiN [sActivity].[tEventTypeMaster] ETM ON ES.EventTypeId=ETM.Id 
				inner Join [sActivity].[tEventMainTypeMaster]  EMTM ON ETM.EventMainTypeId=EMTM.Id --AND EMTM.id=3
				INNER JOIN sSetup.tOrganizationMaster OM ON vSA.OrgId = OM.Id
				INNER JOIN sSetup.tOrgGroupMaster OGM ON OM.OrgGroupId = OGM.Id

			WHERE
				--(vSA.ClassId=0 OR 0=0)
				--AND (vSA.DivisionId=0 OR 0=0)
				(vSA.StatusId=1)
				AND (vSA.OrgId = @rOrgId OR @rOrgId = 0)
				AND (vSA.IsActiveBatch=1)
				AND (OGM.Id = @rOrgId OR @rOrgId = 0)
				AND vSA.AcademicId = @rAcademicId	
				AND (EAT.IsSelfPresent = 0)
END

--for Father

IF(@rUserTypeId = 2 AND @rIsPresentAbsent = 1)
BEGIN
SELECT 
ES.Title AS EventName,
(CASE WHEN EAT.IsFatherPresent = 1 THEN 'PR' ELSE 'AB' END ) AS Status,
ES.FromDate,
ES.ToDate
FROM 
				sStudent.vStudentAcademic vSA
				INNER JOIN sSetup.tClassMaster CM ON CM.Id = vSA.ClassId
				INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = vSA.DivisionId
				INNER JOIN sActivity.tEventAssign EA ON EA.SourceId=vSA.DivisionId AND EA.SourceTypeId=2005 
				--AND EA.EventScheduleId=@rEventScheduleId
				INNER JOIN sActivity.tEventAttendance EAT ON EAT.EventScheduleId = EA.EventScheduleId 
				AND EAT.SourceId = vSA.AcademicId AND EAT.SourceTypeId = 2001
				INNER JOIN sActivity.tEventSchedule ES ON ES.Id = EAT.EventScheduleId
				INNER JOiN [sActivity].[tEventTypeMaster] ETM ON ES.EventTypeId=ETM.Id 
				inner Join [sActivity].[tEventMainTypeMaster]  EMTM ON ETM.EventMainTypeId=EMTM.Id --AND EMTM.id=3
				INNER JOIN sSetup.tOrganizationMaster OM ON vSA.OrgId = OM.Id
				INNER JOIN sSetup.tOrgGroupMaster OGM ON OM.OrgGroupId = OGM.Id

			WHERE
				--(vSA.ClassId=0 OR 0=0)
				--AND (vSA.DivisionId=0 OR 0=0)
				(vSA.StatusId=1)
				AND (vSA.OrgId = @rOrgId OR @rOrgId = 0)
				AND (vSA.IsActiveBatch=1)
				AND (OGM.Id = @rOrgId OR @rOrgId = 0)
				AND vSA.AcademicId = @rAcademicId	
				AND (EAT.IsFatherPresent = 0 OR EAT.IsFatherPresent = 1)
END

IF(@rUserTypeId = 2 AND @rIsPresentAbsent = 2)
BEGIN
SELECT 
ES.Title AS EventName,
(CASE WHEN EAT.IsFatherPresent = 1 THEN 'PR' ELSE 'AB' END ) AS Status,
ES.FromDate,
ES.ToDate
FROM 
				sStudent.vStudentAcademic vSA
				INNER JOIN sSetup.tClassMaster CM ON CM.Id = vSA.ClassId
				INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = vSA.DivisionId
				INNER JOIN sActivity.tEventAssign EA ON EA.SourceId=vSA.DivisionId AND EA.SourceTypeId=2005 
				--AND EA.EventScheduleId=@rEventScheduleId
				INNER JOIN sActivity.tEventAttendance EAT ON EAT.EventScheduleId = EA.EventScheduleId 
				AND EAT.SourceId = vSA.AcademicId AND EAT.SourceTypeId = 2001
				INNER JOIN sActivity.tEventSchedule ES ON ES.Id = EAT.EventScheduleId
				INNER JOiN [sActivity].[tEventTypeMaster] ETM ON ES.EventTypeId=ETM.Id 
				inner Join [sActivity].[tEventMainTypeMaster]  EMTM ON ETM.EventMainTypeId=EMTM.Id --AND EMTM.id=3
				INNER JOIN sSetup.tOrganizationMaster OM ON vSA.OrgId = OM.Id
				INNER JOIN sSetup.tOrgGroupMaster OGM ON OM.OrgGroupId = OGM.Id

			WHERE
				--(vSA.ClassId=0 OR 0=0)
				--AND (vSA.DivisionId=0 OR 0=0)
				(vSA.StatusId=1)
				AND (vSA.OrgId = @rOrgId OR @rOrgId = 0)
				AND (vSA.IsActiveBatch=1)
				AND (OGM.Id = @rOrgId OR @rOrgId = 0)
				AND vSA.AcademicId = @rAcademicId	
				AND (EAT.IsFatherPresent = 1)
END

IF(@rUserTypeId = 2 AND @rIsPresentAbsent = 3)
BEGIN
SELECT 
ES.Title AS EventName,
(CASE WHEN EAT.IsFatherPresent = 1 THEN 'PR' ELSE 'AB' END ) AS Status,
ES.FromDate,
ES.ToDate
FROM 
				sStudent.vStudentAcademic vSA
				INNER JOIN sSetup.tClassMaster CM ON CM.Id = vSA.ClassId
				INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = vSA.DivisionId
				INNER JOIN sActivity.tEventAssign EA ON EA.SourceId=vSA.DivisionId AND EA.SourceTypeId=2005 
				--AND EA.EventScheduleId=@rEventScheduleId
				INNER JOIN sActivity.tEventAttendance EAT ON EAT.EventScheduleId = EA.EventScheduleId 
				AND EAT.SourceId = vSA.AcademicId AND EAT.SourceTypeId = 2001
				INNER JOIN sActivity.tEventSchedule ES ON ES.Id = EAT.EventScheduleId
				INNER JOiN [sActivity].[tEventTypeMaster] ETM ON ES.EventTypeId=ETM.Id 
				inner Join [sActivity].[tEventMainTypeMaster]  EMTM ON ETM.EventMainTypeId=EMTM.Id --AND EMTM.id=3
				INNER JOIN sSetup.tOrganizationMaster OM ON vSA.OrgId = OM.Id
				INNER JOIN sSetup.tOrgGroupMaster OGM ON OM.OrgGroupId = OGM.Id

			WHERE
				--(vSA.ClassId=0 OR 0=0)
				--AND (vSA.DivisionId=0 OR 0=0)
				(vSA.StatusId=1)
				AND (vSA.OrgId = @rOrgId OR @rOrgId = 0)
				AND (vSA.IsActiveBatch=1)
				AND (OGM.Id = @rOrgId OR @rOrgId = 0)
				AND vSA.AcademicId = @rAcademicId	
				AND (EAT.IsFatherPresent = 0)
END

--for Mother

IF(@rUserTypeId = 3 AND @rIsPresentAbsent = 1)
BEGIN
SELECT 
ES.Title AS EventName,
(CASE WHEN EAT.IsMotherPresent = 1 THEN 'PR' ELSE 'AB' END ) AS Status,
ES.FromDate,
ES.ToDate
FROM 
				sStudent.vStudentAcademic vSA
				INNER JOIN sSetup.tClassMaster CM ON CM.Id = vSA.ClassId
				INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = vSA.DivisionId
				INNER JOIN sActivity.tEventAssign EA ON EA.SourceId=vSA.DivisionId AND EA.SourceTypeId=2005 
				--AND EA.EventScheduleId=@rEventScheduleId
				INNER JOIN sActivity.tEventAttendance EAT ON EAT.EventScheduleId = EA.EventScheduleId 
				AND EAT.SourceId = vSA.AcademicId AND EAT.SourceTypeId = 2001
				INNER JOIN sActivity.tEventSchedule ES ON ES.Id = EAT.EventScheduleId
				INNER JOiN [sActivity].[tEventTypeMaster] ETM ON ES.EventTypeId=ETM.Id 
				inner Join [sActivity].[tEventMainTypeMaster]  EMTM ON ETM.EventMainTypeId=EMTM.Id --AND EMTM.id=3
				INNER JOIN sSetup.tOrganizationMaster OM ON vSA.OrgId = OM.Id
				INNER JOIN sSetup.tOrgGroupMaster OGM ON OM.OrgGroupId = OGM.Id

			WHERE
				--(vSA.ClassId=0 OR 0=0)
				--AND (vSA.DivisionId=0 OR 0=0)
				(vSA.StatusId=1)
				AND (vSA.OrgId = @rOrgId OR @rOrgId = 0)
				AND (vSA.IsActiveBatch=1)
				AND (OGM.Id = @rOrgId OR @rOrgId = 0)
				AND vSA.AcademicId = @rAcademicId	
				AND (EAT.IsMotherPresent = 0 OR EAT.IsMotherPresent = 1)
END

IF(@rUserTypeId = 3 AND @rIsPresentAbsent = 2)
BEGIN
SELECT 
ES.Title AS EventName,
(CASE WHEN EAT.IsMotherPresent = 1 THEN 'PR' ELSE 'AB' END ) AS Status,
ES.FromDate,
ES.ToDate
FROM 
				sStudent.vStudentAcademic vSA
				INNER JOIN sSetup.tClassMaster CM ON CM.Id = vSA.ClassId
				INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = vSA.DivisionId
				INNER JOIN sActivity.tEventAssign EA ON EA.SourceId=vSA.DivisionId AND EA.SourceTypeId=2005 
				--AND EA.EventScheduleId=@rEventScheduleId
				INNER JOIN sActivity.tEventAttendance EAT ON EAT.EventScheduleId = EA.EventScheduleId 
				AND EAT.SourceId = vSA.AcademicId AND EAT.SourceTypeId = 2001
				INNER JOIN sActivity.tEventSchedule ES ON ES.Id = EAT.EventScheduleId
				INNER JOiN [sActivity].[tEventTypeMaster] ETM ON ES.EventTypeId=ETM.Id 
				inner Join [sActivity].[tEventMainTypeMaster]  EMTM ON ETM.EventMainTypeId=EMTM.Id --AND EMTM.id=3
				INNER JOIN sSetup.tOrganizationMaster OM ON vSA.OrgId = OM.Id
				INNER JOIN sSetup.tOrgGroupMaster OGM ON OM.OrgGroupId = OGM.Id

			WHERE
				--(vSA.ClassId=0 OR 0=0)
				--AND (vSA.DivisionId=0 OR 0=0)
				(vSA.StatusId=1)
				AND (vSA.OrgId = @rOrgId OR @rOrgId = 0)
				AND (vSA.IsActiveBatch=1)
				AND (OGM.Id = @rOrgId OR @rOrgId = 0)
				AND vSA.AcademicId = @rAcademicId	
				AND (EAT.IsMotherPresent = 1)
END

IF(@rUserTypeId = 3 AND @rIsPresentAbsent = 3)
BEGIN
SELECT 
ES.Title AS EventName,
(CASE WHEN EAT.IsMotherPresent = 1 THEN 'PR' ELSE 'AB' END ) AS Status,
ES.FromDate,
ES.ToDate
FROM 
				sStudent.vStudentAcademic vSA
				INNER JOIN sSetup.tClassMaster CM ON CM.Id = vSA.ClassId
				INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = vSA.DivisionId
				INNER JOIN sActivity.tEventAssign EA ON EA.SourceId=vSA.DivisionId AND EA.SourceTypeId=2005 
				--AND EA.EventScheduleId=@rEventScheduleId
				INNER JOIN sActivity.tEventAttendance EAT ON EAT.EventScheduleId = EA.EventScheduleId 
				AND EAT.SourceId = vSA.AcademicId AND EAT.SourceTypeId = 2001
				INNER JOIN sActivity.tEventSchedule ES ON ES.Id = EAT.EventScheduleId
				INNER JOiN [sActivity].[tEventTypeMaster] ETM ON ES.EventTypeId=ETM.Id 
				inner Join [sActivity].[tEventMainTypeMaster]  EMTM ON ETM.EventMainTypeId=EMTM.Id --AND EMTM.id=3
				INNER JOIN sSetup.tOrganizationMaster OM ON vSA.OrgId = OM.Id
				INNER JOIN sSetup.tOrgGroupMaster OGM ON OM.OrgGroupId = OGM.Id

			WHERE
				--(vSA.ClassId=0 OR 0=0)
				--AND (vSA.DivisionId=0 OR 0=0)
				(vSA.StatusId=1)
				AND (vSA.OrgId = @rOrgId OR @rOrgId = 0)
				AND (vSA.IsActiveBatch=1)
				AND (OGM.Id = @rOrgId OR @rOrgId = 0)
				AND vSA.AcademicId = @rAcademicId	
				AND (EAT.IsMotherPresent = 0)
END

--for Relative

IF(@rUserTypeId = 4 AND @rIsPresentAbsent = 1)
BEGIN
SELECT 
ES.Title AS EventName,
(CASE WHEN EAT.IsGuardianPresent = 1 THEN 'PR' ELSE 'AB' END ) AS Status,
ES.FromDate,
ES.ToDate
FROM 
				sStudent.vStudentAcademic vSA
				INNER JOIN sSetup.tClassMaster CM ON CM.Id = vSA.ClassId
				INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = vSA.DivisionId
				INNER JOIN sActivity.tEventAssign EA ON EA.SourceId=vSA.DivisionId AND EA.SourceTypeId=2005 
				--AND EA.EventScheduleId=@rEventScheduleId
				INNER JOIN sActivity.tEventAttendance EAT ON EAT.EventScheduleId = EA.EventScheduleId 
				AND EAT.SourceId = vSA.AcademicId AND EAT.SourceTypeId = 2001
				INNER JOIN sActivity.tEventSchedule ES ON ES.Id = EAT.EventScheduleId
				INNER JOiN [sActivity].[tEventTypeMaster] ETM ON ES.EventTypeId=ETM.Id 
				inner Join [sActivity].[tEventMainTypeMaster]  EMTM ON ETM.EventMainTypeId=EMTM.Id --AND EMTM.id=3
				INNER JOIN sSetup.tOrganizationMaster OM ON vSA.OrgId = OM.Id
				INNER JOIN sSetup.tOrgGroupMaster OGM ON OM.OrgGroupId = OGM.Id

			WHERE
				--(vSA.ClassId=0 OR 0=0)
				--AND (vSA.DivisionId=0 OR 0=0)
				(vSA.StatusId=1)
				AND (vSA.OrgId = @rOrgId OR @rOrgId = 0)
				AND (vSA.IsActiveBatch=1)
				AND (OGM.Id = @rOrgId OR @rOrgId = 0)
				AND vSA.AcademicId = @rAcademicId	
				AND (EAT.IsGuardianPresent = 0 OR EAT.IsGuardianPresent = 1)
END

IF(@rUserTypeId = 4 AND @rIsPresentAbsent = 2)
BEGIN
SELECT 
ES.Title AS EventName,
(CASE WHEN EAT.IsGuardianPresent = 1 THEN 'PR' ELSE 'AB' END ) AS Status,
ES.FromDate,
ES.ToDate
FROM 
				sStudent.vStudentAcademic vSA
				INNER JOIN sSetup.tClassMaster CM ON CM.Id = vSA.ClassId
				INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = vSA.DivisionId
				INNER JOIN sActivity.tEventAssign EA ON EA.SourceId=vSA.DivisionId AND EA.SourceTypeId=2005 
				--AND EA.EventScheduleId=@rEventScheduleId
				INNER JOIN sActivity.tEventAttendance EAT ON EAT.EventScheduleId = EA.EventScheduleId 
				AND EAT.SourceId = vSA.AcademicId AND EAT.SourceTypeId = 2001
				INNER JOIN sActivity.tEventSchedule ES ON ES.Id = EAT.EventScheduleId
				INNER JOiN [sActivity].[tEventTypeMaster] ETM ON ES.EventTypeId=ETM.Id 
				inner Join [sActivity].[tEventMainTypeMaster]  EMTM ON ETM.EventMainTypeId=EMTM.Id --AND EMTM.id=3
				INNER JOIN sSetup.tOrganizationMaster OM ON vSA.OrgId = OM.Id
				INNER JOIN sSetup.tOrgGroupMaster OGM ON OM.OrgGroupId = OGM.Id

			WHERE
				--(vSA.ClassId=0 OR 0=0)
				--AND (vSA.DivisionId=0 OR 0=0)
				(vSA.StatusId=1)
				AND (vSA.OrgId = @rOrgId OR @rOrgId = 0)
				AND (vSA.IsActiveBatch=1)
				AND (OGM.Id = @rOrgId OR @rOrgId = 0)
				AND vSA.AcademicId = @rAcademicId	
				AND (EAT.IsGuardianPresent = 1)
END

IF(@rUserTypeId = 4 AND @rIsPresentAbsent = 3)
BEGIN
SELECT 
ES.Title AS EventName,
(CASE WHEN EAT.IsGuardianPresent = 1 THEN 'PR' ELSE 'AB' END ) AS Status,
ES.FromDate,
ES.ToDate
FROM 
				sStudent.vStudentAcademic vSA
				INNER JOIN sSetup.tClassMaster CM ON CM.Id = vSA.ClassId
				INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = vSA.DivisionId
				INNER JOIN sActivity.tEventAssign EA ON EA.SourceId=vSA.DivisionId AND EA.SourceTypeId=2005 
				--AND EA.EventScheduleId=@rEventScheduleId
				INNER JOIN sActivity.tEventAttendance EAT ON EAT.EventScheduleId = EA.EventScheduleId 
				AND EAT.SourceId = vSA.AcademicId AND EAT.SourceTypeId = 2001
				INNER JOIN sActivity.tEventSchedule ES ON ES.Id = EAT.EventScheduleId
				INNER JOiN [sActivity].[tEventTypeMaster] ETM ON ES.EventTypeId=ETM.Id 
				inner Join [sActivity].[tEventMainTypeMaster]  EMTM ON ETM.EventMainTypeId=EMTM.Id --AND EMTM.id=3
				INNER JOIN sSetup.tOrganizationMaster OM ON vSA.OrgId = OM.Id
				INNER JOIN sSetup.tOrgGroupMaster OGM ON OM.OrgGroupId = OGM.Id

			WHERE
				--(vSA.ClassId=0 OR 0=0)
				--AND (vSA.DivisionId=0 OR 0=0)
				(vSA.StatusId=1)
				AND (vSA.OrgId = @rOrgId OR @rOrgId = 0)
				AND (vSA.IsActiveBatch=1)
				AND (OGM.Id = @rOrgId OR @rOrgId = 0)
				AND vSA.AcademicId = @rAcademicId	
				AND (EAT.IsGuardianPresent = 0)
END

END
GO
PRINT N'Creating Procedure [sActivity].[pEventAttendanceStudentWiseGet]...';


GO

CREATE PROCEDURE [sActivity].[pEventAttendanceStudentWiseGet]
	
	 @rOrgId smallint,
	 @rAcademicId bigint

	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 		
		Select 
		'Student' AS [Events],
		(SELECT COUNT(EAT.IsSelfPresent)
		FROM 
						sStudent.vStudentAcademic vSA
						INNER JOIN sSetup.tClassMaster CM ON CM.Id = vSA.ClassId
						INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = vSA.DivisionId
						INNER JOIN sActivity.tEventAssign EA ON EA.SourceId=vSA.DivisionId AND EA.SourceTypeId=2005 
						--AND EA.EventScheduleId=@rEventScheduleId
						INNER JOIN sActivity.tEventAttendance EAT ON EAT.EventScheduleId = EA.EventScheduleId 
						AND EAT.SourceId = vSA.AcademicId AND EAT.SourceTypeId = 2001
						INNER JOIN sActivity.tEventSchedule ES ON ES.Id = EAT.EventScheduleId
						INNER JOiN [sActivity].[tEventTypeMaster] ETM ON ES.EventTypeId=ETM.Id 
						inner Join [sActivity].[tEventMainTypeMaster]  EMTM ON ETM.EventMainTypeId=EMTM.Id --AND EMTM.id=3
						INNER JOIN sSetup.tOrganizationMaster OM ON vSA.OrgId = OM.Id
						INNER JOIN sSetup.tOrgGroupMaster OGM ON OM.OrgGroupId = OGM.Id

					WHERE
						--(vSA.ClassId=0 OR 0=0)
						--AND (vSA.DivisionId=0 OR 0=0)
						(vSA.StatusId=1)
						AND (vSA.OrgId=@rOrgId OR @rOrgId=0)
						AND (vSA.IsActiveBatch=1)
						AND (OGM.Id = @rOrgId OR @rOrgId = 0)
						AND vSA.AcademicId = @rAcademicId	
						AND (EAT.IsSelfPresent = 0 OR EAT.IsSelfPresent = 1)
						) AS Total,
			(SELECT COUNT(EAT.IsSelfPresent)
			FROM 
							sStudent.vStudentAcademic vSA
							INNER JOIN sSetup.tClassMaster CM ON CM.Id = vSA.ClassId
							INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = vSA.DivisionId
							INNER JOIN sActivity.tEventAssign EA ON EA.SourceId=vSA.DivisionId AND EA.SourceTypeId=2005 
							--AND EA.EventScheduleId=@rEventScheduleId
							INNER JOIN sActivity.tEventAttendance EAT ON EAT.EventScheduleId = EA.EventScheduleId 
							AND EAT.SourceId = vSA.AcademicId AND EAT.SourceTypeId = 2001
							INNER JOIN sActivity.tEventSchedule ES ON ES.Id = EAT.EventScheduleId
							INNER JOiN [sActivity].[tEventTypeMaster] ETM ON ES.EventTypeId=ETM.Id 
							inner Join [sActivity].[tEventMainTypeMaster]  EMTM ON ETM.EventMainTypeId=EMTM.Id --AND EMTM.id=3
							INNER JOIN sSetup.tOrganizationMaster OM ON vSA.OrgId = OM.Id
							INNER JOIN sSetup.tOrgGroupMaster OGM ON OM.OrgGroupId = OGM.Id

						WHERE
							--(vSA.ClassId=0 OR 0=0)
							--AND (vSA.DivisionId=0 OR 0=0)
							(vSA.StatusId = 1)
							AND (vSA.OrgId = @rOrgId OR @rOrgId = 0)
							AND (vSA.IsActiveBatch = 1 )
							AND (OGM.Id = @rOrgId OR @rOrgId = 0)
							AND vSA.AcademicId = @rAcademicId	
							AND EAT.IsSelfPresent = 1
							) AS Present,

			(SELECT COUNT(EAT.IsSelfPresent)
			FROM 
							sStudent.vStudentAcademic vSA
							INNER JOIN sSetup.tClassMaster CM ON CM.Id = vSA.ClassId
							INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = vSA.DivisionId
							INNER JOIN sActivity.tEventAssign EA ON EA.SourceId=vSA.DivisionId AND EA.SourceTypeId=2005 
							--AND EA.EventScheduleId=@rEventScheduleId
							INNER JOIN sActivity.tEventAttendance EAT ON EAT.EventScheduleId = EA.EventScheduleId 
							AND EAT.SourceId = vSA.AcademicId AND EAT.SourceTypeId = 2001
							INNER JOIN sActivity.tEventSchedule ES ON ES.Id = EAT.EventScheduleId
							INNER JOiN [sActivity].[tEventTypeMaster] ETM ON ES.EventTypeId=ETM.Id 
							inner Join [sActivity].[tEventMainTypeMaster]  EMTM ON ETM.EventMainTypeId=EMTM.Id --AND EMTM.id=3
							INNER JOIN sSetup.tOrganizationMaster OM ON vSA.OrgId = OM.Id
							INNER JOIN sSetup.tOrgGroupMaster OGM ON OM.OrgGroupId = OGM.Id

						WHERE
							--(vSA.ClassId=0 OR 0=0)
							--AND (vSA.DivisionId=0 OR 0=0)
							(vSA.StatusId = 1)
							AND (vSA.OrgId = @rOrgId OR @rOrgId = 0)
							AND (vSA.IsActiveBatch = 1)
							AND (OGM.Id = @rOrgId OR @rOrgId = 0)
							AND vSA.AcademicId = @rAcademicId
							AND EAT.IsSelfPresent = 0
							) AS Absent

UNION ALL

			Select 
			'Father' AS [Events],
			(SELECT COUNT(EAT.IsFatherPresent)
			FROM 
							sStudent.vStudentAcademic vSA
							INNER JOIN sSetup.tClassMaster CM ON CM.Id = vSA.ClassId
							INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = vSA.DivisionId
							INNER JOIN sActivity.tEventAssign EA ON EA.SourceId=vSA.DivisionId AND EA.SourceTypeId=2005 
							--AND EA.EventScheduleId=@rEventScheduleId
							INNER JOIN sActivity.tEventAttendance EAT ON EAT.EventScheduleId = EA.EventScheduleId 
							AND EAT.SourceId = vSA.AcademicId AND EAT.SourceTypeId = 2001
							INNER JOIN sActivity.tEventSchedule ES ON ES.Id = EAT.EventScheduleId
							INNER JOiN [sActivity].[tEventTypeMaster] ETM ON ES.EventTypeId=ETM.Id 
							inner Join [sActivity].[tEventMainTypeMaster]  EMTM ON ETM.EventMainTypeId=EMTM.Id --AND EMTM.id=3
							INNER JOIN sSetup.tOrganizationMaster OM ON vSA.OrgId = OM.Id
							INNER JOIN sSetup.tOrgGroupMaster OGM ON OM.OrgGroupId = OGM.Id

						WHERE
							--(vSA.ClassId=0 OR 0=0)
							--AND (vSA.DivisionId=0 OR 0=0)
							(vSA.StatusId = 1)
							AND (vSA.OrgId = @rOrgId OR @rOrgId = 0)
							AND (vSA.IsActiveBatch = 1)
							AND (OGM.Id = @rOrgId OR @rOrgId = 0)
							AND vSA.AcademicId = @rAcademicId	
							AND (EAT.IsFatherPresent = 0 OR EAT.IsFatherPresent = 1)
							) AS Total,
			(SELECT COUNT(EAT.IsFatherPresent)
			FROM 
							sStudent.vStudentAcademic vSA
							INNER JOIN sSetup.tClassMaster CM ON CM.Id = vSA.ClassId
							INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = vSA.DivisionId
							INNER JOIN sActivity.tEventAssign EA ON EA.SourceId=vSA.DivisionId AND EA.SourceTypeId=2005 
							--AND EA.EventScheduleId=@rEventScheduleId
							INNER JOIN sActivity.tEventAttendance EAT ON EAT.EventScheduleId = EA.EventScheduleId 
							AND EAT.SourceId = vSA.AcademicId AND EAT.SourceTypeId = 2001
							INNER JOIN sActivity.tEventSchedule ES ON ES.Id = EAT.EventScheduleId
							INNER JOiN [sActivity].[tEventTypeMaster] ETM ON ES.EventTypeId=ETM.Id 
							inner Join [sActivity].[tEventMainTypeMaster]  EMTM ON ETM.EventMainTypeId=EMTM.Id --AND EMTM.id=3
							INNER JOIN sSetup.tOrganizationMaster OM ON vSA.OrgId = OM.Id
							INNER JOIN sSetup.tOrgGroupMaster OGM ON OM.OrgGroupId = OGM.Id

						WHERE
							--(vSA.ClassId=0 OR 0=0)
							--AND (vSA.DivisionId=0 OR 0=0)
							(vSA.StatusId = 1)
							AND (vSA.OrgId = @rOrgId OR @rOrgId = 0)
							AND (vSA.IsActiveBatch = 1)
							AND (OGM.Id = @rOrgId OR @rOrgId = 0)
							AND vSA.AcademicId = @rAcademicId	
							AND EAT.IsFatherPresent = 1
							) AS Present,

			(SELECT COUNT(EAT.IsFatherPresent)
			FROM 
							sStudent.vStudentAcademic vSA
							INNER JOIN sSetup.tClassMaster CM ON CM.Id = vSA.ClassId
							INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = vSA.DivisionId
							INNER JOIN sActivity.tEventAssign EA ON EA.SourceId=vSA.DivisionId AND EA.SourceTypeId=2005 
							--AND EA.EventScheduleId=@rEventScheduleId
							INNER JOIN sActivity.tEventAttendance EAT ON EAT.EventScheduleId = EA.EventScheduleId 
							AND EAT.SourceId = vSA.AcademicId AND EAT.SourceTypeId = 2001
							INNER JOIN sActivity.tEventSchedule ES ON ES.Id = EAT.EventScheduleId
							INNER JOiN [sActivity].[tEventTypeMaster] ETM ON ES.EventTypeId=ETM.Id 
							inner Join [sActivity].[tEventMainTypeMaster]  EMTM ON ETM.EventMainTypeId=EMTM.Id --AND EMTM.id=3
							INNER JOIN sSetup.tOrganizationMaster OM ON vSA.OrgId = OM.Id
							INNER JOIN sSetup.tOrgGroupMaster OGM ON OM.OrgGroupId = OGM.Id

						WHERE
							--(vSA.ClassId=0 OR 0=0)
							--AND (vSA.DivisionId=0 OR 0=0)
							(vSA.StatusId = 1)
							AND (vSA.OrgId = @rOrgId OR @rOrgId = 0)
							AND (vSA.IsActiveBatch=1)
							AND (OGM.Id = @rOrgId OR @rOrgId = 0)
							AND vSA.AcademicId = @rAcademicId	
							AND EAT.IsFatherPresent = 0
							) AS Absent

UNION All

			Select 
			'Mother' AS [Events],
			(SELECT COUNT(EAT.IsMotherPresent)
			FROM 
							sStudent.vStudentAcademic vSA
							INNER JOIN sSetup.tClassMaster CM ON CM.Id = vSA.ClassId
							INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = vSA.DivisionId
							INNER JOIN sActivity.tEventAssign EA ON EA.SourceId=vSA.DivisionId AND EA.SourceTypeId=2005 
							--AND EA.EventScheduleId=@rEventScheduleId
							INNER JOIN sActivity.tEventAttendance EAT ON EAT.EventScheduleId = EA.EventScheduleId 
							AND EAT.SourceId = vSA.AcademicId AND EAT.SourceTypeId = 2001
							INNER JOIN sActivity.tEventSchedule ES ON ES.Id = EAT.EventScheduleId
							INNER JOiN [sActivity].[tEventTypeMaster] ETM ON ES.EventTypeId=ETM.Id 
							inner Join [sActivity].[tEventMainTypeMaster]  EMTM ON ETM.EventMainTypeId=EMTM.Id --AND EMTM.id=3
							INNER JOIN sSetup.tOrganizationMaster OM ON vSA.OrgId = OM.Id
							INNER JOIN sSetup.tOrgGroupMaster OGM ON OM.OrgGroupId = OGM.Id

						WHERE
							--(vSA.ClassId=0 OR 0=0)
							--AND (vSA.DivisionId=0 OR 0=0)
							(vSA.StatusId = 1)
							AND (vSA.OrgId = @rOrgId OR @rOrgId = 0)
							AND (vSA.IsActiveBatch = 1)
							AND (OGM.Id = @rOrgId OR @rOrgId = 0)
							AND vSA.AcademicId = @rAcademicId	
							AND (EAT.IsMotherPresent = 0 OR EAT.IsMotherPresent = 1)
							) AS Total,
			(SELECT COUNT(EAT.IsMotherPresent)
			FROM 
							sStudent.vStudentAcademic vSA
							INNER JOIN sSetup.tClassMaster CM ON CM.Id = vSA.ClassId
							INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = vSA.DivisionId
							INNER JOIN sActivity.tEventAssign EA ON EA.SourceId=vSA.DivisionId AND EA.SourceTypeId=2005 
							--AND EA.EventScheduleId=@rEventScheduleId
							INNER JOIN sActivity.tEventAttendance EAT ON EAT.EventScheduleId = EA.EventScheduleId 
							AND EAT.SourceId = vSA.AcademicId AND EAT.SourceTypeId = 2001
							INNER JOIN sActivity.tEventSchedule ES ON ES.Id = EAT.EventScheduleId
							INNER JOiN [sActivity].[tEventTypeMaster] ETM ON ES.EventTypeId=ETM.Id 
							inner Join [sActivity].[tEventMainTypeMaster]  EMTM ON ETM.EventMainTypeId=EMTM.Id --AND EMTM.id=3
							INNER JOIN sSetup.tOrganizationMaster OM ON vSA.OrgId = OM.Id
							INNER JOIN sSetup.tOrgGroupMaster OGM ON OM.OrgGroupId = OGM.Id

						WHERE
							--(vSA.ClassId=0 OR 0=0)
							--AND (vSA.DivisionId=0 OR 0=0)
							(vSA.StatusId = 1)
							AND (vSA.OrgId = @rOrgId OR @rOrgId = 0)
							AND (vSA.IsActiveBatch = 1)
							AND (OGM.Id = @rOrgId OR @rOrgId = 0)
							AND vSA.AcademicId = @rAcademicId	
							AND EAT.IsMotherPresent = 1
							) AS Present,

			(SELECT COUNT(EAT.IsMotherPresent)
			FROM 
							sStudent.vStudentAcademic vSA
							INNER JOIN sSetup.tClassMaster CM ON CM.Id = vSA.ClassId
							INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = vSA.DivisionId
							INNER JOIN sActivity.tEventAssign EA ON EA.SourceId=vSA.DivisionId AND EA.SourceTypeId=2005 
							--AND EA.EventScheduleId=@rEventScheduleId
							INNER JOIN sActivity.tEventAttendance EAT ON EAT.EventScheduleId = EA.EventScheduleId 
							AND EAT.SourceId = vSA.AcademicId AND EAT.SourceTypeId = 2001
							INNER JOIN sActivity.tEventSchedule ES ON ES.Id = EAT.EventScheduleId
							INNER JOiN [sActivity].[tEventTypeMaster] ETM ON ES.EventTypeId=ETM.Id 
							inner Join [sActivity].[tEventMainTypeMaster]  EMTM ON ETM.EventMainTypeId=EMTM.Id --AND EMTM.id=3
							INNER JOIN sSetup.tOrganizationMaster OM ON vSA.OrgId = OM.Id
							INNER JOIN sSetup.tOrgGroupMaster OGM ON OM.OrgGroupId = OGM.Id

						WHERE
						--(vSA.ClassId=0 OR 0=0)
							--AND (vSA.DivisionId=0 OR 0=0)
							(vSA.StatusId = 1)
							AND (vSA.OrgId = @rOrgId OR @rOrgId = 0)
							AND (vSA.IsActiveBatch = 1)
							AND (OGM.Id = @rOrgId OR @rOrgId = 0)
							AND vSA.AcademicId = @rAcademicId	
							AND EAT.IsMotherPresent = 0
							) AS Absent


UNION All

			Select 
			'Relative' AS [Events],
			(SELECT COUNT(EAT.IsGuardianPresent)
			FROM 
							sStudent.vStudentAcademic vSA
							INNER JOIN sSetup.tClassMaster CM ON CM.Id = vSA.ClassId
							INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = vSA.DivisionId
							INNER JOIN sActivity.tEventAssign EA ON EA.SourceId=vSA.DivisionId AND EA.SourceTypeId=2005 
							--AND EA.EventScheduleId=@rEventScheduleId
							INNER JOIN sActivity.tEventAttendance EAT ON EAT.EventScheduleId = EA.EventScheduleId 
							AND EAT.SourceId = vSA.AcademicId AND EAT.SourceTypeId = 2001
							INNER JOIN sActivity.tEventSchedule ES ON ES.Id = EAT.EventScheduleId
							INNER JOiN [sActivity].[tEventTypeMaster] ETM ON ES.EventTypeId=ETM.Id 
							inner Join [sActivity].[tEventMainTypeMaster]  EMTM ON ETM.EventMainTypeId=EMTM.Id --AND EMTM.id=3
							INNER JOIN sSetup.tOrganizationMaster OM ON vSA.OrgId = OM.Id
							INNER JOIN sSetup.tOrgGroupMaster OGM ON OM.OrgGroupId = OGM.Id

						WHERE
							--(vSA.ClassId=0 OR 0=0)
							--AND (vSA.DivisionId=0 OR 0=0)
							(vSA.StatusId = 1)
							AND (vSA.OrgId = @rOrgId OR @rOrgId = 0)
							AND (vSA.IsActiveBatch = 1)
							AND (OGM.Id = @rOrgId OR @rOrgId = 0)
							AND vSA.AcademicId = @rAcademicId	
							AND (EAT.IsGuardianPresent = 0 OR EAT.IsGuardianPresent = 1)
							) AS Total,
			(SELECT COUNT(EAT.IsGuardianPresent)
			FROM 
							sStudent.vStudentAcademic vSA
							INNER JOIN sSetup.tClassMaster CM ON CM.Id = vSA.ClassId
							INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = vSA.DivisionId
							INNER JOIN sActivity.tEventAssign EA ON EA.SourceId=vSA.DivisionId AND EA.SourceTypeId=2005 
							--AND EA.EventScheduleId=@rEventScheduleId
							INNER JOIN sActivity.tEventAttendance EAT ON EAT.EventScheduleId = EA.EventScheduleId 
							AND EAT.SourceId = vSA.AcademicId AND EAT.SourceTypeId = 2001
							INNER JOIN sActivity.tEventSchedule ES ON ES.Id = EAT.EventScheduleId
							INNER JOiN [sActivity].[tEventTypeMaster] ETM ON ES.EventTypeId=ETM.Id 
							inner Join [sActivity].[tEventMainTypeMaster]  EMTM ON ETM.EventMainTypeId=EMTM.Id --AND EMTM.id=3
							INNER JOIN sSetup.tOrganizationMaster OM ON vSA.OrgId = OM.Id
							INNER JOIN sSetup.tOrgGroupMaster OGM ON OM.OrgGroupId = OGM.Id

						WHERE
							--(vSA.ClassId=0 OR 0=0)
							--AND (vSA.DivisionId=0 OR 0=0)
							(vSA.StatusId = 1)
							AND (vSA.OrgId = @rOrgId OR @rOrgId = 0)
							AND (vSA.IsActiveBatch = 1)
							AND (OGM.Id = @rOrgId OR @rOrgId = 0)
							AND vSA.AcademicId = @rAcademicId	
							AND EAT.IsGuardianPresent = 1
							) AS Present,

			(SELECT COUNT(EAT.IsGuardianPresent)
			FROM 
							sStudent.vStudentAcademic vSA
							INNER JOIN sSetup.tClassMaster CM ON CM.Id = vSA.ClassId
							INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = vSA.DivisionId
							INNER JOIN sActivity.tEventAssign EA ON EA.SourceId=vSA.DivisionId AND EA.SourceTypeId=2005 
							--AND EA.EventScheduleId=@rEventScheduleId
							INNER JOIN sActivity.tEventAttendance EAT ON EAT.EventScheduleId = EA.EventScheduleId 
							AND EAT.SourceId = vSA.AcademicId AND EAT.SourceTypeId = 2001
							INNER JOIN sActivity.tEventSchedule ES ON ES.Id = EAT.EventScheduleId
							INNER JOiN [sActivity].[tEventTypeMaster] ETM ON ES.EventTypeId=ETM.Id 
							inner Join [sActivity].[tEventMainTypeMaster]  EMTM ON ETM.EventMainTypeId=EMTM.Id --AND EMTM.id=3
							INNER JOIN sSetup.tOrganizationMaster OM ON vSA.OrgId = OM.Id
							INNER JOIN sSetup.tOrgGroupMaster OGM ON OM.OrgGroupId = OGM.Id

						WHERE
							--(vSA.ClassId=0 OR 0=0)
							--AND (vSA.DivisionId=0 OR 0=0)
							(vSA.StatusId = 1)
							AND (vSA.OrgId = @rOrgId OR @rOrgId = 0)
							AND (vSA.IsActiveBatch = 1)
							AND (OGM.Id = @rOrgId OR @rOrgId = 0)
							AND vSA.AcademicId = @rAcademicId	
							AND EAT.IsGuardianPresent = 0
							) AS Absent


END
GO
PRINT N'Creating Procedure [sBiometric].[pBiometricTypeMasterAdd]...';


GO
CREATE PROCEDURE [sBiometric].[pBiometricTypeMasterAdd]
		
		@rStatus nvarchar(10),
		@rMainStatusId int,
		@rOrgGroupId int,
		@rUserId bigint

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

	if not exists (select 1 from [sBiometric].[tBiometricTypeMaster] WHERE OrgGroupId=@rOrgGroupId AND Status=@rStatus)
	BEGIN
		INSERT INTO [sBiometric].[tBiometricTypeMaster]
		(
			Status,
			MainStatusId,
			OrgGroupId,
			CreatedUserId,
			CreatedDateTime
		)
		VALUES
		(
			@rStatus,
			@rMainStatusId,
			@rOrgGroupId,
			@rUserId,
			sCommon.fGetDate()
		)

		SELECT 1 as Result
	END

	ELSE
	BEGIN
		UPDATE [sBiometric].[tBiometricTypeMaster]
		SET MainStatusId=@rMainStatusId,
			UpdtaedUserId=@rUserId,
			UpdatedDateTime=sCommon.fGetDate()
		WHERE Status=@rStatus
			AND OrgGroupId=@rOrgGroupId

		SELECT 11 as Result
	END

END
GO
PRINT N'Creating Procedure [sBiometric].[pBiometricTypeMasterGet]...';


GO
CREATE PROCEDURE [sBiometric].[pBiometricTypeMasterGet]
		
		@rOrgGroupId int

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	SELECT (case when Status='HD' then 'Half Day'
			when Status='E' then 'Error Case'
			when Status='H' then 'Holiday'
			when Status='XX' then 'Not Applicable'
			when Status='LH' then 'Less Hours'
			when Status='PH' then 'Present On WeekOff Holiday'
			when Status='W' then 'Week Offs' END) as TimeSheetStatus , 
			* 
	From [sBiometric].[tBiometricTypeMaster] 
	WHERE OrgGroupId=@rOrgGroupId
END
GO
PRINT N'Creating Procedure [sEMeeting].[pOnlineMeetingBatchGet]...';


GO

CREATE PROCEDURE [sEMeeting].[pOnlineMeetingBatchGet]
		@rOrgId int
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	BEGIN
	BEGIN TRY
		SELECT 
		Id,
		Title 
		FROM sSetup.tBatchMaster 
		WHERE IsObsolete = 0  
		AND IsHistory = 0  
		AND OrgId = @rOrgId 
		ORDER BY OrderIndex DESC
	END TRY
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
	END
GO
PRINT N'Creating Procedure [sEMeeting].[pOrderIndexMeetingTypeMasterGet]...';


GO

CREATE PROCEDURE [sEMeeting].[pOrderIndexMeetingTypeMasterGet]
@rOrgGroupId int
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	BEGIN
		BEGIN TRY
			SELECT ISNULL(MAX(OrderIndex),0)+1 AS Result FROM sEMeeting.tMeetingTypeMaster WHERE OrgGroupId = @rOrgGroupId
		END TRY
		BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH
	END
GO
PRINT N'Creating Procedure [sPurchase].[pDependentConfigurationGet]...';


GO


CREATE PROCEDURE [sPurchase].[pDependentConfigurationGet]
	  @rOrgId bigint,
	  @rOrgGroupId int,
	  @rUserId int,
	  @rScreenId int
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
		  SELECT CL.Title,
		       CM.Title AS ConfigTitle,
			   CM.ItemKey,
			   CASE WHEN  CS.ItemValue IS NULL THEN CM.ItemValue  ELSE Isnull(CS.ItemValue,0) END AS ItemValue  
	      FROM sConfig.tConfigurationMaster CM   
		  INNER JOIN  sConfig.tConfigurationLevelMaster CL ON CL.Id=CM.ConfigurationLevelId 
		  LEFT JOIN sConfig.tConfigurationSetup CS ON CM.Id=CS.ConfigurationId
		  AND  CS.SourceTypeId=(CASE  WHEN CL.Id =1 THEN 1016 wheN cl.Id=5 THEN 2010 when cL.Id=4 then 95   END) 
		  AND  CS.SourceId=(CASE  WHEN CL.Id =1 THEN @rOrgId wheN cl.Id=5 THEN @rOrgGroupId when cL.Id=5 then @rUserId END) 
		  WHERE  IsObsolete=0 AND ScreenId = @rScreenId 
		  ORDER BY CL.Id
	END TRY

	BEGIN CATCH
    IF @@TRANCOUNT > 0
        ROLLBACK TRAN --RollBack in case of Error
    
    DECLARE @ErrorMessage NVARCHAR(4000);  
    DECLARE @ErrorSeverity INT;  
    DECLARE @ErrorState INT;  
    SELECT   
       @ErrorMessage = ERROR_MESSAGE(),  
       @ErrorSeverity = ERROR_SEVERITY(),  
       @ErrorState = ERROR_STATE();  
    RAISERROR (@ErrorMessage, @ErrorSeverity, @ErrorState);  
    
	END CATCH
END
GO
PRINT N'Creating Procedure [sPurchase].[pDependentFunctionlityGet]...';


GO


CREATE PROCEDURE [sPurchase].[pDependentFunctionlityGet]
	  @rScreenId int
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
		SELECT ISNULL(DependentFunctionlity,'') AS DependentFunctionlity,
			   ISNULL(DependentConfiguration,'')  AS DependentConfiguration 
	     FROM  sSecurity.tScreenDependency WHERE ScreenId = @rScreenId
	END TRY

	BEGIN CATCH
    IF @@TRANCOUNT > 0
        ROLLBACK TRAN --RollBack in case of Error
    
    DECLARE @ErrorMessage NVARCHAR(4000);  
    DECLARE @ErrorSeverity INT;  
    DECLARE @ErrorState INT;  
    SELECT   
       @ErrorMessage = ERROR_MESSAGE(),  
       @ErrorSeverity = ERROR_SEVERITY(),  
       @ErrorState = ERROR_STATE();  
    RAISERROR (@ErrorMessage, @ErrorSeverity, @ErrorState);  
    
	END CATCH
END
GO
PRINT N'Creating Procedure [sPurchase].[pGetGRNReport]...';


GO

-- exec [sPurchase].[pGetGRNReport] 991100001
CREATE PROCEDURE [sPurchase].[pGetGRNReport]
   @rGoodsReceivedNoteId int
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
	DECLARE @HTMLTable NVARCHAR(MAX);

    
	Declare
	@rGRNNumber AS NVARCHAR(20),
	@rPurchaseRequestNumber AS NVARCHAR(20),
	@rPurchaseOrderNumber AS NVARCHAR(20),
	@rRequestedBy AS NVARCHAR(100),
	@rPODueDate AS NVARCHAR(100),
	@rStatus AS NVARCHAR(100),
	@rVendorName AS NVARCHAR(300),
	@rBillToAddress AS NVARCHAR(1000)
	
	    select  @rGRNNumber = ISNULL(GRN.GRNNumber,''),
				@rPurchaseRequestNumber = ISNULL(PR.Number,''),
				@rPurchaseOrderNumber = ISNULL(PO.RefNumber,''),
				@rRequestedBy = ISNULL(GRN.RequestedBy,''),
				@rPODueDate = ISNULL(GRN.PODueDate,''),
				@rStatus = ISNULL(SM.Title,''),
				@rVendorName = ISNULL(VM.Title,''),
				@rBillToAddress = ISNULL(GRN.BillToAddress,'')
		from   [sPurchase].[tGoodsReceivedNote] GRN(nolock) 
			   Left JOIN sProcurement.tVendorMaster  VM on GRN.VendorId = VM.ID
			   Left Join [sWf].[tWfStatusMaster] SM ON SM.Id = GRN.StatusId
			   Left Join [sPurchase].[tPurchaseRequest] PR ON PR.ID = GRN.PurchaseRequestId
			   Left Join [sPurchase].[tPurchaseOrder] PO On PO.Id = GRN.PurchaseOrderId
		where  GRN.Id = @rGoodsReceivedNoteId AND GRN.IsObsolete = 0


    SET @HTMLTable = '';
	if exists(select * from [sPurchase].[tGoodsReceivedNoteDetail] GRND
			where  GRND.GoodsReceivedNoteId = @rGoodsReceivedNoteId)
    Begin
    SET @HTMLTable = @HTMLTable + '<tr>';
    SET @HTMLTable = @HTMLTable + '<th>StockItemCode</th>';
    SET @HTMLTable = @HTMLTable + '<th>StockItemName</th>';
    SET @HTMLTable = @HTMLTable + '<th>Uom</th>';
    SET @HTMLTable = @HTMLTable + '<th>POQty</th>';
	SET @HTMLTable = @HTMLTable + '<th>ReceivedQty</th>';
	SET @HTMLTable = @HTMLTable + '<th>PreviousGRNQty</th>';
	SET @HTMLTable = @HTMLTable + '<th>UnitPrice</th>';
    SET @HTMLTable = @HTMLTable + '</tr>';

	Select @HTMLTable = @HTMLTable+'<tr><td>'+Cast(SIM.Code as Nvarchar(100))+'</td><td>'
+SIM.Title+'</td><td>'+SUMa.Code+'</td><td>'+Cast(GRND.POQty as Nvarchar(20))+'</td><td>'+Cast(GRND.ReceivedQty as Nvarchar(20))+'</td><td>'+Cast(GRND.PreviousGRNQty as Nvarchar(20))+'</td><td>'+Cast(GRND.UnitPrice as Nvarchar(20))+'</td></tr>'
	    from   [sPurchase].[tGoodsReceivedNoteDetail] GRND (nolock)
			   Inner JOIN	sPurchase.tPurchaseOrder PO	ON PO.Id = GRND.GoodsReceivedNoteId AND PO.IsObsolete = 0
			   Inner JOIN	sIp.tStockItemMaster SIM	ON SIM.Id = GRND.StockItemId 
			   Inner JOIN  sFinanceCommon.tStockUomMaster SUMa ON SUMa.Id = SIM.IssueStockUomId
		where  GRND.GoodsReceivedNoteId = @rGoodsReceivedNoteId
    End

select REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(Template, 
		'{GRNNumber}' , @rGRNNumber),
		'{PurchaseRequestNumber}' , @rPurchaseRequestNumber),
		'{PurchaseOrderNumber}' , @rPurchaseOrderNumber),
		'{RequestedBy}' , @rRequestedBy),
		'{Status}' , @rStatus),
		'{PODueDate}' , @rPODueDate),
		'{VendorName}' , @rVendorName),
		'{BillToAddress}' , @rBillToAddress),
		'{GoodsReceivedNoteDetails}' , ISNULL(@HTMLTable,''))

		as Template from sPurchase.tPurchaseReportTemplateMaster where Code='GRN' AND IsObsolete = 0


	END TRY

	BEGIN CATCH
    IF @@TRANCOUNT > 0
        ROLLBACK TRAN 

    
    DECLARE @ErrorMessage NVARCHAR(4000);  
    DECLARE @ErrorSeverity INT;  
    DECLARE @ErrorState INT;  

    SELECT   
       @ErrorMessage = ERROR_MESSAGE(),  
       @ErrorSeverity = ERROR_SEVERITY(),  
       @ErrorState = ERROR_STATE();  

    RAISERROR (@ErrorMessage, @ErrorSeverity, @ErrorState);  
    
	END CATCH
END
GO
PRINT N'Creating Procedure [sPurchase].[pGetIGReport]...';


GO

-- exec [sPurchase].[pGetIGReport] 991100001
CREATE PROCEDURE [sPurchase].[pGetIGReport]
   @rInvoiceGenerateId int
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
	DECLARE @HTMLTable NVARCHAR(MAX);

    
	Declare
	@rINVNumber AS NVARCHAR(20),
	@rGRNNumber AS NVARCHAR(20),
	@rRequestedBy AS NVARCHAR(100),
	@rStatus AS NVARCHAR(100),
	@rInvoiceDate AS NVARCHAR(100),
	@rInvoiceDueDate AS NVARCHAR(100),
	@rBillToAddress AS NVARCHAR(1000),
	@rShipToAddress AS NVARCHAR(1000),
	@rRemarks AS NVARCHAR(500),
	@rVendorCode AS NVARCHAR(100),
	@rVendorName AS NVARCHAR(300)
	
	    select  @rINVNumber = ISNULL(IG.INVNumber,''),
		        @rGRNNumber = ISNULL(GRN.GRNNumber,''),
				@rRequestedBy = ISNULL(IG.RequestedBy,''),
				@rStatus = ISNULL(SM.Title,''),
				@rInvoiceDate = ISNULL(IG.InvoiceDate,''),
		        @rInvoiceDueDate = ISNULL(IG.InvoiceDueDate,''),
				@rBillToAddress = ISNULL(IG.BillToAddress,''),
				@rShipToAddress = ISNULL(IG.ShipToAddress,''),
		        @rRemarks = ISNULL(IG.Remarks,''),
				@rVendorCode = ISNULL(VM.Code,''),
				@rVendorName = ISNULL(VM.Title,'')
		from   [sPurchase].[tInvoiceGenerate] IG(nolock)
		       Left JOIN sProcurement.tVendorMaster  VM on IG.VendorId = VM.ID
			   Left Join [sWf].[tWfStatusMaster] SM ON SM.Id = IG.StatusId
			   Left Join [sPurchase].[tGoodsReceivedNote] GRN ON GRN.Id = IG.GoodsReceivedNoteId
		where  IG.Id = @rInvoiceGenerateId AND IG.IsObsolete = 0


    SET @HTMLTable = '';
	if exists(select * from [sPurchase].[tInvoiceGenerateDetail] IGD
			where  IGD.InvoiceGenerateId = @rInvoiceGenerateId)

	Begin
    SET @HTMLTable = @HTMLTable + '<tr>';
    SET @HTMLTable = @HTMLTable + '<th>StockItemCode</th>';
    SET @HTMLTable = @HTMLTable + '<th>StockItemName</th>';
    SET @HTMLTable = @HTMLTable + '<th>Uom</th>';
    SET @HTMLTable = @HTMLTable + '<th>POQty</th>';
	SET @HTMLTable = @HTMLTable + '<th>ReceivedQty</th>';
	SET @HTMLTable = @HTMLTable + '<th>AcceptedQty</th>';
	SET @HTMLTable = @HTMLTable + '<th>RejectedQty</th>';
	SET @HTMLTable = @HTMLTable + '<th>ReasonForRejection</th>';
    SET @HTMLTable = @HTMLTable + '</tr>';

	Select @HTMLTable = @HTMLTable+'<tr><td>'+Cast(SIM.Code as Nvarchar(100))+'</td><td>'
+SIM.Title+'</td><td>'+SUMa.Code+'</td><td>'+Cast(IGD.POQty as Nvarchar(100))+'</td><td>'+Cast(IGD.ReceivedQty as Nvarchar(20))+'</td><td>'+Cast(IGD.AcceptedQty as Nvarchar(20))+'</td><td>'+Cast(IGD.RejectedQty as Nvarchar(20))+'</td><td>'+Cast(IGD.ReasonForRejection as Nvarchar(300))+'</td></tr>'
	    from   [sPurchase].[tInvoiceGenerateDetail] IGD(nolock)
			   Inner JOIN	sIp.tStockItemMaster SIM	ON SIM.Id = IGD.StockItemId 
			   Inner JOIN  sFinanceCommon.tStockUomMaster SUMa ON SUMa.Id = SIM.IssueStockUomId
		where  IGD.InvoiceGenerateId = @rInvoiceGenerateId
 
    End

select REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(Template, 
		'{INVNumber}' , @rINVNumber),
		'{GRNNumber}' , @rGRNNumber),
		'{RequestedBy}' , @rRequestedBy),
		'{Status}' , @rStatus),
		'{InvoiceDate}' , @rInvoiceDate),
		'{InvoiceDueDate}' , @rInvoiceDueDate),
		'{BillToAddress}' , @rBillToAddress),
		'{ShipToAddress}' , @rShipToAddress),
		'{Remarks}' , @rRemarks),
		'{VendorCode}' , @rVendorCode),
		'{VendorName}' , @rVendorName),
		'{InvoiceGenerateDetails}' , ISNULL(@HTMLTable,''))

		as Template from sPurchase.tPurchaseReportTemplateMaster where Code='IG' AND IsObsolete = 0


	END TRY

	BEGIN CATCH
    IF @@TRANCOUNT > 0
        ROLLBACK TRAN 

    
    DECLARE @ErrorMessage NVARCHAR(4000);  
    DECLARE @ErrorSeverity INT;  
    DECLARE @ErrorState INT;  

    SELECT   
       @ErrorMessage = ERROR_MESSAGE(),  
       @ErrorSeverity = ERROR_SEVERITY(),  
       @ErrorState = ERROR_STATE();  

    RAISERROR (@ErrorMessage, @ErrorSeverity, @ErrorState);  
    
	END CATCH
END
GO
PRINT N'Creating Procedure [sPurchase].[pGetQCReport]...';


GO

-- exec [sPurchase].[pGetQCReport] 991100001
CREATE PROCEDURE [sPurchase].[pGetQCReport]
   @rQualityCheckId int
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
	DECLARE @HTMLTable NVARCHAR(MAX);

    
	Declare
	@rQCNumber AS NVARCHAR(100),
	@rGRNNumber AS NVARCHAR(100),
	@rRequestedBy AS NVARCHAR(100),
	@rStatus AS NVARCHAR(100),
	@rQualityCheckDetails AS NVARCHAR(100)
	
	    select  @rQCNumber = ISNULL(QC.QCNumber,''),
		        @rGRNNumber = ISNULL(GRN.GRNNumber,''),
				@rRequestedBy = ISNULL(QC.RequestedBy,''),
				@rStatus = ISNULL(SM.Title,'')
		from   [sPurchase].[tQualityCheck] QC(nolock)
			   Left Join [sWf].[tWfStatusMaster] SM ON SM.Id = QC.StatusId
			   Left Join [sPurchase].[tGoodsReceivedNote] GRN ON GRN.Id = QC.GoodsReceivedNoteId
		where  QC.Id = @rQualityCheckId AND QC.IsObsolete = 0


    SET @HTMLTable = '';
	if exists(select *  from [sPurchase].[tQualityCheckDetail] QCD
			where QCD.QualityCheckId = @rQualityCheckId)
	Begin
    SET @HTMLTable = @HTMLTable + '<tr>';
    SET @HTMLTable = @HTMLTable + '<th>StockItemCode</th>';
    SET @HTMLTable = @HTMLTable + '<th>StockItemName</th>';
    SET @HTMLTable = @HTMLTable + '<th>Uom</th>';
    SET @HTMLTable = @HTMLTable + '<th>POQty</th>';
	SET @HTMLTable = @HTMLTable + '<th>ReceivedQty</th>';
	SET @HTMLTable = @HTMLTable + '<th>AcceptedQty</th>';
	SET @HTMLTable = @HTMLTable + '<th>RejectedQty</th>';
	SET @HTMLTable = @HTMLTable + '<th>ReasonForRejection</th>';
    SET @HTMLTable = @HTMLTable + '</tr>';

	Select @HTMLTable = @HTMLTable+'<tr><td>'+Cast(SIM.Code as Nvarchar(100))+'</td><td>'
+SIM.Title+'</td><td>'+SUMa.Code+'</td><td>'+Cast(QCD.POQty as Nvarchar(100))+'</td><td>'+Cast(QCD.ReceivedQty as Nvarchar(100))+'</td><td>'+Cast(QCD.AcceptedQty as Nvarchar(100))+'</td><td>'+Cast(QCD.RejectedQty as Nvarchar(100))+'</td><td>'+Cast(QCD.ReasonForRejection as Nvarchar(100))+'</td></tr>'
	    from   [sPurchase].[tQualityCheckDetail] QCD (nolock)
			   Inner JOIN	sIp.tStockItemMaster SIM	ON SIM.Id = QCD.StockItemId 
			   Inner JOIN  sFinanceCommon.tStockUomMaster SUMa ON SUMa.Id = SIM.IssueStockUomId
		where  QCD.QualityCheckId = @rQualityCheckId
    End

select REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(Template, 
		'{QCNumber}' , @rQCNumber),
		'{GRNNumber}' , @rGRNNumber),
		'{RequestedBy}' , @rRequestedBy),
		'{Status}' , @rStatus),
		'{QualityCheckDetails}' , ISNULL(@HTMLTable,''))

		as Template from sPurchase.tPurchaseReportTemplateMaster where Code='QC' AND IsObsolete = 0


	END TRY

	BEGIN CATCH
    IF @@TRANCOUNT > 0
        ROLLBACK TRAN 

    
    DECLARE @ErrorMessage NVARCHAR(4000);  
    DECLARE @ErrorSeverity INT;  
    DECLARE @ErrorState INT;  

    SELECT   
       @ErrorMessage = ERROR_MESSAGE(),  
       @ErrorSeverity = ERROR_SEVERITY(),  
       @ErrorState = ERROR_STATE();  

    RAISERROR (@ErrorMessage, @ErrorSeverity, @ErrorState);  
    
	END CATCH
END
GO
PRINT N'Creating Procedure [sPurchase].[pGetQRReport]...';


GO

-- exec [sPurchase].[pGetQRReport] 991100004
CREATE PROCEDURE [sPurchase].[pGetQRReport]
   @rQuotationRequestId int
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
	DECLARE @HTMLTable NVARCHAR(MAX);

    
	Declare
	@rNumber AS NVARCHAR(20),
	@rName AS NVARCHAR(100),
	@rRFQDate AS NVARCHAR(100),
	@rStatus AS NVARCHAR(100),
	@rDescription AS NVARCHAR(300),
	@rStartDate AS NVARCHAR(100),
	@rEndDate AS NVARCHAR(100),
	@rBidOpen AS NVARCHAR(50),
	@rBidClose AS NVARCHAR(50),
	@rPersonContact AS NVARCHAR(50),
	@rEmail AS NVARCHAR(50),
	@rSendToVendor AS NVARCHAR(10),
	@rVendorCode AS NVARCHAR(100),
	@rVendorName AS NVARCHAR(300),
	@rPurchaseNumber AS NVARCHAR(20)
	
	    select  @rNumber = ISNULL(QR.Number,''),
		        @rName = ISNULL(QR.Name,''),
				@rRFQDate = ISNULL(QR.RFQDate,''),
				@rStatus = ISNULL(SM.Title,''),
				@rDescription = ISNULL(QR.Description,''),
		        @rStartDate = ISNULL(QR.StartDate,''),
				@rEndDate = ISNULL(QR.EndDate,''),
				@rBidOpen = ISNULL(QR.BidOpen,''),
		        @rBidClose = ISNULL(QR.BidClose,''),
				@rPersonContact = ISNULL(QR.PersonContact,''),
				@rEmail = ISNULL(QR.Email,''),
		        @rSendToVendor = ISNULL(QR.SendToVendor,''),
				@rVendorCode = ISNULL(VM.Code,''),
				@rVendorName = ISNULL(VM.Title,''),
				@rPurchaseNumber = ISNULL(PR.Number,'')
		from   [sPurchase].[tQuotationRequest] QR(nolock)
		       Left JOIN sProcurement.tVendorMaster  VM on QR.VendorId = VM.ID
			   Left Join [sWf].[tWfStatusMaster] SM ON SM.Id = QR.StatusId
			   Left Join [sPurchase].[tPurchaseRequest] PR on PR.Id = QR.PurchaseRequestId
		where  QR.Id = @rQuotationRequestId AND QR.IsObsolete = 0


    SET @HTMLTable = '';

	if exists(select * from  [sPurchase].[tQuotationRequestDetail] QRD
			where  QRD.QuotationRequestId = @rQuotationRequestId)
	Begin
		SET @HTMLTable = @HTMLTable + '<tr>';
		SET @HTMLTable = @HTMLTable + '<th>StockItemCode</th>';
		SET @HTMLTable = @HTMLTable + '<th>StockItemName</th>';
		SET @HTMLTable = @HTMLTable + '<th>Uom</th>';
		SET @HTMLTable = @HTMLTable + '<th>RequestedQty</th>';
		SET @HTMLTable = @HTMLTable + '<th>TargetPrice</th>';
		SET @HTMLTable = @HTMLTable + '<th>Remark</th>';
		SET @HTMLTable = @HTMLTable + '</tr>';

		Select @HTMLTable = @HTMLTable+'<tr><td>'+Cast(SIM.Code as Nvarchar(100))+'</td><td>'
	+SIM.Title+'</td><td>'+SUMa.Code+'</td><td>'+Cast(QRD.RequestedQty as Nvarchar(20))+'</td><td>'+Cast(QRD.TargetPrice as Nvarchar(20))+'</td><td>'+Cast(QRD.Remark as Nvarchar(300))+'</td></tr>'
			from   [sPurchase].[tQuotationRequestDetail] QRD(nolock)
				   Inner JOIN	sIp.tStockItemMaster SIM	ON SIM.Id = QRD.StockItemId 
				   Inner JOIN  sFinanceCommon.tStockUomMaster SUMa ON SUMa.Id = SIM.IssueStockUomId
			where  QRD.QuotationRequestId = @rQuotationRequestId
	End
 

select REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(Template, 
		'{Number}' , @rNumber),
		'{Name}' , @rName),
		'{RFQDate}' , @rRFQDate),
		'{Status}' , @rStatus),
		'{Description}' , @rDescription),
		'{StartDate}' , @rStartDate),
		'{EndDate}' , @rEndDate),
		'{BidOpen}' , @rBidOpen),
		'{BidClose}' , @rBidClose),
		'{PersonContact}' , @rPersonContact),
		'{Email}' , @rEmail),
		'{SendToVendor}' , @rSendToVendor),
		'{VendorCode}' , @rVendorCode),
		'{VendorName}' , @rVendorName),
		'{PurchaseNumber}' , @rPurchaseNumber),
		'{QuotationRequestDetails}' , ISNULL(@HTMLTable,''))

		as Template from sPurchase.tPurchaseReportTemplateMaster where Code='QR' AND IsObsolete = 0


	END TRY

	BEGIN CATCH
    IF @@TRANCOUNT > 0
        ROLLBACK TRAN 

    
    DECLARE @ErrorMessage NVARCHAR(4000);  
    DECLARE @ErrorSeverity INT;  
    DECLARE @ErrorState INT;  

    SELECT   
       @ErrorMessage = ERROR_MESSAGE(),  
       @ErrorSeverity = ERROR_SEVERITY(),  
       @ErrorState = ERROR_STATE();  

    RAISERROR (@ErrorMessage, @ErrorSeverity, @ErrorState);  
    
	END CATCH
END
GO
PRINT N'Creating Procedure [sPurchase].[pGetSRReport]...';


GO
-- select * from sPurchase.tPurchaseReportTemplate where id=6
-- exec [sPurchase].[pGetSRReport] 991100001
CREATE PROCEDURE [sPurchase].[pGetSRReport]
   @rSalesReturnId int
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
	DECLARE @HTMLTable NVARCHAR(MAX);

    
	Declare
	@rSRNumber AS NVARCHAR(20),
	@rGRNNumber AS NVARCHAR(20),
	@rRequestedBy AS NVARCHAR(100),
	@rStatus AS NVARCHAR(100),
	@rVendorName AS NVARCHAR(300),
	@rPurchaseOrderNumber AS NVARCHAR(20)
	
	    select  @rSRNumber = ISNULL(SR.SRNumber,''),
		        @rGRNNumber = ISNULL(GRN.GRNNumber,''),
				@rRequestedBy = ISNULL(SR.RequestedBy,''),
				@rStatus = ISNULL(SM.Title,''),
				@rVendorName = ISNULL(VM.Title,''),
				@rPurchaseOrderNumber = ISNULL(PO.RefNumber,'')
		from   [sPurchase].[tSalesReturn] SR(nolock)
		       Left JOIN sProcurement.tVendorMaster  VM on SR.VendorId = VM.ID
			   Left Join [sWf].[tWfStatusMaster] SM ON SM.Id = SR.StatusId
			   Left Join [sPurchase].[tGoodsReceivedNote] GRN ON GRN.Id = SR.GoodsReceivedNoteId
			   Left Join [sPurchase].[tPurchaseOrder] PO On PO.Id = SR.PurchaseOrderId
		where  SR.Id = @rSalesReturnId AND SR.IsObsolete = 0


    SET @HTMLTable = '';
	if exists(select *  from   [sPurchase].[tSalesReturnDetail] SRD
			where  SRD.SalesReturnId = @rSalesReturnId)
    Begin
    SET @HTMLTable = @HTMLTable + '<tr>';
    SET @HTMLTable = @HTMLTable + '<th>StockItemCode</th>';
    SET @HTMLTable = @HTMLTable + '<th>StockItemName</th>';
    SET @HTMLTable = @HTMLTable + '<th>Uom</th>';
    SET @HTMLTable = @HTMLTable + '<th>POQty</th>';
	SET @HTMLTable = @HTMLTable + '<th>ReceivedQty</th>';
	SET @HTMLTable = @HTMLTable + '<th>RejectedQty</th>';
	SET @HTMLTable = @HTMLTable + '<th>CreditNoteIssueDate</th>';
	SET @HTMLTable = @HTMLTable + '<th>ReasonForRejection</th>';
    SET @HTMLTable = @HTMLTable + '</tr>';

	Select @HTMLTable = @HTMLTable+'<tr><td>'+Cast(SIM.Code as Nvarchar(100))+'</td><td>'
+SIM.Title+'</td><td>'+SUMa.Code+'</td><td>'+Cast(SRD.POQty as Nvarchar(20))+'</td><td>'+Cast(SRD.ReceivedQty as Nvarchar(20))+'</td><td>'+Cast(SRD.RejectedQty as Nvarchar(20))+'</td><td>'+Cast(SRD.CreditNoteIssueDate as Nvarchar(100))+'</td><td>'+Cast(SRD.ReasonForRejection as Nvarchar(300))+'</td></tr>'
	    from   [sPurchase].[tSalesReturnDetail] SRD(nolock)
			   Inner JOIN	sIp.tStockItemMaster SIM	ON SIM.Id = SRD.StockItemId 
			   Inner JOIN  sFinanceCommon.tStockUomMaster SUMa ON SUMa.Id = SIM.IssueStockUomId
		where  SRD.SalesReturnId = @rSalesReturnId
 
   End
select REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(Template, 
		'{SRNumber}' , @rSRNumber),
		'{GRNNumber}' , @rGRNNumber),
		'{RequestedBy}' , @rRequestedBy),
		'{Status}' , @rStatus),
		'{VendorName}' , @rVendorName),
		'{PurchaseOrderNumber}' , @rPurchaseOrderNumber),
		'{SalesReturnDetails}' , ISNULL(@HTMLTable,''))

		as Template from sPurchase.tPurchaseReportTemplateMaster where Code='SR' AND IsObsolete = 0


	END TRY

	BEGIN CATCH
    IF @@TRANCOUNT > 0
        ROLLBACK TRAN 

    
    DECLARE @ErrorMessage NVARCHAR(4000);  
    DECLARE @ErrorSeverity INT;  
    DECLARE @ErrorState INT;  

    SELECT   
       @ErrorMessage = ERROR_MESSAGE(),  
       @ErrorSeverity = ERROR_SEVERITY(),  
       @ErrorState = ERROR_STATE();  

    RAISERROR (@ErrorMessage, @ErrorSeverity, @ErrorState);  
    
	END CATCH
END
GO
PRINT N'Creating Procedure [sPurchase].[pHelperPopUpGet]...';


GO


CREATE PROCEDURE [sPurchase].[pHelperPopUpGet]
	  @rScreenId smallint
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
		Select Isnull(HelpDescription,'')
		 from sSecurity.tScreenHelp 
		 WHERE ScreenId = @rScreenId
	END TRY

	BEGIN CATCH
    IF @@TRANCOUNT > 0
        ROLLBACK TRAN --RollBack in case of Error
    
    DECLARE @ErrorMessage NVARCHAR(4000);  
    DECLARE @ErrorSeverity INT;  
    DECLARE @ErrorState INT;  
    SELECT   
       @ErrorMessage = ERROR_MESSAGE(),  
       @ErrorSeverity = ERROR_SEVERITY(),  
       @ErrorState = ERROR_STATE();  
    RAISERROR (@ErrorMessage, @ErrorSeverity, @ErrorState);  
    
	END CATCH
END
GO
PRINT N'Creating Procedure [sPurchase].[pMasterBatchGet]...';


GO


CREATE PROCEDURE [sPurchase].[pMasterBatchGet]
	  @rOrgId int
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
		SELECT Id,
			   Title 
	     FROM  sSetup.tBatchMaster 
		 WHERE IsObsolete = 0 
		 AND IsHistory = 0 
		 AND OrgId = @rOrgId 
		 ORDER BY OrderIndex DESC
	END TRY

	BEGIN CATCH
    IF @@TRANCOUNT > 0
        ROLLBACK TRAN --RollBack in case of Error
    
    DECLARE @ErrorMessage NVARCHAR(4000);  
    DECLARE @ErrorSeverity INT;  
    DECLARE @ErrorState INT;  
    SELECT   
       @ErrorMessage = ERROR_MESSAGE(),  
       @ErrorSeverity = ERROR_SEVERITY(),  
       @ErrorState = ERROR_STATE();  
    RAISERROR (@ErrorMessage, @ErrorSeverity, @ErrorState);  
    
	END CATCH
END
GO
PRINT N'Creating Procedure [sPurchase].[pMasterOrganizationGet]...';


GO


CREATE PROCEDURE [sPurchase].[pMasterOrganizationGet]
	  @rOrgGroupId int,
	  @rUserId bigint
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
		SELECT Id,
			   DisplayTitle as Title 
		FROM  sSetup.vUserOrganization 
		WHERE IsObsolete = 0 
		AND OrgGroupId = @rOrgGroupId 
		AND UserId = @rUserId 
		ORDER BY OrderIndex
	END TRY

	BEGIN CATCH
    IF @@TRANCOUNT > 0
        ROLLBACK TRAN --RollBack in case of Error
    
    DECLARE @ErrorMessage NVARCHAR(4000);  
    DECLARE @ErrorSeverity INT;  
    DECLARE @ErrorState INT;  
    SELECT   
       @ErrorMessage = ERROR_MESSAGE(),  
       @ErrorSeverity = ERROR_SEVERITY(),  
       @ErrorState = ERROR_STATE();  
    RAISERROR (@ErrorMessage, @ErrorSeverity, @ErrorState);  
    
	END CATCH
END
GO
PRINT N'Creating Procedure [sPurchase].[pPOPurchaseRequestDetailGet]...';


GO

--exec [sPurchase].[pPOPurchaseRequestDetailGet] 991100002
CREATE PROCEDURE [sPurchase].[pPOPurchaseRequestDetailGet]
	  @rId int
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
		select PRD.Id,
			   PRD.PurchaseRequestId,
			   PRD.OrgGroupId,
			   PRD.StockItemId,
			   PRD.RequestedQty,
			   PRD.Remark, 
			   SIM.Code	AS StockItemCode,
			   SCM.Title AS CategoryName,
			   SIM.Title AS StockItemName,
			   SUMa.Code AS UOM
		from   [sPurchase].[tPurchaseRequestDetail] PRD (nolock)
			   Inner JOIN	sPurchase.tPurchaseRequest PR	ON PR.Id = PRD.PurchaseRequestId AND PR.IsObsolete = 0 AND PR.StatusId = 3
			   Inner JOIN	sIp.tStockItemMaster SIM	ON SIM.Id = PRD.StockItemId 
			   LEFT JOIN [sIp].[tStockItemCategoryMaster] SCM ON SCM.Id = SIM.StockItemCategoryId
			   Inner JOIN  sFinanceCommon.tStockUomMaster SUMa ON SUMa.Id = SIM.IssueStockUomId
		where  PurchaseRequestId=@rId
	END TRY

	BEGIN CATCH
    IF @@TRANCOUNT > 0
        ROLLBACK TRAN --RollBack in case of Error
    
    DECLARE @ErrorMessage NVARCHAR(4000);  
    DECLARE @ErrorSeverity INT;  
    DECLARE @ErrorState INT;  
    SELECT   
       @ErrorMessage = ERROR_MESSAGE(),  
       @ErrorSeverity = ERROR_SEVERITY(),  
       @ErrorState = ERROR_STATE();  
    RAISERROR (@ErrorMessage, @ErrorSeverity, @ErrorState);  
    
	END CATCH

END
GO
PRINT N'Creating Procedure [sPurchase].[pPurchaseRequestPOApprovedSearchGet]...';


GO

--exec [sPurchase].[pPurchaseRequestPOApprovedSearchGet] '',991100001,'',9911,'2023-01-01','2023-12-18',1,10,null
CREATE PROCEDURE [sPurchase].[pPurchaseRequestPOApprovedSearchGet]

	@rNumber nvarchar(30) = '',
	@rLocationId int,
	@rName nvarchar = '',
	@rOrgGroupId int,
	@rStartDate DateTime = null,
	@rEndDate DateTime = null,
	@rPageNo int,
	@rPageSize int,
	@rStatusId smallint = 0

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY

		DECLARE @TotalRecords BIGINT;
		-- Get the total number of records
		SELECT @TotalRecords = COUNT(Distinct PR.Id) FROM sPurchase.tPurchaseRequest PR (nolock)
		Left Join [sWf].[tWfStatusMaster] SM on PR.StatusId = SM.Id
		Inner Join [sPurchase].[tQuotationRequest] QR on QR.PurchaseRequestId = PR.Id AND QR.StatusId = 3
		Left Join sProcurement.tVendorMaster  VM on QR.VendorId = VM.ID

		WHERE 
				((PR.Number like @rNumber+'%') OR (ISNULL(@rNumber,'') = ''))
   				AND ((PR.RequestedBy like @rName+'%') OR (ISNULL(@rName,'') = ''))
   				--AND ((SLM.Id = @rStoreLocationId) OR (@rStoreLocationId = 0))
   				AND ((PR.OrgGroupId = @rOrgGroupId) OR (@rOrgGroupId=0))
				AND ((PR.StatusId = @rStatusId) OR (ISNULL(@rStatusId,0)=0))
				AND PR.IsObsolete = 0 and PR.StatusId = 3
				AND ((Cast(PR.CreatedDateTime as Date) >= Cast(@rStartDate as Date)) OR (ISNULL(@rStartDate,'')=''))
				AND((Cast(PR.CreatedDateTime as Date) <= Cast(@rEndDate as Date)) OR (ISNULL(@rEndDate,'')=''))


		Select t.* From (
			Select ROW_NUMBER() Over (
			Order by PR.Id desc  
			) AS 'RowNum',PR.Id, 
				PR.Number,
				PR.RequestedBy, 
				PR.LocationId, 
				PR.RequestDate,
				ISNULL(SM.Title,'') as Status,
				VM.Id as VendorId,
				VM.Code AS VendorCode,
				VM.Title AS VendorName
	    FROM		
				sPurchase.tPurchaseRequest PR (nolock)
				Left Join [sWf].[tWfStatusMaster] SM on PR.StatusId = SM.Id
				Inner Join [sPurchase].[tQuotationRequest] QR on QR.PurchaseRequestId = PR.Id AND QR.StatusId = 3
			    Left Join sProcurement.tVendorMaster  VM on QR.VendorId = VM.ID

        WHERE 
				((PR.Number like @rNumber+'%') OR (ISNULL(@rNumber,'') = ''))
   				AND ((PR.RequestedBy like @rName+'%') OR (ISNULL(@rName,'') = ''))
   				--AND ((SLM.Id = @rStoreLocationId) OR (@rStoreLocationId = 0))
   				AND ((PR.OrgGroupId = @rOrgGroupId) OR (@rOrgGroupId=0))
				AND ((PR.StatusId = @rStatusId) OR (ISNULL(@rStatusId,0)=0))
				AND PR.IsObsolete = 0 and PR.StatusId = 3 
				--AND Pr.Id in (select distinct PR.Id from sPurchase.tPurchaseRequest PR
				--Inner Join [sPurchase].[tQuotationRequest] QR on QR.PurchaseRequestId = PR.Id AND QR.StatusId = 3)
				AND ((Cast(PR.CreatedDateTime as Date) >= Cast(@rStartDate as Date)) OR (ISNULL(@rStartDate,'')=''))
				AND((Cast(PR.CreatedDateTime as Date) <= Cast(@rEndDate as Date)) OR (ISNULL(@rEndDate,'')='')))t Where t.RowNum Between
		        ((@rPageNo-1)*@rPageSize +1) AND (@rPageNo*@rpageSize)

		

        SELECT @TotalRecords as TotalRecords
	 END TRY

	BEGIN CATCH
    IF @@TRANCOUNT > 0
        ROLLBACK TRAN --RollBack in case of Error
    
    DECLARE @ErrorMessage NVARCHAR(4000);  
    DECLARE @ErrorSeverity INT;  
    DECLARE @ErrorState INT;  
    SELECT   
       @ErrorMessage = ERROR_MESSAGE(),  
       @ErrorSeverity = ERROR_SEVERITY(),  
       @ErrorState = ERROR_STATE();  
    RAISERROR (@ErrorMessage, @ErrorSeverity, @ErrorState);  
    
	END CATCH  		  
END
GO
PRINT N'Creating Procedure [sPurchase].[pQuotationApprovedVendorGet]...';


GO

--exec sPurchase.pQuotationApprovedVendorGet 991100002,991100001,9911
CREATE PROCEDURE sPurchase.pQuotationApprovedVendorGet
	@rPurchaseRequestId bigint = 0,
	@rLocationId int = 0,
	@rOrgGroupId int

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY

		Select 
		        QR.Id,
		        QR.Number,
				QR.Name,
				QR.PurchaseRequestId, 
				QR.VendorId,
				ISNULL(VM.Title,'') AS VendorName,
				ISNULL(VM.Code,'') AS VendorCode

	    FROM		
				sPurchase.tPurchaseRequest PR  (nolock)
				Inner Join sPurchase.tQuotationRequest QR on QR.PurchaseRequestId = PR.Id and QR.StatusId = 3
				Left JOIN sProcurement.tVendorMaster  VM on QR.VendorId = VM.ID


        WHERE 
   				((PR.OrgGroupId = @rOrgGroupId) OR (@rOrgGroupId=0))
   				AND ((PR.LocationId = @rLocationId) OR (@rLocationId=0))
				AND ((PR.Id = @rPurchaseRequestId) OR (ISNULL(@rPurchaseRequestId,0)=0))
				AND PR.IsObsolete = 0 AND PR.StatusId = 3 AND QR.IsObsolete = 0

   
	 END TRY

	BEGIN CATCH
    IF @@TRANCOUNT > 0
        ROLLBACK TRAN --RollBack in case of Error
    
    DECLARE @ErrorMessage NVARCHAR(4000);  
    DECLARE @ErrorSeverity INT;  
    DECLARE @ErrorState INT;  
    SELECT   
       @ErrorMessage = ERROR_MESSAGE(),  
       @ErrorSeverity = ERROR_SEVERITY(),  
       @ErrorState = ERROR_STATE();  
    RAISERROR (@ErrorMessage, @ErrorSeverity, @ErrorState);  
    
	END CATCH  		  
END
GO
PRINT N'Creating Procedure [sPurchase].[pSearchScreenDependencyGet]...';


GO


CREATE PROCEDURE [sPurchase].[pSearchScreenDependencyGet]
	  @rScreenId int
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
		SELECT SH.ScreenId, 
				SH.IsUpload, 
				SH.UploadRemark, 
				SH.IsExport, 
				SH.ExportRemark, 
				SH.IsImport, 
				SH.ImportRemark 
		FROM   [sSecurity].[tScreenHelp] SH 
		INNER JOIN [sSecurity].[tScreen] S ON S.Id = SH.ScreenId 
		WHERE SH.ScreenId = @rScreenId
	END TRY

	BEGIN CATCH
    IF @@TRANCOUNT > 0
        ROLLBACK TRAN --RollBack in case of Error
    
    DECLARE @ErrorMessage NVARCHAR(4000);  
    DECLARE @ErrorSeverity INT;  
    DECLARE @ErrorState INT;  
    SELECT   
       @ErrorMessage = ERROR_MESSAGE(),  
       @ErrorSeverity = ERROR_SEVERITY(),  
       @ErrorState = ERROR_STATE();  
    RAISERROR (@ErrorMessage, @ErrorSeverity, @ErrorState);  
    
	END CATCH
END
GO
PRINT N'Creating Procedure [sPurchase].[pStockBatchAddModify]...';


GO
--exec [sPurchase].[pStockBatchAddModify] 9911,991100001,991100001,100,'+',9911000000270
CREATE PROCEDURE [sPurchase].[pStockBatchAddModify]
	@rOrgGroupId [int], 
	@rStoreLocationId [int] = 0,
	@rStockItemId [int] = 0,
	@rQuantity decimal(12,2) = 0.00,
	@rOperation nvarchar(20),
	@rUserId [bigint]
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

       DECLARE @1AvailableQuantity Decimal(12,2) 

BEGIN      
    IF Exists(Select Id from sProcurement.tStockBatch where Id = @rStockItemId)
	Begin
		IF(@rOperation = '+')
		Begin
			 UPDATE  sProcurement.tStockBatch
			 SET  AvailableQuantity = ISNULL(AvailableQuantity,0) + @rQuantity,
				  UpdatedUserId = @rUserId,
				  UpdatedDateTime = sCommon.fGetDate()
			 FROM sProcurement.tStockBatch
			 WHERE  
			(StoreLocationId = @rStoreLocationId OR @rStoreLocationId = 0) AND
			(StockItemId = @rStockItemId OR @rStockItemId = 0) AND
			--(Number = @rNumber OR ISNULL(@rNumber, '') = '') AND
			--(ExpiryDate = @rExpiryDate OR ISNULL(@rExpiryDate, '') = '') AND
			 OrgGroupId = @rOrgGroupId
		End
		Else
		Begin
			UPDATE  sProcurement.tStockBatch
			 SET  AvailableQuantity = ISNULL(AvailableQuantity,0) - @rQuantity,
				  UpdatedUserId = @rUserId,
				  UpdatedDateTime = sCommon.fGetDate()
			 FROM sProcurement.tStockBatch
			 WHERE  
			(StoreLocationId = @rStoreLocationId OR @rStoreLocationId = 0) AND
			(StockItemId = @rStockItemId OR @rStockItemId = 0) AND
			--(Number = @rNumber OR ISNULL(@rNumber, '') = '') AND
			--(ExpiryDate = @rExpiryDate OR ISNULL(@rExpiryDate, '') = '') AND
			 OrgGroupId = @rOrgGroupId
		End
	End
END
GO
PRINT N'Creating Procedure [sPurchase].[pStockItemMasterSearchGet]...';


GO
--exec [sPurchase].[pStockItemMasterSearchGet] 991100001,'c'
CREATE PROCEDURE [sPurchase].[pStockItemMasterSearchGet]
	
	@rLocationId int ,
	@rCurrentAlphabet nvarchar(10) 

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
		 
	SELECT
			Id,
			Code,
			Title from sIp.tStockItemMaster 
	   
	  WHERE  
		 ((Title Like @rCurrentAlphabet + '%') OR (ISNULL(@rCurrentAlphabet,'')=''))
	   AND ((LocationId = @rLocationId) OR (ISNULL(@rLocationId,0)=0)) 
	   AND IsObsolete= 0
	  
	 
END
GO
PRINT N'Creating Procedure [sPurchase].[pVendorNotificationGet]...';


GO

 
--exec [sPurchase].[pVendorNotificationGet] 991100022,'',9911
CREATE PROCEDURE [sPurchase].[pVendorNotificationGet]
	     
		 @rQuotationRequestId bigint,
		 @rNotificationLink nvarchar(1000),
		 @rOrgId smallint

	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

	


		Declare @VendorId bigint
		Select @VendorId = QR.VendorId from sPurchase.tQuotationRequest QR Where QR.Id = @rQuotationRequestId AND QR.IsObsolete = 0

		set @rNotificationLink = '<a href="'+@rNotificationLink+'" target="_blank">'+@rNotificationLink+'</a>'
		    
	declare @txtMessage nvarchar(Max)
    select @txtMessage=REPLACE(REPLACE(Template, 
		'[VendorName]' , (SELECT VM.ContactPersonName as Name	
						FROM	sProcurement.tVendorMaster  VM
						WHERE VM.Id = @VendorId)),
		'[NotificationLink]' , @rNotificationLink) from sAlert.tEventTemplate WHERE IsAutoSend = 1 AND OrgId = @rOrgId AND EventId = 158
	
	SELECT 
			--A.AcademicId,
			A.Code,
			A.Name,
			A.ParentContactNo AS MobileNo,	
			A.ParentEmail AS EmailId,
			@txtMessage	AS MsgText,
			'' AS Subject,
			 2001 AS ReceiverSourceTypeId,
			 (SELECT Id FROM sSetup.tOrganizationMaster where OrgGroupId=A.OrgGroupId and Id = A.OrgGroupId) AS OrgId,
			 A.OrgGroupId AS OrgGroupId,
			 A.Id AS ReceiverSourceId,
			 A.Id AS SourceId,
			 2001 AS SourceTypeId,
			 --DM.Title AS MeetingType,
			 --CONVERT(varchar(11),ISNULL(OM.StartDate,'') ,103) AS StartDate,
			 --CONVERT(varchar(11),ISNULL(OM.EndDate,'') ,103) AS EndDate,
			 --EE.EmployeeName AS Teacher,
			 --OM.Title AS Title,
			 A.WhatsAppContactNo
	FROM 
		 [sPurchase].[tQuotationRequestDetail] QRD (nolock)
		Inner JOIN	sPurchase.tQuotationRequest QR	ON QR.Id = QRD.QuotationRequestId AND QR.IsObsolete = 0
		Inner JOIN	sIp.tStockItemMaster SIM	ON SIM.Id = QRD.StockItemId 
		Inner JOIN  sFinanceCommon.tStockUomMaster SUMa ON SUMa.Id = SIM.IssueStockUomId
		INNER JOIN (
			SELECT	VM.Id,
					VM.ContactPersonName as Name,
					VM.Code,
					VM.PhoneNumberOffice as ParentContactNo,
					VM.Email as ParentEmail,
					VM.OrgGroupId,
					VM.PhoneNumberMobile WhatsAppContactNo		
			FROM	sProcurement.tVendorMaster  VM
			LEFT JOIN   sProcurement.tVendorCategoryMaster VC
			ON  VM.VendorCategoryId = VC.Id
			WHERE VM.Id = @VendorId
		) as A ON A.Id = QR.VendorId
		where  QR.Id = @rQuotationRequestId
END
GO
PRINT N'Creating Procedure [sStudent].[pImportStudentLakshya]...';


GO
CREATE PROCEDURE sStudent.pImportStudentLakshya
	@rOrgGroupId SMALLINT
	,@rOrgId SMALLINT
	,@rXmldoc [nvarchar] (max)
	,@rUserId BIGINT
	,@rBatchId INT
	,@rOrgGroupBatchId INT
	,@rOperation INT = 0 --1 For Insert,2 For Update

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
		DECLARE @lCount INT
			,@lInterrorCode INT
			,@intDoc INT
			,@lCode NVARCHAR(20)
			,@lNumber BIGINT
			,@lRegistrationNumber NVARCHAR(20)
			,@lFirstName NVARCHAR(100)
			,@lMiddleName NVARCHAR(100)
			,@lLastName NVARCHAR(100)
			,@lClassId INT
			,@lClass NVARCHAR(100)
			,@lDivisionId INT
			,@lDivision NVARCHAR(100)
			,@lRollNo INT
			,@lAdmissionStandardId INT
			,@lAdmissionStandard NVARCHAR(100)
			,@lAdmissionDate DATE
			,@lPreviousSchool NVARCHAR(200)
			,@lDOB DATE
			,@lGenderId INT = 0
			,@lGender NVARCHAR(10)
			,@lBloodGroupId INT = 0
			,@lBloodGroup NVARCHAR(10)
			,@lAdmissionCategoryId INT
			,@lReligionId INT
			,@lReligion NVARCHAR(100)
			,@lFamilyCast NVARCHAR(100)
			,@lFamilySubCast NVARCHAR(100)
			,@lCastCategoryId INT = 0
			,@lCastCategory NVARCHAR(100)
			,@lParentContactNo NVARCHAR(20)
			,@lParentEmail NVARCHAR(50)
			,@lStudentContactNo NVARCHAR(20)
			,@lStudentEmail NVARCHAR(50)
			,@lPresentStreetOne NVARCHAR(150)
			,@lPresentStreetTwo NVARCHAR(150)
			,@lPresentStreetThree NVARCHAR(150)
			,@lPresentCity NVARCHAR(50)
			,@lPresentZipCode NVARCHAR(20)
			,@lPresentState NVARCHAR(50)
			,@lPresentCountry NVARCHAR(50)
			,@lPresentContactNo NVARCHAR(20)
			,@lEmergencyContactNo NVARCHAR(20)
			,@lBirthPlace NVARCHAR(150)
			,@lBirthTaluka NVARCHAR(150)
			,@lBirthDistrict NVARCHAR(150)
			,@lBirthDateInWord NVARCHAR(150)
			,@lHouseId INT
			,@lHouse NVARCHAR(100)
			,@lMotherTongue NVARCHAR(100)
			,@lAdhaarNumber NVARCHAR(20)
			,@lUIDNumber NVARCHAR(50)
			,@lQuotaId INT
			,@lQuota NVARCHAR(100)
			,@lSUId NVARCHAR(50)
			,@lLeftStandardId INT
			,@lLeftStandard NVARCHAR(100)
			,@lLeftDate DATE
			,@lLCNumber NVARCHAR(20)
			,@lLCDate DATE
			,@lLCReason NVARCHAR(200)
			,@lLCProgress NVARCHAR(200)
			,@lLCConduct NVARCHAR(200)
			,@lLCRemark NVARCHAR(200)
			,@lStatusId SMALLINT
			,@lBirthState NVARCHAR(100)
			,@lBirthCountry NVARCHAR(100)
			,@lAcademicId BIGINT
			,@lPreviousStandard NVARCHAR(100)
			,@lWhatsAppContactNo NVARCHAR(20)
			,@lTribeId INT = 0
			,@lTribe NVARCHAR(100)
			,@lPreviousLeftDate DATE
			,@lFeesRemark NVARCHAR(500)

		DECLARE @EmployeeId BIGINT
		DECLARE @OutStudentId BIGINT
		
		SET @lAdmissionCategoryId = sCommon.fGetIntIdForOrg(1, @rOrgGroupId)

		DECLARE @1StudentId BIGINT = 0

		EXECUTE @lInterrorCode = sp_xml_preparedocument @intDoc OUTPUT,@rXmlDoc

		CREATE TABLE #tTable (
			Id BIGINT identity
			,Code NVARCHAR(20)
			,Number BIGINT
			,RegistrationNumber NVARCHAR(20)
			,FirstName NVARCHAR(100)
			,MiddleName NVARCHAR(100)
			,LastName NVARCHAR(100)
			,ClassId INT NULL
			,Class NVARCHAR(100)
			,DivisionId INT NULL
			,Division NVARCHAR(100)
			,RollNo INT
			,AdmissionStandardId INT
			,AdmissionStandard NVARCHAR(100)
			,AdmissionDate DATE
			,PreviousSchool NVARCHAR(200)
			,DOB DATE
			,GenderId INT NULL
			,Gender NVARCHAR(10)
			,BloodGroupId INT NULL
			,BloodGroup NVARCHAR(10)
			,ReligionId INT
			,Religion NVARCHAR(100)
			,FamilyCast NVARCHAR(100)
			,FamilySubCast NVARCHAR(100)
			,CastCategoryId INT
			,CastCategory NVARCHAR(100)
			,ParentContactNo NVARCHAR(20)
			,ParentEmail NVARCHAR(50)
			,StudentContactNo NVARCHAR(20)
			,StudentEmail NVARCHAR(50)
			,PresentStreetOne NVARCHAR(150)
			,PresentStreetTwo NVARCHAR(150)
			,PresentStreetThree NVARCHAR(150)
			,PresentCity NVARCHAR(50)
			,PresentZipCode NVARCHAR(20)
			,PresentState NVARCHAR(50)
			,PresentCountry NVARCHAR(50)
			,PresentContactNo NVARCHAR(20)
			,EmergencyContactNo NVARCHAR(20)
			,BirthPlace NVARCHAR(150)
			,BirthTaluka NVARCHAR(150)
			,BirthDistrict NVARCHAR(150)
			,BirthDateInWord NVARCHAR(150)
			,CreatedUserId BIGINT
			,HouseId INT
			,House NVARCHAR(100)
			,MotherTongueId INT
			,MotherTongue NVARCHAR(100)
			,AdhaarNumber NVARCHAR(20)
			,UIDNumber NVARCHAR(50)
			,QuotaId INT
			,Quota NVARCHAR(100)
			,SUId NVARCHAR(50)
			,LeftStandardId INT
			,LeftStandard NVARCHAR(100)
			,LeftDate DATE
			,LCNumber NVARCHAR(20)
			,LCDate DATE
			,LCReason NVARCHAR(200)
			,LCProgress NVARCHAR(200)
			,LCConduct NVARCHAR(200)
			,LCRemark NVARCHAR(200)
			,StatusId SMALLINT
			,BirthState NVARCHAR(100)
			,BirthCountry NVARCHAR(100)
			,PreviousStandard NVARCHAR(100)
			,WhatsAppContactNo NVARCHAR(20)
			,TribeId INT NULL
			,Tribe NVARCHAR(100)
			,PreviousLeftDate DATE
			,FeesRemark NVARCHAR(500)
			)

		INSERT INTO #tTable (
			Code
			,Number
			,RegistrationNumber
			,FirstName
			,MiddleName
			,LastName
			,ClassId
			,Class
			,DivisionId
			,Division
			,RollNo
			,AdmissionStandardId
			,AdmissionStandard
			,AdmissionDate
			,PreviousSchool
			,DOB
			,GenderId
			,Gender
			,BloodGroupId
			,BloodGroup
			,ReligionId
			,Religion
			,FamilyCast
			,FamilySubCast
			,CastCategoryId
			,CastCategory
			,ParentContactNo
			,ParentEmail
			,StudentContactNo
			,StudentEmail
			,PresentStreetOne
			,PresentStreetTwo
			,PresentStreetThree
			,PresentCity
			,PresentZipCode
			,PresentState
			,PresentCountry
			,PresentContactNo
			,EmergencyContactNo
			,BirthPlace
			,BirthTaluka
			,BirthDistrict
			,BirthDateInWord
			,CreatedUserId
			,HouseId
			,House
			,MotherTongueId
			,MotherTongue
			,AdhaarNumber
			,UIDNumber
			,QuotaId
			,Quota
			,SUId
			,LeftStandardId
			,LeftStandard
			,LeftDate
			,LCNumber
			,LCDate
			,LCReason
			,LCProgress
			,LCConduct
			,LCRemark
			,StatusId
			,BirthState
			,BirthCountry
			,PreviousStandard
			,WhatsAppContactNo
			,TribeId
			,Tribe
			,PreviousLeftDate
			,FeesRemark
			)
		SELECT Code
			,Number
			,RegistrationNumber
			,sSetup.fPortalXMLTagsReplaceReverse(FirstName) AS FirstName
			,sSetup.fPortalXMLTagsReplaceReverse(MiddleName) AS MiddleName
			,sSetup.fPortalXMLTagsReplaceReverse(LastName) AS LastName
			,0
			,sSetup.fPortalXMLTagsReplaceReverse(Class) AS Class
			,0
			,sSetup.fPortalXMLTagsReplaceReverse(Division) AS Division
			,RollNo
			,0
			,AdmissionStandard
			,AdmissionDate
			,sSetup.fPortalXMLTagsReplaceReverse(PreviousSchool) AS PreviousSchool
			,DOB
			,0
			,sSetup.fPortalXMLTagsReplaceReverse(Gender) AS Gender
			,0
			,BloodGroup
			,0
			,sSetup.fPortalXMLTagsReplaceReverse(Religion) AS Religion
			,sSetup.fPortalXMLTagsReplaceReverse(FamilyCast) AS FamilyCast
			,sSetup.fPortalXMLTagsReplaceReverse(FamilySubCast) AS FamilySubCast
			,0
			,sSetup.fPortalXMLTagsReplaceReverse(CastCategory) AS CastCategory
			,ParentContactNo
			,ParentEmail
			,StudentContactNo
			,StudentEmail
			,sSetup.fPortalXMLTagsReplaceReverse(PresentStreetOne) AS PresentStreetOne
			,sSetup.fPortalXMLTagsReplaceReverse(PresentStreetTwo) AS PresentStreetTwo
			,sSetup.fPortalXMLTagsReplaceReverse(PresentStreetThree) AS PresentStreetThree
			,sSetup.fPortalXMLTagsReplaceReverse(PresentCity) AS PresentCity
			,PresentZipCode
			,sSetup.fPortalXMLTagsReplaceReverse(PresentState) AS PresentState
			,sSetup.fPortalXMLTagsReplaceReverse(PresentCountry) AS PresentCountry
			,PresentContactNo
			,EmergencyContactNo
			,sSetup.fPortalXMLTagsReplaceReverse(BirthPlace) AS BirthPlace
			,sSetup.fPortalXMLTagsReplaceReverse(BirthTaluka) AS BirthTaluka
			,sSetup.fPortalXMLTagsReplaceReverse(BirthDistrict) AS BirthDistrict
			,sSetup.fPortalXMLTagsReplaceReverse(BirthDateInWord) AS BirthDateInWord
			,CreatedUserId
			,0
			,sSetup.fPortalXMLTagsReplaceReverse(House) AS House
			,0
			,sSetup.fPortalXMLTagsReplaceReverse(MotherTongue) AS MotherTongue
			,sSetup.fPortalXMLTagsReplaceReverse(AdhaarNumber) AS AdhaarNumber
			,UIDNumber
			,0
			,Quota
			,SUId
			,0
			,LeftStandard
			,LeftDate
			,LCNumber
			,LCDate
			,sSetup.fPortalXMLTagsReplaceReverse(LCReason) AS LCReason
			,LCProgress
			,LCConduct
			,sSetup.fPortalXMLTagsReplaceReverse(LCRemark) AS LCRemark
			,StatusId
			,sSetup.fPortalXMLTagsReplaceReverse(BirthState) AS BirthState
			,sSetup.fPortalXMLTagsReplaceReverse(BIrthCountry) AS BIrthCountry
			,PreviousStandard
			,WhatsAppContactNo
			,0
			,Tribe
			,PreviousLeftDate
			,sSetup.fPortalXMLTagsReplaceReverse(FeesRemark) AS FeesRemark
		FROM OPENXML(@intDoc, '/Table/ImportStudent', 1) WITH (
				Code NVARCHAR(20) '@Code'
				,Number BIGINT '@Number'
				,RegistrationNumber NVARCHAR(20) '@RegistrationNumber'
				,FirstName NVARCHAR(100) '@FirstName'
				,MiddleName NVARCHAR(100) '@MiddleName'
				,LastName NVARCHAR(100) '@LastName'
				,Class NVARCHAR(100) '@Class'
				,Division NVARCHAR(100) '@Division'
				,RollNo INT '@RollNo'
				,AdmissionStandard NVARCHAR(100) '@AdmissionStandard'
				,AdmissionDate DATE '@AdmissionDate'
				,PreviousSchool NVARCHAR(200) '@PreviousSchool'
				,DOB DATE '@DOB'
				,Gender NVARCHAR(10) '@Gender'
				,BloodGroup NVARCHAR(10) '@BloodGroup'
				,Religion NVARCHAR(100) '@Religion'
				,FamilyCast NVARCHAR(100) '@FamilyCast'
				,FamilySubCast NVARCHAR(100) '@FamilySubCast'
				,CastCategory NVARCHAR(100) '@CastCategory'
				,ParentContactNo NVARCHAR(20) '@ParentContactNo'
				,ParentEmail NVARCHAR(50) '@ParentEmail'
				,StudentContactNo NVARCHAR(20) '@StudentContactNo'
				,StudentEmail NVARCHAR(50) '@StudentEmail'
				,PresentStreetOne NVARCHAR(150) '@PresentStreetOne'
				,PresentStreetTwo NVARCHAR(150) '@PresentStreetTwo'
				,PresentStreetThree NVARCHAR(150) '@PresentStreetThree'
				,PresentCity NVARCHAR(50) '@PresentCity'
				,PresentZipCode NVARCHAR(20) '@PresentZipCode'
				,PresentState NVARCHAR(50) '@PresentState'
				,PresentCountry NVARCHAR(50) '@PresentCountry'
				,PresentContactNo NVARCHAR(20) '@PresentContactNo'
				,EmergencyContactNo NVARCHAR(20) '@EmergencyContactNo'
				,BirthPlace NVARCHAR(150) '@BirthPlace'
				,BirthTaluka NVARCHAR(150) '@BirthTaluka'
				,BirthDistrict NVARCHAR(150) '@BirthDistrict'
				,BirthDateInWord NVARCHAR(150) '@BirthDateInWord'
				,CreatedUserId BIGINT '@CreatedUserId'
				,House NVARCHAR(100) '@House'
				,MotherTongue NVARCHAR(100) '@MotherTongue'
				,AdhaarNumber NVARCHAR(20) '@AdhaarNumber'
				,UIDNumber NVARCHAR(50) '@UIDNumber'
				,Quota NVARCHAR(20) '@Quota'
				,SUId NVARCHAR(50) '@SUId'
				,LeftStandard NVARCHAR(100) '@LeftStandard'
				,LeftDate DATE '@LeftDate'
				,LCNumber NVARCHAR(20) '@LCNumber'
				,LCDate DATE '@LCDate'
				,LCReason NVARCHAR(200) '@LCReason'
				,LCProgress NVARCHAR(200) '@LCProgress'
				,LCConduct NVARCHAR(200) '@LCConduct'
				,LCRemark NVARCHAR(200) '@LCRemark'
				,StatusId SMALLINT '@StatusId'
				,BirthState NVARCHAR(100) '@BirthState'
				,BirthCountry NVARCHAR(100) '@BirthCountry'
				,PreviousStandard NVARCHAR(100) '@PreviousStandard'
				,WhatsAppContactNo NVARCHAR(20) '@WhatsAppContactNo'
				,Tribe NVARCHAR(100) '@Tribe'
				,PreviousLeftDate DATE '@PreviousLeftDate'
				,FeesRemark NVARCHAR(200) '@FeesRemark'
				)

		EXEC sp_xml_removedocument @intDoc

		SELECT @lCount = COUNT(Id) FROM #tTable

		WHILE @lCount > 0
BEGIN
BEGIN TRANSACTION
			SET @lCode = ''
			SET @lNumber = NULL
			SET @lRegistrationNumber = NULL
			SET @lFirstName = ''
			SET @lMiddleName = ''
			SET @lLastName = ''
			SET @lClassId = NULL
			SET @lClass = ''
			SET @lDivisionId = NULL
			SET @lDivision = ''
			SET @lRollNo = NULL
			SET @lAdmissionStandardId = NULL
			SET @lAdmissionStandard = ''
			SET @lAdmissionDate = ''
			SET @lPreviousSchool = ''
			SET @lDOB = ''
			SET @lGenderId = NULL
			SET @lGender = ''
			SET @lBloodGroupId = NULL
			SET @lBloodGroup = ''
			SET @lReligionId = NULL
			SET @lReligion = ''
			SET @lFamilyCast = ''
			SET @lFamilySubCast = ''
			SET @lCastCategoryId = NULL
			SET @lCastCategory = ''
			SET @lParentContactNo = ''
			SET @lParentEmail = ''
			SET @lStudentContactNo = ''
			SET @lStudentEmail = ''
			SET @lPresentStreetOne = ''
			SET @lPresentStreetTwo = ''
			SET @lPresentStreetThree = ''
			SET @lPresentCity = ''
			SET @lPresentZipCode = ''
			SET @lPresentState = ''
			SET @lPresentCountry = ''
			SET @lPresentContactNo = ''
			SET @lEmergencyContactNo = ''
			SET @lBirthPlace = ''
			SET @lBirthTaluka = ''
			SET @lBirthDistrict = ''
			SET @lBirthDateInWord = ''
			SET @OutStudentId = NULL
			SET @lHouseId = NULL
			SET @lHouse = ''
			SET @lMotherTongue = ''
			SET @lAdhaarNumber = ''
			SET @lUIDNumber = ''
			SET @lQuotaId = NULL
			SET @lQuota = ''
			SET @lSUId = ''
			SET @lLeftStandardId = NULL
			SET @lLeftStandard = ''
			SET @lLeftDate = ''
			SET @lLCNumber = ''
			SET @lLCDate = ''
			SET @lLCReason = ''
			SET @lLCProgress = ''
			SET @lLCConduct = ''
			SET @lLCRemark = ''
			SET @lStatusId = NULL
			SET @lBirthState = ''
			SET @lBirthCountry = ''
			SET @lPreviousStandard = ''
			SET @lWhatsAppContactNo = ''
			SET @lTribeId = NULL
			SET @lTribe = ''
			SET @lPreviousLeftDate = ''
			SET @lFeesRemark = ''

			SELECT @lCode = Code
				,@lNumber = Number
				,@lRegistrationNumber = RegistrationNumber
				,@lFirstName = FirstName
				,@lMiddleName = MiddleName
				,@lLastName = LastName
				,@lClass = Class
				,@lDivision = Division
				,@lRollNo = RollNo
				,@lAdmissionStandard = AdmissionStandard
				,@lAdmissionDate = CASE WHEN AdmissionDate = '' THEN NULL ELSE AdmissionDate END
				,@lPreviousSchool = PreviousSchool
				,@lReligion = Religion
				,@lFamilyCast = FamilyCast
				,@lFamilySubCast = FamilySubCast
				,@lCastCategory = CastCategory
				,@lDOB = CASE WHEN DOB = '' THEN NULL ELSE DOB END
				,@lGender = Gender
				,@lBloodGroup = BloodGroup
				,@lParentContactNo = ParentContactNo
				,@lParentEmail = ParentEmail
				,@lStudentContactNo = StudentContactNo
				,@lStudentEmail = StudentEmail
				,@lPresentStreetOne = PresentStreetOne
				,@lPresentStreetTwo = PresentStreetTwo
				,@lPresentStreetThree = PresentStreetThree
				,@lPresentCountry = PresentCountry
				,@lPresentState = PresentState
				,@lPresentCity = PresentCity
				,@lPresentZipCode = PresentZipCode
				,@lPresentContactNo = PresentContactNo
				,@lEmergencyContactNo = EmergencyContactNo
				,@lBirthPlace = BirthPlace
				,@lBirthTaluka = BirthTaluka
				,@lBirthDistrict = BirthDistrict
				,@lBirthDateInWord = BirthDateInWord
				,@lHouse = House
				,@lMotherTongue = MotherTongue
				,@lAdhaarNumber = AdhaarNumber
				,@lUIDNumber = UIDNumber
				,@lSUId = SUId
				,@lLeftStandard = LeftStandard
				,@lLeftDate = CASE WHEN LeftDate = '' THEN NULL ELSE LeftDate END
				,@lLCNumber = LCNumber
				,@lLCDate = CASE WHEN LCDate = '' THEN NULL ELSE LCDate END
				,@lLCReason = LCReason
				,@lLCProgress = LCProgress
				,@lLCConduct = LCConduct
				,@lLCRemark = LCRemark
				,@lStatusId = StatusId
				,@lBirthState = BirthState
				,@lBirthCountry = BirthCountry
				,@lPreviousStandard = PreviousStandard
				,@lWhatsAppContactNo = WhatsAppContactNo
				,@lTribe = Tribe
				,@lPreviousLeftDate = CASE WHEN PreviousLeftDate = '' THEN NULL ELSE PreviousLeftDate END
				,@lFeesRemark = FeesRemark
			FROM #tTable
			WHERE Id = @lCount

			SELECT @lGenderId = ID FROM sCommon.tGenderMaster WHERE Title = @lGender
			SELECT @lLeftStandardId = ID FROM sSetup.tClassMaster WHERE Title = @lLeftStandard AND OrgId = @rOrgId
			SELECT @lClassId = ID FROM sSetup.tClassMaster WHERE Title = @lClass AND OrgId = @rOrgId
			SELECT @lDivisionId = ID FROM sSetup.tDivisionMaster WHERE Title = @lDivision AND ClassId = @lClassId AND OrgId = @rOrgId
			SELECT @lBloodGroupId = ID FROM sCommon.tBloodGroupMaster WHERE Title = @lBloodGroup
			SELECT @lAdmissionStandardId = ID FROM sSetup.tClassMaster WHERE Title = @lAdmissionStandard AND OrgId = @rOrgId
			SELECT @lReligionId = ID FROM sCommon.tReligionMaster WHERE Title = @lReligion AND OrgGroupId = @rOrgGroupId
			SELECT @lCastCategoryId = ID FROM sCommon.tCastCategoryMaster WHERE Title = @lCastCategory AND OrgGroupId = @rOrgGroupId
			SELECT @lHouseId = ID FROM sActivity.tHouseMaster WHERE Title = @lHouse AND OrgId = @rOrgId
			SELECT @lQuotaId = ID FROM sCommon.tQuotaMaster WHERE Title = @lQuota AND OrgGroupId = @rOrgGroupId 
			SELECT @lTribeId = ID FROM sCommon.tTribeMaster WHERE Title = @lTribe

			IF (@lGenderId IS NULL)
				SET @lGenderId = 0

			IF (@lBloodGroupId IS NULL)
				SET @lBloodGroupId = 0

			IF (@lCastCategoryId IS NULL)
				SET @lCastCategoryId = 0

			IF (@lHouseId IS NULL)
				SET @lHouseId = 0

			IF (@lQuotaId IS NULL)
				SET @lQuotaId = 0

			IF (@lTribeId IS NULL)
				SET @lTribeId = 0

			DECLARE @lStudCap INT
				,@lOrgStudentCap INT

			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
				COMMIT TRANSACTION
				RETURN
			END

			IF (@rOperation = 1 OR @rOperation = 0)
			BEGIN
				IF (@lStatusId = 1)
					EXEC sStudent.pStudentMasterAdd 0
						,@lCode
						,@lRegistrationNumber
						,@lNumber
						,@lFirstName
						,@lMiddleName
						,@lLastName
						,@rOrgId
						,@lAdmissionCategoryId
						,1
						,502
						,@rUserId
						,@rUserId
						,@rOrgGroupBatchId
						,@OutStudentId OUTPUT
						,@lSUId
				ELSE
					EXEC sStudent.pStudentMasterAdd 0
						,@lCode
						,@lRegistrationNumber
						,@lNumber
						,@lFirstName
						,@lMiddleName
						,@lLastName
						,@rOrgId
						,@lAdmissionCategoryId
						,3
						,502
						,@rUserId
						,@rUserId
						,@rOrgGroupBatchId
						,@OutStudentId OUTPUT
						,@lSUId

				EXEC sStudent.pAcademicAdd 0
					,@OutStudentId
					,@lClassId
					,@lDivisionId
					,@lRollNo
					,@rOrgId
					,@rBatchId
					,@rUserId
					,@rUserId
					,@lAdmissionCategoryId
					,1
					,@lFeesRemark

				EXEC sStudent.pStudentCommunicationAdd @OutStudentId
					,@lPresentStreetOne
					,@lPresentStreetTwo
					,@lPresentStreetThree
					,@lPresentCountry
					,@lPresentState
					,@lPresentCity
					,@lPresentZipCode
					,@lPresentContactNo
					,NULL
					,NULL
					,NULL
					,NULL
					,NULL
					,NULL
					,NULL
					,NULL
					,NULL
					,NULL
					,NULL
					,NULL
					,NULL
					,NULL
					,NULL
					,@lEmergencyContactNo
					,@lParentContactNo
					,@lParentEmail
					,@lStudentContactNo
					,@lStudentEmail
					,@rUserId
					,@rUserId
					,NULL
					,NULL
					,NULL
					,NULL
					,NULL
					,@lWhatsAppContactNo

				EXEC sStudent.pStudentOtherAdd @OutStudentId
					,@lUIDNumber
					,@lDOB
					,@lGenderId
					,@lReligionId
					,@lBloodGroupId
					,@lBirthPlace
					,@lBirthTaluka
					,@lBirthDistrict
					,@lBirthDateInWord
					,@lFamilyCast
					,@lFamilySubCast
					,@lCastCategoryId
					,NULL
					,@lHouseId
					,NULL
					,NULL
					,''
					,@rUserId
					,@rUserId
					,''
					,@lAdhaarNumber
					,@lMotherTongue
					,@lQuotaId
					,@lBirthState
					,@lBirthCountry
					,@rBatchId
					,@lTribeId

				IF (@lStatusId = 1)
					EXEC [sStudent].[pStudentAdmissionAdd] @OutStudentId
						,@lPreviousSchool
						,NULL
						,NULL
						,NULL
						,NULL
						,@lAdmissionStandardId
						,@lAdmissionDate
						,NULL
						,NULL
						,NULL
						,NULL
						,NULL
						,NULL
						,NULL
						,NULL
						,NULL
						,NULL
						,NULL
						,NULL
						,NULL
						,NULL
						,NULL
						,@rBatchId
						,@rUserId
						,@rUserId
						,1
						,NULL
						,NULL
						,NULL
						,NULL
						,NULL
						,NULL
						,NULL
						,NULL
						,@lPreviousStandard
						,NULL
						,NULL
						,NULL
						,NULL
						,NULL
						,@lPreviousLeftDate
				ELSE
					EXEC [sStudent].[pStudentAdmissionAdd] @OutStudentId
						,@lPreviousSchool
						,NULL
						,NULL
						,NULL
						,NULL
						,@lAdmissionStandardId
						,@lAdmissionDate
						,NULL
						,@lLeftStandardId
						,@lLeftDate
						,NULL
						,NULL
						,NULL
						,@lLCReason
						,@lLCProgress
						,@lLCConduct
						,NULL
						,@lLCNumber
						,@lLCDate
						,@lLCRemark
						,NULL
						,NULL
						,@rBatchId
						,@rUserId
						,@rUserId
						,0
						,NULL
						,NULL
						,NULL
						,NULL
						,NULL
						,NULL
						,NULL
						,NULL
						,@lPreviousStandard
						,NULL
						,NULL
						,NULL
						,NULL
						,NULL
						,@lPreviousLeftDate
			END
			ELSE
			BEGIN
				SET @1StudentId = (SELECT Id FROM sStudent.tStudentMaster WHERE Code COLLATE DATABASE_DEFAULT = @lCode COLLATE DATABASE_DEFAULT AND OrgId = @rOrgId)

				UPDATE sStudent.tStudentMaster
				SET RegistrationNumber = @lRegistrationNumber
					,FirstName = @lFirstName
					,MiddleName = @lMiddleName
					,LastName = @lLastName
					,SUId = @lSUId
					,UpdatedUserId = @rUserId
					,UpdatedDateTime = getdate()
				WHERE Id = @1StudentId

				UPDATE sStudent.tStudentAdmission
				SET AdmissionStandardId = @lAdmissionStandardId
					,AdmissionDate = @lAdmissionDate
					,PreviousSchool = @lPreviousSchool
					,LeftStandardId = @lLeftStandardId
					,LeftDate = @lLeftDate
					,LCNumber = @lLCNumber
					,LCDate = @lLCDate
					,LCRemark = @lLCRemark
					,LCConduct = @lLCConduct
					,LCProgress = @lLCProgress
					,LeftReason = @lLCReason
					,UpdatedUserId = @rUserId
					,UpdatedDateTime = getdate()
					,PreviousStandard = @lPreviousStandard
					,PreviousLeftDate = @lPreviousLeftDate
				WHERE StudentId = @1StudentId

				UPDATE sStudent.tStudentOther
				SET DateOfBirth = @lDOB
					,GenderId = @lGenderId
					,BloodGroupId = @lBloodGroupId
					,ReligionId = @lReligionId
					,FamilyCast = @lFamilyCast
					,FamilySubCast = @lFamilySubCast
					,CastCategoryId = @lCastCategoryId
					,BirthPlace = @lBirthPlace
					,BirthTaluka = @lBirthTaluka
					,BirthDistrict = @lBirthDistrict
					,BirthState = @lBirthState
					,BirthCountry = @lBirthCountry
					,AdhaarNumber = @lAdhaarNumber
					,MotherTongue = @lMotherTongue
					,QuotaId = @lQuotaId
					,UIDNumber = @lUIDNumber
					,HouseId = @lHouseId
					,UpdatedUserId = @rUserId
					,UpdatedDateTime = getdate()
					,TribeId = @lTribeId
				WHERE StudentId = @1StudentId

				IF (@lDivisionId IS NOT NULL)
				BEGIN
					UPDATE sStudent.tAcademic
					SET DivisionId = @lDivisionId
						,RollNo = @lRollNo
						,UpdatedUserId = @rUserId
						,UpdatedDateTime = getdate()
						,FeesRemark = @lFeesRemark
					WHERE StudentId = @1StudentId
						AND BatchId = @rBatchId
						AND OrgId = @rOrgId
				END

				UPDATE sStudent.tStudentCommunication
				SET PresentStreetOne = @lPresentStreetOne
					,PresentStreetTwo = @lPresentStreetTwo
					,PresentStreetThree = @lPresentStreetThree
					,PresentCountry = @lPresentCountry
					,PresentState = @lPresentState
					,PresentCity = @lPresentCity
					,PresentZipCode = @lPresentZipCode
					,PresentContactNo = @lPresentContactNo
					,EmergencyContactNo = @lEmergencyContactNo
					,ParentContactNo = @lParentContactNo
					,ParentEmail = @lParentEmail
					,StudentContactNo = @lStudentContactNo
					,StudentEmail = @lStudentEmail
					,UpdatedUserId = @rUserId
					,UpdatedDateTime = getdate()
				WHERE StudentId = @1StudentId
			END

			SET @lCount = @lCount - 1
			COMMIT TRANSACTION
		END
		SELECT 1
	END TRY

	BEGIN CATCH
		ROLLBACK TRANSACTION
		SELECT ERROR_MESSAGE(),ERROR_LINE()
	END CATCH
END
GO
PRINT N'Altering Procedure [sPurchase].[pQuotationRequestAdd]...';


GO




ALTER PROCEDURE [sPurchase].[pQuotationRequestAdd]
		@rId bigint,
		@rOrgGroupId smallint,
		@rBranchId int,
		@rLocationId int,
		@rPurchaseRequestId bigint,
		@rName varchar(100),
		@rRFQDate datetime,
		@rDescription nvarchar(300),
		@rStartDate datetime,
		@rEndDate datetime,
		@rBidOpen nvarchar(50),
		@rBidClose nvarchar(50),
		@rPersonContact nvarchar(50),
		@rEmail nvarchar(50),
		@rSendToVendor bit,
		@rStatusId smallint,
		@rVendorId int,
		@rUserId bigint,
		@rDetailList sPurchase.QuotationRequestDetailType READONLY
 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
	BEGIN TRANSACTION
		If(@rId > 0)
		Begin
			Update sPurchase.tQuotationRequest
			set
				OrgGroupId =@rOrgGroupId,
				BranchId =@rBranchId,
				LocationId =@rLocationId,
				PurchaseRequestId =@rPurchaseRequestId,
				Name =@rName,
				RFQDate =@rRFQDate,
				Description =@rDescription,
				StartDate =@rStartDate,
				EndDate =@rEndDate,
				BidOpen =@rBidOpen,
				BidClose =@rBidClose,
				PersonContact =@rPersonContact,
				Email =@rEmail,
				SendToVendor =@rSendToVendor,
				StatusId =@rStatusId,
				VendorId =@rVendorId,
				UpdatedUserId = @rUserId,		
				UpdatedDateTime = GetUtcDate()
			where Id = @rId and IsObsolete = 0

			delete from sPurchase.tQuotationRequestDetail
			where Id not in(select Id from @rDetailList)
			and QuotationRequestId = @rId

			update sPurchase.tQuotationRequestDetail
			set
			OrgGroupId = @rOrgGroupId,
			QuotationRequestId = @rId,
			PurchaseRequestDetailId = DL.PurchaseRequestDetailId,
			StockItemId = DL.StockItemId,
			RequestedQty = DL.RequestedQty,
			Remark = DL.Remark,
			TargetPrice = DL.TargetPrice,
			UpdatedUserId = @rUserId,
			UpdatedDateTime = GETUTCDATE()
			from @rDetailList DL
			inner join sPurchase.tQuotationRequestDetail QR ON DL.ID = QR.Id
			where QuotationRequestId = @rId

			DECLARE @lNextNumberQRDA BIGINT	 
			EXECUTE [sCommon].[pGetIntMaxIdForOrgGroup] @rOrgGroupId, 'sPurchase.tQuotationRequestDetail',@lNextNumber = @lNextNumberQRDA output
			SET @lNextNumberQRDA=@lNextNumberQRDA-1
			INSERT INTO sPurchase.tQuotationRequestDetail
			(
				Id,
				OrgGroupId,
				QuotationRequestId,
				PurchaseRequestDetailId,
				StockItemId,
				RequestedQty,
				Remark,
				TargetPrice,
				CreatedUserId,
				CreatedDateTime
			)
			select	@lNextNumberQRDA+Id,
				    @rOrgGroupId,
					@rId,
					PurchaseRequestDetailId, 
					StockItemId,
					RequestedQty,
					Remark,
					TargetPrice,
					@rUserId, 
					GETUTCDATE() 
			from @rDetailList
			where Id not in(Select DL.Id from @rDetailList DL
			inner join sPurchase.tQuotationRequestDetail QR ON DL.ID = QR.Id
			where QR.QuotationRequestId = @rId)
			set @lNextNumberQRDA=@lNextNumberQRDA+(select Count(Id) from @rDetailList where Id not in(Select DL.Id from @rDetailList DL
			inner join sPurchase.tQuotationRequestDetail QR ON DL.ID = QR.Id
			where QR.QuotationRequestId = @rId))
			EXECUTE sCommon.pTableRowIdModify @rOrgGroupId, @rTableTitle = 'sPurchase.tQuotationRequestDetail', @rCurrentNumber = @lNextNumberQRDA

			select @rId
		End
		Else
		Begin
				DECLARE @lNextNumber INT	 
				EXECUTE [sCommon].[pGetIntMaxIdForOrgGroup] @rOrgGroupId, 'sPurchase.tQuotationRequest',@lNextNumber = @lNextNumber output	
				-------------select @lNextNumber
				--DECLARE @loNextNumber nVarchar(20)
				--EXECUTE sCommon.pPrefixSetupNextNumberGet @rOrgId = @rOrgGroupId, @rPrefixFunctionalityId = 1005,@rStoreLocationId = @rLocationId,
				-------------@rNextNumber = @loNextNumber OUTPUT
				If not exists(select * from sPurchase.tQuotationRequest where PurchaseRequestId = @rPurchaseRequestId and VendorId = @rVendorId)
				Begin
																																																																																																																																																																																																																																											
                    INSERT INTO sPurchase.tQuotationRequest
					(
						Id,
						Number,
						OrgGroupId,
						BranchId,
						LocationId,
						PurchaseRequestId,
						Name,
						RFQDate,
						Description,
						StartDate,
						EndDate,
						BidOpen,
						BidClose,
						PersonContact,
						Email,
						SendToVendor,
						StatusId,
						VendorId,
						CreatedUserId,		
						CreatedDateTime
	
					)
					VALUES
					(
						@lNextNumber,
						@lNextNumber,
						@rOrgGroupId,
						@rBranchId ,
						@rLocationId,
						@rPurchaseRequestId,
						@rName,
						@rRFQDate,
						@rDescription,
						@rStartDate,
						@rEndDate ,
						@rBidOpen ,
						@rBidClose,
						@rPersonContact,
						@rEmail,
						@rSendToVendor,
						@rStatusId,
						@rVendorId ,
						@rUserId,		
						GETUTCDATE()
					)
 
					set @rId = @lNextNumber 

					DECLARE @lNextNumberQRD BIGINT	 
					EXECUTE [sCommon].[pGetIntMaxIdForOrgGroup] @rOrgGroupId, 'sPurchase.tQuotationRequestDetail',@lNextNumber = @lNextNumberQRD output
					SET @lNextNumberQRD=@lNextNumberQRD+1
			        
					INSERT INTO sPurchase.tQuotationRequestDetail
					(
						Id,
						OrgGroupId,
						QuotationRequestId,
						PurchaseRequestDetailId,
						StockItemId,
						RequestedQty,
						Remark,
						TargetPrice,
						CreatedUserId,
						CreatedDateTime
					)
					select	@lNextNumberQRD+Id,
							@rOrgGroupId,
							@rId,
							PurchaseRequestDetailId, 
							StockItemId,
							RequestedQty,
							Remark,
							TargetPrice,
							@rUserId, 
							GETUTCDATE() 
					from @rDetailList
					set @lNextNumberQRD=@lNextNumberQRD+(select Count(Id) from @rDetailList)
					EXECUTE sCommon.pTableRowIdModify @rOrgGroupId, @rTableTitle = 'sPurchase.tQuotationRequestDetail', @rCurrentNumber = @lNextNumberQRD

			
					select @rId

					Declare @typeId smallint=0
					Declare @Level smallint=0
					SELECT @typeId=WfTypeMasterId, @Level=WfLevel FROM sWf.tWfSetup WHERE WfFunctionalityId = 2
					IF(@typeId = 1)--parallel
					BEGIN
						exec [sWf].[pWfApprovalAdd] 0,@rId,2041,@rUserId,1,'',0,0,2,@rOrgGroupId
					END
					ELSE IF(@typeId = 2)--sequencial
					Begin
						exec [sWf].[pWfApprovalAdd] 0,@rId,2041,@rUserId,2,'',1,@Level,2,@rOrgGroupId
					End
					ELSE IF(@typeId = 3)--auto approved
					BEGIN
						exec [sWf].[pWfApprovalAdd] 0,@rId,2041,@rUserId,3,'',0,0,2,@rOrgGroupId
					END
				END
				select 1;

		End
	COMMIT TRAN -- Transaction Success!	
	END TRY

	BEGIN CATCH
    IF @@TRANCOUNT > 0
        ROLLBACK TRAN --RollBack in case of Error

    
    DECLARE @ErrorMessage NVARCHAR(4000);  
    DECLARE @ErrorSeverity INT;  
    DECLARE @ErrorState INT;  

    SELECT   
       @ErrorMessage = ERROR_MESSAGE(),  
       @ErrorSeverity = ERROR_SEVERITY(),  
       @ErrorState = ERROR_STATE();  

    RAISERROR (@ErrorMessage, @ErrorSeverity, @ErrorState);  
    
	END CATCH
END

GO



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

