
GO
PRINT N'Dropping Procedure [sAlert].[pOnlineMeetingGet]...';


GO
DROP PROCEDURE [sAlert].[pOnlineMeetingGet];


GO
PRINT N'Creating User-Defined Table Type [sPurchase].[QualityCheckInwardType]...';


GO
CREATE TYPE [sPurchase].[QualityCheckInwardType] AS TABLE (
    [GoodsReceivedNoteDetailId] BIGINT          NOT NULL,
    [StockItemId]               BIGINT          NOT NULL,
    [Title]                     NVARCHAR (300)  NOT NULL,
    [AcceptedQty]               DECIMAL (12, 2) NOT NULL,
    [UnitPrice]                 BIGINT          NOT NULL);


GO


ALTER PROCEDURE [sEMeeting].[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 = 160
		END TRY
		BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH
	END
GO
PRINT N'Altering Procedure [sHrm].[pXMLEmployeeMasterAdd]...';

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
			  UNION ALL
			  SELECT distinct ClassName + '-' + DivisionName FROM sEMeeting.tOnlineMeetingScope OMS INNER JOIN sStudent.vStudentAcademic SA ON OMS.ScopeSourceId = SA.AcademicId Where  OnlineMeetingId = OM.Id AND OMS.ScopeSourceTypeId = 2003
			  UNION ALL
			  SELECT distinct OMG.DisplayTitle + '-' + vEC.DepartmentName FROM sEMeeting.tOnlineMeetingScope OMS INNER JOIN sHrm.vEmployeeCommunication vEC ON OMS.ScopeSourceId = vEC.Id LEFT JOIN sSetup.tOrganizationMaster OMG
				ON vEC.OrgId = OMG.Id Where  OnlineMeetingId = OM.Id AND OMS.ScopeSourceTypeId = 95
			  ) 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 DESC
	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 DESC
		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=2003
			
			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].[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=549 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.StartDate, OM.StartTime DESC
			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=549 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 desc;

		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=549 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.StartDate,OM.StartTime desc
				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=549 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.StartDate, OM.StartTime DESC
		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=2003
			
			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 [sHrm].[pRptEmployeeAttendanceRegisterGet]...';


GO



--exec [sWf].[pWfApprovalGet] 0,'2023-10-10','2024-02-02',0,9911,'',9911000000270,5,10,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 ,
			 @rPageNo INT = 1,
			 @rPageSize INT = 100,
			 @rApprovalRequestId BIGINT = 0

	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY

	DECLARE @lRoleId INT
	SELECT @lRoleId = RoleId FROM [sSecurity].[tUserRole] WHERE UserId = @rUserId

	DECLARE @totalCount INT = 0
	CREATE TABLE #ApprovalReq (
		RowNum INT,
		ApprovalActionId BIGINT,
		DocSourceId BIGINT,
		DocSourceTypeId SMALLINT,
		WorkFlowName NVARCHAR(50),
		WorkFlowId SMALLINT,
		ApprovalRequestId BIGINT,
		CreatedDateTime DATETIME,
		ParticipantSourceTypeId INT,
		SourceId BIGINT,
		Code NVARCHAR(50),
		Name NVARCHAR(50),
		statusId SMALLINT,
		status NVARCHAR(50),
		ActionRemark NVARCHAR(MAX)
	);
	
	INSERT INTO #ApprovalReq
	SELECT ROW_NUMBER() OVER (
				ORDER BY t.ApprovalActionId DESC  
				) AS RowNum,
	t.ApprovalActionId,
	t.DocSourceId,
	t.DocSourceTypeId,
	t.WorkFlowName,
	t.WorkFlowId,
	t.ApprovalRequestId,
	t.CreatedDateTime,
	t.ParticipantSourceTypeId,
	t.SourceId,
	t.Code,
	t.Name,
	t.statusId,
	t.status,
	t.ActionRemark FROM
	(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,
		ISNULL(U.SourceTypeId,95) AS ParticipantSourceTypeId,
		--Case when U.SourceId IS NULL 95 AS ParticipantSourceTypeId,
		U.SourceId AS SourceId,
		EM.Code AS Code ,
		ISNULL(EM.FirstName +' '+ EM.MiddleName +' ' +EM.LastName,U.DisplayTitle) 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 sSecurity.tUser U ON U.Id = AA.ActionEmployeeId
	LEFT JOIN  sHrm.tEmployeeMaster  EM ON EM.Id = U.SourceId AND U.SourceId IS NOT NULL
	
	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,
		ISNULL(U.SourceTypeId,95) AS ParticipantSourceTypeId,
		--Case when U.SourceId IS NULL 95 AS ParticipantSourceTypeId,
		U.SourceId AS SourceId,
		EM.Code AS Code ,
		ISNULL(EM.FirstName +' '+ EM.MiddleName +' ' +EM.LastName,U.DisplayTitle) 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
	LEFT JOIN sWf.tWfApprovalAction AA ON AA.DocSourceId = PR.Id AND AA.WfFunctionalityId = FAA.WfFunctionalityId AND AA.DocSourceTypeId = 2040
	Left JOIN sSecurity.tUser U ON U.Id = FAA.AuthoritySourceId AND FAA.AuthoritySourceTypeId = 1019 AND U.Id = AA.ActionEmployeeId
	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 = U.SourceId AND U.SourceId IS NOT NULL
	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,
		--Case when U.SourceId IS NULL 95 AS ParticipantSourceTypeId,
		EM.Id AS SourceId,
		EM.Code AS Code ,
		ISNULL(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 sSecurity.tUser U ON U.Id = AA.ActionEmployeeId
	LEFT JOIN  sHrm.tEmployeeMaster  EM ON EM.Id = AA.ActionEmployeeId
	WHERE HL.ActionByEmployeeId = (SELECT U.SourceId FROM sSecurity.tUser U WHERE U.Id = @rUserId)
	--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,
		PR.Id AS ApprovalRequestId,
		CONVERT(DATE,PR.CreatedDateTime, 103) AS CreatedDateTime,
		ISNULL(U.SourceTypeId,95) AS ParticipantSourceTypeId,
		--Case when U.SourceId IS NULL 95 AS ParticipantSourceTypeId,
		U.SourceId AS SourceId,
		EM.Code AS Code ,
		ISNULL(EM.FirstName +' '+ EM.MiddleName +' ' +EM.LastName,U.DisplayTitle) 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.tWfApprovalAction AA ON AA.DocSourceId = PR.Id AND AA.WfFunctionalityId = 1 AND AA.DocSourceTypeId = 2040
	LEFT JOIN sWf.tWfStatusMaster SM ON SM.Id = AA.ActionStatusId
	INNER JOIN sWf.tWfFunctionalityMaster WFM ON WFM.Id = 1
	INNER JOIN [sWf].[tWfSetup] SP ON SP.WfFunctionalityId = WFM.Id AND SP.WfTypeMasterId = 3
	LEFT JOIN sSecurity.tUser U ON U.Id = AA.ActionEmployeeId
	LEFT JOIN  sHrm.tEmployeeMaster  EM ON EM.Id = U.SourceId AND U.SourceId IS NOT NULL
	WHERE SP.WfTypeMasterId = 3
	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,
		ISNULL(U.SourceTypeId,95) AS ParticipantSourceTypeId,
		--Case when U.SourceId IS NULL 95 AS ParticipantSourceTypeId,
		U.SourceId AS SourceId,
		EM.Code AS Code ,
		ISNULL(EM.FirstName +' '+ EM.MiddleName +' ' +EM.LastName,U.DisplayTitle) 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 sSecurity.tUser U ON U.Id = AA.ActionEmployeeId
	LEFT JOIN  sHrm.tEmployeeMaster  EM ON EM.Id = U.SourceId AND U.SourceId IS NOT NULL
	
	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,
		ISNULL(U.SourceTypeId,95) AS ParticipantSourceTypeId,
		--Case when U.SourceId IS NULL 95 AS ParticipantSourceTypeId,
		U.SourceId AS SourceId,
		EM.Code AS Code ,
		ISNULL(EM.FirstName +' '+ EM.MiddleName +' ' +EM.LastName,U.DisplayTitle) 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
	LEFT JOIN sWf.tWfApprovalAction AA ON AA.DocSourceId = QR.Id AND AA.WfFunctionalityId = FAA.WfFunctionalityId AND AA.DocSourceTypeId = 2041
	LEFT JOIN sSecurity.tUser U ON U.Id = FAA.AuthoritySourceId AND FAA.AuthoritySourceTypeId = 1019 AND U.Id = AA.ActionEmployeeId
	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 = U.SourceId AND U.SourceId IS NOT NULL
	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,
		--Case when U.SourceId IS NULL 95 AS ParticipantSourceTypeId,
		EM.Id AS SourceId,
		EM.Code AS Code ,
		ISNULL(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 sSecurity.tUser U ON U.Id = AA.ActionEmployeeId
	LEFT JOIN  sHrm.tEmployeeMaster  EM ON EM.Id = AA.ActionEmployeeId
	WHERE HL.ActionByEmployeeId = (SELECT U.SourceId FROM sSecurity.tUser U WHERE U.Id = @rUserId)
	--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,
		QR.Id AS ApprovalRequestId,
		CONVERT(DATE,QR.CreatedDateTime, 103) AS CreatedDateTime,
		ISNULL(U.SourceTypeId,95) AS ParticipantSourceTypeId,
		--Case when U.SourceId IS NULL 95 AS ParticipantSourceTypeId,
		U.SourceId AS SourceId,
		EM.Code AS Code ,
		ISNULL(EM.FirstName +' '+ EM.MiddleName +' ' +EM.LastName,U.DisplayTitle) 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
	LEFT JOIN sWf.tWfApprovalAction AA ON AA.DocSourceId = QR.Id AND AA.WfFunctionalityId = 2 AND AA.DocSourceTypeId = 2041
	LEFT JOIN sWf.tWfStatusMaster SM ON SM.Id = AA.ActionStatusId
	LEFT JOIN sWf.tWfFunctionalityMaster WFM ON WFM.Id = 2
	LEFT JOIN [sWf].[tWfSetup] SP ON SP.WfFunctionalityId = WFM.Id AND SP.WfTypeMasterId = 3
	LEFT JOIN sSecurity.tUser U ON U.Id = AA.ActionEmployeeId
	LEFT JOIN  sHrm.tEmployeeMaster  EM ON EM.Id = U.SourceId AND U.SourceId IS NOT NULL
	WHERE  SP.WfTypeMasterId = 3
	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,
		ISNULL(U.SourceTypeId,95) AS ParticipantSourceTypeId,
		--Case when U.SourceId IS NULL 95 AS ParticipantSourceTypeId,
		U.SourceId AS SourceId,
		EM.Code AS Code ,
		ISNULL(EM.FirstName +' '+ EM.MiddleName +' ' +EM.LastName,U.DisplayTitle) 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 sSecurity.tUser U ON U.Id = AA.ActionEmployeeId
	LEFT JOIN  sHrm.tEmployeeMaster  EM ON EM.Id = U.SourceId AND U.SourceId IS NOT NULL
	
	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,
		ISNULL(U.SourceTypeId,95) AS ParticipantSourceTypeId,
		--Case when U.SourceId IS NULL 95 AS ParticipantSourceTypeId,
		U.SourceId AS SourceId,
		EM.Code AS Code ,
		ISNULL(EM.FirstName +' '+ EM.MiddleName +' ' +EM.LastName,U.DisplayTitle) 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
	LEFT JOIN sWf.tWfApprovalAction AA ON AA.DocSourceId = PO.Id AND AA.WfFunctionalityId = FAA.WfFunctionalityId AND AA.DocSourceTypeId = 2042
	LEFT JOIN sSecurity.tUser U ON U.Id = FAA.AuthoritySourceId AND FAA.AuthoritySourceTypeId = 1019 AND U.Id = AA.ActionEmployeeId
	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 = U.SourceId AND U.SourceId IS NOT NULL
	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,
		--Case when U.SourceId IS NULL 95 AS ParticipantSourceTypeId,
		EM.Id AS SourceId,
		EM.Code AS Code ,
		ISNULL(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 sSecurity.tUser U ON U.Id = AA.ActionEmployeeId
	LEFT JOIN  sHrm.tEmployeeMaster  EM ON EM.Id = AA.ActionEmployeeId
	-- WHERE HL.ActionByEmployeeId = @rUserId
	WHERE HL.ActionByEmployeeId = (SELECT U.SourceId FROM sSecurity.tUser U 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,
		ISNULL(U.SourceTypeId,95) AS ParticipantSourceTypeId,
		--Case when U.SourceId IS NULL 95 AS ParticipantSourceTypeId,
		U.SourceId AS SourceId,
		EM.Code AS Code ,
		ISNULL(EM.FirstName +' '+ EM.MiddleName +' ' +EM.LastName,U.DisplayTitle) 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.tWfApprovalAction AA ON AA.DocSourceId = PO.Id AND AA.WfFunctionalityId = 3 AND AA.DocSourceTypeId = 2042
	LEFT JOIN sWf.tWfStatusMaster SM ON SM.Id = AA.ActionStatusId
	INNER JOIN sWf.tWfFunctionalityMaster WFM ON WFM.Id = 1
	INNER JOIN [sWf].[tWfSetup] SP ON SP.WfFunctionalityId = WFM.Id AND SP.WfTypeMasterId = 3
	LEFT JOIN sSecurity.tUser U ON U.Id = AA.ActionEmployeeId
	LEFT JOIN  sHrm.tEmployeeMaster  EM ON EM.Id = U.SourceId AND U.SourceId IS NOT NULL
	WHERE SP.WfTypeMasterId = 3
	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,
		ISNULL(U.SourceTypeId,95) AS ParticipantSourceTypeId,
		--Case when U.SourceId IS NULL 95 AS ParticipantSourceTypeId,
		U.SourceId AS SourceId,
		EM.Code AS Code ,
		ISNULL(EM.FirstName +' '+ EM.MiddleName +' ' +EM.LastName,U.DisplayTitle) 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 sSecurity.tUser U ON U.Id = AA.ActionEmployeeId
	LEFT JOIN  sHrm.tEmployeeMaster  EM ON EM.Id = U.SourceId AND U.SourceId IS NOT NULL
	
	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,
		ISNULL(U.SourceTypeId,95) AS ParticipantSourceTypeId,
		--Case when U.SourceId IS NULL 95 AS ParticipantSourceTypeId,
		U.SourceId AS SourceId,
		EM.Code AS Code ,
		ISNULL(EM.FirstName +' '+ EM.MiddleName +' ' +EM.LastName,U.DisplayTitle) 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
	LEFT JOIN sWf.tWfApprovalAction AA ON AA.DocSourceId = GRN.Id AND AA.WfFunctionalityId = FAA.WfFunctionalityId AND AA.DocSourceTypeId = 2043
	LEFT JOIN sSecurity.tUser U ON U.Id = FAA.AuthoritySourceId AND FAA.AuthoritySourceTypeId = 1019 AND U.Id = AA.ActionEmployeeId
	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 = U.SourceId AND U.SourceId IS NOT NULL
	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,
		--Case when U.SourceId IS NULL 95 AS ParticipantSourceTypeId,
		EM.Id AS SourceId,
		EM.Code AS Code ,
		ISNULL(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 sSecurity.tUser U ON U.Id = AA.ActionEmployeeId
	LEFT JOIN  sHrm.tEmployeeMaster  EM ON EM.Id = AA.ActionEmployeeId
	-- WHERE HL.ActionByEmployeeId = @rUserId
	WHERE HL.ActionByEmployeeId = (SELECT U.SourceId FROM sSecurity.tUser U 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,
		ISNULL(U.SourceTypeId,95) AS ParticipantSourceTypeId,
		--Case when U.SourceId IS NULL 95 AS ParticipantSourceTypeId,
		U.SourceId AS SourceId,
		EM.Code AS Code ,
		ISNULL(EM.FirstName +' '+ EM.MiddleName +' ' +EM.LastName,U.DisplayTitle) 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.tWfApprovalAction AA ON AA.DocSourceId = GRN.Id AND AA.WfFunctionalityId = 4 AND AA.DocSourceTypeId = 2043
	LEFT JOIN sWf.tWfStatusMaster SM ON SM.Id = AA.ActionStatusId
	INNER JOIN sWf.tWfFunctionalityMaster WFM ON WFM.Id = 4
	INNER JOIN [sWf].[tWfSetup] SP ON SP.WfFunctionalityId = WFM.Id AND SP.WfTypeMasterId = 3
	LEFT JOIN sSecurity.tUser U ON U.Id = AA.ActionEmployeeId
	LEFT JOIN  sHrm.tEmployeeMaster  EM ON EM.Id = U.SourceId AND U.SourceId IS NOT NULL
	WHERE SP.WfTypeMasterId = 3
	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,
		ISNULL(U.SourceTypeId,95) AS ParticipantSourceTypeId,
		--Case when U.SourceId IS NULL 95 AS ParticipantSourceTypeId,
		U.SourceId AS SourceId,
		EM.Code AS Code ,
		ISNULL(EM.FirstName +' '+ EM.MiddleName +' ' +EM.LastName,U.DisplayTitle) 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 sSecurity.tUser U ON U.Id = AA.ActionEmployeeId
	LEFT JOIN  sHrm.tEmployeeMaster  EM ON EM.Id = U.SourceId AND U.SourceId IS NOT NULL
	
	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,
		ISNULL(U.SourceTypeId,95) AS ParticipantSourceTypeId,
		--Case when U.SourceId IS NULL 95 AS ParticipantSourceTypeId,
		U.SourceId AS SourceId,
		EM.Code AS Code ,
		ISNULL(EM.FirstName +' '+ EM.MiddleName +' ' +EM.LastName,U.DisplayTitle) 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
	LEFT JOIN sWf.tWfApprovalAction AA ON AA.DocSourceId = SR.Id AND AA.WfFunctionalityId = FAA.WfFunctionalityId AND AA.DocSourceTypeId = 2043
	LEFT JOIN sSecurity.tUser U ON U.Id = FAA.AuthoritySourceId AND FAA.AuthoritySourceTypeId = 1019 AND U.Id = AA.ActionEmployeeId
	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 = U.SourceId AND U.SourceId IS NOT NULL
	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,
		--Case when U.SourceId IS NULL 95 AS ParticipantSourceTypeId,
		EM.Id AS SourceId,
		EM.Code AS Code ,
		ISNULL(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 sSecurity.tUser U ON U.Id = AA.ActionEmployeeId
	LEFT JOIN  sHrm.tEmployeeMaster  EM ON EM.Id = AA.ActionEmployeeId
	-- WHERE HL.ActionByEmployeeId = @rUserId
	WHERE HL.ActionByEmployeeId = (SELECT U.SourceId FROM sSecurity.tUser U 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,
		ISNULL(U.SourceTypeId,95) AS ParticipantSourceTypeId,
		--Case when U.SourceId IS NULL 95 AS ParticipantSourceTypeId,
		U.SourceId AS SourceId,
		EM.Code AS Code ,
		ISNULL(EM.FirstName +' '+ EM.MiddleName +' ' +EM.LastName,U.DisplayTitle) 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.tWfApprovalAction AA ON AA.DocSourceId = SR.Id AND AA.WfFunctionalityId = 5 AND AA.DocSourceTypeId = 2044
	LEFT JOIN sWf.tWfStatusMaster SM ON SM.Id = AA.ActionStatusId
	INNER JOIN sWf.tWfFunctionalityMaster WFM ON WFM.Id = 5
	INNER JOIN [sWf].[tWfSetup] SP ON SP.WfFunctionalityId = WFM.Id AND SP.WfTypeMasterId = 3
	LEFT JOIN sSecurity.tUser U ON U.Id = AA.ActionEmployeeId
	LEFT JOIN  sHrm.tEmployeeMaster  EM ON EM.Id = U.SourceId AND U.SourceId IS NOT NULL
	WHERE SP.WfTypeMasterId = 3
	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))
	)AS t
	
	SET @totalCount = (SELECT Count(RowNum) FROM #ApprovalReq 
	WHERE ((CAST(CreatedDateTime AS DATE) >= CAST(@rFromDate AS DATE)) OR (ISNULL(@rFromDate,'')=''))
				AND((CAST(CreatedDateTime AS DATE) <= CAST(@rToDate AS DATE)) OR (ISNULL(@rToDate,'')='')))
	SELECT * FROM #ApprovalReq 
	WHERE RowNum BETWEEN
		((@rPageNo-1)*@rPageSize +1) AND (@rPageNo*@rPageSize)
		AND ((CAST(CreatedDateTime AS DATE) >= CAST(@rFromDate AS DATE)) OR (ISNULL(@rFromDate,'')=''))
				AND((CAST(CreatedDateTime AS DATE) <= CAST(@rToDate AS DATE)) OR (ISNULL(@rToDate,'')=''))
	SELECT @totalCount AS TotalRecords
	DROP TABLE #ApprovalReq

	 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 [sWorkflow].[pApprovalRequestGet]...';


GO



ALTER PROCEDURE [sEMeeting].[pCancelMeeting]
	@rId bigint

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	BEGIN
		BEGIN TRY
			
			IF EXISTS (SELECT 1 FROM sEMeeting.tOnlineMeeting WHERE IsCompleted = 550 AND Id = @rId)
			BEGIN
				SELECT -1 as Result
			END
			IF EXISTS (SELECT 1 FROM sEMeeting.tOnlineMeeting WHERE StartDate >= GetUtcDate() AND Id = @rId)
			BEGIN
				SELECT -102 as Result
			END
			ELSE
			BEGIN
				Update sEMeeting.tOnlineMeeting SET IsCompleted = 551 WHERE StartDate < GetUtcDate() AND IsCompleted = 549 AND Id = @rId
				SELECT 1 as Result
			END
		END TRY
		BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -101 AS Result
	END CATCH
	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,
			CASE WHEN @rIsCompleted = 0 THEN 549 ELSE 0 END,
			@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 = CASE WHEN @rIsCompleted = 1 THEN 550 ELSE 549 END,
		   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].[pOnlineMeetingClassGet]...';


GO


ALTER PROCEDURE [sEMeeting].[pOnlineMeetingClassGet]
	@rDepartmentId int,
	@rOrgId int,
	@rUserId bigint

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

	BEGIN TRY
		SELECT DISTINCT CM.Id,CM.DisplayTitle AS Title FROM sSetup.tDivisionMaster DM
                               INNER JOIN sSetup.tClassMaster CM ON CM.Id=DM.ClassId AND CM.OrgId=  @rOrgId 
                               INNER JOIN sSecurity.tUserAccess U ON U.SourceId = DM.Id AND U.SourceTypeId=2005
                               WHERE  CM.DepartmentId= @rDepartmentId  AND U.UserId = @rUserId
	END TRY

	BEGIN CATCH
	 SELECT -1 as Result
	END CATCH

END
GO
PRINT N'Altering Procedure [sEMeeting].[pOnlineMeetingStudentGet]...';


GO


ALTER PROCEDURE [sEMeeting].[pOnlineMeetingStudentGet]
	@rDivisionId int,
	@rOrgId int

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

	BEGIN TRY

	BEGIN
		
		SELECT AcademicId as Id,(Code+' - '+CONVERT(NVARCHAR(10),RollNo)+' - '+Name) AS Title from sStudent.vStudentAcademic WHERE StatusId=1 AND DivisionId=@rDivisionId AND					OrgId=@rOrgId AND	IsActiveBatch=1 ORDER BY RollNo 
	END 
	END TRY
	BEGIN CATCH 
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Altering Procedure [sEMeeting].[pUpdateMeetingDetails]...';


GO


ALTER PROCEDURE [sEMeeting].[pUpdateMeetingDetails]
	@rId bigint,
	@rType nvarchar(20)

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

	BEGIN TRY
 
	IF EXISTS (SELECT 1 from [sEMeeting].[tOnlineMeeting] where Id = @rId AND @rType IN ('Join', 'Start Again', 'Complete'))
	BEGIN
	IF (@rType = 'Join')
		UPDATE [sEMeeting].[tOnlineMeeting] SET IsMeetingStarted=1, StartDateTime = GetUtcDate() WHERE Id= @rId

	ELSE IF (@rType = 'Start Again')
		UPDATE [sEMeeting].[tOnlineMeeting] SET IsCompleted=549,IsMeetingStarted=1 WHERE Id= @rId	

	ELSE IF (@rType = 'Complete')
		UPDATE [sEMeeting].[tOnlineMeeting] SET IsCompleted=550,IsMeetingStarted=0,EndDateTime = GetUtcDate() WHERE Id= @rId

	SELECT 1 as Result
	END 
	ELSE
	BEGIN
		SELECT -101 as Result
	END
	END TRY

	BEGIN CATCH
	SELECT -1 as Result
	END CATCH

END
GO
PRINT N'Altering Procedure [sEMeeting].[pValidateOnlineMeetingTeacher]...';


GO

ALTER PROCEDURE [sEMeeting].[pValidateOnlineMeetingTeacher]
@rOnlineMeetingId bigint = 0,
@rId bigint = 0,
@rStartDate nvarchar(50),
@rStartTime nvarchar(50),
@rEndDate nvarchar(50),
@rEndTime nvarchar(50),
@rMeetingAccountId int = 0

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	BEGIN
		BEGIN TRY
		BEGIN
		if(@rOnlineMeetingId = 0)
		BEGIN
			SELECT 1 
			FROM sEMeeting.tOnlineMeeting OM
			WHERE HostEmployeeId = @rId
        AND (
            (@rStartDate BETWEEN StartDate AND EndDate OR @rEndDate BETWEEN StartDate AND EndDate)
            OR
            (StartDate BETWEEN @rStartDate AND @rEndDate OR EndDate BETWEEN @rStartDate AND @rEndDate)
        )
        AND (
            (@rStartTime BETWEEN StartTime AND EndTime OR @rEndTime BETWEEN StartTime AND EndTime)
            OR
            (StartTime BETWEEN @rStartTime AND @rEndTime OR EndTime BETWEEN @rStartTime AND @rEndTime)
        )
		AND OM.IsCompleted <> 551
		END
		ELSE
		BEGIN
		SELECT 1 
			FROM sEMeeting.tOnlineMeeting OM
			WHERE HostEmployeeId = @rId
        AND (
            (@rStartDate BETWEEN StartDate AND EndDate OR @rEndDate BETWEEN StartDate AND EndDate)
            OR
            (StartDate BETWEEN @rStartDate AND @rEndDate OR EndDate BETWEEN @rStartDate AND @rEndDate)
        )
        AND (
            (@rStartTime BETWEEN StartTime AND EndTime OR @rEndTime BETWEEN StartTime AND EndTime)
            OR
            (StartTime BETWEEN @rStartTime AND @rEndTime OR EndTime BETWEEN @rStartTime AND @rEndTime)
        ) AND @rOnlineMeetingId <> OM.Id
		END
		END
		END TRY
		BEGIN CATCH
		SELECT -101 AS Result
		END CATCH
	END
GO
PRINT N'Altering Procedure [sFee].[pFeeSummaryDashboard]...';


GO


--exec [sPurchase].[pGoodsReceivedNoteApprovedGet] 991100002
ALTER PROCEDURE [sPurchase].[pGoodsReceivedNoteApprovedGet]
	  @rId INT
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
		SELECT  GRN.Id,
				GRN.GRNNumber                               ,
				GRN.OrgGroupId,
				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 AND GRN.StatusId = 3

		SELECT GRND.Id,
			   GRND.GoodsReceivedNoteId,
			   GRND.PurchaseOrderDetailId,
			   GRND.OrgGroupId,
			   SUMa.Id AS UnitTypeId,
			   GRND.StockItemId,
			   GRND.POQty,
			   GRND.ReceivedQty 
			   - (SELECT ISNULL(Sum(QCD.AcceptedQty + QCD.RejectedQty), 0) AS AdjustedReceivedQty
				FROM [sPurchase].[tGoodsReceivedNote] GRN
					 INNER JOIN [sPurchase].[tGoodsReceivedNoteDetail] GRND1 ON GRND1.[GoodsReceivedNoteId] = GRN.Id
					 LEFT JOIN [sPurchase].[tQualityCheckDetail] QCD ON QCD.[GoodsReceivedNoteDetailId] = GRND1.Id
				WHERE GRND1.[GoodsReceivedNoteId] = GRN.Id AND GRND1.Id = GRND.Id
				GROUP BY GRND1.[GoodsReceivedNoteId]
				HAVING SUM(GRND1.ReceivedQty) > ISNULL(SUM(QCD.AcceptedQty + QCD.RejectedQty), 0)) AS 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 AND GRN.StatusId = 3 AND GRND.ReceivedQty > 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].[pGoodsReceivedNoteApprovedSearchGet]...';


GO

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

	@rNumber NVARCHAR(30) = '',
	@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.IsObsolete = 0 AND GRN.StatusId = 3
				AND GRN.Id NOT IN
				(SELECT GRN8.GoodsReceivedNoteId
				  FROM [sPurchase].[tGoodsReceivedNoteDetail] GRN8
				  WHERE GRN8.GoodsReceivedNoteId = GRN.Id 
				  AND  GRN8.ReceivedQty <=
				 (
				  SELECT ISNULL(SUM(QCD.AcceptedQty),0)+ISNULL(SUM(QCD.RejectedQty),0)
				  FROM [sPurchase].[tQualityCheckDetail] QCD
				  INNER JOIN [sPurchase].[tQualityCheck] QC ON QCD.QualityCheckId = Qc.Id
				  WHERE  QC.GoodsReceivedNoteId = GRN8.GoodsReceivedNoteId	AND QCD.GoodsReceivedNoteDetailId =GRN8.Id
				  GROUP BY QC.GoodsReceivedNoteId) 
				  )
				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.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.IsObsolete = 0 AND GRN.StatusId = 3
				AND GRN.Id NOT IN
				(SELECT GRN8.GoodsReceivedNoteId
				  FROM [sPurchase].[tGoodsReceivedNoteDetail] GRN8
				  WHERE GRN8.GoodsReceivedNoteId = GRN.Id 
				  AND  GRN8.ReceivedQty <=
				 (
				  SELECT ISNULL(SUM(QCD.AcceptedQty),0)+ISNULL(SUM(QCD.RejectedQty),0)
				  FROM [sPurchase].[tQualityCheckDetail] QCD
				  INNER JOIN [sPurchase].[tQualityCheck] QC ON QCD.QualityCheckId = Qc.Id
				  WHERE  QC.GoodsReceivedNoteId = GRN8.GoodsReceivedNoteId	AND QCD.GoodsReceivedNoteDetailId =GRN8.Id
				  GROUP BY QC.GoodsReceivedNoteId) 
				  )
				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].[pGoodsReceivedNoteGet]...';


GO

--exec [sPurchase].[pGoodsReceivedNoteGet] 991100001
ALTER PROCEDURE [sPurchase].[pGoodsReceivedNoteGet]
	  @rId INT
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
		SELECT  GRN.Id,
				GRN.GRNNumber                               ,
				GRN.OrgGroupId,
				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,
			   (SELECT GRND1.ReceivedQty - ISNULL(SUM(SRD.RejectedQty), 0)
				from sPurchase.tGoodsReceivedNoteDetail GRND1 
				left join [sPurchase].[tSalesReturnDetail] SRD ON GRND1.Id = SRD.GoodsReceivedNoteDetailId 
				where GRND1.GoodsReceivedNoteId = @rId AND GRND1.Id = GRND.Id group by GRND1.ReceivedQty)
			   AS 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-30',1,10,null
ALTER PROCEDURE [sPurchase].[pGoodsReceivedNoteSearchGet]

	@rNumber NVARCHAR(30) = '',
	@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.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-30',1,10,null
ALTER PROCEDURE [sPurchase].[pGoodsReceivedNoteSearchSRGet]

	@rNumber NVARCHAR(30) = '',
	@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.StatusId = 3
							AND GRN.Id IN
							(SELECT DISTINCT GRN12.Id FROM sPurchase.tSalesReturnDetail SRD
							INNER JOIN sPurchase.tSalesReturn SR ON SR.Id = SRD.SalesReturnId
							INNER JOIN sPurchase.tGoodsReceivedNote GRN12 ON Sr.GoodsReceivedNoteId = Grn12.Id
							INNER JOIN [sPurchase].[tGoodsReceivedNoteDetail] GRND ON SRD.GoodsReceivedNoteDetailId = GRND.Id
							AND GRND.GoodsReceivedNoteId = GRN12.Id
							GROUP BY GRN12.Id
							HAVING  SUM(SRD.RejectedQty) < (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))
							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.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.StatusId = 3
							AND GRN.Id IN
							(SELECT DISTINCT GRN12.Id 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
							GROUP BY GRN12.Id
							HAVING  (ISNULL(SUM(QCD1.RejectedQty),0) >(
							SELECT ISNULL(SUM(SRD.RejectedQty),0) FROM sPurchase.tSalesReturnDetail SRD
							INNER JOIN sPurchase.tSalesReturn SR ON SR.Id = SRD.SalesReturnId
							INNER JOIN sPurchase.tGoodsReceivedNote GRN1 ON Sr.GoodsReceivedNoteId = Grn1.Id
							INNER JOIN [sPurchase].[tGoodsReceivedNoteDetail] GRND ON SRD.GoodsReceivedNoteDetailId = GRND.Id
							AND GRND.GoodsReceivedNoteId = GRN1.Id))
							)
							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] 991100003
ALTER PROCEDURE [sPurchase].[pGoodsReceivedNoteSRGet]
	  @rId INT
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY

		IF((SELECT (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 = @rId) -
				 (SELECT ISNULL(SUM(SRD.RejectedQty),0) FROM sPurchase.tSalesReturnDetail SRD
				INNER JOIN sPurchase.tSalesReturn SR ON SR.Id = SRD.SalesReturnId
				INNER JOIN [sPurchase].[tGoodsReceivedNoteDetail] GRND ON SRD.GoodsReceivedNoteDetailId = GRND.Id
				AND GRND.GoodsReceivedNoteId = @rId
				WHERE SR.GoodsReceivedNoteId = @rId)) = 0)
		BEGIN
			SELECT -101
		END
		ELSE
		BEGIN
			SELECT DISTINCT GRN.Id AS GoodsReceivedNoteId,
					GRN.GRNNumber,
					GRN.OrgGroupId,
					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 AND GRN.StatusId = 3

			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,
					(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) -
					 (SELECT ISNULL(SUM(SRD.RejectedQty),0) FROM sPurchase.tSalesReturnDetail SRD
					INNER JOIN sPurchase.tSalesReturn SR ON SR.Id = SRD.SalesReturnId
					WHERE SR.GoodsReceivedNoteId = GRN.Id AND SRD.GoodsReceivedNoteDetailId = GRND.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 AND GRN.StatusId = 3
		END
	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,
		@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
		    IF NOT EXISTS(SELECT Id FROM sPurchase.tInvoiceGenerate WHERE Id = @rId AND CreatedUserId = @rUserId)
            BEGIN
            SELECT -103
            END
			ELSE
			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
		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,
				0, 		 
				@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].[pInvoiceGenerateGet]...';


GO


ALTER PROCEDURE [sPurchase].[pInvoiceGenerateGet]
	  @rId INT
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
		SELECT  IG.Id,
				IG.INVNumber,
				IG.OrgGroupId,
				IG.GoodsReceivedNoteId,
				IG.RequestedBy,
				IG.VendorId,
				IG.InvoiceDate,
				IG.InvoiceDueDate,
				IG.BillToAddress,
				IG.ShipToAddress,
				IG.Remarks,
				ISNULL(GRN.GRNNumber,'') AS GRNNumber,
				IG.StatusId,
				ISNULL(SM.Title,'') AS Status,
				ISNULL(VM.Title,'') AS VendorName,
				ISNULL(VM.Code,'') AS VendorCode
		FROM   [sPurchase].[tInvoiceGenerate] IG(NOLOCK) 
		LEFT JOIN [sPurchase].[tGoodsReceivedNote] GRN ON GRN.Id = IG.GoodsReceivedNoteID
		LEFT JOIN sProcurement.tVendorMaster  VM ON IG.VendorId = VM.ID
		LEFT JOIN [sWf].[tWfStatusMaster] SM ON SM.Id = IG.StatusId
		WHERE  IG.Id=@rId AND IG.IsObsolete = 0

		SELECT IGD.Id,
			   IGD.InvoiceGenerateId,
			   IGD.GoodsReceivedNoteDetailId,
			   IGD.OrgGroupId,
			   SUMa.Id AS UnitTypeId,
			   IGD.StockItemId,
			   IGD.POQty,
			   IGD.ReceivedQty,
			   IGD.AcceptedQty,
			   IGD.RejectedQty, 
			   IGD.UnitPrice,
			   IGD.ReasonForRejection,
			   SCM.Id AS CategoryId,
			   SCM.Title AS CategoryName,
			   0 AS SubCategoryId,
			   SIM.Code	AS StockItemCode,
			   SIM.Title AS StockItemName,
			   SUMa.Code AS UOM
		FROM   [sPurchase].[tInvoiceGenerateDetail] IGD (NOLOCK)
			   INNER JOIN	sPurchase.tInvoiceGenerate IG	ON IG.Id = IGD.InvoiceGenerateId AND IG.IsObsolete = 0
			   INNER JOIN	sIp.tStockItemMaster SIM	ON SIM.Id = IGD.StockItemId 
			   LEFT JOIN [sIp].[tStockItemCategoryMaster] SCM ON SCM.Id = SIM.StockItemCategoryId
			   INNER JOIN  sFinanceCommon.tStockUomMaster SUMa ON SUMa.Id = SIM.IssueStockUomId
		WHERE  IGD.InvoiceGenerateId=@rId

	END TRY

	BEGIN CATCH
    IF @@TRANCOUNT > 0
        ROLLBACK TRAN --RollBack in case of Error
    
    DECLARE @ErrorMessage NVARCHAR(4000);  
    DECLARE @ErrorSeverity INT;  
    DECLARE @ErrorState INT;  
    SELECT   
       @ErrorMessage = ERROR_MESSAGE(),  
       @ErrorSeverity = ERROR_SEVERITY(),  
       @ErrorState = ERROR_STATE();  
    RAISERROR (@ErrorMessage, @ErrorSeverity, @ErrorState);  
    
	END CATCH
END
GO
PRINT N'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) = '',
	@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.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].[pPurchaseOrderApprovedGet]...';


GO

--exec [sPurchase].[pPurchaseOrderApprovedGet] 991100003
ALTER PROCEDURE [sPurchase].[pPurchaseOrderApprovedGet]
	  @rId INT
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
		IF EXISTS(SELECT PO.Id
		FROM   [sPurchase].[tPurchaseOrder] PO(NOLOCK) 
		INNER JOIN [sPurchase].[tGoodsReceivedNote] GRN ON GRN.PurchaseOrderId = PO.Id AND GRN.StatusId IN (1,2)
		WHERE PO.Id = @rId)
		BEGIN
			SELECT -101
		END
		ELSE
		BEGIN
			SELECT PO.Id AS PurchaseOrderId,
				   PO.RefNumber AS PurchaseOrderNumber,
				   PO.PurchaseRequestId,
				   PO.RequestedBy,
				   PO.StatusId,
				   PO.VendorId,
				   PO.OrgGroupId,
				   PO.PODate AS PODueDate,
				   PO.BillToAddress,
				   PO.ShipToAddress,
				   PO.RequiredBy,
				   ISNULL(SM.Title,'') AS Status,
				   VM.Code AS VendorCode,
				   VM.Title AS VendorName,
				   PR.Number AS PurchaseRequestNumber 
			FROM   [sPurchase].[tPurchaseOrder] PO(NOLOCK) 
				   LEFT JOIN [sPurchase].[tPurchaseRequest] PR ON PR.ID = PO.PurchaseRequestId
				   LEFT JOIN sProcurement.tVendorMaster  VM ON PO.VendorId = VM.ID 
				   LEFT JOIN [sWf].[tWfStatusMaster] SM ON SM.Id = PO.StatusId
			WHERE  PO.Id=@rId AND PO.IsObsolete = 0 AND PO.StatusId = 3

			DECLARE @PreviousGrnQty INT,@UnitPrice INT
			--Select @PreviousGrnQty = Sum(GRND.ReceivedQty)
			--from [sPurchase].[tGoodsReceivedNote] GRN 
			--Left Join sPurchase.tGoodsReceivedNoteDetail GRND ON GRND.GoodsReceivedNoteId = GRN.Id
			--where GRN.PurchaseOrderId = @rId

			SELECT DISTINCT POD.Id AS PurchaseOrderDetailId,
				   POD.PurchaseOrderId,
				   POD.OrgGroupId,
				   POD.PurchaseRequestDetailId,
				   POD.StockItemId,
				   POD.TotalQty AS POQty,
				   POD.Remark, 
				   SUMa.Id AS UnitTypeId,
				   SIM.Code		AS StockItemCode,
				   SIM.Title AS StockItemName,
				   SUMa.Code	AS UOM,
				   SCM.Id AS CategoryId,
				   SCM.Title AS CategoryName,
				   0 AS SubCategoryId,
				   CAST((POD.TotalQty - (SELECT SUM(GRND.ReceivedQty)
					FROM [sPurchase].[tGoodsReceivedNote] GRN 
					LEFT JOIN sPurchase.tGoodsReceivedNoteDetail GRND ON GRND.GoodsReceivedNoteId = GRN.Id
					WHERE GRND.PurchaseOrderDetailId = POD.Id AND GRN.PurchaseOrderId = PO.Id AND GRN.StatusID <> 4)) AS DECIMAL) AS ReceivedQty ,
				   (SELECT SUM(GRND.ReceivedQty)
					FROM [sPurchase].[tGoodsReceivedNote] GRN 
					LEFT JOIN sPurchase.tGoodsReceivedNoteDetail GRND ON GRND.GoodsReceivedNoteId = GRN.Id
					WHERE GRND.PurchaseOrderDetailId = POD.Id AND GRN.PurchaseOrderId = PO.Id AND GRN.StatusID <> 4) AS PreviousGRNQty,
				   (SELECT QRD.TargetPrice FROM [sPurchase].[tQuotationRequestDetail] QRD
					INNER JOIN [sPurchase].[tQuotationRequest] QR ON QR.Id = QRD.QuotationRequestId
					WHERE QRD.StockItemId = POD.StockItemId AND POD.PurchaseRequestDetailId = QRD.PurchaseRequestDetailId
					AND QR.PurchaseRequestId = PO.PurchaseRequestId) AS UnitPrice
			FROM   [sPurchase].[tPurchaseOrderDetail] POD (NOLOCK)
				   INNER JOIN	sPurchase.tPurchaseOrder PO	ON PO.Id = POD.PurchaseOrderId AND PO.IsObsolete = 0 AND PO.StatusId = 3
				   INNER JOIN	sIp.tStockItemMaster SIM	ON SIM.Id = POD.StockItemId 
				   INNER JOIN  sFinanceCommon.tStockUomMaster SUMa ON SUMa.Id = SIM.IssueStockUomId
				   LEFT JOIN [sIp].[tStockItemCategoryMaster] SCM ON SCM.Id = SIM.StockItemCategoryId
			WHERE  POD.PurchaseOrderId=@rId     
		END
		
	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].[pPurchaseOrderApprovedSearchGet]...';


