PRINT N'Dropping Procedure [sPurchase].[pDependentFunctionlityGet]...';


GO
DROP PROCEDURE [sPurchase].[pDependentFunctionlityGet];


GO
PRINT N'Creating Table [sEMeeting].[tTempOnlineMeetingScope]...';


GO
CREATE TABLE [sEMeeting].[tTempOnlineMeetingScope] (
    [TempOnlineMeetingId] NVARCHAR (100) NOT NULL,
    [SourceTypeId]        SMALLINT       NOT NULL,
    [SourceId]            BIGINT         NOT NULL,
    [AssigneeToId]        TINYINT        NULL
);

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,
		@rTempOnlineMeetingId nvarchar(100) = '',
		@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(@rTempOnlineMeetingId <> NULL OR @rTempOnlineMeetingId <> '')
	BEGIN
	DELETE FROM [sEMeeting].[tTempOnlineMeetingScope] WHERE TempOnlineMeetingId = @rTempOnlineMeetingId
	END
	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].[pOnlineMeetingEmployeeGet]...';


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 ,
	Code
	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
PRINT N'Altering Procedure [sEMeeting].[pOnlineMeetingTeacherGet]...';


GO

ALTER PROCEDURE [sEMeeting].[pOnlineMeetingTeacherGet]
	 
	 @rSourceId bigint,
	 @rSourceTypeId int,
	 @rOrgGroupId int,
	 @rOrgId int,
	 @rUserId bigint,
	 @rIsOnlineMeetingAdmin bit
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
BEGIN
	BEGIN TRY
	If (@rSourceTypeId = 2003)
		BEGIN
		 SELECT DISTINCT EM.Id ,ISNULL(EM.FirstName,'') +' ' + ISNULL(EM.MiddleName,'') +' ' + ISNULL(EM.LastName ,'') As Title FROM [sHrm].[tEmployeeMaster] EM
		  INNER	JOIN [sEMeeting].[tOnlineMeeting] OM ON OM.HostEmployeeId=EM.Id
		END
	else if(@rOrgId = 0)
	 BEGIN
		If (@rSourceTypeId = 95)
		BEGIN
			If(@rIsOnlineMeetingAdmin = 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.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 Title
			END
		END
		else
		BEGIN
			SELECT EM.EmployeeId as Id, [sHrm].[fEmployeeNameGet](EM.FirstName , EM.MiddleName, EM.LastName,ISNULL(OrgM.EmployeeNameFormatId,1)) AS Title FROM sHrm.vExtEmployee EM 
			INNER JOIN sSetup.vUserOrganization OM ON OM.Id = EM.OrgId INNER JOIN sSetup.tOrganizationMaster OrgM ON OrgM.Id = EM.OrgId 
            WHERE ISNULL(EM.IsOtherUser,0) = 0 AND  EM.StatusId =7  AND EM.EmployeeGroupId = 1 AND OM.OrgGroupId = @rOrgGroupId AND OM.UserId = @rUserId 
			ORDER BY Title
		END
	 END
	else
		BEGIN
		If (@rSourceTypeId = 95)
		BEGIN
		if(@rIsOnlineMeetingAdmin = 1)
			BEGIN
				SELECT EM.EmployeeId as Id, [sHrm].[fEmployeeNameGet](EM.FirstName , EM.MiddleName, EM.LastName,ISNULL(OM.EmployeeNameFormatId,1)) AS Title FROM sHrm.vExtEmployee EM				INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = EM.OrgId WHERE ISNULL(IsOtherUser,0) = 0 AND  StatusId =7  AND EmployeeGroupId = 1 
				AND OM.OrgGroupId =	@rOrgGroupId AND OM.Id = @rOrgId ORDER BY Title	
			END
		else
			BEGIN
			SELECT EM.EmployeeId as Id, [sHrm].[fEmployeeNameGet](EM.FirstName , EM.MiddleName, EM.LastName,ISNULL(OM.EmployeeNameFormatId,1)) AS Title FROM sHrm.vExtEmployee EM				INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=EM.OrgId WHERE ISNULL(EM.IsOtherUser,0) = 0 AND  EM.StatusId =7  AND EM.EmployeeGroupId = 1
			AND EM.EmployeeId =	@rSourceId	ORDER BY Title
			END
		END
		else
		BEGIN
			SELECT EM.EmployeeId as Id, [sHrm].[fEmployeeNameGet](EM.FirstName , EM.MiddleName, EM.LastName,ISNULL(OrgM.EmployeeNameFormatId,1)) AS Title FROM sHrm.vExtEmployee EM				INNER JOIN sSetup.vUserOrganization OM ON OM.Id = EM.OrgId INNER JOIN sSetup.tOrganizationMaster OrgM ON OrgM.Id = EM.OrgId 
			WHERE ISNULL(EM.IsOtherUser,0) = 0 AND  EM.StatusId =7  AND EM.EmployeeGroupId = 1 AND OM.OrgGroupId = @rOrgGroupId AND OM.UserId = @rUserId AND OM.Id = @rOrgId 
			ORDER BY Title
		END
		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,
	 @rEmployeeId bigint = 0
		 
	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))
				AND (OM.HostEmployeeId = @rEmployeeId OR @rEmployeeId = 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 [sPurchase].[pAttachmentLogAdd]...';


GO

ALTER PROCEDURE [sPurchase].[pAttachmentLogAdd]
		@rMessageId NVARCHAR(MAX),
		@rAttachment NVARCHAR(MAX)
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	BEGIN
	    BEGIN TRANSACTION
		BEGIN TRY	
			INSERT INTO sAlert.tAlertAttachmentLog VALUES (@rMessageId, @rAttachment)
	    COMMIT TRANSACTION
		END TRY
		BEGIN CATCH 
		    ROLLBACK TRANSACTION
			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].[pDependentConfigurationGet]...';


GO


ALTER PROCEDURE [sPurchase].[pDependentConfigurationGet]
	  @rOrgId BIGINT,
	  @rOrgGroupId INT,
	  @rUserId BIGINT,
	  @rScreenId INT
AS
SET NOCOUNT ON

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

	BEGIN CATCH
    IF @@TRANCOUNT > 0
    ROLLBACK TRANSACTION
    
    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].[pGetGRNReport]...';


GO

-- exec [sPurchase].[pGetGRNReport] 991100001
ALTER PROCEDURE [sPurchase].[pGetGRNReport]
      @rGoodsReceivedNoteId INT,
	  @rUserId BIGINT,
	  @rOrgGroupId INT
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
	DECLARE @rStoreLocationId BIGINT
    SELECT @rStoreLocationId = ISNULL(ItemValue,0)
	FROM sConfig.tConfigurationSetup 
	WHERE ConfigurationId  = 542 AND SourceId = @rUserId

	DECLARE @HTMLTable NVARCHAR(MAX);
	DECLARE
	@rGRNNumber AS NVARCHAR(20),
	@rPurchaseRequestNumber AS NVARCHAR(20),
	@rPurchaseOrderNumber AS NVARCHAR(20),
	@rRequestedBy AS NVARCHAR(100),
	@rPODueDate AS NVARCHAR(100),
	@rStatus AS NVARCHAR(100),
	@rVendorName AS NVARCHAR(300),
	@rBillToAddress AS NVARCHAR(1000)
	
	    SELECT @rGRNNumber = ISNULL(GRN.GRNNumber,''),
				@rPurchaseRequestNumber = ISNULL(PR.Number,''),
				@rPurchaseOrderNumber = ISNULL(PO.RefNumber,''),
				@rRequestedBy = ISNULL(GRN.RequestedBy,''),
				@rPODueDate = ISNULL(GRN.PODueDate,''),
				@rStatus = ISNULL(SM.Title,''),
				@rVendorName = ISNULL(VM.Title,''),
				@rBillToAddress = ISNULL(GRN.BillToAddress,'')
		FROM  [sPurchase].[tGoodsReceivedNote] GRN(NOLOCK) 
			   LEFT JOIN sProcurement.tVendorMaster  VM ON GRN.VendorId = VM.ID AND VM.LocationId = @rStoreLocationId AND VM.OrgGroupId = @rOrgGroupId AND VM.IsObsolete = 0 
			   LEFT JOIN [sWf].[tWfStatusMaster] SM ON SM.Id = GRN.StatusId
			   LEFT JOIN [sPurchase].[tPurchaseRequest] PR ON PR.ID = GRN.PurchaseRequestId AND PR.LocationId = @rStoreLocationId AND PR.OrgGroupId = @rOrgGroupId AND PR.IsObsolete = 0 
			   LEFT JOIN [sPurchase].[tPurchaseOrder] PO ON PO.Id = GRN.PurchaseOrderId AND PO.LocationId = @rStoreLocationId AND PO.OrgGroupId = @rOrgGroupId AND PO.IsObsolete = 0 
		WHERE  GRN.Id = @rGoodsReceivedNoteId AND GRN.IsObsolete = 0
               AND GRN.LocationId = @rStoreLocationId
			   AND GRN.OrgGroupId = @rOrgGroupId


    SET @HTMLTable = '';
	IF EXISTS (SELECT * FROM [sPurchase].[tGoodsReceivedNoteDetail] GRND
			WHERE  GRND.GoodsReceivedNoteId = @rGoodsReceivedNoteId)
    BEGIN
    SET @HTMLTable = @HTMLTable + '<tr>';
    SET @HTMLTable = @HTMLTable + '<th>StockItemCode</th>';
    SET @HTMLTable = @HTMLTable + '<th>StockItemName</th>';
    SET @HTMLTable = @HTMLTable + '<th>Uom</th>';
    SET @HTMLTable = @HTMLTable + '<th>POQty</th>';
	SET @HTMLTable = @HTMLTable + '<th>ReceivedQty</th>';
	SET @HTMLTable = @HTMLTable + '<th>PreviousGRNQty</th>';
	SET @HTMLTable = @HTMLTable + '<th>UnitPrice</th>';
    SET @HTMLTable = @HTMLTable + '</tr>';

	SELECT @HTMLTable = @HTMLTable+'<tr><td>'+ISNULL(CAST(SIM.Code AS NVARCHAR(100)),'')+'</td><td>'
+ISNULL(SIM.Title,'')+'</td><td>'+ISNULL(SUMa.Code,'')+'</td><td>'+ISNULL(CAST(GRND.POQty AS NVARCHAR(20)),'')+'</td><td>'+ISNULL(CAST(GRND.ReceivedQty AS NVARCHAR(20)),'')+'</td><td>'+ISNULL(CAST(GRND.PreviousGRNQty AS NVARCHAR(20)),'')+'</td><td>'+ISNULL(CAST(GRND.UnitPrice AS NVARCHAR(20)),'')+'</td></tr>'
	    FROM   [sPurchase].[tGoodsReceivedNoteDetail] GRND (NOLOCK)
		       INNER JOIN  sPurchase.tGoodsReceivedNote GRN ON GRN.Id = GRND.GoodsReceivedNoteId AND GRN.LocationId = @rStoreLocationId AND GRN.OrgGroupId = @rOrgGroupId AND GRN.IsObsolete = 0 
			   INNER JOIN  sPurchase.tPurchaseOrder PO	ON PO.Id = GRN.PurchaseOrderId AND PO.LocationId = @rStoreLocationId AND PO.OrgGroupId = @rOrgGroupId AND PO.IsObsolete = 0 
			   INNER JOIN  sIp.tStockItemMaster SIM	ON SIM.Id = GRND.StockItemId AND SIM.StoreLocationId = @rStoreLocationId AND SIM.OrgGroupId = @rOrgGroupId AND SIM.IsObsolete = 0 
			   INNER JOIN  sFinanceCommon.tStockUomMaster SUMa ON SUMa.Id = SIM.IssueStockUomId
		WHERE  GRND.GoodsReceivedNoteId = @rGoodsReceivedNoteId AND GRN.IsObsolete = 0
		       AND GRN.LocationId = @rStoreLocationId
			   AND GRN.OrgGroupId = @rOrgGroupId
    END

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

		AS Template FROM sPurchase.tPurchaseReportTemplateMaster WHERE Code='GRN' AND IsObsolete = 0

	END TRY

	BEGIN CATCH
    IF @@TRANCOUNT > 0
    ROLLBACK TRANSACTION 

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


GO

-- exec [sPurchase].[pGetIGReport] 991100001
ALTER PROCEDURE [sPurchase].[pGetIGReport]
      @rInvoiceGenerateId INT,
	  @rUserId BIGINT,
	  @rOrgGroupId INT
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
	DECLARE @rStoreLocationId BIGINT
    SELECT @rStoreLocationId = ISNULL(ItemValue,0)
	FROM sConfig.tConfigurationSetup 
	WHERE ConfigurationId  = 542 AND SourceId = @rUserId

	DECLARE @HTMLTable NVARCHAR(MAX);
	DECLARE
	@rINVNumber AS NVARCHAR(20),
	@rGRNNumber AS NVARCHAR(20),
	@rRequestedBy AS NVARCHAR(100),
	@rStatus AS NVARCHAR(100),
	@rInvoiceDate AS NVARCHAR(100),
	@rInvoiceDueDate AS NVARCHAR(100),
	@rBillToAddress AS NVARCHAR(1000),
	@rShipToAddress AS NVARCHAR(1000),
	@rRemarks AS NVARCHAR(500),
	@rVendorCode AS NVARCHAR(100),
	@rVendorName AS NVARCHAR(300)
	
	    SELECT  @rINVNumber = ISNULL(IG.INVNumber,''),
		        @rGRNNumber = ISNULL(GRN.GRNNumber,''),
				@rRequestedBy = ISNULL(IG.RequestedBy,''),
				@rStatus = ISNULL(SM.Title,''),
				@rInvoiceDate = ISNULL(IG.InvoiceDate,''),
		        @rInvoiceDueDate = ISNULL(IG.InvoiceDueDate,''),
				@rBillToAddress = ISNULL(IG.BillToAddress,''),
				@rShipToAddress = ISNULL(IG.ShipToAddress,''),
		        @rRemarks = ISNULL(IG.Remarks,''),
				@rVendorCode = ISNULL(VM.Code,''),
				@rVendorName = ISNULL(VM.Title,'')
		FROM   [sPurchase].[tInvoiceGenerate] IG(NOLOCK)
		       LEFT JOIN sProcurement.tVendorMaster  VM ON IG.VendorId = VM.ID AND VM.LocationId = @rStoreLocationId AND VM.OrgGroupId = @rOrgGroupId AND VM.IsObsolete = 0
			   LEFT JOIN [sWf].[tWfStatusMaster] SM ON SM.Id = IG.StatusId
			   LEFT JOIN [sPurchase].[tGoodsReceivedNote] GRN ON GRN.Id = IG.GoodsReceivedNoteId AND GRN.LocationId = @rStoreLocationId AND GRN.OrgGroupId = @rOrgGroupId AND GRN.IsObsolete = 0
		WHERE  IG.Id = @rInvoiceGenerateId AND IG.IsObsolete = 0
		       AND IG.LocationId = @rStoreLocationId
			   AND IG.OrgGroupId = @rOrgGroupId

    SET @HTMLTable = '';
	IF EXISTS(SELECT * FROM [sPurchase].[tInvoiceGenerateDetail] IGD
			WHERE  IGD.InvoiceGenerateId = @rInvoiceGenerateId)

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

	SELECT @HTMLTable = @HTMLTable+'<tr><td>'+ISNULL(CAST(SIM.Code AS NVARCHAR(100)),'')+'</td><td>'
+ISNULL(SIM.Title,'')+'</td><td>'+ISNULL(SUMa.Code,'')+'</td><td>'+ISNULL(CAST(IGD.POQty AS NVARCHAR(100)),'')+'</td><td>'+ISNULL(CAST(IGD.ReceivedQty AS NVARCHAR(20)),'')+'</td><td>'+ISNULL(CAST(IGD.AcceptedQty AS NVARCHAR(20)),'')+'</td><td>'+ISNULL(CAST(IGD.RejectedQty AS NVARCHAR(20)),'')+'</td><td>'+ISNULL(CAST(IGD.ReasonForRejection AS NVARCHAR(300)),'')+'</td></tr>'
	    FROM   [sPurchase].[tInvoiceGenerateDetail] IGD(NOLOCK)
		       INNER JOIN  [sPurchase].[tInvoiceGenerate] IG ON IG.Id = IGD.InvoiceGenerateId AND IG.LocationId = @rStoreLocationId AND IG.OrgGroupId = @rOrgGroupId AND IG.IsObsolete = 0
			   INNER JOIN	sIp.tStockItemMaster SIM	ON SIM.Id = IGD.StockItemId AND SIM.StoreLocationId = @rStoreLocationId AND SIM.OrgGroupId = @rOrgGroupId AND SIM.IsObsolete = 0 
			   INNER JOIN  sFinanceCommon.tStockUomMaster SUMa ON SUMa.Id = SIM.IssueStockUomId
		WHERE  IGD.InvoiceGenerateId = @rInvoiceGenerateId AND IG.IsObsolete = 0
		       AND IG.LocationId = @rStoreLocationId
			   AND IG.OrgGroupId = @rOrgGroupId
 
    END

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

		AS Template FROM sPurchase.tPurchaseReportTemplateMaster WHERE Code='IG' AND IsObsolete = 0

	END TRY

	BEGIN CATCH
    IF @@TRANCOUNT > 0
    ROLLBACK TRANSACTION 

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


GO

-- exec [sPurchase].[pGetQCReport] 991100001
ALTER PROCEDURE [sPurchase].[pGetQCReport]
      @rQualityCheckId INT,
	  @rUserId BIGINT,
	  @rOrgGroupId INT
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
	DECLARE @rStoreLocationId BIGINT
    SELECT @rStoreLocationId = ISNULL(ItemValue,0)
	FROM sConfig.tConfigurationSetup 
	WHERE ConfigurationId  = 542 AND SourceId = @rUserId

	DECLARE @HTMLTable NVARCHAR(MAX);

    
	DECLARE
	@rQCNumber AS NVARCHAR(100),
	@rGRNNumber AS NVARCHAR(100),
	@rRequestedBy AS NVARCHAR(100),
	@rStatus AS NVARCHAR(100),
	@rQualityCheckDetails AS NVARCHAR(100)
	
	    SELECT  @rQCNumber = ISNULL(QC.QCNumber,''),
		        @rGRNNumber = ISNULL(GRN.GRNNumber,''),
				@rRequestedBy = ISNULL(QC.RequestedBy,''),
				@rStatus = ISNULL(SM.Title,'')
		FROM   [sPurchase].[tQualityCheck] QC(NOLOCK)
			   LEFT JOIN [sWf].[tWfStatusMaster] SM ON SM.Id = QC.StatusId
			   LEFT JOIN [sPurchase].[tGoodsReceivedNote] GRN ON GRN.Id = QC.GoodsReceivedNoteId AND GRN.LocationId = @rStoreLocationId AND GRN.OrgGroupId = @rOrgGroupId AND GRN.IsObsolete = 0
		WHERE  QC.Id = @rQualityCheckId AND QC.IsObsolete = 0
		       AND QC.LocationId = @rStoreLocationId
			   AND QC.OrgGroupId = @rOrgGroupId


    SET @HTMLTable = '';
	IF EXISTS(SELECT *  FROM [sPurchase].[tQualityCheckDetail] QCD
			WHERE QCD.QualityCheckId = @rQualityCheckId)
	BEGIN
    SET @HTMLTable = @HTMLTable + '<tr>';
    SET @HTMLTable = @HTMLTable + '<th>StockItemCode</th>';
    SET @HTMLTable = @HTMLTable + '<th>StockItemName</th>';
    SET @HTMLTable = @HTMLTable + '<th>Uom</th>';
    SET @HTMLTable = @HTMLTable + '<th>POQty</th>';
	SET @HTMLTable = @HTMLTable + '<th>ReceivedQty</th>';
	SET @HTMLTable = @HTMLTable + '<th>AcceptedQty</th>';
	SET @HTMLTable = @HTMLTable + '<th>RejectedQty</th>';
	SET @HTMLTable = @HTMLTable + '<th>ReasonForRejection</th>';
    SET @HTMLTable = @HTMLTable + '</tr>';

	SELECT @HTMLTable = @HTMLTable+'<tr><td>'+ISNULL(CAST(SIM.Code AS NVARCHAR(100)),'')+'</td><td>'
+ISNULL(SIM.Title,'')+'</td><td>'+ISNULL(SUMa.Code,'')+'</td><td>'+ISNULL(CAST(QCD.POQty AS NVARCHAR(100)),'')+'</td><td>'+ISNULL(CAST(QCD.ReceivedQty AS NVARCHAR(100)),'')+'</td><td>'+ISNULL(CAST(QCD.AcceptedQty AS NVARCHAR(100)),'')+'</td><td>'+ISNULL(CAST(QCD.RejectedQty AS NVARCHAR(100)),'')+'</td><td>'+ISNULL(CAST(QCD.ReasonForRejection AS NVARCHAR(100)),'')+'</td></tr>'
	    FROM   [sPurchase].[tQualityCheckDetail] QCD (NOLOCK)
		       INNER JOIN  [sPurchase].[tQualityCheck] QC ON QC.Id = QCD.QualityCheckId AND QC.LocationId = @rStoreLocationId AND QC.OrgGroupId = @rOrgGroupId AND QC.IsObsolete = 0
			   INNER JOIN	sIp.tStockItemMaster SIM	ON SIM.Id = QCD.StockItemId AND SIM.StoreLocationId = @rStoreLocationId AND SIM.OrgGroupId = @rOrgGroupId AND SIM.IsObsolete = 0             
			   INNER JOIN  sFinanceCommon.tStockUomMaster SUMa ON SUMa.Id = SIM.IssueStockUomId
		WHERE  QCD.QualityCheckId = @rQualityCheckId AND QC.IsObsolete = 0
		       AND QC.LocationId = @rStoreLocationId
			   AND QC.OrgGroupId = @rOrgGroupId
    END

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

		AS Template FROM sPurchase.tPurchaseReportTemplateMaster WHERE Code='QC' AND IsObsolete = 0

	END TRY

	BEGIN CATCH
    IF @@TRANCOUNT > 0
    ROLLBACK TRANSACTION 

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


GO

-- exec [sPurchase].[pGetQRReport] 991100004
ALTER PROCEDURE [sPurchase].[pGetQRReport]
      @rQuotationRequestId INT,
	  @rUserId BIGINT,
	  @rOrgGroupId INT
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
	DECLARE @rStoreLocationId BIGINT
    SELECT @rStoreLocationId = ISNULL(ItemValue,0)
	FROM sConfig.tConfigurationSetup 
	WHERE ConfigurationId  = 542 AND SourceId = @rUserId

	DECLARE @HTMLTable NVARCHAR(MAX);

	DECLARE
	@rNumber AS NVARCHAR(20),
	@rName AS NVARCHAR(100),
	@rRFQDate AS NVARCHAR(100),
	@rStatus AS NVARCHAR(100),
	@rDescription AS NVARCHAR(300),
	@rStartDate AS NVARCHAR(100),
	@rEndDate AS NVARCHAR(100),
	@rBidOpen AS NVARCHAR(50),
	@rBidClose AS NVARCHAR(50),
	@rPersonContact AS NVARCHAR(50),
	@rEmail AS NVARCHAR(50),
	@rSendToVendor AS NVARCHAR(10),
	@rVendorCode AS NVARCHAR(100),
	@rVendorName AS NVARCHAR(300),
	@rPurchaseNumber AS NVARCHAR(20)
	
	    SELECT  @rNumber = ISNULL(QR.Number,''),
		        @rName = ISNULL(QR.Name,''),
				@rRFQDate = ISNULL(QR.RFQDate,''),
				@rStatus = ISNULL(SM.Title,''),
				@rDescription = ISNULL(QR.Description,''),
		        @rStartDate = ISNULL(QR.StartDate,''),
				@rEndDate = ISNULL(QR.EndDate,''),
				@rBidOpen = ISNULL(QR.BidOpen,''),
		        @rBidClose = ISNULL(QR.BidClose,''),
				@rPersonContact = ISNULL(QR.PersonContact,''),
				@rEmail = ISNULL(QR.Email,''),
		        @rSendToVendor = ISNULL(QR.SendToVendor,''),
				@rVendorCode = ISNULL(VM.Code,''),
				@rVendorName = ISNULL(VM.Title,''),
				@rPurchaseNumber = ISNULL(PR.Number,'')
		FROM   [sPurchase].[tQuotationRequest] QR(NOLOCK)
		       LEFT JOIN sProcurement.tVendorMaster  VM ON QR.VendorId = VM.ID AND VM.LocationId = @rStoreLocationId AND VM.OrgGroupId = @rOrgGroupId AND VM.IsObsolete = 0
			   LEFT JOIN [sWf].[tWfStatusMaster] SM ON SM.Id = QR.StatusId
			   LEFT JOIN [sPurchase].[tPurchaseRequest] PR ON PR.Id = QR.PurchaseRequestId AND PR.LocationId = @rStoreLocationId AND PR.OrgGroupId = @rOrgGroupId AND PR.IsObsolete = 0
		WHERE  QR.Id = @rQuotationRequestId AND QR.IsObsolete = 0
		       AND QR.LocationId = @rStoreLocationId
			   AND QR.OrgGroupId = @rOrgGroupId


    SET @HTMLTable = '';

	IF EXISTS(SELECT * FROM  [sPurchase].[tQuotationRequestDetail] QRD
			WHERE  QRD.QuotationRequestId = @rQuotationRequestId)
	BEGIN
		SET @HTMLTable = @HTMLTable + '<tr>';
		SET @HTMLTable = @HTMLTable + '<th>StockItemCode</th>';
		SET @HTMLTable = @HTMLTable + '<th>StockItemName</th>';
		SET @HTMLTable = @HTMLTable + '<th>Uom</th>';
		SET @HTMLTable = @HTMLTable + '<th>RequestedQty</th>';
		SET @HTMLTable = @HTMLTable + '<th>TargetPrice</th>';
		SET @HTMLTable = @HTMLTable + '<th>Remark</th>';
		SET @HTMLTable = @HTMLTable + '</tr>';

		SELECT @HTMLTable = @HTMLTable+'<tr><td>'+ISNULL(CAST(SIM.Code AS NVARCHAR(100)),'')+'</td><td>'
	+ISNULL(SIM.Title,'')+'</td><td>'+ISNULL(SUMa.Code,'')+'</td><td>'+ISNULL(CAST(QRD.RequestedQty AS NVARCHAR(20)),'')+'</td><td>'+ISNULL(CAST(QRD.TargetPrice AS NVARCHAR(20)),'')+'</td><td>'+ISNULL(CAST(QRD.Remark AS NVARCHAR(300)),'')+'</td></tr>'
			FROM   [sPurchase].[tQuotationRequestDetail] QRD(NOLOCK)
			       INNER JOIN [sPurchase].[tQuotationRequest] QR ON QR.Id = QRD.QuotationRequestId AND QR.LocationId = @rStoreLocationId AND QR.OrgGroupId = @rOrgGroupId AND QR.IsObsolete = 0
				   INNER JOIN	sIp.tStockItemMaster SIM	ON SIM.Id = QRD.StockItemId AND SIM.StoreLocationId = @rStoreLocationId AND SIM.OrgGroupId = @rOrgGroupId AND SIM.IsObsolete = 0 
				   INNER JOIN  sFinanceCommon.tStockUomMaster SUMa ON SUMa.Id = SIM.IssueStockUomId
			WHERE  QRD.QuotationRequestId = @rQuotationRequestId AND QR.IsObsolete = 0
			       AND QR.LocationId = @rStoreLocationId
			       AND QR.OrgGroupId = @rOrgGroupId
	END
 

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

		AS Template FROM sPurchase.tPurchaseReportTemplateMaster WHERE Code='QR' AND IsObsolete = 0

	END TRY

	BEGIN CATCH
    IF @@TRANCOUNT > 0
    ROLLBACK TRANSACTION 

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


GO
-- select * from sPurchase.tPurchaseReportTemplate where id=6
-- exec [sPurchase].[pGetSRReport] 991100001
ALTER PROCEDURE [sPurchase].[pGetSRReport]
      @rSalesReturnId INT,
	  @rUserId BIGINT,
	  @rOrgGroupId INT
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
	DECLARE @rStoreLocationId BIGINT
    SELECT @rStoreLocationId = ISNULL(ItemValue,0)
	FROM sConfig.tConfigurationSetup 
	WHERE ConfigurationId  = 542 AND SourceId = @rUserId

	DECLARE @HTMLTable NVARCHAR(MAX);

    
	DECLARE
	@rSRNumber AS NVARCHAR(20),
	@rGRNNumber AS NVARCHAR(20),
	@rRequestedBy AS NVARCHAR(100),
	@rStatus AS NVARCHAR(100),
	@rVendorName AS NVARCHAR(300),
	@rPurchaseOrderNumber AS NVARCHAR(20)
	
	    SELECT  @rSRNumber = ISNULL(SR.SRNumber,''),
		        @rGRNNumber = ISNULL(GRN.GRNNumber,''),
				@rRequestedBy = ISNULL(SR.RequestedBy,''),
				@rStatus = ISNULL(SM.Title,''),
				@rVendorName = ISNULL(VM.Title,''),
				@rPurchaseOrderNumber = ISNULL(PO.RefNumber,'')
		FROM   [sPurchase].[tSalesReturn] SR(NOLOCK)
		       LEFT JOIN sProcurement.tVendorMaster  VM ON SR.VendorId = VM.ID AND VM.LocationId = @rStoreLocationId AND VM.OrgGroupId = @rOrgGroupId AND VM.IsObsolete = 0
			   LEFT JOIN [sWf].[tWfStatusMaster] SM ON SM.Id = SR.StatusId
			   LEFT JOIN [sPurchase].[tGoodsReceivedNote] GRN ON GRN.Id = SR.GoodsReceivedNoteId AND GRN.LocationId = @rStoreLocationId AND GRN.OrgGroupId = @rOrgGroupId AND GRN.IsObsolete = 0
			   LEFT JOIN [sPurchase].[tPurchaseOrder] PO ON PO.Id = SR.PurchaseOrderId AND PO.LocationId = @rStoreLocationId AND PO.OrgGroupId = @rOrgGroupId AND PO.IsObsolete = 0
		WHERE  SR.Id = @rSalesReturnId  AND SR.LocationId = @rStoreLocationId AND SR.OrgGroupId = @rOrgGroupId AND SR.IsObsolete = 0


    SET @HTMLTable = '';
	IF EXISTS(SELECT *  FROM   [sPurchase].[tSalesReturnDetail] SRD
			WHERE  SRD.SalesReturnId = @rSalesReturnId)
    BEGIN
    SET @HTMLTable = @HTMLTable + '<tr>';
    SET @HTMLTable = @HTMLTable + '<th>StockItemCode</th>';
    SET @HTMLTable = @HTMLTable + '<th>StockItemName</th>';
    SET @HTMLTable = @HTMLTable + '<th>Uom</th>';
    SET @HTMLTable = @HTMLTable + '<th>POQty</th>';
	SET @HTMLTable = @HTMLTable + '<th>ReceivedQty</th>';
	SET @HTMLTable = @HTMLTable + '<th>RejectedQty</th>';
	SET @HTMLTable = @HTMLTable + '<th>CreditNoteIssueDate</th>';
	SET @HTMLTable = @HTMLTable + '<th>ReasonForRejection</th>';
    SET @HTMLTable = @HTMLTable + '</tr>';

	SELECT @HTMLTable = @HTMLTable+'<tr><td>'+ISNULL(CAST(SIM.Code AS NVARCHAR(100)),'')+'</td><td>'
+ISNULL(SIM.Title,'')+'</td><td>'+ISNULL(SUMa.Code,'')+'</td><td>'+ISNULL(CAST(SRD.POQty AS NVARCHAR(20)),'')+'</td><td>'+ISNULL(CAST(SRD.ReceivedQty AS NVARCHAR(20)),'')+'</td><td>'+ISNULL(CAST(SRD.RejectedQty AS NVARCHAR(20)),'')+'</td><td>'+ISNULL(CAST(SRD.CreditNoteIssueDate AS NVARCHAR(100)),'')+'</td><td>'+ISNULL(CAST(SRD.ReasonForRejection AS NVARCHAR(300)),'')+'</td></tr>'
	    FROM   [sPurchase].[tSalesReturnDetail] SRD(NOLOCK)
			   INNER JOIN  [sPurchase].[tSalesReturn] SR ON SR.Id = SRD.SalesReturnId AND SR.LocationId = @rStoreLocationId AND SR.OrgGroupId = @rOrgGroupId AND SR.IsObsolete = 0
			   INNER JOIN	sIp.tStockItemMaster SIM	ON SIM.Id = SRD.StockItemId AND SIM.StoreLocationId = @rStoreLocationId AND SIM.OrgGroupId = @rOrgGroupId AND SIM.IsObsolete = 0 
			   INNER JOIN  sFinanceCommon.tStockUomMaster SUMa ON SUMa.Id = SIM.IssueStockUomId
		WHERE  SRD.SalesReturnId = @rSalesReturnId AND SRD.OrgGroupId = @rOrgGroupId 
 
   END
SELECT REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(Template, 
		'{SRNumber}' , @rSRNumber),
		'{GRNNumber}' , @rGRNNumber),
		'{RequestedBy}' , @rRequestedBy),
		'{Status}' , @rStatus),
		'{VendorName}' , @rVendorName),
		'{PurchaseOrderNumber}' , @rPurchaseOrderNumber),
		'{SalesReturnDetails}' , ISNULL(@HTMLTable,''))

		AS Template FROM sPurchase.tPurchaseReportTemplateMaster WHERE Code='SR' AND IsObsolete = 0

	END TRY

	BEGIN CATCH
    IF @@TRANCOUNT > 0
    ROLLBACK TRANSACTION 

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


GO

--exec [sPurchase].[pGetTemplate] 991100001
ALTER PROCEDURE [sPurchase].[pGetTemplate]
      @rPurchaseOrderId INT,
	  @rUserId BIGINT,
	  @rOrgGroupId INT
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
	DECLARE @rStoreLocationId BIGINT
    SELECT @rStoreLocationId = ISNULL(ItemValue,0)
	FROM sConfig.tConfigurationSetup 
	WHERE ConfigurationId  = 542 AND SourceId = @rUserId

	DECLARE @HTMLTable NVARCHAR(MAX);

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

	    SELECT  @rRefNumber = ISNULL(PO.RefNumber,''),
				@rPurchaseRequestNumber = ISNULL(PR.Number,''),
				@rRequestedBy = ISNULL(PO.RequestedBy,''),
				@rPoDate = ISNULL(PO.PODate,''),
				@rStatus = ISNULL(SM.Title,''),
				@rVendorCode = ISNULL(VM.Code,''),
				@rVendorName = ISNULL(VM.Title,''),
				@rRequiredBy = ISNULL(PO.RequiredBy,''),
				@rBillToAddress = ISNULL(PO.BillToAddress,''),
				@rShipToAddress = ISNULL(PO.ShipToAddress,'')
		FROM   [sPurchase].[tPurchaseOrder] PO(NOLOCK) 
			   LEFT JOIN sProcurement.tVendorMaster  VM ON PO.VendorId = VM.ID AND VM.LocationId = @rStoreLocationId AND VM.OrgGroupId = @rOrgGroupId AND VM.IsObsolete = 0
			   LEFT JOIN [sWf].[tWfStatusMaster] SM ON SM.Id = PO.StatusId
			   LEFT JOIN [sPurchase].[tPurchaseRequest] PR ON PR.Id = PO.PurchaseRequestId AND PR.LocationId = @rStoreLocationId AND PR.OrgGroupId = @rOrgGroupId AND PR.IsObsolete = 0
		WHERE  PO.Id = @rPurchaseOrderId AND PO.IsObsolete = 0
		       AND PO.LocationId = @rStoreLocationId
			   AND PO.OrgGroupId = @rOrgGroupId


    SET @HTMLTable = '';
	IF EXISTS(SELECT *  FROM   [sPurchase].[tPurchaseOrderDetail] POD
			WHERE  POD.PurchaseOrderId = @rPurchaseOrderId)
    BEGIN
    SET @HTMLTable = @HTMLTable + '<tr>';
    SET @HTMLTable = @HTMLTable + '<th>StockItemCode</th>';
    SET @HTMLTable = @HTMLTable + '<th>StockItemName</th>';
    SET @HTMLTable = @HTMLTable + '<th>Uom</th>';
    SET @HTMLTable = @HTMLTable + '<th>TotalQty</th>';
    SET @HTMLTable = @HTMLTable + '</tr>';

	SELECT @HTMLTable = @HTMLTable+'<tr><td>'+ISNULL(CAST(SIM.Code AS NVARCHAR(100)),'')+'</td><td>'
+ISNULL(SIM.Title,'')+'</td><td>'+ISNULL(SUMa.Code,'')+'</td><td>'+ISNULL(CAST(POD.TotalQty AS NVARCHAR(20)),'')+'</td></tr>'
	  FROM   [sPurchase].[tPurchaseOrderDetail] POD (NOLOCK)
			   INNER JOIN	sPurchase.tPurchaseOrder PO	ON PO.Id = POD.PurchaseOrderId AND PO.LocationId = @rStoreLocationId AND PO.OrgGroupId = @rOrgGroupId AND PO.IsObsolete = 0
			   INNER JOIN	sIp.tStockItemMaster SIM ON SIM.Id = POD.StockItemId AND SIM.StoreLocationId = @rStoreLocationId AND SIM.OrgGroupId = @rOrgGroupId AND SIM.IsObsolete = 0 
			   INNER JOIN   sFinanceCommon.tStockUomMaster SUMa ON SUMa.Id = SIM.IssueStockUomId
		WHERE  POD.PurchaseOrderId = @rPurchaseOrderId AND PO.IsObsolete = 0
		       AND PO.LocationId = @rStoreLocationId
			   AND PO.OrgGroupId = @rOrgGroupId

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

		AS Template FROM sPurchase.tPurchaseReportTemplateMaster WHERE Code='PO' AND IsObsolete = 0

	END TRY

	BEGIN CATCH
    IF @@TRANCOUNT > 0
    ROLLBACK TRANSACTION
    
    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].[pGoodsReceivedNoteApprovedGet]...';


GO

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

BEGIN
	BEGIN TRY
	    DECLARE @rStoreLocationId BIGINT
        SELECT @rStoreLocationId = ISNULL(ItemValue,0)
	    FROM sConfig.tConfigurationSetup 
	    WHERE ConfigurationId  = 542 AND SourceId = @rUserId

		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 AND VM.OrgGroupId = @rOrgGroupId AND VM.LocationId = @rStoreLocationId AND VM.IsObsolete = 0
			   LEFT JOIN [sWf].[tWfStatusMaster] SM ON SM.Id = GRN.StatusId
			   LEFT JOIN [sPurchase].[tPurchaseRequest] PR ON PR.ID = GRN.PurchaseRequestId AND PR.LocationId = @rStoreLocationId AND PR.OrgGroupId = @rOrgGroupId AND PR.IsObsolete = 0
			   LEFT JOIN [sPurchase].[tPurchaseOrder] PO ON PO.Id = GRN.PurchaseOrderId AND PO.LocationId = @rStoreLocationId AND PO.OrgGroupId = @rOrgGroupId AND PO.IsObsolete = 0
		WHERE  GRN.Id=@rId AND GRN.IsObsolete = 0 AND GRN.StatusId = 3
		       AND GRN.LocationId = @rStoreLocationId
			   AND GRN.OrgGroupId = @rOrgGroupId

		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 AND GRN.LocationId = @rStoreLocationId AND GRN.OrgGroupId = @rOrgGroupId AND GRN.IsObsolete = 0
				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.LocationId = @rStoreLocationId AND GRN.OrgGroupId = @rOrgGroupId AND GRN.IsObsolete = 0
			   INNER JOIN	sIp.tStockItemMaster SIM	ON SIM.Id = GRND.StockItemId AND SIM.StoreLocationId = @rStoreLocationId AND SIM.OrgGroupId = @rOrgGroupId AND SIM.IsObsolete = 0
			   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 AND GRN.IsObsolete = 0
		       AND GRN.LocationId = @rStoreLocationId
			   AND GRN.OrgGroupId = @rOrgGroupId
	END TRY

	BEGIN CATCH
    IF @@TRANCOUNT > 0
    ROLLBACK TRANSACTION
    
    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,
	@rUserId BIGINT

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	    DECLARE @rStoreLocationId BIGINT
        SELECT @rStoreLocationId = ISNULL(ItemValue,0)
	    FROM sConfig.tConfigurationSetup 
	    WHERE ConfigurationId  = 542 AND SourceId = @rUserId
	    
		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;
		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 ((GRN.LocationId = @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 AND QC.LocationId = @rStoreLocationId AND QC.OrgGroupId = @rOrgGroupId AND QC.IsObsolete = 0 
				  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 AND VM.LocationId = @rStoreLocationId AND VM.OrgGroupId = @rOrgGroupId AND VM.IsObsolete = 0
				LEFT JOIN [sPurchase].[tPurchaseRequest] PR ON PR.Id = GRN.PurchaseRequestId AND PR.LocationId = @rStoreLocationId AND PR.OrgGroupId = @rOrgGroupId AND PR.IsObsolete = 0
				LEFT JOIN [sPurchase].[tPurchaseOrder] PO ON PO.Id = GRN.PurchaseOrderId AND PO.LocationId = @rStoreLocationId AND PO.OrgGroupId = @rOrgGroupId AND PO.IsObsolete = 0
		WHERE 
				((GRN.GRNNumber LIKE @rNumber+'%') OR (ISNULL(@rNumber,'') = ''))
   				AND ((GRN.RequestedBy LIKE @rName+'%') OR (ISNULL(@rName,'') = ''))
   				AND ((GRN.LocationId = @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 AND QC.LocationId = @rStoreLocationId AND QC.OrgGroupId = @rOrgGroupId AND QC.IsObsolete = 0
				  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 TRANSACTION
    
    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].[pGoodsReceivedNoteDelete]...';


GO



ALTER PROCEDURE [sPurchase].[pGoodsReceivedNoteDelete]
		@rId BIGINT,
		@rStatusId SMALLINT
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
	BEGIN TRANSACTION
		IF(@rId > 0)
		BEGIN
			UPDATE sPurchase.tGoodsReceivedNote
			SET 
				StatusId = @rStatusId,
				IsObsolete = 1,
				DeletedDateTime = GETUTCDATE()
			WHERE Id = @rId AND IsObsolete = 0

			IF EXISTS(SELECT Id FROM sPurchase.tGoodsReceivedNoteDetail WHERE GoodsReceivedNoteId = @rId)
			BEGIN
				DELETE FROM sPurchase.tGoodsReceivedNoteDetail
				WHERE GoodsReceivedNoteId = @rId
			END
			SELECT 1
		END
	COMMIT TRANSACTION
	END TRY

	BEGIN CATCH
    IF @@TRANCOUNT > 0
    ROLLBACK TRANSACTION

    
    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,
	  @rUserId BIGINT,
	  @rOrgGroupId INT
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
	    DECLARE @rStoreLocationId BIGINT
        SELECT @rStoreLocationId = ISNULL(ItemValue,0)
	    FROM sConfig.tConfigurationSetup 
	    WHERE ConfigurationId  = 542 AND SourceId = @rUserId

		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 AND VM.LocationId = @rStoreLocationId AND VM.OrgGroupId = @rOrgGroupId AND VM.IsObsolete = 0
			   LEFT JOIN [sWf].[tWfStatusMaster] SM ON SM.Id = GRN.StatusId
			   LEFT JOIN [sPurchase].[tPurchaseRequest] PR ON PR.ID = GRN.PurchaseRequestId AND PR.LocationId = @rStoreLocationId AND PR.OrgGroupId = @rOrgGroupId AND PR.IsObsolete = 0
			   LEFT JOIN [sPurchase].[tPurchaseOrder] PO On PO.Id = GRN.PurchaseOrderId AND PO.LocationId = @rStoreLocationId AND PO.OrgGroupId = @rOrgGroupId AND PO.IsObsolete = 0
		WHERE  GRN.Id=@rId AND GRN.IsObsolete = 0
		       AND GRN.LocationId = @rStoreLocationId
			   AND GRN.OrgGroupId = @rOrgGroupId

		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.LocationId = @rStoreLocationId AND GRN.OrgGroupId = @rOrgGroupId AND GRN.IsObsolete = 0
			   INNER JOIN	sIp.tStockItemMaster SIM	ON SIM.Id = GRND.StockItemId AND SIM.StoreLocationId = @rStoreLocationId AND SIM.OrgGroupId = @rOrgGroupId AND SIM.IsObsolete = 0
			   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.IsObsolete = 0
		       AND GRN.LocationId = @rStoreLocationId
			   AND GRN.OrgGroupId = @rOrgGroupId
	END TRY

	BEGIN CATCH
    IF @@TRANCOUNT > 0
    ROLLBACK TRANSACTION
    
    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,
	@rUserId BIGINT

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	    DECLARE @rStoreLocationId BIGINT
        SELECT @rStoreLocationId = ISNULL(ItemValue,0)
	    FROM sConfig.tConfigurationSetup 
	    WHERE ConfigurationId  = 542 AND SourceId = @rUserId
	    
		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.tGoodsReceivedNote GRN(NOLOCK)



		WHERE 
				((GRN.GRNNumber LIKE @rNumber+'%') OR (ISNULL(@rNumber,'') = ''))
   				AND ((GRN.RequestedBy LIKE @rName+'%') OR (ISNULL(@rName,'') = ''))
   				AND ((GRN.LocationId = @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 AND VM.LocationId = @rStoreLocationId AND VM.OrgGroupId = @rOrgGroupId AND VM.IsObsolete = 0
				LEFT JOIN [sPurchase].[tPurchaseRequest] PR ON PR.Id = GRN.PurchaseRequestId AND PR.LocationId = @rStoreLocationId AND PR.OrgGroupId = @rOrgGroupId AND PR.IsObsolete = 0
				LEFT JOIN [sPurchase].[tPurchaseOrder] PO ON PO.Id = GRN.PurchaseOrderId AND PO.LocationId = @rStoreLocationId AND PO.OrgGroupId = @rOrgGroupId AND PO.IsObsolete = 0
		WHERE 
				((GRN.GRNNumber LIKE @rNumber+'%') OR (ISNULL(@rNumber,'') = ''))
   				AND ((GRN.RequestedBy LIKE @rName+'%') OR (ISNULL(@rName,'') = ''))
   				AND ((GRN.LocationId = @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 TRANSACTION
    
    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 = '',
	@rStartDate DATETIME = NULL,
	@rEndDate DATETIME = NULL,
	@rOrgGroupId INT,
	@rPageNo INT,
	@rPageSize INT,
	@rStatusId SMALLINT = NULL,
	@rUserId BIGINT

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	                DECLARE @rStoreLocationId BIGINT
					SELECT @rStoreLocationId = ISNULL(ItemValue,0)
					FROM sConfig.tConfigurationSetup 
					WHERE ConfigurationId  = 542 AND SourceId = @rUserId
	    
					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.tGoodsReceivedNote GRN (NOLOCK)

					WHERE 
							((GRN.GRNNumber LIKE @rNumber+'%') OR (ISNULL(@rNumber,'') = ''))
   							AND ((GRN.RequestedBy LIKE @rName+'%') OR (ISNULL(@rName,'') = ''))
   							AND ((GRN.LocationId = @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 
								   AND SR.LocationId = @rStoreLocationId AND SR.OrgGroupId = @rOrgGroupId AND SR.IsObsolete = 0
							INNER JOIN sPurchase.tGoodsReceivedNote GRN12 ON Sr.GoodsReceivedNoteId = Grn12.Id 
								   AND GRN12.LocationId = @rStoreLocationId AND GRN12.OrgGroupId = @rOrgGroupId AND GRN12.IsObsolete = 0
							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 
								   AND QC1.LocationId = @rStoreLocationId AND QC1.OrgGroupId = @rOrgGroupId AND QC1.IsObsolete = 0
							INNER JOIN   sPurchase.tQualityCheckDetail QCD1 ON QCD1.QualityCheckId = QC1.Id AND QCD1.RejectedQty > 0
							WHERE GRN12.Id = GRN.Id AND GRN12.LocationId = @rStoreLocationId AND GRN12.OrgGroupId = @rOrgGroupId AND GRN12.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.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 
								   AND QC1.LocationId = @rStoreLocationId AND QC1.OrgGroupId = @rOrgGroupId AND QC1.IsObsolete = 0
							INNER JOIN   sPurchase.tQualityCheckDetail QCD1 ON QCD1.QualityCheckId = QC1.Id AND QCD1.RejectedQty > 0
							WHERE GRN12.Id = GRN.Id AND GRN12.LocationId = @rStoreLocationId AND GRN12.OrgGroupId = @rOrgGroupId AND GRN12.IsObsolete = 0) 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 ((GRN.LocationId = @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 
								   AND QC1.LocationId = @rStoreLocationId AND QC1.OrgGroupId = @rOrgGroupId AND QC1.IsObsolete = 0
							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 
								   AND SR.LocationId = @rStoreLocationId AND SR.OrgGroupId = @rOrgGroupId AND SR.IsObsolete = 0
							INNER JOIN sPurchase.tGoodsReceivedNote GRN1 ON SR.GoodsReceivedNoteId = GRN1.Id 
								   AND GRN1.LocationId = @rStoreLocationId AND GRN1.OrgGroupId = @rOrgGroupId AND GRN1.IsObsolete = 0
							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 TRANSACTION
    
    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,
	  @rUserId BIGINT,
	  @rOrgGroupId INT
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
	    DECLARE @rStoreLocationId BIGINT
        SELECT @rStoreLocationId = ISNULL(ItemValue,0)
	    FROM sConfig.tConfigurationSetup 
	    WHERE ConfigurationId  = 542 AND SourceId = @rUserId

		IF((SELECT 
				(SELECT SUM(QCD1.RejectedQty) FROM sPurchase.tGoodsReceivedNote GRN12
			    INNER JOIN   sPurchase.tQualityCheck QC1 ON QC1.GoodsReceivedNoteId = GRN12.Id 
					   AND QC1.LocationId = @rStoreLocationId AND QC1.OrgGroupId = @rOrgGroupId AND QC1.IsObsolete = 0
			    INNER JOIN   sPurchase.tQualityCheckDetail QCD1 ON QCD1.QualityCheckId = QC1.Id AND QCD1.RejectedQty > 0
				WHERE GRN12.Id = @rId AND GRN12.LocationId = @rStoreLocationId AND GRN12.OrgGroupId = @rOrgGroupId AND GRN12.IsObsolete = 0) -
				 (SELECT ISNULL(SUM(SRD.RejectedQty),0) FROM sPurchase.tSalesReturnDetail SRD
				INNER JOIN sPurchase.tSalesReturn SR ON SR.Id = SRD.SalesReturnId 
				AND SR.LocationId = @rStoreLocationId AND SR.OrgGroupId = @rOrgGroupId AND SR.IsObsolete = 0
				INNER JOIN [sPurchase].[tGoodsReceivedNoteDetail] GRND ON SRD.GoodsReceivedNoteDetailId = GRND.Id
				AND GRND.GoodsReceivedNoteId = @rId
				WHERE SR.GoodsReceivedNoteId = @rId AND SR.LocationId = @rStoreLocationId AND SR.OrgGroupId = @rOrgGroupId AND SR.IsObsolete = 0)) = 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 AND QC.LocationId = @rStoreLocationId AND QC.OrgGroupId = @rOrgGroupId AND QC.IsObsolete = 0
				   INNER JOIN sPurchase.tPurchaseOrder PO ON PO.Id = GRN.PurchaseOrderId AND PO.LocationId = @rStoreLocationId AND PO.OrgGroupId = @rOrgGroupId AND PO.IsObsolete = 0
				   LEFT JOIN  sProcurement.tVendorMaster  VM ON GRN.VendorId = VM.ID AND VM.LocationId = @rStoreLocationId AND VM.OrgGroupId = @rOrgGroupId AND VM.IsObsolete = 0
				   LEFT Join  sWf.tWfStatusMaster SM ON SM.Id = GRN.StatusId
			WHERE  GRN.Id=@rId AND GRN.StatusId = 3 AND GRN.LocationId = @rStoreLocationId AND GRN.OrgGroupId = @rOrgGroupId AND GRN.IsObsolete = 0

			SELECT DISTINCT GRND.Id AS GoodsReceivedNoteDetailId,
				   GRND.GoodsReceivedNoteId,
				   GRND.PurchaseOrderDetailId,
				   GRND.OrgGroupId,
				   SUMa.Id AS UnitTypeId,
				   GRND.StockItemId,
				   GRND.POQty,
				   GRND.ReceivedQty,
				   GRND.PreviousGRNQty,
				   GRND.UnitPrice,
				   GRND.Remark, 
				 --  (SELECT Sum(QCD1.RejectedQty) FROM sPurchase.tGoodsReceivedNote GRN12
				 --   INNER JOIN   sPurchase.tQualityCheck QC1 ON QC1.GoodsReceivedNoteId = GRN12.Id
				 --   INNER JOIN   sPurchase.tQualityCheckDetail QCD1 ON QCD1.QualityCheckId = QC1.Id AND QCD1.RejectedQty > 0
					--WHERE GRN12.Id = GRN.Id) AS RejectedQty,
					(SELECT SUM(QCD1.RejectedQty) FROM sPurchase.tGoodsReceivedNote GRN12
					INNER JOIN   sPurchase.tQualityCheck QC1 ON QC1.GoodsReceivedNoteId = GRN12.Id 
						   AND QC1.LocationId = @rStoreLocationId AND QC1.OrgGroupId = @rOrgGroupId AND QC1.IsObsolete = 0
					INNER JOIN   sPurchase.tQualityCheckDetail QCD1 ON QCD1.QualityCheckId = QC1.Id AND QCD1.RejectedQty > 0
					WHERE GRN12.Id = GRN.Id AND GRN12.LocationId = @rStoreLocationId AND GRN12.OrgGroupId = @rOrgGroupId AND GRN12.IsObsolete = 0) -
					 (SELECT ISNULL(SUM(SRD.RejectedQty),0) FROM sPurchase.tSalesReturnDetail SRD
					INNER JOIN sPurchase.tSalesReturn SR ON SR.Id = SRD.SalesReturnId AND SR.LocationId = @rStoreLocationId AND SR.OrgGroupId = @rOrgGroupId AND SR.IsObsolete = 0
					WHERE SR.GoodsReceivedNoteId = GRN.Id AND SRD.GoodsReceivedNoteDetailId = GRND.Id 
					AND SR.LocationId = @rStoreLocationId AND SR.OrgGroupId = @rOrgGroupId AND SR.IsObsolete = 0) 
					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.LocationId = @rStoreLocationId AND GRN.OrgGroupId = @rOrgGroupId AND GRN.IsObsolete = 0
				   INNER JOIN sPurchase.tQualityCheck QC ON QC.GoodsReceivedNoteId = GRN.Id 
						  AND QC.LocationId = @rStoreLocationId AND QC.OrgGroupId = @rOrgGroupId AND QC.IsObsolete = 0
				   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 
					      AND SIM.StoreLocationId = @rStoreLocationId AND SIM.OrgGroupId = @rOrgGroupId AND SIM.IsObsolete = 0 
				   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 
				   AND GRN.LocationId = @rStoreLocationId AND GRN.OrgGroupId = @rOrgGroupId AND GRN.IsObsolete = 0
		END
	END TRY

	BEGIN CATCH
    IF @@TRANCOUNT > 0
        ROLLBACK TRANSACTION
    
    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].[pHelperPopUpGet]...';


GO


ALTER PROCEDURE [sPurchase].[pHelperPopUpGet]
	  @rScreenId SMALLINT
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
		SELECT ISNULL(HelpDescription,'')
		 FROM sSecurity.tScreenHelp 
		 WHERE ScreenId = @rScreenId
	END TRY

	BEGIN CATCH
    IF @@TRANCOUNT > 0
        ROLLBACK TRANSACTION
    
    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
	    DECLARE @rStoreLocationId BIGINT
        SELECT @rStoreLocationId = ISNULL(ItemValue,0)
	    FROM sConfig.tConfigurationSetup 
	    WHERE ConfigurationId  = 542 AND SourceId = @rUserId

		IF(@rId > 0)
		BEGIN
		    IF NOT EXISTS(SELECT Id FROM sPurchase.tInvoiceGenerate WHERE Id = @rId AND CreatedUserId = @rUserId 
			AND LocationId = @rStoreLocationId AND OrgGroupId = @rOrgGroupId AND IsObsolete = 0)
            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 LocationId = @rStoreLocationId AND OrgGroupId = @rOrgGroupId AND IsObsolete = 0

				DELETE FROM sPurchase.tInvoiceGenerateDetail
				WHERE Id NOT IN(SELECT Id FROM @rDetailList)
				AND InvoiceGenerateId = @rId AND OrgGroupId = @rOrgGroupId

				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 AND IG.OrgGroupId = @rOrgGroupId

				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 AND IG.OrgGroupId = @rOrgGroupId
				WHERE IG.InvoiceGenerateId = @rId AND IG.OrgGroupId = @rOrgGroupId)
				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 AND IG.OrgGroupId = @rOrgGroupId
				WHERE IG.InvoiceGenerateId = @rId AND IG.OrgGroupId = @rOrgGroupId))
				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,
				@rStoreLocationId, 		 
				@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 TRANSACTION
	END TRY

	BEGIN CATCH
    IF @@TRANCOUNT > 0
        ROLLBACK TRANSACTION

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


GO




ALTER PROCEDURE [sPurchase].[pInvoiceGenerateDelete]
		@rId BIGINT,
		@rStatusId SMALLINT
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
	BEGIN TRANSACTION
		IF(@rId > 0)
		BEGIN 
			UPDATE sPurchase.tInvoiceGenerate
			SET 
				StatusId = @rStatusId,
				IsObsolete = 1,
				DeletedDateTime = GETUTCDATE()
			WHERE Id = @rId AND IsObsolete = 0

			IF EXISTS(SELECT Id FROM sPurchase.tInvoiceGenerateDetail WHERE InvoiceGenerateId = @rId)
			BEGIN
				DELETE FROM sPurchase.tInvoiceGenerateDetail
				WHERE InvoiceGenerateId = @rId
			END
			SELECT 1
	    END
	COMMIT TRANSACTION
	END TRY

	BEGIN CATCH
    IF @@TRANCOUNT > 0
        ROLLBACK TRANSACTION

    
    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,
	  @rUserId BIGINT,
	  @rOrgGroupId INT
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
	    DECLARE @rStoreLocationId BIGINT
        SELECT @rStoreLocationId = ISNULL(ItemValue,0)
	    FROM sConfig.tConfigurationSetup 
	    WHERE ConfigurationId  = 542 AND SourceId = @rUserId

		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 AND GRN.LocationId = @rStoreLocationId AND GRN.OrgGroupId = @rOrgGroupId AND GRN.IsObsolete = 0
		LEFT JOIN sProcurement.tVendorMaster  VM ON IG.VendorId = VM.ID AND VM.LocationId = @rStoreLocationId AND VM.OrgGroupId = @rOrgGroupId AND VM.IsObsolete = 0
		LEFT JOIN [sWf].[tWfStatusMaster] SM ON SM.Id = IG.StatusId
		WHERE  IG.Id=@rId AND IG.IsObsolete = 0
		       AND IG.LocationId = @rStoreLocationId
			   AND IG.OrgGroupId = @rOrgGroupId

		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.LocationId = @rStoreLocationId AND IG.OrgGroupId = @rOrgGroupId AND IG.IsObsolete = 0
			   INNER JOIN	sIp.tStockItemMaster SIM	ON SIM.Id = IGD.StockItemId AND SIM.StoreLocationId = @rStoreLocationId AND SIM.OrgGroupId = @rOrgGroupId AND SIM.IsObsolete = 0
			   LEFT JOIN [sIp].[tStockItemCategoryMaster] SCM ON SCM.Id = SIM.StockItemCategoryId
			   INNER JOIN  sFinanceCommon.tStockUomMaster SUMa ON SUMa.Id = SIM.IssueStockUomId
		WHERE  IGD.InvoiceGenerateId=@rId AND IG.IsObsolete = 0
		       AND IG.LocationId = @rStoreLocationId
			   AND IG.OrgGroupId = @rOrgGroupId
	END TRY

	BEGIN CATCH
    IF @@TRANCOUNT > 0
        ROLLBACK TRANSACTION
    
    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,
	@rUserId BIGINT

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	    DECLARE @rStoreLocationId BIGINT
        SELECT @rStoreLocationId = ISNULL(ItemValue,0)
	    FROM sConfig.tConfigurationSetup 
	    WHERE ConfigurationId  = 542 AND SourceId = @rUserId
	    
		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.tInvoiceGenerate IG (NOLOCK)

		WHERE 
				((IG.INVNumber LIKE @rNumber+'%') OR (ISNULL(@rNumber,'') = ''))
   				AND ((IG.RequestedBy LIKE @rName+'%') OR (ISNULL(@rName,'') = ''))
   				AND ((IG.LocationId = @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 ((IG.LocationId = @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 TRANSACTION
    
    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].[pMasterBatchGet]...';


GO


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

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

	BEGIN CATCH
    IF @@TRANCOUNT > 0
        ROLLBACK TRANSACTION
    
    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].[pMasterOrganizationGet]...';


GO


ALTER PROCEDURE [sPurchase].[pMasterOrganizationGet]
	  @rOrgGroupId INT,
	  @rUserId BIGINT
AS
SET NOCOUNT ON

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

	BEGIN CATCH
    IF @@TRANCOUNT > 0
        ROLLBACK TRANSACTION
    
    DECLARE @ErrorMessage NVARCHAR(4000);  
    DECLARE @ErrorSeverity INT;  
    DECLARE @ErrorState INT;  
    SELECT   
       @ErrorMessage = ERROR_MESSAGE(),  
       @ErrorSeverity = ERROR_SEVERITY(),  
       @ErrorState = ERROR_STATE();  
    RAISERROR (@ErrorMessage, @ErrorSeverity, @ErrorState);  
    
	END CATCH
END
GO



PRINT N'Altering Procedure [sPurchase].[pMenuGet_Purchase]...';


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

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

  UNION
  

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

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


GO

--exec [sPurchase].[pPOPurchaseRequestDetailGet] 991100002
ALTER PROCEDURE [sPurchase].[pPOPurchaseRequestDetailGet]
	  @rId INT,
	  @rUserId BIGINT,
	  @rOrgGroupId INT
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
	BEGIN TRANSACTION
	    DECLARE @rStoreLocationId BIGINT
        SELECT @rStoreLocationId = ISNULL(ItemValue,0)
	    FROM sConfig.tConfigurationSetup 
	    WHERE ConfigurationId  = 542 AND SourceId = @rUserId

		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.LocationId = @rStoreLocationId AND PR.OrgGroupId = @rOrgGroupId AND PR.IsObsolete = 0 AND PR.StatusId = 3
			   INNER JOIN	sIp.tStockItemMaster SIM	ON SIM.Id = PRD.StockItemId AND SIM.StoreLocationId = @rStoreLocationId AND SIM.OrgGroupId = @rOrgGroupId AND SIM.IsObsolete = 0 
			   LEFT JOIN [sIp].[tStockItemCategoryMaster] SCM ON SCM.Id = SIM.StockItemCategoryId
			   INNER JOIN  sFinanceCommon.tStockUomMaster SUMa ON SUMa.Id = SIM.IssueStockUomId
		WHERE  PRD.PurchaseRequestId=@rId AND PR.IsObsolete = 0
		       AND PR.LocationId = @rStoreLocationId
			   AND PR.OrgGroupId = @rOrgGroupId
	COMMIT TRANSACTION
	END TRY

	BEGIN CATCH
    IF @@TRANCOUNT > 0
        ROLLBACK TRANSACTION
    
    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,
	  @rUserId BIGINT,
	  @rOrgGroupId INT
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
		DECLARE @rStoreLocationId BIGINT
        SELECT @rStoreLocationId = ISNULL(ItemValue,0)
	    FROM sConfig.tConfigurationSetup 
	    WHERE ConfigurationId  = 542 AND SourceId = @rUserId

		IF EXISTS(SELECT PO.Id
		FROM   [sPurchase].[tPurchaseOrder] PO(NOLOCK) 
		INNER JOIN [sPurchase].[tGoodsReceivedNote] GRN ON GRN.PurchaseOrderId = PO.Id AND GRN.LocationId = @rStoreLocationId AND GRN.OrgGroupId = @rOrgGroupId AND GRN.IsObsolete = 0 AND GRN.StatusId IN (1,2)
		WHERE PO.Id = @rId AND PO.LocationId = @rStoreLocationId AND PO.OrgGroupId = @rOrgGroupId AND PO.IsObsolete = 0)
		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 AND PR.LocationId = @rStoreLocationId AND PR.OrgGroupId = @rOrgGroupId AND PR.IsObsolete = 0
				   LEFT JOIN sProcurement.tVendorMaster  VM ON PO.VendorId = VM.ID AND VM.LocationId = @rStoreLocationId AND VM.OrgGroupId = @rOrgGroupId AND VM.IsObsolete = 0 
				   LEFT JOIN [sWf].[tWfStatusMaster] SM ON SM.Id = PO.StatusId
			WHERE  PO.Id = @rId
			       AND PO.IsObsolete = 0
				   AND PO.StatusId = 3
			       AND PO.LocationId = @rStoreLocationId
				   AND PO.OrgGroupId = @rOrgGroupId

			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.LocationId = @rStoreLocationId AND GRN.OrgGroupId = @rOrgGroupId AND GRN.IsObsolete = 0 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.LocationId = @rStoreLocationId AND GRN.OrgGroupId = @rOrgGroupId AND GRN.IsObsolete = 0 AND GRN.StatusID <> 4) AS PreviousGRNQty,
				   (SELECT QRD.TargetPrice FROM [sPurchase].[tQuotationRequestDetail] QRD
					INNER JOIN [sPurchase].[tQuotationRequest] QR ON QR.Id = QRD.QuotationRequestId AND QR.LocationId = @rStoreLocationId AND QR.OrgGroupId = @rOrgGroupId AND QR.IsObsolete = 0  
					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 AND PO.LocationId = @rStoreLocationId AND PO.OrgGroupId = @rOrgGroupId AND PO.IsObsolete = 0  
				   INNER JOIN	sIp.tStockItemMaster SIM	ON SIM.Id = POD.StockItemId AND SIM.StoreLocationId = @rStoreLocationId AND SIM.OrgGroupId = @rOrgGroupId AND SIM.IsObsolete = 0  
				   INNER JOIN  sFinanceCommon.tStockUomMaster SUMa ON SUMa.Id = SIM.IssueStockUomId
				   LEFT JOIN [sIp].[tStockItemCategoryMaster] SCM ON SCM.Id = SIM.StockItemCategoryId
			WHERE  POD.PurchaseOrderId = @rId AND PO.IsObsolete = 0 
			       AND PO.LocationId = @rStoreLocationId
				   AND PO.OrgGroupId = @rOrgGroupId 
		END
	END TRY

	BEGIN CATCH
    IF @@TRANCOUNT > 0
        ROLLBACK TRANSACTION
    
    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 = '',
	@rStartDate DATETIME = NULL,
	@rEndDate DATETIME = NULL,
	@rOrgGroupId INT,
	@rPageNo INT,
	@rPageSize INT,
	@rStatusId SMALLINT = 0,
	@rUserId BIGINT

WITH EXECUTE AS CALLER
AS	
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	    DECLARE @rStoreLocationId BIGINT
        SELECT @rStoreLocationId = ISNULL(ItemValue,0)
	    FROM sConfig.tConfigurationSetup 
	    WHERE ConfigurationId  = 542 AND SourceId = @rUserId

		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 (ISNULL(@rNumber,'') = ''))
   				AND ((PO.RequestedBy LIKE @rName+'%') OR (ISNULL(@rName,'') = ''))
   				AND ((PO.LocationId = @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 AND GRN.LocationId = @rStoreLocationId AND GRN.OrgGroupId = @rOrgGroupId AND GRN.IsObsolete = 0
				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 PO.LocationId = @rStoreLocationId AND PO.OrgGroupId = @rOrgGroupId 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.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 ((PO.LocationId = @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 AND GRN.LocationId = @rStoreLocationId AND GRN.OrgGroupId = @rOrgGroupId AND GRN.IsObsolete = 0
				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 PO.LocationId = @rStoreLocationId AND PO.OrgGroupId = @rOrgGroupId 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 TRANSACTION
    
    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].[pPurchaseOrderDelete]...';


GO


ALTER PROCEDURE [sPurchase].[pPurchaseOrderDelete]
		@rId BIGINT,
		@rStatusId SMALLINT
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
	BEGIN TRANSACTION
		IF(@rId > 0)
		BEGIN
			UPDATE sPurchase.tPurchaseOrder
			SET 
				StatusId = @rStatusId,
				IsObsolete = 1,		
				DeletedDateTime = GETUTCDATE()
			WHERE Id = @rId and IsObsolete = 0

			IF EXISTS(SELECT Id FROM sPurchase.tPurchaseOrderDetail WHERE PurchaseOrderId = @rId)
			BEGIN
				DELETE FROM sPurchase.tPurchaseOrderDetail
				WHERE PurchaseOrderId = @rId
			END
			SELECT 1
		END
	COMMIT TRANSACTION
	END TRY

	BEGIN CATCH
    IF @@TRANCOUNT > 0
        ROLLBACK TRANSACTION

    
    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,
	  @rUserId BIGINT,
	  @rOrgGroupId INT
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
	    DECLARE @rStoreLocationId BIGINT
        SELECT @rStoreLocationId = ISNULL(ItemValue,0)
	    FROM sConfig.tConfigurationSetup 
	    WHERE ConfigurationId  = 542 AND SourceId = @rUserId

		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 AND VM.LocationId = @rStoreLocationId AND VM.OrgGroupId = @rOrgGroupId AND VM.IsObsolete = 0
			   LEFT JOIN [sWf].[tWfStatusMaster] SM ON SM.Id = PO.StatusId
			   LEFT JOIN [sPurchase].[tPurchaseRequest] PR ON PR.Id = PO.PurchaseRequestId AND PR.LocationId = @rStoreLocationId AND PR.OrgGroupId = @rOrgGroupId AND PR.IsObsolete = 0
		WHERE  PO.Id = @rId AND PO.IsObsolete = 0
		       AND PO.LocationId = @rStoreLocationId
			   AND PO.OrgGroupId = @rOrgGroupId

		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.LocationId = @rStoreLocationId AND PO.OrgGroupId = @rOrgGroupId AND PO.IsObsolete = 0
			   INNER JOIN	sIp.tStockItemMaster SIM	ON SIM.Id = POD.StockItemId  AND SIM.StoreLocationId = @rStoreLocationId AND SIM.OrgGroupId = @rOrgGroupId AND SIM.IsObsolete = 0
			   LEFT JOIN [sIp].[tStockItemCategoryMaster] SCM ON SCM.Id = SIM.StockItemCategoryId
			   INNER JOIN  sFinanceCommon.tStockUomMaster SUMa ON SUMa.Id = SIM.IssueStockUomId
		WHERE  POD.PurchaseOrderId = @rId AND PO.IsObsolete = 0
		       AND PO.LocationId = @rStoreLocationId
			   AND PO.OrgGroupId = @rOrgGroupId

	END TRY

	BEGIN CATCH
    IF @@TRANCOUNT > 0
        ROLLBACK TRANSACTION
    
    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 = '',
	@rStartDate DATETIME = NULL,
	@rEndDate DATETIME = NULL,
	@rOrgGroupId INT,
	@rPageNo INT,
	@rPageSize INT,
	@rStatusId SMALLINT = NULL,
	@rUserId BIGINT

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	    DECLARE @rStoreLocationId BIGINT
        SELECT @rStoreLocationId = ISNULL(ItemValue,0)
	    FROM sConfig.tConfigurationSetup 
	    WHERE ConfigurationId  = 542 AND SourceId = @rUserId

		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 ((PO.LocationId = @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 ((PO.LocationId = @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 TRANSACTION
    
    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,
	  @rUserId BIGINT,
	  @rOrgGroupId INT
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
	    DECLARE @rStoreLocationId BIGINT
        SELECT @rStoreLocationId = ISNULL(ItemValue,0)
	    FROM sConfig.tConfigurationSetup 
	    WHERE ConfigurationId  = 542 AND SourceId = @rUserId

		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 AND QR.LocationId = @rStoreLocationId AND QR.OrgGroupId = @rOrgGroupId AND QR.IsObsolete = 0
			   LEFT JOIN [sWf].[tWfStatusMaster] SM ON SM.Id = PR.StatusId
			   LEFT JOIN sProcurement.tVendorMaster  VM ON QR.VendorId = VM.ID AND VM.LocationId = @rStoreLocationId AND VM.OrgGroupId = @rOrgGroupId AND VM.IsObsolete = 0
		WHERE  PR.Id=@rId AND PR.IsObsolete = 0 AND PR.StatusId = 3
		       AND PR.LocationId = @rStoreLocationId
			   AND PR.OrgGroupId = @rOrgGroupId

		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.StatusId = 3 AND PR.LocationId = @rStoreLocationId AND PR.OrgGroupId = @rOrgGroupId AND PR.IsObsolete = 0
			   INNER JOIN	sIp.tStockItemMaster SIM	ON SIM.Id = PRD.StockItemId AND SIM.StoreLocationId = @rStoreLocationId AND SIM.OrgGroupId = @rOrgGroupId AND SIM.IsObsolete = 0
			   LEFT JOIN [sIp].[tStockItemCategoryMaster] SCM ON SCM.Id = SIM.StockItemCategoryId
			   INNER JOIN  sFinanceCommon.tStockUomMaster SUMa ON SUMa.Id = SIM.IssueStockUomId
		WHERE  PRD.PurchaseRequestId=@rId AND PR.IsObsolete = 0
		       AND PR.LocationId = @rStoreLocationId
			   AND PR.OrgGroupId = @rOrgGroupId
	END TRY

	BEGIN CATCH
    IF @@TRANCOUNT > 0
        ROLLBACK TRANSACTION
    
    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 = '',
	@rStartDate DATETIME = NULL,
	@rEndDate DATETIME = NULL,
	@rOrgGroupId INT,																				
	@rPageNo INT,
	@rPageSize INT,
	@rStatusId SMALLINT = 0,
	@rUserId BIGINT

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	    DECLARE @rStoreLocationId BIGINT
        SELECT @rStoreLocationId = ISNULL(ItemValue,0)
	    FROM sConfig.tConfigurationSetup 
	    WHERE ConfigurationId  = 542 AND SourceId = @rUserId

		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 ((PR.LocationId = @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

	    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.LocationId = @rStoreLocationId) OR (@rStoreLocationId = 0))
   				AND ((PR.OrgGroupId = @rOrgGroupId) OR (@rOrgGroupId=0))
				AND ((PR.StatusId = @rStatusId) OR (ISNULL(@rStatusId,0)=0))
				AND PR.IsObsolete = 0 AND PR.StatusId = 3 
				AND ((CAST(PR.CreatedDateTime AS DATE) >= CAST(@rStartDate AS DATE)) OR (ISNULL(@rStartDate,'')=''))
				AND((CAST(PR.CreatedDateTime AS DATE) <= CAST(@rEndDate AS DATE)) OR (ISNULL(@rEndDate,'')='')))t WHERE t.RowNum BETWEEN
		        ((@rPageNo-1)*@rPageSize +1) AND (@rPageNo*@rpageSize)

        SELECT @TotalRecords AS TotalRecords
	 END TRY

	BEGIN CATCH
    IF @@TRANCOUNT > 0
        ROLLBACK TRANSACTION
    
    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].[pPurchaseRequestDelete]...';


GO



ALTER PROCEDURE [sPurchase].[pPurchaseRequestDelete]
		@rId BIGINT,
		@rStatusId SMALLINT
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
	BEGIN TRANSACTION
		IF(@rId > 0)
		BEGIN
			UPDATE sPurchase.tPurchaseRequest
			SET 
				StatusId = @rStatusId,
				IsObsolete = 1,		
				DeletedDateTime = GetUtcDate()
			WHERE Id = @rId AND IsObsolete = 0

			IF EXISTS(SELECT Id FROM sPurchase.tPurchaseRequestDetail WHERE PurchaseRequestId = @rId)
			BEGIN
				DELETE FROM sPurchase.tPurchaseRequestDetail
				WHERE PurchaseRequestId = @rId
			END
			SELECT 1
		END
	COMMIT TRANSACTION
	END TRY

	BEGIN CATCH
    IF @@TRANCOUNT > 0
        ROLLBACK TRANSACTION

    
    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]
	  @rUserId BIGINT,
	  @rId BIGINT,
	  @rOrgGroupId INT
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
	    DECLARE @rStoreLocationId BIGINT
        SELECT @rStoreLocationId = ISNULL(ItemValue,0)
	    FROM sConfig.tConfigurationSetup 
	    WHERE ConfigurationId  = 542 AND SourceId = @rUserId

		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 AND VM.LocationId = @rStoreLocationId AND VM.OrgGroupId = @rOrgGroupId AND VM.IsObsolete = 0
				LEFT JOIN [sWf].[tWfStatusMaster] SM ON SM.Id = PR.StatusId
		WHERE   PR.Id=@rId AND PR.IsObsolete = 0
				AND PR.LocationId = @rStoreLocationId
				AND PR.OrgGroupId = @rOrgGroupId

		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.LocationId = @rStoreLocationId AND PR.OrgGroupId = @rOrgGroupId AND PR.IsObsolete = 0
			   INNER JOIN	sIp.tStockItemMaster SIM	ON SIM.Id = PRD.StockItemId AND SIM.StoreLocationId = @rStoreLocationId AND SIM.OrgGroupId = @rOrgGroupId AND SIM.IsObsolete = 0
			   LEFT JOIN [sIp].[tStockItemCategoryMaster] SCM ON SCM.Id = SIM.StockItemCategoryId
			   INNER JOIN  sFinanceCommon.tStockUomMaster SUMa ON SUMa.Id = SIM.IssueStockUomId
		WHERE  PRD.PurchaseRequestId=@rId AND PR.IsObsolete = 0 
		       AND PR.LocationId = @rStoreLocationId
		       AND PR.OrgGroupId = @rOrgGroupId
	END TRY

	BEGIN CATCH
    IF @@TRANCOUNT > 0
        ROLLBACK TRANSACTION
    
    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 = '',
	@rStartDate DATETIME = NULL,
	@rEndDate DATETIME = NULL,
	@rOrgGroupId INT,
	@rPageNo INT,
	@rPageSize INT,
	@rStatusId SMALLINT = 0,
	@rUserId BIGINT

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	    DECLARE @rStoreLocationId BIGINT
        SELECT @rStoreLocationId = ISNULL(ItemValue,0)
	    FROM sConfig.tConfigurationSetup 
	    WHERE ConfigurationId  = 542 AND SourceId = @rUserId
	    
		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(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 AND QR.LocationId = @rStoreLocationId AND QR.OrgGroupId = @rOrgGroupId AND QR.IsObsolete = 0 
		LEFT JOIN sProcurement.tVendorMaster  VM ON QR.VendorId = VM.ID AND VM.LocationId = @rStoreLocationId AND VM.OrgGroupId = @rOrgGroupId AND VM.IsObsolete = 0 

		WHERE 
				((PR.Number LIKE @rNumber+'%') OR (ISNULL(@rNumber,'') = ''))
   				AND ((PR.RequestedBy LIKE @rName+'%') OR (ISNULL(@rName,'') = ''))
   				AND ((PR.LocationId = @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 AND QR.LocationId = @rStoreLocationId AND QR.OrgGroupId = @rOrgGroupId AND QR.IsObsolete = 0 
			    LEFT JOIN sProcurement.tVendorMaster  VM ON QR.VendorId = VM.ID AND VM.LocationId = @rStoreLocationId AND VM.OrgGroupId = @rOrgGroupId AND VM.IsObsolete = 0 

        WHERE 
				((PR.Number LIKE @rNumber+'%') OR (ISNULL(@rNumber,'') = ''))
   				AND ((PR.RequestedBy LIKE @rName+'%') OR (ISNULL(@rName,'') = ''))
   				AND ((PR.LocationId = @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 TRANSACTION
    
    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] '',9911000000065,'',9911,'2024-01-07','2024-01-30',1,10,0
ALTER PROCEDURE [sPurchase].[pPurchaseRequestSearchGet]

	@rNumber NVARCHAR(30) = '',
	@rUserId BIGINT,
	@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 @rStoreLocationId BIGINT
        SELECT @rStoreLocationId = ISNULL(ItemValue,0)
	    FROM sConfig.tConfigurationSetup 
	    WHERE ConfigurationId  = 542 AND SourceId = @rUserId
	    
		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 ((PR.LocationId = @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 ((PR.LocationId = @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 TRANSACTION
    
    DECLARE @ErrorMessage NVARCHAR(4000);  
    DECLARE @ErrorSeverity INT;  
    DECLARE @ErrorState INT;  
    SELECT   
       @ErrorMessage = ERROR_MESSAGE(),  
       @ErrorSeverity = ERROR_SEVERITY(),  
       @ErrorState = ERROR_STATE();  
    RAISERROR (@ErrorMessage, @ErrorSeverity, @ErrorState);  
    
	END CATCH  		  
END
GO
PRINT N'Altering Procedure [sPurchase].[pPurchaseScreenGet]...';


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

	BEGIN CATCH
    IF @@TRANCOUNT > 0
        ROLLBACK TRANSACTION
    
    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].[pPurchaseStatusGet]...';


GO

ALTER PROCEDURE [sPurchase].[pPurchaseStatusGet]
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
		SELECT Id,
			   Title
		FROM   [sWf].[tWfStatusMaster] (NOLOCK) 
		WHERE  IsObsolete = 0
	END TRY

	BEGIN CATCH
    IF @@TRANCOUNT > 0
        ROLLBACK TRANSACTION
    
    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].[pPurchaseStoreLocationMasterGet]...';


GO

--exec [sPurchase].[pPurchaseStoreLocationMasterGet] 9911
ALTER PROCEDURE [sPurchase].[pPurchaseStoreLocationMasterGet]
	@rOrgGroupId INT
	--,
	--@rIsWildCardSearch [bit] = 1

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
    BEGIN TRY
	--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.OrgGroupId = @rOrgGroupId)  
		 AND SLM.IsObsolete = 0
		--((SLM.Id = @rId) OR (ISNULL(@rId,0) = 0))
	 --  AND ((SLM.Title LIKE @rTitle) OR (ISNULL(@rTitle, '') = ''))
	 --  AND ((SLM.Code LIKE @rCode) OR (ISNULL(@rCode, '') = ''))	  
	 END TRY 
	 BEGIN CATCH 
		ROLLBACK TRANSACTION

		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

SET ANSI_NULLS ON
GO
PRINT N'Altering Procedure [sPurchase].[pPurchaseVendorMasterGet]...';


GO

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

BEGIN
	BEGIN TRY
			DECLARE @rStoreLocationId BIGINT
			SELECT @rStoreLocationId = ISNULL(ItemValue,0)
			FROM sConfig.tConfigurationSetup 
			WHERE ConfigurationId  = 542 AND SourceId = @rUserId

		 --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 
	   AND VM.LocationId = @rStoreLocationId
	END TRY

	BEGIN CATCH
    IF @@TRANCOUNT > 0
        ROLLBACK TRANSACTION
    
    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
	    DECLARE @rStoreLocationId BIGINT
        SELECT @rStoreLocationId = ISNULL(ItemValue,0)
	    FROM sConfig.tConfigurationSetup 
	    WHERE ConfigurationId  = 542 AND SourceId = @rUserId

		IF(@rId > 0)
		BEGIN
		   IF NOT EXISTS(SELECT Id FROM sPurchase.tQualityCheck WHERE Id = @rId AND CreatedUserId = @rUserId AND LocationId = @rStoreLocationId AND OrgGroupId = @rOrgGroupId AND IsObsolete = 0)
		   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  AND GRN.LocationId = @rStoreLocationId AND GRN.OrgGroupId = @rOrgGroupId AND GRN.IsObsolete = 0
			INNER JOIN [sPurchase].[tQualityCheck] QC ON GRN.Id = QC.GoodsReceivedNoteId  AND QC.LocationId = @rStoreLocationId AND QC.OrgGroupId = @rOrgGroupId AND QC.IsObsolete = 0
			WHERE QC.Id = @rId  AND QC.LocationId = @rStoreLocationId AND QC.OrgGroupId = @rOrgGroupId AND QC.IsObsolete = 0)
			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 LocationId = @rStoreLocationId AND OrgGroupId = @rOrgGroupId AND IsObsolete = 0

				DELETE FROM sPurchase.tQualityCheckDetail
				WHERE Id NOT IN(SELECT Id FROM @rDetailList)
				AND QualityCheckId = @rId AND OrgGroupId = @rOrgGroupId

				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 AND QC.OrgGroupId = @rOrgGroupId
				WHERE QC.QualityCheckId = @rId AND QC.OrgGroupId = @rOrgGroupId

				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 AND QC.OrgGroupId = @rOrgGroupId
				WHERE QC.QualityCheckId = @rId AND QC.OrgGroupId = @rOrgGroupId)

				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 AND QC.OrgGroupId = @rOrgGroupId
				WHERE QC.QualityCheckId = @rId AND QC.OrgGroupId = @rOrgGroupId))
				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 
			AND GRN.LocationId = @rStoreLocationId AND GRN.OrgGroupId = @rOrgGroupId AND GRN.IsObsolete = 0
			INNER JOIN [sPurchase].[tQualityCheck] QC ON GRN.Id = QC.GoodsReceivedNoteId 
			AND QC.LocationId = @rStoreLocationId AND QC.OrgGroupId = @rOrgGroupId AND QC.IsObsolete = 0
			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,
					@rStoreLocationId, 		 
					@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'
 					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 = @rId
 					--FOR XML AUTO, ROOT('Table'), ELEMENTS
 					FOR XML PATH('StockInward'), ROOT('Table')
 				);

				SELECT @rId
				-- Print or use @XmlString as needed
				--PRINT CONVERT(NVARCHAR(MAX), @XmlString);
				DECLARE @str NVARCHAR(MAX) = CAST(@XmlString AS NVARCHAR(MAX))
				DECLARE @inwardDate DATETIME 
				SET @inwardDate = GETUTCDATE()
				DECLARE @result INT 
				EXEC sProcurement.pStockInwardAdd_New @rOrgGroupId,'',0,@rRequestedBy,@rStoreLocationId,'Inward By Quality Check',@rUserId,@str,@rStoreLocationId,@rOrgGroupId,0,@inwardDate,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

				
			END
			SELECT -101;
		END
	COMMIT TRANSACTION	
	END TRY

	BEGIN CATCH
    IF @@TRANCOUNT > 0
        ROLLBACK TRANSACTION

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


GO



ALTER PROCEDURE [sPurchase].[pQualityCheckDelete]
		@rId BIGINT,
		@rStatusId SMALLINT
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
	BEGIN TRANSACTION
		IF(@rId > 0)
		BEGIN
			UPDATE sPurchase.tQualityCheck
			SET 
				StatusId = @rStatusId,
				IsObsolete = 1,
				DeletedDateTime = GETUTCDATE()
			WHERE Id = @rId AND IsObsolete = 0

			IF EXISTS(SELECT Id FROM sPurchase.tQualityCheckDetail WHERE QualityCheckId = @rId)
			BEGIN
				DELETE FROM sPurchase.tQualityCheckDetail
				WHERE QualityCheckId = @rId
			END
			SELECT 1
		END
	COMMIT TRANSACTION
	END TRY

	BEGIN CATCH
    IF @@TRANCOUNT > 0
        ROLLBACK TRANSACTION

    
    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,
	  @rUserId BIGINT,
	  @rOrgGroupId INT
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
	    DECLARE @rStoreLocationId BIGINT
        SELECT @rStoreLocationId = ISNULL(ItemValue,0)
	    FROM sConfig.tConfigurationSetup 
	    WHERE ConfigurationId  = 542 AND SourceId = @rUserId
	    
		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 
		AND GRN.LocationId = @rStoreLocationId AND GRN.OrgGroupId = @rOrgGroupId AND GRN.IsObsolete = 0
		LEFT JOIN [sWf].[tWfStatusMaster] SM ON SM.Id = QC.StatusId
		WHERE  QC.Id=@rId AND QC.IsObsolete = 0
		       AND QC.LocationId = @rStoreLocationId
			   AND QC.OrgGroupId = @rOrgGroupId

		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.LocationId = @rStoreLocationId AND QCC.OrgGroupId = @rOrgGroupId AND QCC.IsObsolete = 0  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.LocationId = @rStoreLocationId AND QC1.OrgGroupId = @rOrgGroupId AND QC1.IsObsolete = 0 
						WHERE QC1.GoodsReceivedNoteId = QC.GoodsReceivedNoteID AND QCD1.StockItemId = QCD.StockItemId AND QC1.IsObsolete = 0 
						AND QC1.LocationId = @rStoreLocationId AND QC1.OrgGroupId = @rOrgGroupId
						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 
			   AND QC.LocationId = @rStoreLocationId AND QC.OrgGroupId = @rOrgGroupId
			   INNER JOIN	sIp.tStockItemMaster SIM	ON SIM.Id = QCD.StockItemId  AND SIM.IsObsolete = 0 
			   AND SIM.StoreLocationId = @rStoreLocationId AND SIM.OrgGroupId = @rOrgGroupId 
			   LEFT JOIN [sIp].[tStockItemCategoryMaster] SCM ON SCM.Id = SIM.StockItemCategoryId
			   INNER JOIN  sFinanceCommon.tStockUomMaster SUMa ON SUMa.Id = SIM.IssueStockUomId
		WHERE  QCD.QualityCheckId=@rId AND QC.IsObsolete = 0
		       AND QC.LocationId = @rStoreLocationId
			   AND QC.OrgGroupId = @rOrgGroupId

	END TRY

	BEGIN CATCH
    IF @@TRANCOUNT > 0
        ROLLBACK TRANSACTION
    
    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 = '',
	@rStartDate DATETIME = NULL,
	@rEndDate DATETIME = NULL,
	@rOrgGroupId INT,
	@rPageNo INT,
	@rPageSize INT,
	@rStatusId SMALLINT = 0,
	@rUserId BIGINT

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	    DECLARE @rStoreLocationId BIGINT
        SELECT @rStoreLocationId = ISNULL(ItemValue,0)
	    FROM sConfig.tConfigurationSetup 
	    WHERE ConfigurationId  = 542 AND SourceId = @rUserId

		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 ((QC.LocationId = @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 ((QC.LocationId = @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 TRANSACTION
    
    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 TRANSACTION
    
    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].[pQuotationRequestDelete]...';


GO



ALTER PROCEDURE [sPurchase].[pQuotationRequestDelete]
		@rId BIGINT,
		@rStatusId INT
 
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
	BEGIN TRANSACTION
		IF(@rId > 0)
		BEGIN
			UPDATE sPurchase.tQuotationRequest
			SET 
				StatusId = @rStatusId,
				IsObsolete = 1,		
				DeletedDateTime = GETUTCDATE()
			WHERE Id = @rId AND IsObsolete = 0

			IF EXISTS(SELECT Id FROM sPurchase.tQuotationRequestDetail WHERE QuotationRequestId = @rId)
			BEGIN
				DELETE FROM sPurchase.tQuotationRequestDetail
				WHERE QuotationRequestId = @rId
			END
			SELECT 1
		END
	COMMIT TRANSACTION	
	END TRY

	BEGIN CATCH
    IF @@TRANCOUNT > 0
        ROLLBACK TRANSACTION

    
    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,
	  @rUserId BIGINT,
	  @rOrgGroupId INT
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
	    DECLARE @rStoreLocationId BIGINT
        SELECT @rStoreLocationId = ISNULL(ItemValue,0)
	    FROM sConfig.tConfigurationSetup 
	    WHERE ConfigurationId  = 542 AND SourceId = @rUserId

		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 AND VM.LocationId = @rStoreLocationId AND VM.OrgGroupId = @rOrgGroupId AND VM.IsObsolete = 0 
			   LEFT JOIN [sWf].[tWfStatusMaster] SM ON SM.Id = QR.StatusId
			   LEFT JOIN [sPurchase].[tPurchaseRequest] PR ON PR.Id = QR.PurchaseRequestId AND PR.LocationId = @rStoreLocationId AND PR.OrgGroupId = @rOrgGroupId AND PR.IsObsolete = 0 

		WHERE  QR.Id=@rId AND QR.IsObsolete = 0
		       AND QR.LocationId = @rStoreLocationId
			   AND QR.OrgGroupId = @rOrgGroupId

		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.LocationId = @rStoreLocationId AND QR.OrgGroupId = @rOrgGroupId AND QR.IsObsolete = 0
			   INNER JOIN	sIp.tStockItemMaster SIM	ON SIM.Id = QRD.StockItemId AND SIM.StoreLocationId = @rStoreLocationId AND SIM.OrgGroupId = @rOrgGroupId AND SIM.IsObsolete = 0 
			   LEFT JOIN [sIp].[tStockItemCategoryMaster] SCM ON SCM.Id = SIM.StockItemCategoryId
			   INNER JOIN  sFinanceCommon.tStockUomMaster SUMa ON SUMa.Id = SIM.IssueStockUomId
		WHERE  QRD.QuotationRequestId=@rId AND QR.IsObsolete = 0 
		       AND QR.LocationId = @rStoreLocationId
			   AND QR.OrgGroupId = @rOrgGroupId

	END TRY

	BEGIN CATCH
    IF @@TRANCOUNT > 0
        ROLLBACK TRANSACTION
    
    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,
	@rUserId BIGINT

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	    DECLARE @rStoreLocationId BIGINT
        SELECT @rStoreLocationId = ISNULL(ItemValue,0)
	    FROM sConfig.tConfigurationSetup 
	    WHERE ConfigurationId  = 542 AND SourceId = @rUserId

		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.tQuotationRequest QR (NOLOCK)

		WHERE 
				((QR.Number LIKE @rNumber+'%') OR (ISNULL(@rNumber,'') = ''))
   				AND ((QR.Name LIKE @rName+'%') OR (ISNULL(@rName,'') = ''))
				AND ((QR.LocationId = @rStoreLocationId) OR (@rStoreLocationId = 0))
   				AND ((QR.OrgGroupId = @rOrgGroupId) OR (@rOrgGroupId=0))
				AND ((QR.StatusId = @rStatusId) OR (ISNULL(@rStatusId,0)=0))
				AND QR.IsObsolete = 0
				AND ((CAST(QR.CreatedDateTime AS DATE) >= CAST(@rStartDate AS DATE)) OR (ISNULL(@rStartDate,'')=''))
				AND((CAST(QR.CreatedDateTime AS DATE) <= CAST(@rEndDate AS DATE)) OR (ISNULL(@rEndDate,'')=''))


		SELECT t.* FROM (
			SELECT ROW_NUMBER() OVER (
			ORDER BY QR.Id DESC  
			) AS 'RowNum',QR.Id, 
				QR.Number,
				QR.Name AS RequestedBy,
				QR.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.LocationId = @rStoreLocationId) OR (@rStoreLocationId = 0))
   				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 TRANSACTION
    
    DECLARE @ErrorMessage NVARCHAR(4000);  
    DECLARE @ErrorSeverity INT;  
    DECLARE @ErrorState INT;  
    SELECT   
       @ErrorMessage = ERROR_MESSAGE(),  
       @ErrorSeverity = ERROR_SEVERITY(),  
       @ErrorState = ERROR_STATE();  
    RAISERROR (@ErrorMessage, @ErrorSeverity, @ErrorState);  
    
	END CATCH  		  
END
GO
PRINT N'Altering Procedure [sPurchase].[pQuotationVendorGet]...';


GO

 
--exec [sPurchase].[pQuotationVendorGet] 991100010
ALTER PROCEDURE [sPurchase].[pQuotationVendorGet]
	
		 @rQuotationRequestId BIGINT,
	     @rUserId BIGINT,
	     @rOrgGroupId INT
		 --,
	 	-- @rTemplate nvarchar(max)
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
        BEGIN TRY
        DECLARE @rStoreLocationId BIGINT
        SELECT @rStoreLocationId = ISNULL(ItemValue,0)
	    FROM sConfig.tConfigurationSetup 
	    WHERE ConfigurationId  = 542 AND SourceId = @rUserId

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

	    SELECT  @rDescription = ISNULL(QR.Description,''),
				@rStartDate = ISNULL(QR.StartDate,''),
				@rEndDate = ISNULL(QR.EndDate,''),
				@rBidOpen = ISNULL(QR.BidOpen,''),
				@rBidClose = ISNULL(QR.BidClose,''),
				@rPersonContact = ISNULL(QR.PersonContact,''),
				@rEmail = ISNULL(QR.Email,''),
				@rRFQDate = ISNULL(QR.RFQDate,'')
		FROM   [sPurchase].[tQuotationRequest] QR(NOLOCK) 
			   LEFT JOIN sProcurement.tVendorMaster  VM ON QR.VendorId = VM.ID AND VM.OrgGroupId = @rOrgGroupId AND VM.LocationId = @rStoreLocationId AND VM.IsObsolete = 0
			   LEFT JOIN [sWf].[tWfStatusMaster] SM ON SM.Id = QR.StatusId
			   LEFT JOIN [sPurchase].[tPurchaseRequest] PR ON PR.Id = QR.PurchaseRequestId AND PR.LocationId = @rStoreLocationId AND PR.OrgGroupId = @rOrgGroupId AND PR.IsObsolete = 0
		WHERE  QR.Id = @rQuotationRequestId AND QR.IsObsolete = 0
		       AND QR.LocationId = @rStoreLocationId
			   AND QR.OrgGroupId = @rOrgGroupId

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

	SELECT @HTMLTable = @HTMLTable+'<tr><td>'+CAST(SIM.Code AS NVARCHAR(100))+'</td><td>'
	+SIM.Title+'</td><td>'+SUMa.Code+'</td><td>'+CAST(QRD.RequestedQty AS NVARCHAR(100))+
	+'</td><td>'+CAST(QRD.TargetPrice AS NVARCHAR(100))+'</td><td>'+QRD.Remark+'</td></tr>'
	  FROM   [sPurchase].[tQuotationRequestDetail] QRD (NOLOCK)
		INNER JOIN	sPurchase.tQuotationRequest QR	ON QR.Id = QRD.QuotationRequestId AND QR.LocationId = @rStoreLocationId AND QR.OrgGroupId = @rOrgGroupId AND QR.IsObsolete = 0
		INNER JOIN	sIp.tStockItemMaster SIM ON SIM.Id = QRD.StockItemId AND SIM.StoreLocationId = @rStoreLocationId AND SIM.OrgGroupId = @rOrgGroupId AND SIM.IsObsolete = 0
		INNER JOIN  sFinanceCommon.tStockUomMaster SUMa ON SUMa.Id = SIM.IssueStockUomId
		WHERE  QR.Id = @rQuotationRequestId AND QR.IsObsolete = 0
		AND QR.LocationId = @rStoreLocationId
	    AND QR.OrgGroupId = @rOrgGroupId

    --PRINT @HTMLTable;
	DECLARE @txtMessage NVARCHAR(MAX)
    SELECT @txtMessage=REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(Template, 
		'{Description}' , @rDescription),
		'{StartDate}' , @rStartDate),
		'{EndDate}' , @rEndDate),
		'{BidOpen}' , @rBidOpen),
		'{BidClose}' , @rBidClose),
		'{PersonContact}' , @rPersonContact),
		'{Email}' , @rEmail),
		'{RFQDate}' , @rRFQDate),
		'{QuatationDetails}' , @HTMLTable)FROM sPurchase.tPurchaseReportTemplate WHERE id = 1

		DECLARE @VendorId BIGINT
		SELECT @VendorId = QR.VendorId FROM sPurchase.tQuotationRequest QR WHERE QR.Id = @rQuotationRequestId AND QR.IsObsolete = 0 AND QR.LocationId = @rStoreLocationId
		AND QR.OrgGroupId = @rOrgGroupId
	
	SELECT 
			--A.AcademicId,
			A.Code,
			A.Name,
			A.ParentContactNo AS MobileNo,	
			A.ParentEmail AS EmailId,
			@txtMessage	AS MsgText,
			'' AS Subject,
			 2001 AS ReceiverSourceTypeId,
			 (SELECT Id FROM sSetup.tOrganizationMaster WHERE OrgGroupId=A.OrgGroupId AND Id = A.OrgGroupId) AS OrgId,
			 A.OrgGroupId AS OrgGroupId,
			 --A.AcademicId AS ReceiverSourceId,
			 A.Id AS SourceId,
			 2001 AS SourceTypeId,
			 --DM.Title AS MeetingType,
			 --CONVERT(varchar(11),ISNULL(OM.StartDate,'') ,103) AS StartDate,
			 --CONVERT(varchar(11),ISNULL(OM.EndDate,'') ,103) AS EndDate,
			 --EE.EmployeeName AS Teacher,
			 --OM.Title AS Title,
			 A.WhatsAppContactNo
	FROM 
		 [sPurchase].[tQuotationRequestDetail] QRD (NOLOCK)
		INNER JOIN	sPurchase.tQuotationRequest QR	ON QR.Id = QRD.QuotationRequestId AND QR.LocationId = @rStoreLocationId AND QR.OrgGroupId = @rOrgGroupId AND QR.IsObsolete = 0
		INNER JOIN	sIp.tStockItemMaster SIM ON SIM.Id = QRD.StockItemId AND SIM.StoreLocationId = @rStoreLocationId AND SIM.OrgGroupId = @rOrgGroupId AND SIM.IsObsolete = 0 
		INNER JOIN  sFinanceCommon.tStockUomMaster SUMa ON SUMa.Id = SIM.IssueStockUomId
		INNER JOIN (
			SELECT	VM.Id,
					VM.ContactPersonName AS Name,
					VM.Code,
					VM.PhoneNumberOffice AS ParentContactNo,
					VM.Email AS ParentEmail,
					VM.OrgGroupId,
					VM.PhoneNumberMobile WhatsAppContactNo		
			FROM	sProcurement.tVendorMaster  VM
			LEFT JOIN   sProcurement.tVendorCategoryMaster VC
			ON  VM.VendorCategoryId = VC.Id 
			WHERE VM.Id = @VendorId AND VM.LocationId = @rStoreLocationId AND VM.OrgGroupId = @rOrgGroupId AND VM.IsObsolete = 0
		) AS A ON A.Id = QR.VendorId
		WHERE  QR.Id = @rQuotationRequestId AND QR.IsObsolete = 0
		       AND QR.LocationId = @rStoreLocationId
			   AND QR.OrgGroupId = @rOrgGroupId
	   END TRY
	   BEGIN CATCH 
		ROLLBACK TRANSACTION

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


GO



ALTER PROCEDURE [sPurchase].[pSalesReturnDelete]
		@rId BIGINT,
		@rStatusId SMALLINT
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
	BEGIN TRANSACTION
		IF(@rId > 0)
		BEGIN
			UPDATE sPurchase.tSalesReturn
			SET 
				StatusId = @rStatusId,
				IsObsolete = 1,
				DeletedDateTime = GETUTCDATE()
			WHERE Id = @rId AND IsObsolete = 0

			IF EXISTS(SELECT Id FROM sPurchase.tSalesReturnDetail WHERE SalesReturnId = @rId)
			BEGIN
				DELETE FROM sPurchase.tSalesReturnDetail
				WHERE SalesReturnId = @rId
			END
			SELECT 1
		END
	COMMIT TRANSACTION
	END TRY

	BEGIN CATCH
    IF @@TRANCOUNT > 0
        ROLLBACK TRANSACTION

    
    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,
	  @rUserId BIGINT,
	  @rOrgGroupId INT
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
	    DECLARE @rStoreLocationId BIGINT
        SELECT @rStoreLocationId = ISNULL(ItemValue,0)
	    FROM sConfig.tConfigurationSetup 
	    WHERE ConfigurationId  = 542 AND SourceId = @rUserId

		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,
				ISNULL(PO.RefNumber,'') AS PurchaseOrderNumber
		FROM   [sPurchase].[tSalesReturn] SR(NOLOCK) 
		LEFT JOIN [sPurchase].[tGoodsReceivedNote] GRN ON GRN.Id = SR.GoodsReceivedNoteID 
			  AND GRN.LocationId = @rStoreLocationId AND GRN.OrgGroupId = @rOrgGroupId AND GRN.IsObsolete = 0
		LEFT JOIN sPurchase.tPurchaseOrder PO ON PO.Id = SR.PurchaseOrderId 
			  AND PO.LocationId = @rStoreLocationId AND PO.OrgGroupId = @rOrgGroupId AND PO.IsObsolete = 0
		LEFT JOIN [sWf].[tWfStatusMaster] SM ON SM.Id = SR.StatusId
		LEFT JOIN  sProcurement.tVendorMaster  VM ON SR.VendorId = VM.ID 
			  AND VM.LocationId = @rStoreLocationId AND VM.OrgGroupId = @rOrgGroupId AND VM.IsObsolete = 0
		WHERE  SR.Id=@rId AND SR.LocationId = @rStoreLocationId AND SR.OrgGroupId = @rOrgGroupId 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 AND QC1.LocationId = @rStoreLocationId 
					AND QC1.OrgGroupId = @rOrgGroupId AND QC1.IsObsolete = 0) AS GRNRejectedQty
		FROM   [sPurchase].[tSalesReturnDetail] SRD (NOLOCK)
			   INNER JOIN	sPurchase.tSalesReturn SR	ON SR.Id = SRD.SalesReturnId 
				      AND SR.LocationId = @rStoreLocationId AND SR.OrgGroupId = @rOrgGroupId AND SR.IsObsolete = 0
			   INNER JOIN	sIp.tStockItemMaster SIM	ON SIM.Id = SRD.StockItemId 
					  AND SIM.StoreLocationId = @rStoreLocationId AND SIM.OrgGroupId = @rOrgGroupId AND SIM.IsObsolete = 0 
			   LEFT JOIN [sIp].[tStockItemCategoryMaster] SCM ON SCM.Id = SIM.StockItemCategoryId
			   INNER JOIN  sFinanceCommon.tStockUomMaster SUMa ON SUMa.Id = SIM.IssueStockUomId
		WHERE  SRD.SalesReturnId=@rId AND SR.LocationId = @rStoreLocationId AND SR.OrgGroupId = @rOrgGroupId AND SR.IsObsolete = 0
	END TRY

	BEGIN CATCH
    IF @@TRANCOUNT > 0
        ROLLBACK TRANSACTION
    
    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 = '',
	@rStartDate DATETIME = NULL,
	@rEndDate DATETIME = NULL,
	@rOrgGroupId INT,
    @rPageNo INT,
	@rPageSize INT,
	@rStatusId SMALLINT = NULL,
	@rUserId BIGINT

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	    DECLARE @rStoreLocationId BIGINT
        SELECT @rStoreLocationId = ISNULL(ItemValue,0)
	    FROM sConfig.tConfigurationSetup 
	    WHERE ConfigurationId  = 542 AND SourceId = @rUserId

		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 ((SR.LocationId = @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 ((SR.LocationId = @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 TRANSACTION
    
    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].[pSearchScreenDependencyGet]...';


GO


ALTER PROCEDURE [sPurchase].[pSearchScreenDependencyGet]
	  @rScreenId INT
AS
SET NOCOUNT ON

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

	BEGIN CATCH
    IF @@TRANCOUNT > 0
        ROLLBACK TRANSACTION
    
    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].[pStockBatchAddModify]...';


GO
--exec [sPurchase].[pStockBatchAddModify] 9911,991100001,991100001,100,'+',9911000000270
ALTER PROCEDURE [sPurchase].[pStockBatchAddModify]
	@rOrgGroupId INT, 
	@rStoreLocationId INT = 0,
	@rStockItemId INT = 0,
	@rQuantity DECIMAL(12,2) = 0.00,
	@rOperation NVARCHAR(20),
	@rUserId BIGINT
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

       DECLARE @1AvailableQuantity DECIMAL(12,2) 

BEGIN      
    BEGIN TRY
    IF EXISTS(SELECT Id FROM sProcurement.tStockBatch WHERE Id = @rStockItemId)
	BEGIN
		IF(@rOperation = '+')
		BEGIN
			 UPDATE  sProcurement.tStockBatch
			 SET  AvailableQuantity = ISNULL(AvailableQuantity,0) + @rQuantity,
				  UpdatedUserId = @rUserId,
				  UpdatedDateTime = sCommon.fGetDate()
			 FROM sProcurement.tStockBatch
			 WHERE  
			(StoreLocationId = @rStoreLocationId OR @rStoreLocationId = 0) AND
			(StockItemId = @rStockItemId OR @rStockItemId = 0) AND
			--(Number = @rNumber OR ISNULL(@rNumber, '') = '') AND
			--(ExpiryDate = @rExpiryDate OR ISNULL(@rExpiryDate, '') = '') AND
			 OrgGroupId = @rOrgGroupId
		END
		ELSE
		BEGIN
			UPDATE  sProcurement.tStockBatch
			 SET  AvailableQuantity = ISNULL(AvailableQuantity,0) - @rQuantity,
				  UpdatedUserId = @rUserId,
				  UpdatedDateTime = sCommon.fGetDate()
			 FROM sProcurement.tStockBatch
			 WHERE  
			(StoreLocationId = @rStoreLocationId OR @rStoreLocationId = 0) AND
			(StockItemId = @rStockItemId OR @rStockItemId = 0) AND
			--(Number = @rNumber OR ISNULL(@rNumber, '') = '') AND
			--(ExpiryDate = @rExpiryDate OR ISNULL(@rExpiryDate, '') = '') AND
			 OrgGroupId = @rOrgGroupId
		END
	END
	END TRY
	BEGIN CATCH 
		ROLLBACK TRANSACTION

		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,9911000000270,991100017,'','',0,1
ALTER PROCEDURE [sPurchase].[pStockItemMasterGetWithCategory]
    @rOrgGroupId INT,
	@rUserId BIGINT,
	@rId INT = 0,
	@rCode NVARCHAR(100),  
	@rTitle NVARCHAR(100),  
	@rIsAbsoluteTitle BIT = 0,
	@rIsWildCardSearch BIT = 1
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
    BEGIN TRY
    DECLARE @rStoreLocationId BIGINT
    SELECT @rStoreLocationId = ISNULL(ItemValue,0)
	FROM sConfig.tConfigurationSetup 
	WHERE ConfigurationId  = 542 AND SourceId = @rUserId
    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.StoreLocationId = @rStoreLocationId) OR (@rStoreLocationId = 0))
   		AND ((SIM.OrgGroupId = @rOrgGroupId) OR (@rOrgGroupId=0))
		AND SIM.IsObsolete= 0
	END TRY
	BEGIN CATCH 
		ROLLBACK TRANSACTION

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


GO
--exec [sPurchase].[pStockItemMasterSearchGet] 9911000000270,991100001,''
ALTER PROCEDURE [sPurchase].[pStockItemMasterSearchGet]
	@rUserId BIGINT,
	@rOrgGroupId INT,
	@rCurrentAlphabet NVARCHAR(10) 

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
    BEGIN TRY
    DECLARE @rStoreLocationId BIGINT
    SELECT @rStoreLocationId = ISNULL(ItemValue,0)
	FROM sConfig.tConfigurationSetup 
	WHERE ConfigurationId  = 542 AND SourceId = @rUserId
		 
	SELECT
			Id,
			Code,
			Title FROM sIp.tStockItemMaster SIM
	   
	  WHERE  
		 ((Title LIKE @rCurrentAlphabet + '%') OR (ISNULL(@rCurrentAlphabet,'')=''))
	     AND IsObsolete= 0 
	     AND SIM.StoreLocationId = @rStoreLocationId
	     AND SIM.OrgGroupId = @rOrgGroupId 
	END TRY
	BEGIN CATCH 
		ROLLBACK TRANSACTION

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


GO
ALTER 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
    BEGIN TRY

	--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 TRY
	BEGIN CATCH 
		ROLLBACK TRANSACTION

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


GO
ALTER 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
    BEGIN TRY

	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 TRY
	BEGIN CATCH 
		ROLLBACK TRANSACTION

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


GO

ALTER PROCEDURE [sPurchase].[pStudentProfileGet]
@rAcademicId BIGINT,
@rbatchId INT
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
    IF @@TRANCOUNT > 0
        ROLLBACK TRANSACTION
    
    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].[pValidateCloudStorage]...';


GO



ALTER PROCEDURE [sPurchase].[pValidateCloudStorage]
	  @rOrgGroupId SMALLINT
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
		 SELECT ISNULL(SUM(UD.DocumentSize),0) 
		 FROM sCommon.tUploadDocument UD (NOLOCK)
		 INNER JOIN sSetup.tOrgGroupBatchMaster OGBM 
		 ON OGBM.Id = UD.OrgGroupBatchId 
		 WHERE OGBM.OrgGroupId = @rOrgGroupId
	END TRY

	BEGIN CATCH
    IF @@TRANCOUNT > 0
        ROLLBACK TRANSACTION
    
    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].[pVendorNotificationGet]...';


GO

 
--exec [sPurchase].[pVendorNotificationGet] 991100022,'',9911
ALTER PROCEDURE [sPurchase].[pVendorNotificationGet]
		 @rQuotationRequestId BIGINT,
		 @rNotificationLink NVARCHAR(1000),
		 @rOrgId SMALLINT,
	     @rUserId BIGINT,
	     @rOrgGroupId INT

	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
 BEGIN
        BEGIN TRY
        DECLARE @rStoreLocationId BIGINT
        SELECT @rStoreLocationId = ISNULL(ItemValue,0)
	    FROM sConfig.tConfigurationSetup 
	    WHERE ConfigurationId  = 542 AND SourceId = @rUserId

		DECLARE @VendorId BIGINT
		SELECT @VendorId = QR.VendorId FROM sPurchase.tQuotationRequest QR WHERE QR.Id = @rQuotationRequestId AND QR.LocationId = @rStoreLocationId AND QR.OrgGroupId = @rOrgGroupId AND QR.IsObsolete = 0

		SET @rNotificationLink = '<a href="'+@rNotificationLink+'" target="_blank">'+@rNotificationLink+'</a>'
		    
	DECLARE @txtMessage NVARCHAR(MAX)
    SELECT @txtMessage=REPLACE(REPLACE(Template, 
		'[VendorName]' , (SELECT VM.ContactPersonName AS Name	
						FROM	sProcurement.tVendorMaster  VM
						WHERE VM.Id = @VendorId AND VM.LocationId = @rStoreLocationId AND VM.OrgGroupId = @rOrgGroupId AND VM.IsObsolete = 0)),
		'[NotificationLink]' , @rNotificationLink) FROM sAlert.tEventTemplate WHERE IsAutoSend = 1 AND OrgId = @rOrgId AND EventId = 158
	
	SELECT 
			--A.AcademicId,
			A.Code,
			A.Name,
			A.ParentContactNo AS MobileNo,	
			A.ParentEmail AS EmailId,
			@txtMessage	AS MsgText,
			'' AS Subject,
			 2001 AS ReceiverSourceTypeId,
			 (SELECT Id FROM sSetup.tOrganizationMaster WHERE OrgGroupId=A.OrgGroupId AND Id = A.OrgGroupId) AS OrgId,
			 A.OrgGroupId AS OrgGroupId,
			 A.Id AS ReceiverSourceId,
			 A.Id AS SourceId,
			 2001 AS SourceTypeId,
			 --DM.Title AS MeetingType,
			 --CONVERT(varchar(11),ISNULL(OM.StartDate,'') ,103) AS StartDate,
			 --CONVERT(varchar(11),ISNULL(OM.EndDate,'') ,103) AS EndDate,
			 --EE.EmployeeName AS Teacher,
			 --OM.Title AS Title,
			 A.WhatsAppContactNo
	FROM 
		 [sPurchase].[tQuotationRequestDetail] QRD (NOLOCK)
		INNER JOIN	sPurchase.tQuotationRequest QR	ON QR.Id = QRD.QuotationRequestId   AND QR.LocationId = @rStoreLocationId AND QR.OrgGroupId = @rOrgGroupId AND QR.IsObsolete = 0
		INNER JOIN	sIp.tStockItemMaster SIM	ON SIM.Id = QRD.StockItemId  AND SIM.StoreLocationId = @rStoreLocationId AND SIM.OrgGroupId = @rOrgGroupId AND SIM.IsObsolete = 0 
		INNER JOIN  sFinanceCommon.tStockUomMaster SUMa ON SUMa.Id = SIM.IssueStockUomId
		INNER JOIN (
			SELECT	VM.Id,
					VM.ContactPersonName AS Name,
					VM.Code,
					VM.PhoneNumberOffice AS ParentContactNo,
					VM.Email AS ParentEmail,
					VM.OrgGroupId,
					VM.PhoneNumberMobile WhatsAppContactNo		
			FROM	sProcurement.tVendorMaster  VM
			LEFT JOIN   sProcurement.tVendorCategoryMaster VC
			ON  VM.VendorCategoryId = VC.Id
			WHERE VM.Id = @VendorId AND VM.LocationId = @rStoreLocationId AND VM.OrgGroupId = @rOrgGroupId AND VM.IsObsolete = 0
		) AS A ON A.Id = QR.VendorId
		WHERE  QR.Id = @rQuotationRequestId AND QR.IsObsolete = 0
		       AND QR.LocationId = @rStoreLocationId
			   AND QR.OrgGroupId = @rOrgGroupId
	 END TRY
	 BEGIN CATCH 
		ROLLBACK TRANSACTION

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


GO

--exec [sWf].[pWfApprovalAdd] 0,991100029, 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

	DECLARE @rUserId BIGINT
	SET @rUserId = @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,
			@lActionByEmployeeId,
			@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
		DECLARE @rStoreLocationId BIGINT
		SELECT @rStoreLocationId = ISNULL(ItemValue,0)
		FROM sConfig.tConfigurationSetup 
		WHERE ConfigurationId  = 542 AND SourceId = @rUserId

		IF(@rDocSourceTypeId = 2040)
		BEGIN
			UPDATE sPurchase.tPurchaseRequest 
			SET StatusId = @StatusId,
				UpdatedUserId = @rActionEmployeeId,
				UpdatedDateTime = GETUTCDATE()
			WHERE Id = @rDocSourceId AND OrgGroupId = @rOrgGroupId AND LocationId = @rStoreLocationId AND IsObsolete = 0
		END
		ELSE IF(@rDocSourceTypeId = 2041)
		BEGIN
			UPDATE sPurchase.tQuotationRequest 
			SET StatusId = @StatusId,
				UpdatedUserId = @rActionEmployeeId,
				UpdatedDateTime = GETUTCDATE()
			WHERE Id = @rDocSourceId AND OrgGroupId = @rOrgGroupId AND LocationId = @rStoreLocationId AND IsObsolete = 0
		END
		ELSE IF(@rDocSourceTypeId = 2042)
		BEGIN
			UPDATE sPurchase.tPurchaseOrder 
			SET StatusId = @StatusId,
				UpdatedUserId = @rActionEmployeeId,
				UpdatedDateTime = GETUTCDATE()
			WHERE Id = @rDocSourceId AND OrgGroupId = @rOrgGroupId AND LocationId = @rStoreLocationId AND IsObsolete = 0
		END
		ELSE IF(@rDocSourceTypeId = 2043)
		BEGIN
			UPDATE sPurchase.tGoodsReceivedNote 
			SET StatusId = @StatusId,
				UpdatedUserId = @rActionEmployeeId,
				UpdatedDateTime = GETUTCDATE()
			WHERE Id = @rDocSourceId AND OrgGroupId = @rOrgGroupId AND LocationId = @rStoreLocationId AND IsObsolete = 0
		END
		ELSE IF(@rDocSourceTypeId = 2044)
		BEGIN
			UPDATE sPurchase.tSalesReturn 
			SET StatusId = @StatusId,
				UpdatedUserId = @rActionEmployeeId,
				UpdatedDateTime = GETUTCDATE()
			WHERE Id = @rDocSourceId AND OrgGroupId = @rOrgGroupId AND LocationId = @rStoreLocationId AND IsObsolete = 0
		END
	END
	COMMIT TRANSACTION
	END TRY

	BEGIN CATCH
    IF @@TRANCOUNT > 0
        ROLLBACK TRANSACTION

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

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

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


GO


--exec [sWf].[pWfApprovalGet] 1,'2023-10-10','2024-02-02',0,9911,9911,'',9911000000270,1,10,0
 
ALTER  PROCEDURE [sWf].[pWfApprovalGet]
			 @rWfFunctionalityId SMALLINT = 0,
			 @rFromDate DATE = NULL,
			 @rToDate DATE = NULL,
			 @rStatusId SMALLINT = 0,
			 @rOrgId SMALLINT = 0,
			 @rOrgGroupId 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 @rStoreLocationId BIGINT
    SELECT @rStoreLocationId = ISNULL(ItemValue,0)
	FROM sConfig.tConfigurationSetup 
	WHERE ConfigurationId  = 542 AND SourceId = @rUserId

	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
	INNER 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))
	AND PR.LocationId = @rStoreLocationId AND PR.IsObsolete = 0
	AND PR.OrgGroupId = @rOrgGroupId
	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))
	AND PR.LocationId = @rStoreLocationId AND PR.IsObsolete = 0
	AND PR.OrgGroupId = @rOrgGroupId
	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))
	AND PR.LocationId = @rStoreLocationId AND PR.IsObsolete = 0
	AND PR.OrgGroupId = @rOrgGroupId
	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))
	AND PR.LocationId = @rStoreLocationId AND PR.IsObsolete = 0
	AND PR.OrgGroupId = @rOrgGroupId
	------------------------------------------------------------------------------------------------------------------------------------------------------------------
	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
	INNER 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))
	AND QR.LocationId = @rStoreLocationId AND QR.IsObsolete = 0
	AND QR.OrgGroupId = @rOrgGroupId
	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))
	AND QR.LocationId = @rStoreLocationId AND QR.IsObsolete = 0
	AND QR.OrgGroupId = @rOrgGroupId
	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))
	AND QR.LocationId = @rStoreLocationId AND QR.IsObsolete = 0
	AND QR.OrgGroupId = @rOrgGroupId
	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))
	AND QR.LocationId = @rStoreLocationId AND QR.IsObsolete = 0
	AND QR.OrgGroupId = @rOrgGroupId
	------------------------------------------------------------------------------------------------------------------------------------------------------------------
	

	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
	INNER 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))
	AND PO.LocationId = @rStoreLocationId AND PO.IsObsolete = 0
	AND PO.OrgGroupId = @rOrgGroupId
	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))
	AND PO.LocationId = @rStoreLocationId AND PO.IsObsolete = 0
	AND PO.OrgGroupId = @rOrgGroupId
	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))
	AND PO.LocationId = @rStoreLocationId AND PO.IsObsolete = 0
	AND PO.OrgGroupId = @rOrgGroupId
	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))
	AND PO.LocationId = @rStoreLocationId AND PO.IsObsolete = 0
	AND PO.OrgGroupId = @rOrgGroupId
	------------------------------------------------------------------------------------------------------------------------------------------------------------------

	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
	INNER 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))
	AND GRN.LocationId = @rStoreLocationId AND GRN.IsObsolete = 0
	AND GRN.OrgGroupId = @rOrgGroupId
	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))
	AND GRN.LocationId = @rStoreLocationId AND GRN.IsObsolete = 0
	AND GRN.OrgGroupId = @rOrgGroupId
	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))
	AND GRN.LocationId = @rStoreLocationId AND GRN.IsObsolete = 0
	AND GRN.OrgGroupId = @rOrgGroupId
	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))
	AND GRN.LocationId = @rStoreLocationId AND GRN.IsObsolete = 0
	AND GRN.OrgGroupId = @rOrgGroupId
	------------------------------------------------------------------------------------------------------------------------------------------------------------------
	
	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
	INNER 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))
	AND SR.LocationId = @rStoreLocationId AND SR.IsObsolete = 0
	AND SR.OrgGroupId = @rOrgGroupId
	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))
	AND SR.LocationId = @rStoreLocationId AND SR.IsObsolete = 0
	AND SR.OrgGroupId = @rOrgGroupId
	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))
	AND SR.LocationId = @rStoreLocationId AND SR.IsObsolete = 0
	AND SR.OrgGroupId = @rOrgGroupId
	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))
	AND SR.LocationId = @rStoreLocationId AND SR.IsObsolete = 0
	AND SR.OrgGroupId = @rOrgGroupId
	)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 TRANSACTION
    
    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].[pWfFunctionalityMasterGet]...';


GO


ALTER PROCEDURE [sWf].[pWfFunctionalityMasterGet]
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
		SELECT Id,
			   Code,
			   Title,
			   IsObsolete
			   --Type
		FROM   sWf.tWfFunctionalityMaster(NOLOCK)
		WHERE  IsObsolete = 0
	END TRY

	BEGIN CATCH
    IF @@TRANCOUNT > 0
        ROLLBACK TRANSACTION
    
    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].[pWfRoleGet]...';


GO



ALTER PROCEDURE [sWf].[pWfRoleGet]
	  @rOrgGroupId SMALLINT
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
		SELECT Id,
			   Title AS DisplayTitle
	    FROM   sSecurity.tRole (NOLOCK)
		WHERE  IsObsolete='0' AND OrgGroupId = @rOrgGroupId
          AND  Id <> ([sCommon].[fGetIntIdForOrg](21,@rOrgGroupId)) 
		  AND  Id <> ([sCommon].[fGetIntIdForOrg](22,@rOrgGroupId))
	END TRY

	BEGIN CATCH
    IF @@TRANCOUNT > 0
        ROLLBACK TRANSACTION
    
    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



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 AND WFS.OrgGroupId = @rOrgGroupId AND WFS.WfTypeMasterId = @rWfTypeMasterId AND WFS.IsObsolete = 0)
				BEGIN
					SELECT -102
				END
				ELSE
				BEGIN
					IF NOT EXISTS(SELECT WFM.Id
					from [sWf].[tWfFunctionalityMaster] WFM 
					WHERE WFM.Id = @rWfFunctionalityId AND WFM.IsObsolete = 0)
					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.OrgGroupId = @rOrgGroupId AND WS.IsObsolete = 0
							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 AND OrgGroupId = @rOrgGroupId AND IsObsolete = 0

					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

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


GO


ALTER PROCEDURE [sWf].[pWfSetupGet]
	  @rWfFunctionalityId SMALLINT,
	  @rOrgGroupId SMALLINT,
	  @rOrgId SMALLINT
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
		SELECT WFS.AutoId,
			   WFS.WfTypeMasterId,
			   WFS.WfLevel,
			   WFS.OrgGroupId,
			   WFS.WfFunctionalityId
		FROM   [sWf].[tWfSetup] WFS(NOLOCK) 
		WHERE  WFS.WfFunctionalityId = @rWfFunctionalityId AND WFS.OrgGroupId = @rOrgGroupId AND WFS.IsObsolete = 0

		--DECLARE @wfFunctionalityId SMALLINT
		--SELECT @wfFunctionalityId = WfFunctionalityId
		--FROM   [sWf].[tWfSetup](NOLOCK) 
		--WHERE  AutoId = @rId AND OrgGroupId = @rOrgGroupId AND IsObsolete = 0

		SELECT [AutoId]
			  ,[AuthoritySourceTypeId]
			  ,[AuthoritySourceId]
			  ,[OrgId]
			  ,[WfFunctionalityId]
		 FROM  [sWf].[tWfApprovingAuthority] (NOLOCK) 
		 WHERE WfFunctionalityId = @rWfFunctionalityId AND OrgId = @rOrgId
	END TRY

	BEGIN CATCH
    IF @@TRANCOUNT > 0
        ROLLBACK TRANSACTION
    
    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].[pWfTypeMasterGet]...';


GO


ALTER PROCEDURE [sWf].[pWfTypeMasterGet]
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
		SELECT  Id,
				Code,
				Title,
				IsObsolete
		FROM    sWf.tWfTypeMaster(NOLOCK)
		WHERE   IsObsolete = 0
	END TRY

	BEGIN CATCH
    IF @@TRANCOUNT > 0
        ROLLBACK TRANSACTION 
    
    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].[pWfUserGet]...';


GO


ALTER PROCEDURE [sWf].[pWfUserGet]
	  @rOrgGroupId SMALLINT
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
		SELECT U.Id,
	           U.DisplayTitle 
		FROM   sSecurity.tUser U (NOLOCK)
		INNER JOIN sSecurity.tUserRole UR ON UR.UserId = U.Id
		INNER JOIN sSecurity.tRole R ON R.Id = UR.RoleId 
		WHERE U.IsObsolete='0' AND UR.IsObsolete='0' AND U.OrgId = @rOrgGroupId
		AND   R.Id <> ([sCommon].[fGetIntIdForOrg](21,@rOrgGroupId)) 
		AND   R.Id <> ([sCommon].[fGetIntIdForOrg](22,@rOrgGroupId))
	END TRY

	BEGIN CATCH
    IF @@TRANCOUNT > 0
        ROLLBACK TRANSACTION
    
    DECLARE @ErrorMessage NVARCHAR(4000);  
    DECLARE @ErrorSeverity INT;  
    DECLARE @ErrorState INT;  
    SELECT   
       @ErrorMessage = ERROR_MESSAGE(),  
       @ErrorSeverity = ERROR_SEVERITY(),  
       @ErrorState = ERROR_STATE();  
    RAISERROR (@ErrorMessage, @ErrorSeverity, @ErrorState);
	END CATCH
END
GO

PRINT N'Creating Procedure [sEMeeting].[pOnlineMeetingScopeValidate]...';


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


		If EXISTS(select 1 from sEMeeting.tTempOnlineMeetingScope OMS where OMS.SourceId=@rSourceId AND
					OMS.SourceTypeId=@rSourceTypeId AND OMS.TempOnlineMeetingId=@rTempOnlineMeetingId AND AssigneeToId=@rAssigneeToId) 
			BEGIN
				select -101 as Result,'Item Already Exists' AS Msg
				RETURN
			END 

	
	IF(@rSourceTypeId = 2021) -- Organization	
		BEGIN
			If EXISTS(select 1 from  sEMeeting.tTempOnlineMeetingScope OMS
			 INNER JOIN  sSetup.tDepartmentMaster DM 
				ON OMS.SourceId=DM.Id AND OMS.SourceTypeId= 2017
				where DM.OrgId=@rSourceId  AND OMS.TempOnlineMeetingId=@rTempOnlineMeetingId AND AssigneeToId=@rAssigneeToId)
					BEGIN
						select -103 as Result,'Department already Exists' AS Msg
						RETURN
					END 
			If EXISTS(select 1 from  sEMeeting.tTempOnlineMeetingScope OMS 
			 INNER JOIN  sSetup.tClassMaster CM 
				ON OMS.SourceId=CM.Id AND OMS.SourceTypeId= 2016
				where CM.OrgId=@rSourceId  AND OMS.TempOnlineMeetingId=@rTempOnlineMeetingId AND AssigneeToId=@rAssigneeToId)
					BEGIN
						select -103 as Result,'Class already Exists' AS Msg
						RETURN
					END 
					
			If EXISTS(select 1 from  sEMeeting.tTempOnlineMeetingScope OMS 
			 INNER JOIN  sSetup.tDivisionMaster DM 
				ON OMS.SourceId=DM.Id AND OMS.SourceTypeId= 2005
				where DM.OrgId=@rSourceId  AND OMS.TempOnlineMeetingId=@rTempOnlineMeetingId AND AssigneeToId=@rAssigneeToId)
					BEGIN
						select -103 as Result,'Division already Exists' AS Msg
						RETURN
					END 
					
			If EXISTS(select 1 from  sEMeeting.tTempOnlineMeetingScope OMS 
			 INNER JOIN  sStudent.vStudentAcademic SA
				ON OMS.SourceId=SA.AcademicId AND OMS.SourceTypeId= 2003
				where SA.OrgId=@rSourceId  AND OMS.TempOnlineMeetingId=@rTempOnlineMeetingId AND AssigneeToId=@rAssigneeToId)
					BEGIN
						select -103 as Result,'Student already Exists' AS Msg
						RETURN
					END 		

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

    END
			select 1 as Result,'' AS Msg
	
END
GO
PRINT N'Creating Procedure [sEMeeting].[pTempOnlineMeetingScopeAdd]...';


GO


CREATE PROCEDURE [sEMeeting].[pTempOnlineMeetingScopeAdd]

			@rTempOnlineMeetingId nvarchar(100)
           ,@rSourceTypeId smallint
           ,@rSourceId bigint
           ,@rIsDeleted bit
          ,@rAssigneeToId int 
           	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
 

If(@rIsDeleted=1)
BEGIN
	Delete from sEMeeting.tTempOnlineMeetingScope where TempOnlineMeetingId=@rTempOnlineMeetingId AND SourceTypeId=@rSourceTypeId AND AssigneeToId= @rAssigneeToId
	AND SourceId=@rSourceId
	Select @rSourceId as Result
END	
ELSE
BEGIN 
 
	If Exists(select TempOnlineMeetingId from sEMeeting.tTempOnlineMeetingScope where TempOnlineMeetingId=@rTempOnlineMeetingId AND SourceTypeId=@rSourceTypeId
	AND SourceId=@rSourceId AND AssigneeToId= @rAssigneeToId)
		BEGIN
			SELECT @rSourceId AS Result
			RETURN
	  END 
	ELSE
			BEGIN
			INSERT INTO sEMeeting.tTempOnlineMeetingScope
			(
				TempOnlineMeetingId
			   ,SourceTypeId
			   ,SourceId
			   ,AssigneeToId
			)
			VALUES
			(	
				@rTempOnlineMeetingId
			   ,@rSourceTypeId
			   ,@rSourceId
			   ,@rAssigneeToId
			)		
			SELECT 1 AS Result
		 
	END	
END
GO

PRINT N'Creating Procedure [sPurchase].[pConfigurationSetupAddUpdate]...';


GO

 -- select * from sConfig.tConfigurationSetup order by CreatedDateTime desc
 -- exec [sPurchase].[pConfigurationSetupAddUpdate] 'abcdefghijklmno',2010,9911,9911000000003,9911
CREATE PROCEDURE [sPurchase].[pConfigurationSetupAddUpdate]
	 
	--@rConfigurationId [int],
	@rItemValue NVARCHAR(500),
	@rSourceTypeId INT,
	@rSourceId BIGINT,
	@rCreatedUserId BIGINT,
	@rOrgId INT
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
	BEGIN TRANSACTION
		 DECLARE @rConfigurationId INT = 542 --for Purchase StoreLocation
		 DELETE FROM sConfig.tConfigurationSetup 
		 WHERE 
		 ConfigurationId  = @rConfigurationId 
		 AND SourceId=@rSourceId 
		 AND SourceTypeId=@rSourceTypeId
 
		 DECLARE @lNextNumber BIGINT     
	
		 EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sConfig.tConfigurationSetup', 0, 1, 1,@outNextNumber = @lNextNumber OUTPUT

		 IF NOT EXISTS(SELECT 1 FROM sConfig.tConfigurationSetup WHERE ConfigurationId = @rConfigurationId AND SourceId = @rSourceId AND SourceTypeId=@rSourceTypeId)
		 BEGIN
	
			IF(@rItemValue!='')
			BEGIN
			INSERT INTO [sConfig].[tConfigurationSetup]
				   ([Id]
				   ,[ConfigurationId]
				   ,[ItemValue]
				   ,[sourceTypeId]
				   ,[SourceId]
				   ,[CreatedUserId]
				   ,[CreatedDateTime]        
					)
			 VALUES
				   (
					@lNextNumber,
					@rConfigurationId,
					@rItemValue,
					@rSourceTypeId,
					@rSourceId,
					@rCreatedUserId,
					sCommon.fGetDate()
					)
			  END      
				  SELECT @rItemValue AS result
		  END
		  ELSE
		  BEGIN
			  UPDATE sConfig.tConfigurationSetup 
				  SET ItemValue = @rItemValue,
				  UpdatedUserId = @rCreatedUserId,
				  UpdatedDateTime =  sCommon.fGetDate()
          
			  WHERE ConfigurationId  = @rConfigurationId AND SourceId=@rSourceId AND SourceTypeId=@rSourceTypeId
			  SELECT @rItemValue AS result
		  END       
         
	COMMIT TRANSACTION	
	END TRY

	BEGIN CATCH
    IF @@TRANCOUNT > 0
    ROLLBACK TRANSACTION

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

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

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


GO


CREATE PROCEDURE [sPurchase].[pDependentFunctionalityGet]
	  @rScreenId INT
AS
SET NOCOUNT ON

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

	BEGIN CATCH
    IF @@TRANCOUNT > 0
    ROLLBACK TRANSACTION
    
    DECLARE @ErrorMessage NVARCHAR(4000);  
    DECLARE @ErrorSeverity INT;  
    DECLARE @ErrorState INT;  
    SELECT   
       @ErrorMessage = ERROR_MESSAGE(),  
       @ErrorSeverity = ERROR_SEVERITY(),  
       @ErrorState = ERROR_STATE();  
    RAISERROR (@ErrorMessage, @ErrorSeverity, @ErrorState);  
    
	END CATCH
END
GO
PRINT N'Creating Procedure [sPurchase].[pEmployeeMasterIdGet]...';


GO

CREATE PROCEDURE [sPurchase].[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
PRINT N'Creating Procedure [sPurchase].[pGetStoreLocationConfig]...';


GO

   
-- exec [sPurchase].[pGetStoreLocationConfig] 95,9911000000003
CREATE PROCEDURE [sPurchase].[pGetStoreLocationConfig]
	@rSourceTypeId INT,
	@rSourceId BIGINT
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
		 DECLARE @result INT
		 SELECT @result=ISNULL(ItemValue,0)
		 FROM sConfig.tConfigurationSetup 
		 WHERE ConfigurationId  = 542 AND SourceId=@rSourceId AND SourceTypeId=@rSourceTypeId
		 SELECT ISNULL(@result,0)
	END TRY

	BEGIN CATCH
    IF @@TRANCOUNT > 0
    ROLLBACK TRANSACTION
    
    DECLARE @ErrorMessage NVARCHAR(4000);  
    DECLARE @ErrorSeverity INT;  
    DECLARE @ErrorState INT;  
    SELECT   
       @ErrorMessage = ERROR_MESSAGE(),  
       @ErrorSeverity = ERROR_SEVERITY(),  
       @ErrorState = ERROR_STATE();  
    RAISERROR (@ErrorMessage, @ErrorSeverity, @ErrorState);  
    
	END CATCH
END
GO
PRINT N'Creating Procedure [sPurchase].[pNotitficationLogIdGet]...';


GO

CREATE PROCEDURE [sPurchase].[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
PRINT N'Creating Procedure [sPurchase].[pSMSTemplateIdGet]...';


GO

CREATE PROCEDURE [sPurchase].[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

PRINT N'Altering Procedure [sPurchase].[pGoodsReceivedNoteAdd]...';


GO


ALTER PROCEDURE [sPurchase].[pGoodsReceivedNoteAdd]
		@rId BIGINT,
		@rPurchaseRequestId BIGINT,
		@rPurchaseOrderId BIGINT,
		@rPODueDate DATETIME,	
		@rRequestedBy NVARCHAR(100),
		@rOrgGroupId SMALLINT,
		@rStatusId SMALLINT,	
		@rVendorId INT,
		@rBillToAddress NVARCHAR(1000),
		@rUserId BIGINT,
		@rDetailList sPurchase.GoodsReceivedNoteDetailType READONLY
 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
	BEGIN TRANSACTION
	    DECLARE @rStoreLocationId BIGINT
        SELECT @rStoreLocationId = ISNULL(ItemValue,0)
	    FROM sConfig.tConfigurationSetup 
	    WHERE ConfigurationId  = 542 AND SourceId = @rUserId

		IF(@rId > 0)
		BEGIN
		    IF NOT EXISTS(SELECT Id FROM sPurchase.tGoodsReceivedNote WHERE Id = @rId AND CreatedUserId = @rUserId  AND LocationId = @rStoreLocationId AND OrgGroupId = @rOrgGroupId AND IsObsolete = 0)
            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 LocationId = @rStoreLocationId AND OrgGroupId = @rOrgGroupId AND IsObsolete = 0 

				DELETE FROM sPurchase.tGoodsReceivedNoteDetail
				WHERE Id NOT IN(SELECT Id FROM @rDetailList)
				AND GoodsReceivedNoteId = @rId AND OrgGroupId = @rOrgGroupId

				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 GRN.GoodsReceivedNoteId = @rId AND GRN.OrgGroupId = @rOrgGroupId

				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 AND GRN.OrgGroupId = @rOrgGroupId)

				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 AND GRN.OrgGroupId = @rOrgGroupId
				WHERE GRN.GoodsReceivedNoteId = @rId AND GRN.OrgGroupId = @rOrgGroupId))
				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,
						@rStoreLocationId, 		 
						@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 TRANSACTION	
	END TRY

	BEGIN CATCH
    IF @@TRANCOUNT > 0
    ROLLBACK TRANSACTION

    
    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
	    DECLARE @rStoreLocationId BIGINT
        SELECT @rStoreLocationId = ISNULL(ItemValue,0)
	    FROM sConfig.tConfigurationSetup 
	    WHERE ConfigurationId  = 542 AND SourceId = @rUserId

		IF(@rId > 0)
		BEGIN
		    IF NOT EXISTS(SELECT Id FROM sPurchase.tPurchaseOrder WHERE Id = @rId AND CreatedUserId = @rUserId 
			AND LocationId = @rStoreLocationId AND OrgGroupId = @rOrgGroupId AND IsObsolete = 0)
			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 LocationId = @rStoreLocationId AND OrgGroupId = @rOrgGroupId AND IsObsolete = 0

				DELETE FROM sPurchase.tPurchaseOrderDetail
				WHERE Id NOT IN(SELECT Id FROM @rDetailList)
				AND PurchaseOrderId = @rId AND OrgGroupId = @rOrgGroupId

				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 PO.PurchaseOrderId = @rId AND PO.OrgGroupId = @rOrgGroupId

				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 AND PO.OrgGroupId = @rOrgGroupId)
				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 AND PO.OrgGroupId = @rOrgGroupId
				WHERE PO.PurchaseOrderId = @rId AND PO.OrgGroupId = @rOrgGroupId))
				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 AND PO.LocationId = @rStoreLocationId AND PO.OrgGroupId = @rOrgGroupId AND PO.IsObsolete = 0) 
                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,
						@rStoreLocationId, 		 
						@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 TRANSACTION
	END TRY

	BEGIN CATCH
    IF @@TRANCOUNT > 0
        ROLLBACK TRANSACTION

    
    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
			DECLARE @rStoreLocationId BIGINT
            SELECT @rStoreLocationId = ISNULL(ItemValue,0)
	        FROM sConfig.tConfigurationSetup 
	        WHERE ConfigurationId  = 542 AND SourceId = @rUserId
		IF(@rId > 0)
		BEGIN
		    
		    IF NOT EXISTS(SELECT Id FROM sPurchase.tPurchaseRequest WHERE Id = @rId AND CreatedUserId = @rUserId AND LocationId = @rStoreLocationId AND OrgGroupId = @rOrgGroupId AND IsObsolete = 0)
			BEGIN
				SELECT -101
			END
			ELSE
			  BEGIN
				UPDATE sPurchase.tPurchaseRequest
				SET 
					StatusId = @rStatusId,
					UpdatedUserId = @rUserId,		
					UpdatedDateTime = GETUTCDATE()
				WHERE Id = @rId AND IsObsolete = 0 AND LocationId = @rStoreLocationId AND OrgGroupId = @rOrgGroupId 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 AND PR.OrgGroupId = @rOrgGroupId

				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 AND PR.OrgGroupId = @rOrgGroupId) 

				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,
						@rStoreLocationId, 		 
						@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 TRANSACTION
	END TRY

	BEGIN CATCH
    IF @@TRANCOUNT > 0
        ROLLBACK TRANSACTION

    
    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
        DECLARE @rStoreLocationId BIGINT
        SELECT @rStoreLocationId = ISNULL(ItemValue,0)
	    FROM sConfig.tConfigurationSetup 
	    WHERE ConfigurationId  = 542 AND SourceId = @rUserId

		IF(@rId > 0)
		BEGIN
		  IF NOT EXISTS(SELECT Id FROM sPurchase.tQuotationRequest WHERE Id = @rId AND CreatedUserId = @rUserId 
				AND LocationId = @rStoreLocationId AND OrgGroupId = @rOrgGroupId AND IsObsolete = 0)
		    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 LocationId = @rStoreLocationId AND OrgGroupId = @rOrgGroupId AND IsObsolete = 0

				DELETE FROM sPurchase.tQuotationRequestDetail
				WHERE Id NOT IN(SELECT Id FROM @rDetailList)
				AND QuotationRequestId = @rId AND OrgGroupId = @rOrgGroupId

				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 QR.QuotationRequestId = @rId AND QR.OrgGroupId = @rOrgGroupId

				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 AND QR.OrgGroupId = @rOrgGroupId
				WHERE QR.QuotationRequestId = @rId AND QR.OrgGroupId = @rOrgGroupId)
				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 AND QR.OrgGroupId = @rOrgGroupId
				WHERE QR.QuotationRequestId = @rId AND QR.OrgGroupId = @rOrgGroupId))
				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 AND LocationId = @rStoreLocationId AND OrgGroupId = @rOrgGroupId AND IsObsolete = 0)
						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 ,
								@rStoreLocationId,
								@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 TRANSACTION
	END TRY

	BEGIN CATCH
    IF @@TRANCOUNT > 0
        ROLLBACK TRANSACTION

    
    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
	    DECLARE @rStoreLocationId BIGINT
        SELECT @rStoreLocationId = ISNULL(ItemValue,0)
	    FROM sConfig.tConfigurationSetup 
	    WHERE ConfigurationId  = 542 AND SourceId = @rUserId

		IF(@rId > 0)
		BEGIN
		  IF NOT EXISTS(SELECT Id FROM sPurchase.tQuotationRequest WHERE Id = @rId AND CreatedUserId = @rUserId AND LocationId = @rStoreLocationId AND OrgGroupId = @rOrgGroupId AND IsObsolete = 0)
		    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 LocationId = @rStoreLocationId AND OrgGroupId = @rOrgGroupId AND IsObsolete = 0

				DELETE FROM sPurchase.tSalesReturnDetail
				WHERE Id NOT IN(SELECT Id FROM @rDetailList)
				AND SalesReturnId = @rId AND OrgGroupId = @rOrgGroupId

				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 AND SR.OrgGroupId = @rOrgGroupId
				WHERE SalesReturnId = @rId AND OrgGroupId = @rOrgGroupId

				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 AND SR.OrgGroupId = @rOrgGroupId
				WHERE SR.SalesReturnId = @rId AND SR.OrgGroupId = @rOrgGroupId)
				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 AND SR.OrgGroupId = @rOrgGroupId
				WHERE SR.SalesReturnId = @rId AND SR.OrgGroupId = @rOrgGroupId))
				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,
						@rStoreLocationId, 		 
						@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 TRANSACTION
	END TRY

	BEGIN CATCH
    IF @@TRANCOUNT > 0
        ROLLBACK TRANSACTION

    
    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

--------------------------------------------------------------------------------------------------------------------------------------------------

If Exists(select * from sSecurity.tOrganizationTask where TaskId = 31300)
BEGIN
	update sSecurity.tOrganizationTask set AvailablePermission = 3  where TaskId = 31300
END
GO
If Exists(select * from sSecurity.tTask where Id = 31300)
BEGIN
	update 	Security.tTask set AvailablePermission = 3  where Id = 31300
END
GO
--------------------------------------------------------------------------------------------------------------------------------------------------

--------------------------------------------------------------------------------------------------------------------------------------------------

/****** Object:  StoredProcedure [sWf].[pWfUserGet]    Script Date: 01-02-2024 12:00:42 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[sWf].[pWfUserGet]') AND type in (N'P', N'PC'))
DROP PROCEDURE [sWf].[pWfUserGet]
GO
/****** Object:  StoredProcedure [sWf].[pWfTypeMasterGet]    Script Date: 01-02-2024 12:00:42 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[sWf].[pWfTypeMasterGet]') AND type in (N'P', N'PC'))
DROP PROCEDURE [sWf].[pWfTypeMasterGet]
GO
/****** Object:  StoredProcedure [sWf].[pWfSetupGet]    Script Date: 01-02-2024 12:00:42 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[sWf].[pWfSetupGet]') AND type in (N'P', N'PC'))
DROP PROCEDURE [sWf].[pWfSetupGet]
GO
/****** Object:  StoredProcedure [sWf].[pWfSetupAdd]    Script Date: 01-02-2024 12:00:42 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[sWf].[pWfSetupAdd]') AND type in (N'P', N'PC'))
DROP PROCEDURE [sWf].[pWfSetupAdd]
GO
/****** Object:  StoredProcedure [sWf].[pWfRoleGet]    Script Date: 01-02-2024 12:00:42 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[sWf].[pWfRoleGet]') AND type in (N'P', N'PC'))
DROP PROCEDURE [sWf].[pWfRoleGet]
GO
/****** Object:  StoredProcedure [sWf].[pWfFunctionalityMasterGet]    Script Date: 01-02-2024 12:00:42 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[sWf].[pWfFunctionalityMasterGet]') AND type in (N'P', N'PC'))
DROP PROCEDURE [sWf].[pWfFunctionalityMasterGet]
GO
/****** Object:  StoredProcedure [sWf].[pWfApprovalGet]    Script Date: 01-02-2024 12:00:42 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[sWf].[pWfApprovalGet]') AND type in (N'P', N'PC'))
DROP PROCEDURE [sWf].[pWfApprovalGet]
GO
/****** Object:  StoredProcedure [sWf].[pWfApprovalAdd]    Script Date: 01-02-2024 12:00:42 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[sWf].[pWfApprovalAdd]') AND type in (N'P', N'PC'))
DROP PROCEDURE [sWf].[pWfApprovalAdd]
GO
/****** Object:  StoredProcedure [sPurchase].[pWhatsAppTemplateGet]    Script Date: 01-02-2024 12:00:42 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[sPurchase].[pWhatsAppTemplateGet]') AND type in (N'P', N'PC'))
DROP PROCEDURE [sPurchase].[pWhatsAppTemplateGet]
GO
/****** Object:  StoredProcedure [sPurchase].[pVendorNotificationGet]    Script Date: 01-02-2024 12:00:42 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[sPurchase].[pVendorNotificationGet]') AND type in (N'P', N'PC'))
DROP PROCEDURE [sPurchase].[pVendorNotificationGet]
GO
/****** Object:  StoredProcedure [sPurchase].[pValidateCloudStorage]    Script Date: 01-02-2024 12:00:42 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[sPurchase].[pValidateCloudStorage]') AND type in (N'P', N'PC'))
DROP PROCEDURE [sPurchase].[pValidateCloudStorage]
GO
/****** Object:  StoredProcedure [sPurchase].[pStudentProfileGet]    Script Date: 01-02-2024 12:00:42 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[sPurchase].[pStudentProfileGet]') AND type in (N'P', N'PC'))
DROP PROCEDURE [sPurchase].[pStudentProfileGet]
GO
/****** Object:  StoredProcedure [sPurchase].[pStoreLocationMasterGet]    Script Date: 01-02-2024 12:00:42 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[sPurchase].[pStoreLocationMasterGet]') AND type in (N'P', N'PC'))
DROP PROCEDURE [sPurchase].[pStoreLocationMasterGet]
GO
/****** Object:  StoredProcedure [sPurchase].[pStoreLocationGet]    Script Date: 01-02-2024 12:00:42 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[sPurchase].[pStoreLocationGet]') AND type in (N'P', N'PC'))
DROP PROCEDURE [sPurchase].[pStoreLocationGet]
GO
/****** Object:  StoredProcedure [sPurchase].[pStockItemMasterSearchGet]    Script Date: 01-02-2024 12:00:42 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[sPurchase].[pStockItemMasterSearchGet]') AND type in (N'P', N'PC'))
DROP PROCEDURE [sPurchase].[pStockItemMasterSearchGet]
GO
/****** Object:  StoredProcedure [sPurchase].[pStockItemMasterGetWithCategory]    Script Date: 01-02-2024 12:00:42 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[sPurchase].[pStockItemMasterGetWithCategory]') AND type in (N'P', N'PC'))
DROP PROCEDURE [sPurchase].[pStockItemMasterGetWithCategory]
GO
/****** Object:  StoredProcedure [sPurchase].[pStockBatchAddModify]    Script Date: 01-02-2024 12:00:42 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[sPurchase].[pStockBatchAddModify]') AND type in (N'P', N'PC'))
DROP PROCEDURE [sPurchase].[pStockBatchAddModify]
GO
/****** Object:  StoredProcedure [sPurchase].[pSearchScreenDependencyGet]    Script Date: 01-02-2024 12:00:42 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[sPurchase].[pSearchScreenDependencyGet]') AND type in (N'P', N'PC'))
DROP PROCEDURE [sPurchase].[pSearchScreenDependencyGet]
GO
/****** Object:  StoredProcedure [sPurchase].[pSalesReturnSearchGet]    Script Date: 01-02-2024 12:00:42 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[sPurchase].[pSalesReturnSearchGet]') AND type in (N'P', N'PC'))
DROP PROCEDURE [sPurchase].[pSalesReturnSearchGet]
GO
/****** Object:  StoredProcedure [sPurchase].[pSalesReturnGet]    Script Date: 01-02-2024 12:00:42 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[sPurchase].[pSalesReturnGet]') AND type in (N'P', N'PC'))
DROP PROCEDURE [sPurchase].[pSalesReturnGet]
GO
/****** Object:  StoredProcedure [sPurchase].[pSalesReturnDelete]    Script Date: 01-02-2024 12:00:42 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[sPurchase].[pSalesReturnDelete]') AND type in (N'P', N'PC'))
DROP PROCEDURE [sPurchase].[pSalesReturnDelete]
GO
/****** Object:  StoredProcedure [sPurchase].[pSalesReturnAdd]    Script Date: 01-02-2024 12:00:42 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[sPurchase].[pSalesReturnAdd]') AND type in (N'P', N'PC'))
DROP PROCEDURE [sPurchase].[pSalesReturnAdd]
GO
/****** Object:  StoredProcedure [sPurchase].[pQuotationVendorGet]    Script Date: 01-02-2024 12:00:42 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[sPurchase].[pQuotationVendorGet]') AND type in (N'P', N'PC'))
DROP PROCEDURE [sPurchase].[pQuotationVendorGet]
GO
/****** Object:  StoredProcedure [sPurchase].[pQuotationRequestSearchGet]    Script Date: 01-02-2024 12:00:42 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[sPurchase].[pQuotationRequestSearchGet]') AND type in (N'P', N'PC'))
DROP PROCEDURE [sPurchase].[pQuotationRequestSearchGet]
GO
/****** Object:  StoredProcedure [sPurchase].[pQuotationRequestGet]    Script Date: 01-02-2024 12:00:42 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[sPurchase].[pQuotationRequestGet]') AND type in (N'P', N'PC'))
DROP PROCEDURE [sPurchase].[pQuotationRequestGet]
GO
/****** Object:  StoredProcedure [sPurchase].[pQuotationRequestDelete]    Script Date: 01-02-2024 12:00:42 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[sPurchase].[pQuotationRequestDelete]') AND type in (N'P', N'PC'))
DROP PROCEDURE [sPurchase].[pQuotationRequestDelete]
GO
/****** Object:  StoredProcedure [sPurchase].[pQuotationRequestAdd]    Script Date: 01-02-2024 12:00:42 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[sPurchase].[pQuotationRequestAdd]') AND type in (N'P', N'PC'))
DROP PROCEDURE [sPurchase].[pQuotationRequestAdd]
GO
/****** Object:  StoredProcedure [sPurchase].[pQuotationApprovedVendorGet]    Script Date: 01-02-2024 12:00:42 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[sPurchase].[pQuotationApprovedVendorGet]') AND type in (N'P', N'PC'))
DROP PROCEDURE [sPurchase].[pQuotationApprovedVendorGet]
GO
/****** Object:  StoredProcedure [sPurchase].[pQualityCheckSearchGet]    Script Date: 01-02-2024 12:00:42 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[sPurchase].[pQualityCheckSearchGet]') AND type in (N'P', N'PC'))
DROP PROCEDURE [sPurchase].[pQualityCheckSearchGet]
GO
/****** Object:  StoredProcedure [sPurchase].[pQualityCheckGet]    Script Date: 01-02-2024 12:00:42 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[sPurchase].[pQualityCheckGet]') AND type in (N'P', N'PC'))
DROP PROCEDURE [sPurchase].[pQualityCheckGet]
GO
/****** Object:  StoredProcedure [sPurchase].[pQualityCheckDelete]    Script Date: 01-02-2024 12:00:42 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[sPurchase].[pQualityCheckDelete]') AND type in (N'P', N'PC'))
DROP PROCEDURE [sPurchase].[pQualityCheckDelete]
GO
/****** Object:  StoredProcedure [sPurchase].[pQualityCheckAdd]    Script Date: 01-02-2024 12:00:42 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[sPurchase].[pQualityCheckAdd]') AND type in (N'P', N'PC'))
DROP PROCEDURE [sPurchase].[pQualityCheckAdd]
GO
/****** Object:  StoredProcedure [sPurchase].[pPurchaseVendorMasterGet]    Script Date: 01-02-2024 12:00:42 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[sPurchase].[pPurchaseVendorMasterGet]') AND type in (N'P', N'PC'))
DROP PROCEDURE [sPurchase].[pPurchaseVendorMasterGet]
GO
/****** Object:  StoredProcedure [sPurchase].[pPurchaseStoreLocationMasterGet]    Script Date: 01-02-2024 12:00:42 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[sPurchase].[pPurchaseStoreLocationMasterGet]') AND type in (N'P', N'PC'))
DROP PROCEDURE [sPurchase].[pPurchaseStoreLocationMasterGet]
GO
/****** Object:  StoredProcedure [sPurchase].[pPurchaseStatusGet]    Script Date: 01-02-2024 12:00:42 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[sPurchase].[pPurchaseStatusGet]') AND type in (N'P', N'PC'))
DROP PROCEDURE [sPurchase].[pPurchaseStatusGet]
GO
/****** Object:  StoredProcedure [sPurchase].[pPurchaseScreenGet]    Script Date: 01-02-2024 12:00:42 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[sPurchase].[pPurchaseScreenGet]') AND type in (N'P', N'PC'))
DROP PROCEDURE [sPurchase].[pPurchaseScreenGet]
GO
/****** Object:  StoredProcedure [sPurchase].[pPurchaseRequestSearchGet]    Script Date: 01-02-2024 12:00:42 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[sPurchase].[pPurchaseRequestSearchGet]') AND type in (N'P', N'PC'))
DROP PROCEDURE [sPurchase].[pPurchaseRequestSearchGet]
GO
/****** Object:  StoredProcedure [sPurchase].[pPurchaseRequestPOApprovedSearchGet]    Script Date: 01-02-2024 12:00:42 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[sPurchase].[pPurchaseRequestPOApprovedSearchGet]') AND type in (N'P', N'PC'))
DROP PROCEDURE [sPurchase].[pPurchaseRequestPOApprovedSearchGet]
GO
/****** Object:  StoredProcedure [sPurchase].[pPurchaseRequestGet]    Script Date: 01-02-2024 12:00:42 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[sPurchase].[pPurchaseRequestGet]') AND type in (N'P', N'PC'))
DROP PROCEDURE [sPurchase].[pPurchaseRequestGet]
GO
/****** Object:  StoredProcedure [sPurchase].[pPurchaseRequestDelete]    Script Date: 01-02-2024 12:00:42 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[sPurchase].[pPurchaseRequestDelete]') AND type in (N'P', N'PC'))
DROP PROCEDURE [sPurchase].[pPurchaseRequestDelete]
GO
/****** Object:  StoredProcedure [sPurchase].[pPurchaseRequestApprovedSearchGet]    Script Date: 01-02-2024 12:00:42 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[sPurchase].[pPurchaseRequestApprovedSearchGet]') AND type in (N'P', N'PC'))
DROP PROCEDURE [sPurchase].[pPurchaseRequestApprovedSearchGet]
GO
/****** Object:  StoredProcedure [sPurchase].[pPurchaseRequestApprovedGet]    Script Date: 01-02-2024 12:00:42 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[sPurchase].[pPurchaseRequestApprovedGet]') AND type in (N'P', N'PC'))
DROP PROCEDURE [sPurchase].[pPurchaseRequestApprovedGet]
GO
/****** Object:  StoredProcedure [sPurchase].[pPurchaseRequestAdd]    Script Date: 01-02-2024 12:00:42 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[sPurchase].[pPurchaseRequestAdd]') AND type in (N'P', N'PC'))
DROP PROCEDURE [sPurchase].[pPurchaseRequestAdd]
GO
/****** Object:  StoredProcedure [sPurchase].[pPurchaseOrderSearchGet]    Script Date: 01-02-2024 12:00:42 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[sPurchase].[pPurchaseOrderSearchGet]') AND type in (N'P', N'PC'))
DROP PROCEDURE [sPurchase].[pPurchaseOrderSearchGet]
GO
/****** Object:  StoredProcedure [sPurchase].[pPurchaseOrderGet]    Script Date: 01-02-2024 12:00:42 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[sPurchase].[pPurchaseOrderGet]') AND type in (N'P', N'PC'))
DROP PROCEDURE [sPurchase].[pPurchaseOrderGet]
GO
/****** Object:  StoredProcedure [sPurchase].[pPurchaseOrderDelete]    Script Date: 01-02-2024 12:00:42 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[sPurchase].[pPurchaseOrderDelete]') AND type in (N'P', N'PC'))
DROP PROCEDURE [sPurchase].[pPurchaseOrderDelete]
GO
/****** Object:  StoredProcedure [sPurchase].[pPurchaseOrderApprovedSearchGet]    Script Date: 01-02-2024 12:00:42 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[sPurchase].[pPurchaseOrderApprovedSearchGet]') AND type in (N'P', N'PC'))
DROP PROCEDURE [sPurchase].[pPurchaseOrderApprovedSearchGet]
GO
/****** Object:  StoredProcedure [sPurchase].[pPurchaseOrderApprovedGet]    Script Date: 01-02-2024 12:00:42 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[sPurchase].[pPurchaseOrderApprovedGet]') AND type in (N'P', N'PC'))
DROP PROCEDURE [sPurchase].[pPurchaseOrderApprovedGet]
GO
/****** Object:  StoredProcedure [sPurchase].[pPurchaseOrderAdd]    Script Date: 01-02-2024 12:00:42 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[sPurchase].[pPurchaseOrderAdd]') AND type in (N'P', N'PC'))
DROP PROCEDURE [sPurchase].[pPurchaseOrderAdd]
GO
/****** Object:  StoredProcedure [sPurchase].[pPOPurchaseRequestDetailGet]    Script Date: 01-02-2024 12:00:42 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[sPurchase].[pPOPurchaseRequestDetailGet]') AND type in (N'P', N'PC'))
DROP PROCEDURE [sPurchase].[pPOPurchaseRequestDetailGet]
GO
/****** Object:  StoredProcedure [sPurchase].[pOrgGroupIdGet]    Script Date: 01-02-2024 12:00:42 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[sPurchase].[pOrgGroupIdGet]') AND type in (N'P', N'PC'))
DROP PROCEDURE [sPurchase].[pOrgGroupIdGet]
GO
/****** Object:  StoredProcedure [sPurchase].[pMobileNotitficationTitleGet]    Script Date: 01-02-2024 12:00:42 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[sPurchase].[pMobileNotitficationTitleGet]') AND type in (N'P', N'PC'))
DROP PROCEDURE [sPurchase].[pMobileNotitficationTitleGet]
GO
/****** Object:  StoredProcedure [sPurchase].[pMenuGet_Purchase]    Script Date: 01-02-2024 12:00:42 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[sPurchase].[pMenuGet_Purchase]') AND type in (N'P', N'PC'))
DROP PROCEDURE [sPurchase].[pMenuGet_Purchase]
GO
/****** Object:  StoredProcedure [sPurchase].[pMasterOrganizationGet]    Script Date: 01-02-2024 12:00:42 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[sPurchase].[pMasterOrganizationGet]') AND type in (N'P', N'PC'))
DROP PROCEDURE [sPurchase].[pMasterOrganizationGet]
GO
/****** Object:  StoredProcedure [sPurchase].[pMasterBatchGet]    Script Date: 01-02-2024 12:00:42 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[sPurchase].[pMasterBatchGet]') AND type in (N'P', N'PC'))
DROP PROCEDURE [sPurchase].[pMasterBatchGet]
GO
/****** Object:  StoredProcedure [sPurchase].[pInvoiceGenerateSearchGet]    Script Date: 01-02-2024 12:00:42 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[sPurchase].[pInvoiceGenerateSearchGet]') AND type in (N'P', N'PC'))
DROP PROCEDURE [sPurchase].[pInvoiceGenerateSearchGet]
GO
/****** Object:  StoredProcedure [sPurchase].[pInvoiceGenerateGet]    Script Date: 01-02-2024 12:00:42 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[sPurchase].[pInvoiceGenerateGet]') AND type in (N'P', N'PC'))
DROP PROCEDURE [sPurchase].[pInvoiceGenerateGet]
GO
/****** Object:  StoredProcedure [sPurchase].[pInvoiceGenerateDelete]    Script Date: 01-02-2024 12:00:42 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[sPurchase].[pInvoiceGenerateDelete]') AND type in (N'P', N'PC'))
DROP PROCEDURE [sPurchase].[pInvoiceGenerateDelete]
GO
/****** Object:  StoredProcedure [sPurchase].[pInvoiceGenerateAdd]    Script Date: 01-02-2024 12:00:42 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[sPurchase].[pInvoiceGenerateAdd]') AND type in (N'P', N'PC'))
DROP PROCEDURE [sPurchase].[pInvoiceGenerateAdd]
GO
/****** Object:  StoredProcedure [sPurchase].[pHelperPopUpGet]    Script Date: 01-02-2024 12:00:42 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[sPurchase].[pHelperPopUpGet]') AND type in (N'P', N'PC'))
DROP PROCEDURE [sPurchase].[pHelperPopUpGet]
GO
/****** Object:  StoredProcedure [sPurchase].[pGoodsReceivedNoteSRGet]    Script Date: 01-02-2024 12:00:42 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[sPurchase].[pGoodsReceivedNoteSRGet]') AND type in (N'P', N'PC'))
DROP PROCEDURE [sPurchase].[pGoodsReceivedNoteSRGet]
GO
/****** Object:  StoredProcedure [sPurchase].[pGoodsReceivedNoteSearchSRGet]    Script Date: 01-02-2024 12:00:42 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[sPurchase].[pGoodsReceivedNoteSearchSRGet]') AND type in (N'P', N'PC'))
DROP PROCEDURE [sPurchase].[pGoodsReceivedNoteSearchSRGet]
GO
/****** Object:  StoredProcedure [sPurchase].[pGoodsReceivedNoteSearchGet]    Script Date: 01-02-2024 12:00:42 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[sPurchase].[pGoodsReceivedNoteSearchGet]') AND type in (N'P', N'PC'))
DROP PROCEDURE [sPurchase].[pGoodsReceivedNoteSearchGet]
GO
/****** Object:  StoredProcedure [sPurchase].[pGoodsReceivedNoteGet]    Script Date: 01-02-2024 12:00:42 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[sPurchase].[pGoodsReceivedNoteGet]') AND type in (N'P', N'PC'))
DROP PROCEDURE [sPurchase].[pGoodsReceivedNoteGet]
GO
/****** Object:  StoredProcedure [sPurchase].[pGoodsReceivedNoteDelete]    Script Date: 01-02-2024 12:00:42 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[sPurchase].[pGoodsReceivedNoteDelete]') AND type in (N'P', N'PC'))
DROP PROCEDURE [sPurchase].[pGoodsReceivedNoteDelete]
GO
/****** Object:  StoredProcedure [sPurchase].[pGoodsReceivedNoteApprovedSearchGet]    Script Date: 01-02-2024 12:00:42 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[sPurchase].[pGoodsReceivedNoteApprovedSearchGet]') AND type in (N'P', N'PC'))
DROP PROCEDURE [sPurchase].[pGoodsReceivedNoteApprovedSearchGet]
GO
/****** Object:  StoredProcedure [sPurchase].[pGoodsReceivedNoteApprovedGet]    Script Date: 01-02-2024 12:00:42 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[sPurchase].[pGoodsReceivedNoteApprovedGet]') AND type in (N'P', N'PC'))
DROP PROCEDURE [sPurchase].[pGoodsReceivedNoteApprovedGet]
GO
/****** Object:  StoredProcedure [sPurchase].[pGoodsReceivedNoteAdd]    Script Date: 01-02-2024 12:00:42 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[sPurchase].[pGoodsReceivedNoteAdd]') AND type in (N'P', N'PC'))
DROP PROCEDURE [sPurchase].[pGoodsReceivedNoteAdd]
GO
/****** Object:  StoredProcedure [sPurchase].[pGetTemplate]    Script Date: 01-02-2024 12:00:42 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[sPurchase].[pGetTemplate]') AND type in (N'P', N'PC'))
DROP PROCEDURE [sPurchase].[pGetTemplate]
GO
/****** Object:  StoredProcedure [sPurchase].[pGetStoreLocationConfig]    Script Date: 01-02-2024 12:00:42 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[sPurchase].[pGetStoreLocationConfig]') AND type in (N'P', N'PC'))
DROP PROCEDURE [sPurchase].[pGetStoreLocationConfig]
GO
/****** Object:  StoredProcedure [sPurchase].[pGetSRReport]    Script Date: 01-02-2024 12:00:42 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[sPurchase].[pGetSRReport]') AND type in (N'P', N'PC'))
DROP PROCEDURE [sPurchase].[pGetSRReport]
GO
/****** Object:  StoredProcedure [sPurchase].[pGetQRReport]    Script Date: 01-02-2024 12:00:42 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[sPurchase].[pGetQRReport]') AND type in (N'P', N'PC'))
DROP PROCEDURE [sPurchase].[pGetQRReport]
GO
/****** Object:  StoredProcedure [sPurchase].[pGetQCReport]    Script Date: 01-02-2024 12:00:42 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[sPurchase].[pGetQCReport]') AND type in (N'P', N'PC'))
DROP PROCEDURE [sPurchase].[pGetQCReport]
GO
/****** Object:  StoredProcedure [sPurchase].[pGetIGReport]    Script Date: 01-02-2024 12:00:42 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[sPurchase].[pGetIGReport]') AND type in (N'P', N'PC'))
DROP PROCEDURE [sPurchase].[pGetIGReport]
GO
/****** Object:  StoredProcedure [sPurchase].[pGetGRNReport]    Script Date: 01-02-2024 12:00:42 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[sPurchase].[pGetGRNReport]') AND type in (N'P', N'PC'))
DROP PROCEDURE [sPurchase].[pGetGRNReport]
GO
/****** Object:  StoredProcedure [sPurchase].[pEventTemplateGet]    Script Date: 01-02-2024 12:00:42 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[sPurchase].[pEventTemplateGet]') AND type in (N'P', N'PC'))
DROP PROCEDURE [sPurchase].[pEventTemplateGet]
GO
/****** Object:  StoredProcedure [sPurchase].[pEventSMSTemplateIdGet]    Script Date: 01-02-2024 12:00:42 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[sPurchase].[pEventSMSTemplateIdGet]') AND type in (N'P', N'PC'))
DROP PROCEDURE [sPurchase].[pEventSMSTemplateIdGet]
GO
/****** Object:  StoredProcedure [sPurchase].[pDependentFunctionalityGet]    Script Date: 01-02-2024 12:00:42 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[sPurchase].[pDependentFunctionalityGet]') AND type in (N'P', N'PC'))
DROP PROCEDURE [sPurchase].[pDependentFunctionalityGet]
GO
/****** Object:  StoredProcedure [sPurchase].[pDependentConfigurationGet]    Script Date: 01-02-2024 12:00:42 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[sPurchase].[pDependentConfigurationGet]') AND type in (N'P', N'PC'))
DROP PROCEDURE [sPurchase].[pDependentConfigurationGet]
GO
/****** Object:  StoredProcedure [sPurchase].[pConfigurationSetupAddUpdate]    Script Date: 01-02-2024 12:00:42 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[sPurchase].[pConfigurationSetupAddUpdate]') AND type in (N'P', N'PC'))
DROP PROCEDURE [sPurchase].[pConfigurationSetupAddUpdate]
GO
/****** Object:  StoredProcedure [sPurchase].[pAttachmentLogAdd]    Script Date: 01-02-2024 12:00:42 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[sPurchase].[pAttachmentLogAdd]') AND type in (N'P', N'PC'))
DROP PROCEDURE [sPurchase].[pAttachmentLogAdd]
GO
/****** Object:  StoredProcedure [sPurchase].[pAttachmentLogAdd]    Script Date: 01-02-2024 12:00:42 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[sPurchase].[pAttachmentLogAdd]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [sPurchase].[pAttachmentLogAdd] AS'
END
GO

ALTER PROCEDURE [sPurchase].[pAttachmentLogAdd]
		@rMessageId NVARCHAR(MAX),
		@rAttachment NVARCHAR(MAX)
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	BEGIN
	    BEGIN TRANSACTION
		BEGIN TRY
			INSERT INTO sAlert.tAlertAttachmentLog VALUES (@rMessageId, @rAttachment)
	    COMMIT TRANSACTION
		END TRY
		BEGIN CATCH
		    ROLLBACK TRANSACTION
			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 [sPurchase].[pConfigurationSetupAddUpdate]    Script Date: 01-02-2024 12:00:42 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[sPurchase].[pConfigurationSetupAddUpdate]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [sPurchase].[pConfigurationSetupAddUpdate] AS'
END
GO

 -- select * from sConfig.tConfigurationSetup order by CreatedDateTime desc
 -- exec [sPurchase].[pConfigurationSetupAddUpdate] 'abcdefghijklmno',2010,9911,9911000000003,9911
ALTER PROCEDURE [sPurchase].[pConfigurationSetupAddUpdate]

	--@rConfigurationId [int],
	@rItemValue NVARCHAR(500),
	@rSourceTypeId INT,
	@rSourceId BIGINT,
	@rCreatedUserId BIGINT,
	@rOrgId INT

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
	BEGIN TRANSACTION
		 DECLARE @rConfigurationId INT = 542 --for Purchase StoreLocation
		 DELETE FROM sConfig.tConfigurationSetup
		 WHERE
		 ConfigurationId  = @rConfigurationId
		 AND SourceId=@rSourceId
		 AND SourceTypeId=@rSourceTypeId

		 DECLARE @lNextNumber BIGINT

		 EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sConfig.tConfigurationSetup', 0, 1, 1,@outNextNumber = @lNextNumber OUTPUT

		 IF NOT EXISTS(SELECT 1 FROM sConfig.tConfigurationSetup WHERE ConfigurationId = @rConfigurationId AND SourceId = @rSourceId AND SourceTypeId=@rSourceTypeId)
		 BEGIN

			IF(@rItemValue!='')
			BEGIN
			INSERT INTO [sConfig].[tConfigurationSetup]
				   ([Id]
				   ,[ConfigurationId]
				   ,[ItemValue]
				   ,[sourceTypeId]
				   ,[SourceId]
				   ,[CreatedUserId]
				   ,[CreatedDateTime]
					)
			 VALUES
				   (
					@lNextNumber,
					@rConfigurationId,
					@rItemValue,
					@rSourceTypeId,
					@rSourceId,
					@rCreatedUserId,
					sCommon.fGetDate()
					)
			  END
				  SELECT @rItemValue AS result
		  END
		  ELSE
		  BEGIN
			  UPDATE sConfig.tConfigurationSetup
				  SET ItemValue = @rItemValue,
				  UpdatedUserId = @rCreatedUserId,
				  UpdatedDateTime =  sCommon.fGetDate()

			  WHERE ConfigurationId  = @rConfigurationId AND SourceId=@rSourceId AND SourceTypeId=@rSourceTypeId
			  SELECT @rItemValue AS result
		  END

	COMMIT TRANSACTION
	END TRY

	BEGIN CATCH
    IF @@TRANCOUNT > 0
    ROLLBACK TRANSACTION


    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 [sPurchase].[pDependentConfigurationGet]    Script Date: 01-02-2024 12:00:42 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[sPurchase].[pDependentConfigurationGet]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [sPurchase].[pDependentConfigurationGet] AS'
END
GO


ALTER PROCEDURE [sPurchase].[pDependentConfigurationGet]
	  @rOrgId BIGINT,
	  @rOrgGroupId INT,
	  @rUserId BIGINT,
	  @rScreenId INT
AS
SET NOCOUNT ON

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

	BEGIN CATCH
    IF @@TRANCOUNT > 0
    ROLLBACK TRANSACTION

    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 [sPurchase].[pDependentFunctionalityGet]    Script Date: 01-02-2024 12:00:42 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[sPurchase].[pDependentFunctionalityGet]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [sPurchase].[pDependentFunctionalityGet] AS'
END
GO


ALTER PROCEDURE [sPurchase].[pDependentFunctionalityGet]
	  @rScreenId INT
AS
SET NOCOUNT ON

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

	BEGIN CATCH
    IF @@TRANCOUNT > 0
    ROLLBACK TRANSACTION

    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 [sPurchase].[pEventSMSTemplateIdGet]    Script Date: 01-02-2024 12:00:42 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[sPurchase].[pEventSMSTemplateIdGet]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [sPurchase].[pEventSMSTemplateIdGet] AS'
END
GO

ALTER PROCEDURE [sPurchase].[pEventSMSTemplateIdGet]
		@rOrgId INT,
		@rEventId INT
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	BEGIN
		BEGIN TRY
			SELECT SMSTemplateID FROM sAlert.tEventTemplate WHERE EventId = @rEventId AND OrgId=@rOrgId AND AlertModeId = 2
		END TRY
		BEGIN CATCH
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	    END CATCH
	END
GO
/****** Object:  StoredProcedure [sPurchase].[pEventTemplateGet]    Script Date: 01-02-2024 12:00:42 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[sPurchase].[pEventTemplateGet]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [sPurchase].[pEventTemplateGet] AS'
END
GO

ALTER PROCEDURE [sPurchase].[pEventTemplateGet]
		@rOrgId INT
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	BEGIN
		BEGIN TRY
			SELECT EventId,Template FROM sAlert.tEventTemplate WHERE IsAutoSend = 1 AND OrgId =@rOrgId AND EventId = 158
			 --AND AlertModeId in (3)
		END TRY
		BEGIN CATCH
		ROLLBACK TRANSACTION
		    SELECT -1 AS Result
	    END CATCH
	END
GO
/****** Object:  StoredProcedure [sPurchase].[pGetGRNReport]    Script Date: 01-02-2024 12:00:42 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[sPurchase].[pGetGRNReport]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [sPurchase].[pGetGRNReport] AS'
END
GO

-- exec [sPurchase].[pGetGRNReport] 991100001
ALTER PROCEDURE [sPurchase].[pGetGRNReport]
      @rGoodsReceivedNoteId INT,
	  @rUserId BIGINT,
	  @rOrgGroupId INT
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
	DECLARE @rStoreLocationId BIGINT
    SELECT @rStoreLocationId = ISNULL(ItemValue,0)
	FROM sConfig.tConfigurationSetup
	WHERE ConfigurationId  = 542 AND SourceId = @rUserId

	DECLARE @HTMLTable NVARCHAR(MAX);
	DECLARE
	@rGRNNumber AS NVARCHAR(20),
	@rPurchaseRequestNumber AS NVARCHAR(20),
	@rPurchaseOrderNumber AS NVARCHAR(20),
	@rRequestedBy AS NVARCHAR(100),
	@rPODueDate AS NVARCHAR(100),
	@rStatus AS NVARCHAR(100),
	@rVendorName AS NVARCHAR(300),
	@rBillToAddress AS NVARCHAR(1000)

	    SELECT @rGRNNumber = ISNULL(GRN.GRNNumber,''),
				@rPurchaseRequestNumber = ISNULL(PR.Number,''),
				@rPurchaseOrderNumber = ISNULL(PO.RefNumber,''),
				@rRequestedBy = ISNULL(GRN.RequestedBy,''),
				@rPODueDate = ISNULL(GRN.PODueDate,''),
				@rStatus = ISNULL(SM.Title,''),
				@rVendorName = ISNULL(VM.Title,''),
				@rBillToAddress = ISNULL(GRN.BillToAddress,'')
		FROM  [sPurchase].[tGoodsReceivedNote] GRN(NOLOCK)
			   LEFT JOIN sProcurement.tVendorMaster  VM ON GRN.VendorId = VM.ID AND VM.LocationId = @rStoreLocationId AND VM.OrgGroupId = @rOrgGroupId AND VM.IsObsolete = 0
			   LEFT JOIN [sWf].[tWfStatusMaster] SM ON SM.Id = GRN.StatusId
			   LEFT JOIN [sPurchase].[tPurchaseRequest] PR ON PR.ID = GRN.PurchaseRequestId AND PR.LocationId = @rStoreLocationId AND PR.OrgGroupId = @rOrgGroupId AND PR.IsObsolete = 0
			   LEFT JOIN [sPurchase].[tPurchaseOrder] PO ON PO.Id = GRN.PurchaseOrderId AND PO.LocationId = @rStoreLocationId AND PO.OrgGroupId = @rOrgGroupId AND PO.IsObsolete = 0
		WHERE  GRN.Id = @rGoodsReceivedNoteId AND GRN.IsObsolete = 0
               AND GRN.LocationId = @rStoreLocationId
			   AND GRN.OrgGroupId = @rOrgGroupId


    SET @HTMLTable = '';
	IF EXISTS (SELECT * FROM [sPurchase].[tGoodsReceivedNoteDetail] GRND
			WHERE  GRND.GoodsReceivedNoteId = @rGoodsReceivedNoteId)
    BEGIN
    SET @HTMLTable = @HTMLTable + '<tr>';
    SET @HTMLTable = @HTMLTable + '<th>StockItemCode</th>';
    SET @HTMLTable = @HTMLTable + '<th>StockItemName</th>';
    SET @HTMLTable = @HTMLTable + '<th>Uom</th>';
    SET @HTMLTable = @HTMLTable + '<th>POQty</th>';
	SET @HTMLTable = @HTMLTable + '<th>ReceivedQty</th>';
	SET @HTMLTable = @HTMLTable + '<th>PreviousGRNQty</th>';
	SET @HTMLTable = @HTMLTable + '<th>UnitPrice</th>';
    SET @HTMLTable = @HTMLTable + '</tr>';

	SELECT @HTMLTable = @HTMLTable+'<tr><td>'+ISNULL(CAST(SIM.Code AS NVARCHAR(100)),'')+'</td><td>'
+ISNULL(SIM.Title,'')+'</td><td>'+ISNULL(SUMa.Code,'')+'</td><td>'+ISNULL(CAST(GRND.POQty AS NVARCHAR(20)),'')+'</td><td>'+ISNULL(CAST(GRND.ReceivedQty AS NVARCHAR(20)),'')+'</td><td>'+ISNULL(CAST(GRND.PreviousGRNQty AS NVARCHAR(20)),'')+'</td><td>'+ISNULL(CAST(GRND.UnitPrice AS NVARCHAR(20)),'')+'</td></tr>'
	    FROM   [sPurchase].[tGoodsReceivedNoteDetail] GRND (NOLOCK)
		       INNER JOIN  sPurchase.tGoodsReceivedNote GRN ON GRN.Id = GRND.GoodsReceivedNoteId AND GRN.LocationId = @rStoreLocationId AND GRN.OrgGroupId = @rOrgGroupId AND GRN.IsObsolete = 0
			   INNER JOIN  sPurchase.tPurchaseOrder PO	ON PO.Id = GRN.PurchaseOrderId AND PO.LocationId = @rStoreLocationId AND PO.OrgGroupId = @rOrgGroupId AND PO.IsObsolete = 0
			   INNER JOIN  sIp.tStockItemMaster SIM	ON SIM.Id = GRND.StockItemId AND SIM.StoreLocationId = @rStoreLocationId AND SIM.OrgGroupId = @rOrgGroupId AND SIM.IsObsolete = 0
			   INNER JOIN  sFinanceCommon.tStockUomMaster SUMa ON SUMa.Id = SIM.IssueStockUomId
		WHERE  GRND.GoodsReceivedNoteId = @rGoodsReceivedNoteId AND GRN.IsObsolete = 0
		       AND GRN.LocationId = @rStoreLocationId
			   AND GRN.OrgGroupId = @rOrgGroupId
    END

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

		AS Template FROM sPurchase.tPurchaseReportTemplateMaster WHERE Code='GRN' AND IsObsolete = 0

	END TRY

	BEGIN CATCH
    IF @@TRANCOUNT > 0
    ROLLBACK TRANSACTION


    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 [sPurchase].[pGetIGReport]    Script Date: 01-02-2024 12:00:42 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[sPurchase].[pGetIGReport]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [sPurchase].[pGetIGReport] AS'
END
GO

-- exec [sPurchase].[pGetIGReport] 991100001
ALTER PROCEDURE [sPurchase].[pGetIGReport]
      @rInvoiceGenerateId INT,
	  @rUserId BIGINT,
	  @rOrgGroupId INT
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
	DECLARE @rStoreLocationId BIGINT
    SELECT @rStoreLocationId = ISNULL(ItemValue,0)
	FROM sConfig.tConfigurationSetup
	WHERE ConfigurationId  = 542 AND SourceId = @rUserId

	DECLARE @HTMLTable NVARCHAR(MAX);
	DECLARE
	@rINVNumber AS NVARCHAR(20),
	@rGRNNumber AS NVARCHAR(20),
	@rRequestedBy AS NVARCHAR(100),
	@rStatus AS NVARCHAR(100),
	@rInvoiceDate AS NVARCHAR(100),
	@rInvoiceDueDate AS NVARCHAR(100),
	@rBillToAddress AS NVARCHAR(1000),
	@rShipToAddress AS NVARCHAR(1000),
	@rRemarks AS NVARCHAR(500),
	@rVendorCode AS NVARCHAR(100),
	@rVendorName AS NVARCHAR(300)

	    SELECT  @rINVNumber = ISNULL(IG.INVNumber,''),
		        @rGRNNumber = ISNULL(GRN.GRNNumber,''),
				@rRequestedBy = ISNULL(IG.RequestedBy,''),
				@rStatus = ISNULL(SM.Title,''),
				@rInvoiceDate = ISNULL(IG.InvoiceDate,''),
		        @rInvoiceDueDate = ISNULL(IG.InvoiceDueDate,''),
				@rBillToAddress = ISNULL(IG.BillToAddress,''),
				@rShipToAddress = ISNULL(IG.ShipToAddress,''),
		        @rRemarks = ISNULL(IG.Remarks,''),
				@rVendorCode = ISNULL(VM.Code,''),
				@rVendorName = ISNULL(VM.Title,'')
		FROM   [sPurchase].[tInvoiceGenerate] IG(NOLOCK)
		       LEFT JOIN sProcurement.tVendorMaster  VM ON IG.VendorId = VM.ID AND VM.LocationId = @rStoreLocationId AND VM.OrgGroupId = @rOrgGroupId AND VM.IsObsolete = 0
			   LEFT JOIN [sWf].[tWfStatusMaster] SM ON SM.Id = IG.StatusId
			   LEFT JOIN [sPurchase].[tGoodsReceivedNote] GRN ON GRN.Id = IG.GoodsReceivedNoteId AND GRN.LocationId = @rStoreLocationId AND GRN.OrgGroupId = @rOrgGroupId AND GRN.IsObsolete = 0
		WHERE  IG.Id = @rInvoiceGenerateId AND IG.IsObsolete = 0
		       AND IG.LocationId = @rStoreLocationId
			   AND IG.OrgGroupId = @rOrgGroupId

    SET @HTMLTable = '';
	IF EXISTS(SELECT * FROM [sPurchase].[tInvoiceGenerateDetail] IGD
			WHERE  IGD.InvoiceGenerateId = @rInvoiceGenerateId)

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

	SELECT @HTMLTable = @HTMLTable+'<tr><td>'+ISNULL(CAST(SIM.Code AS NVARCHAR(100)),'')+'</td><td>'
+ISNULL(SIM.Title,'')+'</td><td>'+ISNULL(SUMa.Code,'')+'</td><td>'+ISNULL(CAST(IGD.POQty AS NVARCHAR(100)),'')+'</td><td>'+ISNULL(CAST(IGD.ReceivedQty AS NVARCHAR(20)),'')+'</td><td>'+ISNULL(CAST(IGD.AcceptedQty AS NVARCHAR(20)),'')+'</td><td>'+ISNULL(CAST(IGD.RejectedQty AS NVARCHAR(20)),'')+'</td><td>'+ISNULL(CAST(IGD.ReasonForRejection AS NVARCHAR(300)),'')+'</td></tr>'
	    FROM   [sPurchase].[tInvoiceGenerateDetail] IGD(NOLOCK)
		       INNER JOIN  [sPurchase].[tInvoiceGenerate] IG ON IG.Id = IGD.InvoiceGenerateId AND IG.LocationId = @rStoreLocationId AND IG.OrgGroupId = @rOrgGroupId AND IG.IsObsolete = 0
			   INNER JOIN	sIp.tStockItemMaster SIM	ON SIM.Id = IGD.StockItemId AND SIM.StoreLocationId = @rStoreLocationId AND SIM.OrgGroupId = @rOrgGroupId AND SIM.IsObsolete = 0
			   INNER JOIN  sFinanceCommon.tStockUomMaster SUMa ON SUMa.Id = SIM.IssueStockUomId
		WHERE  IGD.InvoiceGenerateId = @rInvoiceGenerateId AND IG.IsObsolete = 0
		       AND IG.LocationId = @rStoreLocationId
			   AND IG.OrgGroupId = @rOrgGroupId

    END

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

		AS Template FROM sPurchase.tPurchaseReportTemplateMaster WHERE Code='IG' AND IsObsolete = 0

	END TRY

	BEGIN CATCH
    IF @@TRANCOUNT > 0
    ROLLBACK TRANSACTION


    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 [sPurchase].[pGetQCReport]    Script Date: 01-02-2024 12:00:42 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[sPurchase].[pGetQCReport]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [sPurchase].[pGetQCReport] AS'
END
GO

-- exec [sPurchase].[pGetQCReport] 991100001
ALTER PROCEDURE [sPurchase].[pGetQCReport]
      @rQualityCheckId INT,
	  @rUserId BIGINT,
	  @rOrgGroupId INT
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
	DECLARE @rStoreLocationId BIGINT
    SELECT @rStoreLocationId = ISNULL(ItemValue,0)
	FROM sConfig.tConfigurationSetup
	WHERE ConfigurationId  = 542 AND SourceId = @rUserId

	DECLARE @HTMLTable NVARCHAR(MAX);


	DECLARE
	@rQCNumber AS NVARCHAR(100),
	@rGRNNumber AS NVARCHAR(100),
	@rRequestedBy AS NVARCHAR(100),
	@rStatus AS NVARCHAR(100),
	@rQualityCheckDetails AS NVARCHAR(100)

	    SELECT  @rQCNumber = ISNULL(QC.QCNumber,''),
		        @rGRNNumber = ISNULL(GRN.GRNNumber,''),
				@rRequestedBy = ISNULL(QC.RequestedBy,''),
				@rStatus = ISNULL(SM.Title,'')
		FROM   [sPurchase].[tQualityCheck] QC(NOLOCK)
			   LEFT JOIN [sWf].[tWfStatusMaster] SM ON SM.Id = QC.StatusId
			   LEFT JOIN [sPurchase].[tGoodsReceivedNote] GRN ON GRN.Id = QC.GoodsReceivedNoteId AND GRN.LocationId = @rStoreLocationId AND GRN.OrgGroupId = @rOrgGroupId AND GRN.IsObsolete = 0
		WHERE  QC.Id = @rQualityCheckId AND QC.IsObsolete = 0
		       AND QC.LocationId = @rStoreLocationId
			   AND QC.OrgGroupId = @rOrgGroupId


    SET @HTMLTable = '';
	IF EXISTS(SELECT *  FROM [sPurchase].[tQualityCheckDetail] QCD
			WHERE QCD.QualityCheckId = @rQualityCheckId)
	BEGIN
    SET @HTMLTable = @HTMLTable + '<tr>';
    SET @HTMLTable = @HTMLTable + '<th>StockItemCode</th>';
    SET @HTMLTable = @HTMLTable + '<th>StockItemName</th>';
    SET @HTMLTable = @HTMLTable + '<th>Uom</th>';
    SET @HTMLTable = @HTMLTable + '<th>POQty</th>';
	SET @HTMLTable = @HTMLTable + '<th>ReceivedQty</th>';
	SET @HTMLTable = @HTMLTable + '<th>AcceptedQty</th>';
	SET @HTMLTable = @HTMLTable + '<th>RejectedQty</th>';
	SET @HTMLTable = @HTMLTable + '<th>ReasonForRejection</th>';
    SET @HTMLTable = @HTMLTable + '</tr>';

	SELECT @HTMLTable = @HTMLTable+'<tr><td>'+ISNULL(CAST(SIM.Code AS NVARCHAR(100)),'')+'</td><td>'
+ISNULL(SIM.Title,'')+'</td><td>'+ISNULL(SUMa.Code,'')+'</td><td>'+ISNULL(CAST(QCD.POQty AS NVARCHAR(100)),'')+'</td><td>'+ISNULL(CAST(QCD.ReceivedQty AS NVARCHAR(100)),'')+'</td><td>'+ISNULL(CAST(QCD.AcceptedQty AS NVARCHAR(100)),'')+'</td><td>'+ISNULL(CAST(QCD.RejectedQty AS NVARCHAR(100)),'')+'</td><td>'+ISNULL(CAST(QCD.ReasonForRejection AS NVARCHAR(100)),'')+'</td></tr>'
	    FROM   [sPurchase].[tQualityCheckDetail] QCD (NOLOCK)
		       INNER JOIN  [sPurchase].[tQualityCheck] QC ON QC.Id = QCD.QualityCheckId AND QC.LocationId = @rStoreLocationId AND QC.OrgGroupId = @rOrgGroupId AND QC.IsObsolete = 0
			   INNER JOIN	sIp.tStockItemMaster SIM	ON SIM.Id = QCD.StockItemId AND SIM.StoreLocationId = @rStoreLocationId AND SIM.OrgGroupId = @rOrgGroupId AND SIM.IsObsolete = 0
			   INNER JOIN  sFinanceCommon.tStockUomMaster SUMa ON SUMa.Id = SIM.IssueStockUomId
		WHERE  QCD.QualityCheckId = @rQualityCheckId AND QC.IsObsolete = 0
		       AND QC.LocationId = @rStoreLocationId
			   AND QC.OrgGroupId = @rOrgGroupId
    END

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

		AS Template FROM sPurchase.tPurchaseReportTemplateMaster WHERE Code='QC' AND IsObsolete = 0

	END TRY

	BEGIN CATCH
    IF @@TRANCOUNT > 0
    ROLLBACK TRANSACTION


    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 [sPurchase].[pGetQRReport]    Script Date: 01-02-2024 12:00:42 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[sPurchase].[pGetQRReport]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [sPurchase].[pGetQRReport] AS'
END
GO

-- exec [sPurchase].[pGetQRReport] 991100004
ALTER PROCEDURE [sPurchase].[pGetQRReport]
      @rQuotationRequestId INT,
	  @rUserId BIGINT,
	  @rOrgGroupId INT
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
	DECLARE @rStoreLocationId BIGINT
    SELECT @rStoreLocationId = ISNULL(ItemValue,0)
	FROM sConfig.tConfigurationSetup
	WHERE ConfigurationId  = 542 AND SourceId = @rUserId

	DECLARE @HTMLTable NVARCHAR(MAX);

	DECLARE
	@rNumber AS NVARCHAR(20),
	@rName AS NVARCHAR(100),
	@rRFQDate AS NVARCHAR(100),
	@rStatus AS NVARCHAR(100),
	@rDescription AS NVARCHAR(300),
	@rStartDate AS NVARCHAR(100),
	@rEndDate AS NVARCHAR(100),
	@rBidOpen AS NVARCHAR(50),
	@rBidClose AS NVARCHAR(50),
	@rPersonContact AS NVARCHAR(50),
	@rEmail AS NVARCHAR(50),
	@rSendToVendor AS NVARCHAR(10),
	@rVendorCode AS NVARCHAR(100),
	@rVendorName AS NVARCHAR(300),
	@rPurchaseNumber AS NVARCHAR(20)

	    SELECT  @rNumber = ISNULL(QR.Number,''),
		        @rName = ISNULL(QR.Name,''),
				@rRFQDate = ISNULL(QR.RFQDate,''),
				@rStatus = ISNULL(SM.Title,''),
				@rDescription = ISNULL(QR.Description,''),
		        @rStartDate = ISNULL(QR.StartDate,''),
				@rEndDate = ISNULL(QR.EndDate,''),
				@rBidOpen = ISNULL(QR.BidOpen,''),
		        @rBidClose = ISNULL(QR.BidClose,''),
				@rPersonContact = ISNULL(QR.PersonContact,''),
				@rEmail = ISNULL(QR.Email,''),
		        @rSendToVendor = ISNULL(QR.SendToVendor,''),
				@rVendorCode = ISNULL(VM.Code,''),
				@rVendorName = ISNULL(VM.Title,''),
				@rPurchaseNumber = ISNULL(PR.Number,'')
		FROM   [sPurchase].[tQuotationRequest] QR(NOLOCK)
		       LEFT JOIN sProcurement.tVendorMaster  VM ON QR.VendorId = VM.ID AND VM.LocationId = @rStoreLocationId AND VM.OrgGroupId = @rOrgGroupId AND VM.IsObsolete = 0
			   LEFT JOIN [sWf].[tWfStatusMaster] SM ON SM.Id = QR.StatusId
			   LEFT JOIN [sPurchase].[tPurchaseRequest] PR ON PR.Id = QR.PurchaseRequestId AND PR.LocationId = @rStoreLocationId AND PR.OrgGroupId = @rOrgGroupId AND PR.IsObsolete = 0
		WHERE  QR.Id = @rQuotationRequestId AND QR.IsObsolete = 0
		       AND QR.LocationId = @rStoreLocationId
			   AND QR.OrgGroupId = @rOrgGroupId


    SET @HTMLTable = '';

	IF EXISTS(SELECT * FROM  [sPurchase].[tQuotationRequestDetail] QRD
			WHERE  QRD.QuotationRequestId = @rQuotationRequestId)
	BEGIN
		SET @HTMLTable = @HTMLTable + '<tr>';
		SET @HTMLTable = @HTMLTable + '<th>StockItemCode</th>';
		SET @HTMLTable = @HTMLTable + '<th>StockItemName</th>';
		SET @HTMLTable = @HTMLTable + '<th>Uom</th>';
		SET @HTMLTable = @HTMLTable + '<th>RequestedQty</th>';
		SET @HTMLTable = @HTMLTable + '<th>TargetPrice</th>';
		SET @HTMLTable = @HTMLTable + '<th>Remark</th>';
		SET @HTMLTable = @HTMLTable + '</tr>';

		SELECT @HTMLTable = @HTMLTable+'<tr><td>'+ISNULL(CAST(SIM.Code AS NVARCHAR(100)),'')+'</td><td>'
	+ISNULL(SIM.Title,'')+'</td><td>'+ISNULL(SUMa.Code,'')+'</td><td>'+ISNULL(CAST(QRD.RequestedQty AS NVARCHAR(20)),'')+'</td><td>'+ISNULL(CAST(QRD.TargetPrice AS NVARCHAR(20)),'')+'</td><td>'+ISNULL(CAST(QRD.Remark AS NVARCHAR(300)),'')+'</td></tr>'
			FROM   [sPurchase].[tQuotationRequestDetail] QRD(NOLOCK)
			       INNER JOIN [sPurchase].[tQuotationRequest] QR ON QR.Id = QRD.QuotationRequestId AND QR.LocationId = @rStoreLocationId AND QR.OrgGroupId = @rOrgGroupId AND QR.IsObsolete = 0
				   INNER JOIN	sIp.tStockItemMaster SIM	ON SIM.Id = QRD.StockItemId AND SIM.StoreLocationId = @rStoreLocationId AND SIM.OrgGroupId = @rOrgGroupId AND SIM.IsObsolete = 0
				   INNER JOIN  sFinanceCommon.tStockUomMaster SUMa ON SUMa.Id = SIM.IssueStockUomId
			WHERE  QRD.QuotationRequestId = @rQuotationRequestId AND QR.IsObsolete = 0
			       AND QR.LocationId = @rStoreLocationId
			       AND QR.OrgGroupId = @rOrgGroupId
	END


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

		AS Template FROM sPurchase.tPurchaseReportTemplateMaster WHERE Code='QR' AND IsObsolete = 0

	END TRY

	BEGIN CATCH
    IF @@TRANCOUNT > 0
    ROLLBACK TRANSACTION


    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 [sPurchase].[pGetSRReport]    Script Date: 01-02-2024 12:00:42 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[sPurchase].[pGetSRReport]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [sPurchase].[pGetSRReport] AS'
END
GO
-- select * from sPurchase.tPurchaseReportTemplate where id=6
-- exec [sPurchase].[pGetSRReport] 991100001
ALTER PROCEDURE [sPurchase].[pGetSRReport]
      @rSalesReturnId INT,
	  @rUserId BIGINT,
	  @rOrgGroupId INT
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
	DECLARE @rStoreLocationId BIGINT
    SELECT @rStoreLocationId = ISNULL(ItemValue,0)
	FROM sConfig.tConfigurationSetup
	WHERE ConfigurationId  = 542 AND SourceId = @rUserId

	DECLARE @HTMLTable NVARCHAR(MAX);


	DECLARE
	@rSRNumber AS NVARCHAR(20),
	@rGRNNumber AS NVARCHAR(20),
	@rRequestedBy AS NVARCHAR(100),
	@rStatus AS NVARCHAR(100),
	@rVendorName AS NVARCHAR(300),
	@rPurchaseOrderNumber AS NVARCHAR(20)

	    SELECT  @rSRNumber = ISNULL(SR.SRNumber,''),
		        @rGRNNumber = ISNULL(GRN.GRNNumber,''),
				@rRequestedBy = ISNULL(SR.RequestedBy,''),
				@rStatus = ISNULL(SM.Title,''),
				@rVendorName = ISNULL(VM.Title,''),
				@rPurchaseOrderNumber = ISNULL(PO.RefNumber,'')
		FROM   [sPurchase].[tSalesReturn] SR(NOLOCK)
		       LEFT JOIN sProcurement.tVendorMaster  VM ON SR.VendorId = VM.ID AND VM.LocationId = @rStoreLocationId AND VM.OrgGroupId = @rOrgGroupId AND VM.IsObsolete = 0
			   LEFT JOIN [sWf].[tWfStatusMaster] SM ON SM.Id = SR.StatusId
			   LEFT JOIN [sPurchase].[tGoodsReceivedNote] GRN ON GRN.Id = SR.GoodsReceivedNoteId AND GRN.LocationId = @rStoreLocationId AND GRN.OrgGroupId = @rOrgGroupId AND GRN.IsObsolete = 0
			   LEFT JOIN [sPurchase].[tPurchaseOrder] PO ON PO.Id = SR.PurchaseOrderId AND PO.LocationId = @rStoreLocationId AND PO.OrgGroupId = @rOrgGroupId AND PO.IsObsolete = 0
		WHERE  SR.Id = @rSalesReturnId  AND SR.LocationId = @rStoreLocationId AND SR.OrgGroupId = @rOrgGroupId AND SR.IsObsolete = 0


    SET @HTMLTable = '';
	IF EXISTS(SELECT *  FROM   [sPurchase].[tSalesReturnDetail] SRD
			WHERE  SRD.SalesReturnId = @rSalesReturnId)
    BEGIN
    SET @HTMLTable = @HTMLTable + '<tr>';
    SET @HTMLTable = @HTMLTable + '<th>StockItemCode</th>';
    SET @HTMLTable = @HTMLTable + '<th>StockItemName</th>';
    SET @HTMLTable = @HTMLTable + '<th>Uom</th>';
    SET @HTMLTable = @HTMLTable + '<th>POQty</th>';
	SET @HTMLTable = @HTMLTable + '<th>ReceivedQty</th>';
	SET @HTMLTable = @HTMLTable + '<th>RejectedQty</th>';
	SET @HTMLTable = @HTMLTable + '<th>CreditNoteIssueDate</th>';
	SET @HTMLTable = @HTMLTable + '<th>ReasonForRejection</th>';
    SET @HTMLTable = @HTMLTable + '</tr>';

	SELECT @HTMLTable = @HTMLTable+'<tr><td>'+ISNULL(CAST(SIM.Code AS NVARCHAR(100)),'')+'</td><td>'
+ISNULL(SIM.Title,'')+'</td><td>'+ISNULL(SUMa.Code,'')+'</td><td>'+ISNULL(CAST(SRD.POQty AS NVARCHAR(20)),'')+'</td><td>'+ISNULL(CAST(SRD.ReceivedQty AS NVARCHAR(20)),'')+'</td><td>'+ISNULL(CAST(SRD.RejectedQty AS NVARCHAR(20)),'')+'</td><td>'+ISNULL(CAST(SRD.CreditNoteIssueDate AS NVARCHAR(100)),'')+'</td><td>'+ISNULL(CAST(SRD.ReasonForRejection AS NVARCHAR(300)),'')+'</td></tr>'
	    FROM   [sPurchase].[tSalesReturnDetail] SRD(NOLOCK)
			   INNER JOIN  [sPurchase].[tSalesReturn] SR ON SR.Id = SRD.SalesReturnId AND SR.LocationId = @rStoreLocationId AND SR.OrgGroupId = @rOrgGroupId AND SR.IsObsolete = 0
			   INNER JOIN	sIp.tStockItemMaster SIM	ON SIM.Id = SRD.StockItemId AND SIM.StoreLocationId = @rStoreLocationId AND SIM.OrgGroupId = @rOrgGroupId AND SIM.IsObsolete = 0
			   INNER JOIN  sFinanceCommon.tStockUomMaster SUMa ON SUMa.Id = SIM.IssueStockUomId
		WHERE  SRD.SalesReturnId = @rSalesReturnId AND SRD.OrgGroupId = @rOrgGroupId

   END
SELECT REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(Template,
		'{SRNumber}' , @rSRNumber),
		'{GRNNumber}' , @rGRNNumber),
		'{RequestedBy}' , @rRequestedBy),
		'{Status}' , @rStatus),
		'{VendorName}' , @rVendorName),
		'{PurchaseOrderNumber}' , @rPurchaseOrderNumber),
		'{SalesReturnDetails}' , ISNULL(@HTMLTable,''))

		AS Template FROM sPurchase.tPurchaseReportTemplateMaster WHERE Code='SR' AND IsObsolete = 0

	END TRY

	BEGIN CATCH
    IF @@TRANCOUNT > 0
    ROLLBACK TRANSACTION


    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 [sPurchase].[pGetStoreLocationConfig]    Script Date: 01-02-2024 12:00:42 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[sPurchase].[pGetStoreLocationConfig]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [sPurchase].[pGetStoreLocationConfig] AS'
END
GO


-- exec [sPurchase].[pGetStoreLocationConfig] 95,9911000000003
ALTER PROCEDURE [sPurchase].[pGetStoreLocationConfig]
	@rSourceTypeId INT,
	@rSourceId BIGINT

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
		 DECLARE @result INT
		 SELECT @result=ISNULL(ItemValue,0)
		 FROM sConfig.tConfigurationSetup
		 WHERE ConfigurationId  = 542 AND SourceId=@rSourceId AND SourceTypeId=@rSourceTypeId
		 SELECT ISNULL(@result,0)
	END TRY

	BEGIN CATCH
    IF @@TRANCOUNT > 0
    ROLLBACK TRANSACTION

    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 [sPurchase].[pGetTemplate]    Script Date: 01-02-2024 12:00:42 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[sPurchase].[pGetTemplate]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [sPurchase].[pGetTemplate] AS'
END
GO

--exec [sPurchase].[pGetTemplate] 991100001
ALTER PROCEDURE [sPurchase].[pGetTemplate]
      @rPurchaseOrderId INT,
	  @rUserId BIGINT,
	  @rOrgGroupId INT
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
	DECLARE @rStoreLocationId BIGINT
    SELECT @rStoreLocationId = ISNULL(ItemValue,0)
	FROM sConfig.tConfigurationSetup
	WHERE ConfigurationId  = 542 AND SourceId = @rUserId

	DECLARE @HTMLTable NVARCHAR(MAX);

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

	    SELECT  @rRefNumber = ISNULL(PO.RefNumber,''),
				@rPurchaseRequestNumber = ISNULL(PR.Number,''),
				@rRequestedBy = ISNULL(PO.RequestedBy,''),
				@rPoDate = ISNULL(PO.PODate,''),
				@rStatus = ISNULL(SM.Title,''),
				@rVendorCode = ISNULL(VM.Code,''),
				@rVendorName = ISNULL(VM.Title,''),
				@rRequiredBy = ISNULL(PO.RequiredBy,''),
				@rBillToAddress = ISNULL(PO.BillToAddress,''),
				@rShipToAddress = ISNULL(PO.ShipToAddress,'')
		FROM   [sPurchase].[tPurchaseOrder] PO(NOLOCK)
			   LEFT JOIN sProcurement.tVendorMaster  VM ON PO.VendorId = VM.ID AND VM.LocationId = @rStoreLocationId AND VM.OrgGroupId = @rOrgGroupId AND VM.IsObsolete = 0
			   LEFT JOIN [sWf].[tWfStatusMaster] SM ON SM.Id = PO.StatusId
			   LEFT JOIN [sPurchase].[tPurchaseRequest] PR ON PR.Id = PO.PurchaseRequestId AND PR.LocationId = @rStoreLocationId AND PR.OrgGroupId = @rOrgGroupId AND PR.IsObsolete = 0
		WHERE  PO.Id = @rPurchaseOrderId AND PO.IsObsolete = 0
		       AND PO.LocationId = @rStoreLocationId
			   AND PO.OrgGroupId = @rOrgGroupId


    SET @HTMLTable = '';
	IF EXISTS(SELECT *  FROM   [sPurchase].[tPurchaseOrderDetail] POD
			WHERE  POD.PurchaseOrderId = @rPurchaseOrderId)
    BEGIN
    SET @HTMLTable = @HTMLTable + '<tr>';
    SET @HTMLTable = @HTMLTable + '<th>StockItemCode</th>';
    SET @HTMLTable = @HTMLTable + '<th>StockItemName</th>';
    SET @HTMLTable = @HTMLTable + '<th>Uom</th>';
    SET @HTMLTable = @HTMLTable + '<th>TotalQty</th>';
    SET @HTMLTable = @HTMLTable + '</tr>';

	SELECT @HTMLTable = @HTMLTable+'<tr><td>'+ISNULL(CAST(SIM.Code AS NVARCHAR(100)),'')+'</td><td>'
+ISNULL(SIM.Title,'')+'</td><td>'+ISNULL(SUMa.Code,'')+'</td><td>'+ISNULL(CAST(POD.TotalQty AS NVARCHAR(20)),'')+'</td></tr>'
	  FROM   [sPurchase].[tPurchaseOrderDetail] POD (NOLOCK)
			   INNER JOIN	sPurchase.tPurchaseOrder PO	ON PO.Id = POD.PurchaseOrderId AND PO.LocationId = @rStoreLocationId AND PO.OrgGroupId = @rOrgGroupId AND PO.IsObsolete = 0
			   INNER JOIN	sIp.tStockItemMaster SIM ON SIM.Id = POD.StockItemId AND SIM.StoreLocationId = @rStoreLocationId AND SIM.OrgGroupId = @rOrgGroupId AND SIM.IsObsolete = 0
			   INNER JOIN   sFinanceCommon.tStockUomMaster SUMa ON SUMa.Id = SIM.IssueStockUomId
		WHERE  POD.PurchaseOrderId = @rPurchaseOrderId AND PO.IsObsolete = 0
		       AND PO.LocationId = @rStoreLocationId
			   AND PO.OrgGroupId = @rOrgGroupId

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

		AS Template FROM sPurchase.tPurchaseReportTemplateMaster WHERE Code='PO' AND IsObsolete = 0

	END TRY

	BEGIN CATCH
    IF @@TRANCOUNT > 0
    ROLLBACK TRANSACTION

    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 [sPurchase].[pGoodsReceivedNoteAdd]    Script Date: 01-02-2024 12:00:42 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[sPurchase].[pGoodsReceivedNoteAdd]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [sPurchase].[pGoodsReceivedNoteAdd] AS'
END
GO


ALTER PROCEDURE [sPurchase].[pGoodsReceivedNoteAdd]
		@rId BIGINT,
		@rPurchaseRequestId BIGINT,
		@rPurchaseOrderId BIGINT,
		@rPODueDate DATETIME,
		@rRequestedBy NVARCHAR(100),
		@rOrgGroupId SMALLINT,
		@rStatusId SMALLINT,
		@rVendorId INT,
		@rBillToAddress NVARCHAR(1000),
		@rUserId BIGINT,
		@rDetailList sPurchase.GoodsReceivedNoteDetailType READONLY

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
	BEGIN TRANSACTION
	    DECLARE @rStoreLocationId BIGINT
        SELECT @rStoreLocationId = ISNULL(ItemValue,0)
	    FROM sConfig.tConfigurationSetup
	    WHERE ConfigurationId  = 542 AND SourceId = @rUserId

		IF(@rId > 0)
		BEGIN
		    IF NOT EXISTS(SELECT Id FROM sPurchase.tGoodsReceivedNote WHERE Id = @rId AND CreatedUserId = @rUserId  AND LocationId = @rStoreLocationId AND OrgGroupId = @rOrgGroupId AND IsObsolete = 0)
            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 LocationId = @rStoreLocationId AND OrgGroupId = @rOrgGroupId AND IsObsolete = 0

				DELETE FROM sPurchase.tGoodsReceivedNoteDetail
				WHERE Id NOT IN(SELECT Id FROM @rDetailList)
				AND GoodsReceivedNoteId = @rId AND OrgGroupId = @rOrgGroupId

				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 GRN.GoodsReceivedNoteId = @rId AND GRN.OrgGroupId = @rOrgGroupId

				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 AND GRN.OrgGroupId = @rOrgGroupId)

				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 AND GRN.OrgGroupId = @rOrgGroupId
				WHERE GRN.GoodsReceivedNoteId = @rId AND GRN.OrgGroupId = @rOrgGroupId))
				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,
						@rStoreLocationId,
						@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 TRANSACTION
	END TRY

	BEGIN CATCH
    IF @@TRANCOUNT > 0
    ROLLBACK TRANSACTION


    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 [sPurchase].[pGoodsReceivedNoteApprovedGet]    Script Date: 01-02-2024 12:00:42 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[sPurchase].[pGoodsReceivedNoteApprovedGet]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [sPurchase].[pGoodsReceivedNoteApprovedGet] AS'
END
GO

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

BEGIN
	BEGIN TRY
	    DECLARE @rStoreLocationId BIGINT
        SELECT @rStoreLocationId = ISNULL(ItemValue,0)
	    FROM sConfig.tConfigurationSetup
	    WHERE ConfigurationId  = 542 AND SourceId = @rUserId

		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 AND VM.OrgGroupId = @rOrgGroupId AND VM.LocationId = @rStoreLocationId AND VM.IsObsolete = 0
			   LEFT JOIN [sWf].[tWfStatusMaster] SM ON SM.Id = GRN.StatusId
			   LEFT JOIN [sPurchase].[tPurchaseRequest] PR ON PR.ID = GRN.PurchaseRequestId AND PR.LocationId = @rStoreLocationId AND PR.OrgGroupId = @rOrgGroupId AND PR.IsObsolete = 0
			   LEFT JOIN [sPurchase].[tPurchaseOrder] PO ON PO.Id = GRN.PurchaseOrderId AND PO.LocationId = @rStoreLocationId AND PO.OrgGroupId = @rOrgGroupId AND PO.IsObsolete = 0
		WHERE  GRN.Id=@rId AND GRN.IsObsolete = 0 AND GRN.StatusId = 3
		       AND GRN.LocationId = @rStoreLocationId
			   AND GRN.OrgGroupId = @rOrgGroupId

		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 AND GRN.LocationId = @rStoreLocationId AND GRN.OrgGroupId = @rOrgGroupId AND GRN.IsObsolete = 0
				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.LocationId = @rStoreLocationId AND GRN.OrgGroupId = @rOrgGroupId AND GRN.IsObsolete = 0
			   INNER JOIN	sIp.tStockItemMaster SIM	ON SIM.Id = GRND.StockItemId AND SIM.StoreLocationId = @rStoreLocationId AND SIM.OrgGroupId = @rOrgGroupId AND SIM.IsObsolete = 0
			   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 AND GRN.IsObsolete = 0
		       AND GRN.LocationId = @rStoreLocationId
			   AND GRN.OrgGroupId = @rOrgGroupId
	END TRY

	BEGIN CATCH
    IF @@TRANCOUNT > 0
    ROLLBACK TRANSACTION

    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 [sPurchase].[pGoodsReceivedNoteApprovedSearchGet]    Script Date: 01-02-2024 12:00:42 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[sPurchase].[pGoodsReceivedNoteApprovedSearchGet]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [sPurchase].[pGoodsReceivedNoteApprovedSearchGet] AS'
END
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,
	@rUserId BIGINT

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	    DECLARE @rStoreLocationId BIGINT
        SELECT @rStoreLocationId = ISNULL(ItemValue,0)
	    FROM sConfig.tConfigurationSetup
	    WHERE ConfigurationId  = 542 AND SourceId = @rUserId

		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;
		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 ((GRN.LocationId = @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 AND QC.LocationId = @rStoreLocationId AND QC.OrgGroupId = @rOrgGroupId AND QC.IsObsolete = 0
				  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 AND VM.LocationId = @rStoreLocationId AND VM.OrgGroupId = @rOrgGroupId AND VM.IsObsolete = 0
				LEFT JOIN [sPurchase].[tPurchaseRequest] PR ON PR.Id = GRN.PurchaseRequestId AND PR.LocationId = @rStoreLocationId AND PR.OrgGroupId = @rOrgGroupId AND PR.IsObsolete = 0
				LEFT JOIN [sPurchase].[tPurchaseOrder] PO ON PO.Id = GRN.PurchaseOrderId AND PO.LocationId = @rStoreLocationId AND PO.OrgGroupId = @rOrgGroupId AND PO.IsObsolete = 0
		WHERE
				((GRN.GRNNumber LIKE @rNumber+'%') OR (ISNULL(@rNumber,'') = ''))
   				AND ((GRN.RequestedBy LIKE @rName+'%') OR (ISNULL(@rName,'') = ''))
   				AND ((GRN.LocationId = @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 AND QC.LocationId = @rStoreLocationId AND QC.OrgGroupId = @rOrgGroupId AND QC.IsObsolete = 0
				  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 TRANSACTION

    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 [sPurchase].[pGoodsReceivedNoteDelete]    Script Date: 01-02-2024 12:00:42 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[sPurchase].[pGoodsReceivedNoteDelete]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [sPurchase].[pGoodsReceivedNoteDelete] AS'
END
GO



ALTER PROCEDURE [sPurchase].[pGoodsReceivedNoteDelete]
		@rId BIGINT,
		@rStatusId SMALLINT
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
	BEGIN TRANSACTION
		IF(@rId > 0)
		BEGIN
			UPDATE sPurchase.tGoodsReceivedNote
			SET
				StatusId = @rStatusId,
				IsObsolete = 1,
				DeletedDateTime = GETUTCDATE()
			WHERE Id = @rId AND IsObsolete = 0

			IF EXISTS(SELECT Id FROM sPurchase.tGoodsReceivedNoteDetail WHERE GoodsReceivedNoteId = @rId)
			BEGIN
				DELETE FROM sPurchase.tGoodsReceivedNoteDetail
				WHERE GoodsReceivedNoteId = @rId
			END
			SELECT 1
		END
	COMMIT TRANSACTION
	END TRY

	BEGIN CATCH
    IF @@TRANCOUNT > 0
    ROLLBACK TRANSACTION


    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 [sPurchase].[pGoodsReceivedNoteGet]    Script Date: 01-02-2024 12:00:42 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[sPurchase].[pGoodsReceivedNoteGet]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [sPurchase].[pGoodsReceivedNoteGet] AS'
END
GO

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

BEGIN
	BEGIN TRY
	    DECLARE @rStoreLocationId BIGINT
        SELECT @rStoreLocationId = ISNULL(ItemValue,0)
	    FROM sConfig.tConfigurationSetup
	    WHERE ConfigurationId  = 542 AND SourceId = @rUserId

		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 AND VM.LocationId = @rStoreLocationId AND VM.OrgGroupId = @rOrgGroupId AND VM.IsObsolete = 0
			   LEFT JOIN [sWf].[tWfStatusMaster] SM ON SM.Id = GRN.StatusId
			   LEFT JOIN [sPurchase].[tPurchaseRequest] PR ON PR.ID = GRN.PurchaseRequestId AND PR.LocationId = @rStoreLocationId AND PR.OrgGroupId = @rOrgGroupId AND PR.IsObsolete = 0
			   LEFT JOIN [sPurchase].[tPurchaseOrder] PO On PO.Id = GRN.PurchaseOrderId AND PO.LocationId = @rStoreLocationId AND PO.OrgGroupId = @rOrgGroupId AND PO.IsObsolete = 0
		WHERE  GRN.Id=@rId AND GRN.IsObsolete = 0
		       AND GRN.LocationId = @rStoreLocationId
			   AND GRN.OrgGroupId = @rOrgGroupId

		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.LocationId = @rStoreLocationId AND GRN.OrgGroupId = @rOrgGroupId AND GRN.IsObsolete = 0
			   INNER JOIN	sIp.tStockItemMaster SIM	ON SIM.Id = GRND.StockItemId AND SIM.StoreLocationId = @rStoreLocationId AND SIM.OrgGroupId = @rOrgGroupId AND SIM.IsObsolete = 0
			   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.IsObsolete = 0
		       AND GRN.LocationId = @rStoreLocationId
			   AND GRN.OrgGroupId = @rOrgGroupId
	END TRY

	BEGIN CATCH
    IF @@TRANCOUNT > 0
    ROLLBACK TRANSACTION

    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 [sPurchase].[pGoodsReceivedNoteSearchGet]    Script Date: 01-02-2024 12:00:42 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[sPurchase].[pGoodsReceivedNoteSearchGet]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [sPurchase].[pGoodsReceivedNoteSearchGet] AS'
END
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,
	@rUserId BIGINT

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	    DECLARE @rStoreLocationId BIGINT
        SELECT @rStoreLocationId = ISNULL(ItemValue,0)
	    FROM sConfig.tConfigurationSetup
	    WHERE ConfigurationId  = 542 AND SourceId = @rUserId

		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.tGoodsReceivedNote GRN(NOLOCK)



		WHERE
				((GRN.GRNNumber LIKE @rNumber+'%') OR (ISNULL(@rNumber,'') = ''))
   				AND ((GRN.RequestedBy LIKE @rName+'%') OR (ISNULL(@rName,'') = ''))
   				AND ((GRN.LocationId = @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 AND VM.LocationId = @rStoreLocationId AND VM.OrgGroupId = @rOrgGroupId AND VM.IsObsolete = 0
				LEFT JOIN [sPurchase].[tPurchaseRequest] PR ON PR.Id = GRN.PurchaseRequestId AND PR.LocationId = @rStoreLocationId AND PR.OrgGroupId = @rOrgGroupId AND PR.IsObsolete = 0
				LEFT JOIN [sPurchase].[tPurchaseOrder] PO ON PO.Id = GRN.PurchaseOrderId AND PO.LocationId = @rStoreLocationId AND PO.OrgGroupId = @rOrgGroupId AND PO.IsObsolete = 0
		WHERE
				((GRN.GRNNumber LIKE @rNumber+'%') OR (ISNULL(@rNumber,'') = ''))
   				AND ((GRN.RequestedBy LIKE @rName+'%') OR (ISNULL(@rName,'') = ''))
   				AND ((GRN.LocationId = @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 TRANSACTION

    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 [sPurchase].[pGoodsReceivedNoteSearchSRGet]    Script Date: 01-02-2024 12:00:42 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[sPurchase].[pGoodsReceivedNoteSearchSRGet]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [sPurchase].[pGoodsReceivedNoteSearchSRGet] AS'
END
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 = '',
	@rStartDate DATETIME = NULL,
	@rEndDate DATETIME = NULL,
	@rOrgGroupId INT,
	@rPageNo INT,
	@rPageSize INT,
	@rStatusId SMALLINT = NULL,
	@rUserId BIGINT

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	                DECLARE @rStoreLocationId BIGINT
					SELECT @rStoreLocationId = ISNULL(ItemValue,0)
					FROM sConfig.tConfigurationSetup
					WHERE ConfigurationId  = 542 AND SourceId = @rUserId

					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.tGoodsReceivedNote GRN (NOLOCK)

					WHERE
							((GRN.GRNNumber LIKE @rNumber+'%') OR (ISNULL(@rNumber,'') = ''))
   							AND ((GRN.RequestedBy LIKE @rName+'%') OR (ISNULL(@rName,'') = ''))
   							AND ((GRN.LocationId = @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
								   AND SR.LocationId = @rStoreLocationId AND SR.OrgGroupId = @rOrgGroupId AND SR.IsObsolete = 0
							INNER JOIN sPurchase.tGoodsReceivedNote GRN12 ON Sr.GoodsReceivedNoteId = Grn12.Id
								   AND GRN12.LocationId = @rStoreLocationId AND GRN12.OrgGroupId = @rOrgGroupId AND GRN12.IsObsolete = 0
							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
								   AND QC1.LocationId = @rStoreLocationId AND QC1.OrgGroupId = @rOrgGroupId AND QC1.IsObsolete = 0
							INNER JOIN   sPurchase.tQualityCheckDetail QCD1 ON QCD1.QualityCheckId = QC1.Id AND QCD1.RejectedQty > 0
							WHERE GRN12.Id = GRN.Id AND GRN12.LocationId = @rStoreLocationId AND GRN12.OrgGroupId = @rOrgGroupId AND GRN12.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.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
								   AND QC1.LocationId = @rStoreLocationId AND QC1.OrgGroupId = @rOrgGroupId AND QC1.IsObsolete = 0
							INNER JOIN   sPurchase.tQualityCheckDetail QCD1 ON QCD1.QualityCheckId = QC1.Id AND QCD1.RejectedQty > 0
							WHERE GRN12.Id = GRN.Id AND GRN12.LocationId = @rStoreLocationId AND GRN12.OrgGroupId = @rOrgGroupId AND GRN12.IsObsolete = 0) 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 ((GRN.LocationId = @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
								   AND QC1.LocationId = @rStoreLocationId AND QC1.OrgGroupId = @rOrgGroupId AND QC1.IsObsolete = 0
							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
								   AND SR.LocationId = @rStoreLocationId AND SR.OrgGroupId = @rOrgGroupId AND SR.IsObsolete = 0
							INNER JOIN sPurchase.tGoodsReceivedNote GRN1 ON SR.GoodsReceivedNoteId = GRN1.Id
								   AND GRN1.LocationId = @rStoreLocationId AND GRN1.OrgGroupId = @rOrgGroupId AND GRN1.IsObsolete = 0
							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 TRANSACTION

    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 [sPurchase].[pGoodsReceivedNoteSRGet]    Script Date: 01-02-2024 12:00:42 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[sPurchase].[pGoodsReceivedNoteSRGet]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [sPurchase].[pGoodsReceivedNoteSRGet] AS'
END
GO

--exec [sPurchase].[pGoodsReceivedNoteSRGet] 991100003
ALTER PROCEDURE [sPurchase].[pGoodsReceivedNoteSRGet]
	  @rId INT,
	  @rUserId BIGINT,
	  @rOrgGroupId INT
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
	    DECLARE @rStoreLocationId BIGINT
        SELECT @rStoreLocationId = ISNULL(ItemValue,0)
	    FROM sConfig.tConfigurationSetup
	    WHERE ConfigurationId  = 542 AND SourceId = @rUserId

		IF((SELECT
				(SELECT SUM(QCD1.RejectedQty) FROM sPurchase.tGoodsReceivedNote GRN12
			    INNER JOIN   sPurchase.tQualityCheck QC1 ON QC1.GoodsReceivedNoteId = GRN12.Id
					   AND QC1.LocationId = @rStoreLocationId AND QC1.OrgGroupId = @rOrgGroupId AND QC1.IsObsolete = 0
			    INNER JOIN   sPurchase.tQualityCheckDetail QCD1 ON QCD1.QualityCheckId = QC1.Id AND QCD1.RejectedQty > 0
				WHERE GRN12.Id = @rId AND GRN12.LocationId = @rStoreLocationId AND GRN12.OrgGroupId = @rOrgGroupId AND GRN12.IsObsolete = 0) -
				 (SELECT ISNULL(SUM(SRD.RejectedQty),0) FROM sPurchase.tSalesReturnDetail SRD
				INNER JOIN sPurchase.tSalesReturn SR ON SR.Id = SRD.SalesReturnId
				AND SR.LocationId = @rStoreLocationId AND SR.OrgGroupId = @rOrgGroupId AND SR.IsObsolete = 0
				INNER JOIN [sPurchase].[tGoodsReceivedNoteDetail] GRND ON SRD.GoodsReceivedNoteDetailId = GRND.Id
				AND GRND.GoodsReceivedNoteId = @rId
				WHERE SR.GoodsReceivedNoteId = @rId AND SR.LocationId = @rStoreLocationId AND SR.OrgGroupId = @rOrgGroupId AND SR.IsObsolete = 0)) = 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 AND QC.LocationId = @rStoreLocationId AND QC.OrgGroupId = @rOrgGroupId AND QC.IsObsolete = 0
				   INNER JOIN sPurchase.tPurchaseOrder PO ON PO.Id = GRN.PurchaseOrderId AND PO.LocationId = @rStoreLocationId AND PO.OrgGroupId = @rOrgGroupId AND PO.IsObsolete = 0
				   LEFT JOIN  sProcurement.tVendorMaster  VM ON GRN.VendorId = VM.ID AND VM.LocationId = @rStoreLocationId AND VM.OrgGroupId = @rOrgGroupId AND VM.IsObsolete = 0
				   LEFT Join  sWf.tWfStatusMaster SM ON SM.Id = GRN.StatusId
			WHERE  GRN.Id=@rId AND GRN.StatusId = 3 AND GRN.LocationId = @rStoreLocationId AND GRN.OrgGroupId = @rOrgGroupId AND GRN.IsObsolete = 0

			SELECT DISTINCT GRND.Id AS GoodsReceivedNoteDetailId,
				   GRND.GoodsReceivedNoteId,
				   GRND.PurchaseOrderDetailId,
				   GRND.OrgGroupId,
				   SUMa.Id AS UnitTypeId,
				   GRND.StockItemId,
				   GRND.POQty,
				   GRND.ReceivedQty,
				   GRND.PreviousGRNQty,
				   GRND.UnitPrice,
				   GRND.Remark,
				 --  (SELECT Sum(QCD1.RejectedQty) FROM sPurchase.tGoodsReceivedNote GRN12
				 --   INNER JOIN   sPurchase.tQualityCheck QC1 ON QC1.GoodsReceivedNoteId = GRN12.Id
				 --   INNER JOIN   sPurchase.tQualityCheckDetail QCD1 ON QCD1.QualityCheckId = QC1.Id AND QCD1.RejectedQty > 0
					--WHERE GRN12.Id = GRN.Id) AS RejectedQty,
					(SELECT SUM(QCD1.RejectedQty) FROM sPurchase.tGoodsReceivedNote GRN12
					INNER JOIN   sPurchase.tQualityCheck QC1 ON QC1.GoodsReceivedNoteId = GRN12.Id
						   AND QC1.LocationId = @rStoreLocationId AND QC1.OrgGroupId = @rOrgGroupId AND QC1.IsObsolete = 0
					INNER JOIN   sPurchase.tQualityCheckDetail QCD1 ON QCD1.QualityCheckId = QC1.Id AND QCD1.RejectedQty > 0
					WHERE GRN12.Id = GRN.Id AND GRN12.LocationId = @rStoreLocationId AND GRN12.OrgGroupId = @rOrgGroupId AND GRN12.IsObsolete = 0) -
					 (SELECT ISNULL(SUM(SRD.RejectedQty),0) FROM sPurchase.tSalesReturnDetail SRD
					INNER JOIN sPurchase.tSalesReturn SR ON SR.Id = SRD.SalesReturnId AND SR.LocationId = @rStoreLocationId AND SR.OrgGroupId = @rOrgGroupId AND SR.IsObsolete = 0
					WHERE SR.GoodsReceivedNoteId = GRN.Id AND SRD.GoodsReceivedNoteDetailId = GRND.Id
					AND SR.LocationId = @rStoreLocationId AND SR.OrgGroupId = @rOrgGroupId AND SR.IsObsolete = 0)
					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.LocationId = @rStoreLocationId AND GRN.OrgGroupId = @rOrgGroupId AND GRN.IsObsolete = 0
				   INNER JOIN sPurchase.tQualityCheck QC ON QC.GoodsReceivedNoteId = GRN.Id
						  AND QC.LocationId = @rStoreLocationId AND QC.OrgGroupId = @rOrgGroupId AND QC.IsObsolete = 0
				   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
					      AND SIM.StoreLocationId = @rStoreLocationId AND SIM.OrgGroupId = @rOrgGroupId AND SIM.IsObsolete = 0
				   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
				   AND GRN.LocationId = @rStoreLocationId AND GRN.OrgGroupId = @rOrgGroupId AND GRN.IsObsolete = 0
		END
	END TRY

	BEGIN CATCH
    IF @@TRANCOUNT > 0
        ROLLBACK TRANSACTION

    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 [sPurchase].[pHelperPopUpGet]    Script Date: 01-02-2024 12:00:42 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[sPurchase].[pHelperPopUpGet]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [sPurchase].[pHelperPopUpGet] AS'
END
GO


ALTER PROCEDURE [sPurchase].[pHelperPopUpGet]
	  @rScreenId SMALLINT
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
		SELECT ISNULL(HelpDescription,'')
		 FROM sSecurity.tScreenHelp
		 WHERE ScreenId = @rScreenId
	END TRY

	BEGIN CATCH
    IF @@TRANCOUNT > 0
        ROLLBACK TRANSACTION

    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 [sPurchase].[pInvoiceGenerateAdd]    Script Date: 01-02-2024 12:00:42 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[sPurchase].[pInvoiceGenerateAdd]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [sPurchase].[pInvoiceGenerateAdd] AS'
END
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
	    DECLARE @rStoreLocationId BIGINT
        SELECT @rStoreLocationId = ISNULL(ItemValue,0)
	    FROM sConfig.tConfigurationSetup
	    WHERE ConfigurationId  = 542 AND SourceId = @rUserId

		IF(@rId > 0)
		BEGIN
		    IF NOT EXISTS(SELECT Id FROM sPurchase.tInvoiceGenerate WHERE Id = @rId AND CreatedUserId = @rUserId
			AND LocationId = @rStoreLocationId AND OrgGroupId = @rOrgGroupId AND IsObsolete = 0)
            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 LocationId = @rStoreLocationId AND OrgGroupId = @rOrgGroupId AND IsObsolete = 0

				DELETE FROM sPurchase.tInvoiceGenerateDetail
				WHERE Id NOT IN(SELECT Id FROM @rDetailList)
				AND InvoiceGenerateId = @rId AND OrgGroupId = @rOrgGroupId

				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 AND IG.OrgGroupId = @rOrgGroupId

				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 AND IG.OrgGroupId = @rOrgGroupId
				WHERE IG.InvoiceGenerateId = @rId AND IG.OrgGroupId = @rOrgGroupId)
				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 AND IG.OrgGroupId = @rOrgGroupId
				WHERE IG.InvoiceGenerateId = @rId AND IG.OrgGroupId = @rOrgGroupId))
				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,
				@rStoreLocationId,
				@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 TRANSACTION
	END TRY

	BEGIN CATCH
    IF @@TRANCOUNT > 0
        ROLLBACK TRANSACTION


    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 [sPurchase].[pInvoiceGenerateDelete]    Script Date: 01-02-2024 12:00:42 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[sPurchase].[pInvoiceGenerateDelete]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [sPurchase].[pInvoiceGenerateDelete] AS'
END
GO




ALTER PROCEDURE [sPurchase].[pInvoiceGenerateDelete]
		@rId BIGINT,
		@rStatusId SMALLINT
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
	BEGIN TRANSACTION
		IF(@rId > 0)
		BEGIN
			UPDATE sPurchase.tInvoiceGenerate
			SET
				StatusId = @rStatusId,
				IsObsolete = 1,
				DeletedDateTime = GETUTCDATE()
			WHERE Id = @rId AND IsObsolete = 0

			IF EXISTS(SELECT Id FROM sPurchase.tInvoiceGenerateDetail WHERE InvoiceGenerateId = @rId)
			BEGIN
				DELETE FROM sPurchase.tInvoiceGenerateDetail
				WHERE InvoiceGenerateId = @rId
			END
			SELECT 1
	    END
	COMMIT TRANSACTION
	END TRY

	BEGIN CATCH
    IF @@TRANCOUNT > 0
        ROLLBACK TRANSACTION


    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 [sPurchase].[pInvoiceGenerateGet]    Script Date: 01-02-2024 12:00:42 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[sPurchase].[pInvoiceGenerateGet]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [sPurchase].[pInvoiceGenerateGet] AS'
END
GO


ALTER PROCEDURE [sPurchase].[pInvoiceGenerateGet]
	  @rId INT,
	  @rUserId BIGINT,
	  @rOrgGroupId INT
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
	    DECLARE @rStoreLocationId BIGINT
        SELECT @rStoreLocationId = ISNULL(ItemValue,0)
	    FROM sConfig.tConfigurationSetup
	    WHERE ConfigurationId  = 542 AND SourceId = @rUserId

		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 AND GRN.LocationId = @rStoreLocationId AND GRN.OrgGroupId = @rOrgGroupId AND GRN.IsObsolete = 0
		LEFT JOIN sProcurement.tVendorMaster  VM ON IG.VendorId = VM.ID AND VM.LocationId = @rStoreLocationId AND VM.OrgGroupId = @rOrgGroupId AND VM.IsObsolete = 0
		LEFT JOIN [sWf].[tWfStatusMaster] SM ON SM.Id = IG.StatusId
		WHERE  IG.Id=@rId AND IG.IsObsolete = 0
		       AND IG.LocationId = @rStoreLocationId
			   AND IG.OrgGroupId = @rOrgGroupId

		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.LocationId = @rStoreLocationId AND IG.OrgGroupId = @rOrgGroupId AND IG.IsObsolete = 0
			   INNER JOIN	sIp.tStockItemMaster SIM	ON SIM.Id = IGD.StockItemId AND SIM.StoreLocationId = @rStoreLocationId AND SIM.OrgGroupId = @rOrgGroupId AND SIM.IsObsolete = 0
			   LEFT JOIN [sIp].[tStockItemCategoryMaster] SCM ON SCM.Id = SIM.StockItemCategoryId
			   INNER JOIN  sFinanceCommon.tStockUomMaster SUMa ON SUMa.Id = SIM.IssueStockUomId
		WHERE  IGD.InvoiceGenerateId=@rId AND IG.IsObsolete = 0
		       AND IG.LocationId = @rStoreLocationId
			   AND IG.OrgGroupId = @rOrgGroupId
	END TRY

	BEGIN CATCH
    IF @@TRANCOUNT > 0
        ROLLBACK TRANSACTION

    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 [sPurchase].[pInvoiceGenerateSearchGet]    Script Date: 01-02-2024 12:00:42 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[sPurchase].[pInvoiceGenerateSearchGet]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [sPurchase].[pInvoiceGenerateSearchGet] AS'
END
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,
	@rUserId BIGINT

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	    DECLARE @rStoreLocationId BIGINT
        SELECT @rStoreLocationId = ISNULL(ItemValue,0)
	    FROM sConfig.tConfigurationSetup
	    WHERE ConfigurationId  = 542 AND SourceId = @rUserId

		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.tInvoiceGenerate IG (NOLOCK)

		WHERE
				((IG.INVNumber LIKE @rNumber+'%') OR (ISNULL(@rNumber,'') = ''))
   				AND ((IG.RequestedBy LIKE @rName+'%') OR (ISNULL(@rName,'') = ''))
   				AND ((IG.LocationId = @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 ((IG.LocationId = @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 TRANSACTION

    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 [sPurchase].[pMasterBatchGet]    Script Date: 01-02-2024 12:00:42 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[sPurchase].[pMasterBatchGet]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [sPurchase].[pMasterBatchGet] AS'
END
GO


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

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

	BEGIN CATCH
    IF @@TRANCOUNT > 0
        ROLLBACK TRANSACTION

    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 [sPurchase].[pMasterOrganizationGet]    Script Date: 01-02-2024 12:00:42 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[sPurchase].[pMasterOrganizationGet]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [sPurchase].[pMasterOrganizationGet] AS'
END
GO


ALTER PROCEDURE [sPurchase].[pMasterOrganizationGet]
	  @rOrgGroupId INT,
	  @rUserId BIGINT
AS
SET NOCOUNT ON

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

	BEGIN CATCH
    IF @@TRANCOUNT > 0
        ROLLBACK TRANSACTION

    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 [sPurchase].[pMenuGet_Purchase]    Script Date: 01-02-2024 12:00:42 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[sPurchase].[pMenuGet_Purchase]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [sPurchase].[pMenuGet_Purchase] AS'
END
GO
--exec [sPurchase].[pMenuGet_Purchase] 9911000000270
ALTER PROCEDURE [sPurchase].[pMenuGet_Purchase]
 @rUserId BIGINT,
 @rMenuId INT = 0,
 @rResourceTypeId INT= 0
 --,
 --@rIsCoreMenu bit = 0

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
 BEGIN TRY
 DECLARE @rIsCoreMenu INT=1
 IF(@rIsCoreMenu=0)
 BEGIN
 IF EXISTS(SELECT 1 FROM sSecurity.tPermissionUser WHERE UserId = @rUserId)
  BEGIN
   SELECT
    MenuID,
    ModuleId,
    ParentMenuID,
    MenuTitle,
    ScreenTitle,
    PageURL,
    ScreenId,
    Permission,
    OrderNumber,
    TaskId,
    PageURL  AS PagePath,
    IconPath

   FROM
     (SELECT Menu.Id AS MenuID,
    ISNULL(Menu.ParentMenuID, 0) AS ParentMenuID,
    Menu.Title AS MenuTitle,
    ISNULL(Screen.Title, '') AS ScreenTitle,
    ISNULL(Screen.Page, '') AS PageURL,
    ISNULL(Screen.ScreenGroupId,0) AS ScreenGroupId,
    ISNULL(Menu.ScreenId, 0) AS ScreenId,
    ISNULL(PermissionValue, 0) AS Permission,
    ISNULL(OrderNumber, 0) AS OrderNumber,
    ISNULL(Screen.TaskId,0) AS TaskId,
    ISNULL(Screen.IconPath,'') As IconPath,
    ISNULL(T.ResourceTypeId,0) AS ResourceTypeId,
    ISNULL(T.ModuleId,0) AS ModuleId


   FROM sSecurity.tMenu Menu
   LEFT OUTER JOIN sSecurity.tScreen Screen
    ON Menu.ScreenId = Screen.Id
   LEFT OUTER JOIN (
       SELECT
        TaskId,
        SUM(Permission & 2) PermissionValue
       FROM
        sSecurity.tPermissionUser P
        INNER JOIN sSecurity.tTask T ON T.Id = P.TaskId
        --INNER JOIN sSecuirty.tOrganizationTask OT ON OT.TaskId = T.Id AND OT.OrgGroupId = P.OrgGroupId
        INNER JOIN sSecurity.tModulePermission MP ON MP.ModuleId = T.ModuleId AND MP.OrgGroupId = P.OrgGroupId
       WHERE
        T.IsObsolete = 0 AND P.UserId = @rUserId
       GROUP BY
        TaskId) TBL2
       ON
        Screen.TaskId = TBL2.TaskId
         LEFT OUTER JOIN sSecurity.tTask  T ON T.Id =  Screen.TaskId AND ResourceTypeId = @rResourceTypeId

       WHERE
       (Menu.IsObsolete = 0)  --For ScreenGroupId Master Page
       AND ISNULL(Screen.IsObsolete, 0) = 0)
       MenuTable
       --INNER JOIN sSecurity.tTask  T ON T.Id =  MenuTable.TaskId
   WHERE
    MenuTable.ScreenId = 0 OR MenuTable.Permission >= 2
    AND
    ((MenuTable.ResourceTypeId = @rResourceTypeId) OR (@rResourceTypeId = 0))
    AND ((MenuTable.MenuID = @rMenuID)OR(@rMenuID = 0))

   ORDER BY
    ParentMenuID
  END
 ELSE
  BEGIN
   SELECT
    MenuID,
    ModuleId,
    ParentMenuID,
    MenuTitle,
    ScreenTitle,
    PageURL,
    ScreenId,
    Permission,
    OrderNumber,
    TaskId,
     PageURL  AS PagePath,
     IconPath

   FROM
     (SELECT Menu.Id AS MenuID,
    ISNULL(Menu.ParentMenuID, 0) AS ParentMenuID,
    Menu.Title AS MenuTitle,
    ISNULL(Screen.Title, '') AS ScreenTitle,
    ISNULL(Screen.Page, '') AS PageURL,
    ISNULL(Screen.ScreenGroupId,0) AS ScreenGroupId,
    ISNULL(Menu.ScreenId, 0) AS ScreenId,
    ISNULL(PermissionValue, 0) AS Permission,
    ISNULL(OrderNumber, 0) AS OrderNumber,
    ISNULL(Screen.TaskId,0) AS TaskId,
    ISNULL(Screen.IconPath,'') As IconPath,
    ISNULL(T.ResourceTypeId,0) AS ResourceTypeId,
    ISNULL(T.ModuleId,0) AS ModuleId


   FROM sSecurity.tMenu Menu
   LEFT OUTER JOIN sSecurity.tScreen Screen
    ON Menu.ScreenId = Screen.Id
   LEFT OUTER JOIN (
       SELECT
        TaskId,
        SUM(Permission & 2) PermissionValue
       FROM
        sSecurity.tPermission P
        INNER JOIN sSecurity.tTask T ON T.Id = P.TaskId
        --INNER JOIN sSecuirty.tOrganizationTask OT ON OT.TaskId = T.Id AND OT.OrgGroupId = P.OrgGroupId
        INNER JOIN sSecurity.tModulePermission MP ON MP.ModuleId = T.ModuleId AND MP.OrgGroupId = P.OrgGroupId
        INNER JOIN
        (
        SELECT RoleId FROM sSecurity.tUserRole UR WHERE  UserId = @rUserId AND IsObsolete = 0
        ) B ON B.RoleId = P.RoleId
       WHERE
        T.IsObsolete = 0
       GROUP BY
        TaskId) TBL2
       ON
        Screen.TaskId = TBL2.TaskId
         LEFT OUTER JOIN sSecurity.tTask  T ON T.Id =  Screen.TaskId AND ResourceTypeId = @rResourceTypeId

       WHERE
       (Menu.IsObsolete = 0)  --For ScreenGroupId Master Page
       AND ISNULL(Screen.IsObsolete, 0) = 0)
       MenuTable
       --INNER JOIN sSecurity.tTask  T ON T.Id =  MenuTable.TaskId
   WHERE
    MenuTable.ScreenId = 0 OR MenuTable.Permission >= 2
    AND
    ((MenuTable.ResourceTypeId = @rResourceTypeId) OR (@rResourceTypeId = 0))
    AND ((MenuTable.MenuID = @rMenuID)OR(@rMenuID = 0))

   ORDER BY
    ParentMenuID
  END
 END
 ELSE
 BEGIN
 SELECT
   MenuID,
   ModuleId,
   ParentMenuID,
   MenuTitle,
   ScreenTitle,
   PageURL,
   ScreenId,
   Permission,
   OrderNumber,
   TaskId,
   PageURL  AS PagePath,
   MenuIsObsolete,
   Icon
  FROM
  (

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

  UNION


  SELECT

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

  GROUP BY P.TaskId
  ) TBL2 ON Screen1.TaskId = TBL2.TaskId
  WHERE (Menu.IsObsolete = 0) AND ISNULL(Screen1.IsObsolete, 0) = 0
  --AND (Menu.ParentMenuID  in (24,2711)
  --OR Menu.Id  in (24,2711))
  AND TBL2.PermissionValue > 0
  AND Screen1.Id IN (31296,31297,31298,31299,31300,31301,31310,31311,31312,31317)
  ) MenuTable
  WHERE
  --(MenuTable.ScreenId = 0 OR MenuTable.Permission >= 2)
  --AND
  ((MenuTable.ResourceTypeId = @rResourceTypeId) OR (@rResourceTypeId = 0))
  AND ((MenuTable.MenuID = @rMenuID)OR(@rMenuID = 0))
  AND MenuIsObsolete = 0
  AND MenuTable.MenuId IN (19184028)
  AND ModuleId IN (96)
  ORDER BY MenuTable.OrderIndex, ParentMenuID
 END
 END TRY
 BEGIN CATCH
   ROLLBACK TRANSACTION

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

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

ALTER PROCEDURE [sPurchase].[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 [sPurchase].[pPOPurchaseRequestDetailGet]    Script Date: 01-02-2024 12:00:42 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[sPurchase].[pPOPurchaseRequestDetailGet]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [sPurchase].[pPOPurchaseRequestDetailGet] AS'
END
GO

--exec [sPurchase].[pPOPurchaseRequestDetailGet] 991100002
ALTER PROCEDURE [sPurchase].[pPOPurchaseRequestDetailGet]
	  @rId INT,
	  @rUserId BIGINT,
	  @rOrgGroupId INT
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
	BEGIN TRANSACTION
	    DECLARE @rStoreLocationId BIGINT
        SELECT @rStoreLocationId = ISNULL(ItemValue,0)
	    FROM sConfig.tConfigurationSetup
	    WHERE ConfigurationId  = 542 AND SourceId = @rUserId

		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.LocationId = @rStoreLocationId AND PR.OrgGroupId = @rOrgGroupId AND PR.IsObsolete = 0 AND PR.StatusId = 3
			   INNER JOIN	sIp.tStockItemMaster SIM	ON SIM.Id = PRD.StockItemId AND SIM.StoreLocationId = @rStoreLocationId AND SIM.OrgGroupId = @rOrgGroupId AND SIM.IsObsolete = 0
			   LEFT JOIN [sIp].[tStockItemCategoryMaster] SCM ON SCM.Id = SIM.StockItemCategoryId
			   INNER JOIN  sFinanceCommon.tStockUomMaster SUMa ON SUMa.Id = SIM.IssueStockUomId
		WHERE  PRD.PurchaseRequestId=@rId AND PR.IsObsolete = 0
		       AND PR.LocationId = @rStoreLocationId
			   AND PR.OrgGroupId = @rOrgGroupId
	COMMIT TRANSACTION
	END TRY

	BEGIN CATCH
    IF @@TRANCOUNT > 0
        ROLLBACK TRANSACTION

    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 [sPurchase].[pPurchaseOrderAdd]    Script Date: 01-02-2024 12:00:42 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[sPurchase].[pPurchaseOrderAdd]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [sPurchase].[pPurchaseOrderAdd] AS'
END
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
	    DECLARE @rStoreLocationId BIGINT
        SELECT @rStoreLocationId = ISNULL(ItemValue,0)
	    FROM sConfig.tConfigurationSetup
	    WHERE ConfigurationId  = 542 AND SourceId = @rUserId

		IF(@rId > 0)
		BEGIN
		    IF NOT EXISTS(SELECT Id FROM sPurchase.tPurchaseOrder WHERE Id = @rId AND CreatedUserId = @rUserId
			AND LocationId = @rStoreLocationId AND OrgGroupId = @rOrgGroupId AND IsObsolete = 0)
			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 LocationId = @rStoreLocationId AND OrgGroupId = @rOrgGroupId AND IsObsolete = 0

				DELETE FROM sPurchase.tPurchaseOrderDetail
				WHERE Id NOT IN(SELECT Id FROM @rDetailList)
				AND PurchaseOrderId = @rId AND OrgGroupId = @rOrgGroupId

				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 PO.PurchaseOrderId = @rId AND PO.OrgGroupId = @rOrgGroupId

				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 AND PO.OrgGroupId = @rOrgGroupId)
				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 AND PO.OrgGroupId = @rOrgGroupId
				WHERE PO.PurchaseOrderId = @rId AND PO.OrgGroupId = @rOrgGroupId))
				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 AND PO.LocationId = @rStoreLocationId AND PO.OrgGroupId = @rOrgGroupId AND PO.IsObsolete = 0)
                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,
						@rStoreLocationId,
						@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 TRANSACTION
	END TRY

	BEGIN CATCH
    IF @@TRANCOUNT > 0
        ROLLBACK TRANSACTION


    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 [sPurchase].[pPurchaseOrderApprovedGet]    Script Date: 01-02-2024 12:00:42 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[sPurchase].[pPurchaseOrderApprovedGet]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [sPurchase].[pPurchaseOrderApprovedGet] AS'
END
GO

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

BEGIN
	BEGIN TRY
		DECLARE @rStoreLocationId BIGINT
        SELECT @rStoreLocationId = ISNULL(ItemValue,0)
	    FROM sConfig.tConfigurationSetup
	    WHERE ConfigurationId  = 542 AND SourceId = @rUserId

		IF EXISTS(SELECT PO.Id
		FROM   [sPurchase].[tPurchaseOrder] PO(NOLOCK)
		INNER JOIN [sPurchase].[tGoodsReceivedNote] GRN ON GRN.PurchaseOrderId = PO.Id AND GRN.LocationId = @rStoreLocationId AND GRN.OrgGroupId = @rOrgGroupId AND GRN.IsObsolete = 0 AND GRN.StatusId IN (1,2)
		WHERE PO.Id = @rId AND PO.LocationId = @rStoreLocationId AND PO.OrgGroupId = @rOrgGroupId AND PO.IsObsolete = 0)
		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 AND PR.LocationId = @rStoreLocationId AND PR.OrgGroupId = @rOrgGroupId AND PR.IsObsolete = 0
				   LEFT JOIN sProcurement.tVendorMaster  VM ON PO.VendorId = VM.ID AND VM.LocationId = @rStoreLocationId AND VM.OrgGroupId = @rOrgGroupId AND VM.IsObsolete = 0
				   LEFT JOIN [sWf].[tWfStatusMaster] SM ON SM.Id = PO.StatusId
			WHERE  PO.Id = @rId
			       AND PO.IsObsolete = 0
				   AND PO.StatusId = 3
			       AND PO.LocationId = @rStoreLocationId
				   AND PO.OrgGroupId = @rOrgGroupId

			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.LocationId = @rStoreLocationId AND GRN.OrgGroupId = @rOrgGroupId AND GRN.IsObsolete = 0 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.LocationId = @rStoreLocationId AND GRN.OrgGroupId = @rOrgGroupId AND GRN.IsObsolete = 0 AND GRN.StatusID <> 4) AS PreviousGRNQty,
				   (SELECT QRD.TargetPrice FROM [sPurchase].[tQuotationRequestDetail] QRD
					INNER JOIN [sPurchase].[tQuotationRequest] QR ON QR.Id = QRD.QuotationRequestId AND QR.LocationId = @rStoreLocationId AND QR.OrgGroupId = @rOrgGroupId AND QR.IsObsolete = 0
					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 AND PO.LocationId = @rStoreLocationId AND PO.OrgGroupId = @rOrgGroupId AND PO.IsObsolete = 0
				   INNER JOIN	sIp.tStockItemMaster SIM	ON SIM.Id = POD.StockItemId AND SIM.StoreLocationId = @rStoreLocationId AND SIM.OrgGroupId = @rOrgGroupId AND SIM.IsObsolete = 0
				   INNER JOIN  sFinanceCommon.tStockUomMaster SUMa ON SUMa.Id = SIM.IssueStockUomId
				   LEFT JOIN [sIp].[tStockItemCategoryMaster] SCM ON SCM.Id = SIM.StockItemCategoryId
			WHERE  POD.PurchaseOrderId = @rId AND PO.IsObsolete = 0
			       AND PO.LocationId = @rStoreLocationId
				   AND PO.OrgGroupId = @rOrgGroupId
		END
	END TRY

	BEGIN CATCH
    IF @@TRANCOUNT > 0
        ROLLBACK TRANSACTION

    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 [sPurchase].[pPurchaseOrderApprovedSearchGet]    Script Date: 01-02-2024 12:00:42 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[sPurchase].[pPurchaseOrderApprovedSearchGet]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [sPurchase].[pPurchaseOrderApprovedSearchGet] AS'
END
GO


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

	@rNumber NVARCHAR(30) = '',
	@rName NVARCHAR = '',
	@rStartDate DATETIME = NULL,
	@rEndDate DATETIME = NULL,
	@rOrgGroupId INT,
	@rPageNo INT,
	@rPageSize INT,
	@rStatusId SMALLINT = 0,
	@rUserId BIGINT

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	    DECLARE @rStoreLocationId BIGINT
        SELECT @rStoreLocationId = ISNULL(ItemValue,0)
	    FROM sConfig.tConfigurationSetup
	    WHERE ConfigurationId  = 542 AND SourceId = @rUserId

		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 (ISNULL(@rNumber,'') = ''))
   				AND ((PO.RequestedBy LIKE @rName+'%') OR (ISNULL(@rName,'') = ''))
   				AND ((PO.LocationId = @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 AND GRN.LocationId = @rStoreLocationId AND GRN.OrgGroupId = @rOrgGroupId AND GRN.IsObsolete = 0
				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 PO.LocationId = @rStoreLocationId AND PO.OrgGroupId = @rOrgGroupId 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.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 ((PO.LocationId = @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 AND GRN.LocationId = @rStoreLocationId AND GRN.OrgGroupId = @rOrgGroupId AND GRN.IsObsolete = 0
				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 PO.LocationId = @rStoreLocationId AND PO.OrgGroupId = @rOrgGroupId 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 TRANSACTION

    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 [sPurchase].[pPurchaseOrderDelete]    Script Date: 01-02-2024 12:00:42 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[sPurchase].[pPurchaseOrderDelete]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [sPurchase].[pPurchaseOrderDelete] AS'
END
GO


ALTER PROCEDURE [sPurchase].[pPurchaseOrderDelete]
		@rId BIGINT,
		@rStatusId SMALLINT
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
	BEGIN TRANSACTION
		IF(@rId > 0)
		BEGIN
			UPDATE sPurchase.tPurchaseOrder
			SET
				StatusId = @rStatusId,
				IsObsolete = 1,
				DeletedDateTime = GETUTCDATE()
			WHERE Id = @rId and IsObsolete = 0

			IF EXISTS(SELECT Id FROM sPurchase.tPurchaseOrderDetail WHERE PurchaseOrderId = @rId)
			BEGIN
				DELETE FROM sPurchase.tPurchaseOrderDetail
				WHERE PurchaseOrderId = @rId
			END
			SELECT 1
		END
	COMMIT TRANSACTION
	END TRY

	BEGIN CATCH
    IF @@TRANCOUNT > 0
        ROLLBACK TRANSACTION


    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 [sPurchase].[pPurchaseOrderGet]    Script Date: 01-02-2024 12:00:42 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[sPurchase].[pPurchaseOrderGet]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [sPurchase].[pPurchaseOrderGet] AS'
END
GO


ALTER PROCEDURE [sPurchase].[pPurchaseOrderGet]
	  @rId INT,
	  @rUserId BIGINT,
	  @rOrgGroupId INT
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
	    DECLARE @rStoreLocationId BIGINT
        SELECT @rStoreLocationId = ISNULL(ItemValue,0)
	    FROM sConfig.tConfigurationSetup
	    WHERE ConfigurationId  = 542 AND SourceId = @rUserId

		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 AND VM.LocationId = @rStoreLocationId AND VM.OrgGroupId = @rOrgGroupId AND VM.IsObsolete = 0
			   LEFT JOIN [sWf].[tWfStatusMaster] SM ON SM.Id = PO.StatusId
			   LEFT JOIN [sPurchase].[tPurchaseRequest] PR ON PR.Id = PO.PurchaseRequestId AND PR.LocationId = @rStoreLocationId AND PR.OrgGroupId = @rOrgGroupId AND PR.IsObsolete = 0
		WHERE  PO.Id = @rId AND PO.IsObsolete = 0
		       AND PO.LocationId = @rStoreLocationId
			   AND PO.OrgGroupId = @rOrgGroupId

		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.LocationId = @rStoreLocationId AND PO.OrgGroupId = @rOrgGroupId AND PO.IsObsolete = 0
			   INNER JOIN	sIp.tStockItemMaster SIM	ON SIM.Id = POD.StockItemId  AND SIM.StoreLocationId = @rStoreLocationId AND SIM.OrgGroupId = @rOrgGroupId AND SIM.IsObsolete = 0
			   LEFT JOIN [sIp].[tStockItemCategoryMaster] SCM ON SCM.Id = SIM.StockItemCategoryId
			   INNER JOIN  sFinanceCommon.tStockUomMaster SUMa ON SUMa.Id = SIM.IssueStockUomId
		WHERE  POD.PurchaseOrderId = @rId AND PO.IsObsolete = 0
		       AND PO.LocationId = @rStoreLocationId
			   AND PO.OrgGroupId = @rOrgGroupId

	END TRY

	BEGIN CATCH
    IF @@TRANCOUNT > 0
        ROLLBACK TRANSACTION

    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 [sPurchase].[pPurchaseOrderSearchGet]    Script Date: 01-02-2024 12:00:42 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[sPurchase].[pPurchaseOrderSearchGet]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [sPurchase].[pPurchaseOrderSearchGet] AS'
END
GO



ALTER PROCEDURE [sPurchase].[pPurchaseOrderSearchGet]

	@rNumber NVARCHAR(30) = '',
	@rName NVARCHAR = '',
	@rStartDate DATETIME = NULL,
	@rEndDate DATETIME = NULL,
	@rOrgGroupId INT,
	@rPageNo INT,
	@rPageSize INT,
	@rStatusId SMALLINT = NULL,
	@rUserId BIGINT

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	    DECLARE @rStoreLocationId BIGINT
        SELECT @rStoreLocationId = ISNULL(ItemValue,0)
	    FROM sConfig.tConfigurationSetup
	    WHERE ConfigurationId  = 542 AND SourceId = @rUserId

		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 ((PO.LocationId = @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 ((PO.LocationId = @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 TRANSACTION

    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 [sPurchase].[pPurchaseRequestAdd]    Script Date: 01-02-2024 12:00:42 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[sPurchase].[pPurchaseRequestAdd]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [sPurchase].[pPurchaseRequestAdd] AS'
END
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
			DECLARE @rStoreLocationId BIGINT
            SELECT @rStoreLocationId = ISNULL(ItemValue,0)
	        FROM sConfig.tConfigurationSetup
	        WHERE ConfigurationId  = 542 AND SourceId = @rUserId
		IF(@rId > 0)
		BEGIN

		    IF NOT EXISTS(SELECT Id FROM sPurchase.tPurchaseRequest WHERE Id = @rId AND CreatedUserId = @rUserId AND LocationId = @rStoreLocationId AND OrgGroupId = @rOrgGroupId AND IsObsolete = 0)
			BEGIN
				SELECT -101
			END
			ELSE
			  BEGIN
				UPDATE sPurchase.tPurchaseRequest
				SET
					StatusId = @rStatusId,
					UpdatedUserId = @rUserId,
					UpdatedDateTime = GETUTCDATE()
				WHERE Id = @rId AND IsObsolete = 0 AND LocationId = @rStoreLocationId AND OrgGroupId = @rOrgGroupId 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 AND PR.OrgGroupId = @rOrgGroupId

				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 AND PR.OrgGroupId = @rOrgGroupId)

				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,
						@rStoreLocationId,
						@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 TRANSACTION
	END TRY

	BEGIN CATCH
    IF @@TRANCOUNT > 0
        ROLLBACK TRANSACTION


    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 [sPurchase].[pPurchaseRequestApprovedGet]    Script Date: 01-02-2024 12:00:42 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[sPurchase].[pPurchaseRequestApprovedGet]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [sPurchase].[pPurchaseRequestApprovedGet] AS'
END
GO

--exec [sPurchase].[pPurchaseRequestApprovedGet] 991100002
ALTER PROCEDURE [sPurchase].[pPurchaseRequestApprovedGet]
	  @rId INT,
	  @rUserId BIGINT,
	  @rOrgGroupId INT
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
	    DECLARE @rStoreLocationId BIGINT
        SELECT @rStoreLocationId = ISNULL(ItemValue,0)
	    FROM sConfig.tConfigurationSetup
	    WHERE ConfigurationId  = 542 AND SourceId = @rUserId

		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 AND QR.LocationId = @rStoreLocationId AND QR.OrgGroupId = @rOrgGroupId AND QR.IsObsolete = 0
			   LEFT JOIN [sWf].[tWfStatusMaster] SM ON SM.Id = PR.StatusId
			   LEFT JOIN sProcurement.tVendorMaster  VM ON QR.VendorId = VM.ID AND VM.LocationId = @rStoreLocationId AND VM.OrgGroupId = @rOrgGroupId AND VM.IsObsolete = 0
		WHERE  PR.Id=@rId AND PR.IsObsolete = 0 AND PR.StatusId = 3
		       AND PR.LocationId = @rStoreLocationId
			   AND PR.OrgGroupId = @rOrgGroupId

		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.StatusId = 3 AND PR.LocationId = @rStoreLocationId AND PR.OrgGroupId = @rOrgGroupId AND PR.IsObsolete = 0
			   INNER JOIN	sIp.tStockItemMaster SIM	ON SIM.Id = PRD.StockItemId AND SIM.StoreLocationId = @rStoreLocationId AND SIM.OrgGroupId = @rOrgGroupId AND SIM.IsObsolete = 0
			   LEFT JOIN [sIp].[tStockItemCategoryMaster] SCM ON SCM.Id = SIM.StockItemCategoryId
			   INNER JOIN  sFinanceCommon.tStockUomMaster SUMa ON SUMa.Id = SIM.IssueStockUomId
		WHERE  PRD.PurchaseRequestId=@rId AND PR.IsObsolete = 0
		       AND PR.LocationId = @rStoreLocationId
			   AND PR.OrgGroupId = @rOrgGroupId
	END TRY

	BEGIN CATCH
    IF @@TRANCOUNT > 0
        ROLLBACK TRANSACTION

    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 [sPurchase].[pPurchaseRequestApprovedSearchGet]    Script Date: 01-02-2024 12:00:42 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[sPurchase].[pPurchaseRequestApprovedSearchGet]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [sPurchase].[pPurchaseRequestApprovedSearchGet] AS'
END
GO

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

	@rNumber NVARCHAR(30) = '',
	@rName NVARCHAR = '',
	@rStartDate DATETIME = NULL,
	@rEndDate DATETIME = NULL,
	@rOrgGroupId INT,
	@rPageNo INT,
	@rPageSize INT,
	@rStatusId SMALLINT = 0,
	@rUserId BIGINT

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	    DECLARE @rStoreLocationId BIGINT
        SELECT @rStoreLocationId = ISNULL(ItemValue,0)
	    FROM sConfig.tConfigurationSetup
	    WHERE ConfigurationId  = 542 AND SourceId = @rUserId

		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 ((PR.LocationId = @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

	    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.LocationId = @rStoreLocationId) OR (@rStoreLocationId = 0))
   				AND ((PR.OrgGroupId = @rOrgGroupId) OR (@rOrgGroupId=0))
				AND ((PR.StatusId = @rStatusId) OR (ISNULL(@rStatusId,0)=0))
				AND PR.IsObsolete = 0 AND PR.StatusId = 3
				AND ((CAST(PR.CreatedDateTime AS DATE) >= CAST(@rStartDate AS DATE)) OR (ISNULL(@rStartDate,'')=''))
				AND((CAST(PR.CreatedDateTime AS DATE) <= CAST(@rEndDate AS DATE)) OR (ISNULL(@rEndDate,'')='')))t WHERE t.RowNum BETWEEN
		        ((@rPageNo-1)*@rPageSize +1) AND (@rPageNo*@rpageSize)

        SELECT @TotalRecords AS TotalRecords
	 END TRY

	BEGIN CATCH
    IF @@TRANCOUNT > 0
        ROLLBACK TRANSACTION

    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 [sPurchase].[pPurchaseRequestDelete]    Script Date: 01-02-2024 12:00:42 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[sPurchase].[pPurchaseRequestDelete]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [sPurchase].[pPurchaseRequestDelete] AS'
END
GO



ALTER PROCEDURE [sPurchase].[pPurchaseRequestDelete]
		@rId BIGINT,
		@rStatusId SMALLINT
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
	BEGIN TRANSACTION
		IF(@rId > 0)
		BEGIN
			UPDATE sPurchase.tPurchaseRequest
			SET
				StatusId = @rStatusId,
				IsObsolete = 1,
				DeletedDateTime = GetUtcDate()
			WHERE Id = @rId AND IsObsolete = 0

			IF EXISTS(SELECT Id FROM sPurchase.tPurchaseRequestDetail WHERE PurchaseRequestId = @rId)
			BEGIN
				DELETE FROM sPurchase.tPurchaseRequestDetail
				WHERE PurchaseRequestId = @rId
			END
			SELECT 1
		END
	COMMIT TRANSACTION
	END TRY

	BEGIN CATCH
    IF @@TRANCOUNT > 0
        ROLLBACK TRANSACTION


    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 [sPurchase].[pPurchaseRequestGet]    Script Date: 01-02-2024 12:00:42 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[sPurchase].[pPurchaseRequestGet]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [sPurchase].[pPurchaseRequestGet] AS'
END
GO

--exec [sPurchase].[pPurchaseRequestGet] 991100003
ALTER PROCEDURE [sPurchase].[pPurchaseRequestGet]
	  @rUserId BIGINT,
	  @rId BIGINT,
	  @rOrgGroupId INT
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
	    DECLARE @rStoreLocationId BIGINT
        SELECT @rStoreLocationId = ISNULL(ItemValue,0)
	    FROM sConfig.tConfigurationSetup
	    WHERE ConfigurationId  = 542 AND SourceId = @rUserId

		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 AND VM.LocationId = @rStoreLocationId AND VM.OrgGroupId = @rOrgGroupId AND VM.IsObsolete = 0
				LEFT JOIN [sWf].[tWfStatusMaster] SM ON SM.Id = PR.StatusId
		WHERE   PR.Id=@rId AND PR.IsObsolete = 0
				AND PR.LocationId = @rStoreLocationId
				AND PR.OrgGroupId = @rOrgGroupId

		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.LocationId = @rStoreLocationId AND PR.OrgGroupId = @rOrgGroupId AND PR.IsObsolete = 0
			   INNER JOIN	sIp.tStockItemMaster SIM	ON SIM.Id = PRD.StockItemId AND SIM.StoreLocationId = @rStoreLocationId AND SIM.OrgGroupId = @rOrgGroupId AND SIM.IsObsolete = 0
			   LEFT JOIN [sIp].[tStockItemCategoryMaster] SCM ON SCM.Id = SIM.StockItemCategoryId
			   INNER JOIN  sFinanceCommon.tStockUomMaster SUMa ON SUMa.Id = SIM.IssueStockUomId
		WHERE  PRD.PurchaseRequestId=@rId AND PR.IsObsolete = 0
		       AND PR.LocationId = @rStoreLocationId
		       AND PR.OrgGroupId = @rOrgGroupId
	END TRY

	BEGIN CATCH
    IF @@TRANCOUNT > 0
        ROLLBACK TRANSACTION

    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 [sPurchase].[pPurchaseRequestPOApprovedSearchGet]    Script Date: 01-02-2024 12:00:42 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[sPurchase].[pPurchaseRequestPOApprovedSearchGet]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [sPurchase].[pPurchaseRequestPOApprovedSearchGet] AS'
END
GO

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

	@rNumber NVARCHAR(30) = '',
	@rName NVARCHAR = '',
	@rStartDate DATETIME = NULL,
	@rEndDate DATETIME = NULL,
	@rOrgGroupId INT,
	@rPageNo INT,
	@rPageSize INT,
	@rStatusId SMALLINT = 0,
	@rUserId BIGINT

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	    DECLARE @rStoreLocationId BIGINT
        SELECT @rStoreLocationId = ISNULL(ItemValue,0)
	    FROM sConfig.tConfigurationSetup
	    WHERE ConfigurationId  = 542 AND SourceId = @rUserId

		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(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 AND QR.LocationId = @rStoreLocationId AND QR.OrgGroupId = @rOrgGroupId AND QR.IsObsolete = 0
		LEFT JOIN sProcurement.tVendorMaster  VM ON QR.VendorId = VM.ID AND VM.LocationId = @rStoreLocationId AND VM.OrgGroupId = @rOrgGroupId AND VM.IsObsolete = 0

		WHERE
				((PR.Number LIKE @rNumber+'%') OR (ISNULL(@rNumber,'') = ''))
   				AND ((PR.RequestedBy LIKE @rName+'%') OR (ISNULL(@rName,'') = ''))
   				AND ((PR.LocationId = @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 AND QR.LocationId = @rStoreLocationId AND QR.OrgGroupId = @rOrgGroupId AND QR.IsObsolete = 0
			    LEFT JOIN sProcurement.tVendorMaster  VM ON QR.VendorId = VM.ID AND VM.LocationId = @rStoreLocationId AND VM.OrgGroupId = @rOrgGroupId AND VM.IsObsolete = 0

        WHERE
				((PR.Number LIKE @rNumber+'%') OR (ISNULL(@rNumber,'') = ''))
   				AND ((PR.RequestedBy LIKE @rName+'%') OR (ISNULL(@rName,'') = ''))
   				AND ((PR.LocationId = @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 TRANSACTION

    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 [sPurchase].[pPurchaseRequestSearchGet]    Script Date: 01-02-2024 12:00:42 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[sPurchase].[pPurchaseRequestSearchGet]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [sPurchase].[pPurchaseRequestSearchGet] AS'
END
GO

--exec [sPurchase].[pPurchaseRequestSearchGet] '',9911000000065,'',9911,'2024-01-07','2024-01-30',1,10,0
ALTER PROCEDURE [sPurchase].[pPurchaseRequestSearchGet]

	@rNumber NVARCHAR(30) = '',
	@rUserId BIGINT,
	@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 @rStoreLocationId BIGINT
        SELECT @rStoreLocationId = ISNULL(ItemValue,0)
	    FROM sConfig.tConfigurationSetup
	    WHERE ConfigurationId  = 542 AND SourceId = @rUserId

		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 ((PR.LocationId = @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 ((PR.LocationId = @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 TRANSACTION

    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 [sPurchase].[pPurchaseScreenGet]    Script Date: 01-02-2024 12:00:42 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[sPurchase].[pPurchaseScreenGet]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [sPurchase].[pPurchaseScreenGet] AS'
END
GO
--exec [sPurchase].[pPurchaseScreenGet]
ALTER PROCEDURE [sPurchase].[pPurchaseScreenGet]
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
		SELECT
			S.Id			AS ScreenId,
			S.Title		AS ScreenTitle,
			S.TaskId		AS TaskId,
			S.Page		As PageUrl,
			S.IsObsolete	AS ScreenIsObsolete,
			S.Title,
			S.Page,
			SG.Id AS ScreenGroupId,
			ISNULL(SG.Title,'') AS ScreenGroupName

		FROM
			sSecurity.tScreen S (NOLOCK)
		LEFT JOIN sSecurity.tScreenGroupMaster SG ON SG.Id=S.ScreenGroupId
		WHERE
			S.IsObsolete = 0 AND S.ScreenGroupID=254 AND S.Id IN (31296,31297,31298,31299,31300,31301,31310,31311,31312,31317)
		ORDER BY S.OrderIndex
	END TRY

	BEGIN CATCH
    IF @@TRANCOUNT > 0
        ROLLBACK TRANSACTION

    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 [sPurchase].[pPurchaseStatusGet]    Script Date: 01-02-2024 12:00:42 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[sPurchase].[pPurchaseStatusGet]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [sPurchase].[pPurchaseStatusGet] AS'
END
GO

ALTER PROCEDURE [sPurchase].[pPurchaseStatusGet]
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
		SELECT Id,
			   Title
		FROM   [sWf].[tWfStatusMaster] (NOLOCK)
		WHERE  IsObsolete = 0
	END TRY

	BEGIN CATCH
    IF @@TRANCOUNT > 0
        ROLLBACK TRANSACTION

    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 [sPurchase].[pPurchaseStoreLocationMasterGet]    Script Date: 01-02-2024 12:00:42 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[sPurchase].[pPurchaseStoreLocationMasterGet]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [sPurchase].[pPurchaseStoreLocationMasterGet] AS'
END
GO

--exec [sPurchase].[pPurchaseStoreLocationMasterGet] 9911
ALTER PROCEDURE [sPurchase].[pPurchaseStoreLocationMasterGet]
	@rOrgGroupId INT
	--,
	--@rIsWildCardSearch [bit] = 1

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
    BEGIN TRY
	--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.OrgGroupId = @rOrgGroupId)
		 AND SLM.IsObsolete = 0
		--((SLM.Id = @rId) OR (ISNULL(@rId,0) = 0))
	 --  AND ((SLM.Title LIKE @rTitle) OR (ISNULL(@rTitle, '') = ''))
	 --  AND ((SLM.Code LIKE @rCode) OR (ISNULL(@rCode, '') = ''))
	 END TRY
	 BEGIN CATCH
		ROLLBACK TRANSACTION

		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

SET ANSI_NULLS ON

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

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

BEGIN
	BEGIN TRY
			DECLARE @rStoreLocationId BIGINT
			SELECT @rStoreLocationId = ISNULL(ItemValue,0)
			FROM sConfig.tConfigurationSetup
			WHERE ConfigurationId  = 542 AND SourceId = @rUserId

		 --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
	   AND VM.LocationId = @rStoreLocationId
	END TRY

	BEGIN CATCH
    IF @@TRANCOUNT > 0
        ROLLBACK TRANSACTION

    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 [sPurchase].[pQualityCheckAdd]    Script Date: 01-02-2024 12:00:42 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[sPurchase].[pQualityCheckAdd]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [sPurchase].[pQualityCheckAdd] AS'
END
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
	    DECLARE @rStoreLocationId BIGINT
        SELECT @rStoreLocationId = ISNULL(ItemValue,0)
	    FROM sConfig.tConfigurationSetup
	    WHERE ConfigurationId  = 542 AND SourceId = @rUserId

		IF(@rId > 0)
		BEGIN
		   IF NOT EXISTS(SELECT Id FROM sPurchase.tQualityCheck WHERE Id = @rId AND CreatedUserId = @rUserId AND LocationId = @rStoreLocationId AND OrgGroupId = @rOrgGroupId AND IsObsolete = 0)
		   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  AND GRN.LocationId = @rStoreLocationId AND GRN.OrgGroupId = @rOrgGroupId AND GRN.IsObsolete = 0
			INNER JOIN [sPurchase].[tQualityCheck] QC ON GRN.Id = QC.GoodsReceivedNoteId  AND QC.LocationId = @rStoreLocationId AND QC.OrgGroupId = @rOrgGroupId AND QC.IsObsolete = 0
			WHERE QC.Id = @rId  AND QC.LocationId = @rStoreLocationId AND QC.OrgGroupId = @rOrgGroupId AND QC.IsObsolete = 0)
			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 LocationId = @rStoreLocationId AND OrgGroupId = @rOrgGroupId AND IsObsolete = 0

				DELETE FROM sPurchase.tQualityCheckDetail
				WHERE Id NOT IN(SELECT Id FROM @rDetailList)
				AND QualityCheckId = @rId AND OrgGroupId = @rOrgGroupId

				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 AND QC.OrgGroupId = @rOrgGroupId
				WHERE QC.QualityCheckId = @rId AND QC.OrgGroupId = @rOrgGroupId

				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 AND QC.OrgGroupId = @rOrgGroupId
				WHERE QC.QualityCheckId = @rId AND QC.OrgGroupId = @rOrgGroupId)

				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 AND QC.OrgGroupId = @rOrgGroupId
				WHERE QC.QualityCheckId = @rId AND QC.OrgGroupId = @rOrgGroupId))
				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
			AND GRN.LocationId = @rStoreLocationId AND GRN.OrgGroupId = @rOrgGroupId AND GRN.IsObsolete = 0
			INNER JOIN [sPurchase].[tQualityCheck] QC ON GRN.Id = QC.GoodsReceivedNoteId
			AND QC.LocationId = @rStoreLocationId AND QC.OrgGroupId = @rOrgGroupId AND QC.IsObsolete = 0
			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,
					@rStoreLocationId,
					@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'
 					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 = @rId
 					--FOR XML AUTO, ROOT('Table'), ELEMENTS
 					FOR XML PATH('StockInward'), ROOT('Table')
 				);

				SELECT @rId
				-- Print or use @XmlString as needed
				--PRINT CONVERT(NVARCHAR(MAX), @XmlString);
				DECLARE @str NVARCHAR(MAX) = CAST(@XmlString AS NVARCHAR(MAX))
				DECLARE @inwardDate DATETIME
				SET @inwardDate = GETUTCDATE()
				DECLARE @result INT
				EXEC sProcurement.pStockInwardAdd_New @rOrgGroupId,'',0,@rRequestedBy,@rStoreLocationId,'Inward By Quality Check',@rUserId,@str,@rStoreLocationId,@rOrgGroupId,0,@inwardDate,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


			END
			SELECT -101;
		END
	COMMIT TRANSACTION
	END TRY

	BEGIN CATCH
    IF @@TRANCOUNT > 0
        ROLLBACK TRANSACTION


    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 [sPurchase].[pQualityCheckDelete]    Script Date: 01-02-2024 12:00:42 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[sPurchase].[pQualityCheckDelete]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [sPurchase].[pQualityCheckDelete] AS'
END
GO



ALTER PROCEDURE [sPurchase].[pQualityCheckDelete]
		@rId BIGINT,
		@rStatusId SMALLINT
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
	BEGIN TRANSACTION
		IF(@rId > 0)
		BEGIN
			UPDATE sPurchase.tQualityCheck
			SET
				StatusId = @rStatusId,
				IsObsolete = 1,
				DeletedDateTime = GETUTCDATE()
			WHERE Id = @rId AND IsObsolete = 0

			IF EXISTS(SELECT Id FROM sPurchase.tQualityCheckDetail WHERE QualityCheckId = @rId)
			BEGIN
				DELETE FROM sPurchase.tQualityCheckDetail
				WHERE QualityCheckId = @rId
			END
			SELECT 1
		END
	COMMIT TRANSACTION
	END TRY

	BEGIN CATCH
    IF @@TRANCOUNT > 0
        ROLLBACK TRANSACTION


    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 [sPurchase].[pQualityCheckGet]    Script Date: 01-02-2024 12:00:42 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[sPurchase].[pQualityCheckGet]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [sPurchase].[pQualityCheckGet] AS'
END
GO

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

BEGIN
	BEGIN TRY
	    DECLARE @rStoreLocationId BIGINT
        SELECT @rStoreLocationId = ISNULL(ItemValue,0)
	    FROM sConfig.tConfigurationSetup
	    WHERE ConfigurationId  = 542 AND SourceId = @rUserId

		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
		AND GRN.LocationId = @rStoreLocationId AND GRN.OrgGroupId = @rOrgGroupId AND GRN.IsObsolete = 0
		LEFT JOIN [sWf].[tWfStatusMaster] SM ON SM.Id = QC.StatusId
		WHERE  QC.Id=@rId AND QC.IsObsolete = 0
		       AND QC.LocationId = @rStoreLocationId
			   AND QC.OrgGroupId = @rOrgGroupId

		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.LocationId = @rStoreLocationId AND QCC.OrgGroupId = @rOrgGroupId AND QCC.IsObsolete = 0  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.LocationId = @rStoreLocationId AND QC1.OrgGroupId = @rOrgGroupId AND QC1.IsObsolete = 0
						WHERE QC1.GoodsReceivedNoteId = QC.GoodsReceivedNoteID AND QCD1.StockItemId = QCD.StockItemId AND QC1.IsObsolete = 0
						AND QC1.LocationId = @rStoreLocationId AND QC1.OrgGroupId = @rOrgGroupId
						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
			   AND QC.LocationId = @rStoreLocationId AND QC.OrgGroupId = @rOrgGroupId
			   INNER JOIN	sIp.tStockItemMaster SIM	ON SIM.Id = QCD.StockItemId  AND SIM.IsObsolete = 0
			   AND SIM.StoreLocationId = @rStoreLocationId AND SIM.OrgGroupId = @rOrgGroupId
			   LEFT JOIN [sIp].[tStockItemCategoryMaster] SCM ON SCM.Id = SIM.StockItemCategoryId
			   INNER JOIN  sFinanceCommon.tStockUomMaster SUMa ON SUMa.Id = SIM.IssueStockUomId
		WHERE  QCD.QualityCheckId=@rId AND QC.IsObsolete = 0
		       AND QC.LocationId = @rStoreLocationId
			   AND QC.OrgGroupId = @rOrgGroupId

	END TRY

	BEGIN CATCH
    IF @@TRANCOUNT > 0
        ROLLBACK TRANSACTION

    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 [sPurchase].[pQualityCheckSearchGet]    Script Date: 01-02-2024 12:00:42 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[sPurchase].[pQualityCheckSearchGet]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [sPurchase].[pQualityCheckSearchGet] AS'
END
GO

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

	@rNumber NVARCHAR(30) = '',
	@rName NVARCHAR = '',
	@rStartDate DATETIME = NULL,
	@rEndDate DATETIME = NULL,
	@rOrgGroupId INT,
	@rPageNo INT,
	@rPageSize INT,
	@rStatusId SMALLINT = 0,
	@rUserId BIGINT

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	    DECLARE @rStoreLocationId BIGINT
        SELECT @rStoreLocationId = ISNULL(ItemValue,0)
	    FROM sConfig.tConfigurationSetup
	    WHERE ConfigurationId  = 542 AND SourceId = @rUserId

		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 ((QC.LocationId = @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 ((QC.LocationId = @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 TRANSACTION

    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 [sPurchase].[pQuotationApprovedVendorGet]    Script Date: 01-02-2024 12:00:42 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[sPurchase].[pQuotationApprovedVendorGet]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [sPurchase].[pQuotationApprovedVendorGet] AS'
END
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 TRANSACTION

    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 [sPurchase].[pQuotationRequestAdd]    Script Date: 01-02-2024 12:00:42 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[sPurchase].[pQuotationRequestAdd]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [sPurchase].[pQuotationRequestAdd] AS'
END
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
        DECLARE @rStoreLocationId BIGINT
        SELECT @rStoreLocationId = ISNULL(ItemValue,0)
	    FROM sConfig.tConfigurationSetup
	    WHERE ConfigurationId  = 542 AND SourceId = @rUserId

		IF(@rId > 0)
		BEGIN
		  IF NOT EXISTS(SELECT Id FROM sPurchase.tQuotationRequest WHERE Id = @rId AND CreatedUserId = @rUserId
				AND LocationId = @rStoreLocationId AND OrgGroupId = @rOrgGroupId AND IsObsolete = 0)
		    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 LocationId = @rStoreLocationId AND OrgGroupId = @rOrgGroupId AND IsObsolete = 0

				DELETE FROM sPurchase.tQuotationRequestDetail
				WHERE Id NOT IN(SELECT Id FROM @rDetailList)
				AND QuotationRequestId = @rId AND OrgGroupId = @rOrgGroupId

				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 QR.QuotationRequestId = @rId AND QR.OrgGroupId = @rOrgGroupId

				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 AND QR.OrgGroupId = @rOrgGroupId
				WHERE QR.QuotationRequestId = @rId AND QR.OrgGroupId = @rOrgGroupId)
				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 AND QR.OrgGroupId = @rOrgGroupId
				WHERE QR.QuotationRequestId = @rId AND QR.OrgGroupId = @rOrgGroupId))
				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 AND LocationId = @rStoreLocationId AND OrgGroupId = @rOrgGroupId AND IsObsolete = 0)
						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 ,
								@rStoreLocationId,
								@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 TRANSACTION
	END TRY

	BEGIN CATCH
    IF @@TRANCOUNT > 0
        ROLLBACK TRANSACTION


    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 [sPurchase].[pQuotationRequestDelete]    Script Date: 01-02-2024 12:00:42 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[sPurchase].[pQuotationRequestDelete]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [sPurchase].[pQuotationRequestDelete] AS'
END
GO



ALTER PROCEDURE [sPurchase].[pQuotationRequestDelete]
		@rId BIGINT,
		@rStatusId INT

AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
	BEGIN TRANSACTION
		IF(@rId > 0)
		BEGIN
			UPDATE sPurchase.tQuotationRequest
			SET
				StatusId = @rStatusId,
				IsObsolete = 1,
				DeletedDateTime = GETUTCDATE()
			WHERE Id = @rId AND IsObsolete = 0

			IF EXISTS(SELECT Id FROM sPurchase.tQuotationRequestDetail WHERE QuotationRequestId = @rId)
			BEGIN
				DELETE FROM sPurchase.tQuotationRequestDetail
				WHERE QuotationRequestId = @rId
			END
			SELECT 1
		END
	COMMIT TRANSACTION
	END TRY

	BEGIN CATCH
    IF @@TRANCOUNT > 0
        ROLLBACK TRANSACTION


    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 [sPurchase].[pQuotationRequestGet]    Script Date: 01-02-2024 12:00:42 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[sPurchase].[pQuotationRequestGet]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [sPurchase].[pQuotationRequestGet] AS'
END
GO


ALTER PROCEDURE [sPurchase].[pQuotationRequestGet]
	  @rId INT,
	  @rUserId BIGINT,
	  @rOrgGroupId INT
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
	    DECLARE @rStoreLocationId BIGINT
        SELECT @rStoreLocationId = ISNULL(ItemValue,0)
	    FROM sConfig.tConfigurationSetup
	    WHERE ConfigurationId  = 542 AND SourceId = @rUserId

		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 AND VM.LocationId = @rStoreLocationId AND VM.OrgGroupId = @rOrgGroupId AND VM.IsObsolete = 0
			   LEFT JOIN [sWf].[tWfStatusMaster] SM ON SM.Id = QR.StatusId
			   LEFT JOIN [sPurchase].[tPurchaseRequest] PR ON PR.Id = QR.PurchaseRequestId AND PR.LocationId = @rStoreLocationId AND PR.OrgGroupId = @rOrgGroupId AND PR.IsObsolete = 0

		WHERE  QR.Id=@rId AND QR.IsObsolete = 0
		       AND QR.LocationId = @rStoreLocationId
			   AND QR.OrgGroupId = @rOrgGroupId

		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.LocationId = @rStoreLocationId AND QR.OrgGroupId = @rOrgGroupId AND QR.IsObsolete = 0
			   INNER JOIN	sIp.tStockItemMaster SIM	ON SIM.Id = QRD.StockItemId AND SIM.StoreLocationId = @rStoreLocationId AND SIM.OrgGroupId = @rOrgGroupId AND SIM.IsObsolete = 0
			   LEFT JOIN [sIp].[tStockItemCategoryMaster] SCM ON SCM.Id = SIM.StockItemCategoryId
			   INNER JOIN  sFinanceCommon.tStockUomMaster SUMa ON SUMa.Id = SIM.IssueStockUomId
		WHERE  QRD.QuotationRequestId=@rId AND QR.IsObsolete = 0
		       AND QR.LocationId = @rStoreLocationId
			   AND QR.OrgGroupId = @rOrgGroupId

	END TRY

	BEGIN CATCH
    IF @@TRANCOUNT > 0
        ROLLBACK TRANSACTION

    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 [sPurchase].[pQuotationRequestSearchGet]    Script Date: 01-02-2024 12:00:42 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[sPurchase].[pQuotationRequestSearchGet]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [sPurchase].[pQuotationRequestSearchGet] AS'
END
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,
	@rUserId BIGINT

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	    DECLARE @rStoreLocationId BIGINT
        SELECT @rStoreLocationId = ISNULL(ItemValue,0)
	    FROM sConfig.tConfigurationSetup
	    WHERE ConfigurationId  = 542 AND SourceId = @rUserId

		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.tQuotationRequest QR (NOLOCK)

		WHERE
				((QR.Number LIKE @rNumber+'%') OR (ISNULL(@rNumber,'') = ''))
   				AND ((QR.Name LIKE @rName+'%') OR (ISNULL(@rName,'') = ''))
				AND ((QR.LocationId = @rStoreLocationId) OR (@rStoreLocationId = 0))
   				AND ((QR.OrgGroupId = @rOrgGroupId) OR (@rOrgGroupId=0))
				AND ((QR.StatusId = @rStatusId) OR (ISNULL(@rStatusId,0)=0))
				AND QR.IsObsolete = 0
				AND ((CAST(QR.CreatedDateTime AS DATE) >= CAST(@rStartDate AS DATE)) OR (ISNULL(@rStartDate,'')=''))
				AND((CAST(QR.CreatedDateTime AS DATE) <= CAST(@rEndDate AS DATE)) OR (ISNULL(@rEndDate,'')=''))


		SELECT t.* FROM (
			SELECT ROW_NUMBER() OVER (
			ORDER BY QR.Id DESC
			) AS 'RowNum',QR.Id,
				QR.Number,
				QR.Name AS RequestedBy,
				QR.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.LocationId = @rStoreLocationId) OR (@rStoreLocationId = 0))
   				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 TRANSACTION

    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 [sPurchase].[pQuotationVendorGet]    Script Date: 01-02-2024 12:00:42 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[sPurchase].[pQuotationVendorGet]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [sPurchase].[pQuotationVendorGet] AS'
END
GO


--exec [sPurchase].[pQuotationVendorGet] 991100010
ALTER PROCEDURE [sPurchase].[pQuotationVendorGet]

		 @rQuotationRequestId BIGINT,
	     @rUserId BIGINT,
	     @rOrgGroupId INT
		 --,
	 	-- @rTemplate nvarchar(max)

	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
        BEGIN TRY
        DECLARE @rStoreLocationId BIGINT
        SELECT @rStoreLocationId = ISNULL(ItemValue,0)
	    FROM sConfig.tConfigurationSetup
	    WHERE ConfigurationId  = 542 AND SourceId = @rUserId

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

	    SELECT  @rDescription = ISNULL(QR.Description,''),
				@rStartDate = ISNULL(QR.StartDate,''),
				@rEndDate = ISNULL(QR.EndDate,''),
				@rBidOpen = ISNULL(QR.BidOpen,''),
				@rBidClose = ISNULL(QR.BidClose,''),
				@rPersonContact = ISNULL(QR.PersonContact,''),
				@rEmail = ISNULL(QR.Email,''),
				@rRFQDate = ISNULL(QR.RFQDate,'')
		FROM   [sPurchase].[tQuotationRequest] QR(NOLOCK)
			   LEFT JOIN sProcurement.tVendorMaster  VM ON QR.VendorId = VM.ID AND VM.OrgGroupId = @rOrgGroupId AND VM.LocationId = @rStoreLocationId AND VM.IsObsolete = 0
			   LEFT JOIN [sWf].[tWfStatusMaster] SM ON SM.Id = QR.StatusId
			   LEFT JOIN [sPurchase].[tPurchaseRequest] PR ON PR.Id = QR.PurchaseRequestId AND PR.LocationId = @rStoreLocationId AND PR.OrgGroupId = @rOrgGroupId AND PR.IsObsolete = 0
		WHERE  QR.Id = @rQuotationRequestId AND QR.IsObsolete = 0
		       AND QR.LocationId = @rStoreLocationId
			   AND QR.OrgGroupId = @rOrgGroupId

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

	SELECT @HTMLTable = @HTMLTable+'<tr><td>'+CAST(SIM.Code AS NVARCHAR(100))+'</td><td>'
	+SIM.Title+'</td><td>'+SUMa.Code+'</td><td>'+CAST(QRD.RequestedQty AS NVARCHAR(100))+
	+'</td><td>'+CAST(QRD.TargetPrice AS NVARCHAR(100))+'</td><td>'+QRD.Remark+'</td></tr>'
	  FROM   [sPurchase].[tQuotationRequestDetail] QRD (NOLOCK)
		INNER JOIN	sPurchase.tQuotationRequest QR	ON QR.Id = QRD.QuotationRequestId AND QR.LocationId = @rStoreLocationId AND QR.OrgGroupId = @rOrgGroupId AND QR.IsObsolete = 0
		INNER JOIN	sIp.tStockItemMaster SIM ON SIM.Id = QRD.StockItemId AND SIM.StoreLocationId = @rStoreLocationId AND SIM.OrgGroupId = @rOrgGroupId AND SIM.IsObsolete = 0
		INNER JOIN  sFinanceCommon.tStockUomMaster SUMa ON SUMa.Id = SIM.IssueStockUomId
		WHERE  QR.Id = @rQuotationRequestId AND QR.IsObsolete = 0
		AND QR.LocationId = @rStoreLocationId
	    AND QR.OrgGroupId = @rOrgGroupId

    --PRINT @HTMLTable;
	DECLARE @txtMessage NVARCHAR(MAX)
    SELECT @txtMessage=REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(Template,
		'{Description}' , @rDescription),
		'{StartDate}' , @rStartDate),
		'{EndDate}' , @rEndDate),
		'{BidOpen}' , @rBidOpen),
		'{BidClose}' , @rBidClose),
		'{PersonContact}' , @rPersonContact),
		'{Email}' , @rEmail),
		'{RFQDate}' , @rRFQDate),
		'{QuatationDetails}' , @HTMLTable)FROM sPurchase.tPurchaseReportTemplate WHERE id = 1

		DECLARE @VendorId BIGINT
		SELECT @VendorId = QR.VendorId FROM sPurchase.tQuotationRequest QR WHERE QR.Id = @rQuotationRequestId AND QR.IsObsolete = 0 AND QR.LocationId = @rStoreLocationId
		AND QR.OrgGroupId = @rOrgGroupId

	SELECT
			--A.AcademicId,
			A.Code,
			A.Name,
			A.ParentContactNo AS MobileNo,
			A.ParentEmail AS EmailId,
			@txtMessage	AS MsgText,
			'' AS Subject,
			 2001 AS ReceiverSourceTypeId,
			 (SELECT Id FROM sSetup.tOrganizationMaster WHERE OrgGroupId=A.OrgGroupId AND Id = A.OrgGroupId) AS OrgId,
			 A.OrgGroupId AS OrgGroupId,
			 --A.AcademicId AS ReceiverSourceId,
			 A.Id AS SourceId,
			 2001 AS SourceTypeId,
			 --DM.Title AS MeetingType,
			 --CONVERT(varchar(11),ISNULL(OM.StartDate,'') ,103) AS StartDate,
			 --CONVERT(varchar(11),ISNULL(OM.EndDate,'') ,103) AS EndDate,
			 --EE.EmployeeName AS Teacher,
			 --OM.Title AS Title,
			 A.WhatsAppContactNo
	FROM
		 [sPurchase].[tQuotationRequestDetail] QRD (NOLOCK)
		INNER JOIN	sPurchase.tQuotationRequest QR	ON QR.Id = QRD.QuotationRequestId AND QR.LocationId = @rStoreLocationId AND QR.OrgGroupId = @rOrgGroupId AND QR.IsObsolete = 0
		INNER JOIN	sIp.tStockItemMaster SIM ON SIM.Id = QRD.StockItemId AND SIM.StoreLocationId = @rStoreLocationId AND SIM.OrgGroupId = @rOrgGroupId AND SIM.IsObsolete = 0
		INNER JOIN  sFinanceCommon.tStockUomMaster SUMa ON SUMa.Id = SIM.IssueStockUomId
		INNER JOIN (
			SELECT	VM.Id,
					VM.ContactPersonName AS Name,
					VM.Code,
					VM.PhoneNumberOffice AS ParentContactNo,
					VM.Email AS ParentEmail,
					VM.OrgGroupId,
					VM.PhoneNumberMobile WhatsAppContactNo
			FROM	sProcurement.tVendorMaster  VM
			LEFT JOIN   sProcurement.tVendorCategoryMaster VC
			ON  VM.VendorCategoryId = VC.Id
			WHERE VM.Id = @VendorId AND VM.LocationId = @rStoreLocationId AND VM.OrgGroupId = @rOrgGroupId AND VM.IsObsolete = 0
		) AS A ON A.Id = QR.VendorId
		WHERE  QR.Id = @rQuotationRequestId AND QR.IsObsolete = 0
		       AND QR.LocationId = @rStoreLocationId
			   AND QR.OrgGroupId = @rOrgGroupId
	   END TRY
	   BEGIN CATCH
		ROLLBACK TRANSACTION

		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 [sPurchase].[pSalesReturnAdd]    Script Date: 01-02-2024 12:00:42 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[sPurchase].[pSalesReturnAdd]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [sPurchase].[pSalesReturnAdd] AS'
END
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
	    DECLARE @rStoreLocationId BIGINT
        SELECT @rStoreLocationId = ISNULL(ItemValue,0)
	    FROM sConfig.tConfigurationSetup
	    WHERE ConfigurationId  = 542 AND SourceId = @rUserId

		IF(@rId > 0)
		BEGIN
		  IF NOT EXISTS(SELECT Id FROM sPurchase.tQuotationRequest WHERE Id = @rId AND CreatedUserId = @rUserId AND LocationId = @rStoreLocationId AND OrgGroupId = @rOrgGroupId AND IsObsolete = 0)
		    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 LocationId = @rStoreLocationId AND OrgGroupId = @rOrgGroupId AND IsObsolete = 0

				DELETE FROM sPurchase.tSalesReturnDetail
				WHERE Id NOT IN(SELECT Id FROM @rDetailList)
				AND SalesReturnId = @rId AND OrgGroupId = @rOrgGroupId

				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 AND SR.OrgGroupId = @rOrgGroupId
				WHERE SalesReturnId = @rId AND OrgGroupId = @rOrgGroupId

				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 AND SR.OrgGroupId = @rOrgGroupId
				WHERE SR.SalesReturnId = @rId AND SR.OrgGroupId = @rOrgGroupId)
				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 AND SR.OrgGroupId = @rOrgGroupId
				WHERE SR.SalesReturnId = @rId AND SR.OrgGroupId = @rOrgGroupId))
				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,
						@rStoreLocationId,
						@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 TRANSACTION
	END TRY

	BEGIN CATCH
    IF @@TRANCOUNT > 0
        ROLLBACK TRANSACTION


    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 [sPurchase].[pSalesReturnDelete]    Script Date: 01-02-2024 12:00:42 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[sPurchase].[pSalesReturnDelete]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [sPurchase].[pSalesReturnDelete] AS'
END
GO



ALTER PROCEDURE [sPurchase].[pSalesReturnDelete]
		@rId BIGINT,
		@rStatusId SMALLINT
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
	BEGIN TRANSACTION
		IF(@rId > 0)
		BEGIN
			UPDATE sPurchase.tSalesReturn
			SET
				StatusId = @rStatusId,
				IsObsolete = 1,
				DeletedDateTime = GETUTCDATE()
			WHERE Id = @rId AND IsObsolete = 0

			IF EXISTS(SELECT Id FROM sPurchase.tSalesReturnDetail WHERE SalesReturnId = @rId)
			BEGIN
				DELETE FROM sPurchase.tSalesReturnDetail
				WHERE SalesReturnId = @rId
			END
			SELECT 1
		END
	COMMIT TRANSACTION
	END TRY

	BEGIN CATCH
    IF @@TRANCOUNT > 0
        ROLLBACK TRANSACTION


    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 [sPurchase].[pSalesReturnGet]    Script Date: 01-02-2024 12:00:42 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[sPurchase].[pSalesReturnGet]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [sPurchase].[pSalesReturnGet] AS'
END
GO

--exec [sPurchase].[pSalesReturnGet] 991100001
ALTER PROCEDURE [sPurchase].[pSalesReturnGet]
	  @rId INT,
	  @rUserId BIGINT,
	  @rOrgGroupId INT
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
	    DECLARE @rStoreLocationId BIGINT
        SELECT @rStoreLocationId = ISNULL(ItemValue,0)
	    FROM sConfig.tConfigurationSetup
	    WHERE ConfigurationId  = 542 AND SourceId = @rUserId

		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,
				ISNULL(PO.RefNumber,'') AS PurchaseOrderNumber
		FROM   [sPurchase].[tSalesReturn] SR(NOLOCK)
		LEFT JOIN [sPurchase].[tGoodsReceivedNote] GRN ON GRN.Id = SR.GoodsReceivedNoteID
			  AND GRN.LocationId = @rStoreLocationId AND GRN.OrgGroupId = @rOrgGroupId AND GRN.IsObsolete = 0
		LEFT JOIN sPurchase.tPurchaseOrder PO ON PO.Id = SR.PurchaseOrderId
			  AND PO.LocationId = @rStoreLocationId AND PO.OrgGroupId = @rOrgGroupId AND PO.IsObsolete = 0
		LEFT JOIN [sWf].[tWfStatusMaster] SM ON SM.Id = SR.StatusId
		LEFT JOIN  sProcurement.tVendorMaster  VM ON SR.VendorId = VM.ID
			  AND VM.LocationId = @rStoreLocationId AND VM.OrgGroupId = @rOrgGroupId AND VM.IsObsolete = 0
		WHERE  SR.Id=@rId AND SR.LocationId = @rStoreLocationId AND SR.OrgGroupId = @rOrgGroupId 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 AND QC1.LocationId = @rStoreLocationId
					AND QC1.OrgGroupId = @rOrgGroupId AND QC1.IsObsolete = 0) AS GRNRejectedQty
		FROM   [sPurchase].[tSalesReturnDetail] SRD (NOLOCK)
			   INNER JOIN	sPurchase.tSalesReturn SR	ON SR.Id = SRD.SalesReturnId
				      AND SR.LocationId = @rStoreLocationId AND SR.OrgGroupId = @rOrgGroupId AND SR.IsObsolete = 0
			   INNER JOIN	sIp.tStockItemMaster SIM	ON SIM.Id = SRD.StockItemId
					  AND SIM.StoreLocationId = @rStoreLocationId AND SIM.OrgGroupId = @rOrgGroupId AND SIM.IsObsolete = 0
			   LEFT JOIN [sIp].[tStockItemCategoryMaster] SCM ON SCM.Id = SIM.StockItemCategoryId
			   INNER JOIN  sFinanceCommon.tStockUomMaster SUMa ON SUMa.Id = SIM.IssueStockUomId
		WHERE  SRD.SalesReturnId=@rId AND SR.LocationId = @rStoreLocationId AND SR.OrgGroupId = @rOrgGroupId AND SR.IsObsolete = 0
	END TRY

	BEGIN CATCH
    IF @@TRANCOUNT > 0
        ROLLBACK TRANSACTION

    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 [sPurchase].[pSalesReturnSearchGet]    Script Date: 01-02-2024 12:00:42 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[sPurchase].[pSalesReturnSearchGet]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [sPurchase].[pSalesReturnSearchGet] AS'
END
GO


ALTER PROCEDURE [sPurchase].[pSalesReturnSearchGet]

	@rNumber NVARCHAR(30) = '',
	@rName NVARCHAR = '',
	@rStartDate DATETIME = NULL,
	@rEndDate DATETIME = NULL,
	@rOrgGroupId INT,
    @rPageNo INT,
	@rPageSize INT,
	@rStatusId SMALLINT = NULL,
	@rUserId BIGINT

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	    DECLARE @rStoreLocationId BIGINT
        SELECT @rStoreLocationId = ISNULL(ItemValue,0)
	    FROM sConfig.tConfigurationSetup
	    WHERE ConfigurationId  = 542 AND SourceId = @rUserId

		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 ((SR.LocationId = @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 ((SR.LocationId = @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 TRANSACTION

    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 [sPurchase].[pSearchScreenDependencyGet]    Script Date: 01-02-2024 12:00:42 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[sPurchase].[pSearchScreenDependencyGet]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [sPurchase].[pSearchScreenDependencyGet] AS'
END
GO


ALTER PROCEDURE [sPurchase].[pSearchScreenDependencyGet]
	  @rScreenId INT
AS
SET NOCOUNT ON

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

	BEGIN CATCH
    IF @@TRANCOUNT > 0
        ROLLBACK TRANSACTION

    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 [sPurchase].[pStockBatchAddModify]    Script Date: 01-02-2024 12:00:42 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[sPurchase].[pStockBatchAddModify]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [sPurchase].[pStockBatchAddModify] AS'
END
GO
--exec [sPurchase].[pStockBatchAddModify] 9911,991100001,991100001,100,'+',9911000000270
ALTER PROCEDURE [sPurchase].[pStockBatchAddModify]
	@rOrgGroupId INT,
	@rStoreLocationId INT = 0,
	@rStockItemId INT = 0,
	@rQuantity DECIMAL(12,2) = 0.00,
	@rOperation NVARCHAR(20),
	@rUserId BIGINT
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

       DECLARE @1AvailableQuantity DECIMAL(12,2)

BEGIN
    BEGIN TRY
    IF EXISTS(SELECT Id FROM sProcurement.tStockBatch WHERE Id = @rStockItemId)
	BEGIN
		IF(@rOperation = '+')
		BEGIN
			 UPDATE  sProcurement.tStockBatch
			 SET  AvailableQuantity = ISNULL(AvailableQuantity,0) + @rQuantity,
				  UpdatedUserId = @rUserId,
				  UpdatedDateTime = sCommon.fGetDate()
			 FROM sProcurement.tStockBatch
			 WHERE
			(StoreLocationId = @rStoreLocationId OR @rStoreLocationId = 0) AND
			(StockItemId = @rStockItemId OR @rStockItemId = 0) AND
			--(Number = @rNumber OR ISNULL(@rNumber, '') = '') AND
			--(ExpiryDate = @rExpiryDate OR ISNULL(@rExpiryDate, '') = '') AND
			 OrgGroupId = @rOrgGroupId
		END
		ELSE
		BEGIN
			UPDATE  sProcurement.tStockBatch
			 SET  AvailableQuantity = ISNULL(AvailableQuantity,0) - @rQuantity,
				  UpdatedUserId = @rUserId,
				  UpdatedDateTime = sCommon.fGetDate()
			 FROM sProcurement.tStockBatch
			 WHERE
			(StoreLocationId = @rStoreLocationId OR @rStoreLocationId = 0) AND
			(StockItemId = @rStockItemId OR @rStockItemId = 0) AND
			--(Number = @rNumber OR ISNULL(@rNumber, '') = '') AND
			--(ExpiryDate = @rExpiryDate OR ISNULL(@rExpiryDate, '') = '') AND
			 OrgGroupId = @rOrgGroupId
		END
	END
	END TRY
	BEGIN CATCH
		ROLLBACK TRANSACTION

		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 [sPurchase].[pStockItemMasterGetWithCategory]    Script Date: 01-02-2024 12:00:42 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[sPurchase].[pStockItemMasterGetWithCategory]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [sPurchase].[pStockItemMasterGetWithCategory] AS'
END
GO

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

BEGIN
    BEGIN TRY
    DECLARE @rStoreLocationId BIGINT
    SELECT @rStoreLocationId = ISNULL(ItemValue,0)
	FROM sConfig.tConfigurationSetup
	WHERE ConfigurationId  = 542 AND SourceId = @rUserId
    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.StoreLocationId = @rStoreLocationId) OR (@rStoreLocationId = 0))
   		AND ((SIM.OrgGroupId = @rOrgGroupId) OR (@rOrgGroupId=0))
		AND SIM.IsObsolete= 0
	END TRY
	BEGIN CATCH
		ROLLBACK TRANSACTION

		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 [sPurchase].[pStockItemMasterSearchGet]    Script Date: 01-02-2024 12:00:42 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[sPurchase].[pStockItemMasterSearchGet]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [sPurchase].[pStockItemMasterSearchGet] AS'
END
GO
--exec [sPurchase].[pStockItemMasterSearchGet] 9911000000270,991100001,''
ALTER PROCEDURE [sPurchase].[pStockItemMasterSearchGet]
	@rUserId BIGINT,
	@rOrgGroupId INT,
	@rCurrentAlphabet NVARCHAR(10)

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
    BEGIN TRY
    DECLARE @rStoreLocationId BIGINT
    SELECT @rStoreLocationId = ISNULL(ItemValue,0)
	FROM sConfig.tConfigurationSetup
	WHERE ConfigurationId  = 542 AND SourceId = @rUserId

	SELECT
			Id,
			Code,
			Title FROM sIp.tStockItemMaster SIM

	  WHERE
		 ((Title LIKE @rCurrentAlphabet + '%') OR (ISNULL(@rCurrentAlphabet,'')=''))
	     AND IsObsolete= 0
	     AND SIM.StoreLocationId = @rStoreLocationId
	     AND SIM.OrgGroupId = @rOrgGroupId
	END TRY
	BEGIN CATCH
		ROLLBACK TRANSACTION

		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 [sPurchase].[pStoreLocationGet]    Script Date: 01-02-2024 12:00:42 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[sPurchase].[pStoreLocationGet]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [sPurchase].[pStoreLocationGet] AS'
END
GO
ALTER 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
    BEGIN TRY

	--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 TRY
	BEGIN CATCH
		ROLLBACK TRANSACTION

		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 [sPurchase].[pStoreLocationMasterGet]    Script Date: 01-02-2024 12:00:42 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[sPurchase].[pStoreLocationMasterGet]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [sPurchase].[pStoreLocationMasterGet] AS'
END
GO
ALTER 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
    BEGIN TRY

	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 TRY
	BEGIN CATCH
		ROLLBACK TRANSACTION

		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 [sPurchase].[pStudentProfileGet]    Script Date: 01-02-2024 12:00:42 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[sPurchase].[pStudentProfileGet]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [sPurchase].[pStudentProfileGet] AS'
END
GO

ALTER PROCEDURE [sPurchase].[pStudentProfileGet]
@rAcademicId BIGINT,
@rbatchId INT
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
    IF @@TRANCOUNT > 0
        ROLLBACK TRANSACTION

    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 [sPurchase].[pValidateCloudStorage]    Script Date: 01-02-2024 12:00:42 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[sPurchase].[pValidateCloudStorage]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [sPurchase].[pValidateCloudStorage] AS'
END
GO



ALTER PROCEDURE [sPurchase].[pValidateCloudStorage]
	  @rOrgGroupId SMALLINT
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
		 SELECT ISNULL(SUM(UD.DocumentSize),0)
		 FROM sCommon.tUploadDocument UD (NOLOCK)
		 INNER JOIN sSetup.tOrgGroupBatchMaster OGBM
		 ON OGBM.Id = UD.OrgGroupBatchId
		 WHERE OGBM.OrgGroupId = @rOrgGroupId
	END TRY

	BEGIN CATCH
    IF @@TRANCOUNT > 0
        ROLLBACK TRANSACTION

    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 [sPurchase].[pVendorNotificationGet]    Script Date: 01-02-2024 12:00:42 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[sPurchase].[pVendorNotificationGet]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [sPurchase].[pVendorNotificationGet] AS'
END
GO


--exec [sPurchase].[pVendorNotificationGet] 991100022,'',9911
ALTER PROCEDURE [sPurchase].[pVendorNotificationGet]
		 @rQuotationRequestId BIGINT,
		 @rNotificationLink NVARCHAR(1000),
		 @rOrgId SMALLINT,
	     @rUserId BIGINT,
	     @rOrgGroupId INT

	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
 BEGIN
        BEGIN TRY
        DECLARE @rStoreLocationId BIGINT
        SELECT @rStoreLocationId = ISNULL(ItemValue,0)
	    FROM sConfig.tConfigurationSetup
	    WHERE ConfigurationId  = 542 AND SourceId = @rUserId

		DECLARE @VendorId BIGINT
		SELECT @VendorId = QR.VendorId FROM sPurchase.tQuotationRequest QR WHERE QR.Id = @rQuotationRequestId AND QR.LocationId = @rStoreLocationId AND QR.OrgGroupId = @rOrgGroupId AND QR.IsObsolete = 0

		SET @rNotificationLink = '<a href="'+@rNotificationLink+'" target="_blank">'+@rNotificationLink+'</a>'

	DECLARE @txtMessage NVARCHAR(MAX)
    SELECT @txtMessage=REPLACE(REPLACE(Template,
		'[VendorName]' , (SELECT VM.ContactPersonName AS Name
						FROM	sProcurement.tVendorMaster  VM
						WHERE VM.Id = @VendorId AND VM.LocationId = @rStoreLocationId AND VM.OrgGroupId = @rOrgGroupId AND VM.IsObsolete = 0)),
		'[NotificationLink]' , @rNotificationLink) FROM sAlert.tEventTemplate WHERE IsAutoSend = 1 AND OrgId = @rOrgId AND EventId = 158

	SELECT
			--A.AcademicId,
			A.Code,
			A.Name,
			A.ParentContactNo AS MobileNo,
			A.ParentEmail AS EmailId,
			@txtMessage	AS MsgText,
			'' AS Subject,
			 2001 AS ReceiverSourceTypeId,
			 (SELECT Id FROM sSetup.tOrganizationMaster WHERE OrgGroupId=A.OrgGroupId AND Id = A.OrgGroupId) AS OrgId,
			 A.OrgGroupId AS OrgGroupId,
			 A.Id AS ReceiverSourceId,
			 A.Id AS SourceId,
			 2001 AS SourceTypeId,
			 --DM.Title AS MeetingType,
			 --CONVERT(varchar(11),ISNULL(OM.StartDate,'') ,103) AS StartDate,
			 --CONVERT(varchar(11),ISNULL(OM.EndDate,'') ,103) AS EndDate,
			 --EE.EmployeeName AS Teacher,
			 --OM.Title AS Title,
			 A.WhatsAppContactNo
	FROM
		 [sPurchase].[tQuotationRequestDetail] QRD (NOLOCK)
		INNER JOIN	sPurchase.tQuotationRequest QR	ON QR.Id = QRD.QuotationRequestId   AND QR.LocationId = @rStoreLocationId AND QR.OrgGroupId = @rOrgGroupId AND QR.IsObsolete = 0
		INNER JOIN	sIp.tStockItemMaster SIM	ON SIM.Id = QRD.StockItemId  AND SIM.StoreLocationId = @rStoreLocationId AND SIM.OrgGroupId = @rOrgGroupId AND SIM.IsObsolete = 0
		INNER JOIN  sFinanceCommon.tStockUomMaster SUMa ON SUMa.Id = SIM.IssueStockUomId
		INNER JOIN (
			SELECT	VM.Id,
					VM.ContactPersonName AS Name,
					VM.Code,
					VM.PhoneNumberOffice AS ParentContactNo,
					VM.Email AS ParentEmail,
					VM.OrgGroupId,
					VM.PhoneNumberMobile WhatsAppContactNo
			FROM	sProcurement.tVendorMaster  VM
			LEFT JOIN   sProcurement.tVendorCategoryMaster VC
			ON  VM.VendorCategoryId = VC.Id
			WHERE VM.Id = @VendorId AND VM.LocationId = @rStoreLocationId AND VM.OrgGroupId = @rOrgGroupId AND VM.IsObsolete = 0
		) AS A ON A.Id = QR.VendorId
		WHERE  QR.Id = @rQuotationRequestId AND QR.IsObsolete = 0
		       AND QR.LocationId = @rStoreLocationId
			   AND QR.OrgGroupId = @rOrgGroupId
	 END TRY
	 BEGIN CATCH
		ROLLBACK TRANSACTION

		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 [sPurchase].[pWhatsAppTemplateGet]    Script Date: 01-02-2024 12:00:42 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[sPurchase].[pWhatsAppTemplateGet]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [sPurchase].[pWhatsAppTemplateGet] AS'
END
GO

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

--exec [sWf].[pWfApprovalAdd] 0,991100029, 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

	DECLARE @rUserId BIGINT
	SET @rUserId = @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,
			@lActionByEmployeeId,
			@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
		DECLARE @rStoreLocationId BIGINT
		SELECT @rStoreLocationId = ISNULL(ItemValue,0)
		FROM sConfig.tConfigurationSetup
		WHERE ConfigurationId  = 542 AND SourceId = @rUserId

		IF(@rDocSourceTypeId = 2040)
		BEGIN
			UPDATE sPurchase.tPurchaseRequest
			SET StatusId = @StatusId,
				UpdatedUserId = @rActionEmployeeId,
				UpdatedDateTime = GETUTCDATE()
			WHERE Id = @rDocSourceId AND OrgGroupId = @rOrgGroupId AND LocationId = @rStoreLocationId AND IsObsolete = 0
		END
		ELSE IF(@rDocSourceTypeId = 2041)
		BEGIN
			UPDATE sPurchase.tQuotationRequest
			SET StatusId = @StatusId,
				UpdatedUserId = @rActionEmployeeId,
				UpdatedDateTime = GETUTCDATE()
			WHERE Id = @rDocSourceId AND OrgGroupId = @rOrgGroupId AND LocationId = @rStoreLocationId AND IsObsolete = 0
		END
		ELSE IF(@rDocSourceTypeId = 2042)
		BEGIN
			UPDATE sPurchase.tPurchaseOrder
			SET StatusId = @StatusId,
				UpdatedUserId = @rActionEmployeeId,
				UpdatedDateTime = GETUTCDATE()
			WHERE Id = @rDocSourceId AND OrgGroupId = @rOrgGroupId AND LocationId = @rStoreLocationId AND IsObsolete = 0
		END
		ELSE IF(@rDocSourceTypeId = 2043)
		BEGIN
			UPDATE sPurchase.tGoodsReceivedNote
			SET StatusId = @StatusId,
				UpdatedUserId = @rActionEmployeeId,
				UpdatedDateTime = GETUTCDATE()
			WHERE Id = @rDocSourceId AND OrgGroupId = @rOrgGroupId AND LocationId = @rStoreLocationId AND IsObsolete = 0
		END
		ELSE IF(@rDocSourceTypeId = 2044)
		BEGIN
			UPDATE sPurchase.tSalesReturn
			SET StatusId = @StatusId,
				UpdatedUserId = @rActionEmployeeId,
				UpdatedDateTime = GETUTCDATE()
			WHERE Id = @rDocSourceId AND OrgGroupId = @rOrgGroupId AND LocationId = @rStoreLocationId AND IsObsolete = 0
		END
	END
	COMMIT TRANSACTION
	END TRY

	BEGIN CATCH
    IF @@TRANCOUNT > 0
        ROLLBACK TRANSACTION


    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 [sWf].[pWfApprovalGet]    Script Date: 01-02-2024 12:00:42 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[sWf].[pWfApprovalGet]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [sWf].[pWfApprovalGet] AS'
END
GO


--exec [sWf].[pWfApprovalGet] 1,'2023-10-10','2024-02-02',0,9911,9911,'',9911000000270,1,10,0

ALTER  PROCEDURE [sWf].[pWfApprovalGet]
			 @rWfFunctionalityId SMALLINT = 0,
			 @rFromDate DATE = NULL,
			 @rToDate DATE = NULL,
			 @rStatusId SMALLINT = 0,
			 @rOrgId SMALLINT = 0,
			 @rOrgGroupId 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 @rStoreLocationId BIGINT
    SELECT @rStoreLocationId = ISNULL(ItemValue,0)
	FROM sConfig.tConfigurationSetup
	WHERE ConfigurationId  = 542 AND SourceId = @rUserId

	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
	INNER 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))
	AND PR.LocationId = @rStoreLocationId AND PR.IsObsolete = 0
	AND PR.OrgGroupId = @rOrgGroupId
	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))
	AND PR.LocationId = @rStoreLocationId AND PR.IsObsolete = 0
	AND PR.OrgGroupId = @rOrgGroupId
	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))
	AND PR.LocationId = @rStoreLocationId AND PR.IsObsolete = 0
	AND PR.OrgGroupId = @rOrgGroupId
	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))
	AND PR.LocationId = @rStoreLocationId AND PR.IsObsolete = 0
	AND PR.OrgGroupId = @rOrgGroupId
	------------------------------------------------------------------------------------------------------------------------------------------------------------------
	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
	INNER 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))
	AND QR.LocationId = @rStoreLocationId AND QR.IsObsolete = 0
	AND QR.OrgGroupId = @rOrgGroupId
	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))
	AND QR.LocationId = @rStoreLocationId AND QR.IsObsolete = 0
	AND QR.OrgGroupId = @rOrgGroupId
	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))
	AND QR.LocationId = @rStoreLocationId AND QR.IsObsolete = 0
	AND QR.OrgGroupId = @rOrgGroupId
	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))
	AND QR.LocationId = @rStoreLocationId AND QR.IsObsolete = 0
	AND QR.OrgGroupId = @rOrgGroupId
	------------------------------------------------------------------------------------------------------------------------------------------------------------------


	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
	INNER 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))
	AND PO.LocationId = @rStoreLocationId AND PO.IsObsolete = 0
	AND PO.OrgGroupId = @rOrgGroupId
	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))
	AND PO.LocationId = @rStoreLocationId AND PO.IsObsolete = 0
	AND PO.OrgGroupId = @rOrgGroupId
	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))
	AND PO.LocationId = @rStoreLocationId AND PO.IsObsolete = 0
	AND PO.OrgGroupId = @rOrgGroupId
	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))
	AND PO.LocationId = @rStoreLocationId AND PO.IsObsolete = 0
	AND PO.OrgGroupId = @rOrgGroupId
	------------------------------------------------------------------------------------------------------------------------------------------------------------------

	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
	INNER 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))
	AND GRN.LocationId = @rStoreLocationId AND GRN.IsObsolete = 0
	AND GRN.OrgGroupId = @rOrgGroupId
	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))
	AND GRN.LocationId = @rStoreLocationId AND GRN.IsObsolete = 0
	AND GRN.OrgGroupId = @rOrgGroupId
	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))
	AND GRN.LocationId = @rStoreLocationId AND GRN.IsObsolete = 0
	AND GRN.OrgGroupId = @rOrgGroupId
	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))
	AND GRN.LocationId = @rStoreLocationId AND GRN.IsObsolete = 0
	AND GRN.OrgGroupId = @rOrgGroupId
	------------------------------------------------------------------------------------------------------------------------------------------------------------------

	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
	INNER 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))
	AND SR.LocationId = @rStoreLocationId AND SR.IsObsolete = 0
	AND SR.OrgGroupId = @rOrgGroupId
	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))
	AND SR.LocationId = @rStoreLocationId AND SR.IsObsolete = 0
	AND SR.OrgGroupId = @rOrgGroupId
	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))
	AND SR.LocationId = @rStoreLocationId AND SR.IsObsolete = 0
	AND SR.OrgGroupId = @rOrgGroupId
	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))
	AND SR.LocationId = @rStoreLocationId AND SR.IsObsolete = 0
	AND SR.OrgGroupId = @rOrgGroupId
	)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 TRANSACTION

    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 [sWf].[pWfFunctionalityMasterGet]    Script Date: 01-02-2024 12:00:42 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[sWf].[pWfFunctionalityMasterGet]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [sWf].[pWfFunctionalityMasterGet] AS'
END
GO


ALTER PROCEDURE [sWf].[pWfFunctionalityMasterGet]
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
		SELECT Id,
			   Code,
			   Title,
			   IsObsolete
			   --Type
		FROM   sWf.tWfFunctionalityMaster(NOLOCK)
		WHERE  IsObsolete = 0
	END TRY

	BEGIN CATCH
    IF @@TRANCOUNT > 0
        ROLLBACK TRANSACTION

    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 [sWf].[pWfRoleGet]    Script Date: 01-02-2024 12:00:42 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[sWf].[pWfRoleGet]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [sWf].[pWfRoleGet] AS'
END
GO



ALTER PROCEDURE [sWf].[pWfRoleGet]
	  @rOrgGroupId SMALLINT
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
		SELECT Id,
			   Title AS DisplayTitle
	    FROM   sSecurity.tRole (NOLOCK)
		WHERE  IsObsolete='0' AND OrgGroupId = @rOrgGroupId
          AND  Id <> ([sCommon].[fGetIntIdForOrg](21,@rOrgGroupId))
		  AND  Id <> ([sCommon].[fGetIntIdForOrg](22,@rOrgGroupId))
	END TRY

	BEGIN CATCH
    IF @@TRANCOUNT > 0
        ROLLBACK TRANSACTION

    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 [sWf].[pWfSetupAdd]    Script Date: 01-02-2024 12:00:42 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[sWf].[pWfSetupAdd]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [sWf].[pWfSetupAdd] AS'
END
GO



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 AND WFS.OrgGroupId = @rOrgGroupId AND WFS.WfTypeMasterId = @rWfTypeMasterId AND WFS.IsObsolete = 0)
				BEGIN
					SELECT -102
				END
				ELSE
				BEGIN
					IF NOT EXISTS(SELECT WFM.Id
					from [sWf].[tWfFunctionalityMaster] WFM
					WHERE WFM.Id = @rWfFunctionalityId AND WFM.IsObsolete = 0)
					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.OrgGroupId = @rOrgGroupId AND WS.IsObsolete = 0
							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 AND OrgGroupId = @rOrgGroupId AND IsObsolete = 0

					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

		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 [sWf].[pWfSetupGet]    Script Date: 01-02-2024 12:00:42 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[sWf].[pWfSetupGet]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [sWf].[pWfSetupGet] AS'
END
GO


ALTER PROCEDURE [sWf].[pWfSetupGet]
	  @rWfFunctionalityId SMALLINT,
	  @rOrgGroupId SMALLINT,
	  @rOrgId SMALLINT
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
		SELECT WFS.AutoId,
			   WFS.WfTypeMasterId,
			   WFS.WfLevel,
			   WFS.OrgGroupId,
			   WFS.WfFunctionalityId
		FROM   [sWf].[tWfSetup] WFS(NOLOCK)
		WHERE  WFS.WfFunctionalityId = @rWfFunctionalityId AND WFS.OrgGroupId = @rOrgGroupId AND WFS.IsObsolete = 0

		--DECLARE @wfFunctionalityId SMALLINT
		--SELECT @wfFunctionalityId = WfFunctionalityId
		--FROM   [sWf].[tWfSetup](NOLOCK)
		--WHERE  AutoId = @rId AND OrgGroupId = @rOrgGroupId AND IsObsolete = 0

		SELECT [AutoId]
			  ,[AuthoritySourceTypeId]
			  ,[AuthoritySourceId]
			  ,[OrgId]
			  ,[WfFunctionalityId]
		 FROM  [sWf].[tWfApprovingAuthority] (NOLOCK)
		 WHERE WfFunctionalityId = @rWfFunctionalityId AND OrgId = @rOrgId
	END TRY

	BEGIN CATCH
    IF @@TRANCOUNT > 0
        ROLLBACK TRANSACTION

    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 [sWf].[pWfTypeMasterGet]    Script Date: 01-02-2024 12:00:42 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[sWf].[pWfTypeMasterGet]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [sWf].[pWfTypeMasterGet] AS'
END
GO


ALTER PROCEDURE [sWf].[pWfTypeMasterGet]
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
		SELECT  Id,
				Code,
				Title,
				IsObsolete
		FROM    sWf.tWfTypeMaster(NOLOCK)
		WHERE   IsObsolete = 0
	END TRY

	BEGIN CATCH
    IF @@TRANCOUNT > 0
        ROLLBACK TRANSACTION

    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 [sWf].[pWfUserGet]    Script Date: 01-02-2024 12:00:42 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[sWf].[pWfUserGet]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [sWf].[pWfUserGet] AS'
END
GO


ALTER PROCEDURE [sWf].[pWfUserGet]
	  @rOrgGroupId SMALLINT
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
		SELECT U.Id,
	           U.DisplayTitle
		FROM   sSecurity.tUser U (NOLOCK)
		INNER JOIN sSecurity.tUserRole UR ON UR.UserId = U.Id
		INNER JOIN sSecurity.tRole R ON R.Id = UR.RoleId
		WHERE U.IsObsolete='0' AND UR.IsObsolete='0' AND U.OrgId = @rOrgGroupId
		AND   R.Id <> ([sCommon].[fGetIntIdForOrg](21,@rOrgGroupId))
		AND   R.Id <> ([sCommon].[fGetIntIdForOrg](22,@rOrgGroupId))
	END TRY

	BEGIN CATCH
    IF @@TRANCOUNT > 0
        ROLLBACK TRANSACTION

    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].[pOnlineMeetingTeacherStudentListGet]    Script Date: 19-01-2024 12:45:53 ******/
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: 19-01-2024 12:45:53 ******/
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].[pOnlineMeetingScopeValidate]    Script Date: 19-01-2024 12:45:53 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[sEMeeting].[pOnlineMeetingScopeValidate]') AND type in (N'P', N'PC'))
DROP PROCEDURE [sEMeeting].[pOnlineMeetingScopeValidate]
GO
/****** Object:  StoredProcedure [sEMeeting].[pOnlineMeetingEmployeeGet]    Script Date: 19-01-2024 12:45:53 ******/
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].[pOnlineMeetingAdd]    Script Date: 19-01-2024 12:45:53 ******/
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:  Table [sEMeeting].[tTempOnlineMeetingScope]    Script Date: 19-01-2024 12:45:53 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[sEMeeting].[tTempOnlineMeetingScope]') AND type in (N'U'))
DROP TABLE [sEMeeting].[tTempOnlineMeetingScope]
GO
/****** Object:  StoredProcedure [sEMeeting].[pTempOnlineMeetingScopeAdd]    Script Date: 19-01-2024 18:51:28 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[sEMeeting].[pTempOnlineMeetingScopeAdd]') AND type in (N'P', N'PC'))
DROP PROCEDURE [sEMeeting].[pTempOnlineMeetingScopeAdd]
GO
/****** Object:  Table [sEMeeting].[tTempOnlineMeetingScope]    Script Date: 19-01-2024 12:45:53 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[sEMeeting].[tTempOnlineMeetingScope]') AND type in (N'U'))
BEGIN
CREATE TABLE [sEMeeting].[tTempOnlineMeetingScope](
	[TempOnlineMeetingId] [nvarchar](100) NOT NULL,
	[SourceTypeId] [smallint] NOT NULL,
	[SourceId] [bigint] NOT NULL,
	[AssigneeToId] [tinyint] NULL
) ON [PRIMARY]
END
GO
/****** Object:  StoredProcedure [sEMeeting].[pOnlineMeetingAdd]    Script Date: 19-01-2024 12:45:53 ******/
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,
		@rTempOnlineMeetingId nvarchar(100) = '',
		@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(@rTempOnlineMeetingId <> NULL OR @rTempOnlineMeetingId <> '')
	BEGIN
	DELETE FROM [sEMeeting].[tTempOnlineMeetingScope] WHERE TempOnlineMeetingId = @rTempOnlineMeetingId
	END
	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].[pOnlineMeetingEmployeeGet]    Script Date: 19-01-2024 12:45:53 ******/
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 ,
	Code
	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].[pOnlineMeetingScopeValidate]    Script Date: 19-01-2024 12:45:53 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[sEMeeting].[pOnlineMeetingScopeValidate]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [sEMeeting].[pOnlineMeetingScopeValidate] AS' 
END
GO
ALTER PROCEDURE [sEMeeting].[pOnlineMeetingScopeValidate]
	 
        @rTempOnlineMeetingId nvarchar(100),
		@rSourceTypeId smallint,
		@rSourceId bigint,
		@rAssigneeToId int
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
					/* Source Type Value
					   2021 - Organization
					   2017 - Department
					   2016 - Class
					   2005 - Division
					   2003 - Student */


		If EXISTS(select 1 from sEMeeting.tTempOnlineMeetingScope OMS where OMS.SourceId=@rSourceId AND
					OMS.SourceTypeId=@rSourceTypeId AND OMS.TempOnlineMeetingId=@rTempOnlineMeetingId AND AssigneeToId=@rAssigneeToId) 
			BEGIN
				select -101 as Result,'Item Already Exists' AS Msg
				RETURN
			END 

	
	IF(@rSourceTypeId = 2021) -- Organization	
		BEGIN
			If EXISTS(select 1 from  sEMeeting.tTempOnlineMeetingScope OMS
			 INNER JOIN  sSetup.tDepartmentMaster DM 
				ON OMS.SourceId=DM.Id AND OMS.SourceTypeId= 2017
				where DM.OrgId=@rSourceId  AND OMS.TempOnlineMeetingId=@rTempOnlineMeetingId AND AssigneeToId=@rAssigneeToId)
					BEGIN
						select -103 as Result,'Department already Exists' AS Msg
						RETURN
					END 
			If EXISTS(select 1 from  sEMeeting.tTempOnlineMeetingScope OMS 
			 INNER JOIN  sSetup.tClassMaster CM 
				ON OMS.SourceId=CM.Id AND OMS.SourceTypeId= 2016
				where CM.OrgId=@rSourceId  AND OMS.TempOnlineMeetingId=@rTempOnlineMeetingId AND AssigneeToId=@rAssigneeToId)
					BEGIN
						select -103 as Result,'Class already Exists' AS Msg
						RETURN
					END 
					
			If EXISTS(select 1 from  sEMeeting.tTempOnlineMeetingScope OMS 
			 INNER JOIN  sSetup.tDivisionMaster DM 
				ON OMS.SourceId=DM.Id AND OMS.SourceTypeId= 2005
				where DM.OrgId=@rSourceId  AND OMS.TempOnlineMeetingId=@rTempOnlineMeetingId AND AssigneeToId=@rAssigneeToId)
					BEGIN
						select -103 as Result,'Division already Exists' AS Msg
						RETURN
					END 
					
			If EXISTS(select 1 from  sEMeeting.tTempOnlineMeetingScope OMS 
			 INNER JOIN  sStudent.vStudentAcademic SA
				ON OMS.SourceId=SA.AcademicId AND OMS.SourceTypeId= 2003
				where SA.OrgId=@rSourceId  AND OMS.TempOnlineMeetingId=@rTempOnlineMeetingId AND AssigneeToId=@rAssigneeToId)
					BEGIN
						select -103 as Result,'Student already Exists' AS Msg
						RETURN
					END 		

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

    END
			select 1 as Result,'' AS Msg
	
END

GO
/****** Object:  StoredProcedure [sEMeeting].[pOnlineMeetingTeacherGet]    Script Date: 19-01-2024 12:45:53 ******/
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,
	 @rIsOnlineMeetingAdmin bit
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
BEGIN
	BEGIN TRY
	If (@rSourceTypeId = 2003)
		BEGIN
		 SELECT DISTINCT EM.Id ,ISNULL(EM.FirstName,'') +' ' + ISNULL(EM.MiddleName,'') +' ' + ISNULL(EM.LastName ,'') As Title FROM [sHrm].[tEmployeeMaster] EM
		  INNER	JOIN [sEMeeting].[tOnlineMeeting] OM ON OM.HostEmployeeId=EM.Id
		END
	else if(@rOrgId = 0)
	 BEGIN
		If (@rSourceTypeId = 95)
		BEGIN
			If(@rIsOnlineMeetingAdmin = 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.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 Title
			END
		END
		else
		BEGIN
			SELECT EM.EmployeeId as Id, [sHrm].[fEmployeeNameGet](EM.FirstName , EM.MiddleName, EM.LastName,ISNULL(OrgM.EmployeeNameFormatId,1)) AS Title FROM sHrm.vExtEmployee EM 
			INNER JOIN sSetup.vUserOrganization OM ON OM.Id = EM.OrgId INNER JOIN sSetup.tOrganizationMaster OrgM ON OrgM.Id = EM.OrgId 
            WHERE ISNULL(EM.IsOtherUser,0) = 0 AND  EM.StatusId =7  AND EM.EmployeeGroupId = 1 AND OM.OrgGroupId = @rOrgGroupId AND OM.UserId = @rUserId 
			ORDER BY Title
		END
	 END
	else
		BEGIN
		If (@rSourceTypeId = 95)
		BEGIN
		if(@rIsOnlineMeetingAdmin = 1)
			BEGIN
				SELECT EM.EmployeeId as Id, [sHrm].[fEmployeeNameGet](EM.FirstName , EM.MiddleName, EM.LastName,ISNULL(OM.EmployeeNameFormatId,1)) AS Title FROM sHrm.vExtEmployee EM				INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = EM.OrgId WHERE ISNULL(IsOtherUser,0) = 0 AND  StatusId =7  AND EmployeeGroupId = 1 
				AND OM.OrgGroupId =	@rOrgGroupId AND OM.Id = @rOrgId ORDER BY Title	
			END
		else
			BEGIN
			SELECT EM.EmployeeId as Id, [sHrm].[fEmployeeNameGet](EM.FirstName , EM.MiddleName, EM.LastName,ISNULL(OM.EmployeeNameFormatId,1)) AS Title FROM sHrm.vExtEmployee EM				INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=EM.OrgId WHERE ISNULL(EM.IsOtherUser,0) = 0 AND  EM.StatusId =7  AND EM.EmployeeGroupId = 1
			AND EM.EmployeeId =	@rSourceId	ORDER BY Title
			END
		END
		else
		BEGIN
			SELECT EM.EmployeeId as Id, [sHrm].[fEmployeeNameGet](EM.FirstName , EM.MiddleName, EM.LastName,ISNULL(OrgM.EmployeeNameFormatId,1)) AS Title FROM sHrm.vExtEmployee EM				INNER JOIN sSetup.vUserOrganization OM ON OM.Id = EM.OrgId INNER JOIN sSetup.tOrganizationMaster OrgM ON OrgM.Id = EM.OrgId 
			WHERE ISNULL(EM.IsOtherUser,0) = 0 AND  EM.StatusId =7  AND EM.EmployeeGroupId = 1 AND OM.OrgGroupId = @rOrgGroupId AND OM.UserId = @rUserId AND OM.Id = @rOrgId 
			ORDER BY Title
		END
		END
	END TRY

	BEGIN CATCH 
		SELECT -1 AS Result
	END CATCH
END


GO
/****** Object:  StoredProcedure [sEMeeting].[pOnlineMeetingTeacherStudentListGet]    Script Date: 19-01-2024 12:45:53 ******/
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,
	 @rEmployeeId bigint = 0
		 
	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))
				AND (OM.HostEmployeeId = @rEmployeeId OR @rEmployeeId = 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].[pTempOnlineMeetingScopeAdd]    Script Date: 19-01-2024 18:51:28 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[sEMeeting].[pTempOnlineMeetingScopeAdd]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [sEMeeting].[pTempOnlineMeetingScopeAdd] AS' 
END
GO


ALTER PROCEDURE [sEMeeting].[pTempOnlineMeetingScopeAdd]

			@rTempOnlineMeetingId nvarchar(100)
           ,@rSourceTypeId smallint
           ,@rSourceId bigint
           ,@rIsDeleted bit
          ,@rAssigneeToId int 
           	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
 

If(@rIsDeleted=1)
BEGIN
	Delete from sEMeeting.tTempOnlineMeetingScope where TempOnlineMeetingId=@rTempOnlineMeetingId AND SourceTypeId=@rSourceTypeId AND AssigneeToId= @rAssigneeToId
	AND SourceId=@rSourceId
	Select @rSourceId as Result
END	
ELSE
BEGIN 
 
	If Exists(select TempOnlineMeetingId from sEMeeting.tTempOnlineMeetingScope where TempOnlineMeetingId=@rTempOnlineMeetingId AND SourceTypeId=@rSourceTypeId
	AND SourceId=@rSourceId AND AssigneeToId= @rAssigneeToId)
		BEGIN
			SELECT @rSourceId AS Result
			RETURN
	  END 
	ELSE
			BEGIN
			INSERT INTO sEMeeting.tTempOnlineMeetingScope
			(
				TempOnlineMeetingId
			   ,SourceTypeId
			   ,SourceId
			   ,AssigneeToId
			)
			VALUES
			(	
				@rTempOnlineMeetingId
			   ,@rSourceTypeId
			   ,@rSourceId
			   ,@rAssigneeToId
			)		
			SELECT 1 AS Result
		 
	END	
END

GO
