﻿USE [FabApprovalSystem]
GO
	/****** Object:  StoredProcedure [dbo].[MRBSubmitForApproval]    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].[MRBSubmitForApproval] @MRBNumber INT,
	@UserID INT,
	@DocumentTypeID INT,
	@SubRoleCategoriesClause VARCHAR(1000),
	@AppoverCount INT OUT AS BEGIN -- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
SET
	NOCOUNT ON;

CREATE TABLE #TempApprovals (
[IssueID] [int] NULL,
[RoleName] [nvarchar](50) NULL,
[SubRole] [nvarchar](50) NOT NULL,
[UserID] [int] NOT NULL,
[SubRoleID] [int] NOT NULL,
[ItemStatus] [int] NULL,
[Step] [int] NULL,
[NotifyDate] [datetime] NULL,
[AssignedDate] [datetime] NULL,
[RoleAssignedDate] [datetime] NULL,
[ApprovalType] [tinyint] NULL
) DECLARE @CurrentDate DATETIME
SET
	@CurrentDate = GETDATE() DECLARE @WorkFlowNumber INT
SELECT
	@WorkFlowNumber = WorkFlowNumber
FROM
	MRB
WHERE
	MRBNumber = @MRBNumber
UPDATE
	MRB
SET
	CurrentStep = 1,
	SubmitedDate = GETDATE()
WHERE
	MRBNumber = @MRBNumber -- make sure to delete any existing approval items before sumbitting/re-submitting an issue
DELETE FROM
	Approval
WHERE
	IssueID = @MRBNumber
	AND DocumentTypeID = @DocumentTypeID -- UPDATE THE APPROVAL LOG
INSERT INTO
	ApprovalLog (
		IssueID,
		UserID,
		OperationType,
		OperationLog,
		DocumentTypeID
	)
VALUES
	(
		@MRBNumber,
		@UserID,
		'Submit',
		'Submitted the document',
		@DocumentTypeID
	) -- UPDATE THE APPROVAL LOG for a system initiated transaction
INSERT INTO
	ApprovalLog (
		IssueID,
		UserID,
		OperationType,
		OperationLog,
		DocumentTypeID
	)
VALUES
	(
		@MRBNumber,
		@UserID,
		'Delete',
		'Delete Existing Approval',
		@DocumentTypeID
	) DECLARE @RHCount INT DECLARE @CheckForITARCompliant INT
SET
	@RHCount = 1 IF @RHCount > 0
SET
	@CheckForITARCompliant = 1
	ELSE
SET
	@CheckForITARCompliant = 0
INSERT INTO
	#TempApprovals
	(
		IssueID,
		RoleName,
		SubRole,
		UserID,
		SubRoleID,
		ItemStatus,
		Step,
		AssignedDate,
		NotifyDate,
		RoleAssignedDate,
		ApprovalType
	) EXEC GetRoles @WorkflowStepNumber = 1,
	@WhereClause = @SubRoleCategoriesClause,
	@CheckForITARCompliant = @CheckForITARCompliant,
	@DocumentTypeID = @DocumentTypeID,
	@IssueID = @MRBNumber,
	@WorkFlowNumber = @WorkFlowNumber
SET
	@AppoverCount = (
		SELECT
			COUNT(*)
		FROM
			#TempApprovals)
			IF @AppoverCount > 0 BEGIN -- INSEERT INTO THE ACTUAL TABLE
		INSERT INTO
			Approval (
				IssueID,
				RoleName,
				SubRole,
				UserID,
				SubRoleID,
				ItemStatus,
				Step,
				AssignedDate,
				NotifyDate,
				RoleAssignedDate,
				ApprovalType,
				DocumentTypeID
			) (
				SELECT
					DISTINCT *,
					@DocumentTypeID AS DocumentTypeID
				FROM
					#TempApprovals)
			END DROP TABLE #TempApprovals
	END
GO