GO


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

	@rNumber nvarchar(30) = '',
	@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 PO.Id NOT IN (SELECT DISTINCT PO.Id FROM sPurchase.tPurchaseOrder PO
				INNER JOIN [sPurchase].[tGoodsReceivedNote] GRN ON GRN.PurchaseOrderId = PO.Id
				INNER JOIN sPurchase.tGoodsReceivedNoteDetail GRND ON GRND.GoodsReceivedNoteId = GRN.Id AND GRND.PreviousGRNQty+GRND.ReceivedQty >= GRND.POQty
				Where Grn.PurchaseOrderId = PO.Id AND GRN.StatusID <> 4)
				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.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 PO.Id NOT IN (SELECT DISTINCT PO.Id FROM sPurchase.tPurchaseOrder PO
				INNER JOIN [sPurchase].[tGoodsReceivedNote] GRN ON GRN.PurchaseOrderId = PO.Id
				INNER JOIN sPurchase.tGoodsReceivedNoteDetail GRND ON GRND.GoodsReceivedNoteId = GRN.Id AND GRND.PreviousGRNQty+GRND.ReceivedQty >= GRND.POQty
				WHERE Grn.PurchaseOrderId = PO.Id AND GRN.StatusId <> 4)
				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].[pPurchaseOrderGet]...';


GO


