﻿USE [FabApprovalSystem]
GO
	/****** Object:  StoredProcedure [dbo].[LTUnlockWorkRequest]    Script Date: 11/21/2024 11:29:05 AM ******/
SET
	ANSI_NULLS ON
GO
SET
	QUOTED_IDENTIFIER ON
GO
	-- =============================================
	-- Author:		<Author,,Name>
	-- Create date: <Create Date,,>
	-- Description:	<Description,,>
	-- =============================================
	CREATE PROCEDURE [dbo].[LTUnlockWorkRequest] AS BEGIN -- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
SET
	NOCOUNT ON;

SELECT
	212 AS UserID,
	WR.SWRNumber AS IssueID,
	WR.ID AS SysDocumentID,
	'WorkRequest' AS DocumentType,
	'Record UnLock' AS OperationType,
	'Record locked by ' + U.FirstName + ' ' + U.LastName + ' on ' + CONVERT(VARCHAR(20), RecordLockedDate) + ' was Unlocked on ' + CONVERT(VARCHAR(20), GETDATE()) AS Comments,
	GETDATE() AS InsertTimeStamp INTO #TempLockedRecords
FROM
	LTWorkRequest WR
	INNER JOIN Users U ON WR.RecordLockedBy = U.UserID
WHERE
	DATEDIFF(MI, RecordLockedDate, GETDATE()) > 30
	AND DATEDIFF(MI, LastUpdateDate, GETDATE()) > 30
INSERT INTO
	EventLog (
		UserID,
		IssueID,
		SysDocumentID,
		DocumentType,
		OperationType,
		Comments,
		InsertTimeStamp
	)
SELECT
	*
FROM
	#TempLockedRecords
UPDATE
	LTWorkRequest
SET
	RecordLockedBy = NULL,
	RecordLockIndicator = 0,
	RecordLockedDate = NULl
WHERE
	ID IN (
		SELECT
			SysDocumentID
		FROM
			#TempLockedRecords)
			DROP TABLE #TempLockedRecords
	END
GO