﻿USE [FabApprovalSystem]
GO
	/****** Object:  StoredProcedure [dbo].[CCUpdateMeetingActionItemRespPersons]    Script Date: 11/21/2024 11:29:04 AM ******/
SET
	ANSI_NULLS ON
GO
SET
	QUOTED_IDENTIFIER ON
GO
	CREATE PROCEDURE [dbo].[CCUpdateMeetingActionItemRespPersons] @MeetingActionItemID int,
	@ResponsibleID varchar(100),
	@Comments varchar(500),
	@UserID int AS BEGIN
SET
	NOCOUNT ON;

SET
	XACT_ABORT ON;

BEGIN TRANSACTION DECLARE @SEPERATOR as VARCHAR(1) DECLARE @SP INT DECLARE @VALUE VARCHAR(1000)
SET
	@SEPERATOR = ',' CREATE TABLE #tempTab (ActionItemResponsible int not null, LoginID varchar(50) not null)
	WHILE PATINDEX('%' + @SEPERATOR + '%', @ResponsibleID) <> 0 BEGIN
SELECT
	@SP = PATINDEX('%' + @SEPERATOR + '%', @ResponsibleID)
SELECT
	@VALUE = LEFT(@ResponsibleID, @SP - 1)
SELECT
	@ResponsibleID = STUFF(@ResponsibleID, 1, @SP, '')
INSERT INTO
	#tempTab (ActionItemResponsible, LoginID) 
SELECT
	UserID,
	LoginID
FROM
	Users
WHERE
	UserID = @VALUE
END
INSERT INTO
	#tempTab (ActionItemResponsible, LoginID) 
SELECT
	UserID,
	LoginID
FROM
	Users
WHERE
	UserID = @ResponsibleID DECLARE @NewRPs varchar(500)
SELECT
	@NewRPs = STUFF(
		(
			SELECT
				',' + RTRIM(LoginID)
			FROM
				#tempTab FOR XML PATH('')), 1, 1, '')
				DECLARE @OldRPs varchar(500)
			SELECT
				@OldRPs = STUFF(
					(
						SELECT
							',' + RTRIM(U.LoginID)
						FROM
							CCMeetingActionItemResponsible AIR
							INNER JOIN Users U ON AIR.ActionItemResponsible = U.UserID
						WHERE
							AIR.MeetingActionItemID = @MeetingActionItemID FOR XML PATH('')
					),
					1,
					1,
					''
				)
			INSERT INTO
				EventLog(
					[IssueID],
					[SysDocumentID],
					[UserID],
					[DocumentType],
					[OperationType],
					[Comments],
					[InsertTimeStamp]
				)
			SELECT
				@MeetingActionItemID,
				NULL,
				@UserID,
				'MeetingActionItem',
				'Reassign Responsible Persons',
				LEFT(
					'Responsible persons changed from ' + @OldRPs + ' to ' + @NewRPs + ' by ' + ISNULL(me.LoginID, CONVERT(varchar(20), @UserID)) + ' comments: ' + @Comments,
					500
				),
				GETDATE()
			FROM
				CCMeetingActionItem
				LEFT OUTER JOIN Users me ON me.UserID = @UserID
			WHERE
				CCMeetingActionItem.ID = @MeetingActionItemID
			DELETE FROM
				CCMeetingActionItemResponsible
			WHERE
				MeetingActionItemID = @MeetingActionItemID
			INSERT INTO
				CCMeetingActionItemResponsible
			SELECT
				@MeetingActionItemID,
				ActionItemResponsible
			FROM
				#tempTab
				DROP TABLE #tempTab
				COMMIT TRANSACTION
		END
		GO