ALTER PROCEDURE [sPurchase].[pPurchaseOrderGet]
	  @rId INT
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
		SELECT PO.Id,
			   PO.RefNumber,
			   PO.PurchaseRequestId,
			   PR.Number AS PurchaseRequestNumber,
			   PO.RequestedBy,
			   PO.StatusId,
			   PO.VendorId,
			   PO.OrgGroupId,
			   PO.PODate,
			   PO.BillToAddress,
			   PO.ShipToAddress,
			   PO.RequiredBy,
			   ISNULL(SM.Title,'') AS Status,
			   VM.Code AS VendorCode,
			   VM.Title AS VendorName 
		FROM   [sPurchase].[tPurchaseOrder] PO(NOLOCK) 
			   LEFT JOIN sProcurement.tVendorMaster  VM ON PO.VendorId = VM.ID
			   LEFT JOIN [sWf].[tWfStatusMaster] SM ON SM.Id = PO.StatusId
			   LEFT JOIN [sPurchase].[tPurchaseRequest] PR ON PR.Id = PO.PurchaseRequestId
		WHERE  PO.Id = @rId AND PO.IsObsolete = 0

		SELECT POD.Id,
			   POD.PurchaseOrderId,
			   POD.PurchaseRequestDetailId,
			   POD.OrgGroupId,
			   POD.StockItemId,
			   POD.TotalQty,
			   POD.Remark, 
			   SIM.Code	AS StockItemCode,
			   SIM.Title AS StockItemName,
			   SCM.Title AS CategoryName,
			   SUMa.Id AS UnitTypeId,
			   SUMa.Code AS UOM
		FROM   [sPurchase].[tPurchaseOrderDetail] POD (NOLOCK)
			   INNER JOIN	sPurchase.tPurchaseOrder PO	ON PO.Id = POD.PurchaseOrderId AND PO.IsObsolete = 0
			   INNER JOIN	sIp.tStockItemMaster SIM	ON SIM.Id = POD.StockItemId 
			   LEFT JOIN [sIp].[tStockItemCategoryMaster] SCM ON SCM.Id = SIM.StockItemCategoryId
			   INNER JOIN  sFinanceCommon.tStockUomMaster SUMa ON SUMa.Id = SIM.IssueStockUomId
		WHERE  POD.PurchaseOrderId = @rId

		
	END TRY

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

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


GO



ALTER PROCEDURE [sPurchase].[pPurchaseOrderSearchGet]

	@rNumber NVARCHAR(30) = '',
	@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.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].[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.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] '','',9911,'2021-01-01','2024-12-11',1,10,null
