﻿USE [FabApprovalSystem]
GO
    /****** Object:  UserDefinedFunction [dbo].[fn_GetLotDispositions]    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_GetLotDispositions] () RETURNS TABLE AS RETURN (
        -- Add the SELECT statement with parameter references here
        -- M_Suffix
        SELECT
            'LotDisposition' AS DocumentType,
            'LotDisposition' AS SubDoc,
            LD.IssueID,
            LD.IssueID AS DocID,
            IssueDate,
            SQ.LotNo AS LotNos,
            pdg.Names AS 'PendingApprovers',
            Title,
            IssueDescription,
            U.FirstName + ' ' + U.LastName AS Originator,
            SubmitedDate,
            CloseDate
        FROM
            LotDisposition LD
            LEFT JOIN Users U ON LD.OriginatorID = U.UserID
            LEFT JOIN (
                SELECT
                    DISTINCT LD.IssueID,
                    STUFF (
                        (
                            SELECT
                                '/' + CAST(L.LotNumber AS varchar(512))
                            FROM
                                Lot L
                            WHERE
                                L.IssueID = LD.IssueID FOR XML PATH('')
                        ),
                        1,
                        1,
                        ''
                    ) AS LotNo
                FROM
                    LotDisposition LD
            ) AS SQ ON LD.IssueID = SQ.IssueID
            LEFT JOIN (
                SELECT
                    DISTINCT LD.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 = 1
                                AND A.IssueID = LD.IssueID
                                AND ItemStatus = 0 FOR XML PATH('')
                        ),
                        1,
                        1,
                        ''
                    ) AS Names
                FROM
                    LotDisposition LD
            ) AS pdg ON LD.IssueID = pdg.IssueID
    )
GO