sozsoft-platform/configs/seeds/sql/object/Prc_P_PurchaseOrderImportRequest.sql
2026-10-11 17:01:11 +03:00

39 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.

CREATE OR ALTER PROCEDURE [dbo].[Prc_P_PurchaseOrderImportRequest]
@Id uniqueidentifier
AS
BEGIN
SET NOCOUNT ON;
DECLARE @Req uniqueidentifier, @Tenant uniqueidentifier, @Supplier uniqueidentifier, @Agr uniqueidentifier, @Status nvarchar(16), @Cnt int;
SELECT @Req = MaterialRequestId, @Tenant = TenantId, @Supplier = SupplierId, @Agr = AgreementId, @Status = Status
FROM Prc_T_PurchaseOrder WHERE Id = @Id;
IF @Req IS NULL RETURN;
IF @Status = 'Cancelled'
THROW 50101, N'İptal edilmiş belgeye talepten aktarım yapılamaz.', 1;
INSERT INTO Prc_T_PurchaseOrderLine (Id, TenantId, PurchaseOrderId, ProductId, Description, Quantity, UomId,
UnitPrice, TaxRate, Amount, MaterialRequestItemId, CreationTime, IsDeleted)
SELECT NEWID(), @Tenant, @Id, i.ProductId, i.RequestReason, i.Quantity, i.UomId,
COALESCE((SELECT TOP 1 al.UnitPrice FROM Prc_T_PurchaseAgreementLine al
WHERE al.AgreementId = @Agr AND al.ProductId = i.ProductId AND al.IsDeleted = 0),
(SELECT TOP 1 ps.Price FROM Inv_T_ProductSupplier ps
WHERE ps.ProductId = i.ProductId AND ps.ContactId = @Supplier AND ps.IsDeleted = 0
ORDER BY ps.MinQuantity), 0),
ISNULL(p.PurchaseTaxRate, 0), 0, i.Id, GETUTCDATE(), 0
FROM Prc_T_MaterialRequestItem i
INNER JOIN Prc_T_MaterialRequest r ON r.Id = i.MaterialRequestId
LEFT JOIN Inv_T_Product p ON p.Id = i.ProductId
WHERE i.MaterialRequestId = @Req AND i.IsDeleted = 0
AND r.ApprovalStatus = N'Onaylandı'
AND i.FulfillmentMethod = 'Purchase' AND i.LineStatus = 'Waiting'
AND NOT EXISTS (SELECT 1 FROM Prc_T_PurchaseOrderLine ol
INNER JOIN Prc_T_PurchaseOrder o ON o.Id = ol.PurchaseOrderId
WHERE ol.MaterialRequestItemId = i.Id AND ol.IsDeleted = 0
AND o.IsDeleted = 0 AND o.Status <> 'Cancelled');
SET @Cnt = @@ROWCOUNT;
UPDATE Prc_T_PurchaseOrder SET MaterialRequestId = NULL WHERE Id = @Id;
IF @Cnt = 0
THROW 50102, N'Seçilen talepte aktarılacak kalem yok (onaylı, Satınalma ile karşılanacak, bekleyen ve başka belgede olmayan kalem bulunamadı).', 1;
END