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

SET
	XACT_ABORT ON;

BEGIN TRANSACTION
INSERT INTO
	EventLog(
		[IssueID],
		[SysDocumentID],
		[UserID],
		[DocumentType],
		[OperationType],
		[Comments],
		[InsertTimeStamp]
	)
SELECT
	@WorkRequestID,
	NULL,
	@UserID,
	'Lot Traveler',
	'Reassign Originator',
	LEFT(
		'Originator changed from ' + ISNULL(
			old.LoginID,
			CONVERT(varchar(20), LTWorkRequest.OriginatorID)
		) + ' to ' + ISNULL(
			new.LoginID,
			CONVERT(varchar(20), @NewOriginatorID)
		) + ' by ' + ISNULL(me.LoginID, CONVERT(varchar(20), @UserID)) + ' comments: ' + @Comments,
		500
	),
	GETDATE()
FROM
	LTWorkRequest
	LEFT OUTER JOIN Users old ON old.UserID = LTWorkRequest.OriginatorID
	LEFT OUTER JOIN Users new ON new.UserID = @NewOriginatorID
	LEFT OUTER JOIN Users me ON me.UserID = @UserID
WHERE
	LTWorkRequest.ID = @WorkRequestID
UPDATE
	LTWorkRequest
SET
	OriginatorID = @NewOriginatorID
WHERE
	ID = @WorkRequestID COMMIT TRANSACTION
END
GO