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): date each Demand-Based Reorder batch in the week it is needed (#1912)

Naveen Kashyapc59336eaaf9b
diff --git a/.ai/runs/2026-10-13-dbr-batches-deferred.md b/.ai/runs/2026-10-13-dbr-batches-deferred.md
new file mode 100644
index 0000000000..d252b2be8d
--- /dev/null
+++ b/.ai/runs/2026-10-13-dbr-batches-deferred.md
@@ -0,0 +1,24 @@
+# Bugfix run: Demand-Based Reorder batches are Deferred right after they are raised
+
+- Date: 2026-10-13
+- Mode: fully-autonomous
+- Request: "When raising a PO, the date on the suggestion appears to be 1 month earlier than it should. When you raise it, you immediately then get a suggestion to defer it by 1 month."
+- Phase plan: root-cause [done earlier in session — HIGH] · instrument [skip — deterministic repro] · fix [run] · test [skip — pure logic, regression test covers it] · commit [run — user asked for a PR]
+
+## Decisions
+
+- Batch dates: each batch is due in the week its share of the demand is needed (user choice) — matches the reschedule check — 2026-10-13
+- Scope: only `computePlanningOrders` (Demand-Based Reorder branch). Its only caller is `generatePlanningActions`; the drawer re-split (`splitIntoOrders`) round-trips per week because batches keep their order (full batches first, remainder last).
+
+## Phase log
+
+- root-cause: HIGH. The Demand-Based Reorder branch dates every batch in the first short week. `deriveChangeActions` judges each PO line by the first demand it covers, so later batches read as early and get a Defer.
+
+- fix: `computePlanningOrders` Demand-Based Reorder branch dates each batch at the first week the projection, plus every earlier batch, is under safety stock; batches sharing a week spread across its days in sizing order, across windows too. Red→green: 2 sizing tests + 1 planning test failed before (all batches in p1; 2 Defers), pass after.
+- fuzz (3,000 random items, scratch test, deleted): Demand-Based Reorder Defers 4,300 → 0. Fixed Reorder Quantity / Maximum Quantity counts unchanged. Demand-Based Reorder Decreases 431 → 498: all on items with a minimum, multiple, batch or max; previously masked by the Defer (one action per order). Existing behavior, not new.
+- gates: biome PASS · typecheck(@carbon/utils, @carbon/planning) PASS · test(@carbon/utils 734, @carbon/planning 324) PASS · erp planning tests (10 files, 118) PASS
+- test: skipped — pure logic, regression tests cover it
+
+## Outcome
+
+- Committed `ab4a68fcf8`; PR #1912 (https://github.com/crbnos/carbon/pull/1912)
diff --git a/.claude/rules/mrp-system.md b/.claude/rules/mrp-system.md
index d390dc5b1f..345a5e4b0d 100644
--- a/.claude/rules/mrp-system.md
+++ b/.claude/rules/mrp-system.md
@@ -292,7 +292,12 @@ Their `demand_data` CTEs read the projection arm net of consumption
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.
+ only as a rounding multiple. In `computePlanningOrders` each Demand-Based
+ Reorder batch is due in the week its share is needed (the first week the
+ projection plus every earlier batch is under safety stock), not all in the
+ window's first short week: `deriveChangeActions` dates a PO line by the
+ first demand it covers, so later batches dated in week 1 were Deferred as
+ soon as they were raised.
- 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
diff --git a/packages/planning/src/mrp/planning-actions.test.ts b/packages/planning/src/mrp/planning-actions.test.ts
index e6ed92c640..3d73d97b48 100644
--- a/packages/planning/src/mrp/planning-actions.test.ts
+++ b/packages/planning/src/mrp/planning-actions.test.ts
@@ -1454,6 +1454,68 @@ describe("projectionsWithExpedites", () => {
});
});
+// Raising what MRP suggests must not earn a Defer on the next run. A
+// Demand-Based Reorder order split into batches was dated all in the window's
+// first week, while the reschedule check dates each PO line by the first
+// demand it covers — the later batches were deferred as soon as they existed.
+describe("Demand-Based Reorder batches raised as suggested", () => {
+ it("get no Defer from the reschedule check", () => {
+ const periods = [
+ { id: "w1", startDate: "2026-10-11" },
+ { id: "w2", startDate: "2026-10-18" },
+ { id: "w3", startDate: "2026-10-25" },
+ { id: "w4", startDate: "2026-11-01" },
+ { id: "w5", startDate: "2026-11-08" }
+ ];
+ const demand = [25, 25, 25, 25, 0];
+ let balance = 0;
+ const projections = demand.map((quantity) => (balance -= quantity));
+ const suggestions = computePlanningOrders({
+ reorderingPolicy: "Demand-Based Reorder",
+ periods,
+ projections,
+ todayDate: "2026-10-11",
+ params: {
+ reorderPoint: 0,
+ reorderQuantity: 0,
+ minimumOrderQuantity: 0,
+ maximumOrderQuantity: 0,
+ orderMultiple: 0,
+ lotSize: 25,
+ maximumInventoryQuantity: 0,
+ demandAccumulationPeriod: 4,
+ demandAccumulationSafetyStock: 0,
+ leadTime: 0
+ }
+ });
+ expect(suggestions).toHaveLength(4);
+
+ const actions = deriveChangeActions({
+ onHand: 0,
+ demandPeriods: periods
+ .map((p, i) => ({
+ periodId: p.id,
+ startDate: p.startDate,
+ quantity: demand[i]!
+ }))
+ .filter((d) => d.quantity > 0),
+ // the Order button writes each suggestion's due date as the line's
+ // required date, which is its arrival date until a supplier promises one
+ openOrders: suggestions.map((s, i) => ({
+ purchaseOrderLineId: `line-${i + 1}`,
+ quantity: s.quantity,
+ dueDate: s.dueDate,
+ requiresManualAction: false
+ })),
+ periods,
+ policyFloor: 0,
+ toleranceDays: TOLERANCE,
+ todayDate: "2026-10-11"
+ });
+ expect(actions).toEqual([]);
+ });
+});
+
// The whole new-supply path for one item, as generatePlanningActions runs it:
// the change actions, then sizing on the adjusted projection, then the fold
// into an open order.
diff --git a/packages/utils/src/planning-sizing.test.ts b/packages/utils/src/planning-sizing.test.ts
index 086e467ca3..88eda5365a 100644
--- a/packages/utils/src/planning-sizing.test.ts
+++ b/packages/utils/src/planning-sizing.test.ts
@@ -2,6 +2,7 @@
// 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.
+import { parseDate } from "@internationalized/date";
import { describe, expect, it } from "vitest";
import type { PlanningSizingParams } from "./planning-sizing";
import {
@@ -246,6 +247,53 @@ describe("computePlanningOrders", () => {
"2026-10-09"
]);
});
+
+ // The reschedule check dates each order by the first demand it covers.
+ // Dated all in the window's first week, the batches for weeks 3 and 4
+ // read as early and got a Defer the moment they were raised.
+ it("dates each batch in the week its share of the window is needed", () => {
+ const orders = computePlanningOrders({
+ reorderingPolicy: "Demand-Based Reorder",
+ periods: weeklyPeriods([
+ "2026-10-05",
+ "2026-10-12",
+ "2026-10-19",
+ "2026-10-26"
+ ]),
+ projections: [-25, -50, -75, -100],
+ todayDate: TODAY,
+ params: params({ demandAccumulationPeriod: 4, lotSize: 25 })
+ });
+ expect(orders.map((o) => [o.periodId, o.dueDate, o.quantity])).toEqual([
+ ["p1", "2026-10-05", 25],
+ ["p2", "2026-10-12", 25],
+ ["p3", "2026-10-19", 25],
+ ["p4", "2026-10-26", 25]
+ ]);
+ expect(orders.map((o) => o.startDate)).toEqual([
+ "2026-09-28",
+ "2026-10-05",
+ "2026-10-12",
+ "2026-10-19"
+ ]);
+ });
+
+ it("spreads the batches one week needs across that week", () => {
+ // 60 short in p1 and 20 more in p2, batches of 20: three in p1, one in p2
+ const orders = computePlanningOrders({
+ reorderingPolicy: "Demand-Based Reorder",
+ periods: weeklyPeriods(["2026-10-05", "2026-10-12"]),
+ projections: [-60, -80],
+ todayDate: TODAY,
+ params: params({ demandAccumulationPeriod: 2, lotSize: 20 })
+ });
+ expect(orders.map((o) => [o.periodId, o.dueDate])).toEqual([
+ ["p1", "2026-10-05"],
+ ["p1", "2026-10-07"],
+ ["p1", "2026-10-09"],
+ ["p2", "2026-10-12"]
+ ]);
+ });
});
describe("Fixed Reorder Quantity", () => {
@@ -594,6 +642,43 @@ describe("splitIntoOrders", () => {
)
).toEqual(orders.map((o) => o.quantity));
});
+
+ // Demand-Based Reorder batches land in the week each is needed, and MRP
+ // sums each week into one action: every week's split must give back that
+ // week's batches, due dates included.
+ it("round-trips Demand-Based Reorder batches spread over several weeks", () => {
+ const overrides = { demandAccumulationPeriod: 4, lotSize: 25 };
+ const orders = computePlanningOrders({
+ reorderingPolicy: "Demand-Based Reorder",
+ periods: weeklyPeriods([
+ "2026-10-05",
+ "2026-10-12",
+ "2026-10-19",
+ "2026-10-26"
+ ]),
+ projections: [-50, -60, -75, -95],
+ todayDate: TODAY,
+ params: params(overrides)
+ });
+ const rules = orderSizingRules("Demand-Based Reorder", params(overrides));
+ const weeks = [...new Set(orders.map((o) => o.periodId))];
+ // 95 short: two batches for p1, one for p2, the remainder for p4 (p3 is
+ // exactly covered)
+ expect(weeks).toEqual(["p1", "p2", "p4"]);
+ for (const week of weeks) {
+ const inWeek = orders.filter((o) => o.periodId === week);
+ const total = inWeek.reduce((sum, o) => sum + o.quantity, 0);
+ const weekStart = inWeek[0]!.dueDate;
+ expect(
+ splitIntoOrders(total, rules).map((o) => ({
+ quantity: o.quantity,
+ dueDate: parseDate(weekStart).add({ days: o.dayOffset }).toString()
+ }))
+ ).toEqual(
+ inWeek.map((o) => ({ quantity: o.quantity, dueDate: o.dueDate }))
+ );
+ }
+ });
});
describe("reducedOrderQuantity", () => {
diff --git a/packages/utils/src/planning-sizing.ts b/packages/utils/src/planning-sizing.ts
index 7f45aafc53..985d95b6c5 100644
--- a/packages/utils/src/planning-sizing.ts
+++ b/packages/utils/src/planning-sizing.ts
@@ -289,6 +289,11 @@ export function computePlanningOrders(
1,
round(Number(demandAccumulationPeriod) || 1, 0, RoundingMode.Down)
);
+ const batches: {
+ periodIndex: number;
+ quantity: number;
+ projectedStock: number;
+ }[] = [];
for (let i = 0; i < periods.length; i += windowLength) {
const windowEnd = Math.min(i + windowLength, periods.length);
@@ -332,36 +337,80 @@ export function computePlanningOrders(
);
}
- // One order per batch, due dates spread across the period
+ // One order per batch, each due in the week its share is needed: the
+ // first week the projection, with every batch before it, is still
+ // under safety stock. The reschedule check dates an order by the
+ // first demand it covers, so a batch for week 3 due in week 1 read
+ // as early and was deferred as soon as it was raised. A batch no
+ // later week needs (rounded up past the shortfall) stays with the
+ // one before it.
const perOrder = demandBasedPerOrder(
lotSize,
maximumOrderQuantity,
orderMultiple
);
+ let neededPeriod = firstDipIndex;
+ let orderedBefore = orderedQuantity;
for (const batch of lotSizeBatches(totalOrderQuantity, perOrder)) {
- const dueDate = parseDate(currentPeriod.startDate).add({
- days: batch.dayOffset
- });
- const startDate = dueDate.subtract({ days: leadTime });
-
- orders.push({
- startDate: startDate.toString(),
- dueDate: dueDate.toString(),
+ let j = neededPeriod;
+ while (
+ j < periods.length &&
+ (projections[j] || 0) + orderedBefore >=
+ demandAccumulationSafetyStock
+ ) {
+ j++;
+ }
+ if (j < periods.length) neededPeriod = j;
+ batches.push({
+ periodIndex: neededPeriod,
quantity: batch.quantity,
- periodId: currentPeriod.id,
- isASAP: startDate.compare(todaysDate) < 0,
- policyName: "Demand-Based Reorder",
- triggerValues: {
- projectedStock: endOfWindowProjection,
- safetyStock: demandAccumulationSafetyStock,
- lotSize,
- leadTime
- }
+ projectedStock: endOfWindowProjection
});
+ orderedBefore += batch.quantity;
}
orderedQuantity += totalOrderQuantity;
}
+
+ // Batches sharing a week spread across its days in the order they were
+ // sized — across windows too, since a surplus batch can land in a later
+ // window's week — so an earlier batch is never due after a later one.
+ const batchesInWeek = new Map<number, number>();
+ for (const batch of batches) {
+ batchesInWeek.set(
+ batch.periodIndex,
+ (batchesInWeek.get(batch.periodIndex) ?? 0) + 1
+ );
+ }
+ const placedInWeek = new Map<number, number>();
+ for (const batch of batches) {
+ const period = periods[batch.periodIndex];
+ if (!period) continue;
+ const indexInWeek = placedInWeek.get(batch.periodIndex) ?? 0;
+ placedInWeek.set(batch.periodIndex, indexInWeek + 1);
+ const dueDate = parseDate(period.startDate).add({
+ days: intFloorDiv(
+ indexInWeek * DAYS_IN_PERIOD,
+ batchesInWeek.get(batch.periodIndex) ?? 1
+ )
+ });
+ const startDate = dueDate.subtract({ days: leadTime });
+
+ orders.push({
+ startDate: startDate.toString(),
+ dueDate: dueDate.toString(),
+ quantity: batch.quantity,
+ periodId: period.id,
+ isASAP: startDate.compare(todaysDate) < 0,
+ policyName: "Demand-Based Reorder",
+ triggerValues: {
+ projectedStock: batch.projectedStock,
+ safetyStock: demandAccumulationSafetyStock,
+ lotSize,
+ leadTime
+ }
+ });
+ }
return orders;
}
case "Fixed Reorder Quantity": {