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): MRP suggestions honor batch size, order rules, frozen orders (#1869)

Brad Barbin1bdcc4b121cb
diff --git a/.claude/rules/mrp-system.md b/.claude/rules/mrp-system.md
index c4aedd764f..a64541004e 100644
--- a/.claude/rules/mrp-system.md
+++ b/.claude/rules/mrp-system.md
@@ -420,6 +420,26 @@ never offered a Cancel, Defer or Expedite.
Increase on a PO line are rounded up to the purchase multiple, and a line
already at it gets no action. An Increase names the PO line's supplier, not
the item's preferred one.
+- **A frozen order is never Expedited, Increased or Decreased**
+ (`isOrderFrozen`): its due date less the item's lead time is before today —
+ every overdue order, and one due sooner than a lead time away. It is already
+ being made or shipped, so none of the three can be carried out. A shortfall
+ it would have absorbed stays a new Order / Make (`convertOrdersToIncreases`
+ skips it), and a frozen order late beyond the tolerance is left where it
+ lands in the sizing projection (`firstNeedPeriodByOrder`'s `frozen`
+ argument), so the need it misses gets new supply instead of a silent gap.
+ Defer, Cancel and Release are unchanged. Before this an overdue job got
+ "Increase from 111 to 131" beside a Make for the same week.
+- **Change actions keep the policy's order rules** (`orderSizingRules`, the
+ same definition the page split reads). A Decrease keeps the policy's
+ minimum and lands on its whole multiples — `orderMultiple`, a Fixed Reorder
+ Quantity order's fixed quantity, a Maximum Quantity order's lot size
+ (`reducedOrderQuantity`, `orderRules` on `deriveChangeActions`). A new-supply
+ suggestion folds into an open order only when the result fits the policy's
+ `maximum` — a batch or the max order quantity, the fixed reorder quantity
+ (`maximumPerOrder` on `convertOrdersToIncreases`); otherwise it stays a new
+ Order / Make. Before this a 50-unit batch job was offered "Increase to 100"
+ and a 40 on a multiple of 10 "Decrease to 37".
- `deriveChangeActions` claims the policy floor (safety stock, reorder point,
minimum reserve) FIRST — from on-hand, then the earliest orders — and an
order holding part of it is never Cancelled, Decreased or Deferred. The floor
@@ -477,10 +497,24 @@ never offered a Cancel, Defer or Expedite.
and a bulk order for rows never opened all read the item's OPEN new-supply
actions (`openNewSupplyActions` + `plannedOrdersFromActions` /
`productionOrdersFromActions`, `ui/Planning/planned-orders-from-actions.ts`,
- tested by `apps/erp/test/planned-orders-from-actions.test.ts`): one row per
- action, on the action's own week, in purchase units for a PO (rounded up by
- the chosen supplier part's factor). They used to be sized again in the
- browser from the weekly projections (`calculateOrders`), which missed what
+ tested by `apps/erp/test/planned-orders-from-actions.test.ts`): each action
+ split back into the orders its policy sized, on the action's own week, in
+ purchase units for a PO (rounded up by the chosen supplier part's factor).
+ MRP sums the orders a week needs into one action (the natural key), so
+ `splitIntoOrders` + `orderSizingRules` (`@carbon/utils`, by the action's
+ `policyName`) restore them: Demand-Based Reorder one per batch (`lotSize`)
+ spread across the week, Fixed Reorder Quantity one of that quantity per
+ day, Maximum Quantity one of at most `maximumOrderQuantity` per day; Stock
+ Only one order. A round-trip test pins the split to `computePlanningOrders`.
+ One order per action turned a 120 on a batch size of 50 into one job of
+ 120 and three fixed reorders of 100 into one order of 300. Each suggested
+ job carries the action's `policyName` / `reason` / `triggerValues` (the
+ chart's order popover reads them), and its `isASAP` is judged per job
+ against the page's `locationToday` from its OWN start date — the action's
+ flag is one per week as of the run (Maximum Quantity keeps the run's flag
+ as a condition, since only the run knows the stock was short). It becomes
+ the created job's `deadlineType`. They
+ used to be sized again in the browser from the weekly projections (`calculateOrders`), which missed what
MRP does after sizing — moving expedited supply, folding a shortfall into
an open order as an Increase, summing each week into one action — so the
drawer showed daily 10s against weekly 50s and offered a new order for the
@@ -685,6 +719,17 @@ never offered a Cancel, Defer or Expedite.
amount is stored. A failed follow-up on a saved job edit (recalculating
requirements, telling the scheduler) is reported as a warning, never a
revert — the edit stands.
+ A Draft job (listed, editable, charted as new supply, but NOT MRP supply)
+ shows a **Plan** button when no action targets it (`renderRowCommand`):
+ `planning.update` `planJob` checks the location, that no sales order owns
+ it and that it is Draft, then `planDraftJob` (`production.server.ts`) recalculates
+ its requirements (a failure leaves it Draft, as `releaseJobs` does), flips
+ it to Planned (`updateJobStatus` `fromStatuses: ["Draft"]`) and runs MRP —
+ after the flip, so the run counts it and the Make suggestion shrinks by
+ it. No scheduler notice: only released jobs are scheduled. The drawer then drops the item's draft
+ list to re-seed. Before this a Draft job and a Make for the same need sat
+ side by side and could both be built (the pre-#1601 drawer promoted
+ Drafts through `order`, which now refuses existing jobs).
Locked rows render as plain cells
(`Grid isRowEditable`). Each row carries the planning action that targets
it — type, suggested value, reason, Apply / Review — so there is no
diff --git a/apps/erp/app/modules/production/AGENTS.md b/apps/erp/app/modules/production/AGENTS.md
index 19945caa75..f754517cee 100644
--- a/apps/erp/app/modules/production/AGENTS.md
+++ b/apps/erp/app/modules/production/AGENTS.md
@@ -109,7 +109,7 @@ pnpm --filter @carbon/erp test
- `getProductionPlanning` — MRP-driven production planning (RPC `get_production_planning_grid`, latest migration `20261006205037`: wraps `get_production_planning` and adds the item group, the planning-horizon fence date, the first negative week, the latest order date and `orderQuantity` — the open Make actions inside the fence, which the default sort uses (the Order / Make button shows the quantity; there is no Qty to Order column), not the base RPC's `quantityToOrder`; `asOf` is the location's today, and `actionTypes` / `actionAssignees` filter on OPEN planning actions inside each item's fence, in the database)
- `nextJobPriority(siblings, deadlineType)` — pure: a job's fractional priority among the jobs already on its date, by deadline type; `calculateJobPriority` reads the siblings and calls it, the planning date apply places a batch with it. `deadlineTypeForPlanningDate(deadlineType)` — the type a job carries once planning gives it a date (No Deadline → Soft Deadline)
- `cancelJob` (`production.server.ts`) — the one cancel path, used by `x+/job+/$jobId.status.tsx` and planning's Cancel action: returns the job's unconsumed picked material, cancels its open picking-list lines, then sets Cancelled and clears the assignee; stops at the first failure, before the status changes. Planning edits a job only while `isJobEditableFromPlanning` (`production.models.ts`: Draft / Planned)
-- `getPlanningActions` / `getPlanningActionsByIds` — the persisted MRP worklist (`planningAction`, written by `generatePlanningActions` in `@carbon/planning` after every MRP run; statuses `Open` / `Dismissed` / `Actioned`). `dismissPlanningActions` / `reopenDismissedPlanningActions` (Dismissed ↔ Open; both return the ids they changed, which the routes report), `markPlanningActionsActioned` (the conditional Open → Actioned claim that is the apply path's lock — an empty result means another apply got there first; it returns the row's suggested quantity and date, which Apply writes instead of the page's possibly stale read) and `reopenPlanningActions` (its rollback, Actioned → Open), `assignPlanningActions` (sets the assignee and marks it overridden so the next MRP run keeps it; Open and Dismissed rows only, returning the ids it changed). `settleNewSupplyPlanningActions` is the page's Order button's settle: the suggested orders it submits carry no action id, so after the PO lines (`Order`) or jobs (`Make`) are created it flips the Open / Dismissed action of each ordered (item, week) pair at the location to Actioned — otherwise the suggestion stayed on the page beside its order until the next MRP run. An Apply reads its actions (`getPlanningActionsByIds`) and their jobs / PO lines in one statement each (Kysely, the ids as parameters — never a PostgREST URL), then applies set-based: `applyProductionPlanningDateActions(db, …)` moves every Expedite / Defer in one transaction (the claim, the jobs, the jobs already on the target dates, one UPDATE of due date + deadline type + priority via the pure `nextJobPriority` — a "No Deadline" job becomes `Soft Deadline`, `deadlineTypeForPlanningDate`, since the job form hides the due date for No Deadline), and the route sends one `schedule-inputs-changed` event for the batch; Increase / Decrease / Cancel call server functions with their own transactions, so they run per job, three jobs at a time, each claimed right before its change. The transaction-scoped claim and release live in `planning-action-claims.ts` (`claimPlanningActions` / `releasePlanningActionClaims`), shared with purchasing's `applyPurchasingPlanningActions`. Bad input to either planning route answers 400, a failed read or write 500. `releasePlanningActionClaim` gives a failed per-job apply's claim back (deleting it instead when MRP has already written an Open row for the same need), and `updatePlanningJob` is planning's single-job write (the drawer's inline edit, and Increase / Decrease), guarded on Draft / Planned in the UPDATE itself; a quantity change restates `scrapQuantity` from the item's scrap rate. `planningAction` is read-only through the API; its writers use the service role. Applied from `x+/production+/planning.update.tsx` and `x+/purchasing+/planning.update.tsx`; UI in `ui/Planning/`: `ProductionPlanningTable` + `ProductionPlanningOrderDrawer`, `planningColumns.tsx` (the column set shared with purchasing: the Stock Availability week strip via `PlanningWeekStrip` + `planning-week-geometry.ts`, `LatestOrderDate`, `PlanningFence` + `planning-fence.ts`), `PlanningActionLines` (the expanded row), `PlanningOrderGrids` + `PlanningDrawerParts` (the drawer's suggested / open-order grids, `periodIdFor`, the "N More After" button), `usePlanningActions` (the dismiss / reopen / assign / apply fetcher), and `planning-action-scope.ts` (`resolvePlanningActionScope`, `actionsOfTypes`, `PLANNING_ACTIONS_COLUMN`, `PLANNING_ASSIGNEE_COLUMN`, `PLANNING_DRAWER_PARAM` — pure, re-exported from `production.models.ts` so vitest can import it), `planned-orders-from-actions.ts` (pure: the drawer's suggested orders, the row's Order / Make quantity and a bulk order are the item's open Order / Make actions — `openNewSupplyActions`, `plannedOrdersFromActions`, `productionOrdersFromActions`, `supplierConversionFactor` — never sized again on screen, so a shortfall MRP folded into an Increase is not offered twice), `planning-increase.ts` (pure: `chartedOrderQuantity` charts an order at its open Increase), and `planning-review.ts` (pure: `planningActionNeedsReview` — Review vs Apply from the order's LIVE status, `purchaseOrderStatus` / `jobStatus` from `getPlanningActions`, not MRP's run-time `requiresManualAction` stamp, so a PO reopened since applies at once; a date move on a supplier-promised line stays Review — and `purchaseOrderPlanningMenu`, which order commands a row's ⋯ offers; `PlanningActionHandlers.purchaseOrderMenuItems` carries them, purchasing only). Both planning grids put the open order drawer's item in the address (`?item=<itemId>`, `useLinkedDrawerItem` in `~/hooks/useDrawerItem`), so a link reopens it; the loader reads that row on its own (`drawerItem`) when it is not on the page. Tests: `planning-action-writes.test.ts`, `apps/erp/test/apply-production-planning-date-actions.test.ts`, `planning-action-scope.test.ts`, `planning-fence.test.ts`, `planning-increase.test.ts`, `planning-review.test.ts`, `planned-orders-from-actions.test.ts`, `planning-week-geometry.test.ts`
+- `getPlanningActions` / `getPlanningActionsByIds` — the persisted MRP worklist (`planningAction`, written by `generatePlanningActions` in `@carbon/planning` after every MRP run; statuses `Open` / `Dismissed` / `Actioned`). `dismissPlanningActions` / `reopenDismissedPlanningActions` (Dismissed ↔ Open; both return the ids they changed, which the routes report), `markPlanningActionsActioned` (the conditional Open → Actioned claim that is the apply path's lock — an empty result means another apply got there first; it returns the row's suggested quantity and date, which Apply writes instead of the page's possibly stale read) and `reopenPlanningActions` (its rollback, Actioned → Open), `assignPlanningActions` (sets the assignee and marks it overridden so the next MRP run keeps it; Open and Dismissed rows only, returning the ids it changed). `settleNewSupplyPlanningActions` is the page's Order button's settle: the suggested orders it submits carry no action id, so after the PO lines (`Order`) or jobs (`Make`) are created it flips the Open / Dismissed action of each ordered (item, week) pair at the location to Actioned — otherwise the suggestion stayed on the page beside its order until the next MRP run. An Apply reads its actions (`getPlanningActionsByIds`) and their jobs / PO lines in one statement each (Kysely, the ids as parameters — never a PostgREST URL), then applies set-based: `applyProductionPlanningDateActions(db, …)` moves every Expedite / Defer in one transaction (the claim, the jobs, the jobs already on the target dates, one UPDATE of due date + deadline type + priority via the pure `nextJobPriority` — a "No Deadline" job becomes `Soft Deadline`, `deadlineTypeForPlanningDate`, since the job form hides the due date for No Deadline), and the route sends one `schedule-inputs-changed` event for the batch; Increase / Decrease / Cancel call server functions with their own transactions, so they run per job, three jobs at a time, each claimed right before its change. The transaction-scoped claim and release live in `planning-action-claims.ts` (`claimPlanningActions` / `releasePlanningActionClaims`), shared with purchasing's `applyPurchasingPlanningActions`. Bad input to either planning route answers 400, a failed read or write 500. `releasePlanningActionClaim` gives a failed per-job apply's claim back (deleting it instead when MRP has already written an Open row for the same need), and `updatePlanningJob` is planning's single-job write (the drawer's inline edit, and Increase / Decrease), guarded on Draft / Planned in the UPDATE itself; a quantity change restates `scrapQuantity` from the item's scrap rate. `planDraftJob` (`production.server.ts`) is the drawer's Plan on a Draft job (`planJob` intent), in `releaseJobs`' order: the requirements recalculation (a failure leaves the job Draft), the guarded Draft → Planned flip, then MRP, so the job counts as supply. It sends no scheduler notice — the scheduler places only released jobs. `replanAfterItemChange` (`production.server.ts`) runs MRP after an item's planning or manufacturing settings are saved, so the planning pages follow them at once. `planningAction` is read-only through the API; its writers use the service role. Applied from `x+/production+/planning.update.tsx` and `x+/purchasing+/planning.update.tsx`; UI in `ui/Planning/`: `ProductionPlanningTable` + `ProductionPlanningOrderDrawer`, `planningColumns.tsx` (the column set shared with purchasing: the Stock Availability week strip via `PlanningWeekStrip` + `planning-week-geometry.ts`, `LatestOrderDate`, `PlanningFence` + `planning-fence.ts`), `PlanningActionLines` (the expanded row), `PlanningOrderGrids` + `PlanningDrawerParts` (the drawer's suggested / open-order grids, `periodIdFor`, the "N More After" button), `usePlanningActions` (the dismiss / reopen / assign / apply fetcher), and `planning-action-scope.ts` (`resolvePlanningActionScope`, `actionsOfTypes`, `PLANNING_ACTIONS_COLUMN`, `PLANNING_ASSIGNEE_COLUMN`, `PLANNING_DRAWER_PARAM` — pure, re-exported from `production.models.ts` so vitest can import it), `planned-orders-from-actions.ts` (pure: the drawer's suggested orders, the row's Order / Make quantity and a bulk order are the item's open Order / Make actions — `openNewSupplyActions`, `plannedOrdersFromActions`, `productionOrdersFromActions`, `supplierConversionFactor` — never sized again on screen, so a shortfall MRP folded into an Increase is not offered twice), `planning-increase.ts` (pure: `chartedOrderQuantity` charts an order at its open Increase), and `planning-review.ts` (pure: `planningActionNeedsReview` — Review vs Apply from the order's LIVE status, `purchaseOrderStatus` / `jobStatus` from `getPlanningActions`, not MRP's run-time `requiresManualAction` stamp, so a PO reopened since applies at once; a date move on a supplier-promised line stays Review — and `purchaseOrderPlanningMenu`, which order commands a row's ⋯ offers; `PlanningActionHandlers.purchaseOrderMenuItems` carries them, purchasing only). Both planning grids put the open order drawer's item in the address (`?item=<itemId>`, `useLinkedDrawerItem` in `~/hooks/useDrawerItem`), so a link reopens it; the loader reads that row on its own (`drawerItem`) when it is not on the page. Tests: `planning-action-writes.test.ts`, `apps/erp/test/apply-production-planning-date-actions.test.ts`, `planning-action-scope.test.ts`, `planning-fence.test.ts`, `planning-increase.test.ts`, `planning-review.test.ts`, `planned-orders-from-actions.test.ts`, `planning-week-geometry.test.ts`
- `upsertMaintenanceDispatch` / `upsertMaintenanceSchedule` — maintenance management
- `updateAssemblyStepHiddenComponents` — autosave for a step's hidden list (route `x+/assembly+/$id.steps.hidden.$stepId.tsx`). The rule "a step never hides its own parts" lives in ONE place, the `assembly_step_strip_own_hidden_components` BEFORE trigger (migration `20260925063121`), which strips + dedupes on every insert/update of either array — no service strips it by hand.
- `getAssemblyInstruction(s)` / `upsertAssemblyInstructionStep` / `getAssemblyInstructionStepMaterials` — assembly instruction authoring; the step upsert derives `instructionText` from the tiptap `description` (viewer/MES consume the plain text)
diff --git a/apps/erp/app/modules/production/production.models.ts b/apps/erp/app/modules/production/production.models.ts
index 476fa06051..5cdbf42564 100644
--- a/apps/erp/app/modules/production/production.models.ts
+++ b/apps/erp/app/modules/production/production.models.ts
@@ -6,6 +6,7 @@ import type { Database } from "@carbon/database";
import { parseDate } from "@internationalized/date";
import { z } from "zod";
import { zfd } from "zod-form-data";
+import { plannedOrderValidator } from "../purchasing/purchasing.models";
import {
methodItemType,
methodOperationOrders,
@@ -1058,7 +1059,13 @@ export const productionOrderValidator = z.object({
existingQuantity: zfd.numeric(z.number().optional()),
existingReadableId: zfd.text(z.string().optional()),
existingStatus: zfd.text(z.enum(jobStatus).optional()),
- isASAP: z.boolean().optional()
+ isASAP: z.boolean().optional(),
+ // Reorder-policy attribution, copied from the Make action (absent on a job
+ // the planner added): the chart's order popover explains the suggestion
+ // from it, as it does for a purchase order.
+ policyName: plannedOrderValidator.shape.policyName,
+ reason: plannedOrderValidator.shape.reason,
+ triggerValues: plannedOrderValidator.shape.triggerValues
});
export type ProductionOrder = z.infer<typeof productionOrderValidator>;
diff --git a/apps/erp/app/modules/production/production.server.ts b/apps/erp/app/modules/production/production.server.ts
index 8bd483c75d..0113eb9fec 100644
--- a/apps/erp/app/modules/production/production.server.ts
+++ b/apps/erp/app/modules/production/production.server.ts
@@ -86,6 +86,114 @@ export async function isAssemblerServiceHealthy(): Promise<boolean> {
// after the status flip (purchase orders) the job is released, and the caller
// must still schedule it and say so.
// Validation (getJobReleaseReadiness) is the caller's, BEFORE this runs.
+/**
+ * Re-plan after an item's planning inputs change: its reordering policy, order
+ * multiple, minimum / maximum order quantity, batch size, lead time. The
+ * planning pages list MRP's stored suggestions, so without a run they kept
+ * the old sizing until the next scheduled one (every 3 hours) — an order
+ * multiple saved now read as ignored. A failed run never fails the save.
+ */
+export async function replanAfterItemChange(
+ db: Kysely<KyselyDatabase>,
+ args: { itemId: string; companyId: string; userId: string }
+) {
+ const mrp = await runMRP(getCarbonServiceRole(), db, {
+ type: "item",
+ id: args.itemId,
+ companyId: args.companyId,
+ userId: args.userId
+ });
+ if (mrp.error) {
+ logger.error("MRP failed after an item's planning settings changed", {
+ companyId: args.companyId,
+ itemId: args.itemId,
+ error: mrp.error
+ });
+ }
+}
+
+/**
+ * Promote a Draft make-to-stock job to Planned from the planning drawer. MRP
+ * does not count a Draft job as supply, so a Draft job and a Make suggestion
+ * for the same need sat side by side and could both be built. In order, as
+ * `releaseJobs` does: the requirements recalculation (a failure stops here,
+ * with the job still Draft, so MRP never counts a job whose requirements are
+ * stale), the guarded status flip (only from Draft), then MRP — which now
+ * counts the job, so the Make suggestion shrinks by it. No scheduler notice:
+ * the scheduler places only released jobs (`activeJobStatuses`), and a Planned
+ * job's dates and priority are unchanged. The caller has checked the job's
+ * location and that no sales order owns it.
+ */
+export async function planDraftJob({
+ client,
+ db,
+ jobId,
+ companyId,
+ userId
+}: {
+ client: SupabaseClient<Database>;
+ db: Kysely<KyselyDatabase>;
+ jobId: string;
+ companyId: string;
+ userId: string;
+}): Promise<{ updated: boolean; error?: string; warning?: string }> {
+ const serviceRole = getCarbonServiceRole();
+ const recalc = await recalculateJobRequirements(serviceRole, db, {
+ id: jobId,
+ companyId,
+ userId
+ });
+ if (recalc.error) {
+ logger.error("Failed to recalculate a Draft job before planning it", {
+ companyId,
+ jobId,
+ error: recalc.error
+ });
+ return {
+ updated: false,
+ error:
+ "The job's materials and operations could not be recalculated, so it was not planned. Recalculate the job and try again."
+ };
+ }
+
+ const flipped = await updateJobStatus(client, {
+ id: jobId,
+ companyId,
+ status: "Planned",
+ updatedBy: userId,
+ fromStatuses: ["Draft"]
+ });
+ if (flipped.error) {
+ logger.error("Failed to plan a Draft job from planning", {
+ companyId,
+ jobId,
+ error: flipped.error
+ });
+ return { updated: false, error: "Failed to plan the job" };
+ }
+ if (!flipped.updated) return { updated: false };
+
+ const mrp = await runMRP(serviceRole, db, {
+ type: "job",
+ id: jobId,
+ companyId,
+ userId
+ });
+ if (mrp.error) {
+ logger.error("MRP failed after planning a Draft job", {
+ companyId,
+ jobId,
+ error: mrp.error
+ });
+ return {
+ updated: true,
+ warning:
+ "The job is Planned, but the suggestions were not refreshed. Press Recalculate."
+ };
+ }
+ return { updated: true };
+}
+
export async function releaseJobs({
client,
db,
diff --git a/apps/erp/app/modules/production/ui/Planning/PlanningDrawerParts.tsx b/apps/erp/app/modules/production/ui/Planning/PlanningDrawerParts.tsx
index fea65f80ef..e91019fc79 100644
--- a/apps/erp/app/modules/production/ui/Planning/PlanningDrawerParts.tsx
+++ b/apps/erp/app/modules/production/ui/Planning/PlanningDrawerParts.tsx
@@ -46,6 +46,7 @@ type PolicyFields = Pick<
| "demandAccumulationPeriod"
| "demandAccumulationSafetyStock"
| "lotSize"
+ | "orderMultiple"
| "minimumOrderQuantity"
| "maximumOrderQuantity"
>;
@@ -144,6 +145,11 @@ export function PlanningPolicySummary({
<span>{formatQuantity(item.lotSize)}</span>
</PlanningSummaryRow>
)}
+ {item.orderMultiple > 1 && (
+ <PlanningSummaryRow label={<Trans>Order Multiple:</Trans>}>
+ <span>{formatQuantity(item.orderMultiple)}</span>
+ </PlanningSummaryRow>
+ )}
{item.minimumOrderQuantity > 0 && (
<PlanningSummaryRow label={<Trans>Minimum Order:</Trans>}>
<span>{formatQuantity(item.minimumOrderQuantity)}</span>
diff --git a/apps/erp/app/modules/production/ui/Planning/PlanningOrderGrids.tsx b/apps/erp/app/modules/production/ui/Planning/PlanningOrderGrids.tsx
index f8a3296bf5..5ed602b708 100644
--- a/apps/erp/app/modules/production/ui/Planning/PlanningOrderGrids.tsx
+++ b/apps/erp/app/modules/production/ui/Planning/PlanningOrderGrids.tsx
@@ -344,6 +344,9 @@ type OpenOrdersGridProps = PlanningActionHandlers & {
value: number | string
) => Promise<boolean>;
onRowsChange: (rows: OpenOrderRow[]) => void;
+ /** A command for an order no planning action targets — the production
+ * drawer's Plan on a Draft job. Rendered in the Suggestion column. */
+ renderRowCommand?: (row: OpenOrderRow) => ReactNode;
};
const QUANTITY_ACTION_TYPES: ReadonlySet<string> = new Set([
@@ -369,6 +372,7 @@ export function OpenOrdersGrid({
renderStatusIcon,
onSave,
onRowsChange,
+ renderRowCommand,
...handlers
}: OpenOrdersGridProps) {
const { t } = useLingui();
@@ -485,6 +489,8 @@ export function OpenOrdersGrid({
cell: ({ row }) => {
const { action, suggestedQuantity, purchaseOrder } = row.original;
if (!action) {
+ const command = renderRowCommand?.(row.original);
+ if (command) return command;
return purchaseOrder && handlers.purchaseOrderMenuItems ? (
<OrderOnlyMenu
order={purchaseOrder}
@@ -539,6 +545,7 @@ export function OpenOrdersGrid({
documentHeader,
quantityHeader,
renderStatusIcon,
+ renderRowCommand,
formatQuantity,
locale,
todayIso,
diff --git a/apps/erp/app/modules/production/ui/Planning/ProductionPlanningOrderDrawer.tsx b/apps/erp/app/modules/production/ui/Planning/ProductionPlanningOrderDrawer.tsx
index 6703db96bf..9c9c369403 100644
--- a/apps/erp/app/modules/production/ui/Planning/ProductionPlanningOrderDrawer.tsx
+++ b/apps/erp/app/modules/production/ui/Planning/ProductionPlanningOrderDrawer.tsx
@@ -85,6 +85,9 @@ type ProductionPlanningOrderDrawerProps = {
/** Apply / dismiss / reopen / assign, owned by the grid (one fetcher). */
actionHandlers: PlanningActionHandlers;
setOrders: (item: ProductionPlanningItem, orders: ProductionOrder[]) => void;
+ /** Drop the item's draft list so the drawer re-seeds from MRP's new
+ * suggestions — after a Draft job is planned, which re-runs MRP. */
+ onSuggestionsStale: (item: ProductionPlanningItem) => void;
locationId: string;
periods: { id: string; startDate: string; endDate: string }[];
isOpen: boolean;
@@ -102,6 +105,7 @@ export const ProductionPlanningOrderDrawer = memo(
actions,
actionHandlers,
setOrders,
+ onSuggestionsStale,
locationId,
periods,
isOpen,
@@ -130,6 +134,8 @@ export const ProductionPlanningOrderDrawer = memo(
// Re-read when the item's actions change: applying one rewrites its job.
const actionsKey = actions.map((a) => `${a.id}:${a.status}`).join(",");
+ // ...and after a Draft job is planned here, which changes its status.
+ const [openJobsVersion, setOpenJobsVersion] = useState(0);
// Only while open: the drawer stays mounted on its last item so it can
// slide out, and that item's actions change with every Apply on the grid.
@@ -180,7 +186,7 @@ export const ProductionPlanningOrderDrawer = memo(
return () => {
isCurrent = false;
};
- }, [isOpen, carbon, row.id, locationId, actionsKey]);
+ }, [isOpen, carbon, row.id, locationId, actionsKey, openJobsVersion]);
const openJobRows = useMemo<OpenOrderRow[] | null | Error>(() => {
if (!Array.isArray(openJobs)) return openJobs;
@@ -284,6 +290,66 @@ export const ProductionPlanningOrderDrawer = memo(
[locationId, revalidate, t]
);
+ // Plan: a Draft job becomes Planned, so MRP counts it as supply. Draft is
+ // the planner's own unfinished job; without this it sat beside a Make
+ // suggestion for the same need, and both could be built. Edit its
+ // quantity and date in the row first — Plan keeps them.
+ const [planningJobId, setPlanningJobId] = useState<string | null>(null);
+ const onPlanDraftJob = useCallback(
+ async (jobId: string) => {
+ setPlanningJobId(jobId);
+ try {
+ const response = await fetch(path.to.bulkUpdateProductionPlanning, {
+ method: "post",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({
+ action: "planJob",
+ locationId,
+ job: { id: jobId }
+ })
+ });
+ const result = (await response.json().catch(() => null)) as {
+ success?: boolean;
+ message?: string;
+ warning?: string;
+ } | null;
+ if (response.ok && result?.success) {
+ if (result.warning) toast.error(result.warning);
+ else toast.success(t`Planned job`);
+ // MRP ran: the suggestions, the grid row and this list all moved
+ onSuggestionsStale(row);
+ setOpenJobsVersion((version) => version + 1);
+ void revalidate();
+ } else {
+ toast.error(result?.message ?? t`Failed to plan job`);
+ }
+ } catch {
+ toast.error(t`Failed to plan job`);
+ } finally {
+ setPlanningJobId(null);
+ }
+ },
+ [locationId, onSuggestionsStale, revalidate, row, t]
+ );
+
+ const renderPlanCommand = useCallback(
+ (openRow: OpenOrderRow) =>
+ openRow.status === "Draft" && actionHandlers.canUpdate ? (
+ <div className="flex justify-end">
+ <Button
+ size="sm"
+ variant="secondary"
+ isLoading={planningJobId === openRow.id}
+ isDisabled={planningJobId !== null}
+ onClick={() => onPlanDraftJob(openRow.id)}
+ >
+ <Trans>Plan</Trans>
+ </Button>
+ </div>
+ ) : null,
+ [actionHandlers.canUpdate, onPlanDraftJob, planningJobId]
+ );
+
const renderOpenJobStatus = useCallback(
(status: string) => (
<JobStatus iconOnly status={status as (typeof jobStatus)[number]} />
@@ -461,6 +527,7 @@ export const ProductionPlanningOrderDrawer = memo(
rows={openJobRows}
todayIso={locationToday}
renderStatusIcon={renderOpenJobStatus}
+ renderRowCommand={renderPlanCommand}
onSave={onSaveOpenJob}
onRowsChange={onOpenJobsChange}
{...actionHandlers}
@@ -507,6 +574,7 @@ export const ProductionPlanningOrderDrawer = memo(
onIncludeBeyondFence,
openJobRows,
renderOpenJobStatus,
+ renderPlanCommand,
onSaveOpenJob,
onOpenJobsChange,
actionHandlers,
diff --git a/apps/erp/app/modules/production/ui/Planning/ProductionPlanningTable.tsx b/apps/erp/app/modules/production/ui/Planning/ProductionPlanningTable.tsx
index 3e326662a8..21a93e420d 100644
--- a/apps/erp/app/modules/production/ui/Planning/ProductionPlanningTable.tsx
+++ b/apps/erp/app/modules/production/ui/Planning/ProductionPlanningTable.tsx
@@ -295,11 +295,12 @@ const ProductionPlanningTable = ({
data.map((row) => [
row.id,
productionOrdersFromActions(
- openNewSupplyActions(actionsByItemId.get(row.id), "Make")
+ openNewSupplyActions(actionsByItemId.get(row.id), "Make"),
+ { item: row, todayDate: locationToday }
)
])
),
- [data, actionsByItemId]
+ [data, actionsByItemId, locationToday]
);
// biome-ignore lint/correctness/useExhaustiveDependencies: suppressed due to migration
@@ -406,6 +407,17 @@ const ProductionPlanningTable = ({
[]
);
+ // Planning a Draft job re-runs MRP: the item's draft list is stale, so the
+ // drawer re-seeds from the new suggestions.
+ const dropOrders = useCallback((item: ProductionPlanningItem) => {
+ if (!item.id) return;
+ setOrdersMap((prev) => {
+ if (!(item.id! in prev)) return prev;
+ const { [item.id!]: _dropped, ...rest } = prev;
+ return rest;
+ });
+ }, []);
+
// The drawer's own Planning Horizon control: the same on-screen override as
// the grid cell, for the row the drawer is open on.
const selectedItemId = selectedItem?.id;
@@ -786,6 +798,7 @@ const ProductionPlanningTable = ({
actions={selectedActions}
actionHandlers={actionHandlers}
setOrders={setOrders}
+ onSuggestionsStale={dropOrders}
periods={periods}
isOpen={isDrawerOpen}
onClose={closeDrawer}
diff --git a/apps/erp/app/modules/production/ui/Planning/planned-orders-from-actions.ts b/apps/erp/app/modules/production/ui/Planning/planned-orders-from-actions.ts
index cf61e75aba..fcd283bb03 100644
--- a/apps/erp/app/modules/production/ui/Planning/planned-orders-from-actions.ts
+++ b/apps/erp/app/modules/production/ui/Planning/planned-orders-from-actions.ts
@@ -15,7 +15,14 @@
// second time.
import type { Database, Json } from "@carbon/database";
-import { RoundingMode, round } from "@carbon/utils";
+import {
+ type OrderSizingParams,
+ orderSizingRules,
+ RoundingMode,
+ round,
+ splitIntoOrders
+} from "@carbon/utils";
+import { parseDate } from "@internationalized/date";
import { z } from "zod";
import type { ProductionOrder } from "~/modules/production/production.models";
import type { PlannedOrder } from "~/modules/purchasing/purchasing.models";
@@ -54,29 +61,111 @@ export function openNewSupplyActions<A extends NewSupplyActionFields>(
);
}
-/** One job suggestion per open Make action, in the item's own units. */
+/** The item's sizing fields, as the planning grid row carries them. */
+export type ItemOrderSizing = {
+ [K in keyof OrderSizingParams]?: number | null;
+};
+
+/**
+ * An action's orders. MRP sums the orders a week needs into one action (one
+ * per item and week), so it is split back into the orders its policy sized
+ * (`splitIntoOrders` by the action's own `policyName`): Demand-Based Reorder
+ * one per batch spread across the week, Fixed Reorder Quantity one of that
+ * quantity per day, Maximum Quantity one of at most the maximum order
+ * quantity per day.
+ */
+function ordersOf(
+ action: NewSupplyActionFields,
+ item: ItemOrderSizing,
+ todayDate?: string
+) {
+ const startDate = action.latestOrderDate ?? action.suggestedDate;
+ const rules = orderSizingRules(action.policyName, {
+ reorderPoint: Number(item.reorderPoint) || 0,
+ reorderQuantity: Number(item.reorderQuantity) || 0,
+ minimumOrderQuantity: Number(item.minimumOrderQuantity) || 0,
+ maximumOrderQuantity: Number(item.maximumOrderQuantity) || 0,
+ orderMultiple: Number(item.orderMultiple) || 0,
+ lotSize: Number(item.lotSize) || 0
+ });
+ return splitIntoOrders(Number(action.suggestedQuantity), rules).map(
+ (batch) => {
+ const orderStart = parseDate(startDate)
+ .add({ days: batch.dayOffset })
+ .toString();
+ return {
+ quantity: batch.quantity,
+ startDate: orderStart,
+ dueDate: parseDate(action.suggestedDate)
+ .add({ days: batch.dayOffset })
+ .toString(),
+ isASAP: isOrderASAP(action, orderStart, todayDate)
+ };
+ }
+ );
+}
+
+/**
+ * Whether an order must start at once: its own start date has passed, judged
+ * against today on the page. MRP stores one flag per week (any of the week's
+ * orders) as of its run, so every batch of the week became an ASAP job, and a
+ * job raised after its start had passed could still be a Soft Deadline.
+ * Maximum Quantity also requires the stock to be short, which only the run
+ * knows. Without today the stored flag is all there is.
+ */
+function isOrderASAP(
+ action: Pick<NewSupplyActionFields, "isASAP" | "policyName">,
+ orderStart: string,
+ todayDate: string | undefined
+): boolean {
+ if (!todayDate) return action.isASAP;
+ // ISO dates order as strings
+ const late = orderStart < todayDate;
+ return action.policyName === "Maximum Quantity"
+ ? late && action.isASAP
+ : late;
+}
+
+/**
+ * The job suggestions of each open Make action — the jobs its policy sized —
+ * in the item's own units, each with the action's policy attribution for the
+ * chart's order popover.
+ */
export function productionOrdersFromActions(
- actions: NewSupplyActionFields[]
+ actions: NewSupplyActionFields[],
+ context: {
+ /** The item's sizing fields. */
+ item?: ItemOrderSizing;
+ /** Today on the location's calendar, to judge each job's ASAP. */
+ todayDate?: string;
+ } = {}
): ProductionOrder[] {
- return actions.map((action) => ({
- startDate: action.latestOrderDate ?? action.suggestedDate,
- dueDate: action.suggestedDate,
- periodId: action.periodId,
- quantity: Number(action.suggestedQuantity),
- isASAP: action.isASAP
- }));
+ return actions.flatMap((action) =>
+ ordersOf(action, context.item ?? {}, context.todayDate).map((batch) => ({
+ startDate: batch.startDate,
+ dueDate: batch.dueDate,
+ periodId: action.periodId,
+ quantity: batch.quantity,
+ isASAP: batch.isASAP,
+ policyName: action.policyName ?? undefined,
+ reason: action.reason ?? undefined,
+ triggerValues: triggerValuesOf(action.triggerValues)
+ }))
+ );
}
/**
- * One purchase suggestion per open Order action. The action's quantity is in
- * inventory units; the order is in the supplier's purchase units, rounded up
- * to a whole unit.
+ * The purchase suggestions of each open Order action — the orders its policy
+ * sized. The action's quantity is in inventory units; each order is in the
+ * supplier's purchase units, rounded up to a whole unit.
*/
export function plannedOrdersFromActions(
actions: NewSupplyActionFields[],
context: {
/** Inventory units in one purchase unit, from the chosen supplier part. */
conversionFactor: number;
+ /** The item's sizing fields, in inventory units. */
+ item?: ItemOrderSizing;
/** The supplier chosen for the row; the action's own supplier otherwise. */
supplierId?: string | null;
itemReadableId?: string;
@@ -85,16 +174,15 @@ export function plannedOrdersFromActions(
}
): PlannedOrder[] {
const { conversionFactor } = context;
- return actions.map((action) => {
- const quantity = Number(action.suggestedQuantity);
- return {
- startDate: action.latestOrderDate ?? action.suggestedDate,
- dueDate: action.suggestedDate,
+ return actions.flatMap((action) =>
+ ordersOf(action, context.item ?? {}).map((batch) => ({
+ startDate: batch.startDate,
+ dueDate: batch.dueDate,
periodId: action.periodId,
quantity:
conversionFactor > 0
- ? round(quantity / conversionFactor, 0, RoundingMode.Up)
- : quantity,
+ ? round(batch.quantity / conversionFactor, 0, RoundingMode.Up)
+ : batch.quantity,
supplierId: context.supplierId ?? action.supplierId ?? undefined,
itemReadableId: context.itemReadableId,
description: context.description,
@@ -102,8 +190,8 @@ export function plannedOrdersFromActions(
policyName: action.policyName ?? undefined,
reason: action.reason ?? undefined,
triggerValues: triggerValuesOf(action.triggerValues)
- };
- });
+ }))
+ );
}
/** MRP writes the policy's trigger values as a flat object of numbers. */
diff --git a/apps/erp/app/modules/purchasing/ui/Planning/PurchasingPlanningTable.tsx b/apps/erp/app/modules/purchasing/ui/Planning/PurchasingPlanningTable.tsx
index 2a45b6c6b4..7e15aa9565 100644
--- a/apps/erp/app/modules/purchasing/ui/Planning/PurchasingPlanningTable.tsx
+++ b/apps/erp/app/modules/purchasing/ui/Planning/PurchasingPlanningTable.tsx
@@ -304,6 +304,7 @@ const PlanningTable = memo(
supplierId
),
supplierId,
+ item: row,
itemReadableId: item?.readableIdWithRevision,
description: item?.name,
unitOfMeasureCode: item?.unitOfMeasureCode
diff --git a/apps/erp/app/routes/x+/consumable+/$itemId.planning.tsx b/apps/erp/app/routes/x+/consumable+/$itemId.planning.tsx
index f115eae65f..7849cc9640 100644
--- a/apps/erp/app/routes/x+/consumable+/$itemId.planning.tsx
+++ b/apps/erp/app/routes/x+/consumable+/$itemId.planning.tsx
@@ -18,9 +18,11 @@ import {
} from "~/modules/items";
import { ItemPlanningForm } from "~/modules/items/ui/Item";
import { ItemPlanningChart } from "~/modules/items/ui/Item/ItemPlanningChart";
+import { replanAfterItemChange } from "~/modules/production/production.server";
import { getLocationsList } from "~/modules/resources";
import { isActiveCompanyEmployee } from "~/modules/shared/shared.server";
import { getUserDefaults } from "~/modules/users/users.server";
+import { getDatabaseClient } from "~/services/database.server";
import type { ListItem } from "~/types";
import { getCustomFields, setCustomFields } from "~/utils/form";
import { path } from "~/utils/path";
@@ -142,6 +144,14 @@ export async function action({ request, params }: ActionFunctionArgs) {
);
}
+ // The planning pages list MRP's suggestions; re-plan so they follow the
+ // new settings now, not at the next scheduled run.
+ await replanAfterItemChange(getDatabaseClient(), {
+ itemId,
+ companyId,
+ userId
+ });
+
throw redirect(
path.to.consumablePlanningLocation(itemId, validation.data.locationId),
await flash(request, success("Updated consumable planning"))
diff --git a/apps/erp/app/routes/x+/material+/$itemId.planning.tsx b/apps/erp/app/routes/x+/material+/$itemId.planning.tsx
index 367208f397..2a96007d69 100644
--- a/apps/erp/app/routes/x+/material+/$itemId.planning.tsx
+++ b/apps/erp/app/routes/x+/material+/$itemId.planning.tsx
@@ -18,9 +18,11 @@ import {
} from "~/modules/items";
import { ItemPlanningForm } from "~/modules/items/ui/Item";
import { ItemPlanningChart } from "~/modules/items/ui/Item/ItemPlanningChart";
+import { replanAfterItemChange } from "~/modules/production/production.server";
import { getLocationsList } from "~/modules/resources";
import { isActiveCompanyEmployee } from "~/modules/shared/shared.server";
import { getUserDefaults } from "~/modules/users/users.server";
+import { getDatabaseClient } from "~/services/database.server";
import type { ListItem } from "~/types";
import { getCustomFields, setCustomFields } from "~/utils/form";
import { path } from "~/utils/path";
@@ -139,6 +141,14 @@ export async function action({ request, params }: ActionFunctionArgs) {
);
}
+ // The planning pages list MRP's suggestions; re-plan so they follow the
+ // new settings now, not at the next scheduled run.
+ await replanAfterItemChange(getDatabaseClient(), {
+ itemId,
+ companyId,
+ userId
+ });
+
throw redirect(
path.to.materialPlanningLocation(itemId, validation.data.locationId),
await flash(request, success("Updated material planning"))
diff --git a/apps/erp/app/routes/x+/part+/$itemId.details.tsx b/apps/erp/app/routes/x+/part+/$itemId.details.tsx
index ec848f2d4e..a9754ce410 100644
--- a/apps/erp/app/routes/x+/part+/$itemId.details.tsx
+++ b/apps/erp/app/routes/x+/part+/$itemId.details.tsx
@@ -52,8 +52,10 @@ import {
} from "~/modules/items/ui/Item";
import ItemManufacturingForm from "~/modules/items/ui/Item/ItemManufacturingForm";
import { ConfigurationParametersForm } from "~/modules/items/ui/Parts";
+import { replanAfterItemChange } from "~/modules/production/production.server";
import type { MethodItemType, MethodType } from "~/modules/shared";
import { getTagsList } from "~/modules/shared";
+import { getDatabaseClient } from "~/services/database.server";
import { getCustomFields, setCustomFields } from "~/utils/form";
import { path } from "~/utils/path";
@@ -206,6 +208,14 @@ export async function action({ request, params }: ActionFunctionArgs) {
);
}
+ // The planning pages list MRP's suggestions; re-plan so they follow the
+ // new settings now, not at the next scheduled run.
+ await replanAfterItemChange(getDatabaseClient(), {
+ itemId,
+ companyId,
+ userId
+ });
+
throw redirect(
path.to.partDetails(itemId),
await flash(request, success("Updated part manufacturing"))
diff --git a/apps/erp/app/routes/x+/part+/$itemId.planning.tsx b/apps/erp/app/routes/x+/part+/$itemId.planning.tsx
index e74b3b6803..e82661594b 100644
--- a/apps/erp/app/routes/x+/part+/$itemId.planning.tsx
+++ b/apps/erp/app/routes/x+/part+/$itemId.planning.tsx
@@ -28,9 +28,11 @@ import {
ItemSupersessionForm
} from "~/modules/items/ui/Item";
import { ItemPlanningChart } from "~/modules/items/ui/Item/ItemPlanningChart";
+import { replanAfterItemChange } from "~/modules/production/production.server";
import { getLocationsList } from "~/modules/resources";
import { isActiveCompanyEmployee } from "~/modules/shared/shared.server";
import { getUserDefaults } from "~/modules/users/users.server";
+import { getDatabaseClient } from "~/services/database.server";
import type { ListItem } from "~/types";
import { getCustomFields, setCustomFields } from "~/utils/form";
import { path } from "~/utils/path";
@@ -269,6 +271,14 @@ export async function action({ request, params }: ActionFunctionArgs) {
);
}
+ // The planning pages list MRP's suggestions; re-plan so they follow the
+ // new settings now, not at the next scheduled run.
+ await replanAfterItemChange(getDatabaseClient(), {
+ itemId,
+ companyId,
+ userId
+ });
+
throw redirect(
path.to.partPlanningLocation(itemId, validation.data.locationId),
await flash(request, success("Updated part planning"))
diff --git a/apps/erp/app/routes/x+/production+/planning.update.tsx b/apps/erp/app/routes/x+/production+/planning.update.tsx
index f6fd8e7043..ec144b46ce 100644
--- a/apps/erp/app/routes/x+/production+/planning.update.tsx
+++ b/apps/erp/app/routes/x+/production+/planning.update.tsx
@@ -27,7 +27,10 @@ import {
updatePlanningJob,
upsertJobMethod
} from "~/modules/production";
-import { cancelJob } from "~/modules/production/production.server";
+import {
+ cancelJob,
+ planDraftJob
+} from "~/modules/production/production.server";
import { isActiveCompanyEmployee } from "~/modules/shared/shared.server";
import { getDatabaseClient } from "~/services/database.server";
@@ -647,6 +650,81 @@ export async function action({ request }: ActionFunctionArgs) {
return { success: true, message: "Updated job" };
}
+ // ── Promote a Draft job to Planned (the drawer's Plan button). MRP does
+ // not count a Draft job as supply; once Planned it does, and the run
+ // inside planDraftJob shrinks the Make suggestion by it. Only this
+ // location's make-to-stock Draft jobs: the drawer lists nothing else, and
+ // a job a sales order owns is that order's, not planning's.
+ case "planJob": {
+ const parsedJob = z.object({ id: z.string().min(1) }).safeParse(job);
+ if (!parsedJob.success) {
+ return data(
+ { success: false, message: "A job id is required" },
+ { status: 400 }
+ );
+ }
+
+ const target = await client
+ .from("job")
+ .select("id, status, locationId, salesOrderId, salesOrderLineId")
+ .eq("id", parsedJob.data.id)
+ .eq("companyId", companyId)
+ .maybeSingle();
+ if (target.error || !target.data) {
+ return data(
+ { success: false, message: "Job not found" },
+ { status: 404 }
+ );
+ }
+ if (target.data.locationId !== locationId) {
+ return data(
+ { success: false, message: "This job is for another location." },
+ { status: 409 }
+ );
+ }
+ if (target.data.salesOrderId || target.data.salesOrderLineId) {
+ return data(
+ {
+ success: false,
+ message: "This job is for a sales order. Plan it on the job."
+ },
+ { status: 409 }
+ );
+ }
+ if (target.data.status !== "Draft") {
+ return data(
+ { success: false, message: "Only a Draft job can be planned." },
+ { status: 409 }
+ );
+ }
+
+ const planned = await planDraftJob({
+ client,
+ db: getDatabaseClient(),
+ jobId: target.data.id,
+ companyId,
+ userId
+ });
+ if (planned.error) {
+ return data(
+ { success: false, message: planned.error },
+ { status: 500 }
+ );
+ }
+ if (!planned.updated) {
+ // Changed by someone else after the status check above.
+ return data(
+ { success: false, message: "Only a Draft job can be planned." },
+ { status: 409 }
+ );
+ }
+ return {
+ success: true,
+ message: "Planned job",
+ ...(planned.warning && { warning: planned.warning })
+ };
+ }
+
// ── Apply a persisted planning action to its target job (spec §P1.5).
// IDOR guard: the request carries ONLY planningActionIds — the type, target
// and proposal values come from the persisted row, loaded by id+companyId
@@ -1223,7 +1301,7 @@ export async function action({ request }: ActionFunctionArgs) {
return data(
{
success: false,
- message: `Unknown action '${action}'. Expected one of: 'order', 'updateJob', 'apply', 'expedite', 'defer', 'increase', 'decrease', 'cancel', 'dismiss', 'reopen', 'assign'`
+ message: `Unknown action '${action}'. Expected one of: 'order', 'updateJob', 'planJob', 'apply', 'expedite', 'defer', 'increase', 'decrease', 'cancel', 'dismiss', 'reopen', 'assign'`
},
{ status: 400 }
);
diff --git a/apps/erp/app/routes/x+/tool+/$itemId.details.tsx b/apps/erp/app/routes/x+/tool+/$itemId.details.tsx
index 6ea5507f1b..6fa1e10120 100644
--- a/apps/erp/app/routes/x+/tool+/$itemId.details.tsx
+++ b/apps/erp/app/routes/x+/tool+/$itemId.details.tsx
@@ -49,8 +49,10 @@ import {
MakeMethodTools
} from "~/modules/items/ui/Item";
import ItemManufacturingForm from "~/modules/items/ui/Item/ItemManufacturingForm";
+import { replanAfterItemChange } from "~/modules/production/production.server";
import type { MethodItemType, MethodType } from "~/modules/shared";
import { getTagsList } from "~/modules/shared";
+import { getDatabaseClient } from "~/services/database.server";
import { getCustomFields, setCustomFields } from "~/utils/form";
import { path } from "~/utils/path";
@@ -188,6 +190,14 @@ export async function action({ request, params }: ActionFunctionArgs) {
);
}
+ // The planning pages list MRP's suggestions; re-plan so they follow the
+ // new settings now, not at the next scheduled run.
+ await replanAfterItemChange(getDatabaseClient(), {
+ itemId,
+ companyId,
+ userId
+ });
+
throw redirect(
path.to.toolDetails(itemId),
await flash(request, success("Updated tool manufacturing"))
diff --git a/apps/erp/app/routes/x+/tool+/$itemId.planning.tsx b/apps/erp/app/routes/x+/tool+/$itemId.planning.tsx
index 78a70ed22b..bd38bcc007 100644
--- a/apps/erp/app/routes/x+/tool+/$itemId.planning.tsx
+++ b/apps/erp/app/routes/x+/tool+/$itemId.planning.tsx
@@ -18,9 +18,11 @@ import {
} from "~/modules/items";
import { ItemPlanningForm } from "~/modules/items/ui/Item";
import { ItemPlanningChart } from "~/modules/items/ui/Item/ItemPlanningChart";
+import { replanAfterItemChange } from "~/modules/production/production.server";
import { getLocationsList } from "~/modules/resources";
import { isActiveCompanyEmployee } from "~/modules/shared/shared.server";
import { getUserDefaults } from "~/modules/users/users.server";
+import { getDatabaseClient } from "~/services/database.server";
import type { ListItem } from "~/types";
import { getCustomFields, setCustomFields } from "~/utils/form";
import { path } from "~/utils/path";
@@ -139,6 +141,14 @@ export async function action({ request, params }: ActionFunctionArgs) {
);
}
+ // The planning pages list MRP's suggestions; re-plan so they follow the
+ // new settings now, not at the next scheduled run.
+ await replanAfterItemChange(getDatabaseClient(), {
+ itemId,
+ companyId,
+ userId
+ });
+
throw redirect(
path.to.toolPlanningLocation(itemId, validation.data.locationId),
await flash(request, success("Updated tool planning"))
diff --git a/apps/erp/test/planned-orders-from-actions.test.ts b/apps/erp/test/planned-orders-from-actions.test.ts
index fdaefff263..8d9c53628d 100644
--- a/apps/erp/test/planned-orders-from-actions.test.ts
+++ b/apps/erp/test/planned-orders-from-actions.test.ts
@@ -173,10 +173,173 @@ describe("productionOrdersFromActions", () => {
dueDate: "2026-10-04",
periodId: "w1",
quantity: 5,
- isASAP: true
+ isASAP: true,
+ policyName: "Fixed Reorder Quantity"
}
]);
});
+
+ // The chart's order popover explains a suggestion from these; production's
+ // suggested jobs dropped them and the popover lost its policy section.
+ it("carries the action's policy attribution", () => {
+ const [order] = productionOrdersFromActions([
+ action({
+ type: "Make",
+ policyName: "Demand-Based Reorder",
+ reason: "Short in week 2",
+ triggerValues: { projectedStock: -30, safetyStock: 0, note: "x" }
+ })
+ ]);
+ expect(order).toMatchObject({
+ policyName: "Demand-Based Reorder",
+ reason: "Short in week 2",
+ triggerValues: { projectedStock: -30, safetyStock: 0 }
+ });
+ });
+
+ // MRP stores one ASAP flag per week, as of its run: every batch became an
+ // ASAP job if any one was, and a job raised after its start date had passed
+ // could still be a Soft Deadline.
+ it("judges each job's ASAP from its own start date and today", () => {
+ const make = action({
+ type: "Make",
+ policyName: "Demand-Based Reorder",
+ suggestedQuantity: 120,
+ suggestedDate: "2026-10-04",
+ latestOrderDate: "2026-09-27",
+ isASAP: false
+ });
+ expect(
+ productionOrdersFromActions([make], {
+ item: { lotSize: 50 },
+ todayDate: "2026-09-29"
+ }).map((o) => [o.startDate, o.isASAP])
+ ).toEqual([
+ ["2026-09-27", true],
+ ["2026-09-29", false],
+ ["2026-10-01", false]
+ ]);
+ });
+
+ it("keeps Maximum Quantity's stock condition from the run", () => {
+ const make = (isASAP: boolean) =>
+ action({
+ type: "Make",
+ policyName: "Maximum Quantity",
+ suggestedQuantity: 10,
+ latestOrderDate: "2026-09-20",
+ isASAP
+ });
+ const asap = (isASAP: boolean) =>
+ productionOrdersFromActions([make(isASAP)], {
+ todayDate: "2026-09-29"
+ })[0]?.isASAP;
+ expect(asap(true)).toBe(true);
+ // started late, but the run found stock above zero: not ASAP
+ expect(asap(false)).toBe(false);
+ });
+});
+
+// MRP sums the orders a week needs into one action; one order per action
+// turned a 120 on a batch size of 50 into a single job of 120, and three
+// fixed reorders of 100 into one order of 300.
+describe("orders split back by the policy that sized them", () => {
+ const make = (policyName: string, suggestedQuantity: number) =>
+ action({
+ type: "Make",
+ policyName,
+ suggestedQuantity,
+ suggestedDate: "2026-10-04",
+ latestOrderDate: "2026-09-27",
+ isASAP: false
+ });
+
+ it("Demand-Based Reorder: one job per batch, spread across the week", () => {
+ expect(
+ productionOrdersFromActions([make("Demand-Based Reorder", 120)], { item: {
+ lotSize: 50
+ } })
+ ).toEqual([
+ {
+ startDate: "2026-09-27",
+ dueDate: "2026-10-04",
+ periodId: "w1",
+ quantity: 50,
+ isASAP: false,
+ policyName: "Demand-Based Reorder"
+ },
+ {
+ startDate: "2026-09-29",
+ dueDate: "2026-10-06",
+ periodId: "w1",
+ quantity: 50,
+ isASAP: false,
+ policyName: "Demand-Based Reorder"
+ },
+ {
+ startDate: "2026-10-01",
+ dueDate: "2026-10-08",
+ periodId: "w1",
+ quantity: 20,
+ isASAP: false,
+ policyName: "Demand-Based Reorder"
+ }
+ ]);
+ });
+
+ it("keeps one job when the item has no batch size", () => {
+ expect(
+ productionOrdersFromActions([make("Demand-Based Reorder", 120)], { item: {
+ lotSize: 0
+ } }).map((o) => o.quantity)
+ ).toEqual([120]);
+ });
+
+ it("Fixed Reorder Quantity: one order of that quantity per day", () => {
+ const orders = productionOrdersFromActions(
+ [make("Fixed Reorder Quantity", 300)],
+ { item: { reorderQuantity: 100, lotSize: 40 } }
+ );
+ expect(orders.map((o) => [o.quantity, o.dueDate])).toEqual([
+ [100, "2026-10-04"],
+ [100, "2026-10-05"],
+ [100, "2026-10-06"]
+ ]);
+ });
+
+ it("Maximum Quantity: never an order past the maximum order quantity", () => {
+ expect(
+ productionOrdersFromActions([make("Maximum Quantity", 450)], { item: {
+ maximumOrderQuantity: 200,
+ lotSize: 50
+ } }).map((o) => o.quantity)
+ ).toEqual([200, 200, 50]);
+ });
+
+ it("Maximum Quantity keeps a lot-multiple order whole", () => {
+ expect(
+ productionOrdersFromActions([make("Maximum Quantity", 100)], { item: {
+ lotSize: 50
+ } }).map((o) => o.quantity)
+ ).toEqual([100]);
+ });
+
+ it("Stock Only is one order of the shortfall", () => {
+ expect(
+ productionOrdersFromActions([make("Stock Only", 120)], { item: {
+ lotSize: 50
+ } }).map((o) => o.quantity)
+ ).toEqual([120]);
+ });
+
+ it("splits a purchase action before converting to purchase units", () => {
+ expect(
+ plannedOrdersFromActions(
+ [action({ policyName: "Fixed Reorder Quantity", suggestedQuantity: 120 })],
+ { conversionFactor: 20, item: { reorderQuantity: 50 } }
+ ).map((o) => o.quantity)
+ ).toEqual([3, 3, 1]);
+ });
});
describe("supplierConversionFactor", () => {
diff --git a/apps/erp/test/release-jobs.test.ts b/apps/erp/test/release-jobs.test.ts
index 73e5ee1fa4..4f3e2182c0 100644
--- a/apps/erp/test/release-jobs.test.ts
+++ b/apps/erp/test/release-jobs.test.ts
@@ -36,10 +36,14 @@ vi.mock("../app/modules/production/production.service", () => ({
}));
import {
+ recalculateJobRequirements,
runMRP,
updateJobStatus
} from "../app/modules/production/production.service";
-import { releaseJobs } from "../app/modules/production/production.server";
+import {
+ planDraftJob,
+ releaseJobs
+} from "../app/modules/production/production.server";
// The release-date write: a chainable, thenable stand-in for the user client.
function clientWith(stamp: { error: null | { message: string } }) {
@@ -107,3 +111,73 @@ describe("releaseJobs", () => {
});
});
});
+
+// The planning drawer's Plan on a Draft job follows releaseJobs' order: MRP
+// must never count a job as supply while its requirements are stale.
+describe("planDraftJob", () => {
+ const plan = () =>
+ planDraftJob({
+ client: {} as any,
+ db: {} as any,
+ jobId: "job-1",
+ companyId: "company-1",
+ userId: "user-1"
+ });
+
+ it("recalculates, flips only from Draft, then runs MRP", async () => {
+ const order: string[] = [];
+ vi.mocked(recalculateJobRequirements).mockImplementationOnce(async () => {
+ order.push("recalculate");
+ return { data: null, error: null } as any;
+ });
+ vi.mocked(updateJobStatus).mockImplementationOnce(async () => {
+ order.push("flip");
+ return { error: null, updated: true } as any;
+ });
+ vi.mocked(runMRP).mockImplementationOnce(async () => {
+ order.push("mrp");
+ return { data: null, error: null } as any;
+ });
+
+ expect(await plan()).toEqual({ updated: true });
+ expect(order).toEqual(["recalculate", "flip", "mrp"]);
+ expect(vi.mocked(updateJobStatus).mock.calls[0]?.[1]).toMatchObject({
+ status: "Planned",
+ fromStatuses: ["Draft"]
+ });
+ });
+
+ it("leaves the job Draft, and runs no MRP, when the recalculation fails", async () => {
+ vi.mocked(recalculateJobRequirements).mockResolvedValueOnce({
+ data: null,
+ error: { message: "boom" }
+ } as any);
+
+ const result = await plan();
+ expect(result.updated).toBe(false);
+ expect(result.error).toBeTruthy();
+ expect(updateJobStatus).not.toHaveBeenCalled();
+ expect(runMRP).not.toHaveBeenCalled();
+ });
+
+ it("runs no MRP when the job is no longer Draft", async () => {
+ vi.mocked(updateJobStatus).mockResolvedValueOnce({
+ error: null,
+ updated: false
+ } as any);
+
+ expect(await plan()).toEqual({ updated: false });
+ expect(runMRP).not.toHaveBeenCalled();
+ });
+
+ it("keeps the job Planned and warns when MRP fails", async () => {
+ vi.mocked(runMRP).mockResolvedValueOnce({
+ data: null,
+ error: new Error("planning blew up")
+ });
+
+ const result = await plan();
+ expect(result.updated).toBe(true);
+ expect(result.warning).toBeTruthy();
+ });
+});
diff --git a/packages/locale/locales/de/erp.po b/packages/locale/locales/de/erp.po
index 2d56019f6d..7cb3d3ac1e 100644
--- a/packages/locale/locales/de/erp.po
+++ b/packages/locale/locales/de/erp.po
@@ -9050,6 +9050,9 @@ msgstr "Fehler beim Laden von verfolgten Entitäten"
msgid "Failed to move account: {0}"
msgstr "Konto konnte nicht verschoben werden: {0}"
+msgid "Failed to plan job"
+msgstr "Fertigungsauftrag konnte nicht geplant werden"
+
msgid "Failed to record gauge"
msgstr "Prüfmittel konnte nicht aufgezeichnet werden"
@@ -14476,6 +14479,9 @@ msgstr "Bestelldatum"
msgid "Order Multiple"
msgstr "Bestellvielfaches"
+msgid "Order Multiple:"
+msgstr "Bestellvielfaches:"
+
msgid "Order Parts"
msgstr "Teile bestellen"
diff --git a/packages/locale/locales/en/erp.po b/packages/locale/locales/en/erp.po
index 47d70cc63c..5e8ba0f241 100644
--- a/packages/locale/locales/en/erp.po
+++ b/packages/locale/locales/en/erp.po
@@ -9050,6 +9050,9 @@ msgstr "Failed to load tracked entities"
msgid "Failed to move account: {0}"
msgstr "Failed to move account: {0}"
+msgid "Failed to plan job"
+msgstr "Failed to plan job"
+
msgid "Failed to record gauge"
msgstr "Failed to record gauge"
@@ -14476,6 +14479,9 @@ msgstr "Order Date"
msgid "Order Multiple"
msgstr "Order Multiple"
+msgid "Order Multiple:"
+msgstr "Order Multiple:"
+
msgid "Order Parts"
msgstr "Order Parts"
diff --git a/packages/locale/locales/es/erp.po b/packages/locale/locales/es/erp.po
index d111428d81..9c6ff92688 100644
--- a/packages/locale/locales/es/erp.po
+++ b/packages/locale/locales/es/erp.po
@@ -9050,6 +9050,9 @@ msgstr "No se pudieron cargar las entidades rastreadas"
msgid "Failed to move account: {0}"
msgstr "Error al mover cuenta: {0}"
+msgid "Failed to plan job"
+msgstr "No se pudo planificar la orden de trabajo"
+
msgid "Failed to record gauge"
msgstr "No se pudo registrar el instrumento de medición"
@@ -14476,6 +14479,9 @@ msgstr "Fecha de Pedido"
msgid "Order Multiple"
msgstr "Múltiplo de Pedido"
+msgid "Order Multiple:"
+msgstr "Múltiplo de pedido:"
+
msgid "Order Parts"
msgstr "Pedir Piezas"
diff --git a/packages/locale/locales/fr/erp.po b/packages/locale/locales/fr/erp.po
index fce339504b..0dc879e7fb 100644
--- a/packages/locale/locales/fr/erp.po
+++ b/packages/locale/locales/fr/erp.po
@@ -9050,6 +9050,9 @@ msgstr "Impossible de charger les entités suivies"
msgid "Failed to move account: {0}"
msgstr "Impossible de déplacer le compte : {0}"
+msgid "Failed to plan job"
+msgstr "Impossible de planifier l'ordre de fabrication"
+
msgid "Failed to record gauge"
msgstr "Échec de l'enregistrement de l'instrument de mesure"
@@ -14476,6 +14479,9 @@ msgstr "Date de commande"
msgid "Order Multiple"
msgstr "Multiplicateur de commande"
+msgid "Order Multiple:"
+msgstr "Multiple de commande :"
+
msgid "Order Parts"
msgstr "Commander des pièces"
diff --git a/packages/locale/locales/hi/erp.po b/packages/locale/locales/hi/erp.po
index 1bc3f1181c..e88a4a6f4a 100644
--- a/packages/locale/locales/hi/erp.po
+++ b/packages/locale/locales/hi/erp.po
@@ -9050,6 +9050,9 @@ msgstr "ट्रैक किए गए इकाइयों को लोड
msgid "Failed to move account: {0}"
msgstr "खाता स्थानांतरित करने में विफल: {0}"
+msgid "Failed to plan job"
+msgstr "जॉब को प्लान करने में विफल"
+
msgid "Failed to record gauge"
msgstr "गेज रिकॉर्ड करने में विफल"
@@ -14476,6 +14479,9 @@ msgstr "ऑर्डर तारीख"
msgid "Order Multiple"
msgstr "ऑर्डर गुणज"
+msgid "Order Multiple:"
+msgstr "ऑर्डर गुणज:"
+
msgid "Order Parts"
msgstr "पार्ट्स ऑर्डर करें"
diff --git a/packages/locale/locales/it/erp.po b/packages/locale/locales/it/erp.po
index d390932526..cf12ead5d6 100644
--- a/packages/locale/locales/it/erp.po
+++ b/packages/locale/locales/it/erp.po
@@ -9050,6 +9050,9 @@ msgstr "Impossibile caricare le entità tracciate"
msgid "Failed to move account: {0}"
msgstr "Impossibile spostare il conto: {0}"
+msgid "Failed to plan job"
+msgstr "Impossibile pianificare l'ordine di produzione"
+
msgid "Failed to record gauge"
msgstr "Impossibile registrare lo strumento di misura"
@@ -14476,6 +14479,9 @@ msgstr "Data dell'ordine"
msgid "Order Multiple"
msgstr "Multiplo d'Ordine"
+msgid "Order Multiple:"
+msgstr "Multiplo d'ordine:"
+
msgid "Order Parts"
msgstr "Ordina Componenti"
diff --git a/packages/locale/locales/ja/erp.po b/packages/locale/locales/ja/erp.po
index e422c8ca14..27f4ed6ada 100644
--- a/packages/locale/locales/ja/erp.po
+++ b/packages/locale/locales/ja/erp.po
@@ -9050,6 +9050,9 @@ msgstr "追跡対象エンティティの読み込みに失敗しました"
msgid "Failed to move account: {0}"
msgstr "勘定科目の移動に失敗しました: {0}"
+msgid "Failed to plan job"
+msgstr "製造指図を計画できませんでした"
+
msgid "Failed to record gauge"
msgstr "測定器の記録に失敗しました"
@@ -14476,6 +14479,9 @@ msgstr "注文日"
msgid "Order Multiple"
msgstr "発注倍数"
+msgid "Order Multiple:"
+msgstr "発注倍数:"
+
msgid "Order Parts"
msgstr "部品を注文"
diff --git a/packages/locale/locales/ko/erp.po b/packages/locale/locales/ko/erp.po
index 54f06767ab..d659e9e47e 100644
--- a/packages/locale/locales/ko/erp.po
+++ b/packages/locale/locales/ko/erp.po
@@ -9050,6 +9050,9 @@ msgstr "추적 개체를 불러오지 못했습니다"
msgid "Failed to move account: {0}"
msgstr "계정 이동 실패: {0}"
+msgid "Failed to plan job"
+msgstr "작업 지시 계획 실패"
+
msgid "Failed to record gauge"
msgstr "계측기 기록에 실패했습니다"
@@ -14476,6 +14479,9 @@ msgstr "주문일"
msgid "Order Multiple"
msgstr "주문 배수"
+msgid "Order Multiple:"
+msgstr "주문 배수:"
+
msgid "Order Parts"
msgstr "부품 발주"
diff --git a/packages/locale/locales/pl/erp.po b/packages/locale/locales/pl/erp.po
index 104f51c811..1363db23ae 100644
--- a/packages/locale/locales/pl/erp.po
+++ b/packages/locale/locales/pl/erp.po
@@ -9050,6 +9050,9 @@ msgstr "Nie udało się załadować śledzonych jednostek"
msgid "Failed to move account: {0}"
msgstr "Nie udało się przenieść konta: {0}"
+msgid "Failed to plan job"
+msgstr "Nie udało się zaplanować zlecenia produkcyjnego"
+
msgid "Failed to record gauge"
msgstr "Nie udało się zapisać przyrządu pomiarowego"
@@ -14476,6 +14479,9 @@ msgstr "Data zamówienia"
msgid "Order Multiple"
msgstr "Wielokrotność Zamówienia"
+msgid "Order Multiple:"
+msgstr "Wielokrotność zamówienia:"
+
msgid "Order Parts"
msgstr "Zamów części"
diff --git a/packages/locale/locales/pt/erp.po b/packages/locale/locales/pt/erp.po
index 6e30e40234..f5be7d0465 100644
--- a/packages/locale/locales/pt/erp.po
+++ b/packages/locale/locales/pt/erp.po
@@ -9050,6 +9050,9 @@ msgstr "Falha ao carregar entidades rastreadas"
msgid "Failed to move account: {0}"
msgstr "Falha ao mover conta: {0}"
+msgid "Failed to plan job"
+msgstr "Falha ao planejar ordem de produção"
+
msgid "Failed to record gauge"
msgstr "Falha ao registrar instrumento de medição"
@@ -14476,6 +14479,9 @@ msgstr "Data do Pedido"
msgid "Order Multiple"
msgstr "Múltiplo de Pedido"
+msgid "Order Multiple:"
+msgstr "Múltiplo de pedido:"
+
msgid "Order Parts"
msgstr "Encomendar Peças"
diff --git a/packages/locale/locales/ru/erp.po b/packages/locale/locales/ru/erp.po
index 83854fd9dd..467596963f 100644
--- a/packages/locale/locales/ru/erp.po
+++ b/packages/locale/locales/ru/erp.po
@@ -9050,6 +9050,9 @@ msgstr "Не удалось загрузить отслеживаемые сущ
msgid "Failed to move account: {0}"
msgstr "Не удалось переместить счет: {0}"
+msgid "Failed to plan job"
+msgstr "Ошибка при планировании производственного заказа"
+
msgid "Failed to record gauge"
msgstr "Не удалось записать средство измерения"
@@ -14476,6 +14479,9 @@ msgstr "Дата заказа"
msgid "Order Multiple"
msgstr "Кратность заказа"
+msgid "Order Multiple:"
+msgstr "Кратность заказа:"
+
msgid "Order Parts"
msgstr "Заказать детали"
diff --git a/packages/locale/locales/tr/erp.po b/packages/locale/locales/tr/erp.po
index 4be6997c99..b00430a9bb 100644
--- a/packages/locale/locales/tr/erp.po
+++ b/packages/locale/locales/tr/erp.po
@@ -9050,6 +9050,9 @@ msgstr "Takip edilen varlıklar yüklenemedi"
msgid "Failed to move account: {0}"
msgstr "Hesap taşınamadı: {0}"
+msgid "Failed to plan job"
+msgstr "İş emrini planlama başarısız"
+
msgid "Failed to record gauge"
msgstr "Ölçüm aleti kaydedilemedi"
@@ -14476,6 +14479,9 @@ msgstr "Sipariş Tarihi"
msgid "Order Multiple"
msgstr "Sipariş katı"
+msgid "Order Multiple:"
+msgstr "Sipariş katı:"
+
msgid "Order Parts"
msgstr "Parça Sipariş Et"
diff --git a/packages/locale/locales/zh/erp.po b/packages/locale/locales/zh/erp.po
index d53521dfca..9e08b02a01 100644
--- a/packages/locale/locales/zh/erp.po
+++ b/packages/locale/locales/zh/erp.po
@@ -9050,6 +9050,9 @@ msgstr "加载跟踪实体失败"
msgid "Failed to move account: {0}"
msgstr "移动账户失败: {0}"
+msgid "Failed to plan job"
+msgstr "规划工单失败"
+
msgid "Failed to record gauge"
msgstr "未能记录量具"
@@ -14476,6 +14479,9 @@ msgstr "订单日期"
msgid "Order Multiple"
msgstr "订购倍数"
+msgid "Order Multiple:"
+msgstr "订购倍数:"
+
msgid "Order Parts"
msgstr "订购零件"
diff --git a/packages/planning/src/mrp/planning-actions.test.ts b/packages/planning/src/mrp/planning-actions.test.ts
index 61f13dc16d..e6ed92c640 100644
--- a/packages/planning/src/mrp/planning-actions.test.ts
+++ b/packages/planning/src/mrp/planning-actions.test.ts
@@ -19,6 +19,7 @@ import {
firstNeedPeriodByOrder,
isCommittedJobStatus,
isCommittedPurchaseOrderStatus,
+ isOrderFrozen,
keyPeriodFor,
naturalKey,
projectionsWithExpedites,
@@ -631,6 +632,166 @@ describe("deriveChangeActions", () => {
});
});
+describe("order-quantity rules on change actions", () => {
+ const jobDecrease = (
+ need: number,
+ quantity: number,
+ orderRules: { minimum: number; multiples: number[] }
+ ) =>
+ deriveChangeActions({
+ ...base,
+ onHand: 0,
+ demandPeriods: [
+ { periodId: "p2", startDate: "2026-10-12", quantity: need }
+ ],
+ openOrders: [
+ {
+ jobId: "job-1",
+ quantity,
+ dueDate: "2026-10-12", // on time → no date action
+ requiresManualAction: false
+ }
+ ],
+ orderRules
+ });
+
+ it("decreases a job to a whole order multiple, not the bare requirement", () => {
+ const actions = jobDecrease(37, 50, { minimum: 0, multiples: [10] });
+ expect(actions).toHaveLength(1);
+ expect(actions[0]).toMatchObject({
+ type: "Decrease",
+ suggestedQuantity: 40
+ });
+ });
+
+ it("raises nothing when the order is already the smallest multiple that covers", () => {
+ expect(jobDecrease(37, 40, { minimum: 0, multiples: [10] })).toEqual([]);
+ });
+
+ it("keeps a Fixed Reorder Quantity order on whole reorder quantities", () => {
+ const actions = jobDecrease(150, 300, { minimum: 0, multiples: [100] });
+ expect(actions[0]).toMatchObject({
+ type: "Decrease",
+ suggestedQuantity: 200
+ });
+ });
+
+ it("never decreases below the minimum order quantity", () => {
+ const actions = jobDecrease(12, 50, { minimum: 25, multiples: [] });
+ expect(actions[0]).toMatchObject({
+ type: "Decrease",
+ suggestedQuantity: 25
+ });
+ });
+});
+
+// An order whose due date less lead time is before today is already being
+// made or shipped. HR-TORSO: an overdue job J000438 (111) got "Increase to
+// 131" beside a Make for the same week, and the planner read the two as
+// ordering twice. Nothing can change such an order in time.
+describe("frozen orders (due date less lead time before today)", () => {
+ // TODAY is 2026-09-11
+ it("is frozen when overdue, or due sooner than a lead time away", () => {
+ expect(isOrderFrozen({ dueDate: "2026-09-04" }, TODAY)).toBe(true);
+ expect(isOrderFrozen({ dueDate: "2026-09-11" }, TODAY)).toBe(false);
+ expect(isOrderFrozen({ dueDate: "2026-09-15" }, TODAY, 7)).toBe(true);
+ expect(isOrderFrozen({ dueDate: "2026-09-18" }, TODAY, 7)).toBe(false);
+ });
+
+ const overdueJob = {
+ jobId: "job-1",
+ quantity: 111,
+ dueDate: "2026-09-04",
+ requiresManualAction: true
+ };
+
+ it("never increases an overdue order — the shortfall stays a new order", () => {
+ const make = {
+ type: "Make" as const,
+ periodId: "p1",
+ suggestedQuantity: 20,
+ suggestedDate: "2026-09-11",
+ horizonDate: "2026-09-11",
+ latestOrderDate: "2026-09-04",
+ isASAP: true,
+ purchaseOrderLineId: null,
+ jobId: null,
+ requiresManualAction: false,
+ supplierId: null,
+ policyName: "Demand-Based Reorder",
+ reason: null,
+ triggerValues: null
+ };
+ const [action] = convertOrdersToIncreases({
+ sizingCandidates: [make],
+ openOrders: [overdueJob],
+ changeActions: [],
+ toleranceDays: TOLERANCE,
+ todayDate: TODAY,
+ leadTimeDays: 7
+ });
+ expect(action).toMatchObject({ type: "Make", suggestedQuantity: 20 });
+ });
+
+ it("never decreases a frozen order", () => {
+ expect(
+ deriveChangeActions({
+ ...base,
+ onHand: 0,
+ demandPeriods: [
+ { periodId: "p1", startDate: "2026-10-05", quantity: 30 }
+ ],
+ openOrders: [overdueJob],
+ leadTimeDays: 7
+ }).filter((action) => action.type === "Decrease")
+ ).toEqual([]);
+ });
+
+ it("never expedites a frozen order, and the projection leaves it where it lands", () => {
+ // needed in p1 (Oct 5), lands in p3 (Oct 19); a 60-day lead time means
+ // it is already in flight
+ const late = {
+ purchaseOrderLineId: "pol-1",
+ quantity: 10,
+ dueDate: "2026-10-19",
+ requiresManualAction: false
+ };
+ const coverage = {
+ onHand: 0,
+ demandPeriods: [
+ { periodId: "p1", startDate: "2026-10-05", quantity: 10 }
+ ],
+ openOrders: [late],
+ periods: PERIODS,
+ policyFloor: 0
+ };
+ expect(
+ deriveChangeActions({
+ ...coverage,
+ toleranceDays: TOLERANCE,
+ todayDate: TODAY,
+ leadTimeDays: 60
+ })
+ ).toEqual([]);
+ expect(
+ firstNeedPeriodByOrder(coverage, {
+ toleranceDays: TOLERANCE,
+ todayDate: TODAY,
+ leadTimeDays: 60
+ }).has("pol-1")
+ ).toBe(false);
+ // with time to change it, it is expedited as before
+ expect(
+ deriveChangeActions({
+ ...coverage,
+ toleranceDays: TOLERANCE,
+ todayDate: TODAY,
+ leadTimeDays: 7
+ })[0]
+ ).toMatchObject({ type: "Expedite" });
+ });
+});
+
describe("convertOrdersToIncreases", () => {
const orderCandidate = {
type: "Order" as const,
@@ -728,6 +889,79 @@ describe("convertOrdersToIncreases", () => {
expect(action?.type).toBe("Order");
});
+ it("never grows a job past the batch size — the batch stays a new job", () => {
+ const make = {
+ ...orderCandidate,
+ type: "Make" as const,
+ supplierId: null,
+ suggestedQuantity: 50
+ };
+ const [action] = convertOrdersToIncreases({
+ sizingCandidates: [make],
+ openOrders: [
+ {
+ jobId: "job-1",
+ quantity: 50,
+ dueDate: "2026-10-12",
+ requiresManualAction: false
+ }
+ ],
+ changeActions: [],
+ toleranceDays: TOLERANCE,
+ todayDate: TODAY,
+ maximumPerOrder: 50
+ });
+ expect(action).toMatchObject({ type: "Make", suggestedQuantity: 50 });
+ });
+
+ it("still folds a suggestion the open order has room for", () => {
+ const make = {
+ ...orderCandidate,
+ type: "Make" as const,
+ supplierId: null,
+ suggestedQuantity: 20
+ };
+ const [action] = convertOrdersToIncreases({
+ sizingCandidates: [make],
+ openOrders: [
+ {
+ jobId: "job-1",
+ quantity: 30,
+ dueDate: "2026-10-12",
+ requiresManualAction: false
+ }
+ ],
+ changeActions: [],
+ toleranceDays: TOLERANCE,
+ todayDate: TODAY,
+ maximumPerOrder: 50
+ });
+ expect(action).toMatchObject({
+ type: "Increase",
+ jobId: "job-1",
+ suggestedQuantity: 50
+ });
+ });
+
+ it("never grows a PO line past the maximum order quantity", () => {
+ const [action] = convertOrdersToIncreases({
+ sizingCandidates: [orderCandidate],
+ openOrders: [
+ {
+ purchaseOrderLineId: "pol-1",
+ quantity: 10,
+ dueDate: "2026-10-12",
+ requiresManualAction: false
+ }
+ ],
+ changeActions: [],
+ toleranceDays: TOLERANCE,
+ todayDate: TODAY,
+ maximumPerOrder: 12
+ });
+ expect(action).toMatchObject({ type: "Order", suggestedQuantity: 5 });
+ });
+
it("never folds a Make suggestion into a purchase order", () => {
const [action] = convertOrdersToIncreases({
sizingCandidates: [{ ...orderCandidate, type: "Make" as const }],
diff --git a/packages/planning/src/mrp/planning-actions.ts b/packages/planning/src/mrp/planning-actions.ts
index 08669c2f62..42ee907491 100644
--- a/packages/planning/src/mrp/planning-actions.ts
+++ b/packages/planning/src/mrp/planning-actions.ts
@@ -37,7 +37,9 @@ import {
computePlanningOrders,
datetime,
equals,
+ orderSizingRules,
RoundingMode,
+ reducedOrderQuantity,
round
} from "@carbon/utils";
import { parseDate, startOfWeek } from "@internationalized/date";
@@ -259,8 +261,55 @@ export type DeriveChangeActionsInput = {
policyFloor: number;
toleranceDays: number;
todayDate: string;
+ /**
+ * How the item's policy sizes one order (`orderSizingRules`). A Decrease
+ * never takes an order below its minimum or off a whole multiple — a Fixed
+ * Reorder Quantity order stays a multiple of that quantity. Absent: none.
+ */
+ orderRules?: Pick<
+ ReturnType<typeof orderSizingRules>,
+ "minimum" | "multiples"
+ >;
+ /**
+ * The item's lead time in days. An order whose latest start (due date less
+ * lead time) has passed is frozen (`isOrderFrozen`): it gets no Expedite,
+ * Increase or Decrease. Absent: 0 — only an overdue order is frozen.
+ */
+ leadTimeDays?: number;
};
+/**
+ * An order nothing can change in time: its due date less the item's lead
+ * time is before today — every overdue order, and one due sooner than a
+ * lead time away. It is already being made or shipped, so an Expedite,
+ * Increase or Decrease on it cannot be carried out; a shortfall it cannot
+ * cover becomes new supply instead. (An Increase on an overdue job sat beside
+ * a Make for the same week, and the planner read the two as ordering twice.)
+ */
+export function isOrderFrozen(
+ order: Pick<OpenSupplyOrder, "dueDate">,
+ todayDate: string,
+ leadTimeDays = 0
+): boolean {
+ return daysBetween(order.dueDate, todayDate) < Math.max(leadTimeDays, 0);
+}
+
+/**
+ * Days an order lands after it is first needed (negative: before). Both dates
+ * count from today at the earliest: an overdue order arrives today, and a need
+ * in the current week is needed today, not on the week's start.
+ */
+function daysLate(
+ order: Pick<OpenSupplyOrder, "dueDate">,
+ firstNeed: { startDate: string },
+ todayDate: string
+): number {
+ return daysBetween(
+ laterDate(order.dueDate, todayDate),
+ laterDate(firstNeed.startDate, todayDate)
+ );
+}
+
type ChangeCandidate = Omit<
PlanningActionCandidate,
"itemId" | "locationId" | "assignee"
@@ -351,12 +400,26 @@ export function firstNeedPeriodByOrder(
input: Pick<
DeriveChangeActionsInput,
"onHand" | "demandPeriods" | "openOrders" | "periods" | "policyFloor"
- >
+ >,
+ /**
+ * With these, a FROZEN order late by more than the tolerance is left out:
+ * it gets no Expedite, so it lands when it lands, and the projection must
+ * not count it earlier — the need it misses gets new supply.
+ */
+ frozen?: { toleranceDays: number; todayDate: string; leadTimeDays?: number }
): Map<string, string> {
const needs = new Map<string, string>();
for (const { order, firstNeed } of walkOrderCoverage(input)) {
const ref = order.purchaseOrderLineId ?? order.jobId;
- if (ref && firstNeed) needs.set(ref, firstNeed.periodId);
+ if (!ref || !firstNeed) continue;
+ if (
+ frozen &&
+ isOrderFrozen(order, frozen.todayDate, frozen.leadTimeDays) &&
+ daysLate(order, firstNeed, frozen.todayDate) > frozen.toleranceDays
+ ) {
+ continue;
+ }
+ needs.set(ref, firstNeed.periodId);
}
return needs;
}
@@ -420,25 +483,29 @@ export function deriveChangeActions(
continue;
}
+ const frozen = isOrderFrozen(order, todayDate, input.leadTimeDays);
+
if (firstNeed) {
// An overdue order arrives today at the earliest, not on its old due
// date: measured from that date it read as "early" and was offered a
- // Defer to a date already past.
- const expectedDate = laterDate(order.dueDate, todayDate);
- // Likewise a need in the current week is needed today, not on the
- // week's start: Apply writes the suggested date onto the order, so an
- // Expedite to a past week start made the order overdue — read as
- // arriving today, days after the week start — and the same Expedite
- // came back every run whenever the tolerance was under a week.
+ // Defer to a date already past. Likewise a need in the current week is
+ // needed today, not on the week's start: Apply writes the suggested
+ // date onto the order, so an Expedite to a past week start made the
+ // order overdue — read as arriving today, days after the week start —
+ // and the same Expedite came back every run whenever the tolerance was
+ // under a week.
const needDate = laterDate(firstNeed.startDate, todayDate);
// gap > 0: the order lands AFTER it is needed
- const gap = daysBetween(expectedDate, needDate);
+ const gap = daysLate(order, firstNeed, todayDate);
// Moving a promised date is agreed with the supplier, not applied.
const dateTarget = {
...target,
requiresManualAction:
target.requiresManualAction || Boolean(order.dateIsPromised)
};
+ // A frozen order cannot be pulled in; the need it misses is planned
+ // as new supply (`firstNeedPeriodByOrder` leaves it where it lands).
+ if (gap > toleranceDays && frozen) continue;
if (gap > toleranceDays) {
actions.push({
...dateTarget,
@@ -470,10 +537,18 @@ export function deriveChangeActions(
// Round at the compare: `consumed` is a running float sum, so the raw
// difference can be ~1e-16 for an order that is fully required.
+ // Nor can a frozen order be cut back.
+ if (frozen) continue;
const required = round(consumed);
- // What the order holds once decreased — a PO line in whole purchase
- // units — so a line already at the rounded quantity is left alone.
- const decreasedTo = quantityAfterApply(order, required);
+ // What the order holds once decreased — no less than the policy's
+ // minimum, on its whole multiples, and a PO line in whole purchase
+ // units — so an order already at that quantity is left alone.
+ const decreasedTo = quantityAfterApply(
+ order,
+ input.orderRules
+ ? reducedOrderQuantity(required, order.quantity, input.orderRules)
+ : required
+ );
if (round(order.quantity - decreasedTo) > 0) {
const period = periodFor(order.dueDate);
actions.push({
@@ -581,8 +656,18 @@ export function convertOrdersToIncreases(args: {
changeActions: ChangeCandidate[];
toleranceDays: number;
todayDate: string;
+ /**
+ * The most one order may hold (`orderSizingRules(...).maximum`: the batch
+ * size, the fixed reorder quantity, the maximum order quantity). A
+ * suggestion is folded only into an order it fits; otherwise it stays a new
+ * order. 0 or absent: no limit.
+ */
+ maximumPerOrder?: number;
+ /** The item's lead time: a frozen order (`isOrderFrozen`) is never increased. */
+ leadTimeDays?: number;
}): ChangeCandidate[] {
const { sizingCandidates, openOrders, changeActions, toleranceDays } = args;
+ const maximumPerOrder = args.maximumPerOrder ?? 0;
// Both dates as the day they mean: an overdue order lands today, and a
// suggestion for the current week (dated its start) is needed today — so
// an order an Expedite moved to today still matches this week's shortfall.
@@ -603,6 +688,21 @@ export function convertOrdersToIncreases(args: {
const isBuy = Boolean(order.purchaseOrderLineId);
if (candidate.type === "Order" && !isBuy) return false;
if (candidate.type === "Make" && isBuy) return false;
+ if (isOrderFrozen(order, args.todayDate, args.leadTimeDays)) return false;
+ // Growing an order past what one order holds (a batch, a fixed
+ // reorder quantity, the maximum order quantity) breaks the rule it was
+ // sized by, so the suggestion stays a new order of its own.
+ if (
+ maximumPerOrder > 0 &&
+ round(
+ quantityAfterApply(
+ order,
+ order.quantity + candidate.suggestedQuantity
+ )
+ ) > maximumPerOrder
+ ) {
+ return false;
+ }
return (
Math.abs(
daysBetween(
@@ -1413,10 +1513,19 @@ export async function generatePlanningActions(
periods,
policyFloor: policyFloorFor(row)
};
+ const orderRules = orderSizingRules(
+ row.supersessionMode === "Stock Only"
+ ? "Stock Only"
+ : row.reorderingPolicy,
+ row
+ );
+ const leadTimeDays = Number(row.leadTime) || 0;
const changeActions = deriveChangeActions({
...coverageInput,
toleranceDays,
- todayDate
+ todayDate,
+ orderRules,
+ leadTimeDays
});
// new-supply suggestions from the shared sizing (same math as the grid),
@@ -1466,7 +1575,11 @@ export async function generatePlanningActions(
periods,
changeActions,
openOrders,
- firstNeedPeriods: firstNeedPeriodByOrder(coverageInput)
+ firstNeedPeriods: firstNeedPeriodByOrder(coverageInput, {
+ toleranceDays,
+ todayDate,
+ leadTimeDays
+ })
});
sizing = computePlanningOrders({
reorderingPolicy: row.reorderingPolicy,
@@ -1512,12 +1625,17 @@ export async function generatePlanningActions(
openOrders,
changeActions,
toleranceDays,
- todayDate
+ todayDate,
+ maximumPerOrder: orderRules.maximum,
+ leadTimeDays
});
// Lot-size splitting can emit several new-supply suggestions in one
// period; persist ONE action per (type, period) with the summed quantity
// — the natural key would otherwise collide and silently drop batches.
+ // The planning pages split the action back into the orders its policy
+ // sized (`splitIntoOrders`): a batch, a fixed reorder quantity, a
+ // maximum order quantity each.
const aggregated = new Map<string, ChangeCandidate>();
const passthrough: ChangeCandidate[] = [];
for (const candidate of merged) {
diff --git a/packages/utils/AGENTS.md b/packages/utils/AGENTS.md
index 5163cc6370..963fea88e2 100644
--- a/packages/utils/AGENTS.md
+++ b/packages/utils/AGENTS.md
@@ -60,7 +60,7 @@ pnpm --filter @carbon/utils typecheck
| `hash` | The repo's stable content hashes — `fnv1a32`/`fnv1a64` (cache and idempotency keys) and `getBucket`. Browser-safe; never add `node:crypto` here |
| `math` | `clamp`/`lerp`/`inverseLerp` only — it re-exports nothing |
| `mode` | Light / dark / system. `getModeFromCookies` resolves the root loader's `mode` (what to render) and `modePreference` (what the user chose): the explicit `mode` cookie wins, else the OS hint cookie, else light. `colorSchemeHintScript` is the inline `<head>` script that writes the OS hint and reloads once when a `system` user was rendered in the wrong mode. The browser-side halves (`useMode`, `useModePreference`, `getSystemMode`) live in `@carbon/react` |
-| `planning-sizing` | `computePlanningOrders` — reorder-quantity sizing for the four reordering policies (`ComputePlanningOrdersInput` — `{ reorderingPolicy, periods, projections, todayDate, params: PlanningSizingParams }` — in, `PlanningOrderSuggestion[]` out). Pure and clock-free (`todayDate` is injected). Shared by the MRP engine and the item planning tab's `ItemReorderPolicy`, so both size an order the same way; `planning-sizing.test.ts` pins it against hand-computed results of the SQL `calculate_quantity_to_order` |
+| `planning-sizing` | `computePlanningOrders` — reorder-quantity sizing for the four reordering policies (`ComputePlanningOrdersInput` — `{ reorderingPolicy, periods, projections, todayDate, params: PlanningSizingParams }` — in, `PlanningOrderSuggestion[]` out). Pure and clock-free (`todayDate` is injected). Also `orderSizingRules(policyName, params)` — how ONE order of a policy is sized (per-order quantity, daily vs spread, maximum, minimum, multiples) — shared by MRP's change actions and the planning pages: `splitIntoOrders` (a week's summed action back into its orders; `lotSizeBatches` is the batch case) and `reducedOrderQuantity` (a Decrease's floor and multiples). Shared by the MRP engine and the item planning tab's `ItemReorderPolicy`, so both size an order the same way; `planning-sizing.test.ts` pins it against hand-computed results of the SQL `calculate_quantity_to_order` |
| `precision` | The whole numeric-precision API (re-exported from `@carbon/database/precision`): `SCALE`, `EPSILON`, `RoundingMode`, `round`, `distributeRoundingResidual`, `scrapAllowance`, `applyRate`, `deriveRate`, `isBalanced`, `assertBalanced` |
| `format` | The ONLY place display/input digit counts are chosen: `moneyFormatOptions` (settlement — the currency's decimals are floor AND ceiling), `rateFormatOptions` (per-unit RATE — those decimals are only the floor, ceiling is `SCALE`), the `PERCENT_FORMAT` / `PERCENT_POINTS_FORMAT` / `SCALE_FORMAT` constants, `cldrCurrencyDecimals`, their `format*` helpers, and `INPUT_FORMAT` / `INPUT_STEP` for editable fields. Call sites pick a KIND, never a digit count |
| `string` | Slugify, truncate, camelCase/titleCase conversions |
diff --git a/packages/utils/src/planning-sizing.test.ts b/packages/utils/src/planning-sizing.test.ts
index 5a27e14b91..025812ee42 100644
--- a/packages/utils/src/planning-sizing.test.ts
+++ b/packages/utils/src/planning-sizing.test.ts
@@ -4,7 +4,13 @@
import { describe, expect, it } from "vitest";
import type { PlanningSizingParams } from "./planning-sizing";
-import { computePlanningOrders } from "./planning-sizing";
+import {
+ computePlanningOrders,
+ lotSizeBatches,
+ orderSizingRules,
+ reducedOrderQuantity,
+ splitIntoOrders
+} from "./planning-sizing";
const params = (
overrides: Partial<PlanningSizingParams> = {}
@@ -346,3 +352,190 @@ describe("computePlanningOrders", () => {
});
});
});
+
+describe("lotSizeBatches", () => {
+ it("splits into full batches with the remainder last, spread across the week", () => {
+ expect(lotSizeBatches(120, 50)).toEqual([
+ { quantity: 50, dayOffset: 0 },
+ { quantity: 50, dayOffset: 2 },
+ { quantity: 20, dayOffset: 4 }
+ ]);
+ });
+
+ it("is one order when it fits in a batch or there is no batch size", () => {
+ expect(lotSizeBatches(50, 50)).toEqual([{ quantity: 50, dayOffset: 0 }]);
+ expect(lotSizeBatches(120, 0)).toEqual([{ quantity: 120, dayOffset: 0 }]);
+ });
+});
+
+describe("orderSizingRules", () => {
+ const item = {
+ reorderPoint: 0,
+ reorderQuantity: 0,
+ minimumOrderQuantity: 0,
+ maximumOrderQuantity: 0,
+ orderMultiple: 0,
+ lotSize: 0
+ };
+
+ it("Demand-Based Reorder: one order per batch, never past batch or max", () => {
+ expect(
+ orderSizingRules("Demand-Based Reorder", {
+ ...item,
+ lotSize: 50,
+ maximumOrderQuantity: 40,
+ minimumOrderQuantity: 5,
+ orderMultiple: 10
+ })
+ ).toEqual({
+ perOrder: 50,
+ daily: false,
+ maximum: 40,
+ minimum: 5,
+ multiples: [10]
+ });
+ });
+
+ it("Fixed Reorder Quantity: every order is the fixed quantity", () => {
+ expect(
+ orderSizingRules("Fixed Reorder Quantity", {
+ ...item,
+ reorderQuantity: 100
+ })
+ ).toMatchObject({
+ perOrder: 100,
+ daily: true,
+ maximum: 100,
+ multiples: [100]
+ });
+ // no reorder quantity orders the reorder point
+ expect(
+ orderSizingRules("Fixed Reorder Quantity", { ...item, reorderPoint: 30 })
+ ).toMatchObject({ perOrder: 30, maximum: 30 });
+ });
+
+ it("Maximum Quantity: orders up to the maximum, on lot multiples", () => {
+ expect(
+ orderSizingRules("Maximum Quantity", {
+ ...item,
+ maximumOrderQuantity: 200,
+ lotSize: 50,
+ orderMultiple: 1
+ })
+ ).toEqual({
+ perOrder: 200,
+ daily: true,
+ maximum: 200,
+ minimum: 0,
+ multiples: [0, 50]
+ });
+ });
+
+ it("Stock Only and Manual Reorder size by no rule", () => {
+ for (const policy of ["Stock Only", "Manual Reorder", null]) {
+ expect(
+ orderSizingRules(policy, { ...item, lotSize: 50, orderMultiple: 10 })
+ ).toEqual({
+ perOrder: 0,
+ daily: false,
+ maximum: 0,
+ minimum: 0,
+ multiples: []
+ });
+ }
+ });
+});
+
+describe("splitIntoOrders", () => {
+ it("splits batches across the week", () => {
+ expect(splitIntoOrders(120, { perOrder: 50, daily: false })).toEqual([
+ { quantity: 50, dayOffset: 0 },
+ { quantity: 50, dayOffset: 2 },
+ { quantity: 20, dayOffset: 4 }
+ ]);
+ });
+
+ it("splits daily orders one per day", () => {
+ expect(splitIntoOrders(300, { perOrder: 100, daily: true })).toEqual([
+ { quantity: 100, dayOffset: 0 },
+ { quantity: 100, dayOffset: 1 },
+ { quantity: 100, dayOffset: 2 }
+ ]);
+ });
+
+ it("is the whole quantity with no per-order size", () => {
+ expect(splitIntoOrders(300, { perOrder: 0, daily: true })).toEqual([
+ { quantity: 300, dayOffset: 0 }
+ ]);
+ });
+
+ // The split must give back exactly the orders computePlanningOrders sized
+ // for the week, or summing them into one action loses them.
+ it.each([
+ [
+ "Fixed Reorder Quantity",
+ { reorderPoint: 250, reorderQuantity: 100 },
+ [-10]
+ ],
+ [
+ "Maximum Quantity",
+ {
+ reorderPoint: 400,
+ reorderQuantity: 1,
+ maximumInventoryQuantity: 500,
+ maximumOrderQuantity: 200
+ },
+ [0]
+ ],
+ [
+ "Demand-Based Reorder",
+ { demandAccumulationSafetyStock: 120, lotSize: 50 },
+ [0]
+ ]
+ ] as const)("round-trips the week %s sized", (policy, overrides, projections) => {
+ const orders = computePlanningOrders({
+ reorderingPolicy: policy,
+ periods: weeklyPeriods(["2026-10-05"]),
+ projections: [...projections],
+ todayDate: TODAY,
+ params: params(overrides)
+ });
+ expect(orders.length).toBeGreaterThan(1);
+ const total = orders.reduce((sum, o) => sum + o.quantity, 0);
+ expect(
+ splitIntoOrders(total, orderSizingRules(policy, params(overrides))).map(
+ (o) => o.quantity
+ )
+ ).toEqual(orders.map((o) => o.quantity));
+ });
+});
+
+describe("reducedOrderQuantity", () => {
+ const rules = { minimum: 0, multiples: [] as number[] };
+
+ it("is the requirement when the item has no order rules", () => {
+ expect(reducedOrderQuantity(37, 50, rules)).toBe(37);
+ });
+
+ it("rounds up to a whole order multiple", () => {
+ expect(reducedOrderQuantity(37, 50, { ...rules, multiples: [10] })).toBe(
+ 40
+ );
+ });
+
+ it("rounds up to every multiple in turn", () => {
+ expect(
+ reducedOrderQuantity(37, 200, { ...rules, multiples: [10, 25] })
+ ).toBe(50);
+ });
+
+ it("never goes below the minimum order quantity", () => {
+ expect(reducedOrderQuantity(12, 50, { ...rules, minimum: 25 })).toBe(25);
+ });
+
+ it("never exceeds the order as it stands", () => {
+ expect(reducedOrderQuantity(42, 45, { ...rules, multiples: [10] })).toBe(
+ 45
+ );
+ });
+});
diff --git a/packages/utils/src/planning-sizing.ts b/packages/utils/src/planning-sizing.ts
index 419adc461c..8723a712c9 100644
--- a/packages/utils/src/planning-sizing.ts
+++ b/packages/utils/src/planning-sizing.ts
@@ -67,6 +67,159 @@ const ceilUnits = (value: number): number => round(value, 0, RoundingMode.Up);
/** Integer floor of a non-negative integer division (a, b integers, b > 0). */
const intFloorDiv = (a: number, b: number): number => (a - (a % b)) / b;
+/** Weekly planning periods. */
+const DAYS_IN_PERIOD = 7;
+
+export type PlannedOrderSplit = {
+ quantity: number;
+ /** Days after the week's first order this one is due. */
+ dayOffset: number;
+};
+
+/**
+ * One order per batch: an order larger than the batch size (`lotSize`) is
+ * made in full batches with the remainder last, due dates spread evenly across
+ * the week. A batch size of 0, or an order that fits in one batch, is one
+ * order. How Demand-Based Reorder splits its order.
+ */
+export function lotSizeBatches(
+ quantity: number,
+ lotSize: number
+): PlannedOrderSplit[] {
+ if (!(lotSize > 0) || quantity <= lotSize) {
+ return [{ quantity, dayOffset: 0 }];
+ }
+ const numberOfBatches = ceilUnits(quantity / lotSize);
+ return Array.from({ length: numberOfBatches }, (_, batch) => ({
+ quantity: Math.min(lotSize, quantity - batch * lotSize),
+ // integer floor — mirrors the original Math.floor without a raw-rounding call
+ dayOffset: intFloorDiv(batch * DAYS_IN_PERIOD, numberOfBatches)
+ }));
+}
+
+export type OrderSizingParams = Pick<
+ PlanningSizingParams,
+ | "reorderPoint"
+ | "reorderQuantity"
+ | "minimumOrderQuantity"
+ | "maximumOrderQuantity"
+ | "orderMultiple"
+ | "lotSize"
+>;
+
+/**
+ * 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.
+ * - `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.
+ * - `minimum` / `multiples`: the least an order holds, and what it is a whole
+ * multiple of.
+ *
+ * MRP keeps one Order / Make action per item and week, so the orders a week
+ * needs are summed into it; the planning pages split it back by `perOrder`
+ * (`splitIntoOrders`). An Increase may not grow an order past `maximum`, and
+ * a Decrease keeps `minimum` and `multiples` (`reducedOrderQuantity`).
+ * Stock Only, Manual Reorder and an unknown policy size by none of them.
+ */
+export function orderSizingRules(
+ policyName: string | null | undefined,
+ params: OrderSizingParams
+): {
+ perOrder: number;
+ daily: boolean;
+ maximum: number;
+ minimum: number;
+ multiples: number[];
+} {
+ const lotSize = Number(params.lotSize) || 0;
+ const maximumOrderQuantity = Number(params.maximumOrderQuantity) || 0;
+ const minimumOrderQuantity = Number(params.minimumOrderQuantity) || 0;
+ const orderMultiple = Number(params.orderMultiple) || 0;
+ switch (policyName) {
+ case "Demand-Based Reorder": {
+ const limits = [lotSize, maximumOrderQuantity].filter((n) => n > 0);
+ return {
+ perOrder: lotSize,
+ daily: false,
+ maximum: limits.length > 0 ? Math.min(...limits) : 0,
+ minimum: minimumOrderQuantity,
+ multiples: [orderMultiple]
+ };
+ }
+ case "Fixed Reorder Quantity": {
+ const reorderQuantity = Number(params.reorderQuantity) || 0;
+ // as computePlanningOrders: no reorder quantity orders the reorder point
+ const fixed =
+ reorderQuantity > 0
+ ? reorderQuantity
+ : Number(params.reorderPoint) || 0;
+ return {
+ perOrder: fixed,
+ daily: true,
+ maximum: fixed,
+ minimum: 0,
+ multiples: [fixed]
+ };
+ }
+ case "Maximum Quantity":
+ return {
+ perOrder: maximumOrderQuantity,
+ daily: true,
+ maximum: maximumOrderQuantity,
+ minimum: minimumOrderQuantity,
+ // as computePlanningOrders: a multiple of 1 is no rule
+ multiples: [orderMultiple > 1 ? orderMultiple : 0, lotSize]
+ };
+ default:
+ return {
+ perOrder: 0,
+ daily: false,
+ maximum: 0,
+ minimum: 0,
+ multiples: []
+ };
+ }
+}
+
+/**
+ * A week's summed Order / Make quantity split back into the orders its policy
+ * sizes: full orders of `perOrder` with the remainder last, one per day
+ * (`daily`) or spread across the week (batches).
+ */
+export function splitIntoOrders(
+ quantity: number,
+ rules: Pick<ReturnType<typeof orderSizingRules>, "perOrder" | "daily">
+): PlannedOrderSplit[] {
+ const split = lotSizeBatches(quantity, rules.perOrder);
+ if (!rules.daily) return split;
+ return split.map((order, index) => ({
+ ...order,
+ dayOffset: Math.min(index, DAYS_IN_PERIOD - 1)
+ }));
+}
+
+/**
+ * What an open order may be reduced to when only `required` of it is needed:
+ * at least the policy's minimum and a whole multiple of each of its multiples.
+ * Never more than `current`, the order as it stands.
+ */
+export function reducedOrderQuantity(
+ required: number,
+ current: number,
+ rules: Pick<ReturnType<typeof orderSizingRules>, "minimum" | "multiples">
+): number {
+ let quantity = Math.max(required, rules.minimum);
+ for (const multiple of rules.multiples) {
+ if (multiple > 0) quantity = ceilToMultiple(quantity, multiple);
+ }
+ return Math.min(quantity, current);
+}
+
export function computePlanningOrders(
input: ComputePlanningOrdersInput
): PlanningOrderSuggestion[] {
@@ -155,57 +308,17 @@ export function computePlanningOrders(
);
}
- // If we have a lot size and need to split orders
- if (lotSize > 0 && totalOrderQuantity > lotSize) {
- const numberOfBatches = ceilUnits(totalOrderQuantity / lotSize);
- const daysInPeriod = 7; // Weekly periods
-
- for (let batch = 0; batch < numberOfBatches; batch++) {
- const batchQuantity = Math.min(
- lotSize,
- totalOrderQuantity - batch * lotSize
- );
-
- // Spread due dates evenly across the period (integer floor —
- // mirrors the original Math.floor without a raw-rounding call)
- const dueDateOffset = intFloorDiv(
- batch * daysInPeriod,
- numberOfBatches
- );
- const dueDate = parseDate(currentPeriod.startDate).add({
- days: dueDateOffset
- });
- const startDate = dueDate.subtract({ days: leadTime });
-
- orders.push({
- startDate: startDate.toString(),
- dueDate: dueDate.toString(),
- quantity: batchQuantity,
- periodId: currentPeriod.id,
- isASAP: startDate.compare(todaysDate) < 0,
- policyName: "Demand-Based Reorder",
- triggerValues: {
- projectedStock: endOfWindowProjection,
- safetyStock: demandAccumulationSafetyStock,
- lotSize,
- leadTime
- }
- });
- }
- } else {
- // Single order for the period
- const orderQuantity =
- lotSize > 0
- ? Math.min(totalOrderQuantity, lotSize)
- : totalOrderQuantity;
-
- const dueDate = parseDate(currentPeriod.startDate);
+ // One order per batch, due dates spread across the period
+ for (const batch of lotSizeBatches(totalOrderQuantity, lotSize)) {
+ const dueDate = parseDate(currentPeriod.startDate).add({
+ days: batch.dayOffset
+ });
const startDate = dueDate.subtract({ days: leadTime });
orders.push({
startDate: startDate.toString(),
dueDate: dueDate.toString(),
- quantity: orderQuantity,
+ quantity: batch.quantity,
periodId: currentPeriod.id,
isASAP: startDate.compare(todaysDate) < 0,
policyName: "Demand-Based Reorder",