ALTER PROCEDURE [sPurchase].[pPurchaseRequestApprovedSearchGet]

	@rNumber NVARCHAR(30) = '',
	@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 ((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.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 ((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].[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.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].[pPurchaseRequestPOApprovedSearchGet]...';


GO

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

	@rNumber NVARCHAR(30) = '',
	@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.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'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) = '',
	@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.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].[pPurchaseVendorMasterGet]...';


GO


ALTER PROCEDURE [sPurchase].[pPurchaseVendorMasterGet]
	@rOrgGroupId INT,
	@rId INT = 0,
	@rTitle NVARCHAR(300) = '',
	--@rIsWildCardSearch [bit] = 1,
	@rCode NVARCHAR(20) = '',
	@rVendorCategoryId INT = 0
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
		 --IF @rIsWildCardSearch = 1
		 --BEGIN
			 SET @rCode = sCommon.fSearchStringGet(@rCode)
		 --END
		     SET @rTitle = sCommon.fSearchStringGet(@rTitle)
		
	     SELECT 
		  
		    VM.Id,
			VM.Code,
			VM.Title,
			VM.IsObsolete,
			VM.CreatedUserId,
			VM.CreatedDateTime,
			VM.UpdatedUserId,
			VM.UpdatedDateTime,
			--VM.Area,
			--VM.City,
			VM.ContactPersonName,
			--VM.Country,
			ISNULL(VM.CreditDays, 0) CreditDays,
			ISNULL(CAST(VM.CreditLimit AS DECIMAL(18, 2)), '0') CreditLimit,
			--VM.CreditLimit,
			VM.Email,
			VM.FaxNumber,			
			VM.PhoneNumberMobile,
			VM.PhoneNumberOffice,			
			--VM.State,
			VM.StreetFour,
			VM.StreetOne,
			VM.StreetThree,
			VM.StreetTwo,			
			VM.VendorCategoryId,
			VM.ZipCode,
			VC.Title VendorCategory,
			VM.State STATETITLE,
			VM.City CITYTITLE,
			VM.Country COUNTRYTITLE,
			VM.Area Area,
			VM.LocationID		
					
	   FROM sProcurement.tVendorMaster  VM (NOLOCK)
	   LEFT JOIN   sProcurement.tVendorCategoryMaster VC
	   ON  VM.VendorCategoryId = VC.Id  
	   --LEFT JOIN  sCommon.tStateMaster SM 
	   --ON VM.StateId = SM.Id 
	   --LEFT JOIN   sCommon.tCityMaster CM 
	   --ON VM.CityId = CM.Id 
	   --LEFT JOIN    sCommon.tAreaMaster AM 
	   --ON VM.AreaId = AM.Id 
	   --LEFT JOIN   sCommon.tCountryMaster CAM
	   --ON VM.CountryId = CAM.Id 		     
	   WHERE ((VM.Id = @rId) OR (@rId = 0))
	   AND	((VM.Code LIKE @rCode) OR (ISNULL(@rCode, '') = ''))
	   AND ((VM.Title LIKE @rTitle) OR (ISNULL(@rTitle, '') = ''))
	   AND ((VM.VendorCategoryId = @rVendorCategoryId) OR (@rVendorCategoryId = 0))
	   AND  VM.OrgGroupId = @rOrgGroupId
	   AND VM.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].[pQualityCheckAdd]...';


GO




ALTER PROCEDURE [sPurchase].[pQualityCheckAdd]
		@rId BIGINT,
		@rGoodsReceivedNoteId BIGINT,
		@rPurchaseOrderId BIGINT,
		@rRequestedBy NVARCHAR(100),
		@rOrgGroupId SMALLINT,
		@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
		   IF NOT EXISTS(SELECT Id FROM sPurchase.tQualityCheck WHERE Id = @rId AND CreatedUserId = @rUserId)
		   BEGIN
		   SELECT -102
		   END
		   ELSE
		    BEGIN
			IF NOT EXISTS(SELECT SR.Id 
			FROM [sPurchase].[tSalesReturn] SR
			INNER JOIN [sPurchase].[tGoodsReceivedNote] GRN ON SR.GoodsReceivedNoteId = GRN.Id
			INNER JOIN [sPurchase].[tQualityCheck] QC ON GRN.Id = QC.GoodsReceivedNoteId
			WHERE QC.Id = @rId)
			BEGIN
				--CREATE TABLE #temp_table (
				--	OrgGroupId SMALLINT,
				--	StockItemId BIGINT,
				--	AcceptedQty DECIMAL(12,2),
				--	Operation NVARCHAR(20),
				--	UserId BIGINT
				--);

				--INSERT INTO #temp_table
				--SELECT QCD.OrgGroupId,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 DL.StockItemId = QCD.StockItemId AND QCD.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
				
				--declare @AcceptedQty decimal = 0
				--Select @AcceptedQty =(Select ISNULL(Sum(SB.AvailableQuantity),0) FROM sProcurement.tStockBatch SB
				--INNER JOIN #temp_table tt ON SB.StockItemId = tt.StockItemId AND tt.Operation = '+'
				--Group by tt.AcceptedQty) -(Select distinct tt1.AcceptedQty
				--FROM sProcurement.tStockBatch SB
				--INNER JOIN #temp_table tt1 ON SB.StockItemId = tt1.StockItemId AND tt1.Operation = '+')

				--UPDATE  sProcurement.tStockBatch
				--SET  AvailableQuantity = AvailableQuantity + @AcceptedQty,
				--	UpdatedUserId = @rUserId,
				--	UpdatedDateTime = sCommon.fGetDate()
				--	where @AcceptedQty > 0
				
				--WHERE  
				
				--(SB.StockItemId = tt.StockItemId) AND
				----(Number = @rNumber OR ISNULL(@rNumber, '') = '') AND
				----(ExpiryDate = @rExpiryDate OR ISNULL(@rExpiryDate, '') = '') AND
				--	SB.OrgGroupId = @rOrgGroupId
				--	AND tt.Operation = '+'
				--Select @AcceptedQty =(Select ISNULL(Sum(SB.AvailableQuantity),0) FROM sProcurement.tStockBatch SB
				--INNER JOIN #temp_table tt ON SB.StockItemId = tt.StockItemId AND tt.Operation = '-'
				--Group by tt.AcceptedQty) -(Select distinct tt1.AcceptedQty
				--FROM sProcurement.tStockBatch SB
				--INNER JOIN #temp_table tt1 ON SB.StockItemId = tt1.StockItemId AND tt1.Operation = '-')

				--UPDATE  sProcurement.tStockBatch
				--SET  AvailableQuantity = AvailableQuantity - @AcceptedQty,
				--	UpdatedUserId = @rUserId,
				--	UpdatedDateTime = sCommon.fGetDate()
				--	where @AcceptedQty > 0
				--WHERE  
				
				--(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
			SELECT -101
		END
		    END
		ELSE
		BEGIN
			IF NOT EXISTS(SELECT SR.Id 
			FROM [sPurchase].[tSalesReturn] SR
			INNER JOIN [sPurchase].[tGoodsReceivedNote] GRN ON SR.GoodsReceivedNoteId = GRN.Id
			INNER JOIN [sPurchase].[tQualityCheck] QC ON GRN.Id = QC.GoodsReceivedNoteId
			WHERE QC.Id = @rId)
			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,
					0, 		 
					@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
				
				
				--inward insert entry
				--DECLARE @XmlString XML;
 
				--SET @XmlString = (
-- 					SELECT 
-- 						   QCD.GoodsReceivedNoteDetailId AS '@StockInwardRequestDetailId',
-- 						   QCD.StockItemId AS '@StockItemId',
-- 						   SIM.Title				AS '@StockItemName',
-- 						   --NULL AS ItemBatch,
-- 						   --NULL AS ItemExpiryDate,
-- 						   QCD.AcceptedQty AS '@InwardQuantity',
-- 						   0 AS '@RequestedQuantity',
-- 						   GRND.UnitPrice AS '@InwardValue'
-- 						   --add unit price
-- 					FROM   [sPurchase].[tQualityCheckDetail] QCD (NOLOCK)
-- 						   INNER JOIN	sPurchase.tQualityCheck QC	ON QC.Id = QCD.QualityCheckId AND QC.IsObsolete = 0
-- 						   INNER JOIN	sIp.tStockItemMaster SIM	ON SIM.Id = QCD.StockItemId 
-- 						   LEFT JOIN [sIp].[tStockItemCategoryMaster] SCM ON SCM.Id = SIM.StockItemCategoryId
-- 						   LEFT JOIN  sFinanceCommon.tStockUomMaster SUMa ON SUMa.Id = SIM.IssueStockUomId
-- 						   LEFT JOIN [sPurchase].[tGoodsReceivedNoteDetail] GRND ON GRND.ID = QCD.GoodsReceivedNoteDetailId
-- 					WHERE  QC.Id=991100001
-- 					--FOR XML AUTO, ROOT('Table'), ELEMENTS
-- 					FOR XML PATH('StockInward'), ROOT('Table')
-- 				);


				---- Print or use @XmlString as needed
				--PRINT CONVERT(NVARCHAR(MAX), @XmlString);
				--Declare @str Nvarchar(MAX) = CAST(@XmlString AS NVARCHAR(MAX))
				----exec sPurchase.pStockInwardAdd_New_Copy_1 @rOrgGroupId,'',0,@rRequestedBy,991100001,'Inward By Quality Check',@rUserId,@str,991100001,@rOrgGroupId,0,null,null
				--exec sProcurement.pStockInwardAdd_New @rOrgGroupId,'',0,@rRequestedBy,991100001,'Inward By Quality Check',@rUserId,@str,991100001,@rOrgGroupId,0,null,null
				
				--declare @AcceptedQtyResult decimal = 0
				--Select @AcceptedQtyResult = (Select distinct QC1.AcceptedQty FROM sProcurement.tStockBatch SB
				--	INNER JOIN sPurchase.tQualityCheckDetail QC1 ON SB.StockItemId = QC1.StockItemId AND QC1.QualityCheckId = @rId)

				--UPDATE  sProcurement.tStockBatch
				--	SET  AvailableQuantity = AvailableQuantity + @AcceptedQtyResult,
				--		UpdatedUserId = @rUserId,
				--		UpdatedDateTime = sCommon.fGetDate()
				--	WHERE  @AcceptedQtyResult > 0
				

				--(SB.StockItemId = QC.StockItemId) AND
				--(Number = @rNumber OR ISNULL(@rNumber, '') = '') AND
				--(ExpiryDate = @rExpiryDate OR ISNULL(@rExpiryDate, '') = '') AND
					--SB.OrgGroupId = @rOrgGroupId AND QualityCheckId = @rId

				SELECT @rId
			END
			SELECT -101;
		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].[pQualityCheckGet]...';


GO

--exec [sPurchase].[pQualityCheckGet] 991100001
ALTER PROCEDURE [sPurchase].[pQualityCheckGet]
	  @rId INT
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
		SELECT  QC.Id,
				QC.QCNumber,
				QC.OrgGroupId,
				QC.GoodsReceivedNoteId,
				QC.PurchaseOrderId,
				QC.RequestedBy,
				ISNULL(GRN.GRNNumber,'') AS GRNNumber,
				QC.StatusId,
				ISNULL(SM.Title,'') AS Status
		FROM   [sPurchase].[tQualityCheck] QC(NOLOCK) 
		LEFT JOIN [sPurchase].[tGoodsReceivedNote] GRN ON GRN.Id = QC.GoodsReceivedNoteID
		LEFT JOIN [sWf].[tWfStatusMaster] SM ON SM.Id = QC.StatusId
		WHERE  QC.Id=@rId AND QC.IsObsolete = 0

		SELECT QCD.Id,
			   QCD.QualityCheckId,
			   QCD.GoodsReceivedNoteDetailId,
			   QCD.OrgGroupId,
			   SUMa.Id AS UnitTypeId,
			   QCD.StockItemId,
			   QCD.POQty,				 
				CASE
					WHEN (Select Count(*) from sPurchase.tQualityCheck QCC where QCC.GoodsReceivedNoteId = QC.GoodsReceivedNoteId AND QCC.StatusId <> 4) = 1 THEN 
						(SELECT GRND.ReceivedQty  FROM [sPurchase].[tGoodsReceivedNoteDetail] GRND
								   WHERE GRND.Id = QCD.GoodsReceivedNoteDetailId
								   AND GRND.GoodsReceivedNoteId = QC.GoodsReceivedNoteId)
					ELSE
						((SELECT GRND.ReceivedQty  FROM [sPurchase].[tGoodsReceivedNoteDetail] GRND
								   WHERE GRND.Id = QCD.GoodsReceivedNoteDetailId
								   AND GRND.GoodsReceivedNoteId = QC.GoodsReceivedNoteId)-
						(SELECT SUM(ISNULL(QCD1.AcceptedQty,0) + ISNULL(QCD1.RejectedQty,0))
						FROM [sPurchase].[tQualityCheckDetail] QCD1 
						INNER JOIN	sPurchase.tQualityCheck QC1	ON QC1.Id = QCD1.QualityCheckId and QC1.GoodsReceivedNoteId = QC.GoodsReceivedNoteID AND QC1.IsObsolete = 0 
						WHERE QC1.GoodsReceivedNoteId = QC.GoodsReceivedNoteID AND QCD1.StockItemId = QCD.StockItemId
						Group By QCD1.StockItemId))+((SELECT SUM(ISNULL(QCD2.AcceptedQty,0) + ISNULL(QCD2.RejectedQty,0))
						FROM [sPurchase].[tQualityCheckDetail] QCD2 
						WHERE QCD2.Id = QCD.Id 
						GROUP BY QCD2.Id))
					END
				AS ReceivedQty,
			   QCD.AcceptedQty,
			   QCD.RejectedQty,
			   QCD.ReasonForRejection, 
			   SCM.Id AS CategoryId,
			   SCM.Title AS CategoryName,
			   0 AS SubCategoryId,
			   SIM.Code				AS StockItemCode,
			   SIM.Title				AS StockItemName,
			   SUMa.Code				AS UOM
		FROM   [sPurchase].[tQualityCheckDetail] QCD (NOLOCK)
			   INNER JOIN	sPurchase.tQualityCheck QC	ON QC.Id = QCD.QualityCheckId AND QC.IsObsolete = 0
			   INNER JOIN	sIp.tStockItemMaster SIM	ON SIM.Id = QCD.StockItemId 
			   LEFT JOIN [sIp].[tStockItemCategoryMaster] SCM ON SCM.Id = SIM.StockItemCategoryId
			   INNER JOIN  sFinanceCommon.tStockUomMaster SUMa ON SUMa.Id = SIM.IssueStockUomId
		WHERE  QCD.QualityCheckId=@rId


	END TRY

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


GO

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

	@rNumber NVARCHAR(30) = '',
	@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,
				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].[pQuotationApprovedVendorGet]...';


GO

--exec sPurchase.pQuotationApprovedVendorGet 991100002,991100001,9911
ALTER PROCEDURE [sPurchase].[pQuotationApprovedVendorGet]
	@rPurchaseRequestId BIGINT = 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.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'Altering Procedure [sPurchase].[pQuotationRequestGet]...';


GO


ALTER PROCEDURE [sPurchase].[pQuotationRequestGet]
	  @rId INT
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
		SELECT QR.Id,
			   QR.Number,
			   QR.PurchaseRequestId,
			   QR.Name,
			   QR.StatusId,
			   QR.VendorId,
			   QR.BranchId,
			   QR.OrgGroupId,
			   QR.RFQDate,
			   QR.Description,
			   QR.StartDate,
			   QR.EndDate,
			   QR.BidOpen,
			   QR.BidClose,
			   QR.PersonContact,
			   QR.Email,
			   QR.SendToVendor,
			   QR.VendorId,
			   ISNULL(SM.Title,'') AS Status,
			   VM.Code AS VendorCode,
			   VM.Title AS VendorName,
			   PR.Number AS PurchaseNumber
		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=@rId AND QR.IsObsolete = 0

		SELECT QRD.Id,
			   QRD.QuotationRequestId,
			   QRD.PurchaseRequestDetailId,
			   QRD.OrgGroupId,
			   QRD.StockItemId,
			   QRD.RequestedQty,
			   QRD.TargetPrice,
			   QRD.Remark, 
			   SIM.Code	AS StockItemCode,
			   SIM.Title AS StockItemName,
			   SCM.Title AS CategoryName,
			   SUMa.Code AS UOM
		FROM   [sPurchase].[tQuotationRequestDetail] QRD (NOLOCK)
			   INNER JOIN	sPurchase.tQuotationRequest QR	ON QR.Id = QRD.QuotationRequestId AND QR.IsObsolete = 0
			   INNER JOIN	sIp.tStockItemMaster SIM	ON SIM.Id = QRD.StockItemId 
			   LEFT JOIN [sIp].[tStockItemCategoryMaster] SCM ON SCM.Id = SIM.StockItemCategoryId
			   INNER JOIN  sFinanceCommon.tStockUomMaster SUMa ON SUMa.Id = SIM.IssueStockUomId
		WHERE  QRD.QuotationRequestId=@rId


	END TRY

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

END
GO
PRINT N'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) = '',
	@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 ((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.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 ((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].[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.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,
			   (SELECT SUM(QCD1.RejectedQty) FROM sPurchase.tQualityCheck QC1
			    INNER JOIN   sPurchase.tQualityCheckDetail QCD1 ON QCD1.QualityCheckId = QC1.Id AND QCD1.RejectedQty > 0
				AND QCD1.GoodsReceivedNoteDetailId = SRD.GoodsReceivedNoteDetailId
				WHERE QC1.GoodsReceivedNoteId = SR.GoodsReceivedNoteId) AS GRNRejectedQty
		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) = '',
	@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,
				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 [sPurchase].[pStockItemMasterGetWithCategory]...';


GO

--exec [sPurchase].[pStockItemMasterGetWithCategory]  9911,991100001,null,null,0,0,991100001
ALTER PROCEDURE [sPurchase].[pStockItemMasterGetWithCategory]
    @rOrgGroupId INT,
	@rId INT = 0,
	@rCode NVARCHAR(100),  
	@rTitle NVARCHAR(100),  
	@rIsAbsoluteTitle BIT = 0,
	@rIsWildCardSearch BIT = 1
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
IF @rIsAbsoluteTitle = 0
	BEGIN
		IF @rIsWildCardSearch = 1
			BEGIN
				SET @rCode = sCommon.fSearchStringGet(@rCode)
				SET @rTitle = sCommon.fSearchStringGet(@rTitle)
			END
	END
 


	SELECT 	SIM.Id,
			SIM.Code,
			--CAST(SIM.StockItemTypeId AS INT) AS StockItemTypeId,
			SIM.Title,
			CAST(ISNULL(sIp.LastPurchasePrice, 0) AS DECIMAL(22, 2)) LastPurchasePrice, 
			SIM.CreatedUserId,
			SIM.CreatedDateTime,
			SIM.UpdatedUserId,
			SIM.UpdatedDateTime,
			--SIT.Title AS StockItemTypeTitle,
			--SIT.Code AS StockItemTypeCode,
			SIM.IssueStockUomId,
			SU.Code UomCode,
			Su.Title UomTitle,
			SIM.IsBatchWiseTracking,
			SCM.Id AS CategoryId,
			SCM.Code AS CategoryName
			
	   FROM	sIp.tStockItemMaster SIM
		INNER JOIN sIp.tStockItemPlanning SIP ON SIP.StockItemId=SIM.Id	

	 --  INNER JOIN sPurchase.tStockItemTypeMaster SIT
		--ON SIM.StockItemTypeId = SIT.Id
	   LEFT OUTER JOIN sFinanceCommon.tStockUomMaster SU
		ON SU.Id = SIM.IssueStockUomId
	   LEFT JOIN [sIp].[tStockItemCategoryMaster] SCM ON SCM.Id = SIM.StockItemCategoryId
	   WHERE((SIM.Id = @rId) OR (@rId = 0)) 
		AND	((SIM.Code LIKE @rCode) OR (ISNULL(@rCode, '') = ''))
		AND	(((SIM.Title LIKE @rTitle) AND @rIsAbsoluteTitle = 0) OR (@rTitle = '' AND @rIsAbsoluteTitle = 0) OR ((SIM.Title = @rTitle ) AND @rIsAbsoluteTitle = 1))
		AND SIM.OrgGroupId = @rOrgGroupId
		AND SIM.IsObsolete= 0
		
END
GO
PRINT N'Altering Procedure [sPurchase].[pStockItemMasterSearchGet]...';


GO
--exec [sPurchase].[pStockItemMasterSearchGet] 991100001,'c'
ALTER PROCEDURE [sPurchase].[pStockItemMasterSearchGet]
	
	@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 IsObsolete= 0
	  
	 
END
GO
PRINT N'Altering Procedure [sSecurity].[pAppPermissionGet]...';


GO

--exec [sWf].[pWfApprovalAdd] 0,991100018, 95, 9911000000270,1,'',1,2,1,9911
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

	IF EXISTS(SELECT SFM.Id FROM [sWf].[tWfFunctionalityMaster] SFM
		INNER JOIN [sWf].[tWfSetup] WFS ON WFS.WfFunctionalityId = SFM.Id
		WHERE WFS.WfTypeMasterId = 2 AND SFM.Id = @rWfFunctionalityId AND @rIsSequancial <> 1)
	BEGIN
		SELECT @rIsSequancial = CASE WHEN WfTypeMasterId = 2 THEN 1 ELSE 0 END,@rWfLevel = WFS.WfLevel FROM [sWf].[tWfFunctionalityMaster] SFM
		INNER JOIN [sWf].[tWfSetup] WFS ON WFS.WfFunctionalityId = SFM.Id
		WHERE WFS.WfTypeMasterId = 2 AND WfLevel > 0 AND SFM.Id = @rWfFunctionalityId
	END

	DECLARE @StatusId SMALLINT
	SET @StatusId = @rActionStatusId

	DECLARE @IsRejectedExists bit = 0

	IF(@rIsSequancial = 1)
	BEGIN
		select @rActionEmployeeId = ISNULL(U.SourceId,U.Id) from   sSecurity.tUser U where U.Id = @rActionEmployeeId

		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

			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
			
			SELECT @lActionByEmployeeId = EmployeeManagerId FROM [sHrm].[tEmployeeJobDetail] WHERE EmployeeId = @rActionEmployeeId
					AND @rActionEmployeeId 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
					,@StatusId
					,''
					,@lActionByEmployeeId
					,sCommon.fGetDate())
		END
		SELECT @rId AS Result
	END
	ELSE
	BEGIN
		IF EXISTS(SELECT AA.Id FROM sWf.tWfApprovalAction AA WHERE AA.ActionStatusId = 3 AND AA.Id = @rId AND AA.ActionEmployeeId <> @rActionEmployeeId)
		BEGIN
			SELECT -201
			SET @IsRejectedExists = 1
		END
		ELSE
		BEGIN
			IF EXISTS(SELECT ID FROM sWf.tWfApprovalAction WHERE id = @rId AND ActionStatusId <> 4)
			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,
					@rActionEmployeeId,
					@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 @rId AS Result 
			END
			ELSE
			BEGIN
				SELECT -101
				SET @IsRejectedExists = 1
			END
		END
	END	
	IF EXISTS(SELECT ID FROM sWf.tWfApprovalAction WHERE id = @rId AND ActionStatusId IN(3,4) AND @IsRejectedExists = 0)
	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].[pWfSetupAdd]...';


GO


-- select * from [sWf].[tWfSetup]
ALTER PROCEDURE [sWf].[pWfSetupAdd]
		@rId SMALLINT,
		@rWfTypeMasterId SMALLINT,
		@rWfLevel SMALLINT,
		@rOrgGroupId SMALLINT,
		@rWfFunctionalityId SMALLINT,
        @rAuthorityList sPurchase.ApprovingAuthorityType READONLY
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
	BEGIN TRANSACTION
		BEGIN
			   

			IF(@rId = 0)
			BEGIN
				IF EXISTS(SELECT WFS.[WfFunctionalityId]
				FROM [sWf].[tWfSetup] WFS(NOLOCK)
				WHERE WFS.[WfFunctionalityId] = @rWfFunctionalityId)
				BEGIN
					SELECT -102
				END
				ELSE
				BEGIN
					IF NOT EXISTS(SELECT WFM.Id
					from [sWf].[tWfFunctionalityMaster] WFM 
					WHERE WFM.Id = @rWfFunctionalityId)
					BEGIN
						SELECT -103
					END
					ELSE
					BEGIN
						INSERT INTO [sWf].[tWfSetup]
						(
						WfTypeMasterId,
						WfLevel,
						OrgGroupId,
						WfFunctionalityId
						)
						VALUES
						(
						@rWfTypeMasterId,
						@rWfLevel,
						@rOrgGroupId,
						@rWfFunctionalityId
						)
						SET @rId = CAST(SCOPE_IDENTITY() AS SMALLINT)

						INSERT INTO sWf.tWfApprovingAuthority
						(
						AuthoritySourceTypeId,
						AuthoritySourceId,
						OrgId,
						WfFunctionalityId
						)
						SELECT 
						AuthoritySourceTypeId,
						AuthoritySourceId,
						OrgId,
						WfFunctionalityId
						FROM @rAuthorityList

						SELECT @rId
					END
				END
			END
			ELSE
			BEGIN
				IF NOT EXISTS(SELECT AA.Id FROM [sWf].[tWfSetup] WS
							INNER JOIN [sWf].[tWfApprovalAction] AA ON WS.WfFunctionalityId = AA.WfFunctionalityId
							WHERE WS.WfFunctionalityId= @rWfFunctionalityId AND WS.WfTypeMasterId <> @rWfTypeMasterId AND AA.ActionStatusId NOT IN (3,4))
				BEGIN
					UPDATE [sWf].[tWfSetup]
					SET 
						WfTypeMasterId = @rWfTypeMasterId,
						WfLevel = @rWfLevel,
						OrgGroupId = @rOrgGroupId,
						WfFunctionalityId = @rWfFunctionalityId
					WHERE AutoId =@rId

					DELETE FROM sWf.tWfApprovingAuthority
					WHERE WfFunctionalityId = @rWfFunctionalityId

					INSERT INTO sWf.tWfApprovingAuthority
					(
					AuthoritySourceTypeId,
					AuthoritySourceId,
					OrgId,
					WfFunctionalityId
					)
					SELECT 
					AuthoritySourceTypeId,
					AuthoritySourceId,
					OrgId,
					WfFunctionalityId
					FROM @rAuthorityList

					SELECT @rId
				END
				ELSE
				BEGIN
					SELECT -101;
				END
			END
		END
	COMMIT TRANSACTION
	END TRY	
	BEGIN CATCH
		ROLLBACK TRANSACTION
		SELECT -1 AS RESULT
	END CATCH
END
GO
PRINT N'Creating Procedure [sActivity].[pEventAttendanceViewGet]...';


GO

CREATE PROCEDURE [sEMeeting].[pEventTemplateGetForAttendance]
		@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 = 161
		END TRY
		BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH
	END
GO
PRINT N'Creating Procedure [sEMeeting].[pOnlineMeetingAbsentStudentListGet]...';


GO
	

CREATE PROCEDURE [sEMeeting].[pOnlineMeetingAbsentStudentListGet]
	@rOnlineMeetingId bigint,
	@rTemplate nvarchar(max)

	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
		 SELECT 
			A.AcademicId,
			A.Code,
			A.Name,
			A.ParentContactNo AS MobileNo,	
			A.ParentEmail AS EmailId,
			replace (
			replace (
			replace (
			replace (
			replace (
			replace (
			replace (
			replace(@rTemplate,'[MeetingType]',OMT.Title),
			'[Name]',A.Name),
			'[StartDate]',CONVERT(varchar(11),ISNULL(OM.StartDate,'') ,103)),
			'[EndDate]',CONVERT(varchar(11),ISNULL(OM.EndDate,'') ,103)),
			'[Teacher]',EE.EmployeeName),
			'[Title]',OM.Title),
			'[StartTime]',CONVERT(varchar(11),ISNULL(OM.StartTime,'') ,8)),
			'[EndTime]',CONVERT(varchar(11),ISNULL(OM.EndTime,'') ,8))
			AS MsgText,
			'' AS Subject,
			 2003 AS ReceiverSourceTypeId,
			 A.OrgId AS OrgId,
			 (SELECT OrgGroupId FROM sSetup.tOrganizationMaster where ID=A.OrgId) AS OrgGroupId,
			 A.AcademicId AS ReceiverSourceId,
			 A.AcademicId AS SourceId,
			 2003 AS SourceTypeId,
			 OMT.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,
			 CONVERT(varchar(11),ISNULL(OM.StartTime,'') ,8) AS StartTime,
			 CONVERT(varchar(11),ISNULL(OM.EndTime,'') ,8) AS EndTime,
			 A.WhatsAppContactNo
	FROM 
		sEMeeting.tOnlineMeeting OM
		INNER JOIN sEMeeting.tMeetingTypeMaster OMT ON OMT.AutoId = OM.MeetingTypeId
		INNER JOIN sHrm.vExtEmployee EE ON EE.EmployeeId = OM.HostEmployeeId
		INNER JOIN (
			SELECT 
				OM.Id as OnlineMeetingId,
				SD.AcademicId,
				SD.Name,
				SD.Code,
				SD.ParentContactNo,	
				SD.ParentEmail,
				SD.OrgId,
				ISNULL(SC.WhatsAppContactNo,'') AS WhatsAppContactNo
			FROM 
			    sEMeeting.tOnlineMeetingScope OMS 
				INNER JOIN sEMeeting.tOnlineMeeting OM ON OMS.OnlineMeetingId = OM.Id 
				INNER JOIN sStudent.vStudentAllDetail SD ON SD.AcademicId = OMS.ScopeSourceId
				LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId = SD.StudentId
			WHERE 
			    OMS.OnlineMeetingId = @rOnlineMeetingId AND SD.StatusId = 1 AND OMS.ScopeSourceTypeId = 2003

			UNION ALL	
																			 			  
			SELECT 
				OM.Id as OnlineMeetingId,
				SD.AcademicId,
				SD.Name,
				SD.Code,
				SD.ParentContactNo,	
				SD.ParentEmail,
				SD.OrgId,
				ISNULL(SC.WhatsAppContactNo,'') AS WhatsAppContactNo
			FROM 
				sEMeeting.tOnlineMeetingScope OMS 
				INNER JOIN sEMeeting.tOnlineMeeting OM ON OMS.OnlineMeetingId = OM.Id 
				INNER JOIN sStudent.vStudentAllDetail SD ON SD.DepartmentId = OMS.ScopeSourceId
				LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId = SD.StudentId
				 
			WHERE 
				OMS.OnlineMeetingId = @rOnlineMeetingId AND SD.StatusId = 1 AND  OMS.ScopeSourceTypeId = 2017

			UNION ALL		
															 			 				  
			SELECT 
				OM.Id as OnlineMeetingId,
				SD.AcademicId,
				SD.Name,
				SD.Code,
				SD.ParentContactNo,	
				SD.ParentEmail,
				SD.OrgId,
				ISNULL(SC.WhatsAppContactNo,'') AS WhatsAppContactNo
			FROM 
				sEMeeting.tOnlineMeetingScope OMS 
				INNER JOIN sEMeeting.tOnlineMeeting OM ON OMS.OnlineMeetingId = OM.Id 
				INNER JOIN sStudent.vStudentAllDetail SD ON SD.ClassId = OMS.ScopeSourceId  
				LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId = SD.StudentId
			WHERE 
				OMS.OnlineMeetingId = @rOnlineMeetingId AND SD.StatusId = 1 AND OMS.ScopeSourceTypeId = 2016

			UNION ALL	
																 			 				  
			SELECT 
				OM.Id as OnlineMeetingId,
				SD.AcademicId,
				SD.Name,
				SD.Code,
				SD.ParentContactNo,	
				SD.ParentEmail,
				SD.OrgId,
				ISNULL(SC.WhatsAppContactNo,'') AS WhatsAppContactNo
			FROM 
				sEMeeting.tOnlineMeetingScope OMS 
				INNER JOIN sEMeeting.tOnlineMeeting OM ON OMS.OnlineMeetingId = OM.Id 
				INNER JOIN sStudent.vStudentAllDetail SD ON SD.DivisionId = OMS.ScopeSourceId
				LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId = SD.StudentId
			WHERE 
				OMS.OnlineMeetingId = @rOnlineMeetingId AND SD.StatusId = 1 AND OMS.ScopeSourceTypeId = 2005

			UNION ALL		
															 			 				  
			SELECT 
				OM.Id as OnlineMeetingId,
				SD.AcademicId,
				SD.Name,
				SD.Code,
				SD.ParentContactNo,	
				SD.ParentEmail,
				SD.OrgId,
				ISNULL(SC.WhatsAppContactNo,'') AS WhatsAppContactNo
			FROM 
				sEMeeting.tOnlineMeetingScope OMS 
				INNER JOIN sEMeeting.tOnlineMeeting OM ON OMS.OnlineMeetingId = OM.Id 
				INNER JOIN sStudent.vStudentAllDetail SD ON SD.OrgId = OMS.ScopeSourceId
				LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId = SD.StudentId 
			WHERE 
				OMS.OnlineMeetingId = @rOnlineMeetingId AND SD.StatusId = 1 AND OMS.ScopeSourceTypeId = 2021
			
		) as A ON A.OnlineMeetingId = OM.Id 
		LEFT JOIN sEMeeting.tOnlineMeetingAttendance OMA ON OMA.OnlineMeetingId = OM.Id AND OMA.ParticipantSourceId = A.AcademicId
	WHERE
		OM.Id = @rOnlineMeetingId AND ISNULL(OMA.IsPresent,0) <> 1
END
GO
PRINT N'Creating Procedure [sEMeeting].[pOnlineMeetingScopeListGet]...';


GO

	

CREATE PROCEDURE [sEMeeting].[pOnlineMeetingScopeListGet]
	
		 @rOnlineMeetingId bigint,
	 	 @rTemplate nvarchar(max)
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	
	SELECT 
			A.AcademicId,
			A.Code,
			A.Name,
			A.ParentContactNo AS MobileNo,	
			A.ParentEmail AS EmailId,
			replace (
			replace (
			replace (
			replace (
			replace (
			replace(@rTemplate,'[MeetingType]',OMT.Title),
			'[StartDate]',CONVERT(varchar(11),ISNULL(OM.StartDate,'') ,103)),
			'[EndDate]',CONVERT(varchar(11),ISNULL(OM.EndDate,'') ,103)),
			'[Title]',OM.Title),
			'[StartTime]',CONVERT(varchar(11),ISNULL(OM.StartTime,'') ,8)),
			'[EndTime]',CONVERT(varchar(11),ISNULL(OM.EndTime,'') ,8))
			AS MsgText,
			'' AS Subject,
			 A.SourceTypeId AS ReceiverSourceTypeId,
			 A.OrgId AS OrgId,
			 (SELECT OrgGroupId FROM sSetup.tOrganizationMaster where ID=A.OrgId) AS OrgGroupId,
			 A.AcademicId AS ReceiverSourceId,
			 A.AcademicId AS SourceId,
			 A.SourceTypeId AS SourceTypeId,
			 OMT.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 
		sEMeeting.tOnlineMeeting OM
		INNER JOIN sEMeeting.tMeetingTypeMaster OMT ON OMT.AutoId = OM.MeetingTypeId
		INNER JOIN sHrm.vExtEmployee EE ON EE.EmployeeId = OM.HostEmployeeId
		INNER JOIN (
			SELECT 
				OM.Id as OnlineMeetingId,
				SD.AcademicId,
				SD.Name,
				SD.Code,
				SD.ParentContactNo,	
				SD.ParentEmail,
				SD.OrgId,
				2003 As SourceTypeId,
				ISNULL(SC.WhatsAppContactNo,'') AS WhatsAppContactNo
			FROM 
			    sEMeeting.tOnlineMeetingScope OMS 
				INNER JOIN sEMeeting.tOnlineMeeting OM ON OMS.OnlineMeetingId = OM.Id 
				INNER JOIN sStudent.vStudentAllDetail SD ON SD.AcademicId = OMS.ScopeSourceId
				LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId = SD.StudentId
			WHERE 
			    OMS.OnlineMeetingId = @rOnlineMeetingId AND SD.StatusId = 1 AND OMS.ScopeSourceTypeId = 2003

			UNION ALL	
																			 			  
			SELECT 
				OM.Id as OnlineMeetingId,
				SD.AcademicId,
				SD.Name,
				SD.Code,
				SD.ParentContactNo,	
				SD.ParentEmail,
				SD.OrgId,
				2003 As SourceTypeId,
				ISNULL(SC.WhatsAppContactNo,'') AS WhatsAppContactNo
			FROM 
				sEMeeting.tOnlineMeetingScope OMS 
				INNER JOIN sEMeeting.tOnlineMeeting OM ON OMS.OnlineMeetingId = OM.Id 
				INNER JOIN sStudent.vStudentAllDetail SD ON SD.DepartmentId = OMS.ScopeSourceId
				 LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId = SD.StudentId
			WHERE 
				OMS.OnlineMeetingId = @rOnlineMeetingId AND SD.StatusId = 1 AND  OMS.ScopeSourceTypeId = 2017 AND OMS.AssigneeId = 2

				UNION ALL	
																			 			  
			SELECT 
				OM.Id as OnlineMeetingId,
				vEC.EmployeeId as AcademicId,
				vEC.EmployeeName as Name,
				vEC.Code,
				vEC.MobileNumber as ParentContactNo,
				vEC.CompanyEmail as ParentEmail,
				vEC.OrgId,
				95 As SourceTypeId,
				ISNULL(vEC.WhatsAppContactNo,'') AS WhatsAppContactNo
			FROM 
				sEMeeting.tOnlineMeetingScope OMS 
				INNER JOIN sEMeeting.tOnlineMeeting OM ON OMS.OnlineMeetingId = OM.Id 
				INNER JOIN sHrm.vEmployeeCommunication vEC ON vEC.DepartmentId = OMS.ScopeSourceId 
			WHERE 
				OMS.OnlineMeetingId = @rOnlineMeetingId AND vEC.StatusId = 7 AND  OMS.ScopeSourceTypeId = 2017 AND OMS.AssigneeId = 3

			UNION ALL		
															 			 				  
			SELECT 
				OM.Id as OnlineMeetingId,
				SD.AcademicId,
				SD.Name,
				SD.Code,
				SD.ParentContactNo,	
				SD.ParentEmail,
				SD.OrgId,
				2003 As SourceTypeId,
				ISNULL(SC.WhatsAppContactNo,'') AS WhatsAppContactNo
			FROM 
				sEMeeting.tOnlineMeetingScope OMS 
				INNER JOIN sEMeeting.tOnlineMeeting OM ON OMS.OnlineMeetingId = OM.Id 
				INNER JOIN sStudent.vStudentAllDetail SD ON SD.ClassId = OMS.ScopeSourceId
				LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId = SD.StudentId
			WHERE 
				OMS.OnlineMeetingId = @rOnlineMeetingId AND SD.StatusId = 1 AND OMS.ScopeSourceTypeId = 2016

			UNION ALL	
																 			 				  
			SELECT 
				OM.Id as OnlineMeetingId,
				SD.AcademicId,
				SD.Name,
				SD.Code,
				SD.ParentContactNo,	
				SD.ParentEmail,
				SD.OrgId,
				2003 As SourceTypeId,
				ISNULL(SC.WhatsAppContactNo,'') AS WhatsAppContactNo
			FROM 
				sEMeeting.tOnlineMeetingScope OMS 
				INNER JOIN sEMeeting.tOnlineMeeting OM ON OMS.OnlineMeetingId = OM.Id 
				INNER JOIN sStudent.vStudentAllDetail SD ON SD.DivisionId = OMS.ScopeSourceId
				LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId = SD.StudentId
			WHERE 
				OMS.OnlineMeetingId = @rOnlineMeetingId AND SD.StatusId = 1 AND OMS.ScopeSourceTypeId = 2005

			UNION ALL		
															 			 				  
			SELECT 
				OM.Id as OnlineMeetingId,
				SD.AcademicId,
				SD.Name,
				SD.Code,
				SD.ParentContactNo,	
				SD.ParentEmail,
				SD.OrgId,
				2003 As SourceTypeId,
				ISNULL(SC.WhatsAppContactNo,'') AS WhatsAppContactNo
			FROM 
				sEMeeting.tOnlineMeetingScope OMS 
				INNER JOIN sEMeeting.tOnlineMeeting OM ON OMS.OnlineMeetingId = OM.Id 
				INNER JOIN sStudent.vStudentAllDetail SD ON SD.OrgId = OMS.ScopeSourceId
				LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId = SD.StudentId
			WHERE 
				OMS.OnlineMeetingId = @rOnlineMeetingId AND SD.StatusId = 1 AND OMS.ScopeSourceTypeId = 2021 AND OMS.AssigneeId = 2

				UNION ALL		
															 			 				  
			SELECT 
				OM.Id as OnlineMeetingId,
				vEC.EmployeeId as AcademicId,
				vEC.EmployeeName as Name,
				vEC.Code,
				vEC.MobileNumber as ParentContactNo,
				vEC.CompanyEmail as ParentEmail,
				vEC.OrgId,
				95 As SourceTypeId,
				ISNULL(vEC.WhatsAppContactNo,'') AS WhatsAppContactNo
			FROM 
				sEMeeting.tOnlineMeetingScope OMS 
				INNER JOIN sEMeeting.tOnlineMeeting OM ON OMS.OnlineMeetingId = OM.Id 
				INNER JOIN sHrm.vEmployeeCommunication vEC ON vEC.OrgID = OMS.ScopeSourceId 
			WHERE 
				OMS.OnlineMeetingId = @rOnlineMeetingId AND vEC.StatusId = 7 AND OMS.ScopeSourceTypeId = 2021 AND OMS.AssigneeId = 3

			UNION ALL

				SELECT Distinct
				OM.Id as OnlineMeetingId,
				vEC.EmployeeId as AcademicId,
				vEC.EmployeeName as Name,
				vEC.Code,
				vEC.MobileNumber as ParentContactNo,
				vEC.CompanyEmail as ParentEmail,
				vEC.OrgId,
				95 As SourceTypeId,
				ISNULL(vEC.WhatsAppContactNo,'') AS WhatsAppContactNo
			FROM 
				sEMeeting.tOnlineMeetingScope OMS 
				INNER JOIN sEMeeting.tOnlineMeeting OM ON OMS.OnlineMeetingId = OM.Id 
				INNER JOIN sHrm.vEmployeeCommunication vEC ON (vEC.EmployeeId = OMS.ScopeSourceId) 
				OR (vEC.EmployeeId = OM.HostEmployeeId)
			WHERE 
				OMS.OnlineMeetingId = @rOnlineMeetingId AND vEC.StatusId = 7 AND OMS.ScopeSourceTypeId = 95
			
		) as A ON A.OnlineMeetingId = OM.Id
	WHERE
		OM.Id = @rOnlineMeetingId
END
GO
PRINT N'Creating Procedure [sFee].[pRptFeeSummaryPaytypewiseReportGet]...';


GO

CREATE PROCEDURE [sPurchase].[pPurchaseStoreLocationMasterGet]
	@rId [int] = 0,
	@rTitle [nvarchar](20) = '',
	@rCode [nvarchar](100) = '',
	@rOrgGroupId int
	--,
	--@rIsWildCardSearch [bit] = 1

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN

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


	 SELECT SLM.Id,
			SLM.Title,
			SLM.CreatedUserId,
			SLM.CreatedDateTime,
			SLM.IsObsolete,
			SLM.UpdatedUserId,
			SLM.UpdatedDateTime,
			SLM.Code,		
			SLM.OrgGroupId,
			OM.Title AS OrgGroupName,
			SLM.Title AS StoreLocationName,
			ISNULL(SLM.IsBatchwiseTracking,0) AS IsBatchwiseTracking,
			Isnull(SLM.DepositHeadId,0) AS DepositHeadId,
			Isnull(SLM.DepositExpenseTypeId,0) AS DepositExpenseTypeId,
			Isnull(SLM.ReportId,0) AS ReportId

	   FROM sIp.tStoreLocationMaster SLM 	   
	   INNER JOIN sSetup.tOrgGroupMaster OM ON OM.Id=SLM.OrgGroupId
	  WHERE ((SLM.Id = @rId) OR (@rId = 0))
	   AND ((SLM.Title LIKE @rTitle) OR (ISNULL(@rTitle, '') = ''))
	   AND ((SLM.Code LIKE @rCode) OR (ISNULL(@rCode, '') = ''))	  
	   AND  (SLM.OrgGroupId = @rOrgGroupId)  
	   AND SLM.IsObsolete = 0
END

SET ANSI_NULLS ON
GO
PRINT N'Creating Procedure [sPurchase].[pStoreLocationGet]...';


GO
CREATE PROCEDURE [sPurchase].[pStoreLocationGet]
	@rId INT = 0,
	@rTitle NVARCHAR(20) = '',
	@rCode NVARCHAR(100) = '',
	@rLocationId INT = 0,
	@rOrgGroupId INT

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN

	--IF @rIsWildCardSearch = 1
	--	BEGIN
			SET @rCode = sCommon.fSearchStringGet(@rCode)
			SET @rTitle = sCommon.fSearchStringGet(@rTitle)
		--END
		
	 SELECT SLM.Id,
			SLM.Title,
			SLM.CreatedUserId,
			SLM.CreatedDateTime,
			SLM.IsObsolete,
			SLM.UpdatedUserId,
			SLM.UpdatedDateTime,
			SLM.Code,		
			SLM.OrgGroupId,
			OM.Title AS OrgGroupName,
			SLM.Title AS StoreLocationName,
			ISNULL(SLM.IsBatchwiseTracking,0) AS IsBatchwiseTracking,
			Isnull(SLM.DepositHeadId,0) AS DepositHeadId,
			Isnull(SLM.DepositExpenseTypeId,0) AS DepositExpenseTypeId,
			Isnull(SLM.ReportId,0) AS ReportId

	   FROM sIp.tStoreLocationMaster SLM 	   
	   INNER JOIN sSetup.tOrgGroupMaster OM ON OM.Id=SLM.OrgGroupId
	   WHERE ((SLM.Id = @rId) OR (@rId = 0))
	   AND ((SLM.Title LIKE @rTitle) OR (ISNULL(@rTitle, '') = ''))
	   AND ((SLM.Code LIKE @rCode) OR (ISNULL(@rCode, '') = ''))	  
	   AND  (SLM.OrgGroupId = @rOrgGroupId)  
	   --AND SLM.IsObsolete = 0
END
GO
PRINT N'Creating Procedure [sPurchase].[pStoreLocationMasterGet]...';


GO
Create PROCEDURE [sPurchase].[pStoreLocationMasterGet]
	@rId [int] = 0,
	@rTitle [nvarchar](20) = '',
	@rCode [nvarchar](100) = '',
	@rLocationId [int] = 0,
	@rOrgGroupId int,
	@rIsWildCardSearch [bit] = 1

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN

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


	 SELECT SLM.Id,
			SLM.Title,
			SLM.CreatedUserId,
			SLM.CreatedDateTime,
			SLM.IsObsolete,
			SLM.UpdatedUserId,
			SLM.UpdatedDateTime,
			SLM.Code,		
			SLM.OrgGroupId,
			OM.Title AS OrgGroupName,
			SLM.Title AS StoreLocationName,
			ISNULL(SLM.IsBatchwiseTracking,0) AS IsBatchwiseTracking,
			Isnull(SLM.DepositHeadId,0) as DepositHeadId,
			Isnull(SLM.DepositExpenseTypeId,0) as DepositExpenseTypeId,
			Isnull(SLM.ReportId,0) as ReportId

	   FROM sIp.tStoreLocationMaster SLM 	   
	   INNER JOIN sSetup.tOrgGroupMaster OM ON OM.Id=SLM.OrgGroupId
	  WHERE ((SLM.Id = @rId) OR (@rId = 0))
	   AND ((SLM.Title LIKE @rTitle) OR (ISNULL(@rTitle, '') = ''))
	   AND ((SLM.Code LIKE @rCode) OR (ISNULL(@rCode, '') = ''))	  
	   AND  (SLM.OrgGroupId = @rOrgGroupId)  
	   --AND SLM.IsObsolete = 0
END
GO
PRINT N'Creating Procedure [sStudent].[pRptClassDivisionCapacityGet]...';


GO


ALTER PROCEDURE [sPurchase].[pGoodsReceivedNoteAdd]
		@rId BIGINT,
		@rPurchaseRequestId BIGINT,
		@rPurchaseOrderId BIGINT,
		@rVendorId INT,
		@rPODueDate DATETIME,	
		@rRequestedBy NVARCHAR(100),
		@rOrgGroupId SMALLINT,
		@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
		    IF NOT EXISTS(SELECT Id FROM sPurchase.tGoodsReceivedNote WHERE Id = @rId AND CreatedUserId = @rUserId)
            BEGIN
            SELECT -103
            END
			ELSE
			BEGIN
			   IF NOT EXISTS(SELECT Id FROM @rDetailList WHERE PreviousGRNQty+ReceivedQty > POQty)
			   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
			SELECT -101
		    END
			END
		ELSE
		BEGIN
		    IF NOT EXISTS(
                SELECT WFS.AutoId FROM [sWf].[tWfSetup] WFS
				WHERE WFS.[WfFunctionalityId] = 4 AND @rOrgGroupId = WFS.[OrgGroupId])
				BEGIN
					SELECT -102
				END
			ELSE
			BEGIN
				IF NOT EXISTS(SELECT Id FROM @rDetailList WHERE PreviousGRNQty+ReceivedQty > POQty)
				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,
						0, 		 
						@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,1,'',1,@Level,4,@rOrgGroupId
					END
					ELSE IF(@typeId = 3)
					BEGIN
						EXEC [sWf].[pWfApprovalAdd] 0,@rId,2043,@rUserId,3,'',0,0,4,@rOrgGroupId
					END
				END
				SELECT -101;
			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].[pPurchaseOrderAdd]...';


GO

ALTER PROCEDURE [sPurchase].[pPurchaseOrderAdd]
		@rId BIGINT,
		@rPurchaseRequestId BIGINT,
		@rPODate DATETIME,	
		@rRequestedBy NVARCHAR(100),
		@rOrgGroupId SMALLINT,
		@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
		    IF NOT EXISTS(SELECT Id FROM sPurchase.tPurchaseOrder WHERE Id = @rId AND CreatedUserId = @rUserId)
			BEGIN
			SELECT -103
			END
			ELSE
			    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
		END
		ELSE
		BEGIN
		    IF NOT EXISTS(
                SELECT WFS.AutoId FROM [sWf].[tWfSetup] WFS
				WHERE WFS.[WfFunctionalityId] = 3 AND @rOrgGroupId = WFS.[OrgGroupId])
				BEGIN
					SELECT -102
				END
			ELSE
			    IF EXISTS(SELECT PO.Id FROM sPurchase.tPurchaseOrder PO WHERE PO.StatusId <> 4 AND PO.PurchaseRequestId = @rPurchaseRequestId) 
                BEGIN
	               SELECT -101
                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,
						0, 		 
						@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,1,'',1,@Level,3,@rOrgGroupId
					END
					ELSE IF(@typeId = 3)--auto approved
					BEGIN
						EXEC [sWf].[pWfApprovalAdd] 0,@rId,2042,@rUserId,3,'',0,0,3,@rOrgGroupId
					END
					--select 1;
				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].[pPurchaseRequestAdd]...';


