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(inventory): honor item supersession in picking lists (#1210) (#1288)

Carbon Agent7459366f114b
diff --git a/.ai/plans/2026-07-30-picking-supersession-1210.md b/.ai/plans/2026-07-30-picking-supersession-1210.md
new file mode 100644
index 0000000000..26243f072c
--- /dev/null
+++ b/.ai/plans/2026-07-30-picking-supersession-1210.md
@@ -0,0 +1,100 @@
+# Plan: Picking Lists Honor Item Supersession (#1210)
+
+- **Date:** 2026-07-30
+- **Branch:** `fix/picking-supersession-1210` → PR base `main`
+- **Issue:** https://github.com/crbnos/carbon/issues/1210
+
+## Problem
+
+Picking ignores `itemSupersession` entirely:
+1. **Superseded predecessors surface for picking** — `get_picking_schedule` counts
+ `Stock Only` (spares-only) and `No Stock` (obsolete) materials as production pick demand.
+2. **Successors are never considered** — when a job material references a superseded item that
+ is out of stock, generation/availability never redirect to the effective successor
+ (`successorItemId`, effectivity date, conversion factor), so jobs show false shortages.
+
+## Grounded current state
+
+- `itemSupersession(itemId PK, companyId, supersessionMode, successorItemId, discontinuationDate,
+ successorEffectivityDate, conversionFactor DEFAULT 1)`. `minimumReserveQuantity` lives on
+ `itemPlanning` (per item+location). Modes: `Consume First`, `Prefer New`, `Stock Only`, `No Stock`.
+- Precedent — `get_purchasing_planning`/`get_production_planning` (`20260618171234`) exclude
+ `No Stock` + past-discontinuation phase-out items and floor `Stock Only` to the reserve.
+- Precedent — shared `buildSupersessionRedirectMap` (`functions/lib/supersession-pick.ts`) used by
+ MRP + job creation; **only** `Consume First`/`Prefer New` redirect there (Stock Only is
+ reserve-governed for *planning*). Picking differs — see D2.
+- `get_picking_schedule` (`20260720160557`): per-**operation** aggregate; the `picks` CTE reads
+ `jobMaterial` where `quantityToIssue > 0`. The material `itemId` is used only in the staged-lineside
+ check (not surfaced). Output `itemId` is the make-method's parent assembly.
+- `generatePickingList` (`inventory.service.ts` ~L3151): copies `jobMaterial.itemId` verbatim onto
+ each `pickingListLine`. **The substitution injection point.**
+- `get_picking_list_availability` (`20260614183507`): per line, warehouse on-hand of `pll.itemId`.
+- `pickingListLine.jobMaterialId` FK already links back to the source material → a substitution is
+ derivable as `line.itemId != jobMaterial.itemId`. **No new column needed.**
+
+## Design decisions
+
+- **D1 — No schema/type changes.** RPCs keep their exact `RETURNS TABLE` (filter rows only);
+ substitution reuses existing columns and `itemSupersession` is already in the generated types, so
+ no generated type is expected to change. Even so, per repo convention **run `pnpm run generate:types`
+ after any migration change, before typechecking** (regenerate in CI or an approved DB environment
+ when local Postgres is unavailable) rather than relying on the committed generated types.
+- **D2 — Picking-specific redirect semantics** (differs from MRP's map):
+ | Mode | Pick behavior |
+ |------|---------------|
+ | `Consume First` | Pick predecessor; **only** when predecessor has zero warehouse on-hand AND an effective successor with stock exists → substitute the line to the successor. (Conservative: never leaves predecessor stock unused, satisfies "predecessor out of stock → pick successor".) |
+ | `Prefer New` | Effective successor → pick successor; else predecessor (fallback until effective). |
+ | `Stock Only` | Effective successor → pick successor (no production use of the reserved predecessor); else **skip** (nothing valid to pick). |
+ | `No Stock` | **Skip** (obsolete, no successor). |
+ - "Effective successor" = `successorItemId` set AND (`successorEffectivityDate` IS NULL OR `<= today`).
+ - Conversion: successor `quantityToPick = quantityToIssue * conversionFactor`.
+- **D3 — No line splitting.** One `pickingListLine` per `jobMaterial` preserved (downstream
+ consumption assumes it). Consume First substitutes the *whole* line only when the predecessor is
+ fully out — avoids a 2-line split whose FK/consumption impact can't be verified without a DB.
+- **D4 — Discontinuation date does NOT suppress picks.** Planning suppresses *new orders* past
+ discontinuation; picking *fulfills existing job demand*. A job that already needs the part must
+ still be pickable. Only supersession *mode* + successor effectivity gate picking.
+ - **Effective-date rule (one basis for both layers).** Successor effectivity is evaluated against
+ the **UTC calendar date** everywhere: the SQL uses `(now() AT TIME ZONE 'UTC')::date` and
+ `generatePickingList` uses `today("UTC")`. This removes any DB-session / server-process timezone
+ skew, so generation and the schedule/availability RPCs always resolve the same effective successor
+ (no boundary case where availability checks the predecessor while generation writes the successor).
+- **D5 — Availability RPC** reports the line's OWN pick item warehouse on-hand. Because generation
+ already redirects a substituted line's `itemId` to the effective successor (D2/D3), `availableQuantity`
+ reflects exactly what the line consumes — no successor fold-in. Folding a successor's stock into a
+ line still targeting the predecessor is deliberately avoided: with no line-splitting (D3) that line
+ consumes the predecessor, so a fold-in would mask a real predecessor shortage and could double-count
+ a successor that also has its own line on the list. Shape unchanged.
+- **D6 — UI marker** (polish): `getPickingListLines` also selects `jobMaterial(itemId)`; the line
+ table shows a "↩ from &lt;predecessor&gt;" marker when `line.itemId != jobMaterial.itemId`.
+
+## Tasks
+
+1. **Migration** `packages/database/supabase/migrations/{ts}_picking-supersession.sql`:
+ - `CREATE OR REPLACE FUNCTION get_picking_schedule(...)` — same signature/return; in the `picks`
+ CTE add a LEFT JOIN LATERAL resolving each material's `pickItemId` (D2, single-hop), exclude
+ rows where `pickItemId IS NULL`, and key the staged-lineside check on `pickItemId`.
+ - `CREATE OR REPLACE FUNCTION get_picking_list_availability(...)` — same signature/return; the
+ line's own pick-item warehouse on-hand, no successor fold-in (D5).
+ - Verify: no precision on `NUMERIC`; `SECURITY INVOKER`; identical `RETURNS TABLE`.
+2. **`generatePickingList`** (`inventory.service.ts`): fetch `itemSupersession` for the materials'
+ items; a pure `resolvePickTarget(...)` helper (D2) chooses `{ itemId, factor }` or skip; compute
+ on-hand/source for the resolved item; write `itemId` = resolved, `quantityToPick` = converted.
+3. **`getPickingListLines`**: add `jobMaterial(itemId)` to the select (D6).
+4. **UI** `PickingListLines.tsx`: render the substituted-from marker (D6).
+5. **Test** (`inventory` vitest): unit-test `resolvePickTarget` across all four modes + effectivity +
+ conversion + out-of-stock branch (red→green).
+6. **Verify:** `pnpm run generate:types` (after the migration, before typecheck — run in CI/an approved
+ DB env if local Postgres is unavailable); `pnpm exec turbo run typecheck --filter=erp
+ --filter=@carbon/database`; `pnpm run lint`; the new unit test. (No local DB → RPC bodies verified by
+ SQL review, not applied.)
+
+## Out of scope / risks
+
+- Multi-hop supersession chains in SQL are single-hop only (matches planning-function style); the TS
+ resolver can collapse if needed but MRP/job-creation already redirect at creation, so a chained
+ predecessor reaching picking is an edge case.
+- No browser/DB verification here (env has no Postgres). Migration correctness is by review; the PR is
+ `agent:needs-verification` for a human to apply + smoke-test.
+</content>
+</invoke>
diff --git a/.claude/rules/inventory-system.md b/.claude/rules/inventory-system.md
index a1a549a306..b9b4677f72 100644
--- a/.claude/rules/inventory-system.md
+++ b/.claude/rules/inventory-system.md
@@ -54,7 +54,18 @@ Key service functions (verified):
- Tracking: `getTrackedEntities`, `getAvailableTrackedEntities` (RPC `get_available_tracked_entities`),
`getSerialNumbersForItem`, `getBatchNumbersForItem`, `getShelfLifeForItems`, `getPickOrder` (FEFO/FIFO).
- Picking: `generatePickingList`, `getPickingListAvailability` (RPC `get_picking_list_availability`),
- `getPickingSchedule` (RPC `get_picking_schedule`).
+ `getPickingSchedule` (RPC `get_picking_schedule`). These honor `itemSupersession`
+ (`20260730143512_picking-supersession.sql` + `inventory/supersession-pick.ts`
+ `resolvePickTarget`): `Prefer New`/`Stock Only` redirect a pick to the effective successor
+ (× `conversionFactor`); `Consume First` redirects only when the predecessor is out of warehouse
+ stock; `No Stock` (and `Stock Only` without an effective successor) is dropped from the schedule
+ and skipped in generation. Note picking's redirect rules differ from the MRP/job-creation map
+ (`functions/lib/supersession-pick.ts`, which redirects only `Consume First`/`Prefer New`) —
+ for picking, `Stock Only` must not be picked for production. A substituted line's `itemId`
+ differs from its `jobMaterial.itemId` (no new column); the availability RPC reports the
+ line's OWN pick item's warehouse on-hand with NO successor fold-in — a substituted line
+ already targets the successor, and folding successor stock into a line still targeting the
+ predecessor would mask a real shortage and double-count the successor.
Validators in `inventory.models.ts`: `inventoryAdjustmentValidator`, `receiptValidator`,
`shipmentValidator`, `stockTransferValidator`, `warehouseTransferValidator`, `storageUnitValidator`,
diff --git a/apps/erp/app/modules/inventory/inventory.service.ts b/apps/erp/app/modules/inventory/inventory.service.ts
index 4a71522fcb..1f2859d224 100644
--- a/apps/erp/app/modules/inventory/inventory.service.ts
+++ b/apps/erp/app/modules/inventory/inventory.service.ts
@@ -35,6 +35,11 @@ import {
isPickingListLocked,
reconcileReceiptLineSerials
} from "./inventory.models";
+import {
+ effectiveSuccessorId,
+ type PickSupersession,
+ resolvePickTarget
+} from "./supersession-pick";
export async function deleteBatchProperty(
client: SupabaseClient<Database>,
@@ -2715,7 +2720,7 @@ export async function getPickingListLines(
return client
.from("pickingListLine")
.select(
- "*, item(name, readableId, itemTrackingType), job(jobId), jobOperation(order, processId, workCenterId, process:process(name), workCenter:workCenter(name)), storageUnit:storageUnit!pickingListLine_storageUnitId_fkey(name, locationId), toStorageUnit:storageUnit!pickingListLine_toStorageUnitId_fkey(name, locationId), trackedEntities:pickingListLineTrackedEntity(trackedEntityId, quantity, quantityPicked, trackedEntity(readableId))"
+ "*, item(name, readableId, itemTrackingType), jobMaterial(itemId, item(readableId)), job(jobId), jobOperation(order, processId, workCenterId, process:process(name), workCenter:workCenter(name)), storageUnit:storageUnit!pickingListLine_storageUnitId_fkey(name, locationId), toStorageUnit:storageUnit!pickingListLine_toStorageUnitId_fkey(name, locationId), trackedEntities:pickingListLineTrackedEntity(trackedEntityId, quantity, quantityPicked, trackedEntity(readableId))"
)
.eq("pickingListId", pickingListId)
.order("jobOperationId")
@@ -3170,6 +3175,55 @@ async function resolveWarehouseSource(
return null;
}
+/**
+ * Whether an item has any WAREHOUSE (non-lineside) on-hand at a location,
+ * INCLUDING the unassigned (null storage unit) bin.
+ *
+ * This is the stock *test*, deliberately decoupled from `resolveWarehouseSource`
+ * (which selects a concrete source shelf and so cannot see null-bin stock). The
+ * picking UI (`PickingListLines`) likewise treats unassigned-bin on-hand as real
+ * stock, so a `Consume First` predecessor must not be judged "out of stock"
+ * merely because all of its on-hand sits in the unassigned bin — that would
+ * spuriously redirect the pick to the successor and leave predecessor stock
+ * unused.
+ */
+async function hasWarehouseStock(
+ client: SupabaseClient<Database>,
+ args: { itemId: string; locationId: string; companyId: string }
+): Promise<boolean> {
+ const quantities = await getItemStorageUnitQuantities(
+ client,
+ args.itemId,
+ args.companyId,
+ args.locationId
+ );
+
+ const perUnit = new Map<string, number>();
+ let unassignedQty = 0;
+ for (const row of quantities.data ?? []) {
+ const unitId = (row as { storageUnitId?: string | null }).storageUnitId;
+ const qty = Number((row as { quantity?: number | null }).quantity ?? 0);
+ // The unassigned (null) bin is warehouse stock — it has no work center.
+ if (!unitId) {
+ unassignedQty += qty;
+ } else {
+ perUnit.set(unitId, (perUnit.get(unitId) ?? 0) + qty);
+ }
+ }
+ if (unassignedQty > 0) return true;
+
+ for (const [storageUnitId, qty] of perUnit) {
+ if (qty <= 0) continue;
+ const effectiveWc = await client.rpc("get_effective_work_center_id", {
+ p_storage_unit_id: storageUnitId
+ });
+ // Any non-lineside bin with on-hand counts as available warehouse stock.
+ if (!effectiveWc.data) return true;
+ }
+
+ return false;
+}
+
export async function generatePickingList(
client: SupabaseClient<Database>,
args: {
@@ -3280,6 +3334,52 @@ export async function generatePickingList(
return { data: null, error: materials.error };
}
+ // Supersession config for every demanded material, so a pick can honor an
+ // item's supersession: redirect to an effective successor (Prefer New /
+ // Stock Only) or, for Consume First, when the predecessor is out of stock.
+ // Mirrors get_picking_schedule's SQL resolution.
+ const materialItemIds = Array.from(
+ new Set((materials.data ?? []).map((m) => m.itemId))
+ );
+ const supersessionByItem = new Map<string, PickSupersession>();
+ if (materialItemIds.length > 0) {
+ const supersessions = await client
+ .from("itemSupersession")
+ .select(
+ "itemId, supersessionMode, successorItemId, successorEffectivityDate, conversionFactor"
+ )
+ .eq("companyId", args.companyId)
+ .in("itemId", materialItemIds);
+ if (supersessions.error) {
+ await client.from("pickingList").delete().eq("id", plId);
+ return { data: null, error: supersessions.error };
+ }
+ for (const row of supersessions.data ?? []) {
+ supersessionByItem.set(row.itemId, row);
+ }
+ }
+ // Business date for supersession effectivity. Uses UTC to match the SQL
+ // schedule/availability path — get_picking_schedule and
+ // get_picking_list_availability compare successorEffectivityDate against the
+ // UTC calendar date ((now() AT TIME ZONE 'UTC')::date) — so generation and
+ // those RPCs never resolve a different effective successor at a timezone
+ // boundary.
+ const asOfDate = today("UTC").toString();
+
+ // Cache per-item on-hand-by-bin so a supersession redirect doesn't refetch.
+ const onHandCache = new Map<string, Map<string, number>>();
+ const onHandFor = async (itemId: string): Promise<Map<string, number>> => {
+ const cached = onHandCache.get(itemId);
+ if (cached) return cached;
+ const map = await getItemOnHandByStorageUnit(client, {
+ itemId,
+ locationId: args.locationId,
+ companyId: args.companyId
+ });
+ onHandCache.set(itemId, map);
+ return map;
+ };
+
// Lazily resolve (and cache) the lineside destination per work center. A
// pick is a transfer from the warehouse source to this lineside shelf;
// production later consumes from it.
@@ -3336,49 +3436,88 @@ export async function generatePickingList(
// 5. Resolve the destination: the operation's work-center lineside shelf.
const toStorageUnitId = await resolveLineside(opWorkCenterId);
- // On-hand of this item per bin at the location (computed once, reused below
- // for both the already-staged skip and warehouse-source resolution).
- const onHandByUnit = await getItemOnHandByStorageUnit(client, {
+ // 6. Honor supersession: decide which item this pick targets. Consume First
+ // needs to know whether the predecessor is out of warehouse stock (and the
+ // successor has stock), so probe those sources first — for that mode only.
+ // The stock TEST uses total non-lineside on-hand (including the unassigned
+ // bin) rather than a resolvable concrete source, so predecessor stock sitting
+ // only in the unassigned bin still blocks a spurious successor redirect.
+ const supersession = supersessionByItem.get(mat.itemId);
+ let predecessorInStock = true;
+ let successorInStock = true;
+ if (supersession?.supersessionMode === "Consume First") {
+ predecessorInStock = await hasWarehouseStock(client, {
+ itemId: mat.itemId,
+ locationId: args.locationId,
+ companyId: args.companyId
+ });
+ const successorId = effectiveSuccessorId(supersession, asOfDate);
+ if (successorId && !predecessorInStock) {
+ successorInStock = await hasWarehouseStock(client, {
+ itemId: successorId,
+ locationId: args.locationId,
+ companyId: args.companyId
+ });
+ }
+ }
+
+ const target = resolvePickTarget({
itemId: mat.itemId,
- locationId: args.locationId,
- companyId: args.companyId
+ supersession,
+ predecessorInStock,
+ successorInStock,
+ asOfDate
});
-
- // Skip when the op's lineside bin already stocks enough to cover the issue —
- // it's already staged here, so there's nothing to pick. We test the ACTUAL
- // on-hand at that bin, not merely whether the jobMaterial's recorded shelf
- // points there: a part can be line-stocked at this work center while the
- // jobMaterial still points at the warehouse (or another line).
+ // Nothing valid to pick for production (No Stock, or Stock Only without an
+ // effective successor) — drop it, matching get_picking_schedule.
+ if (target.kind === "skip") continue;
+
+ const pickItemId = target.itemId;
+ const quantityToPick = quantityToIssue * target.factor;
+
+ // On-hand of the resolved PICK item per bin at the location (reused for the
+ // already-staged skip and warehouse-source resolution).
+ const onHandByUnit = await onHandFor(pickItemId);
+
+ // Skip when the op's lineside bin already stocks enough of the pick item to
+ // cover the (converted) quantity — it's already staged here, so there's
+ // nothing to pick. We test the ACTUAL on-hand at that bin, not merely
+ // whether the jobMaterial's recorded shelf points there: a part can be
+ // line-stocked at this work center while the jobMaterial still points at the
+ // warehouse (or another line).
if (
toStorageUnitId &&
- (onHandByUnit.get(toStorageUnitId) ?? 0) >= quantityToIssue
+ (onHandByUnit.get(toStorageUnitId) ?? 0) >= quantityToPick
) {
continue;
}
- // 6. Determine the source (warehouse) shelf. Use the jobMaterial's shelf
- // only when it's a warehouse (non-lineside) shelf; otherwise resolve a
- // warehouse source by on-hand — never rob another work center's lineside.
- // A null source = a shortage the kitter/planner must resolve.
- let materialEffectiveWc: string | null = null;
- if (mat.storageUnitId) {
+ // 7. Determine the source (warehouse) shelf. The jobMaterial's recorded
+ // shelf is only meaningful when we're picking that same item (the
+ // predecessor); for a substituted successor, resolve a warehouse source by
+ // on-hand. Use the recorded shelf only when it's a warehouse (non-lineside)
+ // shelf; otherwise resolve by on-hand — never rob another work center's
+ // lineside. A null source = a shortage the kitter/planner must resolve.
+ let sourceStorageUnitId: string | null;
+ if (pickItemId === mat.itemId && mat.storageUnitId) {
const effectiveWc = await client.rpc("get_effective_work_center_id", {
p_storage_unit_id: mat.storageUnitId
});
- materialEffectiveWc = (effectiveWc.data as string | null) ?? null;
+ const materialEffectiveWc = (effectiveWc.data as string | null) ?? null;
+ sourceStorageUnitId = materialEffectiveWc
+ ? await resolveWarehouseSource(client, onHandByUnit)
+ : mat.storageUnitId;
+ } else {
+ sourceStorageUnitId = await resolveWarehouseSource(client, onHandByUnit);
}
- const sourceStorageUnitId =
- mat.storageUnitId && !materialEffectiveWc
- ? mat.storageUnitId
- : await resolveWarehouseSource(client, onHandByUnit);
lineRows.push({
pickingListId: plId,
jobId: mat.jobId,
jobMaterialId: mat.id,
jobOperationId: effectiveOperationId,
- itemId: mat.itemId,
- quantityToPick: quantityToIssue,
+ itemId: pickItemId,
+ quantityToPick,
storageUnitId: sourceStorageUnitId,
toStorageUnitId,
companyId: args.companyId,
diff --git a/apps/erp/app/modules/inventory/supersession-pick.test.ts b/apps/erp/app/modules/inventory/supersession-pick.test.ts
new file mode 100644
index 0000000000..413e85c057
--- /dev/null
+++ b/apps/erp/app/modules/inventory/supersession-pick.test.ts
@@ -0,0 +1,169 @@
+import { describe, expect, it } from "vitest";
+import {
+ effectiveSuccessorId,
+ type PickSupersession,
+ resolvePickTarget
+} from "./supersession-pick";
+
+const TODAY = "2026-07-30";
+
+const ss = (over: Partial<PickSupersession>): PickSupersession => ({
+ supersessionMode: "Consume First",
+ successorItemId: "SUCC",
+ successorEffectivityDate: null,
+ conversionFactor: 1,
+ ...over
+});
+
+describe("effectiveSuccessorId", () => {
+ it("returns the successor when effectivity is null (immediate)", () => {
+ expect(effectiveSuccessorId(ss({}), TODAY)).toBe("SUCC");
+ });
+ it("returns the successor when effectivity date has passed", () => {
+ expect(
+ effectiveSuccessorId(
+ ss({ successorEffectivityDate: "2026-01-01" }),
+ TODAY
+ )
+ ).toBe("SUCC");
+ });
+ it("returns null before the effectivity date", () => {
+ expect(
+ effectiveSuccessorId(
+ ss({ successorEffectivityDate: "2026-12-31" }),
+ TODAY
+ )
+ ).toBeNull();
+ });
+ it("returns null when there is no successor", () => {
+ expect(
+ effectiveSuccessorId(ss({ successorItemId: null }), TODAY)
+ ).toBeNull();
+ });
+});
+
+describe("resolvePickTarget", () => {
+ const base = {
+ itemId: "OLD",
+ predecessorInStock: true,
+ successorInStock: true,
+ asOfDate: TODAY
+ };
+
+ it("picks the item unchanged when there is no supersession", () => {
+ expect(resolvePickTarget({ ...base, supersession: undefined })).toEqual({
+ kind: "pick",
+ itemId: "OLD",
+ factor: 1
+ });
+ });
+
+ it("skips a No Stock (obsolete) material", () => {
+ expect(
+ resolvePickTarget({
+ ...base,
+ supersession: ss({
+ supersessionMode: "No Stock",
+ successorItemId: null
+ })
+ })
+ ).toEqual({ kind: "skip" });
+ });
+
+ it("redirects Stock Only to the effective successor with its factor", () => {
+ expect(
+ resolvePickTarget({
+ ...base,
+ supersession: ss({
+ supersessionMode: "Stock Only",
+ conversionFactor: 2
+ })
+ })
+ ).toEqual({ kind: "pick", itemId: "SUCC", factor: 2 });
+ });
+
+ it("skips Stock Only when the successor is not yet effective", () => {
+ expect(
+ resolvePickTarget({
+ ...base,
+ supersession: ss({
+ supersessionMode: "Stock Only",
+ successorEffectivityDate: "2026-12-31"
+ })
+ })
+ ).toEqual({ kind: "skip" });
+ });
+
+ it("redirects Prefer New to the effective successor", () => {
+ expect(
+ resolvePickTarget({
+ ...base,
+ supersession: ss({
+ supersessionMode: "Prefer New",
+ conversionFactor: 3
+ })
+ })
+ ).toEqual({ kind: "pick", itemId: "SUCC", factor: 3 });
+ });
+
+ it("falls back to the predecessor for Prefer New before effectivity", () => {
+ expect(
+ resolvePickTarget({
+ ...base,
+ supersession: ss({
+ supersessionMode: "Prefer New",
+ successorEffectivityDate: "2026-12-31"
+ })
+ })
+ ).toEqual({ kind: "pick", itemId: "OLD", factor: 1 });
+ });
+
+ it("keeps Consume First on the predecessor while it has stock", () => {
+ expect(
+ resolvePickTarget({
+ ...base,
+ predecessorInStock: true,
+ supersession: ss({ supersessionMode: "Consume First" })
+ })
+ ).toEqual({ kind: "pick", itemId: "OLD", factor: 1 });
+ });
+
+ it("redirects Consume First to the successor when the predecessor is out and the successor has stock", () => {
+ expect(
+ resolvePickTarget({
+ ...base,
+ predecessorInStock: false,
+ successorInStock: true,
+ supersession: ss({
+ supersessionMode: "Consume First",
+ conversionFactor: 2
+ })
+ })
+ ).toEqual({ kind: "pick", itemId: "SUCC", factor: 2 });
+ });
+
+ it("keeps Consume First on the predecessor when both are out (shortage the planner resolves)", () => {
+ expect(
+ resolvePickTarget({
+ ...base,
+ predecessorInStock: false,
+ successorInStock: false,
+ supersession: ss({ supersessionMode: "Consume First" })
+ })
+ ).toEqual({ kind: "pick", itemId: "OLD", factor: 1 });
+ });
+
+ it("keeps Consume First on the predecessor when the successor is not yet effective", () => {
+ expect(
+ resolvePickTarget({
+ ...base,
+ predecessorInStock: false,
+ successorInStock: true,
+ supersession: ss({
+ supersessionMode: "Consume First",
+ successorEffectivityDate: "2026-12-31"
+ })
+ })
+ ).toEqual({ kind: "pick", itemId: "OLD", factor: 1 });
+ });
+});
diff --git a/apps/erp/app/modules/inventory/supersession-pick.ts b/apps/erp/app/modules/inventory/supersession-pick.ts
new file mode 100644
index 0000000000..a1346f90ac
--- /dev/null
+++ b/apps/erp/app/modules/inventory/supersession-pick.ts
@@ -0,0 +1,97 @@
+// Picking-side supersession resolution: given a job material's item and its
+// supersession config, decide which item a pick should actually target.
+//
+// This is intentionally SEPARATE from the MRP / job-creation redirect map
+// (packages/database/supabase/functions/lib/supersession-pick.ts), which only
+// redirects `Consume First` / `Prefer New`. Picking has different rules: a
+// `Stock Only` predecessor is reserved for service and must NOT be picked for
+// production, so its effective successor is used instead; a `No Stock`
+// predecessor is obsolete and is skipped entirely. The SQL in
+// `get_picking_schedule` mirrors this exactly.
+//
+// Dates are ISO "YYYY-MM-DD" strings; lexicographic comparison is exact for that
+// format (same convention as the shared redirect map).
+
+export type PickSupersession = {
+ supersessionMode: string;
+ successorItemId: string | null;
+ successorEffectivityDate: string | null;
+ conversionFactor: number | string | null;
+};
+
+export type PickTarget =
+ | { kind: "pick"; itemId: string; factor: number }
+ | { kind: "skip" };
+
+/**
+ * The successor item id when it is effective as of `asOfDate`, else null.
+ * A null effectivity date means "effective immediately".
+ */
+export function effectiveSuccessorId(
+ ss: PickSupersession,
+ asOfDate: string
+): string | null {
+ if (!ss.successorItemId) return null;
+ if (ss.successorEffectivityDate && ss.successorEffectivityDate > asOfDate) {
+ return null;
+ }
+ return ss.successorItemId;
+}
+
+function toFactor(value: number | string | null): number {
+ const n = Number(value ?? 1);
+ return Number.isFinite(n) && n > 0 ? n : 1;
+}
+
+/**
+ * Resolve the item a pick should target for a job material.
+ *
+ * - No supersession → pick the material's own item.
+ * - `No Stock` → skip (obsolete, no successor).
+ * - `Stock Only` → pick the effective successor (never the spares-only
+ * predecessor); skip when there is no effective successor.
+ * - `Prefer New` → pick the effective successor; fall back to the predecessor
+ * until the successor is effective.
+ * - `Consume First` → pick the predecessor; redirect to the successor ONLY when
+ * the predecessor has no warehouse stock and an effective successor with stock
+ * exists (never leaves predecessor stock unused, and satisfies
+ * "predecessor out of stock → pick successor").
+ *
+ * When redirecting to a successor, `factor` is the conversion factor
+ * (1 old = N new); otherwise 1.
+ */
+export function resolvePickTarget(args: {
+ itemId: string;
+ supersession: PickSupersession | undefined;
+ /** predecessor has a resolvable warehouse source (non-lineside on-hand). */
+ predecessorInStock: boolean;
+ /** successor has a resolvable warehouse source (non-lineside on-hand). */
+ successorInStock: boolean;
+ asOfDate: string;
+}): PickTarget {
+ const { itemId, supersession: ss } = args;
+ if (!ss) return { kind: "pick", itemId, factor: 1 };
+
+ const successor = effectiveSuccessorId(ss, args.asOfDate);
+ const factor = toFactor(ss.conversionFactor);
+
+ switch (ss.supersessionMode) {
+ case "No Stock":
+ return { kind: "skip" };
+ case "Stock Only":
+ return successor
+ ? { kind: "pick", itemId: successor, factor }
+ : { kind: "skip" };
+ case "Prefer New":
+ return successor
+ ? { kind: "pick", itemId: successor, factor }
+ : { kind: "pick", itemId, factor: 1 };
+ case "Consume First":
+ if (successor && !args.predecessorInStock && args.successorInStock) {
+ return { kind: "pick", itemId: successor, factor };
+ }
+ return { kind: "pick", itemId, factor: 1 };
+ default:
+ return { kind: "pick", itemId, factor: 1 };
+ }
+}
diff --git a/apps/erp/app/modules/inventory/ui/PickingLists/PickingListLines.tsx b/apps/erp/app/modules/inventory/ui/PickingLists/PickingListLines.tsx
index 3870c0010d..764972cca2 100644
--- a/apps/erp/app/modules/inventory/ui/PickingLists/PickingListLines.tsx
+++ b/apps/erp/app/modules/inventory/ui/PickingLists/PickingListLines.tsx
@@ -263,6 +263,23 @@ function PickingListLineItem({
const item = items.find((i) => i.id === line.itemId);
const itemName = item?.name ?? line.item?.name ?? "";
+ // A pick is substituted when its item differs from the source job material's
+ // item (an item-supersession redirect at generation time). Show the original.
+ const sourceMaterial = (
+ line as {
+ jobMaterial?: {
+ itemId?: string | null;
+ item?: { readableId?: string | null } | null;
+ } | null;
+ }
+ ).jobMaterial;
+ const substitutedFrom =
+ sourceMaterial?.itemId && sourceMaterial.itemId !== line.itemId
+ ? (items.find((i) => i.id === sourceMaterial.itemId)
+ ?.readableIdWithRevision ??
+ sourceMaterial.item?.readableId ??
+ sourceMaterial.itemId)
+ : null;
const quantityToPick = Number(line.quantityToPick ?? 0);
const quantityPicked = Number(line.quantityPicked ?? 0);
const quantityReturned = Number(
@@ -333,6 +350,11 @@ function PickingListLineItem({
<p className="truncate font-mono text-sm text-muted-foreground sm:text-xs">
{item?.readableIdWithRevision ?? line.item?.readableId}
</p>
+ {substitutedFrom && (
+ <p className="truncate text-sm text-blue-700 dark:text-blue-300 sm:text-xs">
+ ↩ <Trans>substituted from</Trans> {substitutedFrom}
+ </p>
+ )}
{isTracked && !isPicked && (
<RecommendedLots resolve={recommendations} lineId={line.id} />
)}
diff --git a/apps/erp/app/routes/api+/mcp+/lib/tool-metadata.json b/apps/erp/app/routes/api+/mcp+/lib/tool-metadata.json
index 902542ca36..aaab3580a8 100644
--- a/apps/erp/app/routes/api+/mcp+/lib/tool-metadata.json
+++ b/apps/erp/app/routes/api+/mcp+/lib/tool-metadata.json
@@ -1,5 +1,5 @@
{
- "generated": "2026-08-04T16:26:26.021Z",
+ "generated": "2026-08-04T16:53:00.934Z",
"totalTools": 1413,
"modules": 15,
"tools": [
diff --git a/packages/database/supabase/migrations/20260730143512_picking-supersession.sql b/packages/database/supabase/migrations/20260730143512_picking-supersession.sql
new file mode 100644
index 0000000000..d3f3356877
--- /dev/null
+++ b/packages/database/supabase/migrations/20260730143512_picking-supersession.sql
@@ -0,0 +1,280 @@
+-- ============================================================================
+-- Picking honors item supersession (#1210).
+--
+-- Two functions recreated with IDENTICAL signatures and RETURNS TABLE (so the
+-- generated types are unchanged):
+--
+-- 1. get_picking_schedule — a superseded job material is resolved to its
+-- EFFECTIVE pick item before the staged-lineside check, and materials with
+-- no valid pick target are dropped from the schedule:
+-- Consume First / Prefer-New-not-yet-effective / no supersession -> predecessor
+-- Prefer New (effective successor) -> successor
+-- Stock Only (effective successor) -> successor
+-- Stock Only (no effective successor) / No Stock -> excluded
+-- This stops spares-only / obsolete predecessors from being surfaced as
+-- production picks, while operations whose demand redirects to a live
+-- successor still appear. Discontinuation date does NOT suppress a pick:
+-- picking fulfills existing job demand (unlike planning, which suppresses
+-- new orders). Successor on-hand is compared in successor units via the
+-- conversion factor. Successor effectivity is evaluated against the UTC
+-- calendar date ((now() AT TIME ZONE 'UTC')::date); generatePickingList in
+-- the app uses today("UTC") to match, so both layers resolve the same
+-- effective successor regardless of the DB session or server timezone.
+--
+-- 2. get_picking_list_availability — warehouse availability is the line's OWN
+-- pick item's non-lineside on-hand. Because generation already redirects a
+-- substituted line's "itemId" to the effective successor, this reflects
+-- exactly what the line consumes. Successor on-hand is NOT folded into a line
+-- still targeting the predecessor: with no line-splitting that line consumes
+-- the predecessor, so folding it in would mask a real predecessor shortage
+-- and could double-count a successor that also has its own line.
+--
+-- Redirect gating is picking-specific and intentionally differs from the MRP /
+-- job-creation map in functions/lib/supersession-pick.ts (which redirects only
+-- Consume First / Prefer New): for PICKING, Stock Only must not be picked for
+-- production, so its effective successor is used instead.
+-- ============================================================================
+
+CREATE OR REPLACE FUNCTION get_picking_schedule(
+ p_location_id TEXT,
+ p_company_id TEXT,
+ p_search TEXT DEFAULT NULL
+)
+RETURNS TABLE (
+ "jobOperationId" TEXT,
+ "jobId" TEXT,
+ "jobMakeMethodId" TEXT,
+ "jobReadableId" TEXT,
+ "itemId" TEXT,
+ "itemReadableId" TEXT,
+ "itemDescription" TEXT,
+ "operationOrder" DOUBLE PRECISION,
+ "operationDescription" TEXT,
+ "processName" TEXT,
+ "workCenterId" TEXT,
+ "workCenterName" TEXT,
+ "operationStatus" "jobOperationStatus",
+ "deadlineType" "deadlineType",
+ "dueDate" DATE,
+ "customerId" TEXT,
+ "customerName" TEXT,
+ "salesOrderId" TEXT,
+ "salesOrderLineId" TEXT,
+ "salesOrderReadableId" TEXT,
+ "thumbnailPath" TEXT,
+ "targetQuantity" NUMERIC,
+ "operationQuantity" NUMERIC,
+ "quantityComplete" NUMERIC,
+ "quantityReworked" NUMERIC,
+ "quantityScrapped" NUMERIC,
+ "setupTime" NUMERIC,
+ "setupUnit" factor,
+ "laborTime" NUMERIC,
+ "laborUnit" factor,
+ "machineTime" NUMERIC,
+ "machineUnit" factor,
+ "tags" TEXT[],
+ "partsToPickCount" BIGINT,
+ "totalQuantityToPick" NUMERIC
+)
+LANGUAGE sql
+STABLE
+SECURITY INVOKER
+AS $$
+ WITH
+ -- Outstanding picks aggregated per effective operation. A material needs
+ -- picking unless the operation's OWN work-center lineside bin already stocks
+ -- enough on-hand to cover it. We test the ACTUAL on-hand at that bin rather
+ -- than whether the jobMaterial's recorded shelf points there: a part can be
+ -- line-stocked at this work center while the jobMaterial still points at the
+ -- warehouse (or another line) — that is already staged, not an outstanding
+ -- pick.
+ picks AS (
+ SELECT
+ jo2."id" AS "jobOperationId",
+ COUNT(*) AS "partsToPickCount",
+ SUM(jm."quantityToIssue") AS "totalQuantityToPick"
+ FROM "jobMaterial" jm
+ -- Materials with no operation assignment are attributed to the first live
+ -- operation of their make method (lowest "order", id tie-break).
+ LEFT JOIN LATERAL (
+ SELECT fo."id"
+ FROM "jobOperation" fo
+ WHERE jm."jobOperationId" IS NULL
+ AND fo."jobMakeMethodId" = jm."jobMakeMethodId"
+ AND fo."companyId" = p_company_id
+ AND fo."status" NOT IN ('Done', 'Canceled')
+ ORDER BY fo."order" ASC, fo."id" ASC
+ LIMIT 1
+ ) first_op ON true
+ JOIN "jobOperation" jo2
+ ON jo2."id" = COALESCE(jm."jobOperationId", first_op."id")
+ -- Supersession config for the demanded material (global, one row per item).
+ LEFT JOIN "itemSupersession" ss
+ ON ss."itemId" = jm."itemId"
+ AND ss."companyId" = p_company_id
+ -- Resolve the EFFECTIVE pick item + unit factor. A NULL "pickItemId" means
+ -- there is nothing valid to pick for production (Stock Only without an
+ -- effective successor, or No Stock) — those rows are dropped below.
+ LEFT JOIN LATERAL (
+ SELECT
+ CASE
+ WHEN ss."itemId" IS NULL THEN jm."itemId"
+ WHEN ss."supersessionMode" = 'Consume First' THEN jm."itemId"
+ WHEN ss."supersessionMode" = 'Prefer New' THEN
+ CASE
+ WHEN ss."successorItemId" IS NOT NULL
+ AND (ss."successorEffectivityDate" IS NULL
+ OR ss."successorEffectivityDate" <= (now() AT TIME ZONE 'UTC')::date)
+ THEN ss."successorItemId"
+ ELSE jm."itemId"
+ END
+ WHEN ss."supersessionMode" = 'Stock Only' THEN
+ CASE
+ WHEN ss."successorItemId" IS NOT NULL
+ AND (ss."successorEffectivityDate" IS NULL
+ OR ss."successorEffectivityDate" <= (now() AT TIME ZONE 'UTC')::date)
+ THEN ss."successorItemId"
+ ELSE NULL
+ END
+ WHEN ss."supersessionMode" = 'No Stock' THEN NULL
+ ELSE jm."itemId"
+ END AS "pickItemId",
+ CASE
+ WHEN ss."supersessionMode" IN ('Prefer New', 'Stock Only')
+ AND ss."successorItemId" IS NOT NULL
+ AND (ss."successorEffectivityDate" IS NULL
+ OR ss."successorEffectivityDate" <= (now() AT TIME ZONE 'UTC')::date)
+ THEN COALESCE(ss."conversionFactor", 1)
+ ELSE 1
+ END AS "pickFactor"
+ ) pit ON true
+ -- The operation's work-center lineside bin (managed default first, else
+ -- oldest), mirroring get_or_create_work_center_lineside's selection.
+ LEFT JOIN LATERAL (
+ SELECT su."id"
+ FROM "storageUnit" su
+ WHERE su."workCenterId" = jo2."workCenterId"
+ AND su."companyId" = p_company_id
+ ORDER BY su."isWorkCenterDefault" DESC, su."createdAt" ASC
+ LIMIT 1
+ ) wcl ON true
+ -- On-hand of the EFFECTIVE pick item already staged at that lineside bin.
+ LEFT JOIN LATERAL (
+ SELECT COALESCE(SUM(il."quantity"), 0) AS qty
+ FROM "itemLedger" il
+ WHERE il."itemId" = pit."pickItemId"
+ AND il."companyId" = p_company_id
+ AND il."storageUnitId" = wcl."id"
+ ) staged ON true
+ WHERE jm."companyId" = p_company_id
+ AND jm."quantityToIssue" > 0
+ -- Drop materials with no valid production pick target (spares-only /
+ -- obsolete predecessors without an effective successor).
+ AND pit."pickItemId" IS NOT NULL
+ -- Needs picking unless the lineside bin already covers the issue qty
+ -- (compared in the pick item's units via the conversion factor).
+ AND (wcl."id" IS NULL OR staged.qty < jm."quantityToIssue" * pit."pickFactor")
+ -- Exclude operations already on a non-cancelled picking list (no dupes).
+ AND NOT EXISTS (
+ SELECT 1 FROM "pickingListLine" pll
+ JOIN "pickingList" pl ON pl."id" = pll."pickingListId"
+ WHERE pll."jobOperationId" = jo2."id"
+ AND pl."status" <> 'Cancelled'
+ )
+ GROUP BY jo2."id"
+ )
+ SELECT
+ jo."id" AS "jobOperationId",
+ j."id" AS "jobId",
+ jo."jobMakeMethodId",
+ j."jobId" AS "jobReadableId",
+ i."id" AS "itemId",
+ i."readableId" AS "itemReadableId",
+ i."name" AS "itemDescription",
+ jo."order" AS "operationOrder",
+ jo."description" AS "operationDescription",
+ p."name" AS "processName",
+ jo."workCenterId",
+ wc."name" AS "workCenterName",
+ CASE WHEN j."status" = 'Paused' THEN 'Paused'::"jobOperationStatus" ELSE jo."status" END AS "operationStatus",
+ j."deadlineType",
+ jo."dueDate",
+ j."customerId",
+ c."name" AS "customerName",
+ j."salesOrderId",
+ j."salesOrderLineId",
+ so."salesOrderId" AS "salesOrderReadableId",
+ COALESCE(mu."thumbnailPath", i."thumbnailPath") AS "thumbnailPath",
+ jo."targetQuantity"::NUMERIC,
+ jo."operationQuantity",
+ jo."quantityComplete",
+ jo."quantityReworked",
+ jo."quantityScrapped",
+ jo."setupTime",
+ jo."setupUnit",
+ jo."laborTime",
+ jo."laborUnit",
+ jo."machineTime",
+ jo."machineUnit",
+ jo."tags",
+ pk."partsToPickCount",
+ pk."totalQuantityToPick"
+ FROM picks pk
+ JOIN "jobOperation" jo ON jo."id" = pk."jobOperationId"
+ JOIN "job" j ON jo."jobId" = j."id"
+ LEFT JOIN "jobMakeMethod" jmm ON jo."jobMakeMethodId" = jmm."id"
+ LEFT JOIN "item" i ON jmm."itemId" = i."id"
+ LEFT JOIN "process" p ON jo."processId" = p."id"
+ LEFT JOIN "workCenter" wc ON jo."workCenterId" = wc."id"
+ LEFT JOIN "customer" c ON j."customerId" = c."id"
+ LEFT JOIN "salesOrder" so ON j."salesOrderId" = so."id"
+ LEFT JOIN "modelUpload" mu ON i."modelUploadId" = mu."id"
+ WHERE j."companyId" = p_company_id
+ AND j."locationId" = p_location_id
+ AND j."status" IN ('Ready', 'In Progress', 'Paused')
+ AND jo."status" NOT IN ('Done', 'Canceled')
+ AND (
+ p_search IS NULL OR p_search = ''
+ OR j."jobId" ILIKE '%' || p_search || '%'
+ OR i."readableId" ILIKE '%' || p_search || '%'
+ OR jo."description" ILIKE '%' || p_search || '%'
+ )
+ ORDER BY jo."dueDate" NULLS LAST, j."jobId";
+$$;
+
+
+CREATE OR REPLACE FUNCTION get_picking_list_availability(p_picking_list_id TEXT)
+RETURNS TABLE (
+ "pickingListLineId" TEXT,
+ "availableQuantity" NUMERIC
+)
+LANGUAGE sql
+STABLE
+SECURITY INVOKER
+AS $$
+ SELECT
+ pll."id" AS "pickingListLineId",
+ -- Warehouse (non-lineside) on-hand of the line's OWN pick item — exactly what
+ -- this line consumes. A supersession redirect is already resolved at
+ -- generation time (a substituted line's "itemId" is the effective successor),
+ -- so availability reflects the real pick item without any fold-in.
+ --
+ -- We deliberately do NOT add a successor's on-hand to a line still targeting
+ -- the predecessor: with no line-splitting, such a line consumes the
+ -- PREDECESSOR, so folding in successor stock would (a) mask a genuine
+ -- predecessor shortage (suppressing the "No Stock" warning while the line
+ -- cannot actually be covered) and (b) double-count the successor's stock when
+ -- the same list also carries a separate line for that successor item.
+ COALESCE((
+ SELECT SUM(il."quantity")
+ FROM "itemLedger" il
+ WHERE il."itemId" = pll."itemId"
+ AND il."companyId" = pl."companyId"
+ AND il."locationId" = pl."locationId"
+ AND get_effective_work_center_id(il."storageUnitId") IS NULL
+ ), 0) AS "availableQuantity"
+ FROM "pickingListLine" pll
+ JOIN "pickingList" pl ON pl."id" = pll."pickingListId"
+ WHERE pll."pickingListId" = p_picking_list_id;
+$$;