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.
TypeScript ai-agentsbill-of-materialserpinventory-managementleanmanufacturingmanufacturing-execution-systemmcp-servermesmrpopen-source-erppostgresqlproduction-planningqmsquality-management-systemreact-routerself-hostedsupabasetraceabilitytypescript
fix(items): offer the whole BOM in step parts pickers, hide BoM/BoP scrollbars (#1446)
Siddharth Gaikwada277baeaddc9
diff --git a/.ai/lessons.md b/.ai/lessons.mdindex 91955a01ef..730c43fcdf 100644--- a/.ai/lessons.md+++ b/.ai/lessons.md@@ -1111,3 +1111,13 @@ canvas hosting Radix popovers/selects.**Rule:** Any new row that reuses an existing readable id must qualify it (`Q000001-1`), and any insert into a table whose unique key can be orphaned by a delete needs `onConflict(...).doUpdateSet(...)` rather than a bare insert. When a user-facing action reports a generic failure, read the edge-runtime container log before theorising — the route's flash message hides the Postgres error code.**Applies to:** `packages/database/supabase/functions/get-method/index.ts` (`quoteToQuote`), `apps/erp/app/modules/sales/sales.service.ts` (`deleteQuote`), any insert into `externalLink`.++## Card lists never get their own scroll region — the page is the only scroll surface++**Context:** The Bill of Material / Bill of Process cards were capped at `max-h-[60dvh]` with an internal ScrollArea (PR #1230) so long lists wouldn't grow the page unbounded. Brad asked for the scrollbars to be removed; hiding the bar but keeping the capped region was the wrong reading.++**Problem:** A nested scroll region doesn't reduce scrolling — the same rows still have to be scrolled through — it just hijacks the wheel whenever the cursor crosses the card, so the user gets two scroll surfaces, scroll-trapping at the region's edges, and a janky feel. "Remove the scroll bars" meant remove the *scrolling*, not restyle the bar.++**Rule:** Card lists (BoM, BoP, and anything similar) render at natural height; the page-level container is the only scroll surface. Don't add `max-h` + `overflow-y-auto` to a card's content to tame its length — if a long list is a problem, solve it with collapse/pagination/virtualization, never a nested scroll region.++**Applies to:** `BillOfMaterial.tsx` / `BillOfProcess.tsx` (items), `JobBillOfMaterial.tsx` / `JobBillOfProcess.tsx`, `QuoteBillOfMaterial.tsx` / `QuoteBillOfProcess.tsx`, and any new card-embedded list in `apps/erp`.diff --git a/apps/erp/app/components/StepLinkEditor.tsx b/apps/erp/app/components/StepLinkEditor.tsxindex bb6f0fcedd..df416ff02d 100644--- a/apps/erp/app/components/StepLinkEditor.tsx+++ b/apps/erp/app/components/StepLinkEditor.tsx@@ -8,11 +8,14 @@ import {CommandList,IconButton,Label,+ NumberField,+ NumberInput,Popover,PopoverContent,PopoverTrigger,VStack} from "@carbon/react";+import { INPUT_FORMAT, INPUT_STEP } from "@carbon/utils";import { useLingui } from "@lingui/react/macro";import { useState } from "react";import { LuCirclePlus, LuX } from "react-icons/lu";@@ -23,8 +26,81 @@ export type StepLinkItem = {// Optional muted second line (e.g. a tool's descriptive name under its id).secondary?: string;quantity: number;+ // Per-step share of the BOM line (parts only). null/undefined = the full line+ // quantity. Editable when the caller supplies onQuantityChange.+ linkedQuantity?: number | null;+ // Curated items (e.g. tools already on the operation) group FIRST in the+ // picker, under primaryGroupLabel, so they aren't buried in the full library.+ primary?: boolean;};+// Compact per-step quantity editor on a linked row. Commits on blur/Enter via+// react-aria's NumberField; only fires when the value actually changed, so a+// plain blur never re-posts. Defaults to the full BOM line quantity. Zero (and+// cleared/invalid input) is refused — a step that uses none of a part should+// not be linked to it — and the controlled value snaps the field back.+function LinkedQuantity({+ item,+ isDisabled,+ onCommit+}: {+ item: StepLinkItem;+ isDisabled: boolean;+ onCommit: (quantity: number) => void;+}) {+ const value = item.linkedQuantity ?? item.quantity;+ return (+ <NumberField+ value={value}+ minValue={0}+ // A step's share can never exceed the BOM line quantity — the line is+ // the source of truth; entries above it clamp down on commit.+ maxValue={item.quantity}+ step={INPUT_STEP.quantity}+ formatOptions={INPUT_FORMAT.quantity}+ isDisabled={isDisabled}+ onChange={(next) => {+ if (Number.isFinite(next) && next > 0 && next !== value) {+ onCommit(next);+ }+ }}+ className="w-20 shrink-0"+ aria-label="Quantity"+ >+ <NumberInput size="sm" className="h-8 pr-2 text-right text-xs" />+ </NumberField>+ );+}++// One selectable row in the picker popover, shared by both groups.+function StepLinkOption({+ item,+ onAdd+}: {+ item: StepLinkItem;+ onAdd: (id: string) => void;+}) {+ return (+ <CommandItem+ value={`${item.name} ${item.secondary ?? ""} ${item.id}`}+ onSelect={() => onAdd(item.id)}+ className="flex items-center justify-between gap-4"+ >+ <div className="flex min-w-0 flex-1 flex-col">+ <span className="truncate">{item.name}</span>+ {item.secondary && (+ <span className="truncate text-xs text-muted-foreground">+ {item.secondary}+ </span>+ )}+ </div>+ <span className="shrink-0 text-xs text-muted-foreground">+ ×{item.quantity}+ </span>+ </CommandItem>+ );+}+// Step-side link picker: assign an operation's BOM parts OR tools to a step (the inverse of the// old BOM/tool "Steps" picker). Presentational — the caller owns the linked set and persists// changes (immediately via a route for saved steps, or a draft buffer for a step being created).@@ -42,7 +118,10 @@ export function StepLinkEditor({isDisabled,busy,onAdd,- onRemove+ onRemove,+ onQuantityChange,+ primaryGroupLabel,+ secondaryGroupLabel}: {label: string;addLabel: string;@@ -57,6 +136,15 @@ export function StepLinkEditor({busy?: boolean;onAdd: (id: string) => void;onRemove: (id: string) => void;+ // When supplied, linked rows show an editable per-step quantity (defaulting to+ // the full BOM line quantity) instead of the static ×N badge — so one line's+ // quantity can be split across steps (5 screws here, 5 on the next step).+ onQuantityChange?: (id: string, quantity: number) => void;+ // Group headings when items mix a curated set (`primary`) with the full+ // library — e.g. "On this operation" over the operation's tools, "All tools"+ // over the rest. Only rendered when at least one available item is primary.+ primaryGroupLabel?: string;+ secondaryGroupLabel?: string;}) {const { t } = useLingui();const [open, setOpen] = useState(false);@@ -64,6 +152,8 @@ export function StepLinkEditor({const linkedSet = new Set(linkedIds);const linked = items.filter((p) => linkedSet.has(p.id));const available = items.filter((p) => !linkedSet.has(p.id));+ const availablePrimary = available.filter((p) => p.primary);+ const availableRest = available.filter((p) => !p.primary);if (isDisabled && linked.length === 0) return null;@@ -96,26 +186,26 @@ export function StepLinkEditor({<CommandInput placeholder={searchPlaceholder} /><CommandList><CommandEmpty>{t`No results`}</CommandEmpty>- <CommandGroup>- {available.map((item) => (- <CommandItem- key={item.id}- value={`${item.name} ${item.secondary ?? ""} ${item.id}`}- onSelect={() => onAdd(item.id)}- className="flex items-center justify-between gap-4"- >- <div className="flex min-w-0 flex-1 flex-col">- <span className="truncate">{item.name}</span>- {item.secondary && (- <span className="truncate text-xs text-muted-foreground">- {item.secondary}- </span>- )}- </div>- <span className="shrink-0 text-xs text-muted-foreground">- ×{item.quantity}- </span>- </CommandItem>+ {availablePrimary.length > 0 && (+ <CommandGroup heading={primaryGroupLabel}>+ {availablePrimary.map((item) => (+ <StepLinkOption+ key={item.id}+ item={item}+ onAdd={onAdd}+ />+ ))}+ </CommandGroup>+ )}+ <CommandGroup+ heading={+ availablePrimary.length > 0+ ? secondaryGroupLabel+ : undefined+ }+ >+ {availableRest.map((item) => (+ <StepLinkOption key={item.id} item={item} onAdd={onAdd} />))}</CommandGroup></CommandList>@@ -142,9 +232,17 @@ export function StepLinkEditor({</span>)}</div>- <span className="shrink-0 rounded-md border px-2 py-0.5 text-xs text-muted-foreground">- ×{item.quantity}- </span>+ {onQuantityChange && !isDisabled ? (+ <LinkedQuantity+ item={item}+ isDisabled={Boolean(busy)}+ onCommit={(quantity) => onQuantityChange(item.id, quantity)}+ />+ ) : (+ <span className="shrink-0 rounded-md border px-2 py-0.5 text-xs text-muted-foreground">+ ×{item.linkedQuantity ?? item.quantity}+ </span>+ )}{!isDisabled && (<IconButtonaria-label={removeLabel}diff --git a/apps/erp/app/modules/items/items.service.test.ts b/apps/erp/app/modules/items/items.service.test.tsindex d22b7c6da7..7826cf7a76 100644--- a/apps/erp/app/modules/items/items.service.test.ts+++ b/apps/erp/app/modules/items/items.service.test.ts@@ -394,7 +394,11 @@ describe("duplicateMethodOperationStep", () => {{ methodOperationToolId: "tool-1", methodOperationStepId: "step-1" }],methodMaterialStep: [- { methodMaterialId: "mat-1", methodOperationStepId: "step-1" }+ {+ methodMaterialId: "mat-1",+ methodOperationStepId: "step-1",+ quantity: 5+ }]};}@@ -431,7 +435,13 @@ describe("duplicateMethodOperationStep", () => {{ methodOperationToolId: "tool-1", methodOperationStepId: "step-new" }]);expect(inserts.find((i) => i.table === "methodMaterialStep")?.rows).toEqual(- [{ methodMaterialId: "mat-1", methodOperationStepId: "step-new" }]+ [+ {+ methodMaterialId: "mat-1",+ methodOperationStepId: "step-new",+ quantity: 5+ }+ ]);});diff --git a/apps/erp/app/modules/items/items.service.ts b/apps/erp/app/modules/items/items.service.tsindex 7ad02dbdfe..b73ac4d444 100644--- a/apps/erp/app/modules/items/items.service.ts+++ b/apps/erp/app/modules/items/items.service.ts@@ -1552,17 +1552,39 @@ export async function getMethodMaterials(return query;}+// The step-link `quantity` column ships with this branch's migration, which only+// runs on main — previews (and the prod window between app deploy and migration)+// run this code against the pre-migration schema. PostgREST fails the WHOLE+// select on an unknown embedded column, so fall back to the quantity-less query+// instead of rendering an empty BOM. 42703 = Postgres undefined_column; PGRST204+// = PostgREST's schema-cache miss for a written column.+function isMissingQuantityColumn(+ error: { code?: string; message?: string } | null+) {+ return error?.code === "42703" || error?.code === "PGRST204";+}+export async function getMethodMaterialsByMakeMethod(client: SupabaseClient<Database>,makeMethodId: string) {- return client+ const result = await client.from("methodMaterial").select(- "*, item(name, itemTrackingType, replenishmentSystem, defaultMethodType, sourcingType), methodMaterialStep(methodOperationStepId)"+ "*, item(name, itemTrackingType, replenishmentSystem, defaultMethodType, sourcingType), methodMaterialStep(methodOperationStepId, quantity)").eq("makeMethodId", makeMethodId).order("order", { ascending: true });+ if (isMissingQuantityColumn(result.error)) {+ return (await client+ .from("methodMaterial")+ .select(+ "*, item(name, itemTrackingType, replenishmentSystem, defaultMethodType, sourcingType), methodMaterialStep(methodOperationStepId)"+ )+ .eq("makeMethodId", makeMethodId)+ .order("order", { ascending: true })) as unknown as typeof result;+ }+ return result;}export async function getMethodOperations(@@ -4177,10 +4199,17 @@ export async function duplicateMethodOperationStep(}// Copy step-scoped part/material links (same operation-level-vs-scoped semantics as tools).- const materialLinks = await client+ // Pre-migration schema: no quantity column — copy the bare links instead.+ let materialLinks = await client.from("methodMaterialStep")- .select("methodMaterialId")+ .select("methodMaterialId, quantity").eq("methodOperationStepId", args.id);+ if (isMissingQuantityColumn(materialLinks.error)) {+ materialLinks = (await client+ .from("methodMaterialStep")+ .select("methodMaterialId")+ .eq("methodOperationStepId", args.id)) as unknown as typeof materialLinks;+ }if (materialLinks.error) {return { data: null, error: materialLinks.error };}@@ -4188,7 +4217,8 @@ export async function duplicateMethodOperationStep(const materialLinkInsert = await client.from("methodMaterialStep").insert(materialLinks.data.map((l) => ({methodMaterialId: l.methodMaterialId,- methodOperationStepId: newStepId+ methodOperationStepId: newStepId,+ ...(l.quantity != null ? { quantity: l.quantity } : {})})));if (materialLinkInsert.error) {@@ -4294,27 +4324,51 @@ export async function replaceMethodMaterialSteps(methodMaterialId: string,methodOperationStepIds: string[]) {+ // Per-step quantities are edited from the step side; a BOM-side rewrite of the+ // step set must not wipe them, so carry each retained step's quantity across+ // the delete-then-insert. Pre-migration schema: quantities don't exist, so+ // fall back to the bare link set.+ let quantityByStepId = new Map<string, number | null>();+ const existing = await client+ .from("methodMaterialStep")+ .select("methodOperationStepId, quantity")+ .eq("methodMaterialId", methodMaterialId);+ if (existing.error && !isMissingQuantityColumn(existing.error)) {+ return existing;+ }+ if (!existing.error) {+ quantityByStepId = new Map(+ (existing.data ?? []).map((l) => [l.methodOperationStepId, l.quantity])+ );+ }const del = await client.from("methodMaterialStep").delete().eq("methodMaterialId", methodMaterialId);if (del.error || methodOperationStepIds.length === 0) return del;return client.from("methodMaterialStep").insert(- methodOperationStepIds.map((methodOperationStepId) => ({- methodMaterialId,- methodOperationStepId- }))+ methodOperationStepIds.map((methodOperationStepId) => {+ const quantity = quantityByStepId.get(methodOperationStepId);+ return {+ methodMaterialId,+ methodOperationStepId,+ ...(quantity != null ? { quantity } : {})+ };+ }));}// Toggle a single part↔step link from the STEP side (the step editor's Parts picker).// `linked` true = link the material to the step, false = unlink. Idempotent on link.+// `quantity` is the per-step share of the BOM line (NULL = the full line quantity);+// re-linking an existing link updates the quantity, so the same call edits a split.export async function setMethodMaterialStepLink(client: SupabaseClient<Database>,args: {methodMaterialId: string;methodOperationStepId: string;linked: boolean;+ quantity?: number | null;}) {if (args.linked) {@@ -4322,12 +4376,14 @@ export async function setMethodMaterialStepLink([{methodMaterialId: args.methodMaterialId,- methodOperationStepId: args.methodOperationStepId+ methodOperationStepId: args.methodOperationStepId,+ // Omit the column when unset so the default link path still works+ // against a pre-migration schema (see isMissingQuantityColumn).+ ...(args.quantity != null ? { quantity: args.quantity } : {})}],{- onConflict: "methodMaterialId,methodOperationStepId",- ignoreDuplicates: true+ onConflict: "methodMaterialId,methodOperationStepId"});}@@ -4339,21 +4395,53 @@ export async function setMethodMaterialStepLink(}// Toggle a single tool↔step link from the STEP side (the step editor's Tools picker).-// `linked` true = link the tool to the step, false = unlink. Idempotent on link. Twin of-// setMethodMaterialStepLink.+// Takes the tool ITEM id: the picker offers the whole tool library, and choosing a+// tool implicitly ensures the operation-level tool row exists (quantity 1 — the same+// row the operation's Tools tab would create) before linking it to the step. Unlink+// removes only the step link; the operation tool row stays (the Tools tab owns it).+// Twin of setMethodMaterialStepLink.export async function setMethodOperationToolStepLink(client: SupabaseClient<Database>,args: {- methodOperationToolId: string;+ operationId: string;+ toolId: string;methodOperationStepId: string;linked: boolean;+ companyId: string;+ createdBy: string;}) {+ const existingTool = await client+ .from("methodOperationTool")+ .select("id")+ .eq("operationId", args.operationId)+ .eq("toolId", args.toolId)+ .order("createdAt", { ascending: true })+ .limit(1)+ .maybeSingle();+ if (existingTool.error) return existingTool;+ let methodOperationToolId = existingTool.data?.id;+if (args.linked) {+ if (!methodOperationToolId) {+ const created = await client+ .from("methodOperationTool")+ .insert({+ operationId: args.operationId,+ toolId: args.toolId,+ quantity: 1,+ companyId: args.companyId,+ createdBy: args.createdBy+ })+ .select("id")+ .single();+ if (created.error) return created;+ methodOperationToolId = created.data.id;+ }return client.from("methodOperationToolStep").upsert([{- methodOperationToolId: args.methodOperationToolId,+ methodOperationToolId,methodOperationStepId: args.methodOperationStepId}],@@ -4363,10 +4451,11 @@ export async function setMethodOperationToolStepLink(});}+ if (!methodOperationToolId) return { data: null, error: null };return client.from("methodOperationToolStep").delete()- .eq("methodOperationToolId", args.methodOperationToolId)+ .eq("methodOperationToolId", methodOperationToolId).eq("methodOperationStepId", args.methodOperationStepId);}diff --git a/apps/erp/app/modules/items/ui/ChangeNotice/AffectedItemDetail.tsx b/apps/erp/app/modules/items/ui/ChangeNotice/AffectedItemDetail.tsxindex 40df694373..5844debf3c 100644--- a/apps/erp/app/modules/items/ui/ChangeNotice/AffectedItemDetail.tsx+++ b/apps/erp/app/modules/items/ui/ChangeNotice/AffectedItemDetail.tsx@@ -248,32 +248,32 @@ export default function AffectedItemDetail({{showBomBop &&(affected.makeMethod ? (<>- <BillOfMaterial- key={`bom:${affected.makeMethod.id}`}+ <BillOfProcess+ key={`bop:${affected.makeMethod.id}`}makeMethod={affected.makeMethod}- parentItemId={affected.draftItemId}- // @ts-expect-error mapped loader shape (mirrors the part route)materials={affected.methodMaterials}+ // @ts-expect-error mapped loader shape (mirrors the part route)operations={affected.methodOperations}configurable={affected.configurable}configurationRules={affected.configurationRules}parameters={affected.parameters}- replenishmentSystem={label?.replenishmentSystem ?? undefined}+ tags={affected.tags}revisionStatus={affected.revisionStatus}releaseControl={affected.releaseControl ?? undefined}isDisabled={isDisabled}disabledReason={disabledReason}/>- <BillOfProcess- key={`bop:${affected.makeMethod.id}`}+ <BillOfMaterial+ key={`bom:${affected.makeMethod.id}`}makeMethod={affected.makeMethod}- materials={affected.methodMaterials}+ parentItemId={affected.draftItemId}// @ts-expect-error mapped loader shape (mirrors the part route)+ materials={affected.methodMaterials}operations={affected.methodOperations}configurable={affected.configurable}configurationRules={affected.configurationRules}parameters={affected.parameters}- tags={affected.tags}+ replenishmentSystem={label?.replenishmentSystem ?? undefined}revisionStatus={affected.revisionStatus}releaseControl={affected.releaseControl ?? undefined}isDisabled={isDisabled}diff --git a/apps/erp/app/modules/items/ui/Item/BillOfMaterial.tsx b/apps/erp/app/modules/items/ui/Item/BillOfMaterial.tsxindex 845fc18233..fb7a400c51 100644--- a/apps/erp/app/modules/items/ui/Item/BillOfMaterial.tsx+++ b/apps/erp/app/modules/items/ui/Item/BillOfMaterial.tsx@@ -19,7 +19,6 @@ import {HStack,IconButton,Label,- ScrollArea,Tooltip,TooltipContent,TooltipTrigger,@@ -545,16 +544,14 @@ const BillOfMaterial = ({{isProductionRevision && (<ReleaseLockAlert isLocked={isReleaseLocked} className="mb-4" />)}- <ScrollArea type="auto" className="max-h-[60dvh]">- <SortableList- isReadOnly={isReadOnly}- items={materials}- onReorder={onReorder}- onToggleItem={onToggleItem}- onRemoveItem={onRemoveItem}- renderItem={renderListItem}- />- </ScrollArea>+ <SortableList+ isReadOnly={isReadOnly}+ items={materials}+ onReorder={onReorder}+ onToggleItem={onToggleItem}+ onRemoveItem={onRemoveItem}+ renderItem={renderListItem}+ /></CardContent>{configuratorDisclosure.isOpen && configuration && (<ConfigurationEditordiff --git a/apps/erp/app/modules/items/ui/Item/BillOfProcess.tsx b/apps/erp/app/modules/items/ui/Item/BillOfProcess.tsxindex d23ccdd05c..0ff90b6f4e 100644--- a/apps/erp/app/modules/items/ui/Item/BillOfProcess.tsx+++ b/apps/erp/app/modules/items/ui/Item/BillOfProcess.tsx@@ -24,7 +24,6 @@ import {IconButton,Label,Loading,- ScrollArea,ToggleGroup,ToggleGroupItem,Tooltip,@@ -163,7 +162,9 @@ type MethodMaterialType = {description?: string | null;quantity?: number | null;methodOperationId?: string | null;- methodMaterialStep?: { methodOperationStepId: string }[] | null;+ methodMaterialStep?:+ | { methodOperationStepId: string; quantity?: number | null }[]+ | null;};type BillOfProcessProps = {@@ -891,16 +892,14 @@ const BillOfProcess = ({{isProductionRevision && (<ReleaseLockAlert isLocked={isReleaseLocked} className="mb-4" />)}- <ScrollArea type="auto" className="max-h-[60dvh]">- <SortableList- isReadOnly={isReadOnly}- items={items}- onReorder={onReorder}- onToggleItem={onToggleItem}- onRemoveItem={onRemoveItem}- renderItem={renderListItem}- />- </ScrollArea>+ <SortableList+ isReadOnly={isReadOnly}+ items={items}+ onReorder={onReorder}+ onToggleItem={onToggleItem}+ onRemoveItem={onRemoveItem}+ renderItem={renderListItem}+ /></CardContent>{configuratorDisclosure.isOpen && configuration && (<ConfigurationEditor@@ -1963,38 +1962,53 @@ function AttributesForm({const draftFileInputRef = useRef<HTMLInputElement>(null);const draftModelInputRef = useRef<HTMLInputElement>(null);- // Parts (this operation's BOM materials) the operator can assign to a step. Parts picked- // while CREATING a step are buffered here and attached right after the step is created.+ // Parts the operator can assign to a step. The whole bill of material is offered —+ // the BOM is the source of truth, and a line needn't be assigned to this operation+ // to be referenced by a step. Parts picked while CREATING a step are buffered here+ // and attached right after the step is created.+ const [allItems] = useItems();const operationParts = useMemo(() =>- (materials ?? [])- .filter((m) => m.methodOperationId === operationId)- .map((m) => ({+ (materials ?? []).map((m) => {+ const item = allItems.find((i) => i.id === m.itemId);+ return {id: m.id,- name: m.description || m.itemId,+ name: item?.readableIdWithRevision ?? m.description ?? m.itemId,+ secondary: item+ ? (m.description ?? item.name ?? undefined)+ : undefined,quantity: m.quantity ?? 1- })),- [materials, operationId]- );- const [draftParts, setDraftParts] = useState<string[]>([]);-- // Tools (this operation's tools) the operator can assign to a step — the tool twin of- // operationParts/draftParts. Tools picked while CREATING a step are buffered here and- // attached right after the step is created (see the effect below).- const allTools = useTools();- const operationTools = useMemo(- () =>- (tools ?? []).map((tl) => {- const tool = allTools.find((x) => x.id === tl.toolId);- return {- id: tl.id ?? "",- name: tool?.readableIdWithRevision ?? tl.toolId ?? "",- secondary: tool?.name ?? undefined,- quantity: tl.quantity ?? 1};}),- [tools, allTools]+ [materials, allItems]);+ const [draftParts, setDraftParts] = useState<string[]>([]);+ // Per-step share of each buffered part's BOM line (absent = the full line+ // quantity), keyed by methodMaterial id; written with the links on step create.+ const [draftPartQuantities, setDraftPartQuantities] = useState<+ Record<string, number>+ >({});++ // Tools the operator can assign to a step — the tool twin of operationParts/+ // draftParts. The whole tool LIBRARY is offered (keyed by tool item id); the+ // operation tool row is created server-side on attach when it doesn't exist+ // yet. Tools picked while CREATING a step are buffered here and attached+ // right after the step is created (see the effect below).+ const allTools = useTools();+ const operationTools = useMemo(() => {+ const opToolByToolId = new Map(+ (tools ?? []).flatMap((tl) =>+ tl.toolId ? [[tl.toolId, tl] as const] : []+ )+ );+ return allTools.map((tool) => ({+ id: tool.id,+ name: tool.readableIdWithRevision,+ secondary: tool.name ?? undefined,+ quantity: opToolByToolId.get(tool.id)?.quantity ?? 1,+ primary: opToolByToolId.has(tool.id)+ }));+ }, [tools, allTools]);const [draftTools, setDraftTools] = useState<string[]>([]);const onUploadImage = async (file: File) => {@@ -2118,10 +2132,15 @@ function AttributesForm({if (!newStepId || draftParts.length === 0 || !carbon) return;let cancelled = false;(async () => {+ // Omit the quantity column when unset so the default path still works+ // against a pre-migration schema (the column only ships on main).const { error } = await carbon.from("methodMaterialStep").insert(draftParts.map((methodMaterialId) => ({methodMaterialId,- methodOperationStepId: newStepId+ methodOperationStepId: newStepId,+ ...(draftPartQuantities[methodMaterialId] != null+ ? { quantity: draftPartQuantities[methodMaterialId] }+ : {})})));if (cancelled) return;@@ -2130,6 +2149,7 @@ function AttributesForm({return;}setDraftParts([]);+ setDraftPartQuantities({});revalidator.revalidate();})();return () => {@@ -2138,20 +2158,29 @@ function AttributesForm({}, [fetcher.data]);// When the new step is created, attach any buffered tools, then revalidate + reset.+ // Goes through the step-tool route (not a direct insert) because the buffer holds+ // tool ITEM ids and the operation tool row may not exist yet — the route creates+ // it before linking. Sequential so a repeated tool never races its own creation.// biome-ignore lint/correctness/useExhaustiveDependencies: keyed off the created step iduseEffect(() => {const newStepId = (fetcher.data as { id?: string | null } | undefined)?.id;if (!newStepId || draftTools.length === 0 || !carbon) return;let cancelled = false;(async () => {- const { error } = await carbon.from("methodOperationToolStep").insert(- draftTools.map((methodOperationToolId) => ({- methodOperationToolId,- methodOperationStepId: newStepId- }))- );+ let failed = false;+ for (const toolId of draftTools) {+ const fd = new FormData();+ fd.append("toolId", toolId);+ fd.append("stepId", newStepId);+ fd.append("linked", "true");+ const res = await fetch(path.to.methodOperationStepTool, {+ method: "POST",+ body: fd+ });+ if (!res.ok) failed = true;+ }if (cancelled) return;- if (error) {+ if (failed) {toast.error(t`Failed to save tools`);return;}@@ -2332,7 +2361,10 @@ function AttributesForm({emptyLabel={t`No parts`}searchPlaceholder={t`Search parts...`}removeLabel={t`Remove part`}- items={operationParts}+ items={operationParts.map((p) => ({+ ...p,+ linkedQuantity: draftPartQuantities[p.id] ?? null+ }))}linkedIds={draftParts}isDisabled={isDisabled}onAdd={(partId) =>@@ -2340,8 +2372,18 @@ function AttributesForm({prev.includes(partId) ? prev : [...prev, partId])}- onRemove={(partId) =>- setDraftParts((prev) => prev.filter((id) => id !== partId))+ onRemove={(partId) => {+ setDraftParts((prev) => prev.filter((id) => id !== partId));+ setDraftPartQuantities((prev) => {+ const { [partId]: _removed, ...rest } = prev;+ return rest;+ });+ }}+ onQuantityChange={(partId, quantity) =>+ setDraftPartQuantities((prev) => ({+ ...prev,+ [partId]: quantity+ }))}/>@@ -2354,6 +2396,8 @@ function AttributesForm({icon={<LuHammer />}items={operationTools}linkedIds={draftTools}+ primaryGroupLabel={t`On this operation`}+ secondaryGroupLabel={t`All tools`}isDisabled={isDisabled}onAdd={(toolId) =>setDraftTools((prev) =>@@ -2711,7 +2755,6 @@ function AttributesListItem({<StepSlides step={attribute} isDisabled={isDisabled} /><StepPartsstep={attribute}- operationId={operationId}materials={materials}isDisabled={isDisabled}/>@@ -2893,30 +2936,36 @@ function AttributesListItem({);}-// Parts assigned to an EXISTING step — the step-side of the part↔step link. Lists this-// operation's BOM parts and toggles each link immediately via the material route. Replaces-// the old BOM "Steps" dropdown (assignment now lives on the step).+// Parts assigned to an EXISTING step — the step-side of the part↔step link. Lists the+// method's whole bill of material (the BOM is the source of truth; a line needn't be+// assigned to this operation) and toggles each link immediately via the material route.+// Replaces the old BOM "Steps" dropdown (assignment now lives on the step).function StepParts({step,- operationId,materials,isDisabled}: {step: OperationStep;- operationId: string;materials: MethodMaterialType[];isDisabled: boolean;}) {const { t } = useLingui();const fetcher = useFetcher();+ const [allItems] = useItems();- const operationParts = (materials ?? [])- .filter((m) => m.methodOperationId === operationId)- .map((m) => ({+ const operationParts = (materials ?? []).map((m) => {+ const item = allItems.find((i) => i.id === m.itemId);+ const link = (m.methodMaterialStep ?? []).find(+ (s) => s.methodOperationStepId === step.id+ );+ return {id: m.id,- name: m.description || m.itemId,- quantity: m.quantity ?? 1- }));+ name: item?.readableIdWithRevision ?? m.description ?? m.itemId,+ secondary: item ? (m.description ?? item.name ?? undefined) : undefined,+ quantity: m.quantity ?? 1,+ linkedQuantity: link?.quantity ?? null+ };+ });const linkedPartIds = (materials ?? []).filter((m) =>@@ -2926,12 +2975,15 @@ function StepParts({).map((m) => m.id);- const toggle = (partId: string, linked: boolean) => {+ const toggle = (partId: string, linked: boolean, quantity?: number) => {if (!step.id) return;const fd = new FormData();fd.append("materialId", partId);fd.append("stepId", step.id);fd.append("linked", String(linked));+ if (linked && quantity !== undefined) {+ fd.append("quantity", String(quantity));+ }fetcher.submit(fd, {method: "post",action: path.to.methodOperationStepMaterial@@ -2951,6 +3003,7 @@ function StepParts({busy={fetcher.state !== "idle"}onAdd={(id) => toggle(id, true)}onRemove={(id) => toggle(id, false)}+ onQuantityChange={(id, quantity) => toggle(id, true, quantity)}/>);}@@ -2971,15 +3024,19 @@ function StepTools({const fetcher = useFetcher();const allTools = useTools();- const operationTools = (tools ?? []).map((tl) => {- const tool = allTools.find((x) => x.id === tl.toolId);- return {- id: tl.id ?? "",- name: tool?.readableIdWithRevision ?? tl.toolId ?? "",- secondary: tool?.name ?? undefined,- quantity: tl.quantity ?? 1- };- });+ // The whole tool LIBRARY is offered (keyed by tool item id) — an operation+ // needn't have a tool on its Tools tab first; picking one here creates the+ // operation tool row (quantity 1) server-side before linking it to the step.+ const opToolByToolId = new Map(+ (tools ?? []).flatMap((tl) => (tl.toolId ? [[tl.toolId, tl] as const] : []))+ );+ const stepTools = allTools.map((tool) => ({+ id: tool.id,+ name: tool.readableIdWithRevision,+ secondary: tool.name ?? undefined,+ quantity: opToolByToolId.get(tool.id)?.quantity ?? 1,+ primary: opToolByToolId.has(tool.id)+ }));const linkedToolIds = (tools ?? []).filter((tl) =>@@ -2994,7 +3051,7 @@ function StepTools({).map((s) => s.methodOperationStepId)).some((stepId) => stepId === step.id))- .map((tl) => tl.id ?? "");+ .flatMap((tl) => (tl.toolId ? [tl.toolId] : []));const toggle = (toolId: string, linked: boolean) => {if (!step.id) return;@@ -3016,7 +3073,9 @@ function StepTools({searchPlaceholder={t`Search tools...`}removeLabel={t`Remove tool`}icon={<LuHammer />}- items={operationTools}+ items={stepTools}+ primaryGroupLabel={t`On this operation`}+ secondaryGroupLabel={t`All tools`}linkedIds={linkedToolIds}isDisabled={isDisabled}busy={fetcher.state !== "idle"}diff --git a/apps/erp/app/modules/production/production.service.test.ts b/apps/erp/app/modules/production/production.service.test.tsindex afebcd8eed..ee977b47c5 100644--- a/apps/erp/app/modules/production/production.service.test.ts+++ b/apps/erp/app/modules/production/production.service.test.ts@@ -234,7 +234,7 @@ describe("duplicateJobOperationStep", () => {{ jobOperationToolId: "tool-1", jobOperationStepId: "step-1" }],jobMaterialStep: [- { jobMaterialId: "mat-1", jobOperationStepId: "step-1" }+ { jobMaterialId: "mat-1", jobOperationStepId: "step-1", quantity: 5 }]};}@@ -276,7 +276,7 @@ describe("duplicateJobOperationStep", () => {{ jobOperationToolId: "tool-1", jobOperationStepId: "step-new" }]);expect(inserts.find((i) => i.table === "jobMaterialStep")?.rows).toEqual([- { jobMaterialId: "mat-1", jobOperationStepId: "step-new" }+ { jobMaterialId: "mat-1", jobOperationStepId: "step-new", quantity: 5 }]);});diff --git a/apps/erp/app/modules/production/production.service.ts b/apps/erp/app/modules/production/production.service.tsindex 6213f48619..7d7dafb63a 100644--- a/apps/erp/app/modules/production/production.service.ts+++ b/apps/erp/app/modules/production/production.service.ts@@ -1528,15 +1528,39 @@ export async function getJobMaterial(.single();}+// The step-link `quantity` column ships with this branch's migration, which only+// runs on main — previews (and the prod window between app deploy and migration)+// run this code against the pre-migration schema. PostgREST fails the WHOLE+// select on an unknown embedded column, so fall back to the quantity-less query+// instead of rendering an empty BOM. 42703 = Postgres undefined_column; PGRST204+// = PostgREST's schema-cache miss for a written column.+function isMissingQuantityColumn(+ error: { code?: string; message?: string } | null+) {+ return error?.code === "42703" || error?.code === "PGRST204";+}+export async function getJobMaterialsByMethodId(client: SupabaseClient<Database>,jobMakeMethodId: string) {- return client+ const result = await client.from("jobMaterial")- .select("*, item(replenishmentSystem), jobMaterialStep(jobOperationStepId)")+ .select(+ "*, item(replenishmentSystem), jobMaterialStep(jobOperationStepId, quantity)"+ ).eq("jobMakeMethodId", jobMakeMethodId).order("order", { ascending: true });+ if (isMissingQuantityColumn(result.error)) {+ return (await client+ .from("jobMaterial")+ .select(+ "*, item(replenishmentSystem), jobMaterialStep(jobOperationStepId)"+ )+ .eq("jobMakeMethodId", jobMakeMethodId)+ .order("order", { ascending: true })) as unknown as typeof result;+ }+ return result;}export async function getJobOperation(@@ -3392,10 +3416,17 @@ export async function duplicateJobOperationStep(}// Copy step-scoped part/material links (same operation-level-vs-scoped semantics as tools).- const materialLinks = await client+ // Pre-migration schema: no quantity column — copy the bare links instead.+ let materialLinks = await client.from("jobMaterialStep")- .select("jobMaterialId")+ .select("jobMaterialId, quantity").eq("jobOperationStepId", args.id);+ if (isMissingQuantityColumn(materialLinks.error)) {+ materialLinks = (await client+ .from("jobMaterialStep")+ .select("jobMaterialId")+ .eq("jobOperationStepId", args.id)) as unknown as typeof materialLinks;+ }if (materialLinks.error) {return { data: null, error: materialLinks.error };}@@ -3403,7 +3434,8 @@ export async function duplicateJobOperationStep(const materialLinkInsert = await client.from("jobMaterialStep").insert(materialLinks.data.map((l) => ({jobMaterialId: l.jobMaterialId,- jobOperationStepId: newStepId+ jobOperationStepId: newStepId,+ ...(l.quantity != null ? { quantity: l.quantity } : {})})));if (materialLinkInsert.error) {@@ -3512,36 +3544,66 @@ export async function replaceJobMaterialSteps(jobMaterialId: string,jobOperationStepIds: string[]) {+ // Per-step quantities are edited from the step side; a BOM-side rewrite of the+ // step set must not wipe them, so carry each retained step's quantity across+ // the delete-then-insert. Pre-migration schema: quantities don't exist, so+ // fall back to the bare link set.+ let quantityByStepId = new Map<string, number | null>();+ const existing = await client+ .from("jobMaterialStep")+ .select("jobOperationStepId, quantity")+ .eq("jobMaterialId", jobMaterialId);+ if (existing.error && !isMissingQuantityColumn(existing.error)) {+ return existing;+ }+ if (!existing.error) {+ quantityByStepId = new Map(+ (existing.data ?? []).map((l) => [l.jobOperationStepId, l.quantity])+ );+ }const del = await client.from("jobMaterialStep").delete().eq("jobMaterialId", jobMaterialId);if (del.error || jobOperationStepIds.length === 0) return del;return client.from("jobMaterialStep").insert(- jobOperationStepIds.map((jobOperationStepId) => ({- jobMaterialId,- jobOperationStepId- }))+ jobOperationStepIds.map((jobOperationStepId) => {+ const quantity = quantityByStepId.get(jobOperationStepId);+ return {+ jobMaterialId,+ jobOperationStepId,+ ...(quantity != null ? { quantity } : {})+ };+ }));}// Toggle a single part↔step link from the STEP side (the step editor's Parts picker).// `linked` true = link the material to the step, false = unlink. Idempotent on link.+// `quantity` is the per-step share of the BOM line (NULL = the full line quantity);+// re-linking an existing link updates the quantity, so the same call edits a split.export async function setJobMaterialStepLink(client: SupabaseClient<Database>,- args: { jobMaterialId: string; jobOperationStepId: string; linked: boolean }+ args: {+ jobMaterialId: string;+ jobOperationStepId: string;+ linked: boolean;+ quantity?: number | null;+ }) {if (args.linked) {return client.from("jobMaterialStep").upsert([{jobMaterialId: args.jobMaterialId,- jobOperationStepId: args.jobOperationStepId+ jobOperationStepId: args.jobOperationStepId,+ // Omit the column when unset so the default link path still works+ // against a pre-migration schema (see isMissingQuantityColumn).+ ...(args.quantity != null ? { quantity: args.quantity } : {})}],{- onConflict: "jobMaterialId,jobOperationStepId",- ignoreDuplicates: true+ onConflict: "jobMaterialId,jobOperationStepId"});}@@ -3553,21 +3615,53 @@ export async function setJobMaterialStepLink(}// Toggle a single tool↔step link from the STEP side (the step editor's Tools picker).-// `linked` true = link the tool to the step, false = unlink. Idempotent on link. Twin of-// setJobMaterialStepLink.+// Takes the tool ITEM id: the picker offers the whole tool library, and choosing a+// tool implicitly ensures the operation-level tool row exists (quantity 1 — the same+// row the operation's Tools tab would create) before linking it to the step. Unlink+// removes only the step link; the operation tool row stays (the Tools tab owns it).+// Twin of setJobMaterialStepLink.export async function setJobOperationToolStepLink(client: SupabaseClient<Database>,args: {- jobOperationToolId: string;+ operationId: string;+ toolId: string;jobOperationStepId: string;linked: boolean;+ companyId: string;+ createdBy: string;}) {+ const existingTool = await client+ .from("jobOperationTool")+ .select("id")+ .eq("operationId", args.operationId)+ .eq("toolId", args.toolId)+ .order("createdAt", { ascending: true })+ .limit(1)+ .maybeSingle();+ if (existingTool.error) return existingTool;+ let jobOperationToolId = existingTool.data?.id;+if (args.linked) {+ if (!jobOperationToolId) {+ const created = await client+ .from("jobOperationTool")+ .insert({+ operationId: args.operationId,+ toolId: args.toolId,+ quantity: 1,+ companyId: args.companyId,+ createdBy: args.createdBy+ })+ .select("id")+ .single();+ if (created.error) return created;+ jobOperationToolId = created.data.id;+ }return client.from("jobOperationToolStep").upsert([{- jobOperationToolId: args.jobOperationToolId,+ jobOperationToolId,jobOperationStepId: args.jobOperationStepId}],@@ -3577,10 +3671,11 @@ export async function setJobOperationToolStepLink(});}+ if (!jobOperationToolId) return { data: null, error: null };return client.from("jobOperationToolStep").delete()- .eq("jobOperationToolId", args.jobOperationToolId)+ .eq("jobOperationToolId", jobOperationToolId).eq("jobOperationStepId", args.jobOperationStepId);}@@ -6327,7 +6422,7 @@ export async function syncAssemblyInstructionToOperation(const sourceMaterials = await trx.selectFrom("assemblyInstructionStepMaterial")- .select(["stepId", "itemId"])+ .select(["stepId", "itemId", "quantity"]).where("companyId", "=", companyId).where("stepId",@@ -6335,10 +6430,13 @@ export async function syncAssemblyInstructionToOperation(sourceSteps.map((step) => step.id)).execute();- const materialsByStep = new Map<string, string[]>();+ const materialsByStep = new Map<+ string,+ { itemId: string; quantity: number | null }[]+ >();for (const material of sourceMaterials) {const list = materialsByStep.get(material.stepId) ?? [];- list.push(material.itemId);+ list.push({ itemId: material.itemId, quantity: material.quantity });materialsByStep.set(material.stepId, list);}@@ -6422,7 +6520,11 @@ export async function syncAssemblyInstructionToOperation(const syncedTargetIds: string[] = [];// source assembly step id → synced job step id, for slide/tool copyingconst targetIdBySource = new Map<string, string>();- const linkPairs: { materialId: string; stepId: string }[] = [];+ const linkPairs: {+ materialId: string;+ stepId: string;+ quantity: number | null;+ }[] = [];let partsUnmatched = 0;for (const [index, source] of sourceSteps.entries()) {@@ -6472,10 +6574,10 @@ export async function syncAssemblyInstructionToOperation(syncedTargetIds.push(targetStepId);targetIdBySource.set(source.id, targetStepId);- for (const itemId of materialsByStep.get(source.id) ?? []) {+ for (const { itemId, quantity } of materialsByStep.get(source.id) ?? []) {const materialId = materialIdByItemId.get(itemId);if (materialId) {- linkPairs.push({ materialId, stepId: targetStepId });+ linkPairs.push({ materialId, stepId: targetStepId, quantity });} else {partsUnmatched++;}@@ -6503,7 +6605,8 @@ export async function syncAssemblyInstructionToOperation(.values(linkPairs.map((pair) => ({jobMaterialId: pair.materialId,- jobOperationStepId: pair.stepId+ jobOperationStepId: pair.stepId,+ quantity: pair.quantity}))).execute();diff --git a/apps/erp/app/modules/production/ui/Jobs/JobBillOfMaterial.tsx b/apps/erp/app/modules/production/ui/Jobs/JobBillOfMaterial.tsxindex d24e19440b..4df0219fea 100644--- a/apps/erp/app/modules/production/ui/Jobs/JobBillOfMaterial.tsx+++ b/apps/erp/app/modules/production/ui/Jobs/JobBillOfMaterial.tsx@@ -18,7 +18,6 @@ import {HStack,IconButton,Label,- ScrollArea,Tooltip,TooltipContent,TooltipTrigger,@@ -571,15 +570,13 @@ const JobBillOfMaterial = ({</CardAction></HStack><CardContent>- <ScrollArea type="auto" className="max-h-[60dvh]">- <SortableList- items={items}- onReorder={onReorder}- onToggleItem={onToggleItem}- onRemoveItem={onRemoveItem}- renderItem={renderListItem}- />- </ScrollArea>+ <SortableList+ items={items}+ onReorder={onReorder}+ onToggleItem={onToggleItem}+ onRemoveItem={onRemoveItem}+ renderItem={renderListItem}+ /></CardContent></Card>);diff --git a/apps/erp/app/modules/production/ui/Jobs/JobBillOfProcess.tsx b/apps/erp/app/modules/production/ui/Jobs/JobBillOfProcess.tsxindex f3140b75cf..d6b0416253 100644--- a/apps/erp/app/modules/production/ui/Jobs/JobBillOfProcess.tsx+++ b/apps/erp/app/modules/production/ui/Jobs/JobBillOfProcess.tsx@@ -200,7 +200,9 @@ type JobMaterial = {description?: string | null;quantity?: number | null;jobOperationId?: string | null;- jobMaterialStep?: { jobOperationStepId: string }[] | null;+ jobMaterialStep?:+ | { jobOperationStepId: string; quantity?: number | null }[]+ | null;};type JobBillOfProcessProps = {@@ -1073,15 +1075,13 @@ const JobBillOfProcess = ({</CardAction></HStack><CardContent>- <ScrollArea type="auto" className="max-h-[60dvh]">- <SortableList- items={items}- onReorder={onReorder}- onToggleItem={onToggleItem}- onRemoveItem={onRemoveItem}- renderItem={renderListItem}- />- </ScrollArea>+ <SortableList+ items={items}+ onReorder={onReorder}+ onToggleItem={onToggleItem}+ onRemoveItem={onRemoveItem}+ renderItem={renderListItem}+ /></CardContent></Card>);@@ -1193,38 +1193,52 @@ function StepsForm({const draftFileInputRef = useRef<HTMLInputElement>(null);const draftModelInputRef = useRef<HTMLInputElement>(null);- // Parts (this operation's BOM materials) the operator can assign to a step. Parts picked- // while CREATING a step are buffered here and attached right after the step is created.+ // Parts the operator can assign to a step. The whole bill of material is offered —+ // the BOM is the source of truth, and a line needn't be assigned to this operation+ // to be referenced by a step. Parts picked while CREATING a step are buffered here+ // and attached right after the step is created.const operationParts = useMemo(() =>- (materials ?? [])- .filter((m) => m.jobOperationId === operationId)- .map((m) => ({+ (materials ?? []).map((m) => {+ const item = allItems.find((i) => i.id === m.itemId);+ return {id: m.id,- name: m.description || m.itemId,+ name: item?.readableIdWithRevision ?? m.description ?? m.itemId,+ secondary: item+ ? (m.description ?? item.name ?? undefined)+ : undefined,quantity: m.quantity ?? 1- })),- [materials, operationId]- );- const [draftParts, setDraftParts] = useState<string[]>([]);-- // Tools (this operation's tools) the operator can assign to a step — the tool twin of- // operationParts/draftParts. Tools picked while CREATING a step are buffered here and- // attached right after the step is created (see the effect below).- const allTools = useTools();- const operationTools = useMemo(- () =>- (tools ?? []).map((tl) => {- const tool = allTools.find((x) => x.id === tl.toolId);- return {- id: tl.id ?? "",- name: tool?.readableIdWithRevision ?? tl.toolId ?? "",- secondary: tool?.name ?? undefined,- quantity: tl.quantity ?? 1};}),- [tools, allTools]+ [materials, allItems]);+ const [draftParts, setDraftParts] = useState<string[]>([]);+ // Per-step share of each buffered part's BOM line (absent = the full line+ // quantity), keyed by jobMaterial id; written with the links on step create.+ const [draftPartQuantities, setDraftPartQuantities] = useState<+ Record<string, number>+ >({});++ // Tools the operator can assign to a step — the tool twin of operationParts/+ // draftParts. The whole tool LIBRARY is offered (keyed by tool item id); the+ // operation tool row is created server-side on attach when it doesn't exist+ // yet. Tools picked while CREATING a step are buffered here and attached+ // right after the step is created (see the effect below).+ const allTools = useTools();+ const operationTools = useMemo(() => {+ const opToolByToolId = new Map(+ (tools ?? []).flatMap((tl) =>+ tl.toolId ? [[tl.toolId, tl] as const] : []+ )+ );+ return allTools.map((tool) => ({+ id: tool.id,+ name: tool.readableIdWithRevision,+ secondary: tool.name ?? undefined,+ quantity: opToolByToolId.get(tool.id)?.quantity ?? 1,+ primary: opToolByToolId.has(tool.id)+ }));+ }, [tools, allTools]);const [draftTools, setDraftTools] = useState<string[]>([]);const materialItemIds = useMemo(@@ -1368,10 +1382,15 @@ function StepsForm({let cancelled = false;const batch = draftParts;(async () => {+ // Omit the quantity column when unset so the default path still works+ // against a pre-migration schema (the column only ships on main).const { error } = await carbon.from("jobMaterialStep").insert(batch.map((jobMaterialId) => ({jobMaterialId,- jobOperationStepId: newStepId+ jobOperationStepId: newStepId,+ ...(draftPartQuantities[jobMaterialId] != null+ ? { quantity: draftPartQuantities[jobMaterialId] }+ : {})})));if (cancelled) return;@@ -1381,6 +1400,7 @@ function StepsForm({}const savedIds = new Set(batch);setDraftParts((prev) => prev.filter((id) => !savedIds.has(id)));+ setDraftPartQuantities({});revalidator.revalidate();})();return () => {@@ -1389,6 +1409,9 @@ function StepsForm({}, [fetcher.data]);// When the new step is created, attach any buffered tools, then revalidate + reset.+ // Goes through the step-tool route (not a direct insert) because the buffer holds+ // tool ITEM ids and the operation tool row may not exist yet — the route creates+ // it before linking. Sequential so a repeated tool never races its own creation.// biome-ignore lint/correctness/useExhaustiveDependencies: keyed off the created step iduseEffect(() => {const newStepId = (fetcher.data as { id?: string | null } | undefined)?.id;@@ -1396,14 +1419,20 @@ function StepsForm({let cancelled = false;const batch = draftTools;(async () => {- const { error } = await carbon.from("jobOperationToolStep").insert(- batch.map((jobOperationToolId) => ({- jobOperationToolId,- jobOperationStepId: newStepId- }))- );+ let failed = false;+ for (const toolId of batch) {+ const fd = new FormData();+ fd.append("toolId", toolId);+ fd.append("stepId", newStepId);+ fd.append("linked", "true");+ const res = await fetch(path.to.jobOperationStepTool, {+ method: "POST",+ body: fd+ });+ if (!res.ok) failed = true;+ }if (cancelled) return;- if (error) {+ if (failed) {toast.error(t`Failed to save tools`);return;}@@ -1591,7 +1620,10 @@ function StepsForm({emptyLabel={t`No parts`}searchPlaceholder={t`Search parts...`}removeLabel={t`Remove part`}- items={operationParts}+ items={operationParts.map((p) => ({+ ...p,+ linkedQuantity: draftPartQuantities[p.id] ?? null+ }))}linkedIds={draftParts}isDisabled={isDisabled}onAdd={(partId) =>@@ -1599,8 +1631,18 @@ function StepsForm({prev.includes(partId) ? prev : [...prev, partId])}- onRemove={(partId) =>- setDraftParts((prev) => prev.filter((id) => id !== partId))+ onRemove={(partId) => {+ setDraftParts((prev) => prev.filter((id) => id !== partId));+ setDraftPartQuantities((prev) => {+ const { [partId]: _removed, ...rest } = prev;+ return rest;+ });+ }}+ onQuantityChange={(partId, quantity) =>+ setDraftPartQuantities((prev) => ({+ ...prev,+ [partId]: quantity+ }))}/>@@ -1613,6 +1655,8 @@ function StepsForm({icon={<LuHammer />}items={operationTools}linkedIds={draftTools}+ primaryGroupLabel={t`On this operation`}+ secondaryGroupLabel={t`All tools`}isDisabled={isDisabled}onAdd={(toolId) =>setDraftTools((prev) =>@@ -1689,27 +1733,34 @@ function StepsForm({// Parts assigned to an EXISTING job step — the step-side of the part↔step link. Toggles each// jobMaterialStep link immediately via the material route. Job-tier twin of StepParts.+// Lists the method's whole bill of material — the BOM is the source of truth, and a+// line needn't be assigned to this operation to be referenced by a step.function JobStepParts({step,- operationId,materials,isDisabled}: {step: JobOperationStep;- operationId: string;materials: JobMaterial[];isDisabled: boolean;}) {const { t } = useLingui();const fetcher = useFetcher();+ const [allItems] = useItems();- const operationParts = (materials ?? [])- .filter((m) => m.jobOperationId === operationId)- .map((m) => ({+ const operationParts = (materials ?? []).map((m) => {+ const item = allItems.find((i) => i.id === m.itemId);+ const link = (m.jobMaterialStep ?? []).find(+ (s) => s.jobOperationStepId === step.id+ );+ return {id: m.id,- name: m.description || m.itemId,- quantity: m.quantity ?? 1- }));+ name: item?.readableIdWithRevision ?? m.description ?? m.itemId,+ secondary: item ? (m.description ?? item.name ?? undefined) : undefined,+ quantity: m.quantity ?? 1,+ linkedQuantity: link?.quantity ?? null+ };+ });const linkedPartIds = (materials ?? []).filter((m) =>@@ -1717,12 +1768,15 @@ function JobStepParts({).map((m) => m.id);- const toggle = (partId: string, linked: boolean) => {+ const toggle = (partId: string, linked: boolean, quantity?: number) => {if (!step.id) return;const fd = new FormData();fd.append("materialId", partId);fd.append("stepId", step.id);fd.append("linked", String(linked));+ if (linked && quantity !== undefined) {+ fd.append("quantity", String(quantity));+ }fetcher.submit(fd, {method: "post",action: path.to.jobOperationStepMaterial@@ -1742,6 +1796,7 @@ function JobStepParts({busy={fetcher.state !== "idle"}onAdd={(id) => toggle(id, true)}onRemove={(id) => toggle(id, false)}+ onQuantityChange={(id, quantity) => toggle(id, true, quantity)}/>);}@@ -1761,15 +1816,19 @@ function JobStepTools({const fetcher = useFetcher();const allTools = useTools();- const operationTools = (tools ?? []).map((tl) => {- const tool = allTools.find((x) => x.id === tl.toolId);- return {- id: tl.id ?? "",- name: tool?.readableIdWithRevision ?? tl.toolId ?? "",- secondary: tool?.name ?? undefined,- quantity: tl.quantity ?? 1- };- });+ // The whole tool LIBRARY is offered (keyed by tool item id) — an operation+ // needn't have a tool on its Tools tab first; picking one here creates the+ // operation tool row (quantity 1) server-side before linking it to the step.+ const opToolByToolId = new Map(+ (tools ?? []).flatMap((tl) => (tl.toolId ? [[tl.toolId, tl] as const] : []))+ );+ const stepTools = allTools.map((tool) => ({+ id: tool.id,+ name: tool.readableIdWithRevision,+ secondary: tool.name ?? undefined,+ quantity: opToolByToolId.get(tool.id)?.quantity ?? 1,+ primary: opToolByToolId.has(tool.id)+ }));const linkedToolIds = (tools ?? []).filter((tl) =>@@ -1781,7 +1840,7 @@ function JobStepTools({).map((s) => s.jobOperationStepId)).some((stepId) => stepId === step.id))- .map((tl) => tl.id ?? "");+ .flatMap((tl) => (tl.toolId ? [tl.toolId] : []));const toggle = (toolId: string, linked: boolean) => {if (!step.id) return;@@ -1803,7 +1862,9 @@ function JobStepTools({searchPlaceholder={t`Search tools...`}removeLabel={t`Remove tool`}icon={<LuHammer />}- items={operationTools}+ items={stepTools}+ primaryGroupLabel={t`On this operation`}+ secondaryGroupLabel={t`All tools`}linkedIds={linkedToolIds}isDisabled={isDisabled}busy={fetcher.state !== "idle"}@@ -2183,7 +2244,6 @@ function StepsListItem({<JobStepSlides step={attribute} isDisabled={isDisabled} /><JobStepPartsstep={attribute}- operationId={operationId}materials={materials}isDisabled={isDisabled}/>diff --git a/apps/erp/app/modules/sales/ui/Quotes/QuoteBillOfMaterial.tsx b/apps/erp/app/modules/sales/ui/Quotes/QuoteBillOfMaterial.tsxindex 07d41a992b..e63cd6fd64 100644--- a/apps/erp/app/modules/sales/ui/Quotes/QuoteBillOfMaterial.tsx+++ b/apps/erp/app/modules/sales/ui/Quotes/QuoteBillOfMaterial.tsx@@ -19,7 +19,6 @@ import {HStack,IconButton,Label,- ScrollArea,Tooltip,TooltipContent,TooltipTrigger,@@ -548,15 +547,13 @@ const QuoteBillOfMaterial = ({</CardAction></HStack><CardContent>- <ScrollArea type="auto" className="max-h-[60dvh]">- <SortableList- items={items}- onReorder={onReorder}- onToggleItem={onToggleItem}- onRemoveItem={onRemoveItem}- renderItem={renderListItem}- />- </ScrollArea>+ <SortableList+ items={items}+ onReorder={onReorder}+ onToggleItem={onToggleItem}+ onRemoveItem={onRemoveItem}+ renderItem={renderListItem}+ /></CardContent></Card>);diff --git a/apps/erp/app/modules/sales/ui/Quotes/QuoteBillOfProcess.tsx b/apps/erp/app/modules/sales/ui/Quotes/QuoteBillOfProcess.tsxindex 3fb16647cf..85d45004f0 100644--- a/apps/erp/app/modules/sales/ui/Quotes/QuoteBillOfProcess.tsx+++ b/apps/erp/app/modules/sales/ui/Quotes/QuoteBillOfProcess.tsx@@ -24,7 +24,6 @@ import {IconButton,Label,Loading,- ScrollArea,ToggleGroup,ToggleGroupItem,Tooltip,@@ -833,15 +832,13 @@ const QuoteBillOfProcess = ({</CardAction></HStack><CardContent>- <ScrollArea type="auto" className="max-h-[60dvh]">- <SortableList- items={items}- onReorder={onReorder}- onToggleItem={onToggleItem}- onRemoveItem={onRemoveItem}- renderItem={renderListItem}- />- </ScrollArea>+ <SortableList+ items={items}+ onReorder={onReorder}+ onToggleItem={onToggleItem}+ onRemoveItem={onRemoveItem}+ renderItem={renderListItem}+ /></CardContent></Card>);diff --git a/apps/erp/app/routes/api+/mcp+/lib/tool-metadata.json b/apps/erp/app/routes/api+/mcp+/lib/tool-metadata.jsonindex d21b258952..79653b99e8 100644--- a/apps/erp/app/routes/api+/mcp+/lib/tool-metadata.json+++ b/apps/erp/app/routes/api+/mcp+/lib/tool-metadata.json@@ -15467,7 +15467,7 @@"module": "items","classification": "WRITE","description": "set method material step link",- "paramCount": 3,+ "paramCount": 4,"serviceParams": ["client","args"@@ -15487,6 +15487,12 @@},"linked": {"type": "boolean"+ },+ "quantity": {+ "type": [+ "number",+ "null"+ ]}},"required": [@@ -15501,7 +15507,7 @@"module": "items","classification": "WRITE","description": "set method operation tool step link",- "paramCount": 3,+ "paramCount": 4,"serviceParams": ["client","args"@@ -15513,7 +15519,10 @@"schema": {"type": "object","properties": {- "methodOperationToolId": {+ "operationId": {+ "type": "string"+ },+ "toolId": {"type": "string"},"methodOperationStepId": {@@ -15524,7 +15533,8 @@}},"required": [- "methodOperationToolId",+ "operationId",+ "toolId","methodOperationStepId","linked"]@@ -22353,7 +22363,7 @@"module": "production","classification": "WRITE","description": "set job material step link",- "paramCount": 3,+ "paramCount": 4,"serviceParams": ["client","args"@@ -22373,6 +22383,12 @@},"linked": {"type": "boolean"+ },+ "quantity": {+ "type": [+ "number",+ "null"+ ]}},"required": [@@ -22387,7 +22403,7 @@"module": "production","classification": "WRITE","description": "set job operation tool step link",- "paramCount": 3,+ "paramCount": 4,"serviceParams": ["client","args"@@ -22399,7 +22415,10 @@"schema": {"type": "object","properties": {- "jobOperationToolId": {+ "operationId": {+ "type": "string"+ },+ "toolId": {"type": "string"},"jobOperationStepId": {@@ -22410,7 +22429,8 @@}},"required": [- "jobOperationToolId",+ "operationId",+ "toolId","jobOperationStepId","linked"]diff --git a/apps/erp/app/routes/x+/items+/methods+/operation.step.material.tsx b/apps/erp/app/routes/x+/items+/methods+/operation.step.material.tsxindex ab60c6c2c3..65ed7cbe1b 100644--- a/apps/erp/app/routes/x+/items+/methods+/operation.step.material.tsx+++ b/apps/erp/app/routes/x+/items+/methods+/operation.step.material.tsx@@ -17,8 +17,19 @@ export async function action({ request }: ActionFunctionArgs) {const methodMaterialId = String(formData.get("materialId") ?? "");const methodOperationStepId = String(formData.get("stepId") ?? "");const linked = formData.get("linked") === "true";+ // Per-step share of the BOM line; absent/blank = the full line quantity.+ // Zero is refused — a step that uses none of a part should be unlinked.+ const rawQuantity = formData.get("quantity");+ const quantity =+ rawQuantity === null || String(rawQuantity).trim() === ""+ ? null+ : Number(rawQuantity);- if (!methodMaterialId || !methodOperationStepId) {+ if (+ !methodMaterialId ||+ !methodOperationStepId ||+ (quantity !== null && (!Number.isFinite(quantity) || quantity <= 0))+ ) {return data({ success: false }, { status: 400 });}@@ -32,10 +43,27 @@ export async function action({ request }: ActionFunctionArgs) {}await assertMethodOperationIsDraft(client, step.data.operationId);+ // A step's share can never exceed the BOM line quantity — the line is the+ // source of truth for what the method requires.+ if (linked && quantity !== null) {+ const material = await client+ .from("methodMaterial")+ .select("quantity")+ .eq("id", methodMaterialId)+ .single();+ if (material.error || !material.data) {+ return data({ success: false }, { status: 404 });+ }+ if (material.data.quantity !== null && quantity > material.data.quantity) {+ return data({ success: false }, { status: 400 });+ }+ }+const result = await setMethodMaterialStepLink(client, {methodMaterialId,methodOperationStepId,- linked+ linked,+ quantity});if (result.error) {return data(diff --git a/apps/erp/app/routes/x+/items+/methods+/operation.step.tool.tsx b/apps/erp/app/routes/x+/items+/methods+/operation.step.tool.tsxindex dfbe083ed0..9f8ccd7cb7 100644--- a/apps/erp/app/routes/x+/items+/methods+/operation.step.tool.tsx+++ b/apps/erp/app/routes/x+/items+/methods+/operation.step.tool.tsx@@ -9,16 +9,20 @@ import {} from "~/modules/items";// Toggle a tool↔step link from the step editor's "Tools" picker (method/item tier).+// `toolId` is the tool ITEM id — the picker offers the whole tool library, and the+// service ensures the operation-level tool row exists before linking.export async function action({ request }: ActionFunctionArgs) {assertIsPost(request);- const { client } = await requirePermissions(request, { update: "parts" });+ const { client, companyId, userId } = await requirePermissions(request, {+ update: "parts"+ });const formData = await request.formData();- const methodOperationToolId = String(formData.get("toolId") ?? "");+ const toolId = String(formData.get("toolId") ?? "");const methodOperationStepId = String(formData.get("stepId") ?? "");const linked = formData.get("linked") === "true";- if (!methodOperationToolId || !methodOperationStepId) {+ if (!toolId || !methodOperationStepId) {return data({ success: false }, { status: 400 });}@@ -33,9 +37,12 @@ export async function action({ request }: ActionFunctionArgs) {await assertMethodOperationIsDraft(client, step.data.operationId);const result = await setMethodOperationToolStepLink(client, {- methodOperationToolId,+ operationId: step.data.operationId,+ toolId,methodOperationStepId,- linked+ linked,+ companyId,+ createdBy: userId});if (result.error) {return data(diff --git a/apps/erp/app/routes/x+/job+/$jobId.details.tsx b/apps/erp/app/routes/x+/job+/$jobId.details.tsxindex 9955fb8166..6904d1e26c 100644--- a/apps/erp/app/routes/x+/job+/$jobId.details.tsx+++ b/apps/erp/app/routes/x+/job+/$jobId.details.tsx@@ -255,14 +255,6 @@ export default function JobDetailsRoute() {{methodId && (<>- <JobBillOfMaterial- key={`bom:${methodId}`}- jobMakeMethodId={methodId}- // @ts-ignore- materials={materials}- // @ts-ignore- operations={operations}- /><JobBillOfProcesskey={`bop:${methodId}`}jobMakeMethodId={methodId}@@ -276,6 +268,14 @@ export default function JobDetailsRoute() {salesOrderLineId={jobData?.job.salesOrderLineId ?? ""}customerId={jobData?.job.customerId ?? ""}/>+ <JobBillOfMaterial+ key={`bom:${methodId}`}+ jobMakeMethodId={methodId}+ // @ts-ignore+ materials={materials}+ // @ts-ignore+ operations={operations}+ /></>)}<Suspense>diff --git a/apps/erp/app/routes/x+/job+/$jobId.make.$methodId.tsx b/apps/erp/app/routes/x+/job+/$jobId.make.$methodId.tsxindex aa7839a28b..0a1cf492e1 100644--- a/apps/erp/app/routes/x+/job+/$jobId.make.$methodId.tsx+++ b/apps/erp/app/routes/x+/job+/$jobId.make.$methodId.tsx@@ -144,14 +144,6 @@ export default function JobMakeMethodRoute() {<VStack spacing={4} className="p-4"><JobMakeMethodTools makeMethod={makeMethod} />- <JobBillOfMaterial- key={`bom:${methodId}`}- jobMakeMethodId={methodId}- // @ts-expect-error TS2322 - TODO: fix type- materials={materials}- // @ts-expect-error- operations={operations}- /><JobBillOfProcesskey={`bop:${methodId}`}jobMakeMethodId={methodId}@@ -164,6 +156,14 @@ export default function JobMakeMethodRoute() {salesOrderLineId={job.salesOrderLineId ?? ""}customerId={job.customerId ?? ""}/>+ <JobBillOfMaterial+ key={`bom:${methodId}`}+ jobMakeMethodId={methodId}+ // @ts-expect-error TS2322 - TODO: fix type+ materials={materials}+ // @ts-expect-error+ operations={operations}+ /><Suspensefallback={<div className="flex w-full h-full rounded bg-gradient-to-tr from-background to-card items-center justify-center min-h-[200px]">diff --git a/apps/erp/app/routes/x+/job+/methods+/operation.step.material.tsx b/apps/erp/app/routes/x+/job+/methods+/operation.step.material.tsxindex c4231e7b10..eea3a1981c 100644--- a/apps/erp/app/routes/x+/job+/methods+/operation.step.material.tsx+++ b/apps/erp/app/routes/x+/job+/methods+/operation.step.material.tsx@@ -16,8 +16,19 @@ export async function action({ request }: ActionFunctionArgs) {const jobMaterialId = String(formData.get("materialId") ?? "");const jobOperationStepId = String(formData.get("stepId") ?? "");const linked = formData.get("linked") === "true";+ // Per-step share of the BOM line; absent/blank = the full line quantity.+ // Zero is refused — a step that uses none of a part should be unlinked.+ const rawQuantity = formData.get("quantity");+ const quantity =+ rawQuantity === null || String(rawQuantity).trim() === ""+ ? null+ : Number(rawQuantity);- if (!jobMaterialId || !jobOperationStepId) {+ if (+ !jobMaterialId ||+ !jobOperationStepId ||+ (quantity !== null && (!Number.isFinite(quantity) || quantity <= 0))+ ) {return data({ success: false }, { status: 400 });}@@ -34,10 +45,27 @@ export async function action({ request }: ActionFunctionArgs) {return data({ success: false }, { status: 404 });}+ // A step's share can never exceed the BOM line quantity — the line is the+ // source of truth for what the job requires.+ if (linked && quantity !== null) {+ const material = await client+ .from("jobMaterial")+ .select("quantity")+ .eq("id", jobMaterialId)+ .single();+ if (material.error || !material.data) {+ return data({ success: false }, { status: 404 });+ }+ if (material.data.quantity !== null && quantity > material.data.quantity) {+ return data({ success: false }, { status: 400 });+ }+ }+const result = await setJobMaterialStepLink(client, {jobMaterialId,jobOperationStepId,- linked+ linked,+ quantity});if (result.error) {return data(diff --git a/apps/erp/app/routes/x+/job+/methods+/operation.step.tool.tsx b/apps/erp/app/routes/x+/job+/methods+/operation.step.tool.tsxindex d58e1d1756..bcba45eeb7 100644--- a/apps/erp/app/routes/x+/job+/methods+/operation.step.tool.tsx+++ b/apps/erp/app/routes/x+/job+/methods+/operation.step.tool.tsx@@ -6,18 +6,20 @@ import { data } from "react-router";import { setJobOperationToolStepLink } from "~/modules/production";// Toggle a tool↔step link from the step editor's "Tools" picker (job tier).+// `toolId` is the tool ITEM id — the picker offers the whole tool library, and the+// service ensures the operation-level tool row exists before linking.export async function action({ request }: ActionFunctionArgs) {assertIsPost(request);- const { client } = await requirePermissions(request, {+ const { client, companyId, userId } = await requirePermissions(request, {update: "production"});const formData = await request.formData();- const jobOperationToolId = String(formData.get("toolId") ?? "");+ const toolId = String(formData.get("toolId") ?? "");const jobOperationStepId = String(formData.get("stepId") ?? "");const linked = formData.get("linked") === "true";- if (!jobOperationToolId || !jobOperationStepId) {+ if (!toolId || !jobOperationStepId) {return data({ success: false }, { status: 400 });}@@ -28,17 +30,20 @@ export async function action({ request }: ActionFunctionArgs) {// foreign step.const step = await client.from("jobOperationStep")- .select("id")+ .select("id, operationId").eq("id", jobOperationStepId).single();- if (step.error || !step.data) {+ if (step.error || !step.data?.operationId) {return data({ success: false }, { status: 404 });}const result = await setJobOperationToolStepLink(client, {- jobOperationToolId,+ operationId: step.data.operationId,+ toolId,jobOperationStepId,- linked+ linked,+ companyId,+ createdBy: userId});if (result.error) {return data(diff --git a/apps/erp/app/routes/x+/part+/$itemId.details.tsx b/apps/erp/app/routes/x+/part+/$itemId.details.tsxindex 981ee027e8..90422ae135 100644--- a/apps/erp/app/routes/x+/part+/$itemId.details.tsx+++ b/apps/erp/app/routes/x+/part+/$itemId.details.tsx@@ -342,41 +342,41 @@ export default function PartDetailsRoute() {partData.partSummary?.replenishmentSystem ?? "") && (<>- <BillOfMaterial- key={`bom:${itemId}`}+ <BillOfProcess+ key={`bop:${itemId}`}makeMethod={methodData.makeMethod}// @ts-ignore- materials={methodData.methodMaterials ?? []}- // @ts-ignore- operations={methodData.methodOperations}+ operations={methodData.methodOperations ?? []}configurable={methodData.partManufacturing?.requiresConfiguration}+ // @ts-ignore+ materials={methodData.methodMaterials ?? []}configurationRules={methodData.configurationRules}parameters={methodData.configurationParametersAndGroups.parameters}- replenishmentSystem={partData.partSummary?.replenishmentSystem}+ tags={tags}revisionStatus={revisionStatus}releaseControl={releaseControl}isDisabled={!!draftLock}disabledReason={lockReason}/>- <BillOfProcess- key={`bop:${itemId}`}+ <BillOfMaterial+ key={`bom:${itemId}`}makeMethod={methodData.makeMethod}// @ts-ignore- operations={methodData.methodOperations ?? []}+ materials={methodData.methodMaterials ?? []}+ // @ts-ignore+ operations={methodData.methodOperations}configurable={methodData.partManufacturing?.requiresConfiguration}- // @ts-ignore- materials={methodData.methodMaterials ?? []}configurationRules={methodData.configurationRules}parameters={methodData.configurationParametersAndGroups.parameters}- tags={tags}+ replenishmentSystem={partData.partSummary?.replenishmentSystem}revisionStatus={revisionStatus}releaseControl={releaseControl}isDisabled={!!draftLock}diff --git a/apps/erp/app/routes/x+/part+/$itemId.make.$makeMethodId.tsx b/apps/erp/app/routes/x+/part+/$itemId.make.$makeMethodId.tsxindex cb2731c1a6..dbc3c09f1c 100644--- a/apps/erp/app/routes/x+/part+/$itemId.make.$makeMethodId.tsx+++ b/apps/erp/app/routes/x+/part+/$itemId.make.$makeMethodId.tsx@@ -178,29 +178,29 @@ export default function PartMakeMethodPage() {</Await></Suspense>- <BillOfMaterial- key={`bom:${makeMethodId}`}+ <BillOfProcess+ key={`bop:${makeMethodId}`}makeMethod={makeMethod}- // @ts-expect-error TS2322 - TODO: fix typematerials={methodMaterials}+ // @ts-expect-erroroperations={methodOperations}configurable={partManufacturing?.requiresConfiguration}configurationRules={configurationRules}parameters={configurationParametersAndGroups.parameters}- replenishmentSystem={partData?.partSummary?.replenishmentSystem}+ tags={tags}revisionStatus={revisionStatus}releaseControl={releaseControl}/>- <BillOfProcess- key={`bop:${makeMethodId}`}+ <BillOfMaterial+ key={`bom:${makeMethodId}`}makeMethod={makeMethod}+ // @ts-expect-error TS2322 - TODO: fix typematerials={methodMaterials}- // @ts-expect-erroroperations={methodOperations}configurable={partManufacturing?.requiresConfiguration}configurationRules={configurationRules}parameters={configurationParametersAndGroups.parameters}- tags={tags}+ replenishmentSystem={partData?.partSummary?.replenishmentSystem}revisionStatus={revisionStatus}releaseControl={releaseControl}/>diff --git a/apps/erp/app/routes/x+/quote+/$quoteId.$lineId.details.tsx b/apps/erp/app/routes/x+/quote+/$quoteId.$lineId.details.tsxindex edd794814b..fd5ae535ed 100644--- a/apps/erp/app/routes/x+/quote+/$quoteId.$lineId.details.tsx+++ b/apps/erp/app/routes/x+/quote+/$quoteId.$lineId.details.tsx@@ -369,14 +369,6 @@ export default function QuoteLine() {{methodData && (<VStack spacing={2}>- <QuoteBillOfMaterial- key={`bom:${methodData.rootMethodId}`}- quoteMakeMethodId={methodData.rootMethodId}- // @ts-ignore- materials={methodData.methodMaterials}- // @ts-expect-error- operations={methodData.methodOperations}- /><QuoteBillOfProcesskey={`bop:${methodData.rootMethodId}`}quoteMakeMethodId={methodData.rootMethodId}@@ -385,6 +377,14 @@ export default function QuoteLine() {operations={methodData.methodOperations}tags={methodData.tags ?? []}/>+ <QuoteBillOfMaterial+ key={`bom:${methodData.rootMethodId}`}+ quoteMakeMethodId={methodData.rootMethodId}+ // @ts-ignore+ materials={methodData.methodMaterials}+ // @ts-expect-error+ operations={methodData.methodOperations}+ /></VStack>)}diff --git a/apps/erp/app/routes/x+/quote+/$quoteId.$lineId.make.$methodId.tsx b/apps/erp/app/routes/x+/quote+/$quoteId.$lineId.make.$methodId.tsxindex ba8604cc9f..57934bafe3 100644--- a/apps/erp/app/routes/x+/quote+/$quoteId.$lineId.make.$methodId.tsx+++ b/apps/erp/app/routes/x+/quote+/$quoteId.$lineId.make.$methodId.tsx@@ -111,13 +111,6 @@ export default function QuoteMakeMethodRoute() {<VStack spacing={2}><QuoteMakeMethodTools />- <QuoteBillOfMaterial- key={`bom:${methodId}`}- quoteMakeMethodId={methodId}- // @ts-expect-error TS2322 - TODO: fix type- materials={materials}- operations={operations}- /><QuoteBillOfProcesskey={`bop:${methodId}`}quoteMakeMethodId={methodId}@@ -127,6 +120,13 @@ export default function QuoteMakeMethodRoute() {operations={operations}tags={tags}/>+ <QuoteBillOfMaterial+ key={`bom:${methodId}`}+ quoteMakeMethodId={methodId}+ // @ts-expect-error TS2322 - TODO: fix type+ materials={materials}+ operations={operations}+ /><Suspense fallback={null}><Await resolve={loaderData.model}>{(model) => (diff --git a/apps/erp/app/routes/x+/service+/$itemId.details.tsx b/apps/erp/app/routes/x+/service+/$itemId.details.tsxindex ac453523c1..6e3eef2b2c 100644--- a/apps/erp/app/routes/x+/service+/$itemId.details.tsx+++ b/apps/erp/app/routes/x+/service+/$itemId.details.tsx@@ -169,6 +169,15 @@ export default function ServiceDetailsRoute() {/>{serviceData.serviceSummary?.replenishmentSystem === "Make" && (<>+ <BillOfProcess+ key={`bop:${itemId}`}+ makeMethod={methodData.makeMethod}+ // @ts-ignore+ operations={methodData.methodOperations ?? []}+ // @ts-ignore+ materials={methodData.methodMaterials ?? []}+ tags={tags}+ /><BillOfMaterialkey={`bom:${itemId}`}makeMethod={methodData.makeMethod}@@ -180,13 +189,6 @@ export default function ServiceDetailsRoute() {serviceData.serviceSummary?.replenishmentSystem}/>- <BillOfProcess- key={`bop:${itemId}`}- makeMethod={methodData.makeMethod}- // @ts-ignore- operations={methodData.methodOperations ?? []}- tags={tags}- /></>)}</>diff --git a/apps/erp/app/routes/x+/service+/$itemId.make.$makeMethodId.tsx b/apps/erp/app/routes/x+/service+/$itemId.make.$makeMethodId.tsxindex d81f992be3..2bee45e3db 100644--- a/apps/erp/app/routes/x+/service+/$itemId.make.$makeMethodId.tsx+++ b/apps/erp/app/routes/x+/service+/$itemId.make.$makeMethodId.tsx@@ -128,14 +128,6 @@ export default function ServiceMakeMethodPage() {</Await></Suspense>- <BillOfMaterial- key={`bom:${makeMethodId}`}- makeMethod={makeMethod}- // @ts-expect-error TS2322 - TODO: fix type- materials={methodMaterials}- operations={methodOperations}- replenishmentSystem={serviceData?.serviceSummary?.replenishmentSystem}- /><BillOfProcesskey={`bop:${makeMethodId}`}makeMethod={makeMethod}@@ -144,6 +136,14 @@ export default function ServiceMakeMethodPage() {operations={methodOperations}tags={tags}/>+ <BillOfMaterial+ key={`bom:${makeMethodId}`}+ makeMethod={makeMethod}+ // @ts-expect-error TS2322 - TODO: fix type+ materials={methodMaterials}+ operations={methodOperations}+ replenishmentSystem={serviceData?.serviceSummary?.replenishmentSystem}+ /></VStack>);}diff --git a/apps/erp/app/routes/x+/tool+/$itemId.details.tsx b/apps/erp/app/routes/x+/tool+/$itemId.details.tsxindex a57a699e70..f59d53a0c7 100644--- a/apps/erp/app/routes/x+/tool+/$itemId.details.tsx+++ b/apps/erp/app/routes/x+/tool+/$itemId.details.tsx@@ -297,25 +297,27 @@ export default function ToolDetailsRoute() {toolData.toolSummary?.replenishmentSystem ?? "") && (<>- <BillOfMaterial- key={`bom:${itemId}`}+ <BillOfProcess+ key={`bop:${itemId}`}makeMethod={methodData.makeMethod}// @ts-ignore- materials={methodData.methodMaterials ?? []}+ operations={methodData.methodOperations ?? []}// @ts-ignore- operations={methodData.methodOperations}- replenishmentSystem={toolData.toolSummary?.replenishmentSystem}+ materials={methodData.methodMaterials ?? []}+ tags={tags}revisionStatus={revisionStatus}releaseControl={releaseControl}isDisabled={!!draftLock}disabledReason={lockReason}/>- <BillOfProcess- key={`bop:${itemId}`}+ <BillOfMaterial+ key={`bom:${itemId}`}makeMethod={methodData.makeMethod}// @ts-ignore- operations={methodData.methodOperations ?? []}- tags={tags}+ materials={methodData.methodMaterials ?? []}+ // @ts-ignore+ operations={methodData.methodOperations}+ replenishmentSystem={toolData.toolSummary?.replenishmentSystem}revisionStatus={revisionStatus}releaseControl={releaseControl}isDisabled={!!draftLock}diff --git a/apps/erp/app/routes/x+/tool+/$itemId.make.$makeMethodId.tsx b/apps/erp/app/routes/x+/tool+/$itemId.make.$makeMethodId.tsxindex 41e4b64624..0d0281583a 100644--- a/apps/erp/app/routes/x+/tool+/$itemId.make.$makeMethodId.tsx+++ b/apps/erp/app/routes/x+/tool+/$itemId.make.$makeMethodId.tsx@@ -145,23 +145,23 @@ export default function ToolMakeMethodPage() {</Await></Suspense>- <BillOfMaterial- key={`bom:${makeMethodId}`}+ <BillOfProcess+ key={`bop:${makeMethodId}`}makeMethod={makeMethod}- // @ts-expect-error TS2322 - TODO: fix typematerials={methodMaterials}+ // @ts-expect-erroroperations={methodOperations}- replenishmentSystem={toolData?.toolSummary?.replenishmentSystem}+ tags={tags}revisionStatus={revisionStatus}releaseControl={releaseControl}/>- <BillOfProcess- key={`bop:${makeMethodId}`}+ <BillOfMaterial+ key={`bom:${makeMethodId}`}makeMethod={makeMethod}+ // @ts-expect-error TS2322 - TODO: fix typematerials={methodMaterials}- // @ts-expect-erroroperations={methodOperations}- tags={tags}+ replenishmentSystem={toolData?.toolSummary?.replenishmentSystem}revisionStatus={revisionStatus}releaseControl={releaseControl}/>diff --git a/apps/mes/app/components/AssemblyView.tsx b/apps/mes/app/components/AssemblyView.tsxindex 52c80c4a0d..1d30d8e17c 100644--- a/apps/mes/app/components/AssemblyView.tsx+++ b/apps/mes/app/components/AssemblyView.tsx@@ -932,25 +932,43 @@ export function AssemblyView({// row flips to issued the instant the owning step is done. Extra parts// (perUnit 0, issued ad-hoc from the floor) are excluded so their raw// quantityIssued drives the X/0 display instead.- const perUnit = m.quantity ?? 0;+ //+ // A link may carry a per-step quantity (the BOM line split across steps:+ // 5 screws here, 5 on another step). The row on THIS step then shows and+ // flips by the current step's share, matching the per-step backflush.+ // UNTRACKED only: tracked (serial/batch) parts are issued by scanning and+ // their quantityIssued is attributed per line, not per step — pairing a+ // per-step requirement with line-level issued would overstate completion+ // on later steps, so tracked cards keep the whole-line numbers.+ const linkShare =+ !isTrackedMat && step?.id != null+ ? ((m.jobOperationStepQuantities ?? {})[step.id] ?? null)+ : null;+ const perUnit = linkShare ?? m.quantity ?? 0;const ownedStepDoneForUnit = isLoose? !!firstStep && isStepDone(firstStep)- : steps.some(- (s) => (m.jobOperationStepIds ?? []).includes(s.id) && isStepDone(s)- );+ : linkShare !== null && step != null+ ? isStepDone(step)+ : steps.some(+ (s) => (m.jobOperationStepIds ?? []).includes(s.id) && isStepDone(s)+ );const issuedOverride =!isTrackedMat && perUnit > 0? ownedStepDoneForUnit? perUnit: 0: undefined;- const state = getIssuedForUnit(m, {+ // Shadow the line quantity with the step share so the card's required/issued+ // numbers describe this step's portion of the split, not the whole line.+ const effectiveMaterial =+ linkShare !== null ? { ...m, quantity: perUnit } : m;+ const state = getIssuedForUnit(effectiveMaterial, {unitIndex: currentUnitIndex,issuedIsPerUnit,issuedOverride});return {- m,+ m: effectiveMaterial,stepNumbers,isTrackedMat,issuedIsPerUnit,diff --git a/apps/mes/app/services/operations.service.ts b/apps/mes/app/services/operations.service.tsindex 60106dfd51..cc08c3cf79 100644--- a/apps/mes/app/services/operations.service.ts+++ b/apps/mes/app/services/operations.service.ts@@ -28,6 +28,17 @@ import type { BaseOperationWithDetails, Job, StorageItem } from "./types";const log = getLogger("mes", "operations");+// The jobMaterialStep `quantity` column ships with a migration that only runs+// on main — previews (and the prod window between app deploy and migration) run+// this code against the pre-migration schema. PostgREST fails the whole select+// on an unknown column, so callers fall back to the quantity-less query.+// 42703 = Postgres undefined_column; PGRST204 = PostgREST schema-cache miss.+function isMissingQuantityColumn(+ error: { code?: string; message?: string } | null+) {+ return error?.code === "42703" || error?.code === "PGRST204";+}+export async function getOpenJobs(client: SupabaseClient<Database>,args: { companyId: string; locationId: string }@@ -671,24 +682,45 @@ export async function getJobMaterialsByOperationId(// Step assignment (Phase 2: part ↔ step, many-to-many). The make-method view doesn't carry// the join rows, so look them up from jobMaterialStep and attach an array. No rows = the// material applies to the whole operation (shown on every step); 1+ rows scope it to those- // steps so the MES shows only the parts involved in the current step.- const stepLinks = await client+ // steps so the MES shows only the parts involved in the current step. Each link may carry+ // a per-step quantity (NULL = the full BOM line quantity), so a line split across steps+ // shows the split share on each step. The quantity column ships with this branch's+ // migration (main-only), so fall back to the bare links against a pre-migration schema.+ let stepLinks = await client.from("jobMaterialStep")- .select("jobMaterialId, jobOperationStepId")+ .select("jobMaterialId, jobOperationStepId, quantity").in("jobMaterialId",(materials.data ?? []).map((m) => m.id ?? ""));+ if (isMissingQuantityColumn(stepLinks.error)) {+ stepLinks = (await client+ .from("jobMaterialStep")+ .select("jobMaterialId, jobOperationStepId")+ .in(+ "jobMaterialId",+ (materials.data ?? []).map((m) => m.id ?? "")+ )) as unknown as typeof stepLinks;+ }const stepIdsByMaterialId = new Map<string, string[]>();+ const stepQuantitiesByMaterialId = new Map<+ string,+ Record<string, number | null>+ >();for (const r of stepLinks.data ?? []) {const list = stepIdsByMaterialId.get(r.jobMaterialId) ?? [];list.push(r.jobOperationStepId);stepIdsByMaterialId.set(r.jobMaterialId, list);+ const quantities = stepQuantitiesByMaterialId.get(r.jobMaterialId) ?? {};+ quantities[r.jobOperationStepId] = r.quantity;+ stepQuantitiesByMaterialId.set(r.jobMaterialId, quantities);}if (materials.data) {materials.data = materials.data.map((m) => ({...m,- jobOperationStepIds: stepIdsByMaterialId.get(m.id ?? "") ?? []+ jobOperationStepIds: stepIdsByMaterialId.get(m.id ?? "") ?? [],+ jobOperationStepQuantities:+ stepQuantitiesByMaterialId.get(m.id ?? "") ?? {}}));}@@ -919,20 +951,37 @@ export async function backflushUntrackedMaterialsOnStepRecord(return { error: materials.error };}- // Step ownership: materialId → the step ids it's assigned to (empty = loose).- const stepLinks = await client+ // Step ownership: materialId → the step ids it's assigned to (empty = loose),+ // plus each link's per-step quantity (NULL = the full BOM line quantity).+ // Falls back to the bare links against a pre-migration schema.+ let stepLinks = await client.from("jobMaterialStep")- .select("jobMaterialId, jobOperationStepId")+ .select("jobMaterialId, jobOperationStepId, quantity").in("jobMaterialId",materials.data.map((m) => m.id));+ if (isMissingQuantityColumn(stepLinks.error)) {+ stepLinks = (await client+ .from("jobMaterialStep")+ .select("jobMaterialId, jobOperationStepId")+ .in(+ "jobMaterialId",+ materials.data.map((m) => m.id)+ )) as unknown as typeof stepLinks;+ }if (stepLinks.error) return { error: stepLinks.error };const ownedSteps = new Map<string, Set<string>>();+ const linkQuantities = new Map<string, Map<string, number | null>>();for (const link of stepLinks.data ?? []) {const set = ownedSteps.get(link.jobMaterialId) ?? new Set<string>();set.add(link.jobOperationStepId);ownedSteps.set(link.jobMaterialId, set);+ const quantities =+ linkQuantities.get(link.jobMaterialId) ??+ new Map<string, number | null>();+ quantities.set(link.jobOperationStepId, link.quantity);+ linkQuantities.set(link.jobMaterialId, quantities);}// Units (index) that have recorded each of the operation's steps, so we can@@ -960,13 +1009,40 @@ export async function backflushUntrackedMaterialsOnStepRecord(owning && owning.size > 0? stepIds.filter((id) => owning.has(id)): [firstStepId];- // Distinct units that recorded at least one owning step — a unit that- // recorded several owning steps of the same material still counts once.+ const quantities = linkQuantities.get(material.id);+ const hasSplitQuantities = triggerStepIds.some(+ (id) => (quantities?.get(id) ?? null) !== null+ );+ // Distinct units that recorded at least one owning step — the line-level+ // requirement bound: a material can never owe more than units × per-unit.const units = new Set<number>();for (const id of triggerStepIds) {for (const idx of unitsByStep.get(id) ?? []) units.add(idx);}- const delta = units.size * perUnit - (material.quantityIssued ?? 0);+ let target: number;+ if (hasSplitQuantities) {+ // The line is SPLIT across steps (5 screws at step 1, 5 at step 2): each+ // owning step consumes its own share as it is recorded, so the target is+ // the per-step sum. A link left without an explicit quantity falls back+ // to the full per-unit quantity for its step. The sum is capped at the+ // line-level bound — the BOM line is the source of truth, so shares that+ // over-allocate the line (2 + 10 on a 5-quantity line) must not issue+ // more stock than the line requires.+ target = Math.min(+ triggerStepIds.reduce(+ (sum, id) =>+ sum ++ (unitsByStep.get(id)?.size ?? 0) * (quantities?.get(id) ?? perUnit),+ 0+ ),+ units.size * perUnit+ );+ } else {+ // Unsplit: distinct units counted once, so the requirement never+ // multiplies across a material's several owning steps.+ target = units.size * perUnit;+ }+ const delta = target - (material.quantityIssued ?? 0);if (delta <= 0) continue;const issue = await client.functions.invoke("issue", {body: {diff --git a/packages/database/src/types.ts b/packages/database/src/types.tsindex 35876a3d6c..76ee6c1462 100644--- a/packages/database/src/types.ts+++ b/packages/database/src/types.ts@@ -23023,14 +23023,17 @@ export type Database = {Row: {jobMaterialId: stringjobOperationStepId: string+ quantity: number | null}Insert: {jobMaterialId: stringjobOperationStepId: string+ quantity?: number | null}Update: {jobMaterialId?: stringjobOperationStepId?: string+ quantity?: number | null}Relationships: [{@@ -29018,14 +29021,17 @@ export type Database = {Row: {methodMaterialId: stringmethodOperationStepId: string+ quantity: number | null}Insert: {methodMaterialId: stringmethodOperationStepId: string+ quantity?: number | null}Update: {methodMaterialId?: stringmethodOperationStepId?: string+ quantity?: number | null}Relationships: [{@@ -43225,14 +43231,17 @@ export type Database = {}quoteMaterialStep: {Row: {+ quantity: number | nullquoteMaterialId: stringquoteOperationStepId: string}Insert: {+ quantity?: number | nullquoteMaterialId: stringquoteOperationStepId: string}Update: {+ quantity?: number | nullquoteMaterialId?: stringquoteOperationStepId?: string}diff --git a/packages/database/supabase/functions/get-method/index.ts b/packages/database/supabase/functions/get-method/index.tsindex c052acf6a2..a3948dfbc9 100644--- a/packages/database/supabase/functions/get-method/index.ts+++ b/packages/database/supabase/functions/get-method/index.ts@@ -116,6 +116,26 @@ function remapStepIds();}+// Material twin of remapStepIds: get_method_tree aggregates methodMaterialStep as+// {id, quantity} objects (quantity NULL = the step uses the full BOM line quantity).+// Bare-string elements are tolerated for trees read before the aggregate changed.+function remapStepLinks(+ oldLinks:+ | Array<string | { id?: string | null; quantity?: number | null } | null>+ | null+ | undefined,+ stepMap: Record<string, string>,+): { stepId: string; quantity: number | null }[] {+ return (oldLinks ?? []).flatMap((link) => {+ const id = typeof link === "string" ? link : link?.id;+ const quantity =+ typeof link === "object" && link !== null ? (link.quantity ?? null) : null;+ return id && stepMap[id]+ ? [{ stepId: stepMap[id], quantity: quantity === null ? null : Number(quantity) }]+ : [];+ });+}+const partsValidator = z.object({billOfMaterial: z.boolean().default(true),billOfProcess: z.boolean().default(true),@@ -1336,11 +1356,17 @@ serve(async (req: Request) => {jobMakeMethodId: parentJobMakeMethodId!,jobOperationId:methodOperationsToJobOperations[child.data.operationId],- // Transient (Phase 2, many-to-many): the part ↔ step links, remapped onto the- // job's steps. Stripped before insert; used to build jobMaterialStep rows.- __stepIds: remapStepIds(- (child.data as { methodOperationStepIds?: string[] | null })- .methodOperationStepIds,+ // Transient (Phase 2, many-to-many): the part ↔ step links (with their+ // per-step quantity), remapped onto the job's steps. Stripped before+ // insert; used to build jobMaterialStep rows.+ __stepLinks: remapStepLinks(+ (+ child.data as {+ methodOperationStepIds?:+ | Array<string | { id?: string | null; quantity?: number | null }>+ | null;+ }+ ).methodOperationStepIds,methodStepsToJobSteps),itemId,@@ -1438,24 +1464,27 @@ serve(async (req: Request) => {.insertInto("jobMaterial").values(madeMaterialsWithIds.map((m) => {- const { __stepIds, ...rest } = m as typeof m & {- __stepIds?: string[];+ const { __stepLinks, ...rest } = m as typeof m & {+ __stepLinks?: { stepId: string; quantity: number | null }[];};return rest;})).execute();- // Part ↔ step links (Phase 2, many-to-many): the transient __stepIds carried the- // remapped job step ids; write them to jobMaterialStep now that the material id- // exists. No links = whole operation (shown on every step in the MES).+ // Part ↔ step links (Phase 2, many-to-many): the transient __stepLinks carried+ // the remapped job step ids + per-step quantity; write them to jobMaterialStep+ // now that the material id exists. No links = whole operation (shown on every+ // step in the MES).const madeStepRows = madeMaterialsWithIds.flatMap((m) =>- ((m as { __stepIds?: string[] }).__stepIds ?? []).map(- (jobOperationStepId) => ({- jobMaterialId: m.id,- jobOperationStepId,- })- )+ (+ (m as { __stepLinks?: { stepId: string; quantity: number | null }[] })+ .__stepLinks ?? []+ ).map((link) => ({+ jobMaterialId: m.id,+ jobOperationStepId: link.stepId,+ quantity: link.quantity,+ })));if (madeStepRows.length > 0) {await trx@@ -1512,7 +1541,7 @@ serve(async (req: Request) => {if (pickedOrBoughtMaterials.length > 0) {// Assign ids up front so part ↔ step links (Phase 2, many-to-many) can reference- // each row; strip the transient __stepIds before inserting the material.+ // each row; strip the transient __stepLinks before inserting the material.const pickedWithIds = pickedOrBoughtMaterials.map((m) => ({...m,id: (m as { id?: string }).id ?? nanoid(),@@ -1521,8 +1550,8 @@ serve(async (req: Request) => {.insertInto("jobMaterial").values(pickedWithIds.map((m) => {- const { __stepIds, ...rest } = m as typeof m & {- __stepIds?: string[];+ const { __stepLinks, ...rest } = m as typeof m & {+ __stepLinks?: { stepId: string; quantity: number | null }[];};return rest;})@@ -1530,12 +1559,14 @@ serve(async (req: Request) => {.execute();const pickedStepRows = pickedWithIds.flatMap((m) =>- ((m as { __stepIds?: string[] }).__stepIds ?? []).map(- (jobOperationStepId) => ({- jobMaterialId: m.id,- jobOperationStepId,- })- )+ (+ (m as { __stepLinks?: { stepId: string; quantity: number | null }[] })+ .__stepLinks ?? []+ ).map((link) => ({+ jobMaterialId: m.id,+ jobOperationStepId: link.stepId,+ quantity: link.quantity,+ })));if (pickedStepRows.length > 0) {await trx@@ -2010,11 +2041,17 @@ serve(async (req: Request) => {jobMakeMethodId: parentJobMakeMethodId!,jobOperationId:methodOperationsToJobOperations[child.data.operationId],- // Transient (Phase 2, many-to-many): the part ↔ step links, remapped onto the- // job's steps. Stripped before insert; used to build jobMaterialStep rows.- __stepIds: remapStepIds(- (child.data as { methodOperationStepIds?: string[] | null })- .methodOperationStepIds,+ // Transient (Phase 2, many-to-many): the part ↔ step links (with their+ // per-step quantity), remapped onto the job's steps. Stripped before+ // insert; used to build jobMaterialStep rows.+ __stepLinks: remapStepLinks(+ (+ child.data as {+ methodOperationStepIds?:+ | Array<string | { id?: string | null; quantity?: number | null }>+ | null;+ }+ ).methodOperationStepIds,methodStepsToJobSteps),itemId: child.data.itemId,@@ -2098,24 +2135,27 @@ serve(async (req: Request) => {.insertInto("jobMaterial").values(madeMaterialsWithIds.map((m) => {- const { __stepIds, ...rest } = m as typeof m & {- __stepIds?: string[];+ const { __stepLinks, ...rest } = m as typeof m & {+ __stepLinks?: { stepId: string; quantity: number | null }[];};return rest;})).execute();- // Part ↔ step links (Phase 2, many-to-many): the transient __stepIds carried the- // remapped job step ids; write them to jobMaterialStep now that the material id- // exists. No links = whole operation (shown on every step in the MES).+ // Part ↔ step links (Phase 2, many-to-many): the transient __stepLinks carried+ // the remapped job step ids + per-step quantity; write them to jobMaterialStep+ // now that the material id exists. No links = whole operation (shown on every+ // step in the MES).const madeStepRows = madeMaterialsWithIds.flatMap((m) =>- ((m as { __stepIds?: string[] }).__stepIds ?? []).map(- (jobOperationStepId) => ({- jobMaterialId: m.id,- jobOperationStepId,- })- )+ (+ (m as { __stepLinks?: { stepId: string; quantity: number | null }[] })+ .__stepLinks ?? []+ ).map((link) => ({+ jobMaterialId: m.id,+ jobOperationStepId: link.stepId,+ quantity: link.quantity,+ })));if (madeStepRows.length > 0) {await trx@@ -2175,7 +2215,7 @@ serve(async (req: Request) => {if (pickedOrBoughtMaterials.length > 0) {// Assign ids up front so part ↔ step links (Phase 2, many-to-many) can reference- // each row; strip the transient __stepIds before inserting the material.+ // each row; strip the transient __stepLinks before inserting the material.const pickedWithIds = pickedOrBoughtMaterials.map((m) => ({...m,id: (m as { id?: string }).id ?? nanoid(),@@ -2184,8 +2224,8 @@ serve(async (req: Request) => {.insertInto("jobMaterial").values(pickedWithIds.map((m) => {- const { __stepIds, ...rest } = m as typeof m & {- __stepIds?: string[];+ const { __stepLinks, ...rest } = m as typeof m & {+ __stepLinks?: { stepId: string; quantity: number | null }[];};return rest;})@@ -2193,12 +2233,14 @@ serve(async (req: Request) => {.execute();const pickedStepRows = pickedWithIds.flatMap((m) =>- ((m as { __stepIds?: string[] }).__stepIds ?? []).map(- (jobOperationStepId) => ({- jobMaterialId: m.id,- jobOperationStepId,- })- )+ (+ (m as { __stepLinks?: { stepId: string; quantity: number | null }[] })+ .__stepLinks ?? []+ ).map((link) => ({+ jobMaterialId: m.id,+ jobOperationStepId: link.stepId,+ quantity: link.quantity,+ })));if (pickedStepRows.length > 0) {await trx@@ -6887,7 +6929,7 @@ async function linkAssemblyStepMaterialsForJobOperations();const stepMaterials = await client.from("assemblyInstructionStepMaterial")- .select("stepId, itemId")+ .select("stepId, itemId, quantity").in("stepId", sourceStepIds).eq("companyId", companyId);if (stepMaterials.error || (stepMaterials.data ?? []).length === 0) {@@ -6913,7 +6955,7 @@ async function linkAssemblyStepMaterialsForJobOperations(? materialIdByItemId.get(link.itemId): undefined;return jobOperationStepId && jobMaterialId- ? [{ jobMaterialId, jobOperationStepId }]+ ? [{ jobMaterialId, jobOperationStepId, quantity: link.quantity ?? null }]: [];});diff --git a/packages/database/supabase/functions/lib/types.ts b/packages/database/supabase/functions/lib/types.tsindex 35876a3d6c..76ee6c1462 100644--- a/packages/database/supabase/functions/lib/types.ts+++ b/packages/database/supabase/functions/lib/types.ts@@ -23023,14 +23023,17 @@ export type Database = {Row: {jobMaterialId: stringjobOperationStepId: string+ quantity: number | null}Insert: {jobMaterialId: stringjobOperationStepId: string+ quantity?: number | null}Update: {jobMaterialId?: stringjobOperationStepId?: string+ quantity?: number | null}Relationships: [{@@ -29018,14 +29021,17 @@ export type Database = {Row: {methodMaterialId: stringmethodOperationStepId: string+ quantity: number | null}Insert: {methodMaterialId: stringmethodOperationStepId: string+ quantity?: number | null}Update: {methodMaterialId?: stringmethodOperationStepId?: string+ quantity?: number | null}Relationships: [{@@ -43225,14 +43231,17 @@ export type Database = {}quoteMaterialStep: {Row: {+ quantity: number | nullquoteMaterialId: stringquoteOperationStepId: string}Insert: {+ quantity?: number | nullquoteMaterialId: stringquoteOperationStepId: string}Update: {+ quantity?: number | nullquoteMaterialId?: stringquoteOperationStepId?: string}diff --git a/packages/database/supabase/migrations/20260820181957_step-material-link-quantity.sql b/packages/database/supabase/migrations/20260820181957_step-material-link-quantity.sqlnew file mode 100644index 0000000000..71a47a15a3--- /dev/null+++ b/packages/database/supabase/migrations/20260820181957_step-material-link-quantity.sql@@ -0,0 +1,186 @@+-- Per-step quantity on the part ↔ step links. A BOM line's quantity can be split across+-- the steps that consume it (10 screws: 5 at step 1, 5 at step 2). NULL = the step uses+-- the full BOM line quantity (legacy rows and the default on link).+ALTER TABLE "methodMaterialStep" ADD COLUMN "quantity" NUMERIC;+ALTER TABLE "jobMaterialStep" ADD COLUMN "quantity" NUMERIC;+ALTER TABLE "quoteMaterialStep" ADD COLUMN "quantity" NUMERIC;++-- Re-land get_method_tree so the aggregated step links carry the quantity: the+-- "methodOperationStepIds" JSONB becomes an array of {id, quantity} objects instead of+-- bare id strings (get-method's remap consumes both shapes). Body otherwise identical+-- to 20260721004140_operation-type-consolidation.sql.+-- line effectivity) merged with the branch's methodOperationStepIds additions.+DROP FUNCTION IF EXISTS get_method_tree(TEXT);+CREATE OR REPLACE FUNCTION get_method_tree(uid TEXT)+RETURNS TABLE (+ "methodMaterialId" TEXT,+ "makeMethodId" TEXT,+ "materialMakeMethodId" TEXT,+ "itemId" TEXT,+ "itemReadableId" TEXT,+ "itemType" TEXT,+ "description" TEXT,+ "unitOfMeasureCode" TEXT,+ "unitCost" NUMERIC,+ "quantity" NUMERIC,+ "methodType" "methodType",+ "itemTrackingType" TEXT,+ "parentMaterialId" TEXT,+ "order" DOUBLE PRECISION,+ "operationId" TEXT,+ "methodOperationStepIds" JSONB,+ "isRoot" BOOLEAN,+ "kit" BOOLEAN,+ "revision" TEXT,+ "externalId" JSONB,+ "version" NUMERIC,+ "storageUnitIds" JSONB,+ "isPickDescendant" BOOLEAN,+ "replenishmentSystem" "itemReplenishmentSystem"+) AS $$+WITH RECURSIVE material AS (+ SELECT+ "id",+ "makeMethodId",+ "methodType",+ COALESCE(+ "materialMakeMethodId",+ CASE WHEN "methodType" = 'Pull from Inventory' THEN (+ SELECT amm.id FROM "activeMakeMethods" amm WHERE amm."itemId" = "methodMaterial"."itemId" LIMIT 1+ ) END+ ) AS "materialMakeMethodId",+ "itemId",+ "itemType",+ "quantity",+ "makeMethodId" AS "parentMaterialId",+ NULL AS "operationId",+ COALESCE("order", 1) AS "order",+ "kit",+ "storageUnitIds",+ false AS "isPickDescendant"+ FROM+ "methodMaterial"+ WHERE+ "makeMethodId" = uid+ UNION+ SELECT+ child."id",+ child."makeMethodId",+ child."methodType",+ COALESCE(+ child."materialMakeMethodId",+ CASE WHEN child."methodType" = 'Pull from Inventory' THEN (+ SELECT amm.id FROM "activeMakeMethods" amm WHERE amm."itemId" = child."itemId" LIMIT 1+ ) END+ ) AS "materialMakeMethodId",+ child."itemId",+ child."itemType",+ child."quantity",+ parent."id" AS "parentMaterialId",+ child."methodOperationId" AS "operationId",+ child."order",+ child."kit",+ child."storageUnitIds",+ (parent."methodType" = 'Pull from Inventory' OR parent."isPickDescendant") AS "isPickDescendant"+ FROM+ "methodMaterial" child+ INNER JOIN material parent ON parent."materialMakeMethodId" = child."makeMethodId"+)+SELECT+ material.id as "methodMaterialId",+ material."makeMethodId",+ material."materialMakeMethodId",+ material."itemId",+ item."readableIdWithRevision" AS "itemReadableId",+ material."itemType",+ item."name" AS "description",+ item."unitOfMeasureCode",+ cost."unitCost",+ material."quantity",+ material."methodType",+ item."itemTrackingType",+ material."parentMaterialId",+ material."order",+ material."operationId",+ (+ SELECT COALESCE(jsonb_agg(jsonb_build_object('id', mms."methodOperationStepId", 'quantity', mms."quantity")), '[]'::jsonb)+ FROM "methodMaterialStep" mms+ WHERE mms."methodMaterialId" = material.id+ ) AS "methodOperationStepIds",+ false AS "isRoot",+ material."kit",+ item."revision",+ (+ SELECT COALESCE(+ jsonb_object_agg(+ eim."integration",+ CASE+ WHEN eim."metadata" IS NOT NULL THEN eim."metadata"+ ELSE to_jsonb(eim."externalId")+ END+ ) FILTER (WHERE eim."externalId" IS NOT NULL),+ '{}'::jsonb+ )+ FROM "externalIntegrationMapping" eim+ WHERE eim."entityType" = 'item' AND eim."entityId" = item.id+ ) AS "externalId",+ mm2."version",+ material."storageUnitIds",+ material."isPickDescendant",+ item."replenishmentSystem"+FROM material+INNER JOIN item+ ON material."itemId" = item.id+INNER JOIN "itemCost" cost+ ON item.id = cost."itemId"+INNER JOIN "makeMethod" mm+ ON material."makeMethodId" = mm.id+LEFT JOIN "makeMethod" mm2+ ON material."materialMakeMethodId" = mm2.id+UNION+SELECT+ mm."id" AS "methodMaterialId",+ NULL AS "makeMethodId",+ mm.id AS "materialMakeMethodId",+ mm."itemId",+ item."readableIdWithRevision" AS "itemReadableId",+ item."type"::text,+ item."name" AS "description",+ item."unitOfMeasureCode",+ cost."unitCost",+ 1 AS "quantity",+ 'Make to Order' AS "methodType",+ item."itemTrackingType",+ NULL AS "parentMaterialId",+ CAST(1 AS DOUBLE PRECISION) AS "order",+ NULL AS "operationId",+ '[]'::jsonb AS "methodOperationStepIds",+ true AS "isRoot",+ false AS "kit",+ item."revision",+ (+ SELECT COALESCE(+ jsonb_object_agg(+ eim."integration",+ CASE+ WHEN eim."metadata" IS NOT NULL THEN eim."metadata"+ ELSE to_jsonb(eim."externalId")+ END+ ) FILTER (WHERE eim."externalId" IS NOT NULL),+ '{}'::jsonb+ )+ FROM "externalIntegrationMapping" eim+ WHERE eim."entityType" = 'item' AND eim."entityId" = item.id+ ) AS "externalId",+ mm."version",+ '{}'::JSONB AS "storageUnitIds",+ false AS "isPickDescendant",+ item."replenishmentSystem"+FROM "makeMethod" mm+INNER JOIN item+ ON mm."itemId" = item.id+INNER JOIN "itemCost" cost+ ON item.id = cost."itemId"+WHERE mm.id = uid+ORDER BY "order"+$$ LANGUAGE sql STABLE;diff --git a/packages/locale/locales/de/erp.po b/packages/locale/locales/de/erp.poindex 56cc16cc4d..f42993cec5 100644--- a/packages/locale/locales/de/erp.po+++ b/packages/locale/locales/de/erp.po@@ -1357,6 +1357,9 @@ msgstr "Alle Lieferanten"msgid "All Time"msgstr "Gesamter Zeitraum"+msgid "All tools"+msgstr "Alle Werkzeuge"+msgid "All Types"msgstr "Alle Typen"@@ -10298,6 +10301,9 @@ msgstr "In Verkaufsauftrag"msgid "On Storage Unit"msgstr "Auf Lagereinheit"+msgid "On this operation"+msgstr "Bei diesem Arbeitsgang"+msgid "On-account credit available"msgstr "Verfügbarer Kontokorrentkreditrahmen"diff --git a/packages/locale/locales/en/erp.po b/packages/locale/locales/en/erp.poindex fcd96b8a50..0e254bd089 100644--- a/packages/locale/locales/en/erp.po+++ b/packages/locale/locales/en/erp.po@@ -1357,6 +1357,9 @@ msgstr "All Suppliers"msgid "All Time"msgstr "All Time"+msgid "All tools"+msgstr "All tools"+msgid "All Types"msgstr "All Types"@@ -10298,6 +10301,9 @@ msgstr "On Sales Order"msgid "On Storage Unit"msgstr "On Storage Unit"+msgid "On this operation"+msgstr "On this operation"+msgid "On-account credit available"msgstr "On-account credit available"diff --git a/packages/locale/locales/es/erp.po b/packages/locale/locales/es/erp.poindex 7458a9a704..47633945a0 100644--- a/packages/locale/locales/es/erp.po+++ b/packages/locale/locales/es/erp.po@@ -1357,6 +1357,9 @@ msgstr "Todos los proveedores"msgid "All Time"msgstr "Todo el tiempo"+msgid "All tools"+msgstr "Todas las herramientas"+msgid "All Types"msgstr "Todos los tipos"@@ -10298,6 +10301,9 @@ msgstr "En Orden de Venta"msgid "On Storage Unit"msgstr "En Unidad de Almacenamiento"+msgid "On this operation"+msgstr "En esta operación"+msgid "On-account credit available"msgstr "Crédito disponible en cuenta"diff --git a/packages/locale/locales/fr/erp.po b/packages/locale/locales/fr/erp.poindex 098962be3e..b3fdbbaa38 100644--- a/packages/locale/locales/fr/erp.po+++ b/packages/locale/locales/fr/erp.po@@ -1357,6 +1357,9 @@ msgstr "Tous les fournisseurs"msgid "All Time"msgstr "Tous les temps"+msgid "All tools"+msgstr "Tous les outils"+msgid "All Types"msgstr "Tous les types"@@ -10298,6 +10301,9 @@ msgstr "Sur commande client"msgid "On Storage Unit"msgstr "Sur l'unité de stockage"+msgid "On this operation"+msgstr "Sur cette opération"+msgid "On-account credit available"msgstr "Crédit en compte disponible"diff --git a/packages/locale/locales/hi/erp.po b/packages/locale/locales/hi/erp.poindex 4f2f43d2a6..fe5f3ba086 100644--- a/packages/locale/locales/hi/erp.po+++ b/packages/locale/locales/hi/erp.po@@ -1357,6 +1357,9 @@ msgstr "सभी आपूर्तिकर्ता"msgid "All Time"msgstr "सभी समय"+msgid "All tools"+msgstr "सभी उपकरण"+msgid "All Types"msgstr "सभी प्रकार"@@ -10298,6 +10301,9 @@ msgstr "बिक्रय आदेश पर"msgid "On Storage Unit"msgstr "स्टोरेज यूनिट पर"+msgid "On this operation"+msgstr "इस ऑपरेशन पर"+msgid "On-account credit available"msgstr "खाते पर उपलब्ध क्रेडिट"diff --git a/packages/locale/locales/it/erp.po b/packages/locale/locales/it/erp.poindex c8e0bbfe25..3dd3c868dd 100644--- a/packages/locale/locales/it/erp.po+++ b/packages/locale/locales/it/erp.po@@ -1357,6 +1357,9 @@ msgstr "Tutti i fornitori"msgid "All Time"msgstr "Tutto il tempo"+msgid "All tools"+msgstr "Tutti gli strumenti"+msgid "All Types"msgstr "Tutti i tipi"@@ -10298,6 +10301,9 @@ msgstr "Su Ordine di Vendita"msgid "On Storage Unit"msgstr "Su Unità di Stoccaggio"+msgid "On this operation"+msgstr "Su questa operazione"+msgid "On-account credit available"msgstr "Credito a conto disponibile"diff --git a/packages/locale/locales/ja/erp.po b/packages/locale/locales/ja/erp.poindex 79efe78716..77b8672800 100644--- a/packages/locale/locales/ja/erp.po+++ b/packages/locale/locales/ja/erp.po@@ -1357,6 +1357,9 @@ msgstr "すべてのサプライヤー"msgid "All Time"msgstr "すべての期間"+msgid "All tools"+msgstr "すべてのツール"+msgid "All Types"msgstr "すべてのタイプ"@@ -10298,6 +10301,9 @@ msgstr "販売注文中"msgid "On Storage Unit"msgstr "保管ユニット上"+msgid "On this operation"+msgstr "この操作で"+msgid "On-account credit available"msgstr "掛け売掛金利用可能"diff --git a/packages/locale/locales/ko/erp.po b/packages/locale/locales/ko/erp.poindex 045769d4e2..cb22ea8974 100644--- a/packages/locale/locales/ko/erp.po+++ b/packages/locale/locales/ko/erp.po@@ -1357,6 +1357,9 @@ msgstr "모든 공급업체"msgid "All Time"msgstr "전체 기간"+msgid "All tools"+msgstr "모든 도구"+msgid "All Types"msgstr "모든 유형"@@ -10298,6 +10301,9 @@ msgstr "판매주문에서"msgid "On Storage Unit"msgstr "저장 단위에서"+msgid "On this operation"+msgstr "이 작업 시"+msgid "On-account credit available"msgstr "사용 가능한 외상 크레딧"diff --git a/packages/locale/locales/pl/erp.po b/packages/locale/locales/pl/erp.poindex 0334eb2cd7..8d56979a63 100644--- a/packages/locale/locales/pl/erp.po+++ b/packages/locale/locales/pl/erp.po@@ -1357,6 +1357,9 @@ msgstr "Wszyscy dostawcy"msgid "All Time"msgstr "Cały czas"+msgid "All tools"+msgstr "Wszystkie narzędzia"+msgid "All Types"msgstr "Wszystkie typy"@@ -10298,6 +10301,9 @@ msgstr "Na zamówieniu sprzedaży"msgid "On Storage Unit"msgstr "Na jednostce magazynowej"+msgid "On this operation"+msgstr "Na tej operacji"+msgid "On-account credit available"msgstr "Dostępny kredyt na koncie"diff --git a/packages/locale/locales/pt/erp.po b/packages/locale/locales/pt/erp.poindex 49e0aca695..6ebad4ade3 100644--- a/packages/locale/locales/pt/erp.po+++ b/packages/locale/locales/pt/erp.po@@ -1357,6 +1357,9 @@ msgstr "Todos os Fornecedores"msgid "All Time"msgstr "Sempre"+msgid "All tools"+msgstr "Todas as ferramentas"+msgid "All Types"msgstr "Todos os Tipos"@@ -10298,6 +10301,9 @@ msgstr "Em Pedido de Venda"msgid "On Storage Unit"msgstr "Na Unidade de Armazenamento"+msgid "On this operation"+msgstr "Nesta operação"+msgid "On-account credit available"msgstr "Crédito em conta disponível"diff --git a/packages/locale/locales/ru/erp.po b/packages/locale/locales/ru/erp.poindex 72bef8e605..3e2f249685 100644--- a/packages/locale/locales/ru/erp.po+++ b/packages/locale/locales/ru/erp.po@@ -1357,6 +1357,9 @@ msgstr "Все поставщики"msgid "All Time"msgstr "Все время"+msgid "All tools"+msgstr "Все инструменты"+msgid "All Types"msgstr "Все типы"@@ -10298,6 +10301,9 @@ msgstr "На заказе продажи"msgid "On Storage Unit"msgstr "На складском отделении"+msgid "On this operation"+msgstr "На эту операцию"+msgid "On-account credit available"msgstr "Доступный кредит на счете"diff --git a/packages/locale/locales/tr/erp.po b/packages/locale/locales/tr/erp.poindex ee60600749..3133a93e01 100644--- a/packages/locale/locales/tr/erp.po+++ b/packages/locale/locales/tr/erp.po@@ -1357,6 +1357,9 @@ msgstr "Tüm Tedarikçiler"msgid "All Time"msgstr "Her Zaman"+msgid "All tools"+msgstr "Tüm araçlar"+msgid "All Types"msgstr "Tüm Türler"@@ -10298,6 +10301,9 @@ msgstr "Satış Siparişi'nde"msgid "On Storage Unit"msgstr "Depolizdeki"+msgid "On this operation"+msgstr "Bu operasyonda"+msgid "On-account credit available"msgstr "Hesapta mevcut kredi"diff --git a/packages/locale/locales/zh/erp.po b/packages/locale/locales/zh/erp.poindex 7fcdbe6301..6faaf267c1 100644--- a/packages/locale/locales/zh/erp.po+++ b/packages/locale/locales/zh/erp.po@@ -1357,6 +1357,9 @@ msgstr "所有供应商"msgid "All Time"msgstr "所有时间"+msgid "All tools"+msgstr "所有工具"+msgid "All Types"msgstr "所有类型"@@ -10298,6 +10301,9 @@ msgstr "在销售订单上"msgid "On Storage Unit"msgstr "在存储单元上"+msgid "On this operation"+msgstr "在此工序上"+msgid "On-account credit available"msgstr "账户信用额度可用"