﻿USE [FabApprovalSystem]
GO
	/****** Object:  StoredProcedure [dbo].[ECNGetECN_TECNPendingApprovalsByOriginator]    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].[ECNGetECN_TECNPendingApprovalsByOriginator] -- Add the parameters for the stored procedure here
	@UserID INT AS BEGIN -- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
SET
	NOCOUNT ON;

-- Insert statements for procedure here
SELECT
	DISTINCT 'ECN' AS DocumentType,
	CASE
		WHEN E.IsECN = 1 THEN 'ECN'
		WHEN E.IsTECN = 1 THEN 'TECN'
		WHEN E.IsEmergencyTECN = 1 THEN 'E-TECN'
		ELSE 'ECN'
	END AS SubDoc,
	E.ECNNumber AS IssueID,
	E.ECNNumber AS DocID,
	'Originator' AS RoleName,
	IssueDate,
	'' AS LotNos,
	ISNULL(pdg.Names, '') AS 'PendingApprovers',
	Title,
	DescriptionOfChange AS IssueDescription,
	U1.FirstName + ' ' + U1.LastName AS Originator,
	SubmitedDate,
	CloseDate
FROM
	ECN E
	INNER JOIN Users U1 ON E.OriginatorID = U1.UserID
	LEFT JOIN Approval AP ON E.ECNNumber = AP.IssueID
	LEFT JOIN (
		SELECT
			DISTINCT E.ECNNumber AS IssueID,
			STUFF (
				(
					SELECT
						'/' + CAST(U.FirstName AS varchar(50)) + ' ' + CAST(U.LastName AS varchar(50)) + '(' + A.RoleName + ')'
					FROM
						Approval A
						INNER JOIN Users U ON A.UserID = U.UserID
					WHERE
						(
							A.DocumentTypeID = 3
							OR A.DocumentTypeID = 4
							OR A.DocumentTypeID = 5
						)
						AND A.IssueID = E.ECNNumber
						AND ItemStatus = 0 FOR XML PATH('')
				),
				1,
				1,
				''
			) AS Names
		FROM
			ECN E
	) AS pdg ON E.ECNNumber = pdg.IssueID
WHERE
	E.OriginatorID = @UserID
	AND CloseDate IS NULL
	AND SubmitedDate IS NOT NULL
	AND Deleted = 0
END
GO