USE [phronCare_OperationsHub]
GO

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Procedure: PhLSM_Expedition_CheckStockItemConflicts
-- Module:    Logistics / Stock (PhLSM)
-- Purpose:   Detect serialized stock items already assigned
--            to active expeditions.
-- Author:    Leandro Rojas
-- Created:   2026-03-05
-- =============================================

ALTER PROCEDURE [dbo].[PhLSM_Expedition_CheckStockItemConflicts]
(
    @StockItemIds dbo.PhLSM_StockItemIdList READONLY,
    @IgnoreExpeditionId INT = NULL
)
AS
BEGIN
    SET NOCOUNT ON;

    SELECT
        d.stockitem_id       AS StockitemId,
        h.id                 AS ExpeditionId,
        h.expeditionnumber   AS Expeditionnumber,
        h.status             AS Status
    FROM dbo.PhLSM_ExpeditionDetails d
        INNER JOIN @StockItemIds ids
            ON ids.stockitem_id = d.stockitem_id
        INNER JOIN dbo.PhLSM_ExpeditionHeaders h
            ON h.id = d.expedition_id
        INNER JOIN dbo.PhLSM_StockItem si
            ON si.id = d.stockitem_id
    WHERE h.status NOT IN (5,6)   -- 5=Cerrada, 6=Anulada
      AND (@IgnoreExpeditionId IS NULL OR h.id <> @IgnoreExpeditionId)
      AND si.serial IS NOT NULL
      AND LTRIM(RTRIM(si.serial)) <> '';
END
GO