﻿USE [FabApprovalSystem]
GO
	/****** Object:  StoredProcedure [dbo].[LTCanAddLocationOperation]    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].[LTCanAddLocationOperation] @Location VARCHAR(50),
	@OperSequence NCHAR(10) = NULL,
	@Operation VARCHAR(50),
	@LTLotID INT,
	@Result INT = 0 OUTPUT AS BEGIN -- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
SET
	NOCOUNT ON;

DECLARE @SPNCurrentSeqForTheLot NCHAR(10) DECLARE @ProcessFlow NCHAR(10) DECLARE @LotNumber VARCHAR(50) DECLARE @SPNCurrentLotLocation NCHAR(10)
SET
	@LotNumber = (
		SELECT
			TOP 1 L.LotNumber
		FROM
			LTLot L
		WHERE
			L.ID = @LTLotID
	)
SET
	@ProcessFlow = (
		SELECT
			TOP 1 L.Process
		FROM
			LTLot L
		WHERE
			L.ID = @LTLotID
	)
SET
	@SPNCurrentLotLocation = (
		SELECT
			WP_CURRENT_LOCATION
		FROM
			vFAB2SPN_WP_RECORD WP
		WHERE
			WP_LOT_NO = @LotNumber
	) -- only allow add hol step at a current location or a location which has not been passed yet
	IF (@SPNCurrentLotLocation <= @Location) BEGIN -- Get the Max Sequence# for this lot for the given location
SET
	@SPNCurrentSeqForTheLot = (
		SELECT
			MAX(SEQ)
		FROM
			vFAB2SPN_WO_RECORD WO
			INNER JOIN vSPNPDB_FLOWLOCS F ON WO.WO_PROCESS = F.PROCESS
			AND WO.WO_LOCATION = F.LOC
			AND WO.WO_OPER_NO = F.OPER
		WHERE
			WO_LOT_NO = @LotNumber
			AND WO_LOCATION = @Location
			AND WO_PROCESS = @ProcessFlow
	) IF (@OperSequence > @SPNCurrentSeqForTheLot)
	OR (@SPNCurrentSeqForTheLot IS NULL) BEGIN
SET
	@Result = 0
END
ELSE
SET
	@Result = -1
END
ELSE
SET
	@Result = -1
END
GO