﻿USE [FabApprovalSystem]
GO
    /****** Object:  StoredProcedure [dbo].[GetLotDispositions]    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].[GetLotDispositions] AS BEGIN -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
SET
    NOCOUNT ON;

SELECT
    LD.IssueID,
    IssueDate,
    SQ.LotNo AS LotNos,
    pdg.Names AS 'PendingApprovers',
    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))
                    FROM
                        Approval A
                        INNER JOIN Users U ON A.UserID = U.UserID
                    WHERE
                        A.DocumentTypeID = 1
                        AND A.IssueID = LD.IssueID
                        AND ItemStatus = 0
                        AND ItemStatus <> 2 FOR XML PATH('')
                ),
                1,
                1,
                ''
            ) AS Names
        FROM
            LotDisposition LD
    ) AS pdg ON LD.IssueID = pdg.IssueID
ORDER BY
    LD.IssueID DESC
END
GO