GO


ALTER PROCEDURE [sPurchase].[pPurchaseRequestAdd]
		@rId BIGINT,
		@rRequestDate DATETIME,
		@rResourceId BIGINT,
		@rRequestedBy NVARCHAR(100),
		@rOrgGroupId SMALLINT,
		@rBranchId 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
		    IF NOT EXISTS(SELECT Id FROM sPurchase.tPurchaseRequest WHERE Id = @rId AND CreatedUserId = @rUserId)
			BEGIN
				SELECT -101
			END
			ELSE
			  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
		END
		ELSE
		BEGIN
			IF NOT EXISTS(
                SELECT WFS.AutoId FROM [sWf].[tWfSetup] WFS
				WHERE WFS.[WfFunctionalityId] = 1 AND @rOrgGroupId = WFS.[OrgGroupId])
				BEGIN
					SELECT -102
				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,
						0, 		 
						@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,1,'',1,@Level,1,@rOrgGroupId
					END
					ELSE IF(@typeId = 3)--auto approved
					BEGIN
						EXEC [sWf].[pWfApprovalAdd] 0,@rId,2040,@rUserId,3,'',0,0,1,@rOrgGroupId
					END
			
				END
		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].[pQuotationRequestAdd]...';


GO




ALTER PROCEDURE [sPurchase].[pQuotationRequestAdd]
		@rId BIGINT,
		@rOrgGroupId SMALLINT,
		@rBranchId 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
		  IF NOT EXISTS(SELECT Id FROM sPurchase.tQuotationRequest WHERE Id = @rId AND CreatedUserId = @rUserId)
		    BEGIN
		    SELECT -103
		    END
		  ELSE
		    BEGIN
			UPDATE sPurchase.tQuotationRequest
			SET
				OrgGroupId =@rOrgGroupId,
				BranchId =@rBranchId,
				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
		END
		ELSE
		BEGIN
			IF NOT EXISTS(
                SELECT WFS.AutoId FROM [sWf].[tWfSetup] WFS
				WHERE WFS.[WfFunctionalityId] = 2 AND @rOrgGroupId = WFS.[OrgGroupId])
				BEGIN
					SELECT -102
				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 ,
								0,
								@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,1,'',1,@Level,2,@rOrgGroupId
							END
							ELSE IF(@typeId = 3)--auto approved
							BEGIN
								EXEC [sWf].[pWfApprovalAdd] 0,@rId,2041,@rUserId,3,'',0,0,2,@rOrgGroupId
							END
						END
						SELECT -101;

				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,
		@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
		  IF NOT EXISTS(SELECT Id FROM sPurchase.tQuotationRequest WHERE Id = @rId AND CreatedUserId = @rUserId)
		    BEGIN
		    SELECT -101
		    END
		  ELSE
		    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
		END
		ELSE
		BEGIN
		    IF NOT EXISTS(
                SELECT WFS.AutoId FROM [sWf].[tWfSetup] WFS
				WHERE WFS.[WfFunctionalityId] = 5 AND @rOrgGroupId = WFS.[OrgGroupId])
				BEGIN
					SELECT -102
				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,
						0, 		 
						@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,1,'',1,@Level,5,@rOrgGroupId
					END
					ELSE IF(@typeId = 3)--auto approved
					BEGIN
						EXEC [sWf].[pWfApprovalAdd] 0,@rId,2044,@rUserId,3,'',0,0,5,@rOrgGroupId
					END
					--select 1;
				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


