﻿USE [FabApprovalSystem]
GO
	/****** Object:  StoredProcedure [dbo].[UpdateApproval_05012017]    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].[UpdateApproval_05012017] @IssueID INT,
	@CurrentStep INT,
	@ItemStatus INT,
	@UserID INT,
	@Comments VARCHAR(1000),
	@SubRoleCategoriesClause VARCHAR(500),
	@DocumentTypeID INT,
	@LastStep BIT OUTPUT,
	@LastApproverInCurrentStep BIT OUTPUT AS BEGIN -- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
SET
	NOCOUNT ON;

DECLARE @ApprovalType INT DECLARE @MaxStep INT DECLARE @RemainingApprovers INT DECLARE @NewStep INT DECLARE @ApproverCountForThisStep INT DECLARE @SubRoleID INT
SET
	@ApprovalType = (
		SELECT
			DISTINCT ApprovalType
		FROM
			Approval
		WHERE
			IssueID = @IssueID
			AND UserID = @UserID
			AND Step = @CurrentStep
			AND DocumentTypeID = @DocumentTypeID
			AND ItemStatus = 0
	)
SET
	@LastStep = 0
SET
	@NewStep = @CurrentStep + 1 -- GET THE LAST STEP IN THE WORKFLOW
SELECT
	@MaxStep = (
		SELECT
			MAX(WS.WorkflowStepNumber)
		FROM
			DocumentType D
			INNER JOIN Workflows W ON D.DocumentTypeID = W.DocumentTypeID
			INNER JOIN WorkflowSteps WS ON WS.WorkflowID = W.WorkflowID
			AND D.DocumentTypeID = @DocumentTypeID
	) -- Get the SubRole ID of the Person Approving/Denying it							
SET
	@SubRoleID = (
		SELECT
			TOP 1 SubRoleID
		FROM
			Approval
		WHERE
			IssueID = @IssueID
			AND UserID = @UserID
			AND Step = @CurrentStep
			AND DocumentTypeID = @DocumentTypeID
	) DECLARE @OperationTypeString VARCHAR(50) IF EXISTS (
		SELECT
			*
		FROM
			ECN
		WHERE
			CancellationInProgress = 1
			AND ECNNumber = @IssueID
	)
SET
	@OperationTypeString = 'Cancellation Approved'
	ELSE IF EXISTS (
		SELECT
			*
		FROM
			ECN
		WHERE
			ExpirationInProgress = 1
			AND ECNNumber = @IssueID
	)
SET
	@OperationTypeString = 'Expiration Approved'
	ELSE
SET
	@OperationTypeString = 'Approved' IF @ItemStatus = 1 -- Approve
	BEGIN
UPDATE
	Approval
SET
	ItemStatus = 1,
	CompletedDate = GETDATE(),
	Comments = @Comments
WHERE
	IssueID = @IssueID
	AND UserID = @UserID
	AND Step = @CurrentStep
	AND DocumentTypeID = @DocumentTypeID
	AND CompletedDate IS NULL IF @ @ROWCOUNT > 0 BEGIN -- UPDATE THE APPROVAL LOG
INSERT INTO
	ApprovalLog (
		IssueID,
		UserID,
		SubRoleID,
		OperationType,
		OperationLog,
		DocumentTypeID
	)
VALUES
	(
		@IssueID,
		@UserID,
		@SubRoleID,
		@OperationTypeString,
		'Approved at step ' + CONVERT(NCHAR(10), @CurrentStep),
		@DocumentTypeID
	)
END IF @ApprovalType = 2 -- ONLY ONE APPROVER PER SUBROLE IS REQUIRED FOR THIS STEP
BEGIN ---- Get the SubRole ID of the Person Approving it
-- Because Only approver is required to approve per SubRole
-- Selete rest the approvers for the SubRoles bellonging to the this approver
DELETE FROM
	Approval
WHERE
	IssueID = @IssueID
	AND UserID <> @UserID
	AND Step = @CurrentStep
	AND DocumentTypeID = @DocumentTypeID
	AND SubRoleID = @SubRoleID -- UPDATE THE APPROVAL LOG
INSERT INTO
	ApprovalLog (
		IssueID,
		UserID,
		SubRoleID,
		OperationType,
		OperationLog,
		DocumentTypeID
	)
VALUES
	(
		@IssueID,
		@UserID,
		@SubRoleID,
		'Delete',
		'Delete approvers for step ' + CONVERT(NCHAR(10), @CurrentStep) + ' for SubRoleID ' + CONVERT(NCHAR(10), @SubRoleID),
		@DocumentTypeID
	) --  Check if there are any pending approvals
SET
	@RemainingApprovers = (
		SELECT
			COUNT(*)
		FROM
			Approval
		WHERE
			IssueID = @IssueID
			AND Step = @CurrentStep
			AND ItemStatus = 0
			AND DocumentTypeID = @DocumentTypeID
	) -- if there are no more approvers in this step then proceed to next step
	IF @RemainingApprovers = 0 BEGIN IF @MaxStep > @CurrentStep -- there are some steps remaining
	BEGIN
SET
	@LastStep = 0 IF @DocumentTypeID = 1 -- Lot Disposition
	BEGIN
UPDATE
	LotDisposition
SET
	CurrentStep = @NewStep
WHERE
	IssueID = @IssueID
END
ELSE IF @DocumentTypeID = 2 -- MRB
BEGIN
UPDATE
	MRB
SET
	CurrentStep = @NewStep
WHERE
	MRBNumber = @IssueID
END
ELSE IF @DocumentTypeID = 3
OR @DocumentTypeID = 4
OR @DocumentTypeID = 5 -- ECN
BEGIN
UPDATE
	ECN
SET
	CurrentStep = @NewStep
WHERE
	ECNNumber = @IssueID
END
ELSE IF @DocumentTypeID = 6 -- LotTraveler
BEGIN
UPDATE
	LTWorkRequest
SET
	CurrentStep = @NewStep
WHERE
	ID = @IssueID
END -- proceed to the next
EXEC InsertApprovers @IssueID,
@NewStep,
@DocumentTypeID,
@SubRoleCategoriesClause,
@ApproverCountForThisStep -- UPDATE THE APPROVAL LOG
INSERT INTO
	ApprovalLog (
		IssueID,
		UserID,
		SubRoleID,
		OperationType,
		OperationLog,
		DocumentTypeID
	)
VALUES
	(
		@IssueID,
		@UserID,
		@SubRoleID,
		'Insert',
		'Insert approvers for step ' + CONVERT(NCHAR(10), @NewStep),
		@DocumentTypeID
	) IF @ApproverCountForThisStep = 0 BEGIN
SET
	@LastApproverInCurrentStep = 1 RETURN;

END
END
ELSE BEGIN -- It was the last step, close the document
SET
	@LastStep = 1 IF @DocumentTypeID = 1 BEGIN
UPDATE
	LotDisposition
SET
	CloseDate = GETDATE()
WHERE
	IssueID = @IssueID
END
ELSE IF @DocumentTypeID = 2 BEGIN
UPDATE
	MRB
SET
	ApprovalDate = GETDATE(),
	ApprovalStatus = 1
WHERE
	MRBNumber = @IssueID
END
ELSE IF @DocumentTypeID = 3
OR @DocumentTypeID = 4
OR @DocumentTypeID = 5 BEGIN IF EXISTS (
	SELECT
		*
	FROM
		ECN
	WHERE
		CancellationInProgress = 1
		AND ECNNumber = @IssueID
) BEGIN
UPDATE
	ECN
SET
	CancellationInProgress = 0,
	CancellationApproved = 1,
	CancellationApprovalDate = GETDATE()
WHERE
	ECNNumber = @IssueID
INSERT INTO
	ApprovalLog (
		IssueID,
		UserID,
		SubRoleID,
		OperationType,
		OperationLog,
		DocumentTypeID
	)
VALUES
	(
		@IssueID,
		@UserID,
		@SubRoleID,
		'Cancelled',
		'Document closed',
		@DocumentTypeID
	)
END
ELSE IF EXISTS (
	SELECT
		*
	FROM
		ECN
	WHERE
		ExpirationInProgress = 1
		AND ECNNumber = @IssueID
) BEGIN
UPDATE
	ECN
SET
	ExpirationInProgress = 0,
	ExpirationProcessed = 1,
	ExpirationProcessedlDate = GETDATE()
WHERE
	ECNNumber = @IssueID
INSERT INTO
	ApprovalLog (
		IssueID,
		UserID,
		SubRoleID,
		OperationType,
		OperationLog,
		DocumentTypeID
	)
VALUES
	(
		@IssueID,
		@UserID,
		@SubRoleID,
		'Expired',
		'Document closed',
		@DocumentTypeID
	)
END
ELSE BEGIN
UPDATE
	ECN
SET
	CloseDate = GETDATE(),
	TECNExtensionState = 0
WHERE
	ECNNumber = @IssueID
END
END
ELSE IF @DocumentTypeID = 6 BEGIN
UPDATE
	LTWorkRequest
SET
	CloseDate = GETDATE(),
	Status = 1
WHERE
	ID = @IssueID
END -- UPDATE THE APPROVAL LOG
INSERT INTO
	ApprovalLog (
		IssueID,
		UserID,
		SubRoleID,
		OperationType,
		OperationLog,
		DocumentTypeID
	)
VALUES
	(
		@IssueID,
		@UserID,
		@SubRoleID,
		'Last Step',
		'Document closed',
		@DocumentTypeID
	)
END
SET
	@LastApproverInCurrentStep = 1
END
ELSE BEGIN
SET
	@LastApproverInCurrentStep = 0
END
END
ELSE -- ALL THE APPROVERS ARE REQUIRED TO APPROVE FOR THIS STEP
BEGIN --  Check if there are any pending approvals
SET
	@RemainingApprovers = (
		SELECT
			COUNT(*)
		FROM
			Approval
		WHERE
			IssueID = @IssueID
			AND Step = @CurrentStep
			AND ItemStatus = 0
			AND DocumentTypeID = @DocumentTypeID
	) -- if there are no more approvers in this step then proceed to next step
	IF @RemainingApprovers = 0 BEGIN IF @MaxStep > @CurrentStep -- there are some steps remaining
	BEGIN
SET
	@LastStep = 0 IF @DocumentTypeID = 1 BEGIN
UPDATE
	LotDisposition
SET
	CurrentStep = @NewStep
WHERE
	IssueID = @IssueID
END
ELSE IF @DocumentTypeID = 2 BEGIN
UPDATE
	MRB
SET
	CurrentStep = @NewStep
WHERE
	MRBNumber = @IssueID
END
ELSE IF @DocumentTypeID = 3
OR @DocumentTypeID = 4
OR @DocumentTypeID = 5 BEGIN
UPDATE
	ECN
SET
	CurrentStep = @NewStep
WHERE
	ECNNumber = @IssueID
END
ELSE IF @DocumentTypeID = 6 BEGIN
UPDATE
	LTWorkRequest
SET
	CurrentStep = @NewStep
WHERE
	ID = @IssueID
END -- UPDATE THE APPROVAL LOG
INSERT INTO
	ApprovalLog (
		IssueID,
		UserID,
		SubRoleID,
		OperationType,
		OperationLog,
		DocumentTypeID
	)
VALUES
	(
		@IssueID,
		@UserID,
		@SubRoleID,
		'Update',
		'Update Document with the new step ' + CONVERT(NCHAR(10), @NewStep),
		@DocumentTypeID
	) -- proceed to the next step
SET
	@LastApproverInCurrentStep = 1 EXEC InsertApprovers @IssueID,
	@NewStep,
	@DocumentTypeID,
	@SubRoleCategoriesClause,
	@ApproverCountForThisStep -- UPDATE THE APPROVAL LOG
INSERT INTO
	ApprovalLog (
		IssueID,
		UserID,
		SubRoleID,
		OperationType,
		OperationLog,
		DocumentTypeID
	)
VALUES
	(
		@IssueID,
		@UserID,
		@SubRoleID,
		'Insert',
		'Insert approvers for step ' + CONVERT(NCHAR(10), @NewStep),
		@DocumentTypeID
	) IF @ApproverCountForThisStep = 0 BEGIN
SET
	@LastApproverInCurrentStep = 1 RETURN;

END
END
ELSE BEGIN -- It was the last step, close the document
SET
	@LastStep = 1
SET
	@LastApproverInCurrentStep = 1 IF @DocumentTypeID = 1 BEGIN
UPDATE
	LotDisposition
SET
	CloseDate = GETDATE()
WHERE
	IssueID = @IssueID
END
ELSE IF @DocumentTypeID = 2 BEGIN
UPDATE
	MRB
SET
	ApprovalDate = GETDATE(),
	ApprovalStatus = 1
WHERE
	MRBNumber = @IssueID
END
ELSE IF @DocumentTypeID = 3
OR @DocumentTypeID = 4
OR @DocumentTypeID = 5 BEGIN IF EXISTS (
	SELECT
		*
	FROM
		ECN
	WHERE
		CancellationInProgress = 1
		AND ECNNumber = @IssueID
) BEGIN
UPDATE
	ECN
SET
	CancellationInProgress = 0,
	CancellationApproved = 1,
	CancellationApprovalDate = GETDATE()
WHERE
	ECNNumber = @IssueID
INSERT INTO
	ApprovalLog (
		IssueID,
		UserID,
		SubRoleID,
		OperationType,
		OperationLog,
		DocumentTypeID
	)
VALUES
	(
		@IssueID,
		@UserID,
		@SubRoleID,
		'Cancelled',
		'Document closed',
		@DocumentTypeID
	)
END
ELSE IF EXISTS (
	SELECT
		*
	FROM
		ECN
	WHERE
		ExpirationInProgress = 1
		AND ECNNumber = @IssueID
) BEGIN
UPDATE
	ECN
SET
	ExpirationInProgress = 0,
	ExpirationProcessed = 1,
	ExpirationProcessedlDate = GETDATE()
WHERE
	ECNNumber = @IssueID
INSERT INTO
	ApprovalLog (
		IssueID,
		UserID,
		SubRoleID,
		OperationType,
		OperationLog,
		DocumentTypeID
	)
VALUES
	(
		@IssueID,
		@UserID,
		@SubRoleID,
		'Expired',
		'Document closed',
		@DocumentTypeID
	)
END
ELSE BEGIN
UPDATE
	ECN
SET
	CloseDate = GETDATE(),
	TECNExtensionState = 0
WHERE
	ECNNumber = @IssueID
END
END
ELSE IF @DocumentTypeID = 6 BEGIN
UPDATE
	LTWorkRequest
SET
	CloseDate = GETDATE(),
	Status = 1
WHERE
	ID = @IssueID
END -- UPDATE THE APPROVAL LOG
INSERT INTO
	ApprovalLog (
		IssueID,
		UserID,
		SubRoleID,
		OperationType,
		OperationLog,
		DocumentTypeID
	)
VALUES
	(
		@IssueID,
		@UserID,
		@SubRoleID,
		'Last Step',
		'Document closed',
		@DocumentTypeID
	)
END
END
ELSE BEGIN
SET
	@LastApproverInCurrentStep = 0
END
END
END
ELSE IF @ItemStatus = 2 -- denied
BEGIN
SET
	@LastStep = 0
SET
	@LastApproverInCurrentStep = 0 -- begin from step 1
UPDATE
	Approval
SET
	ItemStatus = 2,
	CompletedDate = NULL,
	Comments = @Comments
WHERE
	IssueID = @IssueID
	AND UserID = @UserID
	AND Step = @CurrentStep
	AND DocumentTypeID = @DocumentTypeID -- UPDATE THE APPROVAL LOG
INSERT INTO
	ApprovalLog (
		IssueID,
		UserID,
		SubRoleID,
		OperationType,
		OperationLog,
		DocumentTypeID
	)
VALUES
	(
		@IssueID,
		@UserID,
		@SubRoleID,
		'Denied',
		'Denied at step ' + CONVERT(NCHAR(10), @CurrentStep),
		@DocumentTypeID
	) -- get the approvalid of the rejected record, 
	-- as this is the only record which needs to be retained for this issue
	-- this retained record will be deleted when the issue is re-submitted
	DECLARE @ApprovalID INT
SELECT
	@ApprovalID = (
		SELECT
			MAX(ApprovalID)
		FROM
			Approval
		WHERE
			IssueID = @IssueID
			AND UserID = @UserID
			AND Step = @CurrentStep
			AND DocumentTypeID = @DocumentTypeID
	) IF @ApprovalID IS NOT NULL -- do not process, if an invalid approver has processed it
	BEGIN -- delete all the other approvers record for the issue for the current step
DELETE FROM
	Approval
WHERE
	(
		IssueID = @IssueID
		AND ApprovalID <> @ApprovalID
		AND DocumentTypeID = @DocumentTypeID
	) -- If the document is denied and the originator of the document belongs to "Probe" Subrole at the "Execution" step
	-- make sure the that the document appears in the task list of the other users under the "Probe" Subrole
	-- so that the other users under the "Probe" subrole know that the document needs to be re-submitted
	-- this feature is needed becaue the users under the "Probe" subrole work on shifts.
	DECLARE @OriginatorUserID INT -- get the originator ID	
	IF @DocumentTypeID = 1 BEGIN
SELECT
	@OriginatorUserID = USR.UserID
FROM
	LotDisposition LD
	INNER JOIN UserSubRole USR ON LD.OriginatorID = USR.UserID
	INNER JOIN SubRole SR ON USR.SubRoleID = SR.SubRoleID
	INNER JOIN SubRoleCategory SRC ON SR.SubRoleCategoryID = SRC.SubRoleCategoryID
WHERE
	(
		SRC.SubRoleCategoryItem = 'Probe'
		OR SRC.SubRoleCategoryItem = 'Fab'
	)
	AND LD.IssueID = @IssueID
END IF NOT @OriginatorUserID IS NULL BEGIN -- Add the remaiming users from the "Probe" into the "Approval", 
-- so that it appears in the Task List of the Users in the "Probe" Subrole
INSERT INTO
	Approval (
		A.IssueID,
		A.RoleName,
		A.SubRole,
		B.UserID,
		A.SubRoleID,
		A.ItemStatus,
		A.Step,
		A.NotifyDate,
		A.AssignedDate,
		A.RoleAssignedDate,
		A.CompletedDate,
		Comments,
		ApprovalType,
		A.DocumentTypeID,
		DisplayDeniedDocument
	)
SELECT
	A.IssueID,
	B.RoleName,
	B.SubRoleCategoryItem,
	B.UserID,
	A.SubRoleID,
	A.ItemStatus,
	A.Step,
	A.NotifyDate,
	A.AssignedDate,
	A.RoleAssignedDate,
	A.CompletedDate,
	'Denied' AS 'Comments',
	ApprovalType,
	A.DocumentTypeID,
	1
FROM
	(
		SELECT
			*
		FROM
			Approval
		WHERE
			ApprovalID = @ApprovalID
	) AS A
	INNER JOIN (
		SELECT
			@ApprovalID AS ApprovalID,
			USR.UserID,
			SRC.SubRoleCategoryItem,
			R.RoleName
		FROM
			UserSubRole USR
			INNER JOIN SubRole SR ON USR.SubRoleID = SR.SubRoleID
			INNER JOIN SubRoleCategory SRC ON SR.SubRoleCategoryID = SRC.SubRoleCategoryID
			INNER JOIN Role R ON SR.RoleID = R.RoleID
		WHERE
			SRC.SubRoleCategoryItem = 'Probe'
			AND USR.UserID <> @OriginatorUserID
	) AS B ON A.ApprovalID = B.ApprovalID
INSERT INTO
	ApprovalLog (
		IssueID,
		UserID,
		SubRoleID,
		OperationType,
		OperationLog,
		DocumentTypeID
	)
VALUES
	(
		@IssueID,
		@UserID,
		@SubRoleID,
		'Delete',
		'Delete all the other approvals add other users from the Probe "SubRole" the denied one',
		@DocumentTypeID
	)
END
ELSE BEGIN -- UPDATE THE APPROVAL LOG
INSERT INTO
	ApprovalLog (
		IssueID,
		UserID,
		SubRoleID,
		OperationType,
		OperationLog,
		DocumentTypeID
	)
VALUES
	(
		@IssueID,
		@UserID,
		@SubRoleID,
		'Delete',
		'Delete all the other approvals except the denied one',
		@DocumentTypeID
	)
END -- Update LotDisposition Item to begining of the workflow loop
IF @DocumentTypeID = 1
UPDATE
	LotDisposition
SET
	CurrentStep = 0,
	SubmitedDate = NULL
WHERE
	IssueID = @IssueID
	ELSE IF @DocumentTypeID = 2
UPDATE
	MRB
SET
	CurrentStep = 0,
	SubmitedDate = NULL
WHERE
	MRBNumber = @IssueID
	ELSE IF @DocumentTypeID = 3
	OR @DocumentTypeID = 4
	OR @DocumentTypeID = 5
UPDATE
	ECN
SET
	CurrentStep = 0,
	SubmitedDate = NULL
WHERE
	ECNNumber = @IssueID
	ELSE IF @DocumentTypeID = 6
UPDATE
	LTWorkRequest
SET
	CurrentStep = 0,
	SubmitedDate = NULL
WHERE
	ID = @IssueID -- UPDATE THE APPROVAL LOG
INSERT INTO
	ApprovalLog (
		IssueID,
		UserID,
		SubRoleID,
		OperationType,
		OperationLog,
		DocumentTypeID
	)
VALUES
	(
		@IssueID,
		@UserID,
		@SubRoleID,
		'Update',
		'Update the document to step 0',
		@DocumentTypeID
	)
END
END
END
GO