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

40 lines
2.3 KiB
PL/PgSQL
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 REPLACE PROCEDURE public."Prc_P_PurchaseOrderImportRequest"(p_id uuid)
LANGUAGE plpgsql AS $$
DECLARE v_req uuid; v_tenant uuid; v_supplier uuid; v_agr uuid; v_status varchar(16); v_cnt int;
BEGIN
SELECT "MaterialRequestId", "TenantId", "SupplierId", "AgreementId", "Status"
INTO v_req, v_tenant, v_supplier, v_agr, v_status
FROM "Prc_T_PurchaseOrder" WHERE "Id" = p_id;
IF v_req IS NULL THEN RETURN; END IF;
IF v_status = 'Cancelled' THEN
RAISE EXCEPTION 'İptal edilmiş belgeye talepten aktarım yapılamaz.';
END IF;
INSERT INTO "Prc_T_PurchaseOrderLine" ("Id", "TenantId", "PurchaseOrderId", "ProductId", "Description", "Quantity", "UomId",
"UnitPrice", "TaxRate", "Amount", "MaterialRequestItemId", "CreationTime", "IsDeleted")
SELECT gen_random_uuid(), v_tenant, p_id, i."ProductId", i."RequestReason", i."Quantity", i."UomId",
COALESCE((SELECT al."UnitPrice" FROM "Prc_T_PurchaseAgreementLine" al
WHERE al."AgreementId" = v_agr AND al."ProductId" = i."ProductId" AND al."IsDeleted" = false LIMIT 1),
(SELECT ps."Price" FROM "Inv_T_ProductSupplier" ps
WHERE ps."ProductId" = i."ProductId" AND ps."ContactId" = v_supplier AND ps."IsDeleted" = false
ORDER BY ps."MinQuantity" LIMIT 1), 0),
COALESCE(p."PurchaseTaxRate", 0), 0, i."Id", CURRENT_TIMESTAMP, false
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" = v_req AND i."IsDeleted" = false
AND r."ApprovalStatus" = '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" = false
AND o."IsDeleted" = false AND o."Status" <> 'Cancelled');
GET DIAGNOSTICS v_cnt = ROW_COUNT;
UPDATE "Prc_T_PurchaseOrder" SET "MaterialRequestId" = NULL WHERE "Id" = p_id;
IF v_cnt = 0 THEN
RAISE EXCEPTION 'Seçilen talepte aktarılacak kalem yok (onaylı, Satınalma ile karşılanacak, bekleyen ve başka belgede olmayan kalem bulunamadı).';
END IF;
END;
$$;