/****** Object:  StoredProcedure [sEMeeting].[pWhatsAppTemplateGet]    Script Date: 10-01-2024 15:45:04 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[sEMeeting].[pWhatsAppTemplateGet]') AND type in (N'P', N'PC'))
DROP PROCEDURE [sEMeeting].[pWhatsAppTemplateGet]
GO
/****** Object:  StoredProcedure [sEMeeting].[pValidateOnlineMeetingTeacher]    Script Date: 10-01-2024 15:45:04 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[sEMeeting].[pValidateOnlineMeetingTeacher]') AND type in (N'P', N'PC'))
DROP PROCEDURE [sEMeeting].[pValidateOnlineMeetingTeacher]
GO
/****** Object:  StoredProcedure [sEMeeting].[pValidateOnlineMeetingAccount]    Script Date: 10-01-2024 15:45:04 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[sEMeeting].[pValidateOnlineMeetingAccount]') AND type in (N'P', N'PC'))
DROP PROCEDURE [sEMeeting].[pValidateOnlineMeetingAccount]
GO
/****** Object:  StoredProcedure [sEMeeting].[pUpdateOnlineMeetingSettingsToken]    Script Date: 10-01-2024 15:45:04 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[sEMeeting].[pUpdateOnlineMeetingSettingsToken]') AND type in (N'P', N'PC'))
DROP PROCEDURE [sEMeeting].[pUpdateOnlineMeetingSettingsToken]
GO
/****** Object:  StoredProcedure [sEMeeting].[pUpdateOnlineMeetingAccountToken]    Script Date: 10-01-2024 15:45:04 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[sEMeeting].[pUpdateOnlineMeetingAccountToken]') AND type in (N'P', N'PC'))
DROP PROCEDURE [sEMeeting].[pUpdateOnlineMeetingAccountToken]
GO
/****** Object:  StoredProcedure [sEMeeting].[pUpdateMeetingDetails]    Script Date: 10-01-2024 15:45:04 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[sEMeeting].[pUpdateMeetingDetails]') AND type in (N'P', N'PC'))
DROP PROCEDURE [sEMeeting].[pUpdateMeetingDetails]
GO
/****** Object:  StoredProcedure [sEMeeting].[pStudentProfileGet]    Script Date: 10-01-2024 15:45:04 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[sEMeeting].[pStudentProfileGet]') AND type in (N'P', N'PC'))
DROP PROCEDURE [sEMeeting].[pStudentProfileGet]
GO
/****** Object:  StoredProcedure [sEMeeting].[pSMSTemplateIdGet]    Script Date: 10-01-2024 15:45:04 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[sEMeeting].[pSMSTemplateIdGet]') AND type in (N'P', N'PC'))
DROP PROCEDURE [sEMeeting].[pSMSTemplateIdGet]
GO
/****** Object:  StoredProcedure [sEMeeting].[pScreenGet]    Script Date: 10-01-2024 15:45:04 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[sEMeeting].[pScreenGet]') AND type in (N'P', N'PC'))
DROP PROCEDURE [sEMeeting].[pScreenGet]
GO
/****** Object:  StoredProcedure [sEMeeting].[pPermissionGet]    Script Date: 10-01-2024 15:45:04 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[sEMeeting].[pPermissionGet]') AND type in (N'P', N'PC'))
DROP PROCEDURE [sEMeeting].[pPermissionGet]
GO
/****** Object:  StoredProcedure [sEMeeting].[pOrgGroupIdGet]    Script Date: 10-01-2024 15:45:04 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[sEMeeting].[pOrgGroupIdGet]') AND type in (N'P', N'PC'))
DROP PROCEDURE [sEMeeting].[pOrgGroupIdGet]
GO
/****** Object:  StoredProcedure [sEMeeting].[pOrderIndexMeetingTypeMasterGet]    Script Date: 10-01-2024 15:45:04 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[sEMeeting].[pOrderIndexMeetingTypeMasterGet]') AND type in (N'P', N'PC'))
DROP PROCEDURE [sEMeeting].[pOrderIndexMeetingTypeMasterGet]
GO
/****** Object:  StoredProcedure [sEMeeting].[pOnlineMeetingTeacherStudentListGet]    Script Date: 10-01-2024 15:45:04 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[sEMeeting].[pOnlineMeetingTeacherStudentListGet]') AND type in (N'P', N'PC'))
DROP PROCEDURE [sEMeeting].[pOnlineMeetingTeacherStudentListGet]
GO
/****** Object:  StoredProcedure [sEMeeting].[pOnlineMeetingTeacherGet]    Script Date: 10-01-2024 15:45:04 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[sEMeeting].[pOnlineMeetingTeacherGet]') AND type in (N'P', N'PC'))
DROP PROCEDURE [sEMeeting].[pOnlineMeetingTeacherGet]
GO
/****** Object:  StoredProcedure [sEMeeting].[pOnlineMeetingStudentGet]    Script Date: 10-01-2024 15:45:04 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[sEMeeting].[pOnlineMeetingStudentGet]') AND type in (N'P', N'PC'))
DROP PROCEDURE [sEMeeting].[pOnlineMeetingStudentGet]
GO
/****** Object:  StoredProcedure [sEMeeting].[pOnlineMeetingStatusTypeGet]    Script Date: 10-01-2024 15:45:04 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[sEMeeting].[pOnlineMeetingStatusTypeGet]') AND type in (N'P', N'PC'))
DROP PROCEDURE [sEMeeting].[pOnlineMeetingStatusTypeGet]
GO
/****** Object:  StoredProcedure [sEMeeting].[pOnlineMeetingSettingsGet]    Script Date: 10-01-2024 15:45:04 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[sEMeeting].[pOnlineMeetingSettingsGet]') AND type in (N'P', N'PC'))
DROP PROCEDURE [sEMeeting].[pOnlineMeetingSettingsGet]
GO
/****** Object:  StoredProcedure [sEMeeting].[pOnlineMeetingScopeListGet]    Script Date: 10-01-2024 15:45:04 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[sEMeeting].[pOnlineMeetingScopeListGet]') AND type in (N'P', N'PC'))
DROP PROCEDURE [sEMeeting].[pOnlineMeetingScopeListGet]
GO
/****** Object:  StoredProcedure [sEMeeting].[pOnlineMeetingResourceAdd]    Script Date: 10-01-2024 15:45:04 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[sEMeeting].[pOnlineMeetingResourceAdd]') AND type in (N'P', N'PC'))
DROP PROCEDURE [sEMeeting].[pOnlineMeetingResourceAdd]
GO
/****** Object:  StoredProcedure [sEMeeting].[pOnlineMeetingReferenceDelete]    Script Date: 10-01-2024 15:45:04 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[sEMeeting].[pOnlineMeetingReferenceDelete]') AND type in (N'P', N'PC'))
DROP PROCEDURE [sEMeeting].[pOnlineMeetingReferenceDelete]
GO
/****** Object:  StoredProcedure [sEMeeting].[pOnlineMeetingProviderGet]    Script Date: 10-01-2024 15:45:04 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[sEMeeting].[pOnlineMeetingProviderGet]') AND type in (N'P', N'PC'))
DROP PROCEDURE [sEMeeting].[pOnlineMeetingProviderGet]
GO
/****** Object:  StoredProcedure [sEMeeting].[pOnlineMeetingOrganizationGet]    Script Date: 10-01-2024 15:45:04 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[sEMeeting].[pOnlineMeetingOrganizationGet]') AND type in (N'P', N'PC'))
DROP PROCEDURE [sEMeeting].[pOnlineMeetingOrganizationGet]
GO
/****** Object:  StoredProcedure [sEMeeting].[pOnlineMeetingGet]    Script Date: 10-01-2024 15:45:04 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[sEMeeting].[pOnlineMeetingGet]') AND type in (N'P', N'PC'))
DROP PROCEDURE [sEMeeting].[pOnlineMeetingGet]
GO
/****** Object:  StoredProcedure [sEMeeting].[pOnlineMeetingEmployeeGet]    Script Date: 10-01-2024 15:45:04 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[sEMeeting].[pOnlineMeetingEmployeeGet]') AND type in (N'P', N'PC'))
DROP PROCEDURE [sEMeeting].[pOnlineMeetingEmployeeGet]
GO
/****** Object:  StoredProcedure [sEMeeting].[pOnlineMeetingDivisionGet]    Script Date: 10-01-2024 15:45:04 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[sEMeeting].[pOnlineMeetingDivisionGet]') AND type in (N'P', N'PC'))
DROP PROCEDURE [sEMeeting].[pOnlineMeetingDivisionGet]
GO
/****** Object:  StoredProcedure [sEMeeting].[pOnlineMeetingDepartmentGet]    Script Date: 10-01-2024 15:45:04 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[sEMeeting].[pOnlineMeetingDepartmentGet]') AND type in (N'P', N'PC'))
DROP PROCEDURE [sEMeeting].[pOnlineMeetingDepartmentGet]
GO
/****** Object:  StoredProcedure [sEMeeting].[pOnlineMeetingDelete]    Script Date: 10-01-2024 15:45:04 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[sEMeeting].[pOnlineMeetingDelete]') AND type in (N'P', N'PC'))
DROP PROCEDURE [sEMeeting].[pOnlineMeetingDelete]
GO
/****** Object:  StoredProcedure [sEMeeting].[pOnlineMeetingClassGet]    Script Date: 10-01-2024 15:45:04 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[sEMeeting].[pOnlineMeetingClassGet]') AND type in (N'P', N'PC'))
DROP PROCEDURE [sEMeeting].[pOnlineMeetingClassGet]
GO
/****** Object:  StoredProcedure [sEMeeting].[pOnlineMeetingBatchGet]    Script Date: 10-01-2024 15:45:04 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[sEMeeting].[pOnlineMeetingBatchGet]') AND type in (N'P', N'PC'))
DROP PROCEDURE [sEMeeting].[pOnlineMeetingBatchGet]
GO
/****** Object:  StoredProcedure [sEMeeting].[pOnlineMeetingAttendanceGet]    Script Date: 10-01-2024 15:45:04 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[sEMeeting].[pOnlineMeetingAttendanceGet]') AND type in (N'P', N'PC'))
DROP PROCEDURE [sEMeeting].[pOnlineMeetingAttendanceGet]
GO
/****** Object:  StoredProcedure [sEMeeting].[pOnlineMeetingAttendanceAdd]    Script Date: 10-01-2024 15:45:04 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[sEMeeting].[pOnlineMeetingAttendanceAdd]') AND type in (N'P', N'PC'))
DROP PROCEDURE [sEMeeting].[pOnlineMeetingAttendanceAdd]
GO
/****** Object:  StoredProcedure [sEMeeting].[pOnlineMeetingAssigneeGet]    Script Date: 10-01-2024 15:45:04 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[sEMeeting].[pOnlineMeetingAssigneeGet]') AND type in (N'P', N'PC'))
DROP PROCEDURE [sEMeeting].[pOnlineMeetingAssigneeGet]
GO
/****** Object:  StoredProcedure [sEMeeting].[pOnlineMeetingAdd]    Script Date: 10-01-2024 15:45:04 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[sEMeeting].[pOnlineMeetingAdd]') AND type in (N'P', N'PC'))
DROP PROCEDURE [sEMeeting].[pOnlineMeetingAdd]
GO
/****** Object:  StoredProcedure [sEMeeting].[pOnlineMeetingAccounts]    Script Date: 10-01-2024 15:45:04 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[sEMeeting].[pOnlineMeetingAccounts]') AND type in (N'P', N'PC'))
DROP PROCEDURE [sEMeeting].[pOnlineMeetingAccounts]
GO
/****** Object:  StoredProcedure [sEMeeting].[pOnlineMeetingAccountDetailsGet]    Script Date: 10-01-2024 15:45:04 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[sEMeeting].[pOnlineMeetingAccountDetailsGet]') AND type in (N'P', N'PC'))
DROP PROCEDURE [sEMeeting].[pOnlineMeetingAccountDetailsGet]
GO
/****** Object:  StoredProcedure [sEMeeting].[pOnlineMeetingAbsentStudentListGet]    Script Date: 10-01-2024 15:45:04 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[sEMeeting].[pOnlineMeetingAbsentStudentListGet]') AND type in (N'P', N'PC'))
DROP PROCEDURE [sEMeeting].[pOnlineMeetingAbsentStudentListGet]
GO
/****** Object:  StoredProcedure [sEMeeting].[pNotitficationLogIdGet]    Script Date: 10-01-2024 15:45:04 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[sEMeeting].[pNotitficationLogIdGet]') AND type in (N'P', N'PC'))
DROP PROCEDURE [sEMeeting].[pNotitficationLogIdGet]
GO
/****** Object:  StoredProcedure [sEMeeting].[pMobileNotitficationTitleGet]    Script Date: 10-01-2024 15:45:04 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[sEMeeting].[pMobileNotitficationTitleGet]') AND type in (N'P', N'PC'))
DROP PROCEDURE [sEMeeting].[pMobileNotitficationTitleGet]
GO
/****** Object:  StoredProcedure [sEMeeting].[pMenuGet]    Script Date: 10-01-2024 15:45:04 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[sEMeeting].[pMenuGet]') AND type in (N'P', N'PC'))
DROP PROCEDURE [sEMeeting].[pMenuGet]
GO
/****** Object:  StoredProcedure [sEMeeting].[pMeetingTypeMasterDetailGet]    Script Date: 10-01-2024 15:45:04 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[sEMeeting].[pMeetingTypeMasterDetailGet]') AND type in (N'P', N'PC'))
DROP PROCEDURE [sEMeeting].[pMeetingTypeMasterDetailGet]
GO
/****** Object:  StoredProcedure [sEMeeting].[pMeetingTypeMasterDelete]    Script Date: 10-01-2024 15:45:04 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[sEMeeting].[pMeetingTypeMasterDelete]') AND type in (N'P', N'PC'))
DROP PROCEDURE [sEMeeting].[pMeetingTypeMasterDelete]
GO
/****** Object:  StoredProcedure [sEMeeting].[pMeetingTypeMasterAdd]    Script Date: 10-01-2024 15:45:04 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[sEMeeting].[pMeetingTypeMasterAdd]') AND type in (N'P', N'PC'))
DROP PROCEDURE [sEMeeting].[pMeetingTypeMasterAdd]
GO
/****** Object:  StoredProcedure [sEMeeting].[pMeetingTypeGet]    Script Date: 10-01-2024 15:45:04 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[sEMeeting].[pMeetingTypeGet]') AND type in (N'P', N'PC'))
DROP PROCEDURE [sEMeeting].[pMeetingTypeGet]
GO
/****** Object:  StoredProcedure [sEMeeting].[pMeetingAccountNameGet]    Script Date: 10-01-2024 15:45:04 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[sEMeeting].[pMeetingAccountNameGet]') AND type in (N'P', N'PC'))
DROP PROCEDURE [sEMeeting].[pMeetingAccountNameGet]
GO
/****** Object:  StoredProcedure [sEMeeting].[pMeetingAccountGet]    Script Date: 10-01-2024 15:45:04 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[sEMeeting].[pMeetingAccountGet]') AND type in (N'P', N'PC'))
DROP PROCEDURE [sEMeeting].[pMeetingAccountGet]
GO
/****** Object:  StoredProcedure [sEMeeting].[pEventTemplateGetForAttendance]    Script Date: 10-01-2024 15:45:04 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[sEMeeting].[pEventTemplateGetForAttendance]') AND type in (N'P', N'PC'))
DROP PROCEDURE [sEMeeting].[pEventTemplateGetForAttendance]
GO
/****** Object:  StoredProcedure [sEMeeting].[pEventTemplateGet]    Script Date: 10-01-2024 15:45:04 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[sEMeeting].[pEventTemplateGet]') AND type in (N'P', N'PC'))
DROP PROCEDURE [sEMeeting].[pEventTemplateGet]
GO
/****** Object:  StoredProcedure [sEMeeting].[pEventSMSTemplateIdGet]    Script Date: 10-01-2024 15:45:04 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[sEMeeting].[pEventSMSTemplateIdGet]') AND type in (N'P', N'PC'))
DROP PROCEDURE [sEMeeting].[pEventSMSTemplateIdGet]
GO
/****** Object:  StoredProcedure [sEMeeting].[pEmployeeMasterIdGet]    Script Date: 10-01-2024 15:45:04 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[sEMeeting].[pEmployeeMasterIdGet]') AND type in (N'P', N'PC'))
DROP PROCEDURE [sEMeeting].[pEmployeeMasterIdGet]
GO
/****** Object:  StoredProcedure [sEMeeting].[pCreateSMSStatus]    Script Date: 10-01-2024 15:45:04 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[sEMeeting].[pCreateSMSStatus]') AND type in (N'P', N'PC'))
DROP PROCEDURE [sEMeeting].[pCreateSMSStatus]
GO
/****** Object:  StoredProcedure [sEMeeting].[pCancelMeeting]    Script Date: 10-01-2024 15:45:04 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[sEMeeting].[pCancelMeeting]') AND type in (N'P', N'PC'))
DROP PROCEDURE [sEMeeting].[pCancelMeeting]
GO
/****** Object:  StoredProcedure [sEMeeting].[pBatchLockGet]    Script Date: 10-01-2024 15:45:04 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[sEMeeting].[pBatchLockGet]') AND type in (N'P', N'PC'))
DROP PROCEDURE [sEMeeting].[pBatchLockGet]
GO
/****** Object:  StoredProcedure [sEMeeting].[pAttachmentLogAdd]    Script Date: 10-01-2024 15:45:04 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[sEMeeting].[pAttachmentLogAdd]') AND type in (N'P', N'PC'))
DROP PROCEDURE [sEMeeting].[pAttachmentLogAdd]
GO
/****** Object:  StoredProcedure [sEMeeting].[GetStudentProfile]    Script Date: 10-01-2024 15:45:04 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[sEMeeting].[GetStudentProfile]') AND type in (N'P', N'PC'))
DROP PROCEDURE [sEMeeting].[GetStudentProfile]
GO
/****** Object:  StoredProcedure [sEMeeting].[GetStudentProfile]    Script Date: 10-01-2024 15:45:04 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[sEMeeting].[GetStudentProfile]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [sEMeeting].[GetStudentProfile] AS' 
END
GO

ALTER PROCEDURE [sEMeeting].[GetStudentProfile] 
	@racademicId bigint,
	@rbatchId int
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

	SELECT A.OrgId, BatchId, StudentId, A.Id AS AcademicId, SM.Code, A.RollNo, (FirstName +' '+MiddleName+' '+LastName) AS StudentName,
                            SM.FirstName, SM.MiddleName, SM.LastName, A.ClassId, A.DivisionId, (CM.DisplayTitle +'-'+ DM.DisplayTitle) AS ClassDivision,
                            DPM.Id AS DepartmentId, DPM.DisplayTitle AS DepartmentName, SM.SUID, B.Title as BatchName
                             FROM sStudent.tAcademic A INNER JOIN sStudent.tStudentMaster SM ON A.StudentId=SM.Id
                            INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = A.DivisionId
                            INNER JOIN sSetup.tDepartmentMaster DPM ON DPM.Id = CM.DepartmentId
                            INNER JOIN sSetup.tBatchMaster B ON b.Id = A.BatchId
							WHERE A.Id=@racademicId AND BatchId = @rbatchId



END

GO
/****** Object:  StoredProcedure [sEMeeting].[pAttachmentLogAdd]    Script Date: 10-01-2024 15:45:04 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[sEMeeting].[pAttachmentLogAdd]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [sEMeeting].[pAttachmentLogAdd] AS' 
END
GO

ALTER PROCEDURE [sEMeeting].[pAttachmentLogAdd]
		@rMessageId nvarchar(max),
		@rAttachment nvarchar(max)
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	BEGIN
		BEGIN TRY	
			INSERT INTO sAlert.tAlertAttachmentLog VALUES (@rMessageId, @rAttachment)
		END TRY
		BEGIN CATCH 
		ROLLBACK TRANSACTION
	END CATCH
	END

GO
/****** Object:  StoredProcedure [sEMeeting].[pBatchLockGet]    Script Date: 10-01-2024 15:45:04 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[sEMeeting].[pBatchLockGet]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [sEMeeting].[pBatchLockGet] AS' 
END
GO

ALTER PROC [sEMeeting].[pBatchLockGet]
	@rBatchId int

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

	BEGIN TRY

	Select ISNULL(IsLock,0) as IsLock FROM sSetup.tBatchMaster WHERE Id = @rBatchId

	END TRY

	BEGIN CATCH
	SELECT -1 as Result
	END CATCH

END

GO
/****** Object:  StoredProcedure [sEMeeting].[pCancelMeeting]    Script Date: 10-01-2024 15:45:04 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[sEMeeting].[pCancelMeeting]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [sEMeeting].[pCancelMeeting] AS' 
END
GO


ALTER PROCEDURE [sEMeeting].[pCancelMeeting]
	@rId bigint

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	BEGIN
		BEGIN TRY
			
			IF EXISTS (SELECT 1 FROM sEMeeting.tOnlineMeeting WHERE IsCompleted = 550 AND Id = @rId)
			BEGIN
				SELECT -1 as Result
			END
			IF EXISTS (SELECT 1 FROM sEMeeting.tOnlineMeeting WHERE StartDate >= GetUtcDate() AND Id = @rId)
			BEGIN
				SELECT -102 as Result
			END
			ELSE
			BEGIN
				Update sEMeeting.tOnlineMeeting SET IsCompleted = 551 WHERE StartDate < GetUtcDate() AND IsCompleted = 549 AND Id = @rId
				SELECT 1 as Result
			END
		END TRY
		BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -101 AS Result
	END CATCH
	END

GO
/****** Object:  StoredProcedure [sEMeeting].[pCreateSMSStatus]    Script Date: 10-01-2024 15:45:04 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[sEMeeting].[pCreateSMSStatus]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [sEMeeting].[pCreateSMSStatus] AS' 
END
GO

ALTER PROCEDURE [sEMeeting].[pCreateSMSStatus]
		@rResultMessage nvarchar(max)
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	BEGIN
		BEGIN TRY
			Insert Into sAlert.tSMSStatus VALUES (CONVERT(DateTime,GetUtcDate(),103), @rResultMessage)
		END TRY
		BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH
	END

GO
/****** Object:  StoredProcedure [sEMeeting].[pEmployeeMasterIdGet]    Script Date: 10-01-2024 15:45:04 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[sEMeeting].[pEmployeeMasterIdGet]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [sEMeeting].[pEmployeeMasterIdGet] AS' 
END
GO

ALTER PROCEDURE [sEMeeting].[pEmployeeMasterIdGet]
		@rMobileNotificationCode nvarchar(max),
		@rOrgId int
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	BEGIN
		BEGIN TRY
			SELECT Id FROM sHrm.tEmployeeMaster WHERE Code = @rMobileNotificationCode AND OrgId= @rOrgId AND  ISNULL(IsOtherUser,0) = 0 
		END TRY
		BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH
	END

GO
/****** Object:  StoredProcedure [sEMeeting].[pEventSMSTemplateIdGet]    Script Date: 10-01-2024 15:45:04 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[sEMeeting].[pEventSMSTemplateIdGet]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [sEMeeting].[pEventSMSTemplateIdGet] AS' 
END
GO

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

GO
/****** Object:  StoredProcedure [sEMeeting].[pEventTemplateGet]    Script Date: 10-01-2024 15:45:04 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[sEMeeting].[pEventTemplateGet]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [sEMeeting].[pEventTemplateGet] AS' 
END
GO
ALTER PROCEDURE [sEMeeting].[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 = 160
		END TRY
		BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH
	END

GO
/****** Object:  StoredProcedure [sEMeeting].[pEventTemplateGetForAttendance]    Script Date: 10-01-2024 15:45:04 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[sEMeeting].[pEventTemplateGetForAttendance]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [sEMeeting].[pEventTemplateGetForAttendance] AS' 
END
GO


ALTER PROCEDURE [sEMeeting].[pEventTemplateGetForAttendance]
		@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 = 161
		END TRY
		BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH
	END

GO
/****** Object:  StoredProcedure [sEMeeting].[pMeetingAccountGet]    Script Date: 10-01-2024 15:45:04 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[sEMeeting].[pMeetingAccountGet]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [sEMeeting].[pMeetingAccountGet] AS' 
END
GO

ALTER PROCEDURE [sEMeeting].[pMeetingAccountGet]
		@rOrgGroupId smallint
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	BEGIN
	BEGIN TRY
		SELECT
		OMA.Id,
		OMA.AccountName AS Title
		FROM sAcademic.tOnlineMeetingAccount OMA
		WHERE ISNULL(OMA.IsObsolete,0) = 0 AND OMA.OrgGroupId =  @rOrgGroupId
	END TRY
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
	END

GO
/****** Object:  StoredProcedure [sEMeeting].[pMeetingAccountNameGet]    Script Date: 10-01-2024 15:45:04 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[sEMeeting].[pMeetingAccountNameGet]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [sEMeeting].[pMeetingAccountNameGet] AS' 
END
GO

ALTER PROCEDURE [sEMeeting].[pMeetingAccountNameGet]
		@rEmployeeId bigint
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	BEGIN
	BEGIN TRY
	SELECT OMA.Id,
	OMA.AccountName as Title
	FROM sAcademic.tOnlineMeetingAccount OMA 
	WHERE EmployeeId = @rEmployeeId 
	AND ISNULL(OMA.IsObsolete,0) = 0
	END TRY
	BEGIN CATCH 
		SELECT -1 AS Result
	END CATCH	
	END

GO
/****** Object:  StoredProcedure [sEMeeting].[pMeetingTypeGet]    Script Date: 10-01-2024 15:45:04 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[sEMeeting].[pMeetingTypeGet]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [sEMeeting].[pMeetingTypeGet] AS' 
END
GO


ALTER PROCEDURE [sEMeeting].[pMeetingTypeGet]
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	BEGIN
		BEGIN TRY
			Select OM.AutoId as Id, 
			OM.Title
			from sEMeeting.tMeetingTypeMaster OM 
			where IsObsolete = 0 
			order by OrderIndex 
		END TRY
		BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH
	END

GO
/****** Object:  StoredProcedure [sEMeeting].[pMeetingTypeMasterAdd]    Script Date: 10-01-2024 15:45:04 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[sEMeeting].[pMeetingTypeMasterAdd]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [sEMeeting].[pMeetingTypeMasterAdd] AS' 
END
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

	IF (@rAutoId = 0)
	BEGIN
	 
	IF EXISTS (select 1 from sEMeeting.tMeetingTypeMaster where Code = @rCode)
		BEGIN
			SELECT -101 as Result
			Return
		END
	IF EXISTS (select 1 from sEMeeting.tMeetingTypeMaster where OrderIndex = @rOrderIndex)
		BEGIN
			SELECT -102 as Result
			Return
		END
	END
	ELSE
	    BEGIN
		IF EXISTS (select 1 from sEMeeting.tMeetingTypeMaster where Code = @rCode AND AutoId<>@rAutoId)
		BEGIN
			SELECT -101 as Result
			Return
		END
		IF EXISTS (select 1 from sEMeeting.tMeetingTypeMaster where OrderIndex = @rOrderIndex AND AutoId<>@rAutoId)
		BEGIN
			SELECT -102 as Result
			Return
		END
		END

	BEGIN TRANSACTION	
	IF (@rAutoId = 0)
	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
	ELSE
	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

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


GO
/****** Object:  StoredProcedure [sEMeeting].[pMeetingTypeMasterDelete]    Script Date: 10-01-2024 15:45:04 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[sEMeeting].[pMeetingTypeMasterDelete]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [sEMeeting].[pMeetingTypeMasterDelete] AS' 
END
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)
		BEGIN 
			Delete sEMeeting.tMeetingTypeMaster WHERE AutoId = @rId
			SELECT 1 As Result
		END
	END
END TRY
BEGIN CATCH 
		SELECT -1 AS Result
END CATCH
END


GO
/****** Object:  StoredProcedure [sEMeeting].[pMeetingTypeMasterDetailGet]    Script Date: 10-01-2024 15:45:04 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[sEMeeting].[pMeetingTypeMasterDetailGet]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [sEMeeting].[pMeetingTypeMasterDetailGet] AS' 
END
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, IsObsolete
			from [sEMeeting].[tMeetingTypeMaster] MTM 
			 where (MTM.Title LIKE '%' + @rTitle + '%' OR (ISNULL(@rTitle,'') = '') OR @rTitle = '*')
			 Order By MTM.OrderIndex
	END
	ELSE
	BEGIN
		SELECT AutoId, Title, Code, OrderIndex, Description, IsObsolete
			from [sEMeeting].[tMeetingTypeMaster] where AutoId = @rId
	END
END TRY
BEGIN CATCH 
		SELECT -1 AS Result
END CATCH
END

GO
/****** Object:  StoredProcedure [sEMeeting].[pMenuGet]    Script Date: 10-01-2024 15:45:04 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[sEMeeting].[pMenuGet]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [sEMeeting].[pMenuGet] AS' 
END
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
/****** Object:  StoredProcedure [sEMeeting].[pMobileNotitficationTitleGet]    Script Date: 10-01-2024 15:45:04 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[sEMeeting].[pMobileNotitficationTitleGet]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [sEMeeting].[pMobileNotitficationTitleGet] AS' 
END
GO

ALTER PROCEDURE [sEMeeting].[pMobileNotitficationTitleGet]
		@rEventId int
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	BEGIN
		BEGIN TRY	
			SELECT Title FROM sAlert.tEventMaster WHERE Id= @rEventId
		END TRY
		BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH
	END

GO
/****** Object:  StoredProcedure [sEMeeting].[pNotitficationLogIdGet]    Script Date: 10-01-2024 15:45:04 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[sEMeeting].[pNotitficationLogIdGet]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [sEMeeting].[pNotitficationLogIdGet] AS' 
END
GO

ALTER PROCEDURE [sEMeeting].[pNotitficationLogIdGet]
		@rFromId bigint,
		@rToId bigint
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	BEGIN
		BEGIN TRY	
			SELECT Id AS NotificationId FROM sAlert.tNotificationLog WHERE (Id>=@rFromId) AND (Id<=@rToId)
		END TRY
		BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH
	END

GO
/****** Object:  StoredProcedure [sEMeeting].[pOnlineMeetingAbsentStudentListGet]    Script Date: 10-01-2024 15:45:04 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[sEMeeting].[pOnlineMeetingAbsentStudentListGet]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [sEMeeting].[pOnlineMeetingAbsentStudentListGet] AS' 
END
GO
	

ALTER PROCEDURE [sEMeeting].[pOnlineMeetingAbsentStudentListGet]
	@rOnlineMeetingId bigint,
	@rTemplate nvarchar(max)

	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
		 SELECT 
			A.AcademicId,
			A.Code,
			A.Name,
			A.ParentContactNo AS MobileNo,	
			A.ParentEmail AS EmailId,
			replace (
			replace (
			replace (
			replace (
			replace (
			replace (
			replace (
			replace(@rTemplate,'[MeetingType]',OMT.Title),
			'[Name]',A.Name),
			'[StartDate]',CONVERT(varchar(11),ISNULL(OM.StartDate,'') ,103)),
			'[EndDate]',CONVERT(varchar(11),ISNULL(OM.EndDate,'') ,103)),
			'[Teacher]',EE.EmployeeName),
			'[Title]',OM.Title),
			'[StartTime]',CONVERT(varchar(11),ISNULL(OM.StartTime,'') ,8)),
			'[EndTime]',CONVERT(varchar(11),ISNULL(OM.EndTime,'') ,8))
			AS MsgText,
			'' AS Subject,
			 2003 AS ReceiverSourceTypeId,
			 A.OrgId AS OrgId,
			 (SELECT OrgGroupId FROM sSetup.tOrganizationMaster where ID=A.OrgId) AS OrgGroupId,
			 A.AcademicId AS ReceiverSourceId,
			 A.AcademicId AS SourceId,
			 2003 AS SourceTypeId,
			 OMT.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,
			 CONVERT(varchar(11),ISNULL(OM.StartTime,'') ,8) AS StartTime,
			 CONVERT(varchar(11),ISNULL(OM.EndTime,'') ,8) AS EndTime,
			 A.WhatsAppContactNo
	FROM 
		sEMeeting.tOnlineMeeting OM
		INNER JOIN sEMeeting.tMeetingTypeMaster OMT ON OMT.AutoId = OM.MeetingTypeId
		INNER JOIN sHrm.vExtEmployee EE ON EE.EmployeeId = OM.HostEmployeeId
		INNER JOIN (
			SELECT 
				OM.Id as OnlineMeetingId,
				SD.AcademicId,
				SD.Name,
				SD.Code,
				SD.ParentContactNo,	
				SD.ParentEmail,
				SD.OrgId,
				ISNULL(SC.WhatsAppContactNo,'') AS WhatsAppContactNo
			FROM 
			    sEMeeting.tOnlineMeetingScope OMS 
				INNER JOIN sEMeeting.tOnlineMeeting OM ON OMS.OnlineMeetingId = OM.Id 
				INNER JOIN sStudent.vStudentAllDetail SD ON SD.AcademicId = OMS.ScopeSourceId
				LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId = SD.StudentId
			WHERE 
			    OMS.OnlineMeetingId = @rOnlineMeetingId AND SD.StatusId = 1 AND OMS.ScopeSourceTypeId = 2003

			UNION ALL	
																			 			  
			SELECT 
				OM.Id as OnlineMeetingId,
				SD.AcademicId,
				SD.Name,
				SD.Code,
				SD.ParentContactNo,	
				SD.ParentEmail,
				SD.OrgId,
				ISNULL(SC.WhatsAppContactNo,'') AS WhatsAppContactNo
			FROM 
				sEMeeting.tOnlineMeetingScope OMS 
				INNER JOIN sEMeeting.tOnlineMeeting OM ON OMS.OnlineMeetingId = OM.Id 
				INNER JOIN sStudent.vStudentAllDetail SD ON SD.DepartmentId = OMS.ScopeSourceId
				LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId = SD.StudentId
				 
			WHERE 
				OMS.OnlineMeetingId = @rOnlineMeetingId AND SD.StatusId = 1 AND  OMS.ScopeSourceTypeId = 2017

			UNION ALL		
															 			 				  
			SELECT 
				OM.Id as OnlineMeetingId,
				SD.AcademicId,
				SD.Name,
				SD.Code,
				SD.ParentContactNo,	
				SD.ParentEmail,
				SD.OrgId,
				ISNULL(SC.WhatsAppContactNo,'') AS WhatsAppContactNo
			FROM 
				sEMeeting.tOnlineMeetingScope OMS 
				INNER JOIN sEMeeting.tOnlineMeeting OM ON OMS.OnlineMeetingId = OM.Id 
				INNER JOIN sStudent.vStudentAllDetail SD ON SD.ClassId = OMS.ScopeSourceId  
				LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId = SD.StudentId
			WHERE 
				OMS.OnlineMeetingId = @rOnlineMeetingId AND SD.StatusId = 1 AND OMS.ScopeSourceTypeId = 2016

			UNION ALL	
																 			 				  
			SELECT 
				OM.Id as OnlineMeetingId,
				SD.AcademicId,
				SD.Name,
				SD.Code,
				SD.ParentContactNo,	
				SD.ParentEmail,
				SD.OrgId,
				ISNULL(SC.WhatsAppContactNo,'') AS WhatsAppContactNo
			FROM 
				sEMeeting.tOnlineMeetingScope OMS 
				INNER JOIN sEMeeting.tOnlineMeeting OM ON OMS.OnlineMeetingId = OM.Id 
				INNER JOIN sStudent.vStudentAllDetail SD ON SD.DivisionId = OMS.ScopeSourceId
				LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId = SD.StudentId
			WHERE 
				OMS.OnlineMeetingId = @rOnlineMeetingId AND SD.StatusId = 1 AND OMS.ScopeSourceTypeId = 2005

			UNION ALL		
															 			 				  
			SELECT 
				OM.Id as OnlineMeetingId,
				SD.AcademicId,
				SD.Name,
				SD.Code,
				SD.ParentContactNo,	
				SD.ParentEmail,
				SD.OrgId,
				ISNULL(SC.WhatsAppContactNo,'') AS WhatsAppContactNo
			FROM 
				sEMeeting.tOnlineMeetingScope OMS 
				INNER JOIN sEMeeting.tOnlineMeeting OM ON OMS.OnlineMeetingId = OM.Id 
				INNER JOIN sStudent.vStudentAllDetail SD ON SD.OrgId = OMS.ScopeSourceId
				LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId = SD.StudentId 
			WHERE 
				OMS.OnlineMeetingId = @rOnlineMeetingId AND SD.StatusId = 1 AND OMS.ScopeSourceTypeId = 2021
			
		) as A ON A.OnlineMeetingId = OM.Id 
		LEFT JOIN sEMeeting.tOnlineMeetingAttendance OMA ON OMA.OnlineMeetingId = OM.Id AND OMA.ParticipantSourceId = A.AcademicId
	WHERE
		OM.Id = @rOnlineMeetingId AND ISNULL(OMA.IsPresent,0) <> 1
END




GO
/****** Object:  StoredProcedure [sEMeeting].[pOnlineMeetingAccountDetailsGet]    Script Date: 10-01-2024 15:45:04 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[sEMeeting].[pOnlineMeetingAccountDetailsGet]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [sEMeeting].[pOnlineMeetingAccountDetailsGet] AS' 
END
GO

ALTER PROCEDURE [sEMeeting].[pOnlineMeetingAccountDetailsGet]
	@rMeetingAccountId int

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	BEGIN
	BEGIN TRY
		SELECT OAuthAccountId,OAuthClientId,OAuthClientSecret,AccountEmailId,JWTToken FROM sAcademic.tOnlineMeetingAccount WHERE Id = @rMeetingAccountId AND ISNULL(IsObsolete,0) = 0
	END TRY
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
	END

GO
/****** Object:  StoredProcedure [sEMeeting].[pOnlineMeetingAccounts]    Script Date: 10-01-2024 15:45:04 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[sEMeeting].[pOnlineMeetingAccounts]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [sEMeeting].[pOnlineMeetingAccounts] AS' 
END
GO

ALTER PROCEDURE [sEMeeting].[pOnlineMeetingAccounts]
	@rOnlineMeetingAccountId bigint

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	BEGIN
		BEGIN TRY
			SELECT STUFF((SELECT ','+ CONVERT(varchar,OM.Id) FROM sEMeeting.tOnlineMeeting OM WHERE MeetingAccountId =  @rOnlineMeetingAccountId AND IsCompleted = 0								FOR XML PATH('')), 1, 1, '') AS Ids
		END TRY
		BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH
	END

GO
/****** Object:  StoredProcedure [sEMeeting].[pOnlineMeetingAdd]    Script Date: 10-01-2024 15:45:04 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[sEMeeting].[pOnlineMeetingAdd]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [sEMeeting].[pOnlineMeetingAdd] AS' 
END
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,
			CASE WHEN @rIsCompleted = 0 THEN 549 ELSE 0 END,
			@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 = CASE WHEN @rIsCompleted = 1 THEN 550 ELSE 549 END,
		   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
/****** Object:  StoredProcedure [sEMeeting].[pOnlineMeetingAssigneeGet]    Script Date: 10-01-2024 15:45:04 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[sEMeeting].[pOnlineMeetingAssigneeGet]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [sEMeeting].[pOnlineMeetingAssigneeGet] AS' 
END
GO

ALTER PROCEDURE [sEMeeting].[pOnlineMeetingAssigneeGet]
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	BEGIN
		BEGIN TRY
			SELECT Id,
			Title 
			FROM sCommon.tAssigneeMaster
			WHERE IsObsolete=0 ORDER BY Id
		END TRY
		BEGIN CATCH 
		SELECT -1 AS Result
		END CATCH
	END

GO
/****** Object:  StoredProcedure [sEMeeting].[pOnlineMeetingAttendanceAdd]    Script Date: 10-01-2024 15:45:04 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[sEMeeting].[pOnlineMeetingAttendanceAdd]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [sEMeeting].[pOnlineMeetingAttendanceAdd] AS' 
END
GO
ALTER PROCEDURE [sEMeeting].[pOnlineMeetingAttendanceAdd]
	 @rOnlineMeetingId bigint ,
	 @rSourceId bigint,
	 @rSourceTypeId int,
	 @rAttendanceType bit
		 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
	 
	 IF(@rAttendanceType= 1) 
	   BEGIN
	   IF NOT EXISTS (SELECT 1 FROM sEMeeting.tOnlineMeetingAttendance WHERE OnlineMeetingId = @rOnlineMeetingId AND ParticipantSourceId = @rSourceId AND ParticipantSourceTypeId = @rSourceTypeId)
			BEGIN
			INSERT  INTO sEMeeting.tOnlineMeetingAttendance
			(OnlineMeetingId,ParticipantSourceTypeId, ParticipantSourceId, IsPresent ,FirstInDateTime, IsLoggedIn)
			VALUES 
			(@rOnlineMeetingId, @rSourceTypeId, @rSourceId,1,GetDate(), 1)
			END
		SELECT 1 AS Result	
		END
		
		ELSE IF (@rAttendanceType= 0)
		BEGIN
		IF EXISTS (SELECT 1 FROM sEMeeting.tOnlineMeetingAttendance WHERE OnlineMeetingId = @rOnlineMeetingId AND ParticipantSourceId = @rSourceId AND ParticipantSourceTypeId = @rSourceTypeId)
			BEGIN
			UPDATE sEMeeting.tOnlineMeetingAttendance 
			SET LastOutDateTime = GetDate(),
			IsLoggedIn = 0
			Where ParticipantSourceId= @rSourceId AND OnlineMeetingId= @rOnlineMeetingId And ParticipantSourceTypeId = @rSourceTypeId
			SELECT 11 AS Result
			END
			
		ELSE 
		SELECT -1 AS Result
	
END
END

GO
/****** Object:  StoredProcedure [sEMeeting].[pOnlineMeetingAttendanceGet]    Script Date: 10-01-2024 15:45:04 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[sEMeeting].[pOnlineMeetingAttendanceGet]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [sEMeeting].[pOnlineMeetingAttendanceGet] AS' 
END
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
/****** Object:  StoredProcedure [sEMeeting].[pOnlineMeetingBatchGet]    Script Date: 10-01-2024 15:45:04 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[sEMeeting].[pOnlineMeetingBatchGet]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [sEMeeting].[pOnlineMeetingBatchGet] AS' 
END
GO

ALTER 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
/****** Object:  StoredProcedure [sEMeeting].[pOnlineMeetingClassGet]    Script Date: 10-01-2024 15:45:04 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[sEMeeting].[pOnlineMeetingClassGet]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [sEMeeting].[pOnlineMeetingClassGet] AS' 
END
GO

ALTER PROCEDURE [sEMeeting].[pOnlineMeetingClassGet]
	@rDepartmentId int,
	@rOrgId int,
	@rUserId bigint

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

	BEGIN TRY
		SELECT DISTINCT CM.Id,CM.DisplayTitle AS Title FROM sSetup.tDivisionMaster DM
                               INNER JOIN sSetup.tClassMaster CM ON CM.Id=DM.ClassId AND CM.OrgId=  @rOrgId 
                               INNER JOIN sSecurity.tUserAccess U ON U.SourceId = DM.Id AND U.SourceTypeId=2005
                               WHERE  CM.DepartmentId= @rDepartmentId  AND U.UserId = @rUserId
	END TRY

	BEGIN CATCH
	 SELECT -1 as Result
	END CATCH

END

GO
/****** Object:  StoredProcedure [sEMeeting].[pOnlineMeetingDelete]    Script Date: 10-01-2024 15:45:04 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[sEMeeting].[pOnlineMeetingDelete]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [sEMeeting].[pOnlineMeetingDelete] AS' 
END
GO
 
 ALTER PROCEDURE [sEMeeting].[pOnlineMeetingDelete]
	 
	 @rId bigint
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	BEGIN TRY
		BEGIN TRANSACTION
			Delete from sEMeeting.tOnlineMeetingResource where OnlineMeetingId=@rId
			Delete from sEMeeting.tOnlineMeetingReference where OnlineMeetingId=@rId
			Delete from sEMeeting.tOnlineMeetingAttendance where OnlineMeetingId=@rId
			Delete from sEMeeting.tOnlineMeetingScope where OnlineMeetingId=@rId
			Delete from sEMeeting.tOnlineMeetingSettings Where OnlineMeetingId = @rId
			Delete from sEMeeting.tOnlineMeeting where Id=@rId
			select 1 as Result
		COMMIT TRANSACTION			 
	END TRY
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		select -1 as Result		
	END CATCH	
END

GO
/****** Object:  StoredProcedure [sEMeeting].[pOnlineMeetingDepartmentGet]    Script Date: 10-01-2024 15:45:04 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[sEMeeting].[pOnlineMeetingDepartmentGet]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [sEMeeting].[pOnlineMeetingDepartmentGet] AS' 
END
GO


ALTER PROCEDURE [sEMeeting].[pOnlineMeetingDepartmentGet]
		@rOrgId int,
		@rUserId bigint 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	BEGIN
	BEGIN TRY
		SELECT 
		DM.Id, 
		DM.DisplayTitle AS Title 
		FROM sSetup.tDepartmentMaster DM 
		INNER JOIN sSecurity.tUserAccess U ON U.SourceId = DM.Id 
		AND U.SourceTypeId=2017
        WHERE IsObsolete = 0 
		AND OrgId = @rOrgId  
		AND UserId = @rUserId
	END TRY
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
	END

GO
/****** Object:  StoredProcedure [sEMeeting].[pOnlineMeetingDivisionGet]    Script Date: 10-01-2024 15:45:04 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[sEMeeting].[pOnlineMeetingDivisionGet]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [sEMeeting].[pOnlineMeetingDivisionGet] AS' 
END
GO

ALTER PROCEDURE [sEMeeting].[pOnlineMeetingDivisionGet]
	 
	 @rClassId int,
	 @rUserSourceId bigint,
	 @rUserSourceTypeId int,
	 @rOrgId int,
	 @rUserId bigint,
	 @rBatchId int,
	 @rAttendanceEntryBasedOn nvarchar
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
BEGIN
	BEGIN TRY
        if (@rAttendanceEntryBasedOn = 'Class Teacher' AND @rUserSourceTypeId = 95)
			BEGIN
				SELECT DISTINCT DM.Id AS Id, DM.DisplayTitle AS Title
					   FROM sSetup.tClassMaster CM 
					   INNER JOIN sSetup.tDivisionMaster DM ON DM.ClassId = CM.Id
                       INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=CM.OrgId
                       WHERE DM.InchargeemployeeID= @rUserSourceId  
					   AND CM.OrgId= @rOrgId 
					   AND CM.Id = @rClassId
			END	 
		else if (@rAttendanceEntryBasedOn = 'Academic Setup' AND @rUserSourceTypeId = 95)
				BEGIN
					SELECT DISTINCT DivisionId AS Id, DivisionTitle, DivisionOrderIndex AS Title 
                        FROM sAcademic.vTeacherSubjectDivision TSD 
						INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=TSD.OrgId 
						WHERE  TSD.EmployeeId= @rUserSourceId 
						AND TSD.ClassId = @rClassId
                        ORDER BY DivisionOrderIndex
				END
		else
					BEGIN
						SELECT DM.Id,DM.DisplayTitle AS Title 
							   FROM sSetup.tDivisionMaster DM 
                               INNER JOIN sSetup.tClassMaster CM ON CM.Id=DM.ClassId AND CM.OrgId= @rOrgId 
                               INNER JOIN sSecurity.tUserAccess U ON U.SourceId = DM.Id AND U.SourceTypeId=2005 
                               WHERE  CM.Id = @rClassId 
							   AND UserId = @rUserId 
							   Order by DM.OrderIndex
					END
	END TRY

	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH
END

GO
/****** Object:  StoredProcedure [sEMeeting].[pOnlineMeetingEmployeeGet]    Script Date: 10-01-2024 15:45:04 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[sEMeeting].[pOnlineMeetingEmployeeGet]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [sEMeeting].[pOnlineMeetingEmployeeGet] AS' 
END
GO

ALTER PROCEDURE [sEMeeting].[pOnlineMeetingEmployeeGet]
	 
	 @rDepartmentId int,
	 @rOrgId int
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
BEGIN
	BEGIN TRY
	SELECT EmployeeId AS Id,
	EmployeeName AS Title 
	FROM sHrm.vEmployeeCommunication 
	WHERE ISNULL(IsOtherUser,0) = 0 
	AND StatusId=7 
	AND DepartmentId=@rDepartmentId 
	AND OrgId=@rOrgId ORDER BY Code
	END TRY

	BEGIN CATCH 
		SELECT -1 AS Result
	END CATCH
END

GO
/****** Object:  StoredProcedure [sEMeeting].[pOnlineMeetingGet]    Script Date: 10-01-2024 15:45:04 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[sEMeeting].[pOnlineMeetingGet]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [sEMeeting].[pOnlineMeetingGet] AS' 
END
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
			  UNION ALL
			  SELECT distinct ClassName + '-' + DivisionName FROM sEMeeting.tOnlineMeetingScope OMS INNER JOIN sStudent.vStudentAcademic SA ON OMS.ScopeSourceId = SA.AcademicId Where  OnlineMeetingId = OM.Id AND OMS.ScopeSourceTypeId = 2003
			  UNION ALL
			  SELECT distinct OMG.DisplayTitle + '-' + vEC.DepartmentName FROM sEMeeting.tOnlineMeetingScope OMS INNER JOIN sHrm.vEmployeeCommunication vEC ON OMS.ScopeSourceId = vEC.Id LEFT JOIN sSetup.tOrganizationMaster OMG
				ON vEC.OrgId = OMG.Id Where  OnlineMeetingId = OM.Id AND OMS.ScopeSourceTypeId = 95
			  ) 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 DESC
	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 DESC
		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=2003
			
			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
/****** Object:  StoredProcedure [sEMeeting].[pOnlineMeetingOrganizationGet]    Script Date: 10-01-2024 15:45:04 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[sEMeeting].[pOnlineMeetingOrganizationGet]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [sEMeeting].[pOnlineMeetingOrganizationGet] AS' 
END
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
/****** Object:  StoredProcedure [sEMeeting].[pOnlineMeetingProviderGet]    Script Date: 10-01-2024 15:45:04 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[sEMeeting].[pOnlineMeetingProviderGet]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [sEMeeting].[pOnlineMeetingProviderGet] AS' 
END
GO

ALTER PROCEDURE [sEMeeting].[pOnlineMeetingProviderGet]
	@rMeetingAccountId int

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	BEGIN
	BEGIN TRY
		SELECT MeetingProviderId FROM sAcademic.tOnlineMeetingAccount WHERE Id = @rMeetingAccountId AND ISNULL(IsObsolete,0) = 0
	END TRY
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
	END

GO
/****** Object:  StoredProcedure [sEMeeting].[pOnlineMeetingReferenceDelete]    Script Date: 10-01-2024 15:45:04 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[sEMeeting].[pOnlineMeetingReferenceDelete]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [sEMeeting].[pOnlineMeetingReferenceDelete] AS' 
END
GO
 
ALTER PROCEDURE [sEMeeting].[pOnlineMeetingReferenceDelete]

        @rOnlineMeetingId bigint,
		@rReferencePath nvarchar(Max)
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

	IF NOT EXISTS (SELECT 1 FROM sEMeeting.tOnlineMeetingReference WHERE OnlineMeetingId = @rOnlineMeetingId AND ReferencePath = @rReferencePath)
	BEGIN 
		SELECT -1 AS Result
	END
	ELSE
	BEGIN
		DELETE FROM sEMeeting.tOnlineMeetingReference
		WHERE OnlineMeetingId = @rOnlineMeetingId 
		AND ReferencePath = @rReferencePath
		SELECT 1 AS Result
	END
END

GO
/****** Object:  StoredProcedure [sEMeeting].[pOnlineMeetingResourceAdd]    Script Date: 10-01-2024 15:45:04 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[sEMeeting].[pOnlineMeetingResourceAdd]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [sEMeeting].[pOnlineMeetingResourceAdd] AS' 
END
GO

 
 
ALTER PROCEDURE [sEMeeting].[pOnlineMeetingResourceAdd]
	 
	@rOnlineMeetingId bigint,
	@rResourceTypeId smallint,
	@rResourcePath nvarchar(max),	
	@rIsObsolete bit = 0,
	@rCreatedUserId bigint
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	BEGIN TRANSACTION

	IF NOT EXISTS (SELECT 1 FROM [sEMeeting].[tOnlineMeetingResource] WHERE OnlineMeetingId = @rOnlineMeetingId AND ResourcePath = @rResourcePath)
	BEGIN		
	INSERT INTO [sEMeeting].[tOnlineMeetingResource]	
		(
		OnlineMeetingId,
		ResourceTypeId,
		ResourcePath,
		IsObsolete,
		CreatedUserId,
		CreatedDateTime
		)
	VALUES
		(
		@rOnlineMeetingId,
		@rResourceTypeId,
		@rResourcePath,
		@rIsObsolete,
		@rCreatedUserId,
		GetUtcDate()
		)
	END
	COMMIT TRANSACTION
		SELECT 1 AS Result		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END

GO
/****** Object:  StoredProcedure [sEMeeting].[pOnlineMeetingScopeListGet]    Script Date: 10-01-2024 15:45:04 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[sEMeeting].[pOnlineMeetingScopeListGet]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [sEMeeting].[pOnlineMeetingScopeListGet] AS' 
END
GO

	

ALTER PROCEDURE [sEMeeting].[pOnlineMeetingScopeListGet]
	
		 @rOnlineMeetingId bigint,
	 	 @rTemplate nvarchar(max)
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	
	SELECT 
			A.AcademicId,
			A.Code,
			A.Name,
			A.ParentContactNo AS MobileNo,	
			A.ParentEmail AS EmailId,
			replace (
			replace (
			replace (
			replace (
			replace (
			replace(@rTemplate,'[MeetingType]',OMT.Title),
			'[StartDate]',CONVERT(varchar(11),ISNULL(OM.StartDate,'') ,103)),
			'[EndDate]',CONVERT(varchar(11),ISNULL(OM.EndDate,'') ,103)),
			'[Title]',OM.Title),
			'[StartTime]',CONVERT(varchar(11),ISNULL(OM.StartTime,'') ,8)),
			'[EndTime]',CONVERT(varchar(11),ISNULL(OM.EndTime,'') ,8))
			AS MsgText,
			'' AS Subject,
			 A.SourceTypeId AS ReceiverSourceTypeId,
			 A.OrgId AS OrgId,
			 (SELECT OrgGroupId FROM sSetup.tOrganizationMaster where ID=A.OrgId) AS OrgGroupId,
			 A.AcademicId AS ReceiverSourceId,
			 A.AcademicId AS SourceId,
			 A.SourceTypeId AS SourceTypeId,
			 OMT.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 
		sEMeeting.tOnlineMeeting OM
		INNER JOIN sEMeeting.tMeetingTypeMaster OMT ON OMT.AutoId = OM.MeetingTypeId
		INNER JOIN sHrm.vExtEmployee EE ON EE.EmployeeId = OM.HostEmployeeId
		INNER JOIN (
			SELECT 
				OM.Id as OnlineMeetingId,
				SD.AcademicId,
				SD.Name,
				SD.Code,
				SD.ParentContactNo,	
				SD.ParentEmail,
				SD.OrgId,
				2003 As SourceTypeId,
				ISNULL(SC.WhatsAppContactNo,'') AS WhatsAppContactNo
			FROM 
			    sEMeeting.tOnlineMeetingScope OMS 
				INNER JOIN sEMeeting.tOnlineMeeting OM ON OMS.OnlineMeetingId = OM.Id 
				INNER JOIN sStudent.vStudentAllDetail SD ON SD.AcademicId = OMS.ScopeSourceId
				LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId = SD.StudentId
			WHERE 
			    OMS.OnlineMeetingId = @rOnlineMeetingId AND SD.StatusId = 1 AND OMS.ScopeSourceTypeId = 2003

			UNION ALL	
																			 			  
			SELECT 
				OM.Id as OnlineMeetingId,
				SD.AcademicId,
				SD.Name,
				SD.Code,
				SD.ParentContactNo,	
				SD.ParentEmail,
				SD.OrgId,
				2003 As SourceTypeId,
				ISNULL(SC.WhatsAppContactNo,'') AS WhatsAppContactNo
			FROM 
				sEMeeting.tOnlineMeetingScope OMS 
				INNER JOIN sEMeeting.tOnlineMeeting OM ON OMS.OnlineMeetingId = OM.Id 
				INNER JOIN sStudent.vStudentAllDetail SD ON SD.DepartmentId = OMS.ScopeSourceId
				 LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId = SD.StudentId
			WHERE 
				OMS.OnlineMeetingId = @rOnlineMeetingId AND SD.StatusId = 1 AND  OMS.ScopeSourceTypeId = 2017 AND OMS.AssigneeId = 2

				UNION ALL	
																			 			  
			SELECT 
				OM.Id as OnlineMeetingId,
				vEC.EmployeeId as AcademicId,
				vEC.EmployeeName as Name,
				vEC.Code,
				vEC.MobileNumber as ParentContactNo,
				vEC.CompanyEmail as ParentEmail,
				vEC.OrgId,
				95 As SourceTypeId,
				ISNULL(vEC.WhatsAppContactNo,'') AS WhatsAppContactNo
			FROM 
				sEMeeting.tOnlineMeetingScope OMS 
				INNER JOIN sEMeeting.tOnlineMeeting OM ON OMS.OnlineMeetingId = OM.Id 
				INNER JOIN sHrm.vEmployeeCommunication vEC ON vEC.DepartmentId = OMS.ScopeSourceId 
			WHERE 
				OMS.OnlineMeetingId = @rOnlineMeetingId AND vEC.StatusId = 7 AND  OMS.ScopeSourceTypeId = 2017 AND OMS.AssigneeId = 3

			UNION ALL		
															 			 				  
			SELECT 
				OM.Id as OnlineMeetingId,
				SD.AcademicId,
				SD.Name,
				SD.Code,
				SD.ParentContactNo,	
				SD.ParentEmail,
				SD.OrgId,
				2003 As SourceTypeId,
				ISNULL(SC.WhatsAppContactNo,'') AS WhatsAppContactNo
			FROM 
				sEMeeting.tOnlineMeetingScope OMS 
				INNER JOIN sEMeeting.tOnlineMeeting OM ON OMS.OnlineMeetingId = OM.Id 
				INNER JOIN sStudent.vStudentAllDetail SD ON SD.ClassId = OMS.ScopeSourceId
				LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId = SD.StudentId
			WHERE 
				OMS.OnlineMeetingId = @rOnlineMeetingId AND SD.StatusId = 1 AND OMS.ScopeSourceTypeId = 2016

			UNION ALL	
																 			 				  
			SELECT 
				OM.Id as OnlineMeetingId,
				SD.AcademicId,
				SD.Name,
				SD.Code,
				SD.ParentContactNo,	
				SD.ParentEmail,
				SD.OrgId,
				2003 As SourceTypeId,
				ISNULL(SC.WhatsAppContactNo,'') AS WhatsAppContactNo
			FROM 
				sEMeeting.tOnlineMeetingScope OMS 
				INNER JOIN sEMeeting.tOnlineMeeting OM ON OMS.OnlineMeetingId = OM.Id 
				INNER JOIN sStudent.vStudentAllDetail SD ON SD.DivisionId = OMS.ScopeSourceId
				LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId = SD.StudentId
			WHERE 
				OMS.OnlineMeetingId = @rOnlineMeetingId AND SD.StatusId = 1 AND OMS.ScopeSourceTypeId = 2005

			UNION ALL		
															 			 				  
			SELECT 
				OM.Id as OnlineMeetingId,
				SD.AcademicId,
				SD.Name,
				SD.Code,
				SD.ParentContactNo,	
				SD.ParentEmail,
				SD.OrgId,
				2003 As SourceTypeId,
				ISNULL(SC.WhatsAppContactNo,'') AS WhatsAppContactNo
			FROM 
				sEMeeting.tOnlineMeetingScope OMS 
				INNER JOIN sEMeeting.tOnlineMeeting OM ON OMS.OnlineMeetingId = OM.Id 
				INNER JOIN sStudent.vStudentAllDetail SD ON SD.OrgId = OMS.ScopeSourceId
				LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId = SD.StudentId
			WHERE 
				OMS.OnlineMeetingId = @rOnlineMeetingId AND SD.StatusId = 1 AND OMS.ScopeSourceTypeId = 2021 AND OMS.AssigneeId = 2

				UNION ALL		
															 			 				  
			SELECT 
				OM.Id as OnlineMeetingId,
				vEC.EmployeeId as AcademicId,
				vEC.EmployeeName as Name,
				vEC.Code,
				vEC.MobileNumber as ParentContactNo,
				vEC.CompanyEmail as ParentEmail,
				vEC.OrgId,
				95 As SourceTypeId,
				ISNULL(vEC.WhatsAppContactNo,'') AS WhatsAppContactNo
			FROM 
				sEMeeting.tOnlineMeetingScope OMS 
				INNER JOIN sEMeeting.tOnlineMeeting OM ON OMS.OnlineMeetingId = OM.Id 
				INNER JOIN sHrm.vEmployeeCommunication vEC ON vEC.OrgID = OMS.ScopeSourceId 
			WHERE 
				OMS.OnlineMeetingId = @rOnlineMeetingId AND vEC.StatusId = 7 AND OMS.ScopeSourceTypeId = 2021 AND OMS.AssigneeId = 3

			UNION ALL

				SELECT Distinct
				OM.Id as OnlineMeetingId,
				vEC.EmployeeId as AcademicId,
				vEC.EmployeeName as Name,
				vEC.Code,
				vEC.MobileNumber as ParentContactNo,
				vEC.CompanyEmail as ParentEmail,
				vEC.OrgId,
				95 As SourceTypeId,
				ISNULL(vEC.WhatsAppContactNo,'') AS WhatsAppContactNo
			FROM 
				sEMeeting.tOnlineMeetingScope OMS 
				INNER JOIN sEMeeting.tOnlineMeeting OM ON OMS.OnlineMeetingId = OM.Id 
				INNER JOIN sHrm.vEmployeeCommunication vEC ON (vEC.EmployeeId = OMS.ScopeSourceId) 
				OR (vEC.EmployeeId = OM.HostEmployeeId)
			WHERE 
				OMS.OnlineMeetingId = @rOnlineMeetingId AND vEC.StatusId = 7 AND OMS.ScopeSourceTypeId = 95
			
		) as A ON A.OnlineMeetingId = OM.Id
	WHERE
		OM.Id = @rOnlineMeetingId
END






GO
/****** Object:  StoredProcedure [sEMeeting].[pOnlineMeetingSettingsGet]    Script Date: 10-01-2024 15:45:04 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[sEMeeting].[pOnlineMeetingSettingsGet]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [sEMeeting].[pOnlineMeetingSettingsGet] AS' 
END
GO

ALTER PROCEDURE [sEMeeting].[pOnlineMeetingSettingsGet]
		@rOnlineMeetingId bigint
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	BEGIN
		BEGIN TRY
			SELECT APIKey, APISecret, AccountEmailId, OAuthAccountId, OAuthClientId, OAuthClientSecret FROM [sEMeeting].[tOnlineMeetingSettings] WHERE @rOnlineMeetingId = OnlineMeetingId
		END TRY
		BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH
	END

GO
/****** Object:  StoredProcedure [sEMeeting].[pOnlineMeetingStatusTypeGet]    Script Date: 10-01-2024 15:45:04 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[sEMeeting].[pOnlineMeetingStatusTypeGet]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [sEMeeting].[pOnlineMeetingStatusTypeGet] AS' 
END
GO

 
ALTER PROCEDURE [sEMeeting].[pOnlineMeetingStatusTypeGet]
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	BEGIN
	BEGIN TRY
	SELECT 
	SM.Id,
	SM.Title 
	FROM sCommon.tStatusMaster SM 
	WHERE StatusTypeId = 113 ORDER BY Id
	END TRY
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
	END

GO
/****** Object:  StoredProcedure [sEMeeting].[pOnlineMeetingStudentGet]    Script Date: 10-01-2024 15:45:04 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[sEMeeting].[pOnlineMeetingStudentGet]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [sEMeeting].[pOnlineMeetingStudentGet] AS' 
END
GO

ALTER PROCEDURE [sEMeeting].[pOnlineMeetingStudentGet]
	@rDivisionId int,
	@rOrgId int

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

	BEGIN TRY

	BEGIN
		
		SELECT AcademicId as Id,(Code+' - '+CONVERT(NVARCHAR(10),RollNo)+' - '+Name) AS Title from sStudent.vStudentAcademic WHERE StatusId=1 AND DivisionId=@rDivisionId AND					OrgId=@rOrgId AND	IsActiveBatch=1 ORDER BY RollNo 
	END 
	END TRY
	BEGIN CATCH 
		SELECT -1 AS Result
	END CATCH	
		
END

GO
/****** Object:  StoredProcedure [sEMeeting].[pOnlineMeetingTeacherGet]    Script Date: 10-01-2024 15:45:04 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[sEMeeting].[pOnlineMeetingTeacherGet]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [sEMeeting].[pOnlineMeetingTeacherGet] AS' 
END
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
/****** Object:  StoredProcedure [sEMeeting].[pOnlineMeetingTeacherStudentListGet]    Script Date: 10-01-2024 15:45:04 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[sEMeeting].[pOnlineMeetingTeacherStudentListGet]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [sEMeeting].[pOnlineMeetingTeacherStudentListGet] AS' 
END
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=549 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.StartDate, OM.StartTime DESC
			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=549 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 desc;

		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=549 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.StartDate,OM.StartTime desc
				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=549 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.StartDate, OM.StartTime DESC
		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=2003
			
			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
/****** Object:  StoredProcedure [sEMeeting].[pOrderIndexMeetingTypeMasterGet]    Script Date: 10-01-2024 15:45:04 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[sEMeeting].[pOrderIndexMeetingTypeMasterGet]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [sEMeeting].[pOrderIndexMeetingTypeMasterGet] AS' 
END
GO

ALTER 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
/****** Object:  StoredProcedure [sEMeeting].[pOrgGroupIdGet]    Script Date: 10-01-2024 15:45:04 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[sEMeeting].[pOrgGroupIdGet]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [sEMeeting].[pOrgGroupIdGet] AS' 
END
GO

ALTER PROCEDURE [sEMeeting].[pOrgGroupIdGet]
		@rOrgId int
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	BEGIN
		BEGIN TRY
			SELECT OrgGroupId FROM sSetup.tOrganizationMaster WHERE Id = @rOrgId
		END TRY
		BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH
	END

GO
/****** Object:  StoredProcedure [sEMeeting].[pPermissionGet]    Script Date: 10-01-2024 15:45:04 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[sEMeeting].[pPermissionGet]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [sEMeeting].[pPermissionGet] AS' 
END
GO
-- exec sEMeeting.pPermissionGet 9911,9911000000270
ALTER PROCEDURE [sEMeeting].[pPermissionGet]
	@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 P.UserId = @rUserId 
	) 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
	--RoleId 
	
	--IN
	-- (SELECT RoleId FROM sSecurity.tUserRole WHERE IsObsolete = 0 AND UserId = @rUserId )
	) TP 
	GROUP BY TP.TaskId
	
	--SELECT	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 	(Permission & 1) AS C,
	--			(Permission & 2)/2 AS R,
	--			(Permission & 4)/4 AS U,
	--			(Permission & 8)/8 AS D,
	--			(Permission & 16)/16 AS S,
	--			(Permission & 32)/32 AS P,
	--			(Permission & 64)/64 AS X
	--	FROM sSecurity.tPermission
	--	WHERE TaskId = @rTaskId AND 
	--		  RoleId IN (SELECT RoleId FROM sSecurity.tUserRole WHERE IsObsolete = 0 AND UserId = @rUserId)
	--) TP
END


END

GO
/****** Object:  StoredProcedure [sEMeeting].[pScreenGet]    Script Date: 10-01-2024 15:45:04 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[sEMeeting].[pScreenGet]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [sEMeeting].[pScreenGet] AS' 
END
GO
-- exec sEMeeting.pScreenGet 
ALTER PROCEDURE [sEMeeting].[pScreenGet] 
	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 IN (253) OR S.Id = 31293
	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
/****** Object:  StoredProcedure [sEMeeting].[pSMSTemplateIdGet]    Script Date: 10-01-2024 15:45:04 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[sEMeeting].[pSMSTemplateIdGet]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [sEMeeting].[pSMSTemplateIdGet] AS' 
END
GO

ALTER PROCEDURE [sEMeeting].[pSMSTemplateIdGet]
		@rOrgId int,
		@rCustomEventId bigint
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	BEGIN
		BEGIN TRY
			SELECT SMSTemplateID FROM sAlert.tCustomTemplateMaster WHERE Id = @rCustomEventId AND OrgId = @rOrgId
		END TRY
		BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH
	END

GO
/****** Object:  StoredProcedure [sEMeeting].[pStudentProfileGet]    Script Date: 10-01-2024 15:45:04 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[sEMeeting].[pStudentProfileGet]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [sEMeeting].[pStudentProfileGet] AS' 
END
GO

ALTER PROCEDURE [sEMeeting].[pStudentProfileGet]
		@rAcademicId bigint,
		@rBatchId int
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	BEGIN
		BEGIN TRY
			SELECT A.OrgId, BatchId, StudentId, A.Id AS AcademicId, SM.Code, A.RollNo, (FirstName +' '+MiddleName+' '+LastName) AS StudentName,
                           SM.FirstName, SM.MiddleName, SM.LastName, A.ClassId, A.DivisionId, (CM.DisplayTitle + '-' + DM.DisplayTitle) AS ClassDivision,
                            DPM.Id AS DepartmentId, DPM.DisplayTitle AS DepartmentName, SM.SUID, B.Title as BatchName 
                            FROM sStudent.tAcademic A INNER JOIN sStudent.tStudentMaster SM ON A.StudentId=SM.Id
                            INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = A.DivisionId
                            INNER JOIN sSetup.tDepartmentMaster DPM ON DPM.Id = CM.DepartmentId
                            INNER JOIN sSetup.tBatchMaster B ON b.Id = A.BatchId 
                            WHERE A.Id= @rAcademicId  AND BatchId = @rBatchId
		END TRY
		BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH
	END

GO
/****** Object:  StoredProcedure [sEMeeting].[pUpdateMeetingDetails]    Script Date: 10-01-2024 15:45:04 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[sEMeeting].[pUpdateMeetingDetails]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [sEMeeting].[pUpdateMeetingDetails] AS' 
END
GO
ALTER PROCEDURE [sEMeeting].[pUpdateMeetingDetails]
	@rId bigint,
	@rType nvarchar(20)

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

	BEGIN TRY
 
	IF EXISTS (SELECT 1 from [sEMeeting].[tOnlineMeeting] where Id = @rId AND @rType IN ('Join', 'Start Again', 'Complete'))
	BEGIN
	IF (@rType = 'Join')
		UPDATE [sEMeeting].[tOnlineMeeting] SET IsMeetingStarted=1, StartDateTime = GetUtcDate() WHERE Id= @rId

	ELSE IF (@rType = 'Start Again')
		UPDATE [sEMeeting].[tOnlineMeeting] SET IsCompleted=549,IsMeetingStarted=1 WHERE Id= @rId	

	ELSE IF (@rType = 'Complete')
		UPDATE [sEMeeting].[tOnlineMeeting] SET IsCompleted=550,IsMeetingStarted=0,EndDateTime = GetUtcDate() WHERE Id= @rId

	SELECT 1 as Result
	END 
	ELSE
	BEGIN
		SELECT -101 as Result
	END
	END TRY

	BEGIN CATCH
	SELECT -1 as Result
	END CATCH

END


GO
/****** Object:  StoredProcedure [sEMeeting].[pUpdateOnlineMeetingAccountToken]    Script Date: 10-01-2024 15:45:04 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[sEMeeting].[pUpdateOnlineMeetingAccountToken]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [sEMeeting].[pUpdateOnlineMeetingAccountToken] AS' 
END
GO

ALTER PROCEDURE [sEMeeting].[pUpdateOnlineMeetingAccountToken]
	@rAccessToken nvarchar(max),
	@rOnlineMeetingAccountId bigint

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	BEGIN
		BEGIN TRY
			UPDATE sAcademic.tOnlineMeetingAccount SET JWTToken = @rAccessToken Where Id = @rOnlineMeetingAccountId AND MeetingProviderId = 1
			SELECT 11 as Result
		END TRY
		BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH
	END

GO
/****** Object:  StoredProcedure [sEMeeting].[pUpdateOnlineMeetingSettingsToken]    Script Date: 10-01-2024 15:45:04 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[sEMeeting].[pUpdateOnlineMeetingSettingsToken]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [sEMeeting].[pUpdateOnlineMeetingSettingsToken] AS' 
END
GO

ALTER PROCEDURE [sEMeeting].[pUpdateOnlineMeetingSettingsToken]
	@rAccessToken nvarchar(max),
	@rOnlineMeetingIds nvarchar(max)

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	BEGIN
		BEGIN TRY
			UPDATE sEMeeting.tOnlineMeetingSettings SET JWTToken = @rAccessToken WHERE OnlineMeetingId IN (SELECT CAST(Nodes.node.value('.', 'BIGINT') AS INT) AS id
			FROM (
			SELECT CAST('<x>' + REPLACE(@rOnlineMeetingIds, ',', '</x><x>') + '</x>' AS XML) AS xmlcol
			) AS t
			CROSS APPLY xmlcol.nodes('/x') AS Nodes(node))
		SELECT 11 as Result
		END TRY
		BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH
	END

GO
/****** Object:  StoredProcedure [sEMeeting].[pValidateOnlineMeetingAccount]    Script Date: 10-01-2024 15:45:04 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[sEMeeting].[pValidateOnlineMeetingAccount]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [sEMeeting].[pValidateOnlineMeetingAccount] AS' 
END
GO


ALTER PROCEDURE [sEMeeting].[pValidateOnlineMeetingAccount]
@rId bigint = 0,
@rStartDate nvarchar(50),
@rStartTime nvarchar(50),
@rEndDate nvarchar(50),
@rEndTime nvarchar(50),
@rMeetingAccountId int = 0

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	BEGIN
		BEGIN TRY
		if(@rId = 0)
		BEGIN
			SELECT 1 
			FROM sEMeeting.tOnlineMeeting 
			WHERE (((StartDate <= @rStartDate) 
			AND (EndDate >= @rEndDate)) 
			OR ((StartDate >= @rStartDate) 
			AND (EndDate <= @rEndDate)))
            AND (((StartTime <= @rStartTime) 
			AND (EndTime >= @rEndTime)) 
			OR ((StartTime <=  @rStartTime) 
			AND (EndTime >= @rEndTime))) 
			AND MeetingAccountId = @rMeetingAccountId
		END
		ELSE
		BEGIN
			SELECT 1 
			FROM sEMeeting.tOnlineMeeting OM
			WHERE (((StartDate <= @rStartDate) 
			AND (EndDate >= @rEndDate)) 
			OR ((StartDate >= @rStartDate) 
			AND (EndDate <= @rEndDate)))
            AND (((StartTime <= @rStartTime) 
			AND (EndTime >= @rEndTime)) 
			OR ((StartTime <= @rEndTime) 
			AND (EndTime >= @rStartTime))) 
			AND @rId = OM.Id
			AND MeetingAccountId = @rMeetingAccountId
		END
		END TRY
		BEGIN CATCH
		SELECT -101 AS Result
		END CATCH
	END

GO
/****** Object:  StoredProcedure [sEMeeting].[pValidateOnlineMeetingTeacher]    Script Date: 10-01-2024 15:45:04 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[sEMeeting].[pValidateOnlineMeetingTeacher]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [sEMeeting].[pValidateOnlineMeetingTeacher] AS' 
END
GO

ALTER PROCEDURE [sEMeeting].[pValidateOnlineMeetingTeacher]
@rOnlineMeetingId bigint = 0,
@rId bigint = 0,
@rStartDate nvarchar(50),
@rStartTime nvarchar(50),
@rEndDate nvarchar(50),
@rEndTime nvarchar(50),
@rMeetingAccountId int = 0

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	BEGIN
		BEGIN TRY
		BEGIN
		if(@rOnlineMeetingId = 0)
		BEGIN
			SELECT 1 
			FROM sEMeeting.tOnlineMeeting OM
			WHERE HostEmployeeId = @rId
        AND (
            (@rStartDate BETWEEN StartDate AND EndDate OR @rEndDate BETWEEN StartDate AND EndDate)
            OR
            (StartDate BETWEEN @rStartDate AND @rEndDate OR EndDate BETWEEN @rStartDate AND @rEndDate)
        )
        AND (
            (@rStartTime BETWEEN StartTime AND EndTime OR @rEndTime BETWEEN StartTime AND EndTime)
            OR
            (StartTime BETWEEN @rStartTime AND @rEndTime OR EndTime BETWEEN @rStartTime AND @rEndTime)
        )
		AND OM.IsCompleted <> 551
		END
		ELSE
		BEGIN
		SELECT 1 
			FROM sEMeeting.tOnlineMeeting OM
			WHERE HostEmployeeId = @rId
        AND (
            (@rStartDate BETWEEN StartDate AND EndDate OR @rEndDate BETWEEN StartDate AND EndDate)
            OR
            (StartDate BETWEEN @rStartDate AND @rEndDate OR EndDate BETWEEN @rStartDate AND @rEndDate)
        )
        AND (
            (@rStartTime BETWEEN StartTime AND EndTime OR @rEndTime BETWEEN StartTime AND EndTime)
            OR
            (StartTime BETWEEN @rStartTime AND @rEndTime OR EndTime BETWEEN @rStartTime AND @rEndTime)
        ) AND @rOnlineMeetingId <> OM.Id
		END
		END
		END TRY
		BEGIN CATCH
		SELECT -101 AS Result
		END CATCH
	END


GO
/****** Object:  StoredProcedure [sEMeeting].[pWhatsAppTemplateGet]    Script Date: 10-01-2024 15:45:04 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[sEMeeting].[pWhatsAppTemplateGet]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [sEMeeting].[pWhatsAppTemplateGet] AS' 
END
GO

ALTER PROCEDURE [sEMeeting].[pWhatsAppTemplateGet]
		@rEventId int,
		@rOrgId int
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	BEGIN
		BEGIN TRY	
			SELECT Template,WhatsAppTemplate,WhatsAppTemplateLanguage FROM sAlert.tEventTemplate WHERE EventId = @rEventId AND OrgId = @rOrgId AND AlertModeId = 4
		END TRY
		BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH
	END

GO
