﻿USE [FabApprovalSystem]
GO
	/****** Object:  StoredProcedure [dbo].[ECNApproveCancelDocument]    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].[ECNApproveCancelDocument] -- Add the parameters for the stored procedure here
	@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.
	DECLARE @ApprovalType INT DECLARE @MaxStep INT DECLARE @RemainingApprovers INT DECLARE @NewStep INT DECLARE @ApproverCountForThisStep INT DECLARE @SubRoleID INT
SET
	@NewStep = @CurrentStep + 1
SET
	@SubRoleID = (
		SELECT
			TOP 1 SubRoleID
		FROM
			Approval
		WHERE
			IssueID = @IssueID
			AND UserID = @UserID
			AND Step = @CurrentStep
			AND DocumentTypeID = @DocumentTypeID
	) 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
INSERT INTO
	ApprovalLog (
		IssueID,
		UserID,
		SubRoleID,
		OperationType,
		OperationLog,
		DocumentTypeID
	)
VALUES
	(
		@IssueID,
		@UserID,
		@SubRoleID,
		'Approved Cancellation',
		'Approved at step ' + CONVERT(NCHAR(10), @CurrentStep),
		@DocumentTypeID
	)
END
SET
	@RemainingApprovers = (
		SELECT
			COUNT(*)
		FROM
			Approval
		WHERE
			IssueID = @IssueID
			AND Step = @CurrentStep
			AND ItemStatus = 0
			AND DocumentTypeID = @DocumentTypeID
	) IF @RemainingApprovers = 0 BEGIN
SET
	@LastStep = 1
UPDATE
	ECN
SET
	CancellationDate = GETDATE(),
	Cancelled = 1,
	CancellationInProgress = 0
WHERE
	ECNNumber = @IssueID -- UPDATE THE APPROVAL LOG
INSERT INTO
	ApprovalLog (
		IssueID,
		UserID,
		SubRoleID,
		OperationType,
		OperationLog,
		DocumentTypeID
	)
VALUES
	(
		@IssueID,
		@UserID,
		@SubRoleID,
		'Cancelled',
		'Cancelled document',
		@DocumentTypeID
	)
END
ELSE BEGIN
SET
	@LastApproverInCurrentStep = 0
END
END
END
GO