Skip to content

Open-source manufacturing ERP, MES and QMS. Quoting, MRP, inventory, shop floor, quality and lot/serial traceability on one Postgres schema, with a REST API and MCP server. Self-host or use Carbon Cloud.

fix(planning): max order quantity splits orders, live chart supply, surplus items planned (#1904)

Naveen Kashyap9c3b2c260e3e
diff --git a/.ai/plans/2026-10-13-mrp-tester-fixes.md b/.ai/plans/2026-10-13-mrp-tester-fixes.md
new file mode 100644
index 0000000000..e5902d00af
--- /dev/null
+++ b/.ai/plans/2026-10-13-mrp-tester-fixes.md
@@ -0,0 +1,41 @@
+# MRP tester fixes (confirmed items)
+
+Source: tester report of 2026-10-12, verified read-only the same day. Fixes
+the five items that were confirmed in code. Not in scope: #8 (dependent demand
+is lead-time-offset twice — needs a decision on what a demand period means),
+#4/#5 remaining gaps (supplier-part order multiple, batch size under Fixed
+Reorder Quantity, Increase rounding — product calls).
+
+## Tasks
+
+- [x] **#6 Max order quantity splits, never clamps** —
+ `packages/utils/src/planning-sizing.ts` Demand-Based Reorder: size the window
+ need (min, then multiple), then split it into orders of
+ `perOrder = min(lotSize, maximumOrderQuantity)` (zeros ignored; floored to the
+ order multiple when one is set). `orderSizingRules` returns the same
+ `perOrder` so the pages' `splitIntoOrders` round-trips. SQL twin
+ `calculate_quantity_to_order` drops the `LEAST(total, max)` clamp (new
+ migration). Tests: `planning-sizing.test.ts` (replace the "capped to 30"
+ pin), `planned-orders-from-actions.test.ts`.
+- [x] **#7 Legend toggles drive the projection line** —
+ `ItemPlanningChart.tsx` `chartData` reads `hiddenSeries`; a hidden series
+ contributes 0 to the running projection and to stockout / below-safety
+ detection. Pure helper + test in `planningSupplyDemand.ts`.
+- [x] **#9 PO due date in the Supply & Demand list** — `getOpenPurchaseOrderLines`
+ selects `promisedDate`, `dueDate` (required), `orderDate`, `leadTime`; the
+ forecast route derives the row date with `purchaseOrderLineArrivalDate`
+ (exported from `@carbon/planning`).
+- [x] **#2 Chart bars from live open orders** — the forecast route buckets
+ `openPurchaseOrderLines` / `openProductionOrders` into periods by the same
+ dates MRP uses (`purchaseOrderLineArrivalDate`, `jobCompletionDate`, before
+ today → first week, past horizon → dropped) instead of reading
+ `supplyActual` + `supplyForecast`. Pure `bucketSupplyByPeriod` + test. Chart
+ sums per (period, source) instead of assigning.
+- [x] **#10 Surplus-only items reach the engine and the screen** — new migration
+ re-creating `get_production_planning` and `get_purchasing_planning` with the
+ item predicate widened: `OR EXISTS (supply_data with supply > 0)`.
+- [x] Rules: `.claude/rules/mrp-system.md` (lot-sizing claim, RPC predicate,
+ chart source).
+- [x] Verify: `pnpm --filter @carbon/utils test`, `pnpm --filter erp test
+ planningSupplyDemand`, scoped typecheck (utils, planning, erp), biome.
+ Migrations cannot be applied here (local Supabase down) — flag.
diff --git a/.ai/playbooks/planning-chart-live-supply-and-max-order-split.md b/.ai/playbooks/planning-chart-live-supply-and-max-order-split.md
new file mode 100644
index 0000000000..86cf62e28c
--- /dev/null
+++ b/.ai/playbooks/planning-chart-live-supply-and-max-order-split.md
@@ -0,0 +1,58 @@
+# Planning chart live supply, legend what-if, max order split, surplus Cancel
+
+Last tested: 2026-10-13
+Routes: /x/production/planning, /x/purchasing/planning, /x/part/$itemId/planning
+
+## Prerequisites
+- Dev stack up and migrations applied (`crbn migrate`). A migration edited after
+ its version was recorded is NOT re-applied; run the file with `psql -f`.
+- A Buy item with an open Order suggestion, a supplier part (conversion factor 1
+ keeps the drawer in inventory units), and policy Demand-Based Reorder.
+- A make-to-stock job (Planned/Ready) on an item with no demand, for the Cancel.
+- MRP has run at least once after the data exists (Recalculate button, or wait
+ for the 3-hourly cron on the hour UTC).
+
+## Steps
+
+### 1. Surplus item on Production planning (issue 10)
+Open `/x/production/planning?location=<plant>`. The item with the demand-less
+job is listed with a "Cancel" chip in the Actions column. Expand the row: the
+line reads "Cancel job <J…>" with Review/Apply.
+
+### 2. Purchasing planning loads (RPC)
+Open `/x/purchasing/planning?location=<plant>`. Grid renders rows; the row's
+button reads "Order <qty>".
+
+### 3. Max order quantity splits (issue 6)
+Open `/x/part/<itemId>/planning?location=<plant>`. In the Planning card set
+"Maximum Order Quantity" (react-aria number: `fill`, then click another field
+to blur; verify `input[name=maximumOrderQuantity]`). Submit with
+`requestSubmit` on the FIRST button whose text starts with "Save" (the card has
+its own form; a later Save belongs to Supersession). The save re-runs MRP.
+Back on Purchasing planning, click the row's "Order <qty>" button: Suggested
+Orders lists several rows each <= the maximum (2280 with max 1000 → 1,000,
+1,000, 280), due dates spread across the week.
+
+### 4. Order, then the chart (issues 2 and 9)
+Click the drawer's "Order" button. PO lines are created with `requiredDate`
+only. Open the part planning tab: the "Incoming" card grows by the ordered
+quantity before any MRP run, and every new PO row in Supply & Demand shows a
+date (no "No due date").
+
+### 5. Legend what-if (issue 7)
+Read `path.recharts-line-curve`'s `d`. Click the "Supply" legend button: `d`
+changes. Click again: `d` is identical to the first read.
+
+## Selector Notes
+- Legend buttons are plain buttons named "Projected on hand", "Safety stock",
+ "Supply", "Planned", "Demand", "Demand Forecast" under the "Projected
+ inventory" heading.
+- The planning card's number fields have no accessible name; locate by the
+ "What is Maximum Order Quantity?" help button, the textbox follows it.
+- Summary cards: generic "Quantity on Hand<N>", "Incoming<N>", "Outgoing<N>".
+
+## Common Failures
+- `psql -c "a; b"` prints only the last statement's result — one statement per
+ call when reading probes.
+- A sizing function without the accumulation-period clamp spins forever on a
+ stored period of 0; set `statement_timeout` on probes.
diff --git a/.claude/rules/mrp-system.md b/.claude/rules/mrp-system.md
index a64541004e..d390dc5b1f 100644
--- a/.claude/rules/mrp-system.md
+++ b/.claude/rules/mrp-system.md
@@ -287,7 +287,18 @@ Their `demand_data` CTEs read the projection arm net of consumption
project on-hand period-by-period (`week1`…`week52`), and compute `quantityToOrder`
via `calculate_quantity_to_order(...)`, which branches on `reorderingPolicy`:
`'Manual Reorder'` → 0; `'Demand-Based Reorder'`; `'Fixed Reorder Quantity'`;
- `'Maximum Quantity'`. All respect min/max OQ, `orderMultiple`, `lotSize`.
+ `'Maximum Quantity'`. Demand-Based Reorder applies the minimum and the order
+ multiple to the week's need and sizes each ORDER by the smaller of `lotSize`
+ and `maximumOrderQuantity` (`demandBasedPerOrder` in `planning-sizing.ts`;
+ the SQL total is the whole need, `20261013004700`) — a maximum never caps
+ the week. Fixed Reorder Quantity ignores `lotSize`; Maximum Quantity uses it
+ only as a rounding multiple.
+- An item is included when it has demand in the window, a stock-driven policy
+ (reorder point on Fixed Reorder Quantity / Maximum Quantity), OR open supply
+ in the window (`supply_data` with `supply > 0`, `20261013004600`). The third
+ arm is what lets `generatePlanningActions` reach `deriveChangeActions` for a
+ surplus-only item — a job whose forecast was deleted gets its Cancel — and
+ keeps that item on the Material Planning screens.
## "Buy and Make" coercion + BOM decision
@@ -327,6 +338,22 @@ All join through `itemReplenishment` to expose `replenishmentSystem`, `leadTime`
`requiredDate`, `promisedDate` = the line's promised date, else the order
delivery's `receiptPromisedDate`.
+### The item planning chart reads the live lines
+
+`api+/items.$id.$locationId.forecast.ts` builds the chart's supply bars from
+`openPurchaseOrderLines` / `openProductionOrders` bucketed by
+`purchaseOrderLineArrivalDate` / `jobCompletionDate` (both exported from
+`@carbon/planning`) through the pure `bucketSupplyByPeriod`
+(`items/ui/Item/planningSupplyDemand.ts`, tested) — overdue in the first
+week, past the horizon dropped, summed per (week, source). It no longer reads
+`supplyActual` / `supplyForecast`, which only a run refreshes: a PO raised or
+increased from the drawer moves the projection at once, and a new order never
+replaces the week's existing bar. Each PO row in the Supply & Demand list
+carries that arrival date as its `dueDate` (the promise alone left a planned
+line as "No due date"). The legend is a what-if: `projectedChange` (same file)
+leaves a hidden series out of the running projection, stockout and
+below-safety detection, as removing a suggested order does.
+
### When a PO line arrives — one rule
`purchaseOrderLineArrivalDate` (`packages/planning/src/mrp/supply-date.ts`,
diff --git a/apps/erp/app/modules/items/items.service.ts b/apps/erp/app/modules/items/items.service.ts
index b97c1e5ba4..a71e89d89d 100644
--- a/apps/erp/app/modules/items/items.service.ts
+++ b/apps/erp/app/modules/items/items.service.ts
@@ -2160,14 +2160,24 @@ export async function getOpenProductionOrders(
locationId
}: { itemId: string; companyId: string; locationId: string }
) {
- return client
- .from("openProductionOrders")
- .select(
- "id, quantity:quantityToReceive, documentReadableId:jobId, documentId:id, dueDate"
- )
- .eq("itemId", itemId)
- .eq("locationId", locationId)
- .eq("companyId", companyId);
+ return fetchAllFromTable<{
+ id: string;
+ quantity: number | null;
+ documentReadableId: string | null;
+ documentId: string;
+ dueDate: string | null;
+ deadlineType: Database["public"]["Enums"]["deadlineType"] | null;
+ }>(
+ client,
+ "openProductionOrders",
+ "id, quantity:quantityToReceive, documentReadableId:jobId, documentId:id, dueDate, deadlineType",
+ (query) =>
+ query
+ .eq("itemId", itemId)
+ .eq("locationId", locationId)
+ .eq("companyId", companyId)
+ .order("id")
+ );
}
/** @mcp read */
@@ -2179,14 +2189,26 @@ export async function getOpenPurchaseOrderLines(
locationId
}: { itemId: string; companyId: string; locationId: string }
) {
- return client
- .from("openPurchaseOrderLines")
- .select(
- "id, quantity:quantityToReceive, dueDate:promisedDate, ...purchaseOrder(documentReadableId:purchaseOrderId, documentId:id)"
- )
- .eq("itemId", itemId)
- .eq("locationId", locationId)
- .eq("companyId", companyId);
+ return fetchAllFromTable<{
+ id: string;
+ quantity: number | null;
+ promisedDate: string | null;
+ dueDate: string | null;
+ orderDate: string | null;
+ leadTime: number | null;
+ documentReadableId: string | null;
+ documentId: string;
+ }>(
+ client,
+ "openPurchaseOrderLines",
+ "id, quantity:quantityToReceive, promisedDate, dueDate, orderDate, leadTime, ...purchaseOrder(documentReadableId:purchaseOrderId, documentId:id)",
+ (query) =>
+ query
+ .eq("itemId", itemId)
+ .eq("locationId", locationId)
+ .eq("companyId", companyId)
+ .order("id")
+ );
}
/** @mcp read */
diff --git a/apps/erp/app/modules/items/ui/Item/ItemPlanningChart.tsx b/apps/erp/app/modules/items/ui/Item/ItemPlanningChart.tsx
index 3050c44910..58fa93341f 100644
--- a/apps/erp/app/modules/items/ui/Item/ItemPlanningChart.tsx
+++ b/apps/erp/app/modules/items/ui/Item/ItemPlanningChart.tsx
@@ -64,6 +64,7 @@ import type { ChartPlannedOrder } from "./planningSupplyDemand";
import {
demandSourceTypes,
mergePlannedOrders,
+ projectedChange,
type SourceType,
supplySourceTypes
} from "./planningSupplyDemand";
@@ -282,7 +283,7 @@ export const ItemPlanningChart = ({
) {
const sourceType = curr.sourceType as keyof ChartDataPoint;
if (sourceType === "Sales Order" || sourceType === "Job Material") {
- groupedData[curr.periodId][sourceType] = -(curr.actualQuantity ?? 0);
+ groupedData[curr.periodId][sourceType] -= curr.actualQuantity ?? 0;
}
}
});
@@ -299,7 +300,7 @@ export const ItemPlanningChart = ({
sourceType === "Purchase Order" ||
sourceType === "Production Order"
) {
- groupedData[curr.periodId][sourceType] = curr.actualQuantity ?? 0;
+ groupedData[curr.periodId][sourceType] += curr.actualQuantity ?? 0;
}
}
});
@@ -327,13 +328,7 @@ export const ItemPlanningChart = ({
const data = sortedData.map((period) => {
// Add supply (positive), then subtract demand (already stored negative).
- const supplyUp =
- period["Purchase Order"] + period["Production Order"] + period.Planned;
- const demandDown =
- period["Sales Order"] +
- period["Job Material"] +
- period["Demand Forecast"];
- runningProjection += supplyUp + demandDown;
+ runningProjection += projectedChange(period, hiddenSeries);
period.Projection = runningProjection;
if (stockoutDate === null && runningProjection < 0)
@@ -369,7 +364,8 @@ export const ItemPlanningChart = ({
plannedOrders,
conversionFactor,
hasSafetyStock,
- safetyStockValue
+ safetyStockValue,
+ hiddenSeries
]);
const axis = useMemo(() => {
diff --git a/apps/erp/app/modules/items/ui/Item/planningSupplyDemand.test.ts b/apps/erp/app/modules/items/ui/Item/planningSupplyDemand.test.ts
index 3349fac916..e3160ba8c4 100644
--- a/apps/erp/app/modules/items/ui/Item/planningSupplyDemand.test.ts
+++ b/apps/erp/app/modules/items/ui/Item/planningSupplyDemand.test.ts
@@ -5,8 +5,10 @@
import { describe, expect, it } from "vitest";
import type { PlannedOrder } from "../../../purchasing/purchasing.models";
import {
+ bucketSupplyByPeriod,
existingRowId,
mergePlannedOrders,
+ projectedChange,
type SupplyDemandRow
} from "./planningSupplyDemand";
@@ -148,3 +150,66 @@ describe("mergePlannedOrders", () => {
expect(rows[0].quantity).toBe(100);
});
});
+
+describe("bucketSupplyByPeriod", () => {
+ const periods = [
+ { id: "w1", startDate: "2026-10-11", endDate: "2026-10-17" },
+ { id: "w2", startDate: "2026-10-18", endDate: "2026-10-24" }
+ ];
+ const TODAY = "2026-10-13";
+
+ it("sums the lines of a week per source instead of overwriting", () => {
+ expect(
+ bucketSupplyByPeriod(periods, TODAY, [
+ { sourceType: "Purchase Order", quantity: 100, dueDate: "2026-10-19" },
+ { sourceType: "Purchase Order", quantity: 40, dueDate: "2026-10-20" },
+ { sourceType: "Production Order", quantity: 7, dueDate: "2026-10-20" }
+ ])
+ ).toEqual([
+ { periodId: "w2", sourceType: "Purchase Order", actualQuantity: 140 },
+ { periodId: "w2", sourceType: "Production Order", actualQuantity: 7 }
+ ]);
+ });
+
+ it("lands an overdue line in the first week and drops one past the horizon", () => {
+ expect(
+ bucketSupplyByPeriod(periods, TODAY, [
+ { sourceType: "Purchase Order", quantity: 5, dueDate: "2026-09-01" },
+ { sourceType: "Purchase Order", quantity: 9, dueDate: "2027-01-01" }
+ ])
+ ).toEqual([
+ { periodId: "w1", sourceType: "Purchase Order", actualQuantity: 5 }
+ ]);
+ });
+
+ it("skips a line with nothing left to receive", () => {
+ expect(
+ bucketSupplyByPeriod(periods, TODAY, [
+ { sourceType: "Purchase Order", quantity: 0, dueDate: "2026-10-19" }
+ ])
+ ).toEqual([]);
+ });
+});
+
+describe("projectedChange", () => {
+ const week = {
+ "Purchase Order": 100,
+ "Production Order": 20,
+ Planned: 30,
+ "Sales Order": -60,
+ "Job Material": -10,
+ "Demand Forecast": -25
+ };
+
+ it("nets every series when none is hidden", () => {
+ expect(projectedChange(week, new Set())).toBe(55);
+ });
+
+ it("leaves a hidden series out, so the legend is a what-if", () => {
+ expect(projectedChange(week, new Set(["planned"]))).toBe(25);
+ expect(projectedChange(week, new Set(["supply"]))).toBe(-65);
+ expect(projectedChange(week, new Set(["demand", "demandForecast"]))).toBe(
+ 150
+ );
+ });
+});
diff --git a/apps/erp/app/modules/items/ui/Item/planningSupplyDemand.ts b/apps/erp/app/modules/items/ui/Item/planningSupplyDemand.ts
index d0076b6695..fcc1c143c7 100644
--- a/apps/erp/app/modules/items/ui/Item/planningSupplyDemand.ts
+++ b/apps/erp/app/modules/items/ui/Item/planningSupplyDemand.ts
@@ -37,6 +37,86 @@ export function existingRowId(order: ChartPlannedOrder) {
return order.existingLineId ?? order.existingId;
}
+export type SupplySourceType = (typeof supplySourceTypes)[number];
+
+export type ChartPeriod = { id: string; startDate: string; endDate: string };
+
+export type BucketedSupply = {
+ periodId: string;
+ sourceType: SupplySourceType;
+ actualQuantity: number;
+};
+
+/**
+ * Open supply lines bucketed into the chart's weeks the way MRP buckets them
+ * (`findPeriod` in `runMrp`): a line due before today lands in the first
+ * week, one due past the last week is dropped. Summed per (week, source).
+ */
+export function bucketSupplyByPeriod(
+ periods: ChartPeriod[],
+ today: string,
+ lines: { sourceType: SupplySourceType; quantity: number; dueDate: string }[]
+): BucketedSupply[] {
+ const first = periods[0];
+ if (!first) return [];
+ const byKey = new Map<string, BucketedSupply>();
+ for (const line of lines) {
+ if (!(line.quantity > 0)) continue;
+ const period =
+ line.dueDate < today
+ ? first
+ : periods.find(
+ (p) => p.startDate <= line.dueDate && line.dueDate <= p.endDate
+ );
+ if (!period) continue;
+ const key = `${period.id}\x1f${line.sourceType}`;
+ const bucket = byKey.get(key) ?? {
+ periodId: period.id,
+ sourceType: line.sourceType,
+ actualQuantity: 0
+ };
+ bucket.actualQuantity += line.quantity;
+ byKey.set(key, bucket);
+ }
+ return [...byKey.values()];
+}
+
+/** The chart series a legend click can hide that move the projection. */
+export type ProjectionSeries =
+ | "supply"
+ | "planned"
+ | "demand"
+ | "demandForecast";
+
+export type ProjectionPoint = {
+ "Purchase Order": number;
+ "Production Order": number;
+ Planned: number;
+ /** Demand is stored negative. */
+ "Sales Order": number;
+ "Job Material": number;
+ "Demand Forecast": number;
+};
+
+/**
+ * What one week moves the projected on-hand by, counting only the series the
+ * legend shows.
+ */
+export function projectedChange(
+ point: ProjectionPoint,
+ hidden: { has(series: ProjectionSeries): boolean }
+): number {
+ const supply = hidden.has("supply")
+ ? 0
+ : point["Purchase Order"] + point["Production Order"];
+ const planned = hidden.has("planned") ? 0 : point.Planned;
+ const demand = hidden.has("demand")
+ ? 0
+ : point["Sales Order"] + point["Job Material"];
+ const forecast = hidden.has("demandForecast") ? 0 : point["Demand Forecast"];
+ return supply + planned + demand + forecast;
+}
+
export function mergePlannedOrders<T extends SupplyDemandRow>(
rows: T[],
plannedOrders: ChartPlannedOrder[],
diff --git a/apps/erp/app/routes/api+/items.$id.$locationId.forecast.ts b/apps/erp/app/routes/api+/items.$id.$locationId.forecast.ts
index 6ae61fcd14..6b773d17fa 100644
--- a/apps/erp/app/routes/api+/items.$id.$locationId.forecast.ts
+++ b/apps/erp/app/routes/api+/items.$id.$locationId.forecast.ts
@@ -7,6 +7,10 @@ import { requirePermissions } from "@carbon/auth/auth.server";
import { flash } from "@carbon/auth/session.server";
import type { Database } from "@carbon/database";
import { consumableInWholeAssemblies } from "@carbon/database/supersession-pick";
+import {
+ jobCompletionDate,
+ purchaseOrderLineArrivalDate
+} from "@carbon/planning";
import { datetime } from "@carbon/utils";
import type { LoaderFunctionArgs } from "react-router";
import { data } from "react-router";
@@ -15,12 +19,12 @@ import {
getDemandForecastSources,
getItemDemand,
getItemQuantities,
- getItemSupply,
getOpenJobMaterials,
getOpenProductionOrders,
getOpenPurchaseOrderLines,
getOpenSalesOrderLines
} from "~/modules/items/items.service";
+import { bucketSupplyByPeriod } from "~/modules/items/ui/Item/planningSupplyDemand";
import { getOrCreatePeriods } from "~/modules/shared/shared.server";
import { getLocationTimeZone } from "~/modules/shared/timezone.server";
@@ -175,7 +179,6 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
const [
demand,
- supply,
quantities,
openSalesOrderLines,
openJobMaterials,
@@ -189,12 +192,6 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
periods: periods.map((p) => p.id ?? ""),
companyId
}),
- getItemSupply(client, {
- itemId,
- locationId,
- periods: periods.map((p) => p.id ?? ""),
- companyId
- }),
getItemQuantities(client, itemId, companyId, locationId),
getOpenSalesOrderLines(client, { itemId, companyId, locationId }),
getOpenJobMaterials(client, { itemId, companyId, locationId }),
@@ -236,6 +233,19 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
await flash(request, error(demand.error, "Failed to load demand"))
);
}
+ // A failed supply read must not chart as "no supply".
+ if (openPurchaseOrderLines.error || openProductionOrders.error) {
+ return data(
+ defaultResponse,
+ await flash(
+ request,
+ error(
+ openPurchaseOrderLines.error ?? openProductionOrders.error,
+ "Failed to load supply"
+ )
+ )
+ );
+ }
const redirectedOpenJobMaterials = await getRedirectedOpenJobMaterials(
client,
@@ -249,22 +259,50 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
}
);
+ const todayIso = today.toString();
+
+ const purchaseOrderLines = (openPurchaseOrderLines.data ?? []).map(
+ (line) => ({
+ ...line,
+ dueDate: purchaseOrderLineArrivalDate(line, todayIso)
+ })
+ );
+ const productionOrders = (openProductionOrders.data ?? []).map((job) => ({
+ ...job,
+ completionDate: jobCompletionDate(job, todayIso)
+ }));
+
+ const supply = bucketSupplyByPeriod(
+ periods.map((p) => ({
+ id: p.id ?? "",
+ startDate: p.startDate ?? "",
+ endDate: p.endDate ?? ""
+ })),
+ todayIso,
+ [
+ ...purchaseOrderLines.map((line) => ({
+ sourceType: "Purchase Order" as const,
+ quantity: Number(line.quantity ?? 0),
+ dueDate: line.dueDate
+ })),
+ ...productionOrders.map((job) => ({
+ sourceType: "Production Order" as const,
+ quantity: Number(job.quantity ?? 0),
+ dueDate: job.completionDate
+ }))
+ ]
+ );
+
return {
demand: demand.actuals,
demandForecast,
demandForecastSources: demandForecastSources.data ?? [],
- supply: [
- ...supply.actuals,
- ...supply.forecasts.map((f) => ({
- ...f,
- actualQuantity: f.forecastQuantity
- }))
- ],
+ supply,
periods,
quantityOnHand: quantities.data?.quantityOnHand ?? 0,
openSalesOrderLines: openSalesOrderLines.data ?? [],
openJobMaterials: redirectedOpenJobMaterials,
- openProductionOrders: openProductionOrders.data ?? [],
- openPurchaseOrderLines: openPurchaseOrderLines.data ?? []
+ openProductionOrders: productionOrders,
+ openPurchaseOrderLines: purchaseOrderLines
};
}
diff --git a/apps/erp/app/routes/api+/mcp+/lib/tool-manifest.digest.json b/apps/erp/app/routes/api+/mcp+/lib/tool-manifest.digest.json
index 544e4850cc..7321ecef2d 100644
--- a/apps/erp/app/routes/api+/mcp+/lib/tool-manifest.digest.json
+++ b/apps/erp/app/routes/api+/mcp+/lib/tool-manifest.digest.json
@@ -475,8 +475,8 @@
{"name":"items_getMethodTreeArray","classification":"READ","paramCount":1,"schema":"2796fbbcab70","response":"6481a47cef6d","injectAuth":"companyId","permission":"parts:view","paginates":false},
{"name":"items_getNextRevision","classification":"READ","paramCount":1,"schema":"96527a3bce32","response":"00404e686415","injectAuth":"companyId","permission":"parts:view","paginates":false},
{"name":"items_getOpenJobMaterials","classification":"READ","paramCount":2,"schema":"ade4704d7338","response":"3df5c33eb3a4","injectAuth":"companyId","permission":"parts:view","paginates":false},
- {"name":"items_getOpenProductionOrders","classification":"READ","paramCount":2,"schema":"ade4704d7338","response":"6f4bb8737e15","injectAuth":"companyId","permission":"parts:view","paginates":false},
- {"name":"items_getOpenPurchaseOrderLines","classification":"READ","paramCount":2,"schema":"ade4704d7338","response":"ee9244a3a03b","injectAuth":"companyId","permission":"parts:view","paginates":false},
+ {"name":"items_getOpenProductionOrders","classification":"READ","paramCount":2,"schema":"ade4704d7338","response":"0de1519216f7","injectAuth":"companyId","permission":"parts:view","paginates":false},
+ {"name":"items_getOpenPurchaseOrderLines","classification":"READ","paramCount":2,"schema":"ade4704d7338","response":"c53a83bc1272","injectAuth":"companyId","permission":"parts:view","paginates":false},
{"name":"items_getOpenSalesOrderLines","classification":"READ","paramCount":2,"schema":"ade4704d7338","response":"ee9244a3a03b","injectAuth":"companyId","permission":"parts:view","paginates":false},
{"name":"items_getPart","classification":"READ","paramCount":1,"schema":"623ca47a6c74","response":"85d85a501c26","injectAuth":"companyId","permission":"parts:view","paginates":false},
{"name":"items_getParts","classification":"READ","paramCount":4,"schema":"5571215d4362","response":"b134f22017b9","injectAuth":"companyId","permission":"parts:view","paginates":true,"defaults":"always"},
diff --git a/packages/database/supabase/migrations/20261013004600_planning-rpcs-include-open-supply.sql b/packages/database/supabase/migrations/20261013004600_planning-rpcs-include-open-supply.sql
new file mode 100644
index 0000000000..568600f416
--- /dev/null
+++ b/packages/database/supabase/migrations/20261013004600_planning-rpcs-include-open-supply.sql
@@ -0,0 +1,807 @@
+-- SPDX-License-Identifier: AGPL-3.0-only
+-- Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,
+-- including ports, remain AGPLv3; serving them over a network requires releasing their source.
+
+-- The planning RPCs include an item with open supply in the window, not only
+-- one with demand or a stock-driven policy. An item whose demand went away
+-- (a deleted forecast) while a job or PO still supplied it dropped out of
+-- both RPCs, so the Material Planning screens hid it and generatePlanningActions
+-- never reached deriveChangeActions for it — no Cancel for the job.
+-- supply_data sums zeroed rows too, so the test is supply > 0.
+--
+-- get_production_planning forked from 20261006130001_demand-forecast-consumption.sql,
+-- get_purchasing_planning from 20261009181437_supplier-part-currency.sql; the
+-- grid wrappers (20261006205037) select from them unchanged.
+
+DROP FUNCTION IF EXISTS get_production_planning(TEXT, TEXT, TEXT[]);
+CREATE OR REPLACE FUNCTION get_production_planning(company_id TEXT, location_id TEXT, periods TEXT[])
+ RETURNS TABLE (
+ "id" TEXT,
+ "readableIdWithRevision" TEXT,
+ "name" TEXT,
+ "active" BOOLEAN,
+ "type" "itemType",
+ "itemTrackingType" "itemTrackingType",
+ "replenishmentSystem" "itemReplenishmentSystem",
+ "thumbnailPath" TEXT,
+ "unitOfMeasureCode" TEXT,
+ "leadTime" INTEGER,
+ "manufacturingBlocked" BOOLEAN,
+ "lotSize" INTEGER,
+ "reorderingPolicy" "itemReorderingPolicy",
+ "demandAccumulationPeriod" INTEGER,
+ "demandAccumulationSafetyStock" NUMERIC,
+ "reorderPoint" INTEGER,
+ "reorderQuantity" INTEGER,
+ "minimumOrderQuantity" INTEGER,
+ "maximumOrderQuantity" INTEGER,
+ "orderMultiple" INTEGER,
+ "quantityOnHand" NUMERIC,
+ "maximumInventoryQuantity" NUMERIC,
+ "quantityToOrder" NUMERIC,
+ "supersessionMode" TEXT,
+ "minimumReserveQuantity" NUMERIC,
+ "week1" NUMERIC,
+ "week2" NUMERIC,
+ "week3" NUMERIC,
+ "week4" NUMERIC,
+ "week5" NUMERIC,
+ "week6" NUMERIC,
+ "week7" NUMERIC,
+ "week8" NUMERIC,
+ "week9" NUMERIC,
+ "week10" NUMERIC,
+ "week11" NUMERIC,
+ "week12" NUMERIC,
+ "week13" NUMERIC,
+ "week14" NUMERIC,
+ "week15" NUMERIC,
+ "week16" NUMERIC,
+ "week17" NUMERIC,
+ "week18" NUMERIC,
+ "week19" NUMERIC,
+ "week20" NUMERIC,
+ "week21" NUMERIC,
+ "week22" NUMERIC,
+ "week23" NUMERIC,
+ "week24" NUMERIC,
+ "week25" NUMERIC,
+ "week26" NUMERIC,
+ "week27" NUMERIC,
+ "week28" NUMERIC,
+ "week29" NUMERIC,
+ "week30" NUMERIC,
+ "week31" NUMERIC,
+ "week32" NUMERIC,
+ "week33" NUMERIC,
+ "week34" NUMERIC,
+ "week35" NUMERIC,
+ "week36" NUMERIC,
+ "week37" NUMERIC,
+ "week38" NUMERIC,
+ "week39" NUMERIC,
+ "week40" NUMERIC,
+ "week41" NUMERIC,
+ "week42" NUMERIC,
+ "week43" NUMERIC,
+ "week44" NUMERIC,
+ "week45" NUMERIC,
+ "week46" NUMERIC,
+ "week47" NUMERIC,
+ "week48" NUMERIC,
+ "week49" NUMERIC,
+ "week50" NUMERIC,
+ "week51" NUMERIC,
+ "week52" NUMERIC
+ ) AS $$
+BEGIN
+ -- Tenant guard: SECURITY DEFINER bypasses RLS and PostgREST lets any caller
+ -- supply an arbitrary company_id. The shared guard every SECURITY DEFINER
+ -- read opens with (20260925121735_rpc-function-guards.sql), as
+ -- get_purchasing_planning below does: service_role and direct connections
+ -- pass, anyone else must belong to the company.
+ PERFORM assert_company_access(company_id);
+
+ RETURN QUERY
+ WITH RECURSIVE
+ -- Incoming supply per item/period: received quantities (supplyActual) plus
+ -- planned/expected receipts (supplyForecast, e.g. MRP planned orders).
+ supply_data AS (
+ SELECT
+ "itemId",
+ "periodId",
+ SUM(COALESCE("actualQuantity", 0) + COALESCE("forecastQuantity", 0)) AS "supply"
+ FROM (
+ SELECT "itemId", "periodId", "actualQuantity", NULL as "forecastQuantity"
+ FROM "supplyActual"
+ WHERE "companyId" = company_id
+ AND "locationId" = location_id
+ AND "periodId" = ANY(periods)
+ UNION ALL
+ SELECT "itemId", "periodId", NULL as "actualQuantity", "forecastQuantity"
+ FROM "supplyForecast"
+ WHERE "companyId" = company_id
+ AND "locationId" = location_id
+ AND "periodId" = ANY(periods)
+ ) combined
+ GROUP BY "itemId", "periodId"
+ ),
+ -- Demand per item/period, from three sources:
+ -- 1. demandActual — real demand (sales order lines, job materials)
+ -- 2. demandForecast — MRP output: BOM-derived (child) demand
+ -- 3. demandProjection — planner-entered top-level projections (NEW in this
+ -- migration; previously missing, so purely-projected items never showed)
+ demand_data AS (
+ SELECT
+ "itemId",
+ "periodId",
+ SUM(COALESCE("actualQuantity", 0) + COALESCE("forecastQuantity", 0)) AS "demand"
+ FROM (
+ SELECT "itemId", "periodId", "actualQuantity", NULL as "forecastQuantity"
+ FROM "demandActual"
+ WHERE "companyId" = company_id
+ AND "locationId" = location_id
+ AND "periodId" = ANY(periods)
+ UNION ALL
+ SELECT "itemId", "periodId", NULL as "actualQuantity", "forecastQuantity"
+ FROM "demandForecast"
+ WHERE "companyId" = company_id
+ AND "locationId" = location_id
+ AND "periodId" = ANY(periods)
+ UNION ALL
+ -- Top-level manual projections, net of forecast consumption: actual
+ -- demand consumed them during the MRP run (consumedQuantity), so only
+ -- the unconsumed remainder still drives demand here. Without this arm a
+ -- make item whose only demand is a projection never appears in
+ -- production planning to create jobs.
+ SELECT "itemId", "periodId", NULL as "actualQuantity",
+ GREATEST("forecastQuantity" - "consumedQuantity", 0) AS "forecastQuantity"
+ FROM "demandProjection"
+ WHERE "companyId" = company_id
+ AND "locationId" = location_id
+ AND "periodId" = ANY(periods)
+ ) combined
+ GROUP BY "itemId", "periodId"
+ ),
+ -- Which items belong on the production planning screen: active Make items
+ -- with replenishment + planning settings at this location, that either have
+ -- demand in the selected periods or are stock-driven (reorder point with a
+ -- Fixed Reorder Quantity / Maximum Quantity policy). Supersession rules drop
+ -- obsolete/phased-out items.
+ base_items AS (
+ SELECT DISTINCT ON (i."id")
+ i."id",
+ i."readableIdWithRevision",
+ i."name",
+ i."active",
+ i."type",
+ i."itemTrackingType",
+ i."replenishmentSystem",
+ CASE
+ WHEN i."thumbnailPath" IS NULL AND mu."thumbnailPath" IS NOT NULL THEN mu."thumbnailPath"
+ ELSE i."thumbnailPath"
+ END AS "thumbnailPath",
+ i."unitOfMeasureCode",
+ ir."leadTime",
+ ir."manufacturingBlocked",
+ ir."lotSize",
+ ip."reorderingPolicy",
+ ip."demandAccumulationPeriod",
+ ip."demandAccumulationSafetyStock",
+ ip."reorderPoint",
+ ip."reorderQuantity",
+ ip."minimumOrderQuantity",
+ ip."maximumOrderQuantity",
+ ip."orderMultiple",
+ ip."maximumInventoryQuantity",
+ COALESCE((
+ SELECT SUM("quantity")
+ FROM "itemLedger"
+ WHERE "companyId" = company_id
+ AND "locationId" = location_id
+ AND "itemId" = i."id"
+ ), 0) AS "quantityOnHand"
+ FROM "item" i
+ INNER JOIN "itemReplenishment" ir ON i."id" = ir."itemId"
+ INNER JOIN "itemPlanning" ip ON i."id" = ip."itemId" AND ip."locationId" = location_id
+ LEFT JOIN "modelUpload" mu ON mu."id" = i."modelUploadId"
+ WHERE i."companyId" = company_id
+ AND i."replenishmentSystem" = 'Make'
+ AND i."itemTrackingType" != 'Non-Inventory'
+ AND i."active" = TRUE
+ -- Supersession: drop obsolete items and items past their discontinuation
+ -- date so no new orders are suggested.
+ AND NOT EXISTS (
+ SELECT 1 FROM "itemSupersession" ss
+ WHERE ss."itemId" = i."id"
+ AND (
+ ss."supersessionMode" = 'No Stock'
+ OR (
+ -- date-based suppression applies only to the phase-out modes; Stock
+ -- Only keeps replenishing to its reserve floor regardless of date.
+ ss."supersessionMode" IN ('Consume First', 'Prefer New')
+ AND ss."discontinuationDate" IS NOT NULL
+ AND ss."discontinuationDate" <= CURRENT_DATE
+ )
+ )
+ )
+ AND (
+ EXISTS (
+ SELECT 1 FROM demand_data d
+ WHERE d."itemId" = i."id"
+ )
+ OR (
+ ip."reorderPoint" > 0
+ AND ip."reorderingPolicy" IN ('Fixed Reorder Quantity', 'Maximum Quantity')
+ )
+ OR EXISTS (
+ SELECT 1 FROM supply_data s
+ WHERE s."itemId" = i."id" AND s."supply" > 0
+ )
+ )
+ ),
+ -- Week-by-week running inventory balance: start from on-hand, then for each
+ -- selected period add supply and subtract demand (recursive walk). Negative
+ -- values are the projected shortfall the planner needs to cover with jobs.
+ projections AS (
+ SELECT
+ bi.*,
+ periods[1] as "periodId",
+ bi."quantityOnHand" + COALESCE(s."supply", 0) - COALESCE(d."demand", 0) AS "projection",
+ 1 as period_index
+ FROM base_items bi
+ LEFT JOIN supply_data s ON bi."id" = s."itemId" AND s."periodId" = periods[1]
+ LEFT JOIN demand_data d ON bi."id" = d."itemId" AND d."periodId" = periods[1]
+
+ UNION ALL
+
+ SELECT
+ p."id",
+ p."readableIdWithRevision",
+ p."name",
+ p."active",
+ p."type",
+ p."itemTrackingType",
+ p."replenishmentSystem",
+ p."thumbnailPath",
+ p."unitOfMeasureCode",
+ p."leadTime",
+ p."manufacturingBlocked",
+ p."lotSize",
+ p."reorderingPolicy",
+ p."demandAccumulationPeriod",
+ p."demandAccumulationSafetyStock",
+ p."reorderPoint",
+ p."reorderQuantity",
+ p."minimumOrderQuantity",
+ p."maximumOrderQuantity",
+ p."orderMultiple",
+ p."maximumInventoryQuantity",
+ p."quantityOnHand",
+ periods[p.period_index + 1] as "periodId",
+ p."projection" + COALESCE(s."supply", 0) - COALESCE(d."demand", 0) AS "projection",
+ p.period_index + 1 as period_index
+ FROM projections p
+ LEFT JOIN supply_data s ON p."id" = s."itemId" AND s."periodId" = periods[p.period_index + 1]
+ LEFT JOIN demand_data d ON p."id" = d."itemId" AND d."periodId" = periods[p.period_index + 1]
+ WHERE p.period_index < array_length(periods, 1)
+ ),
+ order_quantities AS (
+ SELECT
+ p."id",
+ calculate_quantity_to_order(
+ p."reorderingPolicy",
+ p."reorderPoint",
+ p."reorderQuantity",
+ p."minimumOrderQuantity",
+ p."maximumOrderQuantity",
+ p."orderMultiple",
+ p."lotSize",
+ p."maximumInventoryQuantity",
+ p."demandAccumulationPeriod",
+ p."demandAccumulationSafetyStock",
+ array_agg(p."projection" ORDER BY p.period_index)
+ ) AS "quantityToOrder"
+ FROM projections p
+ GROUP BY
+ p."id",
+ p."reorderingPolicy",
+ p."reorderPoint",
+ p."reorderQuantity",
+ p."minimumOrderQuantity",
+ p."maximumOrderQuantity",
+ p."orderMultiple",
+ p."lotSize",
+ p."maximumInventoryQuantity",
+ p."demandAccumulationPeriod",
+ p."demandAccumulationSafetyStock"
+ )
+ SELECT DISTINCT ON (p."id")
+ p."id",
+ p."readableIdWithRevision",
+ p."name",
+ p."active",
+ p."type",
+ p."itemTrackingType",
+ p."replenishmentSystem",
+ p."thumbnailPath",
+ p."unitOfMeasureCode",
+ p."leadTime",
+ p."manufacturingBlocked",
+ p."lotSize",
+ p."reorderingPolicy",
+ p."demandAccumulationPeriod",
+ p."demandAccumulationSafetyStock",
+ p."reorderPoint",
+ p."reorderQuantity",
+ p."minimumOrderQuantity",
+ p."maximumOrderQuantity",
+ p."orderMultiple",
+ p."quantityOnHand",
+ p."maximumInventoryQuantity",
+ CASE
+ WHEN ss."supersessionMode" = 'Stock Only'
+ THEN GREATEST(
+ 0,
+ COALESCE(rsv."minimumReserveQuantity", 0)
+ - p."quantityOnHand"
+ - COALESCE(sup."incomingSupply", 0)
+ )
+ ELSE COALESCE(oq."quantityToOrder", 0)
+ END AS "quantityToOrder",
+ ss."supersessionMode"::TEXT AS "supersessionMode",
+ COALESCE(rsv."minimumReserveQuantity", 0) AS "minimumReserveQuantity",
+ MAX(CASE WHEN p."periodId" = periods[1] THEN p."projection" END) AS "week1",
+ MAX(CASE WHEN p."periodId" = periods[2] THEN p."projection" END) AS "week2",
+ MAX(CASE WHEN p."periodId" = periods[3] THEN p."projection" END) AS "week3",
+ MAX(CASE WHEN p."periodId" = periods[4] THEN p."projection" END) AS "week4",
+ MAX(CASE WHEN p."periodId" = periods[5] THEN p."projection" END) AS "week5",
+ MAX(CASE WHEN p."periodId" = periods[6] THEN p."projection" END) AS "week6",
+ MAX(CASE WHEN p."periodId" = periods[7] THEN p."projection" END) AS "week7",
+ MAX(CASE WHEN p."periodId" = periods[8] THEN p."projection" END) AS "week8",
+ MAX(CASE WHEN p."periodId" = periods[9] THEN p."projection" END) AS "week9",
+ MAX(CASE WHEN p."periodId" = periods[10] THEN p."projection" END) AS "week10",
+ MAX(CASE WHEN p."periodId" = periods[11] THEN p."projection" END) AS "week11",
+ MAX(CASE WHEN p."periodId" = periods[12] THEN p."projection" END) AS "week12",
+ MAX(CASE WHEN p."periodId" = periods[13] THEN p."projection" END) AS "week13",
+ MAX(CASE WHEN p."periodId" = periods[14] THEN p."projection" END) AS "week14",
+ MAX(CASE WHEN p."periodId" = periods[15] THEN p."projection" END) AS "week15",
+ MAX(CASE WHEN p."periodId" = periods[16] THEN p."projection" END) AS "week16",
+ MAX(CASE WHEN p."periodId" = periods[17] THEN p."projection" END) AS "week17",
+ MAX(CASE WHEN p."periodId" = periods[18] THEN p."projection" END) AS "week18",
+ MAX(CASE WHEN p."periodId" = periods[19] THEN p."projection" END) AS "week19",
+ MAX(CASE WHEN p."periodId" = periods[20] THEN p."projection" END) AS "week20",
+ MAX(CASE WHEN p."periodId" = periods[21] THEN p."projection" END) AS "week21",
+ MAX(CASE WHEN p."periodId" = periods[22] THEN p."projection" END) AS "week22",
+ MAX(CASE WHEN p."periodId" = periods[23] THEN p."projection" END) AS "week23",
+ MAX(CASE WHEN p."periodId" = periods[24] THEN p."projection" END) AS "week24",
+ MAX(CASE WHEN p."periodId" = periods[25] THEN p."projection" END) AS "week25",
+ MAX(CASE WHEN p."periodId" = periods[26] THEN p."projection" END) AS "week26",
+ MAX(CASE WHEN p."periodId" = periods[27] THEN p."projection" END) AS "week27",
+ MAX(CASE WHEN p."periodId" = periods[28] THEN p."projection" END) AS "week28",
+ MAX(CASE WHEN p."periodId" = periods[29] THEN p."projection" END) AS "week29",
+ MAX(CASE WHEN p."periodId" = periods[30] THEN p."projection" END) AS "week30",
+ MAX(CASE WHEN p."periodId" = periods[31] THEN p."projection" END) AS "week31",
+ MAX(CASE WHEN p."periodId" = periods[32] THEN p."projection" END) AS "week32",
+ MAX(CASE WHEN p."periodId" = periods[33] THEN p."projection" END) AS "week33",
+ MAX(CASE WHEN p."periodId" = periods[34] THEN p."projection" END) AS "week34",
+ MAX(CASE WHEN p."periodId" = periods[35] THEN p."projection" END) AS "week35",
+ MAX(CASE WHEN p."periodId" = periods[36] THEN p."projection" END) AS "week36",
+ MAX(CASE WHEN p."periodId" = periods[37] THEN p."projection" END) AS "week37",
+ MAX(CASE WHEN p."periodId" = periods[38] THEN p."projection" END) AS "week38",
+ MAX(CASE WHEN p."periodId" = periods[39] THEN p."projection" END) AS "week39",
+ MAX(CASE WHEN p."periodId" = periods[40] THEN p."projection" END) AS "week40",
+ MAX(CASE WHEN p."periodId" = periods[41] THEN p."projection" END) AS "week41",
+ MAX(CASE WHEN p."periodId" = periods[42] THEN p."projection" END) AS "week42",
+ MAX(CASE WHEN p."periodId" = periods[43] THEN p."projection" END) AS "week43",
+ MAX(CASE WHEN p."periodId" = periods[44] THEN p."projection" END) AS "week44",
+ MAX(CASE WHEN p."periodId" = periods[45] THEN p."projection" END) AS "week45",
+ MAX(CASE WHEN p."periodId" = periods[46] THEN p."projection" END) AS "week46",
+ MAX(CASE WHEN p."periodId" = periods[47] THEN p."projection" END) AS "week47",
+ MAX(CASE WHEN p."periodId" = periods[48] THEN p."projection" END) AS "week48",
+ MAX(CASE WHEN p."periodId" = periods[49] THEN p."projection" END) AS "week49",
+ MAX(CASE WHEN p."periodId" = periods[50] THEN p."projection" END) AS "week50",
+ MAX(CASE WHEN p."periodId" = periods[51] THEN p."projection" END) AS "week51",
+ MAX(CASE WHEN p."periodId" = periods[52] THEN p."projection" END) AS "week52"
+ FROM projections p
+ LEFT JOIN order_quantities oq ON p."id" = oq."id"
+ LEFT JOIN "itemSupersession" ss ON ss."itemId" = p."id"
+ LEFT JOIN "itemPlanning" rsv ON rsv."itemId" = p."id" AND rsv."locationId" = location_id
+ LEFT JOIN (
+ SELECT "itemId", SUM("supply") AS "incomingSupply"
+ FROM supply_data GROUP BY "itemId"
+ ) sup ON sup."itemId" = p."id"
+ GROUP BY
+ p."id",
+ p."readableIdWithRevision",
+ p."name",
+ p."active",
+ p."type",
+ p."itemTrackingType",
+ p."replenishmentSystem",
+ p."thumbnailPath",
+ p."unitOfMeasureCode",
+ p."leadTime",
+ p."manufacturingBlocked",
+ p."lotSize",
+ p."reorderingPolicy",
+ p."demandAccumulationPeriod",
+ p."demandAccumulationSafetyStock",
+ p."reorderPoint",
+ p."reorderQuantity",
+ p."minimumOrderQuantity",
+ p."maximumOrderQuantity",
+ p."orderMultiple",
+ p."quantityOnHand",
+ p."maximumInventoryQuantity",
+ oq."quantityToOrder",
+ ss."supersessionMode",
+ rsv."minimumReserveQuantity",
+ sup."incomingSupply";
+END;
+$$ LANGUAGE plpgsql SECURITY DEFINER SET search_path = public;
+
+CREATE OR REPLACE FUNCTION public.get_purchasing_planning(company_id text, location_id text, periods text[])
+ RETURNS TABLE(id text, "readableIdWithRevision" text, name text, active boolean, type "itemType", "itemTrackingType" "itemTrackingType", "replenishmentSystem" "itemReplenishmentSystem", "thumbnailPath" text, "unitOfMeasureCode" text, "leadTime" integer, "purchasingBlocked" boolean, "lotSize" integer, "reorderingPolicy" "itemReorderingPolicy", "demandAccumulationPeriod" integer, "demandAccumulationSafetyStock" numeric, "reorderPoint" integer, "reorderQuantity" integer, "minimumOrderQuantity" integer, "maximumOrderQuantity" integer, "orderMultiple" integer, "quantityOnHand" numeric, "maximumInventoryQuantity" numeric, suppliers jsonb, "preferredSupplierId" text, "purchasingUnitOfMeasureCode" text, "conversionFactor" numeric, "quantityToOrder" numeric, "supersessionMode" text, "minimumReserveQuantity" numeric, week1 numeric, week2 numeric, week3 numeric, week4 numeric, week5 numeric, week6 numeric, week7 numeric, week8 numeric, week9 numeric, week10 numeric, week11 numeric, week12 numeric, week13 numeric, week14 numeric, week15 numeric, week16 numeric, week17 numeric, week18 numeric, week19 numeric, week20 numeric, week21 numeric, week22 numeric, week23 numeric, week24 numeric, week25 numeric, week26 numeric, week27 numeric, week28 numeric, week29 numeric, week30 numeric, week31 numeric, week32 numeric, week33 numeric, week34 numeric, week35 numeric, week36 numeric, week37 numeric, week38 numeric, week39 numeric, week40 numeric, week41 numeric, week42 numeric, week43 numeric, week44 numeric, week45 numeric, week46 numeric, week47 numeric, week48 numeric, week49 numeric, week50 numeric, week51 numeric, week52 numeric)
+ LANGUAGE sql
+ SECURITY DEFINER
+ SET search_path = public
+AS $function$
+ SELECT assert_company_access(company_id);
+ WITH RECURSIVE
+ supply_data AS (
+ SELECT
+ "itemId",
+ "periodId",
+ SUM(COALESCE("actualQuantity", 0) + COALESCE("forecastQuantity", 0)) AS "supply"
+ FROM (
+ SELECT "itemId", "periodId", "actualQuantity", NULL as "forecastQuantity"
+ FROM "supplyActual"
+ WHERE "companyId" = company_id
+ AND "locationId" = location_id
+ AND "periodId" = ANY(periods)
+ UNION ALL
+ SELECT "itemId", "periodId", NULL as "actualQuantity", "forecastQuantity"
+ FROM "supplyForecast"
+ WHERE "companyId" = company_id
+ AND "locationId" = location_id
+ AND "periodId" = ANY(periods)
+ ) combined
+ GROUP BY "itemId", "periodId"
+ ),
+ demand_data AS (
+ SELECT
+ "itemId",
+ "periodId",
+ SUM(COALESCE("actualQuantity", 0) + COALESCE("forecastQuantity", 0)) AS "demand"
+ FROM (
+ SELECT "itemId", "periodId", "actualQuantity", NULL as "forecastQuantity"
+ FROM "demandActual"
+ WHERE "companyId" = company_id
+ AND "locationId" = location_id
+ AND "periodId" = ANY(periods)
+ UNION ALL
+ SELECT "itemId", "periodId", NULL as "actualQuantity", "forecastQuantity"
+ FROM "demandForecast"
+ WHERE "companyId" = company_id
+ AND "locationId" = location_id
+ AND "periodId" = ANY(periods)
+ UNION ALL
+ -- Top-level manual projections, net of forecast consumption: actual
+ -- demand consumed them during the MRP run (consumedQuantity), so only
+ -- the unconsumed remainder still drives demand here. Without this arm a
+ -- purchased item whose only demand is a projection never appears in
+ -- purchasing planning and never drives a suggested order.
+ SELECT "itemId", "periodId", NULL as "actualQuantity",
+ GREATEST("forecastQuantity" - "consumedQuantity", 0) AS "forecastQuantity"
+ FROM "demandProjection"
+ WHERE "companyId" = company_id
+ AND "locationId" = location_id
+ AND "periodId" = ANY(periods)
+ ) combined
+ GROUP BY "itemId", "periodId"
+ ),
+ base_items AS (
+ SELECT DISTINCT ON (i."id")
+ i."id",
+ i."readableIdWithRevision",
+ i."name",
+ i."active",
+ i."type",
+ i."itemTrackingType",
+ i."replenishmentSystem",
+ CASE
+ WHEN i."thumbnailPath" IS NULL AND mu."thumbnailPath" IS NOT NULL THEN mu."thumbnailPath"
+ ELSE i."thumbnailPath"
+ END AS "thumbnailPath",
+ i."unitOfMeasureCode",
+ ir."leadTime",
+ ir."purchasingBlocked",
+ ir."lotSize",
+ ir."preferredSupplierId",
+ ir."purchasingUnitOfMeasureCode",
+ ir."conversionFactor",
+ ip."reorderingPolicy",
+ ip."demandAccumulationPeriod",
+ ip."demandAccumulationSafetyStock",
+ ip."reorderPoint",
+ ip."reorderQuantity",
+ ip."minimumOrderQuantity",
+ ip."maximumOrderQuantity",
+ ip."orderMultiple",
+ ip."maximumInventoryQuantity",
+ COALESCE(ps."suppliers", '[]'::jsonb) as "suppliers",
+ COALESCE((
+ SELECT SUM("quantity")
+ FROM "itemLedger"
+ WHERE "companyId" = company_id
+ AND "locationId" = location_id
+ AND "itemId" = i."id"
+ ), 0) AS "quantityOnHand"
+ FROM "item" i
+ INNER JOIN "itemReplenishment" ir ON i."id" = ir."itemId"
+ INNER JOIN "itemPlanning" ip ON i."id" = ip."itemId" AND ip."locationId" = location_id
+ LEFT JOIN "modelUpload" mu ON mu."id" = i."modelUploadId"
+ LEFT JOIN (
+ SELECT
+ ps."itemId",
+ jsonb_agg(
+ jsonb_build_object(
+ 'id', ps."id",
+ 'minimumOrderQuantity', ps."minimumOrderQuantity",
+ 'supplierUnitOfMeasureCode', ps."supplierUnitOfMeasureCode",
+ 'conversionFactor', ps."conversionFactor",
+ 'supplierUnitPrice', ps."supplierUnitPrice",
+ 'currencyCode', ps."currencyCode",
+ 'supplierId', ps."supplierId",
+ 'supplierPartId', ps."supplierPartId"
+ )
+ ) AS "suppliers"
+ FROM "supplierPart" ps
+ WHERE ps."companyId" = company_id
+ AND ps.active = true
+ GROUP BY ps."itemId"
+ ) ps ON ps."itemId" = i."id"
+ WHERE i."companyId" = company_id
+ AND i."replenishmentSystem" != 'Make'
+ AND i."itemTrackingType" != 'Non-Inventory'
+ AND i."active" = TRUE
+ -- Supersession: drop obsolete items and items past their discontinuation
+ -- date so no new orders are suggested.
+ AND NOT EXISTS (
+ SELECT 1 FROM "itemSupersession" ss
+ WHERE ss."itemId" = i."id"
+ AND (
+ ss."supersessionMode" = 'No Stock'
+ OR (
+ -- date-based suppression applies only to the phase-out modes; Stock
+ -- Only keeps replenishing to its reserve floor regardless of date.
+ ss."supersessionMode" IN ('Consume First', 'Prefer New')
+ AND ss."discontinuationDate" IS NOT NULL
+ AND ss."discontinuationDate" <= CURRENT_DATE
+ )
+ )
+ )
+ AND (
+ EXISTS (
+ SELECT 1 FROM demand_data d
+ WHERE d."itemId" = i."id"
+ )
+ OR (
+ ip."reorderPoint" > 0
+ AND ip."reorderingPolicy" IN ('Fixed Reorder Quantity', 'Maximum Quantity')
+ )
+ OR EXISTS (
+ SELECT 1 FROM supply_data s
+ WHERE s."itemId" = i."id" AND s."supply" > 0
+ )
+ )
+ ),
+ projections AS (
+ SELECT
+ bi.*,
+ periods[1] as "periodId",
+ bi."quantityOnHand" + COALESCE(s."supply", 0) - COALESCE(d."demand", 0) AS "projection",
+ 1 as period_index
+ FROM base_items bi
+ LEFT JOIN supply_data s ON bi."id" = s."itemId" AND s."periodId" = periods[1]
+ LEFT JOIN demand_data d ON bi."id" = d."itemId" AND d."periodId" = periods[1]
+
+ UNION ALL
+
+ SELECT
+ p."id",
+ p."readableIdWithRevision",
+ p."name",
+ p."active",
+ p."type",
+ p."itemTrackingType",
+ p."replenishmentSystem",
+ p."thumbnailPath",
+ p."unitOfMeasureCode",
+ p."leadTime",
+ p."purchasingBlocked",
+ p."lotSize",
+ p."preferredSupplierId",
+ p."purchasingUnitOfMeasureCode",
+ p."conversionFactor",
+ p."reorderingPolicy",
+ p."demandAccumulationPeriod",
+ p."demandAccumulationSafetyStock",
+ p."reorderPoint",
+ p."reorderQuantity",
+ p."minimumOrderQuantity",
+ p."maximumOrderQuantity",
+ p."orderMultiple",
+ p."maximumInventoryQuantity",
+ p."suppliers",
+ p."quantityOnHand",
+ periods[p.period_index + 1] as "periodId",
+ p."projection" + COALESCE(s."supply", 0) - COALESCE(d."demand", 0) AS "projection",
+ p.period_index + 1 as period_index
+ FROM projections p
+ LEFT JOIN supply_data s ON p."id" = s."itemId" AND s."periodId" = periods[p.period_index + 1]
+ LEFT JOIN demand_data d ON p."id" = d."itemId" AND d."periodId" = periods[p.period_index + 1]
+ WHERE p.period_index < array_length(periods, 1)
+ ),
+ order_quantities AS (
+ SELECT
+ p."id",
+ calculate_quantity_to_order(
+ p."reorderingPolicy",
+ p."reorderPoint",
+ p."reorderQuantity",
+ p."minimumOrderQuantity",
+ p."maximumOrderQuantity",
+ p."orderMultiple",
+ p."lotSize",
+ p."maximumInventoryQuantity",
+ p."demandAccumulationPeriod",
+ p."demandAccumulationSafetyStock",
+ array_agg(p."projection" ORDER BY p.period_index)
+ ) AS "quantityToOrder"
+ FROM projections p
+ GROUP BY
+ p."id",
+ p."reorderingPolicy",
+ p."reorderPoint",
+ p."reorderQuantity",
+ p."minimumOrderQuantity",
+ p."maximumOrderQuantity",
+ p."orderMultiple",
+ p."lotSize",
+ p."maximumInventoryQuantity",
+ p."demandAccumulationPeriod",
+ p."demandAccumulationSafetyStock"
+ )
+ SELECT DISTINCT ON (p."id")
+ p."id",
+ p."readableIdWithRevision",
+ p."name",
+ p."active",
+ p."type",
+ p."itemTrackingType",
+ p."replenishmentSystem",
+ p."thumbnailPath",
+ p."unitOfMeasureCode",
+ p."leadTime",
+ p."purchasingBlocked",
+ p."lotSize",
+ p."reorderingPolicy",
+ p."demandAccumulationPeriod",
+ p."demandAccumulationSafetyStock",
+ p."reorderPoint",
+ p."reorderQuantity",
+ p."minimumOrderQuantity",
+ p."maximumOrderQuantity",
+ p."orderMultiple",
+ p."quantityOnHand",
+ p."maximumInventoryQuantity",
+ p."suppliers",
+ p."preferredSupplierId",
+ p."purchasingUnitOfMeasureCode",
+ p."conversionFactor",
+ CASE
+ WHEN ss."supersessionMode" = 'Stock Only'
+ THEN GREATEST(
+ 0,
+ COALESCE(rsv."minimumReserveQuantity", 0)
+ - p."quantityOnHand"
+ - COALESCE(sup."incomingSupply", 0)
+ )
+ ELSE COALESCE(oq."quantityToOrder", 0)
+ END AS "quantityToOrder",
+ ss."supersessionMode" AS "supersessionMode",
+ COALESCE(rsv."minimumReserveQuantity", 0) AS "minimumReserveQuantity",
+ MAX(CASE WHEN p."periodId" = periods[1] THEN p."projection" END) AS "week1",
+ MAX(CASE WHEN p."periodId" = periods[2] THEN p."projection" END) AS "week2",
+ MAX(CASE WHEN p."periodId" = periods[3] THEN p."projection" END) AS "week3",
+ MAX(CASE WHEN p."periodId" = periods[4] THEN p."projection" END) AS "week4",
+ MAX(CASE WHEN p."periodId" = periods[5] THEN p."projection" END) AS "week5",
+ MAX(CASE WHEN p."periodId" = periods[6] THEN p."projection" END) AS "week6",
+ MAX(CASE WHEN p."periodId" = periods[7] THEN p."projection" END) AS "week7",
+ MAX(CASE WHEN p."periodId" = periods[8] THEN p."projection" END) AS "week8",
+ MAX(CASE WHEN p."periodId" = periods[9] THEN p."projection" END) AS "week9",
+ MAX(CASE WHEN p."periodId" = periods[10] THEN p."projection" END) AS "week10",
+ MAX(CASE WHEN p."periodId" = periods[11] THEN p."projection" END) AS "week11",
+ MAX(CASE WHEN p."periodId" = periods[12] THEN p."projection" END) AS "week12",
+ MAX(CASE WHEN p."periodId" = periods[13] THEN p."projection" END) AS "week13",
+ MAX(CASE WHEN p."periodId" = periods[14] THEN p."projection" END) AS "week14",
+ MAX(CASE WHEN p."periodId" = periods[15] THEN p."projection" END) AS "week15",
+ MAX(CASE WHEN p."periodId" = periods[16] THEN p."projection" END) AS "week16",
+ MAX(CASE WHEN p."periodId" = periods[17] THEN p."projection" END) AS "week17",
+ MAX(CASE WHEN p."periodId" = periods[18] THEN p."projection" END) AS "week18",
+ MAX(CASE WHEN p."periodId" = periods[19] THEN p."projection" END) AS "week19",
+ MAX(CASE WHEN p."periodId" = periods[20] THEN p."projection" END) AS "week20",
+ MAX(CASE WHEN p."periodId" = periods[21] THEN p."projection" END) AS "week21",
+ MAX(CASE WHEN p."periodId" = periods[22] THEN p."projection" END) AS "week22",
+ MAX(CASE WHEN p."periodId" = periods[23] THEN p."projection" END) AS "week23",
+ MAX(CASE WHEN p."periodId" = periods[24] THEN p."projection" END) AS "week24",
+ MAX(CASE WHEN p."periodId" = periods[25] THEN p."projection" END) AS "week25",
+ MAX(CASE WHEN p."periodId" = periods[26] THEN p."projection" END) AS "week26",
+ MAX(CASE WHEN p."periodId" = periods[27] THEN p."projection" END) AS "week27",
+ MAX(CASE WHEN p."periodId" = periods[28] THEN p."projection" END) AS "week28",
+ MAX(CASE WHEN p."periodId" = periods[29] THEN p."projection" END) AS "week29",
+ MAX(CASE WHEN p."periodId" = periods[30] THEN p."projection" END) AS "week30",
+ MAX(CASE WHEN p."periodId" = periods[31] THEN p."projection" END) AS "week31",
+ MAX(CASE WHEN p."periodId" = periods[32] THEN p."projection" END) AS "week32",
+ MAX(CASE WHEN p."periodId" = periods[33] THEN p."projection" END) AS "week33",
+ MAX(CASE WHEN p."periodId" = periods[34] THEN p."projection" END) AS "week34",
+ MAX(CASE WHEN p."periodId" = periods[35] THEN p."projection" END) AS "week35",
+ MAX(CASE WHEN p."periodId" = periods[36] THEN p."projection" END) AS "week36",
+ MAX(CASE WHEN p."periodId" = periods[37] THEN p."projection" END) AS "week37",
+ MAX(CASE WHEN p."periodId" = periods[38] THEN p."projection" END) AS "week38",
+ MAX(CASE WHEN p."periodId" = periods[39] THEN p."projection" END) AS "week39",
+ MAX(CASE WHEN p."periodId" = periods[40] THEN p."projection" END) AS "week40",
+ MAX(CASE WHEN p."periodId" = periods[41] THEN p."projection" END) AS "week41",
+ MAX(CASE WHEN p."periodId" = periods[42] THEN p."projection" END) AS "week42",
+ MAX(CASE WHEN p."periodId" = periods[43] THEN p."projection" END) AS "week43",
+ MAX(CASE WHEN p."periodId" = periods[44] THEN p."projection" END) AS "week44",
+ MAX(CASE WHEN p."periodId" = periods[45] THEN p."projection" END) AS "week45",
+ MAX(CASE WHEN p."periodId" = periods[46] THEN p."projection" END) AS "week46",
+ MAX(CASE WHEN p."periodId" = periods[47] THEN p."projection" END) AS "week47",
+ MAX(CASE WHEN p."periodId" = periods[48] THEN p."projection" END) AS "week48",
+ MAX(CASE WHEN p."periodId" = periods[49] THEN p."projection" END) AS "week49",
+ MAX(CASE WHEN p."periodId" = periods[50] THEN p."projection" END) AS "week50",
+ MAX(CASE WHEN p."periodId" = periods[51] THEN p."projection" END) AS "week51",
+ MAX(CASE WHEN p."periodId" = periods[52] THEN p."projection" END) AS "week52"
+ FROM projections p
+ LEFT JOIN order_quantities oq ON p."id" = oq."id"
+ LEFT JOIN "itemSupersession" ss ON ss."itemId" = p."id"
+ LEFT JOIN "itemPlanning" rsv ON rsv."itemId" = p."id" AND rsv."locationId" = location_id
+ LEFT JOIN (
+ SELECT "itemId", SUM("supply") AS "incomingSupply"
+ FROM supply_data GROUP BY "itemId"
+ ) sup ON sup."itemId" = p."id"
+ GROUP BY
+ p."id",
+ p."readableIdWithRevision",
+ p."name",
+ p."active",
+ p."type",
+ p."itemTrackingType",
+ p."replenishmentSystem",
+ p."thumbnailPath",
+ p."unitOfMeasureCode",
+ p."leadTime",
+ p."purchasingBlocked",
+ p."lotSize",
+ p."reorderingPolicy",
+ p."demandAccumulationPeriod",
+ p."demandAccumulationSafetyStock",
+ p."reorderPoint",
+ p."reorderQuantity",
+ p."minimumOrderQuantity",
+ p."maximumOrderQuantity",
+ p."orderMultiple",
+ p."quantityOnHand",
+ p."maximumInventoryQuantity",
+ p."suppliers",
+ p."preferredSupplierId",
+ p."purchasingUnitOfMeasureCode",
+ p."conversionFactor",
+ oq."quantityToOrder",
+ ss."supersessionMode",
+ rsv."minimumReserveQuantity",
+ sup."incomingSupply";
+$function$;
diff --git a/packages/database/supabase/migrations/20261013004700_planning-max-order-quantity-per-order.sql b/packages/database/supabase/migrations/20261013004700_planning-max-order-quantity-per-order.sql
new file mode 100644
index 0000000000..26f4fd30aa
--- /dev/null
+++ b/packages/database/supabase/migrations/20261013004700_planning-max-order-quantity-per-order.sql
@@ -0,0 +1,135 @@
+-- SPDX-License-Identifier: AGPL-3.0-only
+-- Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,
+-- including ports, remain AGPLv3; serving them over a network requires releasing their source.
+
+-- calculate_quantity_to_order, Demand-Based Reorder: the maximum order
+-- quantity caps ONE order, never the week's need. The total is the whole
+-- shortfall (at least the minimum, a whole order multiple); the TypeScript
+-- twin (computePlanningOrders, @carbon/utils planning-sizing.ts) splits it
+-- into orders of min(lotSize, maximumOrderQuantity). Capping the total left
+-- one order of the maximum per window and the rest of the need unplanned.
+-- Forked from 20260324120000_planning-quantity-to-order.sql.
+
+-- Helper function to calculate total quantity to order based on reorder policy
+CREATE OR REPLACE FUNCTION calculate_quantity_to_order(
+ p_reordering_policy "itemReorderingPolicy",
+ p_reorder_point INTEGER,
+ p_reorder_quantity INTEGER,
+ p_minimum_order_quantity INTEGER,
+ p_maximum_order_quantity INTEGER,
+ p_order_multiple INTEGER,
+ p_lot_size INTEGER,
+ p_maximum_inventory_quantity NUMERIC,
+ p_demand_accumulation_period INTEGER,
+ p_demand_accumulation_safety_stock NUMERIC,
+ p_projections NUMERIC[]
+) RETURNS NUMERIC AS $$
+DECLARE
+ ordered_quantity NUMERIC := 0;
+ num_periods INTEGER;
+ projected_stock NUMERIC;
+ projected_quantity NUMERIC;
+ remaining_needed NUMERIC;
+ total_order_qty NUMERIC;
+ order_qty NUMERIC;
+ required_qty NUMERIC;
+ i INTEGER;
+ j INTEGER;
+ iterations INTEGER;
+ window_length INTEGER;
+BEGIN
+ num_periods := COALESCE(array_length(p_projections, 1), 0);
+ IF num_periods = 0 THEN RETURN 0; END IF;
+
+ CASE p_reordering_policy
+ WHEN 'Manual Reorder' THEN
+ RETURN 0;
+
+ WHEN 'Demand-Based Reorder' THEN
+ -- A stored period of 0 (or NULL) never advanced the loop; one week at least,
+ -- as computePlanningOrders.
+ window_length := GREATEST(1, COALESCE(p_demand_accumulation_period, 1));
+ i := 1;
+ WHILE i <= num_periods LOOP
+ projected_stock := 0;
+ j := i;
+ WHILE j <= LEAST(i + window_length - 1, num_periods) LOOP
+ projected_stock := COALESCE(p_projections[j], 0) + ordered_quantity;
+ j := j + 1;
+ END LOOP;
+
+ IF projected_stock < p_demand_accumulation_safety_stock THEN
+ total_order_qty := p_demand_accumulation_safety_stock - projected_stock;
+
+ total_order_qty := GREATEST(total_order_qty, p_minimum_order_quantity);
+
+ IF p_order_multiple > 0 THEN
+ total_order_qty := CEIL(total_order_qty / p_order_multiple) * p_order_multiple;
+ END IF;
+
+ ordered_quantity := ordered_quantity + total_order_qty;
+ END IF;
+
+ i := i + window_length;
+ END LOOP;
+ RETURN ordered_quantity;
+
+ WHEN 'Fixed Reorder Quantity' THEN
+ FOR i IN 1..num_periods LOOP
+ projected_quantity := COALESCE(p_projections[i], 0);
+ remaining_needed := p_reorder_point - (projected_quantity + ordered_quantity);
+ iterations := 0;
+ WHILE remaining_needed > 0 AND iterations < 5 LOOP
+ IF p_reorder_quantity > 0 THEN
+ order_qty := p_reorder_quantity;
+ ELSE
+ order_qty := p_reorder_point;
+ END IF;
+
+ ordered_quantity := ordered_quantity + order_qty;
+ remaining_needed := p_reorder_point - (projected_quantity + ordered_quantity);
+ iterations := iterations + 1;
+ END LOOP;
+ END LOOP;
+ RETURN ordered_quantity;
+
+ WHEN 'Maximum Quantity' THEN
+ FOR i IN 1..num_periods LOOP
+ projected_quantity := COALESCE(p_projections[i], 0);
+ remaining_needed := p_reorder_point - (projected_quantity + ordered_quantity);
+ iterations := 0;
+ WHILE remaining_needed > 0 AND iterations < 5 LOOP
+ required_qty := p_maximum_inventory_quantity - (projected_quantity + ordered_quantity);
+
+ IF p_reorder_quantity > 0 THEN
+ order_qty := GREATEST(p_minimum_order_quantity, required_qty);
+ ELSE
+ order_qty := p_reorder_point;
+ END IF;
+
+ IF order_qty <= 0 THEN EXIT; END IF;
+
+ IF p_order_multiple > 1 THEN
+ order_qty := CEIL(order_qty / p_order_multiple) * p_order_multiple;
+ END IF;
+
+ IF p_lot_size > 0 THEN
+ order_qty := CEIL(order_qty / p_lot_size) * p_lot_size;
+ END IF;
+
+ IF p_maximum_order_quantity > 0 THEN
+ order_qty := LEAST(order_qty, p_maximum_order_quantity);
+ END IF;
+
+ ordered_quantity := ordered_quantity + order_qty;
+ remaining_needed := p_reorder_point - (projected_quantity + ordered_quantity);
+ iterations := iterations + 1;
+ END LOOP;
+ END LOOP;
+ RETURN ordered_quantity;
+
+ ELSE
+ RETURN 0;
+ END CASE;
+END;
+$$ LANGUAGE plpgsql IMMUTABLE;
diff --git a/packages/jobs/manifests/schema.json b/packages/jobs/manifests/schema.json
index 2bd5cf6ea7..cb4e113fae 100644
--- a/packages/jobs/manifests/schema.json
+++ b/packages/jobs/manifests/schema.json
@@ -1,11 +1,11 @@
{
"kind": "carbon-company-backup",
"version": 1,
- "schemaVersion": "20261012202451",
+ "schemaVersion": "20261013004700",
"sourceCompanyId": "schema-baseline",
"sourceCompanyGroupId": null,
"sourceCompanyName": null,
- "exportedAt": "2026-10-12T20:26:50.710Z",
+ "exportedAt": "2026-10-12T23:12:49.551Z",
"exportedBy": "schema-baseline",
"label": "schema baseline",
"includeStorage": "none",
diff --git a/packages/planning/src/index.ts b/packages/planning/src/index.ts
index c68f5e4acb..10be1fd028 100644
--- a/packages/planning/src/index.ts
+++ b/packages/planning/src/index.ts
@@ -10,6 +10,12 @@
// Material Requirements Planning.
export { type MrpPayload, type MrpResult, runMrp } from "./mrp/mrp.ts";
+// When open supply arrives (one rule for the projection, the reschedule check
+// and the item planning chart).
+export {
+ jobCompletionDate,
+ purchaseOrderLineArrivalDate
+} from "./mrp/supply-date.ts";
// Finite scheduling (formerly reached via @carbon/database/scheduling).
export {
type CalendarWindow,
diff --git a/packages/utils/src/planning-sizing.test.ts b/packages/utils/src/planning-sizing.test.ts
index 025812ee42..086e467ca3 100644
--- a/packages/utils/src/planning-sizing.test.ts
+++ b/packages/utils/src/planning-sizing.test.ts
@@ -129,9 +129,8 @@ describe("computePlanningOrders", () => {
}
});
- it("applies max OQ, min OQ, and order multiple", () => {
- // Shortfall 100, capped to maxOQ 30
- const capped = computePlanningOrders({
+ it("splits a shortfall past the maximum order quantity into several orders", () => {
+ const split = computePlanningOrders({
reorderingPolicy: "Demand-Based Reorder",
periods: weeklyPeriods(["2026-10-05"]),
projections: [0],
@@ -141,8 +140,66 @@ describe("computePlanningOrders", () => {
maximumOrderQuantity: 30
})
});
- expect(capped[0]?.quantity).toBe(30);
+ expect(split.map((o) => o.quantity)).toEqual([30, 30, 30, 10]);
+ // the next window sees the whole 100 as ordered
+ const covered = computePlanningOrders({
+ reorderingPolicy: "Demand-Based Reorder",
+ periods: weeklyPeriods(["2026-10-05", "2026-10-12"]),
+ projections: [0, 0],
+ todayDate: TODAY,
+ params: params({
+ demandAccumulationSafetyStock: 100,
+ maximumOrderQuantity: 30
+ })
+ });
+ expect(covered.map((o) => o.periodId)).toEqual(["p1", "p1", "p1", "p1"]);
+ });
+
+ it("keeps every split order on the order multiple and under the maximum", () => {
+ // need 100, multiple 10, max 25 → orders of 20 (25 floored to the multiple)
+ const orders = computePlanningOrders({
+ reorderingPolicy: "Demand-Based Reorder",
+ periods: weeklyPeriods(["2026-10-05"]),
+ projections: [0],
+ todayDate: TODAY,
+ params: params({
+ demandAccumulationSafetyStock: 100,
+ maximumOrderQuantity: 25,
+ orderMultiple: 10
+ })
+ });
+ expect(orders.map((o) => o.quantity)).toEqual([20, 20, 20, 20, 20]);
+ // a multiple larger than the maximum is the cap
+ const multipleWins = computePlanningOrders({
+ reorderingPolicy: "Demand-Based Reorder",
+ periods: weeklyPeriods(["2026-10-05"]),
+ projections: [0],
+ todayDate: TODAY,
+ params: params({
+ demandAccumulationSafetyStock: 25,
+ maximumOrderQuantity: 8,
+ orderMultiple: 10
+ })
+ });
+ expect(multipleWins.map((o) => o.quantity)).toEqual([10, 10, 10]);
+ });
+
+ it("splits by the smaller of batch size and maximum order quantity", () => {
+ const orders = computePlanningOrders({
+ reorderingPolicy: "Demand-Based Reorder",
+ periods: weeklyPeriods(["2026-10-05"]),
+ projections: [0],
+ todayDate: TODAY,
+ params: params({
+ demandAccumulationSafetyStock: 70,
+ lotSize: 50,
+ maximumOrderQuantity: 30
+ })
+ });
+ expect(orders.map((o) => o.quantity)).toEqual([30, 30, 10]);
+ });
+ it("applies min OQ and order multiple", () => {
// Shortfall 7, rounded up to multiple 5 → 10
const multiple = computePlanningOrders({
reorderingPolicy: "Demand-Based Reorder",
@@ -388,12 +445,32 @@ describe("orderSizingRules", () => {
orderMultiple: 10
})
).toEqual({
- perOrder: 50,
+ perOrder: 40,
daily: false,
maximum: 40,
minimum: 5,
multiples: [10]
});
+ // a batch alone sizes the order
+ expect(
+ orderSizingRules("Demand-Based Reorder", { ...item, lotSize: 50 })
+ ).toMatchObject({ perOrder: 50, maximum: 50 });
+ // a maximum off the multiple is floored to it; under the multiple, the
+ // multiple is the cap
+ expect(
+ orderSizingRules("Demand-Based Reorder", {
+ ...item,
+ maximumOrderQuantity: 25,
+ orderMultiple: 10
+ })
+ ).toMatchObject({ perOrder: 20, maximum: 20 });
+ expect(
+ orderSizingRules("Demand-Based Reorder", {
+ ...item,
+ maximumOrderQuantity: 8,
+ orderMultiple: 10
+ })
+ ).toMatchObject({ perOrder: 10, maximum: 10 });
});
it("Fixed Reorder Quantity: every order is the fixed quantity", () => {
@@ -491,6 +568,15 @@ describe("splitIntoOrders", () => {
"Demand-Based Reorder",
{ demandAccumulationSafetyStock: 120, lotSize: 50 },
[0]
+ ],
+ [
+ "Demand-Based Reorder",
+ {
+ demandAccumulationSafetyStock: 100,
+ maximumOrderQuantity: 25,
+ orderMultiple: 10
+ },
+ [0]
]
] as const)("round-trips the week %s sized", (policy, overrides, projections) => {
const orders = computePlanningOrders({
diff --git a/packages/utils/src/planning-sizing.ts b/packages/utils/src/planning-sizing.ts
index 8723a712c9..7f45aafc53 100644
--- a/packages/utils/src/planning-sizing.ts
+++ b/packages/utils/src/planning-sizing.ts
@@ -107,13 +107,38 @@ export type OrderSizingParams = Pick<
| "lotSize"
>;
+/** Integer floor to a multiple (float-artifact-immune). */
+const floorToMultiple = (value: number, multiple: number): number =>
+ round(value / multiple, 0, RoundingMode.Down) * multiple;
+
+/**
+ * What ONE Demand-Based Reorder order holds: the smaller of the batch size
+ * and the maximum order quantity (0 = no rule), floored to the order multiple
+ * when there is one (a multiple larger than the cap is the cap). 0: one order
+ * of any size.
+ */
+function demandBasedPerOrder(
+ lotSize: number,
+ maximumOrderQuantity: number,
+ orderMultiple: number
+): number {
+ const limits = [lotSize, maximumOrderQuantity].filter((n) => n > 0);
+ if (limits.length === 0) return 0;
+ const limit = Math.min(...limits);
+ if (orderMultiple > 0) {
+ return Math.max(orderMultiple, floorToMultiple(limit, orderMultiple));
+ }
+ return limit;
+}
+
/**
* How ONE order of a reordering policy is sized — the same rules
* `computePlanningOrders` applies, stated once so what happens after sizing
* keeps them:
* - `perOrder`: the quantity one order holds when a need takes several —
- * the batch size (Demand-Based Reorder), the fixed reorder quantity, or the
- * maximum order quantity (Maximum Quantity). 0: one order of any size.
+ * the batch size or maximum order quantity (Demand-Based Reorder,
+ * `demandBasedPerOrder`), the fixed reorder quantity, or the maximum order
+ * quantity (Maximum Quantity). 0: one order of any size.
* - `daily`: several orders in a week fall one per day (Fixed Reorder
* Quantity, Maximum Quantity), not spread across it (batches).
* - `maximum`: the most one order may hold. 0: no limit.
@@ -142,11 +167,15 @@ export function orderSizingRules(
const orderMultiple = Number(params.orderMultiple) || 0;
switch (policyName) {
case "Demand-Based Reorder": {
- const limits = [lotSize, maximumOrderQuantity].filter((n) => n > 0);
+ const perOrder = demandBasedPerOrder(
+ lotSize,
+ maximumOrderQuantity,
+ orderMultiple
+ );
return {
- perOrder: lotSize,
+ perOrder,
daily: false,
- maximum: limits.length > 0 ? Math.min(...limits) : 0,
+ maximum: perOrder,
minimum: minimumOrderQuantity,
multiples: [orderMultiple]
};
@@ -292,13 +321,8 @@ export function computePlanningOrders(
demandAccumulationSafetyStock - endOfWindowProjection
);
- // Apply lot sizing rules
- if (maximumOrderQuantity > 0) {
- totalOrderQuantity = Math.min(
- totalOrderQuantity,
- maximumOrderQuantity
- );
- }
+ // Apply lot sizing rules to the need; the maximum order quantity
+ // caps each order below, never the need.
totalOrderQuantity = Math.max(totalOrderQuantity, minimumOrderQuantity);
if (orderMultiple > 0) {
@@ -309,7 +333,12 @@ export function computePlanningOrders(
}
// One order per batch, due dates spread across the period
- for (const batch of lotSizeBatches(totalOrderQuantity, lotSize)) {
+ const perOrder = demandBasedPerOrder(
+ lotSize,
+ maximumOrderQuantity,
+ orderMultiple
+ );
+ for (const batch of lotSizeBatches(totalOrderQuantity, perOrder)) {
const dueDate = parseDate(currentPeriod.startDate).add({
days: batch.dayOffset
});