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

SELECT
	212 AS UserID,
	A.AuditNo AS IssueID,
	A.AuditNo AS SysDocumentID,
	'Audit' 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
	_8DAudit A
	INNER JOIN Users U ON A.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
	_8DAudit
SET
	RecordLockindicator = 0,
	RecordLockedBy = NULL,
	RecordLockedDate = NULL
WHERE
	AuditNo IN (
		SELECT
			SysDocumentID
		FROM
			#TempLockedRecords)
			DROP TABLE #TempLockedRecords
		SELECT
			212 AS UserID,
			CA.CANo AS IssueID,
			CA.CANo AS SysDocumentID,
			'CA' 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 #NewTempLockedRecords
		FROM
			_8DCorrectiveAction CA
			INNER JOIN Users U ON CA.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
			#NewTempLockedRecords
		UPDATE
			_8DCorrectiveAction
		SET
			RecordLockindicator = 0,
			RecordLockedBy = NULL,
			RecordLockedDate = NULL
		WHERE
			CANo IN (
				SELECT
					SysDocumentID
				FROM
					#NewTempLockedRecords)
					DROP TABLE #NewTempLockedRecords
			END
		GO