﻿USE [FabApprovalSystem]
GO
	/****** Object:  UserDefinedFunction [dbo].[fn_GetLTWorkRequests]    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_GetLTWorkRequests] () RETURNS TABLE AS RETURN (
		-- Add the SELECT statement with parameter references here
		-- M_Suffix
		SELECT
			DISTINCT 'LotTraveler' AS DocumentType,
			'LotTraveler' AS SubDoc,
			W.SWRNumber AS IssueID,
			W.ID AS DocID,
			W.OriginatedDate AS IssueDate,
			W.LotNumber AS LotNos,
			pdg.Names AS 'PendingApprovers',
			Title,
			PurposeOfRequest,
			U.FirstName + ' ' + U.LastName AS Originator,
			SubmitedDate,
			CloseDate
		FROM
			LTWorkRequest W
			LEFT JOIN Users U ON W.OriginatorID = U.UserID
			LEFT JOIN (
				SELECT
					DISTINCT W.ID,
					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
								DocumentTypeID = 6
								AND A.IssueID = W.ID
								AND ItemStatus = 0 FOR XML PATH('')
						),
						1,
						1,
						''
					) AS Names
				FROM
					LTWorkRequest W
			) AS pdg ON W.ID = pdg.ID
		WHERE
			IsCurrentRevision = 1
	)
GO