﻿USE [FabApprovalSystem]
GO
	/****** Object:  UserDefinedFunction [dbo].[fn_GetPRsByUser]    Script Date: 11/21/2024 11:31:55 AM ******/
SET
	ANSI_NULLS ON
GO
SET
	QUOTED_IDENTIFIER ON
GO
	CREATE FUNCTION [dbo].[fn_GetPRsByUser] (@UserID INT) RETURNS TABLE AS RETURN (
		SELECT
			DISTINCT 'PartsRequest' AS DocumentType,
			*
		FROM
			(
				SELECT
					'Parts Request' AS SubDoc,
					PR.PRNumber AS IssueID,
					PR.PRNumber AS DocID,
					CreateDate AS IssueDate,
					'' AS LotNos,
					dbo.fnGetApprovalFullNames(PR.PRNumber, 10, ' / ', 0, 1, 1, 0, 0) AS 'PendingApprovers',
					Title,
					Description AS IssueDescription,
					U1.FirstName + ' ' + U1.LastName AS Originator,
					SubmitDate AS SubmitedDate,
					CloseDate,
					A.ItemStatus,
					NULL AS NextDueDate
				FROM
					PartsRequest PR
					INNER JOIN Approval A ON A.IssueID = PR.PRNumber
					AND A.DocumentTypeID = 10 --INNER JOIN Users U2 ON PR.OriginatorID = U2.UserID 
					INNER JOIN Users U1 ON PR.RequestorID = U1.UserID
				WHERE
					(A.UserID = @UserID)
					AND (
						ItemStatus = 0
						OR (
							ItemStatus = 2
							AND DisplayDeniedDocument = 1
						)
					)
					AND CurrentStep >= 0
			) AS A
	)
GO