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

DECLARE @ParentECNNumber INT;

DECLARE @SuperParentECNNumber INT;

SELECT
	@ParentECNNumber = ISNULL(ConvertedFromNumber, -1)
FROM
	ECN
WHERE
	ECNNumber = @ECNNumber;

IF @ParentECNNumber <> -1 -- If the current document is an ECN and was converted from E-TECN -> TECN -> ECN
BEGIN
SELECT
	@SuperParentECNNumber = ISNULL(ConvertedFromNumber, -1)
FROM
	ECN
WHERE
	ECNNumber = @ParentECNNumber;

END
SELECT
	A.ApprovalLogID,
	U.FirstName + ' ' + U.LastName AS FullName,
	A.OperationType Operation,
	ISNULL(SRC.SubRoleCategoryItem, 'N/A') AS SubRole,
	LogDateTime AS OperationTime,
	A.Comments
FROM
	ApprovalLog A
	INNER JOIN Users U ON A.UserID = U.UserID
	LEFT JOIN SubRole SR ON A.SubRoleID = SR.SubRoleID
	LEFT JOIN SubRoleCategory SRC ON SR.SubRoleCategoryID = SRC.SubRoleCategoryID
WHERE
	(
		OperationType = 'Approved'
		OR OperationType = 'Recalled'
		OR OperationType LIKE '%Denied%'
		OR OperationType LIKE '%CHANGE%'
		OR OperationType LIKE '%Cancel%'
		OR OperationType LIKE '%Expir%'
		OR OperationType LIKE '%Convert%'
		OR OperationType LIKE '%initiated%'
		OR OperationType LIKE '%eject%'
	)
	AND (
		IssueID = @ECNNumber
		OR IssueID = @ParentECNNumber
		OR IssueID = @SuperParentECNNumber
	)
	AND (
		DocumentTypeID = 3
		OR DocumentTypeID = 4
		OR DocumentTypeID = 5
	)
ORDER By
	LogDateTime DESC
END
GO