Skip to content

Open-source manufacturing ERP, MES and QMS. Quoting, MRP, inventory, shop floor, quality and lot/serial traceability on one Postgres schema, with a REST API and MCP server. Self-host or use Carbon Cloud.

fix(sales): prune orphaned quote line prices; feat(traceability): cluster serial siblings (#1342)

Sid5fbe7104b828
diff --git a/.claude/rules/traceability-model.md b/.claude/rules/traceability-model.md
index ca8441f47f..bc230213be 100644
--- a/.claude/rules/traceability-model.md
+++ b/.claude/rules/traceability-model.md
@@ -96,6 +96,23 @@ Non-strict variants exist but include same-activity siblings — prefer strict.
- MES `operations.service.ts`: `getTrackedEntity`, `getTrackedEntitiesByMakeMethodId`,
`getTrackedInputs` (wraps the strict RPCs), `startProductionEvent`.
+**Serial sibling clustering (display only).** A serial item at qty N produces N
+qty-1 entities by design, so one job fans out into N identical nodes. The graph
+collapses siblings that share an identical **edge signature** — the exact set of
+`(activityId, side)` pairs — plus the same item and `status`, into one
+`entityGroup` node (`ui/Traceability/cluster.ts` → `clusterEntities`, called from
+`payloadToFlow` in `ui/Traceability/utils.ts`, whose only caller is the worker's
+`computeFullLayout`). Guards: the traced root never clusters, `quantity !== 1`
+never clusters (protects post-flip batch fragments), the entity must resolve to a
+SINGLE timeline state (a bin-transferred serial replays to two and stays
+individual), and a group needs ≥ 3 members. One edge per signature entry with the
+members' quantities summed. Members are reached only through the sidebar's list —
+cluster nodes carry no expand toggles, since expanding a 50-member group would
+fetch 50 lineages. Clusters travel from the graph to the sidebar (its sibling in
+the route) through `ui/Traceability/store.ts`. Because clustering absorbs serial
+fans, `MAX_ENTITIES` in `lineage.server.ts` is **500**; the BFS must stay complete
+up to it, since a truncated frontier would split a group in two.
+
## Picking / availability (shelf → storageUnit rename)
`get_available_tracked_entities(...)` (`20260614171204`) and
diff --git a/apps/erp/app/modules/inventory/lineage.server.ts b/apps/erp/app/modules/inventory/lineage.server.ts
index 88ad6d3813..aab0304442 100644
--- a/apps/erp/app/modules/inventory/lineage.server.ts
+++ b/apps/erp/app/modules/inventory/lineage.server.ts
@@ -26,7 +26,11 @@ export type LineagePayload = {
containments?: IssueContainment[];
};
-const MAX_ENTITIES = 200;
+// The graph collapses identical serial siblings into group nodes, so a large
+// serial fan no longer costs a node each — the ceiling can afford whole jobs.
+// The BFS must stay COMPLETE up to it: cluster signatures are computed from
+// the full edge set, and a truncated frontier would split a group in two.
+const MAX_ENTITIES = 500;
type LineageState = {
entities: Map<string, TrackedEntity>;
diff --git a/apps/erp/app/modules/inventory/ui/Traceability/GraphLegend.tsx b/apps/erp/app/modules/inventory/ui/Traceability/GraphLegend.tsx
index 0ef6086614..8903f2569b 100644
--- a/apps/erp/app/modules/inventory/ui/Traceability/GraphLegend.tsx
+++ b/apps/erp/app/modules/inventory/ui/Traceability/GraphLegend.tsx
@@ -18,7 +18,7 @@ import {
type Entry = {
label: string;
color: string;
- shape: "circle" | "diamond";
+ shape: "circle" | "diamond" | "stack";
icon: IconType;
};
@@ -30,15 +30,23 @@ const ENTITY_DISPLAY_ORDER: EntityStatus[] = [
"Rejected"
];
-const ENTITY_ENTRIES: Entry[] = ENTITY_DISPLAY_ORDER.map((status) => {
- const meta = ENTITY_STATUS_META[status];
- return {
- label: meta.label,
- color: meta.color,
- shape: "circle",
- icon: meta.icon
- };
-});
+const ENTITY_ENTRIES: Entry[] = [
+ ...ENTITY_DISPLAY_ORDER.map<Entry>((status) => {
+ const meta = ENTITY_STATUS_META[status];
+ return {
+ label: meta.label,
+ color: meta.color,
+ shape: "circle",
+ icon: meta.icon
+ };
+ }),
+ {
+ label: "Serial group",
+ color: ENTITY_STATUS_META.Available.color,
+ shape: "stack",
+ icon: ENTITY_STATUS_META.Available.icon
+ }
+];
const ACTIVITY_ENTRIES: Entry[] = (
Object.keys(ACTIVITY_KIND_META) as ActivityKind[]
@@ -167,10 +175,30 @@ function Row({ entry }: { entry: Entry }) {
return (
<HStack spacing={3} className="items-center">
<div className="relative w-6 h-6 flex items-center justify-center shrink-0">
+ {entry.shape === "stack" && (
+ <>
+ <div
+ className="absolute inset-0 rounded-full ring-1 ring-background"
+ style={{
+ background: entry.color,
+ opacity: 0.3,
+ transform: "translate(4px, -4px)"
+ }}
+ />
+ <div
+ className="absolute inset-0 rounded-full ring-1 ring-background"
+ style={{
+ background: entry.color,
+ opacity: 0.55,
+ transform: "translate(2px, -2px)"
+ }}
+ />
+ </>
+ )}
<div
className={cn(
"absolute inset-0",
- entry.shape === "circle" ? "rounded-full" : "rounded"
+ entry.shape === "diamond" ? "rounded" : "rounded-full"
)}
style={{
background: entry.color,
diff --git a/apps/erp/app/modules/inventory/ui/Traceability/NodeSearchDialog.tsx b/apps/erp/app/modules/inventory/ui/Traceability/NodeSearchDialog.tsx
index ce6177c212..55918c41b7 100644
--- a/apps/erp/app/modules/inventory/ui/Traceability/NodeSearchDialog.tsx
+++ b/apps/erp/app/modules/inventory/ui/Traceability/NodeSearchDialog.tsx
@@ -24,6 +24,9 @@ type Props = {
onOpenChange: (open: boolean) => void;
payload: LineagePayload;
onSelect?: (id: string) => void;
+ /** Maps a clustered serial to the group node that stands in for it — a
+ * member has no node of its own to centre on. */
+ resolveNodeId?: (id: string) => string;
};
type SearchResult = {
@@ -35,7 +38,8 @@ export function NodeSearchDialog({
open,
onOpenChange,
payload,
- onSelect
+ onSelect,
+ resolveNodeId
}: Props) {
const { getNode, setCenter } = useReactFlow();
const navigate = useNavigate();
@@ -79,7 +83,8 @@ export function NodeSearchDialog({
onOpenChange(false);
const inGraph = kind === "entity" ? localIds.e.has(id) : localIds.a.has(id);
if (inGraph) {
- const node = getNode(id);
+ const nodeId = kind === "entity" ? (resolveNodeId?.(id) ?? id) : id;
+ const node = getNode(nodeId);
if (node) {
const w = node.measured?.width ?? node.width ?? 44;
const h = node.measured?.height ?? node.height ?? 44;
diff --git a/apps/erp/app/modules/inventory/ui/Traceability/TraceabilityGraph.tsx b/apps/erp/app/modules/inventory/ui/Traceability/TraceabilityGraph.tsx
index 960f5b0d06..b61e57185c 100644
--- a/apps/erp/app/modules/inventory/ui/Traceability/TraceabilityGraph.tsx
+++ b/apps/erp/app/modules/inventory/ui/Traceability/TraceabilityGraph.tsx
@@ -37,6 +37,7 @@ import {
} from "./metadata";
import { NodeSearchDialog } from "./NodeSearchDialog";
import { ActivityNode } from "./nodes/ActivityNode";
+import { EntityGroupNode } from "./nodes/EntityGroupNode";
import { EntityNode } from "./nodes/EntityNode";
import { useTraceabilityStore } from "./store";
import { TraceabilityTable } from "./TraceabilityTable";
@@ -55,6 +56,7 @@ import {
const nodeTypes: NodeTypes = {
entity: EntityNode as any,
+ entityGroup: EntityGroupNode as any,
activity: ActivityNode as any
};
@@ -66,6 +68,8 @@ const proOptions = { hideAttribution: true };
const EMPTY_NODES: LineageNode[] = [];
const EMPTY_EDGES: LineageEdge[] = [];
+const EMPTY_ROOT_IDS: string[] = [];
+const EMPTY_MEMBER_MAP: Record<string, string> = {};
type Props = {
entities: TrackedEntity[];
@@ -126,7 +130,9 @@ function TraceabilityGraphInner({
toggleExcluded,
clearExcluded,
toggleAdditionalRoot,
- clearAdditionalRoots
+ clearAdditionalRoots,
+ setClusters,
+ setHighlightMember
} = useTraceabilityStore(
useShallow((s) => ({
addExpansion: s.addExpansion,
@@ -141,7 +147,9 @@ function TraceabilityGraphInner({
toggleExcluded: s.toggleExcluded,
clearExcluded: s.clearExcluded,
toggleAdditionalRoot: s.toggleAdditionalRoot,
- clearAdditionalRoots: s.clearAdditionalRoots
+ clearAdditionalRoots: s.clearAdditionalRoots,
+ setClusters: s.setClusters,
+ setHighlightMember: s.setHighlightMember
}))
);
const excludedIds = useTraceabilityStore((s) => s.excludedIds);
@@ -195,7 +203,6 @@ function TraceabilityGraphInner({
setLayoutVersion((v) => v + 1);
}, []);
- const [draggedIds, setDraggedIds] = useState<Set<string>>(new Set());
const [fitted, setFitted] = useState(false);
useEffect(() => {
@@ -212,6 +219,11 @@ function TraceabilityGraphInner({
return set;
}, [payload.entities]);
+ const rootIds = useMemo(
+ () => (rootType === "entity" && rootId ? [rootId] : EMPTY_ROOT_IDS),
+ [rootType, rootId]
+ );
+
const tracingGraphManager = useTracingGraphManager();
const layoutResult = useAsyncLayout(
tracingGraphManager,
@@ -219,10 +231,18 @@ function TraceabilityGraphInner({
direction,
spacing,
rejectIds,
+ rootIds,
layoutVersion
);
const laidNodes = layoutResult?.nodes ?? EMPTY_NODES;
const laidEdges = layoutResult?.edges ?? EMPTY_EDGES;
+ const memberToCluster = layoutResult?.memberToCluster ?? EMPTY_MEMBER_MAP;
+
+ // The sidebar lives beside this component in the route, so cluster data
+ // reaches it through the store rather than props.
+ useEffect(() => {
+ setClusters(layoutResult?.clusters ?? [], memberToCluster);
+ }, [layoutResult, memberToCluster, setClusters]);
const [nodes, setNodes, onNodesChangeRaw] = useNodesState<Node>(
laidNodes as Node[]
@@ -305,7 +325,6 @@ function TraceabilityGraphInner({
useEffect(() => {
setNodes(laidNodes as Node[]);
setEdges(laidEdges as Edge[]);
- setDraggedIds(new Set());
setLayoutAnimating(true);
const t = setTimeout(() => setLayoutAnimating(false), 260);
return () => clearTimeout(t);
@@ -321,17 +340,26 @@ function TraceabilityGraphInner({
const selectedIdSet = useMemo(() => new Set(selectedIds), [selectedIds]);
const selectedId = selectedIds[0] ?? null;
+ // A clustered serial has no node of its own — selecting it means selecting
+ // its group, and telling the sidebar which member to highlight.
+ const resolveNodeId = useCallback(
+ (id: string) => memberToCluster[id] ?? id,
+ [memberToCluster]
+ );
+
const selectNode = useCallback(
(id: string | null) => {
+ const targetId = id === null ? null : resolveNodeId(id);
+ setHighlightMember(id !== null && targetId !== id ? id : null);
setNodes((ns) =>
ns.map((n) => {
- const wantsSelected = id !== null && n.id === id;
+ const wantsSelected = targetId !== null && n.id === targetId;
if (n.selected === wantsSelected) return n;
return { ...n, selected: wantsSelected };
})
);
},
- [setNodes]
+ [setNodes, resolveNodeId, setHighlightMember]
);
const onExpandResult = useCallback(
@@ -409,6 +437,7 @@ function TraceabilityGraphInner({
useProbeBoundary({
payload,
boundaryByNode,
+ memberToCluster,
markExpandable,
markExhausted,
probeCacheRef,
@@ -486,16 +515,12 @@ function TraceabilityGraphInner({
return edges.map((e) => {
const dimmed = isolated ? !isolated.edgeIds.has(e.id) : false;
const highlighted = selectionPath?.edgeIds.has(e.id) ?? false;
- const touchesDragged =
- draggedIds.has(e.source) || draggedIds.has(e.target);
- const baseData = { ...((e.data as any) ?? {}) };
- if (touchesDragged) baseData.points = undefined;
return {
...e,
- data: { ...baseData, dimmed, highlighted }
+ data: { ...((e.data as any) ?? {}), dimmed, highlighted }
};
});
- }, [edges, isolated, selectionPath, draggedIds]);
+ }, [edges, isolated, selectionPath]);
useEffect(() => {
if (!nodesInitialized) return;
@@ -604,14 +629,6 @@ function TraceabilityGraphInner({
onEdgesChange={onEdgesChange}
className="trace-fade-in"
style={{ opacity: fitted ? 1 : 0 }}
- onNodeDragStart={(_, node) =>
- setDraggedIds((prev) => {
- if (prev.has(node.id)) return prev;
- const next = new Set(prev);
- next.add(node.id);
- return next;
- })
- }
nodeTypes={nodeTypes}
edgeTypes={edgeTypes}
proOptions={proOptions}
@@ -642,6 +659,9 @@ function TraceabilityGraphInner({
if (data?.kind === "entity") {
return entityStatusMeta(data.entity?.status).color;
}
+ if (data?.kind === "entityGroup") {
+ return entityStatusMeta(data.cluster?.status).color;
+ }
return ACTIVITY_KIND_META[activityKindFor(data?.activity?.type)]
.color;
}}
@@ -673,6 +693,7 @@ function TraceabilityGraphInner({
onOpenChange={setSearchOpen}
payload={payload}
onSelect={(id) => selectNode(id)}
+ resolveNodeId={resolveNodeId}
/>
{isExpanding && (
diff --git a/apps/erp/app/modules/inventory/ui/Traceability/TraceabilitySidebar.tsx b/apps/erp/app/modules/inventory/ui/Traceability/TraceabilitySidebar.tsx
index e3da5da08e..8906f2a8bd 100644
--- a/apps/erp/app/modules/inventory/ui/Traceability/TraceabilitySidebar.tsx
+++ b/apps/erp/app/modules/inventory/ui/Traceability/TraceabilitySidebar.tsx
@@ -19,9 +19,12 @@ import {
} from "react-icons/lu";
import { Link, useFetcher } from "react-router";
import type { Activity, TrackedEntity } from "~/modules/inventory";
+import { path } from "~/utils/path";
import { capitalize, copyToClipboard } from "~/utils/string";
import { AttributeList, hasRenderedAttributes } from "./attributeRenderers";
import { ContainmentList } from "./ContainmentList";
+import type { ClusterMember, EntityCluster } from "./cluster";
+import { edgeKey } from "./cluster";
import {
ACTIVITY_KIND_META,
activityKindFor,
@@ -40,6 +43,14 @@ import {
type SidebarProps = {
entity: TrackedEntity | null;
activity: Activity | null;
+ /** Set when a serial group node is selected instead of a single entity. */
+ cluster?: EntityCluster | null;
+ /** Every cluster in the current graph, for collapsing an activity's
+ * input/output lists. */
+ clusters?: EntityCluster[];
+ /** Member to scroll to and highlight — set when search picked a clustered
+ * serial, whose group node got selected in its place. */
+ highlightMemberId?: string | null;
payload?: LineagePayload;
onSelect?: (id: string) => void;
selectedIds: string[];
@@ -50,6 +61,9 @@ type SidebarProps = {
export function TraceabilitySidebar({
entity,
activity,
+ cluster = null,
+ clusters,
+ highlightMemberId = null,
payload,
onSelect,
selectedIds,
@@ -58,16 +72,30 @@ export function TraceabilitySidebar({
}: SidebarProps) {
const { t } = useLingui();
const selectedNode = entity ?? activity;
- const selectedNodeType = entity ? "entity" : "activity";
+ const selectedNodeType = cluster ? "group" : entity ? "entity" : "activity";
const selectedNodeAttributes = (
entity ? (entity.attributes ?? {}) : (activity?.attributes ?? {})
) as Record<string, any>;
- const headline = entity
- ? entityHeadline(entity)
- : activity
- ? (activity.type ?? activity.id)
- : "No selection";
+ const clusterByMember = useMemo(() => {
+ const m = new Map<string, EntityCluster>();
+ for (const c of clusters ?? []) {
+ for (const member of c.members) m.set(member.id, c);
+ }
+ return m;
+ }, [clusters]);
+
+ const headline = cluster
+ ? cluster.headline
+ : entity
+ ? entityHeadline(entity)
+ : activity
+ ? (activity.type ?? activity.id)
+ : "No selection";
+
+ // `selectedNode` is null for a cluster, so the header and the Copy ID button
+ // both read from here rather than each deriving the id separately.
+ const copyId = cluster ? cluster.id : (selectedNode?.id ?? "");
const sourceDoc = entity?.sourceDocument ?? activity?.sourceDocument;
const sourceDocId = entity?.sourceDocumentId ?? activity?.sourceDocumentId;
@@ -94,10 +122,27 @@ export function TraceabilitySidebar({
const consumedBy: RelatedActivity[] = [];
const movedBy: RelatedActivity[] = [];
const splits: RelatedActivity[] = [];
- const inputs: RelatedEntity[] = [];
- const outputs: RelatedEntity[] = [];
+ const inputs: RelatedEntityItem[] = [];
+ const outputs: RelatedEntityItem[] = [];
- if (entity) {
+ if (cluster) {
+ // Every member sits on the same edges by construction — one row per
+ // signature entry, carrying the summed quantity.
+ for (const entry of cluster.signature) {
+ const a = activityById.get(entry.activityId);
+ if (!a) continue;
+ const quantity =
+ cluster.quantitiesByEdge[edgeKey(entry.activityId, entry.side)] ??
+ 0;
+ if (entry.side === "output") {
+ producedBy.push({ activity: a, quantity });
+ } else if (isMovementActivity(a.type)) {
+ movedBy.push({ activity: a, quantity });
+ } else {
+ consumedBy.push({ activity: a, quantity });
+ }
+ }
+ } else if (entity) {
// A historical split survivor is recorded as both input and output of
// its own Split activity. That self-loop is neither production nor
// consumption — surface it as a Split instead of lying on both sides.
@@ -145,20 +190,46 @@ export function TraceabilitySidebar({
}
}
} else if (activity) {
- for (const i of payload.inputs) {
- if (i.trackedActivityId !== activity.id) continue;
- const e = entityById.get(i.trackedEntityId);
- if (e) inputs.push({ entity: e, quantity: i.quantity });
- }
- for (const o of payload.outputs) {
- if (o.trackedActivityId !== activity.id) continue;
- const e = entityById.get(o.trackedEntityId);
- if (e) outputs.push({ entity: e, quantity: o.quantity });
- }
+ // Clustered members collapse into one row per group — a 50-serial fan
+ // is unreadable as 50 identical lines.
+ const collect = (
+ rows: { trackedEntityId: string; quantity: number }[],
+ into: RelatedEntityItem[]
+ ) => {
+ const clusterTotals = new Map<string, number>();
+ const clusterOrder: EntityCluster[] = [];
+ for (const row of rows) {
+ const memberCluster = clusterByMember.get(row.trackedEntityId);
+ if (memberCluster) {
+ if (!clusterTotals.has(memberCluster.id)) {
+ clusterOrder.push(memberCluster);
+ }
+ clusterTotals.set(
+ memberCluster.id,
+ (clusterTotals.get(memberCluster.id) ?? 0) + row.quantity
+ );
+ continue;
+ }
+ const e = entityById.get(row.trackedEntityId);
+ if (e) into.push({ entity: e, quantity: row.quantity });
+ }
+ for (const c of clusterOrder) {
+ into.push({ cluster: c, quantity: clusterTotals.get(c.id) ?? 0 });
+ }
+ };
+
+ collect(
+ payload.inputs.filter((i) => i.trackedActivityId === activity.id),
+ inputs
+ );
+ collect(
+ payload.outputs.filter((o) => o.trackedActivityId === activity.id),
+ outputs
+ );
}
return { producedBy, consumedBy, movedBy, splits, inputs, outputs };
- }, [payload, entity, activity]);
+ }, [payload, entity, activity, cluster, clusterByMember]);
const stepRecordsFetcher = useFetcher<{ stepRecords: StepRecord[] }>();
const lastLoadedActivityIdRef = useRef<string | null>(null);
@@ -272,7 +343,14 @@ export function TraceabilitySidebar({
<header className="px-3 pt-3 pb-2.5">
<div className="flex items-center justify-between gap-2 mb-1.5">
<div className="flex items-center gap-1.5 min-w-0">
- {entity ? (
+ {cluster ? (
+ <Badge
+ variant="secondary"
+ className="uppercase tracking-wide text-[10px] shrink-0"
+ >
+ Serial Group
+ </Badge>
+ ) : entity ? (
<Badge
variant="secondary"
className="uppercase tracking-wide text-[10px] shrink-0"
@@ -313,7 +391,7 @@ export function TraceabilitySidebar({
aria-label={t`Copy ID`}
size="sm"
className="p-1 h-7 w-7"
- onClick={() => copyToClipboard(selectedNode?.id ?? "")}
+ onClick={() => copyToClipboard(copyId)}
>
<LuCopy className="w-3.5 h-3.5" />
</Button>
@@ -328,11 +406,34 @@ export function TraceabilitySidebar({
{headline}
</h2>
<p className="text-[11px] text-muted-foreground/70 font-mono break-all leading-4 mt-0.5">
- {selectedNode?.id}
+ {copyId}
</p>
</header>
<div className="flex flex-col divide-y divide-border/40">
+ {cluster && (
+ <Section>
+ <dl className="divide-y divide-border/30">
+ <PropRow label="Status">
+ <TrackedEntityStatus status={cluster.status} />
+ </PropRow>
+ <PropRow label="Serials">
+ <span className="text-sm font-medium tabular-nums">
+ {cluster.members.length}
+ </span>
+ </PropRow>
+ {cluster.readableIdRange && (
+ <PropRow label="Range">
+ <span className="text-sm font-mono">
+ {cluster.readableIdRange[0] === cluster.readableIdRange[1]
+ ? cluster.readableIdRange[0]
+ : `${cluster.readableIdRange[0]}…${cluster.readableIdRange[1]}`}
+ </span>
+ </PropRow>
+ )}
+ </dl>
+ </Section>
+ )}
{(selectedNodeType === "entity" || sourceDoc) && (
<Section>
<dl className="divide-y divide-border/30">
@@ -429,8 +530,8 @@ export function TraceabilitySidebar({
<Section title="Inputs" count={inputs.length}>
<ul className="divide-y divide-border/30">
{inputs.map((item) => (
- <RelatedEntityRow
- key={item.entity.id}
+ <RelatedEntityItemRow
+ key={"cluster" in item ? item.cluster.id : item.entity.id}
item={item}
onSelect={onSelect}
/>
@@ -442,8 +543,8 @@ export function TraceabilitySidebar({
<Section title="Outputs" count={outputs.length}>
<ul className="divide-y divide-border/30">
{outputs.map((item) => (
- <RelatedEntityRow
- key={item.entity.id}
+ <RelatedEntityItemRow
+ key={"cluster" in item ? item.cluster.id : item.entity.id}
item={item}
onSelect={onSelect}
/>
@@ -452,6 +553,15 @@ export function TraceabilitySidebar({
</Section>
)}
+ {cluster && (
+ <Section title="Serials" count={cluster.members.length}>
+ <ClusterMemberList
+ members={cluster.members}
+ highlightMemberId={highlightMemberId}
+ />
+ </Section>
+ )}
+
{containmentsForEntity.length > 0 && (
<Section title="Containments" count={containmentsForEntity.length}>
<ContainmentList items={containmentsForEntity} />
@@ -488,6 +598,8 @@ export function TraceabilitySidebar({
type RelatedActivity = { activity: Activity; quantity: number };
type RelatedEntity = { entity: TrackedEntity; quantity: number };
+type RelatedCluster = { cluster: EntityCluster; quantity: number };
+type RelatedEntityItem = RelatedEntity | RelatedCluster;
function Section({
title,
@@ -646,6 +758,100 @@ function RelatedEntityRow({
);
}
+function RelatedEntityItemRow({
+ item,
+ onSelect
+}: {
+ item: RelatedEntityItem;
+ onSelect?: (id: string) => void;
+}) {
+ if ("cluster" in item) {
+ return <RelatedClusterRow item={item} onSelect={onSelect} />;
+ }
+ return <RelatedEntityRow item={item} onSelect={onSelect} />;
+}
+
+function RelatedClusterRow({
+ item,
+ onSelect
+}: {
+ item: RelatedCluster;
+ onSelect?: (id: string) => void;
+}) {
+ const { cluster } = item;
+ return (
+ <li>
+ <button
+ type="button"
+ onClick={() => onSelect?.(cluster.id)}
+ className={cn(
+ "group w-full flex items-center justify-between gap-2 px-2 py-1.5 text-left rounded-md",
+ "hover:bg-accent/50 transition-colors"
+ )}
+ >
+ <div className="flex items-center gap-2 min-w-0">
+ <TrackedEntityStatus status={cluster.status} />
+ <span className="text-sm truncate">{cluster.headline}</span>
+ <span className="text-[11px] tabular-nums text-muted-foreground shrink-0">
+ ×{cluster.members.length}
+ </span>
+ </div>
+ <div className="flex items-center gap-1 shrink-0">
+ <span className="text-xs tabular-nums text-muted-foreground">
+ {item.quantity}
+ </span>
+ <LuChevronRight className="size-3 text-muted-foreground/60 group-hover:text-foreground transition-colors" />
+ </div>
+ </button>
+ </li>
+ );
+}
+
+/**
+ * A group's members. Plain scroll, no virtualization — even at the 500-entity
+ * ceiling these are single-line text rows, and adding a dependency for that
+ * isn't worth it.
+ */
+function ClusterMemberList({
+ members,
+ highlightMemberId
+}: {
+ members: ClusterMember[];
+ highlightMemberId: string | null;
+}) {
+ const highlightRef = useRef<HTMLLIElement | null>(null);
+
+ useEffect(() => {
+ if (!highlightMemberId) return;
+ highlightRef.current?.scrollIntoView({ block: "nearest" });
+ }, [highlightMemberId]);
+
+ return (
+ <ul className="divide-y divide-border/30 max-h-[320px] overflow-y-auto scrollbar-thin scrollbar-track-transparent scrollbar-thumb-accent">
+ {members.map((member) => {
+ const highlighted = member.id === highlightMemberId;
+ return (
+ <li key={member.id} ref={highlighted ? highlightRef : undefined}>
+ <Link
+ to={`${path.to.traceabilityGraph}?trackedEntityId=${encodeURIComponent(member.id)}`}
+ className={cn(
+ "group w-full flex items-center justify-between gap-2 px-2 py-1.5 text-left rounded-md",
+ "hover:bg-accent/50 transition-colors",
+ highlighted && "bg-accent/60 ring-1 ring-ring"
+ )}
+ >
+ <span className="text-sm font-mono truncate">
+ {member.readableId ?? member.id.slice(0, 8)}
+ </span>
+ <LuChevronRight className="size-3 text-muted-foreground/60 group-hover:text-foreground transition-colors shrink-0" />
+ </Link>
+ </li>
+ );
+ })}
+ </ul>
+ );
+}
+
function StepRecordsSkeleton() {
return (
<ul className="divide-y divide-border/30">
diff --git a/apps/erp/app/modules/inventory/ui/Traceability/cluster.test.ts b/apps/erp/app/modules/inventory/ui/Traceability/cluster.test.ts
new file mode 100644
index 0000000000..db9ae0f198
--- /dev/null
+++ b/apps/erp/app/modules/inventory/ui/Traceability/cluster.test.ts
@@ -0,0 +1,296 @@
+import { describe, expect, it } from "vitest";
+import type {
+ ActivityInput,
+ ActivityOutput,
+ TrackedEntity
+} from "~/modules/inventory";
+import { clusterEntities, edgeKey } from "./cluster";
+
+type EntityOverrides = Partial<
+ Pick<
+ TrackedEntity,
+ | "id"
+ | "readableId"
+ | "quantity"
+ | "status"
+ | "itemId"
+ | "sourceDocumentReadableId"
+ >
+>;
+
+const entity = (id: string, over: EntityOverrides = {}): TrackedEntity =>
+ ({
+ id,
+ readableId: id,
+ quantity: 1,
+ status: "Available",
+ itemId: "PART-1",
+ sourceDocumentReadableId: "PART-1",
+ ...over
+ }) as TrackedEntity;
+
+const input = (activityId: string, entityId: string, quantity = 1) =>
+ ({
+ trackedActivityId: activityId,
+ trackedEntityId: entityId,
+ quantity
+ }) satisfies ActivityInput;
+
+const output = (activityId: string, entityId: string, quantity = 1) =>
+ ({
+ trackedActivityId: activityId,
+ trackedEntityId: entityId,
+ quantity
+ }) satisfies ActivityOutput;
+
+/** Every entity is a single-state candidate unless a test says otherwise. */
+const allEligible = (entities: TrackedEntity[]) =>
+ new Set(entities.map((e) => e.id));
+
+const run = (
+ entities: TrackedEntity[],
+ inputs: ActivityInput[],
+ outputs: ActivityOutput[],
+ opts: Partial<Parameters<typeof clusterEntities>[1]> = {}
+) =>
+ clusterEntities(
+ { entities, inputs, outputs },
+ { eligibleIds: allEligible(entities), ...opts }
+ );
+
+describe("clusterEntities", () => {
+ it("clusters 3 siblings produced by the same job", () => {
+ const entities = ["S1", "S2", "S3"].map((id) => entity(id));
+ const { clusters, memberToCluster } = run(
+ entities,
+ [],
+ entities.map((e) => output("JOB", e.id))
+ );
+
+ expect(clusters).toHaveLength(1);
+ expect(clusters[0].members.map((m) => m.id)).toEqual(["S1", "S2", "S3"]);
+ expect(clusters[0].readableIdRange).toEqual(["S1", "S3"]);
+ expect(clusters[0].signature).toEqual([
+ { activityId: "JOB", side: "output" }
+ ]);
+ expect(memberToCluster).toEqual({
+ S1: clusters[0].id,
+ S2: clusters[0].id,
+ S3: clusters[0].id
+ });
+ });
+
+ it("leaves 2 siblings ungrouped — below the threshold", () => {
+ const entities = ["S1", "S2"].map((id) => entity(id));
+ const { clusters, memberToCluster } = run(
+ entities,
+ [],
+ entities.map((e) => output("JOB", e.id))
+ );
+
+ expect(clusters).toEqual([]);
+ expect(memberToCluster).toEqual({});
+ });
+
+ it("splits siblings by status — a rejected serial keeps its own story", () => {
+ const entities = [
+ entity("S1"),
+ entity("S2"),
+ entity("S3"),
+ entity("S4", { status: "Rejected" }),
+ entity("S5", { status: "Rejected" }),
+ entity("S6", { status: "Rejected" })
+ ];
+ const { clusters } = run(
+ entities,
+ [],
+ entities.map((e) => output("JOB", e.id))
+ );
+
+ expect(clusters).toHaveLength(2);
+ expect(new Set(clusters.map((c) => c.status))).toEqual(
+ new Set(["Available", "Rejected"])
+ );
+ for (const c of clusters) expect(c.members).toHaveLength(3);
+ });
+
+ it("splits siblings by item even on the same activity", () => {
+ const entities = [
+ entity("A1", { itemId: "PART-A", sourceDocumentReadableId: "PART-A" }),
+ entity("A2", { itemId: "PART-A", sourceDocumentReadableId: "PART-A" }),
+ entity("A3", { itemId: "PART-A", sourceDocumentReadableId: "PART-A" }),
+ entity("B1", { itemId: "PART-B", sourceDocumentReadableId: "PART-B" }),
+ entity("B2", { itemId: "PART-B", sourceDocumentReadableId: "PART-B" }),
+ entity("B3", { itemId: "PART-B", sourceDocumentReadableId: "PART-B" })
+ ];
+ const { clusters } = run(
+ entities,
+ [],
+ entities.map((e) => output("JOB", e.id))
+ );
+
+ expect(clusters).toHaveLength(2);
+ expect(clusters.map((c) => c.headline).sort()).toEqual([
+ "PART-A",
+ "PART-B"
+ ]);
+ });
+
+ it("never merges different items that share a sourceDocumentReadableId", () => {
+ // `sourceDocumentReadableId` is a denormalised display string kept in sync
+ // by a trigger; `itemId` is the identity. The documented rule is "same
+ // item", so a stale or colliding display string must not merge two items.
+ const entities = [
+ entity("A1", { itemId: "PART-A", sourceDocumentReadableId: "SHARED" }),
+ entity("A2", { itemId: "PART-A", sourceDocumentReadableId: "SHARED" }),
+ entity("A3", { itemId: "PART-A", sourceDocumentReadableId: "SHARED" }),
+ entity("B1", { itemId: "PART-B", sourceDocumentReadableId: "SHARED" }),
+ entity("B2", { itemId: "PART-B", sourceDocumentReadableId: "SHARED" }),
+ entity("B3", { itemId: "PART-B", sourceDocumentReadableId: "SHARED" })
+ ];
+ const { clusters } = run(
+ entities,
+ [],
+ entities.map((e) => output("JOB", e.id))
+ );
+
+ expect(clusters).toHaveLength(2);
+ for (const c of clusters) expect(c.members).toHaveLength(3);
+ });
+
+ it("never clusters the traced root", () => {
+ const entities = ["S1", "S2", "S3", "S4"].map((id) => entity(id));
+ const { clusters, memberToCluster } = run(
+ entities,
+ [],
+ entities.map((e) => output("JOB", e.id)),
+ { excludeIds: new Set(["S2"]) }
+ );
+
+ expect(clusters).toHaveLength(1);
+ expect(clusters[0].members.map((m) => m.id)).toEqual(["S1", "S3", "S4"]);
+ expect(memberToCluster.S2).toBeUndefined();
+ });
+
+ it("never clusters quantity != 1 — post-flip batch fragments stay individual", () => {
+ const entities = [
+ entity("L1", { quantity: 12 }),
+ entity("L2", { quantity: 12 }),
+ entity("L3", { quantity: 12 })
+ ];
+ const { clusters } = run(
+ entities,
+ [],
+ entities.map((e) => output("JOB", e.id))
+ );
+
+ expect(clusters).toEqual([]);
+ });
+
+ it("never clusters an ineligible (multi-state) entity", () => {
+ const entities = ["S1", "S2", "S3"].map((id) => entity(id));
+ const { clusters } = run(
+ entities,
+ [],
+ entities.map((e) => output("JOB", e.id)),
+ { eligibleIds: new Set(["S1", "S2"]) }
+ );
+
+ expect(clusters).toEqual([]);
+ });
+
+ it("skips entities with no edges", () => {
+ const entities = ["S1", "S2", "S3"].map((id) => entity(id));
+ const { clusters } = run(entities, [], []);
+
+ expect(clusters).toEqual([]);
+ });
+
+ it("sums member quantities per signature edge", () => {
+ const entities = ["S1", "S2", "S3", "S4"].map((id) => entity(id));
+ const { clusters } = run(
+ entities,
+ entities.map((e) => input("SHIP", e.id)),
+ entities.map((e) => output("JOB", e.id))
+ );
+
+ expect(clusters).toHaveLength(1);
+ expect(clusters[0].quantitiesByEdge).toEqual({
+ [edgeKey("JOB", "output")]: 4,
+ [edgeKey("SHIP", "input")]: 4
+ });
+ expect(clusters[0].signature).toEqual([
+ { activityId: "JOB", side: "output" },
+ { activityId: "SHIP", side: "input" }
+ ]);
+ });
+
+ it("splits a mixed fan: shipped siblings cluster apart from produced-only ones", () => {
+ const shipped = ["S1", "S2", "S3"].map((id) => entity(id));
+ const idle = ["S4", "S5", "S6", "S7"].map((id) => entity(id));
+ const entities = [...shipped, ...idle];
+
+ const { clusters } = run(
+ entities,
+ shipped.map((e) => input("SHIP", e.id)),
+ entities.map((e) => output("JOB", e.id))
+ );
+
+ expect(clusters).toHaveLength(2);
+ const bySize = [...clusters].sort(
+ (a, b) => a.members.length - b.members.length
+ );
+ expect(bySize[0].members.map((m) => m.id)).toEqual(["S1", "S2", "S3"]);
+ expect(bySize[0].signature).toHaveLength(2);
+ expect(bySize[1].members.map((m) => m.id)).toEqual([
+ "S4",
+ "S5",
+ "S6",
+ "S7"
+ ]);
+ expect(bySize[1].signature).toEqual([
+ { activityId: "JOB", side: "output" }
+ ]);
+ });
+
+ it("is insensitive to input/output row order", () => {
+ const entities = ["S1", "S2", "S3"].map((id) => entity(id));
+ const forward = run(
+ entities,
+ [input("SHIP", "S1"), input("SHIP", "S2"), input("SHIP", "S3")],
+ [output("JOB", "S1"), output("JOB", "S2"), output("JOB", "S3")]
+ );
+ const reversed = run(
+ entities,
+ [input("SHIP", "S3"), input("SHIP", "S2"), input("SHIP", "S1")],
+ [output("JOB", "S3"), output("JOB", "S2"), output("JOB", "S1")]
+ );
+
+ expect(reversed.clusters[0].id).toBe(forward.clusters[0].id);
+ expect(reversed.clusters[0].members).toEqual(forward.clusters[0].members);
+ });
+
+ it("honours a custom threshold", () => {
+ const entities = ["S1", "S2"].map((id) => entity(id));
+ const { clusters } = run(
+ entities,
+ [],
+ entities.map((e) => output("JOB", e.id)),
+ { threshold: 2 }
+ );
+
+ expect(clusters).toHaveLength(1);
+ });
+
+ it("ignores duplicate entity rows in the payload", () => {
+ const entities = [entity("S1"), entity("S1"), entity("S2"), entity("S3")];
+ const { clusters } = run(
+ entities,
+ [],
+ [output("JOB", "S1"), output("JOB", "S2"), output("JOB", "S3")]
+ );
+
+ expect(clusters).toHaveLength(1);
+ expect(clusters[0].members.map((m) => m.id)).toEqual(["S1", "S2", "S3"]);
+ });
+});
diff --git a/apps/erp/app/modules/inventory/ui/Traceability/cluster.ts b/apps/erp/app/modules/inventory/ui/Traceability/cluster.ts
new file mode 100644
index 0000000000..7379e60903
--- /dev/null
+++ b/apps/erp/app/modules/inventory/ui/Traceability/cluster.ts
@@ -0,0 +1,234 @@
+import { groupBy } from "@carbon/utils";
+import type {
+ ActivityInput,
+ ActivityOutput,
+ TrackedEntity
+} from "~/modules/inventory";
+
+/**
+ * Serial items at quantity N create N quantity-1 tracked entities by design
+ * (the serial pre-split at job creation). A 50-serial job therefore fans out
+ * into 50 identical nodes hanging off one activity, which drowns the graph.
+ *
+ * This pass collapses siblings that tell the exact same story into a single
+ * group node. "Same story" is an identical edge signature — the exact set of
+ * `(activityId, side)` pairs the entity participates in — plus the same item
+ * and status. Anything with a distinct history keeps its own node.
+ *
+ * Display-only: nothing here touches the payload, the schema, or the server.
+ *
+ * This module is deliberately free of runtime dependencies beyond
+ * `@carbon/utils` — it runs inside the lineage Web Worker.
+ */
+
+/** Reserved node-id prefix. Contains no `::s`, so `stateEntityId` leaves it alone. */
+export const CLUSTER_ID_PREFIX = "cluster:";
+
+export const DEFAULT_CLUSTER_THRESHOLD = 3;
+
+export type ClusterSide = "input" | "output";
+
+export type ClusterMember = {
+ id: string;
+ readableId: string | null;
+ quantity: number;
+};
+
+export type ClusterSignatureEntry = {
+ activityId: string;
+ side: ClusterSide;
+};
+
+export type EntityCluster = {
+ id: string;
+ status: TrackedEntity["status"];
+ itemReadableId: string | null;
+ /** Item headline shown on the node and in the sidebar. */
+ headline: string;
+ /** Ordered by readableId. Carries its own snapshots so consumers never
+ * have to re-resolve members out of a payload. */
+ members: ClusterMember[];
+ readableIdRange: [string, string] | null;
+ signature: ClusterSignatureEntry[];
+ /** `${activityId}:${side}` → summed member quantity on that edge. */
+ quantitiesByEdge: Record<string, number>;
+};
+
+export type ClusterResult = {
+ clusters: EntityCluster[];
+ /** Member entity id → cluster id. A plain Record: this crosses the
+ * Comlink structured-clone boundary out of the worker. */
+ memberToCluster: Record<string, string>;
+};
+
+export function edgeKey(activityId: string, side: ClusterSide): string {
+ return `${activityId}:${side}`;
+}
+
+export function isClusterId(id: string): boolean {
+ return id.startsWith(CLUSTER_ID_PREFIX);
+}
+
+type ClusterInputPayload = {
+ entities: TrackedEntity[];
+ inputs: ActivityInput[];
+ outputs: ActivityOutput[];
+};
+
+type ClusterOptions = {
+ threshold?: number;
+ /** Never cluster these — the traced root must stay individually visible. */
+ excludeIds?: Set<string>;
+ /** Only these are candidates. The caller restricts this to entities that
+ * resolve to a single timeline state; a multi-state entity renders as a
+ * chain of nodes that can't collapse into one. */
+ eligibleIds: Set<string>;
+};
+
+/**
+ * `${activityId}:${side}` pairs an entity participates in, sorted so two
+ * entities on the same edges produce the same string regardless of row order.
+ */
+function signatureOf(
+ entityId: string,
+ inputsByEntity: Record<string, ActivityInput[]>,
+ outputsByEntity: Record<string, ActivityOutput[]>
+): ClusterSignatureEntry[] {
+ const entries: ClusterSignatureEntry[] = [];
+ for (const row of inputsByEntity[entityId] ?? []) {
+ entries.push({ activityId: row.trackedActivityId, side: "input" });
+ }
+ for (const row of outputsByEntity[entityId] ?? []) {
+ entries.push({ activityId: row.trackedActivityId, side: "output" });
+ }
+ entries.sort(
+ (a, b) =>
+ a.activityId.localeCompare(b.activityId) || a.side.localeCompare(b.side)
+ );
+ return entries;
+}
+
+export function clusterEntities(
+ payload: ClusterInputPayload,
+ opts: ClusterOptions
+): ClusterResult {
+ const threshold = opts.threshold ?? DEFAULT_CLUSTER_THRESHOLD;
+ const excludeIds = opts.excludeIds ?? new Set<string>();
+ const { eligibleIds } = opts;
+
+ const inputsByEntity = groupBy(payload.inputs, (i) => i.trackedEntityId);
+ const outputsByEntity = groupBy(payload.outputs, (o) => o.trackedEntityId);
+
+ type Candidate = {
+ entity: TrackedEntity;
+ signature: ClusterSignatureEntry[];
+ groupKey: string;
+ };
+
+ const candidates: Candidate[] = [];
+ const seen = new Set<string>();
+
+ for (const entity of payload.entities) {
+ if (!entity?.id || seen.has(entity.id)) continue;
+ seen.add(entity.id);
+ if (excludeIds.has(entity.id)) continue;
+ if (!eligibleIds.has(entity.id)) continue;
+ if (Number(entity.quantity) !== 1) continue;
+
+ const signature = signatureOf(entity.id, inputsByEntity, outputsByEntity);
+ // An entity with no edges is an isolated node — nothing to collapse.
+ if (signature.length === 0) continue;
+
+ // Key on the real `itemId`, not just the denormalised
+ // `sourceDocumentReadableId` display string — the documented rule is "same
+ // item", and identity should not ride on a value a trigger keeps in sync.
+ // Both are included so entities missing one still discriminate on the other.
+ //
+ // JSON rather than a delimiter join: these are data values, so any
+ // separator we picked could in principle appear inside one and collapse
+ // two different groups into one.
+ const groupKey = JSON.stringify([
+ entity.status,
+ entity.itemId ?? "",
+ entity.sourceDocumentReadableId ?? "",
+ signature.map((s) => edgeKey(s.activityId, s.side))
+ ]);
+
+ candidates.push({ entity, signature, groupKey });
+ }
+
+ const clusters: EntityCluster[] = [];
+ const memberToCluster: Record<string, string> = {};
+
+ const grouped = groupBy(candidates, (c) => c.groupKey);
+ // Deterministic cluster order — `groupBy` returns an object, whose key order
+ // is insertion order for these string keys, but sorting makes it explicit.
+ for (const groupKey of Object.keys(grouped).sort()) {
+ const group = grouped[groupKey];
+ if (group.length < threshold) continue;
+
+ const sorted = [...group].sort((a, b) =>
+ (a.entity.readableId ?? a.entity.id).localeCompare(
+ b.entity.readableId ?? b.entity.id
+ )
+ );
+ const first = sorted[0].entity;
+ const signature = sorted[0].signature;
+
+ const quantitiesByEdge: Record<string, number> = {};
+ for (const { entity } of sorted) {
+ for (const row of inputsByEntity[entity.id] ?? []) {
+ const key = edgeKey(row.trackedActivityId, "input");
+ quantitiesByEdge[key] = (quantitiesByEdge[key] ?? 0) + row.quantity;
+ }
+ for (const row of outputsByEntity[entity.id] ?? []) {
+ const key = edgeKey(row.trackedActivityId, "output");
+ quantitiesByEdge[key] = (quantitiesByEdge[key] ?? 0) + row.quantity;
+ }
+ }
+
+ const id = `${CLUSTER_ID_PREFIX}${clusterHash(groupKey)}`;
+ const readableIds = sorted
+ .map((c) => c.entity.readableId)
+ .filter((r): r is string => !!r);
+
+ clusters.push({
+ id,
+ status: first.status,
+ itemReadableId: first.sourceDocumentReadableId ?? null,
+ headline:
+ first.sourceDocumentReadableId ?? first.itemId ?? first.id.slice(0, 8),
+ members: sorted.map(({ entity }) => ({
+ id: entity.id,
+ readableId: entity.readableId,
+ quantity: Number(entity.quantity)
+ })),
+ readableIdRange:
+ readableIds.length > 0
+ ? [readableIds[0], readableIds[readableIds.length - 1]]
+ : null,
+ signature,
+ quantitiesByEdge
+ });
+
+ for (const { entity } of sorted) memberToCluster[entity.id] = id;
+ }
+
+ return { clusters, memberToCluster };
+}
+
+/**
+ * Stable short hash of the group key. Only needs to be collision-free within
+ * one graph, and the key itself is already unique per cluster — this exists so
+ * node ids stay short and don't leak an entity id list into the DOM.
+ */
+function clusterHash(key: string): string {
+ let h1 = 0x811c9dc5;
+ let h2 = 0x01000193;
+ for (let i = 0; i < key.length; i++) {
+ const c = key.charCodeAt(i);
+ h1 = Math.imul(h1 ^ c, 0x01000193) >>> 0;
+ h2 = Math.imul(h2 ^ c, 0x85ebca6b) >>> 0;
+ }
+ return `${h1.toString(36)}${h2.toString(36)}`;
+}
diff --git a/apps/erp/app/modules/inventory/ui/Traceability/edges/QuantityEdge.tsx b/apps/erp/app/modules/inventory/ui/Traceability/edges/QuantityEdge.tsx
index 074b1e6865..fabd9e3632 100644
--- a/apps/erp/app/modules/inventory/ui/Traceability/edges/QuantityEdge.tsx
+++ b/apps/erp/app/modules/inventory/ui/Traceability/edges/QuantityEdge.tsx
@@ -2,10 +2,17 @@ import {
BaseEdge,
EdgeLabelRenderer,
type EdgeProps,
- getSimpleBezierPath
+ getSimpleBezierPath,
+ getSmoothStepPath
} from "@xyflow/react";
import { memo } from "react";
-import type { LineageEdgeData } from "../utils";
+import {
+ EDGE_BORDER_RADIUS,
+ EDGE_OFFSET,
+ EDGE_STYLE,
+ edgeLabelPoint,
+ type LineageEdgeData
+} from "../utils";
type Props = EdgeProps & {
data?: LineageEdgeData & {
@@ -13,7 +20,6 @@ type Props = EdgeProps & {
isReject?: boolean;
isBackEdge?: boolean;
highlighted?: boolean;
- points?: { x: number; y: number }[];
};
};
@@ -27,14 +33,47 @@ function QuantityEdgeImpl({
targetPosition,
data
}: Props) {
- const [edgePath, labelX, labelY] = getSimpleBezierPath({
- sourceX,
- sourceY,
- sourcePosition,
- targetX,
- targetY,
- targetPosition
- });
+ // Keep this in step with EDGE_STYLE — `edgeLabelPoint` samples the matching
+ // geometry, so the two switch together and labels stay on the line.
+ const [edgePath, midX, midY] =
+ EDGE_STYLE === "bezier"
+ ? getSimpleBezierPath({
+ sourceX,
+ sourceY,
+ sourcePosition,
+ targetX,
+ targetY,
+ targetPosition
+ })
+ : getSmoothStepPath({
+ sourceX,
+ sourceY,
+ sourcePosition,
+ targetX,
+ targetY,
+ targetPosition,
+ borderRadius: EDGE_BORDER_RADIUS,
+ offset: EDGE_OFFSET
+ });
+
+ // Parallel edges between the same two ranks all put their label at the same
+ // midpoint, so the pills stack. Layout resolves how far along each path the
+ // label should sit; evaluate that here against the LIVE endpoints so the
+ // label rides the path when a node is dragged.
+ const labelPoint =
+ data?.labelT === undefined
+ ? null
+ : edgeLabelPoint(
+ data.labelT,
+ sourceX,
+ sourceY,
+ sourcePosition,
+ targetX,
+ targetY,
+ targetPosition
+ );
+ const labelX = labelPoint?.x ?? midX;
+ const labelY = labelPoint?.y ?? midY;
const isReject = !!data?.isReject;
const isBackEdge = !!data?.isBackEdge;
diff --git a/apps/erp/app/modules/inventory/ui/Traceability/hooks/useProbeBoundary.ts b/apps/erp/app/modules/inventory/ui/Traceability/hooks/useProbeBoundary.ts
index ebd60f223f..c920986765 100644
--- a/apps/erp/app/modules/inventory/ui/Traceability/hooks/useProbeBoundary.ts
+++ b/apps/erp/app/modules/inventory/ui/Traceability/hooks/useProbeBoundary.ts
@@ -7,6 +7,8 @@ type Boundary = { incoming: Set<string>; outgoing: Set<string> };
type Args = {
payload: LineagePayload;
boundaryByNode: Boundary;
+ /** Member entity id → cluster id. */
+ memberToCluster: Record<string, string>;
markExpandable: (id: string) => void;
markExhausted: (id: string) => void;
probeCacheRef: MutableRefObject<Map<string, LineagePayload>>;
@@ -16,6 +18,7 @@ type Args = {
export function useProbeBoundary({
payload,
boundaryByNode,
+ memberToCluster,
markExpandable,
markExhausted,
probeCacheRef,
@@ -25,6 +28,10 @@ export function useProbeBoundary({
let cancelled = false;
const candidates = payload.entities.filter((e) => {
if (probedRef.current.has(e.id)) return false;
+ // A clustered member's edges belong to its group node, so it always looks
+ // like a boundary. Probing it would fire one request per member and mark
+ // an id that has no node to render the indicator on.
+ if (memberToCluster[e.id]) return false;
const hasIn = boundaryByNode.incoming.has(e.id);
const hasOut = boundaryByNode.outgoing.has(e.id);
return !hasIn || !hasOut;
@@ -66,6 +73,7 @@ export function useProbeBoundary({
}, [
payload,
boundaryByNode,
+ memberToCluster,
markExpandable,
markExhausted,
probeCacheRef,
diff --git a/apps/erp/app/modules/inventory/ui/Traceability/jobNode.test.ts b/apps/erp/app/modules/inventory/ui/Traceability/jobNode.test.ts
new file mode 100644
index 0000000000..183377180e
--- /dev/null
+++ b/apps/erp/app/modules/inventory/ui/Traceability/jobNode.test.ts
@@ -0,0 +1,242 @@
+import { describe, expect, it } from "vitest";
+import type { LineagePayload } from "~/modules/inventory/lineage.server";
+import type { TrackedEntity } from "~/modules/inventory/types";
+import { getEntityJobId, jobNodeId, withJobNode } from "./jobNode";
+
+const JOB = "job_1";
+
+const seed = (id: string, over: Partial<TrackedEntity> = {}): TrackedEntity =>
+ ({
+ id,
+ readableId: id,
+ quantity: 1,
+ status: "Reserved",
+ itemId: "PART-1",
+ sourceDocument: "Item",
+ sourceDocumentId: "PART-1",
+ sourceDocumentReadableId: "PART-1",
+ attributes: { Job: JOB },
+ ...over
+ }) as TrackedEntity;
+
+const payload = (over: Partial<LineagePayload> = {}): LineagePayload => ({
+ entities: [],
+ activities: [],
+ inputs: [],
+ outputs: [],
+ ...over
+});
+
+/** What startProductionEvent writes: one per operation per unit. */
+const productionEvent = (
+ id: string,
+ type: string,
+ createdAt = "2026-08-01T10:00:00Z"
+) =>
+ ({
+ id,
+ type,
+ sourceDocument: "Production Event",
+ sourceDocumentId: `pe_${id}`,
+ createdAt,
+ attributes: { Job: JOB }
+ }) as unknown as LineagePayload["activities"][number];
+
+describe("getEntityJobId", () => {
+ it("reads the Job attribute", () => {
+ expect(getEntityJobId(seed("e1"))).toBe(JOB);
+ });
+ it("returns null when there is no Job attribute", () => {
+ expect(getEntityJobId(seed("e1", { attributes: {} }))).toBeNull();
+ });
+ it("tolerates a missing or non-object attributes blob", () => {
+ expect(getEntityJobId(undefined)).toBeNull();
+ expect(
+ getEntityJobId(seed("e1", { attributes: null as never }))
+ ).toBeNull();
+ expect(
+ getEntityJobId(seed("e1", { attributes: ["nope"] as never }))
+ ).toBeNull();
+ });
+});
+
+describe("withJobNode", () => {
+ it("synthesises a node only when the job has no activity to hang from", () => {
+ const result = withJobNode(
+ payload({ entities: [seed("e1"), seed("e2")] }),
+ JOB,
+ "JOB-0001"
+ );
+
+ expect(result.activities.map((a) => a.id)).toEqual([jobNodeId(JOB)]);
+ expect(result.outputs).toEqual([
+ { trackedActivityId: jobNodeId(JOB), trackedEntityId: "e1", quantity: 1 },
+ { trackedActivityId: jobNodeId(JOB), trackedEntityId: "e2", quantity: 1 }
+ ]);
+ });
+
+ it("hangs un-produced seeds off the production activity, not a job node", () => {
+ const result = withJobNode(
+ payload({
+ entities: [seed("e1"), seed("e2")],
+ activities: [productionEvent("pe1", "Manufacturing")],
+ outputs: [
+ { trackedActivityId: "pe1", trackedEntityId: "e1", quantity: 1 }
+ ]
+ }),
+ JOB,
+ "JOB-0001"
+ );
+
+ // No separate "Job" node — the production activity absorbs its role.
+ expect(result.activities.map((a) => a.id)).toEqual(["pe1"]);
+ expect(result.outputs).toEqual([
+ { trackedActivityId: "pe1", trackedEntityId: "e1", quantity: 1 },
+ { trackedActivityId: "pe1", trackedEntityId: "e2", quantity: 1 }
+ ]);
+ });
+
+ it("anchors on the EARLIEST activity — where a unit enters production", () => {
+ const result = withJobNode(
+ payload({
+ entities: [seed("e1")],
+ activities: [
+ productionEvent("pe3", "Inspect (Labor)", "2026-08-01T12:00:00Z"),
+ productionEvent("pe1", "Weld (Labor)", "2026-08-01T10:00:00Z"),
+ productionEvent("pe2", "Assemble (Setup)", "2026-08-01T11:00:00Z")
+ ]
+ }),
+ JOB,
+ "JOB-0001"
+ );
+
+ expect(result.outputs).toEqual([
+ { trackedActivityId: "pe1", trackedEntityId: "e1", quantity: 1 }
+ ]);
+ });
+
+ it("ignores another job's activities when picking the anchor", () => {
+ const foreign = {
+ id: "pe_other",
+ type: "Weld (Labor)",
+ createdAt: "2026-01-01T00:00:00Z",
+ attributes: { Job: "job_2" }
+ } as unknown as LineagePayload["activities"][number];
+
+ const result = withJobNode(
+ payload({
+ entities: [seed("e1")],
+ activities: [foreign, productionEvent("pe1", "Manufacturing")]
+ }),
+ JOB,
+ "JOB-0001"
+ );
+
+ expect(result.outputs).toEqual([
+ { trackedActivityId: "pe1", trackedEntityId: "e1", quantity: 1 }
+ ]);
+ });
+
+ it("does NOT also claim an entity a real activity already produced", () => {
+ // The duplication: the serial had two parents, the production event and
+ // the job, reading as two separate origins for one entity.
+ const result = withJobNode(
+ payload({
+ entities: [seed("e1")],
+ activities: [productionEvent("pe1", "Weld (Labor)")],
+ outputs: [
+ { trackedActivityId: "pe1", trackedEntityId: "e1", quantity: 1 }
+ ]
+ }),
+ JOB,
+ "JOB-0001"
+ );
+
+ expect(result.activities.map((a) => a.id)).toEqual(["pe1"]);
+ expect(result.outputs).toEqual([
+ { trackedActivityId: "pe1", trackedEntityId: "e1", quantity: 1 }
+ ]);
+ });
+
+ it("drops the job node entirely once production covers every seed", () => {
+ const before = payload({
+ entities: [seed("e1"), seed("e2")],
+ activities: [productionEvent("pe1", "Weld (Labor)")],
+ outputs: [
+ { trackedActivityId: "pe1", trackedEntityId: "e1", quantity: 1 },
+ { trackedActivityId: "pe1", trackedEntityId: "e2", quantity: 1 }
+ ]
+ });
+
+ expect(withJobNode(before, JOB, "JOB-0001")).toEqual(before);
+ });
+
+ it("keeps every production event — operations are never collapsed", () => {
+ const result = withJobNode(
+ payload({
+ entities: [seed("e1"), seed("e2")],
+ activities: [
+ productionEvent("pe1", "Weld (Labor)"),
+ productionEvent("pe2", "Assemble (Setup)"),
+ productionEvent("pe3", "Inspect (Labor)")
+ ],
+ outputs: [
+ { trackedActivityId: "pe1", trackedEntityId: "e1", quantity: 1 }
+ ]
+ }),
+ JOB,
+ "JOB-0001"
+ );
+
+ // Every operation survives; e2 attaches to the earliest rather than
+ // spawning a parallel job node.
+ expect(result.activities.map((a) => a.id)).toEqual(["pe1", "pe2", "pe3"]);
+ expect(result.outputs).toEqual([
+ { trackedActivityId: "pe1", trackedEntityId: "e1", quantity: 1 },
+ { trackedActivityId: "pe1", trackedEntityId: "e2", quantity: 1 }
+ ]);
+ });
+
+ it("ignores entities belonging to a different job", () => {
+ const result = withJobNode(
+ payload({
+ entities: [seed("e1"), seed("other", { attributes: { Job: "job_2" } })]
+ }),
+ JOB,
+ "JOB-0001"
+ );
+
+ expect(result.outputs.map((o) => o.trackedEntityId)).toEqual(["e1"]);
+ });
+
+ it("ignores entities that are neither Reserved nor Item-sourced", () => {
+ const result = withJobNode(
+ payload({
+ entities: [
+ seed("e1", { status: "Available", sourceDocument: "Receipt" })
+ ]
+ }),
+ JOB,
+ "JOB-0001"
+ );
+
+ expect(result.outputs).toEqual([]);
+ expect(result.activities).toEqual([]);
+ });
+
+ it("does not duplicate an existing job node", () => {
+ const existing = {
+ id: jobNodeId(JOB),
+ type: "Job",
+ attributes: {}
+ } as unknown as LineagePayload["activities"][number];
+
+ const result = withJobNode(
+ payload({ entities: [seed("e1")], activities: [existing] }),
+ JOB,
+ "JOB-0001"
+ );
+
+ expect(result.activities).toHaveLength(1);
+ });
+});
diff --git a/apps/erp/app/modules/inventory/ui/Traceability/jobNode.ts b/apps/erp/app/modules/inventory/ui/Traceability/jobNode.ts
new file mode 100644
index 0000000000..0202a69979
--- /dev/null
+++ b/apps/erp/app/modules/inventory/ui/Traceability/jobNode.ts
@@ -0,0 +1,117 @@
+import type { LineagePayload } from "~/modules/inventory/lineage.server";
+import type { TrackedEntity } from "~/modules/inventory/types";
+
+/**
+ * Where a job's not-yet-produced entities hang.
+ *
+ * A job's real activities are its PRODUCTION EVENTS — `startProductionEvent`
+ * writes one per operation per unit, typed "<operation> (<event type>)". The
+ * job itself has no `trackedActivity` row.
+ *
+ * Entities the item event-handlers seed at job creation have no producing
+ * activity yet and would float unconnected. Rather than stand up a separate
+ * "Job" node beside the production activity — two nodes for one origin — those
+ * seeds attach to the job's own production activity, which is what the job
+ * node was standing in for.
+ *
+ * TRADE-OFF: an un-produced seed hanging off a production activity asserts a
+ * production event that has not happened. It reads as "this is where this unit
+ * enters production", which is why the anchor is the EARLIEST activity rather
+ * than an arbitrary one. A job with no activities at all has nothing to attach
+ * to, so there the synthetic node is still the only option.
+ *
+ * Pure and server-free so it can be unit tested; the graph route imports it.
+ */
+
+export const JOB_NODE_PREFIX = "job:";
+
+export function jobNodeId(jobId: string): string {
+ return `${JOB_NODE_PREFIX}${jobId}`;
+}
+
+export function getEntityJobId(
+ entity: TrackedEntity | undefined
+): string | null {
+ const attrs = entity?.attributes;
+ if (!attrs || typeof attrs !== "object" || Array.isArray(attrs)) return null;
+ const job = (attrs as Record<string, unknown>).Job;
+ return typeof job === "string" && job.length > 0 ? job : null;
+}
+
+/**
+ * The job's own production activity to hang un-produced seeds from: the
+ * earliest one, i.e. where a unit enters production. Sorted by `createdAt`
+ * with an id tie-break so the choice is stable across runs.
+ */
+function productionAnchorId(
+ payload: LineagePayload,
+ jobId: string
+): string | null {
+ const own = payload.activities
+ .filter((a) => {
+ if (a.id === jobNodeId(jobId)) return false;
+ const attrs = a.attributes as Record<string, unknown> | null | undefined;
+ return attrs?.Job === jobId;
+ })
+ .sort(
+ (a, b) =>
+ (a.createdAt ?? "").localeCompare(b.createdAt ?? "") ||
+ a.id.localeCompare(b.id)
+ );
+ return own[0]?.id ?? null;
+}
+
+export function withJobNode(
+ payload: LineagePayload,
+ jobId: string,
+ jobReadableId: string
+): LineagePayload {
+ const id = jobNodeId(jobId);
+
+ // Anything a real activity already produced is spoken for.
+ const producedEntityIds = new Set(
+ payload.outputs.map((o) => o.trackedEntityId)
+ );
+
+ const orphanSeeds = payload.entities.filter((entity) => {
+ if (getEntityJobId(entity) !== jobId) return false;
+ if (producedEntityIds.has(entity.id)) return false;
+ return entity.status === "Reserved" || entity.sourceDocument === "Item";
+ });
+
+ // Nothing left to anchor — the job's real activities tell the whole story.
+ if (orphanSeeds.length === 0) return payload;
+
+ const anchorId = productionAnchorId(payload, jobId);
+ const existingActivityIds = new Set(payload.activities.map((a) => a.id));
+
+ // Prefer the job's real production activity; only synthesise a node when the
+ // job has none at all (created, nothing started).
+ const target = anchorId ?? id;
+ const needsSyntheticNode = target === id && !existingActivityIds.has(id);
+
+ return {
+ ...payload,
+ activities: needsSyntheticNode
+ ? [
+ {
+ id,
+ type: "Job",
+ sourceDocument: "Job",
+ sourceDocumentId: jobId,
+ sourceDocumentReadableId: jobReadableId,
+ attributes: { Job: jobId }
+ },
+ ...payload.activities
+ ]
+ : payload.activities,
+ outputs: [
+ ...payload.outputs,
+ ...orphanSeeds.map((entity) => ({
+ trackedActivityId: target,
+ trackedEntityId: entity.id,
+ quantity: entity.quantity
+ }))
+ ]
+ };
+}
diff --git a/apps/erp/app/modules/inventory/ui/Traceability/nodes/ActivityNode.tsx b/apps/erp/app/modules/inventory/ui/Traceability/nodes/ActivityNode.tsx
index 09e68f5fad..cf1e87479a 100644
--- a/apps/erp/app/modules/inventory/ui/Traceability/nodes/ActivityNode.tsx
+++ b/apps/erp/app/modules/inventory/ui/Traceability/nodes/ActivityNode.tsx
@@ -12,7 +12,12 @@ type Props = NodeProps & {
};
};
-function ActivityNodeImpl({ data, selected }: Props) {
+function ActivityNodeImpl({
+ data,
+ selected,
+ sourcePosition,
+ targetPosition
+}: Props) {
const activity = data.activity;
const kind = activityKindFor(activity.type);
const meta = ACTIVITY_KIND_META[kind];
@@ -33,12 +38,12 @@ function ActivityNodeImpl({ data, selected }: Props) {
>
<Handle
type="target"
- position={Position.Top}
+ position={targetPosition ?? Position.Top}
className="!opacity-0 !pointer-events-none !top-1/2 !left-1/2 !-translate-x-1/2 !-translate-y-1/2 !w-1 !h-1 !min-w-0 !min-h-0 !border-0"
/>
<Handle
type="source"
- position={Position.Bottom}
+ position={sourcePosition ?? Position.Bottom}
className="!opacity-0 !pointer-events-none !top-1/2 !left-1/2 !-translate-x-1/2 !-translate-y-1/2 !w-1 !h-1 !min-w-0 !min-h-0 !border-0"
/>
<svg
diff --git a/apps/erp/app/modules/inventory/ui/Traceability/nodes/EntityGroupNode.tsx b/apps/erp/app/modules/inventory/ui/Traceability/nodes/EntityGroupNode.tsx
new file mode 100644
index 0000000000..6c3dfcf1dd
--- /dev/null
+++ b/apps/erp/app/modules/inventory/ui/Traceability/nodes/EntityGroupNode.tsx
@@ -0,0 +1,150 @@
+import { cn } from "@carbon/react";
+import { Handle, type NodeProps, Position, useStore } from "@xyflow/react";
+import { memo } from "react";
+import { NODE_RADIUS, NODE_SIZE } from "../constants";
+import { entityStatusMeta } from "../metadata";
+import type { EntityGroupNodeData } from "../utils";
+
+type Props = NodeProps & {
+ data: EntityGroupNodeData & {
+ selected?: boolean;
+ };
+};
+
+/**
+ * A fan of identical serial siblings drawn as one node. Same 44px footprint as
+ * EntityNode so the worker's dagre layout needs no special case; the stacked
+ * circles behind it are what say "this is many".
+ *
+ * No expand toggles: expanding a 50-member group would fetch 50 lineages.
+ * Members are reached through the sidebar's list instead.
+ */
+function EntityGroupNodeImpl({
+ data,
+ selected,
+ sourcePosition,
+ targetPosition
+}: Props) {
+ const cluster = data.cluster;
+ const count = cluster.members.length;
+
+ const zoomedIn = useStore((s) => s.transform[2] > 0.5);
+ const showLabel = zoomedIn || selected;
+
+ const meta = entityStatusMeta(cluster.status);
+ const Icon = meta.icon;
+ const isRejected = cluster.status === "Rejected";
+ const radius = NODE_RADIUS;
+ const size = NODE_SIZE;
+ const iconSize = 18;
+
+ const range = cluster.readableIdRange;
+ const rangeLabel =
+ range && range[0] !== range[1] ? `${range[0]}…${range[1]}` : range?.[0];
+
+ return (
+ <div
+ className={cn("relative", data.dimmed && "opacity-15")}
+ style={{ width: size, height: size, zIndex: 10 }}
+ >
+ <Handle
+ type="target"
+ position={targetPosition ?? Position.Top}
+ className="!opacity-0 !pointer-events-none !top-1/2 !left-1/2 !-translate-x-1/2 !-translate-y-1/2 !w-1 !h-1 !min-w-0 !min-h-0 !border-0"
+ />
+ <Handle
+ type="source"
+ position={sourcePosition ?? Position.Bottom}
+ className="!opacity-0 !pointer-events-none !top-1/2 !left-1/2 !-translate-x-1/2 !-translate-y-1/2 !w-1 !h-1 !min-w-0 !min-h-0 !border-0"
+ />
+ <svg
+ width={size}
+ height={size}
+ className="absolute inset-0 overflow-visible"
+ aria-hidden
+ >
+ {selected && (
+ <circle
+ cx={radius}
+ cy={radius}
+ r={radius + 6}
+ fill={meta.color}
+ opacity={0.2}
+ />
+ )}
+ {isRejected && (
+ <circle
+ cx={radius}
+ cy={radius}
+ r={radius + 3}
+ fill="none"
+ stroke="hsl(0 84% 60%)"
+ strokeWidth={1.5}
+ strokeDasharray="3 3"
+ />
+ )}
+ {/* Stack effect: two offset copies peeking out behind the face. */}
+ <circle
+ cx={radius + 6}
+ cy={radius - 6}
+ r={radius}
+ fill={meta.color}
+ opacity={0.3}
+ stroke="hsl(var(--background))"
+ strokeWidth={1.5}
+ />
+ <circle
+ cx={radius + 3}
+ cy={radius - 3}
+ r={radius}
+ fill={meta.color}
+ opacity={0.55}
+ stroke="hsl(var(--background))"
+ strokeWidth={1.5}
+ />
+ <circle
+ cx={radius}
+ cy={radius}
+ r={radius}
+ fill={meta.color}
+ stroke={selected ? "hsl(var(--foreground))" : "transparent"}
+ strokeWidth={selected ? 2 : 0}
+ />
+ </svg>
+ <div className="absolute inset-0 flex items-center justify-center pointer-events-none text-white drop-shadow-sm">
+ <Icon style={{ width: iconSize, height: iconSize }} />
+ </div>
+ <div
+ className="absolute -bottom-1 -right-1 rounded-full bg-card border border-border text-[9px] tabular-nums px-1 leading-tight pointer-events-none font-medium"
+ title={`${count} identical ${cluster.status.toLowerCase()} serials`}
+ >
+ ×{count}
+ </div>
+ {showLabel && (
+ <div
+ className={cn(
+ "absolute left-1/2 -translate-x-1/2 whitespace-nowrap pointer-events-none select-none flex flex-col items-center",
+ selected ? "text-foreground" : "text-muted-foreground"
+ )}
+ style={{ top: size + 4 }}
+ >
+ <span
+ className={cn(
+ "text-[11px] tracking-tight px-1.5 py-px rounded bg-background",
+ selected && "font-medium"
+ )}
+ >
+ {cluster.headline}
+ </span>
+ {rangeLabel && (
+ <span className="text-[10px] tracking-tight px-1.5 rounded bg-background text-muted-foreground tabular-nums">
+ {rangeLabel}
+ </span>
+ )}
+ </div>
+ )}
+ </div>
+ );
+}
+
+export const EntityGroupNode = memo(EntityGroupNodeImpl);
diff --git a/apps/erp/app/modules/inventory/ui/Traceability/nodes/EntityNode.tsx b/apps/erp/app/modules/inventory/ui/Traceability/nodes/EntityNode.tsx
index a3ac605e62..8ff3df299f 100644
--- a/apps/erp/app/modules/inventory/ui/Traceability/nodes/EntityNode.tsx
+++ b/apps/erp/app/modules/inventory/ui/Traceability/nodes/EntityNode.tsx
@@ -19,7 +19,13 @@ type Props = NodeProps & {
};
};
-function EntityNodeImpl({ data, selected, id }: Props) {
+function EntityNodeImpl({
+ data,
+ selected,
+ id,
+ sourcePosition,
+ targetPosition
+}: Props) {
const entity = data.entity;
const headline = entityHeadline(entity, 8);
@@ -61,12 +67,12 @@ function EntityNodeImpl({ data, selected, id }: Props) {
>
<Handle
type="target"
- position={Position.Top}
+ position={targetPosition ?? Position.Top}
className="!opacity-0 !pointer-events-none !top-1/2 !left-1/2 !-translate-x-1/2 !-translate-y-1/2 !w-1 !h-1 !min-w-0 !min-h-0 !border-0"
/>
<Handle
type="source"
- position={Position.Bottom}
+ position={sourcePosition ?? Position.Bottom}
className="!opacity-0 !pointer-events-none !top-1/2 !left-1/2 !-translate-x-1/2 !-translate-y-1/2 !w-1 !h-1 !min-w-0 !min-h-0 !border-0"
/>
<svg
diff --git a/apps/erp/app/modules/inventory/ui/Traceability/payloadToFlow.cluster.test.ts b/apps/erp/app/modules/inventory/ui/Traceability/payloadToFlow.cluster.test.ts
new file mode 100644
index 0000000000..3ff612ea81
--- /dev/null
+++ b/apps/erp/app/modules/inventory/ui/Traceability/payloadToFlow.cluster.test.ts
@@ -0,0 +1,182 @@
+import { describe, expect, it } from "vitest";
+import type { Activity, TrackedEntity } from "~/modules/inventory";
+import { isClusterId } from "./cluster";
+import { type LineagePayload, payloadToFlow } from "./utils";
+
+const T0 = "2026-08-01T10:00:00.000Z";
+const T1 = "2026-08-01T11:00:00.000Z";
+
+const serial = (id: string, over: Partial<TrackedEntity> = {}): TrackedEntity =>
+ ({
+ id,
+ readableId: id,
+ quantity: 1,
+ status: "Available",
+ itemId: "PART-1",
+ sourceDocumentReadableId: "PART-1",
+ attributes: {},
+ ...over
+ }) as TrackedEntity;
+
+const activity = (id: string, type: string, createdAt = T0): Activity => ({
+ id,
+ type,
+ attributes: {},
+ createdAt
+});
+
+const flow = (payload: Partial<LineagePayload>, rootIds: string[] = []) =>
+ payloadToFlow(
+ {
+ entities: [],
+ activities: [],
+ inputs: [],
+ outputs: [],
+ ...payload
+ },
+ undefined,
+ { rootIds }
+ );
+
+describe("payloadToFlow clustering", () => {
+ it("emits one group node with a single summed edge for a serial fan", () => {
+ const entities = ["S1", "S2", "S3", "S4", "S5"].map((id) => serial(id));
+ const { nodes, edges, clusters } = flow({
+ entities,
+ activities: [activity("JOB", "Manufacturing")],
+ outputs: entities.map((e) => ({
+ trackedActivityId: "JOB",
+ trackedEntityId: e.id,
+ quantity: 1
+ }))
+ });
+
+ expect(clusters).toHaveLength(1);
+ const groupNodes = nodes.filter((n) => n.type === "entityGroup");
+ expect(groupNodes).toHaveLength(1);
+ expect(isClusterId(groupNodes[0].id)).toBe(true);
+ // The job plus the group — no member nodes.
+ expect(nodes).toHaveLength(2);
+
+ expect(edges).toHaveLength(1);
+ expect(edges[0].source).toBe("JOB");
+ expect(edges[0].target).toBe(groupNodes[0].id);
+ expect(edges[0].data?.quantity).toBe(5);
+ expect(edges[0].data?.kind).toBe("output");
+ });
+
+ it("keeps the traced root as its own node", () => {
+ const entities = ["S1", "S2", "S3", "S4"].map((id) => serial(id));
+ const { nodes, clusters } = flow(
+ {
+ entities,
+ activities: [activity("JOB", "Manufacturing")],
+ outputs: entities.map((e) => ({
+ trackedActivityId: "JOB",
+ trackedEntityId: e.id,
+ quantity: 1
+ }))
+ },
+ ["S1"]
+ );
+
+ expect(clusters[0].members).toHaveLength(3);
+ expect(nodes.map((n) => n.id)).toContain("S1");
+ expect(nodes.filter((n) => n.type === "entityGroup")).toHaveLength(1);
+ });
+
+ it("clusters a produced-then-consumed fan (still one timeline state)", () => {
+ const entities = ["S1", "S2", "S3"].map((id) => serial(id));
+ const { nodes, edges, clusters } = flow({
+ entities,
+ activities: [
+ activity("JOB", "Manufacturing", T0),
+ activity("SHIP", "Shipment", T1)
+ ],
+ outputs: entities.map((e) => ({
+ trackedActivityId: "JOB",
+ trackedEntityId: e.id,
+ quantity: 1
+ })),
+ inputs: entities.map((e) => ({
+ trackedActivityId: "SHIP",
+ trackedEntityId: e.id,
+ quantity: 1
+ }))
+ });
+
+ expect(clusters).toHaveLength(1);
+ const groupId = clusters[0].id;
+ expect(nodes.filter((n) => n.type === "entity")).toHaveLength(0);
+ expect(edges).toHaveLength(2);
+ expect(edges.find((e) => e.target === groupId)?.source).toBe("JOB");
+ expect(edges.find((e) => e.source === groupId)?.target).toBe("SHIP");
+ for (const e of edges) expect(e.data?.quantity).toBe(3);
+ });
+
+ it("leaves bin-transferred serials individual — their timeline has 2 states", () => {
+ const entities = ["S1", "S2", "S3"].map((id) => serial(id));
+ const { nodes, clusters } = flow({
+ entities,
+ activities: [
+ activity("JOB", "Manufacturing", T0),
+ activity("MOVE", "Transfer", T1)
+ ],
+ outputs: entities.map((e) => ({
+ trackedActivityId: "JOB",
+ trackedEntityId: e.id,
+ quantity: 1
+ })),
+ inputs: entities.map((e) => ({
+ trackedActivityId: "MOVE",
+ trackedEntityId: e.id,
+ quantity: 1
+ }))
+ });
+
+ expect(clusters).toEqual([]);
+ expect(nodes.filter((n) => n.type === "entityGroup")).toHaveLength(0);
+ expect(nodes.filter((n) => n.type === "entity").length).toBeGreaterThan(3);
+ });
+
+ it("is unchanged from today's rendering when nothing clusters", () => {
+ const entities = ["S1", "S2"].map((id) => serial(id));
+ const payload = {
+ entities,
+ activities: [activity("JOB", "Manufacturing")],
+ outputs: entities.map((e) => ({
+ trackedActivityId: "JOB",
+ trackedEntityId: e.id,
+ quantity: 1
+ }))
+ };
+
+ const { nodes, edges, clusters, memberToCluster } = flow(payload);
+
+ expect(clusters).toEqual([]);
+ expect(memberToCluster).toEqual({});
+ expect(nodes.map((n) => n.id).sort()).toEqual(["JOB", "S1", "S2"]);
+ // Timeline-driven edge ids, state-suffixed — exactly as before clustering.
+ expect(edges.map((e) => e.id).sort()).toEqual([
+ "out:JOB:S1@0",
+ "out:JOB:S2@0"
+ ]);
+ });
+
+ it("does not cluster a batch lot fan — quantity is not 1", () => {
+ const entities = ["L1", "L2", "L3"].map((id) =>
+ serial(id, { quantity: 12 })
+ );
+ const { clusters } = flow({
+ entities,
+ activities: [activity("JOB", "Manufacturing")],
+ outputs: entities.map((e) => ({
+ trackedActivityId: "JOB",
+ trackedEntityId: e.id,
+ quantity: 12
+ }))
+ });
+
+ expect(clusters).toEqual([]);
+ });
+});
diff --git a/apps/erp/app/modules/inventory/ui/Traceability/store.ts b/apps/erp/app/modules/inventory/ui/Traceability/store.ts
index 7f6773ac17..8fc177e29f 100644
--- a/apps/erp/app/modules/inventory/ui/Traceability/store.ts
+++ b/apps/erp/app/modules/inventory/ui/Traceability/store.ts
@@ -1,5 +1,6 @@
import { create } from "zustand";
import { createJSONStorage, persist } from "zustand/middleware";
+import type { EntityCluster } from "./cluster";
import { clampSpacing, SPACING } from "./constants";
import type { LineagePayload } from "./utils";
@@ -15,6 +16,16 @@ type TraceabilityState = {
excludedIds: Set<string>;
additionalRootIds: Set<string>;
+ /**
+ * Serial clusters from the latest layout. The graph computes them (in the
+ * worker, off the expansion-merged payload) but the sidebar is its SIBLING in
+ * the route, not its child — so they travel through here rather than props.
+ */
+ clusters: EntityCluster[];
+ memberToCluster: Record<string, string>;
+ /** Member the sidebar should scroll to and highlight, set by search. */
+ highlightMemberId: string | null;
+
// persisted preferences
direction: LayoutDirection;
view: ViewMode;
@@ -32,6 +43,11 @@ type TraceabilityState = {
markExhausted: (id: string) => void;
toggleExcluded: (id: string) => void;
clearExcluded: () => void;
+ setClusters: (
+ clusters: EntityCluster[],
+ memberToCluster: Record<string, string>
+ ) => void;
+ setHighlightMember: (id: string | null) => void;
setDirection: (next: LayoutDirection) => void;
setView: (next: ViewMode) => void;
setSpacing: (next: number) => void;
@@ -47,6 +63,9 @@ export const useTraceabilityStore = create<TraceabilityState>()(
exhausted: new Set(),
excludedIds: new Set(),
additionalRootIds: new Set(),
+ clusters: [],
+ memberToCluster: {},
+ highlightMemberId: null,
direction: "TB",
view: "graph",
spacing: SPACING.default,
@@ -59,7 +78,10 @@ export const useTraceabilityStore = create<TraceabilityState>()(
expandable: new Set(),
exhausted: new Set(),
excludedIds: new Set(),
- additionalRootIds: new Set()
+ additionalRootIds: new Set(),
+ clusters: [],
+ memberToCluster: {},
+ highlightMemberId: null
}),
setIsolate: (next) => set({ isolate: next }),
@@ -126,6 +148,16 @@ export const useTraceabilityStore = create<TraceabilityState>()(
s.excludedIds.size === 0 ? {} : { excludedIds: new Set() }
),
+ setClusters: (clusters, memberToCluster) =>
+ set((s) =>
+ s.clusters === clusters ? {} : { clusters, memberToCluster }
+ ),
+
+ setHighlightMember: (id) =>
+ set((s) =>
+ s.highlightMemberId === id ? {} : { highlightMemberId: id }
+ ),
+
setDirection: (next) => set({ direction: next }),
setView: (next) => set({ view: next }),
setSpacing: (next) => set({ spacing: clampSpacing(next) })
diff --git a/apps/erp/app/modules/inventory/ui/Traceability/utils.ts b/apps/erp/app/modules/inventory/ui/Traceability/utils.ts
index 97487ec1f2..bdc2279040 100644
--- a/apps/erp/app/modules/inventory/ui/Traceability/utils.ts
+++ b/apps/erp/app/modules/inventory/ui/Traceability/utils.ts
@@ -5,6 +5,8 @@ import type {
ActivityOutput,
TrackedEntity
} from "~/modules/inventory";
+import type { ClusterResult, EntityCluster } from "./cluster";
+import { clusterEntities, DEFAULT_CLUSTER_THRESHOLD, edgeKey } from "./cluster";
import { NODE_SIZE } from "./constants";
import { isMovementActivity } from "./metadata";
@@ -35,7 +37,15 @@ export type ActivityNodeData = {
movementQuantity?: number;
};
-export type LineageNode = Node<EntityNodeData | ActivityNodeData>;
+export type EntityGroupNodeData = {
+ kind: "entityGroup";
+ cluster: EntityCluster;
+ dimmed: boolean;
+};
+
+export type LineageNode = Node<
+ EntityNodeData | ActivityNodeData | EntityGroupNodeData
+>;
export type LineageEdgeData = {
kind: "input" | "output" | "movement";
@@ -47,7 +57,13 @@ export type LineageEdgeData = {
weight?: number;
isReject?: boolean;
isBackEdge?: boolean;
- points?: { x: number; y: number }[];
+ /**
+ * Where along this edge's own curve the label sits, 0..1 (0.5 = midpoint).
+ * Layout slides it off the midpoint when parallel edges would stack their
+ * pills. Stored as a PARAMETER, not a point, so the label keeps following
+ * the curve when a node is dragged.
+ */
+ labelT?: number;
};
export type LineageEdge = Edge<LineageEdgeData>;
@@ -252,8 +268,9 @@ function buildLotTimeline(
export function payloadToFlow(
payload: LineagePayload,
- positions: Map<string, { x: number; y: number }> = new Map()
-): { nodes: LineageNode[]; edges: LineageEdge[] } {
+ positions: Map<string, { x: number; y: number }> = new Map(),
+ opts: { clusterThreshold?: number; rootIds?: string[] } = {}
+): { nodes: LineageNode[]; edges: LineageEdge[] } & ClusterResult {
const activityById = new Map(payload.activities.map((a) => [a.id, a]));
// Gather each entity's events from the junction rows.
@@ -316,11 +333,47 @@ export function payloadToFlow(
if (timeline) timelines.set(entity.id, timeline);
}
+ const stateCountByEntity = new Map<string, number>();
+ for (const entity of payload.entities) {
+ if (!entity?.id || stateCountByEntity.has(entity.id)) continue;
+ stateCountByEntity.set(
+ entity.id,
+ timelines.get(entity.id)?.stateQuantities.length ?? 1
+ );
+ }
+
+ // Serial fans: collapse identical-story qty-1 siblings into one group node.
+ // Only single-state entities are eligible — a multi-state entity renders as
+ // a chain, which can't fold into a single circle.
+ const singleStateIds = new Set<string>();
+ for (const [id, count] of stateCountByEntity) {
+ if (count === 1) singleStateIds.add(id);
+ }
+ const { clusters, memberToCluster } = clusterEntities(payload, {
+ threshold: opts.clusterThreshold ?? DEFAULT_CLUSTER_THRESHOLD,
+ excludeIds: new Set(opts.rootIds ?? []),
+ eligibleIds: singleStateIds
+ });
+
const nodes: LineageNode[] = [];
const seenNodeIds = new Set<string>();
+ for (const cluster of clusters) {
+ seenNodeIds.add(cluster.id);
+ nodes.push({
+ id: cluster.id,
+ type: "entityGroup",
+ position: positions.get(cluster.id) ?? { x: 0, y: 0 },
+ width: NODE_SIZE,
+ height: NODE_SIZE,
+ measured: { width: NODE_SIZE, height: NODE_SIZE },
+ data: { kind: "entityGroup", cluster, dimmed: false }
+ });
+ }
+
for (const entity of payload.entities) {
if (!entity?.id || seenNodeIds.has(entity.id)) continue;
+ if (memberToCluster[entity.id]) continue;
seenNodeIds.add(entity.id);
const timeline = timelines.get(entity.id);
const stateQuantities = timeline?.stateQuantities ?? [
@@ -400,6 +453,7 @@ export function payloadToFlow(
// Timeline-driven edges: each entity wires its own input/creation/
// continuation edges, labeled with the quantity at that moment.
for (const [entityId, timeline] of timelines) {
+ if (memberToCluster[entityId]) continue;
for (const w of timeline.wiring) {
if (w.beforeState !== null && w.beforeQty !== null) {
pushEdge(
@@ -430,6 +484,7 @@ export function payloadToFlow(
);
for (const input of payload.inputs) {
if (timelines.has(input.trackedEntityId)) continue;
+ if (memberToCluster[input.trackedEntityId]) continue;
const kind = isMovementActivity(
activityTypeById.get(input.trackedActivityId)
)
@@ -445,6 +500,7 @@ export function payloadToFlow(
}
for (const output of payload.outputs) {
if (timelines.has(output.trackedEntityId)) continue;
+ if (memberToCluster[output.trackedEntityId]) continue;
pushEdge(
`out:${output.trackedActivityId}:${output.trackedEntityId}`,
output.trackedActivityId,
@@ -454,7 +510,35 @@ export function payloadToFlow(
);
}
- return { nodes, edges };
+ // One edge per signature entry, standing in for every member edge it
+ // replaced — quantity is their sum.
+ for (const cluster of clusters) {
+ for (const entry of cluster.signature) {
+ const quantity =
+ cluster.quantitiesByEdge[edgeKey(entry.activityId, entry.side)] ?? 0;
+ if (entry.side === "input") {
+ pushEdge(
+ `in:${entry.activityId}:${cluster.id}`,
+ cluster.id,
+ entry.activityId,
+ isMovementActivity(activityTypeById.get(entry.activityId))
+ ? "movement"
+ : "input",
+ quantity
+ );
+ } else {
+ pushEdge(
+ `out:${entry.activityId}:${cluster.id}`,
+ entry.activityId,
+ cluster.id,
+ "output",
+ quantity
+ );
+ }
+ }
+ }
+
+ return { nodes, edges, clusters, memberToCluster };
}
export function mergePayloads(
@@ -701,6 +785,275 @@ export function annotateEdgeWeights(
}
// Compact quantity for node badges/stubs, where horizontal space is tight.
+/**
+ * How edges are drawn. Flipping this is a ONE-LINE change: `QuantityEdge` picks
+ * the matching xyflow path function and `edgeLabelPoint` picks the matching
+ * geometry, so labels can never end up sampling a curve the renderer isn't
+ * drawing (which strands them off the line).
+ */
+export const EDGE_STYLE: "bezier" | "smoothstep" = "bezier";
+
+/** Must match the values QuantityEdge passes to `getSmoothStepPath`. */
+export const EDGE_BORDER_RADIUS = 10;
+/** The handles sit at the node CENTRE, so the run has to clear the circle
+ * (radius 22) before the path is allowed to turn. */
+export const EDGE_OFFSET = 34;
+
+type Pt = { x: number; y: number };
+
+const isHorizontal = (position: string | undefined) =>
+ position === "left" || position === "right";
+
+const handleDir = (position: string | undefined): Pt => {
+ switch (position) {
+ case "left":
+ return { x: -1, y: 0 };
+ case "right":
+ return { x: 1, y: 0 };
+ case "top":
+ return { x: 0, y: -1 };
+ default:
+ return { x: 0, y: 1 };
+ }
+};
+
+/**
+ * The corner points of the orthogonal path `getSmoothStepPath` draws.
+ *
+ * Mirrors xyflow's `getPoints` for the OPPOSITE-handle case, which is the only
+ * one this graph produces — layout pins handles to Bottom→Top (TB) or
+ * Right→Left (LR). Corner rounding is ignored: this is used to place labels,
+ * and label candidates skip the bends anyway.
+ *
+ * Compared as string literals rather than importing the `Position` enum, so
+ * this stays free of a runtime @xyflow/react dependency — it runs in the
+ * lineage Web Worker.
+ */
+export function smoothStepPolyline(
+ sourceX: number,
+ sourceY: number,
+ sourcePosition: string | undefined,
+ targetX: number,
+ targetY: number,
+ targetPosition: string | undefined,
+ offset: number = EDGE_OFFSET
+): Pt[] {
+ const sourceDir = handleDir(sourcePosition);
+ const targetDir = handleDir(targetPosition);
+ const s: Pt = { x: sourceX, y: sourceY };
+ const t: Pt = { x: targetX, y: targetY };
+ const sg: Pt = {
+ x: s.x + sourceDir.x * offset,
+ y: s.y + sourceDir.y * offset
+ };
+ const tg: Pt = {
+ x: t.x + targetDir.x * offset,
+ y: t.y + targetDir.y * offset
+ };
+
+ const horizontal = isHorizontal(sourcePosition);
+ // getDirection: which way the run actually travels between the gapped points.
+ const currDir = horizontal ? (sg.x < tg.x ? 1 : -1) : sg.y < tg.y ? 1 : -1;
+ const sourceComponent = horizontal ? sourceDir.x : sourceDir.y;
+
+ const centerX = (sg.x + tg.x) / 2;
+ const centerY = (sg.y + tg.y) / 2;
+ const verticalSplit: Pt[] = [
+ { x: centerX, y: sg.y },
+ { x: centerX, y: tg.y }
+ ];
+ const horizontalSplit: Pt[] = [
+ { x: sg.x, y: centerY },
+ { x: tg.x, y: centerY }
+ ];
+
+ const bends =
+ sourceComponent === currDir
+ ? horizontal
+ ? verticalSplit
+ : horizontalSplit
+ : horizontal
+ ? horizontalSplit
+ : verticalSplit;
+
+ const same = (a: Pt, b: Pt) => a.x === b.x && a.y === b.y;
+ const raw = [
+ s,
+ ...(same(sg, bends[0]) ? [] : [sg]),
+ ...bends,
+ ...(same(tg, bends[bends.length - 1]) ? [] : [tg]),
+ t
+ ];
+
+ // Drop duplicate and colinear joints. xyflow renders those as a plain `L`
+ // (no bend), so keeping them would make a dead-straight edge look like it
+ // had corners — and label placement would refuse to sit anywhere near them.
+ const simplified: Pt[] = [];
+ for (const p of raw) {
+ const last = simplified[simplified.length - 1];
+ if (last && same(last, p)) continue;
+ if (simplified.length >= 2) {
+ const a = simplified[simplified.length - 2];
+ const b = last!;
+ const colinear =
+ (a.x === b.x && b.x === p.x) || (a.y === b.y && b.y === p.y);
+ if (colinear) simplified.pop();
+ }
+ simplified.push(p);
+ }
+ return simplified;
+}
+
+/**
+ * Walk a polyline to the point at `fraction` of its total length, and report
+ * how far that point is from the nearest corner — a label sitting on a bend
+ * would float off the rounded path the renderer actually draws.
+ */
+export function pointAlongPolyline(
+ points: Pt[],
+ fraction: number
+): { x: number; y: number; distanceToBend: number } {
+ const segLengths: number[] = [];
+ let total = 0;
+ for (let i = 1; i < points.length; i++) {
+ const d = Math.hypot(
+ points[i].x - points[i - 1].x,
+ points[i].y - points[i - 1].y
+ );
+ segLengths.push(d);
+ total += d;
+ }
+ if (total === 0) {
+ return { x: points[0].x, y: points[0].y, distanceToBend: Infinity };
+ }
+
+ let travelled = fraction * total;
+ for (let i = 0; i < segLengths.length; i++) {
+ const len = segLengths[i];
+ if (travelled <= len || i === segLengths.length - 1) {
+ const r = len === 0 ? 0 : Math.min(travelled, len) / len;
+ const a = points[i];
+ const b = points[i + 1];
+ // Only interior joints are bends; the endpoints are not.
+ const startIsBend = i > 0;
+ const endIsBend = i < segLengths.length - 1;
+ const along = r * len;
+ return {
+ x: a.x + (b.x - a.x) * r,
+ y: a.y + (b.y - a.y) * r,
+ distanceToBend: Math.min(
+ startIsBend ? along : Infinity,
+ endIsBend ? len - along : Infinity
+ )
+ };
+ }
+ travelled -= len;
+ }
+
+ const last = points[points.length - 1];
+ return { x: last.x, y: last.y, distanceToBend: Infinity };
+}
+
+/**
+ * A point on the curve `getSimpleBezierPath` draws.
+ *
+ * Mirrors xyflow's `getControl`: a Left/Right handle puts the control at the
+ * midpoint in x and the endpoint's own y; Top/Bottom is the transpose.
+ */
+function bezierControl(
+ position: string | undefined,
+ x1: number,
+ y1: number,
+ x2: number,
+ y2: number
+): [number, number] {
+ return isHorizontal(position) ? [0.5 * (x1 + x2), y1] : [x1, 0.5 * (y1 + y2)];
+}
+
+function cubicAt(
+ t: number,
+ p0: number,
+ c1: number,
+ c2: number,
+ p3: number
+): number {
+ const u = 1 - t;
+ return (
+ u * u * u * p0 + 3 * u * u * t * c1 + 3 * u * t * t * c2 + t * t * t * p3
+ );
+}
+
+export function simpleBezierPointAt(
+ t: number,
+ sourceX: number,
+ sourceY: number,
+ sourcePosition: string | undefined,
+ targetX: number,
+ targetY: number,
+ targetPosition: string | undefined
+): { x: number; y: number } {
+ const [c1x, c1y] = bezierControl(
+ sourcePosition,
+ sourceX,
+ sourceY,
+ targetX,
+ targetY
+ );
+ const [c2x, c2y] = bezierControl(
+ targetPosition,
+ targetX,
+ targetY,
+ sourceX,
+ sourceY
+ );
+ return {
+ x: cubicAt(t, sourceX, c1x, c2x, targetX),
+ y: cubicAt(t, sourceY, c1y, c2y, targetY)
+ };
+}
+
+/**
+ * Where a label sits on an edge. Layout picks the `fraction`; the edge
+ * component evaluates it against LIVE endpoint coordinates, so a dragged node
+ * takes its labels with it.
+ *
+ * Dispatches on EDGE_STYLE so the geometry always matches what is drawn.
+ * A bezier has no corners, hence the infinite bend clearance.
+ */
+export function edgeLabelPoint(
+ fraction: number,
+ sourceX: number,
+ sourceY: number,
+ sourcePosition: string | undefined,
+ targetX: number,
+ targetY: number,
+ targetPosition: string | undefined
+): { x: number; y: number; distanceToBend: number } {
+ if (EDGE_STYLE === "bezier") {
+ const p = simpleBezierPointAt(
+ fraction,
+ sourceX,
+ sourceY,
+ sourcePosition,
+ targetX,
+ targetY,
+ targetPosition
+ );
+ return { ...p, distanceToBend: Infinity };
+ }
+ return pointAlongPolyline(
+ smoothStepPolyline(
+ sourceX,
+ sourceY,
+ sourcePosition,
+ targetX,
+ targetY,
+ targetPosition
+ ),
+ fraction
+ );
+}
+
export function formatQuantity(q: number): string {
if (q >= 1000) return `${(q / 1000).toFixed(1)}k`;
if (Number.isInteger(q)) return String(q);
diff --git a/apps/erp/app/modules/inventory/ui/Traceability/worker/core.ts b/apps/erp/app/modules/inventory/ui/Traceability/worker/core.ts
index a8fa6ca589..897e503e06 100644
--- a/apps/erp/app/modules/inventory/ui/Traceability/worker/core.ts
+++ b/apps/erp/app/modules/inventory/ui/Traceability/worker/core.ts
@@ -1,6 +1,12 @@
import Dagre from "@dagrejs/dagre";
+import type { Position } from "@xyflow/react";
+import type { EntityCluster } from "../cluster";
import {
+ activityHeadline,
annotateEdgeWeights,
+ EDGE_BORDER_RADIUS,
+ edgeLabelPoint,
+ entityHeadline,
type LineageEdge,
type LineageEdgeData,
type LineageNode,
@@ -8,20 +14,29 @@ import {
payloadToFlow
} from "../utils";
-export type LayoutDirection = "TB" | "LR";
+// Position's values ARE these strings. Typed as the enum but written as
+// literals so the worker bundle never pulls in @xyflow/react at runtime.
+const POS_RIGHT = "right" as Position;
+const POS_LEFT = "left" as Position;
+const POS_BOTTOM = "bottom" as Position;
+const POS_TOP = "top" as Position;
-export type EdgePoint = { x: number; y: number };
+export type LayoutDirection = "TB" | "LR";
export type LayoutInput = {
payload: LineagePayload;
direction: LayoutDirection;
spacing: number;
rejectIds: string[];
+ /** Never clustered — the traced root stays individually visible. */
+ rootIds: string[];
};
export type LayoutResult = {
nodes: LineageNode[];
edges: LineageEdge[];
+ clusters: EntityCluster[];
+ memberToCluster: Record<string, string>;
};
export type SelectionPathResult = {
@@ -32,6 +47,158 @@ export type SelectionPathResult = {
const NODE_WIDTH = 44;
const NODE_HEIGHT = 44;
+/**
+ * Every node renders a `whitespace-nowrap` label BELOW its circle, outside the
+ * 44px box xyflow measures. Laying out on the circle alone separates the
+ * circles correctly and lets the labels collide — "SN4-0001…SN4-0004" is far
+ * wider than the dot it belongs to.
+ *
+ * So dagre gets the real footprint: the circle plus whatever the label
+ * occupies. Approximate glyph widths are fine — this only has to be close
+ * enough that neighbours don't touch, and the worker has no DOM to measure in.
+ */
+const CHAR_W_11 = 6.2;
+const CHAR_W_10 = 5.6;
+const LABEL_PAD_X = 12;
+const LABEL_LINE_H = 15;
+const LABEL_GAP = 8;
+
+function labelWidth(text: string, charWidth: number): number {
+ return text.length * charWidth + LABEL_PAD_X;
+}
+
+function nodeFootprint(node: LineageNode): { width: number; height: number } {
+ const data = node.data as Record<string, any> | undefined;
+ let width = NODE_WIDTH;
+ let lines = 0;
+
+ if (data?.kind === "entity" && data.entity) {
+ width = Math.max(
+ width,
+ labelWidth(entityHeadline(data.entity, 8), CHAR_W_11)
+ );
+ lines = 1;
+ } else if (data?.kind === "entityGroup" && data.cluster) {
+ const cluster = data.cluster as EntityCluster;
+ width = Math.max(width, labelWidth(cluster.headline, CHAR_W_11));
+ lines = 1;
+ const range = cluster.readableIdRange;
+ if (range) {
+ const text = range[0] === range[1] ? range[0] : `${range[0]}…${range[1]}`;
+ width = Math.max(width, labelWidth(text, CHAR_W_10));
+ lines = 2;
+ }
+ } else if (data?.kind === "activity" && data.activity) {
+ width = Math.max(
+ width,
+ labelWidth(activityHeadline(data.activity, 8), CHAR_W_11)
+ );
+ lines = 1;
+ }
+
+ const height =
+ NODE_HEIGHT + (lines > 0 ? LABEL_GAP + lines * LABEL_LINE_H : 0);
+ return { width, height };
+}
+
+/**
+ * Where along each edge its quantity pill should sit.
+ *
+ * Every edge defaults its label to the path midpoint, so parallel edges between
+ * the same two ranks stack their pills on top of each other. Slide each one
+ * along its OWN path until it clears the ones already placed — the label stays
+ * visually attached to its edge instead of being nudged into open space.
+ *
+ * Returns the path FRACTION, not a point. An absolute point would be stale the
+ * moment a node is dragged, leaving the pill stranded in open canvas while its
+ * edge moved away.
+ */
+type LabelBox = { x: number; y: number; w: number; h: number };
+
+const LABEL_H = 22;
+const LABEL_MIN_W = 26;
+const LABEL_GAP_PX = 4;
+/** Midpoint first, then alternate outward along the path. */
+const LABEL_T_CANDIDATES = [0.5, 0.4, 0.6, 0.32, 0.68, 0.25, 0.75, 0.18, 0.82];
+/** A label parked on a corner floats off the rounded path the renderer draws. */
+const MIN_BEND_CLEARANCE = EDGE_BORDER_RADIUS + LABEL_H / 2;
+
+function overlaps(a: LabelBox, b: LabelBox): boolean {
+ return (
+ Math.abs(a.x - b.x) * 2 < a.w + b.w + LABEL_GAP_PX * 2 &&
+ Math.abs(a.y - b.y) * 2 < a.h + b.h + LABEL_GAP_PX * 2
+ );
+}
+
+export function resolveEdgeLabelPositions(
+ nodes: LineageNode[],
+ edges: LineageEdge[],
+ direction: LayoutDirection
+): Map<string, number> {
+ const centers = new Map<string, { x: number; y: number }>();
+ for (const n of nodes) {
+ centers.set(n.id, {
+ x: n.position.x + NODE_WIDTH / 2,
+ y: n.position.y + NODE_HEIGHT / 2
+ });
+ }
+
+ const sourcePos = direction === "LR" ? POS_RIGHT : POS_BOTTOM;
+ const targetPos = direction === "LR" ? POS_LEFT : POS_TOP;
+ const placed: LabelBox[] = [];
+ const resolved = new Map<string, number>();
+
+ const candidates = edges
+ .map((e) => {
+ const s = centers.get(e.source);
+ const t = centers.get(e.target);
+ if (!s || !t) return null;
+ const data = e.data as LineageEdgeData | undefined;
+ const text = data?.labelText ?? String(data?.quantity ?? "");
+ return {
+ id: e.id,
+ s,
+ t,
+ w: Math.max(LABEL_MIN_W, text.length * 6.2 + 20),
+ midY: (s.y + t.y) / 2,
+ midX: (s.x + t.x) / 2
+ };
+ })
+ .filter((c): c is NonNullable<typeof c> => c !== null);
+
+ // Deterministic order so the layout doesn't shuffle between runs.
+ candidates.sort(
+ (a, b) => a.midY - b.midY || a.midX - b.midX || (a.id < b.id ? -1 : 1)
+ );
+
+ for (const c of candidates) {
+ const pointAt = (t: number) =>
+ edgeLabelPoint(t, c.s.x, c.s.y, sourcePos, c.t.x, c.t.y, targetPos);
+
+ let chosenT: number | null = null;
+ for (const t of LABEL_T_CANDIDATES) {
+ const p = pointAt(t);
+ if (p.distanceToBend < MIN_BEND_CLEARANCE) continue;
+ const box: LabelBox = { x: p.x, y: p.y, w: c.w, h: LABEL_H };
+ if (!placed.some((q) => overlaps(box, q))) {
+ chosenT = t;
+ placed.push(box);
+ break;
+ }
+ }
+ // Every candidate collided — keep the midpoint rather than fling the label
+ // somewhere it no longer reads as belonging to this edge.
+ if (chosenT === null) {
+ chosenT = 0.5;
+ const p = pointAt(0.5);
+ placed.push({ x: p.x, y: p.y, w: c.w, h: LABEL_H });
+ }
+ resolved.set(c.id, chosenT);
+ }
+
+ return resolved;
+}
+
const SPACING_TABLE: Record<
number,
{ nodesep: number; ranksep: number; edgesep: number }
@@ -105,10 +272,9 @@ export function computeDagreLayout(
): {
positioned: LineageNode[];
backEdges: Set<string>;
- edgePoints: Map<string, EdgePoint[]>;
} {
if (nodes.length === 0) {
- return { positioned: nodes, backEdges: new Set(), edgePoints: new Map() };
+ return { positioned: nodes, backEdges: new Set() };
}
const backEdges = detectBackEdges(nodes, edges);
@@ -128,8 +294,11 @@ export function computeDagreLayout(
});
g.setDefaultEdgeLabel(() => ({}));
+ const footprints = new Map<string, { width: number; height: number }>();
for (const n of nodes) {
- g.setNode(n.id, { width: NODE_WIDTH, height: NODE_HEIGHT });
+ const footprint = nodeFootprint(n);
+ footprints.set(n.id, footprint);
+ g.setNode(n.id, footprint);
}
for (const e of edges) {
@@ -139,41 +308,52 @@ export function computeDagreLayout(
Dagre.layout(g);
+ // dagre centres the FOOTPRINT on (p.x, p.y), but `position` is the top-left
+ // of the 44px circle — the label hangs below it, outside the box. So centre
+ // the circle horizontally and pin it to the top of the footprint.
const positioned = nodes.map((n) => {
const p = g.node(n.id);
if (!p) return n;
+ const footprint = footprints.get(n.id) ?? {
+ width: NODE_WIDTH,
+ height: NODE_HEIGHT
+ };
return {
...n,
- position: { x: p.x - NODE_WIDTH / 2, y: p.y - NODE_HEIGHT / 2 }
+ position: {
+ x: p.x - NODE_WIDTH / 2,
+ y: p.y - footprint.height / 2
+ },
+ sourcePosition: direction === "LR" ? POS_RIGHT : POS_BOTTOM,
+ targetPosition: direction === "LR" ? POS_LEFT : POS_TOP
};
});
- const edgePoints = new Map<string, EdgePoint[]>();
- for (const e of edges) {
- if (backEdges.has(e.id)) continue;
- const dagreEdge = g.edge({ v: e.source, w: e.target, name: e.id }) as
- | { points?: EdgePoint[] }
- | undefined;
- if (dagreEdge?.points && dagreEdge.points.length >= 2) {
- edgePoints.set(e.id, dagreEdge.points);
- }
- }
-
- return { positioned, backEdges, edgePoints };
+ return { positioned, backEdges };
}
export function computeFullLayout(input: LayoutInput): LayoutResult {
- const flow = payloadToFlow(input.payload);
- const weightedEdges = annotateEdgeWeights(
- flow.edges,
- new Set(input.rejectIds)
- );
- const { positioned, backEdges, edgePoints } = computeDagreLayout(
+ const flow = payloadToFlow(input.payload, undefined, {
+ rootIds: input.rootIds
+ });
+ // Reject ids arrive as ENTITY ids, but a rejected member no longer has a
+ // node of its own — its cluster carries the reject styling instead.
+ const rejectIds = new Set(input.rejectIds);
+ for (const cluster of flow.clusters) {
+ if (cluster.status === "Rejected") rejectIds.add(cluster.id);
+ }
+ const weightedEdges = annotateEdgeWeights(flow.edges, rejectIds);
+ const { positioned, backEdges } = computeDagreLayout(
flow.nodes,
weightedEdges,
input.direction,
input.spacing
);
+ const labelTs = resolveEdgeLabelPositions(
+ positioned,
+ weightedEdges,
+ input.direction
+ );
const finalEdges: LineageEdge[] = [];
for (let i = 0; i < weightedEdges.length; i++) {
const e = weightedEdges[i];
@@ -182,11 +362,16 @@ export function computeFullLayout(input: LayoutInput): LayoutResult {
data: {
...(e.data as LineageEdgeData),
isBackEdge: backEdges.has(e.id),
- points: edgePoints.get(e.id)
+ labelT: labelTs.get(e.id)
}
});
}
- return { nodes: positioned, edges: finalEdges };
+ return {
+ nodes: positioned,
+ edges: finalEdges,
+ clusters: flow.clusters,
+ memberToCluster: flow.memberToCluster
+ };
}
export function computeSelectionPath(
diff --git a/apps/erp/app/modules/inventory/ui/Traceability/worker/edgeLabels.test.ts b/apps/erp/app/modules/inventory/ui/Traceability/worker/edgeLabels.test.ts
new file mode 100644
index 0000000000..e7bde2b9de
--- /dev/null
+++ b/apps/erp/app/modules/inventory/ui/Traceability/worker/edgeLabels.test.ts
@@ -0,0 +1,268 @@
+import { describe, expect, it } from "vitest";
+import {
+ edgeLabelPoint,
+ type LineageEdge,
+ type LineageNode,
+ pointAlongPolyline,
+ smoothStepPolyline
+} from "../utils";
+import { resolveEdgeLabelPositions } from "./core";
+
+const node = (id: string, x: number, y: number): LineageNode =>
+ ({
+ id,
+ type: "entity",
+ position: { x, y },
+ data: { kind: "entity", dimmed: false }
+ }) as unknown as LineageNode;
+
+const edge = (
+ id: string,
+ source: string,
+ target: string,
+ quantity = 1
+): LineageEdge =>
+ ({
+ id,
+ source,
+ target,
+ type: "quantity",
+ data: { kind: "output", quantity, dimmed: false }
+ }) as unknown as LineageEdge;
+
+/** Node centre — the handles sit dead centre in the 44px box. */
+const centre = (n: LineageNode) => ({
+ x: n.position.x + 22,
+ y: n.position.y + 22
+});
+
+/** Resolve a `t` back to the point the edge component would render. */
+const pointFor = (
+ nodes: LineageNode[],
+ e: LineageEdge,
+ t: number,
+ direction: "TB" | "LR"
+) => {
+ const s = centre(nodes.find((n) => n.id === e.source)!);
+ const g = centre(nodes.find((n) => n.id === e.target)!);
+ return direction === "LR"
+ ? edgeLabelPoint(t, s.x, s.y, "right", g.x, g.y, "left")
+ : edgeLabelPoint(t, s.x, s.y, "bottom", g.x, g.y, "top");
+};
+
+/** Same overlap test the placement pass uses (gap included). */
+const collide = (
+ a: { x: number; y: number },
+ b: { x: number; y: number },
+ w = 26,
+ h = 22
+) => Math.abs(a.x - b.x) * 2 < w * 2 + 8 && Math.abs(a.y - b.y) * 2 < h * 2 + 8;
+
+describe("resolveEdgeLabelPositions", () => {
+ it("leaves a lone label at the curve midpoint", () => {
+ const nodes = [node("A", 0, 0), node("B", 0, 400)];
+ const ts = resolveEdgeLabelPositions(nodes, [edge("e1", "A", "B")], "TB");
+
+ expect(ts.get("e1")).toBe(0.5);
+ });
+
+ it("separates parallel edges that share a midpoint", () => {
+ // Two sources side by side feeding two targets side by side — every edge
+ // spans the same ranks, so all four midpoints land on the same row.
+ const nodes = [
+ node("S1", 0, 0),
+ node("S2", 200, 0),
+ node("T1", 0, 400),
+ node("T2", 200, 400)
+ ];
+ const edges = [
+ edge("e1", "S1", "T1"),
+ edge("e2", "S1", "T2"),
+ edge("e3", "S2", "T1"),
+ edge("e4", "S2", "T2")
+ ];
+
+ const ts = resolveEdgeLabelPositions(nodes, edges, "TB");
+ const placed = edges.map((e) => pointFor(nodes, e, ts.get(e.id)!, "TB"));
+
+ expect(ts.size).toBe(4);
+ for (let i = 0; i < placed.length; i++) {
+ for (let j = i + 1; j < placed.length; j++) {
+ expect(collide(placed[i], placed[j])).toBe(false);
+ }
+ }
+ });
+
+ it("keeps every label on its own curve", () => {
+ const nodes = [node("S", 0, 0), node("T1", 0, 400), node("T2", 300, 400)];
+ const edges = [edge("e1", "S", "T1"), edge("e2", "S", "T2")];
+ const ts = resolveEdgeLabelPositions(nodes, edges, "TB");
+
+ // e1 is a straight vertical drop, so wherever it slid it stays on x=22.
+ expect(pointFor(nodes, edges[0], ts.get("e1")!, "TB").x).toBe(22);
+ // e2 bows toward T2 — its label must sit between the two columns.
+ const e2 = pointFor(nodes, edges[1], ts.get("e2")!, "TB");
+ expect(e2.x).toBeGreaterThan(22);
+ expect(e2.x).toBeLessThan(322);
+ });
+
+ it("resolves along the horizontal axis in LR", () => {
+ const nodes = [
+ node("S1", 0, 0),
+ node("S2", 0, 200),
+ node("T1", 400, 0),
+ node("T2", 400, 200)
+ ];
+ const edges = [
+ edge("e1", "S1", "T1"),
+ edge("e2", "S1", "T2"),
+ edge("e3", "S2", "T1"),
+ edge("e4", "S2", "T2")
+ ];
+ const ts = resolveEdgeLabelPositions(nodes, edges, "LR");
+ const placed = edges.map((e) => pointFor(nodes, e, ts.get(e.id)!, "LR"));
+
+ for (let i = 0; i < placed.length; i++) {
+ for (let j = i + 1; j < placed.length; j++) {
+ expect(collide(placed[i], placed[j])).toBe(false);
+ }
+ }
+ });
+
+ it("is deterministic across runs", () => {
+ const nodes = [node("S", 0, 0), node("T1", 0, 400), node("T2", 300, 400)];
+ const edges = [edge("e1", "S", "T1"), edge("e2", "S", "T2")];
+
+ const a = resolveEdgeLabelPositions(nodes, edges, "TB");
+ const b = resolveEdgeLabelPositions(nodes, [...edges].reverse(), "TB");
+
+ expect(a.get("e1")).toBe(b.get("e1"));
+ expect(a.get("e2")).toBe(b.get("e2"));
+ });
+
+ it("widens the box for long labels so they still clear", () => {
+ const nodes = [
+ node("S1", 0, 0),
+ node("S2", 200, 0),
+ node("T1", 0, 400),
+ node("T2", 200, 400)
+ ];
+ const edges = [
+ {
+ ...edge("e1", "S1", "T1"),
+ data: {
+ kind: "movement",
+ quantity: 1,
+ labelText: "RECEIVING-DOCK-A",
+ dimmed: false
+ }
+ },
+ {
+ ...edge("e2", "S2", "T2"),
+ data: {
+ kind: "movement",
+ quantity: 1,
+ labelText: "RECEIVING-DOCK-B",
+ dimmed: false
+ }
+ }
+ ] as unknown as LineageEdge[];
+
+ const ts = resolveEdgeLabelPositions(nodes, edges, "TB");
+ const a = pointFor(nodes, edges[0], ts.get("e1")!, "TB");
+ const b = pointFor(nodes, edges[1], ts.get("e2")!, "TB");
+ const wide = "RECEIVING-DOCK-A".length * 6.2 + 20;
+
+ expect(collide(a, b, wide)).toBe(false);
+ });
+
+ it("skips edges whose endpoints are missing", () => {
+ const ts = resolveEdgeLabelPositions(
+ [node("A", 0, 0)],
+ [edge("e1", "A", "GONE")],
+ "TB"
+ );
+
+ expect(ts.size).toBe(0);
+ });
+
+ it("returns a parameter, so a dragged node takes its label along", () => {
+ // The regression: resolving to an absolute point stranded the pill in open
+ // canvas as soon as the node moved. A `t` re-evaluates against the new
+ // endpoints and stays on the curve.
+ const nodes = [node("A", 0, 0), node("B", 0, 400)];
+ const e = edge("e1", "A", "B");
+ const t = resolveEdgeLabelPositions(nodes, [e], "TB").get("e1")!;
+
+ const before = pointFor(nodes, e, t, "TB");
+ const dragged = [node("A", 0, 0), node("B", 600, 900)];
+ const after = pointFor(dragged, e, t, "TB");
+
+ expect(after).not.toEqual(before);
+ // Still exactly on the path between the moved endpoints.
+ expect(after).toEqual(edgeLabelPoint(t, 22, 22, "bottom", 622, 922, "top"));
+ });
+});
+
+describe("smoothStepPolyline", () => {
+ it("routes a TB edge down, across, then down", () => {
+ // Colinear joints are collapsed — xyflow draws those as a plain `L`.
+ expect(smoothStepPolyline(0, 0, "bottom", 200, 400, "top")).toEqual([
+ { x: 0, y: 0 },
+ { x: 0, y: 200 },
+ { x: 200, y: 200 },
+ { x: 200, y: 400 }
+ ]);
+ });
+
+ it("routes an LR edge across, down, then across", () => {
+ expect(smoothStepPolyline(0, 0, "right", 400, 200, "left")).toEqual([
+ { x: 0, y: 0 },
+ { x: 200, y: 0 },
+ { x: 200, y: 200 },
+ { x: 400, y: 200 }
+ ]);
+ });
+
+ it("collapses a dead-straight edge to a single segment", () => {
+ // No real corners here, so nothing should read as a bend — otherwise
+ // label placement would refuse every position on the line.
+ expect(smoothStepPolyline(0, 0, "bottom", 0, 400, "top")).toEqual([
+ { x: 0, y: 0 },
+ { x: 0, y: 400 }
+ ]);
+ });
+
+ it("puts a straight run's midpoint exactly on the line", () => {
+ const p = edgeLabelPoint(0.5, 0, 0, "bottom", 0, 400, "top");
+ expect(p.x).toBe(0);
+ expect(p.y).toBeCloseTo(200, 5);
+ });
+
+ it("reports how close a point is to a bend", () => {
+ // A label parked on a corner floats off the rounded path the renderer
+ // draws, so placement rejects any candidate whose clearance is too small.
+ // Asserted on the polyline directly — `edgeLabelPoint` follows EDGE_STYLE,
+ // and a bezier has no corners at all.
+ const line = smoothStepPolyline(0, 0, "bottom", 300, 400, "top");
+
+ // Dead on the first corner.
+ const corner = pointAlongPolyline(line, 200 / 700);
+ expect(corner.distanceToBend).toBeCloseTo(0, 5);
+
+ // Halfway along the horizontal run, as far from either corner as possible.
+ const middle = pointAlongPolyline(line, (200 + 150) / 700);
+ expect(middle.distanceToBend).toBeCloseTo(150, 5);
+
+ // Endpoints are not themselves bends, so the clearance there is the run
+ // back to the first/last corner (200 each on this path).
+ expect(pointAlongPolyline(line, 0).distanceToBend).toBeCloseTo(200, 5);
+ expect(pointAlongPolyline(line, 1).distanceToBend).toBeCloseTo(200, 5);
+
+ // A path with no corners at all has nothing to avoid.
+ expect(
+ pointAlongPolyline(smoothStepPolyline(0, 0, "bottom", 0, 400, "top"), 0.5)
+ .distanceToBend
+ ).toBe(Infinity);
+ });
+});
diff --git a/apps/erp/app/modules/inventory/ui/Traceability/worker/hooks.ts b/apps/erp/app/modules/inventory/ui/Traceability/worker/hooks.ts
index 0070a1244e..336b6e9cd6 100644
--- a/apps/erp/app/modules/inventory/ui/Traceability/worker/hooks.ts
+++ b/apps/erp/app/modules/inventory/ui/Traceability/worker/hooks.ts
@@ -22,16 +22,24 @@ export function useAsyncLayout(
direction: LayoutDirection,
spacing: number,
rejectIds: Set<string>,
+ rootIds: string[],
layoutVersion: number
): LayoutResult | null {
const [result, setResult] = useState<LayoutResult | null>(null);
const rejectIdsArray = useMemo(() => Array.from(rejectIds), [rejectIds]);
+ const rootKey = rootIds.join("|");
- // biome-ignore lint/correctness/useExhaustiveDependencies: layoutVersion is a manual relayout trigger
+ // biome-ignore lint/correctness/useExhaustiveDependencies: layoutVersion is a manual relayout trigger; rootIds is keyed by rootKey
useEffect(() => {
let cancelled = false;
manager
- .layout({ payload, direction, spacing, rejectIds: rejectIdsArray })
+ .layout({
+ payload,
+ direction,
+ spacing,
+ rejectIds: rejectIdsArray,
+ rootIds
+ })
.then((r) => {
if (cancelled || r === null) return;
setResult(r);
@@ -39,7 +47,15 @@ export function useAsyncLayout(
return () => {
cancelled = true;
};
- }, [manager, payload, direction, spacing, rejectIdsArray, layoutVersion]);
+ }, [
+ manager,
+ payload,
+ direction,
+ spacing,
+ rejectIdsArray,
+ rootKey,
+ layoutVersion
+ ]);
return result;
}
diff --git a/apps/erp/app/modules/sales/AGENTS.md b/apps/erp/app/modules/sales/AGENTS.md
index 411d5c0f96..09228af292 100644
--- a/apps/erp/app/modules/sales/AGENTS.md
+++ b/apps/erp/app/modules/sales/AGENTS.md
@@ -27,7 +27,7 @@ Quotes (with cost rollup and pricing), sales orders, sales RFQs, customer manage
### Never
- Bypass the `convert` edge function for quote→order or RFQ→quote conversions.
-- Delete `quoteLinePrice` rows without preserving `discountPercent`, `leadTime`, and `categoryMarkups` — use `upsertQuoteLinePrices`.
+- Delete `quoteLinePrice` rows when *rewriting* a line's pricing — that must preserve `discountPercent`, `leadTime`, and `categoryMarkups` via `upsertQuoteLinePrices`. Deleting rows for a quantity break the line no longer offers is different and required: see `reconcileQuantityBreaks` (`sales.utils.ts`) and its use in `x+/quote+/$quoteId.$lineId.details.tsx`. Orphaned rows render as selectable options on the customer share page.
- Store `discountPercent` as a whole number (e.g., 10 instead of 0.10).
## Validation Commands
diff --git a/apps/erp/app/modules/sales/index.ts b/apps/erp/app/modules/sales/index.ts
index 46f1b9ed60..f0ff82b5ab 100644
--- a/apps/erp/app/modules/sales/index.ts
+++ b/apps/erp/app/modules/sales/index.ts
@@ -1,3 +1,4 @@
export * from "./sales.models";
export * from "./sales.service";
+export * from "./sales.utils";
export * from "./types";
diff --git a/apps/erp/app/modules/sales/sales.server.ts b/apps/erp/app/modules/sales/sales.server.ts
index f6044736c3..682fdd794a 100644
--- a/apps/erp/app/modules/sales/sales.server.ts
+++ b/apps/erp/app/modules/sales/sales.server.ts
@@ -171,3 +171,50 @@ export async function duplicatePriceOverrides(
return { duplicated: 0, skipped: 0, overwritten: 0, error: e };
}
}
+
+/**
+ * Save a quote line and reconcile its quantity-break prices atomically.
+ *
+ * These three writes have to land together. Previously the line update
+ * committed first, then the prune, then the seed — so a resolver failure left
+ * the line saved with its new breaks unpriced, and a failure after the prune
+ * left it short rows it used to have. The user saw a flashed error but the data
+ * was already half-applied.
+ *
+ * Price ROWS are computed by the caller beforehand (the resolvers only read),
+ * so a pricing failure aborts before anything is written at all. Those reads
+ * are outside the transaction, which is fine: none of them touch the rows being
+ * written here.
+ */
+export async function saveQuoteLineWithPrices(args: {
+ lineId: string;
+ line: Record<string, unknown>;
+ removedQuantities: number[];
+ priceRows: Record<string, unknown>[];
+}): Promise<void> {
+ const { lineId, line, removedQuantities, priceRows } = args;
+ const db = getDatabaseClient();
+
+ await db.transaction().execute(async (trx) => {
+ await trx
+ .updateTable("quoteLine")
+ .set(line as never)
+ .where("id", "=", lineId)
+ .execute();
+
+ if (removedQuantities.length > 0) {
+ await trx
+ .deleteFrom("quoteLinePrice")
+ .where("quoteLineId", "=", lineId)
+ .where("quantity", "in", removedQuantities)
+ .execute();
+ }
+
+ if (priceRows.length > 0) {
+ await trx
+ .insertInto("quoteLinePrice")
+ .values(priceRows as never)
+ .execute();
+ }
+ });
+}
diff --git a/apps/erp/app/modules/sales/sales.service.ts b/apps/erp/app/modules/sales/sales.service.ts
index 9e71f6a75d..a1f42f195a 100644
--- a/apps/erp/app/modules/sales/sales.service.ts
+++ b/apps/erp/app/modules/sales/sales.service.ts
@@ -4224,14 +4224,45 @@ async function buildCostEffects(
return { effects, costCategoryKeys };
}
-export async function calculatePricesForQuantities(
+/**
+ * The three price resolvers below each read a pile of context, compute price
+ * rows, and finish with ONE insert. They are split at that seam so a caller
+ * that needs the write to be atomic with other writes can build the rows first
+ * and hand them to a transaction (see `saveQuoteLineWithPrices`).
+ *
+ * `itemIdOverride` exists because the quote-line save path updates the line and
+ * prices together: the row in the database still holds the OLD `itemId` while
+ * the new one is only in the validated form data, so the caller passes it in
+ * rather than the builder reading a value that is about to change.
+ */
+export type QuoteLinePriceRow = {
+ quoteId: string;
+ quoteLineId: string;
+ companyId: string;
+ quantity: number;
+ unitPrice: number;
+ exchangeRate: number;
+ createdBy: string;
+ leadTime: number;
+ discountPercent: number;
+ categoryMarkups?: Record<string, number>;
+ priceSource?: string;
+};
+
+type BuildPriceRowsResult = {
+ rows: QuoteLinePriceRow[];
+ error: unknown | null;
+};
+
+export async function buildMakeToOrderPriceRows(
client: SupabaseClient<Database>,
quoteId: string,
quoteLineId: string,
quantities: number[],
- userId: string
-) {
- if (!quantities.length) return { error: null };
+ userId: string,
+ itemIdOverride?: string | null
+): Promise<BuildPriceRowsResult> {
+ if (!quantities.length) return { rows: [], error: null };
// 1. Fetch quote (with companyId + customerId) and line in parallel
const [quoteResult, lineResult] = await Promise.all([
@@ -4247,8 +4278,8 @@ export async function calculatePricesForQuantities(
.single()
]);
- if (quoteResult.error) return { error: quoteResult.error };
- if (lineResult.error) return { error: lineResult.error };
+ if (quoteResult.error) return { rows: [], error: quoteResult.error };
+ if (lineResult.error) return { rows: [], error: lineResult.error };
// Fetch settings filtered by company (required for service-role access)
const settingsResult = await client
@@ -4257,11 +4288,14 @@ export async function calculatePricesForQuantities(
.eq("id", quoteResult.data.companyId)
.single();
- if (settingsResult.error) return { error: settingsResult.error };
+ if (settingsResult.error) return { rows: [], error: settingsResult.error };
const companyId = quoteResult.data.companyId;
const customerId = quoteResult.data.customerId ?? undefined;
- const itemId = lineResult.data.itemId ?? undefined;
+ const itemId =
+ itemIdOverride === undefined
+ ? (lineResult.data.itemId ?? undefined)
+ : (itemIdOverride ?? undefined);
const exchangeRate = quoteResult.data.exchangeRate ?? 1;
const precision = lineResult.data.unitPricePrecision ?? 2;
@@ -4279,11 +4313,11 @@ export async function calculatePricesForQuantities(
const result = await buildCostEffects(client, quoteLineId);
// buildCostEffects returns null when the line has no costed method yet —
// treat as a no-op so partial drafts don't block the save.
- if (!result) return { error: null };
+ if (!result) return { rows: [], error: null };
const { effects } = result;
- const priceRows = [];
+ const priceRows: QuoteLinePriceRow[] = [];
for (const qty of quantities) {
const categoryCosts: Record<string, number> = {};
for (const key of costCategoryKeys) {
@@ -4323,7 +4357,27 @@ export async function calculatePricesForQuantities(
});
}
- const insertResult = await client.from("quoteLinePrice").insert(priceRows);
+ return { rows: priceRows, error: null };
+}
+
+export async function calculatePricesForQuantities(
+ client: SupabaseClient<Database>,
+ quoteId: string,
+ quoteLineId: string,
+ quantities: number[],
+ userId: string
+) {
+ const { rows, error } = await buildMakeToOrderPriceRows(
+ client,
+ quoteId,
+ quoteLineId,
+ quantities,
+ userId
+ );
+ if (error) return { error };
+ if (!rows.length) return { error: null };
+
+ const insertResult = await client.from("quoteLinePrice").insert(rows);
if (insertResult.error) {
logger.error("Failed to insert MtO calc quote line prices", {
quoteLineId,
@@ -4334,15 +4388,16 @@ export async function calculatePricesForQuantities(
return { error: null };
}
-export async function resolveQuoteLinePrices(
+export async function buildPullFromInventoryPriceRows(
client: SupabaseClient<Database>,
companyId: string,
quoteId: string,
quoteLineId: string,
quantities: number[],
- userId: string
-) {
- if (!quantities.length) return { error: null };
+ userId: string,
+ itemIdOverride?: string | null
+): Promise<BuildPriceRowsResult> {
+ if (!quantities.length) return { rows: [], error: null };
const [quoteResult, lineResult] = await Promise.all([
client
@@ -4357,17 +4412,19 @@ export async function resolveQuoteLinePrices(
.single()
]);
- if (quoteResult.error) return { error: quoteResult.error };
- if (lineResult.error) return { error: lineResult.error };
+ if (quoteResult.error) return { rows: [], error: quoteResult.error };
+ if (lineResult.error) return { rows: [], error: lineResult.error };
+
+ const itemId =
+ itemIdOverride === undefined ? lineResult.data.itemId : itemIdOverride;
// Missing itemId is a benign draft state, not an error.
- if (!lineResult.data.itemId) return { error: null };
+ if (!itemId) return { rows: [], error: null };
- const itemId = lineResult.data.itemId;
const exchangeRate = quoteResult.data.exchangeRate ?? 1;
const precision = lineResult.data.unitPricePrecision ?? 2;
const customerId = quoteResult.data.customerId ?? undefined;
- const priceRows = [];
+ const priceRows: QuoteLinePriceRow[] = [];
for (const qty of quantities) {
const resolved = await resolvePrice(client, companyId, {
itemId,
@@ -4388,7 +4445,29 @@ export async function resolveQuoteLinePrices(
});
}
- const insertResult = await client.from("quoteLinePrice").insert(priceRows);
+ return { rows: priceRows, error: null };
+}
+
+export async function resolveQuoteLinePrices(
+ client: SupabaseClient<Database>,
+ companyId: string,
+ quoteId: string,
+ quoteLineId: string,
+ quantities: number[],
+ userId: string
+) {
+ const { rows, error } = await buildPullFromInventoryPriceRows(
+ client,
+ companyId,
+ quoteId,
+ quoteLineId,
+ quantities,
+ userId
+ );
+ if (error) return { error };
+ if (!rows.length) return { error: null };
+
+ const insertResult = await client.from("quoteLinePrice").insert(rows);
if (insertResult.error) {
logger.error("Failed to insert Pull quote line prices", {
quoteLineId,
@@ -4399,15 +4478,16 @@ export async function resolveQuoteLinePrices(
return { error: null };
}
-export async function resolvePurchaseToOrderPrices(
+export async function buildPurchaseToOrderPriceRows(
client: SupabaseClient<Database>,
companyId: string,
quoteId: string,
quoteLineId: string,
quantities: number[],
- userId: string
-) {
- if (!quantities.length) return { error: null };
+ userId: string,
+ itemIdOverride?: string | null
+): Promise<BuildPriceRowsResult> {
+ if (!quantities.length) return { rows: [], error: null };
const [quoteResult, lineResult] = await Promise.all([
client
@@ -4422,18 +4502,20 @@ export async function resolvePurchaseToOrderPrices(
.single()
]);
- if (quoteResult.error) return { error: quoteResult.error };
- if (lineResult.error) return { error: lineResult.error };
- if (!lineResult.data.itemId) return { error: null };
+ if (quoteResult.error) return { rows: [], error: quoteResult.error };
+ if (lineResult.error) return { rows: [], error: lineResult.error };
+
+ const itemId =
+ itemIdOverride === undefined ? lineResult.data.itemId : itemIdOverride;
+ if (!itemId) return { rows: [], error: null };
- const itemId = lineResult.data.itemId;
const exchangeRate = quoteResult.data.exchangeRate ?? 1;
const precision = lineResult.data.unitPricePrecision ?? 2;
const customerId = quoteResult.data.customerId ?? undefined;
const priceMap = await getSupplierPriceBreaksForItems(client, [itemId]);
- const priceRows = [];
+ const priceRows: QuoteLinePriceRow[] = [];
for (const qty of quantities) {
const supplierPrice = lookupBuyPriceFromMap(itemId, qty, priceMap, 0);
const resolved = await resolvePrice(client, companyId, {
@@ -4456,7 +4538,29 @@ export async function resolvePurchaseToOrderPrices(
});
}
- const insertResult = await client.from("quoteLinePrice").insert(priceRows);
+ return { rows: priceRows, error: null };
+}
+
+export async function resolvePurchaseToOrderPrices(
+ client: SupabaseClient<Database>,
+ companyId: string,
+ quoteId: string,
+ quoteLineId: string,
+ quantities: number[],
+ userId: string
+) {
+ const { rows, error } = await buildPurchaseToOrderPriceRows(
+ client,
+ companyId,
+ quoteId,
+ quoteLineId,
+ quantities,
+ userId
+ );
+ if (error) return { error };
+ if (!rows.length) return { error: null };
+
+ const insertResult = await client.from("quoteLinePrice").insert(rows);
if (insertResult.error) {
logger.error("Failed to insert P2O quote line prices", {
quoteLineId,
diff --git a/apps/erp/app/modules/sales/sales.utils.test.ts b/apps/erp/app/modules/sales/sales.utils.test.ts
index 5a3ae1864d..7ab1e70763 100644
--- a/apps/erp/app/modules/sales/sales.utils.test.ts
+++ b/apps/erp/app/modules/sales/sales.utils.test.ts
@@ -1,5 +1,60 @@
import { describe, expect, it } from "vitest";
-import { decideRecalcPricing, getEffectiveDefaultMarkups } from "./sales.utils";
+import {
+ decideRecalcPricing,
+ getEffectiveDefaultMarkups,
+ reconcileQuantityBreaks
+} from "./sales.utils";
+
+describe("reconcileQuantityBreaks", () => {
+ it("reports nothing when the breaks are unchanged", () => {
+ expect(reconcileQuantityBreaks([1, 25, 50], [1, 25, 50])).toEqual({
+ added: [],
+ removed: []
+ });
+ });
+ it("reports only additions when breaks are added", () => {
+ expect(reconcileQuantityBreaks([24], [24, 32])).toEqual({
+ added: [32],
+ removed: []
+ });
+ });
+ it("reports removals when a break is dropped — the orphan bug", () => {
+ expect(reconcileQuantityBreaks([1, 24, 32], [24])).toEqual({
+ added: [],
+ removed: [1, 32]
+ });
+ });
+ it("reports both sides of a swap", () => {
+ expect(reconcileQuantityBreaks([1, 25], [25, 100])).toEqual({
+ added: [100],
+ removed: [1]
+ });
+ });
+ it("removes every row when the line offers no breaks", () => {
+ expect(reconcileQuantityBreaks([1, 24], [])).toEqual({
+ added: [],
+ removed: [1, 24]
+ });
+ });
+ it("adds every break when no price rows exist yet", () => {
+ expect(reconcileQuantityBreaks([], [1, 25])).toEqual({
+ added: [1, 25],
+ removed: []
+ });
+ });
+ it("dedupes repeated quantities on either side", () => {
+ expect(reconcileQuantityBreaks([24, 24], [32, 32])).toEqual({
+ added: [32],
+ removed: [24]
+ });
+ });
+ it("handles fractional quantities (the column is NUMERIC(16,5))", () => {
+ expect(reconcileQuantityBreaks([0.5, 1.25], [1.25, 2.5])).toEqual({
+ added: [2.5],
+ removed: [0.5]
+ });
+ });
+});
describe("getEffectiveDefaultMarkups", () => {
it("returns {} when all category defaults are 0 (feature disabled)", () => {
diff --git a/apps/erp/app/modules/sales/sales.utils.ts b/apps/erp/app/modules/sales/sales.utils.ts
index 6ef950ae5b..ca4501b9d0 100644
--- a/apps/erp/app/modules/sales/sales.utils.ts
+++ b/apps/erp/app/modules/sales/sales.utils.ts
@@ -18,6 +18,27 @@ export function getEffectiveDefaultMarkups(
return enabled ? defaultMarkups : {};
}
+/**
+ * Reconcile the quantity breaks a quote line currently offers against the
+ * `quoteLinePrice` rows that exist for it, in BOTH directions.
+ *
+ * The save path historically computed only `added` and seeded rows for it, so
+ * removing a break left its price row behind forever. Those orphans render as
+ * selectable options on the customer share page and trip the finalize
+ * validation, so removal must prune.
+ */
+export function reconcileQuantityBreaks(
+ existing: number[],
+ desired: number[]
+): { added: number[]; removed: number[] } {
+ const existingSet = new Set(existing);
+ const desiredSet = new Set(desired);
+ return {
+ added: Array.from(desiredSet).filter((q) => !existingSet.has(q)),
+ removed: Array.from(existingSet).filter((q) => !desiredSet.has(q))
+ };
+}
+
export type RecalcPricingDecision =
| { mode: "reprice"; markups: CategoryMarkups }
| { mode: "preserve" };
diff --git a/apps/erp/app/modules/sales/ui/Quotes/QuoteFinalizeModal.tsx b/apps/erp/app/modules/sales/ui/Quotes/QuoteFinalizeModal.tsx
index 0ba25b50f3..8090fcd0c5 100644
--- a/apps/erp/app/modules/sales/ui/Quotes/QuoteFinalizeModal.tsx
+++ b/apps/erp/app/modules/sales/ui/Quotes/QuoteFinalizeModal.tsx
@@ -43,8 +43,6 @@ import type {
type QuotationFinalizeModalProps = {
onClose: () => void;
quote?: Quotation;
- lines: QuotationLine[];
- pricing: QuotationPrice[];
shipment: QuotationShipment | null;
fetcher: FetcherWithComponents<{}>;
defaultCc?: string[];
@@ -55,8 +53,7 @@ const QuotationFinalizeModal = ({
onClose,
fetcher,
shipment,
- defaultCc = [],
- pricing
+ defaultCc = []
}: QuotationFinalizeModalProps) => {
const { t } = useLingui();
const { quoteId } = useParams();
@@ -78,7 +75,10 @@ const QuotationFinalizeModal = ({
getQuoteLines(carbon, quoteId),
getQuoteLinePricesByQuoteId(carbon, quoteId)
]);
- setLines(lines.data ?? []);
+ // Declined lines never receive pricing, lead time, or shipping, and
+ // `finalizeQuote` excludes them too — validating them here would flag
+ // every quote containing one.
+ setLines((lines.data ?? []).filter((line) => line.status !== "No Quote"));
setPrices(prices.data ?? []);
} catch {
toast.error("Failed to load quote data");
@@ -108,7 +108,20 @@ const QuotationFinalizeModal = ({
.map((line) => line.itemReadableId)
.filter((id): id is string => id !== undefined);
- const linesWithZeroPriceOrLeadTime = prices
+ // Only rows for a quantity break the line still offers count. A break that
+ // was removed can leave its price row behind, and a freshly-seeded orphan
+ // carries leadTime 0 / shippingCost 0 — enough to fail both checks below for
+ // a quantity the quote no longer sells.
+ const livePrices = prices.filter((price) => {
+ const line = lines.find((line) => line.id === price.quoteLineId);
+ return (
+ !!line &&
+ Array.isArray(line.quantity) &&
+ line.quantity.includes(price.quantity)
+ );
+ });
+
+ const linesWithZeroPriceOrLeadTime = livePrices
.filter((price) => price.unitPrice === 0 || price.leadTime === 0)
.map((price) => {
const line = lines.find((line) => line.id === price.quoteLineId);
@@ -125,7 +138,9 @@ const QuotationFinalizeModal = ({
const hasShippingCost = shipment?.shippingCost && shipment.shippingCost > 0;
const allLinesHaveShippingCosts = lines.every((line) => {
- const linePrices = prices.filter((price) => price.quoteLineId === line.id);
+ const linePrices = livePrices.filter(
+ (price) => price.quoteLineId === line.id
+ );
return linePrices.every(
(price) => price.shippingCost && price.shippingCost > 0
);
diff --git a/apps/erp/app/modules/sales/ui/Quotes/QuoteHeader.tsx b/apps/erp/app/modules/sales/ui/Quotes/QuoteHeader.tsx
index fab7bb0031..83cab656a4 100644
--- a/apps/erp/app/modules/sales/ui/Quotes/QuoteHeader.tsx
+++ b/apps/erp/app/modules/sales/ui/Quotes/QuoteHeader.tsx
@@ -339,8 +339,6 @@ const QuoteHeader = () => {
{finalizeModal.isOpen && (
<QuoteFinalizeModal
quote={routeData?.quote}
- lines={eligibleLines ?? []}
- pricing={routeData?.prices ?? []}
shipment={routeData?.shipment ?? null}
onClose={finalizeModal.onClose}
fetcher={finalizeFetcher}
diff --git a/apps/erp/app/modules/sales/ui/Quotes/QuoteSummary.tsx b/apps/erp/app/modules/sales/ui/Quotes/QuoteSummary.tsx
index 56913b1437..6a423ad3e2 100644
--- a/apps/erp/app/modules/sales/ui/Quotes/QuoteSummary.tsx
+++ b/apps/erp/app/modules/sales/ui/Quotes/QuoteSummary.tsx
@@ -111,9 +111,16 @@ const LineItems = ({
if (!line.id) {
return acc;
}
+ // Scope to the breaks the line still offers — a removed break can
+ // leave an orphaned price row behind.
acc[line.id!] =
routeData?.prices
- ?.filter((p) => p.quoteLineId === line.id)
+ ?.filter(
+ (p) =>
+ p.quoteLineId === line.id &&
+ Array.isArray(line.quantity) &&
+ line.quantity.includes(p.quantity)
+ )
.sort((a, b) => a.quantity - b.quantity) ?? [];
return acc;
},
diff --git a/apps/erp/app/modules/sales/ui/Quotes/QuoteToOrderDrawer.tsx b/apps/erp/app/modules/sales/ui/Quotes/QuoteToOrderDrawer.tsx
index 69ba495dcd..c8d95f10d3 100644
--- a/apps/erp/app/modules/sales/ui/Quotes/QuoteToOrderDrawer.tsx
+++ b/apps/erp/app/modules/sales/ui/Quotes/QuoteToOrderDrawer.tsx
@@ -403,7 +403,14 @@ const LinePricingForm = ({
const pricingByLine = useMemo(
() =>
lines.reduce<Record<string, QuotationPrice[]>>((acc, line) => {
- acc[line.id!] = pricing.filter((p) => p.quoteLineId === line.id);
+ // Scope to the breaks the line still offers — an orphaned price row
+ // picked here would convert into a real sales order line.
+ acc[line.id!] = pricing.filter(
+ (p) =>
+ p.quoteLineId === line.id &&
+ Array.isArray(line.quantity) &&
+ line.quantity.includes(p.quantity)
+ );
return acc;
}, {}),
[lines, pricing]
diff --git a/apps/erp/app/routes/api+/mcp+/lib/tool-metadata.json b/apps/erp/app/routes/api+/mcp+/lib/tool-metadata.json
index ca727721a0..8a9f07d50c 100644
--- a/apps/erp/app/routes/api+/mcp+/lib/tool-metadata.json
+++ b/apps/erp/app/routes/api+/mcp+/lib/tool-metadata.json
@@ -1,6 +1,6 @@
{
- "generated": "2026-08-06T18:37:59.212Z",
- "totalTools": 1414,
+ "generated": "2026-08-07T00:38:01.169Z",
+ "totalTools": 1417,
"modules": 15,
"tools": [
{
@@ -37659,6 +37659,52 @@
]
}
},
+ {
+ "name": "sales_buildMakeToOrderPriceRows",
+ "module": "sales",
+ "classification": "WRITE",
+ "description": "build make to order price rows",
+ "paramCount": 4,
+ "serviceParams": [
+ "client",
+ "quoteId",
+ "quoteLineId",
+ "quantities",
+ "userId",
+ "itemIdOverride"
+ ],
+ "injectAuth": [
+ "companyId"
+ ],
+ "schema": {
+ "type": "object",
+ "properties": {
+ "quoteId": {
+ "type": "string"
+ },
+ "quoteLineId": {
+ "type": "string"
+ },
+ "quantities": {
+ "type": "array",
+ "items": {
+ "type": "number"
+ }
+ },
+ "itemIdOverride": {
+ "type": [
+ "string",
+ "null"
+ ]
+ }
+ },
+ "required": [
+ "quoteId",
+ "quoteLineId",
+ "quantities"
+ ]
+ }
+ },
{
"name": "sales_calculatePricesForQuantities",
"module": "sales",
@@ -37698,6 +37744,53 @@
]
}
},
+ {
+ "name": "sales_buildPullFromInventoryPriceRows",
+ "module": "sales",
+ "classification": "WRITE",
+ "description": "build pull from inventory price rows",
+ "paramCount": 4,
+ "serviceParams": [
+ "client",
+ "companyId",
+ "quoteId",
+ "quoteLineId",
+ "quantities",
+ "userId",
+ "itemIdOverride"
+ ],
+ "injectAuth": [
+ "companyId"
+ ],
+ "schema": {
+ "type": "object",
+ "properties": {
+ "quoteId": {
+ "type": "string"
+ },
+ "quoteLineId": {
+ "type": "string"
+ },
+ "quantities": {
+ "type": "array",
+ "items": {
+ "type": "number"
+ }
+ },
+ "itemIdOverride": {
+ "type": [
+ "string",
+ "null"
+ ]
+ }
+ },
+ "required": [
+ "quoteId",
+ "quoteLineId",
+ "quantities"
+ ]
+ }
+ },
{
"name": "sales_resolveQuoteLinePrices",
"module": "sales",
@@ -37738,6 +37831,53 @@
]
}
},
+ {
+ "name": "sales_buildPurchaseToOrderPriceRows",
+ "module": "sales",
+ "classification": "WRITE",
+ "description": "build purchase to order price rows",
+ "paramCount": 4,
+ "serviceParams": [
+ "client",
+ "companyId",
+ "quoteId",
+ "quoteLineId",
+ "quantities",
+ "userId",
+ "itemIdOverride"
+ ],
+ "injectAuth": [
+ "companyId"
+ ],
+ "schema": {
+ "type": "object",
+ "properties": {
+ "quoteId": {
+ "type": "string"
+ },
+ "quoteLineId": {
+ "type": "string"
+ },
+ "quantities": {
+ "type": "array",
+ "items": {
+ "type": "number"
+ }
+ },
+ "itemIdOverride": {
+ "type": [
+ "string",
+ "null"
+ ]
+ }
+ },
+ "required": [
+ "quoteId",
+ "quoteLineId",
+ "quantities"
+ ]
+ }
+ },
{
"name": "sales_resolvePurchaseToOrderPrices",
"module": "sales",
diff --git a/apps/erp/app/routes/share+/quote.$id.tsx b/apps/erp/app/routes/share+/quote.$id.tsx
index 4b810fc827..0a5230c3c3 100644
--- a/apps/erp/app/routes/share+/quote.$id.tsx
+++ b/apps/erp/app/routes/share+/quote.$id.tsx
@@ -342,9 +342,17 @@ const LineItems = ({
if (!line.id) {
return acc;
}
+ // Scope to the breaks the line actually offers. A removed break can
+ // leave its price row behind, and an orphan here becomes a selectable
+ // option the customer was never meant to see.
acc[line.id!] =
quoteLinePrices
- ?.filter((p) => p.quoteLineId === line.id)
+ ?.filter(
+ (p) =>
+ p.quoteLineId === line.id &&
+ Array.isArray(line.quantity) &&
+ line.quantity.includes(p.quantity)
+ )
.sort((a, b) => a.quantity - b.quantity) ?? [];
return acc;
}, {}) ?? {},
@@ -363,11 +371,7 @@ const LineItems = ({
return (
<VStack spacing={8} className="w-full">
{quoteLines?.map((line) => {
- const prices = quoteLinePrices
- ?.filter((price) => price.quoteLineId === line.id)
- .sort((a, b) => a.quantity - b.quantity);
-
- if (!line || !prices || !line.id) {
+ if (!line || !line.id) {
return null;
}
diff --git a/apps/erp/app/routes/x+/quote+/$quoteId.$lineId.details.tsx b/apps/erp/app/routes/x+/quote+/$quoteId.$lineId.details.tsx
index bcc66fab99..9cdc52ab37 100644
--- a/apps/erp/app/routes/x+/quote+/$quoteId.$lineId.details.tsx
+++ b/apps/erp/app/routes/x+/quote+/$quoteId.$lineId.details.tsx
@@ -22,10 +22,13 @@ import type {
Quotation,
QuotationOperation,
QuotationPrice,
+ QuoteLinePriceRow,
QuoteMethod
} from "~/modules/sales";
import {
- calculatePricesForQuantities,
+ buildMakeToOrderPriceRows,
+ buildPullFromInventoryPriceRows,
+ buildPurchaseToOrderPriceRows,
getConfigurationParametersByQuoteLineId,
getModelByQuoteLineId,
getOpportunityLineDocuments,
@@ -39,10 +42,9 @@ import {
getRootQuoteMakeMethod,
isQuoteLocked,
quoteLineValidator,
- resolvePurchaseToOrderPrices,
- resolveQuoteLinePrices,
- upsertQuoteLine
+ reconcileQuantityBreaks
} from "~/modules/sales";
+import { saveQuoteLineWithPrices } from "~/modules/sales/sales.server";
import {
OpportunityLineDocuments,
OpportunityLineNotes
@@ -62,6 +64,7 @@ import { getTagsList, type SupplierPriceMap } from "~/modules/shared";
import { getCustomFields, setCustomFields } from "~/utils/form";
import { requireUnlocked } from "~/utils/lockedGuard.server";
import { path } from "~/utils/path";
+import { sanitize } from "~/utils/supabase";
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
const { client, companyId } = await requirePermissions(request, {
@@ -150,7 +153,9 @@ export const loader = async ({ request, params }: LoaderFunctionArgs) => {
export async function action({ request, params }: ActionFunctionArgs) {
assertIsPost(request);
- const { client, companyId, userId } = await requirePermissions(request, {
+ // Still the authorization gate, and load-bearing: the write below goes
+ // through Kysely, which bypasses RLS entirely.
+ const { companyId, userId } = await requirePermissions(request, {
create: "sales"
});
@@ -180,90 +185,110 @@ export async function action({ request, params }: ActionFunctionArgs) {
// biome-ignore lint/correctness/noUnusedVariables: suppressed due to migration
const { id, ...d } = validation.data;
- const updateQuotationLine = await upsertQuoteLine(client, {
- id: lineId,
- ...d,
- updatedBy: userId,
- customFields: setCustomFields(formData)
- });
-
- if (updateQuotationLine.error) {
+ // The line update and its price reconciliation have to land together. Prices
+ // are COMPUTED first (the builders only read), so a pricing failure aborts
+ // before anything is written; the three writes then commit in one
+ // transaction. Previously the line update committed on its own, and a
+ // resolver failure left it saved with its new breaks unpriced.
+ const serviceRole = getCarbonServiceRole();
+ const existingPrices = await serviceRole
+ .from("quoteLinePrice")
+ .select("quantity")
+ .eq("quoteLineId", lineId);
+
+ if (existingPrices.error) {
throw redirect(
path.to.quoteLine(quoteId, lineId),
await flash(
request,
- error(updateQuotationLine.error, "Failed to update quote line")
+ error(existingPrices.error, "Failed to read existing quote line prices")
)
);
}
- // The pricing-seeding branches share the same shape: find quantities the
- // user newly added to the row and invoke the method-specific resolver for
- // just those. Surface any resolver failure via flash so the user knows the
- // line saved but pricing didn't land.
- const methodType = d.methodType;
- const needsSeed =
- (methodType === "Make to Order" ||
- methodType === "Pull from Inventory" ||
- methodType === "Purchase to Order") &&
- !!d.quantity?.length;
-
- if (needsSeed) {
- const serviceRole = getCarbonServiceRole();
- const existingPrices = await serviceRole
- .from("quoteLinePrice")
- .select("quantity")
- .eq("quoteLineId", lineId);
-
- const existingQuantities = new Set(
- (existingPrices.data ?? []).map((p) => p.quantity)
- );
-
- const addedQuantities = (d.quantity ?? []).filter(
- (q) => !existingQuantities.has(q)
+ // Reconcile in both directions. Seeding is method-specific and only covers
+ // the three types below, but PRUNING is unconditional: a break removed from a
+ // Make to Stock line — or from a line whose breaks were all cleared — would
+ // otherwise leave rows behind that render as selectable options on the
+ // customer share page and trip the finalize validation.
+ const { added: addedQuantities, removed: removedQuantities } =
+ reconcileQuantityBreaks(
+ (existingPrices.data ?? []).map((p) => p.quantity),
+ d.quantity ?? []
);
- if (addedQuantities.length > 0) {
- const priceResult =
- methodType === "Make to Order"
- ? await calculatePricesForQuantities(
+ const methodType = d.methodType;
+ const needsSeed =
+ methodType === "Make to Order" ||
+ methodType === "Pull from Inventory" ||
+ methodType === "Purchase to Order";
+
+ let priceRows: QuoteLinePriceRow[] = [];
+ if (needsSeed && addedQuantities.length > 0) {
+ // The stored line still holds the OLD itemId — the new one is only in the
+ // validated form data — so pass it through rather than let the builder read
+ // a value this same request is about to change.
+ const built =
+ methodType === "Make to Order"
+ ? await buildMakeToOrderPriceRows(
+ serviceRole,
+ quoteId,
+ lineId,
+ addedQuantities,
+ userId,
+ d.itemId
+ )
+ : methodType === "Pull from Inventory"
+ ? await buildPullFromInventoryPriceRows(
serviceRole,
+ companyId,
quoteId,
lineId,
addedQuantities,
- userId
- )
- : methodType === "Pull from Inventory"
- ? await resolveQuoteLinePrices(
- serviceRole,
- companyId,
- quoteId,
- lineId,
- addedQuantities,
- userId
- )
- : await resolvePurchaseToOrderPrices(
- serviceRole,
- companyId,
- quoteId,
- lineId,
- addedQuantities,
- userId
- );
-
- if (priceResult?.error) {
- throw redirect(
- path.to.quoteLine(quoteId, lineId),
- await flash(
- request,
- error(
- priceResult.error,
- `Failed to seed ${methodType} prices for new quantities`
+ userId,
+ d.itemId
)
+ : await buildPurchaseToOrderPriceRows(
+ serviceRole,
+ companyId,
+ quoteId,
+ lineId,
+ addedQuantities,
+ userId,
+ d.itemId
+ );
+
+ if (built.error) {
+ throw redirect(
+ path.to.quoteLine(quoteId, lineId),
+ await flash(
+ request,
+ error(
+ built.error,
+ `Failed to calculate ${methodType} prices for new quantities`
)
- );
- }
+ )
+ );
}
+ priceRows = built.rows;
+ }
+
+ try {
+ await saveQuoteLineWithPrices({
+ lineId,
+ line: {
+ ...sanitize({ ...d, updatedBy: userId }),
+ customFields: setCustomFields(formData)
+ },
+ removedQuantities,
+ priceRows
+ });
+ } catch (err) {
+ // Kysely throws on rollback — nothing was written.
+ throw redirect(
+ path.to.quoteLine(quoteId, lineId),
+ await flash(request, error(err, "Failed to update quote line"))
+ );
}
throw redirect(path.to.quoteLine(quoteId, lineId));
diff --git a/apps/erp/app/routes/x+/traceability+/graph.tsx b/apps/erp/app/routes/x+/traceability+/graph.tsx
index e3f8c88f47..a5b4fbaecd 100644
--- a/apps/erp/app/routes/x+/traceability+/graph.tsx
+++ b/apps/erp/app/routes/x+/traceability+/graph.tsx
@@ -19,7 +19,13 @@ import {
fetchLineageSubgraph,
type LineagePayload
} from "~/modules/inventory/lineage.server";
+import { isClusterId } from "~/modules/inventory/ui/Traceability/cluster";
import { clampDepth } from "~/modules/inventory/ui/Traceability/constants";
+import {
+ getEntityJobId,
+ withJobNode
+} from "~/modules/inventory/ui/Traceability/jobNode";
+import { useTraceabilityStore } from "~/modules/inventory/ui/Traceability/store";
import { TraceabilityGraph } from "~/modules/inventory/ui/Traceability/TraceabilityGraph";
import { TraceabilitySidebar } from "~/modules/inventory/ui/Traceability/TraceabilitySidebar";
import { stateEntityId } from "~/modules/inventory/ui/Traceability/utils";
@@ -187,13 +193,6 @@ export async function loader({ request }: LoaderFunctionArgs) {
};
}
-function getEntityJobId(entity: TrackedEntity | undefined): string | null {
- const attrs = entity?.attributes;
- if (!attrs || typeof attrs !== "object" || Array.isArray(attrs)) return null;
- const job = (attrs as Record<string, unknown>).Job;
- return typeof job === "string" && job.length > 0 ? job : null;
-}
-
async function getJobReadableId(
client: SupabaseClient<Database>,
jobId: string
@@ -202,54 +201,6 @@ async function getJobReadableId(
return job.data?.jobId ?? jobId;
}
-function withJobNode(
- payload: LineagePayload,
- jobId: string,
- jobReadableId: string
-): LineagePayload {
- const jobNodeId = `job:${jobId}`;
- const existingActivityIds = new Set(payload.activities.map((a) => a.id));
- const existingOutputKeys = new Set(
- payload.outputs.map((o) => `${o.trackedActivityId}:${o.trackedEntityId}`)
- );
- const jobEntities = payload.entities.filter((entity) => {
- if (getEntityJobId(entity) !== jobId) return false;
- return entity.status === "Reserved" || entity.sourceDocument === "Item";
- });
-
- return {
- ...payload,
- activities: existingActivityIds.has(jobNodeId)
- ? payload.activities
- : [
- {
- id: jobNodeId,
- type: "Job",
- sourceDocument: "Job",
- sourceDocumentId: jobId,
- sourceDocumentReadableId: jobReadableId,
- attributes: { Job: jobId }
- },
- ...payload.activities
- ],
- outputs: [
- ...payload.outputs,
- ...jobEntities
- .map((entity) => ({
- trackedActivityId: jobNodeId,
- trackedEntityId: entity.id,
- quantity: entity.quantity
- }))
- .filter(
- (output) =>
- !existingOutputKeys.has(
- `${output.trackedActivityId}:${output.trackedEntityId}`
- )
- )
- ]
- };
-}
-
function mergeLineagePayloads(
base: LineagePayload,
incoming: LineagePayload
@@ -352,30 +303,46 @@ function TraceabilityRouteInner() {
: (entities[0]?.id ?? activities[0]?.id ?? rootId);
const sidebarId = focusedSelectedId ?? fallbackSidebarId;
+ // Clustered serials have no node of their own — the graph writes the cluster
+ // map into the store after each layout so the sidebar (a sibling here, not a
+ // child of the graph) can resolve them.
+ const clusters = useTraceabilityStore((s) => s.clusters);
+ const memberToCluster = useTraceabilityStore((s) => s.memberToCluster);
+ const highlightMemberId = useTraceabilityStore((s) => s.highlightMemberId);
+ const setHighlightMember = useTraceabilityStore((s) => s.setHighlightMember);
+
const { setNodes } = useReactFlow();
const selectNode = useCallback(
(id: string | null) => {
+ const targetId = id === null ? null : (memberToCluster[id] ?? id);
+ setHighlightMember(id !== null && targetId !== id ? id : null);
setNodes((nodes) =>
nodes.map((n) => {
- const wantsSelected = id !== null && n.id === id;
+ const wantsSelected = targetId !== null && n.id === targetId;
if (n.selected === wantsSelected) return n;
return { ...n, selected: wantsSelected };
})
);
},
- [setNodes]
+ [setNodes, memberToCluster, setHighlightMember]
);
// Lot-state nodes carry an `::sN` suffix — the sidebar always shows the
// underlying entity, whichever of its states is selected.
const sidebarEntityId = stateEntityId(sidebarId);
- const selectedEntity =
- (entities.find((e) => e?.id === sidebarEntityId) as
- | TrackedEntity
- | undefined) ?? null;
- const selectedActivity =
- (activities.find((a) => a?.id === sidebarId) as Activity | undefined) ??
- null;
+ const selectedCluster =
+ (isClusterId(sidebarId)
+ ? clusters.find((c) => c.id === sidebarId)
+ : undefined) ?? null;
+ const selectedEntity = selectedCluster
+ ? null
+ : ((entities.find((e) => e?.id === sidebarEntityId) as
+ | TrackedEntity
+ | undefined) ?? null);
+ const selectedActivity = selectedCluster
+ ? null
+ : ((activities.find((a) => a?.id === sidebarId) as Activity | undefined) ??
+ null);
return (
<div className="flex bg-card h-[calc(100dvh-49px)] w-full overflow-hidden scrollbar-hide">
@@ -420,6 +387,9 @@ function TraceabilityRouteInner() {
key={`sidebar-${sidebarId}`}
entity={selectedEntity}
activity={selectedActivity}
+ cluster={selectedCluster}
+ clusters={clusters}
+ highlightMemberId={highlightMemberId}
payload={{
entities: entities as TrackedEntity[],
activities: activities as Activity[],