﻿USE [FabApprovalSystem]
GO
	/****** Object:  StoredProcedure [dbo].[ECNGetAllTECN]    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].[ECNGetAllTECN] 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,
	IssueDate,
	'' AS LotNos,
	ISNULL(pdg.Names, '') AS 'PendingApprovers',
	Title,
	DescriptionOfChange AS IssueDescription,
	U1.FirstName + ' ' + U1.LastName AS Originator,
	SubmitedDate,
	CloseDate,
	ExtensionDate,
	CASE
		WHEN ExtensionDate IS NOT NULL THEN ExtensionDate
		WHEN ExtensionDate IS NULL then ExpirationDate
		ELSE NULL
	END AS 'ExpirationDate'
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))
					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.IsTECN = 1
		OR E.IsEmergencyTECN = 1
	)
	AND CloseDate IS NOT NULL
	AND CancellationApproved = 0
	AND Deleted = 0
	AND CancellationDate IS NULL
	AND Cancelled = 0
	AND (
		GETDATE() <= ExpirationDate
		OR (
			GETDATE() >= ExpirationDate
			AND GETDATE() <= ExtensionDate
		)
	)
END
GO