﻿USE [FabApprovalSystem]
GO
	/****** Object:  StoredProcedure [dbo].[LTGetLotTravelerHeaderForUpdate]    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].[LTGetLotTravelerHeaderForUpdate] -- Add the parameters for the stored procedure here
	@LTLotID INT,
	@UserID INT AS BEGIN -- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
SET
	NOCOUNT ON;

DECLARE @CurrLotTravelerRevisionID INT
SET
	@CurrLotTravelerRevisionID = (
		SELECT
			LA.ID
		FROM
			LTLot L
			INNER JOIN LTLotTravelerRevisionAttrib LA ON L.ID = LA.lTLotID
			AND LA.IsCurrentRevision = 1
		WHERE
			L.ID = @LTLotID
	)
SELECT
	DISTINCT L.ID,
	WR.SWRNumber,
	WR.Title,
	'Approved' AS Status,
	U.FirstName + ' ' + U.LastName AS Originator,
	U1.FirstName + ' ' + U1.LastName AS LastUpdatedBy,
	L.LotNumber,
	L.WIPPartNumber,
	L.PartDescription,
	L.Process,
	WR.IsITAR,
	L.WorkRequestID AS LTWorkRequestID,
	WR.Revision AS WorkReqRevision,
	WR.PurposeOfRequest,
	L.LotTravelerCurrentRevision AS LotTravCurrentRevision,
	LA.RecordLockIndicator,
	LA.RecordLockedBy,
	WR.ProcessFlow AS BaseFlow,
	TraverlerLastUpdatedDatetime AS LastUpdate,
	LA.ID AS LotTravRevID,
	U2.FirstName + ' ' + U2.LastName AS TravelerClosedBy,
	TravelerClosedReason,
	TravelerClosedDate,
	TravelerClosed
FROM
	LTLot L
	INNER JOIN LTWorkRequest WR ON WR.ID = L.WorkRequestID
	INNER JOIN LTLotTravelerRevisionAttrib LA ON L.ID = LA.lTLotID
	AND LA.IsCurrentRevision = 1
	LEFT JOIN Users U ON WR.OriginatorID = U.UserID
	LEFT JOIN Users U1 ON LA.TravelerLastUpdatedBy = U1.UserID
	LEFT JOIN Users U2 ON L.TravelerClosedBy = U2.UserID
WHERE
	L.ID = @LTLotID IF NOT EXISTS(
		SELECT
			*
		FROM
			LTLotTravelerRevisionAttrib
		WHERE
			RecordLockIndicator = 1
			AND ID = @CurrLotTravelerRevisionID
	) BEGIN
UPDATE
	LTLotTravelerRevisionAttrib
SET
	RecordLockIndicator = 1,
	RecordLockedBy = @UserID,
	RecordLockedDate = GETDATE()
WHERE
	ID = @CurrLotTravelerRevisionID
END
END
GO