﻿USE [FabApprovalSystem]
GO
	/****** Object:  StoredProcedure [dbo].[ECNInsertEmergencyECNApprovers_05012017]    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].[ECNInsertEmergencyECNApprovers_05012017] @ECNNumber INT,
	@Step INT,
	@UserID INT,
	@DocumentTypeID INT,
	@SubRoleCategoryName VARCHAR(100),
	@Email VARCHAR(20) OUTPUT AS BEGIN -- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
SET
	NOCOUNT ON;

DECLARE @RoleID INT DECLARE @RoleName VARCHAR(50) DECLARE @SubRoleID INT DECLARE @SubRoleName VARCHAR(50) DECLARE @ApprovalType TINYINT -- Get the approval type of the current step
SET
	@ApprovalType = (
		SELECT
			Top 1 WS.ApprovalType
		FROM
			SubRoleCategory SRC
			INNER JOIN SubRole SR ON SRC.SubRoleCategoryID = SR.SubRoleCategoryID
			INNER JOIN Role R ON SR.RoleID = R.RoleID
			INNER JOIN WorkflowSteps WS ON R.RoleID = WS.RoleID
			INNER JOIN Workflows W ON WS.WorkflowID = W.DocumentTypeID
		WHERE
			SRC.SubRoleCategoryItem = 'Engineering'
			AND W.DocumentTypeID = @DocumentTypeID
	)
SELECT
	Top 1 @ApprovalType = WS.ApprovalType,
	@RoleID = R.RoleID,
	@RoleName = R.RoleName,
	@SubRoleID = SR.SubRoleID,
	@SubRoleName = SR.SubRole
FROM
	SubRoleCategory SRC
	INNER JOIN SubRole SR ON SRC.SubRoleCategoryID = SR.SubRoleCategoryID
	INNER JOIN Role R ON SR.RoleID = R.RoleID
	INNER JOIN WorkflowSteps WS ON R.RoleID = WS.RoleID
	INNER JOIN Workflows W ON WS.WorkflowID = W.DocumentTypeID
WHERE
	SRC.SubRoleCategoryItem = @SubRoleCategoryName
	AND W.DocumentTypeID = @DocumentTypeID
INSERT INTO
	Approval (
		IssueID,
		RoleName,
		SubRole,
		UserID,
		SubRoleID,
		ItemStatus,
		Step,
		AssignedDate,
		NotifyDate,
		RoleAssignedDate,
		ApprovalType,
		DocumentTypeID
	)
VALUES
	(
		@ECNNumber,
		@RoleName,
		@SubRoleName,
		@UserID,
		@SubRoleID,
		0,
		@Step,
		GETDATE(),
		GETDATE(),
		GETDATE(),
		@ApprovalType,
		@DocumentTypeID
	)
SELECT
	@Email = Email
FROM
	Users
WHERE
	UserID = @UserID
END
GO