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(production): correct supersession swaps across all get-method flows (#1481)

Naveen Kashyap8c9072d87280
diff --git a/.ai/lessons.md b/.ai/lessons.md
index 0988117ccf..06ba610b5e 100644
--- a/.ai/lessons.md
+++ b/.ai/lessons.md
@@ -1161,3 +1161,23 @@ canvas hosting Radix popovers/selects.
**Rule:** Adding a browser-safe var is THREE edits, not one: the `getEnv` export, `getBrowserEnv()` + the `Window.env` interface, AND the consuming app's root-loader `env` object (destructure + literal) for every app that needs it client-side. The loader's hand-curated `env` is the real source of `window.env` on the happy path — a key present in `getBrowserEnv()` but absent there is `undefined` in the browser. When an env-driven feature is dark despite the server value being set, diff `getBrowserEnv()`'s keys against the loader's `env` object before touching anything else.
**Applies to:** `apps/erp/app/root.tsx` (and `apps/mes/app/root.tsx`) loader `env` objects, `packages/env/src/index.ts` `getBrowserEnv()`, any `window.env`-gated integration/feature flag.
+
+## Kysely builds ONE column list per multi-row insert — a conditionally-set key writes NULL into its siblings
+
+**Context:** `get-method`'s `quoteLineToJob` builds every `jobMaterial` row into one array, then inserts them with a single `trx.insertInto("jobMaterial").values(rows)`. Only rows whose item had an effective supersession successor carried a `unitCost` key; the rest omitted it, on the assumption that omitting a key lets the column default apply.
+
+**Problem:** Kysely derives the INSERT's column list from the union of keys across ALL rows, not per row. The moment one swapped row carries `unitCost`, the column joins the statement and every row that omitted the key is written `NULL`. `jobMaterial.unitCost` is `NOT NULL DEFAULT 0`, so the whole insert failed with a 23502 and job creation died — and because it is one statement in one transaction, a single swapped line took down the entire job. The column default is only reached when NO row in the batch has the key, which is why it worked until the first quote-to-job with a superseded line. It was invisible to typecheck, to 157 unit tests, and to three review agents; it surfaced the first time a human clicked the flow in a browser.
+
+**Rule:** In a multi-row insert, set every column on EVERY row or on none. Never conditionally spread a key (`...(cond ? {col: v} : {})`) into rows of a batch — that is the shape that writes NULL into the others. If a column is `NOT NULL DEFAULT x` and you want the default, either omit it from all rows or write `x` explicitly. When in doubt write the value explicitly; a default duplicated in code is cheaper than a constraint violation that fails the whole transaction.
+
+**Applies to:** any Kysely `.values([...])` over more than one row, especially `jobMaterial` / `methodMaterial` / any table with `NOT NULL DEFAULT` columns.
+
+## A cast to an OPTIONAL property silently yields `undefined` on a type that lacks it
+
+**Context:** `JobMaterialsTable` renders an "↩ substituted from X" indicator for supersession-swapped job materials, reading the field as `(row.original as { substitutedFromItemId?: string | null }).substitutedFromItemId`. The row type comes from the `get_job_quantity_on_hand` RPC, whose `RETURNS TABLE` never included that column.
+
+**Problem:** Asserting an OPTIONAL property onto a type that does not have it is legal TypeScript and raises nothing — the expression just evaluates to `undefined` on every row, so `{substitutedFrom && ...}` never rendered. The feature wrote correct provenance data to the database for its entire life and displayed it zero times. Had the property been declared non-optional, or read without the cast, it would have been a compile error the day it was written.
+
+**Rule:** Treat `as { someField?: T }` on a row/DTO type as a smell, not a convenience — it is indistinguishable from a field that does not exist. When a UI needs a column its loader does not return, widen the RPC/view and regenerate types so the compiler enforces the contract. More generally: a field written to the DB but rendered nowhere has no feedback loop — `jobMaterial.itemScrapPercentage` was wrong in three code paths for the same reason.
+
+**Applies to:** `apps/erp/app/**` table cells reading loader rows; any `as { x?: T }` over a generated DB/RPC type.
diff --git a/.claude/rules/supersession-system.md b/.claude/rules/supersession-system.md
new file mode 100644
index 0000000000..88eba5bb5e
--- /dev/null
+++ b/.claude/rules/supersession-system.md
@@ -0,0 +1,116 @@
+paths:
+ - "packages/database/supabase/functions/lib/supersession-pick.ts"
+ - "packages/database/supabase/functions/get-method/**"
+ - "packages/database/supabase/functions/mrp/**"
+ - "apps/erp/app/modules/inventory/supersession-pick.ts"
+ - "apps/erp/app/modules/items/ui/Item/ItemSupersessionForm.tsx"
+
+# Item Supersession
+
+"This part is being phased out, use its successor instead." One row per item in
+`itemSupersession` (PK is `("itemId")` alone — not the usual composite), holding
+`supersessionMode`, `successorItemId`, `successorEffectivityDate`,
+`discontinuationDate` and `conversionFactor` (1 old = N new).
+
+Authored at **Part → Planning → Supersession** (`ItemSupersessionForm`, rendered
+by `x+/part+/$itemId.planning.tsx`).
+
+## Three consumers, three different questions
+
+Do not assume one rule. Each answers something different, deliberately.
+
+| Consumer | Source | Question |
+|---|---|---|
+| **MRP** (`mrp/index.ts`) | live, every run | what should we BUY? |
+| **Job creation** (`get-method`) | live at creation, then **frozen** | what does this job consume? |
+| **Picking** (`inventory/supersession-pick.ts`) | live, at pick time | what do we pull off the shelf? |
+
+A `jobMaterial` row is a **snapshot**. Editing a supersession afterwards never
+rewrites existing rows — but picking re-evaluates live, so the same job can be
+picked differently tomorrow. That split is intentional; don't "fix" it.
+
+## Mode gating — only two modes redirect
+
+`REDIRECTING_MODES = { "Consume First", "Prefer New" }`
+(`lib/supersession-pick.ts`). `Stock Only` keeps its successor as a
+reserve-governed reference; `No Stock` has no successor.
+
+**This is the single most common way to set up a test that proves nothing** —
+seed `Stock Only`, watch nothing swap, conclude the feature works.
+
+Picking uses a *different* rule set on purpose
+(`apps/erp/app/modules/inventory/supersession-pick.ts`, mirrored by
+`get_picking_schedule`):
+
+- `No Stock` → skip
+- `Stock Only` → pick the successor (never the spares-only predecessor)
+- `Prefer New` → successor, falling back to the predecessor until effective
+- `Consume First` → predecessor **until it has no warehouse stock**, then successor
+
+## `buildSupersessionRedirectMap` — the shared builder
+
+`lib/supersession-pick.ts`, used by MRP and `get-method` so both resolve a
+supersession by the same rules. It does NOT make their answers identical: each
+caller passes its own `asOfDate` (below), so a date-effective supersession can
+apply to one and not the other. Collapses `A→B→C` to `A→C` with the product of
+the factors.
+
+- Effectivity: `!date || date <= asOfDate`, lexicographic on `YYYY-MM-DD`
+ (all three columns are `DATE`, so string order is chronological).
+- `asOfDate` differs by caller: MRP uses today in the **company timezone**;
+ `get-method` uses the job's build date (`jobBuildDate`).
+- **Cycles are dropped, not collapsed.** A two-row cycle (`A→B` plus `B→A`) is
+ writable from the UI — only *self*-reference is blocked, by both the DB CHECK
+ and the zod refine. Collapsing one produced `A → A` with the cycle's factor
+ product, so an item superseded itself and its quantities were multiplied by
+ garbage. The walk builds into a SECOND map; mutating in place made the result
+ depend on iteration order. Pinned by `lib/supersession-pick.test.ts`.
+
+## get-method: three flows, one invariant
+
+`itemToJob`, `itemToJobMakeMethod`, `quoteLineToJob` each build `jobMaterial`
+rows independently. **Resolve the swap BEFORE any field derives from the item.**
+
+Building the row first and patching it afterwards is how
+`itemScrapPercentage` was left on the predecessor for years: the patch list was
+hand-written and the field was simply absent from it. All three now resolve
+`itemId` at the top of the row builder, so every derived field — scrap rate,
+bin, cost, tracking flags — follows automatically, including fields added later.
+
+`swapMadeSubAssembly` is the exception: a made sub-assembly must be inserted
+before it can be re-exploded, so it genuinely patches. It restates item-derived
+fields by spreading `itemDerivedJobMaterialFields()` rather than listing them.
+
+Made lines cascade `target + scrap` to their children, so a wrong scrap rate
+there under-explodes the entire sub-tree — every row below looks individually
+correct on a wrong base.
+
+`loadSupersessionRedirect` is loaded **once per request**, before the
+transaction, in all three flows. It pages with `fetchAll` + `.order("itemId")`;
+a bare select stops at PostgREST's 1000-row cap and would silently redirect a
+different subset than MRP.
+
+## Columns and what is visible
+
+`jobMaterial.substitutedFromItemId` / `substitutionFactor` record provenance.
+`methodMaterial` has **no** equivalent — so `jobToItem` (Save Method) writes
+swapped items into the master BOM untraceably.
+
+`jobMaterial.itemScrapPercentage` is `NOT NULL`, and `recalculate` only
+re-derives it when the stored value is NULL — which a NOT NULL column never is.
+**A wrong scrap rate is permanent.** It is surfaced by
+`get_job_quantity_on_hand` but rendered nowhere; the substitution indicator in
+`JobMaterialsTable` is the only supersession UI on a job.
+
+## Known gaps
+
+- `quoteLineToJob` never swaps **made** sub-assemblies — documented as "a later
+ layer". Fail-safe (you get the quoted structure), but it disagrees with
+ MRP, which has already redirected that demand.
+- A Make→Buy successor leaves the line on the predecessor, and that fallthrough
+ is indistinguishable from "successor's make method isn't Active" or "item read
+ failed".
+- `jobBuildDate` falls back to **UTC today** when a job has neither start nor due
+ date — which is the default creation path (`No Deadline` renders no due-date
+ field). MRP uses the company timezone; this is where the shared-map guarantee
+ breaks. Baselined in `packages/checks/src/conformance/baseline.json`.
diff --git a/AGENTS.md b/AGENTS.md
index 4b4acaf34c..f0150e905e 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -85,6 +85,7 @@ IMPORTANT: Before any research or coding, match the task to this table. A single
| Issues (NCR, CAPA, ECO, RMA) | `.claude/rules/issue-module.md` |
| Traceability / lot tracking | `.claude/rules/traceability-model.md` |
| Revision system | `.claude/rules/revision-system.md` |
+| Item supersession (phase-out / successor swaps) | `.claude/rules/supersession-system.md` |
| Kanban | `.claude/rules/kanban-system.md` |
| Workflows (customer automation rules) | `.claude/rules/workflow-event-catalog.md` + `.claude/rules/workflow-matcher.md` + `.claude/rules/workflow-engine.md` + `packages/workflows/AGENTS.md` |
| Workflow run history + retention | `.claude/rules/workflow-run-history.md` |
diff --git a/apps/erp/app/modules/production/ui/Jobs/JobMaterialsTable.tsx b/apps/erp/app/modules/production/ui/Jobs/JobMaterialsTable.tsx
index b532c284d3..a8bbd945b1 100644
--- a/apps/erp/app/modules/production/ui/Jobs/JobMaterialsTable.tsx
+++ b/apps/erp/app/modules/production/ui/Jobs/JobMaterialsTable.tsx
@@ -135,9 +135,7 @@ const JobMaterialsTable = memo(
accessorKey: "jobMaterialItemId",
header: t`Item`,
cell: ({ row }) => {
- const substitutedFromId = (
- row.original as { substitutedFromItemId?: string | null }
- ).substitutedFromItemId;
+ const substitutedFromId = row.original.substitutedFromItemId;
const substitutedFrom = substitutedFromId
? (items.find((i) => i.id === substitutedFromId)
?.readableIdWithRevision ?? substitutedFromId)
diff --git a/packages/database/src/types.ts b/packages/database/src/types.ts
index 6b382b895b..1dccda60d7 100644
--- a/packages/database/src/types.ts
+++ b/packages/database/src/types.ts
@@ -76846,6 +76846,7 @@ export type Database = {
estimatedQuantity: number
id: string
itemReadableId: string
+ itemScrapPercentage: number
itemTrackingType: Database["public"]["Enums"]["itemTrackingType"]
jobMakeMethodId: string
jobMaterialItemId: string
@@ -76863,6 +76864,7 @@ export type Database = {
quantityPerParent: number
storageUnitId: string
storageUnitName: string
+ substitutedFromItemId: string
thumbnailPath: string
type: Database["public"]["Enums"]["itemType"]
unitOfMeasureCode: string
diff --git a/packages/database/supabase/functions/get-method/index.ts b/packages/database/supabase/functions/get-method/index.ts
index a3948dfbc9..42f4f11726 100644
--- a/packages/database/supabase/functions/get-method/index.ts
+++ b/packages/database/supabase/functions/get-method/index.ts
@@ -29,7 +29,10 @@ import {
import { KyselyDatabase } from "../lib/postgres/index.ts";
import { importTypeScript } from "../lib/sandbox.ee.ts";
import { getStorageUnitId } from "../lib/storage-units.ts";
-import { buildSupersessionRedirectMap } from "../lib/supersession-pick.ts";
+import {
+ buildSupersessionRedirectMap,
+ type SupersessionRow,
+} from "../lib/supersession-pick.ts";
import { toTiptapDoc } from "../shared/tiptap.ts";
import {
getNextRevisionSequence,
@@ -701,12 +704,34 @@ serve(async (req: Request) => {
collect(root);
if (nodes.length === 0) return;
+ // A Buy/Pick line is swapped to its successor below, so the successor's
+ // scrap percentage and default bin are needed even though no tree node
+ // names it. Derived from THIS tree's nodes, not from the whole company's
+ // redirect map: that map is every itemSupersession row in the tenant, and
+ // feeding all of its targets here made the three reads scale with the
+ // company's supersession count instead of the BOM — the same invoke-
+ // timeout class this prefetch exists to remove (and, unchunked, a
+ // bind-parameter overflow past ~65k ids). Successor trees loaded by
+ // swapMadeSubAssembly re-enter through here, so each covers its own
+ // redirect targets by induction.
+ //
+ // Deliberately NOT exhaustive: a configuration rule can replace a line's
+ // itemId with an item no tree node names, and that item may be superseded
+ // in turn. Those land on the per-material ensureItemsPrefetched below,
+ // which is the safety net for every post-configuration id — this is a
+ // batching hint, not the correctness boundary.
+ const redirectTargets: string[] = [];
+ for (const n of nodes) {
+ const to = supersessionRedirect.get(n.data.itemId)?.to;
+ if (to) redirectTargets.push(to);
+ }
+
// Kysely and PostgREST are separate transports — safe to overlap.
await Promise.all([
- ensureItemsPrefetched(
- reader,
- nodes.map((n) => n.data.itemId)
- ),
+ ensureItemsPrefetched(reader, [
+ ...nodes.map((n) => n.data.itemId),
+ ...redirectTargets,
+ ]),
ensureMakeMethodsPrefetched(
nodes.map((n) => n.data.materialMakeMethodId)
),
@@ -714,12 +739,6 @@ serve(async (req: Request) => {
}
await ensurePrefetched(db, methodTree);
- // Buy/Pick lines can be swapped to their successor item below, so the
- // successors' lookups are needed even though no tree node names them.
- await ensureItemsPrefetched(
- db,
- [...supersessionRedirect.values()].map((r) => r.to)
- );
const getLaborAndOverheadRates = getRatesFromWorkCenters(
workCenters?.data
@@ -1291,6 +1310,13 @@ serve(async (req: Request) => {
// just below refreshes the successor's item fields automatically.
let substitutedFromItemId: string | null = null;
let substitutionFactor: number | null = null;
+ // Captured before the swap so the revert below can undo it whole.
+ const quantityBeforeSupersession = quantity;
+ // Post-configuration, pre-supersession. A configuration rule may
+ // already have moved this line off the BOM's item, and that choice
+ // has to survive a failed successor lookup — see the fallback chain
+ // below.
+ const configuredItemId = itemId;
if (methodType !== "Make to Order") {
const redirect = supersessionRedirect.get(itemId);
if (redirect) {
@@ -1301,13 +1327,28 @@ serve(async (req: Request) => {
}
}
- if (itemId !== child.data.itemId) {
+ // Fall back in order of preference: the successor, then whatever a
+ // configuration rule chose, then the BOM's own item. Reverting
+ // straight to `child.data.itemId` discarded the configuration
+ // rule's decision, which the supersession never overrode — it only
+ // redirected the item that rule had already picked.
+ //
+ // Each candidate is READ before it is accepted, so `itemId` and the
+ // fields derived from it can never disagree. `child.data.itemId`
+ // needs no read: its fields are the defaults already in scope.
+ // What this row WOULD be for if every lookup succeeds.
+ const intendedItemId = itemId;
+ for (const candidate of [
+ ...new Set([itemId, configuredItemId, child.data.itemId]),
+ ]) {
+ itemId = candidate;
+ if (candidate === child.data.itemId) break;
const item = await client
.from("item")
.select(
"readableId, readableIdWithRevision, type, name, itemTrackingType, itemCost(unitCost)"
)
- .eq("id", itemId)
+ .eq("id", candidate)
.eq("companyId", companyId)
.single();
if (item.data) {
@@ -1321,11 +1362,22 @@ serve(async (req: Request) => {
item.data.itemTrackingType === "Serial";
requiresBatchTracking =
item.data.itemTrackingType === "Batch";
- } else {
- itemId = child.data.itemId;
+ break;
}
}
+ if (itemId !== intendedItemId) {
+ // The swap could not be completed, so undo it WHOLLY. Reverting
+ // only `itemId` left the row on a different item while KEEPING
+ // the successor's factor-scaled quantity and a
+ // `substitutedFromItemId` that no longer described it — a
+ // plausible-looking but wrong quantity nothing downstream can
+ // detect or repair.
+ quantity = quantityBeforeSupersession;
+ substitutedFromItemId = null;
+ substitutionFactor = null;
+ }
+
// `itemId` here is post-configuration and post-supersession, so
// it can be an item no tree node named — a configuration rule may
// return any item id. Cover it before reading, or its scrap
@@ -1522,9 +1574,9 @@ serve(async (req: Request) => {
child,
material,
materialId,
+ locationId: job.data?.locationId ?? "",
supersessionRedirect,
newMakeMethodId,
- childTotalForCascade,
traverseMethod,
});
@@ -1693,6 +1745,18 @@ serve(async (req: Request) => {
const methodTree = methodTrees.data?.[0] as MethodTreeItem;
if (!methodTree) throw new Error("Method tree not found");
+ // Loaded ONCE per request, before the transaction — as itemToJob does.
+ // This read pages the company's whole itemSupersession table, and it used
+ // to sit inside traverseMethod, so a BOM of N nodes issued N full-table
+ // reads sequentially inside the transaction holding the pool's single
+ // connection. The map depends only on the company and the job's build
+ // date, both fixed for the request, so per-node reload bought nothing.
+ const supersessionRedirect = await loadSupersessionRedirect(
+ client,
+ companyId,
+ job.data
+ );
+
const getLaborAndOverheadRates = getRatesFromWorkCenters(
workCenters?.data
);
@@ -2009,11 +2073,41 @@ serve(async (req: Request) => {
const mapMethodMaterialToJobMaterial = async (
child: MethodTreeItem
) => {
+ // Resolve the supersession FIRST, so every field below derives
+ // from the item this row ENDS UP being for. This used to run as a
+ // second pass over the finished rows, which meant each new derived
+ // field silently inherited the predecessor's value unless someone
+ // remembered to add it to that pass's patch list — the scrap rate
+ // was read here from the OLD item and never revisited, so a swapped
+ // line costed the predecessor's scrap forever (the column is NOT
+ // NULL, and recalculate only re-derives from NULL). Swapping up
+ // front is what itemToJob already does, and it makes the whole
+ // class of bug unreachable rather than fixing one instance of it.
+ // Buy/Pick only — resolveJobMaterialSupersession returns null for
+ // Make to Order, which swapMadeSubAssembly handles during its own
+ // explosion.
+ const supersession = await resolveJobMaterialSupersession(
+ client,
+ companyId,
+ supersessionRedirect,
+ {
+ itemId: child.data.itemId,
+ methodType: child.data.methodType,
+ }
+ );
+ const itemId = supersession?.itemId ?? child.data.itemId;
+ // 1 old part = `factor` successors. The line's methodType and unit
+ // of measure are deliberately preserved; the factor translates the
+ // quantity.
+ const quantityPerParent =
+ (child.data.quantity ?? 1) * (supersession?.factor ?? 1);
+
// Get scrap percentage for this item
const itemReplenishment = await trx
.selectFrom("itemReplenishment")
.select("scrapPercentage")
- .where("itemId", "=", child.data.itemId)
+ .where("itemId", "=", itemId)
+ .where("companyId", "=", companyId)
.executeTakeFirst();
const itemScrapPercentage = Number(
itemReplenishment?.scrapPercentage ?? 0
@@ -2022,7 +2116,7 @@ serve(async (req: Request) => {
// Calculate scrap quantities for this material
// Use totalQuantityForChildren (parent's total including scrap) for child calculations
const childTargetQuantity =
- totalQuantityForChildren * (child.data.quantity ?? 1);
+ totalQuantityForChildren * quantityPerParent;
const childScrapQuantity = scrapAllowance(
childTargetQuantity,
itemScrapPercentage
@@ -2054,24 +2148,40 @@ serve(async (req: Request) => {
).methodOperationStepIds,
methodStepsToJobSteps
),
- itemId: child.data.itemId,
+ itemId,
kit: child.data.kit,
- itemType: child.data.itemType,
+ itemType: supersession?.itemType ?? child.data.itemType,
methodType: child.data.methodType,
order: child.data.order,
- description: child.data.description,
- quantity: child.data.quantity,
+ description:
+ supersession?.description ?? child.data.description,
+ quantity: quantityPerParent,
scrapQuantity: childScrapQuantity,
estimatedQuantity: childEstimatedQuantity,
- requiresBatchTracking: child.data.itemTrackingType === "Batch",
+ requiresBatchTracking:
+ supersession?.requiresBatchTracking ??
+ child.data.itemTrackingType === "Batch",
requiresSerialTracking:
+ supersession?.requiresSerialTracking ??
child.data.itemTrackingType === "Serial",
unitOfMeasureCode: child.data.unitOfMeasureCode,
- unitCost: child.data.unitCost ?? 0,
+ // Branch on WHETHER a swap happened, not just on the successor
+ // having a cost. `supersession?.unitCost ?? child.data.unitCost`
+ // valued a successor row at the RETIRED part's cost whenever the
+ // successor had no itemCost row — a plausible number for the
+ // wrong item. 0 is at least visibly missing.
+ unitCost: supersession
+ ? (supersession.unitCost ?? 0)
+ : (child.data.unitCost ?? 0),
itemScrapPercentage,
+ substitutedFromItemId:
+ supersession?.substitutedFromItemId ?? null,
+ substitutionFactor: supersession?.factor ?? null,
+ // The bin belongs to the item this row is actually for — the
+ // post-swap `itemId`. An explicit bin on the BOM line still wins.
storageUnitId: await getStorageUnitId(
trx,
- child.data.itemId,
+ itemId,
job.data?.locationId ?? "",
// @ts-ignore: storageUnitIds is a dynamic field
child.data.storageUnitIds?.[job.data.locationId] ?? undefined
@@ -2096,34 +2206,10 @@ serve(async (req: Request) => {
}
}
- // Supersession swap when pulling a method onto an existing job
- // (itemToJobMakeMethod): same shared logic + build-date gating as the
- // other paths. Made materials are left for their own sub-explosion.
- const supersessionRedirect = await loadSupersessionRedirect(
- client,
- companyId,
- job.data
- );
- for (const m of pickedOrBoughtMaterials) {
- const sup = await resolveJobMaterialSupersession(
- client,
- companyId,
- supersessionRedirect,
- { itemId: m.itemId, methodType: m.methodType }
- );
- if (!sup) continue;
- m.substitutedFromItemId = sup.substitutedFromItemId;
- m.substitutionFactor = sup.factor;
- m.itemId = sup.itemId;
- m.itemType = sup.itemType;
- m.description = sup.description;
- m.unitCost = sup.unitCost ?? m.unitCost;
- m.requiresSerialTracking = sup.requiresSerialTracking;
- m.requiresBatchTracking = sup.requiresBatchTracking;
- m.quantity = (m.quantity ?? 0) * sup.factor;
- m.estimatedQuantity = (m.estimatedQuantity ?? 0) * sup.factor;
- m.scrapQuantity = (m.scrapQuantity ?? 0) * sup.factor;
- }
+ // The supersession swap happens inside mapMethodMaterialToJobMaterial,
+ // before any field derives from the item — there is deliberately no
+ // second pass here. Made materials are left for their own
+ // sub-explosion (swapMadeSubAssembly).
if (madeMaterials.length > 0) {
const madeMaterialsWithIds = madeMaterials.map((m) => ({
@@ -2196,9 +2282,9 @@ serve(async (req: Request) => {
child,
material,
materialId,
+ locationId: job.data?.locationId ?? "",
supersessionRedirect,
newMakeMethodId,
- childTotalForCascade,
traverseMethod,
});
@@ -5088,6 +5174,18 @@ serve(async (req: Request) => {
.data?.[0] as QuoteMethodTreeItem;
if (!quoteMethodTree) throw new Error("Method tree not found");
+ // Loaded ONCE per request, before the transaction — as itemToJob does.
+ // This read pages the company's whole itemSupersession table, and it used
+ // to sit inside the per-node traverseQuoteMethod callback, so a BOM of N
+ // nodes issued N full-table reads sequentially inside the transaction
+ // holding the pool's single connection. The map depends only on the
+ // company and the job's build date, both fixed for the request.
+ const supersessionRedirect = await loadSupersessionRedirect(
+ client,
+ companyId,
+ job.data
+ );
+
const quoteMaterialIdToJobMaterialId: Record<string, string> = {};
const quoteMakeMethodIdToJobMakeMethodId: Record<string, string> = {};
// Track estimated quantities for each make method to set on operations
@@ -5185,11 +5283,34 @@ serve(async (req: Request) => {
const newMaterialId = nanoid();
quoteMaterialIdToJobMaterialId[child.id] = newMaterialId;
+ // Resolve the supersession FIRST — see the note in
+ // itemToJobMakeMethod's mapper. Deriving the scrap rate, bin and
+ // quantities from the pre-swap item and patching the row
+ // afterwards is what left swapped lines costing the
+ // predecessor's scrap; swapping up front means every field here,
+ // and any field added later, is computed for the item the row
+ // ends up being for. Buy/Pick only — made sub-assemblies are not
+ // swapped on the quote path at all (their successors' methods
+ // would have to be re-exploded from the item side).
+ const supersession = await resolveJobMaterialSupersession(
+ client,
+ companyId,
+ supersessionRedirect,
+ {
+ itemId: child.data.itemId,
+ methodType: child.data.methodType,
+ }
+ );
+ const itemId = supersession?.itemId ?? child.data.itemId;
+ const quantityPerParent =
+ (child.data.quantity ?? 1) * (supersession?.factor ?? 1);
+
// Get scrap percentage for this item
const itemReplenishment = await trx
.selectFrom("itemReplenishment")
.select("scrapPercentage")
- .where("itemId", "=", child.data.itemId)
+ .where("itemId", "=", itemId)
+ .where("companyId", "=", companyId)
.executeTakeFirst();
const itemScrapPercentage = Number(
itemReplenishment?.scrapPercentage ?? 0
@@ -5198,7 +5319,7 @@ serve(async (req: Request) => {
// Calculate scrap quantities for this child material
// Target = parent's total (including scrap) * quantity per parent
const childTargetQuantity =
- nodeTotalForChildren * (child.data.quantity ?? 1);
+ nodeTotalForChildren * quantityPerParent;
// Scrap applies to every method type (mirrors itemToJob)
const childScrapQuantity = scrapAllowance(
childTargetQuantity,
@@ -5227,31 +5348,55 @@ serve(async (req: Request) => {
jobMaterialInserts.push({
id: newMaterialId,
jobId,
- itemId: child.data.itemId,
- itemType: child.data.itemType,
+ itemId,
+ itemType: supersession?.itemType ?? child.data.itemType,
kit: child.data.kit,
methodType: child.data.methodType,
order: child.data.order,
- description: child.data.description,
+ description:
+ supersession?.description ?? child.data.description,
jobMakeMethodId:
child.data.quoteMakeMethodId === quoteMakeMethod.data.id
? jobMakeMethod.data.id
: quoteMakeMethodIdToJobMakeMethodId[
child.data.quoteMakeMethodId
],
- quantity: child.data.quantity,
+ quantity: quantityPerParent,
scrapQuantity: childScrapQuantity,
estimatedQuantity: childEstimatedQuantity,
itemScrapPercentage,
+ substitutedFromItemId:
+ supersession?.substitutedFromItemId ?? null,
+ substitutionFactor: supersession?.factor ?? null,
+ // ALWAYS set, never conditionally spread. Kysely builds ONE
+ // column list for a multi-row insert, so the moment a single
+ // swapped row carries `unitCost` the column joins the statement
+ // and every row that omitted the key is written NULL — and
+ // `jobMaterial.unitCost` is NOT NULL DEFAULT 0, so the whole
+ // insert fails. Omitting a key only reaches the default when NO
+ // row in the batch has it.
+ //
+ // Branch on whether a swap happened, matching the other two
+ // flows: a swapped row must not inherit the predecessor's cost,
+ // and an unswapped one keeps the quote line's own. This path
+ // never set the column before, so unswapped rows silently took
+ // the 0 default even though the quote tree carries a cost.
+ unitCost: supersession
+ ? (supersession.unitCost ?? 0)
+ : (child.data.unitCost ?? 0),
+ // The bin belongs to the post-swap item; an explicit bin on the
+ // quote line still wins.
storageUnitId: await getStorageUnitId(
trx,
- child.data.itemId,
+ itemId,
job.data.locationId,
child.data.storageUnitId
),
requiresBatchTracking:
+ supersession?.requiresBatchTracking ??
child.data.itemTrackingType === "Batch",
requiresSerialTracking:
+ supersession?.requiresSerialTracking ??
child.data.itemTrackingType === "Serial",
unitOfMeasureCode: child.data.unitOfMeasureCode,
companyId,
@@ -5277,35 +5422,9 @@ serve(async (req: Request) => {
}
if (parts.billOfMaterial && jobMaterialInserts.length > 0) {
- // Supersession swap at job creation (quote -> job): same shared
- // logic + build-date gating as the itemToJob path. Built here so
- // it's in scope for the post-build override below.
- const supersessionRedirect = await loadSupersessionRedirect(
- client,
- companyId,
- job.data
- );
- // Swap any Buy/Pick line whose item has an effective successor.
- for (const m of jobMaterialInserts) {
- const sup = await resolveJobMaterialSupersession(
- client,
- companyId,
- supersessionRedirect,
- { itemId: m.itemId, methodType: m.methodType }
- );
- if (!sup) continue;
- m.substitutedFromItemId = sup.substitutedFromItemId;
- m.substitutionFactor = sup.factor;
- m.itemId = sup.itemId;
- m.itemType = sup.itemType;
- m.description = sup.description;
- m.unitCost = sup.unitCost ?? m.unitCost;
- m.requiresSerialTracking = sup.requiresSerialTracking;
- m.requiresBatchTracking = sup.requiresBatchTracking;
- m.quantity = (m.quantity ?? 0) * sup.factor;
- m.estimatedQuantity = (m.estimatedQuantity ?? 0) * sup.factor;
- m.scrapQuantity = (m.scrapQuantity ?? 0) * sup.factor;
- }
+ // The supersession swap happens where each row is built, before
+ // any field derives from the item — there is deliberately no
+ // second pass here.
await trx
.insertInto("jobMaterial")
.values(jobMaterialInserts)
@@ -6408,18 +6527,94 @@ async function loadSupersessionRedirect(
companyId: string,
job: { startDate?: string | null; dueDate?: string | null } | null | undefined
): Promise<Map<string, { to: string; factor: number }>> {
- const supersessionRows = await client
- .from("itemSupersession")
- .select(
- "itemId, supersessionMode, successorItemId, successorEffectivityDate, conversionFactor"
- )
- .eq("companyId", companyId);
+ // Paged, exactly like MRP's read of the same table (mrp/index.ts): a bare
+ // select stops at PostgREST's 1000-row `max_rows` cap and silently drops the
+ // rest, so a tenant past that many supersessions would redirect an arbitrary
+ // subset — while MRP, which pages, redirects all of them. The two disagreeing
+ // about which part to consume is precisely what this shared helper exists to
+ // prevent, and the local stack does not enforce the cap, so it ships unseen.
+ // `.order("itemId")` is a precondition of that paging, not cosmetic: without a
+ // stable sort PostgREST may order rows differently per page, dropping and
+ // duplicating some.
+ const supersessionRows = await fetchAll<SupersessionRow>(() =>
+ client
+ .from("itemSupersession")
+ .select(
+ "itemId, supersessionMode, successorItemId, successorEffectivityDate, conversionFactor"
+ )
+ .eq("companyId", companyId)
+ .order("itemId")
+ );
+ // Throw, like every other read in this function. An empty map is
+ // indistinguishable from "this company supersedes nothing", so swallowing the
+ // error builds a real work order out of retired parts and reports success —
+ // and nothing downstream can tell that job apart from a correct one. Failing
+ // is recoverable: the route returns `{ error }`, the caller toasts it
+ // (JobMakeMethodTools), and the user retries with nothing written.
+ if (supersessionRows.error) {
+ throw new Error(
+ `Failed to load supersessions: ${supersessionRows.error.message}`
+ );
+ }
return buildSupersessionRedirectMap(
supersessionRows.data ?? [],
jobBuildDate(job)
);
}
+// EVERY jobMaterial field that is a function of WHICH ITEM the row is for, in
+// one place. A supersession swap has to restate all of them, and the way that
+// goes wrong is a hand-written field list that drifts: `itemScrapPercentage` was
+// simply absent from the swap's `.set({...})`, so a swapped line costed the
+// predecessor's scrap forever. Returning them as an object the caller SPREADS
+// means a field added here reaches the swap without a second edit — the list
+// cannot fall out of sync with itself.
+//
+// Quantities are deliberately NOT here: they depend on the parent's cascade and
+// the method type, which this function has no view of. It returns the scrap RATE
+// and lets the caller derive the allowance.
+async function itemDerivedJobMaterialFields(opts: {
+ client: SupabaseClient<Database>;
+ trx: Transaction<DB>;
+ companyId: string;
+ itemId: string;
+ locationId: string;
+ /** An explicit bin on the BOM line still wins over the item's default. */
+ lineStorageUnitId?: string;
+}) {
+ const { client, trx, companyId, itemId, locationId, lineStorageUnitId } =
+ opts;
+
+ const [item, replenishment, storageUnitId] = await Promise.all([
+ client
+ .from("item")
+ .select("type, name, itemTrackingType, itemCost(unitCost)")
+ .eq("id", itemId)
+ .eq("companyId", companyId)
+ .single(),
+ trx
+ .selectFrom("itemReplenishment")
+ .select("scrapPercentage")
+ .where("itemId", "=", itemId)
+ .where("companyId", "=", companyId)
+ .executeTakeFirst(),
+ getStorageUnitId(trx, itemId, locationId, lineStorageUnitId),
+ ]);
+
+ if (!item.data) return null;
+
+ return {
+ itemId,
+ itemType: item.data.type,
+ description: item.data.name,
+ unitCost: item.data.itemCost?.[0]?.unitCost ?? 0,
+ requiresSerialTracking: item.data.itemTrackingType === "Serial",
+ requiresBatchTracking: item.data.itemTrackingType === "Batch",
+ itemScrapPercentage: Number(replenishment?.scrapPercentage ?? 0),
+ storageUnitId,
+ };
+}
+
// Made-component supersession at job creation: if a made child has an effective
// successor that is ITSELF a made item, repoint the job material at the successor
// and explode the SUCCESSOR's method (date-pruned) instead of the old part's,
@@ -6439,9 +6634,10 @@ async function swapMadeSubAssembly(opts: {
}
| undefined;
materialId: string;
+ /** The job's location — the successor's default bin is resolved against it. */
+ locationId: string;
supersessionRedirect: Map<string, { to: string; factor: number }>;
newMakeMethodId: string;
- childTotalForCascade: number;
traverseMethod: (
node: MethodTreeItem,
parentJobMakeMethodId: string | null,
@@ -6455,9 +6651,9 @@ async function swapMadeSubAssembly(opts: {
child,
material,
materialId,
+ locationId,
supersessionRedirect,
newMakeMethodId,
- childTotalForCascade,
traverseMethod,
} = opts;
@@ -6470,29 +6666,44 @@ async function swapMadeSubAssembly(opts: {
.eq("itemId", madeRedirect.to)
.eq("companyId", companyId)
.maybeSingle();
- const successorItem = successorMakeMethod.data
- ? await client
- .from("item")
- .select("type, name, itemTrackingType, itemCost(unitCost)")
- .eq("id", madeRedirect.to)
- .eq("companyId", companyId)
- .single()
- : null;
- if (!successorMakeMethod.data || !successorItem?.data) return false;
+ if (!successorMakeMethod.data) return false;
+
+ // Every item-dependent field, restated for the successor in ONE step. Spread,
+ // never hand-listed: this row is being repointed at a different item, so all
+ // of them change together, and a field added to the helper arrives here
+ // automatically. `itemScrapPercentage` going missing from a hand-written list
+ // is exactly how a swapped line ended up costing the predecessor's scrap.
+ const itemFields = await itemDerivedJobMaterialFields({
+ client,
+ trx,
+ companyId,
+ itemId: madeRedirect.to,
+ locationId,
+ // @ts-ignore: storageUnitIds is a dynamic field
+ lineStorageUnitId: child.data.storageUnitIds?.[locationId] ?? undefined,
+ });
+ if (!itemFields) return false;
+
+ // Quantities are the caller's business, not the helper's — they depend on the
+ // cascade and the method type. Make to Order: estimatedQuantity is the GOOD
+ // quantity, scrap excluded, and target + scrap is what children explode
+ // against. Deriving both from the SAME scrap rate is what stops the row and
+ // its sub-tree disagreeing.
+ const targetQuantity =
+ (material?.estimatedQuantity ?? 0) * madeRedirect.factor;
+ const scrapQuantity = scrapAllowance(
+ targetQuantity,
+ itemFields.itemScrapPercentage
+ );
+ const totalWithScrap = targetQuantity + scrapQuantity;
await trx
.updateTable("jobMaterial")
.set({
- itemId: madeRedirect.to,
- itemType: successorItem.data.type,
- description: successorItem.data.name,
- unitCost: successorItem.data.itemCost?.[0]?.unitCost ?? 0,
- requiresSerialTracking: successorItem.data.itemTrackingType === "Serial",
- requiresBatchTracking: successorItem.data.itemTrackingType === "Batch",
+ ...itemFields,
quantity: (material?.quantity ?? 0) * madeRedirect.factor,
- estimatedQuantity:
- (material?.estimatedQuantity ?? 0) * madeRedirect.factor,
- scrapQuantity: (material?.scrapQuantity ?? 0) * madeRedirect.factor,
+ estimatedQuantity: targetQuantity,
+ scrapQuantity,
substitutedFromItemId: child.data.itemId,
substitutionFactor: madeRedirect.factor,
})
@@ -6502,11 +6713,11 @@ async function swapMadeSubAssembly(opts: {
const successorTree = await getMethodTree(client, successorMakeMethod.data.id);
const successorRoot = successorTree.data?.[0];
if (successorRoot) {
- await traverseMethod(
- successorRoot,
- newMakeMethodId,
- (childTotalForCascade || 1) * madeRedirect.factor
- );
+ // The SAME total the row above was written with — not the predecessor's,
+ // rescaled. `|| 1` mirrors the unswapped path's fallback exactly; the old
+ // `(childTotalForCascade || 1) * factor` yielded `factor` for a zero total
+ // where the unswapped path yields 1.
+ await traverseMethod(successorRoot, newMakeMethodId, totalWithScrap || 1);
}
return true;
}
diff --git a/packages/database/supabase/functions/lib/supersession-pick.test.ts b/packages/database/supabase/functions/lib/supersession-pick.test.ts
new file mode 100644
index 0000000000..f1497c3fc6
--- /dev/null
+++ b/packages/database/supabase/functions/lib/supersession-pick.test.ts
@@ -0,0 +1,216 @@
+import { assertEquals } from "https://deno.land/[email protected]/testing/asserts.ts";
+import {
+ buildSupersessionRedirectMap,
+ type SupersessionRow,
+} from "./supersession-pick.ts";
+
+// `buildSupersessionRedirectMap` is the single source of truth for "should this
+// component be swapped for its successor", shared by the MRP engine (planning)
+// and the get-method edge function (job creation) so the two can never disagree.
+// A divergence between them is invisible in the app — the plan and the job it
+// produces simply disagree about which part to consume — so the contract is
+// pinned here rather than by running either caller.
+//
+// Four things it owns: mode gating, effectivity-date gating, multi-hop chain
+// collapse with the factor product, and cycle handling.
+
+const ASOF = "2026-08-18";
+
+const row = (overrides: Partial<SupersessionRow> = {}): SupersessionRow => ({
+ itemId: "A",
+ supersessionMode: "Consume First",
+ successorItemId: "B",
+ successorEffectivityDate: null,
+ conversionFactor: 1,
+ ...overrides,
+});
+
+Deno.test("redirects for Consume First", () => {
+ const map = buildSupersessionRedirectMap([row()], ASOF);
+ assertEquals(map.get("A"), { to: "B", factor: 1 });
+});
+
+Deno.test("redirects for Prefer New", () => {
+ const map = buildSupersessionRedirectMap(
+ [row({ supersessionMode: "Prefer New" })],
+ ASOF
+ );
+ assertEquals(map.get("A"), { to: "B", factor: 1 });
+});
+
+// Stock Only keeps its successor as a reserve-governed reference and No Stock
+// has no successor to move demand to — neither redirects. Seeding a test with
+// one of these modes is the easiest way to "prove" a swap works when nothing
+// swapped at all.
+Deno.test("does not redirect for Stock Only or No Stock", () => {
+ for (const supersessionMode of ["Stock Only", "No Stock"]) {
+ const map = buildSupersessionRedirectMap([row({ supersessionMode })], ASOF);
+ assertEquals(map.size, 0, supersessionMode);
+ }
+});
+
+Deno.test("does not redirect without a successor", () => {
+ const map = buildSupersessionRedirectMap(
+ [row({ successorItemId: null })],
+ ASOF
+ );
+ assertEquals(map.size, 0);
+});
+
+Deno.test("carries the conversion factor", () => {
+ const map = buildSupersessionRedirectMap([row({ conversionFactor: 2.5 })], ASOF);
+ assertEquals(map.get("A"), { to: "B", factor: 2.5 });
+});
+
+// NUMERIC arrives as a string from some drivers, and a null/0 factor would
+// silently zero a job's quantities — both coerce to 1.
+Deno.test("coerces a string factor and falls back to 1", () => {
+ assertEquals(
+ buildSupersessionRedirectMap([row({ conversionFactor: "3" })], ASOF).get("A"),
+ { to: "B", factor: 3 }
+ );
+ for (const conversionFactor of [null, 0]) {
+ assertEquals(
+ buildSupersessionRedirectMap([row({ conversionFactor })], ASOF).get("A"),
+ { to: "B", factor: 1 },
+ String(conversionFactor)
+ );
+ }
+});
+
+Deno.test("a null effectivity date is effective immediately", () => {
+ const map = buildSupersessionRedirectMap(
+ [row({ successorEffectivityDate: null })],
+ ASOF
+ );
+ assertEquals(map.get("A"), { to: "B", factor: 1 });
+});
+
+// Lexicographic compare on "YYYY-MM-DD" — the boundary day itself is effective.
+Deno.test("effectivity gates on the as-of date, inclusive", () => {
+ const cases: [string, boolean][] = [
+ ["2026-08-17", true],
+ [ASOF, true],
+ ["2026-08-19", false],
+ ];
+ for (const [successorEffectivityDate, effective] of cases) {
+ const map = buildSupersessionRedirectMap(
+ [row({ successorEffectivityDate })],
+ ASOF
+ );
+ assertEquals(map.size, effective ? 1 : 0, successorEffectivityDate);
+ }
+});
+
+// A->B->C collapses to A->C so a caller never has to walk the chain itself.
+Deno.test("collapses a multi-hop chain and multiplies the factors", () => {
+ const map = buildSupersessionRedirectMap(
+ [
+ row({ itemId: "A", successorItemId: "B", conversionFactor: 2 }),
+ row({ itemId: "B", successorItemId: "C", conversionFactor: 3 }),
+ ],
+ ASOF
+ );
+ assertEquals(map.get("A"), { to: "C", factor: 6 });
+ assertEquals(map.get("B"), { to: "C", factor: 3 });
+});
+
+// A hop that is not yet effective ends the chain there rather than being
+// skipped over — demand stops at the last part actually in service.
+Deno.test("stops a chain at the first ineffective hop", () => {
+ const map = buildSupersessionRedirectMap(
+ [
+ row({ itemId: "A", successorItemId: "B", conversionFactor: 2 }),
+ row({
+ itemId: "B",
+ successorItemId: "C",
+ conversionFactor: 3,
+ successorEffectivityDate: "2026-12-01",
+ }),
+ ],
+ ASOF
+ );
+ assertEquals(map.get("A"), { to: "B", factor: 2 });
+ assertEquals(map.has("B"), false);
+});
+
+// The DB CHECK and the zod validator both only block a SELF-reference, so a
+// two-row cycle (A->B plus B->A) is fully writable from the UI. A cycle has no
+// meaningful terminal successor, so the only safe answer is to redirect
+// neither part — an item that supersedes itself would be inserted with
+// substitutedFromItemId pointing at its own id and its quantity multiplied by
+// the cycle's factor product, which no downstream step can detect or repair.
+Deno.test("drops a two-item cycle instead of redirecting to self", () => {
+ const map = buildSupersessionRedirectMap(
+ [
+ row({ itemId: "A", successorItemId: "B", conversionFactor: 2 }),
+ row({ itemId: "B", successorItemId: "A", conversionFactor: 3 }),
+ ],
+ ASOF
+ );
+ assertEquals(map.has("A"), false);
+ assertEquals(map.has("B"), false);
+});
+
+Deno.test("drops a three-item cycle", () => {
+ const map = buildSupersessionRedirectMap(
+ [
+ row({ itemId: "A", successorItemId: "B", conversionFactor: 2 }),
+ row({ itemId: "B", successorItemId: "C", conversionFactor: 2 }),
+ row({ itemId: "C", successorItemId: "A", conversionFactor: 2 }),
+ ],
+ ASOF
+ );
+ assertEquals(map.size, 0);
+});
+
+// A chain that FEEDS a cycle must not inherit the cycle's spun-up factor. The
+// tail is unresolvable, so the entry that leads into it goes too.
+Deno.test("drops a chain that terminates in a cycle", () => {
+ const map = buildSupersessionRedirectMap(
+ [
+ row({ itemId: "A", successorItemId: "B", conversionFactor: 2 }),
+ row({ itemId: "B", successorItemId: "C", conversionFactor: 3 }),
+ row({ itemId: "C", successorItemId: "B", conversionFactor: 5 }),
+ ],
+ ASOF
+ );
+ assertEquals(map.has("A"), false);
+ assertEquals(map.has("B"), false);
+ assertEquals(map.has("C"), false);
+});
+
+// The collapse walk reads the uncollapsed map and writes into a separate one, so
+// no entry can observe another's already-collapsed factor. Row order must not
+// change the answer — mutating in place is what made it order-dependent.
+Deno.test("chain collapse is independent of row order", () => {
+ const rows = [
+ row({ itemId: "A", successorItemId: "B", conversionFactor: 2 }),
+ row({ itemId: "B", successorItemId: "C", conversionFactor: 3 }),
+ row({ itemId: "C", successorItemId: "D", conversionFactor: 5 }),
+ ];
+ const forward = buildSupersessionRedirectMap(rows, ASOF);
+ const reversed = buildSupersessionRedirectMap([...rows].reverse(), ASOF);
+
+ assertEquals(forward.get("A"), { to: "D", factor: 30 });
+ assertEquals(reversed.get("A"), forward.get("A"));
+ assertEquals(reversed.get("B"), forward.get("B"));
+ assertEquals(reversed.get("C"), forward.get("C"));
+});
+
+// One row per item is guaranteed by the PK (itemSupersession_pkey is on
+// "itemId" alone), but the builder is fed whatever the caller read.
+Deno.test("last row wins for a duplicated itemId", () => {
+ const map = buildSupersessionRedirectMap(
+ [
+ row({ itemId: "A", successorItemId: "B" }),
+ row({ itemId: "A", successorItemId: "C" }),
+ ],
+ ASOF
+ );
+ assertEquals(map.get("A"), { to: "C", factor: 1 });
+});
+
+Deno.test("returns an empty map for no rows", () => {
+ assertEquals(buildSupersessionRedirectMap([], ASOF).size, 0);
+});
diff --git a/packages/database/supabase/functions/lib/supersession-pick.ts b/packages/database/supabase/functions/lib/supersession-pick.ts
index 2f07b83efb..89833d92f4 100644
--- a/packages/database/supabase/functions/lib/supersession-pick.ts
+++ b/packages/database/supabase/functions/lib/supersession-pick.ts
@@ -52,9 +52,14 @@ export function buildSupersessionRedirectMap(
});
}
- // Collapse multi-hop chains, multiplying factors along the way, cycle-safe.
- for (const oldId of [...redirect.keys()]) {
- const start = redirect.get(oldId)!;
+ // Collapse multi-hop chains, multiplying factors along the way. Built into a
+ // SECOND map rather than updating `redirect` in place: mutating it mid-walk
+ // makes the result depend on which entry is visited first (a later entry reads
+ // an earlier one's already-collapsed value and multiplies its factor in twice)
+ // and, once cycle entries are dropped, lets a cycle member read a deleted
+ // predecessor, see no successor, and pass as a clean terminal.
+ const collapsed = new Map<string, Redirect>();
+ for (const [oldId, start] of redirect) {
let to = start.to;
let factor = start.factor;
const seen = new Set<string>([oldId]);
@@ -64,8 +69,16 @@ export function buildSupersessionRedirectMap(
factor *= next.factor;
to = next.to;
}
- redirect.set(oldId, { to, factor });
+ // Exiting with `to` still in the map means the walk closed a loop. A cycle
+ // has no terminal successor, so there is nothing safe to point at — drop the
+ // entry and leave the demand on the original part. Keeping it made the item
+ // supersede ITSELF (`substitutedFromItemId` = its own id) while multiplying
+ // the job's quantities by the cycle's factor product, which is invisible
+ // downstream: the quantity is a plausible number and nothing can repair it.
+ // Only a self-reference is blocked by the DB CHECK and the zod validator, so
+ // a two-row cycle is writable straight from the UI.
+ if (!redirect.has(to)) collapsed.set(oldId, { to, factor });
}
- return redirect;
+ return collapsed;
}
diff --git a/packages/database/supabase/functions/lib/types.ts b/packages/database/supabase/functions/lib/types.ts
index 6b382b895b..1dccda60d7 100644
--- a/packages/database/supabase/functions/lib/types.ts
+++ b/packages/database/supabase/functions/lib/types.ts
@@ -76846,6 +76846,7 @@ export type Database = {
estimatedQuantity: number
id: string
itemReadableId: string
+ itemScrapPercentage: number
itemTrackingType: Database["public"]["Enums"]["itemTrackingType"]
jobMakeMethodId: string
jobMaterialItemId: string
@@ -76863,6 +76864,7 @@ export type Database = {
quantityPerParent: number
storageUnitId: string
storageUnitName: string
+ substitutedFromItemId: string
thumbnailPath: string
type: Database["public"]["Enums"]["itemType"]
unitOfMeasureCode: string
diff --git a/packages/database/supabase/migrations/20260825141102_job-material-supersession-visibility.sql b/packages/database/supabase/migrations/20260825141102_job-material-supersession-visibility.sql
new file mode 100644
index 0000000000..1e10cf5d3c
--- /dev/null
+++ b/packages/database/supabase/migrations/20260825141102_job-material-supersession-visibility.sql
@@ -0,0 +1,283 @@
+-- Surface supersession provenance + the locked scrap rate on job materials.
+--
+-- `jobMaterial.substitutedFromItemId` / `substitutionFactor` have been written
+-- since the supersession feature shipped, and `JobMaterialsTable` already
+-- renders an "substituted from X" line from the first — but this RPC backs that
+-- page and returned neither column, so the indicator read `undefined` on every
+-- row and has never once rendered. The cell reaches for the field through an
+-- `as { substitutedFromItemId?: string | null }` cast, which asserts an OPTIONAL
+-- property onto a row type that lacks it, so nothing failed to compile.
+--
+-- `itemScrapPercentage` is surfaced for the same reason: it is locked at job
+-- creation, `recalculate` only re-derives it when the stored value is NULL (and
+-- the column is NOT NULL), so a wrong value is permanent — and it was invisible
+-- in the product, which is how it stayed unnoticed.
+--
+-- Return type changes, so this is DROP + CREATE, not CREATE OR REPLACE. The body
+-- is otherwise unchanged from the definition installed by
+-- 20260708204214_partial-gr-visibility-and-short-close.sql; only the two columns
+-- are added (RETURNS TABLE, the job_materials CTE, and the final SELECT), plus a
+-- pinned search_path on the SECURITY DEFINER declaration.
+
+DROP FUNCTION IF EXISTS get_job_quantity_on_hand;
+
+CREATE OR REPLACE FUNCTION public.get_job_quantity_on_hand(job_id text, company_id text, location_id text)
+ RETURNS TABLE(id text, "jobMaterialItemId" text, "jobMakeMethodId" text, "itemReadableId" text, name text, description text, "itemTrackingType" "itemTrackingType", "methodType" "methodType", type "itemType", "thumbnailPath" text, "unitOfMeasureCode" text, "quantityPerParent" numeric, "estimatedQuantity" numeric, "quantityIssued" numeric, "quantityOnHandInStorageUnit" numeric, "quantityOnHandNotInStorageUnit" numeric, "quantityOnSalesOrder" numeric, "quantityOnPurchaseOrder" numeric, "quantityOnProductionOrder" numeric, "quantityFromProductionOrderInStorageUnit" numeric, "quantityFromProductionOrderNotInStorageUnit" numeric, "quantityInTransitToStorageUnit" numeric, "storageUnitId" text, "storageUnitName" text, "itemScrapPercentage" numeric, "substitutedFromItemId" text)
+ LANGUAGE plpgsql
+ SECURITY DEFINER
+ -- SECURITY DEFINER runs as the owner and resolves unqualified names through the
+ -- CALLER's search_path, so pin it: a caller-created schema must not be able to
+ -- shadow the tables below. Every object this reads lives in public.
+ SET search_path = public, pg_temp
+AS $function$
+ BEGIN
+ RETURN QUERY
+
+WITH
+ job_materials AS (
+ SELECT
+ jm."id",
+ jm."itemId",
+ jm."jobMakeMethodId",
+ jm."description",
+ jm."methodType",
+ jm."quantity",
+ jm."estimatedQuantity",
+ jm."quantityIssued",
+ jm."storageUnitId",
+ jm."itemScrapPercentage",
+ jm."substitutedFromItemId"
+ FROM
+ "jobMaterial" jm
+ WHERE
+ jm."jobId" = job_id
+ -- SECURITY DEFINER bypasses RLS, so the caller's company must be checked
+ -- here: without it a valid job id from another tenant returns its rows.
+ AND jm."companyId" = company_id
+ ),
+ -- Distinct item / item+unit sets used to FILTER the aggregate CTEs below.
+ -- Joining the raw job_materials rows fans out (multiplies) the aggregates when
+ -- an item is on more than one BoM line — these dedupe so each item is counted
+ -- once.
+ job_material_items AS (
+ SELECT DISTINCT jm."itemId" FROM job_materials jm
+ ),
+ job_material_item_units AS (
+ SELECT DISTINCT jm."itemId", jm."storageUnitId" FROM job_materials jm
+ ),
+ open_purchase_orders AS (
+ SELECT
+ pol."itemId" AS "purchaseOrderItemId",
+ SUM(pol."quantityToReceive" * COALESCE(pol."conversionFactor", 1)) AS "quantityOnPurchaseOrder"
+ FROM
+ "purchaseOrder" po
+ INNER JOIN "purchaseOrderLine" pol
+ ON pol."purchaseOrderId" = po."id"
+ INNER JOIN job_material_items jm
+ ON jm."itemId" = pol."itemId"
+ WHERE
+ po."status" IN (
+ 'Planned',
+ 'Needs Approval',
+ 'To Review',
+ 'To Receive',
+ 'To Receive and Invoice'
+ )
+ AND po."companyId" = company_id
+ AND pol."locationId" = location_id
+ AND pol."receivedComplete" = false
+ GROUP BY pol."itemId"
+ ),
+ open_stock_transfers_to AS (
+ SELECT
+ stl."itemId",
+ stl."toStorageUnitId" AS "storageUnitId",
+ SUM(stl."outstandingQuantity") AS "quantityOnStockTransferTo"
+ FROM "stockTransferLine" stl
+ INNER JOIN "stockTransfer" st ON stl."stockTransferId" = st."id"
+ INNER JOIN job_material_items jm ON jm."itemId" = stl."itemId"
+ WHERE st."status" IN ('Released', 'In Progress')
+ AND st."companyId" = company_id
+ AND st."locationId" = location_id
+ GROUP BY stl."itemId", stl."toStorageUnitId"
+ ),
+ open_stock_transfers_from AS (
+ SELECT
+ stl."itemId",
+ stl."fromStorageUnitId" AS "storageUnitId",
+ SUM(stl."outstandingQuantity") AS "quantityOnStockTransferFrom"
+ FROM "stockTransferLine" stl
+ INNER JOIN "stockTransfer" st ON stl."stockTransferId" = st."id"
+ INNER JOIN job_material_items jm ON jm."itemId" = stl."itemId"
+ WHERE st."status" IN ('Released', 'In Progress')
+ AND st."companyId" = company_id
+ AND st."locationId" = location_id
+ GROUP BY stl."itemId", stl."fromStorageUnitId"
+ ),
+ stock_transfers_in_transit AS (
+ SELECT
+ COALESCE(stt."itemId", stf."itemId") AS "itemId",
+ COALESCE(stt."storageUnitId", stf."storageUnitId") AS "storageUnitId",
+ COALESCE(stt."quantityOnStockTransferTo", 0) - COALESCE(stf."quantityOnStockTransferFrom", 0) AS "quantityInTransit"
+ FROM open_stock_transfers_to stt
+ FULL OUTER JOIN open_stock_transfers_from stf ON stt."itemId" = stf."itemId" AND stt."storageUnitId" = stf."storageUnitId"
+ ),
+ open_sales_orders AS (
+ SELECT
+ sol."itemId" AS "salesOrderItemId",
+ SUM(sol."quantityToSend") AS "quantityOnSalesOrder"
+ FROM
+ "salesOrder" so
+ INNER JOIN "salesOrderLine" sol
+ ON sol."salesOrderId" = so."id"
+ INNER JOIN job_material_items jm
+ ON jm."itemId" = sol."itemId"
+ WHERE
+ so."status" IN (
+ 'Confirmed',
+ 'To Ship and Invoice',
+ 'To Ship',
+ 'To Invoice',
+ 'In Progress'
+ )
+ AND so."companyId" = company_id
+ AND sol."locationId" = location_id
+ GROUP BY sol."itemId"
+ ),
+ open_jobs AS (
+ SELECT
+ j."itemId" AS "jobItemId",
+ SUM(j."productionQuantity" + j."scrapQuantity" - j."quantityReceivedToInventory" - j."quantityShipped") AS "quantityOnProductionOrder"
+ FROM job j
+ WHERE j."status" IN (
+ 'Planned',
+ 'Ready',
+ 'In Progress',
+ 'Paused'
+ )
+ AND j."companyId" = company_id
+ AND j."locationId" = location_id
+ GROUP BY j."itemId"
+ ),
+ open_job_requirements AS (
+ SELECT
+ jm."itemId",
+ jm."storageUnitId",
+ SUM(jm."quantityToIssue") AS "quantityOnProductionDemand"
+ FROM "jobMaterial" jm
+ INNER JOIN "job" j ON jm."jobId" = j."id"
+ INNER JOIN job_material_items jmat
+ ON jmat."itemId" = jm."itemId"
+ WHERE j."status" IN (
+ 'Planned',
+ 'Ready',
+ 'In Progress',
+ 'Paused'
+ )
+ AND jm."methodType" != 'Make to Order'
+ AND j."companyId" = company_id
+ AND j."locationId" = location_id
+ GROUP BY jm."itemId", jm."storageUnitId"
+ ),
+ open_job_requirements_in_storage_unit AS (
+ SELECT
+ ojr."itemId",
+ SUM(ojr."quantityOnProductionDemand") AS "quantityOnProductionDemandInStorageUnit"
+ FROM open_job_requirements ojr
+ INNER JOIN job_material_item_units jm
+ ON jm."itemId" = ojr."itemId" AND jm."storageUnitId" = ojr."storageUnitId"
+ GROUP BY ojr."itemId"
+ ),
+ open_job_requirements_not_in_storage_unit AS (
+ SELECT
+ ojr."itemId",
+ SUM(ojr."quantityOnProductionDemand") AS "quantityOnProductionDemandNotInStorageUnit"
+ FROM open_job_requirements ojr
+ INNER JOIN job_material_item_units jm
+ ON jm."itemId" = ojr."itemId" AND (jm."storageUnitId" IS NULL OR ojr."storageUnitId" IS NULL OR jm."storageUnitId" != ojr."storageUnitId")
+ GROUP BY ojr."itemId"
+ ),
+ item_ledgers AS (
+ SELECT
+ il."itemId" AS "ledgerItemId",
+ il."storageUnitId",
+ -- quantityOnHand excludes only Rejected tracked entities. On Hold
+ -- units are still physically in the warehouse and count toward
+ -- on-hand. Rows with no tracked entity always count.
+ SUM(il."quantity") FILTER (
+ WHERE il."trackedEntityStatus" IS NULL
+ OR il."trackedEntityStatus" != 'Rejected'
+ ) AS "quantityOnHand"
+ FROM "itemLedger" il
+ INNER JOIN job_material_items jm
+ ON jm."itemId" = il."itemId"
+ WHERE il."companyId" = company_id
+ AND il."locationId" = location_id
+ GROUP BY il."itemId", il."storageUnitId"
+ ),
+ item_ledgers_in_storage_unit AS (
+ SELECT
+ il."ledgerItemId",
+ SUM(il."quantityOnHand") AS "quantityOnHandInStorageUnit"
+ FROM item_ledgers il
+ INNER JOIN job_material_item_units jm
+ ON jm."itemId" = il."ledgerItemId" AND jm."storageUnitId" = il."storageUnitId"
+ GROUP BY il."ledgerItemId"
+ ),
+ item_ledgers_not_in_storage_unit AS (
+ SELECT
+ il."ledgerItemId",
+ SUM(il."quantityOnHand") AS "quantityOnHandNotInStorageUnit"
+ FROM item_ledgers il
+ INNER JOIN job_material_item_units jm
+ ON jm."itemId" = il."ledgerItemId" AND (jm."storageUnitId" IS NULL OR il."storageUnitId" IS NULL OR jm."storageUnitId" != il."storageUnitId")
+ GROUP BY il."ledgerItemId"
+ )
+
+SELECT
+ jm."id",
+ jm."itemId" AS "jobMaterialItemId",
+ jm."jobMakeMethodId",
+ i."readableId" AS "itemReadableId",
+ i."name",
+ jm."description",
+ i."itemTrackingType",
+ jm."methodType",
+ i."type",
+ CASE
+ WHEN i."thumbnailPath" IS NULL AND mu."thumbnailPath" IS NOT NULL THEN mu."thumbnailPath"
+ ELSE i."thumbnailPath"
+ END AS "thumbnailPath",
+ i."unitOfMeasureCode",
+ jm."quantity" as "quantityPerParent",
+ jm."estimatedQuantity",
+ jm."quantityIssued",
+ COALESCE(ils."quantityOnHandInStorageUnit", 0) AS "quantityOnHandInStorageUnit",
+ COALESCE(ilns."quantityOnHandNotInStorageUnit", 0) AS "quantityOnHandNotInStorageUnit",
+ COALESCE(so."quantityOnSalesOrder", 0) AS "quantityOnSalesOrder",
+ COALESCE(po."quantityOnPurchaseOrder", 0) AS "quantityOnPurchaseOrder",
+ COALESCE(oj."quantityOnProductionOrder", 0) AS "quantityOnProductionOrder",
+ COALESCE(ojis."quantityOnProductionDemandInStorageUnit", 0) AS "quantityFromProductionOrderInStorageUnit",
+ COALESCE(ojns."quantityOnProductionDemandNotInStorageUnit", 0) AS "quantityFromProductionOrderNotInStorageUnit",
+ COALESCE(stit."quantityInTransit", 0) AS "quantityInTransitToStorageUnit",
+ jm."storageUnitId",
+ s."name" AS "storageUnitName",
+ jm."itemScrapPercentage",
+ jm."substitutedFromItemId"
+FROM
+ job_materials jm
+ INNER JOIN "item" i ON i."id" = jm."itemId"
+ LEFT JOIN "storageUnit" s ON s."id" = jm."storageUnitId"
+ LEFT JOIN item_ledgers_in_storage_unit ils ON i."id" = ils."ledgerItemId"
+ LEFT JOIN item_ledgers_not_in_storage_unit ilns ON i."id" = ilns."ledgerItemId"
+ LEFT JOIN open_sales_orders so ON i."id" = so."salesOrderItemId"
+ LEFT JOIN open_purchase_orders po ON i."id" = po."purchaseOrderItemId"
+ LEFT JOIN open_jobs oj ON i."id" = oj."jobItemId"
+ LEFT JOIN open_job_requirements_in_storage_unit ojis ON i."id" = ojis."itemId"
+ LEFT JOIN open_job_requirements_not_in_storage_unit ojns ON i."id" = ojns."itemId"
+ LEFT JOIN "modelUpload" mu ON mu.id = i."modelUploadId"
+ LEFT JOIN stock_transfers_in_transit stit ON jm."itemId" = stit."itemId" AND jm."storageUnitId" = stit."storageUnitId";
+ END;
+$function$
+
+
diff --git a/packages/database/supabase/migrations/20260825194738_job-material-item-swap-tracked-entity.sql b/packages/database/supabase/migrations/20260825194738_job-material-item-swap-tracked-entity.sql
new file mode 100644
index 0000000000..c4eea30272
--- /dev/null
+++ b/packages/database/supabase/migrations/20260825194738_job-material-item-swap-tracked-entity.sql
@@ -0,0 +1,139 @@
+-- Repoint the existing tracked entity when a Make to Order job material is
+-- swapped to a different item, instead of inserting a second one.
+--
+-- `sync_update_job_material_make_method_item_id` has two branches. The first
+-- (no jobMakeMethod yet) creates the make method AND its 'Reserved'
+-- trackedEntity — correct. The second (make method already exists) updated the
+-- make method and then inserted ANOTHER trackedEntity, unguarded, even though
+-- the row created at insert time is still there.
+--
+-- Every made-component supersession swap therefore left two 'Reserved' entities
+-- for one job material, and they were not duplicates of each other: the first
+-- kept the PREDECESSOR's itemId and readable id and was never repointed. Both
+-- carry the same 'Job Material' / 'Job Make Method' attributes, so every
+-- consumer that keys off those sees both — MES walks the operator through a
+-- phantom unit, an extra label prints bearing the retired part number, and
+-- `existingEntityCount` in the issue function is inflated, which suppresses
+-- legitimate scrap-replacement units.
+--
+-- Inventory and GL are unaffected: on-hand comes from `itemLedger`, and a
+-- 'Reserved' entity with no ledger row contributes zero.
+--
+-- The fix updates in place, so the stale predecessor row is corrected rather
+-- than merely being left un-duplicated. The insert is kept as a fallback for
+-- when no reserved entity exists (the row was consumed, or history predates
+-- the insert-time interceptor) so the branch can never leave the material with
+-- no entity at all.
+--
+-- Scope note: this branch is not supersession-specific. It runs whenever a
+-- Make to Order material's item changes on a job that already has a make
+-- method — editing a made material's item by hand hits the same path, and had
+-- the same duplicate.
+
+CREATE OR REPLACE FUNCTION sync_update_job_material_make_method_item_id(
+ p_table TEXT, p_operation TEXT, p_new JSONB, p_old JSONB
+) RETURNS VOID LANGUAGE plpgsql SECURITY DEFINER AS $$
+DECLARE
+ v_item_readable_id TEXT;
+ v_item_tracking_type TEXT;
+ v_job_make_method_id TEXT;
+ -- Bare NUMERIC: the repo bans a precision spec on NUMERIC, and the
+ -- conformance gate scans migration TEXT — so carrying the original
+ -- declaration's precision forward registered as a new violation (as does
+ -- quoting it in a comment). Behaviour is identical: makeMethod.version is
+ -- itself a constrained numeric, so the value round-trips through this local
+ -- unchanged and lands back in the same column.
+ v_version NUMERIC;
+ v_attributes JSONB;
+BEGIN
+ IF p_operation != 'UPDATE' THEN RETURN; END IF;
+
+ IF NOT (
+ ((p_old->>'methodType') = 'Make to Order' AND (p_old->>'itemId') IS DISTINCT FROM (p_new->>'itemId'))
+ OR ((p_new->>'methodType') = 'Make to Order' AND (p_old->>'methodType') != 'Make to Order')
+ ) THEN
+ RETURN;
+ END IF;
+
+ -- Both lookups are company-scoped: "item" is keyed ("id", "companyId") and
+ -- "activeMakeMethods" is per company, so matching on the item id alone could
+ -- read another tenant's row. Pre-existing in the definition this replaces.
+ SELECT "readableIdWithRevision", "itemTrackingType"
+ INTO v_item_readable_id, v_item_tracking_type
+ FROM "item"
+ WHERE "id" = p_new->>'itemId'
+ AND "companyId" = p_new->>'companyId';
+
+ SELECT "version" INTO v_version FROM "activeMakeMethods"
+ WHERE "itemId" = p_new->>'itemId'
+ AND "companyId" = p_new->>'companyId';
+
+ IF NOT EXISTS (
+ SELECT 1 FROM "jobMakeMethod"
+ WHERE "jobId" = p_new->>'jobId' AND "parentMaterialId" = p_new->>'id'
+ ) THEN
+ INSERT INTO "jobMakeMethod" (
+ "jobId", "parentMaterialId", "itemId", "companyId", "createdBy",
+ "requiresSerialTracking", "requiresBatchTracking", "version"
+ ) VALUES (
+ p_new->>'jobId', p_new->>'id', p_new->>'itemId', p_new->>'companyId', p_new->>'createdBy',
+ v_item_tracking_type = 'Serial', v_item_tracking_type = 'Batch', v_version
+ )
+ RETURNING "id" INTO v_job_make_method_id;
+
+ INSERT INTO "trackedEntity" (
+ "sourceDocument", "sourceDocumentId", "sourceDocumentReadableId",
+ "quantity", "status", "companyId", "createdBy", "attributes", "itemId"
+ ) VALUES (
+ 'Item', p_new->>'itemId', v_item_readable_id,
+ (p_new->>'quantity')::numeric, 'Reserved',
+ p_new->>'companyId', p_new->>'createdBy',
+ jsonb_build_object('Job', p_new->>'jobId', 'Job Make Method', v_job_make_method_id, 'Job Material', p_new->>'id'),
+ p_new->>'itemId'
+ );
+ ELSE
+ UPDATE "jobMakeMethod"
+ SET "itemId" = p_new->>'itemId',
+ "requiresSerialTracking" = (v_item_tracking_type = 'Serial'),
+ "requiresBatchTracking" = (v_item_tracking_type = 'Batch'),
+ "version" = v_version
+ WHERE "jobId" = p_new->>'jobId' AND "parentMaterialId" = p_new->>'id'
+ RETURNING "id" INTO v_job_make_method_id;
+
+ v_attributes := jsonb_build_object(
+ 'Job', p_new->>'jobId',
+ 'Job Make Method', v_job_make_method_id,
+ 'Job Material', p_new->>'id'
+ );
+
+ -- Repoint what is already there. Restricted to 'Reserved': an entity that
+ -- has been consumed or received is history, and rewriting its item would
+ -- falsify what was actually built.
+ UPDATE "trackedEntity"
+ SET "sourceDocumentId" = p_new->>'itemId',
+ "sourceDocumentReadableId" = v_item_readable_id,
+ "itemId" = p_new->>'itemId',
+ "quantity" = (p_new->>'quantity')::numeric,
+ -- Merge, don't replace: the shelf-life stamp writes expirationDate into
+ -- this same attributes object, and an assignment would silently drop it.
+ "attributes" = "attributes" || v_attributes
+ WHERE "companyId" = p_new->>'companyId'
+ AND "status" = 'Reserved'
+ AND "attributes"->>'Job Material' = p_new->>'id';
+
+ -- Only when there was nothing to repoint.
+ IF NOT FOUND THEN
+ INSERT INTO "trackedEntity" (
+ "sourceDocument", "sourceDocumentId", "sourceDocumentReadableId",
+ "quantity", "status", "companyId", "createdBy", "attributes", "itemId"
+ ) VALUES (
+ 'Item', p_new->>'itemId', v_item_readable_id,
+ (p_new->>'quantity')::numeric, 'Reserved',
+ p_new->>'companyId', p_new->>'createdBy',
+ v_attributes,
+ p_new->>'itemId'
+ );
+ END IF;
+ END IF;
+END;
+$$;