﻿USE [FabApprovalSystem]
GO
	/****** Object:  UserDefinedFunction [dbo].[fn_GetECNs]    Script Date: 11/21/2024 11:31:55 AM ******/
SET
	ANSI_NULLS ON
GO
SET
	QUOTED_IDENTIFIER ON
GO
	-- =============================================
	-- Author:		<Author,,Name>
	-- Create date: <Create Date,,>
	-- Description:	<Description,,>
	-- =============================================
	CREATE FUNCTION [dbo].[fn_GetECNs] () RETURNS TABLE AS RETURN (
		-- Add the SELECT statement with parameter references here
		-- M_Suffix
		SELECT
			'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,
			IssueDate,
			'' AS LotNos,
			pdg.Names AS 'PendingApprovers',
			Title,
			DescriptionOfChange AS IssueDescription,
			U.FirstName + ' ' + U.LastName AS Originator,
			SubmitedDate,
			CloseDate
		FROM
			ECN E
			LEFT JOIN Users U ON E.OriginatorID = U.UserID
			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
								)
								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.Deleted = 0
	)
GO