sozsoft-platform/configs/seeds/sql/object/Prc_P_MaterialRequestPlanSuggest.sql
2026-10-14 12:07:11 +03:00

52 lines
2.2 KiB
Transact-SQL
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

-- Planla diyaloğunun Öner'i (App.Prc.MaterialRequestPlanLine › InsertCommand):
-- kalemin taslak planını sıfırlayıp planlanacak kalanı dağıtır. Önce stok: teslim konumu (stoktan karşılama), sonra serbest stoğu en çok
-- olan konum (Prc_V_MaterialRequestPlanSource); kalan kısım satınalma: Prc_V_MaterialRequestPlanVendor'ın SuggestRank'ı ilk olan,
-- fiyat listesinde ya da alım geçmişinde bulunan tedarikçi (hiç bilinmeyen kontak seçilmez, kalan planlanmadan kalır). Satırlar
-- Prc_P_MaterialRequestPlanLineSave ile yazılır; kalem, stok ve kalan kuralları oradadır.
CREATE OR ALTER PROCEDURE [dbo].[Prc_P_MaterialRequestPlanSuggest]
@Id uniqueidentifier,
@TenantId uniqueidentifier,
@LastModifierId uniqueidentifier
AS
BEGIN
SET NOCOUNT ON;
SET XACT_ABORT ON;
DECLARE @Left decimal(18, 4), @Qty decimal(18, 4), @Free decimal(18, 4), @Key nvarchar(80);
BEGIN TRANSACTION;
DELETE FROM Prc_T_MaterialRequestPlanLine
WHERE MaterialRequestItemId = @Id AND (TenantId = @TenantId OR (TenantId IS NULL AND @TenantId IS NULL));
SELECT @Left = ISNULL(RemainingQuantity, 0) FROM Prc_V_MaterialRequestItemPlan WHERE Id = @Id;
DECLARE sources CURSOR LOCAL FAST_FORWARD FOR
SELECT Id, FreeQuantity
FROM Prc_V_MaterialRequestPlanSource
WHERE BaseId = @Id AND FreeQuantity > 0
ORDER BY IsDestination DESC, FreeQuantity DESC;
OPEN sources;
FETCH NEXT FROM sources INTO @Key, @Free;
WHILE @@FETCH_STATUS = 0 AND @Left > 0
BEGIN
SET @Qty = CASE WHEN @Free < @Left THEN @Free ELSE @Left END;
EXEC Prc_P_MaterialRequestPlanLineSave @Key, 'Transfer', @Qty, @TenantId, @LastModifierId;
SET @Left = @Left - @Qty;
FETCH NEXT FROM sources INTO @Key, @Free;
END
CLOSE sources;
DEALLOCATE sources;
IF @Left > 0
BEGIN
SET @Key = NULL;
SELECT TOP 1 @Key = Id
FROM Prc_V_MaterialRequestPlanVendor
WHERE BaseId = @Id AND (Price IS NOT NULL OR LastPurchaseDate IS NOT NULL)
ORDER BY SuggestRank;
IF @Key IS NOT NULL
EXEC Prc_P_MaterialRequestPlanLineSave @Key, 'Purchase', @Left, @TenantId, @LastModifierId;
END
COMMIT TRANSACTION;
END
GO